blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
247
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 4
111
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
58
| visit_date
timestamp[ns]date 2015-07-25 18:16:41
2023-09-06 10:45:08
| revision_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| github_id
int64 3.89k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 25
values | gha_event_created_at
timestamp[ns]date 2012-06-07 00:51:45
2023-09-14 21:58:52
⌀ | gha_created_at
timestamp[ns]date 2008-03-27 23:40:48
2023-08-24 19:49:39
⌀ | gha_language
stringclasses 159
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
10.5M
| extension
stringclasses 111
values | filename
stringlengths 1
195
| text
stringlengths 7
10.5M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a0cdce3d798894adf81881125fcef92751a90a46
|
b46f65355d9a79e8d7ea7bd473a7d559ee601a1b
|
/src/curses/menu_horizontal.hpp
|
670196d4dfc07278f2015d2eb0044ee3678fab41
|
[] |
no_license
|
ekuiter/bsdl
|
8c50eba05f43a789fc58c2e92aa3cd0a6d62d52b
|
1f9d9cf5f1f55dab3480023456e244001a6a9eae
|
refs/heads/master
| 2020-04-05T15:16:29.337225
| 2018-10-16T19:40:46
| 2018-10-16T19:40:46
| 68,543,822
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,966
|
hpp
|
menu_horizontal.hpp
|
#pragma once
#include "menu_base.hpp"
#include "window_plain.hpp"
#include "window_sub.hpp"
#include "platform.hpp"
#include <vector>
#include <unordered_map>
#include <memory>
using namespace std;
namespace curses {
namespace menu {
template <typename T>
class horizontal : public base<T> {
vector<unique_ptr<window::sub>> tabs;
unordered_map<int, unique_ptr<window::plain>> tab_content_windows;
int tab_width, tab_height;
window::sub content_window;
int get_tabbing_width() {
return this->get_entries() * tab_width;
}
bool should_draw_closing_line() {
return get_tabbing_width() < this->_window.get_bounds().width;
}
void refresh_content_window() {
wborder(content_window.get(), 0, 0, ' ', 0, ACS_VLINE, ACS_VLINE, 0, 0);
this->_stream << content_window << stream::refresh();
if (should_draw_closing_line()) {
this->_stream << this->_window << stream::move(point(get_tabbing_width(), tab_height - 1)) <<
stream::write(stream::ext_char(ACS_HLINE),
this->_window.get_bounds().width - get_tabbing_width() - 1) <<
stream::ext_char(ACS_URCORNER) << stream::refresh();
}
}
void refresh_tab_content_window(int item) {
for (auto& pair : tab_content_windows)
pair.second->hide();
if (tab_content_windows[item])
tab_content_windows[item]->show();
else {
point p;
this->_stream << content_window << stream::get(p, stream::get::coord::BEG);
unique_ptr<window::plain> tab_content_window(
new window::plain(rectangle(p + point(2, 0), content_window.get_dimensions() - point(4, 1)))
);
tab_content_window->override_layer(this->_window.get_paneled_window().get_layer());
this->pointer_from(item)->create_view(*tab_content_window);
this->_stream << *tab_content_window << stream::refresh();
tab_content_windows[item] = move(tab_content_window);
}
}
void tab_border(window& tab, bool sel, bool neigh,
chtype ls, chtype rs, chtype ts, chtype bs, chtype tl, chtype tr, chtype bl, chtype br) {
point max = tab.get_dimensions() - point(1, 1);
ls = ls ? ls : ACS_VLINE, rs = rs ? rs : ACS_VLINE, ts = ts ? ts : ACS_HLINE, bs = bs ? bs : ACS_HLINE;
tl = tl ? tl : ACS_ULCORNER, tr = tr ? tr : ACS_URCORNER, bl = bl ? bl : ACS_LLCORNER, br = br ? br : ACS_LRCORNER;
auto vertical_line = [this, &max](int x, chtype c) {
for (int i = 1; i < max.y; i++)
this->_stream << stream::move(point(x, i)) << stream::write(stream::ext_char(c));
return "";
};
this->_stream << tab;
this->toggle_highlight(tab, sel);
this->_stream <<
stream::move(point(1, 0)) << stream::write(stream::ext_char(ts), max.x - 1) <<
stream::move(point(1, max.y)) << stream::write(stream::ext_char(bs), max.x - 1) <<
stream::move(point(max.x, 0)) << stream::ext_char(tr) <<
stream::move(point(max.x, max.y)) << stream::ext_char(br) << vertical_line(max.x, rs);
this->toggle_highlight(tab, neigh);
this->_stream << vertical_line(0, ls) <<
stream::move(point(0, 0)) << stream::ext_char(tl) <<
stream::move(point(0, max.y)) << stream::ext_char(bl);
this->toggle_highlight(tab, neigh);
this->toggle_highlight(tab, sel);
}
void refresh_border(window& tab, int entry, bool sel = false, bool neigh = false) {
chtype closing_corner = should_draw_closing_line() ? (sel ? ACS_LLCORNER : ACS_BTEE) : (sel ? ACS_VLINE : ACS_RTEE);
vector<vector<chtype>> borders = {
// rs, tl, tr, bl, br
/* 1 */ {0, 0, 0, sel ? ACS_VLINE : ACS_LTEE, sel ? ACS_LLCORNER : ACS_BTEE},
/* l */ {' ', 0, ACS_HLINE, sel ? ACS_VLINE : ACS_LTEE, sel ? ' ' : ACS_HLINE},
/* m */ {' ', ACS_TTEE, ACS_HLINE, sel ? ACS_LRCORNER : (neigh ? ACS_LLCORNER : ACS_BTEE), sel ? ' ' : ACS_HLINE},
/* r */ {0, ACS_TTEE, 0, sel ? ACS_LRCORNER : (neigh ? ACS_LLCORNER : ACS_BTEE), closing_corner}
};
int set = this->get_entries() == 1 ? 0 :
entry == 0 ? 1 :
entry < this->get_entries() - 1 ? 2 : 3;
tab_border(tab, sel, neigh, 0, borders[set][0], 0, sel ? ' ' : 0,
borders[set][1], borders[set][2], borders[set][3], borders[set][4]);
}
public:
horizontal(window& window, T& pointers, const typename base<T>::pointer_type selected_ptr = nullptr,
int _tab_width = 20, const color& highlight_color = color::get_accent_color()):
base<T>(window, pointers, selected_ptr, 0, window.get_bounds().width / _tab_width, highlight_color),
tab_width(_tab_width), tab_height(3),
content_window(window, rectangle(0, tab_height, window.get_dimensions() - point(0, tab_height))) {
if (this->item_number == 0)
throw exception("horizontal menu has no tabs");
for (int i = 0; i < this->max_entries; i++)
tabs.push_back(unique_ptr<window::sub>(
new window::sub(this->_window, rectangle(i * tab_width, 0, tab_width, tab_height))
));
window.set_keyboard_callback([this](int ch) {
if (ch == KEY_LEFT)
this->change_selection(-1);
if (ch == KEY_RIGHT)
this->change_selection(1);
return true;
});
int entry = 0;
for (auto& tab : tabs) {
tab->set_mouse_callback([this, entry](MEVENT e) {
if (entry >= this->item_number)
return true;
if (e.bstate & BUTTON1_PRESSED && e.x != 0)
this->select_entry(entry);
if (e.bstate & BUTTON2_PRESSED)
this->change_selection(-1);
if (e.bstate & BUTTON4_PRESSED)
this->change_selection(1);
return true;
});
entry++;
}
refresh();
}
~horizontal() {
for (auto ptr : this->pointers)
ptr->destroy_view();
}
void refresh() override {
this->refresh_items([this](int entry, int i, const typename base<T>::pointer_type ptr) {
window& tab = *tabs[entry];
this->_stream << tab << stream::move(point(2, 1));
this->refresh_item(tab, "", ptr, tab_width - 1);
refresh_border(tab, entry);
this->_stream << stream::refresh();
});
this->refresh_selected_item([this](int selected_entry) {
window& tab = *tabs[selected_entry];
this->_stream << tab << stream::move(point(1, 1)) <<
stream::write_attribute(A_BOLD, this->highlight_color, tab_width - 2);
refresh_border(tab, selected_entry, true);
this->_stream << stream::refresh();
int neighbour_entry = selected_entry + 1;
if (neighbour_entry < this->get_entries()) {
window& neighbour_tab = *tabs[neighbour_entry];
refresh_border(neighbour_tab, neighbour_entry, false, true);
this->_stream << neighbour_tab << stream::refresh();
}
});
refresh_content_window();
refresh_tab_content_window(this->selected_item);
}
};
}
}
|
68af46fe1af2e74dda91f8ef22d480cded54abe4
|
b81f164d4038e610abfd60a3bd660d5c2ad7dda1
|
/PerfectJazz/services/sound_Queue.h
|
3adc5e7f30017df21e57449fc6328843b299d862
|
[] |
no_license
|
MorbidCuriosity84/PerfectJazz
|
141a99c14d42d17972d67b5caf68433f6bd1b0b6
|
1145e43cc3354a72ba2fb7d4282aa243ecc8c079
|
refs/heads/main
| 2023-04-12T05:33:03.121711
| 2021-05-05T13:03:30
| 2021-05-05T13:03:30
| 353,403,708
| 1
| 0
| null | 2021-05-05T15:52:25
| 2021-03-31T15:28:15
|
C++
|
UTF-8
|
C++
| false
| false
| 479
|
h
|
sound_Queue.h
|
#pragma once
#include <queue>
#include <SFML/Audio.hpp>
#include "../game.h"
using namespace std;
using namespace sf;
//Holds a static array of ints that represents the current buffer being used
class SoundQueue
{
protected:
static int counts[32]; //keeps a pointer to the next available sound
public:
//Default constructor
SoundQueue() = default;
//Default destructor
~SoundQueue() = default;
//Gets sounds from the buffer
static sf::Sound getSound(SOUNDS sound);
};
|
4bd7f6e18563ed5a26b374679fce7b369da5c278
|
768371d8c4db95ad629da1bf2023b89f05f53953
|
/applayerprotocols/httpexamples/nwsswsptrhnd/CNwssWspTransportHandler.cpp
|
509926302da70331da16e3a152e066225c69a372
|
[] |
no_license
|
SymbianSource/oss.FCL.sf.mw.netprotocols
|
5eae982437f5b25dcf3d7a21aae917f5c7c0a5bd
|
cc43765893d358f20903b5635a2a125134a2ede8
|
refs/heads/master
| 2021-01-13T08:23:16.214294
| 2010-10-03T21:53:08
| 2010-10-03T21:53:08
| 71,899,655
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,157
|
cpp
|
CNwssWspTransportHandler.cpp
|
// Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies).
// All rights reserved.
// This component and the accompanying materials are made available
// under the terms of "Eclipse Public License v1.0"
// which accompanies this distribution, and is available
// at the URL "http://www.eclipse.org/legal/epl-v10.html".
//
// Initial Contributors:
// Nokia Corporation - initial contribution.
//
// Contributors:
//
// Description:
//
// System includes
//
#include <wsp/mwspcosessioncallback.h>
#include <wsp/mwspcomethodcallback.h>
#include <wsp/mwspproxyinfoprovider.h>
#include <wsp/mwspsessionheadersprovider.h>
#include <wsp/mwspcapabilityprovider.h>
#include <wsp/mwspcapabilityviewer.h>
#include <wsp/mwspcapabilitysetter.h>
#include <wsp/mwspextendedmethods.h>
#include <wsp/mwspheadercodepages.h>
#include <wsp/mwspaliasaddresses.h>
#include <wsp/mwspunknowncapabilities.h>
#include <http/mhttpdatasupplier.h>
#include <uri8.h>
// Local includes
//
#include "tnwsswsptrhndpanic.h"
#include "testoom.h"
// Class signature
//
#include "CNwssWspTransportHandler.h"
// Constants used in this file
//
//
// Implementation of class 'CNwssWspTransportHandler'
//
CNwssWspTransportHandler* CNwssWspTransportHandler::NewL(TAny* aInstantiationParams)
{
CNwssWspTransportHandler* me = new(ELeave)CNwssWspTransportHandler(aInstantiationParams);
CleanupStack::PushL(me);
me->ConstructL();
CleanupStack::Pop(me);
return me;
}
CNwssWspTransportHandler::CNwssWspTransportHandler(TAny* aInstantiationParams)
: CWspTransportHandler(*(REINTERPRET_CAST(CWspTransportHandler::SInstantiationParams*, aInstantiationParams)->iStringPool),
(REINTERPRET_CAST(CWspTransportHandler::SInstantiationParams*, aInstantiationParams)->iSecurityPolicy),
*(REINTERPRET_CAST(CWspTransportHandler::SInstantiationParams*, aInstantiationParams)->iSessionCB),
*(REINTERPRET_CAST(CWspTransportHandler::SInstantiationParams*, aInstantiationParams)->iProxyInfoProv),
*(REINTERPRET_CAST(CWspTransportHandler::SInstantiationParams*, aInstantiationParams)->iCapProv),
*(REINTERPRET_CAST(CWspTransportHandler::SInstantiationParams*, aInstantiationParams)->iSessHdrProv))
{
}
CNwssWspTransportHandler::~CNwssWspTransportHandler()
{
delete iWspCOSession;
iWapStackHnd.Close();
}
CWspTransportHandler::TWspSupportedServices CNwssWspTransportHandler::SupportedServices() const
{
// report what this plug-in can support
return CWspTransportHandler::ECOSessionService | CWspTransportHandler::ECOMethodInvocationService;
}
void CNwssWspTransportHandler::ConstructL()
{
// Create a Connection-Oriented session handler
MSecurityPolicy* secPol = (iSecurityPolicy? iSecurityPolicy : this);
iWspCOSession = CNwssWspCOSession::NewL(iStringPool, *this, *this, *secPol, iSessionCB);
// Connect to the WAP Stack server. Leave if this fails.
__TESTOOMD(stkErr, iWapStackHnd.Connect());
User::LeaveIfError(stkErr);
}
MWspCOSessionInvoker& CNwssWspTransportHandler::COSessionInvoker()
{
return *iWspCOSession;
}
MWspCOMethodInvoker& CNwssWspTransportHandler::COTransactionInvoker()
{
return *iWspCOSession;
}
MWspCOPushInvoker& CNwssWspTransportHandler::COPushInvoker()
{
TNwssWspTrHndPanic::Panic(TNwssWspTrHndPanic::ECOPushNotSupported);
return (MWspCOPushInvoker&)(*(MWspCOSessionInvoker*)NULL);
}
MWspCLMethodInvoker& CNwssWspTransportHandler::CLMethodInvoker()
{
TNwssWspTrHndPanic::Panic(TNwssWspTrHndPanic::EConnectionLessNotSupported);
return (MWspCLMethodInvoker&)(*(MWspCOSessionInvoker*)NULL);
}
MWspCLPushInvoker& CNwssWspTransportHandler::CLPushInvoker()
{
TNwssWspTrHndPanic::Panic(TNwssWspTrHndPanic::EConnectionLessNotSupported);
return (MWspCLPushInvoker&)(*(MWspCOSessionInvoker*)NULL);
}
RWAPServ& CNwssWspTransportHandler::WapStack()
{
return iWapStackHnd;
}
MWspProxyInfoProvider& CNwssWspTransportHandler::ProxyInfoProvider() const
{
return iProxyInfoProv;
}
MWspCapabilityProvider& CNwssWspTransportHandler::CapabilityProvider() const
{
return iCapProv;
}
MWspSessionHeadersProvider& CNwssWspTransportHandler::SessionHeadersProvider() const
{
return iSessHdrProv;
}
void
CNwssWspTransportHandler::ValidateUntrustedServerCert(TCertInfo& /*aServerCert*/,
TRequestStatus& aStatus) const
{
TRequestStatus* stat = &aStatus;
User::RequestComplete(stat, KErrNone);
}
void CNwssWspTransportHandler::CancelValidateUntrustedServerCert()
{
}
const RArray<TWtlsCipherSuite>& CNwssWspTransportHandler::GetWtlsCipherSuites()
{
return iDefSecPolCipherSuites;
}
const TDesC8&
CNwssWspTransportHandler::GetTlsCipherSuites()
{
return KNullDesC8();
}
const RArray<TWtlsKeyExchangeSuite>& CNwssWspTransportHandler::GetWtlsKeyExchangeSuites()
{
return iDefSecPolKeyExchSuite;
}
TInt
CNwssWspTransportHandler::GetNamedPolicyProperty(RStringF /*aPropertyName*/, RString& /*aPropertyValue*/)
{
return KErrNotFound;
}
void CNwssWspTransportHandler::Reserved1()
{
}
void CNwssWspTransportHandler::Reserved2()
{
}
TInt CNwssWspTransportHandler::ServerCert(TCertInfo& aCertInfo) const
{
return iWspCOSession->ServerCert(aCertInfo);
}
|
8d5497f529cb75f98d6feab658804821d9534910
|
cc75ad98e33a2722a022067dab29a0a9696effcf
|
/Classes/Networking/Command.h
|
791fda14919298866fa94dc88aeb197fcc1402c4
|
[] |
no_license
|
smj10j/LightSwarm
|
70056a6631d806d5023a420a522608abba9fe9d8
|
a40f990d92199528ea19798c201920dff9c654d3
|
refs/heads/master
| 2016-09-05T11:25:38.128554
| 2014-01-19T16:34:36
| 2014-01-19T16:34:36
| 6,862,613
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 774
|
h
|
Command.h
|
//
// Command.h
// LightSwarm
//
// Created by Stephen Johnson on 12/6/12.
//
//
#ifndef __LightSwarm__Command__
#define __LightSwarm__Command__
#include "Common.h"
#include "Spark.h"
#include "Orb.h"
#include "GameScene.h"
#include <set>
#include <list>
USING_NS_CC;
using namespace std;
enum COMMAND_TYPE {
MOVE
};
enum COMMAND_ID_TYPE {
ORB,
SPARK
};
class Command
{
public:
Command(COMMAND_TYPE command, int frame, COMMAND_ID_TYPE idType, list<int>& ids, list<CCPoint>& path):
_command(command),
_frame(frame),
_idType(idType),
_ids(ids),
_path(path) {
}
virtual ~Command();
COMMAND_TYPE _command;
int _frame;
COMMAND_ID_TYPE _idType;
list<int> _ids;
list<CCPoint> _path;
private:
};
#endif /* defined(__LightSwarm__Command__) */
|
1e37ba6f90ad10c98f7a8f38664b8a29083eec58
|
b34cd2fb7a9e361fe1deb0170e3df323ec33259f
|
/Nexus/Source/DefinitionsTests/RegionTester.cpp
|
578e53ee97ed514a48febada7e77aa522b8e256e
|
[] |
no_license
|
lineCode/nexus
|
c4479879dba1fbd11573c129f15b7b3c2156463e
|
aea7e2cbcf96a113f58eed947138b76e09b8fccb
|
refs/heads/master
| 2022-04-19T01:10:22.139995
| 2020-04-16T23:07:23
| 2020-04-16T23:07:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,370
|
cpp
|
RegionTester.cpp
|
#include "Nexus/DefinitionsTests/RegionTester.hpp"
#include "Nexus/Definitions/DefaultCountryDatabase.hpp"
#include "Nexus/Definitions/DefaultMarketDatabase.hpp"
#include "Nexus/Definitions/Region.hpp"
using namespace Nexus;
using namespace Nexus::Tests;
using namespace std;
namespace {
void TestProperSubset(const Region& subset, const Region& superset) {
CPPUNIT_ASSERT(subset < superset);
CPPUNIT_ASSERT(subset <= superset);
CPPUNIT_ASSERT(!(subset == superset));
CPPUNIT_ASSERT(subset != superset);
CPPUNIT_ASSERT(!(subset >= superset));
CPPUNIT_ASSERT(!(subset > superset));
CPPUNIT_ASSERT(!(superset < subset));
CPPUNIT_ASSERT(!(superset <= subset));
CPPUNIT_ASSERT(!(superset == subset));
CPPUNIT_ASSERT(superset != subset);
CPPUNIT_ASSERT(superset >= subset);
CPPUNIT_ASSERT(superset > subset);
}
void TestDistinctSets(const Region& a, const Region& b) {
CPPUNIT_ASSERT(!(a < b));
CPPUNIT_ASSERT(!(a <= b));
CPPUNIT_ASSERT(!(a == b));
CPPUNIT_ASSERT(a != b);
CPPUNIT_ASSERT(!(a >= b));
CPPUNIT_ASSERT(!(a > b));
CPPUNIT_ASSERT(!(b < a));
CPPUNIT_ASSERT(!(b <= a));
CPPUNIT_ASSERT(!(b == a));
CPPUNIT_ASSERT(b != a);
CPPUNIT_ASSERT(!(b >= a));
CPPUNIT_ASSERT(!(b > a));
}
}
void RegionTester::TestMarketRegionSubsetOfCountryRegion() {
Region country = DefaultCountries::US();
Region market = GetDefaultMarketDatabase().FromCode(DefaultMarkets::NASDAQ());
TestProperSubset(market, country);
}
void RegionTester::TestSecurityRegionSubsetOfMarketRegion() {
Region market = GetDefaultMarketDatabase().FromCode(DefaultMarkets::NASDAQ());
Region security = Security("TST", DefaultMarkets::NASDAQ(),
DefaultCountries::US());
TestProperSubset(security, market);
}
void RegionTester::TestSecurityRegionSubsetOfCountryRegion() {
Region country = DefaultCountries::US();
Region security = Security("TST", DefaultMarkets::NASDAQ(),
DefaultCountries::US());
TestProperSubset(security, country);
}
void RegionTester::TestDistinctCountryRegions() {
Region us = DefaultCountries::US();
Region ca = DefaultCountries::CA();
TestDistinctSets(us, ca);
Region northAmerica = us + ca;
Region br = DefaultCountries::BR();
TestDistinctSets(northAmerica, br);
TestProperSubset(us, northAmerica);
TestProperSubset(ca, northAmerica);
}
|
4a20305f7f42eb96c5b1730df920edecd649ca00
|
63413883346217e542efd49c411dee9ff7fd32a0
|
/Farthest Nodes in a Tree.cpp
|
cd238c48610941aa773cb1fbe38f197a02646eae
|
[] |
no_license
|
ssangskriti/Random
|
0592a7f3c56cda84d4a86ea2b48a12e6db6186bf
|
47e0448ebe5385b076164a61323229135b90c8a1
|
refs/heads/master
| 2021-06-27T23:17:21.454898
| 2020-11-16T17:15:43
| 2020-11-16T17:15:43
| 188,286,093
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,637
|
cpp
|
Farthest Nodes in a Tree.cpp
|
#include<bits/stdc++.h>
using namespace std;
vector<pair<long long int,long long int>>v[30000];
long long int visited[30000],weight[30000];
void bfs(long long int node)
{
queue<long long int> q;
q.push(node);
long long int i,fro;
memset(visited,0,sizeof(visited));
visited[node] = 1;
while(!q.empty())
{
fro = q.front();
q.pop();
for(i=0; i<v[fro].size(); i++)
{
if(visited[v[fro][i].first]==0)
{
visited[v[fro][i].first] = 1;
q.push(v[fro][i].first);
weight[v[fro][i].first]= weight[fro]+v[fro][i].second;
}
}
}
}
int main()
{
long long int n,a,b,i,j,w,k,t;
cin>>t;
for(k=1; k<=t; k++)
{
for(i=0; i<30000; i++)
v[i].clear();
cin>>n;
memset(weight,0,sizeof(weight));
pair<long long int, long long int> p;
for(i=0; i<n-1; i++)
{
cin>>a>>b>>w;
p.first=b, p.second=w;
v[a].push_back(p);
p.first=a;
v[b].push_back(p);
}
bfs(0);
long long int maxim =-1,node;
for(i=0; i<n; i++)
{
if(maxim<weight[i])
{
maxim=weight[i];
node=i;
}
}
memset(weight,0,sizeof(weight));
maxim=-1;
bfs(node);
for(i=0; i<n; i++)
{
if(maxim<weight[i])
{
maxim=weight[i];
}
}
printf("Case %lld: %lld\n",k,maxim);
}
return 0;
}
|
925f845843dba04c93e8c8aa7e670057ebed4f86
|
4bf7d1afba08d81993060103a510b2e4a350a9ed
|
/Acid/src/Utilities/XmlReader.cpp
|
6f433fd428d091f5e91554732ac22a22c9a04413
|
[] |
no_license
|
ChrisToumanian/Acid-Engine
|
7b27d9d5b66c640db19343701843293f4ca1eab5
|
350548a02c2e58d9921070648be1e191cc5f11ee
|
refs/heads/master
| 2021-05-05T09:42:01.513051
| 2018-01-17T22:21:16
| 2018-01-17T22:21:16
| 114,245,811
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 843
|
cpp
|
XmlReader.cpp
|
#include "XmlReader.h"
XmlReader::XmlReader(string _filename)
{
filename = _filename;
stream.open(filename);
if (!stream.is_open())
{
readable = false;
}
else
{
readable = true;
}
}
string XmlReader::GetXML()
{
string xml = "";
if (readable)
{
string word;
stream >> word;
while (stream.good())
{
xml += word;
xml += " ";
stream >> word;
}
Reset();
}
return xml;
}
string XmlReader::FindValue(string name)
{
string value = "";
string xml = GetXML();
int occurance = xml.find(name);
if (occurance != -1)
{
value = xml.substr(occurance, xml.size());
int begin = value.find(">") + 1;
int end = value.find("</");
value = value.substr(begin, end - begin);
}
return value;
}
void XmlReader::Reset()
{
stream.clear();
stream.seekg(0);
}
|
9826c27d3cffe36c30fa87cf43ffcd07e7382582
|
a31be33001e81982c5a5c7ba5c53489e3d77015b
|
/CPP/Datashit/09-10-2017_12-09-39/C__SamyeProstyeProgrammy/pr8.cpp
|
ceafeb8e1a8452b54f3e87b2cdf65e8826a1259f
|
[] |
no_license
|
uvlad7/1_course
|
b713933c52f042a23cb9edf31f667a4de038a162
|
ff81d57cbae7c195f4512f1fee7edf21c5bfa858
|
refs/heads/master
| 2023-05-13T11:50:31.479184
| 2021-05-30T18:43:36
| 2021-05-30T18:43:36
| 372,290,084
| 0
| 0
| null | null | null | null |
WINDOWS-1251
|
C++
| false
| false
| 648
|
cpp
|
pr8.cpp
|
//поиск простых чисел по уже найденым (по массиву простых чисел)
#include <iostream>
#include <math.h>
#include <conio.h>
using namespace std;
int main()
{
int n,i=0,k=3,temp=1;
int *a;
bool c=0;
cout<<"input maximum = ";
cin>>n;
a=new int [n];
a[0]=2;
while(k<=n)
{
while(i<temp&&a[i]<int(sqrt(double(n))))
{
if (k%a[i]==0)
{
c=1;
break;
}
i++;
}
if (c==0)
{
i=temp+1;
a[i]=k;
cout<<k<<" ";
k++;
temp++;
i=0;
}
else
{
k++;
c=0;
i=0;
}
}
cout<<endl;
system("PAUSE");
}
|
b9a8da344ec048fe187ac9189f9f36033f478f72
|
9aaef904b70f8f8e04a87cbd9f0eedf806632755
|
/Week1/hw1.cpp
|
278ffe62b32a430e395276d109531d52a4983082
|
[] |
no_license
|
dsansyzbayev/Algo-DataStr
|
b1b7ac54d276ba69338a40ea9b99a4617fee8f76
|
bac173bb745767363fdd4781234614f609f3f745
|
refs/heads/master
| 2020-09-10T23:44:04.615995
| 2019-11-15T07:31:39
| 2019-11-15T07:31:39
| 221,868,854
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,178
|
cpp
|
hw1.cpp
|
#include <iostream>
#include <queue>
using namespace std;
template<typename T>
class Node{
public:
T data;
Node *next;
Node *prev;
Node(int data){
this ->data = data;
next = NULL;
prev = NULL;
}
};
template<typename T>
class Queue{
public:
Node<T> *head, *tail;
int sz;
Queue(){
head = NULL;
tail = NULL;
sz= 0;
}
int size(){
return sz;
}
bool empty(){
return sz == 0;
}
void push_back(T data){
Node<T> *node = new Node<T>(data);
if(head == NULL){
head = node;
tail = node;
}
else {
node->prev = tail;
tail->next = node;
tail = node;
}
sz++;
}
void push_front(T data){
Node<T> *node = new Node<T>(data);
if(head == NULL){
tail=node;
head = node;
}
else {
node->next = head;
head->prev = node;
head = node;
}
sz++;
}
void pop_front(){
if(head!= NULL){
head = head->next;
sz--;
}
}
void pop_back(){
if(tail!=NULL){
tail = tail->prev;
sz--;
}
}
T last(){
return tail->data;
}
T front(){
return head->data;
}
};
int main(){
Queue<int> *queue = new Queue<int>();
while(true){
string s;
cin >> s;
if(s=="push_front"){
int n;
cin >> n;
queue->push_front(n);
cout<< "ok";
}
else if(s=="push_back"){
int n;
cin >> n;
queue->push_back(n);
cout << "ok";
}
else if(s=="pop_front"){
if(queue->size()>0)
queue->pop_front();
else
cout << "error";
}
else if(s=="pop_back"){
if(queue -> size() >0)
queue->pop_back();
else
cout << "error";
}
else if(s=="front"){
if(queue->size()>0)
cout << queue->front();
else
cout << "error";
}
else if(s=="last"){
if(queue->size() >0)
cout << queue ->last();
else
cout << "error";
}
else if(s=="size"){
cout << queue->size();
}
else if(s=="clear"){
while(!queue->empty()){
queue->pop_back();
}
if(queue->empty()){
cout << "ok";
}
}
else if(s=="exit"){
cout << "bye";
exit(0);
}
}
return 0;
}
|
d4ff559c1db413920e1689abe1b0e04cc6622515
|
cd790fb7e8ef78b1989531f5864f67649dcb1557
|
/uva10474(WhereistheMarble).cpp
|
d8fea65a5131a8ca576ac1be7ec6c91460b78243
|
[] |
no_license
|
FatimaTasnim/uva-solution
|
59387c26816c271b17e9604255934b7c8c7faf11
|
c7d75f0a5384229b243504dfbef4686052b9dea8
|
refs/heads/master
| 2020-03-27T22:23:18.611201
| 2018-10-23T05:53:46
| 2018-10-23T05:53:46
| 147,226,519
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,233
|
cpp
|
uva10474(WhereistheMarble).cpp
|
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,m,q,raju,num,i,j,f,l,mid,ans,c=1,flag;
vector<int>meena;
freopen("test.txt","r",stdin);
freopen("test1.txt","w",stdout);
while(1){
//ans=-1;
scanf("%d%d",&n,&q);
if(n==q && q==0)break;
printf("CASE# %d:\n",c++);
for(j=0;j<n;j++){
scanf("%d",&num);
meena.push_back(num);
}
sort(meena.begin(),meena.end());
for(i=0;i<q;i++){
flag=0,ans=-1;
scanf("%d",&raju);
f=1,l=n;
mid=(f+l)/2;
while(f<=l){
// cout << mid << " " << meena[mid-1]<<endl;
// system("pause");
if(meena[mid-1]<raju)
f=mid+1;
if(meena[mid-1]>raju)
l=mid-1;
if(meena[mid-1]==raju){
if(meena[mid-2]<raju||mid==1){
ans=mid;
break;
}
else mid--,flag=1;
}
//cout << f << " " << l << endl;
if(flag==0)
mid=(f+l)/2;
}
if(ans<0)
printf("%d not found\n",raju);
else printf("%d found at %d\n",raju,ans);
}
meena.clear();
}
return 0;
}
|
b85ccf0febef17786089b5876bbd086ce200c4a3
|
d184b9046d8a6816c6d2f23ce1bb730d9f1daa8b
|
/cpp_11_examples/ranged_based_for_loop.h
|
d8fc968ca1f325532d00afeeca1db7da8a926cc3
|
[] |
no_license
|
pabitrapadhy/cpp_11_examples
|
0fbbed11f23bf3e72eee136548674a3ba877c4cf
|
824966eff3b957b0ab4222103d942dec7b678bfe
|
refs/heads/master
| 2020-03-20T15:14:29.670901
| 2018-08-05T16:13:15
| 2018-08-05T16:13:15
| 137,507,784
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,031
|
h
|
ranged_based_for_loop.h
|
//
// ranged_based_for_loop.h
// cpp_11_examples
//
// Created by Padhy, Pabitra on 17/06/18.
// Copyright © 2018 Padhy, Pabitra. All rights reserved.
//
// https://www.geeksforgeeks.org/range-based-loop-c/
#ifndef ranged_based_for_loop_h
#define ranged_based_for_loop_h
#include <iostream>
#include <vector>
#include <map>
using namespace std;
namespace PP_CPP11 {
// NOTE: this uses the uniform initialization & initializers list of C++11
std::vector<int> mylist = {1,2,3,4,5};
std::map<std::string, int> mymap = {{"a", 97}, {"b", 98}, {"c", 99}, {"d", 100}};
// logic execution
bool execute() {
for (auto& i : mylist) {
i *= 2;
cout << "\nitem : " << i;
}
for (auto i : {1,2,3,4,5}) {
cout << "\nitem : " << i;
}
for (auto it : mymap) {
cout << "\n map key is: " << it.first << ", map value is: " << it.second;
}
return true;
}
}
#endif /* ranged_based_for_loop_h */
|
e2b5f28b505caa52714f50956468defa06174f03
|
7fbdba315508dd46e99cb2f0438df7eb91cc7846
|
/lowercase/Source.cpp
|
b86b88a6c096c2bfcc1c5a8efdd6659ecf75935f
|
[] |
no_license
|
jayrosen-design/Lowercase
|
ac219f58a64d117441186885eb5154804fdf2ce7
|
e4314ba841098010ab60b7a2ef648f51cdee36e2
|
refs/heads/master
| 2018-01-09T18:54:05.479927
| 2015-12-16T20:10:56
| 2015-12-16T20:10:56
| 48,132,536
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,498
|
cpp
|
Source.cpp
|
//Jay Rosen
//This program opens, reads, and writes to a file the lowercase string of original contents
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
using namespace std;
// Grammar class declaration
class Grammar
{
private:
static const int SIZE = 500;
char fileName1[SIZE];
char fileName2[SIZE];
char ch;
public:
ifstream inFile;
fstream outFile;
void getInFile(string);
void getOutFile(string);
void closeFile();
void lowerCase();
};
// Program that uses Grammar class
/**************************************************************
* Grammar::getInFile *
* Open txt file that user input the name of and validate. *
**************************************************************/
void Grammar::getInFile(string fileName1)
{
inFile.open(fileName1);
if (!inFile)
{
cout << "\n\t\tERROR: could not be read file\n\n\t\t";
exit(0);
}
}
/**************************************************************
* Grammar::getOutFile *
* Create txt file that user input the name of and pass to lowerCase() *
**************************************************************/
void Grammar::getOutFile(string fileName2)
{
outFile.open(fileName2, ios::out);
lowerCase();
}
/**************************************************************
* Grammar::lowercase *
* Transform strings from text file to all lowercase *
**************************************************************/
void Grammar::lowerCase()
{
inFile.get(ch);
while (!inFile.eof())
{
outFile.put(tolower(ch));
inFile.get(ch);
}
closeFile();
}
/**************************************************************
* Grammar::closeFile *
* Open txt file that user input the name of and validate. *
**************************************************************/
void Grammar::closeFile()
{
inFile.close();
outFile.close();
cout << "\n\t\tGrammar editor has edited the file.\n\t\tCheck txt file for results.\n\n\t\t";
}
//Driver programs
int main()
{
Grammar editor;
string file1 = "";
string file2 = "";
cout << "\n\n\n\t\tWhat txt file do you want to edit? ";
cin >> file1;
editor.getInFile(file1);
cout << "\t\tWhere should " << file1 << " edits be saved to? ";
cin >> file2;
editor.getOutFile(file2);
system("pause");
return 0;
}
|
25f3183fe00ee3137aa4d733345cd0c9894b3277
|
04afcedce033eb35c2bbccf72fbf382fba348f43
|
/CECS 275_ Lab 6/CECS 275 Lab 6/main.cpp
|
d348e897058f9ee0f915f695008223cdbbc78223
|
[] |
no_license
|
trevor1232/Data-Structures
|
a53c8c46dd57d57554e630e2a69fb0bab10a7567
|
409454cefdb037a551a43c15d881cf4daee5d3f5
|
refs/heads/master
| 2022-11-30T21:51:25.205098
| 2020-08-05T03:06:07
| 2020-08-05T03:06:07
| 285,160,132
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,091
|
cpp
|
main.cpp
|
/*
Name: Trevor Scott
Date: 03/19/2020
Program: Project1: Yaht-Z Game
Description: This game was made by using classes, functions, and an array of dice. This game's purpose was to find the following:
matching dies, a series of dies, and three of a kind dice. I separated the respected classes into .h header files and .cpp files. As you keep finding matches you will increment your point total.
*/
//directives
#include <iostream>
#include <ctime>
#include "CheckInput.h"
#include "Player.h"
#include "die.h"
using namespace std;
//main
int main(){
//menu
cout << "Welcome to the Yaht-z Game!!!" << endl;
cout << endl;
//calling the class and having play as starting it
Player play;
bool keepPlaying =true;
//this is to call srand and use it for dice to have random values
srand(time(NULL));
while(keepPlaying){
play.takeTurn();
cout << "Play again? (Y or N)";
keepPlaying = getYesNo();
}
cout << "Game is over! " << endl;
cout << "Final Score = " << play.getPoints() << " Points" << endl;
}
|
22893e42cf971eed6f4a0a42db438c319ef151bf
|
45b13ef1f5d2c9047af75d75f93c11479a7e63c5
|
/json.cpp
|
c00e8f919266aa006d2383e5c3eedf390ec6b881
|
[] |
no_license
|
Irbis691/Labs
|
2e8ab012c08d4ce31daa5477f73f60ea8d4ba134
|
4280e8b06ef142cdcd8d9fe9d950e67ee7b53790
|
refs/heads/master
| 2022-12-21T15:06:34.153531
| 2020-09-17T14:34:35
| 2020-09-17T14:34:35
| 295,177,696
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,808
|
cpp
|
json.cpp
|
#include <iostream>
#include "json.h"
using namespace std;
namespace Json {
Document::Document(Node root) : root(move(root)) {
}
const Node& Document::GetRoot() const {
return root;
}
Node LoadNode(istream& input);
Node LoadArray(istream& input) {
vector<Node> result;
for(char c; input >> c && c != ']';) {
if(c != ',') {
input.putback(c);
}
result.push_back(LoadNode(input));
}
return Node(move(result));
}
Node LoadIntOrDouble(istream& input) {
string result;
if(input.peek() == '-') {
result += '-';
input.get();
}
while (isdigit(input.peek())) {
result += to_string(input.get() - '0');
}
if(input.peek() == '.') {
result += '.';
input.get();
while (isdigit(input.peek())) {
result += to_string(input.get() - '0');
}
return Node(stod(result));
}
return Node(stoi(result));
}
Node LoadString(istream& input) {
string line;
getline(input, line, '"');
return Node(move(line));
}
Node LoadDict(istream& input) {
map<string, Node> result;
for(char c; input >> c && c != '}';) {
if(c == ',') {
input >> c;
}
string key = LoadString(input).AsString();
input >> c;
result.emplace(move(key), LoadNode(input));
}
return Node(move(result));
}
Node LoadBool(istream& input) {
bool b;
input >> boolalpha >> b;
return Node(b);
}
Node LoadNode(istream& input) {
char c;
input >> c;
if(c == '[') {
return LoadArray(input);
} else if(c == '{') {
return LoadDict(input);
} else if(c == '"') {
return LoadString(input);
} else {
input.putback(c);
c = input.peek();
if(c == 't' || c == 'f') {
return LoadBool(input);
} else {
return LoadIntOrDouble(input);
}
}
}
Document Load(istream& input) {
return Document{LoadNode(input)};
}
}
|
befc2f01fca42816f64022cb7f3a933ecd2320eb
|
64491dfc2e3a06a6d58086f75e5afee23f3d3e3b
|
/qml/test/Controller_c.cpp
|
eb0c14c3d1fb9fd483759e8ce6d9a8ed9e51d5f1
|
[] |
no_license
|
gasche/lablqt
|
9f59e01ee1a0c6cacc31fb06e0dd58e24aab0337
|
0f2c8f8f5c1cdc96d4d7a199ada1adf1592188b6
|
refs/heads/master
| 2021-01-22T17:15:02.404661
| 2013-12-13T15:06:39
| 2013-12-13T15:06:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,521
|
cpp
|
Controller_c.cpp
|
#include "Controller_c.h"
Controller::Controller() : _camlobjHolder(0) {
}
//onItemSelected: int->int->unit
void Controller::onItemSelected(int x0,int x1) {
CAMLparam0();
CAMLlocal3(_ans,_meth,_x0);
CAMLlocalN(_args,3);
CAMLlocal2(_cca0,_cca1);
value _camlobj = this->_camlobjHolder;
Q_ASSERT(Is_block(_camlobj));
Q_ASSERT(Tag_val(_camlobj) == Object_tag);
_meth = caml_get_public_method(_camlobj, caml_hash_variant("onItemSelected"));
_args[0] = _camlobj;
_cca0 = Val_int(x0);
_args[1] = _cca0;
_cca1 = Val_int(x1);
_args[2] = _cca1;
caml_callbackN(_meth, 3, _args);
CAMLreturn0;
}
//setPaths: string list->unit
void Controller::setPaths(QList<QString> x0) {
CAMLparam0();
CAMLlocal5(_ans,_meth,_x0,_x1,_x2);
CAMLlocalN(_args,2);
CAMLlocal1(_cca0);
value _camlobj = this->_camlobjHolder;
Q_ASSERT(Is_block(_camlobj));
Q_ASSERT(Tag_val(_camlobj) == Object_tag);
_meth = caml_get_public_method(_camlobj, caml_hash_variant("setPaths"));
_args[0] = _camlobj;
_cca0 = Val_emptylist;
if ((x0).length() != 0) {
auto it = (x0).end() - 1;
for (;;) {
_x0 = caml_alloc(2,0);
_x1 = caml_copy_string((*it).toLocal8Bit().data() );
Store_field(_x0, 0, _x1);
Store_field(_x0, 1, _cca0);
_cca0 = _x0;
if ((x0).begin() == it) break;
it--;
}
}
_args[1] = _cca0;
caml_callbackN(_meth, 2, _args);
CAMLreturn0;
}
//paths: string list
QList<QString> Controller::paths() {
CAMLparam0();
CAMLlocal5(_ans,_meth,_x0,_x1,_x2);
CAMLlocalN(_args,1);
value _camlobj = this->_camlobjHolder;
Q_ASSERT(Is_block(_camlobj));
Q_ASSERT(Tag_val(_camlobj) == Object_tag);
_meth = caml_get_public_method(_camlobj, caml_hash_variant("paths"));
_ans = caml_callback2(_meth, _camlobj, Val_unit);
QList<QString> cppans;
//generating: string list
_x0 = _ans;
while (_x0 != Val_emptylist) {
_x1 = Field(_x0,0); /* head */
QString xx1;
xx1 = QString(String_val(_x1));
cppans << xx1;
_x0 = Field(_x0,1);
}
CAMLreturnT(QList<QString>,cppans);
}
//getFullPath: string
QString Controller::getFullPath() {
CAMLparam0();
CAMLlocal3(_ans,_meth,_x0);
CAMLlocalN(_args,1);
value _camlobj = this->_camlobjHolder;
Q_ASSERT(Is_block(_camlobj));
Q_ASSERT(Tag_val(_camlobj) == Object_tag);
_meth = caml_get_public_method(_camlobj, caml_hash_variant("getFullPath"));
_ans = caml_callback2(_meth, _camlobj, Val_unit);
QString cppans;
cppans = QString(String_val(_ans));
CAMLreturnT(QString,cppans);
}
//isHasData: bool
bool Controller::isHasData() {
CAMLparam0();
CAMLlocal3(_ans,_meth,_x0);
CAMLlocalN(_args,1);
value _camlobj = this->_camlobjHolder;
Q_ASSERT(Is_block(_camlobj));
Q_ASSERT(Tag_val(_camlobj) == Object_tag);
_meth = caml_get_public_method(_camlobj, caml_hash_variant("isHasData"));
_ans = caml_callback2(_meth, _camlobj, Val_unit);
bool cppans;
cppans = Bool_val(_ans);
CAMLreturnT(bool,cppans);
}
extern "C" value caml_Controller_hasDataChanged_cppmeth_wrapper(value _cppobj,value _x0) {
CAMLparam2(_cppobj,_x0);
CAMLlocal1(_z0);
Controller *o = (Controller*) (Field(_cppobj,0));
bool z0;
z0 = Bool_val(_x0);
o->hasDataChanged(z0);
CAMLreturn(Val_unit);
}
//getDescr: string
QString Controller::getDescr() {
CAMLparam0();
CAMLlocal3(_ans,_meth,_x0);
CAMLlocalN(_args,1);
value _camlobj = this->_camlobjHolder;
Q_ASSERT(Is_block(_camlobj));
Q_ASSERT(Tag_val(_camlobj) == Object_tag);
_meth = caml_get_public_method(_camlobj, caml_hash_variant("getDescr"));
_ans = caml_callback2(_meth, _camlobj, Val_unit);
QString cppans;
cppans = QString(String_val(_ans));
CAMLreturnT(QString,cppans);
}
extern "C" value caml_Controller_descChanged_cppmeth_wrapper(value _cppobj,value _x0) {
CAMLparam2(_cppobj,_x0);
CAMLlocal1(_z0);
Controller *o = (Controller*) (Field(_cppobj,0));
QString z0;
z0 = QString(String_val(_x0));
o->descChanged(z0);
CAMLreturn(Val_unit);
}
extern "C" value caml_create_Controller(value _dummyUnitVal) {
CAMLparam1(_dummyUnitVal);
CAMLlocal1(_ans);
_ans = caml_alloc_small(1, Abstract_tag);
(*((Controller **) &Field(_ans, 0))) = new Controller();
CAMLreturn(_ans);
}
extern "C" value caml_store_value_in_Controller(value _cppobj,value _camlobj) {
CAMLparam2(_cppobj,_camlobj);
Controller *o = (Controller*) (Field(_cppobj,0));
o->storeCAMLobj(_camlobj); // register global root in member function
//caml_register_global_root(&(o->_camlobjHolder));
CAMLreturn(Val_unit);
}
|
629528ea6da0407af9287224f39c2acaab0d7e2b
|
bbb0236a4102004e05cd672be131b1bed3f9843f
|
/XPropertiesWnd/XPropertiesWndPpg.h
|
dcababe6dd43f057aaa0a944544a326f189b5a58
|
[] |
no_license
|
ExaLake/way-back
|
c52ea7fba0687ad42f1acf3f59405a68cfe0427b
|
af5aa9e016fadcdb96fe2dc9a2c1a18927b89a2d
|
refs/heads/master
| 2020-12-03T22:17:39.193401
| 2020-01-03T03:18:51
| 2020-01-03T03:18:51
| 231,503,200
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,302
|
h
|
XPropertiesWndPpg.h
|
/************************************
REVISION LOG ENTRY
Revision By: Mihai Filimon
Revised on 10/13/98 2:28:22 PM
Comments: XPropertiesWndPpg.h : Declaration of the CXPropertiesWndPropPage property page class.
************************************/
//{{AFX_INCLUDES()
#include "XFloorPropertiesWndDesign.h"
#include "HighLightButton.h"
#include "ModalEdit.h"
//}}AFX_INCLUDES
#include <afxcmn.h>
#if !defined(AFX_XPROPERTIESWNDPPG_H__7B914A6B_6271_11D2_86B8_0040055C08D9__INCLUDED_)
#define AFX_XPROPERTIESWNDPPG_H__7B914A6B_6271_11D2_86B8_0040055C08D9__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
////////////////////////////////////////////////////////////////////////////
// CXPropertiesWndPropPage : See XPropertiesWndPpg.cpp.cpp for implementation.
class CXPropertiesWndPropPage : public COlePropertyPage
{
DECLARE_DYNCREATE(CXPropertiesWndPropPage)
DECLARE_OLECREATE_EX(CXPropertiesWndPropPage)
friend class CXFloorPropertiesWndDesign;
// Constructor
public:
virtual void Refresh();
static LRESULT CALLBACK CallWndProcHookParent( int nCode, WPARAM wParam, LPARAM lParam);
static CXPropertiesWndPropPage* m_pThis;
HHOOK m_hHook;
CXPropertiesWndPropPage();
virtual BOOL PreTranslateMessage( MSG* pMsg );
// Dialog Data
//{{AFX_DATA(CXPropertiesWndPropPage)
enum { IDD = IDD_PROPPAGE_XPROPERTIESWND_PREVIEW };
CModalEdit m_edtRename;
CSliderCtrl m_sldAddDel;
CXFloorPropertiesWndDesign m_xFloorWndPages;
//}}AFX_DATA
// Implementation
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Message maps
protected:
virtual void RenamePage(int nIndex);
virtual void DeletePage();
virtual void AddPage();
//{{AFX_MSG(CXPropertiesWndPropPage)
virtual BOOL OnInitDialog();
afx_msg void OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar);
afx_msg void OnClickOnActivePageXfloorwndctrlPages(short nIndex);
DECLARE_EVENTSINK_MAP()
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
private:
int m_nRenamePage;
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_XPROPERTIESWNDPPG_H__7B914A6B_6271_11D2_86B8_0040055C08D9__INCLUDED)
|
7ab1c51d006b4faed5272109cf56647622357967
|
c8fa202c120e1e4ab9740d4b9355d646c8b32144
|
/RaptorStackedVertDrawable.cpp
|
de83fe3730f00527598dd9c2c5e56b73b67d9bed
|
[] |
no_license
|
Roman-Port/EagleSDR
|
2ebe31a1c0f2ae654e0ada375a7bf2bfc0e0c6bb
|
8568272b3686b2b6013226dc7e1867a6df1ec0e6
|
refs/heads/master
| 2023-07-10T14:50:24.621738
| 2021-08-08T22:06:17
| 2021-08-08T22:06:17
| 394,103,551
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 940
|
cpp
|
RaptorStackedVertDrawable.cpp
|
#include "RaptorStackedVertDrawable.h"
#include <algorithm>
int RaptorStackedVertDrawable::get_requested_height()
{
return RAPTOR_SCREEN_HEIGHT;
}
int RaptorStackedVertDrawable::get_requested_width()
{
int size = 0;
RaptorDrawable* cursor = 0;
while (enumerate_children(&cursor)) {
size = std::max(size, cursor->get_requested_width());
}
return size + padding_left + padding_right;
}
int RaptorStackedVertDrawable::stacked_container_size()
{
return get_height() - padding_top - padding_bottom;
}
void RaptorStackedVertDrawable::stacked_query(RaptorDrawable* drawable, int* requestedSize, bool* resizeAllowed)
{
*requestedSize = drawable->get_requested_height();
*resizeAllowed = drawable->get_resize_allowed();
}
void RaptorStackedVertDrawable::stacked_apply(RaptorDrawable* drawable, int size, int offset)
{
drawable->request_layout(padding_left, offset + padding_top, get_width() - padding_left - padding_right, size);
}
|
91d756d907d67bff358444527b2c19e0b0f88d9f
|
32cf32acfae2392a48e5db6c8b6726e51e501559
|
/src/setup_test.cpp
|
9a4f2747b8e008e49434b6364bcb94da7c7a8c07
|
[] |
no_license
|
ToraNova/xsedar
|
6e5e00a2eff35005ce98514004219da861b24fe4
|
3b2b712cc6398e5c0acff110fa80114436d885e5
|
refs/heads/master
| 2020-05-07T14:29:25.949597
| 2019-04-16T06:59:37
| 2019-04-16T06:59:37
| 180,596,584
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,733
|
cpp
|
setup_test.cpp
|
/*
SETUP TEST - test functionality
Toranova 2019
*/
#include "xsedar.h"
#include <cstdlib>
#include <iostream>
//pivotal
#include "justGarble.h"
#define circuit_filename "justine_aes.gc"
using namespace std;
int main(int argc, char *argv[]){
cout << "Setup Test...\n" ;
if(argc<2){
cout << "Please specify sender:0 or receiver:others\n" ;
return -1;
}
//networking params
string addr = "127.0.0.1";
uint16_t port = 7766; //using port for obliv, port+1 for normal socket send
//memory testing vars
int32_t tr=0,tt;
//the number of OTs that are performed. Has to be initialized to a certain minimum size due to
uint64_t numOTs = 1000000;
uint32_t runs = 1;
uint32_t nsndvals = 2;
uint32_t bitlength = 8;
uint32_t num_threads = 1;
uint32_t nSecParam = 128;
uint32_t nBaseOTs = 190;
uint32_t nChecks = 380;
//Determines whether the program is executed in the sender or receiver role
uint32_t nPID = atoi(argv[1]);
//loads up a garbled AES circuit
GarbledCircuit circuit;
readCircuitFromFile(&circuit, circuit_filename);
block inputLabels[2 * circuit.n];
block outputMap[2 * circuit.m]; //JMS: Change from m to 2 * m
block finalOutput[circuit.m];
block extractedLabels[circuit.n];
int outputVals[circuit.m];
ot_ext_prot eProt = ALSZ; //IKNP seems to fail
field_type eFType = ECC_FIELD;
MaskingFunction *fMaskFct;
if(nPID == SERVER_ID){
//the program functions as the sender
cout << "Performing Garbling" <<endl;
garbleCircuit(&circuit, inputLabels, outputMap);
cout << "Setting up as the oblivious transfer sender (Alice)..." << endl;
xsedar_sender xs = xsedar_sender();
xs.init_msock(addr,port);
cout << "Sender setup successful..." << endl;
CBitVector delta;
CBitVector** X = (CBitVector**) malloc(sizeof(CBitVector*) * nsndvals); //allocate memory for the target
cout << "Initiating Oblivious Send" << endl;
//The masking function with which the values that are sent in the last communication step are processed
fMaskFct = new XORMasking(bitlength, delta);
//creates delta as an array with "numOTs" entries of "bitlength" bit-values and fills delta with random values
delta.Create(numOTs, bitlength, xs.getCrypt());
//Create the X values as two arrays with "numOTs" entries of "bitlength" bit-values and resets them to 0
for(uint32_t i = 0; i < nsndvals; i++) {
X[i] = new CBitVector();
X[i]->Create(numOTs, bitlength);
}
cout << "Sending bits obliviously" << endl;
//sends out
for(uint32_t i = 0; i < runs; i++) {
xs.obliv_transfer(
X, numOTs, bitlength, nsndvals, &tt, &tr, fMaskFct
);
}
}else{
//the program functions as the receiver
cout << "Setting up as the oblivous transfer receiver (Bob)" << endl;
xsedar_receiver xr = xsedar_receiver();
xr.init_msock(addr,port);
cout << "Receiver setup successful..." << endl;
CBitVector choices, response;
cout << "Initiating Oblivious Receive" << endl;
//The masking function with which the values that are sent in the last communication step are processed
fMaskFct = new XORMasking(bitlength);
//Create the bitvector choices as a bitvector with numOTs entries
choices.Create(numOTs * ceil_log2(nsndvals), xr.getCrypt());
//Pre-generate the respose vector for the results
response.Create(numOTs, bitlength);
response.Reset();
cout << "Receiving bits obliviously" << endl;
//receives
for(uint32_t i = 0; i < runs; i++) {
xr.obliv_receive(
&choices, &response, numOTs, bitlength, nsndvals, &tt, &tr, fMaskFct
);
}
}
// CLEANUP routine
std::cout << "Trial run OK" << std::endl;
return 0;
}
|
64b708c13cd30338bbfbe2956c7f6f4cca6aae47
|
f4cbb24f2971d65ce3a820773007acfce58082d9
|
/Lab1/StartScene.h
|
cb537c152fd2121188b1bf0f080e15beb8a41dfd
|
[] |
no_license
|
FotisSpinos/Games-Programming-2---Fotios-Spinos-Final
|
86a2f3e459a17e61a0271e215555aeee4b88e337
|
c8075d20338cfb49cfc5b2da96f8baa159134ab8
|
refs/heads/master
| 2021-10-09T04:21:49.636303
| 2018-12-21T01:30:35
| 2018-12-21T01:30:35
| 162,508,816
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 193
|
h
|
StartScene.h
|
#pragma once
#include "Scene.h"
class StartScene : public Scene
{
public:
StartScene(); //Constructor
~StartScene(); //Destructor
// Overites the parent method editor
void editor();
};
|
06f1eb80f914340295527e4f8fcec1b59750dcea
|
603347abb45530f937403d14a4800216c94ac547
|
/Source Files/Spaceship.cpp
|
040f9586627955ce8a95a1f26f706a9ef9245dbd
|
[] |
no_license
|
Rafels/Space-Invaders-Game
|
d25baf4a59a98463e70690d104687485ff7871c9
|
6fd1bd02872765d4c831eb0895760c9169061c65
|
refs/heads/master
| 2021-01-20T12:28:09.321398
| 2017-05-05T11:20:19
| 2017-05-05T11:20:19
| 90,366,834
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 845
|
cpp
|
Spaceship.cpp
|
#include "Asteroid.h"
#include "Bullet.h"
#include "Spaceship.h"
#include "Aliens.h"
Spaceship::Spaceship(sf::Vector2f pos, sf::Vector2f spd, std::string path):
Entity(pos,spd,path)
{
getSprite().setScale(0.075, 0.075);
}
void Spaceship::setLives(int liv)
{
lives = liv;
}
int Spaceship::getLives()
{
return lives;
}
void Spaceship::collide(Entity* e)
{
}
void Spaceship::collide(Bullet* e)
{
/*if (e->getIsAlive == false)
return;
*/
if (getIsAlive() == false)
return;
lives--;
if (lives <= 0)
{
kill();
}
e->kill();
}
void Spaceship::collide(Asteroid* e)
{
}
void Spaceship::collide(Spaceship* e)
{
}
void Spaceship::collide(Aliens* e)
{
/*
if (e->getIsAlive == false)
return;
*/
if (getIsAlive() == false)
return;
kill();
}
Spaceship::~Spaceship()
{
}
|
7dd32ccbd03c3bb960ad2c474152ab0831d5c58c
|
510acf5ff609781ae8f18366a0263f291247a305
|
/1385B_restore_the_permutation_by_merger.cpp
|
756307be2a5b50a798b6d807d0c9c28efb03a2e9
|
[] |
no_license
|
damianomiotek/Codeforces
|
0d4f39c582fde0b850a21e326bb6885e26dfdcc5
|
655bd295733c1941f46c46e5dd1a8691cef0a0aa
|
refs/heads/master
| 2023-02-01T04:17:32.884211
| 2020-12-17T20:48:17
| 2020-12-17T20:48:17
| 309,803,042
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 620
|
cpp
|
1385B_restore_the_permutation_by_merger.cpp
|
#include <iostream>
#include <vector>
#include <set>
using namespace std;
int main()
{
int t, n, number;
set<int> numbers;
vector<int> output;
cin >> t;
for(int i = 0; i < t; i++)
{
cin >> n;
for(int j = 0; j < n * 2; j++)
{
cin >> number;
if(numbers.count(number) == 0)
{
numbers.insert(number);
output.push_back(number);
}
}
for(int el : output)
cout << el << " ";
cout << endl;
output.clear();
numbers.clear();
}
return 0;
}
|
c7611427d920d87897ec49819250ac80ea779166
|
959503e864228a10f6fe180d21339abba5e50bad
|
/main.cpp
|
f6d7dd2950051f75e3a88448a0d366409151101d
|
[] |
no_license
|
wiekonek/dns-spoofer
|
bb32b99001d42bcb9f5b3644d590233417725f2b
|
4d2c9c84a62f71bfdb87a796170b23281784fee6
|
refs/heads/master
| 2021-07-09T13:22:02.477877
| 2017-10-06T13:27:39
| 2017-10-06T13:27:39
| 103,516,006
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,624
|
cpp
|
main.cpp
|
#include <iostream>
#include <algorithm>
#include "ArpSpoofer.h"
#include "DnsSpoofer.h"
#include "GatewayInfo.h"
using std::for_each;
using std::string;
//char const *interface = "wlo1";
char const *interface = "wlan0";
uint8_t *getIpFromString(char *string);
vector<string> get_domain_name(char *query_payload);
int main(int argc, char * argv[]) {
if(argc < 3){
cout << "Provide target domain and resposne ip" << endl;
cout << "example: dns_spoofer jacek.pl.com 192.168.0.10" << endl;
cout << "Using default: dns_spoofer wiekon.com.pl yafud.pl_ip" << endl;
}
const vector<string> &domain = get_domain_name(argv[1]);
uint8_t *redirect_ip = getIpFromString(argv[2]);
GatewayInfo* gatewayInfo = new GatewayInfo();
char *gw = gatewayInfo->getGateway();
uint8_t *gateway = getIpFromString(gw);
if(fork()){
DnsSpoofer *dnsSpoofer = new DnsSpoofer();
dnsSpoofer->start_spoofing(const_cast<char *>(interface), domain, redirect_ip);
} else {
auto arpSpoofer = new ArpSpoofer();
arpSpoofer->start_spoofing(const_cast<char *>(interface), gateway);
}
return 0;
}
uint8_t *getIpFromString(char *string) {
unsigned char *buf = new unsigned char[(sizeof(struct in6_addr))];
inet_pton(AF_INET, string, buf);
return buf;
}
vector<string> get_domain_name(char *query_payload) {
vector<string> spoof_target;
char *names = strtok(query_payload, ".");
while(names != NULL){
spoof_target.push_back(reinterpret_cast<char*>(names));
names = strtok(NULL, ".");
}
return spoof_target;
}
|
7a840be3e419e4dafb8e01e66dcdd7f867c0586f
|
d4c720f93631097ee048940d669e0859e85eabcf
|
/ash/style/color_palette_controller.cc
|
52fa7c39da7c227ab986ff284381a16c99eadcdb
|
[
"BSD-3-Clause"
] |
permissive
|
otcshare/chromium-src
|
26a7372773b53b236784c51677c566dc0ad839e4
|
3b920d87437d9293f654de1f22d3ea341e7a8b55
|
refs/heads/webnn
| 2023-03-21T03:20:15.377034
| 2023-01-25T21:19:44
| 2023-01-25T21:19:44
| 209,262,645
| 18
| 21
|
BSD-3-Clause
| 2023-03-23T06:20:07
| 2019-09-18T08:52:07
| null |
UTF-8
|
C++
| false
| false
| 3,529
|
cc
|
color_palette_controller.cc
|
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/style/color_palette_controller.h"
#include <memory>
#include "base/logging.h"
#include "base/observer_list.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/task_runner.h"
#include "base/time/time.h"
namespace ash {
namespace {
// TODO(b/258719005): Finish implementation with code that works/uses libmonet.
class ColorPaletteControllerImpl : public ColorPaletteController {
public:
ColorPaletteControllerImpl() = default;
~ColorPaletteControllerImpl() override = default;
void AddObserver(Observer* observer) override {
observers_.AddObserver(observer);
}
void RemoveObserver(Observer* observer) override {
observers_.RemoveObserver(observer);
}
void SetColorScheme(ColorScheme scheme,
base::OnceClosure on_complete) override {
DVLOG(1) << "Setting color scheme to: " << (int)scheme;
current_scheme_ = scheme;
// TODO(b/258719005): Call this after the native theme change has been
// applied. Also, actually change things.
base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE, std::move(on_complete), base::Milliseconds(100));
}
void SetStaticColor(SkColor seed_color,
base::OnceClosure on_complete) override {
DVLOG(1) << "Static color scheme: " << (int)seed_color;
static_color_ = seed_color;
current_scheme_ = ColorScheme::kStatic;
// TODO(b/258719005): Call this after the native theme change has been
// applied. Also, actually change things.
base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE, std::move(on_complete), base::Milliseconds(100));
}
ColorPaletteSeed GetColorPaletteSeed() const override {
// TODO(b/258719005): Implement me!
return {.seed_color = static_color_,
.scheme = current_scheme_,
.color_mode = ui::ColorProviderManager::ColorMode::kLight};
}
bool UsesWallpaperSeedColor() const override {
// Scheme tracks if wallpaper color is used.
return current_scheme_ != ColorScheme::kStatic;
}
ColorScheme color_scheme() const override { return current_scheme_; }
absl::optional<SkColor> static_color() const override {
if (current_scheme_ == ColorScheme::kStatic) {
return static_color_;
}
return absl::nullopt;
}
void GenerateSampleScheme(ColorScheme scheme,
SampleSchemeCallback callback) const override {
// TODO(b/258719005): Return correct and different schemes for each
// `scheme`.
DCHECK_NE(scheme, ColorScheme::kStatic)
<< "Requesting a static scheme doesn't make sense since there is no "
"seed color";
SampleScheme sample = {.primary = SK_ColorRED,
.secondary = SK_ColorGREEN,
.tertiary = SK_ColorBLUE};
base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE, base::BindOnce(std::move(callback), sample),
base::Milliseconds(20));
}
private:
SkColor static_color_ = SK_ColorBLUE;
ColorScheme current_scheme_ = ColorScheme::kTonalSpot;
base::ObserverList<ColorPaletteController::Observer> observers_;
};
} // namespace
// static
std::unique_ptr<ColorPaletteController> ColorPaletteController::Create() {
return std::make_unique<ColorPaletteControllerImpl>();
}
} // namespace ash
|
3ce5ff1989b98d1fe9f5f1fc24891e3f19d2c86a
|
63247e1e7c5800ef36207c505f0b8cb7a8615061
|
/include/myLib.hpp
|
49b8a9069e7508585d3c73c66b3d56927734f0b9
|
[] |
no_license
|
metroff/VU_BC_Hash
|
c27fb82a1f3c310d9f74039e6f370cd262479685
|
bb6e14f48392ccdaac814c87ae81030f8b6a05a9
|
refs/heads/main
| 2023-08-12T23:21:38.802321
| 2021-10-07T17:14:04
| 2021-10-07T17:14:04
| 411,592,481
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 109
|
hpp
|
myLib.hpp
|
#pragma once
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <sstream>
|
fcc85acc1bcb24bfc320e22b856354ce5e8645fa
|
097fa369095ab2b98aedf49ca2e54f1cd45db7ae
|
/Group Work/DataConverter.h
|
b4d5cd1c775c5ca43a9c1c76152b6bca846f3930
|
[] |
no_license
|
SubinChitrakar/BudgetManagement
|
6ad6317312e67b9f5acb646cef7636d163792ed2
|
c92d673bee5d4ad0e48dcb4e8834fdee2be068f7
|
refs/heads/master
| 2020-08-31T03:49:39.173455
| 2019-11-18T09:40:43
| 2019-11-18T09:40:43
| 214,163,247
| 0
| 0
| null | 2019-10-30T15:58:23
| 2019-10-10T11:19:58
|
C++
|
UTF-8
|
C++
| false
| false
| 994
|
h
|
DataConverter.h
|
#pragma once
#include <string>
#include <iostream>
#include "json.hpp"
#include "EncryptDecrypt.h"
#include "Category.h"
#include "User.h"
#include "Category.h"
#include "NormalTransaction.h"
#include "RecurringTransaction.h"
using nlohmann::json;
using namespace std;
class DataConverter
{
private:
json& j;
EncryptDecrypt& ec;
void saveData() { ec.fileEncrypt(j.dump(), j["user"]["password"]); }
public:
DataConverter(json& json, EncryptDecrypt& ecd) : j(json),ec(ecd) {};
User* convertToUser();
vector<Category> convertToCategory();
vector<NormalTransaction> convertToNormalTransaction(vector<Category>& catList);
vector<RecurringTransaction> convertToRecurringTransaction(vector<Category>& catList);
void convertFromCategory(vector<Category> categoryList);
void convertFromNormalTransaction(vector<NormalTransaction>& normalTransactionList);
void convertFromRecurringTransaction(vector<RecurringTransaction>& recurringTransactionList);
void convertFromUser(User& user);
};
|
cb4c10a91793972f780aeee97b0d18707d75121b
|
4b719e84f26dcd3fb47da5d811c758dd3eb68a52
|
/part2/transpose.cpp
|
80b2eba62d2f2ff6f935b6f1ddda51473474215f
|
[] |
no_license
|
Prianick/cppStudy
|
679f41a31905179d6d488f09d63f85f01383556c
|
066c27d63dc3ed9d3df6b9eaf6aeeae440b6fecc
|
refs/heads/master
| 2021-01-26T00:49:02.703116
| 2020-07-12T09:00:22
| 2020-07-12T09:00:22
| 243,247,437
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,378
|
cpp
|
transpose.cpp
|
#include <iostream>
/*
Конспект.
- m[i] <=> *(m + i) - т.е. мы берем указатель m, прибавляем к нему целое число i, далее * разименовывание т.е. берем значение.
- В многомерном массиве есть массив с указателями на строки. То есть есть указатель на указатель строки int **
- * - это оператор разименования ссылки и получения ее значения
const - (https://habr.com/ru/post/59558/) - создает переменную значение которой изменить нельзя
size_t - базовый тип, размер которого соответствует размеру базавого типа операционный системы 64 32
для более эффективного выделения памяти нужно:
- выделить массив с указателями на строки
- затем выделить массив со строками это будет площадь матрицы (rows * cols)
- после этого поместить указатели на начало каждой строки в массив с указателми
- т.е. отступаем от начала массива размер массива с указателями, плюс размер текущей строки умноженный на номер строки
*/
int **transpose(int **m, unsigned rows, unsigned cols) {
int **m2 = new int *[cols];
m2[0]= new int[rows * cols];
for (int i = 1; i != cols; ++i) {
m2[i] = m2[i - 1] + rows;
}
for (int i = 0; i != rows; ++i) {
for (int j = 0; j != cols; ++j) {
m2[j][i] = m[i][j];
}
}
return m2;
}
int main() {
int m2d[2][3] = {{1, 2, 3},
{1, 2, 3}};
int rows = 3;
int cols = 3;
int **m = new int *[rows];
int **m2 = new int *[rows];
for (int k = 0; k < cols; ++k) {
m2[k] = new int[rows];
}
for (size_t i = 0; i != rows; ++i) {
m[i] = new int[4];
for (size_t j = 0; j != cols; ++j) {
m[i][j] = j;
}
}
m2 = transpose(m, rows, cols);
std::cout << m2[2][1] << m[1][2];
}
|
e89317fed04acaacfef63463e010399aba8c5109
|
ee507b3010c903ec716315f7df2ba4ef5ae5921a
|
/util/AI_PathFind.h
|
1f3d922bc6bca978ec8846e9122696cee13441bc
|
[] |
no_license
|
sopyer/Shadowgrounds
|
ac6b281cd95d762096dfc04ddae70d3f3e63be05
|
691cb389c7d8121eda85ea73409bbbb74bfdb103
|
refs/heads/master
| 2020-03-29T18:25:48.103837
| 2017-06-24T17:08:50
| 2017-06-24T17:08:50
| 9,700,603
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,270
|
h
|
AI_PathFind.h
|
#ifndef INCLUDED_AI_PATHFIND_H
#define INCLUDED_AI_PATHFIND_H
#ifdef _MSC_VER
#pragma warning(disable: 4786) // Debug info truncate
#pragma warning(disable: 4514) // Unreferenced inline function
#endif
#ifndef INCLUDED_VECTOR
#define INCLUDED_VECTOR
#include <vector>
#endif
#include <DatatypeDef.h>
class IStorm3D_Model;
namespace game {
class CoverMap;
}
namespace util
{
class LightMap;
}
namespace frozenbyte {
namespace ai {
class PathSimplifier;
// This should be in general os_types.h or such
typedef unsigned short int uint16;
// Stores paths
class Path
{
// Path in reverse order
std::vector<int> xPositions;
std::vector<int> yPositions;
public:
Path();
~Path();
// Adds waypoint (to end of the list - start of the path)
void addPoint(int xPosition, int yPosition);
// Returns number of waypoints
int getSize() const;
// Waypoints are returned from vectors size()-1 to 0
int getPointX(int index) const;
int getPointY(int index) const;
// New: for pathdeformer use...
// Waypoint index should be from vectors size()-1 to 0
void setPoint(int index, int xPosition, int yPosition);
};
// Pathblock (buildings, ..)
class Pathblock
{
// NEW: ignore this, raytrace used instead of the old block map...
// Space reserved (0 = free, 1 = block area
/*
std::vector<std::vector<unsigned char> > blocks;
*/
// Doors, ...
std::vector<std::pair<int, int> > portals;
// Dummy pointer. Link this to parent model
IStorm3D_Model *model;
int xPosition;
int yPosition;
int xSize;
int ySize;
public:
Pathblock();
~Pathblock();
// Units are in path's blocks
void setSize(int xSize, int ySize); // Whole map is marked free after this
void setPosition(int xPosition, int yPosition); // Upper-left corner
// All internals should be accessible from these
void addPortal(int xPosition, int yPosition);
void removePortal(int xPosition, int yPosition);
void setBlockArea(int xPosition, int yPosition); // All blocks which belong to this
void setFreeArea(int xPosition, int yPosition); // Mark as free space (might be blocked on pathfinder, thought)
void setModel(IStorm3D_Model *model);
// Query stuff
int getPositionX() const;
int getPositionY() const;
int getSizeX() const;
int getSizeY() const;
const std::vector<std::pair<int, int> > &getPortals() const;
// NEW: ignore this, raytrace used instead of the old block map...
/*
const std::vector<std::vector<unsigned char> > &getBlocks() const;
*/
IStorm3D_Model *getModel() const;
};
class PathFind
{
// Height data should come from elsewhere
//std::vector<std::vector<uint16> > heightMap;
// ...using shared heightmap now
// --jpk
uint16 *heightMap;
// There can be many obstacles on each point
std::vector<std::vector<signed char> > obstacleMap;
// Buildings (should probably work out some fancy hierarchy for finding these)
std::vector<Pathblock> blockMap;
// Heuristic value for search
float heuristicWeight;
// Dimensions
int xSize;
int ySize;
//int accuracyFactor;
int accuracyShift;
int pathfindDepth;
int xSizeHeightmap;
int ySizeHeightmap;
int coverAvoidDistance;
int coverBlockDistance;
int lightAvoidAmount;
game::CoverMap *coverMap;
util::LightMap *lightMap;
bool portalRoutesDisabled;
// Not implemented
PathFind(const PathFind &rhs);
PathFind &operator = (const PathFind &rhs);
public:
PathFind();
~PathFind();
void disablePortalRoutes(bool disable);
// Set heightmap data. Loses all obstacles. AccuracyFactor sets multiplier for pathfind map size
void setHeightMap(uint16 *heightValues, int xSize, int ySize, int accuracyFactor = 1);
// Adds obstacle to given point (tree/..).
void addObstacle(int xPosition, int yPosition);
// Removes obstacle from given point
void removeObstacle(int xPosition, int yPosition);
// sets the cover map to use
// used by vehicles to avoid getting to forests and near obstacles
// NOTE: bad dependecy to game namespace!
// -jpk
void setCoverMap(game::CoverMap *coverMap);
// sets the light map to use
void setLightMap(util::LightMap *lightMap);
// sets maximum depth for pathfind to given absolute value
// NOTE: depth may be limited by internal absolute maximum limit too.
void setPathfindDepthByAbsoluteValue(int depth);
// sets maximum depth for pathfind to given relative value
// (percentages of internal absolute maximum limit)
void setPathfindDepthByPercentage(int depth);
// sets the distance from which all covers (obstacles) are avoided.
void setCoverAvoidDistance(int coverAvoidDistance);
// sets the distance from which all covers (obstacles) are considered
// to be blocking.
void setCoverBlockDistance(int coverBlockDistance);
// sets the amount above which light is avoided
void setLightAvoidAmount(int lightAvoidAmount);
// Pointers are stored
void addPathblock(const Pathblock &block);
// Set heuristics. Increasing value speeds up search while
// affecting quality. Avoid setting less than one >:)
// 1 -> optimal path
// 1+ faster search, lower quality path
void setHeuristicWeight(float value = 1.f);
// Finds route between points. Returns true if path exists
// Climb penaly means cost factor for each unit moved upwards
// -> cost = realCost() + heightDelta*climbPenalty
// Eg. step from 0,0 to 1,1 always costs sqrt(2.f) (w/o climbing).
// -> With climbFactor 1.f
// -> Climbing 100 units raises cost to (sqrt(2)+100) !
// So, scale both maxHeightDifference and climbFactor to suit your scene
bool findRoute(Path *resultPath, int xStart, int yStart, int xEnd, int yEnd, int maxHeightDifference, float climbPenalty, const VC3 &startWorldCoords, const VC3 &endWorldCoords) const;
// Returns true if point is blocked (obstacle)
bool isBlocked(int xPosition, int yPosition) const;
// Returns amount of obstacles at given point
// (An optimization hack really) --jpk
int getBlockingCount(int xPosition, int yPosition) const;
// NOTE: for loading of the pathfind map...
void setBlockingCount(int xPosition, int yPosition, int amount);
// Returns model (from pathblocks) at given point. 0 if not found
IStorm3D_Model *getModelAt(int xPosition, int yPosition, const VC3 &worldCoords) const;
private:
bool findActualRoute(Path *resultPath, int xStart, int yStart, int xEnd, int yEnd, int maxHeightDifference, float climbPenalty, const Pathblock *avoidBlock) const;
// Returns height at given point
int getHeight(int xPosition, int yPosition) const;
// Returns true if can move from start to end.
// Points are assumed to be neighbours
bool isMovable(int xStart, int yStart, int xEnd, int yEnd, int maxHeightDifference) const;
// Distance costs are no longer squared
// Returns estimated cost between points (already multipled with heuristic weight)
float estimateCost(int xStart, int yStart, int xEnd, int yEnd) const;
// Returns real cost between neighbours
float realCost(int xStart, int yStart, int xEnd, int yEnd, float climbPenalty) const;
// blockid (index), -1 = none
int blockAt(int xPosition, int yPosition, const VC3 &worldCoords) const;
// 0 = free, 1 = belongs to block
int blockedAt(int xPosition, int yPosition, const Pathblock &block) const;
friend class PathSimplifier;
};
} // end of namespace ai
} // end of namespace frozenbyte
#endif
|
d267c22c0a43c1b73f5de1d67ddd0705470d1e82
|
88e352a391faa3474cf9066c2e2b6185b47fe19e
|
/SkyBox.cpp
|
343ebd421b80670430c25c1d23a7cb4118abf22b
|
[] |
no_license
|
ChitoseRuri/Deja_vu
|
95422dcf85b8a6e17ce34785e93c217a9d903dd7
|
bcc3ed8258122b82bb3c19c75ad01fc9077c22dc
|
refs/heads/master
| 2020-12-14T22:17:45.368779
| 2020-02-21T14:34:54
| 2020-02-21T14:34:54
| 234,888,765
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,872
|
cpp
|
SkyBox.cpp
|
#include "SkyBox.h"
SkyBox::SkyBox()
{
}
SkyBox::~SkyBox()
{
}
void SkyBox::init(ID3D11Device* pDevice, std::wstring fileName)
{
if (fileName.substr(fileName.size() - 3) == L"DDS")
{
assert(true);
}
else
{
loadImageTexture(pDevice, std::move(fileName));
}
}
void SkyBox::draw(ID3D11DeviceContext* pContext, const CBWorld& eyeCB)
{
// 设置顶点/索引缓冲区
UINT strides = m_vertexStride;
UINT offsets = 0;
pContext->IASetVertexBuffers(0, 1, m_pVertexBuffer.GetAddressOf(), &strides, &offsets);
pContext->IASetIndexBuffer(m_pIndexBuffer.Get(), DXGI_FORMAT_R16_UINT, 0);
// 获取之前已经绑定到渲染管线上的常量缓冲区并进行修改
ComPtr<ID3D11Buffer> cBuffer = nullptr;
pContext->VSGetConstantBuffers(0, 1, cBuffer.GetAddressOf());
// 更新常量缓冲区
D3D11_MAPPED_SUBRESOURCE mappedData;
HR(pContext->Map(cBuffer.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedData));
memcpy_s(mappedData.pData, sizeof(CBWorld), &eyeCB, sizeof(CBWorld));
pContext->Unmap(cBuffer.Get(), 0);
// 设置纹理
pContext->PSSetShaderResources(0, 1, m_pTexture.GetAddressOf());
// 可以开始绘制
pContext->DrawIndexed(m_indexCount, 0, 0);
}
void SkyBox::loadImageTexture(ID3D11Device* pDevice, std::wstring fileName)
{
constexpr float hp = 1.0f / 3.0f;
constexpr float wp = 1.0f / 4.0f;
auto meshData = Geometry::CreateBox();
auto& vertexDataArr = meshData.vertexVec;
// 右面(+X面)
vertexDataArr[0].tex = { wp * 3.0f, hp * 2.0f };
vertexDataArr[1].tex = { wp * 3.0f, hp };
vertexDataArr[2].tex = { wp * 2.0f, hp };
vertexDataArr[3].tex = { wp * 2.0f, hp * 2.0f };
// 左面(-X面)
vertexDataArr[4].tex = { wp, hp * 2.0f };
vertexDataArr[5].tex = { wp, hp };
vertexDataArr[6].tex = { 0.0f, hp };
vertexDataArr[7].tex = { 0.0f, hp * 2.0f };
// 顶面(+Y面)
vertexDataArr[8].tex = { wp, 0.0f };
vertexDataArr[9].tex = { wp, hp };
vertexDataArr[10].tex = { wp * 2.0f, hp };
vertexDataArr[11].tex = { wp * 2.0f, 0.0f };
// 底面(-Y面)
vertexDataArr[12].tex = { wp * 2.0f, 1.0f };
vertexDataArr[13].tex = { wp * 2.0f, hp * 2.0f };
vertexDataArr[14].tex = { wp, hp * 2.0f };
vertexDataArr[15].tex = { wp, 1.0f };
// 背面(+Z面)
vertexDataArr[16].tex = { wp * 2.0f, hp * 2.0f };
vertexDataArr[17].tex = { wp * 2.0f, hp };
vertexDataArr[18].tex = { wp, hp };
vertexDataArr[19].tex = { wp, hp * 2.0f };
// 正面(-Z面)
vertexDataArr[20].tex = { 1.0f, hp * 2.0f };
vertexDataArr[21].tex = { 1.0f, hp };
vertexDataArr[22].tex = { wp * 3.0f, hp };
vertexDataArr[23].tex = { wp * 3.0f, hp * 2.0f };
for (UINT i = 0; i < 4; ++i)
{
// 右面(+X面)
vertexDataArr[i].normal = XMFLOAT3(1.0f, 0.0f, 0.0f);
// 左面(-X面)
vertexDataArr[i + 4].normal = XMFLOAT3(-1.0f, 0.0f, 0.0f);
// 顶面(+Y面)
vertexDataArr[i + 8].normal = XMFLOAT3(0.0f, 1.0f, 0.0f);
// 底面(-Y面)
vertexDataArr[i + 12].normal = XMFLOAT3(0.0f, -1.0f, 0.0f);
// 背面(+Z面)
vertexDataArr[i + 16].normal = XMFLOAT3(0.0f, 0.0f, 1.0f);
// 正面(-Z面)
vertexDataArr[i + 20].normal = XMFLOAT3(0.0f, 0.0f, -1.0f);
}
for (UINT i = 0; i < 24; ++i)
{
meshData.vertexVec.push_back(vertexDataArr[i]);
}
// 反向索引
meshData.indexVec = {
0, 1, 2, 2, 3, 0, // 右面(+X面)
4, 5, 6, 6, 7, 4, // 左面(-X面)
8, 9, 10, 10, 11, 8, // 顶面(+Y面)
12, 13, 14, 14, 15, 12, // 底面(-Y面)
16, 17, 18, 18, 19, 16, // 背面(+Z面)
20, 21, 22, 22, 23, 20 // 正面(-Z面)
};
size_t index = ResourceDepot::loadGeometry(pDevice, meshData, L"skybox");
auto mesh = ResourceDepot::getMeshBuffer(index);
m_pVertexBuffer = mesh.vertexBuffer;
m_pIndexBuffer = mesh.indexBuffer;
m_indexCount = mesh.count;
m_vertexStride = mesh.vertexStride;
index = ResourceDepot::loadImage(pDevice, L"Texture\\daylight.jpg", L"sky");
m_pTexture = ResourceDepot::getShaderResource(index);
}
|
34835ba917c45aeb7a6d43b3298029b4f74e288e
|
6c8dafe293c24ec79f2f1b2bcf8eb52015bdb36f
|
/src/game_state.hpp
|
b2cf8ff9d4f352e3eda339a1a11284db76563142
|
[] |
no_license
|
aalin/game2004
|
a483aefe33e3ce327b1c3d55a070cb09e92c00e9
|
de5e2da8ef1e5446e73672aa2b1a2fca9671b92b
|
refs/heads/master
| 2022-07-13T16:48:24.218786
| 2020-05-17T12:02:25
| 2020-05-17T12:02:25
| 263,699,489
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 422
|
hpp
|
game_state.hpp
|
#ifndef GAME_STATE_HPP
#define GAME_STATE_HPP
#include "engine.hpp"
#include "keyboard.hpp"
class GameState {
public:
GameState(Engine &game) : _game(game) { }
virtual ~GameState() { }
virtual void setup() = 0;
virtual void pause() = 0;
virtual void update(double s, const Keyboard &) = 0;
virtual void draw() = 0;
protected:
Engine& getGame() { return _game; };
private:
Engine &_game;
};
#endif
|
01add35009bb7a3e020b388ef19fe0446afff315
|
5b244e82d9a1c585905db8e8f25cc44bd0ebac8a
|
/algorithms/sorting/insertionsort/insertsort.cpp
|
9520f1560d2a4f5e4a5a853e1db599f076474972
|
[] |
no_license
|
thinkphp/computer-science-in-c
|
fe58f92ffacbe1de9523c1bfa21473f70fe99362
|
685107b9671c0cc519dc35f46f3a182dbdac572c
|
refs/heads/master
| 2023-08-31T01:36:51.368399
| 2023-08-30T06:08:07
| 2023-08-30T06:08:07
| 23,139,753
| 6
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,118
|
cpp
|
insertsort.cpp
|
#include <iostream>
#include <fstream>
#define FIN "algsort.in"
#define FOUT "algsort.out"
#define MAXN 500005
using namespace std;
//prototypes
void read();
void display();
void insertion();
void write();
//input
ifstream fin(FIN);
//output
ofstream fout(FOUT);
//declare an array of integers
//global vector
int v[ MAXN ],
//store the number of elements
//global variable
n;
//main function
int main() {
read();
insertion();
write();
return(0);
}
void read() {
fin>>n;
for(int i = 0; i < n; i++) {
fin>>v[ i ];
}
fin.close();
}
void insertion() {
int i,j,aux;
int li,ls,middle;
//binary search
for(i = 1; i < n; i++) {
aux = v[i];
li = 0;
ls = i - 1;
while(li <= ls) {
middle = (li+ls)/2;
if(aux < v[ middle ]) {
ls = middle - 1;
} else{
li = middle + 1;
}
}
for(j = i - 1; j >= li; j--) {
v[ j + 1 ] = v[ j ];
}
v[ li ] = aux;
}
}
void write() {
cout<<"\n";
for(int i=0;i<n;i++) {
fout<<v[i]<<" ";
}
fout.close();
}
|
574649fdd9e130e5ff9150832cad61ccbde13016
|
df1937f102d84bd7c9a761f2b68d34e8222c6592
|
/Scanner.h
|
ed7a6726b136d96f8906d996e80950ea06d61c47
|
[] |
no_license
|
Ardivaba/OpenMemes
|
33e78722adc3ea69b991580b190a9ece78427dbb
|
0ab720dd0643e48fc735f3ecce431815c344bac1
|
refs/heads/master
| 2021-01-12T03:13:21.109261
| 2017-01-06T06:25:18
| 2017-01-06T06:25:18
| 78,180,174
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 374
|
h
|
Scanner.h
|
#pragma once
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <vector>
#include <list>
#include <Windows.h>
using namespace cv;
class Scanner
{
public:
static Mat currentFrame;
static std::list<Point> findHealths();
static void setFrame(Mat frame);
};
|
de517f24c7bd61bf276b214b03532ba0009a8010
|
e15f1ed0b421726b4c19f6cc933ecca6225caf3f
|
/src/dataio.h
|
736e3bd9a323fef3f829c1f3a5d621503faed67c
|
[
"BSD-3-Clause"
] |
permissive
|
glaivesoft/biomedicaldataio
|
52782b88aae46354060c5dace12470ec90b296a7
|
73e5fd6379e45ac06efdab7728edba645852d8ff
|
refs/heads/master
| 2021-01-13T04:05:08.776190
| 2017-11-09T23:24:38
| 2017-11-09T23:24:38
| 77,942,404
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,681
|
h
|
dataio.h
|
// dataio.h
// read/write .tif, .nii, .raw, ...
// developed by Yang Yu (gnayuy@gmail.com)
#ifndef __DATAIO_H__
#define __DATAIO_H__
#include "biomedicaldataio.h"
//
extern "C" {
#include "tiff.h"
#include "tiffio.h"
#include "nifti1_io.h"
#include "znzlib.h"
};
#include "klb_imageIO.h"
//
template <class Tdata, class Tidx>
int convertImageOrder(Tdata *&p, Tidx dimx, Tidx dimy, Tidx dimz, Tidx dimc, bool cxyz2xyzc)
{
//
/// convert image order [CXYZ] <-> [XYZC]
//
//
if(!p)
{
cout<<"Invalid pointer for convertImageOrder."<<endl;
return -1;
}
//
Tidx offset_tif_x = dimc;
Tidx offset_tif_y = offset_tif_x*dimx;
Tidx offset_tif_z = offset_tif_y*dimy;
Tidx offset_ilia_y = dimx;
Tidx offset_ilia_z = offset_ilia_y*dimy;
Tidx offset_ilia_c = offset_ilia_z*dimz;
Tidx imagesz = dimc*offset_ilia_c;
//
Tdata *pTmp = NULL;
new1dp<Tdata, Tidx>(pTmp, imagesz);
memcpy(pTmp, p, imagesz * sizeof(Tdata) );
// std::copy(&p[0], &p[imagesz-1], pTmp);
//
for (Tidx c=0; c<dimc; c++)
{
Tidx offset_out_c = c*offset_ilia_c;
for (Tidx z=0; z<dimz; z++)
{
Tidx offset_in_z = z*offset_tif_z;
Tidx offset_out_z = z*offset_ilia_z + offset_out_c;
for (Tidx y=0; y<dimy; y++)
{
Tidx offset_in_y = y*offset_tif_y + offset_in_z;
Tidx offset_out_y = y*offset_ilia_y + offset_out_z;
for (Tidx x=0; x<dimx; x++)
{
Tidx idx_in = offset_in_y + x*offset_tif_x + c;
Tidx idx_out = offset_out_y + x;
if(cxyz2xyzc)
{
// CXYZ -> XYZC
p[idx_out] = pTmp[idx_in];
}
else
{
// XYZC -> CXYZ
p[idx_in] = pTmp[idx_out];
}
}// x
}// y
}// z
}// c
// de-alloc
del1dp<Tdata>(pTmp);
//
return 0;
}
// TIFF
class TiffIO : public BioMedicalDataIO
{
public:
TiffIO();
~TiffIO();
public:
// reading
bool canReadFile(char *fileNameToRead);
int read();
// writing
bool canWriteFile(char *fileNameToWrite);
int write();
//
void close();
//
void changeImageOrder(bool io);
private:
uint16 config;
uint16 bitspersample, samplesperpixel;
uint16 compression, photometric;
uint32 width, length;
uint16 orientation;
uint32 tilewidth, tilelength, rowsperstrip;
uint16 transferR, transferG, transferB, transferA;
uint16 colormapR, colormapG, colormapB, colormapA;
bool bICC;
uint32 lenICC;
void** dataICC;
bool bINKS, bInkName;
uint16 ninks;
const char* inknames;
int inknameslen;
bool bPG;
unsigned short m_CurrentPage, m_NumberOfPages;
bool bTiled;
uint16 fillorder;
uint32 m_NumberOfTiles;
private:
uint32 m_SUBFILETYPE;
uint16 m_THRESHHOLDING;
char* m_DOCUMENTNAME;
char* m_IMAGEDESCRIPTION;
char* m_MAKE;
char* m_MODEL;
uint16 m_MINSAMPLEVALUE;
uint16 m_MAXSAMPLEVALUE;
float m_XRESOLUTION;
float m_YRESOLUTION;
char* m_PAGENAME;
float m_XPOSITION;
float m_YPOSITION;
uint16 m_RESOLUTIONUNIT;
char* m_SOFTWARE;
char* m_DATETIME;
char* m_ARTIST;
char* m_HOSTCOMPUTER;
float* m_WHITEPOINT;
float* m_PRIMARYCHROMATICITIES;
uint16 m_HALFTONEHINTS1, m_HALFTONEHINTS2;
uint16 m_INKSET;
uint16 m_DOTRANGE1, m_DOTRANGE2;
char* m_TARGETPRINTER;
uint16 m_SAMPLEFORMAT;
float* m_YCBCRCOEFFICIENTS;
uint16 m_YCBCRSUBSAMPLING1, m_YCBCRSUBSAMPLING2;
uint16 m_YCBCRPOSITIONING;
float* m_REFERENCEBLACKWHITE;
uint16 m_EXTRASAMPLES1;
uint16* m_EXTRASAMPLES2;
double m_SMINSAMPLEVALUE;
double m_SMAXSAMPLEVALUE;
double m_STONITS;
unsigned int m_SubFiles;
unsigned int m_IgnoredSubFiles;
//
TIFF* m_TiffImage;
};
// NIfTI
class NiftiIO : public BioMedicalDataIO
{
public:
NiftiIO();
~NiftiIO();
public:
// reading
bool canReadFile(char *fileNameToRead);
int read();
// writing
bool canWriteFile(char *fileNameToWrite);
int write();
int write(const void *buffer, long sx, long sy, long sz, long sc, long st, int datatype, float vx, float vy, float vz);
// compressed ?
int isCompressed(const char * filename);
private:
bool mustRescale();
void setPixelType(IOPixelType pt);
private:
znzFile m_GZFile;
nifti_image *m_NiftiImage;
double m_RescaleSlope;
double m_RescaleIntercept;
bool m_LegacyAnalyze75Mode;
IOPixelType m_PixelType;
};
// KLB
class KLBIO : public BioMedicalDataIO
{
public:
KLBIO();
~KLBIO();
public:
// reading
bool canReadFile(char *fileNameToRead);
// writing
bool canWriteFile(char *fileNameToWrite);
private:
KLB_COMPRESSION_TYPE compressionType;
int numThreads;
uint32_t xyzct[KLB_DATA_DIMS], blockSize[KLB_DATA_DIMS];
float32_t voxelsize[KLB_DATA_DIMS];
KLB_DATA_TYPE datatype;
char metadata[KLB_METADATA_SIZE];
};
// RAW
class RawIO : public BioMedicalDataIO
{
public:
RawIO();
~RawIO();
public:
// reading
bool canReadFile(char *fileNameToRead);
int read();
// writing
bool canWriteFile(char *fileNameToWrite);
int write();
};
#endif // __DATAIO_H__
|
046527a75ef001c99059dc01ea32321c719804db
|
7b4739c25e9d0f4f14f534e93e51124edcdf5737
|
/MsgManager.cpp
|
fe147cea1fc6f587ac32e1b4efbc27d16d58810c
|
[] |
no_license
|
1024210879/TimeRoulette
|
3eaf4981002b2d913ca529fd9fe02ba08dc90d52
|
1f773e9d3ce099a7471b7d67f3728f396f27e7bd
|
refs/heads/main
| 2023-05-22T07:20:15.644997
| 2021-06-07T12:22:21
| 2021-06-07T12:30:38
| 374,073,336
| 5
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,707
|
cpp
|
MsgManager.cpp
|
#include "MsgManager.h"
MsgManager* MsgManager::msgManager = NULL;
MsgManager::MsgManager(QObject *parent) :
QObject(parent)
{
}
MsgManager *MsgManager::instance()
{
if ( msgManager == NULL)
{
QMutex mt;
mt.lock();
if ( msgManager == NULL )
{
msgManager = new MsgManager;
}
mt.unlock();
}
return msgManager;
}
bool MsgManager::registerSignal(const QString topic,
const QObject *obj,
const char* signal,
Qt::ConnectionType type)
{
// 注册信号
if ( m_mapSignal.contains(topic) )
{ // 存在则尾插
m_mapSignal[topic].push_back({obj, signal});
}
else
{ // 不存在则新增
m_mapSignal.insert(topic, {{obj, signal}});
}
// 建立连接
if ( m_mapSlot.contains(topic) )
{
for (auto stObj: m_mapSlot.value(topic))
{
connect(obj, signal, stObj.obj, stObj.sigSlot, type);
}
}
}
bool MsgManager::registerSlot(const QString topic,
const QObject *obj,
const char* slot,
Qt::ConnectionType type)
{
// 注册槽
if ( m_mapSlot.contains(topic) )
{ // 存在则尾插
m_mapSlot[topic].push_back({obj, slot});
}
else
{ // 不存在则新增
m_mapSlot.insert(topic, {{obj, slot}});
}
// 建立连接
if ( m_mapSignal.contains(topic) )
{
for (auto stObj: m_mapSignal.value(topic))
{
connect(stObj.obj, stObj.sigSlot, obj, slot, type);
}
}
}
|
eb7972e2000533a638ee8d0bc169e1ed65fe09ae
|
dc80d726a341d93f2f08d703a259637e8652f7a7
|
/Minimal/Node.h
|
8cd2b2b8d34d279caba606a4de0a8ad1b9bf46a6
|
[] |
no_license
|
tommyang/CSE190Proj1VR
|
5ae11bc6fdec40d666ea66c0c7a103fa368aa3d4
|
cb9a1fb1ce0fc2c5cdec1934f5a70e04d48a0713
|
refs/heads/master
| 2021-03-16T05:36:52.468482
| 2017-04-21T12:08:12
| 2017-04-21T12:08:12
| 88,941,321
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 668
|
h
|
Node.h
|
//
// Node.h
// CSE167Proj3
//
// Created by Tommy Yang on 11/2/16.
// Copyright © 2016 tOMG. All rights reserved.
//
#ifndef Node_h
#define Node_h
#define GLFW_INCLUDE_GLEXT
#ifdef __APPLE__
#define GLFW_INCLUDE_GLCOREARB
#else
#include <GL/glew.h>
#endif
#include <GLFW/glfw3.h>
// Use of degrees is deprecated. Use radians instead.
#ifndef GLM_FORCE_RADIANS
#define GLM_FORCE_RADIANS
#endif
#include <glm/mat4x4.hpp>
#include <glm/gtc/matrix_transform.hpp>
class Node {
public:
virtual void draw(glm::mat4 C) = 0;
virtual void draw(glm::mat4 C, GLint shaderProgram, glm::mat4 P, glm::mat4 V) = 0;
virtual void update() = 0;
};
#endif /* Node_h */
|
2129edb5814edd5c4c5f18e2afb5882be4a177c1
|
a8bc4bdef4ebc4ebfc2ae7267486e88bb3f457ab
|
/GBuffer.cpp
|
b5870620ce6c12be8459499a504dafde5366985b
|
[] |
no_license
|
KennySq/Narco
|
4bd41662c94f3dd39111d01462c1be0bc34c188e
|
ee455207c6295cc26a468a7fdb72c50fad7b62d0
|
refs/heads/master
| 2023-08-14T10:57:18.755015
| 2021-09-25T05:12:54
| 2021-09-25T05:12:54
| 407,928,569
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 786
|
cpp
|
GBuffer.cpp
|
#include"inc/GBuffer.h"
namespace NARCO
{
GBuffer::GBuffer(ID3D11Device* device, unsigned int width, unsigned int height)
: mBufferCount(ARRAYSIZE(GBufferFormats)), mDevice(device), mWidth(width), mHeight(height),
mRenderTargets(8), mShaderResources(128)
{
for (unsigned int i = 0; i < mBufferCount; i++)
{
D3DTexture2D* buffer = new D3DTexture2D(device, GBufferFormats[i],
D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE,
D3D11_USAGE_DEFAULT, width, height, 1, 0);
mBuffers.emplace_back(buffer);
mRenderTargets[i] = buffer->GetRenderTarget();
mShaderResources[i] = buffer->GetShaderResource();
}
mDepth = new D3DDepthStencil(device, D3D11_BIND_SHADER_RESOURCE, D3D11_USAGE_DEFAULT, width, height, 1);
}
GBuffer::~GBuffer()
{
}
}
|
942a38b1926c7aade81bb3bdc1e9ed733699128a
|
5e4000688f3c3910e99124a08f974ef4dce31829
|
/Sail/src/Sail/graphics/shader/Shader.h
|
25973da30c2607de0cdd464f56ee7062cfe657de
|
[
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
Skratzy/Sail
|
e82f6f2c192e4071034b0b9b8ae7b5210c256919
|
750665557de0547fcbc83b99b3094190c09147bb
|
refs/heads/master
| 2020-06-04T23:46:15.261874
| 2019-09-11T08:07:51
| 2019-09-11T08:07:51
| 192,237,848
| 0
| 0
|
MIT
| 2019-08-28T09:33:49
| 2019-06-16T21:19:02
|
C++
|
UTF-8
|
C++
| false
| false
| 505
|
h
|
Shader.h
|
#pragma once
#include "Sail/api/shader/ShaderPipeline.h"
#include <memory>
#include <string>
class Shader {
public:
Shader(const std::string& filename);
virtual ~Shader();
ShaderPipeline* getPipeline();
virtual void bind();
virtual void setClippingPlane(const glm::vec4& clippingPlane) {};
protected:
void finish();
protected:
// This is a raw pointer and not a smart pointer because reload() requires new (*) T() functionality
ShaderPipeline* shaderPipeline;
private:
bool m_finished;
};
|
a7421536e0ee863a89b799a2ccd19d948473162d
|
b1e9874c9665ba3ab271dde111e4a8b2591537eb
|
/src/smldata.ddl.cpp
|
9632781cb744857190ddbd5fd53ef2901c2eeabb
|
[] |
no_license
|
lcls-psana/psddl_pds2psana
|
528640e07b8004e0fbce89a101da48f5c25389d8
|
314c012c6115da22dd7be54662d2a0db5576c7cb
|
refs/heads/master
| 2021-12-13T18:09:51.277458
| 2021-12-07T10:31:10
| 2021-12-07T10:31:10
| 82,350,112
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,764
|
cpp
|
smldata.ddl.cpp
|
// *** Do not edit this file, it is auto-generated ***
#include "psddl_pds2psana/smldata.ddl.h"
#include <cstddef>
#include <stdexcept>
namespace psddl_pds2psana {
namespace SmlData {
ConfigV1::ConfigV1(const boost::shared_ptr<const XtcType>& xtcPtr)
: Psana::SmlData::ConfigV1()
, m_xtcObj(xtcPtr)
{
}
ConfigV1::~ConfigV1()
{
}
uint32_t ConfigV1::sizeThreshold() const {
return m_xtcObj->sizeThreshold();
}
template <typename Config>
OrigDgramOffsetV1<Config>::OrigDgramOffsetV1(const boost::shared_ptr<const XtcType>& xtcPtr, const boost::shared_ptr<const Config>& cfgPtr)
: Psana::SmlData::OrigDgramOffsetV1()
, m_xtcObj(xtcPtr)
, m_cfgPtr(cfgPtr)
{
}
template <typename Config>
OrigDgramOffsetV1<Config>::~OrigDgramOffsetV1()
{
}
template <typename Config>
int64_t OrigDgramOffsetV1<Config>::fileOffset() const {
return m_xtcObj->fileOffset();
}
template <typename Config>
uint32_t OrigDgramOffsetV1<Config>::extent() const {
return m_xtcObj->extent();
}
template class OrigDgramOffsetV1<Pds::SmlData::ConfigV1>;
template <typename Config>
ProxyV1<Config>::ProxyV1(const boost::shared_ptr<const XtcType>& xtcPtr, const boost::shared_ptr<const Config>& cfgPtr)
: Psana::SmlData::ProxyV1()
, m_xtcObj(xtcPtr)
, m_cfgPtr(cfgPtr)
, _type(xtcPtr->type())
{
}
template <typename Config>
ProxyV1<Config>::~ProxyV1()
{
}
template <typename Config>
int64_t ProxyV1<Config>::fileOffset() const {
return m_xtcObj->fileOffset();
}
template <typename Config>
const Pds::TypeId& ProxyV1<Config>::type() const { return _type; }
template <typename Config>
uint32_t ProxyV1<Config>::extent() const {
return m_xtcObj->extent();
}
template class ProxyV1<Pds::SmlData::ConfigV1>;
} // namespace SmlData
} // namespace psddl_pds2psana
|
f733fedece9c803e60641fb1f9de948ff63309ff
|
eb35b7d701ab61a394986c84ae12a5092ff34557
|
/include/AVL.hpp
|
ebc6f0ed57ed93e388467c76a3c43eee28074e81
|
[] |
no_license
|
yigittin/Datastructers-Project
|
bd59ea57aee0c355037c65f133a1d172617cdd25
|
5eaf12b9c97d7af6fac5b1496ec66ec0379f80c4
|
refs/heads/master
| 2023-07-16T09:33:40.675524
| 2021-08-30T21:15:16
| 2021-08-30T21:15:16
| 401,487,869
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,901
|
hpp
|
AVL.hpp
|
/**
* @file AVL.hpp
* @description AVL Ağacının header dosyası
* @course 1. A GRUBU
* @assignment 2. ÖDEV
* @date 22.08.2021
* @author İbrahim Yiğit Tın ibrahim.tin@ogr.sakarya.edu.tr
*/
#ifndef AVL_HPP
#define AVL_HPP
#include <iostream>
#include <cmath>
#include "Stack.hpp"
#include "StackString.hpp"
#include <string>
#include "Dugum.hpp"
using namespace std;
class AVL{
private:
Dugum* kok;
StackString*yigit=new StackString();
//Veri eklememizi sağlayan fonksiyon insert fonksiyonu
//Her eklemede dengeleme işlemi gerçekleştiriyor
Dugum* insert(int x, Dugum* t);
//Dengeleme işlemi için ağaç rotasyonları
Dugum* solTekRot(Dugum* &altDugum);
Dugum* sagTekRot(Dugum* &altDugum);
Dugum* solCiftRot(Dugum* &altDugum);
Dugum* sagCiftRot(Dugum* &altDugum);
//Derinlik ve Yükseklik için her eklemede ağacı dolaşıp stacklere pushluyoruz
void preorder(Dugum *altDugum);
//Her eklenen düğümde derinliği hesaplayan fonksiyon
int Depth(Dugum *altDugum);
//Düğümün yüksekliğini hesapladığımız fonksyion
int Yukseklik(Dugum *altDugum);
//Levelorder şekilde ağacı yazdıran fonksiyon
void SeviyeYazdir(Dugum *altDugum,int seviye);
public:
AVL();
Dugum* getKok();
//Veri eklemek ve stackstringe isim göndermek için kullandığımız fonksiyon
void Ekle(string str,int yeni);
void preorder();
//Levelorder işlemini çağırabilmemiz için public fonksiyon
void levelorder();
int Yukseklik();
};
#endif
|
262cb485ccf028a3108db02f764cb4b25f4a5137
|
a475e2bbf2615f657fbce21d1c74170d35621f49
|
/system_Programming_myshell/system_Programming_myshell/소스.cpp
|
e71637361abf915d8793f0d8261eda4c54216683
|
[] |
no_license
|
leedaegun/school_Project
|
559a843ba337d9d41e88c26fee9b400cd23b6bae
|
7d0c70a9ec5a9a725ef3b4f6db2cfa3dea00c8c5
|
refs/heads/master
| 2020-03-24T13:20:39.393785
| 2018-07-29T08:12:06
| 2018-07-29T08:12:06
| 142,742,040
| 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 3,338
|
cpp
|
소스.cpp
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#define MAX_LINE_LENGTH 1000
#define INPUT_REDIRECTION ">"
#define INPUT_REDIRECTION2 "2>"
#define OUTPUT_REDIRECTION "<"
#define PIPE "|"
#define BACKGROUND '&'
#define SPACE " \t\r\n"
int prompt(char*);
int parse(char*, char**, const char*);
int check_background(char*, int);
void redirection(char**, int, int, int);
void inner_excute(char*);
void execute(char*, int);
int main(int argc, char** argv) {
char line[MAX_LINE_LENGTH];
int line_lenth;
int i;
if (argc>1) {//입력값 있을때
strcpy(line, argv[1]);
line_lenth = strlen(line) - 1;
execute(line, line_lenth);
}
else {//입력값 없을때
while (1) {
line_lenth = prompt(line);
execute(line, line_lenth);
}
}
return 0;
}
//쉘 프롬프트
int prompt(char* line) {
int n;
printf("[%s]$ ", get_current_dir_name());
if (fgets(line, MAX_LINE_LENGTH, stdin) == NULL) {
printf("\n");
exit(0);
}
n = strlen(line) - 1;
return n;
}
//백그라운드 확인
int check_background(char* argv, int argc)
{
if (argv[argc - 1] == BACKGROUND)
return 1;
else
return 0;
}
//파싱
int parse(char* line, char** argv, const char* slice)
{
int n = 0;
char*temp = strtok(line, slice);
if (temp == NULL) return 0;
while (temp != NULL) {
argv[n++] = temp;
temp = strtok(NULL, slice);
}
argv[n] = '\0';
return n;
}
//리다이렉션
void redirection(char** params, int fd, int i, int flag) {
if ((fd = open(params[i + 1], flag, 0644)) == -1)
perror("open");
if (close(STDOUT_FILENO) == -1)
perror("close");
if (dup2(fd, STDOUT_FILENO) == -1)
perror("dup2");
if (close(fd) == -1)
perror("close");
}
//파이프
void execute(char* argv, int argc) {
int pid, i;
int status;
int fd[2];
char* arguments[MAX_LINE_LENGTH];
int bg = check_background(argv, argc);//백그라운드 확인
int num = parse(argv, arguments, PIPE);//파이프 파싱
if ((pid = fork()) == -1)
perror("fork");
else if (pid == 0) {
for (i = 0; i < num - 1; i++) {
pipe(fd);//pipe
if (fork() == 0) {
close(fd[0]);
dup2(fd[1], STDOUT_FILENO);
inner_excute(arguments[i]);
}
else {
close(fd[1]);
dup2(fd[0], STDIN_FILENO);
}
}
inner_excute(arguments[i]);
}
else {
if (bg == 0)//백그라운드&
if ((pid = waitpid(pid, &status, 0)) == -1)//wait
perror("waitpid");
}
}
//명령문, 리다이렉션 실행
void inner_excute(char* argv) {
char* params[MAX_LINE_LENGTH];
int argc = parse(argv, params, SPACE);
int fd = -1;
int flag = 0;
int i;
for (i = 0; i < argc; i++) {
//리다이렉션
if (strcmp(params[i], INPUT_REDIRECTION) == 0) {// >
flag = O_WRONLY | O_CREAT | O_TRUNC;
redirection(params, fd, i, flag);
params[i] = '\0';
i++;
}
if (strcmp(params[i], OUTPUT_REDIRECTION) == 0) {// <
flag = O_WRONLY | O_CREAT;
redirection(params, fd, i, flag);
params[i] = '\0';
i++;
}
if (strcmp(params[i], INPUT_REDIRECTION2) == 0) {// 2>
flag = O_WRONLY | O_CREAT | O_TRUNC;
redirection(params, fd, i, flag);
params[i] = '\0';
i++;
}
}
if (execvp(params[0], params) == -1)//명령어 실행
perror("execvp");
exit(0);
}
|
747fd1fb5306aca07e8bd6dc0d7999b190045451
|
e4fa11cc5f6b76517e17acc6277d150ed89b8815
|
/CommonClass/CodeMsg.cpp
|
74e54eb2ac85c76d989d13abffcf4ee5c4125a67
|
[] |
no_license
|
yeadong/Fighting
|
37512f9c0d407f8ac2599d6b876a45fe5a0225a2
|
1dde011d0e202db24b97b551ff11ba4a6212564d
|
refs/heads/master
| 2021-04-27T19:16:19.767540
| 2016-03-03T04:01:59
| 2016-03-03T04:01:59
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,515
|
cpp
|
CodeMsg.cpp
|
#include "CodeMsg.h"
CodeMsg G_CodeMsgMap[] =
{
DEFINE_PACK_CODE(code_unknown,"unknown"),
DEFINE_PACK_CODE(code_login,"login"),
DEFINE_PACK_CODE(code_login_ret_ok,"login ok"),
DEFINE_PACK_CODE(code_login_ret_failed,"login failed"),
DEFINE_PACK_CODE(code_leave,"leave"),
DEFINE_PACK_CODE(code_leave_ret,"leave return"),
DEFINE_PACK_CODE(code_create_game,"create game"),
DEFINE_PACK_CODE(code_create_game_ret_ok,"create game ok"),
DEFINE_PACK_CODE(code_create_game_ret_failed,"create game failed"),
DEFINE_PACK_CODE(code_join_game_req_gameinfo,"request game info"),
DEFINE_PACK_CODE(code_join_game_rsp_gameinfo,"respond game info"),
DEFINE_PACK_CODE(code_join_game,"join game"),
DEFINE_PACK_CODE(code_join_game_ret_ok,"join game ok"),
DEFINE_PACK_CODE(code_create_game_ret_failed,"join game failed"),
DEFINE_PACK_CODE(code_begin_game,"begin game"),
DEFINE_PACK_CODE(code_begin_game_ret_ok,"begin game ok"),
DEFINE_PACK_CODE(code_begin_game_ret_failed,"begin game failed"),
DEFINE_PACK_CODE(code_stop_game,"stop game"),
DEFINE_PACK_CODE(code_stop_game_ret,"stop game return"),
DEFINE_PACK_CODE(code_select_hero,"select game"),
DEFINE_PACK_CODE(code_select_hero_ret_ok,"select game ok"),
DEFINE_PACK_CODE(code_select_hero_ret_failed,"select game failed"),
/* {code_unknown,"unknown"},
{code_login,"login"},
{code_login_ret_ok,"login ok"},
{code_login_ret_failed,"login failed"},
{code_leave,"leave"},
{code_leave_ret,"leave return"},
{code_create_game,"create game"},
{code_create_game_ret_ok,"create game ok"},
{code_create_game_ret_failed,"create game failed"},
{code_join_game_req_gameinfo,"request game info"},
{code_join_game_rsp_gameinfo,"respond game info"},
{code_join_game,"join game"},
{code_join_game_ret_ok,"join game ok"},
{code_create_game_ret_failed,"join game failed"},
{code_begin_game,"begin game"},
{code_begin_game_ret_ok,"begin game ok"},
{code_begin_game_ret_failed,"begin game failed"},
{code_stop_game,"stop game"},
{code_stop_game_ret,"stop game return"},
{code_select_hero,"select game"},
{code_select_hero_ret_ok,"select game ok"},
{code_select_hero_ret_failed,"select game failed"},*/
};
string CodeToMsg(PackageCode code)
{
int count = sizeof(G_CodeMsgMap) / sizeof(CodeMsg);
for(int i = 0; i < count; ++i)
{
if(code == G_CodeMsgMap[i].code)
{
return G_CodeMsgMap[i].msg;
break;
}
}
return G_CodeMsgMap[0].msg;
}
|
682bef0e7133eed6b9c9ddf03943da9a875ff8eb
|
8469434575ef9752c6c82ced7b1f193ac1afa0d7
|
/pit/mappings/.svn/text-base/DropParticles.h.svn-base
|
77689a8319eb7b32c8a49b49fad3d45e479b909d
|
[] |
no_license
|
POWER-Morzh/particles
|
d37c6f0fb27d1d1b7f624dad77c676a9888d9373
|
3de5e1967e39a3bac3e8e567d417335cbab0db2e
|
refs/heads/master
| 2020-12-24T17:54:18.452415
| 2014-10-05T17:21:40
| 2014-10-05T17:21:40
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 19,690
|
DropParticles.h.svn-base
|
// This file is part of the Peano project. For conditions of distribution and
// use, please see the copyright notice at www.peano-framework.org
#ifndef PARTICLES_PIT_MAPPINGS_DropParticles_H_
#define PARTICLES_PIT_MAPPINGS_DropParticles_H_
#include "tarch/logging/Log.h"
#include "tarch/la/Vector.h"
#include "peano/grid/VertexEnumerator.h"
#include "peano/MappingSpecification.h"
#include "tarch/multicore/MulticoreDefinitions.h"
#include "particles/pit/Vertex.h"
#include "particles/pit/Cell.h"
#include "particles/pit/State.h"
#include "particles/pit/records/Particle.h"
namespace particles {
namespace pit {
namespace mappings {
class DropParticles;
}
}
}
/**
* This is a mapping from the spacetree traversal events to your user-defined activities.
* The latter are realised within the mappings.
*
* @author Peano Development Toolkit (PDT) by Tobias Weinzierl
* @version $Revision: 1.10 $
*/
class particles::pit::mappings::DropParticles {
private:
/**
* Logging device for the trace macros.
*/
static tarch::logging::Log _log;
ParticleHeap::HeapEntries extractParticlesToBeDroppedIntoChildCell(
const particles::pit::Cell& coarseGridCell,
const tarch::la::Vector<DIMENSIONS,double>& fineGridCellOffset,
const tarch::la::Vector<DIMENSIONS,double>& fineGridCellH
) const;
public:
/**
* Realises the reflecting boundaries. If you have a proper lift mechanism,
* the reflection has to be evaluated on the root node of the tree only, i.e.
* on the node having root as parent.
*/
static void reflectParticle( particles::pit::records::Particle& particle );
/**
* These flags are used to inform Peano about your operation. It tells the
* framework whether the operation is empty, whether it works only on the
* spacetree leaves, whether the operation can restart if the thread
* crashes (resiliency), and so forth. This information allows Peano to
* optimise the code.
*
* @see peano::MappingSpecification for information on thread safety.
*/
static peano::MappingSpecification touchVertexLastTimeSpecification();
static peano::MappingSpecification touchVertexFirstTimeSpecification();
static peano::MappingSpecification enterCellSpecification();
static peano::MappingSpecification leaveCellSpecification();
static peano::MappingSpecification ascendSpecification();
static peano::MappingSpecification descendSpecification();
/**
* Mapping constructor.
*
* Nop
*/
DropParticles();
#if defined(SharedMemoryParallelisation)
/**
* Nop
*/
DropParticles(const DropParticles& masterThread);
#endif
/**
* Nop
*/
virtual ~DropParticles();
#if defined(SharedMemoryParallelisation)
/**
* Nop
*/
void mergeWithWorkerThread(const DropParticles& workerThread);
#endif
/**
* Nop
*/
void createInnerVertex(
particles::pit::Vertex& fineGridVertex,
const tarch::la::Vector<DIMENSIONS,double>& fineGridX,
const tarch::la::Vector<DIMENSIONS,double>& fineGridH,
particles::pit::Vertex * const coarseGridVertices,
const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator,
particles::pit::Cell& coarseGridCell,
const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfVertex
);
/**
* Nop
*/
void createBoundaryVertex(
particles::pit::Vertex& fineGridVertex,
const tarch::la::Vector<DIMENSIONS,double>& fineGridX,
const tarch::la::Vector<DIMENSIONS,double>& fineGridH,
particles::pit::Vertex * const coarseGridVertices,
const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator,
particles::pit::Cell& coarseGridCell,
const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfVertex
);
/**
* Nop
*/
void createHangingVertex(
particles::pit::Vertex& fineGridVertex,
const tarch::la::Vector<DIMENSIONS,double>& fineGridX,
const tarch::la::Vector<DIMENSIONS,double>& fineGridH,
particles::pit::Vertex * const coarseGridVertices,
const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator,
particles::pit::Cell& coarseGridCell,
const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfVertex
);
/**
* Nop
*/
void destroyHangingVertex(
const particles::pit::Vertex& fineGridVertex,
const tarch::la::Vector<DIMENSIONS,double>& fineGridX,
const tarch::la::Vector<DIMENSIONS,double>& fineGridH,
particles::pit::Vertex * const coarseGridVertices,
const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator,
particles::pit::Cell& coarseGridCell,
const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfVertex
);
/**
* Nop
*/
void destroyVertex(
const particles::pit::Vertex& fineGridVertex,
const tarch::la::Vector<DIMENSIONS,double>& fineGridX,
const tarch::la::Vector<DIMENSIONS,double>& fineGridH,
particles::pit::Vertex * const coarseGridVertices,
const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator,
particles::pit::Cell& coarseGridCell,
const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfVertex
);
/**
* Nop
*/
void createCell(
particles::pit::Cell& fineGridCell,
particles::pit::Vertex * const fineGridVertices,
const peano::grid::VertexEnumerator& fineGridVerticesEnumerator,
particles::pit::Vertex * const coarseGridVertices,
const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator,
particles::pit::Cell& coarseGridCell,
const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfCell
);
/**
* Nop
*/
void destroyCell(
const particles::pit::Cell& fineGridCell,
particles::pit::Vertex * const fineGridVertices,
const peano::grid::VertexEnumerator& fineGridVerticesEnumerator,
particles::pit::Vertex * const coarseGridVertices,
const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator,
particles::pit::Cell& coarseGridCell,
const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfCell
);
#ifdef Parallel
/**
* Nop
*/
void mergeWithNeighbour(
particles::pit::Vertex& vertex,
const particles::pit::Vertex& neighbour,
int fromRank,
const tarch::la::Vector<DIMENSIONS,double>& x,
const tarch::la::Vector<DIMENSIONS,double>& h,
int level
);
/**
* Nop
*/
void prepareSendToNeighbour(
particles::pit::Vertex& vertex,
int toRank,
const tarch::la::Vector<DIMENSIONS,double>& x,
const tarch::la::Vector<DIMENSIONS,double>& h,
int level
);
/**
* Nop
*
* Realised in LiftParticles.
*/
void prepareCopyToRemoteNode(
particles::pit::Vertex& localVertex,
int toRank,
const tarch::la::Vector<DIMENSIONS,double>& x,
const tarch::la::Vector<DIMENSIONS,double>& h,
int level
);
/**
* Nop
*
* Realised in LiftParticles.
*/
void prepareCopyToRemoteNode(
particles::pit::Cell& localCell,
int toRank,
const tarch::la::Vector<DIMENSIONS,double>& cellCentre,
const tarch::la::Vector<DIMENSIONS,double>& cellSize,
int level
);
/**
* Nop
*/
void mergeWithRemoteDataDueToForkOrJoin(
particles::pit::Vertex& localVertex,
const particles::pit::Vertex& masterOrWorkerVertex,
int fromRank,
const tarch::la::Vector<DIMENSIONS,double>& x,
const tarch::la::Vector<DIMENSIONS,double>& h,
int level
);
/**
* Nop
*/
void mergeWithRemoteDataDueToForkOrJoin(
particles::pit::Cell& localCell,
const particles::pit::Cell& masterOrWorkerCell,
int fromRank,
const tarch::la::Vector<DIMENSIONS,double>& cellCentre,
const tarch::la::Vector<DIMENSIONS,double>& cellSize,
int level
);
/**
* Perpare startup send to worker
*
* Extract all particles from the coarser cell that are to be dropped into the
* fine grid cell and send them to worker. If the coarser cell is the root
* cell, we are running this code on the global master, and the are no
* particles on the coarser level. Otherwise, there always is at least a
* heap index.
*
* @see descend()
*/
bool prepareSendToWorker(
particles::pit::Cell& fineGridCell,
particles::pit::Vertex * const fineGridVertices,
const peano::grid::VertexEnumerator& fineGridVerticesEnumerator,
particles::pit::Vertex * const coarseGridVertices,
const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator,
particles::pit::Cell& coarseGridCell,
const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfCell,
int worker
);
/**
* Nop
*/
void mergeWithMaster(
const particles::pit::Cell& workerGridCell,
particles::pit::Vertex * const workerGridVertices,
const peano::grid::VertexEnumerator& workerEnumerator,
particles::pit::Cell& fineGridCell,
particles::pit::Vertex * const fineGridVertices,
const peano::grid::VertexEnumerator& fineGridVerticesEnumerator,
particles::pit::Vertex * const coarseGridVertices,
const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator,
particles::pit::Cell& coarseGridCell,
const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfCell,
int worker,
const particles::pit::State& workerState,
particles::pit::State& masterState
);
/**
* Nop
*/
void prepareSendToMaster(
particles::pit::Cell& localCell,
particles::pit::Vertex * vertices,
const peano::grid::VertexEnumerator& verticesEnumerator,
const particles::pit::Vertex * const coarseGridVertices,
const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator,
const particles::pit::Cell& coarseGridCell,
const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfCell
);
/**
* Counterpart of prepareSendToWorker().
*
* Take the data from the master and insert it into received cell. Before,
* we have to assign the received cell and index. See mergeWithWorker()
* for the further particles' lifecycle.
*
* !!! Remarks on Cell Indices
*
* receivedCell is a bit-wise copy from the master node. As a result, it
* has to hold a heap index. However, this value is invalid - it refers to
* a heap entry on the master. We hence first create a new index and
* overwrite the received cell's property. Then, we store the received
* particle data from the master in the heap given that brand new heap
* index. Finally, we merge the received heap data into the local tree's
* root and erase the newly created index from the heap. Merge and free
* mechanism can be found in mergeWithWorker().
*/
void receiveDataFromMaster(
particles::pit::Cell& receivedCell,
particles::pit::Vertex * receivedVertices,
const peano::grid::VertexEnumerator& receivedVerticesEnumerator,
particles::pit::Vertex * const receivedCoarseGridVertices,
const peano::grid::VertexEnumerator& receivedCoarseGridVerticesEnumerator,
particles::pit::Cell& receivedCoarseGridCell,
particles::pit::Vertex * const workersCoarseGridVertices,
const peano::grid::VertexEnumerator& workersCoarseGridVerticesEnumerator,
particles::pit::Cell& workersCoarseGridCell,
const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfCell
);
/**
* Merge received data with worker data
*
* Takes the particle (temporary) assigned to receivedMasterCell and copies
* its particles into the local cell. Afterwards, the received cell's heap
* index is freed. This time, we really
*/
void mergeWithWorker(
particles::pit::Cell& localCell,
const particles::pit::Cell& receivedMasterCell,
const tarch::la::Vector<DIMENSIONS,double>& cellCentre,
const tarch::la::Vector<DIMENSIONS,double>& cellSize,
int level
);
/**
* Counterpart of mergeWithMaster()
*/
void mergeWithWorker(
particles::pit::Vertex& localVertex,
const particles::pit::Vertex& receivedMasterVertex,
const tarch::la::Vector<DIMENSIONS,double>& x,
const tarch::la::Vector<DIMENSIONS,double>& h,
int level
);
#endif
/**
* Nop
*/
void touchVertexFirstTime(
particles::pit::Vertex& fineGridVertex,
const tarch::la::Vector<DIMENSIONS,double>& fineGridX,
const tarch::la::Vector<DIMENSIONS,double>& fineGridH,
particles::pit::Vertex * const coarseGridVertices,
const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator,
particles::pit::Cell& coarseGridCell,
const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfVertex
);
/**
* Nop
*/
void touchVertexLastTime(
particles::pit::Vertex& fineGridVertex,
const tarch::la::Vector<DIMENSIONS,double>& fineGridX,
const tarch::la::Vector<DIMENSIONS,double>& fineGridH,
particles::pit::Vertex * const coarseGridVertices,
const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator,
particles::pit::Cell& coarseGridCell,
const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfVertex
);
/**
* Enter a cell and apply boundary conditions
*
* Basically, the drop mechanism's enter cell event is empty, as there is
* nothing to drop in a cell. However, if the cell is the root of the tree,
* we apply reflecting boundary conditions here. Afterwards, the reflected
* particles (and those that haven't hit the boundary) will be sorted into
* the children due to descend().
*
* In parallel mode, the reflection acts if any only if we are on the rank
* that is the only worker of the global master, i.e. the rank that is
* responsible for the coarsest inner tree cell. There is no explicit check
* for this situation, i.e. we apply the reflection method on each (parallel)
* root node in the grid. As those nodes still are few, as the reflection
* reduces to nop for those cells that are not adjacent to the global domain
* boundary, and as the reflection is idempotent, we can do this, and we can
* afford it.
*/
void enterCell(
particles::pit::Cell& fineGridCell,
particles::pit::Vertex * const fineGridVertices,
const peano::grid::VertexEnumerator& fineGridVerticesEnumerator,
particles::pit::Vertex * const coarseGridVertices,
const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator,
particles::pit::Cell& coarseGridCell,
const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfCell
);
/**
* Nop
*/
void leaveCell(
particles::pit::Cell& fineGridCell,
particles::pit::Vertex * const fineGridVertices,
const peano::grid::VertexEnumerator& fineGridVerticesEnumerator,
particles::pit::Vertex * const coarseGridVertices,
const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator,
particles::pit::Cell& coarseGridCell,
const tarch::la::Vector<DIMENSIONS,int>& fineGridPositionOfCell
);
/**
* Nop
*/
void beginIteration(
particles::pit::State& solverState
);
/**
* Nop
*/
void endIteration(
particles::pit::State& solverState
);
/**
* Descend in the spacetree
*
* Loop over the @f$ 3^d @f$ children and drop the particles from the
* coarser cell into these children. Afterward, there are no particles on
* the coarser level anymore.
*
* !!! Distributed memory parallelisation
*
* It might happen that one of the children is a remote node, i.e. the root
* of a remote spacetree. We can be sure that no particles are to be moved
* into a deployed cell as prepareSendToWorker() is called before descend()
* and already has handled those particles.
*/
void descend(
particles::pit::Cell * const fineGridCells,
particles::pit::Vertex * const fineGridVertices,
const peano::grid::VertexEnumerator& fineGridVerticesEnumerator,
particles::pit::Vertex * const coarseGridVertices,
const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator,
particles::pit::Cell& coarseGridCell
);
/**
* Nop
*/
void ascend(
particles::pit::Cell * const fineGridCells,
particles::pit::Vertex * const fineGridVertices,
const peano::grid::VertexEnumerator& fineGridVerticesEnumerator,
particles::pit::Vertex * const coarseGridVertices,
const peano::grid::VertexEnumerator& coarseGridVerticesEnumerator,
particles::pit::Cell& coarseGridCell
);
};
#endif
|
|
73406f38860922b52910617e44e122ba277985d6
|
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
|
/NT/inetcore/winhttp/tools/spork/src/spobj/debugpage.cxx
|
e26d98e5b5fb9f83da4975f44694c7a5c81b19f1
|
[] |
no_license
|
jjzhang166/WinNT5_src_20201004
|
712894fcf94fb82c49e5cd09d719da00740e0436
|
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
|
refs/heads/Win2K3
| 2023-08-12T01:31:59.670176
| 2021-10-14T15:14:37
| 2021-10-14T15:14:37
| 586,134,273
| 1
| 0
| null | 2023-01-07T03:47:45
| 2023-01-07T03:47:44
| null |
UTF-8
|
C++
| false
| false
| 5,842
|
cxx
|
debugpage.cxx
|
/*++=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Copyright (c) 2001 Microsoft Corporation
Module Name:
debugpage.cxx
Abstract:
Implements the debug options property page.
Author:
Paul M Midgen (pmidge) 22-February-2001
Revision History:
22-February-2001 pmidge
Created
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--*/
#include <common.h>
LPCWSTR g_wszEnableDebug = L"_EnableDebug";
LPCWSTR g_wszBreakOnScriptStart = L"_BreakOnScriptStart";
LPCWSTR g_wszEnableDebugWindow = L"_EnableDebugWindow";
//-----------------------------------------------------------------------------
// dialog window procedures
//-----------------------------------------------------------------------------
INT_PTR
Spork::_DebugPropPageProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch( uMsg )
{
case WM_INITDIALOG :
{
_LoadDebugOptions();
}
break;
case WM_NOTIFY :
{
switch( ((NMHDR*) lParam)->code )
{
case PSN_SETACTIVE :
{
DBGOPTIONS dbo = {0};
if( m_pMLV )
m_pMLV->GetDebugOptions(&dbo);
CheckDlgButton(
hwnd,
IDB_ENABLEDEBUG,
(dbo.bEnableDebug ? BST_CHECKED : BST_UNCHECKED)
);
EnableWindow(
GetDlgItem(hwnd, IDB_DBGBREAK),
(IsDlgButtonChecked(hwnd, IDB_ENABLEDEBUG) == BST_CHECKED)
);
CheckDlgButton(
hwnd,
IDB_DBGBREAK,
(dbo.bBreakOnScriptStart ? BST_CHECKED : BST_UNCHECKED)
);
CheckDlgButton(
hwnd,
IDB_ENABLEDBGOUT,
(dbo.bEnableDebugWindow ? BST_CHECKED : BST_UNCHECKED)
);
}
break;
case PSN_KILLACTIVE :
{
SetWindowLongPtr(hwnd, DWLP_MSGRESULT, (LONG_PTR) FALSE);
}
return 1L;
case PSN_APPLY :
{
_SaveDebugOptions(hwnd);
SetWindowLongPtr(hwnd, DWLP_MSGRESULT, PSNRET_NOERROR);
}
return 1L;
}
}
case WM_COMMAND :
{
BOOL bPageChanged = FALSE;
switch( LOWORD(wParam) )
{
case IDB_ENABLEDEBUG :
{
EnableWindow(
GetDlgItem(hwnd, IDB_DBGBREAK),
(IsDlgButtonChecked(hwnd, LOWORD(wParam)) == BST_CHECKED)
);
bPageChanged = TRUE;
}
break;
case IDB_DBGBREAK :
case IDB_ENABLEDBGOUT :
{
bPageChanged = TRUE;
}
break;
}
if( bPageChanged )
{
PropSheet_Changed(GetParent(hwnd), hwnd);
}
}
break;
default : return 0L;
}
return 0L;
}
//-----------------------------------------------------------------------------
// handlers for dialog events
//-----------------------------------------------------------------------------
BOOL
Spork::_LoadDebugOptions(void)
{
LPWSTR wszProfilePath = _GetCurrentProfilePath();
LPVOID pvData = NULL;
DBGOPTIONS dbo = {0}; // defaults to all debugging support off
if( wszProfilePath )
{
if( GetRegValueFromKey(wszProfilePath, g_wszEnableDebug, REG_DWORD, &pvData) )
{
dbo.bEnableDebug = (BOOL) *((LPDWORD) pvData);
SAFEDELETEBUF(pvData);
}
if( GetRegValueFromKey(wszProfilePath, g_wszBreakOnScriptStart, REG_DWORD, &pvData) )
{
dbo.bBreakOnScriptStart = *((LPDWORD) pvData);
SAFEDELETEBUF(pvData);
}
if( GetRegValueFromKey(wszProfilePath, g_wszEnableDebugWindow, REG_DWORD, &pvData) )
{
dbo.bEnableDebugWindow = *((LPDWORD) pvData);
SAFEDELETEBUF(pvData);
}
SAFEDELETEBUF(wszProfilePath);
m_pMLV->SetDebugOptions(dbo);
}
return TRUE;
}
BOOL
Spork::_SaveDebugOptions(HWND dialog)
{
LPWSTR wszProfilePath = _GetCurrentProfilePath();
DBGOPTIONS dbo = {0};
dbo.bEnableDebug = (IsDlgButtonChecked(dialog, IDB_ENABLEDEBUG) == BST_CHECKED);
dbo.bBreakOnScriptStart = (IsDlgButtonChecked(dialog, IDB_DBGBREAK) == BST_CHECKED);
dbo.bEnableDebugWindow = (IsDlgButtonChecked(dialog, IDB_ENABLEDBGOUT) == BST_CHECKED);
if( wszProfilePath )
{
SetRegValueInKey(wszProfilePath, g_wszEnableDebug, REG_DWORD, (LPVOID) &dbo.bEnableDebug, sizeof(DWORD));
SetRegValueInKey(wszProfilePath, g_wszBreakOnScriptStart, REG_DWORD, (LPVOID) &dbo.bBreakOnScriptStart, sizeof(DWORD));
SetRegValueInKey(wszProfilePath, g_wszEnableDebugWindow, REG_DWORD, (LPVOID) &dbo.bEnableDebugWindow, sizeof(DWORD));
m_pMLV->SetDebugOptions(dbo);
SAFEDELETEBUF(wszProfilePath);
}
return TRUE;
}
//-----------------------------------------------------------------------------
// friend window procs, delegate to private class members
//-----------------------------------------------------------------------------
INT_PTR
CALLBACK
DebugPropPageProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
static PSPORK ps = NULL;
if( !ps )
{
switch( uMsg )
{
case WM_INITDIALOG :
{
ps = (PSPORK) ((LPPROPSHEETPAGE) lParam)->lParam;
}
break;
default : return FALSE;
}
}
return ps->_DebugPropPageProc(hwnd, uMsg, wParam, lParam);
}
|
262f84b7f9341e4ce85afd60538e7209fb191025
|
2320227045665d275bd43fbb7127066a90e39598
|
/Source/PluginEditor.h
|
03469a19c6fd242efcca2eb824a3e8a03b72cfe2
|
[] |
no_license
|
maxgraf96/DAFX_Assignment_2
|
d40abd514b27c05a9566d76086ce521f21d5d0be
|
5f18e75ace47c62b55d3a8cc7bc40a0943bcc7ef
|
refs/heads/master
| 2023-05-28T08:50:26.810696
| 2021-06-17T14:36:29
| 2021-06-17T14:36:29
| 247,538,806
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,111
|
h
|
PluginEditor.h
|
/*
==============================================================================
This file was auto-generated!
It contains the basic framework code for a JUCE plugin editor.
==============================================================================
*/
#pragma once
#include "PluginProcessor.h"
#include "JUCEEditor.h"
/**
*This class is currently mainly a wrapper for the JUCEEditor.
*/
class Dafx_assignment_2AudioProcessorEditor : public AudioProcessorEditor
{
public:
Dafx_assignment_2AudioProcessorEditor (Dafx_assignment_2AudioProcessor&, AudioProcessorValueTreeState& vts, SamplePanel& samplePanel);
~Dafx_assignment_2AudioProcessorEditor();
void paint (Graphics&) override;
void resized() override;
private:
// Reference to the main audio processor
Dafx_assignment_2AudioProcessor& processor;
// State management
AudioProcessorValueTreeState& valueTreeState;
// Main editor built with Projucer GUI editor
std::unique_ptr<JUCEEditor> editor;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Dafx_assignment_2AudioProcessorEditor)
};
|
98d0dcab4cd537601946f74e8473e8e2afc015ef
|
be3989c18030bb6d6fd51c20419d68d04358d5be
|
/ControlFlowVisualization/src/items/VControlFlowMethodSwitch.cpp
|
289941f8147a984a9917551c7b3340b74f3d7ae2
|
[
"BSD-3-Clause"
] |
permissive
|
Andresbu/Envision
|
e6226ab826a15827ad7187823625646e3f1c5c12
|
864396334ed521c2ff6dee8a24f624b2c70e2a86
|
refs/heads/master
| 2021-01-18T08:43:15.416892
| 2012-03-29T15:36:27
| 2012-03-29T15:36:27
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,270
|
cpp
|
VControlFlowMethodSwitch.cpp
|
/***********************************************************************************************************************
**
** Copyright (c) 2011, 2012 ETH Zurich
** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
**********************************************************************************************************************/
/*
* VControlFlowMethodSwitch.cpp
*
* Created on: Mar 1, 2012
* Author: Dimitar Asenov
*/
#include "items/VControlFlowMethodSwitch.h"
#include "items/VMethodCF.h"
#include "OOVisualization/src/top_level/VMethod.h"
namespace ControlFlowVisualization {
ITEM_COMMON_DEFINITIONS(VControlFlowMethodSwitch, "item")
VControlFlowMethodSwitch::VControlFlowMethodSwitch(Item* parent, NodeType* node, const StyleType* style)
:ItemWithNode<Visualization::Item, OOModel::Method>(parent, node, style), showAsControlFlow_(false),
metCF_(nullptr), met_(nullptr)
{
}
bool VControlFlowMethodSwitch::sizeDependsOnParent() const
{
if (metCF_) return metCF_->sizeDependsOnParent();
else return met_->sizeDependsOnParent();
}
void VControlFlowMethodSwitch::determineChildren()
{
if (isRenderingChanged())
{
SAFE_DELETE(met_);
SAFE_DELETE(metCF_);
}
if (isShownAsControlFlow()) synchronizeItem<VMethodCF>(metCF_, node(), nullptr);
else synchronizeItem<OOVisualization::VMethod>(met_, node(), nullptr);
}
void VControlFlowMethodSwitch::updateGeometry(int availableWidth, int availableHeight)
{
if (metCF_) Item::updateGeometry(metCF_, availableWidth, availableHeight);
else Item::updateGeometry(met_, availableWidth, availableHeight);
}
bool VControlFlowMethodSwitch::isRenderingChanged() const
{
return (met_ && isShownAsControlFlow()) || (metCF_ && !isShownAsControlFlow());
}
} /* namespace ControlFlowVisualization */
|
dbd27b8ebdff08e7f054c20842ec0084f66a0320
|
e8cb8cc6ee0a5c790eb0948cbf1801c9527ce108
|
/GameEngineArchitecture/include/Collision.h
|
f573f66124e8de460d140a6dc8a513a709f960ed
|
[
"MIT"
] |
permissive
|
Cubes58/Team_NoName_GameEngine
|
84c2042d873d25b72828248633fb4bd40b154755
|
5b1f75a61c43a1e1649b5a34a799aab65af70afd
|
refs/heads/master
| 2020-04-22T16:48:01.531092
| 2019-05-03T12:36:34
| 2019-05-03T12:36:34
| 170,520,218
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,881
|
h
|
Collision.h
|
/**
@file Collision.h
@brief A class that handles collisions.
*/
#pragma once
#include <cmath>
#include <glm/glm.hpp>
/*! \class Collision
\brief A class that handles collisions.
*/
class Collision {
public:
Collision() = default; //!< Default constructor.
~Collision() = default; //!< Default destructor.
/*!
\brief Detects a collision between two AABB objects.
\param p_EntityOnePosition entity one's position.
\param p_EntityTwoPosition entity two's position.
\param p_EntityOneSize entity one's size.
\param p_EntityTwoSize entity two's size.
\return Returns true if a collision has happened, false otherwise.
*/
bool operator()(const glm::vec3 &p_EntityOnePosition, const glm::vec3 &p_EntityTwoPosition, const glm::vec3 &p_EntityOneSize, const glm::vec3 &p_EntityTwoSize) {
glm::vec2 entityOneXAxisLine(p_EntityOnePosition.x - p_EntityOneSize.x, p_EntityOnePosition.x + p_EntityOneSize.x);
glm::vec2 entityOneYAxisLine(p_EntityOnePosition.y - p_EntityOneSize.y, p_EntityOnePosition.y + p_EntityOneSize.y);
glm::vec2 entityOneZAxisLine(p_EntityOnePosition.z - p_EntityOneSize.z, p_EntityOnePosition.z + p_EntityOneSize.z);
glm::vec2 entityTwoXAxisLine(p_EntityTwoPosition.x - p_EntityTwoSize.x, p_EntityTwoPosition.x + p_EntityTwoSize.x);
glm::vec2 entityTwoYAxisLine(p_EntityTwoPosition.y - p_EntityTwoSize.y, p_EntityTwoPosition.y + p_EntityTwoSize.y);
glm::vec2 entityTwoZAxisLine(p_EntityTwoPosition.z - p_EntityTwoSize.z, p_EntityTwoPosition.z + p_EntityTwoSize.z);
// AABB collision check.
if (entityOneXAxisLine.x >= entityTwoXAxisLine.x && entityOneXAxisLine.y <= entityTwoXAxisLine.y
&& entityOneYAxisLine.x >= entityTwoYAxisLine.x && entityOneYAxisLine.y <= entityTwoYAxisLine.y
&& entityOneZAxisLine.x >= entityTwoZAxisLine.x && entityOneZAxisLine.y <= entityTwoZAxisLine.y) {
return true;
}
return false;
}
};
|
ef6be5db0aeaf100479ca0d1c2830c20690f5951
|
e8a3c0b3722cacdb99e15693bff0a4333b7ccf16
|
/Code forces/Divide by Zero 2018 and Codeforces Round #474 (Div. 1 + Div. 2, combined)/aaa.cpp
|
62689b6650774a31dfd77f4d49df306a9a23a611
|
[] |
no_license
|
piyush1146115/Competitive-Programming
|
690f57acd374892791b16a08e14a686a225f73fa
|
66c975e0433f30539d826a4c2aa92970570b87bf
|
refs/heads/master
| 2023-08-18T03:04:24.680817
| 2023-08-12T19:15:51
| 2023-08-12T19:15:51
| 211,923,913
| 5
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 872
|
cpp
|
aaa.cpp
|
#include<bits/stdc++.h>
using namespace std;
int ar[20000];
int br[20000];
int k1,k2,n;
struct st{int dif,ind; };
vector<st>v;
bool cmp(st aa,st bb)
{
if(aa.dif==bb.dif)
return aa.ind<bb.ind;
return aa.dif<bb.dif;
}
int main(){
cin>>n;
cin>>k1>>k2;
for(int i=0;i<n;i++)
cin>>ar[i];
for(int i=0;i<n;i++)
cin>>br[i];
for(int i=0;i<n;i++)
{
st temp;
temp.dif=abs(ar[i]-br[i]);
temp.ind=i;
v.push_back(temp);
}
sort(v.begin(),v.end(),cmp);
int l=v.size();
int total=k1+k2;
while(total)
{
total--;
if(l)
{v[l-1].dif=abs(v[l-1].dif-1);
sort(v.begin(),v.end(),cmp);
}
}
long long int sum=0;
for(int i=0;i<n;i++)
{
sum+=(long long int)(v[i].dif*v[i].dif);
}
cout<<sum<<endl;
}
|
c37a5202e6e82f4d597f67fb5f10b46490e63861
|
c3192020e560076ef8af3dce5355f7ab0ff685be
|
/legged_control/legged_controllers/src/utility_control.cpp
|
99cd42dc1493bc000b398c1021aad6c350914287
|
[
"BSD-3-Clause"
] |
permissive
|
CiaranZ/CIaran
|
604c93b1126643fcf6fd6f34e5b420b7a4c41ab4
|
185624ce371482820eba3d59fd0122e9d332bfde
|
refs/heads/master
| 2023-06-11T11:21:30.667753
| 2023-05-30T10:27:39
| 2023-05-30T10:27:39
| 123,782,966
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,388
|
cpp
|
utility_control.cpp
|
#include <pinocchio/fwd.hpp> // forward declarations must be included first.
#include <pinocchio/algorithm/jacobian.hpp>
#include <pinocchio/algorithm/frames.hpp>
#include <pinocchio/algorithm/kinematics.hpp>
#include "legged_controllers/utility_control.h"
#include <algorithm>
using Eigen::MatrixXd;
using Eigen::VectorXd;
namespace ocs2 {
namespace legged_robot {
Utilitypolicy::Utilitypolicy(legged::LeggedInterface& legged_interface, std::shared_ptr<GaitSchedule> gaitSchedulePtr,
std::map<std::string, ModeSequenceTemplate> gaitMapconst, vector_t& optcurrent, std::vector<legged::ContactSensorHandle>& contact_sensor_handles,
const std::string& robotName)
: legged_interface_(legged_interface),gaitMapconst_(gaitMapconst),gaitSchedulePtr_(std::move(gaitSchedulePtr)),optcurrent_(optcurrent),contact_sensor_handles_(contact_sensor_handles)
{
}
void Utilitypolicy::preSolverRun(scalar_t initTime, scalar_t finalTime, const vector_t& currentState,
const ReferenceManagerInterface& referenceManager)
{
const auto timeHorizon = finalTime - initTime;
static auto gaitCommand="stance";
static auto gaitCommandold="none";
std::vector<std::pair<size_t, double>> vtMap;
// CentroidalModelPinocchioMapping pinocchio_mapping(legged_interface_.getCentroidalModelInfo());
// PinocchioEndEffectorKinematics ee_kinematics(legged_interface_.getPinocchioInterface(), pinocchio_mapping,
// legged_interface_.modelSettings().contactNames3DoF);
// const auto& model = legged_interface_.getPinocchioInterface().getModel();
// auto& data = legged_interface_.getPinocchioInterface().getData();
// ee_kinematics.setPinocchioInterface(legged_interface_.getPinocchioInterface());
// auto currenteepos = ee_kinematics.getPosition(currentState);
// static std::vector<vector3_t> currenteepos_contact;
// auto state_final = referenceManager.getTargetTrajectories().stateTrajectory.back();
// auto state_start = referenceManager.getTargetTrajectories().stateTrajectory.front();
// static vector_t state_start_last = state_start;
// pinocchio::forwardKinematics(model, data, centroidal_model::getGeneralizedCoordinates(state_start, legged_interface_.getCentroidalModelInfo()));
// pinocchio::updateFramePlacements(model, data);
// auto feetPositions_start = ee_kinematics.getPosition(state_start);
// pinocchio::forwardKinematics(model, data, centroidal_model::getGeneralizedCoordinates(state_final, legged_interface_.getCentroidalModelInfo()));
// pinocchio::updateFramePlacements(model, data);
// auto feetPositions_opt = ee_kinematics.getPosition(state_final);
// auto composition = currentState.segment<3>(6);
// auto composition_ref = state_final.segment<3>(6);
// auto composition_start = state_start.segment<3>(6);
std::vector<vector3_t> feetForces(legged_interface_.getCentroidalModelInfo().numThreeDofContacts);
for (size_t i = 0; i < legged_interface_.getCentroidalModelInfo().numThreeDofContacts; i++) {
feetForces[i] = centroidal_model::getContactForces(optcurrent_, i, legged_interface_.getCentroidalModelInfo());
std::cerr << "feetForces "<<i<<":"<<feetForces[i]<<std::endl;
}
// if(currenteepos_contact.empty())
// {
// currenteepos_contact = currenteepos;
// }
// // if(state_start_last.empty())
// // {
// // state_start_last = state_start;
// // }
// for (size_t i = 0; i < 4; i++)
// {
// if(contact_sensor_handles_[i].isContact())
// currenteepos_contact[i] = currenteepos[i];
// }
// std::vector<vector3_t> com2pfeet(4);
// static vector3_t staticcompos;
// static std::vector<vector3_t> feet_ref; //每次收到指令的时候
// if (feet_ref.empty())
// {
// feet_ref = com2pfeet;
// }
// if (state_start_last != state_start)
// {
// for (size_t i = 0; i < 4; i++)
// {
// feet_ref[i]= currenteepos_contact[i] - composition;
// }
// state_start_last = state_start;
// }
// auto currentrefstate = referenceManager.getTargetTrajectories().getDesiredState(initTime);
// auto currentrefstatecom = currentrefstate.segment<3>(6);
// for (size_t i = 0; i < 4; i++)
// {
// com2pfeet[i]= currenteepos_contact[i] - composition; // 每时每刻的
// // std::cerr << "leg com2pfeet No."<<i<<":"<< com2pfeet[i] << "\n";
// }
// std::vector<vector3_t> beforemapping(4);
// for (size_t i = 0; i < 4; i++)
// {
// vector3_t unitwheelvector ;
// VectorXd wheelvector(3);
// vector3_t bodyvector;
// MatrixXd rotw2b;
// // rotw2b.setZero(3,3);
// // rotw2b(0,0) = cos(-currentState(9));
// // rotw2b(0,1) = -sin(-currentState(9));
// // rotw2b(1,0) = sin(-currentState(9));
// // rotw2b(1,1) = cos(-currentState(9));
// unitwheelvector(0) = cos(currentState(9)); // 这个不对
// unitwheelvector(1) = sin(currentState(9));//-1
// auto pointby = unitwheelvector.dot(currentrefstatecom);
// bodyvector= pointby*unitwheelvector;
// // bodyvector = rotw2b * wheelvector;
// beforemapping[i] =(feet_ref[i]+currentrefstatecom) - (com2pfeet[i]+bodyvector);
// // std::cerr << "leg cos No."<<i<<": \n"<< cos(currentState(9)) << "\n";
// // std::cerr << "leg sin No."<<i<<": \n"<< sin(currentState(9)) << "\n";
// // std::cerr << "leg currenteepos_contact No."<<i<<":\n"<< currenteepos_contact[i] << "\n";
// // std::cerr << "staticcompos"<<i<<":\n"<< currentrefstatecom << "\n";
// // std::cerr << "eet_ref[i]+currentrefstatecom"<<i<<":\n"<< feet_ref[i]+currentrefstatecom << "\n";
// // std::cerr << "(com2pfeet[i]+bodyvector)"<<i<<":\n"<<(com2pfeet[i]+bodyvector) << "\n";
// // std::cerr << "bodyvector"<<i<<":\n"<< bodyvector << "\n";
// // std::cerr << "wheelvector[0]"<<i<<":\n"<< wheelvector[0] << "\n";
// // std::cerr << "leg unitwheelvector No."<<i<<":\n"<< unitwheelvector << "\n";
// // std::cerr << "leg pointby No."<<i<<":\n"<< pointby << "\n";
// // std::cerr << "leg feet_ref No."<<i<<":\n"<< feet_ref[i] << "\n";
// // std::cerr << "leg com2pfeet No."<<i<<":\n"<< com2pfeet[i] << "\n";
// }
// float lemada1 = 0.1;
// float lemada2 = 0.1;
// vector_t leguitility(4);
// for (size_t i = 0; i < 4; i++)
// {
// vector3_t unitwheelvector ;
// vector3_t unitwheelvectorv;
// unitwheelvector(0) = cos(currentState(9));
// unitwheelvector(1) = sin(currentState(9));
// unitwheelvectorv(0)= cos(currentState(9));
// unitwheelvectorv(1)= sin(currentState(9));
// leguitility[i] = 1.0-sqrt((((unitwheelvector.dot(beforemapping[i]))/lemada1)*((unitwheelvector.dot(beforemapping[i]))/lemada1))+(((unitwheelvectorv.dot(beforemapping[i]))/lemada2)*((unitwheelvectorv.dot(beforemapping[i]))/lemada2)));
// // std::cerr << "leg lemada1 No."<<i<<":"<< ((unitwheelvector.dot(beforemapping[i]))/lemada1) << "\n";
// // std::cerr << "leg lemada2 No."<<i<<":"<< ((unitwheelvectorv.dot(beforemapping[i]))/lemada2) << "\n";
// // std::cerr << "leg uitility No."<<i<<":"<< leguitility[i] << "\n";
// }
static std::map<size_t, double> gaitCommandstack;
gaitCommandstack.clear();
for (size_t i = 0; i < 4; i++)
{
if(abs(feetForces[i][1])>15)
{
gaitCommandstack.insert({i,abs(feetForces[i][1])});
}
// std::cerr << "leg uitility No."<<i<<":"<< gaitCommandstack[i] <<"\n";
}
// //lflhrfrh
if(!gaitCommandstack.empty())
{
double sumforce;
for (size_t i = 0; i < gaitCommandstack.size(); i++)
{
sumforce += gaitCommandstack[i];
// std::cerr << "leg uitility No."<<i<<":"<< gaitCommandstack[i] <<"\n";
}
if(gaitCommandstack.size() == 1)
{
if(gaitCommandstack[0]>10)
gaitCommand = "trot";
}
else if(gaitCommandstack.size() == 2)
{
if(gaitCommandstack[0]+gaitCommandstack[1]>20)
gaitCommand = "trot";
}
else if(gaitCommandstack.size() == 3)
{
if(gaitCommandstack[0]+gaitCommandstack[1]+gaitCommandstack[2]>30)
gaitCommand = "trot";
}
else if(gaitCommandstack.size() == 4)
{
if(gaitCommandstack[0]+gaitCommandstack[1]+gaitCommandstack[2]+gaitCommandstack[3]>40)
gaitCommand = "trot";
}
// vtMap.clear();
// for (auto it = gaitCommandstack.begin(); it != gaitCommandstack.end(); it++)
// {
// vtMap.push_back(std::make_pair(it->first, it->second));
// // std::cerr << "leg vtMap No."<<it->first<<":"<< it->second <<"\n";
// }
// for (size_t i = 0; i < vtMap.size(); i++)
// {
// std::cerr << "leg vtMap No."<<vtMap[i].first<<":"<< vtMap[i].second <<"\n";
// }
// sort(vtMap.begin(), vtMap.end(),
// [](const std::pair<size_t, double> &x, const std::pair<size_t, double> &y) -> size_t {
// return x.second < y.second;
// });
// static size_t filter_cnt = 0;
// static size_t old_feet = 0;
// //vtmap 按照value排列
// if(vtMap.size() == 1)
// {
// switch (vtMap[0].first)
// {
// case 0: //lf
// {
// if(!contact_sensor_handles_[1].isContact() || !contact_sensor_handles_[2].isContact())
// gaitCommand = "lf_recover";
// }
// break;
// case 1://rf
// {
// if(!contact_sensor_handles_[0].isContact() || !contact_sensor_handles_[3].isContact())
// gaitCommand = "rf_recover";
// }
// break;
// case 2://lh
// {
// if(!contact_sensor_handles_[1].isContact() || !contact_sensor_handles_[3].isContact())
// gaitCommand = "lh_recover";
// }
// break;
// case 3://rh
// {
// if(!contact_sensor_handles_[1].isContact() || !contact_sensor_handles_[2].isContact())
// gaitCommand = "rh_recover";
// }
// break;
// default:
// break;
// }
// }
// else if(vtMap.size() == 4)
// {
// switch (vtMap[0].first)
// {
// case 0:
// case 3:
// {
// if(!contact_sensor_handles_[1].isContact() || !contact_sensor_handles_[2].isContact())
// gaitCommand = "lf_rh_recover";
// }
// break;
// case 1:
// case 2:
// {
// if(!contact_sensor_handles_[0].isContact() || !contact_sensor_handles_[3].isContact())
// gaitCommand = "lh_rf_recover";
// }
// break;
// default:
// break;
// }
// }
// else
// {
// switch (vtMap[0].first)
// {
// case 0://LF
// vtMap[1].first == 3 ?gaitCommand = "lf_rh_recover":gaitCommand = "lf_recover";
// break;
// case 1://rf
// vtMap[1].first == 2 ?gaitCommand = "lh_rf_recover":gaitCommand = "rf_recover";
// break;
// case 2:
// vtMap[1].first == 1 ?gaitCommand = "lf_rh_recover":gaitCommand = "lh_recover";
// break;
// case 3:
// vtMap[1].first == 0 ?gaitCommand = "lh_rf_recover":gaitCommand = "rh_recover";
// break;
// default:
// break;
// }
// }
}
else
{
gaitCommand = "stance";
}
if(gaitCommandold == gaitCommand)
{
std::cerr << "gaitCommand"<<gaitCommand<<"\n";;
}
else
{
std::cerr << "gaitCommand"<<gaitCommand<<"\n";
gaitSchedulePtr_->insertModeSequenceTemplate(gaitMapconst_.at(gaitCommand),finalTime, timeHorizon);
}
gaitCommandold = gaitCommand;
// if(leguitility[3]<0.5 && gaitCommand !="rh_recover")
// {
// gaitCommand ="rh_recover";
// std::cerr << "leg uitility" << leguitility[3] << "gaitCommand"<<gaitCommand<<"\n";
// gaitSchedulePtr_->insertModeSequenceTemplate(gaitMapconst_.at(gaitCommand),finalTime, timeHorizon);
// }
// else if(leguitility[3]>=0.5 && gaitCommand !="stance")
// {
// gaitCommand ="stance";
// std::cerr << "leg uitility" << leguitility[3] << "gaitCommand"<<gaitCommand<<"\n";
// gaitSchedulePtr_->insertModeSequenceTemplate(gaitMapconst_.at(gaitCommand),finalTime, timeHorizon);
// }
}
} // namespace legged_robot
}
|
41bcc0a145443033e7f25983f1b260a6f4a374de
|
decbc163a046664db70b1dbea8919d123df496df
|
/STL/STL_generic_function.cpp
|
9a173ae580cb8bddad832af1134f92eb80779bca
|
[] |
no_license
|
divyansh199/STL
|
b3fcd31ca782736ad3a9acda4f90fc7c8c540a36
|
1d717f965f5039f3334f8183302aba3353b33f37
|
refs/heads/master
| 2022-12-05T08:47:41.948297
| 2020-08-18T14:59:39
| 2020-08-18T14:59:39
| 288,218,339
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 925
|
cpp
|
STL_generic_function.cpp
|
//generic means fuction work with diff data type//
//algo as generic//
#include<bits/stdc++.h>
using namespace std;
template<typename t>
int search(t arr[],int n,t key)
{
for(int p=0;p<n;p++)
{
if(arr[p]==key)
return p;
}
return n;
}
template<class ForwardIterator,class T>
ForwardIterator search(ForwardIterator start,ForwardIterator end,T key)
{
while(start!=end)
{
if(*start == key)
{
return start;
}
start++;
}
return end;
}
int main(){
/*
int a[]= {1,2,3,4 ,10,12};
int n= sizeof(a)/sizeof(int);
int key =10;
cout<<search(a,n,key)<<endl;
float b[]={1.1,1.2,1.3};
float k= 1.2;
cout<<search(b,3,k);
*/
list<int>l;
l.push_back(1);
l.push_back(2);
l.push_back(5);
l.push_back(3);
auto it = search(l.begin(),l.end(),5);
if(it == l.end())
{
cout<<"list is empty";
}
else{
cout<<*it<<endl;
}
}
|
8106a2fa8001e72f904d44041a452d968ba3d7f5
|
0fa8a85b9a83cf0eb6ab9173f2cdfa7d26741a26
|
/Sources/Overload/OvUI/include/OvUI/Widgets/Selection/ComboBox.h
|
bbd1edb999c352d5c2b394d6cf90d28eb1a30be8
|
[
"MIT"
] |
permissive
|
adriengivry/Overload
|
79221401de4cc5864bfdb97289249f23fa2d299b
|
151972a6d299cb08d2824af398c12abe4ea3f2e7
|
refs/heads/develop
| 2023-07-20T12:09:25.481109
| 2023-06-27T13:49:50
| 2023-06-27T13:49:50
| 191,771,083
| 1,465
| 207
|
MIT
| 2023-07-06T19:30:12
| 2019-06-13T13:45:15
|
C++
|
UTF-8
|
C++
| false
| false
| 613
|
h
|
ComboBox.h
|
/**
* @project: Overload
* @author: Overload Tech.
* @licence: MIT
*/
#pragma once
#include <map>
#include <OvTools/Eventing/Event.h>
#include "OvUI/Widgets/DataWidget.h"
namespace OvUI::Widgets::Selection
{
/**
* Widget that can display a list of values that the user can select
*/
class ComboBox : public DataWidget<int>
{
public:
/**
* Constructor
* @param p_currentChoice
*/
ComboBox(int p_currentChoice = 0);
protected:
void _Draw_Impl() override;
public:
std::map<int, std::string> choices;
int currentChoice;
public:
OvTools::Eventing::Event<int> ValueChangedEvent;
};
}
|
f8a523960c0f187e21a9e7d71b5036ee5a3e6227
|
3b86e73a2f3213a2265373935a6641c5052b7c20
|
/dialog.h
|
818aec8c03115fe730618451443929885d6cb01b
|
[] |
no_license
|
381706-1KolesovaChristina/vkr_imit_sto
|
90c6b9261d36ae2565e2a6c42186c7768b86091b
|
cff640173584369e569a6a9097cd241475c8fc71
|
refs/heads/main
| 2023-06-22T14:10:22.635521
| 2021-07-23T12:02:41
| 2021-07-23T12:02:41
| 388,780,597
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 429
|
h
|
dialog.h
|
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include <vector>
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = nullptr);
~Dialog();
signals:
void sendData (std::vector<int> vecT, std::vector<int> vecC);
public slots:
void on_pushButton_clicked();
private:
Ui::Dialog *ui;
};
#endif // DIALOG_H
|
7e9aaab845d2fd77276a797d8fb0acd2c0744b43
|
a6f13eae9385ff1c1c84a2c310d3d3e12d096bb2
|
/Sources/BaseMuteAction.cpp
|
423ea872c6e4a6511ff46f46bcd804bbb9119225
|
[
"CC0-1.0",
"MIT"
] |
permissive
|
stream-notes/StreamDeck-AudioMute
|
ec5830005c7a8e4f7d10671eacc1fc0a0a85bb6b
|
ca6f0b98cf46e848ad4facfecf8c23667fb6a428
|
refs/heads/master
| 2023-03-05T08:49:48.441080
| 2021-02-20T19:22:15
| 2021-02-20T19:22:15
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,856
|
cpp
|
BaseMuteAction.cpp
|
/* Copyright (c) 2019-present, Fred Emmott
*
* This source code is licensed under the MIT-style license found in the
* LICENSE file.
*/
#include "BaseMuteAction.h"
#include <StreamDeckSDK/EPLJSONUtils.h>
#include <StreamDeckSDK/ESDLogger.h>
#include <AudioDevices/AudioDevices.h>
#include "DefaultAudioDevices.h"
using json = nlohmann::json;
void from_json(const json& json, MuteActionSettings& settings) {
const auto default_id =
DefaultAudioDevices::GetRealDeviceID(
DefaultAudioDevices::COMMUNICATIONS_INPUT_ID
).empty()
? DefaultAudioDevices::DEFAULT_INPUT_ID
: DefaultAudioDevices::COMMUNICATIONS_INPUT_ID;
settings.deviceID = json.value<std::string>("deviceID", default_id);
settings.feedbackSounds = json.value<bool>("feedbackSounds", true);
settings.ptt = json.value<bool>("ptt", false);
}
namespace FredEmmott::Audio {
void to_json(json& j, const AudioDeviceState& state) {
switch (state) {
case AudioDeviceState::CONNECTED:
j = "connected";
return;
case AudioDeviceState::DEVICE_NOT_PRESENT:
j = "device_not_present";
return;
case AudioDeviceState::DEVICE_DISABLED:
j = "device_disabled";
return;
case AudioDeviceState::DEVICE_PRESENT_NO_CONNECTION:
j = "device_present_no_connection";
return;
}
}
void to_json(json& j, const AudioDeviceInfo& device) {
j = json({{"id", device.id},
{"interfaceName", device.interfaceName},
{"endpointName", device.endpointName},
{"displayName", device.displayName},
{"state", device.state}});
}
}// namespace FredEmmott::Audio
BaseMuteAction::~BaseMuteAction() {
}
std::string BaseMuteAction::GetRealDeviceID() const {
return mRealDeviceID;
}
void BaseMuteAction::SendToPlugin(const nlohmann::json& payload) {
const auto event = EPLJSONUtils::GetStringByName(payload, "event");
if (event != "getDeviceList") {
return;
}
SendToPropertyInspector(
json{{"event", event},
{"outputDevices", GetAudioDeviceList(AudioDeviceDirection::OUTPUT)},
{"inputDevices", GetAudioDeviceList(AudioDeviceDirection::INPUT)},
{"defaultDevices",
{{DefaultAudioDevices::DEFAULT_INPUT_ID,
DefaultAudioDevices::GetRealDeviceID(
DefaultAudioDevices::DEFAULT_INPUT_ID)},
{DefaultAudioDevices::DEFAULT_OUTPUT_ID,
DefaultAudioDevices::GetRealDeviceID(
DefaultAudioDevices::DEFAULT_OUTPUT_ID)},
{DefaultAudioDevices::COMMUNICATIONS_INPUT_ID,
DefaultAudioDevices::GetRealDeviceID(
DefaultAudioDevices::COMMUNICATIONS_INPUT_ID)},
{DefaultAudioDevices::COMMUNICATIONS_OUTPUT_ID,
DefaultAudioDevices::GetRealDeviceID(
DefaultAudioDevices::COMMUNICATIONS_OUTPUT_ID)}}}});
}
void BaseMuteAction::SettingsDidChange(
const MuteActionSettings& old_settings,
const MuteActionSettings& new_settings) {
mFeedbackSounds = new_settings.feedbackSounds;
if (old_settings.deviceID == new_settings.deviceID) {
return;
}
mRealDeviceID = DefaultAudioDevices::GetRealDeviceID(new_settings.deviceID);
RealDeviceDidChange();
if (mRealDeviceID == new_settings.deviceID) {
return;
}
// Differing real device ID means we have a place holder device, e.g.
// 'Default input device'
ESDDebug("Registering default device change callback for {}", GetContext());
mDefaultChangeCallbackHandle = std::move(AddDefaultAudioDeviceChangeCallback(
[this](
AudioDeviceDirection direction, AudioDeviceRole role,
const std::string& device) {
ESDDebug("In default device change callback for {}", GetContext());
if (
DefaultAudioDevices::GetSpecialDeviceID(direction, role)
!= GetSettings().deviceID) {
ESDDebug("Not this device");
return;
}
ESDLog(
"Special device change: old device: '{}' - new device: '{}'",
mRealDeviceID, device);
if (device == mRealDeviceID) {
ESDLog("Default default change for context {} didn't actually change");
return;
}
mRealDeviceID = device;
ESDLog(
"Invoking RealDeviceDidChange from callback for context {}",
GetContext());
RealDeviceDidChange();
}));
}
bool BaseMuteAction::FeedbackSoundsEnabled() const {
return mFeedbackSounds;
}
void BaseMuteAction::RealDeviceDidChange() {
const auto device(GetRealDeviceID());
mMuteUnmuteCallbackHandle = std::move(AddAudioDeviceMuteUnmuteCallback(
device, [this](bool isMuted) { this->MuteStateDidChange(isMuted); }));
try {
MuteStateDidChange(IsAudioDeviceMuted(device));
} catch (device_error) {
ShowAlert();
}
}
void BaseMuteAction::KeyUp() {
try {
DoAction();
} catch (FredEmmott::Audio::device_error e) {
ShowAlert();
}
}
|
3949a6075e1a89a56e01d1181a360c0b3574e90d
|
8c9715e1f55f132015c168c15be1d8dbb28a5192
|
/ProjectRvR/Scene.cpp
|
5f61e3909453b8245a116416155d01993dac564b
|
[
"MIT"
] |
permissive
|
yippee-ki-yay/ProjectRvR
|
f8eeb55d76b466fb272a4bc3cbec344b0a3625af
|
9b3f26f8fe8fa6227bfbfe4d4d72b0e0d9fb4ef1
|
refs/heads/master
| 2021-01-20T11:47:50.693600
| 2015-02-19T09:04:00
| 2015-02-19T09:04:00
| 30,359,600
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,736
|
cpp
|
Scene.cpp
|
#include "Scene.h"
#include "Rocket.h"
#include <iostream>
#include "util.h"
Scene::Scene(int width, int height, std::string title)
{
window = new sf::RenderWindow(sf::VideoMode(width, height), title);
event = new sf::Event;
window->setFramerateLimit(30); //uvek da je 30fps moze da se promeni kasnije
window->setKeyRepeatEnabled(false);
//testPath = new RocketPath(0, 600); //ovo je u sustini x vrednost funkcije 0..600
srand(time(NULL));
rot = 0;
}
Scene::~Scene()
{
delete window;
delete event;
}
bool Scene::isActive()
{
return window->isOpen();
}
void Scene::update()
{
while(window->pollEvent(*event))
{
if(event->type == sf::Event::Closed)
window->close();
if (event->type == sf::Event::KeyPressed)
{
if(event->key.code == sf::Keyboard::Space)
{
if(manager.hasRockets())
{
sf::Time t = fireClock.getElapsedTime();
std::cout<<t.asMilliseconds()<<std::endl;
if(t.asMilliseconds() >= 500)
{
std::cout << "DODAO NAPAD" << std::endl;
Rocket* r = manager.getRocket(RocketManager::ATTACK);
float x[3] = {400, 0, -400};
float y[3] = {-300, -150, -300};
x[1] = rand()%200 - 100;
y[1] = rand()%500 - 250;
interpolation(x, y, r->getFun());
fireClock.restart();
}
}
}
}
}
window->clear();
base.checkFirstWall(&manager);
base.gatherPoints(&defManager);
/** TEST DEO KODA OKO KRETANJA */
explosions.draw(window);
base.draw(window);
manager.checkCollision(window, &explosions, &defManager);
manager.draw(window); //crta rakete
defManager.draw(window);
manager.checkBounds();
//manager.printActive();
window->display();
sf::Time t = clock.getElapsedTime();
clock.restart().asSeconds();
}
|
de3d307a6f16e05d6f180b02f073ad3f04cbf814
|
68409a9b920f7c5924bf6ed1974b0c20d80f279f
|
/Game.h
|
bca835015f1490ae78a3558a6f110206743bdcd1
|
[] |
no_license
|
love-ziji/Sokoban
|
ec5440b3baadbcf6e94ff22853bd3aede655ad40
|
e3c8d9dd1329ca8d0cdac2fb2fe34021a266a468
|
refs/heads/master
| 2022-12-21T20:07:10.920703
| 2020-09-23T01:31:32
| 2020-09-23T01:31:32
| 297,818,369
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 363
|
h
|
Game.h
|
#define _GAEM_H__
#ifdef _GAEM_H__
#include <iostream>
using namespace std;
#include <conio.h>
#define M 10
#define N 11
class Game
{
public:
int Move(int map[M][N], int ch);
void Draw(int map[M][N], int c);
int Judge(int map[M][N]);
private:
int Push(int map[M][N], int offsetX, int offsetY);
void Postion(int map[M][N]);
int posX;
int posY;
};
#endif
|
ef6a9bd86a2bbcde7b5f49123933f5d5a81686cd
|
7d64e03e403eca85248677d8dc72751c93940e48
|
/src/engine/leveldb/MojDbLevelTxnIterator.cpp
|
142421f557563d34a3e3fec49f2a39f792a68875
|
[
"Apache-2.0"
] |
permissive
|
webosce/db8
|
a6f6ec64d3cb8653dc522ee7a3e8fad78fcc0203
|
994da8732319c6cafc59778eec5f82186f73b6ab
|
refs/heads/webosce
| 2023-05-13T15:18:39.562208
| 2018-08-23T08:51:14
| 2018-09-14T13:30:43
| 145,513,369
| 0
| 1
|
Apache-2.0
| 2023-04-26T02:43:57
| 2018-08-21T05:52:45
|
C++
|
UTF-8
|
C++
| false
| false
| 9,619
|
cpp
|
MojDbLevelTxnIterator.cpp
|
// Copyright (c) 2013-2018 LG Electronics, 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.
//
// SPDX-License-Identifier: Apache-2.0
#include "engine/leveldb/MojDbLevelTxnIterator.h"
#include "engine/leveldb/MojDbLevelEngine.h"
#include "engine/leveldb/MojDbLevelTxn.h"
namespace {
inline bool operator<(const leveldb::Slice &a, const leveldb::Slice &b)
{ return a.compare(b) < 0; }
inline bool operator>(const leveldb::Slice &a, const leveldb::Slice &b)
{ return a.compare(b) > 0; }
enum Order { LT = -1, EQ = 0, GT = 1 };
Order compare(const MojDbLevelIterator &x, const MojDbLevelContainerIterator &y)
{
const bool xb = x.isBegin(),
xe = x.isEnd(),
yb = y.isBegin(),
ye = y.isEnd();
if ((xb && yb) || (xe && ye)) return EQ;
if (xb || ye) return LT;
if (xe || yb) return GT;
int r = x->key().ToString().compare(y->first);
return r < 0 ? LT :
r > 0 ? GT :
EQ ;
}
}
std::string string_to_hex(const std::string& input)
{
static const char* const lut = "0123456789ABCDEF";
size_t len = input.length();
std::string output;
output.reserve(2 * len);
for (size_t i = 0; i < len; ++i)
{
const unsigned char c = input[i];
output.push_back(lut[c >> 4]);
output.push_back(lut[c & 15]);
}
return output;
}
MojDbLevelTxnIterator::MojDbLevelTxnIterator(MojDbLevelTableTxn *txn) :
inserts(txn->m_pendingValues),
deletes(txn->m_pendingDeletes),
leveldb(txn->m_db),
m_it(leveldb),
m_insertsItertor (inserts),
m_txn(txn)
{
MojAssert( txn );
// set iterator to first element
first();
}
MojDbLevelTxnIterator::~MojDbLevelTxnIterator()
{
if (m_txn) m_txn->detach(this);
}
void MojDbLevelTxnIterator::detach()
{
MojAssert( m_txn );
m_txn = 0;
}
void MojDbLevelTxnIterator::notifyPut(const leveldb::Slice &key)
{
// Idea here is to re-align our transaction iterator if new key is in range
// of keys where database iterator and transaction iterator points to.
// Need to take care of next cases:
// 1) going forward: m_it->key() <= key < m_insertsItertor->first
// 2) going backward: m_insertIterator->first < key <= m_it->key()
// lets see in which relations we are with leveldb iterator
bool keyLtDb; // key < m_it->key()
bool keyEqDb; // key == m_it->key()
if (m_it.isBegin()) keyLtDb = false, keyEqDb = false;
else if (m_it.isEnd()) keyLtDb = true, keyEqDb = false;
else
{
keyLtDb = key < m_it->key();
keyEqDb = key == m_it->key();
}
// lets see in which relations we are with transaction iterator
bool keyLtTxn;
bool keyEqTxn;
if (m_insertsItertor.isBegin()) keyLtTxn = false, keyEqTxn = false;
else if (m_insertsItertor.isEnd()) keyLtTxn = true, keyEqTxn = false;
else
{
keyLtTxn = key < m_insertsItertor->first;
keyEqTxn = key == m_insertsItertor->first;
}
if (m_fwd)
{
// exclude case: key < db || txn <= key
if (keyLtDb || !keyLtTxn) return;
--m_insertsItertor; // set to a new key
}
else
{
// exclude case: key <= txn || db < key
if (keyLtTxn || keyEqTxn || (!keyLtDb && !keyEqDb)) return;
++m_insertsItertor; // set to a new key
}
}
void MojDbLevelTxnIterator::notifyDelete(const leveldb::Slice &key)
{
// if no harm for txn iterator - nothing to do
if (!m_insertsItertor.isValid()) return;
if (m_insertsItertor->first != key) return;
if (m_fwd)
{
MojAssert( !isBegin() );
switch (compare(m_it, m_insertsItertor))
{
case EQ:
++m_it; skipDeleted();
++m_insertsItertor;
break;
default: MojAssert( !"happens" );
case GT:
case LT:
++m_insertsItertor;
break;
}
}
else
{
MojAssert( !isEnd() );
switch (compare(m_it, m_insertsItertor))
{
case EQ:
--m_it; skipDeleted();
--m_insertsItertor;
break;
default: MojAssert( !"happens" );
case GT:
case LT:
--m_insertsItertor;
break;
}
}
m_invalid = true;
}
void MojDbLevelTxnIterator::skipDeleted()
{
if (m_fwd) {
while (!m_it.isEnd() && isDeleted(m_it->key().ToString())) {
++m_it;
}
} else {
while (!m_it.isBegin() && isDeleted(m_it->key().ToString())) {
--m_it;
}
}
}
bool MojDbLevelTxnIterator::inTransaction() const
{
// Note that in case when both iterators points to the records with same
// key we prefer to take one from transaction
switch( compare(m_it, m_insertsItertor) )
{
case LT: return !m_fwd;
case GT: return m_fwd;
case EQ: return true;
default: MojAssert( !"happens" );
}
return true;
}
std::string MojDbLevelTxnIterator::getValue()
{
if (inTransaction())
return m_insertsItertor->second;
else
return m_it->value().ToString();
}
const std::string MojDbLevelTxnIterator::getKey() const
{
if (inTransaction())
return m_insertsItertor->first;
else
return m_it->key().ToString();
}
bool MojDbLevelTxnIterator::keyStartsWith(const std::string& key) const
{
std::string currentKey = getKey();
if (key.size() > currentKey.size())
return false;
return std::mismatch(key.begin(), key.end(), currentKey.begin()).first == key.end();
}
void MojDbLevelTxnIterator::first()
{
m_fwd = true;
m_invalid = false;
m_it.toFirst();
m_insertsItertor.toFirst();
skipDeleted();
}
void MojDbLevelTxnIterator::last()
{
m_fwd = false;
m_invalid = false;
m_it.toLast();
m_insertsItertor.toLast();
skipDeleted();
}
bool MojDbLevelTxnIterator::isValid() const
{
return !m_invalid && (m_it.isValid() || m_insertsItertor.isValid());
}
bool MojDbLevelTxnIterator::isDeleted(const std::string& key) const
{
return ( deletes.find(key) != deletes.end() );
}
void MojDbLevelTxnIterator::prev()
{
MojAssert( !isBegin() );
if (isEnd()) return last();
if (m_fwd) {
const std::string ¤tKey = getKey();
m_fwd = false;
m_invalid = false;
// after switching direction we may end up with one of the iterators
// pointing to one of the tails
if (m_it.isEnd()) { --m_it; skipDeleted(); }
else if (m_insertsItertor.isEnd()) --m_insertsItertor;
else
{
if (currentKey < getKey()) prev();
}
MojAssert( getKey() == currentKey );
}
else if (m_invalid)
{
// we already jumped here from deleted record
m_invalid = false;
return;
}
if (m_insertsItertor.isBegin()) {
--m_it;
skipDeleted();
return;
}
if (m_it.isBegin()) {
--m_insertsItertor;
return;
}
MojAssert( !m_it.isEnd() );
MojAssert( !m_insertsItertor.isEnd() );
if (m_it->key().ToString() > m_insertsItertor->first) {
--m_it;
skipDeleted();
} else if (m_it->key().ToString() == m_insertsItertor->first) {
// advance both iterators to the next key value
--m_insertsItertor;
--m_it;
skipDeleted();
} else {
--m_insertsItertor;
}
}
void MojDbLevelTxnIterator::next()
{
MojAssert( !isEnd() );
if (isBegin()) return first();
if (!m_fwd) {
const std::string ¤tKey = getKey();
m_fwd = true;
m_invalid = false;
// after switching direction we may end up with one of the iterators
// pointing to one of the tails
if (m_it.isBegin()) { ++m_it; skipDeleted(); }
else if (m_insertsItertor.isBegin()) ++m_insertsItertor;
else
{
if (getKey() < currentKey) next();
}
MojAssert( getKey() == currentKey );
}
else if (m_invalid)
{
// we already jumped here from deleted record
m_invalid = false;
return;
}
m_invalid = false;
if (m_insertsItertor.isEnd()) {
++m_it;
skipDeleted();
return;
}
if (m_it.isEnd()) {
++m_insertsItertor;
return;
}
MojAssert( !m_it.isBegin() );
MojAssert( !m_insertsItertor.isBegin() );
if (m_it->key().ToString() < m_insertsItertor->first) {
++m_it;
skipDeleted();
} else if (m_it->key().ToString() == m_insertsItertor->first) {
// advance both iterators to the next key value
++m_insertsItertor;
++m_it;
skipDeleted();
} else {
++m_insertsItertor;
}
}
void MojDbLevelTxnIterator::seek(const std::string& key)
{
m_fwd = true;
m_invalid = false;
m_it.seek(key);
skipDeleted();
m_insertsItertor = inserts.lower_bound(key);
}
leveldb::Status MojDbLevelTxnIterator::status() const
{
return m_it->status();
}
|
c9f3c87c915666343f75efdf784bebc3d351ac76
|
71a89138623598a878ffb0e8d4d12e778cd7969f
|
/src/TCCalibCBTimeWalk.cxx
|
8aefc6d2c82545b8187d6f0aa26ad703d58ada57
|
[] |
no_license
|
werthm/CaLib
|
e72c5af06d7dc36379fe83ca06e5a0dc463fc945
|
78822c30f021ded75dd59114ff3ccd577cd20f5f
|
refs/heads/master
| 2021-01-17T10:09:08.642995
| 2019-11-27T16:38:40
| 2019-11-27T16:38:40
| 15,238,984
| 0
| 2
| null | 2014-12-20T12:05:27
| 2013-12-16T22:28:15
|
C++
|
UTF-8
|
C++
| false
| false
| 14,540
|
cxx
|
TCCalibCBTimeWalk.cxx
|
/*************************************************************************
* Author: Irakli Keshelashvili, Dominik Werthmueller, Thomas Strub
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TCCalibCBTimeWalk //
// //
// Calibration module for the CB time walk. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TH1.h"
#include "TH2.h"
#include "TGraphErrors.h"
#include "TF1.h"
#include "TCLine.h"
#include "TCanvas.h"
#include "TMath.h"
#include "TSystem.h"
#include "TCCalibCBTimeWalk.h"
#include "TCConfig.h"
#include "TCMySQLManager.h"
#include "TCFileManager.h"
#include "TCReadConfig.h"
#include "TCUtils.h"
ClassImp(TCCalibCBTimeWalk)
//______________________________________________________________________________
TCCalibCBTimeWalk::TCCalibCBTimeWalk()
: TCCalib("CB.TimeWalk", "CB time walk calibration", "Data.CB.Walk.Par0", TCConfig::kMaxCB)
{
// Empty constructor.
// init members
fFileManager = 0;
fPar0 = 0;
fPar1 = 0;
fPar2 = 0;
fPar3 = 0;
fGFitPoints = 0;
fTimeProj = 0;
fLine = 0;
fDelay = 0;
fUseEnergyWeight = kTRUE;
fUsePointDensityWeight = kTRUE;
fWalkType = kDefault;
}
//______________________________________________________________________________
TCCalibCBTimeWalk::~TCCalibCBTimeWalk()
{
// Destructor.
if (fFileManager) delete fFileManager;
if (fPar0) delete [] fPar0;
if (fPar1) delete [] fPar1;
if (fPar2) delete [] fPar2;
if (fPar3) delete [] fPar3;
if (fGFitPoints) delete fGFitPoints;
if (fTimeProj) delete fTimeProj;
if (fLine) delete fLine;
}
//______________________________________________________________________________
void TCCalibCBTimeWalk::Init()
{
// Init the module.
// init members
fFileManager = new TCFileManager(fData.Data(), fCalibration.Data(), fNset, fSet);
fPar0 = new Double_t[fNelem];
fPar1 = new Double_t[fNelem];
fPar2 = new Double_t[fNelem];
fPar3 = new Double_t[fNelem];
fGFitPoints = 0;
fTimeProj = 0;
fLine = new TCLine();
fDelay = 0;
// configure line
fLine->SetLineColor(4);
fLine->SetLineWidth(3);
// get histogram name
if (!TCReadConfig::GetReader()->GetConfig("CB.TimeWalk.Histo.Fit.Name"))
{
Error("Init", "Histogram name was not found in configuration!");
return;
}
else fHistoName = *TCReadConfig::GetReader()->GetConfig("CB.TimeWalk.Histo.Fit.Name");
// get projection fit display delay
fDelay = TCReadConfig::GetReader()->GetConfigInt("CB.TimeWalk.Fit.Delay");
// init weigths
fUseEnergyWeight = kTRUE;
fUsePointDensityWeight = kTRUE;
// get correction type
TString* type = TCReadConfig::GetReader()->GetConfig("CB.TimeWalk.Type");
if (!type)
{
fWalkType = kDefault;
Info("Init", "Using default walk correction");
}
else
{
TString t(*type);
t.ToLower();
if (t == "default")
{
fWalkType = kDefault;
Info("Init", "Using default walk correction");
}
else if (t == "strub")
{
fWalkType = kStrub;
Info("Init", "Using Strub walk correction");
}
else
{
fWalkType = kDefault;
Info("Init", "Using default walk correction");
}
}
// read old parameters (only from first set)
TCMySQLManager::GetManager()->ReadParameters("Data.CB.Walk.Par0", fCalibration.Data(), fSet[0], fPar0, fNelem);
TCMySQLManager::GetManager()->ReadParameters("Data.CB.Walk.Par1", fCalibration.Data(), fSet[0], fPar1, fNelem);
TCMySQLManager::GetManager()->ReadParameters("Data.CB.Walk.Par2", fCalibration.Data(), fSet[0], fPar2, fNelem);
TCMySQLManager::GetManager()->ReadParameters("Data.CB.Walk.Par3", fCalibration.Data(), fSet[0], fPar3, fNelem);
// draw main histogram
fCanvasFit->Divide(1, 2, 0.001, 0.001);
fCanvasFit->cd(1)->SetLogz();
// draw the overview histogram
fCanvasResult->cd();
}
//______________________________________________________________________________
void TCCalibCBTimeWalk::Fit(Int_t elem)
{
// Perform the fit of the element 'elem'.
Char_t tmp[256];
// get configuration
Double_t lowLimit, highLimit;
TCReadConfig::GetReader()->GetConfigDoubleDouble("CB.TimeWalk.Histo.Fit.Xaxis.Range", &lowLimit, &highLimit);
// create histogram name
sprintf(tmp, "%s_%03d", fHistoName.Data(), elem);
// get histogram
if (!fIsReFit)
{
// delete old histogram
if (fMainHisto) delete fMainHisto;
// get new
fMainHisto = fFileManager->GetHistogram(tmp);
}
if (!fMainHisto)
{
Error("Fit", "Main histogram does not exist!");
return;
}
// draw main histogram
if (!fIsReFit)
{
if (fMainHisto->GetEntries() > 0) fCanvasFit->cd(1)->SetLogz(1);
else fCanvasFit->cd(1)->SetLogz(0);
TCUtils::FormatHistogram(fMainHisto, "CB.TimeWalk.Histo.Fit");
fMainHisto->Draw("colz");
fCanvasFit->Update();
}
// check for sufficient statistics
if (fMainHisto->GetEntries() < 1000 && !TCUtils::IsCBHole(elem))
{
Error("Fit", "Not enough statistics!");
return;
}
// copy old points
TGraphErrors oldp;
if (fIsReFit && fGFitPoints) oldp = TGraphErrors(*fGFitPoints);
// create new graph (fit data)
if (fGFitPoints) delete fGFitPoints;
fGFitPoints = new TGraphErrors();
fGFitPoints->SetMarkerStyle(20);
fGFitPoints->SetMarkerColor(kBlack);
// prepare stuff for adding
Double_t low_e = 0;
Int_t added = 0;
Double_t added_e = 0;
Double_t added_w = 0;
// get bins for fitting range
Int_t startBin = fMainHisto->GetXaxis()->FindBin(lowLimit);
Int_t endBin = fMainHisto->GetXaxis()->FindBin(highLimit);
// loop over energy bins
for (Int_t i = startBin; i <= endBin; i++)
{
// create time projection
sprintf(tmp, "ProjTime_%d_%d", elem, i);
TH1* proj = (TH1D*) ((TH2*) fMainHisto)->ProjectionY(tmp, i, i, "e");
// skip empty projections
if (proj->GetEntries() == 0)
{
delete proj;
continue;
}
// first loop (after fit)
if (added == 0)
{
low_e = fMainHisto->GetXaxis()->GetBinLowEdge(i);
if (fTimeProj) delete fTimeProj;
fTimeProj = (TH1*) proj->Clone("TimeProjection");
// reset values
added_e = 0;
added_w = 0;
}
else
{
fTimeProj->Add(proj);
}
// add up bin contribution
Double_t weight = fUseEnergyWeight ? proj->GetEntries() : 1.;
added_w += weight;
added_e += fMainHisto->GetXaxis()->GetBinCenter(i) * weight;
added++;
// delete projection
delete proj;
// calc energy interval
Double_t e_int = fMainHisto->GetXaxis()->GetBinUpEdge(i) - low_e;
// minimum energy interval
if (e_int < 0.5) continue;
// check if projection has enough entries
if (fTimeProj->GetEntries() < 300 && i < endBin)
continue;
// calculate mean energy
Double_t energy = added_e/added_w;
//
// fit time projection
//
// create fitting function
if (fFitFunc) delete fFitFunc;
sprintf(tmp, "fWalkProfile_%i", elem);
fFitFunc = new TF1(tmp, "gaus(0)");
fFitFunc->SetLineColor(kBlue);
// prepare fitting function
Int_t maxbin = fTimeProj->GetMaximumBin();
Double_t peak = fTimeProj->GetBinCenter(maxbin);
Double_t max = fTimeProj->GetMaximum();
// find old (changed) peak pos
Bool_t skip = kFALSE;
if (fIsReFit)
{
// init
skip = kTRUE;
// loop over old points
for (Int_t j = 0; j < oldp.GetN(); j++)
{
// find point
if (low_e < oldp.GetX()[j] && oldp.GetX()[j] < low_e+e_int)
{
skip = kFALSE;
peak = oldp.GetY()[j];
break;
}
}
}
// skip if no old (deleted) point found
if (skip)
{
added = 0;
continue;
}
// prepare fit
fFitFunc->SetRange(peak - 20, peak + 20);
fFitFunc->SetParameters(max, peak, 1.);
fFitFunc->SetParLimits(0, max*0.5, max*1.5); // peak height
fFitFunc->SetParLimits(1, peak - 5, peak + 5); // peak position
fFitFunc->SetParLimits(2, 0.5, 20.0); // sigma
// perform fit
fTimeProj->Fit(fFitFunc, "RBQ0");
// get parameters
Double_t mean = fFitFunc->GetParameter(1);
Double_t error = fFitFunc->GetParError(1);
// format line
fLine->SetPos(mean);
// check fit error
if (error < 1.)
{
Int_t n = fGFitPoints->GetN();
fGFitPoints->SetPoint(n, energy, mean);
fGFitPoints->SetPointError(n, 0., error);
}
// plot projection fit
if (fDelay > 0)
{
fCanvasFit->cd(2);
fTimeProj->GetXaxis()->SetRangeUser(mean - 30, mean + 30);
fTimeProj->Draw("hist");
fFitFunc->Draw("same");
fLine->Draw();
fCanvasFit->Update();
gSystem->Sleep(fDelay);
}
// reset value
added = 0;
} // for: loop over energy bins
//
// fit profile
//
// check for enough points
if (fGFitPoints->GetN() < 3)
{
Error("Fit", "Not enough fit points!");
return;
}
// create fitting function
sprintf(tmp, "fTWalk_%d", elem);
if (fFitFunc) delete fFitFunc;
if (fWalkType == kDefault)
fFitFunc = new TF1(tmp, "[0] + [1] / TMath::Power(x + [2], [3])", lowLimit, highLimit);
else if (fWalkType == kStrub)
fFitFunc = new TF1(tmp, "[0] + [1] / TMath::Power(x - 1, [3]) + x*[2]", lowLimit, highLimit);
fFitFunc->SetLineColor(kBlue);
fFitFunc->SetNpx(2000);
// weight point errors by point density
if (fUsePointDensityWeight)
{
for (Int_t i = 0; i < fGFitPoints->GetN(); i++)
{
Double_t* x = fGFitPoints->GetX();
//Double_t* y = fGFitPoints->GetY();
Double_t diff = 0.;
// get distance to previous point (use only x-coord)
if (i > 0)
{
Double_t xdiff = x[i]-x[i-1];
Double_t ydiff = 0;//y[i]-y[i-1];
diff += TMath::Sqrt(xdiff*xdiff + ydiff*ydiff);
}
// get distance to next point
if (i < fGFitPoints->GetN()-1)
{
Double_t xdiff = x[i+1]-x[i];
Double_t ydiff = 0;//y[i+1]-y[i];
diff += TMath::Sqrt(xdiff*xdiff + ydiff*ydiff);
}
// get mean distance
if (i > 0 && i < fGFitPoints->GetN()-1)
diff /= 2.;
// set new error = old error / sqrt(dist)
fGFitPoints->SetPointError(i, fGFitPoints->GetEX()[i], 1./TMath::Sqrt(diff) * fGFitPoints->GetEY()[i]);
}
}
// prepare fitting function
fFitFunc->SetParameters(-50, 60, 0.2, 0.3);
fFitFunc->SetParLimits(1, -5000, 5000);
if (fWalkType == kDefault)
fFitFunc->SetParLimits(2, -1, 10);
fFitFunc->SetParLimits(3, 0, 1);
// perform fit
for (Int_t i = 0; i < 10; i++)
if (!fGFitPoints->Fit(fFitFunc, "RB0Q")) break;
// read parameters
fPar0[elem] = fFitFunc->GetParameter(0);
fPar1[elem] = fFitFunc->GetParameter(1);
fPar2[elem] = fFitFunc->GetParameter(2);
fPar3[elem] = fFitFunc->GetParameter(3);
// draw energy projection and fit
fFitFunc->SetRange(-fFitFunc->GetParameter(2), 1000);
fCanvasResult->cd();
fGFitPoints->Draw("ap");
fGFitPoints->GetXaxis()->SetLimits(lowLimit, highLimit);
fFitFunc->Draw("same");
fCanvasResult->Update();
fCanvasFit->cd(1);
fFitFunc->Draw("same");
fCanvasFit->Update();
}
//______________________________________________________________________________
void TCCalibCBTimeWalk::Calculate(Int_t elem)
{
// Calculate the new value of the element 'elem'.
Bool_t noval = kFALSE;
// check no fits
if (fPar0[elem] == 0 && fPar1[elem] == 0 &&
fPar2[elem] == 0 && fPar3[elem] == 0) noval = kTRUE;
// user information
printf("Element: %03d Par0: %12.8f "
"Par1: %12.8f Par2: %12.8f Par3: %12.8f",
elem, fPar0[elem], fPar1[elem], fPar2[elem], fPar3[elem]);
if (noval) printf(" -> no fit");
if (TCUtils::IsCBHole(elem)) printf(" (hole)");
printf("\n");
}
//______________________________________________________________________________
void TCCalibCBTimeWalk::PrintValues()
{
// Print out the old and new values for all elements.
// loop over elements
for (Int_t i = 0; i < fNelem; i++)
{
printf("Element: %03d Par0: %12.8f "
"Par1: %12.8f Par2: %12.8f Par3: %12.8f\n",
i, fPar0[i], fPar1[i], fPar2[i], fPar3[i]);
}
}
//______________________________________________________________________________
void TCCalibCBTimeWalk::WriteValues()
{
// Write the obtained calibration values to the database.
// write values to database
for (Int_t i = 0; i < fNset; i++)
{
TCMySQLManager::GetManager()->WriteParameters("Data.CB.Walk.Par0", fCalibration.Data(), fSet[i], fPar0, fNelem);
TCMySQLManager::GetManager()->WriteParameters("Data.CB.Walk.Par1", fCalibration.Data(), fSet[i], fPar1, fNelem);
TCMySQLManager::GetManager()->WriteParameters("Data.CB.Walk.Par2", fCalibration.Data(), fSet[i], fPar2, fNelem);
TCMySQLManager::GetManager()->WriteParameters("Data.CB.Walk.Par3", fCalibration.Data(), fSet[i], fPar3, fNelem);
}
}
|
316421af20964abe12e5fbf5cd868964f5f43df4
|
c0ee175d7b02707a39a1a6895207749ee0e98694
|
/canvas.cpp
|
a74422f7ff91563689337306e4b8bfcc9eaaa009
|
[] |
no_license
|
dwipasawitra/simple-tetris
|
48ed4347cdf6148985f67a08f9078f6432df6907
|
00d48f7f4da300454c971a4c52fc9c98f10070e0
|
refs/heads/master
| 2020-12-24T13:35:40.085643
| 2013-01-16T19:42:25
| 2013-01-16T19:42:25
| 7,287,724
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,890
|
cpp
|
canvas.cpp
|
#include "canvas.h"
canvas::canvas(game *gameParent)
{
this->gameParent = gameParent;
this->gameBorder = load_bitmap("border.bmp", NULL);
// Initialize gameCanvasDraw
for(int i = 0; i < GAME_MAX_X; i++)
{
for(int j = 0; j < GAME_MAX_Y; j++)
{
this->gameCanvasDraw[i][j] = false;
}
}
}
canvas::~canvas()
{
// Destroy game border bitmap
destroy_bitmap(this->gameBorder);
}
void canvas::redrawGraphicAll()
{
int i, j;
// OLD INEFFICIENT ALGORITHM
for(i=0;i<GAME_MAX_X;i++)
{
for(j=0;j<GAME_MAX_Y;j++)
{
if(gameParent->gameBlock[i][j] != NULL)
{
this->drawBlock(i, j, gameParent->gameBlock[i][j]);
}
else
{
this->clearBlock(i, j);
}
}
}
}
void canvas::redrawGraphic()
{
// Redraw algorithm
// Check all matrix content
// Check if there is a block in graphic
//
// Yes: Keep it when matrix cell present
// Remove it when matrix cell doesn't present
// No: Draw it when matrix cell present
// Keep it when matrix cell doesn't present
int i, j;
for(i=0;i<GAME_MAX_X;i++)
{
for(j=0;j<GAME_MAX_Y;j++)
{
if(this->checkPoint(i, j))
{
if(gameParent->gameBlock[i][j] == NULL)
{
this->clearBlock(i, j);
}
}
else
{
if(gameParent->gameBlock[i][j] != NULL)
{
this->drawBlock(i, j, gameParent->gameBlock[i][j]);
}
}
}
}
}
void canvas::drawBlock(int x, int y, block *property)
{
// Save the state into gameCanvasDraw matrices
this->gameCanvasDraw[x][y] = true;
int drawPointX, drawPointY;
int blockColor;
// If Y-axis is 0 to 3, you can't draw it
if(y>=0 && y<=3)
{
return;
}
else
{
y = y-4;
}
// drawPoint = Left top point of each block
drawPointX = (20*x) + GAME_CANVAS_START_X;
drawPointY = (20*y) + GAME_CANVAS_START_Y;
// From left top point, draw the image
blit(property->getImage(), screen, 0, 0, drawPointX, drawPointY, 20, 20);
}
void canvas::clearBlock(int x, int y)
{
int drawPointX, drawPointY;
// Save the state into gameCanvasDraw matrices
this->gameCanvasDraw[x][y] = false;
// If Y-axis is 0 to 3, you can't draw it
if(y>=0 && y<=3)
{
return;
}
else
{
y = y-4;
}
// drawPoint = left top point of each block
drawPointX = (20*x) + GAME_CANVAS_START_X;
drawPointY = (20*y) + GAME_CANVAS_START_Y;
// From left top point, draw background in that position
blit(gameParent->background, screen, drawPointX, drawPointY, drawPointX, drawPointY, 20, 20);
// Done
}
// Unused because efficient redraw algorith hadn't implemented yet
/*
bool canvas::checkPoint(int x, int y)
{
int checkPointX, checkPointY;
// If Y-axis is 0 to 3, you can't draw it
if(y>=0 && y<=3)
{
return 1;
}
else
{
y = y-4;
}
// checkPoint = Center point of each block
checkPointX = (20*x+10) + GAME_CANVAS_START_X;
checkPointY = (20*y+10) + GAME_CANVAS_START_Y;
// Check current property on that block
return is_inside_bitmap(gameParent->background, checkPointX, checkPointY, 0);
}
*/
bool canvas::checkPoint(int x, int y)
{
return this->gameCanvasDraw[x][y];
}
void canvas::redrawBorder()
{
blit(gameBorder, screen, 0, 0, 10, 10, 340, 460);
blit(gameParent->background, screen, 20, 20, 20, 20, 320, 440);
}
|
5af991144ea4f5dff00fea530e3cc5b83f1a57f5
|
a4af8baee721e7c3610688a6e68586d839095c70
|
/cpp_cookbook/ch_8/8_12.h
|
0853e510f90f924f1f452529d808890ede4e187f
|
[] |
no_license
|
timothyshull/cpp_scratchpad_old
|
0b086916a6b93189d842f89806428976925ecc2b
|
f670085fa92b8cf4b911a522f88d75d7cc6a759b
|
refs/heads/master
| 2021-01-22T20:34:31.008988
| 2017-03-17T15:52:41
| 2017-03-17T15:52:41
| 85,329,261
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 330
|
h
|
8_12.h
|
//
// Created by Timothy Shull on 12/25/15.
//
#ifndef CPP_COOKBOOK_8_12_H
#define CPP_COOKBOOK_8_12_H
class ObjectManager {
public:
template<typename T>
T* gimmeAnObject();
template<typename T>
void gimmeAnObject(T*& p);
};
class X {
};
class Y {
};
void testMemberTemplate();
#endif //CPP_COOKBOOK_8_12_H
|
bdf2b10aa507c58b6839e2864a07ea0e980df832
|
ece914fa59ce3be64b4b01a123b588776635633e
|
/6/src/myproject/Polynomial.h
|
62c33183407b8ae3972fbf2ea6eba78c327a7029
|
[] |
no_license
|
HronoSF/SP_2019
|
073902d15d68b75e946e16197f534b0e89fe0620
|
d3af94ad23914eafdf07d4f6ad2e1a119908633c
|
refs/heads/master
| 2020-08-08T03:53:15.684349
| 2020-01-21T17:26:28
| 2020-01-21T17:26:28
| 213,702,730
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,021
|
h
|
Polynomial.h
|
#include <complex>
#include <memory>
template<class T>
class Polynomial {
private:
std::unique_ptr<T[]> array; // array[0] = a(n), array[size-1] = a(0)
int size;
template<class Arg>
void setArgs(int place, Arg head) {
array[place] = head;
}
template<class Arg>
void setArgs(int place, Arg head, Arg tail) {
array[place] = head;
array[place + 1] = tail;
}
template<class Head, class ... Args>
void setArgs(int place, Head head, Args ... tail) {
array[place] = head;
voidSetArgs(place + 1, tail...);
}
public:
explicit Polynomial() = delete;
Polynomial(const Polynomial &) = delete;
Polynomial(Polynomial &&data) : array(std::move(data.array)) {
size = data.size;
}
Polynomial &operator=(Polynomial &&data) {
size = std::move(data.size);
array = std::move(data.array);
return *this;
}
~Polynomial() = default;
template<class ... Args>
Polynomial(T head, Args ... args): array(new T[sizeof...(args) + 1]{std::forward<Args>(args)...}) {
size = sizeof...(args) + 1;
array[0] = head;
setArgs(1, args...);
}
Polynomial(T *arr, int size) {
array.reset(arr);
std::swap(this->size, size);
}
int getSize() const {
return size;
}
void multiply(T x) {
for (int i = 0; i < size; i++) {
array[i] = array[i] * x;
}
}
T getArg(int place) const {
return array[place];
}
};
template<typename T>
struct is_complex_t : public std::false_type {
};
template<typename T>
struct is_complex_t<std::complex<T>> : public std::true_type {
};
template<typename T>
constexpr bool is_complex() { return is_complex_t<T>::value; }
template<class T>
typename std::enable_if<std::is_arithmetic<T>::value, Polynomial<T>>::type
schurTransform(Polynomial<T> &p) {
int size = p.getSize();
T *array = new T[size];
for (int i = 0; i < size; i++) {
array[i] = p.getArg(size - 1 - i);
}
Polynomial<T> reciprocal = std::move(Polynomial<T>(array, size));
reciprocal.multiply(p.getArg(0));
p.multiply(p.getArg(p.getSize() - 1));
T *schurArray = new T[size];
for (int k = 0; k < size; k++) {
schurArray[k] = p.getArg(k) - reciprocal.getArg(k);
}
return std::move(Polynomial<T>(schurArray, size));
}
template<class T>
typename std::enable_if<is_complex_t<T>::value, Polynomial<T>>::type
schurTransform(Polynomial<T> &p) {
int size = p.getSize();
T *array = new T[size];
for (int i = 0; i < size; i++) {
array[i] = std::conj(p.getArg(size - 1 - i));
}
Polynomial<T> reciprocal(Polynomial<T>(array, size));
reciprocal.multiply(p.getArg(0));
p.multiply(std::conj(p.getArg(p.getSize() - 1)));
T *schurArray = new T[size];
for (int k = 0; k < size; k++) {
schurArray[k] = p.getArg(k) - reciprocal.getArg(k);
}
return Polynomial<T>(schurArray, size);
}
|
1e9fbee4ea9d2034ce2d367b240972adffe8d482
|
e8be5e13152f1ccfece36ba47569614a87842d96
|
/GameSanGuo/GameSanGuo/Classes/game/main/first/Lottery9View/SGLandingReward.h
|
255bfdc1f7d19f2530fc1fbdea44a7742da84501
|
[] |
no_license
|
Crasader/warCraft
|
571ed9a3181b0eb52940cdd2965b7445c004d58f
|
b9cf69828c61bdf55b2af3b587f3be06de93768c
|
refs/heads/master
| 2020-12-13T18:05:17.592831
| 2016-01-19T13:42:19
| 2016-01-19T13:42:19
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,418
|
h
|
SGLandingReward.h
|
//
// SGLandingReward.h
// GameSanGuo
//
// Created by 陈雪龙 on 13-4-8.
//
//
#ifndef __GameSanGuo__SGLandingReward__
#define __GameSanGuo__SGLandingReward__
#include "SGBaseLayer.h"
#include "SGBoxDelegate.h"
class SGLandingReward : public SGBaseLayer
{
private:
int state;
SGButton *uncard;
SGButton *enterGame;
int currChance;
int btntag;
int chanceTag[9];
int tempTag;
int logindays;
int chances;
SGCCLabelTTF *label1;
CCArray *tagArray;
SGButton *tempBtn;
CCSprite *tempBg;
SGButton *AllBtn;
void testFlipCardCallFunc1();
void testFlipCardCallFunc2();
void testFlipCardCallFunc3(CCNode *node);
void testFlipCardCallFunc4(CCNode *node);
void testeffect(CCNode *node);
void sortLandingButton();
protected:
SGBoxDelegate *deletage;
protected:
void initView(SGBoxDelegate *dg);
void confirmHandler(CCNode *sender);
void lotteryListener(CCObject *obj);
virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent);
virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent);
virtual void onEnter();
virtual void onExit();
public:
SGLandingReward();
~SGLandingReward();
static SGLandingReward *create(SGBoxDelegate *dg);
void showCard();
void boxCloseWithOutCallBack();
};
#endif /* defined(__GameSanGuo__SGLandingReward__) */
|
1c1af7b0343c109a98778e27e2a47dc4595bf775
|
f75348d6c688d97a597b8460224ba8c693357ff0
|
/win32/ATL7/ImageMagickObject/ImageMagickObject.cpp
|
d40fe262ca2b1af5544fe28b3f22e6dc51d60eed
|
[] |
no_license
|
ImageMagick/contrib
|
5c5a5b8a87e3dd2c1cb41c4aee58b20cb73ef998
|
2b0f77d1c4b0cba537dd4662025abdad5857c9e4
|
refs/heads/main
| 2023-08-11T04:30:35.457144
| 2018-04-04T00:15:38
| 2018-04-04T00:15:38
| 36,986,741
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 46,224
|
cpp
|
ImageMagickObject.cpp
|
/*
ImageMagickObject.cpp
*/
#include "ImageMagickObject_.h"
static const DWORD dwErrorBase = 5000;
static const int nDefaultArgumentSize = 128;
static const LCID lcidDefault = 0;
static const int DEF_DEBUG_MODE = _CRTDBG_MODE_DEBUG;
// for logging
static const char objName[] = "ImageMagickObject";
static const char methodName[] = "Perform";
// xtrnarray
static const TCHAR xtrnarray_fmt[] = _T("xtrnarray:%p,%ws");
[module(dll, name = "ImageMagickObject", helpstring = "ImageMagickObject 1.0 Type Library")]
class CModuelOverrideClass
{
private:
TCHAR m_szAppPath[MAX_PATH];
public:
BOOL WINAPI DllMain(
DWORD dwReason,
LPVOID lpReserved
)
{
//ATLASSERT( FALSE );
if (dwReason == DLL_PROCESS_ATTACH)
{
MagickCore::ExceptionInfo
*exception;
#ifdef _DEBUG
int tmpDbgFlag;
#endif
HINSTANCE hModuleInstance = _AtlBaseModule.GetModuleInstance();
HINSTANCE hMResourceInstance = _AtlBaseModule.GetResourceInstance();
if (!GetModuleFileName(hModuleInstance, m_szAppPath, MAX_PATH))
{
return FALSE;
}
#ifdef _DEBUG
tmpDbgFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
tmpDbgFlag |= _CRTDBG_CHECK_ALWAYS_DF;
//tmpDbgFlag |= _CRTDBG_DELAY_FREE_MEM_DF;
tmpDbgFlag |= _CRTDBG_LEAK_CHECK_DF;
tmpDbgFlag |= _CRTDBG_ALLOC_MEM_DF;
_CrtSetDbgFlag(tmpDbgFlag);
_CrtSetReportMode(_CRT_ASSERT, DEF_DEBUG_MODE);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG);
_CrtSetReportMode(_CRT_ERROR, DEF_DEBUG_MODE);
#endif
CT2AEX<MAX_PATH> app_path(m_szAppPath);
MagickCore::MagickCoreGenesis(app_path, MagickCore::MagickFalse);
}
else if (dwReason == DLL_PROCESS_DETACH)
{
CT2AEX<MAX_PATH> app_path(m_szAppPath);
(void)MagickCore::LogMagickEvent(MagickCore::ResourceEvent, GetMagickModule(),
"DLL Detach - path: %s", (const char *) app_path);
MagickCore::MagickCoreTerminus();
#ifdef _DEBUG
if (_CrtDumpMemoryLeaks())
{
/* MagickCore::DebugString("ImageMagickObject - DLL Detach - leaks detected\n"); */
}
#endif
}
return __super::DllMain(dwReason, lpReserved);
}
};
[emitidl];
/////////////////////////////////////////////////////////////////////////////
// IMagickImage
[
object,
uuid("7F670536-00AE-4EDF-B06F-13BD22B25624"),
dual,
helpstring("IMagickImage Interface"),
pointer_default(unique)
]
__interface IMagickImage : IDispatch
{
//Standard Server Side Component Methods
HRESULT OnStartPage([in] IUnknown * piUnk);
HRESULT OnEndPage();
[propget, id(1)] HRESULT Count([out, retval] long* pVal);
[vararg, id(2)] HRESULT Add([in, out, satype(VARIANT)] SAFEARRAY * *pArrayVar, [out, retval] VARIANT * pVar);
[id(3)] HRESULT Remove([in] VARIANT varIndex);
[vararg, id(4)] HRESULT Compare([in, out, satype(VARIANT)] SAFEARRAY * *pArrayVar, [out, retval] VARIANT * pVar);
[vararg, id(5)] HRESULT Composite([in, out, satype(VARIANT)] SAFEARRAY * *pArrayVar, [out, retval] VARIANT * pVar);
[vararg, id(6)] HRESULT Convert([in, out, satype(VARIANT)] SAFEARRAY * *pArrayVar, [out, retval] VARIANT * pVar);
[vararg, id(7)] HRESULT Identify([in, out, satype(VARIANT)] SAFEARRAY * *pArrayVar, [out, retval] VARIANT * pVar);
[vararg, id(8)] HRESULT Mogrify([in, out, satype(VARIANT)] SAFEARRAY * *pArrayVar, [out, retval] VARIANT * pVar);
[vararg, id(9)] HRESULT Montage([in, out, satype(VARIANT)] SAFEARRAY * *pArrayVar, [out, retval] VARIANT * pVar);
[vararg, id(10)] HRESULT Stream([in, out, satype(VARIANT)] SAFEARRAY * *pArrayVar, [out, retval] VARIANT * pVar);
[vararg, id(11)] HRESULT TestHarness([in, out, satype(VARIANT)] SAFEARRAY * *pArrayVar, [out, retval] VARIANT * pVar);
[propget, id(DISPID_NEWENUM)] HRESULT _NewEnum([out, retval] LPUNKNOWN * pVal);
[propget, id(DISPID_VALUE)] HRESULT Item([in] VARIANT varIndex, [out, retval] VARIANT * pVal);
[propget, id(14)] HRESULT Messages([out, retval] VARIANT * pVal);
};
class MagickImageError
{
public:
MagickCore::ExceptionInfo *exception;
bool fullException;
DWORD fullExceptionCode;
public:
MagickImageError()
{
fullException = FALSE;
fullExceptionCode = 0;
exception = MagickCore::AcquireExceptionInfo();
}
void Cleanup()
{
if (exception != (MagickCore::ExceptionInfo *) NULL)
exception = MagickCore::DestroyExceptionInfo(exception);
}
static LPCSTR translate_exception(DWORD);
LPCSTR translate_exception() const
{
return translate_exception(fullExceptionCode);
}
};
/////////////////////////////////////////////////////////////////////////////
// MagickImage
[
coclass,
threading(both),
support_error_info("IMagickImage"),
vi_progid("ImageMagickObject.MagickImage"),
progid("ImageMagickObject.MagickImage.1"),
version(1.0),
uuid("5630BE5A-3F5F-4BCA-A511-AD6A6386CAC1"),
helpstring("MagickImage Class")
]
class ATL_NO_VTABLE MagickImage :
public IObjectControl,
public IObjectConstruct,
public ISupportErrorInfoImpl<&__uuidof(IMagickImage)>,
public IObjectWithSiteImpl<MagickImage>,
public IMagickImage
{
public:
MagickImage()
{
#ifdef _DEBUG
//ATLASSERT( FALSE );
#endif
MagickCore::SetWarningHandler(warninghandler);
MagickCore::SetErrorHandler(errorhandler);
MagickCore::SetFatalErrorHandler(fatalerrorhandler);
(void)MagickCore::LogMagickEvent(MagickCore::ResourceEvent, GetMagickModule(),
"MagickImage constructor");
m_bOnStartPageCalled = FALSE;
}
private:
HRESULT TestHarness(
SAFEARRAY** pArrayVar,
VARIANT* pVar
);
HRESULT Compare(
SAFEARRAY** pArrayVar,
VARIANT* pVar
);
HRESULT Composite(
SAFEARRAY** pArrayVar,
VARIANT* pVar
);
HRESULT Convert(
SAFEARRAY** pArrayVar,
VARIANT* pVar
);
HRESULT Identify(
SAFEARRAY** pArrayVar,
VARIANT* pVar
);
HRESULT Mogrify(
SAFEARRAY** pArrayVar,
VARIANT* pVar
);
HRESULT Montage(
SAFEARRAY** pArrayVar,
VARIANT* pVar
);
HRESULT Stream(
SAFEARRAY** pArrayVar,
VARIANT* pVar
);
HRESULT Execute(
MagickCore::MagickBooleanType(*func)(MagickCore::ImageInfo* image_info, const int argc, char** argv, char** text, MagickCore::ExceptionInfo* exception),
char** text,
MagickCore::ImageInfo * info,
MagickCore::ExceptionInfo * exception
);
HRESULT Perform(
MagickCore::MagickBooleanType(*func)(MagickCore::ImageInfo* image_info, const int argc, char** argv, char** text, MagickCore::ExceptionInfo* exception),
SAFEARRAY * *pArrayVar,
VARIANT * pVar2,
MagickCore::ExceptionInfo * exception
);
private:
LPSTR* m_argv;
int m_argc;
int m_argvIndex;
HRESULT AllocateArgs(
int iArgs
);
HRESULT ReAllocateArgs(
int iArgs
);
void DeleteArgs(
void
);
char** GetArgv(
void
);
int GetArgc(
void
);
void EmptyArgs(
void
);
HRESULT AddArgs(LPCWSTR);
HRESULT AddArgs(LPCSTR);
private:
static void warninghandler(
const MagickCore::ExceptionType warning,
const char* message,
const char* qualifier
);
static void errorhandler(
const MagickCore::ExceptionType error,
const char* message,
const char* qualifier
);
static void fatalerrorhandler(
const MagickCore::ExceptionType error,
const char* message,
const char* qualifier
);
static void CheckAndReportError(
MagickImageError& error,
HRESULT& hr,
const char* program
);
static void GetXtrnArrayStr(CString&, const SAFEARRAY*, LPCWSTR);
static void GetXtrnArrayStr(CString&, const SAFEARRAY*);
public:
DECLARE_PROTECT_FINAL_CONSTRUCT()
HRESULT FinalConstruct()
{
(void)MagickCore::LogMagickEvent(MagickCore::ResourceEvent, GetMagickModule(),
"FinalConstruct");
AllocateArgs(nDefaultArgumentSize);
//MagickCore::MagickCoreGenesis(NULL);
return S_OK;
}
void FinalRelease()
{
(void)MagickCore::LogMagickEvent(MagickCore::ResourceEvent, GetMagickModule(),
"FinalRelease");
DeleteArgs();
}
// Support for ASP page notifications methods
public:
//Active Server Pages Methods
STDMETHOD(OnStartPage) (IUnknown * IUnk);
STDMETHOD(OnEndPage) ();
STDMETHOD(get_Item) ( /*[in]*/ VARIANT varIndex, /*[out, retval]*/ VARIANT * pVar);
STDMETHOD(get__NewEnum) ( /*[out, retval]*/ LPUNKNOWN * pVal);
STDMETHOD(get_Count) ( /*[out, retval]*/ long* pVal);
STDMETHOD(get_Messages) ( /*[out, retval]*/ VARIANT * pVar);
STDMETHOD(Remove) ( /*[in]*/ VARIANT varIndex);
STDMETHOD(Add) ( /*[in,out]*/ SAFEARRAY * *pArrayVar, /*[out, retval]*/ VARIANT * pVar);
private:
CComPtr<IRequest>m_piRequest; //Request Object
CComPtr<IResponse>m_piResponse; //Response Object
CComPtr<ISessionObject>m_piSession; //Session Object
CComPtr<IServer>m_piServer; //Server Object
CComPtr<IApplicationObject>m_piApplication; //Application Object
BOOL m_bOnStartPageCalled; //OnStartPage successful?
CComPtr<IObjectContext> m_spObjectContext;
public:
// Support for COM+ activation and deactivation
STDMETHOD(Activate) ();
STDMETHOD_(BOOL, CanBePooled) ();
STDMETHOD_(void, Deactivate) ();
STDMETHOD(Construct) (IDispatch * pCtorObj);
};
LPCSTR MagickImageError::translate_exception(DWORD code)
{
switch (code)
{
case EXCEPTION_ACCESS_VIOLATION:
return "access violation";
case EXCEPTION_DATATYPE_MISALIGNMENT:
return "data misalignment";
case EXCEPTION_BREAKPOINT:
return "debug breakpoint";
case EXCEPTION_SINGLE_STEP:
return "debug single step";
case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
return "array out of bounds";
case EXCEPTION_FLT_DENORMAL_OPERAND:
return "float denormal operand";
case EXCEPTION_FLT_DIVIDE_BY_ZERO:
return "float devide by zero";
case EXCEPTION_FLT_INEXACT_RESULT:
return "float inexact result";
case EXCEPTION_FLT_INVALID_OPERATION:
return "float invalid operation";
case EXCEPTION_FLT_OVERFLOW:
return "float overflow";
case EXCEPTION_FLT_STACK_CHECK:
return "float stack check";
case EXCEPTION_FLT_UNDERFLOW:
return "float underflow";
case EXCEPTION_INT_DIVIDE_BY_ZERO:
return "integer divide by zero";
case EXCEPTION_INT_OVERFLOW:
return "integer overflow";
case EXCEPTION_PRIV_INSTRUCTION:
return "privleged instruction";
case EXCEPTION_IN_PAGE_ERROR:
return "page error";
case EXCEPTION_ILLEGAL_INSTRUCTION:
return "illegal instruction";
case EXCEPTION_NONCONTINUABLE_EXCEPTION:
return "noncontinuable instruction";
case EXCEPTION_STACK_OVERFLOW:
return "stack overflow";
case EXCEPTION_INVALID_DISPOSITION:
return "invalid disosition";
case EXCEPTION_GUARD_PAGE:
return "guard page";
case EXCEPTION_INVALID_HANDLE:
return "invalid handle";
default:
return "operating system exception";
}
}
#define ThrowPerformException( exception, code, reason, description )\
{\
(void)MagickCore::LogMagickEvent( MagickCore::ResourceEvent, GetMagickModule(),\
"%s - %s %s", objName, reason, description );\
MagickCore::ThrowException( exception, code, reason, description );\
return E_INVALIDARG;\
}
#define LogInformation( reason, description )\
{\
(void)MagickCore::LogMagickEvent( MagickCore::ResourceEvent, GetMagickModule(),\
"%s - %s %s", objName, reason, description );\
}
static long SafeArraySize(
SAFEARRAY* psa
)
{
HRESULT hr;
long lBoundl, lBoundu;
hr = ::SafeArrayGetLBound(psa, 1, &lBoundl);
if (FAILED(hr))
{
return 0;
}
hr = ::SafeArrayGetUBound(psa, 1, &lBoundu);
if (FAILED(hr))
{
return 0;
}
return (lBoundu - lBoundl + 1);
}
void MagickImage::GetXtrnArrayStr(CString& s, const SAFEARRAY* psa, LPCWSTR wszName)
{
s.Format(xtrnarray_fmt, psa, wszName);
}
void MagickImage::GetXtrnArrayStr(CString& s, const SAFEARRAY* psa)
{
GetXtrnArrayStr(s, psa, L"");
}
STDMETHODIMP MagickImage::get_Count(
long* pVal
)
{
ATLTRACENOTIMPL(_T("MagickImage::get_Count"));
}
STDMETHODIMP MagickImage::get__NewEnum(
LPUNKNOWN* pVal
)
{
ATLTRACENOTIMPL(_T("MagickImage::get__NewEnum"));
}
STDMETHODIMP MagickImage::get_Item(
VARIANT varIndex,
VARIANT* pVal
)
{
HRESULT hr = E_INVALIDARG;
VARIANTARG* pvarIndex = &varIndex;
VARTYPE vt = V_VT(pvarIndex);
long lIndex = 0;
CComVariant var;
while (vt == (VT_VARIANT | VT_BYREF))
{
pvarIndex = V_VARIANTREF(pvarIndex);
vt = V_VT(pvarIndex);
}
if (V_ISARRAY(pvarIndex))
{
return hr;
}
if ((vt & ~VT_BYREF) == VT_BSTR)
{
CW2A szVal(V_BSTR(pvarIndex));
var = _T("");
if (szVal)
{
MagickCore::Image* image;
MagickCore::ImageInfo* image_info;
MagickCore::ExceptionInfo *exception;
LPSTR lpszNext;
lpszNext = StrChrA(szVal, '.');
if (lpszNext == NULL)
{
lpszNext = "%w,%h,%m";
}
else
{
*lpszNext++ = '\0';
}
// lookup the registry id using token and pass the image in
exception = MagickCore::AcquireExceptionInfo();
image = (MagickCore::Image *) MagickCore::GetImageRegistry(MagickCore::ImageRegistryType, szVal, exception);
if (image != (MagickCore::Image*)NULL)
{
LPSTR text;
image_info = MagickCore::CloneImageInfo((MagickCore::ImageInfo*)NULL);
text = MagickCore::InterpretImageProperties(image_info, image, lpszNext, exception);
MagickCore::DestroyImageList(image);
MagickCore::DestroyImageInfo(image_info);
var = text;
MagickCore::RelinquishMagickMemory(text);
hr = S_OK;
}
(void)MagickCore::DestroyExceptionInfo(exception);
}
}
var.Detach(pVal);
return hr;
}
STDMETHODIMP MagickImage::get_Messages(
VARIANT* pVar
)
{
HRESULT hr = E_NOTIMPL;
#ifdef PERFORM_MESSAGE_CACHING
if (m_coll.size())
{
CSAVector<VARIANT>v(m_coll.size());
if (!v)
{
//m_coll.clear();
return E_OUTOFMEMORY;
}
else
{
// WARNING: This nested code block is required because
// CSAVectorData ctor performs a SafeArrayAccessData
// and you have to make sure the SafeArrayUnaccessData
// is called (which it is in the CSAVectorData dtor)
// before you use the CSAVector::DetachTo(...).
CSAVectorData<VARIANT>msgs(v);
if (!msgs)
{
//m_coll.clear();
return E_OUTOFMEMORY;
}
else
{
for (int index = 0; index < m_coll.size(); ++index)
{
CComVariant vt(m_coll[index]);
HRESULT hr = vt.Detach(&msgs[index]);
}
}
}
V_VT(pVar) = VT_ARRAY | VT_VARIANT;
V_ARRAY(pVar) = v.Detach();
//m_coll.clear();
}
#endif
return hr;
}
STDMETHODIMP MagickImage::Add(
SAFEARRAY** pArrayVar,
VARIANT* pVar
)
{
ATLTRACENOTIMPL(_T("MagickImage::Add"));
}
STDMETHODIMP MagickImage::Remove(
VARIANT varIndex
)
{
HRESULT hr = E_INVALIDARG;
VARIANTARG* pvarIndex = &varIndex;
VARTYPE vt = V_VT(pvarIndex);
while (vt == (VT_VARIANT | VT_BYREF))
{
pvarIndex = V_VARIANTREF(pvarIndex);
vt = V_VT(pvarIndex);
}
if (V_ISARRAY(pvarIndex))
{
return hr;
}
switch (vt & ~VT_BYREF)
{
case VT_BSTR:
{
if (!V_ISBYREF(pvarIndex))
{
CW2A szVal(V_BSTR(pvarIndex));
if (szVal)
{
if (MagickCore::DeleteImageRegistry(szVal))
{
hr = S_OK;
}
}
}
break;
}
}
return hr;
}
HRESULT MagickImage::Perform(
MagickCore::MagickBooleanType(*func)(MagickCore::ImageInfo* image_info, const int argc, char** argv, char** text, MagickCore::ExceptionInfo* exception),
SAFEARRAY** pArrayVar,
VARIANT* pVar,
MagickCore::ExceptionInfo* exception
)
{
bool bDebug = false;
HRESULT hr = E_INVALIDARG;
char* text;
#ifdef _DEBUG
//ATLASSERT( FALSE );
#endif
LogInformation(methodName, "enter");
text = (char*)NULL;
if (!pArrayVar)
{
ThrowPerformException(exception, MagickCore::ErrorException,
"Perform", "Argument list is NULL");
}
CComSafeArray<VARIANT>rg(*pArrayVar);
if (!rg)
{
ThrowPerformException(exception, MagickCore::ErrorException,
"Perform", "Argument list is bad");
}
if (rg.GetDimensions() != 1)
{
ThrowPerformException(exception, MagickCore::ErrorException,
"Perform", "Multi dimensional array passed");
}
if (rg.GetType() != VT_VARIANT)
{
ThrowPerformException(exception, MagickCore::ErrorException,
"Perform", "Non VARIANT array type passed");
}
int iLastVal = rg.GetCount();
bool bFoundOption = false;
for (int i = 0; i < iLastVal; ++i)
{
VARIANT& varIndex = rg[i];
VARIANTARG* pvarIndex = &varIndex;
VARTYPE vt = V_VT(pvarIndex);
while (vt == (VT_VARIANT | VT_BYREF))
{
pvarIndex = V_VARIANTREF(pvarIndex);
vt = V_VT(pvarIndex);
}
//->
if (V_ISARRAY(pvarIndex))
{
CString sArg;
SAFEARRAY* psa;
if (V_ISBYREF(pvarIndex))
{
psa = *V_ARRAYREF(pvarIndex);
}
else
{
psa = V_ARRAY(pvarIndex);
}
//----->
{
//------->
if (psa)
{
VARTYPE vatype = (V_VT(pvarIndex) & ~(VT_ARRAY | VT_BYREF));
int ndim = SafeArrayGetDim(psa);
if (ndim != 1)
{
ThrowPerformException(exception, MagickCore::ErrorException,
"Perform", "Multi-dimensional arrays not supported");
}
if (i < (iLastVal - 1))
//------------>
{
bool bFoundIt = false;
// This is any array that is not the last one in the arg
// list. This means it must be an input so we just pass
// it along.
switch (vatype)
//--------------->
{
case VT_UI1:
{
GetXtrnArrayStr(sArg, psa);
hr = AddArgs(sArg);
break;
}
default:
//----------------->
{
CComSafeArray<VARIANT>vals(psa);
if (vals)
//--------------------->
{
VARIANT& varFirst = vals[0];
VARIANTARG* pvarFirst = &varFirst;
if (V_VT(pvarFirst) == VT_BSTR)
//------------------------->
{
VARIANT& varSecond = vals[1];
VARIANTARG* pvarSecond = &varSecond;
if (V_ISARRAY(pvarSecond))
//--------------------------->
{
if (V_ISBYREF(pvarSecond))
{
VARTYPE vatype2 = (V_VT(pvarSecond) & ~(VT_ARRAY | VT_BYREF));
if (vatype2 == VT_UI1)
{
SAFEARRAY* psax = *V_ARRAYREF(pvarSecond);
int ndim2 = SafeArrayGetDim(psax);
if (ndim2 != 1)
{
ThrowPerformException(exception, MagickCore::ErrorException,
"Perform", "Input blob support requires a 1d array (1)");
}
GetXtrnArrayStr(sArg, psax, pvarFirst->bstrVal);
hr = AddArgs(sArg);
}
}
else
{
VARTYPE vatype2 = (V_VT(pvarSecond) & ~(VT_ARRAY));
if (vatype2 == VT_UI1)
{
SAFEARRAY* psax = V_ARRAY(pvarSecond);
int ndim2 = SafeArrayGetDim(psax);
if (ndim2 != 1)
{
ThrowPerformException(exception, MagickCore::ErrorException,
"Perform", "Input blob support requires a 1d array (2)");
}
/*
else
{
LPCWSTR pReturnBuffer = NULL;
long size = SafeArraySize( psax );
hr = SafeArrayAccessData( psax, (void**)&pReturnBuffer );
if( SUCCEEDED( hr ) )
{
hr = SafeArrayUnaccessData( psax );
}
}
*/
GetXtrnArrayStr(sArg, psax, pvarFirst->bstrVal);
hr = AddArgs(sArg);
}
}
//--------------------------->
} // end of V_ISARRAY
//------------------------->
} // end of == VT_BSTR
else
{
GetXtrnArrayStr(sArg, psa);
hr = AddArgs(sArg);
}
//vals.UnaccessData();
vals.Detach();
break;
//--------------------->
} // end of vals not NULL
//----------------->
} // end of default case
//--------------->
} // end of the switch
//------------->
}
else
{
// This is the last thing in the arg list and thus must
// the output array. We check the contents to a string of
// characters that says what format to encode the data in.
if (vatype == VT_UI1)
{
// the output is passed as an array of bytes - this
// is the way that VB does it.
LPCWSTR pReturnBuffer = NULL;
long size = SafeArraySize(psa);
hr = SafeArrayAccessData(psa, (void**)&pReturnBuffer);
if (SUCCEEDED(hr))
{
CStringW ws(pReturnBuffer, size);
hr = SafeArrayUnaccessData(psa);
SafeArrayDestroy(psa);
SAFEARRAY* pSafeArray = SafeArrayCreateVector(VT_UI1, 0, 0);
GetXtrnArrayStr(sArg, pSafeArray, ws);
hr = AddArgs(sArg);
if (V_ISBYREF(pvarIndex))
{
V_VT(pvarIndex) = VT_ARRAY | VT_UI1 | VT_BYREF;
*V_ARRAYREF(pvarIndex) = pSafeArray;
}
else
{
V_VT(pvarIndex) = VT_ARRAY | VT_UI1;
V_ARRAY(pvarIndex) = pSafeArray;
}
}
else
{
ThrowPerformException(exception, MagickCore::ErrorException,
"Perform", "Output array for blob must be 1d");
}
}
else
{
// the output is passed as a variant that is a BSTR
// - this is the way that VBSCRIPT and ASP does it.
CComSafeArray<VARIANT>vals(psa);
if (vals)
{
VARIANT& varFirst = vals[0];
VARIANTARG* pvarFirst = &varFirst;
if (V_VT(pvarFirst) == VT_BSTR)
{
//vals.UnaccessData();
SafeArrayDestroy(psa);
SAFEARRAY* pSafeArray = SafeArrayCreateVector(VT_UI1, 0, 0);
GetXtrnArrayStr(sArg, pSafeArray, pvarFirst->bstrVal);
hr = AddArgs(sArg);
if (V_ISBYREF(pvarIndex))
{
V_VT(pvarIndex) = VT_ARRAY | VT_UI1 | VT_BYREF;
*V_ARRAYREF(pvarIndex) = pSafeArray;
}
else
{
V_VT(pvarIndex) = VT_ARRAY | VT_UI1;
V_ARRAY(pvarIndex) = pSafeArray;
}
}
}
else
{
ThrowPerformException(exception, MagickCore::ErrorException,
"Perform", "Output array for blob is invalid");
}
}
}
}
else
{
//------->
ThrowPerformException(exception, MagickCore::ErrorException,
"Perform", "A passed array is not a valid array");
}
}
//----->
}
//-> // V_ISARRAY
else
{
switch (vt)
{
case VT_VARIANT: // invalid, should never happen
case VT_EMPTY:
case VT_NULL:
bFoundOption = false;
break;
case VT_BSTR:
case VT_BSTR | VT_BYREF:
{
LPTSTR lpszVal;
LPTSTR lpszNext;
CW2T str(V_ISBYREF(pvarIndex) ? *V_BSTRREF(pvarIndex) : V_BSTR(pvarIndex));
lpszVal = (LPTSTR)str;
bFoundOption = false;
// is this a command line option argument?
if ((*lpszVal == _T('+')) || (*lpszVal == _T('-')))
{
bFoundOption = true;
lpszNext = StrChr(lpszVal, _T('='));
if (lpszNext == NULL)
{
hr = AddArgs(V_BSTR(pvarIndex));
}
else
{
int nLength = lpszNext - lpszVal;
if (nLength > 16)
{
hr = AddArgs(V_BSTR(pvarIndex));
}
else
{
*lpszNext = _T('\0');
hr = AddArgs(lpszVal);
hr = AddArgs(++lpszNext);
}
break;
}
}
else
{
hr = AddArgs(lpszVal);
}
break;
}
case VT_UI1:
case VT_UI1 | VT_BYREF:
case VT_I2:
case VT_I2 | VT_BYREF:
case VT_I4:
case VT_I4 | VT_BYREF:
case VT_R4:
case VT_R4 | VT_BYREF:
case VT_R8:
case VT_R8 | VT_BYREF:
case VT_DECIMAL:
case VT_DECIMAL | VT_BYREF:
{
VARIANT variant;
bFoundOption = false;
VariantInit(&variant);
hr = VariantChangeTypeEx(&variant, pvarIndex, lcidDefault, 0, VT_BSTR);
if (SUCCEEDED(hr) && (V_VT(&variant) == VT_BSTR))
{
hr = AddArgs(V_BSTR(&variant));
}
VariantClear(&variant);
break;
}
default:
ThrowPerformException(exception, MagickCore::ErrorException,
"Perform", "Unsupported argument type");
}
}
}
LogInformation(methodName, "before execute");
MagickCore::ImageInfo
* image_info;
image_info = MagickCore::CloneImageInfo((MagickCore::ImageInfo*)NULL);
#ifdef _DEBUG
//ATLASSERT( FALSE );
#endif
hr = Execute(func, &text, image_info, exception);
MagickCore::DestroyImageInfo(image_info);
LogInformation(methodName, "after execute");
if (text != (char*)NULL)
{
CComVariant var;
var = text;
var.Detach(pVar);
MagickCore::RelinquishMagickMemory(text);
}
LogInformation(methodName, "return");
return hr;
}
void MagickImage::warninghandler(
const MagickCore::ExceptionType warning,
const char* message,
const char* qualifier
)
{
char warning_text[MagickPathExtent];
if (!message)
{
LogInformation("warninghandler", "called with no message");
return;
}
MagickCore::FormatLocaleString(warning_text, MagickPathExtent,
"warning %d: %.1024s%s%.1024s%s%s%.64s%s\n", warning, message,
qualifier ? " (" : "", qualifier ? qualifier : "",
qualifier ? ")" : "", errno ? " [" : "",
errno ? strerror(errno) : "", errno ? "]" : "");
(void)MagickCore::LogMagickEvent(MagickCore::ResourceEvent, GetMagickModule(), warning_text);
}
void MagickImage::errorhandler(
const MagickCore::ExceptionType warning,
const char* message,
const char* qualifier
)
{
char error_text[MagickPathExtent];
if (!message)
{
LogInformation("errorhandler", "called with no message");
return;
}
MagickCore::FormatLocaleString(error_text, MagickPathExtent,
"error %d: %.1024s%s%.1024s%s%s%.64s%s\n", warning, message,
qualifier ? " (" : "", qualifier ? qualifier : "",
qualifier ? ")" : "", errno ? " [" : "",
errno ? strerror(errno) : "", errno ? "]" : "");
(void)MagickCore::LogMagickEvent(MagickCore::ResourceEvent, GetMagickModule(), error_text);
}
void MagickImage::fatalerrorhandler(
const MagickCore::ExceptionType error,
const char* message,
const char* qualifier
)
{
char fatalerror_text[MagickPathExtent];
if (!message)
{
LogInformation("fatalhandler", "called with no message");
return;
}
MagickCore::FormatLocaleString(fatalerror_text, MagickPathExtent,
"fatal error %d: %.1024s%s%.1024s%s%s%.64s%s", error,
(message ? message : "ERROR"),
qualifier ? " (" : "", qualifier ? qualifier : "", qualifier ? ")" : "",
errno ? " [" : "", errno ? strerror(errno) : "", errno ? "]" : "");
(void)MagickCore::LogMagickEvent(MagickCore::ResourceEvent, GetMagickModule(), fatalerror_text);
// ATLASSERT( FALSE );
}
#define ENABLE_FULL_EXCEPTIONS
void MagickImage::CheckAndReportError(
MagickImageError& error,
HRESULT& hr,
const char* program
)
{
char message_text[MagickPathExtent];
if (FAILED(hr))
{
if (error.fullException)
{
MagickCore::FormatLocaleString(message_text, MagickPathExtent,
"%s: 0x%08X: %.1024s", program, error.fullExceptionCode, error.translate_exception());
}
else
{
const MagickCore::ExceptionInfo* exceptionlist;
MagickCore::ResetLinkedListIterator((MagickCore::LinkedListInfo*)error.exception->exceptions);
exceptionlist = (const MagickCore::ExceptionInfo*)MagickCore::GetNextValueInLinkedList((MagickCore::LinkedListInfo*)
error.exception->exceptions);
*message_text = 0;
while (exceptionlist != (const MagickCore::ExceptionInfo*)NULL)
{
size_t len = strlen(message_text);
if (MagickPathExtent - len < 0)
{
break;
}
MagickCore::FormatLocaleString(message_text + len, MagickPathExtent - len,
"%s: %d: %.1024s: %.1024s\r\n",
program,
exceptionlist->severity,
exceptionlist->reason ? exceptionlist->reason : "",
exceptionlist->description ? exceptionlist->description : "");
exceptionlist = (const MagickCore::ExceptionInfo*)MagickCore::GetNextValueInLinkedList((MagickCore::LinkedListInfo*)
error.exception->exceptions);
}
hr = MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, dwErrorBase + 1001);
#ifdef _DEBUG
//ATLASSERT( FALSE );
#endif
CA2WEX<MagickPathExtent>wsMessageText(message_text);
Error(wsMessageText, __uuidof(IMagickImage), hr);
}
}
error.Cleanup();
}
HRESULT MagickImage::Execute(
MagickCore::MagickBooleanType(*func)(MagickCore::ImageInfo* image_info, const int argc, char** argv, char** text, MagickCore::ExceptionInfo* exception),
char** s,
MagickCore::ImageInfo* image_info,
MagickCore::ExceptionInfo* exception
)
{
MagickCore::MagickBooleanType
status;
status = (func)(image_info, GetArgc(), GetArgv(), s, exception);
if (status == MagickCore::MagickFalse)
{
return E_UNEXPECTED;
}
return S_OK;
}
HRESULT MagickImage::TestHarness(
SAFEARRAY** pArrayVar,
VARIANT* pVar
)
{
HRESULT hr = S_OK;
(void)MagickCore::LogMagickEvent(MagickCore::ResourceEvent, GetMagickModule(),
"TestHarness");
MagickCore::ExceptionInfo *exception;
char
* reason,
*description,
message_text[MagickPathExtent];
reason = "unknown";
description = "unknown";
exception = MagickCore::AcquireExceptionInfo();
CComVariant var;
if (!pArrayVar)
{
return E_INVALIDARG;
}
CComSafeArray<VARIANT>rg(*pArrayVar);
if (!rg)
{
return E_INVALIDARG;
}
if (rg.GetDimensions() != 1)
{
ThrowPerformException(exception, MagickCore::ErrorException,
"Perform", "Multi dimensional array passed");
}
if (rg.GetType() != VT_VARIANT)
{
ThrowPerformException(exception, MagickCore::ErrorException,
"Perform", "Non VARIANT array type passed");
}
EmptyArgs();
AddArgs(L"-convert");
int iLastVal = rg.GetCount();
for (int i = 0; i < iLastVal; ++i)
{
{
CComVariant vt(rg[i]);
vt.ChangeType(VT_BSTR);
CW2A str(vt.bstrVal);
(void)MagickCore::LogMagickEvent(MagickCore::ResourceEvent, GetMagickModule(),
"arg: %s", (LPCSTR)str);
hr = AddArgs(vt.bstrVal);
}
}
//__try
{
char* text;
MagickCore::ImageInfo* image_info;
image_info = MagickCore::CloneImageInfo((MagickCore::ImageInfo*)NULL);
text = (char*)NULL;
hr = Execute(MagickCore::ConvertImageCommand, &text, image_info, exception);
MagickCore::DestroyImageInfo(image_info);
if (text != (char*)NULL)
{
var = text;
var.Detach(pVar);
MagickCore::RelinquishMagickMemory(text);
}
if (FAILED(hr))
{
if (exception->reason)
{
reason = exception->reason;
}
if (exception->description)
{
description = exception->description;
}
}
}
//__except(1)
//{
// hr = E_UNEXPECTED;
// reason = "exception";
// description = translate_exception(_exception_code());
//}
if (FAILED(hr))
{
hr = MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, dwErrorBase + 1001);
MagickCore::FormatLocaleString(message_text, MagickPathExtent,
"convert: %d: %.1024s: %.1024s", exception->severity, reason, description);
CA2WEX<MagickPathExtent> str(message_text);
#ifdef _DEBUG
// ATLASSERT( FALSE );
#endif
Error(str, __uuidof(IMagickImage), hr);
}
MagickCore::DestroyExceptionInfo(exception);
return hr;
}
STDMETHODIMP MagickImage::Compare(
SAFEARRAY** pArrayVar,
VARIANT* pVar
)
{
HRESULT hr;
class MagickImageError error;
//unsigned char
// *leaktest;
//leaktest=(unsigned char *) MagickCore::AcquireMemory(1024);
#ifdef ENABLE_FULL_EXCEPTIONS
__try
#endif
{
EmptyArgs();
AddArgs(L"-compare");
hr = Perform(MagickCore::CompareImagesCommand, pArrayVar, pVar, error.exception);
}
#ifdef ENABLE_FULL_EXCEPTIONS
__except (1)
{
hr = E_UNEXPECTED;
error.fullException = TRUE;
error.fullExceptionCode = _exception_code();
}
#endif
CheckAndReportError(error, hr, "compare");
return hr;
}
STDMETHODIMP MagickImage::Composite(
SAFEARRAY** pArrayVar,
VARIANT* pVar
)
{
HRESULT hr;
MagickImageError error;
#ifdef ENABLE_FULL_EXCEPTIONS
__try
#endif
{
EmptyArgs();
AddArgs(L"-composite");
hr = Perform(MagickCore::CompositeImageCommand, pArrayVar, pVar, error.exception);
}
#ifdef ENABLE_FULL_EXCEPTIONS
__except (1)
{
hr = E_UNEXPECTED;
error.fullException = TRUE;
error.fullExceptionCode = _exception_code();
}
#endif
CheckAndReportError(error, hr, "composite");
return hr;
}
STDMETHODIMP MagickImage::Convert(
SAFEARRAY** pArrayVar,
VARIANT* pVar
)
{
HRESULT hr;
MagickImageError error;
ATLASSERT(FALSE);
#ifdef ENABLE_FULL_EXCEPTIONS
__try
#endif
{
EmptyArgs();
AddArgs(L"-convert");
hr = Perform(MagickCore::ConvertImageCommand, pArrayVar, pVar, error.exception);
}
#ifdef ENABLE_FULL_EXCEPTIONS
__except (1)
{
hr = E_UNEXPECTED;
error.fullException = TRUE;
error.fullExceptionCode = _exception_code();
}
#endif
CheckAndReportError(error, hr, "convert");
return hr;
}
HRESULT MagickImage::Identify(
SAFEARRAY** pArrayVar,
VARIANT* pVar
)
{
HRESULT hr;
MagickImageError error;
#ifdef ENABLE_FULL_EXCEPTIONS
__try
#endif
{
EmptyArgs();
AddArgs(L"-identify");
hr = Perform(MagickCore::IdentifyImageCommand, pArrayVar, pVar, error.exception);
}
#ifdef ENABLE_FULL_EXCEPTIONS
__except (1)
{
hr = E_UNEXPECTED;
error.fullException = TRUE;
error.fullExceptionCode = _exception_code();
}
#endif
CheckAndReportError(error, hr, "identity");
return hr;
}
HRESULT MagickImage::Mogrify(
SAFEARRAY** pArrayVar,
VARIANT* pVar
)
{
HRESULT hr;
MagickImageError error;
#ifdef ENABLE_FULL_EXCEPTIONS
__try
#endif
{
EmptyArgs();
AddArgs(L"-mogrify");
hr = Perform(MagickCore::MogrifyImageCommand, pArrayVar, pVar, error.exception);
}
#ifdef ENABLE_FULL_EXCEPTIONS
__except (1)
{
hr = E_UNEXPECTED;
error.fullException = TRUE;
error.fullExceptionCode = _exception_code();
}
#endif
CheckAndReportError(error, hr, "morgify");
return hr;
}
HRESULT MagickImage::Montage(
SAFEARRAY** pArrayVar,
VARIANT* pVar
)
{
HRESULT hr;
MagickImageError error;
#ifdef ENABLE_FULL_EXCEPTIONS
__try
#endif
{
EmptyArgs();
AddArgs(L"-montage");
hr = Perform(MagickCore::MontageImageCommand, pArrayVar, pVar, error.exception);
}
#ifdef ENABLE_FULL_EXCEPTIONS
__except (1)
{
hr = E_UNEXPECTED;
error.fullException = TRUE;
error.fullExceptionCode = _exception_code();
}
#endif
CheckAndReportError(error, hr, "montage");
return hr;
}
STDMETHODIMP MagickImage::Stream(
SAFEARRAY** pArrayVar,
VARIANT* pVar
)
{
HRESULT hr;
MagickImageError error;
#ifdef ENABLE_FULL_EXCEPTIONS
__try
#endif
{
EmptyArgs();
AddArgs(L"-stream");
hr = Perform(MagickCore::StreamImageCommand, pArrayVar, pVar, error.exception);
}
#ifdef ENABLE_FULL_EXCEPTIONS
__except (1)
{
hr = E_UNEXPECTED;
error.fullException = TRUE;
error.fullExceptionCode = _exception_code();
}
#endif
CheckAndReportError(error, hr, "stream");
return hr;
}
HRESULT MagickImage::AddArgs(
LPCWSTR widestr
)
{
HRESULT hr = E_OUTOFMEMORY;
if (m_argvIndex >= m_argc)
{
return hr;
}
hr = S_OK;
CW2A sArgUTF8(widestr, CP_UTF8);
m_argv[m_argvIndex++] = strdup(sArgUTF8);
CW2A sArgANSI(widestr);
(void)MagickCore::LogMagickEvent(MagickCore::ResourceEvent, GetMagickModule(),
"arg: %s", (LPSTR)sArgANSI);
if (m_argvIndex >= m_argc)
{
hr = ReAllocateArgs(nDefaultArgumentSize);
}
return hr;
}
HRESULT MagickImage::AddArgs(
LPCSTR lpstr
)
{
HRESULT hr = E_OUTOFMEMORY;
if (m_argvIndex >= m_argc)
{
return hr;
}
hr = S_OK;
CA2W wsArg(lpstr);
CW2A sArgUTF8(wsArg, CP_UTF8);
CW2A sArgANSI(wsArg);
m_argv[m_argvIndex++] = strdup(sArgUTF8);
(void)MagickCore::LogMagickEvent(MagickCore::ResourceEvent, GetMagickModule(),
"arg: %s", (LPSTR)sArgANSI);
if (m_argvIndex >= m_argc)
{
hr = ReAllocateArgs(nDefaultArgumentSize);
}
return hr;
}
HRESULT MagickImage::AllocateArgs(
int cArgc
)
{
m_argv = new LPSTR[cArgc];
if (m_argv == NULL)
{
return E_OUTOFMEMORY;
}
m_argc = cArgc;
m_argvIndex = 0;
for (int i = 0; i < m_argc; i++)
{
m_argv[i] = NULL;
}
return S_OK;
}
HRESULT MagickImage::ReAllocateArgs(
int cArgc
)
{
LPSTR* argv = m_argv;
int argc = m_argc + cArgc;
argv = new LPSTR[argc];
if (argv == NULL)
{
return E_OUTOFMEMORY;
}
for (int i = 0; i < argc; i++)
{
if (i < m_argc)
{
argv[i] = m_argv[i];
}
else
{
argv[i] = NULL;
}
}
if (m_argv)
{
delete m_argv;
m_argv = argv;
}
m_argc = argc;
return S_OK;
}
void MagickImage::DeleteArgs()
{
EmptyArgs();
if (m_argv)
{
delete m_argv;
}
}
char** MagickImage::GetArgv()
{
return m_argv;
}
int MagickImage::GetArgc()
{
return m_argvIndex;
}
void MagickImage::EmptyArgs()
{
for (int i = 0; i < m_argc; i++)
{
free((void*)(m_argv[i]));
m_argv[i] = NULL;
}
m_argvIndex = 0;
}
STDMETHODIMP MagickImage::OnStartPage(
IUnknown* pUnk
)
{
(void)MagickCore::LogMagickEvent(MagickCore::ResourceEvent, GetMagickModule(),
"OnStartPage");
if (!pUnk)
{
return E_POINTER;
}
CComPtr<IScriptingContext>spContext;
HRESULT hr;
// Get the IScriptingContext Interface
hr = pUnk->QueryInterface(__uuidof(IScriptingContext), (void**)&spContext);
if (FAILED(hr))
{
return hr;
}
// Get Request Object Pointer
hr = spContext->get_Request(&m_piRequest);
if (FAILED(hr))
{
(void)MagickCore::LogMagickEvent(MagickCore::ResourceEvent, GetMagickModule(),
"OnStartPage get Request failed");
//spContext.Release();
//return hr;
}
// Get Response Object Pointer
hr = spContext->get_Response(&m_piResponse);
if (FAILED(hr))
{
(void)MagickCore::LogMagickEvent(MagickCore::ResourceEvent, GetMagickModule(),
"OnStartPage get Response failed");
//m_piRequest.Release();
//return hr;
}
// Get Server Object Pointer
hr = spContext->get_Server(&m_piServer);
if (FAILED(hr))
{
(void)MagickCore::LogMagickEvent(MagickCore::ResourceEvent, GetMagickModule(),
"OnStartPage get Server failed");
//m_piRequest.Release();
//m_piResponse.Release();
//return hr;
}
// Get Session Object Pointer
hr = spContext->get_Session(&m_piSession);
if (FAILED(hr))
{
(void)MagickCore::LogMagickEvent(MagickCore::ResourceEvent, GetMagickModule(),
"OnStartPage get Session failed");
//m_piRequest.Release();
//m_piResponse.Release();
//m_piServer.Release();
//return hr;
}
// Get Application Object Pointer
hr = spContext->get_Application(&m_piApplication);
if (FAILED(hr))
{
(void)MagickCore::LogMagickEvent(MagickCore::ResourceEvent, GetMagickModule(),
"OnStartPage get Application failed");
//m_piRequest.Release();
//m_piResponse.Release();
//m_piServer.Release();
//m_piSession.Release();
//return hr;
}
m_bOnStartPageCalled = TRUE;
{
CComPtr<IRequestDictionary>pReadDictionary;
CComPtr<IReadCookie>pCookieDictionary;
hr = m_piRequest->get_Cookies(&pReadDictionary);
if (SUCCEEDED(hr))
{
CComVariant vtIn(_T("MAGICK_DEBUG"));
CComVariant vtKey(_T("level"));
CComVariant vtOut;
CComVariant vtCookieValue;
hr = pReadDictionary->get_Item(vtIn, &vtOut);
if (SUCCEEDED(hr) && (V_VT(&vtOut) == VT_DISPATCH))
{
pCookieDictionary = (IReadCookie*)(vtOut.pdispVal);
hr = pCookieDictionary->get_Item(vtKey, &vtCookieValue);
if (SUCCEEDED(hr) && (V_VT(&vtCookieValue) == VT_BSTR))
{
CW2T str(vtCookieValue.bstrVal);
int level = _ttoi(str);
#if defined (_ENABLE_OLD_LOGGING_SUPPORT_)
MagickCore::DebugLevel(level);
#endif
(void)MagickCore::LogMagickEvent(MagickCore::ResourceEvent, GetMagickModule(),
"OnStartPage debug level: %d", level);
}
else
{
(void)MagickCore::LogMagickEvent(MagickCore::ResourceEvent, GetMagickModule(),
"OnStartPage - parse error");
}
}
else
{
(void)MagickCore::LogMagickEvent(MagickCore::ResourceEvent, GetMagickModule(),
"OnStartPage - no MAGICK_DEBUG");
}
}
else
{
(void)MagickCore::LogMagickEvent(MagickCore::ResourceEvent, GetMagickModule(),
"OnStartPage - no cookies");
}
}
return S_OK;
}
STDMETHODIMP MagickImage::OnEndPage()
{
(void)MagickCore::LogMagickEvent(MagickCore::ResourceEvent, GetMagickModule(),
"OnEndPage");
m_bOnStartPageCalled = FALSE;
// Release all interfaces
if (m_piRequest)
{
m_piRequest.Release();
}
if (m_piResponse)
{
m_piResponse.Release();
}
if (m_piServer)
{
m_piServer.Release();
}
if (m_piSession)
{
m_piSession.Release();
}
if (m_piApplication)
{
m_piApplication.Release();
}
return S_OK;
}
HRESULT MagickImage::Activate()
{
(void)MagickCore::LogMagickEvent(MagickCore::ResourceEvent, GetMagickModule(),
"Activate");
HRESULT hr = GetObjectContext(&m_spObjectContext);
if (SUCCEEDED(hr))
{
return S_OK;
}
return hr;
}
BOOL MagickImage::CanBePooled()
{
(void)MagickCore::LogMagickEvent(MagickCore::ResourceEvent, GetMagickModule(),
"CanBePooled");
return FALSE;
}
void MagickImage::Deactivate()
{
(void)MagickCore::LogMagickEvent(MagickCore::ResourceEvent, GetMagickModule(),
"Deactivate");
m_spObjectContext.Release();
}
typedef CAtlArray<CStringA>CStringArray;
static void LocalTokenize(
const CStringA& s,
LPCSTR sz,
CStringArray& asToken
)
{
int nPos = 0;
CStringA sToken;
asToken.RemoveAll();
sToken = s.Tokenize(sz, nPos);
while (!sToken.IsEmpty())
{
asToken.Add(sToken);
}
if (asToken.GetCount() == 0)
{
asToken.Add(s);
}
}
HRESULT MagickImage::Construct(
IDispatch* pCtorObj
)
{
(void)MagickCore::LogMagickEvent(MagickCore::ResourceEvent, GetMagickModule(),
"Construct");
CComPtr<IObjectConstructString>spObjectConstructString;
HRESULT hr = pCtorObj->QueryInterface(&spObjectConstructString);
if (SUCCEEDED(hr))
{
CComBSTR bstrConstruct;
hr = spObjectConstructString->get_ConstructString(&bstrConstruct);
if (SUCCEEDED(hr))
{
CStringA sOptions(bstrConstruct);
int nPos = 0;
CStringA sToken;
CStringArray asToken;
(void)MagickCore::LogMagickEvent(MagickCore::ResourceEvent, GetMagickModule(),
"Construct data: %s", (LPCSTR)sOptions);
sToken = sOptions.Tokenize(".", nPos);
while (!sToken.IsEmpty())
{
LocalTokenize(sToken, "=", asToken);
if (asToken.GetCount() == 2)
{
const CStringA& sName = asToken[0];
const CStringA& sValue = asToken[1];
(void)MagickCore::LogMagickEvent(MagickCore::ResourceEvent, GetMagickModule(),
"Construct name: %s value: %s",
(LPCSTR)sName, (LPCSTR)sValue);
#if defined (_ENABLE_OLD_LOGGING_SUPPORT_)
if (sName.Compare("MAGICK_DEBUG_LEVEL") == 0)
{
MagickCore::DebugLevel(atoi(sValue));
}
if (sName.Compare("MAGICK_DEBUG_PATH") == 0)
{
MagickCore::DebugFilePath(sValue);
}
if (sName.Compare("MAGICK_LOG_EVENTMASK") == 0)
{
MagickCore::SetLogEventMask(sValue);
}
#endif
} // if
} // while
} // if
}
return hr;
}
|
f17e274faf2a9a99b307e01f6b07c3ed191a5897
|
34844cc98087574ee7aee8c22d725486d099bcfd
|
/SensorGridPM/SensorGridPM.ino
|
6e095722409636268c46e7c2ce4497373cfb1756
|
[] |
no_license
|
NUKnightLab/SensorGrid
|
5b943607671238768c264e6691ef5053fcaf77fe
|
33ce8d1358c6cdaa241d6065f5a627406d6265fe
|
refs/heads/master
| 2021-10-22T16:40:12.955350
| 2019-09-11T21:07:15
| 2019-09-11T21:07:15
| 81,235,519
| 12
| 2
| null | 2021-03-19T23:13:11
| 2017-02-07T17:35:59
|
C++
|
UTF-8
|
C++
| false
| false
| 4,722
|
ino
|
SensorGridPM.ino
|
/**
* Knight Lab SensorGrid
*
* Wireless air pollution (Particulate Matter PM2.5 & PM10) monitoring over LoRa radio
*
* Copyright 2018 Northwestern University
*/
//#include <KnightLab_GPS.h>
#include "config.h"
#include "runtime.h"
#include <LoRa.h>
#include <LoRaHarvest.h>
#define SET_CLOCK false
#define SERIAL_TIMEOUT 10000
WatchdogType Watchdog;
RTC_PCF8523 rtc;
int start_epoch;
OLED oled = OLED(rtc);
/* local utilities */
static void setupLogging() {
Serial.begin(115200);
set_logging(true);
}
static void setRTC() {
DateTime dt = DateTime(start_epoch);
rtc.adjust(DateTime(start_epoch - 18000)); // Subtract 5 hours to adjust for timezone
}
static void setRTCz() {
DateTime dt = rtc.now();
rtcz.setDate(dt.day(), dt.month(), dt.year()-2000); // When setting the year to 2018, it becomes 34
rtcz.setTime(dt.hour(), dt.minute(), dt.second());
}
static void printCurrentTime() {
DateTime dt = rtc.now();
logln(F("Current time: %02d:%02d:%02d, "), rtcz.getHours(), rtcz.getMinutes(), rtcz.getSeconds());
logln(F("Current Epoch: %u"), rtcz.getEpoch());
}
/* end local utilities */
/*
* interrupts
*/
void aButton_ISR() {
static bool busy = false;
if (busy) return;
busy = true;
// rtcz.disableAlarm();
static volatile int state = 0;
state = !digitalRead(BUTTON_A);
if (state) {
logln(F("A-Button pushed"));
oled.toggleDisplayState();
}
if (oled.isOn()) {
//updateClock(); // Temporarily removed
oled.displayDateTime();
} else {
oled.clear();
}
busy = false;
// rtcz.disableAlarm();
/*
aButtonState = !digitalRead(BUTTON_A);
if (aButtonState) {
_on = !_on;
if (_on) {
_activated_time = millis();
displayDateTimeOLED();
} else {
standbyOLED();
}
}
*/
}
/*
void updateClock() {
int gps_year = GPS.year;
if (gps_year != 0 && gps_year != 80) {
uint32_t gps_time = DateTime(GPS.year, GPS.month, GPS.day, GPS.hour, GPS.minute, GPS.seconds).unixtime();
uint32_t rtc_time = rtc.now().unixtime();
if (rtc_time - gps_time > 1 || gps_time - rtc_time > 1) {
rtc.adjust(DateTime(GPS.year, GPS.month, GPS.day, GPS.hour, GPS.minute, GPS.seconds));
}
}
setRTCz();
}
*/
void setupSensors() {
pinMode(12, OUTPUT); // enable pin to HPM boost
Serial.println("Loading sensor config ...");
loadSensorConfig(nodeId(), getTime);
Serial.println(".. done loading sensor config");
}
void setupClocks() {
rtc.begin();
/* In general, we no longer use SET_CLOCK. Instead use a GPS module to set the time */
if (SET_CLOCK) {
log_(F("Printing initial DateTime: "));
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
log_(F(__DATE__));
log_(F(' '));
logln(F(__TIME__));
}
rtcz.begin();
setRTCz();
}
/* hard fault handler */
/* see Segger debug manual: https://www.segger.com/downloads/application-notes/AN00016 */
static volatile unsigned int _Continue;
void HardFault_Handler(void) {
_Continue = 0u;
//
// When stuck here, change the variable value to != 0 in order to step out
//
logln(F("!!!!**** HARD FAULT -- REQUESTING RESET *****!!!!"));
SCB->AIRCR = 0x05FA0004; // System reset
while (_Continue == 0u) {}
}
// Doesn't include watchdog like the one in runtime
static void standbyTEMP() {
if (DO_STANDBY) {
rtcz.standbyMode();
}
}
// Doesn't include interrupt function like in runtime
void setInterruptTimeoutTEMP(DateTime &datetime) {
rtcz.setAlarmSeconds(datetime.second());
rtcz.setAlarmMinutes(datetime.minute());
rtcz.enableAlarm(rtcz.MATCH_MMSS);
}
void waitSerial()
{
unsigned long _start = millis();
while ( !Serial && (millis() - _start) < SERIAL_TIMEOUT ) {}
}
void setup() {
waitSerial();
rtcz.begin();
systemStartTime(rtcz.getEpoch());
Watchdog.enable();
config.loadConfig();
nodeId(config.node_id);
setupSensors();
setupLoRa(config.RFM95_CS, config.RFM95_RST, config.RFM95_INT);
setupRunner();
for (uint8_t i=0; i<255; i++) {
txPower(i, DEFAULT_LORA_TX_POWER);
}
Watchdog.disable();
recordRestart();
}
void loop() {
Watchdog.enable();
runRunner();
/**
* Some apparent lockups may actually be indefinite looping on STANDBY status
* if for some reason the scheduled interrupt never happens to kick us out of
* STANDBY mode. For that reason, the standby_timer will track time and should
* never get to be longer than the scheduled heartbeat period.
*/
//static uint32_t standby_timer = getTime();
}
|
91c1f59a2668d7f4cd4ed69c7e7feeb30d3019d7
|
278e3b84e4e97524928c5d27099e64fa744d67ff
|
/GLES3Renderer/GLES3Renderer/GfxUniformZBuffer.cpp
|
240f390bca60ee40f4e1e7014032004f69e2c47e
|
[
"Apache-2.0"
] |
permissive
|
LiangYue1981816/CrossEngine-GLES3Renderer
|
8f4d47a8c247c4e78d4d34d9887bcd6bee5f2113
|
8d092307c22164895c4f92395ef291c87f2811e6
|
refs/heads/master
| 2020-03-18T01:44:22.512483
| 2018-08-02T03:04:08
| 2018-08-02T03:04:08
| 134,157,249
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,030
|
cpp
|
GfxUniformZBuffer.cpp
|
#include "stdio.h"
#include "stdlib.h"
#include "GfxUniformBuffer.h"
#include "GfxUniformZBuffer.h"
CGfxUniformZBuffer::CGfxUniformZBuffer(void)
: m_bDirty(false)
, m_pUniformBuffer(NULL)
{
m_pUniformBuffer = new CGfxUniformBuffer;
m_pUniformBuffer->Create(NULL, sizeof(m_params), true);
}
CGfxUniformZBuffer::~CGfxUniformZBuffer(void)
{
m_pUniformBuffer->Destroy();
delete m_pUniformBuffer;
}
void CGfxUniformZBuffer::SetZBuffer(float zNear, float zFar)
{
// OpenGL
float x = (1.0f - zFar / zNear) / 2.0f;
float y = (1.0f + zFar / zNear) / 2.0f;
// D3D
//float x = 1.0f - zFar / zNear;
//float y = zFar / zNear;
m_bDirty = true;
m_params.zbuffer = glm::vec4(x, y, x / zFar, y / zFar);
}
void CGfxUniformZBuffer::Apply(void)
{
if (m_bDirty) {
m_bDirty = false;
m_pUniformBuffer->SetData(&m_params, sizeof(m_params));
}
}
GLuint CGfxUniformZBuffer::GetSize(void) const
{
return m_pUniformBuffer->GetSize();
}
GLuint CGfxUniformZBuffer::GetBuffer(void) const
{
return m_pUniformBuffer->GetBuffer();
}
|
83000299ac8f6e0a6dfec97552561d6a3c906a3e
|
5c44f478f470f2e081210c8cc180a342405f33c8
|
/Day 7/Three Sum Closest.cpp
|
5df1a628ea2e082588287900a0c948d5d93cdd80
|
[] |
no_license
|
Debashish-hub/100-Days-Of-Coding
|
33e0e280122af5496ed6fc788e89885977477ed6
|
263f33a0247e0b0001a85a42543b4596ee03adc9
|
refs/heads/main
| 2023-06-08T08:09:59.740053
| 2021-06-28T15:57:31
| 2021-06-28T15:57:31
| 346,478,715
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,940
|
cpp
|
Three Sum Closest.cpp
|
//Three Sum Closest
//Easy Accuracy: 28.11% Submissions: 7140 Points: 2
//Given an array Arr of N numbers and another number target, find three integers
//in the array such that the sum is closest to target. Return the sum of the three integers.
// { Driver Code Starts
//Initial function template for C++
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function template for C++
// arr : given vector of elements
// target : given sum value
class Solution{
public:
int threeSumClosest(vector<int> arr, int target) {
// Your code goes here
int res = INT_MIN, minDiff = INT_MAX;
sort(arr.begin(), arr.end());
for(int i = 0; i < arr.size(); i++){
int sum = arr[i];
int l = i+1, h = arr.size()-1;
while(l < h){
int temp = sum + arr[l] + arr[h];
int diff = abs(target - temp);
if(diff == 0)
return temp;
else if(temp < target)
l++;
else
h--;
if(minDiff == diff){
res = max(res, temp);
}
else {
minDiff = min(diff, minDiff);
if(minDiff == diff)
res = temp;
}
}
}
return res;
}
};
// { Driver Code Starts.
int main() {
int t;
cin >> t;
while(t--) {
int n,target;
cin >> n >> target;
vector<int> vec(n);
for(int i = 0 ; i < n ; ++ i )
cin >> vec[i];
Solution obj;
cout << obj.threeSumClosest(vec, target) << "\n";
}
}
//Position this line where user code will be pasted.
// } Driver Code Ends
|
af1e9fe1d28842d924b400578abb4cedf97daac5
|
cfa27073eadacfb581a0ce09d391272e2d764fc3
|
/src/archon/image/computed_image.hpp
|
4e9a9ef525a3a0e02ac1e5689f88069ed998382d
|
[] |
no_license
|
kspangsege/archon
|
e1b5cd2413cef95782ee8c8185be0086289fa318
|
d8c323efd2d7914cc96d832a070f31168c4b847b
|
refs/heads/master
| 2023-09-01T02:58:03.071535
| 2023-08-31T18:15:41
| 2023-08-31T19:50:37
| 15,814,007
| 2
| 0
| null | 2023-09-13T10:16:58
| 2014-01-11T00:41:43
|
C++
|
UTF-8
|
C++
| false
| false
| 4,737
|
hpp
|
computed_image.hpp
|
// This file is part of the Archon project, a suite of C++ libraries.
//
// Copyright (C) 2022 Kristian Spangsege <kristian.spangsege@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#ifndef ARCHON_X_IMAGE_X_COMPUTED_IMAGE_HPP
#define ARCHON_X_IMAGE_X_COMPUTED_IMAGE_HPP
/// \file
#include <algorithm>
#include <utility>
#include <archon/core/type.hpp>
#include <archon/image/geom.hpp>
#include <archon/image/tray.hpp>
#include <archon/image/comp_repr.hpp>
#include <archon/image/color_space.hpp>
#include <archon/image/pixel.hpp>
#include <archon/image/buffer_format.hpp>
#include <archon/image/image.hpp>
namespace archon::image {
/// \brief Image whose pixels are computed on demand.
///
/// This class offers an image imaplementation where pixels are computed on demand, rather
/// than being read from memory.
///
/// Here is an example of how it might be used:
///
/// \code{.cpp}
///
/// archon::image::ComputedImage image(image_size, [&](archon::image::Pos pos) {
/// archon::image::float_type val = noise(pos);
/// return archon::image::Pixel_Lum_F({ val });
/// });
/// archon::image::save(image, path, locale);
///
/// \endcode
///
/// FIXME: Find a way to support custom color spaces
///
template<class R, class F> class ComputedImage
: public image::Image {
public:
using pixel_repr_type = R;
using func_type = F;
using pixel_type = image::Pixel<pixel_repr_type>;
ComputedImage(image::Size size, func_type func);
// Overriding virtual member functions of `image::Image`.
auto get_size() const noexcept -> image::Size override final;
bool try_get_buffer(image::BufferFormat&, const void*&) const override final;
auto get_transfer_info() const -> TransferInfo override final;
auto get_palette() const noexcept -> const Image* override final;
void read(image::Pos, const image::Tray<void>&) const override final;
private:
image::Size m_size;
func_type m_func;
};
template<class F> ComputedImage(image::Size, F) -> ComputedImage<typename core::ReturnType<F>::repr_type, F>;
// Implementation
template<class R, class F>
inline ComputedImage<R, F>::ComputedImage(image::Size size, func_type func)
: m_size(size)
, m_func(std::move(func)) // Throws
{
}
template<class R, class F>
auto ComputedImage<R, F>::get_size() const noexcept -> image::Size
{
return m_size;
}
template<class R, class F>
bool ComputedImage<R, F>::try_get_buffer(image::BufferFormat&, const void*&) const
{
return false;
}
template<class R, class F>
auto ComputedImage<R, F>::get_transfer_info() const -> TransferInfo
{
return {
pixel_repr_type::comp_repr,
&image::get_color_space(pixel_repr_type::color_space_tag),
pixel_repr_type::has_alpha,
image::comp_repr_bit_width<pixel_repr_type::comp_repr>(),
};
}
template<class R, class F>
auto ComputedImage<R, F>::get_palette() const noexcept -> const Image*
{
return nullptr;
}
template<class R, class F>
void ComputedImage<R, F>::read(image::Pos pos, const image::Tray<void>& tray) const
{
using comp_type = typename pixel_repr_type::comp_type;
image::Tray tray_2 = tray.cast_to<comp_type>();
for (int x = 0; x < tray_2.size.width; ++x) {
for (int y = 0; y < tray_2.size.height; ++y) {
image::Pos pos_2 = pos + image::Size(x, y);
pixel_type pixel = m_func(pos_2); // Throws
const comp_type* origin = pixel.data();
comp_type* destin = tray_2(x, y);
std::copy(origin, origin + pixel_repr_type::num_channels, destin);
}
}
}
} // namespace archon::image
#endif // ARCHON_X_IMAGE_X_COMPUTED_IMAGE_HPP
|
e635b0fd784142a1e361a4987ba53a7bc916f83e
|
9a149637db59ccd94dfe2bb1139d007708b067fe
|
/Dynamic Programming/printCodesIterative.cpp
|
449741f156638fb2423d608c451b304f7d1d1751
|
[] |
no_license
|
Nishant-Pall/C-practice
|
280da609cfc53f32e83e9cf0b221843e03343773
|
2502cb7d04ea611a7847720262eee3ad93186db2
|
refs/heads/master
| 2021-08-15T21:57:15.511091
| 2020-09-05T16:37:48
| 2020-09-05T16:37:48
| 225,806,107
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 645
|
cpp
|
printCodesIterative.cpp
|
#include <iostream>
#include <string>
using namespace std;
int getCodesIterative(int* input, int size, int*arr) {
int *output = new int[size+1];
output[0] = 1;
output[1] = 1;
for(int i=2; i<size; i++){
output[i] = output[i-1];
if(input[i-2]*10+input[i-1] <= 26){
output[i] += output[i-2];
}
}
int ans = output[size];
delete[] output;
return ans;
}
int main(){
int size;
cin>>size;
int *input = new int[size];
int *arr = new int[size+1];
for(int i=0; i<size; i++){
arr[i]=0;
}
for(int i=0; i<size; i++){
cin>>input[i];
}
cout<<getCodesIterative(input, size, arr);
}
|
dfa572d77dc73f8b3e6e4800939631c02529955b
|
776a3a17511602988bfe718c220e9b212dc07439
|
/ZOJ/4021/15843235_AC_110ms_1164kB.cpp
|
5eeeedfc85e342183a383c0d428ae13e403b2888
|
[] |
no_license
|
DcmTruman/my_acm_training
|
bc1675d1de0c689bde9f62d8e15b3d885ca6b984
|
c54643ca395ad4be3dc4b640504a0fdc62f70b1c
|
refs/heads/master
| 2020-05-16T06:19:17.356731
| 2019-04-22T18:01:46
| 2019-04-22T18:01:46
| 182,840,197
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,616
|
cpp
|
15843235_AC_110ms_1164kB.cpp
|
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
char ss[500020];
char stack[500020];
int num;
char ops(char x){
return x=='T'? 'F':'T';
}
char calc(char x,char t,char y){
if(t=='&'){
if(x=='T'&&y=='T') return 'T';
if(x=='X'||y=='X') return 'X';
if(x=='T'||y=='T') return 'F';
return 'X';
}else if(t=='|'){
if(x=='T'||y=='T') return 'T';
if(x=='F'||y=='F') return 'F';
return 'X';
}
}
int main()
{
int T,n;
scanf("%d",&T);
while(T--){
scanf("%s",ss);
n=strlen(ss);
num=0; stack[0]='(';
ss[n]=')'; ss[n+1]='\0';
for(int i=0;i<=n;i++){
stack[++num]=ss[i];
if(stack[num]==')'){
num-=2;
if(stack[num+1]=='('){
stack[num+1]='\0'; continue;
}
while(stack[num]!='('){
if(stack[num]=='|'){
stack[num-1]=calc(stack[num-1],'|',stack[num+1]);
num-=2;
}else{
break;
}
}
if(stack[num]=='('){
stack[num]=stack[num+1];
if(stack[num]=='X' && num!=0) stack[num]='F';
}
}
while(stack[num]=='T'||stack[num]=='F'||stack[num]=='X'){
if(stack[num-1]=='!'){
stack[num-1]=ops(stack[num]);
num-=1;
}else{
break;
}
}
while(stack[num]=='T'||stack[num]=='F'||stack[num]=='X'){
if(stack[num-1]=='&'){
stack[num-2]=calc(stack[num-2],'&',stack[num]);
num-=2;
}else{
break;
}
}
stack[num+1]='\0';
//printf(">> %s\n",stack);
}
//printf("%s\n",stack);
if(stack[0]=='T'){
printf("0\n");
}else if(stack[0]=='F'){
printf("1\n");
}else if(stack[0]=='X'){
printf("2\n");
}else{
printf("1\n");
}
}
return 0;
}
|
3dfb257aed2bdbf050fc64f2929892c4c3526253
|
6958f617af0c5a76304ceb1006c77bc70ca0e195
|
/tests/cpp/transforms/inlining_test.cpp
|
6740a17ac7e5e2ee1cc4748f07c7059870db05df
|
[
"Apache-2.0"
] |
permissive
|
taichi-dev/taichi
|
3fae315a494f1c97392d5b931c939abbbfba1bdc
|
b30b511f55e3d0ebff765ee048d0aaa4ba9e7667
|
refs/heads/master
| 2023-09-02T13:28:18.208792
| 2023-08-23T23:22:43
| 2023-08-23T23:22:43
| 74,660,642
| 17,231
| 1,841
|
Apache-2.0
| 2023-09-14T11:29:32
| 2016-11-24T10:00:05
|
C++
|
UTF-8
|
C++
| false
| false
| 2,077
|
cpp
|
inlining_test.cpp
|
#include "gtest/gtest.h"
#include "taichi/ir/analysis.h"
#include "taichi/ir/ir_builder.h"
#include "taichi/ir/statements.h"
#include "taichi/ir/transforms.h"
#include "taichi/program/program.h"
namespace taichi::lang {
class InliningTest : public ::testing::Test {
protected:
void SetUp() override {
prog_ = std::make_unique<Program>();
prog_->materialize_runtime();
}
std::unique_ptr<Program> prog_;
};
TEST_F(InliningTest, ArgLoadOfArgLoad) {
IRBuilder builder;
// def test_func(x: ti.i32) -> ti.i32:
// return x + 1
auto *arg = builder.create_arg_load(/*arg_id=*/{0}, get_data_type<int>(),
/*is_ptr=*/false, /*arg_depth=*/0);
auto *sum = builder.create_add(arg, builder.get_int32(1));
builder.create_return(sum);
auto func_body = builder.extract_ir();
EXPECT_TRUE(func_body->is<Block>());
auto *func_block = func_body->as<Block>();
EXPECT_EQ(func_block->size(), 4);
auto *func = prog_->create_function(
FunctionKey("test_func", /*func_id=*/0, /*instance_id=*/0));
func->insert_scalar_param(get_data_type<int>());
func->insert_ret(get_data_type<int>());
func->set_function_body(std::move(func_body));
func->finalize_params();
func->finalize_rets();
// def kernel(x: ti.i32) -> ti.i32:
// return test_func(x)
auto *kernel_arg =
builder.create_arg_load(/*arg_id=*/{0}, get_data_type<int>(),
/*is_ptr=*/false, /*arg_depth=*/0);
auto *func_call = builder.create_func_call(func, {kernel_arg});
builder.create_return(func_call);
auto kernel_body = builder.extract_ir();
EXPECT_TRUE(kernel_body->is<Block>());
auto *kernel_block = kernel_body->as<Block>();
EXPECT_EQ(kernel_block->size(), 3);
irpass::type_check(kernel_block, CompileConfig());
irpass::inlining(kernel_block, CompileConfig(), {});
irpass::full_simplify(kernel_block, CompileConfig(), {false, false});
EXPECT_EQ(kernel_block->size(), 4);
EXPECT_TRUE(irpass::analysis::same_statements(func_block, kernel_block));
}
} // namespace taichi::lang
|
0ad60ef04d4d78235d8c2c8d52c919486d4f898c
|
048fddf3e02996a50163d014987d2a1e0f852b05
|
/20200425/p.cpp
|
5dd9528ab3b675a9f2e41f2cc96a713ab5690d11
|
[] |
no_license
|
muhammadali493/Competitive-coding
|
2a226d4214ea2a9c39dcd078d449d8791d80a033
|
0a6bb332fb2d05a4e647360a4c933e912107e581
|
refs/heads/master
| 2023-07-17T08:40:06.201930
| 2020-06-07T07:41:39
| 2020-06-07T07:41:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 828
|
cpp
|
p.cpp
|
#include <iostream>
using namespace std;
const int N = 100000 + 100;
int open[N][5];
int dp[N][5];
int n;
int main() {
ios::sync_with_stdio(false);
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= 4; j++) {
cin >> open[i][j];
}
}
dp[0][0] = 0;
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= 4; j++) {
dp[i][0] = max(dp[i][0], dp[i - 1][j]);
}
for (int j = 1; j <= 4; j++) {
if (open[i][j] == 0) continue;
for (int k = 0; k <= 4; k++) {
if (k == j) continue;
dp[i][j] = max(dp[i][j], dp[i - 1][k] + 1);
}
}
}
int ans = 0;
for (int i = 0; i < 5; i++) {
ans = max(ans, dp[n][i]);
}
cout << ans << endl;
return 0;
}
|
9458d39332ce39838d97a0de6d7c88a791680532
|
66c9d369172413174e8e21ed4049fc7a4fcbcba3
|
/矩阵乘法求斐波那契.cpp
|
b26d05909d78460b502c0732e7ba82aeed3dd2ef
|
[] |
no_license
|
Xrvitd/C_code
|
f145d629a0e3fc36eef4721f649ccaa2c0567f5d
|
caf03c0ccb2413ff4b768f1e7bddc882de3bb825
|
refs/heads/master
| 2020-03-10T04:56:45.196112
| 2018-04-12T07:02:54
| 2018-04-12T07:02:54
| 129,205,311
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 860
|
cpp
|
矩阵乘法求斐波那契.cpp
|
#include<iostream>
using namespace std;
long long n,m,f;
struct zqm
{
int a[3][3];
}q[10001],p;
zqm c(zqm x,zqm y)
{
zqm s;
s.a[1][1]=x.a[1][1]*y.a[1][1]+x.a[1][2]*y.a[2][1];
s.a[1][2]=x.a[1][1]*y.a[1][2]+x.a[1][2]*y.a[2][2];
s.a[2][1]=x.a[2][1]*y.a[1][1]+x.a[2][2]*y.a[2][1];
s.a[2][2]=x.a[2][1]*y.a[1][2]+x.a[2][2]*y.a[2][2];
return s;
}
void debug(zqm x)
{
for(int i=1;i<=2;i++)
{
for(int j=1;j<=2;j++)
{
cout<<x.a[i][j]<<" ";
}cout<<endl;
}
cout<<endl;
}
zqm ksm(zqm x,int m)
{
zqm ans=p;
for(;m;m>>=1,x=c(x,x))
{
if(m&1)
{
ans=c(ans,x);
}
}
return ans;
}
int main()
{
cin>>n;
p.a[1][1]=1;
p.a[1][2]=1;
p.a[2][2]=0;
p.a[2][1]=1;
zqm q;
q=p;
/*for(int i=1;i<=10;i++)
{
q=c(q,p);
debug(q);
}*/
zqm zq=ksm(p,n-3);
f=zq.a[1][1]+zq.a[1][2];
cout<<f;
}
|
89ba1c0e5e3723025c08802700c5c361a44168c2
|
91c38d6739ef7eb47455396371cb75f0a668c9ff
|
/test/CompilationTests/LambdaTests/Catcher/LValue.cpp
|
760bd014e35e2f71eb12eb7a1b5b698d80588ca7
|
[
"MIT"
] |
permissive
|
rocky01/promise
|
8256ab0d2e599f690f31e6b035e1ae67293e60a1
|
638415a117207a4cae9181e04114e1d7575a9689
|
refs/heads/master
| 2020-04-01T09:14:14.878034
| 2018-10-15T07:31:16
| 2018-10-15T07:31:16
| 153,066,476
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 965
|
cpp
|
LValue.cpp
|
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "Promise.hpp"
using namespace prm;
struct Bools
{
bool first;
bool second;
};
class CatcherLambdaResolveRejectLValue: public ::testing::TestWithParam<Bools>
{ };
INSTANTIATE_TEST_CASE_P(
TestWithParameters, CatcherLambdaResolveRejectLValue, testing::Values(
Bools{false, false},
Bools{false, true},
Bools{true, false},
Bools{true, true}
));
// ExeVoid, ResolveT, RejectT
// ExeT, ResolveT, RejectT
TEST_P(CatcherLambdaResolveRejectLValue, ERRErrorResolveRethrow)
{
auto lv = [this](double e, Resolver<char> resolve, Rethrower<int> rethrow) {
ASSERT_TRUE(3.0 == e);
return GetParam().second ? resolve('w') : rethrow(5);
};
make_promise([this](int e, Resolver<char> resolve, Rejector<double> reject) {
ASSERT_TRUE(10 == e);
return GetParam().first ? resolve('w') : reject(3.0);
})
.catcher(lv)
.startExecution(10);
}
|
e6ce5287406229557b1f973e4edc7075bc3d0315
|
a65e50b0df7b0bec719bc8d6e2206ce11046cc72
|
/osf-to-esf/dbsk2d/algo/dbsk2d_ishock_transform_sptr.h
|
4660a8bf09a368cd25d0fe464d7a10431815e98a
|
[
"MIT"
] |
permissive
|
wenhanshi/lemsvxl-shock-computation
|
fe91c7ca73f9260533fe9393ccef60ac5ef45077
|
1208e5f6a0c9fddbdffcc20f2c1d914e07015b45
|
refs/heads/master
| 2021-05-07T08:24:21.197895
| 2017-11-15T13:37:59
| 2017-11-15T13:37:59
| 109,273,353
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 262
|
h
|
dbsk2d_ishock_transform_sptr.h
|
#ifndef dbsk2d_ishock_transform_sptr_h
#define dbsk2d_ishock_transform_sptr_h
class dbsk2d_ishock_transform;
#include <vbl/vbl_smart_ptr.h>
typedef vbl_smart_ptr<dbsk2d_ishock_transform> dbsk2d_ishock_transform_sptr;
#endif // dbsk2d_ishock_transform_sptr_h
|
0e646d38c3d98a961064b69e1e67e2525442823f
|
a1a3d5ed46ca8e72a34eefcc993ff350279e5968
|
/EC_8Queens.cpp
|
8dfa57d5f52179fc45357b63d820ce39a509adbb
|
[] |
no_license
|
jasoncs1997/8-queens-problem-
|
2f4424846416310b6d938530df79f37ccf681a78
|
6754dfa2f75b5951aed631098c7e9b323ecb5533
|
refs/heads/master
| 2020-03-29T18:17:49.308982
| 2018-09-25T03:42:37
| 2018-09-25T03:42:37
| 150,203,888
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,619
|
cpp
|
EC_8Queens.cpp
|
/**~*~*
8 Queens Problem
Extra Credit: This program prints one solution to the 8 Queens Puzzle.
Change it to display and count all solutions.
Run the program and save the output as a comment at the end of the source file
NAME:HUY DUC DAO 22C
*~**/
#include <iostream>
#include <iomanip>
#include <string>
#include "StackADT.h"
using namespace std;
const int SIZE = 30;
int getValidSize(int low, int high, string msg);
bool threatened(int board[][SIZE], int row, int col, int boardSize);
void placeQueens(Stack<int> *stack, int boardSize,int row, int col,int board[][SIZE],int &);
void printBoard(Stack<int> *stack, int boardSize);
int main ( void )
{
int count = 0;//keep count of how many possible solutions
int boardSize;
Stack<int> *stack = new Stack<int>;
cout << "\n\t **~*~** Eight Queens problem **~*~** \n\n"
"\t Place a queen in each row of the board\n"
"\t so that no two queens threaten each other. \n";
boardSize = getValidSize (4, SIZE, "the board size: ");
int row, col;
int board[SIZE][SIZE] = { 0 }; // 0 no queen: 1 queen
row = 0;
col = -1;
placeQueens(stack, boardSize,row, col,board,count);
cout << "\n\t **~*~** THE END **~*~** \n\n";
system("PAUSE");
return 0;
}
/**~*~*
This function prompts the user to enter an integer number within a given range
If the input is not valid (not a number or if it is outside of the range) it
prompts the user to enter a new number, until the input is valid.
*~**/
int getValidSize(int low, int high, string msg)
{
int num;
do
{
cout << "\nPlease enter " << msg << " (" << low << " to " << high << "): ";
cin >> num;
cin.clear(); // to clear the error flag
cin.ignore(80, '\n'); // to discard the unwanted input from the input buffer
}while(cin.fail() || num < low || num > high);
return num;
}
/**~*~*
Position queens on a game board so that no queen
can capture any other queen.
*~**/
void placeQueens(Stack<int> *stack, int boardSize,int row, int col,int board[SIZE][SIZE],int &count)
{
while (row < boardSize)
{
while (col < boardSize && row < boardSize)
{
col++;
if (!threatened(board, row, col, boardSize))
{
board[row][col] = 1;
stack->push(col);
row++;
col = -1;
}
while (col >= boardSize - 1)
{
if (stack->isEmpty())
{
cout << "There is a total of " << count << " possible solutions" << endl;
return;
}
else
{
stack->pop(col);
row--;
board[row][col] = 0;
}
}
//check if the stack is full of size
//if so, the program will start printing the solution
if (stack->getCount() == boardSize)
{
cout << "Solution #:" << count + 1 << endl;
printBoard(stack, boardSize);
stack->pop(col);
row--;
board[row][col] = 0;//backtracking
count++;
}
}
}
}
/**~*~*
Checks rows, columns, and diagonals for threatening queens
- board contains current positions for queens.
- row and col are position for new queen
- boardSize is number of rows and cols in board.
- returns true if guarded; false if not guarded
*~**/
bool threatened(int board[][SIZE], int row, int col, int boardSize)
{
int r, c;
// Check current col for a queen
c = col;
for (r = 0; r < row; r++)
if (board[r][c] == 1)
return true;
// Check diagonal right-up
for (r = row - 1, c = col + 1; r > -1 && c < boardSize; r--, c++)
if (board[r][c] == 1)
return true;
// Check diagonal left-up
for (r = row - 1, c = col - 1; r > -1 && c > -1; r--, c--)
if (board[r][c] == 1)
return true;
return false;
}
/**~*~*
Print positions of chess queens on a game board
- stack contains positions of queen.
- boardSize is the number of rows and columns
*~**/
void printBoard (Stack<int> *stack, int boardSize)
{
int col, stCol;
Stack<int> *pOutStack = new Stack<int>;
if (stack->isEmpty())
{
cout << "There are no positions on this board\n";
return;
}
if (boardSize > 16)
{
cout << "Only boards <= 16 are printed!\n";
return;
}
// Reverse stack
while (!stack->isEmpty())
{
stack->pop(stCol);
pOutStack->push(stCol);
}
// Print Column numbers
cout << "\n ";
for(int i = 0; i < boardSize; i++)
cout << setw(3) << i + 1 << "|";
cout << endl;
// print divider
cout << " ";
for(int i = 0; i < boardSize; i++)
cout << "--- ";
cout << endl;
// print board
int row = 0;
while (!pOutStack->isEmpty())
{
pOutStack->pop(stCol);
stack->push(stCol);//building the stack all over again
cout << "(" << setw(2) << row + 1 << ", " << setw(2) << stCol + 1 << "} |";
for (col = 0; col < boardSize; col++)
{
if (stCol == col)
cout << " Q |";
else
cout << " |";
}
cout << endl;
cout << " ";
for(int i = 0; i < boardSize; i++)
{
cout << "--- ";
}
cout << endl;
row++;
}
}
/**~*~*
**~*~** Eight Queens problem **~*~**
Place a queen in each row of the board
so that no two queens threaten each other.
Please enter the board size: (4 to 30): 5
1| 2| 3| 4| 5|
--- --- --- --- ---
( 1, 1} | Q | | | | |
--- --- --- --- ---
( 2, 3} | | | Q | | |
--- --- --- --- ---
( 3, 5} | | | | | Q |
--- --- --- --- ---
( 4, 2} | | Q | | | |
--- --- --- --- ---
( 5, 4} | | | | Q | |
--- --- --- --- ---
**~*~** THE END **~*~**
Process returned 0 (0x0) execution time : 1.685 s
*~**/
/**~*~*
**~*~** Eight Queens problem **~*~**
Place a queen in each row of the board
so that no two queens threaten each other.
Please enter the board size: (4 to 30): 30
Only boards <= 16 are printed!
**~*~** THE END **~*~**
Process returned 0 (0x0) execution time : 140.509 s
*~**/
/*
**~*~** Eight Queens problem **~*~**
Place a queen in each row of the board
so that no two queens threaten each other.
Please enter the board size: (4 to 30): 5
Solution #:1
1| 2| 3| 4| 5|
--- --- --- --- ---
( 1, 1} | Q | | | | |
--- --- --- --- ---
( 2, 3} | | | Q | | |
--- --- --- --- ---
( 3, 5} | | | | | Q |
--- --- --- --- ---
( 4, 2} | | Q | | | |
--- --- --- --- ---
( 5, 4} | | | | Q | |
--- --- --- --- ---
Solution #:2
1| 2| 3| 4| 5|
--- --- --- --- ---
( 1, 1} | Q | | | | |
--- --- --- --- ---
( 2, 4} | | | | Q | |
--- --- --- --- ---
( 3, 2} | | Q | | | |
--- --- --- --- ---
( 4, 5} | | | | | Q |
--- --- --- --- ---
( 5, 3} | | | Q | | |
--- --- --- --- ---
Solution #:3
1| 2| 3| 4| 5|
--- --- --- --- ---
( 1, 2} | | Q | | | |
--- --- --- --- ---
( 2, 4} | | | | Q | |
--- --- --- --- ---
( 3, 1} | Q | | | | |
--- --- --- --- ---
( 4, 3} | | | Q | | |
--- --- --- --- ---
( 5, 5} | | | | | Q |
--- --- --- --- ---
Solution #:4
1| 2| 3| 4| 5|
--- --- --- --- ---
( 1, 2} | | Q | | | |
--- --- --- --- ---
( 2, 5} | | | | | Q |
--- --- --- --- ---
( 3, 3} | | | Q | | |
--- --- --- --- ---
( 4, 1} | Q | | | | |
--- --- --- --- ---
( 5, 4} | | | | Q | |
--- --- --- --- ---
Solution #:5
1| 2| 3| 4| 5|
--- --- --- --- ---
( 1, 3} | | | Q | | |
--- --- --- --- ---
( 2, 1} | Q | | | | |
--- --- --- --- ---
( 3, 4} | | | | Q | |
--- --- --- --- ---
( 4, 2} | | Q | | | |
--- --- --- --- ---
( 5, 5} | | | | | Q |
--- --- --- --- ---
Solution #:6
1| 2| 3| 4| 5|
--- --- --- --- ---
( 1, 3} | | | Q | | |
--- --- --- --- ---
( 2, 5} | | | | | Q |
--- --- --- --- ---
( 3, 2} | | Q | | | |
--- --- --- --- ---
( 4, 4} | | | | Q | |
--- --- --- --- ---
( 5, 1} | Q | | | | |
--- --- --- --- ---
Solution #:7
1| 2| 3| 4| 5|
--- --- --- --- ---
( 1, 4} | | | | Q | |
--- --- --- --- ---
( 2, 1} | Q | | | | |
--- --- --- --- ---
( 3, 3} | | | Q | | |
--- --- --- --- ---
( 4, 5} | | | | | Q |
--- --- --- --- ---
( 5, 2} | | Q | | | |
--- --- --- --- ---
Solution #:8
1| 2| 3| 4| 5|
--- --- --- --- ---
( 1, 4} | | | | Q | |
--- --- --- --- ---
( 2, 2} | | Q | | | |
--- --- --- --- ---
( 3, 5} | | | | | Q |
--- --- --- --- ---
( 4, 3} | | | Q | | |
--- --- --- --- ---
( 5, 1} | Q | | | | |
--- --- --- --- ---
Solution #:9
1| 2| 3| 4| 5|
--- --- --- --- ---
( 1, 5} | | | | | Q |
--- --- --- --- ---
( 2, 2} | | Q | | | |
--- --- --- --- ---
( 3, 4} | | | | Q | |
--- --- --- --- ---
( 4, 1} | Q | | | | |
--- --- --- --- ---
( 5, 3} | | | Q | | |
--- --- --- --- ---
Solution #:10
1| 2| 3| 4| 5|
--- --- --- --- ---
( 1, 5} | | | | | Q |
--- --- --- --- ---
( 2, 3} | | | Q | | |
--- --- --- --- ---
( 3, 1} | Q | | | | |
--- --- --- --- ---
( 4, 4} | | | | Q | |
--- --- --- --- ---
( 5, 2} | | Q | | | |
--- --- --- --- ---
There is a total of 10 possible solutions
**~*~** THE END **~*~**
Press any key to continue . . .
*/
|
52be40f0c3866b20a3335b0d596bf808a8c79cb4
|
0b88599a7bf318d06117f6c29c653a978b3f07a6
|
/libdialogutil/dialogbase.h
|
2e18be94d1e60aa196ac29a16c7f0b832cc695a3
|
[] |
no_license
|
KDE/kooka
|
21571d9066e253532dfade2d76a73cc7505f598b
|
a03ddf8091cbebedd9ef5479431c474642ca81b5
|
refs/heads/master
| 2023-08-30T17:35:23.977260
| 2023-08-29T01:35:32
| 2023-08-29T01:35:32
| 42,732,867
| 6
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,721
|
h
|
dialogbase.h
|
/************************************************************************
* *
* This file is part of Kooka, a scanning/OCR application using *
* Qt <http://www.qt.io> and KDE Frameworks <http://www.kde.org>. *
* *
* Copyright (C) 2016 Jonathan Marten <jjm@keelhaul.me.uk> *
* *
* Kooka is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation and appearing in the *
* file COPYING included in the packaging of this file; either *
* version 2 of the License, or (at your option) any later version. *
* *
* As a special exception, permission is given to link this program *
* with any version of the KADMOS OCR/ICR engine (a product of *
* reRecognition GmbH, Kreuzlingen), and distribute the resulting *
* executable without including the source code for KADMOS in the *
* source distribution. *
* *
* 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; see the file COPYING. If *
* not, see <http://www.gnu.org/licenses/>. *
* *
************************************************************************/
#ifndef DIALOGBASE_H
#define DIALOGBASE_H
#include <qdialog.h>
#include <qdialogbuttonbox.h>
#include "libdialogutil_export.h"
class QShowEvent;
class QSpacerItem;
class KGuiItem;
class KConfigGroup;
class DialogStateWatcher;
class DialogStateSaver;
/**
* @short A wrapper for QDialog incorporating some convenience functions.
*
* This is a lightweight wrapper around QDialog, incorporating some useful
* functions which used to be provided by KDialog in KDE4. These are:
*
* - Managing the button box and providing access to its buttons
* - Managing the top level layout
* - Saving and restoring the dialog size
*
* @author Jonathan Marten
**/
class LIBDIALOGUTIL_EXPORT DialogBase : public QDialog
{
Q_OBJECT
public:
/**
* Destructor.
*
**/
virtual ~DialogBase() = default;
/**
* Retrieve the main widget.
*
* @return the main widget
**/
QWidget *mainWidget() const { return (mMainWidget); }
/**
* Set a state saver for the dialog.
*
* This may be a subclass of a DialogStateSaver, reimplemented in
* order to save special dialog settings (e.g. the column states of
* a list view). If this is not set then a plain DialogStateSaver
* will be created and used internally. If a nullptr state saver is
* set explicitly using this function, then no state restoring or
* saving will be done.
*
* @param saver the state saver
*
* @note The saver should be set before the dialog is shown for
* the first time.
* @see DialogStateSaver
**/
void setStateSaver(DialogStateSaver *saver);
/**
* Access the state saver used by the dialog.
*
* This may be the default one, or that set by @c setStateSaver().
*
* @return the state saver
**/
DialogStateSaver *stateSaver() const;
/**
* Access the state watcher used by the dialog.
*
* This is created and used internally.
*
* @return the state watcher
**/
DialogStateWatcher *stateWatcher() const { return (mStateWatcher); }
/**
* Get a vertical spacing suitable for use within the dialog layout.
*
* @return The spacing hint
**/
static int verticalSpacing();
/**
* Get a horizontal spacing suitable for use within the dialog layout.
*
* @return The spacing hint
**/
static int horizontalSpacing();
/**
* Create a spacer item suitable for use within a vertical layout.
*
* @return The spacer item
**/
static QSpacerItem *verticalSpacerItem();
/**
* Create a spacer item suitable for use within a horizontal layout.
*
* @return The spacer item
**/
static QSpacerItem *horizontalSpacerItem();
/**
* Access the dialog's button box.
*
* @return the button box
**/
QDialogButtonBox *buttonBox() const { return (mButtonBox); }
/**
* Set the standard buttons to be displayed within the button box.
*
* @param buttons The buttons required
*
* @note This can be called at any time and the buttons will change
* accordingly. However, the buttons will be regenerated which means
* that any special button text or icons, or any signal connections from
* them, will be lost.
**/
void setButtons(QDialogButtonBox::StandardButtons buttons);
/**
* Set the enable state of a button.
*
* @param button The button to set
* @param state The enable state for the button
**/
void setButtonEnabled(QDialogButtonBox::StandardButton button, bool state = true);
/**
* Set the text of a button.
*
* @param button The button to set
* @param state The new text for the button
*
* @note This can be called at any time, and the button will change
* accordingly.
**/
void setButtonText(QDialogButtonBox::StandardButton button, const QString &text);
/**
* Set the icon of a button.
*
* @param button The button to set
* @param state The new icon for the button
*
* @note This can be called at any time, and the button will change
* accordingly.
**/
void setButtonIcon(QDialogButtonBox::StandardButton button, const QIcon &icon);
/**
* Set up a button from a @c KGuiItem.
*
* @param button The button to set
* @param guiItem The @c KGuiItem for the button
*
* @note This can be called at any time, and the button will change
* accordingly.
**/
void setButtonGuiItem(QDialogButtonBox::StandardButton button, const KGuiItem &guiItem);
protected:
/**
* Constructor.
*
* @param pnt Parent widget
**/
explicit DialogBase(QWidget *pnt = nullptr);
/**
* Set the main widget to be displayed within the dialog.
*
* @param w The widget
**/
void setMainWidget(QWidget *w) { mMainWidget = w; }
/**
* @reimp
**/
void showEvent(QShowEvent *ev) override;
private:
QDialogButtonBox *mButtonBox;
QWidget *mMainWidget;
DialogStateWatcher *mStateWatcher;
};
#endif // DIALOGBASE_H
|
c6df17e9778996f9f049aed59df0c8bc7beb1d58
|
1e66d7d55cae697268616d9c3bb5722eff540d69
|
/proyecto/cpersona.h
|
5071ac03cc79225f280550bd1663bddd2b8e8bd4
|
[] |
no_license
|
ChristianSnchz/QT
|
14a97f38d7d46aa0f13105a0042c996c0cdbd96d
|
071830a2e4c409f90c442c1edff0f0289538fca2
|
refs/heads/master
| 2021-01-17T17:52:57.142534
| 2016-10-12T04:07:27
| 2016-10-12T04:07:27
| 70,661,446
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 759
|
h
|
cpersona.h
|
/**
@file cpersona.h
@brief Declaracion de la clase cPersona
Contiene los atributos y metodos de la clase
@Author Caceres, Jesus. Sanchez, Christian
@date 07/2015
*/
#ifndef CPERSONA_H
#define CPERSONA_H
#include <string>
class cPersona
{
private:
std::string nombre;
std::string cedula;
std::string direccion;
std::string telefono;
public:
cPersona();
~cPersona(){};
std::string verNombre() const;
std::string verCedula() const;
std::string verDireccion() const;
std::string verTelefono() const;
void setNombre(std::string);
void setCedula(std::string);
void setDireccion(std::string);
void setTelefono(std::string);
};
#endif // CPERSONA_H
|
c942ba2f7dd22379cbcc772b638025b965850c86
|
c51febc209233a9160f41913d895415704d2391f
|
/library/ATF/_OBJECT_TYPE_LIST.hpp
|
fca7e11ccd22ca126b186c5ce4054e62bb73c6a4
|
[
"MIT"
] |
permissive
|
roussukke/Yorozuya
|
81f81e5e759ecae02c793e65d6c3acc504091bc3
|
d9a44592b0714da1aebf492b64fdcb3fa072afe5
|
refs/heads/master
| 2023-07-08T03:23:00.584855
| 2023-06-29T08:20:25
| 2023-06-29T08:20:25
| 463,330,454
| 0
| 0
|
MIT
| 2022-02-24T23:15:01
| 2022-02-24T23:15:00
| null |
UTF-8
|
C++
| false
| false
| 342
|
hpp
|
_OBJECT_TYPE_LIST.hpp
|
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <_GUID.hpp>
START_ATF_NAMESPACE
struct _OBJECT_TYPE_LIST
{
unsigned __int16 Level;
unsigned __int16 Sbz;
_GUID *ObjectType;
};
END_ATF_NAMESPACE
|
4e23a2bef0a15b7ef6009b780ce9ddcc5e174393
|
46c5bab97ed043c5cc60c82884c1afa3d9a6689e
|
/src/SuccessState.hpp
|
de672c2723322cdf50b12f66518c69059b4c1714
|
[] |
no_license
|
Lucy-CH/cpp_CW4
|
424b3c6ea2fd02a2c3c0c248359492df9ab4d6a0
|
4700b2bd7fc7158be84f2e161e0fd8ee07034262
|
refs/heads/master
| 2022-07-17T08:28:49.127533
| 2020-05-19T09:53:31
| 2020-05-19T09:53:31
| 255,769,751
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 600
|
hpp
|
SuccessState.hpp
|
//
// SuccessState.hpp
// SDL2_App
//
// Created by Le Cheng on 19/05/2020.
//
#pragma once
#include "State.hpp"
#include "Psylc7Engine.hpp"
#ifndef DeathState_hpp
#define DeathState_hpp
#include <stdio.h>
#endif /* DeathState_hpp */
class SuccessState
: public State
{
public:
SuccessState(Psylc7Engine* pEngine);
~SuccessState();
void SetUpBackgroundBuffer();
void virtDrawStringsOnTop();
void virtKeyDown(int iKeyCode);
void InitialiseObjects();
void update();
void MouseDown(int iButton, int iX, int iY);
int changeoffset();
protected:
SimpleImage image;
};
|
4a6f835cebc4693ba34827ac8e3c491e5adc6349
|
ece1237e78a64ffab0f52c5f8c12ed1d2a1cef07
|
/28_数组中出现次数超过一半的数字/solution.cc
|
3a82f34c22ad5fab331fdbb78a26bad1dd1a1a33
|
[] |
no_license
|
zbqxyz/jianzhi_offer
|
4b88ec5f6e88628542b54f9c34c5d1558a6354eb
|
182e96d94d9d318899de58fede510f4afae68223
|
refs/heads/master
| 2020-04-22T09:31:39.114390
| 2018-08-21T15:10:42
| 2018-08-21T15:10:42
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 662
|
cc
|
solution.cc
|
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int MoreThanHalfNum_Solution(vector<int> numbers) {
int res = numbers[0];
int balance = 1;
for (int i = 0; i < numbers.size(); i++) {
if (balance == 0) {
res = numbers[i];
balance = 1;
} else if (numbers[i] == numbers[i - 1])
balance++;
else
balance--;
}
if (validInput(numbers, res) == false)
res = 0;
return res;
}
bool validInput(vector<int> &numbers, int result) {
int cnt = 0;
for (auto i : numbers) {
if (i == result)
cnt++;
}
return 2 * cnt > numbers.size();
}
};
|
d5d0d711b6c27b08fb760cf27d8bb22a319a1078
|
ef23ae86df646cd3192b62066ec8abbdb6a26426
|
/dev/g++/projects/embedded/demos/tcp_echo/src/tcp_echo.cc
|
12f783a631deff00b84748707272586f43e60c2c
|
[
"MIT"
] |
permissive
|
YannGarcia/repo
|
9e3c43248814a9084a5ab9480c352a8f17e9076b
|
0f3de24c71d942c752ada03c10861e83853fdf71
|
refs/heads/master
| 2021-06-15T22:25:21.873408
| 2021-05-06T06:22:14
| 2021-05-06T06:22:14
| 74,947,093
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,694
|
cc
|
tcp_echo.cc
|
/*!
* \file tcp_echo.cpp
* \brief tcp_echo class implementation file
* \author garciay.yann@gmail.com
* \copyright Copyright (c) 2017 ygarcia. All rights reserved
* \license This project is released under the MIT License
* \version 0.1
*/
#include "tcp_echo.hh"
tcp_echo::tcp_echo(const std::string& p_address, const uint16_t p_port, logger::logger& p_logger) :
_logger(p_logger),
_addr(p_address, p_port) {
_channel = channel_manager::get_instance().create_channel(channel_type::tcp, _addr);
if (_channel < 0) {
throw std::string("tcp_echo::tcp_echo: Cannot create the channel");
}
// Connect to host
_logger.info("tcp_echo::tcp_echo: _channel= %d", _channel);
int32_t result = channel_manager::get_instance().get_channel(_channel).connect();
if (result < 0) {
throw std::string("tcp_echo::tcp_echo: Failed connect to the server");
}
uint32_t tries = 0;
do {
std::vector<uint32_t> fds;
std::vector<uint32_t> s;
s.push_back(_channel);
channel_manager::get_instance().poll_channels(1000, s, fds); // 1000 ms
_logger.info("tcp_echo::tcp_echo: 0000: %d", fds.size());
std::vector<uint32_t>::iterator it = std::find(fds.begin(), fds.end(), _channel);
_logger.info("tcp_echo::tcp_echo: 1111");
if (it != fds.end()) { // Some data are available
break;
}
_logger.info("tcp_echo::tcp_echo: 2222");
} while (tries++ < 5);
if (tries == 5) { // Some data are available
throw std::string("tcp_echo::tcp_echo: Cannot connect to the server");
}
_logger.info("tcp_echo::tcp_echo: 3333");
} // End of ctor
tcp_echo::~tcp_echo() {
channel_manager::get_instance().get_channel(_channel).disconnect();
channel_manager::get_instance().remove_channel(_channel);
} // End of dtor
int32_t tcp_echo::send(const std::string& p_message) {
_logger.info("Client send %s", p_message.c_str());
std::vector<uint8_t> buffer(p_message.cbegin(), p_message.cend());
return channel_manager::get_instance().get_channel(_channel).write(buffer);
}
int32_t tcp_echo::receive(std::string& p_message) {
std::vector<uint8_t> buffer(128, 0x00);
std::vector<uint32_t> fds;
channel_manager::get_instance().poll_channels(1000, fds); // 1000 ms
std::vector<uint32_t>::iterator it = std::find(fds.begin(), fds.end(), _channel);
int32_t result = -1;
if (it != fds.end()) {
_logger.info("tcp_echo: New incoming data...");
result = channel_manager::get_instance().get_channel(_channel).read(buffer);
_logger.info("Client receive result = %d", result);
if (result != -1) {
p_message.assign(buffer.cbegin(), buffer.cend());
} else {
p_message = "";
}
}
return result;
}
|
7544ee82d1740c0ff7fed927cf600289a7b137ed
|
f83ef53177180ebfeb5a3e230aa29794f52ce1fc
|
/ACE/ACE_wrappers/TAO/examples/AMH/Sink_Server/MT_AMH_Server.cpp
|
33e6ccb54ab4a66ff3c82c72f245f473ca5e93b6
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-sun-iiop",
"Apache-2.0"
] |
permissive
|
msrLi/portingSources
|
fe7528b3fd08eed4a1b41383c88ee5c09c2294ef
|
57d561730ab27804a3172b33807f2bffbc9e52ae
|
refs/heads/master
| 2021-07-08T01:22:29.604203
| 2019-07-10T13:07:06
| 2019-07-10T13:07:06
| 196,183,165
| 2
| 1
|
Apache-2.0
| 2020-10-13T14:30:53
| 2019-07-10T10:16:46
| null |
UTF-8
|
C++
| false
| false
| 1,967
|
cpp
|
MT_AMH_Server.cpp
|
#include "MT_AMH_Server.h"
#include "tao/Strategies/advanced_resource.h"
#include "ace/Task.h"
#include "ace/Get_Opt.h"
MT_AMH_Server::MT_AMH_Server (int &argc, ACE_TCHAR **argv)
: Base_Server (argc, argv)
{
}
MT_AMH_Server::~MT_AMH_Server (void)
{
}
void
MT_AMH_Server::usage (const char *message)
{
static const char * usage =
"invoke as: mt_server -o <ior_output_file>\n"
" -n <num_threads>\n"
"-s <sleep_time (in microseconds)>\n";
// @@ Mayur, why don't you just place the usage message directly in
// the below ACE_ERROR macro? It's not a big deal. It's just
// something we normally do.
//
// Mayur: Seems cleaner to me this way.
ACE_ERROR ((LM_ERROR, "%C : %C", message, usage));
}
int
MT_AMH_Server::parse_args (void)
{
// Let the base server parse it's argumrents first
if (Base_Server::parse_args () != 1)
{
this->usage ("");
ACE_OS::exit (1);
}
ACE_Get_Opt get_opts (this->argc_, this->argv_, ACE_TEXT("n:"));
int c;
int count_argv = 0;
while ((c = get_opts ()) != -1)
{
++count_argv;
switch (c)
{
case 'n':
{
this->nthreads_ = ACE_OS::atoi (get_opts.opt_arg ());
{
// Added unneeded '{ & }' just to satisfy Win32
for (int i = count_argv; i <= this->argc_; ++i)
this->argv_ [i] = this->argv_ [i+2];
}
// Decrement the value of this->argc_ to reflect the removal
// of '-n' option.
this->argc_ = this->argc_ - 2;
return 1;
}
case '?':
default:
// Don't do anything.
break;
}
}
return 0;
}
void
MT_AMH_Server::start_threads (void)
{
// Each of this thread runs the event loop
this->activate (THR_NEW_LWP | THR_JOINABLE, this->nthreads_, 1);
this->thr_mgr ()->wait ();
}
int
MT_AMH_Server::svc (void)
{
run_event_loop ();
return 1;
}
|
74b0a4a0a5879621de29c0cb1aa2882abf80082e
|
6502a0aab23adfdf482bfeb02f6bf85e113add37
|
/TetrisApp/TetrisApp/CBlockT.h
|
9ab8cf60890f3452b308a35f66fa1fc72d143196
|
[] |
no_license
|
netddigi/TetrisGame
|
15b4cf10b3d9dd79d9a1285b1cba6ee8b85848e9
|
47062f48ca4644f96a889785b62a26e21ffa711e
|
refs/heads/master
| 2021-01-19T15:16:14.169680
| 2017-08-21T14:44:06
| 2017-08-21T14:44:06
| 100,954,867
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 166
|
h
|
CBlockT.h
|
#pragma once
#include "CBlock.h"
class CBlockT : CBlock
{
public:
CBlockT();
void ChangeDirection() override;
void ChangePosition() override;
public:
private:
};
|
d32176a12432f0d920bd1aaa663e8c3de3f85a23
|
9c21a1f7caf0b889201414e5a97c5e2a3147d0cc
|
/Dogodo/Dogodo/ContentProvider.cpp
|
70a44a7e70b981af43b6807bf8343fe4880fa8f3
|
[] |
no_license
|
dlCdS/Dev
|
f95a2e41b71de2ea562c268e713e3879ac74e3b4
|
304ee4cbef803f98d1017927fddb3b036ffcf165
|
refs/heads/master
| 2022-01-13T00:33:19.449933
| 2021-10-25T14:40:08
| 2021-10-25T14:40:08
| 220,112,062
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,232
|
cpp
|
ContentProvider.cpp
|
#include "ContentProvider.h"
ContentProvider ContentProvider::_sing = ContentProvider();
ContentProvider::ContentProvider() : Widgetable("Content_Provider", true)
{
}
std::string ContentProvider::XMLName() const
{
return "ContentProvider";
}
void ContentProvider::associate()
{
WAssociateWidget("Left", new ContainerWidget(square_d(-1, -1, 0.3, 1)));
WAssociateWidget("Left:Up", new ContainerWidget(square_d(-1, -1, 1, 0.2)));
WAssociateWidget("Left:Up:Ressource", new ListWidget());
WAssociateWidget("Left:Up:Ressource:Title", new ContainerWidget());
WAssociateWidget("Left:Up:Ressource:Display", RessourceProvider::GetContainer());
WAssociateWidget("Left:Down", new ContainerWidget(square_d(-1, 0.2, 1, 0.8)));
WAssociateWidget("Right", new ContainerWidget(square_d(0.3, 0, 0.7, 1)));
WAddPage("Ressources", "Left:Up:Ressource:Title", RessourceProvider::GetSingleton());
}
ContentProvider::~ContentProvider()
{
}
void ContentProvider::Init()
{
_sing._container.freeAll();
_sing.load(CONTENT_PROVIDER_FILENAME);
}
void ContentProvider::Build()
{
_sing.build();
}
Widget * ContentProvider::GetContainer()
{
return _sing.getContainer();
}
Widgetable * ContentProvider::GetSingleton()
{
return &_sing;
}
|
0f1944aba26d358a2372bfa723f6446aa833442d
|
d7b528318a4e1b0892fd68e47c4584ec733d3dcc
|
/Hacker-Rank/c++/structs.cpp
|
264d4e370731edfbd6533506c1810b468064258c
|
[] |
no_license
|
mehrankamal/vigilant-coder
|
7a30b5b12258322734433466fb068f19ddcc52da
|
da893adaad71b557842f36e5d76b2a963ef4234b
|
refs/heads/master
| 2020-04-30T03:16:54.157697
| 2019-12-09T20:27:13
| 2019-12-09T20:27:13
| 176,582,729
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 489
|
cpp
|
structs.cpp
|
//Problem:
//Link:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
struct Student
{
int age;
string firstName;
string lastName;
int standard;
};
int main() {
Student st;
cin >> st.age >> st.firstName >> st.lastName >> st.standard;
cout << st.age << " " << st.firstName << " " << st.lastName << " " << st.standard;
return 0;
}
|
91f26d706f2fd550edd2f49ed109af917b6e5fbb
|
0b6d89f6b34e8f556daa7637b0b017ffef0afe01
|
/src/ff_eam.cpp
|
3a12f5b8706b2c5de28c69ebf7b04a8f6a72c20b
|
[] |
no_license
|
jpdu/MAPP
|
199dc2a5dbd40b68ec3c2033527a8ea46a96b56a
|
43e00f8f9d87c0a2a645f33dcaf62bb7c13fcfa3
|
refs/heads/master
| 2021-01-15T12:31:57.249273
| 2015-11-24T22:34:09
| 2015-11-24T22:34:09
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,918
|
cpp
|
ff_eam.cpp
|
#include <stdlib.h>
#include "neighbor.h"
#include "ff_eam.h"
#include "atom_types.h"
#include "error.h"
#include "memory.h"
using namespace MAPP_NS;
enum{NOT_SET,FUNC_FL,SET_FL,FINNIS_FL};
/*--------------------------------------------
constructor
--------------------------------------------*/
ForceField_eam::
ForceField_eam(MAPP* mapp):ForceFieldMD(mapp)
{
if(mapp->mode!=MD_mode)
error->abort("ff eam works only "
"for md mode");
max_pairs=0;
eam_reader=NULL;
}
/*--------------------------------------------
destructor
--------------------------------------------*/
ForceField_eam::~ForceField_eam()
{
delete eam_reader;
}
/*--------------------------------------------
force calculation
--------------------------------------------*/
void ForceField_eam::
force_calc(bool st_clc)
{
if(max_pairs<neighbor->no_pairs)
{
if(max_pairs)
{
delete [] drhoi_dr;
delete [] drhoj_dr;
}
max_pairs=neighbor->no_pairs;
CREATE1D(drhoi_dr,max_pairs);
CREATE1D(drhoj_dr,max_pairs);
}
type0* x=mapp->x->begin();
type0* fvec=f->begin();
type0* rho=rho_ptr->begin();
md_type* type=mapp->type->begin();
int iatm,jatm;
int itype,jtype,icomp,jcomp;
type0 dx0,dx1,dx2,rsq,z2p,z2;
type0 r,p,r_inv,fpair,tmp0,tmp1;
type0 drho_i_dr,drho_j_dr,dphi_dr;
type0 rho_i,rho_j,phi;
int m,istart;
type0* coef;
int** neighbor_list=neighbor->neighbor_list;
int* neighbor_list_size=neighbor->neighbor_list_size;
nrgy_strss_lcl[0]=0.0;
if (st_clc)
for(int i=1;i<7;i++)
nrgy_strss_lcl[i]=0.0;
int natms=atoms->natms;
for(iatm=0;iatm<natms;iatm++) rho[iatm]=0.0;
istart=0;
for(iatm=0;iatm<natms;iatm++)
{
itype=type[iatm];
icomp=3*iatm;
for(int j=0;j<neighbor_list_size[iatm];j++)
{
jatm=neighbor_list[iatm][j];
jtype=type[jatm];
jcomp=3*jatm;
dx0=x[icomp]-x[jcomp];
dx1=x[icomp+1]-x[jcomp+1];
dx2=x[icomp+2]-x[jcomp+2];
rsq=dx0*dx0+dx1*dx1+dx2*dx2;
drhoi_dr[istart]=drhoj_dr[istart]=0.0;
if(rsq < cut_sq[COMP(itype,jtype)])
{
r=sqrt(rsq);
r_inv=1.0/r;
p=r*dr_inv;
m=static_cast<int>(p);
m=MIN(m,nr-2);
p-=m;
p=MIN(p,1.0);
coef=rho_arr[type2rho[jtype][itype]][m];
rho_i=((coef[3]*p+coef[2])*p+coef[1])*p+coef[0];
drho_i_dr=(coef[6]*p+coef[5])*p+coef[4];
coef=rho_arr[type2rho[itype][jtype]][m];
rho_j=((coef[3]*p+coef[2])*p+coef[1])*p+coef[0];
drho_j_dr=(coef[6]*p+coef[5])*p+coef[4];
coef=phi_r_arr[type2phi[itype][jtype]][m];
z2p=(coef[6]*p + coef[5])*p+coef[4];
z2=((coef[3]*p+coef[2])*p+coef[1])*p+coef[0];
phi=z2*r_inv;
dphi_dr=z2p*r_inv-phi*r_inv;
rho[iatm]+=rho_i;
if(jatm<natms)
rho[jatm]+=rho_j;
fpair=-dphi_dr*r_inv;
fvec[icomp]+=fpair*dx0;
fvec[icomp+1]+=fpair*dx1;
fvec[icomp+2]+=fpair*dx2;
if(jatm<natms)
{
fvec[jcomp]-=fpair*dx0;
fvec[jcomp+1]-=fpair*dx1;
fvec[jcomp+2]-=fpair*dx2;
}
if(jatm>=natms)
{
fpair*=0.5;
phi*=0.5;
}
nrgy_strss_lcl[0]+=phi;
if (st_clc)
{
nrgy_strss_lcl[1]-=fpair*dx0*dx0;
nrgy_strss_lcl[2]-=fpair*dx1*dx1;
nrgy_strss_lcl[3]-=fpair*dx2*dx2;
nrgy_strss_lcl[4]-=fpair*dx1*dx2;
nrgy_strss_lcl[5]-=fpair*dx2*dx0;
nrgy_strss_lcl[6]-=fpair*dx0*dx1;
}
drhoi_dr[istart]=-drho_i_dr*r_inv;
drhoj_dr[istart]=-drho_j_dr*r_inv;
}
istart++;
}
p=rho[iatm]*drho_inv;
m=static_cast<int> (p);
m=MIN(m,nrho-2);
p-=m;
p=MIN(p,1.0);
itype=type[iatm];
coef=F_arr[itype][m];
tmp1=(coef[6]*p+coef[5])*p+coef[4];
tmp0=((coef[3]*p+coef[2])*p+coef[1])*p+coef[0];
if(rho[iatm]>rho_max)
tmp0+=tmp1*(rho[iatm]-rho_max);
nrgy_strss_lcl[0]+=tmp0;
rho[iatm]=tmp1;
}
atoms->update(rho_ptr);
istart=0;
for(iatm=0;iatm<natms;iatm++)
{
itype=type[iatm];
icomp=3*iatm;
for(int j=0;j<neighbor_list_size[iatm];j++)
{
if(drhoi_dr[istart]!=0.0 || drhoj_dr[istart]!=0.0)
{
jatm=neighbor_list[iatm][j];
jtype=type[jatm];
jcomp=3*jatm;
fpair=rho[iatm]*drhoi_dr[istart]+rho[jatm]*drhoj_dr[istart];
dx0=x[icomp]-x[jcomp];
dx1=x[icomp+1]-x[jcomp+1];
dx2=x[icomp+2]-x[jcomp+2];
fvec[icomp]+=dx0*fpair;
fvec[icomp+1]+=dx1*fpair;
fvec[icomp+2]+=dx2*fpair;
if(jatm<natms)
{
fvec[jcomp]-=dx0*fpair;
fvec[jcomp+1]-=dx1*fpair;
fvec[jcomp+2]-=dx2*fpair;
}
if(jatm>=natms)
fpair*=0.5;
if(st_clc)
{
nrgy_strss_lcl[1]-=fpair*dx0*dx0;
nrgy_strss_lcl[2]-=fpair*dx1*dx1;
nrgy_strss_lcl[3]-=fpair*dx2*dx2;
nrgy_strss_lcl[4]-=fpair*dx1*dx2;
nrgy_strss_lcl[5]-=fpair*dx2*dx0;
nrgy_strss_lcl[6]-=fpair*dx0*dx1;
}
}
istart++;
}
}
if(st_clc)
{
for(int i=0;i<7;i++)
nrgy_strss[i]=0.0;
MPI_Allreduce(nrgy_strss_lcl,nrgy_strss,7,MPI_TYPE0,MPI_SUM,world);
}
else
{
MPI_Allreduce(nrgy_strss_lcl,nrgy_strss,1,MPI_TYPE0,MPI_SUM,world);
}
}
/*--------------------------------------------
energy calculation
--------------------------------------------*/
type0 ForceField_eam::energy_calc()
{
type0* x=mapp->x->begin();
type0* rho=rho_ptr->begin();
md_type* type=mapp->type->begin();
int iatm,jatm;
int itype,jtype,icomp,jcomp;
type0 dx0,dx1,dx2,rsq;
type0 r,p,phi,tmp0;
int m;
type0* coef;
int** neighbor_list=neighbor->neighbor_list;
int* neighbor_list_size=neighbor->neighbor_list_size;
type0 en=0.0;
type0 en_tot=0.0;
int natms=atoms->natms;
for(iatm=0;iatm<natms;iatm++) rho[iatm]=0.0;
for(iatm=0;iatm<natms;iatm++)
{
itype=type[iatm];
icomp=3*iatm;
for(int j=0;j<neighbor_list_size[iatm];j++)
{
jatm=neighbor_list[iatm][j];
jtype=type[jatm];
jcomp=3*jatm;
dx0=x[icomp]-x[jcomp];
dx1=x[icomp+1]-x[jcomp+1];
dx2=x[icomp+2]-x[jcomp+2];
rsq=dx0*dx0+dx1*dx1+dx2*dx2;
if(rsq<cut_sq[COMP(itype,jtype)])
{
r=sqrt(rsq);
p=r*dr_inv;
m=static_cast<int>(p);
m=MIN(m,nr-2);
p-=m;
p=MIN(p,1.0);
coef=phi_r_arr[type2phi[itype][jtype]][m];
phi=(((coef[3]*p+coef[2])*p+coef[1])*p+coef[0])/r;
coef=rho_arr[type2rho[jtype][itype]][m];
rho[iatm]+=((coef[3]*p+coef[2])*p+coef[1])*p+coef[0];
if(jatm<natms)
{
coef=rho_arr[type2rho[itype][jtype]][m];
rho[jatm]+=((coef[3]*p+coef[2])*p+coef[1])*p+coef[0];
en+=phi;
}
else
en+=0.5*phi;
}
}
p=rho[iatm]*drho_inv;
m=static_cast<int>(p);
m=MIN(m,nrho-2);
p-=m;
p=MIN(p,1.0);
itype=type[iatm];
coef=F_arr[itype][m];
tmp0=((coef[3]*p+coef[2])*p+coef[1])*p+coef[0];
if(rho[iatm]>rho_max)
{
//tmp0+=((3.0*coef[3]*p+2.0*coef[2])*p+coef[1])*dr_inv*(rho[iatm]-rho_max);
tmp0+=((coef[6]*p+coef[5])*p+coef[4])*(rho[iatm]-rho_max);
}
en+=tmp0;
}
MPI_Allreduce(&en,&en_tot,1,MPI_TYPE0,MPI_SUM,world);
return en_tot;
}
/*--------------------------------------------
init before running
--------------------------------------------*/
void ForceField_eam::init()
{
neighbor->pair_wise=1;
rho_ptr=new Vec<type0>(atoms,1);
}
/*--------------------------------------------
fin after running
--------------------------------------------*/
void ForceField_eam::fin()
{
if(max_pairs)
{
delete [] drhoi_dr;
delete [] drhoj_dr;
max_pairs=0;
}
delete rho_ptr;
}
/*--------------------------------------------
destructor
--------------------------------------------*/
void ForceField_eam::coef(int nargs,char** args)
{
if (nargs<3)
error->abort("ff_coef for ff eam "
"should at least have 2 arguments");
cut_off_alloc();
delete eam_reader;
eam_reader=new EAMFileReader(mapp);
eam_reader->file_format(args[1]);
int iarg=2;
while(iarg<nargs)
{
eam_reader->add_file(args[iarg],iarg-2);
iarg++;
}
setup();
}
/*--------------------------------------------
setup
--------------------------------------------*/
void ForceField_eam::setup()
{
eam_reader->setup();
nr=eam_reader->nr;
nrho=eam_reader->nrho;
dr=eam_reader->dr;
drho=eam_reader->drho;
dr_inv=eam_reader->dr_inv;
drho_inv=eam_reader->drho_inv;
rho_max=eam_reader->rho_max;
F_arr=eam_reader->F_arr;
phi_r_arr=eam_reader->phi_r_arr;
rho_arr=eam_reader->rho_arr;
type2rho=eam_reader->type2rho;
type2phi=eam_reader->type2phi;
int no_types=atom_types->no_types;
memcpy(cut_sq,eam_reader->cut_sq,(no_types*(no_types+1)/2)*sizeof(type0));
}
|
b2b1f5c532a51ebbf0464ee88bb150d50375c829
|
6f616f3f10cfa43707c102ec286fe048dea80fb0
|
/test/types/json/json_traits.cpp
|
a1a028683660b3adf7ee303c47462a4df1b34be2
|
[
"MIT"
] |
permissive
|
ExternalRepositories/libfly
|
9e9003d5790be5877554e8b8e7a8545de7d03fd2
|
5acfc424a68031c0004b3c1cb5bef9d76dd129fb
|
refs/heads/main
| 2023-06-26T21:58:08.774786
| 2021-06-21T13:47:50
| 2021-06-21T13:47:50
| 377,925,131
| 0
| 0
|
MIT
| 2021-06-17T18:24:03
| 2021-06-17T18:24:02
| null |
UTF-8
|
C++
| false
| false
| 19,632
|
cpp
|
json_traits.cpp
|
#include "fly/types/json/json_traits.hpp"
#include "catch2/catch_template_test_macros.hpp"
#include "catch2/catch_test_macros.hpp"
#include <array>
#include <deque>
#include <forward_list>
#include <list>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <vector>
CATCH_TEMPLATE_TEST_CASE(
"JsonTraits",
"[json]",
std::string,
std::wstring,
std::u8string,
std::u16string,
std::u32string)
{
using string_type = TestType;
using char_type = typename TestType::value_type;
using view_type = std::basic_string_view<char_type>;
using array_type = std::array<int, 4>;
using deque_type = std::deque<int>;
using forward_list_type = std::forward_list<int>;
using list_type = std::list<int>;
using multiset_type = std::multiset<int>;
using set_type = std::set<int>;
using unordered_multiset_type = std::unordered_multiset<int>;
using unordered_set_type = std::unordered_set<int>;
using vector_type = std::vector<int>;
using map_type = std::map<string_type, int>;
using multimap_type = std::multimap<string_type, int>;
using unordered_map_type = std::unordered_map<string_type, int>;
using unordered_multimap_type = std::unordered_multimap<string_type, int>;
using null_type = std::nullptr_t;
using boolean_type = bool;
using signed_integer_type = int;
using unsigned_integer_type = unsigned int;
using float_type = float;
using double_type = double;
using long_double_type = long double;
CATCH_SECTION("Traits for null-like JSON types")
{
CATCH_CHECK(fly::JsonTraits::is_null_v<null_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_null_v<array_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_null_v<deque_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_null_v<forward_list_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_null_v<list_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_null_v<map_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_null_v<multimap_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_null_v<multiset_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_null_v<set_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_null_v<unordered_map_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_null_v<unordered_multimap_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_null_v<unordered_multiset_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_null_v<unordered_set_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_null_v<vector_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_null_v<boolean_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_null_v<string_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_null_v<signed_integer_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_null_v<unsigned_integer_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_null_v<double_type>);
}
CATCH_SECTION("Traits for string-like JSON types")
{
CATCH_CHECK(fly::JsonTraits::is_string_v<const string_type>);
CATCH_CHECK(fly::JsonTraits::is_string_v<string_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_v<const char_type *>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_v<char_type *>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_v<const char_type[]>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_v<char_type[]>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_v<const view_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_v<view_type>);
CATCH_CHECK(fly::JsonTraits::is_string_like_v<const string_type>);
CATCH_CHECK(fly::JsonTraits::is_string_like_v<string_type>);
CATCH_CHECK(fly::JsonTraits::is_string_like_v<const char_type *>);
CATCH_CHECK(fly::JsonTraits::is_string_like_v<char_type *>);
CATCH_CHECK(fly::JsonTraits::is_string_like_v<const char_type[]>);
CATCH_CHECK(fly::JsonTraits::is_string_like_v<char_type[]>);
CATCH_CHECK(fly::JsonTraits::is_string_like_v<const view_type>);
CATCH_CHECK(fly::JsonTraits::is_string_like_v<view_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_v<array_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_v<deque_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_v<forward_list_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_v<list_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_v<map_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_v<multimap_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_v<multiset_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_v<set_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_v<unordered_map_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_v<unordered_multimap_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_v<unordered_multiset_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_v<unordered_set_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_v<vector_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_like_v<array_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_like_v<deque_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_like_v<forward_list_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_like_v<list_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_like_v<map_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_like_v<multimap_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_like_v<multiset_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_like_v<set_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_like_v<unordered_map_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_like_v<unordered_multimap_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_like_v<unordered_multiset_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_like_v<unordered_set_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_like_v<vector_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_v<null_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_v<signed_integer_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_v<boolean_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_v<float_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_v<double_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_v<const char_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_v<char_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_like_v<null_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_like_v<signed_integer_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_like_v<boolean_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_like_v<float_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_like_v<double_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_like_v<const char_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_string_like_v<char_type>);
}
CATCH_SECTION("Traits for boolean-like JSON types")
{
CATCH_CHECK(fly::JsonTraits::is_boolean_v<boolean_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_boolean_v<array_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_boolean_v<deque_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_boolean_v<forward_list_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_boolean_v<list_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_boolean_v<map_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_boolean_v<multimap_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_boolean_v<multiset_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_boolean_v<set_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_boolean_v<unordered_map_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_boolean_v<unordered_multimap_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_boolean_v<unordered_multiset_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_boolean_v<unordered_set_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_boolean_v<vector_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_boolean_v<null_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_boolean_v<string_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_boolean_v<signed_integer_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_boolean_v<unsigned_integer_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_boolean_v<double_type>);
}
CATCH_SECTION("Traits for signed-integer-like JSON types")
{
CATCH_CHECK(fly::JsonTraits::is_signed_integer_v<signed_integer_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_signed_integer_v<array_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_signed_integer_v<deque_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_signed_integer_v<forward_list_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_signed_integer_v<list_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_signed_integer_v<map_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_signed_integer_v<multimap_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_signed_integer_v<multiset_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_signed_integer_v<set_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_signed_integer_v<unordered_map_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_signed_integer_v<unordered_multimap_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_signed_integer_v<unordered_multiset_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_signed_integer_v<unordered_set_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_signed_integer_v<vector_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_signed_integer_v<null_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_signed_integer_v<string_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_signed_integer_v<double_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_signed_integer_v<boolean_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_signed_integer_v<unsigned_integer_type>);
}
CATCH_SECTION("Traits for unsigned-integer-like JSON types")
{
CATCH_CHECK(fly::JsonTraits::is_unsigned_integer_v<unsigned_integer_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_unsigned_integer_v<array_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_unsigned_integer_v<deque_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_unsigned_integer_v<forward_list_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_unsigned_integer_v<list_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_unsigned_integer_v<map_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_unsigned_integer_v<multimap_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_unsigned_integer_v<multiset_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_unsigned_integer_v<set_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_unsigned_integer_v<unordered_map_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_unsigned_integer_v<unordered_multimap_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_unsigned_integer_v<unordered_multiset_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_unsigned_integer_v<unordered_set_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_unsigned_integer_v<vector_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_unsigned_integer_v<null_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_unsigned_integer_v<string_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_unsigned_integer_v<signed_integer_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_unsigned_integer_v<double_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_unsigned_integer_v<boolean_type>);
}
CATCH_SECTION("Traits for floating-point-like JSON types")
{
CATCH_CHECK(fly::JsonTraits::is_floating_point_v<float_type>);
CATCH_CHECK(fly::JsonTraits::is_floating_point_v<double_type>);
CATCH_CHECK(fly::JsonTraits::is_floating_point_v<long_double_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_floating_point_v<array_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_floating_point_v<deque_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_floating_point_v<forward_list_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_floating_point_v<list_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_floating_point_v<map_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_floating_point_v<multimap_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_floating_point_v<multiset_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_floating_point_v<set_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_floating_point_v<unordered_map_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_floating_point_v<unordered_multimap_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_floating_point_v<unordered_multiset_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_floating_point_v<unordered_set_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_floating_point_v<vector_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_floating_point_v<null_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_floating_point_v<string_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_floating_point_v<signed_integer_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_floating_point_v<unsigned_integer_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_floating_point_v<boolean_type>);
}
CATCH_SECTION("Traits for object-like JSON types")
{
CATCH_CHECK(fly::JsonTraits::is_object_v<map_type>);
CATCH_CHECK(fly::JsonTraits::is_object_v<multimap_type>);
CATCH_CHECK(fly::JsonTraits::is_object_v<unordered_map_type>);
CATCH_CHECK(fly::JsonTraits::is_object_v<unordered_multimap_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_object_v<std::map<int, int>>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_object_v<std::multimap<int, int>>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_object_v<std::unordered_map<int, int>>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_object_v<std::unordered_multimap<int, int>>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_object_v<array_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_object_v<deque_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_object_v<forward_list_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_object_v<list_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_object_v<multiset_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_object_v<set_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_object_v<unordered_multiset_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_object_v<unordered_set_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_object_v<vector_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_object_v<null_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_object_v<string_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_object_v<signed_integer_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_object_v<unsigned_integer_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_object_v<double_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_object_v<boolean_type>);
}
CATCH_SECTION("Traits for array-like JSON types")
{
CATCH_CHECK(fly::JsonTraits::is_array_v<array_type>);
CATCH_CHECK(fly::JsonTraits::is_array_v<deque_type>);
CATCH_CHECK(fly::JsonTraits::is_array_v<forward_list_type>);
CATCH_CHECK(fly::JsonTraits::is_array_v<list_type>);
CATCH_CHECK(fly::JsonTraits::is_array_v<multiset_type>);
CATCH_CHECK(fly::JsonTraits::is_array_v<set_type>);
CATCH_CHECK(fly::JsonTraits::is_array_v<unordered_multiset_type>);
CATCH_CHECK(fly::JsonTraits::is_array_v<unordered_set_type>);
CATCH_CHECK(fly::JsonTraits::is_array_v<vector_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_array_v<map_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_array_v<multimap_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_array_v<unordered_map_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_array_v<unordered_multimap_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_array_v<null_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_array_v<string_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_array_v<signed_integer_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_array_v<unsigned_integer_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_array_v<double_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_array_v<boolean_type>);
}
CATCH_SECTION("Traits for container JSON types")
{
CATCH_CHECK(fly::JsonTraits::is_container_v<string_type>);
CATCH_CHECK(fly::JsonTraits::is_container_v<array_type>);
CATCH_CHECK(fly::JsonTraits::is_container_v<deque_type>);
CATCH_CHECK(fly::JsonTraits::is_container_v<forward_list_type>);
CATCH_CHECK(fly::JsonTraits::is_container_v<list_type>);
CATCH_CHECK(fly::JsonTraits::is_container_v<multiset_type>);
CATCH_CHECK(fly::JsonTraits::is_container_v<set_type>);
CATCH_CHECK(fly::JsonTraits::is_container_v<unordered_multiset_type>);
CATCH_CHECK(fly::JsonTraits::is_container_v<unordered_set_type>);
CATCH_CHECK(fly::JsonTraits::is_container_v<vector_type>);
CATCH_CHECK(fly::JsonTraits::is_container_v<map_type>);
CATCH_CHECK(fly::JsonTraits::is_container_v<multimap_type>);
CATCH_CHECK(fly::JsonTraits::is_container_v<unordered_map_type>);
CATCH_CHECK(fly::JsonTraits::is_container_v<unordered_multimap_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_container_v<null_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_container_v<signed_integer_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_container_v<unsigned_integer_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_container_v<double_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_container_v<boolean_type>);
}
CATCH_SECTION("Traits for iterable JSON types")
{
CATCH_CHECK(fly::JsonTraits::is_iterable_v<array_type>);
CATCH_CHECK(fly::JsonTraits::is_iterable_v<deque_type>);
CATCH_CHECK(fly::JsonTraits::is_iterable_v<forward_list_type>);
CATCH_CHECK(fly::JsonTraits::is_iterable_v<list_type>);
CATCH_CHECK(fly::JsonTraits::is_iterable_v<multiset_type>);
CATCH_CHECK(fly::JsonTraits::is_iterable_v<set_type>);
CATCH_CHECK(fly::JsonTraits::is_iterable_v<unordered_multiset_type>);
CATCH_CHECK(fly::JsonTraits::is_iterable_v<unordered_set_type>);
CATCH_CHECK(fly::JsonTraits::is_iterable_v<vector_type>);
CATCH_CHECK(fly::JsonTraits::is_iterable_v<map_type>);
CATCH_CHECK(fly::JsonTraits::is_iterable_v<multimap_type>);
CATCH_CHECK(fly::JsonTraits::is_iterable_v<unordered_map_type>);
CATCH_CHECK(fly::JsonTraits::is_iterable_v<unordered_multimap_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_iterable_v<null_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_iterable_v<string_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_iterable_v<signed_integer_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_iterable_v<unsigned_integer_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_iterable_v<double_type>);
CATCH_CHECK_FALSE(fly::JsonTraits::is_iterable_v<boolean_type>);
}
}
|
140ad0d503dd0f383afb15dd72ce89d4df6179af
|
3188d2b4e8e9869c80819e8a3d99ebace8adfd06
|
/Practice/LastStoneWeightII.cpp
|
cb4f7a2e2583ed472eb939fa43de3bcef264b790
|
[] |
no_license
|
Divyalok123/LeetCode_Practice
|
78ce9ba0deb8719b71111e17ae65422d76d2a306
|
2ac1dd229e7154e5ddddb0c72b9bfbb9c897d825
|
refs/heads/master
| 2023-06-30T08:55:33.369349
| 2021-08-01T06:17:06
| 2021-08-01T06:17:06
| 256,864,709
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,573
|
cpp
|
LastStoneWeightII.cpp
|
/*
https://leetcode.com/problems/last-stone-weight-ii/
*/
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
// Solution 2 (DP)
class Solution {
public:
int lastStoneWeightII(vector<int>& stones) {
int n = stones.size();
int sum = 0;
for(int& i: stones) sum += i;
vector<vector<bool>> dp(sum/2+1, vector<bool>(n+1));
for(int i = 0; i <= n; i++) dp[0][i] = 1;
int mm = 0;
for(int i = 1; i <= n; i++) {
for(int s = 1; s <= sum/2; s++) {
if(dp[s][i-1])
dp[s][i] = 1;
else if(s >= stones[i-1])
dp[s][i] = dp[s-stones[i-1]][i-1];
if(dp[s][i] && s > mm) mm = s;
}
}
return sum - 2*mm;
}
};
// Solution 1 (memo)
class Solution {
public:
vector<vector<int>> dp;
int helper(vector<int>& stones, int total, int curr, int i) {
if(i == stones.size()) {
int ans = total-curr;
return ans < 0 ? -ans : ans;
}
if(dp[i][curr] != -1)
return dp[i][curr];
int a = helper(stones, total-stones[i], curr + stones[i], i+1);
int b = helper(stones, total, curr, i+1);
return dp[i][curr] = (a < b) ? a : b;
}
int lastStoneWeightII(vector<int>& stones) {
int n = stones.size();
int sum = 0;
for(int& i: stones)
sum += i;
dp.assign(n, vector<int>(sum+1, -1));
return helper(stones, sum, 0, 0);
}
};
|
99ce3ff8bcfb6a5d2b08748eefa1b7ebcccd861a
|
ece30e7058d8bd42bc13c54560228bd7add50358
|
/DataCollector/mozilla/xulrunner-sdk/include/mozilla/dom/CSS.h
|
adf583d95091588f1b4dd30bd0dcd3d4217cc026
|
[
"Apache-2.0"
] |
permissive
|
andrasigneczi/TravelOptimizer
|
b0fe4d53f6494d40ba4e8b98cc293cb5451542ee
|
b08805f97f0823fd28975a36db67193386aceb22
|
refs/heads/master
| 2022-07-22T02:07:32.619451
| 2018-12-03T13:58:21
| 2018-12-03T13:58:21
| 53,926,539
| 1
| 0
|
Apache-2.0
| 2022-07-06T20:05:38
| 2016-03-15T08:16:59
|
C++
|
UTF-8
|
C++
| false
| false
| 1,178
|
h
|
CSS.h
|
/* -*- 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/. */
/* DOM object holding utility CSS functions */
#ifndef mozilla_dom_CSS_h_
#define mozilla_dom_CSS_h_
#include "mozilla/Attributes.h"
#include "mozilla/Preferences.h"
namespace mozilla {
class ErrorResult;
namespace dom {
class GlobalObject;
class CSS {
private:
CSS() = delete;
public:
static bool Supports(const GlobalObject& aGlobal,
const nsAString& aProperty,
const nsAString& aValue,
ErrorResult& aRv);
static bool Supports(const GlobalObject& aGlobal,
const nsAString& aDeclaration,
ErrorResult& aRv);
static void Escape(const GlobalObject& aGlobal,
const nsAString& aIdent,
nsAString& aReturn,
ErrorResult& aRv);
};
} // namespace dom
} // namespace mozilla
#endif // mozilla_dom_CSS_h_
|
25203ac2af0fdadd0f40eb704a6bc381e5ce8e4c
|
507f3970637d523d2aa99eb16fff627a628fd8b8
|
/ass02/hw02_tree01/VectorBnode.h
|
e57d1b8327e155926131765457f25d2cb0dcadc8
|
[] |
no_license
|
suryak/Advanced-Data-Structures
|
e6ddec480868c50a45a70234dd5188e0300e3e64
|
f5b1cd8e1fbb688b15038738b5151e54719bc039
|
refs/heads/master
| 2021-01-02T08:56:32.530782
| 2014-03-17T17:42:20
| 2014-03-17T17:42:20
| 17,835,253
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 471
|
h
|
VectorBnode.h
|
#pragma once
#include "Interfaces02.h"
#include "Bnode.h"
#include<string>
class VectorBnode{
public:
size_t length;
size_t used;
Bnode **items;
int key;
std::string value;
VectorBnode(){
length = 1;
used = 0;
items = new Bnode*[1];
}
~VectorBnode(){}
void push_back(Bnode *item);
void pop_back();
Bnode* get(int index);
void set(int index, Bnode *item);
size_t size();
};
|
8355e07fdbaaffa3b8f2fe55389b6f938b6e9554
|
dcc668891c58cd594234d49a209c4a5e788e2341
|
/include/lol/def/PatcherP2PStatusUpdate.hpp
|
90518ba7816068ae79a3a7153e3a957bd54157a6
|
[
"BSD-3-Clause"
] |
permissive
|
Arryboom/LeagueAPI
|
56d6832f125d1843d575330ae5b0c8172945cca8
|
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
|
refs/heads/master
| 2021-09-28T01:05:12.713109
| 2018-11-13T03:05:31
| 2018-11-13T03:05:31
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 376
|
hpp
|
PatcherP2PStatusUpdate.hpp
|
#pragma once
#include "../base_def.hpp"
namespace lol {
struct PatcherP2PStatusUpdate {
bool isAllowedByUser;
};
inline void to_json(json& j, const PatcherP2PStatusUpdate& v) {
j["isAllowedByUser"] = v.isAllowedByUser;
}
inline void from_json(const json& j, PatcherP2PStatusUpdate& v) {
v.isAllowedByUser = j.at("isAllowedByUser").get<bool>();
}
}
|
86cb113831684b6860ae3bf304f82e42c8a9d219
|
1567a71b4143bcd9090c21927062a6225fab7800
|
/foo_output_pipe/ConIo.h
|
151792a94eae7c924aeafe7f22f0f53a364e1330
|
[] |
no_license
|
saivert/foo_output_pipe
|
e792ccb859fb26320e95d5bf9cee169676249cff
|
35ae3c546d0602863cb565d7c012c795b2683b4a
|
refs/heads/master
| 2020-12-31T04:28:52.655874
| 2018-07-02T07:52:18
| 2018-07-02T07:52:18
| 49,016,653
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,033
|
h
|
ConIo.h
|
#pragma once
#include <queue>
class CConIo
{
private:
WCHAR cmdline[MAX_PATH];
PROCESS_INFORMATION process_info;
const int samplerate;
const int channels;
void _WriteWavHeader(service_ptr_t<file> file_stream);
typedef struct
{
char RIFF_marker[4];
uint32_t file_size;
char filetype_header[4];
char format_marker[4];
uint32_t data_header_length;
uint16_t format_type;
uint16_t number_of_channels;
uint32_t sample_rate;
uint32_t bytes_per_second;
uint16_t bytes_per_frame;
uint16_t bits_per_sample;
} WaveHeader;
void _MakeWavHeader(WaveHeader &hdr, uint32_t sample_rate, uint16_t bit_depth, uint16_t channels);
abort_callback_impl abrt;
const bool showconsole;
double curvol;
HANDLE child_input_write;
service_ptr_t<file> file_stream;
bool ready;
public:
CConIo(LPWSTR child, int samplerate, int channels, bool showconsole);
void Write(const audio_chunk &d);
bool isReady();
void Flush();
void SetVol(double p_vol) {
curvol = p_vol;
}
void Abort() {
abrt.abort();
}
~CConIo();
};
|
ffb4fb2b83b51b33dd6cf399757b506ec8000c5e
|
7268f845ea8cd66d443212d20dc13dcfe840219e
|
/剑指 Offer 16. 数值的整数次方.cpp
|
961eed82c88792992346ae00881ad4a2f24c93d9
|
[] |
no_license
|
watermelonyip/leetcode
|
5cb02bc7f0531fc31304cab32a66aa2ee8aa7a54
|
b7e59bfb76258f76973e3e0d7ed27d5762731c9e
|
refs/heads/main
| 2023-03-22T22:18:19.936557
| 2021-03-17T07:50:54
| 2021-03-17T07:50:54
| 318,970,710
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,484
|
cpp
|
剑指 Offer 16. 数值的整数次方.cpp
|
/*
实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。
-100.0 < x < 100.0
n 是 32 位有符号整数,其数值范围是 [−2^31, 2^31 − 1]
思路:先处理特殊情况,base为0,exponent为0或1。若exponent为负数,需要求绝对值。循环求余的方法,若exponent为偶数,则计算base^exponent = base^(expoent/2) * base^(exponet/2);
若exponent为奇数,则计算base^exponent = base^(expoent/2) * base^(exponet/2) * base。也可以用递归的方法,两种方法都不是很熟悉,需要多练。
易错点:特殊情况处理,当exponent为负数求绝对值时,需要考虑边界值,exponent求余后需要用unsigned int之类的类型来表示。&操作和>>操作,位运算比乘除法和求余运算效率要高。
*/
class Solution {
public:
double myPow(double x, int n) {
if(x == 0)
return 0;
if(n == 0)
return 1;
if(n == 1)
return x;
unsigned int exponent = (unsigned int)(abs(n));
//cout << "exponent: " << exponent << endl;
double result = 1;
while(exponent){
if(exponent & 0x1 == 1)
result *= x;
x *= x;
exponent = exponent >> 1;
//cout << exponent << " " << result << endl;
}
if(n < 0)
result = 1.0 / result;
return result;
}
};
|
f84fdbc3bc88ef4e2a0c83673096ce1c1669a173
|
2c01969db3e4de0131618057125aee655cba0cb8
|
/quisp/utils/ComponentProvider.h
|
d5870bb6e475913ac2345ff271febc23abb01c5b
|
[
"BSD-3-Clause",
"MPL-2.0",
"LicenseRef-scancode-free-unknown"
] |
permissive
|
sfc-aqua/quisp
|
c86ee50e08047c6a5469e01ae8740710e9287636
|
eddfe7ee80535a624987941653c59da2ce138929
|
refs/heads/master
| 2023-08-31T10:23:57.939878
| 2023-08-07T03:00:56
| 2023-08-07T03:00:56
| 246,997,413
| 77
| 36
|
BSD-3-Clause
| 2023-09-05T10:07:25
| 2020-03-13T05:48:04
|
C++
|
UTF-8
|
C++
| false
| false
| 2,671
|
h
|
ComponentProvider.h
|
#pragma once
#include <omnetpp.h>
#include "DefaultComponentProviderStrategy.h"
#include "IComponentProviderStrategy.h"
#include "modules/Logger/LoggerModule.h"
#include "modules/QRSA/QRSA.h"
#include "modules/common_types.h"
#include "utils.h"
namespace quisp::utils {
/**
* \brief ComponentProvider class provides a way to access other quisp other modules.
*
* This class itself doesn't know how to get other modules, All actual behaviors are
* delegated to strategy class.
* \see IComponentProviderStrategy
* \see DefaultComponentProviderStrategy
*/
class ComponentProvider {
public:
ComponentProvider(omnetpp::cModule *_module);
cModule *getQNode();
cModule *getNode();
int getNodeAddr();
cModule *getNeighborNode(cModule *qnic);
bool isQNodeType(const cModuleType *const type);
bool isBSANodeType(const cModuleType *const type);
bool isSPDCNodeType(const cModuleType *const type);
IStationaryQubit *getStationaryQubit(modules::qrsa::IQubitRecord *const qubit_record);
IStationaryQubit *getStationaryQubit(int qnic_index, int qubit_index, QNIC_type qnic_type);
cModule *getQNIC(int qnic_index, QNIC_type qnic_type);
int getNumQubits(int qnic_index, QNIC_type qnic_type);
IRoutingDaemon *getRoutingDaemon();
IHardwareMonitor *getHardwareMonitor();
IRealTimeController *getRealTimeController();
IQuantumBackend *getQuantumBackend();
ILogger *getLogger();
cTopology *getTopologyForRoutingDaemon(const cModule *const rd_module);
cTopology *getTopologyForRouter();
const std::unordered_map<int, int> getEndNodeWeightMapForApplication(std::string node_type);
// when a this class instantiated, a strategy class instantiation may fail because
// the strategy class may depend on other modules instantiated by OMNeT++'s NED file.
// So this method is for delaying to instantiate the strategy class.
// And also we can inject a strategy for unit testing.
void setStrategy(std::unique_ptr<IComponentProviderStrategy> _strategy);
// an owner module of this class.
// strategy class will access to other modules by the module.
omnetpp::cModule *module;
private:
// An actual strategy.
// This will be instantiated when it is needed through ensureStrategy method.
// It will be deleted automatically when ComponentProvider's deconstructor called.
std::unique_ptr<IComponentProviderStrategy> strategy = nullptr;
SharedResource *getSharedResource();
// before calling strategy class, this internal method ensure that
// the strategy class instance exists.
// if there's no strategy, this method uses DefaultComponentProviderStrategy.
void ensureStrategy();
};
} // namespace quisp::utils
|
b1bea51ffda0c5fdf587480a340d78f865bd9113
|
d31ed4f3bd9a9d24ff388749c056a0ea6255a76c
|
/src/platform/update_engine/decompressing_file_writer.cc
|
96db0100b18dbab125b4cd8a66f8f14ed20e8fa1
|
[
"BSD-3-Clause"
] |
permissive
|
Escapist70/chromiumos
|
c840e15a4320765acba08e13f20ecc9ec9d108ad
|
380301ef6831c966b1389bffe0cd51fcccfcd612
|
refs/heads/master
| 2021-01-18T12:34:27.303926
| 2010-02-26T21:10:11
| 2010-02-26T21:10:11
| 20,645,371
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,983
|
cc
|
decompressing_file_writer.cc
|
// Copyright (c) 2009 The Chromium OS 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 "update_engine/decompressing_file_writer.h"
namespace chromeos_update_engine {
// typedef struct z_stream_s {
// Bytef *next_in; /* next input byte */
// uInt avail_in; /* number of bytes available at next_in */
// uLong total_in; /* total nb of input bytes read so far */
//
// Bytef *next_out; /* next output byte should be put there */
// uInt avail_out; /* remaining free space at next_out */
// uLong total_out; /* total nb of bytes output so far */
//
// char *msg; /* last error message, NULL if no error */
// struct internal_state FAR *state; /* not visible by applications */
//
// alloc_func zalloc; /* used to allocate the internal state */
// free_func zfree; /* used to free the internal state */
// voidpf opaque; /* private data object passed to zalloc and zfree */
//
// int data_type; /* best guess about the data type: binary or text */
// uLong adler; /* adler32 value of the uncompressed data */
// uLong reserved; /* reserved for future use */
// } z_stream;
int GzipDecompressingFileWriter::Write(const void* bytes, size_t count) {
// Steps:
// put the data on next_in
// call inflate until it returns nothing, each time writing what we get
// check that next_in has no data left.
// It seems that zlib can keep internal buffers in the stream object,
// so not all data we get fed to us this time will necessarily
// be written out this time (in decompressed form).
if (stream_.avail_in) {
LOG(ERROR) << "Have data already. Bailing";
return -1;
}
char buf[1024];
buffer_.reserve(count);
buffer_.clear();
CHECK_GE(buffer_.capacity(), count);
const char* char_bytes = reinterpret_cast<const char*>(bytes);
buffer_.insert(buffer_.end(), char_bytes, char_bytes + count);
stream_.next_in = reinterpret_cast<Bytef*>(&buffer_[0]);
stream_.avail_in = count;
int retcode = Z_OK;
while (Z_OK == retcode) {
stream_.next_out = reinterpret_cast<Bytef*>(buf);
stream_.avail_out = sizeof(buf);
int retcode = inflate(&stream_, Z_NO_FLUSH);
// check for Z_STREAM_END, Z_OK, or Z_BUF_ERROR (which is non-fatal)
if (Z_STREAM_END != retcode && Z_OK != retcode && Z_BUF_ERROR != retcode) {
LOG(ERROR) << "zlib inflate() error:" << retcode;
if (stream_.msg)
LOG(ERROR) << "message:" << stream_.msg;
return 0;
}
int count_received = sizeof(buf) - stream_.avail_out;
if (count_received > 0) {
next_->Write(buf, count_received);
} else {
// Inflate returned no data; we're done for now. Make sure no
// input data remain.
CHECK_EQ(0, stream_.avail_in);
break;
}
}
return count;
}
} // namespace chromeos_update_engine
|
538a6827d1b5b292a0cff05ada941818d31a7689
|
734ad0714537e082832fc8c5c9746edb991a5b14
|
/src/ksLabel.h
|
fc2b16ca0fee69c687f0c474b1367c025d1e5677
|
[
"MIT"
] |
permissive
|
ipud2/KingEngine
|
d672cb9d4425bca0a9196d92e81973cda2312fd3
|
5c7e5ff89bfd7acc1031470660fc89b06d56101b
|
refs/heads/master
| 2020-06-29T13:23:31.332861
| 2016-07-22T03:22:10
| 2016-07-22T03:22:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,774
|
h
|
ksLabel.h
|
/********************************************************
* Class: ksLabel
* Author: Beyond Parallel - Jacob Neal
*
* Filename: ksLabel.h
*
* Overview:
* Label class that inherits from the base game
* control.
*
********************************************************/
#ifndef KS_LABEL_H
#define KS_LABEL_H
#include <SFML/Graphics.hpp>
#include <string>
#include "ksVector2D.h"
#include "ksControl.h"
class ksLabel : public ksControl
{
public:
// Constructors
ksLabel(sf::Font * font, std::string str, double x, double y, int character_size = 12);
// Methods
virtual void drawControl(sf::RenderWindow & app);
virtual bool getVisibility();
virtual void moveControl(double x, double y);
virtual bool pressed(int mouse_x, int mouse_y);
virtual bool isPressed();
virtual void resize(int screen_width, int screen_height);
virtual void setCenter(double x, double y);
virtual void setControlPosition(double x, double y);
virtual void setOpacity(double opacity);
virtual void setPressed(bool pressed);
void setText(std::string str);
virtual void setVisibility(bool visibility);
private:
// Data members
ksVector2D m_position;
sf::Text m_text;
bool m_pressed;
bool m_visible;
int m_character_size;
};
#endif
|
faacde61d7fa7b9126d2328e9f41c6556778a83c
|
b23e8b8fa4f70d915f0c8d3c6ed57ba2d2ae4ee6
|
/sandpit/GridTransformCode/CPlusPlusCode/GDM_Binary.cpp
|
43fdf86022d777e971f6128fbdc56a7a261e3a48
|
[] |
no_license
|
cwarecsiro/gdmEngine
|
99195eefc1369165051ce8985f5954369358664c
|
4fd57e609f7411ebb989b0987e6b10d33af63ae4
|
refs/heads/master
| 2021-07-15T23:33:37.415368
| 2018-11-23T00:06:05
| 2018-11-23T00:06:05
| 137,005,799
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,016
|
cpp
|
GDM_Binary.cpp
|
//
// GDM_Binary.cpp
//
#include "stdafx.h"
#include "GDM_Binary.h"
#include <iostream>
#include <string>
//
// Calculate a Cyclic Redundancy Check value for the CRC calculation methods
//
unsigned long CRC32Value(int i)
{
unsigned long ulCRC = i;
for (int j=8; j>0; j--)
{
if (ulCRC & 1)
ulCRC = (ulCRC >> 1) ^ CRC32_POLYNOMIAL;
else
ulCRC >>=1;
}
return(ulCRC);
}
//
// Calculate the 32-bit CRC of a block of data all at once
//
unsigned long CalculateBlockCRC32(unsigned long ulCount, unsigned char *ucBuffer)
{
unsigned long ulTemp1;
unsigned long ulTemp2;
unsigned long ulCRC = 0;
while (ulCount-- != 0)
{
ulTemp1 = (ulCRC >> 8) & 0x00FFFFFFL;
ulTemp2 = CRC32Value(((int)ulCRC ^ *ucBuffer++) & 0xFF);
ulCRC = ulTemp1 ^ ulTemp1;
}
return(ulCRC);
}
//
// Swap bytes from big endian to Little endian
//
unsigned long ByteSwap(unsigned long n)
{
return(((n & 0x000000FF) << 24) +
((n & 0x0000FF00) << 8) +
((n & 0x00FF0000) >> 8) +
((n & 0xFF000000) >> 24));
}
|
9c34874a75f350924957e95bdf355c53cf08b291
|
11dcefc3768cc67f6563f7e0e4713bae740cad63
|
/hyeyoo/3주차_DP_2/암호코드.cpp
|
e1945f49142ecdbf4852f4774d1a570dff3b7070
|
[] |
no_license
|
42somoim/42somoim1
|
dac54edee33aadf1a17f60768446e5faf07ed952
|
039e00085290d048a7345bcec7db797e4c7330d2
|
refs/heads/master
| 2023-05-06T13:07:01.242428
| 2021-05-28T12:07:45
| 2021-05-28T12:07:45
| 280,406,020
| 2
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,481
|
cpp
|
암호코드.cpp
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* 암호코드.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: hyeyoo <hyeyoo@student.42seoul.kr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/08/13 14:48:55 by hyeyoo #+# #+# */
/* Updated: 2020/08/13 14:52:48 by hyeyoo ### ########.fr */
/* */
/* ************************************************************************** */
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
string code;
getline(cin, code);
int len = code.length();
int *arr = new int[len + 1];
for(int i = 1; i <= code.length(); i++) {
arr[i] = code[i - 1] - '0';
}
const int b = 1000000;
int *d = new int[len + 1];
for(int i = 1; i <= len; i++) {
if (1 <= arr[i] && arr[i] <= 9)
d[i] = (d[i - 1] + d[i]) % b;
if (i >= 2) {
int val = arr[i - 1] * 10 + arr[i];
if (10 <= val && val <= 26) {
d[i] = (d[i - 2] + d[i]) % b;
}
}
}
cout << d[len] << endl;
delete[] d;
delete[] arr;
}
|
7271966ebb562fc1fb0c972a815a3426c44e4b75
|
15ab7e1c875f803aa0d68385e5af99abe7f84a11
|
/view/pageRank.cpp
|
a2246c4236e144e54ae6b29e9a2369ad0a33e9bc
|
[] |
no_license
|
lincandong/Basketball_Data_Visualization
|
25875b4ee851caa0f16786ca0f0443efdba488fa
|
48289a37a1e6633d33e88b79fee9a1507a5c1e40
|
refs/heads/master
| 2021-07-25T19:30:18.069395
| 2018-11-09T01:49:20
| 2018-11-09T01:49:20
| 140,906,959
| 6
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 26,845
|
cpp
|
pageRank.cpp
|
#include "pageRank.h"
#include "ui_pageRank.h"
#include <iostream>
pageRank::pageRank(QWidget *parent) :
QWidget(parent),
ui(new Ui::pageRank)
{
ui->setupUi(this);
// connections
connect(ui->buttonShoot, &QPushButton::clicked, this, &pageRank::showShoot);
connect(ui->buttonThree, &QPushButton::clicked, this, &pageRank::showThree);
connect(ui->buttonPenalty, &QPushButton::clicked, this, &pageRank::showPenalty);
connect(ui->buttonBackboard, &QPushButton::clicked, this, &pageRank::showBackboard);
connect(ui->buttonAssisting, &QPushButton::clicked, this, &pageRank::showAssisting);
connect(ui->buttonFalut, &QPushButton::clicked, this, &pageRank::showFalut);
connect(ui->buttonScore, &QPushButton::clicked, this, &pageRank::showScore);
connect(ui->buttonVictory, &QPushButton::clicked, this, &pageRank::showVictory);
}
pageRank::~pageRank()
{
delete ui;
}
void pageRank::init()
{
// initialize parameter
para = make_shared<rankParameter>("fgper", 17);
isTeam = true;
// show chart
showShoot();
}
void pageRank::showShoot()
{
// show chart page and set scroll area's height
if (ui->stackedWidget->currentWidget() != ui->pageShoot)
ui->stackedWidget->setCurrentWidget(ui->pageShoot);
ui->scrollAreaWidgetContents->setMinimumHeight(1500);
// modify parameter and send command
para->option = "fgper";
para->season = 2017;
if (isTeam == true)
{
teamRankCommand->setParameter(para);
teamRankCommand->action();
}
else
{
playerRankCommand->setParameter(para);
playerRankCommand->action();
}
// get current data
QBarSet *set1 = new QBarSet("投篮");
QBarSet *set2 = new QBarSet("命中");
QBarSet *set3 = new QBarSet("出手");
QStringList categories;
if (isTeam)
{
vector<shared_ptr<team_avg>>::reverse_iterator riter;
for (riter = teamRank->rbegin(); riter != teamRank->rend(); riter++)
{
*set1 << (*riter)->fgper;
*set2 << (*riter)->fg;
*set3 << (*riter)->fga;
categories << QString::fromStdString((*riter)->name);
}
}
else
{
vector<shared_ptr<player_avg>>::reverse_iterator riter;
for (riter = playerRank->rbegin(); riter != playerRank->rend(); riter++)
{
*set1 << (*riter)->fgper;
*set2 << (*riter)->fg;
*set3 << (*riter)->fga;
categories << QString::fromStdString((*riter)->name);
}
}
QHorizontalBarSeries *series1 = new QHorizontalBarSeries;
series1->append(set1);
series1->setLabelsPosition(QAbstractBarSeries::LabelsInsideEnd);
series1->setLabelsVisible(true);
QHorizontalBarSeries *series2 = new QHorizontalBarSeries;
series2->append(set2);
series2->setLabelsPosition(QAbstractBarSeries::LabelsInsideEnd);
series2->setLabelsVisible(true);
QHorizontalBarSeries *series3 = new QHorizontalBarSeries;
series3->append(set3);
series3->setLabelsPosition(QAbstractBarSeries::LabelsInsideEnd);
series3->setLabelsVisible(true);
// set axis
QBarCategoryAxis *axis1 = new QBarCategoryAxis();
QBarCategoryAxis *axis2 = new QBarCategoryAxis();
QBarCategoryAxis *axis3 = new QBarCategoryAxis();
axis1->append(categories);
axis2->append(categories);
axis3->append(categories);
// update view
QChart *chart1 = new QChart;
chart1->setAnimationOptions(QChart::SeriesAnimations);
chart1->addSeries(series1);
chart1->createDefaultAxes();
chart1->setAxisY(axis1, series1);
QChart *chart2 = new QChart;
chart2->setAnimationOptions(QChart::SeriesAnimations);
chart2->addSeries(series2);
chart2->createDefaultAxes();
chart2->setAxisY(axis2, series2);
QChart *chart3 = new QChart;
chart3->setAnimationOptions(QChart::SeriesAnimations);
chart3->addSeries(series3);
chart3->createDefaultAxes();
chart3->setAxisY(axis3, series3);
if (ui->layoutShoot->itemAt(0) != nullptr)
{
QLayoutItem *child;
while ((child =ui->layoutShoot->takeAt(0)) != 0) {
child->widget()->setParent(nullptr);
ui->layoutShoot->removeItem(child);
}
}
QChartView *view1 = new QChartView;
view1->setChart(chart1);
QChartView *view2 = new QChartView;
view2->setChart(chart2);
QChartView *view3 = new QChartView;
view3->setChart(chart3);
ui->layoutShoot->addWidget(view1, 0, 0);
ui->layoutShoot->addWidget(view2, 1, 0);
ui->layoutShoot->addWidget(view3, 2, 0);
}
void pageRank::showThree()
{
if (ui->stackedWidget->currentWidget() != ui->pageThree)
ui->stackedWidget->setCurrentWidget(ui->pageThree);
ui->scrollAreaWidgetContents->setMinimumHeight(1500);
// modify parameter and send command
para->option = "threepper";
para->season = 2017;
if (isTeam == true)
{
teamRankCommand->setParameter(para);
teamRankCommand->action();
}
else
{
playerRankCommand->setParameter(para);
playerRankCommand->action();
}
// get current data
QBarSet *set1 = new QBarSet("三分");
QBarSet *set2 = new QBarSet("命中");
QBarSet *set3 = new QBarSet("出手");
QStringList categories;
if (isTeam)
{
vector<shared_ptr<team_avg>>::reverse_iterator riter;
for (riter = teamRank->rbegin(); riter != teamRank->rend(); riter++)
{
*set1 << (*riter)->threepper;
*set2 << (*riter)->threep;
*set3 << (*riter)->threepa;
categories << QString::fromStdString((*riter)->name);
}
}
else
{
vector<shared_ptr<player_avg>>::reverse_iterator riter;
for (riter = playerRank->rbegin(); riter != playerRank->rend(); riter++)
{
*set1 << (*riter)->threepper;
*set2 << (*riter)->threep;
*set3 << (*riter)->threepa;
categories << QString::fromStdString((*riter)->name);
}
}
QHorizontalBarSeries *series1 = new QHorizontalBarSeries;
series1->append(set1);
series1->setLabelsPosition(QAbstractBarSeries::LabelsInsideEnd);
series1->setLabelsVisible(true);
QHorizontalBarSeries *series2 = new QHorizontalBarSeries;
series2->append(set2);
series2->setLabelsPosition(QAbstractBarSeries::LabelsInsideEnd);
series2->setLabelsVisible(true);
QHorizontalBarSeries *series3 = new QHorizontalBarSeries;
series3->append(set3);
series3->setLabelsPosition(QAbstractBarSeries::LabelsInsideEnd);
series3->setLabelsVisible(true);
QBarCategoryAxis *axis1 = new QBarCategoryAxis();
QBarCategoryAxis *axis2 = new QBarCategoryAxis();
QBarCategoryAxis *axis3 = new QBarCategoryAxis();
axis1->append(categories);
axis2->append(categories);
axis3->append(categories);
// update view
QChart *chart1 = new QChart;
chart1->setAnimationOptions(QChart::SeriesAnimations);
chart1->addSeries(series1);
chart1->createDefaultAxes();
chart1->setAxisY(axis1, series1);
QChart *chart2 = new QChart;
chart2->setAnimationOptions(QChart::SeriesAnimations);
chart2->addSeries(series2);
chart2->createDefaultAxes();
chart2->setAxisY(axis2, series2);
QChart *chart3 = new QChart;
chart3->setAnimationOptions(QChart::SeriesAnimations);
chart3->addSeries(series3);
chart3->createDefaultAxes();
chart3->setAxisY(axis3, series3);
if (ui->layoutShoot->itemAt(0) != nullptr)
{
QLayoutItem *child;
while ((child =ui->layoutThree->takeAt(0)) != 0) {
child->widget()->setParent(nullptr);
ui->layoutThree->removeItem(child);
}
}
QChartView *view1 = new QChartView;
view1->setChart(chart1);
QChartView *view2 = new QChartView;
view2->setChart(chart2);
QChartView *view3 = new QChartView;
view3->setChart(chart3);
ui->layoutThree->addWidget(view1, 0, 0);
ui->layoutThree->addWidget(view2, 1, 0);
ui->layoutThree->addWidget(view3, 2, 0);
}
void pageRank::showPenalty()
{
if (ui->stackedWidget->currentWidget() != ui->pagePenalty)
ui->stackedWidget->setCurrentWidget(ui->pagePenalty);
ui->scrollAreaWidgetContents->setMinimumHeight(1500);
// modify parameter and send command
para->option = "ftper";
para->season = 2017;
if (isTeam == true)
{
teamRankCommand->setParameter(para);
teamRankCommand->action();
}
else
{
playerRankCommand->setParameter(para);
playerRankCommand->action();
}
// get current data
QBarSet *set1 = new QBarSet("罚球");
QBarSet *set2 = new QBarSet("命中");
QBarSet *set3 = new QBarSet("出手");
QStringList categories;
if (isTeam)
{
vector<shared_ptr<team_avg>>::reverse_iterator riter;
for (riter = teamRank->rbegin(); riter != teamRank->rend(); riter++)
{
*set1 << (*riter)->ftper;
*set2 << (*riter)->ft;
*set3 << (*riter)->fta;
categories << QString::fromStdString((*riter)->name);
}
}
else
{
vector<shared_ptr<player_avg>>::reverse_iterator riter;
for (riter = playerRank->rbegin(); riter != playerRank->rend(); riter++)
{
*set1 << (*riter)->ftper;
*set2 << (*riter)->ft;
*set3 << (*riter)->fta;
categories << QString::fromStdString((*riter)->name);
}
}
QHorizontalBarSeries *series1 = new QHorizontalBarSeries;
series1->append(set1);
series1->setLabelsPosition(QAbstractBarSeries::LabelsInsideEnd);
series1->setLabelsVisible(true);
QHorizontalBarSeries *series2 = new QHorizontalBarSeries;
series2->append(set2);
series2->setLabelsPosition(QAbstractBarSeries::LabelsInsideEnd);
series2->setLabelsVisible(true);
QHorizontalBarSeries *series3 = new QHorizontalBarSeries;
series3->append(set3);
series3->setLabelsPosition(QAbstractBarSeries::LabelsInsideEnd);
series3->setLabelsVisible(true);
QBarCategoryAxis *axis1 = new QBarCategoryAxis();
QBarCategoryAxis *axis2 = new QBarCategoryAxis();
QBarCategoryAxis *axis3 = new QBarCategoryAxis();
axis1->append(categories);
axis2->append(categories);
axis3->append(categories);
// update view
QChart *chart1 = new QChart;
chart1->setAnimationOptions(QChart::SeriesAnimations);
chart1->addSeries(series1);
chart1->createDefaultAxes();
chart1->setAxisY(axis1, series1);
QChart *chart2 = new QChart;
chart2->setAnimationOptions(QChart::SeriesAnimations);
chart2->addSeries(series2);
chart2->createDefaultAxes();
chart2->setAxisY(axis2, series2);
QChart *chart3 = new QChart;
chart3->setAnimationOptions(QChart::SeriesAnimations);
chart3->addSeries(series3);
chart3->createDefaultAxes();
chart3->setAxisY(axis3, series3);
if (ui->layoutShoot->itemAt(0) != nullptr)
{
QLayoutItem *child;
while ((child =ui->layoutPenalty->takeAt(0)) != 0) {
child->widget()->setParent(nullptr);
ui->layoutPenalty->removeItem(child);
}
}
QChartView *view1 = new QChartView;
view1->setChart(chart1);
QChartView *view2 = new QChartView;
view2->setChart(chart2);
QChartView *view3 = new QChartView;
view3->setChart(chart3);
ui->layoutPenalty->addWidget(view1, 0, 0);
ui->layoutPenalty->addWidget(view2, 1, 0);
ui->layoutPenalty->addWidget(view3, 2, 0);
}
void pageRank::showBackboard()
{
if (ui->stackedWidget->currentWidget() != ui->pageBackboard)
ui->stackedWidget->setCurrentWidget(ui->pageBackboard);
ui->scrollAreaWidgetContents->setMinimumHeight(1500);
// modify parameter and send command
para->option = "trb";
para->season = 2017;
if (isTeam == true)
{
teamRankCommand->setParameter(para);
teamRankCommand->action();
}
else
{
playerRankCommand->setParameter(para);
playerRankCommand->action();
}
// get current data
QBarSet *set1 = new QBarSet("篮板");
QBarSet *set2 = new QBarSet("前场");
QBarSet *set3 = new QBarSet("后场");
QStringList categories;
if (isTeam)
{
vector<shared_ptr<team_avg>>::reverse_iterator riter;
for (riter = teamRank->rbegin(); riter != teamRank->rend(); riter++)
{
*set1 << (*riter)->trb;
*set2 << (*riter)->orb;
*set3 << (*riter)->drb;
categories << QString::fromStdString((*riter)->name);
}
}
else
{
vector<shared_ptr<player_avg>>::reverse_iterator riter;
for (riter = playerRank->rbegin(); riter != playerRank->rend(); riter++)
{
*set1 << (*riter)->trb;
*set2 << (*riter)->orb;
*set3 << (*riter)->drb;
categories << QString::fromStdString((*riter)->name);
}
}
QHorizontalBarSeries *series1 = new QHorizontalBarSeries;
series1->append(set1);
series1->setLabelsPosition(QAbstractBarSeries::LabelsInsideEnd);
series1->setLabelsVisible(true);
QHorizontalBarSeries *series2 = new QHorizontalBarSeries;
series2->append(set2);
series2->setLabelsPosition(QAbstractBarSeries::LabelsInsideEnd);
series2->setLabelsVisible(true);
QHorizontalBarSeries *series3 = new QHorizontalBarSeries;
series3->append(set3);
series3->setLabelsPosition(QAbstractBarSeries::LabelsInsideEnd);
series3->setLabelsVisible(true);
QBarCategoryAxis *axis1 = new QBarCategoryAxis();
QBarCategoryAxis *axis2 = new QBarCategoryAxis();
QBarCategoryAxis *axis3 = new QBarCategoryAxis();
axis1->append(categories);
axis2->append(categories);
axis3->append(categories);
// update view
QChart *chart1 = new QChart;
chart1->setAnimationOptions(QChart::SeriesAnimations);
chart1->addSeries(series1);
chart1->createDefaultAxes();
chart1->setAxisY(axis1, series1);
QChart *chart2 = new QChart;
chart2->setAnimationOptions(QChart::SeriesAnimations);
chart2->addSeries(series2);
chart2->createDefaultAxes();
chart2->setAxisY(axis2, series2);
QChart *chart3 = new QChart;
chart3->setAnimationOptions(QChart::SeriesAnimations);
chart3->addSeries(series3);
chart3->createDefaultAxes();
chart3->setAxisY(axis3, series3);
if (ui->layoutShoot->itemAt(0) != nullptr)
{
QLayoutItem *child;
while ((child =ui->layoutBackboard->takeAt(0)) != 0) {
child->widget()->setParent(nullptr);
ui->layoutBackboard->removeItem(child);
}
}
QChartView *view1 = new QChartView;
view1->setChart(chart1);
QChartView *view2 = new QChartView;
view2->setChart(chart2);
QChartView *view3 = new QChartView;
view3->setChart(chart3);
ui->layoutBackboard->addWidget(view1, 0, 0);
ui->layoutBackboard->addWidget(view2, 1, 0);
ui->layoutBackboard->addWidget(view3, 2, 0);
}
void pageRank::showAssisting()
{
if (ui->stackedWidget->currentWidget() != ui->pageAssisting)
ui->stackedWidget->setCurrentWidget(ui->pageAssisting);
ui->scrollAreaWidgetContents->setMinimumHeight(1500);
// modify parameter and send command
para->option = "ast";
para->season = 2017;
if (isTeam == true)
{
teamRankCommand->setParameter(para);
teamRankCommand->action();
}
else
{
playerRankCommand->setParameter(para);
playerRankCommand->action();
}
// get current data
QBarSet *set1 = new QBarSet("助攻");
QBarSet *set2 = new QBarSet("抢断");
QBarSet *set3 = new QBarSet("盖帽");
QStringList categories;
if (isTeam)
{
vector<shared_ptr<team_avg>>::reverse_iterator riter;
for (riter = teamRank->rbegin(); riter != teamRank->rend(); riter++)
{
*set1 << (*riter)->ast;
*set2 << (*riter)->stl;
*set3 << (*riter)->blk;
categories << QString::fromStdString((*riter)->name);
}
}
else
{
vector<shared_ptr<player_avg>>::reverse_iterator riter;
for (riter = playerRank->rbegin(); riter != playerRank->rend(); riter++)
{
*set1 << (*riter)->ast;
*set2 << (*riter)->stl;
*set3 << (*riter)->blk;
categories << QString::fromStdString((*riter)->name);
}
}
QHorizontalBarSeries *series1 = new QHorizontalBarSeries;
series1->append(set1);
series1->setLabelsPosition(QAbstractBarSeries::LabelsInsideEnd);
series1->setLabelsVisible(true);
QHorizontalBarSeries *series2 = new QHorizontalBarSeries;
series2->append(set2);
series2->setLabelsPosition(QAbstractBarSeries::LabelsInsideEnd);
series2->setLabelsVisible(true);
QHorizontalBarSeries *series3 = new QHorizontalBarSeries;
series3->append(set3);
series3->setLabelsPosition(QAbstractBarSeries::LabelsInsideEnd);
series3->setLabelsVisible(true);
QBarCategoryAxis *axis1 = new QBarCategoryAxis();
QBarCategoryAxis *axis2 = new QBarCategoryAxis();
QBarCategoryAxis *axis3 = new QBarCategoryAxis();
axis1->append(categories);
axis2->append(categories);
axis3->append(categories);
// update view
QChart *chart1 = new QChart;
chart1->setAnimationOptions(QChart::SeriesAnimations);
chart1->addSeries(series1);
chart1->createDefaultAxes();
chart1->setAxisY(axis1, series1);
QChart *chart2 = new QChart;
chart2->setAnimationOptions(QChart::SeriesAnimations);
chart2->addSeries(series2);
chart2->createDefaultAxes();
chart2->setAxisY(axis2, series2);
QChart *chart3 = new QChart;
chart3->setAnimationOptions(QChart::SeriesAnimations);
chart3->addSeries(series3);
chart3->createDefaultAxes();
chart3->setAxisY(axis3, series3);
if (ui->layoutShoot->itemAt(0) != nullptr)
{
QLayoutItem *child;
while ((child =ui->layoutAssisting->takeAt(0)) != 0) {
child->widget()->setParent(nullptr);
ui->layoutAssisting->removeItem(child);
}
}
QChartView *view1 = new QChartView;
view1->setChart(chart1);
QChartView *view2 = new QChartView;
view2->setChart(chart2);
QChartView *view3 = new QChartView;
view3->setChart(chart3);
ui->layoutAssisting->addWidget(view1, 0, 0);
ui->layoutAssisting->addWidget(view2, 1, 0);
ui->layoutAssisting->addWidget(view3, 2, 0);
}
void pageRank::showFalut()
{
if (ui->stackedWidget->currentWidget() != ui->pageFalut)
ui->stackedWidget->setCurrentWidget(ui->pageFalut);
ui->scrollAreaWidgetContents->setMinimumHeight(1500);
// modify parameter and send command
para->option = "tov";
para->season = 2017;
if (isTeam == true)
{
teamRankCommand->setParameter(para);
teamRankCommand->action();
}
else
{
playerRankCommand->setParameter(para);
playerRankCommand->action();
}
// get current data
QBarSet *set1 = new QBarSet("失误");
QBarSet *set2 = new QBarSet("犯规");
QStringList categories;
if (isTeam)
{
vector<shared_ptr<team_avg>>::reverse_iterator riter;
for (riter = teamRank->rbegin(); riter != teamRank->rend(); riter++)
{
*set1 << (*riter)->tov;
*set2 << (*riter)->pf;
categories << QString::fromStdString((*riter)->name);
}
}
else
{
vector<shared_ptr<player_avg>>::reverse_iterator riter;
for (riter = playerRank->rbegin(); riter != playerRank->rend(); riter++)
{
*set1 << (*riter)->tov;
*set2 << (*riter)->pf;
categories << QString::fromStdString((*riter)->name);
}
}
QHorizontalBarSeries *series1 = new QHorizontalBarSeries;
series1->append(set1);
series1->setLabelsPosition(QAbstractBarSeries::LabelsInsideEnd);
series1->setLabelsVisible(true);
QHorizontalBarSeries *series2 = new QHorizontalBarSeries;
series2->append(set2);
series2->setLabelsPosition(QAbstractBarSeries::LabelsInsideEnd);
series2->setLabelsVisible(true);
QBarCategoryAxis *axis1 = new QBarCategoryAxis();
QBarCategoryAxis *axis2 = new QBarCategoryAxis();
axis1->append(categories);
axis2->append(categories);
// update view
QChart *chart1 = new QChart;
chart1->setAnimationOptions(QChart::SeriesAnimations);
chart1->addSeries(series1);
chart1->createDefaultAxes();
chart1->setAxisY(axis1, series1);
QChart *chart2 = new QChart;
chart2->setAnimationOptions(QChart::SeriesAnimations);
chart2->addSeries(series2);
chart2->createDefaultAxes();
chart2->setAxisY(axis2, series2);
if (ui->layoutShoot->itemAt(0) != nullptr)
{
QLayoutItem *child;
while ((child =ui->layoutFalut->takeAt(0)) != 0) {
child->widget()->setParent(nullptr);
ui->layoutFalut->removeItem(child);
}
}
QChartView *view1 = new QChartView;
view1->setChart(chart1);
QChartView *view2 = new QChartView;
view2->setChart(chart2);
ui->layoutFalut->addWidget(view1, 0, 0);
ui->layoutFalut->addWidget(view2, 1, 0);
}
void pageRank::showScore()
{
if (ui->stackedWidget->currentWidget() != ui->pageScore)
ui->stackedWidget->setCurrentWidget(ui->pageScore);
ui->scrollAreaWidgetContents->setMinimumHeight(500);
// modify parameter and send command
para->option = "pts";
para->season = 2017;
if (isTeam == true)
{
teamRankCommand->setParameter(para);
teamRankCommand->action();
}
else
{
playerRankCommand->setParameter(para);
playerRankCommand->action();
}
// get current data
QBarSet *set1 = new QBarSet("得分");
QStringList categories;
if (isTeam)
{
vector<shared_ptr<team_avg>>::reverse_iterator riter;
for (riter = teamRank->rbegin(); riter != teamRank->rend(); riter++)
{
*set1 << (*riter)->pts;
categories << QString::fromStdString((*riter)->name);
}
}
else
{
vector<shared_ptr<player_avg>>::reverse_iterator riter;
for (riter = playerRank->rbegin(); riter != playerRank->rend(); riter++)
{
*set1 << (*riter)->pts;
categories << QString::fromStdString((*riter)->name);
}
}
QHorizontalBarSeries *series1 = new QHorizontalBarSeries;
series1->append(set1);
series1->setLabelsPosition(QAbstractBarSeries::LabelsInsideEnd);
series1->setLabelsVisible(true);
QBarCategoryAxis *axis1 = new QBarCategoryAxis();
axis1->append(categories);
// update view
QChart *chart1 = new QChart;
chart1->setAnimationOptions(QChart::SeriesAnimations);
chart1->addSeries(series1);
chart1->createDefaultAxes();
chart1->setAxisY(axis1, series1);
if (ui->layoutShoot->itemAt(0) != nullptr)
{
QLayoutItem *child;
while ((child =ui->layoutScore->takeAt(0)) != 0) {
child->widget()->setParent(nullptr);
ui->layoutScore->removeItem(child);
}
}
QChartView *view1 = new QChartView;
view1->setChart(chart1);
ui->layoutScore->addWidget(view1, 0, 0);
}
void pageRank::showVictory()
{
if (ui->stackedWidget->currentWidget() != ui->pageVictory)
ui->stackedWidget->setCurrentWidget(ui->pageVictory);
ui->scrollAreaWidgetContents->setMinimumHeight(1000);
// modify parameter and send command
para->season = 2017;
if (isTeam == true)
{
para->option = "wg";
teamRankCommand->setParameter(para);
teamRankCommand->action();
}
else
{
para->option = "w";
playerRankCommand->setParameter(para);
playerRankCommand->action();
}
// get current data
QBarSet *set1 = new QBarSet("胜");
QBarSet *set2 = new QBarSet("负");
QStringList categories;
if (isTeam)
{
vector<shared_ptr<team_avg>>::reverse_iterator riter;
for (riter = teamRank->rbegin(); riter != teamRank->rend(); riter++)
{
*set1 << (*riter)->wg;
*set2 << (*riter)->lg;
categories << QString::fromStdString((*riter)->name);
}
}
else
{
vector<shared_ptr<player_avg>>::reverse_iterator riter;
for (riter = playerRank->rbegin(); riter != playerRank->rend(); riter++)
{
*set1 << (*riter)->w;
*set2 << (*riter)->l;
categories << QString::fromStdString((*riter)->name);
}
}
QHorizontalBarSeries *series1 = new QHorizontalBarSeries;
series1->append(set1);
series1->setLabelsPosition(QAbstractBarSeries::LabelsInsideEnd);
series1->setLabelsVisible(true);
QHorizontalBarSeries *series2 = new QHorizontalBarSeries;
series2->append(set2);
series2->setLabelsPosition(QAbstractBarSeries::LabelsInsideEnd);
series2->setLabelsVisible(true);
QBarCategoryAxis *axis1 = new QBarCategoryAxis();
QBarCategoryAxis *axis2 = new QBarCategoryAxis();
axis1->append(categories);
axis2->append(categories);
// update view
QChart *chart1 = new QChart;
chart1->setAnimationOptions(QChart::SeriesAnimations);
chart1->addSeries(series1);
chart1->createDefaultAxes();
chart1->setAxisY(axis1, series1);
QChart *chart2 = new QChart;
chart2->setAnimationOptions(QChart::SeriesAnimations);
chart2->addSeries(series2);
chart2->createDefaultAxes();
chart2->setAxisY(axis2, series2);
if (ui->layoutShoot->itemAt(0) != nullptr)
{
QLayoutItem *child;
while ((child =ui->layoutVictory->takeAt(0)) != 0) {
child->widget()->setParent(nullptr);
ui->layoutVictory->removeItem(child);
}
}
QChartView *view1 = new QChartView;
view1->setChart(chart1);
QChartView *view2 = new QChartView;
view2->setChart(chart2);
ui->layoutVictory->addWidget(view1, 0, 0);
ui->layoutVictory->addWidget(view2, 1, 0);
}
void pageRank::setTeamRankCommand(std::shared_ptr<command> ptr)
{
teamRankCommand = ptr;
}
void pageRank::setPlayerRankCommand(shared_ptr<command> ptr)
{
playerRankCommand = ptr;
}
void pageRank::setPlayerRank(shared_ptr<vector<shared_ptr<player_avg>>> playerRank)
{
this->playerRank = playerRank;
}
void pageRank::setTeamRank(shared_ptr<vector<shared_ptr<team_avg>>> teamRank)
{
this->teamRank = teamRank;
}
void pageRank::on_buttonTeam_clicked()
{
isTeam = true;
showShoot();
}
void pageRank::on_buttonPlayer_clicked()
{
isTeam = false;
showShoot();
}
|
3c1464346e1f684ebb7e0489a16a2cc0d82384d6
|
4d815360a103946d046998458292ac50edd024e9
|
/Uno/main.cpp
|
ec0977e5df5eb7d9ec3ff20d4d7de7a4d4c32fe3
|
[] |
no_license
|
KingFroz/CodeSnippets
|
d535160b54888ad9dbf8b2895aa757100ce6bfbe
|
54d1eb2fb502819b6b4e76033be0b46b3c4a49e0
|
refs/heads/master
| 2021-04-12T07:27:21.408941
| 2018-07-17T15:04:42
| 2018-07-17T15:04:42
| 94,508,851
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,238
|
cpp
|
main.cpp
|
// main.cpp : Entry point for the project
// This includes all of our standard headers
#include "src\\UnitTest++.h"
#include "src\\TestReporterStdout.h"
#include "stdafx.h"
#include "TestManager.h"
#include "Game.h"
/***********/
/* Globals */
/***********/
/**************/
/* Prototypes */
/**************/
// Our primary routine. This is called when the program starts.
//
// Return: We always return 0.
int main(int, const char*[])
{
// This will check for memory leaks. They will show up in your
// output window along with the line number. Replace the
// -1 argument in the second call with the allocation number
// and then trace back through the call stack to find the leak.
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
_CrtSetBreakAlloc(-1);
srand(unsigned int(time(0)));
/*
#if LAB1
UnitTest::RunAllTests();
#elif LAB2
UnitTest::RunAllTests();
#elif LAB3
UnitTest::RunAllTests();
#elif LAB4
UnitTest::RunAllTests();
#elif LAB6
UnitTest::RunAllTests();
#elif LAB7
UnitTest::RunAllTests();
#eliF GAME
Game game;
game.Run();
#endif
*/
#if GAME
Game game;
game.Run();
#else
UnitTest::RunAllTests();
#endif
Console::ResetColor();
cout << "\n\n";
system("pause");
return 0;
}
|
55ef41917db6dac8981382fc2770d6511ecbf436
|
6207880e0d033a1fd4427738f315dece3350e94b
|
/EinsteinPrototype/Scenes/AlertViewScene.h
|
ebf0a03ee6da9101c4d1c240bec639d14b0ca61c
|
[] |
no_license
|
Crasader/AlbertEinstein
|
1b08854558f3820679181fd9f8cb70e91cb75234
|
6b32c209dbef4d748e7ac5657cf6a389e8c0a560
|
refs/heads/master
| 2020-12-12T23:39:39.433935
| 2014-05-23T20:58:03
| 2014-05-23T20:58:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,208
|
h
|
AlertViewScene.h
|
//
// AlertViewScene.h
// EinsteinPrototype
//
// Created by Marco Rossi on 2/14/13.
// Copyright (c) 2013 Farofa Studios. All rights reserved.
//
#ifndef __EinsteinPrototype__AlertViewScene__
#define __EinsteinPrototype__AlertViewScene__
#include <iostream>
#include "Enumerations.h"
/**************************************************************
**** Exibe Popup de Rota e Estacionamento ***
**************************************************************/
class AlertViewScene {
private:
public:
static bool isActive ;
static void showMessageRota(cocos2d::CCNode* sender, cocos2d::SEL_MenuHandler callbackFunction , int wayPoint);
static void showMessageParking
(cocos2d::CCNode* sender, cocos2d::SEL_MenuHandler callbackFunction , int wayPoint);
static void showMessageParkingOption(cocos2d::CCNode* parent, cocos2d::SEL_MenuHandler entering,cocos2d::SEL_MenuHandler outing,cocos2d::SEL_MenuHandler quiting);
static void showMessageSearch(cocos2d::CCNode* sender, cocos2d::SEL_MenuHandler callbackFunction);
void btnCloseAlert(cocos2d::CCObject *sender);
};
#endif /* defined(__EinsteinPrototype__AlertViewScene__) */
|
e4510595698e67e25d8b7f8d8cacdf8dbd486ce4
|
7707a9fcbde28b547f462b44f10243d85a4d2c01
|
/Cpp/Stone/src/stone_ast.h
|
c4c72b7bd9df533145d61e5aab7f70f98aca29ae
|
[] |
no_license
|
BruceChen7/ToysCode
|
3db20377ff2dd5d5d373527c47cf11e8295bebe2
|
9f1eecf58b2f94ef46a7b7dcd9b18757563cf09f
|
refs/heads/master
| 2022-12-22T07:48:31.405552
| 2019-08-15T03:47:07
| 2019-08-15T03:47:07
| 28,715,550
| 6
| 0
| null | 2022-12-16T01:51:30
| 2015-01-02T14:30:22
|
C++
|
UTF-8
|
C++
| false
| false
| 2,185
|
h
|
stone_ast.h
|
#ifndef __STONE_SRC_STONE_AST__
#define __STONE_SRC_STONE_AST__
#include <memory>
#include <vector>
#include "lexical.h"
namespace Stone
{
class AstLeafNode;
class AstNumber;
class AstIdentifier;
class AstString;
class AstOperation;
class IVisitor
{
public:
virtual bool visit(AstNumber* number) = 0;
virtual bool visit(AstIdentifier* identifer) = 0;
virtual bool visit(AstOperation* operation) = 0;
virtual bool visit(AstString* operation) = 0;
};
/**
* It's a base class used by AstNumber, AstIdentifier
* AstString class
*
*/
class AstLeafNode
{
public:
virtual bool parse(IVisitor* visitor) = 0;
std::shared_ptr<struct Token> get_token()
{
return token_;
}
private:
std::shared_ptr<struct Token> token_;
};
class AstParser:public IVisitor
{
public:
bool visit(AstNumber* number);
bool visit(AstString* string);
bool visit(AstIdentifier* Identifier);
bool visit(AstOperation* opeation);
private:
//private method
bool parse_ast_leaf(AstLeafNode* node, Code_Token_Type type);
//data member
int err_line_num_;
std::string err_msg_;
};
class AstNumber:public AstLeafNode
{
public:
using Ptr = std::shared_ptr<struct Token>;
bool parse(IVisitor* visitor)
{
return visitor->visit(this);
}
};
class AstString:public AstLeafNode
{
public:
using Ptr = std::shared_ptr<struct Token>;
bool parse(IVisitor* visitor)
{
return visitor->visit(this);
}
};
class AstIdentifier:public AstLeafNode
{
public:
using Ptr = std::shared_ptr<struct Token>;
bool parse(IVisitor* visitor)
{
return visitor->visit(this);
}
};
}
#endif
|
1ae5f0236d701029e1587e03737a19dfe9ca54f6
|
783c9e1061bb55541f873cfcd86d82fc20be2eb2
|
/ProcToThreads/main.cpp
|
71037a83e07cc2d09e6852e0747d3a6ea454e8ec
|
[] |
no_license
|
Komdosh/MPI_TESTS
|
f4cbae2e460c0c6d45b7ab7cc3125f0985b80e0d
|
d16e8c8c3504355e96a6110c923c9cb6d887b78b
|
refs/heads/master
| 2020-03-30T08:41:55.116055
| 2020-01-19T12:14:39
| 2020-01-19T12:14:39
| 151,032,770
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,075
|
cpp
|
main.cpp
|
#include <iostream>
#include <x86intrin.h>
#include <mpi.h>
#include <unistd.h>
#include "cpu_helper.cpp"
int ELEMENTS = 50000;
int CORES = 4;
int NUM_OF_THREADS = 3;
int RATE = 10000;
using namespace std;
struct ThreadData_s {
int threadId;
int rank;
int *shared;
double *times;
};
typedef ThreadData_s ThreadData;
pthread_barrier_t pThreadBarrier;
void sendSharedArr(int *arrToSend, int destRank, int tag) {
for (int i = 0; i < RATE; ++i) {
MPI_Send(&(arrToSend[0]), ELEMENTS, MPI_INT, destRank, tag, MPI_COMM_WORLD);
// printf("SEND: destRank: %d, tag: %d\n", destRank, tag);
}
}
void receiveSharedArr(int sourceRank, int tag) {
int *local = new int[ELEMENTS];
for (int i = 0; i < RATE; ++i) {
MPI_Recv(&(local[0]), ELEMENTS, MPI_INT, sourceRank, tag, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
// printf("RES: rank: %d, arr: %d\n", sourceRank, local[0]);
}
}
void *MPIAction(void *threadarg) {
auto *threadData = (ThreadData *) threadarg;
int rank = threadData->rank;
int threadId = threadData->threadId;
int *shared = threadData->shared;
double *times = threadData->times;
double start = MPI_Wtime();
pthread_barrier_wait(&pThreadBarrier);
if (threadId == NUM_OF_THREADS - 1) {
MPI_Barrier(MPI_COMM_WORLD);
}
sendSharedArr(shared, threadId + 1, threadId + 1);
// printf("MAIN RECV: sourceRank: %d, tag: %d\n", threadId+1, threadId+1);
receiveSharedArr(threadId + 1, threadId + 1);
times[threadId] = MPI_Wtime() - start;
pthread_exit(nullptr);
}
void runMPI(char **argv) {
int provided;
int rank, np, len;
char processorName[MPI_MAX_PROCESSOR_NAME];
int argc = 1;
MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &np);
MPI_Get_processor_name(processorName, &len);
double times[NUM_OF_THREADS];
if (rank == 0) {
pthread_barrier_init(&pThreadBarrier, nullptr, NUM_OF_THREADS);
cpu_set_t cpuset[CORES];
pthread_t threads[NUM_OF_THREADS];
for (int i = 0; i < CORES; i++) {
CPU_ZERO(&cpuset[i]);
CPU_SET(i, &cpuset[i]);
}
int shared[NUM_OF_THREADS][ELEMENTS];
ThreadData td[NUM_OF_THREADS];
for (int i = 0; i < NUM_OF_THREADS; i++) {
td[i].rank = rank;
td[i].threadId = i;
td[i].shared = shared[i];
td[i].times = times;
for (int n = 0; n < ELEMENTS; n++) {
shared[i][n] = (rank + 1) * 100 + (i + 1) * 10 + n;
}
int rc = pthread_create(&threads[i], nullptr, MPIAction, (void *) &td[i]);
int s = pthread_setaffinity_np(threads[i], sizeof(cpu_set_t), &cpuset[i % CORES]);
if (s != 0) {
pthread_exit(nullptr);
}
if (rc) {
exit(-1);
}
}
double maxTime = 0.0;
for (int i = 0; i < NUM_OF_THREADS; i++) {
pthread_join(threads[i], nullptr);
if (maxTime < times[i]) {
maxTime = times[i];
}
}
pthread_barrier_destroy(&pThreadBarrier);
printf("%d\n", (int) (maxTime * 1000));
} else {
int *shared = new int[ELEMENTS]{0};
for (int n = 0; n < ELEMENTS; n++) {
shared[n] = (rank + 1) * 100 + (rank + 1) * 10 + n;
}
// printf("CHILD RECV: sourceRank: %d, tag: %d\n", 0, rank);
MPI_Barrier(MPI_COMM_WORLD);
receiveSharedArr(0, rank);
sendSharedArr(shared, 0, rank);
}
MPI_Finalize();
}
int main(int argc, char **argv) {
NUM_OF_THREADS = atoi(argv[1]) - 1;
CORES = atoi(argv[2]);
RATE = atoi(argv[3]);
ELEMENTS = atoi(argv[4]);
if (NUM_OF_THREADS < 2) {
printf("Threads number should be greater than 2\n");
exit(1);
}
char *args[] = {
(char *) "VerySimple",
NULL
};
runMPI(args);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.