blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b4cbdf6bdcd0b97e3471e6ff9fd34a260efc9a8e | 2efbd55f9c7f39bddc1348f3a9d38a8f05d0644a | /plugins/eeui/WeexSDK/ios/weex_core/Source/include/wtf/dtoa.h | 83f092bb214f6216d118c222b2ff6114bf1232d4 | [
"MIT"
] | permissive | bonniesl/yktapp | 23b05cc53214269bf1d792dcf41993b425bfe470 | 3f96b7aad945e9aa110f0643d9a57e28d0645ab6 | refs/heads/master | 2023-03-27T04:27:14.921221 | 2021-03-25T06:29:16 | 2021-03-25T06:33:12 | 351,330,677 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,704 | h | /*
* Copyright (C) 2003, 2008, 2012 Apple Inc. All rights reserved.
*
* 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; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#ifndef WTF_dtoa_h
#define WTF_dtoa_h
#include <unicode/utypes.h>
#include <wtf/ASCIICType.h>
#include <wtf/dtoa/double-conversion.h>
#include <wtf/text/StringView.h>
namespace WTF {
typedef char DtoaBuffer[80];
WTF_EXPORT_PRIVATE void dtoa(DtoaBuffer result, double dd, bool& sign, int& exponent, unsigned& precision);
WTF_EXPORT_PRIVATE void dtoaRoundSF(DtoaBuffer result, double dd, int ndigits, bool& sign, int& exponent, unsigned& precision);
WTF_EXPORT_PRIVATE void dtoaRoundDP(DtoaBuffer result, double dd, int ndigits, bool& sign, int& exponent, unsigned& precision);
// Size = 80 for sizeof(DtoaBuffer) + some sign bits, decimal point, 'e', exponent digits.
const unsigned NumberToStringBufferLength = 96;
typedef char NumberToStringBuffer[NumberToStringBufferLength];
typedef LChar NumberToLStringBuffer[NumberToStringBufferLength];
WTF_EXPORT_PRIVATE const char* numberToString(double, NumberToStringBuffer);
WTF_EXPORT_PRIVATE const char* numberToFixedPrecisionString(double, unsigned significantFigures, NumberToStringBuffer, bool truncateTrailingZeros = false);
WTF_EXPORT_PRIVATE const char* numberToFixedWidthString(double, unsigned decimalPlaces, NumberToStringBuffer);
double parseDouble(const LChar* string, size_t length, size_t& parsedLength);
double parseDouble(const UChar* string, size_t length, size_t& parsedLength);
double parseDouble(StringView, size_t& parsedLength);
namespace Internal {
WTF_EXPORT_PRIVATE double parseDoubleFromLongString(const UChar* string, size_t length, size_t& parsedLength);
}
inline double parseDouble(const LChar* string, size_t length, size_t& parsedLength)
{
return double_conversion::StringToDoubleConverter::StringToDouble(reinterpret_cast<const char*>(string), length, &parsedLength);
}
inline double parseDouble(const UChar* string, size_t length, size_t& parsedLength)
{
const size_t conversionBufferSize = 64;
if (length > conversionBufferSize)
return Internal::parseDoubleFromLongString(string, length, parsedLength);
LChar conversionBuffer[conversionBufferSize];
for (int i = 0; i < static_cast<int>(length); ++i)
conversionBuffer[i] = isASCII(string[i]) ? string[i] : 0;
return parseDouble(conversionBuffer, length, parsedLength);
}
inline double parseDouble(StringView string, size_t& parsedLength)
{
if (string.is8Bit())
return parseDouble(string.characters8(), string.length(), parsedLength);
return parseDouble(string.characters16(), string.length(), parsedLength);
}
} // namespace WTF
using WTF::NumberToStringBuffer;
using WTF::NumberToLStringBuffer;
using WTF::numberToString;
using WTF::numberToFixedPrecisionString;
using WTF::numberToFixedWidthString;
using WTF::parseDouble;
#endif // WTF_dtoa_h
| [
"1336429771@qq.com"
] | 1336429771@qq.com |
16f6f4bced0c50a79add47dbaf3e582d5479c6e2 | f8517de40106c2fc190f0a8c46128e8b67f7c169 | /AllJoyn/Samples/OICAdapter/iotivity-1.0.0/resource/oc_logger/include/oc_logger.hpp | 2d0df21448b4f239ccd3ffe1de0233fc8b1825cb | [
"MIT",
"BSD-3-Clause",
"GPL-2.0-only",
"Apache-2.0"
] | permissive | ferreiramarcelo/samples | eb77df10fe39567b7ebf72b75dc8800e2470108a | 4691f529dae5c440a5df71deda40c57976ee4928 | refs/heads/develop | 2023-06-21T00:31:52.939554 | 2021-01-23T16:26:59 | 2021-01-23T16:26:59 | 66,746,116 | 0 | 0 | MIT | 2023-06-19T20:52:43 | 2016-08-28T02:48:20 | C | UTF-8 | C++ | false | false | 1,046 | hpp | //******************************************************************
//
// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#ifndef __OC_LOG_HPP_20140910
#define __OC_LOG_HPP_20140910
#include "oc_logger.h"
#include "oc_log_stream.hpp"
#include "targets/oc_console_logger.h"
#include "targets/oc_ostream_logger.h"
#endif
| [
"artemz@microsoft.com"
] | artemz@microsoft.com |
a9feebad607de513a0b89388802646dac3e3081f | 02c22f9cdab5fa3462469c827f76c505897f5b76 | /src/core/integrators/photon_map/Photon.hpp | f0f441916df8ca19d6a3a4561e9ffdfa5f052fae | [
"Zlib",
"BSD-3-Clause",
"MIT",
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"Unlicense",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | libingzeng/tungsten | 42070b9d64c66c2abc9de4b33a58eb30e0188aef | 8d3e08f6fe825ee90da9ab3e8008b45821ba3c67 | refs/heads/master | 2020-03-31T09:48:13.683372 | 2018-11-04T07:37:59 | 2018-11-04T07:37:59 | 152,111,453 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,336 | hpp | #ifndef PHOTON_HPP_
#define PHOTON_HPP_
#include "math/Vec.hpp"
namespace Tungsten {
struct Photon
{
uint32 splitData;
uint32 bounce;
Vec3f pos;
Vec3f dir;
Vec3f power;
void setSplitInfo(uint32 childIdx, uint32 splitDim, uint32 childCount)
{
uint32 childMask = childCount == 0 ? 0 : (childCount == 1 ? 1 : 3);
splitData = (splitDim << 30u) | (childMask << 28u) | childIdx;
}
bool hasLeftChild() const
{
return (splitData & (1u << 28u)) != 0;
}
bool hasRightChild() const
{
return (splitData & (1u << 29u)) != 0;
}
uint32 splitDim() const
{
return splitData >> 30u;
}
uint32 childIdx() const
{
return splitData & 0x0FFFFFFFu;
}
};
struct VolumePhoton : public Photon
{
Vec3f minBounds;
Vec3f maxBounds;
float radiusSq;
};
struct PathPhoton
{
Vec3f pos;
Vec3f power;
Vec3f dir;
float length;
float sampledLength;
uint32 data;
void setPathInfo(uint32 bounce, bool onSurface)
{
data = bounce;
if (onSurface)
data |= (1u << 31u);
}
bool onSurface() const
{
return (data & (1u << 31u)) != 0;
}
uint32 bounce() const
{
return data & ~(1u << 31u);
}
};
struct PhotonBeam
{
Vec3f p0, p1;
Vec3f dir;
float length;
Vec3f power;
int bounce;
bool valid;
};
struct PhotonPlane0D
{
Vec3f p0, p1, p2, p3;
Vec3f power;
Vec3f d1;
float l1;
int bounce;
bool valid;
Box3f bounds() const
{
Box3f box;
box.grow(p0);
box.grow(p1);
box.grow(p2);
box.grow(p3);
return box;
}
};
struct PhotonPlane1D
{
Vec3f p;
Vec3f invU, invV, invW;
Vec3f center, a, b, c;
Vec3f power;
Vec3f d1;
float l1;
float invDet;
float binCount;
int bounce;
bool valid;
Box3f bounds() const
{
Box3f box;
box.grow(center + a + b + c);
box.grow(center - a + b + c);
box.grow(center + a - b + c);
box.grow(center - a - b + c);
box.grow(center + a + b - c);
box.grow(center - a + b - c);
box.grow(center + a - b - c);
box.grow(center - a - b - c);
return box;
}
};
}
#endif /* PHOTON_HPP_ */
| [
"mail@noobody.org"
] | mail@noobody.org |
cd15ab34b66ef0c6ac0e93d2c9184a03748da5cb | 574c0dbf05e263357b32d58fc5e2af79a845b3e0 | /Engine_Graphics/include/ComputeShader.h | 859b09dd0e96333b17de497f6eb4dfb99a53660f | [
"MIT"
] | permissive | subr3v/s-engine | 8d2d5d2063f99231c4f7b95b8137037fe6252e1d | d77b9ccd0fff3982a303f14ce809691a570f61a3 | refs/heads/master | 2021-01-10T03:04:33.928634 | 2016-04-02T14:12:29 | 2016-04-02T14:12:29 | 55,234,945 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 911 | h | #ifndef ComputeShader_h__
#define ComputeShader_h__
#include <d3d11.h>
class FGraphicsContext;
class FShaderProgramInfo;
class FComputeShader
{
public:
FComputeShader(FGraphicsContext* GraphicsContext, const FShaderProgramInfo* ComputeShaderInfo);
~FComputeShader();
void Bind(ID3D11DeviceContext* DeviceContext);
void SetShaderResources(ID3D11DeviceContext* DeviceContext, ID3D11ShaderResourceView** Resources, int ResourceCount);
void SetShaderUnorderedAccessViews(ID3D11DeviceContext* DeviceContext, ID3D11UnorderedAccessView** Uavs, int UavsCount, const UINT* InitialCounts);
void SetShaderConstantBuffers(ID3D11DeviceContext* DeviceContext, ID3D11Buffer** Buffers, int BuffersCount);
void Execute(ID3D11DeviceContext* DeviceContext, int ThreadGroupCountX, int ThreadGroupCountY, int ThreadGroupCountZ);
private:
ID3D11ComputeShader* ComputeShader = nullptr;
};
#endif // ComputeShader_h__
| [
"subr3v@gmail.com"
] | subr3v@gmail.com |
906b39e70de12e65a3ab34d7030be09abfb766de | 75452de12ec9eea346e3b9c7789ac0abf3eb1d73 | /src/storage/fs_test/link.cc | ab8d7439e770cb0f6c1aae58b932ab98d79bf280 | [
"BSD-3-Clause"
] | permissive | oshunter/fuchsia | c9285cc8c14be067b80246e701434bbef4d606d1 | 2196fc8c176d01969466b97bba3f31ec55f7767b | refs/heads/master | 2022-12-22T11:30:15.486382 | 2020-08-16T03:41:23 | 2020-08-16T03:41:23 | 287,920,017 | 2 | 2 | BSD-3-Clause | 2022-12-16T03:30:27 | 2020-08-16T10:18:30 | C++ | UTF-8 | C++ | false | false | 12,907 | cc | // Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <optional>
#include <vector>
#include "src/storage/fs_test/fs_test_fixture.h"
#include "src/storage/fs_test/misc.h"
namespace fs_test {
namespace {
using HardLinkTest = FilesystemTest;
void CheckLinkCount(const std::string& path, unsigned count) {
struct stat s;
ASSERT_EQ(stat(path.c_str(), &s), 0);
ASSERT_EQ(s.st_nlink, count);
}
TEST_P(HardLinkTest, Basic) {
const std::string old_path = GetPath("a");
const std::string new_path = GetPath("b");
// Make a file, fill it with content
int fd = open(old_path.c_str(), O_RDWR | O_CREAT | O_EXCL, 0644);
ASSERT_GT(fd, 0);
uint8_t buf[100];
for (size_t i = 0; i < sizeof(buf); i++) {
buf[i] = (uint8_t)rand();
}
ASSERT_EQ(write(fd, buf, sizeof(buf)), static_cast<ssize_t>(sizeof(buf)));
ASSERT_NO_FATAL_FAILURE(CheckFileContents(fd, buf));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(old_path, 1));
ASSERT_EQ(link(old_path.c_str(), new_path.c_str()), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(old_path, 2));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(new_path, 2));
// Confirm that both the old link and the new links exist
int fd2 = open(new_path.c_str(), O_RDONLY, 0644);
ASSERT_GT(fd2, 0);
ASSERT_NO_FATAL_FAILURE(CheckFileContents(fd2, buf));
ASSERT_NO_FATAL_FAILURE(CheckFileContents(fd, buf));
// Remove the old link
ASSERT_EQ(close(fd), 0);
ASSERT_EQ(close(fd2), 0);
ASSERT_EQ(unlink(old_path.c_str()), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(new_path, 1));
// Open the link by its new name, and verify that the contents have
// not been altered by the removal of the old link.
fd = open(new_path.c_str(), O_RDONLY, 0644);
ASSERT_GT(fd, 0);
ASSERT_NO_FATAL_FAILURE(CheckFileContents(fd, buf));
ASSERT_EQ(close(fd), 0);
ASSERT_EQ(unlink(new_path.c_str()), 0);
}
TEST_P(HardLinkTest, test_link_count_dirs) {
ASSERT_EQ(mkdir(GetPath("dira").c_str(), 0755), 0);
// New directories should have two links:
// Parent --> newdir
// newdir ('.') --> newdir
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira"), 2));
// Adding a file won't change the parent link count...
int fd = open(GetPath("dira/file").c_str(), O_RDWR | O_CREAT | O_EXCL, 0644);
ASSERT_GT(fd, 0);
ASSERT_EQ(close(fd), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira"), 2));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira/file"), 1));
// But adding a directory WILL change the parent link count.
ASSERT_EQ(mkdir(GetPath("dira/dirb").c_str(), 0755), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira/dirb"), 2));
// Test that adding "depth" increases the dir count as we expect.
ASSERT_EQ(mkdir(GetPath("dira/dirb/dirc").c_str(), 0755), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira/dirb"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira/dirb/dirc"), 2));
// Demonstrate that unwinding also reduces the link count.
ASSERT_EQ(unlink(GetPath("dira/dirb/dirc").c_str()), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira/dirb"), 2));
ASSERT_EQ(unlink(GetPath("dira/dirb").c_str()), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira"), 2));
// Test that adding "width" increases the dir count too.
ASSERT_EQ(mkdir(GetPath("dira/dirb").c_str(), 0755), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira/dirb"), 2));
ASSERT_EQ(mkdir(GetPath("dira/dirc").c_str(), 0755), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira"), 4));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira/dirb"), 2));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira/dirc"), 2));
// Demonstrate that unwinding also reduces the link count.
ASSERT_EQ(unlink(GetPath("dira/dirc").c_str()), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira/dirb"), 2));
ASSERT_EQ(unlink(GetPath("dira/dirb").c_str()), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira"), 2));
ASSERT_EQ(unlink(GetPath("dira/file").c_str()), 0);
ASSERT_EQ(unlink(GetPath("dira").c_str()), 0);
}
TEST_P(HardLinkTest, CorrectLinkCountAfterRename) {
// Check that link count does not change with simple rename
ASSERT_EQ(mkdir(GetPath("dir").c_str(), 0755), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir"), 2));
ASSERT_EQ(rename(GetPath("dir").c_str(), GetPath("dir_parent").c_str()), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent"), 2));
// Set up parent directory with child directories
ASSERT_EQ(mkdir(GetPath("dir_parent/dir_child_a").c_str(), 0755), 0);
ASSERT_EQ(mkdir(GetPath("dir_parent/dir_child_b").c_str(), 0755), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent"), 4));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent/dir_child_a"), 2));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent/dir_child_b"), 2));
// Rename a child directory out of its parent directory
ASSERT_EQ(rename(GetPath("dir_parent/dir_child_b").c_str(), GetPath("dir_parent_alt").c_str()),
0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent/dir_child_a"), 2));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt"), 2));
// Rename a parent directory into another directory
ASSERT_EQ(
rename(GetPath("dir_parent").c_str(), GetPath("dir_parent_alt/dir_semi_parent").c_str()), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt/dir_semi_parent"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt/dir_semi_parent/dir_child_a"), 2));
// Rename a directory on top of an empty directory
ASSERT_EQ(mkdir(GetPath("dir_child").c_str(), 0755), 0);
ASSERT_EQ(rename(GetPath("dir_child").c_str(),
GetPath("dir_parent_alt/dir_semi_parent/dir_child_a").c_str()),
0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt/dir_semi_parent"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt/dir_semi_parent/dir_child_a"), 2));
// Rename a directory on top of an empty directory from a non-root directory
ASSERT_EQ(mkdir(GetPath("dir").c_str(), 0755), 0);
ASSERT_EQ(mkdir(GetPath("dir/dir_child").c_str(), 0755), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir/dir_child"), 2));
ASSERT_EQ(rename(GetPath("dir/dir_child").c_str(),
GetPath("dir_parent_alt/dir_semi_parent/dir_child_a").c_str()),
0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir"), 2));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt/dir_semi_parent"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt/dir_semi_parent/dir_child_a"), 2));
// Rename a file on top of a file from a non-root directory
ASSERT_EQ(unlink(GetPath("dir_parent_alt/dir_semi_parent/dir_child_a").c_str()), 0);
int fd = open(GetPath("dir/dir_child").c_str(), O_RDWR | O_CREAT | O_EXCL, 0644);
ASSERT_GT(fd, 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir"), 2));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir/dir_child"), 1));
int fd2 = open(GetPath("dir_parent_alt/dir_semi_parent/dir_child_a").c_str(),
O_RDWR | O_CREAT | O_EXCL, 0644);
ASSERT_GT(fd2, 0);
ASSERT_EQ(rename(GetPath("dir/dir_child").c_str(),
GetPath("dir_parent_alt/dir_semi_parent/dir_child_a").c_str()),
0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir"), 2));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt/dir_semi_parent"), 2));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt/dir_semi_parent/dir_child_a"), 1));
ASSERT_EQ(close(fd), 0);
ASSERT_EQ(close(fd2), 0);
// Clean up
ASSERT_EQ(unlink(GetPath("dir_parent_alt/dir_semi_parent/dir_child_a").c_str()), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt/dir_semi_parent"), 2));
ASSERT_EQ(unlink(GetPath("dir_parent_alt/dir_semi_parent").c_str()), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt"), 2));
ASSERT_EQ(unlink(GetPath("dir_parent_alt").c_str()), 0);
ASSERT_EQ(unlink(GetPath("dir").c_str()), 0);
}
TEST_P(HardLinkTest, AcrossDirectories) {
ASSERT_EQ(mkdir(GetPath("dira").c_str(), 0755), 0);
// New directories should have two links:
// Parent --> newdir
// newdir ('.') --> newdir
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira"), 2));
ASSERT_EQ(mkdir(GetPath("dirb").c_str(), 0755), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dirb"), 2));
const std::string old_path = GetPath("dira/a");
const std::string new_path = GetPath("dirb/b");
// Make a file, fill it with content
int fd = open(old_path.c_str(), O_RDWR | O_CREAT | O_EXCL, 0644);
ASSERT_GT(fd, 0);
uint8_t buf[100];
for (size_t i = 0; i < sizeof(buf); i++) {
buf[i] = (uint8_t)rand();
}
ASSERT_EQ(write(fd, buf, sizeof(buf)), static_cast<ssize_t>(sizeof(buf)));
ASSERT_NO_FATAL_FAILURE(CheckFileContents(fd, buf));
ASSERT_EQ(link(old_path.c_str(), new_path.c_str()), 0);
// Confirm that both the old link and the new links exist
int fd2 = open(new_path.c_str(), O_RDWR, 0644);
ASSERT_GT(fd2, 0);
ASSERT_NO_FATAL_FAILURE(CheckFileContents(fd2, buf));
ASSERT_NO_FATAL_FAILURE(CheckFileContents(fd, buf));
// Remove the old link
ASSERT_EQ(close(fd), 0);
ASSERT_EQ(close(fd2), 0);
ASSERT_EQ(unlink(old_path.c_str()), 0);
// Open the link by its new name
fd = open(new_path.c_str(), O_RDWR, 0644);
ASSERT_GT(fd, 0);
ASSERT_NO_FATAL_FAILURE(CheckFileContents(fd, buf));
ASSERT_EQ(close(fd), 0);
ASSERT_EQ(unlink(new_path.c_str()), 0);
ASSERT_EQ(unlink(GetPath("dira").c_str()), 0);
ASSERT_EQ(unlink(GetPath("dirb").c_str()), 0);
}
TEST_P(HardLinkTest, Errors) {
const std::string dir_path = GetPath("dir");
const std::string old_path = GetPath("a");
const std::string new_path = GetPath("b");
const std::string new_path_dir = GetPath("b/");
// We should not be able to create hard links to directories
ASSERT_EQ(mkdir(dir_path.c_str(), 0755), 0);
ASSERT_EQ(link(dir_path.c_str(), new_path.c_str()), -1);
ASSERT_EQ(unlink(dir_path.c_str()), 0);
// We should not be able to create hard links to non-existent files
ASSERT_EQ(link(old_path.c_str(), new_path.c_str()), -1);
ASSERT_EQ(errno, ENOENT);
int fd = open(old_path.c_str(), O_RDWR | O_CREAT | O_EXCL, 0644);
ASSERT_GT(fd, 0);
ASSERT_EQ(close(fd), 0);
// We should not be able to link to or from . or ..
ASSERT_EQ(link(old_path.c_str(), GetPath(".").c_str()), -1);
ASSERT_EQ(link(old_path.c_str(), GetPath("..").c_str()), -1);
ASSERT_EQ(link(GetPath(".").c_str(), new_path.c_str()), -1);
ASSERT_EQ(link(GetPath("..").c_str(), new_path.c_str()), -1);
// We should not be able to link a file to itself
ASSERT_EQ(link(old_path.c_str(), old_path.c_str()), -1);
ASSERT_EQ(errno, EEXIST);
// We should not be able to link a file to a path that implies it must be a directory
ASSERT_EQ(link(old_path.c_str(), new_path_dir.c_str()), -1);
// After linking, we shouldn't be able to link again
ASSERT_EQ(link(old_path.c_str(), new_path.c_str()), 0);
ASSERT_EQ(link(old_path.c_str(), new_path.c_str()), -1);
ASSERT_EQ(errno, EEXIST);
// In either order
ASSERT_EQ(link(new_path.c_str(), old_path.c_str()), -1);
ASSERT_EQ(errno, EEXIST);
ASSERT_EQ(unlink(new_path.c_str()), 0);
ASSERT_EQ(unlink(old_path.c_str()), 0);
}
INSTANTIATE_TEST_SUITE_P(
/*no prefix*/, HardLinkTest,
testing::ValuesIn(MapAndFilterAllTestFilesystems(
[](const TestFilesystemOptions& options) -> std::optional<TestFilesystemOptions> {
if (options.filesystem->GetTraits().supports_hard_links) {
return options;
} else {
return std::nullopt;
}
})),
testing::PrintToStringParamName());
} // namespace
} // namespace fs_test
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
9a0f0484baf335c54b14c235ec39e910a255c40b | d32424b20ae663a143464a9277f8090bd017a7f6 | /arsenal/datastructure/BinaryTree/Traversal.cpp | 13b2ccf10e67bc8c895ab158b41e8b11b1a02f1e | [] | no_license | Vesion/Misirlou | a8df716c17a3072e5cf84b5e279c06e2eac9e6a7 | 95274c8ccb3b457d5e884bf26948b03967b40b32 | refs/heads/master | 2023-05-01T10:05:40.709033 | 2023-04-22T18:41:29 | 2023-04-22T18:43:05 | 51,061,447 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,296 | cpp | #include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <stack>
#include <queue>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v) : val(v), left(NULL), right(NULL) {}
};
// preorder / inorder / postorder / level order
// recursively + iteratively
// preorder traverse, recursively
class Solution_pre_re {
public:
void preorder(TreeNode* root) {
if (root) {
cout << root->val << " ";
preorder(root->left);
preorder(root->right);
}
}
};
// preorder traverse, stack
class Solution_pre_it {
public:
void preorder(TreeNode* root) {
if (!root) return;
stack<TreeNode*> st;
st.push(root);
while (!st.empty()) {
TreeNode* p = st.top(); st.pop();
cout << p->val << " ";
if (p->right) st.push(p->right);
if (p->left) st.push(p->left);
}
}
};
// inorder traverse, recursively
class Solution_in_re {
public:
void inorder(TreeNode* root) {
if (root) {
inorder(root->left);
cout << root->val << " ";
inorder(root->right);
}
}
};
// inorder traverse, stack
class Solution_in_it {
public:
void inorder(TreeNode* root) {
if (!root) return;
stack<TreeNode*> st;
TreeNode* p = root;
while (!st.empty() || p) {
if (p) {
st.push(p);
p = p->left;
} else {
p = st.top(); st.pop();
cout << p->val;
p = p->right;
}
}
}
};
// postorder traverse, recursively
class Solution_post_re {
public:
void postorder(TreeNode* root) {
if (root) {
postorder(root->left);
postorder(root->right);
cout << root->val << " ";
}
}
};
// postorder traverse, stack
class Solution_post_it {
public:
void postorder(TreeNode* root) {
if (!root) return;
TreeNode* pre = NULL; // the last poped node
TreeNode* cur = root;
stack<TreeNode*> st;
while (cur || !st.empty()) {
if (cur) {
st.push(cur);
cur = cur->left;
} else {
TreeNode* t = st.top();
if (t->right && t->right != pre)
cur = t->right;
else {
cout << t->val << " ";
pre = t;
st.pop();
}
}
}
}
};
// level traverse, queue
class Solution_level {
public:
void levelorder(TreeNode* root) {
if (!root) return;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* p = q.front(); q.pop();
cout << p->val << " ";
if (p->left) q.push(p->left);
if (p->right) q.push(p->right);
}
}
};
int main() {
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);
return 0;
}
| [
"xuxiang19930924@126.com"
] | xuxiang19930924@126.com |
499a464d33c11783fd3171e0923f6fd7ae3e73d2 | 44ab461147c679c6f654b5ca8643557e1033ffb9 | /geo_normal_3d_omp.cpp | 8af6006bb32a07c23e37e642f6151e1129950c3c | [
"BSD-3-Clause"
] | permissive | snowmanman/structrock | 767e6f5544aae48e1d70e2c3cf56091f5e7ff40f | 754d8c481d22a48ea7eb4e055eb16c64c44055ab | refs/heads/master | 2021-07-31T01:03:37.715307 | 2020-07-16T07:32:03 | 2020-07-16T07:32:03 | 193,132,993 | 1 | 1 | BSD-3-Clause | 2019-06-21T16:56:32 | 2019-06-21T16:56:32 | null | UTF-8 | C++ | false | false | 2,019 | cpp | /*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*
*/
#include <pcl/point_types.h>
#include <pcl/impl/instantiate.hpp>
#include "geo_normal_3d_omp.h"
// Instantiations of specific point types
template class GeoNormalEstimationOMP<pcl::PointXYZ, pcl::Normal>;
template class GeoNormalEstimationOMP<pcl::PointXYZRGB, pcl::Normal>;
| [
"WXGHolmes@Gmail.com"
] | WXGHolmes@Gmail.com |
32663debfe682c9ef244f125e9ee675f6fb00ad2 | cfeac52f970e8901871bd02d9acb7de66b9fb6b4 | /generated/src/aws-cpp-sdk-ec2/source/model/GetCoipPoolUsageRequest.cpp | daee2872508f86176bd7096dfac25ef966e7efb8 | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | aws/aws-sdk-cpp | aff116ddf9ca2b41e45c47dba1c2b7754935c585 | 9a7606a6c98e13c759032c2e920c7c64a6a35264 | refs/heads/main | 2023-08-25T11:16:55.982089 | 2023-08-24T18:14:53 | 2023-08-24T18:14:53 | 35,440,404 | 1,681 | 1,133 | Apache-2.0 | 2023-09-12T15:59:33 | 2015-05-11T17:57:32 | null | UTF-8 | C++ | false | false | 1,481 | cpp | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/ec2/model/GetCoipPoolUsageRequest.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
using namespace Aws::EC2::Model;
using namespace Aws::Utils;
GetCoipPoolUsageRequest::GetCoipPoolUsageRequest() :
m_poolIdHasBeenSet(false),
m_filtersHasBeenSet(false),
m_maxResults(0),
m_maxResultsHasBeenSet(false),
m_nextTokenHasBeenSet(false),
m_dryRun(false),
m_dryRunHasBeenSet(false)
{
}
Aws::String GetCoipPoolUsageRequest::SerializePayload() const
{
Aws::StringStream ss;
ss << "Action=GetCoipPoolUsage&";
if(m_poolIdHasBeenSet)
{
ss << "PoolId=" << StringUtils::URLEncode(m_poolId.c_str()) << "&";
}
if(m_filtersHasBeenSet)
{
unsigned filtersCount = 1;
for(auto& item : m_filters)
{
item.OutputToStream(ss, "Filter.", filtersCount, "");
filtersCount++;
}
}
if(m_maxResultsHasBeenSet)
{
ss << "MaxResults=" << m_maxResults << "&";
}
if(m_nextTokenHasBeenSet)
{
ss << "NextToken=" << StringUtils::URLEncode(m_nextToken.c_str()) << "&";
}
if(m_dryRunHasBeenSet)
{
ss << "DryRun=" << std::boolalpha << m_dryRun << "&";
}
ss << "Version=2016-11-15";
return ss.str();
}
void GetCoipPoolUsageRequest::DumpBodyToUrl(Aws::Http::URI& uri ) const
{
uri.SetQueryString(SerializePayload());
}
| [
"sdavtaker@users.noreply.github.com"
] | sdavtaker@users.noreply.github.com |
47884bfb4ca1d013c02678a75adb9a24b49fd605 | 9614eda056137277b2da5097ceb7583cb9a42fdb | /Cluedo/room.h | 2ce431fa326f72357d6fa5ef2baeb5a429a32449 | [] | no_license | CPeacockEngineeringLTD/Cluedo | 4a6ddb58dbf80296706ccf5f7385abac471a20df | 34ce55c406c0f4c498b90b235ac87cff39405146 | refs/heads/master | 2023-06-03T12:13:34.889883 | 2021-06-26T08:37:39 | 2021-06-26T08:37:39 | 324,749,885 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 185 | h | #pragma once
#include <string>
#include <chrono>
class room{
public:
static std::wstring getContents(int a);
static void chooseMurder();
static bool checkMurder(int a);
};
| [
"clegguy@hotmail.co.uk"
] | clegguy@hotmail.co.uk |
c582935ddb500b1c672fe3d0ad22dd3b33fac7c9 | 208650de138a6b05b8b8e7e4ca6df9dc72290402 | /Contests/LT/2.cpp | 420328deba7462ff448ab5cfa78a75c8458fe0c1 | [] | no_license | cs15b047/CF | 9fcf83c5fd09124b6eaebbd4ecd67d19a1302582 | d220d73a2d8739bbb10f4ed71437c06625870490 | refs/heads/master | 2021-08-20T06:21:24.577260 | 2021-06-09T04:56:47 | 2021-06-09T04:57:29 | 177,541,957 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 768 | cpp | #include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
int main(int argc, char const *argv[])
{
ll t;scanf("%lld",&t);
for(int i=0;i<t;i++){
ll n,m;scanf("%lld%lld",&n,&m);
vector<string>grid;grid.clear();grid.resize(n);
for(int j=0;j<n;j++)cin >> grid[j];
bool flag = true;
if((n<=1) || (m<=1))flag=0;
for(int j=0;j<n;j++){
for(int k=0;k<m;k++){
if(grid[j][k] == '.'){
if(j==0){
bool c1=0;
if(k!=m-1)c1 = c1 || (grid[j+1][k] != "#") && (grid[j+1][k+1] != "#") && (grid[j][k+1] != "#") ;
if(k!=0)c1 = c1 || (grid[j+1][k] != "#") && (grid[j+1][k-1] != "#") && (grid[j][k-1]!="#") ;
}
}
if(!flag)break;
}
if(!flag)break;
}
if(!flag)cout << "NO"<< endl;
else cout << "YES" << endl;
}
} | [
"cs15b047@smail.iitm.ac.in"
] | cs15b047@smail.iitm.ac.in |
12ad3191dc3e63ddff4a944b9700f009a7a79028 | 762d0c7c44687373bf643624c8ac616cb08cd227 | /Espresso Shot/src/Espresso/main.cpp | 56050ded678e29d7e6daa7fe8b711b9ddc9e7e7f | [
"MIT"
] | permissive | Promethaes/Espresso-Shot-Engine | eba955c95cbbce03cb22051bd055ae89a499d984 | 6dffcbd5e69708af2f8251b701b7052207162e9b | refs/heads/master | 2020-07-17T03:27:23.751072 | 2019-09-10T02:56:06 | 2019-09-10T02:56:06 | 205,931,611 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,235 | cpp | #include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <Fmod/fmod.h>
#include <Fmod/fmod_common.h>
#include <Fmod/fmod.hpp>
#include <Fmod/fmod_errors.h>
#include <iostream>
#include <vector>
#include <time.h>
#include "Espresso/Camera.h"
#include "Espresso/ShaderProgram.h"
#include "Espresso/XinputManager.h"
#include "Espresso/Scene Manager.h"
#include "Espresso/Test Scene.h"
#include "Espresso/f16.h"
#define _CRT_SECURE_NO_WARNINGS
#define Scenes Espresso::Scene::scenes
#define GameObjects Espresso::GameObject::gameObjects
#define ESPRESSOSHOTPATH std::string(std::getenv("EspressoShotPath"))
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(Espresso::Camera& defaultCamera, float dt, GLFWwindow* window);
void mouse_callback(GLFWwindow* window, double xpos, double ypos);
//settings, might change from globals to something else
float lastX = 400, lastY = 300;
float yaw = -90.0f;
float pitch = 0.0f;
bool firstMouse = true;
Espresso::Camera* defaultCamera = new Espresso::Camera();
float dt = 0.0f; // Time between current frame and last frame
float lastFrame = 0.0f; // Time of last frame
int main() {
srand(time(0));
//initialize glfw
#pragma region InitialzeGLFW
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
GLFWwindow* window = glfwCreateWindow(800 * 2, 600 * 2, "Espresso Test", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << "\n";
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glfwSetCursorPosCallback(window, mouse_callback);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << "\n";
return -1;
}
//end initialization
#pragma endregion
#pragma region InitializeFmod
///This code is NOT mine, it is from <https://www.fmod.com/resources/documentation-api?version=2.0&page=white-papers-getting-started.html>
FMOD_RESULT result;
FMOD::System* system = NULL;
result = FMOD::System_Create(&system); // Create the main system object.
if (result != FMOD_OK)
{
printf("FMOD error! (%d) %s\n", result, FMOD_ErrorString(result));
exit(-1);
}
result = system->init(512, FMOD_INIT_NORMAL, 0); // Initialize FMOD.
if (result != FMOD_OK)
{
printf("FMOD error! (%d) %s\n", result, FMOD_ErrorString(result));
exit(-1);
}
#pragma endregion
///FMOD::Sound** sound = nullptr;
///FMOD::ChannelGroup** group1;
///std::string soundPath = ESPRESSOSHOTPATH + "Assets/Sound/testSound.mp3";
///auto soundHandle = system->createSound(soundPath.c_str(),FMOD_2D ,new FMOD_CREATESOUNDEXINFO(),sound);
///auto channelGHandle = system->createChannelGroup("group1", group1);
///FMOD::Channel** channel = nullptr;
///
///system->playSound(*sound, *group1, false, channel);
Espresso::Shader lightingShader(ESPRESSOSHOTPATH + "Assets/Shaders/lightingShader.vert", ESPRESSOSHOTPATH + "Assets/Shaders/lightingShader.frag");
Sedna::XinputManager* manager = new Sedna::XinputManager();
Sedna::XinputController* controller = manager->getController(0);
bool f16Test = false;
bool sceneTest = true;
if (f16Test == true)
sceneTest = true;
//if (f16Test)
// Espresso::F16 f16(Espresso::Mesh(ESPRESSOSHOTPATH + "Assets/Mesh/f16.obj"), lightingShader, manager, 0);
//run this scene
if (sceneTest)
Espresso::TestScene* s = new Espresso::TestScene(true);
glEnable(GL_DEPTH_TEST);
//render loop
while (!glfwWindowShouldClose(window))
{
float currentFrame = glfwGetTime();
dt = currentFrame - lastFrame;
lastFrame = currentFrame;
processInput(*defaultCamera, dt, window);
glClearColor(0.33f, 0.33f, 0.33f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//manager->update();
for (unsigned i = 0; i < Scenes.size(); i++) {
if (!Scenes[i]->isInit())
Scenes[i]->init();
if (Scenes[i]->isInit())
Scenes[i]->baseUpdate(dt, *defaultCamera);
}
for (auto x : GameObjects)
x->baseUpdate(dt);
glfwSwapBuffers(window);
glfwPollEvents();
}
//end of program
glfwTerminate();
return 0;
}
void processInput(Espresso::Camera& defaultCamera, float dt, GLFWwindow* window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
defaultCamera.move(window, 2.5f * dt);
}
void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
if (firstMouse)
{
lastX = xpos;
lastY = ypos;
firstMouse = false;
}
float xoffset = xpos - lastX;
float yoffset = lastY - ypos;
lastX = xpos;
lastY = ypos;
defaultCamera->doMouseMovement(xoffset, yoffset);
}
void framebuffer_size_callback(GLFWwindow* window, int width, int height) {
glViewport(0, 0, width, height);
} | [
"anth19800@hotmail.com"
] | anth19800@hotmail.com |
acb9df39bd96bba5f0d39befbd0c510017a27ba5 | 28dba754ddf8211d754dd4a6b0704bbedb2bd373 | /Topcoder/FiveHundredEleven.cpp | fc0ab1ccbd74c616c6787170b50421e79a72bca9 | [] | no_license | zjsxzy/algo | 599354679bd72ef20c724bb50b42fce65ceab76f | a84494969952f981bfdc38003f7269e5c80a142e | refs/heads/master | 2023-08-31T17:00:53.393421 | 2023-08-19T14:20:31 | 2023-08-19T14:20:31 | 10,140,040 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,684 | cpp | #line 2 "FiveHundredEleven.cpp"
#include <map>
#include <set>
#include <list>
#include <cmath>
#include <queue>
#include <stack>
#include <bitset>
#include <vector>
#include <cstdio>
#include <string>
#include <sstream>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
int dp[555][55];
vector<int> c;
int n;
int dfs(int mem, int played)
{
if (mem == 511) return 1;
if (played == n) return 0;
int &res = dp[mem][played];
if (res == -1)
{
res = false;
int cnt = 0;
for (int i = 0; i < n; i++)
if ((mem | c[i]) == mem)
{
cnt++;
}
if (cnt > played && !dfs(mem, played + 1))
res = true;
for (int i = 0; i < n; i++)
if ((mem | c[i]) != mem && !dfs((mem | c[i]), played + 1))
res = true;
}
return res;
}
class FiveHundredEleven
{
public:
string theWinner(vector <int> cards)
{
memset(dp, -1, sizeof(dp));
c = cards;
n = c.size();
return dfs(0, 0) ? "Fox Ciel" : "Toastman";
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arr0[] = {3, 5, 7, 9, 510}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "Fox Ciel"; verify_case(0, Arg1, theWinner(Arg0)); }
void test_case_1() { int Arr0[] = {0, 0, 0, 0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "Toastman"; verify_case(1, Arg1, theWinner(Arg0)); }
void test_case_2() { int Arr0[] = {511}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "Toastman"; verify_case(2, Arg1, theWinner(Arg0)); }
void test_case_3() { int Arr0[] = {5, 58, 192, 256}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "Fox Ciel"; verify_case(3, Arg1, theWinner(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
FiveHundredEleven ___test;
for (int i = 0; i <= 5; i++)
___test.run_test(i);
return 0;
}
// END CUT HERE
| [
"zjsxzy@gmail.com"
] | zjsxzy@gmail.com |
5b5d13f0c89a783af659e096a9c2448a3894259e | 7b80d8166c41e164db46403cf10c2e5300238dd6 | /APP/COMMON/InvBusinessFunc.cpp | d93d0955fda11c65e705f6ba21af4ca7bd654d60 | [] | no_license | duanwenhuiIMAU/SKJ_FWSK_1.0000 | d7a3862d1f02d1a62a6726fd7efc3d348c666383 | 004d47182ebca13428d78500a0425ada195c5e7b | refs/heads/master | 2020-04-27T13:39:35.511980 | 2015-09-16T09:45:36 | 2015-09-16T09:46:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,910 | cpp |
#include "InvBusinessFunc.h"
#include "commonFunc.h"
#include "YWXML_FPDR.h"
#include "YWXML_BSPFPFF.h"
#include "YWXML_BSPFPSH.h"
#include "YWXML_FJTH.h"
#include "YWXML_GPXXXP.h"
#include "YWXML_GPXXXPJS.h"
#include "YWXML_BSPFPCX.h"
#include "BusinessBase.h"
#include "LOGCTRL.h"
//#define NO_POS_DEBUG
#include "pos_debug.h"
CInvBusinessFunc::CInvBusinessFunc()
{
}
CInvBusinessFunc::~CInvBusinessFunc()
{
}
INT32 CInvBusinessFunc::BSPFPCXPro(CYWXML_GY &ywxml_gy, UINT32 &InvCount, CInvVol *pInvVol, string &strErr)
{
INT32 ret = SUCCESS;
ret = g_pBusBase->BSPFPCX_Business(ywxml_gy, InvCount, pInvVol, strErr);
return g_pBusBase->ErrParse(ret, strErr);;
}
INT32 CInvBusinessFunc::InvReadIn(CYWXML_GY &ywxml_gy, UINT8 strJzlx, string &strErr)
{
INT32 ret = SUCCESS;
ret = g_pBusBase->FPDR_Business(ywxml_gy, strJzlx, strErr);
return g_pBusBase->ErrParse(ret, strErr);;
}
INT32 CInvBusinessFunc::ZJInvDistribute(CYWXML_GY &ywxml_gy, CInvVol *pInvVol, UINT8 strJzlx, string &strErr)
{
INT32 ret = SUCCESS;
ret = g_pBusBase->BSPFPFF_Business(ywxml_gy, strJzlx, pInvVol, strErr);
return g_pBusBase->ErrParse(ret, strErr);;
}
INT32 CInvBusinessFunc::ZJInvRecover(CYWXML_GY &ywxml_gy, CInvVol *pInvVol, UINT8 strJzlx, string &strErr)
{
INT32 ret = SUCCESS;
ret = g_pBusBase->BSPFPSH_Business(ywxml_gy, strJzlx, pInvVol, strErr);
return g_pBusBase->ErrParse(ret, strErr);;
}
INT32 CInvBusinessFunc::FJInvReturn(CYWXML_GY &ywxml_gy, UINT8 strJzlx, string &strErr)
{
INT32 ret = SUCCESS;
ret = g_pBusBase->FJTH_Business(ywxml_gy, strJzlx, strErr);
return g_pBusBase->ErrParse(ret, strErr);;
}
INT32 CInvBusinessFunc::TJXXCXPro(CYWXML_GY &ywxml_gy, INT32 &monthcount, CTjxxhz *pTjxxhz, string &strErr)
{
INT32 ret = SUCCESS;
ret = g_pBusBase->TJXXCX_Business(ywxml_gy, monthcount, pTjxxhz, strErr);
return g_pBusBase->ErrParse(ret, strErr);
}
INT32 CInvBusinessFunc::WLLQFPPro(CYWXML_GY &ywxml_gy, CInvVol *pInvVol, string &strErr)
{
INT32 ret = SUCCESS;
UINT8 xxlx = SKSBQTYXXCX_XXLX_WLLQFPJGQR;
string sksbxx("");
ret = g_pBusBase->SKSBQTYXXCX_Business(ywxml_gy, xxlx, sksbxx, strErr);
ret = g_pBusBase->ErrParse(ret, strErr);
if(ret != SUCCESS)
{
return FAILURE;
}
if(sksbxx.length() > 0)
{
DBG_PRINT(("here"));
ret = g_pBusBase->WLLQFPJGQR_Business(ywxml_gy, pInvVol, sksbxx, strErr);
ret = g_pBusBase->ErrParse(ret, strErr);
if(ret != SUCCESS)
{
return FAILURE;
}
ret = g_pBusBase->GPXXXPJS_Business(ywxml_gy, pInvVol->m_fpjjsmw, strErr);
ret = g_pBusBase->ErrParse(ret, strErr);
if(ret != SUCCESS)
{
return FAILURE;
}
}
else
{
DBG_PRINT(("here"));
xxlx = SKSBQTYXXCX_XXLX_WLLQFP;
ret = g_pBusBase->SKSBQTYXXCX_Business(ywxml_gy, xxlx, sksbxx, strErr);
ret = g_pBusBase->ErrParse(ret, strErr);
if(ret != SUCCESS)
{
return FAILURE;
}
ret = g_pBusBase->WLLQFP_Business(ywxml_gy, pInvVol, sksbxx, strErr);
ret = g_pBusBase->ErrParse(ret, strErr);
if(ret != SUCCESS)
{
return FAILURE;
}
ret = g_pBusBase->GPXXXP_Business(ywxml_gy, pInvVol->m_fpjmw, strErr);
ret = g_pBusBase->ErrParse(ret, strErr);
if(ret != SUCCESS)
{
return FAILURE;
}
CommonSleep(1000);
ret = WLLQFPJGQRPro(ywxml_gy, pInvVol, strErr);
}
return ret;
}
INT32 CInvBusinessFunc::WLLQFPJGQRPro(CYWXML_GY &ywxml_gy, CInvVol *pInvVol, string &strErr)
{
INT32 ret = SUCCESS;
UINT8 xxlx = SKSBQTYXXCX_XXLX_WLLQFPJGQR;
string sksbxx("");
ret = g_pBusBase->SKSBQTYXXCX_Business(ywxml_gy, xxlx, sksbxx, strErr);
ret = g_pBusBase->ErrParse(ret, strErr);
if(ret != SUCCESS)
{
return FAILURE;
}
ret = g_pBusBase->WLLQFPJGQR_Business(ywxml_gy, pInvVol, sksbxx, strErr);
ret = g_pBusBase->ErrParse(ret, strErr);
if(ret != SUCCESS)
{
return FAILURE;
}
ret = g_pBusBase->GPXXXPJS_Business(ywxml_gy, pInvVol->m_fpjjsmw, strErr);
ret = g_pBusBase->ErrParse(ret, strErr);
return ret;
}
| [
"zhangchaoyang@aisino.com"
] | zhangchaoyang@aisino.com |
7149fc13ad7642c91ce070746fee5cd3991ae785 | fe5223cead58a475e43d5289a695d01aab1ec15f | /hphp/compiler/type_annotation.cpp | 19bdd7532fe87e74faeb90329e7d7fb1953ae62e | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-generic-cla",
"PHP-3.01",
"Zend-2.0"
] | permissive | zilberstein/hhvm | ca188c730f5bdbdfb3f3ed0867418a6bcf6ec1b6 | 34f129dce3a7686d32e1ace6b0f6ba03013d7b6e | refs/heads/master | 2021-01-15T10:07:12.837945 | 2014-02-28T20:08:48 | 2014-02-28T20:08:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,187 | cpp | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2014 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/compiler/type_annotation.h"
#include "hphp/util/util.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
// constructors/destructors
TypeAnnotation::TypeAnnotation(const std::string &name,
TypeAnnotationPtr typeArgs) : m_name(name),
m_typeArgs(typeArgs),
m_typeList(TypeAnnotationPtr()),
m_nullable(false),
m_soft(false),
m_tuple(false),
m_function(false),
m_xhp(false),
m_typevar(false) { }
std::string TypeAnnotation::vanillaName() const {
// filter out types that should not be exposed to the runtime
if (m_nullable || m_soft || m_typevar || m_function) {
return "";
}
if (!m_name.compare("mixed") || !m_name.compare("this")) {
return "";
}
return m_name;
}
std::string TypeAnnotation::fullName() const {
std::string name;
if (m_soft) {
name += '@';
}
if (m_nullable) {
name += '?';
}
if (m_function) {
functionTypeName(name);
} else if (m_xhp) {
xhpTypeName(name);
} else if (m_tuple) {
tupleTypeName(name);
} else if (m_typeArgs) {
genericTypeName(name);
} else {
name += m_name;
}
return name;
}
DataType TypeAnnotation::dataType(bool expectedType /*= false */) const {
if (m_function || m_xhp || m_tuple) {
return KindOfObject;
}
if (m_typeArgs) {
return !m_name.compare("array") ? KindOfArray : KindOfObject;
}
if (!expectedType && (m_nullable || m_soft)) {
return KindOfUnknown;
}
if (!m_name.compare("null") || !m_name.compare("void")) {
return KindOfNull;
}
if (!m_name.compare("bool")) return KindOfBoolean;
if (!m_name.compare("int")) return KindOfInt64;
if (!m_name.compare("float")) return KindOfDouble;
if (!m_name.compare("num")) return KindOfUnknown;
if (!m_name.compare("string")) return KindOfString;
if (!m_name.compare("array")) return KindOfArray;
if (!m_name.compare("resource")) return KindOfResource;
if (!m_name.compare("mixed")) return KindOfUnknown;
return KindOfObject;
}
void TypeAnnotation::getAllSimpleNames(std::vector<std::string>& names) const {
names.push_back(m_name);
if (m_typeList) {
m_typeList->getAllSimpleNames(names);
} else if (m_typeArgs) {
m_typeArgs->getAllSimpleNames(names);
}
}
void TypeAnnotation::functionTypeName(std::string &name) const {
name += "(function (";
// return value of function types is the first element of type list
TypeAnnotationPtr retType = m_typeArgs;
TypeAnnotationPtr typeEl = m_typeArgs->m_typeList;
bool hasArgs = (typeEl != nullptr);
while (typeEl) {
name += typeEl->fullName();
typeEl = typeEl->m_typeList;
name += ", ";
}
// replace the trailing ", " (if any) with "): "
if (hasArgs) {
name.replace(name.size() - 2, 2, "): ");
} else {
name += "): ";
}
// add function return value
name += retType->fullName();
name += ")";
}
// xhp names are mangled so we get them back to their original definition
// @see the mangling in ScannerToken::xhpLabel
void TypeAnnotation::xhpTypeName(std::string &name) const {
// remove prefix if any
if (m_name.compare(0, sizeof("xhp_") - 1, "xhp_") == 0) {
name += std::string(m_name).replace(0, sizeof("xhp_") - 1, ":");
} else {
name += m_name;
}
// un-mangle back
Util::replaceAll(name, "__", ":");
Util::replaceAll(name, "_", "-");
}
void TypeAnnotation::tupleTypeName(std::string &name) const {
name += "(";
TypeAnnotationPtr typeEl = m_typeArgs;
while (typeEl) {
name += typeEl->fullName();
typeEl = typeEl->m_typeList;
name += ", ";
}
// replace the trailing ", " with ")"
name.replace(name.size() - 2, 2, ")");
}
void TypeAnnotation::genericTypeName(std::string &name) const {
name += m_name;
name += "<";
TypeAnnotationPtr typeEl = m_typeArgs;
while (typeEl) {
name += typeEl->fullName();
typeEl = typeEl->m_typeList;
name += ", ";
}
// replace the trailing ", " with ">"
name.replace(name.size() - 2, 2, ">");
}
void TypeAnnotation::appendToTypeList(TypeAnnotationPtr typeList) {
if (m_typeList) {
TypeAnnotationPtr current = m_typeList;
while (current->m_typeList) {
current = current->m_typeList;
}
current->m_typeList = typeList;
} else {
m_typeList = typeList;
}
}
void TypeAnnotation::outputCodeModel(CodeGenerator& cg) {
TypeAnnotationPtr typeArgsElem = m_typeArgs;
auto numTypeArgs = 0;
while (typeArgsElem != nullptr) {
numTypeArgs++;
typeArgsElem = typeArgsElem->m_typeList;
}
typeArgsElem = m_typeArgs;
auto numProps = 1;
if (m_nullable) numProps++;
if (m_soft) numProps++;
if (m_function) {
numProps++;
// Since this is a function type, the first type argument is the return type
// and no typeArguments property will be serialized unless there are at
// least two type arguments.
if (numTypeArgs > 1) numProps++;
} else {
if (numTypeArgs > 0) numProps++;
}
cg.printObjectHeader("TypeExpression", numProps);
cg.printPropertyHeader("name");
cg.printValue(m_tuple ? "tuple" : m_name);
if (m_nullable) {
cg.printPropertyHeader("isNullable");
cg.printBool(true);
}
if (m_soft) {
cg.printPropertyHeader("isSoft");
cg.printBool(true);
}
if (m_function) {
cg.printPropertyHeader("returnType");
typeArgsElem->outputCodeModel(cg);
typeArgsElem = typeArgsElem->m_typeList;
// Since we've grabbed the first element of the list as the return
// type, make sure that the logic for serializing type arguments gets
// disabled unless there is at least one more type argument.
numTypeArgs--;
}
if (numTypeArgs > 0) {
cg.printPropertyHeader("typeArguments");
cg.printf("V:9:\"HH\\Vector\":%d:{", numTypeArgs);
while (typeArgsElem != nullptr) {
typeArgsElem->outputCodeModel(cg);
typeArgsElem = typeArgsElem->m_typeList;
}
cg.printf("}");
}
cg.printObjectFooter();
}
}
| [
"sgolemon@fb.com"
] | sgolemon@fb.com |
86923448d578c330e3c6763d488d5bfb8dfe952b | 8694f8a9ca03012ac173ed4e30025fe815ed9581 | /Chapter7/quick_sort.cpp | fff7b89c3759b43f032d3791422222317a92d7f5 | [] | no_license | kenyangzq/Introduction_to_Algorithms | 2dff7aa8ac8cef8966d2b5d027fb162e76f7fd4d | a1764fef7093e8bd7159b28592fa4a1cd8d99abf | refs/heads/master | 2020-03-08T17:17:14.089603 | 2018-04-15T20:30:48 | 2018-04-15T20:30:48 | 128,264,855 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 812 | cpp |
#include <algorithm>
#include <iostream>
#include <vector>
#include <stdexcept>
#include <cmath>
int partition(std::vector<int> & vec, int l, int r) {
int x = vec[r];
int i = l;
for (int j = l; j < r; j++) {
if (vec[j] <= x)
std::swap(vec[i++], vec[j]);
}
std::swap(vec[i], vec[r]);
return i;
}
void quick_sort_help(std::vector<int> & vec, int l, int r) {
if (l < r) {
int q = partition(vec, l, r);
quick_sort_help(vec,l,q-1);
quick_sort_help(vec,q+1,r);
}
}
void quick_sort(std::vector<int> & vec) {
quick_sort_help(vec, 0, vec.size()-1);
}
int main() {
std::ostream_iterator<int> iter(std::cout, " ");
int arr[12] = {3,2,1,3,4,15,32,6,3,31,34,8};
std::vector<int> tmp(arr, arr+12);
quick_sort(tmp);
std::copy(tmp.begin(),tmp.end(), iter);
std::cout << std::endl;
}
| [
"ziqi.yang@vanderbilt.edu"
] | ziqi.yang@vanderbilt.edu |
77bb5431a79ade64f37a484de79853de02dc79de | 5512b175913434519ff0f99d89631036d07fbb82 | /Beginner/Bodybuilder (BUILDB)/bodybuilder.cpp | 4a970c2256310970232927e540a61b221a5ab9b4 | [
"Apache-2.0"
] | permissive | sakayaparp/CodeChef | ea53d6dec5929775acb37e644297a7a915aed1dd | 84cc11304f9abd42d5b657c196756c6402e187d9 | refs/heads/main | 2023-09-01T20:21:56.671530 | 2021-10-06T04:22:30 | 2021-10-06T04:22:30 | 414,112,104 | 1 | 0 | Apache-2.0 | 2021-10-06T07:27:55 | 2021-10-06T07:27:55 | null | UTF-8 | C++ | false | false | 758 | cpp |
#include <bits/stdc++.h>
#define ll long long
#define sz(x) ((int) (x).size())
#define all(x) (x).begin(), (x).end()
#define vi vector<int>
#define pii pair<int, int>
#define rep(i, a, b) for(int i = (a); i < (b); i++)
using namespace std;
template<typename T>
using minpq = priority_queue<T, vector<T>, greater<T>>;
void solve() {
int n;
ll r;
cin >> n >> r;
vector<ll> a(n + 1);
rep(i, 1, n + 1) cin >> a[i];
ll x = 0, ans = 0;
rep(i, 1, n + 1) {
ll b;
cin >> b;
x = max(0LL, x - r * (a[i] - a[i - 1]));
x += b;
ans = max(ans, x);
}
cout << ans << '\n';
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int te;
cin >> te;
while(te--) solve();
}
| [
"noreply@github.com"
] | sakayaparp.noreply@github.com |
319ddeeb26f32637d62ef98d079fea0dff532ad0 | 452f7ba589dec9c9c7fbfbf9f0e4f8fedbdf392c | /xerolibs/xeromisc/MessageDestFile.cpp | 39f74314e203363993bc4e3894eed3fd5606d393 | [] | no_license | errorcodexero/endurance2019 | 51364f9e2a638029439002622e445d60016fb772 | f2442d43c845c3b9c6d94e86c21ecc571a3410b6 | refs/heads/master | 2020-12-29T22:42:08.917542 | 2020-02-06T18:54:22 | 2020-02-06T18:54:22 | 238,759,923 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,403 | cpp | #include "MessageDestFile.h"
namespace xero
{
namespace misc
{
void MessageDestFile::initialize()
{
strm_p_ = nullptr;
setTimeout(15 * 1000); // Default to 15 seconds. Stored in ms.
}
MessageDestFile::MessageDestFile()
{
initialize();
}
MessageDestFile::MessageDestFile(const std::string &name)
{
initialize();
setFile(name);
}
MessageDestFile::~MessageDestFile()
{
if (strm_p_ != nullptr)
delete strm_p_;
}
void MessageDestFile::setTimeout(unsigned long int timeout_limit)
{
timeout_limit_ = timeout_limit;
}
bool MessageDestFile::setFile(const std::string &name)
{
filename_ = name;
strm_p_ = new std::ofstream(name);
if (!strm_p_->is_open())
{
if (!ref_established_)
{
start_ = std::chrono::steady_clock::now();
ref_established_ = true;
std::cout << "Warning: Could not open log file '" << name << "' for writing. Will keep trying to reopen it." << std::endl;
}
strm_p_ = nullptr;
return false;
}
return true;
}
void MessageDestFile::displayMessage(const MessageLogger::MessageType &type, uint64_t subs, const std::string &msg)
{
if (!enabled_)
{
return;
}
std::string prefix;
if (type == MessageLogger::MessageType::warning)
prefix == "WARNING: ";
if (type == MessageLogger::MessageType::error)
prefix == "ERROR: ";
std::string appended_msg = prefix + msg;
if (strm_p_ != nullptr)
{
(*strm_p_) << (appended_msg) << std::endl;
}
else
{
if (setFile(filename_))
{ // Succeeded in opening file
std::cout << "Succeeded in opening log file." << std::endl;
for (auto const &m : msg_q_)
{
(*strm_p_) << m << std::endl;
}
msg_q_.clear();
(*strm_p_) << (appended_msg) << std::endl;
}
else
{
msg_q_.push_back(appended_msg);
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start_).count();
if (elapsed > timeout_limit_)
{
std::cout << "Logging disabled. Timeout reached and log file still not successfully opened." << std::endl;
enabled_ = false;
}
};
}
}
} // namespace misc
} // namespace xero
| [
"bwg@cypress.com"
] | bwg@cypress.com |
672e57bf4a0dbe3f343eeaf474cd66345ba5b041 | 144d2d44e3fa9c561d069009276ae76db8ff8b1c | /Examples/Features/LogisticContrastEnhancementImageFilter/Main.cpp | 89ec509d0ffc8e9830e6d33cb429d5ee4350090d | [] | no_license | cancan101/ITK | f6f51d6cec93ed907886b3dcb477b65261cd8d6d | d8c89499eedeb228f5b127e11055bc245deb891a | refs/heads/master | 2021-08-08T04:23:53.232248 | 2017-10-06T12:56:44 | 2017-10-06T12:56:44 | 108,953,488 | 1 | 0 | null | 2017-10-31T06:15:57 | 2017-10-31T06:15:57 | null | UTF-8 | C++ | false | false | 2,018 | cpp | #include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkLogisticContrastEnhancementImageFilter.h"
int main(int argc, char* argv[])
{
if ( argc < 4 )
{
std::cerr << "Missing parameters. " << std::endl;
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0]
<< " inputImageFileName outputImageFileName [flipObject:(1 is true or 0 is false)] thrMethod "
<< std::endl;
return -1;
}
const unsigned int Dimension = 3;
typedef float PixelType;
typedef itk::Image<PixelType, Dimension> InputImageType;
typedef itk::Image<PixelType, Dimension> OutputImageType;
typedef itk::ImageFileReader<InputImageType> ReaderType;
typedef itk::ImageFileWriter<OutputImageType> WriterType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(argv[1]);
try
{
reader->Update();
}
catch ( itk::ExceptionObject &err)
{
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return -1;
}
typedef itk::LogisticContrastEnhancementImageFilter<InputImageType, OutputImageType> FilterType;
FilterType::Pointer filter = FilterType::New();
filter->SetInput(reader->GetOutput());
filter->SetNumberOfBins(128);
if (atof(argv[3])==1) {
filter->FlipObjectAreaOn();
}
filter->SetThresholdMethod(atoi(argv[4]));
filter->Update();
std::cout<<"Alpha: "<<filter->GetAlpha()<<std::endl;
std::cout<<"Beta: "<<filter->GetBeta()<<std::endl;
typename WriterType::Pointer writer = WriterType::New();
writer->SetFileName(argv[2]);
writer->SetInput(filter->GetOutput());
try
{
writer->Update();
}
catch ( itk::ExceptionObject &err)
{
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return -1;
}
return EXIT_SUCCESS;
}
| [
"acsenrafilho@gmail.com"
] | acsenrafilho@gmail.com |
ef0de11f5dcff3f6ccb028dbcf9b1510c027b9a0 | 3da18f95e457f3ac8c41c468cd7271ba9717bb19 | /03.sdl_MoveImage/app/simplesdl.cpp | f1943482165743e78f9b1be4097ed5ac7cba401b | [] | no_license | Falmouth-Games-Academy/GAM340-SDL | f61cfb9fe3d42f8957a1b972c5b5630c3721bfc8 | f9dc8c545b38536d1858276fe6720223517fdb5f | refs/heads/master | 2020-08-11T21:28:10.741500 | 2019-10-12T10:55:22 | 2019-10-12T10:55:22 | 214,630,576 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,183 | cpp | #include <SDL.h>
#include <SDL_image.h>
#include <stdlib.h>
#include <stdio.h>
#include <windows.h>
#undef main
#include <stdlib.h> //rand()
#pragma comment(lib, "SDL2main.lib")
#pragma comment(lib, "SDL2.lib")
#pragma comment(lib, "SDL2_image.lib")
SDL_Window *window = NULL;
SDL_Renderer *renderer = NULL;
int main(int argc, char *argv[])
{
//Initialise IMG system, this allows us to load PNG files
int imgFlags = IMG_INIT_PNG;
IMG_Init(imgFlags);
//Initialise window & renderer
window = NULL;
renderer = NULL;
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) != 0)
{
SDL_Log("Failed to initialize SDL: %s", SDL_GetError());
return false;
}
//create a window that is 800x600 pixels
window = SDL_CreateWindow("title", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 600, SDL_WINDOW_OPENGL);
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
//load a bitmap using the IMG library
SDL_Surface* srcImage = IMG_Load("resources/ball.png");
if (srcImage == NULL)
{
SDL_Log("SDL_Surface: can't load image\n");
goto quit;
}
SDL_Texture* ballTexture;
//convert the
ballTexture = SDL_CreateTextureFromSurface(renderer, srcImage);
if (ballTexture == NULL)
{
SDL_Log("SDL_Texture: can't create texture\n");
goto quit;
}
Uint32 lastElapsedTime=0, fpsTimer=0;
Uint32 elaspedTime = 0;
Uint32 fpsTime = 0;
SDL_Event event;
bool quitting = false;
signed int ball_xvel = 0;
signed int ball_yvel = 0;
signed int ballX = 800/2;
signed int ballY = 600/2;
//The main application loop
//This uses SDL_GetTicks() to record elapsed time and pause the application with Sleep to keep it running at 60fps rather than thousands of fps
while (!quitting)
{
fpsTime = SDL_GetTicks() - lastElapsedTime;
lastElapsedTime = SDL_GetTicks();
//Clear the screen before we draw to it
//https://wiki.libsdl.org/SDL_RenderClear
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
// SDL uses events to communicate with the application
// In this instance, the app is just responding to SDL_QUIT messages which occur when the application is closed
// to close the app down, either press the X icon on the window or get you program to generation an SDL_QUIT event internally
while (SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_QUIT:
{
quitting = true;
}
break;
/* Look for a keypress */
//https://www.libsdl.org/release/SDL-1.2.15/docs/html/guideinputkeyboard.html
case SDL_KEYDOWN:
{
switch (event.key.keysym.sym)
{
case SDLK_LEFT:
ball_xvel = -1;
break;
case SDLK_RIGHT:
ball_xvel = 1;
break;
case SDLK_UP:
ball_yvel = -1;
break;
case SDLK_DOWN:
ball_yvel = 1;
break;
default:
break;
}
break;
}
case SDL_KEYUP:
{
switch (event.key.keysym.sym)
{
case SDLK_LEFT:
if (ball_xvel < 0)
ball_xvel = 0;
break;
case SDLK_RIGHT:
if (ball_xvel > 0)
ball_xvel = 0;
break;
case SDLK_UP:
if (ball_yvel < 0)
ball_yvel = 0;
break;
case SDLK_DOWN:
if (ball_yvel > 0)
ball_yvel = 0;
break;
default:
break;
}
}
break;
}
}
ballX += ball_xvel;
ballY += ball_yvel;
//draw the ball using SDL_RenderCopy
//this requires a rectangle of the ball's position and size (for scalability)
SDL_Rect dest;
dest.x = ballX;
dest.y = ballY;
dest.w = 32;
dest.h = 32;
SDL_RenderCopy(renderer, ballTexture, NULL, &dest);
//This uses the window title to display frame performance information
{
char temp[255];
sprintf(temp, "Frame Time:%.3f (%3.0f FPS)", (float)(fpsTime), 1000.0f/fpsTime);
SDL_SetWindowTitle(window, temp);
}
//End of frame rendering
SDL_RenderPresent(renderer);
//Sleep the app
if (elaspedTime < 16)
{
Sleep(16 - elaspedTime);
}
}
quit:
//On end of application, close down resources and exit
SDL_DestroyWindow(window);
SDL_Quit();
window = NULL;
renderer = NULL;
return 0;
} | [
"gareth_lewis@yahoo.com"
] | gareth_lewis@yahoo.com |
3a1739865ce70ba4d7bcfe87380648ad24a6adb8 | 4060dfd3ee62b32ecf287944ebbc38ef889f5fca | /Dynamic Programming/392. Is Subsequence.cpp | 9b7a4a57567c9ad3bfef27a1fad38e49ed3153b9 | [] | no_license | Sensrdt/Leet-Code-Sol | e5cd6b25a6aa9628f1d311d02ad03c4a435fe47c | 893d0614849b2416d920929e0ee1156b6218c6b9 | refs/heads/master | 2020-07-01T15:12:07.546062 | 2020-06-07T13:34:55 | 2020-06-07T13:34:55 | 201,206,677 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 447 | cpp | class Solution
{
public:
bool isSubsequence(string s, string t)
{
int n = s.length(), m = t.length();
int i = 0, j = 0;
while (i < n && j < m)
{
if (s[i] == t[j])
{
i++;
j++;
}
else
j++;
}
if (i == n)
return true;
else
return false;
}
}; | [
"stsdutta2@gmail.com"
] | stsdutta2@gmail.com |
31664c5453e631e0b1d84d0451e1451eebd91d6a | 09029c871c08379f427ce472000673411bd6b21c | /lib/libnet/nstream_proactor.cpp | d63773e0476f2a4250e6441b4ed0d70eeaa44650 | [] | no_license | sbunce/p2p | 0c1a9fb8259fc0d60623c22f5950bed9fad234e2 | e5e97714de193295b88b2610080acebd9be18252 | refs/heads/master | 2021-05-02T07:37:54.674279 | 2018-11-19T05:29:30 | 2018-11-19T05:29:30 | 17,999,320 | 2 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 15,103 | cpp | #include <net/nstream_proactor.hpp>
//BEGIN events
net::nstream_proactor::conn_info::conn_info(
const boost::uint64_t conn_ID_in,
const dir_t dir_in,
const tran_t tran_in,
const boost::optional<endpoint> & local_ep_in,
const boost::optional<endpoint> & remote_ep_in
):
conn_ID(conn_ID_in),
dir(dir_in),
tran(tran_in),
local_ep(local_ep_in),
remote_ep(remote_ep_in)
{
}
net::nstream_proactor::connect_event::connect_event(
const boost::shared_ptr<const conn_info> & info_in
):
info(info_in)
{
}
net::nstream_proactor::disconnect_event::disconnect_event(
const boost::shared_ptr<const conn_info> & info_in,
const error_t error_in
):
info(info_in),
error(error_in)
{
}
net::nstream_proactor::recv_event::recv_event(
const boost::shared_ptr<const conn_info> & info_in,
const buffer & buf_in
):
info(info_in),
buf(buf_in)
{
}
net::nstream_proactor::send_event::send_event(
const boost::shared_ptr<const conn_info> & info_in,
const unsigned last_send_in,
const unsigned send_buf_size_in
):
info(info_in),
last_send(last_send_in),
send_buf_size(send_buf_size_in)
{
}
//END events
//BEGIN conn
net::nstream_proactor::conn::~conn()
{
}
void net::nstream_proactor::conn::schedule_send(const buffer & buf,
const bool close_on_empty)
{
}
bool net::nstream_proactor::conn::timed_out()
{
return false;
}
void net::nstream_proactor::conn::write()
{
}
//END conn
//BEGIN conn_container
net::nstream_proactor::conn_container::conn_container():
unused_conn_ID(0),
last_time(std::time(NULL)),
incoming_conn_limit(0),
outgoing_conn_limit(0),
incoming_conns(0),
outgoing_conns(0)
{
}
void net::nstream_proactor::conn_container::add(const boost::shared_ptr<conn> & C)
{
Socket.insert(std::make_pair(C->socket(), C));
ID.insert(std::make_pair(C->info()->conn_ID, C));
}
void net::nstream_proactor::conn_container::check_timeouts()
{
if(last_time != std::time(NULL)){
last_time = std::time(NULL);
std::list<boost::uint64_t> timed_out;
for(std::map<boost::uint64_t, boost::shared_ptr<conn> >::iterator
it_cur = ID.begin(), it_end = ID.end(); it_cur != it_end; ++it_cur)
{
if(it_cur->second->timed_out()){
timed_out.push_back(it_cur->second->info()->conn_ID);
it_cur->second->set_error(timeout_error);
}
}
for(std::list<boost::uint64_t>::iterator it_cur = timed_out.begin(),
it_end = timed_out.end(); it_cur != it_end; ++it_cur)
{
remove(*it_cur);
}
}
}
boost::uint64_t net::nstream_proactor::conn_container::new_conn_ID()
{
return unused_conn_ID++;
}
std::set<int> net::nstream_proactor::conn_container::read_set()
{
return _read_set;
}
void net::nstream_proactor::conn_container::monitor_read(const int socket_FD)
{
_read_set.insert(socket_FD);
}
void net::nstream_proactor::conn_container::monitor_write(const int socket_FD)
{
_write_set.insert(socket_FD);
}
void net::nstream_proactor::conn_container::perform_reads(
const std::set<int> & read_set_in)
{
for(std::set<int>::const_iterator it_cur = read_set_in.begin(),
it_end = read_set_in.end(); it_cur != it_end; ++it_cur)
{
std::map<int, boost::shared_ptr<conn> >::iterator
it = Socket.find(*it_cur);
if(it != Socket.end()){
it->second->read();
}
}
}
void net::nstream_proactor::conn_container::perform_writes(
const std::set<int> & write_set_in)
{
for(std::set<int>::const_iterator it_cur = write_set_in.begin(),
it_end = write_set_in.end(); it_cur != it_end; ++it_cur)
{
std::map<int, boost::shared_ptr<conn> >::iterator
it = Socket.find(*it_cur);
if(it != Socket.end()){
it->second->write();
}
}
}
void net::nstream_proactor::conn_container::remove(const boost::uint64_t conn_ID)
{
std::map<boost::uint64_t, boost::shared_ptr<conn> >::iterator
it = ID.find(conn_ID);
if(it != ID.end()){
_read_set.erase(it->second->socket());
_write_set.erase(it->second->socket());
Socket.erase(it->second->socket());
ID.erase(it->second->info()->conn_ID);
}
}
void net::nstream_proactor::conn_container::schedule_send(
const boost::uint64_t conn_ID, const buffer & buf, const bool close_on_empty)
{
std::map<boost::uint64_t, boost::shared_ptr<conn> >::iterator
it = ID.find(conn_ID);
if(it != ID.end()){
it->second->schedule_send(buf, close_on_empty);
}
}
void net::nstream_proactor::conn_container::unmonitor_read(const int socket_FD)
{
_read_set.erase(socket_FD);
}
void net::nstream_proactor::conn_container::unmonitor_write(const int socket_FD)
{
_write_set.erase(socket_FD);
}
std::set<int> net::nstream_proactor::conn_container::write_set()
{
return _write_set;
}
//END conn_container
//BEGIN conn_nstream
net::nstream_proactor::conn_nstream::conn_nstream(
dispatcher & Dispatcher_in,
conn_container & Conn_Container_in,
const endpoint & ep
):
Dispatcher(Dispatcher_in),
Conn_Container(Conn_Container_in),
N(new nstream()),
close_on_empty(false),
half_open(true),
timeout(std::time(NULL) + connect_timeout),
error(no_error)
{
N->open_async(ep);
socket_FD = N->socket();
_info.reset(new conn_info(
Conn_Container.new_conn_ID(),
outgoing_dir,
nstream_tran,
N->local_ep(),
N->remote_ep()
));
Conn_Container.monitor_write(socket_FD);
}
net::nstream_proactor::conn_nstream::conn_nstream(
dispatcher & Dispatcher_in,
conn_container & Conn_Container_in,
boost::shared_ptr<nstream> N_in
):
Dispatcher(Dispatcher_in),
Conn_Container(Conn_Container_in),
N(N_in),
close_on_empty(false),
half_open(false),
timeout(std::time(NULL) + idle_timeout),
error(no_error)
{
socket_FD = N->socket();
assert(N->is_open());
_info.reset(new conn_info(
Conn_Container.new_conn_ID(),
incoming_dir,
nstream_tran,
N->local_ep(),
N->remote_ep()
));
Dispatcher.connect(connect_event(_info));
Conn_Container.monitor_read(socket_FD);
}
net::nstream_proactor::conn_nstream::~conn_nstream()
{
Dispatcher.disconnect(disconnect_event(_info, error));
}
boost::shared_ptr<const net::nstream_proactor::conn_info>
net::nstream_proactor::conn_nstream::info()
{
return _info;
}
void net::nstream_proactor::conn_nstream::read()
{
touch();
buffer buf;
int n_bytes = N->recv(buf);
if(n_bytes <= 0){
//assume connection reset (may not be)
error = connection_reset_error;
Conn_Container.remove(_info->conn_ID);
}else{
Dispatcher.recv(recv_event(_info, buf));
}
}
void net::nstream_proactor::conn_nstream::schedule_send(const buffer & buf,
const bool close_on_empty_in)
{
if(close_on_empty_in){
close_on_empty = true;
}
send_buf.append(buf);
if(send_buf.empty() && close_on_empty){
Conn_Container.remove(_info->conn_ID);
}else{
Conn_Container.monitor_write(socket_FD);
}
}
void net::nstream_proactor::conn_nstream::set_error(const error_t error_in)
{
error = error_in;
}
int net::nstream_proactor::conn_nstream::socket()
{
return socket_FD;
}
bool net::nstream_proactor::conn_nstream::timed_out()
{
return timeout > std::time(NULL);
}
void net::nstream_proactor::conn_nstream::touch()
{
timeout = std::time(NULL) + idle_timeout;
}
void net::nstream_proactor::conn_nstream::write()
{
touch();
if(half_open){
if(N->is_open_async()){
half_open = false;
Dispatcher.connect(connect_event(_info));
//send_buf always empty after connect
Conn_Container.unmonitor_write(socket_FD);
Conn_Container.monitor_read(socket_FD);
}else{
error = connect_error;
Conn_Container.remove(_info->conn_ID);
}
}else{
int n_bytes = N->send(send_buf);
if(send_buf.empty()){
Conn_Container.unmonitor_write(socket_FD);
}
if(n_bytes <= 0){
error = connection_reset_error;
Conn_Container.remove(_info->conn_ID);
}else if(close_on_empty && send_buf.empty()){
Conn_Container.remove(_info->conn_ID);
}else{
Dispatcher.send(send_event(_info, n_bytes, send_buf.size()));
}
}
};
//END conn_nstream
//BEGIN conn_listener
net::nstream_proactor::conn_listener::conn_listener(
dispatcher & Dispatcher_in,
conn_container & Conn_Container_in,
const endpoint & ep
):
Dispatcher(Dispatcher_in),
Conn_Container(Conn_Container_in),
error(no_error)
{
Listener.open(ep);
Listener.set_non_blocking(true);
socket_FD = Listener.socket();
_info.reset(new conn_info(
Conn_Container.new_conn_ID(),
outgoing_dir,
nstream_listen_tran,
ep
));
if(Listener.is_open()){
Dispatcher.connect(connect_event(_info));
Conn_Container.monitor_read(socket_FD);
}else{
error = listen_error;
}
}
net::nstream_proactor::conn_listener::~conn_listener()
{
Dispatcher.disconnect(disconnect_event(_info, error));
}
boost::shared_ptr<const net::nstream_proactor::conn_info>
net::nstream_proactor::conn_listener::info()
{
return _info;
}
boost::optional<net::endpoint> net::nstream_proactor::conn_listener::ep()
{
return Listener.local_ep();
}
void net::nstream_proactor::conn_listener::read()
{
while(boost::shared_ptr<nstream> N = Listener.accept()){
boost::shared_ptr<conn_nstream> CN(new conn_nstream(Dispatcher,
Conn_Container, N));
Conn_Container.add(CN);
}
}
void net::nstream_proactor::conn_listener::set_error(const error_t error_in)
{
error = error_in;
}
int net::nstream_proactor::conn_listener::socket()
{
return socket_FD;
}
//END conn_listener
//BEGIN dispatcher
net::nstream_proactor::dispatcher::dispatcher(
const boost::function<void (connect_event)> & connect_call_back_in,
const boost::function<void (disconnect_event)> & disconnect_call_back_in,
const boost::function<void (recv_event)> & recv_call_back_in,
const boost::function<void (send_event)> & send_call_back_in
):
connect_call_back(connect_call_back_in),
disconnect_call_back(disconnect_call_back_in),
recv_call_back(recv_call_back_in),
send_call_back(send_call_back_in),
producer_cnt(1),
job_cnt(0)
{
for(unsigned x=0; x<threads; ++x){
workers.create_thread(boost::bind(&dispatcher::dispatch, this));
}
}
net::nstream_proactor::dispatcher::~dispatcher()
{
join();
workers.interrupt_all();
workers.join_all();
}
void net::nstream_proactor::dispatcher::connect(const connect_event & CE)
{
boost::mutex::scoped_lock lock(mutex);
while(Job.size() >= max_buf){
consumer_cond.wait(mutex);
}
boost::function<void ()> func = boost::bind(connect_call_back, CE);
Job.push_back(std::make_pair(CE.info->conn_ID, func));
++producer_cnt;
++job_cnt;
producer_cond.notify_one();
}
void net::nstream_proactor::dispatcher::disconnect(const disconnect_event & DE)
{
boost::mutex::scoped_lock lock(mutex);
while(Job.size() >= max_buf){
consumer_cond.wait(mutex);
}
boost::function<void ()> func = boost::bind(disconnect_call_back, DE);
Job.push_back(std::make_pair(DE.info->conn_ID, func));
++producer_cnt;
++job_cnt;
producer_cond.notify_one();
}
void net::nstream_proactor::dispatcher::join()
{
boost::mutex::scoped_lock lock(mutex);
while(job_cnt > 0){
empty_cond.wait(mutex);
}
}
void net::nstream_proactor::dispatcher::recv(const recv_event & RE)
{
boost::mutex::scoped_lock lock(mutex);
while(Job.size() >= max_buf){
consumer_cond.wait(mutex);
}
boost::function<void ()> func = boost::bind(recv_call_back, RE);
Job.push_back(std::make_pair(RE.info->conn_ID, func));
++producer_cnt;
++job_cnt;
producer_cond.notify_one();
}
void net::nstream_proactor::dispatcher::send(const send_event & SE)
{
boost::mutex::scoped_lock lock(mutex);
while(Job.size() >= max_buf){
consumer_cond.wait(mutex);
}
boost::function<void ()> func = boost::bind(send_call_back, SE);
Job.push_back(std::make_pair(SE.info->conn_ID, func));
++producer_cnt;
++job_cnt;
producer_cond.notify_one();
}
void net::nstream_proactor::dispatcher::dispatch()
{
//when no job to run we wait until producer_cnt greater than this
boost::uint64_t wait_until = 0;
while(true){
std::pair<boost::uint64_t, boost::function<void ()> > p;
{//BEGIN lock scope
boost::mutex::scoped_lock lock(mutex);
while(Job.empty() || wait_until > producer_cnt){
producer_cond.wait(mutex);
}
for(std::list<std::pair<boost::uint64_t, boost::function<void ()> > >::iterator
it_cur = Job.begin(), it_end = Job.end(); it_cur != it_end; ++it_cur)
{
if(memoize.insert(it_cur->first).second){
p = *it_cur;
Job.erase(it_cur);
break;
}
}
if(!p.second){
//no job we can currently run, wait until a job added to check again
wait_until = producer_cnt + 1;
continue;
}
}//END lock scope
p.second();
{//BEGIN lock scope
boost::mutex::scoped_lock lock(mutex);
memoize.erase(p.first);
--job_cnt;
if(job_cnt == 0){
empty_cond.notify_all();
}
}//END lock scope
consumer_cond.notify_one();
}
}
//END dispatcher
net::nstream_proactor::nstream_proactor(
const boost::function<void (connect_event)> & connect_call_back_in,
const boost::function<void (disconnect_event)> & disconnect_call_back_in,
const boost::function<void (recv_event)> & recv_call_back_in,
const boost::function<void (send_event)> & send_call_back_in
):
Dispatcher(
connect_call_back_in,
disconnect_call_back_in,
recv_call_back_in,
send_call_back_in
),
Internal_TP(1, 1024)
{
Internal_TP.enqueue(boost::bind(&nstream_proactor::main_loop, this));
}
void net::nstream_proactor::connect(const endpoint & ep)
{
Internal_TP.enqueue(boost::bind(&nstream_proactor::connect_relay, this, ep));
Select.interrupt();
}
void net::nstream_proactor::connect_relay(const endpoint & ep)
{
boost::shared_ptr<conn_nstream> CL(new conn_nstream(Dispatcher,
Conn_Container, ep));
if(CL->socket() != -1){
Conn_Container.add(CL);
}
}
void net::nstream_proactor::disconnect(const boost::uint64_t conn_ID)
{
Internal_TP.enqueue(boost::bind(&nstream_proactor::disconnect_relay, this, conn_ID));
Select.interrupt();
}
void net::nstream_proactor::disconnect_relay(const boost::uint64_t conn_ID)
{
Conn_Container.remove(conn_ID);
}
channel::future<boost::optional<net::endpoint> > net::nstream_proactor::listen(
const endpoint & ep)
{
channel::promise<boost::optional<net::endpoint> > promise;
Internal_TP.enqueue(boost::bind(&nstream_proactor::listen_relay, this, ep, promise));
Select.interrupt();
return promise.get_future();
}
void net::nstream_proactor::listen_relay(const endpoint ep,
channel::promise<boost::optional<net::endpoint> > promise)
{
boost::shared_ptr<conn_listener> CL(new conn_listener(Dispatcher,
Conn_Container, ep));
if(CL->socket() != -1){
Conn_Container.add(CL);
}
promise = CL->ep();
}
void net::nstream_proactor::main_loop()
{
std::set<int> read_set = Conn_Container.read_set();
std::set<int> write_set = Conn_Container.write_set();
Select(read_set, write_set, 1000);
Conn_Container.perform_reads(read_set);
Conn_Container.perform_writes(write_set);
Conn_Container.check_timeouts();
Internal_TP.enqueue(boost::bind(&nstream_proactor::main_loop, this));
}
void net::nstream_proactor::send(const boost::uint64_t conn_ID,
const buffer & buf, const bool close_on_empty)
{
Internal_TP.enqueue(boost::bind(&nstream_proactor::send_relay, this, conn_ID,
buf, close_on_empty));
Select.interrupt();
}
void net::nstream_proactor::send_relay(const boost::uint64_t conn_ID,
const buffer buf, const bool close_on_empty)
{
Conn_Container.schedule_send(conn_ID, buf, close_on_empty);
}
| [
"seth@seth.dnsdojo.net"
] | seth@seth.dnsdojo.net |
ff5158eb6e56886f120dadafb3b99ce51bfda92e | b25898993f8646c8517d93662cbe9ae33cf51095 | /o2xfs-xfs3/src/o2xfs-xfs310-test.dll/cpp/cim/PowerSaveControl3_10.cpp | 219514a453dc3b7f8feeb95a101a8e413fc5e0ed | [
"BSD-2-Clause"
] | permissive | dotfeng/O2Xfs | 5e4a16cd11305d4476ce28fb15887d6393ca90cd | 27e9b09fc8f5a8f4b0c6d9a5d1746cadb61b121d | refs/heads/master | 2021-01-24T20:25:10.044447 | 2017-03-08T22:07:02 | 2017-03-08T22:07:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,871 | cpp | /*
* Copyright (c) 2017, Andreas Fagschlunger. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "cim/at_o2xfs_xfs_cim_v3_10_PowerSaveControl3_10Test.h"
#include <Windows.h>
#include <XFSCIM.H>
#include "at.o2xfs.win32.h"
WFSCIMPOWERSAVECONTROL PowerSaveControl;
JNIEXPORT jobject JNICALL Java_at_o2xfs_xfs_cim_v3_110_PowerSaveControl3_110Test_buildPowerSaveControl3_110(JNIEnv *env, jobject obj) {
PowerSaveControl.usMaxPowerSaveRecoveryTime = 1234;
return NewBuffer(env, &PowerSaveControl, sizeof(WFSCIMPOWERSAVECONTROL));
} | [
"github@fagschlunger.co.at"
] | github@fagschlunger.co.at |
5951a59ac5649f243bf34e5dabfa281905ce418c | f67f6607786bf68ee83751c4fa48263a4c1db5f2 | /bankingstoragereterievedata.cpp | 71b1049d655281506740589d40b99c6cda36c67b | [] | no_license | shwetakumawat/bankingstorageandreterivingdata | 8689bf370b7003f42d8887780ebde4dbcfef13b0 | d7acd6d3d04a734c754cbd8994b7503fa3e4a7f1 | refs/heads/master | 2020-08-08T15:28:34.330908 | 2019-10-09T08:13:07 | 2019-10-09T08:13:07 | 213,859,393 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,852 | cpp |
#include<iostream>
#include<fstream>
#include<cctype>
#include<iomanip>
using namespace std;
class account
{
int acno;
char name[50];
int deposit;
char type;
public:
void create_account();
void show_account() const;
void modify();
void dep(int);
void draw(int);
void report() const;
int retacno() const;
int retdeposit() const;
char rettype() const;
};
void account::create_account()
{
cout<<"\nEnter The account No. :";
cin>>acno;
cout<<"\n\nEnter The Name of The account Holder : ";
cin.ignore();
cin.getline(name,50);
cout<<"\nEnter Type of The account (C/S) : ";
cin>>type;
type=toupper(type);
cout<<"\nEnter The Initial amount(>=500 for Saving and >=1000 for current ) : ";
cin>>deposit;
cout<<"\n\n\nAccount Created..";
}
void account::show_account() const
{
cout<<"\nAccount No. : "<<acno;
cout<<"\nAccount Holder Name : ";
cout<<name;
cout<<"\nType of Account : "<<type;
cout<<"\nBalance amount : "<<deposit;
}
void account::modify()
{
cout<<"\nAccount No. : "<<acno;
cout<<"\nModify Account Holder Name : ";
cin.ignore();
cin.getline(name,50);
cout<<"\nModify Type of Account : ";
cin>>type;
type=toupper(type);
cout<<"\nModify Balance amount : ";
cin>>deposit;
}
void account::dep(int x)
{
deposit+=x;
}
void account::draw(int x)
{
deposit-=x;
}
void account::report() const
{
cout<<acno<<setw(10)<<" "<<name<<setw(10)<<" "<<type<<setw(6)<<deposit<<endl;
}
int account::retacno() const
{
return acno;
}
int account::retdeposit() const
{
return deposit;
}
char account::rettype() const
{
return type;
}
void write_account();
void display_sp(int);
void modify_account(int);
void delete_account(int);
void display_all();
void deposit_withdraw(int, int);
int main()
{
char ch;
int num;
do
{
system("cls");
cout<<"\n\tBANK MANAGEMENT SYSTEM";
cout<<"\n\t01. NEW ACCOUNT";
cout<<"\n\t02. DEPOSIT AMOUNT";
cout<<"\n\t03. WITHDRAW AMOUNT";
cout<<"\n\t04. BALANCE ENQUIRY";
cout<<"\n\t05. ACCOUNT OWNER NAMES";
cout<<"\n\t06. CLOSE ACCOUNT";
cout<<"\n\t07. MODIFY ACCOUNT";
cout<<"\n\t08. EXIT";
cout<<"\n\tSelect Your Option (1-8) ";
cin>>ch;
system("cls");
switch(ch)
{
case '1':
write_account();
break;
case '2':
cout<<"\n\n\tEnter The account No. : "; cin>>num;
deposit_withdraw(num, 1);
break;
case '3':
cout<<"\n\n\tEnter The account No. : "; cin>>num;
deposit_withdraw(num, 2);
break;
case '4':
cout<<"\n\n\tEnter The account No. : "; cin>>num;
display_sp(num);
break;
case '5':
display_all();
break;
case '6':
cout<<"\n\n\tEnter The account No. : "; cin>>num;
delete_account(num);
break;
case '7':
cout<<"\n\n\tEnter The account No. : "; cin>>num;
modify_account(num);
break;
case '8':
cout<<"\n\n\tThanks for using bank managemnt system";
break;
default :cout<<"\a";
}
cin.ignore();
cin.get();
}while(ch!='8');
return 0;
}
void write_account()
{
account ac;
ofstream outFile;
outFile.open("account.dat",ios::binary|ios::app);
ac.create_account();
outFile.write(reinterpret_cast<char *> (&ac), sizeof(account));
outFile.close();
}
void display_sp(int n)
{
account ac;
bool flag=false;
ifstream inFile;
inFile.open("account.dat",ios::binary);
if(!inFile)
{
cout<<"File could not be open !! Press any Key...";
return;
}
cout<<"\nBALANCE DETAILS\n";
while(inFile.read(reinterpret_cast<char *> (&ac), sizeof(account)))
{
if(ac.retacno()==n)
{
ac.show_account();
flag=true;
}
}
inFile.close();
if(flag==false)
cout<<"\n\nAccount number does not exist";
}
void modify_account(int n)
{
bool found=false;
account ac;
fstream File;
File.open("account.dat",ios::binary|ios::in|ios::out);
if(!File)
{
cout<<"File could not be open !! Press any Key...";
return;
}
while(!File.eof() && found==false)
{
File.read(reinterpret_cast<char *> (&ac), sizeof(account));
if(ac.retacno()==n)
{
ac.show_account();
cout<<"\n\nEnter The New Details of account"<<endl;
ac.modify();
int pos=(-1)*static_cast<int>(sizeof(account));
File.seekp(pos,ios::cur);
File.write(reinterpret_cast<char *> (&ac), sizeof(account));
cout<<"\n\n\t Record Updated";
found=true;
}
}
File.close();
if(found==false)
cout<<"\n\n Record Not Found ";
}
void delete_account(int n)
{
account ac;
ifstream inFile;
ofstream outFile;
inFile.open("account.dat",ios::binary);
if(!inFile)
{
cout<<"File could not be open !! Press any Key...";
return;
}
outFile.open("Temp.dat",ios::binary);
inFile.seekg(0,ios::beg);
while(inFile.read(reinterpret_cast<char *> (&ac), sizeof(account)))
{
if(ac.retacno()!=n)
{
outFile.write(reinterpret_cast<char *> (&ac), sizeof(account));
}
}
inFile.close();
outFile.close();
remove("account.dat");
rename("Temp.dat","account.dat");
cout<<"\n\n\tRecord Deleted ..";
}
void display_all()
{
account ac;
ifstream inFile;
inFile.open("account.dat",ios::binary);
if(!inFile)
{
cout<<"File could not be open !! Press any Key...";
return;
}
cout<<"\n\n\t\tACCOUNT OWNER NAMES\n\n";
cout<<"**********************************************\n";
cout<<"A/c no. NAME ENTER BALANCE\n";
cout<<"**********************************************\n";
while(inFile.read(reinterpret_cast<char *> (&ac), sizeof(account)))
{
ac.report();
}
inFile.close();
}
void deposit_withdraw(int n, int option)
{
int amt;
bool found=false;
account ac;
fstream File;
File.open("account.dat", ios::binary|ios::in|ios::out);
if(!File)
{
cout<<"File could not be open !! Press any Key...";
return;
}
while(!File.eof() && found==false)
{
File.read(reinterpret_cast<char *> (&ac), sizeof(account));
if(ac.retacno()==n)
{
ac.show_account();
if(option==1)
{
cout<<"\n\n\tTO DEPOSITE AMOUNT ";
cout<<"\n\nEnter The amount to be deposited";
cin>>amt;
ac.dep(amt);
}
if(option==2)
{
cout<<"\n\n\tTO WITHDRAW AMOUNT ";
cout<<"\n\nEnter The amount to be withdraw";
cin>>amt;
int bal=ac.retdeposit()-amt;
if((bal<500 && ac.rettype()=='S') || (bal<1000 && ac.rettype()=='C'))
cout<<"Insufficience balance";
else
ac.draw(amt);
}
int pos=(-1)*static_cast<int>(sizeof(ac));
File.seekp(pos,ios::cur);
File.write(reinterpret_cast<char *> (&ac), sizeof(account));
cout<<"\n\n\t Record Updated";
found=true;
}
}
File.close();
if(found==false)
cout<<"\n\n Record Not Found ";
}
| [
"noreply@github.com"
] | shwetakumawat.noreply@github.com |
30abd459cf47c58c0e9ac346a192f7e286726f8b | a3f5923ae3826fae0378307607b9bf0b1b54a41e | /TestHX711/TestHX711.ino | 3def94fcaf302c55c1d1ca06535df328195455a6 | [
"MIT"
] | permissive | nuzhmiammar/Code-Tahap-Awal | fe6016113c0dee1a3bf103a44362ed9561714e41 | e6fa39142a21087a514e0c845307f8d2d2dbe173 | refs/heads/main | 2023-02-15T09:24:37.449530 | 2021-01-18T12:11:05 | 2021-01-18T12:11:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 327 | ino | #include "HX711.h"
#define DOUT A0
#define CLK A1
HX711 scale(DOUT, CLK);
float calibration_factor = 344.10;
int GRAM;
void setup() {
Serial.begin(9600);
scale.set_scale();
scale.tare();
}
void loop() {
scale.set_scale(calibration_factor);
GRAM = scale.get_units(), 4;
Serial.println(GRAM);
}
| [
"noreply@github.com"
] | nuzhmiammar.noreply@github.com |
68a9f515c4489b4070112007eae98def7213bd67 | b01cf41ed58bf297cf13d0a8a7f4feeecedafb4b | /Contest 3/H TAXI/main.cpp | c7d2e474a2ceab94dcd52302e77b0b3dc8b26a95 | [] | no_license | thanhnx12/TTUD-1 | 636a25f2c7486a820253c36b182be9345a6e6495 | f05a71692622ce36e5b5efc85a58d4f953b592ff | refs/heads/master | 2023-03-15T16:49:09.091169 | 2020-07-19T11:02:25 | 2020-07-19T11:02:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,038 | cpp | #include <bits/stdc++.h>
using namespace std;
int n,k,c[23][23],d[23],dem = 0,_min = 1e9;
int res = 1e9,s = 0,t;
void Try(int x,int y){
if(dem < k)
for(int i = 1; i <= n; i++){
if(!d[i]){
dem++;
d[i] = 1;
s+=c[y][i];
if(s + (t-x)*_min < res) Try(x+1,i);
s-=c[y][i];
d[i] = 0;
dem--;
}
}
for(int i = n+1; i < t; i++){
if(!d[i] && d[i-n]){
dem--;
d[i] = 1;
s+=c[y][i];
if(x == t - 1) {
res = min(res,s+c[i][0]);
}
if(s + (t-x)*_min < res) Try(x+1,i);
s-=c[y][i];
d[i] = 0;
dem++;
}
}
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n;
k = 1;
t = (n << 1)+1;
for(int i = 0; i < t; i++)
for(int j = 0; j < t; j++){
cin >> c[i][j];
if(i != j) _min = min(_min,c[i][j]);
}
Try(1,0);
cout << res;
}
| [
"ntd275@gmail.com"
] | ntd275@gmail.com |
f10fac8f10c4bc63ef9058e613cdb0c4611f6036 | 27e0a8065d73de8deedfb58a94730f7c3c55261e | /数组中常见的问题/167. 两数之和 II - 输入有序数组/main.cpp | 21a16c516c2624004646a54ccc0ae050f82de929 | [] | no_license | Jae1010/leetcode | 5ea717eb15f5fff560b04a6f5301c4ed682fcbda | 8f55d4ead6cd1ebb7e166d64a73e5d2890bf4425 | refs/heads/master | 2023-02-02T05:39:00.627840 | 2020-12-22T06:54:04 | 2020-12-22T06:54:04 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,883 | cpp | //==================================================================
// Leetcode代码
// 作者:曹佳
//==================================================================
//
// 167. 两数之和 II - 输入有序数组
// 题目:给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。
// 函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。
//说明:
//返回的下标值(index1 和 index2)不是从零开始的。
//你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
//
#include <iostream>
#include <vector>
using namespace std;
//暴力解法
vector<int> twoSum1(vector<int>& numbers, int target) {
vector<int> result;
for(int i = 0; i < numbers.size()-1;i++)
for(int j = i+1; j < numbers.size(); j++){
if(numbers[i] + numbers[j] == target){
result.push_back(++i);
result.push_back(++j);
return result;
}
}
return result;
}
//双指针 时间复杂度O(n), 空间复杂度O(1), 对撞指针
vector<int> twoSum2(vector<int>& numbers, int target) {
int i = 0;
vector<int> result;
if(numbers[i] > target)
return result ;
int j = numbers.size()-1;
while( j > i){
if(numbers[j] >= target){
j--;
continue;
}
if(numbers[i] + numbers[j] > target)
j--;
else if(numbers[i] + numbers[j] < target)
i++;
else{
result.push_back(i+1);
result.push_back(j+1);
return result;
}
}
return result;
}
int main()
{
vector<int> ivec = { -1, 0};
vector<int> vec = twoSum1(ivec, -1);
for(auto i : vec)
cout << i << " ";
cout << endl;
return 0;
}
| [
"335181140@qq.com"
] | 335181140@qq.com |
6db0d0ae48960109b30c22d919ca11f857788ff4 | b4ba3bc2725c8ff84cd80803c8b53afbe5e95e07 | /Medusa/Medusa/Geometry/Size3.h | a8a89c08ec57e315cb8cf864dacd7e638b6e29c5 | [
"MIT"
] | permissive | xueliuxing28/Medusa | c4be1ed32c2914ff58bf02593f41cf16e42cc293 | 15b0a59d7ecc5ba839d66461f62d10d6dbafef7b | refs/heads/master | 2021-06-06T08:27:41.655517 | 2016-10-08T09:49:54 | 2016-10-08T09:49:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,396 | h | // Copyright (c) 2015 fjz13. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
#pragma once
#include "MedusaPreDeclares.h"
#include "Core/Assertion/CommonAssert.h"
#include "Geometry/Size2.h"
#include "Core/Math/Math.h"
#include "Core/System/BitConverter.h"
MEDUSA_BEGIN;
template<typename T>
class Size3
{
public:
union
{
T Buffer[3];
struct
{
T Width;
T Height;
T Depth;
};
};
const static Size3 Zero;
public:
Size3(void){}
Size3(T width,T height,T depth):Width(width),Height(height),Depth(depth){}
template<typename T1>
Size3(const Size3<T1>& size):Width((T)size.Width),Height((T)size.Height),Depth((T)size.Depth){}
template<typename T1>
Size3(const Size2<T1>& size):Width((T)size.Width),Height((T)size.Height),Depth((T)0){}
template<typename T1>
explicit Size3(T1 val):Width((T)val),Height((T)val),Depth((T)val){}
template<typename T1>
Size3& operator=(const Size3<T1>& size){Width=(T)size.Width;Height=(T)size.Height;Depth=(T)size.Depth;return *this;}
template<typename T1>
Size3& operator=(const Size2<T1>& size){Width=(T)size.Width;Height=(T)size.Height;Depth=(T)0;return *this;}
template<typename T1>
Size3& operator=(T1 val){Width=(T)val;Height=(T)val;Depth=(T)val;return *this;}
template<typename T1>
bool operator==(const Size3<T1>& size)const{return Math::IsEqual(Width,size.Width)&&Math::IsEqual(Height,size.Height)&&Math::IsEqual(Depth,size.Depth);}
template<typename T1>
bool operator!=(const Size3<T1>& size)const{return !operator==(size);}
template<typename T1>
bool operator>(const Size3<T1>& size)const{return Width>size.Width&&Height>size.Height&&Depth>size.Depth;}
template<typename T1>
bool operator<(const Size3<T1>& size)const{return Width<size.Width&&Height<size.Height&&Depth<size.Depth;}
template<typename T1>
bool operator>=(const Size3<T1>& size)const{return Width>=size.Width&&Height>=size.Height&&Depth>=size.Depth;}
template<typename T1>
bool operator<=(const Size3<T1>& size)const{return Width<=size.Width&&Height<=size.Height&&Depth<=size.Depth;}
template<typename T1>
Size3 operator+(const Size3<T1>& size)const{return Size3(Width+size.Width,Height+size.Height,Depth+size.Depth);}
template<typename T1>
Size3 operator-(const Size3<T1>& size)const{return Size3(Width-size.Width,Height-size.Height,Depth-size.Depth);}
template<typename T1>
Size3& operator+=(const Size3<T1>& size){Width+=size.Width;Height+=size.Height;Depth+=size.Depth;return *this;}
template<typename T1>
Size3& operator-=(const Size3<T1>& size){Width-=size.Width;Height-=size.Height;Depth-=size.Depth;return *this;}
template<typename T1>
Size3 operator*(T1 delta)const{return Size3(Width*delta,Height*delta,Depth*delta);}
template<typename T1>
Size3& operator*=(T1 delta){Width*=delta;Height*=delta;Depth*=delta;return *this;}
template<typename T1>
Size3 operator/(T1 delta)const{MEDUSA_ASSERT_NOT_ZERO(delta,"");return Size3(Width/delta,Height/delta,Depth/delta);}
template<typename T1>
Size3& operator/=(T1 delta){MEDUSA_ASSERT_NOT_ZERO(delta,"");Width/=delta;Height/=delta;Depth/=delta;return *this;}
template<typename T1>
Size3 operator+(T1 delta)const{return Size3(Width+delta,Height+delta,Depth+delta);}
template<typename T1>
Size3& operator+=(T1 delta){Width+=delta;Height+=delta;Depth+=delta;return *this;}
template<typename T1>
Size3 operator-(T1 delta)const{return Size3(Width-delta,Height-delta,Depth-delta);}
template<typename T1>
Size3& operator-=(T1 delta){Width-=delta;Height-=delta;Depth-=delta;return *this;}
Size3 operator<<(uint32 delta)const{return Size3(Width<<delta,Height<<delta,Depth<<delta);}
Size3& operator<<=(uint32 delta){Width<<=delta;Height<<=delta;Depth<<=delta;return *this;}
Size3 operator>>(uint32 delta)const{return Size3(Width>>delta,Height>>delta,Depth>>delta);}
Size3& operator>>=(uint32 delta){Width>>=delta;Height>>=delta;Depth>>=delta;return *this;}
Size3& operator++(){++Width;++Height;++Depth;return *this;}
Size3& operator--(){--Width;--Height;--Depth;return *this;}
Size3 operator++(int){Size3 orign=*this;++Width;++Height;++Depth;return orign;}
Size3 operator--(int){Size3 orign=*this;--Width;--Height;--Depth;return orign;}
Size3 operator-()const { return Size3(-Width, -Height,-Depth); }
template<typename T1>
friend Size3 operator*(T1 delta,const Size3<T>& size){return Size3(delta*size.Width,delta*size.Height,delta*size.Depth);}
Size2<T> To2D()const{return Size2<T>(Width,Height);}
bool IsEmpty()const{return Math::IsZero(Width)||Math::IsZero(Height)||Math::IsZero(Depth);}
T Volume()const{return Width*Height*Depth;}
intp HashCode()const{return HashUtility::Hash(Buffer);}
bool IsNearlyZero(float tolerance = 1.e-4f)const
{
return Math::Abs(Width) <= tolerance && Math::Abs(Height) <= tolerance&&Math::Abs(Depth) <= tolerance;
}
static Size3 LinearInterpolate(const Size3& begin,const Size3& end,float blend)
{
return Size2<T>(Math::LinearInterpolate(begin.Width,end.Width,blend),Math::LinearInterpolate(begin.Height,end.Height,blend),Math::LinearInterpolate(begin.Depth,end.Depth,blend));
}
};
template<typename T>
MEDUSA_WEAK_MULTIPLE_DEFINE const Size3<T> Size3<T>::Zero(0,0,0);
//[PRE_DECLARE_BEGIN]
typedef Size3<uint32> Size3U;
typedef Size3<int> Size3I;
typedef Size3<float> Size3F;
//[PRE_DECLARE_END]
#define msize3u(x,y,z) Size3U(x,y,z)
#define msize3i(x,y,z) Size3I(x,y,z)
#define msize3(x,y,z) Size3F(x,y,z)
MEDUSA_END;
#ifdef MEDUSA_LUA
#include "Core/Lua/LuaState.h"
MEDUSA_BEGIN;
template <typename T>
struct LuaTypeMapping <Size3<T>>//[IGNORE_PRE_DECLARE]
{
static void Push(lua_State* L, const Size3<T>& val)
{
LuaStack s(L);
s.NewTable(0, 3);
s.Rawset("Width", val.Width);
s.Rawset("Height", val.Height);
s.Rawset("Depth", val.Depth);
}
static Size3<T> Get(lua_State* L, int index)
{
Size3<T> result;
LuaStack s(L);
result.Width = s.Get<T>("Width",index);
result.Height = s.Get<T>("Height",index);
result.Depth = s.Get<T>("Depth",index);
return result;
}
static Size3<T> Optional(lua_State* L, int index, const Size3<T>& def)
{
return lua_isnoneornil(L, index) ? Size3<T>::Zero : Get(L, index);
}
static bool TryGet(lua_State* L, int index, Size3<T>& outValue)
{
RETURN_FALSE_IF(lua_isnoneornil(L, index));
outValue = Get(L, index);
return true;
}
};
MEDUSA_END;
#endif
| [
"fjz13@live.cn"
] | fjz13@live.cn |
8b216672a7fd7fc582af19186085131e3308e1a3 | d63e9b801d9b1e5b959310db757c7e13fa51c5d7 | /C++/Queue_Wt/Queue_Wt/Queue_Wt.hpp | a9c8cc510b030da2de4098e1e6beb8746c47350e | [] | no_license | BillMark98/xcode | 5a5a6257d02bd15f64e6b2eba92beee7ae602970 | 9da7a1632b0448fde9cf0e02bed3e25d32c1cc35 | refs/heads/master | 2020-04-02T10:17:18.161830 | 2018-10-23T13:33:55 | 2018-10-23T13:33:55 | 154,330,027 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,249 | hpp | //
// Queue_Wt.hpp
// Queue_Wt
//
// Created by Bill on 10/31/17.
// Copyright © 2017 Bill. All rights reserved.
//
#ifndef Queue_Wt_hpp
#define Queue_Wt_hpp
#include <iostream>
#include <string>
#include <iomanip>
using std::cout;
using std::cin;
using std::endl;
using std::setw;
using std::string;
template < typename T>
class Queue
{
class Node
{
public:
T item;
Node * next;
Node(const T & it): item(it),next(nullptr) {}
};
private:
/*struct Node
{
T item;
Node * next;
};*/
enum {Q_SIZE = 10};
Node * front;
Node * rear;
int items;
const int qsize;
Queue(const Queue & q) : qsize(0),items(0) {}
Queue & operator[](const Queue & q) {return *this;}
public:
Queue(int qs = Q_SIZE) : qsize(qs){ front = rear = nullptr; items = 0;}
~Queue();
bool isempty() const {return items == 0;}
bool isfull() const { return items == qsize;}
int queuecount() const {return items;}
bool enqueue(const T & item);
bool dequeue(T & item);
};
template <typename T>
Queue<T>::~Queue()
{
Node * temp = front;
while(temp != nullptr)
{
temp = front;
front = front -> next;
delete temp;
}
}
template <typename T>
bool Queue<T>::enqueue(const T & item)
{
if(isfull())
return false;
/*Node * temp = new Node;
temp -> item = item;
temp -> next = nullptr;*/
Node * temp = new Node(item);
if(rear == nullptr)
{
front = rear = temp;
//front -> next = rear -> next = nullptr;
}
else
{
rear -> next = temp;
}
items ++;
rear = temp;
return true;
}
template <typename T>
bool Queue<T>::dequeue(T & item)
{
if(isempty())
return false;
Node * temp = front;
item = front -> item;
front = front -> next;
delete temp;
items --;
if(front == nullptr)
rear = nullptr;
return true;
}
class Worker
{
private:
string fullname;
long id;
public:
Worker(): fullname("no one"),id(0L) {}
Worker(const string & s, long n) : fullname(s),id(n) {}
~Worker() {}
void Set();
void Show() const;
};
#endif /* Queue_Wt_hpp */
| [
"panwei.hu@rwth-aachen.de"
] | panwei.hu@rwth-aachen.de |
c1d503576b286fc58fc0c0bdf8b77e78cae54f4a | dd20b761f4f5df086f9c3c64f1e642286270324e | /adjacency_list/adjacency_list.cpp | a1409880fa52c7990756324be96f790066faa4c3 | [
"MIT"
] | permissive | guiaugusto/cpp_playground | bccaab8710af1a243e65cdb7a3f5707df6e7988c | e68b4c1c209b9bc4ea1a44bcd81d4ccb8fafa678 | refs/heads/master | 2020-05-17T01:05:07.647080 | 2019-05-22T18:37:43 | 2019-05-22T18:37:43 | 183,416,317 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,231 | cpp | #include <bits/stdc++.h>
using namespace std;
class Node{
public:
int index;
vector<int> list;
bool visited;
};
vector<Node> nodes;
void marked_as_visited(int c){
nodes[c].visited = true;
vector<int>::iterator begin = nodes[c].list.begin();
for(int i = 0; i < nodes[c].list.size(); i++){
if(!nodes[nodes[c].list[i]].visited){
marked_as_visited(nodes[c].list[i]);
nodes[c].list.erase(begin+i);
i--;
}
}
}
int main(){
int n, q, qc, c, res = 0;
int from, to;
Node node_aux;
vector<int> vazio;
cin >> n >> q;
for(int i = 0; i < n; i++){
node_aux.index = i;
node_aux.list = vazio;
node_aux.visited = false;
nodes.push_back(node_aux);
}
for(int i = 0; i < q; i++){
cin >> from >> to;
nodes[from-1].list.push_back(to-1);
nodes[to-1].list.push_back(from-1);
}
cin >> qc;
for(int i = 0; i < qc; i++){
cin >> c;
marked_as_visited(c-1);
}
for(int i = 0; i < nodes.size(); i++){
if(!nodes[i].visited){
marked_as_visited(i);
res++;
}
}
cout << res << endl;
}
| [
"guilherme.francais@gmail.com"
] | guilherme.francais@gmail.com |
850b2170278b8c1cccb53545ebf47af1253083ba | 397e5b58b968f122fbac156a84392334a237b0f6 | /include/DetectorConstruction_Messenger.hh | 6073319c8ec626102975b7d9ffd16f4987df8d5c | [] | no_license | aschester/TIP_Coulex_RDM | f0ccdf17c36d470c3ede7f1ec73a02d383a5ef68 | f09c78661cf1ee8c7d42d8b2dc031acda6e48a6a | refs/heads/master | 2021-01-01T18:57:05.616869 | 2017-07-26T21:41:54 | 2017-07-26T21:41:54 | 98,467,464 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 740 | hh | #ifndef DetectorConstruction_Messenger_h
#define DetectorConstruction_Messenger_h 1
#include "DetectorConstruction.hh"
#include "globals.hh"
#include "G4UImessenger.hh"
#include "G4UIdirectory.hh"
#include "G4UIcmdWithAString.hh"
#include "G4UIcmdWithADoubleAndUnit.hh"
#include "G4UIcmdWithoutParameter.hh"
class DetectorConstruction_Messenger: public G4UImessenger
{
public:
DetectorConstruction_Messenger(DetectorConstruction*);
~DetectorConstruction_Messenger();
void SetNewValue(G4UIcommand*, G4String);
private:
DetectorConstruction* theDetector;
G4UIdirectory* DetectorDir;
G4UIcmdWithoutParameter* RepCmd;
G4UIcmdWithADoubleAndUnit* STCmd;
G4UIcmdWithADoubleAndUnit* SPCmd;
};
#endif
| [
"noreply@github.com"
] | aschester.noreply@github.com |
83ca2014792c62eb3b1a554386d63be592d6f227 | 438e2b02741015225f5b54130f3a97d4005c3f58 | /BOJ/1275.cpp | 0e3c88a03ca2808d581071c5f58fe5ea280fd4a6 | [] | no_license | jiho5993/solving_algorithm | 20c2e3e3ee6e14116554d0fd00918447ca21784c | fbbe52bc372d418e204128e78432038dfb60b410 | refs/heads/master | 2022-10-27T13:36:27.393518 | 2022-10-16T09:32:18 | 2022-10-16T09:32:18 | 193,317,544 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,544 | cpp | #include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(), (x).end()
typedef long long ll;
ll arr[100001];
typedef struct SegTree {
vector<ll> tree;
int size;
SegTree(int N): size(N) {
tree.resize(N*4);
}
ll init(int node, int st, int en) {
if(st == en) return tree[node] = arr[st];
int mid = (st+en)/2;
return tree[node] = init(node*2, st, mid) + init(node*2+1, mid+1, en);
}
void update(int idx, ll diff) { update(1, 0, size-1, idx, diff); }
void update(int node, int st, int en, int idx, ll diff) {
if(!(st <= idx && idx <= en)) return;
tree[node] += diff;
if(st != en) {
int mid = (st+en)/2;
update(node*2, st, mid, idx, diff);
update(node*2+1, mid+1, en, idx, diff);
}
}
ll sum(int left, int right) { return sum(1, 0, size-1, left, right); }
ll sum(int node, int st, int en, int left, int right) {
if(en < left || right < st) return 0;
if(left <= st && en <= right) return tree[node];
int mid = (st+en)/2;
return sum(node*2, st, mid, left, right) + sum(node*2+1, mid+1, en, left, right);
}
} ST;
int main() {
ios_base::sync_with_stdio(false), cin.tie(0);
int N, Q; cin >> N >> Q;
for(int i=0; i<N; i++) cin >> arr[i];
ST tree(N);
tree.init(1, 0, N-1);
while(Q--) {
int a, b, c, d; cin >> a >> b >> c >> d;
if(a > b) swap(a, b);
cout << tree.sum(a-1, b-1) << '\n';
ll diff = d-arr[c-1];
arr[c-1] = d;
tree.update(c-1, diff);
}
return 0;
} | [
"jiho5993@naver.com"
] | jiho5993@naver.com |
70808b5a528d05962adaa67cadc6783fa4d37556 | b04aba222b36f229061fd38edf806aae31534449 | /include/scalapackpp/wrappers/linear_systems/posv.hpp | 8758c3e780d55df9cdcf9c58c029d19cf7bbd273 | [] | no_license | ValeevGroup/scalapackpp | 49ce1a5db96b0585f214d0115fcaad46fc1c3e92 | 321b6fc8749fd020042fd1d75cb2292613cec178 | refs/heads/master | 2022-06-13T01:48:12.633522 | 2020-02-07T17:03:49 | 2020-02-07T17:03:49 | 239,920,851 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 437 | hpp | #pragma once
#include <scalapackpp/types.hpp>
#include <scalapackpp/util/sfinae.hpp>
namespace scalapackpp::wrappers {
template <typename T>
detail::enable_if_scalapack_supported_t<T, scalapack_int>
pposv( const char* UPLO, scalapack_int N, scalapack_int NRHS,
const T* A, scalapack_int IA, scalapack_int JA, const scalapack_desc& DESCA,
T* B, scalapack_int IB, scalapack_int JB, const scalapack_desc& DESCB );
}
| [
"dbwy@lbl.gov"
] | dbwy@lbl.gov |
5b0230bd6ca0c645077030692a6fa632e67482f8 | fb61b5a0264d42d976ee383b7302779621aab327 | /02_OF_cylinder/ppWall/5/U | 2c8c31ab6f0d3b3848f62b8d0e5da58763e0db75 | [] | no_license | Ccaccia73/Aerodinamica | 31062b24a6893262000df2f3d53dde304969182a | 49485cde03a6a4fd569722c9ca4b3558825221ad | refs/heads/master | 2021-01-23T03:16:31.037716 | 2018-01-21T14:55:05 | 2018-01-21T14:55:05 | 86,064,538 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 10,328 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 4.1 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volVectorField;
location "5";
object U;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 1 -1 0 0 0 0];
internalField nonuniform List<vector>
400
(
(0.025 -1.63442e-16 0)
(0.025 -1.02891e-16 0)
(0.025 3.3873e-18 0)
(0.025 -7.86043e-18 0)
(0.025 7.16088e-18 0)
(0.025 -7.7648e-18 0)
(0.025 7.22531e-18 0)
(0.025 -3.61277e-18 0)
(0.025 3.95437e-19 0)
(0.025 -2.78522e-18 0)
(0.025 3.6346e-18 0)
(0.025 2.49842e-18 0)
(0.025 -2.16921e-18 0)
(0.025 -1.93857e-18 0)
(0.025 -4.705e-18 0)
(0.025 3.06388e-18 0)
(0.025 -1.88352e-18 0)
(0.025 4.00054e-18 0)
(0.025 -5.98892e-17 0)
(0.025 -9.46342e-17 0)
(0.075 -6.86875e-16 0)
(0.075 -5.12172e-16 0)
(0.075 -4.10061e-18 0)
(0.075 -2.4642e-17 0)
(0.075 2.15357e-17 0)
(0.075 -2.81892e-17 0)
(0.075 2.66668e-17 0)
(0.075 -9.70675e-18 0)
(0.075 -3.17665e-18 0)
(0.075 -1.00084e-17 0)
(0.075 1.57736e-17 0)
(0.075 1.3311e-17 0)
(0.075 -7.34549e-18 0)
(0.075 -1.43516e-17 0)
(0.075 -2.00545e-17 0)
(0.075 1.10498e-17 0)
(0.075 -6.00873e-18 0)
(0.075 1.54285e-17 0)
(0.075 -3.20519e-16 0)
(0.075 -4.31488e-16 0)
(0.125 -1.52225e-15 0)
(0.125 -1.27652e-15 0)
(0.125 -4.54593e-17 0)
(0.125 -3.96384e-17 0)
(0.125 3.41347e-17 0)
(0.125 -5.30348e-17 0)
(0.125 5.16068e-17 0)
(0.125 -1.42723e-17 0)
(0.125 -1.6441e-17 0)
(0.125 -2.01759e-17 0)
(0.125 3.8705e-17 0)
(0.125 3.24285e-17 0)
(0.125 -1.41058e-17 0)
(0.125 -4.02875e-17 0)
(0.125 -4.64532e-17 0)
(0.125 2.32484e-17 0)
(0.125 -1.01305e-17 0)
(0.125 2.83635e-17 0)
(0.125 -8.35877e-16 0)
(0.125 -1.02086e-15 0)
(0.175 -2.46166e-15 0)
(0.175 -2.21436e-15 0)
(0.175 -1.15884e-16 0)
(0.175 -4.56795e-17 0)
(0.175 4.22127e-17 0)
(0.175 -7.93279e-17 0)
(0.175 7.68652e-17 0)
(0.175 -1.33537e-17 0)
(0.175 -4.03005e-17 0)
(0.175 -3.21412e-17 0)
(0.175 6.72488e-17 0)
(0.175 5.7145e-17 0)
(0.175 -1.85104e-17 0)
(0.175 -7.51122e-17 0)
(0.175 -8.00405e-17 0)
(0.175 3.7998e-17 0)
(0.175 -1.31194e-17 0)
(0.175 4.22554e-17 0)
(0.175 -1.50708e-15 0)
(0.175 -1.74389e-15 0)
(0.225 -3.35311e-15 0)
(0.225 -3.16604e-15 0)
(0.225 -2.03295e-16 0)
(0.225 -4.14634e-17 0)
(0.225 4.41501e-17 0)
(0.225 -1.06422e-16 0)
(0.225 1.03468e-16 0)
(0.225 -7.54734e-18 0)
(0.225 -7.34495e-17 0)
(0.225 -4.78043e-17 0)
(0.225 1.01886e-16 0)
(0.225 8.32988e-17 0)
(0.225 -2.0438e-17 0)
(0.225 -1.14388e-16 0)
(0.225 -1.13803e-16 0)
(0.225 5.51259e-17 0)
(0.225 -1.81307e-17 0)
(0.225 5.18157e-17 0)
(0.225 -2.2341e-15 0)
(0.225 -2.49728e-15 0)
(0.275 -4.09107e-15 0)
(0.275 -4.00756e-15 0)
(0.275 -2.92567e-16 0)
(0.275 -3.19341e-17 0)
(0.275 4.22998e-17 0)
(0.275 -1.30287e-16 0)
(0.275 1.28669e-16 0)
(0.275 5.24956e-18 0)
(0.275 -1.11347e-16 0)
(0.275 -6.88367e-17 0)
(0.275 1.36818e-16 0)
(0.275 1.08514e-16 0)
(0.275 -1.57828e-17 0)
(0.275 -1.52772e-16 0)
(0.275 -1.48301e-16 0)
(0.275 7.05401e-17 0)
(0.275 -2.19275e-17 0)
(0.275 5.73473e-17 0)
(0.275 -2.93229e-15 0)
(0.275 -3.1966e-15 0)
(0.325 -4.60325e-15 0)
(0.325 -4.64796e-15 0)
(0.325 -3.76358e-16 0)
(0.325 -1.60505e-17 0)
(0.325 3.707e-17 0)
(0.325 -1.49847e-16 0)
(0.325 1.53995e-16 0)
(0.325 1.82288e-17 0)
(0.325 -1.51595e-16 0)
(0.325 -8.92879e-17 0)
(0.325 1.67683e-16 0)
(0.325 1.30057e-16 0)
(0.325 -7.13734e-18 0)
(0.325 -1.8552e-16 0)
(0.325 -1.80517e-16 0)
(0.325 8.03663e-17 0)
(0.325 -2.04971e-17 0)
(0.325 6.18502e-17 0)
(0.325 -3.53506e-15 0)
(0.325 -3.77985e-15 0)
(0.375 -4.84633e-15 0)
(0.375 -5.02838e-15 0)
(0.375 -4.4697e-16 0)
(0.375 3.43088e-18 0)
(0.375 3.09221e-17 0)
(0.375 -1.64555e-16 0)
(0.375 1.81019e-16 0)
(0.375 2.75651e-17 0)
(0.375 -1.94577e-16 0)
(0.375 -1.03217e-16 0)
(0.375 1.94797e-16 0)
(0.375 1.45321e-16 0)
(0.375 4.92203e-18 0)
(0.375 -2.10282e-16 0)
(0.375 -2.08516e-16 0)
(0.375 8.37388e-17 0)
(0.375 -1.29865e-17 0)
(0.375 6.33526e-17 0)
(0.375 -3.98719e-15 0)
(0.375 -4.19071e-15 0)
(0.425 -4.80648e-15 0)
(0.425 -5.12694e-15 0)
(0.425 -4.94139e-16 0)
(0.425 2.80945e-17 0)
(0.425 1.9392e-17 0)
(0.425 -1.68989e-16 0)
(0.425 2.01054e-16 0)
(0.425 3.49329e-17 0)
(0.425 -2.36454e-16 0)
(0.425 -1.10146e-16 0)
(0.425 2.19307e-16 0)
(0.425 1.49498e-16 0)
(0.425 1.4915e-17 0)
(0.425 -2.1969e-16 0)
(0.425 -2.27499e-16 0)
(0.425 7.79375e-17 0)
(0.425 -1.36894e-18 0)
(0.425 6.66469e-17 0)
(0.425 -4.24856e-15 0)
(0.425 -4.39552e-15 0)
(0.475 -4.49542e-15 0)
(0.475 -4.94428e-15 0)
(0.475 -5.08008e-16 0)
(0.475 5.39534e-17 0)
(0.475 2.46781e-18 0)
(0.475 -1.63248e-16 0)
(0.475 2.11683e-16 0)
(0.475 4.14842e-17 0)
(0.475 -2.68841e-16 0)
(0.475 -1.19613e-16 0)
(0.475 2.36995e-16 0)
(0.475 1.45162e-16 0)
(0.475 2.62059e-17 0)
(0.475 -2.16309e-16 0)
(0.475 -2.37383e-16 0)
(0.475 6.52932e-17 0)
(0.475 1.02234e-17 0)
(0.475 6.96942e-17 0)
(0.475 -4.29586e-15 0)
(0.475 -4.37761e-15 0)
(0.525 -3.9569e-15 0)
(0.525 -4.50333e-15 0)
(0.525 -4.91101e-16 0)
(0.525 7.28154e-17 0)
(0.525 -1.5306e-17 0)
(0.525 -1.47715e-16 0)
(0.525 2.14994e-16 0)
(0.525 4.15118e-17 0)
(0.525 -2.86744e-16 0)
(0.525 -1.23231e-16 0)
(0.525 2.42765e-16 0)
(0.525 1.29883e-16 0)
(0.525 3.95682e-17 0)
(0.525 -2.03943e-16 0)
(0.525 -2.39939e-16 0)
(0.525 5.54614e-17 0)
(0.525 1.72156e-17 0)
(0.525 7.15347e-17 0)
(0.525 -4.13098e-15 0)
(0.525 -4.14184e-15 0)
(0.575 -3.24452e-15 0)
(0.575 -3.86334e-15 0)
(0.575 -4.49835e-16 0)
(0.575 8.39648e-17 0)
(0.575 -3.25721e-17 0)
(0.575 -1.22815e-16 0)
(0.575 2.11093e-16 0)
(0.575 4.10279e-17 0)
(0.575 -2.95383e-16 0)
(0.575 -1.23126e-16 0)
(0.575 2.39401e-16 0)
(0.575 1.10639e-16 0)
(0.575 4.70455e-17 0)
(0.575 -1.86629e-16 0)
(0.575 -2.26491e-16 0)
(0.575 4.43936e-17 0)
(0.575 1.95724e-17 0)
(0.575 7.40034e-17 0)
(0.575 -3.77932e-15 0)
(0.575 -3.71481e-15 0)
(0.625 -2.43462e-15 0)
(0.625 -3.09685e-15 0)
(0.625 -3.89103e-16 0)
(0.625 9.15862e-17 0)
(0.625 -5.53413e-17 0)
(0.625 -9.2049e-17 0)
(0.625 1.97694e-16 0)
(0.625 4.92682e-17 0)
(0.625 -2.86074e-16 0)
(0.625 -1.31198e-16 0)
(0.625 2.24112e-16 0)
(0.625 1.00604e-16 0)
(0.625 4.84322e-17 0)
(0.625 -1.71422e-16 0)
(0.625 -1.95471e-16 0)
(0.625 3.15861e-17 0)
(0.625 1.68603e-17 0)
(0.625 7.65407e-17 0)
(0.625 -3.27573e-15 0)
(0.625 -3.14452e-15 0)
(0.675 -1.60897e-15 0)
(0.675 -2.2873e-15 0)
(0.675 -3.23073e-16 0)
(0.675 1.01992e-16 0)
(0.675 -7.70956e-17 0)
(0.675 -5.32052e-17 0)
(0.675 1.72744e-16 0)
(0.675 5.33235e-17 0)
(0.675 -2.60213e-16 0)
(0.675 -1.31635e-16 0)
(0.675 1.98584e-16 0)
(0.675 8.53645e-17 0)
(0.675 4.1368e-17 0)
(0.675 -1.61535e-16 0)
(0.675 -1.49546e-16 0)
(0.675 2.80224e-17 0)
(0.675 1.04492e-17 0)
(0.675 7.29014e-17 0)
(0.675 -2.66916e-15 0)
(0.675 -2.49328e-15 0)
(0.725 -8.59153e-16 0)
(0.725 -1.51893e-15 0)
(0.725 -2.55465e-16 0)
(0.725 1.06832e-16 0)
(0.725 -8.3744e-17 0)
(0.725 -2.01515e-17 0)
(0.725 1.33649e-16 0)
(0.725 5.24927e-17 0)
(0.725 -2.15596e-16 0)
(0.725 -1.25797e-16 0)
(0.725 1.67299e-16 0)
(0.725 6.20418e-17 0)
(0.725 3.22885e-17 0)
(0.725 -1.40618e-16 0)
(0.725 -1.04089e-16 0)
(0.725 2.29693e-17 0)
(0.725 3.00429e-18 0)
(0.725 6.34064e-17 0)
(0.725 -2.02744e-15 0)
(0.725 -1.82022e-15 0)
(0.775 -2.57206e-16 0)
(0.775 -8.69856e-16 0)
(0.775 -1.87093e-16 0)
(0.775 9.78688e-17 0)
(0.775 -8.2131e-17 0)
(0.775 7.89345e-18 0)
(0.775 9.10133e-17 0)
(0.775 3.63829e-17 0)
(0.775 -1.64375e-16 0)
(0.775 -1.02599e-16 0)
(0.775 1.30585e-16 0)
(0.775 4.15056e-17 0)
(0.775 2.13665e-17 0)
(0.775 -1.13225e-16 0)
(0.775 -5.8307e-17 0)
(0.775 1.94477e-17 0)
(0.775 -6.27511e-18 0)
(0.775 4.951e-17 0)
(0.775 -1.40469e-15 0)
(0.775 -1.18445e-15 0)
(0.825 1.4001e-16 0)
(0.825 -3.88237e-16 0)
(0.825 -1.28826e-16 0)
(0.825 7.12279e-17 0)
(0.825 -7.33466e-17 0)
(0.825 3.40088e-17 0)
(0.825 5.35721e-17 0)
(0.825 1.57367e-17 0)
(0.825 -1.20495e-16 0)
(0.825 -6.41861e-17 0)
(0.825 9.01961e-17 0)
(0.825 2.48468e-17 0)
(0.825 1.24278e-17 0)
(0.825 -8.36437e-17 0)
(0.825 -1.94592e-17 0)
(0.825 1.12115e-17 0)
(0.825 -1.40556e-17 0)
(0.825 3.41836e-17 0)
(0.825 -8.50665e-16 0)
(0.825 -6.46288e-16 0)
(0.875 2.92156e-16 0)
(0.875 -9.3292e-17 0)
(0.875 -8.02891e-17 0)
(0.875 4.00281e-17 0)
(0.875 -5.20977e-17 0)
(0.875 4.20719e-17 0)
(0.875 2.4081e-17 0)
(0.875 1.24121e-18 0)
(0.875 -7.68219e-17 0)
(0.875 -3.20565e-17 0)
(0.875 5.45158e-17 0)
(0.875 1.24346e-17 0)
(0.875 7.46547e-18 0)
(0.875 -4.66554e-17 0)
(0.875 -1.86172e-18 0)
(0.875 -3.11424e-18 0)
(0.875 -1.53548e-17 0)
(0.875 2.61e-17 0)
(0.875 -4.15422e-16 0)
(0.875 -2.53619e-16 0)
(0.925 2.46104e-16 0)
(0.925 1.9431e-17 0)
(0.925 -4.02636e-17 0)
(0.925 1.84241e-17 0)
(0.925 -3.04405e-17 0)
(0.925 3.05673e-17 0)
(0.925 1.06717e-17 0)
(0.925 -4.62345e-18 0)
(0.925 -4.19307e-17 0)
(0.925 -1.35844e-17 0)
(0.925 3.18854e-17 0)
(0.925 3.71058e-18 0)
(0.925 8.24278e-18 0)
(0.925 -1.9177e-17 0)
(0.925 3.87005e-19 0)
(0.925 -6.99901e-18 0)
(0.925 -9.3528e-18 0)
(0.925 1.37353e-17 0)
(0.925 -1.36414e-16 0)
(0.925 -3.50476e-17 0)
(0.975 9.21789e-17 0)
(0.975 1.9269e-17 0)
(0.975 -1.20951e-17 0)
(0.975 4.45301e-18 0)
(0.975 -9.59767e-18 0)
(0.975 1.11509e-17 0)
(0.975 2.59073e-19 0)
(0.975 -1.91008e-18 0)
(0.975 -1.14918e-17 0)
(0.975 -2.98895e-18 0)
(0.975 9.78727e-18 0)
(0.975 -4.76877e-19 0)
(0.975 1.94634e-18 0)
(0.975 -3.28777e-18 0)
(0.975 -1.50696e-18 0)
(0.975 -4.59078e-18 0)
(0.975 -5.28051e-19 0)
(0.975 2.69132e-18 0)
(0.975 -1.72461e-17 0)
(0.975 1.34087e-17 0)
)
;
boundaryField
{
top
{
type fixedValue;
value uniform (1 0 0);
}
bottom
{
type fixedValue;
value uniform (0 0 0);
}
inlet
{
type zeroGradient;
}
outlet
{
type zeroGradient;
}
frontAndBack
{
type empty;
}
}
// ************************************************************************* //
| [
"c.caccia@libero.it"
] | c.caccia@libero.it | |
31cc2f89f1954b3b5018f203b67b5ce4f91d9211 | 3288e8ff6adc21524a399dd97fc018469520b323 | /cpp_cookbok/3-5.cpp | e5f6ae78a86f2ea275d43c8e7d89d33e2a1e98e2 | [] | no_license | arraytools/C | 2a04cfe07da43d385dc1c3b3b86e6f9cd0099a52 | 42e127024f19ad432d82240cca9435ec3882a542 | refs/heads/master | 2018-12-28T16:07:51.710347 | 2015-01-17T00:25:20 | 2015-01-17T00:25:20 | 10,589,340 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 904 | cpp | #include <iostream>
#include <boost/lexical_cast.hpp>
using namespace std;
using boost::lexical_cast;
using boost::bad_lexical_cast;
template<typename T>
bool isValid(const string& num) {
bool res = true;
try {
T tmp = lexical_cast<T>(num);
}
catch (bad_lexical_cast &e) {
res = false;
}
return(res);
}
void test(const string& s) {
if (isValid<int>(s))
cout << s << " is a valid integer." << endl;
else
cout << s << " is NOT a valid integer." << endl;
if (isValid<double>(s))
cout << s << " is a valid double." << endl;
else
cout << s << " is NOT a valid double." << endl;
if (isValid<float>(s))
cout << s << " is a valid float." << endl;
else
cout << s << " is NOT a valid float." << endl;
}
int main( ) {
test("12345");
test("1.23456");
test("-1.23456");
test(" - 1.23456");
test("+1.23456");
test(" 1.23456 ");
test("asdf");
}
| [
"arraytools@gmail.com"
] | arraytools@gmail.com |
5d03165d9339fbf6d9dc4eaf388c284d3d861b23 | 8e86c2e07a7f3c275c395761634c0ed2ed412db8 | /uva/10004-Bicoloring/solution.cpp | e803569b584f424e89f1b3a81767c1c1e811bf4d | [] | no_license | ramirezjpdf/problems | e145d82d876f7c4d0b99a6453a22aecec07d1fe5 | 0896b8e072f5a29752f02d38878ac361ed3586b5 | refs/heads/master | 2021-01-19T19:38:06.205467 | 2017-04-17T14:31:42 | 2017-04-17T14:31:42 | 88,431,062 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,315 | cpp | #include <iostream>
#include <vector>
#include <queue>
using namespace std;
const int MAXV = 200;
const int MAXDEGREE = 200;
struct graph{
vector<vector<int> > edges;
vector<int> degrees;
int nvertices;
int nedges;
graph() : edges(MAXV, vector<int>(MAXDEGREE)),
degrees(MAXV, 0) {}
};
void insertedge(graph &g, int x, int y, bool directed) {
if (g.degrees[x] > MAXDEGREE) {
cout << "Warning: insertion(" << x << ", " << y;
cout << " exceeds max degrees" << endl;
}
g.edges[x][g.degrees[x]] = y;
g.degrees[x]++;
if (directed) insertedge(g, y, x, false);
else g.nedges++;
}
bool readgraph(graph &g, bool directed) {
int m;
int x, y;
cin >> g.nvertices >> m;
if (g.nvertices == 0) return false;
for (int i = 0; i < m; i++) {
cin >> x >> y;
insertedge(g, x, y, directed);
}
return true;
}
void printgraph(graph &g) {
for (vector<vector<int> >::iterator it = g.edges.begin();
it != g.edges.end(); ++it) {
cout << (it - g.edges.begin()) << ":";
for (vector<int>::iterator it2 = (*it).begin();
it2 != (*it).end(); ++it2) {
cout << " " << *it2;
}
cout << endl;
}
}
const int RED = 2;
const int BLUE = 3;
const int UNCOLOR = 0;
int ccolor(int color) {
if (color == RED) return BLUE;
if (color == BLUE) return RED;
if (color = UNCOLOR) return UNCOLOR;
}
bool bicoloredbfs(graph g, int start) {
vector<bool> discovered(g.nvertices, false);
vector<bool> processed(g.nvertices, false);
bool bicolored = true;
vector<int> colors(g.nvertices, UNCOLOR);
queue<int> q;
q.push(start);
discovered[start] = true;
colors[start] = RED;
while(!q.empty()) {
int v = q.front();
q.pop();
processed[v] = true;
for (int i = 0; i < g.degrees[v]; i++) {
if (!discovered[g.edges[v][i]]) {
q.push(g.edges[v][i]);
discovered[g.edges[v][i]] = true;
colors[g.edges[v][i]] = ccolor(colors[v]);
} else {
if (colors[v] == colors[g.edges[v][i]]) {
bicolored = false;
return bicolored;
}
}
}
}
return bicolored;
}
int main() {
graph *g = new graph();
while (readgraph(*g, false)) {
if (bicoloredbfs(*g, 0))
cout << "BICOLORABLE." << endl;
else
cout << "NOT BICOLORABLE." << endl;
delete g;
g = new graph();
}
delete g;
return 0;
} | [
"ramirez.jpdf@ymail.com"
] | ramirez.jpdf@ymail.com |
1838d39fc88c7664d78bd5cee5c32705f02e3700 | b72a026e8f6a3f7e87c8aefcb7ae50031fea9c71 | /backend/backend/passengernode.cpp | 73648bb5a1527f4d0a1d4317de77499967ce6096 | [] | no_license | quoccuonglqd/CTDL2018-2019 | ab985f691168ffb4a972b9e324bb14b225eb2e5a | ecd6c3b023b32effec8b629276596b8e84b635a9 | refs/heads/master | 2020-06-11T22:46:19.463247 | 2019-06-27T14:17:23 | 2019-06-27T14:17:23 | 194,110,991 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 554 | cpp | #include "stdafx.h"
#include "passengernode.h"
passengernode * passengernode::getleft() const
{
return left;
}
passengernode * passengernode::getright() const
{
return right;
}
passengernode * passengernode::getpar() const
{
return par;
}
void passengernode::setleft(passengernode * src)
{
left = src;
}
void passengernode::setright(passengernode * src)
{
right = src;
}
void passengernode::setpar(passengernode * src)
{
par = src;
}
passengernode::passengernode()
{
left = right = par = nullptr;
}
passengernode::~passengernode()
{
}
| [
"quoccuonglqd123@gmail.com"
] | quoccuonglqd123@gmail.com |
c78c28e786c707ef691a7ee1430e22affa1df716 | 54bd24a7ec00e2128e74704833035740926fe1a2 | /c3dEngine2/c3dEngine/c3dEngine/platform/win32/appFrame/mainWindowGlobal.cpp | 0616e9ea5140a25de95191681d4b717bd01f47d1 | [
"MIT"
] | permissive | qaz734913414/c3dEngine2 | 3739073d7d6f1046cdfce19ca7a5fdc9c7a9bada | 0c12d077d8f2bac8c12b8f720eccc5a2f3f3a7c1 | refs/heads/master | 2020-04-15T19:47:52.391730 | 2015-12-14T16:07:29 | 2015-12-14T16:07:29 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 479 | cpp | #include "mainWindowGlobal.h"
//global var
bool isTouching;
long tf=0,t=0,dt=0;//tf上次进入idle,t本次进入idle,dt本次与上次进入idle时间间隔--abc
float captionHeight=0;//标题栏高度--abc
float frameBoarder=0;//窗口边框宽度--abc
//win32 global var
HDC hDC=NULL; // Private GDI Device Context
HGLRC hRC=NULL; // Permanent Rendering Context
HWND hWnd=NULL; // Holds Our Window Handle
HINSTANCE hInstance; // Holds The Instance Of The Application | [
"350479720@qq.com"
] | 350479720@qq.com |
790244b04b966a3f6349a7430883688fcb39aba3 | 41a4994a18f3e3a411a63e028a5c75e2e5f820f4 | /2020_StressW/2020_StressW/DrawModule.cpp | ae3e298158d01e094697496d9923fbab36453cda | [] | no_license | JS-0125/2021GameServerTermProject | f2c74b954794b4b10346a06e93bcafb2434b4531 | 85c3ff47593f1a4c6d7ff789e5fb244a81c50b6c | refs/heads/main | 2023-05-27T12:54:29.419528 | 2021-06-15T14:49:11 | 2021-06-15T14:49:11 | 375,627,551 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 18,138 | cpp | /*
* This Code Was Created By Jeff Molofee 2000
* Modified by Shawn T. to handle (%3.2f, num) parameters.
* A HUGE Thanks To Fredric Echols For Cleaning Up
* And Optimizing The Base Code, Making It More Flexible!
* If You've Found This Code Useful, Please Let Me Know.
* Visit My Site At nehe.gamedev.net
*/
#include <windows.h> // Header File For Windows
#include <math.h> // Header File For Windows Math Library
#include <stdio.h> // Header File For Standard Input/Output
#include <stdarg.h> // Header File For Variable Argument Routines
#include <gl\gl.h> // Header File For The OpenGL32 Library
#include <gl\glu.h> // Header File For The GLu32 Library
#include <atomic>
#include <memory>
//#include <gl\glaux.h> // Header File For The Glaux Library
#pragma comment (lib, "opengl32.lib")
#pragma comment (lib, "glu32.lib")
#include "NetworkModule.h"
HDC hDC = NULL; // Private GDI Device Context
HGLRC hRC = NULL; // Permanent Rendering Context
HWND hWnd = NULL; // Holds Our Window Handle
HINSTANCE hInstance; // Holds The Instance Of The Application
GLuint base; // Base Display List For The Font Set
GLfloat cnt1; // 1st Counter Used To Move Text & For Coloring
GLfloat cnt2; // 2nd Counter Used To Move Text & For Coloring
bool keys[256]; // Array Used For The Keyboard Routine
bool active = TRUE; // Window Active Flag Set To TRUE By Default
bool fullscreen = TRUE; // Fullscreen Flag Set To Fullscreen Mode By Default
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); // Declaration For WndProc
GLvoid BuildFont(GLvoid) // Build Our Bitmap Font
{
HFONT font; // Windows Font ID
HFONT oldfont; // Used For Good House Keeping
base = glGenLists(96); // Storage For 96 Characters
font = CreateFont(-24, // Height Of Font
0, // Width Of Font
0, // Angle Of Escapement
0, // Orientation Angle
FW_BOLD, // Font Weight
FALSE, // Italic
FALSE, // Underline
FALSE, // Strikeout
ANSI_CHARSET, // Character Set Identifier
OUT_TT_PRECIS, // Output Precision
CLIP_DEFAULT_PRECIS, // Clipping Precision
ANTIALIASED_QUALITY, // Output Quality
FF_DONTCARE | DEFAULT_PITCH, // Family And Pitch
L"Courier New"); // Font Name
oldfont = (HFONT)SelectObject(hDC, font); // Selects The Font We Want
wglUseFontBitmaps(hDC, 32, 96, base); // Builds 96 Characters Starting At Character 32
SelectObject(hDC, oldfont); // Selects The Font We Want
DeleteObject(font); // Delete The Font
}
GLvoid KillFont(GLvoid) // Delete The Font List
{
glDeleteLists(base, 96); // Delete All 96 Characters
}
GLvoid glPrint(const char* fmt, ...) // Custom GL "Print" Routine
{
char text[256]; // Holds Our String
va_list ap; // Pointer To List Of Arguments
if (fmt == NULL) // If There's No Text
return; // Do Nothing
va_start(ap, fmt); // Parses The String For Variables
vsprintf_s(text, fmt, ap); // And Converts Symbols To Actual Numbers
va_end(ap); // Results Are Stored In Text
glPushAttrib(GL_LIST_BIT); // Pushes The Display List Bits
glListBase(base - 32); // Sets The Base Character to 32
glCallLists((GLsizei)strlen(text), GL_UNSIGNED_BYTE, text); // Draws The Display List Text
glPopAttrib(); // Pops The Display List Bits
}
GLvoid ReSizeGLScene(GLsizei width, GLsizei height) // Resize And Initialize The GL Window
{
if (height == 0) // Prevent A Divide By Zero By
{
height = 1; // Making Height Equal One
}
glViewport(0, 0, width, height); // Reset The Current Viewport
glMatrixMode(GL_PROJECTION); // Select The Projection Matrix
glLoadIdentity(); // Reset The Projection Matrix
// Calculate The Aspect Ratio Of The Window
gluPerspective(45.0f, (GLfloat)width / (GLfloat)height, 0.1f, 100.0f);
glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix
glLoadIdentity(); // Reset The Modelview Matrix
glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix
glLoadIdentity(); // Reset The Modelview Matrix
}
int InitGL(GLvoid) // All Setup For OpenGL Goes Here
{
glShadeModel(GL_SMOOTH); // Enable Smooth Shading
glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background
glClearDepth(1.0f); // Depth Buffer Setup
glEnable(GL_DEPTH_TEST); // Enables Depth Testing
glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations
BuildFont(); // Build The Font
return TRUE; // Initialization Went OK
}
int DrawGLScene(GLvoid) // Here's Where We Do All The Drawing
{
int size = 0;
float* points = nullptr;
// 클라이언트가 몇 개 접속, 캐릭터들 x,y 좌표
GetPointCloud(&size, &points);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer
glLoadIdentity(); // Reset The Current Modelview Matrix
glTranslatef(0.14f, -0.4f, -1.0f); // Move One Unit Into The Screen
// Pulsing Colors Based On Text Position
glColor3f(1, 1, 0);
// Position The Text On The Screen
glRasterPos2f(0.0f, 0.00f);
glPrint("STRESS TEST [%d]", (int)active_clients); // Print GL Text To The Screen
glRasterPos2f(0.0f, 0.05f);
glPrint("Delay : %dms", global_delay);
glColor3f(1, 1, 1);
glPointSize(2.0);
glBegin(GL_POINTS);
for (int i = 0; i < size; i++)
{
float x, y, z;
x = points[i * 2] / 200.0f - 1.25f;
y = 1.25f - points[i * 2 + 1] / 200.0f;
z = -1.0f;
glVertex3f(x, y, z);
}
glEnd();
return TRUE; // Everything Went OK
}
GLvoid KillGLWindow(GLvoid) // Properly Kill The Window
{
if (fullscreen) // Are We In Fullscreen Mode?
{
ChangeDisplaySettings(NULL, 0); // If So Switch Back To The Desktop
ShowCursor(TRUE); // Show Mouse Pointer
}
if (hRC) // Do We Have A Rendering Context?
{
if (!wglMakeCurrent(NULL, NULL)) // Are We Able To Release The DC And RC Contexts?
{
MessageBox(NULL, L"Release Of DC And RC Failed.", L"SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
}
if (!wglDeleteContext(hRC)) // Are We Able To Delete The RC?
{
MessageBox(NULL, L"Release Rendering Context Failed.", L"SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
}
hRC = NULL; // Set RC To NULL
}
if (hDC && !ReleaseDC(hWnd, hDC)) // Are We Able To Release The DC
{
MessageBox(NULL, L"Release Device Context Failed.", L"SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
hDC = NULL; // Set DC To NULL
}
if (hWnd && !DestroyWindow(hWnd)) // Are We Able To Destroy The Window?
{
MessageBox(NULL, L"Could Not Release hWnd.", L"SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
hWnd = NULL; // Set hWnd To NULL
}
if (!UnregisterClass(L"OpenGL", hInstance)) // Are We Able To Unregister Class
{
MessageBox(NULL, L"Could Not Unregister Class.", L"SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
hInstance = NULL; // Set hInstance To NULL
}
KillFont();
}
/* This Code Creates Our OpenGL Window. Parameters Are: *
* title - Title To Appear At The Top Of The Window *
* width - Width Of The GL Window Or Fullscreen Mode *
* height - Height Of The GL Window Or Fullscreen Mode *
* bits - Number Of Bits To Use For Color (8/16/24/32) *
* fullscreenflag - Use Fullscreen Mode (TRUE) Or Windowed Mode (FALSE) */
BOOL CreateGLWindow(const wchar_t* title, int width, int height, BYTE bits, bool fullscreenflag)
{
GLuint PixelFormat; // Holds The Results After Searching For A Match
WNDCLASS wc; // Windows Class Structure
DWORD dwExStyle; // Window Extended Style
DWORD dwStyle; // Window Style
RECT WindowRect; // Grabs Rectangle Upper Left / Lower Right Values
WindowRect.left = (long)0; // Set Left Value To 0
WindowRect.right = (long)width; // Set Right Value To Requested Width
WindowRect.top = (long)0; // Set Top Value To 0
WindowRect.bottom = (long)height; // Set Bottom Value To Requested Height
fullscreen = fullscreenflag; // Set The Global Fullscreen Flag
hInstance = GetModuleHandle(NULL); // Grab An Instance For Our Window
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Redraw On Size, And Own DC For Window.
wc.lpfnWndProc = (WNDPROC)WndProc; // WndProc Handles Messages
wc.cbClsExtra = 0; // No Extra Window Data
wc.cbWndExtra = 0; // No Extra Window Data
wc.hInstance = hInstance; // Set The Instance
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // Load The Default Icon
wc.hCursor = LoadCursor(NULL, IDC_ARROW); // Load The Arrow Pointer
wc.hbrBackground = NULL; // No Background Required For GL
wc.lpszMenuName = NULL; // We Don't Want A Menu
wc.lpszClassName = L"OpenGL"; // Set The Class Name
if (!RegisterClass(&wc)) // Attempt To Register The Window Class
{
MessageBox(NULL, L"Failed To Register The Window Class.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (fullscreen) // Attempt Fullscreen Mode?
{
DEVMODE dmScreenSettings; // Device Mode
memset(&dmScreenSettings, 0, sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared
dmScreenSettings.dmSize = sizeof(dmScreenSettings); // Size Of The Devmode Structure
dmScreenSettings.dmPelsWidth = width; // Selected Screen Width
dmScreenSettings.dmPelsHeight = height; // Selected Screen Height
dmScreenSettings.dmBitsPerPel = bits; // Selected Bits Per Pixel
dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
// Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.
if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
{
// If The Mode Fails, Offer Two Options. Quit Or Use Windowed Mode.
if (MessageBox(NULL, L"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?", L"NeHe GL", MB_YESNO | MB_ICONEXCLAMATION) == IDYES)
{
fullscreen = FALSE; // Windowed Mode Selected. Fullscreen = FALSE
}
else
{
// Pop Up A Message Box Letting User Know The Program Is Closing.
MessageBox(NULL, L"Program Will Now Close.", L"ERROR", MB_OK | MB_ICONSTOP);
return FALSE; // Return FALSE
}
}
}
if (fullscreen) // Are We Still In Fullscreen Mode?
{
dwExStyle = WS_EX_APPWINDOW; // Window Extended Style
dwStyle = WS_POPUP; // Windows Style
ShowCursor(FALSE); // Hide Mouse Pointer
}
else
{
dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Window Extended Style
dwStyle = WS_OVERLAPPEDWINDOW; // Windows Style
}
AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle); // Adjust Window To True Requested Size
// Create The Window
if (!(hWnd = CreateWindowEx(dwExStyle, // Extended Style For The Window
L"OpenGL", // Class Name
title, // Window Title
dwStyle | // Defined Window Style
WS_CLIPSIBLINGS | // Required Window Style
WS_CLIPCHILDREN, // Required Window Style
0, 0, // Window Position
WindowRect.right - WindowRect.left, // Calculate Window Width
WindowRect.bottom - WindowRect.top, // Calculate Window Height
NULL, // No Parent Window
NULL, // No Menu
hInstance, // Instance
NULL))) // Dont Pass Anything To WM_CREATE
{
KillGLWindow(); // Reset The Display
MessageBox(NULL, L"Window Creation Error.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
static PIXELFORMATDESCRIPTOR pfd = // pfd Tells Windows How We Want Things To Be
{
sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
1, // Version Number
PFD_DRAW_TO_WINDOW | // Format Must Support Window
PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
PFD_DOUBLEBUFFER, // Must Support Double Buffering
PFD_TYPE_RGBA, // Request An RGBA Format
bits, // Select Our Color Depth
0, 0, 0, 0, 0, 0, // Color Bits Ignored
0, // No Alpha Buffer
0, // Shift Bit Ignored
0, // No Accumulation Buffer
0, 0, 0, 0, // Accumulation Bits Ignored
16, // 16Bit Z-Buffer (Depth Buffer)
0, // No Stencil Buffer
0, // No Auxiliary Buffer
PFD_MAIN_PLANE, // Main Drawing Layer
0, // Reserved
0, 0, 0 // Layer Masks Ignored
};
if (!(hDC = GetDC(hWnd))) // Did We Get A Device Context?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL, L"Can't Create A GL Device Context.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd))) // Did Windows Find A Matching Pixel Format?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL, L"Can't Find A Suitable PixelFormat.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (!SetPixelFormat(hDC, PixelFormat, &pfd)) // Are We Able To Set The Pixel Format?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL, L"Can't Set The PixelFormat.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (!(hRC = wglCreateContext(hDC))) // Are We Able To Get A Rendering Context?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL, L"Can't Create A GL Rendering Context.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (!wglMakeCurrent(hDC, hRC)) // Try To Activate The Rendering Context
{
KillGLWindow(); // Reset The Display
MessageBox(NULL, L"Can't Activate The GL Rendering Context.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
ShowWindow(hWnd, SW_SHOW); // Show The Window
SetForegroundWindow(hWnd); // Slightly Higher Priority
SetFocus(hWnd); // Sets Keyboard Focus To The Window
ReSizeGLScene(width, height); // Set Up Our Perspective GL Screen
if (!InitGL()) // Initialize Our Newly Created GL Window
{
KillGLWindow(); // Reset The Display
MessageBox(NULL, L"Initialization Failed.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
return TRUE; // Success
}
LRESULT CALLBACK WndProc(HWND hWnd, // Handle For This Window
UINT uMsg, // Message For This Window
WPARAM wParam, // Additional Message Information
LPARAM lParam) // Additional Message Information
{
switch (uMsg) // Check For Windows Messages
{
case WM_ACTIVATE: // Watch For Window Activate Message
{
if (!HIWORD(wParam)) // Check Minimization State
{
active = TRUE; // Program Is Active
}
else
{
active = FALSE; // Program Is No Longer Active
}
return 0; // Return To The Message Loop
}
case WM_SYSCOMMAND: // Intercept System Commands
{
switch (wParam) // Check System Calls
{
case SC_SCREENSAVE: // Screensaver Trying To Start?
case SC_MONITORPOWER: // Monitor Trying To Enter Powersave?
return 0; // Prevent From Happening
}
break; // Exit
}
case WM_CLOSE: // Did We Receive A Close Message?
{
PostQuitMessage(0); // Send A Quit Message
return 0; // Jump Back
}
case WM_KEYDOWN: // Is A Key Being Held Down?
{
keys[wParam] = TRUE; // If So, Mark It As TRUE
return 0; // Jump Back
}
case WM_KEYUP: // Has A Key Been Released?
{
keys[wParam] = FALSE; // If So, Mark It As FALSE
return 0; // Jump Back
}
case WM_SIZE: // Resize The OpenGL Window
{
ReSizeGLScene(LOWORD(lParam), HIWORD(lParam)); // LoWord=Width, HiWord=Height
return 0; // Jump Back
}
}
// Pass All Unhandled Messages To DefWindowProc
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
int WINAPI WinMain(HINSTANCE hInstance, // Instance
HINSTANCE hPrevInstance, // Previous Instance
LPSTR lpCmdLine, // Command Line Parameters
int nCmdShow) // Window Show State
{
MSG msg; // Windows Message Structure
BOOL done = FALSE; // Bool Variable To Exit Loop
fullscreen = FALSE; // Windowed Mode
// Create Our OpenGL Window
if (!CreateGLWindow(L"Stress Test Client", 640, 480, 16, fullscreen))
{
return 0; // Quit If Window Was Not Created
}
InitializeNetwork();
while (!done) // Loop That Runs While done=FALSE
{
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) // Is There A Message Waiting?
{
if (msg.message == WM_QUIT) // Have We Received A Quit Message?
{
done = TRUE; // If So done=TRUE
}
else // If Not, Deal With Window Messages
{
TranslateMessage(&msg); // Translate The Message
DispatchMessage(&msg); // Dispatch The Message
}
}
else // If There Are No Messages
{
// Draw The Scene. Watch For ESC Key And Quit Messages From DrawGLScene()
if ((active && !DrawGLScene()) || keys[VK_ESCAPE]) // Active? Was There A Quit Received?
{
done = TRUE; // ESC or DrawGLScene Signalled A Quit
}
else // Not Time To Quit, Update Screen
{
SwapBuffers(hDC); // Swap Buffers (Double Buffering)
}
if (keys[VK_F1]) // Is F1 Being Pressed?
{
keys[VK_F1] = FALSE; // If So Make Key FALSE
KillGLWindow(); // Kill Our Current Window
fullscreen = !fullscreen; // Toggle Fullscreen / Windowed Mode
// Recreate Our OpenGL Window
if (!CreateGLWindow(L"NeHe's Bitmap Font Tutorial", 640, 480, 16, fullscreen))
{
return 0; // Quit If Window Was Not Created
}
}
}
}
// Shutdown
KillGLWindow(); // Kill The Window
return ((int)msg.wParam); // Exit The Program
}
| [
"realline@kpu.ac.kr"
] | realline@kpu.ac.kr |
1e6a0b3ca628c1fa0dcef34af9fda0d341923cf1 | c2672fa922da6f0c292206c99a551565a145d942 | /crazyclient/frameworks/cocos2d-x/cocos/scripting/lua-bindings/manual/cocostudio/lua-cocos-studio-conversions.cpp | b0044442be3dad998f90d39ff4f4adf08e5c543a | [
"MIT"
] | permissive | lache/RacingKingLee | 2b37d7962766cfc99cacc1949e55bd055715414b | eb3a961c6c71d44e797eb2394613e4c8196feb31 | refs/heads/master | 2022-11-09T02:24:15.448152 | 2015-07-27T16:40:09 | 2015-07-27T16:40:09 | 36,938,174 | 0 | 1 | MIT | 2022-10-27T05:03:56 | 2015-06-05T14:47:06 | C++ | UTF-8 | C++ | false | false | 3,174 | cpp | /****************************************************************************
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "lua-cocos-studio-conversions.h"
#include "ActionTimeline/CCActionTimeline.h"
#if COCOS2D_DEBUG >=1
extern void luaval_to_native_err(lua_State* L,const char* msg,tolua_Error* err, const char* funcName);
#endif
bool luaval_to_animationInfo(lua_State* L, int lo, cocostudio::timeline::AnimationInfo* outValue , const char* funcName)
{
if (nullptr == L || nullptr == outValue)
return false;
bool ok = true;
tolua_Error tolua_err;
if (!tolua_istable(L, lo, 0, &tolua_err) )
{
#if COCOS2D_DEBUG >=1
luaval_to_native_err(L,"#ferror:",&tolua_err,funcName);
#endif
ok = false;
}
if (ok)
{
lua_pushstring(L, "name"); /* L: paramStack key */
lua_gettable(L,lo); /* L: paramStack paramStack[lo][key] */
outValue->name = lua_isstring(L, -1)? lua_tostring(L, -1) : "";
lua_pop(L,1); /* L: paramStack*/
lua_pushstring(L, "startIndex");
lua_gettable(L,lo);
outValue->startIndex = lua_isnumber(L, -1)?(int)lua_tonumber(L, -1) : 0;
lua_pop(L,1);
lua_pushstring(L, "endIndex");
lua_gettable(L, lo);
outValue->endIndex = lua_isnumber(L, -1)?(int)lua_tonumber(L, -1) : 0;
lua_pop(L, 1);
return true;
}
return false;
}
void animationInfo_to_luaval(lua_State* L,const cocostudio::timeline::AnimationInfo& inValue)
{
if (nullptr == L)
return;
lua_newtable(L);
lua_pushstring(L, "name");
lua_pushstring(L, inValue.name.c_str());
lua_rawset(L, -3);
lua_pushstring(L, "startIndex");
lua_pushnumber(L, (lua_Number)inValue.startIndex);
lua_rawset(L, -3);
lua_pushstring(L, "endIndex");
lua_pushnumber(L, (lua_Number)inValue.endIndex);
lua_rawset(L, -3);
}
| [
"gasbank@msn.com"
] | gasbank@msn.com |
80ead1a20f7c2c0100b176d566c510ea12385c0f | 10854fab019a83ad29f4e16fe45616720c95d75b | /MilesMacklin-Sandbox/core/vec2.h | 83f132fa2f273b0c5be8e75a513323d87f22b165 | [] | no_license | Woking-34/daedalus-playground | 2e928e95f371196d039e035ef035a90ad468c5e5 | 41a884194aa8b42e1aa2ecbc76e71b1390e085ba | refs/heads/master | 2021-06-16T03:35:19.755817 | 2021-05-29T10:52:44 | 2021-05-29T10:52:44 | 175,941,574 | 8 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 4,011 | h | #pragma once
#if defined(_WIN32) && !defined(__CUDACC__)
#if defined(_DEBUG)
#define VEC2_VALIDATE() { assert(_finite(x));\
assert(!_isnan(x));\
\
assert(_finite(y));\
assert(!_isnan(y));\
}
#else
#define VEC2_VALIDATE() {\
assert(isfinite(x));\
assert(isfinite(y)); }\
#endif // _WIN32
#else
#define VEC2_VALIDATE()
#endif
#ifdef _DEBUG
#define FLOAT_VALIDATE(f) { assert(_finite(f)); assert(!_isnan(f)); }
#else
#define FLOAT_VALIDATE(f)
#endif
// vec2
template <typename T>
class XVector2
{
public:
typedef T value_type;
CUDA_CALLABLE XVector2() : x(0.0f), y(0.0f) { VEC2_VALIDATE(); }
CUDA_CALLABLE XVector2(T _x) : x(_x), y(_x) { VEC2_VALIDATE(); }
CUDA_CALLABLE XVector2(T _x, T _y) : x(_x), y(_y) { VEC2_VALIDATE(); }
CUDA_CALLABLE XVector2(const T* p) : x(p[0]), y(p[1]) {}
template <typename U>
CUDA_CALLABLE explicit XVector2(const XVector2<U>& v) : x(v.x), y(v.y) {}
CUDA_CALLABLE operator T* () { return &x; }
CUDA_CALLABLE operator const T* () const { return &x; };
CUDA_CALLABLE void Set(T x_, T y_) { VEC2_VALIDATE(); x = x_; y = y_; }
CUDA_CALLABLE XVector2<T> operator * (T scale) const { XVector2<T> r(*this); r *= scale; VEC2_VALIDATE(); return r; }
CUDA_CALLABLE XVector2<T> operator / (T scale) const { XVector2<T> r(*this); r /= scale; VEC2_VALIDATE(); return r; }
CUDA_CALLABLE XVector2<T> operator + (const XVector2<T>& v) const { XVector2<T> r(*this); r += v; VEC2_VALIDATE(); return r; }
CUDA_CALLABLE XVector2<T> operator - (const XVector2<T>& v) const { XVector2<T> r(*this); r -= v; VEC2_VALIDATE(); return r; }
CUDA_CALLABLE XVector2<T>& operator *=(T scale) {x *= scale; y *= scale; VEC2_VALIDATE(); return *this;}
CUDA_CALLABLE XVector2<T>& operator /=(T scale) {T s(1.0f/scale); x *= s; y *= s; VEC2_VALIDATE(); return *this;}
CUDA_CALLABLE XVector2<T>& operator +=(const XVector2<T>& v) {x += v.x; y += v.y; VEC2_VALIDATE(); return *this;}
CUDA_CALLABLE XVector2<T>& operator -=(const XVector2<T>& v) {x -= v.x; y -= v.y; VEC2_VALIDATE(); return *this;}
CUDA_CALLABLE XVector2<T>& operator *=(const XVector2<T>& scale) {x *= scale.x; y *= scale.y; VEC2_VALIDATE(); return *this;}
// negate
CUDA_CALLABLE XVector2<T> operator -() const { VEC2_VALIDATE(); return XVector2<T>(-x, -y); }
// returns this vector
CUDA_CALLABLE void Normalize() { *this /= Length(*this); }
CUDA_CALLABLE void SafeNormalize(const XVector2<T>& v=XVector2<T>(0.0f,0.0f))
{
T length = Length(*this);
*this = (length==0.00001f)?v:(*this /= length);
}
T x;
T y;
};
typedef XVector2<float> Vec2;
typedef XVector2<float> Vector2;
// lhs scalar scale
template <typename T>
CUDA_CALLABLE XVector2<T> operator *(T lhs, const XVector2<T>& rhs)
{
XVector2<T> r(rhs);
r *= lhs;
return r;
}
template <typename T>
CUDA_CALLABLE XVector2<T> operator*(const XVector2<T>& lhs, const XVector2<T>& rhs)
{
XVector2<T> r(lhs);
r *= rhs;
return r;
}
template <typename T>
CUDA_CALLABLE bool operator==(const XVector2<T>& lhs, const XVector2<T>& rhs)
{
return (lhs.x == rhs.x && lhs.y == rhs.y);
}
template <typename T>
CUDA_CALLABLE T Dot(const XVector2<T>& v1, const XVector2<T>& v2)
{
return v1.x * v2.x + v1.y * v2.y;
}
// returns the ccw perpendicular vector
template <typename T>
CUDA_CALLABLE XVector2<T> PerpCCW(const XVector2<T>& v)
{
return XVector2<T>(-v.y, v.x);
}
template <typename T>
CUDA_CALLABLE XVector2<T> PerpCW(const XVector2<T>& v)
{
return XVector2<T>(v.y, -v.x);
}
// component wise min max functions
template <typename T>
CUDA_CALLABLE XVector2<T> Max(const XVector2<T>& a, const XVector2<T>& b)
{
return XVector2<T>(Max(a.x, b.x), Max(a.y, b.y));
}
template <typename T>
CUDA_CALLABLE XVector2<T> Min(const XVector2<T>& a, const XVector2<T>& b)
{
return XVector2<T>(Min(a.x, b.x), Min(a.y, b.y));
}
// 2d cross product, treat as if a and b are in the xy plane and return magnitude of z
template <typename T>
CUDA_CALLABLE T Cross(const XVector2<T>& a, const XVector2<T>& b)
{
return (a.x*b.y - a.y*b.x);
}
| [
"m_nyers@yahoo.com"
] | m_nyers@yahoo.com |
060f7a8ba41e89bd99fa7921b39c1143602e9e6c | c681c3fb11347eaa9ce3a4a51f8ad55bc89c80ed | /GoblinEngine with SFML/Core/MapCell.cpp | 72ae8daca3dd42dac5434d6b0673446e8a0e9e7f | [] | no_license | chibicitiberiu/goblin-engine | 933b72778691eda084042892429e1578645b211e | a66466cb9bb148473f062d49e1e8d8790d375b9d | refs/heads/master | 2016-09-06T05:36:52.160481 | 2013-09-06T21:26:21 | 2013-09-06T21:26:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 455 | cpp | #include "MapCell.h"
namespace Goblin
{
MapCell::MapCell(void)
{
}
MapCell::~MapCell(void)
{
}
int MapCell::getTerrainType() const
{
return this->terrainType;
}
float MapCell::getHeight() const
{
return this->height;
}
void MapCell::setTerrainType(int value)
{
this->terrainType = value;
}
void MapCell::setHeight(float value)
{
this->height = value;
}
Object* MapCell::clone() const
{
return new MapCell(*this);
}
} | [
"chibicitiberiu@gmail.com"
] | chibicitiberiu@gmail.com |
4ef2ffc17ddb791a484d830030875b4c423b79df | ce588945eabc48c36ce87e7601751d9addcb2cec | /yooncpp/project/step10/AccountHandler.cpp | db4a7766eeeffc014e964bd5b2ec2e025289b454 | [] | no_license | jun097kim/study-cpp | 6512f482d45fc2f958014e7f59b238b3d2920eee | 282e93aa0ee7cc09289e0c3478cba2b2b7dab263 | refs/heads/master | 2020-03-21T05:07:56.110571 | 2018-07-18T15:20:25 | 2018-07-18T15:20:25 | 138,145,698 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,344 | cpp | #include "BankingCommonDecl.h"
#include "AccountHandler.h"
#include "NormalAccount.h"
#include "HighCreditAccount.h"
void AccountHandler::ShowMenu() const
{
cout << "-----Menu-----" << endl;
cout << "1. 계좌개설" << endl;
cout << "2. 입 금" << endl;
cout << "3. 출 금" << endl;
cout << "4. 계좌정보 전체 출력" << endl;
cout << "5. 프로그램 종료" << endl;
}
void AccountHandler::MakeAccount()
{
int sel;
cout << "[계좌종류선택]" << endl;
cout << "1. 보통예금계좌 ";
cout << "2. 신용신뢰계좌 " << endl;
cout << "선택: ";
cin >> sel;
if (sel == NORMAL)
MakeNormalAccount();
else
MakeCreditAccount();
}
void AccountHandler::MakeNormalAccount()
{
int id;
String name;
int balance;
int interRate;
cout << "[보틍예금계좌 개설]" << endl;
cout << "계좌ID: "; cin >> id;
cout << "이 름: "; cin >> name;
cout << "입금액: "; cin >> balance;
cout << "이자율: "; cin >> interRate;
cout << endl;
accArr[accNum++] = new NormalAccount(id, balance, name, interRate);
}
void AccountHandler::MakeCreditAccount()
{
int id;
String name;
int balance;
int interRate;
int creditLevel;
cout << "[신용신뢰계좌 개설]" << endl;
cout << "계좌ID: "; cin >> id;
cout << "이 름: "; cin >> name;
cout << "입금액: "; cin >> balance;
cout << "이자율: "; cin >> interRate;
cout << "신용등급(1toA, 2toB, 3toC): "; cin >> creditLevel;
cout << endl;
switch (creditLevel)
{
case 1:
accArr[accNum++] = new HighCreditAccount(id, balance, name, interRate, LEVEL_A);
break;
case 2:
accArr[accNum++] = new HighCreditAccount(id, balance, name, interRate, LEVEL_B);
break;
case 3:
accArr[accNum++] = new HighCreditAccount(id, balance, name, interRate, LEVEL_C);
break;
}
}
void AccountHandler::DepositMoney()
{
int money;
int id;
cout << "[입 금]" << endl;
cout << "계좌ID: "; cin >> id;
cout << "입금액: "; cin >> money;
for (int i = 0; i < accNum; i++)
{
if (accArr[i]->GetAccID() == id)
{
accArr[i]->Deposit(money);
cout << "입금완료" << endl << endl;
return;
}
}
cout << "유효하지 않은 ID 입니다." << endl << endl;
}
void AccountHandler::WithdrawMoney()
{
int money;
int id;
cout << "[출 금]" << endl;
cout << "계좌ID: "; cin >> id;
cout << "출금액: "; cin >> money;
for (int i = 0; i < accNum; i++)
{
if (accArr[i]->GetAccID() == id)
{
if (accArr[i]->Withdraw(money) == 0)
{
cout << "잔액부족" << endl << endl;
return;
}
cout << "출금완료" << endl << endl;
return;
}
}
cout << "유효하지 않은 ID 입니다." << endl << endl;
}
void AccountHandler::ShowAllAccInfo() const
{
for (int i = 0; i < accNum; i++)
{
accArr[i]->ShowAccInfo();
}
}
AccountHandler::AccountHandler()
: accNum(0)
{ }
AccountHandler::~AccountHandler()
{
for (int i = 0; i < accNum; i++)
delete accArr[i];
} | [
"jun097kim@gmail.com"
] | jun097kim@gmail.com |
a4ebdba4b4e5b0e8e0309dd4d8caaefef35a5642 | 2eb8c826a7d6d097f503a9fbc94ee4eaae09faeb | /C로배우는 자료구조/03장/3-14_재귀호출로_factorial_값_구하기/3-14.cpp | 68a462324c76ae53635beb07b63268c9cacbb0c4 | [] | no_license | kimth007kim/C_dataStructure | a93ef4b7ce4c30509ceb4fa32d588faec81e754b | 96cdbece50ed8d3c98de42ed14b5190b325cf2d6 | refs/heads/master | 2023-03-01T14:25:50.837999 | 2021-02-06T15:19:31 | 2021-02-06T15:19:31 | 321,634,656 | 1 | 0 | null | null | null | null | UHC | C++ | false | false | 526 | cpp | #include<stdio.h>
long int fact(int);
void main() {
int n, result;
printf("\n 정수를 입력하세요!! ");
scanf_s("%d", &n);
result = fact(n);
printf("\n\n %d의 factorial 값은 %ld입니다.\n", n, result);
getchar();
}
long int fact(int n)
{
int value;
if (n <= 1) {
printf("\n fact(1)함수 호출!");
printf("\n fact(1)값 1 반환!!");
return 1;
}
else {
printf("\n fact(%d)함수 호출!", n);
value = (n * fact(n - 1));
printf("\n fact(%d)값 %ld 반환!!", n, value);
return value;
}
} | [
"kimth007kim@naver.com"
] | kimth007kim@naver.com |
15330a65ac0b9f447bc06b3a7909dfe622121e53 | 74359a77bc2ee4f4730d1bd9716fd3cea13fa54c | /src/api/udf/UDFFactory.h | 36396a5fc8508828a16fa6a63eeb4198c6e02230 | [
"Apache-2.0"
] | permissive | Anewczs/nebula | 32c0d82e982a41886d3ea0d8d3d331b7e5c5a473 | f9bcd3c6df47c459712c1c30c5183873970182ae | refs/heads/master | 2022-04-23T00:01:30.514432 | 2020-04-18T00:46:56 | 2020-04-20T22:27:54 | 257,549,610 | 1 | 0 | null | 2020-04-21T09:47:01 | 2020-04-21T09:47:00 | null | UTF-8 | C++ | false | false | 2,698 | h | /*
* Copyright 2017-present Shawn Cao
*
* 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 "Avg.h"
#include "Count.h"
#include "In.h"
#include "Like.h"
#include "Max.h"
#include "Min.h"
#include "Not.h"
#include "Pct.h"
#include "Prefix.h"
#include "Sum.h"
#include "api/dsl/Base.h"
#include "surface/eval/UDF.h"
#include "type/Type.h"
/**
* Create UDF/UDAF object based on parameters
*/
namespace nebula {
namespace api {
namespace udf {
using UDFKind = nebula::surface::eval::UDFType;
class UDFFactory {
public:
template <UDFKind UKIND, nebula::type::Kind IK, typename... Args>
static std::unique_ptr<nebula::surface::eval::ValueEval>
createUDF(std::shared_ptr<nebula::api::dsl::Expression> expr, Args&&... args) {
constexpr auto name = nebula::surface::eval::UdfTraits<UKIND, IK>::Name;
if constexpr (UKIND == UDFKind::NOT) {
return std::make_unique<Not>(name, expr->asEval());
}
if constexpr (UKIND == UDFKind::MAX) {
return std::make_unique<Max<IK>>(name, expr->asEval());
}
if constexpr (UKIND == UDFKind::MIN) {
return std::make_unique<Min<IK>>(name, expr->asEval());
}
if constexpr (UKIND == UDFKind::COUNT) {
return std::make_unique<Count<IK>>(name, expr->asEval());
}
if constexpr (UKIND == UDFKind::SUM) {
return std::make_unique<Sum<IK>>(name, expr->asEval());
}
if constexpr (UKIND == UDFKind::AVG) {
return std::make_unique<Avg<IK>>(name, expr->asEval());
}
if constexpr (UKIND == UDFKind::PCT) {
return std::make_unique<Pct<IK>>(name, expr->asEval(), std::forward<Args>(args)...);
}
if constexpr (UKIND == UDFKind::LIKE) {
return std::make_unique<Like>(name, expr->asEval(), std::forward<Args>(args)...);
}
if constexpr (UKIND == UDFKind::PREFIX) {
return std::make_unique<Prefix>(name, expr->asEval(), std::forward<Args>(args)...);
}
if constexpr (UKIND == UDFKind::IN) {
return std::make_unique<In<IK>>(name, expr, std::forward<Args>(args)...);
}
throw NException(fmt::format("Unimplemented UDF {0}", name));
}
};
} // namespace udf
} // namespace api
} // namespace nebula | [
"caoxhua@gmail.com"
] | caoxhua@gmail.com |
8ef003f4e85e511c0438ebe75fee7990ba1936b1 | 290575cb248a2d31ee83d329bf4cf0fb9cb82950 | /server/ppm-reader.cc | 38be77618c0dcac5494e40ea476d7a91a39d662b | [] | no_license | scottyallen/flaschen-taschen | cc8bda61df3e8ea43aa9a7dae1b92f16bf4342fa | 9cd03255154ceac7cd8fd93a0079ab3e3348f5a1 | refs/heads/master | 2020-04-05T23:38:18.586179 | 2016-05-06T17:43:15 | 2016-05-10T04:25:39 | 58,512,269 | 0 | 1 | null | 2016-05-11T03:43:42 | 2016-05-11T03:43:39 | null | UTF-8 | C++ | false | false | 3,539 | cc | // -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil; -*-
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation version 2.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://gnu.org/licenses/gpl-2.0.txt>
// Very simple ppm reader.
#include "ppm-reader.h"
#include <stdlib.h>
#include <ctype.h>
static const char *skipWhitespace(const char *buffer, const char *end) {
for (;;) {
while (buffer < end && isspace(*buffer))
++buffer;
if (buffer >= end)
return NULL;
if (*buffer == '#') {
while (buffer < end && *buffer != '\n') // read to end of line.
++buffer;
continue; // Back to whitespace eating.
}
return buffer;
}
}
// Read next number. Start reading at *start; modifies the *start pointer
// to point to the character just after the decimal number or NULL if reading
// was not successful.
static int readNextNumber(const char **start, const char *end) {
const char *start_number = skipWhitespace(*start, end);
if (start_number == NULL) { *start = NULL; return 0; }
char *end_number = NULL;
int result = strtol(start_number, &end_number, 10);
if (end_number == start_number) { *start = NULL; return 0; }
*start = end_number;
return result;
}
const char *ReadImageData(const char *in_buffer, size_t buf_len,
struct ImageMetaInfo *info) {
if (in_buffer[0] != 'P' || in_buffer[1] != '6' ||
(!isspace(in_buffer[2]) && in_buffer[2] != '#')) {
return in_buffer; // raw image. No P6 magic header.
}
const char *const end = in_buffer + buf_len;
const char *parse_buffer = in_buffer + 2;
const int width = readNextNumber(&parse_buffer, end);
if (parse_buffer == NULL) return in_buffer;
const int height = readNextNumber(&parse_buffer, end);
if (parse_buffer == NULL) return in_buffer;
const int range = readNextNumber(&parse_buffer, end);
if (parse_buffer == NULL) return in_buffer;
if (!isspace(*parse_buffer++)) return in_buffer; // last char before data
// Now make sure that the rest of the buffer still makes sense
const size_t expected_image_data = width * height * 3;
const size_t actual_data = end - parse_buffer;
if (actual_data < expected_image_data)
return in_buffer; // Uh, not enough data.
if (actual_data > expected_image_data) {
// Our extension: at the end of the binary data, we provide an optional
// offset. We can't store it in the header, as it is fixed in number
// of fields. But nobody cares what is at the end of the buffer.
const char *offset_data = parse_buffer + expected_image_data;
info->offset_x = readNextNumber(&offset_data, end);
if (offset_data != NULL) {
info->offset_y = readNextNumber(&offset_data, end);
}
if (offset_data != NULL) {
info->layer = readNextNumber(&offset_data, end);
}
}
info->width = width;
info->height = height;
info->range = range;
return parse_buffer;
}
| [
"h.zeller@acm.org"
] | h.zeller@acm.org |
42a02da877b41b9855a921ecaedbfb975f93f548 | 309975d60e30260f2e02d11e71eaaf6e08b93659 | /Sources/Internal/Render/RHI/Common/PreProcessor.h | 34720025c39672d79a6a8c7cd44d9372d7baa34c | [] | permissive | BlitzModder/dava.engine | e83b038a9d24b37c00b095e83ffdfd8cd497823c | 0c7a16e627fc0d12309250d6e5e207333b35361e | refs/heads/development | 2023-03-15T12:30:32.342501 | 2018-02-19T11:09:02 | 2018-02-19T11:09:02 | 122,161,150 | 4 | 3 | BSD-3-Clause | 2018-02-20T06:00:07 | 2018-02-20T06:00:07 | null | UTF-8 | C++ | false | false | 3,115 | h | #pragma once
#include "ExpressionEvaluator.h"
namespace DAVA
{
class PreProc
{
public:
struct FileCallback
{
virtual ~FileCallback() = default;
virtual bool Open(const char* /*file_name*/) = 0;
virtual void Close() = 0;
virtual uint32 Size() const = 0;
virtual uint32 Read(uint32 /*max_sz*/, void* /*dst*/) = 0;
};
using TextBuffer = std::vector<char>;
public:
PreProc(FileCallback* fc = nullptr);
~PreProc();
bool ProcessFile(const char* file_name, TextBuffer* output);
bool Process(const char* src_text, TextBuffer* output);
void Clear();
bool AddDefine(const char* name, const char* value);
private:
struct Line
{
uint32 line_n;
const char* text;
Line(const char* t, uint32 n)
: text(t)
, line_n(n)
{
}
};
using LineVector = std::vector<Line>;
void Reset();
char* AllocBuffer(uint32 sz);
bool ProcessInplaceInternal(char* src_text, TextBuffer* output);
bool ProcessBuffer(char* text, LineVector& line);
bool ProcessInclude(const char* file_name, LineVector& line);
bool ProcessDefine(const char* name, const char* val);
void Undefine(const char* name);
void GenerateOutput(TextBuffer* output, LineVector& line);
char* GetExpression(char* txt, char** end) const;
char* GetIdentifier(char* txt, char** end) const;
int32 GetNameAndValue(char* txt, char** name, char** value, char** end) const;
void ReportExprEvalError(uint32 line_n);
char* ExpandMacroInLine(char* txt);
char* GetNextToken(char* txt, ptrdiff_t txtSize, ptrdiff_t& tokenSize);
const char* GetNextToken(const char* txt, ptrdiff_t txtSize, ptrdiff_t& tokenSize);
public:
enum : uint32
{
MaxMacroValueLength = 128,
MaxLocalStringLength = 2048,
};
struct MacroStringBuffer
{
const char* value = nullptr;
uint32 length = 0;
MacroStringBuffer() = default;
MacroStringBuffer(const char* nm, uint32 sz)
: value(nm)
, length(sz)
{
}
bool operator==(const MacroStringBuffer& r) const
{
bool equals = false;
if (length == r.length)
{
equals = (strncmp(value, r.value, length) == 0);
}
return equals;
}
};
struct MacroStringBufferHash
{
uint64 operator()(const MacroStringBuffer& m) const
{
return DAVA::HashValue_N(m.value, m.length);
}
};
using MacroMap = UnorderedMap<MacroStringBuffer, MacroStringBuffer, MacroStringBufferHash>;
private:
enum : uint32
{
InvalidValue = static_cast<uint32>(-1)
};
enum : char
{
Tab = '\t',
Zero = '\0',
Space = ' ',
NewLine = '\n',
DoubleQuotes = '\"',
CarriageReturn = '\r',
};
MacroMap macro;
Vector<char*> buffer;
ExpressionEvaluator evaluator;
FileCallback* fileCB = nullptr;
const char* curFileName = "<buffer>";
};
} | [
"m_molokovskih@wargaming.net"
] | m_molokovskih@wargaming.net |
15e2221369b1c3cabde9170f5bedc3fb7c877b94 | 49b878b65e9eb00232490243ccb9aea9760a4a6d | /ash/public/cpp/holding_space/holding_space_constants.h | 1d07baf95dac95d4817a530ef8820e4eb7cf7cf6 | [
"BSD-3-Clause"
] | permissive | romanzes/chromium | 5a46f234a233b3e113891a5d643a79667eaf2ffb | 12893215d9efc3b0b4d427fc60f5369c6bf6b938 | refs/heads/master | 2022-12-28T00:20:03.524839 | 2020-10-08T21:01:52 | 2020-10-08T21:01:52 | 302,470,347 | 0 | 0 | BSD-3-Clause | 2020-10-08T22:10:22 | 2020-10-08T21:54:38 | null | UTF-8 | C++ | false | false | 2,634 | 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 ASH_PUBLIC_CPP_HOLDING_SPACE_HOLDING_SPACE_CONSTANTS_H_
#define ASH_PUBLIC_CPP_HOLDING_SPACE_HOLDING_SPACE_CONSTANTS_H_
#include "ash/public/cpp/app_menu_constants.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/geometry/size.h"
namespace ash {
// Appearance.
constexpr int kHoldingSpaceBubbleWidth = 360;
constexpr gfx::Insets kHoldingSpaceContainerPadding(16);
constexpr int kHoldingSpaceContainerChildSpacing = 16;
constexpr int kHoldingSpaceContainerSpacing = 8;
constexpr gfx::Insets kHoldingSpaceChipPadding(8);
constexpr int kHoldingSpaceChipChildSpacing = 8;
constexpr int kHoldingSpaceChipHeight = 40;
constexpr int kHoldingSpaceChipIconSize = 24;
constexpr int kHoldingSpaceChipWidth = 160;
constexpr int kHoldingSpaceChipsPerRow = 2;
constexpr int kHoldingSpaceColumnSpacing = 8;
constexpr int kHoldingSpaceColumnWidth = 160;
constexpr int kHoldingSpaceContextMenuMargin = 8;
constexpr int kHoldingSpaceCornerRadius = 8;
constexpr int kHoldingSpaceDownloadsChevronIconSize = 20;
constexpr int kHoldingSpaceDownloadsHeaderSpacing = 16;
constexpr int kHoldingSpacePinIconSize = 20;
constexpr int kHoldingSpaceRowSpacing = 8;
constexpr gfx::Insets kHoldingSpaceScreenshotPadding(8);
constexpr gfx::Size kHoldingSpaceScreenshotPinButtonSize(24, 24);
constexpr int kHoldingSpaceScreenshotSpacing = 8;
constexpr gfx::Size kHoldingSpaceScreenshotSize(104, 80);
constexpr gfx::Insets kHoldingSpaceScreenshotsContainerPadding(8, 0);
constexpr float kHoldingSpaceSelectedOverlayOpacity = 0.24f;
constexpr int kHoldingSpaceTrayMainAxisMargin = 6;
// Context menu commands.
enum HoldingSpaceCommandId {
kPinItem,
kCopyImageToClipboard,
kShowInFolder,
kUnpinItem,
kMaxValue = kUnpinItem
};
// View IDs.
constexpr int kHoldingSpacePinnedFilesContainerId = 1;
constexpr int kHoldingSpaceRecentFilesContainerId = 2;
// The maximum allowed age for files restored into the holding space model.
// Note that this is not enforced for pinned items.
constexpr base::TimeDelta kMaxFileAge = base::TimeDelta::FromDays(1);
// The maximum allowed number of downloads to display in holding space UI.
constexpr size_t kMaxDownloads = 2u;
// The maximum allowed number of screenshots to display in holding space UI.
constexpr size_t kMaxScreenshots = 3u;
// Mime type with wildcard which matches all image types.
constexpr char kMimeTypeImage[] = "image/*";
} // namespace ash
#endif // ASH_PUBLIC_CPP_HOLDING_SPACE_HOLDING_SPACE_CONSTANTS_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
ed55f5d416a845e1c57846fbc85989bca8e1612d | 709b54207de45074aede80d7f4cf8373f15a208a | /CPP/Special Palindrome Again/SpecialPalindromeAgain.cpp | 259e80eb0865cd9499fa8ee3d9cea3ff2a8a7645 | [] | no_license | codemasa/Hackerrank | 40f5b86d9f3680fc3fe62434e4d82bffa7f31961 | a82ed18680e18656609dd7658875fd8f25764156 | refs/heads/master | 2020-03-30T21:37:48.245959 | 2019-05-23T16:05:05 | 2019-05-23T16:05:05 | 151,635,401 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 415 | cpp | #include <bits/stdc++.h>
using namespace std;
// Complete the substrCount function below.
long substrCount(int n, string s) {
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
int n;
cin >> n;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
string s;
getline(cin, s);
long result = substrCount(n, s);
fout << result << "\n";
fout.close();
return 0;
}
| [
"cody.masao@gmail.com"
] | cody.masao@gmail.com |
cf86dd40e683355353298b44f6db48632b066139 | 3f6b0498b97a3f71f444a58b5a7e06f09f4571e0 | /Source/InfiniEx/Public/Characters/Heros/InfiniKnight.h | c9622fabb0105b310d52cbfdd9dece4353213609 | [] | no_license | aalhamoudi/InfiniWar | 517aad84f0ed1c3fba5fec204df4007f6165a9d8 | 2f6cfcf9ce4a8062e4f8ba4df61bb15f71e1ec0d | refs/heads/master | 2020-04-20T12:33:54.830018 | 2017-01-29T04:06:42 | 2017-01-29T04:06:42 | 168,846,326 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 631 | h | // Copyright Abdulrahman Alhamoudi, 2016 - All rights reserved.
#pragma once
#include "InfiniHero.h"
#include "InfiniKnight.generated.h"
/**
*
*/
UCLASS()
class INFINIEX_API AInfiniKnight : public AInfiniHero
{
GENERATED_BODY()
public:
// Character Vitals //
/** Max Stamina */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Vitals)
float MaxStamina;
/** Stamina Regen */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Vitals)
float StaminaRegen;
/** Actual Stamina */
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = Vitals)
float Stamina;
};
| [
"aalha028@uottawa.ca"
] | aalha028@uottawa.ca |
0aec9bf3a97a6d36914b6c4a41342c2b392510a4 | e44283331c214e69f049d3d23b6350dbf2abbf32 | /All ACM Codes/contest/light oj 02.09.2016/F.cpp | bdbf7737f690345559b7df376fd2b25178edfe7c | [] | no_license | Abiduddin/Competitive-Programming-Codes | cd2a8730998859d751e1891b4bc9bd3a790b8416 | 59b51b08c6f34c1bed941c8b86490ee9a250e5a9 | refs/heads/master | 2020-09-09T22:54:09.708942 | 2019-11-14T02:31:06 | 2019-11-14T02:31:06 | 221,588,892 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 308 | cpp | #include <stdio.h>
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int i,j,l=0,k,m,n,p;
scanf("%d",&i);
while(i--)
{
scanf("%d.%d.%d.%d",&k,&m,&n,&p);
printf("Case %d: ",++l);
cout<<oct<<k<<"."<<oct<<m<<"."<<oct<<n<<"."<<oct<<p<<endl;
}
}
| [
"abidakash456@gmail.com"
] | abidakash456@gmail.com |
3e10ed5e09663fbf07c1c714ff2e2fafa207925d | 49fc9092d53d1c06843986e57cf3b7e63007acdf | /include/shipeditordlg.h | 8752155ef01b62b8e2d9722b4ce825ec264cf455 | [] | no_license | ptitSeb/freespace2 | 8615e5c55b9a19bdf280bc0e0b164f9e33640045 | 500ee249f7033aac9b389436b1737a404277259c | refs/heads/master | 2020-09-20T19:13:59.618314 | 2019-01-02T10:51:59 | 2019-01-02T10:51:59 | 67,286,355 | 9 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 7,869 | h | /*
* Copyright (C) Volition, Inc. 1999. All rights reserved.
*
* All source code herein is the property of Volition, Inc. You may not sell
* or otherwise commercially exploit the source or things you created based on
* the source.
*/
/*
* $Logfile: /Freespace2/code/Fred2/ShipEditorDlg.h $
* $Revision: 110 $
* $Date: 2002-06-09 06:41:30 +0200 (Sun, 09 Jun 2002) $
* $Author: relnev $
*
* Single ship editing dialog
*
* $Log$
* Revision 1.2 2002/06/09 04:41:15 relnev
* added copyright header
*
* Revision 1.1.1.1 2002/05/03 03:28:12 root
* Initial import.
*
*
* 4 5/20/99 7:00p Dave
* Added alternate type names for ships. Changed swarm missile table
* entries.
*
* 3 2/11/99 2:15p Andsager
* Add ship explosion modification to FRED
*
* 2 10/07/98 6:28p Dave
* Initial checkin. Renamed all relevant stuff to be Fred2 instead of
* Fred. Globalized mission and campaign file extensions. Removed Silent
* Threat specific code.
*
* 1 10/07/98 3:01p Dave
*
* 1 10/07/98 3:00p Dave
*
* 65 4/07/98 9:42a Allender
* put in persona combo box into ship editor. Removed code to assign
* personas based on message
*
* 64 3/27/98 12:02p Sandeep
*
* 63 3/25/98 4:14p Hoffoss
* Split ship editor up into ship editor and a misc dialog, which tracks
* flags and such.
*
* 62 3/16/98 8:27p Allender
* Fred support for two new AI flags -- kamikaze and no dynamic goals.
*
* 61 3/09/98 4:30p Allender
* multiplayer secondary weapon changes. red-alert and cargo-known-delay
* sexpressions. Add time cargo revealed to ship structure
*
* 60 2/17/98 11:42a Hoffoss
* Added support for hidden from sensors condition.
*
* 59 2/06/98 2:54p Hoffoss
* Fixed some bugs in dialog init, and cleared up some of the confusion
* about how it works by renaming some variables and adding comments.
*
* 58 1/29/98 5:14p Hoffoss
* Added support for a SF_INVULNERABLE ship flag in Fred.
*
* 57 11/13/97 4:14p Allender
* automatic assignment of hotkeys for starting wings. Appripriate
* warnings when they are incorrectly used. hotkeys correctly assigned to
* ships/wing arriving after mission start
*
* 56 11/10/97 10:13p Allender
* added departure anchor to Fred and Freespace in preparation for using
* docking bays. Functional in Fred, not in FreeSpace.
*
* 55 10/21/97 4:49p Allender
* added flags to Fred and FreeSpace to forgo warp effect (toggle in ship
* editor in Fred)
*
* 54 10/14/97 5:33p Hoffoss
* Added Fred support (and fsm support) for the no_arrival_music flags in
* ships and wings.
*
* 53 9/17/97 5:43p Hoffoss
* Added Fred support for new player start information.
*
* 52 9/04/97 4:31p Hoffoss
* Fixed bug: Changed ship editor to not touch wing info (arrival or
* departure cues) to avoid conflicts with wing editor's changes.
*
* 51 8/30/97 9:52p Hoffoss
* Implemented arrival location, distance, and anchor in Fred.
*
* 50 8/25/97 5:56p Hoffoss
* Added multiple asteroid field support, loading and saving of asteroid
* fields, and ship score field to Fred.
*
* 49 8/20/97 6:53p Hoffoss
* Implemented escort flag support in Fred.
*
* 48 8/16/97 12:06p Hoffoss
* Fixed bug where a whole wing is deleted that is being referenced.
*
* 47 8/12/97 7:17p Hoffoss
* Added previous button to ship and wing editors.
*
* 46 8/12/97 6:32p Hoffoss
* Added code to allow hiding of arrival and departure cues in editors.
*
* 45 8/08/97 1:31p Hoffoss
* Added syncronization protection to cur_object_index changes.
*
* $NoKeywords: $
*/
#ifndef _SHIPEDITORDLG_H
#define _SHIPEDITORDLG_H
#include "sexp_tree.h"
#include "shipgoalsdlg.h"
#include "management.h"
/////////////////////////////////////////////////////////////////////////////
// CShipEditorDlg dialog
#define WM_GOODBYE (WM_USER+5)
#define ID_ALWAYS_ON_TOP 0x0f00
class numeric_edit_control
{
int value;
int unique;
int control_id;
CWnd *dlg;
public:
void setup(int id, CWnd *wnd);
void blank() { unique = 0; }
void init(int n);
void set(int n);
void display();
void save(int *n);
void fix(int n);
};
class CShipEditorDlg : public CDialog
{
private:
int make_ship_list(int *arr);
int update_ship(int ship);
int initialized;
int multi_edit;
int always_on_top;
int cue_height;
int mission_type; // indicates if single player(1) or multiplayer(0)
CView* m_pSEView;
CCriticalSection CS_update;
// Construction
public:
int player_ship, single_ship;
int editing;
int modified;
int select_sexp_node;
int bypass_errors;
int bypass_all;
int enable; // used to enable(1)/disable(0) controls based on if any ship selected
int p_enable; // used to enable(1)/disable(0) controls based on if a player ship
int tristate_set(int val, int cur_state);
void show_hide_sexp_help();
void calc_cue_height();
int verify();
void OnInitMenu(CMenu *m);
void OnOK();
int update_data(int redraw = 1);
void initialize_data(int full);
CShipEditorDlg(CWnd* pParent = NULL); // standard constructor
CShipEditorDlg(CView* pView);
// alternate ship name stuff
void ship_alt_name_init(int base_ship);
void ship_alt_name_close(int base_ship);
BOOL Create();
// Dialog Data
//{{AFX_DATA(CShipEditorDlg)
enum { IDD = IDD_SHIP_EDITOR };
CButton m_no_departure_warp;
CButton m_no_arrival_warp;
CButton m_player_ship;
CSpinButtonCtrl m_destroy_spin;
CSpinButtonCtrl m_departure_delay_spin;
CSpinButtonCtrl m_arrival_delay_spin;
sexp_tree m_departure_tree;
sexp_tree m_arrival_tree;
CString m_ship_name;
CString m_cargo1;
int m_ship_class;
int m_team;
int m_arrival_location;
int m_departure_location;
int m_ai_class;
numeric_edit_control m_arrival_delay;
numeric_edit_control m_departure_delay;
int m_hotkey;
BOOL m_update_arrival;
BOOL m_update_departure;
numeric_edit_control m_destroy_value;
numeric_edit_control m_score;
numeric_edit_control m_arrival_dist;
numeric_edit_control m_kdamage;
int m_arrival_target;
int m_departure_target;
int m_persona;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CShipEditorDlg)
public:
virtual BOOL Create(LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CCreateContext* pContext = NULL);
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
virtual BOOL OnCommand(WPARAM wParam, LPARAM lParam);
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CShipEditorDlg)
afx_msg void OnClose();
afx_msg void OnRclickArrivalTree(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnRclickDepartureTree(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnBeginlabeleditArrivalTree(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnBeginlabeleditDepartureTree(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnEndlabeleditArrivalTree(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnEndlabeleditDepartureTree(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnGoals();
afx_msg void OnSelchangeShipClass();
afx_msg void OnInitialStatus();
afx_msg void OnWeapons();
afx_msg void OnShipReset();
afx_msg void OnDeleteShip();
afx_msg void OnShipTbl();
afx_msg void OnNext();
afx_msg void OnSelchangedArrivalTree(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnSelchangedDepartureTree(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnHideCues();
afx_msg void OnPrev();
afx_msg void OnSelchangeArrivalLocation();
afx_msg void OnPlayerShip();
afx_msg void OnNoArrivalWarp();
afx_msg void OnNoDepartureWarp();
afx_msg void OnSelchangeDepartureLocation();
afx_msg void OnSelchangeHotkey();
afx_msg void OnFlags();
afx_msg void OnIgnoreOrders();
afx_msg void OnSpecialExp();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
#endif
| [
"sebastien.chev@gmail.com"
] | sebastien.chev@gmail.com |
56fb32cda41c77a4991911c4e64499921e591188 | 3cf9e141cc8fee9d490224741297d3eca3f5feff | /C++ Benchmark Programs/Benchmark Files 1/classtester/autogen-sources/source-4701.cpp | 54ef0911cbf36626b42b137984caf04c3aa75cf9 | [] | no_license | TeamVault/tauCFI | e0ac60b8106fc1bb9874adc515fc01672b775123 | e677d8cc7acd0b1dd0ac0212ff8362fcd4178c10 | refs/heads/master | 2023-05-30T20:57:13.450360 | 2021-06-14T09:10:24 | 2021-06-14T09:10:24 | 154,563,655 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,765 | cpp | struct c0;
void __attribute__ ((noinline)) tester0(c0* p);
struct c0
{
bool active0;
c0() : active0(true) {}
virtual ~c0()
{
tester0(this);
active0 = false;
}
virtual void f0(){}
};
void __attribute__ ((noinline)) tester0(c0* p)
{
p->f0();
}
struct c1;
void __attribute__ ((noinline)) tester1(c1* p);
struct c1
{
bool active1;
c1() : active1(true) {}
virtual ~c1()
{
tester1(this);
active1 = false;
}
virtual void f1(){}
};
void __attribute__ ((noinline)) tester1(c1* p)
{
p->f1();
}
struct c2;
void __attribute__ ((noinline)) tester2(c2* p);
struct c2 : c0
{
bool active2;
c2() : active2(true) {}
virtual ~c2()
{
tester2(this);
c0 *p0_0 = (c0*)(c2*)(this);
tester0(p0_0);
active2 = false;
}
virtual void f2(){}
};
void __attribute__ ((noinline)) tester2(c2* p)
{
p->f2();
if (p->active0)
p->f0();
}
struct c3;
void __attribute__ ((noinline)) tester3(c3* p);
struct c3 : virtual c1, c0
{
bool active3;
c3() : active3(true) {}
virtual ~c3()
{
tester3(this);
c0 *p0_0 = (c0*)(c3*)(this);
tester0(p0_0);
c1 *p1_0 = (c1*)(c3*)(this);
tester1(p1_0);
active3 = false;
}
virtual void f3(){}
};
void __attribute__ ((noinline)) tester3(c3* p)
{
p->f3();
if (p->active0)
p->f0();
if (p->active1)
p->f1();
}
struct c4;
void __attribute__ ((noinline)) tester4(c4* p);
struct c4 : virtual c1, virtual c2, c3
{
bool active4;
c4() : active4(true) {}
virtual ~c4()
{
tester4(this);
c0 *p0_0 = (c0*)(c2*)(c4*)(this);
tester0(p0_0);
c0 *p0_1 = (c0*)(c3*)(c4*)(this);
tester0(p0_1);
c1 *p1_0 = (c1*)(c4*)(this);
tester1(p1_0);
c1 *p1_1 = (c1*)(c3*)(c4*)(this);
tester1(p1_1);
c2 *p2_0 = (c2*)(c4*)(this);
tester2(p2_0);
c3 *p3_0 = (c3*)(c4*)(this);
tester3(p3_0);
active4 = false;
}
virtual void f4(){}
};
void __attribute__ ((noinline)) tester4(c4* p)
{
p->f4();
if (p->active3)
p->f3();
if (p->active1)
p->f1();
if (p->active2)
p->f2();
}
int __attribute__ ((noinline)) inc(int v) {return ++v;}
int main()
{
c0* ptrs0[25];
ptrs0[0] = (c0*)(new c0());
ptrs0[1] = (c0*)(c2*)(new c2());
ptrs0[2] = (c0*)(c3*)(new c3());
ptrs0[3] = (c0*)(c2*)(c4*)(new c4());
ptrs0[4] = (c0*)(c3*)(c4*)(new c4());
for (int i=0;i<5;i=inc(i))
{
tester0(ptrs0[i]);
delete ptrs0[i];
}
c1* ptrs1[25];
ptrs1[0] = (c1*)(new c1());
ptrs1[1] = (c1*)(c3*)(new c3());
ptrs1[2] = (c1*)(c4*)(new c4());
ptrs1[3] = (c1*)(c3*)(c4*)(new c4());
for (int i=0;i<4;i=inc(i))
{
tester1(ptrs1[i]);
delete ptrs1[i];
}
c2* ptrs2[25];
ptrs2[0] = (c2*)(new c2());
ptrs2[1] = (c2*)(c4*)(new c4());
for (int i=0;i<2;i=inc(i))
{
tester2(ptrs2[i]);
delete ptrs2[i];
}
c3* ptrs3[25];
ptrs3[0] = (c3*)(new c3());
ptrs3[1] = (c3*)(c4*)(new c4());
for (int i=0;i<2;i=inc(i))
{
tester3(ptrs3[i]);
delete ptrs3[i];
}
c4* ptrs4[25];
ptrs4[0] = (c4*)(new c4());
for (int i=0;i<1;i=inc(i))
{
tester4(ptrs4[i]);
delete ptrs4[i];
}
return 0;
}
| [
"ga72foq@mytum.de"
] | ga72foq@mytum.de |
8d5585974d3998a3b38d87026aa3daa0ca7bc8cc | 820f4cd8567a92f3d4d98c234871fa3256ce9d5a | /src/Sim/BarnesHut.hpp | f3da3bbef8fa90f7d25e40f2ec4e30dffccb71fa | [] | no_license | matty9090/Procedural-Universe | 6635805cb8bb4ce4ae31ed459c8f49486fb8b324 | 3242f594bfe1553b4359fb97db6b0b1975e7503b | refs/heads/master | 2022-08-06T16:25:18.399832 | 2020-05-23T22:21:18 | 2020-05-23T22:21:18 | 208,433,218 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 940 | hpp | #pragma once
#include <GeometricPrimitive.h>
#include "Octree.hpp"
#include "INBodySim.hpp"
#include "Render/Model/Cube.hpp"
#include "Core/ThreadPool.hpp"
class BarnesHut : public INBodySim
{
public:
BarnesHut(ID3D11DeviceContext* context);
~BarnesHut();
void Init(std::vector<Particle>& particles) final;
void Update(float dt) final;
void RenderDebug(DirectX::SimpleMath::Matrix view, DirectX::SimpleMath::Matrix proj);
private:
BoundingCube Bounds;
std::unique_ptr<Octree> Tree;
std::vector<Particle>* Particles;
ID3D11DeviceContext* Context;
struct ParticleInfo
{
size_t Index;
size_t Loops;
};
CThreadPool<ParticleInfo> Pool;
std::unique_ptr<Cube> DebugCube;
std::unique_ptr<DirectX::GeometricPrimitive> DebugSphere;
void Exec(const ParticleInfo& info);
}; | [
"lowe.matthew@mail.com"
] | lowe.matthew@mail.com |
d5910ae213634215bb41c35ea9d97bef4d90e9de | 7b0c32697ea55325608dfaca954538292acd7e8f | /src/main.cpp | eb21d0a742794e0a50b79ade0497bcac9dead1a0 | [] | no_license | TobyPDE/cntk-api-experiment | 197819f619c7a962370c76bd068ef3bbe80e7774 | 70750da43bf0cea9304a2f4a4dceefad0d20f7d9 | refs/heads/master | 2021-06-10T08:51:17.600560 | 2016-12-22T21:01:43 | 2016-12-22T21:01:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 445 | cpp | //
// Created by toby on 01.12.16.
//
#include "chianti/layers.h"
#include <string>
#include <iostream>
int main(int argc, const char** argv)
{
auto device = CNTK::DeviceDescriptor::GPUDevice(0);
auto X = CNTK::InputVariable({ 2, 2, 3 }, CNTK::DataType::Float);
CNTK::FunctionPtr network;
network = Chianti::Layers::Conv2DLayer(X, device)
.filterSize({3, 3})
.pad("same")
.numFilters(64);
} | [
"tobias.pohlen@gmail.com"
] | tobias.pohlen@gmail.com |
6e5cc19f0eee9dd659fcc0edce453b52584b289a | 0b1dfd176953fdb3675eb0085dae5d0dd8873574 | /Algorithms/Sorting/SelectionSort/SelectionSortLinkedList.cpp | a741048f0805403d7e0713cb68a88662f63a1071 | [] | no_license | ManasMahapatra/DS-Algo-Implementations | 54fee36a5bb90f42b4947c7fb0b7c53f719e734f | 639941a020134cfd483136e9774f2dc6184d1e1c | refs/heads/master | 2020-07-28T06:05:43.202647 | 2019-10-10T04:29:29 | 2019-10-10T04:29:29 | 209,331,511 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,769 | cpp | #include <stdio.h>
#include <iostream>
#include "../../../DataStructures/LinearDataStructures/LinkedList/LinkedList.cpp"
class SortedLinkedList : public LinkedList {
public:
void selectionSort() {
//Variable to store current minimum value
int newMinimumValue;
//Pointer to point at the new minimum index
node* newMinimumNode = NULL;
//Variable to store current minimum Node
node* currentMinimumNode;
//Inner and outer traverse Node
node* innerTraverseNode;
//Start the outer loop from head
node* traverseNode = head;
while (traverseNode != NULL) {
//set the current node as minimum
currentMinimumNode = traverseNode;
//Store the minimuym considered data
newMinimumValue = currentMinimumNode->data;
//Start the inner lop from the next node onwards
innerTraverseNode = traverseNode->next;
while(innerTraverseNode != NULL) {
//change the new minimum only when the traversing node's data will be less than the current minimum data
if (innerTraverseNode->data < newMinimumValue) {
newMinimumValue = innerTraverseNode->data;
newMinimumNode = innerTraverseNode;
}
innerTraverseNode = innerTraverseNode->next;
}
//Swap only if theres a node and then reset the minimum node to NULL
if (newMinimumNode != NULL) {
newMinimumNode->data = currentMinimumNode->data;
currentMinimumNode->data = newMinimumValue;
newMinimumNode = NULL;
}
traverseNode = traverseNode->next;
}
}
};
| [
"chirag301212@gmail.com"
] | chirag301212@gmail.com |
3f62efe84a200de69cc7eb01af27631456f490bb | 553a22eb54b2bc5df030d0c72d4a74ac4003aa4e | /unitrotate.cpp | ea63c22944956dbb691ae425615e09b2e3056fff | [] | no_license | jchristi/taddraw | d2cffaae01c660351e0f56235671e9d2fad6e0a1 | b52868b1f5ffede884c9c0ea46fb11b105d24f2b | refs/heads/master | 2016-09-06T14:36:20.774557 | 2015-05-30T16:11:35 | 2015-05-30T16:11:35 | 35,358,173 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,652 | cpp | #include "oddraw.h"
#include "iddrawsurface.h"
#include "unitrotate.h"
char *NewMem;
CUnitRotate::CUnitRotate()
{
LocalShare->UnitRotate = this;
IDDrawSurface::OutptTxt ( "New CUnitRotate");
}
CUnitRotate::~CUnitRotate()
{
}
bool CUnitRotate::Message(HWND WinProchWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
switch(Msg)
{
case WM_KEYDOWN:
if(wParam == 81 && (GetAsyncKeyState(17)&0x8000)>0) // ctrl + q
{
Rotate();
//SetMem();
return true;
}
break;
}
return false;
}
void CUnitRotate::SetMem()
{
NewMem = new char[500000];
int Add = (int)&NewMem;
WriteProcessMemory(GetCurrentProcess(), (void*)0x42E46A, &Add, 4, NULL);
memset(NewMem, 500000, 0);
}
void CUnitRotate::Rotate()
{
//FixAck();
int UnitOffset = 0x118;
int *PTR1 = (int*)0x511de8;
int *UnitPTR = (int*)((*PTR1)+0x1b8e+0x3c);
int NumUnits = *((int*)(*PTR1+0x1ca7))& 0x0000ffff;
int i=0;
int OwnUnitBegin = 0;
while(OwnUnitBegin<NumUnits)
{
//short *OwnUnitBegin = (short*)(*UnitPTR + 2 + i*UnitOffset);
char *UnitDead = (char*)(*UnitPTR + 247 + i*UnitOffset);
char *Builder = (char*)(*UnitPTR + 31 + i*UnitOffset);
short *XPos = (short*)(*UnitPTR + 0x6c + i*UnitOffset);
short *YPos = (short*)(*UnitPTR + 0x74 + i*UnitOffset);
int *IsUnit = (int*)(*UnitPTR + 0 + i*UnitOffset);
char *UnitSelected = (char*)(*UnitPTR + 272 + i*UnitOffset);
//char *Working = (char*)(*UnitPTR + 186 + i*UnitOffset);
//int *Moving = (int*)(*UnitPTR + 208 + i*UnitOffset);
int *UnitOrderPTR = (int*)(*UnitPTR + 92 + i*UnitOffset);
int *DefiPTR = (int*)(*UnitPTR + 146 + i*UnitOffset);
int *DefPTR = (int*)*DefiPTR;
if(*UnitDead!=0 && *UnitDead!=1)
{
if(strcmp((char*)DefPTR, "Vehicle Plant") == 0)
{
char *NewUnitDef = new char[0x249];
memcpy(NewUnitDef, (char*)*DefiPTR, 0x249);
*DefiPTR = (int)NewUnitDef;
char *NewYardMap = new char[48];
int *YardMap = (int*)(NewUnitDef + 334);
memcpy(NewYardMap, (char*)*YardMap, 48);
NewYardMap[2] = 0x2d;
NewYardMap[3] = 0x2d;
NewYardMap[4] = 0x2d;
NewYardMap[5] = 0x2d;
//for(int x=0; x<480; x++)
// NewYardMap[x] = 0x2D;
int *tmpPTR = (int*)YardMap;
*tmpPTR = (int)NewYardMap;
IDDrawSurface::OutptTxt(NewUnitDef);
}
OwnUnitBegin++;
}
i++;
if(i == 5000)
{
//LastNum = 0;
return;
}
}
}
| [
"xpoy@d74ebf05-6d01-4e7b-8b90-17afc8ece2ee"
] | xpoy@d74ebf05-6d01-4e7b-8b90-17afc8ece2ee |
13e213b98d4623b49ffde49642bb47f425a66370 | 76874343d99e3292df374deeca5e1cb7dd064f81 | /algorithms/ShellSort.cpp | 5e44992c51713bd9363cd886a1d0c59ef44cd499 | [] | no_license | wfwei/coding | 2e8afa40ed8fdec9b63d426d42695bf6292e31b8 | 1d31c640b2882217fbf8235889b07cc27235a54e | refs/heads/master | 2021-01-10T19:54:53.933525 | 2013-09-23T07:31:53 | 2013-09-23T07:31:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 527 | cpp | #include<stdio.h>
#define SIZE 12
void prt(int A[], int size){
int i;
for(i=0; i<size; i++)
printf("%d ", A[i]);
printf("\n");
}
void ShellSort(int *A, int s, int e){
int i, j, tmp, inc;
for(inc=(e-s)/2; inc>0; inc/=2){
for(i=inc+s; i<=e; i++){
tmp = A[i];
j = i;
while(j-inc>=s && tmp<A[j-inc]){
A[j] = A[j-inc];
j-=inc;
}
A[j] = tmp;
}
}
}
int main(int argc, char* argv[])
{
int A[SIZE] = {1, 10, 14, 16, 4, 7, 9, 3, 2, 8, 5, 11};
ShellSort(A, 0, SIZE-1);
prt(A, SIZE);
return 0;
}
| [
"cf.wfwei@gmail.com"
] | cf.wfwei@gmail.com |
1f1bdcd8951e6e586dac1d2f5eb6dc0e393ca1df | 0280d3e052ac227d778f6a1dbee1b0bdd1678407 | /CodeFights Challenges/growingPlant.cpp | 09d974566342efbce1438298f6e418e84ecf73cb | [] | no_license | oknashar/Problem-Solving | 5d9da159ab5190fcdcff9fc229a25c0f4090801c | 07656a0ace44d1933f1212ecc4dc99d7813de2bf | refs/heads/master | 2022-08-15T12:34:18.820659 | 2020-05-24T23:28:41 | 2020-05-24T23:28:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 303 | cpp | //link: https://codefights.com/arcade/intro/level-9/xHvruDnQCx7mYom3T/
int growingPlant(int upSpeed, int downSpeed, int desiredHeight) {
int curr = 0, i=0;
while(true){
i++;
curr += upSpeed;
if(curr >= desiredHeight)
return i;
curr -= downSpeed;
}
}
| [
"noreply@github.com"
] | oknashar.noreply@github.com |
bf4dc8196b11390cf6d1858ebb65458dd8deabb8 | 91b241f1340b2062f5f7fa257b6f59f58ba24fbe | /Lab04OOP/VolumetricShape/CBody.h | 196b06cbbac0d0c6262e0d8c6cbe1a4b29cfc6a3 | [] | no_license | fjodor-rybakov/OOP | fed50967936da4d59075cbaf7939c7b36cf54e47 | 38971571177d0be9a1d7f33de8ecdb0720ac62bc | refs/heads/master | 2020-03-11T11:10:45.203118 | 2018-05-22T17:38:24 | 2018-05-22T17:38:24 | 129,962,735 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 389 | h | #pragma once
#include "string"
#include "vector"
class CBody
{
public:
CBody(const std::string &type);
CBody(const std::string &type, double density);
virtual double GetDensity() const;
virtual double GetVolume() const;
double GetMass() const;
std::string ToString() const;
std::string GetType() const;
private:
double m_density, m_volume = 0, m_mass = 0;
std::string m_type;
}; | [
"fedryb@mail.ru"
] | fedryb@mail.ru |
ec4348a8ee15a7bcdc8a37ae04286738da6b416b | a9f6a3dfc2fb54547c5451d5c1380842aff45311 | /EM_8x8/ArduinoTestCode/Arduino_EM_8x8_scanner8/Arduino_EM_8x8_scanner8.ino | d5935c2a35088c312cf62a5ca7e05c01577003ca | [
"MIT"
] | permissive | CmdrZin/chips_avr_examples | e7b5403db501456f26f88909bc27d40ae20ba831 | d4b57a8efd6aff2a678adef4fd405e6359e891e6 | refs/heads/master | 2021-08-06T03:38:08.789930 | 2021-01-13T04:42:03 | 2021-01-13T04:42:03 | 26,470,544 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,941 | ino | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 Nels D. "Chip" Pearson (aka CmdrZin)
*
* 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.
*/
/*
* Arduino Emote Mod 8x8 Load Icon Test - Scanner8
* This code changes a vertical line of dots to scan back and forth.
*/
#include <Wire.h>
#define SERIAL_USB 1
/* *** LOCAL PROTOTYPES *** */
uint8_t makeHeader( uint8_t len );
#define SLAVE_ADRS 0x60 // MUST match AVR chip I2C address
/* NOTE: ALL commands are a minimum of three bytes. LEN MOD CMD .. .. */
#define MOD_EM_SERVICE_ID 0x20
#define MES_SET_ICON 0x01
#define MES_SET_ICON_LEN 4
#define MES_LOAD_ICON 0x02
#define MES_LOAD_ICON_LEN 11
int slave = SLAVE_ADRS; // has to be an int.
byte count = 0; // simple counter
int cmdLen;
bool state = true; // toggle state to change direction of scan
uint8_t outBuff[16];
uint8_t icon[8] = {
0b00000000,
0b00000000,
0b00000000,
0b00000000,
0b00000000,
0b00000000,
0b00000000,
0b00000000
};
void setup()
{
Wire.begin(); // join i2c bus
#if(SERIAL_USB == 1)
Serial.begin(57600); // Set BAUD rate
#endif
}
void loop()
{
uint8_t row;
#if(SERIAL_USB == 1)
Serial.print("Count ");
Serial.println(count++, DEC);
#else
++count;
#endif
// Update icon
if( state )
{
for( row=0; row<8; ++row )
icon[row] <<= 1;
if( icon[3] == 0 )
{
for( row=0; row<8; ++row )
icon[row] = 0x80;
state = !state;
}
}
else
{
for( row=0; row<8; ++row )
icon[row] >>= 1;
if( icon[3] == 0 )
{
for( row=0; row<8; ++row )
icon[row] = 0x01;
state = !state;
}
}
// Send CMD to Slave.
outBuff[0] = makeHeader( MES_LOAD_ICON_LEN-3 );
outBuff[1] = MOD_EM_SERVICE_ID;
outBuff[2] = MES_LOAD_ICON;
for( row = 0; row<8; ++row ) {
outBuff[row+3] = icon[row];
}
cmdLen = MES_LOAD_ICON_LEN;
#if(SERIAL_USB == 1)
Serial.print(outBuff[0], HEX);
Serial.print(" ");
Serial.print(outBuff[1], HEX);
Serial.print(" ");
Serial.print(outBuff[2], HEX);
Serial.print(" ");
Serial.print(outBuff[3], HEX);
Serial.print(" ");
Serial.print(outBuff[4], HEX);
Serial.print(" ");
Serial.print(outBuff[5], HEX);
Serial.print(" ");
Serial.print(outBuff[6], HEX);
Serial.print(" ");
Serial.print(outBuff[7], HEX);
Serial.print(" ");
Serial.print(outBuff[8], HEX);
Serial.print(" ");
Serial.print(outBuff[9], HEX);
Serial.print(" ");
Serial.println(outBuff[10], HEX);
#endif
Wire.beginTransmission(slave); // transmit to Slave. Have to do this each time.
Wire.write(outBuff, cmdLen); // sends device ID and data
Wire.endTransmission(); // complete transmit
delay(200);
}
uint8_t makeHeader( uint8_t len )
{
uint8_t temp;
temp = ((~len) << 4) & 0xF0; // shift and mask
temp = temp | (len & 0x0F);
return (temp);
}
| [
"chip@gameactive.org"
] | chip@gameactive.org |
7f22c3a63446e839a2a6ee577e5edb7e79aa4c4c | 75e49b7e53cf60c99b7ab338127028a457e2721b | /sources/plug_osg/src/luna/bind_osgUtil_RenderBin_SortCallback.cpp | ac50a7b77870f7b98a2e81e4415308fa67b0b485 | [] | no_license | roche-emmanuel/singularity | 32f47813c90b9cd5655f3bead9997215cbf02d6a | e9165d68fc09d2767e8acb1e9e0493a014b87399 | refs/heads/master | 2021-01-12T01:21:39.961949 | 2012-10-05T10:48:21 | 2012-10-05T10:48:21 | 78,375,325 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,382 | cpp | #include <plug_common.h>
class luna_wrapper_osgUtil_RenderBin_SortCallback {
public:
typedef Luna< osgUtil::RenderBin::SortCallback > luna_t;
// Derived class converters:
static int _cast_from_Referenced(lua_State *L) {
// all checked are already performed before reaching this point.
osgUtil::RenderBin::SortCallback* ptr= dynamic_cast< osgUtil::RenderBin::SortCallback* >(Luna< osg::Referenced >::check(L,1));
if(!ptr)
return 0;
// Otherwise push the pointer:
Luna< osgUtil::RenderBin::SortCallback >::push(L,ptr,false);
return 1;
};
// Function checkers:
inline static bool _lg_typecheck_sortImplementation(lua_State *L) {
if( lua_gettop(L)!=2 ) return false;
if( (lua_isnil(L,2)==0 && !Luna<void>::has_uniqueid(L,2,50169651)) ) return false;
return true;
}
// Operator checkers:
// (found 0 valid operators)
// Function binds:
// void osgUtil::RenderBin::SortCallback::sortImplementation(osgUtil::RenderBin * )
static int _bind_sortImplementation(lua_State *L) {
if (!_lg_typecheck_sortImplementation(L)) {
luna_printStack(L);
luaL_error(L, "luna typecheck failed in void osgUtil::RenderBin::SortCallback::sortImplementation(osgUtil::RenderBin * ) function, expected prototype:\nvoid osgUtil::RenderBin::SortCallback::sortImplementation(osgUtil::RenderBin * )\nClass arguments details:\narg 1 ID = 50169651\n");
}
osgUtil::RenderBin* _arg1=dynamic_cast< osgUtil::RenderBin* >(Luna< osg::Referenced >::check(L,2));
osgUtil::RenderBin::SortCallback* self=dynamic_cast< osgUtil::RenderBin::SortCallback* >(Luna< osg::Referenced >::check(L,1));
if(!self) {
luna_printStack(L);
luaL_error(L, "Invalid object in function call void osgUtil::RenderBin::SortCallback::sortImplementation(osgUtil::RenderBin *)");
}
self->sortImplementation(_arg1);
return 0;
}
// Operator binds:
};
osgUtil::RenderBin::SortCallback* LunaTraits< osgUtil::RenderBin::SortCallback >::_bind_ctor(lua_State *L) {
return NULL; // Class is abstract.
// Abstract methods:
// void osgUtil::RenderBin::SortCallback::sortImplementation(osgUtil::RenderBin * )
// Abstract operators:
}
void LunaTraits< osgUtil::RenderBin::SortCallback >::_bind_dtor(osgUtil::RenderBin::SortCallback* obj) {
osg::ref_ptr<osg::Referenced> refptr = obj;
}
const char LunaTraits< osgUtil::RenderBin::SortCallback >::className[] = "SortCallback";
const char LunaTraits< osgUtil::RenderBin::SortCallback >::fullName[] = "osgUtil::RenderBin::SortCallback";
const char LunaTraits< osgUtil::RenderBin::SortCallback >::moduleName[] = "osgUtil";
const char* LunaTraits< osgUtil::RenderBin::SortCallback >::parents[] = {"osg.Referenced", 0};
const int LunaTraits< osgUtil::RenderBin::SortCallback >::hash = 60083473;
const int LunaTraits< osgUtil::RenderBin::SortCallback >::uniqueIDs[] = {50169651,0};
luna_RegType LunaTraits< osgUtil::RenderBin::SortCallback >::methods[] = {
{"sortImplementation", &luna_wrapper_osgUtil_RenderBin_SortCallback::_bind_sortImplementation},
{0,0}
};
luna_ConverterType LunaTraits< osgUtil::RenderBin::SortCallback >::converters[] = {
{"osg::Referenced", &luna_wrapper_osgUtil_RenderBin_SortCallback::_cast_from_Referenced},
{0,0}
};
luna_RegEnumType LunaTraits< osgUtil::RenderBin::SortCallback >::enumValues[] = {
{0,0}
};
| [
"roche.emmanuel@gmail.com"
] | roche.emmanuel@gmail.com |
683a8c9a04ee349aadec78d77d060b5dcbbc37e9 | 51635684d03e47ebad12b8872ff469b83f36aa52 | /external/gcc-12.1.0/libstdc++-v3/testsuite/29_atomics/atomic/65147.cc | 0c390bb86420dc47e6566df048e8fb7009799039 | [
"LGPL-2.1-only",
"GPL-3.0-only",
"GCC-exception-3.1",
"GPL-2.0-only",
"LGPL-3.0-only",
"LGPL-2.0-or-later",
"Zlib",
"LicenseRef-scancode-public-domain"
] | permissive | zhmu/ananas | 8fb48ddfe3582f85ff39184fc7a3c58725fe731a | 30850c1639f03bccbfb2f2b03361792cc8fae52e | refs/heads/master | 2022-06-25T10:44:46.256604 | 2022-06-12T17:04:40 | 2022-06-12T17:04:40 | 30,108,381 | 59 | 8 | Zlib | 2021-09-26T17:30:30 | 2015-01-31T09:44:33 | C | UTF-8 | C++ | false | false | 960 | cc | // Copyright (C) 2015-2022 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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, 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 General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// { dg-do compile { target c++11 } }
#include <atomic>
struct S16 {
char c[16];
};
static_assert( alignof(std::atomic<S16>) >= 16,
"atomic<S16> must be aligned to at least its size" );
| [
"rink@rink.nu"
] | rink@rink.nu |
5b421b25131b907b73ca8fc247a14cfea9087b25 | fe4ebfc4a21f996e4e792e75961c74453fab85c0 | /src/error.h | 83963ee566c20715cc3d397cab81e8ef39bc7cd6 | [] | no_license | xeekworx/spacetheory | 4e2971e83e9eaeb0640cfabb2595679e495ab1b9 | 753c88e96e9880c8485f0930e7476faedebbde28 | refs/heads/master | 2021-01-19T22:52:39.807236 | 2018-03-11T03:23:21 | 2018-03-11T03:23:21 | 88,878,200 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 463 | h | #pragma once
#include <stdexcept>
namespace spacetheory {
class error : public std::runtime_error
{
// May extend the capability of this in the future, but to avoid the
// mass changes needed I'm going to go ahead and make use of this
// everywhere.
public:
explicit error(const std::string& what_arg) : runtime_error(what_arg) {}
explicit error(const char* what_arg) : runtime_error(what_arg) {}
};
} | [
"xeek@xeekworx.com"
] | xeek@xeekworx.com |
732ac11c843ec35b1b22d949eb6cffa7607a0a06 | 06810247a5fe519f3521adcc031b9a65011b485e | /No/2020.cpp | 546b0cf6044ce8f1a41ea4282456248925cb864d | [] | no_license | yjhmelody/hdoj | ce036b7573200a4b075f4d8815595e5afc904887 | 4fabb95b2cb42c984ad5f0e7e8cc9680110c1b0c | refs/heads/master | 2020-02-26T13:31:30.066347 | 2016-11-22T14:21:39 | 2016-11-22T14:21:39 | 68,513,913 | 0 | 0 | null | 2016-11-21T09:21:58 | 2016-09-18T10:21:50 | C++ | UTF-8 | C++ | false | false | 568 | cpp | #include<stdio.h>
#include<string.h>
int main()
{
int n,i,temp,k,j;
while(~scanf("%d",&n)&&n)
{
int a[100],b[100];
memset(b,0,sizeof(b));
for(i=0;i<n;i++)
{
scanf("%d",a+i);
if(a[i]<0)
{
b[i]=1;
a[i]=-a[i];
}
}
for(i=0;i<n;++i)
{
k=i;
for(j=i+1;j<n;++j)
{
if(a[k]<a[j])
k=j;
}
temp=a[k];
a[k]=a[i];
a[i]=temp;
temp=b[k];
b[k]=b[i];
b[i]=temp;
}
for(i=0;i<n-1;i++)
{
if(b[i])
printf("-");
printf("%d ",a[i]);
}
if(b[i])
printf("-");
printf("%d\n",a[i]);
}
return 0;
}
| [
"465402634@qq.com"
] | 465402634@qq.com |
80e34a3bf7d64e059e631eaffa96110b5060c441 | 068c1a644084a3920969949dfd0f0de5b9528a29 | /cpp-cgdk/model/Unit.h | 9056d5370dc08c5fcd4304555f14aa0cdb68c54f | [] | no_license | m16a/game01 | 28374fa824aa95daa556dc157e220ec1c1d057f1 | ef9169e82ce551539c5bb4d5720ba39f8c551125 | refs/heads/master | 2021-01-15T22:52:57.832889 | 2013-11-29T18:09:09 | 2013-11-29T18:09:09 | 14,368,124 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 451 | h | #pragma once
#ifndef _UNIT_H_
#define _UNIT_H_
namespace model {
class Unit {
private:
long long id;
int x;
int y;
protected:
Unit(long long id, int x, int y);
public:
virtual ~Unit();
long long getId() const;
int getX() const;
int getY() const;
double getDistanceTo(int x, int y) const;
double getDistanceTo(const Unit& unit) const;
};
}
#endif
| [
"mshvorak@gmail.com"
] | mshvorak@gmail.com |
4ffcd993dcc3945c439a3e08513e557fbc285915 | ec7a0d96847f30a34d0502697c92f51b1b7adc52 | /src/RayTracer.h | 47f39a8eca8c1131a891537c3c6a734170f6376a | [] | no_license | LeeDua/RayTracing | fd7cc0d90605c703d1941b39cc0252023310f2ed | d9498e74a2a10c3538cea1347680e97255266e77 | refs/heads/master | 2023-02-03T07:36:13.576376 | 2020-12-16T15:30:15 | 2020-12-16T15:30:15 | 319,074,879 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,261 | h | #ifndef RAY_TRACER_H
#define RAY_TRACER_H
#include "HittableVec.h"
#include "Ray.h"
#include "Material.h"
#include "BVH.h"
namespace RayTracing{
class RayTracerBase{
public:
virtual MatColor trace(Ray& ray) const = 0;
private:
virtual void recursiveTrace(Ray& ray, HitRecord& hit_record, MatColor& color) const = 0;
};
class RayTracer: public virtual RayTracerBase{
public:
RayTracer(HittableVec& scene):scene(scene){};
MatColor trace(Ray& ray) const override{
HitRecord hit_record;
MatColor color(1.0,1.0,1.0);
recursiveTrace(ray, hit_record, color);
#ifdef COLORED_BG
dtype mix = (1.0 + ray.direction()[1])*0.5;
MatColor mixed_color = (1.0-mix)*MatColor(1.0,1.0,1.0) + mix * MatColor(0.5,0.7,1.0);
return color * mixed_color;
#endif
if(ray.hit_once)
return color;
return MatColor();
}
private:
void recursiveTrace(Ray& ray, HitRecord& hit_record, MatColor& color) const override{
if(scene.hit(ray, hit_record)){
hit_record.material->interactWithLight(ray, hit_record, color);
ray.updateDepthCounter();
if(ray.isAlive()){
return recursiveTrace(ray, hit_record, color);
}
}
}
HittableVec scene;
};
class BVHRayTracer: public RayTracer{
public:
//has to do post init for bbox, so the scene is not marked const
BVHRayTracer(HittableVec& scene):RayTracer(scene){
scene.init();
tree = std::make_shared<BVHTree>(scene);
}
private:
void recursiveTrace(Ray& ray, HitRecord& hit_record, MatColor& color) const override{
if(tree->hit(ray, hit_record)){
hit_record.material->interactWithLight(ray, hit_record, color);
ray.updateDepthCounter();
if(ray.isAlive()){
recursiveTrace(ray, hit_record, color);
}
}
}
private:
std::shared_ptr<BVHTree> tree;
};
}
#endif | [
"1063809383@qq.com"
] | 1063809383@qq.com |
7daaa44851dee0f89b9408248a411398998fe570 | 220a9d0f6a7dea7c6eeea192a820e8c53dd4bbd1 | /crack/main.cpp | 5c5780ad7a95541d364dc3407fbf3900a111b6b1 | [] | no_license | IamLupo/hackhound-cyber-challenge | 8e340fc4ef8ec62be1eaadf183e16311d9e57fa2 | 759c322924f7594d35e396c24fb7edbc2a181a6c | refs/heads/master | 2021-01-10T17:56:52.258273 | 2014-02-05T18:27:44 | 2014-02-05T18:27:44 | 44,474,075 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 34,243 | cpp | #include <boost/thread.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <windows.h>
using namespace std;
enum Secret_Message
{
MSG_DEC_SUCCES,
MSG_ENC_SUCCES,
MSG_USAGE,
MSG_ERROR_INPUT_FILE,
MSG_ERROR_OUTPUT_FILE,
MSG_ERROR_FILE_FORMAT,
MSG_ERROR_PASSWORD,
MSG_ERROR_MALFUNCTION
};
enum Thread_Status
{
THREAD_STATUS_NONE = -1,
THREAD_STATUS_RUNNING,
THREAD_STATUS_FINISHED
};
//Functions
unsigned int ThreadReverseMultiplication(int threads, unsigned int output, unsigned int mul);
void FindMasterThree(Thread_Status* thread_status, unsigned int begin, unsigned int end,
unsigned int master_key[4], unsigned int enc_file_keys_3, unsigned int time);
char secret_message_0[] = { 0x4C, 0x77, 0x21, 0x26, 0x53, 0x50, 0x7C, 0x23, 0x25, 0x7A, 0x60,
0x51, 0x27, 0x21, 0x21, 0x77, 0x77, 0x4C, 0x77, 0x4C, 0x00 };
char secret_message_1[] = { 0x77, 0x7A, 0x21, 0x26, 0x53, 0x50, 0x7C, 0x23, 0x25, 0x7A, 0x60,
0x51, 0x27, 0x21, 0x21, 0x77, 0x77, 0x4C, 0x77, 0x4C, 0x00 };
char secret_message_2[] = { 0x27, 0x51, 0x4B, 0x4D, 0x77, 0x3E, 0x60, 0x21, 0x26, 0x53, 0x50,
0x7C, 0x60, 0x0F, 0x49, 0x4C, 0x65, 0x77, 0x1F, 0x60, 0x49, 0x22,
0x23, 0x24, 0x77, 0x75, 0x23, 0x7A, 0x1F, 0x60, 0x49, 0x22, 0x23,
0x24, 0x77, 0x75, 0x25, 0x27, 0x7C, 0x1F, 0x60, 0x49, 0x50, 0x4B,
0x51, 0x51, 0x7D, 0x25, 0x26, 0x4C, 0x1F, 0x00 };
char secret_message_3[] = { 0x77, 0x26, 0x26, 0x25, 0x26, 0x3E, 0x60, 0x21, 0x4B, 0x7A, 0x60,
0x7A, 0x25, 0x7C, 0x60, 0x25, 0x50, 0x77, 0x7A, 0x60, 0x23, 0x7A,
0x50, 0x27, 0x7C, 0x60, 0x22, 0x23, 0x24, 0x77, 0x00 };
char secret_message_4[] = { 0x77, 0x26, 0x26, 0x25, 0x26, 0x3E, 0x60, 0x21, 0x4B, 0x7A, 0x60,
0x7A, 0x25, 0x7C, 0x60, 0x25, 0x50, 0x77, 0x7A, 0x60, 0x25, 0x27,
0x7C, 0x50, 0x27, 0x7C, 0x60, 0x22, 0x23, 0x24, 0x77, 0x00 };
char secret_message_5[] = { 0x77, 0x26, 0x26, 0x25, 0x26, 0x3E, 0x60, 0x23, 0x7A, 0x52, 0x4B,
0x24, 0x23, 0x4C, 0x60, 0x22, 0x23, 0x24, 0x77, 0x60, 0x22, 0x25,
0x26, 0x4F, 0x4B, 0x7C, 0x00 };
char secret_message_6[] = { 0x77, 0x26, 0x26, 0x25, 0x26, 0x3E, 0x60, 0x23, 0x7A, 0x21, 0x25,
0x26, 0x26, 0x77, 0x21, 0x7C, 0x60, 0x50, 0x4B, 0x51, 0x51, 0x7D,
0x25, 0x26, 0x4C, 0x00 };
char secret_message_7[] = { 0x77, 0x26, 0x26, 0x25, 0x26, 0x3E, 0x60, 0x51, 0x25, 0x4F, 0x77,
0x7C, 0x78, 0x23, 0x7A, 0x4D, 0x60, 0x21, 0x4B, 0x27, 0x51, 0x77,
0x4C, 0x60, 0x7C, 0x78, 0x77, 0x60, 0x4B, 0x50, 0x50, 0x24, 0x23,
0x21, 0x4B, 0x7C, 0x23, 0x25, 0x7A, 0x60, 0x7C, 0x25, 0x60, 0x4F,
0x4B, 0x24, 0x22, 0x27, 0x7A, 0x21, 0x7C, 0x23, 0x25, 0x7A, 0x00 };
char secret_message_8[] = { 0x1C, 0x26, 0x25, 0x24, 0x25, 0x24, 0x25, 0x24, 0x25, 0x00 };
void DecryptMessage(char* message)
{
unsigned int message_length = (unsigned)strlen(message);
int i;
for (i = 0; i < message_length; i++)
{
message[i] = (message[i] * 3) & 0x8000007F;
}
}
void ShowMessageAndExit(Secret_Message id)
{
char* message_ptr;
if(id == MSG_DEC_SUCCES)
message_ptr = secret_message_0;
else if(id == MSG_ENC_SUCCES)
message_ptr = secret_message_1;
else if(id == MSG_USAGE)
message_ptr = secret_message_2;
else if(id == MSG_ERROR_INPUT_FILE)
message_ptr = secret_message_3;
else if(id == MSG_ERROR_OUTPUT_FILE)
message_ptr = secret_message_4;
else if(id == MSG_ERROR_FILE_FORMAT)
message_ptr = secret_message_5;
else if(id == MSG_ERROR_PASSWORD)
message_ptr = secret_message_6;
else if(id == MSG_ERROR_MALFUNCTION)
message_ptr = secret_message_7;
//Decrypt
DecryptMessage(message_ptr);
//Draw
printf("%s \n", message_ptr);
//Exit
if(id == MSG_DEC_SUCCES || id == MSG_ENC_SUCCES || id == MSG_USAGE)
exit(EXIT_SUCCESS);
else
exit(EXIT_FAILURE);
/* You already know the answer! :D */
}
void InitKey(unsigned int generated_key[4], char* _password)
{
unsigned int i, temp_value;
temp_value = 0x3C;
for(i = 0; i < 16; i++)
{
unsigned int byte_id = i / 4;
unsigned int byte_position = i % 4;
if(byte_position == 0)
generated_key[byte_id] += (temp_value);
else if(byte_position == 1)
generated_key[byte_id] += (temp_value * 0x100);
else if(byte_position == 2)
generated_key[byte_id] += (temp_value * 0x10000);
else if(byte_position == 3)
generated_key[byte_id] += (temp_value * 0x1000000);
}
//Password
unsigned int password_length = strlen(_password);
unsigned int fix = 0x0;
temp_value = (((generated_key[0] & 0xFF000000) / 0x1000000) + password_length) & 0xFF;
generated_key[0] = (temp_value * 0x1000000) + (generated_key[0] & 0x00FFFFFF);
for(i = 0; i < password_length + fix; i++)
{
unsigned int byte_id = ((i + 1) % 16) / 4;
unsigned int byte_position = ((i + 1) % 16) % 4;
if(byte_position == 0 && byte_id == 0)
{
fix += 0x1;
}
else if(byte_position == 0)
{
temp_value = (generated_key[byte_id] & 0xFF000000) / 0x1000000;
temp_value = (temp_value + (unsigned int)_password[i - fix]) & 0xFF;
generated_key[byte_id] = (temp_value * 0x1000000) + (generated_key[byte_id] & 0x00FFFFFF);
}
else if(byte_position == 1)
{
temp_value = (generated_key[byte_id] & 0xFF0000) / 0x10000;
temp_value = (temp_value + (unsigned int)_password[i - fix]) & 0xFF;
generated_key[byte_id] = (temp_value * 0x10000) + (generated_key[byte_id] & 0xFF00FFFF);
}
else if(byte_position == 2)
{
temp_value = (generated_key[byte_id] & 0xFF00) / 0x100;
temp_value = (temp_value + (unsigned int)_password[i - fix]) & 0xFF;
generated_key[byte_id] = (temp_value * 0x100) + (generated_key[byte_id] & 0xFFFF00FF);
}
else if(byte_position == 3)
{
temp_value = generated_key[byte_id] & 0xFF;
temp_value = (temp_value + (unsigned int)_password[i - fix]) & 0xFF;
/* You like carrot? */
generated_key[byte_id] = temp_value + (generated_key[byte_id] & 0xFFFFFF00);
}
}
}
void GenerateKey(unsigned int master_key[4], unsigned int generated_key[4])
{
unsigned int key_values[] = { 0xE, // 0000 1110
0x3, // 0001 0011
0xA, // 0010 1010
0xB, // 0011 1011
0x0, // 0100 0000
0x9, // 0101 1001
0x8, // 0110 1000
0x5, // 0111 0101
0xC, // 1000 1100
0xF, // 1001 1111
0x6, // 1010 0110
0x1, // 1011 0001
0x4, // 1100 0100
0xD, // 1101 1101
0x2, // 1110 0010
0x7 }; // 1111 0111 //4e byte doesnt change! :D hehe :D
unsigned int i;
unsigned int j;
for (i = 0; i < 32; i++)
{
generated_key[0] = (generated_key[0] + master_key[0]) * 0xF97CE7B7;
generated_key[1] = (generated_key[1] + master_key[1]) * 0xE9701ECB;
generated_key[2] = (generated_key[2] + master_key[2]) * 0x70103AA1;
generated_key[3] = (generated_key[3] + master_key[i % 3] + i) * 0xBD810313;
unsigned int temp_key[] = { 0x0, 0x0, 0x0, 0x0 };
for(j = 0; j < 32; j++)
{
unsigned int id;
id = (((generated_key[3] >> (0x1F - j)) & 0x1) * 0x2);
id = (id ^ (generated_key[2] >> (0x1F - j)) & 0x1) * 0x2;
id = (id ^ ((generated_key[1] >> (0x1F - j)) & 0x1)) * 0x2;
id = id ^ ((generated_key[0] >> (0x1F - j)) & 0x1);
temp_key[0] = (key_values[id] & 0x1) ^ (temp_key[0] + temp_key[0]); // Because the first bit never change the generate_key will also not change :D
temp_key[1] = ((key_values[id] >> 0x1) & 0x1) ^ (temp_key[1] + temp_key[1]);
temp_key[2] = ((key_values[id] >> 0x2) & 0x1) ^ (temp_key[2] + temp_key[2]);
temp_key[3] = ((key_values[id] >> 0x3) & 0x1) ^ (temp_key[3] + temp_key[3]);
}
generated_key[0] = temp_key[0];
generated_key[1] = temp_key[1];
generated_key[2] = temp_key[2];
generated_key[3] = temp_key[3];
}
generated_key[0] += master_key[0];
generated_key[1] += master_key[1];
generated_key[2] += master_key[2];
generated_key[3] += master_key[0];
}
void InitMasterKey(unsigned int master_key[4], unsigned int generated_key[4])
{
master_key[0] = generated_key[0];
master_key[1] = generated_key[1];
master_key[2] = generated_key[2];
master_key[3] = generated_key[3];
generated_key[0] = master_key[2] ^ master_key[1] ^ master_key[0];
generated_key[1] = master_key[3] ^ master_key[1] ^ master_key[0];
generated_key[2] = master_key[3] ^ master_key[2] ^ master_key[0];
generated_key[3] = master_key[3] ^ master_key[2] ^ master_key[1];
}
/* Blub */
void InitMasterTimeKey(unsigned int master_key[4], unsigned int mastertime_key[4], unsigned int time)
{
mastertime_key[0] = master_key[0] ^ time;
mastertime_key[1] = master_key[1] ^ time;
mastertime_key[2] = master_key[2] ^ time;
mastertime_key[3] = master_key[3] ^ time;
GenerateKey(master_key, mastertime_key);
}
void Encrypt(char* _input_file, char* _output_file, char* _password)
{
FILE* input_file;
FILE* output_file;
size_t result;
//Open Input File
input_file = fopen(_input_file,"rb");
if(input_file == NULL)
ShowMessageAndExit(MSG_ERROR_INPUT_FILE);
//Create Output File
output_file = fopen(_output_file,"wb");
if(output_file == NULL)
{
fclose(input_file);
ShowMessageAndExit(MSG_ERROR_OUTPUT_FILE);
}
//Make Header
char header[4] = { 'E', 'N', 'C', '/' };
fwrite(header, sizeof(char), 4, output_file);
//generate password hash and write to file
unsigned int generated_key[4] = { 0x0, 0x0, 0x0, 0x0 };
unsigned int master_key[4] = { 0x0, 0x0, 0x0, 0x0 };
InitKey(generated_key, _password);
GenerateKey(master_key, generated_key);
InitMasterKey(master_key, generated_key);
GenerateKey(master_key, generated_key);
char password_hash[4] = { ((generated_key[0] & 0xFF) / 0x1),
((generated_key[0] & 0xFF00) / 0x100),
((generated_key[0] & 0xFF0000) / 0x10000),
((generated_key[0] & 0xFF000000) / 0x1000000)};
fwrite(password_hash, sizeof(char), 4, output_file);
unsigned int time = GetTickCount();
InitMasterTimeKey(master_key, generated_key, time); //WTF WHY?!
char key[4];
for(int i = 0; i < 4; i++)
{
char key[4] = { ((generated_key[i] & 0xFF) / 0x1),
((generated_key[i] & 0xFF00) / 0x100),
((generated_key[i] & 0xFF0000) / 0x10000),
((generated_key[i] & 0xFF000000) / 0x1000000)};
fwrite(key, sizeof(char), 4, output_file);
}
//read data and encrypt it
char buffer[16];
do
{
GenerateKey(master_key, generated_key);
result = fread(buffer, 1, 16, input_file);
buffer[0] = (buffer[0] & 0xFF) ^ (generated_key[0] & 0xFF); // HOP
buffer[1] = (buffer[1] & 0xFF) ^ ((generated_key[0] & 0xFF00) / 0x100); // HOP
buffer[2] = (buffer[2] & 0xFF) ^ ((generated_key[0] & 0xFF0000) / 0x10000); // HOP
buffer[3] = (buffer[3] & 0xFF) ^ ((generated_key[0] & 0xFF000000) / 0x1000000); // HOP
buffer[4] = (buffer[4] & 0xFF) ^ (generated_key[1] & 0xFF); // HOP
buffer[5] = (buffer[5] & 0xFF) ^ ((generated_key[1] & 0xFF00) / 0x100); // HOP
buffer[6] = (buffer[6] & 0xFF) ^ ((generated_key[1] & 0xFF0000) / 0x10000); // HOP
buffer[7] = (buffer[7] & 0xFF) ^ ((generated_key[1] & 0xFF000000) / 0x1000000); // HOP
buffer[8] = (buffer[8] & 0xFF) ^ (generated_key[2] & 0xFF); // HOP
buffer[9] = (buffer[9] & 0xFF) ^ ((generated_key[2] & 0xFF00) / 0x100); // HOP
buffer[10] = (buffer[10] & 0xFF) ^ ((generated_key[2] & 0xFF0000) / 0x10000); // HOP
buffer[11] = (buffer[11] & 0xFF) ^ ((generated_key[2] & 0xFF000000) / 0x1000000); // HOP
buffer[12] = (buffer[12] & 0xFF) ^ (generated_key[3] & 0xFF); // HOP
buffer[13] = (buffer[13] & 0xFF) ^ ((generated_key[3] & 0xFF00) / 0x100); // HOP
buffer[14] = (buffer[14] & 0xFF) ^ ((generated_key[3] & 0xFF0000) / 0x10000); // HOP
buffer[15] = (buffer[15] & 0xFF) ^ ((generated_key[3] & 0xFF000000) / 0x1000000); // HOP
fwrite(buffer, sizeof(char), result, output_file);
}
while(result == 16);
fclose(input_file);
fclose(output_file);
ShowMessageAndExit(MSG_ENC_SUCCES);
}
void Decrypt(char* _input_file, char* _output_file, char* _password)
{
FILE* input_file;
FILE* output_file;
size_t result;
//Open Input File
input_file = fopen(_input_file,"rb");
if(input_file == NULL)
ShowMessageAndExit(MSG_ERROR_INPUT_FILE);
//Create Output File
output_file = fopen(_output_file,"wb");
if(output_file == NULL)
{
fclose(input_file);
ShowMessageAndExit(MSG_ERROR_OUTPUT_FILE);
}
//Read Format
char header[4];
result = fread(header, 1, 4, input_file);
if(result != 4)
{
fclose(input_file);
fclose(output_file);
ShowMessageAndExit(MSG_ERROR_MALFUNCTION);
}
if(header[0] == 0x2F && header[1] == 0x43 && header[2] == 0x4E && header[3] == 0x45 ) // header is "ENC/"
{
fclose(input_file);
fclose(output_file);
ShowMessageAndExit(MSG_ERROR_FILE_FORMAT);
}
//generate password hash with password
unsigned int generated_key[4] = { 0x0, 0x0, 0x0, 0x0 };
unsigned int master_key[4] = { 0x0, 0x0, 0x0, 0x0 };
InitKey(generated_key, _password);
GenerateKey(master_key, generated_key);
InitMasterKey(master_key, generated_key);
GenerateKey(master_key, generated_key);
//Get password hash out of file
char password_hash[4];
result = fread(password_hash, 1, 4, input_file);
if(result != 4)
{
fclose(input_file);
fclose(output_file);
ShowMessageAndExit(MSG_ERROR_MALFUNCTION);
}
//Check Password hash with each other
if( (password_hash[0] & 0xFF) != ((generated_key[0] & 0xFF) / 0x1) ||
(password_hash[1] & 0xFF) != ((generated_key[0] & 0xFF00) / 0x100) ||
(password_hash[2] & 0xFF) != ((generated_key[0] & 0xFF0000) / 0x10000) ||
(password_hash[3] & 0xFF) != ((generated_key[0] & 0xFF000000) / 0x1000000))
{
fclose(input_file);
fclose(output_file);
/* I told you so! */
ShowMessageAndExit(MSG_ERROR_PASSWORD);
}
//Get generated_key out of file
char key[4];
for(int i = 0; i < 4; i++)
{
result = fread(key, 1, 4, input_file);
if(result != 4)
{
fclose(input_file);
fclose(output_file);
ShowMessageAndExit(MSG_ERROR_MALFUNCTION);
}
generated_key[i] = ((key[3] & 0xFF) * 0x1000000) + ((key[2] & 0xFF) * 0x10000) + ((key[1] & 0xFF) * 0x100) + (key[0] & 0xFF);
}
//read data and decrypt it
char buffer[16];
do
{
GenerateKey(master_key, generated_key);
result = fread(buffer, 1, 16, input_file);
buffer[0] = (buffer[0] & 0xFF) ^ (generated_key[0] & 0xFF); // HOP
buffer[1] = (buffer[1] & 0xFF) ^ ((generated_key[0] & 0xFF00) / 0x100); // HOP
buffer[2] = (buffer[2] & 0xFF) ^ ((generated_key[0] & 0xFF0000) / 0x10000); // HOP
buffer[3] = (buffer[3] & 0xFF) ^ ((generated_key[0] & 0xFF000000) / 0x1000000); // HOP
buffer[4] = (buffer[4] & 0xFF) ^ (generated_key[1] & 0xFF); // HOP
buffer[5] = (buffer[5] & 0xFF) ^ ((generated_key[1] & 0xFF00) / 0x100); // HOP
buffer[6] = (buffer[6] & 0xFF) ^ ((generated_key[1] & 0xFF0000) / 0x10000); // HOP
buffer[7] = (buffer[7] & 0xFF) ^ ((generated_key[1] & 0xFF000000) / 0x1000000); // HOP
buffer[8] = (buffer[8] & 0xFF) ^ (generated_key[2] & 0xFF); // HOP
buffer[9] = (buffer[9] & 0xFF) ^ ((generated_key[2] & 0xFF00) / 0x100); // HOP
buffer[10] = (buffer[10] & 0xFF) ^ ((generated_key[2] & 0xFF0000) / 0x10000); // HOP
buffer[11] = (buffer[11] & 0xFF) ^ ((generated_key[2] & 0xFF000000) / 0x1000000); // HOP
buffer[12] = (buffer[12] & 0xFF) ^ (generated_key[3] & 0xFF); // HOP
buffer[13] = (buffer[13] & 0xFF) ^ ((generated_key[3] & 0xFF00) / 0x100); // HOP
buffer[14] = (buffer[14] & 0xFF) ^ ((generated_key[3] & 0xFF0000) / 0x10000); // HOP
buffer[15] = (buffer[15] & 0xFF) ^ ((generated_key[3] & 0xFF000000) / 0x1000000); // HOP
fwrite(buffer, sizeof(char), result, output_file);
}
while(result == 16);
fclose(input_file);
fclose(output_file);
ShowMessageAndExit(MSG_DEC_SUCCES);
}
//---- Reverse Functions ----
void ReverseBites(unsigned int key[4])
{
unsigned int key_values[] = { 0x4, //x
0xB, //x
0xE, //x
0x1, //x
0xC, //x
0x7, //x
0xA, //x
0xF, //x
0x6, //x
0x5, //x
0x2, //x
0x3, //x
0x8, //x
0xD, //x
0x0, //
0x9 }; //
unsigned int id;
unsigned int i;
unsigned int temp_key[] = { 0x0, 0x0, 0x0, 0x0 };
for(i = 0; i < 32; i++)
{
id = (((key[3] >> (0x1F - i)) & 0x1) * 0x2);
id = (id ^ (key[2] >> (0x1F - i)) & 0x1) * 0x2;
id = (id ^ ((key[1] >> (0x1F - i)) & 0x1)) * 0x2;
id = id ^ ((key[0] >> (0x1F - i)) & 0x1);
//temp_key[3] = (key_values[id] & 0x1) ^ (temp_key[3] + temp_key[3]); //fail ! This we can make better :D
temp_key[0] = ((key[0] >> (0x1F - i)) & 0x1) ^ (temp_key[0] + temp_key[0]); // Fix
temp_key[1] = ((key_values[id] >> 0x1) & 0x1) ^ (temp_key[1] + temp_key[1]);
temp_key[2] = ((key_values[id] >> 0x2) & 0x1) ^ (temp_key[2] + temp_key[2]);
temp_key[3] = ((key_values[id] >> 0x3) & 0x1) ^ (temp_key[3] + temp_key[3]);
}
key[0] = temp_key[0];
key[1] = temp_key[1];
key[2] = temp_key[2];
key[3] = temp_key[3];
}
void ReverseMultiplication(unsigned int* return_value, Thread_Status* thread_status, unsigned int begin, unsigned int end, unsigned int output, unsigned int mul)
{
try
{
unsigned int i;
for(i = begin; i < end; i++)
{
if((i * mul) == output)
{
*thread_status = THREAD_STATUS_FINISHED;
*return_value = i;
return;
}
}
}
catch(boost::thread_interrupted&)
{
return;
}
}
void ReverseGenerateKey(int threads, unsigned int master_key[4], unsigned int password_edited[4])
{
password_edited[0] = master_key[0];
password_edited[1] = master_key[1];
password_edited[2] = master_key[2];
password_edited[3] = master_key[3];
unsigned int i;
unsigned int j;
unsigned int id;
for(i = 0; i < 32; i++)
{
id = (31 - i);
ReverseBites(password_edited);
//Multiply
password_edited[0] = ThreadReverseMultiplication(threads, password_edited[0], 0xF97CE7B7);
password_edited[1] = ThreadReverseMultiplication(threads, password_edited[1], 0xE9701ECB);
password_edited[2] = ThreadReverseMultiplication(threads, password_edited[2], 0x70103AA1);
password_edited[3] = ThreadReverseMultiplication(threads, password_edited[3], 0xBD810313) - id;
}
char password[15];
password[0] = (((password_edited[0] & 0xFF00) / 0x100) - 0x3C) & 0xFF;
password[1] = ((password_edited[0] & 0xFF) - 0x3C) & 0xFF;
password[2] = (((password_edited[1] & 0xFF000000) / 0x1000000) - 0x3C) & 0xFF;
password[3] = (((password_edited[1] & 0xFF0000) / 0x10000) - 0x3C) & 0xFF;
password[4] = (((password_edited[1] & 0xFF00) / 0x100) - 0x3C) & 0xFF;
password[5] = ((password_edited[1] & 0xFF) - 0x3C) & 0xFF;
password[6] = (((password_edited[2] & 0xFF000000) / 0x1000000) - 0x3C) & 0xFF;
password[7] = (((password_edited[2] & 0xFF0000) / 0x10000) - 0x3C) & 0xFF;
password[8] = (((password_edited[2] & 0xFF00) / 0x100) - 0x3C) & 0xFF;
password[9] = ((password_edited[2] & 0xFF) - 0x3C) & 0xFF;
password[10] = (((password_edited[3] & 0xFF000000) / 0x1000000) - 0x3C) & 0xFF;
password[11] = (((password_edited[3] & 0xFF0000) / 0x10000) - 0x3C) & 0xFF;
password[12] = (((password_edited[3] & 0xFF00) / 0x100) - 0x3C) & 0xFF;
password[13] = ((password_edited[3] & 0xFF) - 0x3C) & 0xFF;
password[14] = '\0';
cout << master_key[3] << " - " << ((((password_edited[0] & 0xFF0000) / 0x10000) - 0x3C) & 0xFF) << " - " << password << endl;
}
//---- Threads ----
unsigned int ThreadReverseMultiplication(int threads, unsigned int output, unsigned int mul)
{
unsigned int i;
boost::thread_group tgroup;
unsigned int return_value[threads];
Thread_Status thread_status[threads];
unsigned int space = 0xFFFFFFFF / threads;
for(i = 0; i < threads; i++)
{
return_value[i] = 0;
thread_status[i] = THREAD_STATUS_RUNNING;
tgroup.create_thread(
boost::bind(
&ReverseMultiplication,
&return_value[i],
&thread_status[i],
i * space,
(i + 1) * space,
output,
mul
)
);
}
bool found = false;
unsigned int id = 0;
while(!found)
{
for(i = 0; i < threads; i++)
{
if(thread_status[i] == THREAD_STATUS_FINISHED)
{
thread_status[i] = THREAD_STATUS_NONE;
if(return_value[i] != 0)
{
found = true;
id = i;
}
}
}
}
//Ending threads
tgroup.interrupt_all();
tgroup.join_all();
return return_value[id];
}
void FindMasterThree(Thread_Status* thread_status, unsigned int begin, unsigned int end,
unsigned int master_key[4], unsigned int enc_file_keys_3, unsigned int time)
{
try
{
unsigned int i;
unsigned int mastertime_key[4] = { 0x0, 0x0, 0x0, 0x0 };
for(i = begin; i < end; i++)
{
master_key[3] = i;
InitMasterTimeKey(master_key, mastertime_key, time);
if(mastertime_key[3] == enc_file_keys_3)
{
cout << "found = " << i << endl;
}
}
*thread_status = THREAD_STATUS_FINISHED;
return;
}
catch(boost::thread_interrupted&)
{
return;
}
}
//---- Cracker ----
//Part 1
/*
We know that a zip begins with "0x50, 0x4b, 0x03, 0x04". Also we know the encrypted data. We can calculated the next encryption key.
Next we know that GenerateKey function has a bug.
generated_key_0_output = (generated_key_0_input * master_key_0) * 0xF97CE7B7 <- 32 times repeated.
Now we have this case:
generated_key_output = next_encryption_key
generated_key_0_input = 0xe4d6f212;
We now only have to bruteforce the master_key_0
*/
unsigned int Crack_Part_1(unsigned int enc_file_keys_0, unsigned int enc_file_data_0)
{
unsigned int generate;
unsigned int master;
unsigned int check_0 = 0x50 ^ (enc_file_data_0 & 0xFF); //Key part 1
unsigned int check_1 = 0x4b ^ ((enc_file_data_0 & 0xFF00) / 0x100); //Key part 2
unsigned int check_2 = 0x03 ^ ((enc_file_data_0 & 0xFF0000) / 0x10000); //Key part 3
unsigned int check_3 = 0x04 ^ ((enc_file_data_0 & 0xFF000000) / 0x1000000); //Key part 4
unsigned int check_key = (check_3 * 0x1000000) + (check_2 * 0x10000) + (check_1 * 0x100) + check_0;
unsigned int i;
for(i = 0x4293777F; i < 0xFFFFFFFF; i++)
{
generate = enc_file_keys_0;
master = i;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
if(generate == check_key)
return i;
}
return 0;
}
//Part 2
/*
Now we have the master_key_0 we can now bruteforce the time
*/
unsigned int Crack_Part_2(unsigned int master_key_0, unsigned int enc_file_keys_0)
{
unsigned int generate;
unsigned int i;
for(i = 0xE1C871; i < 0xFFFFFFFF; i++)
{
generate = master_key_0 ^ i;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
if(enc_file_keys_0 == generate)
return i;
}
return 0;
}
//Part 3
/*
Because we have the master_key_0 and the enc_file_passwordhash we can try to find the generator_0
*/
unsigned int Crack_Part_3(unsigned int master_key_0, unsigned int enc_file_passwordhash)
{
unsigned int generate;
unsigned int i;
for(i = 0x72EE2D82; i < 0xFFFFFFFF; i++)
{
generate = i;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
if(enc_file_passwordhash == generate)
return i;
}
return 0;
}
/*
Because we know that "master_key_1XORmaster_key_2 = master_key_1 ^ master_key_2". We know that there are only 2^32 posibilities to bruteforce.
Also master_key_3 is useless in GenerateKey because it hasnt been used.
*/
void Crack_Part_4(unsigned int master_key[4], unsigned int enc_file_keys[4], unsigned int enc_file_data_1, unsigned int master_key_1XORmaster_key_2, unsigned int options[10])
{
unsigned int found = 0x0;
unsigned int check_0 = 0x14 ^ (enc_file_data_1 & 0xFF); //Key part 1
unsigned int check_1 = 0x00 ^ ((enc_file_data_1 & 0xFF00) / 0x100); //Key part 2
unsigned int check_2 = 0x00 ^ ((enc_file_data_1 & 0xFF0000) / 0x10000); //Key part 3
unsigned int check_3 = 0x00 ^ ((enc_file_data_1 & 0xFF000000) / 0x1000000); //Key part 4
unsigned int check_key = (check_3 * 0x1000000) + (check_2 * 0x10000) + (check_1 * 0x100) + check_0;
unsigned int i;
for(i = 0x1DD79212; i < 0x1DD79213; i++) // Right answer
{
unsigned int generate[] = { enc_file_keys[0], enc_file_keys[1], enc_file_keys[2], enc_file_keys[3] };
unsigned int master[] = { master_key[0], i, (i ^ master_key_1XORmaster_key_2), 0 };
GenerateKey(master, generate);
if(generate[1] == check_key)
{
options[found] = i;
found++;
}
}
}
//Part 5
/*
Because we only don't know the master_key_3 we need to bruteforce to get the same values as "enc_file_keys".
*/
void Crack_Part_5(int threads, unsigned int master_key[4], unsigned int enc_file_keys_3, unsigned int time)
{
unsigned int i;
boost::thread_group tgroup;
Thread_Status thread_status[threads];
unsigned int space = 0xFFFFFFFF / threads;
for(i = 0; i < threads; i++)
{
unsigned int temp_master_key[4] = { master_key[0], master_key[1], master_key[2], 0x0 };
thread_status[i] = THREAD_STATUS_RUNNING;
tgroup.create_thread(
boost::bind(
&FindMasterThree,
&thread_status[i],
i * space,
(i + 1) * space,
temp_master_key,
enc_file_keys_3,
time
)
);
}
unsigned int done = 0;
bool found = false;
while(!found)
{
for(i = 0; i < threads; i++)
{
if(thread_status[i] == THREAD_STATUS_FINISHED)
{
thread_status[i] = THREAD_STATUS_NONE;
done++;
cout << "done = " << done << endl;
if(done >= threads)
found = true;
}
}
}
//Ending threads
tgroup.interrupt_all();
tgroup.join_all();
}
//Part 6
/*
Because we have the generate and the master_key complete, we can reverse the "GenerateKey" function to get
the output of "InitKey" function. What we know that the first value - 3C is the length. Also if the password is longer then
15 symbols it will add 2 charter with each other. like the 1e and the 16e charter + 3C. In this case our password is 16 charters.
We have to look with our eyes what the 1e and 16e charter will be.
*/
void Crack_Part_6(int threads, unsigned int master_key[4], unsigned int password_edited[4])
{
unsigned int i;
unsigned int options[43] = {
0x023B6A2D, 0x04F502B4, 0x065D6A2D, 0x0C7502B4,
0x0E5D6A2D, 0x125D6A2D, 0x1A06A22D, 0x2306A22D,
0x28116A2D, 0x2B7B6A2D, 0x2C116A2D, 0x2E5D6A2D,
0x3A3B6A2D, 0x3E86A22D, 0x48F502B4, 0x4C7502B4,
0x525D6A2D, 0x5ADD6A2D, 0x637D6A2D, 0x6D9D6A2D,
0x6E5D6A2D, 0x7E86A22D, 0x823B6A2D, 0x865D6A2D,
0x8E5D6A2D, 0x925D6A2D, 0x965D6A2D, 0x9A06A22D,
0xA8116A2D, 0xA8F502B4, 0xAE5D6A2D, 0xBA3B6A2D,
0xC37D6A2D, 0xC686A22D, 0xC8F502B4, 0xDA06A22D,
0xE25D6A2D, 0xE37D6A2D, 0xE8116A2D, 0xED9D6A2D,
0xF25D6A2D, 0xFA3B6A2D, 0xFE86A22D
};
for (i = 0; i < 43; i++)
{
master_key[3] = options[i];
ReverseGenerateKey(threads, master_key, password_edited);
}
}
//---- Main ----
int main(int argc, char* argv[])
{
if(argc == 5 && strcmp(argv[1], "-e") == 0)
{
Encrypt(argv[2], argv[3], argv[4]);
}
else if(argc == 5 && strcmp(argv[1], "-d") == 0)
{
Decrypt(argv[2], argv[3], argv[4]);
}
else if(argc == 3 && strcmp(argv[1], "-c") == 0)
{
int threads = static_cast<int>(boost::thread::hardware_concurrency());
//Known values
unsigned int enc_file_passwordhash = 0xb0a0da81;
unsigned int enc_file_keys[] = { 0xac9b280d, 0x753012f2, 0xa700d292, 0x64017b35 };
unsigned int enc_file_data[] = { 0xbc7d475c, 0x4843623c, 0xe61aa83c, 0x6248ea14 };
unsigned int generated_key[4] = { 0x0, 0x0, 0x0, 0x0 };
unsigned int password_edited[4] = { 0x0, 0x0, 0x0, 0x0 };
unsigned int master_key_1XORmaster_key_2 = 0x0;
unsigned int mastertime_key[4] = { 0x0, 0x0, 0x0, 0x0 };
//Bruteforced values
unsigned int master_key[4] = { 0x4293777F, 0x1DD79212, 0x2DAAC8EF, 0x965D6A2D };
unsigned int enc_file_time = 0x00E1C871;
if(strcmp(argv[2], "master") == 0)
{
//Master key 0
master_key[0] = Crack_Part_1(enc_file_keys[0], enc_file_data[0]);
cout << "master_key_0 = " << master_key[0] << endl;
//Encryption Time
enc_file_time = Crack_Part_2(master_key[0], enc_file_keys[0]);
cout << "enc_file_time = " << enc_file_time << endl;
//Generator 0
generated_key[0] = Crack_Part_3(master_key[0], enc_file_passwordhash);
master_key_1XORmaster_key_2 = generated_key[0] ^ master_key[0];
cout << "generated_key = " << generated_key[0] << endl;
cout << "master_key_1XORmaster_key_2 = " << master_key_1XORmaster_key_2 << endl;
//Master key 1 & 2
unsigned int options[10] = { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 };
Crack_Part_4(master_key, enc_file_keys, enc_file_data[1], master_key_1XORmaster_key_2, options);
//Draw
cout << "Options" << endl;
unsigned int i;
for(i = 0; i < 10 && options[i] != 0; i++)
{
cout << "master_key = " << master_key[0] << " - " << options[i] << " - " << (options[i] ^ master_key_1XORmaster_key_2) << endl;
}
}
else if(strcmp(argv[2], "full_master") == 0) // Look at the keys.txt for the output
{
Crack_Part_5(threads, master_key, enc_file_keys[3], enc_file_time);
}
else if(strcmp(argv[2], "password") == 0) // Look at the keys.txt for the output
{
Crack_Part_6(threads, master_key, password_edited);
}
/*
Result:
4C B7 7C 7F - A7 84 6C 91 - AA 80 70 91 - 7C AA 80 A9
-----------------------------------------------------
48 40 43 - 6b 48 30 55 - 6e 44 34 55 - 40 6e 44 6d
33
charters = 0xC4 - 0xC3 = 0x10 = 16 charters
Pass: H@CkH0UnD4U@nDm3
*/
}
else
{
ShowMessageAndExit(MSG_USAGE);
}
}
| [
"admin@ludoruisch.nl"
] | admin@ludoruisch.nl |
ca40657bd158f4e699cbf901e41f232b7120358a | 717c70331e83947539c4a68dd63d1863bbed32e0 | /textga/textga_cpplib/trunk/src/tag/AbstractElement.cpp | e296d4cafd0f39234be57f9a3267247e81357af7 | [] | no_license | hoboaki/oldcode | 5907bdd01af84d6d2d779e26d6e4dbd3be1a028c | 2c2aa0b20dc3f48656011dd5eb197d79fa3266cf | refs/heads/master | 2020-12-03T03:51:03.125931 | 2017-06-29T13:44:19 | 2017-06-29T13:44:19 | 95,781,642 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 964 | cpp | /**
* @file
* @brief AbstractElement.hppの実装を記述する。
*/
#include <textga/tag/AbstractElement.hpp>
//------------------------------------------------------------
namespace textga {
namespace tag {
//------------------------------------------------------------
AbstractElement::AbstractElement(
const char *name
, const ElementKind aKind
)
: name_( name )
, elementKind_( aKind )
{
}
//------------------------------------------------------------
AbstractElement::~AbstractElement()
{
}
//------------------------------------------------------------
const char* AbstractElement::name()const
{
return name_;
}
//------------------------------------------------------------
ElementKind AbstractElement::elementKind()const
{
return elementKind_;
}
//------------------------------------------------------------
}}
//------------------------------------------------------------
// EOF
| [
"hoboaki@10106.net"
] | hoboaki@10106.net |
344e5463bf57057605d10ce82ce12d025e413dee | 45e0fbd9a9dbcdd4fbe6aaa2fdb2aed296f81e33 | /FindSecret/Classes/Native/mscorlib_System_Array_InternalEnumerator_1_gen3490621956.h | c1411b4d6113c3f87907f446a3999f1d05ba3f51 | [
"MIT"
] | permissive | GodIsWord/NewFindSecret | d4a5d2d810ee1f9d6b3bc91168895cc808bac817 | 4f98f316d29936380f9665d6a6d89962d9ee5478 | refs/heads/master | 2020-03-24T09:54:50.239014 | 2018-10-27T05:22:11 | 2018-10-27T05:22:11 | 142,641,511 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,458 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "mscorlib_System_ValueType3640485471.h"
// System.Array
struct Il2CppArray;
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Array/InternalEnumerator`1<EasyAR.IRecorderNotify>
struct InternalEnumerator_1_t3490621956
{
public:
// System.Array System.Array/InternalEnumerator`1::array
Il2CppArray * ___array_0;
// System.Int32 System.Array/InternalEnumerator`1::idx
int32_t ___idx_1;
public:
inline static int32_t get_offset_of_array_0() { return static_cast<int32_t>(offsetof(InternalEnumerator_1_t3490621956, ___array_0)); }
inline Il2CppArray * get_array_0() const { return ___array_0; }
inline Il2CppArray ** get_address_of_array_0() { return &___array_0; }
inline void set_array_0(Il2CppArray * value)
{
___array_0 = value;
Il2CppCodeGenWriteBarrier(&___array_0, value);
}
inline static int32_t get_offset_of_idx_1() { return static_cast<int32_t>(offsetof(InternalEnumerator_1_t3490621956, ___idx_1)); }
inline int32_t get_idx_1() const { return ___idx_1; }
inline int32_t* get_address_of_idx_1() { return &___idx_1; }
inline void set_idx_1(int32_t value)
{
___idx_1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"zhangyide@9fbank.cc"
] | zhangyide@9fbank.cc |
229751f0e206b96ff80af466e8f6ca188f1798b5 | afaf58bfe495edc9da224d597912763df1b5a410 | /src/kt84/openmesh/debug_writeSVG.hh | 92e57d80ae33d11765548fac2be55577e3c6738c | [] | no_license | tian0ti/sketch | 1c5ee62a6411e478f292cfbaa98760d98f62288e | 3ef958dfc69a32a822c6ce71c2d3b4839e1592a0 | refs/heads/master | 2016-09-06T13:40:57.836963 | 2015-04-13T08:46:58 | 2015-04-13T08:46:58 | 33,857,540 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,989 | hh | #pragma once
#include <cstdio>
#include <sstream>
#include "simple_svg_1.0.0.hpp"
namespace {
#ifdef _WIN32
inline FILE* popen(const char* command, const char* mode) { return _popen(command, mode); }
inline int pclose(FILE* file) { return _pclose(file); }
#endif
}
namespace kt84 {
template <class TMesh>
inline void debug_writeSVG(
const TMesh& mesh,
const char* filename = "debug.svg",
bool export_pdf = false,
double dimension = 500.0,
double stroke_width = 1.0,
bool draw_vidx = true,
bool draw_fidx = true,
bool draw_eidx = true,
const char* font_family = "Courier",
double font_size = 10.0,
double font_stroke_width = 1.0)
{
auto p0 = mesh.point(mesh.vertex_handle(0));
double xmin = p0[0], xmax = xmin;
double ymin = p0[1], ymax = ymin;
for (auto v : mesh.vertices()) {
if (mesh.has_vertex_status() && mesh.status(v).deleted()) continue;
auto p = mesh.point(v);
xmin = std::min<double>(xmin, p[0]);
xmax = std::max<double>(xmax, p[0]);
ymin = std::min<double>(ymin, p[1]);
ymax = std::max<double>(ymax, p[1]);
}
double margin = (xmax - xmin + ymax - ymin) * 0.1;
xmin -= margin; xmax += margin;
ymin -= margin; ymax += margin;
double scaling = dimension / std::min<double>(xmax - xmin, ymax - ymin);
svg::Document doc(filename, svg::Layout(svg::Dimensions(scaling * (xmax - xmin), scaling * (ymax - ymin))));
auto make_svgPoint = [&] (const typename TMesh::Point& p) {
return svg::Point(scaling * (p[0] - xmin),
scaling * (p[1] - ymin));
};
auto int2str = [](int i) {
std::stringstream ss;
ss << i;
return ss.str();
};
for (auto f : mesh.faces()) {
if (mesh.has_face_status() && mesh.status(f).deleted()) continue;
svg::Polygon polygon(svg::Fill(svg::Color::Silver), svg::Stroke(font_stroke_width, svg::Color::Black));
for (auto fv = mesh.cfv_iter(f); fv.is_valid(); ++fv)
polygon << make_svgPoint(mesh.point(*fv));
doc << polygon;
}
svg::Font font(font_size, font_family);
if (draw_vidx) {
for (auto v : mesh.vertices()) {
if (mesh.has_vertex_status() && mesh.status(v).deleted()) continue;
doc << svg::Text(make_svgPoint(mesh.point(v)), int2str(v.idx()), svg::Fill(), font, svg::Stroke(font_stroke_width, svg::Color::Red));
}
}
if (draw_fidx) {
for (auto f : mesh.faces()) {
if (mesh.has_face_status() && mesh.status(f).deleted()) continue;
typename TMesh::Point p;
p.vectorize(0);
int cnt = 0;
for (auto fv = mesh.cfv_iter(f); fv.is_valid(); ++fv) {
p += mesh.point(*fv);
++cnt;
}
p *= 1.0 / cnt;
doc << svg::Text(make_svgPoint(p), int2str(f.idx()), svg::Fill(), font, svg::Stroke(font_stroke_width, svg::Color::Blue));
}
}
if (draw_eidx) {
for (auto e : mesh.edges()) {
if (mesh.has_edge_status() && mesh.status(e).deleted()) continue;
auto p0 = mesh.point(mesh.to_vertex_handle(mesh.halfedge_handle(e, 0)));
auto p1 = mesh.point(mesh.to_vertex_handle(mesh.halfedge_handle(e, 1)));
doc << svg::Text(make_svgPoint((p0 + p1) * 0.5), int2str(e.idx()), svg::Fill(), font, svg::Stroke(1, svg::Color::Brown));
}
}
doc.save();
if (export_pdf) {
std::stringstream command;
command << "inkscape --export-pdf=" << filename << ".pdf " << filename;
FILE* p = popen(command.str().c_str(), "r");
const int BUF_SIZE = 4096;
char buf[BUF_SIZE];
buf[0] = 0;
while (fgets(buf, BUF_SIZE, p) != nullptr) {}
pclose(p);
}
}
}
| [
"sjulin@gmail.com"
] | sjulin@gmail.com |
981a8fbedba3b2b38b6778717cf006506b9adc33 | f730e0181244b8035c0a08f43f3ca157f16c3eed | /admin.cpp | 99f2472c0032df11e15971179c6650ad4055eca1 | [] | no_license | EdelAlan/PurchaseOrderManagementSystem | fc9f062a9d0dd7007f7be578d56cae490ff1628a | 690b9008aceef73b658fed9c4610a6cfdf597be4 | refs/heads/master | 2021-01-01T19:31:24.891290 | 2017-07-28T02:41:42 | 2017-07-28T02:41:42 | 98,600,313 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,311 | cpp | #include <stdio.h>
#include "admin.h"
using namespace std;
void admin::menu() {
std::cout << "Signed as Admin" << std::endl;
std::cout << std::endl;
std::cout << "1. Item Entry" << std::endl;
std::cout << "2. Supplier Entry" << std::endl;
std::cout << "3. Daily Sales Entry" << std::endl;
std::cout << "4. Create a Purchase Requisition" << std::endl;
std::cout << "5. Display Requisitions" << std::endl;
std::cout << "6. Display Purchase Orders" << std::endl;
std::cout << "7. Display Items" << std::endl;
std::cout << "8. Display Suppliers" << std::endl;
std::cout << "9. Register New User" << std::endl;
std::cout << "0. Log out" << std::endl;
int i;
std::cout << "Enter the number: ";
std::cin >> i;
std::cout << std::endl;
if (i == 1) itemEntry();
else if (i == 2) supplierEntry();
else if (i == 3) dailySalesEntry();
else if (i == 4) createPR();
else if (i == 5) displayPRs();
else if (i == 6) displayPOs();
else if (i == 7) displayItems();
else if (i == 8) displaySuppliers();
else if (i == 9) registerUser();
else if (i == 0) logout();
else menu();
}
admin::admin() {}
const std::string &admin::getUsername() const {
return username;
}
const std::string &admin::getPassword() const {
return password;
}
void admin::createPO() {
PurchaseManager::createPO();
menu();
}
void admin::displayItems() {
for (unsigned int i = 0; i < salesManager.getItems()->size(); ++i) {
cout << i + 1 << ". ID - " << salesManager.getItems()->at(i).getId()
<< ". Name - " << salesManager.getItems()->at(i).getName()
<< ". Quantity - " << salesManager.getItems()->at(i).getQuantity()
<< ". Supplier - " << salesManager.getItems()->at(i).getSupplier() << endl;
}
menu();
}
void admin::displaySuppliers() {
for (unsigned int i = 0; i < salesManager.getSuppliers()->size(); ++i) {
cout << i + 1 << ". ID: " << salesManager.getSuppliers()->at(i).getId() << ". Name: "
<< salesManager.getSuppliers()->at(i).getName() << endl;
}
menu();
}
void admin::itemEntry() {
cout << "Item Entry Menu" << endl;
cout << endl;
cout << "1. Add Item" << endl;
cout << "2. Delete Item" << endl;
cout << "3. Edit Item" << endl;
cout << "0. Exit to Main Menu" << endl;
int i;
cout << "Enter the number: ";
cin >> i;
if (i == 1) addItem();
else if (i == 2) deleteItem();
else if (i == 3) editItem();
else if (i == 0) menu();
else itemEntry();
}
void admin::addItem() {
SalesManager::addItem();
}
void admin::deleteItem() {
SalesManager::deleteItem();
}
void admin::editItem() {
SalesManager::editItem();
}
void admin::supplierEntry() {
cout << "Supplier Entry Menu" << endl;
cout << endl;
cout << "1. Add Supplier" << endl;
cout << "2. Delete Supplier" << endl;
cout << "3. Edit Supplier" << endl;
cout << "0. Exit to Main Menu" << endl;
int i;
cout << "Enter the number: ";
cin >> i;
if (i == 1) addSupplier();
else if (i == 2) deleteSupplier();
else if (i == 3) editSupplier();
else if (i == 0) menu();
else supplierEntry();
}
void admin::addSupplier() {
SalesManager::addSupplier();
}
void admin::deleteSupplier() {
SalesManager::deleteSupplier();
}
void admin::editSupplier() {
SalesManager::editSupplier();
}
void admin::dailySalesEntry() {
int id;
int quantity;
cout << "Daily Sales Entry Menu" << endl;
cout << endl;
cout << "Enter id: " << endl;
cin >> id;
cout << "Enter quantity: " << endl;
cin >> quantity;
int choose;
for (unsigned int i = 0; i < items->size(); ++i) {
cout << i + 1 << ". ID - " << items->at(i).getId()
<< ". Name - " << items->at(i).getName()
<< ". Quantity - " << items->at(i).getQuantity()
<< ". Supplier - " << items->at(i).getSupplier() << endl;
}
cout << endl;
cout << "Enter item's number: ";
cin >> choose;
cout << endl;
if (quantity < 0) {
cout << "Wrong input" << endl;
menu();
} else {
items->at(choose - 1).setQuantity(items->at(choose - 1).getQuantity() - quantity);
cout << "Item - " << items->at(choose - 1).getName() << endl
<< "New quantity - " << items->at(choose - 1).getQuantity() << endl;
}
DailyItemWise *dailyItemWise = new DailyItemWise(id, quantity);
dailyItemWises->push_back(*dailyItemWise);
menu();
}
void admin::createPR() {
SalesManager::createPR();
menu();
}
void admin::displayPRs() {
for (unsigned int i = 0; i < purchaseRequisitions->size(); ++i) {
cout << endl
<< endl << "Purchase Requisition ID - " << purchaseRequisitions->at(i).getId()
<< endl << "Item - ID" << purchaseRequisitions->at(i).getItem()
<< endl << "Quantity asked - " << purchaseRequisitions->at(i).getNeededQuantity()
<< endl << "Created by Sales Manager - ID" << purchaseRequisitions->at(i).getSalesManager() << endl;
}
menu();
}
void admin::displayPOs() {
for (unsigned int i = 0; i < purchaseOrders->size(); ++i) {
cout << endl
<< endl << "Purchase Order ID - " << purchaseOrders->at(i).getID()
<< endl << "Purchase Requisition ID - " << purchaseOrders->at(i).getPrID()
<< endl << "Approved by Purchase Manager - ID" << purchaseOrders->at(i).getPurchaseManager();
}
menu();
}
void admin::logout() {
login();
}
void admin::registerUser() {
std::cout << "Register Menu" << std::endl;
std::cout << std::endl;
std::cout << "1. Register Sales Manager" << std::endl;
std::cout << "2. Register Purchase Manager" << std::endl;
std::cout << "0. Menu" << std::endl;
int i;
std::cout << "Enter the number: ";
std::cin >> i;
std::cout << std::endl;
if (i == 1) registerSm();
else if (i == 2) registerPm();
else menu();
}
void admin::registerPm() {
std::string null = "0";
int id;
std::string name;
std::string password;
std::cout << std::endl;
std::cout << "Enter Purchase Manager's ID, enter 0 to exit: ";
std::cin >> id;
if (id == 0) { registerUser(); }
else {
for (unsigned int i = 0; i < purchaseManagers->size(); ++i) {
if (purchaseManagers->at(i).getId() == id) {
std::cout << std::endl << " Purchase Manager with such Id already exists" << std::endl;
registerUser();
break;
} else continue;
}
std::cout << std::endl;
std::cout << "Enter Purchase Manager's name, enter 0 to exit: ";
std::cin >> name;
if (name == null) { registerUser(); }
else {
for (unsigned int i = 0; i < purchaseManagers->size(); ++i) {
if (purchaseManagers->at(i).getName() == name) {
std::cout << " Purchase Manager with such name already exists" << std::endl;
registerUser();
break;
} else continue;
}
std::cout << "Create password: ";
std::cin >> password;
std::cout << std::endl;
PurchaseManager *purchaseManager = new PurchaseManager(id, name, password);
purchaseManagers->push_back(*purchaseManager);
std::cout << std::endl << "New Purchase Manager was saved"
<< std::endl << "ID: " << id
<< std::endl << "Name: " << name << std::endl;
registerUser();
}
}
}
void admin::registerSm() {
std::string null = "0";
int id;
std::string name;
std::string password;
std::cout << std::endl;
std::cout << "Enter Sales Manager's ID, enter 0 to exit: ";
std::cin >> id;
if (id == 0) { registerUser(); }
else {
for (unsigned int i = 0; i < salesManagers->size(); ++i) {
if (salesManagers->at(i).getId() == id) {
std::cout << std::endl << " Sales Manager with such Id already exists" << std::endl;
registerUser();
break;
} else continue;
}
std::cout << std::endl;
std::cout << "Enter Sales Manager's name, enter 0 to exit: ";
std::cin >> name;
if (name == null) { registerUser(); }
else {
for (unsigned int i = 0; i < salesManagers->size(); ++i) {
if (salesManagers->at(i).getName() == name) {
std::cout << " Sales Manager with such name already exists" << std::endl;
registerUser();
break;
} else continue;
}
std::cout << "Create password: ";
std::cin >> password;
std::cout << std::endl;
SalesManager *salesManager = new SalesManager(id, name, password);
salesManagers->push_back(*salesManager);
std::cout << std::endl << "New Sales Manager was saved"
<< std::endl << "ID: " << id
<< std::endl << "Name: " << name << std::endl;
registerUser();
}
}
}
void admin::login() {
std::string username;
std::string password;
std::cout << std::endl << "Login Menu" << std::endl;
std::cout << "Enter username: ";
std::cin >> username;
std::cout << "Enter password: ";
std::cin >> password;
if (username == this->getUsername() && password == this->getPassword()) {
this->menu();
}
for (unsigned int i = 0; i < purchaseManagers->size(); ++i) {
if (username == purchaseManagers->at(i).getName() && password == purchaseManagers->at(i).getPassword()) {
purchaseManagers->at(i).menu();
}
}
for (unsigned int i = 0; i < salesManagers->size(); ++i) {
if (username == salesManagers->at(i).getName() && password == salesManagers->at(i).getPassword()) {
salesManagers->at(i).menu();
} else if (username == this->getUsername() && password == this->getPassword()) {
this->menu();
}
}
std::cout << "wrong input" << std::endl;
login();
}
| [
"my.magic@mail.ru"
] | my.magic@mail.ru |
b803bcb0f8dd44db80198fbb85549ec464fec015 | 0f7a4119185aff6f48907e8a5b2666d91a47c56b | /sstd_utility/windows_boost/boost/unordered/detail/fwd.hpp | 27978bd932a7ec830ef5cbe353737a16074d9068 | [] | no_license | jixhua/QQmlQuickBook | 6636c77e9553a86f09cd59a2e89a83eaa9f153b6 | 782799ec3426291be0b0a2e37dc3e209006f0415 | refs/heads/master | 2021-09-28T13:02:48.880908 | 2018-11-17T10:43:47 | 2018-11-17T10:43:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,975 | hpp |
// Copyright (C) 2008-2016 Daniel James.
// 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 BOOST_UNORDERED_FWD_HPP_INCLUDED
#define BOOST_UNORDERED_FWD_HPP_INCLUDED
#include <boost/config.hpp>
#if defined(BOOST_HAS_PRAGMA_ONCE)
#pragma once
#endif
#include <boost/predef.h>
#if defined(BOOST_UNORDERED_HAVE_PIECEWISE_CONSTRUCT)
// Already defined.
#elif defined(BOOST_LIBSTDCXX11)
// https://github.com/gcc-mirror/gcc/blob/gcc-4_6-branch/libstdc++-v3/include/bits/stl_pair.h#L70
#if BOOST_LIBSTDCXX_VERSION > 40600
#define BOOST_UNORDERED_HAVE_PIECEWISE_CONSTRUCT 1
#endif
#elif BOOST_LIB_STD_CXX
// https://github.com/llvm-mirror/libcxx/blob/release_30/include/utility#L206
#if BOOST_LIB_STD_CXX >= BOOST_VERSION_NUMBER(3, 0, 0)
#define BOOST_UNORDERED_HAVE_PIECEWISE_CONSTRUCT 1
#endif
#elif defined(BOOST_LIB_STD_DINKUMWARE)
// Apparently C++11 standard supported in Visual Studio 2012
// https://msdn.microsoft.com/en-us/library/hh567368.aspx#stl
// 2012 = VC+11 = BOOST_MSVC 1700 Hopefully!
// I have no idea when Dinkumware added it, probably a lot
// earlier than this check.
#if BOOST_LIB_STD_DINKUMWARE >= BOOST_VERSION_NUMBER(6, 50, 0) || \
BOOST_COMP_MSVC >= BOOST_VERSION_NUMBER(17, 0, 0)
#define BOOST_UNORDERED_HAVE_PIECEWISE_CONSTRUCT 1
#endif
#endif
// Assume that an unknown library does not support piecewise construction.
#if !defined(BOOST_UNORDERED_HAVE_PIECEWISE_CONSTRUCT)
#define BOOST_UNORDERED_HAVE_PIECEWISE_CONSTRUCT 0
#endif
#if BOOST_UNORDERED_HAVE_PIECEWISE_CONSTRUCT
#include <utility>
#endif
namespace boost {
namespace unordered {
#if BOOST_UNORDERED_HAVE_PIECEWISE_CONSTRUCT
using std::piecewise_construct_t;
using std::piecewise_construct;
#else
struct piecewise_construct_t
{
};
const piecewise_construct_t piecewise_construct = piecewise_construct_t();
#endif
}
}
#endif
| [
"nanguazhude@vip.qq.com"
] | nanguazhude@vip.qq.com |
0fd85692c4b1ad5719c87a96bac8ab6ca55da0b1 | 3680fc5ba33cea0fbaf0bd7f686569370059359a | /worker/main.cpp | 0aa2b03d63c74beb6d9a258c5d1c155dd558d4cc | [] | no_license | recheal-zhang/fifo | bca3044b0487ef4c806f1a46a5b1e3891f53773e | ea30e955f3768670882a49310a82ed0b5379ed90 | refs/heads/master | 2021-06-16T03:07:06.477311 | 2017-04-26T01:49:29 | 2017-04-26T01:49:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 799 | cpp | #include <unistd.h>
#include <iostream>
#include <string>
#include "Util.h"
#include "Define.h"
#include "Fifo.h"
#include "Epoll.h"
using namespace std;
int main(){
cout << "hello worker" << endl;
std::string fifoClientName =
CUtil::getFifoName(WORKER_1_KEY);
CFifo fifoSend(fifoClientName.c_str());
int fd = open(fifoClientName.c_str(),
O_WRONLY,
0);
char msg[5] = "1234";
CUtil::writeMsgToFifo(fd, msg, 5);
Epoll workerEpoll;
std::string fifoServerName =
CUtil::getFifoName(MASTER_1_KEY);
workerEpoll.addFifoWriteFdInfo(fd);
workerEpoll.addFifoFdFromServer(
CUtil::openfileReadonlyNonblock(
fifoServerName.c_str()));
workerEpoll.monitor();
return 0;
}
| [
"zhanglichao0331@163.com"
] | zhanglichao0331@163.com |
4878fdb76b5859886e438583c7ef5b5e13a15cbf | eb2f8b3271e8ef9c9b092fcaeff3ff8307f7af86 | /Grade 10-12/2018 autumn/NOIP/NOIP2018提高组Day2程序包/answers/GD-0014/travel/travel.cpp | 96532cbf32bb1f23f8954a9452fdd533290e70c0 | [] | no_license | Orion545/OI-Record | 0071ecde8f766c6db1f67b9c2adf07d98fd4634f | fa7d3a36c4a184fde889123d0a66d896232ef14c | refs/heads/master | 2022-01-13T19:39:22.590840 | 2019-05-26T07:50:17 | 2019-05-26T07:50:17 | 188,645,194 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,374 | cpp | #include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int N = 5005;
int n, m, dfsq[2 * N], dfn[N], list[N], cnt = 0;
struct edge
{
int from, to, next;
void add(int x, int y) {
from = x; to = y;
next = list[x]; list[x] = cnt;
}
} e[2 * N];
struct node {
int num;
bool operator < (const node &x) const {
return num > x.num;
}
};
typedef priority_queue<node> pq;
pq a[N];
bool v[N];
int ans[N], curr[N];
void minn() {
bool flag = false;
for(int i = 1; i <= n; i++) {
if (flag) ans[i] = curr[i];
else if (curr[i] < ans[i]) {
flag = true;
ans[i] = curr[i];
} else if (curr[i] > ans[i]) {
return;
}
}
}
void dfs(int x, int sum) {
}
void print(int x) {
v[x] = 1;
printf("%d ", x);
while(! a[x].empty()) {
node tmp = a[x].top();
int y = tmp.num;
a[x].pop();
if (! v[y]) {
print(y);
}
}
}
void print1() {
for (int i = 1; i <= n; i++) {
printf("%d ", ans[i]);
}
}
int main () {
freopen("travel.in", "r", stdin);
freopen("travel.out", "w", stdout);
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; i++) {
int x, y;
scanf("%d%d", &x, &y);
node tmp;
tmp.num = y;
a[x].push(tmp);
tmp.num = x;
a[y].push(tmp);
e[++cnt].add(x, y);
e[++cnt].add(y, x);
}
if (m == n - 1) {
print(1);
} else if (m == n) {
dfs(1, 0);
print1();
}
fclose(stdin); fclose(stdout);
return 0;
}
| [
"orion545@qq.com"
] | orion545@qq.com |
5ffb44c96596a9d4957ed49c296e5adca57ed302 | 592490cd67944e3d2e777de130e5e5a121ef2dca | /module04/ex01/AWeapon.hpp | c98861c4b8b60ce18f72b4d4bd942e10e3437c78 | [] | no_license | VictorTennekes/CPP_Piscine | 322b0298755cf16c1387fc155c0ea082f6ce163f | fad40c86c0fe67d5a151e72b26685c42f4e07460 | refs/heads/master | 2023-01-01T17:46:20.249434 | 2020-10-22T09:53:09 | 2020-10-22T09:53:09 | 291,345,452 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,374 | hpp | /* ************************************************************************** */
/* */
/* :::::::: */
/* AWeapon.hpp :+: :+: */
/* +:+ */
/* By: vtenneke <vtenneke@student.codam.nl> +#+ */
/* +#+ */
/* Created: 2020/08/04 15:55:49 by vtenneke #+# #+# */
/* Updated: 2020/08/04 15:55:49 by vtenneke ######## odam.nl */
/* */
/* ************************************************************************** */
#ifndef AWEAPON_HPP
# define AWEAPON_HPP
# include <string>
class AWeapon {
public:
AWeapon(std::string const &name, int apcost, int damage);
AWeapon(const AWeapon &src);
AWeapon &operator=(const AWeapon &weapon);
virtual ~AWeapon();
std::string const &getName() const;
int getAPCost() const;
int getDamage() const;
virtual void attack() const = 0;
protected:
std::string _name;
int _apCost;
int _damage;
private:
AWeapon();
};
#endif
| [
"victor@tennekes.nl"
] | victor@tennekes.nl |
f9e49a693614c9e0107e9cbf5c2751b65dd0a009 | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14699/function14699_schedule_30/function14699_schedule_30_wrapper.cpp | d14ce7e376b2a21490105cbf2accf64336b29dc3 | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 933 | cpp | #include "Halide.h"
#include "function14699_schedule_30_wrapper.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <fstream>
#include <chrono>
#define MAX_RAND 200
int main(int, char **){
Halide::Buffer<int32_t> buf00(256, 256, 512);
Halide::Buffer<int32_t> buf0(256, 256, 512);
init_buffer(buf0, (int32_t)0);
auto t1 = std::chrono::high_resolution_clock::now();
function14699_schedule_30(buf00.raw_buffer(), buf0.raw_buffer());
auto t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = t2 - t1;
std::ofstream exec_times_file;
exec_times_file.open("../data/programs/function14699/function14699_schedule_30/exec_times.txt", std::ios_base::app);
if (exec_times_file.is_open()){
exec_times_file << diff.count() * 1000000 << "us" <<std::endl;
exec_times_file.close();
}
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
7fe86cdbd85130cde70c881e178f255ff74240f0 | d741c1b64758eec7a7619dfce0ebf7015bcd4675 | /ekbase/base/sessionmanager.cpp | 555f7b58799339c02d609ff6adbd59e2853076e2 | [
"MIT"
] | permissive | maat2019/exkit | ebc4def068efb98c594dacc3013893b06a0d36d2 | 18d71e84d688060f0c30af456dcbec5252ebbdac | refs/heads/master | 2022-01-25T12:05:08.042818 | 2019-05-20T10:00:20 | 2019-05-20T10:00:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 461 | cpp | #include "sessionmanager.h"
#include "holder.h"
SessionManager::SessionManager(Holder *hld)
: hld(hld), session()
{
}
SessionManager::~SessionManager()
{
}
Session SessionManager::GetSession()
{
std::lock_guard<std::mutex> lock(mtx);
if (session.sessId == 0)
LOGW("SessMan has no session");
return session;
}
void SessionManager::Update(Session &session)
{
std::lock_guard<std::mutex> lock(mtx);
this->session = session;
}
| [
"artintexo@yandex.ru"
] | artintexo@yandex.ru |
1615f37d81f147a8ecc9820d9625355300c8fe66 | 53aaac390ce455b4039aa0e68375885adae99111 | /Array/reverse_array.cpp | 99a482c66b0067cb006446ae548941682bba5e7f | [] | no_license | devesh-iitism/Data-Structures | 419bd41207d58edf23d72f946a080be5b32f3e21 | 8c955fc2a55f8ef01b17b3fc3d5fdbc39bc06ae3 | refs/heads/master | 2023-05-14T11:19:29.099647 | 2021-06-08T02:03:41 | 2021-06-08T02:03:41 | 368,142,197 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 499 | cpp | #include<bits/stdc++.h>
#define pb push_back
using namespace std;
int main()
{
int n; cin>>n;
vector<int> arr(n, 0);
for(int i=0;i<n;i++) {
cin>>arr[i];
}
cout<<"Before: ";
for(int i=0;i<n;i++) {
cout<<arr[i]<<" ";
}
cout<<"\n";
int l = 0, r = n-1;
while(l<r) {
swap(arr[l], arr[r]);
l++;
r--;
}
cout<<"After: ";
for(int i=0;i<n;i++) {
cout<<arr[i]<<" ";
}
cout<<"\n";
return 0;
} | [
"dcdev001@gmail.com"
] | dcdev001@gmail.com |
806accfbc483f5c0c17301747d9de7c5caffb20a | 41d0aee2205d1d1d244faf6b72bae5b48d3839af | /testsuites/unittest/posix/mqueue/full/It_posix_queue_150.cpp | 6852a595d460782605c8a3ba45550a54662ae954 | [
"BSD-3-Clause"
] | permissive | SunnyLy/kernel_liteos_a_note | 75d2df014abce78e85722406331343832f74cec4 | 9c54aa38d2330b365e55e5feff1f808c3b6dba25 | refs/heads/master | 2023-08-19T13:15:21.905929 | 2021-10-22T09:26:15 | 2021-10-22T09:26:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,077 | cpp | /*
* Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "It_posix_queue.h"
static UINT32 Testcase(VOID)
{
INT32 ret;
const CHAR *msgptr = MQUEUE_SEND_STRING_TEST;
CHAR msgrcd[MQUEUE_STANDARD_NAME_LENGTH] = {0};
CHAR mqname[MQUEUE_STANDARD_NAME_LENGTH] = "";
mqd_t mqueue;
struct mq_attr attr = { 0 };
attr.mq_msgsize = MQUEUE_STANDARD_NAME_LENGTH;
attr.mq_maxmsg = MQUEUE_STANDARD_NAME_LENGTH;
snprintf(mqname, MQUEUE_STANDARD_NAME_LENGTH, "/mq150_%d", LosCurTaskIDGet());
mqueue = mq_open(mqname, O_CREAT | O_RDWR | O_NONBLOCK, S_IRUSR | S_IWUSR, &attr);
ICUNIT_GOTO_NOT_EQUAL(mqueue, (mqd_t)-1, mqueue, EXIT1);
ret = mq_send((mqd_t)(-1), msgptr, strlen(msgptr), 0);
ICUNIT_GOTO_EQUAL(ret, MQUEUE_IS_ERROR, ret, EXIT1);
ICUNIT_GOTO_EQUAL(errno, EBADF, errno, EXIT1);
ret = mq_receive(mqueue, msgrcd, MQUEUE_STANDARD_NAME_LENGTH, NULL);
ICUNIT_GOTO_EQUAL(ret, MQUEUE_IS_ERROR, ret, EXIT1);
ICUNIT_GOTO_EQUAL(errno, EAGAIN, errno, EXIT1);
ret = mq_close(mqueue);
ICUNIT_GOTO_EQUAL(ret, MQUEUE_NO_ERROR, ret, EXIT1);
ret = mq_unlink(mqname);
ICUNIT_GOTO_EQUAL(ret, MQUEUE_NO_ERROR, ret, EXIT);
return MQUEUE_NO_ERROR;
EXIT1:
mq_close(mqueue);
EXIT:
mq_unlink(mqname);
return MQUEUE_NO_ERROR;
}
VOID ItPosixQueue150(VOID) // IT_Layer_ModuleORFeature_No
{
TEST_ADD_CASE("IT_POSIX_QUEUE_150", Testcase, TEST_POSIX, TEST_QUE, TEST_LEVEL2, TEST_FUNCTION);
}
| [
"kuangyufei@126.com"
] | kuangyufei@126.com |
6c977ef5923ba58dd6d462db9ad547674fe15754 | d0a3edcc3172d5d60b43776cd36bcc51027a3d77 | /delete Node Recursively.cpp | 8b2b41f0e41ee631a58380b8f05ac97a7578151f | [] | no_license | Sanchitgoyal2000/Singly-Linked-List | b2b4ddabc1d8b7b7a5c644e9c02b628ad9f24201 | 32aa172a6e0fd3b9406fed75c167fb12c9f28d35 | refs/heads/master | 2020-07-01T13:04:54.754825 | 2020-03-28T06:41:16 | 2020-03-28T06:41:16 | 201,184,082 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 297 | cpp | struct Node* recursivedelete(struct Node *head,int p)
{
if(p<1)
return head;
if(p==1)
{
struct Node *temp1=(struct Node*)malloc(sizeof(struct Node));
temp1=head->next;
free(head);
return temp1;
}
head->next=recursivedelete(head->next,p-1);
return head;
}
| [
"noreply@github.com"
] | Sanchitgoyal2000.noreply@github.com |
ea0627d8876c11909807b564cf1f701253e0c9b0 | 2511b9066113f8c1e9cb18b6943094616e15fea0 | /WinrtApp/MainPage.cpp | feff90adc31e4920d70f9a08e46244ce2c897c07 | [] | no_license | wcj233/StaticLibraryWinrt | d3af71cf16ba7a1d0b4a5a355c2b114ec79cff31 | 2047eeea2d522bfe8bfcf14e0d71a7d6ca12fbc7 | refs/heads/master | 2022-11-13T16:38:09.622454 | 2020-06-23T08:32:41 | 2020-06-23T08:32:41 | 274,352,115 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 666 | cpp | #include "pch.h"
#include "MainPage.h"
#include "MainPage.g.cpp"
#include <winrt/StaticLibrary1.h>
using namespace winrt;
using namespace Windows::UI::Xaml;
namespace winrt::WinrtApp::implementation
{
MainPage::MainPage()
{
InitializeComponent();
}
int32_t MainPage::MyProperty()
{
throw hresult_not_implemented();
}
void MainPage::MyProperty(int32_t /* value */)
{
throw hresult_not_implemented();
}
void MainPage::ClickHandler(IInspectable const&, RoutedEventArgs const&)
{
myButton().Content(box_value(L"Clicked"));
StaticLibrary1::Class aa;
aa.showP1();
}
}
| [
"v-faywan@microsoft.com"
] | v-faywan@microsoft.com |
db70e704e4eea6851082831a8adf627f62db575c | c2bbe165858014ea7fd226710fa3dc1f4af36fe8 | /src/locMatrix.cpp | 69877a4fda10ece5f6a3539e6b69e2799fcd89cc | [] | no_license | tonymugen/GWAlikeMeth | 5781bb71e0ac79d6772d405a025f4379a52453cc | 8245a7224ba4253681f54aaedd17a60b4520bedf | refs/heads/master | 2020-04-16T00:34:56.464885 | 2020-01-31T22:28:18 | 2020-01-31T22:28:18 | 165,144,017 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 59,218 | cpp | /*
* Copyright (c) 2016 Anthony J. Greenberg
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
/// C++ matrix class for development.
/** \file
* \author Anthony J. Greenberg
* \copyright Copyright (c) 2016 Anthony J. Greenberg
* \version 0.1
*
* This is the class implementation file for the experimental Matrix class. This version is for including in R packages, so it uses the R BLAS and LAPACK interfaces.
*
*
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <climits>
#include <utility>
#include <R_ext/Lapack.h>
#include <R_ext/BLAS.h>
#include "locMatrix.hpp"
#include "random.hpp"
using std::endl;
using std::flush;
using std::ofstream;
using std::ifstream;
using std::stringstream;
using std::ios;
using std::vector;
using std::string;
using std::stod;
using std::fill;
using std::memcpy;
using std::nan;
using std::numeric_limits;
using namespace BayesicSpace;
// Friend functions
Matrix BayesicSpace::operator*(const double &scal, const Matrix &m){
Matrix res(m);
for (size_t iElm = 0; iElm < m.Ncol_*m.Nrow_; iElm++) {
res.data_[iElm] *= scal;
}
return res;
}
Matrix BayesicSpace::operator+(const double &scal, const Matrix &m){
Matrix res(m);
for (size_t iElm = 0; iElm < m.Ncol_*m.Nrow_; iElm++) {
res.data_[iElm] += scal;
}
return res;
}
// Matrix methods
Matrix::Matrix(const size_t &nrow, const size_t &ncol) : Nrow_(nrow), Ncol_(ncol) { // not using uniform initialization list because Xcode code completion goes nuts
if ( (Nrow_ > INT_MAX) || (Ncol_ > INT_MAX) ) {
throw string("ERROR: Matrix dimensions exceed INT_MAX in Matrix initializing constructor");
}
size_t Ntot = Nrow_ * Ncol_;
if (!Ntot) { // one of the dimensions is zero
throw string("ERROR: one of the dimensions is 0 in the Matrix initializing constructor");
}
if ((Ntot < Nrow_) || (Ntot < Ncol_)) { // this happens only if there is wrap-around
throw string("ERROR: dimensions are too large resulting in wrap-around in the Matrix initializing constructor");
}
data_ = new double[Ntot];
}
// Using the C++-11 delegating constructor facility
Matrix::Matrix(const double &val, const size_t &nrow, const size_t &ncol) : Matrix(nrow, ncol) {
size_t Ntot = Nrow_ * Ncol_;
fill(data_, data_ + Ntot, val);
}
Matrix::Matrix(const double inArr[], const size_t &nrow, const size_t &ncol) : Matrix(nrow, ncol) {
size_t Ntot = Nrow_ * Ncol_;
memcpy(data_, inArr, Ntot*sizeof(*inArr));
}
Matrix::Matrix(const vector<double> &inVec, const size_t &nrow, const size_t &ncol) : Matrix(nrow, ncol) {
size_t Ntot = Nrow_ * Ncol_;
if (inVec.size() < Ntot){
throw string("ERROR: input vector is not long enough in the Matrix vector-based constructor");
}
memcpy(data_, inVec.data(), Ntot*sizeof(double));
}
Matrix::Matrix(const string &fileName, const char &delim): Nrow_(0), Ncol_(0) {
ifstream matIn(fileName.c_str());
if (!matIn) {
string errMsg = "ERROR: cannot open file " + fileName + " in Matrix constructor from file";
throw errMsg;
}
// Copy all the lines into a vector of strings.
// Cannot assign the values to the data_ array on the fly because I need to know the dimensions to allocate the data_ array.
vector<string> lines;
string currentElem;
while (getline(matIn, currentElem)){
lines.push_back(currentElem);
}
matIn.close();
Nrow_ = lines.size();
if (Nrow_ == 0) {
string errMsg = "ERROR: no rows in the file " + fileName + "ERROR: no rows in the file";
throw errMsg;
}
// going through the first line is enough to establish
vector<double> firstLine;
stringstream lineStream;
lineStream.str(lines[0]);
while (getline(lineStream, currentElem, delim)) {
firstLine.push_back(stod(currentElem));
}
lineStream.str("");
Ncol_ = firstLine.size();
if (Ncol_ == 0) {
string errMsg = "ERROR: no rows in the file " + fileName + " in Matrix constructor from file";
throw errMsg;
}
size_t Ntot = Ncol_ * Nrow_;
if ((Ntot < Nrow_) || (Ntot < Ncol_)) { // this happens only if there is wrap-around
throw string("ERROR: dimensions are too large resulting in wrap-around in the Matrix constructor from file");
}
data_ = new double[Ntot];
size_t jCol = 0;
for (auto &iFL : firstLine) {
data_[Nrow_*jCol] = iFL; // just the first row
jCol++;
}
firstLine.resize(0);
// now go through the rest of the lines
size_t iRow = 1;
for (auto lnIt = lines.begin() + 1; lnIt != lines.end(); ++lnIt) {
stringstream elemStrm;
elemStrm.str(*lnIt);
jCol = 0;
while (getline(elemStrm, currentElem, delim)) {
data_[Nrow_*jCol + iRow] = stod(currentElem);
jCol++;
}
iRow++;
if (jCol != Ncol_) {
string errMsg = "ERROR: in file " + fileName + " not all lines have the same number of columns (Matrix constructor from file)";
throw errMsg;
}
}
}
Matrix::~Matrix(){
delete [] data_;
data_ = nullptr;
Ncol_ = 0;
Nrow_ = 0;
}
Matrix::Matrix(const Matrix &inMat){
Ncol_ = inMat.Ncol_;
Nrow_ = inMat.Nrow_;
if (Ncol_ && Nrow_) {
data_ = new double[Nrow_ * Ncol_];
memcpy(data_, inMat.data_, (Ncol_ * Nrow_)*sizeof(double));
} else {
data_ = nullptr;
}
}
Matrix& Matrix::operator=(const Matrix &inMat){
if (this != &inMat) {
delete [] data_;
Ncol_ = inMat.Ncol_;
Nrow_ = inMat.Nrow_;
if (Ncol_ && Nrow_) {
data_ = new double[Nrow_ * Ncol_];
memcpy(data_, inMat.data_, (Ncol_ * Nrow_)*sizeof(double));
} else {
data_ = nullptr;
}
}
return *this;
}
Matrix::Matrix(Matrix &&inMat) {
data_ = inMat.data_;
Ncol_ = inMat.Ncol_;
Nrow_ = inMat.Nrow_;
inMat.data_ = nullptr;
inMat.Ncol_ = 0;
inMat.Nrow_ = 0;
}
Matrix& Matrix::operator=(Matrix &&inMat){
if (this != &inMat) {
delete [] data_;
data_ = inMat.data_;
Ncol_ = inMat.Ncol_;
Nrow_ = inMat.Nrow_;
inMat.data_ = nullptr;
inMat.Ncol_ = 0;
inMat.Nrow_ = 0;
}
return *this;
}
double Matrix::getElem(const size_t& iRow, const size_t &jCol) const{
#ifndef LMRG_CHECK_OFF
if ((iRow >= Nrow_) || (jCol >= Ncol_)) {
throw string("ERROR: element out of range in getElem()");
}
#endif
return data_[Nrow_*jCol + iRow];
}
void Matrix::setElem(const size_t& iRow, const size_t &jCol, const double &input){
#ifndef LMRG_CHECK_OFF
if ((iRow >= Nrow_) || (jCol >= Ncol_)) {
throw string("ERROR: element out of range in setElem()");
}
#endif
data_[Nrow_*jCol + iRow] = input;
}
void Matrix::setCol(const size_t jCol, const vector<double> data){
#ifndef LMRG_CHECK_OFF
if (jCol >= Ncol_) {
throw string("ERROR: column index out of range in setCol()");
}
if (data.size() < Nrow_) {
throw string("ERROR: vector length smaller than the number of rows in setCol()");
}
#endif
double *colBeg = data_ + jCol*Nrow_;
memcpy(colBeg, data.data(), Nrow_*sizeof(double));
}
void Matrix::resize(const size_t &nrow, const size_t &ncol){
delete [] data_;
Nrow_ = nrow;
Ncol_ = ncol;
if (Ncol_ && Nrow_) {
data_ = new double[Nrow_ * Ncol_]();
} else {
data_ = nullptr;
}
}
void Matrix::save(const string &outFileName) const {
remove(outFileName.c_str());
ofstream outFl(outFileName.c_str(), ios::app);
if (!outFl) {
string errMsg = "ERROR: cannot open file " + outFileName + " for writing to save Matrix";
throw errMsg;
}
if ((Nrow_ == 0) || (Ncol_ == 0)) {
outFl.close();
return;
}
for (size_t iRow = 0; iRow < Nrow_; iRow++) {
// first element
outFl << data_[iRow] << flush;
for (size_t jCol = 1; jCol < Ncol_; jCol++) {
outFl << "\t" << data_[Nrow_*jCol + iRow] << flush;
}
outFl << endl;
}
outFl.close();
}
void Matrix::vectorize(vector<double> &out) const {
out.resize(Nrow_*Ncol_);
memcpy(out.data(), data_, out.size()*sizeof(double));
}
void Matrix::chol(){
#ifndef LMRG_CHECK_OFF
if (Nrow_ != Ncol_) {
throw string("ERROR: matrix has to be symmetric for Cholesky decomposition");
}
if (Nrow_ > INT_MAX) {
throw string("ERROR: matrix dimension too big to safely convert to int in in-place Cholesky decomposition");
}
if ( (Nrow_ == 0) || (Ncol_ == 0) ) {
throw string("ERROR: one of the dimensions is zero");
}
#endif
int info = 0;
char tri = 'L';
int N = static_cast<int>(Nrow_); // conversion should be OK: magnitude of Nrow_ checked in the constructor
dpotrf_(&tri, &N, data_, &N, &info);
if (info < 0) {
throw string("ERROR: illegal element in in-place Cholesky decomposition");
} else if (info > 0) {
throw string("ERROR: matrix is not positive definite in in-place Cholesky decomposition");
}
}
void Matrix::chol(Matrix &out) const {
#ifndef LMRG_CHECK_OFF
if (Nrow_ != Ncol_) {
throw string("ERROR: matrix has to be symmetric for Cholesky decomposition");
}
if ( (Nrow_ == 0) || (Ncol_ == 0) ) {
throw string("ERROR: one of the dimensions is zero");
}
#endif
if ((Nrow_ != out.Nrow_) || (Ncol_ != out.Ncol_)) {
out.resize(Nrow_, Ncol_);
}
memcpy(out.data_, data_, (Nrow_ * Ncol_)*sizeof(double));
int info = 0;
char tri = 'L';
int N = static_cast<int>(Nrow_); // conversion should be safe: Nrow_ magnitude checked during construction
dpotrf_(&tri, &N, out.data_, &N, &info);
if (info < 0) {
throw string("ERROR: illegal matrix element in copy Cholesky decomposition");
} else if (info > 0) {
throw string("ERROR: matrix is not positive definite in copy Cholesky decomposition");
}
}
void Matrix::cholInv(){
#ifndef LMRG_CHECK_OFF
if (Nrow_ != Ncol_) {
throw string("ERROR: matrix has to be symmetric for Cholesky inversion");
}
if ( (Nrow_ == 0) || (Ncol_ == 0) ) {
throw string("ERROR: one of the dimensions is zero");
}
#endif
int info = 0;
char tri = 'L';
int N = static_cast<int>(Nrow_); // conversion should be safe: Nrow_ magnitude checked during construction
dpotri_(&tri, &N, data_, &N, &info);
if (info < 0) {
throw string("ERROR: illegal matrix element in-place Cholesky inversion");
} else if (info > 0) {
throw string("ERROR: a diagonal element of the matrix is zero. Cannot complete in-place Cholesky inversion");
}
// copying the lower triangle to the upper
for (size_t iRow = 0; iRow < Nrow_; iRow++) {
for (size_t jCol = 0; jCol < iRow; jCol++) {
data_[Nrow_*iRow + jCol] = data_[Nrow_*jCol + iRow];
}
}
}
void Matrix::cholInv(Matrix &out) const {
#ifndef LMRG_CHECK_OFF
if (Nrow_ != Ncol_) {
throw string("ERROR: matrix has to be square for Cholesky inversion");
}
if ( (Nrow_ == 0) || (Ncol_ == 0) ) {
throw string("ERROR: one of the dimensions is zero");
}
#endif
if ((Nrow_ != out.Nrow_) || (Ncol_ != out.Ncol_)) {
out.resize(Nrow_, Ncol_);
}
memcpy(out.data_, data_, (Nrow_ * Ncol_)*sizeof(double));
int info = 0;
char tri = 'L';
int N = static_cast<int>(Nrow_); // safe to convert: Nrow_ checked at construction
dpotri_(&tri, &N, out.data_, &N, &info);
if (info < 0) {
throw string("ERROR: illegal matrix element in copy Cholesky inversion");
} else if (info > 0) {
throw string("ERROR: a diagonal element of the matrix is zero. Cannot complete copy Cholesky inversion");
}
for (size_t iRow = 0; iRow < Nrow_; iRow++) {
for (size_t jCol = 0; jCol < iRow; jCol++) {
out.data_[Nrow_*iRow + jCol] = out.data_[Nrow_*jCol + iRow];
}
}
}
void Matrix::svd(Matrix &U, vector<double> &s){
#ifndef LMRG_CHECK_OFF
if ( (Nrow_ == 0) || (Ncol_ == 0) ) {
throw string("ERROR: one of the dimensions is zero");
}
#endif
if ((Nrow_ != U.Nrow_) || (U.Nrow_ != U.Ncol_)) {
U.resize(Nrow_, Nrow_);
}
if (s.size() < Ncol_) {
s.resize(Ncol_, 0.0);
}
int Nvt = 1;
vector<double>vt(1, 0.0);
int resSVD = 0;
int Nw = -1; // set this to pre-run dgesvd_ for calculation of workspace size
vector<double>workArr(1, 0.0);
char jobu = 'A';
char jobvt = 'N';
// the following casts are safe because dimensions are checked at construction
int Nr = static_cast<int>(Nrow_);
int Nc = static_cast<int>(Ncol_);
// first calculate working space
dgesvd_(&jobu, &jobvt, &Nr, &Nc, data_, &Nr, s.data(), U.data_, &Nr, vt.data(), &Nvt, workArr.data(), &Nw, &resSVD);
Nw = workArr[0];
workArr.resize(Nw, 0.0);
dgesvd_(&jobu, &jobvt, &Nr, &Nc, data_, &Nr, s.data(), U.data_, &Nr, vt.data(), &Nvt, workArr.data(), &Nw, &resSVD);
workArr.resize(0);
if (resSVD < 0) {
throw string("ERROR: illegal matrix element in SVD");
} else if (resSVD > 0){
throw string("ERROR: DBDSQR did not converge in SVD");
}
}
void Matrix::svdSafe(Matrix &U, vector<double> &s) const {
#ifndef LMRG_CHECK_OFF
if ( (Nrow_ == 0) || (Ncol_ == 0) ) {
throw string("ERROR: one of the dimensions is zero");
}
#endif
double *dataCopy = new double[Nrow_ * Ncol_];
memcpy(dataCopy, data_, (Nrow_ * Ncol_)*sizeof(double));
if ((Nrow_ != U.Nrow_) || (U.Nrow_ != U.Ncol_)) {
U.resize(Nrow_, Nrow_);
}
if (s.size() < Ncol_) {
s.resize(Ncol_, 0.0);
}
int Nvt = 1;
vector<double>vt(1, 0.0);
int resSVD = 0;
int Nw = -1; // set this to pre-run dgesvd_ for calculation of workspace size
vector<double>workArr(1, 0.0);
char jobu = 'A';
char jobvt = 'N';
// the folloeing casts are safe because the dimensions are checked at construction
int Nr = static_cast<int>(Nrow_);
int Nc = static_cast<int>(Ncol_);
// first calculate working space
dgesvd_(&jobu, &jobvt, &Nr, &Nc, dataCopy, &Nr, s.data(), U.data_, &Nr, vt.data(), &Nvt, workArr.data(), &Nw, &resSVD);
Nw = workArr[0];
workArr.resize(Nw, 0.0);
dgesvd_(&jobu, &jobvt, &Nr, &Nc, dataCopy, &Nr, s.data(), U.data_, &Nr, vt.data(), &Nvt, workArr.data(), &Nw, &resSVD);
workArr.resize(0);
if (resSVD < 0) {
throw string("ERROR: illegal matrix element in safe SVD");
exit(14);
} else if (resSVD > 0){
throw string("ERROR: DBDSQR did not converge in safe SVD");
}
delete [] dataCopy;
}
void Matrix::eigen(const char &tri, Matrix &U, vector<double> &lam){
#ifndef LMRG_CHECK_OFF
if (Nrow_ != Ncol_) {
throw string("ERROR: matrix has to be at least square in eigen()");
}
if ( (Nrow_ == 0) || (Ncol_ == 0) ) {
throw string("ERROR: one of the dimensions is zero");
}
#endif
// test the output size and adjust if necessary
if ((Ncol_ > U.Nrow_) || (Ncol_ > U.Ncol_)) {
U.resize(Ncol_, Ncol_);
}
if (Ncol_ > lam.size()) {
lam.resize(Ncol_, 0.0);
}
char jobz = 'V'; // computing eigenvectors
char range = 'A'; // doing all of them
char uplo;
if (tri == 'u') {
uplo = 'U';
} else if (tri == 'l'){
uplo = 'L';
} else {
throw string("ERROR: unknown triangle indicator in eigen()");
}
// the following casts are safe because Nrow_ magnitude is checked at construction
int N = static_cast<int>(Nrow_);
int lda = static_cast<int>(Nrow_);
// placeholder variables. Not referenced since we are computing all eigenvectors
double vl = 0.0;
double vu = 0.0;
int il = 0;
int iu = 0;
double abstol = sqrt(numeric_limits<double>::epsilon()); // absolute tolerance. Shouldn't be too close to epsilon since I don't need very precise estimation of small eigenvalues
int M = N;
int ldz = N;
vector<int> isuppz(2*M, 0);
vector<double> work(1, 0.0); // workspace; size will be determined
int lwork = -1; // to start; this lets us determine workspace size
vector<int> iwork(1, 0); // integer workspace; size to be calculated
int liwork = -1; // to start; this lets us determine integer workspace size
int info = 0;
dsyevr_(&jobz, &range, &uplo, &N, data_, &lda, &vl, &vu, &il, &iu, &abstol, &M, lam.data(), U.data_, &ldz, isuppz.data(), work.data(), &lwork, iwork.data(), &liwork, &info);
lwork = work[0];
work.resize(static_cast<size_t>(lwork), 0.0);
liwork = iwork[0];
iwork.resize(static_cast<size_t>(liwork), 0);
// run the actual estimation
dsyevr_(&jobz, &range, &uplo, &N, data_, &lda, &vl, &vu, &il, &iu, &abstol, &M, lam.data(), U.data_, &ldz, isuppz.data(), work.data(), &lwork, iwork.data(), &liwork, &info);
// set tiny eigenvalues to exactly zero
for (auto &l : lam) {
if (fabs(l) <= abstol) {
l = 0.0;
}
}
}
void Matrix::eigen(const char &tri, const size_t &n, Matrix &U, vector<double> &lam){
#ifndef LMRG_CHECK_OFF
if (Nrow_ != Ncol_) {
throw string("ERROR: matrix has to be at least square in eigen()");
}
if (Nrow_ < n) {
throw string("ERROR: the input number of eigenvalues greater than matrix dimensions");
}
if ( (Nrow_ == 0) || (Ncol_ == 0) ) {
throw string("ERROR: one of the dimensions is zero");
}
#endif
if (Nrow_ == n) { // if we are doing all of them, just run regular eigen()
Matrix::eigen(tri, U, lam);
return;
}
char jobz = 'V'; // computing eigenvectors
char range = 'I'; // doing some of them
char uplo;
if (tri == 'u') {
uplo = 'U';
} else if (tri == 'l'){
uplo = 'L';
} else {
throw string("ERROR: unknown triangle indicator in eigen()");
}
int N = static_cast<int>(Nrow_);
int lda = static_cast<int>(Nrow_);
// placeholder variables. Not referenced since we are computing a certain number of eigenvectors, not based on the values of the eigenvalues
double vl = 0.0;
double vu = 0.0;
int il = N - static_cast<int>(n) + 1; // looks like the count base-1
int iu = N; // do all the remaining eigenvalues
double abstol = sqrt(numeric_limits<double>::epsilon()); // absolute tolerance. Shouldn't be too close to epsilon since I don't need very precise estimation of small eigenvalues
int M = iu - il + 1;
int ldz = N;
// test the output size and adjust if necessary
if ((Nrow_ > U.Nrow_) || (static_cast<size_t>(M) > U.Ncol_)) {
U.resize(Ncol_, static_cast<size_t>(M));
}
if (static_cast<size_t>(M) > lam.size()) {
lam.resize(static_cast<size_t>(M), 0.0);
}
vector<int> isuppz(2*M, 0);
vector<double> work(1, 0.0); // workspace; size will be determined
int lwork = -1; // to start; this lets us determine workspace size
vector<int> iwork(1, 0); // integer workspace; size to be calculated
int liwork = -1; // to start; this lets us determine integer workspace size
int info = 0;
dsyevr_(&jobz, &range, &uplo, &N, data_, &lda, &vl, &vu, &il, &iu, &abstol, &M, lam.data(), U.data_, &ldz, isuppz.data(), work.data(), &lwork, iwork.data(), &liwork, &info);
lwork = work[0];
work.resize(static_cast<size_t>(lwork), 0.0);
liwork = iwork[0];
iwork.resize(static_cast<size_t>(liwork), 0);
// run the actual estimation
dsyevr_(&jobz, &range, &uplo, &N, data_, &lda, &vl, &vu, &il, &iu, &abstol, &M, lam.data(), U.data_, &ldz, isuppz.data(), work.data(), &lwork, iwork.data(), &liwork, &info);
// set tiny eigenvalues to exactly zero
for (auto &l : lam) {
if (fabs(l) <= abstol) {
l = 0.0;
}
}
}
void Matrix::eigenSafe(const char &tri, Matrix &U, vector<double> &lam){
#ifndef LMRG_CHECK_OFF
if (Nrow_ != Ncol_) {
throw string("ERROR: matrix has to be at least square in eigen()");
}
if ( (Nrow_ == 0) || (Ncol_ == 0) ) {
throw string("ERROR: one of the dimensions is zero");
}
#endif
// test the output size and adjust if necessary
if ((Ncol_ > U.Nrow_) || (Ncol_ > U.Ncol_)) {
U.resize(Ncol_, Ncol_);
}
if (Ncol_ > lam.size()) {
lam.resize(Ncol_, 0.0);
}
char jobz = 'V'; // computing eigenvectors
char range = 'A'; // doing all of them
char uplo;
if (tri == 'u') {
uplo = 'U';
} else if (tri == 'l'){
uplo = 'L';
} else {
throw string("ERROR: unknown triangle indicator in eigen()");
}
int N = static_cast<int>(Nrow_);
int lda = static_cast<int>(Nrow_);
// placeholder variables. Not referenced since we are computing all eigenvectors
double vl = 0.0;
double vu = 0.0;
int il = 0;
int iu = 0;
double abstol = sqrt(numeric_limits<double>::epsilon()); // absolute tolerance. Shouldn't be too close to epsilon since I don't need very precise estimation of small eigenvalues
int M = N;
int ldz = N;
vector<int> isuppz(2*M, 0);
vector<double> work(1, 0.0); // workspace; size will be determined
int lwork = -1; // to start; this lets us determine workspace size
vector<int> iwork(1, 0); // integer workspace; size to be calculated
int liwork = -1; // to start; this lets us determine integer workspace size
int info = 0;
double *dataCopy = new double[Nrow_ * Ncol_];
memcpy(dataCopy, data_, (Nrow_ * Ncol_)*sizeof(double));
dsyevr_(&jobz, &range, &uplo, &N, dataCopy, &lda, &vl, &vu, &il, &iu, &abstol, &M, lam.data(), U.data_, &ldz, isuppz.data(), work.data(), &lwork, iwork.data(), &liwork, &info);
lwork = work[0];
work.resize(static_cast<size_t>(lwork), 0.0);
liwork = iwork[0];
iwork.resize(static_cast<size_t>(liwork), 0);
// run the actual estimation
dsyevr_(&jobz, &range, &uplo, &N, dataCopy, &lda, &vl, &vu, &il, &iu, &abstol, &M, lam.data(), U.data_, &ldz, isuppz.data(), work.data(), &lwork, iwork.data(), &liwork, &info);
delete [] dataCopy;
// set tiny eigenvalues to exactly zero
for (auto &l : lam) {
if (fabs(l) <= abstol) {
l = 0.0;
}
}
}
void Matrix::eigenSafe(const char &tri, const size_t &n, Matrix &U, vector<double> &lam){
#ifndef LMRG_CHECK_OFF
if (Nrow_ != Ncol_) {
throw string("ERROR: matrix has to be at least square in eigen()");
}
if (Nrow_ < n) {
throw string("ERROR: the input number of eigenvalues greater than matrix dimensions");
}
if ( (Nrow_ == 0) || (Ncol_ == 0) ) {
throw string("ERROR: one of the dimensions is zero");
}
#endif
if (Nrow_ == n) { // if we are doing all of them, just run regular eigen()
Matrix::eigenSafe(tri, U, lam);
return;
}
char jobz = 'V'; // computing eigenvectors
char range = 'I'; // doing some of them
char uplo;
if (tri == 'u') {
uplo = 'U';
} else if (tri == 'l'){
uplo = 'L';
} else {
throw string("ERROR: unknown triangle indicator in eigen()");
}
int N = static_cast<int>(Nrow_);
int lda = static_cast<int>(Nrow_);
// placeholder variables. Not referenced since we are computing a certain number of eigenvectors, not based on the values of the eigenvalues
double vl = 0.0;
double vu = 0.0;
int il = N - static_cast<int>(n) + 1; // looks like the count base-1
int iu = N; // do all the remaining eigenvalues
double abstol = sqrt(numeric_limits<double>::epsilon()); // absolute tolerance. Shouldn't be too close to epsilon since I don't need very precise estimation of small eigenvalues
int M = iu - il + 1;
int ldz = N;
// test the output size and adjust if necessary
if ((Nrow_ > U.Nrow_) || (static_cast<size_t>(M) > U.Ncol_)) {
U.resize(Ncol_, static_cast<size_t>(M));
}
if (static_cast<size_t>(M) > lam.size()) {
lam.resize(static_cast<size_t>(M), 0.0);
}
vector<int> isuppz(2*M, 0);
vector<double> work(1, 0.0); // workspace; size will be determined
int lwork = -1; // to start; this lets us determine workspace size
vector<int> iwork(1, 0); // integer workspace; size to be calculated
int liwork = -1; // to start; this lets us determine integer workspace size
int info = 0;
double *dataCopy = new double[Nrow_ * Ncol_];
memcpy(dataCopy, data_, (Nrow_ * Ncol_)*sizeof(double));
dsyevr_(&jobz, &range, &uplo, &N, dataCopy, &lda, &vl, &vu, &il, &iu, &abstol, &M, lam.data(), U.data_, &ldz, isuppz.data(), work.data(), &lwork, iwork.data(), &liwork, &info);
lwork = work[0];
work.resize(static_cast<size_t>(lwork), 0.0);
liwork = iwork[0];
iwork.resize(static_cast<size_t>(liwork), 0);
// run the actual estimation
dsyevr_(&jobz, &range, &uplo, &N, dataCopy, &lda, &vl, &vu, &il, &iu, &abstol, &M, lam.data(), U.data_, &ldz, isuppz.data(), work.data(), &lwork, iwork.data(), &liwork, &info);
delete [] dataCopy;
// set tiny eigenvalues to exactly zero
for (auto &l : lam) {
if (fabs(l) <= abstol) {
l = 0.0;
}
}
}
void Matrix::premultZ(const Matrix &Z){
#ifndef LMRG_CHECK_OFF
if (Z.getNcols() != Nrow_) {
throw string("ERROR: Incompatible dimensions between Z and M in premultZ()");
}
if ( (Nrow_ == 0) || (Ncol_ == 0) ) {
throw string("ERROR: one of the dimensions is zero");
exit(24);
}
#endif
// build the vector that stores all the new row IDs for each old row (represented by columns of Z)
vector< vector<size_t> > fac(Z.getNcols());
for (size_t oldRow = 0; oldRow < Z.getNcols(); oldRow++) {
for (size_t newRow = 0; newRow < Z.getNrows(); newRow++) {
if (Z.getElem(newRow, oldRow) == 1.0) {
fac[oldRow].push_back(newRow);
} else if (Z.getElem(newRow, oldRow) != 0.0) {
throw string("ERROR: design matrix can only have elements 1 or 0 in premultZ()");
}
}
}
double *dataCopy = new double[Nrow_ * Ncol_];
memcpy(dataCopy, data_, (Nrow_ * Ncol_)*sizeof(double));
delete [] data_;
data_ = new double[Z.getNrows() * Ncol_];
for (size_t oldRow = 0; oldRow < Z.getNcols(); oldRow++) {
// going through all the rows of Z that correspond to the old row of M
for (auto &f : fac[oldRow]) {
//copying the row of M
for (size_t jCol = 0; jCol < Ncol_; jCol++) {
data_[Z.getNrows()*jCol + f] = dataCopy[Nrow_*jCol + oldRow];
}
}
}
Nrow_ = Z.getNrows();
delete [] dataCopy;
}
void Matrix::premultZ(const Matrix &Z, Matrix &out) const {
#ifndef LMRG_CHECK_OFF
if (Z.getNcols() != Nrow_) {
throw string("ERROR: Incompatible dimensions between Z and M in premultZ()");
}
if ( (Nrow_ == 0) || (Ncol_ == 0) ) {
throw string("ERROR: one of the dimensions is zero");
}
#endif
// build the vector that stores all the new row IDs for each old row (represented by columns of Z)
vector< vector<size_t> > fac(Z.getNcols());
for (size_t oldRow = 0; oldRow < Z.getNcols(); oldRow++) {
for (size_t newRow = 0; newRow < Z.getNrows(); newRow++) {
if (Z.getElem(newRow, oldRow) == 1.0) {
fac[oldRow].push_back(newRow);
} else if (Z.getElem(newRow, oldRow) != 0.0) {
throw string("ERROR: design matrix can only have elements 1 or 0 in premultZ()");
}
}
}
if ((Z.getNrows() != out.getNrows()) || (Ncol_ != out.getNcols())) {
out.resize(Z.getNrows(), Ncol_);
}
for (size_t oldRow = 0; oldRow < Z.getNcols(); oldRow++) {
// going through all the rows of Z that correspond to the old row of M
for (auto &f : fac[oldRow]) {
// copying the row of M
for (size_t jCol = 0; jCol < Ncol_; jCol++) {
out.data_[Z.getNrows()*jCol + f] = data_[Nrow_*jCol + oldRow];
}
}
}
}
void Matrix::premultZt(const Matrix &Z){
#ifndef LMRG_CHECK_OFF
if (Z.getNrows() != Nrow_) {
throw string("ERROR: Incompatible dimensions between Z and M in premultZt()");
}
if ( (Nrow_ == 0) || (Ncol_ == 0) ) {
throw string("ERROR: one of the dimensions is zero");
}
#endif
// build the vector that stores all the new row IDs for each old row (represented by columns of Z)
vector< vector<size_t> > fac(Z.getNcols());
for (size_t oldRow = 0; oldRow < Z.getNcols(); oldRow++) {
for (size_t newRow = 0; newRow < Z.getNrows(); newRow++) {
if (Z.getElem(newRow, oldRow) == 1.0) {
fac[oldRow].push_back(newRow);
} else if (Z.getElem(newRow, oldRow) != 0.0) {
throw string("ERROR: design matrix can only have elements 1 or 0 in premultZt()");
}
}
}
double *dataCopy = new double[Nrow_ * Ncol_];
memcpy(dataCopy, data_, (Nrow_ * Ncol_)*sizeof(double));
delete [] data_;
data_ = new double[Z.getNcols() * Ncol_](); // value-initializing for summing to work
for (size_t newRow = 0; newRow < Z.getNcols(); newRow++) {
// going through all the rows of Z that correspond to the new (summed) row of M
for (auto &f : fac[newRow]) {
// summing the rows of M within the group defined by rows of Z
for (size_t jCol = 0; jCol < Ncol_; jCol++) {
data_[Z.getNcols()*jCol + newRow] += dataCopy[Nrow_*jCol + f];
}
}
}
Nrow_ = Z.getNcols();
delete [] dataCopy;
}
void Matrix::premultZt(const Matrix &Z, Matrix &out) const {
#ifndef LMRG_CHECK_OFF
if (Z.getNrows() != Nrow_) {
throw string("ERROR: Incompatible dimensions between Z and M in premultZt()");
}
if ( (Nrow_ == 0) || (Ncol_ == 0) ) {
throw string("ERROR: one of the dimensions is zero");
}
#endif
// build the vector that stores all the new row IDs for each old row (represented by columns of Z)
vector< vector<size_t> > fac(Z.getNcols());
for (size_t oldRow = 0; oldRow < Z.getNcols(); oldRow++) {
for (size_t newRow = 0; newRow < Z.getNrows(); newRow++) {
if (Z.getElem(newRow, oldRow) == 1.0) {
fac[oldRow].push_back(newRow);
} else if (Z.getElem(newRow, oldRow) != 0.0) {
throw string("ERROR: design matrix can only have elements 1 or 0 in premultZt()");
}
}
}
if ((Z.getNcols() != out.getNrows()) || (Ncol_ != out.getNcols())) {
out.resize(Z.getNcols(), Ncol_); // resizing already sets all to 0.0
} else {
fill(out.data_, out.data_ + (out.Ncol_*out.Nrow_), 0.0);
}
for (size_t newRow = 0; newRow < Z.getNcols(); newRow++) {
// going through all the rows of Z that correspond to the new row of M
for (auto &f : fac[newRow]) {
// summing the rows of M within the group defined by rows of Z
for (size_t jCol = 0; jCol < Ncol_; jCol++) {
out.data_[Z.getNcols()*jCol + newRow] += data_[Nrow_*jCol + f];
}
}
}
}
void Matrix::postmultZ(const Matrix &Z){
#ifndef LMRG_CHECK_OFF
if (Z.getNrows() != Ncol_) {
throw string("ERROR: Incompatible dimensions between Z and M in postmultZ()");
}
if ( (Nrow_ == 0) || (Ncol_ == 0) ) {
throw string("ERROR: one of the dimensions is zero");
}
#endif
// build the vector that stores all the old row IDs for each new row
vector< vector<size_t> > fac(Z.getNcols());
for (size_t newCol = 0; newCol < Z.getNcols(); newCol++) {
for (size_t oldRow = 0; oldRow < Z.getNrows(); oldRow++) {
if (Z.getElem(oldRow, newCol) == 1.0) {
fac[newCol].push_back(oldRow);
} else if (Z.getElem(oldRow, newCol) != 0.0) {
throw string("ERROR: design matrix can only have elements 1 or 0 in postmultZ()");
}
}
}
double *dataCopy = new double[Nrow_ * Ncol_];
memcpy(dataCopy, data_, (Nrow_ * Ncol_)*sizeof(double));
delete [] data_;
data_ = new double[Nrow_ * Z.getNcols()](); // value initialization for sums to work
for (size_t newCol = 0; newCol < Z.getNcols(); newCol++) {
// going through all the rows of Z that correspond to the new column of M
for (auto &f : fac[newCol]) {
// summing the rows of M within the group defined by rows of Z
for (size_t iRow = 0; iRow < Nrow_; iRow++) {
data_[Z.getNcols()*newCol + iRow] += dataCopy[Nrow_*f + iRow];
}
}
}
Ncol_ = Z.getNcols();
delete [] dataCopy;
}
void Matrix::postmultZ(const Matrix &Z, Matrix &out) const{
#ifndef LMRG_CHECK_OFF
if (Z.getNrows() != Ncol_) {
throw string("ERROR: Incompatible dimensions between Z and M in postmultZ()");
}
if ( (Nrow_ == 0) || (Ncol_ == 0) ) {
throw string("ERROR: one of the dimensions is zero");
}
#endif
// build the vector that stores all the old column IDs for each new column
vector< vector<size_t> > fac(Z.getNcols());
for (size_t newCol = 0; newCol < Z.getNcols(); newCol++) {
for (size_t oldRow = 0; oldRow < Z.getNrows(); oldRow++) {
if (Z.getElem(oldRow, newCol) == 1.0) {
fac[newCol].push_back(oldRow);
} else if (Z.getElem(oldRow, newCol) != 0.0) {
throw string("ERROR: design matrix can only have elements 1 or 0 in postmultZ()");
}
}
}
if ((Z.getNcols() != out.getNcols()) || (Nrow_ != out.getNrows())) {
out.resize(Nrow_, Z.getNcols());
}
for (size_t newCol = 0; newCol < Z.getNcols(); newCol++) {
// going through all the rows of Z that correspond to the new column of M
for (auto &f : fac[newCol]) {
// summing the rows of M within the group defined by rows of Z
for (size_t iRow = 0; iRow < Nrow_; iRow++) {
out.data_[Z.getNcols()*newCol + iRow] += data_[Nrow_*f + iRow];
}
}
}
}
void Matrix::postmultZt(const Matrix &Z){
#ifndef LMRG_CHECK_OFF
if (Z.getNcols() != Ncol_) { // Z not transposed
throw string("ERROR: Incompatible dimensions between Z and M in postmultZ()");
}
if ( (Nrow_ == 0) || (Ncol_ == 0) ) {
throw string("ERROR: one of the dimensions is zero");
}
#endif
// build the vector that stores all the new row IDs for each old row (represented by columns of Z)
vector< vector<size_t> > fac(Z.getNcols());
for (size_t oldRow = 0; oldRow < Z.getNcols(); oldRow++) {
for (size_t newRow = 0; newRow < Z.getNrows(); newRow++) {
if (Z.getElem(newRow, oldRow) == 1.0) {
fac[oldRow].push_back(newRow);
} else if (Z.getElem(newRow, oldRow) != 0.0) {
throw string("ERROR: design matrix can only have elements 1 or 0 in postmultZ()");
}
}
}
double *dataCopy = new double[Nrow_ * Ncol_];
memcpy(dataCopy, data_, (Nrow_ * Ncol_)*sizeof(double));
delete [] data_;
data_ = new double[Z.getNrows() * Nrow_];
for (size_t oldCol = 0; oldCol < Z.getNcols(); oldCol++) {
// going through all the rows of Z that correspond to the old column of M
for (auto &f : fac[oldCol]) {
// copying the column of M
memcpy(data_ + f*Nrow_, dataCopy + oldCol*Nrow_, Nrow_*sizeof(double));
}
}
Ncol_ = Z.getNrows();
delete [] dataCopy;
}
void Matrix::postmultZt(const Matrix &Z, Matrix &out) const{
#ifndef LMRG_CHECK_OFF
if (Z.getNcols() != Ncol_) { // Z not transposed
throw string("ERROR: Incompatible dimensions between Z and M in postmultZ()");
}
if ( (Nrow_ == 0) || (Ncol_ == 0) ) {
throw string("ERROR: one of the dimensions is zero");
}
#endif
// build the vector that stores all the new row IDs for each old row (represented by columns of Z)
vector< vector<size_t> > fac(Z.getNcols());
for (size_t oldRow = 0; oldRow < Z.getNcols(); oldRow++) {
for (size_t newRow = 0; newRow < Z.getNrows(); newRow++) {
if (Z.getElem(newRow, oldRow) == 1.0) {
fac[oldRow].push_back(newRow);
} else if (Z.getElem(newRow, oldRow) != 0.0) {
throw string("ERROR: design matrix can only have elements 1 or 0 in postmultZ()");
}
}
}
// careful: Z is not transposed, but will be constructing MZ^t
if ((Z.getNrows() != out.getNcols()) || (Nrow_ != out.getNrows())) {
out.resize(Z.getNrows(), Nrow_);
}
for (size_t oldCol = 0; oldCol < Z.getNcols(); oldCol++) {
// going through all the rows of Z that correspond to the old column of M
for (auto &f : fac[oldCol]) {
// copying the column of M
memcpy(out.data_ + f*Nrow_, data_ + oldCol*Nrow_, Nrow_*sizeof(double));
}
}
}
void Matrix::syrk(const char &tri, const double &alpha, const double &beta, Matrix &C) const {
#ifndef LMRG_CHECK_OFF
if ((Ncol_ > INT_MAX) || (Nrow_ > INT_MAX)) {
throw string("ERROR: at least one matrix dimension too big to safely convert to int in syrk()");
}
if ( (Nrow_ == 0) || (Ncol_ == 0) ) {
throw string("ERROR: one of the dimensions is zero");
}
#endif
if ((C.getNrows() != Ncol_) || (C.getNcols() != Ncol_)) {
C.resize(Ncol_, Ncol_);
}
// integer parameters
const int n = static_cast<int>(Ncol_);
const int k = static_cast<int>(Nrow_);
const int lda = static_cast<int>(Nrow_);
const int ldc = static_cast<int>(Ncol_);
// transpose token
const char trans = 't';
dsyrk_(&tri, &trans, &n, &k, &alpha, data_, &lda, &beta, C.data_, &ldc);
}
void Matrix::tsyrk(const char &tri, const double &alpha, const double &beta, Matrix &C) const {
#ifndef LMRG_CHECK_OFF
if ((Ncol_ > INT_MAX) || (Nrow_ > INT_MAX)) {
throw string("ERROR: at least one matrix dimension too big to safely convert to int in tsyrk()");
}
if ( (Nrow_ == 0) || (Ncol_ == 0) ) {
throw string("ERROR: one of the dimensions is zero");
}
#endif
if ((C.getNrows() != Nrow_) || (C.getNcols() != Nrow_)) {
C.resize(Nrow_, Nrow_);
}
// integer parameters
const int n = static_cast<int>(Nrow_);
const int k = static_cast<int>(Ncol_);
const int lda = static_cast<int>(Nrow_);
const int ldc = static_cast<int>(Nrow_);
// transpose token
const char trans = 'n';
dsyrk_(&tri, &trans, &n, &k, &alpha, data_, &lda, &beta, C.data_, &ldc);
}
void Matrix::symm(const char &tri, const char &side, const double &alpha, const Matrix &symA, const double &beta, Matrix &C) const{
#ifndef LMRG_CHECK_OFF
if ( (Nrow_ == 0) || (Ncol_ == 0) ) {
throw string("ERROR: one of the dimensions is zero");
}
if (symA.getNrows() != symA.getNcols()) {
throw string("ERROR: symmetric matrix symA has to be square in symm()");
}
if (side == 'l') {
if ((Nrow_ > INT_MAX) || (symA.getNcols() > INT_MAX)) {
throw string("ERROR: at least one matrix dimension too big to safely convert to int in symm()");
}
} else if (side == 'r') {
if ((symA.getNrows() > INT_MAX) || (Ncol_ > INT_MAX)) {
throw string("ERROR: at least one matrix dimension too big to safely convert to int in symm()");
}
}
if ((symA.getNcols() != Nrow_) && (side == 'l')) { // AB
throw string("ERROR: Incompatible dimensions between B and A in symm()");
}
if ((symA.getNrows() != Ncol_) && (side == 'r')) { // BA
throw string("ERROR: Incompatible dimensions between A and B in symm()");
}
#endif
int m;
int n;
if (side == 'l') { // AB
m = static_cast<int>(symA.getNrows());
n = static_cast<int>(Ncol_);
if ((C.getNrows() != symA.getNrows()) || (C.getNcols() != Ncol_)) {
C.resize(symA.getNrows(), Ncol_);
}
} else if (side == 'r') { // BA
m = static_cast<int>(Nrow_);
n = static_cast<int>(symA.getNcols());
if ((C.getNrows() != Nrow_) || (C.getNcols() != symA.getNcols())) {
C.resize(Nrow_, symA.getNcols());
}
} else {
throw string("ERROR: unknown side indicator in symm()");
}
// final integer parameters
const int lda = static_cast<int>(symA.getNrows());
const int ldb = static_cast<int>(Nrow_);
const int ldc = m; // for clarity
dsymm_(&side, &tri, &m, &n, &alpha, symA.data_, &lda, data_, &ldb, &beta, C.data_, &ldc);
}
void Matrix::symc(const char &tri, const double &alpha, const Matrix &X, const size_t &xCol, const double &beta, vector<double> &y) const{
#ifndef LMRG_CHECK_OFF
if ( (Nrow_ == 0) || (Ncol_ == 0) ) {
throw string("ERROR: one of the dimensions is zero");
}
if (Ncol_ != Nrow_) {
throw string("ERROR: symmetric matrix (current object) has to be square in symc()");
}
if ((Ncol_ > INT_MAX) || (X.getNrows() > INT_MAX)) {
throw string("ERROR: at least one matrix dimension too big to safely convert to int in symc()");
}
if (X.getNrows() != Ncol_) {
throw string("ERROR: Incompatible dimensions between A and X in symc()");
}
if (xCol >= X.getNcols()) {
throw string("ERROR: column index out of range for matrix X in symc()");
}
#endif
if (y.size() < Nrow_) {
y.resize(Nrow_);
}
// BLAS routine constants
const int n = static_cast<int>(Nrow_);
const int lda = n;
const int incx = 1;
const int incy = 1;
const double *xbeg = X.data_ + xCol*(X.Nrow_); // offset to the column of interest
dsymv_(&tri, &n, &alpha, data_, &lda, xbeg, &incx, &beta, y.data(), &incy);
}
void Matrix::gemm(const bool &transA, const double &alpha, const Matrix &A, const bool &transB, const double &beta, Matrix &C) const{
#ifndef LMRG_CHECK_OFF
if ( (Nrow_ == 0) || (Ncol_ == 0) ) {
throw string("ERROR: one of the dimensions is zero");
}
if ((A.getNcols() > INT_MAX) || (A.getNrows() > INT_MAX)) {
throw string("ERROR: at least one A matrix dimension too big to safely convert to int in gemm()");
}
if (transB) {
if (Nrow_ > INT_MAX) {
throw string("ERROR: at least one B matrix dimension too big to safely convert to int in gemm()");
}
} else {
if (Ncol_ > INT_MAX) {
throw string("ERROR: at least one B matrix dimension too big to safely convert to int in gemm()");
}
}
if (transA) {
if (transB && (A.getNrows() != Ncol_)) {
throw string("ERROR: Incompatible dimensions between A^T and B^T in gemm()");
} else if (!transB && (A.getNrows() != Nrow_)){
throw string("ERROR: Incompatible dimensions between A^T and B in gemm()");
}
} else {
if (transB && (A.getNcols() != Ncol_)) {
throw string("ERROR: Incompatible dimensions between A and B^T in gemm()");
exit(16);
} else if (!transB && (A.getNcols() != Nrow_)) {
throw string("ERROR: Incompatible dimensions between A and B in gemm()");
}
}
#endif
char tAtok;
char tBtok;
int m;
int k;
int n;
if (transA) {
tAtok = 't';
m = static_cast<int>(A.getNcols());
k = static_cast<int>(A.getNrows());
if (transB) {
tBtok = 't';
n = static_cast<int>(Nrow_);
if ((C.getNrows() != A.getNcols()) || (C.getNcols() != Nrow_)) {
C.resize(A.getNcols(), Nrow_);
}
} else {
tBtok = 'n';
n = static_cast<int>(Ncol_);
if ((C.getNrows() != A.getNcols()) || (C.getNcols() != Ncol_)) {
C.resize(A.getNcols(), Ncol_);
}
}
} else {
tAtok = 'n';
m = static_cast<int>(A.getNrows());
k = static_cast<int>(A.getNcols());
if (transB) {
tBtok = 't';
n = static_cast<int>(Nrow_);
if ((C.getNrows() != A.getNrows()) || (C.getNcols() != Nrow_)) {
C.resize(A.getNrows(), Nrow_);
}
} else {
tBtok = 'n';
n = static_cast<int>(Ncol_);
if ((C.getNrows() != A.getNrows()) || (C.getNcols() != Ncol_)) {
C.resize(A.getNrows(), Ncol_);
}
}
}
const int lda = (transA ? k : m);
const int ldb = (transB ? n : k);
const int ldc = m;
dgemm_(&tAtok, &tBtok, &m, &n, &k, &alpha, A.data_, &lda, data_, &ldb, &beta, C.data_, &ldc);
}
void Matrix::gemc(const bool &trans, const double &alpha, const Matrix &X, const size_t &xCol, const double &beta, vector<double> &y) const {
#ifndef LMRG_CHECK_OFF
if ( (Nrow_ == 0) || (Ncol_ == 0) ) {
throw string("ERROR: one of the dimensions is zero");
}
if (trans) {
if ((Nrow_ > INT_MAX) || (X.getNrows() > INT_MAX)) {
throw string("ERROR: at least one matrix dimension too big to safely convert to int in gemc()");
}
if (Nrow_ != X.getNrows()) {
throw string("ERROR: Incompatible dimensions between A and X in gemc()");
}
} else {
if ((Ncol_ > INT_MAX) || (X.getNrows() > INT_MAX)) {
throw string("ERROR: at least one matrix dimension too big to safely convert to int in gemc()");
}
if (Ncol_ != X.getNrows()) {
throw string("ERROR: Incompatible dimensions between A and X in gemc()");
}
}
if (xCol >= X.getNcols()) {
throw string("ERROR: column index out of range for matrix X in gemc()");
}
#endif
if (y.size() < Nrow_) {
y.resize(Nrow_);
}
// Establish constants for DGEMV
const char tTok = (trans ? 't' : 'n');
const int m = static_cast<int>(Nrow_);
const int n = static_cast<int>(Ncol_);
const int lda = m;
const int incx = 1;
const int incy = 1;
const double *xbeg = X.data_ + xCol*(X.Nrow_); // offset to the column of interest
dgemv_(&tTok, &m, &n, &alpha, data_, &lda, xbeg, &incx, &beta, y.data(), &incy);
}
Matrix Matrix::colShuffle() const{
Matrix out(Nrow_, Ncol_);
RanDraw rng;
vector<uint64_t> ind = rng.shuffleUint(Ncol_); // shuffled column index
for (size_t j = 0; j < Ncol_; ++j) {
for (size_t i = 0; i < Nrow_; ++i) {
out.setElem(i, ind[j], this->getElem(i, j));
}
}
return out;
}
Matrix Matrix::rowShuffle() const{
Matrix out(Nrow_, Ncol_);
RanDraw rng;
vector<uint64_t> ind = rng.shuffleUint(Nrow_); // shuffled column index
for (size_t j = 0; j < Ncol_; ++j) {
for (size_t i = 0; i < Nrow_; ++i) {
out.setElem(ind[i], j, this->getElem(i, j));
}
}
return out;
}
Matrix Matrix::operator*(const Matrix &m) const{
#ifndef LMRG_CHECK_OFF
if ((Nrow_ != m.Nrow_) || (Ncol_ != m.Ncol_)) {
throw string("ERROR: Incompatible dimensions between matrices in the Hadamard product");
}
#endif
Matrix res(*this);
for (size_t iElm = 0; iElm < Ncol_*Nrow_; iElm++) {
res.data_[iElm] *= m.data_[iElm];
}
return res;
}
Matrix Matrix::operator*(const double &scal) const{
Matrix res(*this);
for (size_t iElm = 0; iElm < Ncol_*Nrow_; iElm++) {
res.data_[iElm] *= scal;
}
return res;
}
Matrix Matrix::operator/(const Matrix &m) const{
#ifndef LMRG_CHECK_OFF
if ((Nrow_ != m.Nrow_) || (Ncol_ != m.Ncol_)) {
throw string("ERROR: Incompatible dimensions between matrices in the Hadamard product");
}
#endif
Matrix res(*this);
for (size_t iElm = 0; iElm < Ncol_*Nrow_; iElm++) {
res.data_[iElm] /= m.data_[iElm];
}
return res;
}
Matrix Matrix::operator/(const double &scal) const{
Matrix res(*this);
for (size_t iElm = 0; iElm < Ncol_*Nrow_; iElm++) {
res.data_[iElm] /= scal;
}
return res;
}
Matrix Matrix::operator+(const Matrix &m) const{
#ifndef LMRG_CHECK_OFF
if ((Nrow_ != m.Nrow_) || (Ncol_ != m.Ncol_)) {
throw string("ERROR: Incompatible dimensions between matrices in the Hadamard product");
}
#endif
Matrix res(*this);
for (size_t iElm = 0; iElm < Ncol_*Nrow_; iElm++) {
res.data_[iElm] += m.data_[iElm];
}
return res;
}
Matrix Matrix::operator+(const double &scal) const{
Matrix res(*this);
for (size_t iElm = 0; iElm < Ncol_*Nrow_; iElm++) {
res.data_[iElm] += scal;
}
return res;
}
Matrix Matrix::operator-(const Matrix &m) const{
#ifndef LMRG_CHECK_OFF
if ((Nrow_ != m.Nrow_) || (Ncol_ != m.Ncol_)) {
throw string("ERROR: Incompatible dimensions between matrices in the Hadamard product");
}
#endif
Matrix res(*this);
for (size_t iElm = 0; iElm < Ncol_*Nrow_; iElm++) {
res.data_[iElm] -= m.data_[iElm];
}
return res;
}
Matrix Matrix::operator-(const double &scal) const{
Matrix res(*this);
for (size_t iElm = 0; iElm < Ncol_*Nrow_; iElm++) {
res.data_[iElm] -= scal;
}
return res;
}
Matrix& Matrix::operator+=(const double &scal){
for (size_t iElm = 0; iElm < Ncol_*Nrow_; iElm++) {
data_[iElm] += scal;
}
return *this;
}
Matrix& Matrix::operator*=(const double &scal){
for (size_t iElm = 0; iElm < Ncol_*Nrow_; iElm++) {
data_[iElm] *= scal;
}
return *this;
}
Matrix& Matrix::operator-=(const double &scal){
for (size_t iElm = 0; iElm < Ncol_*Nrow_; iElm++) {
data_[iElm] -= scal;
}
return *this;
}
Matrix& Matrix::operator/=(const double &scal){
for (size_t iElm = 0; iElm < Ncol_*Nrow_; iElm++) {
data_[iElm] /= scal;
}
return *this;
}
void Matrix::rowMeans(vector<double> &means) const{
if (means.size() < Nrow_) {
means.resize(Nrow_);
}
for (size_t iRow = 0; iRow < Nrow_; iRow++) {
means[iRow] = 0.0; // in case something was in the vector passed to the function and resize did not erase it
for (size_t jCol = 0; jCol < Ncol_; jCol++) {
// numerically stable recursive mean calculation. GSL does it this way.
means[iRow] += (data_[Nrow_*jCol + iRow] - means[iRow])/static_cast<double>(jCol + 1);
}
}
}
void Matrix::colMeans(vector<double> &means) const{
if (means.size() < Ncol_) {
means.resize(Ncol_);
}
for (size_t jCol = 0; jCol < Ncol_; jCol++) {
means[jCol] = 0.0; // in case something was in the vector passed to the function and resize did not erase it
for (size_t iRow = 0; iRow < Nrow_; iRow++) {
// numerically stable recursive mean calculation. GSL does it this way.
means[jCol] += (data_[Nrow_*jCol + iRow] - means[jCol])/static_cast<double>(iRow + 1);
}
}
}
void Matrix::rowSums(vector<double> &sums) const{
if (sums.size() < Nrow_) {
sums.resize(Nrow_);
}
for (size_t iRow = 0; iRow < Nrow_; iRow++) {
sums[iRow] = 0.0; // in case something was in the vector passed to the function and resize did not erase it
for (size_t jCol = 0; jCol < Ncol_; jCol++) {
// not necessarily mumerically stable. Revisit later
sums[iRow] += data_[Nrow_*jCol + iRow];
}
}
}
void Matrix::colSums(vector<double> &sums) const{
if (sums.size() < Ncol_) {
sums.resize(Ncol_);
}
for (size_t jCol = 0; jCol < Ncol_; jCol++) {
sums[jCol] = 0.0; // in case something was in the vector passed to the function and resize did not erase it
for (size_t iRow = 0; iRow < Nrow_; iRow++) {
// not necessarily mumerically stable. Revisit later
sums[jCol] += data_[Nrow_*jCol + iRow];
}
}
}
void Matrix::rowMultiply(const vector<double> &scalars){
#ifndef LMRG_CHECK_OFF
if (scalars.size() != Ncol_) {
throw string("ERROR: Vector of scalars has wrong length in rowMultiply(vector)");
}
#endif
for (size_t iRow = 0; iRow < Nrow_; iRow++) {
for (size_t jCol = 0; jCol < Ncol_; jCol++) {
data_[Nrow_*jCol + iRow] *= scalars[jCol];
}
}
}
void Matrix::rowMultiply(const double &scalar, const size_t &iRow){
#ifndef LMRG_CHECK_OFF
if (iRow >= Nrow_) {
throw string("ERROR: Row index out of bounds in rowMultiply(scalar)");
}
#endif
for (size_t jCol = 0; jCol < Ncol_; jCol++) {
data_[Nrow_*jCol + iRow] *= scalar;
}
}
void Matrix::colMultiply(const vector<double> &scalars){
#ifndef LMRG_CHECK_OFF
if (scalars.size() != Nrow_) {
throw string("ERROR: Vector of scalars has wrong length in colMultiply(vector)");
}
#endif
for (size_t jCol = 0; jCol < Ncol_; jCol++) {
for (size_t iRow = 0; iRow < Nrow_; iRow++) {
data_[Nrow_*jCol + iRow] *= scalars[iRow];
}
}
}
void Matrix::colMultiply(const double &scalar, const size_t &jCol){
#ifndef LMRG_CHECK_OFF
if (jCol >= Ncol_) {
throw string("ERROR: Column index out of bounds in colMultiply(scalar)");
}
#endif
for (size_t iRow = 0; iRow < Nrow_; iRow++) {
data_[Nrow_*jCol + iRow] *= scalar;
}
}
void Matrix::rowDivide(const vector<double> &scalars){
#ifndef LMRG_CHECK_OFF
if (scalars.size() != Ncol_) {
throw string("ERROR: Vector of scalars has wrong length in rowDivide(vector)");
}
#endif
for (size_t iRow = 0; iRow < Nrow_; iRow++) {
for (size_t jCol = 0; jCol < Ncol_; jCol++) {
data_[Nrow_*jCol + iRow] /= scalars[jCol];
}
}
}
void Matrix::rowDivide(const double &scalar, const size_t &iRow){
#ifndef LMRG_CHECK_OFF
if (iRow >= Nrow_) {
throw string("ERROR: Row index out of bounds in rowDivide(scalar)");
}
#endif
for (size_t jCol = 0; jCol < Ncol_; jCol++) {
data_[Nrow_*jCol + iRow] /= scalar;
}
}
void Matrix::colDivide(const vector<double> &scalars){
#ifndef LMRG_CHECK_OFF
if (scalars.size() != Nrow_) {
throw string("ERROR: Vector of scalars has wrong length in colDivide(vector)");
}
#endif
for (size_t jCol = 0; jCol < Ncol_; jCol++) {
for (size_t iRow = 0; iRow < Nrow_; iRow++) {
data_[Nrow_*jCol + iRow] /= scalars[iRow];
}
}
}
void Matrix::colDivide(const double &scalar, const size_t &jCol){
#ifndef LMRG_CHECK_OFF
if (jCol >= Ncol_) {
throw string("ERROR: Column index out of bounds in colDivide(scalar)");
}
#endif
for (size_t iRow = 0; iRow < Nrow_; iRow++) {
data_[Nrow_*jCol + iRow] /= scalar;
}
}
void Matrix::rowAdd(const vector<double> &scalars){
#ifndef LMRG_CHECK_OFF
if (scalars.size() != Ncol_) {
throw string("ERROR: Vector of scalars has wrong length in rowAdd(vector)");
}
#endif
for (size_t iRow = 0; iRow < Nrow_; iRow++) {
for (size_t jCol = 0; jCol < Ncol_; jCol++) {
data_[Nrow_*jCol + iRow] += scalars[jCol];
}
}
}
void Matrix::rowAdd(const double &scalar, const size_t &iRow){
#ifndef LMRG_CHECK_OFF
if (iRow >= Nrow_) {
throw string("ERROR: Row index out of bounds in rowAdd(scalar)");
}
#endif
for (size_t jCol = 0; jCol < Ncol_; jCol++) {
data_[Nrow_*jCol + iRow] += scalar;
}
}
void Matrix::colAdd(const vector<double> &scalars){
#ifndef LMRG_CHECK_OFF
if (scalars.size() != Nrow_) {
throw string("ERROR: Vector of scalars has wrong length in colAdd(vector)");
}
#endif
for (size_t jCol = 0; jCol < Ncol_; jCol++) {
for (size_t iRow = 0; iRow < Nrow_; iRow++) {
data_[Nrow_*jCol + iRow] += scalars[iRow];
}
}
}
void Matrix::colAdd(const double &scalar, const size_t &jCol){
#ifndef LMRG_CHECK_OFF
if (jCol >= Ncol_) {
throw string("ERROR: Column index out of bounds in colAdd(scalar)");
}
#endif
for (size_t iRow = 0; iRow < Nrow_; iRow++) {
data_[Nrow_*jCol + iRow] += scalar;
}
}
void Matrix::rowSub(const vector<double> &scalars){
#ifndef LMRG_CHECK_OFF
if (scalars.size() != Ncol_) {
throw string("ERROR: Vector of scalars has wrong length in rowSub(vector)");
}
#endif
for (size_t iRow = 0; iRow < Nrow_; iRow++) {
for (size_t jCol = 0; jCol < Ncol_; jCol++) {
data_[Nrow_*jCol + iRow] -= scalars[jCol];
}
}
}
void Matrix::rowSub(const double &scalar, const size_t &iRow){
#ifndef LMRG_CHECK_OFF
if (iRow >= Nrow_) {
throw string("ERROR: Row index out of bounds in rowSub(scalar)");
}
#endif
for (size_t jCol = 0; jCol < Ncol_; jCol++) {
data_[Nrow_*jCol + iRow] -= scalar;
}
}
void Matrix::colSub(const vector<double> &scalars){
#ifndef LMRG_CHECK_OFF
if (scalars.size() != Nrow_) {
throw string("ERROR: Vector of scalars has wrong length in colSub(vector)");
}
#endif
for (size_t jCol = 0; jCol < Ncol_; jCol++) {
for (size_t iRow = 0; iRow < Nrow_; iRow++) {
data_[Nrow_*jCol + iRow] -= scalars[iRow];
}
}
}
void Matrix::colSub(const double &scalar, const size_t &jCol){
#ifndef LMRG_CHECK_OFF
if (jCol >= Ncol_) {
throw string("ERROR: Column index out of bounds in colSub(scalar)");
}
#endif
for (size_t iRow = 0; iRow < Nrow_; iRow++) {
data_[Nrow_*jCol + iRow] -= scalar;
}
}
void Matrix::appendCol(const Matrix &cols){
#ifndef LMRG_CHECK_OFF
if (Ncol_ > cols.Ncol_ + Ncol_) { // happens on wrap-around
throw string("ERROR: Number of columns too big to expand");
}
#endif
// if the other matrix is empty, do nothing
if ( (cols.Ncol_ == 0) || (cols.Nrow_ == 0) ) {
return;
}
if (this == &cols) { // self-appending
if (Ncol_ && Nrow_) {
double *dataCopy = new double[Nrow_ * Ncol_];
memcpy(dataCopy, data_, (Nrow_ * Ncol_)*sizeof(double));
delete [] data_;
data_ = new double[Nrow_ * 2 * Ncol_];
memcpy(data_, dataCopy, (Nrow_ * Ncol_)*sizeof(double));
memcpy(data_ + Nrow_*Ncol_, dataCopy, (Nrow_ * Ncol_)*sizeof(double));
Ncol_ *= 2;
delete [] dataCopy;
} else {
return;
}
} else {
#ifndef LMRG_CHECK_OFF
if (Nrow_ != cols.Nrow_) {
throw string("ERROR: Number of rows in appeneded object not equal to the number of rows in focal matrix");
}
#endif
double *dataCopy = new double[Nrow_ * Ncol_];
memcpy(dataCopy, data_, (Nrow_ * Ncol_)*sizeof(double));
delete [] data_;
data_ = new double[Nrow_ * (cols.Ncol_ + Ncol_)];
memcpy(data_, dataCopy, (Nrow_ * Ncol_)*sizeof(double));
delete [] dataCopy;
memcpy(data_ + Nrow_*Ncol_, cols.data_, (Nrow_ * (cols.Ncol_))*sizeof(double));
Ncol_ += cols.Ncol_;
}
}
void Matrix::appendRow(const Matrix &rows){
#ifndef LMRG_CHECK_OFF
if (Nrow_ > rows.Nrow_ + Nrow_) { // happens on wrap-around
throw string("ERROR: Number of rows too big to expand");
}
#endif
// if the other matrix is empty, do nothing
if ( (rows.Nrow_ == 0) || (rows.Ncol_ == 0) ) {
return;
}
if (this == &rows) { // self-appending
if (Nrow_ && Ncol_) {
double *dataCopy = new double[Nrow_ * Ncol_];
memcpy(dataCopy, data_, (Nrow_ * Ncol_)*sizeof(double));
delete [] data_;
data_ = new double[2 * Nrow_ * Ncol_];
// since rows are discontinuous, have to go column by column and copy rows within each column
for (size_t jCol = 0; jCol < Ncol_; jCol++) {
memcpy(data_ + 2*Nrow_*jCol, dataCopy + Nrow_*jCol, Nrow_*sizeof(double));
memcpy(data_ + 2*Nrow_*jCol + Nrow_, dataCopy + Nrow_*jCol, Nrow_*sizeof(double));
}
Nrow_ *= 2;
delete [] dataCopy;
} else {
return;
}
} else {
#ifndef LMRG_CHECK_OFF
if (Ncol_ != rows.Ncol_) {
throw string("ERROR: Number of columns in appeneded object not equal to the number of columns in focal matrix");
}
#endif
double *dataCopy = new double[Nrow_ * Ncol_];
memcpy(dataCopy, data_, (Nrow_ * Ncol_)*sizeof(double));
delete [] data_;
data_ = new double[(rows.Nrow_ + Nrow_) * Ncol_];
// since rows are discontinuous, have to go column by column and copy rows within each column
for (size_t jCol = 0; jCol < Ncol_; jCol++) {
memcpy(data_ + (rows.Nrow_+Nrow_)*jCol, dataCopy + Nrow_*jCol, Nrow_*sizeof(double));
memcpy(data_ + (rows.Nrow_+Nrow_)*jCol + Nrow_, rows.data_ + (rows.Nrow_)*jCol, (rows.Nrow_)*sizeof(double));
}
Nrow_ += rows.Nrow_;
delete [] dataCopy;
}
}
void Matrix::dropLeftCols(const size_t &newFirst){
#ifndef LMRG_CHECK_OFF
if (newFirst >= Ncol_) {
throw string("ERROR: New first column index is past the last column in dropLeftCols()");
}
#endif
if (newFirst == 0) {
return;
}
double *dataCopy = new double[Nrow_ * Ncol_];
memcpy(dataCopy, data_, (Nrow_ * Ncol_)*sizeof(double));
delete [] data_;
Ncol_ -= newFirst;
data_ = new double[Ncol_ * Nrow_];
memcpy(data_, dataCopy + newFirst*Nrow_, (Nrow_ * Ncol_)*sizeof(double));
delete [] dataCopy;
}
void Matrix::dropRightCols(const size_t &newLast){
#ifndef LMRG_CHECK_OFF
if (newLast >= Ncol_) {
throw string("ERROR: New last column index is past the last column in dropRightCols()");
}
#endif
if (newLast == (Ncol_ - 1)) {
return;
}
double *dataCopy = new double[Nrow_ * Ncol_];
memcpy(dataCopy, data_, (Nrow_ * Ncol_)*sizeof(double));
delete [] data_;
Ncol_ = newLast + 1;
data_ = new double[Ncol_ * Nrow_];
memcpy(data_, dataCopy, (Nrow_ * Ncol_)*sizeof(double));
delete [] dataCopy;
}
void Matrix::dropTopRows(const size_t &newTop){
#ifndef LMRG_CHECK_OFF
if (newTop >= Nrow_) {
throw string("ERROR: New first row index is past the last row in dropTopRows()");
}
#endif
if (newTop == 0) {
return;
}
double *dataCopy = new double[Nrow_ * Ncol_];
memcpy(dataCopy, data_, (Nrow_ * Ncol_)*sizeof(double));
delete [] data_;
const size_t oldNrow = Nrow_;
Nrow_ -= newTop;
data_ = new double[Nrow_ * Ncol_];
// copying the discontinuous rows by copying chunks of columns
for (size_t jCol = 0; jCol < Ncol_; jCol++) {
memcpy(data_ + Nrow_*jCol, dataCopy + newTop + oldNrow*jCol, Nrow_*sizeof(double));
}
delete [] dataCopy;
}
void Matrix::dropBottomRows(const size_t &newBottom){
#ifndef LMRG_CHECK_OFF
if (newBottom >= Nrow_) {
throw string("ERROR: New last row index is past the last row in dropBottomRows()");
}
#endif
if (newBottom == (Nrow_ -1)) {
return;
}
double *dataCopy = new double[Nrow_ * Ncol_];
memcpy(dataCopy, data_, (Nrow_ * Ncol_)*sizeof(double));
delete [] data_;
const size_t oldNrow = Nrow_;
Nrow_ = newBottom + 1;
data_ = new double[Nrow_ * Ncol_];
// copying the discontinuous rows by copying chunks of columns
for (size_t jCol = 0; jCol < Ncol_; jCol++) {
memcpy(data_ + Nrow_*jCol, dataCopy + oldNrow*jCol, Nrow_*sizeof(double));
}
delete [] dataCopy;
}
| [
"info@bayesicresearch.org"
] | info@bayesicresearch.org |
6870ac65a787817b64c4dde8594a1141adfc4f20 | 85b9ce4fb88972d9b86dce594ae4fb3acfcd0a4b | /build/Android/Release/Global Pot/app/src/main/include/Fuse.Animations.MasterPropertyGet.h | a733d6ac85b16a46bf4b5cb4616e6ea7b020f558 | [] | no_license | bgirr/Global-Pot_App | 16431a99e26f1c60dc16223fb388d9fd525cb5fa | c96c5a8fb95acde66fc286bcd9a5cdf160ba8b1b | refs/heads/master | 2021-01-09T06:29:18.255583 | 2017-02-21T23:27:47 | 2017-02-21T23:27:47 | 80,985,681 | 0 | 0 | null | 2017-02-21T23:27:48 | 2017-02-05T10:29:14 | C++ | UTF-8 | C++ | false | false | 685 | h | // This file was generated based on C:\Users\EliteBook-User\AppData\Local\Fusetools\Packages\Fuse.Animations\0.44.1\$.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.Object.h>
namespace g{
namespace Fuse{
namespace Animations{
// internal abstract interface MasterPropertyGet :1704
// {
uInterfaceType* MasterPropertyGet_typeof();
struct MasterPropertyGet
{
void(*fp_GetPropertyObject)(uObject*, uObject**);
static uObject* GetPropertyObject(const uInterface& __this) { uObject* __retval; return __this.VTable<MasterPropertyGet>()->fp_GetPropertyObject(__this, &__retval), __retval; }
};
// }
}}} // ::g::Fuse::Animations
| [
"girr.benjamin@gmail.com"
] | girr.benjamin@gmail.com |
41c0c8d723450b591519783178c5787f65d439e4 | 69a2604ec0058aadc68d4a003661881a4674b7d8 | /cpp/server/main.cpp | 7eaac2d5c57d6891bc96fb8b5dbf094d467ac7ef | [
"MIT"
] | permissive | danieljoos/grpc-error-details | f62e6c0fdbe1b72cfe2fd195e279589ee907b5f2 | 3e127d1b4d3cccc6c86c5bfe71a683170b5bea06 | refs/heads/master | 2022-03-18T20:22:26.090404 | 2022-03-09T18:12:51 | 2022-03-09T18:12:51 | 128,110,245 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,550 | cpp |
#include <grpc++/grpc++.h>
#include <grpc++/support/error_details.h>
#include <grpc/grpc.h>
#include "example.grpc.pb.h"
#include "example.pb.h"
// This is the compiled protobuf header of `google::rpc::Status`.
#include "status.pb.h"
class ExampleHelloImpl final : public example::ExampleHello::Service {
grpc::Status SaySomething(grpc::ServerContext* context,
const example::SaySomethingRequest* request,
example::SaySomethingResponse* response) final override {
// Create a protobuf message object that represents our custom information
example::ErrorDetails details;
details.set_why("some detailed error information");
// Create a google::rpc::Status protobuf message object that will be sent in
// the grpc trailers. The custom error-details object (see above) will be
// packed into an `Any` field.
google::rpc::Status status;
status.set_code(grpc::StatusCode::UNKNOWN);
status.set_message("normal error message");
status.add_details()->PackFrom(details);
// Call the `SetErrorDetails` support function of grpc.
grpc::Status result;
grpc::SetErrorDetails(status, &result);
return result;
}
};
int main(int argc, char** argv) {
ExampleHelloImpl service;
grpc::ServerBuilder()
.AddListeningPort("127.0.0.1:50001", grpc::InsecureServerCredentials())
.RegisterService(&service)
.BuildAndStart()
->Wait();
return 0;
}
| [
"daniel@joosweb.de"
] | daniel@joosweb.de |
ee30b318a81b221ce7770cb5b0a082e289ffc982 | 41b4adb10cc86338d85db6636900168f55e7ff18 | /aws-cpp-sdk-storagegateway/source/model/ErrorCode.cpp | 6307f8d502af4e923b791bf91d805c84ee83b32e | [
"JSON",
"MIT",
"Apache-2.0"
] | permissive | totalkyos/AWS | 1c9ac30206ef6cf8ca38d2c3d1496fa9c15e5e80 | 7cb444814e938f3df59530ea4ebe8e19b9418793 | refs/heads/master | 2021-01-20T20:42:09.978428 | 2016-07-16T00:03:49 | 2016-07-16T00:03:49 | 63,465,708 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 21,369 | cpp | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/storagegateway/model/ErrorCode.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace StorageGateway
{
namespace Model
{
namespace ErrorCodeMapper
{
static const int ActivationKeyExpired_HASH = HashingUtils::HashString("ActivationKeyExpired");
static const int ActivationKeyInvalid_HASH = HashingUtils::HashString("ActivationKeyInvalid");
static const int ActivationKeyNotFound_HASH = HashingUtils::HashString("ActivationKeyNotFound");
static const int GatewayInternalError_HASH = HashingUtils::HashString("GatewayInternalError");
static const int GatewayNotConnected_HASH = HashingUtils::HashString("GatewayNotConnected");
static const int GatewayNotFound_HASH = HashingUtils::HashString("GatewayNotFound");
static const int GatewayProxyNetworkConnectionBusy_HASH = HashingUtils::HashString("GatewayProxyNetworkConnectionBusy");
static const int AuthenticationFailure_HASH = HashingUtils::HashString("AuthenticationFailure");
static const int BandwidthThrottleScheduleNotFound_HASH = HashingUtils::HashString("BandwidthThrottleScheduleNotFound");
static const int Blocked_HASH = HashingUtils::HashString("Blocked");
static const int CannotExportSnapshot_HASH = HashingUtils::HashString("CannotExportSnapshot");
static const int ChapCredentialNotFound_HASH = HashingUtils::HashString("ChapCredentialNotFound");
static const int DiskAlreadyAllocated_HASH = HashingUtils::HashString("DiskAlreadyAllocated");
static const int DiskDoesNotExist_HASH = HashingUtils::HashString("DiskDoesNotExist");
static const int DiskSizeGreaterThanVolumeMaxSize_HASH = HashingUtils::HashString("DiskSizeGreaterThanVolumeMaxSize");
static const int DiskSizeLessThanVolumeSize_HASH = HashingUtils::HashString("DiskSizeLessThanVolumeSize");
static const int DiskSizeNotGigAligned_HASH = HashingUtils::HashString("DiskSizeNotGigAligned");
static const int DuplicateCertificateInfo_HASH = HashingUtils::HashString("DuplicateCertificateInfo");
static const int DuplicateSchedule_HASH = HashingUtils::HashString("DuplicateSchedule");
static const int EndpointNotFound_HASH = HashingUtils::HashString("EndpointNotFound");
static const int IAMNotSupported_HASH = HashingUtils::HashString("IAMNotSupported");
static const int InitiatorInvalid_HASH = HashingUtils::HashString("InitiatorInvalid");
static const int InitiatorNotFound_HASH = HashingUtils::HashString("InitiatorNotFound");
static const int InternalError_HASH = HashingUtils::HashString("InternalError");
static const int InvalidGateway_HASH = HashingUtils::HashString("InvalidGateway");
static const int InvalidEndpoint_HASH = HashingUtils::HashString("InvalidEndpoint");
static const int InvalidParameters_HASH = HashingUtils::HashString("InvalidParameters");
static const int InvalidSchedule_HASH = HashingUtils::HashString("InvalidSchedule");
static const int LocalStorageLimitExceeded_HASH = HashingUtils::HashString("LocalStorageLimitExceeded");
static const int LunAlreadyAllocated_HASH = HashingUtils::HashString("LunAlreadyAllocated ");
static const int LunInvalid_HASH = HashingUtils::HashString("LunInvalid");
static const int MaximumContentLengthExceeded_HASH = HashingUtils::HashString("MaximumContentLengthExceeded");
static const int MaximumTapeCartridgeCountExceeded_HASH = HashingUtils::HashString("MaximumTapeCartridgeCountExceeded");
static const int MaximumVolumeCountExceeded_HASH = HashingUtils::HashString("MaximumVolumeCountExceeded");
static const int NetworkConfigurationChanged_HASH = HashingUtils::HashString("NetworkConfigurationChanged");
static const int NoDisksAvailable_HASH = HashingUtils::HashString("NoDisksAvailable");
static const int NotImplemented_HASH = HashingUtils::HashString("NotImplemented");
static const int NotSupported_HASH = HashingUtils::HashString("NotSupported");
static const int OperationAborted_HASH = HashingUtils::HashString("OperationAborted");
static const int OutdatedGateway_HASH = HashingUtils::HashString("OutdatedGateway");
static const int ParametersNotImplemented_HASH = HashingUtils::HashString("ParametersNotImplemented");
static const int RegionInvalid_HASH = HashingUtils::HashString("RegionInvalid");
static const int RequestTimeout_HASH = HashingUtils::HashString("RequestTimeout");
static const int ServiceUnavailable_HASH = HashingUtils::HashString("ServiceUnavailable");
static const int SnapshotDeleted_HASH = HashingUtils::HashString("SnapshotDeleted");
static const int SnapshotIdInvalid_HASH = HashingUtils::HashString("SnapshotIdInvalid");
static const int SnapshotInProgress_HASH = HashingUtils::HashString("SnapshotInProgress");
static const int SnapshotNotFound_HASH = HashingUtils::HashString("SnapshotNotFound");
static const int SnapshotScheduleNotFound_HASH = HashingUtils::HashString("SnapshotScheduleNotFound");
static const int StagingAreaFull_HASH = HashingUtils::HashString("StagingAreaFull");
static const int StorageFailure_HASH = HashingUtils::HashString("StorageFailure");
static const int TapeCartridgeNotFound_HASH = HashingUtils::HashString("TapeCartridgeNotFound");
static const int TargetAlreadyExists_HASH = HashingUtils::HashString("TargetAlreadyExists");
static const int TargetInvalid_HASH = HashingUtils::HashString("TargetInvalid");
static const int TargetNotFound_HASH = HashingUtils::HashString("TargetNotFound");
static const int UnauthorizedOperation_HASH = HashingUtils::HashString("UnauthorizedOperation");
static const int VolumeAlreadyExists_HASH = HashingUtils::HashString("VolumeAlreadyExists");
static const int VolumeIdInvalid_HASH = HashingUtils::HashString("VolumeIdInvalid");
static const int VolumeInUse_HASH = HashingUtils::HashString("VolumeInUse");
static const int VolumeNotFound_HASH = HashingUtils::HashString("VolumeNotFound");
static const int VolumeNotReady_HASH = HashingUtils::HashString("VolumeNotReady");
ErrorCode GetErrorCodeForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == ActivationKeyExpired_HASH)
{
return ErrorCode::ActivationKeyExpired;
}
else if (hashCode == ActivationKeyInvalid_HASH)
{
return ErrorCode::ActivationKeyInvalid;
}
else if (hashCode == ActivationKeyNotFound_HASH)
{
return ErrorCode::ActivationKeyNotFound;
}
else if (hashCode == GatewayInternalError_HASH)
{
return ErrorCode::GatewayInternalError;
}
else if (hashCode == GatewayNotConnected_HASH)
{
return ErrorCode::GatewayNotConnected;
}
else if (hashCode == GatewayNotFound_HASH)
{
return ErrorCode::GatewayNotFound;
}
else if (hashCode == GatewayProxyNetworkConnectionBusy_HASH)
{
return ErrorCode::GatewayProxyNetworkConnectionBusy;
}
else if (hashCode == AuthenticationFailure_HASH)
{
return ErrorCode::AuthenticationFailure;
}
else if (hashCode == BandwidthThrottleScheduleNotFound_HASH)
{
return ErrorCode::BandwidthThrottleScheduleNotFound;
}
else if (hashCode == Blocked_HASH)
{
return ErrorCode::Blocked;
}
else if (hashCode == CannotExportSnapshot_HASH)
{
return ErrorCode::CannotExportSnapshot;
}
else if (hashCode == ChapCredentialNotFound_HASH)
{
return ErrorCode::ChapCredentialNotFound;
}
else if (hashCode == DiskAlreadyAllocated_HASH)
{
return ErrorCode::DiskAlreadyAllocated;
}
else if (hashCode == DiskDoesNotExist_HASH)
{
return ErrorCode::DiskDoesNotExist;
}
else if (hashCode == DiskSizeGreaterThanVolumeMaxSize_HASH)
{
return ErrorCode::DiskSizeGreaterThanVolumeMaxSize;
}
else if (hashCode == DiskSizeLessThanVolumeSize_HASH)
{
return ErrorCode::DiskSizeLessThanVolumeSize;
}
else if (hashCode == DiskSizeNotGigAligned_HASH)
{
return ErrorCode::DiskSizeNotGigAligned;
}
else if (hashCode == DuplicateCertificateInfo_HASH)
{
return ErrorCode::DuplicateCertificateInfo;
}
else if (hashCode == DuplicateSchedule_HASH)
{
return ErrorCode::DuplicateSchedule;
}
else if (hashCode == EndpointNotFound_HASH)
{
return ErrorCode::EndpointNotFound;
}
else if (hashCode == IAMNotSupported_HASH)
{
return ErrorCode::IAMNotSupported;
}
else if (hashCode == InitiatorInvalid_HASH)
{
return ErrorCode::InitiatorInvalid;
}
else if (hashCode == InitiatorNotFound_HASH)
{
return ErrorCode::InitiatorNotFound;
}
else if (hashCode == InternalError_HASH)
{
return ErrorCode::InternalError;
}
else if (hashCode == InvalidGateway_HASH)
{
return ErrorCode::InvalidGateway;
}
else if (hashCode == InvalidEndpoint_HASH)
{
return ErrorCode::InvalidEndpoint;
}
else if (hashCode == InvalidParameters_HASH)
{
return ErrorCode::InvalidParameters;
}
else if (hashCode == InvalidSchedule_HASH)
{
return ErrorCode::InvalidSchedule;
}
else if (hashCode == LocalStorageLimitExceeded_HASH)
{
return ErrorCode::LocalStorageLimitExceeded;
}
else if (hashCode == LunAlreadyAllocated_HASH)
{
return ErrorCode::LunAlreadyAllocated;
}
else if (hashCode == LunInvalid_HASH)
{
return ErrorCode::LunInvalid;
}
else if (hashCode == MaximumContentLengthExceeded_HASH)
{
return ErrorCode::MaximumContentLengthExceeded;
}
else if (hashCode == MaximumTapeCartridgeCountExceeded_HASH)
{
return ErrorCode::MaximumTapeCartridgeCountExceeded;
}
else if (hashCode == MaximumVolumeCountExceeded_HASH)
{
return ErrorCode::MaximumVolumeCountExceeded;
}
else if (hashCode == NetworkConfigurationChanged_HASH)
{
return ErrorCode::NetworkConfigurationChanged;
}
else if (hashCode == NoDisksAvailable_HASH)
{
return ErrorCode::NoDisksAvailable;
}
else if (hashCode == NotImplemented_HASH)
{
return ErrorCode::NotImplemented;
}
else if (hashCode == NotSupported_HASH)
{
return ErrorCode::NotSupported;
}
else if (hashCode == OperationAborted_HASH)
{
return ErrorCode::OperationAborted;
}
else if (hashCode == OutdatedGateway_HASH)
{
return ErrorCode::OutdatedGateway;
}
else if (hashCode == ParametersNotImplemented_HASH)
{
return ErrorCode::ParametersNotImplemented;
}
else if (hashCode == RegionInvalid_HASH)
{
return ErrorCode::RegionInvalid;
}
else if (hashCode == RequestTimeout_HASH)
{
return ErrorCode::RequestTimeout;
}
else if (hashCode == ServiceUnavailable_HASH)
{
return ErrorCode::ServiceUnavailable;
}
else if (hashCode == SnapshotDeleted_HASH)
{
return ErrorCode::SnapshotDeleted;
}
else if (hashCode == SnapshotIdInvalid_HASH)
{
return ErrorCode::SnapshotIdInvalid;
}
else if (hashCode == SnapshotInProgress_HASH)
{
return ErrorCode::SnapshotInProgress;
}
else if (hashCode == SnapshotNotFound_HASH)
{
return ErrorCode::SnapshotNotFound;
}
else if (hashCode == SnapshotScheduleNotFound_HASH)
{
return ErrorCode::SnapshotScheduleNotFound;
}
else if (hashCode == StagingAreaFull_HASH)
{
return ErrorCode::StagingAreaFull;
}
else if (hashCode == StorageFailure_HASH)
{
return ErrorCode::StorageFailure;
}
else if (hashCode == TapeCartridgeNotFound_HASH)
{
return ErrorCode::TapeCartridgeNotFound;
}
else if (hashCode == TargetAlreadyExists_HASH)
{
return ErrorCode::TargetAlreadyExists;
}
else if (hashCode == TargetInvalid_HASH)
{
return ErrorCode::TargetInvalid;
}
else if (hashCode == TargetNotFound_HASH)
{
return ErrorCode::TargetNotFound;
}
else if (hashCode == UnauthorizedOperation_HASH)
{
return ErrorCode::UnauthorizedOperation;
}
else if (hashCode == VolumeAlreadyExists_HASH)
{
return ErrorCode::VolumeAlreadyExists;
}
else if (hashCode == VolumeIdInvalid_HASH)
{
return ErrorCode::VolumeIdInvalid;
}
else if (hashCode == VolumeInUse_HASH)
{
return ErrorCode::VolumeInUse;
}
else if (hashCode == VolumeNotFound_HASH)
{
return ErrorCode::VolumeNotFound;
}
else if (hashCode == VolumeNotReady_HASH)
{
return ErrorCode::VolumeNotReady;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<ErrorCode>(hashCode);
}
return ErrorCode::NOT_SET;
}
Aws::String GetNameForErrorCode(ErrorCode enumValue)
{
switch(enumValue)
{
case ErrorCode::ActivationKeyExpired:
return "ActivationKeyExpired";
case ErrorCode::ActivationKeyInvalid:
return "ActivationKeyInvalid";
case ErrorCode::ActivationKeyNotFound:
return "ActivationKeyNotFound";
case ErrorCode::GatewayInternalError:
return "GatewayInternalError";
case ErrorCode::GatewayNotConnected:
return "GatewayNotConnected";
case ErrorCode::GatewayNotFound:
return "GatewayNotFound";
case ErrorCode::GatewayProxyNetworkConnectionBusy:
return "GatewayProxyNetworkConnectionBusy";
case ErrorCode::AuthenticationFailure:
return "AuthenticationFailure";
case ErrorCode::BandwidthThrottleScheduleNotFound:
return "BandwidthThrottleScheduleNotFound";
case ErrorCode::Blocked:
return "Blocked";
case ErrorCode::CannotExportSnapshot:
return "CannotExportSnapshot";
case ErrorCode::ChapCredentialNotFound:
return "ChapCredentialNotFound";
case ErrorCode::DiskAlreadyAllocated:
return "DiskAlreadyAllocated";
case ErrorCode::DiskDoesNotExist:
return "DiskDoesNotExist";
case ErrorCode::DiskSizeGreaterThanVolumeMaxSize:
return "DiskSizeGreaterThanVolumeMaxSize";
case ErrorCode::DiskSizeLessThanVolumeSize:
return "DiskSizeLessThanVolumeSize";
case ErrorCode::DiskSizeNotGigAligned:
return "DiskSizeNotGigAligned";
case ErrorCode::DuplicateCertificateInfo:
return "DuplicateCertificateInfo";
case ErrorCode::DuplicateSchedule:
return "DuplicateSchedule";
case ErrorCode::EndpointNotFound:
return "EndpointNotFound";
case ErrorCode::IAMNotSupported:
return "IAMNotSupported";
case ErrorCode::InitiatorInvalid:
return "InitiatorInvalid";
case ErrorCode::InitiatorNotFound:
return "InitiatorNotFound";
case ErrorCode::InternalError:
return "InternalError";
case ErrorCode::InvalidGateway:
return "InvalidGateway";
case ErrorCode::InvalidEndpoint:
return "InvalidEndpoint";
case ErrorCode::InvalidParameters:
return "InvalidParameters";
case ErrorCode::InvalidSchedule:
return "InvalidSchedule";
case ErrorCode::LocalStorageLimitExceeded:
return "LocalStorageLimitExceeded";
case ErrorCode::LunAlreadyAllocated:
return "LunAlreadyAllocated ";
case ErrorCode::LunInvalid:
return "LunInvalid";
case ErrorCode::MaximumContentLengthExceeded:
return "MaximumContentLengthExceeded";
case ErrorCode::MaximumTapeCartridgeCountExceeded:
return "MaximumTapeCartridgeCountExceeded";
case ErrorCode::MaximumVolumeCountExceeded:
return "MaximumVolumeCountExceeded";
case ErrorCode::NetworkConfigurationChanged:
return "NetworkConfigurationChanged";
case ErrorCode::NoDisksAvailable:
return "NoDisksAvailable";
case ErrorCode::NotImplemented:
return "NotImplemented";
case ErrorCode::NotSupported:
return "NotSupported";
case ErrorCode::OperationAborted:
return "OperationAborted";
case ErrorCode::OutdatedGateway:
return "OutdatedGateway";
case ErrorCode::ParametersNotImplemented:
return "ParametersNotImplemented";
case ErrorCode::RegionInvalid:
return "RegionInvalid";
case ErrorCode::RequestTimeout:
return "RequestTimeout";
case ErrorCode::ServiceUnavailable:
return "ServiceUnavailable";
case ErrorCode::SnapshotDeleted:
return "SnapshotDeleted";
case ErrorCode::SnapshotIdInvalid:
return "SnapshotIdInvalid";
case ErrorCode::SnapshotInProgress:
return "SnapshotInProgress";
case ErrorCode::SnapshotNotFound:
return "SnapshotNotFound";
case ErrorCode::SnapshotScheduleNotFound:
return "SnapshotScheduleNotFound";
case ErrorCode::StagingAreaFull:
return "StagingAreaFull";
case ErrorCode::StorageFailure:
return "StorageFailure";
case ErrorCode::TapeCartridgeNotFound:
return "TapeCartridgeNotFound";
case ErrorCode::TargetAlreadyExists:
return "TargetAlreadyExists";
case ErrorCode::TargetInvalid:
return "TargetInvalid";
case ErrorCode::TargetNotFound:
return "TargetNotFound";
case ErrorCode::UnauthorizedOperation:
return "UnauthorizedOperation";
case ErrorCode::VolumeAlreadyExists:
return "VolumeAlreadyExists";
case ErrorCode::VolumeIdInvalid:
return "VolumeIdInvalid";
case ErrorCode::VolumeInUse:
return "VolumeInUse";
case ErrorCode::VolumeNotFound:
return "VolumeNotFound";
case ErrorCode::VolumeNotReady:
return "VolumeNotReady";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return "";
}
}
} // namespace ErrorCodeMapper
} // namespace Model
} // namespace StorageGateway
} // namespace Aws
| [
"henso@amazon.com"
] | henso@amazon.com |
255e6131640b0864b72b32e008802d3f726e938b | 100000b8c66f0b7a95c8985518e2214f1ede2597 | /Homework 10/Homework 10/HW10Source.cpp | 8d149c4fd2b78547bd142c7ff9f29ca9846494aa | [] | no_license | Kardbord/CS1400 | 9803a3941c544e2eadb31a7966d32c4aaf908deb | 8130b970b7c1c9f85c42e9e4098e1f6ad1a93ea5 | refs/heads/master | 2021-05-11T09:01:28.322815 | 2018-01-19T02:34:25 | 2018-01-19T02:34:25 | 118,066,492 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,841 | cpp | //Tanner Kvarfordt
//A02052217
/*This program uses input from a file to display the average high and low temperatures
over however many days are included in the file. It will also display how many days are
in the file and the number of days that the temperature was below 32 degrees Fahrenheit.*/
#include<iostream>
#include<fstream>
#include<string>
#include<iomanip>
using namespace std;
int main() {
//create input file variable and link it to weather.txt
ifstream inputFile;
inputFile.open("weather.txt");
if (inputFile.fail()) {
cout << "\aError opening weather.txt\n\n";
return 1;
}
//declare any other necessary variables
int entry = 0;
int days = 0; //this will be our counter variable for number of days
int coldDays = 0; //another counter variable for days below freezing
double highTemp = 0, lowTemp = 0; //individual temps for each day
double highTemps = 0, lowTemps = 0; //running totals of high and low temps
double avgHighTemps, avgLowTemps;
string day; //using this to read past the day of the week in the input file and check that weather.txt is formatted correctly
//use a while loop to gather data from weather.txt
while (inputFile >> day) {
entry++;
//check that we are reading days of the week
if (day == "Saturday" || day == "saturday"
|| day == "Sunday" || day == "sunday"
|| day == "Monday" || day == "monday"
|| day == "Tuesday" || day == "tuesday"
|| day == "Wednesday" || day == "wednesday"
|| day == "Thursday" || day == "thursday"
|| day == "Friday" || day == "friday") {
inputFile >> highTemp;
inputFile >> lowTemp;
//check that the high temp is greater than the low temp
if (highTemp < lowTemp) {
cout << "\aWarning! weather.txt is not formatted correctly.\n"
"High and low temperatures are reversed for entry number " << entry << ". \n"
"Entry number " << entry << " will be skipped.\n\n";
}
else {
days++;
highTemps += highTemp;
lowTemps += lowTemp;
//if statement to test for temperatures below freezing
if (highTemp <= 32 || lowTemp <= 32) {
coldDays++;
}
}
}
else {
cout << "\aWarning! weather.txt is not formatted correctly.\n"
"Entry number " << entry << " is not a valid day (" << day << ") and will be skipped.\n\n";
}
}
//close the file
inputFile.close();
//processing to get the average high and low temps
avgHighTemps = highTemps / days;
avgLowTemps = lowTemps / days;
//display output
cout << "Total number of days: " << days << endl;
cout << "Total number of days below freezing: " << coldDays << endl;
cout << setprecision(2) << fixed;
cout << "Average low temperature: " << avgLowTemps << " degrees Fahrenheit." << endl;
cout << "Average high temperature: " << avgHighTemps << " degrees Fahrenheit." << endl;
cout << endl << endl;
return 0;
} | [
"tanner.kvarfordt@aggiemail.usu.edu"
] | tanner.kvarfordt@aggiemail.usu.edu |
e855ae2bb6d2b6401b5a5aa0a49d19522687f9b2 | 2482d7f225d0e2a30fd86fc884d1b09f0f709a67 | /source/piece.h | b2e5cb299e67ccade852f9d7e189906e2af27644 | [] | no_license | EduardGomezEscandell/ConsoleChess | 0f194683b6e6aad16d562077bbf9b132c999d639 | bc2a2ef7e262b320633f4120b2ec0a8597f55b93 | refs/heads/master | 2023-04-27T13:13:18.258816 | 2021-05-10T17:01:38 | 2021-05-10T17:01:38 | 356,655,820 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,428 | h | #ifndef CHESS_PIECE_H
#define CHESS_PIECE_H
#include "defines.h"
#include "move.h"
#include <vector>
#include <memory>
#define CHESS_DEFINE_PIECE_BOILERPLATE(Name, NameCapitalized, Symbol)\
\
Name::Name(const int & rank, \
const int & file, \
Board * parent_board, \
const Colour & colour) \
: Piece(rank, file, parent_board, colour) \
{ \
} \
\
Piece * Name::Clone(Board * parent_board) const \
{ \
Piece * ptr = new Name(*this); \
ptr->ChangeBoard(parent_board); \
return ptr; \
} \
\
char Name::GetPieceCharacter() const \
{ \
static constexpr char c = Symbol; \
return mColour==Colour::BLACK ? c : (c + 'A'-'a'); \
} \
\
PieceSet Name::GetPieceType() const \
{ \
return PieceSet::NameCapitalized; \
} \
namespace ConsoleChess {
class Board;
class Piece
{
public:
// Constructors
Piece(const int & rank, const int & file, Board * parent_board, const Colour & colour);
/**
* @brief Clone: This method allocates a raw pointer and copies the relevant information top clone the piece.
* Ownership is granted to the caller, so it's recomended to use this method only to construct smart pointers.
* @param parent_board: The board that will contain the clone.
* @return Piece*: The raw pointer containing the clone.
*/
virtual Piece * Clone(Board * parent_board) const = 0;
// Editors
virtual void UpdateLegalMoves() = 0;
void SetLocation(const int & rank, const int & file);
void ChangeBoard(Board * rNewBoard);
void SetAliveState(bool alive);
// Getters
bool IsAlive() const;
virtual PieceSet GetPieceType() const = 0;
virtual char GetPieceCharacter() const = 0;
std::vector<Move> & GetMoves();
const std::vector<Move> & GetMoves() const;
Colour GetColour() const;
virtual void RemoveCastlingRights();
// Queries
virtual bool IsInCheck() const;
bool CanMoveTo(const int rank, const int file) const;
virtual bool HasCastlingRights() const;
protected:
bool mIsAlive = true;
int mLocation[2];
Board * mParentBoard;
std::vector<Move> mLegalMoves;
const Colour mColour = Colour::UNDEFINED;
friend class Board;
// Editors
void StraightLineMoveUpdate(const int delta_r, const int delta_f);
// Queries
bool CheckDestinationSquare(const int & rank, const int & file) const;
bool CheckIfCaptures(const int & rank, const int & file) const;
};
}
#endif // CHESS_PIECE_H
| [
"eduard.gomez.escandell@gmail.com"
] | eduard.gomez.escandell@gmail.com |
8c2b55df03516fcbb4a31c25d0888b4b45a61643 | 48e4c9712b38a90b819c84db064422e1088c4565 | /toolchains/motoezx/qt/include/qt-2.3.8/qwssocket_qws.h | d359b1b6d2cfc1299f592979dab894452cfbc564 | [] | no_license | blchinezu/EZX-SDK_CPP-QT-SDL | 8e4605ed5940805f49d76e7700f19023dea9e36b | cbb01e0f1dd03bdf8b071f503c4e3e43b2e6ac33 | refs/heads/master | 2020-06-05T15:25:21.527826 | 2020-05-15T11:11:13 | 2020-05-15T11:11:13 | 39,446,244 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,356 | h | /****************************************************************************
** $Id: qt/src/kernel/qwssocket_qws.h 2.3.8 edited 2004-08-05 $
**
** Definition of QWSSocket and related classes.
**
** Created : 970521
**
** Copyright (C) 1992-2000 Trolltech AS. All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses for Qt/Embedded may use this file in accordance with the
** Qt Embedded Commercial License Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
** information about Qt Commercial License Agreements.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#ifndef QWSSOCKETDEVICE_H
#define QWSSOCKETDEVICE_H
#ifndef QT_H
#include "qsocket.h"
#include "qserversocket.h"
#endif // QT_H
#ifndef QT_NO_QWS_MULTIPROCESS
class QWSSocket : public QSocket
{
Q_OBJECT
public:
QWSSocket( QObject *parent=0, const char *name=0 );
~QWSSocket();
virtual void connectToLocalFile( const QString &file );
private: // Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
QWSSocket( const QWSSocket & );
QWSSocket &operator=( const QWSSocket & );
#endif
};
class QWSServerSocket : public QServerSocket
{
Q_OBJECT
public:
QWSServerSocket( const QString& file, int backlog = 0,
QObject *parent=0, const char *name=0 );
~QWSServerSocket();
private: // Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
QWSServerSocket( const QWSServerSocket & );
QWSServerSocket &operator=( const QWSServerSocket & );
#endif
};
#endif //QT_NO_QWS_MULTIPROCESS
#endif // QWSSOCKETDEVICE_H
| [
"eu.gabii@yahoo.com"
] | eu.gabii@yahoo.com |
cb33b63d556c81ae617c2a28d5bf407a61fe662c | 9bbef6def62136a555bbe5dd6962fe929f5f102d | /lldb/include/lldb/Target/TraceCursor.h | c27bba3abf4cb9a9e740e24d587e10874c8e80b6 | [
"NCSA",
"Apache-2.0",
"LLVM-exception"
] | permissive | jmorse/llvm-project | ca96001f51957966a718d350f51e88580cd96a83 | ee8da6369225f47f85e61e1ef2807af6a8677a0d | refs/heads/master | 2023-07-27T02:18:21.584156 | 2021-07-11T14:10:11 | 2021-07-11T14:10:11 | 183,056,402 | 1 | 0 | null | 2023-03-03T20:51:17 | 2019-04-23T16:39:17 | null | UTF-8 | C++ | false | false | 5,377 | h | //===-- TraceCursor.h -------------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef LLDB_TARGET_TRACE_CURSOR_H
#define LLDB_TARGET_TRACE_CURSOR_H
#include "lldb/lldb-private.h"
namespace lldb_private {
/// Class used for iterating over the instructions of a thread's trace.
///
/// This class attempts to be a generic interface for accessing the instructions
/// of the trace so that each Trace plug-in can reconstruct, represent and store
/// the instruction data in an flexible way that is efficient for the given
/// technology.
///
/// Live processes:
/// In the case of a live process trace, an instance of a \a TraceCursor should
/// point to the trace at the moment it was collected. If the process is later
/// resumed and new trace data is collected, that should leave that old cursor
/// unaffected.
///
/// Errors in the trace:
/// As there could be errors when reconstructing the instructions of a trace,
/// these errors are represented as failed instructions, and the cursor can
/// point at them. The consumer should invoke \a TraceCursor::GetError() to
/// check if the cursor is pointing to either a valid instruction or an error.
///
/// Instructions:
/// A \a TraceCursor always points to a specific instruction or error in the
/// trace.
///
/// The Trace initially points to the last item in the trace.
///
/// Sample usage:
///
/// TraceCursorUP cursor = trace.GetTrace(thread);
///
/// auto granularity = eTraceInstructionControlFlowTypeCall |
/// eTraceInstructionControlFlowTypeReturn;
///
/// do {
/// if (llvm::Error error = cursor->GetError())
/// cout << "error found at: " << llvm::toString(error) << endl;
/// else if (cursor->GetInstructionControlFlowType() &
/// eTraceInstructionControlFlowTypeCall)
/// std::cout << "call found at " << cursor->GetLoadAddress() <<
/// std::endl;
/// else if (cursor->GetInstructionControlFlowType() &
/// eTraceInstructionControlFlowTypeReturn)
/// std::cout << "return found at " << cursor->GetLoadAddress() <<
/// std::endl;
/// } while(cursor->Prev(granularity));
class TraceCursor {
public:
virtual ~TraceCursor() = default;
/// Move the cursor to the next instruction more recent chronologically in the
/// trace given the provided granularity. If such instruction is not found,
/// the cursor doesn't move.
///
/// \param[in] granularity
/// Bitmask granularity filter. The cursor stops at the next
/// instruction that matches the specified granularity.
///
/// \param[in] ignore_errors
/// If \b false, the cursor stops as soon as it finds a failure in the
/// trace and points at it.
///
/// \return
/// \b true if the cursor effectively moved and now points to a different
/// item in the trace, including errors when \b ignore_errors is \b false.
/// In other words, if \b false is returned, then the trace is pointing at
/// the same item in the trace as before.
virtual bool Next(lldb::TraceInstructionControlFlowType granularity =
lldb::eTraceInstructionControlFlowTypeInstruction,
bool ignore_errors = false) = 0;
/// Similar to \a TraceCursor::Next(), but moves backwards chronologically.
virtual bool Prev(lldb::TraceInstructionControlFlowType granularity =
lldb::eTraceInstructionControlFlowTypeInstruction,
bool ignore_errors = false) = 0;
/// Force the cursor to point to the end of the trace, i.e. the most recent
/// item.
virtual void SeekToEnd() = 0;
/// Force the cursor to point to the beginning of the trace, i.e. the oldest
/// item.
virtual void SeekToBegin() = 0;
/// \return
/// \b true if the trace corresponds to a live process who has resumed after
/// the trace cursor was created. Otherwise, including the case in which the
/// process is a post-mortem one, return \b false.
bool IsStale();
/// Instruction or error information
/// \{
/// Get the corresponding error message if the cursor points to an error in
/// the trace.
///
/// \return
/// \b llvm::Error::success if the cursor is not pointing to an error in
/// the trace. Otherwise return an \a llvm::Error describing the issue.
virtual llvm::Error GetError() = 0;
/// \return
/// The load address of the instruction the cursor is pointing at. If the
/// cursor points to an error in the trace, return \b
/// LLDB_INVALID_ADDRESS.
virtual lldb::addr_t GetLoadAddress() = 0;
/// \return
/// The \a lldb::TraceInstructionControlFlowType categories the
/// instruction the cursor is pointing at falls into. If the cursor points
/// to an error in the trace, return \b 0.
virtual lldb::TraceInstructionControlFlowType
GetInstructionControlFlowType() = 0;
/// \}
private:
/// The stop ID when the cursor was created.
uint32_t m_stop_id = 0;
/// The trace that owns this cursor.
lldb::TraceSP m_trace_sp;
};
} // namespace lldb_private
#endif // LLDB_TARGET_TRACE_CURSOR_H
| [
"wallace@fb.com"
] | wallace@fb.com |
9997ceb4aab912b427c1cde4a4c663c97fcccfcf | aad71b18989fb7e67c577b3c9e6309f6475e03b2 | /rootex/framework/entity_factory.h | 043bb13e893f45f9484736573d1acd96efc7dec3 | [
"MIT"
] | permissive | meetcshah19/Rootex | 8bb5f79834777c10966dc5dbd2d0f0ca18a142b5 | 002725f80ee6ce02a01e1d18630f5635ad2a5b0c | refs/heads/master | 2021-05-18T21:50:12.894803 | 2020-07-27T16:33:48 | 2020-07-27T16:33:48 | 251,438,812 | 0 | 0 | MIT | 2020-03-30T22:04:07 | 2020-03-30T22:04:07 | null | UTF-8 | C++ | false | false | 2,369 | h | #pragma once
#include "common/common.h"
#include "resource_file.h"
#include "entity.h"
#include "component.h"
/// Invalid ID for an entity
#define INVALID_ID 0
/// Root entity ID
#define ROOT_ENTITY_ID 1
/// Function pointer to a function that constructs a component, taking in a set of component data.
typedef Component* (*ComponentCreator)(const JSON::json& componentDescription);
/// Function pointer to a function that default constructs a component.
typedef Component* (*ComponentDefaultCreator)();
typedef int EntityID;
/// Collection of a component, its name, and a function that constructs that component.
typedef Vector<Tuple<ComponentID, String, ComponentCreator>> ComponentDatabase;
/// Collection of a component, its name, and a function that constructs a default component.
typedef Vector<Tuple<ComponentID, String, ComponentDefaultCreator>> DefaultComponentDatabase;
class EntityFactory
{
static EntityID s_CurrentID;
static EntityID s_CurrentEditorID;
HashMap<EntityID, Ref<Entity>> m_Entities;
EntityID getNextID();
EntityID getNextEditorID();
protected:
ComponentDatabase m_ComponentCreators;
DefaultComponentDatabase m_DefaultComponentCreators;
EntityFactory();
EntityFactory(EntityFactory&) = delete;
~EntityFactory();
Ref<Entity> createRootEntity();
friend class HierarchyGraph;
Variant deleteEntityEvent(const Event* event);
public:
static void RegisterAPI(sol::state& rootex);
static EntityFactory* GetSingleton();
Ref<Component> createComponent(const String& name, const JSON::json& componentData);
Ref<Component> createDefaultComponent(const String& name);
Ref<Entity> createEntity(TextResourceFile* entityJSONDescription, bool isEditorOnly = false);
/// Get entity by ID.
Ref<Entity> findEntity(EntityID entityID);
void setupLiveEntities();
void addDefaultComponent(Ref<Entity> entity, String componentName);
void addComponent(Ref<Entity> entity, Ref<Component> component);
/// Pass in a boolean that determines whether the Root entity should be saved from destruction or not.
void destroyEntities(bool saveRoot);
void deleteEntity(Ref<Entity> entity);
const ComponentDatabase& getComponentDatabase() const { return m_ComponentCreators; }
const HashMap<EntityID, Ref<Entity>>& getEntities() const { return m_Entities; }
HashMap<EntityID, Ref<Entity>>& getMutableEntities() { return m_Entities; }
};
| [
"wtwarit@gmail.com"
] | wtwarit@gmail.com |
b1cdfe7aec7059aab02d56b2126877b3f2e6e464 | 00f95f1ce60a571faefd214db17442d7d32450c6 | /src/midi/render.cpp | 2d67e368b51846681086028ccf20b973025f1c40 | [] | no_license | emildekeyser/midi-parser | fcff34a6d5a2874fe66e9f8e7442d45cf0ae442d | e452b30bb2a7e85d8c90d253253e65ec71c3ac9b | refs/heads/master | 2023-01-09T22:24:56.619955 | 2020-08-09T13:56:41 | 2020-08-09T13:56:41 | 312,271,949 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,618 | cpp | #include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <sstream>
#include <numeric>
#include <iomanip>
#include "imaging/bitmap.h"
#include "imaging/bmp-format.h"
#include "midi/midi.h"
#include "render.h"
std::map<int, imaging::Color> gen_colors(std::vector<midi::NOTE> notes)
{
imaging::Color available_colors[] = {
imaging::Color(0, 0, 1),
imaging::Color(0, 1, 0),
imaging::Color(0, 1, 1),
imaging::Color(1, 0, 0),
imaging::Color(1, 0, 1),
imaging::Color(1, 1, 0),
imaging::Color(1, 1, 1)
};
std::map<int, imaging::Color> colors;
int i = 0;
for (midi::NOTE n : notes)
{
int ins = value(n.instrument);
if (colors.count(ins) == 0) {
colors[ins] = available_colors[i];
if(i < 7) {
i++;
}
}
}
return colors;
}
double gen_total_height(std::vector<midi::NOTE> notes)
{
std::vector<double> note_ends;
for (midi::NOTE n : notes) {
note_ends.push_back(value(n.start) + value(n.duration));
}
double max = 0;
for (double note_end : note_ends) {
if (note_end > max) {
max = note_end;
}
}
return max;
}
std::pair<double, double> gen_low_high_notes(std::vector<midi::NOTE> notes)
{
double max = 0;
double min = 127;
for (midi::NOTE n : notes) {
if (value(n.note_number) > max) {
max = value(n.note_number);
}
if (value(n.note_number) < min) {
min = value(n.note_number);
}
}
return std::pair<double, double>(min, max);
}
std::string indexed_filename(int index, std::string pattern)
{
std::string filename = pattern;
std::stringstream formatted_index;
formatted_index << std::setfill('0') << std::setw(5) << index;
size_t pos = filename.find("%d");
filename.replace(pos, 2, formatted_index.str());
return filename;
}
void render(Parameters params)
{
std::ifstream ifs(params.midifile);
std::vector<midi::NOTE> notes = midi::read_notes(ifs);
double scale = (double) params.scale / 100.0;
auto color_init = [](Position p){return imaging::Color(0, 0, 0); };
double total_heigth = gen_total_height(notes);
auto bitmap = imaging::Bitmap(params.width, (total_heigth + params.height) * scale, color_init);
auto colors = gen_colors(notes);
auto low_high_notes_pair = gen_low_high_notes(notes);
double low = low_high_notes_pair.first;
double high = low_high_notes_pair.second;
double width = params.width / (high - low + 1);
for (midi::NOTE note : notes) {
if (params.verbose)
std::cout << note << "\n";
double height = value(note.duration) * scale;
double x = (value(note.note_number) - low) * width;
double y = value(note.start) * scale;
auto color = colors[value(note.instrument)];
auto slice = bitmap.slice(x, y, width, height);
auto offset = Position(x, y);
slice->for_each_position([&bitmap, &color, &offset](const Position& p) {
bitmap[offset + p] = color;
});
}
for (double y = 0; y <= total_heigth; y += params.step) {
auto slice = bitmap.slice(0, y, params.width, params.height);
auto filename = indexed_filename(y / params.step, params.pattern);
if (params.verbose)
std::cout << filename << "\n";
imaging::save_as_bmp(filename, *slice);
}
}
| [
"emil.dekeyser@student.ucll.be"
] | emil.dekeyser@student.ucll.be |
f193ef483bff463ebfdf2c17d2c21249364bdb4e | 4ae1d3431c99958b4a79ffb003588738ac5724df | /gengen/staticcodegetter.h | 99fcd336f4708b8552aa5ff918799d49d6f7b9a7 | [
"MIT"
] | permissive | JaDogg/GenGen | 2971e0c0c8c40f1ff0a7dff6e88c9df7bba8a6eb | 29a28ce809095a28683193d55d2291996cc90b47 | refs/heads/master | 2021-01-19T18:10:38.662843 | 2015-02-01T14:52:05 | 2015-02-01T14:52:05 | 30,136,109 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 683 | h | #ifndef STATICCODEGETTER_H
#define STATICCODEGETTER_H
#include <string>
class StaticCodeGetter {
public:
virtual std::string GetBeforePreHeader() = 0; // our header message
virtual std::string GetAfterPreHeader() = 0; // our includes and functions before main()
virtual std::string GetAfterHeader() = 0; // int main(){
virtual std::string GetBeforeFooter() = 0; // }
virtual std::string GetAfterFooter() = 0; // functions after main()
virtual std::string GetAfterPostFooter() = 0; // our post code ex=> if __init__ == '__main__':
virtual unsigned int GetStartingIndent() = 0; // get starting indent of all line code, doesn't affect block code
};
#endif
| [
"jadogg.coder@gmail.com"
] | jadogg.coder@gmail.com |
a09e078eb8dd6367ff30ede189de09fd4d7c2cce | 519c64b3f1a8d8c12121141f9f950db8c31d3ac9 | /Poj/2376.cpp | 3855ebb58af6ba8c050ea127ed4257a0386e8e55 | [] | no_license | Ronnoc/Training | 7c7db931865dd5a7ba222b3c1c384a43459737f0 | 75d16ac8f33dfe0cf47548bf75d35a8b51967184 | refs/heads/master | 2022-11-11T19:57:53.845777 | 2022-11-06T02:54:34 | 2022-11-06T02:54:34 | 13,489,501 | 17 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 1,343 | cpp | #include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <cctype>
#include <cstdio>
#include <string>
#include <vector>
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <sstream>
#include <iostream>
#include <algorithm>
using namespace std;
#define PB push_back
#define MP make_pair
#define AA first
#define BB second
#define OP begin()
#define ED end()
#define SZ size()
#define SORT(x) sort(x.OP,x.ED)
#define SQ(x) ((x)*(x))
#define SSP system("pause")
#define cmin(x,y) x=min(x,y)
#define cmax(x,y) x=max(x,y)
typedef long long LL;
typedef pair<int, int> PII;
const double eps=1e-8;
const double PI=acos( -1. );
const LL MOD = 1000000007;
int G[1000005];
int F[1000005];
int main() {
//freopen("","r",stdin);
//freopen("","w",stdout);
int i,j,k,T;
int n,m;
while(~scanf("%d%d",&n,&m)){
for(i=1;i<=m;i++)G[i]=-1;
for(i=1;i<=n;i++){
int u,v;
scanf("%d%d",&u,&v);
if(u<1)u=1;
if(v>m)v=m;
cmax(G[u],v);
}
F[1]=G[1];
for(i=2;i<=m;i++)F[i]=max(F[i-1],G[i]);
int ans=0;
int where=0;
int fail=0;
while(where<m){
int next=F[where+1];
if(next<where+1){fail=1;break;}
where=next;
ans++;
}
if(!fail)printf("%d\n",ans);
else printf("-1\n");
}
return 0;
}
| [
"kybconnor@126.com"
] | kybconnor@126.com |
6fd6ef50dfc87965adf3ea30720c692658cab3da | fb0969b4687bd3eb8986feacdbd7fc327ed44fe9 | /for_and_arrays/1_7_14.cpp | 7a95d2a9ee56f945fc890d197dc7001b046e87a9 | [] | no_license | chinoiserie/stepik_yandex_cpp | 574cc869d05d564c85280e51080f186257705f5a | 5bd83b5d0c543aca10da8dbd3b7d11ad83da9624 | refs/heads/master | 2020-03-28T18:55:09.538571 | 2018-09-19T20:24:00 | 2018-09-19T20:24:00 | 148,926,731 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,412 | cpp | /* N кеглей выставили в один ряд, занумеровав их слева направо числами от 1 до N. Затем по этому ряду бросили K шаров,
при этом i-й шар сбил все кегли с номерами от li до ri включительно. Определите, какие кегли остались стоять на месте.
Формат входных данных
Программа получает на вход количество кеглей N и количество бросков K. Далее идет K пар чисел li, ri, при этом 1 ≤ li, ri ≤ N.
Формат выходных данных
Программа должна вывести последовательность из N символов, где j-й символ есть “I”, если j-я кегля осталась стоять, или “.”,
если j-я кегля была сбита. */
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector <string> a(n);
for (int i = 0; i < n; i++) {
a[i] = "I";
}
int k, l, r;
cin >> k;
for (int i = 0; i < k; i++) {
cin >> l >> r;
for (int j = (l - 1); j < r; j++) {
a[j] = ".";
}
}
for (auto now : a) {
cout << now;
}
return 0;
}
| [
"noreply@github.com"
] | chinoiserie.noreply@github.com |
848fcf7c4528214efe623f166c525a9484b7ffbf | b2119eea95c182c183913cc3574e75e8689d3130 | /SOURCES/ui/src/common/missions.cpp | 99b17abf6de96f5da054016678a56f5753f8d400 | [
"Unlicense"
] | permissive | 1059444127/Negev-Storm | 11233b1b3741f643ff14b5aa7b6ee08de40ab69f | 86de63e195577339f6e4a94198bedd31833a8be8 | refs/heads/master | 2021-05-28T10:48:53.536896 | 2015-02-08T10:42:15 | 2015-02-08T10:42:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,003 | cpp | //
// Mission Building stuff for the UI
//
//
#include <windows.h>
#include "unit.h"
#include "campwp.h"
#include "campstr.h"
#include "squadron.h"
#include "division.h"
#include "flight.h"
#include "team.h"
#include "find.h"
#include "misseval.h"
#include "camplist.h"
#include "chandler.h"
#include "ui95_ext.h"
#include "cmap.h"
#include "uicomms.h"
#include "userids.h"
#include "textids.h"
#include "classtbl.h"
#include "ui_cmpgn.h"
#include "ACSelect.h"
#include "gps.h"
#include "urefresh.h"
void UpdateMissionWindow(long ID);
void MakeIndividualATO(VU_ID flightID);
void SetupFlightSpecificControls (Flight flt);
void SetSingle_Comms_Ctrls();
extern C_Handler *gMainHandler;
extern VU_ID gSelectedFlightID;
VU_ID gPlayerFlightID=FalconNullId;
VU_ID gCurrentFlightID=FalconNullId;
short gCurrentAircraftNum;
short gPlayerPlane=-1;
long StopLookingforMission=0;
extern short InCleanup;
extern int gTimeModeServer;
extern bool g_bServer;
extern C_Map *gMapMgr;
extern GlobalPositioningSystem *gGps;
static short FlightStatusID[]= // 1 to 1 correspondence with enum list in ui_cmpgn.h
{
TXT_BRIEFING,
TXT_ENROUTE,
TXT_INGRESS,
TXT_PATROL,
TXT_EGRESS,
TXT_RETURNTOBASE,
TXT_LANDING,
};
long GetFlightTime(Flight element)
{
WayPoint wp;
if(!element)
return(0);
wp=element->GetCurrentUnitWP();
if(wp)
return(wp->GetWPDepartureTime());
return(0);
}
short GetFlightStatusID(Flight element)
{
WayPoint wp=NULL;
int found=0;
short ID=0;
if(!element)
return(0);
wp=element->GetCurrentUnitWP();
if(wp)
{
if(wp->GetWPAction() == WP_TAKEOFF)
{
ID=_MIS_BRIEFING;
found = 1;
}
else if(element->GetOverrideWP())
{
ID=_MIS_ENROUTE;
found = 1;
}
else
{
found;
ID=_MIS_RTB;
while ((found == 0) && (wp))
{
if(wp->GetWPAction() == WP_ASSEMBLE)
{
ID=_MIS_ENROUTE;
found=1;
}
else if(wp->GetWPAction() == WP_POSTASSEMBLE)
{
ID=_MIS_EGRESS;
found=1;
}
else if(wp->GetWPFlags() & WPF_TARGET)
{
if
(
element->GetUnitMission() == AMIS_BARCAP ||
element->GetUnitMission() == AMIS_BARCAP2 ||
element->GetUnitMission() == AMIS_HAVCAP ||
element->GetUnitMission() == AMIS_RESCAP ||
element->GetUnitMission() == AMIS_TARCAP ||
element->GetUnitMission() == AMIS_AMBUSHCAP
)
{
ID=_MIS_PATROL;
}
else
{
ID=_MIS_INGRESS;
}
found=1;
}
else if(wp->GetWPAction() == WP_LAND)
{
ID=_MIS_LAND;
found=0;
}
if(wp->GetWPAction() == WP_LAND)
{
wp=NULL;
}
else
{
wp=wp->GetNextWP();
}
}
}
if ((TheCampaign.Flags & CAMP_TACTICAL) && (!found))
{
ID=_MIS_ENROUTE;
}
}
else
{
ID=_MIS_RTB;
}
return(ID);
}
void CheckCampaignFlyButton()
{
C_Window *win;
C_Button *btn;
Flight flt;
short plane;
short Enabled=0;
flt = FalconLocalSession->GetPlayerFlight();
plane = FalconLocalSession->GetPilotSlot();
if ((gCommsMgr) && (gCommsMgr->Online ()))
{
// Don't care about restricting access when online
if(flt && plane != 255)
Enabled=1;
}
else
{
// OW - sylvains checkfly fix
#if 1
if(flt && plane != 255 && GetFlightStatusID(flt) < _MIS_EGRESS)
// ADDED BY S.G. SO UNINITIALIZED FLIGHTS CAN'T TAKE OFF
{
int i, dontEnable = 0;
if (GetFlightStatusID(flt) > _MIS_BRIEFING) {
for (i = 0; i < 4 && dontEnable == 0; i++) {
if (FalconLocalSession->GetPlayerFlight()->plane_stats[i] == AIRCRAFT_AVAILABLE && FalconLocalSession->GetPlayerFlight()->pilots[i] == NO_PILOT)
dontEnable = 1;
}
}
if (!dontEnable)
// END OF ADDED SECTION
Enabled=1;
}
#else
if(flt && plane != 255 && GetFlightStatusID(flt) < _MIS_EGRESS)
Enabled=1;
#endif
}
win=gMainHandler->FindWindow(CP_TOOLBAR);
if(win)
{
btn=(C_Button *)win->FindControl(SINGLE_FLY_CTRL);
if(btn)
{
if(Enabled)
btn->SetFlagBitOn(C_BIT_ENABLED);
else
btn->SetFlagBitOff(C_BIT_ENABLED);
btn->Refresh();
}
btn=(C_Button *)win->FindControl(COMMS_FLY_CTRL);
if(btn)
{
if(Enabled)
btn->SetFlagBitOn(C_BIT_ENABLED);
else
btn->SetFlagBitOff(C_BIT_ENABLED);
btn->Refresh();
}
}
win=gMainHandler->FindWindow(TAC_TOOLBAR_WIN);
if(win)
{
btn=(C_Button *)win->FindControl(SINGLE_FLY_CTRL);
if(btn)
{
if(Enabled)
btn->SetFlagBitOn(C_BIT_ENABLED);
else
btn->SetFlagBitOff(C_BIT_ENABLED);
btn->Refresh();
}
btn=(C_Button *)win->FindControl(COMMS_FLY_CTRL);
if(btn)
{
if(Enabled)
btn->SetFlagBitOn(C_BIT_ENABLED);
else
btn->SetFlagBitOff(C_BIT_ENABLED);
btn->Refresh();
}
}
}
static void MissionSelectCB(long,short hittype,C_Base *control)
{
C_Window *win;
Flight flight;
F4CSECTIONHANDLE *Leave;
if(hittype != C_TYPE_LMOUSEUP)
return;
Leave=UI_Enter(control->Parent_);
win=control->Parent_;
if(win)
{
gCurrentFlightID=((C_Mission*)control)->GetVUID();
gSelectedFlightID=gCurrentFlightID;
flight = (Flight)vuDatabase->Find(gCurrentFlightID);
if(flight && !flight->IsDead())
{
TheCampaign.MissionEvaluator->PreMissionEval(flight,255);
UpdateMissionWindow(win->GetID());
MakeIndividualATO(gCurrentFlightID);
if(gMapMgr)
{
gMapMgr->SetCurrentWaypointList(gCurrentFlightID);
SetupFlightSpecificControls(flight);
gMapMgr->FitFlightPlan();
gMapMgr->DrawMap();
}
}
}
control->SetState(static_cast<short>(control->GetState()|1));
control->Refresh();
CheckCampaignFlyButton();
UI_Leave(Leave);
}
static void SelectMission(C_Base *control)
{
C_Window *win;
Flight flight;
F4CSECTIONHANDLE *Leave;
Leave=UI_Enter(control->Parent_);
win=control->Parent_;
if(win)
{
gCurrentFlightID=((C_Mission*)control)->GetVUID();
gSelectedFlightID=gCurrentFlightID;
flight = (Flight)vuDatabase->Find(gCurrentFlightID);
if(flight && !flight->IsDead())
{
TheCampaign.MissionEvaluator->PreMissionEval(flight,255);
UpdateMissionWindow(win->GetID());
MakeIndividualATO(gCurrentFlightID);
}
}
control->SetState(static_cast<short>(control->GetState()|1));
control->Refresh();
CheckCampaignFlyButton();
UI_Leave(Leave);
}
void FindMissionInBriefing(long ID)
{
C_Window *win;
C_TreeList *tree;
TREELIST *cur;
Flight flight;
win=gMainHandler->FindWindow(ID);
if(win)
{
tree=(C_TreeList *)win->FindControl(MISSION_LIST_TREE);
if(tree)
{
cur=tree->GetRoot();
while(cur)
{
if(cur->Item_ && !(cur->Item_->GetFlags() & C_BIT_INVISIBLE))
{
if(((C_Mission*)cur->Item_)->GetStatusID() < _MIS_EGRESS)
{
flight=(Flight)vuDatabase->Find(((C_Mission*)cur->Item_)->GetVUID());
if(flight)
{
if(flight->GetTotalVehicles())
{
cur->Item_->SetState(1);
if(!StopLookingforMission)
{
MissionSelectCB(cur->ID_,C_TYPE_LMOUSEUP,cur->Item_);
// KLUDGE: Throw player in 1st slot
// KCK: This should be done regardless of online status
// if(!gCommsMgr->Online())
// { // Throw player in 1st slot
RequestACSlot(flight, 0, static_cast<uchar>(flight->GetAdjustedAircraftSlot(0)), 0, 0, 1);
// }
StopLookingforMission=1;
}
else
SelectMission(cur->Item_);
return;
}
}
}
}
cur=cur->Next;
}
}
}
}
UI_Refresher *FindMissionItem(Flight flight)
{
UI_Refresher *urec;
urec = (UI_Refresher*)gGps->Find(flight->GetCampID());
if (urec && urec->Mission_)
{
MissionSelectCB(urec->Mission_->GetID(),C_TYPE_LMOUSEUP,urec->Mission_);
return urec;
}
return NULL;
}
C_Mission *MakeMissionItem(C_TreeList *tree,Flight element)
{
C_Mission *mission;
C_Window *win;
_TCHAR buffer[200];
TREELIST *item;
int ent_mission;
Package package;
WayPoint wp;
if(!element->Final())
return(NULL);
if(TheCampaign.Flags & CAMP_TACTICAL)
{
if (element->GetOwner () != FalconLocalSession->GetTeam ())
{
return NULL;
}
}
else
{
if(element->GetUnitSquadronID() != FalconLocalSession->GetPlayerSquadronID())
return(NULL);
}
if(!tree || !element || !element->GetUnitParent())
return(NULL);
// Create new record
mission=new C_Mission;
if(!mission)
return(NULL);
win=tree->GetParent();
if(!win)
return(NULL);
mission->Setup(element->GetCampID(),0); // ID=element->CampID;
mission->SetFont(win->Font_);
mission->SetClient(tree->GetClient());
mission->SetW(win->ClientArea_[tree->GetClient()].right - win->ClientArea_[tree->GetClient()].left);
mission->SetH(gFontList->GetHeight(tree->GetFont()));
// Set takeoff time string
wp = element->GetFirstUnitWP();
if (wp) { // JPO CTD fix
GetTimeString(wp->GetWPDepartureTime(),buffer);
mission->SetTakeOff(static_cast<short>(tree->GetUserNumber(C_STATE_0)),0,buffer);
mission->SetTakeOffTime(wp->GetWPDepartureTime());
}
// Set Mission Type
ent_mission = element->GetUnitMission();
if (ent_mission == AMIS_ALERT)
ent_mission = AMIS_INTERCEPT;
mission->SetMission(static_cast<short>(tree->GetUserNumber(C_STATE_1)),0,MissStr[ent_mission]);
mission->SetMissionID(static_cast<short>(element->GetUnitMission()));
// Set Package (campID of package)
_stprintf(buffer,"%1d",element->GetUnitParent()->GetCampID());
mission->SetPackage(static_cast<short>(tree->GetUserNumber(C_STATE_2)),0,buffer);
mission->SetPackageID(element->GetUnitParent()->GetCampID());
// Set Mission Status String
mission->SetStatusID(GetFlightStatusID(element));
mission->SetStatus(static_cast<short>(tree->GetUserNumber(C_STATE_3)),0,gStringMgr->GetString(FlightStatusID[mission->GetStatusID()]));
// Set Mission Priority String
package = element->GetUnitPackage();
buffer[1]=0;
// KCK: It seemed more logical to get the priority from the flight, not the package's request
// PJW: Why Kevin you are sooo fucking wrong... and ASK when making changes butt fuck
// buffer[0]=(255 - element->GetUnitPriority()) / 51 + _T('A');
buffer[0]=static_cast<char>((255 - package->GetMissionRequest()->priority) / 51 + _T('A'));
mission->SetPriority(static_cast<short>(tree->GetUserNumber(C_STATE_4)),0,buffer);
mission->SetPriorityID(static_cast<short>(255 - package->GetMissionRequest()->priority));
// Set a callback incase someone actually wants to see this mission
// if (TheCampaign.Flags & CAMP_TACTICAL)
// {
// mission->SetCallback (TacMissionSelectCB);
// }
// else
// {
mission->SetCallback(MissionSelectCB);
// }
// Tack on the VU_ID
mission->SetVUID(element->Id());
mission->SetUserNumber(C_STATE_0,element->GetTeam());
mission->SetUserNumber(C_STATE_1,wp ? wp->GetWPDepartureTime() : 0);
mission->SetUserNumber(C_STATE_2,1000 - element->GetUnitPriority()); // Priority
mission->SetUserNumber(C_STATE_3,element->GetUnitMission());
if (!element->Final() || element->GetUnitMission() == AMIS_ALERT)
{
mission->SetFlagBitOn(C_BIT_INVISIBLE);
}
// Add to tree
item=tree->CreateItem(element->GetCampID(),C_TYPE_ITEM,mission);
mission->SetOwner(item);
if(tree->AddItem(tree->GetRoot(),item))
return(mission);
mission->Cleanup();
delete mission;
delete item;
return(NULL);
}
void MissionUpdateStatus(Flight element,C_Mission *mission)
{
mission->Refresh();
mission->SetStatusID(GetFlightStatusID(element));
mission->SetStatus(gStringMgr->GetString(FlightStatusID[mission->GetStatusID()]));
if(gPlayerFlightID == element->Id())
{
if(mission->GetStatusID() >= _MIS_EGRESS)
{
mission->SetState(static_cast<short>(mission->GetState()&1));
FalconLocalSession->SetPlayerFlight(NULL);
FalconLocalSession->SetPilotSlot(255);
gPlayerFlightID=FalconNullId;
gPlayerPlane=-1;
}
}
mission->Refresh();
if(gCurrentFlightID == element->Id())
{
UpdateMissionWindow(CB_MISSION_SCREEN);
UpdateMissionWindow(TAC_AIRCRAFT);
}
if(gMapMgr)
gMapMgr->UpdateWaypoint(element);
}
void MissionUpdateTime(Flight element,C_Mission *mission)
{
_TCHAR buffer[80];
mission->Refresh();
WayPoint wp = element->GetFirstUnitWP();
if (wp) { // JPO CTD fix
GetTimeString(wp->GetWPDepartureTime(),buffer);
mission->SetTakeOff(buffer);
mission->SetTakeOffTime(wp->GetWPDepartureTime());
}
else
mission->SetTakeOff(_T("Unknown"));
mission->Refresh();
}
void RemoveMissionCB(TREELIST *item)
{
C_Mission *mis;
if(!item)
return;
mis=(C_Mission*)item->Item_;
if(gPlayerFlightID == mis->GetVUID())
{
gPlayerFlightID=FalconNullId;
gPlayerPlane=-1;
}
if(gMapMgr)
gMapMgr->RemoveWaypoints(static_cast<short>(item->Item_->GetUserNumber(0)),item->Item_->GetID() << 8);
if(InCleanup)
return;
if(gCurrentFlightID == mis->GetVUID()) // our mission is being removed... find the next mission in briefing
{
if(TheCampaign.Flags & CAMP_TACTICAL)
{
if (gTimeModeServer||g_bServer)
{
FindMissionInBriefing(TAC_AIRCRAFT);
}
UpdateMissionWindow(TAC_AIRCRAFT);
}
else
{
if (gTimeModeServer||g_bServer)
{
FindMissionInBriefing(CB_MISSION_SCREEN);
UpdateMissionWindow(CB_MISSION_SCREEN);
}
}
}
}
| [
"israelyflightsimulator@gmail.com"
] | israelyflightsimulator@gmail.com |
13040b33274f5b196ee3ca22e4a9ed28e1053615 | 777a11faede97e93799bf14c4885d3c9f674af21 | /DirectProgramming/DPC++FPGA/ReferenceDesigns/db/src/query12/pipe_types.hpp | f7b24c05c2abb67e625fff02413d8e307bbbfcd1 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | delecui/oneAPI-samples | 26ab2acd1646e6d7979efe58226921bbb0c8fdbc | dd944e85680bd5603d13d58ea422757c5ce0c15b | refs/heads/master | 2023-07-16T04:30:10.949547 | 2021-08-16T21:48:44 | 2021-08-16T21:48:44 | 359,517,315 | 1 | 0 | MIT | 2021-08-17T02:25:59 | 2021-04-19T15:58:36 | null | UTF-8 | C++ | false | false | 3,072 | hpp | #ifndef __PIPE_TYPES_H__
#define __PIPE_TYPES_H__
#pragma once
#include <CL/sycl.hpp>
#include <sycl/ext/intel/fpga_extensions.hpp>
#include "../db_utils/StreamingData.hpp"
#include "../dbdata.hpp"
using namespace sycl;
//
// A single row of the ORDERS table
// with a subset of the columns (needed for this query)
//
class OrdersRow {
public:
OrdersRow() : valid(false), orderkey(0), orderpriority(0) {}
OrdersRow(bool v_valid, DBIdentifier v_key, int v_orderpriority)
: valid(v_valid), orderkey(v_key), orderpriority(v_orderpriority) {}
DBIdentifier PrimaryKey() const { return orderkey; }
bool valid;
DBIdentifier orderkey;
int orderpriority;
};
//
// A single row of the LINEITEM table
// with a subset of the columns (needed for this query)
//
class LineItemRow {
public:
LineItemRow()
: valid(false),
orderkey(0),
shipmode(0),
commitdate(0),
shipdate(0),
receiptdate(0) {}
LineItemRow(bool v_valid, DBIdentifier v_key, int v_shipmode,
DBDate v_commitdate, DBDate v_shipdate, DBDate v_receiptdate)
: valid(v_valid),
orderkey(v_key),
shipmode(v_shipmode),
commitdate(v_commitdate),
shipdate(v_shipdate),
receiptdate(v_receiptdate) {}
DBIdentifier PrimaryKey() const { return orderkey; }
bool valid;
DBIdentifier orderkey;
int shipmode;
DBDate commitdate;
DBDate shipdate;
DBDate receiptdate;
};
//
// A row of the join LINEITEM and ORDERS table
//
class JoinedRow {
public:
JoinedRow()
: valid(false),
orderpriority(0),
shipmode(0),
commitdate(0),
shipdate(0),
receiptdate(0) {}
JoinedRow(bool v_valid, DBIdentifier v_key, int v_orderpriority, int v_shipmode,
DBDate v_commitdate, DBDate v_shipdate, DBDate v_receiptdate)
: valid(v_valid),
orderpriority(v_orderpriority),
shipmode(v_shipmode),
commitdate(v_commitdate),
shipdate(v_shipdate),
receiptdate(v_receiptdate) {}
void Join(const OrdersRow& o_row, const LineItemRow& l_row) {
orderpriority = o_row.orderpriority;
shipmode = l_row.shipmode;
commitdate = l_row.commitdate;
shipdate = l_row.shipdate;
receiptdate = l_row.receiptdate;
}
bool valid;
int orderpriority;
int shipmode;
DBDate commitdate;
DBDate shipdate;
DBDate receiptdate;
};
// JOIN window sizes
constexpr int kOrderJoinWindowSize = 4;
constexpr int kLineItemJoinWindowSize = 16;
// pipe data types
using OrdersRowPipeData = StreamingData<OrdersRow, kOrderJoinWindowSize>;
using LineItemRowPipeData = StreamingData<LineItemRow, kLineItemJoinWindowSize>;
using JoinedRowPipeData = StreamingData<JoinedRow, kLineItemJoinWindowSize>;
// the pipes
using OrdersProducerPipe =
pipe<class OrdersProducerPipeClass, OrdersRowPipeData>;
using LineItemProducerPipe =
pipe<class LineItemProducerPipeClass, LineItemRowPipeData>;
using JoinedProducerPipe =
pipe<class JoinedProducerPipeClass, JoinedRowPipeData>;
#endif /* __PIPE_TYPES_H__ */
| [
"noreply@github.com"
] | delecui.noreply@github.com |
cc008d030e816170c6a4ae37bb3c468c8f708fa9 | a805a483de393a9110bb339522a90582f8817367 | /Display.h | fef21f2ad07d330c4ad7505a57c5b4e632ae6324 | [] | no_license | Nanoxium/hpc_cellular_automata | 98900025fe86f59f4173b1cc46e23c8f98f7ad62 | 1c9134863cbde11e972dc411e8a656cbfb97d06b | refs/heads/master | 2023-03-14T16:22:08.808017 | 2020-07-17T12:15:52 | 2020-07-17T12:15:52 | 350,714,700 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 568 | h | #ifndef Display_H_
#define Display_H_
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
struct color{
float r;
float g;
float b;
};
template <class T>
class Display {
public:
Display( T* data, unsigned int sizex, unsigned int sizey, T max );
~Display();
void show();
char waitForKey();
static void groundColorMix( color &col, float x, float min, float max );
private:
T *data_;
unsigned int sizeX_;
unsigned int sizeY_;
unsigned int max_;
cv::Mat img_;
};
#include "Display.cpp"
#endif /* Display_H_ */
| [
"jerome.chetelat@etu.hesge.ch"
] | jerome.chetelat@etu.hesge.ch |
a07213e12d486af036a0e0af20e37ce8a3b1f8a8 | 42ae585ddad8ef6d7d9c28543f119d675a7721d8 | /Codeforces/Educational/80/A. Deadline (IMP - Binary search).cpp | 06c3529325178ecdf3e2a4615deed348388657fa | [] | no_license | arnab9997/DSA-Problems-Personal | d32dd11c1226a244352c43178207ac841542f5a5 | 5d5945178ea67278382b3cc85c2b3f123ac3afcc | refs/heads/main | 2023-01-13T20:11:42.514785 | 2020-11-17T03:16:18 | 2020-11-17T03:16:18 | 313,490,773 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,260 | cpp | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define endl '\n'
#define REP(i, a, n) for(int i=a; i<n; ++i)
#define pb push_back
#define sz(x) (int)((x).size())
#define all(x) (x).begin(), (x).end()
typedef pair<int, int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
#define sq(a) (a)*(a)
const double PI = 3.141592653589793238460;
const ll mod = 1e9+7;
void FAST(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
}
bool comp(const pair<int, int> &a, const pair<int, int> &b){
return (a.first > b.second);
}
int f(int x, int d){
double temp = x + ceil (d / (x + 1));
return temp;
}
int main(){
FAST();
//Code goes past here
int t;
cin >> t;
while(t--){
int n, d;
cin >> n >> d;
int l = 0; r = n; //int l = 1, r = d - 1; -->> Wrong
bool flag = false;
while(l <= r){
int mid = l + (r - l) / 2;
int time = mid + ceil((double)d / (mid + 1));
if(time > d)
r = mid - 1;
else{
if(time <= n){
flag = true;
cout << "YES\n";
break;
}
l = mid + 1;
}
}
if(falg == false)
cout << "NO\n";
}
return 0;
}
| [
"noreply@github.com"
] | arnab9997.noreply@github.com |
78f3e4beba2fe23df3919e8c575d730653d9d546 | d4df1707f1651063e1617a2b86a6b0b79a36b120 | /less_than_k_in_query[l,r]_using_BIT.cpp | ab2c441df371a349fe426bcb0eba8f3fe21ea71a | [] | no_license | naresh9949/Problams | 654b170c1dfed48aefb7c811175fd0bf8f04ad46 | f2e66a4ede9319697366d28bf548c3f2a28d866c | refs/heads/master | 2022-09-18T05:39:10.536231 | 2020-06-04T05:57:18 | 2020-06-04T05:57:18 | 269,272,932 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,936 | cpp | #include<iostream>
using namespace std;
class FenwickTree
{
int size;
int *Tree;
int *ar;
public:
FenwickTree(int n)
{
Tree = new int[n+1];
size = n+1;
memset(Tree,0,size);
}
int GetSum(int index)
{
int pos = index+1;
int sum = 0;
while(pos!=0)
{
sum+=Tree[pos];
pos = GetParent(pos);
}
return sum;
}
void Update(int index,int value)
{
Update_Util(index,value);
}
void Update_Util(int index,int value)
{
int pos = index+1;
while(pos<size)
{
Tree[pos] = Tree[pos]+value;
pos = GetNext(pos);
}
}
void show()
{
cout<<"BIT :";
for(int i=0;i<size;i++)
cout<<Tree[i]<<" ";
cout<<endl;
cout<<"ARR ";
for(int i=0;i<size-1;i++)
cout<<ar[i]<<" ";
cout<<endl;
}
int GetNext(int k)
{
return k + (k & -k);
}
int GetParent(int k)
{
return k - (k & -k);
}
};
struct ArrEle
{
int idx,val;
};
struct Query
{
int l,r,x,idx;
};
bool com1(ArrEle a1,ArrEle a2)
{
return a1.val<a2.val;
}
bool com2(Query a1,Query a2)
{
return a1.x<a2.x;
}
void ans(ArrEle a[],Query Q[],int n,int q)
{
sort(a,a+n,com1);
sort(Q,Q+q,com2);
int cur = 0;
int ans[q];
FenwickTree bit(n);
for(int i=0;i<q;i++)
{
while(a[cur].val<=Q[i].x && cur<n)
{
bit.Update(a[cur].idx+1,1);
cur++;
}
ans[Q[i].idx] = bit.GetSum(Q[i].r+1)-bit.GetSum(Q[i].l);
}
for(int i=0;i<q;i++)
cout<<ans[i]<<" ";
cout<<endl;
}
int main()
{
ArrEle a[5];
a[0].val = 2;
a[0].idx = 0;
a[1].val = 3;
a[1].idx = 1;
a[2].val = 4;
a[2].idx = 2;
a[3].val = 5;
a[3].idx = 3;
a[4].val = -5;
a[4].idx = 4;
Query Q[2];
Q[0].l = 0;
Q[0].r = 2;
Q[0].x = 2;
Q[0].idx = 0;
Q[1].l = 0;
Q[1].r = 3;
Q[1].x = 5;
Q[1].idx = 1;
ans(a,Q,5,2);
FenwickTree f(5);
f.Update(1,1);
} | [
"noreply@github.com"
] | naresh9949.noreply@github.com |
42ebf8c1402d81c926ac1d3c29dfc91313306215 | bd8bcdb88c102a1ddf2c0f429dbef392296b67af | /include/fengine/IO/Crypto/DecryptionException.h | 6239efde4b21add78b9b21041b260f8b1ded655c | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | LukasBanana/ForkENGINE | be03cee942b0e20e30a01318c2639de87a72c79c | 8b575bd1d47741ad5025a499cb87909dbabc3492 | refs/heads/master | 2020-05-23T09:08:44.864715 | 2017-01-30T16:35:34 | 2017-01-30T16:35:34 | 80,437,868 | 14 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 856 | h | /*
* Decryption exception header
*
* This file is part of the "ForkENGINE" (Copyright (c) 2014 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#ifndef __FORK_DECRYPTION_EXCEPTION_H__
#define __FORK_DECRYPTION_EXCEPTION_H__
#include "Core/Exception/DefaultException.h"
namespace Fork
{
/**
Decryption exception.
\ingroup fork_exception
*/
class FORK_EXPORT DecryptionException : public DefaultException
{
public:
DecryptionException(
const std::string& decryptionMethod, const std::string& errorDesc) :
DefaultException
{
"DecryptionException",
"Encryption: " + decryptionMethod + ", Description: " + errorDesc
}
{
}
};
} // /namespace Fork
#endif
// ======================== | [
"lukas.hermanns90@gmail.com"
] | lukas.hermanns90@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.