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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e21dcb13b199e44988e7247e78db463b205cc524 | f5884f3ab6d4c57e658a49a0ccf4e24aaf45ff06 | /mds3d_td3/src/viewer.h | 88b2b3262413b0936fda4a7e71d677dfce2426a0 | [] | no_license | Komroh/Monde3D | 894fa2a846b91f1ca2516913dd419d54c07062b5 | fd139c4c548ef55efcbe96618e4a8d67785cab3c | refs/heads/master | 2021-11-30T09:13:39.536731 | 2019-03-21T11:25:25 | 2019-03-21T11:25:25 | 170,553,073 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,104 | h | #ifndef VIEWER_H
#define VIEWER_H
#include "opengl.h"
#include "shader.h"
#include "camera.h"
#include "trackball.h"
#include "mesh.h"
#include <iostream>
class Viewer{
public:
//! Constructor
Viewer();
virtual ~Viewer();
// gl stuff
void init(int w, int h);
void drawScene2D();
void drawScene();
void updateAndDrawScene();
void reshape(int w, int h);
void loadShaders();
// events
void mousePressed(GLFWwindow* window, int button, int action);
void mouseMoved(int x, int y);
void mouseScroll(double x, double y);
void keyPressed(int key, int action, int mods);
void charPressed(int key);
private:
int _winWidth, _winHeight;
Camera _cam;
Shader _shader;
Mesh _mesh;
float _value;
float _theta;
Eigen::Vector2f _translat;
// Mouse parameters for the trackball
enum TrackMode
{
TM_NO_TRACK=0, TM_ROTATE_AROUND, TM_ZOOM,
TM_LOCAL_ROTATE, TM_FLY_Z, TM_FLY_PAN
};
TrackMode _trackingMode = TM_NO_TRACK;
Trackball _trackball;
Eigen::Vector2i _lastMousePos;
};
#endif
| [
"maxime.pacaud@etu.u-bordeaux.fr"
] | maxime.pacaud@etu.u-bordeaux.fr |
a0bb92267d8a62cd4c0a0eca9de6d91e9cd43719 | 1341ebf56cee66f15431236c74e8bb1db02558ac | /components/password_manager/core/browser/password_save_manager.h | 02a3297c9176609d21befb95b6b28377b29953a0 | [
"BSD-3-Clause"
] | permissive | nerdooit/chromium | 41584349b52e0b941ec45ebb5ba5695268e5872f | de77d445d3428ef72455c3b0d9be7e050d447135 | refs/heads/master | 2023-01-11T20:03:40.846099 | 2020-01-25T12:45:08 | 2020-01-25T12:45:08 | 236,195,538 | 1 | 0 | BSD-3-Clause | 2020-01-25T16:25:12 | 2020-01-25T16:25:11 | null | UTF-8 | C++ | false | false | 3,643 | h | // Copyright 2019 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 COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_SAVE_MANAGER_H_
#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_SAVE_MANAGER_H_
#include "base/macros.h"
#include "components/password_manager/core/browser/password_store.h"
namespace autofill {
struct FormData;
struct PasswordForm;
} // namespace autofill
namespace password_manager {
class PasswordManagerClient;
class FormFetcher;
class VotesUploader;
class FormSaver;
class PasswordFormMetricsRecorder;
class PasswordManagerDriver;
// Implementations of this interface should encapsulate the password Save/Update
// logic. One implementation of this class will provide the Save/Update logic in
// case of multiple password stores. This ensures that the PasswordFormManager
// stays agnostic to whether one password store or multiple password stores are
// active. While FormSaver abstracts the implementation of different
// operations (e.g. Save()), PasswordSaveManager is responsible for deciding
// what and where to Save().
class PasswordSaveManager {
public:
PasswordSaveManager() = default;
virtual ~PasswordSaveManager() = default;
virtual void Init(PasswordManagerClient* client,
const FormFetcher* form_fetcher,
scoped_refptr<PasswordFormMetricsRecorder> metrics_recorder,
VotesUploader* votes_uploader) = 0;
virtual const autofill::PasswordForm* GetPendingCredentials() const = 0;
virtual const base::string16& GetGeneratedPassword() const = 0;
virtual FormSaver* GetFormSaver() const = 0;
// Create pending credentials from |parsed_submitted_form| and
// |parsed_observed_form| and |submitted_form|.
virtual void CreatePendingCredentials(
const autofill::PasswordForm& parsed_submitted_form,
const autofill::FormData& observed_form,
const autofill::FormData& submitted_form,
bool is_http_auth,
bool is_credential_api_save) = 0;
virtual void Save(const autofill::FormData& observed_form,
const autofill::PasswordForm& parsed_submitted_form) = 0;
virtual void Update(const autofill::PasswordForm& credentials_to_update,
const autofill::FormData& observed_form,
const autofill::PasswordForm& parsed_submitted_form) = 0;
virtual void PermanentlyBlacklist(
const PasswordStore::FormDigest& form_digest) = 0;
virtual void Unblacklist(const PasswordStore::FormDigest& form_digest) = 0;
// Called when generated password is accepted or changed by user.
virtual void PresaveGeneratedPassword(autofill::PasswordForm parsed_form) = 0;
// Called when user wants to start generation flow for |generated|.
virtual void GeneratedPasswordAccepted(
autofill::PasswordForm parsed_form,
base::WeakPtr<PasswordManagerDriver> driver) = 0;
// Signals that the user cancels password generation.
virtual void PasswordNoLongerGenerated() = 0;
// Moves the pending credentials together with any other PSL matched ones from
// the profile store to the account store.
virtual void MoveCredentialsToAccountStore() = 0;
virtual bool IsNewLogin() const = 0;
virtual bool IsPasswordUpdate() const = 0;
virtual bool HasGeneratedPassword() const = 0;
virtual std::unique_ptr<PasswordSaveManager> Clone() = 0;
private:
DISALLOW_COPY_AND_ASSIGN(PasswordSaveManager);
};
} // namespace password_manager
#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_SAVE_MANAGER_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
aa579ede8adf9dfa06e8ca81f5a421ccbf12c2b9 | 5a5328c0ad39230779aa52c9ae57ec193b88941e | /tesseract4android/src/main/cpp/tesseract/src/src/textord/bbgrid.cpp | e186cc15a2d842d32368e5ad5079213c533b7de8 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | permissive | adaptech-cz/Tesseract4Android | 66978579ccc80587b8a0ae3eebe79f152fa382cd | 8ae584f54502d5457c8b9d62401eaa99551352c3 | refs/heads/master | 2023-07-21T16:49:39.617935 | 2023-07-18T12:13:29 | 2023-07-18T12:13:29 | 168,021,668 | 517 | 101 | Apache-2.0 | 2021-03-29T11:52:21 | 2019-01-28T19:21:34 | C | UTF-8 | C++ | false | false | 10,537 | cpp | ///////////////////////////////////////////////////////////////////////
// File: bbgrid.cpp
// Description: Class to hold BLOBNBOXs in a grid for fast access
// to neighbours.
// Author: Ray Smith
//
// (C) Copyright 2007, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#include "bbgrid.h"
#include "helpers.h"
#include "ocrblock.h"
namespace tesseract {
///////////////////////////////////////////////////////////////////////
// BBGrid IMPLEMENTATION.
///////////////////////////////////////////////////////////////////////
GridBase::GridBase(int gridsize, const ICOORD &bleft, const ICOORD &tright) {
Init(gridsize, bleft, tright);
}
// Destructor.
// It is defined here, so the compiler can create a single vtable
// instead of weak vtables in every compilation unit.
GridBase::~GridBase() = default;
// (Re)Initialize the grid. The gridsize is the size in pixels of each cell,
// and bleft, tright are the bounding box of everything to go in it.
void GridBase::Init(int gridsize, const ICOORD &bleft, const ICOORD &tright) {
gridsize_ = gridsize;
bleft_ = bleft;
tright_ = tright;
if (gridsize_ == 0) {
gridsize_ = 1;
}
gridwidth_ = (tright.x() - bleft.x() + gridsize_ - 1) / gridsize_;
gridheight_ = (tright.y() - bleft.y() + gridsize_ - 1) / gridsize_;
gridbuckets_ = gridwidth_ * gridheight_;
}
// Compute the given grid coordinates from image coords.
void GridBase::GridCoords(int x, int y, int *grid_x, int *grid_y) const {
*grid_x = (x - bleft_.x()) / gridsize_;
*grid_y = (y - bleft_.y()) / gridsize_;
ClipGridCoords(grid_x, grid_y);
}
// Clip the given grid coordinates to fit within the grid.
void GridBase::ClipGridCoords(int *x, int *y) const {
*x = ClipToRange(*x, 0, gridwidth_ - 1);
*y = ClipToRange(*y, 0, gridheight_ - 1);
}
IntGrid::IntGrid() {
grid_ = nullptr;
}
IntGrid::IntGrid(int gridsize, const ICOORD &bleft, const ICOORD &tright) : grid_(nullptr) {
Init(gridsize, bleft, tright);
}
IntGrid::~IntGrid() {
delete[] grid_;
}
// (Re)Initialize the grid. The gridsize is the size in pixels of each cell,
// and bleft, tright are the bounding box of everything to go in it.
void IntGrid::Init(int gridsize, const ICOORD &bleft, const ICOORD &tright) {
GridBase::Init(gridsize, bleft, tright);
delete[] grid_;
grid_ = new int[gridbuckets_];
Clear();
}
// Clear all the ints in the grid to zero.
void IntGrid::Clear() {
for (int i = 0; i < gridbuckets_; ++i) {
grid_[i] = 0;
}
}
// Rotate the grid by rotation, keeping cell contents.
// rotation must be a multiple of 90 degrees.
// NOTE: due to partial cells, cell coverage in the rotated grid will be
// inexact. This is why there is no Rotate for the generic BBGrid.
// TODO(rays) investigate fixing this inaccuracy by moving the origin after
// rotation.
void IntGrid::Rotate(const FCOORD &rotation) {
ASSERT_HOST(rotation.x() == 0.0f || rotation.y() == 0.0f);
ICOORD old_bleft(bleft());
// ICOORD old_tright(tright());
int old_width = gridwidth();
int old_height = gridheight();
TBOX box(bleft(), tright());
box.rotate(rotation);
int *old_grid = grid_;
grid_ = nullptr;
Init(gridsize(), box.botleft(), box.topright());
// Iterate over the old grid, copying data to the rotated position in the new.
int oldi = 0;
FCOORD x_step(rotation);
x_step *= gridsize();
for (int oldy = 0; oldy < old_height; ++oldy) {
FCOORD line_pos(old_bleft.x(), old_bleft.y() + gridsize() * oldy);
line_pos.rotate(rotation);
for (int oldx = 0; oldx < old_width; ++oldx, line_pos += x_step, ++oldi) {
int grid_x, grid_y;
GridCoords(static_cast<int>(line_pos.x() + 0.5), static_cast<int>(line_pos.y() + 0.5),
&grid_x, &grid_y);
grid_[grid_y * gridwidth() + grid_x] = old_grid[oldi];
}
}
delete[] old_grid;
}
// Returns a new IntGrid containing values equal to the sum of all the
// neighbouring cells. The returned grid must be deleted after use.
// For ease of implementation, edge cells are double counted, to make them
// have the same range as the non-edge cells.
IntGrid *IntGrid::NeighbourhoodSum() const {
auto *sumgrid = new IntGrid(gridsize(), bleft(), tright());
for (int y = 0; y < gridheight(); ++y) {
for (int x = 0; x < gridwidth(); ++x) {
int cell_count = 0;
for (int yoffset = -1; yoffset <= 1; ++yoffset) {
for (int xoffset = -1; xoffset <= 1; ++xoffset) {
int grid_x = x + xoffset;
int grid_y = y + yoffset;
ClipGridCoords(&grid_x, &grid_y);
cell_count += GridCellValue(grid_x, grid_y);
}
}
if (GridCellValue(x, y) > 1) {
sumgrid->SetGridCell(x, y, cell_count);
}
}
}
return sumgrid;
}
// Returns true if more than half the area of the rect is covered by grid
// cells that are over the threshold.
bool IntGrid::RectMostlyOverThreshold(const TBOX &rect, int threshold) const {
int min_x, min_y, max_x, max_y;
GridCoords(rect.left(), rect.bottom(), &min_x, &min_y);
GridCoords(rect.right(), rect.top(), &max_x, &max_y);
int total_area = 0;
for (int y = min_y; y <= max_y; ++y) {
for (int x = min_x; x <= max_x; ++x) {
int value = GridCellValue(x, y);
if (value > threshold) {
TBOX cell_box(x * gridsize_, y * gridsize_, (x + 1) * gridsize_, (y + 1) * gridsize_);
cell_box &= rect; // This is in-place box intersection.
total_area += cell_box.area();
}
}
}
return total_area * 2 > rect.area();
}
// Returns true if any cell value in the given rectangle is zero.
bool IntGrid::AnyZeroInRect(const TBOX &rect) const {
int min_x, min_y, max_x, max_y;
GridCoords(rect.left(), rect.bottom(), &min_x, &min_y);
GridCoords(rect.right(), rect.top(), &max_x, &max_y);
for (int y = min_y; y <= max_y; ++y) {
for (int x = min_x; x <= max_x; ++x) {
if (GridCellValue(x, y) == 0) {
return true;
}
}
}
return false;
}
// Returns a full-resolution binary pix in which each cell over the given
// threshold is filled as a black square. pixDestroy after use.
// Edge cells, which have a zero 4-neighbour, are not marked.
Image IntGrid::ThresholdToPix(int threshold) const {
Image pix = pixCreate(tright().x() - bleft().x(), tright().y() - bleft().y(), 1);
int cellsize = gridsize();
for (int y = 0; y < gridheight(); ++y) {
for (int x = 0; x < gridwidth(); ++x) {
if (GridCellValue(x, y) > threshold && GridCellValue(x - 1, y) > 0 &&
GridCellValue(x + 1, y) > 0 && GridCellValue(x, y - 1) > 0 &&
GridCellValue(x, y + 1) > 0) {
pixRasterop(pix, x * cellsize, tright().y() - ((y + 1) * cellsize), cellsize, cellsize,
PIX_SET, nullptr, 0, 0);
}
}
}
return pix;
}
// Make a Pix of the correct scaled size for the TraceOutline functions.
static Image GridReducedPix(const TBOX &box, int gridsize, ICOORD bleft, int *left, int *bottom) {
// Compute grid bounds of the outline and pad all round by 1.
int grid_left = (box.left() - bleft.x()) / gridsize - 1;
int grid_bottom = (box.bottom() - bleft.y()) / gridsize - 1;
int grid_right = (box.right() - bleft.x()) / gridsize + 1;
int grid_top = (box.top() - bleft.y()) / gridsize + 1;
*left = grid_left;
*bottom = grid_bottom;
return pixCreate(grid_right - grid_left + 1, grid_top - grid_bottom + 1, 1);
}
// Helper function to return a scaled Pix with one pixel per grid cell,
// set (black) where the given outline enters the corresponding grid cell,
// and clear where the outline does not touch the grid cell.
// Also returns the grid coords of the bottom-left of the Pix, in *left
// and *bottom, which corresponds to (0, 0) on the Pix.
// Note that the Pix is used upside-down, with (0, 0) being the bottom-left.
Image TraceOutlineOnReducedPix(C_OUTLINE *outline, int gridsize, ICOORD bleft, int *left,
int *bottom) {
const TBOX &box = outline->bounding_box();
Image pix = GridReducedPix(box, gridsize, bleft, left, bottom);
int wpl = pixGetWpl(pix);
l_uint32 *data = pixGetData(pix);
int length = outline->pathlength();
ICOORD pos = outline->start_pos();
for (int i = 0; i < length; ++i) {
int grid_x = (pos.x() - bleft.x()) / gridsize - *left;
int grid_y = (pos.y() - bleft.y()) / gridsize - *bottom;
SET_DATA_BIT(data + grid_y * wpl, grid_x);
pos += outline->step(i);
}
return pix;
}
#if 0 // Example code shows how to use TraceOutlineOnReducedPix.
C_OUTLINE_IT ol_it(blob->cblob()->out_list());
int grid_left, grid_bottom;
Pix* pix = TraceOutlineOnReducedPix(ol_it.data(), gridsize_, bleft_,
&grid_left, &grid_bottom);
grid->InsertPixPtBBox(grid_left, grid_bottom, pix, blob);
pix.destroy();
#endif
// As TraceOutlineOnReducedPix above, but on a BLOCK instead of a C_OUTLINE.
Image TraceBlockOnReducedPix(BLOCK *block, int gridsize, ICOORD bleft, int *left, int *bottom) {
const TBOX &box = block->pdblk.bounding_box();
Image pix = GridReducedPix(box, gridsize, bleft, left, bottom);
int wpl = pixGetWpl(pix);
l_uint32 *data = pixGetData(pix);
ICOORDELT_IT it(block->pdblk.poly_block()->points());
for (it.mark_cycle_pt(); !it.cycled_list();) {
ICOORD pos = *it.data();
it.forward();
ICOORD next_pos = *it.data();
ICOORD line_vector = next_pos - pos;
int major, minor;
ICOORD major_step, minor_step;
line_vector.setup_render(&major_step, &minor_step, &major, &minor);
int accumulator = major / 2;
while (pos != next_pos) {
int grid_x = (pos.x() - bleft.x()) / gridsize - *left;
int grid_y = (pos.y() - bleft.y()) / gridsize - *bottom;
SET_DATA_BIT(data + grid_y * wpl, grid_x);
pos += major_step;
accumulator += minor;
if (accumulator >= major) {
accumulator -= major;
pos += minor_step;
}
}
}
return pix;
}
} // namespace tesseract.
| [
"posel@adaptech.cz"
] | posel@adaptech.cz |
df8459340701af2b458f83f37a8d8e0f74f67b5b | 19feb0913fc72ddc15b3b78f3a1ee2a2c1a45c80 | /Implementing Graphs with Maps and Sets (and Dijkstras Shortest Path Algorithm)/dijkstra.cpp | 5f2738621a5c59f98e1938c5d36c581c1d2fdb33 | [] | no_license | heqiao1017/Data-Structure-Implementation-and-Analysis | d2126c12ffd6cb09a294369c509694384d1a6e36 | cd264c2eb376860b279540e13bee9b89c987a96e | refs/heads/master | 2021-01-02T09:40:17.255822 | 2017-08-03T20:50:12 | 2017-08-03T20:50:12 | 99,270,104 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,231 | cpp | #include <string>
#include <iostream>
#include <fstream>
#include "ics46goody.hpp"
#include "array_queue.hpp"
#include "hash_graph.hpp"
#include "dijkstra.hpp"
std::string get_node_in_graph(const ics::DistGraph& g, std::string prompt, bool allow_QUIT) {
std::string node;
for(;;) {
node = ics::prompt_string(prompt + " (must be in graph" + (allow_QUIT ? " or QUIT" : "") + ")");
if ( (allow_QUIT && node == "QUIT") || g.has_node(node) )
break;
}
return node;
}
int main() {
try {
std::ifstream in_graph;
ics::safe_open(in_graph,"Enter graph file name","flightcost.txt");
ics::DistGraph graph;
graph.load(in_graph);
std::cout<<graph;
std::string start = get_node_in_graph(graph,"\nEnter start node",true);
auto answer_map=ics::extended_dijkstra(graph,start);
std::cout<<answer_map<<std::endl;
for(;;) {
std::string end = get_node_in_graph(graph,"\nEnter stop node",true);
if (end == "QUIT")
break;
std::cout<<"Cost is "<<answer_map[end].cost<<"; path is "<<recover_path(answer_map,end)<<std::endl;
}
} catch (ics::IcsError& e) {
std::cout << e.what() << std::endl;
}
return 0;
}
| [
"noreply@github.com"
] | heqiao1017.noreply@github.com |
6f60eb5f14e640a636e1a23e01411d850273dfaf | e27f9d4c48355b5ea6d562aae35b7ca46ed3fc1c | /src/tools/clang/tools/extra/modularize/ModuleAssistant.cpp | 3d2b99414b8ff29c81fbf72ccb9ce4557402cd4b | [
"NCSA"
] | permissive | dongAxis/clang-700.0.72 | 67c4bb38b77e63da966e5dbd4e6ea7b6725b2484 | 513e64095d87e15954b41a22da367552a1c4dcc4 | refs/heads/master | 2021-01-10T12:17:26.230788 | 2016-02-04T04:29:53 | 2016-02-04T04:29:53 | 51,051,978 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,733 | cpp | //===--- ModuleAssistant.cpp - Module map generation manager -*- C++ -*---===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===---------------------------------------------------------------------===//
//
// This file defines the module generation entry point function,
// createModuleMap, a Module class for representing a module,
// and various implementation functions for doing the underlying
// work, described below.
//
// The "Module" class represents a module, with members for storing the module
// name, associated header file names, and sub-modules, and an "output"
// function that recursively writes the module definitions.
//
// The "createModuleMap" function implements the top-level logic of the
// assistant mode. It calls a loadModuleDescriptions function to walk
// the header list passed to it and creates a tree of Module objects
// representing the module hierarchy, represented by a "Module" object,
// the "RootModule". This root module may or may not represent an actual
// module in the module map, depending on the "--root-module" option passed
// to modularize. It then calls a writeModuleMap function to set up the
// module map file output and walk the module tree, outputting the module
// map file using a stream obtained and managed by an
// llvm::tool_output_file object.
//
//===---------------------------------------------------------------------===//
#include "Modularize.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/ToolOutputFile.h"
#include <vector>
// Local definitions:
namespace {
// Internal class definitions:
// Represents a module.
class Module {
public:
Module(llvm::StringRef Name);
Module();
~Module();
bool output(llvm::raw_fd_ostream &OS, int Indent);
Module *findSubModule(llvm::StringRef SubName);
public:
std::string Name;
std::vector<std::string> HeaderFileNames;
std::vector<Module *> SubModules;
};
} // end anonymous namespace.
// Module functions:
// Constructors.
Module::Module(llvm::StringRef Name) : Name(Name) {}
Module::Module() {}
// Destructor.
Module::~Module() {
// Free submodules.
while (!SubModules.empty()) {
Module *last = SubModules.back();
SubModules.pop_back();
delete last;
}
}
// Write a module hierarchy to the given output stream.
bool Module::output(llvm::raw_fd_ostream &OS, int Indent) {
// If this is not the nameless root module, start a module definition.
if (Name.size() != 0) {
OS.indent(Indent);
OS << "module " << Name << " {\n";
Indent += 2;
}
// Output submodules.
for (std::vector<Module *>::iterator I = SubModules.begin(),
E = SubModules.end();
I != E; ++I) {
if (!(*I)->output(OS, Indent))
return false;
}
// Output header files.
for (std::vector<std::string>::iterator I = HeaderFileNames.begin(),
E = HeaderFileNames.end();
I != E; ++I) {
OS.indent(Indent);
OS << "header \"" << *I << "\"\n";
}
// If this module has header files, output export directive.
if (HeaderFileNames.size() != 0) {
OS.indent(Indent);
OS << "export *\n";
}
// If this is not the nameless root module, close the module definition.
if (Name.size() != 0) {
Indent -= 2;
OS.indent(Indent);
OS << "}\n";
}
return true;
}
// Lookup a sub-module.
Module *Module::findSubModule(llvm::StringRef SubName) {
for (std::vector<Module *>::iterator I = SubModules.begin(),
E = SubModules.end();
I != E; ++I) {
if ((*I)->Name == SubName)
return *I;
}
return nullptr;
}
// Implementation functions:
// Reserved keywords in module.map syntax.
// Keep in sync with keywords in module map parser in Lex/ModuleMap.cpp,
// such as in ModuleMapParser::consumeToken().
static const char *ReservedNames[] = {
"config_macros", "export", "module", "conflict", "framework",
"requires", "exclude", "header", "private", "explicit",
"link", "umbrella", "extern", "use", nullptr // Flag end.
};
// Convert module name to a non-keyword.
// Prepends a '_' to the name if and only if the name is a keyword.
static std::string
ensureNoCollisionWithReservedName(llvm::StringRef MightBeReservedName) {
std::string SafeName = MightBeReservedName;
for (int Index = 0; ReservedNames[Index] != nullptr; ++Index) {
if (MightBeReservedName == ReservedNames[Index]) {
SafeName.insert(0, "_");
break;
}
}
return SafeName;
}
// Add one module, given a header file path.
static bool addModuleDescription(Module *RootModule,
llvm::StringRef HeaderFilePath,
llvm::StringRef HeaderPrefix,
DependencyMap &Dependencies) {
Module *CurrentModule = RootModule;
DependentsVector &FileDependents = Dependencies[HeaderFilePath];
std::string FilePath;
// Strip prefix.
// HeaderFilePath should be compared to natively-canonicalized Prefix.
llvm::SmallString<256> NativePath, NativePrefix;
llvm::sys::path::native(HeaderFilePath, NativePath);
llvm::sys::path::native(HeaderPrefix, NativePrefix);
if (NativePath.startswith(NativePrefix))
FilePath = NativePath.substr(NativePrefix.size() + 1);
else
FilePath = HeaderFilePath;
int Count = FileDependents.size();
// Headers that go into modules must not depend on other files being
// included first. If there are any dependents, warn user and omit.
if (Count != 0) {
llvm::errs() << "warning: " << FilePath
<< " depends on other headers being included first,"
" meaning the module.map won't compile."
" This header will be omitted from the module map.\n";
return true;
}
// Make canonical.
std::replace(FilePath.begin(), FilePath.end(), '\\', '/');
// Insert module into tree, using subdirectories as submodules.
for (llvm::sys::path::const_iterator I = llvm::sys::path::begin(FilePath),
E = llvm::sys::path::end(FilePath);
I != E; ++I) {
if ((*I)[0] == '.')
continue;
std::string Stem = llvm::sys::path::stem(*I);
Stem = ensureNoCollisionWithReservedName(Stem);
Module *SubModule = CurrentModule->findSubModule(Stem);
if (!SubModule) {
SubModule = new Module(Stem);
CurrentModule->SubModules.push_back(SubModule);
}
CurrentModule = SubModule;
}
// Add header file name to headers.
CurrentModule->HeaderFileNames.push_back(FilePath);
return true;
}
// Create the internal module tree representation.
static Module *loadModuleDescriptions(
llvm::StringRef RootModuleName, llvm::ArrayRef<std::string> HeaderFileNames,
DependencyMap &Dependencies, llvm::StringRef HeaderPrefix) {
// Create root module.
Module *RootModule = new Module(RootModuleName);
llvm::SmallString<256> CurrentDirectory;
llvm::sys::fs::current_path(CurrentDirectory);
// If no header prefix, use current directory.
if (HeaderPrefix.size() == 0)
HeaderPrefix = CurrentDirectory;
// Walk the header file names and output the module map.
for (llvm::ArrayRef<std::string>::iterator I = HeaderFileNames.begin(),
E = HeaderFileNames.end();
I != E; ++I) {
// Add as a module.
if (!addModuleDescription(RootModule, *I, HeaderPrefix, Dependencies))
return nullptr;
}
return RootModule;
}
// Kick off the writing of the module map.
static bool writeModuleMap(llvm::StringRef ModuleMapPath,
llvm::StringRef HeaderPrefix, Module *RootModule) {
llvm::SmallString<256> HeaderDirectory(ModuleMapPath);
llvm::sys::path::remove_filename(HeaderDirectory);
llvm::SmallString<256> FilePath;
// Get the module map file path to be used.
if ((HeaderDirectory.size() == 0) && (HeaderPrefix.size() != 0)) {
FilePath = HeaderPrefix;
// Prepend header file name prefix if it's not absolute.
llvm::sys::path::append(FilePath, ModuleMapPath);
llvm::sys::path::native(FilePath);
} else {
FilePath = ModuleMapPath;
llvm::sys::path::native(FilePath);
}
// Set up module map output file.
std::error_code EC;
llvm::tool_output_file Out(FilePath, EC, llvm::sys::fs::F_Text);
if (EC) {
llvm::errs() << Argv0 << ": error opening " << FilePath << ":"
<< EC.message() << "\n";
return false;
}
// Get output stream from tool output buffer/manager.
llvm::raw_fd_ostream &OS = Out.os();
// Output file comment.
OS << "// " << ModuleMapPath << "\n";
OS << "// Generated by: " << CommandLine << "\n\n";
// Write module hierarchy from internal representation.
if (!RootModule->output(OS, 0))
return false;
// Tell tool_output_file that we want to keep the file.
Out.keep();
return true;
}
// Global functions:
// Module map generation entry point.
bool createModuleMap(llvm::StringRef ModuleMapPath,
llvm::ArrayRef<std::string> HeaderFileNames,
DependencyMap &Dependencies, llvm::StringRef HeaderPrefix,
llvm::StringRef RootModuleName) {
// Load internal representation of modules.
std::unique_ptr<Module> RootModule(loadModuleDescriptions(
RootModuleName, HeaderFileNames, Dependencies, HeaderPrefix));
if (!RootModule.get())
return false;
// Write module map file.
return writeModuleMap(ModuleMapPath, HeaderPrefix, RootModule.get());
}
| [
"amo260@gmail.com"
] | amo260@gmail.com |
0cfae3b02d745d15d02ae92df60e227fb43ed663 | b5d6cd3d27534f169789e0c8abca3a6de47b31d3 | /Util/Socket.cpp | b88a7925d87b5764f7de6cb7d6ff45065f80abad | [] | no_license | luxigo/metricsphere | faea406ef745e075674e28fb816189e663fb0969 | 18005d143de38f6edadf371b272cb493f39b3665 | refs/heads/master | 2020-06-07T10:00:32.700737 | 2014-09-19T15:27:40 | 2014-09-19T15:27:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,259 | cpp | /*
Copyright (c) 2006, Michael Kazhdan and Matthew Bolitho
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer. Redistributions in binary form must reproduce
the above copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the distribution.
Neither the name of the Johns Hopkins University 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.
*/
#include "Socket.h"
int MyWinSock::_wsaCount = 0;
WSADATA MyWinSock::_wsaData;
CRITICAL_SECTION MyWinSock::stdinLock;
CRITICAL_SECTION MyWinSock::stderrLock;
CRITICAL_SECTION MyWinSock::systemLock;
#if STORE_CONNECTION_TABLE
hash_map< int , ConnectionData > MyWinSock::ConnectionTable;
#endif // STORE_CONNECTION_TABLE
void printfId(const char* format,...)
{
va_list args;
va_start(args,format);
printf( "%d] " , GetCurrentThreadId() );
vprintf(format,args);
va_end(args);
}
void fprintfId(FILE* fp , const char* format,...)
{
va_list args;
va_start( args , format );
fprintf( fp , "%d] " , GetCurrentThreadId() );
vfprintf( fp , format , args );
va_end( args);
}
bool MyWaitForSingleObject( HANDLE hHandle , DWORD milliseconds , const char* deadlockMessage , ... )
{
#if DEBUG_DEADLOCK
int state;
while( (state = WaitForSingleObject( hHandle , milliseconds ) ) == WAIT_TIMEOUT )
{
MyWinSock::fprintfId( stderr , "Possible single deadlock: " );
MyWinSock::StderrLock lock;
va_list args;
va_start( args , deadlockMessage );
vfprintf( stderr , deadlockMessage , args );
va_end( args );
fprintf( stderr , "\n" );
}
if( state != WAIT_OBJECT_0 )
{
MyWinSock::fprintfId( stderr , "Failed to wait for single event: " ) , PrintError();
return false;
}
#else // !DEBUG_DEADLOCK
if( WaitForSingleObject( hHandle , INFINITE ) != WAIT_OBJECT_0 )
{
MyWinSock::StderrLock lock;
fprintf( stderr , "Failed to wait for single event: " ) , PrintError();
return false;
}
#endif // DEADLOCK
return true;
}
bool MyWaitForMultipleObjects( DWORD nCount , const HANDLE* lpHandles , DWORD milliseconds , const char* deadlockMessage , ... )
{
#if DEBUG_DEADLOCK
int state;
while( (state = WaitForMultipleObjects( nCount , lpHandles , TRUE , milliseconds ) ) == WAIT_TIMEOUT )
{
MyWinSock::fprintfId( stderr , "Possible multiple deadlock: " );
MyWinSock::StderrLock lock;
va_list args;
va_start( args , deadlockMessage );
vfprintf( stderr , deadlockMessage , args );
va_end( args );
fprintf( stderr , "\n" );
}
if( state != WAIT_OBJECT_0 )
{
MyWinSock::fprintfId( stderr , "Failed to wait for multiple events: " ) , PrintError();
MyWinSock::StderrLock lock;
va_list args;
va_start( args , deadlockMessage );
vfprintf( stderr , deadlockMessage , args );
va_end( args );
fprintf( stderr , "\n" );
return false;
}
#else // !DEBUG_DEADLOCK
if( WaitForMultipleObjects( nCount , lpHandles , TRUE , INFINITE ) != WAIT_OBJECT_0 )
{
MyWinSock::StderrLock lock;
fprintf( stderr , "Failed to wait for multiple events: " ) , PrintError();
return false;
}
#endif // DEADLOCK
return false;
}
void MyWinSock::Load( void )
{
if(!_wsaCount)
{
InitializeCriticalSection( &stdinLock );
InitializeCriticalSection( &stderrLock );
InitializeCriticalSection( &systemLock );
if( WSAStartup( MAKEWORD(2,2), &_wsaData ) ) fprintfId( stderr , "WSAStartup failed: %s\n", LastSocketError() ) , exit(0);
}
_wsaCount++;
}
void MyWinSock::UnLoad( void )
{
_wsaCount--;
if(!_wsaCount)
{
WSACleanup();
DeleteCriticalSection( &stdinLock );
DeleteCriticalSection( &stderrLock );
DeleteCriticalSection( &systemLock );
}
}
void MyWinSock::fprintfId( FILE* fp , const char* format,...)
{
EnterCriticalSection( &stdinLock );
va_list args;
va_start(args,format);
fprintf( fp , "%d] " , GetCurrentThreadId() );
vfprintf( fp , format , args );
va_end(args);
LeaveCriticalSection( &stdinLock );
}
void MyWinSock::printfId(const char* format,...)
{
EnterCriticalSection( &stdinLock );
va_list args;
va_start(args,format);
printf( "%d] " , GetCurrentThreadId() );
vprintf(format,args);
va_end(args);
LeaveCriticalSection( &stdinLock );
}
//////////////////
void StartReceiveOnSocket( SOCKET& s , bool blockingSend , const char* errorMessage , ... )
{
if( blockingSend )
{
#if DEBUG_SOCKET
printfId( " Sending Acknowledgement (%d)\n" , s );
#endif // DEBUG_SOCKET
int ack;
if( !SendOnSocket( s , GetPointer( ack ) , sizeof(ack) ) )
{
fprintfId( stderr , "Failed to send acknowledgement (%d)\n" , s );
{
MyWinSock::StderrLock lock;
va_list args;
va_start( args , errorMessage );
vfprintf( stderr , errorMessage , args );
va_end( args );
fprintf( stderr , "\n" );
}
exit(0);
}
#if DEBUG_SOCKET
printfId( " Done (%d)\n" , s ) , fflush( stdout );
#endif // DEBUG_SOCKET
}
}
void EndSendOnSocket( SOCKET& s , bool blockingSend , const char* errorMessage , ... )
{
if( blockingSend )
{
#if DEBUG_SOCKET
printfId( " Receiving Acknowledgement (%d)\n" , s ) , fflush( stdout );
#endif // DEBUG_SOCKET
int ack;
if( !ReceiveOnSocket( s , GetPointer( ack ) , sizeof(ack) ) )
{
fprintfId( stderr , "Failed to receive acknowledgement (%d)\n" , s );
{
MyWinSock::StderrLock lock;
va_list args;
va_start( args , errorMessage );
vfprintf( stderr , errorMessage , args );
va_end( args );
fprintf( stderr , "\n" );
}
exit(0);
}
#if DEBUG_SOCKET
printfId( " Done (%d)\n" , s ) , fflush( stdout );
#endif // DEBUG_SOCKET
}
}
bool StartReceiveOnSocket( SOCKET& s , bool blockingSend )
{
if( blockingSend )
{
#if DEBUG_SOCKET
printfId( " Sending Acknowledgement (%d)\n" , s ) , fflush( stdout );
#endif // DEBUG_SOCKET
int ack;
if( !SendOnSocket( s , GetPointer( ack ) , sizeof(ack) ) )
{
fprintfId( stderr , "Failed to send acknowledgement (%d)\n" , s );
return false;
}
#if DEBUG_SOCKET
printfId( " Done (%d)\n" , s ) , fflush( stdout );
#endif // DEBUG_SOCKET
}
return true;
}
bool EndSendOnSocket( SOCKET& s , bool blockingSend )
{
if( blockingSend )
{
#if DEBUG_SOCKET
printfId( " Receiving Acknowledgement (%d)\n" , s ) , fflush( stdout );
#endif // DEBUG_SOCKET
int ack;
if( !ReceiveOnSocket( s , GetPointer( ack ) , sizeof(ack) ) )
{
fprintfId( stderr , "Failed to receive acknowledgement (%d)\n" , s );
return false;
}
#if DEBUG_SOCKET
printfId( " Done (%d)\n" , s ) , fflush( stdout );
#endif // DEBUG_SOCKET
}
return true;
}
void PrintHostAddress( void )
{
MyWinSock::SystemLock lock;
char hostName[512];
gethostname( hostName , 512 );
hostent* host = gethostbyname( hostName );
for( int i=0 ; ; i++ )
if( host->h_addr_list[i] == NULL ) break;
else printf( "Address[%d]: %s\n" , i , inet_ntoa( *(struct in_addr*)host->h_addr_list[i] ) ) , fflush( stdout );
for( int i=0 ; ; i++ )
if( host->h_aliases[i] == NULL ) break;
else printf( "Aliases[%d]: %s\n" , i , host->h_aliases[i] ) , fflush( stdout );
}
void GetHostAddress( char* address , char* prefix)
{
char hostName[512];
gethostname( hostName , 512 );
{
MyWinSock::SystemLock lock;
hostent* host = gethostbyname( hostName );
if( !prefix )
{
strcpy( address , inet_ntoa(*(struct in_addr*)host->h_addr) );
return;
}
for( int i=0 ; ; i++ )
if( host->h_addr_list[i] == NULL ) break;
else if( strstr( inet_ntoa( *(struct in_addr*)host->h_addr_list[i] ) , prefix ) )
{
strcpy( address , inet_ntoa(*(struct in_addr*)host->h_addr_list[i]) );
return;
}
strcpy( address , inet_ntoa(*(struct in_addr*)host->h_addr) );
}
}
int GetLocalSocketPort( SOCKET& s )
{
struct sockaddr_in local;
int len=sizeof(local);
if( getsockname ( s , (struct sockaddr*) &local , &len ) == SOCKET_ERROR )
{
fprintfId( stderr , "Error at getsockname(): %s\n" , LastSocketError() );
return -1;
}
return int(ntohs(local.sin_port));
}
const char* GetLocalSocketAddress( SOCKET& s )
{
struct sockaddr_in local;
int len=sizeof(local);
if( getsockname ( s , (struct sockaddr*) &local , &len ) == SOCKET_ERROR )
{
fprintfId( stderr , "Error at getsockname(): %s\n" , LastSocketError() );
return NULL;
}
return inet_ntoa( local.sin_addr );
}
int GetPeerSocketPort( SOCKET& s )
{
struct sockaddr_in peer;
int len = sizeof( peer );
if( getpeername ( s , (struct sockaddr*) &peer , &len ) == SOCKET_ERROR )
{
fprintfId( stderr , "Error at getpeername(): %s\n" , LastSocketError() );
return -1;
}
return int(ntohs( peer.sin_port) );
}
const char* GetPeerSocketAddress( SOCKET& s )
{
struct sockaddr_in peer;
int len=sizeof( peer );
if( getpeername ( s , (struct sockaddr*) &peer , &len ) == SOCKET_ERROR )
{
fprintfId( stderr , "Error at getpeername(): %s\n" , LastSocketError() );
return NULL;
}
return inet_ntoa( peer.sin_addr );
}
SOCKET GetConnectSocket( const char* address , int port , int ms , bool progress )
{
in_addr addr;
inet_aton( address , &addr );
return GetConnectSocket( addr , port , ms , progress );
}
SOCKET GetConnectSocket( in_addr address , int port , int ms , bool progress )
{
struct sockaddr_in addr_in;
memset( &addr_in, 0, sizeof(addr_in) );
addr_in.sin_family = AF_INET;
addr_in.sin_addr = address;
addr_in.sin_port= htons ( port );
SOCKET sock = socket( AF_INET, SOCK_STREAM , 0);
if ( sock == INVALID_SOCKET )
{
fprintfId( stderr , "Error at GetConnectSocket( ... , %d ): %s\n" , port , LastSocketError() );
return INVALID_SOCKET;
}
long long sleepCount = 0;
while (connect( sock, (const sockaddr*)&addr_in, sizeof(addr_in) ) == SOCKET_ERROR)
{
sleepCount++;
Sleep( 1 );
if( progress && !(sleepCount%ms) ) printf( "." );
}
if( progress ) printf( "\n" ) , fflush( stdout );
int val = 1;
setsockopt( sock , IPPROTO_TCP , TCP_NODELAY , (char*)&val , sizeof(val) );
#if STORE_CONNECTION_TABLE
if( sock!=INVALID_SOCKET )
{
MyWinSock::SystemLock lock;
ConnectionData& data = MyWinSock::ConnectionTable[ sock ];
struct sockaddr_in addr;
int len = sizeof( addr );
if( getsockname ( sock , (struct sockaddr*) &addr , &len ) == SOCKET_ERROR )
{
fprintfId( stderr , "Error at getsockname(): %s\n" , LastSocketError() );
return NULL;
}
memcpy( &data.localAddr , &addr.sin_addr , sizeof( addr.sin_addr ) );
data.localPort = int( ntohs( addr.sin_port ) );
if( getpeername ( sock , (struct sockaddr*) &addr , &len ) == SOCKET_ERROR )
{
fprintfId( stderr , "Error at getpeername(): %s\n" , LastSocketError() );
return NULL;
}
memcpy( &data.peerAddr , &addr.sin_addr , sizeof( addr.sin_addr ) );
data.peerPort = int( ntohs( addr.sin_port ) );
}
#endif // STORE_CONNECTION_TABLE
return sock;
}
SOCKET AcceptSocket( SOCKET listen )
{
SOCKET sock = accept( listen , NULL , NULL );
if ( sock == INVALID_SOCKET )
{
fprintfId( stderr , "accept failed: %s\n" , LastSocketError() );
return INVALID_SOCKET;
}
int val = 1;
setsockopt( sock , IPPROTO_TCP , TCP_NODELAY , (char*)&val , sizeof(val) );
#if STORE_CONNECTION_TABLE
if( sock!=INVALID_SOCKET )
{
MyWinSock::SystemLock lock;
ConnectionData& data = MyWinSock::ConnectionTable[ sock ];
struct sockaddr_in addr;
int len = sizeof( addr );
if( getsockname ( sock , (struct sockaddr*) &addr , &len ) == SOCKET_ERROR )
{
fprintfId( stderr , "Error at getsockname(): %s\n" , LastSocketError() );
return NULL;
}
memcpy( &data.localAddr , &addr.sin_addr , sizeof( addr.sin_addr ) );
data.localPort = int( ntohs( addr.sin_port ) );
if( getpeername ( sock , (struct sockaddr*) &addr , &len ) == SOCKET_ERROR )
{
fprintfId( stderr , "Error at getpeername(): %s\n" , LastSocketError() );
return NULL;
}
memcpy( &data.peerAddr , &addr.sin_addr , sizeof( addr.sin_addr ) );
data.peerPort = int( ntohs( addr.sin_port ) );
}
#endif // STORE_CONNECTION_TABLE
return sock;
}
SOCKET GetListenSocket( int& port )
{
SOCKET listenSocket = socket(AF_INET, SOCK_STREAM, 0);
if (listenSocket == INVALID_SOCKET)
{
fprintfId( stderr , "Error at socket(): %s\n", LastSocketError());
return INVALID_SOCKET;
}
struct sockaddr_in local;
memset(&local, 0, sizeof(local));
local.sin_addr.s_addr = htonl(INADDR_ANY);
local.sin_port = htons(port);
local.sin_family = AF_INET;
// Setup the TCP listening socket
if (bind( listenSocket, (const sockaddr*)&local, sizeof(local) ) == SOCKET_ERROR)
{
fprintfId( stderr , "bind failed: %s\n" , LastSocketError());
closesocket(listenSocket);
return INVALID_SOCKET;
}
if ( listen( listenSocket, SOMAXCONN ) == SOCKET_ERROR )
{
fprintfId( stderr , "Error at listen(): %s\n" , LastSocketError() );
closesocket(listenSocket);
return INVALID_SOCKET;
}
int len=sizeof(local);
if(getsockname(listenSocket,(struct sockaddr*)&local,&len) == SOCKET_ERROR)
{
fprintfId( stderr , "Error at getsockname(): %s\n" , LastSocketError() );
closesocket(listenSocket);
return INVALID_SOCKET;
}
port=int(ntohs(local.sin_port));
return listenSocket;
}
void CloseSocket( SOCKET& s )
{
#if STORE_CONNECTION_TABLE
if( s!=INVALID_SOCKET )
{
MyWinSock::SystemLock lock;
MyWinSock::ConnectionTable.erase( s );
}
#endif // STORE_CONNECTION_TABLE
if( s!=INVALID_SOCKET ) closesocket( s );
s = INVALID_SOCKET;
}
int inet_aton(const char *cp, struct in_addr *inp)
{
unsigned int a = 0, b = 0, c = 0, d = 0;
int n = 0, r;
unsigned long int addr = 0;
r = sscanf(cp, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n);
if (r == 0 || n == 0) return 0;
cp += n;
if (*cp) return 0;
if (a > 255 || b > 255 || c > 255 || d > 255) return 0;
if (inp) {
addr += a; addr <<= 8;
addr += b; addr <<= 8;
addr += c; addr <<= 8;
addr += d;
inp->s_addr = htonl(addr);
}
return 1;
}
static const char *wstrerror(int err)
{
switch (err)
{
case WSAEINTR: return "Interrupted function call";
case WSAEACCES: return "Permission denied";
case WSAEFAULT: return "Bad address";
case WSAEINVAL: return "Invalid argument";
case WSAEMFILE: return "Too many open files";
case WSAEWOULDBLOCK: return "Resource temporarily unavailable";
case WSAEINPROGRESS: return "Operation now in progress";
case WSAEALREADY: return "Operation already in progress";
case WSAENOTSOCK: return "Socket operation on nonsocket";
case WSAEDESTADDRREQ: return "Destination address required";
case WSAEMSGSIZE: return "Message too long";
case WSAEPROTOTYPE: return "Protocol wrong type for socket";
case WSAENOPROTOOPT: return "Bad protocol option";
case WSAEPROTONOSUPPORT: return "Protocol not supported";
case WSAESOCKTNOSUPPORT: return "Socket type not supported";
case WSAEOPNOTSUPP: return "Operation not supported";
case WSAEPFNOSUPPORT: return "Protocol family not supported";
case WSAEAFNOSUPPORT: return "Address family not supported by protocol family";
case WSAEADDRINUSE: return "Address already in use";
case WSAEADDRNOTAVAIL: return "Cannot assign requested address";
case WSAENETDOWN: return "Network is down";
case WSAENETUNREACH: return "Network is unreachable";
case WSAENETRESET: return "Network dropped connection on reset";
case WSAECONNABORTED: return "Software caused connection abort";
case WSAECONNRESET: return "Connection reset by peer";
case WSAENOBUFS: return "No buffer space available";
case WSAEISCONN: return "Socket is already connected";
case WSAENOTCONN: return "Socket is not connected";
case WSAESHUTDOWN: return "Cannot send after socket shutdown";
case WSAETIMEDOUT: return "Connection timed out";
case WSAECONNREFUSED: return "Connection refused";
case WSAEHOSTDOWN: return "Host is down";
case WSAEHOSTUNREACH: return "No route to host";
case WSAEPROCLIM: return "Too many processes";
case WSASYSNOTREADY: return "Network subsystem is unavailable";
case WSAVERNOTSUPPORTED: return "Winsock.dll version out of range";
case WSANOTINITIALISED: return "Successful WSAStartup not yet performed";
case WSAEDISCON: return "Graceful shutdown in progress";
case WSAHOST_NOT_FOUND: return "Host not found";
case WSATRY_AGAIN: return "Nonauthoritative host not found";
case WSANO_RECOVERY: return "Nonrecoverable name lookup error";
case WSANO_DATA: return "Valid name, no data record of requested type";
default: return "Unknown error";
}
}
//static const char* LastSocketError(void) { return wstrerror( WSAGetLastError() ); }
const char* LastSocketError(void) { return wstrerror( WSAGetLastError() ); }
///////////////////////////
// DataStreamConstructor //
///////////////////////////
DataStreamConstructor::DataStreamConstructor( void )
{
_sock = INVALID_SOCKET;
_stream = NULL;
char address[512];
_myPID = GetCurrentProcessId( );
GetHostAddress( address );
inet_aton( address, &_myAddr );
}
void DataStreamConstructor::init( SOCKET sock , bool master , bool cleanUp )
{
_sock = sock;
_master = master;
_cleanUp = cleanUp;
}
DataStream* DataStreamConstructor::getDataStream( void ) { return _stream; }
void DataStreamConstructor::doStep( int sNum )
{
switch( sNum )
{
case 0:
if( !_master )
{
SendOnSocket( _sock , GetPointer(_myAddr) , sizeof(_myAddr) );
SendOnSocket( _sock , GetPointer(_myPID ) , sizeof(_myPID) );
}
break;
case 1:
if( _master )
{
in_addr addr;
int pid;
ReceiveOnSocket( _sock , GetPointer(addr) , sizeof(addr) );
ReceiveOnSocket( _sock , GetPointer(pid ) , sizeof(pid) );
if( _myAddr.s_addr == addr.s_addr && _myPID == pid )
{
SharedMemoryBuffer::StreamPair sPair;
SharedMemoryBuffer::StreamPair::CreateSharedBufferPair( sPair );
SendOnSocket( _sock , GetPointer(sPair.second) , sizeof( sPair.second ) );
_stream = sPair.first;
if( _cleanUp ) CloseSocket( _sock );
}
else
{
SharedMemoryBuffer::SecondStream* sStream = NULL;
SendOnSocket( _sock , GetPointer(sStream) , sizeof( sStream ) );
_stream = new Socket( _sock );
}
}
break;
case 2:
if( !_master )
{
SharedMemoryBuffer::SecondStream* sStream;
ReceiveOnSocket( _sock , GetPointer(sStream) , sizeof( sStream ) );
if( sStream )
{
if( _cleanUp ) CloseSocket( _sock );
_stream = sStream;
}
else _stream = new Socket( _sock );
}
break;
}
}
////////////////
// DataStream //
////////////////
DataStream* DataStream::GetDataStream( SOCKET sock , bool master , bool cleanUp )
{
char address[512];
in_addr myAddr , addr;
int pid , myPID = GetCurrentProcessId( );
GetHostAddress( address );
inet_aton( address, &myAddr );
if( master )
{
ReceiveOnSocket( sock , GetPointer(addr) , sizeof(addr) );
ReceiveOnSocket( sock , GetPointer(pid ) , sizeof(pid) );
if( myAddr.s_addr == addr.s_addr && myPID == pid )
{
SharedMemoryBuffer::StreamPair sPair;
SharedMemoryBuffer::StreamPair::CreateSharedBufferPair( sPair );
SendOnSocket( sock , GetPointer(sPair.second) , sizeof( sPair.second ) );
if( cleanUp ) CloseSocket( sock );
return sPair.first;
}
else
{
SharedMemoryBuffer::SecondStream* sStream = NULL;
SendOnSocket( sock , GetPointer(sStream) , sizeof( sStream ) );
return new Socket( sock );
}
}
else
{
SendOnSocket( sock , GetPointer(myAddr) , sizeof(myAddr) );
SendOnSocket( sock , GetPointer(myPID ) , sizeof(myPID) );
SharedMemoryBuffer::SecondStream* sStream;
ReceiveOnSocket( sock , GetPointer(sStream) , sizeof( sStream ) );
if( sStream )
{
if( cleanUp ) CloseSocket( sock );
return sStream;
}
else return new Socket( sock );
}
}
////////////
// Socket //
////////////
Socket::Socket( SOCKET sock ) { _sock = sock; _mySocket = false; }
Socket::Socket( const char* address , int port , int ms , bool progress )
{
_sock = GetConnectSocket( address , port , ms , progress );
_mySocket = true;
}
Socket::Socket( in_addr address , int port , int ms , bool progress )
{
_sock = GetConnectSocket( address , port , ms , progress );
_mySocket = true;
}
Socket::~Socket( void ) { if( _mySocket ) CloseSocket( _sock); }
bool Socket::write( ConstPointer( byte ) buf , int len ) { return SendOnSocket ( _sock , buf , len ); }
bool Socket::read ( Pointer( byte ) buf , int len ){ return ReceiveOnSocket( _sock , buf , len ); }
////////////////////////
// SharedMemoryBuffer //
////////////////////////
SharedMemoryBuffer::SharedMemoryBuffer( void )
{
_buf1 = NullPointer< byte >( );
_buf2 = NullPointer< byte >( );
_bufSize1 = _bufSize2 = 0;
_loadHandle1 = CreateEvent( NULL , false , false , NULL );
_loadHandle2 = CreateEvent( NULL , false , false , NULL );
_unloadHandle1 = CreateEvent( NULL , false , true , NULL );
_unloadHandle2 = CreateEvent( NULL , false , true , NULL );
}
SharedMemoryBuffer::~SharedMemoryBuffer( void )
{
FreeArray( _buf1 ) , _bufSize1 = 0;
FreeArray( _buf2 ) , _bufSize2 = 0;
CloseHandle( _loadHandle1 ) , _loadHandle1 = NULL;
CloseHandle( _loadHandle2 ) , _loadHandle2 = NULL;
CloseHandle( _unloadHandle1 ) , _unloadHandle1 = NULL;
CloseHandle( _unloadHandle2 ) , _unloadHandle2 = NULL;
}
SharedMemoryBuffer::FirstStream::FirstStream ( SharedMemoryBuffer* smb ) { _smb = smb; }
SharedMemoryBuffer::SecondStream::SecondStream( SharedMemoryBuffer* smb ) { _smb = smb; }
SharedMemoryBuffer::FirstStream::~FirstStream ( void ) { if( _smb ) delete _smb , _smb = NULL; }
SharedMemoryBuffer::SecondStream::~SecondStream( void ) { _smb = NULL; }
// The first stream reads on buf1 and writes on buf2
bool SharedMemoryBuffer::FirstStream::read( Pointer( byte ) buf , int len )
{
if( WaitForSingleObject( _smb->_loadHandle1 , INFINITE ) != WAIT_OBJECT_0 ) fprintfId( stderr , "Wait for single failed: " ) , PrintError();
if( len>_smb->_bufSize1 )
{
printf( "Uh oh 1\n" ) , fflush( stdout );
return false;
}
memcpy( buf , _smb->_buf1 , len );
SetEvent( _smb->_unloadHandle1 );
return true;
}
bool SharedMemoryBuffer::FirstStream::write( ConstPointer( byte ) buf , int len )
{
if( WaitForSingleObject( _smb->_unloadHandle2 , INFINITE ) != WAIT_OBJECT_0 ) fprintfId( stderr , "Wait for single failed: " ) , PrintError();
if( len>_smb->_bufSize2 )
{
FreeArray( _smb->_buf2 );
_smb->_bufSize2 = 0;
_smb->_buf2 = AllocArray< byte >( len , 1 , "SharedMemoryBuffer::FirstStream::write (_smb->_buf2)" );
if( !_smb->_buf2 )
{
printf( "Uh oh 2\n" ) , fflush( stdout );
return false;
}
_smb->_bufSize2 = len;
}
memcpy( _smb->_buf2 , buf , len );
SetEvent( _smb->_loadHandle2 );
return true;
}
bool SharedMemoryBuffer::SecondStream::read( Pointer( byte ) buf , int len )
{
if( WaitForSingleObject( _smb->_loadHandle2 , INFINITE ) != WAIT_OBJECT_0 ) fprintfId( stderr , "Wait for single failed: " ) , PrintError();
if( len>_smb->_bufSize2 )
{
printf( "Uh oh 3\n" ) , fflush( stdout );
return false;
}
memcpy( buf , _smb->_buf2 , len );
SetEvent( _smb->_unloadHandle2 );
return true;
}
bool SharedMemoryBuffer::SecondStream::write( ConstPointer( byte ) buf , int len )
{
if( WaitForSingleObject( _smb->_unloadHandle1 , INFINITE ) != WAIT_OBJECT_0 ) fprintfId( stderr , "Wait for single failed: " ) , PrintError();
if( len>_smb->_bufSize1 )
{
FreeArray( _smb->_buf1 );
_smb->_bufSize1 = 0;
_smb->_buf1 = AllocArray< byte >( len , 1 , "SharedMemoryBuffer::SecondStream::write (_smb->_buf1)" );
if( !_smb->_buf1 )
{
printf( "Uh oh 4\n" ) , fflush( stdout );
return false;
}
_smb->_bufSize1 = len;
}
memcpy( _smb->_buf1 , buf , len );
SetEvent( _smb->_loadHandle1 );
return true;
}
bool SharedMemoryBuffer::StreamPair::CreateSharedBufferPair( StreamPair& pair )
{
SharedMemoryBuffer* smb = new SharedMemoryBuffer( );
pair.first = new SharedMemoryBuffer::FirstStream ( smb );
pair.second = new SharedMemoryBuffer::SecondStream( smb );
if( !pair.first || !pair.second )
{
fprintf( stderr , "Failed to create shared buffer pair\n" );
return false;
}
return true;
}
SharedMemoryBuffer::StreamPair::StreamPair( void )
{
first = NULL;
second = NULL;
}
| [
"luc.deschenaux@freesurf.ch"
] | luc.deschenaux@freesurf.ch |
ef649af7a31c50e84d352f211aabf5ab487d9c19 | 48298469e7d828ab1aa54a419701c23afeeadce1 | /Login/Packets/WLRetCharLoginHandler.cpp | 38cdeb007e169de80892ec0870e07d9cb0eb3989 | [] | no_license | brock7/TianLong | c39fccb3fd2aa0ad42c9c4183d67a843ab2ce9c2 | 8142f9ccb118e76a5cd0a8b168bcf25e58e0be8b | refs/heads/master | 2021-01-10T14:19:19.850859 | 2016-02-20T13:58:55 | 2016-02-20T13:58:55 | 52,155,393 | 5 | 3 | null | null | null | null | GB18030 | C++ | false | false | 7,620 | cpp | #include "stdafx.h"
#include "WLRetCharLogin.h"
#include "ProcessManager.h"
#include "ProcessPlayerManager.h"
#include "ServerManager.h"
#include "LoginPlayer.h"
#include "LCRetCharLogin.h"
#include "PlayerPool.h"
#include "TimeManager.h"
#include "DBLogicManager.h"
#include "DBCharFullData.h"
#include "DB_Struct.h"
#include "LWAskCharLogin.h"
#include "PacketFactoryManager.h"
#include "Log.h"
#include "DBThreadManager.h"
UINT WLRetCharLoginHandler::Execute(WLRetCharLogin* pPacket, Player* pPlayer )
{
__ENTER_FUNCTION
TID CurrentThreadID = MyGetCurrentThreadID();
if(CurrentThreadID == g_pServerManager->m_ThreadID)
{
g_pProcessManager->SendPacket(pPacket,pPacket->GetPlayerID());
return PACKET_EXE_NOTREMOVE;
}
else if(CurrentThreadID == g_pProcessPlayerManager->m_ThreadID)
{
PlayerID_t PlayerID = pPacket->GetPlayerID();
LoginPlayer* pLoginPlayer = g_pPlayerPool->GetPlayer(PlayerID);
Assert(pLoginPlayer);
if(strcmp(pLoginPlayer->GetAccount(),pPacket->GetAccount())!= 0)
{
Log::SaveLog(LOGIN_LOGFILE,"WLRetCharLoginHandler::Execute()....acc error,acc=%s,packacc=%s",
pPacket->GetAccount(),pPacket->GetAccount());
return PACKET_EXE_CONTINUE;
}
if(pPacket->GetHoldStatus() == TRUE) //用户在线
{
LCRetCharLogin Msg;
Msg.SetResult(pPacket->GetResult());
if(pPacket->GetResult() == ASKCHARLOGIN_SERVER_STOP)
{
pLoginPlayer->SendPacket(&Msg);
Log::SaveLog(LOGIN_LOGFILE,"WLRetCharLoginHandler::Execute()....User is Online ,Server is CrashDown\
Account = %s,GUID = %d",pPacket->GetAccount(),pPacket->GetPlayerGUID());
return PACKET_EXE_CONTINUE;
}
if(pPacket->GetResult() == ASKCHARLOGIN_SUCCESS)
{
//计算角色所在服务器信息
ID_t ServerID = pPacket->GetPlayerServerID();
INT index = g_Config.m_ServerInfo.m_HashServer[ServerID] ;
_SERVER_DATA* pServerData = &(g_Config.m_ServerInfo.m_pServer[index]);
Assert(pServerData);
Msg.SetServerIP(pServerData->m_IP0);
Msg.SetServerPort(pServerData->m_Port0);
//取得用户登陆Key值
Msg.SetUserKey(pLoginPlayer->GetUserKey());
pLoginPlayer->SendPacket(&Msg);
pLoginPlayer->SetPlayerStatus(PS_LOGIN_SERVER_READY);
Log::SaveLog(LOGIN_LOGFILE,"WLRetCharLoginHandler::Execute()...Online ,Acc=%s,GUID=%X,IP=%s,Port=%d,SID=%d",
pPacket->GetAccount(),pPacket->GetPlayerGUID(),
pServerData->m_IP0,pServerData->m_Port0,
ServerID);
return PACKET_EXE_CONTINUE;
}
}
else //用户不在线 ,需要Load 数据
{
//对数据库操作频繁度判断
UINT uTime = g_pTimeManager->CurrentTime();
if(uTime<pLoginPlayer->m_LastDBOpTime+DB_OPERATION_TIME)
{
//用户操作过于频繁
LCRetCharLogin Msg;
Msg.SetResult(ASKCHARLOGIN_OP_TIMES);
pLoginPlayer->SendPacket(&Msg);
Log::SaveLog(LOGIN_LOGFILE,"WLRetCharLoginHandler::Execute()....User Need Load From DB Account = %s,GUID = %X",pPacket->GetAccount(),pPacket->GetPlayerGUID());
return PACKET_EXE_CONTINUE;
}
//
if(pPacket->GetResult() == ASKCHARLIST_WORLD_FULL
|| pPacket->GetResult() == ASKCHARLOGIN_SERVER_STOP)
{
LCRetCharLogin Msg;
Msg.SetResult(pPacket->GetResult());
pLoginPlayer->SendPacket(&Msg);
Log::SaveLog(LOGIN_LOGFILE,"WLRetCharLoginHandler::Execute()....User Can't Login Account = %s,GUID = %X ,Result = %d",pPacket->GetAccount(),pPacket->GetPlayerGUID(),pPacket->GetResult());
return PACKET_EXE_CONTINUE;
}
if (pPacket->GetResult() == ASKCHARLOGIN_LOADDB_ERROR)
{
if(g_pDBThreadManager->SendPacket(pPacket,pLoginPlayer->PlayerID()))
{//加入成功,将消息发送到DB处理
pLoginPlayer->m_LastDBOpTime = uTime;
return PACKET_EXE_NOTREMOVE;
}
else
{
//DB 压力过大,让用户重新尝试
LCRetCharLogin Msg;
Msg.SetResult(ASKCHARLOGIN_SERVER_BUSY);
pLoginPlayer->SendPacket(&Msg);
pLoginPlayer->m_LastDBOpTime = uTime;
Log::SaveLog(LOGIN_LOGFILE,"WLRetCharLoginHandler::Execute()....Server Busy Account = %s,GUID = %X",pPacket->GetAccount(),pPacket->GetPlayerGUID());
return PACKET_EXE_CONTINUE;
}
}
}
}
else if(g_pDBThreadManager->IsPoolTID(CurrentThreadID))
{
PlayerID_t PlayerID = pPacket->GetPlayerID();
GUID_t PlayerCharGUID = pPacket->GetPlayerGUID();
LoginPlayer* pLoginPlayer = static_cast<LoginPlayer*>(pPlayer);
Assert(pLoginPlayer);
if(pLoginPlayer->GetDBOperating() == TRUE||!g_pDBThreadManager->GetInterface(CurrentThreadID)->IsConnected())
{
LCRetCharLogin* pRetCharLoginMsg =
(LCRetCharLogin*)g_pPacketFactoryManager->CreatePacket(PACKET_LC_RETCHARLOGIN);
if(!pRetCharLoginMsg)
{
AssertEx(FALSE,"创建 LCRetCharLogin 消息失败");
}
pRetCharLoginMsg->SetResult(ASKCHARLOGIN_SERVER_BUSY);
g_pProcessManager->SendPacket(pRetCharLoginMsg,PlayerID);
Log::SaveLog( LOGIN_LOGFILE, "WLRetCharLoginHandler::Execute()....数据库操作冲突!") ;
return PACKET_EXE_CONTINUE;
}
pLoginPlayer->SetDBOperating(TRUE);
ODBCInterface* pInterface = g_pDBThreadManager->GetInterface(CurrentThreadID);
Assert(pInterface);
DBCharFullData CharFullDataObject(pInterface);
CharFullDataObject.SetCharGuid(PlayerCharGUID);
BOOL bRetLoad = CharFullDataObject.Load();
INT ResultCount = CharFullDataObject.GetResultCount();
if(!bRetLoad)
{
Log::SaveLog(LOGIN_LOGFILE,"CharFullDataObject.Load()....Get Errors: %s",CharFullDataObject.GetErrorMessage());
LCRetCharLogin* pRetCharLoginMsg =
(LCRetCharLogin*)g_pPacketFactoryManager->CreatePacket(PACKET_LC_RETCHARLOGIN);
if(!pRetCharLoginMsg)
{
AssertEx(FALSE,"创建 LCRetCharLogin 消息失败");
}
pRetCharLoginMsg->SetResult(ASKCHARLOGIN_LOADDB_ERROR);
g_pProcessManager->SendPacket(pRetCharLoginMsg,PlayerID);
pLoginPlayer->SetDBOperating(FALSE);
return PACKET_EXE_NOTREMOVE;
}
if(ResultCount == 0)
{
Assert(FALSE);
LCRetCharLogin* pRetCharLoginMsg =
(LCRetCharLogin*)g_pPacketFactoryManager->CreatePacket(PACKET_LC_RETCHARLOGIN);
pRetCharLoginMsg->SetResult(ASKCHARLOGIN_LOADDB_ERROR);
g_pProcessManager->SendPacket(pRetCharLoginMsg,PlayerID);
pLoginPlayer->SetDBOperating(FALSE);
return PACKET_EXE_NOTREMOVE;
}
LWAskCharLogin* pMsg =
(LWAskCharLogin*)g_pPacketFactoryManager->CreatePacket(PACKET_LW_ASKCHARLOGIN);
if(!pMsg)
{
AssertEx(FALSE,"创建 LWAskCharLogin 消息失败");
}
UINT res1, res2, res3, res4;
INT nRet = CharFullDataObject.ParseResult(pMsg->GetUserData(),res1, res2, res3, res4);
if( nRet == 2 || nRet == 3 )
Log::SaveLog(LOGIN_LOGFILE,"WLRetCharLoginHandler::Execute()....Get Errors:(Ret=%d) %d,%d,%d,%d", nRet, res1, res2, res3, res4);
pMsg->GetUserData()->m_Human.m_LastLoginTime = g_pTimeManager->CurrentDate();
pMsg->SetAskStatus(ALS_SENDDATA);
pMsg->SetAccount(pLoginPlayer->GetAccount());
pMsg->SetPlayerID(PlayerID);
pMsg->SetPlayerGUID(PlayerCharGUID);
pMsg->SetUserKey(pLoginPlayer->GetUserKey());
pMsg->SetUserAge(pLoginPlayer->GetPlayerAge());
g_pServerManager->SendPacket(pMsg,WORLD_PLAYER_ID);
pLoginPlayer->SetDBOperating(FALSE);
}
else
{
AssertEx(FALSE,"WLRetCharLoginHandler 线程资源执行错误!");
}
Log::SaveLog(LOGIN_LOGFILE,"WLRetCharLoginHandler::Execute()....OK!");
return PACKET_EXE_CONTINUE;
__LEAVE_FUNCTION
return PACKET_EXE_ERROR;
} | [
"xiaowave@gmail.com"
] | xiaowave@gmail.com |
fa169bd33732aebbd9cfc9205d54a94bf5002da8 | 80f2fa4f1f4d56eef9471174f80b62838db9fc3b | /xdl/ps-plus/ps-plus/common/test/hdfs_test.cc | b30068e9857eb0be01aaf4136048c9c9402148e5 | [
"Apache-2.0"
] | permissive | laozhuang727/x-deeplearning | a54f2fef1794274cbcd6fc55680ea19760d38f8a | 781545783a4e2bbbda48fc64318fb2c6d8bbb3cc | refs/heads/master | 2020-05-09T17:06:00.495080 | 2019-08-15T01:45:40 | 2019-08-15T01:45:40 | 181,295,053 | 1 | 0 | Apache-2.0 | 2019-08-15T01:45:41 | 2019-04-14T10:51:53 | PureBasic | UTF-8 | C++ | false | false | 1,479 | cc | #include "gtest/gtest.h"
#include "ps-plus/common/data_source.h"
#include "ps-plus/common/hdfs_data_source.h"
#include "test/util/hdfs_launcher.h"
using ps::Status;
using ps::DataClosure;
using ps::HdfsDataSource;
class MockHdfsDS : public HdfsDataSource {
public:
MockHdfsDS(const std::string &file_path, size_t file_num) : HdfsDataSource(file_path, file_num) {}
Status Call(const std::string &stream) {
return InitFromFile(stream);
}
};
class HdfsDataSourceTest : public testing::Test {
public:
static void SetUpTestCase() {}
static void TearDownTestCase() {}
};
TEST_F(HdfsDataSourceTest, HdfsDataSource) {
int hdfs_port = xdl::HDFSLauncher::Instance()->GetPort();
std::string hdfs_prefix = "hdfs://127.0.0.1:" + std::to_string(hdfs_port);
std::string dir = hdfs_prefix + "/test_data/data_io/";
{
std::unique_ptr<HdfsDataSource> hds(new HdfsDataSource(dir, 1));
ASSERT_NE(hds, nullptr);
Status st = hds->Init(1, 1, 100);
ASSERT_EQ(st, Status::Ok());
DataClosure dc;
st = hds->Get(1, &dc);
ASSERT_NE(st, Status::Ok());
std::vector<int64_t> ids;
ids.push_back(1);
ids.push_back(2);
std::vector<DataClosure> cs;
st = hds->BatchGet(ids, &cs);
ASSERT_EQ(cs.size(), 1);
std::vector<int64_t> rst;
hds->BatchGetV2(ids, &cs, &rst);
ASSERT_EQ(cs.size(), 0);
}
{
auto ds = new MockHdfsDS(dir, 1);
Status st = ds->Call(dir);
ASSERT_NE(st, Status::Ok());
delete ds;
}
}
| [
"yue.song@alibaba-inc.com"
] | yue.song@alibaba-inc.com |
3a543800a7368b90afec7978766bee7892e4c891 | 9fa292d97ceb374068d355bd41097d0407d68bd3 | /src/rspf/plugin/rspfSharedObjectBridge.cpp | e3d04c041b114dfcb82dbe97f16b8f7c84a3a40e | [] | no_license | mfkiwl/rspf_v2.0 | 4d90153b92cc416663c798e05f87e348ad8792ef | f22d2707b775a4776fc8359a255f39c26ecc96a3 | refs/heads/master | 2021-05-27T04:36:34.132569 | 2013-07-16T04:04:12 | 2013-07-16T04:04:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 63 | cpp | #include <rspf/plugin/rspfSharedObjectBridge.h>
extern "C"
{
}
| [
"loongfee@gmail.com"
] | loongfee@gmail.com |
4b9e6a337e3f611ea2b5662efa9f71c67acc09b2 | 44bfa7c4c299558a0d8e948b117ac4a25c719b3b | /PaddleCV/rrpn/models/ext_op/src/rotated_anchor_generator_op.cc | 854245aaa2ce80024d608fb76fda001b48a505ac | [
"Apache-2.0"
] | permissive | littletomatodonkey/models | 408b53a1948df677685b61e9be24e86a513ffc94 | a60babdf382aba71fe447b3259441b4bed947414 | refs/heads/develop | 2022-10-21T18:46:19.606900 | 2020-04-27T14:36:08 | 2020-04-27T14:36:08 | 230,208,446 | 5 | 3 | Apache-2.0 | 2021-12-20T12:23:37 | 2019-12-26T06:29:32 | Python | UTF-8 | C++ | false | false | 7,008 | cc | /* Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include "rotated_anchor_generator_op.h"
namespace paddle {
namespace operators {
class RotatedAnchorGeneratorOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext* ctx) const override {
PADDLE_ENFORCE(
ctx->HasInput("Input"),
"Input(Input) of RotatedAnchorGeneratorOp should not be null.");
PADDLE_ENFORCE(
ctx->HasOutput("Anchors"),
"Output(Anchors) of RotatedAnchorGeneratorOp should not be null.");
PADDLE_ENFORCE(
ctx->HasOutput("Variances"),
"Output(Variances) of RotatedAnchorGeneratorOp should not be null.");
auto input_dims = ctx->GetInputDim("Input");
PADDLE_ENFORCE(input_dims.size() == 4, "The layout of input is NCHW.");
auto anchor_sizes = ctx->Attrs().Get<std::vector<float>>("anchor_sizes");
auto aspect_ratios = ctx->Attrs().Get<std::vector<float>>("aspect_ratios");
auto angles = ctx->Attrs().Get<std::vector<float>>("angles");
auto stride = ctx->Attrs().Get<std::vector<float>>("stride");
auto variances = ctx->Attrs().Get<std::vector<float>>("variances");
size_t num_anchors =
aspect_ratios.size() * anchor_sizes.size() * angles.size();
std::vector<int64_t> dim_vec(4);
dim_vec[0] = input_dims[2];
dim_vec[1] = input_dims[3];
dim_vec[2] = num_anchors;
dim_vec[3] = 5;
ctx->SetOutputDim("Anchors", framework::make_ddim(dim_vec));
ctx->SetOutputDim("Variances", framework::make_ddim(dim_vec));
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext& ctx) const override {
return framework::OpKernelType(
ctx.Input<framework::Tensor>("Input")->type(), ctx.device_context());
}
};
class RotatedAnchorGeneratorOpMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput("Input",
"(Tensor, default Tensor<float>), "
"the input feature is a tensor with a rank of 4. "
"The layout is NCHW.");
AddOutput("Anchors",
"(Tensor, default Tensor<float>), the output is a "
"tensor with a rank of 4. The layout is [H, W, num_anchors, 5]. "
"H is the height of input, W is the width of input, num_anchors "
"is the box count of each position. "
"Each anchor is in (xctr, yctr, w, h, thelta) format");
AddOutput("Variances",
"(Tensor, default Tensor<float>), the expanded variances for "
"normalizing bbox regression targets. The layout is [H, W, "
"num_anchors, 5]. "
"H is the height of input, W is the width of input, num_anchors "
"is the box count of each position. "
"Each variance is in (xctr, yctr, w, h, thelta) format");
AddAttr<std::vector<float>>(
"anchor_sizes",
"(vector<float>) List of Rotated Region Proposal Network(RRPN) anchor "
"sizes "
" given in absolute pixels e.g. (64, 128, 256, 512)."
" For instance, the anchor size of 64 means the area of this anchor "
"equals to 64**2.")
.AddCustomChecker([](const std::vector<float>& anchor_sizes) {
PADDLE_ENFORCE_GT(anchor_sizes.size(),
0UL,
"Size of anchor_sizes must be at least 1.");
for (size_t i = 0; i < anchor_sizes.size(); ++i) {
PADDLE_ENFORCE_GT(
anchor_sizes[i], 0.0, "anchor_sizes[%d] must be positive.", i);
}
});
AddAttr<std::vector<float>>(
"aspect_ratios",
"(vector<float>) List of Rotated Region Proposal Network(RRPN) anchor "
"aspect "
"ratios, e.g. (0.5, 1, 2)."
"For instacne, the aspect ratio of 0.5 means the height / width of "
"this anchor equals 0.5.");
AddAttr<std::vector<float>>(
"angles",
"(vector<float>) List of Rotated Region Proposal Network(RRPN) anchor "
"angles, "
"e.g. (-30.0, 0.0, 30.0, 60.0, 90.0, 120.0)."
"For instacne, the aspect ratio of 0.5 means the height / width of "
"this anchor equals 0.5.");
AddAttr<std::vector<float>>("variances",
"(vector<float>) List of variances to be used "
"in box regression deltas")
.AddCustomChecker([](const std::vector<float>& variances) {
PADDLE_ENFORCE_EQ(
variances.size(), 5UL, "Must and only provide 5 variance.");
for (size_t i = 0; i < variances.size(); ++i) {
PADDLE_ENFORCE_GT(
variances[i], 0.0, "variance[%d] must be greater than 0.", i);
}
});
AddAttr<std::vector<float>>("stride",
"Anchors stride across width and height, "
"with a default of (16, 16)")
.SetDefault(std::vector<float>(2, 16.0))
.AddCustomChecker([](const std::vector<float>& stride) {
PADDLE_ENFORCE_EQ(
stride.size(),
2UL,
"Must and only provide 2 stride for width and height.");
for (size_t i = 0; i < stride.size(); ++i) {
PADDLE_ENFORCE_GT(
stride[i], 0.0, "stride[%d] should be larger than 0.", i);
}
});
AddAttr<float>("offset",
"(float) "
"Anchor center offset, with a default of 0.5")
.SetDefault(0.5);
AddComment(R"DOC(
RotatedAnchorGenerator operator
Generates anchors for RRPN. algorithm.
Each position of the input produce N anchors, N =
size(anchor_sizes) * size(aspect_ratios) * size(angles).
Please get more information from the following papers:
https://arxiv.org/abs/1703.01086.
)DOC");
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OPERATOR(
rotated_anchor_generator,
ops::RotatedAnchorGeneratorOp,
ops::RotatedAnchorGeneratorOpMaker,
paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>,
paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>);
REGISTER_OP_CPU_KERNEL(rotated_anchor_generator,
ops::RotatedAnchorGeneratorOpKernel<float>,
ops::RotatedAnchorGeneratorOpKernel<double>);
| [
"noreply@github.com"
] | littletomatodonkey.noreply@github.com |
e777c48e5f243922c0bddf40b612eab02555a808 | 5bbb7a0aacf260e5c85b2411c877f68576035a58 | /Unit6/split_str6.cpp | cc22be01de6b56c36550211bb6daa896eac62e81 | [] | no_license | HeidiTran/accelerated-c-barbara-moo-andrew-koenig | 80ed03c62f99fe895c6b1da77584fc2e4dd8bb5c | 8205d590ac6b08c83b0cccc3e2ba50ddcf650025 | refs/heads/master | 2022-04-10T21:40:48.581780 | 2020-03-08T15:58:24 | 2020-03-08T15:58:24 | 160,249,414 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,788 | cpp | // This program break a line of input into words
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
#include <cctype>
#include <algorithm>
#include <iterator>
#include <list>
using namespace std;
bool isSpace(const char& c)
{
return isspace(c);
}
bool not_space(const char& c)
{
return !isspace(c);
}
// Split and return a vector contain words
vector<string> split(const string& str)
{
typedef string::const_iterator iter;
vector<string> ret;
iter i = str.begin();
while (i != str.end())
{
i = find_if(i, str.end(), not_space);
iter j = find_if(i, str.end(), isSpace);
ret.push_back(string(i, j));
i = j;
}
return ret;
}
// Out: output iterator. We can use split with any kind of iterator (forward, bidirectional, random-access iterators)
// EXCEPT a pure Input iterator such as istream_iterator
template <class Out>
void split(const string& str, Out os)
{
typedef string::const_iterator iter;
iter i = str.begin();
while (i != str.end())
{
i = find_if(i, str.end(), not_space);
iter j = find_if(i, str.end(), isSpace);
if (i != str.end())
*os++ = string(i, j);
i = j;
}
}
int main() {
string s;
/*
// Write words into almost any kind of container + use different types of iterators
// This example append the words after split function to a list called word_list
list<string> word_list;
while (getline(cin, s))
{
split(s, back_inserter(word_list));
//split(s, front_inserter(word_list));
for (list<string>::iterator it = word_list.begin(); it != word_list.end(); it++)
cout << *it << endl;
}
*/
// Seperate the input line into separate words, and writes those words onto the standard output
while (getline(cin, s))
{
split(s, ostream_iterator<string>(cout, "\n"));
}
return 0;
} | [
"HeidiTran1410@gmail.com"
] | HeidiTran1410@gmail.com |
37196b6e131ba535a1c189d610ed0f17a2c2e504 | 75e6a8b381afd2d7cb597004a9a6496d439b3a2b | /lib/rc-switch/RCSwitch.h | 36a28407d368d9dbdce224948f8d376e6ad5abd2 | [
"MIT"
] | permissive | SmbatYeranyan/firmware-iot-home-control | 32564ba38b85a4cf79a8fc5c204ee1beaa3ec66d | eed8d214c9d5b55e372868925ce25603e024c42e | refs/heads/master | 2020-12-25T15:17:58.201103 | 2016-11-02T08:55:59 | 2016-11-02T08:55:59 | 64,009,256 | 0 | 0 | null | null | null | null | ISO-8859-3 | C++ | false | false | 4,938 | h | /*
RCSwitch - Arduino libary for remote control outlet switches
Copyright (c) 2011 Suat Özgür. All right reserved.
Contributors:
- Andre Koehler / info(at)tomate-online(dot)de
- Gordeev Andrey Vladimirovich / gordeev(at)openpyro(dot)com
- Skineffect / http://forum.ardumote.com/viewtopic.php?f=2&t=46
- Dominik Fischer / dom_fischer(at)web(dot)de
- Frank Oltmanns / <first name>.<last name>(at)gmail(dot)com
Project home: http://code.google.com/p/rc-switch/
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _RCSwitch_h
#define _RCSwitch_h
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#elif defined(ENERGIA) // LaunchPad, FraunchPad and StellarPad specific
#include "Energia.h"
#else
#include "WProgram.h"
#endif
// At least for the ATTiny X4/X5, receiving has to be disabled due to
// missing libm depencies (udivmodhi4)
#if defined( __AVR_ATtinyX5__ ) or defined ( __AVR_ATtinyX4__ )
#define RCSwitchDisableReceiving
#endif
// Number of maximum High/Low changes per packet.
// We can handle up to (unsigned long) => 32 bit * 2 H/L changes per bit + 2 for sync
#define RCSWITCH_MAX_CHANGES 67
#define PROTOCOL3_SYNC_FACTOR 71
#define PROTOCOL3_0_HIGH_CYCLES 4
#define PROTOCOL3_0_LOW_CYCLES 11
#define PROTOCOL3_1_HIGH_CYCLES 9
#define PROTOCOL3_1_LOW_CYCLES 6
class RCSwitch {
public:
RCSwitch();
void switchOn(int nGroupNumber, int nSwitchNumber);
void switchOff(int nGroupNumber, int nSwitchNumber);
void switchOn(char* sGroup, int nSwitchNumber);
void switchOff(char* sGroup, int nSwitchNumber);
void switchOn(char sFamily, int nGroup, int nDevice);
void switchOff(char sFamily, int nGroup, int nDevice);
void switchOn(char* sGroup, char* sDevice);
void switchOff(char* sGroup, char* sDevice);
void switchOn(char sGroup, int nDevice);
void switchOff(char sGroup, int nDevice);
void sendTriState(char* Code);
void send(unsigned long Code, unsigned int length);
void send(char* Code);
#if not defined( RCSwitchDisableReceiving )
void enableReceive(int interrupt);
void enableReceive();
void disableReceive();
bool available();
void resetAvailable();
unsigned long getReceivedValue();
unsigned int getReceivedBitlength();
unsigned int getReceivedDelay();
unsigned int getReceivedProtocol();
unsigned int* getReceivedRawdata();
#endif
void enableTransmit(int nTransmitterPin);
void disableTransmit();
void setPulseLength(int nPulseLength);
void setRepeatTransmit(int nRepeatTransmit);
#if not defined( RCSwitchDisableReceiving )
void setReceiveTolerance(int nPercent);
#endif
void setProtocol(int nProtocol);
void setProtocol(int nProtocol, int nPulseLength);
private:
char* getCodeWordB(int nGroupNumber, int nSwitchNumber, boolean bStatus);
char* getCodeWordA(char* sGroup, int nSwitchNumber, boolean bStatus);
char* getCodeWordA(char* sGroup, char* sDevice, boolean bStatus);
char* getCodeWordC(char sFamily, int nGroup, int nDevice, boolean bStatus);
char* getCodeWordD(char group, int nDevice, boolean bStatus);
void sendT0();
void sendT1();
void sendTF();
void send0();
void send1();
void sendSync();
void transmit(int nHighPulses, int nLowPulses);
static char* dec2binWzerofill(unsigned long dec, unsigned int length);
static char* dec2binWcharfill(unsigned long dec, unsigned int length, char fill);
#if not defined( RCSwitchDisableReceiving )
static void handleInterrupt();
static bool receiveProtocol1(unsigned int changeCount);
static bool receiveProtocol3(unsigned int changeCount);
int nReceiverInterrupt;
#endif
int nTransmitterPin;
int nPulseLength;
int nRepeatTransmit;
char nProtocol;
#if not defined( RCSwitchDisableReceiving )
static int nReceiveTolerance;
static unsigned long nReceivedValue;
static unsigned int nReceivedBitlength;
static unsigned int nReceivedDelay;
static unsigned int nReceivedProtocol;
#endif
/*
* timings[0] contains sync timing, followed by a number of bits
*/
static unsigned int timings[RCSWITCH_MAX_CHANGES];
};
#endif
| [
"smbat.yeranyan@gmail.com"
] | smbat.yeranyan@gmail.com |
6e9bb3a2414ebe55ef2522d87b36d2c1ea27db6f | 8b69b0fa5665d972658b9a0b8609e2f6722658dd | /QtUtility/minidump.cpp | f5b6c534dbe4cb8364598e77e2bfa48851c6a386 | [] | no_license | hcz362329/hcz362329-QtUtility | 19cbdb59a920573d0882a053d599e016a7237beb | b7c16fdad89b1b917e4b463838f81502dc9b00ee | refs/heads/master | 2022-11-15T08:16:43.047133 | 2020-07-08T03:55:04 | 2020-07-08T03:55:04 | 250,267,308 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 10,249 | cpp | #include "MiniDump.h"
#include "Shlwapi.h"
#pragma comment(lib,"Shlwapi.lib")
static void hprintf(HANDLE LogFile, LPCTSTR format, ...)
{
TCHAR buffer[2000]; // wvsprintf never prints more than one K.
va_list arglist;
va_start(arglist, format);
wvsprintf(buffer, format, arglist);
va_end(arglist);
DWORD NumBytes;
WriteFile(LogFile, buffer, lstrlen(buffer) * sizeof(TCHAR), &NumBytes, 0);
}
static BOOL GetLogicalAddress(PVOID addr, PTSTR szModule, DWORD len, DWORD& section, DWORD& offset)
{
MEMORY_BASIC_INFORMATION mbi;
if (!VirtualQuery(addr, &mbi, sizeof(mbi)))
return FALSE;
DWORD hMod = (DWORD)mbi.AllocationBase;
if (!GetModuleFileName((HMODULE)hMod, szModule, len))
return FALSE;
// Point to the DOS header in memory
PIMAGE_DOS_HEADER pDosHdr = (PIMAGE_DOS_HEADER)hMod;
// From the DOS header, find the NT (PE) header
PIMAGE_NT_HEADERS pNtHdr = (PIMAGE_NT_HEADERS)(hMod + pDosHdr->e_lfanew);
PIMAGE_SECTION_HEADER pSection = IMAGE_FIRST_SECTION(pNtHdr);
DWORD rva = (DWORD)addr - hMod; // RVA is offset from module load address
// Iterate through the section table, looking for the one that encompasses
// the linear address.
for (unsigned i = 0;
i < pNtHdr->FileHeader.NumberOfSections;
i++, pSection++)
{
DWORD sectionStart = pSection->VirtualAddress;
DWORD sectionEnd = sectionStart
+ max(pSection->SizeOfRawData, pSection->Misc.VirtualSize);
// Is the address in this section???
if ((rva >= sectionStart) && (rva <= sectionEnd))
{
// Yes, address is in the section. Calculate section and offset,
// and store in the "section" & "offset" params, which were
// passed by reference.
section = i + 1;
offset = rva - sectionStart;
return TRUE;
}
}
return FALSE; // Should never get here!
}
MiniDump::MiniDump()
{
}
MiniDump::~MiniDump()
{
}
void MiniDump::EnableAutoDump(bool bEnable)
{
if (bEnable)
{
SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ApplicationCrashHandler);
}
}
LONG MiniDump::ApplicationCrashHandler(EXCEPTION_POINTERS *pException)
{
/*if (IsDebuggerPresent())
{
return EXCEPTION_CONTINUE_SEARCH;
}*/
static int n = 0;
n++;
TCHAR szDumpDir[MAX_PATH] = { 0 };
TCHAR szDumpFile[MAX_PATH] = { 0 };
TCHAR szMsg[MAX_PATH] = { 0 };
SYSTEMTIME stTime = { 0 };
// 构建dump文件路径;
GetLocalTime(&stTime);
GetModuleFileName(NULL, szDumpDir, MAX_PATH);
*(wcsrchr(szDumpDir,'\\'))=0;
//::GetCurrentDirectory(MAX_PATH, szDumpDir);
TSprintf(szDumpFile, _T("%s\\%04d%02d%02d_%02d%02d%02d-%d.dmp"), szDumpDir,
stTime.wYear, stTime.wMonth, stTime.wDay,
stTime.wHour, stTime.wMinute, stTime.wSecond,n);
// 创建dump文件;
//::MessageBox(0, 0, 0, 0);
WriteErrorLog(pException);
CreateDumpFile(szDumpFile, pException);
// 弹出一个错误对话框或者提示上传, 并退出程序;
TSprintf(szMsg, _T("I'm so sorry, but the program crashed.\r\ndump file : %s"), szDumpFile);
//FatalAppExit(-1, szMsg);
return EXCEPTION_EXECUTE_HANDLER;
}
void MiniDump::CreateDumpFile(LPCWSTR strPath, EXCEPTION_POINTERS *pException)
{
// 创建Dump文件;
HANDLE hDumpFile = CreateFile(strPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
// Dump信息;
MINIDUMP_EXCEPTION_INFORMATION dumpInfo;
dumpInfo.ExceptionPointers = pException;
dumpInfo.ThreadId = GetCurrentThreadId();
dumpInfo.ClientPointers = FALSE;
// 写入Dump文件内容;
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, (MINIDUMP_TYPE)(MiniDumpNormal | MiniDumpWithDataSegs), &dumpInfo, NULL, NULL);
CloseHandle(hDumpFile);
}
void MiniDump::WriteErrorLog(PEXCEPTION_POINTERS pExInfo) {
PEXCEPTION_RECORD pException = pExInfo->ExceptionRecord;
PCONTEXT pContext = pExInfo->ContextRecord;
MEMORY_BASIC_INFORMATION memInfo;
TCHAR szDumpDir[MAX_PATH] = {0};
GetModuleFileName(NULL, szDumpDir, MAX_PATH);
*(wcsrchr(szDumpDir, '\\')) = 0;
TCHAR szErrorLog[MAX_PATH * 2] = { 0 };
lstrcat(szErrorLog, _T("./Error.Log"));
TSprintf(szErrorLog, _T("%s\\Error.Log"), szDumpDir);
BOOL bFileExists = PathFileExists(szErrorLog);
HANDLE hLogFile = CreateFile(szErrorLog, GENERIC_WRITE, 0, 0,
bFileExists ? OPEN_EXISTING : CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, 0);
if (hLogFile != INVALID_HANDLE_VALUE)
{
TCHAR szTemp[256];
if (bFileExists)
{
// 末尾追加
SetFilePointer(hLogFile, 0, NULL, FILE_END);
hprintf(hLogFile, _T("\r\n--------------------\r\n"));
}
SYSTEMTIME stTime = { 0 };
// 构建dump文件路径;
GetLocalTime(&stTime);
wsprintf(szTemp, _T("%02d-%02d-%02d %02d:%02d:%02d\r\n"),
stTime.wYear, stTime.wMonth, stTime.wDay,
stTime.wHour, stTime.wMinute, stTime.wSecond);
hprintf(hLogFile, szTemp);
hprintf(hLogFile, _T("qtutility log\r\n"));
//Program Information:
hprintf(hLogFile, _T("\r\nProgram Information:\r\n"));
//System Information:
hprintf(hLogFile, _T("\r\nSystem Information:\r\n"));
//操作系统信息
//DirectX信息
//显示设备信息
//CPU类型
//内存
MEMORYSTATUSEX memoryStatus;
memset(&memoryStatus, sizeof(MEMORYSTATUS), 0);
memoryStatus.dwLength = sizeof(MEMORYSTATUS);
GlobalMemoryStatusEx(&memoryStatus);
hprintf(hLogFile, _T("Memory: [Available]%I64dM / [Total]%I64dM \r\n"), memoryStatus.ullAvailPhys >> 20, memoryStatus.ullTotalPhys >> 20);
//硬盘
TCHAR szBuffer[MAX_PATH];
ZeroMemory(szBuffer, sizeof(szBuffer));
GetWindowsDirectory(szBuffer, sizeof(szBuffer));
TCHAR szHarddisk[MAX_PATH];
lstrcpy(szHarddisk, szBuffer);
TCHAR * pszDisk = wcschr(szHarddisk, _T(':'));
if (pszDisk != NULL)
{
szHarddisk[pszDisk - szHarddisk + 1] = 0;
}
if (GetProcAddress(GetModuleHandle(_T("kernel32.dll")), "GetDiskFreeSpaceExA"))
{
ULARGE_INTEGER ulAvailable;
ULARGE_INTEGER ulTotal;
ULARGE_INTEGER ulFree;
GetDiskFreeSpaceEx(szHarddisk, &ulAvailable, &ulTotal, &ulFree);
hprintf(hLogFile, _T("System Disk: [Available]%ldM / [Total]%ldM\r\n"), (ulFree.HighPart << (32 - 20)) + (ulFree.LowPart >> 20),
(ulTotal.HighPart << (32 - 20)) + (ulTotal.LowPart >> 20));
}
else
{
DWORD dwSectorsPerCluster; // sectors per cluster
DWORD dwBytesPerSector; // bytes per sector
DWORD dwNumberOfFreeClusters; // free clusters
DWORD dwTotalNumberOfClusters; // total clusters
GetDiskFreeSpace(szHarddisk, &dwSectorsPerCluster, &dwBytesPerSector, &dwNumberOfFreeClusters, &dwTotalNumberOfClusters);
hprintf(hLogFile, _T("System Disk: [Available]%ldM / [Total]%ldM\r\n"), ((((dwNumberOfFreeClusters*dwSectorsPerCluster) >> 10)*dwBytesPerSector) >> 10,
(((dwTotalNumberOfClusters*dwSectorsPerCluster) >> 10)*dwBytesPerSector) >> 10));
}
//网络
//是否设置了代理服务器
//是否在防火墙内
//IP地址
//Error Information:
hprintf(hLogFile, _T("\r\nError Information:\r\n"));
TCHAR szCrashModuleName[MAX_PATH] = { _T("Unknown") };
if (VirtualQuery((void*)pContext->Eip, &memInfo, sizeof(memInfo)) &&
GetModuleFileName((HINSTANCE)memInfo.AllocationBase, szCrashModuleName, sizeof(szCrashModuleName)) > 0)
{
}
hprintf(hLogFile, _T("Error Module:%s \r\n"), szCrashModuleName);
hprintf(hLogFile, _T("Code: 0x%08x \r\n"), pException->ExceptionCode);
hprintf(hLogFile, _T("Flag: 0x%08x \r\n"), pException->ExceptionFlags);
hprintf(hLogFile, _T("Addr: 0x%08x \r\n"), pException->ExceptionAddress);
if (EXCEPTION_ACCESS_VIOLATION == pException->ExceptionCode)
{
for (int i = 0; i < (int)pException->NumberParameters; i++)
{
hprintf(hLogFile, _T("%d: %d(0x%08x)\r\n"), i, pException->ExceptionInformation[i], pException->ExceptionInformation[i]);
}
if (pException->NumberParameters >= 2)
{
TCHAR szReadWrite[256] = { 0 };
if (pException->ExceptionInformation[0])
{
lstrcpy(szReadWrite, _T("Write to"));
}
else
{
lstrcpy(szReadWrite, _T("Read from"));
}
hprintf(hLogFile, _T("%s location %08x caused an access violation.\r\n"), szReadWrite, pException->ExceptionInformation[1]);
}
}
hprintf(hLogFile, _T("Caused error at %04x:%08x.\r\n"), pContext->SegCs, pContext->Eip);
hprintf(hLogFile, _T("\r\nRegisters:\r\n"));
hprintf(hLogFile, _T("EAX=%08x CS=%04x EIP=%08x EFLGS=%08x\r\n"),
pContext->Eax, pContext->SegCs, pContext->Eip, pContext->EFlags);
hprintf(hLogFile, _T("EBX=%08x SS=%04x ESP=%08x EBP=%08x\r\n"),
pContext->Ebx, pContext->SegSs, pContext->Esp, pContext->Ebp);
hprintf(hLogFile, _T("ECX=%08x DS=%04x ESI=%08x FS=%04x\r\n"),
pContext->Ecx, pContext->SegDs, pContext->Esi, pContext->SegFs);
hprintf(hLogFile, _T("EDX=%08x ES=%04x EDI=%08x GS=%04x\r\n"),
pContext->Edx, pContext->SegEs, pContext->Edi, pContext->SegGs);
int NumCodeBytes = 16; // Number of code bytes to record.
hprintf(hLogFile, _T("Bytes at CS:EIP:\r\n"));
unsigned char *code = (unsigned char*)pContext->Eip;
for (int codebyte = 0; codebyte < NumCodeBytes; codebyte++)
{
__try
{
hprintf(hLogFile, _T("%02x "), code[codebyte]);
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
hprintf(hLogFile, _T("?? "));
}
}
hprintf(hLogFile, _T("\r\n"));
hprintf(hLogFile, _T("Call Stack:\r\n"));
DWORD pc = pContext->Eip;
PDWORD pFrame, pPrevFrame;
pFrame = (PDWORD)pContext->Ebp;
do
{
TCHAR szModule[MAX_PATH] = _T("");
DWORD section = 0, offset = 0;
__try
{
if (GetLogicalAddress((PVOID)pc, szModule, sizeof(szModule), section, offset) == FALSE)
{
break;
}
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
break;
}
hprintf(hLogFile, _T("%08X %04X:%08X %s\r\n"), pc, section, offset, szModule);
pc = pFrame[1];
pPrevFrame = pFrame;
pFrame = (PDWORD)pFrame[0]; // precede to next higher frame on stack
if ((DWORD)pFrame & 3) // Frame pointer must be aligned on a
break; // DWORD boundary. Bail if not so.
if (pFrame <= pPrevFrame)
break;
// Can two DWORDs be read from the supposed frame address?
if (IsBadWritePtr(pFrame, sizeof(PVOID) * 2))
break;
} while (1);
hprintf(hLogFile, _T("\r\n"));
hprintf(hLogFile, _T("\r\nqtutility error log end......\r\n"));
CloseHandle(hLogFile);
}
else
{
}
} | [
"hcz362329@163.com"
] | hcz362329@163.com |
8fc1fcfe48157816f39c1b961a75fd81dbc832d7 | 56b063c7daaa33fe03d15373261d9432b7204626 | /examples/01_Polling/ErriezMCP23017_MultiplePins/ErriezMCP23017_MultiplePins.ino | bc59ebac25bdcdb95be8769ea3128dc2e7b43a51 | [
"MIT"
] | permissive | Erriez/ErriezMCP23017 | d16e6c280db0036cb736d0f150cf5d7f2f64b23c | 93b431d8059bff3590e6c2baa0433f3005477a2b | refs/heads/master | 2021-05-26T22:53:44.806736 | 2020-09-06T09:34:06 | 2020-09-06T09:34:06 | 254,180,771 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,741 | ino | /*
* MIT License
*
* Copyright (c) 2020 Erriez
*
* 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.
*/
/*!
* \brief MCP23017 I2C 16-pin IO-expander example for Arduino
* \details
* Source: https://github.com/Erriez/ErriezMCP23017
* Documentation: https://erriez.github.io/ErriezMCP23017
*
* This example demonstrates the "Arduino easy" way to handle inputs and
* outputs. Handling inputs and outputs simultanesouly is not possible,
* because this example uses a blocking delay(). Please refer to PinPort
* example to handle inputs and outputs currently.
*
* Hardware:
* - MCP23017 SDA, SCL connected to MCU I2C (TWI) pins
* - PA0..PA7: Button input with pull-up
* - PB0..PB7: LED output
*/
#include <Arduino.h>
#include <Wire.h>
#include <ErriezMCP23017.h>
// Default I2C Address 0x20
#define MCP23017_I2C_ADDRESS 0x20
// Create MCP23017 object
ErriezMCP23017 mcp = ErriezMCP23017(MCP23017_I2C_ADDRESS);
static void handleOutputs()
{
Serial.println(F("Shift output PORTB..."));
// Pins B0..B7 HIGH with a blocking delay
for (uint8_t outputPin = 8; outputPin <= 15; outputPin++) {
mcp.digitalWrite(outputPin, HIGH);
delay(100);
}
// Pins B0..B7 LOW with a blocking delay
for (uint8_t outputPin = 15; outputPin >= 7; outputPin--) {
mcp.digitalWrite(outputPin, LOW);
delay(100);
}
}
static void handleInputs()
{
Serial.println(F("Input PORTA:"));
// Print state input pins PORTA
for (uint8_t inputPin = 0; inputPin <= 7; inputPin++) {
Serial.print(F(" A"));
Serial.print(inputPin);
Serial.print(F(": "));
if (mcp.digitalRead(inputPin)) {
Serial.println(F("HIGH"));
} else {
Serial.println(F("LOW"));
}
}
}
void setup()
{
// Initialize Serial
Serial.begin(115200);
Serial.println(F("\nErriez MCP23017 I2C IO-expander Multiple Pin example"));
// Initialize Wire
Wire.begin();
Wire.setClock(400000);
// Initialize MCP23017
while (!mcp.begin()) {
Serial.print(F("Error: MCP23017 not found, code: "));
Serial.println(mcp.getI2CStatus());
delay(3000);
}
// Pins A0..A7 input with pull-up enabled
for (uint8_t inputPin = 0; inputPin <= 7; inputPin++) {
mcp.pinMode(inputPin, INPUT_PULLUP);
}
// Pins B0..B7 output
for (uint8_t outputPin = 8; outputPin <= 15; outputPin++) {
mcp.pinMode(outputPin, OUTPUT);
}
// Print registers
// mcp.dumpRegisters(&Serial);
}
void loop()
{
// Synchronous call to handle outputs
handleOutputs();
// Handle inputs
handleInputs();
}
| [
"erriez@users.noreply.github.com"
] | erriez@users.noreply.github.com |
ac49f19d18ce1d80ece1f16509d2b29b441cffed | 54cfb83f5ad185d343562b812723b8fc59c75d5b | /Mega Man X3/Mega Man X3/QuadTree.h | ea1405d2102a3399caa15950edb694abbea93dc2 | [] | no_license | vantranguit920/Game-MegamanX3 | 3a98db9be2471c6d83b15f02553d8f34b40ad9ff | 58fe7924d7c3395a7b361a30bd55a28961a4fdf5 | refs/heads/master | 2022-01-31T06:18:25.652911 | 2019-06-05T08:04:17 | 2019-06-05T08:04:17 | 190,344,169 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 615 | h | #pragma once
#include <d3dx9.h>
#include <d3d9.h>
#include <vector>
#include "Viewport.h"
#include "Object.h"
class QuadTree
{
protected:
int GetIndex(RECT r);
void Split();
bool IsContain(RECT r);
public:
QuadTree();
QuadTree(int level, RECT bound);
~QuadTree();
void Clear();
void InsertObject(Object *object);
void GetObjectsCollideAble(std::vector<Object*> &listObject, std::vector<Object*> &listWall, RECT rect);
void GetAllObject(std::vector<Object*> &listObject, RECT rect);
int GetTotalObject();
RECT Bound;
int mLevel;
std::vector<Object*> mListObject;
QuadTree **Nodes;
}; | [
"="
] | = |
5b128d41003329c693cded6d8d74c457ed970a2c | 584a9ef92a9eb07d34f1df5e1f7a6aa64528193c | /Vector.inl | fff012780485056e109231ff6372e2d6d69e4da4 | [] | no_license | hp298/Hand-Writing-Recognition-Project | b2cf245f6e3892c1d71933704f03f63a7aac7803 | 6b251c42dba06580df0a3a0ccc51eb77fec0e830 | refs/heads/master | 2022-12-18T08:46:49.919831 | 2020-09-26T15:00:40 | 2020-09-26T15:00:40 | 298,836,363 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 4,008 | inl | //========================================================================
// Vector.inl
//========================================================================
// Implementation of Vector.
#include "ece2400-stdlib.h"
#include "sort.h"
//'''' ASSIGNMENT TASK '''''''''''''''''''''''''''''''''''''''''''''''''''
// Implement Vector.
//''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
// default constructor
template < typename T >
Vector<T>::Vector()
{
m_size = 0;
m_maxSize = 1;
m_a = new T[1];
}
// destructor
template < typename T >
Vector<T>::~Vector()
{
if (m_maxSize != 0)
clear();
}
// copy constructor
template < typename T >
Vector<T>::Vector( const Vector<T>& vec )
{
copy( vec.m_a, vec.m_size, vec.m_maxSize );
}
// non-default constructor
template < typename T >
Vector<T>::Vector( T* a, size_t size )
{
if ( size == 0 )
Vector<T>();
else
copy( a, size, size );
}
// = operator
template < typename T >
Vector<T>& Vector<T>::operator=( const Vector<T>& vec )
{
if ( this != &vec )
copy( vec.m_a, vec.m_size, vec.m_maxSize );
return *this;
}
// size function
template < typename T >
size_t Vector<T>::size() const
{
return m_size;
}
// vector push back
template < typename T >
void Vector<T>::push_back( const T& v )
{
if ( m_maxSize == 0 ) {
clear();
m_maxSize = 1;
m_a = new T[1];
}
if ( m_size >= m_maxSize ) {
T *a = new T[m_size];
for ( size_t i = 0; i < m_size; i++ )
a[i] = m_a[i];
size_t size = m_size;
size_t maxSize = ( 2 * size );
copy( a, size, maxSize );
delete[] a;
}
m_a[m_size] = v;
m_size++;
}
// at const
template < typename T >
const T& Vector<T>::at( size_t idx ) const
{
if ( idx < m_size )
return m_a[idx];
else
throw ece2400::OutOfRange("Index value must be less the size.");
}
// at
template < typename T >
T& Vector<T>::at( size_t idx )
{
if ( idx < m_size )
return m_a[idx];
else
throw ece2400::OutOfRange("Index value must be less the size.");
}
// find
template < typename T >
bool Vector<T>::find( const T& v ) const
{
for ( size_t i = 0; i < m_size; i++ ) {
if ( m_a[i] == v )
return true;
}
return false;
}
// find closests
template < typename T >
const T& Vector<T>::find_closest( const T& v ) const
{
if ( m_size < 2 ) {
if ( m_size == 0 )
throw ece2400::OutOfRange("The vector is empty.");
return m_a[0];
}
size_t closestIdx = 0;
auto min = abs( m_a[0] - v );
for( size_t i = 0; i < m_size; i++ ) {
auto diff = abs( m_a[i] - v );
if ( diff == 0 )
return m_a[i];
if ( diff < min ) {
closestIdx = i;
min = abs( m_a[i] - v );
}
}
return m_a[closestIdx];
}
// sort
template < typename T >
void Vector<T>::sort()
{
::sort( m_a, m_size);
}
// print
template < typename T >
void Vector<T>::print() const
{
for( size_t i = 0; i < m_size; i++ )
m_a[i].print();
printf( "\n" );
}
// [] op const
template < typename T >
const T& Vector<T>::operator[]( size_t idx ) const
{
return m_a[idx];
}
// [] op
template < typename T >
T& Vector<T>::operator[]( size_t idx )
{
return m_a[idx];
}
// clear helper
template < typename T >
void Vector<T>::clear()
{
delete[] m_a;
m_size = 0;
m_maxSize = 0;
}
// copy helper
template < typename T >
void Vector<T>::copy( T *a, size_t size, size_t maxSize )
{
if ( m_maxSize != 0 )
clear();
m_size = size;
m_maxSize = maxSize;
m_a = new T[m_maxSize];
for( size_t i = 0; i < m_size; i++ )
m_a[i] = a[i];
}
// hrs-alt find closests
template < typename T >
const T& Vector<T>::find_closest_alt( const T& v)
{
size_t closestIdx = 0;
auto min = abs( m_a[0] - v );
for( size_t i = 0; i < m_size; i++ ) {
auto diff = abs( m_a[i] - v );
if ( diff == 0 )
return m_a[i];
if ( diff < min ) {
closestIdx = i;
min = abs( m_a[i] - v );
}
}
m_altVar = closestIdx;
return m_a[closestIdx];
}
| [
"noreply@github.com"
] | hp298.noreply@github.com |
607d13340523fee829413d8f7b4ab7ada967b1d6 | 923848f44bb26cc20724bbe9d605b384a236e80c | /Лабораторная работа№9.cpp | d70e9eb1b83f80728a74adecac6740f130753f12 | [] | no_license | AlisaTarasova/Laboratory_9 | 8097c4fddc4002b153ea05929a6d3c14edcb0ad6 | e3d0d11977bc664245a4f1a849039a8613e8f466 | refs/heads/main | 2023-04-29T22:17:52.975334 | 2021-05-22T09:56:15 | 2021-05-22T09:56:15 | 369,772,168 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,045 | cpp | #include <iostream>
#include <fstream>
#include <string>
using namespace std;
void Vvod(int N1, int N2, int n)
{
if (N2 - N1 == 1)
{
cout << "Между строками N1 и N2 нет строк."<<endl;
}
else
{
ifstream F1("F1.txt");
ofstream F2("F2.txt");
if (F1.is_open() && F2.is_open())
{
int i = 1;
while (!F1.eof())
{
string str;
getline(F1, str);
if (str[0] == 'а')
{
if ((i > N1) && (i < N2))
{
F2 << str << endl;
}
}
i++;
}
F1.close();
F2.close();
}
else
cout << "Не удалось открыть файлы F1.txt или F2.txt для копирования."<< endl;
}
}
void Shet(int i, int j, int k, int num)
{
ifstream F2("F2.txt");
if (F2.is_open())
{
while (!F2.eof())
{
string str;
getline(F2, str);
i = 0;
while (str[i] !=NULL)
{
if (str[i] != ' ' && str[i] != 'а' && str[i] != 'у' && str[i] != 'е' && str[i] != 'ы' &&
str[i] != 'о' && str[i] != 'э' && str[i] != 'я' && str[i] != 'и' && str[i] != 'ю')
j++;
i++;
}
if (j > k)
{
k = j;
num++;
}
j = 0;
}
if (k != 0)
cout << "Больше всего согласных букв в строке под № " << num << ", количество согласных букв = " << k;
else
cout << "В файде F2.txt нет строк или нет строк с согласными буквами.";
}
else
cout<< "Не удалось открыть файл F2.txt для подсчёта согласных букв.";
}
int main()
{
system("color F0");
setlocale(0, "");
int n = 0;
int N1, N2;
ifstream F1("F1.txt");
if (F1.is_open())
{
while (!F1.eof())
{
string str;
getline(F1, str);
n++;
}
}
else
cout << "Не удалось открыть файл F1.txt для подсчёта строк.";
F1.close();
if (n > 2)
{
cout << "Введите N1: ";
cin >> N1;
while ((N1 <= 0) || (N1 > n - 2))
{
cout << "Введите N1: ";
cin >> N1;
}
cout << "Введите N2: ";
cin >> N2;
while ((N2 <= N1) || (N2 > n))
{
cout << "Введите N2: ";
cin >> N2;
}
Vvod(N1, N2, n);
Shet(0, 0, 0, 0);
}
else
cout << "Файл F1 не был открыт или в нём меньше двух строк.";
return 0;
}
| [
"noreply@github.com"
] | AlisaTarasova.noreply@github.com |
e354035c7126ffec8166505540f358db6739ebad | 299d2a05d40c2962332abc83e203a3160906d53b | /w1_SimpleEcho/eServer.cpp | bd874e9448d8da8ca764869bdb4aa0921d96f11d | [] | no_license | woodok/w1_SimpleEcho | de49bc275f49926e9b6af21e3cc79f5a25777346 | 99af62f2e5f4186c0a7787885ba4ba961fce9446 | refs/heads/master | 2020-12-24T14:01:19.998896 | 2015-07-08T06:02:28 | 2015-07-08T06:02:28 | 37,452,633 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 3,483 | cpp | #include <iostream>
//#include <stdio.h>
#include <cstdio>
//#include <stdlib.h>
#include <cstdlib>
#include <process.h>
#include <WinSock2.h>
#include <Windows.h>
#define BUF_SIZE 100
#define READ 3
#define WRITE 5
typedef struct
{
SOCKET hClntSock;
SOCKADDR_IN clntAdr;
} PER_HANDLE_DATA, *LPPER_HANDLE_DATA;
typedef struct
{
OVERLAPPED overlapped;
WSABUF wsaBuf;
char buffer[BUF_SIZE];
int rwMode; // read mode / write mode distinguisher
} PER_IO_DATA, *LPPER_IO_DATA;
DWORD WINAPI EchoThreadMain(LPVOID CompletionPortIO);
void ErrorHandling(char * mesaage);
int main(int argc, char * argv[])
{
WSADATA wsaData;
HANDLE hComPort;
SYSTEM_INFO sysInfo;
LPPER_IO_DATA ioInfo;
LPPER_HANDLE_DATA handleInfo;
SOCKET hServSock;
SOCKADDR_IN servAdr;
int recvBytes, i, flags = 0;
if (argc != 2) {
printf("Usage : %s <port>\n", argv[0]);
exit(1);
}
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
ErrorHandling("WSAStartup() error");
hComPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
GetSystemInfo(&sysInfo);
for (i = 0; i < (int)(sysInfo.dwNumberOfProcessors); i++)
_beginthreadex(NULL, 0, (unsigned int (__stdcall *)(void *))EchoThreadMain, (LPVOID)hComPort, 0, NULL);
hServSock = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED);
memset(&servAdr, 0, sizeof(servAdr));
servAdr.sin_family = AF_INET;
servAdr.sin_addr.s_addr = htonl(INADDR_ANY);
servAdr.sin_port = htons(atoi(argv[1]));
bind(hServSock, (SOCKADDR *)&servAdr, sizeof(servAdr));
listen(hServSock, 5);
while (1)
{
SOCKET hClntSock;
SOCKADDR_IN clntAdr;
int addrLen = sizeof(clntAdr);
hClntSock = accept(hServSock, (SOCKADDR *)&clntAdr, &addrLen);
handleInfo = (LPPER_HANDLE_DATA)malloc(sizeof(PER_HANDLE_DATA));
handleInfo->hClntSock = hClntSock;
memcpy(&(handleInfo->clntAdr), &clntAdr, addrLen);
CreateIoCompletionPort((HANDLE)hClntSock, hComPort, (DWORD)handleInfo, 0);
ioInfo = (LPPER_IO_DATA)malloc(sizeof(PER_IO_DATA));
memset(&(ioInfo->overlapped), 0, sizeof(OVERLAPPED));
ioInfo->wsaBuf.len = BUF_SIZE;
ioInfo->wsaBuf.buf = ioInfo->buffer;
ioInfo->rwMode = READ;
WSARecv(handleInfo->hClntSock, &(ioInfo->wsaBuf), 1, (LPDWORD)&recvBytes, (LPDWORD)&flags, &(ioInfo->overlapped), NULL);
}
return 0;
}
DWORD WINAPI EchoThreadMain(LPVOID pComPort)
{
HANDLE hComPort = (HANDLE)pComPort;
SOCKET sock;
DWORD bytesTrans;
LPPER_HANDLE_DATA handleInfo;
LPPER_IO_DATA ioInfo;
DWORD flags = 0;
while (1)
{
GetQueuedCompletionStatus(hComPort, &bytesTrans, (LPDWORD)&handleInfo, (LPOVERLAPPED *)&ioInfo, INFINITE);
sock = handleInfo->hClntSock;
if (ioInfo->rwMode == READ)
{
puts("message received");
if (bytesTrans == 0) // EOF Àü¼Û½Ã
{
closesocket(sock);
free(handleInfo); free(ioInfo);
continue;
}
memset(&(ioInfo->overlapped), 0, sizeof(OVERLAPPED));
ioInfo->wsaBuf.len = bytesTrans;
ioInfo->rwMode = WRITE;
WSASend(sock, &(ioInfo->wsaBuf), 1, NULL, 0, &(ioInfo->overlapped), NULL);
ioInfo = (LPPER_IO_DATA)malloc(sizeof(PER_IO_DATA));
memset(&(ioInfo->overlapped), 0, sizeof(OVERLAPPED));
ioInfo->wsaBuf.len = BUF_SIZE;
ioInfo->wsaBuf.buf = ioInfo->buffer;
ioInfo->rwMode = READ;
WSARecv(sock, &(ioInfo->wsaBuf), 1, NULL, &flags, &(ioInfo->overlapped), NULL);
}
else
{
puts("message sent");
free(ioInfo);
}
}
return 0;
}
void ErrorHandling(char * message)
{
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
} | [
"newwoodok@gmail.com"
] | newwoodok@gmail.com |
0e20fdbd84c58b50c7371ecf21d8b78d3b5591b5 | 4351f7b1d0f8e9a7168525ae17515cc802b6c254 | /W452. Minimum Number of Arrows to Burst Balloons.cpp | 78dce7f8391b294b157cd003646259573675bf82 | [] | no_license | PluckyCoward/WCH_IS_DEAD | a55034e0e5ea0f3a32e1bbec871fdcaf3be8a129 | db20f4ab3388bb310d9cdf9ffdd13e863f9159ec | refs/heads/master | 2023-02-17T19:08:25.082897 | 2021-01-15T09:59:42 | 2021-01-15T09:59:42 | 234,245,320 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 484 | cpp | class Solution {
public:
int findMinArrowShots(vector<vector<int>>& points) {
if(points.empty())
return 0;
sort(points.begin(), points.end(), [](const vector<int> &u, const vector<int> &v){
return u[1] < v[1];
});
int pos = points[0][1];
int res = 1;
for (auto p : points) {
if (p[0] > pos) {
pos = p[1];
res++;
}
}
return res;
}
}; | [
"Wchoward@users.noreply.github.com"
] | Wchoward@users.noreply.github.com |
648c59e40264057e7f76dd20d811ae6b6f6c48ec | ee6a7af57576d722e4c1fe8a0ac1cf47f6c2aa46 | /2-C++E-commerce platform-2021-lab2/src/screen_jump.cpp | 9e80924331b7c82806e62b72c181f55fe074eba6 | [] | no_license | WZH-hub/C-E-commerce-platform-2021 | 3e544e034b4b349e035c9a598c84ef6d5417770a | 9f4b65d742b4ae75978670a12d20c8ac15f7cef1 | refs/heads/master | 2023-06-25T09:42:33.380862 | 2021-07-29T07:48:14 | 2021-07-29T07:48:14 | 390,638,643 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,199 | cpp | #include "screen_jump.h"
using namespace std;
user_func user;
int screen_jump::screen_01()
{
int change = 0;
cout << "****************************************" << endl;
cout << "What do you want to do?" << endl;
cout << "0) quit." << endl;
cout << "1) show all goods." << endl;
cout << "2) show the goods of somebody." << endl;
cout << "3) show the goods of the same kind." << endl;
cout << "4) sign up." << endl;
cout << "5) sign in." << endl;
cout << "6) show the information of consumer." << endl;
cout << "7) show the information of business(with goods)." << endl;
cout << "****************************************" << endl;
cout << "Please input the order in the front:" << endl;
cin.sync(); //清除缓冲区的数据流
user.get_int(change);
while ((change != 0 && change != 1 && change != 2 && change != 3 && change != 4 && change != 5 && change != 6 && change != 7) || cin.fail())
{
if (cin.fail())
{
cin.clear();
cin.sync();
}
cout << "Please input the order again:" << endl;
cin.sync();
user.get_int(change);
}
return change; //因为序号直接对应id,不需要改变
}
int screen_jump::screen_02()
{
int change = 0;
cout << "****************************************" << endl;
cout << "What do you want to do?" << endl;
cout << "0) quit." << endl;
cout << "1) show all goods." << endl;
cout << "2) show the goods of somebody." << endl;
cout << "3) show the goods of the same kind." << endl;
cout << "4) sign up." << endl;
cout << "5) sign in." << endl;
cout << "6) show the information of consumer." << endl;
cout << "7) show the information of business(with goods)." << endl;
cout << "****************************************" << endl;
cout << "Please input the order in the front:" << endl;
cin.sync(); //清除缓冲区的数据流
user.get_int(change);
while ((change != 0 && change != 1 && change != 2 && change != 3 && change != 4 && change != 5 && change != 6 && change != 7) || cin.fail())
{
if (cin.fail())
{
cin.clear();
cin.sync();
}
cout << "Please input the order again:" << endl;
cin.sync();
user.get_int(change);
}
return change; //因为序号直接对应id,不需要改变
}
int screen_jump::screen_03()
{
int change = 0;
cout << "****************************************" << endl;
cout << "What do you want to do?" << endl;
cout << "0) quit." << endl;
cout << "1) show all goods." << endl;
cout << "2) show the goods of somebody." << endl;
cout << "3) show the goods of the same kind." << endl;
cout << "4) sign up." << endl;
cout << "5) sign in." << endl;
cout << "6) show the information of consumer." << endl;
cout << "7) show the information of business(with goods)." << endl;
cout << "****************************************" << endl;
cout << "Please input the order in the front:" << endl;
cin.sync(); //清除缓冲区的数据流
user.get_int(change);
while ((change != 0 && change != 1 && change != 2 && change != 3 && change != 4 && change != 5 && change != 6 && change != 7) || cin.fail())
{
if (cin.fail())
{
cin.clear();
cin.sync();
}
cout << "Please input the order again:" << endl;
cin.sync();
user.get_int(change);
}
return change; //因为序号直接对应id,不需要改变
}
int screen_jump::screen_04()
{
int change = 0;
cout << "****************************************" << endl;
cout << "What do you want to do?" << endl;
cout << "0) quit." << endl;
cout << "1) show all goods." << endl;
cout << "2) show the goods of somebody." << endl;
cout << "3) show the goods of the same kind." << endl;
cout << "4) sign up." << endl;
cout << "5) sign in." << endl;
cout << "****************************************" << endl;
cout << "Please input the order in the front:" << endl;
cin.sync(); //清除缓冲区的数据流
user.get_int(change);
while ((change != 0 && change != 1 && change != 2 && change != 3 && change != 4 && change != 5) || cin.fail())
{
if (cin.fail())
{
cin.clear();
cin.sync();
}
cout << "Please input the order again:" << endl;
cin.sync();
user.get_int(change);
}
return change; //因为序号直接对应id,不需要改变
}
int screen_jump::screen_05(int change)
{
if (change == 1) //商家
return 7;
else if (change == 2) //消费者
return 6;
else if (change == 3) //管理员
return 14;
else
return 1;
}
int screen_jump::screen_06()
{
int change = 0;
cout << "****************************************" << endl;
cout << "What do you want to do?" << endl;
cout << "0) quit." << endl;
cout << "1) show all goods." << endl;
cout << "2) show the goods of somebody." << endl;
cout << "3) show the goods of the same kind." << endl;
cout << "4) sign up." << endl;
cout << "5) sign in." << endl;
cout << "6) recharge." << endl;
cout << "7) change password." << endl;
cout << "8) add the goods to your cart." << endl;
cout << "9) change your cart." << endl;
cout << "10) generate your order." << endl;
cout << "11) pay for your order." << endl;
cout << "****************************************" << endl;
cout << "Please input the order in the front:" << endl;
cin.sync(); //清除缓冲区的数据流
user.get_int(change);
while ((change != 0 && change != 1 && change != 2 && change != 3 && change != 4 && change != 5 && change != 6 && change != 7 && change != 8 && change != 9 && change != 10 && change != 11) || cin.fail())
{
if (cin.fail())
{
cin.clear();
cin.sync();
}
cout << "Please input the order again:" << endl;
cin.sync();
user.get_int(change);
}
switch (change)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
return change;
case 6:
return 8;
case 7:
return 10;
case 8:
return 15;
case 9:
return 16;
case 10:
return 17;
case 11:
return 18;
}
return 1;
}
int screen_jump::screen_07()
{
int change = 0;
cout << "****************************************" << endl;
cout << "What do you want to do?" << endl;
cout << "0) quit." << endl;
cout << "1) show all goods." << endl;
cout << "2) show the goods of somebody." << endl;
cout << "3) show the goods of the same kind." << endl;
cout << "4) sign up." << endl;
cout << "5) sign in." << endl;
cout << "6) change goods information." << endl;
cout << "7) change password." << endl;
cout << "8) add goods." << endl;
cout << "****************************************" << endl;
cout << "Please input the order in the front:" << endl;
cin.sync(); //清除缓冲区的数据流
user.get_int(change);
while ((change != 0 && change != 1 && change != 2 && change != 3 && change != 4 && change != 5 && change != 6 && change != 7 && change != 8) || cin.fail())
{
if (cin.fail())
{
cin.clear();
cin.sync();
}
cout << "Please input the order again:" << endl;
cin.sync();
user.get_int(change);
}
switch (change)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
return change;
case 6:
return 9;
case 7:
return 10;
case 8:
return 11;
}
return 1;
}
int screen_jump::screen_08(int change)
{
//根据反馈的情况进行跳转
//消费者登录且充值成功,返回1;未登录,返回2;放弃充值,返回0
if (change == 1 || change == 0)
return 6;
else //未登录的话跳转到登录界面
return 5;
}
int screen_jump::screen_09()
{
return 7;
}
int screen_jump::screen_10(int change)
{
if (change == 1) //商家
return 7;
else if (change == 2) //消费者
return 6;
else //还没有登录
return 5;
}
int screen_jump::screen_11()
{
return 7;
}
int screen_jump::screen_14()
{
int change = 0;
cout << "****************************************" << endl;
cout << "What do you want to do?" << endl;
cout << "0) quit." << endl;
cout << "1) show all goods." << endl;
cout << "2) show the goods of somebody." << endl;
cout << "3) show the goods of the same kind." << endl;
cout << "4) sign up." << endl;
cout << "5) sign in." << endl;
cout << "****************************************" << endl;
cout << "Please input the order in the front:" << endl;
cin.sync(); //清除缓冲区的数据流
user.get_int(change);
while ((change != 0 && change != 1 && change != 2 && change != 3 && change != 4 && change != 5) || cin.fail())
{
if (cin.fail())
{
cin.clear();
cin.sync();
}
cout << "Please input the order again:" << endl;
cin.sync();
user.get_int(change);
}
return change; //因为序号直接对应id,不需要改变
}
int screen_jump::screen_15()
{
int change = 0;
cout << "****************************************" << endl;
cout << "What do you want to do?" << endl;
cout << "0) quit." << endl;
cout << "1) show all goods." << endl;
cout << "2) show the goods of somebody." << endl;
cout << "3) show the goods of the same kind." << endl;
cout << "4) sign up." << endl;
cout << "5) sign in." << endl;
cout << "6) show the information of consumer." << endl;
cout << "7) show the information of business(with goods)." << endl;
cout << "8) add the goods to your cart." << endl;
cout << "9) change your cart." << endl;
cout << "10) generate your order." << endl;
cout << "****************************************" << endl;
cout << "Please input the order in the front:" << endl;
cin.sync(); //清除缓冲区的数据流
user.get_int(change);
while ((change != 0 && change != 1 && change != 2 && change != 3 && change != 4 && change != 5 && change != 6 && change != 7 && change != 8 && change != 9 && change != 10) || cin.fail())
{
if (cin.fail())
{
cin.clear();
cin.sync();
}
cout << "Please input the order again:" << endl;
cin.sync();
user.get_int(change);
}
switch (change)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
return change;
case 8:
return 15;
case 9:
return 16;
case 10:
return 17;
}
return 1;
}
int screen_jump::screen_16()
{
int change = 0;
cout << "****************************************" << endl;
cout << "What do you want to do?" << endl;
cout << "0) quit." << endl;
cout << "1) show all goods." << endl;
cout << "2) show the goods of somebody." << endl;
cout << "3) show the goods of the same kind." << endl;
cout << "4) sign up." << endl;
cout << "5) sign in." << endl;
cout << "6) show the information of consumer." << endl;
cout << "7) show the information of business(with goods)." << endl;
cout << "8) add the goods to your cart." << endl;
cout << "9) change your cart." << endl;
cout << "10) generate your order." << endl;
cout << "11) pay or cancel your order." << endl;
cout << "****************************************" << endl;
cout << "Please input the order in the front:" << endl;
cin.sync(); //清除缓冲区的数据流
user.get_int(change);
while ((change != 0 && change != 1 && change != 2 && change != 3 && change != 4 && change != 5 && change != 6 && change != 7 && change != 8 && change != 9 && change != 10 && change != 11) || cin.fail())
{
if (cin.fail())
{
cin.clear();
cin.sync();
}
cout << "Please input the order again:" << endl;
cin.sync();
user.get_int(change);
}
switch (change)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
return change;
case 8:
return 15;
case 9:
return 16;
case 10:
return 17;
case 11:
return 18;
}
return 1;
}
int screen_jump::screen_17()
{
int change = 0;
cout << "****************************************" << endl;
cout << "What do you want to do?" << endl;
cout << "0) quit." << endl;
cout << "1) show all goods." << endl;
cout << "2) show the goods of somebody." << endl;
cout << "3) show the goods of the same kind." << endl;
cout << "4) sign up." << endl;
cout << "5) sign in." << endl;
cout << "6) show the information of consumer." << endl;
cout << "7) show the information of business(with goods)." << endl;
cout << "8) add the goods to your cart." << endl;
cout << "9) change your cart." << endl;
cout << "10) generate your order." << endl;
cout << "11) pay or cancel your order." << endl;
//cout << "11) pay for your order." << endl;
cout << "****************************************" << endl;
cout << "Please input the order in the front:" << endl;
cin.sync(); //清除缓冲区的数据流
user.get_int(change);
while ((change != 0 && change != 1 && change != 2 && change != 3 && change != 4 && change != 5 && change != 6 && change != 7 && change != 8 && change != 9 && change != 10 && change != 11) || cin.fail())
{
if (cin.fail())
{
cin.clear();
cin.sync();
}
cout << "Please input the order again:" << endl;
cin.sync();
user.get_int(change);
}
switch (change)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
return change;
case 6:
return 8;
case 7:
return 10;
case 8:
return 15;
case 9:
return 16;
case 10:
return 17;
case 11:
return 18;
}
return 1;
}
int screen_jump::screen_18()
{
int change = 0;
cout << "****************************************" << endl;
cout << "What do you want to do?" << endl;
cout << "0) quit." << endl;
cout << "1) show all goods." << endl;
cout << "2) show the goods of somebody." << endl;
cout << "3) show the goods of the same kind." << endl;
cout << "4) sign up." << endl;
cout << "5) sign in." << endl;
cout << "6) show the information of consumer." << endl;
cout << "7) show the information of business(with goods)." << endl;
cout << "8) add the goods to your cart." << endl;
cout << "9) change your cart." << endl;
cout << "10) generate your order." << endl;
cout << "11) recharge." << endl;
cout << "12) pay or cancel your order." << endl;
//cout << "11) pay for your order." << endl;
cout
<< "****************************************" << endl;
cout << "Please input the order in the front:" << endl;
cin.sync(); //清除缓冲区的数据流
user.get_int(change);
while ((change != 0 && change != 1 && change != 2 && change != 3 && change != 4 && change != 5 && change != 6 && change != 7 && change != 8 && change != 9 && change != 10 && change != 11) || cin.fail())
{
if (cin.fail())
{
cin.clear();
cin.sync();
}
cout << "Please input the order again:" << endl;
cin.sync();
user.get_int(change);
}
switch (change)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
return change;
case 6:
return 6;
case 7:
return 7;
case 8:
return 15;
case 9:
return 16;
case 10:
return 17;
case 11:
return 8;
case 12:
return 18;
}
return 1;
} | [
"wangzhenhao137@163.com"
] | wangzhenhao137@163.com |
4c12c938b71e24c55c0ca8884a012fa9d8ca3166 | a93f5a41959faa793f4f22c439ad4c1ea92668b8 | /AntsBook/2_3_7/main03.cpp | 7d28f1fd7e099e0566a856969134e46d08b4c4e4 | [] | no_license | admiswalker/i-am-learning-coding | 08a473da773d0e2e67d44462c2d7dee83fa0adac | 9c0d152d313aae06affdf0823fd59a188705d8f8 | refs/heads/master | 2021-07-07T05:21:09.871137 | 2020-12-21T23:55:42 | 2020-12-21T23:55:42 | 218,574,075 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 590 | cpp | // ref of base: ants book page. 66
#include <bits/stdc++.h>
using namespace std;
void dps(const int n, const int m, const int mod){
vector<int> dp(m+1, 0);
dp[0] = 1;
for(int i=1; i<=m; ++i){
for(int j=0; j<=n; ++j){
if(j-i>=0){
dp[j] += dp[j-i];
dp[j] %= mod;
}else{
dp[j] = dp[i-1];
dp[j] %= mod;
}
}
}
printf("%d\n", dp[m]);
}
int main(){
int n=4;
int m=3;
int mod=10000;
dps(n, m, mod);
return 0;
}
/*
4
3
10000
*/
| [
"admiswalker@gmail.com"
] | admiswalker@gmail.com |
ac5357d253d193d658044d9db0bc6ee8b48cfaa4 | 61c49d20245da7c4af2bf745978997eafae76350 | /c-plus-plus-como-programar/cap-6-funcoes-recursao/funcao_argumento_void.cpp | 3e5df05ef9cff640455d59ceaced6acc6ba003db | [] | no_license | virginiasatyro/c-plus-plus | c71c59a1cb75ff36d116e72a70cd226cdebc68d8 | 69a57494fc2a82dc3285b93798f9ec8210d8057f | refs/heads/master | 2022-11-24T10:50:22.741089 | 2020-07-28T22:46:00 | 2020-07-28T22:46:00 | 147,515,932 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 662 | cpp | /***********************************************************************************
* File: funcao_argumento_void.cpp
* C++
* Author: Virgínia Sátyro
* License: Free - Open Source
* Created on 2020 April
*
* Funções que não aceitam argumentos.
***********************************************************************************/
#include <iostream>
using namespace std;
void function1(); // não aceita argumentos
void function2();
int main()
{
function1();
function2();
return 0;
}
void function1()
{
cout << "function1 takes no arguments" << endl;
}
void function2()
{
cout << "function2 takes no arguments" << endl;
} | [
"vivi_satyro@hotmail.com"
] | vivi_satyro@hotmail.com |
99dd3e134bcd8195c630cd63bfc6fcff87c543c2 | cfeac52f970e8901871bd02d9acb7de66b9fb6b4 | /generated/src/aws-cpp-sdk-networkmanager/source/model/DisassociateCustomerGatewayRequest.cpp | 4efe4b511fa98be672f358814b63b0f386e09290 | [
"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 | 628 | cpp | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/networkmanager/model/DisassociateCustomerGatewayRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::NetworkManager::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
DisassociateCustomerGatewayRequest::DisassociateCustomerGatewayRequest() :
m_globalNetworkIdHasBeenSet(false),
m_customerGatewayArnHasBeenSet(false)
{
}
Aws::String DisassociateCustomerGatewayRequest::SerializePayload() const
{
return {};
}
| [
"sdavtaker@users.noreply.github.com"
] | sdavtaker@users.noreply.github.com |
06267d7d1ca36e8e64fc0dd7c0b5efea8ee4c380 | 4bb00c27ab23f3410adbe990d1f26c5b57eebadc | /CPAR-Project1/MatrixMultiplicationCLI.cpp | 3ea329ff19bc72baabc1bed65a604035e8be033e | [] | no_license | carlosmccosta/Distributed-Prime-Sieve | 680d4d8e94643f5e26cb49aab4df53d08b24342c | dd6ac055f44c5d48732c5b75049fe62ee1f5ddd2 | refs/heads/master | 2016-09-05T17:11:48.374641 | 2014-11-26T14:16:39 | 2014-11-26T14:16:39 | 17,256,999 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,647 | cpp | #include "MatrixMultiplicationCLI.h"
MatrixMultiplicationCLI::MatrixMultiplicationCLI(void) {}
MatrixMultiplicationCLI::~MatrixMultiplicationCLI(void) {}
int main() {
ConsoleInput::getInstance()->clearConsoleScreen();
int option = 1;
bool roundLoaded = false;
do {
ConsoleInput::getInstance()->clearConsoleScreen();
cout << "############### Parallel computing - Project 1 - Carlos Costa #####################\n";
cout << " >>> Matrix multiplication <<< \n";
cout << "#######################################################################################\n\n\n";
cout << " 1 - Basic matrix multiplication\n";
cout << " 2 - Line matrix multiplication\n";
cout << " 3 - Block matrix multiplication\n\n";
cout << " 0 - Exit\n\n\n" << endl;
option = ConsoleInput::getInstance()->getIntCin(" >>> Option: ", " -> Insert one of the listed options!\n", 0, 4);
if (option == 0) {
break;
}
bool validOption = true;
bool loadFromFiles = false;
BidimensionalMatrix *leftMatrix, *rightMatrix;
MatrixMultiplication* matrixMultAlgorithm;
string leftMatrixFilename;
string rightMatrixFilename;
string resultFile = "";
unsigned int blockColumnSize = 1, blockLineSize = 1;
loadFromFiles = ConsoleInput::getInstance()->getYesNoCin("\n ## Load matrices from files? (Y/N): ");
if (loadFromFiles) {
cout << " # Left matrix file: ";
leftMatrixFilename = ConsoleInput::getInstance()->getLineCin();
leftMatrix = new BidimensionalMatrix();
if (!leftMatrix->initializeMatrixFromFile(leftMatrixFilename)) {
ConsoleInput::getInstance()->getUserInput();
continue;
}
cout << " # Right matrix file: ";
rightMatrixFilename = ConsoleInput::getInstance()->getLineCin();
rightMatrix = new BidimensionalMatrix();
if (!rightMatrix->initializeMatrixFromFile(rightMatrixFilename)) {
ConsoleInput::getInstance()->getUserInput();
continue;
}
bool loadResultFile = ConsoleInput::getInstance()->getYesNoCin("\n ## Load result file to compare? (Y/N): ");
if (loadResultFile) {
cout << " # Result matrix file: ";
resultFile = ConsoleInput::getInstance()->getLineCin();
}
} else {
cout << " > Using default initialization...\n\n";
unsigned int numberOfColumnsOfLeftMatrix = (unsigned int)ConsoleInput::getInstance()->getIntCin(" ## Number of columns of left matrix: ", " -> Insert a number > 1!\n", 2, INT_MAX);
unsigned int numberOfLinesOfLeftMatrix = (unsigned int)ConsoleInput::getInstance()->getIntCin(" ## Number of lines of left matrix: ", " -> Insert a number > 1!\n", 2, INT_MAX);
unsigned int numberOfColumnsOfRightMatrix = (unsigned int)ConsoleInput::getInstance()->getIntCin(" ## Number of columns of right matrix: ", " -> Insert a number > 1!\n", 2, INT_MAX);
leftMatrix = new BidimensionalMatrix(numberOfColumnsOfLeftMatrix, numberOfLinesOfLeftMatrix);
leftMatrix->initializeMatrix();
rightMatrix = new BidimensionalMatrix(numberOfColumnsOfRightMatrix, numberOfColumnsOfLeftMatrix);
rightMatrix->initializeMatrixWithSequenceOnLines();
}
switch (option) {
case 1: {
matrixMultAlgorithm = new MatrixMultiplicationBasic();
break;
}
case 2: {
matrixMultAlgorithm = new MatrixMultiplicationLine();
break;
}
case 3: {
blockColumnSize = (unsigned int)ConsoleInput::getInstance()->getIntCin(" ## Block column size: ", " -> Insert a number > 1!\n", 2, INT_MAX);
blockLineSize = (unsigned int)ConsoleInput::getInstance()->getIntCin(" ## Block line size: ", " -> Insert a number > 1!\n", 2, INT_MAX);
matrixMultAlgorithm = new MatrixMultiplicationBlock();
break;
}
default: {
validOption = false;
break;
}
}
if (validOption) {
cout << endl << "\n > Multiplying matrices...";
shared_ptr<BidimensionalMatrix> resultMatrix = matrixMultAlgorithm->performMultiplication(*leftMatrix, *rightMatrix, blockColumnSize, blockLineSize);
cout << "\n -> Multiplication finished in " << matrixMultAlgorithm->getPerformanceTimer().getElapsedTimeInSec() << " seconds\n" << endl;
bool validationResult;
if (loadFromFiles) {
cout << " > Validating result matrix with result file supplied...\n";
validationResult = resultMatrix->validateResultFromFile(resultFile);
} else {
cout << " > Validating result matrix from default initialization (result should be sum of powers)...\n";
validationResult = resultMatrix->validateResultOfDefaultMatrixInitialization(rightMatrix->getNumberLines());
}
if (validationResult) {
cout << " -> Result matrix validated!\n\n";
} else {
cout << " -> Result matrix incorrect!\n\n";
}
int exportType = ConsoleInput::getInstance()->getIntCin(" ## Export matrices? (1-Only result, 2-All, 0-None): ", " -> Insert the number of the option!\n", 0, 3);
if (exportType == 2) {
leftMatrix->exportMatrixToFile("leftMatrix.txt");
cout << " > Exporting left matrix to leftMatrix.txt...\n";
rightMatrix->exportMatrixToFile("rightMatrix.txt");
cout << " > Exporting right matrix to rightMatrix.txt...\n";
}
if (exportType == 1 || exportType == 2) {
cout << " > Exporting result matrix to resultMatrix.txt...\n";
resultMatrix->exportMatrixToFile("resultMatrix.txt");
}
cout << " -> Export finished!\n";
delete leftMatrix;
delete rightMatrix;
resultMatrix.reset();
delete matrixMultAlgorithm;
cout << endl << endl;
ConsoleInput::getInstance()->getUserInput();
}
} while (option != 0);
return 0;
}
| [
"carloscosta.cmcc@gmail.com"
] | carloscosta.cmcc@gmail.com |
1347f8d6ffe50fbb53937df29c2e8c2c428c4733 | 1af1f8f18ef5b8e2218133f20aac1bbd0060ec55 | /CSound Manager/CSound/CSoundComponent.h | 0ad0c67a44c5cb346aeefe1e716a51c2bc479935 | [] | no_license | ReDEnergy/3DSound-Prototypying | c589ba3a13b2a2bb7cd458faec0b4b1db1e969dc | 9e7c2daa09739460bd634f977d2f95f918ec338a | refs/heads/master | 2021-01-10T16:15:52.761219 | 2017-07-03T19:57:17 | 2017-07-03T19:57:17 | 49,384,240 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 791 | h | #pragma once
#include <vector>
#include <CSound/CSoundEntity.h>
#include <CSound/CSoundForward.h>
#include <CSound/CSoundComponentProperty.h>
#include <CSound/Templates/CSoundList.h>
class DLLExport CSoundComponent
: public CSoundEntity
, public CSoundList<CSoundComponentProperty, CSoundComponent>
{
public:
CSoundComponent();
CSoundComponent(const CSoundComponent &Comp);
~CSoundComponent();
void Update();
void InitControlChannels();
void AddControlChannel(const char* channel);
const std::vector<std::string>& GetControlChannels() const;
void SetParent(CSoundInstrument *instrument);
void SetParent(CSoundInstrumentBlock *instrument) {};
private:
CSoundInstrument *parent;
std::vector<std::string> controlChannels;
std::vector<std::string> controls;
};
| [
"gabriel.ivanica@gmail.com"
] | gabriel.ivanica@gmail.com |
4179c5a6a547b10dc36bd13fb2c3ece17ff8a315 | 82bba04be05e518845b99d749a3293668725e9e7 | /QHG3/common/PolyLine.h | 5cdaac7b1170fd4424fb64bb0653d1e25bc4ac17 | [] | no_license | Achandroth/QHG | e914618776f38ed765da3f9c64ec62b983fc3df3 | 7e64d82dc3b798a05f2a725da4286621d2ba9241 | refs/heads/master | 2023-06-04T06:24:41.078369 | 2018-07-04T11:01:08 | 2018-07-04T11:01:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 975 | h | /*============================================================================
| PolyLine
|
| representation of a piecewise linear function
|
| Author: Jody Weissmann
\===========================================================================*/
#ifndef __POLYLINE_H__
#define __POLYLINE_H__
#include <vector>
#include <stdio.h>
#include "zlib.h"
class PolyLine {
public:
PolyLine(unsigned int iNumSegments);
PolyLine(PolyLine *pPL);
~PolyLine();
void addPoint(unsigned int i, double fX, double fV) {
m_afX[i] = fX;
m_afV[i] = fV;
if (i > 0) {
m_afA[i-1] = (m_afV[i] - m_afV[i-1])/(m_afX[i] - m_afX[i-1]);
}
}
double getVal(double fX);
void write(FILE *fOut);
void display(const char *pIndent, const char *pCaption);
static PolyLine *readFromString(const char *pData);
unsigned int m_iNumSegments;
double *m_afX;
double *m_afV;
double *m_afA;
};
#endif
| [
"jody@aim.uzh.ch"
] | jody@aim.uzh.ch |
88acb98f2abdaf02ec07fc34165a6637d154f116 | 948a6bbb8ef60a97c4350bf1fbccbc972bbfcb4f | /thirdparty/Indy10/C18/Win32/Release/IdSASL_CRAMBase.hpp | c90708b74a4536c49d46173c6c250099116d99ee | [] | no_license | hotsoft/components | 504c6935b892c74796a8cbec91736185507ed149 | 2d41768ff68c0c6535a1ee40f3e8abc90cb19c9b | refs/heads/master | 2023-09-03T22:46:13.153273 | 2023-08-18T13:16:19 | 2023-08-18T13:16:19 | 14,142,719 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,466 | hpp | // CodeGear C++Builder
// Copyright (c) 1995, 2013 by Embarcadero Technologies, Inc.
// All rights reserved
// (DO NOT EDIT: machine generated header) 'IdSASL_CRAMBase.pas' rev: 25.00 (Windows)
#ifndef Idsasl_crambaseHPP
#define Idsasl_crambaseHPP
#pragma delphiheader begin
#pragma option push
#pragma option -w- // All warnings off
#pragma option -Vx // Zero-length empty class member
#pragma pack(push,8)
#include <System.hpp> // Pascal unit
#include <SysInit.hpp> // Pascal unit
#include <IdHMACSHA1.hpp> // Pascal unit
#include <IdSASL.hpp> // Pascal unit
#include <IdSASLUserPass.hpp> // Pascal unit
#include <IdBaseComponent.hpp> // Pascal unit
#include <System.Classes.hpp> // Pascal unit
//-- user supplied -----------------------------------------------------------
namespace Idsasl_crambase
{
//-- type declarations -------------------------------------------------------
class DELPHICLASS TIdSASLCRAMBase;
#pragma pack(push,4)
class PASCALIMPLEMENTATION TIdSASLCRAMBase : public Idsasluserpass::TIdSASLUserPass
{
typedef Idsasluserpass::TIdSASLUserPass inherited;
public:
__classmethod virtual System::UnicodeString __fastcall BuildKeydAuth(const System::UnicodeString APassword, const System::UnicodeString AChallenge);
virtual System::UnicodeString __fastcall StartAuthenticate(const System::UnicodeString AChallenge, const System::UnicodeString AHost, const System::UnicodeString AProtocolName);
virtual System::UnicodeString __fastcall ContinueAuthenticate(const System::UnicodeString ALastResponse, const System::UnicodeString AHost, const System::UnicodeString AProtocolName);
public:
/* TIdSASL.Destroy */ inline __fastcall virtual ~TIdSASLCRAMBase(void) { }
public:
/* TIdBaseComponent.Create */ inline __fastcall TIdSASLCRAMBase(System::Classes::TComponent* AOwner)/* overload */ : Idsasluserpass::TIdSASLUserPass(AOwner) { }
public:
/* TIdInitializerComponent.Create */ inline __fastcall TIdSASLCRAMBase(void)/* overload */ : Idsasluserpass::TIdSASLUserPass() { }
};
#pragma pack(pop)
//-- var, const, procedure ---------------------------------------------------
} /* namespace Idsasl_crambase */
#if !defined(DELPHIHEADER_NO_IMPLICIT_NAMESPACE_USE) && !defined(NO_USING_NAMESPACE_IDSASL_CRAMBASE)
using namespace Idsasl_crambase;
#endif
#pragma pack(pop)
#pragma option pop
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // Idsasl_crambaseHPP
| [
"desenv7@labplus.com.br"
] | desenv7@labplus.com.br |
8b318fecee9b8af41fd28f50b728bb9aa4733253 | 773357b475f59bbdde3a2de632638fef976e330a | /src/TopDownCameraController.h | c74ac1e19a181dede2df9f9f066c7fbe290501c0 | [
"MIT"
] | permissive | q4a/GLKeeper | 568544cc86a88536f104f7f38d6e018a62e47510 | a2207e2a459a254cbc703306ef92a09ecf714090 | refs/heads/master | 2022-11-25T08:32:44.100454 | 2020-06-26T11:36:25 | 2020-06-26T11:36:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,799 | h | #pragma once
#include "CameraController.h"
class TopDownCameraController: public CameraController
{
public:
TopDownCameraController();
// set 3rd person camera params
// @param yawDegrees, pitchDegrees: Yaw and pitch specified in degrees
// @param distance: Distance to focus point
void Set3rdPersonParams(float yawDegrees, float pitchDegrees, float distance);
// set camera focus position
// @param position: Position
void SetFocusPoint(const glm::vec3& position);
// stop moving or rotating
void StopCameraActivity();
// process frame logic
void HandleUpdateFrame(float deltaTime) override;
// process controller is attached to game scene
void HandleSceneAttach() override;
// process controller is detached from game scene
void HandleSceneDetach() override;
// process input event
// @param inputEvent: Event data
void HandleInputEvent(MouseButtonInputEvent& inputEvent) override;
void HandleInputEvent(MouseMovedInputEvent& inputEvent) override;
void HandleInputEvent(MouseScrollInputEvent& inputEvent) override;
void HandleInputEvent(KeyInputEvent& inputEvent) override;
void HandleInputEvent(KeyCharEvent& inputEvent) override;
void HandleScreenResolutionChanged();
private:
void SetupCameraView();
void SetupCameraProjection();
private:
// current viewer params
float mDegYaw;
float mDegPitch;
float mDistance;
float mFOVy;
glm::vec3 mFocusPoint;
// current activity flags
bool mIncreasingFov;
bool mDecreasingFov;
bool mIncreasingPitch;
bool mDecreasingPitch;
bool mZoomingIn;
bool mZoomingOut;
bool mMovingN;
bool mMovingE;
bool mMovingS;
bool mMovingW;
bool mMovingAltMode;
};
| [
"codename.cpp@gmail.com"
] | codename.cpp@gmail.com |
55b45ca44eec1e742434e575279ceafe49bec09b | e2d8baee41d39d078aa4c866f11e3f70b006407b | /XMLlib/SRC/XMLNameSpace.h | 1fdaa702004e1c5e33bb9448ae97f06052129218 | [] | no_license | b-swat/XML | 0a909827f39d7e8e4e28367b464392a6069ce5fa | 9e0d5f161cd0a55090e90cf41000683cb4c79bd4 | refs/heads/master | 2021-09-27T19:51:50.621381 | 2018-11-11T03:05:41 | 2018-11-11T03:05:41 | 143,589,133 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 439 | h | #pragma once
#include <vector>
#include "../stdafx.h"
#include "XMLNode.h"
#include "XMLString.h"
namespace XML
{
class XMLNameSpace
{
char m_quote;
XMLString m_name;
XMLString m_path;
public:
XMLNode *nodeOwner;
XMLNameSpace(XMLString &_name, XMLString &_path, char _quote);
~XMLNameSpace();
std::wstring toWString();
XMLString* getFullName();
XMLString* getPath();
std::wstring getName();
};
}
| [
"work@ELIS"
] | work@ELIS |
cd3644731dac7b60a6ff028e0f100a23c0adb291 | 740fdf1cca74bdb8f930a7907a48f9bdd9b5fbd3 | /content/shell/android/linker_test_apk/chromium_linker_test_android.cc | 6e8ef567e98c644416f235d22613e8c800c91688 | [
"BSD-3-Clause"
] | permissive | hefen1/chromium | a1384249e2bb7669df189235a1ff49ac11fc5790 | 52f0b6830e000ca7c5e9aa19488af85be792cc88 | refs/heads/master | 2016-09-05T18:20:24.971432 | 2015-03-23T14:53:29 | 2015-03-23T14:53:29 | 32,579,801 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,495 | cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/android/jni_android.h"
#include "base/android/jni_onload_delegate.h"
#include "content/public/app/content_jni_onload.h"
#include "content/public/app/content_main.h"
#include "content/public/browser/android/compositor.h"
#include "content/shell/android/linker_test_apk/chromium_linker_test_linker_tests.h"
#include "content/shell/android/shell_jni_registrar.h"
#include "content/shell/app/shell_main_delegate.h"
namespace {
class ChromiumLinkerTestJNIOnLoadDelegate :
public base::android::JNIOnLoadDelegate {
public:
bool RegisterJNI(JNIEnv* env) override {
// To be called only from the UI thread. If loading the library is done on
// a separate thread, this should be moved elsewhere.
if (!content::android::RegisterShellJni(env))
return false;
if (!content::RegisterLinkerTestsJni(env))
return false;
return true;
}
bool Init() override {
content::Compositor::Initialize();
content::SetContentMainDelegate(new content::ShellMainDelegate());
return true;
}
};
} // namespace
// This is called by the VM when the shared library is first loaded.
JNI_EXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) {
ChromiumLinkerTestJNIOnLoadDelegate delegate;
if (!content::android::OnJNIOnLoad(vm, &delegate))
return -1;
return JNI_VERSION_1_4;
}
| [
"hefen2007303257@gmail.com"
] | hefen2007303257@gmail.com |
20ba8558a6045e8c83e646c9c12c01dbaea8c24b | 081642f0c0486db9bede51f2e9308baf257ac097 | /PDFWriter3_6/PDFWriterTestPlayground/WindowsPath.cpp | 5598495389c6bd7fbef8d9ec789cfd55ab88b85c | [
"Apache-2.0"
] | permissive | Hopding/hummus-ios-build | 3f1d1f70f3832e58f52930d4e609b43192f7f4a3 | 28292bfdb2a8551bdcb87a4d1a009e16455d2e41 | refs/heads/master | 2021-01-16T19:08:45.999760 | 2018-02-25T16:43:07 | 2018-02-25T16:43:07 | 100,146,456 | 2 | 1 | null | 2018-02-25T16:43:08 | 2017-08-13T01:24:08 | C | UTF-8 | C++ | false | false | 4,419 | cpp | #include "WindowsPath.h"
#include <sstream>
WindowsPath::WindowsPath(void)
{
}
WindowsPath::WindowsPath(const string& inPath)
{
SetPathFromString(inPath);
}
WindowsPath::~WindowsPath(void)
{
}
void WindowsPath::SetPathFromString(const string& inPath)
{
// path is expected to be either <driveLetter>:\<folder1>\<folder2>....
// or <folder1>\<folder2>...
mPathComponents.clear();
mDriveLetter = "";
string::size_type searchPosition = 0;
if(inPath.size() > 1 && inPath.at(1) == ':')
{
mDriveLetter = inPath.substr(0,1);
searchPosition = 3; // may be eitehr c: or c:\...., which should be equivelent
}
string newComponent;
while(searchPosition < inPath.length())
{
string::size_type findResult = inPath.find("\\",searchPosition);
if(findResult == inPath.npos)
newComponent = inPath.substr(searchPosition,findResult);
else
newComponent = inPath.substr(searchPosition,findResult-searchPosition);
// with .. i'm doing some calculation already of sparing interim folders.
// as a result if there are still ..s they will be only at the beginning of the path
if(newComponent == ".." && mPathComponents.size() > 0 && mPathComponents.back() != "..")
PopPathComponent();
else if(newComponent != ".")
PushPathComponent(newComponent);
searchPosition = (findResult == inPath.npos) ? inPath.length() : findResult+1;
}
}
bool WindowsPath::IsAbsolute() const
{
return mDriveLetter.length() > 0;
}
WindowsPath WindowsPath::GetFolder() const
{
WindowsPath newPath;
// in edge case of drive letter only, will return the same path. in empty relative, will enter empty relative
// in all other cases will return a path which is the same drive letter, and with one less component from the component list
newPath.SetDriveLetter(mDriveLetter);
newPath.mPathComponents = mPathComponents;
newPath.PopPathComponent();
return newPath;
}
WindowsPath WindowsPath::InterpretFrom(const WindowsPath& inPath) const
{
if(IsAbsolute()) // for absolute paths retain as is
return *this;
// otherwise, construct a new path from the two paths, and return
WindowsPath newPath = inPath;
StringList::const_iterator it = mPathComponents.begin();
for(; it != mPathComponents.end();++it)
{
if(*it == "..")
newPath.PopPathComponent();
else
newPath.PushPathComponent(*it);
}
return newPath;
}
string WindowsPath::ToString() const
{
stringstream pathStream;
if(mDriveLetter != "")
pathStream<<mDriveLetter<<":\\";
if(mPathComponents.size() > 0)
{
StringList::const_iterator it = mPathComponents.begin();
pathStream<<*it;
++it;
for(; it != mPathComponents.end();++it)
pathStream<<"\\"<<*it;
}
return pathStream.str();
}
void WindowsPath::PushPathComponent(const string& inComponent)
{
mPathComponents.push_back(inComponent);
}
void WindowsPath::PopPathComponent()
{
if(mPathComponents.size() > 0)
mPathComponents.pop_back();
}
void WindowsPath::SetDriveLetter(const string& inDriveLetter)
{
mDriveLetter = inDriveLetter;
}
FileURL WindowsPath::ToFileURL() const
{
FileURL aFileURL;
if(IsAbsolute())
{
// a drive letter is written to path like this: file:// /c|
aFileURL.PushPathComponent(mDriveLetter + "|");
aFileURL.SetIsAbsolute(true);
}
StringList::const_iterator it = mPathComponents.begin();
for(; it != mPathComponents.end(); ++it)
aFileURL.PushPathComponent(*it);
return aFileURL;
}
void WindowsPath::FromFileURL(const FileURL& inFileURL)
{
SingleValueContainerIterator<const StringList> itComponents = inFileURL.GetComponentsIterator();
mPathComponents.clear();
mDriveLetter = "";
// move to first component (if empty...just return)
if(!itComponents.MoveNext())
return;
// check first component, if it's a drive letter
if(itComponents.GetItem().at(itComponents.GetItem().length() - 1) == '|')
mDriveLetter = itComponents.GetItem().substr(0,itComponents.GetItem().length() - 1);
else
mPathComponents.push_back(itComponents.GetItem());
while(itComponents.MoveNext())
mPathComponents.push_back(itComponents.GetItem());
}
| [
"andrew.dillon.j@gmail.com"
] | andrew.dillon.j@gmail.com |
2684fbb6d34fc189b3ebd26e490a26db85da0658 | 8cc6d6f590285ef00e0f30e0151c4d407847b651 | /build_test/windows-build/Sources/include/kha/Resource.h | 469d20cbde6723c63ce05f3a900bd23936d2c707 | [] | no_license | piboistudios/ArmoryDeformIssues | e087d5097af74f958fd89dd8dd17ca57627bf6d1 | 84e8b14c5098a4a4db310c5177c5dcd46f40212d | refs/heads/master | 2020-03-24T11:42:11.270376 | 2018-07-28T16:33:45 | 2018-07-28T16:33:45 | 142,692,926 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 582 | h | // Generated by Haxe 3.4.4 (git build master @ 99b08bb)
#ifndef INCLUDED_kha_Resource
#define INCLUDED_kha_Resource
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
HX_DECLARE_CLASS1(kha,Resource)
namespace kha{
class HXCPP_CLASS_ATTRIBUTES Resource_obj {
public:
typedef hx::Object super;
HX_DO_INTERFACE_RTTI;
void (hx::Object :: *_hx_unload)();
static inline void unload( ::Dynamic _hx_) {
(_hx_.mPtr->*( static_cast< ::kha::Resource_obj *>(_hx_.mPtr->_hx_getInterface(0xf962acd2)))->_hx_unload)();
}
};
} // end namespace kha
#endif /* INCLUDED_kha_Resource */
| [
"gabriel.speed.bullock@gmail.com"
] | gabriel.speed.bullock@gmail.com |
195dc15f0ac104f216e880dd22001d05a52e3d26 | b1cca159764e0cedd802239af2fc95543c7e761c | /ext/libgecode3/vendor/gecode-3.7.3/gecode/iter/values-map.hpp | e999bb671c8f30306a321e2b80ccdb32ce397b75 | [
"MIT",
"Apache-2.0"
] | permissive | chef/dep-selector-libgecode | b6b878a1ed4a6c9c6045297e2bfec534cf1a1e8e | 76d7245d981c8742dc539be18ec63ad3e9f4a16a | refs/heads/main | 2023-09-02T19:15:43.797125 | 2021-08-24T17:02:02 | 2021-08-24T17:02:02 | 18,507,156 | 8 | 18 | Apache-2.0 | 2023-08-22T21:15:31 | 2014-04-07T05:23:13 | Ruby | UTF-8 | C++ | false | false | 3,769 | hpp | /* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Christian Schulte <schulte@gecode.org>
*
* Copyright:
* Christian Schulte, 2008
*
* Last modified:
* $Date: 2010-07-29 01:35:33 +1000 (Thu, 29 Jul 2010) $ by $Author: schulte $
* $Revision: 11294 $
*
* This file is part of Gecode, the generic constraint
* development environment:
* http://www.gecode.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.
*
*/
namespace Gecode { namespace Iter { namespace Values {
/**
* \brief Value iterator for mapping values of a value iterator
*
* If \a strict is true, the values obtained by mapping must be
* strictly increasing (that is, no duplicates).
*
* \ingroup FuncIterValues
*/
template<class I, class M, bool strict=false>
class Map {
protected:
/// Input iterator
I i;
/// Mapping object
M m;
public:
/// \name Constructors and initialization
//@{
/// Default constructor
Map(void);
/// Initialize with values from \a i
Map(I& i);
/// Initialize with values from \a i and map \a m
Map(I& i, const M& m);
/// Initialize with values from \a i
void init(I& i);
/// Initialize with values from \a i and map \a m
void init(I& i, const M& m);
//@}
/// \name Iteration control
//@{
/// Test whether iterator is still at a value or done
bool operator ()(void) const;
/// Move iterator to next value (if possible)
void operator ++(void);
//@}
/// \name Value access
//@{
/// Return current value
int val(void) const;
//@}
};
template<class I, class M, bool strict>
forceinline
Map<I,M,strict>::Map(void) {}
template<class I, class M, bool strict>
forceinline
Map<I,M,strict>::Map(I& i0) : i(i0) {}
template<class I, class M, bool strict>
forceinline
Map<I,M,strict>::Map(I& i0, const M& m0) : i(i0), m(m0) {}
template<class I, class M, bool strict>
forceinline void
Map<I,M,strict>::init(I& i0) {
i=i0;
}
template<class I, class M, bool strict>
forceinline void
Map<I,M,strict>::init(I& i0, const M& m0) {
i=i0; m=m0;
}
template<class I, class M, bool strict>
forceinline void
Map<I,M,strict>::operator ++(void) {
if (strict) {
++i;
} else {
int n=m.val(i.val());
do {
++i;
} while (i() && (n == m.val(i.val())));
}
}
template<class I, class M, bool strict>
forceinline bool
Map<I,M,strict>::operator ()(void) const {
return i();
}
template<class I, class M, bool strict>
forceinline int
Map<I,M,strict>::val(void) const {
return m.val(i.val());
}
}}}
// STATISTICS: iter-any
| [
"dan@getchef.com"
] | dan@getchef.com |
89ba0fa00df3fdb92accdec1a870195cc8a5f302 | 5568848932432e0b913c8052ada26a56620525ac | /tensorflow/core/kernels/sparse_xent_op.h | cf28d4a07ef49e94c126847e334b940ec414c12e | [
"Apache-2.0"
] | permissive | agouwin/udacity_deep_learning_homework | 96eb49b99817bd050e4d011f2aad84e9eefb6e36 | bbfa69be8685a5070c4a97d50e94bd4b37c5ce44 | refs/heads/master | 2022-12-25T07:15:27.941679 | 2016-03-06T18:38:46 | 2016-03-06T18:38:46 | 52,696,105 | 0 | 0 | Apache-2.0 | 2022-12-14T18:17:08 | 2016-02-28T00:34:23 | C++ | UTF-8 | C++ | false | false | 7,702 | h | /* Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_KERNELS_XENT_OP_H_
#define TENSORFLOW_KERNELS_XENT_OP_H_
// Functor definition for SparseXentOp, must be compilable by nvcc.
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
namespace sparse_xent_helpers {
template <typename T>
typename TTypes<const T, 1>::Tensor32Bit To32BitConst(
typename TTypes<T>::Vec in) {
return To32Bit(typename TTypes<T>::ConstVec(in.data(), in.dimensions()));
}
template <typename T>
typename TTypes<const T, 2>::Tensor32Bit To32BitConst(
typename TTypes<T>::Matrix in) {
return To32Bit(typename TTypes<T>::ConstMatrix(in.data(), in.dimensions()));
}
} // namespace sparse_xent_helpers
namespace generator {
// Generator for calculation of the sparse Xent loss.
// This generator takes the logits, the sum of the exponentiated
// logits, and the label indices. For each minibatch entry, ignoring
// the batch index b, it calculates:
//
// loss[j] = (log(sum_exp_logits) - logits[j]) * 1{ j == label }
//
// for j = 0 .. num_classes. This value must be summed over all j for
// the final loss.
template <typename T>
class SparseXentLossGenerator {
public:
EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE SparseXentLossGenerator(
typename TTypes<const T, 2>::Tensor32Bit logits,
typename TTypes<const T, 1>::Tensor32Bit sum_exp_logits,
TTypes<const int64, 1>::Tensor32Bit labels)
: logits_(logits), sum_exp_logits_(sum_exp_logits), labels_(labels) {}
EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE T
operator()(const Eigen::array<int, 2>& coords) const {
int batch = coords[0];
int depth = coords[1];
return (labels_(batch) == depth)
? (std::log(sum_exp_logits_(batch)) - logits_(coords))
: T(0.0);
};
private:
typename TTypes<const T, 2>::Tensor32Bit logits_;
typename TTypes<const T, 1>::Tensor32Bit sum_exp_logits_;
TTypes<const int64, 1>::Tensor32Bit labels_;
};
// Generator for calculation of the sparse Xent gradient.
// This generator takes the logits, the sum of the exponentiated
// logits, and the label indices. For each minibatch entry, ignoring
// the batch index b, it calculates:
//
// exp(logits[j]) / sum_exp_logits - 1{ j == label }
//
// for j = 0 .. num_classes.
template <typename T>
class SparseXentGradGenerator {
public:
EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE SparseXentGradGenerator(
typename TTypes<const T, 2>::Tensor32Bit logits,
typename TTypes<const T, 1>::Tensor32Bit sum_exp_logits,
TTypes<const int64, 1>::Tensor32Bit labels)
: logits_(logits), sum_exp_logits_(sum_exp_logits), labels_(labels) {}
EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE T
operator()(const Eigen::array<int, 2>& coords) const {
int batch = coords[0];
int depth = coords[1];
T subtract = (depth == labels_(batch)) ? T(1.0) : T(0.0);
return std::exp(logits_(coords)) / sum_exp_logits_(batch) - subtract;
};
private:
typename TTypes<const T, 2>::Tensor32Bit logits_;
typename TTypes<const T, 1>::Tensor32Bit sum_exp_logits_;
TTypes<const int64, 1>::Tensor32Bit labels_;
};
} // namespace generator
namespace functor {
// Functor used by SparseXentOp to do the computations.
template <typename Device, typename T>
struct SparseXentFunctor {
// Computes Cross Entropy loss and backprop.
//
// logits: batch_size, num_classes.
// labels: num_classes.
// scratch: temporary tensor, dims: batch_size, 1
// loss: output tensor for the loss, dims: batch_size.
// backprop: output tensor for the backprop, dims: batch_size, num_classes.
void operator()(const Device& d, typename TTypes<T>::ConstMatrix logits,
typename TTypes<int64>::ConstVec labels,
typename TTypes<T>::Vec scratch, typename TTypes<T>::Vec loss,
typename TTypes<T>::Matrix backprop);
};
// Eigen code implementing SparseXentFunctor::operator().
// This code works for both CPU and GPU and is used by the functor
// specializations for both device types.
template <typename Device, typename T>
struct SparseXentEigenImpl {
static void Compute(const Device& d, typename TTypes<T>::ConstMatrix logits,
typename TTypes<int64>::ConstVec labels,
typename TTypes<T>::Vec scratch,
typename TTypes<T>::Vec loss,
typename TTypes<T>::Matrix backprop) {
// NOTE(touts): This duplicates some of the computations in softmax_op
// because we need the intermediate (logits -max(logits)) values to
// avoid a log(exp()) in the computation of the loss.
const int kBatchDim = 0;
const int kClassDim = 1;
const int batch_size = logits.dimension(kBatchDim);
const int num_classes = logits.dimension(kClassDim);
// These arrays are used to reduce along the class dimension, and broadcast
// the resulting value to all classes.
#if !defined(EIGEN_HAS_INDEX_LIST)
Eigen::array<int, 1> along_class;
along_class[0] = kClassDim;
Eigen::array<int, 1> batch_only;
batch_only[0] = batch_size;
Eigen::array<int, 2> batch_by_one;
batch_by_one[0] = batch_size;
batch_by_one[1] = 1;
Eigen::array<int, 2> one_by_class;
one_by_class[0] = 1;
one_by_class[1] = num_classes;
#else
Eigen::IndexList<Eigen::type2index<kClassDim> > along_class;
Eigen::IndexList<int, Eigen::type2index<1> > batch_by_one;
batch_by_one.set(0, batch_size);
Eigen::IndexList<int> batch_only;
batch_only.set(0, batch_size);
Eigen::IndexList<Eigen::type2index<1>, int> one_by_class;
one_by_class.set(1, num_classes);
#endif
// scratch = max_logits along classes.
To32Bit(scratch).device(d) = To32Bit(logits).maximum(along_class);
// backprop = logits - max_logits.
To32Bit(backprop).device(d) =
To32Bit(logits) -
To32Bit(scratch).reshape(batch_by_one).broadcast(one_by_class);
// scratch = sum(exp(logits - max_logits)) along classes.
To32Bit(scratch).device(d) = To32Bit(backprop).exp().sum(along_class);
// sum(-labels *
// ((logits - max_logits) - log(sum(exp(logits - max_logits)))))
// along classes
generator::SparseXentLossGenerator<T> sparse_xent_loss_gen(
sparse_xent_helpers::To32BitConst<T>(backprop),
sparse_xent_helpers::To32BitConst<T>(scratch), To32Bit(labels));
To32Bit(loss).device(d) =
To32Bit(backprop).generate(sparse_xent_loss_gen).sum(along_class);
// backprop: prob - labels, where
// prob = exp(logits - max_logits) / sum(exp(logits - max_logits))
generator::SparseXentGradGenerator<T> sparse_xent_grad_gen(
sparse_xent_helpers::To32BitConst<T>(backprop),
sparse_xent_helpers::To32BitConst<T>(scratch), To32Bit(labels));
To32Bit(backprop).device(d) =
To32Bit(backprop).generate(sparse_xent_grad_gen);
}
};
} // namespace functor
} // namespace tensorflow
#endif // TENSORFLOW_KERNELS_XENT_OP_H_
| [
"vrv@google.com"
] | vrv@google.com |
916fe8bb2128e9fe1d6b7da54d960d1d9ff938d8 | 416fd0f6e8537dc1a11025d11e0be40c3948d304 | /src-es/Menu.cpp | 2fcb6344e2774e1ac49afe90a54950f45e6347de | [] | no_license | fabiopichler/ZeldaOLB-SDL2 | a5a3b1db692286ad66bda2e569374abaabc7d4c2 | d30a0c1436163e8da7fcaac0eb953eed35fcf3f4 | refs/heads/master | 2022-10-30T20:39:48.533757 | 2020-06-12T20:41:06 | 2020-06-12T20:41:06 | 266,054,320 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 19,655 | cpp | /*
Zelda Oni Link Begins
Copyright (C) 2006-2008 Vincent Jouillat
Please send bugreports with examples or suggestions to www.zeldaroth.fr
*/
#include <sstream>
#include <iostream>
#include <string>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include "Menu.h"
#include "Texte.h"
#include "Joueur.h"
#include "Monde.h"
#include "Projectile.h"
#include "Jeu.h"
Menu::Menu(Jeu* jeu) : gpJeu(jeu), sens(0), val(0), anim(0) {
lastAnimTime = SDL_GetTicks();
imageCadre = IMG_Load("data/images/menu/bord.png");
imageCoeur = IMG_Load("data/images/menu/coeur.png");
imageObjets = IMG_Load("data/images/statut/objets.png");
imageInventaire = IMG_Load("data/images/statut/inventaire.png");
SDL_SetColorKey(imageCadre,SDL_TRUE,SDL_MapRGB(imageCadre->format,0,0,255));
SDL_SetColorKey(imageCoeur,SDL_TRUE,SDL_MapRGB(imageCoeur->format,0,0,255));
}
Menu::~Menu() {
SDL_FreeSurface(imageCadre);
SDL_FreeSurface(imageCoeur);
SDL_FreeSurface(imageObjets);
SDL_FreeSurface(imageInventaire);
}
void Menu::draw(SDL_Surface* gpScreen) {
if (!gpJeu->getStop()) gpJeu->setStop(true);
drawCadres(gpScreen);
drawCoeur(gpScreen);
drawCristaux(gpScreen);
drawStatut(gpScreen);
drawInventaire(gpScreen);
drawCurseur(gpScreen);
if(SDL_GetTicks() > lastAnimTime + 240) {
lastAnimTime = SDL_GetTicks();
anim++;
if (anim > 1) anim = 0;
}
if(sens==1 && val<200)val+=25;
if(sens==0 && val > 0) {
val-=25;
if (val<=0) gpJeu->setStop(false);
}
}
void Menu::drawCurseur(SDL_Surface* gpScreen) {
int dec = 200-val;
SDL_Rect src;
SDL_Rect dst;
Joueur* gpJoueur = gpJeu->getJoueur();
src.w=32; src.h=32; src.y=0;
//curseur
if (anim==1) {
if ((gpJoueur->getTypeAnim()<4 || gpJoueur->getTypeAnim()>20) && !gpJoueur->getOni())
src.x=48; else src.x=80;
dst.x=24+32*(gpJoueur->getObjet()%3)-dec;
dst.y=24+32*(gpJoueur->getObjet()/3);
if (dst.x > -15) {
if (dst.x < 0) {src.x -= dst.x; src.w+= dst.x; dst.x = 0;}
SDL_BlitSurface(imageCadre, &src, gpScreen, &dst);
if (src.w < 16) {src.x -= (16-src.w); dst.x-= (16-src.w); src.w = 16;}
}
}
}
void Menu::drawCadres(SDL_Surface* gpScreen) {
int dec = 200-val;
SDL_Rect src;
SDL_Rect dst;
src.w=16; src.h=16;
//cadre inventaire
src.x = 0; src.y = 0; dst.x = 16-dec; dst.y = 16;
if (dst.x > -15) {
if (dst.x < 0) {src.x -= dst.x; src.w+= dst.x; dst.x = 0;}
SDL_BlitSurface(imageCadre, &src, gpScreen, &dst);
if (src.w < 16) {src.x -= (16-src.w); dst.x-= (16-src.w); src.w = 16;}
}
src.x = 16;
for (int i = 0; i < 5; i++) {
dst.x += 16;
if (dst.x > -15) {
if (dst.x < 0) {src.x -= dst.x; src.w+= dst.x; dst.x = 0;}
SDL_BlitSurface(imageCadre, &src, gpScreen, &dst);
if (src.w < 16) {src.x -= (16-src.w); dst.x-= (16-src.w); src.w = 16;}
}
}
src.x = 32; dst.x+=16;
if (dst.x > -15) {
if (dst.x < 0) {src.x -= dst.x; src.w+= dst.x; dst.x = 0;}
SDL_BlitSurface(imageCadre, &src, gpScreen, &dst);
if (src.w < 16) {src.x -= (16-src.w); dst.x-= (16-src.w); src.w = 16;}
}
src.y=16;
for (int j = 0; j < 7; j++) {
src.x=0; dst.x=16-dec; dst.y+=16;
if (dst.x > -15) {
if (dst.x < 0) {src.x -= dst.x; src.w+= dst.x; dst.x = 0;}
SDL_BlitSurface(imageCadre, &src, gpScreen, &dst);
if (src.w < 16) {src.x -= (16-src.w); dst.x-= (16-src.w); src.w = 16;}
}
src.x=16;
for (int i = 0; i < 5; i++) {
dst.x+=16;
if (dst.x > -15) {
if (dst.x < 0) {src.x -= dst.x; src.w+= dst.x; dst.x = 0;}
SDL_BlitSurface(imageCadre, &src, gpScreen, &dst);
if (src.w < 16) {src.x -= (16-src.w); dst.x-= (16-src.w); src.w = 16;}
}
}
src.x=32; dst.x+=16;
if (dst.x > -15) {
if (dst.x < 0) {src.x -= dst.x; src.w+= dst.x; dst.x = 0;}
SDL_BlitSurface(imageCadre, &src, gpScreen, &dst);
if (src.w < 16) {src.x -= (16-src.w); dst.x-= (16-src.w); src.w = 16;}
}
}
src.y=32;
src.x=0; dst.x=16-dec; dst.y+=16;
if (dst.x > -15) {
if (dst.x < 0) {src.x -= dst.x; src.w+= dst.x; dst.x = 0;}
SDL_BlitSurface(imageCadre, &src, gpScreen, &dst);
if (src.w < 16) {src.x -= (16-src.w); dst.x-= (16-src.w); src.w = 16;}
}
src.x=16;
for (int i = 0; i < 5; i++) {
dst.x+=16;
if (dst.x > -15) {
if (dst.x < 0) {src.x -= dst.x; src.w+= dst.x; dst.x = 0;}
SDL_BlitSurface(imageCadre, &src, gpScreen, &dst);
if (src.w < 16) {src.x -= (16-src.w); dst.x-= (16-src.w); src.w = 16;}
}
}
src.x=32; dst.x+=16;
if (dst.x > -15) {
if (dst.x < 0) {src.x -= dst.x; src.w+= dst.x; dst.x = 0;}
SDL_BlitSurface(imageCadre, &src, gpScreen, &dst);
if (src.w < 16) {src.x -= (16-src.w); dst.x-= (16-src.w); src.w = 16;}
}
//cadre statut
src.x = 0; src.y = 0; dst.x = 144; dst.y = 16 - dec;
if (dst.y > -15) {
if (dst.y < 0) {src.y -= dst.y; src.h+= dst.y; dst.y = 0;}
SDL_BlitSurface(imageCadre, &src, gpScreen, &dst);
if (src.h < 16) {src.y -= (16-src.h); dst.y-= (16-src.h); src.h = 16;}
}
src.x = 16;
for (int i = 0; i < 8; i++) {
dst.x += 16;
if (dst.y > -15) {
if (dst.y < 0) {src.y -= dst.y; src.h+= dst.y; dst.y = 0;}
SDL_BlitSurface(imageCadre, &src, gpScreen, &dst);
if (src.h < 16) {src.y -= (16-src.h); dst.y-= (16-src.h); src.h = 16;}
}
}
src.x = 32; dst.x+=16;
if (dst.y > -15) {
if (dst.y < 0) {src.y -= dst.y; src.h+= dst.y; dst.y = 0;}
SDL_BlitSurface(imageCadre, &src, gpScreen, &dst);
if (src.h < 16) {src.y -= (16-src.h); dst.y-= (16-src.h); src.h = 16;}
}
src.y=16;
for (int j = 0; j < 7; j++) {
src.x=0; dst.x=144; dst.y+=16;
if (dst.y > -15) {
if (dst.y < 0) {src.y -= dst.y; src.h+= dst.y; dst.y = 0;}
SDL_BlitSurface(imageCadre, &src, gpScreen, &dst);
if (src.h < 16) {src.y -= (16-src.h); dst.y-= (16-src.h); src.h = 16;}
}
src.x=16;
for (int i = 0; i < 8; i++) {
dst.x+=16;
if (dst.y > -15) {
if (dst.y < 0) {src.y -= dst.y; src.h+= dst.y; dst.y = 0;}
SDL_BlitSurface(imageCadre, &src, gpScreen, &dst);
if (src.h < 16) {src.y -= (16-src.h); dst.y-= (16-src.h); src.h = 16;}
}
}
src.x=32; dst.x+=16;
if (dst.y > -15) {
if (dst.y < 0) {src.y -= dst.y; src.h+= dst.y; dst.y = 0;}
SDL_BlitSurface(imageCadre, &src, gpScreen, &dst);
if (src.h < 16) {src.y -= (16-src.h); dst.y-= (16-src.h); src.h = 16;}
}
}
src.y=32; src.x=0; dst.x=144; dst.y+=16;
if (dst.y > -15) {
if (dst.y < 0) {src.y -= dst.y; src.h+= dst.y; dst.y = 0;}
SDL_BlitSurface(imageCadre, &src, gpScreen, &dst);
if (src.h < 16) {src.y -= (16-src.h); dst.y-= (16-src.h); src.h = 16;}
}
src.x=16;
for (int i = 0; i < 8; i++) {
dst.x+=16;
if (dst.y > -15) {
if (dst.y < 0) {src.y -= dst.y; src.h+= dst.y; dst.y = 0;}
SDL_BlitSurface(imageCadre, &src, gpScreen, &dst);
if (src.h < 16) {src.y -= (16-src.h); dst.y-= (16-src.h); src.h = 16;}
}
}
src.x=32; dst.x+=16;
if (dst.y > -15) {
if (dst.y < 0) {src.y -= dst.y; src.h+= dst.y; dst.y = 0;}
SDL_BlitSurface(imageCadre, &src, gpScreen, &dst);
if (src.h < 16) {src.y -= (16-src.h); dst.y-= (16-src.h); src.h = 16;}
}
//cadre cristaux
src.x = 0; src.y = 0; dst.x = 80; dst.y = 176+dec;
SDL_BlitSurface(imageCadre, &src, gpScreen, &dst);
src.x = 16;
for (int i = 0; i < 8; i++) {
dst.x += 16;
SDL_BlitSurface(imageCadre, &src, gpScreen, &dst);
}
src.x = 32; dst.x+=16;
SDL_BlitSurface(imageCadre, &src, gpScreen, &dst);
src.y=16; src.x=0; dst.x=80; dst.y+=16;
SDL_BlitSurface(imageCadre, &src, gpScreen, &dst);
src.x=16;
for (int i = 0; i < 8; i++) {
dst.x+=16;
SDL_BlitSurface(imageCadre, &src, gpScreen, &dst);
}
src.x=32; dst.x+=16;
SDL_BlitSurface(imageCadre, &src, gpScreen, &dst);
src.y=32; src.x=0; dst.x=80; dst.y+=16;
SDL_BlitSurface(imageCadre, &src, gpScreen, &dst);
src.x=16;
for (int i = 0; i < 8; i++) {
dst.x+=16;
SDL_BlitSurface(imageCadre, &src, gpScreen, &dst);
}
src.x=32; dst.x+=16;
SDL_BlitSurface(imageCadre, &src, gpScreen, &dst);
//cadre link
src.w=48; src.h=48;
src.x = 0; src.y = 0; dst.x = 16; dst.y = 176+dec;
SDL_BlitSurface(imageCadre, &src, gpScreen, &dst);
gpJeu->getJoueur()->draw2(32,186+dec,gpScreen);
//cadre coeur
src.w=48; src.h=48;
src.x = 0; src.y = 0; dst.x = 256+dec; dst.y = 176;
SDL_BlitSurface(imageCadre, &src, gpScreen, &dst);
}
void Menu::drawInventaire(SDL_Surface* gpScreen) {
int dec = 200-val;
Joueur* gpJoueur = gpJeu->getJoueur();
gpJeu->affiche(gpScreen, "X", 20-dec,20);
SDL_Rect src;
SDL_Rect dst;
src.w=16; src.h=17;
//arc
if (gpJoueur->hasObjet(O_ARC)) {
src.x=0; dst.x=32-dec; dst.y=32;
if (gpJoueur->hasObjet(O_ARC)==5)src.y=0; else {src.x=16; src.y=102;}
if (dst.x > -15) {
if (dst.x < 0) {src.x -= dst.x; src.w+= dst.x; dst.x = 0;}
SDL_BlitSurface(imageInventaire, &src, gpScreen, &dst);
if (src.w < 16) {src.x -= (16-src.w); dst.x-= (16-src.w); src.w = 16;}
}
}
//grappin
if (gpJoueur->hasObjet(O_GRAPPIN)) {
src.x=16; src.y=0; dst.x=64-dec; dst.y=32;
if (dst.x > -15) {
if (dst.x < 0) {src.x -= dst.x; src.w+= dst.x; dst.x = 0;}
SDL_BlitSurface(imageInventaire, &src, gpScreen, &dst);
if (src.w < 16) {src.x -= (16-src.w); dst.x-= (16-src.w); src.w = 16;}
}
}
//bombes
if (gpJoueur->hasObjet(O_SAC_BOMBES) && gpJoueur->getBombe()>0) {
src.x=32; src.y=0; dst.x=96-dec; dst.y=32;
if (dst.x > -15) {
if (dst.x < 0) {src.x -= dst.x; src.w+= dst.x; dst.x = 0;}
SDL_BlitSurface(imageInventaire, &src, gpScreen, &dst);
if (src.w < 16) {src.x -= (16-src.w); dst.x-= (16-src.w); src.w = 16;}
}
}
//baguette de feu
if (gpJoueur->hasObjet(O_BFEU)) {
src.x=0; src.y=17; dst.x=32-dec; dst.y=64;
if (dst.x > -15) {
if (dst.x < 0) {src.x -= dst.x; src.w+= dst.x; dst.x = 0;}
SDL_BlitSurface(imageInventaire, &src, gpScreen, &dst);
if (src.w < 16) {src.x -= (16-src.w); dst.x-= (16-src.w); src.w = 16;}
}
}
//baguette de glace
if (gpJoueur->hasObjet(O_BGLACE)) {
src.x=16; src.y=17; dst.x=64-dec; dst.y=64;
if (dst.x > -15) {
if (dst.x < 0) {src.x -= dst.x; src.w+= dst.x; dst.x = 0;}
SDL_BlitSurface(imageInventaire, &src, gpScreen, &dst);
if (src.w < 16) {src.x -= (16-src.w); dst.x-= (16-src.w); src.w = 16;}
}
}
//lanterne
if (gpJoueur->hasObjet(O_LANTERNE)) {
src.x=32; src.y=17; dst.x=96-dec; dst.y=64;
if (dst.x > -15) {
if (dst.x < 0) {src.x -= dst.x; src.w+= dst.x; dst.x = 0;}
SDL_BlitSurface(imageInventaire, &src, gpScreen, &dst);
if (src.w < 16) {src.x -= (16-src.w); dst.x-= (16-src.w); src.w = 16;}
}
}
//marteau
if (gpJoueur->hasObjet(O_MARTEAU)) {
src.x=0; src.y=34; dst.x=32-dec; dst.y=96;
if (dst.x > -15) {
if (dst.x < 0) {src.x -= dst.x; src.w+= dst.x; dst.x = 0;}
SDL_BlitSurface(imageInventaire, &src, gpScreen, &dst);
if (src.w < 16) {src.x -= (16-src.w); dst.x-= (16-src.w); src.w = 16;}
}
}
//flute
if (gpJoueur->hasObjet(O_OCARINA)) {
src.x=0; src.y=85; dst.x=64-dec; dst.y=96;
if (dst.x > -15) {
if (dst.x < 0) {src.x -= dst.x; src.w+= dst.x; dst.x = 0;}
SDL_BlitSurface(imageInventaire, &src, gpScreen, &dst);
if (src.w < 16) {src.x -= (16-src.w); dst.x-= (16-src.w); src.w = 16;}
}
}
//masque
if (gpJoueur->hasObjet(O_MASQUE)) {
src.x=0; src.y=102; dst.x=96-dec; dst.y=96;
if (gpJoueur->hasObjet(O_MASQUE)==2) {src.x=16;src.y=85;}
if (dst.x > -15) {
if (dst.x < 0) {src.x -= dst.x; src.w+= dst.x; dst.x = 0;}
SDL_BlitSurface(imageInventaire, &src, gpScreen, &dst);
if (src.w < 16) {src.x -= (16-src.w); dst.x-= (16-src.w); src.w = 16;}
}
}
//bouteilles
for (int i = 0; i < 3; i++) {
if (gpJoueur->hasBouteille(i)) {
dst.x=32*(i+1)-dec; dst.y=128;
switch (gpJoueur->hasBouteille(i)) {
case 1 : src.x=0; src.y=68; break;
case 2 : src.x=0; src.y=51; break;
case 3 : src.x=16; src.y=51; break;
case 4 : src.x=32; src.y=51; break;
}
if (dst.x > -15) {
if (dst.x < 0) {src.x -= dst.x; src.w+= dst.x; dst.x = 0;}
SDL_BlitSurface(imageInventaire, &src, gpScreen, &dst);
if (src.w < 16) {src.x -= (16-src.w); dst.x-= (16-src.w); src.w = 16;}
}
}
}
}
void Menu::drawStatut(SDL_Surface* gpScreen) {
int dec = 200-val;
std::ostringstream oss;
Joueur* gpJoueur = gpJeu->getJoueur();
int i = 36;
if (!gpJoueur->hasObjet(O_LANTERNE) || !gpJoueur->getOnilink()) i+=8;
gpJeu->affiche(gpScreen, "ESTATUTO :", 148,20-dec);
int v = gpJoueur->getVie();
int vm = gpJoueur->getVieMax();
if (v < 10) oss<<"0"; oss << v << "/";
if (vm < 10) oss<<"0"; oss << vm;
gpJeu->affiche(gpScreen, "VIDA : " + oss.str(), 148,i-dec);
i+=16;
if (gpJoueur->hasObjet(O_LANTERNE)) {
oss.str("");
int m = gpJoueur->getMagie();
int mm = gpJoueur->getMagieMax();
if (m < 10) oss<<"0"; oss << m << "/";
if (mm < 10) oss<<"0"; oss << mm;
gpJeu->affiche(gpScreen, "MAGIA : " + oss.str(), 148,i-dec);
i+=16;
}
if (gpJoueur->getOnilink()) {
oss.str("");
int o = gpJoueur->getOnijauge();
int oo = gpJoueur->getOnimax();
if (o < 10) oss<<"0"; oss << o << "/";
if (oo < 10) oss<<"0"; oss << oo;
gpJeu->affiche(gpScreen, "ONI LINK : " + oss.str(), 148,i-dec);
i+=16;
}
oss.str("");
oss << gpJoueur->getForce();
gpJeu->affiche(gpScreen, "FUERZA : " + oss.str(), 148,i-dec);
i+=16;
oss.str("");
oss << gpJoueur->getDefense();
gpJeu->affiche(gpScreen, "DEFENSA : " + oss.str(), 148,i-dec);
i+=16;
oss.str("");
int h = gpJoueur->getTemps(2);
int m = gpJoueur->getTemps(1);
int s = gpJoueur->getTemps(0);
if (h < 10) oss<<"0"; oss << h << ":";
if (m < 10) oss<<"0"; oss << m << ":";
if (s < 10) oss<<"0"; oss << s;
gpJeu->affiche(gpScreen, "TIEMPO : " + oss.str(), 148,i-dec);
SDL_Rect src;
SDL_Rect dst;
src.y=0; src.w=16; src.h=16; dst.y=136-dec;
//épée
if (gpJoueur->getEpee()) {
src.x = 16 * (gpJoueur->getEpee()-1); dst.x=156;
if (gpJoueur->getOni()) {
if (gpJoueur->hasObjet(O_MASQUE)==2) src.x=162;
else src.x=112;
}
if (dst.y > -15) {
if (dst.y < 0) {src.y -= dst.y; src.h+= dst.y; dst.y = 0;}
SDL_BlitSurface(imageObjets, &src, gpScreen, &dst);
if (src.h < 16) {src.y -= (16-src.h); dst.y-= (16-src.h); src.h = 16;}
}
}
//bouclier
if (gpJoueur->getBouclier()) {
src.x = 16 * (gpJoueur->getBouclier()-1); src.y=16; dst.x=176;
if (gpJoueur->getOni()) {
if (gpJoueur->hasObjet(O_MASQUE)==2) src.x=162;
else {src.x=96; src.y=0;}
}
if (dst.y > -15) {
if (dst.y < 0) {src.y -= dst.y; src.h+= dst.y; dst.y = 0;}
SDL_BlitSurface(imageObjets, &src, gpScreen, &dst);
if (src.h < 16) {src.y -= (16-src.h); dst.y-= (16-src.h); src.h = 16;}
}
}
//tunique
if (gpJoueur->getTunique()) {
src.x = 48 + 16 * (gpJoueur->getTunique()-1); src.y=16; dst.x=196;
if (gpJoueur->getOni()) src.x=96;
if (dst.y > -15) {
if (dst.y < 0) {src.y -= dst.y; src.h+= dst.y; dst.y = 0;}
SDL_BlitSurface(imageObjets, &src, gpScreen, &dst);
if (src.h < 16) {src.y -= (16-src.h); dst.y-= (16-src.h); src.h = 16;}
}
}
//bottes
if (gpJoueur->hasObjet(O_BOTTES)) {
src.x = 80; src.y=0; dst.x=216;
if (dst.y > -15) {
if (dst.y < 0) {src.y -= dst.y; src.h+= dst.y; dst.y = 0;}
SDL_BlitSurface(imageObjets, &src, gpScreen, &dst);
if (src.h < 16) {src.y -= (16-src.h); dst.y-= (16-src.h); src.h = 16;}
}
}
//gants
if (gpJoueur->hasObjet(O_GANTS)) {
src.x=32; dst.x=236;
if (gpJoueur->hasObjet(O_GANTS)==2)src.y=34; else src.y=85;
if (dst.y > -15) {
if (dst.y < 0) {src.y -= dst.y; src.h+= dst.y; dst.y = 0;}
SDL_BlitSurface(imageInventaire, &src, gpScreen, &dst);
if (src.h < 16) {src.y -= (16-src.h); dst.y-= (16-src.h); src.h = 16;}
}
}
//palmes
if (gpJoueur->hasObjet(O_PALMES)) {
src.x=16; src.y=34; dst.x=256;
if (dst.y > -15) {
if (dst.y < 0) {src.y -= dst.y; src.h+= dst.y; dst.y = 0;}
SDL_BlitSurface(imageInventaire, &src, gpScreen, &dst);
if (src.h < 16) {src.y -= (16-src.h); dst.y-= (16-src.h); src.h = 16;}
}
}
//sac de bombes
if (gpJoueur->hasObjet(O_SAC_BOMBES)) {
src.x = 112; src.y = 16; dst.x=276;
if (dst.y > -15) {
if (dst.y < 0) {src.y -= dst.y; src.h+= dst.y; dst.y = 0;}
SDL_BlitSurface(imageObjets, &src, gpScreen, &dst);
if (src.h < 16) {src.y -= (16-src.h); dst.y-= (16-src.h); src.h = 16;}
}
}
}
void Menu::drawCristaux(SDL_Surface* gpScreen) {
int dec = 200-val;
gpJeu->affiche(gpScreen, "GRAAL :", 84,180+dec);
SDL_Rect src;
SDL_Rect dst;
src.w=16; src.h=16; src.y=68;
dst.x=94; dst.y=198+dec;
for (int i = 0; i < 5; i++) {
if (gpJeu->getJoueur()->hasCristal(i)) src.x=16;
else src.x=32;
SDL_BlitSurface(imageInventaire, &src, gpScreen, &dst);
dst.x+=32-3;
}
}
void Menu::drawCoeur(SDL_Surface* gpScreen) {
int dec = 200-val;
SDL_Rect src;
SDL_Rect dst;
src.w=16; src.h=16; src.y=0; src.x = 16*(gpJeu->getJoueur()->nbQuarts()%4);
dst.x = 272+dec; dst.y = 192;
SDL_BlitSurface(imageCoeur, &src, gpScreen, &dst);
}
void Menu::menuIn() {
sens = 1; val = 0;
gpJeu->getAudio()->playSound(1);
}
void Menu::menuOut() {
sens = 0;
gpJeu->getAudio()->playSound(2);
}
int Menu::getVal() { return val;}
| [
"fabiopichler1992@gmail.com"
] | fabiopichler1992@gmail.com |
6754b285c9b4e8616961a99b8046e28ee3554c92 | 3c09d1c279c8578791dae535852c06e09efad4a1 | /Projects/Safet Sunay/Bingo 12.10.2014/Bingo/src/BingoEfect.cpp | 884f11cc619fe717fcc5a8aa63753ea4ef633471 | [] | no_license | rosen90/GitHub | f00653f8a65cdffc479b70d2d7ca8f9e103d3eeb | 851d210f2f6073d818e0984fa9daab96e833b066 | refs/heads/master | 2016-09-12T23:57:19.530896 | 2016-05-04T22:09:03 | 2016-05-04T22:09:03 | 58,085,509 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 3,710 | cpp | /*
* BingoEfect.cpp
*
* Created on: 9.10.2014 ã.
* Author: sony
*/
#include "BingoEfect.h"
SDL_Renderer* BingoEfect::renderer;
int BingoEfect::cutColor;
BingoEfect::BingoEfect()
{
renderer = NULL;
efectTexture = NULL;
degrees = 0;
process = 0;
cuttingColor.reverse = 0;
cutColor = 0;
cuttingColor.g = 0;
cuttingColor.b = 0;
cuttingColor.reverse = 0;
}
void BingoEfect::loadBingoEfects(string path)
{
SDL_Surface* tempSurface = IMG_Load(path.c_str());
if(tempSurface == NULL)
{
printf("Temporary button surface failed to load.");
}
else
{
//Color key image
SDL_SetColorKey( tempSurface, SDL_TRUE, SDL_MapRGB( tempSurface->format, 0xFF, 0x00, 0x00 ) );
efectTexture = SDL_CreateTextureFromSurface(renderer, tempSurface);
if(efectTexture == NULL)
{
printf("Button texture failed to load.");
}
else
{
m_Rect.w = 75;
// tempSurface->w-25;
m_Rect.h =75;
// tempSurface->h-25;
}
SDL_FreeSurface( tempSurface );
}
}
void BingoEfect::fillEfects(string efectPath, int x, int y, vector<BingoEfect>& efectContainer, BingoEfect temp)
{
temp.loadBingoEfects(efectPath.c_str());
temp.setEfectRect(x, y);
efectContainer.push_back(temp);
}
void BingoEfect::fillEfectsInVector(vector<BingoEfect>& efectContainer, BingoEfect obj)
{
fillEfects("LaFinEffect/1.png", 335, 0,efectContainer, obj);
fillEfects("LaFinEffect/2.png", 410, 24,efectContainer, obj);
fillEfects("LaFinEffect/3.png", 485, 0,efectContainer, obj);
fillEfects("LaFinEffect/4.png", 560, 24,efectContainer, obj);
fillEfects("LaFinEffect/5.png", 635, 0,efectContainer, obj);
}
void BingoEfect::makeEffect(int x, int degrees)
{
colorEffect(0);
m_Rect.x = x;
SDL_RenderCopyEx(renderer, efectTexture,NULL, &m_Rect, degrees, NULL, SDL_FLIP_NONE );
}
void BingoEfect::setEfectRect(int x, int y)
{
m_Rect.x = x;
m_Rect.y = y;
}
void BingoEfect::setEfectRectWH(int w, int h)
{
m_Rect.w = w;
m_Rect.h = h;
}
void BingoEfect::setRenderer(SDL_Renderer* rend)
{
renderer = rend;
}
void BingoEfect::moveLaFinEffect(int x, int direction)
{
switch(process)
{
case 0:
if(shrink())
{
process++;
}
break;
case 1:
if(moveDown())
{
process++;
}
break;
case 2:
if (chooseDirection(x, direction))
{
process++;
}
break;
case 3:
if (moveWhileSpining(direction))
{
process++;
}
break;
case 4:
colorEffect(10);
break;
default: break;
}
SDL_RenderCopyEx(renderer, efectTexture,NULL, &m_Rect, degrees, NULL, SDL_FLIP_NONE );
}
bool BingoEfect::shrink()
{
m_Rect.w --;
m_Rect.h --;
return m_Rect.w == 40;
}
bool BingoEfect::moveDown()
{
m_Rect.y +=2;
return m_Rect.y == 100;
}
bool BingoEfect::chooseDirection(int x, int direction)
{
m_Rect.x = m_Rect.x + (2*direction);
degrees = degrees + (11*direction);
return m_Rect.x == x;
}
bool BingoEfect::moveWhileSpining(int direction)
{
degrees = degrees + (4 * direction);
if (degrees >= 360 || degrees <= -360)
{
degrees = 0;
}
return degrees == 0;
}
void BingoEfect::setColor( Uint8 red, Uint8 green, Uint8 blue )
{
//Modulate texture
SDL_SetTextureColorMod( efectTexture, red, green, blue );
}
void BingoEfect::colorEffect(int speed)
{
if (cuttingColor.reverse == 0)
{
if (cutColor >= 120)
{
cuttingColor.reverse = 1;
}
cutColor += speed;
}
else
{
if (cutColor <= 5)
{
cuttingColor.reverse = 0;
}
cutColor -= speed;
}
setColor(100 + cutColor, 100 + cutColor, 100 + cutColor);
}
void BingoEfect::returnDefaultValuesEffect(int y)
{
m_Rect.w = 75;
m_Rect.h = 75;
m_Rect.y = y;
process = 0;
}
BingoEfect::~BingoEfect()
{
// TODO Auto-generated destructor stub
}
| [
"karadinev@gmail.com"
] | karadinev@gmail.com |
943f8e268e15c88c2b00eac0c9a41ee547ebae28 | 8934affdf9942be1ad55c40833e32d630b0712a7 | /LumenEngine-core/Material.cpp | 7f285d1bb37c982fc9a340c576b944044e4c5a3b | [] | no_license | wyattjhammond/LumenEngine | 0a665dee203f5138069ae2a7d04ded8117652b9e | 62572114fad82c2364e6e90d5b0881577dc39b41 | refs/heads/master | 2021-06-17T22:50:48.663676 | 2017-06-27T14:24:09 | 2017-06-27T14:24:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 795 | cpp | #include "Material.h"
Material::Material(unsigned numOfShaders, const char ** shaders)
{
m_numOfShaders = numOfShaders;
m_shaderPaths = new char*[numOfShaders];
for (unsigned i = 0; i < numOfShaders; ++i) {
unsigned len = strlen(shaders[i]) + 1;
m_shaderPaths[i] = new char[len];
strcpy_s(m_shaderPaths[i], len, shaders[i]);
}
}
Material::Material(unsigned numOfShaders, std::string * shaders)
{
m_numOfShaders = numOfShaders;
m_shaderPaths = new char*[numOfShaders];
for (unsigned i = 0; i < numOfShaders; ++i) {
unsigned len = shaders[i].length() + 1;
m_shaderPaths[i] = new char[len];
strcpy_s(m_shaderPaths[i], len, shaders[i].c_str());
}
}
Material::~Material()
{
for (unsigned i = 0; i < m_numOfShaders; ++i)
delete[] m_shaderPaths[i];
delete[] m_shaderPaths;
}
| [
"stonegrump@gmail.com"
] | stonegrump@gmail.com |
e5c8712331ab126b4c9289f312160ff10b1c6cce | 44227276cdce0d15ee0cdd19a9f38a37b9da33d7 | /arcane/src/arcane/core/ISharedReference.h | af1a8398fc8fcbc5f89a3bcf4661a3a1e2816bee | [
"Apache-2.0",
"LGPL-2.1-or-later"
] | permissive | arcaneframework/framework | 7d0050f0bbceb8cc43c60168ba74fff0d605e9a3 | 813cfb5eda537ce2073f32b1a9de6b08529c5ab6 | refs/heads/main | 2023-08-19T05:44:47.722046 | 2023-08-11T16:22:12 | 2023-08-11T16:22:12 | 357,932,008 | 31 | 21 | Apache-2.0 | 2023-09-14T16:42:12 | 2021-04-14T14:21:07 | C++ | UTF-8 | C++ | false | false | 2,802 | h | // -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*-
//-----------------------------------------------------------------------------
// Copyright 2000-2022 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com)
// See the top-level COPYRIGHT file for details.
// SPDX-License-Identifier: Apache-2.0
//-----------------------------------------------------------------------------
/*---------------------------------------------------------------------------*/
/* ISharedReference.h (C) 2000-2006 */
/* */
/* Interface de la classe compteur de référence. */
/*---------------------------------------------------------------------------*/
#ifndef ARCANE_ISHAREDREFERENCE_H
#define ARCANE_ISHAREDREFERENCE_H
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
#include "arcane/utils/Ptr.h"
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ARCANE_BEGIN_NAMESPACE
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/*!
* \ingroup Core
* \brief Interface d'un compteur de référence.
*
Le compteur de référence permet à une instance classe de connaître le nombre
de références sur elle. Lorsque ce nombre arrive à zéro, cela signifie
que l'instance n'est plus utilisée. Ce système est utilisé principalement
pour libérer automatiquement la mémoire lorsque le nombre de références
tombe à zéro.
Cette classe s'utilise par l'intermédiaire de classes comme AutoRefT qui
permettent d'incrémenter ou de décrémenter automatiquement le compteur
de l'objet sur lesquelles elles pointent.
\since 0.2.9
\author Gilles Grospellier
\date 06/10/2000
*/
class ARCANE_CORE_EXPORT ISharedReference
{
public:
//! Libère les ressources
virtual ~ISharedReference(){}
public:
//! Incrémente le compteur de référence
virtual void addRef() =0;
//! Décrémente le compteur de référence
virtual void removeRef() =0;
//! Retourne la valeur du compteur de référence
virtual Int32 refCount() const =0;
};
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ARCANE_END_NAMESPACE
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
#endif
| [
"Gilles.Grospellier@cea.fr"
] | Gilles.Grospellier@cea.fr |
a7b19ca098742591ab146cc560787106cdb43e2b | 841322eddd57db0b12f6abd685dd399f28be0c68 | /qt_creator_basic/4/build-4_3_myBuddy-Desktop_Qt_5_10_1_MinGW_32bit-Debug/debug/moc_mywidget.cpp | 22b8099f0f4a9b3e3196daed93939698f8c0d474 | [] | no_license | cat1984x/Learning_Qt | c52e030850d254b4a5541968d86c56b5cdf504f7 | 4deaa4e86112c263f5421d2f91b0ba1ca14e482a | refs/heads/master | 2022-01-08T10:24:08.201942 | 2018-05-02T07:19:03 | 2018-05-02T07:19:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,604 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'mywidget.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.10.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../4_3_myBuddy/mywidget.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'mywidget.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.10.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_MyWidget_t {
QByteArrayData data[1];
char stringdata0[9];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_MyWidget_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_MyWidget_t qt_meta_stringdata_MyWidget = {
{
QT_MOC_LITERAL(0, 0, 8) // "MyWidget"
},
"MyWidget"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_MyWidget[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
void MyWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
QT_INIT_METAOBJECT const QMetaObject MyWidget::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_MyWidget.data,
qt_meta_data_MyWidget, qt_static_metacall, nullptr, nullptr}
};
const QMetaObject *MyWidget::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *MyWidget::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_MyWidget.stringdata0))
return static_cast<void*>(this);
return QWidget::qt_metacast(_clname);
}
int MyWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| [
"chenyushen1989@gmail.com"
] | chenyushen1989@gmail.com |
ec3704a1b8734cc7aeeecf7a901e39d017d005e0 | 1cbb4b9f4cf513846622d4124588f50347e22eac | /CPP-Programming/week07/assignment/string_op.cpp | c8d7519b03daf7fc0bb713feedf659dd88b193b5 | [] | no_license | googed/coursera-Foundamentals-of-Programming-and-Algorithms | 51831718bebf7cc94aadc80e9ca1339ac06c07f8 | edc394a9d67cb1300c30eef513a588f12a7eea22 | refs/heads/master | 2021-01-15T22:51:37.054239 | 2017-02-26T18:20:14 | 2017-02-26T18:20:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,404 | cpp | #include <iostream>
#include <string>
#include <stdlib.h>
#include <cstdio>
using namespace std;
const int kMaxNum = 20;
string str[kMaxNum];
int number = 0;
char* strItoa = new char[101];
int GotNXL();
string GotS();
string copy();
string add();
int find();
int rfind();
void insert();
void reset();
void print();
void printall();
int GotNXL() {
string NXL;
int nxl;
cin >> NXL;
if (NXL == "find")
nxl = find();
else if (NXL == "rfind")
nxl = rfind();
else
nxl = atoi(NXL.c_str());
return nxl;
}
string GotS() {
string S, result;
cin >> S;
result = S;
if (S == "add")
result = add();
else if (S == "copy")
result = copy();
return result;
}
string copy() {
string result;
int n, x, l;
n = GotNXL();
x = GotNXL();
l = GotNXL();
result = str[n - 1].substr(x, l);
return result;
}
string add() {
string S1, S2;
S1 = GotS();
S2 = GotS();
for (int i = 0; i < S1.size(); i++)
{
if (S1.at(i) < '0' || S1.at(i) > '9')
{
return S1 + S2;
}
}
for (int i = 0; i < S2.size(); i++)
{
if (S2.at(i) < '0' || S2.at(i) > '9')
{
return S1 + S2;
}
}
long a = atoi(S1.c_str());
long b = atoi(S2.c_str());
if (a >= 0 && a <= 99999 && b >= 0 && b <= 99999)
{
long c = a + b;
sprintf(strItoa, "%d", c);
return strItoa;
}
else
return S1 + S2;
}
int find() {
string S;
int n, pos;
S = GotS();
n = GotNXL();
pos = str[n - 1].find(S);
if (pos == string::npos)
return str[n - 1].size();
else
return pos;
}
int rfind() {
string S;
int n, pos;
S = GotS();
n = GotNXL();
pos = str[n - 1].rfind(S);
if (pos == string::npos)
return str[n - 1].size();
else
return pos;
}
void insert() {
string S;
int n, x;
S = GotS();
n = GotNXL();
x = GotNXL();
str[n - 1].insert(x, S);
}
void reset() {
string S;
int n;
S = GotS();
n = GotNXL();
str[n - 1] = S;
}
void print() {
int n;
n = GotNXL();
cout << str[n - 1] << endl;
}
void printall() {
for (int i = 0; i < number; ++i)
cout << str[i] << endl;
}
int main(int argc, char const *argv[])
{
string order;
cin >> number;
for (int i = 0; i < number; ++i)
{
cin >> str[i];
}
while (1) {
cin >> order;
if (order == "over")
break;
else if (order == "insert")
insert();
else if (order == "reset")
reset();
else if (order == "print")
print();
else if (order == "printall")
printall();
else if (order == "insert")
insert();
}
return 0;
} | [
"zipan@paypal.com"
] | zipan@paypal.com |
331afdb0b4ff52c4e3263d57782ae98fed55337e | 1f63dde39fcc5f8be29f2acb947c41f1b6f1683e | /Boss2D/addon/_old/webrtc-qt5.11.2_for_boss/modules/remote_bitrate_estimator/include/send_time_history.h | 931eb3467eadf3e9d6f3d414aa6e4ad1d6dc59c9 | [
"MIT",
"LicenseRef-scancode-google-patent-license-webrtc",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"GPL-1.0-or-later",
"LicenseRef-scancode-takuya-ooura",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown",
"MS-LPL",
"LicenseRef-scancode-google-patent-licen... | permissive | koobonil/Boss2D | 09ca948823e0df5a5a53b64a10033c4f3665483a | e5eb355b57228a701495f2660f137bd05628c202 | refs/heads/master | 2022-10-20T09:02:51.341143 | 2019-07-18T02:13:44 | 2019-07-18T02:13:44 | 105,999,368 | 7 | 2 | MIT | 2022-10-04T23:31:12 | 2017-10-06T11:57:07 | C++ | UTF-8 | C++ | false | false | 2,139 | h | /*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef MODULES_REMOTE_BITRATE_ESTIMATOR_INCLUDE_SEND_TIME_HISTORY_H_
#define MODULES_REMOTE_BITRATE_ESTIMATOR_INCLUDE_SEND_TIME_HISTORY_H_
#include <map>
#include BOSS_WEBRTC_U_modules__include__module_common_types_h //original-code:"modules/include/module_common_types.h"
#include BOSS_WEBRTC_U_rtc_base__basictypes_h //original-code:"rtc_base/basictypes.h"
#include BOSS_WEBRTC_U_rtc_base__constructormagic_h //original-code:"rtc_base/constructormagic.h"
namespace webrtc {
class Clock;
struct PacketFeedback;
class SendTimeHistory {
public:
SendTimeHistory(const Clock* clock, int64_t packet_age_limit_ms);
~SendTimeHistory();
// Cleanup old entries, then add new packet info with provided parameters.
void AddAndRemoveOld(const PacketFeedback& packet);
// Updates packet info identified by |sequence_number| with |send_time_ms|.
// Return false if not found.
bool OnSentPacket(uint16_t sequence_number, int64_t send_time_ms);
// Look up PacketFeedback for a sent packet, based on the sequence number, and
// populate all fields except for arrival_time. The packet parameter must
// thus be non-null and have the sequence_number field set.
bool GetFeedback(PacketFeedback* packet_feedback, bool remove);
size_t GetOutstandingBytes(uint16_t local_net_id,
uint16_t remote_net_id) const;
private:
const Clock* const clock_;
const int64_t packet_age_limit_ms_;
SequenceNumberUnwrapper seq_num_unwrapper_;
std::map<int64_t, PacketFeedback> history_;
rtc::Optional<int64_t> latest_acked_seq_num_;
RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(SendTimeHistory);
};
} // namespace webrtc
#endif // MODULES_REMOTE_BITRATE_ESTIMATOR_INCLUDE_SEND_TIME_HISTORY_H_
| [
"slacealic@nate.com"
] | slacealic@nate.com |
2f3314d94b1512ac8ba6299dbca288c836f94d67 | 67650d44c0f699a1ed84929fa0d707c373b6f34d | /helloCpp/concurrency/AccountManager.cpp | a0ccadefd5072570c4defe2c1249e9b111a588bd | [] | no_license | SebLKMa/CodingForFun | 1575e87c66103f013474da350b819c3c5bc61950 | 0f891ca2234fc795ff367bae3bf9d223dfbec008 | refs/heads/master | 2020-12-25T18:05:14.509841 | 2018-12-20T07:27:58 | 2018-12-20T07:27:58 | 68,350,257 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 134 | cpp | //#include "stdafx.h"
#include "AccountManager.h"
/*
AccountManager::AccountManager()
{
}
AccountManager::~AccountManager()
{
}
*/
| [
"sebmalikkeung@gmail.com"
] | sebmalikkeung@gmail.com |
3dd6a94e7f414b04e24e8c95810d5e1234757742 | 715e090142030abb0f92fa0d77ce9c0c82c702fc | /Common/src/GLFW_Common.cpp | 2b481dd7ad79409b6ce0319b1d5c77f4492984d7 | [] | no_license | Timmoth/LearningOpenGL | 0fc36bf2916e53825f5e3c513d2e37e6de4d0ed3 | 11448e90994f44d0c8db8221bbce96d6ad0cf8ac | refs/heads/master | 2021-05-04T22:14:09.728645 | 2018-02-19T08:27:28 | 2018-02-19T08:27:28 | 120,018,763 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 878 | cpp | #include "../Headers/GLFW_Common.h"
int InitGLFW() {
cout << "Initializing GLFW library" << endl;
//Perform initialization checks to ensure hardware & software features are available on the machine
if (!glfwInit()) {
//Handle initialization failure
cout << "Error initializing GLFW library" << endl;
return 0;
}
return 1;
}
GLFWwindow* CreateGLFWwindow(string title, int width, int height) {
cout << "Creating the OpenGL Context" << endl;
//Attempt to create a handle to a OpenGL context
GLFWwindow* window = glfwCreateWindow(width, height, title.c_str(), NULL, NULL);
if (!window) {
cout << "Could not create OpenGL Window" << endl;
//free any allocated resources
glfwTerminate();
return NULL;
}
//Make the window's context the current one for this thread
glfwMakeContextCurrent(window);
glViewport(0, 0, width, height);
return window;
} | [
"timmoth.jones@gmail.com"
] | timmoth.jones@gmail.com |
61ee977a895fe173df2af32de3a627c7b7353743 | cb9fa06fb616972f94370b69f69efc53ecc7d700 | /keyboard_control/main.cpp | c2d3c0789e966505328cfd078bcae2634c3433cc | [] | no_license | jiachenwei/tiny-utility | f0d71c7cb309c6b911bfe9df777d6d436818754d | 1a7a4b4801ea3d3bf0629f02807e965f9002cf10 | refs/heads/main | 2023-05-11T02:12:47.487367 | 2021-05-31T01:41:06 | 2021-05-31T01:41:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,669 | cpp | /**
* @file main.cpp
* @brief
* @author Chenwei Jia (cwjia98@gmail.com)
* @version 1.0
* @date 2021-05-20
*/
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <termio.h>
#include <unistd.h>
#include <iostream>
#include <mutex>
#include <thread>
#define ACCELE_RATE 0.5 // 向前加速度
#define REVERSE_ACCELE_RATE -0.5 // 向后加速度
#define NATURAL_DEACCELE_RATE -0.2 // 自然减速度
#define BRAKE_DEACCELE_RATE -1 // 刹车减速度
#define WHEEL_RATE 10 // 转动角度的速率
#define MAX_WHEEL_ANGLE 570 // 方向盘最大转动角度
int current_max_speed = 0;
int current_wheel_angle = 0;
int current_gear_state = 1;
bool current_hand_brake_state = 1;
char current_drive_state = 0;
int current_control_state = 0;
std::mutex m;
unsigned char scan_keyboard() {
char kb_input = 0;
struct termios new_settings;
struct termios stored_settings;
tcgetattr(STDIN_FILENO, &stored_settings); //获得stdin 输入
new_settings = stored_settings; //
new_settings.c_lflag &= (~ICANON); //
new_settings.c_lflag &= (~ECHO); //
new_settings.c_cc[VTIME] = 0;
tcgetattr(STDIN_FILENO, &stored_settings); //获得stdin 输入
new_settings.c_cc[VMIN] = 1;
tcsetattr(STDIN_FILENO, TCSAFLUSH,
&new_settings); // STDIN_FILENO TCSANOW
fd_set rfds;
struct timeval tv;
FD_ZERO(&rfds);
FD_SET(0, &rfds);
tv.tv_sec = 0;
tv.tv_usec = 500000;
if (select(1, &rfds, NULL, NULL, &tv) > 0) {
kb_input = getchar();
}
tcsetattr(STDIN_FILENO, TCSAFLUSH, &stored_settings);
return kb_input;
}
int keyboard_input_map(unsigned char key) {
std::lock_guard<std::mutex> g1(m);
current_drive_state = 2;
int ret = 0;
if (key == 27) {
ret = -1; // 复位,
current_wheel_angle = 0;
current_max_speed = 0;
current_gear_state = 4;
current_drive_state = 0;
} else if (key == 'w' || key == 'W') {
ret = 1; // 发送一个正的加速度
current_drive_state = 1;
} else if (key == 's' || key == 'S') {
ret = 2; // 发送一个负的加速度
current_drive_state = -1;
} else if (key == 'a' || key == 'A') {
ret = 3; // 向左打方向盘
current_wheel_angle =
(current_wheel_angle - WHEEL_RATE <= -MAX_WHEEL_ANGLE
? -MAX_WHEEL_ANGLE
: current_wheel_angle - WHEEL_RATE);
} else if (key == 'd' || key == 'D') {
ret = 4; // 向右打方向盘
current_wheel_angle =
(current_wheel_angle + WHEEL_RATE >= MAX_WHEEL_ANGLE
? MAX_WHEEL_ANGLE
: current_wheel_angle + WHEEL_RATE);
} else if (key == 'q' || key == 'Q') {
ret = 5; // 快速向左打方向盘
current_wheel_angle =
(current_wheel_angle - WHEEL_RATE * 2 <= -MAX_WHEEL_ANGLE
? -MAX_WHEEL_ANGLE
: current_wheel_angle - WHEEL_RATE * 2);
} else if (key == 'e' || key == 'E') {
ret = 6; // 快速向右打方向盘
current_wheel_angle =
(current_wheel_angle + WHEEL_RATE * 2 >= MAX_WHEEL_ANGLE
? MAX_WHEEL_ANGLE
: current_wheel_angle + WHEEL_RATE * 2);
} else if (key == 'r' || key == 'R') {
ret = 7; // 方向盘复位至零
current_wheel_angle = 0;
} else if (key == 32) {
ret = 8; // 刹车
current_drive_state = 0;
} else if (key == '1') {
ret = 11; // P档
current_gear_state = 1;
} else if (key == '2') {
ret = 12; // R档
current_gear_state = 2;
} else if (key == '3') {
ret = 13; // N档
current_gear_state = 3;
} else if (key == '4') {
ret = 14; // D档
current_gear_state = 4;
} else if (key == '>' || key == '.') {
ret = 21; // 拉手刹
current_hand_brake_state = true;
} else if (key == '<' || key == ',') {
ret = 22; // 放手刹
current_hand_brake_state = false;
} else if (key == '+' || key == '=') {
ret = 31; // 升高最大车速
current_max_speed++;
current_max_speed = current_max_speed >= 180 ? 180 : current_max_speed;
} else if (key == '-' || key == '_') {
ret = 32; // 降低最大车速
current_max_speed--;
current_max_speed = current_max_speed <= 0 ? 0 : current_max_speed;
} else {
ret = 0; // 无操作
}
current_control_state = ret;
return ret;
}
void print_info() {
std::lock_guard<std::mutex> g2(m);
std::cout << "\033[2J\033[0;0H\033[?25l";
std::cout << "\n\033[1m--键盘调试工具--\033[0m\n" << std::endl;
std::cout << "0.紧急情况按住Esc\n";
struct winsize size;
ioctl(STDIN_FILENO, TIOCGWINSZ, &size);
if (current_hand_brake_state) {
std::cout
<< "1.手刹状态:放下(,) \033[4m\033[1m\033[41m拉起(.)\033[0m\n";
} else {
std::cout
<< "1.手刹状态:\033[4m\033[1m\033[42m放下(,)\033[0m 拉起(.)\n";
}
if (current_gear_state == 1) {
std::printf(
"2.当前档位:\033[41m\033[1m\033[4m\033[38mP(1)\033[0m R(2) N(3) "
"D(4)\n");
} else if (current_gear_state == 2) {
std::printf(
"2.当前档位:P(1) \033[42m\033[1m\033[4m\033[38mR(2)\033[0m N(3) "
"D(4)\n");
} else if (current_gear_state == 3) {
std::printf(
"2.当前档位:P(1) R(2) \033[42m\033[1m\033[4m\033[38mN(3)\033[0m "
"D(4)\n");
} else if (current_gear_state == 4) {
std::printf(
"2.当前档位:P(1) R(2) N(3) "
"\033[42m\033[1m\033[4m\033[38mD(4)\033[0m\n");
}
if (current_drive_state == 1) {
std::cout << "3.行驶状态:\033[4m\033[1m前进(W)\033[0m 制动(Space) "
"倒车(S) 滑行\n";
} else if (current_drive_state == 0) {
std::cout << "3.行驶状态:前进(W) \033[4m\033[1m制动(Space)\033[0m "
"倒车(S) 滑行\n";
} else if (current_drive_state == -1) {
std::cout << "3.行驶状态:前进(W) 制动(Space) "
"\033[4m\033[1m倒车(S)\033[0m 滑行\n";
} else {
std::cout << "3.行驶状态:前进(W) 制动(Space) 倒车(S) "
"\033[4m\033[1m滑行\033[0m\n";
}
std::printf("4.最大车速:\033[1m%4d\033[0mkm/h (+/-)\n", current_max_speed);
std::printf(
"5.转向角度:\033[1m%4d\033[0mdegree (慢速:A/D, 快速:Q/E, 复位:R)\n",
current_wheel_angle);
int slen = int((size.ws_col - 1) / 2) - 1;
std::string lsb(slen, ' ');
std::string rsb(slen, ' ');
std::string ls(0, ' ');
std::string rs(0, ' ');
if (current_wheel_angle > 0) {
int rslen =
int(float(current_wheel_angle) / MAX_WHEEL_ANGLE * (slen - 1));
rs = std::string(rslen, '>');
rsb = std::string(slen - rslen, ' ');
} else if (current_wheel_angle < 0) {
int lslen =
int(float(-current_wheel_angle) / MAX_WHEEL_ANGLE * (slen - 1));
ls = std::string(lslen, '<');
lsb = std::string(slen - lslen, ' ');
} else {
;
}
std::cout << "[" + lsb + "\033[42m" + ls + "\033[0m|\033[42m" + rs +
"\033[0m" + rsb + "]\n";
printf("\33[%d;0Hcontrol state:%d\033[?25h\r\n", size.ws_row - 1,
current_control_state);
}
void publish_message() {
std::lock_guard<std::mutex> g3(m);
if (current_control_state == -1) { // 最大车速与方向盘角度复位
;
} else if (current_control_state / 10 == 0) { // 发送控车指令
;
} else if (current_control_state / 10 == 1) { // 发送档位指令
;
} else if (current_control_state / 10 == 2) { // 发送手刹指令
;
} else if (current_control_state / 10 == 3) { // 调整最大车速,控车时发出
;
} else {
;
}
}
void input() {
while (1) {
keyboard_input_map(scan_keyboard());
}
}
void print() {
while (1) {
print_info();
usleep(50000);
}
}
void publish() {
while (1) {
publish_message();
usleep(10000);
}
}
using namespace std;
int main(int argc, char *argv[]) {
thread thread_input(input);
thread thread_print(print);
thread thread_publish(publish);
thread_input.join();
thread_print.join();
thread_publish.join();
return 0;
}
| [
"cwjia98@gmail.com"
] | cwjia98@gmail.com |
5c96919dcb8ab2ac11fbcde6a86999c725153fdb | ce036ed927ccf735ac51524d7413bed05e2b25c4 | /Y86.h | d6570b0825f9b1ccc025c427bed24c753ec74942 | [] | no_license | reevesjd/lab4 | f0fe0b71cc66888b815050299f7a1e5bdf7468d4 | 845485ae36f3f91a27f814a0151270cc80818330 | refs/heads/master | 2020-04-20T22:32:55.069025 | 2019-02-04T22:38:55 | 2019-02-04T22:38:55 | 169,143,655 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 615 | h | /*
File: Y86.h
Desc: Y86 class declaration
Author: efb
*/
#ifndef Y86_H
#define Y86_H
#include <string>
#include "Memory.h"
#include "ProgRegisters.h"
class Y86 {
Memory memory;
ProgRegisters regs;
/* Private member functions */
/* Public interface */
public:
Y86();
void reset();
void clockP0();
void clockP1();
Memory& getMemory(){return memory;} // used to test memory
ProgRegisters& getProgRegisters(){return regs;} // used to test registers
};
#endif | [
"ellerhc@student2.cs.appstate.edu"
] | ellerhc@student2.cs.appstate.edu |
0910cc41b52aebe892877b612c6a10f732c4fc2e | 4a5bf98f527d5e3ebb5a372090a093094bd20451 | /617A.cpp | 76e9b72dbaae032273c2d1dd810c1f1f7dd0acf9 | [] | no_license | nc1337/Codeforces | 0af50746109d40da015aa2c44921a8f902958193 | b256bb84b982dd9732903b58c32f6eef7c92f363 | refs/heads/main | 2023-04-19T11:34:46.460367 | 2021-05-17T05:50:47 | 2021-05-17T05:50:47 | 368,062,370 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 261 | cpp |
#include <bits/stdc++.h>
using namespace std;
int main() {
int x;
int cnt = 0;
cin>>x;
while(x != 0) {
cnt += x / 5;
x %= 5;
cnt += x / 4;
x %= 4;
cnt += x / 3;
x %= 3;
cnt += x / 2;
x %= 2;
cnt += x;
x = 0;
}
cout<<cnt;
return 0;
}
| [
"nitinmax1000@gmail.com"
] | nitinmax1000@gmail.com |
4ee680c6139ee956b77be2eb2d21bae23d6cef27 | eff037739063243685ad09d0db639a80d3433c98 | /02-cpp/file-io/fstream.cpp | c5d4522fea4fcba304e348d436af7042b9970d48 | [] | no_license | mahumberto/misc-programming | 34f4cfbcd9f9c404aba25256eb357b5aa17bbd75 | 6e7fbdcac3eca9ee21623ee15c77de74d2befc1a | refs/heads/master | 2023-06-10T07:16:27.436628 | 2017-06-14T16:52:44 | 2017-06-14T16:52:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,453 | cpp | /**
* File io basics
* - include <fstream> //includes file stream handle lib
* - ofstream myfile; //for writing to a file
* - ifstream myfile; //for reading a file
* - fstream myfile; //for reading and writing a file
* - myfile.open("fname"); //opens file called fname
* - myfile.close("fname"); //closes file called fname
*/
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int readFile()
{
string line;
//create an input stream to write to the file
ifstream myfileO ("input.txt");
if (myfileO.is_open())
{
while ( getline (myfileO,line) )
{
cout << line << '\n';
}
myfileO.close();
}
else cout << "Unable to open file for reading";
}
int main () {
//create an output stream to write to the file
//ios:app - append the new lines to the end of the file
ofstream myfileI ("input.txt", ios::app);
if (myfileI.is_open())
{
myfileI << "\nI am adding a line.\n";
myfileI << "I am adding another line.\n";
myfileI.close();
}
else cout << "Unable to open file for writing";
readFile();
//rw input.tx
fstream myfile("input.txt");
if(myfile.is_open())
{
myfile << "Replace char sequence and erases endl also";
myfile << endl;
myfile.close();
}
else cout << "Unable to open file for writing";
readFile();
return 0;
}
| [
"ma.humberto@gmail.com"
] | ma.humberto@gmail.com |
bab3c30c887a700af02b545767d01f5ba868c3b9 | 01ae35a36363cdcd8034b9f40e519203428b69ff | /NavigationSystem/src/CPOI.h | db296455fe496a7517188003ae002ca7073da50b | [] | no_license | tanjilul-alam-57/Project1 | 6e1c09d202715b4aaa3a56f52031a7feca578904 | 0abd830795aa15f5fbe178a4fecd472e4a812b2f | refs/heads/master | 2020-04-10T06:36:46.235892 | 2018-12-07T19:17:34 | 2018-12-07T19:17:34 | 160,859,708 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 826 | h | /*
* CPOI.h
*
* Created on: Nov 19, 2018
* Author: Tanjil
*/
#ifndef CPOI_H_
#define CPOI_H_
#include <string.h>
#include <iostream>
#include "CWaypoint.h"
enum t_poi{Resturant,Hotel, Pub, Market, NONE, Park};
using namespace std;
//declaring inheritance and making CWaypoints attributes public in this class
class CPOI : public CWaypoint
{
private:
//declaring private attributes
string m_description;
t_poi m_type;
public:
//declaring constructor & public functions.
CPOI(t_poi type=NONE, string description="", string name="", double latitude=0, double longitude=0);
void print();
void getAllDataByReference(string &name, double &latitude, double &longitude, t_poi &type, string &description);
//Declared destructor.
//virtual ~CPOI();
};
#endif /* CPOI_H_ */
| [
"alam.tanjilul@gmail.com"
] | alam.tanjilul@gmail.com |
6be60835ab962dc90e3c4c468c17345f54bf9f6e | 2ada10483cd3f9512034a9da0c1477417e5437bc | /src/practice/src/hackerrank/src/cpp_exception_handling.cpp | 1c5650373f839c7aa793e1574e5642de238ecf0c | [
"BSD-3-Clause"
] | permissive | behnamasadi/data_structure_algorithm | d76f4ba3b1d8c64e30be63dc799e9c16127e656e | ba58f96b4cb1f9a4c4b2dc748aed75370747cbe7 | refs/heads/master | 2021-06-24T10:56:59.249390 | 2021-06-22T16:41:53 | 2021-06-22T16:41:53 | 245,398,545 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 905 | cpp | #include <iostream>
#include <stdexcept>
using namespace std;
int largest_proper_divisor(int n) {
if (n == 0) {
throw invalid_argument("largest proper divisor is not defined for n=0");
}
if (n == 1) {
throw invalid_argument("largest proper divisor is not defined for n=1");
}
for (int i = n/2; i >= 1; --i) {
if (n % i == 0) {
return i;
}
}
return -1; // will never happen
}
void process_input(int n)
{
int d ;
try
{
d = largest_proper_divisor(n);
}
catch (invalid_argument &e)
{
std::cout<<e.what() <<std::endl;
std::cout<<"returning control flow to caller"<<std::endl;
return;
}
cout << "result=" << d << endl;
std::cout<<"returning control flow to caller"<<std::endl;
}
int main() {
int n;
cin >> n;
process_input(n);
return 0;
}
| [
"behnam.asadi@gmail.com"
] | behnam.asadi@gmail.com |
08b764bdd3e3b185bb2ae1fa7712dda1952ec754 | 07fe910f4a2c7d14e67db40ab88a8c91d9406857 | /game/t3/runtime/Runtime_Engine.h | c074a823adc95faabbbb54526781149b650276b4 | [] | no_license | SEDS/GAME | e6d7f7a8bb034e421842007614d306b3a6321fde | 3e4621298624b9189b5b6b43ff002306fde23f08 | refs/heads/master | 2021-03-12T23:27:39.115003 | 2015-09-22T15:05:33 | 2015-09-22T15:05:33 | 20,278,561 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,877 | h | // -*- C++ -*-
//=============================================================================
/**
* @file T3_Runtime_Engine.h
*
* $Id$
*
* @author James H. Hill
*/
//=============================================================================
#ifndef _T3_RUNTIME_ENGINE_H_
#define _T3_RUNTIME_ENGINE_H_
#include "game/mga/utils/modelgen.h"
#include "game/mga/Model.h"
#include "ace/Null_Mutex.h"
#include "ace/Singleton.h"
#include "ace/SString.h"
#include "ace/Hash_Map_Manager.h"
#include "Runtime_export.h"
#include "Event_Listener.h"
#include "algorithm.h"
namespace T3
{
/**
* @class create_failed
*
* Exception thrown when creating an element fails for unknown
* reasons.
*/
class T3_RUNTIME_Export create_failed
{
public:
create_failed (GAME::Mga::Object_in parent, const std::string & type)
: parent_ (parent),
type_ (type)
{
}
GAME::Mga::Object parent (void) const
{
return this->parent_;
}
const std::string & type (void) const
{
return this->type_;
}
private:
/// Parent for the creation.
GAME::Mga::Object parent_;
/// Target type to create.
std::string type_;
};
/**
* @class bad_parent
*
* Exception thrown when the specified parent object is not
* eligible l to be a parent (i.e., not a Model or Folder).
*/
class T3_RUNTIME_Export bad_parent
{
public:
bad_parent (GAME::Mga::Object_in parent)
: parent_ (parent)
{
}
private:
GAME::Mga::Object parent_;
};
/**
* @class invalid_type
*
* Exception thrown when the specified type is not valid. This
* can occur when creating an child element, or setting the value
* of an attribute.
*/
class T3_RUNTIME_Export invalid_type
{
public:
invalid_type (GAME::Mga::Object_in parent, const std::string & type)
: parent_ (parent),
type_ (type)
{
}
private:
GAME::Mga::Object parent_;
std::string type_;
};
/**
* @class invalid_attr
*
* Exception thrown when the specified type is not valid. This
* can occur when creating an child element, or setting the value
* of an attribute.
*/
class T3_RUNTIME_Export invalid_attr
{
public:
invalid_attr (GAME::Mga::FCO_in fco, const std::string & attr)
: fco_ (fco),
attr_ (attr)
{
}
private:
GAME::Mga::FCO fco_;
std::string attr_;
};
}
/**
* @class T3_Runtime_Engine
*/
class T3_RUNTIME_Export T3_Runtime_Engine
{
public:
typedef ACE_Hash_Map_Manager <ACE_CString, GAME::Mga::FCO, ACE_Null_Mutex>
SYMBOL_TABLE;
typedef ACE_Hash_Map_Manager <ACE_CString, bool, ACE_Null_Mutex>
FLAG_TABLE;
typedef ACE_Hash_Map_Manager <ACE_CString, std::string, ACE_Null_Mutex>
STRING_TABLE;
typedef ACE_Hash_Map_Manager <ACE_CString, int, ACE_Null_Mutex>
INT_TABLE;
typedef ACE_Hash_Map_Manager <ACE_CString, double, ACE_Null_Mutex>
DOUBLE_TABLE;
/// Default constructor.
T3_Runtime_Engine (void);
/// Destructor.
~T3_Runtime_Engine (void);
GAME::Mga::Object create_element (GAME::Mga::Object_in parent,
const std::string & type);
template <typename Cond>
GAME::Mga::Object create_element_if_not (GAME::Mga::Object_in parent,
const std::string & type,
Cond cond)
{
switch (parent->type ())
{
case OBJTYPE_MODEL:
return create_element_if_not (GAME::Mga::Model::_narrow (parent), type, cond);
break;
case OBJTYPE_FOLDER:
// ignore for now
throw T3::bad_parent (parent);
break;
default:
throw T3::bad_parent (parent);
}
}
template <typename Cond>
GAME::Mga::Object create_element_if_not (GAME::Mga::Model_in parent,
const std::string & type,
Cond cond)
{
// Get the children of the specified type.
std::vector <GAME::Mga::FCO> children;
GAME::Mga::Object object;
if (parent->children (type, children))
{
std::vector <GAME::Mga::FCO>::const_iterator result;
result = std::find_if (children.begin (),
children.end (),
cond);
if (result != children.end ())
{
object = *result;
if (0 != this->listener_)
this->listener_->handle_new_object (object);
}
}
// Since we could not find the object, we need to create
// a new one for the model.
if (object.is_nil ())
object = this->create_element (parent, type);
// Initialize the FCO.
this->init_fco (GAME::Mga::FCO::_narrow (object));
return object;
}
GAME::Mga::Object create_element (GAME::Mga::Folder_in parent,
const std::string & type);
GAME::Mga::Object create_element (GAME::Mga::Model_in parent,
const std::string & type);
bool create_connection_to (const GAME::Mga::Object_in src,
const std::string & dest,
const std::string & type);
/**
* Set the value of an attribute for the active object.
*
* @param[in] name Name of the target attribute
* @param[in] value Value of the target attribute
*/
void set_attribute (GAME::Mga::FCO_in fco, const std::string & name, const std::string & value);
void set_attribute (GAME::Mga::FCO_in fco, const std::string & name, long value);
void set_attribute (GAME::Mga::FCO_in fco, const std::string & name, bool value);
void set_attribute (GAME::Mga::FCO_in fco, const std::string & name, double value);
bool store_reference (const GAME::Mga::Object_in obj, const std::string & symbol);
bool resolve (const GAME::Mga::Object_in obj, const std::string & symbol, GAME::Mga::FCO & fco);
bool store_attribute (const std::string & name, bool value);
bool store_attribute (const std::string & name, double value);
bool store_attribute (const std::string & name, int value);
bool store_attribute (const std::string & name, const std::string & value);
bool store_predefined_reference (const GAME::Mga::Object_in obj, const char * pt);
const SYMBOL_TABLE & symbols (void) const;
SYMBOL_TABLE & symbols (void);
void preprocess (GAME::Mga::Object_in parent, const std::string & include_file);
bool create_unique_reference (GAME::Mga::Object_in parent,
const std::string & symbol,
const std::string & type);
bool create_unique_reference (GAME::Mga::Object_in parent,
const std::string & symbol,
const std::string & type,
GAME::Mga::FCO & ref_element);
T3_Event_Listener * event_listener (void);
void event_listener (T3_Event_Listener * listener);
private:
void preprocess_impl (GAME::Mga::Model_in model);
void init_fco (GAME::Mga::FCO_in fco);
void resolve_reference (GAME::Mga::FCO_in fco);
/// Symbol table for the engine.
SYMBOL_TABLE sym_table_;
FLAG_TABLE stored_flags_;
INT_TABLE stored_ints_;
STRING_TABLE stored_strings_;
DOUBLE_TABLE stored_doubles_;
GAME::Mga::FCO stored_ref_;
/// Event listener for the runtime engine.
T3_Event_Listener * listener_;
void get_scope (const GAME::Mga::Object_in obj, std::string & scope);
};
#define T3_RUNTIME_ENGINE_SINGLETON \
ACE_Singleton <T3_Runtime_Engine, ACE_Null_Mutex>;
T3_RUNTIME_SINGLETON_DECLARATION (T3_RUNTIME_ENGINE_SINGLETON);
#define T3_RUNTIME_ENGINE \
ACE_Singleton <T3_Runtime_Engine, ACE_Null_Mutex>::instance ()
#include "Runtime_Engine.inl"
#endif // !defined _T3_RUNTIME_ENGINE_H_
| [
"hillj@cs.iupui.edu"
] | hillj@cs.iupui.edu |
bafdc4396c1cc874a7ea941c3b50da62370dfeda | f79e67e9dcffadbb9f293510ec03333cec6ab8fe | /Source/ShooterInSnow/BehaviorTree/Tasks/BTTask_Shoot.cpp | c69dec74882310e7d639c9656ffae2a6ec7dc990 | [] | no_license | ali-v-1985/ShooterInSnow | b09401a561c7eeb54a71b872495c79b92aeae015 | 48f5808140ff614c1d93b8d04e9384993cdd5b7f | refs/heads/master | 2022-12-27T13:55:59.031030 | 2020-10-12T00:18:38 | 2020-10-12T00:18:38 | 301,841,158 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 781 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "BTTask_Shoot.h"
#include "EditorBuildUtils.h"
#include "AIController.h"
#include "ShooterInSnow/Characters/ShooterCharacter.h"
UBTTask_Shoot::UBTTask_Shoot()
{
NodeName = TEXT("Shoot");
}
EBTNodeResult::Type UBTTask_Shoot::ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory)
{
Super::ExecuteTask(OwnerComp, NodeMemory);
if(OwnerComp.GetAIOwner() == nullptr)
{
return EBTNodeResult::Failed;
}
AShooterCharacter* AICharacter = Cast<AShooterCharacter>(OwnerComp.GetAIOwner()->GetPawn());
if(AICharacter == nullptr)
{
return EBTNodeResult::Failed;
}
AICharacter->PullTrigger();
return EBTNodeResult::Succeeded;
}
| [
"ali.valizadeh.h@gmail.com"
] | ali.valizadeh.h@gmail.com |
9942d4993939ebd646cedc2ff5073340cfe493a2 | 88e152e0cb34a79022e4f1cba6d7780e40c7ba19 | /src/Meteor/MapInfo.cpp | e58d19616de3e8a56a2a845ba7fd11abf4d5d73f | [
"MIT"
] | permissive | namse/meteor | a8292499a343dc64193b935e39b3c659d80f9bfd | 635fe8b99079cb5505e9fb1701430d4723f7eb1f | refs/heads/master | 2021-05-26T14:20:20.068395 | 2013-11-06T06:09:12 | 2013-11-06T06:09:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,250 | cpp | #include "stdafx.h"
#include "MapInfo.h"
// ----------------------------------------------------------------
// Constructor
// ----------------------------------------------------------------
CMapInfo::CMapInfo( std::wstring mapType )
: m_MapType( mapType )
{
}
// ----------------------------------------------------------------
// Destrutor
// ----------------------------------------------------------------
CMapInfo::~CMapInfo(void)
{
}
// ----------------------------------------------------------------
// LoadResource
// ----------------------------------------------------------------
bool CMapInfo::LoadResource()
{
HANDLE hFile;
DWORD dwBytesRead = 0;
DWORD dwBytesWrite = 0;
std::wstring filePath = m_MapType + L".map";
hFile = CreateFile( filePath.c_str(), // file to open
GENERIC_READ, // open for reading
FILE_SHARE_READ, // share for reading
NULL, // default security
OPEN_EXISTING, // existing file only
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no attr. template
if ( hFile == INVALID_HANDLE_VALUE )
{
wprintf( L"Error: unable to open file \"%s\" for read.\n", filePath.c_str() );
return false;
}
if ( FALSE == ReadFile( hFile, &m_Header, sizeof(m_Header), &dwBytesRead, NULL ) ||
dwBytesRead < sizeof(m_Header) )
{
wprintf( L"Error: Unable to read from file.\n" );
CloseHandle(hFile);
return false;
}
for ( UINT count = 0; count < m_Header.m_TileCount; ++count )
{
TileData tileData;
if ( FALSE == ReadFile( hFile, &tileData, sizeof(tileData), &dwBytesRead, NULL ) ||
dwBytesRead < sizeof(tileData) )
{
wprintf( L"Error: Unable to read from file.\n" );
CloseHandle(hFile);
return false;
}
m_Tiles.push_back( tileData );
}
for ( UINT count = 0; count < m_Header.m_MapCount; ++count )
{
CMapData * mapData = new CMapData();
mapData->Read( hFile );
m_Maps.push_back( mapData );
}
CloseHandle( hFile );
return true;
}
// ----------------------------------------------------------------
// Release
// ----------------------------------------------------------------
void CMapInfo::Release()
{
for ( auto map : m_Maps )
delete map;
}
| [
"jinus.kr@gmail.com"
] | jinus.kr@gmail.com |
4c8df626849616c45806c6ea64b70d76d1a558cb | d4939b7abaa937359adc5e193a8b634a1edc0754 | /hamdist.cpp | bcec74533d4e3234326f379f80c8d4c183d43fdf | [] | no_license | aadityavikram/Solved_Questions | 60f2d43b15291776d0c75b0f89825452397bac54 | f538f47fca41c5cf7bdc893923f8facc10072a8b | refs/heads/master | 2021-07-13T05:36:35.313482 | 2021-04-12T16:17:06 | 2021-04-12T16:17:06 | 243,957,030 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 334 | cpp | // https://leetcode.com/problems/hamming-distance/
// Solution 1: -
int hammingDistance(int x, int y) {
int x0r=x^y,count=0;
while(x0r){
x0r&=(x0r-1);
count++;
}return count;
}
// Solution 2: -
int hammingDistance(int x, int y) {
return __builtin_popcount(x^y);
}
| [
"noreply@github.com"
] | aadityavikram.noreply@github.com |
af54c3e52e28636b35c85498d3d2be6bdbd7ea03 | 9ff8e317e7293033e3983c5e6660adc4eff75762 | /Source/menu/SGF_OptionPlaymode.cpp | aa754a18187c27335669e2a7f26d16d195ddb86c | [] | no_license | rasputtim/SGF | b26fd29487b93c8e67c73f866635830796970116 | d8af92216bf4e86aeb452fda841c73932de09b65 | refs/heads/master | 2020-03-28T21:55:14.668643 | 2018-11-03T21:15:32 | 2018-11-03T21:15:32 | 147,579,544 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,596 | cpp | /*
SGF - Super Game Fabric Super Game Fabric
Copyright (C) 2010-2011 Rasputtim <raputtim@hotmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <sstream>
#include "menu/SGF_OptionPlayMode.h"
#include "util/SGF_Debug.h"
#include "menu/SGF_MenuGlobal.h"
#include "SGF_Global.h"
#include "graphics/all.h"
using namespace ::std;
namespace SGF {
namespace Menu {
COptionPlayMode::COptionPlayMode(const Gui::CContextBox & parent,const Token *token) throw (CLoadException):
CMenuOption(parent,token),
lblue(255),
lgreen(255),
rblue(255),
rgreen(255){
setRunnable(false);
if ( *token != "play-mode" ){
throw CLoadException(__FILE__, __LINE__,"Not a play-mode");
}
readName(token);
}
COptionPlayMode::~COptionPlayMode(){
// Nothing
}
string COptionPlayMode::getText(){
ostringstream out;
out << CMenuOption::getText() << ": ";
/* TODO: language translations of these */
if (CMenuGlobals::freeForAll()){
out << "Free for all";
} else if (CMenuGlobals::cooperative()){
out << "Cooperative";
}
return out.str();
}
void COptionPlayMode::logic(){
if (lblue < 255){
lblue += 5;
}
if (rblue < 255){
rblue += 5;
}
if (lgreen < 255){
lgreen += 5;
}
if (rgreen < 255){
rgreen += 5;
}
//s setLeftAdjustColor(Colors::makeColor(255, lblue, lgreen));
//s setRightAdjustColor(Colors::makeColor(255, rblue, rgreen));
}
void run(const Menu::CContext &)
{}
void COptionPlayMode::changeMode(){
if (CMenuGlobals::freeForAll()){
CMenuGlobals::setCooperative();
} else if (CMenuGlobals::cooperative()){
CMenuGlobals::setFreeForAll();
}
}
bool COptionPlayMode::leftKey(){
changeMode();
lblue = lgreen = 0;
return true;
}
bool COptionPlayMode::rightKey(){
changeMode();
rblue = rgreen = 0;
return true;
}
}
} //end SGF | [
"rasputtim@hotmail.com"
] | rasputtim@hotmail.com |
e9dfefb68f30616593bdc99d0dd678916c335c07 | 05aebd51ced6eee139d3c24aeb0cba9036d0991d | /ExpProcessQt/ExpProcessQt/IO_Center.h | a3ec5b0b18fd3deb620d9ba58d100904a4280642 | [] | no_license | saroad/MEI_Tool | fbac53bdc6a3978621d672a4de2cfe2e65fc5702 | fb7f815ecf27234ef477a2d407d7a58f84053b54 | refs/heads/master | 2021-01-20T19:18:41.440612 | 2016-06-16T17:09:35 | 2016-06-16T17:09:35 | 61,309,717 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,217 | h | #include <iostream>
#include <string.h>
#include <QtGui/QApplication>
#include <QDebug>
#include <QThread>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>
#include <time.h>
#include <QMessageBox>
#include "ExpressionList.h"
#include "Expression.h"
#include "AutoIt_Connector.h"
#include "Output.h"
#include "LatexImageBuilder.h"
#include "IO_Wait.h"
using namespace std;
#ifndef IO_CENTER_H
#define IO_CENTER_H
class IO_Center : public QObject
{
Q_OBJECT
public:
static IO_Center* getInstance();
~IO_Center();
//string process(string input);
//void run();
void begin();
bool *runAgain;
private:
static bool instanceFlag;
static IO_Center *instance;
IO_Center();
AutoIt_Connector *connector;
Expression *formula;
void initialise();
LatexImageBuilder *builder;
ExpressionList *GUI;
vector<string> *exprResults;
IO_Wait *pendingThread;
QMessageBox* msgBox;
//
void interactWithUser();
void sendGUIHandle();
string getUserInput();
void processInput(string input);
void loadSuggestions();
//string waitForUserChoice();
int getUserChoice();
void sendOutput();
void finish();
public slots:
//void sendOutput();
void trigger();
};
#endif | [
"saroadmelanka@yahoo.com"
] | saroadmelanka@yahoo.com |
1363380dc1239f8a87ba673d306aaf9a8b128044 | b88bf5e0f138e9b20e823f6d01c302879e6155a1 | /CPP/longest_increasing_subsequence.cpp | 6de8eb2b37df9c13106154a6a4bd68d5e1fa407c | [
"MIT"
] | permissive | anshul3pathi/Project-alpha | 4e828ecb27de9fb90baf6c81ab4958d8d8dcfe85 | 54803533c68b9cfcd4a1f17447a092b15c1d929d | refs/heads/main | 2023-01-10T11:58:38.299315 | 2020-10-27T10:55:35 | 2020-10-27T10:55:35 | 307,665,785 | 0 | 0 | MIT | 2020-10-27T10:38:43 | 2020-10-27T10:38:43 | null | UTF-8 | C++ | false | false | 954 | cpp | #include <iostream>
using namespace std;
int main(){
int length; //number of elements
cin >> length;
int value[length]; //array to store value of elements
for(int i=0; i<length; ++i){
cin>>value[i];
}
/*algorithm:
This problem can be solved using Dynamic Programming.
Time complexity of the algorithm will be O(n^2)
Each state of DP will store the longest increasing subsequence
ending at that position
*/
int dp[length];
//initialising dp[i] = 1; since in any case we can have a single element
for(int i=0; i<length; ++i){
dp[i]=1;
}
for(int i=0; i<length; ++i){
for(int j=0; j<i; ++j){
if(value[i]>=value[j]){
dp[i]=max(dp[i], dp[j]+1);
}
}
}
int answer =0; //answer is going to be maximum of all dp[i]
for(int i=0; i<length; ++i){
answer= max(answer, dp[i]);
}
cout<<answer;
} | [
"tanaymodani18@gmail.com"
] | tanaymodani18@gmail.com |
c3fa73b93b16bd36ec0e4c6e08ee92a7d214710e | 6c4bcd1ad86869ee15aab228853060b26ed09e3b | /mailnews/imap/src/nsImapUtils.cpp | aa78a8cf384285debf554d4d06357a41de3e333b | [] | no_license | mxOBS/deb-pkg_icedove | 18b43958d7bfc3529dc7de505ab6d31a08446be1 | 10b6a968583b8d721bedcffc87851c569e2467a3 | refs/heads/master | 2021-01-20T08:24:26.807514 | 2015-05-14T13:56:12 | 2015-05-14T13:56:12 | 35,611,831 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,724 | cpp | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "msgCore.h"
#include "nsImapUtils.h"
#include "nsCOMPtr.h"
#include "nsIServiceManager.h"
#include "prsystem.h"
#include "prprf.h"
#include "nsNetCID.h"
// stuff for temporary root folder hack
#include "nsIMsgAccountManager.h"
#include "nsIMsgIncomingServer.h"
#include "nsIImapIncomingServer.h"
#include "nsMsgBaseCID.h"
#include "nsImapCore.h"
#include "nsMsgUtils.h"
#include "nsImapFlagAndUidState.h"
#include "nsISupportsObsolete.h"
#include "nsIMAPNamespace.h"
#include "nsIImapFlagAndUidState.h"
nsresult
nsImapURI2FullName(const char* rootURI, const char* hostName, const char* uriStr,
char **name)
{
nsAutoCString uri(uriStr);
nsAutoCString fullName;
if (uri.Find(rootURI) != 0)
return NS_ERROR_FAILURE;
fullName = Substring(uri, strlen(rootURI));
uri = fullName;
int32_t hostStart = uri.Find(hostName);
if (hostStart <= 0)
return NS_ERROR_FAILURE;
fullName = Substring(uri, hostStart);
uri = fullName;
int32_t hostEnd = uri.FindChar('/');
if (hostEnd <= 0)
return NS_ERROR_FAILURE;
fullName = Substring(uri, hostEnd + 1);
if (fullName.IsEmpty())
return NS_ERROR_FAILURE;
*name = ToNewCString(fullName);
return NS_OK;
}
/* parses ImapMessageURI */
nsresult nsParseImapMessageURI(const char* uri, nsCString& folderURI, uint32_t *key, char **part)
{
if(!key)
return NS_ERROR_NULL_POINTER;
nsAutoCString uriStr(uri);
int32_t folderEnd = -1;
// imap-message uri's can have imap:// url strings tacked on the end,
// e.g., when opening/saving attachments. We don't want to look for '#'
// in that part of the uri, if the attachment name contains '#',
// so check for that here.
if (StringBeginsWith(uriStr, NS_LITERAL_CSTRING("imap-message")))
folderEnd = uriStr.Find("imap://");
int32_t keySeparator = MsgRFindChar(uriStr, '#', folderEnd);
if(keySeparator != -1)
{
int32_t keyEndSeparator = MsgFindCharInSet(uriStr, "/?&", keySeparator);
nsAutoString folderPath;
folderURI = StringHead(uriStr, keySeparator);
folderURI.Cut(4, 8); // cut out the _message part of imap-message:
// folder uri's don't have fully escaped usernames.
int32_t atPos = folderURI.FindChar('@');
if (atPos != -1)
{
nsCString unescapedName, escapedName;
int32_t userNamePos = folderURI.Find("//") + 2;
uint32_t origUserNameLen = atPos - userNamePos;
if (NS_SUCCEEDED(MsgUnescapeString(Substring(folderURI, userNamePos,
origUserNameLen),
0, unescapedName)))
{
// Re-escape the username, matching the way we do it in uris, not the
// way necko escapes urls. See nsMsgIncomingServer::GetServerURI.
MsgEscapeString(unescapedName, nsINetUtil::ESCAPE_XALPHAS, escapedName);
folderURI.Replace(userNamePos, origUserNameLen, escapedName);
}
}
nsAutoCString keyStr;
if (keyEndSeparator != -1)
keyStr = Substring(uriStr, keySeparator + 1, keyEndSeparator - (keySeparator + 1));
else
keyStr = Substring(uriStr, keySeparator + 1);
*key = strtoul(keyStr.get(), nullptr, 10);
if (part && keyEndSeparator != -1)
{
int32_t partPos = MsgFind(uriStr, "part=", false, keyEndSeparator);
if (partPos != -1)
{
*part = ToNewCString(Substring(uriStr, keyEndSeparator));
}
}
}
return NS_OK;
}
nsresult nsBuildImapMessageURI(const char *baseURI, uint32_t key, nsCString& uri)
{
uri.Append(baseURI);
uri.Append('#');
uri.AppendInt(key);
return NS_OK;
}
nsresult nsCreateImapBaseMessageURI(const nsACString& baseURI, nsCString &baseMessageURI)
{
nsAutoCString tailURI(baseURI);
// chop off imap:/
if (tailURI.Find(kImapRootURI) == 0)
tailURI.Cut(0, PL_strlen(kImapRootURI));
baseMessageURI = kImapMessageRootURI;
baseMessageURI += tailURI;
return NS_OK;
}
// nsImapMailboxSpec definition
NS_IMPL_ISUPPORTS(nsImapMailboxSpec, nsIMailboxSpec)
nsImapMailboxSpec::nsImapMailboxSpec()
{
mFolder_UIDVALIDITY = 0;
mHighestModSeq = 0;
mNumOfMessages = 0;
mNumOfUnseenMessages = 0;
mNumOfRecentMessages = 0;
mNextUID = 0;
mBoxFlags = 0;
mSupportedUserFlags = 0;
mHierarchySeparator = '\0';
mFolderSelected = false;
mDiscoveredFromLsub = false;
mOnlineVerified = false;
mNamespaceForFolder = nullptr;
}
nsImapMailboxSpec::~nsImapMailboxSpec()
{
}
NS_IMPL_GETSET(nsImapMailboxSpec, Folder_UIDVALIDITY, int32_t, mFolder_UIDVALIDITY)
NS_IMPL_GETSET(nsImapMailboxSpec, HighestModSeq, uint64_t, mHighestModSeq)
NS_IMPL_GETSET(nsImapMailboxSpec, NumMessages, int32_t, mNumOfMessages)
NS_IMPL_GETSET(nsImapMailboxSpec, NumUnseenMessages, int32_t, mNumOfUnseenMessages)
NS_IMPL_GETSET(nsImapMailboxSpec, NumRecentMessages, int32_t, mNumOfRecentMessages)
NS_IMPL_GETSET(nsImapMailboxSpec, NextUID, int32_t, mNextUID)
NS_IMPL_GETSET(nsImapMailboxSpec, HierarchyDelimiter, char, mHierarchySeparator)
NS_IMPL_GETSET(nsImapMailboxSpec, FolderSelected, bool, mFolderSelected)
NS_IMPL_GETSET(nsImapMailboxSpec, DiscoveredFromLsub, bool, mDiscoveredFromLsub)
NS_IMPL_GETSET(nsImapMailboxSpec, OnlineVerified, bool, mOnlineVerified)
NS_IMPL_GETSET(nsImapMailboxSpec, SupportedUserFlags, uint32_t, mSupportedUserFlags)
NS_IMPL_GETSET(nsImapMailboxSpec, Box_flags, uint32_t, mBoxFlags)
NS_IMPL_GETSET(nsImapMailboxSpec, NamespaceForFolder, nsIMAPNamespace *, mNamespaceForFolder)
NS_IMETHODIMP nsImapMailboxSpec::GetAllocatedPathName(nsACString &aAllocatedPathName)
{
aAllocatedPathName = mAllocatedPathName;
return NS_OK;
}
NS_IMETHODIMP nsImapMailboxSpec::SetAllocatedPathName(const nsACString &aAllocatedPathName)
{
mAllocatedPathName = aAllocatedPathName;
return NS_OK;
}
NS_IMETHODIMP nsImapMailboxSpec::GetUnicharPathName(nsAString &aUnicharPathName)
{
aUnicharPathName = aUnicharPathName;
return NS_OK;
}
NS_IMETHODIMP nsImapMailboxSpec::SetUnicharPathName(const nsAString &aUnicharPathName)
{
mUnicharPathName = aUnicharPathName;
return NS_OK;
}
NS_IMETHODIMP nsImapMailboxSpec::GetHostName(nsACString &aHostName)
{
aHostName = mHostName;
return NS_OK;
}
NS_IMETHODIMP nsImapMailboxSpec::SetHostName(const nsACString &aHostName)
{
mHostName = aHostName;
return NS_OK;
}
NS_IMETHODIMP nsImapMailboxSpec::GetFlagState(nsIImapFlagAndUidState ** aFlagState)
{
NS_ENSURE_ARG_POINTER(aFlagState);
NS_IF_ADDREF(*aFlagState = mFlagState);
return NS_OK;
}
NS_IMETHODIMP nsImapMailboxSpec::SetFlagState(nsIImapFlagAndUidState * aFlagState)
{
NS_ENSURE_ARG_POINTER(aFlagState);
mFlagState = aFlagState;
return NS_OK;
}
nsImapMailboxSpec& nsImapMailboxSpec::operator= (const nsImapMailboxSpec& aCopy)
{
mFolder_UIDVALIDITY = aCopy.mFolder_UIDVALIDITY;
mHighestModSeq = aCopy.mHighestModSeq;
mNumOfMessages = aCopy.mNumOfMessages;
mNumOfUnseenMessages = aCopy.mNumOfUnseenMessages;
mNumOfRecentMessages = aCopy.mNumOfRecentMessages;
mBoxFlags = aCopy.mBoxFlags;
mSupportedUserFlags = aCopy.mSupportedUserFlags;
mAllocatedPathName.Assign(aCopy.mAllocatedPathName);
mUnicharPathName.Assign(aCopy.mUnicharPathName);
mHierarchySeparator = mHierarchySeparator;
mHostName.Assign(aCopy.mHostName);
mFlagState = aCopy.mFlagState;
mNamespaceForFolder = aCopy.mNamespaceForFolder;
mFolderSelected = aCopy.mFolderSelected;
mDiscoveredFromLsub = aCopy.mDiscoveredFromLsub;
mOnlineVerified = aCopy.mOnlineVerified;
return *this;
}
// use the flagState to determine if the gaps in the msgUids correspond to gaps in the mailbox,
// in which case we can still use ranges. If flagState is null, we won't do this.
void AllocateImapUidString(uint32_t *msgUids, uint32_t &msgCount,
nsImapFlagAndUidState *flagState, nsCString &returnString)
{
uint32_t startSequence = (msgCount > 0) ? msgUids[0] : 0xFFFFFFFF;
uint32_t curSequenceEnd = startSequence;
uint32_t total = msgCount;
int32_t curFlagStateIndex = -1;
// a partial fetch flag state doesn't help us, so don't use it.
if (flagState && flagState->GetPartialUIDFetch())
flagState = nullptr;
for (uint32_t keyIndex = 0; keyIndex < total; keyIndex++)
{
uint32_t curKey = msgUids[keyIndex];
uint32_t nextKey = (keyIndex + 1 < total) ? msgUids[keyIndex + 1] : 0xFFFFFFFF;
bool lastKey = (nextKey == 0xFFFFFFFF);
if (lastKey)
curSequenceEnd = curKey;
if (!lastKey)
{
if (nextKey == curSequenceEnd + 1)
{
curSequenceEnd = nextKey;
curFlagStateIndex++;
continue;
}
if (flagState)
{
if (curFlagStateIndex == -1)
{
bool foundIt;
flagState->GetMessageFlagsFromUID(curSequenceEnd, &foundIt, &curFlagStateIndex);
if (!foundIt)
{
NS_WARNING("flag state missing key");
// The start of this sequence is missing from flag state, so move
// on to the next key.
curFlagStateIndex = -1;
curSequenceEnd = startSequence = nextKey;
continue;
}
}
curFlagStateIndex++;
uint32_t nextUidInFlagState;
nsresult rv = flagState->GetUidOfMessage(curFlagStateIndex, &nextUidInFlagState);
if (NS_SUCCEEDED(rv) && nextUidInFlagState == nextKey)
{
curSequenceEnd = nextKey;
continue;
}
}
}
if (curSequenceEnd > startSequence)
{
returnString.AppendInt((int64_t) startSequence);
returnString += ':';
returnString.AppendInt((int64_t) curSequenceEnd);
startSequence = nextKey;
curSequenceEnd = startSequence;
curFlagStateIndex = -1;
}
else
{
startSequence = nextKey;
curSequenceEnd = startSequence;
returnString.AppendInt((int64_t) msgUids[keyIndex]);
curFlagStateIndex = -1;
}
// check if we've generated too long a string - if there's no flag state,
// it means we just need to go ahead and generate a too long string
// because the calling code won't handle breaking up the strings.
if (flagState && returnString.Length() > 950)
{
msgCount = keyIndex;
break;
}
// If we are not the last item then we need to add the comma
// but it's important we do it here, after the length check
if (!lastKey)
returnString += ',';
}
}
void ParseUidString(const char *uidString, nsTArray<nsMsgKey> &keys)
{
// This is in the form <id>,<id>, or <id1>:<id2>
char curChar = *uidString;
bool isRange = false;
uint32_t curToken;
uint32_t saveStartToken = 0;
for (const char *curCharPtr = uidString; curChar && *curCharPtr;)
{
const char *currentKeyToken = curCharPtr;
curChar = *curCharPtr;
while (curChar != ':' && curChar != ',' && curChar != '\0')
curChar = *curCharPtr++;
// we don't need to null terminate currentKeyToken because strtoul
// stops at non-numeric chars.
curToken = strtoul(currentKeyToken, nullptr, 10);
if (isRange)
{
while (saveStartToken < curToken)
keys.AppendElement(saveStartToken++);
}
keys.AppendElement(curToken);
isRange = (curChar == ':');
if (isRange)
saveStartToken = curToken + 1;
}
}
void AppendUid(nsCString &msgIds, uint32_t uid)
{
char buf[20];
PR_snprintf(buf, sizeof(buf), "%u", uid);
msgIds.Append(buf);
}
| [
"privacy@not.given"
] | privacy@not.given |
08e75e11d56f187928bba7e42e33ff51a9bb8a29 | e215ac34daff0eda58d978ee097db6c77dcf592e | /menuEngine.h | 6fb21398528f1ed72ff4424db05c43ede8a19ca0 | [] | no_license | nguditis/Mario-Kart | f9dc8227a89127cd6a993178ca06277df03de0a5 | a15060c224759811f62f60b77ecb67d685dc8825 | refs/heads/master | 2020-04-06T11:14:35.640969 | 2018-12-12T22:32:56 | 2018-12-12T22:32:56 | 157,409,285 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 556 | h | #ifndef MENU_ENGINE_H
#define MENU_ENGINE_H
#include <vector>
#include <SDL.h>
#include "menu.h"
class MenuEngine {
public:
MenuEngine ();
~MenuEngine ();
void play();
int getOptionChoice() const { return optionChoice; }
int getTrackNumber() const {return track;}
void setTrack(int track) {track = track;};
private:
Clock& clock;
SDL_Renderer * const renderer;
Menu menu;
int optionChoice;
int track;
void draw() const;
void update(Uint32);
MenuEngine(const MenuEngine&);
MenuEngine& operator=(const MenuEngine&);
};
#endif | [
"nguditis@icloud.com"
] | nguditis@icloud.com |
2c51b5d79b5de45f874c42f15559982bd6d7933b | e979844d55c1ef0313d9eb6703e48defbcd29aa1 | /Terabit/tests/P2_Test/Session.cpp | 84e7b3d0cda9bfdd28b6ade5bdb3b8fe01e955f4 | [] | no_license | sue602/Terabit4ACE6.x | cfb365d816b77fdf43836d76fa36dcf854da7005 | 1b1366fc1ae9fd7c42b69f151ece9d1d858ed66f | refs/heads/master | 2021-01-01T06:15:04.594124 | 2017-07-16T15:55:19 | 2017-07-16T15:55:19 | 97,391,901 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 16,737 | cpp | /*********************************************************************
** Copyright (C) 2003 Terabit Pty Ltd. All rights reserved.
**
** This file is part of the POSIX-Proactor module.
**
**
**
**
**
**
**
**
**********************************************************************/
// ============================================================================
/**
* @file Session.cpp
*
*
* @author Alexander Libman <libman@terabit.com.au>
*/
// ============================================================================
#include "test_config.h"
#include "P2_Test.h"
#include "ace/Flag_Manip.h" //add by vincent 170610
// *************************************************************
// Session
// *************************************************************
Session::Session (Bridge * bridge)
: bridge_ (bridge),
rs_ (),
ws_ (),
handle_ (ACE_INVALID_HANDLE),
total_snd_(0),
total_rcv_(0),
total_w_ (0),
total_r_ (0),
ref_cnt_w_(0),
ref_cnt_r_(0),
flags_ (0)
{
ACE_ASSERT (this->bridge_ != 0);
}
Session::~Session (void)
{
this->close ();
}
void
Session::close ()
{
if (this->handle_ != ACE_INVALID_HANDLE)
ACE_OS::closesocket (this->handle_);
this->handle_= ACE_INVALID_HANDLE;
}
void
Session::cancel ()
{
this->ws_.cancel ();
this->rs_.cancel ();
#if defined(ACE_WIN32)
this->close();
#endif
return;
}
int
Session::index (void) const
{
return this->bridge ()->index ();
}
int
Session::is_open(void) const
{
return ((this->flags_ & SSN_OPEN) != 0);
}
void
Session::addresses (const ACE_Addr& peer, const ACE_Addr& local)
{
ACE_TCHAR str_peer [256];
ACE_TCHAR str_local[256];
TRB_Sock_Addr::to_string (peer, str_peer, sizeof (str_peer)/sizeof (ACE_TCHAR));
TRB_Sock_Addr::to_string (local, str_local, sizeof (str_local)/sizeof (ACE_TCHAR));
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("(%t) %s=%d Remote=%s Local=%s\n"),
this->get_name(),
this->index(),
str_peer,
str_local));
}
void
Session::open (ACE_HANDLE handle, ACE_Message_Block & mb)
{
ACE_UNUSED_ARG(mb);
{
ACE_GUARD (ACE_SYNCH_MUTEX, monitor, this->bridge_->mutex());
this->open_streams (handle);
if (bridge_->check_ref () != 0)
return;
}
this->bridge_->try_destroy ();
}
int
Session::open_streams (ACE_HANDLE handle)
{
this->handle_ = handle;
if (this->handle_ == ACE_INVALID_HANDLE)
return -1;
TRB_Proactor * proactor = this->bridge ()->acceptor ().proactor();
if (this->ws_.open (*this,
this->handle_,
0, // completion key,
proactor) == -1)
ACE_ERROR_RETURN ((LM_ERROR,
ACE_TEXT ("(%t) %s=%d %p\n"),
this->get_name(),
this->index(),
ACE_TEXT (" TRB_Asynch_Write_Stream::open")),
-1);
if (this->rs_.open (*this,
this->handle_,
0, // completion key,
proactor) == -1)
ACE_ERROR_RETURN ((LM_ERROR,
ACE_TEXT ("(%t) %s=%d %p\n"),
this->get_name(),
this->index(),
ACE_TEXT (" TRB_Asynch_Read_Stream::open")),
-1);
this->flags_ |= SSN_OPEN;
return this->on_open();
}
int
Session::initiate_read_stream (void)
{
if (this->bridge_->should_finish() ||
(this->flags_ & SSN_RCV_CLOSED) ||
this->handle_ == ACE_INVALID_HANDLE)
return -1;
ACE_Message_Block *mb = 0;
size_t r_blksize = this->bridge_->acceptor().task().config().r_blksize();
int loglevel = this->bridge_->acceptor().task().config().loglevel ();
ACE_NEW_RETURN (mb,
ACE_Message_Block (r_blksize+1),
-1);
if (loglevel <= 1)
{
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("(%t) %s=%d Initiate READ %u bytes\n"),
this->get_name (),
this->index (),
(u_int) r_blksize ));
}
// Inititiate read
if (this->rs_.read (*mb, r_blksize) == -1)
{
mb->release ();
ACE_ERROR_RETURN((LM_ERROR,
ACE_TEXT ("(%t) %s=%d attempt read failed\n"),
this->get_name(),
this->index()),
-1);
}
this->ref_cnt_r_++;
this->total_r_++;
return 0;
}
int
Session::initiate_write_stream (ACE_Message_Block &mb, size_t nbytes)
{
int loglevel = this->bridge_->acceptor().task().config().loglevel ();
int mb_type = mb.msg_type ();
if (this->bridge_->should_finish() ||
(this->flags_ & SSN_SND_CLOSED) ||
this->handle_ == ACE_INVALID_HANDLE)
{
mb.release ();
return -1;
}
if (nbytes == 0 ||
mb_type == ACE_Message_Block::MB_HANGUP ||
mb_type == ACE_Message_Block::MB_ERROR)
{
ACE_OS::shutdown (this->handle_, ACE_SHUTDOWN_WRITE);
this->flags_ |= SSN_SND_CLOSED;
mb.release ();
return -1;
//this->cancel ();
//ACE_ERROR_RETURN((LM_ERROR,
// ACE_TEXT ("(%t) %s=%d attempt write 0 bytes\n"),
// this->get_name(),
// this->index()),
// -1);
}
if (loglevel <= 1)
{
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("(%t) %s=%d Initiate WRITE %u bytes\n"),
this->get_name (),
this->index (),
(u_int) nbytes ));
}
if (this->ws_.write (mb, nbytes) == -1)
{
mb.release ();
ACE_ERROR_RETURN((LM_ERROR,
ACE_TEXT ("(%t) %s=%d attempt write failed\n"),
this->get_name(),
this->index()),
-1);
}
this->ref_cnt_w_++;
this->total_w_++;
return 0;
}
void
Session::handle_read_stream (const TRB_Asynch_Read_Stream::Result &result)
{
{
ACE_GUARD (ACE_SYNCH_MUTEX, monitor, this->bridge_->mutex());
int loglevel = this->bridge_->acceptor().task().config().loglevel ();
--this->ref_cnt_r_;
ACE_Message_Block & mb = result.message_block ();
// Reset pointers.
mb.rd_ptr ()[result.bytes_transferred ()] = '\0';
if (loglevel == 0)
{
LogLocker log_lock;
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("(%t) **** %s=%d handle_read_stream() ****\n"),
this->get_name(),
this->index()));
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("%s = %d\n"),
ACE_TEXT ("bytes_to_read"),
result.bytes_to_read ()));
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("%s = %d\n"),
ACE_TEXT ("handle"),
result.handle ()));
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("%s = %d\n"),
ACE_TEXT ("bytes_transfered"),
result.bytes_transferred ()));
/*
-------------------------------------------
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("%s = %@\n"),
ACE_TEXT ("act"),
result.act ()));
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("%s = %d\n"),
ACE_TEXT ("success"),
result.success ()));
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("%s = %@\n"),
ACE_TEXT ("completion_key"),
result.completion_key ()));
-------------------------------------------
*/
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("%s = %d\n"),
ACE_TEXT ("error"),
result.error ()));
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("%s = %s\n"),
ACE_TEXT ("message_block"),
mb.rd_ptr ()));
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("**** end of message ****************\n")));
}
else if (result.error () != 0)
{
LogLocker log_lock;
ACE_Log_Msg::instance ()->errnum (result.error ());
ACE_Log_Msg::instance ()->log (LM_ERROR,
ACE_TEXT ("(%t) %s=%d ERROR %p\n"),
this->get_name (),
this->index (),
ACE_TEXT ("read"));
}
else if ( loglevel ==1 )
{
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("(%t) %s=%d read=%d bytes ok\n"),
this->get_name (),
this->index (),
result.bytes_transferred ()));
}
if (result.error () == 0 && result.bytes_transferred () > 0)
{
this->total_rcv_ += result.bytes_transferred ();
}
else
{
this->flags_ |= SSN_RCV_CLOSED;
mb.msg_type (ACE_Message_Block::MB_HANGUP);
mb.wr_ptr (mb.rd_ptr());
}
this->on_data_received (mb);
if (bridge_->check_ref () != 0)
return;
}
this->bridge_->try_destroy ();
}
void
Session::handle_write_stream (const TRB_Asynch_Write_Stream::Result &result)
{
{
ACE_GUARD (ACE_SYNCH_MUTEX, monitor, this->bridge_->mutex());
int loglevel = this->bridge_->acceptor().task().config().loglevel ();
--this->ref_cnt_w_;
ACE_Message_Block & mb = result.message_block ();
if (loglevel == 0)
{
LogLocker log_lock;
//mb.rd_ptr () [0] = '\0';
mb.rd_ptr (mb.rd_ptr () - result.bytes_transferred ());
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("(%t) **** %s=%d handle_write_stream() ****\n"),
this->get_name(),
this->index()));
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("%s = %d\n"),
ACE_TEXT ("bytes_to_write"),
result.bytes_to_write ()));
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("%s = %d\n"),
ACE_TEXT ("handle"),
result.handle ()));
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("%s = %d\n"),
ACE_TEXT ("bytes_transfered"),
result.bytes_transferred ()));
/*
-------------------------------------------
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("%s = %@\n"),
ACE_TEXT ("act"),
result.act ()));
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("%s = %d\n"),
ACE_TEXT ("success"),
result.success ()));
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("%s = %@\n"),
ACE_TEXT ("completion_key"),
result.completion_key ()));
-------------------------------------------
*/
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("%s = %d\n"),
ACE_TEXT ("error"),
result.error ()));
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("%s = %s\n"),
ACE_TEXT ("message_block"),
mb.rd_ptr ()));
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("**** end of message ****************\n")));
}
else if (result.error () != 0)
{
LogLocker log_lock;
ACE_Log_Msg::instance ()->errnum (result.error ());
ACE_Log_Msg::instance ()->log (LM_ERROR,
ACE_TEXT ("(%t) %s=%d ERROR %p\n"),
this->get_name (),
this->index (),
ACE_TEXT ("write"));
}
else if ( loglevel ==1 )
{
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("(%t) %s=%d write=%d bytes ok\n"),
this->get_name (),
this->index (),
result.bytes_transferred ()));
}
if (result.error () == 0 && result.bytes_transferred () > 0)
{
this->total_snd_ += result.bytes_transferred ();
}
else
{
mb.msg_type (ACE_Message_Block::MB_ERROR);
mb.wr_ptr (mb.rd_ptr());
}
this->on_data_sent (mb);
if (bridge_->check_ref () != 0)
return;
}
this->bridge_->try_destroy ();
}
// *********************************************************
// Receiver
// *********************************************************
Receiver::Receiver (Bridge * bridge)
: Session (bridge)
{
}
Receiver::~Receiver (void)
{
if (this->get_ref_cnt () != 0)
ACE_ERROR ((LM_WARNING,
ACE_TEXT ("(%t) %s=%d deleted with pending ")
ACE_TEXT ("W=%d R=%d\n"),
this->get_name (),
this->index (),
this->get_ref_cnt_w (),
this->get_ref_cnt_r ()));
this->close();
}
const ACE_TCHAR *
Receiver::get_name (void) const
{
return ACE_TEXT("RCVR");
}
int
Receiver::on_open (void)
{
//int num = 1+(w_size/r_blksize);
//for (; num > 0; --num)
//this->initiate_read_stream ();
//return 0;
//this->bridge ()->on_data_sent (&mb, Bridge::Q_S2R);
this->bridge ()->on_data_received (0, Bridge::Q_R2S);
return 0;
}
int
Receiver::on_data_received(ACE_Message_Block & mb)
{
return this->bridge ()->on_data_received (&mb, Bridge::Q_R2S);
}
int
Receiver::on_data_sent(ACE_Message_Block & mb)
{
return this->bridge ()->on_data_sent (&mb, Bridge::Q_S2R);
}
// *********************************************************
// Sender
// *********************************************************
Sender::Sender (Bridge * bridge)
: Session (bridge)
{
;
}
Sender::~Sender (void)
{
if (this->get_ref_cnt () != 0)
ACE_ERROR ((LM_WARNING,
ACE_TEXT ("(%t) %s=%d deleted with pending ")
ACE_TEXT ("W=%d R=%d\n"),
this->get_name (),
this->index (),
this->get_ref_cnt_w (),
this->get_ref_cnt_r ()));
this->close();
}
const ACE_TCHAR *
Sender::get_name (void) const
{
return ACE_TEXT("SNDR");
}
int
Sender::on_open (void)
{
//int num = 1+(w_size/r_blksize);
//for (; num > 0; --num)
//this->initiate_read_stream ();
this->bridge ()->on_data_received (0, Bridge::Q_S2R);
this->bridge ()->on_data_sent (0, Bridge::Q_R2S);
return 0;
}
int
Sender::on_data_received(ACE_Message_Block & mb)
{
return this->bridge ()->on_data_received (&mb, Bridge::Q_S2R);
}
int
Sender::on_data_sent(ACE_Message_Block & mb)
{
return this->bridge ()->on_data_sent (&mb, Bridge::Q_R2S);
}
int
Sender::connect(const ACE_Addr & addr)
{
ACE_ASSERT(this->handle_ == ACE_INVALID_HANDLE);
TRB_Proactor * proactor = this->bridge ()->acceptor ().proactor();
if (this->bridge_->should_finish ())
return -1;
if (this->asynch_connect_.open (*this, // handler
ACE_INVALID_HANDLE, //handle
0, // completion key
proactor) == -1)
ACE_ERROR_RETURN
((LM_ERROR,
ACE_TEXT ("(%t) %s=%d %p\n"),
this->get_name(),
this->index(),
ACE_TEXT (" TRB_Asynch_Connect::open")),
-1);
if (this->asynch_connect_.connect
(ACE_INVALID_HANDLE,
addr, // remote sap
ACE_Addr::sap_any, // local sap
1, // reuse addr
0) != 0) // act
ACE_ERROR_RETURN
((LM_ERROR,
ACE_TEXT ("(%t) %s=%d %p\n"),
this->get_name(),
this->index(),
ACE_TEXT (" TRB_Asynch_Connect::open")),
-1);
++this->ref_cnt_w_;
return 0;
}
void
Sender::handle_connect (const TRB_Asynch_Connect::Result &result)
{
{
ACE_GUARD (ACE_SYNCH_MUTEX, monitor, this->bridge_->mutex());
--this->ref_cnt_w_;
ACE_HANDLE handle = result.connect_handle();
if (handle != ACE_INVALID_HANDLE)
{
ACE::clr_flags (handle, ACE_NONBLOCK);
this->parse_address(result);
}
this->open_streams(handle);
if (this->bridge_->check_ref () != 0)
return;
}
this->bridge_->try_destroy ();
}
void
Sender::parse_address (const TRB_Asynch_Connect::Result &result)
{
const ACE_Addr& remote_address = result.remote_address ();
const ACE_Addr& local_address = result.local_address ();
this->addresses(remote_address, local_address);
}
| [
"suyinxiang@onemt.com.cn"
] | suyinxiang@onemt.com.cn |
213ee6d131fe02a9b461df0f6b5a4722a49f3df2 | 848ef045c5d0911737cb1f82e202916a46c84844 | /COffer/2_6_bitree.cpp | 8725560e8f934b0f221ae99d37c93e6c4d3c3150 | [] | no_license | flydom/funcode | cd41cdc01a617b018fedfd5a1e620760a4aeb066 | c9cb3b5ca8eca629ded34a9689d959498179b525 | refs/heads/master | 2021-01-16T19:32:04.637889 | 2018-08-12T14:01:22 | 2018-08-12T14:01:22 | 28,263,701 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,811 | cpp |
BinaryTreeNode* BuildCore(int *startPreorder, int *endPreorder,
int *startInorder, int *endInorder)
{
int rootValue = startPreorder[0];
// 构建树或子树的根节点
BinaryTreeNode *root = new BinaryTreeNode();
if (root == NULL)
{
return NULL;
}
root->m_nValue = rootValue;
root->m_pLeft = root->m_pRight = NULL;
// 只有一个节点
if (startPreorder == endPreorder)
{
if (startInorder == endInorder && *startPreorder == *startInorder)
{
return root;
}
else
{
printf("Invalid input.!\n");
return NULL;
}
}
// 到中序序列中找根节点
int *rootInorder = startInorder;
while (rootInorder <= endInorder && *rootInorder != rootValue)
{
rootInorder++;
}
if (rootInorder > endInorder)
{
printf("Invalid input.!\n");
return NULL;
}
// 递归构建中序遍历根节点中的左右子树
int leftLength = rootInorder - startInorder;
int *leftPreorderEnd = startPreorder + leftLength;
if (leftLength > 0)
{
root->m_pLeft = BuildCore(startPreorder + 1, leftPreorderEnd,
startInorder, rootInorder - 1);
}
if (leftLength < endPreorder - startPreorder)
{
root->m_pRight = BuildCore(leftPreorderEnd + 1, endPreorder,
rootInorder + 1, endInorder);
}
return root;
}
BinaryTreeNode* BuildBiTree(int *preorder, int *inorder, int length)
{
if (preorder == NULL || inorder == NULL || length <= 0)
{
return NULL;
}
return BuildCore(preorder, preorder + length - 1,
inorder, preorder + length - 1);
}
| [
"fzy0201k@gmail.com"
] | fzy0201k@gmail.com |
bd17106de54c85256ef0390f2d6cdc749fd19776 | e26442d07aa93d7beb8376d4bdfdd803c145ba52 | /implement/multicam-win-6.7.0.102256-sampleprograms/Samples/MsVc/DominoSnapshotTrigger/StdAfx.cpp | bdb526903bcdbef5cd1a4ef1e2e937bd356b1043 | [] | no_license | Shelro/bracesEraser | c19c10d2cfca36c8c97695f505dc0f5ada77db6e | 23331c780f601e921c4d51b2adae57280945a1d3 | refs/heads/master | 2020-12-30T12:23:15.132672 | 2017-06-25T06:44:38 | 2017-06-25T06:44:38 | 91,428,927 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 221 | cpp | // stdafx.cpp : source file that includes just the standard includes
// DominoSnapshotTrigger.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| [
"inyi13zyy@gmail.com"
] | inyi13zyy@gmail.com |
925dd9d299374e9815b1b11123792f3d92cfe47c | 1786f51414ac5919b4a80c7858e11f7eb12cb1a9 | /POJ1179.cpp | 09ad3caf987fef8a048d461a3836bbffb62e9cfd | [] | no_license | SetsunaChyan/OI_source_code | 206c4d7a0d2587a4d09beeeb185765bca0948f27 | bb484131e02467cdccd6456ea1ecb17a72f6e3f6 | refs/heads/master | 2020-04-06T21:42:44.429553 | 2019-12-02T09:18:54 | 2019-12-02T09:18:54 | 157,811,588 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,282 | cpp | #include <cstdio>
#include <memory.h>
#include <algorithm>
using namespace std;
const int INF=0x3f3f3f3f;
int n,f[110][110][2],maxn=-INF;
struct node
{
int val;
char opt;
}e[110];
inline int max(int a,int b){return a>b?a:b;}
inline int min(int a,int b){return a<b?a:b;}
int main()
{
scanf("%d",&n);
scanf(" %c",&e[n].opt);e[2*n].opt=e[n].opt;
for(int i=1;i<n;i++)
{
scanf("%d %c",&e[i].val,&e[i].opt);
e[i+n].val=e[i].val;
e[i+n].opt=e[i].opt;
f[i][i][0]=f[i+n][i+n][0]=f[i][i][1]=f[i+n][i+n][1]=e[i].val;
}
scanf("%d",&e[n].val);e[2*n].val=e[n].val;
f[n][n][0]=f[2*n][2*n][0]=f[n][n][1]=f[2*n][2*n][1]=e[n].val;
for(int len=2;len<=n;len++)
for(int l=1;l<=2*n-len+1;l++)
{
int r=l+len-1;
f[l][r][0]=INF;f[l][r][1]=-INF;
for(int k=l;k<r;k++)
if(e[k].opt=='t')
{
f[l][r][0]=min(f[l][k][0]+f[k+1][r][0],f[l][r][0]);
f[l][r][1]=max(f[l][k][1]+f[k+1][r][1],f[l][r][1]);
}
else
for(int x=0;x<=1;x++)
for(int y=0;y<=1;y++)
{
int z=f[l][k][x]*f[k+1][r][y];
f[l][r][0]=min(z,f[l][r][0]);
f[l][r][1]=max(z,f[l][r][1]);
}
}
for(int i=1;i<=n;i++)
maxn=max(maxn,f[i][i+n-1][1]);
printf("%d\n",maxn);
for(int i=1;i<=n;i++)
if(f[i][i+n-1][1]==maxn)
printf("%d ",i);
return 0;
} | [
"ctzguozi@163.com"
] | ctzguozi@163.com |
89f91fe9d396f1c3474db31e0429ba4c3234c5ae | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /cynosdb/src/v20190107/model/DescribeClusterPasswordComplexityRequest.cpp | b7a8e8a7672d55d5952e028d04b7333e90c786d3 | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp | 9f5df8220eaaf72f7eaee07b2ede94f89313651f | 42a76b812b81d1b52ec6a217fafc8faa135e06ca | refs/heads/master | 2023-08-30T03:22:45.269556 | 2023-08-30T00:45:39 | 2023-08-30T00:45:39 | 188,991,963 | 55 | 37 | Apache-2.0 | 2023-08-17T03:13:20 | 2019-05-28T08:56:08 | C++ | UTF-8 | C++ | false | false | 2,107 | cpp | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/cynosdb/v20190107/model/DescribeClusterPasswordComplexityRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Cynosdb::V20190107::Model;
using namespace std;
DescribeClusterPasswordComplexityRequest::DescribeClusterPasswordComplexityRequest() :
m_clusterIdHasBeenSet(false)
{
}
string DescribeClusterPasswordComplexityRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
if (m_clusterIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ClusterId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_clusterId.c_str(), allocator).Move(), allocator);
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
string DescribeClusterPasswordComplexityRequest::GetClusterId() const
{
return m_clusterId;
}
void DescribeClusterPasswordComplexityRequest::SetClusterId(const string& _clusterId)
{
m_clusterId = _clusterId;
m_clusterIdHasBeenSet = true;
}
bool DescribeClusterPasswordComplexityRequest::ClusterIdHasBeenSet() const
{
return m_clusterIdHasBeenSet;
}
| [
"tencentcloudapi@tencent.com"
] | tencentcloudapi@tencent.com |
4298c8c146de60fb90e024a6db9fba842f4eba82 | e3550d1f2cc802b38c7a8e7da56cb068bf85e57b | /DataStructures/RAPTOR/Entities/ArrivalLabel.h | 67a2564e81b3bb324bcca8227d6b3c3584f403d3 | [
"MIT"
] | permissive | kit-algo/ULTRA-Trip-Based | 6c98006ab8004c9f43999e7fc0e904ed9058bbad | 855f79f1cef89a5aa184700e6761edd9e0800f38 | refs/heads/master | 2022-05-06T08:57:42.036045 | 2022-03-16T15:58:25 | 2022-03-16T15:58:25 | 276,053,058 | 6 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 2,300 | h | /**********************************************************************************
Copyright (c) 2020 Jonas Sauer
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**********************************************************************************/
#pragma once
#include <iostream>
#include <vector>
#include <string>
namespace RAPTOR {
class ArrivalLabel {
public:
ArrivalLabel(const int arrivalTime = never, const size_t numberOfTrips = -1) :
arrivalTime(arrivalTime),
numberOfTrips(numberOfTrips) {
}
inline bool operator<(const ArrivalLabel& other) const noexcept {
return (arrivalTime < other.arrivalTime) || ((arrivalTime == other.arrivalTime) && (numberOfTrips < other.numberOfTrips));
}
inline bool operator==(const ArrivalLabel& other) const noexcept {
return (arrivalTime == other.arrivalTime) && (numberOfTrips == other.numberOfTrips);
}
inline bool operator!=(const ArrivalLabel& other) const noexcept {
return !(*this == other);
}
inline friend std::ostream& operator<<(std::ostream& out, const ArrivalLabel& label) noexcept {
return out << "arrivalTime: " << label.arrivalTime << ", numberOfTrips: " << label.numberOfTrips;
}
public:
int arrivalTime;
size_t numberOfTrips;
};
}
| [
"zuendorf@kit.edu"
] | zuendorf@kit.edu |
6ccd2ed54e0829baf5224dc30a2c43669fb0701f | 5bb5b8b94a081c5312ed94a0e26e649d7b844f7b | /Region.cpp | ce5f64939ffc4bbb46824011ceee29ad2553e37f | [] | no_license | N1kla3/administration-devision | acf9f36f47368c4905c691756b90f4995126a08b | 24dea744d2c1be0179505a0c383294c6c4f438b3 | refs/heads/master | 2020-08-18T13:07:05.402489 | 2019-10-17T09:52:40 | 2019-10-17T09:52:40 | 215,792,555 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 613 | cpp | //
// Created by Kolya on 9/29/2019.
//
#include "Region.h"
Region::Region(std::vector<District> &distr, City* cap, std::string nameOb):capital(cap), districts(distr), name(nameOb){
}
unsigned int Region::getPopulation() {
unsigned int result = 0;
for(auto & iter : districts){
result += iter.getPopulation();
}
result += capital->getPopulation();
return result;
}
unsigned int Region::getAllAdminPoints() {
unsigned int result = 0;
for(auto & iter : districts){
result += iter.getAllAdminPoints();
}
result += capital->getAdminPoint();
return result;
} | [
"kolya.vladimirsky@gmail.com"
] | kolya.vladimirsky@gmail.com |
0f057369175f35f38d2fb9cb2c15f248f626874b | 8fe29627b31630fef4f7b696a9c1e6cf442e1aeb | /PD_shape/scripts/common/laplacian/meshlp/tmesh.cpp | 740ea817a96a06b6c35bfe29c626d973c741fe1c | [] | no_license | ChunyuanLI/Persistence_Diagram | 5b1e8c4b379c1e4e878048abe0f84ee534e6600c | cb5ac8506424cd841feb6bea9a64cb9128d47dc4 | refs/heads/master | 2021-01-21T10:34:19.447413 | 2018-10-23T00:11:45 | 2018-10-23T00:11:45 | 83,454,742 | 6 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 20,642 | cpp | #include <math.h>
#include <queue>
#include <fstream>
#include "tmesh.h"
#include "offobj.h"
typedef unsigned int uint;
double __partcolorgrtable[31][3] = {
{0, 0, 1},
{0, 0.0625, 0.9375},
{0, 0.1250, 0.8750},
{0, 0.1875, 0.8125},
{0, 0.2500, 0.7500},
{0, 0.3125, 0.6875},
{0, 0.3750, 0.6250},
{0, 0.4375, 0.5625},
{0, 0.5625, 0.4375},
{0, 0.6250, 0.3750},
{0, 0.6875, 0.3125},
{0, 0.7500, 0.2500},
{0, 0.8125, 0.1875},
{0, 0.8750, 0.1250},
{0, 0.9375, 0.0625},
{0, 1, 0},
{0.0625, 0.9375, 0},
{0.1250, 0.8750, 0},
{0.1875, 0.8125, 0},
{0.2500, 0.7500, 0},
{0.3125, 0.6875, 0},
{0.3750, 0.6250, 0},
{0.4375, 0.5625, 0},
{0.5625, 0.4375, 0},
{0.6250, 0.3750, 0},
{0.6875, 0.3125, 0},
{0.7500, 0.2500, 0},
{0.8125, 0.1875, 0},
{0.8750, 0.1250, 0},
{0.9375, 0.0625, 0},
{1, 0, 0}
};
void get_color(double v, double minv, double maxv, double c[3])
{
double scale = 0.8;
/*
//---------------------------------------------------------------------------------------
//all warm to cold
double nnv = maxv - minv;
int minc = 0, maxc = 63;
double vs = (v - minv) / nnv * (maxc - minc + 1);
int i = (int)(vs);
for(int j = 0; j < 3; j ++)
c[j] = scale * ((vs - i) * (__colortable[i + 1][j] - __colortable[i][j]) + __colortable[i][j]);
// cout<<"c: "<<c[0]<<" "<<c[1]<<" "<<c[2]<<endl;
//---------------------------------------------------------------------------------------
*/
//maxv = 2.5;
//minv = 1;
double nnv = maxv - minv;
if(fabs(nnv) < MYNZERO){
for(int j = 0; j < 3; j ++)
c[j] = scale * __partcolorgrtable[15][j];
return;
}
//---------------------------------------------------------------------------------------
//warm to cold
int minc = 0, maxc = 30;
if(v <= minv){
for(int j = 0; j < 3; j ++)
c[j] = scale * __partcolorgrtable[minc][j];
return;
}
if(v >= maxv){
for(int j = 0; j < 3; j ++)
c[j] = scale * __partcolorgrtable[maxc][j];
return;
}
double vs = (v - minv) / nnv * (maxc - minc);
int i = (int)(vs);
for(int j = 0; j < 3; j ++)
c[j] = scale * ((vs - i) * (__partcolorgrtable[i + 1][j] - __partcolorgrtable[i][j]) + __partcolorgrtable[i][j]);
// cout<<"c: "<<c[0]<<" "<<c[1]<<" "<<c[2]<<endl;
//---------------------------------------------------------------------------------------
/*
//---------------------------------------------------------------------------------------
//grey scale
double maxc = 0, minc = 0.5;
if(v <= minv) { c[0] = c[1] = c[2] = minc; return; }
if(v >= maxv) { c[0] = c[1] = c[2] = maxc; return; }
double t = (v - 1) / nnv;
c[0] = c[1] = c[2] = minc + (maxc - minc) * t;
//---------------------------------------------------------------------------------------
*/
}
bool TMesh::ReadOffFile(char *filename)
{
string str(filename);
OffFileReader reader(str);
if(reader.bad)
return false;
OffObj obj;
if( reader.get_next_off_object(obj) ){
for(unsigned int i = 0; i < obj.vertices.size(); i ++){
add_vertex( VTMesh( obj.vertices[i].x, obj.vertices[i].y, obj.vertices[i].z) );
}
for(unsigned int i = 0; i < obj.facets.size(); i ++){
if(obj.facets[i].size() != 3){
cerr<<"Error: invalid triangle mesh."<<endl;
return false;
}
unsigned int fid = add_facet( FTMesh( (obj.facets[i])[0], (obj.facets[i])[1], (obj.facets[i])[2]) );
assert(fid == i);
}
//get the bounding box of mesh
GetBBox();
//Generate the topology for tmesh
GenerateMeshTopo();
//Mark the non_manifoldness
MarkNonManifoldness();
//debug
//PrintMeshTopo();
//getchar();
return true;
}else{
return false;
}
}
bool TMesh::ReadMatlabStruct(double *tri, int nt, double *X, double *Y, double *Z, int nv) {
for (int v = 0; v < nv; v++) {
add_vertex( VTMesh(*X++, *Y++, *Z++) );
}
for (int t = 0; t < nt; t++) {
unsigned int fid = add_facet( FTMesh(tri[0]-1, tri[nt]-1, tri[nt+nt]-1) );
tri++;
assert(fid == t);
}
assert(v_count() == nv);
assert(f_count() == nt);
//get the bounding box of mesh
GetBBox();
//Generate the topology for tmesh
GenerateMeshTopo();
//Mark the non_manifoldness
MarkNonManifoldness();
return true;
}
bool TMesh::ReadOffFile(char *filename, bool wcolor)
{
ifstream fin_temp;
fin_temp.open(filename);
if( !fin_temp.good() ){
return false;
}
ofstream fout_temp;
fout_temp.open("temp.m");
if(!fout_temp.good()){
cerr<<"Failed to open file temp.m"<<endl;
return false;
}
// Read the off file and skip the comments.
// Write the comment-less off file to a file, called "temp.m".
while(! fin_temp.eof()){
char line[90];
fin_temp.getline(line, 90);
if(line[0] == 'O' || line[0] == '#')
;
else
fout_temp << line << endl;
}
fin_temp.close();
fout_temp.close();
FILE *fp;
if( (fp = fopen("temp.m", "r")) == NULL ){
cerr<<"Failed to open file temp.m"<<endl;
return false;
}
unsigned int n_ver, n_facet, n_edge;
fscanf(fp, "%d %d %d", &n_ver, &n_facet, &n_edge);
// cerr<<"n_ver: "<<n_ver<<" n_facet: "<<n_facet<<endl;
float x, y, z;
//vertex information
for(unsigned int i = 0; i < n_ver; i ++){
fscanf(fp, "%f %f %f", &x, &y, &z);
//cerr<<"x y z"<<x<<" "<<y<<" "<<z<<endl;
//VTMesh v(x, y, z);
add_vertex( VTMesh(x, y, z) );
}
//cout<<"vertex done"<<endl;
//facet information
int nv, vid0, vid1, vid2;
float r, g, b, a;
for(unsigned int i = 0; i < n_facet; i ++){
fscanf(fp, "%d %d %d %d", &nv, &vid0, &vid1, &vid2);
if(wcolor) fscanf(fp, "%f %f %f %f", &r, &g, &b, &a);
unsigned int fid = add_facet( FTMesh(vid0, vid1, vid2) );
assert(fid == i);
}
//cerr<<"facet done"<<endl;
assert(v_count() == n_ver);
assert(f_count() == n_facet);
//get the bounding box of mesh
GetBBox();
//Delete the temp.m file
system("rm temp.m");
//Generate the topology for tmesh
GenerateMeshTopo();
//Mark the non_manifoldness
MarkNonManifoldness();
//debug
// PrintMeshTopo();
// getchar();
return true;
}
void TMesh::GenerateMeshTopo()
{
unsigned int vid0, vid1, vid2;
for(unsigned int i = 0; i < f_count(); i ++){
vid0 = facet(i).vert(0);
vid1 = facet(i).vert(1);
vid2 = facet(i).vert(2);
// cout<<i<<"th facet: vertices: "<<vid0<<" "<<vid1<<" "<<vid2<<endl;
//generate the vertex topology
vertex(vid0).add_facet(i);
vertex(vid1).add_facet(i);
vertex(vid2).add_facet(i);
vertex(vid0).add_unique_vert(vid1);
vertex(vid1).add_unique_vert(vid0);
vertex(vid1).add_unique_vert(vid2);
vertex(vid2).add_unique_vert(vid1);
vertex(vid2).add_unique_vert(vid0);
vertex(vid0).add_unique_vert(vid2);
}
//cerr<<"facet done"<<endl;
for(unsigned int i = 0; i < f_count(); i ++)
{
//cout<<"fid: "<<i<<endl;
//iterate over all facets
for(int j = 0; j < 3; j ++){
//cout<<j<<"th vertex "<<endl;
//edge vert(j) -- vert((j + 1) % 3)
vid1 = facet(i).vert(j);
vid2 = facet(i).vert((j + 1) % 3);
//seach the adjacent triangle sharing edge (j + 2) % 3
for(unsigned int fit = 0; fit < vertex(vid1).n_facets(); fit ++){
unsigned int fid = vertex(vid1).facet(fit);
if(fid <= i) continue;
//cout<<"connected facet: "<<fid<<endl;
int i1, i2;
if( (i2 = facet(fid).index(vid2)) == -1 ) continue;
i1 = facet(fid).index(vid1);
assert(i1 >= 0);
if( facet(i).facet((j + 2) % 3) >= 0){
cerr<<"non-manifold1: "<<i<<"--"<<fid<<" along edge: "<<vid1<<" "<<vid2<<endl;
continue;
}
for(int k = 0; k < 3; k ++){
if(k != i1 && k != i2){
if(facet(fid).facet(k) >= 0){
cerr<<"non-manifold1: "<<i<<"--"<<fid<<" along edge: "<<vid1<<" "<<vid2<<endl;
}
else{ //Only when both facets have not neighbouring facet along
//this edge can they be the neighbouring faect for each other.
facet(fid).set_facet(k, i);
facet(i).set_facet((j + 2) % 3, fid);
}
break;
}
}//for k
}//for fit
}//for j
}//for i
//cout<<"topo done"<<endl;
//set boundary flag
//for particle
for(unsigned int i = 0; i < f_count(); i ++){
for(int j = 0; j < 3; j ++){
if(facet(i).facet(j) >= 0) continue;
facet(i).set_flag(FTMESH_FLAG_BOUNDARY);
vertex( facet(i).vert((j + 1) % 3) ).set_flag(VTMESH_FLAG_BOUNDARY);
vertex( facet(i).vert((j + 2) % 3) ).set_flag(VTMESH_FLAG_BOUNDARY);
}
}
//Check whether the topology of the mesh is valid.
CheckMeshTopo();
}
//--------------------------------------------------
//MarkNonManifoldness:
//----------------
//Check the non_manifoldness for each vertex and mark
//the vertex and all the incident facets if it is a
//non_manifold vertex.
//--------------------------------------------------
void TMesh::MarkNonManifoldness()
{
unsigned int vid, fid, count;
int ind, fid_circ, ind_circ, fid_pre;
for(vid = 0; vid < v_count(); vid ++){
VTMesh vert = vertex(vid);
if( vert.n_facets() == 0) continue;
fid = vert.facet(0);
ind = facet(fid).index(vid);
//assert(ind >= 0);
if (ind < 0) break;
facet(fid).set_flag(FTMESH_FLAG_VISITED);
count = 1;
#define UMBRELLAWALK(vid, fid, fid_circ) \
fid_pre = fid; \
while(fid_circ >= 0 && fid_circ != (int)fid){ \
if( facet(fid_circ).check_flag(FTMESH_FLAG_VISITED) ) break; \
facet(fid_circ).set_flag(FTMESH_FLAG_VISITED); \
count ++; \
ind_circ = facet(fid_circ).index(vid); \
assert(ind_circ >= 0); \
if( fid_pre != facet(fid_circ).facet( (ind_circ + 1) % 3 ) ){ \
fid_pre = fid_circ; \
fid_circ = facet(fid_circ).facet( (ind_circ + 1) % 3 ); \
} \
else{ \
fid_pre = fid_circ; \
fid_circ = facet(fid_circ).facet( (ind_circ + 2) % 3 ); \
} \
}
fid_circ = facet(fid).facet( (ind + 1) % 3 );
UMBRELLAWALK(vid, fid, fid_circ);
fid_circ = facet(fid).facet( (ind + 2) % 3 );
UMBRELLAWALK(vid, fid, fid_circ);
//If the incident facets does not form an umbrella, then mark
if( count < vert.n_facets() ){
vert.set_flag(VTMESH_FLAG_NMANIFOLD);
for(unsigned int i = 0; i < vert.n_facets(); i ++)
facet( vert.facet(i) ).un_set_flag(FTMESH_FLAG_NMANIFOLD);
}
//Unset FTMESH_FLAG_VISITED
for(unsigned int i = 0; i < vert.n_facets(); i ++)
facet( vert.facet(i) ).un_set_flag(FTMESH_FLAG_VISITED);
}
}
//--------------------------------------------------
//OrientateFacets:
//----------------
//Orientate the facets so that all the manifold facets will have
//a consistent orientation
//--------------------------------------------------
void TMesh::OrientateFacets()
{
unsigned int fid, f;
queue<unsigned int> fid_queue;
unsigned int max_nfacets, nfacets, fid_start;
unsigned int vid1, vid2;
int ind1, ind2;
int fid_adj;
//Find largest part of the surface which can be orientated.
max_nfacets = 0;
for(f = 0; f < f_count(); f ++){
if( facet(f).check_flag(FTMESH_FLAG_NMANIFOLD) ) continue;
if( facet(f).check_flag(FTMESH_FLAG_VISITED) ) continue;
fid_queue.push(f);
facet(f).set_flag(FTMESH_FLAG_VISITED);
nfacets = 0;
while( !fid_queue.empty() ){
fid = fid_queue.front(); fid_queue.pop();
nfacets ++;
for(int j = 0; j < 3; j ++){
fid_adj = facet(fid).facet(j);
if(fid_adj < 0) continue;
if( facet(fid_adj).check_flag(FTMESH_FLAG_NMANIFOLD) ) continue;
if( facet(fid_adj).check_flag(FTMESH_FLAG_VISITED) ) continue;
fid_queue.push(fid_adj);
facet(fid_adj).set_flag(FTMESH_FLAG_VISITED);
}
}
if( nfacets > max_nfacets ){
max_nfacets = nfacets;
fid_start = f;
}
}
//unset flags
for(f = 0; f < f_count(); f ++)
facet(f).un_set_flag(FTMESH_FLAG_VISITED);
//orientate the facets
fid_queue.push(fid_start);
facet(fid_start).set_flag(FTMESH_FLAG_ORIENTATE);
while( !fid_queue.empty()){
fid = fid_queue.front(); fid_queue.pop();
for(int j = 0; j < 3; j ++){
fid_adj = facet(fid).facet(j);
if(fid_adj < 0) continue;
if( facet(fid_adj).check_flag(FTMESH_FLAG_NMANIFOLD) ) continue;
if( facet(fid_adj).check_flag(FTMESH_FLAG_ORIENTATE) ) continue;
vid1 = facet(fid).vert( (j + 1) % 3 );
vid2 = facet(fid).vert( (j + 2) % 3 );
ind1 = facet(fid_adj).index(vid1);
ind2 = facet(fid_adj).index(vid2);
assert( ind1 >= 0 && ind2 >= 0 );
//If the orientation of "fid" and "fid_adj" are consisitent
if( (ind2 + 1) % 3 == ind1 ){
if( facet(fid).check_flag(FTMESH_FLAG_REVERSE) )
facet(fid_adj).set_flag(FTMESH_FLAG_REVERSE);
}
else{ //Otherwise the orientation of "fid" and "fid_adj" are NOT consisitent
assert( (ind1 + 1) % 3 == ind2 );
if( !(facet(fid).check_flag(FTMESH_FLAG_REVERSE)) )
facet(fid_adj).set_flag(FTMESH_FLAG_REVERSE);
}
fid_queue.push(fid_adj);
facet(fid_adj).set_flag(FTMESH_FLAG_ORIENTATE);
}//for j
}//while
}
void TMesh::PrintMeshTopo()
{
cout<<"vertex top"<<endl;
for(uint i = 0; i < v_count(); i ++){
cout<<"vertex "<<i<<": "<<vertex(i).coord()<<endl;
cout<<"\t incident vertex: ";
for(unsigned int vit = 0; vit < vertex(i).n_verts(); vit ++)
cout<<"\t"<<vertex(i).vert(vit)<<" ";
cout<<endl;
cout<<"\t incident triangle: ";
for(unsigned int fit = 0; fit < vertex(i).n_facets(); fit ++)
cout<<"\t"<<vertex(i).facet(fit)<<" ";
cout<<endl;
}
cout<<endl;
cout<<"triangle top"<<endl;
for(unsigned int i = 0; i < f_count(); i ++){
cout<<"triangle "<<i<<endl;
cout<<"\t vert: ";
for(int j = 0; j < 3; j ++)
cout<<"\t"<<facet(i).vert(j)<<" ";
cout<<endl;
cout<<"\t adj_facet: ";
for(int j = 0; j < 3; j ++)
cout<<"\t"<<facet(i).facet(j)<<" ";
cout<<endl;
}
cout<<endl;
}
bool TMesh::CheckMeshTopo()
{
//check facet topo
bool good = true;
for(unsigned int i = 0; i < f_count(); i ++){
for(int j = 0; j < 3; j ++){
int fid = facet(i).facet(j);
if(fid < 0) continue;
int findex = facet(fid).findex(facet(i).vert((j + 1) % 3), facet(i).vert((j + 2) % 3));
if(findex < 0){
cerr<<"mesh topo check error!"<<endl;
cerr<<"fid: "<<i<<" eid: "<<" fid_adj: "<<fid<<endl;
good = false;
}
//assert(findex >= 0);
}
}
//check vertex topo
for(unsigned int i = 0; i < v_count(); i ++){
for(unsigned int j = 0; j < vertex(i).n_facets(); j ++){
unsigned int fid = vertex(i).facet(j);
int vindex = facet(fid).index(i);
if(vindex < 0){
cerr<<"mesh topo check error!"<<endl;
cerr<< "vid: "<<i<<" fid: "<<fid<<endl;
good = false;
}
//assert(vindex >= 0);
}
for(unsigned int j = 0; j < vertex(i).n_verts(); j ++){
unsigned int vid = vertex(i).vert(j);
int vindex = vertex(vid).index(i);
if(vindex < 0){
cerr<<"mesh topo check error!"<<endl;
cerr<<"vid: "<<i<<" vid: "<<vid<<endl;
good = false;
}
//assert(vindex >= 0);
}
}
if(!good){
cerr<<"Warning: the input mesh is not a manifold, which MAY crash the successive computation."<<endl;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////////////
//GetBBox
//--------
//Get a box which is twice as bigger as the boundding box of the object
//
void TMesh::GetBBox()
{
if(v_count() == 0 ){
_pmin = VECTOR3();
_pmax = VECTOR3();
return;
}
for(int i = 0; i < 3; i ++){
_pmin[i] = (vertex(0).coord())(i);
_pmax[i] = (vertex(0).coord())(i);
}
for(unsigned int i = 1; i < v_count(); i ++){
for(int j = 0; j < 3; j ++){
if( (vertex(i).coord())(j) < _pmin[j] )
_pmin[j] = (vertex(i).coord())(j);
else if((vertex(i).coord())(j) > _pmax[j])
_pmax[j] = (vertex(i).coord())(j);
}//for j
}//for i
//cerr<<"BBox: min "<<_pmin[0]<<" "<<_pmin[1]<<" "<<_pmin[2]
//<<" max "<<_pmax[0]<<" "<<_pmax[1]<<" "<<_pmax[2]<<endl;
}
bool TMesh::IsOutBBox(VECTOR3 pt)
{
if(pt[0] < _pmin[0] || pt[0] > _pmax[0]) return true;
if(pt[1] < _pmin[1] || pt[1] > _pmax[1]) return true;
if(pt[2] < _pmin[2] || pt[2] > _pmax[2]) return true;
return false;
}
////////////////////////////////////////////////////////////////////////////////////////
//Meshsize
//--------
//Estimate mesh size
//
void TMesh::MeshSize(double& maxs, double& mins, double& aves)
{
maxs = -FLT_MAX;
mins = FLT_MAX;
aves = 0;
for(unsigned int i = 0; i < f_count(); i ++){
for(unsigned int j = 0; j < 3; j ++){
int vid0 = facet(i).vert(j);
int vid1 = facet(i).vert((j + 1) % 3);
double length = dot(vertex(vid0).coord() - vertex(vid1).coord(), vertex(vid0).coord() - vertex(vid1).coord());
length = sqrt(fabs(length));
aves += length;
if(maxs < length){
maxs = length;
}
if(mins > length){
mins = length;
}
}
}
aves /= 3 * f_count();
cout<<"maxs: "<<maxs<<" mins: "<<mins<<" aves: "<<aves<<endl;
}
//================================================================
//begin: off file outpur function
//================================================================
void TMesh::OutMeshOffFile(char *filename)
{
FILE *fp;
if( (fp = fopen(filename, "w")) == NULL ){
std::cout<<"Failed to open file!"<<std::endl;
return;
}
fprintf(fp, "LIST\n");
fprintf(fp, "appearance {linewidth 7}\n");
fprintf(fp, "{\n");
fprintf(fp, "OFF\n");
fprintf(fp, "%d %d 0\n", v_count(), f_count());
for(unsigned int i = 0; i < v_count(); i ++){
fprintf(fp, "%f %f %f\n", (vertex(i).coord())(0), (vertex(i).coord())(1), (vertex(i).coord())(2));
}
for(unsigned int i = 0; i < f_count(); i ++){
if( vertex(facet(i).vert(0)).check_flag(VTMESH_FLAG_SELECTED)
&& vertex(facet(i).vert(1)).check_flag(VTMESH_FLAG_SELECTED)
&& vertex(facet(i).vert(2)).check_flag(VTMESH_FLAG_SELECTED))
fprintf(fp, "3 %d %d %d 0.2 0.2 0.2 1\n", facet(i).vert(0), facet(i).vert(1), facet(i).vert(2));
else
fprintf(fp, "3 %d %d %d 1 1 1 1\n", facet(i).vert(0), facet(i).vert(1), facet(i).vert(2));
}
fprintf(fp, "}\n");
fclose(fp);
}
void TMesh::OutMeshOffFile(FILE *fp, double r, double g, double b, double a)
{
if( fp == NULL ){
std::cout<<"Invalid FILE pointer"<<std::endl;
return;
}
fprintf(fp, "{\n");
fprintf(fp, "OFF\n");
fprintf(fp, "%d %d 0\n", v_count(), f_count());
for(unsigned int i = 0; i < v_count(); i ++){
fprintf(fp, "%f %f %f\n", (vertex(i).coord())(0), (vertex(i).coord())(1), (vertex(i).coord())(2));
}
for(unsigned int i = 0; i < f_count(); i ++){
if( facet(i).check_flag(FTMESH_FLAG_SELECT) )
fprintf(fp, "3 %d %d %d 1 0 0 1\n", facet(i).vert(0), facet(i).vert(1), facet(i).vert(2));
else
fprintf(fp, "3 %d %d %d %f %f %f %f\n", facet(i).vert(0), facet(i).vert(1), facet(i).vert(2), r, g, b, a);
}
fprintf(fp, "}\n");
}
/*
void TMesh::OutMeshOffFile(FILE *fp, double r, double g, double b, double a)
{
if( fp == NULL ){
std::cout<<"Invalid FILE pointer"<<std::endl;
return;
}
fprintf(fp, "{\n");
fprintf(fp, "OFF\n");
fprintf(fp, "%d %d 0\n", v_count(), f_count());
for(unsigned int i = 0; i < v_count(); i ++){
fprintf(fp, "%f %f %f\n", (vertex(i).coord())(0), (vertex(i).coord())(1), (vertex(i).coord())(2));
}
for(unsigned int i = 0; i < f_count(); i ++){
fprintf(fp, "3 %d %d %d 1 0 0 1\n", facet(i).vert(0), facet(i).vert(1), facet(i).vert(2));
fprintf(fp, "3 %d %d %d %f %f %f %f\n", facet(i).vert(0), facet(i).vert(1), facet(i).vert(2), r, g, b, a);
}
fprintf(fp, "}\n");
}
*/
//================================================================
//end: off file outpur function
//================================================================
| [
"cl319@duke.edu"
] | cl319@duke.edu |
e22d695480709e4327d1bfc1b4b7aa2d97ad4428 | a7b00f469b109fa53176a573ebd6d24687db0a42 | /src/GFA_Parser.hpp | 89034dbd5c4b81c56e9f72fd03e9cf9b9f4d9f6f | [
"BSD-2-Clause",
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"CC-BY-3.0"
] | permissive | winni2k/bifrost | 8b3fe23482833644e458d09bf04bf79e7e5437dd | 5be773b3ccc3d432cea4e12ef32a60f17cd3e129 | refs/heads/master | 2021-01-01T12:28:26.407618 | 2020-06-05T18:04:45 | 2020-06-05T18:04:45 | 239,278,677 | 0 | 0 | BSD-2-Clause | 2020-02-09T09:36:23 | 2020-02-09T09:36:22 | null | UTF-8 | C++ | false | false | 3,682 | hpp | #ifndef BIFROST_GFA_PARSER_HPP
#define BIFROST_GFA_PARSER_HPP
#include <string>
#include <cstring>
#include <vector>
#include <sys/stat.h>
#include <stdint.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <memory>
using namespace std;
class GFA_Parser {
struct Sequence {
string id;
string seq;
size_t len;
vector<string> tags;
Sequence() : seq("*"), len(0) {};
Sequence(const string& id_, const string& seq_, const size_t len_) : id(id_), seq(seq_), len(len_) {};
inline void clear() {
id.clear();
tags.clear();
seq = "*";
len = 0;
}
};
struct Edge {
string edge_id;
string vertexA_id;
size_t pos_start_overlapA;
size_t pos_end_overlapA;
bool strand_overlapA;
string vertexB_id;
size_t pos_start_overlapB;
size_t pos_end_overlapB;
bool strand_overlapB;
Edge() : edge_id("*"),
vertexA_id(), pos_start_overlapA(0), pos_end_overlapA(0), strand_overlapA(true),
vertexB_id(), pos_start_overlapB(0), pos_end_overlapB(0), strand_overlapB(true) {};
Edge(const string vertexA_id_, const size_t pos_start_overlapA_, const size_t pos_end_overlapA_, const bool strand_overlapA_,
const string vertexB_id_, const size_t pos_start_overlapB_, const size_t pos_end_overlapB_, const bool strand_overlapB_,
const string edge_id_ = "*") : edge_id(edge_id_),
vertexA_id(vertexA_id_), pos_start_overlapA(pos_start_overlapA_), pos_end_overlapA(pos_end_overlapA_), strand_overlapA(strand_overlapA_),
vertexB_id(vertexB_id_), pos_start_overlapB(pos_start_overlapB_), pos_end_overlapB(pos_end_overlapB_), strand_overlapB(strand_overlapB_) {};
inline void clear() {
vertexA_id.clear();
vertexB_id.clear();
edge_id = "*";
pos_start_overlapA = 0;
pos_end_overlapA = 0;
pos_start_overlapB = 0;
pos_end_overlapB = 0;
strand_overlapA = true;
strand_overlapB = true;
}
};
public:
typedef pair<const Sequence*, const Edge*> GFA_line;
GFA_Parser();
GFA_Parser(const string& filename);
GFA_Parser(const vector<string>& filenames);
~GFA_Parser();
GFA_Parser(GFA_Parser&& o);
GFA_Parser& operator=(GFA_Parser&& o);
bool open_write(const size_t version_GFA = 1, const string tags_line_header = "");
bool open_read();
void close();
bool write_sequence(const string& id, const size_t len, const string seq = "*", const string tags_line = "");
bool write_edge(const string vertexA_id, const size_t pos_start_overlapA, const size_t pos_end_overlapA, const bool strand_overlapA,
const string vertexB_id, const size_t pos_start_overlapB, const size_t pos_end_overlapB, const bool strand_overlapB,
const string edge_id = "*");
GFA_line read(size_t& file_id);
GFA_line read(size_t& file_id, bool& new_file_opened, const bool skip_edges = false);
private:
bool open(const size_t idx_filename);
vector<string> graph_filenames;
ifstream* graphfile_in;
istream graph_in;
ofstream* graphfile_out;
ostream graph_out;
size_t v_gfa;
size_t file_no;
char buffer_stream[8192];
bool file_open_write;
bool file_open_read;
Sequence s;
Edge e;
};
#endif
| [
"guillaumeholley@gmail.com"
] | guillaumeholley@gmail.com |
c59cea5136d20825bac205e984a688f5398f37ab | def2d52900e0d47f166a3632c51346590b387f6e | /lg1313/main.cpp | 39119d246bb9d5e9585d552f1ed87d8634692c6b | [] | no_license | lianix/NOIpStudy | acfd1501d7276c5ce20b600b8c3cb6ddf2a9c1e2 | d0b5f928acb4fbcf64bfa7bbb59d441373daffc4 | refs/heads/master | 2020-06-15T04:29:15.501956 | 2019-04-04T13:00:52 | 2019-04-04T13:00:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 745 | cpp | #include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
using namespace std;
int base=10007;
int d[2000][2000];
int quickPow(int a,int b){
int bas=a;
int ans=1;
while(b){
if(b&1)ans=(ans*bas)%base;
bas=(bas*bas)%base;
b>>=1;
}
return ans;
}
int main() {
int a,b,k,n,m;
cin>>a>>b>>k>>n>>m;
a%=base;
b%=base;
a=quickPow(a,n);
b=quickPow(b,m);
for (int i = 0; i<=k; i++)
{
d[i][0] = 1;
d[i][i] = 1;
}
int c=min(n,m);
for (int i = 2; i<=k; i++)//从1开始就会WA
{
for (int j = 1; j<=c; j++)
{
d[i][j] = (d[i-1][j]+d[i-1][j-1]) %base;
}
}
int sum = (a*b)%base;
sum=(sum* d[k][c])%base;
printf("%d",sum);
return 0;
}
| [
"noreply@github.com"
] | lianix.noreply@github.com |
3e9ec2b21d842b2ff50d27c1f9dc22d6cbd01cf6 | 38c10c01007624cd2056884f25e0d6ab85442194 | /net/android/keystore.cc | 4fa8dbf6329a2f4bed4a6abc7c51eb1a0a3b28d2 | [
"BSD-3-Clause"
] | permissive | zenoalbisser/chromium | 6ecf37b6c030c84f1b26282bc4ef95769c62a9b2 | e71f21b9b4b9b839f5093301974a45545dad2691 | refs/heads/master | 2022-12-25T14:23:18.568575 | 2016-07-14T21:49:52 | 2016-07-23T08:02:51 | 63,980,627 | 0 | 2 | BSD-3-Clause | 2022-12-12T12:43:41 | 2016-07-22T20:14:04 | null | UTF-8 | C++ | false | false | 4,265 | cc | // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/android/keystore.h"
#include <vector>
#include "base/android/jni_android.h"
#include "base/android/jni_array.h"
#include "base/logging.h"
#include "jni/AndroidKeyStore_jni.h"
#include "net/android/android_private_key.h"
using base::android::AttachCurrentThread;
using base::android::HasException;
using base::android::JavaByteArrayToByteVector;
using base::android::ScopedJavaLocalRef;
using base::android::ToJavaByteArray;
using base::android::JavaArrayOfByteArrayToStringVector;
namespace net {
namespace android {
bool GetRSAKeyModulus(jobject private_key_ref, std::vector<uint8_t>* result) {
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jbyteArray> modulus_ref =
Java_AndroidKeyStore_getRSAKeyModulus(env,
GetKeyStore(private_key_ref).obj(),
private_key_ref);
if (modulus_ref.is_null())
return false;
JavaByteArrayToByteVector(env, modulus_ref.obj(), result);
return true;
}
bool GetECKeyOrder(jobject private_key_ref, std::vector<uint8_t>* result) {
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jbyteArray> order_ref =
Java_AndroidKeyStore_getECKeyOrder(
env,
GetKeyStore(private_key_ref).obj(),
private_key_ref);
if (order_ref.is_null())
return false;
JavaByteArrayToByteVector(env, order_ref.obj(), result);
return true;
}
bool RawSignDigestWithPrivateKey(jobject private_key_ref,
const base::StringPiece& digest,
std::vector<uint8_t>* signature) {
JNIEnv* env = AttachCurrentThread();
// Convert message to byte[] array.
ScopedJavaLocalRef<jbyteArray> digest_ref = ToJavaByteArray(
env, reinterpret_cast<const uint8_t*>(digest.data()), digest.length());
DCHECK(!digest_ref.is_null());
// Invoke platform API
ScopedJavaLocalRef<jbyteArray> signature_ref =
Java_AndroidKeyStore_rawSignDigestWithPrivateKey(
env,
GetKeyStore(private_key_ref).obj(),
private_key_ref,
digest_ref.obj());
if (HasException(env) || signature_ref.is_null())
return false;
// Write signature to string.
JavaByteArrayToByteVector(env, signature_ref.obj(), signature);
return true;
}
PrivateKeyType GetPrivateKeyType(jobject private_key_ref) {
JNIEnv* env = AttachCurrentThread();
int type = Java_AndroidKeyStore_getPrivateKeyType(
env,
GetKeyStore(private_key_ref).obj(),
private_key_ref);
return static_cast<PrivateKeyType>(type);
}
AndroidEVP_PKEY* GetOpenSSLSystemHandleForPrivateKey(jobject private_key_ref) {
JNIEnv* env = AttachCurrentThread();
// Note: the pointer is passed as a jint here because that's how it
// is stored in the Java object. Java doesn't have a primitive type
// like intptr_t that matches the size of pointers on the host
// machine, and Android only runs on 32-bit CPUs.
//
// Given that this routine shall only be called on Android < 4.2,
// this won't be a problem in the far future (e.g. when Android gets
// ported to 64-bit environments, if ever).
long pkey = Java_AndroidKeyStore_getOpenSSLHandleForPrivateKey(
env,
GetKeyStore(private_key_ref).obj(),
private_key_ref);
return reinterpret_cast<AndroidEVP_PKEY*>(pkey);
}
ScopedJavaLocalRef<jobject> GetOpenSSLEngineForPrivateKey(
jobject private_key_ref) {
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jobject> engine =
Java_AndroidKeyStore_getOpenSSLEngineForPrivateKey(
env,
GetKeyStore(private_key_ref).obj(),
private_key_ref);
return engine;
}
void ReleaseKey(jobject private_key_ref) {
JNIEnv* env = AttachCurrentThread();
Java_AndroidKeyStore_releaseKey(env,
GetKeyStore(private_key_ref).obj(),
private_key_ref);
env->DeleteGlobalRef(private_key_ref);
}
bool RegisterKeyStore(JNIEnv* env) {
return RegisterNativesImpl(env);
}
} // namespace android
} // namespace net
| [
"zeno.albisser@hemispherian.com"
] | zeno.albisser@hemispherian.com |
c8ccef9343110dcab3189529752fd6daf3e5736d | 73f0dcdc5c3f06a1d43dfab55ca40c78fe9ee403 | /libgbgui/icon.hpp | 3eecb0ddff91011037491a068db7ebb2e88e4a3b | [] | no_license | mugisaku/gamebaby-20180928-dumped | 6da84972407ec7e8a66b35e3975924f8e6207008 | 10a010db9e6369db334c84c73eef06f96e6834c9 | refs/heads/master | 2021-09-23T00:29:03.519034 | 2018-09-19T05:08:50 | 2018-09-19T05:08:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,092 | hpp | #ifndef gbgui_icon_hpp
#define gbgui_icon_hpp
#include"libgbstd/color.hpp"
#include<initializer_list>
namespace gbgui{
namespace icons{
using namespace gbstd;
class
icon
{
public:
static constexpr int size = 16;
private:
color m_data[size][size]={0};
public:
icon(std::initializer_list<int> ls) noexcept;
icon(std::initializer_list<color> ls) noexcept;
void set_color(int x, int y, color i) noexcept{ m_data[y][x] = i;}
color get_color(int x, int y ) const noexcept{return m_data[y][x] ;}
void print() const noexcept;
};
extern const icon checked;
extern const icon unchecked;
extern const icon radio_checked;
extern const icon radio_unchecked;
extern const icon up;
// static const icon sunken_up;
extern const icon left;
extern const icon sunken_left;
extern const icon right;
extern const icon sunken_right;
extern const icon down;
// static const icon sunken_down;
extern const icon plus;
extern const icon minus;
}
using icon = icons::icon;
}
#endif
| [
"lentilspring@gmail.com"
] | lentilspring@gmail.com |
f825c3fe161901b08953d42f01e7aa0472c90c50 | 91ff482968f618098c8faeeca892c6d256ee415c | /cf/617B.cpp | 64363ab8796bfe990e847f4b093db4b3f7de6500 | [] | no_license | Rajat-Goyal/all-over-again | 5728c8d05afc409f103d78f6fbbd3be1bf382793 | a5e4192762febf1666808c4068c83502ef7485fb | refs/heads/master | 2021-01-20T11:18:17.477916 | 2018-10-03T12:12:44 | 2018-10-03T12:12:44 | 83,948,322 | 0 | 1 | null | 2018-10-03T12:12:46 | 2017-03-05T05:48:38 | C++ | UTF-8 | C++ | false | false | 901 | cpp | #include<iostream>
#include<bits/stdc++.h>
#define uint64 unsigned long long int
using namespace std;
int main(){
ios::sync_with_stdio(false);
uint64 n;
cin>>n;
uint64 arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
uint64 l=0,r=0;
uint64 flag = 0 ;
uint64 ans=0;
for(int i=0;i<n;i++){
if(arr[i]==1){
l=i;
ans=1;
break;
}
}
for(int i=n-1;i>=0;i--){
if(arr[i]==1){
r=i;
ans=1;
break;
}
}
//cout<<l<<" "<<r<<endl;
for(int i=l;i<r;i++){
//cout<<arr[i]<<endl;
uint64 cnt = 1;
if(arr[i]==1)continue;
else if(arr[i]==0){
i+=1;
while(arr[i]!=1 && i<=r){
cnt+=1;
i+=1;
}
ans*=(cnt+1);
}
}
cout<<ans<<endl;
}
| [
"rajat1881@gmail.com"
] | rajat1881@gmail.com |
8d43b6bf45d6c401fcdb6c2d78cd08a5e4356242 | dc927839f4697c048fb5607dc75a0d6d8870c917 | /hyphy/trunk/GUIElements/Platform Source/MacOS/WindowClasses/.svn/text-base/HYPlatformDataPanel.cpp.svn-base | 1f65f5965be223c3ca6369de7323f596b7e0a4a7 | [] | no_license | ReiiSky/OCLHYPHY | 1a7637aa456c2427ee013a0c7c9cf9f7919c704e | fc69561b36573795796f8a8790e9bff5fac4a766 | refs/heads/master | 2023-01-11T01:19:24.270971 | 2011-09-20T21:33:05 | 2011-09-20T21:33:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,447 | /*
Mac OS Portions of the data panel class
Sergei L. Kosakovsky Pond, Spring 2000 - December 2002.
*/
#include "HYTreePanel.h"
#include "HYDataPanel.h"
#include "HYUtils.h"
#include "likefunc.h"
//__________________________________________________________________
bool _HYDataPanel::_ProcessMenuSelection (long msel)
{
if (_HYWindow::_ProcessMenuSelection(msel))
return true;
long menuChoice = msel&0x0000ffff;
MenuHandle treeMenu;
_HYSequencePane* sp = (_HYSequencePane*)GetObject (0);
_HYSequencePane* sp2 =(_HYSequencePane*)GetObject (4);
_String prompt;
bool done = false;
switch (msel/0xffff)
{
case 129: // file menu
{
if (menuChoice==4) // save
{
SaveDataPanel (savePath.sLength);
done = true;
}
else
if (menuChoice==8) // print
{
_PrintData();
done = true;
}
HiliteMenu(0);
if (done) return true;
break;
}
case 130: // edit
{
HiliteMenu(0);
if (menuChoice==4) // copy
{
_CopySelectionToClipboard ();
}
else
if (menuChoice==6) // delete selection
{
//DeleteCurrentSelection();
return true;
}
else
if (menuChoice==3) // cut selection
{
//CutSelectionToClipboard ();
return true;
}
else
if (menuChoice==5) // paste selection
{
//PasteClipboardTree();
return true;
}
else
if (menuChoice==8) // select all
{
sp->SelectAll(true);
return true;
}
else
if (menuChoice==11) // Find
{
FindFunction();
return true;
}
else
if (menuChoice==12) // Find
{
HandleSearchAndReplace();
return true;
}
return false;
}
case HY_DATAPANEL_MENU_ID:
{
switch (menuChoice)
{
case 1:
SelectPartition();
break;
case 2:
if (sp->selection.lLength)
CreatePartition (sp->selection,1,true);
break;
case 3:
InvertSelection();
break;
case 11:
PartitionPropsMenu ();
break;
case 12:
InputPartitionString ();
break;
case 15:
SimulateDataSet (0,true);
break;
case 17:
HandleFontChange ();
break;
}
HiliteMenu(0);
return true;
}
case HY_DATAPANEL_MENU_ID+1:
{
switch (menuChoice)
{
case 1:
BuildLikelihoodFunction();
break;
case 3:
OptimizeLikelihoodFunction();
break;
case 5:
DisplayParameterTable ();
break;
case 7:
OpenGeneralBSWindow ();
break;
}
HiliteMenu(0);
return true;
}
case HY_DATAPANEL_HMENU_ID:
{
treeMenu = GetMenuHandle (HY_DATAPANEL_HMENU_ID);
long newBlockSize;
if (menuChoice==1)
newBlockSize = 9;
else
newBlockSize = 10;
if (sp->blockWidth!=newBlockSize)
{
sp->blockWidth = newBlockSize;
sp2->blockWidth = newBlockSize;
sp->BuildPane();
sp->_MarkForUpdate();
sp2->BuildPane();
sp2->_MarkForUpdate();
SetItemMark(treeMenu,menuChoice==1?2:1,noMark);
SetItemMark(treeMenu,menuChoice,checkMark);
InvalMenuBar();
}
HiliteMenu(0);
return true;
}
case HY_DATAPANEL_HMENU_ID+1:
{
treeMenu = GetMenuHandle (HY_DATAPANEL_HMENU_ID+1);
bool newDisplay;
if (menuChoice==1)
newDisplay = false;
else
newDisplay = true;
if (sp->showDots!=newDisplay)
{
sp->showDots = newDisplay;
sp->BuildPane();
sp->_MarkForUpdate();
SetItemMark(treeMenu,menuChoice==1?2:1,noMark);
SetItemMark(treeMenu,menuChoice,checkMark);
InvalMenuBar();
}
HiliteMenu(0);
return true;
}
case HY_DATAPANEL_HMENU_ID+2:
{
treeMenu = GetMenuHandle (HY_DATAPANEL_HMENU_ID+2);
if (menuChoice<=3)
{
unsigned char newDisplay;
switch (menuChoice)
{
case 1:
newDisplay = HY_SEQUENCE_PANE_NAMES_NONE;
break;
case 2:
newDisplay = HY_SEQUENCE_PANE_NAMES_SHORT;
break;
case 3:
newDisplay = HY_SEQUENCE_PANE_NAMES_ALL;
}
if ((sp->nameDisplayFlags&HY_SEQUENCE_PANE_NAMES_MASK)!=newDisplay)
{
SetItemMark(treeMenu,(sp->nameDisplayFlags&HY_SEQUENCE_PANE_NAMES_MASK)+1,noMark);
sp->SetNameDisplayMode(newDisplay,true);
sp2->SetNameDisplayMode(newDisplay,true);
BuildThermometer();
BuildMarksPane();
SetItemMark(treeMenu,menuChoice,checkMark);
InvalMenuBar();
}
}
else
{
if (menuChoice==5) // alphabetize
sp->AlphabetizeSpecies();
else
if (menuChoice==6)
sp->RevertFileOrder();
else
if (menuChoice==7)
sp->CleanUpSequenceNames();
}
HiliteMenu(0);
return true;
}
case HY_DATAPANEL_HMENU_ID+3: // omitted sequences
{
RestoreOmittedSequence(menuChoice-3);
HiliteMenu(0);
return true;
}
case HY_DATAPANEL_HMENU_ID+4: // status lines
{
if (AdjustStatusLine (menuChoice-1))
CheckMenuItem(GetMenuHandle (HY_DATAPANEL_HMENU_ID+4),menuChoice,true);
else
CheckMenuItem(GetMenuHandle (HY_DATAPANEL_HMENU_ID+4),menuChoice,false);
HiliteMenu(0);
return true;
}
case HY_DATAPANEL_HMENU_ID+5: // likelihood display
{
ComputeLikelihoodFunction (menuChoice-1);
HiliteMenu(0);
return true;
}
case HY_DATAPANEL_HMENU_ID+6: // simulate data set
{
SimulateDataSet (menuChoice-1);
HiliteMenu(0);
return true;
}
case HY_DATAPANEL_HMENU_ID+7: // save/save as
{
SaveDataPanel (menuChoice==2);
HiliteMenu(0);
return true;
}
case HY_DATAPANEL_HMENU_ID+8: // infer
{
InferTopologies (menuChoice==2);
_VerifyInferMenu ();
HiliteMenu(0);
return true;
}
case HY_DATAPANEL_HMENU_ID+9: // dataProcs
{
ExecuteProcessor (menuChoice-1);
return true;
}
HiliteMenu(0);
InvalMenuBar();
}
return false;
}
//__________________________________________________________________
void _HYDataPanel::_PaintThermRect(bool update)
{
navRect = ComputeNavRect();
_HYCanvas* theCanvas = (_HYCanvas*)GetObject (1);
GrafPtr savedPort;
GetPort(&savedPort);
#ifdef OPAQUE_TOOLBOX_STRUCTS
SetPort(GetWindowPort(theWindow));
#else
SetPort(theWindow);
#endif
Rect r;
r.left = navRect.left+theCanvas->rel.left+thermRect.left+1;
r.right = navRect.right+theCanvas->rel.left+thermRect.left-1;
r.top = navRect.top+theCanvas->rel.top+thermRect.top+1;
r.bottom = navRect.bottom+theCanvas->rel.top+thermRect.top-1;
RGBColor saveColor,
newColor = {255*256,151*256,51*256};
PenState ps;
GetPenState (&ps);
GetForeColor (&saveColor);
RGBForeColor (&newColor);
PenSize (2,2);
FrameRect (&r);
RGBForeColor (&saveColor);
if (update)
{
RgnHandle oldClip, newClip;
oldClip = NewRgn();
newClip = NewRgn();
RectRgn (oldClip,&r);
InsetRect (&r,2,2);
RectRgn (newClip,&r);
DiffRgn (oldClip,newClip,newClip);
GetClip (oldClip);
DiffRgn (oldClip,newClip,newClip);
SetClip (newClip);
_HYRect rect;
rect.left = componentL.lData[1];
rect.right = componentR.lData[1];
rect.top = componentT.lData[1];
rect.bottom = componentB.lData[1];
theCanvas->_Paint((char*)&rect);
SetClip (oldClip);
DisposeRgn (oldClip);
DisposeRgn (newClip);
}
SetPenState (&ps);
_PaintLFStatus ();
SetPort(savedPort);
}
//__________________________________________________________________
void _HYDataPanel::_PaintLFStatus(void)
{
GrafPtr savedPort;
GetPort(&savedPort);
#ifdef OPAQUE_TOOLBOX_STRUCTS
SetPort(GetWindowPort(theWindow));
#else
SetPort(theWindow);
#endif
if (lfID<0)
{
_SimpleList goodP;
bool paintOrange = GenerateGoodPartitions (goodP);
if (goodP.lLength)
_PaintTheCircle (paintOrange?orangeButtonIcon:yellowButtonIcon,theWindow);
else
_PaintTheCircle (redButtonIcon,theWindow);
}
else
_PaintTheCircle (greenButtonIcon,theWindow);
SetPort(savedPort);
}
//__________________________________________________________________
void _HYDataPanel::_PrintData(void)
{
_HYSequencePane* sp = (_HYSequencePane*)GetObject (0);
GrafPtr savePort;
#ifdef TARGET_API_MAC_CARBON
PMRect prRect;
#else
TPrStatus prStatus;
TPPrPort printPort;
OSErr err;
#endif
#ifdef TARGET_API_MAC_CARBON
OSStatus theStatus;
Boolean isAccepted;
PMPrintSession hyPC;
theStatus = PMCreateSession(&hyPC);
if (theStatus != noErr)
return;
#endif
if (!InitPrint(hyPC))
{
_String errMsg ("Could not initialize printing variables.");
WarnError (errMsg);
terminateExecution = false;
return;
}
GetPort(&savePort);
#ifdef TARGET_API_MAC_CARBON
if (gPrintSettings != kPMNoPrintSettings)
theStatus = PMSessionValidatePrintSettings(hyPC,gPrintSettings, kPMDontWantBoolean);
else
{
theStatus = PMCreatePrintSettings(&gPrintSettings);
if ((theStatus == noErr) && (gPrintSettings != kPMNoPrintSettings))
theStatus = PMSessionDefaultPrintSettings(hyPC,gPrintSettings);
}
if (theStatus == noErr)
{
theStatus = PMSessionPrintDialog(hyPC,gPrintSettings, gPageFormat, &isAccepted);
if (isAccepted)
{
theStatus = PMGetAdjustedPageRect(gPageFormat, &prRect);
if (theStatus != noErr)
return;
theStatus = PMSessionBeginDocument(hyPC,gPrintSettings, gPageFormat);
if (theStatus != noErr)
return;
long printW = prRect.right-prRect.left-2,
printH = prRect.bottom-prRect.top-2;
UInt32 startPage,
endPage;
PMGetFirstPage (gPrintSettings,&startPage);
PMGetLastPage (gPrintSettings,&endPage);
#else
PrOpen();
if (err=PrError())
{
_String errMsg ("Could not print the data set. Error Code:");
errMsg = errMsg & (long)err;
WarnError (errMsg);
terminateExecution = false;
return;
}
if (PrJobDialog(prRecHdl))
{
printPort = PrOpenDoc(prRecHdl, nil, nil);
SetPort((GrafPtr)printPort);
long printW = (*prRecHdl)->prInfo.rPage.right-2,
printH = (*prRecHdl)->prInfo.rPage.bottom-2,
startPage = (*prRecHdl)->prJob.iFstPage,
endPage = (*prRecHdl)->prJob.iLstPage;
#endif
long
vOffset = sp->GetSlotHeight()*sp->speciesIndex.lLength+sp->GetSlotHeight()*3/2+1+20*(dataPartitions.lLength>0),
cOffset = (printW-sp->headerWidth)/sp->charWidth,
pageShift = printH/vOffset,
sC = sp->startColumn,
lC = sp->endColumn,
sR = sp->startRow,
lR = sp->endRow,
sH = sp->settings.bottom,
pageCount;
_HYColor c1 = sp->backColor,
c2 = sp->headerColor,
bc = {0,0,0};
sp->backColor = (_HYColor){255,255,255};
sp->headerColor = (_HYColor){255,255,255};
cOffset -= ((cOffset/sp->blockWidth)*2)/sp->charWidth;
cOffset = (cOffset/sp->blockWidth)*sp->blockWidth;
pageShift *= cOffset;
if (sp->columnStrings.lLength%pageShift==0)
pageShift = sp->columnStrings.lLength / pageShift;
else
pageShift = sp->columnStrings.lLength / pageShift + 1;
if (endPage > pageShift)
endPage = pageShift;
sp->startColumn = 0;
sp->endColumn = cOffset;
sp->startRow = 0;
sp->endRow = sp->speciesIndex.lLength;
sp->settings.bottom = vOffset+5+HY_SCROLLER_WIDTH;
for (pageCount = 1; pageCount<startPage; pageCount++)
{
#ifdef TARGET_API_MAC_CARBON
theStatus = PMSessionBeginPage(hyPC,gPageFormat,NULL);
if (theStatus != noErr)
break;
theStatus = PMSessionEndPage(hyPC);
if (theStatus != noErr)
break;
#else
PrOpenPage (printPort, nil);
PrClosePage (printPort);
#endif
sp->endColumn += printH/vOffset * cOffset;
sp->startColumn += printH/vOffset * cOffset;
}
Rect hangover = {0,
sp->headerWidth + cOffset * sp->charWidth + (cOffset * 2)/sp->blockWidth + 1,
vOffset,
printW},
frame = {0,0,vOffset+1,hangover.left};
if (sp->startColumn< sp->columnStrings.lLength)
for (pageCount = startPage; pageCount<=endPage; pageCount++)
{
pageShift = vOffset;
#ifdef TARGET_API_MAC_CARBON
theStatus = PMSessionBeginPage(hyPC,gPageFormat, NULL);
if (theStatus != noErr)
break;
GrafPtr ppPort;
PMSessionGetGraphicsContext (hyPC, NULL, (void**)&ppPort);
SetPort (ppPort);
#else
PrOpenPage (printPort, nil);
#endif
SetOrigin (0,0);
sp->_HYGraphicPane::SetFont (sp->GetFont());
sp->SetColor (sp->GetColor());
while (pageShift < printH)
{
sp->BuildPane (false);
sp->SetColor (bc);
PenSize (1,1);
//EraseRect (&hangover);
if (dataPartitions.lLength)
{
_HYRect daFrame;
daFrame.top = frame.bottom;
daFrame.bottom = frame.bottom + 20;
daFrame.left = frame.left + HY_SEQUENCE_PANE_CHAR_SPACING/2 + sp->headerWidth;
daFrame.right = daFrame.left + cOffset*sp->charWidth + 2*(cOffset/sp->blockWidth) - HY_SCROLLER_WIDTH;
BuildThermometer (&daFrame);
}
//FrameRect (&frame);
sp->startColumn = sp->endColumn;
sp->endColumn += cOffset;
SetOrigin (0,-pageShift);
pageShift += vOffset;
if (sp->startColumn>=sp->columnStrings.lLength)
break;
}
#ifdef TARGET_API_MAC_CARBON
theStatus = PMSessionEndPage(hyPC);
if (theStatus != noErr)
break;
#else
PrClosePage (printPort);
#endif
}
sp->startColumn = sC;
sp->endColumn = lC;
sp->startRow = sR;
sp->endRow = lR;
sp->backColor = c1;
sp->headerColor = c2;
sp->settings.bottom = sH;
#ifdef TARGET_API_MAC_CARBON
theStatus = PMSessionEndDocument(hyPC);
SetPort(savePort);
if (theStatus == noErr)
{
if (gFlattenedFormat != NULL)
{
DisposeHandle(gFlattenedFormat);
gFlattenedFormat = NULL;
}
theStatus = PMFlattenPageFormat(gPageFormat, &gFlattenedFormat);
}
if (theStatus == noErr)
{
if (gFlattenedSettings != NULL)
{
DisposeHandle(gFlattenedSettings);
gFlattenedSettings = NULL;
}
theStatus = PMFlattenPrintSettings(gPrintSettings, &gFlattenedSettings);
}
if (gPageFormat != kPMNoPageFormat)
{
theStatus = PMRelease(gPageFormat);
gPageFormat = kPMNoPageFormat;
}
if (gPrintSettings != kPMNoPrintSettings)
{
theStatus = PMRelease(gPrintSettings);
gPrintSettings = kPMNoPrintSettings;
}
theStatus = PMRelease(hyPC);
#else
PrCloseDoc(printPort);
if (((*prRecHdl)->prJob.bJDocLoop = bSpoolLoop) && (!PrError() ) )
PrPicFile(prRecHdl, nil, nil, nil, &prStatus);
#endif
}
#ifdef TARGET_API_MAC_CARBON
else
theStatus = PMRelease(hyPC);
#endif
#ifdef TARGET_API_MAC_CARBON
}
#else
PrClose();
SetPort(savePort);
#endif
}
//__________________________________________________________________
void _HYDataPanel::_VerifyInferMenu(void)
{
MenuHandle lfMenu = GetMenuHandle (HY_DATAPANEL_MENU_ID+1),
inferSubMenu = GetMenuHandle (HY_DATAPANEL_HMENU_ID+8);
_SimpleList gp;
if (GenerateGoodPartitions(gp))
{
if (!inferSubMenu)
{
inferSubMenu = NewMenu(HY_DATAPANEL_HMENU_ID+8,"\p");
InsertMenu (inferSubMenu,hierMenu);
SetItemCmd (lfMenu,1,hMenuCmd);
SetItemMark(lfMenu,1,HY_DATAPANEL_HMENU_ID+8);
InsertMenuItem (inferSubMenu,"\pInfer Topology/L",10000);
InsertMenuItem (inferSubMenu,"\pInfer Topology with Constraints",10000);
SetMenuItemText (lfMenu,1,"\pInference...");
}
}
else
{
if (inferSubMenu)
{
SetItemMark (lfMenu,1,noMark);
DeleteMenu (HY_DATAPANEL_HMENU_ID+8);
DisposeMenu (inferSubMenu);
SetMenuItemText (lfMenu,1,"\pBuild Function");
SetItemCmd (lfMenu,1,'L');
}
}
}
//__________________________________________________________________
void _HYDataPanel::_SetMenuBar(void)
{
//BufferToConsole ("_HYDataPanel::_SetMenuBar\n");
_HYWindow::_SetMenuBar();
MenuHandle t = GetMenuHandle (130),
dM = GetMenuHandle (HY_DATAPANEL_MENU_ID);
_HYWindow::_SetMenuBar();
EnableMenuItem (t,4);
EnableMenuItem (t,8);
if (!dM)
{
MenuHandle dataMenu = NewMenu(HY_DATAPANEL_MENU_ID,"\pData"),
lfMenu = NewMenu (HY_DATAPANEL_MENU_ID+1,"\pLikelihood"),
blockMenu = NewMenu(HY_DATAPANEL_HMENU_ID,"\p"),
repeatCharMenu = NewMenu(HY_DATAPANEL_HMENU_ID+1,"\p"),
nameDisplayMenu = NewMenu(HY_DATAPANEL_HMENU_ID+2,"\p"),
omittedSpecies = NewMenu(HY_DATAPANEL_HMENU_ID+3,"\p"),
additionalInfo = NewMenu(HY_DATAPANEL_HMENU_ID+4,"\p"),
lfDisplayMode = NewMenu(HY_DATAPANEL_HMENU_ID+5,"\p"),
simulateData = NewMenu(HY_DATAPANEL_HMENU_ID+6,"\p"),
saveSubMenu = NewMenu(HY_DATAPANEL_HMENU_ID+7,"\p"),
dataProcMenu = NewMenu(HY_DATAPANEL_HMENU_ID+9,"\p");
if (!(dataMenu&&blockMenu&&repeatCharMenu&&nameDisplayMenu&&omittedSpecies&&additionalInfo))
warnError (-108);
InsertMenuItem (dataMenu,"\p(Partition->Selection/1",10000); // 1
InsertMenuItem (dataMenu,"\p(Selection->Partition/2",10000); // 2
InsertMenuItem (dataMenu,"\pInvert Selection/3",10000); // 3
InsertMenuItem (dataMenu,"\p(-",10000); // 4
InsertMenuItem (dataMenu,"\pBlock Width",10000); // 5
InsertMenuItem (dataMenu,"\pRepeating Characters",10000); // 6
InsertMenuItem (dataMenu,"\pName Display",10000); // 7
InsertMenuItem (dataMenu,"\pOmitted Sequences",10000); // 8
InsertMenuItem (dataMenu,"\pAdditional Info",10000); // 9
InsertMenuItem (dataMenu,"\p(-",10000); // 10
InsertMenuItem (dataMenu,"\p(Paritition Properties",10000); // 11
InsertMenuItem (dataMenu,"\pInput Partition",10000); // 12
InsertMenuItem (dataMenu,"\p(-",10000); // 13
InsertMenuItem (dataMenu,"\p(Simulation",10000); // 14
InsertMenuItem (dataMenu,"\p(Ancestors",10000); // 15
InsertMenuItem (dataMenu,"\p(-",10000); // 16
InsertMenuItem (dataMenu,"\pFont Options",10000); // 17
InsertMenuItem (dataMenu,"\p(-",10000); // 18
InsertMenuItem (dataMenu,"\pData Processing",10000); // 19
InsertMenuItem (blockMenu,"\p9",10000);
InsertMenuItem (blockMenu,"\p10",10000);
InsertMenuItem (lfMenu,"\pBuild Function/L",10000);
InsertMenuItem (lfMenu,"\p(Display",10000);
InsertMenuItem (lfMenu,"\p(Optimize/T",10000);
InsertMenuItem (lfMenu,"\p(-",10000);
InsertMenuItem (lfMenu,"\p(Show Parameters/H",10000);
InsertMenuItem (lfMenu,"\p(-",10000);
InsertMenuItem (lfMenu,"\p(General Bootstrap/B",10000);
InsertMenuItem (lfMenu,"\p(-",10000);
InsertMenuItem (lfDisplayMode,"\pLog-Lkhd Only",10000);
InsertMenuItem (lfDisplayMode,"\pLog-Lkhd & Parameter Values",10000);
InsertMenuItem (lfDisplayMode,"\pLog-Lkhd & Concise Trees",10000);
InsertMenuItem (lfDisplayMode,"\pParameter Listing",10000);
InsertMenuItem (lfDisplayMode,"\pLog-Lkhd & Complete Trees",10000);
InsertMenuItem (simulateData,"\pSimulate 1",10000);
InsertMenuItem (simulateData,"\pSimulate 1 To File",10000);
InsertMenuItem (simulateData,"\pSimulate Many",10000);
//SetItemMark (blockMenu,2,checkMark);
InsertMenuItem (repeatCharMenu,"\pDisplay Actual Character",10000);
InsertMenuItem (repeatCharMenu,"\pDisplay '.'",10000);
//SetItemMark (repeatCharMenu,1,checkMark);
InsertMenuItem (nameDisplayMenu,"\pNone",10000);
InsertMenuItem (nameDisplayMenu,"\pFirst 10 characters",10000);
_HYSequencePane *sp = (_HYSequencePane*)GetCellObject(2,0);
if (sp->shortHeaderWidth==sp->fullHeaderWidth)
DisableMenuItem (nameDisplayMenu,2);
InsertMenuItem (nameDisplayMenu,"\pFull Names",10000);
InsertMenuItem (nameDisplayMenu,"\p(-",10000);
InsertMenuItem (nameDisplayMenu,"\pAlphabetize names",10000);
InsertMenuItem (nameDisplayMenu,"\pRevert to file order",10000);
InsertMenuItem (nameDisplayMenu,"\pClean up sequence names",10000);
//SetItemMark (nameDisplayMenu,3,checkMark);
InsertMenuItem (omittedSpecies,"\pRestore All",10000);
InsertMenuItem (omittedSpecies,"\p(-",10000);
InsertMenuItem (additionalInfo,"\pConsensus Sequence",10000);
InsertMenuItem (additionalInfo,"\p(Rate Class",10000);
InsertMenuItem (additionalInfo,"\p(Aminoacid Translation",10000);
InsertMenuItem (additionalInfo,"\pReference Sequence",10000);
InsertMenuItem (saveSubMenu,"\pSave.../S",10000);
InsertMenuItem (saveSubMenu,"\pSave As...",10000);
InsertMenu (dataMenu,132);
InsertMenu (lfMenu,132);
InsertMenu (blockMenu,hierMenu);
InsertMenu (repeatCharMenu,hierMenu);
InsertMenu (nameDisplayMenu,hierMenu);
InsertMenu (omittedSpecies,hierMenu);
InsertMenu (additionalInfo,hierMenu);
InsertMenu (lfDisplayMode,hierMenu);
InsertMenu (simulateData,hierMenu);
InsertMenu (saveSubMenu,hierMenu);
InsertMenu (dataProcMenu,hierMenu);
SetItemCmd (lfMenu,2,hMenuCmd);
SetItemMark(lfMenu,2,HY_DATAPANEL_HMENU_ID+5);
SetItemCmd (dataMenu,5,hMenuCmd);
SetItemMark(dataMenu,5,HY_DATAPANEL_HMENU_ID);
SetItemCmd (dataMenu,6,hMenuCmd);
SetItemMark(dataMenu,6,HY_DATAPANEL_HMENU_ID+1);
SetItemCmd (dataMenu,7,hMenuCmd);
SetItemMark(dataMenu,7,HY_DATAPANEL_HMENU_ID+2);
SetItemCmd (dataMenu,8,hMenuCmd);
SetItemMark(dataMenu,8,HY_DATAPANEL_HMENU_ID+3);
SetItemCmd (dataMenu,9,hMenuCmd);
SetItemMark(dataMenu,9,HY_DATAPANEL_HMENU_ID+4);
SetItemCmd (dataMenu,14,hMenuCmd);
SetItemMark(dataMenu,14,HY_DATAPANEL_HMENU_ID+6);
SetItemCmd (dataMenu,19,hMenuCmd);
SetItemMark(dataMenu,19,HY_DATAPANEL_HMENU_ID+9);
if (omittedSeqs.lLength==0)
DisableMenuItem (dataMenu,8);
else
_OmitSelectedSpecies(omittedSeqs);
if (dataPanelProcessors.lLength == 0)
DisableMenuItem (dataMenu,19);
else
{
Str255 buffer;
for (long k=0; k<dataPanelProcessors.lLength; k++)
{
_String *thisItem = (_String*)dataPanelProcessors (k),
chopped = thisItem->Cut (thisItem->FindBackwards (':',0,-1)+1,-1);
StringToStr255 (chopped,buffer);
InsertMenuItem (dataProcMenu, buffer,10000);
}
}
CheckMenuItem (additionalInfo,1,addedLines&HY_DATAPANEL_CONSENSUS);
CheckMenuItem (additionalInfo,2,addedLines&HY_DATAPANEL_RATECLASS);
CheckMenuItem (additionalInfo,3,addedLines&HY_DATAPANEL_TRANSLATION);
CheckMenuItem (additionalInfo,4,addedLines&HY_DATAPANEL_REFERENCE);
CheckMenuItem (blockMenu,(sp->blockWidth==10)?2:1,true);
if (sp->nameDisplayFlags&HY_SEQUENCE_PANE_NAMES_ALL)
CheckMenuItem (nameDisplayMenu,3,true);
else
if (sp->nameDisplayFlags&HY_SEQUENCE_PANE_NAMES_SHORT)
CheckMenuItem (nameDisplayMenu,2,true);
else
CheckMenuItem (nameDisplayMenu,1,true);
if (sp->showDots)
CheckMenuItem (repeatCharMenu,2,true);
else
CheckMenuItem (repeatCharMenu,1,true);
if (dataType&HY_DATAPANEL_NUCDATA)
EnableMenuItem (additionalInfo,3);
_UpdateLFMenu();
if (aquaInterfaceOn)
{
InsertMenuItem (t,"\p(-", 9);
InsertMenuItem (t,"\pFind.../F", 10);
InsertMenuItem (t,"\pSearch and Replace...", 11);
}
else
{
InsertMenuItem (t,"\pFind.../F", 10);
InsertMenuItem (t,"\pSearch and Replace...", 11);
InsertMenuItem (t,"\p(-", 12);
}
}
t = GetMenuHandle (129);
SetItemCmd (t,4,hMenuCmd);
SetItemMark(t,4,HY_DATAPANEL_HMENU_ID+7);
_VerifyInferMenu ();
InvalMenuBar();
}
//__________________________________________________________________
void _HYDataPanel::_UpdateLFMenu (void)
{
MenuHandle lfMenu = GetMenuHandle (HY_DATAPANEL_MENU_ID+1),
dataMenu = GetMenuHandle (HY_DATAPANEL_MENU_ID),
addMenu= GetMenuHandle (HY_DATAPANEL_HMENU_ID+4);
if (lfMenu && dataMenu && addMenu)
{
if (lfID>=0)
{
EnableMenuItem (lfMenu,2);
EnableMenuItem (lfMenu,3);
EnableMenuItem (lfMenu,5);
EnableMenuItem (lfMenu,7);
EnableMenuItem (dataMenu,14);
EnableMenuItem (dataMenu,15);
if (((_LikelihoodFunction*)likeFuncList (lfID))->GetCategoryVars().lLength)
{
EnableMenuItem (addMenu,2);
return;
}
}
else
{
DisableMenuItem (lfMenu,3);
DisableMenuItem (lfMenu,2);
DisableMenuItem (lfMenu,5);
DisableMenuItem (lfMenu,7);
DisableMenuItem (dataMenu,14);
DisableMenuItem (dataMenu,15);
}
DisableMenuItem (addMenu,2);
}
}
//__________________________________________________________________
void _HYDataPanel::_UpdateSelectionChoices (bool toggle)
{
MenuHandle dataMenu = GetMenuHandle (HY_DATAPANEL_MENU_ID);
if (toggle)
{
EnableMenuItem(dataMenu,2);
//EnableMenuItem(dataMenu,3);
}
else
{
DisableMenuItem(dataMenu,2);
//DisableMenuItem(dataMenu,3);
}
InvalMenuBar();
}
//__________________________________________________________________
void _HYDataPanel::_CopySelectionToClipboard (void)
{
_HYSequencePane* sp = (_HYSequencePane*)GetObject(0);
_String cbStr (128L,true);
if (sp->selection.lLength)
{
for (long m=0; m<sp->speciesIndex.lLength; m++)
{
long idx = sp->speciesIndex.lData[m];
for (long k=0; k<sp->selection.lLength; k++)
{
cbStr << ((_String*)(sp->columnStrings(sp->selection.lData[k])))->sData[idx];
if (k&&((k+1)%sp->blockWidth==0))
cbStr << ' ';
}
cbStr << '\r';
}
}
else
if (sp->vselection.lLength)
for (long m=0; m<sp->vselection.lLength; m++)
{
cbStr << (_String*)(sp->rowHeaders(sp->speciesIndex(sp->vselection.lData[m])));
cbStr << '\r';
}
cbStr.Finalize();
if (cbStr.sLength)
PlaceStringInClipboard (cbStr,nil);
}
//__________________________________________________________________
void _HYDataPanel::_OmitSelectedSpecies (_SimpleList& idx)
{
MenuHandle dataMenu = GetMenuHandle (HY_DATAPANEL_MENU_ID),
omittedSpecies = GetMenuHandle (HY_DATAPANEL_HMENU_ID+3);
if (omittedSpecies)
{
_HYSequencePane* sp = (_HYSequencePane*)GetObject(0);
for (long k=0; k<idx.lLength; k++)
{
Str255 buffer;
_String* thisSpec = (_String*)sp->rowHeaders(idx.lData[k]);
StringToStr255 (*thisSpec, buffer);
InsertMenuItem (omittedSpecies,buffer,10000);
}
EnableMenuItem (dataMenu,8);
}
}
//__________________________________________________________________
void _HYDataPanel::_RestoreOmittedSequence (long index)
{
MenuHandle dataMenu = GetMenuHandle (HY_DATAPANEL_MENU_ID),
omittedSpecies = GetMenuHandle (HY_DATAPANEL_HMENU_ID+3);
if (index>=0)
{
DeleteMenuItem (omittedSpecies,index+3);
if (CountMenuItems(omittedSpecies)==2)
DisableMenuItem (dataMenu,8);
}
else
{
for (long k=0; k< omittedSeqs.lLength; k++)
DeleteMenuItem (omittedSpecies,3);
DisableMenuItem (dataMenu,8);
}
}
//__________________________________________________________________
void _HYDataPanel::_UpdatePartitionOperations (_SimpleList* sl)
{
MenuHandle dataMenu = GetMenuHandle (HY_DATAPANEL_MENU_ID);
if (sl->lData[0])
{
EnableMenuItem (dataMenu,1);
EnableMenuItem (dataMenu,11);
}
else
{
DisableMenuItem(dataMenu,1);
DisableMenuItem(dataMenu,11);
}
InvalMenuBar();
}
//__________________________________________________________________
void _HYDataPanel::_UnsetMenuBar(void)
{
//BufferToConsole ("_HYDataPanel::_UnsetMenuBar\n");
MenuHandle treeMenu = GetMenuHandle (HY_DATAPANEL_MENU_ID),
lfMenu = GetMenuHandle (HY_DATAPANEL_MENU_ID+1),
blockMenu = GetMenuHandle (HY_DATAPANEL_HMENU_ID),
repeatCharMenu = GetMenuHandle (HY_DATAPANEL_HMENU_ID+1),
nameDisplayMenu = GetMenuHandle (HY_DATAPANEL_HMENU_ID+2),
omittedSequences = GetMenuHandle (HY_DATAPANEL_HMENU_ID+3),
additionalInfo = GetMenuHandle (HY_DATAPANEL_HMENU_ID+4),
lfDisplayOptions = GetMenuHandle (HY_DATAPANEL_HMENU_ID+5),
simulateData = GetMenuHandle (HY_DATAPANEL_HMENU_ID+6),
saveSubMenu = GetMenuHandle (HY_DATAPANEL_HMENU_ID+7),
inferSubMenu = GetMenuHandle (HY_DATAPANEL_HMENU_ID+8),
dataPanelProc = GetMenuHandle (HY_DATAPANEL_HMENU_ID+9),
fMenu = GetMenuHandle (129);
DeleteMenu (HY_DATAPANEL_MENU_ID);
DeleteMenu (HY_DATAPANEL_MENU_ID+1);
DeleteMenu (HY_DATAPANEL_HMENU_ID);
DeleteMenu (HY_DATAPANEL_HMENU_ID+1);
DeleteMenu (HY_DATAPANEL_HMENU_ID+2);
DeleteMenu (HY_DATAPANEL_HMENU_ID+3);
DeleteMenu (HY_DATAPANEL_HMENU_ID+4);
DeleteMenu (HY_DATAPANEL_HMENU_ID+5);
DeleteMenu (HY_DATAPANEL_HMENU_ID+6);
DeleteMenu (HY_DATAPANEL_HMENU_ID+7);
DeleteMenu (HY_DATAPANEL_HMENU_ID+9);
DisposeMenu (treeMenu);
DisposeMenu (lfMenu);
DisposeMenu (blockMenu);
DisposeMenu (repeatCharMenu);
DisposeMenu (nameDisplayMenu);
DisposeMenu (omittedSequences);
DisposeMenu (additionalInfo);
DisposeMenu (lfDisplayOptions);
DisposeMenu (simulateData);
DisposeMenu (saveSubMenu);
DisposeMenu (dataPanelProc);
if (inferSubMenu)
{
DeleteMenu (HY_DATAPANEL_HMENU_ID+8);
DisposeMenu (inferSubMenu);
}
SetItemCmd (fMenu,4,'S');
SetItemMark(fMenu,4,noMark);
fMenu = GetMenuHandle (130);
if (!aquaInterfaceOn)
DeleteMenuItem (fMenu,13);
DeleteMenuItem (fMenu,12);
DeleteMenuItem (fMenu,11);
if (aquaInterfaceOn)
DeleteMenuItem (fMenu,10);
_HYWindow::_UnsetMenuBar();
}
//__________________________________________________________________
bool _HYDataPanel::_ProcessOSEvent (Ptr vEvent)
{
EventRecord* theEvent = (EventRecord*)vEvent;
static UInt32 lastClick = 0;
static int lastH = 0, lastV = 0;
if (!_HYTWindow::_ProcessOSEvent (vEvent))
{
if (theEvent->what==mouseDown)
{
Point localClick = theEvent->where;
GrafPtr savedPort;
GetPort(&savedPort);
#ifdef OPAQUE_TOOLBOX_STRUCTS
SetPort(GetWindowPort(theWindow));
#else
SetPort(theWindow);
#endif
GlobalToLocal (&localClick);
bool dblClick = (theEvent->when-lastClick<GetDblTime())&&(abs(localClick.h-lastH)<5)&&(abs(localClick.v-lastV)<5);
lastClick = theEvent->when;
lastH = localClick.h;
lastV = localClick.v;
int c = FindClickedCell(localClick.h,localClick.v),ch,cv;
if (c<0) return false;
if (c==1) // navBar
{
ch = localClick.h-componentL.lData[1]-thermRect.left;
cv = localClick.v-componentT.lData[1]-thermRect.top;
if (dblClick)
{
NavBarDblClick (ch);
return true;
}
if (navRect.Contains(ch,cv))
{
Point oldPt, newPt,deltaPt;
deltaPt.h = (navRect.right+navRect.left)/2-ch;
deltaPt.v = (navRect.top+navRect.bottom)/2-cv;
oldPt=localClick;
if (StillDown())
{
while (WaitMouseUp())
{
GetMouse( &newPt);
//if ( DeltaPoint(oldPt, newPt) )
if ( oldPt.h!=newPt.h )
{
oldPt=newPt;
ch = newPt.h-componentL.lData[1]+deltaPt.h;
cv = newPt.v-componentT.lData[1]+deltaPt.v;
ch-=thermRect.left;
cv-=thermRect.top;
forceUpdateForScrolling = true;
SetNavRectCenter (ch,cv);
forceUpdateForScrolling = false;
}
}
}
}
else
SetNavRectCenter (ch,cv);
return true;
}
else
if ((c==4)&&(theEvent->modifiers&controlKey))
{
_HYSequencePane* sp2 = (_HYSequencePane*)components (4);
sp2->ProcessContextualPopUp (localClick.h,localClick.v);
return true;
}
}
else
if ((theEvent->what==keyDown) || (theEvent->what==autoKey))
{
unsigned char keyCode = (theEvent->message&keyCodeMask)>>8;
if ((keyCode==0x7B)||(keyCode==0x7C)) // left/right arrow
{
_HYSequencePane* sp = (_HYSequencePane*) GetObject (0);
if ((keyCode==0x7B)&&(sp->startColumn))
sp->HScrollPane (-1);
else
if ((keyCode==0x7C)&&(sp->endColumn<sp->columnStrings.lLength))
sp->HScrollPane (1);
return true;
}
}
}
else
return true;
return false;
}
//EOF | [
"martin.audacis@gmail.com"
] | martin.audacis@gmail.com | |
17347f9925e4783cf553a87a1eaa2ce8c07e78fc | 7decc996d7af648d16a27514823c8e613c12aecc | /basic_matrix_operations_example.cc | f804263778577fac620a07750ddb778083af600d | [] | no_license | vfragoso/eigen_labs | b87074c8532b3e05d61837ffb6068f10a4f03ba6 | 10365040be577f70a3b5d13802a1e039568879e3 | refs/heads/master | 2020-09-16T16:15:00.404247 | 2016-09-09T16:50:42 | 2016-09-09T16:50:42 | 67,816,030 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,510 | cc | // Copyright (C) 2016 West Virginia University.
// 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 West Virginia University 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 HOLDERS 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.
//
// Please contact the author of this library if you have any questions.
// Author: Victor Fragoso (victor.fragoso@mail.wvu.edu)
#include <iostream>
#include <Eigen/Core> // For standard vector and matrices.
#include <Eigen/Geometry> // For cross products.
// This example illustrates how to compute matrix-matrix, matrix-vector, and
// vector-vector operations. For a quick review of more operations using Eigen
// see https://eigen.tuxfamily.org/dox/group__TutorialMatrixArithmetic.html.
int main(int argc, char** argv) {
// Let's start with vector-vector operations.
// Dot products.
Eigen::Vector3f vector1;
Eigen::Vector3f vector2;
vector1.setRandom();
vector2.setRandom();
std::cout << "vector1 (transpose): " << vector1.transpose() << "\n";
std::cout << "vector2 (transpose): " << vector2.transpose() << "\n";
std::cout << "Dot product: " << vector1.dot(vector2) << "\n";
// Computing norms.
std::cout << "vector1 (norm): " << vector1.norm() << "\n";
std::cout << "vector2 (norm): " << vector2.norm() << "\n";
// Transforming vectors into unit vectors.
Eigen::Vector3f normalized_vector1 = vector1.normalized();
// Unit vector in place.
vector1.normalize();
// Eigen overloads several operators (e.g., +, -, and *). These overlads
// allow us to call several operations very naturally.
// For instance, the addition of vectors:
const Eigen::Vector3f added_vectors = vector1 + vector2;
std::cout << "Added vectors (transpose): "
<< added_vectors.transpose() << "\n";
// Scaling a vector.
const float scalar = 5.0f;
const Eigen::Vector3f scaled_vector = scalar * vector1;
std::cout << "Original vector (norm): " << vector1.norm() << "\n";
std::cout << "Scaled Vector (norm): " << scaled_vector.norm() << "\n";
// Cross product.
const Eigen::Vector3f cross_product = vector1.cross(vector2);
std::cout << "Cross product: " << cross_product.transpose() << "\n";
// Let's review matrix-vector operations.
const Eigen::Matrix3f random_matrix = Eigen::Matrix3f::Random();
std::cout << "Matrix-vector multiplication: \n"
<< random_matrix * scaled_vector << std::endl;
// Let's review matrix-matrix operations.
// Addition.
const Eigen::Matrix3f identity = Eigen::Matrix3f::Identity();
std::cout << "Addition: \n" << identity + random_matrix << "\n";
// Multiplication.
const Eigen::Matrix3f result = identity * random_matrix;
std::cout << "Multiplication: \n" << result << "\n";
// Eigen is very efficient when several operations occur in a statement.
// It automatically finds a way internally to make the operations as efficient
// as possible.
const Eigen::Vector3f result2 =
(scalar * identity * random_matrix * scaled_vector) + added_vectors;
std::cout << "Efficient evalution of operations: "
<< result2.transpose() << "\n";
return 0;
}
| [
"victor.fragoso@mail.wvu.edu"
] | victor.fragoso@mail.wvu.edu |
fb2455bfbae5bc01370b3405025889a3df7af309 | a9072e3730a9477bdd9e3b846f5d7ade235624aa | /倒写.cpp | 19e949413426366c81d6f2e05b75992fd12a2149 | [] | no_license | maZymaZe/cpp_code | c921c978abfceb692620a46b4fce7f59cf39660d | 7486fe2a967c7a7ddb0022a052932b92a8c967c3 | refs/heads/master | 2022-05-30T16:16:56.096698 | 2022-05-24T04:42:37 | 2022-05-24T04:42:37 | 251,477,503 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 149 | cpp | #include<cstdio>
int main(){
int d[5];
for(int i=1;i<=3;i++){
scanf("%1d",&d[i]);
}
for(int i=3;i>=1;i--){
printf("%1d",d[i]);
}
return 0;
}
| [
"782618517@qq.com"
] | 782618517@qq.com |
906e8d508f5c58031291956d77df5a6b3ba752d2 | 2578cf213bd9428422f370d8ca9de7d014040a5e | /09-Texture/3D Texture.cpp | 4329adca53394a83dba7113a9d502a49d5c4af9b | [] | no_license | Yadnesh-Kulkarni/DirectX11 | 5294478e8d5ac61a247c3924968a405c5e016335 | f4bba6ee7d11e53748398395ddb4700011ae5bc4 | refs/heads/master | 2023-07-26T10:01:44.971698 | 2021-09-14T22:17:25 | 2021-09-14T22:17:25 | 406,536,327 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 39,836 | cpp | #include<Windows.h>
#include<stdio.h>
#include<d3d11.h>
#include<d3dcompiler.h>
#pragma warning( disable: 4838)
#include "XNAMath\xnamath.h"
#include "WICTextureLoader.h"
#pragma comment(lib,"d3d11.lib")
#pragma comment(lib,"USER32.lib")
#pragma comment(lib,"GDI32.lib")
#pragma comment(lib,"KERNEL32.lib")
#pragma comment(lib,"D3dcompiler.lib")
#pragma comment(lib,"DirectXTK.lib")
#define WIN_WIDTH 800
#define WIN_HEIGHT 600
LRESULT CALLBACK WndProc(HWND,UINT,WPARAM,LPARAM);
FILE *gpFile = NULL;
char gszLogFileName[] = "Log.txt";
HWND ghwnd = NULL;
DWORD dwStyle;
WINDOWPLACEMENT wpPrev = {sizeof(WINDOWPLACEMENT)};
bool gbActiveWindow = false;
bool gbEscapeKeyIsPressed = false;
bool gbFullscreen = false;
ID3D11DeviceContext *gpID3D11DeviceContext = NULL;
IDXGISwapChain *gpIDXGISwapChain = NULL;
ID3D11Device *gpID3D11Device = NULL;
ID3D11RenderTargetView *gpID3D11RenderTargetView = NULL;
ID3D11VertexShader *gpID3D11VertexShader = NULL;
ID3D11PixelShader *gpID3D11PixelShader = NULL;
ID3D11Buffer *gpID3D11Buffer_VertexBuffer_Pyramid_Position = NULL;
ID3D11Buffer *gpID3D11Buffer_VertexBuffer_Pyramid_Texture = NULL;
ID3D11Buffer *gpID3D11Buffer_VertexBuffer_Cube_Position = NULL;
ID3D11Buffer *gpID3D11Buffer_VertexBuffer_Cube_Texture = NULL;
ID3D11InputLayout *gpID3D11InputLayout = NULL;
ID3D11Buffer *gpID3D11Buffer_ConstantBuffer = NULL;
ID3D11RasterizerState *gpID3D11RasterizerState = NULL;
ID3D11DepthStencilView *gpID3D11DepthStencilView = NULL;
ID3D11ShaderResourceView *gpID3D11ShaderResourceView_Texture_Pyramid = NULL;
ID3D11ShaderResourceView *gpID3D11ShaderResourceView_Texture_Cube = NULL;
ID3D11SamplerState *gpID3D11SamplerState_Texture_Pyramid = NULL;
ID3D11SamplerState *gpID3D11SamplerState_Texture_Cube = NULL;
float pyramid_rotation = 0.0f;
float cube_rotation = 0.0f;
struct CBUFFER
{
XMMATRIX WorldViewProjectionMatrix;
};
XMMATRIX gPerspectiveProjectionMatrix;
float gClearColor[4];
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpszCmdLine,int iCmdSHow)
{
HRESULT initialize();
void display();
void uninitialize();
void update();
WNDCLASSEX wndclassex;
HWND hwnd;
TCHAR szClassName[] = TEXT("MyD3D11 Class");
bool bDone = false;
MSG msg;
if(fopen_s(&gpFile,gszLogFileName,"w")!=0)
{
MessageBox(NULL,TEXT("Log File Can Not Be Created...Exiting"),TEXT("ERROR"),MB_ICONERROR);
exit(0);
}
else
{
fprintf_s(gpFile,"Log File Is Successfully Opened.\n");
fclose(gpFile);
}
wndclassex.cbSize = sizeof(WNDCLASSEX);
wndclassex.cbClsExtra = 0;
wndclassex.cbWndExtra = 0;
wndclassex.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wndclassex.hCursor = LoadCursor(hInstance,IDC_ARROW);
wndclassex.hIcon = LoadIcon(hInstance,IDI_APPLICATION);
wndclassex.hIconSm = LoadIcon(hInstance,IDI_APPLICATION);
wndclassex.hInstance = hInstance;
wndclassex.lpfnWndProc = WndProc;
wndclassex.lpszClassName = szClassName;
wndclassex.lpszMenuName = NULL;
wndclassex.style = CS_VREDRAW | CS_HREDRAW;
if(!RegisterClassEx(&wndclassex))
{
MessageBox(NULL,TEXT("Could Not Register Class...Exiting!!!"),TEXT("Error"),MB_ICONERROR);
return 0;
}
hwnd = CreateWindow(szClassName,TEXT("Plain Window"),WS_OVERLAPPEDWINDOW,100,100,WIN_WIDTH,WIN_HEIGHT,NULL,NULL,hInstance,NULL);
if(hwnd == NULL)
{
MessageBox(NULL,TEXT("Could Not Create Window...Exiting!!!"),TEXT("Error"),MB_ICONERROR);
return 0;
}
ghwnd = hwnd;
ShowWindow(hwnd,iCmdSHow);
SetForegroundWindow(hwnd);
SetFocus(hwnd);
HRESULT hr;
hr = initialize();
if(FAILED(hr))
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"initialize() Failed...Exiting!!!.\n");
fclose(gpFile);
DestroyWindow(hwnd);
hwnd = NULL;
}
else
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"initialize() Succeeded.\n");
fclose(gpFile);
}
while(bDone == false)
{
if(PeekMessage(&msg,NULL,0,0,PM_REMOVE))
{
if(msg.message == WM_QUIT)
bDone = true;
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
else
{
update();
display();
if(gbActiveWindow == true)
{
if(gbEscapeKeyIsPressed == true)
{
bDone = true;
}
}
}
}
uninitialize();
return ((int)msg.wParam);
}
LRESULT CALLBACK WndProc(HWND hwnd,UINT iMsg,WPARAM wParam,LPARAM lParam)
{
HRESULT resize(int,int);
void ToggleFullscreen();
void uninitialize();
HRESULT hr;
switch(iMsg)
{
case WM_ACTIVATE:
if(HIWORD(wParam)==0)
gbActiveWindow = true;
else
gbActiveWindow = false;
break;
case WM_ERASEBKGND:
return(0);
case WM_SIZE:
if(gpID3D11DeviceContext)
{
hr = resize(HIWORD(lParam),LOWORD(lParam));
if(FAILED(hr))
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"resize() Failed...Exiting!!!.\n");
fclose(gpFile);
return(hr);
}
else
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"resize() Succeeded.\n");
fclose(gpFile);
}
}
break;
case WM_KEYDOWN:
switch(wParam)
{
case VK_ESCAPE:
if(gbEscapeKeyIsPressed == false)
{
gbEscapeKeyIsPressed = true;
}
break;
case 0x46:
if(gbFullscreen == false)
{
ToggleFullscreen();
gbFullscreen = true;
}
else
{
ToggleFullscreen();
gbFullscreen = false;
}
break;
default:
break;
}
break;
case WM_LBUTTONDOWN:
break;
case WM_CLOSE:
uninitialize();
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
break;
}
return (DefWindowProc(hwnd,iMsg,wParam,lParam));
}
void ToggleFullscreen()
{
MONITORINFO mi;
if(gbFullscreen == false)
{
dwStyle = GetWindowLong(ghwnd,GWL_STYLE);
if(dwStyle & WS_OVERLAPPEDWINDOW)
{
mi = { sizeof(MONITORINFO) };
if(GetWindowPlacement(ghwnd,&wpPrev) && GetMonitorInfo(MonitorFromWindow(ghwnd,MONITORINFOF_PRIMARY),&mi))
{
SetWindowLong(ghwnd,GWL_STYLE,dwStyle & ~WS_OVERLAPPEDWINDOW);
SetWindowPos(ghwnd,HWND_TOP,mi.rcMonitor.left,mi.rcMonitor.top,mi.rcMonitor.right-mi.rcMonitor.left,mi.rcMonitor.bottom-mi.rcMonitor.top,SWP_NOZORDER | SWP_FRAMECHANGED);
}
}
ShowCursor(FALSE);
}
else
{
SetWindowLong(ghwnd,GWL_STYLE,dwStyle | WS_OVERLAPPEDWINDOW);
SetWindowPlacement(ghwnd,&wpPrev);
SetWindowPos(ghwnd,HWND_TOP,0,0,0,0,SWP_NOMOVE | SWP_NOSIZE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_FRAMECHANGED);
ShowCursor(TRUE);
}
}
HRESULT initialize()
{
void uninitialize();
HRESULT LoadD3DTexture(const wchar_t *,ID3D11ShaderResourceView **);
HRESULT resize(int,int);
HRESULT hr;
D3D_DRIVER_TYPE d3dDriverType;
D3D_DRIVER_TYPE d3dDriverTypes[] = { D3D_DRIVER_TYPE_HARDWARE , D3D_DRIVER_TYPE_WARP , D3D_DRIVER_TYPE_REFERENCE };
D3D_FEATURE_LEVEL d3dFeatureLevel_required = D3D_FEATURE_LEVEL_11_0;
D3D_FEATURE_LEVEL d3dFeatureLevel_acquired = D3D_FEATURE_LEVEL_10_0;
UINT createDeviceFlags = 0;
UINT numDriverTypes = 0;
UINT numFeatureLevels = 1;
numDriverTypes = sizeof(d3dDriverTypes) / sizeof(d3dDriverTypes[0]);
DXGI_SWAP_CHAIN_DESC dxgiSwapChainDesc;
ZeroMemory((void *)&dxgiSwapChainDesc,sizeof(DXGI_SWAP_CHAIN_DESC));
dxgiSwapChainDesc.BufferCount = 1;
dxgiSwapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
dxgiSwapChainDesc.BufferDesc.Height = WIN_HEIGHT;
dxgiSwapChainDesc.BufferDesc.Width = WIN_WIDTH;
dxgiSwapChainDesc.BufferDesc.RefreshRate.Numerator = 60;
dxgiSwapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
dxgiSwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
dxgiSwapChainDesc.OutputWindow = ghwnd;
dxgiSwapChainDesc.SampleDesc.Count = 4;
dxgiSwapChainDesc.SampleDesc.Quality = 1;
dxgiSwapChainDesc.Windowed = TRUE;
for(UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++)
{
d3dDriverType = d3dDriverTypes[driverTypeIndex];
hr = D3D11CreateDeviceAndSwapChain(NULL,d3dDriverType,NULL,createDeviceFlags,&d3dFeatureLevel_required,numFeatureLevels,D3D11_SDK_VERSION,&dxgiSwapChainDesc,&gpIDXGISwapChain,&gpID3D11Device,&d3dFeatureLevel_acquired,&gpID3D11DeviceContext);
if(SUCCEEDED(hr))
break;
}
if(FAILED(hr))
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"D3D11CreateDeviceAndSwapChain() Failed...Exiting!!!.\n");
fclose(gpFile);
return(hr);
}
else
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"D3D11CreateDeviceAndSwapChain() Succeeded.\n");
fprintf_s(gpFile,"The Chosen Driver is Of : ");
if(d3dDriverType == D3D_DRIVER_TYPE_HARDWARE)
{
fprintf_s(gpFile,"Hardware Type.\n");
}
else if(d3dDriverType == D3D_DRIVER_TYPE_WARP)
{
fprintf_s(gpFile,"Warp Type.\n");
}
else if(d3dDriverType == D3D_DRIVER_TYPE_REFERENCE)
{
fprintf_s(gpFile,"Reference Type.\n");
}
fprintf_s(gpFile,"The Supported Highest Level is : ");
if(d3dFeatureLevel_acquired == D3D_FEATURE_LEVEL_11_0)
{
fprintf_s(gpFile,"11.0\n");
}
else if(d3dFeatureLevel_acquired == D3D_FEATURE_LEVEL_10_1)
{
fprintf_s(gpFile,"10.1\n");
}
else if(d3dFeatureLevel_acquired == D3D_FEATURE_LEVEL_10_0)
{
fprintf_s(gpFile,"10.0\n");
}
else
{
fprintf_s(gpFile,"Unknown\n");
}
fclose(gpFile);
}
//=============================================================VERTEX SHADER==========================================================
const char *vertexShaderSourceCode =
"cbuffer ConstantBuffer"\
"{"\
"float4x4 worldViewProjectionMatrix;"\
"}"\
"struct vertex_output"\
"{"\
"float4 position : SV_POSITION;"\
"float2 texcoord : TEXCOORD;"\
"};"\
"vertex_output main(float4 pos : POSITION,float4 tex : TEXCOORD)"\
"{"\
"vertex_output vout;"\
"vout.position = mul(worldViewProjectionMatrix,pos);"\
"vout.texcoord = tex;"\
"return(vout);"\
"}";
ID3DBlob *pID3DBlob_VertexShaderCode = NULL;
ID3DBlob *pID3DBlob_Error = NULL;
hr = D3DCompile(vertexShaderSourceCode,
lstrlenA(vertexShaderSourceCode)+1,
"VS",
NULL,
D3D_COMPILE_STANDARD_FILE_INCLUDE,
"main",
"vs_5_0",
0,
0,
&pID3DBlob_VertexShaderCode,
&pID3DBlob_Error
);
if(FAILED(hr))
{
if(pID3DBlob_Error != NULL)
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"D3DCompile() Failed For Vertex Shader : %s\n",(char *)pID3DBlob_Error->GetBufferPointer());
fclose(gpFile);
pID3DBlob_Error->Release();
pID3DBlob_Error = NULL;
return hr;
}
}
else
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"D3DCompile Succeded for Vertex Shader\n");
fclose(gpFile);
}
hr = gpID3D11Device->CreateVertexShader(pID3DBlob_VertexShaderCode->GetBufferPointer(),pID3DBlob_VertexShaderCode->GetBufferSize(),NULL,&gpID3D11VertexShader);
if(FAILED(hr))
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"CreateVertexShader() Failed \n");
fclose(gpFile);
pID3DBlob_VertexShaderCode->Release();
pID3DBlob_VertexShaderCode = NULL;
}
else
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"CreateVertexShader Succeded\n");
fclose(gpFile);
}
gpID3D11DeviceContext->VSSetShader(gpID3D11VertexShader,0,0);
//=============================================================PIXEL SHADER===================================================
const char *pixelShaderSourceCode =
"Texture2D myTexture2D;"\
"SamplerState mySamplerState;"\
"float4 main(float4 position : SV_POSITION,float2 texcoord : TEXCOORD) : SV_TARGET"\
"{"\
"float4 color = myTexture2D.Sample(mySamplerState,texcoord);"\
"return color;"\
"}";
ID3DBlob *pID3DBlob_PixelShaderCode = NULL;
pID3DBlob_Error = NULL;
hr = D3DCompile(pixelShaderSourceCode,
lstrlenA(pixelShaderSourceCode)+1,
"PS",
NULL,
D3D_COMPILE_STANDARD_FILE_INCLUDE,
"main",
"ps_5_0",
0,
0,
&pID3DBlob_PixelShaderCode,
&pID3DBlob_Error);
if(FAILED(hr))
{
if(pID3DBlob_Error != NULL)
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"D3DCompile() Failed For Pixel Shader : %s\n",(char *)pID3DBlob_Error->GetBufferPointer());
fclose(gpFile);
pID3DBlob_Error->Release();
pID3DBlob_Error = NULL;
return hr;
}
}
else
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"D3DCompile Succeded for Pixel Shader\n");
fclose(gpFile);
}
hr = gpID3D11Device->CreatePixelShader(pID3DBlob_PixelShaderCode->GetBufferPointer(),pID3DBlob_PixelShaderCode->GetBufferSize(),NULL,&gpID3D11PixelShader);
if(FAILED(hr))
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"CreatePixelShader() Failed \n");
fclose(gpFile);
pID3DBlob_PixelShaderCode->Release();
pID3DBlob_PixelShaderCode = NULL;
}
else
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"CreatePixelShader Succeded\n");
fclose(gpFile);
}
gpID3D11DeviceContext->PSSetShader(gpID3D11PixelShader,0,0);
pID3DBlob_PixelShaderCode->Release();
pID3DBlob_PixelShaderCode = NULL;
//===========================================================INITIALIZATION===============================================
//======================TRIANGLE=====================
float vertices_pyramid[] =
{
// triangle of front side
// front-top
0.0f, 1.0f, 0.0f,
// front-right
1.0f, -1.0f, -1.0f,
// front-left
-1.0f, -1.0f, -1.0f,
// triangle of right side
// right-top
0.0f, 1.0f, 0.0f,
// right-right
1.0f, -1.0f, 1.0f,
// right-left
1.0f, -1.0f, -1.0f,
// triangle of back side
// back-top
0.0f, 1.0f, 0.0f,
// back-right
-1.0f, -1.0f, 1.0f,
// back-left
1.0f, -1.0f, 1.0f,
// triangle of left side
// left-top
0.0f, 1.0f, 0.0f,
// left-right
-1.0f, -1.0f, -1.0f,
// left-left
-1.0f, -1.0f, 1.0f,
};
float texcoord_pyramid[] =
{
0.5, 1.0,
// front-right
1.0, 0.0,
// front-left
0.0, 0.0,
// triangle of right side
// right-top
0.5, 1.0,
// right-right
0.0, 0.0,
// right-left
1.0, 0.0,
// triangle of back side
// back-top
0.5, 1.0,
// back-right
0.0, 0.0,
// back-left
1.0, 0.0,
// triangle of left side
// left-top
0.5, 1.0,
// left-right
1.0, 0.0,
// left-left
0.0, 0.0,
};
//Triangle Position
D3D11_BUFFER_DESC bufferDesc;
ZeroMemory(&bufferDesc,sizeof(D3D11_BUFFER_DESC));
bufferDesc.Usage = D3D11_USAGE_DYNAMIC;
bufferDesc.ByteWidth = sizeof(float)*ARRAYSIZE(vertices_pyramid);
bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
hr = gpID3D11Device->CreateBuffer(&bufferDesc,NULL,&gpID3D11Buffer_VertexBuffer_Pyramid_Position);
if(FAILED(hr))
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"CreateBuffer() Failed \n");
fclose(gpFile);
return (hr);
}
else
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"CreateBuffer Succeded\n");
fclose(gpFile);
}
D3D11_MAPPED_SUBRESOURCE mappedSubResource;
ZeroMemory(&mappedSubResource,sizeof(D3D11_MAPPED_SUBRESOURCE));
gpID3D11DeviceContext->Map(gpID3D11Buffer_VertexBuffer_Pyramid_Position,NULL,D3D11_MAP_WRITE_DISCARD,NULL,&mappedSubResource);
memcpy(mappedSubResource.pData,vertices_pyramid,sizeof(vertices_pyramid));
gpID3D11DeviceContext->Unmap(gpID3D11Buffer_VertexBuffer_Pyramid_Position,NULL);
//======================Triangle Color============
ZeroMemory(&bufferDesc,sizeof(D3D11_BUFFER_DESC));
bufferDesc.Usage = D3D11_USAGE_DYNAMIC;
bufferDesc.ByteWidth = sizeof(float) * sizeof(texcoord_pyramid);
bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
hr = gpID3D11Device->CreateBuffer(&bufferDesc,NULL,&gpID3D11Buffer_VertexBuffer_Pyramid_Texture);
if(FAILED(hr))
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"CreateBuffer() Failed \n");
fclose(gpFile);
return (hr);
}
else
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"CreateBuffer Succeded\n");
fclose(gpFile);
}
ZeroMemory(&mappedSubResource,sizeof(D3D11_MAPPED_SUBRESOURCE));
gpID3D11DeviceContext->Map(gpID3D11Buffer_VertexBuffer_Pyramid_Texture,0,D3D11_MAP_WRITE_DISCARD,0,&mappedSubResource);
memcpy(mappedSubResource.pData,texcoord_pyramid,sizeof(texcoord_pyramid));
gpID3D11DeviceContext->Unmap(gpID3D11Buffer_VertexBuffer_Pyramid_Texture,0);
//==================QUAD==================
float vertices_cube [] =
{
// SIDE 1 ( TOP )
// triangle 1
-1.0f, +1.0f, +1.0f,
+1.0f, +1.0f, +1.0f,
-1.0f, +1.0f, -1.0f,
// triangle 2
-1.0f, +1.0f, -1.0f,
+1.0f, +1.0f, +1.0f,
+1.0f, +1.0f, -1.0f,
// SIDE 2 ( BOTTOM )
// triangle 1
+1.0f, -1.0f, -1.0f,
+1.0f, -1.0f, +1.0f,
-1.0f, -1.0f, -1.0f,
// triangle 2
-1.0f, -1.0f, -1.0f,
+1.0f, -1.0f, +1.0f,
-1.0f, -1.0f, +1.0f,
// SIDE 3 ( FRONT )
// triangle 1
-1.0f, +1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
// triangle 2
-1.0f, -1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
+1.0f, -1.0f, -1.0f,
// SIDE 4 ( BACK )
// triangle 1
+1.0f, -1.0f, +1.0f,
+1.0f, +1.0f, +1.0f,
-1.0f, -1.0f, +1.0f,
// triangle 2
-1.0f, -1.0f, +1.0f,
+1.0f, +1.0f, +1.0f,
-1.0f, +1.0f, +1.0f,
// SIDE 5 ( LEFT )
// triangle 1
-1.0f, +1.0f, +1.0f,
-1.0f, +1.0f, -1.0f,
-1.0f, -1.0f, +1.0f,
// triangle 2
-1.0f, -1.0f, +1.0f,
-1.0f, +1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
// SIDE 6 ( RIGHT )
// triangle 1
+1.0f, -1.0f, -1.0f,
+1.0f, +1.0f, -1.0f,
+1.0f, -1.0f, +1.0f,
// triangle 2
+1.0f, -1.0f, +1.0f,
+1.0f, +1.0f, -1.0f,
+1.0f, +1.0f, +1.0f,
};
float texcoord_cube[] =
{
+0.0f, +0.0f,
+0.0f, +1.0f,
+1.0f, +0.0f,
// triangle 2
+1.0f, +0.0f,
+0.0f, +1.0f,
+1.0f, +1.0f,
// SIDE 2 ( BOTTOM )
// triangle 1
+0.0f, +0.0f,
+0.0f, +1.0f,
+1.0f, +0.0f,
// triangle 2
+1.0f, +0.0f,
+0.0f, +1.0f,
+1.0f, +1.0f,
// SIDE 3 ( FRONT )
// triangle 1
+0.0f, +0.0f,
+0.0f, +1.0f,
+1.0f, +0.0f,
// triangle 2
+1.0f, +0.0f,
+0.0f, +1.0f,
+1.0f, +1.0f,
// SIDE 4 ( BACK )
// triangle 1
+0.0f, +0.0f,
+0.0f, +1.0f,
+1.0f, +0.0f,
// triangle 2
+1.0f, +0.0f,
+0.0f, +1.0f,
+1.0f, +1.0f,
// SIDE 5 ( LEFT )
// triangle 1
+0.0f, +0.0f,
+0.0f, +1.0f,
+1.0f, +0.0f,
// triangle 2
+1.0f, +0.0f,
+0.0f, +1.0f,
+1.0f, +1.0f,
// SIDE 6 ( RIGHT )
// triangle 1
+0.0f, +0.0f,
+0.0f, +1.0f,
+1.0f, +0.0f,
// triangle 2
+1.0f, +0.0f,
+0.0f, +1.0f,
+1.0f, +1.0f,
};
//Quad Position
ZeroMemory(&bufferDesc,sizeof(D3D11_BUFFER_DESC));
bufferDesc.Usage = D3D11_USAGE_DYNAMIC;
bufferDesc.ByteWidth = sizeof(float) * sizeof(vertices_cube);
bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
hr = gpID3D11Device->CreateBuffer(&bufferDesc,NULL,&gpID3D11Buffer_VertexBuffer_Cube_Position);
if(FAILED(hr))
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"CreateBuffer() Failed \n");
fclose(gpFile);
return (hr);
}
else
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"CreateBuffer Succeded\n");
fclose(gpFile);
}
ZeroMemory(&mappedSubResource,sizeof(D3D11_MAPPED_SUBRESOURCE));
gpID3D11DeviceContext->Map(gpID3D11Buffer_VertexBuffer_Cube_Position,0,D3D11_MAP_WRITE_DISCARD,0,&mappedSubResource);
memcpy(mappedSubResource.pData,vertices_cube,sizeof(vertices_cube));
gpID3D11DeviceContext->Unmap(gpID3D11Buffer_VertexBuffer_Cube_Position,0);
//Cube Color
ZeroMemory(&bufferDesc,sizeof(D3D11_BUFFER_DESC));
bufferDesc.Usage = D3D11_USAGE_DYNAMIC;
bufferDesc.ByteWidth = sizeof(float) * sizeof(texcoord_cube);
bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
hr = gpID3D11Device->CreateBuffer(&bufferDesc,NULL,&gpID3D11Buffer_VertexBuffer_Cube_Texture);
if(FAILED(hr))
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"CreateBuffer() Failed \n");
fclose(gpFile);
return (hr);
}
else
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"CreateBuffer Succeded\n");
fclose(gpFile);
}
ZeroMemory(&mappedSubResource,sizeof(D3D11_MAPPED_SUBRESOURCE));
gpID3D11DeviceContext->Map(gpID3D11Buffer_VertexBuffer_Cube_Texture,0,D3D11_MAP_WRITE_DISCARD,0,&mappedSubResource);
memcpy(mappedSubResource.pData,texcoord_cube,sizeof(texcoord_cube));
gpID3D11DeviceContext->Unmap(gpID3D11Buffer_VertexBuffer_Cube_Texture,0);
//=========================================Input Layout=================================
D3D11_INPUT_ELEMENT_DESC inputElementDesc[2];
ZeroMemory(&inputElementDesc,sizeof(D3D11_INPUT_ELEMENT_DESC));
inputElementDesc[0].SemanticName = "POSITION";
inputElementDesc[0].SemanticIndex = 0;
inputElementDesc[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
inputElementDesc[0].InputSlot = 0;
inputElementDesc[0].AlignedByteOffset = 0;
inputElementDesc[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
inputElementDesc[0].InstanceDataStepRate = 0;
inputElementDesc[1].SemanticName = "TEXCOORD";
inputElementDesc[1].SemanticIndex = 0;
inputElementDesc[1].Format = DXGI_FORMAT_R32G32_FLOAT;
inputElementDesc[1].InputSlot = 1;
inputElementDesc[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
inputElementDesc[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
inputElementDesc[1].InstanceDataStepRate = 0;
hr = gpID3D11Device->CreateInputLayout(inputElementDesc,2,pID3DBlob_VertexShaderCode->GetBufferPointer(),pID3DBlob_VertexShaderCode->GetBufferSize(),&gpID3D11InputLayout);
if(FAILED(hr))
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"CreateInputLayout() Failed \n");
fclose(gpFile);
pID3DBlob_PixelShaderCode->Release();
pID3DBlob_PixelShaderCode = NULL;
}
else
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"CreateInputLayout Succeded\n");
fclose(gpFile);
}
gpID3D11DeviceContext->IASetInputLayout(gpID3D11InputLayout);
pID3DBlob_VertexShaderCode->Release();
pID3DBlob_VertexShaderCode = NULL;
D3D11_BUFFER_DESC bufferDesc_ConstantBuffer;
ZeroMemory(&bufferDesc_ConstantBuffer,sizeof(D3D11_BUFFER_DESC));
bufferDesc_ConstantBuffer.Usage = D3D11_USAGE_DEFAULT;
bufferDesc_ConstantBuffer.ByteWidth = sizeof(CBUFFER);
bufferDesc_ConstantBuffer.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
hr = gpID3D11Device->CreateBuffer(&bufferDesc_ConstantBuffer,nullptr,&gpID3D11Buffer_ConstantBuffer);
if(FAILED(hr))
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"CreateBuffer() Failed for Constant Buffer\n");
fclose(gpFile);
return hr;
}
else
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"CreateBuffer() Succeded for Constant Buffer\n");
fclose(gpFile);
}
gpID3D11DeviceContext->VSSetConstantBuffers(0,1,&gpID3D11Buffer_ConstantBuffer);
D3D11_RASTERIZER_DESC rasterizerDesc;
ZeroMemory(&rasterizerDesc,sizeof(D3D11_RASTERIZER_DESC));
rasterizerDesc.AntialiasedLineEnable = FALSE;
rasterizerDesc.MultisampleEnable = FALSE;
rasterizerDesc.DepthBias = 0;
rasterizerDesc.DepthBiasClamp = 0.0f;
rasterizerDesc.SlopeScaledDepthBias = 0.0f;
rasterizerDesc.CullMode = D3D11_CULL_NONE;
rasterizerDesc.DepthClipEnable = TRUE;
rasterizerDesc.FillMode = D3D11_FILL_SOLID;
rasterizerDesc.FrontCounterClockwise = FALSE;
rasterizerDesc.ScissorEnable = FALSE;
gpID3D11Device->CreateRasterizerState(&rasterizerDesc,&gpID3D11RasterizerState);
gpID3D11DeviceContext->RSSetState(gpID3D11RasterizerState);
hr = LoadD3DTexture(L"Stone.bmp",&gpID3D11ShaderResourceView_Texture_Pyramid);
if(FAILED(hr))
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"LoadD3DTexture() Failed for Pyramid\n");
fclose(gpFile);
return hr;
}
else
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"LoadD3DTexture() Succeded for Pyramid\n");
fclose(gpFile);
}
D3D11_SAMPLER_DESC samplerDesc;
ZeroMemory(&samplerDesc,sizeof(D3D11_SAMPLER_DESC));
samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
hr = gpID3D11Device->CreateSamplerState(&samplerDesc,&gpID3D11SamplerState_Texture_Pyramid);
if(FAILED(hr))
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"CreateSamplerState() Failed for Pyramid\n");
fclose(gpFile);
return hr;
}
else
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"CreateSamplerState() Succeded for Pyramid\n");
fclose(gpFile);
}
hr = LoadD3DTexture(L"Kundali.bmp",&gpID3D11ShaderResourceView_Texture_Cube);
if(FAILED(hr))
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"LoadD3DTexture() Failed for Cube\n");
fclose(gpFile);
return hr;
}
else
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"LoadD3DTexture() Succeded for Cube\n");
fclose(gpFile);
}
ZeroMemory(&samplerDesc,sizeof(D3D11_SAMPLER_DESC));
samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
hr = gpID3D11Device->CreateSamplerState(&samplerDesc,&gpID3D11SamplerState_Texture_Cube);
if(FAILED(hr))
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"CreateSamplerState() Failed for Cube\n");
fclose(gpFile);
return hr;
}
else
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"CreateSamplerState() Succeded for Cube\n");
fclose(gpFile);
}
gClearColor[0] = 0.0f;
gClearColor[1] = 0.0f;
gClearColor[2] = 0.0f;
gClearColor[3] = 0.0f;
gPerspectiveProjectionMatrix = XMMatrixIdentity();
hr = resize(WIN_WIDTH,WIN_HEIGHT);
if(FAILED(hr))
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"Resize() Failed...Exiting!!!.\n");
fclose(gpFile);
return(hr);
}
else
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"Resize() Succeeded.\n");
fclose(gpFile);
}
return (S_OK);
}
HRESULT LoadD3DTexture(const wchar_t *textureFileName,ID3D11ShaderResourceView **ppID3D11ShaderResourceView)
{
HRESULT hr;
hr = DirectX::CreateWICTextureFromFile(gpID3D11Device,gpID3D11DeviceContext,textureFileName,NULL,ppID3D11ShaderResourceView);
if(FAILED(hr))
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"CreateWICTextureFromFile() Failed...Exiting!!!.\n");
fclose(gpFile);
return(hr);
}
else
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"CreateWICTextureFromFile() Succeeded.\n");
fclose(gpFile);
}
return hr;
}
HRESULT resize(int width,int height)
{
HRESULT hr = S_OK;
if(gpID3D11DepthStencilView)
{
gpID3D11DepthStencilView->Release();
gpID3D11DepthStencilView = NULL;
}
if(gpID3D11RenderTargetView)
{
gpID3D11RenderTargetView->Release();
gpID3D11RenderTargetView = NULL;
}
gpIDXGISwapChain->ResizeBuffers(1,width,height,DXGI_FORMAT_R8G8B8A8_UNORM,0);
ID3D11Texture2D *pID3D11Texture2D_BackBuffer;
gpIDXGISwapChain->GetBuffer(0,__uuidof(ID3D11Texture2D),(LPVOID *)&pID3D11Texture2D_BackBuffer);
hr = gpID3D11Device->CreateRenderTargetView(pID3D11Texture2D_BackBuffer,NULL,&gpID3D11RenderTargetView);
if(FAILED(hr))
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"ID3D11Device::CreateRenderTargetView() Failed...Exiting!!!.\n");
fclose(gpFile);
return(hr);
}
else
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"ID3D11Device::CreateRenderTargetView() Succeeded.\n");
fclose(gpFile);
}
pID3D11Texture2D_BackBuffer->Release();
pID3D11Texture2D_BackBuffer = NULL;
D3D11_TEXTURE2D_DESC depthDesc;
ZeroMemory(&depthDesc,sizeof(D3D11_TEXTURE2D_DESC));
depthDesc.Width = width;
depthDesc.Height = height;
depthDesc.ArraySize = 1;
depthDesc.MipLevels = 1;
depthDesc.SampleDesc.Count = 4;
depthDesc.SampleDesc.Quality = 1;
depthDesc.Format = DXGI_FORMAT_D32_FLOAT;
depthDesc.Usage = D3D11_USAGE_DEFAULT;
depthDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
depthDesc.CPUAccessFlags = 0;
depthDesc.MiscFlags = 0;
ID3D11Texture2D *pID3D11Texture2D_Depth = NULL;
hr = gpID3D11Device->CreateTexture2D(&depthDesc,NULL,&pID3D11Texture2D_Depth);
if(FAILED(hr))
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"ID3D11Device::CreateTexture2D() Failed...Exiting!!!.\n");
fclose(gpFile);
return(hr);
}
else
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"ID3D11Device::CreateTexture2D() Succeeded.\n");
fclose(gpFile);
}
D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc;
ZeroMemory(&dsvDesc,sizeof(D3D11_DEPTH_STENCIL_VIEW_DESC));
dsvDesc.Format = DXGI_FORMAT_D32_FLOAT;
dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMS;
hr = gpID3D11Device->CreateDepthStencilView(pID3D11Texture2D_Depth,&dsvDesc,&gpID3D11DepthStencilView);
if(FAILED(hr))
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"ID3D11Device::CreateDepthStencilView() Failed...Exiting!!!.\n");
fclose(gpFile);
return(hr);
}
else
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"ID3D11Device::CreateDepthStencilView() Succeeded.\n");
fclose(gpFile);
}
pID3D11Texture2D_Depth->Release();
pID3D11Texture2D_Depth = NULL;
gpID3D11DeviceContext->OMSetRenderTargets(1,&gpID3D11RenderTargetView,gpID3D11DepthStencilView);
D3D11_VIEWPORT d3d11ViewPort;
d3d11ViewPort.TopLeftX = 0;
d3d11ViewPort.TopLeftY = 0;
d3d11ViewPort.Width = (float)width;
d3d11ViewPort.Height = (float)height;
d3d11ViewPort.MinDepth = 0.0f;
d3d11ViewPort.MaxDepth = 1.0f;
gpID3D11DeviceContext->RSSetViewports(1,&d3d11ViewPort);
gPerspectiveProjectionMatrix = XMMatrixPerspectiveFovLH(XMConvertToRadians(45.0f),(float)width/(float)height,0.1f,100.0f);
return hr;
}
void display()
{
gpID3D11DeviceContext->ClearRenderTargetView(gpID3D11RenderTargetView,gClearColor);
gpID3D11DeviceContext->ClearDepthStencilView(gpID3D11DepthStencilView,D3D11_CLEAR_DEPTH,1.0f,0);
//Triangle
UINT stride = sizeof(float) * 3;
UINT offset = 0;
gpID3D11DeviceContext->IASetVertexBuffers(0,1,&gpID3D11Buffer_VertexBuffer_Pyramid_Position,&stride,&offset);
stride = sizeof(float) * 2;
gpID3D11DeviceContext->IASetVertexBuffers(1,1,&gpID3D11Buffer_VertexBuffer_Pyramid_Texture,&stride,&offset);
gpID3D11DeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
gpID3D11DeviceContext->PSSetShaderResources(0,1,&gpID3D11ShaderResourceView_Texture_Pyramid);
gpID3D11DeviceContext->PSSetSamplers(0,1,&gpID3D11SamplerState_Texture_Pyramid);
XMMATRIX worldMatrix = XMMatrixIdentity();
XMMATRIX viewMatrix = XMMatrixIdentity();
XMMATRIX rotationMatrix = XMMatrixIdentity();
rotationMatrix = XMMatrixRotationY(pyramid_rotation);
worldMatrix = XMMatrixTranslation(-1.5f,0.0f,12.0f);
worldMatrix = rotationMatrix * worldMatrix;
XMMATRIX wvpMatrix = worldMatrix * viewMatrix * gPerspectiveProjectionMatrix;
CBUFFER constantBuffer;
constantBuffer.WorldViewProjectionMatrix = wvpMatrix;
gpID3D11DeviceContext->UpdateSubresource(gpID3D11Buffer_ConstantBuffer,0,NULL,&constantBuffer,0,0);
gpID3D11DeviceContext->Draw(3,0);
gpID3D11DeviceContext->Draw(3,3);
gpID3D11DeviceContext->Draw(3,6);
gpID3D11DeviceContext->Draw(3,9);
//Quad
stride = sizeof(float) * 3;
gpID3D11DeviceContext->IASetVertexBuffers(0,1,&gpID3D11Buffer_VertexBuffer_Cube_Position,&stride,&offset);
stride = sizeof(float) * 2;
gpID3D11DeviceContext->IASetVertexBuffers(1,1,&gpID3D11Buffer_VertexBuffer_Cube_Texture,&stride,&offset);
gpID3D11DeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
gpID3D11DeviceContext->PSSetShaderResources(0,1,&gpID3D11ShaderResourceView_Texture_Cube);
gpID3D11DeviceContext->PSSetSamplers(0,1,&gpID3D11SamplerState_Texture_Cube);
worldMatrix = XMMatrixIdentity();
viewMatrix = XMMatrixIdentity();
rotationMatrix = XMMatrixIdentity();
XMMATRIX rotationMatrixX = XMMatrixIdentity();
XMMATRIX rotationMatrixY = XMMatrixIdentity();
XMMATRIX rotationMatrixZ = XMMatrixIdentity();
rotationMatrixX = XMMatrixRotationX(cube_rotation);
rotationMatrixY = XMMatrixRotationY(cube_rotation);
rotationMatrixZ = XMMatrixRotationZ(cube_rotation);
rotationMatrix = rotationMatrixX * rotationMatrixY * rotationMatrixZ;
XMMATRIX scaleMatrix = XMMatrixScaling(0.75f,0.75f,0.75f);
worldMatrix = XMMatrixTranslation(1.5f,0.0f,12.0f);
worldMatrix = scaleMatrix * rotationMatrix * worldMatrix;
wvpMatrix = worldMatrix * viewMatrix * gPerspectiveProjectionMatrix;
constantBuffer.WorldViewProjectionMatrix = wvpMatrix;
gpID3D11DeviceContext->UpdateSubresource(gpID3D11Buffer_ConstantBuffer,0,NULL,&constantBuffer,0,0);
gpID3D11DeviceContext->Draw(6,0);
gpID3D11DeviceContext->Draw(6,6);
gpID3D11DeviceContext->Draw(6,12);
gpID3D11DeviceContext->Draw(6,18);
gpID3D11DeviceContext->Draw(6,24);
gpID3D11DeviceContext->Draw(6,30);
gpIDXGISwapChain->Present(0,0);
}
void update()
{
pyramid_rotation = pyramid_rotation + 0.005f;
if(pyramid_rotation >= 360.0f)
pyramid_rotation = 0.0f;
cube_rotation = cube_rotation + 0.005f;
if(cube_rotation >= 360.0f)
cube_rotation = 0.0f;
}
void uninitialize()
{
if(gpID3D11SamplerState_Texture_Cube)
{
gpID3D11SamplerState_Texture_Cube->Release();
gpID3D11SamplerState_Texture_Cube = NULL;
}
if(gpID3D11ShaderResourceView_Texture_Cube)
{
gpID3D11ShaderResourceView_Texture_Cube->Release();
gpID3D11ShaderResourceView_Texture_Cube = NULL;
}
if(gpID3D11SamplerState_Texture_Pyramid)
{
gpID3D11SamplerState_Texture_Pyramid->Release();
gpID3D11SamplerState_Texture_Pyramid = NULL;
}
if(gpID3D11ShaderResourceView_Texture_Pyramid)
{
gpID3D11ShaderResourceView_Texture_Pyramid->Release();
gpID3D11ShaderResourceView_Texture_Pyramid = NULL;
}
if(gpID3D11RasterizerState)
{
gpID3D11RasterizerState->Release();
gpID3D11RasterizerState = NULL;
}
if(gpID3D11Buffer_ConstantBuffer)
{
gpID3D11Buffer_ConstantBuffer->Release();
gpID3D11Buffer_ConstantBuffer = NULL;
}
if(gpID3D11InputLayout)
{
gpID3D11InputLayout->Release();
gpID3D11InputLayout = NULL;
}
if(gpID3D11Buffer_VertexBuffer_Cube_Texture)
{
gpID3D11Buffer_VertexBuffer_Cube_Texture->Release();
gpID3D11Buffer_VertexBuffer_Cube_Texture = NULL;
}
if(gpID3D11Buffer_VertexBuffer_Cube_Position)
{
gpID3D11Buffer_VertexBuffer_Cube_Position->Release();
gpID3D11Buffer_VertexBuffer_Cube_Position = NULL;
}
if(gpID3D11Buffer_VertexBuffer_Pyramid_Texture)
{
gpID3D11Buffer_VertexBuffer_Pyramid_Texture->Release();
gpID3D11Buffer_VertexBuffer_Pyramid_Texture = NULL;
}
if(gpID3D11Buffer_VertexBuffer_Pyramid_Position)
{
gpID3D11Buffer_VertexBuffer_Pyramid_Position->Release();
gpID3D11Buffer_VertexBuffer_Pyramid_Position = NULL;
}
if(gpID3D11PixelShader)
{
gpID3D11PixelShader->Release();
gpID3D11PixelShader = NULL;
}
if(gpID3D11VertexShader)
{
gpID3D11VertexShader->Release();
gpID3D11VertexShader = NULL;
}
if(gpID3D11DepthStencilView)
{
gpID3D11DepthStencilView->Release();
gpID3D11DepthStencilView = NULL;
}
if(gpID3D11RenderTargetView)
{
gpID3D11RenderTargetView->Release();
gpID3D11RenderTargetView = NULL;
}
if(gpIDXGISwapChain)
{
gpIDXGISwapChain->Release();
gpIDXGISwapChain = NULL;
}
if(gpID3D11DeviceContext)
{
gpID3D11DeviceContext->Release();
gpID3D11DeviceContext = NULL;
}
if(gpID3D11Device)
{
gpID3D11Device->Release();
gpID3D11Device = NULL;
}
if(gpFile)
{
fopen_s(&gpFile,gszLogFileName,"a+");
fprintf_s(gpFile,"Uninitialize() Succeeded!!!.\n");
fprintf_s(gpFile,"Log File is Successfully Closed.\n");
fclose(gpFile);
}
} | [
"ykulkar2@uncc.edu"
] | ykulkar2@uncc.edu |
591d08f58de87ed65422e0cc1ce25a0f93bd6e02 | ee57390d0b7c7299ab37939a3c9b11e427b470ad | /lib/Target/AMDGPU/SIMachineFunctionInfo.h | 8c38cdae5d960087e466bac1630b3909ff8d35af | [
"NCSA"
] | permissive | Hatelix/NyuziToolchain | 2bf3af1da8f63f131590d9d245ea4003ebe0a4c8 | f7f036b55c1839328ee630a1d81919d1f294e801 | refs/heads/master | 2020-04-04T14:17:08.192165 | 2018-05-12T19:33:08 | 2018-05-12T19:33:08 | 155,993,376 | 0 | 0 | NOASSERTION | 2018-11-03T14:56:39 | 2018-11-03T14:56:39 | null | UTF-8 | C++ | false | false | 18,529 | h | //==- SIMachineFunctionInfo.h - SIMachineFunctionInfo interface --*- C++ -*-==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// \file
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_TARGET_AMDGPU_SIMACHINEFUNCTIONINFO_H
#define LLVM_LIB_TARGET_AMDGPU_SIMACHINEFUNCTIONINFO_H
#include "AMDGPUArgumentUsageInfo.h"
#include "AMDGPUMachineFunction.h"
#include "SIRegisterInfo.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/CodeGen/PseudoSourceValue.h"
#include "llvm/CodeGen/TargetInstrInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/Support/ErrorHandling.h"
#include <array>
#include <cassert>
#include <utility>
#include <vector>
namespace llvm {
class MachineFrameInfo;
class MachineFunction;
class SIInstrInfo;
class TargetRegisterClass;
class AMDGPUImagePseudoSourceValue : public PseudoSourceValue {
public:
// TODO: Is the img rsrc useful?
explicit AMDGPUImagePseudoSourceValue(const TargetInstrInfo &TII) :
PseudoSourceValue(PseudoSourceValue::TargetCustom, TII) {}
bool isConstant(const MachineFrameInfo *) const override {
// This should probably be true for most images, but we will start by being
// conservative.
return false;
}
bool isAliased(const MachineFrameInfo *) const override {
return true;
}
bool mayAlias(const MachineFrameInfo *) const override {
return true;
}
};
class AMDGPUBufferPseudoSourceValue : public PseudoSourceValue {
public:
explicit AMDGPUBufferPseudoSourceValue(const TargetInstrInfo &TII) :
PseudoSourceValue(PseudoSourceValue::TargetCustom, TII) { }
bool isConstant(const MachineFrameInfo *) const override {
// This should probably be true for most images, but we will start by being
// conservative.
return false;
}
bool isAliased(const MachineFrameInfo *) const override {
return true;
}
bool mayAlias(const MachineFrameInfo *) const override {
return true;
}
};
/// This class keeps track of the SPI_SP_INPUT_ADDR config register, which
/// tells the hardware which interpolation parameters to load.
class SIMachineFunctionInfo final : public AMDGPUMachineFunction {
unsigned TIDReg = AMDGPU::NoRegister;
// Registers that may be reserved for spilling purposes. These may be the same
// as the input registers.
unsigned ScratchRSrcReg = AMDGPU::PRIVATE_RSRC_REG;
unsigned ScratchWaveOffsetReg = AMDGPU::SCRATCH_WAVE_OFFSET_REG;
// This is the current function's incremented size from the kernel's scratch
// wave offset register. For an entry function, this is exactly the same as
// the ScratchWaveOffsetReg.
unsigned FrameOffsetReg = AMDGPU::FP_REG;
// Top of the stack SGPR offset derived from the ScratchWaveOffsetReg.
unsigned StackPtrOffsetReg = AMDGPU::SP_REG;
AMDGPUFunctionArgInfo ArgInfo;
// Graphics info.
unsigned PSInputAddr = 0;
unsigned PSInputEnable = 0;
/// Number of bytes of arguments this function has on the stack. If the callee
/// is expected to restore the argument stack this should be a multiple of 16,
/// all usable during a tail call.
///
/// The alternative would forbid tail call optimisation in some cases: if we
/// want to transfer control from a function with 8-bytes of stack-argument
/// space to a function with 16-bytes then misalignment of this value would
/// make a stack adjustment necessary, which could not be undone by the
/// callee.
unsigned BytesInStackArgArea = 0;
bool ReturnsVoid = true;
// A pair of default/requested minimum/maximum flat work group sizes.
// Minimum - first, maximum - second.
std::pair<unsigned, unsigned> FlatWorkGroupSizes = {0, 0};
// A pair of default/requested minimum/maximum number of waves per execution
// unit. Minimum - first, maximum - second.
std::pair<unsigned, unsigned> WavesPerEU = {0, 0};
// Stack object indices for work group IDs.
std::array<int, 3> DebuggerWorkGroupIDStackObjectIndices = {{0, 0, 0}};
// Stack object indices for work item IDs.
std::array<int, 3> DebuggerWorkItemIDStackObjectIndices = {{0, 0, 0}};
DenseMap<const Value *,
std::unique_ptr<const AMDGPUBufferPseudoSourceValue>> BufferPSVs;
DenseMap<const Value *,
std::unique_ptr<const AMDGPUImagePseudoSourceValue>> ImagePSVs;
private:
unsigned LDSWaveSpillSize = 0;
unsigned NumUserSGPRs = 0;
unsigned NumSystemSGPRs = 0;
bool HasSpilledSGPRs = false;
bool HasSpilledVGPRs = false;
bool HasNonSpillStackObjects = false;
bool IsStackRealigned = false;
unsigned NumSpilledSGPRs = 0;
unsigned NumSpilledVGPRs = 0;
// Feature bits required for inputs passed in user SGPRs.
bool PrivateSegmentBuffer : 1;
bool DispatchPtr : 1;
bool QueuePtr : 1;
bool KernargSegmentPtr : 1;
bool DispatchID : 1;
bool FlatScratchInit : 1;
bool GridWorkgroupCountX : 1;
bool GridWorkgroupCountY : 1;
bool GridWorkgroupCountZ : 1;
// Feature bits required for inputs passed in system SGPRs.
bool WorkGroupIDX : 1; // Always initialized.
bool WorkGroupIDY : 1;
bool WorkGroupIDZ : 1;
bool WorkGroupInfo : 1;
bool PrivateSegmentWaveByteOffset : 1;
bool WorkItemIDX : 1; // Always initialized.
bool WorkItemIDY : 1;
bool WorkItemIDZ : 1;
// Private memory buffer
// Compute directly in sgpr[0:1]
// Other shaders indirect 64-bits at sgpr[0:1]
bool ImplicitBufferPtr : 1;
// Pointer to where the ABI inserts special kernel arguments separate from the
// user arguments. This is an offset from the KernargSegmentPtr.
bool ImplicitArgPtr : 1;
// The hard-wired high half of the address of the global information table
// for AMDPAL OS type. 0xffffffff represents no hard-wired high half, since
// current hardware only allows a 16 bit value.
unsigned GITPtrHigh;
unsigned HighBitsOf32BitAddress;
MCPhysReg getNextUserSGPR() const {
assert(NumSystemSGPRs == 0 && "System SGPRs must be added after user SGPRs");
return AMDGPU::SGPR0 + NumUserSGPRs;
}
MCPhysReg getNextSystemSGPR() const {
return AMDGPU::SGPR0 + NumUserSGPRs + NumSystemSGPRs;
}
public:
struct SpilledReg {
unsigned VGPR = AMDGPU::NoRegister;
int Lane = -1;
SpilledReg() = default;
SpilledReg(unsigned R, int L) : VGPR (R), Lane (L) {}
bool hasLane() { return Lane != -1;}
bool hasReg() { return VGPR != AMDGPU::NoRegister;}
};
struct SGPRSpillVGPRCSR {
// VGPR used for SGPR spills
unsigned VGPR;
// If the VGPR is a CSR, the stack slot used to save/restore it in the
// prolog/epilog.
Optional<int> FI;
SGPRSpillVGPRCSR(unsigned V, Optional<int> F) : VGPR(V), FI(F) {}
};
private:
// SGPR->VGPR spilling support.
using SpillRegMask = std::pair<unsigned, unsigned>;
// Track VGPR + wave index for each subregister of the SGPR spilled to
// frameindex key.
DenseMap<int, std::vector<SpilledReg>> SGPRToVGPRSpills;
unsigned NumVGPRSpillLanes = 0;
SmallVector<SGPRSpillVGPRCSR, 2> SpillVGPRs;
public:
SIMachineFunctionInfo(const MachineFunction &MF);
ArrayRef<SpilledReg> getSGPRToVGPRSpills(int FrameIndex) const {
auto I = SGPRToVGPRSpills.find(FrameIndex);
return (I == SGPRToVGPRSpills.end()) ?
ArrayRef<SpilledReg>() : makeArrayRef(I->second);
}
ArrayRef<SGPRSpillVGPRCSR> getSGPRSpillVGPRs() const {
return SpillVGPRs;
}
bool allocateSGPRSpillToVGPR(MachineFunction &MF, int FI);
void removeSGPRToVGPRFrameIndices(MachineFrameInfo &MFI);
bool hasCalculatedTID() const { return TIDReg != AMDGPU::NoRegister; }
unsigned getTIDReg() const { return TIDReg; }
void setTIDReg(unsigned Reg) { TIDReg = Reg; }
unsigned getBytesInStackArgArea() const {
return BytesInStackArgArea;
}
void setBytesInStackArgArea(unsigned Bytes) {
BytesInStackArgArea = Bytes;
}
// Add user SGPRs.
unsigned addPrivateSegmentBuffer(const SIRegisterInfo &TRI);
unsigned addDispatchPtr(const SIRegisterInfo &TRI);
unsigned addQueuePtr(const SIRegisterInfo &TRI);
unsigned addKernargSegmentPtr(const SIRegisterInfo &TRI);
unsigned addDispatchID(const SIRegisterInfo &TRI);
unsigned addFlatScratchInit(const SIRegisterInfo &TRI);
unsigned addImplicitBufferPtr(const SIRegisterInfo &TRI);
// Add system SGPRs.
unsigned addWorkGroupIDX() {
ArgInfo.WorkGroupIDX = ArgDescriptor::createRegister(getNextSystemSGPR());
NumSystemSGPRs += 1;
return ArgInfo.WorkGroupIDX.getRegister();
}
unsigned addWorkGroupIDY() {
ArgInfo.WorkGroupIDY = ArgDescriptor::createRegister(getNextSystemSGPR());
NumSystemSGPRs += 1;
return ArgInfo.WorkGroupIDY.getRegister();
}
unsigned addWorkGroupIDZ() {
ArgInfo.WorkGroupIDZ = ArgDescriptor::createRegister(getNextSystemSGPR());
NumSystemSGPRs += 1;
return ArgInfo.WorkGroupIDZ.getRegister();
}
unsigned addWorkGroupInfo() {
ArgInfo.WorkGroupInfo = ArgDescriptor::createRegister(getNextSystemSGPR());
NumSystemSGPRs += 1;
return ArgInfo.WorkGroupInfo.getRegister();
}
// Add special VGPR inputs
void setWorkItemIDX(ArgDescriptor Arg) {
ArgInfo.WorkItemIDX = Arg;
}
void setWorkItemIDY(ArgDescriptor Arg) {
ArgInfo.WorkItemIDY = Arg;
}
void setWorkItemIDZ(ArgDescriptor Arg) {
ArgInfo.WorkItemIDZ = Arg;
}
unsigned addPrivateSegmentWaveByteOffset() {
ArgInfo.PrivateSegmentWaveByteOffset
= ArgDescriptor::createRegister(getNextSystemSGPR());
NumSystemSGPRs += 1;
return ArgInfo.PrivateSegmentWaveByteOffset.getRegister();
}
void setPrivateSegmentWaveByteOffset(unsigned Reg) {
ArgInfo.PrivateSegmentWaveByteOffset = ArgDescriptor::createRegister(Reg);
}
bool hasPrivateSegmentBuffer() const {
return PrivateSegmentBuffer;
}
bool hasDispatchPtr() const {
return DispatchPtr;
}
bool hasQueuePtr() const {
return QueuePtr;
}
bool hasKernargSegmentPtr() const {
return KernargSegmentPtr;
}
bool hasDispatchID() const {
return DispatchID;
}
bool hasFlatScratchInit() const {
return FlatScratchInit;
}
bool hasGridWorkgroupCountX() const {
return GridWorkgroupCountX;
}
bool hasGridWorkgroupCountY() const {
return GridWorkgroupCountY;
}
bool hasGridWorkgroupCountZ() const {
return GridWorkgroupCountZ;
}
bool hasWorkGroupIDX() const {
return WorkGroupIDX;
}
bool hasWorkGroupIDY() const {
return WorkGroupIDY;
}
bool hasWorkGroupIDZ() const {
return WorkGroupIDZ;
}
bool hasWorkGroupInfo() const {
return WorkGroupInfo;
}
bool hasPrivateSegmentWaveByteOffset() const {
return PrivateSegmentWaveByteOffset;
}
bool hasWorkItemIDX() const {
return WorkItemIDX;
}
bool hasWorkItemIDY() const {
return WorkItemIDY;
}
bool hasWorkItemIDZ() const {
return WorkItemIDZ;
}
bool hasImplicitArgPtr() const {
return ImplicitArgPtr;
}
bool hasImplicitBufferPtr() const {
return ImplicitBufferPtr;
}
AMDGPUFunctionArgInfo &getArgInfo() {
return ArgInfo;
}
const AMDGPUFunctionArgInfo &getArgInfo() const {
return ArgInfo;
}
std::pair<const ArgDescriptor *, const TargetRegisterClass *>
getPreloadedValue(AMDGPUFunctionArgInfo::PreloadedValue Value) const {
return ArgInfo.getPreloadedValue(Value);
}
unsigned getPreloadedReg(AMDGPUFunctionArgInfo::PreloadedValue Value) const {
return ArgInfo.getPreloadedValue(Value).first->getRegister();
}
unsigned getGITPtrHigh() const {
return GITPtrHigh;
}
unsigned get32BitAddressHighBits() const {
return HighBitsOf32BitAddress;
}
unsigned getNumUserSGPRs() const {
return NumUserSGPRs;
}
unsigned getNumPreloadedSGPRs() const {
return NumUserSGPRs + NumSystemSGPRs;
}
unsigned getPrivateSegmentWaveByteOffsetSystemSGPR() const {
return ArgInfo.PrivateSegmentWaveByteOffset.getRegister();
}
/// \brief Returns the physical register reserved for use as the resource
/// descriptor for scratch accesses.
unsigned getScratchRSrcReg() const {
return ScratchRSrcReg;
}
void setScratchRSrcReg(unsigned Reg) {
assert(Reg != AMDGPU::NoRegister && "Should never be unset");
ScratchRSrcReg = Reg;
}
unsigned getScratchWaveOffsetReg() const {
return ScratchWaveOffsetReg;
}
unsigned getFrameOffsetReg() const {
return FrameOffsetReg;
}
void setStackPtrOffsetReg(unsigned Reg) {
StackPtrOffsetReg = Reg;
}
// Note the unset value for this is AMDGPU::SP_REG rather than
// NoRegister. This is mostly a workaround for MIR tests where state that
// can't be directly computed from the function is not preserved in serialized
// MIR.
unsigned getStackPtrOffsetReg() const {
return StackPtrOffsetReg;
}
void setScratchWaveOffsetReg(unsigned Reg) {
assert(Reg != AMDGPU::NoRegister && "Should never be unset");
ScratchWaveOffsetReg = Reg;
if (isEntryFunction())
FrameOffsetReg = ScratchWaveOffsetReg;
}
unsigned getQueuePtrUserSGPR() const {
return ArgInfo.QueuePtr.getRegister();
}
unsigned getImplicitBufferPtrUserSGPR() const {
return ArgInfo.ImplicitBufferPtr.getRegister();
}
bool hasSpilledSGPRs() const {
return HasSpilledSGPRs;
}
void setHasSpilledSGPRs(bool Spill = true) {
HasSpilledSGPRs = Spill;
}
bool hasSpilledVGPRs() const {
return HasSpilledVGPRs;
}
void setHasSpilledVGPRs(bool Spill = true) {
HasSpilledVGPRs = Spill;
}
bool hasNonSpillStackObjects() const {
return HasNonSpillStackObjects;
}
void setHasNonSpillStackObjects(bool StackObject = true) {
HasNonSpillStackObjects = StackObject;
}
bool isStackRealigned() const {
return IsStackRealigned;
}
void setIsStackRealigned(bool Realigned = true) {
IsStackRealigned = Realigned;
}
unsigned getNumSpilledSGPRs() const {
return NumSpilledSGPRs;
}
unsigned getNumSpilledVGPRs() const {
return NumSpilledVGPRs;
}
void addToSpilledSGPRs(unsigned num) {
NumSpilledSGPRs += num;
}
void addToSpilledVGPRs(unsigned num) {
NumSpilledVGPRs += num;
}
unsigned getPSInputAddr() const {
return PSInputAddr;
}
unsigned getPSInputEnable() const {
return PSInputEnable;
}
bool isPSInputAllocated(unsigned Index) const {
return PSInputAddr & (1 << Index);
}
void markPSInputAllocated(unsigned Index) {
PSInputAddr |= 1 << Index;
}
void markPSInputEnabled(unsigned Index) {
PSInputEnable |= 1 << Index;
}
bool returnsVoid() const {
return ReturnsVoid;
}
void setIfReturnsVoid(bool Value) {
ReturnsVoid = Value;
}
/// \returns A pair of default/requested minimum/maximum flat work group sizes
/// for this function.
std::pair<unsigned, unsigned> getFlatWorkGroupSizes() const {
return FlatWorkGroupSizes;
}
/// \returns Default/requested minimum flat work group size for this function.
unsigned getMinFlatWorkGroupSize() const {
return FlatWorkGroupSizes.first;
}
/// \returns Default/requested maximum flat work group size for this function.
unsigned getMaxFlatWorkGroupSize() const {
return FlatWorkGroupSizes.second;
}
/// \returns A pair of default/requested minimum/maximum number of waves per
/// execution unit.
std::pair<unsigned, unsigned> getWavesPerEU() const {
return WavesPerEU;
}
/// \returns Default/requested minimum number of waves per execution unit.
unsigned getMinWavesPerEU() const {
return WavesPerEU.first;
}
/// \returns Default/requested maximum number of waves per execution unit.
unsigned getMaxWavesPerEU() const {
return WavesPerEU.second;
}
/// \returns Stack object index for \p Dim's work group ID.
int getDebuggerWorkGroupIDStackObjectIndex(unsigned Dim) const {
assert(Dim < 3);
return DebuggerWorkGroupIDStackObjectIndices[Dim];
}
/// \brief Sets stack object index for \p Dim's work group ID to \p ObjectIdx.
void setDebuggerWorkGroupIDStackObjectIndex(unsigned Dim, int ObjectIdx) {
assert(Dim < 3);
DebuggerWorkGroupIDStackObjectIndices[Dim] = ObjectIdx;
}
/// \returns Stack object index for \p Dim's work item ID.
int getDebuggerWorkItemIDStackObjectIndex(unsigned Dim) const {
assert(Dim < 3);
return DebuggerWorkItemIDStackObjectIndices[Dim];
}
/// \brief Sets stack object index for \p Dim's work item ID to \p ObjectIdx.
void setDebuggerWorkItemIDStackObjectIndex(unsigned Dim, int ObjectIdx) {
assert(Dim < 3);
DebuggerWorkItemIDStackObjectIndices[Dim] = ObjectIdx;
}
/// \returns SGPR used for \p Dim's work group ID.
unsigned getWorkGroupIDSGPR(unsigned Dim) const {
switch (Dim) {
case 0:
assert(hasWorkGroupIDX());
return ArgInfo.WorkGroupIDX.getRegister();
case 1:
assert(hasWorkGroupIDY());
return ArgInfo.WorkGroupIDY.getRegister();
case 2:
assert(hasWorkGroupIDZ());
return ArgInfo.WorkGroupIDZ.getRegister();
}
llvm_unreachable("unexpected dimension");
}
/// \returns VGPR used for \p Dim' work item ID.
unsigned getWorkItemIDVGPR(unsigned Dim) const {
switch (Dim) {
case 0:
assert(hasWorkItemIDX());
return AMDGPU::VGPR0;
case 1:
assert(hasWorkItemIDY());
return AMDGPU::VGPR1;
case 2:
assert(hasWorkItemIDZ());
return AMDGPU::VGPR2;
}
llvm_unreachable("unexpected dimension");
}
unsigned getLDSWaveSpillSize() const {
return LDSWaveSpillSize;
}
const AMDGPUBufferPseudoSourceValue *getBufferPSV(const SIInstrInfo &TII,
const Value *BufferRsrc) {
assert(BufferRsrc);
auto PSV = BufferPSVs.try_emplace(
BufferRsrc,
llvm::make_unique<AMDGPUBufferPseudoSourceValue>(TII));
return PSV.first->second.get();
}
const AMDGPUImagePseudoSourceValue *getImagePSV(const SIInstrInfo &TII,
const Value *ImgRsrc) {
assert(ImgRsrc);
auto PSV = ImagePSVs.try_emplace(
ImgRsrc,
llvm::make_unique<AMDGPUImagePseudoSourceValue>(TII));
return PSV.first->second.get();
}
};
} // end namespace llvm
#endif // LLVM_LIB_TARGET_AMDGPU_SIMACHINEFUNCTIONINFO_H
| [
"jeffbush001@gmail.com"
] | jeffbush001@gmail.com |
beda68bab3c17aea02d36bf051bfcb445b586813 | da9a410dfbb5feefc64f4f10173205a5970cc903 | /3 - Tipos de datos arborescentes/21 - Elemento mínimo de un árbol/21-ElementoMinimoDeUnArbol.cpp | dc49f4fcde488bc9d14db698dfa12ee33776e193 | [] | no_license | alberzos/Estructuras-de-Datos-ED | 111eec42da5d514895f37c3904cce4859caac268 | 194d200d0f808672b0fb06860c91bc720742851d | refs/heads/master | 2022-11-13T22:03:41.439962 | 2020-07-11T11:31:39 | 2020-07-11T11:31:39 | 278,846,961 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,526 | cpp | // ALVARO BERZOSA TORDESILLAS
// F08
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include "bintree_eda.h"
template <typename T>
// función que resuelve el problema
T resolver(bintree<T> arbol) {
T minimo = arbol.root();
if(!arbol.left().empty())
minimo = std::min(minimo, resolver(arbol.left()));
if(!arbol.right().empty())
minimo = std::min(minimo, resolver(arbol.right()));
return minimo;
}
// Resuelve un caso de prueba, leyendo de la entrada la
// configuración, y escribiendo la respuesta
bool resuelveCaso() {
// leer los datos de la entrada
std::string tipo;
std::cin >> tipo;
if (! std::cin)
return false;
if(tipo == "N"){
bintree<int> arbolN = leerArbol(-1);
std::cout << resolver(arbolN) << "\n";
}
else if(tipo == "P"){
std::string v = "#";
bintree<std::string> arbolP = leerArbol(v);
std::cout << resolver(arbolP) << "\n";
}
// escribir sol
return true;
}
int main() {
/*
// Para la entrada por fichero.
// Comentar para acepta el reto
#ifndef DOMJUDGE
std::ifstream in("datos.txt");
auto cinbuf = std::cin.rdbuf(in.rdbuf()); //save old buf and redirect std::cin to casos.txt
#endif
*/
while (resuelveCaso())
;
/*
// Para restablecer entrada. Comentar para acepta el reto
#ifndef DOMJUDGE // para dejar todo como estaba al principio
std::cin.rdbuf(cinbuf);
system("PAUSE");
#endif
*/
return 0;
}
| [
"noreply@github.com"
] | alberzos.noreply@github.com |
f553932a7060a7b1e69bb609114c8777e4fa0c21 | 95ab8a21dda989fde5b0796d1488c30128a01391 | /CodeForces/C++/1204C.cpp | 0b0d374dee956af9e4628c171e89db7dcefd5402 | [] | no_license | neelaryan2/CompetitiveProgramming | caa20ffcdee57fb2e15ceac0e7ebbe4e7277dc34 | 959c3092942751f833b489cc91744fc68f8c65d2 | refs/heads/master | 2021-06-28T14:10:50.545527 | 2021-02-15T17:34:03 | 2021-02-15T17:34:03 | 216,887,910 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,655 | cpp | #include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#include "trace.h"
#else
#define trace(args...)
#endif
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
using vi = vector<int>;
#define mp make_pair
#define ub upper_bound
#define lb lower_bound
#define fi first
#define se second
#define pb push_back
#define eb emplace_back
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()
const int inf = 1e9 + 7;
void solve(int test) {
int n;
cin >> n;
vector<vi> dist(n, vi(n));
for (int i = 0; i < n; i++) {
string s;
cin >> s;
for (int j = 0; j < n; j++) {
if (i == j)
dist[i][j] = 0;
else if (s[j] == '1')
dist[i][j] = 1;
else
dist[i][j] = inf;
}
}
for (int k = 0; k < n; k++)
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);
trace(dist);
int m;
cin >> m;
vector<int> p(m);
for (int& e : p)
cin >> e, e--;
vector<int> ans(1, 0);
for (int i = 1; i < m; i++) {
int j = ans.back();
if (dist[p[j]][p[i]] != i - j)
ans.eb(i - 1);
}
ans.eb(m - 1);
cout << ans.size() << '\n';
for (int e : ans)
cout << p[e] + 1 << ' ';
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t = 1;
// cin >> t;
for (int i = 1; i <= t; i++) {
// cout << "Case #" << i << ": ";
solve(i);
cout << '\n';
}
}
| [
"neelaryan2@gmail.com"
] | neelaryan2@gmail.com |
2931eeb622ba6da3f17a6004e00a88f14a8fbfdd | 50526cc6fa91669fad19264450f0a88d98af5fa3 | /hackerrank/cpp/3_basic_datatypes.cpp | 5188f1b504d138fce0cb120d738c2b8b40fa5bcd | [] | no_license | dvogt23/CodeChallenges | e07a6c5b8d58cf7c1be06e3f38d8a218f19cdee7 | 95513ca9b535cb325390e63c24dabd2ba5475db6 | refs/heads/master | 2022-12-10T09:02:45.334624 | 2022-12-01T21:09:41 | 2022-12-01T21:09:41 | 151,611,815 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 436 | cpp | #include <iostream>
#include <cstdio>
using namespace std;
/*
Sample input:
3 12345678912345 a 334.23 14049.30493
Sample output:
3
12345678912345
a
334.230
14049.304930000
*/
int main() {
// Complete the code.
int i;
long l;
char c;
float f;
double d;
scanf("%i %li %c %f %lf", &i, &l, &c, &f, &d);
printf("%i\n%li\n%c\n%.3f\n%.9lf", i, l, c, f, d);
return 0;
}
| [
"divogt@live.de"
] | divogt@live.de |
54fd16728b9a79d526936873920e6b3c6992d590 | 0813ecdda1a7c00242a3657da8a9a933a7c37a56 | /miniFS.Core/src/stream/MFSStreamWriter.cpp | d853a1d3ebf16b178f80d13a6b624882090c61f5 | [] | no_license | Lancern/miniFS | ab128b6db008463970e529a94c835ca3de8a0ea6 | 0e5a59e1dec0357c00d3bfde74bd335ebaacf157 | refs/heads/master | 2020-03-27T08:54:23.003551 | 2018-09-16T12:17:12 | 2018-09-16T12:17:12 | 146,296,992 | 1 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 371 | cpp | #include "../../include/stream/MFSStreamWriter.h"
MFSStreamWriter::MFSStreamWriter(MFSStream * stream)
: _stream(stream)
{
}
MFSStream * MFSStreamWriter::GetStream() const
{
return _stream;
}
void MFSStreamWriter::Write(const MFSString & string)
{
_stream->Write(string.GetRawString(), string.GetLength() * sizeof(wchar_t));
this->Write<wchar_t>(0);
}
| [
"xh19980325@126.com"
] | xh19980325@126.com |
fcfe2224f2fc63255c087c01590b7f0c42475614 | 6954bd0bc9e45e5d23fa6e4266828a0a421ce779 | /map.h | d075993fe95ecd3e573b361652a67587b4e6544c | [
"Apache-2.0"
] | permissive | SalimTerryLi/WAGLPLANNER | 5e86bc85e03255ebc5ce515ffe02b20f591aa711 | 6adfe7e246a62661f5fcaba29beab90984dfd0c9 | refs/heads/main | 2023-01-12T05:58:36.963671 | 2020-11-18T03:01:31 | 2020-11-18T03:01:31 | 313,789,173 | 0 | 0 | Apache-2.0 | 2020-11-18T01:28:41 | 2020-11-18T01:28:40 | null | UTF-8 | C++ | false | false | 1,343 | h | #ifndef MAP_H
#define MAP_H
#include <QMainWindow>
#include <QPaintEvent>
#include <QPainter>
#include <QDebug>
#include <QPoint>
#include <QColor>
#include <QPen>
#include <QObject>
#include <QEvent>
#include <QFont>
#include <QList>
#include <QStandardItemModel>
#include <QStandardItem>
#include "loadingmachine.h"
#include "landmark.h"
class Map
{
public:
static QPoint coordinateToBlock(int cox , int coz); //坐标转换为区块坐标
public:
double scale = 1.0 ; //比例尺, 比例尺为1时 , 屏幕像素坐标10 = minecraft中1米
double offset_x = 0 ; //偏移量x,表示屏幕正中心的世界坐标
double offset_z = 0; //偏移量z
QList<LoadingMachine> loadmachine_list;
QList<Landmark> landmark_list;
LoadingMachine* getMachineById(int id);
bool isExistLoadingMachine(int id);
Landmark* getMarkById(int id);
bool isExistLandMark(int id);
QStringList lmchstr;
QStringList ldmkstr;
public:
Map();
void generateGrid(QPainter* p , QPoint* mouse_pos, int type);
void addLoadingMachine(LoadingMachine m);
void addLandMark(Landmark l);
void deleteLoadingMachine(int id);
void deleteLandMark(int id);
void clear();
int g(int dx ,int a); //辅助计算函数
};
#endif // MAP_H
| [
"noreply@github.com"
] | SalimTerryLi.noreply@github.com |
b95afa84fc3410dafc1b3a4ba8ccb718821444e2 | 374295882c901ee5c6ced8d17ca2b578cd483dd4 | /stack/stack(basic)/nearest smaller to right.cpp | 0c2a6cecab4be9598d223721adeddb958ec1a37c | [] | no_license | chinmay021/Interview-Preparation | 232dba9d7d952fffa9475f8d8282f0edbf498726 | c1b6f3e083025581f7157df887e1b87a9e153e98 | refs/heads/master | 2022-12-15T17:51:41.570297 | 2020-09-12T05:28:19 | 2020-09-12T05:28:19 | 279,581,708 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 614 | cpp | vector<long long> v;
stack<long long> s;
for (long long i = n - 1; i >= 0; i--) // right to left
{
if (s.size() == 0)
{
v.push_back(-1);
}
else if (s.size() > 0 && s.top() < arr[i])
{
v.push_back(s.top());
}
else if (s.size() > 0 && s.top() >= arr[i])
{
while (s.size() > 0 && s.top() >= arr[i])
{
s.pop();
}
if (s.size() == 0)
{
v.push_back(-1);
}
else
{
v.push_back(s.top());
}
}
s.push(arr[i]);
}
reverse(v.begin(), v.end()); // reversal
return v; | [
"chinmaykumar021@gmail.com"
] | chinmaykumar021@gmail.com |
451d9554cac35b94d5399f33ac69947106b465ed | ee6e6e5ecf3a4e130e46b49dd0868a8b74c703eb | /11th-april-2019/12th-april-2019/poly.cpp | d2a8aafd9d3d51162bc110231a5f815f7dff4691 | [] | no_license | ashishcodekul777/cpp | e5045fffd8f7c9c3f8eed1c1f5929f1bcb57af2a | 077408bf0a86a3694baf1f72c623f8380cf48780 | refs/heads/master | 2022-01-08T03:31:03.488322 | 2019-06-04T12:18:21 | 2019-06-04T12:18:21 | 179,631,505 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 901 | cpp | #include <iostream>
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape( int a = 0, int b = 0){
width = a;
height = b;
}
int area()
{
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape {
public:
Rectangle( int a = 0, int b = 0):Shape(a, b) { }
int area () {
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};
class Triangle: public Shape {
public:
Triangle( int a = 0, int b = 0):Shape(a, b) { }
int area () { cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
};
int main()
{
Shape *shape;
Rectangle rect(10,7);
Traingle Tri(10,3);
shape= ▭
shape->area();
shape= &tri;
shape->area();
return 0;
}
| [
"ashish444rao@gmail.com"
] | ashish444rao@gmail.com |
b048ca48e8774dcaab43d0b2ad58ec7f592f4bae | 2c548b2a481036c51a3bed07a0ebe20a7e59ec45 | /String/Quick3String.cpp | 5f695a2502c7c387fab9233397a5670b25603318 | [] | no_license | yuanmie/Data-Struct-And-Algorithm | 2f2e4765ebd491a684bccaec9e2d37e62c19a927 | eca4f14075e8c7af0794e48cd260dd816a7b5605 | refs/heads/master | 2021-01-10T01:09:29.103834 | 2017-05-08T14:50:55 | 2017-05-08T14:50:55 | 44,149,761 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,920 | cpp | /*
快速3向字符串排序,将数组划为小于,等于,大于3类。
然后递归的采用同样的步骤,达到排序的目的。
时间复杂度为:
O(n) = n/3 + n/3 + n/3 + O(n/3) + O(n/3) + O(n/3)
==> O(n) = (nlog_3^n)
*/
#include <iostream>
#include <string>
#include <cstdio>
#include <cassert>
using std::string;
using std::cout;
void _quick3Sort(string* strs, int lo, int hi, int d);
int charAt(const std::string& str, int index){
assert(index >= 0);
int strLen = str.length();
if(index < strLen){
return (int)str[index];
}else{
return -1;
}
}
void swap(string* str, int src, int dest){
string temp = str[src];
str[src] = str[dest];
str[dest] = temp;
}
void quick3Sort(string* strs, int length){
assert(length > 0);
_quick3Sort(strs, 0, length-1, 0);
}
void _quick3Sort(string* strs, int lo, int hi, int d){
if(lo >= hi) return;
int v = charAt(strs[lo], d);
int i = lo + 1;
int lt = lo;
int gt = hi;
while( i <= gt ){
int t = charAt(strs[i], d);
if(t < v){
swap(strs, i, lt);
++i;
++lt;
}else if(t > v){
swap(strs, i, gt);
--gt;
}else{
++i;
}
}
_quick3Sort(strs, lo, lt-1, d);
if(v > 0){
_quick3Sort(strs, lt, gt, d+1);
}
_quick3Sort(strs, gt+1, hi, d);
}
int main(){
string s1("are");
string s2("by");
string s3("sea");
string s4("seashells");
string s5("seashells");
string s6("sells");
string s7("sells");
string s8("she");
string s9("she");
string s10("shells");
string s11("shore");
string s12("surely");
string s13("the");
string s14("the");
int M = 14;
string strs[M] = {s1,s11,s14,s12,s13,s8,s9,s10,s2,s3,s7,s6,s5,s4};
for(int i = 0; i < M; i++){
std::cout << strs[i] << "\t";
}
printf("start sort\n");
quick3Sort(strs, 14);
printf("after sort\n");
for(int i = 0; i < M; i++){
std::cout << strs[i] << "\t";
}
} | [
"1695883544@qq.com"
] | 1695883544@qq.com |
102e5ad322eeb0528c60ed5353b8d68456f93141 | e74687a6b394c47ffd8df8a31cfe0409e891078b | /fbgemm_gpu/src/layout_transform_ops_cpu.cpp | 2a66482c3f81a23660494a6d0749525c2e4ae4c3 | [
"BSD-3-Clause"
] | permissive | LinGongHeng/FBGEMM | b046003125dd0057d002263ac2f5fb08ccf3bd56 | 6cd2bde4684431fe5a4005edf6d0139abf462956 | refs/heads/main | 2023-09-04T20:55:48.748202 | 2021-11-24T21:41:14 | 2021-11-24T21:42:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,977 | cpp | /*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <ATen/ATen.h>
#include <ATen/core/op_registration/op_registration.h>
#include <torch/library.h>
#include "ATen/Parallel.h"
#include "fbgemm_gpu/sparse_ops_utils.h"
namespace fbgemm {
at::Tensor recat_embedding_grad_output_mixed_D_cpu(
const at::Tensor& grad_output, // [B_local][Sum_T_global(D)]
const std::vector<int64_t>& dim_sum_per_rank) {
TORCH_CHECK(grad_output.is_contiguous());
const auto B_local = grad_output.sizes()[0];
at::Tensor sharded_grad_output =
at::empty({grad_output.numel()}, grad_output.options());
int n = dim_sum_per_rank.size();
std::vector<int64_t> accum_dim_sum(n + 1);
accum_dim_sum[0] = 0;
std::partial_sum(
dim_sum_per_rank.begin(), dim_sum_per_rank.end(), &accum_dim_sum[1]);
const auto global_dim_sum = accum_dim_sum[n];
TORCH_CHECK(B_local * global_dim_sum == grad_output.numel());
AT_DISPATCH_FLOATING_TYPES_AND_HALF(
grad_output.type(), "recat_embedding_gradients", ([&] {
const auto go = grad_output.accessor<scalar_t, 2>();
auto sgo = sharded_grad_output.accessor<scalar_t, 1>();
at::parallel_for(
0, n * B_local, 1, [&](int64_t i_begin, int64_t i_end) {
const auto dim_begin = i_begin / B_local;
const auto dim_end = (i_end + B_local - 1) / B_local;
for (const auto dim : c10::irange(dim_begin, dim_end)) {
const auto dim_sum = dim_sum_per_rank[dim];
const auto sgo_offset = B_local * accum_dim_sum[dim];
scalar_t* dst = &sgo[sgo_offset];
const scalar_t* src = &go[0][accum_dim_sum[dim]];
const auto r_begin = (dim == dim_begin) ? i_begin % B_local : 0;
const auto r_end = (dim == dim_end - 1 && i_end % B_local != 0)
? i_end % B_local
: B_local;
for (const auto r : c10::irange(r_begin, r_end)) {
memcpy(
dst + r * dim_sum,
src + r * global_dim_sum,
dim_sum * sizeof(scalar_t));
}
}
});
}));
return sharded_grad_output;
}
} // namespace fbgemm
TORCH_LIBRARY_FRAGMENT(fbgemm, m) {
m.def(
"recat_embedding_grad_output_mixed_D_batch(Tensor grad_output, Tensor dim_sum_per_rank, Tensor cumsum_dim_sum_per_rank) -> Tensor");
m.def(
"recat_embedding_grad_output_mixed_D(Tensor grad_output, int[] dim_sum_per_rank) -> Tensor");
m.def(
"recat_embedding_grad_output(Tensor grad_output, int[] num_features_per_rank) -> Tensor");
}
TORCH_LIBRARY_IMPL(fbgemm, CPU, m) {
m.impl(
"recat_embedding_grad_output_mixed_D",
fbgemm::recat_embedding_grad_output_mixed_D_cpu);
}
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
ca43c264bf3395026f6a88c00ba4332cc20d9e0c | ecfadf59abf0c377e4fbaafb8f594420d8d23277 | /Docs/cpptut/SOURCE/VIRTUAL3.CPP | ad669a03789dd9f0bc875b968d78452b300b9020 | [] | no_license | laurentd75/ggnkua_Atari_ST_Sources_Repository | 71fad5fc5ee3ea7bbd807ec6a6d4a99f7ef31334 | b51e02ffd546ba8260a5645a51acd90d66c16832 | refs/heads/master | 2023-08-31T14:13:18.440660 | 2023-08-24T10:09:58 | 2023-08-24T10:09:58 | 164,442,362 | 0 | 0 | null | 2023-09-03T00:24:29 | 2019-01-07T14:12:47 | null | UTF-8 | C++ | false | false | 1,032 | cpp | // Chapter 10 - Program 3
#include <iostream.h>
class vehicle {
int wheels;
float weight;
public:
void message(void) { cout << "Vehicle message\n";}
};
class car : public vehicle {
int passenger_load;
public:
void message(void) { cout << "Car message\n";}
};
class truck : public vehicle {
int passenger_load;
float payload;
public:
int passengers(void) {return passenger_load;}
};
class boat : public vehicle {
int passenger_load;
public:
int passengers(void) {return passenger_load;}
void message(void) { cout << "Boat message\n";}
};
main()
{
vehicle *unicycle;
car *sedan;
truck *semi;
boat *sailboat;
unicycle = new vehicle;
unicycle->message();
sedan = new car;
sedan->message();
semi = new truck;
semi->message();
sailboat = new boat;
sailboat->message();
}
// Result of execution
//
// Vehicle message
// Car message
// Vehicle message
// Boat message
| [
"ggn.dbug@gmail.com"
] | ggn.dbug@gmail.com |
fd8a42f58a105a59b89b2ce6117c82746d828ddc | ec2de16739cd71afef4a632a606e83444daf21b1 | /DevC++/Code power/lat sach.cpp | b9025d0669f71b36fc8204b851e83b8227c1a66d | [] | no_license | minhcongnguyen1508/Code-Java-C--UET | f96bc409c720cb80aaa2f96da81b3870e0937292 | 24c8018fac67479e0fc01c2068c9ee1a7a700311 | refs/heads/master | 2020-04-22T00:21:17.478448 | 2019-02-10T12:58:07 | 2019-02-10T12:58:07 | 169,976,733 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 239 | cpp | //
# include <iostream>
# include <algorithm>
# include <string>
# include <vector>
using namespace std;
int main(){
int a =- 7, b =- 7, c = 7, d = 7, e;
e = d++ || a++ && b++;
printf("%d %d %d %d %d", a, b, c, d, e);
}
| [
"minhcongnguyen1508@gmail.com"
] | minhcongnguyen1508@gmail.com |
66f4bd5ea0e01721604a6c4a1c01130acf64b7df | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/curl/gumtree/curl_new_log_8228.cpp | 579a7e56236524d29a1ecac22c5db84a68cab584 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 524 | cpp | fputs(
" backend that supports this operation. The c-ares backend is the\n"
" only such one. (Added in 7.33.0)\n"
"\n"
" -e, --referer <URL>\n"
" (HTTP) Sends the \"Referer Page\" information to the HTTP server.\n"
" This can also be set with the -H, --header flag of course. When\n"
" used with -L, --location you can append \";auto\" to the --referer\n"
" URL to make curl automatically set the previous URL when it fol-\n"
, stdout); | [
"993273596@qq.com"
] | 993273596@qq.com |
a3b8dd84e713de6b68aa9cab34c493c5434212ed | 64c511bb0c1a61134966ff03a46d2f2802cda379 | /Search_Sort/Union_Intersection.cpp | 6e9898fe08ecea5c792b0dcf83b986f16da7850a | [] | no_license | ria28/Data-Structures-And-Algorithms | 96f2278e35c4a1bb346d81fbea0e9da0f57c90c0 | 3225ba1b3dec9c2f77d6b2c9cc5cb9933cbb306d | refs/heads/master | 2023-06-08T07:50:57.422775 | 2021-07-03T11:43:10 | 2021-07-03T11:43:10 | 278,084,625 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,665 | cpp | #include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
vector<int> intersection(vector<int> &nums1, vector<int> &nums2)
{
unordered_set<int> set{nums1.begin(), nums1.end()};
vector<int> intersect;
for (auto n : nums2)
{
if (set.find(n) != set.end())
{
intersect.push_back(n);
set.erase(n);
}
}
return intersect;
}
void intersection_three(int arr1[], int arr2[], int arr3[], int & n1, int & n2, int & n3)
{
int i = 0, j = 0, k = 0;
// vector<int> intersect;
while (i < n1 && j < n2 && k < n3)
{
if (arr1[i] == arr2[j] && arr2[j]==arr2[k])
{
// intersect.push_back(arr1[i]);
cout<<arr1[i]<<" ";
i++;
j++;
k++;
}
else if(arr1[i]<arr2[j])
i++;
else if(arr2[j]<arr3[k])
j++;
else
k++;
}
// return intersect;
}
int main(int args, char **argc)
{
int ar1[] = {1, 5, 10, 20, 40, 80};
int ar2[] = {6, 7, 20, 80, 100};
int ar3[] = {3, 4, 15, 20, 30, 70, 80, 120};
int n1 = sizeof(ar1) / sizeof(ar1[0]);
int n2 = sizeof(ar2) / sizeof(ar2[0]);
int n3 = sizeof(ar3) / sizeof(ar3[0]);
// vector<int> nums1{1, 2, 3, 4};
// vector<int> nums2{2, 4, 6, 8};
// vector<int> intersect = intersection(nums1, nums2);
// for (int i = 0; i < intersect.size(); i++)
// {
// cout << intersect[i];
// }
intersection_three(ar1,ar2,ar3,n1,n2,n3);
// for (int i = 0; i < intersect2.size(); i++)
// {
// cout << intersect2[i];
// }
} | [
"riajaiswal28@gmail.com"
] | riajaiswal28@gmail.com |
51756f3001d47660de53543acc24929119683c8e | 4f8a5913a01276e335b39bbfd366f839dab4fada | /deps/boost/libs/variant/test/auto_visitors.cpp | 84c91c9d2fa7c929b1aced29a9dfd139673a2f86 | [
"MIT",
"GPL-1.0-or-later",
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | teolemon/poedit | d6b08505e0fe3ca46d6686a9e7e70e4923db8f4a | 7a61156a6efb884202b0d60a342600cab7b3d1d5 | refs/heads/master | 2021-07-11T08:20:20.337006 | 2015-08-22T01:09:24 | 2015-08-22T01:09:24 | 41,184,280 | 0 | 0 | MIT | 2021-03-04T13:18:07 | 2015-08-22T01:07:46 | C++ | UTF-8 | C++ | false | false | 10,100 | cpp | //-----------------------------------------------------------------------------
// boost-libs variant/test/auto_visitors.cpp source file
// See http://www.boost.org for updates, documentation, and revision history.
//-----------------------------------------------------------------------------
//
// Copyright (c) 2014-2015 Antony Polukhin
//
// 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)
#include "boost/config.hpp"
#include "boost/test/minimal.hpp"
#include "boost/variant.hpp"
#include "boost/variant/multivisitors.hpp"
#include "boost/lexical_cast.hpp"
struct lex_streamer_explicit: boost::static_visitor<std::string> {
template <class T>
const char* operator()(const T& ) {
return "10";
}
template <class T1, class T2>
const char* operator()(const T1& , const T2& ) {
return "100";
}
};
void run_explicit()
{
typedef boost::variant<int, std::string, double> variant_type;
variant_type v2("10"), v1("100");
lex_streamer_explicit visitor_ref;
// Must return instance of std::string
BOOST_CHECK(boost::apply_visitor(visitor_ref, v2).c_str() == std::string("10"));
BOOST_CHECK(boost::apply_visitor(visitor_ref, v2, v1).c_str() == std::string("100"));
}
// Most part of tests from this file require decltype(auto)
#ifdef BOOST_NO_CXX14_DECLTYPE_AUTO
void run()
{
BOOST_CHECK(true);
}
void run2()
{
BOOST_CHECK(true);
}
void run3()
{
BOOST_CHECK(true);
}
#else
#include <iostream>
struct lex_streamer {
template <class T>
std::string operator()(const T& val) const {
return boost::lexical_cast<std::string>(val);
}
};
struct lex_streamer_void {
template <class T>
void operator()(const T& val) const {
std::cout << val << std::endl;
}
template <class T1, class T2>
void operator()(const T1& val, const T2& val2) const {
std::cout << val << '+' << val2 << std::endl;
}
template <class T1, class T2, class T3>
void operator()(const T1& val, const T2& val2, const T3& val3) const {
std::cout << val << '+' << val2 << '+' << val3 << std::endl;
}
};
struct lex_streamer2 {
std::string res;
template <class T>
const char* operator()(const T& val) const {
return "fail";
}
template <class T1, class T2>
const char* operator()(const T1& v1, const T2& v2) const {
return "fail2";
}
template <class T1, class T2, class T3>
const char* operator()(const T1& v1, const T2& v2, const T3& v3) const {
return "fail3";
}
template <class T>
std::string& operator()(const T& val) {
res = boost::lexical_cast<std::string>(val);
return res;
}
template <class T1, class T2>
std::string& operator()(const T1& v1, const T2& v2) {
res = boost::lexical_cast<std::string>(v1) + "+" + boost::lexical_cast<std::string>(v2);
return res;
}
template <class T1, class T2, class T3>
std::string& operator()(const T1& v1, const T2& v2, const T3& v3) {
res = boost::lexical_cast<std::string>(v1) + "+" + boost::lexical_cast<std::string>(v2)
+ "+" + boost::lexical_cast<std::string>(v3);
return res;
}
};
#ifndef BOOST_VARIANT_DO_NOT_USE_VARIADIC_TEMPLATES
# define BOOST_CHECK_IF_HAS_VARIADIC(x) BOOST_CHECK(x)
#else
# define BOOST_CHECK_IF_HAS_VARIADIC(x) /**/
#endif
void run()
{
typedef boost::variant<int, std::string, double> variant_type;
variant_type v1(1), v2("10"), v3(100.0);
lex_streamer lex_streamer_visitor;
BOOST_CHECK(boost::apply_visitor(lex_streamer(), v1) == "1");
BOOST_CHECK_IF_HAS_VARIADIC(boost::apply_visitor(lex_streamer_visitor)(v1) == "1");
BOOST_CHECK(boost::apply_visitor(lex_streamer(), v2) == "10");
BOOST_CHECK_IF_HAS_VARIADIC(boost::apply_visitor(lex_streamer_visitor)(v2) == "10");
#ifndef BOOST_NO_CXX14_GENERIC_LAMBDAS
BOOST_CHECK(boost::apply_visitor([](auto v) { return boost::lexical_cast<std::string>(v); }, v1) == "1");
BOOST_CHECK(boost::apply_visitor([](auto v) { return boost::lexical_cast<std::string>(v); }, v2) == "10");
// Retun type must be the same in all instances, so this code does not compile
//boost::variant<int, short, unsigned> v_diff_types(1);
//BOOST_CHECK(boost::apply_visitor([](auto v) { return v; }, v_diff_types) == 1);
boost::apply_visitor([](auto v) { std::cout << v << std::endl; }, v1);
boost::apply_visitor([](auto v) { std::cout << v << std::endl; }, v2);
#endif
lex_streamer2 visitor_ref;
BOOST_CHECK(boost::apply_visitor(visitor_ref, v1) == "1");
BOOST_CHECK(boost::apply_visitor(visitor_ref, v2) == "10");
#ifndef BOOST_VARIANT_DO_NOT_USE_VARIADIC_TEMPLATES
std::string& ref_to_string = boost::apply_visitor(visitor_ref, v1);
BOOST_CHECK(ref_to_string == "1");
#endif
lex_streamer_void lex_streamer_void_visitor;
boost::apply_visitor(lex_streamer_void(), v1);
boost::apply_visitor(lex_streamer_void(), v2);
#ifndef BOOST_VARIANT_DO_NOT_USE_VARIADIC_TEMPLATES
boost::apply_visitor(lex_streamer_void_visitor)(v2);
#endif
}
struct lex_combine {
template <class T1, class T2>
std::string operator()(const T1& v1, const T2& v2) const {
return boost::lexical_cast<std::string>(v1) + "+" + boost::lexical_cast<std::string>(v2);
}
template <class T1, class T2, class T3>
std::string operator()(const T1& v1, const T2& v2, const T3& v3) const {
return boost::lexical_cast<std::string>(v1) + "+"
+ boost::lexical_cast<std::string>(v2) + '+'
+ boost::lexical_cast<std::string>(v3);
}
};
void run2()
{
typedef boost::variant<int, std::string, double> variant_type;
variant_type v1(1), v2("10"), v3(100.0);
lex_combine lex_combine_visitor;
BOOST_CHECK(boost::apply_visitor(lex_combine(), v1, v2) == "1+10");
BOOST_CHECK(boost::apply_visitor(lex_combine(), v2, v1) == "10+1");
BOOST_CHECK_IF_HAS_VARIADIC(boost::apply_visitor(lex_combine_visitor)(v2, v1) == "10+1");
#ifndef BOOST_NO_CXX14_GENERIC_LAMBDAS
BOOST_CHECK(
boost::apply_visitor(
[](auto v1, auto v2) {
return boost::lexical_cast<std::string>(v1) + "+"
+ boost::lexical_cast<std::string>(v2);
}
, v1
, v2
) == "1+10"
);
BOOST_CHECK(
boost::apply_visitor(
[](auto v1, auto v2) {
return boost::lexical_cast<std::string>(v1) + "+"
+ boost::lexical_cast<std::string>(v2);
}
, v2
, v1
) == "10+1"
);
boost::apply_visitor([](auto v1, auto v2) { std::cout << v1 << '+' << v2 << std::endl; }, v1, v2);
boost::apply_visitor([](auto v1, auto v2) { std::cout << v1 << '+' << v2 << std::endl; }, v2, v1);
#endif
lex_streamer2 visitor_ref;
BOOST_CHECK(boost::apply_visitor(visitor_ref, v1, v2) == "1+10");
BOOST_CHECK(boost::apply_visitor(visitor_ref, v2, v1) == "10+1");
#ifndef BOOST_VARIANT_DO_NOT_USE_VARIADIC_TEMPLATES
std::string& ref_to_string = boost::apply_visitor(visitor_ref)(v1, v2);
BOOST_CHECK(ref_to_string == "1+10");
#endif
boost::apply_visitor(lex_streamer_void(), v1, v2);
boost::apply_visitor(lex_streamer_void(), v2, v1);
}
#undef BOOST_CHECK_IF_HAS_VARIADIC
void run3()
{
#if !defined(BOOST_VARIANT_DO_NOT_USE_VARIADIC_TEMPLATES) && !defined(BOOST_NO_CXX11_HDR_TUPLE)
typedef boost::variant<int, std::string, double> variant_type;
variant_type v1(1), v2("10"), v3(100);
lex_combine lex_combine_visitor;
BOOST_CHECK(boost::apply_visitor(lex_combine(), v1, v2, v3) == "1+10+100");
BOOST_CHECK(boost::apply_visitor(lex_combine(), v2, v1, v3) == "10+1+100");
BOOST_CHECK(boost::apply_visitor(lex_combine_visitor)(v2, v1, v3) == "10+1+100");
#ifndef BOOST_NO_CXX14_GENERIC_LAMBDAS
BOOST_CHECK(
boost::apply_visitor(
[](auto v1, auto v2, auto v3) {
return boost::lexical_cast<std::string>(v1) + "+"
+ boost::lexical_cast<std::string>(v2) + "+"
+ boost::lexical_cast<std::string>(v3);
}
, v1
, v2
, v3
) == "1+10+100"
);
BOOST_CHECK(
boost::apply_visitor(
[](auto v1, auto v2, auto v3) {
return boost::lexical_cast<std::string>(v1) + "+"
+ boost::lexical_cast<std::string>(v2) + "+"
+ boost::lexical_cast<std::string>(v3);
}
, v3
, v1
, v3
) == "100+1+100"
);
boost::apply_visitor(
[](auto v1, auto v2, auto v3) { std::cout << v1 << '+' << v2 << '+' << v3 << std::endl; },
v1, v2, v3
);
boost::apply_visitor(
[](auto v1, auto v2, auto v3) { std::cout << v1 << '+' << v2 << '+' << v3 << std::endl; },
v2, v1, v3
);
#endif
lex_streamer2 visitor_ref;
BOOST_CHECK(boost::apply_visitor(visitor_ref, v1, v2) == "1+10");
BOOST_CHECK(boost::apply_visitor(visitor_ref)(v2, v1) == "10+1");
std::string& ref_to_string = boost::apply_visitor(visitor_ref, v1, v2);
BOOST_CHECK(ref_to_string == "1+10");
lex_streamer_void lex_streamer_void_visitor;
boost::apply_visitor(lex_streamer_void(), v1, v2, v1);
boost::apply_visitor(lex_streamer_void(), v2, v1, v1);
boost::apply_visitor(lex_streamer_void_visitor)(v2, v1, v1);
#endif // !defined(BOOST_VARIANT_DO_NOT_USE_VARIADIC_TEMPLATES) && !defined(BOOST_NO_CXX11_HDR_TUPLE)
}
#endif
int test_main(int , char* [])
{
run_explicit();
run();
run2();
run3();
return 0;
}
| [
"vaclav@slavik.io"
] | vaclav@slavik.io |
d3fbfeed10e274def4d3cef2c5d1b9932b00f2f4 | 663f25816bac61647fd0ba9e4f55fe4eb6a9b292 | /source/code/programs/transcompilers/unilang/unilang_to_code/program_options/program_options.cpp | ca9fdf4304fa8cd3fd992384199c15d6c0a51906 | [
"MIT"
] | permissive | luxe/unilang | a318e327cc642fabdcd08f3238aac47e4e65929f | 832f4bb1dc078e1f5ab5838b8e0c4bb98ba0e022 | refs/heads/main | 2023-07-25T06:32:18.993934 | 2023-07-13T02:22:06 | 2023-07-13T02:22:06 | 40,274,795 | 42 | 8 | MIT | 2023-07-19T10:36:56 | 2015-08-06T00:02:56 | Fancy | UTF-8 | C++ | false | false | 3,039 | cpp |
#include "program_options.hpp"
#include <string>
#include <iostream>
//constructor
Program_Options::Program_Options(int const& argc, char** const& argv){
using namespace boost::program_options;
//build all the possible flags and add description.
options_description desc (Get_Options_Description());
//set positional arguments
positional_options_description pod;
//build variable map
Build_Variable_Map(argc,argv,desc,pod);
//process immediate options
Process_Immediate_Options(desc);
//validate the mandatory flags
Check_For_Mandatory_Flags_Not_Passed();
}
boost::program_options::options_description Program_Options::Get_Options_Description(void){
using namespace boost::program_options;
//Program Description
options_description desc("converts unilang file to code json");
//Program Flags
desc.add_options()
//these are flag descriptions of that can be passed into the class.
//the code inserted, are the flags added by the user through the
//program_options_maker flag interface
("input_file,i",value<std::string>(),"input file")
("output_file,o",value<std::string>(),"output path")
//+----------------------------------------------------------+
//| Obligatory |
//+----------------------------------------------------------+
("help,h","produce this help message")
("version,v","display version")
;
return desc;
}
void Program_Options::Build_Variable_Map(int const& argc, char** const& argv, boost::program_options::options_description const& desc, boost::program_options::positional_options_description const& pod){
using namespace boost::program_options;
//store user flag data. crash elegantly if they pass incorrect flags.
try{
store(command_line_parser(argc, argv).options(desc).positional(pod).run(), vm);
notify(vm);
}
catch(error& e){
std::cerr << "ERROR: " << e.what() << std::endl;
std::cerr << desc << std::endl;
exit(EXIT_FAILURE);
}
return;
}
void Program_Options::Process_Immediate_Options( boost::program_options::options_description const& desc){
//do not continue the program if the user wanted to see the version or help data
if (vm.count("version")){
std::cout << "\nThis is version " << 1 << " of the string tree getter.\n\n";
exit(EXIT_SUCCESS);
}
else if (vm.count("help")){
std::cout << '\n' << desc << '\n';
exit(EXIT_SUCCESS);
}
return;
}
void Program_Options::Check_For_Mandatory_Flags_Not_Passed(){
std::vector<std::string> flags_not_passed;
if (!flags_not_passed.empty()){
std::cerr << "you need to pass the following flags still:\n";
for (auto it: flags_not_passed){
std::cerr << '\t' << it << '\n';
}
exit(EXIT_FAILURE);
}
return;
}
std::string Program_Options::Input_File() const{
std::string data;
if (vm.count("input_file")){
data = vm["input_file"].as<std::string>();
}
return data;
}
std::string Program_Options::Output_File() const{
std::string data;
if (vm.count("output_file")){
data = vm["output_file"].as<std::string>();
}
return data;
} | [
"thickey@uber.com"
] | thickey@uber.com |
f318c6c2fcde8a6989e34213047dcac04038859d | 6383cd8579cfa2a61b46bb77150c10e8413e0f32 | /include/trie-node.inl | 312f3b852398e226cca6a646a5626fd1cf26c40c | [
"MIT"
] | permissive | gokselgoktas/boggle-solver | 8c1510307daeed6204f42433aad30a4394ac5d1f | 577ced63526e2e06dc26b0470f8b56d2553241a4 | refs/heads/master | 2020-05-29T15:41:27.628172 | 2017-07-27T14:35:09 | 2017-07-27T14:35:09 | 60,730,647 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 510 | inl | #ifndef BOGGLE_TRIE_NODE_INL
#define BOGGLE_TRIE_NODE_INL
namespace boggle {
bool TrieNode::isWordBoundary() const
{
return isWordBoundary_;
}
#ifdef BOGGLE_COUNT_NODE_DEPENDENCIES
size_t TrieNode::getDependencyCount() const
{
return dependencyCount_;
}
#endif
TrieNode::Subnodes &TrieNode::getSubnodes()
{
return subnodes_;
}
TrieNode::Subnodes const &TrieNode::getSubnodes() const
{
return subnodes_;
}
size_t TrieNode::getSubnodeCount() const
{
return subnodes_.size();
}
}
#endif
| [
"gokselgoktas@gmail.com"
] | gokselgoktas@gmail.com |
342f6d5668384bbfc74c5ca58bb3c57e3daa2d4e | e027dbe3f227f315ce17e995c78c61721d2f97f0 | /Engine/ColorShaderClass.h | 7ec1422ba9cfaa46b044adbd902d480d0baa0222 | [] | no_license | CheesyPanda42/Engine | fb3ce15dbe9bf711db6de402f7c803853a029bcf | 17b0bee2d041d3c8a1935dc4c03fc042b3ad38cc | refs/heads/master | 2023-04-08T07:50:50.716590 | 2013-11-06T04:58:12 | 2013-11-06T04:58:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 918 | h | #include <D3D11.h>
#include <D3DX10math.h> // write own math
#include <D3DX11async.h>
#include <fstream>
using namespace std;
class ColorShaderClass
{
public:
ColorShaderClass(void);
ColorShaderClass(const ColorShaderClass&);
~ColorShaderClass(void);
bool Initialize(ID3D11Device*, HWND);
void Shutdown();
bool Render(ID3D11DeviceContext*, int, D3DXMATRIX, D3DXMATRIX, D3DXMATRIX);
private:
struct MatrixBufferType
{
D3DXMATRIX world;
D3DXMATRIX view;
D3DXMATRIX proj;
};
bool InitializeShader(ID3D11Device*, HWND, WCHAR*, WCHAR*);
void ShutdownShader();
void OutputShaderErrorMessage(ID3D10Blob*, HWND, WCHAR*);
bool SetShaderParameters(ID3D11DeviceContext*, D3DXMATRIX, D3DXMATRIX, D3DXMATRIX);
void RenderShader(ID3D11DeviceContext*, int);
ID3D11VertexShader* m_vertexShader;
ID3D11PixelShader* m_pixelShader;
ID3D11InputLayout* m_layout;
ID3D11Buffer* m_matrixBuffer;
};
| [
"cprelerson42@gmail.com"
] | cprelerson42@gmail.com |
febc0e8389cf7538dbfe0c2f5ba8021df070da9f | f47b329d81123e4cf3c395b7d1af3c454309dcea | /Data Structures/Linked_list/Linked_list_rev_loop.cpp | c8e685242f30ff19a3fe656da48eb80276bb0efd | [] | no_license | Deepan20/Cpp | 7a9ea2074c2460612b65139fcb631ae1678b9eaa | 8cbcedfb31f310ebc8116a865039cf7f56999c01 | refs/heads/main | 2023-07-21T11:50:38.238434 | 2021-08-16T17:54:29 | 2021-08-16T17:54:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,388 | cpp | #include<iostream>
using namespace std;
struct node
{
int data;
node* next;
};
node* insert(node *head,int a)
{
node *temp1=new node();
temp1->data=a;
temp1->next=NULL;
if(head==NULL)
{
head=temp1;
return head;
}
node *temp2=head;
while(temp2->next!=NULL)
{
temp2=temp2->next;
}
temp2->next=temp1;
return head;
}
void print(node *head)
{
node *temp =head; // pointing to first element
cout<<"\nThe elements are : ";
while(temp!=NULL)
{
cout<<temp->data<<", ";
temp=temp->next;
}
}
node* Reverse(node* head)
{
node *prev,*current,*next_node;
prev=NULL;
current=head;
while(current!=NULL)
{
next_node=current->next; // storing the next address in next_node
current->next=prev; // linking the current to previous node
prev=current; // updating prev pointer
current=next_node; // updating current pointer
}
head =prev; // sice prev points to last node, we point head to this node as last step
return head;
}
int main()
{
node* head=NULL;
int n,a;
head =insert(head,1);
head =insert(head,2);
head =insert(head,3);
head =insert(head,4);
head =insert(head,5);
print(head);
head=Reverse(head);
print(head);
return 0;
}
// here we have to keep track of the previous node as well as the next node for reversing it | [
"ksasidharan98@gmail.com"
] | ksasidharan98@gmail.com |
aac6ce90556213e846fe71bd5b69314b48ab206f | 0674e81a160161996251fb4b063c801330ccd1e2 | /codeforces/April Fool Day Contest 2014/E.cpp | 5951b727336d20c8da2782201cdcf638aa3446a1 | [] | no_license | joshuabezaleel/cp | 8a2c9b44605810da4367efeb981f822ae5e1e9a2 | 57f365458cca38c3c0fb1f5af1c6b44b74f3b53e | refs/heads/master | 2022-07-19T00:39:34.395495 | 2020-05-23T20:37:20 | 2020-05-23T20:37:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,826 | cpp | #include <vector>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <algorithm>
#include <utility>
#include <numeric>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cassert>
#include <limits>
using namespace std;
#ifdef DEBUG
#define debug(...) printf(__VA_ARGS__)
#define GetTime() fprintf(stderr,"Running time: %.3lf second\n",((double)clock())/CLOCKS_PER_SEC)
#else
#define debug(...)
#define GetTime()
#endif
//type definitions
typedef long long ll;
typedef double db;
typedef pair<int,int> pii;
typedef vector<int> vint;
//abbreviations
#define A first
#define B second
#define MP make_pair
#define PB push_back
//macros
#define REP(i,n) for (int i = 0; i < (n); ++i)
#define REPD(i,n) for (int i = (n)-1; 0 <= i; --i)
#define FOR(i,a,b) for (int i = (a); i <= (b); ++i)
#define FORD(i,a,b) for (int i = (a); (b) <= i; --i)
#define FORIT(it,c) for (__typeof ((c).begin()) it = (c).begin(); it != (c).end(); it++)
#define ALL(a) (a).begin(),(a).end()
#define SZ(a) ((int)(a).size())
#define RESET(a,x) memset(a,x,sizeof(a))
#define EXIST(a,s) ((s).find(a) != (s).end())
#define MX(a,b) a = max((a),(b));
#define MN(a,b) a = min((a),(b));
inline void OPEN(const string &s) {
freopen((s + ".in").c_str(), "r", stdin);
freopen((s + ".out").c_str(), "w", stdout);
}
/* -------------- end of azaky's template -------------- */
int main(){
db x;
cin >> x;
FOR(a, 1, 10) FOR(h, 1, 10) {
db _a = (db)a / 2.;
db _h = (db)h;
db hyp = sqrt(_a * _a + _h * _h);
db y = _a * _h / hyp;
if (fabs(x - y) < 1e-6) {
cout << a << " " << h << endl;
return 0;
}
}
return 0;
}
| [
"ahmadzaky003@gmail.com"
] | ahmadzaky003@gmail.com |
1f9449af0209d942fece54be541d4ba12a9421d1 | 03f037d0f6371856ede958f0c9d02771d5402baf | /graphics/VTK-7.0.0/ThirdParty/xdmf3/vtkxdmf3/XdmfAttributeCenter.hpp | 58ec56413f952efd3dd7f005dd4c216aa412c427 | [
"BSD-3-Clause"
] | permissive | hlzz/dotfiles | b22dc2dc5a9086353ed6dfeee884f7f0a9ddb1eb | 0591f71230c919c827ba569099eb3b75897e163e | refs/heads/master | 2021-01-10T10:06:31.018179 | 2016-09-27T08:13:18 | 2016-09-27T08:13:18 | 55,040,954 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,195 | hpp | /*****************************************************************************/
/* XDMF */
/* eXtensible Data Model and Format */
/* */
/* Id : XdmfAttributeCenter.hpp */
/* */
/* Author: */
/* Kenneth Leiter */
/* kenneth.leiter@arl.army.mil */
/* US Army Research Laboratory */
/* Aberdeen Proving Ground, MD */
/* */
/* Copyright @ 2011 US Army Research Laboratory */
/* All Rights Reserved */
/* See Copyright.txt for details */
/* */
/* This software is distributed WITHOUT ANY WARRANTY; without */
/* even the implied warranty of MERCHANTABILITY or FITNESS */
/* FOR A PARTICULAR PURPOSE. See the above copyright notice */
/* for more information. */
/* */
/*****************************************************************************/
#ifndef XDMFATTRIBUTECENTER_HPP_
#define XDMFATTRIBUTECENTER_HPP_
// Includes
#include "Xdmf.hpp"
#include "XdmfItemProperty.hpp"
/**
* @brief Property describing where XdmfAttribute values are centered.
*
* XdmfAttributeCenter is a property used by XdmfAttribute to specify
* where its values are centered on an XdmfGrid. A specific
* XdmfAttributeCenter can be created by calling on of the static
* methods in the class, i.e. XdmfAttributeCenter::Cell().
* Xdmf supports the following attribute centers:
*
* Example of use:
*
* C++
*
* @dontinclude ExampleXdmfAttribute.cpp
* @skipline //#initialization
* @until //#initialization
* @skipline //#setCenter
* @until //#setCenter
* @skipline //#getCenter
* @until //#getCenter
*
* Python
*
* @dontinclude XdmfExampleAttribute.py
* @skipline #//initialization
* @until #//initialization
* @skipline #//setCenter
* @until #//setCenter
* @skipline #//getCenter
* @until #//getCenter
*
* Grid
* Cell
* Face
* Edge
* Node
*/
class XDMF_EXPORT XdmfAttributeCenter : public XdmfItemProperty {
public:
virtual ~XdmfAttributeCenter();
friend class XdmfAttribute;
// Supported Xdmf Attribute Centers
static shared_ptr<const XdmfAttributeCenter> Grid();
static shared_ptr<const XdmfAttributeCenter> Cell();
static shared_ptr<const XdmfAttributeCenter> Face();
static shared_ptr<const XdmfAttributeCenter> Edge();
static shared_ptr<const XdmfAttributeCenter> Node();
void
getProperties(std::map<std::string, std::string> & collectedProperties) const;
protected:
/**
* Protected constructor for XdmfAttributeCenter. The constructor
* is protected because all attribute centers supported by Xdmf
* should be accessed through more specific static methods that
* construct XdmfAttributeCenters -
* i.e. XdmfAttributeCenter::Node().
*
* @param name The name of the XdmfAttributeCenter to construct.
*/
XdmfAttributeCenter(const std::string & name);
private:
XdmfAttributeCenter(const XdmfAttributeCenter &); // Not implemented.
void operator=(const XdmfAttributeCenter &); // Not implemented.
static shared_ptr<const XdmfAttributeCenter>
New(const std::map<std::string, std::string> & itemProperties);
std::string mName;
};
#endif /* XDMFATTRIBUTECENTER_HPP_ */
| [
"shentianweipku@gmail.com"
] | shentianweipku@gmail.com |
51cb7b98dfd36c601da5d9bb9c40ac0ce1c626d6 | 6ca8f9a932f25494401c8974b463078745fef963 | /Engine/Code/Rectangle.cpp | 45e80c90cf9c42bc184ddeed1b97f2bd58fcb430 | [] | no_license | jang6556/DungeonDefenders | 29cca6047e828d8f2b5c77c0059cfbaace4d53bf | 526fe493b89ac4f8e883074f60a05a7b96fa0c43 | refs/heads/master | 2023-02-01T12:39:34.271291 | 2020-12-07T16:55:03 | 2020-12-07T16:55:03 | 319,384,221 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 8,676 | cpp | #include "..\Header\Rectangle.h"
CRectangle::CRectangle(LPDIRECT3DDEVICE9 _m_pGraphicDev)
:CVIBuffer(_m_pGraphicDev)
{
}
CRectangle::CRectangle(const CRectangle & rhs)
:CVIBuffer(rhs)
{
}
HRESULT CRectangle::Initialize()
{
iVertexSize = 36;
iIndexSize = 64;
m_pGraphicDev->CreateVertexBuffer(sizeof(VertexNormal) * iVertexSize, D3DUSAGE_WRITEONLY, D3DFVF_XYZ | D3DFVF_NORMAL, D3DPOOL_MANAGED, &VB, 0);
m_pGraphicDev->CreateIndexBuffer(sizeof(DWORD) * iIndexSize, D3DUSAGE_WRITEONLY, D3DFMT_INDEX16, D3DPOOL_MANAGED, &IB, 0);
VertexNormal* pVertex = nullptr;
VB->Lock(0, 0, (void**)&pVertex, 0);
//전면
pVertex[0] = VertexNormal(D3DXVECTOR3(-2.f, -3.f, -1.f));
pVertex[1] = VertexNormal(D3DXVECTOR3(-2.f, 3.f, -1.f));
pVertex[2] = VertexNormal(D3DXVECTOR3( 2.f, 3.f, -1.f));
pVertex[0].vNormal = VertexNoramlize(pVertex[0].vPosition, pVertex[1].vPosition, pVertex[2].vPosition);
pVertex[1].vNormal = VertexNoramlize(pVertex[0].vPosition, pVertex[1].vPosition, pVertex[2].vPosition);
pVertex[2].vNormal = VertexNoramlize(pVertex[0].vPosition, pVertex[1].vPosition, pVertex[2].vPosition);
pVertex[3] = VertexNormal(D3DXVECTOR3(-2.f, -3.f, -1.f));
pVertex[4] = VertexNormal(D3DXVECTOR3(2.f, 3.f, -1.f));
pVertex[5] = VertexNormal(D3DXVECTOR3(2.f, -3.f, -1.f));
pVertex[3].vNormal = VertexNoramlize(pVertex[3].vPosition, pVertex[4].vPosition, pVertex[5].vPosition);
pVertex[4].vNormal = VertexNoramlize(pVertex[3].vPosition, pVertex[4].vPosition, pVertex[5].vPosition);
pVertex[5].vNormal = VertexNoramlize(pVertex[3].vPosition, pVertex[4].vPosition, pVertex[5].vPosition);
//후면
pVertex[6] = VertexNormal(D3DXVECTOR3(2.f, -3.f, 1.f));
pVertex[7] = VertexNormal(D3DXVECTOR3(2.f, 3.f, 1.f));
pVertex[8] = VertexNormal(D3DXVECTOR3(-2.f, 3.f, 1.f));
pVertex[6].vNormal = VertexNoramlize(pVertex[6].vPosition, pVertex[7].vPosition, pVertex[8].vPosition);
pVertex[7].vNormal = VertexNoramlize(pVertex[6].vPosition, pVertex[7].vPosition, pVertex[8].vPosition);
pVertex[8].vNormal = VertexNoramlize(pVertex[6].vPosition, pVertex[7].vPosition, pVertex[8].vPosition);
pVertex[9 ] = VertexNormal(D3DXVECTOR3( 2.f, -3.f,1.f));
pVertex[10] = VertexNormal(D3DXVECTOR3(-2.f, 3.f, 1.f));
pVertex[11] = VertexNormal(D3DXVECTOR3(-2.f, -3.f, 1.f));
pVertex[9].vNormal = VertexNoramlize(pVertex[9].vPosition, pVertex[10].vPosition, pVertex[11].vPosition);
pVertex[10].vNormal = VertexNoramlize(pVertex[9].vPosition, pVertex[10].vPosition, pVertex[11].vPosition);
pVertex[11].vNormal = VertexNoramlize(pVertex[9].vPosition, pVertex[10].vPosition, pVertex[11].vPosition);
//우측
pVertex[12] = VertexNormal(D3DXVECTOR3(2.f, -3.f, -1.f));
pVertex[13] = VertexNormal(D3DXVECTOR3(2.f, 3.f, -1.f));
pVertex[14] = VertexNormal(D3DXVECTOR3(2.f, 3.f, 1.f));
pVertex[12].vNormal = VertexNoramlize(pVertex[12].vPosition, pVertex[13].vPosition, pVertex[14].vPosition);
pVertex[13].vNormal = VertexNoramlize(pVertex[12].vPosition, pVertex[13].vPosition, pVertex[14].vPosition);
pVertex[14].vNormal = VertexNoramlize(pVertex[12].vPosition, pVertex[13].vPosition, pVertex[14].vPosition);
pVertex[15] = VertexNormal(D3DXVECTOR3(2.f, -3.f, -1.f));
pVertex[16] = VertexNormal(D3DXVECTOR3(2.f, 3.f, 1.f));
pVertex[17] = VertexNormal(D3DXVECTOR3(2.f, -3.f, 1.f));
pVertex[15].vNormal = VertexNoramlize(pVertex[15].vPosition, pVertex[16].vPosition, pVertex[17].vPosition);
pVertex[16].vNormal = VertexNoramlize(pVertex[15].vPosition, pVertex[16].vPosition, pVertex[17].vPosition);
pVertex[17].vNormal = VertexNoramlize(pVertex[15].vPosition, pVertex[16].vPosition, pVertex[17].vPosition);
//좌측
pVertex[18] = VertexNormal(D3DXVECTOR3(-2.f, -3.f, 1.f));
pVertex[19] = VertexNormal(D3DXVECTOR3(-2.f, 3.f, 1.f));
pVertex[20] = VertexNormal(D3DXVECTOR3(-2.f, 3.f, -1.f));
pVertex[18].vNormal = VertexNoramlize(pVertex[18].vPosition, pVertex[19].vPosition, pVertex[20].vPosition);
pVertex[19].vNormal = VertexNoramlize(pVertex[18].vPosition, pVertex[19].vPosition, pVertex[20].vPosition);
pVertex[20].vNormal = VertexNoramlize(pVertex[18].vPosition, pVertex[19].vPosition, pVertex[20].vPosition);
pVertex[21] = VertexNormal(D3DXVECTOR3(-2.f, -3.f, 1.f));
pVertex[22] = VertexNormal(D3DXVECTOR3(-2.f, 3.f, -1.f));
pVertex[23] = VertexNormal(D3DXVECTOR3(-2.f, -3.f, -1.f));
pVertex[21].vNormal = VertexNoramlize(pVertex[21].vPosition, pVertex[22].vPosition, pVertex[23].vPosition);
pVertex[22].vNormal = VertexNoramlize(pVertex[21].vPosition, pVertex[22].vPosition, pVertex[23].vPosition);
pVertex[23].vNormal = VertexNoramlize(pVertex[21].vPosition, pVertex[22].vPosition, pVertex[23].vPosition);
//위
pVertex[24] = VertexNormal(D3DXVECTOR3(-2.f, 3.f, -1.f));
pVertex[25] = VertexNormal(D3DXVECTOR3(-2.f, 3.f, 1.f));
pVertex[26] = VertexNormal(D3DXVECTOR3(2.f, 3.f, 1.f));
pVertex[24].vNormal = VertexNoramlize(pVertex[24].vPosition, pVertex[25].vPosition, pVertex[26].vPosition);
pVertex[25].vNormal = VertexNoramlize(pVertex[24].vPosition, pVertex[25].vPosition, pVertex[26].vPosition);
pVertex[26].vNormal = VertexNoramlize(pVertex[24].vPosition, pVertex[25].vPosition, pVertex[26].vPosition);
pVertex[27] = VertexNormal(D3DXVECTOR3(-2.f, 3.f, -1.f));
pVertex[28] = VertexNormal(D3DXVECTOR3( 2.f, 3.f, 1.f));
pVertex[29] = VertexNormal(D3DXVECTOR3( 2.f, 3.f, -1.f));
pVertex[27].vNormal = VertexNoramlize(pVertex[27].vPosition, pVertex[28].vPosition, pVertex[29].vPosition);
pVertex[28].vNormal = VertexNoramlize(pVertex[27].vPosition, pVertex[28].vPosition, pVertex[29].vPosition);
pVertex[29].vNormal = VertexNoramlize(pVertex[27].vPosition, pVertex[28].vPosition, pVertex[29].vPosition);
//아래
pVertex[30] = VertexNormal(D3DXVECTOR3(-2.f, -3.f, 1.f));
pVertex[31] = VertexNormal(D3DXVECTOR3(-2.f, -3.f, -1.f));
pVertex[32] = VertexNormal(D3DXVECTOR3( 2.f, -3.f, -1.f));
pVertex[30].vNormal = VertexNoramlize(pVertex[30].vPosition, pVertex[31].vPosition, pVertex[32].vPosition);
pVertex[31].vNormal = VertexNoramlize(pVertex[30].vPosition, pVertex[31].vPosition, pVertex[32].vPosition);
pVertex[32].vNormal = VertexNoramlize(pVertex[30].vPosition, pVertex[31].vPosition, pVertex[32].vPosition);
pVertex[33] = VertexNormal(D3DXVECTOR3(-2.f, -3.f, 1.f));
pVertex[34] = VertexNormal(D3DXVECTOR3(2.f, -3.f, -1.f));
pVertex[35] = VertexNormal(D3DXVECTOR3(2.f, -3.f, 1.f));
pVertex[33].vNormal = VertexNoramlize(pVertex[33].vPosition, pVertex[34].vPosition, pVertex[35].vPosition);
pVertex[34].vNormal = VertexNoramlize(pVertex[33].vPosition, pVertex[34].vPosition, pVertex[35].vPosition);
pVertex[35].vNormal = VertexNoramlize(pVertex[33].vPosition, pVertex[34].vPosition, pVertex[35].vPosition);
VB->Unlock();
WORD* Indices = nullptr;
IB->Lock(0, 0, (void**)&Indices, 0);
Indices[0] = 0; Indices[1] = 1; Indices[2] = 2;
Indices[3] = 3; Indices[4] = 4; Indices[5] = 5;
Indices[6] = 6; Indices[7] = 7; Indices[8] = 8;
Indices[9] = 9; Indices[10] = 10; Indices[11] = 11;
Indices[12] = 12; Indices[13] = 13; Indices[14] = 14;
Indices[15] = 15; Indices[16] = 16; Indices[17] = 17;
Indices[18] = 18; Indices[19] = 19; Indices[20] = 20;
Indices[21] = 21; Indices[22] = 22; Indices[23] = 23;
Indices[24] = 24; Indices[25] = 25; Indices[26] = 26;
Indices[27] = 27; Indices[28] = 28; Indices[29] = 29;
Indices[30] = 30; Indices[31] = 31; Indices[32] = 32;
Indices[33] = 33; Indices[34] = 34; Indices[35] = 35;
IB->Unlock();
m_Material.Ambient = D3DXCOLOR(1.f, 0.f, 0.f, 1.f);
m_Material.Specular = D3DXCOLOR(1.f, 0.f, 0.f, 1.f);
m_Material.Diffuse = D3DXCOLOR(1.f, 0.f, 0.f, 1.f);
m_Material.Emissive = D3DXCOLOR(0.f, 0.f, 0.f, 0.f);
m_Material.Power = 5.f;
return NOERROR;
}
_int CRectangle::Progress(const _float & fTimeDelta)
{
return _int();
}
_int CRectangle::LateProgress(const _float & fTimeDelta)
{
return _int();
}
HRESULT CRectangle::Render(CTransform* pTransform)
{
D3DMATERIAL9 pOut;
m_pGraphicDev->GetMaterial(&pOut);
m_pGraphicDev->SetMaterial(&m_Material);
m_pGraphicDev->SetStreamSource(0, VB, 0, sizeof(VertexNormal));
m_pGraphicDev->SetIndices(IB);
m_pGraphicDev->SetFVF(D3DFVF_XYZ | D3DFVF_NORMAL);
m_pGraphicDev->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, iVertexSize, 0, 12);
//m_pGraphicDev->SetMaterial(&pOut);
return NOERROR;
}
CRectangle * CRectangle::Create(LPDIRECT3DDEVICE9 _m_pGraphicDev)
{
CRectangle* pInstance = new CRectangle(_m_pGraphicDev);
if (FAILED(pInstance->Initialize()))
{
_MSGBOX("CRectangle Created Failed");
Safe_Release(pInstance);
}
return pInstance;
}
CComponent * CRectangle::Clone()
{
return new CRectangle(*this);
}
void CRectangle::Free()
{
CVIBuffer::Free();
}
| [
"jang6556@gitbub.com"
] | jang6556@gitbub.com |
2b4c148b004e247c1ab55ff12efbe6d966bb18aa | 2252a5c24e8be3096eca7603d3e81815126addec | /image_helper.cpp | c359c08766d860dda30c286359323ee6c3389787 | [] | no_license | flyish/rsa_license | c6c138640c5a7c2d7a95a58739e394ed109312f9 | f0792efce29b5f68328a6e0587799df4cac9e3af | refs/heads/master | 2020-03-21T15:20:05.807397 | 2018-06-26T08:23:11 | 2018-06-26T08:23:11 | 138,706,880 | 1 | 1 | null | null | null | null | GB18030 | C++ | false | false | 3,937 | cpp | #include "stdafx.h"
#include "image_helper.h"
#include <windows.h>
bool image_find_section_pointer(void* pModuleBase, const char* lpszSectionName, void** ppPos, size_t* lpSize)
{
IMAGE_DOS_HEADER *pDosHead;
IMAGE_FILE_HEADER *pPEHead;
IMAGE_SECTION_HEADER *pSection;
*ppPos = NULL;
*lpSize = 0;
if (::IsBadReadPtr(pModuleBase, sizeof(IMAGE_DOS_HEADER)) || ::IsBadReadPtr(lpszSectionName, 8))
return false;
if (strlen(lpszSectionName) >= 16)
return false;
char szSecName[16];
memset(szSecName, 0, 16);
strncpy(szSecName, lpszSectionName, IMAGE_SIZEOF_SHORT_NAME);
unsigned char *pszModuleBase = (unsigned char *)pModuleBase;
pDosHead = (IMAGE_DOS_HEADER *)pszModuleBase;
//跳过DOS头不和DOS stub代码,定位到PE标志位置
DWORD Signature = *(DWORD *)(pszModuleBase + pDosHead->e_lfanew);
if (Signature != IMAGE_NT_SIGNATURE) //"PE/0/0"
return false;
//定位到PE header
pPEHead = (IMAGE_FILE_HEADER *)(pszModuleBase + pDosHead->e_lfanew + sizeof(DWORD));
int nSizeofOptionHeader;
if (pPEHead->SizeOfOptionalHeader == 0)
nSizeofOptionHeader = sizeof(IMAGE_OPTIONAL_HEADER);
else
nSizeofOptionHeader = pPEHead->SizeOfOptionalHeader;
bool bFind = false;
//跳过PE header和Option Header,定位到Section表位置
pSection = (IMAGE_SECTION_HEADER *)((unsigned char *)pPEHead + sizeof(IMAGE_FILE_HEADER)+nSizeofOptionHeader);
for (int i = 0; i < pPEHead->NumberOfSections; i++)
{
if (!strncmp(szSecName, (const char*)pSection[i].Name, IMAGE_SIZEOF_SHORT_NAME)) //比较段名称
{
*ppPos = (void *)(pszModuleBase + pSection[i].VirtualAddress); //计算实际虚地址
*lpSize = pSection[i].Misc.VirtualSize; //实际大小
bFind = true;
break;
}
}
return bFind;
}
int image_va_to_file_offset(void* pModuleBase, void* pVA)
{
IMAGE_DOS_HEADER *pDosHead;
IMAGE_FILE_HEADER *pPEHead;
IMAGE_SECTION_HEADER *pSection;
if (::IsBadReadPtr(pModuleBase, sizeof(IMAGE_DOS_HEADER)) || ::IsBadReadPtr(pVA, 4))
return -1;
unsigned char *pszModuleBase = (unsigned char *)pModuleBase;
pDosHead = (IMAGE_DOS_HEADER *)pszModuleBase;
//跳过DOS头不和DOS stub代码,定位到PE标志位置
DWORD Signature = *(DWORD *)(pszModuleBase + pDosHead->e_lfanew);
if (Signature != IMAGE_NT_SIGNATURE) //"PE/0/0"
return -1;
unsigned char *pszVA = (unsigned char *)pVA;
int nFileOffset = -1;
//定位到PE header
pPEHead = (IMAGE_FILE_HEADER *)(pszModuleBase + pDosHead->e_lfanew + sizeof(DWORD));
int nSizeofOptionHeader;
if (pPEHead->SizeOfOptionalHeader == 0)
nSizeofOptionHeader = sizeof(IMAGE_OPTIONAL_HEADER);
else
nSizeofOptionHeader = pPEHead->SizeOfOptionalHeader;
//跳过PE header和Option Header,定位到Section表位置
pSection = (IMAGE_SECTION_HEADER *)((unsigned char *)pPEHead + sizeof(IMAGE_FILE_HEADER)+nSizeofOptionHeader);
for (int i = 0; i < pPEHead->NumberOfSections; i++)
{
if (!strncmp(".text", (const char*)pSection[i].Name, 5)) //比较段名称
{
//代码文件偏移量 = 代码内存虚拟地址 - (代码段内存虚拟地址 - 代码段的文件偏移)
nFileOffset = (int)( pszVA - (pszModuleBase + pSection[i].VirtualAddress - pSection[i].PointerToRawData) );
break;
}
}
return nFileOffset;
}
int image_find_code_tag(void *pStartAddr, unsigned long *pTagLoc, unsigned long lTagValue, int nSerachLength)
{
int nPos = -1;
int i = 0;
unsigned char *pAddr = (unsigned char *)pStartAddr;
while (i < nSerachLength)
{
if ((*pAddr == 0xC7) && (*(pAddr + 1) == 0x05))//查找mov指令
{
unsigned long *Loc = (unsigned long *)((unsigned char*)pAddr + 2);
if (*Loc == (unsigned long)pTagLoc)//此处的数据*Loc就是全局静态变量的地址
{
unsigned long *Val = (unsigned long *)((unsigned char*)pAddr + 6);
if (*Val == lTagValue)//此处的数据*Val就是常数lTagValue值
{
nPos = i;
break;//find tag
}
}
}
pAddr++;
i++;
}
return nPos;
}
| [
"lihailuo@126.com"
] | lihailuo@126.com |
79b450ad1c3dc10bcbd003576b04c1cd4ebb8ecd | 4a83406f95a4ba8f15bb4bfff0bb34f5f36ddcde | /Atcoder/DP contest/B Frog 2.cpp | 77d84308084b8e707590c01073d2edc019d8ddba | [] | no_license | 2001adarsh/Contests | 5d3523ca6a5eb3eab0505733dc9144890eecb45e | a162b2a11b00d70e2b49292854b2ba826ca01311 | refs/heads/master | 2021-12-15T02:11:30.852367 | 2021-12-12T11:22:55 | 2021-12-12T11:22:55 | 252,377,884 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 710 | cpp | #include<bits/stdc++.h>
using namespace std;
#define int long long int
#define endl "\n"
#define inf 1000000000000000000LL
int dp[100005];
int32_t main()
{ ios_base::sync_with_stdio(false);
cin.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int n, K;
cin >> n >> K;
int arr[n];
for (int i = 0; i < n; ++i)
cin >> arr[i];
memset(dp, 0, sizeof dp);
for (int i = 1; i < n; i++) {
dp[i] = INT_MAX;
for (int j = 1; j <= K; j++) {
if (j <= i)
dp[i] = min(dp[i], dp[i - j] + abs(arr[i - j] - arr[i]));
}
}
cout << dp[n - 1];
return 0;
} | [
"2001adarshsingh@gmail.com"
] | 2001adarshsingh@gmail.com |
0dc244c68934dcf3e4b6aa5122bb96506787b345 | e51e8a6a04d0e57901cca3d866f33e54736053c9 | /CodeForces/1159/a/54029171.cpp | b9d2bd59cdc5ec8e791ff1362e6ec7e10d555196 | [] | no_license | Nipun4338/Solved-Programming-Problems | 7cb638112ef3d135fc6594eac9c6e79c5b0a0592 | 401a9ecc3157b8b4aa275ceb8c67f4e90213bccd | refs/heads/master | 2023-05-17T02:22:57.007396 | 2021-06-10T17:08:10 | 2021-06-10T17:08:10 | 283,442,802 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 385 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int a,sum=0;
char c;
cin>>a;
for(int i=0; i<a; i++)
{
cin>>c;
if(c=='+')
{
sum++;
}
else if(c=='-')
{
sum--;
if(sum<0)
{
sum=0;
}
}
}
cout<<sum<<endl;
return 0;
}
| [
"49658560+Nipun4338@users.noreply.github.com"
] | 49658560+Nipun4338@users.noreply.github.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.