blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bdbdb90bee6c1f9e6d654b9ab798630c73572a7a | 41e4a0f6af3f4405447089c2a2068d913d22c89a | /src/Platform.h | 9472e063ac7ffd1cafad97f9769288bc596bb8d7 | [
"MIT"
] | permissive | juliendehos/SenjoUCIAdapter | d18c0e2d8ac4770d6d74405c7f7195f42068ce8e | 57fac1cb7d300ff98a5a0678b6696513aa97e72a | refs/heads/master | 2020-07-09T14:13:47.636099 | 2015-06-10T01:22:40 | 2015-06-10T01:22:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,374 | h | //----------------------------------------------------------------------------
// Copyright (c) 2015 Shawn Chidester <zd3nik@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//----------------------------------------------------------------------------
#ifndef SENJO_PLATFORM_H
#define SENJO_PLATFORM_H
#define MAKE_XSTR(x) MAKE_STR(x)
#define MAKE_STR(x) #x
#ifndef GIT_REV
#define GIT_REV norev
#endif
#ifdef WIN32
#include <Windows.h>
#pragma warning(disable:4800)
#pragma warning(disable:4806)
#pragma warning(disable:4996)
#define PRId64 "lld"
#define PRIu64 "llu"
#define snprintf _snprintf
#else // not WIN32
#define __STDC_LIMIT_MACROS
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <unistd.h>
#define stricmp strcasecmp
#endif
#include <algorithm>
#include <assert.h>
#include <cstdint>
#include <errno.h>
#include <iostream>
#include <list>
#include <map>
#include <set>
#include <string>
#include <time.h>
namespace senjo
{
//----------------------------------------------------------------------------
//! \brief Get current millisecond timestamp
//! \return Number of milliseconds since epoch
//----------------------------------------------------------------------------
static inline uint64_t Now()
{
#ifdef WIN32
return static_cast<uint64_t>(GetTickCount());
#else
struct timeval tv;
gettimeofday(&tv, NULL);
return static_cast<uint64_t>((tv.tv_sec * 1000) + (tv.tv_usec / 1000));
#endif
}
static inline bool MillisecondSleep(const unsigned int msecs)
{
#ifdef WIN32
SetLastError(0);
Sleep(msecs);
return GetLastError() ? false : true;
#else
return usleep(1000 * msecs) ? false : true;
#endif
}
//----------------------------------------------------------------------------
//! \brief Convert unsigned 64-bit integer to double
//! Disables compiler warning whe using windows compiler
//! \param[in] value Unsigned 64-bit integer
//! \return \p value converted to double
//----------------------------------------------------------------------------
static inline double ToDouble(const uint64_t value)
{
#ifdef WIN32
#pragma warning(push)
#pragma warning(disable:4244)
#endif
return static_cast<double>(value);
#ifdef WIN32
#pragma warning(pop)
#endif
}
//----------------------------------------------------------------------------
//! \brief Convert millisecond timestamp to seconds as double
//! \param[in] msecs Millisecond timestamp
//! \return \p msecs converted to seconds as double
//----------------------------------------------------------------------------
static inline double ToSeconds(const uint64_t msecs)
{
return (ToDouble(msecs) / 1000.0);
}
//----------------------------------------------------------------------------
//! \brief Calculate average from two doubles
//! \param[in] total The numerator
//! \param[in] count The denominator
//! \return \p total divided by \p count as double
//----------------------------------------------------------------------------
static inline double Average(const double total, const double count)
{
return (count ? (total / count) : 0);
}
//----------------------------------------------------------------------------
//! \brief Calculate average from two unsigned 64-bit integers
//! \param[in] total The numerator
//! \param[in] count The denominator
//! \return \p total divided by \p count as double
//----------------------------------------------------------------------------
static inline double Average(const uint64_t total, const uint64_t count)
{
return (count ? (ToDouble(total) / ToDouble(count)) : 0);
}
//----------------------------------------------------------------------------
//! \brief Calculate average from two native integers
//! \param[in] total The numerator
//! \param[in] count The denominator
//! \return \p total divided by \p count as double
//----------------------------------------------------------------------------
static inline double Average(const int total, const int count)
{
return (count ? (ToDouble(total) / ToDouble(count)) : 0);
}
//----------------------------------------------------------------------------
//! \brief Calculate K-rate from two doubles
//! \param[in] count The number of items
//! \param[in] msecs The number of milliseconds spent
//! \return \p count per seconds as double
//----------------------------------------------------------------------------
static inline double Rate(const double count, const double msecs)
{
return (msecs ? ((count / msecs) * 1000) : 0);
}
//----------------------------------------------------------------------------
//! \brief Calculate K-rate from two unsigned 64-bit integers
//! \param[in] count The number of items
//! \param[in] msecs The number of milliseconds spent
//! \return \p count per seconds as double
//----------------------------------------------------------------------------
static inline double Rate(const uint64_t count, const uint64_t msecs)
{
return Rate(ToDouble(count), ToDouble(msecs));
}
//----------------------------------------------------------------------------
//! \brief Calculate K-rate from two native integers
//! \param[in] count The number of items
//! \param[in] msecs The number of milliseconds spent
//! \return \p count per seconds as double
//----------------------------------------------------------------------------
static inline double Rate(const int count, const int msecs)
{
return Rate(static_cast<double>(count), static_cast<double>(msecs));
}
//----------------------------------------------------------------------------
//! \brief Calculate percentage from two doubles
//! \param[in] top The numerator
//! \param[in] bottom The denominator
//! \return \p top divided by \p bottom multiplied by 100 as double
//----------------------------------------------------------------------------
static inline double Percent(const double top, const double bottom)
{
return (bottom ? (100 * (top / bottom)) : 0);
}
//----------------------------------------------------------------------------
//! \brief Calculate percentage from two unsigned 64-bit integers
//! \param[in] top The numerator
//! \param[in] bottom The denominator
//! \return \p top divided by \p bottom multiplied by 100 as double
//----------------------------------------------------------------------------
static inline double Percent(const uint64_t top, const uint64_t bottom)
{
return (bottom ? (100 * (ToDouble(top) / ToDouble(bottom))) : 0);
}
//----------------------------------------------------------------------------
//! \brief Calculate percentage from two native integers
//! \param[in] top The numerator
//! \param[in] bottom The denominator
//! \return \p top divided by \p bottom multiplied by 100 as double
//----------------------------------------------------------------------------
static inline double Percent(const int top, const int bottom)
{
return (bottom ? (100 * (static_cast<double>(top) / bottom)) : 0);
}
//----------------------------------------------------------------------------
//! \brief Move \p position to beginning of next word
//! \param[in,out] position Pointer to position within a NULL terminated string
//! \return Updated \p position value
//----------------------------------------------------------------------------
static inline const char* NextWord(const char*& position)
{
while (position && *position && isspace(*position)) {
++position;
}
return position;
}
//----------------------------------------------------------------------------
//! \brief Move \p position to beginning of next word
//! \param[in,out] position Pointer to position within a NULL terminated string
//! \return Updated \p position value
//----------------------------------------------------------------------------
static inline char* NextWord(char*& position)
{
while (position && *position && isspace(*position)) {
++position;
}
return position;
}
//----------------------------------------------------------------------------
//! \brief Move \p position to beginning of next whitespace segment
//! \param[in,out] position Pointer to position within a NULL terminated string
//! \return Updated \p position value
//----------------------------------------------------------------------------
static inline const char* NextSpace(const char*& position)
{
while (position && *position && !isspace(*position)) {
++position;
}
return position;
}
//----------------------------------------------------------------------------
//! \brief Move \p position to beginning of next whitespace segment
//! \param[in,out] position Pointer to position within a NULL terminated string
//! \return Updated \p position value
//----------------------------------------------------------------------------
static inline char* NextSpace(char*& position)
{
while (position && *position && !isspace(*position)) {
++position;
}
return position;
}
//----------------------------------------------------------------------------
//! \brief Move \p position to last character of current word
//! \param[in,out] position Pointer to position within a NULL terminated string
//! \return Updated \p position value
//----------------------------------------------------------------------------
static inline char* WordEnd(char*& position)
{
while (position && *position && position[1] && !isspace(position[1])) {
++position;
}
return position;
}
//----------------------------------------------------------------------------
//! \brief Prepare a string for parsing
//! All whitespace in \p str is converted to spaces.
//! The first new-line or carriage-return found is converted to NULL terminator.
//! \param[in,out] str The string, updated to start at first word
//! \return Updated \p str value
//----------------------------------------------------------------------------
static inline char* NormalizeString(char*& str)
{
for (char* n = str; n && *n; ++n) {
if ((*n == '\n') || (*n == '\r')) {
*n = 0;
break;
}
if ((*n != ' ') && isspace(*n)) {
*n = ' ';
}
}
return NextWord(str);
}
//----------------------------------------------------------------------------
//! \brief Does the given parameter name match the current word in a string?
//! \param[in] name The parameter name to check for
//! \param[in,out] params Current word, updated to next word if matches
//! \return true if current word in \p params matches \p name
//----------------------------------------------------------------------------
static inline bool ParamMatch(const std::string& name, const char*& params)
{
if (name.empty() || !params) {
return false;
}
if (strncmp(params, name.c_str(), name.size()) ||
(params[name.size()] && !isspace(params[name.size()])))
{
return false;
}
NextWord(params += name.size());
return true;
}
//----------------------------------------------------------------------------
//! \brief Does the given parameter name exist at the current word in a string?
//! \param[in] name The parameter name to check for
//! \param[out] exists Set to true if current word matches \p name
//! \param[in,out] params The current word in string of parameters
//! \return true if current word in \p params matches \p name
//----------------------------------------------------------------------------
static inline bool HasParam(const std::string& name, bool& exists,
const char*& params)
{
if (!ParamMatch(name, params)) {
return false;
}
exists = true;
return true;
}
//----------------------------------------------------------------------------
//! \brief Does 'name value' pattern exist at current position in a string?
//! \param[in] name The parameter name to check for
//! \param[out] value Set to word after \p name if current word matches \p name
//! \param[in,out] params The current word in string of parameters
//! \param[out] invalid Set to true if \p name is not followed by a value
//! \return true if current word in \p params matches \p name and has value
//----------------------------------------------------------------------------
static inline bool StringParam(const std::string& name, std::string& value,
const char*& params, bool& invalid)
{
if (!ParamMatch(name, params)) {
return false;
}
if (!params || !*params) {
invalid = true;
}
else {
const char* begin = params;
NextSpace(params);
value.assign(begin, (params - begin));
NextWord(params);
}
return true;
}
//----------------------------------------------------------------------------
//! \brief Does 'name number' pattern exist at current position in a string?
//! \param[in] name The parameter name to check for
//! \param[out] value Set to value after \p name if current word matches \p name
//! \param[in,out] params The current word in string of parameters
//! \param[out] invalid Set to true if \p name is not followed by a number
//! \return true if current word in \p params matches \p name and has value
//----------------------------------------------------------------------------
template<typename Number>
static inline bool NumberParam(const std::string& name, Number& value,
const char*& params, bool& invalid)
{
if (!ParamMatch(name, params)) {
return false;
}
if (!params || !*params || !isdigit(*params)) {
invalid = true;
}
else {
value = (*params++ - '0');
while (*params && isdigit(*params)) {
value = ((10 * value) + (*params++ - '0'));
}
if (*params && !isspace(*params)) {
invalid = true;
}
else {
NextWord(params);
}
}
return true;
}
//----------------------------------------------------------------------------
//! \brief Consume the value at current position in a string
//! \param[out] value Populated with the value in \p params
//! \param[in,out] params The current position in a string of parameter values
//! \param[int] next THe next expected parameter name
//! \return true If a non-empty value was assigned to \p value
//----------------------------------------------------------------------------
static inline bool ParamValue(std::string& value, const char*& params,
const std::string& next)
{
if (params && *NextWord(params)) {
const char* end = next.size() ? strstr(params, next.c_str()) : NULL;
while (end && end[next.size()] && !isspace(end[next.size()])) {
NextSpace(end += next.size());
end = strstr(end, next.c_str());
}
if (!end) {
end = (params + strlen(params));
}
while ((end > params) && isspace(end[-1])) {
--end;
}
value.assign(params, (end - params));
if (value.size()) {
NextWord(params += value.size());
return true;
}
}
return false;
}
} // namespace senjo
#endif // SENJO_PLATFORM_H
| [
"zd3nik@gmail.com"
] | zd3nik@gmail.com |
8b263b33aec006f6c8f0cfe20b4a9c1eb971d4e6 | e79b82c678db5f548f8b0228f9ebb9736cb6bfa8 | /AttractorsEngine/Pixel.h | 1f48bd1ef8f1647e251c3fe347a0e564490a3189 | [] | no_license | veldrinlab/veldrinlabProjects | 5988822986271c53323d6d79af7a89c32e7ec6ba | 46992f5c7cc77b4fba3c3078dc444cf9fb49fcc0 | refs/heads/master | 2021-01-10T19:25:43.145557 | 2013-09-18T16:05:06 | 2013-09-18T16:05:06 | null | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 345 | h | /**
* Pixel class represents structure of RGBA color pixel format, used to create procedural graphis.
* @file Pixel.h
* @author Szymon "Veldrin" Jabłoński
* @date 2010-09-27
* @version 1.0
*/
#ifndef PIXEL_H
#define PIXEL_H
class Pixel
{
public:
unsigned char r;
unsigned char g;
unsigned char b;
unsigned char a;
};
#endif | [
"="
] | = |
5965803868be1f0e4a28abf5d7f98cb1fd66de35 | 0c16b56351e499efa62629cbdb97703151acc43a | /Benchtop/src/main/include/Robot.h | ae8dc724711eea5ecd52b289b7188093e6bf37c8 | [] | no_license | slylockfox/Cybertronics | 2d7bcee69d4aa6549be765e17daa7df3cce4e60f | 3a65841056fc2a1edb611c35de7c23dd0ab8c4db | refs/heads/master | 2020-04-17T17:10:28.654711 | 2019-02-17T17:16:29 | 2019-02-17T17:16:29 | 166,772,062 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,563 | h | /*----------------------------------------------------------------------------*/
/* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <string>
#include <frc/TimedRobot.h>
#include <frc/smartdashboard/SendableChooser.h>
#include <frc/Joystick.h>
#include <frc/Spark.h>
#include <frc/Timer.h>
#include <frc/drive/DifferentialDrive.h>
#include <frc/livewindow/LiveWindow.h>
class Robot : public frc::TimedRobot {
public:
void RobotInit() override;
void RobotPeriodic() override;
void AutonomousInit() override;
void AutonomousPeriodic() override;
void TeleopInit() override;
void TeleopPeriodic() override;
void TestPeriodic() override;
Robot() {
m_robotDrive.SetExpiration(0.1);
m_timer.Start();
}
private:
frc::SendableChooser<std::string> m_chooser;
const std::string kAutoNameDefault = "Default";
const std::string kAutoNameCustom = "My Auto";
std::string m_autoSelected;
// Robot drive system
frc::Spark m_left{1};
frc::Spark m_right{0};
frc::DifferentialDrive m_robotDrive{m_left, m_right};
frc::Joystick m_stick{0};
frc::LiveWindow& m_lw = *frc::LiveWindow::GetInstance();
frc::Timer m_timer;
};
| [
"slylock2@mac.com"
] | slylock2@mac.com |
4aed27527fbb4fc65e22541764df7312adad050e | 127b4bb0893d5ca8fb066e9e2d770538240432ea | /yellowfellow-ac/UVA/10048/12396745_AC_20ms_0kB.cpp | 3388883e61b4ceb9a44888a15e1614352234b129 | [] | no_license | kuningfellow/Kuburan-CP | 5481f3f7fce9471acd108dc601adc183c9105672 | 2dc8bbc8c18a8746d32a4a20910b717c066d0d41 | refs/heads/master | 2020-04-24T15:13:40.853652 | 2019-12-24T07:21:38 | 2019-12-24T07:21:38 | 172,057,574 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,437 | cpp | //UVA 10048 Audiophobia
//floyd warshall
#include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;
int con[105][105];
int n;
int main()
{
int kas=1;
while (1<2)
{
int e,q;
cin>>n>>e>>q;
if (n==0&&e==0&&q==0)break;
for (int i=0;i<n;i++)
{
for (int j=0;j<n;j++)
{
con[i][j]=-1;
}
}
int a,b,c;
for (int i=0;i<e;i++)
{
cin>>a>>b>>c;
con[a-1][b-1]=c;
con[b-1][a-1]=c;
}
for (int k=0;k<n;k++)
{
for (int i=0;i<n;i++)
{
for (int j=0;j<n;j++)
{
if (con[i][k]!=-1&&con[k][j]!=-1)
{
c=max(con[i][k],con[k][j]);
}
else continue;
if (con[i][j]==-1)
{
con[i][j]=c;
}
else
{
con[i][j]=min(con[i][j],c);
}
}
}
}
if (kas>1)printf ("\n");
printf ("Case #%d\n",kas++);
for (int i=0;i<q;i++)
{
cin>>a>>b;
c=con[a-1][b-1];
if (c==-1)printf ("no path\n");
else printf ("%d\n",c);
}
}
}
| [
"williamgunawaneka@gmail.com"
] | williamgunawaneka@gmail.com |
f8cdb92dfc25124595bf6ff34c51d8b07b95cf83 | 1e85083611abb457a5bbfb04676c16e3f31b6527 | /StringCalculator.h | a9374328637df3f2721d88922d9a7231c35851cc | [] | no_license | ThomasAy/StringCalculator | 29cb08e78818755858f3f84af08c69643e29b3bc | 107cf8c023f77a6b385a595c4ceb8e8a11452804 | refs/heads/master | 2020-05-17T17:52:33.627077 | 2014-05-28T16:31:37 | 2014-05-28T16:31:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 369 | h | /**
* Copyright (C) 2012-2014 Phonations
* License: http://www.gnu.org/licenses/gpl.html GPL version 2 or higher
*/
#ifndef STRINGCALCULATOR_H
#define STRINGCALCULATOR_H
#include "stdio.h"
#include "iostream"
#include <string>
using namespace std;
class StringCalculator
{
public:
StringCalculator();
int add(string s1 = "");
};
#endif // STRINGCALCULATOR_H
| [
"thomas@phonations.com"
] | thomas@phonations.com |
6d7de6cb5b8e9f8f088088326900a8fa7a8d189a | 8a5f0eda7e09ef69b8a2a49b760397bc6200d134 | /Templates/Tree/LCA.cpp | 1475f2bcaedafe4b0b3b3d9c110887cc7d836e34 | [] | no_license | 2997ms/Competitive-programming-problems | 5ea54f2c63d963655cd046f33c8a85e03e314d51 | 23028f10875631897588613180fc5a8f2613e724 | refs/heads/master | 2022-12-15T08:54:56.269845 | 2022-12-08T21:45:09 | 2022-12-08T22:20:42 | 58,099,655 | 2 | 0 | null | 2019-09-01T01:40:51 | 2016-05-05T02:53:10 | C++ | UTF-8 | C++ | false | false | 1,236 | cpp | struct LcaStruct {
int root;
int n;
int fa[maxn][30];
int depth[maxn];
vector<int>vec[maxn];
void dfs(int u,int pre,int d) //预处理出每个节点的深度及父亲节点
{
fa[u][0]=pre;
depth[u]=d;
for(int i=0;i<vec[u].size();i++)
{
int v=vec[u][i];
if(v!=pre)
{
dfs(v, u, d + 1);
}
}
}
void init() //预处理出每个节点往上走2^k所到的节点,超过根节点记为-1
{
dfs(root,-1,0); //root为根节点
for(int j=0;(1<<(j+1))<=n;j++)
{
for(int i=0;i<=n;i++)
{
if(fa[i][j]<0)
fa[i][j+1]=-1;
else
fa[i][j+1]=fa[fa[i][j]][j];
}
}
}
int LCA(int u,int v)
{
if(depth[u]>depth[v]) swap(u,v);
int temp=depth[v]-depth[u];
for(int i=0;(1<<i)<=temp;i++) //使u,v在同一深度
{
if((1<<i)&temp)
v=fa[v][i];
}
if(v==u) return u;
for(int i=20;i>=0;i--) //两个节点一起往上走
{
if(fa[u][i]!=fa[v][i])
{
u=fa[u][i];
v=fa[v][i];
}
}
return fa[u][0];
}
}lca; | [
"wangchong756@gamil.com"
] | wangchong756@gamil.com |
54645c5c79509b86a8af5a013a641a5ee8b1bf44 | 094cd67dd4904fbb7d7befd32f1684275e994d5b | /src/chainparamsbase.cpp | 6c29d6652f30091ad85bc6ae53af082ce86f8237 | [
"MIT"
] | permissive | Arinerron/jobecoin | a9219ee50b927fefe657e1844987c69e422fb81f | d6c966cf94c44061c157da77def3e15ecb866a2b | refs/heads/master | 2021-08-20T02:55:06.170471 | 2017-11-28T02:05:06 | 2017-11-28T02:05:06 | 112,209,637 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,756 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Jobecoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <chainparamsbase.h>
#include <tinyformat.h>
#include <util.h>
#include <assert.h>
const std::string CBaseChainParams::MAIN = "main";
const std::string CBaseChainParams::TESTNET = "test";
const std::string CBaseChainParams::REGTEST = "regtest";
void AppendParamsHelpMessages(std::string& strUsage, bool debugHelp)
{
strUsage += HelpMessageGroup(_("Chain selection options:"));
strUsage += HelpMessageOpt("-testnet", _("Use the test chain"));
if (debugHelp) {
strUsage += HelpMessageOpt("-regtest", "Enter regression test mode, which uses a special chain in which blocks can be solved instantly. "
"This is intended for regression testing tools and app development.");
}
}
/**
* Main network
*/
class CBaseMainParams : public CBaseChainParams
{
public:
CBaseMainParams()
{
nRPCPort = 8332;
}
};
/**
* Testnet (v3)
*/
class CBaseTestNetParams : public CBaseChainParams
{
public:
CBaseTestNetParams()
{
nRPCPort = 18332;
strDataDir = "testnet3";
}
};
/*
* Regression test
*/
class CBaseRegTestParams : public CBaseChainParams
{
public:
CBaseRegTestParams()
{
nRPCPort = 18443;
strDataDir = "regtest";
}
};
static std::unique_ptr<CBaseChainParams> globalChainBaseParams;
const CBaseChainParams& BaseParams()
{
assert(globalChainBaseParams);
return *globalChainBaseParams;
}
std::unique_ptr<CBaseChainParams> CreateBaseChainParams(const std::string& chain)
{
if (chain == CBaseChainParams::MAIN)
return std::unique_ptr<CBaseChainParams>(new CBaseMainParams());
else if (chain == CBaseChainParams::TESTNET)
return std::unique_ptr<CBaseChainParams>(new CBaseTestNetParams());
else if (chain == CBaseChainParams::REGTEST)
return std::unique_ptr<CBaseChainParams>(new CBaseRegTestParams());
else
throw std::runtime_error(strprintf("%s: Unknown chain %s.", __func__, chain));
}
void SelectBaseParams(const std::string& chain)
{
globalChainBaseParams = CreateBaseChainParams(chain);
}
std::string ChainNameFromCommandLine()
{
bool fRegTest = gArgs.GetBoolArg("-regtest", false);
bool fTestNet = gArgs.GetBoolArg("-testnet", false);
if (fTestNet && fRegTest)
throw std::runtime_error("Invalid combination of -regtest and -testnet.");
if (fRegTest)
return CBaseChainParams::REGTEST;
if (fTestNet)
return CBaseChainParams::TESTNET;
return CBaseChainParams::MAIN;
}
| [
"arinesau@gmail.com"
] | arinesau@gmail.com |
86dc648b9dbd2312db40e0e93fbbc40fd1095515 | 46bdced06890f17f795c165b207f2b8f8b9fef5d | /src/renderer/include/KeyFrame.h | 895d8eb91228acc3aed4a795181d805c8c4e3bd7 | [] | no_license | zgpxgame/iEngine | 5a74faf5704f199166af538ffc8f1da6b353f0a0 | 25be7ca619dc750cc418e3faa7de88883d5cda6f | refs/heads/master | 2020-06-01T15:39:17.985636 | 2015-09-18T13:20:26 | 2015-09-18T13:20:26 | 4,594,111 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,149 | h | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://ogre.sourceforge.net/
Copyright (c)2000-2002 The OGRE Team
Also see acknowledgements in Readme.html
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.
-----------------------------------------------------------------------------
*/
#ifndef __KeyFrame_H__
#define __KeyFrame_H__
#include "Prerequisites.h"
#include "Vector3.h"
#include "Quaternion.h"
namespace renderer {
/** A key frame in an animation sequence defined by an AnimationTrack.
@remarks
This class can be used as a basis for all kinds of key frames.
The unifying principle is that multiple KeyFrames define an
animation sequence, with the exact state of the animation being an
interpolation between these key frames.
*/
class _RendererExport KeyFrame {
public:
/// Simple constructor, only used for creating temp objects
KeyFrame();
/** Default constructor, you should not call this but use AnimationTrack::createKeyFrame instead. */
KeyFrame(Real time);
/** Gets the time of this keyframe in the animation sequence. */
Real getTime(void) const;
/** Sets the translation associated with this keyframe.
@remarks
The translation factor affects how much the keyframe translates (moves) it's animable
object at it's time index.
@param trans The vector to translate by
*/
void setTranslate(const Vector3& trans);
/** Gets the translation applied by this keyframe. */
Vector3 getTranslate(void) const;
/** Sets the scaling factor applied by this keyframe to the animable
object at it's time index.
@param scale The vector to scale by (beware of supplying zero values for any component of this
vector, it will scale the object to zero dimensions)
*/
void setScale(const Vector3& scale);
/** Gets the scaling factor applied by this keyframe. */
Vector3 getScale(void) const;
/** Sets the rotation applied by this keyframe.
@param rot The rotation applied; use Quaternion methods to convert from angle/axis or Matrix3 if
you don't like using Quaternions directly.
*/
void setRotation(const Quaternion& rot);
/** Gets the rotation applied by this keyframe. */
Quaternion getRotation(void) const;
protected:
Real mTime;
Vector3 mTranslate;
Vector3 mScale;
Quaternion mRotate;
};
}
#endif
| [
"zgpxgame@126.com"
] | zgpxgame@126.com |
76bfc404d0eefaf307ee7d52d2bee8a698597a30 | 0f6f8641f461859895bf7404c8e5b17cdcbd3147 | /DiffusionCAProcessor/main.cpp | a1994ce123724c43119823648f5f79a2cf085fc1 | [] | no_license | illbegood/diffusionCA | 87aa701b7b9d68ef347058b7f576ed530514df40 | 8f61cccf531b8319da3045e358282523abc32053 | refs/heads/master | 2020-08-10T01:52:33.287492 | 2020-04-15T11:47:54 | 2020-04-15T11:47:54 | 214,227,136 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,583 | cpp | //#include <mpi.h>
//#include <iostream>
//#include <string>
//#include <vector>
//#include "..\\io.h"
//#include "..\\controller.h"
//#include "..\\model.h"
//
//using namespace std;
//
//
//int mpi_rank, mpi_size;
//unsigned dim, n, argIndex = 1, lastSize, crossSectionSize, reqCount = 0, mod, quot, thisLastSize, centerIdx;
//size_t Left, temp;
//vector<unsigned> leftSend, leftRecv, rightSend, rightRecv;
//vector<size_t> center;
//char ** ARGV;
//Controller c;
//CA *ca;
//vector<string> args;
//MPI_Request req[4];
//
//
//void print(const vector<unsigned>& v) {
// for (auto i = v.begin(); i != v.end(); ++i)
// cout << *i << " ";
// cout << endl;
//}
//
//void print(const vector<size_t>& v) {
// for (auto i = v.begin(); i != v.end(); ++i)
// cout << *i << " ";
// cout << endl;
//}
//
//void check_center() {
// if (mpi_rank == centerIdx)
// cout << ca->testO(center) << ca->testN(center) << " ";
//}
//
//void createCA() {
// unsigned ret;
// args.push_back("blank");
// //dim
// args.push_back(ARGV[argIndex]);
// dim = stoi(ARGV[argIndex++]);
// //size
// for (unsigned i = 0; i < dim - 1; ++i)
// args.push_back(ARGV[argIndex++]);
// lastSize = stoi(ARGV[argIndex++]);
// mod = lastSize % mpi_size;
// quot = lastSize / mpi_size;
// thisLastSize = quot + (mpi_rank < mod ? 1 : 0);
// Left = 0;
// for (ret = 0; ret < lastSize && Left <= lastSize / 2; ++ret) {
// temp = quot + (ret < mod ? 1 : 0);
// Left += temp;
// }
// thisLastSize += 2;
// args.push_back(to_string(thisLastSize));
// //p
// args.push_back(ARGV[argIndex++]);
// CA::cmd_blank(args, c);
// ca = c.getCA();
// //if (mpi_rank == 0)
// //cout << ret - 1 << " " << Left << " " << temp << endl;
// centerIdx = --ret;
// if (mpi_rank == ret) {
// vector<size_t> sizes = ca->getSize();
// center.resize(dim);
// for (unsigned i = 0; i < dim - 1; ++i)
// center[i] = sizes[i] / 2;
// center[dim - 1] = lastSize / 2 - (Left - temp) + 1;
// ca->set(center, CA::initialCount);
// print(center);
// }
// check_center();
//}
//
//void configureCA() {
// n = stoi(ARGV[argIndex++]);
// char *mask = ARGV[argIndex++];
// args.clear();
// args.push_back("mode");
// args.push_back(mask[0] == '0' ? "0" : "1");
// CA::cmd_mode(args, c);
// args.clear();
// args.push_back("border");
// args.push_back(mask[1] == '0' ? "0" : "1");
// CA::cmd_border(args, c);
// crossSectionSize = ca->getTotalSize() / thisLastSize;
//}
//
//void init_pcr() {
// if (mpi_rank != 0) {
// leftSend.resize(crossSectionSize);
// MPI_Send_init(&leftSend[0], crossSectionSize, MPI_UNSIGNED, (mpi_rank + mpi_size - 1) % mpi_size, 123, MPI_COMM_WORLD, &req[reqCount++]);
// leftRecv.resize(crossSectionSize);
// MPI_Recv_init(&leftRecv[0], crossSectionSize, MPI_UNSIGNED, (mpi_rank + mpi_size - 1) % mpi_size, 123, MPI_COMM_WORLD, &req[reqCount++]);
// }
// if (mpi_rank != mpi_size - 1) {
// rightSend.resize(crossSectionSize);
// MPI_Send_init(&rightSend[0], crossSectionSize, MPI_UNSIGNED, (mpi_rank + 1) % mpi_size, 123, MPI_COMM_WORLD, &req[reqCount++]);
// rightRecv.resize(crossSectionSize);
// MPI_Recv_init(&rightRecv[0], crossSectionSize, MPI_UNSIGNED, (mpi_rank + 1) % mpi_size, 123, MPI_COMM_WORLD, &req[reqCount++]);
// }
//}
//
//void step() {
// check_center();
// ca->stepBounds();
// if (mpi_rank != 0) {
// leftSend = ca->getLeftBorder();
// //cout << "leftSend ";
// //print(leftSend);
// }
// if (mpi_rank != mpi_size - 1) {
// rightSend = ca->getRightBorder();
// //cout << "rightSend ";
// //print(rightSend);
// }
// check_center();
// MPI_Startall(reqCount, req);
// check_center();
// ca->stepNoBounds();
// check_center();
// MPI_Waitall(reqCount, req, MPI_STATUSES_IGNORE);
// if (mpi_rank != 0) {
// ca->addToLeftBorder(leftRecv);
// //cout << "leftRecv ";
// //print(leftRecv);
// }
// if (mpi_rank != mpi_size - 1) {
// ca->addToRightBorder(rightRecv);
// //cout << "rightRecv ";
// //print(rightRecv);
// }
// check_center();
// ca->finishStep();
// check_center();
//}
//
//void save() {
// args.clear();
// args.push_back("save");
// args.push_back(to_string(mpi_rank));
// IO::cmd_save(args, c);
//}
//
//int main(int argc, char **argv) {
// MPI_Init(&argc, &argv);
// MPI_Comm_size(MPI_COMM_WORLD, &mpi_size);
// MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank);
// ARGV = argv;
// createCA();
// configureCA();
// init_pcr();
// for (unsigned I = 0; I < n; ++I)
// step();
// vector<unsigned> values = ca->getParticles();
// vector<unsigned> whole;
// int* recvcounts, *displs;
// if (mpi_rank == 0) {
// whole.resize(crossSectionSize * lastSize);
// recvcounts = new int[mpi_size];
// displs = new int[mpi_size];
// size_t offset = 0;
// for (int i = 0; i < mpi_size; ++i) {
// recvcounts[i] = (quot + (i < mod ? 1 : 0)) * crossSectionSize;
// displs[i] = offset;
// offset += recvcounts[i];
// }
// }
// save();
// //MPI_Barrier(MPI_COMM_WORLD);
// MPI_Gatherv(&values[crossSectionSize], values.size() - 2 * crossSectionSize, MPI_UNSIGNED, &whole[0], recvcounts, displs, MPI_UNSIGNED, 0, MPI_COMM_WORLD);
// if (mpi_rank == 0) {
// delete[] recvcounts;
// delete[] displs;
// vector<size_t> dimSize = ca->getSize();
// dimSize[dim - 1] = lastSize;
// c.setCA(new CA(dimSize, ca->getPMove(), whole));
// args.clear();
// args.push_back("save");
// args.push_back(argv[argIndex++]);
// cout << endl;
// IO::cmd_save(args, c);
// }
// MPI_Finalize();
//}
int main(){} | [
"noreply@github.com"
] | noreply@github.com |
f4fdca7d9c001ca8bea1e44bf724a04e4cff4137 | efc129216f321f85720f6fdfd5663a5c344a67ab | /mpgame/anim/Anim_Testmodel.cpp | 8dc4deb15469da9e499aa51f2dbbce639a71398f | [] | no_license | Stradex/q4-librecoop | 70d27054d303d847a5016b14e3286d1c267618ea | cd0c47e5f1b499bf146b65ae7d3d1e84eb95eb1f | refs/heads/main | 2023-03-14T01:17:59.154888 | 2021-02-25T06:36:48 | 2021-02-25T06:36:48 | 341,447,640 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,252 | cpp | /*
=============================================================================
MODEL TESTING
Model viewing can begin with either "testmodel <modelname>"
The names must be the full pathname after the basedir, like
"models/weapons/v_launch/tris.md3" or "players/male/tris.md3"
Extension will default to ".ase" if not specified.
Testmodel will create a fake entity 100 units in front of the current view
position, directly facing the viewer. It will remain immobile, so you can
move around it to view it from different angles.
g_testModelRotate
g_testModelAnimate
g_testModelBlend
=============================================================================
*/
#include "../../idlib/precompiled.h"
#pragma hdrstop
#include "../Game_local.h"
CLASS_DECLARATION( idAnimatedEntity, idTestModel )
EVENT( EV_FootstepLeft, idTestModel::Event_Footstep )
EVENT( EV_FootstepRight, idTestModel::Event_Footstep )
END_CLASS
/*
================
idTestModel::idTestModel
================
*/
idTestModel::idTestModel() {
head = NULL;
headAnimator = NULL;
anim = 0;
headAnim = 0;
starttime = 0;
animtime = 0;
mode = 0;
frame = 0;
}
/*
================
idTestModel::Save
================
*/
void idTestModel::Save( idSaveGame *savefile ) {
}
/*
================
idTestModel::Restore
================
*/
void idTestModel::Restore( idRestoreGame *savefile ) {
// FIXME: one day we may actually want to save/restore test models, but for now we'll just delete them
delete this;
}
/*
================
idTestModel::Spawn
================
*/
void idTestModel::Spawn( void ) {
idVec3 size;
idBounds bounds;
const char *headModel;
jointHandle_t joint;
idStr jointName;
idVec3 origin, modelOffset;
idMat3 axis;
const idKeyValue *kv;
copyJoints_t copyJoint;
// RAVEN BEGIN
// ddynerman: new heads
idAFAttachment *headEnt;
// RAVEN END
if ( renderEntity.hModel && renderEntity.hModel->IsDefaultModel() && !animator.ModelDef() ) {
gameLocal.Warning( "Unable to create testmodel for '%s' : model defaulted", spawnArgs.GetString( "model" ) );
PostEventMS( &EV_Remove, 0 );
return;
}
mode = g_testModelAnimate.GetInteger();
animator.RemoveOriginOffset( g_testModelAnimate.GetInteger() == 1 );
physicsObj.SetSelf( this );
physicsObj.SetOrigin( GetPhysics()->GetOrigin() );
physicsObj.SetAxis( GetPhysics()->GetAxis() );
if ( spawnArgs.GetVector( "mins", NULL, bounds[0] ) ) {
spawnArgs.GetVector( "maxs", NULL, bounds[1] );
physicsObj.SetClipBox( bounds, 1.0f );
physicsObj.SetContents( 0 );
} else if ( spawnArgs.GetVector( "size", NULL, size ) ) {
bounds[ 0 ].Set( size.x * -0.5f, size.y * -0.5f, 0.0f );
bounds[ 1 ].Set( size.x * 0.5f, size.y * 0.5f, size.z );
physicsObj.SetClipBox( bounds, 1.0f );
physicsObj.SetContents( 0 );
}
spawnArgs.GetVector( "offsetModel", "0 0 0", modelOffset );
// add the head model if it has one
headModel = spawnArgs.GetString( "def_head", "" );
if ( headModel[ 0 ] ) {
// RAVEN BEGIN
// ddynerman: new heads
jointName = spawnArgs.GetString( "joint_head" );
joint = animator.GetJointHandle( jointName );
if ( joint == INVALID_JOINT ) {
gameLocal.Warning( "Joint '%s' not found for 'joint_head'", jointName.c_str() );
} else {
// copy any sounds in case we have frame commands on the head
idDict args;
const idKeyValue *sndKV = spawnArgs.MatchPrefix( "snd_", NULL );
while( sndKV ) {
args.Set( sndKV->GetKey(), sndKV->GetValue() );
sndKV = spawnArgs.MatchPrefix( "snd_", sndKV );
}
args.Set( "classname", headModel );
if( !gameLocal.SpawnEntityDef( args, ( idEntity ** )&headEnt ) ) {
gameLocal.Warning( "idTestModel::Spawn() - Unknown head model '%s'\n", headModel );
return;
}
headEnt->spawnArgs.Set( "classname", headModel );
headEnt->SetName( va( "%s_head", name.c_str() ) );
headEnt->SetBody ( this, headEnt->spawnArgs.GetString ( "model" ), joint );
headEnt->BindToJoint( this, joint, true );
headEnt->SetOrigin( vec3_origin );
headEnt->SetAxis( mat3_identity );
headEnt->InitCopyJoints ( );
head = headEnt;
// RAVEN END
headAnimator = head.GetEntity()->GetAnimator();
// set up the list of joints to copy to the head
for( kv = spawnArgs.MatchPrefix( "copy_joint", NULL ); kv != NULL; kv = spawnArgs.MatchPrefix( "copy_joint", kv ) ) {
jointName = kv->GetKey();
if ( jointName.StripLeadingOnce( "copy_joint_world " ) ) {
copyJoint.mod = JOINTMOD_WORLD_OVERRIDE;
} else {
jointName.StripLeadingOnce( "copy_joint " );
copyJoint.mod = JOINTMOD_LOCAL_OVERRIDE;
}
copyJoint.from = animator.GetJointHandle( jointName );
if ( copyJoint.from == INVALID_JOINT ) {
gameLocal.Warning( "Unknown copy_joint '%s'", jointName.c_str() );
continue;
}
copyJoint.to = headAnimator->GetJointHandle( jointName );
if ( copyJoint.to == INVALID_JOINT ) {
gameLocal.Warning( "Unknown copy_joint '%s' on head", jointName.c_str() );
continue;
}
copyJoints.Append( copyJoint );
}
}
}
// start any shader effects based off of the spawn time
renderEntity.shaderParms[ SHADERPARM_TIMEOFFSET ] = -MS2SEC( gameLocal.time );
SetPhysics( &physicsObj );
// always keep updating so we can see the skeleton for the default pose
fl.forcePhysicsUpdate = true;
gameLocal.Printf( "Added testmodel at origin = '%s', angles = '%s'\n", GetPhysics()->GetOrigin().ToString(), GetPhysics()->GetAxis().ToAngles().ToString() );
BecomeActive( TH_THINK );
}
/*
================
idTestModel::~idTestModel
================
*/
idTestModel::~idTestModel() {
StopSound( SND_CHANNEL_ANY, false );
if ( renderEntity.hModel ) {
gameLocal.Printf( "Removing testmodel %s\n", renderEntity.hModel->Name() );
} else {
gameLocal.Printf( "Removing testmodel\n" );
}
if ( gameLocal.testmodel == this ) {
gameLocal.testmodel = NULL;
}
if ( head.GetEntity() ) {
// RAVEN BEGIN
// ddynerman: allow instant respawning of head
head.GetEntity()->SetName( va( "%s_oldhead", head.GetEntity()->name.c_str() ) );
// RAVEN END
head.GetEntity()->StopSound( SND_CHANNEL_ANY, false );
head.GetEntity()->PostEventMS( &EV_Remove, 0 );
}
SetPhysics( NULL );
}
/*
===============
idTestModel::Event_Footstep
===============
*/
void idTestModel::Event_Footstep( void ) {
StartSound( "snd_footstep", SND_CHANNEL_BODY, 0, false, NULL );
}
/*
================
idTestModel::ShouldConstructScriptObjectAtSpawn
Called during idEntity::Spawn to see if it should construct the script object or not.
Overridden by subclasses that need to spawn the script object themselves.
================
*/
bool idTestModel::ShouldConstructScriptObjectAtSpawn( void ) const {
return false;
}
/*
================
idTestModel::Think
================
*/
void idTestModel::Think( void ) {
idVec3 pos;
idMat3 axis;
idAngles ang;
int i;
frameBlend_t frameBlend = { 0 };
if ( thinkFlags & TH_THINK ) {
if ( anim && ( gameLocal.testmodel == this ) && ( mode != g_testModelAnimate.GetInteger() ) ) {
StopSound( SND_CHANNEL_ANY, false );
if ( head.GetEntity() ) {
head.GetEntity()->StopSound( SND_CHANNEL_ANY, false );
}
switch( g_testModelAnimate.GetInteger() ) {
default:
case 0:
// cycle anim with origin reset
if ( animator.NumFrames( anim ) <= 1 ) {
// single frame animations end immediately, so just cycle it since it's the same result
animator.CycleAnim( ANIMCHANNEL_ALL, anim, gameLocal.time, FRAME2MS( g_testModelBlend.GetInteger() ) );
if ( headAnim ) {
headAnimator->CycleAnim( ANIMCHANNEL_ALL, headAnim, gameLocal.time, FRAME2MS( g_testModelBlend.GetInteger() ) );
}
} else {
animator.PlayAnim( ANIMCHANNEL_ALL, anim, gameLocal.time, FRAME2MS( g_testModelBlend.GetInteger() ) );
if ( headAnim ) {
headAnimator->PlayAnim( ANIMCHANNEL_ALL, headAnim, gameLocal.time, FRAME2MS( g_testModelBlend.GetInteger() ) );
if ( headAnimator->AnimLength( headAnim ) > animator.AnimLength( anim ) ) {
// loop the body anim when the head anim is longer
animator.CurrentAnim( ANIMCHANNEL_ALL )->SetCycleCount( -1 );
}
}
}
animator.RemoveOriginOffset( false );
break;
case 1:
// cycle anim with fixed origin
animator.CycleAnim( ANIMCHANNEL_ALL, anim, gameLocal.time, FRAME2MS( g_testModelBlend.GetInteger() ) );
animator.RemoveOriginOffset( true );
if ( headAnim ) {
headAnimator->CycleAnim( ANIMCHANNEL_ALL, headAnim, gameLocal.time, FRAME2MS( g_testModelBlend.GetInteger() ) );
}
break;
case 2:
// cycle anim with continuous origin
animator.CycleAnim( ANIMCHANNEL_ALL, anim, gameLocal.time, FRAME2MS( g_testModelBlend.GetInteger() ) );
animator.RemoveOriginOffset( false );
if ( headAnim ) {
headAnimator->CycleAnim( ANIMCHANNEL_ALL, headAnim, gameLocal.time, FRAME2MS( g_testModelBlend.GetInteger() ) );
}
break;
case 3:
// RAVEN BEGIN
// frame by frame with continuous origin
frameBlend.frame1 = frame;
frameBlend.frame2 = frame;
frameBlend.frontlerp = 1.0f;
animator.SetFrame( ANIMCHANNEL_ALL, anim, frameBlend );
animator.RemoveOriginOffset( false );
if ( headAnim ) {
headAnimator->SetFrame( ANIMCHANNEL_ALL, headAnim, frameBlend );
}
// RAVEN END
break;
case 4:
// play anim once
animator.PlayAnim( ANIMCHANNEL_ALL, anim, gameLocal.time, FRAME2MS( g_testModelBlend.GetInteger() ) );
animator.RemoveOriginOffset( false );
if ( headAnim ) {
headAnimator->PlayAnim( ANIMCHANNEL_ALL, headAnim, gameLocal.time, FRAME2MS( g_testModelBlend.GetInteger() ) );
}
break;
case 5:
// RAVEN BEGIN
// frame by frame with fixed origin
frameBlend.frame1 = frame;
frameBlend.frame2 = frame;
frameBlend.frontlerp = 1.0f;
animator.SetFrame( ANIMCHANNEL_ALL, anim, frameBlend );
animator.RemoveOriginOffset( true );
if ( headAnim ) {
headAnimator->SetFrame( ANIMCHANNEL_ALL, headAnim, frameBlend );
}
// RAVEN END
break;
}
mode = g_testModelAnimate.GetInteger();
}
if ( ( mode == 0 ) && ( gameLocal.time >= starttime + animtime ) ) {
starttime = gameLocal.time;
StopSound( SND_CHANNEL_ANY, false );
animator.PlayAnim( ANIMCHANNEL_ALL, anim, gameLocal.time, FRAME2MS( g_testModelBlend.GetInteger() ) );
if ( headAnim ) {
headAnimator->PlayAnim( ANIMCHANNEL_ALL, headAnim, gameLocal.time, FRAME2MS( g_testModelBlend.GetInteger() ) );
if ( headAnimator->AnimLength( headAnim ) > animator.AnimLength( anim ) ) {
// loop the body anim when the head anim is longer
animator.CurrentAnim( ANIMCHANNEL_ALL )->SetCycleCount( -1 );
}
}
}
if ( headAnimator ) {
// copy the animation from the body to the head
for( i = 0; i < copyJoints.Num(); i++ ) {
if ( copyJoints[ i ].mod == JOINTMOD_WORLD_OVERRIDE ) {
idMat3 mat = head.GetEntity()->GetPhysics()->GetAxis().Transpose();
GetJointWorldTransform( copyJoints[ i ].from, gameLocal.time, pos, axis );
pos -= head.GetEntity()->GetPhysics()->GetOrigin();
headAnimator->SetJointPos( copyJoints[ i ].to, copyJoints[ i ].mod, pos * mat );
headAnimator->SetJointAxis( copyJoints[ i ].to, copyJoints[ i ].mod, axis * mat );
} else {
animator.GetJointLocalTransform( copyJoints[ i ].from, gameLocal.time, pos, axis );
headAnimator->SetJointPos( copyJoints[ i ].to, copyJoints[ i ].mod, pos );
headAnimator->SetJointAxis( copyJoints[ i ].to, copyJoints[ i ].mod, axis );
}
}
}
// update rotation
RunPhysics();
physicsObj.GetAngles( ang );
physicsObj.SetAngularExtrapolation( extrapolation_t(EXTRAPOLATION_LINEAR|EXTRAPOLATION_NOSTOP), gameLocal.time, 0, ang, idAngles( 0, g_testModelRotate.GetFloat() * 360.0f / 60.0f, 0 ), ang_zero );
idClipModel *clip = physicsObj.GetClipModel();
if ( clip && animator.ModelDef() ) {
idVec3 neworigin;
idMat3 axis;
jointHandle_t joint;
joint = animator.GetJointHandle( "origin" );
animator.GetJointTransform( joint, gameLocal.time, neworigin, axis );
neworigin = ( ( neworigin - animator.ModelDef()->GetVisualOffset() ) * physicsObj.GetAxis() ) + GetPhysics()->GetOrigin();
// RAVEN BEGIN
// ddynerman: multiple clip worlds
clip->Link( this, 0, neworigin, clip->GetAxis() );
// RAVEN END
}
}
UpdateAnimation();
Present();
if ( ( gameLocal.testmodel == this ) && g_showTestModelFrame.GetInteger() && anim ) {
gameLocal.Printf( "^5 Anim: ^7%s ^5Frame: ^7%d/%d Time: %.3f\n", animator.AnimFullName( anim ), animator.CurrentAnim( ANIMCHANNEL_ALL )->GetFrameNumber( gameLocal.time ),
animator.CurrentAnim( ANIMCHANNEL_ALL )->NumFrames(), MS2SEC( gameLocal.time - animator.CurrentAnim( ANIMCHANNEL_ALL )->GetStartTime() ) );
if ( headAnim ) {
gameLocal.Printf( "^5 Head: ^7%s ^5Frame: ^7%d/%d Time: %.3f\n\n", headAnimator->AnimFullName( headAnim ), headAnimator->CurrentAnim( ANIMCHANNEL_ALL )->GetFrameNumber( gameLocal.time ),
headAnimator->CurrentAnim( ANIMCHANNEL_ALL )->NumFrames(), MS2SEC( gameLocal.time - headAnimator->CurrentAnim( ANIMCHANNEL_ALL )->GetStartTime() ) );
} else {
gameLocal.Printf( "\n\n" );
}
}
}
/*
================
idTestModel::NextAnim
================
*/
void idTestModel::NextAnim( const idCmdArgs &args ) {
if ( !animator.NumAnims() ) {
return;
}
anim++;
if ( anim >= animator.NumAnims() ) {
// anim 0 is no anim
anim = 1;
}
starttime = gameLocal.time;
animtime = animator.AnimLength( anim );
animname = animator.AnimFullName( anim );
headAnim = 0;
if ( headAnimator ) {
headAnimator->ClearAllAnims( gameLocal.time, 0 );
headAnim = headAnimator->GetAnim( animname );
if ( !headAnim ) {
headAnim = headAnimator->GetAnim( "idle" );
}
if ( headAnim && ( headAnimator->AnimLength( headAnim ) > animtime ) ) {
animtime = headAnimator->AnimLength( headAnim );
}
}
gameLocal.Printf( "anim '%s', %d.%03d seconds, %d frames\n", animname.c_str(), animator.AnimLength( anim ) / 1000, animator.AnimLength( anim ) % 1000, animator.NumFrames( anim ) );
if ( headAnim ) {
gameLocal.Printf( "head '%s', %d.%03d seconds, %d frames\n", headAnimator->AnimFullName( headAnim ), headAnimator->AnimLength( headAnim ) / 1000, headAnimator->AnimLength( headAnim ) % 1000, headAnimator->NumFrames( headAnim ) );
}
// reset the anim
mode = -1;
frame = 1;
}
/*
================
idTestModel::PrevAnim
================
*/
void idTestModel::PrevAnim( const idCmdArgs &args ) {
if ( !animator.NumAnims() ) {
return;
}
headAnim = 0;
anim--;
if ( anim < 0 ) {
anim = animator.NumAnims() - 1;
}
starttime = gameLocal.time;
animtime = animator.AnimLength( anim );
animname = animator.AnimFullName( anim );
headAnim = 0;
if ( headAnimator ) {
headAnimator->ClearAllAnims( gameLocal.time, 0 );
headAnim = headAnimator->GetAnim( animname );
if ( !headAnim ) {
headAnim = headAnimator->GetAnim( "idle" );
}
if ( headAnim && ( headAnimator->AnimLength( headAnim ) > animtime ) ) {
animtime = headAnimator->AnimLength( headAnim );
}
}
gameLocal.Printf( "anim '%s', %d.%03d seconds, %d frames\n", animname.c_str(), animator.AnimLength( anim ) / 1000, animator.AnimLength( anim ) % 1000, animator.NumFrames( anim ) );
if ( headAnim ) {
gameLocal.Printf( "head '%s', %d.%03d seconds, %d frames\n", headAnimator->AnimFullName( headAnim ), headAnimator->AnimLength( headAnim ) / 1000, headAnimator->AnimLength( headAnim ) % 1000, headAnimator->NumFrames( headAnim ) );
}
// reset the anim
mode = -1;
frame = 1;
}
/*
================
idTestModel::NextFrame
================
*/
void idTestModel::NextFrame( const idCmdArgs &args ) {
if ( !anim || ( ( g_testModelAnimate.GetInteger() != 3 ) && ( g_testModelAnimate.GetInteger() != 5 ) ) ) {
return;
}
frame++;
if ( frame > animator.NumFrames( anim ) ) {
frame = 1;
}
gameLocal.Printf( "^5 Anim: ^7%s\n^5Frame: ^7%d/%d\n\n", animator.AnimFullName( anim ), frame, animator.NumFrames( anim ) );
// reset the anim
mode = -1;
}
/*
================
idTestModel::PrevFrame
================
*/
void idTestModel::PrevFrame( const idCmdArgs &args ) {
if ( !anim || ( ( g_testModelAnimate.GetInteger() != 3 ) && ( g_testModelAnimate.GetInteger() != 5 ) ) ) {
return;
}
frame--;
if ( frame < 1 ) {
frame = animator.NumFrames( anim );
}
gameLocal.Printf( "^5 Anim: ^7%s\n^5Frame: ^7%d/%d\n\n", animator.AnimFullName( anim ), frame, animator.NumFrames( anim ) );
// reset the anim
mode = -1;
}
/*
================
idTestModel::TestAnim
================
*/
void idTestModel::TestAnim( const idCmdArgs &args ) {
idStr name;
int animNum;
const idAnim *newanim;
if ( args.Argc() < 2 ) {
gameLocal.Printf( "usage: testanim <animname>\n" );
return;
}
newanim = NULL;
name = args.Argv( 1 );
#if 0
if ( strstr( name, ".ma" ) || strstr( name, ".mb" ) ) {
const idMD5Anim *md5anims[ ANIM_MaxSyncedAnims ];
idModelExport exporter;
exporter.ExportAnim( name );
name.SetFileExtension( MD5_ANIM_EXT );
md5anims[ 0 ] = animationLib.GetAnim( name );
if ( md5anims[ 0 ] ) {
customAnim.SetAnim( animator.ModelDef(), name, name, 1, md5anims );
newanim = &customAnim;
}
} else {
animNum = animator.GetAnim( name );
}
#else
animNum = animator.GetAnim( name );
#endif
if ( !animNum ) {
gameLocal.Printf( "Animation '%s' not found.\n", name.c_str() );
return;
}
anim = animNum;
starttime = gameLocal.time;
animtime = animator.AnimLength( anim );
headAnim = 0;
if ( headAnimator ) {
headAnimator->ClearAllAnims( gameLocal.time, 0 );
headAnim = headAnimator->GetAnim( animname );
if ( !headAnim ) {
headAnim = headAnimator->GetAnim( "idle" );
if ( !headAnim ) {
gameLocal.Printf( "Missing 'idle' anim for head.\n" );
}
}
if ( headAnim && ( headAnimator->AnimLength( headAnim ) > animtime ) ) {
animtime = headAnimator->AnimLength( headAnim );
}
}
animname = name;
gameLocal.Printf( "anim '%s', %d.%03d seconds, %d frames\n", animname.c_str(), animator.AnimLength( anim ) / 1000, animator.AnimLength( anim ) % 1000, animator.NumFrames( anim ) );
// reset the anim
mode = -1;
}
/*
=====================
idTestModel::BlendAnim
=====================
*/
void idTestModel::BlendAnim( const idCmdArgs &args ) {
int anim1;
int anim2;
if ( args.Argc() < 4 ) {
gameLocal.Printf( "usage: testblend <anim1> <anim2> <frames>\n" );
return;
}
anim1 = gameLocal.testmodel->animator.GetAnim( args.Argv( 1 ) );
if ( !anim1 ) {
gameLocal.Printf( "Animation '%s' not found.\n", args.Argv( 1 ) );
return;
}
anim2 = gameLocal.testmodel->animator.GetAnim( args.Argv( 2 ) );
if ( !anim2 ) {
gameLocal.Printf( "Animation '%s' not found.\n", args.Argv( 2 ) );
return;
}
animname = args.Argv( 2 );
animator.CycleAnim( ANIMCHANNEL_ALL, anim1, gameLocal.time, 0 );
animator.CycleAnim( ANIMCHANNEL_ALL, anim2, gameLocal.time, FRAME2MS( atoi( args.Argv( 3 ) ) ) );
anim = anim2;
headAnim = 0;
}
/***********************************************************************
Testmodel console commands
***********************************************************************/
/*
=================
idTestModel::KeepTestModel_f
Makes the current test model permanent, allowing you to place
multiple test models
=================
*/
void idTestModel::KeepTestModel_f( const idCmdArgs &args ) {
if ( !gameLocal.testmodel ) {
gameLocal.Printf( "No active testModel.\n" );
return;
}
gameLocal.Printf( "modelDef %i kept\n", gameLocal.testmodel->renderEntity.hModel );
gameLocal.testmodel = NULL;
}
/*
=================
idTestModel::TestSkin_f
Sets a skin on an existing testModel
=================
*/
void idTestModel::TestSkin_f( const idCmdArgs &args ) {
idVec3 offset;
idStr name;
idPlayer * player;
idDict dict;
player = gameLocal.GetLocalPlayer();
if ( !player || !gameLocal.CheatsOk() ) {
return;
}
// delete the testModel if active
if ( !gameLocal.testmodel ) {
gameLocal.Printf( "No active testModel\n" );
return;
}
if ( args.Argc() < 2 ) {
gameLocal.Printf( "removing testSkin.\n" );
gameLocal.testmodel->SetSkin( NULL );
return;
}
name = args.Argv( 1 );
gameLocal.testmodel->SetSkin( declManager->FindSkin( name ) );
}
/*
=================
idTestModel::TestShaderParm_f
Sets a shaderParm on an existing testModel
=================
*/
void idTestModel::TestShaderParm_f( const idCmdArgs &args ) {
idVec3 offset;
idStr name;
idPlayer * player;
idDict dict;
player = gameLocal.GetLocalPlayer();
if ( !player || !gameLocal.CheatsOk() ) {
return;
}
// delete the testModel if active
if ( !gameLocal.testmodel ) {
gameLocal.Printf( "No active testModel\n" );
return;
}
if ( args.Argc() != 3 ) {
gameLocal.Printf( "USAGE: testShaderParm <parmNum> <float | \"time\">\n" );
return;
}
int parm = atoi( args.Argv( 1 ) );
if ( parm < 0 || parm >= MAX_ENTITY_SHADER_PARMS ) {
gameLocal.Printf( "parmNum %i out of range\n", parm );
return;
}
float value;
if ( !stricmp( args.Argv( 2 ), "time" ) ) {
value = gameLocal.time * -0.001;
} else {
value = atof( args.Argv( 2 ) );
}
gameLocal.testmodel->SetShaderParm( parm, value );
}
/*
=================
idTestModel::TestModel_f
Creates a static modelDef in front of the current position, which
can then be moved around
=================
*/
void idTestModel::TestModel_f( const idCmdArgs &args ) {
idVec3 offset;
idStr name;
idPlayer * player;
const idDict * entityDef;
idDict dict;
player = gameLocal.GetLocalPlayer();
if ( !player || !gameLocal.CheatsOk() ) {
return;
}
// delete the testModel if active
if ( gameLocal.testmodel ) {
delete gameLocal.testmodel;
gameLocal.testmodel = NULL;
}
if ( args.Argc() < 2 ) {
return;
}
name = args.Argv( 1 );
entityDef = gameLocal.FindEntityDefDict( name, false );
if ( entityDef ) {
dict = *entityDef;
} else {
if ( declManager->FindType( DECL_MODELDEF, name, false ) ) {
dict.Set( "model", name );
} else {
// allow map models with underscore prefixes to be tested during development
// without appending an ase
if ( name[ 0 ] != '_' ) {
name.DefaultFileExtension( ".ase" );
}
if ( strstr( name, ".ma" ) || strstr( name, ".mb" ) ) {
idModelExport exporter;
exporter.ExportModel( name );
name.SetFileExtension( MD5_MESH_EXT );
}
if ( !renderModelManager->CheckModel( name ) ) {
gameLocal.Printf( "Can't register model\n" );
return;
}
dict.Set( "model", name );
}
}
offset = player->GetPhysics()->GetOrigin() + player->viewAngles.ToForward() * 100.0f;
dict.Set( "origin", offset.ToString() );
dict.Set( "angle", va( "%f", player->viewAngles.yaw + 180.0f ) );
// RAVEN BEGIN
// jnewquist: Use accessor for static class type
gameLocal.testmodel = ( idTestModel * )gameLocal.SpawnEntityType( idTestModel::GetClassType(), &dict );
// RAVEN END
gameLocal.testmodel->renderEntity.shaderParms[SHADERPARM_TIMEOFFSET] = -MS2SEC( gameLocal.time );
}
/*
=====================
idTestModel::ArgCompletion_TestModel
=====================
*/
void idTestModel::ArgCompletion_TestModel( const idCmdArgs &args, void(*callback)( const char *s ) ) {
int i, num;
num = declManager->GetNumDecls( DECL_ENTITYDEF );
for ( i = 0; i < num; i++ ) {
callback( idStr( args.Argv( 0 ) ) + " " + declManager->DeclByIndex( DECL_ENTITYDEF, i , false )->GetName() );
}
num = declManager->GetNumDecls( DECL_MODELDEF );
for ( i = 0; i < num; i++ ) {
callback( idStr( args.Argv( 0 ) ) + " " + declManager->DeclByIndex( DECL_MODELDEF, i , false )->GetName() );
}
cmdSystem->ArgCompletion_FolderExtension( args, callback, "models/", false, ".lwo", ".ase", ".md5mesh", ".ma", ".mb", NULL );
}
/*
=====================
idTestModel::TestParticleStopTime_f
=====================
*/
void idTestModel::TestParticleStopTime_f( const idCmdArgs &args ) {
if ( !gameLocal.testmodel ) {
gameLocal.Printf( "No testModel active.\n" );
return;
}
gameLocal.testmodel->renderEntity.shaderParms[SHADERPARM_PARTICLE_STOPTIME] = MS2SEC( gameLocal.time );
gameLocal.testmodel->UpdateVisuals();
}
/*
=====================
idTestModel::TestAnim_f
=====================
*/
void idTestModel::TestAnim_f( const idCmdArgs &args ) {
if ( !gameLocal.testmodel ) {
gameLocal.Printf( "No testModel active.\n" );
return;
}
gameLocal.testmodel->TestAnim( args );
}
/*
=====================
idTestModel::ArgCompletion_TestAnim
=====================
*/
void idTestModel::ArgCompletion_TestAnim( const idCmdArgs &args, void(*callback)( const char *s ) ) {
if ( gameLocal.testmodel ) {
idAnimator *animator = gameLocal.testmodel->GetAnimator();
for( int i = 0; i < animator->NumAnims(); i++ ) {
callback( va( "%s %s", args.Argv( 0 ), animator->AnimFullName( i ) ) );
}
}
}
/*
=====================
idTestModel::TestBlend_f
=====================
*/
void idTestModel::TestBlend_f( const idCmdArgs &args ) {
if ( !gameLocal.testmodel ) {
gameLocal.Printf( "No testModel active.\n" );
return;
}
gameLocal.testmodel->BlendAnim( args );
}
/*
=====================
idTestModel::TestModelNextAnim_f
=====================
*/
void idTestModel::TestModelNextAnim_f( const idCmdArgs &args ) {
if ( !gameLocal.testmodel ) {
gameLocal.Printf( "No testModel active.\n" );
return;
}
gameLocal.testmodel->NextAnim( args );
}
/*
=====================
idTestModel::TestModelPrevAnim_f
=====================
*/
void idTestModel::TestModelPrevAnim_f( const idCmdArgs &args ) {
if ( !gameLocal.testmodel ) {
gameLocal.Printf( "No testModel active.\n" );
return;
}
gameLocal.testmodel->PrevAnim( args );
}
/*
=====================
idTestModel::TestModelNextFrame_f
=====================
*/
void idTestModel::TestModelNextFrame_f( const idCmdArgs &args ) {
if ( !gameLocal.testmodel ) {
gameLocal.Printf( "No testModel active.\n" );
return;
}
gameLocal.testmodel->NextFrame( args );
}
/*
=====================
idTestModel::TestModelPrevFrame_f
=====================
*/
void idTestModel::TestModelPrevFrame_f( const idCmdArgs &args ) {
if ( !gameLocal.testmodel ) {
gameLocal.Printf( "No testModel active.\n" );
return;
}
gameLocal.testmodel->PrevFrame( args );
}
| [
"stradexengine@gmail.com"
] | stradexengine@gmail.com |
546756051e28f5cd5b0ec960246d67116038c878 | 5cfea31967a3ce443c361b280a5eb9298e6951af | /src/Base/Shell/Command.cpp | 982e8f4b428aed402c8bf480707a517416220f47 | [
"Zlib"
] | permissive | gleibson/phobos3d | 7a2e128d1de0aff1352859fb6557bc6fb03b916b | c0336456d946f3a9e62fb9b7815831ad32820da5 | refs/heads/master | 2020-04-05T18:32:15.383805 | 2013-08-21T02:54:25 | 2013-08-21T02:54:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 944 | cpp | /*
Phobos 3d
March 2010
Copyright (c) 2005-2011 Bruno Sanches http://code.google.com/p/phobos3d
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "Phobos/Shell/Command.h"
| [
"bcsanches@gmail.com"
] | bcsanches@gmail.com |
b353149766ebab6d1bc4bf05fcb483d13abbfdbe | 38c10c01007624cd2056884f25e0d6ab85442194 | /content/common/child_process_host_impl.h | d859323627af09b1863ef6717c3140730fe6c9fb | [
"BSD-3-Clause"
] | permissive | zenoalbisser/chromium | 6ecf37b6c030c84f1b26282bc4ef95769c62a9b2 | e71f21b9b4b9b839f5093301974a45545dad2691 | refs/heads/master | 2022-12-25T14:23:18.568575 | 2016-07-14T21:49:52 | 2016-07-23T08:02:51 | 63,980,627 | 0 | 2 | BSD-3-Clause | 2022-12-12T12:43:41 | 2016-07-22T20:14:04 | null | UTF-8 | C++ | false | false | 4,597 | h | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_COMMON_CHILD_PROCESS_HOST_IMPL_H_
#define CONTENT_COMMON_CHILD_PROCESS_HOST_IMPL_H_
#include <string>
#include <vector>
#include "build/build_config.h"
#include "base/basictypes.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/shared_memory.h"
#include "base/memory/singleton.h"
#include "base/process/process.h"
#include "base/strings/string16.h"
#include "content/public/common/child_process_host.h"
#include "ipc/ipc_listener.h"
#include "ui/gfx/gpu_memory_buffer.h"
namespace base {
class FilePath;
}
namespace IPC {
class MessageFilter;
}
namespace content {
class ChildProcessHostDelegate;
// Provides common functionality for hosting a child process and processing IPC
// messages between the host and the child process. Users are responsible
// for the actual launching and terminating of the child processes.
class CONTENT_EXPORT ChildProcessHostImpl : public ChildProcessHost,
public IPC::Listener {
public:
~ChildProcessHostImpl() override;
// Public and static for reuse by RenderMessageFilter.
static void AllocateSharedMemory(
size_t buffer_size, base::ProcessHandle child_process,
base::SharedMemoryHandle* handle);
// Returns a unique ID to identify a child process. On construction, this
// function will be used to generate the id_, but it is also used to generate
// IDs for the RenderProcessHost, which doesn't inherit from us, and whose IDs
// must be unique for all child processes.
//
// This function is threadsafe since RenderProcessHost is on the UI thread,
// but normally this will be used on the IO thread.
//
// This will never return ChildProcessHost::kInvalidUniqueID.
static int GenerateChildProcessUniqueId();
// Derives a tracing process id from a child process id. Child process ids
// cannot be used directly in child process for tracing due to security
// reasons (see: discussion in crrev.com/1173263004). This method is meant to
// be used when tracing for identifying cross-process shared memory from a
// process which knows the child process id of its endpoints. The value
// returned by this method is guaranteed to be equal to the value returned by
// MemoryDumpManager::GetTracingProcessId() in the corresponding child
// process.
//
// Never returns MemoryDumpManager::kInvalidTracingProcessId.
// Returns only ChildProcessHost::kBrowserTracingProcessId in single-process
// mode.
static uint64 ChildProcessUniqueIdToTracingProcessId(int child_process_id);
// ChildProcessHost implementation
bool Send(IPC::Message* message) override;
void ForceShutdown() override;
std::string CreateChannel() override;
bool IsChannelOpening() override;
void AddFilter(IPC::MessageFilter* filter) override;
#if defined(OS_POSIX)
base::ScopedFD TakeClientFileDescriptor() override;
#endif
private:
friend class ChildProcessHost;
explicit ChildProcessHostImpl(ChildProcessHostDelegate* delegate);
// IPC::Listener methods:
bool OnMessageReceived(const IPC::Message& msg) override;
void OnChannelConnected(int32 peer_pid) override;
void OnChannelError() override;
void OnBadMessageReceived(const IPC::Message& message) override;
// Message handlers:
void OnShutdownRequest();
void OnAllocateSharedMemory(uint32 buffer_size,
base::SharedMemoryHandle* handle);
void OnAllocateGpuMemoryBuffer(gfx::GpuMemoryBufferId id,
uint32 width,
uint32 height,
gfx::BufferFormat format,
gfx::BufferUsage usage,
gfx::GpuMemoryBufferHandle* handle);
void OnDeletedGpuMemoryBuffer(gfx::GpuMemoryBufferId id,
uint32 sync_point);
ChildProcessHostDelegate* delegate_;
base::Process peer_process_;
bool opening_channel_; // True while we're waiting the channel to be opened.
scoped_ptr<IPC::Channel> channel_;
std::string channel_id_;
// Holds all the IPC message filters. Since this object lives on the IO
// thread, we don't have a IPC::ChannelProxy and so we manage filters
// manually.
std::vector<scoped_refptr<IPC::MessageFilter> > filters_;
DISALLOW_COPY_AND_ASSIGN(ChildProcessHostImpl);
};
} // namespace content
#endif // CONTENT_COMMON_CHILD_PROCESS_HOST_IMPL_H_
| [
"zeno.albisser@hemispherian.com"
] | zeno.albisser@hemispherian.com |
cf71a20b4487191b6244d44d92569cd98963ce62 | 872f24199d847f05ddb4d8f7ac69eaed9336a0d5 | /code/flagging/Flagging/RFDataMapper.cc | bdb231921228791fbb0a8f066d0c9629c71e87d5 | [] | no_license | schiebel/casa | 8004f7d63ca037b4579af8a8bbfb4fa08e87ced4 | e2ced7349036d8fc13d0a65aad9a77b76bfe55d1 | refs/heads/master | 2016-09-05T16:20:59.022063 | 2015-08-26T18:46:26 | 2015-08-26T18:46:26 | 41,441,084 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,931 | cc |
//# RFDataMapper.cc: this defines RFDataMapper
//# Copyright (C) 2000,2001
//# Associated Universities, Inc. Washington DC, USA.
//#
//# This library is free software; you can redistribute it and/or modify it
//# under the terms of the GNU Library General Public License as published by
//# the Free Software Foundation; either version 2 of the License, or (at your
//# option) any later version.
//#
//# This library is distributed in the hope that it will be useful, but WITHOUT
//# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
//# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
//# License for more details.
//#
//# You should have received a copy of the GNU Library General Public License
//# along with this library; if not, write to the Free Software Foundation,
//# Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA.
//#
//# Correspondence concerning AIPS++ should be addressed as follows:
//# Internet email: aips2-request@nrao.edu.
//# Postal address: AIPS++ Project Office
//# National Radio Astronomy Observatory
//# 520 Edgemont Road
//# Charlottesville, VA 22903-2475 USA
//#
//# $Id$
#include <flagging/Flagging/RFDataMapper.h>
#include <casa/Arrays/Slice.h>
#include <casa/Arrays/Cube.h>
#include <casa/Arrays/ArrayMath.h>
#include <casa/Exceptions/Error.h>
#include <casa/BasicMath/Math.h>
#include <casa/BasicSL/Constants.h>
#include <msvis/MSVis/VisBuffer.h>
#include <msvis/MSVis/VisibilityIterator.h>
#include <measures/Measures/MDirection.h>
namespace casa { //# NAMESPACE CASA - BEGIN
/*
// Define functions for mapping a VisBuffer to obsevred, model and corrected
// visibility cubes
#define CubeMapper(name,method) \
static Cube<Complex> * CubeMap##name ( VisBuffer &vb ) \
{ return &vb.method(); }
CubeMapper(Obs,visCube);
CubeMapper(Model,modelVisCube);
CubeMapper(Corrected,correctedVisCube);
#undef CubeMapper
// Define functions for mapping a VisBuffer to residual
// visibility cube
#define CubeMapper1(name,method1,method2) \
static Cube<Complex> * CubeMap##name ( VisBuffer &vb ) \
{ return &(vb.method1() - vb.method2()); }
CubeMapper(ResCorrected,correctedVisCube,modelVisCube);
CubeMapper(ResObs,visCube,modelVisCube);
#undef CubeMapper1
*/
/// before assigning pviscube..
/* vb.visCube() = vb.correctedVisCube() - vb.modelVisCube() */
static Cube<Complex> * CubeMapObs ( VisBuffer &vb ){ return &vb.visCube(); }
static Cube<Complex> * CubeMapModel ( VisBuffer &vb ){ return &vb.modelVisCube(); }
static Cube<Complex> * CubeMapCorrected ( VisBuffer &vb ){ return &vb.correctedVisCube(); }
static Cube<Complex> * CubeMapResCorrected ( VisBuffer &vb )
{ vb.visCube() = vb.correctedVisCube() - vb.modelVisCube();
return &vb.visCube(); }
//{ return &(vb.correctedVisCube() - vb.modelVisCube()); }
static Cube<Complex> * CubeMapResObs ( VisBuffer &vb )
{ vb.visCube() = vb.visCube() - vb.modelVisCube();
return &vb.visCube(); }
//{ return &(vb.visCube() - vb.modelVisCube()); }
// a dummyRowMapper for uninitialized row mappings
Float RFDataMapper::dummyRowMapper (uInt)
{
throw( AipsError("DataMapper: call to unititialized RowMapper") );
}
// define a bunch of row mapper for various UVW stuff
#define UVW ((*puvw)(ir))
#define UVRowMapper(name,expr) \
Float RFDataMapper::name##_RowMapper (uInt ir) \
{ return expr; }
UVRowMapper(U,UVW(0));
UVRowMapper(V,UVW(1));
UVRowMapper(W,UVW(2));
UVRowMapper(AbsU,abs(UVW(0)));
UVRowMapper(AbsV,abs(UVW(1)));
UVRowMapper(AbsW,abs(UVW(2)));
UVRowMapper(UVD,sqrt(UVW(0)*UVW(0)+UVW(1)*UVW(1)));
UVRowMapper(UVA,atan2(UVW(0),UVW(1))/C::pi*180);
UVRowMapper(HA,sin_dec!=0 ? atan2(UVW(1)/sin_dec,UVW(0))/C::pi*180 : 0 );
// these arrays define a mapping between column names and cube mappers
const String
COL_ID[] = { "OBS", "DATA", "MODEL",
"CORR", "CORRECTED",
"RES",
"RES_CORR", "RES_CORRECTED",
"RES_OBS", "RES_DATA"};
const RFDataMapper::CubeMapperFunc
COL_MAP[] = { &CubeMapObs, &CubeMapObs, &CubeMapModel,
&CubeMapCorrected, &CubeMapCorrected,
&CubeMapResCorrected,
&CubeMapResCorrected, &CubeMapResCorrected,
&CubeMapResObs, &CubeMapResObs};
// -----------------------------------------------------------------------
// RFDataMapper::getCubeMapper
// Maps column name to a cube mapper function
// -----------------------------------------------------------------------
RFDataMapper::CubeMapperFunc RFDataMapper::getCubeMapper( const String &column,Bool throw_excp )
{
// setup cube mapper
if( !column.length() )
return COL_MAP[0];
String col( upcase(column) );
for( uInt i=0; i<sizeof(COL_ID)/sizeof(COL_ID[0]); i++ ) {
if( col.matches(COL_ID[i]) )
return COL_MAP[i];
}
if( throw_excp )
throw( AipsError("DataMapper: unknown column "+column) );
return NULL;
}
// -----------------------------------------------------------------------
// Constructor 1
// For visibility expressions
// -----------------------------------------------------------------------
RFDataMapper::RFDataMapper ( const String &colmn,DDMapper *map )
: desc(""),
ddm(map),
// rowmapper(NULL),
cubemap(getCubeMapper(colmn,True)),
mytype(MAPCORR)
{
sin_dec = -10; // need not be computed by default, so set to <-1
full_cycle = cycle_base = 0; // by default, mapped values are not cyclic
rowmapper = &RFDataMapper::dummyRowMapper;
}
// -----------------------------------------------------------------------
// Constructor 2
// For visibility expressions, with explicit column specification
// -----------------------------------------------------------------------
RFDataMapper::RFDataMapper ( const Vector<String> &expr0,const String &defcol )
: expr_desc(""),
ddm(NULL),
cubemap(NULL),
// rowmapper(dummyRowMapper),
mytype(MAPCORR)
{
sin_dec = -10; // need not be computed by default, so set to <-1
full_cycle = cycle_base = 0; // by default, mapped values are not cyclic
rowmapper = &RFDataMapper::dummyRowMapper;
Vector<String> expr( splitExpression(expr0) );
// first, check for per-row expressions (i.e., UVW, etc.)
// at this point, assume we have a per-row expression (i.e. UVW, etc.)
Bool absof=False;
String el = upcase(expr(0));
if( el == "ABS" )
{
absof=True;
if( expr.nelements()<2 )
throw(AipsError("DataMapper: illegal expression "+expr(0)));
el = upcase( expr(1) );
}
else if( el.matches("ABS",0) )
{
absof = True;
el = el.after(3);
}
if( el == "U" )
rowmapper = absof ? &RFDataMapper::AbsU_RowMapper : &RFDataMapper::U_RowMapper;
else if( el == "V" )
rowmapper = absof ? &RFDataMapper::AbsV_RowMapper : &RFDataMapper::V_RowMapper;
else if( el == "W" )
rowmapper = absof ? &RFDataMapper::AbsW_RowMapper : &RFDataMapper::W_RowMapper;
else if( el == "UVD" || el == "UVDIST" )
rowmapper = &RFDataMapper::UVD_RowMapper;
else if( el == "UVA" || el == "UVANGLE" )
{
rowmapper = &RFDataMapper::UVA_RowMapper;
full_cycle = 360; // mapping into angles
cycle_base = -180;
}
else if( el == "HA" || el == "HANGLE" )
{
sin_dec = 0; // will need to be computed
rowmapper = &RFDataMapper::HA_RowMapper;
full_cycle = 360; // mapping into angles
cycle_base = -180;
}
else
rowmapper = NULL;
// have we set up a valid row mapper? Return then
if( rowmapper )
{
desc = absof ? "|"+el+"|" : el;
expr_desc = desc;
mytype = MAPROW;
return;
}
// at this point, it must be a valid correlation expression
String column(defcol);
// see if expression starts with a non-empty column specification, if so,
// remember the column, and shift it out of the expression vector
CubeMapperFunc cm = getCubeMapper(expr(0));
if( cm && expr(0).length() )
{
column = expr(0);
expr = expr(Slice(1,expr.nelements()-1));
}
// check if it parses to a valid DDMapper expression
ddm = DDFunc::getMapper(expr_desc,expr);
// valid expression? Set ourselves up as a correlation mapper then
if( ddm )
{
if( !cm ) // set column from defcol if not set above
cm = getCubeMapper(defcol,True);
cubemap = cm;
desc = (column.length() ? "("+upcase(column)+")" : String("") )+expr_desc;
mytype = MAPCORR;
return;
}
// invalid expression, so throw an exception
String s;
for( uInt i=0; i<expr.nelements(); i++ )
{
if( i )
s+=" ";
s+=expr(i);
}
throw(AipsError("DataMapper: illegal expression "+s));
}
RFDataMapper::~RFDataMapper ()
{
if( ddm )
delete ddm;
};
// computes a correlations mask
RFlagWord RFDataMapper::corrMask ( const VisibilityIterator &vi )
{
Vector<Int> corr;
vi.corrType(corr);
// for a visibilities mapper, ask the DDMapper
if( mytype == MAPCORR )
{
if( !ddm->reset( corr ) )
return 0;
return (RFlagWord) ddm->corrMask();
}
// for a row mapper, flag all correlations
else if( mytype == MAPROW )
{
return (1<<corr.nelements())-1;
}
else // paranoid case
throw( AipsError( "DataMapper: unknown mytype") );
}
// sets up for a visbuffer
void RFDataMapper::setVisBuffer ( VisBuffer &vb )
{
if( mytype == MAPCORR )
pviscube = (*cubemap)(vb);
else if( mytype == MAPROW )
puvw = &vb.uvw();
else
throw( AipsError( "DataMapper: unknown mytype") );
// extract sine of declination, if needed
if( sin_dec>=-1 )
{
sin_dec = sin( MDirection::Convert( vb.phaseCenter(),
MDirection::Ref(MDirection::J2000)
)().getAngle().getBaseValue()(1) );
}
}
} //# NAMESPACE CASA - END
| [
"darrell@schiebel.us"
] | darrell@schiebel.us |
8eec209c85e7f3e840f8d7bc9722fafd1e2f9221 | e49a3cdc5b5a6035babaa4e14b2f497b434369d4 | /CloningVisual/CloningVisual.h | e02692e8890cf8842c1e49c5754240ddd392cb96 | [] | no_license | xiaoyaoth/GSimCloning_repo | 19dc6f8de1e364eec1617b92e6b08abd9d715675 | 333dc62955edbf97aa0e1f873e32549a48009964 | refs/heads/master | 2020-06-17T17:07:57.654571 | 2016-11-28T15:26:47 | 2016-11-28T15:26:47 | 74,985,764 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 547 | h |
// CloningVisual.h : main header file for the PROJECT_NAME application
//
#pragma once
#ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH"
#endif
#include "resource.h" // main symbols
// CCloningVisualApp:
// See CloningVisual.cpp for the implementation of this class
//
class CCloningVisualApp : public CWinApp
{
public:
CCloningVisualApp();
// Overrides
public:
virtual BOOL InitInstance();
// Implementation
DECLARE_MESSAGE_MAP()
};
extern CCloningVisualApp theApp; | [
"xiaoyaoth@gmail.com"
] | xiaoyaoth@gmail.com |
34155bc228594b1fbc5363a3d93049df006a0930 | b45ad73b8d4951b40891cc8cf9c2d51373729d74 | /一本通OJ/1476.cpp | 3a89c3fd6da185aed98e17a5f7e5561b74c06134 | [] | no_license | TTP1128/wangjunrui-s-code | 4849ff0d4f6fbfa04e8930fb8c7a25980f3251e7 | 58e94ce1b64676feef4d5bf7a1bf89b527ada568 | refs/heads/master | 2020-12-23T11:49:38.313178 | 2020-01-25T05:19:16 | 2020-01-25T05:19:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 906 | cpp | #include<cstdio>
using namespace std;
#define r register
inline int read()
{
char s=getchar();
bool f=false;
int x=0;
while(!(s>='0'&&s<='9'))
{
if(s=='-')
f=true;
s=getchar();
}
while(s>='0'&&s<='9')
{
x=(x<<1)+(x<<3)+s-'0';
s=getchar();
}
return f?-x:x;
}
int n,m,ch[1000010][2],s[10010],sum[1000010],bo[1000010],tot=1;
inline void insert(int s[])
{
int u=1;
for(r int i=1,c; i<=s[0]; i++)
{
c=s[i];
if(!ch[u][c])
ch[u][c]=++tot;
u=ch[u][c];
sum[u]++;
}
bo[u]++;
}
inline void find(int s[])
{
int u=1,ans=0;
for(r int i=1,c; i<=s[0]; i++)
{
c=s[i];
ans+=bo[u];
u=ch[u][c];
}
printf("%d\n",ans+sum[u]);
}
int main()
{
n=read();
m=read();
for(r int j=1; j<=n; j++)
{
s[0]=read();
for(r int i=1; i<=s[0]; i++)
s[i]=read();
insert(s);
}
for(r int j=1; j<=m; j++)
{
s[0]=read();
for(r int i=1; i<=s[0]; i++)
s[i]=read();
find(s);
}
}
| [
"2147483647@qq.com"
] | 2147483647@qq.com |
7017771b0730338fd312d568e511dd7bde6a4b79 | 36dc7e93a90955c2d7a956baf701ba4ed1927b1d | /stl/std_copy.cpp | 1a0e83a59d053b2e4fef8962842ba3e2c5148908 | [] | no_license | Wei-N-Ning/cxxAlgorithms | 12e59b9dba9642653a56eb48d8f6d810312dee67 | 9b592e08c547014fc88d804bb009d017cf8434f5 | refs/heads/master | 2021-06-21T01:02:40.288878 | 2020-12-28T00:37:39 | 2020-12-28T00:37:39 | 147,929,667 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 866 | cpp |
// source
// mentioned in more exception item 13, lazy copy / ref counting
// reference:
// https://en.cppreference.com/w/cpp/algorithm/copy
//
// interesting read:
// performance comparison between std::copy and memcpy()
// https://stackoverflow.com/questions/4707012/is-it-better-to-use-stdmemcpy-or-stdcopy-in-terms-to-performance
//
// the conclusion is to use std::copy()
#include <list>
#include <set>
#include <cassert>
// this is the case where memcpy can not work
void test_copy_non_contiguous_data() {
std::set<double> src{3, 0, 14, 1, 59, 26, 5, 35, -8, -97};
std::list<double> dest(10);
// set iterator provides the source elements in sorted order
std::copy(src.cbegin(), src.cend(), dest.begin());
assert(-97 == dest.front());
assert(59 == dest.back());
}
int main() {
test_copy_non_contiguous_data();
return 0;
}
| [
"nwcgnw@gmail.com"
] | nwcgnw@gmail.com |
4c9d0721076fa1ea368d43a9bc8d9bfd7cc51ec8 | 50bdaa2e71aae37240c61c930decbfe9d1e504b8 | /harp-daal-app/daal-src/algorithms/kernel/pca/pca_result_fpt.cpp | 943812984f2b21137240596f54dee80ee5d300ed | [
"Apache-2.0"
] | permissive | prawalgangwar/harp | 010b1f669ee54941365ba1204be4e1484c15f108 | 3c3a3bf2d519f76ccf8ae17d8b3681e0a93048b7 | refs/heads/master | 2020-09-13T19:57:54.274328 | 2017-06-20T00:03:57 | 2017-06-20T00:03:57 | 94,464,682 | 0 | 0 | null | 2017-06-15T17:49:16 | 2017-06-15T17:49:16 | null | UTF-8 | C++ | false | false | 1,317 | cpp | /* file: pca_result_fpt.cpp */
/*******************************************************************************
* Copyright 2014-2016 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
/*
//++
// Implementation of PCA algorithm interface.
//--
*/
#include "pca_result.h"
namespace daal
{
namespace algorithms
{
namespace pca
{
template DAAL_EXPORT void Result::allocate<DAAL_FPTYPE>(const daal::algorithms::Input *input, daal::algorithms::Parameter *parameter, const Method method);
template DAAL_EXPORT void Result::allocate<DAAL_FPTYPE>(const daal::algorithms::PartialResult *partialResult, daal::algorithms::Parameter *parameter, const Method method);
}// namespace pca
}// namespace algorithms
}// namespace daal
| [
"lc37@156-56-102-164.dhcp-bl.indiana.edu"
] | lc37@156-56-102-164.dhcp-bl.indiana.edu |
edfc7e606ce4af7f3a0c513719e71e9949ed9e86 | b367fe5f0c2c50846b002b59472c50453e1629bc | /xbox_leak_may_2020/xbox trunk/xbox/private/test/directx/d3d/conf/Cubemap/Utility.cpp | 2157550ea89ea4ad51b709c885987e07d74578b4 | [] | no_license | sgzwiz/xbox_leak_may_2020 | 11b441502a659c8da8a1aa199f89f6236dd59325 | fd00b4b3b2abb1ea6ef9ac64b755419741a3af00 | refs/heads/master | 2022-12-23T16:14:54.706755 | 2020-09-27T18:24:48 | 2020-09-27T18:24:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,798 | cpp | //#define D3D_OVERLOADS
#include "d3dlocus.h"
#include "cd3dtest.h"
#include "3dmath.h"
#include "Cubemap.h"
bool CCubemap::BltCubicTexture(void)
{
/*
// Blt from source sysmem to vidmem method
POINT Pt = {0,0};
for (int i=0;i<6;i++)
{
for (int j=0;j<m_paSysTexture->m_pSrcSurface->GetNumAttachedSurfaces();j++)
{
CDirectDrawSurface * pSurface = m_paTexture->m_pSrcSurface->GetCubicSurface(i)->GetAttachedSurface(j);
CDirectDrawSurface * pSysSurface = m_paSysTexture->m_pSrcSurface->GetCubicSurface(i)->GetAttachedSurface(j);
// Blt from source sysmem to source target method
if (!pSurface->Blt(pSysSurface,Pt))
{
WriteToLog("Source Blt(%d) failed with HResult = %s.",i,GetHResultString(GetLastError()).c_str());
RELEASE(pSurface);
RELEASE(pSysSurface);
return false;
}
RELEASE(pSurface);
RELEASE(pSysSurface);
if (NULL != m_pRefTarget)
{
CDirectDrawSurface * pSurface = m_paTexture->m_pRefSurface->GetCubicSurface(i)->GetAttachedSurface(j);
CDirectDrawSurface * pSysSurface = m_paSysTexture->m_pRefSurface->GetCubicSurface(i)->GetAttachedSurface(j);
// Blt from ref sysmem to ref target method
if (!pSurface->Blt(pSysSurface,Pt))
{
WriteToLog("Reference Blt(%d) failed with HResult = %s.",i,GetHResultString(GetLastError()).c_str());
RELEASE(pSurface);
RELEASE(pSysSurface);
return false;
}
RELEASE(pSurface);
RELEASE(pSysSurface);
}
}
}
*/
return true;
}
| [
"benjamin.barratt@icloud.com"
] | benjamin.barratt@icloud.com |
3f7962ac3c9301242937ed0d1bbff92a2825ab3a | cecfda84e25466259d3ef091953c3ac7b44dc1fc | /UVa Online Judge/volume101/10164 Number Game/in.cpp | 5e2a2d7e536b5d58d4ff48a09c6c5e9eb3a70ee4 | [] | no_license | metaphysis/Code | 8e3c3610484a8b5ca0bb116bc499a064dda55966 | d144f4026872aae45b38562457464497728ae0d6 | refs/heads/master | 2023-07-26T12:44:21.932839 | 2023-07-12T13:39:41 | 2023-07-12T13:39:41 | 53,327,611 | 231 | 57 | null | null | null | null | UTF-8 | C++ | false | false | 483 | cpp | #include <bits/stdc++.h>
using namespace std;
int main(int argc, char *argv[])
{
srand(time(NULL));
int N[10] = {2, 4, 8, 16, 32, 64, 128, 256, 512, 1024};
for (int cases = 1; cases <= 100; cases++)
{
int n = N[rand() % 10];
cout << n << '\n';
for (int i = 0; i < (2 * n - 1); i++)
{
if (i) cout << ' ';
cout << (rand() % 1000 + 1);
}
cout << '\n';
}
cout << "0\n";
return 0;
}
| [
"metaphysis@yeah.net"
] | metaphysis@yeah.net |
30717dd9e6ea146635d4894a103aad3eac0a232c | ed91c77afaeb0e075da38153aa89c6ee8382d3fc | /mediasoup-client/deps/webrtc/src/api/create_peerconnection_factory.h | 4eb0a00e5401c0dcd719526b666359b4ec0726de | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-google-patent-license-webrtc",
"LicenseRef-scancode-google-patent-license-webm",
"MIT"
] | permissive | whatisor/mediasoup-client-android | 37bf1aeaadc8db642cff449a26545bf15da27539 | dc3d812974991d9b94efbc303aa2deb358928546 | refs/heads/master | 2023-04-26T12:24:18.355241 | 2023-01-02T16:55:19 | 2023-01-02T16:55:19 | 243,833,549 | 0 | 0 | MIT | 2020-02-28T18:56:36 | 2020-02-28T18:56:36 | null | UTF-8 | C++ | false | false | 2,136 | h | /*
* Copyright 2018 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef API_CREATE_PEERCONNECTION_FACTORY_H_
#define API_CREATE_PEERCONNECTION_FACTORY_H_
#include <memory>
#include "api/audio/audio_mixer.h"
#include "api/audio_codecs/audio_decoder_factory.h"
#include "api/audio_codecs/audio_encoder_factory.h"
#include "api/peer_connection_interface.h"
#include "api/scoped_refptr.h"
#include "api/video_codecs/video_decoder_factory.h"
#include "api/video_codecs/video_encoder_factory.h"
namespace rtc {
// TODO(bugs.webrtc.org/9987): Move rtc::Thread to api/ or expose a better
// type. At the moment, rtc::Thread is not part of api/ so it cannot be
// included in order to avoid to leak internal types.
class Thread;
} // namespace rtc
namespace webrtc {
class AudioDeviceModule;
class AudioFrameProcessor;
class AudioProcessing;
// Create a new instance of PeerConnectionFactoryInterface with optional video
// codec factories. These video factories represents all video codecs, i.e. no
// extra internal video codecs will be added.
RTC_EXPORT rtc::scoped_refptr<PeerConnectionFactoryInterface>
CreatePeerConnectionFactory(
rtc::Thread* network_thread,
rtc::Thread* worker_thread,
rtc::Thread* signaling_thread,
rtc::scoped_refptr<AudioDeviceModule> default_adm,
rtc::scoped_refptr<AudioEncoderFactory> audio_encoder_factory,
rtc::scoped_refptr<AudioDecoderFactory> audio_decoder_factory,
std::unique_ptr<VideoEncoderFactory> video_encoder_factory,
std::unique_ptr<VideoDecoderFactory> video_decoder_factory,
rtc::scoped_refptr<AudioMixer> audio_mixer,
rtc::scoped_refptr<AudioProcessing> audio_processing,
AudioFrameProcessor* audio_frame_processor = nullptr);
} // namespace webrtc
#endif // API_CREATE_PEERCONNECTION_FACTORY_H_
| [
"wuhaiyang1213@gmail.com"
] | wuhaiyang1213@gmail.com |
e54fd1b8be7e1ee06a87887bbc70286114bcf697 | 4985aad8ecfceca8027709cf488bc2c601443385 | /build/Android/Debug/app/src/main/include/Fuse.Controls.VideoIm-7c15c6f7.h | 9fd07cd2640c4f52f0b623b6161e97e5e16042e4 | [] | no_license | pacol85/Test1 | a9fd874711af67cb6b9559d9a4a0e10037944d89 | c7bb59a1b961bfb40fe320ee44ca67e068f0a827 | refs/heads/master | 2021-01-25T11:39:32.441939 | 2017-06-12T21:48:37 | 2017-06-12T21:48:37 | 93,937,614 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,869 | h | // This file was generated based on '../../AppData/Local/Fusetools/Packages/Fuse.Controls.Video/1.0.2/$.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Controls.VideoIm-aee99c23.h>
#include <Uno.IDisposable.h>
#include <Uno.Int2.h>
#include <Uno.Object.h>
namespace g{namespace Fuse{namespace Controls{namespace VideoImpl{struct GraphicsVideoService;}}}}
namespace g{namespace Uno{namespace Graphics{struct VideoTexture;}}}
namespace g{namespace Uno{namespace UX{struct FileSource;}}}
namespace g{namespace Uno{struct EventArgs;}}
namespace g{namespace Uno{struct Exception;}}
namespace g{
namespace Fuse{
namespace Controls{
namespace VideoImpl{
// internal sealed class GraphicsVideoService :677
// {
struct GraphicsVideoService_type : uType
{
::g::Fuse::Controls::VideoImpl::IVideoService interface0;
::g::Uno::IDisposable interface1;
};
GraphicsVideoService_type* GraphicsVideoService_typeof();
void GraphicsVideoService__ctor__fn(GraphicsVideoService* __this, uObject* callbacks);
void GraphicsVideoService__FuseControlsVideoImplIVideoServiceset_AutoPlay_fn(GraphicsVideoService* __this, bool* value);
void GraphicsVideoService__FuseControlsVideoImplIVideoServiceget_Duration_fn(GraphicsVideoService* __this, double* __retval);
void GraphicsVideoService__FuseControlsVideoImplIVideoServiceset_IsLooping_fn(GraphicsVideoService* __this, bool* value);
void GraphicsVideoService__FuseControlsVideoImplIVideoServiceget_IsValid_fn(GraphicsVideoService* __this, bool* __retval);
void GraphicsVideoService__FuseControlsVideoImplIVideoServiceLoad_fn(GraphicsVideoService* __this, uString* url);
void GraphicsVideoService__FuseControlsVideoImplIVideoServiceLoad1_fn(GraphicsVideoService* __this, ::g::Uno::UX::FileSource* file);
void GraphicsVideoService__FuseControlsVideoImplIVideoServicePause_fn(GraphicsVideoService* __this);
void GraphicsVideoService__FuseControlsVideoImplIVideoServicePlay_fn(GraphicsVideoService* __this);
void GraphicsVideoService__FuseControlsVideoImplIVideoServiceget_Position_fn(GraphicsVideoService* __this, double* __retval);
void GraphicsVideoService__FuseControlsVideoImplIVideoServiceset_Position_fn(GraphicsVideoService* __this, double* value);
void GraphicsVideoService__FuseControlsVideoImplIVideoServiceget_RotationDegrees_fn(GraphicsVideoService* __this, int* __retval);
void GraphicsVideoService__FuseControlsVideoImplIVideoServiceget_Size_fn(GraphicsVideoService* __this, ::g::Uno::Int2* __retval);
void GraphicsVideoService__FuseControlsVideoImplIVideoServiceUnload_fn(GraphicsVideoService* __this);
void GraphicsVideoService__FuseControlsVideoImplIVideoServiceUpdate_fn(GraphicsVideoService* __this);
void GraphicsVideoService__FuseControlsVideoImplIVideoServiceget_VideoTexture_fn(GraphicsVideoService* __this, ::g::Uno::Graphics::VideoTexture** __retval);
void GraphicsVideoService__FuseControlsVideoImplIVideoServiceset_Volume_fn(GraphicsVideoService* __this, float* value);
void GraphicsVideoService__get_IsCompleted_fn(GraphicsVideoService* __this, bool* __retval);
void GraphicsVideoService__New1_fn(uObject* callbacks, GraphicsVideoService** __retval);
void GraphicsVideoService__OnLoaded_fn(GraphicsVideoService* __this, uObject* player);
void GraphicsVideoService__OnLoadingError_fn(GraphicsVideoService* __this, ::g::Uno::Exception* e);
void GraphicsVideoService__OnPlayerError_fn(GraphicsVideoService* __this, uObject* sender, ::g::Uno::Exception* e);
void GraphicsVideoService__OnPlayerFrameAvailable_fn(GraphicsVideoService* __this, uObject* sender, ::g::Uno::EventArgs* args);
void GraphicsVideoService__get_Player_fn(GraphicsVideoService* __this, uObject** __retval);
void GraphicsVideoService__Reset_fn(GraphicsVideoService* __this);
void GraphicsVideoService__SetPlayer_fn(GraphicsVideoService* __this, uObject* player);
void GraphicsVideoService__UnoIDisposableDispose_fn(GraphicsVideoService* __this);
struct GraphicsVideoService : uObject
{
bool _autoPlay;
uStrong<uObject*> _callbacks;
double _durationCache;
uStrong<uObject*> _empty;
bool _isLooping;
uStrong<uObject*> _loading;
uStrong<uObject*> _player;
int _rotationCache;
::g::Uno::Int2 _sizeCache;
float _volume;
static float CompletionTimeThreshold_;
static float& CompletionTimeThreshold() { return GraphicsVideoService_typeof()->Init(), CompletionTimeThreshold_; }
void ctor_(uObject* callbacks);
bool IsCompleted();
void OnLoaded(uObject* player);
void OnLoadingError(::g::Uno::Exception* e);
void OnPlayerError(uObject* sender, ::g::Uno::Exception* e);
void OnPlayerFrameAvailable(uObject* sender, ::g::Uno::EventArgs* args);
uObject* Player();
void Reset();
void SetPlayer(uObject* player);
static GraphicsVideoService* New1(uObject* callbacks);
};
// }
}}}} // ::g::Fuse::Controls::VideoImpl
| [
"newreality64@gmail.com"
] | newreality64@gmail.com |
0ed3c442c1a4f237fa4e53cf1495ce4cece038c6 | ab784073a4924bad0b996234537625b4d3371191 | /src/lightlda/src/lightlda.cpp | d76717324841a3c91644cf2af8358ee53cd6d780 | [
"MIT"
] | permissive | francktcheng/LDA-Benchmark | 8ed257bd87eae25ae0221e3966b580c2b0e66033 | 9b387972c2ae48ef0c6eeb285c61f8ac82c10a94 | refs/heads/master | 2021-01-01T16:37:22.844545 | 2017-07-20T20:15:00 | 2017-07-20T20:15:00 | 97,874,046 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,619 | cpp | #include "common.h"
#include "trainer.h"
#include "alias_table.h"
#include "data_stream.h"
#include "data_block.h"
#include "document.h"
#include "meta.h"
#include "util.h"
#include <vector>
#include <iostream>
#include <multiverso/barrier.h>
#include <multiverso/log.h>
#include <multiverso/row.h>
#ifdef VTUNE_PROF
// to write trigger file for vtune profiling
#include <iostream>
#include <fstream>
using namespace std;
#endif
namespace multiverso { namespace lightlda
{
class LightLDA
{
public:
static void Run(int argc, char** argv)
{
Config::Init(argc, argv);
AliasTable* alias_table = new AliasTable();
Barrier* barrier = new Barrier(Config::num_local_workers);
meta.Init();
std::vector<TrainerBase*> trainers;
for (int32_t i = 0; i < Config::num_local_workers; ++i)
{
Trainer* trainer = new Trainer(alias_table, barrier, &meta);
trainers.push_back(trainer);
}
ParamLoader* param_loader = new ParamLoader();
multiverso::Config config;
config.num_servers = Config::num_servers;
config.num_aggregator = Config::num_aggregator;
config.server_endpoint_file = Config::server_file;
Multiverso::Init(trainers, param_loader, config, &argc, &argv);
Log::ResetLogFile("LightLDA."
+ std::to_string(clock()) + ".log");
data_stream = CreateDataStream();
InitMultiverso();
Train();
Multiverso::Close();
for (auto& trainer : trainers)
{
delete trainer;
}
delete param_loader;
//DumpDocTopic();
delete data_stream;
delete barrier;
delete alias_table;
}
private:
static void Train()
{
#ifdef VTUNE_PROF
//write trigger file to disk and enable vtune
ofstream vtune_trigger;
vtune_trigger.open("vtune-flag.txt");
vtune_trigger << "Start training process and trigger vtune profiling.\n";
vtune_trigger.close();
#endif
Multiverso::BeginTrain();
for (int32_t i = 0; i < Config::num_iterations; ++i)
{
Multiverso::BeginClock();
// Train corpus block by block
for (int32_t block = 0; block < Config::num_blocks; ++block)
{
data_stream->BeforeDataAccess();
DataBlock& data_block = data_stream->CurrDataBlock();
data_block.set_meta(&meta.local_vocab(block));
int32_t num_slice = meta.local_vocab(block).num_slice();
Log::Info("num_slice:%d, num_block:%d\n", num_slice, Config::num_blocks);
std::vector<LDADataBlock> data(num_slice);
// Train datablock slice by slice
for (int32_t slice = 0; slice < num_slice; ++slice)
{
LDADataBlock* lda_block = &data[slice];
lda_block->set_data(&data_block);
lda_block->set_iteration(i);
lda_block->set_block(block);
lda_block->set_slice(slice);
Multiverso::PushDataBlock(lda_block);
}
Multiverso::Wait();
data_stream->EndDataAccess();
}
Multiverso::EndClock();
}
Multiverso::EndTrain();
}
static void InitMultiverso()
{
Multiverso::BeginConfig();
CreateTable();
ConfigTable();
Initialize();
Multiverso::EndConfig();
}
static void Initialize()
{
xorshift_rng rng;
for (int32_t block = 0; block < Config::num_blocks; ++block)
{
data_stream->BeforeDataAccess();
DataBlock& data_block = data_stream->CurrDataBlock();
int32_t num_slice = meta.local_vocab(block).num_slice();
for (int32_t slice = 0; slice < num_slice; ++slice)
{
for (int32_t i = 0; i < data_block.Size(); ++i)
{
Document* doc = data_block.GetOneDoc(i);
int32_t& cursor = doc->Cursor();
if (slice == 0) cursor = 0;
int32_t last_word = meta.local_vocab(block).LastWord(slice);
for (; cursor < doc->Size(); ++cursor)
{
if (doc->Word(cursor) > last_word) break;
// Init the latent variable
if (!Config::warm_start)
doc->SetTopic(cursor, rng.rand_k(Config::num_topics));
// Init the server table
Multiverso::AddToServer<int32_t>(kWordTopicTable,
doc->Word(cursor), doc->Topic(cursor), 1);
Multiverso::AddToServer<int64_t>(kSummaryRow,
0, doc->Topic(cursor), 1);
}
}
Multiverso::Flush();
}
data_stream->EndDataAccess();
}
}
static void DumpDocTopic()
{
Row<int32_t> doc_topic_counter(0, Format::Sparse, kMaxDocLength);
for (int32_t block = 0; block < Config::num_blocks; ++block)
{
std::ofstream fout("doc_topic." + std::to_string(block));
data_stream->BeforeDataAccess();
DataBlock& data_block = data_stream->CurrDataBlock();
for (int i = 0; i < data_block.Size(); ++i)
{
Document* doc = data_block.GetOneDoc(i);
doc_topic_counter.Clear();
doc->GetDocTopicVector(doc_topic_counter);
fout << i << " "; // doc id
Row<int32_t>::iterator iter = doc_topic_counter.Iterator();
while (iter.HasNext())
{
fout << " " << iter.Key() << ":" << iter.Value();
iter.Next();
}
fout << std::endl;
}
data_stream->EndDataAccess();
}
}
static void CreateTable()
{
int32_t num_vocabs = Config::num_vocabs;
int32_t num_topics = Config::num_topics;
Type int_type = Type::Int;
Type longlong_type = Type::LongLong;
multiverso::Format dense_format = multiverso::Format::Dense;
multiverso::Format sparse_format = multiverso::Format::Sparse;
Multiverso::AddServerTable(kWordTopicTable, num_vocabs,
num_topics, int_type, dense_format);
Multiverso::AddCacheTable(kWordTopicTable, num_vocabs,
num_topics, int_type, dense_format, Config::model_capacity);
Multiverso::AddAggregatorTable(kWordTopicTable, num_vocabs,
num_topics, int_type, dense_format, Config::delta_capacity);
Multiverso::AddTable(kSummaryRow, 1, Config::num_topics,
longlong_type, dense_format);
}
static void ConfigTable()
{
multiverso::Format dense_format = multiverso::Format::Dense;
multiverso::Format sparse_format = multiverso::Format::Sparse;
for (int32_t word = 0; word < Config::num_vocabs; ++word)
{
if (meta.tf(word) > 0)
{
if (meta.tf(word) * kLoadFactor > Config::num_topics)
{
Multiverso::SetServerRow(kWordTopicTable,
word, dense_format, Config::num_topics);
Multiverso::SetCacheRow(kWordTopicTable,
word, dense_format, Config::num_topics);
}
else
{
Multiverso::SetServerRow(kWordTopicTable,
word, sparse_format, meta.tf(word) * kLoadFactor);
Multiverso::SetCacheRow(kWordTopicTable,
word, sparse_format, meta.tf(word) * kLoadFactor);
}
}
if (meta.local_tf(word) > 0)
{
if (meta.local_tf(word) * 2 * kLoadFactor > Config::num_topics)
Multiverso::SetAggregatorRow(kWordTopicTable,
word, dense_format, Config::num_topics);
else
Multiverso::SetAggregatorRow(kWordTopicTable, word,
sparse_format, meta.local_tf(word) * 2 * kLoadFactor);
}
}
}
private:
/*! \brief training data access */
static IDataStream* data_stream;
/*! \brief training data meta information */
static Meta meta;
};
IDataStream* LightLDA::data_stream = nullptr;
Meta LightLDA::meta;
} // namespace lightlda
} // namespace multiverso
int main(int argc, char** argv)
{
multiverso::lightlda::LightLDA::Run(argc, argv);
return 0;
}
| [
"pengb@indiana.edu"
] | pengb@indiana.edu |
d862965e3c0095e308a06129cb21c55bee71461d | c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64 | /Engine/Source/ThirdParty/HairWorks/Nv/Common/Platform/Win/NvCoWinMemoryAllocator.h | 5e3079cc313f3f9a190f696feee703bb682556e7 | [
"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 | 1,614 | h | /* Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
* NVIDIA CORPORATION and its licensors retain all intellectual property
* and proprietary rights in and to this software, related documentation
* and any modifications thereto. Any use, reproduction, disclosure or
* distribution of this software and related documentation without an express
* license agreement from NVIDIA CORPORATION is strictly prohibited. */
#ifndef NV_CO_WIN_MEMORY_ALLOCATOR_H
#define NV_CO_WIN_MEMORY_ALLOCATOR_H
#include <Nv/Common/NvCoCommon.h>
#include <Nv/Common/NvCoMemoryAllocator.h>
/** \addtogroup common
@{
*/
namespace nvidia {
namespace Common {
/// Windows implementation of memory allocator
class WinMemoryAllocator: public MemoryAllocator
{
public:
virtual ~WinMemoryAllocator() {}
void* simpleAllocate(SizeT size) NV_OVERRIDE;
void simpleDeallocate(const void* pointer) NV_OVERRIDE;
void* allocate(SizeT size) NV_OVERRIDE;
void deallocate(const void* ptr, SizeT size) NV_OVERRIDE;
void* reallocate(void* ptr, SizeT oldSize, SizeT oldUsed, SizeT newSize) NV_OVERRIDE;
void* alignedAllocate(SizeT size, SizeT align) NV_OVERRIDE;
void alignedDeallocate(const void* ptr, SizeT align, SizeT size) NV_OVERRIDE;
void* alignedReallocate(void* ptr, SizeT align, SizeT oldSize, SizeT oldUsed, SizeT newSize) NV_OVERRIDE;
/// Get the singleton
NV_FORCE_INLINE static WinMemoryAllocator* getSingleton() { return &s_singleton; }
private:
static WinMemoryAllocator s_singleton;
WinMemoryAllocator() {}
};
} // namespace Common
} // namespace nvidia
/** @} */
#endif // NV_CO_WIN_MEMORY_ALLOCATOR_H | [
"tungnt.rec@gmail.com"
] | tungnt.rec@gmail.com |
b2d997d3b282f0b50b4a51656d4562edf3e92a11 | 3148c2786d41c6dbaae788c698839b37d5fbef07 | /leetcode_cc/207.course-schedule.cc | 3b3ff50a78830f9f8d1c420de33799486520fec6 | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | fuhailin/show-me-cpp-code | 97b5b5ee8b05cfcb8204c7d4c948aa14a5decbdf | 40b41451bc7218c82c975a9feb65f8cc340446e7 | refs/heads/master | 2022-05-16T13:56:04.156171 | 2022-03-20T10:46:09 | 2022-03-20T10:46:09 | 128,388,041 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,225 | cc | #include <iostream>
#include <queue>
#include <vector>
using namespace std;
class Solution {
public:
bool
canFinish(int numCourses, vector<vector<int>>& prerequisites)
{
vector<int> res;
vector<vector<int>> graph; // 邻接表存储有向图
vector<int> indegree(numCourses); // 计算各节点的入度
graph.resize(numCourses);
for (auto& edge : prerequisites) {
graph[edge[1]].push_back(edge[0]);
indegree[edge[0]]++;
}
queue<int> que;
for (int i = 0; i < numCourses; i++) {
if(indegree[i] == 0) {
que.push(i);
}
}
while (!que.empty()) {
int root = que.front();
res.push_back(root);
que.pop();
for(int node : graph[root]) {
indegree[node]--;
if(indegree[node] == 0) {
que.push(node);
}
}
}
return res.size() == numCourses;
}
};
int main(int argc, const char** argv)
{
Solution so;
vector<vector<int>> test = {
{ 1, 0 },
{ 0, 1 }
};
bool res = so.canFinish(2, test);
return 0;
} | [
"hailinfufu@outlook.com"
] | hailinfufu@outlook.com |
4db62cb277ac3cbed5eb5da129ea57ddb13e8b2b | 965d7baa952d30cb3058e013c94db5de3040a66d | /Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/PawleyFit.h | 455df893d86d5afafc4a473e538a13125d3b0cff | [] | no_license | quantumsteve/mantid | dd96eda1838247e711e74e6ee3aa440198e0d85a | ac0262a566a4648220d7d9d988cbec12d1ef8d46 | refs/heads/master | 2020-12-27T15:29:55.820641 | 2015-05-26T13:37:26 | 2015-05-26T13:37:26 | 36,074,468 | 0 | 0 | null | 2015-05-22T13:45:48 | 2015-05-22T13:45:48 | null | UTF-8 | C++ | false | false | 3,463 | h | #ifndef MANTID_CURVEFITTING_PAWLEYFIT_H_
#define MANTID_CURVEFITTING_PAWLEYFIT_H_
#include "MantidKernel/System.h"
#include "MantidAPI/Algorithm.h"
#include "MantidCurveFitting/PawleyFunction.h"
#include "MantidKernel/Unit.h"
namespace Mantid {
namespace CurveFitting {
/** @class V3DFromHKLColumnExtractor
Small helper class to extract HKLs as V3D from table columns. The table
column can either store V3D directly, or a string with various separators:
, ; [ ] (space)
*/
struct DLLExport V3DFromHKLColumnExtractor {
Kernel::V3D operator()(const API::Column_const_sptr &hklColumn,
size_t i) const;
protected:
Kernel::V3D getHKLFromV3DColumn(const API::Column_const_sptr &hklColumn,
size_t i) const;
Kernel::V3D getHKLFromStringColumn(const API::Column_const_sptr &hklColumn,
size_t i) const;
Kernel::V3D getHKLFromString(const std::string &hklString) const;
};
/** @class PawleyFit
This algorithm uses the Pawley-method to refine lattice parameters using a
powder diffractogram and a list of unique Miller indices. From the initial
lattice parameters, theoretical reflection positions are calculated. Each
reflection is described by the peak profile function supplied by the user and
all parameters except the one for location of the reflection are freely
refined. Available lattice parameters depend on the selected crystal system.
@author Michael Wedel, Paul Scherrer Institut - SINQ
@date 15/03/2015
Copyright © 2015 PSI-NXMM
This file is part of Mantid.
Mantid 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 3 of the License, or
(at your option) any later version.
Mantid is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
File change history is stored at: <https://github.com/mantidproject/mantid>
Code Documentation is available at: <http://doxygen.mantidproject.org>
*/
class DLLExport PawleyFit : public API::Algorithm {
public:
PawleyFit();
virtual ~PawleyFit() {}
const std::string name() const { return "PawleyFit"; }
int version() const { return 1; }
const std::string summary() const;
const std::string category() const { return "Diffraction"; }
protected:
double getTransformedCenter(double d, const Kernel::Unit_sptr &unit) const;
void addHKLsToFunction(PawleyFunction_sptr &pawleyFn,
const API::ITableWorkspace_sptr &tableWs,
const Kernel::Unit_sptr &unit, double startX,
double endX) const;
API::ITableWorkspace_sptr
getLatticeFromFunction(const PawleyFunction_sptr &pawleyFn) const;
API::ITableWorkspace_sptr
getPeakParametersFromFunction(const PawleyFunction_sptr &pawleyFn) const;
API::IFunction_sptr
getCompositeFunction(const PawleyFunction_sptr &pawleyFn) const;
void init();
void exec();
Kernel::Unit_sptr m_dUnit;
};
} // namespace CurveFitting
} // namespace Mantid
#endif /* MANTID_CURVEFITTING_PAWLEYFIT_H_ */
| [
"michael.wedel@psi.ch"
] | michael.wedel@psi.ch |
2b5134f1ffad3ce2cb13f8545b9b65a4297dd569 | d543bd6e66eebbef9f9f8df69f5eb1143b1b280c | /VirtualHDDManager/VHMScript.h | 761dbacf63cbf6727637d8cd09e8f164d43df219 | [] | no_license | byeongkeunahn/VirtualHDDManager | de9218558abcf1fc46eabc762cdf5b23790d849c | 4ad4188dfc7f907930b536ac1b3781ef9ab549d5 | refs/heads/master | 2021-01-22T22:57:23.530769 | 2017-03-20T15:19:00 | 2017-03-20T15:19:00 | 85,592,679 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 2,986 | h |
#pragma once
#define VHM_SCRIPT_SIZE_MAX (1048576)
FWDDEF_HANDLE(LIST_HANDLE);
class CVHMRoot;
class CVHMScript
{
public:
CVHMScript();
virtual ~CVHMScript();
int SetVHMRoot(CVHMRoot *pVHMRoot);
CVHMRoot *GetVHMRoot();
// 스크립트 로드
int LoadScript(LPCTSTR lpszScriptFile);
int LoadScript(BYTE *pScript, size_t szScript);
int UnloadScript();
int ExecuteScript(LPCTSTR lpszScriptFile);
protected:
/* 스크립트에서 명령과 레이블을 추출 */
int ParseScript();
// ParseScript 내부 구현
/* 추출된 명령을 실행 직전 포맷으로 변환 */
int ConvertCommand(const WCHAR *pwszData, size_t ccData, WCHAR *pwszOutput, size_t *pccOutput);
int ParseAndExecuteCommand(const WCHAR * pwszData, size_t ccData, size_t * pccProcessed, CVHMRoot * pVHMRoot);
int SkipUnwantedCharacter(const WCHAR * pwszData, size_t ccData, size_t * pccProcessed);
int SkipLine(const WCHAR * pwszData, size_t ccData, size_t * pccProcessed);
int SkipUntilCharacter(const WCHAR * pwszData, size_t ccData, WCHAR wszChar, size_t * pccProcessed);
int GetCommandLength(const WCHAR * pwszData, size_t ccData, size_t * pccLength);
int GetCommandWordCount(const WCHAR * pwszData, size_t ccLength, size_t * pccCommand);
int SplitCommand(const WCHAR * pwszData, size_t ccLength, size_t ccCommand, LPCWCHAR * ppwszCommandArray, size_t * pccLengthArray);
int ExecuteCommand(size_t ccCommand, LPCWCHAR * ppwszCommandArray, size_t * pccLengthArray, CVHMRoot * pVHMRoot);
protected:
/* 유니코드로 변환 (BOM 없는 형태로) */
int ConvertToUnicode(const void *pInput, size_t szInput, void *pOutput, size_t *pszOutput);
// ConvertToUnicode 내부 구현
int ConvAnsiToUnicode(const void *pInput, size_t szInput, void *pOutput, size_t *pszOutput);
int ConvUtf8ToUnicode(const void *pInput, size_t szInput, void *pOutput, size_t *pszOutput);
int ConvU16BToUnicode(const void *pInput, size_t szInput, void *pOutput, size_t *pszOutput);
int ConvU16LToUnicode(const void *pInput, size_t szInput, void *pOutput, size_t *pszOutput);
int ConvU32BToUnicode(const void *pInput, size_t szInput, void *pOutput, size_t *pszOutput);
int ConvU32LToUnicode(const void *pInput, size_t szInput, void *pOutput, size_t *pszOutput);
protected:
/* 내부 데이터 저장소 관리 */
// 저장소 생성 및 파괴
int InitializeInternalStorage();
int DestroyInternalStorage();
BOOL IsInternalStorageInitialized();
int EmptyInternalStorage();
// 저장소 항목 삽입 및 삭제
protected:
/**** 내부 변수 ****
* NOTE: NULL으로 포인터의 유효성을 나타냄
*/
BYTE *m_pScript; // 스크립트를 통째로 읽어들인 형태
size_t m_szScript;
BOOL m_bInternalStorageInitialized;
LIST_HANDLE m_plCommand;
LIST_HANDLE m_plLabel;
LIST_HANDLE m_plError;
CVHMRoot *m_pVHMRoot;
};
| [
"7p54ks3@naver.com"
] | 7p54ks3@naver.com |
15121d21d7a751032b16bfa222266605b2ce10d3 | 1a7698d1703d453e198fdb00b2a537e4bc9e269d | /compiler_old/cVarAddrNode.h | d78e138bf418bf29dead4a4decf5bb2cf478093f | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | philip-w-howard/stackl | bebb3526c1f666a6bbab41d0f7c51947da2529ab | 180349fedc612c99f8cdf94756c628f6e228b654 | refs/heads/master | 2023-04-27T19:25:12.372749 | 2023-04-14T18:59:49 | 2023-04-14T18:59:49 | 32,224,130 | 12 | 5 | MIT | 2023-04-20T01:13:56 | 2015-03-14T17:41:55 | C++ | UTF-8 | C++ | false | false | 1,270 | h | #pragma once
#include <string>
#include <list>
using std::list;
#include "cAstNode.h"
#include "cExprNode.h"
#include "cAstList.h"
#include "cStructDeclNode.h"
#include "cArrayValNode.h"
#include "cVarDeclNode.h"
#include "cSymbolTable.h"
#include "cVarPartNode.h"
#include "parse.h"
#include "codegen.h"
class cVarAddrNode : public cExprNode
{
public:
cVarAddrNode(cVarRefNode *var)
{
mOffset = 0;
mVar = var;
}
cDeclNode *GetType()
{
return mVar->GetType();
}
virtual int ComputeOffsets(int base)
{
mVar->ComputeOffsets(base);
mOffset = mVar->GetOffset();
return base;
}
virtual std::string toString()
{
std::string result = "&";
result += mVar->toString();
return result;
}
virtual void GenerateCode()
{
if (mVar->IsGlobal())
{
EmitInt(PUSH_OP);
EmitGlobalRef(mVar->Name());
EmitInt(PUSH_OP);
EmitInt(mOffset);
EmitInt(PLUS_OP);
} else {
EmitInt(PUSH_OP);
EmitInt(mOffset);
EmitInt(PUSHFP_OP);
EmitInt(PLUS_OP);
}
}
protected:
cVarRefNode *mVar;
int mOffset;
};
| [
"phil.howard@oit.edu"
] | phil.howard@oit.edu |
63549c46c1ef79863a4b518ffa7d05975e02e2f6 | f931479b6c8a4dd6407f0fa026da020c6028d0ba | /include/asio_include_dir/asio/detail/posix_mutex.hpp | 7447f7207399d0888b525bb726975d1bf1bfb68a | [] | no_license | STORCH-paul/storch_project_1 | 84e21bbeade24032568d716d727b8f0be63c08df | 19b19c46ff69dbcca72f0dbff294f452c5f15ab2 | refs/heads/master | 2023-02-10T14:23:21.874924 | 2021-01-10T20:25:36 | 2021-01-10T20:25:36 | 319,001,696 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,657 | hpp | //
// detail/posix_mutex.hpp
// ~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_DETAIL_POSIX_MUTEX_HPP
#define ASIO_DETAIL_POSIX_MUTEX_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio_include_dir/asio/detail/config.hpp"
#if defined(ASIO_HAS_PTHREADS)
#include <pthread.h>
#include "asio_include_dir/asio/detail/noncopyable.hpp"
#include "asio_include_dir/asio/detail/scoped_lock.hpp"
#include "asio_include_dir/asio/detail/push_options.hpp"
namespace asio {
namespace detail {
class posix_event;
class posix_mutex
: private noncopyable
{
public:
typedef asio::detail::scoped_lock<posix_mutex> scoped_lock;
// Constructor.
ASIO_DECL posix_mutex();
// Destructor.
~posix_mutex()
{
::pthread_mutex_destroy(&mutex_); // Ignore EBUSY.
}
// Lock the mutex.
void lock()
{
(void)::pthread_mutex_lock(&mutex_); // Ignore EINVAL.
}
// Unlock the mutex.
void unlock()
{
(void)::pthread_mutex_unlock(&mutex_); // Ignore EINVAL.
}
private:
friend class posix_event;
::pthread_mutex_t mutex_;
};
} // namespace detail
} // namespace asio
#include "asio_include_dir/asio/detail/pop_options.hpp"
#if defined(ASIO_HEADER_ONLY)
# include "asio_include_dir/asio/detail/impl/posix_mutex.ipp"
#endif // defined(ASIO_HEADER_ONLY)
#endif // defined(ASIO_HAS_PTHREADS)
#endif // ASIO_DETAIL_POSIX_MUTEX_HPP
| [
"sto.paul14@gmail.com"
] | sto.paul14@gmail.com |
3fefdff92125ab64bd2e6187fd9556b81e1f0951 | 0fd10b0d148def985ab2e437678ef3498488b05d | /GrauphTest/SmartRouting.cpp | ecc06451815fb43dfaf7c1621d9b26c6911626ef | [] | no_license | wlzkstlz/SmartRouting | 4e7c1add65a74dfc5f0474f47cf0ca6bcff571f3 | 00ddb17fa73ce8384532e109705511af23d85581 | refs/heads/master | 2021-01-12T10:50:17.566912 | 2016-11-06T15:23:08 | 2016-11-06T15:23:08 | 72,728,115 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 18,614 | cpp | #include"SmartRouting.h"
#include"commonAlg.h"
#include"iostream"
using namespace std;
#define MAX_ROOM_NUM 25//支持最大房间数目
#define REGION_ROOM_VALUE_STEP (255/MAX_ROOM_NUM)
#define CORNER_SEARCH_RANGE (4*ROOM_BORDER_PANT_WIDTH)
#define CORNER_CLUSTER_RANGE (4*ROOM_BORDER_PANT_WIDTH)
#define MAIN_TUBE_DISCRETE_STEP 2.0
#define INT_INFINITY 1000000
#define DIST_THRESHOLD_BETWEEN_ROOMS_KN (ROOM_BORDER_PANT_WIDTH*8.0)//不同房间节点被认为可以直接穿墙连接的距离阈值
#define DIST_THRESHOLD_CLOSE_TO_MAIN_TUBE (ROOM_BORDER_PANT_WIDTH*8.0)//认为空调与主管同贴一堵墙的距离阈值
CSmartRouting::CSmartRouting()
{
}
CSmartRouting::~CSmartRouting()
{
if (mConnectiveMatrix)
{
for (size_t i = 0; i < mKeyNodes.size(); i++)
if (mConnectiveMatrix[i])
delete mConnectiveMatrix[i];
delete mConnectiveMatrix;
}
}
void CSmartRouting::ReadSourceImg(const char*file_name)
{
mSourceMat = imread(file_name);
mMat4Draw = Mat::zeros(mSourceMat.size(), CV_8UC1);
}
void CSmartRouting::RecognizeRooms()
{
//【1】draw mBorderUIPts
mMat4Draw.setTo(Scalar::all(255));
for (size_t i = 0; i < mBorderUIPts.size(); i++)
for (size_t j=1;j<mBorderUIPts[i].size();j++)
line(mMat4Draw, mBorderUIPts[i][j-1], mBorderUIPts[i][j], Scalar::all(0), ROOM_BORDER_PANT_WIDTH);
/*4SHOW*/
{
namedWindow("RecognizeRooms", CV_WINDOW_FREERATIO);
imshow("RecognizeRooms", mMat4Draw);
waitKey(-1);
}
/*4SHOW END*/
//【2】findContour
vector<vector<cv::Point>>contours;
vector<cv::Vec4i>h;
findContours(mMat4Draw.clone(), contours, h, CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE);
for (size_t i = 0; i < contours.size(); i++)
{
if (h[i][3]<0)//区域外轮廓
{
mMat4Draw.setTo(Scalar::all(0));
drawContours(mMat4Draw, contours, i, Scalar::all(255), -1);
int child_id = h[i][2];
while (child_id >= 0)
{
drawContours(mMat4Draw, contours, child_id, Scalar::all(0), -1);
child_id = h[child_id][0];
}
mRoomContours.push_back(contours[i]);
Mat region = mMat4Draw.clone();
mRoomRegions.push_back(region);
mACLocationsFromUI.push_back(Point(-1, -1));//initialize into undefined!
}
}
int max_id = -1;
double max_area = 0;
for (size_t i=0;i<mRoomContours.size();i++)
{
double area = contourArea(mRoomContours[i]);
if (area>max_area)
{
max_area = area;
max_id = i;
}
}
//【3】将最外轮廓放到最后
vector<Point> temp_contour = mRoomContours[max_id];
mRoomContours[max_id] = mRoomContours.back();
mRoomContours.back() = temp_contour;
Mat temp_region = mRoomRegions[max_id];
mRoomRegions[max_id] = mRoomRegions.back();
mRoomRegions.back() = temp_region;
}
void CSmartRouting::RecognizeCorners()
{
/*4SHOW*/
{
namedWindow("RecognizeCorners", CV_WINDOW_FREERATIO);
}
/*4SHOW END*/
for (size_t i = 0; i < mRoomContours.size()-1; i++)//【遍历每个房间】
{
bool*is_corner_like = new bool[mRoomContours[i].size()];//可能的墙角点数组
for (size_t j = 0; j < mRoomContours[i].size(); j++)//【遍历房间的每一个外轮廓点,生成可能的墙角点数组】
{
is_corner_like[j] = false;//init
vector<int>region_types;
for (int m = -CORNER_SEARCH_RANGE; m <= CORNER_SEARCH_RANGE; m++)
{
for (int n = -CORNER_SEARCH_RANGE; n <= CORNER_SEARCH_RANGE; n++)
{
int xx = mRoomContours[i][j].x +n;
int yy = mRoomContours[i][j].y+ m;
for (int k=0;k<mRoomRegions.size();k++)
{
uchar*data = (mRoomRegions[k]).ptr<uchar>(yy);
if (data[xx]>127)
{
bool is_new = true;
for (int q=0;q<region_types.size();q++)
if (region_types[q] == k)
is_new = false;
if (is_new)
region_types.push_back(int(k));
}
}
}
}
if (region_types.size()>=3)
is_corner_like[j] = true;
}
vector<Point3f>corner_centres;
for (size_t j=0;j<mRoomContours[i].size();j++)
{
if (is_corner_like[j])
{
int belong_to = -1;
for (size_t k = 0; k < corner_centres.size(); k++)
{
if (sqrt(pow(corner_centres[k].x - mRoomContours[i][j].x, 2) + pow(corner_centres[k].y - mRoomContours[i][j].y, 2)) < CORNER_CLUSTER_RANGE)
{
belong_to = k;
break;
}
}
if (belong_to == -1)
{
corner_centres.push_back(Point3f(mRoomContours[i][j].x, mRoomContours[i][j].y, 1.0));
continue;
}
double w1 = ((double)corner_centres[belong_to].z / (double)(corner_centres[belong_to].z + 1.0));
double w2 = 1.0 - w1;
double zz = corner_centres[belong_to].z + 1.0;
corner_centres[belong_to] = corner_centres[belong_to] * w1 + Point3f(mRoomContours[i][j].x, mRoomContours[i][j].y, 1.0)*w2;
corner_centres[belong_to].z = zz;
}
}
for (size_t s=0;s<corner_centres.size();s++)//【生成角点】
{
TKeyNode key_node;
int min_id = -1;
double min_dist = 100000.0;
for (size_t j=0;j< mRoomContours[i].size(); j++)
{
double distance = sqrt(pow(corner_centres[s].x- mRoomContours[i][j].x,2) + pow(corner_centres[s].y - mRoomContours[i][j].y, 2));
if (distance<min_dist)
{
min_dist = distance;
min_id = j;
}
}
key_node.location = mRoomContours[i][min_id];
key_node.room_id = i;
key_node.contour_id = min_id;
key_node.type = KNT_CORNER;
key_node.node_id = mKeyNodes.size();
mKeyNodes.push_back(key_node);
}
delete is_corner_like;
}
/*4SHOW*/
{
Mat mat4show = mSourceMat.clone();
mat4show.setTo(Scalar::all(0));
drawContours(mat4show, mRoomContours, -1, Scalar(0, 255, 0));
for (size_t k = 0; k < mKeyNodes.size(); k++)
{
circle(mat4show, mKeyNodes[k].location, 4, Scalar(0, 0, 255), 1);
}
imshow("RecognizeCorners", mat4show);
imwrite("RecognizeCorners.bmp", mat4show);
waitKey(-1);
cvtColor(mat4show, mMat4Draw, CV_BGR2GRAY);
//mMat4Draw = mat4show;
}
/*4SHOW END*/
}
void CSmartRouting::RecognizeMainTubeEnds()
{
//【1】离散主管道点列
for (size_t i = 1; i < mMainTubeUIPts.size(); i++)
{
mMainTubeDiscretePts.push_back(mMainTubeUIPts[i - 1]);
double angel = CCommonAlg::calcVectAngel((double)(mMainTubeUIPts[i].x - mMainTubeUIPts[i - 1].x), (double)(mMainTubeUIPts[i].y - mMainTubeUIPts[i - 1].y));
double distance = sqrt(pow(mMainTubeUIPts[i].x - mMainTubeUIPts[i - 1].x, 2) + pow(mMainTubeUIPts[i].y - mMainTubeUIPts[i - 1].y, 2));
double temp = MAIN_TUBE_DISCRETE_STEP;
for (; temp < distance; temp += MAIN_TUBE_DISCRETE_STEP)
{
Point pt = mMainTubeUIPts[i - 1];
pt.x += temp*cos(angel);
pt.y += temp*sin(angel);
mMainTubeDiscretePts.push_back(pt);
}
}
//【2】判断离散点是否处于墙上
Mat mat4draw = mMat4Draw.clone();
mat4draw.setTo(Scalar(0));
for (size_t i = 0; i < mBorderUIPts.size(); i++)
for (size_t j = 1; j < mBorderUIPts[i].size(); j++)
line(mat4draw, mBorderUIPts[i][j - 1], mBorderUIPts[i][j], Scalar(255), ROOM_BORDER_PANT_WIDTH);
vector<bool>is_wall_pts;
is_wall_pts.reserve(mMainTubeDiscretePts.size());
for (size_t i = 0; i < mMainTubeDiscretePts.size(); i++)
{
uchar*data = mat4draw.ptr<uchar>(mMainTubeDiscretePts[i].y);
is_wall_pts.push_back((bool)(data[mMainTubeDiscretePts[i].x]>127));
}
//【3】找出端点
bool pre_on_wall = false;
vector<bool>is_end_pts;
is_end_pts.reserve(mMainTubeDiscretePts.size());
for (size_t i = 0; i<is_wall_pts.size(); i++)
{
bool is_end_pt = false;
if (is_wall_pts[i]!= pre_on_wall)
{
pre_on_wall = is_wall_pts[i];
is_end_pt = true;
}
is_end_pts.push_back(is_end_pt);
}
//【4】生成TKeyNode
for (size_t i = 0; i < is_end_pts.size(); i++)
{
if (is_end_pts[i])
{
int room_id = -1;
int contour_id = -1;
double min_dist = 100000.0;
for (size_t j = 0; j < mRoomContours.size()-1; j++)
{
for (size_t k = 0; k < mRoomContours[j].size(); k++)
{
double dist = sqrt(pow(mRoomContours[j][k].x- mMainTubeDiscretePts[i].x,2) + pow(mRoomContours[j][k].y - mMainTubeDiscretePts[i].y, 2));
if (dist<min_dist)
{
min_dist = dist;
room_id = j;
contour_id = k;
}
}
}
if (room_id>=0)
{
TKeyNode key_node;
key_node.location = mRoomContours[room_id][contour_id];
key_node.room_id = room_id;
key_node.contour_id = contour_id;
key_node.main_tube_discrete_id = i;
key_node.type = KeyNodeType::KNT_MAIN_TUBE_END;
key_node.node_id = mKeyNodes.size();
mKeyNodes.push_back(key_node);
}
}
}
/*4SHOW*/
{
namedWindow("RecognizeMainTubeEnds", CV_WINDOW_FREERATIO);
Mat mat4show_color = Mat::zeros(mat4draw.size(), CV_8UC3);
cvtColor(mat4draw, mat4show_color, CV_GRAY2BGR);
for (size_t i = 0; i < mMainTubeDiscretePts.size(); i++)
circle(mat4show_color, mMainTubeDiscretePts[i], 1, Scalar(0, 255, 0));
for (size_t i = 0; i < mKeyNodes.size(); i++)
if (mKeyNodes[i].type== KeyNodeType::KNT_MAIN_TUBE_END)
circle(mat4show_color, mKeyNodes[i].location, 2, Scalar(0, 0, 255));
imshow("RecognizeMainTubeEnds", mat4show_color);
imwrite("RecognizeMainTubeEnds.bmp", mat4show_color);
waitKey(-1);
}
/*4SHOW END*/
}
void CSmartRouting::RecognizeACLocation()
{
for (size_t i = 0; i < mACLocationsFromUI.size()-1; i++)
{
if (mACLocationsFromUI[i].x >= 0 && mACLocationsFromUI[i].y >= 0)
{
int contour_id = -1;
double min_dist = 100000.0;
for (size_t j = 0; j < mRoomContours[i].size(); j++)
{
double dist = sqrt(pow(mRoomContours[i][j].x- mACLocationsFromUI[i].x,2)+pow(mRoomContours[i][j].y - mACLocationsFromUI[i].y, 2));
if (dist<min_dist)
{
min_dist = dist;
contour_id = j;
}
}
if (contour_id>=0)
{
TKeyNode key_node;
key_node.location = mRoomContours[i][contour_id];
key_node.room_id = i;
key_node.contour_id = contour_id;
key_node.type = KeyNodeType::KNT_AC;
key_node.node_id = mKeyNodes.size();
mKeyNodes.push_back(key_node);
}
}
}
}
void CSmartRouting::CheckIsCloseToMainTube()
{
for (size_t i = 0; i < mKeyNodes.size(); i++)
{
if (mKeyNodes[i].type== KeyNodeType::KNT_AC)
{
int min_id = -1;
double min_dist = 1000000.0;
for (size_t j = 0; j < mMainTubeDiscretePts.size(); j++)
{
double distance = sqrt(pow(mMainTubeDiscretePts[j].x-mKeyNodes[i].location.x,2)+
pow(mMainTubeDiscretePts[j].y - mKeyNodes[i].location.y, 2));
if (distance<min_dist)
{
min_dist = distance;
min_id = j;
}
}
if (min_dist<DIST_THRESHOLD_CLOSE_TO_MAIN_TUBE)
mKeyNodes[i].close_to_maintube_id = min_id;
}
}
}
void CSmartRouting::ShowResult()
{
namedWindow("ShowResult", CV_WINDOW_FREERATIO);
Mat mat4show_color = Mat::zeros(mMat4Draw.size(), CV_8UC3);
//1.画房间区域
for (size_t i = 0; i < mRoomRegions.size(); i++)
mat4show_color.setTo(Scalar::all(127), mRoomRegions[i]);
//2.画描边线条
for (size_t i = 0; i < mBorderUIPts.size(); i++)
for (size_t j = 1; j < mBorderUIPts[i].size(); j++)
line(mat4show_color, mBorderUIPts[i][j - 1], mBorderUIPts[i][j], Scalar(0, 255, 0), ROOM_BORDER_PANT_WIDTH);
//3.画主管道线条
for (size_t i = 1; i < mMainTubeUIPts.size(); i++)
line(mat4show_color, mMainTubeUIPts[i- 1], mMainTubeUIPts[i], Scalar(0, 0, 255), ROOM_BORDER_PANT_WIDTH);
//4.画空调标记位置
for (size_t i = 0; i < mACLocationsFromUI.size()-1; i++)
if (mACLocationsFromUI[i].x >= 0 && mACLocationsFromUI[i].y >= 0)
circle(mat4show_color, mACLocationsFromUI[i], 5, Scalar(0x98, 0xfb, 0x98), 1);
//5.画关键点位置
for (size_t i = 0; i < mKeyNodes.size(); i++)
{
cout << "mKeyNodes[" << mKeyNodes[i].node_id << "]:type=" << mKeyNodes[i].type << "; room_id = " << mKeyNodes[i].room_id << "; contour_id = " << mKeyNodes[i].contour_id << "; location = " << mKeyNodes[i].location << "; main_tube_discrete_id=" << mKeyNodes[i].main_tube_discrete_id << endl;
switch (mKeyNodes[i].type)
{
case KeyNodeType::KNT_CORNER:
circle(mat4show_color, mKeyNodes[i].location, 3, Scalar(0xcd, 0x00, 0xcd), 1);
break;
case KeyNodeType::KNT_AC :
circle(mat4show_color, mKeyNodes[i].location, 3, Scalar(0xd4, 0xff, 0x7f), 1);
break;
case KeyNodeType::KNT_MAIN_TUBE_END :
circle(mat4show_color, mKeyNodes[i].location, 3, Scalar(0x8e, 0x38, 0x8e), 1);
break;
default:
break;
}
}
//6显示与存储图片
imshow("ShowResult", mat4show_color);
imwrite("ShowResult.bmp", mat4show_color);
waitKey(-1);
}
void CSmartRouting::CreateConnectiveMatrix()
{
//【1】申请内存并初始化邻接矩阵
mConnectiveMatrix = new int*[mKeyNodes.size()];
for (size_t i = 0; i < mKeyNodes.size(); i++)
{
mConnectiveMatrix[i] = new int[mKeyNodes.size()];
for (size_t j = 0; j < mKeyNodes.size(); j++)
mConnectiveMatrix[i][j] = INT_INFINITY;
}
//【2】生成邻接矩阵值
//4 test
int total = 0;
for (size_t i = 0; i < mKeyNodes.size(); i++)
{
cout << "【" << i<<"】";
for (size_t j = 0; j < mKeyNodes.size(); j++)
{
if (i==j)
mConnectiveMatrix[i][j] = 0;
else if (mKeyNodes[i].room_id==mKeyNodes[j].room_id)//同一个房间内部节点
{
int id_s = mKeyNodes[j].contour_id < mKeyNodes[i].contour_id ? mKeyNodes[j].contour_id : mKeyNodes[i].contour_id;
int id_l = mKeyNodes[j].contour_id > mKeyNodes[i].contour_id ? mKeyNodes[j].contour_id : mKeyNodes[i].contour_id;
int increase_dist = id_l - id_s;
int decrease_dist = mRoomContours[mKeyNodes[i].room_id].size()- increase_dist;
mConnectiveMatrix[i][j] = increase_dist < decrease_dist ? increase_dist : -decrease_dist;//负数代表ID递减距离更近
}
else
{
double distance = sqrt(pow(mKeyNodes[i].location.x- mKeyNodes[j].location.x,2)+
pow(mKeyNodes[i].location.y - mKeyNodes[j].location.y, 2));
if (distance < DIST_THRESHOLD_BETWEEN_ROOMS_KN)//不同房间非常靠近的两个点可以穿墙连接
{
mConnectiveMatrix[i][j] = 1;
total++;
}
}
cout << mConnectiveMatrix[i][j] << ", ";
}
cout << ";" << endl;
}
cout << "total=" << total << endl;
}
void CSmartRouting::SolveShortestPathProblem()
{
for (size_t i = 0; i < mKeyNodes.size(); i++)
{
if (mKeyNodes[i].type== KeyNodeType::KNT_AC&&mKeyNodes[i].close_to_maintube_id==-1)
{
mKeyNodes[i].path_list = new int[mKeyNodes.size()];
mKeyNodes[i].dist_list = new int[mKeyNodes.size()];
ShortestPath_Dijkstra(mKeyNodes.size(),i,mConnectiveMatrix, mKeyNodes[i].path_list, mKeyNodes[i].dist_list);
int min_id = -1;
int min_dist = INT_INFINITY;
for (size_t j = 0; j < mKeyNodes.size(); j++)
{
if (mKeyNodes[j].type == KeyNodeType::KNT_MAIN_TUBE_END)
{
if (mKeyNodes[i].dist_list[j]<min_dist)
{
min_dist = mKeyNodes[i].dist_list[j];
min_id = j;
}
}
}
mKeyNodes[i].closest_maintube_end_id = min_id;
}
}
}
void CSmartRouting::ShowShortestPaths()
{
namedWindow("ShowShortestPaths", CV_WINDOW_FREERATIO);
Mat mat4show_color = Mat::zeros(mMat4Draw.size(), CV_8UC3);
//1.画房间区域
for (size_t i = 0; i < mRoomRegions.size(); i++)
mat4show_color.setTo(Scalar::all(127), mRoomRegions[i]);
//2.画描边线条
for (size_t i = 0; i < mBorderUIPts.size(); i++)
for (size_t j = 1; j < mBorderUIPts[i].size(); j++)
line(mat4show_color, mBorderUIPts[i][j - 1], mBorderUIPts[i][j], Scalar(0, 255, 0), ROOM_BORDER_PANT_WIDTH);
//3.画主管道线条
for (size_t i = 1; i < mMainTubeUIPts.size(); i++)
line(mat4show_color, mMainTubeUIPts[i - 1], mMainTubeUIPts[i], Scalar(0, 0, 255), ROOM_BORDER_PANT_WIDTH);
//4.画空调标记位置
for (size_t i = 0; i < mACLocationsFromUI.size() - 1; i++)
if (mACLocationsFromUI[i].x >= 0 && mACLocationsFromUI[i].y >= 0)
circle(mat4show_color, mACLocationsFromUI[i], 5, Scalar(0x98, 0xfb, 0x98), 1);
//5.画管道路径
for (size_t i = 0; i < mKeyNodes.size(); i++)
{
if (mKeyNodes[i].type== KeyNodeType::KNT_AC)//对每个室内机
{
//与主管端点连接
if (mKeyNodes[i].closest_maintube_end_id>=0)
{
int middle_node_id = mKeyNodes[i].closest_maintube_end_id;
while (middle_node_id!=i)
{
int pre_node_id = mKeyNodes[i].path_list[middle_node_id];
if (pre_node_id < 0)
break;
if (mConnectiveMatrix[middle_node_id][pre_node_id]==1)
line(mat4show_color, mKeyNodes[middle_node_id].location, mKeyNodes[pre_node_id].location,Scalar(255,0,0),2);
else
{
int contour_id_s = mKeyNodes[middle_node_id].contour_id < mKeyNodes[pre_node_id].contour_id ?
mKeyNodes[middle_node_id].contour_id : mKeyNodes[pre_node_id].contour_id;
int contour_id_l = mKeyNodes[middle_node_id].contour_id > mKeyNodes[pre_node_id].contour_id ?
mKeyNodes[middle_node_id].contour_id : mKeyNodes[pre_node_id].contour_id;
if (mConnectiveMatrix[middle_node_id][pre_node_id]>0)
for (size_t j = contour_id_s+1; j <contour_id_l; j++)
line(mat4show_color, mRoomContours[mKeyNodes[middle_node_id].room_id][j-1],
mRoomContours[mKeyNodes[middle_node_id].room_id][j ], Scalar(255, 0, 0), 2);
else
{
int cur_id = contour_id_l;
int next_id = (cur_id + 1) % mRoomContours[mKeyNodes[middle_node_id].room_id].size();
while (cur_id != contour_id_s)
{
line(mat4show_color, mRoomContours[mKeyNodes[middle_node_id].room_id][cur_id],
mRoomContours[mKeyNodes[middle_node_id].room_id][next_id], Scalar(255, 0, 0), 2);
cur_id = next_id;
next_id= (cur_id + 1) % mRoomContours[mKeyNodes[middle_node_id].room_id].size();
}
}
}
middle_node_id = pre_node_id;
}
}
//与主管端穿墙连接
else if (mKeyNodes[i].close_to_maintube_id>=0)
line(mat4show_color, mKeyNodes[i].location,mMainTubeDiscretePts[mKeyNodes[i].close_to_maintube_id], Scalar(255, 0, 0), 2);
imshow("ShowShortestPaths", mat4show_color);
waitKey(-1);
}
}
//6显示与存储图片
imshow("ShowShortestPaths", mat4show_color);
imwrite("ShowShortestPaths.bmp", mat4show_color);
waitKey(-1);
}
void CSmartRouting::ShortestPath_Dijkstra(int size, int v0, int** matrix, int*P, int *D)
{
int v, w, k, min;
bool *final=new bool[size];
for (size_t v = 0; v < size; v++)
{
final[v] = false;
D[v] = abs(matrix[v0][v]);
P[v] =v0;
}
D[v0] = 0;
final[v0] = true;
for (v=0; v < size; v++)
{
min = INT_INFINITY;
for (size_t w = 0; w < size; w++)
{
if (!final[w]&&D[w]<INT_INFINITY)
{
k = w;
min = D[w];
}
}
final[k] = true;
for (w = 0; w < size; w++)
{
if (!final[w]&&(min+abs(matrix[k][w])<=D[w]))
{
D[w] = min + abs(matrix[k][w]);
P[w] = k;
}
}
}
} | [
"543912140@qq.com"
] | 543912140@qq.com |
f6f3641b4392f30f680c3f7561c92289100da45b | 4e376acc9137e84833e0d26f725ee1e57d184200 | /Source/ArtilleryStrategy/AI/Tasks/SetWeaponTarget.cpp | 0bf925027492a9a9d3d1d477bddedeba7137ec86 | [] | no_license | jonike/ArtilleryStrategy | c1f92a5626f9edde3d3eec397008f90d97e2974f | 2573c21f42afeb8aea456b5759c1a87a2fcb3b13 | refs/heads/master | 2020-12-26T16:54:50.294304 | 2019-06-01T09:25:43 | 2019-06-01T09:25:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,903 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "SetWeaponTarget.h"
#include "Interfaces/PlayerProperty.h"
#include "Interfaces/WeaponBuilding.h"
#include "Interfaces/WorldTile.h"
#include "Libraries/EnemiesLibrary.h"
#include "BehaviorTree/BlackboardComponent.h"
USetWeaponTarget::USetWeaponTarget()
{
WeaponKey.AddObjectFilter(this, GET_MEMBER_NAME_CHECKED(USetWeaponTarget, WeaponKey), UPlayerProperty::StaticClass());
WeaponKey.AddObjectFilter(this, GET_MEMBER_NAME_CHECKED(USetWeaponTarget, WeaponKey), UWeaponBuilding::StaticClass());
TargetKey.AddObjectFilter(this, GET_MEMBER_NAME_CHECKED(USetWeaponTarget, TargetKey), UPlayerProperty::StaticClass());
TargetKey.AddObjectFilter(this, GET_MEMBER_NAME_CHECKED(USetWeaponTarget, TargetKey), UWorldTile::StaticClass());
TargetKey.AddObjectFilter(this, GET_MEMBER_NAME_CHECKED(USetWeaponTarget, TargetKey), AActor::StaticClass());
}
EBTNodeResult::Type USetWeaponTarget::ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory)
{
if (const auto Targets = UEnemiesLibrary::GetAttackTargets(OwnerComp.GetAIOwner()))
{
if (const auto Target = SelectTarget(OwnerComp, Targets))
{
OwnerComp.GetBlackboardComponent()->SetValueAsObject(TargetKey.SelectedKeyName, Target);
return EBTNodeResult::Succeeded;
}
}
return EBTNodeResult::Failed;
}
EBTNodeResult::Type USetWeaponTarget::AbortTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory)
{
return EBTNodeResult::Aborted;
}
void USetWeaponTarget::OnGameplayTaskActivated(UGameplayTask& Task)
{
}
AActor* USetWeaponTarget::SelectTarget(const UBehaviorTreeComponent& OwnerComp, UAttackTargets* Targets) const
{
if (Targets->GetTargets().Num() == 0)
{
return nullptr;
}
const auto& TargetsAsArray = Targets->GetTargets();
const auto Index = FMath::RandRange(0, TargetsAsArray.Num() - 1);
return TargetsAsArray[Index];
}
| [
"korotkov.ivan.s@gmail.com"
] | korotkov.ivan.s@gmail.com |
8c95adc3186690491e0599dd5babd29bd14c7a46 | 0d0bfbc7f3ec76d60a190bcb74b11f6e9a678927 | /src/Window.cpp | 686cd1617a4cdb6251f654c52b10aca407010e99 | [] | no_license | erikjuvan/sample_and_graph | 14a9b5a3828f5f98cd183ba9605da0fe58df4d4a | b3a3caf8dc3515979d2541ba4c6fe1db01020476 | refs/heads/master | 2021-10-29T03:04:19.937111 | 2021-06-03T13:09:58 | 2021-06-03T13:09:58 | 252,125,539 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,356 | cpp | #include "Window.hpp"
Window::Window(int w, int h, const std::string& title, sf::Uint32 style)
{
m_window = std::make_unique<sf::RenderWindow>(sf::VideoMode(w, h), title, style);
m_event = std::make_unique<sf::Event>();
// Make room for plenty widgets, to avoid reallocations.
m_widgets.reserve(100);
//m_window->setFramerateLimit(60); // currently already m_running at 60 fps even without limit
}
void Window::Events()
{
while (m_window->pollEvent(*m_event)) {
if (m_event->type == sf::Event::Closed) {
m_window->close();
}
for (int i = 0; i < m_widgets.size(); ++i) {
m_widgets[i]->Handle(*m_event);
}
}
}
void Window::Create(int w, int h, const std::string& title, sf::Uint32 style)
{
m_window->create(sf::VideoMode(w, h), title, style);
}
void Window::Close()
{
m_window->close();
}
void Window::Add(std::shared_ptr<Widget> const& widget)
{
m_widgets.push_back(widget);
}
void Window::Remove(std::shared_ptr<Widget> const& widget)
{
auto it = std::find(m_widgets.begin(), m_widgets.end(), widget);
if (it != m_widgets.end())
m_widgets.erase(it);
}
void Window::Draw()
{
m_window->clear(backgroundColor);
for (const auto& w : m_widgets) {
m_window->draw(*w);
}
m_window->display();
}
void Window::Update()
{
Events();
Draw();
}
void Window::SetVisible(bool visible)
{
m_window->setVisible(visible);
}
bool Window::IsOpen() const
{
return m_window->isOpen();
}
sf::Vector2i Window::GetPosition() const
{
return m_window->getPosition();
}
void Window::SetPosition(const sf::Vector2i& position)
{
m_window->setPosition(position);
}
#if defined(_WIN32)
#include <Windows.h>
void Window::AlwaysOnTop(bool top)
{
SetWindowPos(m_window->getSystemHandle(), HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
}
void Window::MakeTransparent()
{
HWND hwnd = m_window->getSystemHandle();
SetWindowLongPtr(hwnd, GWL_EXSTYLE, GetWindowLongPtr(hwnd, GWL_EXSTYLE) | WS_EX_LAYERED);
}
void Window::SetTransparency(sf::Uint8 alpha)
{
SetLayeredWindowAttributes(m_window->getSystemHandle(), 0, alpha, LWA_ALPHA);
}
#else
void Window::AlwaysOnTop(bool top)
{
}
void Window::MakeTransparent()
{
}
void Window::SetTransparency(sf::Uint8 alpha)
{
}
#endif | [
"erik.kiefer.juvan@sensum.eu"
] | erik.kiefer.juvan@sensum.eu |
868281efab214f394526c5b3fa22a007c4662c72 | 4eb4242f67eb54c601885461bac58b648d91d561 | /algorithm/constant_hash/code.cc | 08487872ab22bb755a1ecda3043b9ce9f4c43534 | [] | no_license | biebipan/coding | 630c873ecedc43a9a8698c0f51e26efb536dabd1 | 7709df7e979f2deb5401d835d0e3b119a7cd88d8 | refs/heads/master | 2022-01-06T18:52:00.969411 | 2018-07-18T04:30:02 | 2018-07-18T04:30:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,538 | cc | // Copyright 2014 Liqiang Guo. All Rights Reserved.
// Author: Liqiang Guo (guoliqiang2006@gmail.com)
// I just want to GH to hss~
// Date : 2014-01-12 22:03:41
// File : code.cc
// Brief :
#include "base/public/common_ojhead.h"
namespace algorithm {
struct Node {
unsigned int hv;
std::string host;
Node(unsigned int hvi, const std::string & hosti) : hv(hvi), host(hosti) {}
bool operator < (const Node & x) const {
return hv < x.hv;
}
};
class CHash {
public:
unsigned int Hash(const char * str) {
unsigned int rs = 0;
while (*str != '\0') {
rs = rs * 31 + *str;
str++;
}
return rs;
}
void Set(std::vector<std::string> hosts) {
for (int i = 0; i < hosts.size(); i++) {
unsigned int hv = Hash(hosts[i].c_str());
hv_to_host.push_back(Node(hv, hosts[i]));
}
std::sort(hv_to_host.begin(), hv_to_host.end());
}
// 二分查找大于等于key的hash值的server的ip
std::string Get(const std::string & key) {
unsigned int hv = Hash(key.c_str());
int b = 0;
int e = hv_to_host.size() - 1;
while (b <= e) {
int mid = b + (e - b) / 2;
if (hv_to_host[mid].hv >= hv && (mid == 0 || hv_to_host[mid - 1].hv < hv)) return hv_to_host[mid].host;
else if (hv_to_host[b].hv >= hv) e = mid - 1;
else b = mid + 1;
}
return hv_to_host[0].host;
}
private:
std::vector<Node> hv_to_host; // hash value and host
};
} // namespace algorithm
using namespace algorithm;
int main(int argc, char** argv) {
return 0;
}
| [
"guoliqiang2006@126.com"
] | guoliqiang2006@126.com |
43aac500c1c7e25ba0bea474ee3e383526c961f9 | e44b39d795f3e604ab5a9698ecd4447332d0cc48 | /2015 XTU excise/b.cpp | cec771fd26b085c528924b452ff6285de70e1361 | [] | no_license | Ilovezilian/acm | 4cd2d114333107f750812ccd2380af99e21942bb | c9f2fe995aec41ca0912a16eeda939675c6cc620 | refs/heads/master | 2021-06-07T23:41:01.335060 | 2016-10-30T02:25:17 | 2016-10-30T02:25:17 | 39,359,796 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,545 | cpp | /* ***********************************************
Author :Ilovezilian
Created Time :2015/9/7 15:54:37
File Name :b.cpp
************************************************ */
#include <bits/stdc++.h>
#define INF 0x7fffffff
using namespace std;
const int N = 1e5+10, mod = 1e9+7;
int n, cas;
struct nod
{
int h, w;
} retOfBob[N], retOfAlice[N];
bool cmp1(nod a, nod b)
{
if(a.w <= b.w && a.h <= b.h) return 1;
return 0;
/*
if(a.h == b.h) return a.w < b.w;
return a.h < b.h;
*/
}
bool cmp2(nod a, nod b)
{
if(a.w <= b.w && a.h <= b.h) return 1;
return 0;
/*
if(a.h == b.h) return a.w > b.w;
return a.h < b.h;
*/
}
void prt_sort()
{
printf("Alice-------------------\n");
for(int i = 0; i < n; i ++)
printf("(%d,%d,%d)\n", i, retOfAlice[i].h, retOfAlice[i].w);
printf("Bob-------------------\n");
for(int i = 0; i < n; i++)
printf("(%d,%d,%d)\n", i, retOfBob[i].h, retOfBob[i].w);
printf("-------------------\n");
}
void solve()
{
scanf("%d", &n);
for(int i = 0; i < n; i ++)
scanf("%d%d", &retOfAlice[i].h, &retOfAlice[i].w);
for(int i = 0; i < n; i ++)
scanf("%d%d", &retOfBob[i].h, &retOfBob[i].w);
sort(retOfBob, retOfBob + n, cmp1);
sort(retOfAlice, retOfAlice + n, cmp2);
prt_sort();
int ans = 0;
for(int i = 0, j = n - 1; i < n; i ++, j --)
if(retOfBob[i].h <= retOfAlice[j].h && retOfBob[i].w <= retOfAlice[j].w) ans ++;
printf("%d\n", ans);
}
int main()
{
//freopen("","r",stdin);
//freopen("","w",stdout);
int T;
scanf("%d", &T);
while(T --) solve();
return 0;
}
| [
"1084288424@qq.com"
] | 1084288424@qq.com |
60562531189d7b163dc08e42e800e1ce104946d0 | a50d709ded0cf5f561628d4a3475a816e7fa10ca | /Проект25/Minigames.cpp | 82476698aa9e33edb99ca60a8caa03e5d67a50e1 | [] | no_license | EnjiRouz/Skyline-Text-Novel | e1211d2182828c3bff4bea4ad7ef531b346d86cc | 72e91e1f61b4c6f45cb9b02c5fe1829d15a196ce | refs/heads/master | 2021-10-11T07:58:35.869477 | 2019-01-23T13:44:23 | 2019-01-23T13:44:23 | null | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 4,987 | cpp | #include "Minigames.h"
#include "Skyline.h"
#define N 9 //высота, ось ОУ
#define M 30//широта, ось ОХ
/*
**Мини-игра "Отмычка" (или "Замочек", или "Ключик")
**
*******************************************
** игроку даётся возможность взломать замок отмычкой:
** для этого нужно в определённый момент поднять отмычку в замке.
** будьте осторожны, отмычка может сломаться вместе с замком, если её поднять невовремя
*******************************************
**
*/
void skeletonKey(int* res)
{
//объявляем динамический двумерный массив
char** Map = new char*[N];
for (int i = 0; i < N; i++)
{
Map[i] = new char[M];
}
//задаём начальную карту
char a[N][M] =
{
{ '|','|','|','|','|','|','|','|','|','|','|','|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ' },
{ '|','|','|','|','|','|','|','|','|','|','|','|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ' },
{ '/','/','/','/','/','/','/','/','/','/','/','/',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ' },
{ '|','|','*','|','|','@','|','|','*','|','|','/',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ' },
{ ' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','&','=','=','=','=','=','=','=','=','=','=','=','#','#','#','#','#','#','#' },
{ '|','|','|','|','|','|','|','|','|','|','|','/',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ' },
{ '/','/','/','/','/','/','/','/','/','/','/','/',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ' },
{ '|','|','|','|','|','|','|','|','|','|','|','|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ' },
{ '|','|','|','|','|','|','|','|','|','|','|','|',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ' },
};
//переносим начальную карту в динамический массив
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
Map[i][j] = a[i][j];
}
}
//определяем строку, где передвигается отмычка
int fix_y = DEFAULT;
for (int i = 0; i < N; i++)
{
if (Map[i][0] == ' ')
{
fix_y = i;
}
}
moveSK(Map, fix_y, M, N, res);//передвижение отмычки(процесс игры)
//удаление динамического двумерного массива
for (int i = 0; i < N; i++)
{
delete[]Map[i];
}
delete[]Map;
}
// функция вывода игровой карты в консоль
void showMap(char** map, int y, int x)
{
cout << "\n\n";
for (int i = 0; i < y; i++)//перебор по вертикали
{
cout << "\t\t\t";
for (int j = 0; j < x; j++)//перебор по горизонтали
cout << map[i][j];
cout << endl;
}
cout << "\n\n";
}
// функция передвигает отмычку и
void moveSK(char** map, int fix_y, int x, int y, int* res)
{
int determinant = -1;
int sensor = 11;
while (*res == DEFAULT)
{
if (determinant == -1)
{
char m = map[fix_y][DEFAULT];
for (int i = 0; i < x - 1; i++)
{
map[fix_y][i] = map[fix_y][i - determinant];
}
map[fix_y][x - 1] = m;
sensor--;
stand(0,2);
showMap(map, y, x);
Sleep(100);
*res = ifUseSK(map, fix_y, sensor);
if (map[fix_y][DEFAULT] == '&') determinant = 1;
}
else
{
char n = map[fix_y][x - 1];
for (int j = x - 1; j > 0; j--)
{
map[fix_y][j] = map[fix_y][j - determinant];
}
map[fix_y][DEFAULT] = n;
sensor++;
stand(0, 2);
showMap(map, y, x);
Sleep(100);
*res = ifUseSK(map, fix_y, sensor);
if (map[fix_y][x - 1] == '#') determinant = -1;
}
}
}
// если совершена попытка открыть замок, эта функция определяет результат попытки
int ifUseSK(char** map, int y, int x)
{
int result = 0;
if (_kbhit())
{
if (map[y - 1][x] == '@')
{
result = 1;
}
else result = 2;
}
return result;
}
// вывод результата попытки
void inputResult(int a, int* res)
{
if (a == 1)
{
system("cls");
cout << "* * *** * * * * ***** * *\n"
<< " * * * * * * * * * ** *\n"
<< " * * * * * * * * * * *\n"
<< " * * * * * * * * * * **\n"
<< " * *** *** * * ***** * *";
*res=*res+1;///////
}
if (a == 2)
{
system("cls");
cout << "* * *** * * * *** *** *****\n"
<< " * * * * * * * * * * * \n"
<< " * * * * * * * * *** *****\n"
<< " * * * * * * * * * * \n"
<< " * *** *** ***** *** *** *****";
}
Sleep(3000);
}
| [
"enji.rouz@yandex.ru"
] | enji.rouz@yandex.ru |
171621bcd6b4f63c990448a92777dc2e0e2da102 | 449551b089905f130abe7caa486b804d81399e09 | /pattern_trainer/framefeatureclassifier.cpp | f910625cfe41b596b2f85b6fa774b2f4cd374693 | [] | no_license | mcsyp/ad_sweep_pattern | 4c8f6374ad65c1d7a87b7f9bfc9df4ab749822de | 515f89cc52420d47b9b30cb290c58c44c1544b7f | refs/heads/master | 2020-12-13T19:58:32.620377 | 2017-08-02T07:02:12 | 2017-08-02T07:02:12 | 95,511,002 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,096 | cpp | #include "framefeatureclassifier.h"
#include <stdio.h>
#include <math.h>
using namespace std;
using namespace qri_neuron_lib;
using namespace feature_engine;
FrameFeatureClassifier::FrameFeatureClassifier(const param_wave_t & wave)
:FeatureClassifier({FrameFeatureExtractor::RAW_ROWS,FrameFeatureExtractor::RAW_COLS,FrameFeatureExtractor::RAW_DELTA},
{FrameFeatureExtractor::FEATURE_GAP_MIN,FrameFeatureExtractor::FEATURE_GAP_MAX},
NULL)
{
this->ptr_extractor_ = new FrameFeatureExtractor(wave);
}
FrameFeatureClassifier::FrameFeatureClassifier(const param_wave_t & wave, NeuronEngineFloat &engine)
:FeatureClassifier(engine,
{FrameFeatureExtractor::RAW_ROWS,FrameFeatureExtractor::RAW_COLS,FrameFeatureExtractor::RAW_DELTA},
{FrameFeatureExtractor::FEATURE_GAP_MIN,FrameFeatureExtractor::FEATURE_GAP_MAX},
NULL)
{
this->ptr_extractor_ = new FrameFeatureExtractor(wave);
}
FrameFeatureClassifier::~FrameFeatureClassifier(){
if(this->ptr_extractor_) delete this->ptr_extractor_;
}
| [
"turltesyp@163.com"
] | turltesyp@163.com |
1c21f5ed564d982a1a01ce76ff2543a3ad9db25f | 425eb72d3d8dc0492c649e0a29f757c3e9750d78 | /Source/System/Wifi/LibNM/DBus/Wifi_LibNM_DBus_SavedConnection.h | b944e1687af06be097355186dd0190f915fb80d6 | [] | no_license | centuryglass/Pocket-Home-Bismuth | 76a79a6d72d17253e1fe5c4702dc77a462a46f13 | c5cc2703f6176e97416e51877a6484b0ebd6b872 | refs/heads/master | 2022-06-18T18:27:16.736586 | 2022-06-02T16:13:01 | 2022-06-02T16:13:01 | 112,958,912 | 36 | 9 | null | 2022-06-02T16:13:02 | 2017-12-03T19:57:34 | C++ | UTF-8 | C++ | false | false | 6,398 | h | #pragma once
/**
* @file Wifi_LibNM_DBus_SavedConnection.h
*
* @brief Controls a saved network connection stored remotely by
* NetworkManager.
*/
#include "GLib_DBus_Proxy.h"
#include "Wifi_LibNM_Connection.h"
#include "JuceHeader.h"
namespace Wifi { namespace LibNM { namespace DBus {
class SavedConnection; } } }
/**
* @brief A D-Bus proxy wrapper used to access a single saved connection held
* by NetworkManager.
*
* All saved network connections visible to NetworkManager on the system
* running this application may be loaded as SavedConnection objects.
* SavedConnection objects are primarily meant to handle Wifi connections, and
* support for other connection types is incomplete.
*
* If the saved connection is a valid Wifi connection, SavedConnection can
* create a Connection object that may be used with the LibNM::Client to
* activate the connection if a compatible access point is visible.
*
* SavedConnection may be used to delete its connection from NetworkManager.
* This will affect other connection applications using NetworkManager, and it
* cannot be undone.
*/
class Wifi::LibNM::DBus::SavedConnection : public GLib::DBus::Proxy
{
public:
/**
* @brief Creates an empty object with no linked connection.
*/
SavedConnection();
/**
* @brief Initializes a SavedConnection from a DBus connection path.
*
* @param path A valid DBus path to a NetworkManager saved connection.
*/
SavedConnection(const char* path);
virtual ~SavedConnection() { }
/**
* @brief Gets the connection's DBus path.
*
* @return The DBus path used to create this object, or the empty string
* if the connection is not valid.
*/
const juce::String& getPath() const;
/**
* @brief Checks if this connection is a wifi connection.
*
* @return Whether the saved connection has wifi connection settings.
*/
bool isWifiConnection() const;
/**
* @brief Gets the Connection object generated from this connection's data.
*
* Only Wifi connections are supported, other connection types will result
* in incomplete Connection objects.
*
* @return The Connection object for this connection, or nullptr if the
* connection is invalid.
*/
Connection getNMConnection();
/**
* @brief Gets the last recorded time this saved connection was active.
*
* @return The last time the connection was active, or the Unix epoch if
* the connection has no saved connection time.
*/
juce::Time lastConnectionTime() const;
/**
* @brief Checks if the connection has a saved wireless security key.
*
* @return Whether a security key value was found in this connection's
* settings.
*/
bool hasSavedKey() const;
/**
* @brief Deletes this connection from the list of saved connections.
*
* This object will be null after this function is called.
*/
void deleteConnection();
/**
* @brief Compares SavedConnections using their connection paths.
*
* @param rhs A connection to compare with this object.
*
* @return Whether this connection and rhs share a DBus path.
*/
bool operator== (const SavedConnection& rhs) const;
/**
* @brief Compares SavedConnections with NMConnections using their
* connection paths.
*
* @param rhs A connection to compare with this object.
*
* @return Whether this connection and rhs share a DBus path.
*/
bool operator== (NMConnection* rhs) const;
private:
/**
* @brief Returns one of this connection's settings objects.
*
* @param name The name of the connection setting to find.
*
* @return The setting with the matching name, if found. If this value
* is non-null, it will need to be freed with g_variant_unref.
*/
GVariant* getSetting(const char* name) const;
/**
* @brief Returns the value of a specific settings object property.
*
* @param settingName The name of the connection setting to search.
*
* @param propName The name of the property to search for in the
* settings object.
*
* @return The matching property, if found. If this value is
* non-null, it will need to be freed with
* g_variant_unref.
*/
GVariant* getSettingProp(const char* settingName, const char* propName)
const;
/**
* @brief Returns the value of a specific settings object property.
*
* @param settingsObject A settings object extracted from this connection.
*
* @param propName The name of the property to search for in the
* settings object.
*
* @return The matching property, if found. If this value is
* non-null, it will need to be freed with
* g_variant_unref.
*/
GVariant* getSettingProp(GVariant* settingsObject, const char* propName)
const;
/**
* @brief Checks if this connection has a particular setting type.
*
* @param settingName The name of a connection settings object to find.
*
* @return Whether a settings object named settingName exists.
*/
bool hasSetting(const char* settingName) const;
/**
* @brief Checks if this connection has a specific setting type, and if
* that settings object as a specific property.
*
* Don't use this if you actually need any data from the setting, in that
* case it's more effective to just get the setting object and check if
* getSettingParam returns null.
*
* @param settingName The name of a connection settings object to find.
*
* @param propName The name of a settings property to check for.
*
* @return Whether a settings object named settingName exists
* and contains a property called propName.
*/
bool hasSettingProperty(const char* settingName, const char* propName)
const;
// The SavedConnection's DBus path:
juce::String path;
};
| [
"anthony0857@gmail.com"
] | anthony0857@gmail.com |
c0e085a8a0334758d63858a88ace3e225ed829a8 | ab69017623937d04241eb4a0f6416f6322b0e0d5 | /Archive/Codeforces - Codeforces Global Round 11/B. Chess Cheater/solution.cpp | 6bb906e02a8eea926edadeefadf984e6f9210c55 | [] | no_license | i-tick/competitive_programming | dbd7da9aad7eb16a6d5707dce8bac43cf27a7b4e | 90653bce9611b50750b18ea23077a6c5012e5cfa | refs/heads/master | 2023-01-02T10:13:31.899215 | 2020-10-29T15:28:13 | 2020-10-29T15:28:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,145 | cpp | #include <bits/stdc++.h>
#define sz(v) ((int)(v).size())
#define all(v) (v).begin(), (v).end()
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> ii;
const int N = 1e5 + 5;
int n, k;
char a[N];
void solve() {
cin >> n >> k;
int ans = 0, cnt = 0;
int ch = 0;
for (int i = 1; i <= n; i++) {
cin >> a[i];
if (a[i] == 'W') {
ans += 2;
ch = 1;
} else {
cnt++;
}
}
if (cnt <= k) {
cout << 2 * n - 1 << "\n";
return;
}
if (a[1] == 'W') {
ans--;
}
vi l;
int last = 0;
for (int i = 2; i <= n; i++) {
if (a[i - 1] == 'L' && a[i] == 'W') {
if (last != 0) {
l.push_back(i - last - 1);
}
ans--;
}
if (a[i - 1] == 'W' && a[i] == 'L') {
last = i - 1;
}
}
sort(all(l));
for (int i : l) {
// cout << i << " ";
if (k >= i) {
ans += i * 2 + 1;
k -= i;
}
}
// cout << "\n";
ans += 2 * k;
if (ch == 0) {
ans--;
}
cout << max(ans, 0) << "\n";
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while (t--) {
solve();
}
} | [
"cunbidun@gmail.com"
] | cunbidun@gmail.com |
2a4251deade92fcc3f4676ab08379c2468cc7fba | b7f4ddd9741cdfbe86beab96e9d8f72d4bd62450 | /Threaded Binary Tree Traversal.cpp | 90008fca2bdee47042cce359f487ab6efc364e8f | [] | no_license | AnshulPrasad2602/Threaded-Binary-Tree | 6d9b53d3aa322b02514f7d4319c77b412c6c616a | 7bf7f5cfb11a84fd76511b621261fad802051402 | refs/heads/master | 2022-10-05T03:45:47.755895 | 2020-06-07T18:08:02 | 2020-06-07T18:08:02 | 270,390,274 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,268 | cpp |
#include<iostream>
#include<string.h>
using namespace std;
class tnode
{
public:
int data;
int lthread,rthread;
tnode *left,*right;
};
class tree:public tnode
{
public:
tnode *root,*head;
tree()
{
root=NULL;
head=new tnode();
head->lthread=head->rthread=0;
head->left=head->right=NULL;
}
void create();
void inorder();
void preorder();
void postorder();
tnode* search(tnode *temp);
};
void tree::create()
{
tnode *temp,*newnode;
int n,flag;
char ch='y',c;
while(ch=='y'||ch=='Y')
{
cout<<"\nEnter data to be inserted: ";
cin>>n;
newnode=new tnode();
newnode->data=n;
newnode->lthread=newnode->rthread=0;
newnode->left=newnode->right=NULL;
flag=1;
if(root==NULL)
{
root=newnode;
root->left=root->right=head;
}
else
{
temp=root;
while(flag==1)
{
if(n<temp->data)
{
if(temp->lthread==0)
{
newnode->lthread=newnode->rthread=0;
newnode->left=temp->left;
newnode->right=temp;
temp->left=newnode;
temp->lthread=1;
flag=0;
}
else
{
temp=temp->left;
flag=1;
}
}
else
{
if(temp->rthread==0)
{
newnode->lthread=newnode->rthread=0;
newnode->right=temp->right;
newnode->left=temp;
temp->right=newnode;
temp->rthread=1;
flag=0;
}
else
{
temp=temp->right;
flag=1;
}
}
}
}
cout<<"Add more nodes(Y/N): ";
cin>>ch;
}
}
void tree::preorder()
{
tnode *temp=root;
cout<<"\nPREORDER TRAVERSAL";
while(temp!=head)
{
while(temp->lthread==1)
{
cout<<" "<<temp->data;
temp=temp->left;
}
if(temp->lthread==0 && temp->rthread==0)
{
cout<<" "<<temp->data;
}
while(temp->rthread==0 && temp!=head)
{
temp=temp->right;
}
if(temp==head)
return;
temp=temp->right;
if(temp->lthread==1 || temp->rthread==1)
{
cout<<" "<<temp->data;
}
}
}
void tree::postorder()
{
tnode *temp=root;
tnode *parent;
int nextaction=1;
int count=0,count1=0;
while(1)
{
switch(nextaction)
{
case 1:
while(temp->lthread==1)
temp=temp->left;
cout<<" "<<temp->data;
temp=temp->right;
parent=temp->right;
nextaction=2;
break;
case 2:
while(temp->rthread==1)
temp=temp->right;
cout<<" "<<temp->data;
temp=temp->left;
parent=temp->left;
nextaction=3;
break;
case 3:
cout<<" "<<temp->data;
parent=search(temp);
//cout<<"parent data: "<<parent->data;
if(parent->data==root->data)
count=count+1;
if(parent->data==root->data && count==2)
{
cout<<" "<<parent->data;
return;
}
//cout<<"1. temp->data:"<<temp->data;
if(temp->data==root->left->data && count==1)
{
temp=parent;
nextaction=4;
count1++;
}
if(count1==1 && parent->data!=root->data)
{
temp=parent;
count1=0;
nextaction=3;
}
if(temp->data==parent->left->data)
{
temp=parent;
nextaction=2;
count1++;
}
if(temp->data==root->left->data && count==1)
{
temp=parent;
nextaction=4;
count1++;
}
else if(temp->data==parent->right->data)
{
temp=parent;
nextaction=1;
count1++;
}
//cout<<"count: "<<count;
//cout<<"count1: "<<count1;
break;
case 4:
if(temp->data==root->data)
temp=temp->right;
while(temp->lthread==1)
temp=temp->left;
cout<<" "<<temp->data;
temp=temp->right;
nextaction=2;
break;
}
}
}
tnode* tree::search(tnode *temp)
{
tnode *temp1=root;
while(temp1!=head)
{
if(temp1->left->data==temp->data || temp1->right->data==temp->data)
{
//cout<<" temp1->data: "<<temp1->left->data;
//cout<<" temp1->data1: "<<temp1->right->data;
return temp1;
break;
}
else if(temp->data<temp1->data)
{
//cout<<" search 1 ";
temp1=temp1->left;
}
else if(temp->data>temp->data)
{
//cout<<" search 2 ";
temp1=temp1->right;
}
}
}
void tree::inorder()
{
tnode *temp=root;
cout<<"\nINORDER TRAVERSAL";
while(temp!=head)
{
while(temp->lthread==1)
temp=temp->left;
cout<<" "<<temp->data;
while(temp->rthread==0 && temp!=head)
{
temp=temp->right;
if(temp->data!=head->data)
{
cout<<" "<<temp->data;
}
}
if(temp==head)
return;
temp=temp->right;
}
}
int main()
{
int c,n;
char ch='y';
tree t;
while(ch!='n'||ch!='N')
{
cout<<"\n 1.CREATION OF TREE \n 2.INORDER TRAVERSAL \n 3.PREORDER TRAVERSAL \n 4.POSTORDER TRAVERSAL \nEnter choice : ";
cin>>c;
switch(c)
{
case 1:
t.create();
break;
case 2:
t.inorder();
break;
case 3:
t.preorder();
break;
case 4:
t.postorder();
break;
}
cout<<"\nDo you want to continue(Y/N): ";
cin>>ch;
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
7d8a9a9e75e796a85dd2b987afb16a287ae2799e | f115901d03013bf0459b39da1b10f017c88eace5 | /tests/test_iomanager.cc | 75fa449346249b2da20b12bd1c1e85596a11afcb | [] | no_license | autoli/server-design | 4fc41dfc5cb4b125dd559007beba7744b0e45edd | cb186a2039fcb693a94227f714db724b033fa538 | refs/heads/master | 2023-02-26T19:23:06.474423 | 2021-02-07T06:48:19 | 2021-02-07T06:48:19 | 312,457,197 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,065 | cc | #include "../autoli/autoli.h"
#include "../autoli/iomanager.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <iostream>
#include <sys/epoll.h>
autoli::Logger::ptr g_logger = AUTOLI_LOG_ROOT();
int sock = 0;
void test_fiber() {
AUTOLI_LOG_INFO(g_logger) << "test_fiber sock=" << sock;
//sleep(3);
//close(sock);
//autoli::IOManager::GetThis()->cancelAll(sock);
sock = socket(AF_INET, SOCK_STREAM, 0);
fcntl(sock, F_SETFL, O_NONBLOCK);
sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(80);
inet_pton(AF_INET, "14.215.177.38", &addr.sin_addr.s_addr);
if(!connect(sock, (const sockaddr*)&addr, sizeof(addr))) {
} else if(errno == EINPROGRESS) {
AUTOLI_LOG_INFO(g_logger) << "add event errno=" << errno << " " << strerror(errno);
autoli::IOManager::GetThis()->addEvent(sock, autoli::IOManager::READ, [](){
AUTOLI_LOG_INFO(g_logger) << "read callback";
});
autoli::IOManager::GetThis()->addEvent(sock, autoli::IOManager::WRITE, [](){
AUTOLI_LOG_INFO(g_logger) << "write callback";
//close(sock);
autoli::IOManager::GetThis()->cancelEvent(sock, autoli::IOManager::READ);
close(sock);
});
} else {
AUTOLI_LOG_INFO(g_logger) << "else " << errno << " " << strerror(errno);
}
}
void test1() {
std::cout << "EPOLLIN=" << EPOLLIN
<< " EPOLLOUT=" << EPOLLOUT << std::endl;
autoli::IOManager iom(2, false);
iom.schedule(&test_fiber);
}
autoli::Timer::ptr s_timer;
void test_timer() {
autoli::IOManager iom(2);
s_timer = iom.addTimer(1000, [](){
static int i = 0;
AUTOLI_LOG_INFO(g_logger) << "hello timer i=" << i;
if(++i == 3) {
s_timer->reset(2000, true);
//s_timer->cancel();
}
}, true);
}
int main(int argc, char** argv) {
test1();
//test_timer();
return 0;
}
| [
"auto_lilei_stu@163.com"
] | auto_lilei_stu@163.com |
f8d9d87dbe8a42af60f5ad6d668882f35bbff28d | 8d4a8205e803a5c21fdc73bb64b8d1f0d12c32a0 | /Sources/MainSystem.cpp | a5ac062ddec5e2f757bcc9d9b677899e02cf85a6 | [] | no_license | Vlarod/Cataster-system-with-B-tree | 7f3c79d6888997af984dd37740483511ceace115 | 75321568512ff3f393019383603d8fc20e9f1b26 | refs/heads/master | 2022-08-04T15:03:06.904763 | 2020-05-28T11:16:14 | 2020-05-28T11:16:14 | 267,569,309 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,126 | cpp | #include "MainSystem.h"
Btree * MainSystem::getPropertiesViaID()
{
return propertiesViaID;
}
Btree * MainSystem::getPropertiesViaIDandCA()
{
return propertiesViaIDandCA;
}
int MainSystem::getCurrLoadPropDataIndex()
{
return currLoadPropDataIndex;
}
int MainSystem::getPropertiesViaIdDegree()
{
return propertiesViaIdDegree;
}
int MainSystem::getPropertiesViaIdAndCADegree()
{
return propertiesViaIdAndCADegree;
}
int MainSystem::getPropertySize()
{
return propertySize;
}
int MainSystem::getLastIndex()
{
return lastIndex;
}
std::string MainSystem::getDataFileName()
{
return dataFile;
}
std::string MainSystem::getPropertiesViaIdFile()
{
return propertiesViaIdFile;
}
std::string MainSystem::getPropertiesViaIdAndCAFile()
{
return propertiesViaIdAndCAFile;
}
bool MainSystem::addProperty(int idNumber, int zipNumber, std::string caName, std::string descr)
{
KeyPropertyID * newKey = new KeyPropertyID();
KeyPropertyIDandCA * newKeyCa = new KeyPropertyIDandCA();
Property * newProperty = new Property(idNumber,zipNumber,caName,descr);
newKey->setPointerToRecord((Zaznam*)newProperty);
newKey->setId(idNumber);
newKey->setBlockIndex(lastIndex);
newKeyCa->setPointerToRecord((Zaznam*)newProperty);
newKeyCa->setZip(newProperty->getZIPNumber());
newKeyCa->setCaName(newProperty->getCatasterName());
newKeyCa->setBlockIndex(lastIndex);
if (getPropertiesViaID()->searchKey((Key*)newKey) == nullptr) {
if (getPropertiesViaIDandCA()->searchKey((Key*)newKeyCa) == nullptr) {
writeDataToFile(newProperty);
if (propertiesViaID->insert((Key*)newKey) == true) {
if (propertiesViaIDandCA->insert((Key*)newKeyCa) == true) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}
}
}
bool MainSystem::setDescription(std::string newdescr, Property * prop)
{
prop->setDescription(newdescr);
this->updateDataInFile(prop);
return true;
}
void MainSystem::writeDataToFile(Property * prop)
{
std::vector<unsigned char> *vect = new std::vector<unsigned char>;
prop->toByteArray(vect);
this->setPropertySize(prop->getSize());
std::ofstream OutFile;
OutFile.open(dataFile, std::ios::in | std::ios::binary);
OutFile.seekp(lastIndex * vect->size());
OutFile.write((char*)&*(vect->begin()), vect->size());
OutFile.close();
lastIndex++;
}
void MainSystem::updateDataInFile(Property * prop)
{
std::vector<unsigned char> *vect = new std::vector<unsigned char>;
prop->toByteArray(vect);
std::ofstream OutFile;
OutFile.open(dataFile, std::ios::in | std::ios::binary);
OutFile.seekp(this->getCurrLoadPropDataIndex() * vect->size());
OutFile.write((char*)&*(vect->begin()), vect->size());
OutFile.close();
}
void MainSystem::setCurrLoadPropDataIndex(int newInd)
{
currLoadPropDataIndex = newInd;
}
void MainSystem::setPropertiesViaIdDegree(int newdeg)
{
propertiesViaIdDegree = newdeg;
}
void MainSystem::setPropertiesViaIdAndCaDegree(int newdeg)
{
propertiesViaIdAndCADegree = newdeg;
}
void MainSystem::setPropertySize(int newSize)
{
propertySize = newSize;
}
void MainSystem::setLastIndex(int nLIndex)
{
lastIndex = nLIndex;
}
void MainSystem::setDataFile(std::string newDataFile)
{
dataFile = newDataFile;
}
void MainSystem::generateData(int numberOfD)
{
for (int i = 0; i < numberOfD; i++) {
KeyPropertyID *newKeyId = new KeyPropertyID();
KeyPropertyIDandCA *newKeyIdCa = new KeyPropertyIDandCA();
int id = 1 + rand() % ((1000 + 1) - 1);
int zip = 1 + rand() % ((1000 + 1) - 1);
std::string caName = this->randomStringGenerator(14);
std::string descr = this->randomStringGenerator(19);
Property *newProperty = new Property(id,zip,caName,descr);
newKeyId->setBlockIndex(lastIndex);
newKeyId->setId(id);
newKeyId->setPointerToRecord((Zaznam*)newProperty);
newKeyIdCa->setBlockIndex(lastIndex);
newKeyIdCa->setZip(zip);
newKeyIdCa->setCaName(caName);
newKeyIdCa->setPointerToRecord((Zaznam*)newProperty);
writeDataToFile(newProperty);
propertiesViaID->insert((Key*)newKeyId);
propertiesViaIDandCA->insert((Key*)newKeyIdCa);
}
}
void MainSystem::saveConf(std::string nameFile)
{
std::ofstream myfile;
myfile.open("conf.txt");
myfile << lastIndex << "\n";
myfile << dataFile << "\n";
myfile << propertySize << "\n";
myfile << propertiesViaIdDegree << "\n";
myfile << propertiesViaIdFile << "\n";
myfile << this->getPropertiesViaID()->getRootIndex() << "\n";
myfile << this->getPropertiesViaID()->getLastAdressIndex() << "\n";
myfile << propertiesViaIdAndCADegree << "\n";
myfile << propertiesViaIdAndCAFile << "\n";
myfile << this->getPropertiesViaIDandCA()->getRootIndex() << "\n";
myfile << this->getPropertiesViaIDandCA()->getLastAdressIndex();
myfile.close();
}
void MainSystem::readConf(std::string nameFile)
{
std::string line;
std::ifstream myfile("conf.txt");
if (myfile.is_open())
{
int lastIndex1;
int propertiesViaIdDegree1;
int propertiesViaIdLastIndex;
int propertiesViaIdAndCADegree1;
int propertiesViaIdAndCALastIndex;
std::string propertiesViaIdFile1;
std::string propertiesViaIdAndCAFile1;
std::string dataFile1;
int propertySize1;
int viaIdRootIndex1;
int viaZipCaRootIndex1;
getline(myfile, line);
lastIndex1 = stoi(line);
getline(myfile, line);
dataFile1 = line;
getline(myfile, line);
propertySize1 = stoi(line);
getline(myfile, line);
propertiesViaIdDegree1 = stoi(line);
getline(myfile, line);
propertiesViaIdFile1 = line;
getline(myfile, line);
viaIdRootIndex1 = stoi(line);
getline(myfile, line);
propertiesViaIdLastIndex = stoi(line);
getline(myfile, line);
propertiesViaIdAndCADegree1 = stoi(line);
getline(myfile, line);
propertiesViaIdAndCAFile1 = line;
getline(myfile, line);
viaZipCaRootIndex1 = stoi(line);
getline(myfile, line);
propertiesViaIdAndCALastIndex = stoi(line);
myfile.close();
this->setLastIndex(lastIndex1);
this->setPropertySize(propertySize1);
this->setDataFile(dataFile1);
propertiesViaID = new Btree(propertiesViaIdDegree1, propertiesViaIdFile1);
propertiesViaIDandCA = new Btree(propertiesViaIdAndCADegree1, propertiesViaIdAndCAFile1);
KeyPropertyID *newKid = new KeyPropertyID();
KeyPropertyIDandCA *newKidCa = new KeyPropertyIDandCA();
propertiesViaID->searchBlockViaIndex(viaIdRootIndex1, propertySize1,(Key*)newKid);
propertiesViaID->setLastAdress(propertiesViaIdLastIndex);
propertiesViaIDandCA->searchBlockViaIndex(viaZipCaRootIndex1, propertySize1,(Key*)newKidCa);
propertiesViaIDandCA->setLastAdress(propertiesViaIdAndCALastIndex);
}
}
std::string MainSystem::randomStringGenerator(int size)
{
std::string str = "";
str.resize(size);
for (int i = 0; i < size; i++) {
str[i] = rand() % 26 + 65;
}
return str;
}
Property * MainSystem::searchPropertyViaId(int id)
{
KeyPropertyID* sProperty = new KeyPropertyID();
sProperty->setId(id);
KeyPropertyID * fProperty = (KeyPropertyID*)getPropertiesViaID()->searchKey((Key*)sProperty);
if (fProperty != nullptr) {
Property * newProp = new Property();
newProp->fromByteArray(readDataFromFile(fProperty->getBlockIndex()));
this->setCurrLoadPropDataIndex(fProperty->getBlockIndex());
return newProp;
}
else {
return nullptr;
}
}
Property * MainSystem::searchPropertyViaIdanCA(int id, std::string ca)
{
KeyPropertyIDandCA* sProperty = new KeyPropertyIDandCA();
sProperty->setZip(id);
sProperty->setCaName(ca);
KeyPropertyIDandCA * fProperty = (KeyPropertyIDandCA*)getPropertiesViaIDandCA()->searchKey((Key*)sProperty);
if (fProperty != nullptr) {
Property * newProp = new Property();
newProp->fromByteArray(readDataFromFile(fProperty->getBlockIndex()));
this->setCurrLoadPropDataIndex(fProperty->getBlockIndex());
return newProp;
}
else {
return nullptr;
}
}
char * MainSystem::readDataFromFile(int index)
{
std::streampos size;
char * memblock;
std::ifstream file(dataFile, std::ios::in | std::ios::binary | std::ios::ate);
if (file.is_open())
{
size = this->getPropertySize();
memblock = new char[size];
file.seekg(index * size, std::ios::beg);
file.read(memblock, size);
file.close();
return memblock;
}
}
MainSystem::MainSystem()
{
}
MainSystem::MainSystem(int idDegree, int idCaDegree)
{
propertiesViaID = new Btree(idCaDegree, "viaId.bin");
propertiesViaIDandCA = new Btree(idCaDegree, "viaIDandCA.bin");
lastIndex = 0;
}
MainSystem::MainSystem(int idDegree, int zipCaDegree, std::string datafile, std::string idFile, std::string zipCaFile) :propertiesViaIdDegree(idDegree), propertiesViaIdAndCADegree(zipCaDegree),dataFile(datafile), propertiesViaIdFile(idFile), propertiesViaIdAndCAFile(zipCaFile) {
propertiesViaID = new Btree(idDegree, idFile);
propertiesViaIDandCA = new Btree(zipCaDegree, zipCaFile);
lastIndex = 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
ac581f17529632698f70f76eebc3eca0dfc512fa | fd6f212011807f3c0ade7cc74f1b7dd4d2c51c6b | /lookup.ino | b9d6f015c84176a8479ea49f3bfab18e4f3cc388 | [] | no_license | WaiPhyoMaung/sinusoidal | 51c1e4ff1d8561fcfbfb65485dc4b9d71bb264fe | d434b46b3f4068718261c966cb25983344704846 | refs/heads/master | 2023-03-16T05:51:52.168292 | 2018-05-12T09:32:48 | 2018-05-12T09:32:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,427 | ino | // test four different patterns for stepper acceleration
// test program for DOIT ESPDUINO + CNCShield 3
// remove resistor R1 from CNCshield !!!
// May 2018
// by misan
PROGMEM const int speed0[]={0,3847,1646,1263,1064,938,848,779,725,681,644,613,585,562,540,521,504,489,475,461,449,438,428,418,409,401,393,385,378,372,365,359,354,348,343,338,333,328,324,320,316,312,308,304,301,297,294,291,288,285,282,279,276,274,271,269,266,264,262,259,257,255,253,251,249,247,245,243,241,240,238,236,234,233,231,230,228,227,225,224,222,221,220,218,217,216,214,213,212,211,210,208,207,206,205,204,203,202,201,200,199,198,197,196,195,194,193,192,191,190,189,189,188,187,186,185,184,184,183,182,181,181,180,179,178,178,177,176,175,175,174,173,173,172,171,171,170,170,169,168,168,167,167,166,165,165,164,164,163,163,162,161,161,160,160,159,159,158,158,157,157,156,156,155,155,154,154,153,153,153,152,152,151,151,150,150,149,149,149,148,148,147,147,147,146,146,145,145,145,144,144,143,143,143,142,142,142,141,141,141,140,140,139,139,139,138,138,138,137,137,137,136,136,136,135,135,135,135,134,134,134,133,133,133,132,132,132,132,131,131,131,130,130,130,130,129,129,129,128,128,128,128,127,127,127,127,126,126,126,126,125,125,125,125,124,124,124,124,123,123,123,123,122,122,122,122,121,121,121,121,121,120,120,120,120,119,119,119,119,119,118,118,118,118,117,117,117,117,117,116,116,116,116,116,115,115,115,115,115,114,114,114,114,114,114,113,113,113,113,113,112,112,112,112,112,112,111,111,111,111,111,110,110,110,110,110,110,109,109,109,109,109,109,108,108,108,108,108,108,108,107,107,107,107,107,107,106,106,106,106,106,106,105,105,105,105,105,105,105,104,104,104,104,104,104,104,103,103,103,103,103,103,103,102,102,102,102,102,102,102,101,101,101,101,101,101,101,101,100,100,100,100,100,100,100,100,99,99,99,99,99,99,99,99,98,98,98,98,98,98,98,98,97,97,97,97,97,97,97,97,97,96,96,96,96,96,96,96,96,95,95,95,95,95,95,95,95,95,94,94,94,94,94,94,94,94,94,94,93,93,93,93,93,93,93,93,93,93,92,92,92,92,92,92,92,92,92,91,91,91,91,91,91,91,91,91,91,91,90,90,90,90,90,90,90,90,90,90,89,89,89,89,89,89,89,89,89,89,89,88,88,88,88,88,88,88,88,88,88,88,88,87,87,87,87,87,87,87,87,87,87,87,87,86,86,86,86,86,86,86,86,86,86,86,86,85,85,85,85,85,85,85,85,85,85,85,85,84,84,84,84,84,84,84,84,84,84,84,84,84,84,83,83,83,83,83,83,83,83,83,83,83,83,83,82,82,82,82,82,82,82,82,82,82,82,82,82,82,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,74,74,74,74,74,74,74,74,74,74,74,74,74,74,74,74,74,74,74,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,71,71,71,71,71,71,71,71,71,71,71,71,71,71,71,71,71,71,71,71,71,70,70,70,70,70,70,70,70,70,70,70,70,70,70,70,70,70,70,70,70,70,70,70,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,67,67,67,67,67,67,67,67,67,67,67,67,67,67,67,67,67,67,67,67,67,67,67,67,67,67,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,62,62,62,62,62};
PROGMEM const int speed1[]={0,16562,3206,2164,1683,1397,1206,1067,962,878,810,754,706,665,629,598,570,545,523,503,484,467,452,438,425,412,401,390,380,371,362,354,346,339,332,325,318,313,307,301,296,291,286,282,277,273,269,265,261,257,254,250,247,244,241,238,235,232,229,227,224,222,219,217,215,213,210,208,206,204,202,200,199,197,195,193,192,190,188,187,185,184,182,181,179,178,177,175,174,173,172,170,169,168,167,166,165,163,162,161,160,159,158,157,156,155,155,154,153,152,151,150,149,148,148,147,146,145,144,144,143,142,142,141,140,139,139,138,137,137,136,135,135,134,134,133,132,132,131,131,130,129,129,128,128,127,127,126,126,125,125,124,124,123,123,122,122,121,121,121,120,120,119,119,118,118,117,117,117,116,116,115,115,115,114,114,114,113,113,112,112,112,111,111,111,110,110,110,109,109,109,108,108,108,107,107,107,106,106,106,106,105,105,105,104,104,104,104,103,103,103,102,102,102,102,101,101,101,101,100,100,100,100,99,99,99,99,98,98,98,98,98,97,97,97,97,96,96,96,96,96,95,95,95,95,95,94,94,94,94,94,93,93,93,93,93,92,92,92,92,92,91,91,91,91,91,91,90,90,90,90,90,90,89,89,89,89,89,89,88,88,88,88,88,88,87,87,87,87,87,87,87,86,86,86,86,86,86,86,85,85,85,85,85,85,85,85,84,84,84,84,84,84,84,83,83,83,83,83,83,83,83,83,82,82,82,82,82,82,82,82,81,81,81,81,81,81,81,81,81,80,80,80,80,80,80,80,80,80,80,79,79,79,79,79,79,79,79,79,79,78,78,78,78,78,78,78,78,78,78,77,77,77,77,77,77,77,77,77,77,77,77,76,76,76,76,76,76,76,76,76,76,76,76,75,75,75,75,75,75,75,75,75,75,75,75,75,75,74,74,74,74,74,74,74,74,74,74,74,74,74,74,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,71,71,71,71,71,71,71,71,71,71,71,71,71,71,71,71,71,71,70,70,70,70,70,70,70,70,70,70,70,70,70,70,70,70,70,70,70,70,70,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,68,67,67,67,67,67,67,67,67,67,67,67,67,67,67,67,67,67,67,67,67,67,67,67,67,67,67,67,67,67,67,67,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,62,63,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62,62};
PROGMEM const int speed2[]={0,14018,2721,1839,1432,1191,1029,912,823,753,695,648,607,573,543,516,493,472,453,436,421,407,394,382,370,360,351,342,333,325,318,311,305,298,292,287,282,276,272,267,263,258,254,251,247,243,240,237,233,230,227,225,222,219,217,214,212,210,207,205,203,201,199,197,195,193,191,190,188,186,185,183,182,180,179,177,176,174,173,172,171,169,168,167,166,165,164,162,161,160,159,158,157,156,155,155,154,153,152,151,150,149,148,148,147,146,145,145,144,143,142,142,141,140,140,139,138,138,137,137,136,135,135,134,134,133,133,132,131,131,130,130,129,129,128,128,127,127,126,126,126,125,125,124,124,123,123,122,122,122,121,121,120,120,120,119,119,119,118,118,118,117,117,116,116,116,115,115,115,115,114,114,114,113,113,113,112,112,112,111,111,111,111,110,110,110,110,109,109,109,108,108,108,108,108,107,107,107,107,106,106,106,106,105,105,105,105,105,104,104,104,104,103,103,103,103,103,102,102,102,102,102,101,101,101,101,101,101,100,100,100,100,100,99,99,99,99,99,99,99,98,98,98,98,98,98,97,97,97,97,97,97,96,96,96,96,96,96,96,95,95,95,95,95,95,95,95,94,94,94,94,94,94,94,94,93,93,93,93,93,93,93,93,92,92,92,92,92,92,92,92,92,91,91,91,91,91,91,91,91,91,90,90,90,90,90,90,90,90,90,90,90,89,89,89,89,89,89,89,89,89,89,88,88,88,88,88,88,88,88,88,88,88,88,87,87,87,87,87,87,87,87,87,87,87,87,87,86,86,86,86,86,86,86,86,86,86,86,86,86,86,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,76,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75,75};
PROGMEM const int speed3[]={0,8538,2272,1601,1281,1085,952,855,779,719,669,628,593,562,535,512,491,472,455,439,425,412,400,389,379,369,360,352,344,337,330,323,317,311,305,300,295,290,285,281,277,273,269,265,261,258,255,251,248,245,242,240,237,234,232,229,227,225,222,220,218,216,214,212,210,208,206,205,203,201,200,198,197,195,194,192,191,189,188,187,185,184,183,182,181,179,178,177,176,175,174,173,172,171,170,169,168,167,166,165,164,164,163,162,161,160,159,159,158,157,156,156,155,154,154,153,152,151,151,150,149,149,148,148,147,146,146,145,145,144,144,143,142,142,141,141,140,140,139,139,138,138,137,137,137,136,136,135,135,134,134,133,133,133,132,132,131,131,131,130,130,129,129,129,128,128,128,127,127,127,126,126,125,125,125,124,124,124,124,123,123,123,122,122,122,121,121,121,120,120,120,120,119,119,119,119,118,118,118,117,117,117,117,116,116,116,116,115,115,115,115,114,114,114,114,114,113,113,113,113,112,112,112,112,112,111,111,111,111,111,110,110,110,110,110,109,109,109,109,109,108,108,108,108,108,108,107,107,107,107,107,107,106,106,106,106,106,106,105,105,105,105,105,105,104,104,104,104,104,104,104,103,103,103,103,103,103,102,102,102,102,102,102,102,102,101,101,101,101,101,101,101,100,100,100,100,100,100,100,100,99,99,99,99,99,99,99,99,99,98,98,98,98,98,98,98,98,97,97,97,97,97,97,97,97,97,97,96,96,96,96,96,96,96,96,96,96,95,95,95,95,95,95,95,95,95,95,95,94,94,94,94,94,94,94,94,94,94,94,93,93,93,93,93,93,93,93,93,93,93,93,92,92,92,92,92,92,92,92,92,92,92,92,92,91,91,91,91,91,91,91,91,91,91,91,91,91,91,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,89,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,87,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,81,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,80,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,79,78,79,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,77,78,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77};
int i=0;
float scale;
#define STEPX 26
#define DIRX 16
#define ENABLE 12
#define STEPY 25
#define DIRY 27
#define STEPZ 25
#define DIRZ 14
#define SERVO 23
#define ledPin 2
const int* espTime=speed0;
int incr=1;
void setup()
{
pinMode(ENABLE, OUTPUT); // enable
pinMode(STEPY, OUTPUT); // stepY
pinMode(DIRY, OUTPUT); // dirY
digitalWrite(ENABLE, LOW);
Serial.begin(115200);
}
long t;
void loop()
{ for(int speed=5; speed<18; speed++) {
t=millis();
motion((3200),(20000),speed*160);
Serial.print(" T="); Serial.println(millis()-t);
delay(2000);
}
}
float t1, step_rate;
int e1, N;
void motion(int L, float a, float vm) { // move L steps, with a accel and vm as max speed for trapezoidal-like motion
t1=vm/a; // acceleration tim
e1=t1*vm/2; // number of steps for acceleration
if(L<2*e1) {e1=L/2; t1=sqrt(2*a*e1)/a; } // case of triangular motion
N=L-2*e1; // remaining steps for coasting at vm speed
//t1*=10; // pre-scale for table operation
Serial.print("t1="); Serial.print(t1); Serial.print(" e1="); Serial.print(e1); Serial.print(" N="); Serial.print(N);
accel(t1,e1);
coast(N);
decel(t1,e1);
}
void accel(float t1, int e1) {
// adapt the acceleration phase to last t1 seconds
for(i=0; i<e1; i++) {
delayMicroseconds((step_rate = whatDelay(i,e1)*t1*1000/e1));
digitalWrite(STEPY, HIGH);
digitalWrite(STEPY, LOW);
}
}
int whatDelay(int i, int e1) { // takes the number of actual step and total accel steps and returns the time from 0 to 2*PI
return pgm_read_word_near(speed3 + (i*1000/e1));
}
void coast(int N) {
for(i=0; i<N; i++) {
delayMicroseconds(step_rate);
digitalWrite(STEPY, HIGH);
digitalWrite(STEPY, LOW);
}
}
void decel(float t1, int e1) {
// adapt the acceleration phase to last t1 seconds
for(i=e1; i>0; i--) {
delayMicroseconds(whatDelay(i,e1)*t1*1000/e1);
digitalWrite(STEPY, HIGH);
digitalWrite(STEPY, LOW);
}
}
| [
"noreply@github.com"
] | noreply@github.com |
3057835637a4ddc60796da18006fc81f79583238 | 09eaf2b22ad39d284eea42bad4756a39b34da8a2 | /provas/xor-e-filhos/opentrains/010315/C/C.cpp | 2db08d194716c6b372008486490778d295b8b184 | [] | no_license | victorsenam/treinos | 186b70c44b7e06c7c07a86cb6849636210c9fc61 | 72a920ce803a738e25b6fc87efa32b20415de5f5 | refs/heads/master | 2021-01-24T05:58:48.713217 | 2018-10-14T13:51:29 | 2018-10-14T13:51:29 | 41,270,007 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,189 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef unsigned long long int ull;
typedef long long int ll;
#ifndef ONLINE_JUDGE
#define DEBUG(...) {fprintf(stderr, __VA_ARGS__);}
#else
#define DEBUG(...) {}
#endif
const int N = 1007;
int n, k;
int a[2][N];
int p[N];
bool b;
int cmp_t (int i, int j) {
if (a[!b][i] == a[!b][j])
return i < j;
return a[!b][i] < a[!b][j];
}
int main () {
scanf("%d %d", &n, &k);
for (int i = 0; i < n; i++) {
p[i] = i;
a[0][i] = a[1][i] = -1;
}
int i;
for (i = n-1; i+1; i--) {
b = (i&1);
sort(p+i+1, p+n, cmp_t);
int m = k;
int c = max((n-i+1)/2-1, 0);
for (int j = 0; j < i; j++)
a[b][j] = -1;
for (int j = i+1; j < n; j++) {
if (c > 0) {
a[b][p[j]] = a[!b][p[j]] + 1;
c--;
} else {
a[b][p[j]] = 0;
}
m -= a[b][p[j]];
}
a[b][i] = m;
if (m < 0)
for (int j = 0; j < n; j++)
a[b][j] = a[!b][j];
}
for (int j = 0; j < n; j++)
printf("%d ", a[0][j]);
printf("\n");
}
| [
"victorsenam@gmail.com"
] | victorsenam@gmail.com |
4b5e89abdd98a05bfabca293fd1e19fe1279da3e | 01a42b69633daf62a2eb3bb70c5b1b6e2639aa5f | /SCUM_BP_Magazine_MP5_classes.hpp | d1eecd595b79aec5feaf2c503236a934d7335e07 | [] | no_license | Kehczar/scum_sdk | 45db80e46dac736cc7370912ed671fa77fcb95cf | 8d1770b44321a9d0b277e4029551f39b11f15111 | refs/heads/master | 2022-07-25T10:06:20.892750 | 2020-05-21T11:45:36 | 2020-05-21T11:45:36 | 265,826,541 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 995 | hpp | #pragma once
// Scum 3.79.22573 (UE 4.24)
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace Classes
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_Magazine_MP5.BP_Magazine_MP5_C
// 0x0000 (0x06A8 - 0x06A8)
class ABP_Magazine_MP5_C : public AWeaponAttachmentMagazine
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_Magazine_MP5.BP_Magazine_MP5_C");
return ptr;
}
void SetAmmoCount(int* Amount);
void Server_InsertCartridgeIntoMagazine(class AAmmunitionItem** ammo);
void OnRep_AmmoCountOwnerHelper();
void OnRep_AmmoCount();
void OnAmmoChangedEvent();
void Multicast_SetLoadedVariables(int* ammoCount);
class UClass* GetProjectileClass();
int GetCapacity();
int GetAmmoCount();
void AddAmmo(int* Amount);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"65712402+Kehczar@users.noreply.github.com"
] | 65712402+Kehczar@users.noreply.github.com |
8c4b76e3ed17f290df973c83b07aca892df1add4 | 05c51c3090c2bc5f7816c5391efb5019c60c59a3 | /Progetto_Tirocinio/MazeMind/Classes/Player.h | 659fe95b1c54646c0935ec15bea708093426edf8 | [] | no_license | NicholasNapolitano/Progetto_Tirocinio | 6d024e42b51057aede69e9bc225dfdbb84de483d | 32df5496ac6c41a7a7b1f7fb1a339eb747af6877 | refs/heads/master | 2021-01-01T16:58:34.972821 | 2017-09-11T18:35:40 | 2017-09-11T18:35:40 | 97,965,900 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,303 | h | #ifndef __PLAYER_H__
#define __PLAYER_H__
#include "cocos2d.h"
#include "Enums.h"
USING_NS_CC;
class MapManager;
class Player : public cocos2d::Sprite
{
public:
static Player* create(const std::string& filename);
const State getState() const;
const char* getStateName() const;
void update(float dt) override;
void input(State input);
void setMovingState(Moving state);
void StartGoingUp();
void StartGoingDown();
void StartGoingLeft();
void StartGoingRight();
bool beCarefulLeft(Point position);
bool beCarefulRight(Point position);
bool beCarefulUp(Point position);
bool beCarefulDown(Point position);
bool beCarefulLeftUp(Point position);
bool beCarefulRightUp(Point position);
bool beCarefulLeftDown(Point position);
bool beCarefulRightDown(Point position);
void setDestination(Point destination);
void setMappa(int** mappa);
Point getDestination();
void controlPosition(Point position);
void setMapGame(MapManager* mapGame);
void SetPreviousState(State state);
void followTheWall();
bool Solve(int x, int y);
Player* getPlayer();
protected:
void SetState(State state);
Point destination;
private:
State _state;
Moving MState;
MapManager* mapGame;
State previousState;
int** mappa;
std::list<Point> path;
float deltaTime;
};
#endif // __PLAYER_H__ | [
"dark.rai95@hotmail.it"
] | dark.rai95@hotmail.it |
02c7c85766119e61b8581a934cfcffc9e34ab7b5 | c32b9b623fc526c8394aa4316eaca719718142a7 | /Break It/SIMON/475team27/475team27/uberzahl/uberzahl.h | 5ee1de5ef05d0eeac63ff1ab41566d152e3d7f8b | [] | no_license | codycann/eecs475_dsa | 358190ada878bf53b218b2c6fe0b3d66ce9b5243 | b5c4b3d11a4e7af7a9404414c86d08bb24daac22 | refs/heads/master | 2020-05-18T21:00:20.682064 | 2014-04-25T09:04:02 | 2014-04-25T09:04:02 | 18,195,353 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,812 | h | #ifndef UBERZAHL_H
#define UBERZAHL_H
#include<iostream>
#include<string>
#include<vector>
#include<climits>
//#include<gmpxx.h>
// CONFIGURATIONS :
// smallType is used for storage -- uberzahl.value[i]
// * Adjusting this will adjust the memory efficiency
// * For most efficient use of memory use your processor's word size
// mediumType and largeType should be capable of holding 2x MAX(smallType)
// * These are used mainly for bit manipulation
#define smallType unsigned int
#define mediumType unsigned long long
#define largeType unsigned long long
// maxBits controls how many bits to use our of your smallType container
// you must ensure that maxBits <= BITLEN(smallType)
#define maxBits 32
// mask is used to truncate numbers to the correct bitlength
// mask must be a value of all 1's maxBits long
#define mask 0xffffffffL
// RAND_MAX can be different between compilers and so it is handled here
// If your RAND_MAX is different from below (not 16, 32, 64 bit) you should add it below
// and compile with the correct RAND_MAX length
// ( specifying a smaller RAND_MAX than you have will result in a non-uniform distribution
#if RAND_MAX == 32767
#define RAND_BITS 16
#elif RAND_MAX == 2147483647
#define RAND_BITS 32
#else
#define RAND_BITS 64
#endif
// UBERZAHL CLASS DEFINITION :
class uberzahl {
public:
uberzahl ( void );
~uberzahl ( void );
uberzahl ( const char* );
uberzahl ( largeType );
uberzahl ( const uberzahl& );
// uberzahl( const mpz_class& );
const uberzahl& operator = ( const uberzahl& );
// uses the rand function - to seed use srand (unsigned int seed);
uberzahl random ( mediumType );
friend std::ostream& operator << ( std::ostream&, const uberzahl& );
// standard arithmetic operations
uberzahl operator + ( const uberzahl& ) const;
uberzahl operator - ( const uberzahl& ) const;
uberzahl operator * ( const uberzahl& ) const;
uberzahl operator / ( const uberzahl& ) const;
uberzahl operator / ( smallType ) const;
uberzahl operator % ( const uberzahl& ) const;
smallType operator % ( smallType ) const;
uberzahl exp ( const uberzahl& ) const;
uberzahl expm( const uberzahl&, const uberzahl& ) const;
// standard numeric comparators
bool operator > ( const uberzahl& ) const;
bool operator < ( const uberzahl& ) const;
bool operator >= ( const uberzahl& ) const;
bool operator <= ( const uberzahl& ) const;
bool operator == ( const uberzahl& ) const;
// bool operator == ( const mpz_class& ) const;
bool operator != ( const uberzahl& ) const;
// standard c/c++ bitwize operators
uberzahl operator | ( const uberzahl& ) const;
uberzahl operator & ( const uberzahl& ) const;
uberzahl operator ^ ( const uberzahl& ) const;
uberzahl operator >> ( smallType ) const;
uberzahl operator << ( smallType ) const;
uberzahl extract ( smallType, smallType );
uberzahl rotateLeft ( smallType, smallType, smallType );
uberzahl rotateRight ( smallType, smallType, smallType );
void setBit ( smallType );
void clearBit ( smallType );
void toggleBit ( smallType );
// auxilary functions
uberzahl inverse ( const uberzahl& ) const;
uberzahl gcd ( const uberzahl& ) const;
smallType bit ( mediumType ) const;
smallType bitLength ( void ) const;
private:
std::vector<smallType> value;
void convert_to_numeric ( const char* );
std::string convert_to_string ( void ) const;
void clean_bits ( void );
std::pair<std::pair<uberzahl,uberzahl>,bool> inverse ( const uberzahl&, const uberzahl& ) const;
};
uberzahl random ( const uberzahl&, const uberzahl& );
bool rabinmiller ( const uberzahl&, unsigned int );
uberzahl nextprime ( const uberzahl&, unsigned int );
#endif
| [
"kevin@krakauer.org"
] | kevin@krakauer.org |
bfafa228f883d152e398a7916315010f054c4dbd | d8e55486f7aeb3050003007d3fbe6da834e17284 | /Cursen/Handle/Handle.cpp | 7cbadfcb957570ea91c20e583ce46e06c8877bd4 | [] | no_license | bmartin5263/Cursen | 1572aa0570fb27bf18d18dff8444e251d363193d | 30f6296ecdb9da8ac863b315646cd34cfe3181d9 | refs/heads/master | 2022-01-28T09:41:19.657134 | 2022-01-03T05:54:54 | 2022-01-03T05:54:54 | 158,553,592 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 737 | cpp | //
// Created by Brandon Martin on 5/29/19.
//
#include <assert.h>
#include "Handle.h"
#include "Cursen/Drawing/TerminalManager.h"
#include "HandleManager.h"
Handle::Handle()
{
HandleStatus status = HandleManager::ActivateHandle(this->id, this->index);
assert(status == HandleStatus::Success);
cursen::TerminalManager::Flash();
}
Handle::~Handle()
{
HandleManager::InvalidateHandle(*this);
}
unsigned int Handle::getId() const
{
return this->id;
}
unsigned int Handle::getIndex() const
{
return this->index;
}
HandleStatus Handle::IsValid(Handle &handle)
{
return HandleManager::IsValid(handle);
}
HandleStatus Handle::Invalidate(Handle &handle)
{
return HandleManager::InvalidateHandle(handle);
} | [
"bsm2112@yahoo.com"
] | bsm2112@yahoo.com |
04f1e8a9e37569b836ba0dc4e2ed4ab1f2d7a197 | 473bf1956ff0ab848a51f563cf5e90e7c1c3b698 | /Unreal/CarlaUE4/Plugins/Carla/Source/Carla/MapGen/GraphTypes.h | f332636a860216c134ca963df8e87de319823b37 | [
"MIT",
"CC-BY-4.0"
] | permissive | danielsuo/carla | 1704f7736069b58d521e7d069431369180842064 | adbd696869bcb3866df202931ce39641150ea5d9 | refs/heads/master | 2021-08-23T22:05:23.436206 | 2017-12-06T19:39:16 | 2017-12-06T19:39:16 | 113,339,366 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,452 | h | // Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma
// de Barcelona (UAB), and the INTEL Visual Computing Lab.
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.
#pragma once
#include "CityMapDefinitions.h"
#include <vector>
namespace MapGen {
#ifdef CARLA_ROAD_GENERATOR_EXTRA_LOG
/// For debug only purposes.
template <char C>
struct DataIndex : private NonCopyable
{
DataIndex() : index(++NEXT_INDEX) {}
static void ResetIndex() {
NEXT_INDEX = 0u;
}
template <typename OSTREAM>
friend OSTREAM &operator<<(OSTREAM &os, const DataIndex &d) {
os << C << d.index;
return os;
}
// private:
uint32 index = 0u;
static uint32 NEXT_INDEX;
};
# define INHERIT_GRAPH_TYPE_BASE_CLASS(c) : public DataIndex<c>
#else
# define INHERIT_GRAPH_TYPE_BASE_CLASS(c) : private NonCopyable
#endif // CARLA_ROAD_GENERATOR_EXTRA_LOG
struct GraphNode INHERIT_GRAPH_TYPE_BASE_CLASS('n')
{
uint32 EdgeCount;
bool bIsIntersection = true; // at this point every node is an intersection.
EIntersectionType IntersectionType;
float Rotation;
std::vector<float> Rots;
};
struct GraphHalfEdge INHERIT_GRAPH_TYPE_BASE_CLASS('e')
{
float Angle;
};
struct GraphFace INHERIT_GRAPH_TYPE_BASE_CLASS('f')
{
};
#undef INHERIT_GRAPH_TYPE_BASE_CLASS
} // namespace MapGen
| [
"nsubiron@cvc.uab.es"
] | nsubiron@cvc.uab.es |
4725b17105e8070811f7bfd9b821db12df6ef45a | a527c3ffe236ce0aed5f1fca1b1950b64d1cdcac | /simulator/src/cuda-sim/ptx_sim.h | e680016c6884af3044d46c65b15ad04d3c39296e | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | csl-iisc/SBRP-ASPLOS23 | a9ad1463a6e738b1a93806c09e31e4e4eb719665 | 0ce2de799f4ac18608ed2a01546fbeee457e5490 | refs/heads/main | 2023-04-14T06:13:28.967789 | 2023-03-22T23:00:12 | 2023-03-22T23:00:12 | 553,858,319 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,674 | h | // Copyright (c) 2009-2011, The University of British Columbia
// 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 University of British Columbia 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.
#ifndef ptx_sim_h_INCLUDED
#define ptx_sim_h_INCLUDED
#include <stdlib.h>
#include "../abstract_hardware_model.h"
#include "../tr1_hash_map.h"
#include "half.h"
#include <assert.h>
#include "opcodes.h"
#include <list>
#include <map>
#include <set>
#include <string>
#include "memory.h"
#define GCC_VERSION \
(__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
struct param_t {
const void *pdata;
int type;
size_t size;
size_t offset;
};
#include <stack>
#include "memory.h"
using half_float::half;
union ptx_reg_t {
ptx_reg_t() {
bits.ms = 0;
bits.ls = 0;
u128.low = 0;
u128.lowest = 0;
u128.highest = 0;
u128.high = 0;
s8 = 0;
s16 = 0;
s32 = 0;
s64 = 0;
u8 = 0;
u16 = 0;
u64 = 0;
f16 = 0;
f32 = 0;
f64 = 0;
pred = 0;
}
ptx_reg_t(unsigned x) {
bits.ms = 0;
bits.ls = 0;
u128.low = 0;
u128.lowest = 0;
u128.highest = 0;
u128.high = 0;
s8 = 0;
s16 = 0;
s32 = 0;
s64 = 0;
u8 = 0;
u16 = 0;
u64 = 0;
f16 = 0;
f32 = 0;
f64 = 0;
pred = 0;
u32 = x;
}
operator unsigned int() { return u32; }
operator unsigned short() { return u16; }
operator unsigned char() { return u8; }
operator unsigned long long() { return u64; }
void mask_and(unsigned ms, unsigned ls) {
bits.ms &= ms;
bits.ls &= ls;
}
void mask_or(unsigned ms, unsigned ls) {
bits.ms |= ms;
bits.ls |= ls;
}
int get_bit(unsigned bit) {
if (bit < 32)
return (bits.ls >> bit) & 1;
else
return (bits.ms >> (bit - 32)) & 1;
}
signed char s8;
signed short s16;
signed int s32;
signed long long s64;
unsigned char u8;
unsigned short u16;
unsigned int u32;
unsigned long long u64;
// gcc 4.7.0
#if GCC_VERSION >= 40700
half f16;
#else
float f16;
#endif
float f32;
double f64;
struct {
unsigned ls;
unsigned ms;
} bits;
struct {
unsigned int lowest;
unsigned int low;
unsigned int high;
unsigned int highest;
} u128;
unsigned pred : 4;
};
class ptx_instruction;
class operand_info;
class symbol_table;
class function_info;
class ptx_thread_info;
class ptx_cta_info {
public:
ptx_cta_info(unsigned sm_idx, gpgpu_context *ctx);
void add_thread(ptx_thread_info *thd);
unsigned num_threads() const;
void check_cta_thread_status_and_reset();
void register_thread_exit(ptx_thread_info *thd);
void register_deleted_thread(ptx_thread_info *thd);
unsigned get_sm_idx() const;
unsigned get_bar_threads() const;
void inc_bar_threads();
void reset_bar_threads();
private:
// backward pointer
class gpgpu_context *gpgpu_ctx;
unsigned m_bar_threads;
unsigned long long m_uid;
unsigned m_sm_idx;
std::set<ptx_thread_info *> m_threads_in_cta;
std::set<ptx_thread_info *> m_threads_that_have_exited;
std::set<ptx_thread_info *> m_dangling_pointers;
};
class ptx_warp_info {
public:
ptx_warp_info(); // add get_core or something, or threads?
unsigned get_done_threads() const;
void inc_done_threads();
void reset_done_threads();
private:
unsigned m_done_threads;
};
class symbol;
struct stack_entry {
stack_entry() {
m_symbol_table = NULL;
m_func_info = NULL;
m_PC = 0;
m_RPC = -1;
m_return_var_src = NULL;
m_return_var_dst = NULL;
m_call_uid = 0;
m_valid = false;
}
stack_entry(symbol_table *s, function_info *f, unsigned pc, unsigned rpc,
const symbol *return_var_src, const symbol *return_var_dst,
unsigned call_uid) {
m_symbol_table = s;
m_func_info = f;
m_PC = pc;
m_RPC = rpc;
m_return_var_src = return_var_src;
m_return_var_dst = return_var_dst;
m_call_uid = call_uid;
m_valid = true;
}
bool m_valid;
symbol_table *m_symbol_table;
function_info *m_func_info;
unsigned m_PC;
unsigned m_RPC;
const symbol *m_return_var_src;
const symbol *m_return_var_dst;
unsigned m_call_uid;
};
class ptx_version {
public:
ptx_version() {
m_valid = false;
m_ptx_version = 0;
m_ptx_extensions = 0;
m_sm_version_valid = false;
m_texmode_unified = true;
m_map_f64_to_f32 = true;
}
ptx_version(float ver, unsigned extensions) {
m_valid = true;
m_ptx_version = ver;
m_ptx_extensions = extensions;
m_sm_version_valid = false;
m_texmode_unified = true;
}
void set_target(const char *sm_ver, const char *ext, const char *ext2) {
assert(m_valid);
m_sm_version_str = sm_ver;
check_target_extension(ext);
check_target_extension(ext2);
sscanf(sm_ver, "%u", &m_sm_version);
m_sm_version_valid = true;
}
float ver() const {
assert(m_valid);
return m_ptx_version;
}
unsigned target() const {
assert(m_valid && m_sm_version_valid);
return m_sm_version;
}
unsigned extensions() const {
assert(m_valid);
return m_ptx_extensions;
}
private:
void check_target_extension(const char *ext) {
if (ext) {
if (!strcmp(ext, "texmode_independent"))
m_texmode_unified = false;
else if (!strcmp(ext, "texmode_unified"))
m_texmode_unified = true;
else if (!strcmp(ext, "map_f64_to_f32"))
m_map_f64_to_f32 = true;
else
abort();
}
}
bool m_valid;
float m_ptx_version;
unsigned m_sm_version_valid;
std::string m_sm_version_str;
bool m_texmode_unified;
bool m_map_f64_to_f32;
unsigned m_sm_version;
unsigned m_ptx_extensions;
};
class ptx_thread_info {
public:
~ptx_thread_info();
ptx_thread_info(kernel_info_t &kernel);
void init(gpgpu_t *gpu, core_t *core, unsigned sid, unsigned cta_id,
unsigned wid, unsigned tid, bool fsim) {
m_gpu = gpu;
m_core = core;
m_hw_sid = sid;
m_hw_ctaid = cta_id;
m_hw_wid = wid;
m_hw_tid = tid;
m_functionalSimulationMode = fsim;
}
void ptx_fetch_inst(inst_t &inst) const;
void ptx_exec_inst(warp_inst_t &inst, unsigned lane_id);
const ptx_version &get_ptx_version() const;
void set_reg(const symbol *reg, const ptx_reg_t &value);
void print_reg_thread(char *fname);
void resume_reg_thread(char *fname, symbol_table *symtab);
ptx_reg_t get_reg(const symbol *reg);
ptx_reg_t get_operand_value(const operand_info &op, operand_info dstInfo,
unsigned opType, ptx_thread_info *thread,
int derefFlag);
void set_operand_value(const operand_info &dst, const ptx_reg_t &data,
unsigned type, ptx_thread_info *thread,
const ptx_instruction *pI);
void set_operand_value(const operand_info &dst, const ptx_reg_t &data,
unsigned type, ptx_thread_info *thread,
const ptx_instruction *pI, int overflow, int carry);
void get_vector_operand_values(const operand_info &op, ptx_reg_t *ptx_regs,
unsigned num_elements);
void set_vector_operand_values(const operand_info &dst,
const ptx_reg_t &data1, const ptx_reg_t &data2,
const ptx_reg_t &data3,
const ptx_reg_t &data4);
void set_wmma_vector_operand_values(
const operand_info &dst, const ptx_reg_t &data1, const ptx_reg_t &data2,
const ptx_reg_t &data3, const ptx_reg_t &data4, const ptx_reg_t &data5,
const ptx_reg_t &data6, const ptx_reg_t &data7, const ptx_reg_t &data8);
function_info *func_info() { return m_func_info; }
void print_insn(unsigned pc, FILE *fp) const;
void set_info(function_info *func);
unsigned get_uid() const { return m_uid; }
dim3 get_ctaid() const { return m_ctaid; }
dim3 get_tid() const { return m_tid; }
dim3 get_ntid() const { return m_ntid; }
class gpgpu_sim *get_gpu() {
return (gpgpu_sim *)m_gpu;
}
unsigned get_hw_tid() const { return m_hw_tid; }
unsigned get_hw_ctaid() const { return m_hw_ctaid; }
unsigned get_hw_wid() const { return m_hw_wid; }
unsigned get_hw_sid() const { return m_hw_sid; }
core_t *get_core() { return m_core; }
unsigned get_icount() const { return m_icount; }
void set_valid() { m_valid = true; }
addr_t last_eaddr() const { return m_last_effective_address; }
memory_space_t last_space() const { return m_last_memory_space; }
dram_callback_t last_callback() const { return m_last_dram_callback; }
unsigned long long get_cta_uid() { return m_cta_info->get_sm_idx(); }
void set_single_thread_single_block() {
m_ntid.x = 1;
m_ntid.y = 1;
m_ntid.z = 1;
m_ctaid.x = 0;
m_ctaid.y = 0;
m_ctaid.z = 0;
m_tid.x = 0;
m_tid.y = 0;
m_tid.z = 0;
m_nctaid.x = 1;
m_nctaid.y = 1;
m_nctaid.z = 1;
m_gridid = 0;
m_valid = true;
}
void set_tid(dim3 tid) { m_tid = tid; }
void cpy_tid_to_reg(dim3 tid);
void set_ctaid(dim3 ctaid) { m_ctaid = ctaid; }
void set_ntid(dim3 tid) { m_ntid = tid; }
void set_nctaid(dim3 cta_size) { m_nctaid = cta_size; }
unsigned get_builtin(int builtin_id, unsigned dim_mod);
void set_done();
bool is_done() { return m_thread_done; }
unsigned donecycle() const { return m_cycle_done; }
unsigned next_instr() {
m_icount++;
m_branch_taken = false;
return m_PC;
}
bool branch_taken() const { return m_branch_taken; }
unsigned get_pc() const { return m_PC; }
void set_npc(unsigned npc) { m_NPC = npc; }
void set_npc(const function_info *f);
void callstack_push(unsigned npc, unsigned rpc, const symbol *return_var_src,
const symbol *return_var_dst, unsigned call_uid);
bool callstack_pop();
void callstack_push_plus(unsigned npc, unsigned rpc,
const symbol *return_var_src,
const symbol *return_var_dst, unsigned call_uid);
bool callstack_pop_plus();
void dump_callstack() const;
std::string get_location() const;
const ptx_instruction *get_inst() const;
const ptx_instruction *get_inst(addr_t pc) const;
bool rpc_updated() const { return m_RPC_updated; }
bool last_was_call() const { return m_last_was_call; }
unsigned get_rpc() const { return m_RPC; }
void clearRPC() {
m_RPC = -1;
m_RPC_updated = false;
m_last_was_call = false;
}
unsigned get_return_PC() { return m_callstack.back().m_PC; }
void update_pc() { m_PC = m_NPC; }
void dump_regs(FILE *fp);
void dump_modifiedregs(FILE *fp);
void clear_modifiedregs() {
m_debug_trace_regs_modified.back().clear();
m_debug_trace_regs_read.back().clear();
}
function_info *get_finfo() { return m_func_info; }
const function_info *get_finfo() const { return m_func_info; }
void push_breakaddr(const operand_info &breakaddr);
const operand_info &pop_breakaddr();
void enable_debug_trace() { m_enable_debug_trace = true; }
unsigned get_local_mem_stack_pointer() const {
return m_local_mem_stack_pointer;
}
memory_space *get_global_memory() { return m_gpu->get_global_memory(); }
memory_space *get_tex_memory() { return m_gpu->get_tex_memory(); }
memory_space *get_surf_memory() { return m_gpu->get_surf_memory(); }
memory_space *get_param_memory() { return m_kernel.get_param_memory(); }
const gpgpu_functional_sim_config &get_config() const {
return m_gpu->get_config();
}
bool isInFunctionalSimulationMode() { return m_functionalSimulationMode; }
void exitCore() {
// m_core is not used in case of functional simulation mode
if (!m_functionalSimulationMode) m_core->warp_exit(m_hw_wid);
}
void registerExit() { m_cta_info->register_thread_exit(this); }
unsigned get_reduction_value(unsigned ctaid, unsigned barid) {
return m_core->get_reduction_value(ctaid, barid);
}
void and_reduction(unsigned ctaid, unsigned barid, bool value) {
m_core->and_reduction(ctaid, barid, value);
}
void or_reduction(unsigned ctaid, unsigned barid, bool value) {
m_core->or_reduction(ctaid, barid, value);
}
void popc_reduction(unsigned ctaid, unsigned barid, bool value) {
m_core->popc_reduction(ctaid, barid, value);
}
// Jin: get corresponding kernel grid for CDP purpose
kernel_info_t &get_kernel() { return m_kernel; }
public:
addr_t m_last_effective_address;
bool m_branch_taken;
memory_space_t m_last_memory_space;
dram_callback_t m_last_dram_callback;
memory_space *m_shared_mem;
memory_space *m_sstarr_mem;
memory_space *m_local_mem;
ptx_warp_info *m_warp_info;
ptx_cta_info *m_cta_info;
ptx_reg_t m_last_set_operand_value;
private:
bool m_functionalSimulationMode;
unsigned m_uid;
kernel_info_t &m_kernel;
core_t *m_core;
gpgpu_t *m_gpu;
bool m_valid;
dim3 m_ntid;
dim3 m_tid;
dim3 m_nctaid;
dim3 m_ctaid;
unsigned m_gridid;
bool m_thread_done;
unsigned m_hw_sid;
unsigned m_hw_tid;
unsigned m_hw_wid;
unsigned m_hw_ctaid;
unsigned m_icount;
unsigned m_PC;
unsigned m_NPC;
unsigned m_RPC;
bool m_RPC_updated;
bool m_last_was_call;
unsigned m_cycle_done;
int m_barrier_num;
bool m_at_barrier;
symbol_table *m_symbol_table;
function_info *m_func_info;
std::list<stack_entry> m_callstack;
unsigned m_local_mem_stack_pointer;
typedef tr1_hash_map<const symbol *, ptx_reg_t> reg_map_t;
std::list<reg_map_t> m_regs;
std::list<reg_map_t> m_debug_trace_regs_modified;
std::list<reg_map_t> m_debug_trace_regs_read;
bool m_enable_debug_trace;
std::stack<class operand_info, std::vector<operand_info> > m_breakaddrs;
};
addr_t generic_to_local(unsigned smid, unsigned hwtid, addr_t addr);
addr_t generic_to_shared(unsigned smid, addr_t addr);
addr_t generic_to_global(addr_t addr);
addr_t local_to_generic(unsigned smid, unsigned hwtid, addr_t addr);
addr_t shared_to_generic(unsigned smid, addr_t addr);
addr_t global_to_generic(addr_t addr);
bool isspace_local(unsigned smid, unsigned hwtid, addr_t addr);
bool isspace_shared(unsigned smid, addr_t addr);
bool isspace_global(addr_t addr);
bool is_pm(addr_t addr);
memory_space_t whichspace(addr_t addr);
extern unsigned g_ptx_thread_info_uid_next;
#endif
| [
"akamath1997@gmail.com"
] | akamath1997@gmail.com |
93b83276f197900d6ad3171da7b634dd8ed35790 | 3efc50ba20499cc9948473ee9ed2ccfce257d79a | /data/code-jam/files/635101_ianchou_563117_1_extracted_pa.cpp | 2b139616e08428a0d6570daf9f9e52fa96ff3cf5 | [] | no_license | arthurherbout/crypto_code_detection | 7e10ed03238278690d2d9acaa90fab73e52bab86 | 3c9ff8a4b2e4d341a069956a6259bf9f731adfc0 | refs/heads/master | 2020-07-29T15:34:31.380731 | 2019-12-20T13:52:39 | 2019-12-20T13:52:39 | 209,857,592 | 9 | 4 | null | 2019-12-20T13:52:42 | 2019-09-20T18:35:35 | C | UTF-8 | C++ | false | false | 748 | cpp | #include<map>
#include<iostream>
#include<string>
using namespace std;
map<string, int> path;
int main(void){
int t,n,m,ans;
string q,s;
cin>>t;
for(int z=1;z<=t;++z){
ans = 0;
path.clear();
cin>>n>>m;
for(int i=0;i<n;++i){
cin>>q;
for(int i=1;i<=q.size();++i){
if(q[i]=='/' || i==q.size())
path[q.substr(0,i)] = 1;
}
}
for(int i=0;i<m;++i){
cin>>q;
for(int i=1;i<=q.size();++i){
if(q[i]=='/' || i==q.size()){
s = q.substr(0,i);
if(path.find(s) == path.end()){
++ans;
path[s] = 1;
}
}
}
}
cout<<"Case #"<<z<<": " <<ans<<endl;
}
return 0;
}
| [
"arthurherbout@gmail.com"
] | arthurherbout@gmail.com |
d5092a3acc52667fde77a7864d30670e67a4086c | e759e684c8b799a2363f435e49ea99cd6d356870 | /control/actuator.h | d80bcd7e746254516db9519c7569ad068672af7e | [] | no_license | Jorjor70/meuh | 56e115c107cc82bfc42dbfefef1101e64b34c3b5 | 0e2ee0227281c08f6e1dd8c892c03b162d3802dc | refs/heads/master | 2021-01-18T10:10:26.416036 | 2013-01-30T12:01:30 | 2013-01-30T12:01:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 698 | h | #ifndef CONTROL_ACTUATOR_H
#define CONTROL_ACTUATOR_H
#include <math/types.h>
#include <sparse/linear/dimension.h>
#include <map>
#include <phys/dof.h>
namespace control {
struct dof;
struct actuator {
const math::natural dim;
actuator( math::natural n );
typedef const actuator* key;
typedef std::map<key, math::vec> vector;
typedef std::map<phys::dof::key, math::mat> row;
typedef std::map<key, row> matrix;
typedef vector bounds;
struct pack {
const actuator::matrix& matrix;
const actuator::bounds& bounds;
};
};
}
namespace sparse {
namespace linear {
math::natural dim(control::actuator::key d);
}
}
#endif
| [
"maxime.tournier@inria.fr"
] | maxime.tournier@inria.fr |
6c716be6965c1669277420656246b7649759c37b | 633514319d7693d1143fbf8a4e25bebf6965e732 | /myStar/Classes/LayerHudControl.h | 2783104f133407286244819415830b7424d6aa17 | [] | no_license | sdycxxl2010/voyage | e4562fdc4167a674cb44c9510db2d383328bba3e | d1115797124fbd71c86253c012ffe21e547d4a14 | refs/heads/master | 2021-05-03T22:26:49.052599 | 2018-07-05T02:43:08 | 2018-07-05T02:43:08 | 120,390,464 | 2 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 598 | h | #pragma once
#include "cocos2d.h"
USING_NS_CC ;
#include "cocostudio/CocoStudio.h"
using namespace cocostudio;
#include "ui/CocosGUI.h"
using namespace cocos2d::ui;
#include <unordered_map>
using namespace std ;
class LayerMapWalk ;
class LayerHudControl :
public Layer
{
public:
LayerHudControl( );
~LayerHudControl( );
public:
CREATE_FUNC( LayerHudControl ) ;
bool init( ) ;
public:
LayerMapWalk * m_pLayerMapWalk ;
Text *m_pTxtInfo ;
Text *m_pTxtInfo2 ;
// ×Ö·û´®±í
unordered_map< string , string> m_StringList ;
};
| [
"sdycxxl2010"
] | sdycxxl2010 |
2efbd2d7bfde57ff281ac1b8720a51c37aeb2a10 | 786de89be635eb21295070a6a3452f3a7fe6712c | /psddl_hdf2psana/tags/V00-01-17/src/evr.ddl.cpp | a795c10b56feccbd0f25f131ba919d9f982a86eb | [] | no_license | connectthefuture/psdmrepo | 85267cfe8d54564f99e17035efe931077c8f7a37 | f32870a987a7493e7bf0f0a5c1712a5a030ef199 | refs/heads/master | 2021-01-13T03:26:35.494026 | 2015-09-03T22:22:11 | 2015-09-03T22:22:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 74,049 | cpp |
// *** Do not edit this file, it is auto-generated ***
#include "psddl_hdf2psana/evr.ddl.h"
#include "hdf5pp/ArrayType.h"
#include "hdf5pp/CompoundType.h"
#include "hdf5pp/EnumType.h"
#include "hdf5pp/VlenType.h"
#include "hdf5pp/Utils.h"
#include "PSEvt/DataProxy.h"
#include "psddl_hdf2psana/evr.ddlm.h"
#include "psddl_hdf2psana/evr.ddlm.h"
namespace psddl_hdf2psana {
namespace EvrData {
hdf5pp::Type ns_PulseConfig_v0_dataset_data_stored_type()
{
typedef ns_PulseConfig_v0::dataset_data DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("pulse", offsetof(DsType, pulse), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("_input_control_value", offsetof(DsType, _input_control_value), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("_output_control_value", offsetof(DsType, _output_control_value), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("polarity", offsetof(DsType, polarity), hdf5pp::TypeTraits<uint8_t>::stored_type());
type.insert("map_set_enable", offsetof(DsType, map_set_enable), hdf5pp::TypeTraits<uint8_t>::stored_type());
type.insert("map_reset_enable", offsetof(DsType, map_reset_enable), hdf5pp::TypeTraits<uint8_t>::stored_type());
type.insert("map_trigger_enable", offsetof(DsType, map_trigger_enable), hdf5pp::TypeTraits<uint8_t>::stored_type());
type.insert("prescale", offsetof(DsType, prescale), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("delay", offsetof(DsType, delay), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("width", offsetof(DsType, width), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("trigger", offsetof(DsType, trigger), hdf5pp::TypeTraits<int16_t>::stored_type());
type.insert("set", offsetof(DsType, set), hdf5pp::TypeTraits<int16_t>::stored_type());
type.insert("clear", offsetof(DsType, clear), hdf5pp::TypeTraits<int16_t>::stored_type());
return type;
}
hdf5pp::Type ns_PulseConfig_v0::dataset_data::stored_type()
{
static hdf5pp::Type type = ns_PulseConfig_v0_dataset_data_stored_type();
return type;
}
hdf5pp::Type ns_PulseConfig_v0_dataset_data_native_type()
{
typedef ns_PulseConfig_v0::dataset_data DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("pulse", offsetof(DsType, pulse), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("_input_control_value", offsetof(DsType, _input_control_value), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("_output_control_value", offsetof(DsType, _output_control_value), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("polarity", offsetof(DsType, polarity), hdf5pp::TypeTraits<uint8_t>::native_type());
type.insert("map_set_enable", offsetof(DsType, map_set_enable), hdf5pp::TypeTraits<uint8_t>::native_type());
type.insert("map_reset_enable", offsetof(DsType, map_reset_enable), hdf5pp::TypeTraits<uint8_t>::native_type());
type.insert("map_trigger_enable", offsetof(DsType, map_trigger_enable), hdf5pp::TypeTraits<uint8_t>::native_type());
type.insert("prescale", offsetof(DsType, prescale), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("delay", offsetof(DsType, delay), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("width", offsetof(DsType, width), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("trigger", offsetof(DsType, trigger), hdf5pp::TypeTraits<int16_t>::native_type());
type.insert("set", offsetof(DsType, set), hdf5pp::TypeTraits<int16_t>::native_type());
type.insert("clear", offsetof(DsType, clear), hdf5pp::TypeTraits<int16_t>::native_type());
return type;
}
hdf5pp::Type ns_PulseConfig_v0::dataset_data::native_type()
{
static hdf5pp::Type type = ns_PulseConfig_v0_dataset_data_native_type();
return type;
}
ns_PulseConfig_v0::dataset_data::dataset_data()
{
}
ns_PulseConfig_v0::dataset_data::~dataset_data()
{
}
boost::shared_ptr<Psana::EvrData::PulseConfig>
Proxy_PulseConfig_v0::getTypedImpl(PSEvt::ProxyDictI* dict, const Pds::Src& source, const std::string& key)
{
if (not m_data) {
boost::shared_ptr<EvrData::ns_PulseConfig_v0::dataset_data> ds_data = hdf5pp::Utils::readGroup<EvrData::ns_PulseConfig_v0::dataset_data>(m_group, "data", m_idx);
m_data.reset(new PsanaType(ds_data->pulse, ds_data->trigger, ds_data->set, ds_data->clear, ds_data->polarity, ds_data->map_set_enable, ds_data->map_reset_enable, ds_data->map_trigger_enable, ds_data->prescale, ds_data->delay, ds_data->width));
}
return m_data;
}
boost::shared_ptr<PSEvt::Proxy<Psana::EvrData::PulseConfig> > make_PulseConfig(int version, hdf5pp::Group group, hsize_t idx) {
switch (version) {
case 0:
return boost::make_shared<Proxy_PulseConfig_v0>(group, idx);
default:
return boost::make_shared<PSEvt::DataProxy<Psana::EvrData::PulseConfig> >(boost::shared_ptr<Psana::EvrData::PulseConfig>());
}
}
hdf5pp::Type ns_PulseConfigV3_v0_dataset_data_stored_type()
{
typedef ns_PulseConfigV3_v0::dataset_data DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("pulseId", offsetof(DsType, pulseId), hdf5pp::TypeTraits<uint16_t>::stored_type());
type.insert("polarity", offsetof(DsType, polarity), hdf5pp::TypeTraits<uint16_t>::stored_type());
type.insert("prescale", offsetof(DsType, prescale), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("delay", offsetof(DsType, delay), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("width", offsetof(DsType, width), hdf5pp::TypeTraits<uint32_t>::stored_type());
return type;
}
hdf5pp::Type ns_PulseConfigV3_v0::dataset_data::stored_type()
{
static hdf5pp::Type type = ns_PulseConfigV3_v0_dataset_data_stored_type();
return type;
}
hdf5pp::Type ns_PulseConfigV3_v0_dataset_data_native_type()
{
typedef ns_PulseConfigV3_v0::dataset_data DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("pulseId", offsetof(DsType, pulseId), hdf5pp::TypeTraits<uint16_t>::native_type());
type.insert("polarity", offsetof(DsType, polarity), hdf5pp::TypeTraits<uint16_t>::native_type());
type.insert("prescale", offsetof(DsType, prescale), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("delay", offsetof(DsType, delay), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("width", offsetof(DsType, width), hdf5pp::TypeTraits<uint32_t>::native_type());
return type;
}
hdf5pp::Type ns_PulseConfigV3_v0::dataset_data::native_type()
{
static hdf5pp::Type type = ns_PulseConfigV3_v0_dataset_data_native_type();
return type;
}
ns_PulseConfigV3_v0::dataset_data::dataset_data()
{
}
ns_PulseConfigV3_v0::dataset_data::~dataset_data()
{
}
boost::shared_ptr<Psana::EvrData::PulseConfigV3>
Proxy_PulseConfigV3_v0::getTypedImpl(PSEvt::ProxyDictI* dict, const Pds::Src& source, const std::string& key)
{
if (not m_data) {
boost::shared_ptr<EvrData::ns_PulseConfigV3_v0::dataset_data> ds_data = hdf5pp::Utils::readGroup<EvrData::ns_PulseConfigV3_v0::dataset_data>(m_group, "data", m_idx);
m_data.reset(new PsanaType(ds_data->pulseId, ds_data->polarity, ds_data->prescale, ds_data->delay, ds_data->width));
}
return m_data;
}
boost::shared_ptr<PSEvt::Proxy<Psana::EvrData::PulseConfigV3> > make_PulseConfigV3(int version, hdf5pp::Group group, hsize_t idx) {
switch (version) {
case 0:
return boost::make_shared<Proxy_PulseConfigV3_v0>(group, idx);
default:
return boost::make_shared<PSEvt::DataProxy<Psana::EvrData::PulseConfigV3> >(boost::shared_ptr<Psana::EvrData::PulseConfigV3>());
}
}
hdf5pp::Type ns_EventCodeV3_v0_dataset_data_stored_type()
{
typedef ns_EventCodeV3_v0::dataset_data DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("code", offsetof(DsType, code), hdf5pp::TypeTraits<uint16_t>::stored_type());
type.insert("_u16MaskEventAttr_value", offsetof(DsType, _u16MaskEventAttr_value), hdf5pp::TypeTraits<uint16_t>::stored_type());
type.insert("isReadout", offsetof(DsType, isReadout), hdf5pp::TypeTraits<uint8_t>::stored_type());
type.insert("isTerminator", offsetof(DsType, isTerminator), hdf5pp::TypeTraits<uint8_t>::stored_type());
type.insert("maskTrigger", offsetof(DsType, maskTrigger), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("maskSet", offsetof(DsType, maskSet), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("maskClear", offsetof(DsType, maskClear), hdf5pp::TypeTraits<uint32_t>::stored_type());
return type;
}
hdf5pp::Type ns_EventCodeV3_v0::dataset_data::stored_type()
{
static hdf5pp::Type type = ns_EventCodeV3_v0_dataset_data_stored_type();
return type;
}
hdf5pp::Type ns_EventCodeV3_v0_dataset_data_native_type()
{
typedef ns_EventCodeV3_v0::dataset_data DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("code", offsetof(DsType, code), hdf5pp::TypeTraits<uint16_t>::native_type());
type.insert("_u16MaskEventAttr_value", offsetof(DsType, _u16MaskEventAttr_value), hdf5pp::TypeTraits<uint16_t>::native_type());
type.insert("isReadout", offsetof(DsType, isReadout), hdf5pp::TypeTraits<uint8_t>::native_type());
type.insert("isTerminator", offsetof(DsType, isTerminator), hdf5pp::TypeTraits<uint8_t>::native_type());
type.insert("maskTrigger", offsetof(DsType, maskTrigger), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("maskSet", offsetof(DsType, maskSet), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("maskClear", offsetof(DsType, maskClear), hdf5pp::TypeTraits<uint32_t>::native_type());
return type;
}
hdf5pp::Type ns_EventCodeV3_v0::dataset_data::native_type()
{
static hdf5pp::Type type = ns_EventCodeV3_v0_dataset_data_native_type();
return type;
}
ns_EventCodeV3_v0::dataset_data::dataset_data()
{
}
ns_EventCodeV3_v0::dataset_data::~dataset_data()
{
}
boost::shared_ptr<Psana::EvrData::EventCodeV3>
Proxy_EventCodeV3_v0::getTypedImpl(PSEvt::ProxyDictI* dict, const Pds::Src& source, const std::string& key)
{
if (not m_data) {
boost::shared_ptr<EvrData::ns_EventCodeV3_v0::dataset_data> ds_data = hdf5pp::Utils::readGroup<EvrData::ns_EventCodeV3_v0::dataset_data>(m_group, "data", m_idx);
m_data.reset(new PsanaType(ds_data->code, ds_data->isReadout, ds_data->isTerminator, ds_data->maskTrigger, ds_data->maskSet, ds_data->maskClear));
}
return m_data;
}
boost::shared_ptr<PSEvt::Proxy<Psana::EvrData::EventCodeV3> > make_EventCodeV3(int version, hdf5pp::Group group, hsize_t idx) {
switch (version) {
case 0:
return boost::make_shared<Proxy_EventCodeV3_v0>(group, idx);
default:
return boost::make_shared<PSEvt::DataProxy<Psana::EvrData::EventCodeV3> >(boost::shared_ptr<Psana::EvrData::EventCodeV3>());
}
}
hdf5pp::Type ns_EventCodeV4_v0_dataset_data_stored_type()
{
typedef ns_EventCodeV4_v0::dataset_data DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("code", offsetof(DsType, code), hdf5pp::TypeTraits<uint16_t>::stored_type());
type.insert("_u16MaskEventAttr_value", offsetof(DsType, _u16MaskEventAttr_value), hdf5pp::TypeTraits<uint16_t>::stored_type());
type.insert("isReadout", offsetof(DsType, isReadout), hdf5pp::TypeTraits<uint8_t>::stored_type());
type.insert("isTerminator", offsetof(DsType, isTerminator), hdf5pp::TypeTraits<uint8_t>::stored_type());
type.insert("reportDelay", offsetof(DsType, reportDelay), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("reportWidth", offsetof(DsType, reportWidth), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("maskTrigger", offsetof(DsType, maskTrigger), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("maskSet", offsetof(DsType, maskSet), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("maskClear", offsetof(DsType, maskClear), hdf5pp::TypeTraits<uint32_t>::stored_type());
return type;
}
hdf5pp::Type ns_EventCodeV4_v0::dataset_data::stored_type()
{
static hdf5pp::Type type = ns_EventCodeV4_v0_dataset_data_stored_type();
return type;
}
hdf5pp::Type ns_EventCodeV4_v0_dataset_data_native_type()
{
typedef ns_EventCodeV4_v0::dataset_data DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("code", offsetof(DsType, code), hdf5pp::TypeTraits<uint16_t>::native_type());
type.insert("_u16MaskEventAttr_value", offsetof(DsType, _u16MaskEventAttr_value), hdf5pp::TypeTraits<uint16_t>::native_type());
type.insert("isReadout", offsetof(DsType, isReadout), hdf5pp::TypeTraits<uint8_t>::native_type());
type.insert("isTerminator", offsetof(DsType, isTerminator), hdf5pp::TypeTraits<uint8_t>::native_type());
type.insert("reportDelay", offsetof(DsType, reportDelay), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("reportWidth", offsetof(DsType, reportWidth), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("maskTrigger", offsetof(DsType, maskTrigger), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("maskSet", offsetof(DsType, maskSet), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("maskClear", offsetof(DsType, maskClear), hdf5pp::TypeTraits<uint32_t>::native_type());
return type;
}
hdf5pp::Type ns_EventCodeV4_v0::dataset_data::native_type()
{
static hdf5pp::Type type = ns_EventCodeV4_v0_dataset_data_native_type();
return type;
}
ns_EventCodeV4_v0::dataset_data::dataset_data()
{
}
ns_EventCodeV4_v0::dataset_data::~dataset_data()
{
}
boost::shared_ptr<Psana::EvrData::EventCodeV4>
Proxy_EventCodeV4_v0::getTypedImpl(PSEvt::ProxyDictI* dict, const Pds::Src& source, const std::string& key)
{
if (not m_data) {
boost::shared_ptr<EvrData::ns_EventCodeV4_v0::dataset_data> ds_data = hdf5pp::Utils::readGroup<EvrData::ns_EventCodeV4_v0::dataset_data>(m_group, "data", m_idx);
m_data.reset(new PsanaType(ds_data->code, ds_data->isReadout, ds_data->isTerminator, ds_data->reportDelay, ds_data->reportWidth, ds_data->maskTrigger, ds_data->maskSet, ds_data->maskClear));
}
return m_data;
}
boost::shared_ptr<PSEvt::Proxy<Psana::EvrData::EventCodeV4> > make_EventCodeV4(int version, hdf5pp::Group group, hsize_t idx) {
switch (version) {
case 0:
return boost::make_shared<Proxy_EventCodeV4_v0>(group, idx);
default:
return boost::make_shared<PSEvt::DataProxy<Psana::EvrData::EventCodeV4> >(boost::shared_ptr<Psana::EvrData::EventCodeV4>());
}
}
hdf5pp::Type ns_EventCodeV5_v0_dataset_data_stored_type()
{
typedef ns_EventCodeV5_v0::dataset_data DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("code", offsetof(DsType, code), hdf5pp::TypeTraits<uint16_t>::stored_type());
type.insert("isReadout", offsetof(DsType, isReadout), hdf5pp::TypeTraits<uint8_t>::stored_type());
type.insert("isCommand", offsetof(DsType, isCommand), hdf5pp::TypeTraits<uint8_t>::stored_type());
type.insert("isLatch", offsetof(DsType, isLatch), hdf5pp::TypeTraits<uint8_t>::stored_type());
type.insert("reportDelay", offsetof(DsType, reportDelay), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("reportWidth", offsetof(DsType, reportWidth), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("maskTrigger", offsetof(DsType, maskTrigger), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("maskSet", offsetof(DsType, maskSet), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("maskClear", offsetof(DsType, maskClear), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("desc", offsetof(DsType, desc), hdf5pp::TypeTraits<const char*>::stored_type());
return type;
}
hdf5pp::Type ns_EventCodeV5_v0::dataset_data::stored_type()
{
static hdf5pp::Type type = ns_EventCodeV5_v0_dataset_data_stored_type();
return type;
}
hdf5pp::Type ns_EventCodeV5_v0_dataset_data_native_type()
{
typedef ns_EventCodeV5_v0::dataset_data DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("code", offsetof(DsType, code), hdf5pp::TypeTraits<uint16_t>::native_type());
type.insert("isReadout", offsetof(DsType, isReadout), hdf5pp::TypeTraits<uint8_t>::native_type());
type.insert("isCommand", offsetof(DsType, isCommand), hdf5pp::TypeTraits<uint8_t>::native_type());
type.insert("isLatch", offsetof(DsType, isLatch), hdf5pp::TypeTraits<uint8_t>::native_type());
type.insert("reportDelay", offsetof(DsType, reportDelay), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("reportWidth", offsetof(DsType, reportWidth), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("maskTrigger", offsetof(DsType, maskTrigger), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("maskSet", offsetof(DsType, maskSet), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("maskClear", offsetof(DsType, maskClear), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("desc", offsetof(DsType, desc), hdf5pp::TypeTraits<const char*>::native_type());
return type;
}
hdf5pp::Type ns_EventCodeV5_v0::dataset_data::native_type()
{
static hdf5pp::Type type = ns_EventCodeV5_v0_dataset_data_native_type();
return type;
}
ns_EventCodeV5_v0::dataset_data::dataset_data()
{
}
ns_EventCodeV5_v0::dataset_data::~dataset_data()
{
}
boost::shared_ptr<Psana::EvrData::EventCodeV5>
Proxy_EventCodeV5_v0::getTypedImpl(PSEvt::ProxyDictI* dict, const Pds::Src& source, const std::string& key)
{
if (not m_data) {
boost::shared_ptr<EvrData::ns_EventCodeV5_v0::dataset_data> ds_data = hdf5pp::Utils::readGroup<EvrData::ns_EventCodeV5_v0::dataset_data>(m_group, "data", m_idx);
m_data.reset(new PsanaType(ds_data->code, ds_data->isReadout, ds_data->isCommand, ds_data->isLatch, ds_data->reportDelay, ds_data->reportWidth, ds_data->maskTrigger, ds_data->maskSet, ds_data->maskClear, ds_data->desc));
}
return m_data;
}
boost::shared_ptr<PSEvt::Proxy<Psana::EvrData::EventCodeV5> > make_EventCodeV5(int version, hdf5pp::Group group, hsize_t idx) {
switch (version) {
case 0:
return boost::make_shared<Proxy_EventCodeV5_v0>(group, idx);
default:
return boost::make_shared<PSEvt::DataProxy<Psana::EvrData::EventCodeV5> >(boost::shared_ptr<Psana::EvrData::EventCodeV5>());
}
}
hdf5pp::Type ns_EventCodeV6_v0_dataset_data_stored_type()
{
typedef ns_EventCodeV6_v0::dataset_data DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("code", offsetof(DsType, code), hdf5pp::TypeTraits<uint16_t>::stored_type());
type.insert("isReadout", offsetof(DsType, isReadout), hdf5pp::TypeTraits<uint8_t>::stored_type());
type.insert("isCommand", offsetof(DsType, isCommand), hdf5pp::TypeTraits<uint8_t>::stored_type());
type.insert("isLatch", offsetof(DsType, isLatch), hdf5pp::TypeTraits<uint8_t>::stored_type());
type.insert("reportDelay", offsetof(DsType, reportDelay), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("reportWidth", offsetof(DsType, reportWidth), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("maskTrigger", offsetof(DsType, maskTrigger), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("maskSet", offsetof(DsType, maskSet), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("maskClear", offsetof(DsType, maskClear), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("desc", offsetof(DsType, desc), hdf5pp::TypeTraits<const char*>::stored_type());
type.insert("readoutGroup", offsetof(DsType, readoutGroup), hdf5pp::TypeTraits<uint16_t>::stored_type());
return type;
}
hdf5pp::Type ns_EventCodeV6_v0::dataset_data::stored_type()
{
static hdf5pp::Type type = ns_EventCodeV6_v0_dataset_data_stored_type();
return type;
}
hdf5pp::Type ns_EventCodeV6_v0_dataset_data_native_type()
{
typedef ns_EventCodeV6_v0::dataset_data DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("code", offsetof(DsType, code), hdf5pp::TypeTraits<uint16_t>::native_type());
type.insert("isReadout", offsetof(DsType, isReadout), hdf5pp::TypeTraits<uint8_t>::native_type());
type.insert("isCommand", offsetof(DsType, isCommand), hdf5pp::TypeTraits<uint8_t>::native_type());
type.insert("isLatch", offsetof(DsType, isLatch), hdf5pp::TypeTraits<uint8_t>::native_type());
type.insert("reportDelay", offsetof(DsType, reportDelay), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("reportWidth", offsetof(DsType, reportWidth), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("maskTrigger", offsetof(DsType, maskTrigger), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("maskSet", offsetof(DsType, maskSet), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("maskClear", offsetof(DsType, maskClear), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("desc", offsetof(DsType, desc), hdf5pp::TypeTraits<const char*>::native_type());
type.insert("readoutGroup", offsetof(DsType, readoutGroup), hdf5pp::TypeTraits<uint16_t>::native_type());
return type;
}
hdf5pp::Type ns_EventCodeV6_v0::dataset_data::native_type()
{
static hdf5pp::Type type = ns_EventCodeV6_v0_dataset_data_native_type();
return type;
}
ns_EventCodeV6_v0::dataset_data::dataset_data()
{
}
ns_EventCodeV6_v0::dataset_data::~dataset_data()
{
}
boost::shared_ptr<Psana::EvrData::EventCodeV6>
Proxy_EventCodeV6_v0::getTypedImpl(PSEvt::ProxyDictI* dict, const Pds::Src& source, const std::string& key)
{
if (not m_data) {
boost::shared_ptr<EvrData::ns_EventCodeV6_v0::dataset_data> ds_data = hdf5pp::Utils::readGroup<EvrData::ns_EventCodeV6_v0::dataset_data>(m_group, "data", m_idx);
m_data.reset(new PsanaType(ds_data->code, ds_data->isReadout, ds_data->isCommand, ds_data->isLatch, ds_data->reportDelay, ds_data->reportWidth, ds_data->maskTrigger, ds_data->maskSet, ds_data->maskClear, ds_data->desc, ds_data->readoutGroup));
}
return m_data;
}
boost::shared_ptr<PSEvt::Proxy<Psana::EvrData::EventCodeV6> > make_EventCodeV6(int version, hdf5pp::Group group, hsize_t idx) {
switch (version) {
case 0:
return boost::make_shared<Proxy_EventCodeV6_v0>(group, idx);
default:
return boost::make_shared<PSEvt::DataProxy<Psana::EvrData::EventCodeV6> >(boost::shared_ptr<Psana::EvrData::EventCodeV6>());
}
}
hdf5pp::Type ns_OutputMap_v0_dataset_data_stored_type()
{
typedef ns_OutputMap_v0::dataset_data DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("value", offsetof(DsType, value), hdf5pp::TypeTraits<uint32_t>::stored_type());
hdf5pp::EnumType<int32_t> _enum_type_source = hdf5pp::EnumType<int32_t>::enumType();
_enum_type_source.insert("Pulse", Psana::EvrData::OutputMap::Pulse);
_enum_type_source.insert("DBus", Psana::EvrData::OutputMap::DBus);
_enum_type_source.insert("Prescaler", Psana::EvrData::OutputMap::Prescaler);
_enum_type_source.insert("Force_High", Psana::EvrData::OutputMap::Force_High);
_enum_type_source.insert("Force_Low", Psana::EvrData::OutputMap::Force_Low);
type.insert("source", offsetof(DsType, source), _enum_type_source);
type.insert("source_id", offsetof(DsType, source_id), hdf5pp::TypeTraits<uint8_t>::stored_type());
hdf5pp::EnumType<int32_t> _enum_type_conn = hdf5pp::EnumType<int32_t>::enumType();
_enum_type_conn.insert("FrontPanel", Psana::EvrData::OutputMap::FrontPanel);
_enum_type_conn.insert("UnivIO", Psana::EvrData::OutputMap::UnivIO);
type.insert("conn", offsetof(DsType, conn), _enum_type_conn);
type.insert("conn_id", offsetof(DsType, conn_id), hdf5pp::TypeTraits<uint8_t>::stored_type());
return type;
}
hdf5pp::Type ns_OutputMap_v0::dataset_data::stored_type()
{
static hdf5pp::Type type = ns_OutputMap_v0_dataset_data_stored_type();
return type;
}
hdf5pp::Type ns_OutputMap_v0_dataset_data_native_type()
{
typedef ns_OutputMap_v0::dataset_data DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("value", offsetof(DsType, value), hdf5pp::TypeTraits<uint32_t>::native_type());
hdf5pp::EnumType<int32_t> _enum_type_source = hdf5pp::EnumType<int32_t>::enumType();
_enum_type_source.insert("Pulse", Psana::EvrData::OutputMap::Pulse);
_enum_type_source.insert("DBus", Psana::EvrData::OutputMap::DBus);
_enum_type_source.insert("Prescaler", Psana::EvrData::OutputMap::Prescaler);
_enum_type_source.insert("Force_High", Psana::EvrData::OutputMap::Force_High);
_enum_type_source.insert("Force_Low", Psana::EvrData::OutputMap::Force_Low);
type.insert("source", offsetof(DsType, source), _enum_type_source);
type.insert("source_id", offsetof(DsType, source_id), hdf5pp::TypeTraits<uint8_t>::native_type());
hdf5pp::EnumType<int32_t> _enum_type_conn = hdf5pp::EnumType<int32_t>::enumType();
_enum_type_conn.insert("FrontPanel", Psana::EvrData::OutputMap::FrontPanel);
_enum_type_conn.insert("UnivIO", Psana::EvrData::OutputMap::UnivIO);
type.insert("conn", offsetof(DsType, conn), _enum_type_conn);
type.insert("conn_id", offsetof(DsType, conn_id), hdf5pp::TypeTraits<uint8_t>::native_type());
return type;
}
hdf5pp::Type ns_OutputMap_v0::dataset_data::native_type()
{
static hdf5pp::Type type = ns_OutputMap_v0_dataset_data_native_type();
return type;
}
ns_OutputMap_v0::dataset_data::dataset_data()
{
}
ns_OutputMap_v0::dataset_data::~dataset_data()
{
}
boost::shared_ptr<Psana::EvrData::OutputMap>
Proxy_OutputMap_v0::getTypedImpl(PSEvt::ProxyDictI* dict, const Pds::Src& source, const std::string& key)
{
if (not m_data) {
boost::shared_ptr<EvrData::ns_OutputMap_v0::dataset_data> ds_data = hdf5pp::Utils::readGroup<EvrData::ns_OutputMap_v0::dataset_data>(m_group, "data", m_idx);
m_data.reset(new PsanaType(Psana::EvrData::OutputMap::Source(ds_data->source), ds_data->source_id, Psana::EvrData::OutputMap::Conn(ds_data->conn), ds_data->conn_id));
}
return m_data;
}
boost::shared_ptr<PSEvt::Proxy<Psana::EvrData::OutputMap> > make_OutputMap(int version, hdf5pp::Group group, hsize_t idx) {
switch (version) {
case 0:
return boost::make_shared<Proxy_OutputMap_v0>(group, idx);
default:
return boost::make_shared<PSEvt::DataProxy<Psana::EvrData::OutputMap> >(boost::shared_ptr<Psana::EvrData::OutputMap>());
}
}
hdf5pp::Type ns_OutputMapV2_v0_dataset_data_stored_type()
{
typedef ns_OutputMapV2_v0::dataset_data DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("value", offsetof(DsType, value), hdf5pp::TypeTraits<uint32_t>::stored_type());
hdf5pp::EnumType<int32_t> _enum_type_source = hdf5pp::EnumType<int32_t>::enumType();
_enum_type_source.insert("Pulse", Psana::EvrData::OutputMapV2::Pulse);
_enum_type_source.insert("DBus", Psana::EvrData::OutputMapV2::DBus);
_enum_type_source.insert("Prescaler", Psana::EvrData::OutputMapV2::Prescaler);
_enum_type_source.insert("Force_High", Psana::EvrData::OutputMapV2::Force_High);
_enum_type_source.insert("Force_Low", Psana::EvrData::OutputMapV2::Force_Low);
type.insert("source", offsetof(DsType, source), _enum_type_source);
type.insert("source_id", offsetof(DsType, source_id), hdf5pp::TypeTraits<uint8_t>::stored_type());
hdf5pp::EnumType<int32_t> _enum_type_conn = hdf5pp::EnumType<int32_t>::enumType();
_enum_type_conn.insert("FrontPanel", Psana::EvrData::OutputMapV2::FrontPanel);
_enum_type_conn.insert("UnivIO", Psana::EvrData::OutputMapV2::UnivIO);
type.insert("conn", offsetof(DsType, conn), _enum_type_conn);
type.insert("conn_id", offsetof(DsType, conn_id), hdf5pp::TypeTraits<uint8_t>::stored_type());
type.insert("module", offsetof(DsType, module), hdf5pp::TypeTraits<uint8_t>::stored_type());
return type;
}
hdf5pp::Type ns_OutputMapV2_v0::dataset_data::stored_type()
{
static hdf5pp::Type type = ns_OutputMapV2_v0_dataset_data_stored_type();
return type;
}
hdf5pp::Type ns_OutputMapV2_v0_dataset_data_native_type()
{
typedef ns_OutputMapV2_v0::dataset_data DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("value", offsetof(DsType, value), hdf5pp::TypeTraits<uint32_t>::native_type());
hdf5pp::EnumType<int32_t> _enum_type_source = hdf5pp::EnumType<int32_t>::enumType();
_enum_type_source.insert("Pulse", Psana::EvrData::OutputMapV2::Pulse);
_enum_type_source.insert("DBus", Psana::EvrData::OutputMapV2::DBus);
_enum_type_source.insert("Prescaler", Psana::EvrData::OutputMapV2::Prescaler);
_enum_type_source.insert("Force_High", Psana::EvrData::OutputMapV2::Force_High);
_enum_type_source.insert("Force_Low", Psana::EvrData::OutputMapV2::Force_Low);
type.insert("source", offsetof(DsType, source), _enum_type_source);
type.insert("source_id", offsetof(DsType, source_id), hdf5pp::TypeTraits<uint8_t>::native_type());
hdf5pp::EnumType<int32_t> _enum_type_conn = hdf5pp::EnumType<int32_t>::enumType();
_enum_type_conn.insert("FrontPanel", Psana::EvrData::OutputMapV2::FrontPanel);
_enum_type_conn.insert("UnivIO", Psana::EvrData::OutputMapV2::UnivIO);
type.insert("conn", offsetof(DsType, conn), _enum_type_conn);
type.insert("conn_id", offsetof(DsType, conn_id), hdf5pp::TypeTraits<uint8_t>::native_type());
type.insert("module", offsetof(DsType, module), hdf5pp::TypeTraits<uint8_t>::native_type());
return type;
}
hdf5pp::Type ns_OutputMapV2_v0::dataset_data::native_type()
{
static hdf5pp::Type type = ns_OutputMapV2_v0_dataset_data_native_type();
return type;
}
ns_OutputMapV2_v0::dataset_data::dataset_data()
{
}
ns_OutputMapV2_v0::dataset_data::~dataset_data()
{
}
boost::shared_ptr<Psana::EvrData::OutputMapV2>
Proxy_OutputMapV2_v0::getTypedImpl(PSEvt::ProxyDictI* dict, const Pds::Src& source, const std::string& key)
{
if (not m_data) {
boost::shared_ptr<EvrData::ns_OutputMapV2_v0::dataset_data> ds_data = hdf5pp::Utils::readGroup<EvrData::ns_OutputMapV2_v0::dataset_data>(m_group, "data", m_idx);
m_data.reset(new PsanaType(Psana::EvrData::OutputMapV2::Source(ds_data->source), ds_data->source_id, Psana::EvrData::OutputMapV2::Conn(ds_data->conn), ds_data->conn_id, ds_data->module));
}
return m_data;
}
boost::shared_ptr<PSEvt::Proxy<Psana::EvrData::OutputMapV2> > make_OutputMapV2(int version, hdf5pp::Group group, hsize_t idx) {
switch (version) {
case 0:
return boost::make_shared<Proxy_OutputMapV2_v0>(group, idx);
default:
return boost::make_shared<PSEvt::DataProxy<Psana::EvrData::OutputMapV2> >(boost::shared_ptr<Psana::EvrData::OutputMapV2>());
}
}
hdf5pp::Type ns_ConfigV1_v0_dataset_config_stored_type()
{
typedef ns_ConfigV1_v0::dataset_config DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("npulses", offsetof(DsType, npulses), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("noutputs", offsetof(DsType, noutputs), hdf5pp::TypeTraits<uint32_t>::stored_type());
return type;
}
hdf5pp::Type ns_ConfigV1_v0::dataset_config::stored_type()
{
static hdf5pp::Type type = ns_ConfigV1_v0_dataset_config_stored_type();
return type;
}
hdf5pp::Type ns_ConfigV1_v0_dataset_config_native_type()
{
typedef ns_ConfigV1_v0::dataset_config DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("npulses", offsetof(DsType, npulses), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("noutputs", offsetof(DsType, noutputs), hdf5pp::TypeTraits<uint32_t>::native_type());
return type;
}
hdf5pp::Type ns_ConfigV1_v0::dataset_config::native_type()
{
static hdf5pp::Type type = ns_ConfigV1_v0_dataset_config_native_type();
return type;
}
ns_ConfigV1_v0::dataset_config::dataset_config()
{
}
ns_ConfigV1_v0::dataset_config::~dataset_config()
{
}
uint32_t ConfigV1_v0::npulses() const {
if (not m_ds_config) read_ds_config();
return uint32_t(m_ds_config->npulses);
}
uint32_t ConfigV1_v0::noutputs() const {
if (not m_ds_config) read_ds_config();
return uint32_t(m_ds_config->noutputs);
}
ndarray<const Psana::EvrData::PulseConfig, 1> ConfigV1_v0::pulses() const {
if (m_ds_pulses.empty()) read_ds_pulses();
return m_ds_pulses;
}
ndarray<const Psana::EvrData::OutputMap, 1> ConfigV1_v0::output_maps() const {
if (m_ds_output_maps.empty()) read_ds_output_maps();
return m_ds_output_maps;
}
void ConfigV1_v0::read_ds_config() const {
m_ds_config = hdf5pp::Utils::readGroup<EvrData::ns_ConfigV1_v0::dataset_config>(m_group, "config", m_idx);
}
void ConfigV1_v0::read_ds_pulses() const {
ndarray<EvrData::ns_PulseConfig_v0::dataset_data, 1> arr = hdf5pp::Utils::readNdarray<EvrData::ns_PulseConfig_v0::dataset_data, 1>(m_group, "pulses", m_idx);
ndarray<Psana::EvrData::PulseConfig, 1> tmp(arr.shape());
std::copy(arr.begin(), arr.end(), tmp.begin());
m_ds_pulses = tmp;
}
void ConfigV1_v0::read_ds_output_maps() const {
ndarray<EvrData::ns_OutputMap_v0::dataset_data, 1> arr = hdf5pp::Utils::readNdarray<EvrData::ns_OutputMap_v0::dataset_data, 1>(m_group, "output_maps", m_idx);
ndarray<Psana::EvrData::OutputMap, 1> tmp(arr.shape());
std::copy(arr.begin(), arr.end(), tmp.begin());
m_ds_output_maps = tmp;
}
boost::shared_ptr<PSEvt::Proxy<Psana::EvrData::ConfigV1> > make_ConfigV1(int version, hdf5pp::Group group, hsize_t idx) {
switch (version) {
case 0:
return boost::make_shared<PSEvt::DataProxy<Psana::EvrData::ConfigV1> >(boost::make_shared<ConfigV1_v0>(group, idx));
default:
return boost::make_shared<PSEvt::DataProxy<Psana::EvrData::ConfigV1> >(boost::shared_ptr<Psana::EvrData::ConfigV1>());
}
}
hdf5pp::Type ns_ConfigV2_v0_dataset_config_stored_type()
{
typedef ns_ConfigV2_v0::dataset_config DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("opcode", offsetof(DsType, opcode), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("npulses", offsetof(DsType, npulses), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("noutputs", offsetof(DsType, noutputs), hdf5pp::TypeTraits<uint32_t>::stored_type());
hdf5pp::EnumType<int32_t> _enum_type_beam = hdf5pp::EnumType<int32_t>::enumType();
_enum_type_beam.insert("Off", Psana::EvrData::ConfigV2::Off);
_enum_type_beam.insert("On", Psana::EvrData::ConfigV2::On);
type.insert("beam", offsetof(DsType, beam), _enum_type_beam);
hdf5pp::EnumType<int32_t> _enum_type_rate = hdf5pp::EnumType<int32_t>::enumType();
_enum_type_rate.insert("r120Hz", Psana::EvrData::ConfigV2::r120Hz);
_enum_type_rate.insert("r60Hz", Psana::EvrData::ConfigV2::r60Hz);
_enum_type_rate.insert("r30Hz", Psana::EvrData::ConfigV2::r30Hz);
_enum_type_rate.insert("r10Hz", Psana::EvrData::ConfigV2::r10Hz);
_enum_type_rate.insert("r5Hz", Psana::EvrData::ConfigV2::r5Hz);
_enum_type_rate.insert("r1Hz", Psana::EvrData::ConfigV2::r1Hz);
_enum_type_rate.insert("r0_5Hz", Psana::EvrData::ConfigV2::r0_5Hz);
_enum_type_rate.insert("Single", Psana::EvrData::ConfigV2::Single);
_enum_type_rate.insert("NumberOfRates", Psana::EvrData::ConfigV2::NumberOfRates);
type.insert("rate", offsetof(DsType, rate), _enum_type_rate);
return type;
}
hdf5pp::Type ns_ConfigV2_v0::dataset_config::stored_type()
{
static hdf5pp::Type type = ns_ConfigV2_v0_dataset_config_stored_type();
return type;
}
hdf5pp::Type ns_ConfigV2_v0_dataset_config_native_type()
{
typedef ns_ConfigV2_v0::dataset_config DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("opcode", offsetof(DsType, opcode), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("npulses", offsetof(DsType, npulses), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("noutputs", offsetof(DsType, noutputs), hdf5pp::TypeTraits<uint32_t>::native_type());
hdf5pp::EnumType<int32_t> _enum_type_beam = hdf5pp::EnumType<int32_t>::enumType();
_enum_type_beam.insert("Off", Psana::EvrData::ConfigV2::Off);
_enum_type_beam.insert("On", Psana::EvrData::ConfigV2::On);
type.insert("beam", offsetof(DsType, beam), _enum_type_beam);
hdf5pp::EnumType<int32_t> _enum_type_rate = hdf5pp::EnumType<int32_t>::enumType();
_enum_type_rate.insert("r120Hz", Psana::EvrData::ConfigV2::r120Hz);
_enum_type_rate.insert("r60Hz", Psana::EvrData::ConfigV2::r60Hz);
_enum_type_rate.insert("r30Hz", Psana::EvrData::ConfigV2::r30Hz);
_enum_type_rate.insert("r10Hz", Psana::EvrData::ConfigV2::r10Hz);
_enum_type_rate.insert("r5Hz", Psana::EvrData::ConfigV2::r5Hz);
_enum_type_rate.insert("r1Hz", Psana::EvrData::ConfigV2::r1Hz);
_enum_type_rate.insert("r0_5Hz", Psana::EvrData::ConfigV2::r0_5Hz);
_enum_type_rate.insert("Single", Psana::EvrData::ConfigV2::Single);
_enum_type_rate.insert("NumberOfRates", Psana::EvrData::ConfigV2::NumberOfRates);
type.insert("rate", offsetof(DsType, rate), _enum_type_rate);
return type;
}
hdf5pp::Type ns_ConfigV2_v0::dataset_config::native_type()
{
static hdf5pp::Type type = ns_ConfigV2_v0_dataset_config_native_type();
return type;
}
ns_ConfigV2_v0::dataset_config::dataset_config()
{
}
ns_ConfigV2_v0::dataset_config::~dataset_config()
{
}
uint32_t ConfigV2_v0::opcode() const {
if (not m_ds_config) read_ds_config();
return uint32_t(m_ds_config->opcode);
}
uint32_t ConfigV2_v0::npulses() const {
if (not m_ds_config) read_ds_config();
return uint32_t(m_ds_config->npulses);
}
uint32_t ConfigV2_v0::noutputs() const {
if (not m_ds_config) read_ds_config();
return uint32_t(m_ds_config->noutputs);
}
ndarray<const Psana::EvrData::PulseConfig, 1> ConfigV2_v0::pulses() const {
if (m_ds_pulses.empty()) read_ds_pulses();
return m_ds_pulses;
}
ndarray<const Psana::EvrData::OutputMap, 1> ConfigV2_v0::output_maps() const {
if (m_ds_output_maps.empty()) read_ds_output_maps();
return m_ds_output_maps;
}
Psana::EvrData::ConfigV2::BeamCode ConfigV2_v0::beam() const {
if (not m_ds_config) read_ds_config();
return Psana::EvrData::ConfigV2::BeamCode(m_ds_config->beam);
}
Psana::EvrData::ConfigV2::RateCode ConfigV2_v0::rate() const {
if (not m_ds_config) read_ds_config();
return Psana::EvrData::ConfigV2::RateCode(m_ds_config->rate);
}
void ConfigV2_v0::read_ds_config() const {
m_ds_config = hdf5pp::Utils::readGroup<EvrData::ns_ConfigV2_v0::dataset_config>(m_group, "config", m_idx);
}
void ConfigV2_v0::read_ds_pulses() const {
ndarray<EvrData::ns_PulseConfig_v0::dataset_data, 1> arr = hdf5pp::Utils::readNdarray<EvrData::ns_PulseConfig_v0::dataset_data, 1>(m_group, "pulses", m_idx);
ndarray<Psana::EvrData::PulseConfig, 1> tmp(arr.shape());
std::copy(arr.begin(), arr.end(), tmp.begin());
m_ds_pulses = tmp;
}
void ConfigV2_v0::read_ds_output_maps() const {
ndarray<EvrData::ns_OutputMap_v0::dataset_data, 1> arr = hdf5pp::Utils::readNdarray<EvrData::ns_OutputMap_v0::dataset_data, 1>(m_group, "output_maps", m_idx);
ndarray<Psana::EvrData::OutputMap, 1> tmp(arr.shape());
std::copy(arr.begin(), arr.end(), tmp.begin());
m_ds_output_maps = tmp;
}
boost::shared_ptr<PSEvt::Proxy<Psana::EvrData::ConfigV2> > make_ConfigV2(int version, hdf5pp::Group group, hsize_t idx) {
switch (version) {
case 0:
return boost::make_shared<PSEvt::DataProxy<Psana::EvrData::ConfigV2> >(boost::make_shared<ConfigV2_v0>(group, idx));
default:
return boost::make_shared<PSEvt::DataProxy<Psana::EvrData::ConfigV2> >(boost::shared_ptr<Psana::EvrData::ConfigV2>());
}
}
hdf5pp::Type ns_ConfigV3_v0_dataset_config_stored_type()
{
typedef ns_ConfigV3_v0::dataset_config DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("neventcodes", offsetof(DsType, neventcodes), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("npulses", offsetof(DsType, npulses), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("noutputs", offsetof(DsType, noutputs), hdf5pp::TypeTraits<uint32_t>::stored_type());
return type;
}
hdf5pp::Type ns_ConfigV3_v0::dataset_config::stored_type()
{
static hdf5pp::Type type = ns_ConfigV3_v0_dataset_config_stored_type();
return type;
}
hdf5pp::Type ns_ConfigV3_v0_dataset_config_native_type()
{
typedef ns_ConfigV3_v0::dataset_config DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("neventcodes", offsetof(DsType, neventcodes), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("npulses", offsetof(DsType, npulses), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("noutputs", offsetof(DsType, noutputs), hdf5pp::TypeTraits<uint32_t>::native_type());
return type;
}
hdf5pp::Type ns_ConfigV3_v0::dataset_config::native_type()
{
static hdf5pp::Type type = ns_ConfigV3_v0_dataset_config_native_type();
return type;
}
ns_ConfigV3_v0::dataset_config::dataset_config()
{
}
ns_ConfigV3_v0::dataset_config::~dataset_config()
{
}
uint32_t ConfigV3_v0::neventcodes() const {
if (not m_ds_config) read_ds_config();
return uint32_t(m_ds_config->neventcodes);
}
uint32_t ConfigV3_v0::npulses() const {
if (not m_ds_config) read_ds_config();
return uint32_t(m_ds_config->npulses);
}
uint32_t ConfigV3_v0::noutputs() const {
if (not m_ds_config) read_ds_config();
return uint32_t(m_ds_config->noutputs);
}
ndarray<const Psana::EvrData::EventCodeV3, 1> ConfigV3_v0::eventcodes() const {
if (m_ds_eventcodes.empty()) read_ds_eventcodes();
return m_ds_eventcodes;
}
ndarray<const Psana::EvrData::PulseConfigV3, 1> ConfigV3_v0::pulses() const {
if (m_ds_pulses.empty()) read_ds_pulses();
return m_ds_pulses;
}
ndarray<const Psana::EvrData::OutputMap, 1> ConfigV3_v0::output_maps() const {
if (m_ds_output_maps.empty()) read_ds_output_maps();
return m_ds_output_maps;
}
void ConfigV3_v0::read_ds_config() const {
m_ds_config = hdf5pp::Utils::readGroup<EvrData::ns_ConfigV3_v0::dataset_config>(m_group, "config", m_idx);
}
void ConfigV3_v0::read_ds_eventcodes() const {
ndarray<EvrData::ns_EventCodeV3_v0::dataset_data, 1> arr = hdf5pp::Utils::readNdarray<EvrData::ns_EventCodeV3_v0::dataset_data, 1>(m_group, "eventcodes", m_idx);
ndarray<Psana::EvrData::EventCodeV3, 1> tmp(arr.shape());
std::copy(arr.begin(), arr.end(), tmp.begin());
m_ds_eventcodes = tmp;
}
void ConfigV3_v0::read_ds_pulses() const {
ndarray<EvrData::ns_PulseConfigV3_v0::dataset_data, 1> arr = hdf5pp::Utils::readNdarray<EvrData::ns_PulseConfigV3_v0::dataset_data, 1>(m_group, "pulses", m_idx);
ndarray<Psana::EvrData::PulseConfigV3, 1> tmp(arr.shape());
std::copy(arr.begin(), arr.end(), tmp.begin());
m_ds_pulses = tmp;
}
void ConfigV3_v0::read_ds_output_maps() const {
ndarray<EvrData::ns_OutputMap_v0::dataset_data, 1> arr = hdf5pp::Utils::readNdarray<EvrData::ns_OutputMap_v0::dataset_data, 1>(m_group, "output_maps", m_idx);
ndarray<Psana::EvrData::OutputMap, 1> tmp(arr.shape());
std::copy(arr.begin(), arr.end(), tmp.begin());
m_ds_output_maps = tmp;
}
boost::shared_ptr<PSEvt::Proxy<Psana::EvrData::ConfigV3> > make_ConfigV3(int version, hdf5pp::Group group, hsize_t idx) {
switch (version) {
case 0:
return boost::make_shared<PSEvt::DataProxy<Psana::EvrData::ConfigV3> >(boost::make_shared<ConfigV3_v0>(group, idx));
default:
return boost::make_shared<PSEvt::DataProxy<Psana::EvrData::ConfigV3> >(boost::shared_ptr<Psana::EvrData::ConfigV3>());
}
}
hdf5pp::Type ns_ConfigV4_v0_dataset_config_stored_type()
{
typedef ns_ConfigV4_v0::dataset_config DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("neventcodes", offsetof(DsType, neventcodes), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("npulses", offsetof(DsType, npulses), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("noutputs", offsetof(DsType, noutputs), hdf5pp::TypeTraits<uint32_t>::stored_type());
return type;
}
hdf5pp::Type ns_ConfigV4_v0::dataset_config::stored_type()
{
static hdf5pp::Type type = ns_ConfigV4_v0_dataset_config_stored_type();
return type;
}
hdf5pp::Type ns_ConfigV4_v0_dataset_config_native_type()
{
typedef ns_ConfigV4_v0::dataset_config DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("neventcodes", offsetof(DsType, neventcodes), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("npulses", offsetof(DsType, npulses), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("noutputs", offsetof(DsType, noutputs), hdf5pp::TypeTraits<uint32_t>::native_type());
return type;
}
hdf5pp::Type ns_ConfigV4_v0::dataset_config::native_type()
{
static hdf5pp::Type type = ns_ConfigV4_v0_dataset_config_native_type();
return type;
}
ns_ConfigV4_v0::dataset_config::dataset_config()
{
}
ns_ConfigV4_v0::dataset_config::~dataset_config()
{
}
uint32_t ConfigV4_v0::neventcodes() const {
if (not m_ds_config) read_ds_config();
return uint32_t(m_ds_config->neventcodes);
}
uint32_t ConfigV4_v0::npulses() const {
if (not m_ds_config) read_ds_config();
return uint32_t(m_ds_config->npulses);
}
uint32_t ConfigV4_v0::noutputs() const {
if (not m_ds_config) read_ds_config();
return uint32_t(m_ds_config->noutputs);
}
ndarray<const Psana::EvrData::EventCodeV4, 1> ConfigV4_v0::eventcodes() const {
if (m_ds_eventcodes.empty()) read_ds_eventcodes();
return m_ds_eventcodes;
}
ndarray<const Psana::EvrData::PulseConfigV3, 1> ConfigV4_v0::pulses() const {
if (m_ds_pulses.empty()) read_ds_pulses();
return m_ds_pulses;
}
ndarray<const Psana::EvrData::OutputMap, 1> ConfigV4_v0::output_maps() const {
if (m_ds_output_maps.empty()) read_ds_output_maps();
return m_ds_output_maps;
}
void ConfigV4_v0::read_ds_config() const {
m_ds_config = hdf5pp::Utils::readGroup<EvrData::ns_ConfigV4_v0::dataset_config>(m_group, "config", m_idx);
}
void ConfigV4_v0::read_ds_eventcodes() const {
ndarray<EvrData::ns_EventCodeV4_v0::dataset_data, 1> arr = hdf5pp::Utils::readNdarray<EvrData::ns_EventCodeV4_v0::dataset_data, 1>(m_group, "eventcodes", m_idx);
ndarray<Psana::EvrData::EventCodeV4, 1> tmp(arr.shape());
std::copy(arr.begin(), arr.end(), tmp.begin());
m_ds_eventcodes = tmp;
}
void ConfigV4_v0::read_ds_pulses() const {
ndarray<EvrData::ns_PulseConfigV3_v0::dataset_data, 1> arr = hdf5pp::Utils::readNdarray<EvrData::ns_PulseConfigV3_v0::dataset_data, 1>(m_group, "pulses", m_idx);
ndarray<Psana::EvrData::PulseConfigV3, 1> tmp(arr.shape());
std::copy(arr.begin(), arr.end(), tmp.begin());
m_ds_pulses = tmp;
}
void ConfigV4_v0::read_ds_output_maps() const {
ndarray<EvrData::ns_OutputMap_v0::dataset_data, 1> arr = hdf5pp::Utils::readNdarray<EvrData::ns_OutputMap_v0::dataset_data, 1>(m_group, "output_maps", m_idx);
ndarray<Psana::EvrData::OutputMap, 1> tmp(arr.shape());
std::copy(arr.begin(), arr.end(), tmp.begin());
m_ds_output_maps = tmp;
}
boost::shared_ptr<PSEvt::Proxy<Psana::EvrData::ConfigV4> > make_ConfigV4(int version, hdf5pp::Group group, hsize_t idx) {
switch (version) {
case 0:
return boost::make_shared<PSEvt::DataProxy<Psana::EvrData::ConfigV4> >(boost::make_shared<ConfigV4_v0>(group, idx));
default:
return boost::make_shared<PSEvt::DataProxy<Psana::EvrData::ConfigV4> >(boost::shared_ptr<Psana::EvrData::ConfigV4>());
}
}
hdf5pp::Type ns_SequencerEntry_v0_dataset_data_stored_type()
{
typedef ns_SequencerEntry_v0::dataset_data DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("delay", offsetof(DsType, delay), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("eventcode", offsetof(DsType, eventcode), hdf5pp::TypeTraits<uint32_t>::stored_type());
return type;
}
hdf5pp::Type ns_SequencerEntry_v0::dataset_data::stored_type()
{
static hdf5pp::Type type = ns_SequencerEntry_v0_dataset_data_stored_type();
return type;
}
hdf5pp::Type ns_SequencerEntry_v0_dataset_data_native_type()
{
typedef ns_SequencerEntry_v0::dataset_data DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("delay", offsetof(DsType, delay), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("eventcode", offsetof(DsType, eventcode), hdf5pp::TypeTraits<uint32_t>::native_type());
return type;
}
hdf5pp::Type ns_SequencerEntry_v0::dataset_data::native_type()
{
static hdf5pp::Type type = ns_SequencerEntry_v0_dataset_data_native_type();
return type;
}
ns_SequencerEntry_v0::dataset_data::dataset_data()
{
}
ns_SequencerEntry_v0::dataset_data::~dataset_data()
{
}
boost::shared_ptr<Psana::EvrData::SequencerEntry>
Proxy_SequencerEntry_v0::getTypedImpl(PSEvt::ProxyDictI* dict, const Pds::Src& source, const std::string& key)
{
if (not m_data) {
boost::shared_ptr<EvrData::ns_SequencerEntry_v0::dataset_data> ds_data = hdf5pp::Utils::readGroup<EvrData::ns_SequencerEntry_v0::dataset_data>(m_group, "data", m_idx);
m_data.reset(new PsanaType(ds_data->eventcode, ds_data->delay));
}
return m_data;
}
boost::shared_ptr<PSEvt::Proxy<Psana::EvrData::SequencerEntry> > make_SequencerEntry(int version, hdf5pp::Group group, hsize_t idx) {
switch (version) {
case 0:
return boost::make_shared<Proxy_SequencerEntry_v0>(group, idx);
default:
return boost::make_shared<PSEvt::DataProxy<Psana::EvrData::SequencerEntry> >(boost::shared_ptr<Psana::EvrData::SequencerEntry>());
}
}
hdf5pp::Type ns_SequencerConfigV1_v0_dataset_config_stored_type()
{
typedef ns_SequencerConfigV1_v0::dataset_config DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
hdf5pp::EnumType<int32_t> _enum_type_sync_source = hdf5pp::EnumType<int32_t>::enumType();
_enum_type_sync_source.insert("r120Hz", Psana::EvrData::SequencerConfigV1::r120Hz);
_enum_type_sync_source.insert("r60Hz", Psana::EvrData::SequencerConfigV1::r60Hz);
_enum_type_sync_source.insert("r30Hz", Psana::EvrData::SequencerConfigV1::r30Hz);
_enum_type_sync_source.insert("r10Hz", Psana::EvrData::SequencerConfigV1::r10Hz);
_enum_type_sync_source.insert("r5Hz", Psana::EvrData::SequencerConfigV1::r5Hz);
_enum_type_sync_source.insert("r1Hz", Psana::EvrData::SequencerConfigV1::r1Hz);
_enum_type_sync_source.insert("r0_5Hz", Psana::EvrData::SequencerConfigV1::r0_5Hz);
_enum_type_sync_source.insert("Disable", Psana::EvrData::SequencerConfigV1::Disable);
type.insert("sync_source", offsetof(DsType, sync_source), _enum_type_sync_source);
hdf5pp::EnumType<int32_t> _enum_type_beam_source = hdf5pp::EnumType<int32_t>::enumType();
_enum_type_beam_source.insert("r120Hz", Psana::EvrData::SequencerConfigV1::r120Hz);
_enum_type_beam_source.insert("r60Hz", Psana::EvrData::SequencerConfigV1::r60Hz);
_enum_type_beam_source.insert("r30Hz", Psana::EvrData::SequencerConfigV1::r30Hz);
_enum_type_beam_source.insert("r10Hz", Psana::EvrData::SequencerConfigV1::r10Hz);
_enum_type_beam_source.insert("r5Hz", Psana::EvrData::SequencerConfigV1::r5Hz);
_enum_type_beam_source.insert("r1Hz", Psana::EvrData::SequencerConfigV1::r1Hz);
_enum_type_beam_source.insert("r0_5Hz", Psana::EvrData::SequencerConfigV1::r0_5Hz);
_enum_type_beam_source.insert("Disable", Psana::EvrData::SequencerConfigV1::Disable);
type.insert("beam_source", offsetof(DsType, beam_source), _enum_type_beam_source);
type.insert("length", offsetof(DsType, length), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("cycles", offsetof(DsType, cycles), hdf5pp::TypeTraits<uint32_t>::stored_type());
hdf5pp::VlenType _array_type_entries = hdf5pp::VlenType::vlenType(hdf5pp::TypeTraits<EvrData::ns_SequencerEntry_v0::dataset_data>::stored_type());
type.insert("entries", offsetof(DsType, vlen_entries), _array_type_entries);
return type;
}
hdf5pp::Type ns_SequencerConfigV1_v0::dataset_config::stored_type()
{
static hdf5pp::Type type = ns_SequencerConfigV1_v0_dataset_config_stored_type();
return type;
}
hdf5pp::Type ns_SequencerConfigV1_v0_dataset_config_native_type()
{
typedef ns_SequencerConfigV1_v0::dataset_config DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
hdf5pp::EnumType<int32_t> _enum_type_sync_source = hdf5pp::EnumType<int32_t>::enumType();
_enum_type_sync_source.insert("r120Hz", Psana::EvrData::SequencerConfigV1::r120Hz);
_enum_type_sync_source.insert("r60Hz", Psana::EvrData::SequencerConfigV1::r60Hz);
_enum_type_sync_source.insert("r30Hz", Psana::EvrData::SequencerConfigV1::r30Hz);
_enum_type_sync_source.insert("r10Hz", Psana::EvrData::SequencerConfigV1::r10Hz);
_enum_type_sync_source.insert("r5Hz", Psana::EvrData::SequencerConfigV1::r5Hz);
_enum_type_sync_source.insert("r1Hz", Psana::EvrData::SequencerConfigV1::r1Hz);
_enum_type_sync_source.insert("r0_5Hz", Psana::EvrData::SequencerConfigV1::r0_5Hz);
_enum_type_sync_source.insert("Disable", Psana::EvrData::SequencerConfigV1::Disable);
type.insert("sync_source", offsetof(DsType, sync_source), _enum_type_sync_source);
hdf5pp::EnumType<int32_t> _enum_type_beam_source = hdf5pp::EnumType<int32_t>::enumType();
_enum_type_beam_source.insert("r120Hz", Psana::EvrData::SequencerConfigV1::r120Hz);
_enum_type_beam_source.insert("r60Hz", Psana::EvrData::SequencerConfigV1::r60Hz);
_enum_type_beam_source.insert("r30Hz", Psana::EvrData::SequencerConfigV1::r30Hz);
_enum_type_beam_source.insert("r10Hz", Psana::EvrData::SequencerConfigV1::r10Hz);
_enum_type_beam_source.insert("r5Hz", Psana::EvrData::SequencerConfigV1::r5Hz);
_enum_type_beam_source.insert("r1Hz", Psana::EvrData::SequencerConfigV1::r1Hz);
_enum_type_beam_source.insert("r0_5Hz", Psana::EvrData::SequencerConfigV1::r0_5Hz);
_enum_type_beam_source.insert("Disable", Psana::EvrData::SequencerConfigV1::Disable);
type.insert("beam_source", offsetof(DsType, beam_source), _enum_type_beam_source);
type.insert("length", offsetof(DsType, length), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("cycles", offsetof(DsType, cycles), hdf5pp::TypeTraits<uint32_t>::native_type());
hdf5pp::VlenType _array_type_entries = hdf5pp::VlenType::vlenType(hdf5pp::TypeTraits<EvrData::ns_SequencerEntry_v0::dataset_data>::native_type());
type.insert("entries", offsetof(DsType, vlen_entries), _array_type_entries);
return type;
}
hdf5pp::Type ns_SequencerConfigV1_v0::dataset_config::native_type()
{
static hdf5pp::Type type = ns_SequencerConfigV1_v0_dataset_config_native_type();
return type;
}
ns_SequencerConfigV1_v0::dataset_config::dataset_config()
{
this->vlen_entries = 0;
this->entries = 0;
}
ns_SequencerConfigV1_v0::dataset_config::~dataset_config()
{
free(this->entries);
}
Psana::EvrData::SequencerConfigV1::Source SequencerConfigV1_v0::sync_source() const {
if (not m_ds_config) read_ds_config();
return Psana::EvrData::SequencerConfigV1::Source(m_ds_config->sync_source);
}
Psana::EvrData::SequencerConfigV1::Source SequencerConfigV1_v0::beam_source() const {
if (not m_ds_config) read_ds_config();
return Psana::EvrData::SequencerConfigV1::Source(m_ds_config->beam_source);
}
uint32_t SequencerConfigV1_v0::length() const {
if (not m_ds_config) read_ds_config();
return uint32_t(m_ds_config->length);
}
uint32_t SequencerConfigV1_v0::cycles() const {
if (not m_ds_config) read_ds_config();
return uint32_t(m_ds_config->cycles);
}
ndarray<const Psana::EvrData::SequencerEntry, 1> SequencerConfigV1_v0::entries() const {
if (not m_ds_config) read_ds_config();
if (m_ds_storage_config_entries.empty()) {
unsigned shape[] = {m_ds_config->vlen_entries};
ndarray<Psana::EvrData::SequencerEntry, 1> tmparr(shape);
std::copy(m_ds_config->entries, m_ds_config->entries+m_ds_config->vlen_entries, tmparr.begin());
m_ds_storage_config_entries = tmparr;
}
return m_ds_storage_config_entries;
}
void SequencerConfigV1_v0::read_ds_config() const {
m_ds_config = hdf5pp::Utils::readGroup<EvrData::ns_SequencerConfigV1_v0::dataset_config>(m_group, "config", m_idx);
}
hdf5pp::Type ns_ConfigV5_v0_dataset_config_stored_type()
{
typedef ns_ConfigV5_v0::dataset_config DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("neventcodes", offsetof(DsType, neventcodes), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("npulses", offsetof(DsType, npulses), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("noutputs", offsetof(DsType, noutputs), hdf5pp::TypeTraits<uint32_t>::stored_type());
return type;
}
hdf5pp::Type ns_ConfigV5_v0::dataset_config::stored_type()
{
static hdf5pp::Type type = ns_ConfigV5_v0_dataset_config_stored_type();
return type;
}
hdf5pp::Type ns_ConfigV5_v0_dataset_config_native_type()
{
typedef ns_ConfigV5_v0::dataset_config DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("neventcodes", offsetof(DsType, neventcodes), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("npulses", offsetof(DsType, npulses), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("noutputs", offsetof(DsType, noutputs), hdf5pp::TypeTraits<uint32_t>::native_type());
return type;
}
hdf5pp::Type ns_ConfigV5_v0::dataset_config::native_type()
{
static hdf5pp::Type type = ns_ConfigV5_v0_dataset_config_native_type();
return type;
}
ns_ConfigV5_v0::dataset_config::dataset_config()
{
}
ns_ConfigV5_v0::dataset_config::~dataset_config()
{
}
uint32_t ConfigV5_v0::neventcodes() const {
if (not m_ds_config) read_ds_config();
return uint32_t(m_ds_config->neventcodes);
}
uint32_t ConfigV5_v0::npulses() const {
if (not m_ds_config) read_ds_config();
return uint32_t(m_ds_config->npulses);
}
uint32_t ConfigV5_v0::noutputs() const {
if (not m_ds_config) read_ds_config();
return uint32_t(m_ds_config->noutputs);
}
ndarray<const Psana::EvrData::EventCodeV5, 1> ConfigV5_v0::eventcodes() const {
if (m_ds_eventcodes.empty()) read_ds_eventcodes();
return m_ds_eventcodes;
}
ndarray<const Psana::EvrData::PulseConfigV3, 1> ConfigV5_v0::pulses() const {
if (m_ds_pulses.empty()) read_ds_pulses();
return m_ds_pulses;
}
ndarray<const Psana::EvrData::OutputMap, 1> ConfigV5_v0::output_maps() const {
if (m_ds_output_maps.empty()) read_ds_output_maps();
return m_ds_output_maps;
}
const Psana::EvrData::SequencerConfigV1& ConfigV5_v0::seq_config() const {
if (not m_ds_storage_seq_config) {
if (not m_ds_seq_config) read_ds_seq_config();
m_ds_storage_seq_config = boost::make_shared<EvrData::SequencerConfigV1_v0>(m_ds_seq_config);
}
return *m_ds_storage_seq_config;
}
void ConfigV5_v0::read_ds_config() const {
m_ds_config = hdf5pp::Utils::readGroup<EvrData::ns_ConfigV5_v0::dataset_config>(m_group, "config", m_idx);
}
void ConfigV5_v0::read_ds_eventcodes() const {
ndarray<EvrData::ns_EventCodeV5_v0::dataset_data, 1> arr = hdf5pp::Utils::readNdarray<EvrData::ns_EventCodeV5_v0::dataset_data, 1>(m_group, "eventcodes", m_idx);
ndarray<Psana::EvrData::EventCodeV5, 1> tmp(arr.shape());
std::copy(arr.begin(), arr.end(), tmp.begin());
m_ds_eventcodes = tmp;
}
void ConfigV5_v0::read_ds_pulses() const {
ndarray<EvrData::ns_PulseConfigV3_v0::dataset_data, 1> arr = hdf5pp::Utils::readNdarray<EvrData::ns_PulseConfigV3_v0::dataset_data, 1>(m_group, "pulses", m_idx);
ndarray<Psana::EvrData::PulseConfigV3, 1> tmp(arr.shape());
std::copy(arr.begin(), arr.end(), tmp.begin());
m_ds_pulses = tmp;
}
void ConfigV5_v0::read_ds_output_maps() const {
ndarray<EvrData::ns_OutputMap_v0::dataset_data, 1> arr = hdf5pp::Utils::readNdarray<EvrData::ns_OutputMap_v0::dataset_data, 1>(m_group, "output_maps", m_idx);
ndarray<Psana::EvrData::OutputMap, 1> tmp(arr.shape());
std::copy(arr.begin(), arr.end(), tmp.begin());
m_ds_output_maps = tmp;
}
void ConfigV5_v0::read_ds_seq_config() const {
m_ds_seq_config = hdf5pp::Utils::readGroup<EvrData::ns_SequencerConfigV1_v0::dataset_config>(m_group, "seq_config", m_idx);
m_ds_storage_seq_config = boost::make_shared<SequencerConfigV1_v0>(m_ds_seq_config);
}
boost::shared_ptr<PSEvt::Proxy<Psana::EvrData::ConfigV5> > make_ConfigV5(int version, hdf5pp::Group group, hsize_t idx) {
switch (version) {
case 0:
return boost::make_shared<PSEvt::DataProxy<Psana::EvrData::ConfigV5> >(boost::make_shared<ConfigV5_v0>(group, idx));
default:
return boost::make_shared<PSEvt::DataProxy<Psana::EvrData::ConfigV5> >(boost::shared_ptr<Psana::EvrData::ConfigV5>());
}
}
hdf5pp::Type ns_ConfigV6_v0_dataset_config_stored_type()
{
typedef ns_ConfigV6_v0::dataset_config DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("neventcodes", offsetof(DsType, neventcodes), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("npulses", offsetof(DsType, npulses), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("noutputs", offsetof(DsType, noutputs), hdf5pp::TypeTraits<uint32_t>::stored_type());
return type;
}
hdf5pp::Type ns_ConfigV6_v0::dataset_config::stored_type()
{
static hdf5pp::Type type = ns_ConfigV6_v0_dataset_config_stored_type();
return type;
}
hdf5pp::Type ns_ConfigV6_v0_dataset_config_native_type()
{
typedef ns_ConfigV6_v0::dataset_config DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("neventcodes", offsetof(DsType, neventcodes), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("npulses", offsetof(DsType, npulses), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("noutputs", offsetof(DsType, noutputs), hdf5pp::TypeTraits<uint32_t>::native_type());
return type;
}
hdf5pp::Type ns_ConfigV6_v0::dataset_config::native_type()
{
static hdf5pp::Type type = ns_ConfigV6_v0_dataset_config_native_type();
return type;
}
ns_ConfigV6_v0::dataset_config::dataset_config()
{
}
ns_ConfigV6_v0::dataset_config::~dataset_config()
{
}
uint32_t ConfigV6_v0::neventcodes() const {
if (not m_ds_config) read_ds_config();
return uint32_t(m_ds_config->neventcodes);
}
uint32_t ConfigV6_v0::npulses() const {
if (not m_ds_config) read_ds_config();
return uint32_t(m_ds_config->npulses);
}
uint32_t ConfigV6_v0::noutputs() const {
if (not m_ds_config) read_ds_config();
return uint32_t(m_ds_config->noutputs);
}
ndarray<const Psana::EvrData::EventCodeV5, 1> ConfigV6_v0::eventcodes() const {
if (m_ds_eventcodes.empty()) read_ds_eventcodes();
return m_ds_eventcodes;
}
ndarray<const Psana::EvrData::PulseConfigV3, 1> ConfigV6_v0::pulses() const {
if (m_ds_pulses.empty()) read_ds_pulses();
return m_ds_pulses;
}
ndarray<const Psana::EvrData::OutputMapV2, 1> ConfigV6_v0::output_maps() const {
if (m_ds_output_maps.empty()) read_ds_output_maps();
return m_ds_output_maps;
}
const Psana::EvrData::SequencerConfigV1& ConfigV6_v0::seq_config() const {
if (not m_ds_storage_seq_config) {
if (not m_ds_seq_config) read_ds_seq_config();
m_ds_storage_seq_config = boost::make_shared<EvrData::SequencerConfigV1_v0>(m_ds_seq_config);
}
return *m_ds_storage_seq_config;
}
void ConfigV6_v0::read_ds_config() const {
m_ds_config = hdf5pp::Utils::readGroup<EvrData::ns_ConfigV6_v0::dataset_config>(m_group, "config", m_idx);
}
void ConfigV6_v0::read_ds_eventcodes() const {
ndarray<EvrData::ns_EventCodeV5_v0::dataset_data, 1> arr = hdf5pp::Utils::readNdarray<EvrData::ns_EventCodeV5_v0::dataset_data, 1>(m_group, "eventcodes", m_idx);
ndarray<Psana::EvrData::EventCodeV5, 1> tmp(arr.shape());
std::copy(arr.begin(), arr.end(), tmp.begin());
m_ds_eventcodes = tmp;
}
void ConfigV6_v0::read_ds_pulses() const {
ndarray<EvrData::ns_PulseConfigV3_v0::dataset_data, 1> arr = hdf5pp::Utils::readNdarray<EvrData::ns_PulseConfigV3_v0::dataset_data, 1>(m_group, "pulses", m_idx);
ndarray<Psana::EvrData::PulseConfigV3, 1> tmp(arr.shape());
std::copy(arr.begin(), arr.end(), tmp.begin());
m_ds_pulses = tmp;
}
void ConfigV6_v0::read_ds_output_maps() const {
ndarray<EvrData::ns_OutputMapV2_v0::dataset_data, 1> arr = hdf5pp::Utils::readNdarray<EvrData::ns_OutputMapV2_v0::dataset_data, 1>(m_group, "output_maps", m_idx);
ndarray<Psana::EvrData::OutputMapV2, 1> tmp(arr.shape());
std::copy(arr.begin(), arr.end(), tmp.begin());
m_ds_output_maps = tmp;
}
void ConfigV6_v0::read_ds_seq_config() const {
m_ds_seq_config = hdf5pp::Utils::readGroup<EvrData::ns_SequencerConfigV1_v0::dataset_config>(m_group, "seq_config", m_idx);
m_ds_storage_seq_config = boost::make_shared<SequencerConfigV1_v0>(m_ds_seq_config);
}
boost::shared_ptr<PSEvt::Proxy<Psana::EvrData::ConfigV6> > make_ConfigV6(int version, hdf5pp::Group group, hsize_t idx) {
switch (version) {
case 0:
return boost::make_shared<PSEvt::DataProxy<Psana::EvrData::ConfigV6> >(boost::make_shared<ConfigV6_v0>(group, idx));
default:
return boost::make_shared<PSEvt::DataProxy<Psana::EvrData::ConfigV6> >(boost::shared_ptr<Psana::EvrData::ConfigV6>());
}
}
hdf5pp::Type ns_ConfigV7_v0_dataset_config_stored_type()
{
typedef ns_ConfigV7_v0::dataset_config DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("neventcodes", offsetof(DsType, neventcodes), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("npulses", offsetof(DsType, npulses), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("noutputs", offsetof(DsType, noutputs), hdf5pp::TypeTraits<uint32_t>::stored_type());
return type;
}
hdf5pp::Type ns_ConfigV7_v0::dataset_config::stored_type()
{
static hdf5pp::Type type = ns_ConfigV7_v0_dataset_config_stored_type();
return type;
}
hdf5pp::Type ns_ConfigV7_v0_dataset_config_native_type()
{
typedef ns_ConfigV7_v0::dataset_config DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("neventcodes", offsetof(DsType, neventcodes), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("npulses", offsetof(DsType, npulses), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("noutputs", offsetof(DsType, noutputs), hdf5pp::TypeTraits<uint32_t>::native_type());
return type;
}
hdf5pp::Type ns_ConfigV7_v0::dataset_config::native_type()
{
static hdf5pp::Type type = ns_ConfigV7_v0_dataset_config_native_type();
return type;
}
ns_ConfigV7_v0::dataset_config::dataset_config()
{
}
ns_ConfigV7_v0::dataset_config::~dataset_config()
{
}
uint32_t ConfigV7_v0::neventcodes() const {
if (not m_ds_config) read_ds_config();
return uint32_t(m_ds_config->neventcodes);
}
uint32_t ConfigV7_v0::npulses() const {
if (not m_ds_config) read_ds_config();
return uint32_t(m_ds_config->npulses);
}
uint32_t ConfigV7_v0::noutputs() const {
if (not m_ds_config) read_ds_config();
return uint32_t(m_ds_config->noutputs);
}
ndarray<const Psana::EvrData::EventCodeV6, 1> ConfigV7_v0::eventcodes() const {
if (m_ds_eventcodes.empty()) read_ds_eventcodes();
return m_ds_eventcodes;
}
ndarray<const Psana::EvrData::PulseConfigV3, 1> ConfigV7_v0::pulses() const {
if (m_ds_pulses.empty()) read_ds_pulses();
return m_ds_pulses;
}
ndarray<const Psana::EvrData::OutputMapV2, 1> ConfigV7_v0::output_maps() const {
if (m_ds_output_maps.empty()) read_ds_output_maps();
return m_ds_output_maps;
}
const Psana::EvrData::SequencerConfigV1& ConfigV7_v0::seq_config() const {
if (not m_ds_storage_seq_config) {
if (not m_ds_seq_config) read_ds_seq_config();
m_ds_storage_seq_config = boost::make_shared<EvrData::SequencerConfigV1_v0>(m_ds_seq_config);
}
return *m_ds_storage_seq_config;
}
void ConfigV7_v0::read_ds_config() const {
m_ds_config = hdf5pp::Utils::readGroup<EvrData::ns_ConfigV7_v0::dataset_config>(m_group, "config", m_idx);
}
void ConfigV7_v0::read_ds_eventcodes() const {
ndarray<EvrData::ns_EventCodeV6_v0::dataset_data, 1> arr = hdf5pp::Utils::readNdarray<EvrData::ns_EventCodeV6_v0::dataset_data, 1>(m_group, "eventcodes", m_idx);
ndarray<Psana::EvrData::EventCodeV6, 1> tmp(arr.shape());
std::copy(arr.begin(), arr.end(), tmp.begin());
m_ds_eventcodes = tmp;
}
void ConfigV7_v0::read_ds_pulses() const {
ndarray<EvrData::ns_PulseConfigV3_v0::dataset_data, 1> arr = hdf5pp::Utils::readNdarray<EvrData::ns_PulseConfigV3_v0::dataset_data, 1>(m_group, "pulses", m_idx);
ndarray<Psana::EvrData::PulseConfigV3, 1> tmp(arr.shape());
std::copy(arr.begin(), arr.end(), tmp.begin());
m_ds_pulses = tmp;
}
void ConfigV7_v0::read_ds_output_maps() const {
ndarray<EvrData::ns_OutputMapV2_v0::dataset_data, 1> arr = hdf5pp::Utils::readNdarray<EvrData::ns_OutputMapV2_v0::dataset_data, 1>(m_group, "output_maps", m_idx);
ndarray<Psana::EvrData::OutputMapV2, 1> tmp(arr.shape());
std::copy(arr.begin(), arr.end(), tmp.begin());
m_ds_output_maps = tmp;
}
void ConfigV7_v0::read_ds_seq_config() const {
m_ds_seq_config = hdf5pp::Utils::readGroup<EvrData::ns_SequencerConfigV1_v0::dataset_config>(m_group, "seq_config", m_idx);
m_ds_storage_seq_config = boost::make_shared<SequencerConfigV1_v0>(m_ds_seq_config);
}
boost::shared_ptr<PSEvt::Proxy<Psana::EvrData::ConfigV7> > make_ConfigV7(int version, hdf5pp::Group group, hsize_t idx) {
switch (version) {
case 0:
return boost::make_shared<PSEvt::DataProxy<Psana::EvrData::ConfigV7> >(boost::make_shared<ConfigV7_v0>(group, idx));
default:
return boost::make_shared<PSEvt::DataProxy<Psana::EvrData::ConfigV7> >(boost::shared_ptr<Psana::EvrData::ConfigV7>());
}
}
hdf5pp::Type ns_FIFOEvent_v0_dataset_data_stored_type()
{
typedef ns_FIFOEvent_v0::dataset_data DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("timestampHigh", offsetof(DsType, timestampHigh), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("timestampLow", offsetof(DsType, timestampLow), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("eventCode", offsetof(DsType, eventCode), hdf5pp::TypeTraits<uint32_t>::stored_type());
return type;
}
hdf5pp::Type ns_FIFOEvent_v0::dataset_data::stored_type()
{
static hdf5pp::Type type = ns_FIFOEvent_v0_dataset_data_stored_type();
return type;
}
hdf5pp::Type ns_FIFOEvent_v0_dataset_data_native_type()
{
typedef ns_FIFOEvent_v0::dataset_data DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("timestampHigh", offsetof(DsType, timestampHigh), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("timestampLow", offsetof(DsType, timestampLow), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("eventCode", offsetof(DsType, eventCode), hdf5pp::TypeTraits<uint32_t>::native_type());
return type;
}
hdf5pp::Type ns_FIFOEvent_v0::dataset_data::native_type()
{
static hdf5pp::Type type = ns_FIFOEvent_v0_dataset_data_native_type();
return type;
}
ns_FIFOEvent_v0::dataset_data::dataset_data()
{
}
ns_FIFOEvent_v0::dataset_data::~dataset_data()
{
}
boost::shared_ptr<Psana::EvrData::FIFOEvent>
Proxy_FIFOEvent_v0::getTypedImpl(PSEvt::ProxyDictI* dict, const Pds::Src& source, const std::string& key)
{
if (not m_data) {
boost::shared_ptr<EvrData::ns_FIFOEvent_v0::dataset_data> ds_data = hdf5pp::Utils::readGroup<EvrData::ns_FIFOEvent_v0::dataset_data>(m_group, "data", m_idx);
m_data.reset(new PsanaType(ds_data->timestampHigh, ds_data->timestampLow, ds_data->eventCode));
}
return m_data;
}
boost::shared_ptr<PSEvt::Proxy<Psana::EvrData::FIFOEvent> > make_FIFOEvent(int version, hdf5pp::Group group, hsize_t idx) {
switch (version) {
case 0:
return boost::make_shared<Proxy_FIFOEvent_v0>(group, idx);
default:
return boost::make_shared<PSEvt::DataProxy<Psana::EvrData::FIFOEvent> >(boost::shared_ptr<Psana::EvrData::FIFOEvent>());
}
}
hdf5pp::Type ns_DataV3_v0_dataset_data_stored_type()
{
typedef ns_DataV3_v0::dataset_data DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
hdf5pp::VlenType _array_type_fifoEvents = hdf5pp::VlenType::vlenType(hdf5pp::TypeTraits<EvrData::ns_FIFOEvent_v0::dataset_data>::stored_type());
type.insert("fifoEvents", offsetof(DsType, vlen_fifoEvents), _array_type_fifoEvents);
return type;
}
hdf5pp::Type ns_DataV3_v0::dataset_data::stored_type()
{
static hdf5pp::Type type = ns_DataV3_v0_dataset_data_stored_type();
return type;
}
hdf5pp::Type ns_DataV3_v0_dataset_data_native_type()
{
typedef ns_DataV3_v0::dataset_data DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
hdf5pp::VlenType _array_type_fifoEvents = hdf5pp::VlenType::vlenType(hdf5pp::TypeTraits<EvrData::ns_FIFOEvent_v0::dataset_data>::native_type());
type.insert("fifoEvents", offsetof(DsType, vlen_fifoEvents), _array_type_fifoEvents);
return type;
}
hdf5pp::Type ns_DataV3_v0::dataset_data::native_type()
{
static hdf5pp::Type type = ns_DataV3_v0_dataset_data_native_type();
return type;
}
ns_DataV3_v0::dataset_data::dataset_data()
{
this->vlen_fifoEvents = 0;
this->fifoEvents = 0;
}
ns_DataV3_v0::dataset_data::~dataset_data()
{
free(this->fifoEvents);
}
ndarray<const Psana::EvrData::FIFOEvent, 1> DataV3_v0::fifoEvents() const {
if (not m_ds_data) read_ds_data();
if (m_ds_storage_data_fifoEvents.empty()) {
unsigned shape[] = {m_ds_data->vlen_fifoEvents};
ndarray<Psana::EvrData::FIFOEvent, 1> tmparr(shape);
std::copy(m_ds_data->fifoEvents, m_ds_data->fifoEvents+m_ds_data->vlen_fifoEvents, tmparr.begin());
m_ds_storage_data_fifoEvents = tmparr;
}
return m_ds_storage_data_fifoEvents;
}
void DataV3_v0::read_ds_data() const {
m_ds_data = hdf5pp::Utils::readGroup<EvrData::ns_DataV3_v0::dataset_data>(m_group, "data", m_idx);
}
boost::shared_ptr<PSEvt::Proxy<Psana::EvrData::DataV3> > make_DataV3(int version, hdf5pp::Group group, hsize_t idx) {
switch (version) {
case 0:
return boost::make_shared<PSEvt::DataProxy<Psana::EvrData::DataV3> >(boost::make_shared<DataV3_v0>(group, idx));
default:
return boost::make_shared<PSEvt::DataProxy<Psana::EvrData::DataV3> >(boost::shared_ptr<Psana::EvrData::DataV3>());
}
}
boost::shared_ptr<PSEvt::Proxy<Psana::EvrData::IOConfigV1> > make_IOConfigV1(int version, hdf5pp::Group group, hsize_t idx) {
switch (version) {
case 0:
return boost::make_shared<PSEvt::DataProxy<Psana::EvrData::IOConfigV1> >(boost::make_shared<IOConfigV1_v0>(group, idx));
default:
return boost::make_shared<PSEvt::DataProxy<Psana::EvrData::IOConfigV1> >(boost::shared_ptr<Psana::EvrData::IOConfigV1>());
}
}
} // namespace EvrData
} // namespace psddl_hdf2psana
| [
"salnikov@SLAC.STANFORD.EDU@b967ad99-d558-0410-b138-e0f6c56caec7"
] | salnikov@SLAC.STANFORD.EDU@b967ad99-d558-0410-b138-e0f6c56caec7 |
275167a149226ef63d8708ec0e1aab44e33e9454 | bd7486a56e71b520d0016f170aafa9633d44f05b | /multiwinia/code/worldobject/eruptionmarker.h | c096b0a6ece3cbb95c88cf800f1bf3f4daa76d97 | [] | no_license | bsella/Darwinia-and-Multiwinia-Source-Code | 3bf1d7117f1be48a7038e2ab9f7d385bf82852d1 | 22f2069b9228a02c7e2953ace1ea63c2ef534e41 | refs/heads/master | 2022-05-31T18:35:59.264774 | 2022-04-24T22:40:30 | 2022-04-24T22:40:30 | 290,299,680 | 0 | 0 | null | 2020-08-25T19:02:29 | 2020-08-25T19:02:29 | null | UTF-8 | C++ | false | false | 650 | h | #ifndef _included_eruptionmarker_h
#define _included_eruptionmarker_h
#include "worldobject/building.h"
class EruptionMarker : public Building
{
public:
bool m_erupting;
double m_timer;
EruptionMarker();
bool Advance();
void RenderAlphas( double _predictionTime );
bool DoesSphereHit (Vector3 const &_pos, double _radius);
bool DoesShapeHit (Shape *_shape, Matrix34 _transform);
bool DoesRayHit (Vector3 const &_rayStart, Vector3 const &_rayDir,
double _rayLen=1e10, Vector3 *_pos=NULL, Vector3 *_norm=NULL);
};
#endif | [
"root@9244cb4f-d52e-49a9-a756-7d4e53ad8306"
] | root@9244cb4f-d52e-49a9-a756-7d4e53ad8306 |
3006ad6b2839e29195c2e920608bbab905f089e3 | bd8dff663c463faa69e2bfa9ee177b50c617f701 | /A1030.cpp | e551f7ea6c3ba3f5d2146f9858f590542d50b04e | [] | no_license | Gabriel-18/PAT | 94b8b0b02955458f736f781246d91b9c6ee25794 | f66e5f6c6db22e1be28b738523cb589e9ce12b11 | refs/heads/master | 2022-12-07T08:15:11.181501 | 2020-09-05T01:27:38 | 2020-09-05T01:28:18 | 198,178,163 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,181 | cpp | //
// Created by kelper on 2019/12/18.
//
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
const int MAXV = 510;
const int INF = 1000000000;
int n, m, st, ed, G[MAXV][MAXV], cost[MAXV][MAXV];
int d[MAXV], minCost = INF;
bool vis[MAXV] = {false};
vector<int> pre[MAXV];
vector<int > tempPath, path;
void Dijkstra(int s) {
fill(d, d + MAXV, INF);
d[s] = 0;
for (int i = 0; i < n; ++i) {
int u = -1, MIN = INF;
for (int j = 0; j < n; ++j) {
if (vis[j] == false && d[j] < MIN) {
u = j;
MIN = d[j];
}
}
if (u == -1) {
return;
}
vis[u] = true;
for (int v = 0; v < n; ++v) {
if (vis[v] == false && G[u][v] != INF) {
if (d[u] + G[u][v] < d[v]) {
d[v] = d[u] + G[u][v];
pre[v].clear();
pre[v].push_back(u);
} else if (d[u] + G[u][v] == d[v]) {
pre[v].push_back(u);
}
}
}
}
}
void DFS(int v) {
if (v == st) {
tempPath.push_back(v);
int tempCost = 0;
for (int i = tempPath.size() - 1; i > 0; --i) {
int id = tempPath[i], idNext = tempPath[i - 1];
tempCost += cost[id][idNext];
}
if (tempCost < minCost) {
minCost = tempCost;
path = tempPath;
}
tempPath.pop_back();
return;
}
tempPath.push_back(v);
for (int i = 0; i < pre[v].size(); ++i) {
DFS(pre[v][i]);
}
tempPath.pop_back();
}
int main() {
scanf("%d%d%d%d", &n, &m, &st, &ed);
int u, v;
fill(G[0], G[0] + MAXV * MAXV, INF);
fill(cost[0], cost[0] + MAXV * MAXV, INF);
for (int i = 0; i < m; i++) {
scanf("%d%d", &u, &v);
scanf("%d%d", &G[u][v], &cost[u][v]);
G[v][u] = G[u][v];
cost[v][u] = cost[u][v];
}
Dijkstra(st);
DFS(ed);
for (int i = path.size() - 1; i >= 0; --i) {
printf("%d ", path[i]);
}
printf("%d %d\n", d[ed], minCost);
return 0;
} | [
"644050173@qq.com"
] | 644050173@qq.com |
019d3d796096dbd083103cac09e2a185adcef2be | ad74f7a42e8dec14ec7576252fcbc3fc46679f27 | /BTIPGatherer/BTDBInterface.cpp | 3f19d96804e64e0f1fa3f2e0dca191e1ab5becfe | [] | no_license | radtek/TrapperKeeper | 56fed7afa259aee20d6d81e71e19786f2f0d9418 | 63f87606ae02e7c29608fedfdf8b7e65339b8e9a | refs/heads/master | 2020-05-29T16:49:29.708375 | 2013-05-15T08:33:23 | 2013-05-15T08:33:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 130 | cpp | #include "StdAfx.h"
#include ".\btdbinterface.h"
BTDBInterface::BTDBInterface(void)
{
}
BTDBInterface::~BTDBInterface(void)
{
}
| [
"occupymyday@gmail.com"
] | occupymyday@gmail.com |
f4e65e039255705ed6c573283f4fbdc74b66d9ad | f1869dbbac579b48b32c9c5fdee70146ceb56ecf | /art/runtime/elf_file.h | f72b4edde9ae14fb2d8df81414cea32eaeeab202 | [
"NCSA",
"Apache-2.0"
] | permissive | verdigrass/ART | 49346fff5d2cada657d24eb1be9d54421a8c9b0a | bf45638eb74cd978ff25d51b03f81551c5482c1d | refs/heads/master | 2021-01-01T06:14:49.012752 | 2017-07-16T15:10:36 | 2017-07-16T15:10:36 | 97,390,820 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,283 | h | /*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ART_RUNTIME_ELF_FILE_H_
#define ART_RUNTIME_ELF_FILE_H_
#include <map>
#include <memory>
#include <vector>
#include "base/unix_file/fd_file.h"
#include "globals.h"
#include "elf_utils.h"
#include "mem_map.h"
#include "os.h"
namespace art {
// Interface to GDB JIT for backtrace information.
extern "C" {
struct JITCodeEntry;
}
// Used for compile time and runtime for ElfFile access. Because of
// the need for use at runtime, cannot directly use LLVM classes such as
// ELFObjectFile.
class ElfFile {
public:
static ElfFile* Open(File* file, bool writable, bool program_header_only, std::string* error_msg);
// Open with specific mmap flags, Always maps in the whole file, not just the
// program header sections.
static ElfFile* Open(File* file, int mmap_prot, int mmap_flags, std::string* error_msg);
~ElfFile();
// Load segments into memory based on PT_LOAD program headers
const File& GetFile() const {
return *file_;
}
byte* Begin() const {
return map_->Begin();
}
byte* End() const {
return map_->End();
}
size_t Size() const {
return map_->Size();
}
Elf32_Ehdr& GetHeader() const;
Elf32_Word GetProgramHeaderNum() const;
Elf32_Phdr* GetProgramHeader(Elf32_Word) const;
Elf32_Word GetSectionHeaderNum() const;
Elf32_Shdr* GetSectionHeader(Elf32_Word) const;
Elf32_Shdr* FindSectionByType(Elf32_Word type) const;
Elf32_Shdr* FindSectionByName(const std::string& name) const;
Elf32_Shdr* GetSectionNameStringSection() const;
// Find .dynsym using .hash for more efficient lookup than FindSymbolAddress.
const byte* FindDynamicSymbolAddress(const std::string& symbol_name) const;
Elf32_Word GetSymbolNum(Elf32_Shdr&) const;
Elf32_Sym* GetSymbol(Elf32_Word section_type, Elf32_Word i) const;
// Find address of symbol in specified table, returning 0 if it is
// not found. See FindSymbolByName for an explanation of build_map.
Elf32_Addr FindSymbolAddress(Elf32_Word section_type,
const std::string& symbol_name,
bool build_map);
// Lookup a string given string section and offset. Returns nullptr for
// special 0 offset.
const char* GetString(Elf32_Shdr&, Elf32_Word) const;
Elf32_Word GetDynamicNum() const;
Elf32_Dyn& GetDynamic(Elf32_Word) const;
Elf32_Word GetRelNum(Elf32_Shdr&) const;
Elf32_Rel& GetRel(Elf32_Shdr&, Elf32_Word) const;
Elf32_Word GetRelaNum(Elf32_Shdr&) const;
Elf32_Rela& GetRela(Elf32_Shdr&, Elf32_Word) const;
// Returns the expected size when the file is loaded at runtime
size_t GetLoadedSize() const;
// Load segments into memory based on PT_LOAD program headers.
// executable is true at run time, false at compile time.
bool Load(bool executable, std::string* error_msg);
private:
ElfFile(File* file, bool writable, bool program_header_only);
bool Setup(int prot, int flags, std::string* error_msg);
bool SetMap(MemMap* map, std::string* error_msg);
byte* GetProgramHeadersStart() const;
byte* GetSectionHeadersStart() const;
Elf32_Phdr& GetDynamicProgramHeader() const;
Elf32_Dyn* GetDynamicSectionStart() const;
Elf32_Sym* GetSymbolSectionStart(Elf32_Word section_type) const;
const char* GetStringSectionStart(Elf32_Word section_type) const;
Elf32_Rel* GetRelSectionStart(Elf32_Shdr&) const;
Elf32_Rela* GetRelaSectionStart(Elf32_Shdr&) const;
Elf32_Word* GetHashSectionStart() const;
Elf32_Word GetHashBucketNum() const;
Elf32_Word GetHashChainNum() const;
Elf32_Word GetHashBucket(size_t i, bool* ok) const;
Elf32_Word GetHashChain(size_t i, bool* ok) const;
typedef std::map<std::string, Elf32_Sym*> SymbolTable;
SymbolTable** GetSymbolTable(Elf32_Word section_type);
bool ValidPointer(const byte* start) const;
const Elf32_Sym* FindDynamicSymbol(const std::string& symbol_name) const;
// Check that certain sections and their dependencies exist.
bool CheckSectionsExist(std::string* error_msg) const;
// Check that the link of the first section links to the second section.
bool CheckSectionsLinked(const byte* source, const byte* target) const;
// Check whether the offset is in range, and set to target to Begin() + offset if OK.
bool CheckAndSet(Elf32_Off offset, const char* label, byte** target, std::string* error_msg);
// Find symbol in specified table, returning nullptr if it is not found.
//
// If build_map is true, builds a map to speed repeated access. The
// map does not included untyped symbol values (aka STT_NOTYPE)
// since they can contain duplicates. If build_map is false, the map
// will be used if it was already created. Typically build_map
// should be set unless only a small number of symbols will be
// looked up.
Elf32_Sym* FindSymbolByName(Elf32_Word section_type,
const std::string& symbol_name,
bool build_map);
Elf32_Phdr* FindProgamHeaderByType(Elf32_Word type) const;
Elf32_Dyn* FindDynamicByType(Elf32_Sword type) const;
Elf32_Word FindDynamicValueByType(Elf32_Sword type) const;
// Lookup a string by section type. Returns nullptr for special 0 offset.
const char* GetString(Elf32_Word section_type, Elf32_Word) const;
const File* const file_;
const bool writable_;
const bool program_header_only_;
// ELF header mapping. If program_header_only_ is false, will
// actually point to the entire elf file.
std::unique_ptr<MemMap> map_;
Elf32_Ehdr* header_;
std::vector<MemMap*> segments_;
// Pointer to start of first PT_LOAD program segment after Load()
// when program_header_only_ is true.
byte* base_address_;
// The program header should always available but use GetProgramHeadersStart() to be sure.
byte* program_headers_start_;
// Conditionally available values. Use accessors to ensure they exist if they are required.
byte* section_headers_start_;
Elf32_Phdr* dynamic_program_header_;
Elf32_Dyn* dynamic_section_start_;
Elf32_Sym* symtab_section_start_;
Elf32_Sym* dynsym_section_start_;
char* strtab_section_start_;
char* dynstr_section_start_;
Elf32_Word* hash_section_start_;
SymbolTable* symtab_symbol_table_;
SymbolTable* dynsym_symbol_table_;
// Support for GDB JIT
byte* jit_elf_image_;
JITCodeEntry* jit_gdb_entry_;
std::unique_ptr<ElfFile> gdb_file_mapping_;
void GdbJITSupport();
};
} // namespace art
#endif // ART_RUNTIME_ELF_FILE_H_
| [
"future.tiger@163.com"
] | future.tiger@163.com |
db263a95799ae11c3e85e98332f53e8960820e6f | ea714cbbf855a6f05eb17fab820bbcd453d3d42b | /Uneven_3d_array.h | 52bc37cc8a2d28d66f221a7ca72981f5ebe6bf40 | [] | no_license | DaniilKam/Uneven-array | 3c34658583d6910c2aab08bd56f23bbcbd119298 | 67a8c701e801c56755bf62d75689f85c97d91939 | refs/heads/master | 2022-07-03T14:51:30.881661 | 2020-05-12T16:49:53 | 2020-05-12T16:49:53 | 263,394,650 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 909 | h | #pragma once
#ifndef _UNEVEN_3D_ARRAY_H_
#define _UNEVEN_3D_ARRAY_H_
#include <cstdint>
#include "Uneven_2d_array_.h"
#include "Uneven_setup.h"
class Une3DArray
{
public:
uint8_t PreInit(uint32_t ArraysCount);
uint8_t Init();
uint8_t SetLayerCount(uint32_t Array, uint32_t LayerCount);
uint8_t SetLayerSize(uint32_t Array, uint32_t Layer, uint32_t Size);
uint8_t wr(uint32_t Array, uint32_t Layer, uint32_t pos, TypeVar val);
TypeVar rd(uint32_t Array, uint32_t Layer, uint32_t pos);
uint8_t Create();
uint8_t Delete();
private:
uint32_t getPos(uint32_t Array, uint32_t Layer, uint32_t pos);
TypeVar* Arrays;
uint32_t Arrays_count = 1;
uint32_t* Layers_count;
uint32_t Size = 0;
UneArray_ Layers_size; //layer - Array; pos - layer, val - Size
UneArray_ Shift;
bool preinit = false;
bool init = false;
bool build = false;
};
#endif // !_UNEVEN_3D_ARRAY_H_ | [
"noreply@github.com"
] | noreply@github.com |
5ed1cc0dc73c1394d491f5f8ea95013e2ab5fd72 | 287dc1683f7e19a5239c2b8addbc8531809f9177 | /boboleetcode/Play-Leetcode-master/0210-Course-Schedule-II/cpp-0210/main2.cpp | a29f047cc74810e6ad5a360519aed0bbcf7645a9 | [
"Apache-2.0"
] | permissive | yaominzh/CodeLrn2019 | ea192cf18981816c6adafe43d85e2462d4bc6e5d | adc727d92904c5c5d445a2621813dfa99474206d | refs/heads/master | 2023-01-06T14:11:45.281011 | 2020-10-28T07:16:32 | 2020-10-28T07:16:32 | 164,027,453 | 2 | 0 | Apache-2.0 | 2023-01-06T00:39:06 | 2019-01-03T22:02:24 | C++ | UTF-8 | C++ | false | false | 1,580 | cpp | /// Source : https://leetcode.com/problems/course-schedule-ii/
/// Author : liuyubobobo
/// Time : 2018-12-16
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
/// Using Queue is enough
/// Since we are only interested in 0-indegree vertex :-)
///
/// Time Complexity: O(E)
/// Space Complexity: O(V + E)
class Solution {
public:
vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<int> pre(numCourses, 0);
vector<vector<int>> g(numCourses);
for(const pair<int, int>& p: prerequisites){
int from = p.second;
int to = p.first;
g[from].push_back(to);
pre[to] ++;
}
queue<int> q;
for(int i = 0; i < numCourses; i ++)
if(pre[i] == 0)
q.push(i);
vector<int> res;
while(!q.empty()){
int id = q.front();
q.pop();
res.push_back(id);
for(int next: g[id]){
pre[next] --;
if(pre[next] == 0)
q.push(next);
}
}
if(res.size() == numCourses)
return res;
return {};
}
};
void print_vec(const vector<int>& vec){
for(int e: vec)
cout << e << " ";
cout << endl;
}
int main() {
vector<pair<int, int>> pre1 = {{1,0}};
print_vec(Solution().findOrder(2, pre1));
// 0 1
vector<pair<int, int>> pre2 = {{1,0},{2,0},{3,1},{3,2}};
print_vec(Solution().findOrder(4, pre2));
// 0 1 2 3
return 0;
} | [
"mcuallen@gmail.com"
] | mcuallen@gmail.com |
1d0503d9e46ea048e2f3ed4724e9e47117a91008 | 8afb5afd38548c631f6f9536846039ef6cb297b9 | /MY_REPOS/misc-experiments/_FIREBFIRE/grpc/test/cpp/util/subprocess.cc | c1cd4ce5e34bafa0d8d0005a2d80cc48f2540401 | [
"Apache-2.0",
"MIT"
] | permissive | bgoonz/UsefulResourceRepo2.0 | d87588ffd668bb498f7787b896cc7b20d83ce0ad | 2cb4b45dd14a230aa0e800042e893f8dfb23beda | refs/heads/master | 2023-03-17T01:22:05.254751 | 2022-08-11T03:18:22 | 2022-08-11T03:18:22 | 382,628,698 | 10 | 12 | MIT | 2022-10-10T14:13:54 | 2021-07-03T13:58:52 | null | UTF-8 | C++ | false | false | 955 | cc | /*
*
* Copyright 2015 gRPC authors.
*
* 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
*
s.h"
#include <vector>
#include "test/core/util/subprocess.h"
namespace grpc {
static gpr_subprocess* MakeProcess(const std::vector<std::string>& args) {
std::vector<const char*> vargs;
for (auto it = args.begin(); it != args.end(); ++it) {
vargs.push_back(it->c_str());
}
return gpr_subprocess_create(vargs.size(), &vargs[0]);
}
SubProcess::SubProcess(const std::vector<std::string>& args)
: subprocess_(MakeProcess(args)) {}
SubProcess::~SubProcess() { gpr_subprocess_destroy(subprocess_); }
int SubProcess::Join() { return gpr_subprocess_join(subprocess_); }
void SubProcess::Interrupt() { gpr_subprocess_interrupt(subprocess_); }
} // namespace grpc
| [
"bryan.guner@gmail.com"
] | bryan.guner@gmail.com |
1e11758270c0eda2da4e35fcb2c9fda0ad16602e | 74ee6252ff75ac3938227522afd630564052811c | /src/rpcwallet.cpp | 91c1a28fd35740f4ada3285eeafcd700226f734c | [
"MIT"
] | permissive | asiacoin15/Asiacoin | bc639758726199f54734d7f54b185de33836b83e | 31de40dd5e4bfb6991a7f236ec4a22db125b42bc | refs/heads/master | 2021-01-10T14:02:38.535107 | 2016-02-14T16:20:12 | 2016-02-14T16:20:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 55,073 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp>
#include "wallet.h"
#include "walletdb.h"
#include "bitcoinrpc.h"
#include "init.h"
#include "base58.h"
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
int64 nWalletUnlockTime;
static CCriticalSection cs_nWalletUnlockTime;
std::string HelpRequiringPassphrase()
{
return pwalletMain && pwalletMain->IsCrypted()
? "\nrequires wallet passphrase to be set with walletpassphrase first"
: "";
}
void EnsureWalletIsUnlocked()
{
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
}
void WalletTxToJSON(const CWalletTx& wtx, Object& entry)
{
int confirms = wtx.GetDepthInMainChain();
entry.push_back(Pair("confirmations", confirms));
if (wtx.IsCoinBase())
entry.push_back(Pair("generated", true));
if (confirms > 0)
{
entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex()));
entry.push_back(Pair("blockindex", wtx.nIndex));
entry.push_back(Pair("blocktime", (boost::int64_t)(mapBlockIndex[wtx.hashBlock]->nTime)));
}
entry.push_back(Pair("txid", wtx.GetHash().GetHex()));
entry.push_back(Pair("normtxid", wtx.GetNormalizedHash().GetHex()));
entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime()));
entry.push_back(Pair("timereceived", (boost::int64_t)wtx.nTimeReceived));
BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue)
entry.push_back(Pair(item.first, item.second));
}
string AccountFromValue(const Value& value)
{
string strAccount = value.get_str();
if (strAccount == "*")
throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name");
return strAccount;
}
Value getinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getinfo\n"
"Returns an object containing various state info.");
proxyType proxy;
GetProxy(NET_IPV4, proxy);
Object obj;
obj.push_back(Pair("version", (int)CLIENT_VERSION));
obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION));
if (pwalletMain) {
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
}
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("timeoffset", (boost::int64_t)GetTimeOffset()));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("proxy", (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string())));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("testnet", fTestNet));
if (pwalletMain) {
obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize()));
}
obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee)));
obj.push_back(Pair("mininput", ValueFromAmount(nMinimumInputValue)));
if (pwalletMain && pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", (boost::int64_t)nWalletUnlockTime));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
return obj;
}
Value getnewaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getnewaddress [account]\n"
"Returns a new Asiacoin address for receiving payments. "
"If [account] is specified (recommended), it is added to the address book "
"so payments received with the address will be credited to [account].");
// Parse the account first so we don't generate a key if there's an error
string strAccount;
if (params.size() > 0)
strAccount = AccountFromValue(params[0]);
if (!pwalletMain->IsLocked())
pwalletMain->TopUpKeyPool();
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwalletMain->GetKeyFromPool(newKey, false))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
CKeyID keyID = newKey.GetID();
pwalletMain->SetAddressBookName(keyID, strAccount);
return CBitcoinAddress(keyID).ToString();
}
CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
CAccount account;
walletdb.ReadAccount(strAccount, account);
bool bKeyUsed = false;
// Check if the current key has been used
if (account.vchPubKey.IsValid())
{
CScript scriptPubKey;
scriptPubKey.SetDestination(account.vchPubKey.GetID());
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();
it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid();
++it)
{
const CWalletTx& wtx = (*it).second;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
bKeyUsed = true;
}
}
// Generate a new key
if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed)
{
if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), strAccount);
walletdb.WriteAccount(strAccount, account);
}
return CBitcoinAddress(account.vchPubKey.GetID());
}
Value getaccountaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccountaddress <account>\n"
"Returns the current Asiacoin address for receiving payments to this account.");
// Parse the account first so we don't generate a key if there's an error
string strAccount = AccountFromValue(params[0]);
Value ret;
ret = GetAccountAddress(strAccount).ToString();
return ret;
}
Value setaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setaccount <asiacoinaddress> <account>\n"
"Sets the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Asiacoin address");
string strAccount;
if (params.size() > 1)
strAccount = AccountFromValue(params[1]);
// Detect when changing the account of an address that is the 'unused current key' of another account:
if (pwalletMain->mapAddressBook.count(address.Get()))
{
string strOldAccount = pwalletMain->mapAddressBook[address.Get()];
if (address == GetAccountAddress(strOldAccount))
GetAccountAddress(strOldAccount, true);
}
pwalletMain->SetAddressBookName(address.Get(), strAccount);
return Value::null;
}
Value getaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccount <asiacoinaddress>\n"
"Returns the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Asiacoin address");
string strAccount;
map<CTxDestination, string>::iterator mi = pwalletMain->mapAddressBook.find(address.Get());
if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty())
strAccount = (*mi).second;
return strAccount;
}
Value getaddressesbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaddressesbyaccount <account>\n"
"Returns the list of addresses for the given account.");
string strAccount = AccountFromValue(params[0]);
// Find all addresses that have the given account
Array ret;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strName = item.second;
if (strName == strAccount)
ret.push_back(address.ToString());
}
return ret;
}
Value setmininput(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1)
throw runtime_error(
"setmininput <amount>\n"
"<amount> is a real and is rounded to the nearest 0.00000001");
// Amount
int64 nAmount = 0;
if (params[0].get_real() != 0.0)
nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts
nMinimumInputValue = nAmount;
return true;
}
Value sendtoaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendtoaddress <asiacoinaddress> <amount> [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.00000001"
+ HelpRequiringPassphrase());
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Asiacoin address");
// Amount
int64 nAmount = AmountFromValue(params[1]);
// Wallet comments
CWalletTx wtx;
if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
wtx.mapValue["comment"] = params[2].get_str();
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["to"] = params[3].get_str();
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
if (strError != "")
throw JSONRPCError(RPC_WALLET_ERROR, strError);
return wtx.GetHash().GetHex();
}
Value listaddressgroupings(const Array& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listaddressgroupings\n"
"Lists groups of addresses which have had their common ownership\n"
"made public by common use as inputs or as the resulting change\n"
"in past transactions");
Array jsonGroupings;
map<CTxDestination, int64> balances = pwalletMain->GetAddressBalances();
BOOST_FOREACH(set<CTxDestination> grouping, pwalletMain->GetAddressGroupings())
{
Array jsonGrouping;
BOOST_FOREACH(CTxDestination address, grouping)
{
Array addressInfo;
addressInfo.push_back(CBitcoinAddress(address).ToString());
addressInfo.push_back(ValueFromAmount(balances[address]));
{
LOCK(pwalletMain->cs_wallet);
if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end())
addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second);
}
jsonGrouping.push_back(addressInfo);
}
jsonGroupings.push_back(jsonGrouping);
}
return jsonGroupings;
}
Value signmessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"signmessage <asiacoinaddress> <message>\n"
"Sign a message with the private key of an address");
EnsureWalletIsUnlocked();
string strAddress = params[0].get_str();
string strMessage = params[1].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
CKey key;
if (!pwalletMain->GetKey(keyID, key))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
vector<unsigned char> vchSig;
if (!key.SignCompact(ss.GetHash(), vchSig))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
return EncodeBase64(&vchSig[0], vchSig.size());
}
Value verifymessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 3)
throw runtime_error(
"verifymessage <asiacoinaddress> <signature> <message>\n"
"Verify a signed message");
string strAddress = params[0].get_str();
string strSign = params[1].get_str();
string strMessage = params[2].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
bool fInvalid = false;
vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
if (fInvalid)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
CPubKey pubkey;
if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))
return false;
return (pubkey.GetID() == keyID);
}
Value getreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaddress <asiacoinaddress> [minconf=1]\n"
"Returns the total amount received by <asiacoinaddress> in transactions with at least [minconf] confirmations.");
// Bitcoin address
CBitcoinAddress address = CBitcoinAddress(params[0].get_str());
CScript scriptPubKey;
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Asiacoin address");
scriptPubKey.SetDestination(address.Get());
if (!IsMine(*pwalletMain,scriptPubKey))
return (double)0.0;
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Tally
int64 nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !wtx.IsFinal())
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
return ValueFromAmount(nAmount);
}
void GetAccountAddresses(string strAccount, set<CTxDestination>& setAddress)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& item, pwalletMain->mapAddressBook)
{
const CTxDestination& address = item.first;
const string& strName = item.second;
if (strName == strAccount)
setAddress.insert(address);
}
}
Value getreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaccount <account> [minconf=1]\n"
"Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.");
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Get the set of pub keys assigned to account
string strAccount = AccountFromValue(params[0]);
set<CTxDestination> setAddress;
GetAccountAddresses(strAccount, setAddress);
// Tally
int64 nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !wtx.IsFinal())
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address))
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
}
return (double)nAmount / (double)COIN;
}
int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth)
{
int64 nBalance = 0;
// Tally wallet transactions
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsFinal())
continue;
int64 nReceived, nSent, nFee;
wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee);
if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth)
nBalance += nReceived;
nBalance -= nSent + nFee;
}
// Tally internal accounting entries
nBalance += walletdb.GetAccountCreditDebit(strAccount);
return nBalance;
}
int64 GetAccountBalance(const string& strAccount, int nMinDepth)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
return GetAccountBalance(walletdb, strAccount, nMinDepth);
}
Value getbalance(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getbalance [account] [minconf=1]\n"
"If [account] is not specified, returns the server's total available balance.\n"
"If [account] is specified, returns the balance in the account.");
if (params.size() == 0)
return ValueFromAmount(pwalletMain->GetBalance());
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
if (params[0].get_str() == "*") {
// Calculate total balance a different way from GetBalance()
// (GetBalance() sums up all unspent TxOuts)
// getbalance and getbalance '*' 0 should return the same number
int64 nBalance = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsConfirmed())
continue;
int64 allFee;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount);
if (wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
nBalance += r.second;
}
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listSent)
nBalance -= r.second;
nBalance -= allFee;
}
return ValueFromAmount(nBalance);
}
string strAccount = AccountFromValue(params[0]);
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
return ValueFromAmount(nBalance);
}
Value movecmd(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 5)
throw runtime_error(
"move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n"
"Move from one account in your wallet to another.");
string strFrom = AccountFromValue(params[0]);
string strTo = AccountFromValue(params[1]);
int64 nAmount = AmountFromValue(params[2]);
if (params.size() > 3)
// unused parameter, used to be nMinDepth, keep type-checking it though
(void)params[3].get_int();
string strComment;
if (params.size() > 4)
strComment = params[4].get_str();
CWalletDB walletdb(pwalletMain->strWalletFile);
if (!walletdb.TxnBegin())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
int64 nNow = GetAdjustedTime();
// Debit
CAccountingEntry debit;
debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
debit.strAccount = strFrom;
debit.nCreditDebit = -nAmount;
debit.nTime = nNow;
debit.strOtherAccount = strTo;
debit.strComment = strComment;
walletdb.WriteAccountingEntry(debit);
// Credit
CAccountingEntry credit;
credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
credit.strAccount = strTo;
credit.nCreditDebit = nAmount;
credit.nTime = nNow;
credit.strOtherAccount = strFrom;
credit.strComment = strComment;
walletdb.WriteAccountingEntry(credit);
if (!walletdb.TxnCommit())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
return true;
}
Value sendfrom(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 6)
throw runtime_error(
"sendfrom <fromaccount> <toasiacoinaddress> <amount> [minconf=1] [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.00000001"
+ HelpRequiringPassphrase());
string strAccount = AccountFromValue(params[0]);
CBitcoinAddress address(params[1].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Asiacoin address");
int64 nAmount = AmountFromValue(params[2]);
int nMinDepth = 1;
if (params.size() > 3)
nMinDepth = params[3].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
wtx.mapValue["comment"] = params[4].get_str();
if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())
wtx.mapValue["to"] = params[5].get_str();
EnsureWalletIsUnlocked();
// Check funds
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
if (nAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
if (strError != "")
throw JSONRPCError(RPC_WALLET_ERROR, strError);
return wtx.GetHash().GetHex();
}
Value sendmany(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n"
"amounts are double-precision floating point numbers"
+ HelpRequiringPassphrase());
string strAccount = AccountFromValue(params[0]);
Object sendTo = params[1].get_obj();
int nMinDepth = 1;
if (params.size() > 2)
nMinDepth = params[2].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["comment"] = params[3].get_str();
set<CBitcoinAddress> setAddress;
vector<pair<CScript, int64> > vecSend;
int64 totalAmount = 0;
BOOST_FOREACH(const Pair& s, sendTo)
{
CBitcoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Asiacoin address: ")+s.name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_);
setAddress.insert(address);
CScript scriptPubKey;
scriptPubKey.SetDestination(address.Get());
int64 nAmount = AmountFromValue(s.value_);
totalAmount += nAmount;
vecSend.push_back(make_pair(scriptPubKey, nAmount));
}
EnsureWalletIsUnlocked();
// Check funds
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
if (totalAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
CReserveKey keyChange(pwalletMain);
int64 nFeeRequired = 0;
string strFailReason;
bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, strFailReason);
if (!fCreated)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason);
if (!pwalletMain->CommitTransaction(wtx, keyChange))
throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed");
return wtx.GetHash().GetHex();
}
//
// Used by addmultisigaddress / createmultisig:
//
static CScript _createmultisig(const Array& params)
{
int nRequired = params[0].get_int();
const Array& keys = params[1].get_array();
// Gather public keys
if (nRequired < 1)
throw runtime_error("a multisignature address must require at least one key to redeem");
if ((int)keys.size() < nRequired)
throw runtime_error(
strprintf("not enough keys supplied "
"(got %"PRIszu" keys, but need at least %d to redeem)", keys.size(), nRequired));
std::vector<CPubKey> pubkeys;
pubkeys.resize(keys.size());
for (unsigned int i = 0; i < keys.size(); i++)
{
const std::string& ks = keys[i].get_str();
// Case 1: Asiacoin address and we have full public key:
CBitcoinAddress address(ks);
if (pwalletMain && address.IsValid())
{
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw runtime_error(
strprintf("%s does not refer to a key",ks.c_str()));
CPubKey vchPubKey;
if (!pwalletMain->GetPubKey(keyID, vchPubKey))
throw runtime_error(
strprintf("no full public key for address %s",ks.c_str()));
if (!vchPubKey.IsFullyValid())
throw runtime_error(" Invalid public key: "+ks);
pubkeys[i] = vchPubKey;
}
// Case 2: hex public key
else if (IsHex(ks))
{
CPubKey vchPubKey(ParseHex(ks));
if (!vchPubKey.IsFullyValid())
throw runtime_error(" Invalid public key: "+ks);
pubkeys[i] = vchPubKey;
}
else
{
throw runtime_error(" Invalid public key: "+ks);
}
}
CScript result;
result.SetMultisig(nRequired, pubkeys);
return result;
}
Value addmultisigaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
{
string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n"
"Add a nrequired-to-sign multisignature address to the wallet\"\n"
"each key is a Asiacoin address or hex-encoded public key\n"
"If [account] is specified, assign address to [account].";
throw runtime_error(msg);
}
string strAccount;
if (params.size() > 2)
strAccount = AccountFromValue(params[2]);
// Construct using pay-to-script-hash:
CScript inner = _createmultisig(params);
CScriptID innerID = inner.GetID();
pwalletMain->AddCScript(inner);
pwalletMain->SetAddressBookName(innerID, strAccount);
return CBitcoinAddress(innerID).ToString();
}
Value createmultisig(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 2)
{
string msg = "createmultisig <nrequired> <'[\"key\",\"key\"]'>\n"
"Creates a multi-signature address and returns a json object\n"
"with keys:\n"
"address : asiacoin address\n"
"redeemScript : hex-encoded redemption script";
throw runtime_error(msg);
}
// Construct using pay-to-script-hash:
CScript inner = _createmultisig(params);
CScriptID innerID = inner.GetID();
CBitcoinAddress address(innerID);
Object result;
result.push_back(Pair("address", address.ToString()));
result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end())));
return result;
}
struct tallyitem
{
int64 nAmount;
int nConf;
vector<uint256> txids;
tallyitem()
{
nAmount = 0;
nConf = std::numeric_limits<int>::max();
}
};
Value ListReceived(const Array& params, bool fByAccounts)
{
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
// Whether to include empty accounts
bool fIncludeEmpty = false;
if (params.size() > 1)
fIncludeEmpty = params[1].get_bool();
// Tally
map<CBitcoinAddress, tallyitem> mapTally;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !wtx.IsFinal())
continue;
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < nMinDepth)
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address) || !IsMine(*pwalletMain, address))
continue;
tallyitem& item = mapTally[address];
item.nAmount += txout.nValue;
item.nConf = min(item.nConf, nDepth);
item.txids.push_back(wtx.GetHash());
}
}
// Reply
Array ret;
map<string, tallyitem> mapAccountTally;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strAccount = item.second;
map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address);
if (it == mapTally.end() && !fIncludeEmpty)
continue;
int64 nAmount = 0;
int nConf = std::numeric_limits<int>::max();
if (it != mapTally.end())
{
nAmount = (*it).second.nAmount;
nConf = (*it).second.nConf;
}
if (fByAccounts)
{
tallyitem& item = mapAccountTally[strAccount];
item.nAmount += nAmount;
item.nConf = min(item.nConf, nConf);
}
else
{
Object obj;
obj.push_back(Pair("address", address.ToString()));
obj.push_back(Pair("account", strAccount));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
Array transactions;
if (it != mapTally.end())
{
BOOST_FOREACH(const uint256& item, (*it).second.txids)
{
transactions.push_back(item.GetHex());
}
}
obj.push_back(Pair("txids", transactions));
ret.push_back(obj);
}
}
if (fByAccounts)
{
for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
{
int64 nAmount = (*it).second.nAmount;
int nConf = (*it).second.nConf;
Object obj;
obj.push_back(Pair("account", (*it).first));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
ret.push_back(obj);
}
}
return ret;
}
Value listreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listreceivedbyaddress [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include addresses that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"address\" : receiving address\n"
" \"account\" : the account of the receiving address\n"
" \"amount\" : total amount received by the address\n"
" \"confirmations\" : number of confirmations of the most recent transaction included\n"
" \"txids\" : list of transactions with outputs to the address\n");
return ListReceived(params, false);
}
Value listreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listreceivedbyaccount [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include accounts that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"account\" : the account of the receiving addresses\n"
" \"amount\" : total amount received by addresses with this account\n"
" \"confirmations\" : number of confirmations of the most recent transaction included");
return ListReceived(params, true);
}
static void MaybePushAddress(Object & entry, const CTxDestination &dest)
{
CBitcoinAddress addr;
if (addr.Set(dest))
entry.push_back(Pair("address", addr.ToString()));
}
void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret)
{
int64 nFee;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount);
bool fAllAccounts = (strAccount == string("*"));
// Sent
if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent)
{
Object entry;
entry.push_back(Pair("account", strSentAccount));
MaybePushAddress(entry, s.first);
entry.push_back(Pair("category", "send"));
entry.push_back(Pair("amount", ValueFromAmount(-s.second)));
entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
// Received
if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived)
{
string account;
if (pwalletMain->mapAddressBook.count(r.first))
account = pwalletMain->mapAddressBook[r.first];
if (fAllAccounts || (account == strAccount))
{
Object entry;
entry.push_back(Pair("account", account));
MaybePushAddress(entry, r.first);
if (wtx.IsCoinBase())
{
if (wtx.GetDepthInMainChain() < 1)
entry.push_back(Pair("category", "orphan"));
else if (wtx.GetBlocksToMaturity() > 0)
entry.push_back(Pair("category", "immature"));
else
entry.push_back(Pair("category", "generate"));
}
else
{
entry.push_back(Pair("category", "receive"));
}
entry.push_back(Pair("amount", ValueFromAmount(r.second)));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
}
}
void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret)
{
bool fAllAccounts = (strAccount == string("*"));
if (fAllAccounts || acentry.strAccount == strAccount)
{
Object entry;
entry.push_back(Pair("account", acentry.strAccount));
entry.push_back(Pair("category", "move"));
entry.push_back(Pair("time", (boost::int64_t)acentry.nTime));
entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
entry.push_back(Pair("comment", acentry.strComment));
ret.push_back(entry);
}
}
Value listtransactions(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listtransactions [account] [count=10] [from=0]\n"
"Returns up to [count] most recent transactions skipping the first [from] transactions for account [account].");
string strAccount = "*";
if (params.size() > 0)
strAccount = params[0].get_str();
int nCount = 10;
if (params.size() > 1)
nCount = params[1].get_int();
int nFrom = 0;
if (params.size() > 2)
nFrom = params[2].get_int();
if (nCount < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
if (nFrom < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from");
Array ret;
std::list<CAccountingEntry> acentries;
CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, strAccount);
// iterate backwards until we have nCount items to return:
for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
if (pwtx != 0)
ListTransactions(*pwtx, strAccount, 0, true, ret);
CAccountingEntry *const pacentry = (*it).second.second;
if (pacentry != 0)
AcentryToJSON(*pacentry, strAccount, ret);
if ((int)ret.size() >= (nCount+nFrom)) break;
}
// ret is newest to oldest
if (nFrom > (int)ret.size())
nFrom = ret.size();
if ((nFrom + nCount) > (int)ret.size())
nCount = ret.size() - nFrom;
Array::iterator first = ret.begin();
std::advance(first, nFrom);
Array::iterator last = ret.begin();
std::advance(last, nFrom+nCount);
if (last != ret.end()) ret.erase(last, ret.end());
if (first != ret.begin()) ret.erase(ret.begin(), first);
std::reverse(ret.begin(), ret.end()); // Return oldest to newest
return ret;
}
Value listaccounts(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"listaccounts [minconf=1]\n"
"Returns Object that has account names as keys, account balances as values.");
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
map<string, int64> mapAccountBalances;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& entry, pwalletMain->mapAddressBook) {
if (IsMine(*pwalletMain, entry.first)) // This address belongs to me
mapAccountBalances[entry.second] = 0;
}
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
int64 nFee;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount);
mapAccountBalances[strSentAccount] -= nFee;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent)
mapAccountBalances[strSentAccount] -= s.second;
if (wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived)
if (pwalletMain->mapAddressBook.count(r.first))
mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second;
else
mapAccountBalances[""] += r.second;
}
}
list<CAccountingEntry> acentries;
CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries);
BOOST_FOREACH(const CAccountingEntry& entry, acentries)
mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
Object ret;
BOOST_FOREACH(const PAIRTYPE(string, int64)& accountBalance, mapAccountBalances) {
ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
}
return ret;
}
Value listsinceblock(const Array& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listsinceblock [blockhash] [target-confirmations]\n"
"Get all transactions in blocks since block [blockhash], or all transactions if omitted");
CBlockIndex *pindex = NULL;
int target_confirms = 1;
if (params.size() > 0)
{
uint256 blockId = 0;
blockId.SetHex(params[0].get_str());
pindex = CBlockLocator(blockId).GetBlockIndex();
}
if (params.size() > 1)
{
target_confirms = params[1].get_int();
if (target_confirms < 1)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
}
int depth = pindex ? (1 + nBestHeight - pindex->nHeight) : -1;
Array transactions;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++)
{
CWalletTx tx = (*it).second;
if (depth == -1 || tx.GetDepthInMainChain() < depth)
ListTransactions(tx, "*", 0, true, transactions);
}
uint256 lastblock;
if (target_confirms == 1)
{
lastblock = hashBestChain;
}
else
{
int target_height = pindexBest->nHeight + 1 - target_confirms;
CBlockIndex *block;
for (block = pindexBest;
block && block->nHeight > target_height;
block = block->pprev) { }
lastblock = block ? block->GetBlockHash() : 0;
}
Object ret;
ret.push_back(Pair("transactions", transactions));
ret.push_back(Pair("lastblock", lastblock.GetHex()));
return ret;
}
Value gettransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"gettransaction <txid>\n"
"Get detailed information about in-wallet transaction <txid>");
uint256 hash;
hash.SetHex(params[0].get_str());
Object entry;
if (!pwalletMain->mapWallet.count(hash))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id");
const CWalletTx& wtx = pwalletMain->mapWallet[hash];
int64 nCredit = wtx.GetCredit();
int64 nDebit = wtx.GetDebit();
int64 nNet = nCredit - nDebit;
int64 nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0);
entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
if (wtx.IsFromMe())
entry.push_back(Pair("fee", ValueFromAmount(nFee)));
WalletTxToJSON(wtx, entry);
Array details;
ListTransactions(wtx, "*", 0, false, details);
entry.push_back(Pair("details", details));
return entry;
}
Value backupwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"backupwallet <destination>\n"
"Safely copies wallet.dat to destination, which can be a directory or a path with filename.");
string strDest = params[0].get_str();
if (!BackupWallet(*pwalletMain, strDest))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!");
return Value::null;
}
Value keypoolrefill(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"keypoolrefill\n"
"Fills the keypool."
+ HelpRequiringPassphrase());
EnsureWalletIsUnlocked();
pwalletMain->TopUpKeyPool();
if (pwalletMain->GetKeyPoolSize() < GetArg("-keypool", 100))
throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool.");
return Value::null;
}
void ThreadTopUpKeyPool(void* parg)
{
// Make this thread recognisable as the key-topping-up thread
RenameThread("bitcoin-key-top");
pwalletMain->TopUpKeyPool();
}
void ThreadCleanWalletPassphrase(void* parg)
{
// Make this thread recognisable as the wallet relocking thread
RenameThread("bitcoin-lock-wa");
int64 nMyWakeTime = GetTimeMillis() + *((int64*)parg) * 1000;
ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime);
if (nWalletUnlockTime == 0)
{
nWalletUnlockTime = nMyWakeTime;
do
{
if (nWalletUnlockTime==0)
break;
int64 nToSleep = nWalletUnlockTime - GetTimeMillis();
if (nToSleep <= 0)
break;
LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime);
MilliSleep(nToSleep);
ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime);
} while(1);
if (nWalletUnlockTime)
{
nWalletUnlockTime = 0;
pwalletMain->Lock();
}
}
else
{
if (nWalletUnlockTime < nMyWakeTime)
nWalletUnlockTime = nMyWakeTime;
}
LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime);
delete (int64*)parg;
}
Value walletpassphrase(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw runtime_error(
"walletpassphrase <passphrase> <timeout>\n"
"Stores the wallet decryption key in memory for <timeout> seconds.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called.");
if (!pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already unlocked.");
// Note that the walletpassphrase is stored in params[0] which is not mlock()ed
SecureString strWalletPass;
strWalletPass.reserve(100);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() > 0)
{
if (!pwalletMain->Unlock(strWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
}
else
throw runtime_error(
"walletpassphrase <passphrase> <timeout>\n"
"Stores the wallet decryption key in memory for <timeout> seconds.");
NewThread(ThreadTopUpKeyPool, NULL);
int64* pnSleepTime = new int64(params[1].get_int64());
NewThread(ThreadCleanWalletPassphrase, pnSleepTime);
return Value::null;
}
Value walletpassphrasechange(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");
// TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strOldWalletPass;
strOldWalletPass.reserve(100);
strOldWalletPass = params[0].get_str().c_str();
SecureString strNewWalletPass;
strNewWalletPass.reserve(100);
strNewWalletPass = params[1].get_str().c_str();
if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1)
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
return Value::null;
}
Value walletlock(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0))
throw runtime_error(
"walletlock\n"
"Removes the wallet encryption key from memory, locking the wallet.\n"
"After calling this method, you will need to call walletpassphrase again\n"
"before being able to call any methods which require the wallet to be unlocked.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called.");
{
LOCK(cs_nWalletUnlockTime);
pwalletMain->Lock();
nWalletUnlockTime = 0;
}
return Value::null;
}
Value encryptwallet(const Array& params, bool fHelp)
{
if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1))
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (fHelp)
return true;
if (pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called.");
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strWalletPass;
strWalletPass.reserve(100);
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() < 1)
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (!pwalletMain->EncryptWallet(strWalletPass))
throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet.");
// BDB seems to have a bad habit of writing old data into
// slack space in .dat files; that is bad if the old data is
// unencrypted private keys. So:
StartShutdown();
return "wallet encrypted; Asiacoin server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup.";
}
class DescribeAddressVisitor : public boost::static_visitor<Object>
{
public:
Object operator()(const CNoDestination &dest) const { return Object(); }
Object operator()(const CKeyID &keyID) const {
Object obj;
CPubKey vchPubKey;
pwalletMain->GetPubKey(keyID, vchPubKey);
obj.push_back(Pair("isscript", false));
obj.push_back(Pair("pubkey", HexStr(vchPubKey)));
obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
return obj;
}
Object operator()(const CScriptID &scriptID) const {
Object obj;
obj.push_back(Pair("isscript", true));
CScript subscript;
pwalletMain->GetCScript(scriptID, subscript);
std::vector<CTxDestination> addresses;
txnouttype whichType;
int nRequired;
ExtractDestinations(subscript, whichType, addresses, nRequired);
obj.push_back(Pair("script", GetTxnOutputType(whichType)));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
obj.push_back(Pair("addresses", a));
if (whichType == TX_MULTISIG)
obj.push_back(Pair("sigsrequired", nRequired));
return obj;
}
};
Value validateaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"validateaddress <asiacoinaddress>\n"
"Return information about <asiacoinaddress>.");
CBitcoinAddress address(params[0].get_str());
bool isValid = address.IsValid();
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
bool fMine = pwalletMain ? IsMine(*pwalletMain, dest) : false;
ret.push_back(Pair("ismine", fMine));
if (fMine) {
Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain && pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest]));
}
return ret;
}
Value lockunspent(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"lockunspent unlock? [array-of-Objects]\n"
"Updates list of temporarily unspendable outputs.");
if (params.size() == 1)
RPCTypeCheck(params, list_of(bool_type));
else
RPCTypeCheck(params, list_of(bool_type)(array_type));
bool fUnlock = params[0].get_bool();
if (params.size() == 1) {
if (fUnlock)
pwalletMain->UnlockAllCoins();
return true;
}
Array outputs = params[1].get_array();
BOOST_FOREACH(Value& output, outputs)
{
if (output.type() != obj_type)
throw JSONRPCError(-8, "Invalid parameter, expected object");
const Object& o = output.get_obj();
RPCTypeCheck(o, map_list_of("txid", str_type)("vout", int_type));
string txid = find_value(o, "txid").get_str();
if (!IsHex(txid))
throw JSONRPCError(-8, "Invalid parameter, expected hex txid");
int nOutput = find_value(o, "vout").get_int();
if (nOutput < 0)
throw JSONRPCError(-8, "Invalid parameter, vout must be positive");
COutPoint outpt(uint256(txid), nOutput);
if (fUnlock)
pwalletMain->UnlockCoin(outpt);
else
pwalletMain->LockCoin(outpt);
}
return true;
}
Value listlockunspent(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"listlockunspent\n"
"Returns list of temporarily unspendable outputs.");
vector<COutPoint> vOutpts;
pwalletMain->ListLockedCoins(vOutpts);
Array ret;
BOOST_FOREACH(COutPoint &outpt, vOutpts) {
Object o;
o.push_back(Pair("txid", outpt.hash.GetHex()));
o.push_back(Pair("vout", (int)outpt.n));
ret.push_back(o);
}
return ret;
}
| [
"india2010"
] | india2010 |
1072bb3ef4842f08cf9b50b596a3440e0a63dcf8 | 0e8d87ea03823b0eda67cb442b5fd6a97edf8957 | /implementation/mcts_node.h | 7c2b4bceb4bd31df7473bc2c89b2b0ee27fa3000 | [] | no_license | senu/MiMHex | 2cf8266d6f4545ae0520608db370a3856743ccd4 | 98f701c9857ba42eeb197540eb1c92a8fec85e3e | refs/heads/master | 2020-01-23T21:13:35.009297 | 2010-01-09T13:48:36 | 2010-01-09T13:48:36 | 465,238 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,509 | h | #ifndef MCTS_NODE_H_
#define MCTS_NODE_H_
#include "board.h"
#include "auto_pointer.h"
#include "params.h"
namespace Hex {
class Statistics {
public:
Statistics(uint start_won, uint start_played)
: won(start_won), played(start_played) { }
public:
uint won;
uint played;
};
class MCTSNode {
public:
MCTSNode() : uct_stats(Params::initialization, 2 * Params::initialization),
rave_stats(Params::initialization, 2 * Params::initialization),
loc(0), valid_ucb(false), valid_rave(false) { }
MCTSNode(Location location) : uct_stats(Params::initialization, 2 * Params::initialization),
rave_stats(Params::initialization, 2 * Params::initialization), loc(location),
valid_ucb(false), valid_rave(false) { }
MCTSNode* FindBestChild(uint children_number);
MCTSNode* FindChildToSelect(uint children_number);
float GetUCB();
float GetRAVE();
float GetMu();
float GetRAVEMu();
float GetUCBWeight();
float Eval();
void Expand(Board& board);
void RecursivePrint(std::ostream& stream, uint max_children,
uint current_level, uint children_count, Player player);
void SetInvalidUCB() { valid_ucb = false; }
void SetInvalidRAVE() { valid_rave = false; }
void ComputeUCBStats();
friend class MCTSTree;
public:
Statistics uct_stats;
Statistics rave_stats;
private:
Location loc;
AutoTable<MCTSNode> children;
AutoTable<MCTSNode*> pos_to_children_mapping;
float ucb;
float ucb_weight;
bool valid_ucb;
float rave;
bool valid_rave;
};
} // namespace Hex
#endif /* MCTS_NODE_H_ */
| [
"lukasz.lew@gmail.com"
] | lukasz.lew@gmail.com |
efe0187fd18c1222d9425839e70d9bdb937d578f | ee20d5f0983ce8bc7466090b135519d1114ede9d | /Upsolving/URI/2061.cpp | 5881b49af65a7b2791ecdda980aa06938c40c78a | [] | no_license | rodrigoAMF/competitive-programming | a12038dd17144044365c1126fa17f968186479d4 | 06b38197a042bfbd27b20f707493e0a19fda7234 | refs/heads/master | 2020-03-31T18:28:11.301068 | 2019-08-02T21:35:53 | 2019-08-02T21:35:53 | 152,459,900 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 587 | cpp | #include <bits/stdc++.h>
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
#define INF 0x3F3F3F3F
#define LINF 0x3F3F3F3F3F3F3F3FLL
#define DINF (double)1e+30
#define EPS (double)1e-9
#define RAD(x) (double)(x*PI)/180.0
#define PCT(x,y) (double)x*100.0/y
#define forn(i, n) for ( int i = 0; i < (n); ++i )
#define forxn(i, x, n) for ( int i = (x); i < (n); ++i )
using namespace std;
int main(){
int a, n;
string aux;
cin >> a >> n;
forn(i, n){
cin >> aux;
if(aux == "fechou"){
a++;
}else{
a--;
}
}
cout << a << endl;
return 0;
} | [
"rodrigoamf@outlook.com"
] | rodrigoamf@outlook.com |
932c2c94ba17b4884f1df699f250c7ec378094d5 | 948f4e13af6b3014582909cc6d762606f2a43365 | /testcases/juliet_test_suite/testcases/CWE319_Cleartext_Tx_Sensitive_Info/CWE319_Cleartext_Tx_Sensitive_Info__w32_char_listen_socket_84_bad.cpp | 3497f9b4604e8cf953e73d667c06d777914ecb62 | [] | no_license | junxzm1990/ASAN-- | 0056a341b8537142e10373c8417f27d7825ad89b | ca96e46422407a55bed4aa551a6ad28ec1eeef4e | refs/heads/master | 2022-08-02T15:38:56.286555 | 2022-06-16T22:19:54 | 2022-06-16T22:19:54 | 408,238,453 | 74 | 13 | null | 2022-06-16T22:19:55 | 2021-09-19T21:14:59 | null | UTF-8 | C++ | false | false | 4,926 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE319_Cleartext_Tx_Sensitive_Info__w32_char_listen_socket_84_bad.cpp
Label Definition File: CWE319_Cleartext_Tx_Sensitive_Info__w32.label.xml
Template File: sources-sinks-84_bad.tmpl.cpp
*/
/*
* @description
* CWE: 319 Cleartext Transmission of Sensitive Information
* BadSource: listen_socket Read the password using a listen socket (server side)
* GoodSource: Use a hardcoded password (one that was not sent over the network)
* Sinks:
* GoodSink: Decrypt the password before using it in an authentication API call to show that it was transferred as ciphertext
* BadSink : Use the password directly from the source in an authentication API call to show that it was transferred as plaintext
* Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use
*
* */
#ifndef OMITBAD
#include "std_testcase.h"
#include "CWE319_Cleartext_Tx_Sensitive_Info__w32_char_listen_socket_84.h"
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define TCP_PORT 27015
#define LISTEN_BACKLOG 5
#pragma comment(lib, "advapi32.lib")
#define HASH_INPUT "ABCDEFG123456" /* INCIDENTAL: Hardcoded crypto */
namespace CWE319_Cleartext_Tx_Sensitive_Info__w32_char_listen_socket_84
{
CWE319_Cleartext_Tx_Sensitive_Info__w32_char_listen_socket_84_bad::CWE319_Cleartext_Tx_Sensitive_Info__w32_char_listen_socket_84_bad(char * passwordCopy)
{
password = passwordCopy;
{
WSADATA wsaData;
int wsaDataInit = 0;
int recvResult;
struct sockaddr_in service;
char *replace;
SOCKET listenSocket = INVALID_SOCKET;
SOCKET acceptSocket = INVALID_SOCKET;
size_t passwordLen = strlen(password);
do
{
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listenSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = INADDR_ANY;
service.sin_port = htons(TCP_PORT);
if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR)
{
break;
}
acceptSocket = accept(listenSocket, NULL, NULL);
if (acceptSocket == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed */
/* POTENTIAL FLAW: Reading sensitive data from the network */
recvResult = recv(acceptSocket, (char*)(password + passwordLen), (100 - passwordLen - 1) * sizeof(char), 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* Append null terminator */
password[passwordLen + recvResult / sizeof(char)] = '\0';
/* Eliminate CRLF */
replace = strchr(password, '\r');
if (replace)
{
*replace = '\0';
}
replace = strchr(password, '\n');
if (replace)
{
*replace = '\0';
}
}
while (0);
if (listenSocket != INVALID_SOCKET)
{
closesocket(listenSocket);
}
if (acceptSocket != INVALID_SOCKET)
{
closesocket(acceptSocket);
}
if (wsaDataInit)
{
WSACleanup();
}
}
}
CWE319_Cleartext_Tx_Sensitive_Info__w32_char_listen_socket_84_bad::~CWE319_Cleartext_Tx_Sensitive_Info__w32_char_listen_socket_84_bad()
{
{
HANDLE pHandle;
char * username = "User";
char * domain = "Domain";
/* Use the password in LogonUser() to establish that it is "sensitive" */
/* POTENTIAL FLAW: Using sensitive information that was possibly sent in plaintext over the network */
if (LogonUserA(
username,
domain,
password,
LOGON32_LOGON_NETWORK,
LOGON32_PROVIDER_DEFAULT,
&pHandle) != 0)
{
printLine("User logged in successfully.");
CloseHandle(pHandle);
}
else
{
printLine("Unable to login.");
}
}
}
}
#endif /* OMITBAD */
| [
"yzhang0701@gmail.com"
] | yzhang0701@gmail.com |
caec9be7217cdb5d1a987eff5ca5fb4ce9c7e9ae | 186538b6a72c7db4260bee0cf2f4044ae8883472 | /src/cliente/editor/mapa_editor.h | b46b924fe3ab81761d3f1c92d781067baccda75a | [] | no_license | santiagomariani/Portal2DGame | fe160ae85f936044259f52e103b6de866e915018 | 9240ccfab551a07796c076b69f14b8e393cf8e0d | refs/heads/master | 2022-01-28T17:48:26.188150 | 2019-06-25T18:28:36 | 2019-06-25T18:28:36 | 184,281,551 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,127 | h | #ifndef MAPA_EDITOR_H
#define MAPA_EDITOR_H
#include <map>
#include <SDL2/SDL.h>
#include <vector>
#include "imagen.h"
#include "pieza.h"
#include "cursor.h"
#include <string>
// Representa un mapa del juego
class MapaEditor{
SDL_Rect camara;
std::map<int, std::map<int, Pieza>> mapa;
std::map<int, int> conexiones;
int celda;
bool estado_logico;
Cursor& cursor;
int convertirPosicion(int a);
public:
MapaEditor(int ancho_cam, int alto_cam, int celda, Cursor& cursor);
// Agrega una pieza en la posicion (x, y)
void agregar(int x, int y, Pieza pieza);
// Quita la pieza que hay en la posicion (x, y)
void quitar(int x, int y);
// Muestra las piezas que contiene
void render();
// Permite moverse por el mapa con las flechitas y entrar
// en modo logico con la "l"
void recibirEvento(SDL_KeyboardEvent& evento);
// Actualiza el cursor con los datos de la pieza clickeada
void recibirEvento(SDL_MouseButtonEvent& evento);
// Se guarda en un archivo yaml con el nombre recibido
std::string guardar();
// Conecta dos piezas solo si son parte de la logica
void conectar();
};
#endif //MAPA_EDITOR | [
"seba21log@gmail.com"
] | seba21log@gmail.com |
31a001a36357d63ba71a15c42419625a52d0d9bb | fb8da7ada05298248c62eb5d8dbd23a6ae2e7b49 | /src/silverbullet/dataio/volumeio/FileBasedVolume.cpp | 4446180622f4548ffcfbe3f8e6fcb88bd0dcb301 | [] | no_license | HPC-Group/Trinity | f86c09c4ac4a774c3bc26a261c23816a9c21f8bb | 483f21a2778a480719a61a4a2448d8fd5d21a301 | refs/heads/master | 2021-05-01T02:58:55.607398 | 2016-09-27T15:50:19 | 2016-09-27T15:50:19 | 68,828,512 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,816 | cpp | #include "silverbullet/dataio/volumeio/FileBasedVolume.h"
#include <sstream>
namespace DataIO {
namespace VolumeIO {
FileBasedVolume::FileBasedVolume(const std::string& filename) :
Volume(),
m_filename(filename)
{
}
FileBasedVolume::FileBasedVolume(const std::string& filename,
VolumeMetadataPtr metadata) :
Volume(metadata),
m_filename(filename)
{
}
const std::string FileBasedVolume::toString() const {
std::stringstream result;
result << m_filename << ", " << Volume::toString();
return result.str();
}
}
}
/*
The MIT License
Copyright (c) 2014 HPC Group, Univeristy Duisburg-Essen
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
| [
"andrey.krekhov@uni-due.de"
] | andrey.krekhov@uni-due.de |
db1fd6561c2601e3500f0399e760b008a12bace4 | f1413abb8aeba69c40893e20fd06dc7de6a54d64 | /game/observable.h | f4f11c35e74f0498fc2130f43d969fb26260a205 | [] | no_license | datalurkur/Bushido-Mongers | 5ae91e1e738a8dd501f50ff6af96e9ecd5482877 | e3cad44fc8e019373c73f8bb77a0a9d58ce83915 | refs/heads/master | 2016-09-09T22:51:05.839055 | 2014-12-19T00:27:46 | 2014-12-19T00:27:46 | 6,514,450 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 380 | h | #ifndef OBSERVABLE_H
#define OBSERVABLE_H
#include "util/timestamp.h"
class Observable {
public:
Observable();
time_t lastChanged() const;
void setLastChanged(time_t changed);
// An attachment point for subclasses to define custom behavior when they're observed
virtual void onChanged();
protected:
void markChanged();
private:
time_t _lastChanged;
};
#endif
| [
"datalurkur@gmail.com"
] | datalurkur@gmail.com |
0da3292f9667864f216ce3aebd0604f7a6aa99d1 | b10767339e7ac7798e67df24bcc3330d9bbf9a90 | /Braille.ino | 8fb575e6596a98c267cce26343abc6b2d3e9e38d | [] | no_license | marloudeguzman/Arduino-Braille-Translator | 58aba195924605ad8b3049ee7782d564391b60f0 | de2920b4806041c732d783d5d34f7423f2865afa | refs/heads/master | 2021-06-11T19:39:12.105378 | 2017-01-15T04:00:19 | 2017-01-15T04:00:19 | 78,993,526 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 15,568 | ino | #define PIN_SCE 7
#define PIN_RESET 6
#define PIN_DC 5
#define PIN_SDIN 11
#define PIN_SCLK 13
#define PIN_LED 9
#define LCD_C LOW
#define LCD_D HIGH
#define LCD_X 84
#define LCD_Y 48
const int topright = 8; // top right pushbutton pin
const int topleft = 4; // top leftpushbutton pin
const int midright = 3; // mid right pushbutton pin
const int midleft = 2; // mid left pushbutton pin
const int botright = 1; // bottom right pushbutton pin
const int botleft = 0; // bottom left pushbutton pin
const int reset = 10; // reset pushbutton pin
const int translate = 12; // translate pushbutton pin
const int trLED = A0; // top right LED pin
const int tlLED = A1; // top left LED pin
const int mrLED = A2; // mid right LED pin
const int mlLED = A3; // mid left LED pin
const int brLED = A4; // bottom right LED pin
const int blLED = A5; // bottom left LED pin
static const byte ASCII[][5] =
{
{0x00, 0x00, 0x00, 0x00, 0x00} // 20
, {0x00, 0x00, 0x5f, 0x00, 0x00} // 21 !
, {0x00, 0x07, 0x00, 0x07, 0x00} // 22 "
, {0x14, 0x7f, 0x14, 0x7f, 0x14} // 23 #
, {0x24, 0x2a, 0x7f, 0x2a, 0x12} // 24 $
, {0x23, 0x13, 0x08, 0x64, 0x62} // 25 %
, {0x36, 0x49, 0x55, 0x22, 0x50} // 26 &
, {0x00, 0x05, 0x03, 0x00, 0x00} // 27 '
, {0x00, 0x1c, 0x22, 0x41, 0x00} // 28 (
, {0x00, 0x41, 0x22, 0x1c, 0x00} // 29 )
, {0x14, 0x08, 0x3e, 0x08, 0x14} // 2a *
, {0x08, 0x08, 0x3e, 0x08, 0x08} // 2b +
, {0x00, 0x50, 0x30, 0x00, 0x00} // 2c ,
, {0x08, 0x08, 0x08, 0x08, 0x08} // 2d -
, {0x00, 0x60, 0x60, 0x00, 0x00} // 2e .
, {0x20, 0x10, 0x08, 0x04, 0x02} // 2f /
, {0x3e, 0x51, 0x49, 0x45, 0x3e} // 30 0
, {0x00, 0x42, 0x7f, 0x40, 0x00} // 31 1
, {0x42, 0x61, 0x51, 0x49, 0x46} // 32 2
, {0x21, 0x41, 0x45, 0x4b, 0x31} // 33 3
, {0x18, 0x14, 0x12, 0x7f, 0x10} // 34 4
, {0x27, 0x45, 0x45, 0x45, 0x39} // 35 5
, {0x3c, 0x4a, 0x49, 0x49, 0x30} // 36 6
, {0x01, 0x71, 0x09, 0x05, 0x03} // 37 7
, {0x36, 0x49, 0x49, 0x49, 0x36} // 38 8
, {0x06, 0x49, 0x49, 0x29, 0x1e} // 39 9
, {0x00, 0x36, 0x36, 0x00, 0x00} // 3a :
, {0x00, 0x56, 0x36, 0x00, 0x00} // 3b ;
, {0x08, 0x14, 0x22, 0x41, 0x00} // 3c <
, {0x14, 0x14, 0x14, 0x14, 0x14} // 3d =
, {0x00, 0x41, 0x22, 0x14, 0x08} // 3e >
, {0x02, 0x01, 0x51, 0x09, 0x06} // 3f ?
, {0x32, 0x49, 0x79, 0x41, 0x3e} // 40 @
, {0x7e, 0x11, 0x11, 0x11, 0x7e} // 41 A
, {0x7f, 0x49, 0x49, 0x49, 0x36} // 42 B
, {0x3e, 0x41, 0x41, 0x41, 0x22} // 43 C
, {0x7f, 0x41, 0x41, 0x22, 0x1c} // 44 D
, {0x7f, 0x49, 0x49, 0x49, 0x41} // 45 E
, {0x7f, 0x09, 0x09, 0x09, 0x01} // 46 F
, {0x3e, 0x41, 0x49, 0x49, 0x7a} // 47 G
, {0x7f, 0x08, 0x08, 0x08, 0x7f} // 48 H
, {0x00, 0x41, 0x7f, 0x41, 0x00} // 49 I
, {0x20, 0x40, 0x41, 0x3f, 0x01} // 4a J
, {0x7f, 0x08, 0x14, 0x22, 0x41} // 4b K
, {0x7f, 0x40, 0x40, 0x40, 0x40} // 4c L
, {0x7f, 0x02, 0x0c, 0x02, 0x7f} // 4d M
, {0x7f, 0x04, 0x08, 0x10, 0x7f} // 4e N
, {0x3e, 0x41, 0x41, 0x41, 0x3e} // 4f O
, {0x7f, 0x09, 0x09, 0x09, 0x06} // 50 P
, {0x3e, 0x41, 0x51, 0x21, 0x5e} // 51 Q
, {0x7f, 0x09, 0x19, 0x29, 0x46} // 52 R
, {0x46, 0x49, 0x49, 0x49, 0x31} // 53 S
, {0x01, 0x01, 0x7f, 0x01, 0x01} // 54 T
, {0x3f, 0x40, 0x40, 0x40, 0x3f} // 55 U
, {0x1f, 0x20, 0x40, 0x20, 0x1f} // 56 V
, {0x3f, 0x40, 0x38, 0x40, 0x3f} // 57 W
, {0x63, 0x14, 0x08, 0x14, 0x63} // 58 X
, {0x07, 0x08, 0x70, 0x08, 0x07} // 59 Y
, {0x61, 0x51, 0x49, 0x45, 0x43} // 5a Z
, {0x00, 0x7f, 0x41, 0x41, 0x00} // 5b [
, {0x02, 0x04, 0x08, 0x10, 0x20} // 5c ¥
, {0x00, 0x41, 0x41, 0x7f, 0x00} // 5d ]
, {0x04, 0x02, 0x01, 0x02, 0x04} // 5e ^
, {0x40, 0x40, 0x40, 0x40, 0x40} // 5f _
, {0x00, 0x01, 0x02, 0x04, 0x00} // 60 `
, {0x20, 0x54, 0x54, 0x54, 0x78} // 61 a
, {0x7f, 0x48, 0x44, 0x44, 0x38} // 62 b
, {0x38, 0x44, 0x44, 0x44, 0x20} // 63 c
, {0x38, 0x44, 0x44, 0x48, 0x7f} // 64 d
, {0x38, 0x54, 0x54, 0x54, 0x18} // 65 e
, {0x08, 0x7e, 0x09, 0x01, 0x02} // 66 f
, {0x0c, 0x52, 0x52, 0x52, 0x3e} // 67 g
, {0x7f, 0x08, 0x04, 0x04, 0x78} // 68 h
, {0x00, 0x44, 0x7d, 0x40, 0x00} // 69 i
, {0x20, 0x40, 0x44, 0x3d, 0x00} // 6a j
, {0x7f, 0x10, 0x28, 0x44, 0x00} // 6b k
, {0x00, 0x41, 0x7f, 0x40, 0x00} // 6c l
, {0x7c, 0x04, 0x18, 0x04, 0x78} // 6d m
, {0x7c, 0x08, 0x04, 0x04, 0x78} // 6e n
, {0x38, 0x44, 0x44, 0x44, 0x38} // 6f o
, {0x7c, 0x14, 0x14, 0x14, 0x08} // 70 p
, {0x08, 0x14, 0x14, 0x18, 0x7c} // 71 q
, {0x7c, 0x08, 0x04, 0x04, 0x08} // 72 r
, {0x48, 0x54, 0x54, 0x54, 0x20} // 73 s
, {0x04, 0x3f, 0x44, 0x40, 0x20} // 74 t
, {0x3c, 0x40, 0x40, 0x20, 0x7c} // 75 u
, {0x1c, 0x20, 0x40, 0x20, 0x1c} // 76 v
, {0x3c, 0x40, 0x30, 0x40, 0x3c} // 77 w
, {0x44, 0x28, 0x10, 0x28, 0x44} // 78 x
, {0x0c, 0x50, 0x50, 0x50, 0x3c} // 79 y
, {0x44, 0x64, 0x54, 0x4c, 0x44} // 7a z
, {0x00, 0x08, 0x36, 0x41, 0x00} // 7b {
, {0x00, 0x00, 0x7f, 0x00, 0x00} // 7c |
, {0x00, 0x41, 0x36, 0x08, 0x00} // 7d }
, {0x10, 0x08, 0x08, 0x10, 0x08} // 7e ←
, {0x78, 0x46, 0x41, 0x46, 0x78} // 7f →
};
void LcdCharacter(char character)
{
LcdWrite(LCD_D, 0x00);
for (int index = 0; index < 5; index++)
{
LcdWrite(LCD_D, ASCII[character - 0x20][index]);
}
LcdWrite(LCD_D, 0x00);
}
void LcdClear(void)
{
for (int index = 0; index < LCD_X * LCD_Y / 8; index++)
{
LcdWrite(LCD_D, 0x00);
}
}
void LcdInitialise(void)
{
pinMode(PIN_SCE, OUTPUT);
pinMode(PIN_RESET, OUTPUT);
pinMode(PIN_DC, OUTPUT);
pinMode(PIN_SDIN, OUTPUT);
pinMode(PIN_SCLK, OUTPUT);
pinMode(PIN_LED, OUTPUT);
digitalWrite(PIN_RESET, LOW);
digitalWrite(PIN_RESET, HIGH);
analogWrite(PIN_LED, 255);
LcdWrite(LCD_C, 0x21 ); // LCD Extended Commands.
LcdWrite(LCD_C, 0xB1 ); // Set LCD Vop (Contrast).
LcdWrite(LCD_C, 0x04 ); // Set Temp coefficent. //0x04
LcdWrite(LCD_C, 0x14 ); // LCD bias mode 1:48. //0x13
LcdWrite(LCD_C, 0x20 ); // LCD Basic Commands
LcdWrite(LCD_C, 0x0C ); // LCD in normal mode.
}
void LcdString(char *characters)
{
while (*characters)
{
LcdCharacter(*characters++);
}
}
void LcdWrite(byte dc, byte data)
{
digitalWrite(PIN_DC, dc);
digitalWrite(PIN_SCE, LOW);
shiftOut(PIN_SDIN, PIN_SCLK, MSBFIRST, data);
digitalWrite(PIN_SCE, HIGH);
}
void resetInput(void)
{
digitalWrite(trLED, LOW); // turn the LED off
digitalWrite(tlLED, LOW); // turn the LED off
digitalWrite(mrLED, LOW); // turn the LED off
digitalWrite(mlLED, LOW); // turn the LED off
digitalWrite(brLED, LOW); // turn the LED off
digitalWrite(blLED, LOW); // turn the LED off
}
//void setup(void)
void setup()
{
// Set up the pushbutton pins to be an input:
pinMode(topright, INPUT);
pinMode(topleft, INPUT);
pinMode(midright, INPUT);
pinMode(midleft, INPUT);
pinMode(botright, INPUT);
pinMode(botleft, INPUT);
// Set up the LED pin to be an output:
pinMode(trLED, OUTPUT);
pinMode(tlLED, OUTPUT);
pinMode(mrLED, OUTPUT);
pinMode(mlLED, OUTPUT);
pinMode(brLED, OUTPUT);
pinMode(blLED, OUTPUT);
LcdInitialise();
// LcdClear();
}
void loop()
{
int toprightState, topleftState, midrightState, midleftState, botrightState, botleftState, resetState, translateState; // variables to hold the pushbutton states
int trLEDState, tlLEDState, mrLEDState, mlLEDState, brLEDState, blLEDState; //variables to hold the LED states
toprightState = digitalRead(topright);
topleftState = digitalRead(topleft);
midrightState = digitalRead(midright);
midleftState = digitalRead(midleft);
botrightState = digitalRead(botright);
botleftState = digitalRead(botleft);
resetState = digitalRead(reset);
translateState = digitalRead(translate);
trLEDState = digitalRead(trLED);
tlLEDState = digitalRead(tlLED);
mrLEDState = digitalRead(mrLED);
mlLEDState = digitalRead(mlLED);
brLEDState = digitalRead(brLED);
blLEDState = digitalRead(blLED);
if (toprightState == LOW)
{
digitalWrite(trLED, HIGH); // turn the LED on
}
if (topleftState == LOW)
{
digitalWrite(tlLED, HIGH); // turn the LED on
}
if (midrightState == LOW)
{
digitalWrite(mrLED, HIGH); // turn the LED on
}
if (midleftState == LOW)
{
digitalWrite(mlLED, HIGH); // turn the LED on
}
if (botrightState == LOW)
{
digitalWrite(brLED, HIGH); // turn the LED on
}
if (botleftState == LOW)
{
digitalWrite(blLED, HIGH); // turn the LED on
}
if (resetState == LOW)
{
resetInput();
}
if (resetState == LOW && translateState == LOW)
{
LcdInitialise();
LcdClear();
}
if (translateState == LOW && tlLEDState == HIGH && trLEDState == HIGH && mlLEDState == HIGH && mrLEDState == HIGH && blLEDState == HIGH && brLEDState == HIGH)
{
LcdString(" ");
resetInput();
}
if (translateState == LOW && tlLEDState == HIGH && trLEDState == LOW && mlLEDState == LOW && mrLEDState == LOW && blLEDState == LOW && brLEDState == LOW)
{
LcdString("A");
resetInput();
}
if (translateState == LOW && tlLEDState == HIGH && trLEDState == LOW && mlLEDState == HIGH && mrLEDState == LOW && blLEDState == LOW && brLEDState == LOW)
{
LcdString("B");
resetInput();
}
if (translateState == LOW && tlLEDState == HIGH && trLEDState == HIGH && mlLEDState == LOW && mrLEDState == LOW && blLEDState == LOW && brLEDState == LOW)
{
LcdString("C");
resetInput();
}
if (translateState == LOW && tlLEDState == HIGH && trLEDState == HIGH && mlLEDState == LOW && mrLEDState == HIGH && blLEDState == LOW && brLEDState == LOW)
{
LcdString("D");
resetInput();
}
if (translateState == LOW && tlLEDState == HIGH && trLEDState == LOW && mlLEDState == LOW && mrLEDState == HIGH && blLEDState == LOW && brLEDState == LOW)
{
LcdString("E");
resetInput();
}
if (translateState == LOW && tlLEDState == HIGH && trLEDState == HIGH && mlLEDState == HIGH && mrLEDState == LOW && blLEDState == LOW && brLEDState == LOW)
{
LcdString("F");
resetInput();
}
if (translateState == LOW && tlLEDState == HIGH && trLEDState == HIGH && mlLEDState == HIGH && mrLEDState == HIGH && blLEDState == LOW && brLEDState == LOW)
{
LcdString("G");
resetInput();
}
if (translateState == LOW && tlLEDState == HIGH && trLEDState == LOW && mlLEDState == HIGH && mrLEDState == HIGH && blLEDState == LOW && brLEDState == LOW)
{
LcdString("H");
resetInput();
}
if (translateState == LOW && tlLEDState == LOW && trLEDState == HIGH && mlLEDState == HIGH && mrLEDState == LOW && blLEDState == LOW && brLEDState == LOW)
{
LcdString("I");
resetInput();
}
if (translateState == LOW && tlLEDState == LOW && trLEDState == HIGH && mlLEDState == HIGH && mrLEDState == HIGH && blLEDState == LOW && brLEDState == LOW)
{
LcdString("J");
resetInput();
}
if (translateState == LOW && tlLEDState == HIGH && trLEDState == LOW && mlLEDState == LOW && mrLEDState == LOW && blLEDState == HIGH && brLEDState == LOW)
{
LcdString("K");
resetInput();
}
if (translateState == LOW && tlLEDState == HIGH && trLEDState == LOW && mlLEDState == HIGH && mrLEDState == LOW && blLEDState == HIGH && brLEDState == LOW)
{
LcdString("L");
resetInput();
}
if (translateState == LOW && tlLEDState == HIGH && trLEDState == HIGH && mlLEDState == LOW && mrLEDState == LOW && blLEDState == HIGH && brLEDState == LOW)
{
LcdString("M");
resetInput();
}
if (translateState == LOW && tlLEDState == HIGH && trLEDState == HIGH && mlLEDState == LOW && mrLEDState == HIGH && blLEDState == HIGH && brLEDState == LOW)
{
LcdString("N");
resetInput();
}
if (translateState == LOW && tlLEDState == HIGH && trLEDState == LOW && mlLEDState == LOW && mrLEDState == HIGH && blLEDState == HIGH && brLEDState == LOW)
{
LcdString("O");
resetInput();
}
if (translateState == LOW && tlLEDState == HIGH && trLEDState == HIGH && mlLEDState == HIGH && mrLEDState == LOW && blLEDState == HIGH && brLEDState == LOW)
{
LcdString("P");
resetInput();
}
if (translateState == LOW && tlLEDState == HIGH && trLEDState == HIGH && mlLEDState == HIGH && mrLEDState == HIGH && blLEDState == HIGH && brLEDState == LOW)
{
LcdString("Q");
resetInput();
}
if (translateState == LOW && tlLEDState == HIGH && trLEDState == LOW && mlLEDState == HIGH && mrLEDState == HIGH && blLEDState == HIGH && brLEDState == LOW)
{
LcdString("R");
resetInput();
}
if (translateState == LOW && tlLEDState == LOW && trLEDState == HIGH && mlLEDState == HIGH && mrLEDState == LOW && blLEDState == HIGH && brLEDState == LOW)
{
LcdString("S");
resetInput();
}
if (translateState == LOW && tlLEDState == LOW && trLEDState == HIGH && mlLEDState == HIGH && mrLEDState == HIGH && blLEDState == HIGH && brLEDState == LOW)
{
LcdString("T");
resetInput();
}
if (translateState == LOW && tlLEDState == HIGH && trLEDState == LOW && mlLEDState == LOW && mrLEDState == LOW && blLEDState == HIGH && brLEDState == HIGH)
{
LcdString("U");
resetInput();
}
if (translateState == LOW && tlLEDState == HIGH && trLEDState == LOW && mlLEDState == HIGH && mrLEDState == LOW && blLEDState == HIGH && brLEDState == HIGH)
{
LcdString("V");
resetInput();
}
if (translateState == LOW && tlLEDState == LOW && trLEDState == HIGH && mlLEDState == HIGH && mrLEDState == HIGH && blLEDState == LOW && brLEDState == HIGH)
{
LcdString("W");
resetInput();
}
if (translateState == LOW && tlLEDState == HIGH && trLEDState == HIGH && mlLEDState == LOW && mrLEDState == LOW && blLEDState == HIGH && brLEDState == HIGH)
{
LcdString("X");
resetInput();
}
if (translateState == LOW && tlLEDState == HIGH && trLEDState == HIGH && mlLEDState == LOW && mrLEDState == HIGH && blLEDState == HIGH && brLEDState == HIGH)
{
LcdString("Y");
resetInput();
}
if (translateState == LOW && tlLEDState == HIGH && trLEDState == LOW && mlLEDState == LOW && mrLEDState == HIGH && blLEDState == HIGH && brLEDState == HIGH)
{
LcdString("Z");
resetInput();
}
if (translateState == LOW && tlLEDState == LOW && trLEDState == LOW && mlLEDState == HIGH && mrLEDState == HIGH && blLEDState == HIGH && brLEDState == LOW)
{
LcdString("!");
resetInput();
}
if (translateState == LOW && tlLEDState == LOW && trLEDState == LOW && mlLEDState == LOW && mrLEDState == LOW && blLEDState == HIGH && brLEDState == LOW)
{
LcdString("'");
resetInput();
}
if (translateState == LOW && tlLEDState == LOW && trLEDState == LOW && mlLEDState == HIGH && mrLEDState == LOW && blLEDState == LOW && brLEDState == LOW)
{
LcdString(",");
resetInput();
}
if (translateState == LOW && tlLEDState == LOW && trLEDState == LOW && mlLEDState == LOW && mrLEDState == LOW && blLEDState == HIGH && brLEDState == HIGH)
{
LcdString("-");
resetInput();
}
if (translateState == LOW && tlLEDState == LOW && trLEDState == LOW && mlLEDState == HIGH && mrLEDState == HIGH && blLEDState == LOW && brLEDState == HIGH)
{
LcdString(".");
resetInput();
}
if (translateState == LOW && tlLEDState == LOW && trLEDState == LOW && mlLEDState == HIGH && mrLEDState == LOW && blLEDState == HIGH && brLEDState == HIGH)
{
LcdString("?");
resetInput();
}
if (translateState == LOW && tlLEDState == LOW && trLEDState == HIGH && mlLEDState == LOW && mrLEDState == HIGH && blLEDState == HIGH && brLEDState == HIGH)
{
LcdString("#");
resetInput();
}
}
| [
"noreply@github.com"
] | noreply@github.com |
52b26c4e07aa55ed97d4a8f825e4c900225389f7 | fecdba626691b5807641861a03c75efda3c6caec | /liblapin/adv/get_scope.cpp | 7a52692ee45f854326ceaf7a1ea5abd834878a41 | [] | no_license | thecyril/Wolf3D | 33763018a65285c2f0f9fee2999d8f384be72a0e | cd28b4611f66cfe512433887d0df0b2751e50ae9 | refs/heads/master | 2021-01-20T18:15:11.502892 | 2016-06-13T16:12:37 | 2016-06-13T16:12:37 | 60,971,498 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 422 | cpp | // Jason Brillante "Damdoshi"
// Hanged Bunny Studio 2014-2016
//
// Bibliothèque Lapin
#include "lapin_private.h"
t_bunny_ini_scope *bunny_ini_get_scope(t_bunny_ini *ini,
const char *scope)
{
bpt::Ini *in = (bpt::Ini*)ini;
std::map<std::string, bpt::Ini::Scope>::iterator it;
if ((it = in->GetData().find(std::string(scope))) == in->GetData().end())
return (NULL);
return (&it->second);
}
| [
"puccio_c@epitech.eu"
] | puccio_c@epitech.eu |
8868d1748fa743c0cd008b59a7a1b489f3bcd782 | d9444ab5c81e184a062c9b9923943e7ab7758e8f | /rush00/src/modules/username.cpp | 97454cdb35f43b4ede21c97a5c66311402454bf6 | [] | no_license | MarjorieLV/cpp | eae1831e47c7166bccef7cca85f67d01464af429 | 32504496cc79ad66424c7f62ecbcb11fb5bc0b7a | refs/heads/master | 2021-06-09T21:28:26.174130 | 2016-12-07T13:22:08 | 2016-12-07T13:22:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 507 | cpp | #include <string>
#include <unistd.h>
#include "ImonitorModule.hpp"
#include "username.hpp"
UserName::UserName()
{
_username = getlogin();
}
UserName::UserName(UserName const &src)
{
*this = src;
}
UserName::~UserName(){}
UserName &UserName::operator=(UserName const &src)
{
if (this != &src) {
_username = src.getVar();
}
return *this;
}
void UserName::update() const{}
const UserName *UserName::getModule() const
{
return this;
}
std::string UserName::getVar() const
{
return _username;
} | [
"marjorie.lv@gmail.com"
] | marjorie.lv@gmail.com |
10da716e2033be11f98fd5955577ea3642a64d8e | b72e33e7416e4dc7d3f4d4fd4bb5bb0ed8e01d99 | /TetrisOpenGL/src/shape.cpp | dbf2db6c377e5796296e7627b4a4ac8a72a951b9 | [] | no_license | isaachibou/TetrisOpenGL | db80d1d00217a286b8c474708f55e99b61f0c867 | 4f8533c3c4f4d3e088e537da497eb505c1ccadc9 | refs/heads/master | 2016-09-05T20:17:28.727735 | 2014-06-14T17:50:10 | 2014-06-14T17:50:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,665 | cpp | #include "shape.h"
#include "iostream"
using namespace std;
Shape::Shape()
{
this->index = 0;
this->rotation = 0;
this->OffSet = 0;
for(int i=0;i<4;i++)
{
this->Lines[i] = 0;
}
}
Shape::~Shape()
{
}
// Accessors
int
Shape::getLines(int i)
{
return this->Lines[i];
}
void
Shape::setLines(int i, int value)
{
this->Lines[i] = value;
}
int
Shape::getOffSet()
{
return this->OffSet;
}
void
Shape::setOffSet( int value)
{
this->OffSet = value;
}
int
Shape::getRed()
{
return this->red;
}
int
Shape::getGreen()
{
return this->green;
}
int
Shape::getBlue()
{
return this->blue;
}
// Calculation
int*
Shape::DevelopFloor(int i)
{
string res;
int floor = this->Lines[i];
int SIZE = 10;
int *Buffer = (int*) malloc(SIZE*sizeof(Buffer));
for(i=0; i<10; i++)
{
if(floor%2 == 0)
{
res = '0' + res;
floor /= 2;
}
else
{
res = '1' + res;
floor /= 2;
}
}
for(i=0; i<SIZE; i++)
{
Buffer[i] = res[i]-48;
}
return Buffer;
}
int
Shape::getHeight()
{
int h=0;
for(int i=0;i<4;i++)
{
if(this->Lines[i] != 0)
{ h++; }
}
return h;
}
int
Shape::getIndex()
{
return this->index;
}
void
Shape::setIndex(int value)
{
this->index = value;
}
int
Shape::getRotation()
{
return this->rotation;
}
void
Shape::setRotation(int value)
{
this->rotation = value;
}
int
Shape::getLineRotation(int rotation, int index,int k)
{
return this->Collection[index][rotation][k];
}
/* Operators */
Shape&
Shape::operator =(const Shape& s)
{
this->index = s.index;
for(int i=0; i<0; i++)
{
this->Lines[i] = s.Lines[i];
}
}
/* Display */
void
Shape::drawShape()
{
int* tmp;
char c =254, d=255;
for(int i=0; i<4; i++)
{
printf("\n |");
for(int j=0; j<10;j++)
{
tmp = DevelopFloor(i);
if(tmp[j] == 1)
{
printf(" %c", c);
}
else
{
printf(" %c", d);
}
}
printf(" |");
}
}
// Fill
void
Shape::GetShape()
{
int randNum = rand() %(0+7);
for(int i=0;i<4;i++)
{
this->Lines[i] = this->Collection[randNum][0][i];
}
this->index = randNum;
this->rotation = 0;
this->OffSet = 0;
switch(this->index)
{
case 0:
this->red = 0;
this->green = 0;
this->blue = 1;
break;
case 1:
this->red = 0;
this->green = 1;
this->blue = 1;
break;
case 2:
this->red = 1;
this->green = 0;
this->blue = 1;
break;
case 3:
this->red = 1;
this->green = 0;
this->blue = 0;
break;
case 4:
this->red = 0;
this->green = 1;
this->blue = 0;
break;
case 5:
this->red = 1 ;
this->green = 1;
this->blue = 0;
break;
case 6:
this->red = 1;
this->green = 1;
this->blue = 1;
break;
}
}
void
Shape::GetThisShape(Shape s)
{
for(int i=0;i<4;i++)
{
this->Lines[i] = s.getLines(i);
}
this->index = s.getIndex();
this->rotation = 0;
this->OffSet = 0;
this->red = s.getRed();
this->green = s.getGreen();
this->blue = s.getBlue();
}
| [
"isaac.hibou@gmail.com"
] | isaac.hibou@gmail.com |
3c8c2452c9965f9001d7a6b36ed76348122fa2d4 | 16b142e8cd4a704c0488646c82141716409a698b | /Section4.3/buylow.cpp | 082c2e38fb0c6ddaa04ac8b46002aed530800f06 | [] | no_license | BragCat/USACO | 3ba602c50210e60ebda3653263d27eb34996e31d | db22e56e5d42c462ea38cf656c4dfba619f79265 | refs/heads/master | 2018-11-22T08:42:46.196513 | 2018-10-30T13:46:07 | 2018-10-30T13:46:07 | 100,441,033 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,471 | cpp | /*
ID: bragcat1
LANG: C++11
TASK: buylow
*/
#include <fstream>
using namespace std;
const int MAX_N = 5000;
const int MAX_B = 32;
const int DECIMAL = 100000000;
class BigNumber {
public:
int digits[MAX_B] = {0};
int digitCnt = 0;
BigNumber() {
digits[0] = 1;
digitCnt = 1;
}
BigNumber & plus(BigNumber &number) {
int digitCnt1 = number.digitCnt;
int up = 0;
for (int i = 0; i < max(digitCnt1, digitCnt) + 1; ++i) {
digits[i] = digits[i] + number.digits[i] + up;
up = digits[i] / DECIMAL;
digits[i] %= DECIMAL;
}
while (digits[digitCnt] > 0) {
++digitCnt;
}
return *this;
}
BigNumber & copy(BigNumber &number) {
for (int i = 0; i < digitCnt; ++i) {
digits[i] = 0;
}
digitCnt = number.digitCnt;
for (int i = 0; i < digitCnt; ++i) {
digits[i] = number.digits[i];
}
return *this;
}
};
int price[MAX_N + 1];
int n;
int f[MAX_N + 1];
BigNumber g[MAX_N + 1];
int nextIndex[MAX_N + 1];
void print(ofstream &fout, BigNumber number) {
for (int i = number.digitCnt - 1; i >= 0; --i) {
int k = DECIMAL / 10;
int digit = number.digits[i];
if (i != number.digitCnt - 1) {
while (k > digit) {
fout << 0;
k /= 10;
}
}
fout << digit;
}
}
int main() {
ifstream fin("buylow.in");
fin >> n;
for (int i = 0; i < n; ++i) {
fin >> price[i];
}
fin.close();
price[n++] = 0;
for (int i = 0; i < n; ++i) {
f[i] = 1;
for (int j = i + 1; j < n; ++j) {
if (price[i] == price[j]) {
nextIndex[i] = j;
break;
}
}
}
for (int i = 1; i < n; ++i) {
for (int j = 0; j < i; ++j) {
if (price[j] > price[i]) {
if (nextIndex[j] && nextIndex[j] < i) {
continue;
}
if (f[j] + 1 > f[i]) {
f[i] = f[j] + 1;
g[i].copy(g[j]);
}
else if (f[j] + 1 == f[i]) {
g[i].plus(g[j]);
}
}
}
}
ofstream fout("buylow.out");
fout << f[n - 1] - 1 << " ";
print(fout, g[n - 1]);
fout << endl;
fout.close();
return 0;
}
| [
"bragcat.li@gmail.com"
] | bragcat.li@gmail.com |
9959246b3034d064c1451e2c657ff0b753b0ecc5 | e97a742ca5958cd7d0dd3d08764954b91b0f6518 | /annotator/AnnotationManipulator.h | 723c8b1582abb4c67d59d6d144b2f89b0ea1d75a | [] | no_license | shayannikoohemat/grammar | f6532e27321e1dd1346b4c71f64d4c9da46584f2 | a393a200499af974ecdc7db2c69c2a97887ee4f4 | refs/heads/master | 2023-08-04T04:13:12.417338 | 2017-10-20T14:46:18 | 2017-10-20T14:46:18 | 107,680,241 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,441 | h | //
// Created by NikoohematS on 7-8-2017.
//
#ifndef ANNOTATOR_ANNOTATIONMANIPULATION_H
#define ANNOTATOR_ANNOTATIONMANIPULATION_H
#endif //ANNOTATOR_ANNOTATIONMANIPULATION_H
#include <iostream>
#include "Annotator.h"
#include <sstream>
#include <limits.h>
#include "LaserUnit.h"
void ExportClasLabelNames(char* directory);
void ImportAnnotatedAsciiToLaser(string dirname, string ascii_extension);
LaserPoints MergeLabels (LaserPoints lp);
void LaserPointsManipulationBatch(string directory, string ouput_directory);
void Laser2AsciiBatch(string directory,
int store_x, int store_y, int store_z,
string out_put_directory="",
int store_r=0, int store_g=0, int store_b=0,
int store_l=0, int store_l2=0, int store_fs=0,
int store_p=0, int store_lpf=0, int store_pl=0,
int store_pn=0, int store_sn=0, int store_lsn=0,
int store_poln=0, int store_scan=0, int store_t=0,
int store_a=0, int store_cnt=0, int store_tt=0,
int store_xt=0, int store_yt=0, int store_zt=0);
LaserSubUnit readAsciiPCD(char *ascii_file, char* ascii_file_filter,
int remove_double_points,
int column_x, int column_y, int column_z,
int column_r, int column_g, int column_b,
int column_p, int column_n, int column_l, int column_pl,
int column_pn, int column_sn, int column_poln,
int column_scan, int column_t, int column_a,
int column_int, int column_fs, int header_lines,
double x_offset, double y_offset, double z_offset,
int p_offset,
double x_scale, double y_scale, double z_scale,
int set_r, int fixed_r, int set_p, int fixed_p,
int set_l, int fixed_l, int set_scan, int fixed_scan,
int set_fs, int fixed_fs,
char *rootname, char *output_directory,
int meta_type, int max_subunit_size,
int rgb_scale, int int_scale,
int column_nx, int column_ny, int column_nz);
| [
"m7661953@utwente.nl"
] | m7661953@utwente.nl |
b4dc4fec40773a55a803774ab8b8c7625a056787 | 3342f3b95c08d16333176324064a75896d1642a8 | /catkin_ws/src/cankaodaima/abb_irb1200_planning/scripts/ros_lib/moveit_msgs/MotionPlanDetailedResponse.h | da98411d446e85c91581aadd51ddb90ca38ac545 | [] | no_license | suxiyuanSJTU/test | 3232bf8d53b41cc3fe0ca319f4cff4045eaa8db7 | 88611d121c25d33848a2b9d406ba65e0003d6978 | refs/heads/master | 2023-08-13T07:17:49.542271 | 2021-10-14T05:05:42 | 2021-10-14T05:05:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,373 | h | #ifndef _ROS_moveit_msgs_MotionPlanDetailedResponse_h
#define _ROS_moveit_msgs_MotionPlanDetailedResponse_h
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include "ros/msg.h"
#include "moveit_msgs/RobotState.h"
#include "moveit_msgs/RobotTrajectory.h"
#include "moveit_msgs/MoveItErrorCodes.h"
namespace moveit_msgs
{
class MotionPlanDetailedResponse : public ros::Msg
{
public:
typedef moveit_msgs::RobotState _trajectory_start_type;
_trajectory_start_type trajectory_start;
typedef const char* _group_name_type;
_group_name_type group_name;
uint32_t trajectory_length;
typedef moveit_msgs::RobotTrajectory _trajectory_type;
_trajectory_type st_trajectory;
_trajectory_type * trajectory;
uint32_t description_length;
typedef char* _description_type;
_description_type st_description;
_description_type * description;
uint32_t processing_time_length;
typedef float _processing_time_type;
_processing_time_type st_processing_time;
_processing_time_type * processing_time;
typedef moveit_msgs::MoveItErrorCodes _error_code_type;
_error_code_type error_code;
MotionPlanDetailedResponse():
trajectory_start(),
group_name(""),
trajectory_length(0), st_trajectory(), trajectory(nullptr),
description_length(0), st_description(), description(nullptr),
processing_time_length(0), st_processing_time(), processing_time(nullptr),
error_code()
{
}
virtual int serialize(unsigned char *outbuffer) const override
{
int offset = 0;
offset += this->trajectory_start.serialize(outbuffer + offset);
uint32_t length_group_name = strlen(this->group_name);
varToArr(outbuffer + offset, length_group_name);
offset += 4;
memcpy(outbuffer + offset, this->group_name, length_group_name);
offset += length_group_name;
*(outbuffer + offset + 0) = (this->trajectory_length >> (8 * 0)) & 0xFF;
*(outbuffer + offset + 1) = (this->trajectory_length >> (8 * 1)) & 0xFF;
*(outbuffer + offset + 2) = (this->trajectory_length >> (8 * 2)) & 0xFF;
*(outbuffer + offset + 3) = (this->trajectory_length >> (8 * 3)) & 0xFF;
offset += sizeof(this->trajectory_length);
for( uint32_t i = 0; i < trajectory_length; i++){
offset += this->trajectory[i].serialize(outbuffer + offset);
}
*(outbuffer + offset + 0) = (this->description_length >> (8 * 0)) & 0xFF;
*(outbuffer + offset + 1) = (this->description_length >> (8 * 1)) & 0xFF;
*(outbuffer + offset + 2) = (this->description_length >> (8 * 2)) & 0xFF;
*(outbuffer + offset + 3) = (this->description_length >> (8 * 3)) & 0xFF;
offset += sizeof(this->description_length);
for( uint32_t i = 0; i < description_length; i++){
uint32_t length_descriptioni = strlen(this->description[i]);
varToArr(outbuffer + offset, length_descriptioni);
offset += 4;
memcpy(outbuffer + offset, this->description[i], length_descriptioni);
offset += length_descriptioni;
}
*(outbuffer + offset + 0) = (this->processing_time_length >> (8 * 0)) & 0xFF;
*(outbuffer + offset + 1) = (this->processing_time_length >> (8 * 1)) & 0xFF;
*(outbuffer + offset + 2) = (this->processing_time_length >> (8 * 2)) & 0xFF;
*(outbuffer + offset + 3) = (this->processing_time_length >> (8 * 3)) & 0xFF;
offset += sizeof(this->processing_time_length);
for( uint32_t i = 0; i < processing_time_length; i++){
offset += serializeAvrFloat64(outbuffer + offset, this->processing_time[i]);
}
offset += this->error_code.serialize(outbuffer + offset);
return offset;
}
virtual int deserialize(unsigned char *inbuffer) override
{
int offset = 0;
offset += this->trajectory_start.deserialize(inbuffer + offset);
uint32_t length_group_name;
arrToVar(length_group_name, (inbuffer + offset));
offset += 4;
for(unsigned int k= offset; k< offset+length_group_name; ++k){
inbuffer[k-1]=inbuffer[k];
}
inbuffer[offset+length_group_name-1]=0;
this->group_name = (char *)(inbuffer + offset-1);
offset += length_group_name;
uint32_t trajectory_lengthT = ((uint32_t) (*(inbuffer + offset)));
trajectory_lengthT |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1);
trajectory_lengthT |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2);
trajectory_lengthT |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3);
offset += sizeof(this->trajectory_length);
if(trajectory_lengthT > trajectory_length)
this->trajectory = (moveit_msgs::RobotTrajectory*)realloc(this->trajectory, trajectory_lengthT * sizeof(moveit_msgs::RobotTrajectory));
trajectory_length = trajectory_lengthT;
for( uint32_t i = 0; i < trajectory_length; i++){
offset += this->st_trajectory.deserialize(inbuffer + offset);
memcpy( &(this->trajectory[i]), &(this->st_trajectory), sizeof(moveit_msgs::RobotTrajectory));
}
uint32_t description_lengthT = ((uint32_t) (*(inbuffer + offset)));
description_lengthT |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1);
description_lengthT |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2);
description_lengthT |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3);
offset += sizeof(this->description_length);
if(description_lengthT > description_length)
this->description = (char**)realloc(this->description, description_lengthT * sizeof(char*));
description_length = description_lengthT;
for( uint32_t i = 0; i < description_length; i++){
uint32_t length_st_description;
arrToVar(length_st_description, (inbuffer + offset));
offset += 4;
for(unsigned int k= offset; k< offset+length_st_description; ++k){
inbuffer[k-1]=inbuffer[k];
}
inbuffer[offset+length_st_description-1]=0;
this->st_description = (char *)(inbuffer + offset-1);
offset += length_st_description;
memcpy( &(this->description[i]), &(this->st_description), sizeof(char*));
}
uint32_t processing_time_lengthT = ((uint32_t) (*(inbuffer + offset)));
processing_time_lengthT |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1);
processing_time_lengthT |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2);
processing_time_lengthT |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3);
offset += sizeof(this->processing_time_length);
if(processing_time_lengthT > processing_time_length)
this->processing_time = (float*)realloc(this->processing_time, processing_time_lengthT * sizeof(float));
processing_time_length = processing_time_lengthT;
for( uint32_t i = 0; i < processing_time_length; i++){
offset += deserializeAvrFloat64(inbuffer + offset, &(this->st_processing_time));
memcpy( &(this->processing_time[i]), &(this->st_processing_time), sizeof(float));
}
offset += this->error_code.deserialize(inbuffer + offset);
return offset;
}
virtual const char * getType() override { return "moveit_msgs/MotionPlanDetailedResponse"; };
virtual const char * getMD5() override { return "7b84c374bb2e37bdc0eba664f7636a8f"; };
};
}
#endif
| [
"sxy12138@sjtu.edu.cn"
] | sxy12138@sjtu.edu.cn |
95e14e281f61e7ec7dee8aece3805f0101381310 | 16bdc31a22afc2bd3f66065d03b588b0893415a7 | /src/hash.cpp | 79e987d3134836e6310b97d8e45d9415e1eb4adb | [
"Artistic-2.0"
] | permissive | theanonym/libyoba-perl | 308de60eaa06a5e78639bff13832f435bbaac754 | c97dda6222636f69664aca58271d2a8ca6540783 | refs/heads/master | 2021-01-19T20:23:09.466025 | 2017-04-24T17:51:57 | 2017-04-24T17:51:57 | 88,501,611 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,748 | cpp | #include "yobaperl/hash.hpp"
#include "yobaperl/perl.hpp"
#include "yobaperl/scalar.hpp"
namespace yoba {
Hash::Hash(Perl & perl, HV * hv, bool increase_refcount)
: Variable(perl, reinterpret_cast<SV *>(hv), increase_refcount)
{
}
I32 Hash::getSize() const
{
return HvUSEDKEYS(getHV());
}
bool Hash::isEmpty() const
{
return getSize() == 0;
}
bool Hash::isExists(const std::string & key) const
{
return hv_exists(getHV(), key.c_str(), key.length());
}
Scalar Hash::get(const std::string & key)
{
if(isExists(key))
{
SV ** elements = hv_fetch(getHV(), key.c_str(), key.length(), /* lval */NULL);
YOBAPERL_ASSERT(elements);
SV * element = *elements;
YOBAPERL_ASSERT(element);
return Scalar(_perl, element, /* ref++ */true);
}
else
{
std::string error = "Hash entry not exists (key: " + key + ")";
if(_perl.isExceptionsEnabled())
throw PerlException(_perl.getId(), error);
if(_perl.isWarningsEnabled())
warn("%s", error.c_str());
return _perl.newScalar();
}
}
Hash & Hash::insert(const std::string & key, const Scalar & value)
{
_store(key, value.getSV());
return *this;
}
Hash & Hash::insert(const std::pair<std::string, Scalar> & pair)
{
insert(pair.first, pair.second);
return *this;
}
Hash & Hash::insert(const std::unordered_map<std::string, Scalar> & hashmap)
{
for(auto it = hashmap.cbegin(); it != hashmap.cend(); it++)
insert(it->first, it->second);
return *this;
}
Scalar Hash::remove(const std::string & key)
{
if(isExists(key))
{
SV * result = hv_delete(getHV(), key.c_str(), static_cast<U32>(key.length()), /* flags */0);
YOBAPERL_ASSERT(result);
return Scalar(_perl, result, /* ref++ */true);
}
else
{
std::string error = "Hash entry not exists (key: " + key + ")";
if(_perl.isExceptionsEnabled())
throw PerlException(_perl.getId(), error);
if(_perl.isWarningsEnabled())
warn("%s", error.c_str());
return _perl.newScalar();
}
}
Hash & Hash::clear()
{
hv_clear(getHV());
return *this;
}
std::string Hash::toString() const
{
std::stringstream ss;
ss << "(";
auto it = begin();
while(it)
{
ss << *it;
if(++it)
ss << ", ";
}
ss << ")";
return ss.str();
}
std::unordered_map<std::string, Scalar> Hash::toMap() const
{
std::unordered_map<std::string, Scalar> result;
result.reserve(getSize());
auto it = begin();
while(it)
{
result.insert((*it).toPair());
++it;
}
return result;
}
Scalar Hash::makeRef() const
{
return Scalar(_perl, newRV_inc(MUTABLE_SV(getHV())), false);
}
Hash Hash::makeCopy() const
{
Hash result = _perl.newHash();
for(HashEntry entry : *this)
result.insert(entry.getKey(), entry.getValue().makeCopy());
return result;
}
Hash::Iterator Hash::begin() const
{
return Iterator(*this);
}
Hash::Iterator Hash::end() const
{
return Iterator(*this, /* is_null */true);
}
HV * Hash::getHV() const
{
return reinterpret_cast<HV *>(getSV());
}
Hash::operator bool() const
{
return !isEmpty();
}
Scalar Hash::operator[] (const std::string & key) noexcept
{
return Scalar(_perl, *hv_fetch(getHV(), key.c_str(), key.length(), /* lval */NULL), /* ref++ */true);
}
Scalar Hash::operator[] (const char * key) noexcept
{
return (*this)[std::string(key)];
}
void Hash::_store(const std::string & key, SV * value)
{
SvREFCNT_inc_NN(value);
hv_store(getHV(), key.c_str(), key.length(), value, /* hash */0);
}
I32 Hash::_interInit() const
{
return hv_iterinit(getHV());
}
HE * Hash::_interNext() const
{
return hv_iternext(getHV());
}
} // namespace yoba
| [
"none"
] | none |
95cd80b9650e27de98c74a24fb6e5ebc66c7ef07 | 5a0586046657fa55e50ac5c058b9ede669438486 | /libts/tsStoreMySQL.h | a45ef0d2943ad93e78b014636547c346f938af5b | [] | no_license | mrhill/tickstore | c4edf28119938d825022479904a121a7d77a16ae | cfc3af9a3de2cf0f0aa63b6a977062a58061063c | refs/heads/master | 2016-08-06T06:12:00.784639 | 2013-06-21T14:43:13 | 2013-06-21T14:43:13 | 2,438,234 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,035 | h | #ifndef tsSTOREMYSQL_H
#define tsSTOREMYSQL_H
#include "tsStore.h"
#include "tsMutex.h"
#include "tsMySQL.h"
#include <map>
class tsStoreMySQL : public tsStore
{
tsMySQLCon mCon;
tsMutex mMutex;
struct InsertParam
{
bbU64 mSym;
bbU64 mTime;
unsigned long mEscRawTickLength;
bbU32 mCount;
bbU16 mTT;
char mEscRawTick[tsTick::SERIALIZEDMAXSIZE*2 + 1];
};
struct Feed
{
bbU64 mFeedID;
MYSQL_STMT* mInsertStmt;
MYSQL_BIND mInsertParam[5];
Feed(tsStoreMySQL& parent, bbU64 feedID);
~Feed();
};
typedef std::map<bbU64, Feed*> FeedMap;
FeedMap mFeedMap;
InsertParam mInsertParam;
void CreateFeedTable(bbU64 feedID);
Feed* GetFeed(bbU64 feedID);
void InsertTick(Feed* pFeed, tsTick& tick, const char* pRawTick, bbUINT tickSize);
public:
tsStoreMySQL(const char* pDBName);
virtual ~tsStoreMySQL();
virtual void SaveTick(const char* pRawTick, bbUINT tickSize);
};
#endif
| [
"github@schalig.org"
] | github@schalig.org |
2771bfc1a306fae61c628293887a493920723a75 | 0c420e8b97af7a1dacb668b1b8ef1180a8d47588 | /Backup2306/EvCoreLibraries/EvUtilities/stdafx.cpp | fd159444b495042fc29b124d53dcfa1deab8acc9 | [] | no_license | Spritutu/Halcon_develop | 9da18019b3fefac60f81ed94d9ce0f6b04ce7bbe | f2ea3292e7a13d65cab5cb5a4d507978ca593b66 | refs/heads/master | 2022-11-04T22:17:35.137845 | 2020-06-22T17:30:19 | 2020-06-22T17:30:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 290 | cpp | // stdafx.cpp : source file that includes just the standard includes
// EvUtilities.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"huynhbuutu@gmail.com"
] | huynhbuutu@gmail.com |
e1b8188537a5dde27102dc06b9cebb2414290bea | 873acd5a55ec63deb451d8a9c0413f3109605c82 | /PSqExp1/src/View.cpp | 332b5aaf81cce1e963be029ba7802f4c8607b561 | [
"MIT"
] | permissive | Colosu/Bachelor-Thesis | cb760dad941b98860268bba1c6ba5457dabd23df | 311af0bf28265763066a6cfbd5ccccdb57ada7e5 | refs/heads/master | 2022-01-15T23:32:46.424218 | 2019-07-01T15:33:06 | 2019-07-01T15:33:06 | 125,886,824 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 252 | cpp | /*
* View.cpp
*
* Created on: 29 jul. 2017
* Author: colosu
*/
#include "View.h"
namespace fst {
View::View() {
// TODO Auto-generated constructor stub
}
View::~View() {
// TODO Auto-generated destructor stub
}
} /* namespace std */
| [
"noreply@github.com"
] | noreply@github.com |
9485305d7858772b1c6c87cdb0bce56786feca9f | 841ce8cd825b6fa814e122e9a910cf474c343ca0 | /src/Tools/include/point.hpp | b5eb5ec87b30253822dfbeb1923d7f0491998c1f | [
"MIT"
] | permissive | eibmtcs/lbdg | b9fb495e6d2c45ccbaf6d249a1218313f1323371 | 48fdbb3f2104fd21700e978b83615acc25acb769 | refs/heads/master | 2023-05-11T17:58:17.730180 | 2021-06-02T10:01:18 | 2021-06-02T10:01:18 | 372,824,509 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 458 | hpp | #ifndef __POINT_HPP__
#define __POINT_HPP__
#include <iostream>
#include <glm/glm.hpp>
class Point {
public:
Point(float x = 0, float y = 0, float z = 0) : x(x), y(y), z(z) {}
Point &operator=(Point &rhs);
Point &operator=(const Point &rhs);
Point &setXyz(float x, float y, float z);
operator glm::vec3() const;
float getX();
float getY();
float getZ();
void debug();
float x;
float y;
float z;
};
#endif
| [
"eibmtcs@outlook.com"
] | eibmtcs@outlook.com |
f7d3184a894fc78d50c56d4f039687efef792916 | 5c0cde9516179e199beda1104a329b252c7684b7 | /Graphics/Middleware/QT/include/QtCore/qstate.h | 8080c9062d2faaa9c43a55d05cd95bd3fb0461b1 | [] | no_license | herocrx/OpenGLMatrices | 3f8ff924e7160e76464d9480af7cf5652954622b | ca532ebba199945813a563fe2fbadc2f408e9f4b | refs/heads/master | 2021-05-07T08:28:21.614604 | 2017-12-17T19:45:40 | 2017-12-17T19:45:40 | 109,338,861 | 0 | 0 | null | 2017-12-17T19:45:41 | 2017-11-03T01:47:27 | HTML | UTF-8 | C++ | false | false | 4,028 | h | /****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QSTATE_H
#define QSTATE_H
#include <QtCore/qabstractstate.h>
#include <QtCore/qlist.h>
QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
#ifndef QT_NO_STATEMACHINE
class QAbstractTransition;
class QSignalTransition;
class QStatePrivate;
class Q_CORE_EXPORT QState : public QAbstractState
{
Q_OBJECT
Q_PROPERTY(QAbstractState* initialState READ initialState WRITE setInitialState)
Q_PROPERTY(QAbstractState* errorState READ errorState WRITE setErrorState)
Q_PROPERTY(ChildMode childMode READ childMode WRITE setChildMode)
Q_ENUMS(ChildMode RestorePolicy)
public:
enum ChildMode {
ExclusiveStates,
ParallelStates
};
enum RestorePolicy {
DontRestoreProperties,
RestoreProperties
};
QState(QState *parent = 0);
QState(ChildMode childMode, QState *parent = 0);
~QState();
QAbstractState *errorState() const;
void setErrorState(QAbstractState *state);
void addTransition(QAbstractTransition *transition);
QSignalTransition *addTransition(const QObject *sender, const char *signal, QAbstractState *target);
QAbstractTransition *addTransition(QAbstractState *target);
void removeTransition(QAbstractTransition *transition);
QList<QAbstractTransition*> transitions() const;
QAbstractState *initialState() const;
void setInitialState(QAbstractState *state);
ChildMode childMode() const;
void setChildMode(ChildMode mode);
#ifndef QT_NO_PROPERTIES
void assignProperty(QObject *object, const char *name,
const QVariant &value);
#endif
Q_SIGNALS:
void finished(
#if !defined(Q_QDOC)
QPrivateSignal
#endif
);
void propertiesAssigned(
#if !defined(Q_QDOC)
QPrivateSignal
#endif
);
protected:
void onEntry(QEvent *event);
void onExit(QEvent *event);
bool event(QEvent *e);
protected:
QState(QStatePrivate &dd, QState *parent);
private:
Q_DISABLE_COPY(QState)
Q_DECLARE_PRIVATE(QState)
};
#endif //QT_NO_STATEMACHINE
QT_END_NAMESPACE
QT_END_HEADER
#endif
| [
"hubertkuc13@gmail.com"
] | hubertkuc13@gmail.com |
fa98a0dab4de23411af51417d774863f449fe89e | 55b1b1f6cf39ef1980dcfe79a82913c82ee8616d | /src/qt/bitcoingui.cpp | b3eff81d869a2d329605e0deb3dc08af1f8c9fe2 | [
"MIT"
] | permissive | yibitcoin/yibitcoin3 | 23b1a81effb808d8738c21cbda7fe3e4015d005a | 972eab2a93413d73aff4312f91503287682188c0 | refs/heads/master | 2021-01-19T09:46:41.280059 | 2017-04-10T08:05:41 | 2017-04-10T08:05:41 | 87,783,571 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 37,787 | cpp | /*
* Qt4 bitcoin GUI.
*
* W.J. van der Laan 2011-2012
* The Bitcoin Developers 2011-2012
*/
#include "bitcoingui.h"
#include "transactiontablemodel.h"
#include "addressbookpage.h"
#include "sendcoinsdialog.h"
#include "signverifymessagedialog.h"
#include "optionsdialog.h"
#include "aboutdialog.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "editaddressdialog.h"
#include "optionsmodel.h"
#include "transactiondescdialog.h"
#include "addresstablemodel.h"
#include "transactionview.h"
#include "overviewpage.h"
#include "bitcoinunits.h"
#include "guiconstants.h"
#include "askpassphrasedialog.h"
#include "notificator.h"
#include "guiutil.h"
#include "rpcconsole.h"
#include "wallet.h"
#ifdef Q_OS_MAC
#include "macdockiconhandler.h"
#endif
#include <QApplication>
#include <QMainWindow>
#include <QMenuBar>
#include <QMenu>
#include <QIcon>
#include <QTabWidget>
#include <QVBoxLayout>
#include <QToolBar>
#include <QStatusBar>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QLocale>
#include <QMessageBox>
#include <QMimeData>
#include <QProgressBar>
#include <QStackedWidget>
#include <QDateTime>
#include <QMovie>
#include <QFileDialog>
#include <QDesktopServices>
#include <QTimer>
#include <QDragEnterEvent>
#include <QUrl>
#include <QStyle>
#include <iostream>
extern CWallet* pwalletMain;
extern int64_t nLastCoinStakeSearchInterval;
extern unsigned int nTargetSpacing;
double GetPoSKernelPS();
BitcoinGUI::BitcoinGUI(QWidget *parent):
QMainWindow(parent),
clientModel(0),
walletModel(0),
encryptWalletAction(0),
changePassphraseAction(0),
unlockWalletAction(0),
lockWalletAction(0),
aboutQtAction(0),
trayIcon(0),
notificator(0),
rpcConsole(0)
{
resize(850, 550);
setWindowTitle(tr("Yibitcoin") + " - " + tr("Wallet"));
// Prevent resizing.
setFixedSize(size());
// Remove "hand" cursor from status bar.
this->statusBar()->setSizeGripEnabled(false);
// this->setStyleSheet(".BitcoinGUI { background-image: url(:/images/background-no-logo); } \
// * { color: rgb(255, 255, 255); \
// background-color: rgba(255, 255, 255, 0); \
// selection-background-color: rgb(2, 6, 150); \
// } \
// QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid white; } \
// QTableView { background-color: rgb(2, 6, 15); alternate-background-color: rgb(2, 6, 50); } \
// QHeaderView::section { \
// background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, \
// stop:0 rgb(2, 6, 15), stop: 0.5 rgb(2, 6, 70), \
// stop: 0.6 rgb(2, 6, 70), stop:1 rgb(2, 6, 15)); \
// color: white; \
// padding-left: 4px; \
// border: 1px solid #6c6c6c; \
// } \
// QFrame#frameMain, QToolButton:on { \
// background-color: rgba(11, 38, 73, 210); \
// border: 1px solid rgb(0, 186, 255); \
// border-radius: 4px; \
// } \
// QValueComboBox, QLineEdit, QDoubleSpinBox { \
// border: 1px solid rgb(2, 6, 150) \
// }\
// ");
#ifndef Q_OS_MAC
qApp->setWindowIcon(QIcon(":icons/bitcoin"));
setWindowIcon(QIcon(":icons/bitcoin"));
#else
setUnifiedTitleAndToolBarOnMac(true);
QApplication::setAttribute(Qt::AA_DontShowIconsInMenus);
#endif
// Accept D&D of URIs
setAcceptDrops(true);
// Create actions for the toolbar, menu bar and tray/dock icon
createActions();
// Create application menu bar
createMenuBar();
// Create the toolbars
createToolBars();
// Create the tray icon (or setup the dock icon)
createTrayIcon();
// Create tabs
overviewPage = new OverviewPage(this);
{
transactionsPage = new QWidget(this);
QHBoxLayout* hl = new QHBoxLayout(transactionsPage);
QFrame* frameMain = new QFrame(transactionsPage);
hl->addWidget(frameMain);
frameMain->setObjectName(QString("frameMain"));
frameMain->setFrameShape(QFrame::NoFrame);
QVBoxLayout *vbox = new QVBoxLayout(frameMain);
transactionView = new TransactionView(transactionsPage);
vbox->addWidget(transactionView);
frameMain->setLayout(vbox);
}
addressBookPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab);
receiveCoinsPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab);
sendCoinsPage = new SendCoinsDialog(this);
signVerifyMessageDialog.reset(new SignVerifyMessageDialog);
centralWidget = new QStackedWidget(this);
centralWidget->addWidget(overviewPage);
centralWidget->addWidget(transactionsPage);
centralWidget->addWidget(addressBookPage);
centralWidget->addWidget(receiveCoinsPage);
centralWidget->addWidget(sendCoinsPage);
setCentralWidget(centralWidget);
// Create status bar
statusBar();
// Status bar notification icons
QFrame *frameBlocks = new QFrame();
frameBlocks->setContentsMargins(0,0,0,0);
frameBlocks->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);
QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks);
frameBlocksLayout->setContentsMargins(3,0,3,0);
frameBlocksLayout->setSpacing(3);
labelEncryptionIcon = new QLabel();
labelStakingIcon = new QLabel();
labelConnectionsIcon = new QLabel();
labelBlocksIcon = new QLabel();
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelEncryptionIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelStakingIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelConnectionsIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelBlocksIcon);
frameBlocksLayout->addStretch();
if (GetBoolArg("-staking", true))
{
QTimer *timerStakingIcon = new QTimer(labelStakingIcon);
connect(timerStakingIcon, SIGNAL(timeout()), this, SLOT(updateStakingIcon()));
timerStakingIcon->start(30 * 1000);
updateStakingIcon();
}
// Progress bar and label for blocks download
progressBarLabel = new QLabel();
progressBarLabel->setVisible(false);
progressBar = new QProgressBar();
progressBar->setAlignment(Qt::AlignCenter);
progressBar->setVisible(false);
// Override style sheet for progress bar for styles that have a segmented progress bar,
// as they make the text unreadable (workaround for issue #1071)
// See https://qt-project.org/doc/qt-4.8/gallery.html
QString curStyle = qApp->style()->metaObject()->className();
if(curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle")
{
progressBar->setStyleSheet("QProgressBar { background-color: #e8e8e8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #FF8000, stop: 1 orange); border-radius: 7px; margin: 0px; }");
}
statusBar()->addWidget(progressBarLabel);
statusBar()->addWidget(progressBar);
statusBar()->addPermanentWidget(frameBlocks);
syncIconMovie = new QMovie(":/movies/update_spinner", "mng", this);
// Clicking on a transaction on the overview page simply sends you to transaction history page
connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), this, SLOT(gotoHistoryPage()));
connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex)));
// Double-clicking on a transaction on the transaction history page shows details
connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails()));
rpcConsole.reset(new RPCConsole);
connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole.data(), SLOT(show()));
// Clicking on "Verify Message" in the address book sends you to the verify message tab
connect(addressBookPage, SIGNAL(verifyMessage(QString)), this, SLOT(gotoVerifyMessageTab(QString)));
// Clicking on "Sign Message" in the receive coins page sends you to the sign message tab
connect(receiveCoinsPage, SIGNAL(signMessage(QString)), this, SLOT(gotoSignMessageTab(QString)));
gotoOverviewPage();
}
BitcoinGUI::~BitcoinGUI()
{
if(trayIcon) // Hide tray icon, as deleting will let it linger until quit (on Ubuntu)
trayIcon->hide();
#ifdef Q_OS_MAC
delete appMenuBar;
#endif
}
void BitcoinGUI::createActions()
{
QActionGroup *tabGroup = new QActionGroup(this);
overviewAction = new QAction(QIcon(":/icons/overview"), tr("&Overview"), this);
overviewAction->setToolTip(tr("Show general overview of wallet"));
overviewAction->setCheckable(true);
overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1));
tabGroup->addAction(overviewAction);
sendCoinsAction = new QAction(QIcon(":/icons/send"), tr("&Send coins"), this);
sendCoinsAction->setToolTip(tr("Send coins to a Yibitcoin address"));
sendCoinsAction->setCheckable(true);
sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2));
tabGroup->addAction(sendCoinsAction);
receiveCoinsAction = new QAction(QIcon(":/icons/receiving_addresses"), tr("&Receive coins"), this);
receiveCoinsAction->setToolTip(tr("Show the list of addresses for receiving payments"));
receiveCoinsAction->setCheckable(true);
receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3));
tabGroup->addAction(receiveCoinsAction);
historyAction = new QAction(QIcon(":/icons/history"), tr("&Transactions"), this);
historyAction->setToolTip(tr("Browse transaction history"));
historyAction->setCheckable(true);
historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4));
tabGroup->addAction(historyAction);
addressBookAction = new QAction(QIcon(":/icons/address-book"), tr("&Address Book"), this);
addressBookAction->setToolTip(tr("Edit the list of stored addresses and labels"));
addressBookAction->setCheckable(true);
addressBookAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_5));
tabGroup->addAction(addressBookAction);
connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage()));
connect(addressBookAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(addressBookAction, SIGNAL(triggered()), this, SLOT(gotoAddressBookPage()));
quitAction = new QAction(QIcon(":/icons/quit"), tr("E&xit"), this);
quitAction->setToolTip(tr("Quit application"));
quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
quitAction->setMenuRole(QAction::QuitRole);
aboutAction = new QAction(QIcon(":/icons/bitcoin"), tr("&About Yibitcoin"), this);
aboutAction->setToolTip(tr("Show information about Yibitcoin"));
aboutAction->setMenuRole(QAction::AboutRole);
aboutQtAction = new QAction(QIcon(":/trolltech/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this);
aboutQtAction->setToolTip(tr("Show information about Qt"));
aboutQtAction->setMenuRole(QAction::AboutQtRole);
optionsAction = new QAction(QIcon(":/icons/options"), tr("&Options..."), this);
optionsAction->setToolTip(tr("Modify configuration options for Yibitcoin"));
optionsAction->setMenuRole(QAction::PreferencesRole);
toggleHideAction = new QAction(QIcon(":/icons/bitcoin"), tr("&Show / Hide"), this);
encryptWalletAction = new QAction(QIcon(":/icons/lock_closed"), tr("&Encrypt Wallet..."), this);
encryptWalletAction->setToolTip(tr("Encrypt or decrypt wallet"));
encryptWalletAction->setCheckable(true);
backupWalletAction = new QAction(QIcon(":/icons/filesave"), tr("&Backup Wallet..."), this);
backupWalletAction->setToolTip(tr("Backup wallet to another location"));
changePassphraseAction = new QAction(QIcon(":/icons/key"), tr("&Change Passphrase..."), this);
changePassphraseAction->setToolTip(tr("Change the passphrase used for wallet encryption"));
unlockWalletAction = new QAction(QIcon(":/icons/lock_open"), tr("&Unlock Wallet..."), this);
unlockWalletAction->setToolTip(tr("Unlock wallet"));
lockWalletAction = new QAction(QIcon(":/icons/lock_closed"), tr("&Lock Wallet"), this);
lockWalletAction->setToolTip(tr("Lock wallet"));
signMessageAction = new QAction(QIcon(":/icons/edit"), tr("Sign &message..."), this);
verifyMessageAction = new QAction(QIcon(":/icons/transaction_0"), tr("&Verify message..."), this);
exportAction = new QAction(QIcon(":/icons/export"), tr("&Export..."), this);
exportAction->setToolTip(tr("Export the data in the current tab to a file"));
openRPCConsoleAction = new QAction(QIcon(":/icons/debugwindow"), tr("&Debug window"), this);
openRPCConsoleAction->setToolTip(tr("Open debugging and diagnostic console"));
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked()));
connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked()));
connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHidden()));
connect(encryptWalletAction, SIGNAL(triggered(bool)), this, SLOT(encryptWallet(bool)));
connect(backupWalletAction, SIGNAL(triggered()), this, SLOT(backupWallet()));
connect(changePassphraseAction, SIGNAL(triggered()), this, SLOT(changePassphrase()));
connect(unlockWalletAction, SIGNAL(triggered()), this, SLOT(unlockWallet()));
connect(lockWalletAction, SIGNAL(triggered()), this, SLOT(lockWallet()));
connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab()));
connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab()));
}
void BitcoinGUI::createMenuBar()
{
#ifdef Q_OS_MAC
// Create a decoupled menu bar on Mac which stays even if the window is closed
appMenuBar = new QMenuBar();
#else
// Get the main window's menu bar on other platforms
appMenuBar = menuBar();
#endif
//appMenuBar->setStyleSheet("QMenuBar::item { background-color: black; color: white }");
// Configure the menus
QMenu *file = appMenuBar->addMenu(tr("&File"));
file->addAction(backupWalletAction);
file->addAction(exportAction);
file->addAction(signMessageAction);
file->addAction(verifyMessageAction);
file->addSeparator();
file->addAction(quitAction);
QMenu *settings = appMenuBar->addMenu(tr("&Settings"));
settings->addAction(encryptWalletAction);
settings->addAction(changePassphraseAction);
settings->addAction(unlockWalletAction);
settings->addAction(lockWalletAction);
settings->addSeparator();
settings->addAction(optionsAction);
QMenu *help = appMenuBar->addMenu(tr("&Help"));
help->addAction(openRPCConsoleAction);
help->addSeparator();
help->addAction(aboutAction);
help->addAction(aboutQtAction);
}
void BitcoinGUI::createToolBars()
{
QToolBar *toolbar = addToolBar(tr("Tabs toolbar"));
toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
toolbar->addAction(overviewAction);
toolbar->addAction(sendCoinsAction);
toolbar->addAction(receiveCoinsAction);
toolbar->addAction(historyAction);
toolbar->addAction(addressBookAction);
toolbar->setMovable(false);
QToolBar *toolbar2 = addToolBar(tr("Actions toolbar"));
toolbar2->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
toolbar2->addAction(exportAction);
toolbar2->setMovable(false);
}
void BitcoinGUI::setClientModel(ClientModel *clientModel)
{
this->clientModel = clientModel;
if(clientModel)
{
// Replace some strings and icons, when using the testnet
if(clientModel->isTestNet())
{
setWindowTitle(windowTitle() + QString(" ") + tr("[testnet]"));
#ifndef Q_OS_MAC
qApp->setWindowIcon(QIcon(":icons/bitcoin_testnet"));
setWindowIcon(QIcon(":icons/bitcoin_testnet"));
#else
MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet"));
#endif
if(trayIcon)
{
trayIcon->setToolTip(tr("Yibitcoin client") + QString(" ") + tr("[testnet]"));
trayIcon->setIcon(QIcon(":/icons/toolbar_testnet"));
toggleHideAction->setIcon(QIcon(":/icons/toolbar_testnet"));
}
aboutAction->setIcon(QIcon(":/icons/toolbar_testnet"));
}
// Keep up to date with client
setNumConnections(clientModel->getNumConnections());
connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
setNumBlocks(clientModel->getNumBlocks(), clientModel->getNumBlocksOfPeers());
connect(clientModel, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int)));
// Report errors from network/worker thread
connect(clientModel, SIGNAL(error(QString,QString,bool)), this, SLOT(error(QString,QString,bool)));
rpcConsole->setClientModel(clientModel);
addressBookPage->setOptionsModel(clientModel->getOptionsModel());
receiveCoinsPage->setOptionsModel(clientModel->getOptionsModel());
}
}
void BitcoinGUI::setWalletModel(WalletModel *walletModel)
{
this->walletModel = walletModel;
if(walletModel)
{
// Report errors from wallet thread
connect(walletModel, SIGNAL(error(QString,QString,bool)), this, SLOT(error(QString,QString,bool)));
// Put transaction list in tabs
transactionView->setModel(walletModel);
overviewPage->setModel(walletModel);
addressBookPage->setModel(walletModel->getAddressTableModel());
receiveCoinsPage->setModel(walletModel->getAddressTableModel());
sendCoinsPage->setModel(walletModel);
signVerifyMessageDialog->setModel(walletModel);
setEncryptionStatus(walletModel->getEncryptionStatus());
connect(walletModel, SIGNAL(encryptionStatusChanged(int)), this, SLOT(setEncryptionStatus(int)));
// Balloon pop-up for new transaction
connect(walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),
this, SLOT(incomingTransaction(QModelIndex,int,int)));
// Ask for passphrase if needed
connect(walletModel, SIGNAL(requireUnlock()), this, SLOT(unlockWallet()));
}
}
void BitcoinGUI::createTrayIcon()
{
QMenu *trayIconMenu;
#ifndef Q_OS_MAC
trayIcon = new QSystemTrayIcon(this);
trayIconMenu = new QMenu(this);
trayIcon->setContextMenu(trayIconMenu);
trayIcon->setToolTip(tr("Yibitcoin client"));
trayIcon->setIcon(QIcon(":/icons/toolbar"));
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));
trayIcon->show();
#else
// Note: On Mac, the dock icon is used to provide the tray's functionality.
MacDockIconHandler *dockIconHandler = MacDockIconHandler::instance();
dockIconHandler->setMainWindow((QMainWindow *)this);
trayIconMenu = dockIconHandler->dockMenu();
#endif
// Configuration of the tray icon (or dock icon) icon menu
trayIconMenu->addAction(toggleHideAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(sendCoinsAction);
trayIconMenu->addAction(receiveCoinsAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(signMessageAction);
trayIconMenu->addAction(verifyMessageAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(optionsAction);
trayIconMenu->addAction(openRPCConsoleAction);
#ifndef Q_OS_MAC // This is built-in on Mac
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
#endif
notificator = new Notificator(qApp->applicationName(), trayIcon);
}
#ifndef Q_OS_MAC
void BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
if(reason == QSystemTrayIcon::Trigger)
{
// Click on system tray icon triggers show/hide of the main window
toggleHideAction->trigger();
}
}
#endif
void BitcoinGUI::optionsClicked()
{
if(!clientModel || !clientModel->getOptionsModel())
return;
OptionsDialog dlg;
dlg.setModel(clientModel->getOptionsModel());
dlg.exec();
}
void BitcoinGUI::aboutClicked()
{
AboutDialog dlg;
dlg.setModel(clientModel);
dlg.exec();
}
void BitcoinGUI::setNumConnections(int count)
{
QString icon;
switch(count)
{
case 0: icon = ":/icons/connect_0"; break;
case 1: case 2: case 3: icon = ":/icons/connect_1"; break;
case 4: case 5: case 6: icon = ":/icons/connect_2"; break;
case 7: case 8: case 9: icon = ":/icons/connect_3"; break;
default: icon = ":/icons/connect_4"; break;
}
labelConnectionsIcon->setPixmap(QIcon(icon).pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelConnectionsIcon->setToolTip(tr("%n active connection(s) to Yibitcoin network", "", count));
}
void BitcoinGUI::setNumBlocks(int count, int nTotalBlocks)
{
// don't show / hide progress bar and its label if we have no connection to the network
if (!clientModel || clientModel->getNumConnections() == 0)
{
progressBarLabel->setVisible(false);
progressBar->setVisible(false);
return;
}
QString strStatusBarWarnings = clientModel->getStatusBarWarnings();
QString tooltip;
if(count < nTotalBlocks)
{
int nRemainingBlocks = nTotalBlocks - count;
float nPercentageDone = count / (nTotalBlocks * 0.01f);
if (strStatusBarWarnings.isEmpty())
{
progressBarLabel->setText(tr("Synchronizing with network..."));
progressBarLabel->setVisible(true);
progressBar->setFormat(tr("~%n block(s) remaining", "", nRemainingBlocks));
progressBar->setMaximum(nTotalBlocks);
progressBar->setValue(count);
progressBar->setVisible(true);
}
tooltip = tr("Downloaded %1 of %2 blocks of transaction history (%3% done).").arg(count).arg(nTotalBlocks).arg(nPercentageDone, 0, 'f', 2);
}
else
{
if (strStatusBarWarnings.isEmpty())
progressBarLabel->setVisible(false);
progressBar->setVisible(false);
tooltip = tr("Downloaded %1 blocks of transaction history.").arg(count);
}
// Override progressBarLabel text and hide progress bar, when we have warnings to display
if (!strStatusBarWarnings.isEmpty())
{
progressBarLabel->setText(strStatusBarWarnings);
progressBarLabel->setVisible(true);
progressBar->setVisible(false);
}
QDateTime lastBlockDate = clientModel->getLastBlockDate();
int secs = lastBlockDate.secsTo(QDateTime::currentDateTime());
QString text;
// Represent time from last generated block in human readable text
if(secs <= 0)
{
// Fully up to date. Leave text empty.
}
else if(secs < 60)
{
text = tr("%n second(s) ago","",secs);
}
else if(secs < 60*60)
{
text = tr("%n minute(s) ago","",secs/60);
}
else if(secs < 24*60*60)
{
text = tr("%n hour(s) ago","",secs/(60*60));
}
else
{
text = tr("%n day(s) ago","",secs/(60*60*24));
}
// Set icon state: spinning if catching up, tick otherwise
if(secs < 90*60 && count >= nTotalBlocks)
{
tooltip = tr("Up to date") + QString(".<br>") + tooltip;
labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
overviewPage->showOutOfSyncWarning(false);
}
else
{
tooltip = tr("Catching up...") + QString("<br>") + tooltip;
labelBlocksIcon->setMovie(syncIconMovie);
syncIconMovie->start();
overviewPage->showOutOfSyncWarning(true);
}
if(!text.isEmpty())
{
tooltip += QString("<br>");
tooltip += tr("Last received block was generated %1.").arg(text);
}
// Don't word-wrap this (fixed-width) tooltip
tooltip = QString("<nobr>") + tooltip + QString("</nobr>");
labelBlocksIcon->setToolTip(tooltip);
progressBarLabel->setToolTip(tooltip);
progressBar->setToolTip(tooltip);
}
void BitcoinGUI::error(const QString &title, const QString &message, bool modal)
{
// Report errors from network/worker thread
if(modal)
{
QMessageBox::critical(this, title, message, QMessageBox::Ok, QMessageBox::Ok);
} else {
notificator->notify(Notificator::Critical, title, message);
}
}
void BitcoinGUI::changeEvent(QEvent *e)
{
QMainWindow::changeEvent(e);
#ifndef Q_OS_MAC // Ignored on Mac
if(e->type() == QEvent::WindowStateChange)
{
if(clientModel && clientModel->getOptionsModel()->getMinimizeToTray())
{
QWindowStateChangeEvent *wsevt = static_cast<QWindowStateChangeEvent*>(e);
if(!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized())
{
QTimer::singleShot(0, this, SLOT(hide()));
e->ignore();
}
}
}
#endif
}
void BitcoinGUI::closeEvent(QCloseEvent *event)
{
if(clientModel)
{
#ifndef Q_OS_MAC // Ignored on Mac
if(!clientModel->getOptionsModel()->getMinimizeToTray() &&
!clientModel->getOptionsModel()->getMinimizeOnClose())
{
qApp->quit();
}
#endif
}
QMainWindow::closeEvent(event);
}
void BitcoinGUI::askFee(qint64 nFeeRequired, bool *payFee)
{
QString strMessage =
tr("This transaction is over the size limit. You can still send it for a fee of %1, "
"which goes to the nodes that process your transaction and helps to support the network. "
"Do you want to pay the fee?").arg(
BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, nFeeRequired));
QMessageBox::StandardButton retval = QMessageBox::question(
this, tr("Confirm transaction fee"), strMessage,
QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Yes);
*payFee = (retval == QMessageBox::Yes);
}
void BitcoinGUI::incomingTransaction(const QModelIndex & parent, int start, int end)
{
if(!walletModel || !clientModel)
return;
TransactionTableModel *ttm = walletModel->getTransactionTableModel();
qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent)
.data(Qt::EditRole).toULongLong();
if(!clientModel->inInitialBlockDownload())
{
// On new transaction, make an info balloon
// Unless the initial block download is in progress, to prevent balloon-spam
QString date = ttm->index(start, TransactionTableModel::Date, parent)
.data().toString();
QString type = ttm->index(start, TransactionTableModel::Type, parent)
.data().toString();
QString address = ttm->index(start, TransactionTableModel::ToAddress, parent)
.data().toString();
QIcon icon = qvariant_cast<QIcon>(ttm->index(start,
TransactionTableModel::ToAddress, parent)
.data(Qt::DecorationRole));
notificator->notify(Notificator::Information,
(amount)<0 ? tr("Sent transaction") :
tr("Incoming transaction"),
tr("Date: %1\n"
"Amount: %2\n"
"Type: %3\n"
"Address: %4\n")
.arg(date)
.arg(BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), amount, true))
.arg(type)
.arg(address), icon);
}
}
void BitcoinGUI::gotoOverviewPage()
{
overviewAction->setChecked(true);
centralWidget->setCurrentWidget(overviewPage);
exportAction->setEnabled(false);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
}
void BitcoinGUI::gotoHistoryPage()
{
historyAction->setChecked(true);
centralWidget->setCurrentWidget(transactionsPage);
exportAction->setEnabled(true);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
connect(exportAction, SIGNAL(triggered()), transactionView, SLOT(exportClicked()));
}
void BitcoinGUI::gotoAddressBookPage()
{
addressBookAction->setChecked(true);
centralWidget->setCurrentWidget(addressBookPage);
exportAction->setEnabled(true);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
connect(exportAction, SIGNAL(triggered()), addressBookPage, SLOT(exportClicked()));
}
void BitcoinGUI::gotoReceiveCoinsPage()
{
receiveCoinsAction->setChecked(true);
centralWidget->setCurrentWidget(receiveCoinsPage);
exportAction->setEnabled(true);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
connect(exportAction, SIGNAL(triggered()), receiveCoinsPage, SLOT(exportClicked()));
}
void BitcoinGUI::gotoSendCoinsPage()
{
sendCoinsAction->setChecked(true);
centralWidget->setCurrentWidget(sendCoinsPage);
exportAction->setEnabled(false);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
}
void BitcoinGUI::gotoSignMessageTab(QString addr)
{
// call show() in showTab_SM()
signVerifyMessageDialog->showTab_SM(true);
if(!addr.isEmpty())
signVerifyMessageDialog->setAddress_SM(addr);
}
void BitcoinGUI::gotoVerifyMessageTab(QString addr)
{
// call show() in showTab_VM()
signVerifyMessageDialog->showTab_VM(true);
if(!addr.isEmpty())
signVerifyMessageDialog->setAddress_VM(addr);
}
void BitcoinGUI::dragEnterEvent(QDragEnterEvent *event)
{
// Accept only URIs
if(event->mimeData()->hasUrls())
event->acceptProposedAction();
}
void BitcoinGUI::dropEvent(QDropEvent *event)
{
if(event->mimeData()->hasUrls())
{
int nValidUrisFound = 0;
QList<QUrl> uris = event->mimeData()->urls();
foreach(const QUrl &uri, uris)
{
if (sendCoinsPage->handleURI(uri.toString()))
nValidUrisFound++;
}
// if valid URIs were found
if (nValidUrisFound)
gotoSendCoinsPage();
else
notificator->notify(Notificator::Warning, tr("URI handling"), tr("URI can not be parsed! This can be caused by an invalid Yibitcoin address or malformed URI parameters."));
}
event->acceptProposedAction();
}
void BitcoinGUI::handleURI(QString strURI)
{
// URI has to be valid
if (sendCoinsPage->handleURI(strURI))
{
showNormalIfMinimized();
gotoSendCoinsPage();
}
else
notificator->notify(Notificator::Warning, tr("URI handling"), tr("URI can not be parsed! This can be caused by an invalid Yibitcoin address or malformed URI parameters."));
}
void BitcoinGUI::setEncryptionStatus(int status)
{
switch(status)
{
case WalletModel::Unencrypted:
labelEncryptionIcon->hide();
encryptWalletAction->setChecked(false);
changePassphraseAction->setEnabled(false);
unlockWalletAction->setVisible(false);
lockWalletAction->setVisible(false);
encryptWalletAction->setEnabled(true);
break;
case WalletModel::Unlocked:
labelEncryptionIcon->show();
labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
unlockWalletAction->setVisible(false);
lockWalletAction->setVisible(true);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
case WalletModel::Locked:
labelEncryptionIcon->show();
labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_closed").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
unlockWalletAction->setVisible(true);
lockWalletAction->setVisible(false);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
}
}
void BitcoinGUI::encryptWallet(bool status)
{
if(!walletModel)
return;
AskPassphraseDialog dlg(status ? AskPassphraseDialog::Encrypt:
AskPassphraseDialog::Decrypt, this);
dlg.setModel(walletModel);
dlg.exec();
setEncryptionStatus(walletModel->getEncryptionStatus());
}
void BitcoinGUI::backupWallet()
{
QString saveDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
QString filename = QFileDialog::getSaveFileName(this, tr("Backup Wallet"), saveDir, tr("Wallet Data (*.dat)"));
if(!filename.isEmpty()) {
if(!walletModel->backupWallet(filename)) {
QMessageBox::warning(this, tr("Backup Failed"), tr("There was an error trying to save the wallet data to the new location."));
}
}
}
void BitcoinGUI::changePassphrase()
{
AskPassphraseDialog dlg(AskPassphraseDialog::ChangePass, this);
dlg.setModel(walletModel);
dlg.exec();
}
void BitcoinGUI::unlockWallet()
{
if(!walletModel)
return;
// Unlock wallet when requested by wallet model
if(walletModel->getEncryptionStatus() == WalletModel::Locked)
{
AskPassphraseDialog::Mode mode = sender() == unlockWalletAction ?
AskPassphraseDialog::UnlockStaking : AskPassphraseDialog::Unlock;
AskPassphraseDialog dlg(mode, this);
dlg.setModel(walletModel);
dlg.exec();
}
}
void BitcoinGUI::lockWallet()
{
if(!walletModel)
return;
walletModel->setWalletLocked(true);
}
void BitcoinGUI::showNormalIfMinimized(bool fToggleHidden)
{
// activateWindow() (sometimes) helps with keyboard focus on Windows
if (isHidden())
{
show();
activateWindow();
}
else if (isMinimized())
{
showNormal();
activateWindow();
}
else if (GUIUtil::isObscured(this))
{
raise();
activateWindow();
}
else if(fToggleHidden)
hide();
}
void BitcoinGUI::toggleHidden()
{
showNormalIfMinimized(true);
}
void BitcoinGUI::updateStakingIcon()
{
uint64_t nMinWeight = 0, nMaxWeight = 0, nWeight = 0;
if (pwalletMain)
pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight);
if (nLastCoinStakeSearchInterval && nWeight)
{
uint64_t nNetworkWeight = GetPoSKernelPS();
unsigned nEstimateTime = nTargetSpacing * nNetworkWeight / nWeight;
QString text;
if (nEstimateTime < 60)
{
text = tr("%n second(s)", "", nEstimateTime);
}
else if (nEstimateTime < 60*60)
{
text = tr("%n minute(s)", "", nEstimateTime/60);
}
else if (nEstimateTime < 24*60*60)
{
text = tr("%n hour(s)", "", nEstimateTime/(60*60));
}
else
{
text = tr("%n day(s)", "", nEstimateTime/(60*60*24));
}
labelStakingIcon->setPixmap(QIcon(":/icons/staking_on").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelStakingIcon->setToolTip(tr("Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3").arg(nWeight).arg(nNetworkWeight).arg(text));
}
else
{
labelStakingIcon->setPixmap(QIcon(":/icons/staking_off").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
if (pwalletMain && pwalletMain->IsLocked())
labelStakingIcon->setToolTip(tr("Not staking because wallet is locked"));
else if (vNodes.empty())
labelStakingIcon->setToolTip(tr("Not staking because wallet is offline"));
else if (IsInitialBlockDownload())
labelStakingIcon->setToolTip(tr("Not staking because wallet is syncing"));
else if (!nWeight)
labelStakingIcon->setToolTip(tr("Not staking because you don't have mature coins"));
else
labelStakingIcon->setToolTip(tr("Not staking"));
}
}
| [
"fuwenke@gmail.com"
] | fuwenke@gmail.com |
f825d0f5bc769efa6453944139d713eae2f4035e | 42b50020d2914500979fe0143dc7b60c94697c15 | /App1/Importer.cpp | a950ea497f93c919500f7c4fac7bbb11fb50a52d | [] | no_license | 999eagle/cga | 6eb2bff1f82ead9cfd20afd2009aeb6d33a19118 | 5d8786c46c049e0187001a9449901e60f742c42c | refs/heads/master | 2021-01-19T13:14:50.902182 | 2017-12-15T17:10:59 | 2017-12-15T17:10:59 | 88,075,815 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,108 | cpp | #include "pch.h"
#include "Importer.h"
#include "ECS\Components\ModelComponents.h"
#include "ECS\Entity.h"
#include "ECS\Components\TransformComponent.h"
std::shared_ptr<Texture> TextureImporter::LoadTexture(const std::string & path, aiTextureType type)
{
auto it = this->loadedTextures.find(path);
if (it != this->loadedTextures.end())
{
return it->second;
}
int width, height, channels;
unsigned char* image = SOIL_load_image(path.c_str(), &width, &height, &channels, SOIL_LOAD_RGB);
if (image == NULL)
{
std::cerr << "Error loading texture data from file " << path << std::endl;
return NULL;
}
auto newTexture = std::make_shared<Texture>();
newTexture->type = type;
glGenTextures(1, &newTexture->textureId);
glBindTexture(GL_TEXTURE_2D, newTexture->textureId);
GLint internalFormat = GL_COMPRESSED_RGB;
if (type == aiTextureType_DIFFUSE)
internalFormat = GL_COMPRESSED_SRGB;
glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
glGenerateMipmap(GL_TEXTURE_2D);
SOIL_free_image_data(image);
glBindTexture(GL_TEXTURE_2D, 0);
#ifdef _DEBUG
glObjectLabel(GL_TEXTURE, newTexture->textureId, -1, ("Texture: " + path).c_str());
#endif
this->loadedTextures.insert(std::make_pair(path, newTexture));
return newTexture;
}
TextureImporter::~TextureImporter()
{
for (auto it = this->loadedTextures.begin(); it != this->loadedTextures.end(); it++)
{
glDeleteTextures(1, &(it->second->textureId));
}
}
std::shared_ptr<Material> MaterialImporter::LoadMaterial(const std::string & albedoMapPath, const std::string & normalMapPath, const std::string & metallicMapPath, const std::string & roughnessMapPath)
{
std::vector<std::shared_ptr<Texture>> textures;
if (albedoMapPath != "")
{
textures.push_back(TextureImporter::GetInstance().LoadTexture(albedoMapPath, aiTextureType_DIFFUSE));
}
if (normalMapPath != "")
{
textures.push_back(TextureImporter::GetInstance().LoadTexture(normalMapPath, aiTextureType_NORMALS));
}
if (metallicMapPath != "")
{
textures.push_back(TextureImporter::GetInstance().LoadTexture(metallicMapPath, aiTextureType_SPECULAR));
}
if (roughnessMapPath != "")
{
textures.push_back(TextureImporter::GetInstance().LoadTexture(roughnessMapPath, aiTextureType_SHININESS));
}
return std::make_shared<Material>(textures);
}
std::shared_ptr<Material> MaterialImporter::LoadMaterial(const std::string & materialPath)
{
auto it = this->loadedMaterials.find(materialPath);
if (it != this->loadedMaterials.end())
{
return it->second;
}
std::string directory = materialPath.substr(0, materialPath.find_last_of("\\/") + 1);
std::fstream matFile;
matFile.open(materialPath, std::fstream::in);
std::string mat;
std::vector<std::shared_ptr<Texture>> textures;
while (std::getline(matFile, mat))
{
auto spaceIdx = mat.find(" ");
auto key = mat.substr(0, spaceIdx);
auto value = mat.substr(spaceIdx + 1);
if (key == "map_albedo") textures.push_back(TextureImporter::GetInstance().LoadTexture(directory + value, aiTextureType_DIFFUSE));
else if (key == "map_normal") textures.push_back(TextureImporter::GetInstance().LoadTexture(directory + value, aiTextureType_NORMALS));
else if (key == "map_metallic") textures.push_back(TextureImporter::GetInstance().LoadTexture(directory + value, aiTextureType_SPECULAR));
else if (key == "map_roughness") textures.push_back(TextureImporter::GetInstance().LoadTexture(directory + value, aiTextureType_SHININESS));
else std::cerr << "Unknown key " << key << " in material " << materialPath << "!" << std::endl;
}
auto newMat = std::make_shared<Material>(textures);
this->loadedMaterials.insert(std::make_pair(materialPath, newMat));
return newMat;
}
ECS::Entity * ModelImporter::LoadModel(ECS::World * world, const std::string & path)
{
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(path,
aiProcess_Triangulate |
aiProcess_FindInvalidData |
aiProcess_GenUVCoords |
aiProcess_JoinIdenticalVertices |
aiProcess_CalcTangentSpace |
aiProcess_GenSmoothNormals |
aiProcess_OptimizeMeshes |
aiProcess_FlipUVs);
if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode)
{
std::cerr << "Import error in file " << path << ": " << importer.GetErrorString() << std::endl;
return NULL;
}
std::string directory = path.substr(0, path.find_last_of("\\/") + 1);
std::string name = path;
return this->ProcessNode(world, scene->mRootNode, scene, directory, name);
}
ECS::Entity * ModelImporter::ProcessNode(ECS::World * world, const aiNode * node, const aiScene * scene, const std::string & directory, const std::string & name)
{
auto entity = new ECS::Entity();
world->AddEntity(entity);
auto transform = entity->GetComponent<ECS::Components::TransformComponent>();
transform->SetLocalTransform(glm::transpose(glm::make_mat4(&(node->mTransformation.a1))));
if (node->mNumMeshes == 1)
{
this->ProcessMesh(entity, scene->mMeshes[node->mMeshes[0]], scene, directory, name);
}
else
{
for (uint32_t i = 0; i < node->mNumMeshes; i++)
{
auto childEntity = new ECS::Entity();
world->AddEntity(childEntity);
childEntity->GetComponent<ECS::Components::TransformComponent>()->SetParent(transform);
this->ProcessMesh(childEntity, scene->mMeshes[node->mMeshes[i]], scene, directory, name);
}
}
for (uint32_t i = 0; i < node->mNumChildren; i++)
{
auto child = this->ProcessNode(world, node->mChildren[i], scene, directory, name);
child->GetComponent<ECS::Components::TransformComponent>()->SetParent(transform);
}
return entity;
}
void ModelImporter::ProcessMesh(ECS::Entity * entity, const aiMesh * mesh, const aiScene * scene, const std::string & directory, const std::string & name)
{
std::vector<VertexType> vertices;
std::vector<GLuint> indices;
std::vector<std::shared_ptr<Texture>> textures;
for (uint32_t i = 0; i < mesh->mNumVertices; i++)
{
VertexType vertex;
vertex.position.x = mesh->mVertices[i].x;
vertex.position.y = mesh->mVertices[i].y;
vertex.position.z = mesh->mVertices[i].z;
if (mesh->mTextureCoords[0])
{
vertex.texCoord.x = mesh->mTextureCoords[0][i].x;
vertex.texCoord.y = mesh->mTextureCoords[0][i].y;
}
vertex.normal.x = mesh->mNormals[i].x;
vertex.normal.y = mesh->mNormals[i].y;
vertex.normal.z = mesh->mNormals[i].z;
vertex.tangent.x = mesh->mTangents[i].x;
vertex.tangent.y = mesh->mTangents[i].y;
vertex.tangent.z = mesh->mTangents[i].z;
vertex.bitangent.x = mesh->mBitangents[i].x;
vertex.bitangent.y = mesh->mBitangents[i].y;
vertex.bitangent.z = mesh->mBitangents[i].z;
if (glm::dot(glm::cross(vertex.normal, vertex.tangent), vertex.bitangent) < 0)
{
vertex.tangent *= -1.0;
}
vertices.push_back(vertex);
}
for (uint32_t i = 0; i < mesh->mNumFaces; i++)
{
aiFace face = mesh->mFaces[i];
indices.push_back(face.mIndices[0]);
indices.push_back(face.mIndices[1]);
indices.push_back(face.mIndices[2]);
}
aiMaterial * mat = scene->mMaterials[mesh->mMaterialIndex];
// load referenced textures
this->LoadTextures(textures, mat, aiTextureType_DIFFUSE, directory);
this->LoadTextures(textures, mat, aiTextureType_NORMALS, directory);
this->LoadTextures(textures, mat, aiTextureType_HEIGHT, directory);
this->LoadTextures(textures, mat, aiTextureType_SPECULAR, directory);
this->LoadTextures(textures, mat, aiTextureType_SHININESS, directory);
auto newMesh = std::make_shared<Mesh<VertexType>>(vertices, indices, name + "\\" + mesh->mName.C_Str());
auto material = std::make_shared<Material>(textures);
entity->AddComponent<ECS::Components::MeshComponent<VertexType>>(newMesh);
entity->AddComponent<ECS::Components::MaterialComponent>(material);
}
void ModelImporter::LoadTextures(std::vector<std::shared_ptr<Texture>> & textures, const aiMaterial * material, aiTextureType type, const std::string & directory)
{
for (uint32_t i = 0; i < material->GetTextureCount(type); i++)
{
aiString path;
material->GetTexture(type, i, &path);
textures.push_back(TextureImporter::GetInstance().LoadTexture(directory + std::string(path.C_Str()), type));
}
}
| [
"erik@tauchert.de"
] | erik@tauchert.de |
8a33807f63d12bfaa95fa746d37739ad6df05367 | e6cee4e15faf09d3e976b80845d985cb171d1f07 | /AddLanguage/AddLanguage/components/imgdecoder-gdip/imgdecoder-gdip.cpp | d0525bb0bd7e79777030b7d9cb736e877b7daa20 | [
"MIT"
] | permissive | yangchaoqin/addlanguage | d272bb6faf4138783b245ef682154897605d72d7 | 80a8580caa766424fd61e59de5276f96ae9d47b6 | refs/heads/master | 2022-11-26T08:29:52.075178 | 2020-08-06T11:53:21 | 2020-08-06T11:53:21 | 284,695,423 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,788 | cpp | // imgdecoder-gdip.cpp : Defines the exported functions for the DLL application.
//
#include <Windows.h>
#include <GdiPlus.h>
#pragma comment(lib,"gdiplus")
#include "imgdecoder-gdip.h"
#include <interface/render-i.h>
using namespace Gdiplus;
namespace SOUI
{
//////////////////////////////////////////////////////////////////////////
// SImgFrame_PNG
SImgFrame_GDIP::SImgFrame_GDIP()
:m_pdata(NULL)
,m_nWid(0)
,m_nHei(0)
,m_nFrameDelay(0)
{
}
SImgFrame_GDIP::~SImgFrame_GDIP()
{
if(m_pdata) delete []m_pdata;
}
void SImgFrame_GDIP::Attach( const BYTE * pdata,int nWid,int nHei,int nDelay )
{
int bufSize = nWid*nHei*4;
m_pdata=new BYTE[bufSize];
BYTE *pDst = m_pdata;
const BYTE *pSrc = pdata;
int pixel_count = nWid * nHei;
for (int i=0; i < pixel_count; ++i) {
BYTE a = pSrc[3];
if (a)
{
pDst[0] = (pSrc[0] *a)/255;
pDst[1] = (pSrc[1] *a)/255;
pDst[2] = (pSrc[2] *a)/255;
pDst[3] = a;
}else
{
memset(pDst,0,4);
}
pDst += 4;
pSrc += 4;
}
m_nWid=(nWid);
m_nHei=(nHei);
m_nFrameDelay=(nDelay);
}
BOOL SImgFrame_GDIP::GetSize( UINT *pWid,UINT *pHei )
{
if(!m_pdata) return FALSE;
*pWid = m_nWid;
*pHei = m_nHei;
return TRUE;
}
BOOL SImgFrame_GDIP::CopyPixels(const RECT *prc,UINT cbStride, UINT cbBufferSize, BYTE *pbBuffer )
{
if(!m_pdata || cbBufferSize != m_nHei * m_nWid *4) return FALSE;
memcpy(pbBuffer,m_pdata,cbBufferSize);
return TRUE;
}
//////////////////////////////////////////////////////////////////////////
// SImgX_PNG
int SImgX_GDIP::LoadFromMemory( void *pBuf,size_t bufLen )
{
HGLOBAL hMem = ::GlobalAlloc(GMEM_FIXED, bufLen);
BYTE* pMem = (BYTE*)::GlobalLock(hMem);
memcpy(pMem,pBuf,bufLen);
IStream* pStm = NULL;
::CreateStreamOnHGlobal(hMem, TRUE, &pStm);
Bitmap * bmpSrc= new Bitmap(pStm);
pStm->Release();
::GlobalUnlock(hMem);
if (!bmpSrc) return 0;
int nRet = _InitFromGdipBitmap(bmpSrc);
delete bmpSrc;
return nRet;
}
int SImgX_GDIP::LoadFromFile( LPCWSTR pszFileName )
{
Bitmap * bmpSrc= new Bitmap(pszFileName);
if (!bmpSrc) return 0;
int nRet = _InitFromGdipBitmap(bmpSrc);
delete bmpSrc;
return nRet;
}
int SImgX_GDIP::LoadFromFile( LPCSTR pszFileName )
{
wchar_t wszFileName[MAX_PATH+1];
MultiByteToWideChar(CP_ACP,0,pszFileName,-1,wszFileName,MAX_PATH);
if(GetLastError()==ERROR_INSUFFICIENT_BUFFER) return 0;
return LoadFromFile(wszFileName);
}
SImgX_GDIP::SImgX_GDIP( BOOL bPremultiplied )
:m_bPremultiplied(bPremultiplied)
,m_pImgArray(NULL)
,m_nFrameCount(0)
{
}
SImgX_GDIP::~SImgX_GDIP( void )
{
if(m_pImgArray) delete []m_pImgArray;
}
UINT SImgX_GDIP::GetFrameCount()
{
return m_nFrameCount;
}
int SImgX_GDIP::_InitFromGdipBitmap(Bitmap * bmpSrc)
{
GUID pageGuid = FrameDimensionTime;
// Get the number of frames in the first dimension.
m_nFrameCount = max(1, bmpSrc->GetFrameCount(&pageGuid));
SIZE imSize={bmpSrc->GetWidth(),bmpSrc->GetHeight()};
if (m_nFrameCount>1)
{
m_pImgArray=new SImgFrame_GDIP[m_nFrameCount];
int nSize = bmpSrc->GetPropertyItemSize(PropertyTagFrameDelay);
// Allocate a buffer to receive the property item.
PropertyItem* pDelays = (PropertyItem*) new char[nSize];
bmpSrc->GetPropertyItem(PropertyTagFrameDelay, nSize, pDelays);
Bitmap *bmp = new Bitmap(imSize.cx,imSize.cy,PixelFormat32bppARGB);
for (int i=0; i<m_nFrameCount; i++)
{
GUID pageGuid = FrameDimensionTime;
bmpSrc->SelectActiveFrame(&pageGuid, i);
Graphics g(bmp);
g.Clear(Color(0,0,0,0));
g.DrawImage(bmpSrc,0,0,imSize.cx,imSize.cy);
int nFrameDelay =10*max(((int*) pDelays->value)[i], 10);
BitmapData* bitmapData = new BitmapData;
Rect rect(0,0, imSize.cx,imSize.cy);
bmp->LockBits(
&rect,
ImageLockModeRead,
PixelFormat32bppARGB,
bitmapData);
m_pImgArray[i].Attach((BYTE*)bitmapData->Scan0,imSize.cx,imSize.cy,nFrameDelay);
bmp->UnlockBits(bitmapData);
delete bitmapData;
}
delete bmp;
delete [] pDelays;
}
else
{
m_pImgArray = new SImgFrame_GDIP[1];
BitmapData* bitmapData = new BitmapData;
Rect rect(0,0, imSize.cx,imSize.cy);
bmpSrc->LockBits(
&rect,
ImageLockModeRead,
PixelFormat32bppARGB,
bitmapData);
m_pImgArray[0].Attach((BYTE*)bitmapData->Scan0,imSize.cx,imSize.cy,0);
bmpSrc->UnlockBits(bitmapData);
delete bitmapData;
}
return m_nFrameCount;
}
//////////////////////////////////////////////////////////////////////////
// SImgDecoderFactory_PNG
SImgDecoderFactory_GDIP::SImgDecoderFactory_GDIP( )
{
GdiplusStartupInput gdiplusStartupInput;
BOOL bOK = Ok == GdiplusStartup(&_gdiPlusToken, &gdiplusStartupInput, NULL);
if(!bOK)
{
SASSERT(0);
}
}
SImgDecoderFactory_GDIP::~SImgDecoderFactory_GDIP()
{
if (_gdiPlusToken != 0)
{
GdiplusShutdown(_gdiPlusToken);
_gdiPlusToken = 0;
}
}
BOOL SImgDecoderFactory_GDIP::CreateImgX( IImgX **ppImgDecoder )
{
*ppImgDecoder = new SImgX_GDIP(TRUE);
return TRUE;
}
CLSID FindCodecForFileType( REFGUID guidFileType, const Gdiplus::ImageCodecInfo* pCodecs, UINT nCodecs )
{
for( UINT iCodec = 0; iCodec < nCodecs; iCodec++ )
{
if( pCodecs[iCodec].FormatID == guidFileType )
{
return( pCodecs[iCodec].Clsid );
}
}
return( CLSID_NULL );
}
HRESULT SImgDecoderFactory_GDIP::SaveImage(IBitmap *pImg, LPCWSTR pszFileName,const LPVOID pFormat)
{
const GUID * pFmtID = (const GUID*)pFormat;
UINT nEncoders;
UINT nBytes;
Gdiplus::Status status;
status = Gdiplus::GetImageEncodersSize( &nEncoders, &nBytes );
if( status != Gdiplus::Ok )
{
return( E_FAIL );
}
//USES_ATL_SAFE_ALLOCA;
Gdiplus::ImageCodecInfo* pEncoders = static_cast< Gdiplus::ImageCodecInfo* >( malloc(nBytes) );
if( pEncoders == NULL )
return E_OUTOFMEMORY;
status = Gdiplus::GetImageEncoders( nEncoders, nBytes, pEncoders );
if( status != Gdiplus::Ok )
{
free(pEncoders);
return( E_FAIL );
}
CLSID clsidEncoder = FindCodecForFileType( *pFmtID, pEncoders, nEncoders );
free(pEncoders);
if( clsidEncoder == CLSID_NULL )
{
return( E_FAIL );
}
LPVOID pBits = pImg->LockPixelBits();
Bitmap bmp(pImg->Width(),pImg->Height(),pImg->Width()*4,PixelFormat32bppPARGB,(BYTE*)pBits);
pImg->UnlockPixelBits(pBits);
Image *gdipImg = &bmp;
return Ok == gdipImg->Save(pszFileName,&clsidEncoder)?S_OK:E_FAIL;
}
LPCWSTR SImgDecoderFactory_GDIP::GetDescription() const
{
return DESC_IMGDECODER;
}
//////////////////////////////////////////////////////////////////////////
namespace IMGDECODOR_GDIP
{
BOOL SCreateInstance( IObjRef **pImgDecoderFactory )
{
*pImgDecoderFactory = new SImgDecoderFactory_GDIP();
return TRUE;
}
}
}//end of namespace SOUI
| [
"charlieyang@futunn.com"
] | charlieyang@futunn.com |
03fb76dd51806ed8d941ce7c7895dd856a0b7e8d | cdf3684363161efee732ba1eacb5cabe574b41ca | /AllJoyn.Lamp.Sample/AllJoyn.Lamp.WinRuntime/LampDetailsProducer.h | 578336f6073db1ccac85f09af17e0eda65f19849 | [
"Apache-2.0"
] | permissive | sgrebnov/ajn-sample-win10 | a25efebdb8e5fbb5c9289fd20e7da4bdbd77e3d9 | 13d9ba404006794fc94ff2dd5d7c5985d20242f9 | refs/heads/master | 2021-01-10T04:17:27.194731 | 2015-08-27T07:15:56 | 2015-08-27T07:15:56 | 36,291,279 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,350 | h | //-----------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//
// Tool: AllJoynCodeGen.exe
// Version: 1.0.0
//
// This tool is located in the Windows 10 SDK and the Windows 10 AllJoyn
// Visual Studio Extension in the Visual Studio Extension Gallery.
//
// The generated code should be packaged in a Windows 10 C++/CX Runtime
// Component which can be consumed in any UAP-supported language using
// APIs that are available in Windows.Devices.AllJoyn.
//
// Using AllJoynCodeGen - Invoke the following command with a valid
// Introspection XML file:
// AllJoynCodeGen -i <INPUT XML FILE> -o <OUTPUT DIRECTORY>
// </auto-generated>
//-----------------------------------------------------------------------------
#pragma once
namespace org { namespace allseen { namespace LSF {
extern PCSTR c_LampDetailsIntrospectionXml;
ref class LampDetailsProducer;
public interface class ILampDetailsProducer
{
event Windows::Foundation::TypedEventHandler<LampDetailsProducer^, Windows::Devices::AllJoyn::AllJoynProducerStoppedEventArgs^>^ Stopped;
event Windows::Foundation::TypedEventHandler<LampDetailsProducer^, Windows::Devices::AllJoyn::AllJoynSessionLostEventArgs^>^ SessionLost;
event Windows::Foundation::TypedEventHandler<LampDetailsProducer^, Windows::Devices::AllJoyn::AllJoynSessionMemberAddedEventArgs^>^ SessionMemberAdded;
event Windows::Foundation::TypedEventHandler<LampDetailsProducer^, Windows::Devices::AllJoyn::AllJoynSessionMemberRemovedEventArgs^>^ SessionMemberRemoved;
};
public ref class LampDetailsProducer sealed : [Windows::Foundation::Metadata::Default] ILampDetailsProducer
{
public:
LampDetailsProducer(Windows::Devices::AllJoyn::AllJoynBusAttachment^ busAttachment);
virtual ~LampDetailsProducer();
// The implementation of ILampDetailsService that will handle method calls and property requests.
property ILampDetailsService^ Service
{
ILampDetailsService^ get() { return m_serviceInterface; }
void set(ILampDetailsService^ value) { m_serviceInterface = value; }
}
// Used to send signals or register functions to handle received signals.
property LampDetailsSignals^ Signals
{
LampDetailsSignals^ get() { return m_signals; }
}
// This event will fire whenever this producer is stopped.
virtual event Windows::Foundation::TypedEventHandler<LampDetailsProducer^, Windows::Devices::AllJoyn::AllJoynProducerStoppedEventArgs^>^ Stopped;
// This event will fire whenever the producer loses the session that it created.
virtual event Windows::Foundation::TypedEventHandler<LampDetailsProducer^, Windows::Devices::AllJoyn::AllJoynSessionLostEventArgs^>^ SessionLost;
// This event will fire whenever a member joins the session.
virtual event Windows::Foundation::TypedEventHandler<LampDetailsProducer^, Windows::Devices::AllJoyn::AllJoynSessionMemberAddedEventArgs^>^ SessionMemberAdded;
// This event will fire whenever a member leaves the session.
virtual event Windows::Foundation::TypedEventHandler<LampDetailsProducer^, Windows::Devices::AllJoyn::AllJoynSessionMemberRemovedEventArgs^>^ SessionMemberRemoved;
// Start advertising the service.
void Start();
// Stop advertising the service.
void Stop();
// Remove a member that has joined this session.
int32 RemoveMemberFromSession(_In_ Platform::String^ uniqueName);
internal:
bool OnAcceptSessionJoiner(_In_ alljoyn_sessionport sessionPort, _In_ PCSTR joiner, _In_ const alljoyn_sessionopts opts);
void OnSessionJoined(_In_ alljoyn_sessionport sessionPort, _In_ alljoyn_sessionid id, _In_ PCSTR joiner);
QStatus OnPropertyGet(_In_ PCSTR interfaceName, _In_ PCSTR propertyName, _Inout_ alljoyn_msgarg val);
QStatus OnPropertySet(_In_ PCSTR interfaceName, _In_ PCSTR propertyName, _In_ alljoyn_msgarg val);
void OnSessionLost(_In_ alljoyn_sessionid sessionId, _In_ alljoyn_sessionlostreason reason);
void OnSessionMemberAdded(_In_ alljoyn_sessionid sessionId, _In_ PCSTR uniqueName);
void OnSessionMemberRemoved(_In_ alljoyn_sessionid sessionId, _In_ PCSTR uniqueName);
property Platform::String^ ServiceObjectPath
{
Platform::String^ get() { return m_ServiceObjectPath; }
void set(Platform::String^ value) { m_ServiceObjectPath = value; }
}
property alljoyn_busobject BusObject
{
alljoyn_busobject get() { return m_busObject; }
void set(alljoyn_busobject value) { m_busObject = value; }
}
property alljoyn_sessionportlistener SessionPortListener
{
alljoyn_sessionportlistener get() { return m_sessionPortListener; }
void set(alljoyn_sessionportlistener value) { m_sessionPortListener = value; }
}
property alljoyn_sessionlistener SessionListener
{
alljoyn_sessionlistener get() { return m_sessionListener; }
void set(alljoyn_sessionlistener value) { m_sessionListener = value; }
}
property alljoyn_sessionport SessionPort
{
alljoyn_sessionport get() { return m_sessionPort; }
internal:
void set(alljoyn_sessionport value) { m_sessionPort = value; }
}
property alljoyn_sessionid SessionId
{
alljoyn_sessionid get() { return m_sessionId; }
}
// Stop advertising the service and pass status to anyone listening for the Stopped event.
void StopInternal(int32 status);
void BusAttachmentStateChanged(_In_ Windows::Devices::AllJoyn::AllJoynBusAttachment^ sender, _In_ Windows::Devices::AllJoyn::AllJoynBusAttachmentStateChangedEventArgs^ args);
private:
// Register a callback function to handle methods.
QStatus AddMethodHandler(_In_ alljoyn_interfacedescription interfaceDescription, _In_ PCSTR methodName, _In_ alljoyn_messagereceiver_methodhandler_ptr handler);
// Register a callback function to handle incoming signals.
QStatus AddSignalHandler(_In_ alljoyn_busattachment busAttachment, _In_ alljoyn_interfacedescription interfaceDescription, _In_ PCSTR methodName, _In_ alljoyn_messagereceiver_signalhandler_ptr handler);
void UnregisterFromBus();
Windows::Devices::AllJoyn::AllJoynBusAttachment^ m_busAttachment;
Windows::Foundation::EventRegistrationToken m_busAttachmentStateChangedToken;
LampDetailsSignals^ m_signals;
ILampDetailsService^ m_serviceInterface;
Platform::String^ m_ServiceObjectPath;
alljoyn_busobject m_busObject;
alljoyn_sessionportlistener m_sessionPortListener;
alljoyn_sessionlistener m_sessionListener;
alljoyn_sessionport m_sessionPort;
alljoyn_sessionid m_sessionId;
// Used to pass a pointer to this class to callbacks
Platform::WeakReference* m_weak;
// These maps are required because we need a way to pass the producer to the method
// and signal handlers, but the current AllJoyn C API does not allow passing a context to these
// callbacks.
static std::map<alljoyn_busobject, Platform::WeakReference*> SourceObjects;
static std::map<alljoyn_interfacedescription, Platform::WeakReference*> SourceInterfaces;
};
} } }
| [
"v-segreb@microsoft.com"
] | v-segreb@microsoft.com |
ed1cd7f43ac7fe5c18c88daca2feb4e3da4021dd | ef23e388061a637f82b815d32f7af8cb60c5bb1f | /src/mess/includes/ti85.h | 9d0676664f9afd198e672198329096d5bf1c9551 | [] | no_license | marcellodash/psmame | 76fd877a210d50d34f23e50d338e65a17deff066 | 09f52313bd3b06311b910ed67a0e7c70c2dd2535 | refs/heads/master | 2021-05-29T23:57:23.333706 | 2011-06-23T20:11:22 | 2011-06-23T20:11:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,499 | h | /*****************************************************************************
*
* includes/ti85.h
*
****************************************************************************/
#ifndef TI85_H_
#define TI85_H_
#include "imagedev/snapquik.h"
class ti85_state : public driver_device
{
public:
ti85_state(running_machine &machine, const driver_device_config_base &config)
: driver_device(machine, config),
m_nvram(*this, "nvram") { }
optional_shared_ptr<UINT8> m_nvram;
UINT8 m_LCD_memory_base;
UINT8 m_LCD_contrast;
UINT8 m_LCD_status;
UINT8 m_timer_interrupt_mask;
UINT8 m_ti82_video_buffer[0x300];
UINT8 m_ti_calculator_model;
UINT8 m_timer_interrupt_status;
UINT8 m_ON_interrupt_mask;
UINT8 m_ON_interrupt_status;
UINT8 m_ON_pressed;
UINT8 m_ti8x_memory_page_1;
UINT8 m_ti8x_memory_page_2;
UINT8 m_LCD_mask;
UINT8 m_power_mode;
UINT8 m_keypad_mask;
UINT8 m_video_buffer_width;
UINT8 m_interrupt_speed;
UINT8 m_port4_bit0;
UINT8 m_ti81_port_7_data;
UINT8 *m_ti8x_ram;
UINT8 m_PCR;
UINT8 m_red_out;
UINT8 m_white_out;
UINT8 m_ti82_video_mode;
UINT8 m_ti82_video_x;
UINT8 m_ti82_video_y;
UINT8 m_ti82_video_dir;
UINT8 m_ti82_video_scroll;
UINT8 m_ti82_video_bit;
UINT8 m_ti82_video_col;
UINT8 m_ti8x_port2;
UINT8 m_ti83p_port4;
int m_ti_video_memory_size;
int m_ti_screen_x_size;
int m_ti_screen_y_size;
int m_ti_number_of_frames;
UINT8 * m_frames;
};
/*----------- defined in machine/ti85.c -----------*/
MACHINE_START( ti81 );
MACHINE_START( ti82 );
MACHINE_START( ti85 );
MACHINE_START( ti83p );
MACHINE_START( ti86 );
MACHINE_RESET( ti85 );
NVRAM_HANDLER( ti83p );
NVRAM_HANDLER( ti86 );
SNAPSHOT_LOAD( ti8x );
WRITE8_HANDLER( ti81_port_0007_w );
READ8_HANDLER( ti85_port_0000_r );
READ8_HANDLER( ti8x_keypad_r );
READ8_HANDLER( ti85_port_0002_r );
READ8_HANDLER( ti85_port_0003_r );
READ8_HANDLER( ti85_port_0004_r );
READ8_HANDLER( ti85_port_0005_r );
READ8_HANDLER( ti85_port_0006_r );
READ8_HANDLER( ti85_port_0007_r );
READ8_HANDLER( ti86_port_0005_r );
READ8_HANDLER( ti86_port_0006_r );
READ8_HANDLER( ti82_port_0000_r );
READ8_HANDLER( ti82_port_0002_r );
READ8_HANDLER( ti82_port_0010_r );
READ8_HANDLER( ti82_port_0011_r );
READ8_HANDLER( ti83_port_0000_r );
READ8_HANDLER( ti83_port_0002_r );
READ8_HANDLER( ti83_port_0003_r );
READ8_HANDLER( ti73_port_0000_r );
READ8_HANDLER( ti83p_port_0000_r );
READ8_HANDLER( ti83p_port_0002_r );
WRITE8_HANDLER( ti85_port_0000_w );
WRITE8_HANDLER( ti8x_keypad_w );
WRITE8_HANDLER( ti85_port_0002_w );
WRITE8_HANDLER( ti85_port_0003_w );
WRITE8_HANDLER( ti85_port_0004_w );
WRITE8_HANDLER( ti85_port_0005_w );
WRITE8_HANDLER( ti85_port_0006_w );
WRITE8_HANDLER( ti85_port_0007_w );
WRITE8_HANDLER( ti86_port_0005_w );
WRITE8_HANDLER( ti86_port_0006_w );
WRITE8_HANDLER( ti82_port_0000_w );
WRITE8_HANDLER( ti82_port_0002_w );
WRITE8_HANDLER( ti82_port_0010_w );
WRITE8_HANDLER( ti82_port_0011_w );
WRITE8_HANDLER( ti83_port_0000_w );
WRITE8_HANDLER( ti83_port_0002_w );
WRITE8_HANDLER( ti83_port_0003_w );
WRITE8_HANDLER( ti73_port_0000_w );
WRITE8_HANDLER( ti83p_port_0000_w );
WRITE8_HANDLER( ti83p_port_0002_w );
WRITE8_HANDLER( ti83p_port_0003_w );
WRITE8_HANDLER( ti83p_port_0004_w );
WRITE8_HANDLER( ti83p_port_0006_w );
WRITE8_HANDLER( ti83p_port_0007_w );
WRITE8_HANDLER( ti83p_port_0010_w );
/*----------- defined in video/ti85.c -----------*/
VIDEO_START( ti85 );
SCREEN_UPDATE( ti85 );
SCREEN_UPDATE( ti82 );
PALETTE_INIT( ti85 );
#endif /* TI85_H_ */
| [
"Mike@localhost"
] | Mike@localhost |
a82cda7c37b5386866acd89b16f4d8041a8e6119 | bbbc505ddebcc710c0cbf7143d360b492a7af452 | /zerojudge/AC/c124.cpp | 97dd3fe1b4c48b7ae8d04509b237826e0bf57d79 | [] | no_license | mandy840907/cpp | 25efb95b181775042a3aee9acaac04a1a9746233 | 793414c2af24b78cbfafff8c738eb5d83c610570 | refs/heads/master | 2020-05-29T17:07:54.273693 | 2020-04-08T04:45:29 | 2020-04-08T04:45:29 | 54,814,842 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,736 | cpp | #include <iostream>
#include <queue>
using namespace std;
struct Point {
int i, j, k, step;
};
void debugPoint(Point p)
{
cout << "(" << p.i << ", " << p.j << ", " << p.k << ") " << p.step << " ";
}
int main()
{
int L, R, C;
string castle[30][30];
int step[30][30][30];
while(cin >> L >> R >> C)
{
Point start;
queue<Point> myqueue;
if(L + R + C == 0)
break;
for(int i = 0; i < L; i++)
{
for(int j = 0; j < R; j++)
{
cin >> castle[i][j];
for(int k = 0; k < C; k++)
{
step[i][j][k] = -1;
if(castle[i][j][k] == 'S')
{
start.i = i;
start.j = j;
start.k = k;
start.step = 0;
}
}
}
}
// debugPoint(start);
myqueue.push(start);
Point t;
int offset[][3] = {
{1, 0, 0},
{-1, 0, 0},
{0, 1, 0},
{0, -1, 0},
{0, 0, 1},
{0, 0, -1},
};
while(!myqueue.empty())
{
t = myqueue.front(); // the first in line
// debugPoint(t);
myqueue.pop();
if(t.i < 0 || t.i >= L)
continue;
if(t.j < 0 || t.j >= R)
continue;
if(t.k < 0 || t.k >= C)
continue;
if(castle[t.i][t.j][t.k] == '#')
continue;
if(step[t.i][t.j][t.k] != -1)
continue;
if(castle[t.i][t.j][t.k] == 'E')
break;
step[t.i][t.j][t.k] = t.step;
for(int i=0; i<6; i++)
{
Point n { t.i + offset[i][0], t.j + offset[i][1], t.k + offset[i][2], t.step + 1 };
myqueue.push(n);
}
}
// debugPoint(t);
if(castle[t.i][t.j][t.k] == 'E')
cout << "Escaped in " << t.step << " minute(s)." << endl;
else
cout << "Trapped!" << endl;
// for(int i = 0; i < L; i++)
// {
// for(int j = 0; j < R; j++)
// {
// cout << castle[i][j] << endl;
// }
// cout << endl;
// }
}
return 0;
} | [
"mandy840907@gmail.com"
] | mandy840907@gmail.com |
8953e2c312128ec83a74b73a2d5ffd20e3b588ed | e424bee39dd3b6cc3ab84ccea29fed5e3971acae | /WarszawQA_Selenium/browser/firefox-sdk-47/include/mozilla/dom/AbstractWorkerBinding.h | f49ae02bd7fd0bd8f4c447723665435a06a0ef74 | [] | no_license | okulynyak/warszawqa | b0f8e1689418fbd7356983a32605878e0a6e220f | 3e3312f99933a06353e316ec9cc54eafa9a081f4 | refs/heads/master | 2021-08-27T22:31:04.708072 | 2017-12-10T15:44:26 | 2017-12-10T15:44:26 | 113,602,184 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 602 | h | /* THIS FILE IS AUTOGENERATED FROM AbstractWorker.webidl BY Codegen.py - DO NOT EDIT */
#ifndef mozilla_dom_AbstractWorkerBinding_h
#define mozilla_dom_AbstractWorkerBinding_h
#include "js/RootingAPI.h"
#include "jspubtd.h"
#include "mozilla/ErrorResult.h"
#include "mozilla/dom/BindingDeclarations.h"
#include "mozilla/dom/Nullable.h"
namespace mozilla {
namespace dom {
struct NativePropertyHooks;
class ProtoAndIfaceCache;
} // namespace dom
} // namespace mozilla
namespace mozilla {
namespace dom {
} // namespace dom
} // namespace mozilla
#endif // mozilla_dom_AbstractWorkerBinding_h
| [
"okulynyak@gmail.com"
] | okulynyak@gmail.com |
cdeb23a0a58fba3738c8d0759335b7d924411989 | fe57d4ebb298e7d03757edce2805cd3d9813d7b0 | /controlleragent/MaintenancePlugin.h | 53420a8be62201830759c3131947d71d9a400db0 | [] | no_license | angrysea/AMGServer | 97b88c055121d0a974724491e27670c667510985 | 5764ac3c93b5fb6c811a1ae6ea480c6f8bca4bcb | refs/heads/master | 2020-05-19T09:19:39.288176 | 2015-01-14T23:46:30 | 2015-01-14T23:46:30 | 29,271,647 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,486 | h | package com.db.sws.pluginagent;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import com.db.sws.dbswsex.DBSWSException;
import com.db.sws.dbswsex.PluginException;
import com.db.sws.messaging.Address;
import com.db.sws.messaging.Envelope;
import com.db.sws.messaging.Message;
import com.db.sws.messaging.Messenger;
import com.db.sws.registry.PluginEntry;
public final class MaintenancePlugin extends SystemPlugin {
static private Map<String, MaintenanceWorker> workers = Collections
.synchronizedMap(new HashMap<String, MaintenanceWorker>(10));
public void startPlugin(PluginEntry entry) throws Exception {
}
public boolean preProcessMessage(Envelope env) {
return true;
}
public Object process(Envelope env) throws Exception {
try {
if (env.isMethod("ping")) {
ping(env.getHeader().getMessage());
} else if (env.isMethod("pong")) {
pong(env.getHeader().getMessage());
}
} catch (Exception e) {
PluginException agentex = new PluginException(
DBSWSException.SEVERITY_FATAL,
PluginException.ANT_OBJDOTRANS);
agentex.logMessage("Method not supported by Deutsche Bank Maintenance Agent. "
+ e.getMessage());
throw e;
}
return null;
}
public void ping(Message msg) {
try {
Message message = Message.createReply(msg);
message.setMethod("pong");
Messenger.postMessage(message);
} catch (Exception e) {
e.printStackTrace();
}
}
public void pong(Message msg) {
try {
MaintenanceWorker worker = workers.get(msg.getReplyTo().getURL());
worker.setResponded(true);
worker.setEndTime(System.currentTimeMillis());
// System.out.println("Response time for peer " +
// worker.getAddress().getURL() + " is " +
// Long.toString(worker.getPingTime()));
} catch (Exception e) {
e.printStackTrace();
}
}
public String process(String xml) throws Exception {
PluginException agentex = new PluginException(
DBSWSException.SEVERITY_FATAL,
PluginException.ANT_OBJDOTRANS);
agentex.logMessage(agentex);
throw agentex;
}
static public void doPing(Address address) {
MaintenanceWorker worker = new MaintenanceWorker(address);
workers.put(address.getURL(), worker);
}
static public Collection<MaintenanceWorker> workers() {
return workers.values();
}
static public void clear() {
workers.clear();
}
}
| [
"agraffeo@gmail.com"
] | agraffeo@gmail.com |
77771ba3868923858c764e15be39347f7c86657c | c712c82341b30aad4678f6fbc758d6d20bd84c37 | /CAC_Source_1.7884/_SessChk.cpp | 42959b036dc646ecbbcf10ee54aa282990cdfbcf | [] | no_license | governmentbg/EPEP_2019_d2 | ab547c729021e1d625181e264bdf287703dcb46c | 5e68240f15805c485505438b27de12bab56df91e | refs/heads/master | 2022-12-26T10:00:41.766991 | 2020-09-28T13:55:30 | 2020-09-28T13:55:30 | 292,803,726 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 6,995 | cpp | #include "cac.h" // 18.may.2001
//# include "all.h"
bool bad_session (const BriefSessionsToCheckGroup & sess,
const SessionErrors whichError,
outText * pOfs, const bool errMsg)
{
char tmp [196] ;
const size_t errSz = 1024 ;
char * const err = new char [errSz] ;
const char * const UnexpMembersh1 = "Броят съдии не е " ;
const char * const UnexpMembersh2 = ", както се очаква" ;
err [0] = '\0' ;
DatedContainer_ (sess).Print (tmp, sizeof (tmp)) ;
switch (whichError)
{
case SE_WrongMembership1 :
scSprintf (errSz, err,
"%s:\n""%s1%s.", tmp, UnexpMembersh1, UnexpMembersh2) ;
break ;
case SE_WrongMembership2 :
scSprintf (errSz, err,
"%s:\n""%s2%s.", tmp, UnexpMembersh1, UnexpMembersh2) ;
break ;
case SE_WrongMembership3 :
scSprintf (errSz, err,
"%s:\n""%s3%s.", tmp, UnexpMembersh1, UnexpMembersh2) ;
break ;
case SE_BadFixConcerningNextSess :
scSprintf (errSz, err,
"%s:\n"
"Заседанието е докладвано, но предходното заседание "
"по делото все още не е. ВНИМАНИЕ, това противоречие се "
"открива само ако и двете заседания са в разглеждания "
"период.",
tmp) ;
break ;
case SE_BadFixConcerningLawDate :
scSprintf (errSz, err,
"%s:\n""Датата на заседанието е по-малка от датата на "
"образуване на делото.", tmp) ;
break ;
case SE_DifferentCompositions :
scSprintf (errSz, err,
"%s:\n""Съставът не съвпада със състава на делото.",
tmp) ;
break ;
default :
scSprintf (errSz, err,
"%s:\n""Unspecified error.", tmp) ;
break ;
}
if (errMsg) // 04.jan.2000
error (err) ;
if (pOfs)
{
const column clmn (70, err) ;
for (size_t i = 0 ; i < clmn.getRowsCount () ; i ++)
{
if (pOfs -> pageLinesLeft () < 2)
pOfs -> newPage () ;
(* pOfs) << clmn [i] ;
pOfs -> newLine () ;
}
}
delete [] err ;
return false ;
} // bad_session
class TCheckSessionsThread : public TCheckupThread
{
protected:
const char* const types;
const CDate begDate;
const CDate endDate;
const long int composition;
const char* const lawKinds;
const char* const sessKinds;
const bool excludeResFixed;
const bool closedMembershipIsAlwaysOK;
bool& okYet;
outText* const pOf;
virtual bool ArgsOk();
virtual void Execute();
public:
TCheckSessionsThread(const char* const types_, const CDate begD,
const CDate endD, const long int composit,
const char* const lawKinds_, const char* const sessKinds_,
const bool excludeResFixed_,
const bool closedMembershipIsAlwaysOK_, bool& okYet_,
outText& of);
bool WantBreak() { return wtdl->WantBreak(); }
};
TCheckSessionsThread::
TCheckSessionsThread(const char* const types_, const CDate begD,
const CDate endD, const long int composit,
const char* const lawKinds_, const char* const sessKinds_,
const bool excludeResFixed_,
const bool closedMembershipIsAlwaysOK_, bool& okYet_,
outText& of):
types(types_), begDate(begD), endDate(endD), composition(composit),
lawKinds(lawKinds_), sessKinds(sessKinds_),
excludeResFixed(excludeResFixed_),
closedMembershipIsAlwaysOK(closedMembershipIsAlwaysOK_),
okYet(okYet_), pOf(of ? &of : NULL)
{
}
bool TCheckSessionsThread::ArgsOk()
{
return (TCheckupThread::ArgsOk() && types && types[0] &&
begDate.Empty() == false && endDate.Empty() == false);
}
void TCheckSessionsThread::Execute()
{
try
{ // -- 0 --
wtdl->SetHeader("Проверка на заседанията....");
wtdl->PleaseWait();
SessionsToCheck sessions (types, begDate, endDate, composition,
lawKinds, sessKinds, excludeResFixed) ;
TLawsuit law ;
BriefSessionsToCheckGroup prevSess ;
BriefSessionsToCheckGroup sess ;
totalPartSteps = sessions.SessionsFound();
wtdl->SetProgressRange(0, totalPartSteps);
endingVal = totalPartSteps;
clearGroupData (law) ;
while (sessions.NextSession (sess))
{ // -- 2 --
Tick(false);
if(wtdl->WantBreak())
break;
if (! (TRCDKey_ (law.key) == TRCDKey_ (sess.key)))
{
law.key = sess.key ;
if (! law.Get ())
{
clearGroupData (law) ;
law.key = sess.key ;
}
}
if (sess.result != RESULT_FIXED && sess.result != RESULT_DECREE)
if (law.finished.Empty () || sess.date <= law.finished)
if (judges_membership_ok_spk (law.kind, sess,
closedMembershipIsAlwaysOK, pOf)
== false)
okYet = false ;
if (sess.date < law.date)
okYet = bad_session (sess, SE_BadFixConcerningLawDate, pOf) ;
if (excludeResFixed == false)
if (TRCDKey_ (prevSess.key) == TRCDKey_ (sess.key))
if (prevSess.result == RESULT_FIXED &&
sess.result != RESULT_FIXED)
okYet = bad_session (sess, SE_BadFixConcerningNextSess, pOf) ;
# if INSTANCE
# if APPEAL
# else // of APPEAL
if (composition)
if (sess.composition != law.composition)
okYet = bad_session (sess, SE_DifferentCompositions, pOf) ;
# endif // of APPEAL
# else // of INSTANCE
if (composition)
if (sess.composition != law.composition)
okYet = bad_session (sess, SE_DifferentCompositions, pOf) ;
# endif // of INSTANCE
if (excludeResFixed == false)
prevSess.MoveDataFromBSCG (sess) ;
} // -- 2 --
Tick(true);
wtdl->AlmostDone();
} // -- 0 --
CATCH_ANYTHING
}
bool check_sessions(const char *const types, const CDate &begDate, const CDate &endDate, TWindow *parent,
const long composition, const char *const lawKinds, const char *const sessKinds, const bool excludeResFixed,
const bool closedMembershipIsAlwaysOK, bool *pCheckTerminated, bool *pInconsistencyFound)
{
if (!(types && types[0] && (begDate.Empty() == false && endDate.Empty() == false)))
return false;
bool okYet = true;
long outPos;
outText of(parent, EMPTY_FMT);
{
TCheckSessionsThread checker(types, begDate, endDate, composition, lawKinds, sessKinds, excludeResFixed,
closedMembershipIsAlwaysOK, okYet, of);
checker.Generate();
if (pCheckTerminated)
*pCheckTerminated = checker.WantBreak();
}
outPos = of.pcount();
of.newPage();
of.newLine();
if (okYet == false)
{
if (pInconsistencyFound)
*pInconsistencyFound = true;
okYet = ask("Бяха открити противоречия в данните за заседанията.\n%s", Q_CONTINUE);
}
if (!(okYet && outPos == 0))
show_text_stream_use_settings(NULL, of, EMPTY_FMT, FLOAT_ALIGNMENT);
return okYet;
}
| [
"git@vakata.com"
] | git@vakata.com |
b4ad23a9103f3b28f901848491a67b76e88de489 | 19ca234285e3569ea2d4809d7855d0bbf58c7baa | /ffmpeg-lib/src/main/jni/Audio.h | 3e02a7c2c2c27c54f769d795843ea965b95d64e0 | [] | no_license | justinhaisheng/music-test | 549fcc3a2669ecf276381d1e105fd908621d8887 | bcbec82160bc8284764153f5b3cf3b46a3101910 | refs/heads/master | 2020-11-25T20:31:49.982878 | 2020-01-20T07:36:12 | 2020-01-20T07:36:12 | 228,832,883 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,737 | h | //
// Created by yangw on 2018-2-28.
//
#ifndef MYMUSIC_WLAUDIO_H
#define MYMUSIC_WLAUDIO_H
#include "PlayQueue.h"
#include "Playstatus.h"
#include "CallJava.h"
extern "C"
{
#include "libavcodec/avcodec.h"
#include <libswresample/swresample.h>
#include <SLES/OpenSLES.h>
#include <SLES/OpenSLES_Android.h>
};
class Audio {
public:
int streamIndex = -1;
AVCodecContext *avCodecContext = NULL;
AVCodecParameters *codecpar = NULL;
CallJava *callJava = NULL;
PlayQueue *queue = NULL;
Playstatus *playstatus = NULL;
pthread_t thread_play;
AVPacket *avPacket = NULL;
AVFrame *avFrame = NULL;
//int ret = 0;
uint8_t *buffer = NULL;
//int data_size = 0;
int sample_rate;
int duration = 0;//总时长
AVRational time_base;//AVframe 的时间基
double cureent_clock;//
double now_time;//当前frame时间
double last_time;//上一次调用的时间
// 引擎接口
SLObjectItf engineObject = NULL;
SLEngineItf engineEngine = NULL;
//混音器
SLObjectItf outputMixObject = NULL;
SLEnvironmentalReverbItf outputMixEnvironmentalReverb = NULL;
SLEnvironmentalReverbSettings reverbSettings = SL_I3DL2_ENVIRONMENT_PRESET_STONECORRIDOR;
//pcm
SLObjectItf pcmPlayerObject = NULL;
SLPlayItf pcmPlayerPlay = NULL;
//缓冲器队列接口
SLAndroidSimpleBufferQueueItf pcmBufferQueue = NULL;
public:
Audio(Playstatus *playstatus,int sample_rate,CallJava *callJava);
~Audio();
void play();
void resume();
void pause();
void release();
void stop();
void initOpenSLES();
int resampleAudio();
SLuint32 getCurrentSampleRateForOpensles(int sample_rate);
};
#endif //MYMUSIC_WLAUDIO_H
| [
"haisheng.lu@aispeech.com"
] | haisheng.lu@aispeech.com |
89c94a948e32354874b441d8c0f91186e4330ab8 | 146ebca326d4d1417629080ee7703ea56cbb994b | /include/Shader.h | c6ce7b784752b7a1d6d19d11b439ac0209e1c1e5 | [] | no_license | chrisjuchem/rubiks-sim | 5ef4da27fe6876f05b4f08d6b02fd8cf9198c52c | 353002b7525aae25e81c3283e9465116d9b05335 | refs/heads/master | 2020-05-16T20:39:37.013824 | 2019-04-24T18:03:40 | 2019-04-24T19:08:44 | 183,286,175 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,414 | h | #ifndef SHADER_H
#define SHADER_H
#include <string>
#include <iostream>
#include <fstream>
#include <glad/glad.h>
class Shader{
public:
// Shader constructor
Shader();
// Shader Destructor
~Shader();
// Use this shader in our pipeline.
void Bind() const;
// Remove shader from our pipeline
void Unbind() const;
// Load a shader
std::string LoadShader(const std::string& fname);
// Create a Shader from a loaded vertex and fragment shader
void CreateShader(const std::string& vertexShaderSource, const std::string& fragmentShaderSource);
// return the shader id
GLuint getID() const;
// Set our uniforms for our shader.
void setUniformMatrix4fv(const GLchar* name, const GLfloat* value);
void setUniform3f(const GLchar* name, float v0, float v1, float v2);
void setUniform1i(const GLchar* name, int value);
void setUniform1f(const GLchar* name, float value);
private:
// Compiles loaded shaders
unsigned int CompileShader(unsigned int type, const std::string& source);
// Makes sure shaders 'linked' successfully
bool CheckLinkStatus(GLuint programID);
// Shader loading utility programs
void printProgramLog( GLuint program );
void printShaderLog( GLuint shader );
// Logs an error message
void Log(const char* system, const char* message);
// The unique shaderID
GLuint shaderID;
};
#endif
| [
"chrisjuchem15@gmail.com"
] | chrisjuchem15@gmail.com |
43d636a72cef09e9fd0967327026f8824c49dc9f | 23c6e6f35680bee885ee071ee123870c3dbc1e3d | /divine/mc/ctx-assume.hpp | 0e63ebc2606ab943f673edd2a96bdb85e4a57aa8 | [] | no_license | paradise-fi/divine | 3a354c00f39ad5788e08eb0e33aff9d2f5919369 | d47985e0b5175a7b4ee506fb05198c4dd9eeb7ce | refs/heads/master | 2021-07-09T08:23:44.201902 | 2021-03-21T14:24:02 | 2021-03-21T14:24:02 | 95,647,518 | 15 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,433 | hpp | // -*- mode: C++; indent-tabs-mode: nil; c-basic-offset: 4 -*-
/*
* (c) 2019 Petr Ročkai <code@fixp.eu>
*
* 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.
*/
#pragma once
#include <divine/vm/types.hpp>
#include <divine/vm/pointer.hpp>
#include <divine/smt/extract.hpp>
#include <brick-compose>
namespace divine::mc
{
template< typename next >
struct ctx_assume_ : next
{
std::vector< vm::HeapPointer > _assume;
using next::trace;
void trace( vm::TraceAssume ta )
{
_assume.push_back( ta.ptr );
if ( this->debug_allowed() )
trace( "ASSUME " + smt::extract::to_string( this->heap(), ta.ptr ) );
}
};
using ctx_assume = brq::module< ctx_assume_ >;
}
| [
"me@mornfall.net"
] | me@mornfall.net |
02671781bc9b751ee0e9550d8c9fe5615be5e063 | 1b02aa7827ad6c486aa16b0ed4dc8ef111b54b49 | /source/memory/LinearAllocator.inl | aa4709a7b282c0cd48ff8ab1c3f1b28fed6447df | [] | no_license | Nodli/HoneyComb | 6c3d8fa354ffefd6660a027301915c8caca9df63 | cf530ef70a5a42b1231822cfbef33750ffe6ac5e | refs/heads/master | 2021-12-14T00:36:27.300292 | 2021-12-04T23:43:47 | 2021-12-04T23:43:47 | 201,672,823 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 445 | inl | #ifndef INL_LINEARALLOCATOR
#define INL_LINEARALLOCATOR
template<typename T, typename ... ConstructorArguments>
T* LinearAllocator::get(const ConstructorArguments& ... arguments){
char* aligned_ptr = current + (current % std::alignment_of(T));
if((memory_bytes - (aligned_ptr - memory)) >= sizeof(T)){
current = aligned_ptr;
return new (aligned_ptr) T(arguments...);
}else{
return nullptr;
}
}
#endif
| [
"rambure.hugo@hotmail.fr"
] | rambure.hugo@hotmail.fr |
48c1b8a416334249803dd097638b1e2ff3b398ed | df6a2965e89a0ccd8176cf96a5b234e0aba0d655 | /src/qt/receiverequestdialog.h | 71e69876b1c6a3fa58c7e425082ba41a451373d4 | [
"MIT"
] | permissive | myceworld/myce | 1a1a0cf9263b2c648e97ef396d319dc91aefc545 | cd35e045da941dc70c340e6f6d2ec39e985410ae | refs/heads/master | 2022-08-23T02:01:17.461095 | 2022-03-12T06:17:09 | 2022-03-12T06:17:09 | 153,254,761 | 11 | 11 | MIT | 2022-03-12T06:17:10 | 2018-10-16T08:59:05 | C++ | UTF-8 | C++ | false | false | 1,518 | h | // Copyright (c) 2011-2013 The Bitcoin developers
// Copyright (c) 2017 The Pivx developers
// Copyright (c) 2018 The Myce developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_RECEIVEREQUESTDIALOG_H
#define BITCOIN_QT_RECEIVEREQUESTDIALOG_H
#include "walletmodel.h"
#include <QDialog>
#include <QImage>
#include <QLabel>
class OptionsModel;
namespace Ui
{
class ReceiveRequestDialog;
}
QT_BEGIN_NAMESPACE
class QMenu;
QT_END_NAMESPACE
/* Label widget for QR code. This image can be dragged, dropped, copied and saved
* to disk.
*/
class QRImageWidget : public QLabel
{
Q_OBJECT
public:
explicit QRImageWidget(QWidget* parent = 0);
QImage exportImage();
public slots:
void saveImage();
void copyImage();
protected:
virtual void mousePressEvent(QMouseEvent* event);
virtual void contextMenuEvent(QContextMenuEvent* event);
private:
QMenu* contextMenu;
};
class ReceiveRequestDialog : public QDialog
{
Q_OBJECT
public:
explicit ReceiveRequestDialog(QWidget* parent = 0);
~ReceiveRequestDialog();
void setModel(OptionsModel* model);
void setInfo(const SendCoinsRecipient& info);
private slots:
void on_btnCopyURI_clicked();
void on_btnCopyAddress_clicked();
void update();
private:
Ui::ReceiveRequestDialog* ui;
OptionsModel* model;
SendCoinsRecipient info;
};
#endif // BITCOIN_QT_RECEIVEREQUESTDIALOG_H
| [
"noreply@github.com"
] | noreply@github.com |
1a7fdcc40b2d42261b4dbd60a099234a874acdce | bd1fea86d862456a2ec9f56d57f8948456d55ee6 | /000/068/373/CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_char_memcpy_65a.cpp | add7d6f51149f9f69cb14f14a8829a391369a63c | [] | no_license | CU-0xff/juliet-cpp | d62b8485104d8a9160f29213368324c946f38274 | d8586a217bc94cbcfeeec5d39b12d02e9c6045a2 | refs/heads/master | 2021-03-07T15:44:19.446957 | 2020-03-10T12:45:40 | 2020-03-10T12:45:40 | 246,275,244 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,568 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_char_memcpy_65a.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805.string.label.xml
Template File: sources-sink-65a.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Allocate using new[] and set data pointer to a small buffer
* GoodSource: Allocate using new[] and set data pointer to a large buffer
* Sinks: memcpy
* BadSink : Copy string to data using memcpy
* Flow Variant: 65 Data/control flow: data passed as an argument from one function to a function in a different source file called via a function pointer
*
* */
#include "std_testcase.h"
#include <wchar.h>
namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_char_memcpy_65
{
#ifndef OMITBAD
/* bad function declaration */
void badSink(char * data);
void bad()
{
char * data;
/* define a function pointer */
void (*funcPtr) (char *) = badSink;
data = NULL;
/* FLAW: Allocate using new[] and point data to a small buffer that is smaller than the large buffer used in the sinks */
data = new char[50];
data[0] = '\0'; /* null terminate */
/* use the function pointer */
funcPtr(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(char * data);
static void goodG2B()
{
char * data;
void (*funcPtr) (char *) = goodG2BSink;
data = NULL;
/* FIX: Allocate using new[] and point data to a large buffer that is at least as large as the large buffer used in the sink */
data = new char[100];
data[0] = '\0'; /* null terminate */
funcPtr(data);
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_char_memcpy_65; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| [
"frank@fischer.com.mt"
] | frank@fischer.com.mt |
750b0432e8617d8659236f4e97618b487007e2e1 | 9c90b3655ba167ed8f2e993dbd3a631bb97ed4d1 | /src/lvltextgen.cc | b85f20de164038d5cc68eddf9428c15265145e7a | [] | no_license | althaitran/MadBirds | 5d0194d9085158b62b984a082b41124201d8e092 | a978868d6d6c8842e2818f127648ae2bcd5a3efe | refs/heads/master | 2021-01-10T19:27:10.511690 | 2012-02-25T17:46:27 | 2012-02-25T17:46:27 | 3,546,024 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,445 | cc | #include <iostream>
#include <sstream>
#include <fstream>
#include "lvltextgen.h"
using namespace std;
//Constructor
LvlTextGen::LvlTextGen() {}
//Destructor
LvlTextGen::~LvlTextGen() {}
//Generates a level by setting the spawn points of the Sling, Bird, Target,
//Terrain, and Block objects
bool LvlTextGen::Generate(int level, int spring_c, int gravity, Sling **sling,
Bird **bird, list<Target *> &targets,
list<Terrain *> &terrain, list<Block *> &blocks){
bool createSling = false; //Keeps track of if a sling was ever made.
ifstream lvlReader; //File to read level info from
stringstream fileNameStream; //Stream to store the name of the file to read.
string fileName; //Name of the file to read.
//Obtain the level file's name
fileNameStream << lvlFolder << lvlPrefix << level << lvlSuffix;
fileName = fileNameStream.str();
lvlReader.open(fileName.c_str()); //Start reading contents of the file
//Only generate anything if the level file exists.
if (lvlReader.is_open()) {
string curWord; //Current word from file being read.
lvlReader >> curWord; //Read a word from lvlReader
while (!lvlReader.eof()) {
//Now, depending on the word, create a certain object.
if (curWord == "sling") { //Generate sling and bird
//Next 2 items should indicate the position of the sling.
int x, y;
lvlReader >> x;
lvlReader >> y;
//Only if there was no trouble getting x and y do the sling and
//bird get made.
if (!lvlReader.fail()) {
createSling = true;
//Either initialize or modify sling, depending on its existence.
if (*sling != 0) {
(*sling)->setXPos(x);
(*sling)->setYPos(y);
} else {
*sling = new Sling(x,y, spring_c);
(*sling)->Hold();
}
//Either initialize or modify bird, depending on its existence.
if (*bird != 0) {
(*bird)->setXPos(x - 10);
(*bird)->setYPos(y - 10);
(*bird)->setXSpeed(0);
(*bird)->setYSpeed(0);
(*bird)->setOnSling(true);
(*bird)->setYAccel(gravity);
} else {
*bird = new Bird(x - 10,y - 10);
(*bird)->setYAccel(gravity);
(*bird)->setOnSling(true);
}
} else { //Couldn't read sling parameters. Thus, file is invalid.
lvlReader.close();
cout << "Could not read sling parameters. Level not loaded." << endl;
return false;
}
} else if (curWord == "terrain") { //Generate terrain
//Next 4 words should indicate the position and size of terrain.
int x, y, width, height;
lvlReader >> x;
lvlReader >> y;
lvlReader >> width;
lvlReader >> height;
//If no problems occurred getting x, y, width, and height, create
//a new terrain object, and store it in the terrain list.
if (!lvlReader.fail()){
Terrain *newTerrain = new Terrain(x, y, width, height);
terrain.push_back(newTerrain);
} else { //Couldn't read terrain parameters. Thus, file is invalid.
lvlReader.close();
cout << "Could not read terrain parameters. Level not loaded." << endl;
return false;
}
} else if (curWord == "block") { //Generate block
//Next 2 words should indicate the position of the blocks.
int x, y;
lvlReader >> x;
lvlReader >> y;
//If no problems occurred getting x and y, create a new block
//object, and store it in the block list.
if (!lvlReader.fail()){
Block *newBlock = new Block(x, y);
newBlock->setYAccel(gravity);
blocks.push_back(newBlock);
} else { //Couldn't read block parameters. Thus, file is invalid.
lvlReader.close();
cout << "Could not read block parameters. Level not loaded." << endl;
return false;
}
} else if (curWord == "target"){ //Generate target
//Next 2 words should indicate the position of the targets.
int x, y;
lvlReader >> x;
lvlReader >> y;
//If no problems occurred getting x and y, create a new target
//object, and store it in the block list.
if (!lvlReader.fail()){
Target *newTarget = new Target(x, y);
newTarget->setYAccel(gravity);
targets.push_back(newTarget);
} else { //Couldn't read target parameters. Thus, file is invalid.
lvlReader.close();
cout << "Could not read target parameters. Level not loaded." << endl;
return false;
}
} else { //Couldn't identify word. File is, therefore, invalid.
lvlReader.close();
cout << "Could not read file. Level not loaded." << endl;
return false;
}
lvlReader >> curWord; //Read next word from lvlReader
}
lvlReader.close(); //Make sure to close the reader before exiting.
} else { //If the file can't be read, then a level wasn't generated.
return false;
}
//If a sling wasn't generated, then this level is invalid
if (!createSling) {
cout << "The level file doesn't create a sling. It is, therefore, invalid." << endl;
return false;
}
return true;
}
| [
"althaitran@gmail.com"
] | althaitran@gmail.com |
13a244b5a6d8659065a9dfd548278c51dea7942f | 875a07e0844ecca3a79939372000519fac0515fe | /cnpc/src/NVRConnector/src/DBConnector.cpp | f3af2319d5f938f74d2c1f3851384d37891f2e7c | [] | no_license | iamlinix/code-share | 78cad5cbeaa829f0c4838cba53053efd357be06c | 20b3ca8ee5f440b6492e669598da0af9bf43db08 | refs/heads/master | 2023-03-07T15:53:11.626748 | 2021-02-25T23:17:40 | 2021-02-25T23:17:40 | 342,403,299 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,844 | cpp | #include <stdio.h>
#include <string.h>
#include <errno.h>
#include <errmsg.h>
#include <sys/stat.h>
#include "NVRConnector.h"
#include "util.h"
///////////////////////////////////////////////////////////////////////////////
//
MYSQL *DB_Init()
{
MYSQL *conn;
/* db configure*/
char *server = (char *)"127.0.0.1";
char *user = (char *)"tav";
char *password = (char *)"Qwer_1234";
char *database = (char *)"tav";
int port = 3306;
/* do connect */
conn = mysql_init(NULL);
/* Connect to database */
if (!mysql_real_connect(conn, server, user, password, database, port, NULL, 0))
{
LOG_ERR(">>> Connect DB failed: %s\n", mysql_error(conn));
return NULL;
}
if (mysql_set_character_set(conn, "utf8"))
{
LOG_ERR(">>> MySQL set character set [utf8] failed: %s", mysql_error(conn));
mysql_close(conn);
return NULL;
}
LOG_INFO(">>> DB Connected.");
return conn;
}
MYSQL *DB_Reconnect()
{
LOG_INFO(">>> DB Re-Connected.");
return DB_Init();
}
void DB_Close(MYSQL *conn)
{
LOG_INFO(">>> DB Closed.");
if (conn)
{
mysql_close(conn);
}
}
static int dump_picture_file(veh_info_t *vehi, char *name, int size)
{
char full_name[256] = { 0 };
char full_dir[256] = { 0 };
if (!vehi->pic_buff || vehi->pic_buff_size <= 0)
{
return 0;
}
//struct tm *fmt_tm = &vehi->t;
struct tm *fmt_tm;
fmt_tm = localtime(&vehi->post_time);
if (vehi->plate_num[0] == 0x0)
{
snprintf(name, size, "%04d%02d%02d_%02d%02d%02d_none.jpg",
//vehi->tm.wYear, vehi->tm.byMonth, vehi->tm.byDay,
//vehi->tm.byHour, vehi->tm.byMinute, vehi->tm.bySecond);
1900 + fmt_tm->tm_year, fmt_tm->tm_mon + 1, fmt_tm->tm_mday,
fmt_tm->tm_hour, fmt_tm->tm_min, fmt_tm->tm_sec);
}
else
{
snprintf(name, size, "%04d%02d%02d_%02d%02d%02d_%s.jpg",
//vehi->tm.wYear, vehi->tm.byMonth, vehi->tm.byDay,
//vehi->tm.byHour, vehi->tm.byMinute, vehi->tm.bySecond,
1900 + fmt_tm->tm_year, fmt_tm->tm_mon + 1, fmt_tm->tm_mday,
fmt_tm->tm_hour, fmt_tm->tm_min, fmt_tm->tm_sec,
vehi->plate_num);
}
/* check dir first */
snprintf(full_dir, 256, "%s/%04d%02d%02d", NVR_PIC_PATH,
1900 + fmt_tm->tm_year, fmt_tm->tm_mon + 1, fmt_tm->tm_mday);
if (0 == access(full_dir, 0))
{
}
else
{
if (mkdir(full_dir, 0755) == -1)
{
LOG_ERR(">>> mkdir %s failed.", full_dir);
return -1;
}
else
{
LOG_DBG(">>> mkdir %s success.", full_dir);
}
}
snprintf(full_name, 256, "%s/%s", full_dir, name);
LOG_INFO(">>> picture file name: %s", full_name);
FILE *fp = fopen(full_name, "wb");
if (fp)
{
fwrite(vehi->pic_buff, vehi->pic_buff_size, sizeof(char), fp);
fclose(fp);
LOG_INFO(">>> dump picture to file.");
}
else
{
LOG_INFO(">>> dump picture to file failed: %d(%s).", errno, strerror(errno));
}
return 0;
}
int DB_Connector(MYSQL *conn, veh_info_t *vehi)
{
char sql[1024] = {0};
/* Dump picture file */
char out_name[256] = { 0 };
dump_picture_file(vehi, out_name, 256);
if (!conn || !vehi)
{
LOG_ERR("para is null (conn: %p, vehi: %p).", conn, vehi);
return -1;
}
/* convert time */
char tbuff[20] = { 0 };
struct tm *fmt_tm;
LOG_DBG(">>> post time: %lld", vehi->post_time);
fmt_tm = localtime(&vehi->post_time);
strftime(tbuff, 20, "%Y-%m-%d %H:%M:%S", fmt_tm);
//snprintf(tbuff, 20, "%04d-%02d-%02d %02d:%02d:%02d",
// vehi->tm.wYear, vehi->tm.byMonth, vehi->tm.byDay,
// vehi->tm.byHour, vehi->tm.byMinute, vehi->tm.bySecond);
LOG_INFO(">>> time buff: %s", tbuff);
/* convert time */
char nbuff[20] = { 0 };
struct tm *now_tm;
time_t now;
time(&now);
now_tm = localtime(&now);
strftime(nbuff, 20, "%Y-%m-%d %H:%M:%S", now_tm);
LOG_INFO(">>> now time buff: %s", nbuff);
//if (vehi->plate_num[0] == 0x65 && vehi->plate_num[1] == 0xe0)
//{
// LOG_DBG(">>> Got a none plate, skip it.");
// return 0;
//}
/* format sql command */
snprintf(sql, 1024, "INSERT INTO vehicle (STATION_ID, CHANNEL_ID, POST_TIME, \
PLATE_NUM, PLATE_COLOR, VEH_TYPE, VEH_BRAND, VEH_SUB_BRAND, \
VEH_MODEL, VEH_PIC_FNAME, CREATE_TIME) \
VALUES (%d, %d, \"%s\", \"%s\", %d, %d, %d, %d, %d, \"%s\", \"%s\")",
vehi->station_id, vehi->channel_id, tbuff, vehi->plate_num, \
vehi->plate_color, vehi->veh_type, vehi->veh_brand, \
vehi->veh_sub_brand, vehi->veh_model, out_name, nbuff);
/* send SQL query */
LOG_INFO(">>> [DB] begin excute sql...");
LOG_DBG(">>> [DB] command: %s", sql);
int status = mysql_query(conn, sql);
if (status != 0)
{
if (status == CR_SERVER_LOST || status == CR_SERVER_GONE_ERROR)
{
LOG_INFO(">>> [DB] mysql conn lost, reconnect...");
/* do re-connect */
DB_Close(conn);
conn = DB_Reconnect();
if (conn)
{
if (mysql_query(conn, sql))
{
LOG_ERR("mysql query failed.");
return -1;
}
}
}
else
{
LOG_ERR(">>> mysql query failed with code %d(%s).",
status, mysql_error(conn));
}
}
LOG_INFO(">>> [DB] finish excute sql.");
//res = mysql_use_result(conn);
return 0;
}
| [
"linxin@taveen.cn"
] | linxin@taveen.cn |
af842da5396ace0d1b6654a47867cbaaca495978 | 9e78a5a7dbd79d40ef1a8ca6e9d45620cf594cd0 | /Leetcode/1680. Concatenation of Consecutive Binary Numbers.cpp | 504269e71c7f37025616750b73eccec12aeedabc | [] | no_license | Akimbaevsako/CodeIt | ff6cf2bde5e5e95b37d818e4ace7774c2a2ec64b | 22e27d94d76ec044ca65d1169cb3f8d610fa2bf3 | refs/heads/master | 2023-04-04T23:16:52.822415 | 2021-03-12T18:53:41 | 2021-03-12T18:53:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,324 | cpp | //1680. Concatenation of Consecutive Binary Numbers
// ques link: https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers/
//-------------------------------------------------SOLUTION-------------------------------------------------
class Solution {
public:
// string dtb(string s,int n){
// if(n==1)
// return s+to_string(1);
// else{
// while(n>0){
// int j=n%2;
// s+=to_string(j);
// n/=2;
// }
// }
// return dtb(s,n-1);
// }
int concatenatedBinary(int n) {
// string st=dtb("",n);
// reverse(st.begin(),st.end());
// long int m=1e9 +7;
// int le=st.length()-1;
// long int x=0;
// for(int i=st.length()-1;i>=0;--i){
// x+=int(st[i])*pow(2,le-i);
// }
// cout<<x<<" "<<st<<endl;
// return x%m;
long res = 0;
for (int i = 1, j, bitLen; i <= n; i++) {
j = i;
bitLen = 0;
// computing the length in bits of i
while (j) {
bitLen++;
j >>= 1;
}
// shifting res by bitLen bits
res = (res << bitLen) % 1000000007 + i;
}
return res;
}
};
| [
"noreply@github.com"
] | noreply@github.com |
f12bffc2f1a53938544d4bd301036107e4343970 | d3f5a219e1eb65c33a7c8d26b6e0e6f052f518b4 | /tictactoe.cpp | 730915c1cbe97303d728e73ae4b4902df4925bb2 | [] | no_license | guptavaibhav1998/3-In-1 | ec0b855eba19106d0c5aa54f5b9d1822dcb5d5bf | eeb0ae7ff5da53be7afefece00f4f596150c2041 | refs/heads/master | 2020-03-24T04:01:50.241241 | 2018-07-26T13:02:38 | 2018-07-26T13:02:38 | 142,441,356 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,431 | cpp | #include <iostream>
#include<cstdlib>
using namespace std;
char matrix[3][3] = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
char player = 'X';
int n;
void DrawTicTackToe()
{
system("cls");
cout << "TicTacToe Game" << endl;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}
}
void InputTicTackToe()
{
int a;
cout << "It's " << player << " turn. "<<endl <<"Press the number of the field: "<<endl;
cin >> a;
if (a == 1)
{
if (matrix[0][0] == '1')
matrix[0][0] = player;
else
{
cout << "Field is already in use try again!" << endl;
InputTicTackToe();
}
}
else if (a == 2)
{
if (matrix[0][1] == '2')
matrix[0][1] = player;
else
{
cout << "Field is already in use try again!" << endl;
InputTicTackToe();
}
}
else if (a == 3)
{
if (matrix[0][2] == '3')
matrix[0][2] = player;
else
{
cout << "Field is already in use try again!" << endl;
InputTicTackToe();
}
}
else if (a == 4)
{
if (matrix[1][0] == '4')
matrix[1][0] = player;
else
{
cout << "Field is already in use try again!" << endl;
InputTicTackToe();
}
}
else if (a == 5)
{
if (matrix[1][1] == '5')
matrix[1][1] = player;
else
{
cout << "Field is already in use try again!" << endl;
InputTicTackToe();
}
}
else if (a == 6)
{
if (matrix[1][2] == '6')
matrix[1][2] = player;
else
{
cout << "Field is already in use try again!" << endl;
InputTicTackToe();
}
}
else if (a == 7)
{
if (matrix[2][0] == '7')
matrix[2][0] = player;
else
{
cout << "Field is already in use try again!" << endl;
InputTicTackToe();
}
}
else if (a == 8)
{
if (matrix[2][1] == '8')
matrix[2][1] = player;
else
{
cout << "Field is already in use try again!" << endl;
InputTicTackToe();
}
}
else if (a == 9)
{
if (matrix[2][2] == '9')
matrix[2][2] = player;
else
{
cout << "Field is already in use try again!" << endl;
InputTicTackToe();
}
}
}
void TogglePlayer()
{
if (player == 'X')
player = 'O';
else
player = 'X';
}
char Win()
{
//first player
if (matrix[0][0] == 'X' && matrix[0][1] == 'X' && matrix[0][2] == 'X')
return 'X';
if (matrix[1][0] == 'X' && matrix[1][1] == 'X' && matrix[1][2] == 'X')
return 'X';
if (matrix[2][0] == 'X' && matrix[2][1] == 'X' && matrix[2][2] == 'X')
return 'X';
if (matrix[0][0] == 'X' && matrix[1][0] == 'X' && matrix[2][0] == 'X')
return 'X';
if (matrix[0][1] == 'X' && matrix[1][1] == 'X' && matrix[2][1] == 'X')
return 'X';
if (matrix[0][2] == 'X' && matrix[1][2] == 'X' && matrix[2][2] == 'X')
return 'X';
if (matrix[0][0] == 'X' && matrix[1][1] == 'X' && matrix[2][2] == 'X')
return 'X';
if (matrix[2][0] == 'X' && matrix[1][1] == 'X' && matrix[0][2] == 'X')
return 'X';
//second player
if (matrix[0][0] == 'O' && matrix[0][1] == 'O' && matrix[0][2] == 'O')
return 'O';
if (matrix[1][0] == 'O' && matrix[1][1] == 'O' && matrix[1][2] == 'O')
return 'O';
if (matrix[2][0] == 'O' && matrix[2][1] == 'O' && matrix[2][2] == 'O')
return 'O';
if (matrix[0][0] == 'O' && matrix[1][0] == 'O' && matrix[2][0] == 'O')
return 'O';
if (matrix[0][1] == 'O' && matrix[1][1] == 'O' && matrix[2][1] == 'O')
return 'O';
if (matrix[0][2] == 'O' && matrix[1][2] == 'O' && matrix[2][2] == 'O')
return 'O';
if (matrix[0][0] == 'O' && matrix[1][1] == 'O' && matrix[2][2] == 'O')
return 'O';
if (matrix[2][0] == 'O' && matrix[1][1] == 'O' && matrix[0][2] == 'O')
return 'O';
return '/';
}
void RunTickTackToe()
{
int chances = 0;
DrawTicTackToe();
while (1)
{
chances++;
InputTicTackToe();
DrawTicTackToe();
if (Win() == 'X')
{
cout<<endl << "X wins!" << endl;
break;
}
else if (Win() == 'O')
{
cout<<endl << "O wins!" << endl;
break;
}
else if (chances == 9)
{
cout<<endl << "It's a draw!" << endl;
break;
}
TogglePlayer();
}
system("pause");
}
/*int main()
{
n = 0;
DrawTicTackToe();
while (1)
{
n++;
InputTicTackToe();
DrawTicTackToe();
if (Win() == 'X')
{
cout << "X wins!" << endl;
break;
}
else if (Win() == 'O')
{
cout << "O wins!" << endl;
break;
}
else if (Win() == '/' && n == 9)
{
cout << "It's a DrawTicTackToe!" << endl;
break;
}
TogglePlayer();
}
system("pause");
return 0;
}
*/
| [
"guptavaibhav1998@gmail.com"
] | guptavaibhav1998@gmail.com |
85d52ecaa8478e452bc1f36b5e617452d6e890fe | 32cdaf8adcddab13302757b31635ca881d89a0cd | /src/TabletInspector/Resources.h | 1dbd26827c866b44d53dfd4636f91815e363b192 | [
"Apache-2.0"
] | permissive | shuhari/TabletInspector | 4696a839fbcb031f234da3b280d16971c8cbe281 | 6c34fb2c52c4610e43aa39c2054a950dcb40ae95 | refs/heads/master | 2020-03-28T20:40:35.980701 | 2018-10-22T03:11:03 | 2018-10-22T03:11:03 | 149,092,618 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 408 | h | #pragma once
class Resources {
public:
static QIcon appIcon();
static QIcon settings();
static QIcon debug();
static QIcon info();
static QIcon warn();
static QIcon error();
static QIcon logs();
static QIcon prop();
static QIcon data();
static QIcon clear();
static QPixmap connected();
static QPixmap disconnected();
static QPixmap appIconPixmap();
};
| [
"shuhari@outlook.com"
] | shuhari@outlook.com |
f76d925ec6f9c7319498b5b49b53de1ad0900600 | f9c232f58e4e92d5654b462cf778e2180971763e | /CppAsync/util/ContextRef.h | f732387e5e75818e7b6bf50d33f00c454407cf89 | [
"Apache-2.0"
] | permissive | zdeslav/CppAsync | 68c811cd82899543b1a88d0e580a30f58bec964e | 7157c82a4bb892ccb0604a12d6368e715c163e55 | refs/heads/master | 2020-12-07T15:16:48.947941 | 2015-10-20T11:15:03 | 2015-10-20T11:15:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,752 | h | /*
* Copyright 2015 Valentin Milea
*
* 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.
*/
#pragma once
#include "../impl/Common.h"
#include "../impl/Assert.h"
#include "Meta.h"
namespace ut {
namespace detail
{
template <class T>
struct ContextNode;
template <>
struct ContextNode<void>
{
std::shared_ptr<void> parent;
ContextNode(const std::shared_ptr<void>& parent) _ut_noexcept
: parent(parent) { }
};
template <class T>
struct ContextNode : ContextNode<void>
{
T value;
template <class ...Args>
ContextNode(const std::shared_ptr<void>& parent, Args&&... args)
: base_type(parent)
, value(std::forward<Args>(args)...) { }
private:
using base_type = ContextNode<void>;
};
}
template <class T, class Alloc>
struct ContextRefMixin;
template <class T, class Alloc = std::allocator<char>>
class ContextRef : public ContextRefMixin<T, Alloc>
{
public:
using value_type = T;
using alloc_type = Alloc;
template <class ...Args>
ContextRef(const std::shared_ptr<void>& parent, const Alloc& alloc, Args&&... args)
: mNode(std::allocate_shared<detail::ContextNode<T>>(alloc,
parent, std::forward<Args>(args)...))
, mAlloc(alloc) { }
template <class U,
class Z = T, EnableIfVoid<Z> = nullptr>
ContextRef(const ContextRef<U, Alloc>& other) _ut_noexcept
: mNode(other.mNode)
, mAlloc(other.mAlloc) { }
ContextRef(const ContextRef& other) _ut_noexcept
: mNode(other.mNode)
, mAlloc(other.mAlloc) { }
template <class U,
class Z = T, EnableIfVoid<Z> = nullptr>
ContextRef(ContextRef<U, Alloc>&& other) _ut_noexcept
: mNode(std::move(other.mNode))
, mAlloc(std::move(other.mAlloc)) { }
ContextRef(ContextRef&& other) _ut_noexcept
: mNode(std::move(other.mNode))
, mAlloc(std::move(other.mAlloc)) { }
template <class U,
class Z = T, EnableIfVoid<Z> = nullptr>
ContextRef& operator=(const ContextRef<U, Alloc>& other) _ut_noexcept
{
mNode = other.mNode;
mAlloc = other.mAlloc;
return *this;
}
ContextRef& operator=(const ContextRef& other) _ut_noexcept
{
mNode = other.mNode;
mAlloc = other.mAlloc;
return *this;
}
template <class U,
class Z = T, EnableIfVoid<Z> = nullptr>
ContextRef& operator=(ContextRef<U, Alloc>&& other) _ut_noexcept
{
ut_assert(this != &other);
mNode = std::move(other.mNode);
mAlloc = std::move(other.mAlloc);
return *this;
}
ContextRef& operator=(ContextRef&& other) _ut_noexcept
{
ut_assert(this != &other);
mNode = std::move(other.mNode);
mAlloc = std::move(other.mAlloc);
return *this;
}
template <class U, class ...Args>
ContextRef<U, Alloc> spawn(Args&&... args) const
{
return ContextRef<U, Alloc>(mNode, mAlloc, std::forward<Args>(args)...);
}
template <class U, class UAlloc, class ...Args>
ContextRef<U, UAlloc> spawnWithAllocator(const UAlloc& alloc, Args&&... args) const
{
return ContextRef<U, UAlloc>(mNode, alloc, std::forward<Args>(args)...);
}
std::shared_ptr<void> parentPtr() const _ut_noexcept
{
return mNode->parent;
}
std::shared_ptr<void> ptr() const _ut_noexcept
{
return mNode;
}
Alloc allocator() const _ut_noexcept
{
return mAlloc;
}
private:
std::shared_ptr<detail::ContextNode<T>> mNode;
Alloc mAlloc;
template <class U, class UAlloc>
friend class ContextRef;
friend struct ContextRefMixin<T, Alloc>;
};
template <class T, class Alloc>
struct ContextRefMixin
{
ContextRef<void, Alloc> operator()() const _ut_noexcept
{
return ContextRef<void, Alloc>(thiz());
}
const T& operator*() const
{
return thiz().mNode->value;
}
T& operator*()
{
return thiz().mNode->value;
}
const T* operator->() const
{
return &thiz().mNode->value;
}
T* operator->()
{
return &thiz().mNode->value;
}
private:
const ContextRef<T, Alloc>& thiz() const
{
return static_cast<const ContextRef<T, Alloc>&>(*this); // safe cast
}
ContextRef<T, Alloc>& thiz()
{
return static_cast<ContextRef<T, Alloc>&>(*this); // safe cast
}
};
template <class Alloc>
struct ContextRefMixin<void, Alloc>
{
ContextRef<void, Alloc> operator()() const _ut_noexcept
{
return thiz();
}
private:
const ContextRef<void, Alloc>& thiz() const
{
return static_cast<const ContextRef<void, Alloc>&>(*this); // safe cast
}
};
template <class T, class Alloc, class ...Args>
inline ContextRef<T, Alloc> makeContextWithAllocator(const Alloc& alloc, Args&&... args)
{
return ContextRef<T, Alloc>(std::shared_ptr<void>(), alloc, std::forward<Args>(args)...);
}
template <class T, class Alloc = std::allocator<char>, class ...Args>
inline ContextRef<T, Alloc> makeContext(Args&&... args)
{
return makeContextWithAllocator<T>(Alloc(), std::forward<Args>(args)...);
}
}
| [
"valentin.milea@gmail.com"
] | valentin.milea@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.