blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
sequencelengths
1
1
author_id
stringlengths
0
158
3179f1d5ecff66c0c70ff3c591162a06e19fa35d
e2df82085ac658a7ca7c974919f3809e89d646bb
/LibWebRtcUsingExample/Include/modules/audio_processing/residual_echo_detector.h
e8ae552d6c0979e53c984a774eb3888bdc1d1e9e
[ "Apache-2.0", "MIT" ]
permissive
HATTER-LONG/NoteBook_WebRtcLearning
7c846cf548804361123ff9cd6017cc05b3b9a559
834c94c82646e57d53fa5f1cc8210dda3799b78f
refs/heads/master
2023-06-30T21:45:56.672079
2021-08-07T08:46:34
2021-08-07T08:46:34
338,822,304
3
2
null
2021-02-14T14:33:08
2021-02-14T14:22:12
null
UTF-8
C++
false
false
3,421
h
/* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef MODULES_AUDIO_PROCESSING_RESIDUAL_ECHO_DETECTOR_H_ #define MODULES_AUDIO_PROCESSING_RESIDUAL_ECHO_DETECTOR_H_ #include <vector> #include "api/array_view.h" #include "modules/audio_processing/echo_detector/circular_buffer.h" #include "modules/audio_processing/echo_detector/mean_variance_estimator.h" #include "modules/audio_processing/echo_detector/moving_max.h" #include "modules/audio_processing/echo_detector/normalized_covariance_estimator.h" #include "modules/audio_processing/include/audio_processing.h" namespace webrtc { class ApmDataDumper; class AudioBuffer; class ResidualEchoDetector : public EchoDetector { public: ResidualEchoDetector(); ~ResidualEchoDetector() override; // This function should be called while holding the render lock. void AnalyzeRenderAudio(rtc::ArrayView<const float> render_audio) override; // This function should be called while holding the capture lock. void AnalyzeCaptureAudio(rtc::ArrayView<const float> capture_audio) override; // This function should be called while holding the capture lock. void Initialize(int sample_rate_hz, int num_channels) override; // This function is for testing purposes only. void SetReliabilityForTest(float value) { reliability_ = value; } // This function should be called while holding the capture lock. EchoDetector::Metrics GetMetrics() const override; private: static int instance_count_; std::unique_ptr<ApmDataDumper> data_dumper_; // Keep track if the |Process| function has been previously called. bool first_process_call_ = true; // Buffer for storing the power of incoming farend buffers. This is needed for // cases where calls to BufferFarend and Process are jittery. CircularBuffer render_buffer_; // Count how long ago it was that the size of |render_buffer_| was zero. This // value is also reset to zero when clock drift is detected and a value from // the renderbuffer is discarded, even though the buffer is not actually zero // at that point. This is done to avoid repeatedly removing elements in this // situation. size_t frames_since_zero_buffer_size_ = 0; // Circular buffers containing delayed versions of the power, mean and // standard deviation, for calculating the delayed covariance values. std::vector<float> render_power_; std::vector<float> render_power_mean_; std::vector<float> render_power_std_dev_; // Covariance estimates for different delay values. std::vector<NormalizedCovarianceEstimator> covariances_; // Index where next element should be inserted in all of the above circular // buffers. size_t next_insertion_index_ = 0; MeanVarianceEstimator render_statistics_; MeanVarianceEstimator capture_statistics_; // Current echo likelihood. float echo_likelihood_ = 0.f; // Reliability of the current likelihood. float reliability_ = 0.f; MovingMax recent_likelihood_max_; int log_counter_ = 0; }; } // namespace webrtc #endif // MODULES_AUDIO_PROCESSING_RESIDUAL_ECHO_DETECTOR_H_
c77db69fa1ac15bfe3c82a9d8894468cc3b55117
dc8eddcc1944b03bb622248c83536fd4639ad6e3
/indurop/dependency/bicomc/include/bicomc/detail/compiler/gcc_atomic.h
f1a590e348f3c2253e8cb3e355cbf004a7fde56b
[]
no_license
MinsooK/RSP
3284692e4a5a614e0e61817f91804b731d2d35a5
e038ba46e12a2076bf07f83e13c3ae8ae311a457
refs/heads/master
2021-01-01T06:56:50.087016
2017-07-18T05:47:13
2017-07-18T05:47:13
97,426,652
0
0
null
null
null
null
UTF-8
C++
false
false
1,902
h
#ifndef BICOMC_DETAIL_COMPILER_GCC_ATOMIC_H__ #define BICOMC_DETAIL_COMPILER_GCC_ATOMIC_H__ #if !defined(__GNUC__) # error "compiler is not gcc" #endif // !def __GNUC__ #include "../../stdint.h" #include "../../type_traits.h" namespace bcc { namespace detail { #if __GNUC__ >= 4 && __GNUC_MINOR__ >= 7 inline void atomic_store(atomic_intptr_t* pObject, bcc::intptr_t desired) BICOMC_NOEXCEPT { __atomic_store_n(pObject, desired, __ATOMIC_SEQ_CST); } inline bcc::intptr_t atomic_load(atomic_intptr_t const* pObject) BICOMC_NOEXCEPT { return __atomic_load_n(pObject, __ATOMIC_SEQ_CST); } inline bcc::intptr_t atomic_exchange(atomic_intptr_t* pObject, bcc::intptr_t desired) BICOMC_NOEXCEPT { return __atomic_exchange_n(pObject, desired, __ATOMIC_SEQ_CST); } inline bool atomic_compare_exchange_strong(atomic_intptr_t* pObject, bcc::intptr_t* pExpected, bcc::intptr_t desired) BICOMC_NOEXCEPT { return __atomic_compare_exchange_n(pObject, pExpected, desired, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); } #else inline void atomic_store(atomic_intptr_t* pObject, bcc::intptr_t desired) BICOMC_NOEXCEPT { __sync_lock_test_and_set(pObject, desired); } inline bcc::intptr_t atomic_load(atomic_intptr_t const* pObject) BICOMC_NOEXCEPT { return __sync_fetch_and_or(const_cast<atomic_intptr_t*>(pObject), 0); } inline bcc::intptr_t atomic_exchange(atomic_intptr_t* pObject, bcc::intptr_t desired) BICOMC_NOEXCEPT { return __sync_lock_test_and_set(pObject, desired); } inline bool atomic_compare_exchange_strong(atomic_intptr_t* pObject, bcc::intptr_t* pExpected, bcc::intptr_t desired) BICOMC_NOEXCEPT { bcc::intptr_t e = *pExpected; return e == (*pExpected = __sync_val_compare_and_swap(pObject, e, desired)); } #endif // __GNUC__ >= 4 && __GNUC_MINOR__ >= 7 } // namespace detail } // namespace bcc #endif // !def BICOMC_DETAIL_COMPILER_GCC_ATOMIC_H__
adc4caac007bf90e6db908443b263b05c677bf7c
4c25432a6d82aaebd82fd48e927317b15a6bf6ab
/data/dataset_2017/dataset_2017_8/TheEnglishMajor27/8294486_5654117850546176_TheEnglishMajor27.cpp
b4c0aa8a3a8f5a57d0032df3b2c633684a82aa4b
[]
no_license
wzj1988tv/code-imitator
dca9fb7c2e7559007e5dbadbbc0d0f2deeb52933
07a461d43e5c440931b6519c8a3f62e771da2fc2
refs/heads/master
2020-12-09T05:33:21.473300
2020-01-09T15:29:24
2020-01-09T15:29:24
231,937,335
1
0
null
2020-01-05T15:28:38
2020-01-05T15:28:37
null
UTF-8
C++
false
false
1,771
cpp
#include <bits/stdc++.h> using namespace std; #define x first #define y second typedef long long ll; typedef pair<int,int> pt; const int base = 1000000007; const int maxn = 100002; int n; char res[maxn]; pt a[maxn]; bool cmp(pt a,pt b) { return (a.x > b.x); } void solve(int test) { int i,j; int s[10]; scanf("%d",&n); for (i=1;i<=6;i++) scanf("%d",&s[i]); a[1].x = s[1]; a[1].y = 'R'; a[2].x = s[3]; a[2].y = 'Y'; a[3].x = s[5]; a[3].y = 'B'; //if (n<=20) printf("%d %d 0 %d 0 %d 0 \n",n,a[1].x,a[2].x,a[3].x); printf("Case #%d: ",test); if (a[1].x > a[2].x + a[3].x) {printf("IMPOSSIBLE\n"); return;} if (a[2].x > a[1].x + a[3].x) {printf("IMPOSSIBLE\n"); return;} if (a[3].x > a[2].x + a[1].x) {printf("IMPOSSIBLE\n"); return;} sort(a+1,a+3+1,cmp); res[1] = a[1].y; a[1].x--; for (i=2;i<=n;i++) { sort(a+1,a+3+1,cmp); if (a[1].y!=res[i-1]) {res[i] = a[1].y; a[1].x--;} else { if (res[i-2]==a[2].y) { if (a[2].x > 0) {a[2].x--; res[i] = a[2].y;} else {a[3].x--; res[i] = a[3].y;} } else if (res[i-2]==a[3].y) { if (a[3].x > 0) {a[3].x--; res[i] = a[3].y;} else {a[2].x--; res[i] = a[2].y;} } else if (a[2].x > 0) {a[2].x--; res[i] = a[2].y;} else if (a[3].x > 0) {a[3].x--; res[i] = a[3].y;} } } if (res[n]==res[1]) swap(res[n],res[n-1]); res[n+1] = 0; printf("%s\n",res+1); } int main() { int i,t; freopen("B.in","r",stdin); freopen("B1.out","w",stdout); scanf("%d",&t); for (i=1;i<=t;i++) solve(i); return 0; }
c7a86e8e4cbfde558e0720adca59c001d79f58cf
e12e3156a18af57bd689a683e25dc062a7a06ce6
/vendors/XQilla-2.3.3/src/functions/XQUserFunction.cpp
1e885cbfca806fbac39b45e344fcf0f2f92e71b2
[ "Apache-2.0" ]
permissive
FeiLuo/xpathDemo
0d041862f665c1630af620461020b3c5f0119d36
79a8c4fd9aa6aef3c14982e091921d3c051856a5
refs/heads/master
2021-01-24T10:53:55.763897
2016-10-08T11:57:59
2016-10-08T11:57:59
70,307,372
0
0
null
null
null
null
UTF-8
C++
false
false
29,238
cpp
/* * Copyright (c) 2001-2008 * DecisionSoft Limited. All rights reserved. * Copyright (c) 2004-2008 * Oracle. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * $Id$ */ #include <sstream> #include <xqilla/framework/XQillaExport.hpp> #include <xqilla/functions/XQUserFunction.hpp> #include <xqilla/exceptions/FunctionException.hpp> #include <xqilla/exceptions/XPath2TypeMatchException.hpp> #include <xqilla/exceptions/StaticErrorException.hpp> #include <xqilla/ast/XQSequence.hpp> #include <xqilla/ast/XQVariable.hpp> #include <xqilla/context/VariableStore.hpp> #include <xqilla/context/VariableTypeStore.hpp> #include <xqilla/utils/XPath2NSUtils.hpp> #include <xqilla/utils/XPath2Utils.hpp> #include <xqilla/context/DynamicContext.hpp> #include <xqilla/context/ContextHelpers.hpp> #include <xqilla/ast/XQTreatAs.hpp> #include <xqilla/update/PendingUpdateList.hpp> #include <xqilla/exceptions/StaticErrorException.hpp> #include <xqilla/runtime/ClosureResult.hpp> #include <xqilla/optimizer/ASTVisitor.hpp> #include <xqilla/optimizer/StaticTyper.hpp> #include "../lexer/XQLexer.hpp" #include <xercesc/util/XMLString.hpp> #include <xercesc/framework/XMLBuffer.hpp> #include <xercesc/validators/schema/SchemaSymbols.hpp> #include <xercesc/validators/datatype/DatatypeValidator.hpp> XERCES_CPP_NAMESPACE_USE; using namespace std; /* http://www.w3.org/2005/xquery-local-functions */ const XMLCh XQUserFunction::XMLChXQueryLocalFunctionsURI[] = { chLatin_h, chLatin_t, chLatin_t, chLatin_p, chColon, chForwardSlash, chForwardSlash, chLatin_w, chLatin_w, chLatin_w, chPeriod, chLatin_w, chDigit_3, chPeriod, chLatin_o, chLatin_r, chLatin_g, chForwardSlash, chDigit_2, chDigit_0, chDigit_0, chDigit_5, chForwardSlash, chLatin_x, chLatin_q, chLatin_u, chLatin_e, chLatin_r, chLatin_y, chDash, chLatin_l, chLatin_o, chLatin_c, chLatin_a, chLatin_l, chDash, chLatin_f, chLatin_u, chLatin_n, chLatin_c, chLatin_t, chLatin_i, chLatin_o, chLatin_n, chLatin_s, chNull }; XQUserFunction::XQUserFunction(const XMLCh *qname, FunctionSignature *signature, ASTNode *body, bool isGlobal, XPath2MemoryManager *mm) : FuncFactory(signature->argSpecs == 0 ? 0 : signature->argSpecs->size(), mm), body_(body), exFunc_(NULL), qname_(qname), pattern_(0), templateInstance_(0), modes_(0), signature_(signature), isGlobal_(isGlobal), isTemplate_(false), memMgr_(mm), src_(mm), staticTyped_(BEFORE), recursive_(false), delayed_(false), moduleDocCache_(NULL) { } XQUserFunction::XQUserFunction(const XMLCh *qname, VectorOfASTNodes *pattern, FunctionSignature *signature, ASTNode *body, XPath2MemoryManager *mm) : FuncFactory(signature->argSpecs == 0 ? 0 : signature->argSpecs->size(), mm), body_(body), exFunc_(NULL), qname_(qname), pattern_(pattern), templateInstance_(0), modes_(0), signature_(signature), isGlobal_(true), isTemplate_(true), memMgr_(mm), src_(mm), staticTyped_(BEFORE), recursive_(false), delayed_(false), moduleDocCache_(NULL) { } XQUserFunction::XQUserFunction(const XQUserFunction *o, XPath2MemoryManager *mm) : FuncFactory(o->uri_, o->name_, o->minArgs_, o->maxArgs_, mm), body_(o->body_), exFunc_(o->exFunc_), qname_(o->qname_), pattern_(0), templateInstance_(o->templateInstance_), modes_(0), signature_(new (mm) FunctionSignature(o->signature_, mm)), isGlobal_(o->isGlobal_), isTemplate_(o->isTemplate_), memMgr_(mm), src_(mm), staticTyped_(o->staticTyped_), recursive_(o->recursive_), delayed_(o->delayed_), moduleDocCache_(o->moduleDocCache_) { if(o->pattern_) { pattern_ = new (mm) VectorOfASTNodes(XQillaAllocator<ASTNode*>(mm)); *pattern_ = *o->pattern_; } if(o->modes_) { modes_ = new (mm) ModeList(XQillaAllocator<Mode*>(mm)); XQUserFunction::ModeList::const_iterator modeIt = o->getModeList()->begin(); for(; modeIt != o->getModeList()->end(); ++modeIt) { modes_->push_back(new (mm) Mode(*modeIt)); } } setLocationInfo(o); src_.copy(o->src_); } void XQUserFunction::releaseImpl() { if(pattern_) { pattern_->~VectorOfASTNodes(); memMgr_->deallocate(pattern_); } if(modes_) { XQUserFunction::ModeList::iterator modeIt = modes_->begin(); for(; modeIt != modes_->end(); ++modeIt) { memMgr_->deallocate(*modeIt); } #if defined(_MSC_VER) && (_MSC_VER < 1300) modes_->~vector<Mode*,XQillaAllocator<Mode*> >(); #else modes_->~ModeList(); #endif memMgr_->deallocate(modes_); } signature_->release(); src_.clear(); memMgr_->deallocate(this); } ASTNode* XQUserFunction::createInstance(const VectorOfASTNodes &args, XPath2MemoryManager *mm) const { return new (mm) XQUserFunctionInstance(this, args, mm); } void XQUserFunction::Mode::staticResolution(StaticContext* context) { if(qname_ != 0) { uri_ = context->getUriBoundToPrefix(XPath2NSUtils::getPrefix(qname_, context->getMemoryManager()), this); name_ = XPath2NSUtils::getLocalName(qname_); } } bool XQUserFunction::Mode::equals(const Mode *o) const { if(o == 0) return state_ == DEFAULT; if(state_ == ALL || o->state_ == CURRENT) return true; return state_ == o->state_ && XPath2Utils::equals(uri_, o->uri_) && XPath2Utils::equals(name_, o->name_); } void XQUserFunction::resolveName(StaticContext *context) { XPath2MemoryManager *mm = context->getMemoryManager(); if(qname_ != 0 && name_ == 0) { const XMLCh *prefix = XPath2NSUtils::getPrefix(qname_, mm); name_ = XPath2NSUtils::getLocalName(qname_); if(prefix == 0 || *prefix == 0) { uri_ = context->getDefaultFuncNS(); } else { uri_ = context->getUriBoundToPrefix(prefix, this); } } if(name_ != 0) { setURINameHash(uri_, name_); } } void XQUserFunction::staticResolutionStage1(StaticContext *context) { XPath2MemoryManager *mm = context->getMemoryManager(); resolveName(context); if(name_ != 0 && !isTemplate_ && !delayed_) { if(XPath2Utils::equals(uri_, XMLUni::fgXMLURIName) || XPath2Utils::equals(uri_, SchemaSymbols::fgURI_SCHEMAFORSCHEMA) || XPath2Utils::equals(uri_, SchemaSymbols::fgURI_XSI) || XPath2Utils::equals(uri_, XQFunction::XMLChFunctionURI) || XPath2Utils::equals(uri_, SchemaSymbols::fgURI_SCHEMAFORSCHEMA)) { XQThrow(FunctionException, X("XQUserFunction::staticResolutionStage1"), X("A user defined function must not be in the namespaces xml, xsd, xsi, fn or xdt [err:XQST0045]")); } else if(uri_ == 0 || *uri_ == 0) XQThrow(FunctionException, X("XQUserFunction::staticResolutionStage1"), X("A user defined function must be defined in a namespace [err:XQST0060]")); } // Check for the implementation of an external function if(body_ == NULL) { exFunc_ = context->lookUpExternalFunction(uri_, name_, minArgs_); if(exFunc_ == NULL) { XMLBuffer buf; buf.set(X("External function '{")); buf.append(uri_); buf.append(X("}")); buf.append(name_); buf.append(X("' with ")); XMLCh szNumBuff[20]; XMLString::binToText((unsigned int)minArgs_, szNumBuff, 19, 10); buf.append(szNumBuff); buf.append(X(" argument(s) has not been bound to an implementation")); XQThrow(FunctionException, X("XQUserFunction::staticResolutionStage1"), buf.getRawBuffer()); } } signature_->staticResolution(context); // Resolve the mode names if(modes_) { if(modes_->empty()) { XQThrow(StaticErrorException, X("XQUserFunction::staticResolution"), X("At least one mode must be specified for a template [err:XTSE0550]")); } ModeList::iterator it, it2; for(it = modes_->begin(); it != modes_->end(); ++it) { (*it)->staticResolution(context); // Check for "#all" with other values if((*it)->getState() == Mode::ALL && modes_->size() != 1) { XQThrow3(StaticErrorException, X("XQUserFunction::staticResolution"), X("The mode #all must not be specified in addition to other modes [err:XTSE0550]"), *it); } // Check for duplicate modes it2 = it; for(++it2; it2 != modes_->end(); ++it2) { if((*it)->getState() == (*it2)->getState() && XPath2Utils::equals((*it)->getName(), (*it2)->getName()) && XPath2Utils::equals((*it)->getURI(), (*it2)->getURI())) { XMLBuffer buf; buf.append(X("The mode {")); buf.append((*it)->getURI()); buf.append(X("}")); buf.append((*it)->getName()); buf.append(X(" has been specified more than once [err:XTSE0550]")); XQThrow3(StaticErrorException, X("XQUserFunction::staticResolution"), buf.getRawBuffer(), *it2); } } } } // Set up a default StaticType and StaticAnalysis if(signature_->returnType) { if(body_ != NULL) { body_ = signature_->returnType->convertFunctionArg(body_, context, /*numericfunction*/false, signature_->returnType); } bool isPrimitive; signature_->returnType->getStaticType(src_.getStaticType(), context, isPrimitive, signature_->returnType); } else { // Default type is item()* src_.getStaticType() = StaticType(StaticType::ITEM_TYPE, 0, StaticType::UNLIMITED); } if(signature_->updating == FunctionSignature::OP_TRUE) { src_.updating(true); } // TBD What about the other parts of the StaticAnalysis - jpcs src_.forceNoFolding(true); if(pattern_ != 0 && !pattern_->empty()) { // Set the pattern's initial static type to NODE_TYPE VectorOfASTNodes::iterator patIt = pattern_->begin(); for(; patIt != pattern_->end(); ++patIt) { const_cast<StaticAnalysis&>((*patIt)->getStaticAnalysis()).getStaticType() = StaticType(StaticType::NODE_TYPE, 0, StaticType::UNLIMITED); } } if(isTemplate_) { // Build an instance of the template for us to call VectorOfASTNodes newArgs = VectorOfASTNodes(XQillaAllocator<ASTNode*>(mm)); if(signature_->argSpecs != 0) { ArgumentSpecs::const_iterator argIt; for(argIt = signature_->argSpecs->begin(); argIt != signature_->argSpecs->end(); ++argIt) { XQVariable *argVar = new (mm) XQVariable((*argIt)->getURI(), (*argIt)->getName(), mm); argVar->setLocationInfo(*argIt); newArgs.push_back(argVar); } } templateInstance_ = createInstance(newArgs, mm); templateInstance_->setLocationInfo(this); } } void XQUserFunction::staticResolutionStage2(StaticContext *context) { // Prevent static typing being run on this function by a // loop of delayed functions AutoReset<StaticTypingStatus> reset(staticTyped_); staticTyped_ = AFTER; if(pattern_ != 0 && !pattern_->empty()) { VectorOfASTNodes::iterator patIt = pattern_->begin(); for(; patIt != pattern_->end(); ++patIt) { (*patIt) = (*patIt)->staticResolution(context); } } if(templateInstance_) { templateInstance_ = templateInstance_->staticResolution(context); } if(body_ != NULL) { body_ = body_->staticResolution(context); } } class UDFStaticTyper : private ASTVisitor { public: UDFStaticTyper() : context_(0), styper_(0) {} void run(ASTNode *item, StaticContext *context, StaticTyper *styper) { context_ = context; styper_ = styper; optimize(item); } private: virtual ASTNode *optimizeUserFunction(XQUserFunctionInstance *item) { XQQuery *module = context_->getModule()-> findModuleForFunction(item->getFunctionURI(), item->getFunctionName(), item->getArguments().size()); if(module == context_->getModule()) { // See if we can work out a better return type for the user defined function. // This call will just return if it's already been static typed const_cast<XQUserFunction*>(item->getFunctionDefinition())->staticTypingOnce(context_, styper_); } return ASTVisitor::optimizeUserFunction(item); } virtual ASTNode *optimizeApplyTemplates(XQApplyTemplates *item) { // The XQApplyTemplates could call any template with a pattern - // so try to static type all of them before us const UserFunctions &templates = context_->getTemplateRules(); UserFunctions::const_iterator inIt; for(inIt = templates.begin(); inIt != templates.end(); ++inIt) { if((*inIt)->getPattern() != 0) (*inIt)->staticTypingOnce(context_, styper_); } return ASTVisitor::optimizeApplyTemplates(item); } virtual ASTNode *optimizeCallTemplate(XQCallTemplate *item) { // The XQCallTemplate could call any template with a name - // so try to static type all of them before us const UserFunctions &templates = context_->getTemplateRules(); UserFunctions::const_iterator inIt; for(inIt = templates.begin(); inIt != templates.end(); ++inIt) { if((*inIt)->getName() != 0) (*inIt)->staticTypingOnce(context_, styper_); } return ASTVisitor::optimizeCallTemplate(item); } virtual ASTNode *optimizeInlineFunction(XQInlineFunction *item) { return item; } virtual ASTNode *optimizeFunctionRef(XQFunctionRef *item) { return item; } StaticContext *context_; StaticTyper *styper_; }; void XQUserFunction::staticTypeFunctionCalls(ASTNode *item, StaticContext *context, StaticTyper *styper) { // TBD DB XML version of UDFStaticTyper? - jpcs UDFStaticTyper().run(item, context, styper); } void XQUserFunction::staticTypingOnce(StaticContext *context, StaticTyper *styper) { // Avoid inifinite recursion for recursive functions // TBD Need to declare everything as being used - jpcs if(staticTyped_ != BEFORE) { if(staticTyped_ == DURING) recursive_ = true; XQGlobalVariable *global = 0; StaticTyper::PrologItem *breadcrumb = styper->getTrail(); for(; breadcrumb; breadcrumb = breadcrumb->prev) { if(breadcrumb->global) global = breadcrumb->global; if(breadcrumb->function == this) break; } if(global && breadcrumb) { XMLBuffer buf; buf.append(X("The initializing expression for variable {")); buf.append(global->getVariableURI()); buf.append(X("}")); buf.append(global->getVariableLocalName()); buf.append(X(" depends on itself [err:XQST0054]")); XQThrow3(StaticErrorException, X("XQUserFunction::staticTypingOnce"), buf.getRawBuffer(), global); } return; } staticTyped_ = DURING; StaticTyper::PrologItem breadcrumb(this, styper->getTrail()); AutoReset<StaticTyper::PrologItem*> autorReset2(styper->getTrail()); styper->getTrail() = &breadcrumb;; GlobalVariables globalsUsed(XQillaAllocator<XQGlobalVariable*>(context->getMemoryManager())); { AutoReset<GlobalVariables*> autoReset(styper->getGlobalsUsed()); styper->getGlobalsUsed() = &globalsUsed; staticTyping(context, styper); } if(!globalsUsed.empty()) { // Static type the global variables we depend on GlobalVariables::iterator it = globalsUsed.begin(); for(; it != globalsUsed.end(); ++it) { (*it)->staticTypingOnce(context, styper); } // Re-static type this function definition staticTyping(context, styper); } staticTyped_ = AFTER; } void XQUserFunction::resetStaticTypingOnce() { staticTyped_ = BEFORE; } void XQUserFunction::staticTyping(StaticContext *context, StaticTyper *styper) { // Nothing more to do for external functions if(body_ == NULL) return; if(signature_->updating == FunctionSignature::OP_TRUE && signature_->returnType != NULL) { XQThrow(StaticErrorException, X("XQUserFunction::staticTyping"), X("It is a static error for an updating function to declare a return type [err:XUST0028]")); } // Find user defined functions and templates that are referenced in our body, // and try to call staticTyping() on them before us. if(context) staticTypeFunctionCalls(body_, context, styper); bool ciTypeSet = false; StaticType ciType = StaticType(); if(pattern_ != NULL) { VectorOfASTNodes::iterator patIt = pattern_->begin(); for(; patIt != pattern_->end(); ++patIt) { (*patIt) = (*patIt)->staticTyping(context, styper); if(!ciTypeSet) { ciTypeSet = true; ciType = (*patIt)->getStaticAnalysis().getStaticType(); } else ciType |= (*patIt)->getStaticAnalysis().getStaticType(); } if(ciTypeSet) { ciType.setCardinality(1, 1); } } if(isTemplate_ && name_ != 0) { // Named template ciTypeSet = true; ciType = StaticType::ITEM_TYPE; } // define the new variables in a new scope and assign them the proper values if(context) { VariableTypeStore *varStore = context->getVariableTypeStore(); if(isGlobal_) varStore->addLocalScope(); else varStore->addLogicalBlockScope(); // Declare the parameters if(signature_->argSpecs) { ArgumentSpecs::iterator it; for(it = signature_->argSpecs->begin(); it != signature_->argSpecs->end (); ++it) { varStore->declareVar((*it)->getURI(), (*it)->getName(), (*it)->getStaticAnalysis()); } } } { // Declare the context item AutoContextItemTypeReset contextTypeReset(context, ciType); body_ = body_->staticTyping(context, styper); } if(context) context->getVariableTypeStore()->removeScope(); if(signature_->updating == FunctionSignature::OP_TRUE) { if(!body_->getStaticAnalysis().isUpdating() && !body_->getStaticAnalysis().isPossiblyUpdating()) XQThrow(StaticErrorException, X("XQUserFunction::staticTyping"), X("It is a static error for the body expression of a user defined updating function " "not to be an updating expression [err:XUST0002]")); } else { if(body_->getStaticAnalysis().isUpdating()) { if(isTemplate_) { XQThrow(StaticErrorException, X("XQUserFunction::staticTyping"), X("It is a static error for the body expression of a template " "to be an updating expression [err:XUST0001]")); } else { XQThrow(StaticErrorException, X("XQUserFunction::staticTyping"), X("It is a static error for the body expression of a user defined function " "to be an updating expression [err:XUST0001]")); } } } // Remove the parameter variables from the stored StaticAnalysis src_.clear(); src_.copy(body_->getStaticAnalysis()); if(signature_->argSpecs) { for(ArgumentSpecs::iterator it = signature_->argSpecs->begin(); it != signature_->argSpecs->end (); ++it) { if(!src_.removeVariable((*it)->getURI(), (*it)->getName())) { // The parameter isn't used, so set it to null, so that we don't bother to evaluate it (*it)->setNotUsed(); } } } // Run staticTyping on the template instances if(templateInstance_ != 0 && context) { StaticAnalysis templateVarSrc(context->getMemoryManager()); templateVarSrc.getStaticType() = StaticType::ITEM_TYPE; VariableTypeStore *varStore = context->getVariableTypeStore(); varStore->addLogicalBlockScope(); if(signature_->argSpecs != 0) { ArgumentSpecs::const_iterator argIt; for(argIt = signature_->argSpecs->begin(); argIt != signature_->argSpecs->end(); ++argIt) { varStore->declareVar((*argIt)->getURI(), (*argIt)->getName(), templateVarSrc); } } // Turn off warnings here, since they are largely irrelevent to the user AutoMessageListenerReset reset(context); templateInstance_ = templateInstance_->staticTyping(context, styper); varStore->removeScope(); } } //////////////////////////////////////////////////////////////////////////////////////////////////// XQUserFunctionInstance::XQUserFunctionInstance(const XQUserFunction* funcDef, const VectorOfASTNodes& args, XPath2MemoryManager* expr) : XQFunction(funcDef->getName(), 0, args, expr), addReturnCheck_(funcDef->body_ == NULL && funcDef->signature_->returnType != NULL), funcDef_(funcDef) { _type = ASTNode::USER_FUNCTION; uri_ = funcDef->getURI(); signature_ = funcDef->getSignature(); } XQUserFunctionInstance::XQUserFunctionInstance(const XQUserFunction *funcDef, const VectorOfASTNodes& args, bool addReturnCheck, XPath2MemoryManager *mm) : XQFunction(funcDef->getName(), 0, args, mm), addReturnCheck_(addReturnCheck), funcDef_(funcDef) { _type = ASTNode::USER_FUNCTION; uri_ = funcDef->getURI(); signature_ = funcDef->getSignature(); } Result XQUserFunctionInstance::getArgument(size_t index, DynamicContext *context) const { if(index >= funcDef_->getMaxArgs()) return 0; return _args[index]->createResult(context); } ASTNode* XQUserFunctionInstance::staticResolution(StaticContext* context) { XPath2MemoryManager *mm = context->getMemoryManager(); // We don't trust external functions, so check their return type if(addReturnCheck_) { addReturnCheck_ = false; XQTreatAs *treatAs = new (mm) XQTreatAs(this, funcDef_->signature_->returnType, mm); treatAs->setLocationInfo(funcDef_->signature_->returnType); return treatAs->staticResolution(context); } if(funcDef_->signature_->argSpecs != 0) { VectorOfASTNodes::iterator argIt = _args.begin(); for(ArgumentSpecs::iterator defIt = funcDef_->signature_->argSpecs->begin(); defIt != funcDef_->signature_->argSpecs->end() && argIt != _args.end(); ++defIt, ++argIt) { // The spec doesn't allow us to skip static errors, so we have to check even if // the parameter isn't used *argIt = (*defIt)->getType()->convertFunctionArg(*argIt, context, /*numericfunction*/false, *argIt); *argIt = (*argIt)->staticResolution(context); } } return this; } ASTNode *XQUserFunctionInstance::staticTypingImpl(StaticContext *context) { if(funcDef_->body_ != NULL) { _src.clear(); _src.copy(funcDef_->src_); } else { // Force the type check to happen, by declaring our type as item()* _src.clear(); _src.getStaticType() = StaticType(StaticType::ITEM_TYPE, 0, StaticType::UNLIMITED); _src.forceNoFolding(true); } VectorOfASTNodes::iterator argIt; for(argIt = _args.begin(); argIt != _args.end(); ++argIt) { // The spec doesn't allow us to skip static errors, so we have to check even if // the parameter isn't used if((*argIt)->getStaticAnalysis().isUpdating()) { if(funcDef_->isTemplate()) { XQThrow(StaticErrorException, X("XQUserFunctionInstance::staticTyping"), X("It is a static error for the argument expression of a call template expression " "to be an updating expression [err:XUST0001]")); } else { XQThrow(StaticErrorException, X("XQUserFunctionInstance::staticTyping"), X("It is a static error for the argument expression of a function call expression " "to be an updating expression [err:XUST0001]")); } } // TBD Check all static errors in staticResolution, so we can skip static typing - jpcs // if((*defIt)->_qname) _src.add((*argIt)->getStaticAnalysis()); } return this; } void XQUserFunctionInstance::evaluateArguments(VarStoreImpl &scope, DynamicContext *context) const { if(funcDef_->getSignature()->argSpecs != 0) { // the variables should be evaluated in the calling context // (before the VariableStore::addLocalScope call: after this call, the variables that can be seen are only the local ones) VectorOfASTNodes::const_iterator argIt = _args.begin(); for(ArgumentSpecs::const_iterator defIt = funcDef_->signature_->argSpecs->begin(); defIt != funcDef_->signature_->argSpecs->end() && argIt != _args.end(); ++defIt, ++argIt) { if((*defIt)->isUsed()) { scope.setVar((*defIt)->getURI(), (*defIt)->getName(), (*argIt)->createResult(context)); } else { // Skip evaluation of the parameter, since it isn't used, and debugging isn't enabled } } } } EventGenerator::Ptr XQUserFunctionInstance::generateEvents(EventHandler *events, DynamicContext *context, bool preserveNS, bool preserveType) const { if(funcDef_->getFunctionBody() == NULL) { return ASTNodeImpl::generateEvents(events, context, preserveNS, preserveType); } context->testInterrupt(); VarStoreImpl scope(context->getMemoryManager(), funcDef_->isGlobal() ? context->getGlobalVariableStore() : context->getVariableStore()); evaluateArguments(scope, context); AutoDocumentCacheReset reset(context); if(funcDef_->getModuleDocumentCache()) context->setDocumentCache(funcDef_->getModuleDocumentCache()); AutoVariableStoreReset reset2(context, &scope); AutoRegexGroupStoreReset reset3(context); if(!funcDef_->isTemplate()) context->setRegexGroupStore(0); return new ClosureEventGenerator(funcDef_->getFunctionBody(), context, preserveNS, preserveType); } PendingUpdateList XQUserFunctionInstance::createUpdateList(DynamicContext *context) const { context->testInterrupt(); if(funcDef_->getFunctionBody() == NULL) { return funcDef_->getExternalFunction()->executeUpdate(this, context); } VarStoreImpl scope(context->getMemoryManager(), funcDef_->isGlobal() ? context->getGlobalVariableStore() : context->getVariableStore()); evaluateArguments(scope, context); AutoDocumentCacheReset reset(context); if(funcDef_->getModuleDocumentCache()) context->setDocumentCache(funcDef_->getModuleDocumentCache()); AutoVariableStoreReset reset2(context, &scope); AutoRegexGroupStoreReset reset3(context, 0); if(!funcDef_->isTemplate()) context->setRegexGroupStore(0); PendingUpdateList result = funcDef_->getFunctionBody()->createUpdateList(context); return result; } Result XQUserFunctionInstance::createResult(DynamicContext* context, int flags) const { context->testInterrupt(); if(funcDef_->body_ != NULL) { VarStoreImpl scope(context->getMemoryManager(), funcDef_->isGlobal() ? context->getGlobalVariableStore() : context->getVariableStore()); evaluateArguments(scope, context); AutoRegexGroupStoreReset reset3(context); if(!funcDef_->isTemplate()) context->setRegexGroupStore(0); AutoDocumentCacheReset reset(context); DocumentCache* docCache = funcDef_->getModuleDocumentCache(); if(docCache) context->setDocumentCache(docCache); AutoVariableStoreReset vsReset(context, &scope); return ClosureResult::create(funcDef_->getFunctionBody(), context); } else { return funcDef_->getExternalFunction()->execute(this, context); } } //////////////////////////////////////////////////////////////////////////////////////////////////// DelayedFuncFactory::DelayedFuncFactory(const XMLCh *uri, const XMLCh *name, size_t numArgs, const XMLCh *body, int line, int column, XQQuery *query) : FuncFactory(uri, name, numArgs, numArgs, query->getStaticContext()->getMemoryManager()), body_(body), body8_(0), line_(line), column_(column), query_(query), function_(0) { } DelayedFuncFactory::DelayedFuncFactory(const XMLCh *uri, const XMLCh *name, size_t numArgs, const char *body, int line, int column, XQQuery *query) : FuncFactory(uri, name, numArgs, numArgs, query->getStaticContext()->getMemoryManager()), body_(0), body8_(body), line_(line), column_(column), query_(query), function_(0) { } ASTNode *DelayedFuncFactory::createInstance(const VectorOfASTNodes &args, XPath2MemoryManager* memMgr) const { if(function_ == 0) { DynamicContext *context = (DynamicContext*)query_->getStaticContext(); if(body_ == 0) { const_cast<const XMLCh *&>(body_) = context->getMemoryManager()->getPooledString(body8_); } XQLexer lexer(memMgr, _LANG_FUNCDECL_, query_->getFile(), line_, column_, body_); XQParserArgs args(&lexer, query_); XQParser::yyparse(&args); const_cast<XQUserFunction*&>(function_) = args._function; function_->setDelayed(true); query_->addFunction(function_); function_->staticResolutionStage1(context); AutoDelete<Optimizer> optimizer(XQilla::createOptimizer(context, XQilla::NO_OPTIMIZATION)); optimizer->startOptimize(function_); } return function_->createInstance(args, memMgr); }
8b046f25df86a8360c715f7ed0b75143ca67932c
f05bded855ddb4e8d2ed041724df431f8361ddfc
/dev/Scroller/ScrollOptions.h
dc9fafb9334914045a4ad8cd499b95cd8eb39a6e
[ "MIT" ]
permissive
EthanHu01/microsoft-ui-xaml
863ac6e9dfbb4ff6dadf328c0ea6633ebebca76f
ca95be6f5248eaa55ec523f2d6e7b50f6e0d53e7
refs/heads/master
2022-04-23T13:13:23.041995
2020-04-24T21:02:46
2020-04-24T21:02:46
259,182,755
2
0
MIT
2020-04-27T02:22:11
2020-04-27T02:22:10
null
UTF-8
C++
false
false
1,184
h
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. #pragma once #include "Scroller.h" #include "ScrollOptions.g.h" class ScrollOptions : public winrt::implementation::ScrollOptionsT<ScrollOptions> { public: ScrollOptions(winrt::AnimationMode const& animationMode); ScrollOptions(winrt::AnimationMode const& animationMode, winrt::SnapPointsMode const& snapPointsMode); ~ScrollOptions() { SCROLLER_TRACE_VERBOSE(nullptr, TRACE_MSG_METH, METH_NAME, this); } static constexpr winrt::AnimationMode s_defaultAnimationMode{ winrt::AnimationMode::Auto }; static constexpr winrt::SnapPointsMode s_defaultSnapPointsMode{ winrt::SnapPointsMode::Default }; winrt::AnimationMode AnimationMode() const; void AnimationMode(winrt::AnimationMode const& animationMode); winrt::SnapPointsMode SnapPointsMode() const; void SnapPointsMode(winrt::SnapPointsMode const& snapPointsMode); private: winrt::AnimationMode m_animationMode{ s_defaultAnimationMode }; winrt::SnapPointsMode m_snapPointsMode{ s_defaultSnapPointsMode }; };
5d309ad922993d294a63a3106d23b45db0689e02
6b861145dd91e55be7fe0f862f917a2ec056db40
/ftest.cpp
145b7b6e45f359a17104be0a4183842a647755c8
[]
no_license
burakov28/optimized_big_integer
06272e2ee09c3431cbf882f687f5efabdd371e73
dd6d19885fd64056550c1e48ed27d1314e439693
refs/heads/master
2021-01-13T03:17:18.149401
2016-12-29T14:30:44
2016-12-29T14:30:44
77,592,942
0
0
null
null
null
null
UTF-8
C++
false
false
1,023
cpp
#include "optimized_vector.cpp" using namespace std; int main() { optimized_vector < int > line; for (int i = 0; i < 20; ++i) { line.push_back(i + 1); for (int j = 0; j < (int) line.size(); ++j) { cout << line[j] << " "; } cout << endl; } line.reverse(); for (int i = 0; i < (int) line.size(); ++i) { cout << line[i] << " "; } cout << endl; line.resize(30); for (int i = 0; i < (int) line.size(); ++i) { cout << line[i] << " "; } cout << endl; line.resize(15); for (int i = 0; i < (int) line.size(); ++i) { cout << line[i] << " "; } cout << endl; line.resize(20); for (int i = 0; i < (int) line.size(); ++i) { cout << line[i] << " "; } cout << endl; for (int i = 0; i < 20; ++i) { line.pop_back(); for (int j = 0; j < (int) line.size(); ++j) { cout << line[j] << " "; } cout << endl; } return 0; }
6e315ca78c46ed1b826952b47b292e11ec34afda
00e65bf5628bac43c7dc6d86cfbc6ea0484a4ad8
/src/node/async_aes.h
0cd60eb311757c2674ec2280cb6a593b88c37d79
[ "MIT" ]
permissive
kiskovacs/node-webcrypto-ossl
228176ea70174689ac40ed848d67e0500b2b76bf
4d096890b355b9e4e94fbec9ba29c3d43b09ef67
refs/heads/master
2021-01-17T16:06:23.725051
2016-02-16T11:38:59
2016-02-16T11:38:59
51,757,958
0
0
null
2016-02-15T13:38:53
2016-02-15T13:38:53
null
UTF-8
C++
false
false
2,376
h
#ifndef OSSL_NODE_ASYNC_AES_H_INCLUDE #define OSSL_NODE_ASYNC_AES_H_INCLUDE #include "../core/common.h" #include "../aes/common.h" class AsyncAesGenerateKey : public Nan::AsyncWorker { public: AsyncAesGenerateKey( Nan::Callback *callback, int keySize ) : AsyncWorker(callback), keySize(keySize) {} ~AsyncAesGenerateKey() {} void Execute(); void HandleOKCallback(); protected: int keySize; // Result Handle<ScopedAES> key; }; class AsyncAesEncryptCBC : public Nan::AsyncWorker { public: AsyncAesEncryptCBC( Nan::Callback *callback, Handle<ScopedAES> hKey, Handle<std::string> hInput, Handle<std::string> hIv, bool encrypt ) : AsyncWorker(callback), hKey(hKey), hInput(hInput), hIv(hIv), encrypt(encrypt) {} ~AsyncAesEncryptCBC() {} void Execute(); void HandleOKCallback(); protected: bool encrypt; Handle<std::string> hIv; Handle<std::string> hInput; Handle<ScopedAES> hKey; // Result Handle<std::string> hOutput; }; class AsyncAesExport : public Nan::AsyncWorker { public: AsyncAesExport( Nan::Callback *callback, Handle<ScopedAES> hKey ) : AsyncWorker(callback), hKey(hKey) {} ~AsyncAesExport() {} void Execute(); void HandleOKCallback(); protected: Handle<ScopedAES> hKey; // Result Handle<std::string> hOutput; }; class AsyncAesImport : public Nan::AsyncWorker { public: AsyncAesImport( Nan::Callback *callback, Handle<std::string> hInput ) : AsyncWorker(callback), hInput(hInput) {} ~AsyncAesImport() {} void Execute(); void HandleOKCallback(); protected: Handle<std::string> hInput; // Result Handle<ScopedAES> hKey; }; class AsyncAesEncryptGCM : public Nan::AsyncWorker { public: AsyncAesEncryptGCM( Nan::Callback *callback, Handle<ScopedAES> hKey, Handle<std::string> hInput, Handle<std::string> hIv, Handle<std::string> hAad, int tagSize, bool encrypt ) : AsyncWorker(callback), hKey(hKey), hInput(hInput), hIv(hIv), hAad(hAad), tagSize(tagSize), encrypt(encrypt) {} ~AsyncAesEncryptGCM() {} void Execute(); void HandleOKCallback(); protected: Handle<ScopedAES> hKey; Handle<std::string> hInput; Handle<std::string> hIv; Handle<std::string> hAad; int tagSize; bool encrypt; // Result Handle<std::string> hOutput; }; #endif // OSSL_NODE_ASYNC_AES_H_INCLUDE
dc1b977a1ede71d4499bae437682283896d9679d
81dfe750f761728e74525b5b5083861ef958fc4e
/arg/utils/cMersenneTwister.h
fded85d2c95926670bc7269510d4934c32179d57
[]
no_license
foowie/my-velvet
a64eb111ffa5106bf90c61cde1ffb710231044fb
be381c06e023026e7ee12e3a04414c8142b710cc
refs/heads/master
2020-04-16T10:38:26.365604
2013-07-04T14:41:19
2013-07-04T14:41:19
10,336,924
0
0
null
null
null
null
UTF-8
C++
false
false
9,355
h
/**************************************************************************} { } { ccMersenneTwister.h } { } { } { Copyright (c) 2011 Vaclav Snasel } { } { VERSION: 2.0 DATE 5/12/2010 } { } { following functionality: } { source M. Matsumoto and T. Nishimura, "Mersenne Twister: } { A 623-Dimensionally Equidistributed Uniform Pseudo-Random } { Number Generator", ACM Transactions on Modeling and Computer } { Simulation, Vol. 8, No. 1, January 1998, pp 3-30. } { } { } { UPDATE HISTORY: } { } { } {**************************************************************************/ #ifndef __CMERSENNETWISTER_H__ #define __CMERSENNETWISTER_H__ #include <ctime> #include <cmath> #include <climits> class cMersenneTwister { // Data protected: static const unsigned int N = 624; // length of state vector static const unsigned int SAVE = N + 1; // length of array for save() static const unsigned int M = 397; // period parameter unsigned int state[N]; // internal state unsigned int *pNext; // next value to get from state unsigned int left; // number of values left before reload needed // Methods public: cMersenneTwister(const unsigned int oneSeed); // initialize with a simple unsigned int cMersenneTwister(unsigned int *const bigSeed, unsigned int const seedLength = N); // or array cMersenneTwister(); // auto-initialize with /dev/urandom or time() and clock() // Do NOT use for CRYPTOGRAPHY without securely hashing several returned // values together, otherwise the generator state can be learned after // reading 624 consecutive values. // Access to 32-bit random numbers unsigned int randInt(); // integer in [0,2^32-1] unsigned int randInt(const unsigned int n); // integer in [0,n] for n < 2^32 double rand(); // real number in [0,1] double rand(const double n); // real number in [0,n] double randExc(); // real number in [0,1) double randExc(const double n); // real number in [0,n) double randDblExc(); // real number in (0,1) double randDblExc(const double n); // real number in (0,n) // Access to 53-bit random numbers (capacity of IEEE double precision) double rand53(); // real number in [0,1) // Access to nonuniform random number distributions double randNorm(const double mean = 0.0, const double stddev = 1.0); // Re-seeding functions with same behavior as initializers void seed(const unsigned int oneSeed); void seed(unsigned int *const bigSeed, const unsigned int seedLength = N); protected: void initialize(const unsigned int oneSeed); void reload(); inline unsigned int hiBit(const unsigned int u) const { return u & 0x80000000UL; } inline unsigned int loBit(const unsigned int u) const { return u & 0x00000001UL; } inline unsigned int loBits(const unsigned int u) const { return u & 0x7fffffffUL; } unsigned int mixBits(const unsigned int u, const unsigned int v) const { return hiBit(u) | loBits(v); } unsigned int magic(const unsigned int u) const { return loBit(u) ? 0x9908b0dfUL : 0x0UL; } unsigned int twist(const unsigned int m, const unsigned int s0, const unsigned int s1) const { return m ^ (mixBits(s0,s1)>>1) ^ magic(s1); } static unsigned int hash(time_t t, clock_t c); }; // Functions are defined in order of usage to assist inlining inline unsigned int cMersenneTwister::hash(time_t t, clock_t c) { // Get a unsigned int from t and c // Better than unsigned int(x) in case x is floating point in [0,1] // Based on code by Lawrence Kirby ([email protected]) static unsigned int differ = 0; // guarantee time-based seeds will change unsigned int h1 = 0; unsigned char *p = (unsigned char *) &t; for(unsigned int i = 0; i < sizeof(t); ++i) { h1 *= UCHAR_MAX + 2U; h1 += p[i]; } unsigned int h2 = 0; p = (unsigned char *) &c; for(unsigned int j = 0; j < sizeof(c); ++j) { h2 *= UCHAR_MAX + 2U; h2 += p[j]; } return (h1 + differ++) ^ h2; } inline void cMersenneTwister::initialize(const unsigned int seed) { // Initialize generator state with seed // See Knuth TAOCP Vol 2, 3rd Ed, p.106 for multiplier. // In previous versions, most significant bits (MSBs) of the seed affect // only MSBs of the state array. Modified 9 Jan 2002 by Makoto Matsumoto. unsigned int *s = state; unsigned int *r = state; *s++ = seed & 0xffffffffUL; for(unsigned int i = 1; i < N; ++i) { *s++ = (1812433253UL * (*r ^ (*r >> 30)) + i) & 0xffffffffUL; r++; } } inline void cMersenneTwister::reload() { // Generate N new values in state // Made clearer and faster by Matthew Bellew ([email protected]) int MmN = int(M) - int(N); // in case enums are unsigned unsigned int *p = state; for(int i = N - M; i--; ++p) { *p = twist(p[M], p[0], p[1]); } for(int i = M; --i; ++p) { *p = twist(p[MmN], p[0], p[1]); } *p = twist(p[MmN], p[0], state[0]); left = N, pNext = state; } inline void cMersenneTwister::seed(const unsigned int oneSeed) { // Seed the generator with a simple unsigned int initialize(oneSeed); reload(); } inline void cMersenneTwister::seed(unsigned int *const bigSeed, const unsigned int seedLength) { // Seed the generator with an array of unsigned int's // There are 2^19937-1 possible initial states. This function allows // all of those to be accessed by providing at least 19937 bits (with a // default seed length of N = 624 unsigned int's). Any bits above the lower 32 // in each element are discarded. // Just call seed() if you want to get array from /dev/urandom initialize(19650218UL); unsigned int i = 1; unsigned int j = 0; for(int k = (N > seedLength ? N : seedLength); k; --k) { state[i] = state[i] ^ ((state[i-1] ^ (state[i-1] >> 30)) * 1664525UL); state[i] += (bigSeed[j] & 0xffffffffUL) + j; state[i] &= 0xffffffffUL; ++i; ++j; if(i >= N) { state[0] = state[N-1]; i = 1; } if(j >= seedLength) { j = 0; } } for(int k = N - 1; k; --k) { state[i] = state[i] ^ ((state[i-1] ^ (state[i-1] >> 30)) * 1566083941UL); state[i] -= i; state[i] &= 0xffffffffUL; ++i; if(i >= N) { state[0] = state[N-1]; i = 1; } } state[0] = 0x80000000UL; // MSB is 1, assuring non-zero initial array reload(); } inline cMersenneTwister::cMersenneTwister() { seed((unsigned int) time(NULL)); } inline cMersenneTwister::cMersenneTwister(const unsigned int oneSeed) { seed(oneSeed); } inline cMersenneTwister::cMersenneTwister(unsigned int *const bigSeed, const unsigned int seedLength) { seed(bigSeed,seedLength); } inline unsigned int cMersenneTwister::randInt() { // Pull a 32-bit integer from the generator state // Every other access function simply transforms the numbers extracted here if (left == 0) { reload(); } --left; unsigned int s1; s1 = *pNext++; s1 ^= (s1 >> 11); s1 ^= (s1 << 7) & 0x9d2c5680UL; s1 ^= (s1 << 15) & 0xefc60000UL; return (s1 ^ (s1 >> 18)); } inline unsigned int cMersenneTwister::randInt(const unsigned int n) { // Find which bits are used in n // Optimized by Magnus Jonsson ([email protected]) unsigned int used = n; used |= used >> 1; used |= used >> 2; used |= used >> 4; used |= used >> 8; used |= used >> 16; // Draw numbers until one is found in [0,n] unsigned int i; do i = randInt() & used; // toss unused bits to shorten search while(i > n); return i; } inline double cMersenneTwister::rand() { return double(randInt()) * (1.0 / 4294967295.0); } inline double cMersenneTwister::rand(const double n) { return rand() * n; } inline double cMersenneTwister::randExc() { return double(randInt()) * (1.0 / 4294967296.0); } inline double cMersenneTwister::randExc(const double n) { return randExc() * n; } inline double cMersenneTwister::randDblExc() { return (double(randInt()) + 0.5) * (1.0 / 4294967296.0); } inline double cMersenneTwister::randDblExc(const double n) { return randDblExc() * n; } inline double cMersenneTwister::rand53() { unsigned int a = randInt() >> 5, b = randInt() >> 6; return (a * 67108864.0 + b) * (1.0 / 9007199254740992.0); // by Isaku Wada } inline double cMersenneTwister::randNorm(const double mean, const double stddev) { // Return a real number from a normal (Gaussian) distribution with given // mean and standard deviation by polar form of Box-Muller transformation double x, y, r; do { x = 2.0 * rand() - 1.0; y = 2.0 * rand() - 1.0; r = x * x + y * y; } while (r >= 1.0 || r == 0.0); double s = sqrt(-2.0 * log(r) / r); return mean + x * s * stddev; } #endif // __CMERSENNETWISTER_H__
3f4b5264e76ae4bc09a07c53b563aaa2689f8d7e
89dedd7f3c7acc81d12e2bcb2e716f9af9e5fa04
/net/udp/datagram_socket.h
19936979f4157706bdf3f1a5a2505e8d7edba0ed
[ "BSD-3-Clause" ]
permissive
bino7/chromium
8d26f84a1b6e38a73d1b97fea6057c634eff68cb
4666a6bb6fdcb1114afecf77bdaa239d9787b752
refs/heads/master
2022-12-22T14:31:53.913081
2016-09-06T10:05:11
2016-09-06T10:05:11
67,410,510
1
3
BSD-3-Clause
2022-12-17T03:08:52
2016-09-05T10:11:59
null
UTF-8
C++
false
false
1,645
h
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef NET_UDP_DATAGRAM_SOCKET_H_ #define NET_UDP_DATAGRAM_SOCKET_H_ #include "net/base/net_export.h" namespace net { class BoundNetLog; class IPEndPoint; // A datagram socket is an interface to a protocol which exchanges // datagrams, like UDP. class NET_EXPORT_PRIVATE DatagramSocket { public: // Type of source port binding to use. enum BindType { RANDOM_BIND, DEFAULT_BIND, }; virtual ~DatagramSocket() {} // Close the socket. virtual void Close() = 0; // Copy the remote udp address into |address| and return a network error code. virtual int GetPeerAddress(IPEndPoint* address) const = 0; // Copy the local udp address into |address| and return a network error code. // (similar to getsockname) virtual int GetLocalAddress(IPEndPoint* address) const = 0; // Switch to use non-blocking IO. Must be called right after construction and // before other calls. virtual void UseNonBlockingIO() = 0; // Requests that packets sent by this socket not be fragment, either locally // by the host, or by routers (via the DF bit in the IPv4 packet header). // May not be supported by all platforms. Returns a return a network error // code if there was a problem, but the socket will still be usable. Can not // return ERR_IO_PENDING. virtual int SetDoNotFragment() = 0; // Gets the NetLog for this socket. virtual const BoundNetLog& NetLog() const = 0; }; } // namespace net #endif // NET_UDP_DATAGRAM_SOCKET_H_
ad83f021ed6f64075b35423eb42919c1fd6edfe7
5d4dadf46e4fbfb734409bd7f286c71d99b906dd
/SDLFramework/SDLFramework/BaseGameEntity.h
7a8b104afcdd26fb3916c17bac330c682d934bae
[]
no_license
andrewservania/KMINTWeek4
e2b0e0a734c87887a1b66b46f2cd046368094505
ff0d963f1411ac78f7cdd488b6cbe69ccc6cd755
refs/heads/master
2021-01-10T13:46:44.778480
2015-10-30T22:22:25
2015-10-30T22:22:25
43,364,509
0
0
null
null
null
null
UTF-8
C++
false
false
1,596
h
#pragma once #include "IGameObject.h" #include "Vector2D.h" class BaseGameEntity : public IGameObject { private: int id; // Every entity has a unique identifying number static int nextValidID; // This is the next valid ID. Each time a BaseGameEntity is instantiated // this value is updated //this is a generic flag bool tag; // every entity has a type associated with (health, troll, ammo etc) int entityType; void SetID(int val); protected: // The entity's location within the arena Vector2D position; Vector2D scale; //The length of this object's bounding radius double boundingRadius; public: enum{ default_entity_type = -1 }; BaseGameEntity(int id, int _entity_type, Vector2D _pos, double _r); virtual ~BaseGameEntity(); virtual void Update(float deltaTime) = 0; Vector2D Pos()const{ return position; } void SetPos(Vector2D new_pos){ position = new_pos; } double BRadius()const{ return boundingRadius; } void SetBRadius(double r){ boundingRadius = r; } int ID()const{ return id; } bool IsTagged()const{ return tag; } void Tag(){ tag = true; } void UnTag(){ tag = false; } Vector2D Scale()const{ return scale; } void SetScale(Vector2D val){ boundingRadius *= MaxOf(val.x, val.y) / MaxOf(scale.x, scale.y); scale = val; } void SetScale(double val){ boundingRadius *= (val / MaxOf(scale.x, scale.y)); scale = Vector2D(val, val); } int EntityType()const{ return entityType; } void SetEntityType(int new_type){ entityType = new_type; } };
ae392ddc54e8dd631a5bf7108f65848e28c5653f
d4e96aa48ddff651558a3fe2212ebb3a3afe5ac3
/Modules/Video/IO/test/itkFileListVideoIOTest.cxx
3448aae1a00c6c1d17eabe1e3a9835d7cc01658c
[ "SMLNJ", "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-mit-old-style", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer", "NTP", "IJG", "GPL-1.0-or-later", "libtiff", "BSD-4.3TAHOE", "Zlib", "MIT", "LicenseRef-scancode-proprietary-license", "Spencer-86", "Apache-2.0", "FSFUL", "LicenseRef-scancode-public-domain", "Libpng", "BSD-2-Clause" ]
permissive
nalinimsingh/ITK_4D
18e8929672df64df58a6446f047e6ec04d3c2616
95a2eacaeaffe572889832ef0894239f89e3f303
refs/heads/master
2020-03-17T18:58:50.953317
2018-10-01T20:46:43
2018-10-01T21:21:01
133,841,430
0
0
Apache-2.0
2018-05-17T16:34:54
2018-05-17T16:34:53
null
UTF-8
C++
false
false
10,722
cxx
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include <iostream> #include <fstream> #include "itkFileListVideoIO.h" #include "itkImportImageFilter.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkMath.h" #include "itkTestingMacros.h" #include "itkVideoIOBase.h" typedef itk::SizeValueType SizeValueType; int test_FileListVideoIO( const char* input, char* nonVideoInput, char* output, char* itkNotUsed(cameraOutput), unsigned int inWidth, unsigned int inHeight, SizeValueType inNumFrames, double inFpS ) { // ITK typedefs typedef itk::RGBPixel<char> PixelType; typedef itk::Image<PixelType, 2> ImageType; typedef itk::ImageFileReader<ImageType> ReaderType; int ret = EXIT_SUCCESS; // Create the VideoIO itk::FileListVideoIO::Pointer fileListIO = itk::FileListVideoIO::New(); EXERCISE_BASIC_OBJECT_METHODS( fileListIO, FileListVideoIO, VideoIOBase ); fileListIO->SetFileName(input); std::cout << "FileListVideoIO::CanReadFile..." << std::endl; // Test CanReadFile on good file if (!fileListIO->CanReadFile(input)) { std::cerr << "Could not read " << input << std::endl; ret = EXIT_FAILURE; } // Test CanReadFile on non-existant file std::string nonExistantFile = "Bad/Path/To/Nothing"; if (fileListIO->CanReadFile(nonExistantFile.c_str())) { std::cerr << "Should have failed to open \"" << nonExistantFile << "\"" << std::endl; ret = EXIT_FAILURE; } // Test CanReadFile on non-image file list if (fileListIO->CanReadFile(nonVideoInput)) { std::cerr << "Should have failed to open \"" << nonVideoInput << "\"" << std::endl; ret = EXIT_FAILURE; } std::cout << "FileListVideoIO::ReadImageInformation..." << std::endl; fileListIO->SetFileName(input); fileListIO->ReadImageInformation(); bool infoSet = true; std::stringstream paramMessage; if (fileListIO->GetDimensions(0) != inWidth) { infoSet = false; paramMessage << "Width mismatch: (expected) " << inWidth << " != (got) " << fileListIO->GetDimensions(0) << std::endl; } if (fileListIO->GetDimensions(1) != inHeight) { infoSet = false; paramMessage << "Height mismatch: (expected) " << inHeight << " != (got) " << fileListIO->GetDimensions(1) << std::endl; } double epsilon = 0.0001; if ( !itk::Math::FloatAlmostEqual( fileListIO->GetFramesPerSecond(), inFpS, 10, epsilon) ) { infoSet = false; paramMessage << "FpS mismatch: (expected) " << inFpS << " != (got) " << fileListIO->GetFramesPerSecond() << std::endl; } if (fileListIO->GetFrameTotal() != inNumFrames) { infoSet = false; paramMessage << "FrameTotal mismatch: (expected) " << inNumFrames << " != (got) " << fileListIO->GetFrameTotal() << std::endl; } if (!infoSet) { std::cerr << paramMessage.str(); ret = EXIT_FAILURE; } // Exercise other FileListVideoIO methods std::cout << "PositionInMSec: " << fileListIO->GetPositionInMSec() << std::endl; std::cout << "Ratio: " << fileListIO->GetRatio() << std::endl; std::cout << "IFrameInterval: " << fileListIO->GetIFrameInterval() << std::endl; std::cout << "FileListVideoIO::Read..." << std::endl; std::cout << "Comparing all " << fileListIO->GetFrameTotal() << " frames" << std::endl; // Set up ImageFileReader ReaderType::Pointer reader = ReaderType::New(); // Loop through all frames std::vector<std::string> filenames = fileListIO->SplitFileNames(input); for (SizeValueType i = 0; i < fileListIO->GetFrameTotal(); ++i) { // Read the image file directly reader->SetFileName(filenames[i]); reader->Update(); // Read the image using FileListVideoIO size_t bufferSize = fileListIO->GetImageSizeInBytes(); PixelType* buffer = new PixelType[bufferSize]; fileListIO->Read(static_cast<void*>(buffer)); // Compare Spacing, Origin, Direction for (unsigned int j = 0; j < ImageType::ImageDimension; ++j) { if (itk::Math::NotExactlyEquals(fileListIO->GetSpacing(j), reader->GetImageIO()->GetSpacing(j))) { std::cerr << "Spacing not read correctly" << std::endl; ret = false; } if (itk::Math::NotExactlyEquals(fileListIO->GetOrigin(j), reader->GetImageIO()->GetOrigin(j))) { std::cerr << "Origin not read correctly" << std::endl; ret = false; } if (fileListIO->GetDirection(j) != reader->GetImageIO()->GetDirection(j)) { std::cerr << "Direction not read correctly" << std::endl; ret = false; } } // Compare buffer contents if (memcmp(reinterpret_cast<void*>(buffer), reinterpret_cast<void*>(reader->GetOutput()->GetBufferPointer()), bufferSize)) { std::cerr << "Frame buffers don't match for frame " << i << std::endl; ret = false; } delete[] buffer; } std::cout << "FileListVideoIO::SetNextFrameToRead" << std::endl; // try seeking to the end SizeValueType seekFrame = fileListIO->GetFrameTotal()-1; if (!fileListIO->SetNextFrameToRead(seekFrame)) { std::cerr << "Failed to seek to second I-Frame..." << std::endl; ret = EXIT_FAILURE; } // Save the current parameters double fps = fileListIO->GetFramesPerSecond(); unsigned int width = fileListIO->GetDimensions(0); unsigned int height = fileListIO->GetDimensions(1); const char* fourCC = "MP42"; unsigned int nChannels = fileListIO->GetNumberOfComponents(); // Reset the VideoIO fileListIO->FinishReadingOrWriting(); std::cout << "FileListVideoIO::SetWriterParameters..." << std::endl; // Reset the saved parameters std::vector<itk::SizeValueType> size; size.push_back(width); size.push_back(height); fileListIO->SetWriterParameters(fps, size, fourCC, nChannels, itk::ImageIOBase::UCHAR); // Make sure they set correctly if (itk::Math::NotExactlyEquals(fileListIO->GetFramesPerSecond(), fps) || fileListIO->GetDimensions(0) != width || fileListIO->GetDimensions(1) != height || fileListIO->GetNumberOfComponents() != nChannels) { std::cerr << "Didn't set writer parmeters correctly" << std::endl; std::cerr << " FpS -> Got: " << fileListIO->GetFramesPerSecond() << " Expected: " << fps << std::endl; std::cerr << " width -> Got: " << fileListIO->GetDimensions(0) << " Expected: " << width << std::endl; std::cerr << " height -> Got: " << fileListIO->GetDimensions(1) << " Expected: " << height << std::endl; std::cerr << " NChannels -> Got: " << fileListIO->GetNumberOfComponents() << " Expected: " << nChannels << std::endl; ret = EXIT_FAILURE; } std::cout << "FileListVideoIO::CanWriteFile..." << std::endl; // Test CanWriteFile on good filename if (!fileListIO->CanWriteFile(output)) { std::cerr << "CanWriteFile didn't return true correctly" << std::endl; ret = EXIT_FAILURE; } // Test CanWriteFile on bad filename if (fileListIO->CanWriteFile("asdfasdfasdf")) { std::cerr << "CanWriteFile should have failed for bad filename" << std::endl; ret = EXIT_FAILURE; } std::cout << "FileListVideoIO::Write..." << std::endl; // Set output filename fileListIO->SetFileName( output ); // Set up a two more VideoIOs to read while we're writing itk::FileListVideoIO::Pointer fileListIO2 = itk::FileListVideoIO::New(); itk::FileListVideoIO::Pointer fileListIO3 = itk::FileListVideoIO::New(); fileListIO2->SetFileName( input ); fileListIO2->ReadImageInformation(); fileListIO3->SetFileName( output ); // Loop through all frames to read with fileListIO2 and write with fileListIO for (unsigned int i = 0; i < inNumFrames; ++i) { // Set up a buffer to read to size_t bufferSize = fileListIO2->GetImageSizeInBytes(); PixelType* buffer = new PixelType[bufferSize]; // Read into the buffer fileListIO2->Read(static_cast<void*>(buffer)); // Write out the frame from the buffer fileListIO->Write(static_cast<void*>(buffer)); // Now, read back in from the written file and make sure the buffers match fileListIO3->ReadImageInformation(); PixelType* reReadBuffer = new PixelType[bufferSize]; fileListIO3->Read(static_cast<void*>(reReadBuffer)); if (memcmp(reinterpret_cast<void*>(buffer), reinterpret_cast<void*>(reReadBuffer), bufferSize)) { std::cerr << "Didn't write correctly for frame " << i << std::endl; ret = EXIT_FAILURE; } delete[] buffer; delete[] reReadBuffer; } // Finish writing fileListIO2->FinishReadingOrWriting(); fileListIO->FinishReadingOrWriting(); std::cout << "Test finished" << std::endl; return ret; } int itkFileListVideoIOTest( int argc, char *argv[] ) { if (argc != 13) { std::cerr << "Usage: " << argv[0]; std::cerr << " videoInput(5 files) non-VideoInput videoOutput webcamOutput"; std::cerr << " width height numFrames FpS" << std::endl; return EXIT_FAILURE; } // Parse the input video files std::string inFile = ""; for( int i = 1; i <= 5; ++i ) { inFile = inFile + std::string(argv[i]); if( i != 5 ) { inFile = inFile + std::string(","); } } return test_FileListVideoIO(inFile.c_str(), argv[6], argv[7], argv[8], atoi(argv[9]), atoi(argv[10]), atoi(argv[11]), atof(argv[12])); }
1fadce42dc745eca61f546ece565e8af0d83887f
db001562ab523b3b733022a5c85c755c9bf92527
/source/Reservacion.cpp
b6ce8ae49d7b6b7bbe6e8c502f86aa59a5be35b3
[]
no_license
nattfv/airline-book
6af164dfa8944df47b284b7714c8fe0acd2ea92e
0f3c4e73cbda9e71bdc806780d02327a4604d117
refs/heads/master
2020-03-19T12:17:11.439886
2018-05-30T21:02:39
2018-05-30T21:02:39
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
3,198
cpp
#include "Reservacion.h" #include"utiles.h" Reservacion::Reservacion() : cantidadReservados(0), vuelo(NULL), vendedor(NULL), cliente(NULL) { } Reservacion::Reservacion(Vuelo * _vuelo, Vendedor * _vendedor, Cliente* _cliente) { cantidadReservados = 0; vuelo = new Vuelo(*_vuelo); vendedor = new Vendedor(*_vendedor); cliente = _cliente; asientosReservados = new AsientoReservado(); } Reservacion::Reservacion(const Reservacion & r) { cantidadReservados = r.cantidadReservados; vuelo = new Vuelo(*r.vuelo); vendedor = new Vendedor(*r.vendedor); cliente = new Cliente(*r.cliente); asientosReservados = new AsientoReservado(*r.asientosReservados); } Reservacion::~Reservacion() { delete vendedor; delete asientosReservados; delete cliente; } Reservacion & Reservacion::operator=(const Reservacion & r) { if (this != &r) { if (vuelo) delete vuelo; if (vendedor) delete vendedor; if (cliente) delete cliente; cantidadReservados = r.cantidadReservados; vuelo = new Vuelo(*r.vuelo); vendedor = new Vendedor(*r.vendedor); cliente = new Cliente(*r.cliente); asientosReservados = new AsientoReservado(*r.asientosReservados); } return *this; } string Reservacion::mostrarReservacion() { stringstream s; s << "Reservados: " << cantidadReservados << " asientos\n" << asientosReservados->mostrarAsientosReservados() /*<< "Vendedor\n" << vendedor->mostrarVendedor() << "\n"*/ << "Cliente\n" << cliente->mostrarCliente() << "\n" << "Vuelo\n" << vuelo->mostrarVuelo(); return s.str(); } /* Verifica si no ha excedido la cantida de asiento para reservar */ bool Reservacion::puedoReservar(int _fila, int _columna, Vuelo* a) //mejor que le caiga el avion por parametro { Avion* avion = vuelo->obtenerAvion(); //avion asignado al vuelo MatrizAsiento* asientos = avion->obtenerPasajeros(); //los asientos actualizados del avion Asiento* posibleAsiento = asientos->obtenerAsiento(_fila, _columna); //el asiento que quiero reservar if (asientosReservados->agregar(posibleAsiento)) { cantidadReservados++; a->actualizarPasajero(_fila, _columna); return true; } else return false; } bool Reservacion::compararVendedor(Vendedor * v) { return *vendedor == *v; } ostream & operator<<(ostream & out, Reservacion & _d) { return out <<_d.mostrarReservacion(); } ofstream & operator<<(ofstream & archivo, Reservacion & d) { archivo << d.cantidadReservados << "\n"; archivo << *d.vuelo; archivo << *d.vendedor; archivo << *d.cliente; archivo << *d.asientosReservados; return archivo; } ifstream & operator>>(ifstream & archivo, Reservacion & d) { // TODO: insertar una instrucción return aquí string hilera = procesarHilera(archivo); stringstream particion(hilera); Vuelo vuelo; Vendedor vendedor; Cliente cliente; AsientoReservado asientosReservados; int cantidadReservados = procesarInt(particion, '\n'); archivo >> vuelo; archivo >> vendedor; archivo >> cliente; archivo >> asientosReservados; d.cantidadReservados = cantidadReservados; d.vuelo = new Vuelo(vuelo); d.vendedor = new Vendedor(vendedor); d.cliente = new Cliente(cliente); d.asientosReservados = new AsientoReservado(asientosReservados); return archivo; }
2e01fcc10935d16a26c731907f62e6c4a69e300b
2b3bb647861a2c8d5362b7e54de95470b82fd916
/array4.cpp
652f04a4c66a9ffbe14e6142d795a117299b1f5f
[]
no_license
shobhit3661/DSA-Practice
564f25aeff53ae509be688d7aa50d9a200db22ac
ad5b071a03bdbb4d8b97d04126683dbf5b4926b6
refs/heads/master
2023-03-28T14:12:17.139676
2021-04-02T12:06:22
2021-04-02T12:06:22
307,766,484
1
0
null
null
null
null
UTF-8
C++
false
false
592
cpp
#include<bits/stdc++.h> #define fast ios::sync_with_stdio(false); cin.tie(0); cout.tie(0) typedef long long int ll; using namespace std; void solve() { int n; cin>>n; int ar[i]; for(int i=0;i<n;i++)cin>>ar[i]; int zero=0,one=0,two=0; for(int i=0;i<n;i++) { if(ar[i]==0) { zero++; } if(ar[i]==1) { one++; } if(ar[i]==2) { two++; } } for(int i=0;i<zero;i++)cout<<"0"<<" "; for(int i=0;i<one;i++)cout<<"1"<<" "; for(int i=0;i<two;i++)cout<<"2"<<" "; cout<<"\n"; } int main() { fast; ll t=1; cin>>t; while(t--) solve(); return 0; }
10a03d09cdd4ead5ccb9ecea154267f12f97b69b
3a18d90e150c2a6d51457d0df936a18818c94685
/buyMaxStocks.cpp
e5c8212046343b1017f0e1ed3b96b254b9e37de2
[]
no_license
pradhanpobitra/DSA450_sheet
9b3457ff72ea4571fa1f881fb332c3aff084f471
bd4baefeac053afed872c6ddae7d68faa252072c
refs/heads/main
2023-06-30T02:53:16.377733
2021-06-04T04:26:50
2021-06-04T04:26:50
328,868,155
0
0
null
null
null
null
UTF-8
C++
false
false
727
cpp
#include<bits/stdc++.h> using namespace std; bool myway(const pair<int,int> &a,const pair<int,int> &b) { return a.first < b.first; } int main() { int n,x,i,k; cin >> n >> k; vector<pair<int,int>> v; for(i=1;i<=n;i++) { cin >> x; v.push_back(make_pair(x,i)); } sort(v.begin(),v.end(),myway); int count = 0; i=0; while(1) { if(i >= n || v[i].first > k) break; int buyable = k / v[i].first; if(buyable >= v[i].second) { count += v[i].second; k -= v[i].second * v[i].first; } else { count += buyable; k -= buyable * v[i].first; } i++; } cout << count << endl; }
50fe229d53f958da76f0e4436c4c43c6d515c30e
ac33ec551332ad8467d1018b1753a8edadefb542
/src/tagger/LabelExtractor.hh
c47813f23907b5e7c4e3542be9ebb496125d4447
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
mrummuka/FinnPos
65ec058caed5d2b8cb0253b85e42d0d38f835ade
33fa8ed889246bbdfa4de11a489b94f06fc87d85
refs/heads/master
2021-01-12T20:57:05.384183
2016-05-14T21:33:30
2016-05-14T21:33:30
58,828,649
0
0
null
2016-05-14T20:21:02
2016-05-14T20:21:02
null
UTF-8
C++
false
false
3,390
hh
/** * @file LabelExtractor.hh * @Author Miikka Silfverberg * @brief Suffix-based label guesser */ /////////////////////////////////////////////////////////////////////////////// // // // (C) Copyright 2014, University of Helsinki // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // // /////////////////////////////////////////////////////////////////////////////// #ifndef HEADER_LabelExtractor_hh #define HEADER_LabelExtractor_hh #include <string> #include <vector> //#include <unordered_map> #include "UnorderedMapSet.hh" #include "io.hh" #include "exceptions.hh" #include "SuffixLabelMap.hh" #include "TaggerOptions.hh" class Data; class LabelExtractor { public: static int all_time_word_count; static int all_time_guess_count; LabelExtractor(unsigned int max_suffix_len=10); LabelExtractor(const TaggerOptions &tagger_options); virtual ~LabelExtractor(void); virtual void set_label_candidates(const std::string &word_form, bool use_lexicon, float mass, LabelVector &target, int candidate_count = -1) const; void train(Data &data); unsigned int get_boundary_label(void) const; unsigned int get_label(const std::string &label_string); LabelVector get_labels(const StringVector &label_strings); const std::string &get_label_string(unsigned int label) const; unsigned int label_count(void) const; void store(std::ostream &out) const; void load(std::istream &in, bool reverse_bytes); bool operator==(const LabelExtractor &another) const; const LabelVector &sub_labels(unsigned int label) const; bool is_oov(const std::string &wf) const; bool open_class(unsigned int label) const; void set_options(TaggerOptions &tagger_options); private: typedef std::vector<SuffixLabelMap> SuffixLabelMapVector; typedef std::unordered_map<std::string, LabelVector> SubstringLabelMap; typedef std::unordered_map<unsigned int, LabelVector> SubLabelMap; typedef std::unordered_map<unsigned int, unsigned int> LabelCountMap; unsigned int max_suffix_len; int max_guesses; std::unordered_map<std::string, unsigned int> label_map; StringVector string_map; //SubstringLabelMap label_counts; SuffixLabelMapVector label_counts; SubstringLabelMap lexicon; SubLabelMap sub_label_map; std::unordered_map<std::string, unsigned int> oov_words; LabelCountMap open_classes; }; #endif // HEADER_LabelExtractor_hh
200520cda71925dc796b115404af5c8d6466e8ff
aaabfbb7faadb59f0dad573be47781f267a10812
/elliptic_group.h
6c6fbb66d199bdd2eeb247bf06c8156a7f965917
[]
no_license
MansDolorem/ecdsa_example
774da0f304a7e967fb17d49a3fdaa0a3e2b0be8c
be219078ce292c58599bf0066e566297e359bf88
refs/heads/master
2021-07-22T13:56:57.998071
2017-10-31T19:45:58
2017-10-31T19:45:58
109,041,580
0
0
null
null
null
null
UTF-8
C++
false
false
747
h
#pragma once #include <fstream> #include <time.h> #define FILENAME_LENGTH 12 struct point { int x; int y; }; struct signature { int r; int s; }; class elliptic_group { private: int module; int a; int b; point G; int order_of_G; int secret_key; char filename[FILENAME_LENGTH]; public: point public_key; signature signature; elliptic_group() { module = 71; a = 27; b = 39; G = point{ 38,29 }; order_of_G = 13; } void set_filename(char* _filename) { for (int i = 0; i < FILENAME_LENGTH; i++) { filename[i] = _filename[i]; } } void generate_secret_key(); void generate_public_key(); bool read(uint8_t* message); void write(uint8_t* message); void sign(uint8_t* message); bool verify(uint8_t* message); };
0a1ac96736d6cbf5bc26867cd49e8fa9d64506e5
6697cd726d4cd3744ae52a7d5618f4ad107befba
/CP/1500/subarray_divisibilty.cpp
912590626c202da2d07b23fa4e40a80e71fa6554
[]
no_license
Saifu0/Competitive-Programming
4385777115d5d83ba5140324c309db1e6c16f4af
ecc1c05f1a85636c57f7f6609dd6a002f220c0b0
refs/heads/master
2022-12-15T09:11:53.907652
2020-09-08T08:20:44
2020-09-08T08:20:44
293,743,953
0
0
null
null
null
null
UTF-8
C++
false
false
794
cpp
#include<bits/stdc++.h> using namespace std; #define NINJA ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0) #define deb(x) cout << #x << " " << x << endl; #define fo(i,n) for(int i=0;i<n;i++) #define Fo(i,k,n) for(int i=k;i<n;i++) #define vi vector<int> #define ii pair<int,int> #define vii vector<ii> #define ll long long #define pb push_back #define endl "\n" #define mp map<int,int> #define F first #define S second #define sz(v) (int)v.size() #define mod 1000000007 int main(){ NINJA; ll n; cin >> n; vector<ll> a(n+1); fo(i,n) cin >> a[i]; ll MOD[n]; memset(MOD,0,sizeof(MOD)); ll sum = 0; fo(i,n){ sum += a[i]; MOD[((sum%n)+n)%n]++; } ll ans = 0; fo(i,n){ if(MOD[i]>1) ans += (MOD[i]*(MOD[i]-1))/2; } ans += MOD[0]; cout << ans << endl; return 0; }
bc46b8cca46b659e3a848ffb0d8fcef72eaa95e4
a38d00d6149066257f9c3ec206208afa04fc2650
/source/loonyland/bullet.cpp
dce19eab24aa8c73fb8035d0e9ab8169dd3e3b3e
[ "MIT" ]
permissive
Circadious/HamSandwich
727e3fae2430f20632f3baf5ec03ce02e95665ad
fd401b6e66e19f5eb5962cbba4d2040c0a7bb7ae
refs/heads/master
2023-07-18T03:47:38.786323
2021-09-06T04:59:03
2021-09-06T04:59:03
403,419,358
0
0
MIT
2021-09-06T04:59:04
2021-09-05T21:49:06
C++
UTF-8
C++
false
false
80,512
cpp
#include "bullet.h" #include "guy.h" #include "player.h" #include "quest.h" #include "options.h" #include "loonyball.h" #include "bowling.h" #include "ch_witch.h" #include "badge.h" bullet_t bullet[MAX_BULLETS]; sprite_set_t *bulletSpr; byte reflect=0; byte ballSoundClock,ballSteerClock; byte bulControl; byte bulletHittingType; void InitBullets(void) { bulletSpr=new sprite_set_t("graphics/bullets.jsp"); memset(bullet,0,MAX_BULLETS*sizeof(bullet_t)); } void ExitBullets(void) { delete bulletSpr; } byte Bulletable(bullet_t *me,Map *map,int x,int y) { // the IF_NOBULLET thing is cheesy - it is used only for autodoors, don't use for // anything else or it will mess up if(map->map[x+y*map->width].wall || (ItemFlags(map->map[x+y*map->width].item)&IF_TALL) || (curWorld.terrain[map->map[x+y*map->width].floor].flags&TF_NOBULLET) || ((ItemFlags(map->map[x+y*map->width].item)&IF_NOBULLET) && map->map[x+y*map->width].itemInfo<4)) { if(me->type==BLT_BOMB && map->map[x+y*map->width].item==ITM_BOOMROCK) { BombRanOut(me); } return 0; } return 1; } void CheckBoomRock(Map *map,int x,int y) { if(x>=0 && y>=0 && x<map->width && y<map->height) { if(map->map[x+y*map->width].item==ITM_BOOMROCK) { map->map[x+y*map->width].item=0; ExplodeParticles2(PART_DIRT,(x*TILE_WIDTH+TILE_WIDTH/2)*FIXAMT, (y*TILE_HEIGHT+TILE_HEIGHT/2)*FIXAMT,0,60,20); BadgeCheck(BE_DESTROY,ITM_BOOMROCK,map); } } } void CheckBoomRocks(Map *map,int xx,int yy,int size) { int i,j; int mapx,mapy,mapx1,mapx2,mapy1,mapy2; xx>>=FIXSHIFT; yy>>=FIXSHIFT; mapx=xx/TILE_WIDTH; mapy=yy/TILE_HEIGHT; mapx1=(xx-size)/TILE_WIDTH; mapy1=(yy-size)/TILE_HEIGHT; mapx2=(xx+size)/TILE_WIDTH; mapy2=(yy+size)/TILE_HEIGHT; for(i=mapx1;i<=mapx2;i++) for(j=mapy1;j<=mapy2;j++) { CheckBoomRock(map,i,j); } } byte GoodBullet(byte type) { return (type==BLT_BALLLIGHTNING || type==BLT_WHOOPEE || type==BLT_WHOOPEE2 || type==BLT_WHOOPEE3 || type==BLT_CACTUS || type==BLT_BOOMERANG || type==BLT_ICE || type==BLT_BOMB || type==BLT_GOODBOOM || type==BLT_GOODBOOM2 || type==BLT_HOTPANTS || type==BLT_ICE2 || type==BLT_BATSHOT || type==BLT_PSDSHOT || type==BLT_LOONYBALL || type==BLT_BOWLINGBALL || type==BLT_BOWLBOOM || (type>=BLT_WITCHBLAST && type<=BLT_WITCHKABOOM) || type==BLT_WOLFSHOT || type==BLT_CACTUS2 || (type>=BLT_SUMBOOM && type<=BLT_SUMHEAL) || type==BLT_DEVILDOLL || type==BLT_BATGAS || type==BLT_AURA || type==BLT_THFKNIFE || type==BLT_KNIFESHRP || type==BLT_THFFIRE); } byte BulletCanGo(bullet_t *me,int xx,int yy,Map *map,byte size) { byte result; int mapx,mapy,mapx1,mapx2,mapy1,mapy2; xx>>=FIXSHIFT; yy>>=FIXSHIFT; mapx=xx/TILE_WIDTH; mapy=yy/TILE_HEIGHT; mapx1=(xx-size)/TILE_WIDTH; mapy1=(yy-size)/TILE_HEIGHT; mapx2=(xx+size)/TILE_WIDTH; mapy2=(yy+size)/TILE_HEIGHT; result=(xx>=0 && yy>=0 && mapx2<map->width && mapy2<map->height && (Bulletable(me,map,mapx,mapy1)) && (Bulletable(me,map,mapx,mapy2)) && (Bulletable(me,map,mapx1,mapy)) && (Bulletable(me,map,mapx2,mapy)) && (Bulletable(me,map,mapx,mapy)) && (Bulletable(me,map,mapx1,mapy1)) && (Bulletable(me,map,mapx2,mapy1)) && (Bulletable(me,map,mapx2,mapy2)) && (Bulletable(me,map,mapx1,mapy2))); if((!result) && GoodBullet(me->type)) SpecialShootCheck(map,mapx,mapy); return result; } void BulletHitWallX(bullet_t *me,Map *map,world_t *world) { if(player.worldNum!=WORLD_BOWLING) TileHitCheck(me->x>>FIXSHIFT,me->y>>FIXSHIFT,8,map); switch(me->type) { case BLT_BALLLIGHTNING: case BLT_PSDSHOT: case BLT_WITCHBLAST: case BLT_DEVILDOLL: case BLT_THFKNIFE: if(me->type==BLT_THFKNIFE) { if(player.spellXP[ITM_WCACTUS-ITM_WBOMB]) { int i; for(i=0;i<2;i++) FireBullet(me->x-me->dx,me->y-me->dy,(byte)Random(256),BLT_KNIFESHRP); } me->target=0; } if(player.fireFlags&FF_REFLECT) { me->x-=me->dx; me->facing=(byte)(84+Random(89)); if(me->dx<0) me->facing=(me->facing+128)&255; me->dx=Cosine(me->facing)*11; me->dy=Sine(me->facing)*11; } else BulletRanOut(me,map,world); break; case BLT_LOONYBALL: me->x-=me->dx; me->dx=-me->dx; me->dy+=-FIXAMT/8+Random(FIXAMT/4+1); break; case BLT_BOWLINGBALL: case BLT_BOOMERANG: case BLT_SUMHEAL: me->x-=me->dx; me->dx=-me->dx; break; case BLT_ENERGY: case BLT_BIGSHOT: case BLT_FLAMEWALL: case BLT_FLAMESHOT: case BLT_BATSHOT: case BLT_WOLFSHOT: case BLT_SUMFLAME: ExplodeParticles(PART_HAMMER,me->x,me->y,me->z,4); me->type=0; break; case BLT_CLAW: ExplodeParticles(PART_SNOW2,me->x,me->y,me->z,7); me->type=0; break; case BLT_EARTHSPIKE: case BLT_EARTHSPIKE2: ExplodeParticles(PART_DIRT,me->x,me->y,me->z,8); me->type=0; break; case BLT_GASBLAST: me->x-=me->dx; me->dx=0; if(me->timer>6) me->timer=6; break; case BLT_WHOOPEE: case BLT_WHOOPEE2: case BLT_WHOOPEE3: case BLT_WITCHGAS: case BLT_HOTPANTS: case BLT_ORBGRENADE: case BLT_WATER: case BLT_FOUNTAIN: case BLT_SUMGAS: case BLT_BATGAS: case BLT_THFFIRE: me->x-=me->dx; me->dx=0; break; case BLT_MEGABOOM: case BLT_GOODBOOM: case BLT_GOODBOOM2: case BLT_BOWLBOOM: case BLT_SUMBOOM: break; case BLT_ITEM: me->x-=me->dx; me->dx=-me->dx-FIXAMT*2+Random(FIXAMT*4); Clamp(&me->dx,FIXAMT*6); break; case BLT_CACTUS: case BLT_CACTUS2: case BLT_KNIFESHRP: me->target=0; me->x-=me->dx; me->facing=(byte)(84+Random(89)); if(me->dx<0) me->facing=(me->facing+128)&255; me->dx=Cosine(me->facing)*16; me->dy=Sine(me->facing)*16; break; case BLT_WITCHBUZZSAW: BulletRanOut(me,map,world); break; case BLT_ICE: case BLT_ICE2: case BLT_ICESHARD: case BLT_MISSILE: case BLT_WIND: case BLT_WITCHICE: case BLT_SUMFROST: BulletRanOut(me,map,world); break; case BLT_BOMB: case BLT_WITCHPLAGUE: me->x-=me->dx; me->dx=-me->dx; break; case BLT_EVILFACE: // can go through anything break; } } void BulletHitWallY(bullet_t *me,Map *map,world_t *world) { if(player.worldNum!=WORLD_BOWLING) TileHitCheck(me->x>>FIXSHIFT,me->y>>FIXSHIFT,8,map); switch(me->type) { case BLT_BALLLIGHTNING: case BLT_PSDSHOT: case BLT_WITCHBLAST: case BLT_DEVILDOLL: case BLT_THFKNIFE: if(me->type==BLT_THFKNIFE) { if(player.spellXP[ITM_WCACTUS-ITM_WBOMB]) { int i; for(i=0;i<3;i++) FireBullet(me->x-me->dx,me->y-me->dy,(byte)Random(256),BLT_KNIFESHRP); } me->target=0; } if(player.fireFlags&FF_REFLECT) { me->y-=me->dy; me->facing=(byte)(20+Random(89)); if(me->dy>0) me->facing+=128; me->dx=Cosine(me->facing)*11; me->dy=Sine(me->facing)*11; } else BulletRanOut(me,map,world); break; case BLT_LOONYBALL: me->y-=me->dy; me->dy=-me->dy; me->dx+=-FIXAMT/8+Random(FIXAMT/4+1); break; case BLT_BOWLINGBALL: case BLT_BOOMERANG: case BLT_SUMHEAL: me->y-=me->dy; me->dy=-me->dy; break; case BLT_ENERGY: case BLT_BIGSHOT: case BLT_FLAMEWALL: case BLT_FLAMESHOT: case BLT_BATSHOT: case BLT_WOLFSHOT: case BLT_SUMFLAME: ExplodeParticles(PART_HAMMER,me->x,me->y,me->z,4); me->type=0; break; case BLT_CLAW: ExplodeParticles(PART_SNOW2,me->x,me->y,me->z,7); me->type=0; break; case BLT_EARTHSPIKE: case BLT_EARTHSPIKE2: ExplodeParticles(PART_DIRT,me->x,me->y,me->z,8); me->type=0; break; case BLT_GASBLAST: me->y-=me->dy; me->dy=0; if(me->timer>6) me->timer=6; break; case BLT_WHOOPEE: case BLT_WHOOPEE2: case BLT_WHOOPEE3: case BLT_WITCHGAS: case BLT_HOTPANTS: case BLT_ORBGRENADE: case BLT_WATER: case BLT_FOUNTAIN: case BLT_SUMGAS: case BLT_BATGAS: case BLT_THFFIRE: me->y-=me->dy; me->dy=0; break; case BLT_MEGABOOM: case BLT_GOODBOOM: case BLT_GOODBOOM2: case BLT_BOWLBOOM: case BLT_SUMBOOM: break; case BLT_ITEM: me->y-=me->dy; me->dy=-me->dy-FIXAMT*2+Random(FIXAMT*4); Clamp(&me->dy,FIXAMT*6); break; case BLT_CACTUS: case BLT_CACTUS2: case BLT_KNIFESHRP: me->target=0; me->y-=me->dy; me->facing=(byte)(20+Random(89)); if(me->dy>0) me->facing+=128; me->dx=Cosine(me->facing)*16; me->dy=Sine(me->facing)*16; break; case BLT_WITCHBUZZSAW: BulletRanOut(me,map,world); break; case BLT_ICE: case BLT_ICE2: case BLT_MISSILE: case BLT_WIND: case BLT_ICESHARD: case BLT_WITCHICE: case BLT_SUMFROST: BulletRanOut(me,map,world); break; case BLT_BOMB: case BLT_WITCHPLAGUE: me->y-=me->dy; me->dy=-me->dy; break; case BLT_EVILFACE: // can go through anything break; } } void BulletHitFloor(bullet_t *me,Map *map,world_t *world) { switch(me->type) { case BLT_BALLLIGHTNING: case BLT_BOMB: me->z=0; me->dz=-me->dz; break; case BLT_LOONYBALL: if(me->dz<-FIXAMT) { MakeSound(SND_BALLBOUNCE,me->x,me->y,SND_CUTOFF,300); } me->z=0; me->dz=-me->dz*15/16; // friction! Dampen(&me->dx,FIXAMT/8); Dampen(&me->dy,FIXAMT/8); break; case BLT_DEVILDOLL: me->z=0; me->dz=-me->dz*11/16; // friction! Dampen(&me->dx,FIXAMT/8); Dampen(&me->dy,FIXAMT/8); break; case BLT_ENERGY: case BLT_BIGSHOT: ExplodeParticles(PART_HAMMER,me->x,me->y,me->z,4); me->type=0; break; case BLT_BOWLINGBALL: me->z=0; me->dz=-me->dz/2; Dampen(&me->dx,FIXAMT/32); Dampen(&me->dy,FIXAMT/32); break; case BLT_FLAMEWALL: case BLT_EARTHSPIKE: case BLT_EARTHSPIKE2: case BLT_GASBLAST: case BLT_WHOOPEE: case BLT_WHOOPEE2: case BLT_WHOOPEE3: case BLT_MEGABOOM: case BLT_GOODBOOM: case BLT_GOODBOOM2: case BLT_CACTUS: case BLT_CACTUS2: case BLT_ICE: case BLT_ICE2: case BLT_BOOMERANG: case BLT_HOTPANTS: case BLT_MISSILE: case BLT_BATSHOT: case BLT_WIND: case BLT_ICESHARD: case BLT_FOUNTAIN: case BLT_FLAMESHOT: case BLT_PSDSHOT: case BLT_BOWLBOOM: case BLT_WITCHBLAST: case BLT_WITCHBUZZSAW: case BLT_WITCHICE: case BLT_WITCHGAS: case BLT_WITCHPLAGUE: case BLT_WOLFSHOT: case BLT_CLAW: case BLT_SUMBOOM: case BLT_SUMGAS: case BLT_SUMFLAME: case BLT_SUMHEAL: case BLT_SUMFROST: case BLT_BATGAS: case BLT_THFKNIFE: case BLT_KNIFESHRP: case BLT_THFFIRE: // don't care about the floor break; case BLT_ORBGRENADE: case BLT_WATER: BulletRanOut(me,map,world); break; case BLT_ITEM: me->z=0; me->dz=-me->dz; break; case BLT_EVILFACE: // can go through anything break; } } void BombRanOut(bullet_t *me) { if(player.wpnLevel==0) { me->type=BLT_GOODBOOM; me->timer=7; MakeSound(SND_BOOM,me->x,me->y,SND_CUTOFF,1200); } else if(player.wpnLevel==1) { me->type=BLT_GOODBOOM; me->timer=7; MakeSound(SND_BOOM,me->x,me->y,SND_CUTOFF,1200); // and launch two more FireBullet(me->x-64*FIXAMT+Random(128*FIXAMT), me->y-48*FIXAMT+Random(96*FIXAMT),0,BLT_GOODBOOM); FireBullet(me->x-64*FIXAMT+Random(128*FIXAMT), me->y-48*FIXAMT+Random(96*FIXAMT),0,BLT_GOODBOOM); } else { me->type=BLT_GOODBOOM2; me->timer=9; MakeSound(SND_BIGBOOM,me->x,me->y,SND_CUTOFF,1200); } me->anim=0; me->dx=0; me->dy=0; me->dz=0; } void BulletRanOut(bullet_t *me,Map *map,world_t *world) { switch(me->type) { case BLT_WITCHSHOCK: case BLT_ENERGY: case BLT_BIGSHOT: case BLT_FLAMEWALL: case BLT_EARTHSPIKE: case BLT_EARTHSPIKE2: case BLT_GASBLAST: case BLT_MEGABOOM: case BLT_GOODBOOM: case BLT_GOODBOOM2: case BLT_BOWLBOOM: case BLT_BADBOOM: case BLT_ITEM: case BLT_WHOOPEE: case BLT_WHOOPEE2: case BLT_WHOOPEE3: case BLT_CACTUS: case BLT_CACTUS2: case BLT_SWAMPGAS: case BLT_SWAMPGAS2: case BLT_MISLSMOKE: case BLT_HOTPANTS: case BLT_BATSHOT: case BLT_FOUNTAIN: case BLT_FLAMESHOT: case BLT_EVILFACE: case BLT_WITCHKABOOM: case BLT_WITCHSPEED: case BLT_WITCHGAS: case BLT_WITCHPLAGUE: case BLT_WOLFSHOT: case BLT_CLAW: case BLT_SUMBOOM: case BLT_SUMGAS: case BLT_SUMFLAME: case BLT_SUMHEAL: case BLT_BATGAS: case BLT_AURA: case BLT_KNIFESHRP: case BLT_THFFIRE: me->type=0; break; case BLT_LOONYBALL: me->timer=100; break; case BLT_BOWLINGBALL: GutterBall(); ExplodeParticles(PART_SNOW2,me->x,me->y,me->z,8); me->type=0; break; case BLT_WIND: ExplodeParticles(PART_SNOW2,me->x,me->y,me->z,8); me->type=BLT_NONE; break; case BLT_THFKNIFE: ExplodeParticles(PART_SNOW2,me->x,me->y,me->z,3); me->type=BLT_NONE; if(player.spellXP[ITM_WBOMB-ITM_WBOMB]) FireBullet(me->x,me->y,me->facing,BLT_GOODBOOM); if(player.spellXP[ITM_WWHOOPEE-ITM_WBOMB]) FireBullet(me->x,me->y,me->facing,BLT_WHOOPEE); break; case BLT_BALLLIGHTNING: case BLT_PSDSHOT: case BLT_WITCHBLAST: case BLT_WITCHBUZZSAW: case BLT_DEVILDOLL: if(opt.cheats[CH_FROGWPN]) ExplodeParticles(PART_SLIME,me->x,me->y,me->z,4); else ExplodeParticles(PART_SNOW2,me->x,me->y,me->z,4); me->type=BLT_NONE; break; case BLT_BOOMERANG: ExplodeParticles(PART_DIRT,me->x,me->y,me->z,8); me->type=0; break; case BLT_ICE: case BLT_ICE2: case BLT_ICESHARD: case BLT_WITCHICE: case BLT_SUMFROST: ExplodeParticles(PART_SNOW2,me->x,me->y,me->z,8); me->type=0; break; case BLT_ORBGRENADE: FireBullet(me->x,me->y,0,BLT_MEGABOOM); me->type=0; break; case BLT_MISSILE: FireBullet(me->x,me->y,0,BLT_BADBOOM); me->type=0; break; case BLT_BOMB: BombRanOut(me); break; case BLT_WATER: if(Random(3)==0) MakeSound(SND_WATERSPLASH,me->x,me->y,SND_CUTOFF,200); ExplodeParticles(PART_WATER,me->x,me->y,me->z,8); me->type=BLT_NONE; break; } } void HitBadguys(bullet_t *me,Map *map,world_t *world) { int i; byte b; bullet_t *you; bulletHittingType=me->type; switch(me->type) { case BLT_WITCHICE: if(FreezeVictimWitch(me->x>>FIXSHIFT,me->y>>FIXSHIFT,12,me->dx,me->dy,65535,250,map,world)) { me->type=BLT_NONE; ExplodeParticles(PART_SNOW2,me->x,me->y,me->z,10); } break; case BLT_WITCHGAS: if(FindVictims(me->x>>FIXSHIFT,me->y>>FIXSHIFT,24,me->dx,me->dy,1+SpellLevel(SPL_PLAGUE)/3,map,world)) { // nothing, just ouch } break; case BLT_WITCHBLAST: case BLT_DEVILDOLL: if(player.monsType==MONS_PLYRSUMMON) { i=5; } else { i=SpellLevel(SPL_BLAST)*2; if(opt.cheats[CH_HEAVYHIT]) i*=3; i+=2; } if(FindVictim(me->x>>FIXSHIFT,me->y>>FIXSHIFT,12,me->dx,me->dy,i,map,world)) { ExplodeParticles(PART_SNOW2,me->x,me->y,me->z,8); me->type=BLT_NONE; } break; case BLT_WITCHBUZZSAW: if(FindNewVictim(me->x>>FIXSHIFT,me->y>>FIXSHIFT,&me->target,12,me->dx,me->dy,2,map,world)) { ExplodeParticles(PART_SNOW2,me->x,me->y,me->z,3); } break; case BLT_LOONYBALL: GetKicked(me); break; case BLT_BOWLINGBALL: if(FindVictim(me->x>>FIXSHIFT,me->y>>FIXSHIFT,10,me->dx,me->dy,10,map,world)) { ExplodeParticles(PART_SNOW2,me->x,me->y,me->z,8); BowlingBallIsDone(); me->type=0; } break; case BLT_BALLLIGHTNING: i=player.firePower*2+2; if(opt.cheats[CH_HEAVYHIT]) { i+=player.fireRange*2; i+=player.fireRate*2; } if(FindVictim(me->x>>FIXSHIFT,me->y>>FIXSHIFT,12,me->dx,me->dy,i,map,world)) { ExplodeParticles(PART_SNOW2,me->x,me->y,me->z,8); me->type=BLT_NONE; } break; case BLT_PSDSHOT: i=2+player.firePower/2; if(opt.cheats[CH_HEAVYHIT]) { i+=player.fireRange*2; i+=player.fireRate*2; } if(FindVictim(me->x>>FIXSHIFT,me->y>>FIXSHIFT,12,me->dx,me->dy,i,map,world)) { ExplodeParticles(PART_SNOW2,me->x,me->y,me->z,8); me->type=BLT_NONE; } break; case BLT_WOLFSHOT: i=(player.firePower/2)+2; if(opt.cheats[CH_HEAVYHIT]) { i+=player.fireRate/2; i*=(player.fireRange/3)+1; } if(FindVictim(me->x>>FIXSHIFT,me->y>>FIXSHIFT,8,me->dx,me->dy,i,map,world)) { ExplodeParticles(PART_HAMMER,me->x,me->y,me->z,8); me->type=BLT_NONE; } break; case BLT_BATSHOT: if(FindVictim(me->x>>FIXSHIFT,me->y>>FIXSHIFT,8,me->dx,me->dy,1,map,world)) { ExplodeParticles(PART_HAMMER,me->x,me->y,me->z,8); me->type=BLT_NONE; } break; case BLT_THFKNIFE: if(FindNewVictim(me->x>>FIXSHIFT,me->y>>FIXSHIFT,&me->target,8,me->dx,me->dy,2,map,world)) { if(player.spellXP[ITM_WICE-ITM_WBOMB] && me->target) { if(GetGuy(me->target)->hp>0 && !(MonsterFlags(GetGuy(me->target)->type)&MF_INVINCIBLE)) GetGuy(me->target)->ice+=20; } if(player.spellXP[ITM_WCACTUS-ITM_WBOMB]) { for(i=0;i<3;i++) { you=FireBullet(me->x-me->dx,me->y-me->dy,(byte)Random(256),BLT_KNIFESHRP); if(you) you->target=me->target; } } ExplodeParticles(PART_SNOW2,me->x,me->y,me->z,3); BulletRanOut(me,map,world); if(player.spellXP[ITM_WLIGHTNING-ITM_WBOMB]) { me->type=BLT_THFKNIFE; // don't vanish it if you've got the lightning powerup } } break; case BLT_BIGSHOT: if(FindGoodVictim(me->x>>FIXSHIFT,me->y>>FIXSHIFT,12,me->dx,me->dy,3,map,world)) { me->type=BLT_NONE; ExplodeParticles(PART_HAMMER,me->x,me->y,me->z,12); } break; case BLT_ENERGY: if(FindGoodVictim(me->x>>FIXSHIFT,me->y>>FIXSHIFT,8,me->dx,me->dy,1,map,world)) { me->type=BLT_NONE; ExplodeParticles(PART_HAMMER,me->x,me->y,me->z,6); } break; case BLT_FLAMEWALL: if(FindGoodVictim(me->x>>FIXSHIFT,me->y>>FIXSHIFT,16,me->dx,me->dy,1,map,world)) { // make a noise } break; case BLT_SUMFLAME: if(FindVictims(me->x>>FIXSHIFT,me->y>>FIXSHIFT,16,0,0,1,map,world)) { // ouch } FindSummonToHelp(me->x>>FIXSHIFT,me->y>>FIXSHIFT,16,1,map,world); break; case BLT_FLAMESHOT: if(FindGoodVictim(me->x>>FIXSHIFT,me->y>>FIXSHIFT,16,me->dx,me->dy,3,map,world)) { // make a noise } break; case BLT_EARTHSPIKE: if(FindGoodVictim(me->x>>FIXSHIFT,me->y>>FIXSHIFT,16,me->dx,me->dy,3,map,world)) { } break; case BLT_EARTHSPIKE2: if(FindGoodVictim(me->x>>FIXSHIFT,me->y>>FIXSHIFT,16,me->dx,me->dy,1,map,world)) { } break; case BLT_GASBLAST: if(b=FindGoodVictim(me->x>>FIXSHIFT,me->y>>FIXSHIFT,24,me->dx,me->dy,0,map,world)) { // 3 hearts/seconds of poison please if(b==2) PoisonPlayer(32*3); } break; case BLT_MEGABOOM: if(FindGoodVictim(me->x>>FIXSHIFT,me->y>>FIXSHIFT,100,0,0,4,map,world)) { // ouch } break; case BLT_ITEM: if(ItemHitPlayer(me->x>>FIXSHIFT,me->y>>FIXSHIFT,12,0,0,me->anim,map,world)) { me->type=BLT_NONE; ExplodeParticles(PART_HAMMER,me->x,me->y,me->z,8); } break; case BLT_WHOOPEE: case BLT_WHOOPEE2: case BLT_WHOOPEE3: if(FindVictims(me->x>>FIXSHIFT,me->y>>FIXSHIFT,24,me->dx,me->dy,1+(me->type==BLT_WHOOPEE3),map,world)) { // nothing, just ouch } break; case BLT_SUMGAS: case BLT_BATGAS: if(FindVictims(me->x>>FIXSHIFT,me->y>>FIXSHIFT,24,me->dx,me->dy,1,map,world)) { // nothing, just ouch } break; case BLT_CACTUS: if(FindVictim(me->x>>FIXSHIFT,me->y>>FIXSHIFT,4,me->dx,me->dy,player.wpnLevel+1,map,world)) { me->type=BLT_NONE; ExplodeParticles(PART_YELLOW,me->x,me->y,me->z,3); } break; case BLT_KNIFESHRP: if(FindNewVictim(me->x>>FIXSHIFT,me->y>>FIXSHIFT,&me->target,4,me->dx,me->dy,1,map,world)) { me->type=BLT_NONE; ExplodeParticles(PART_SNOW2,me->x,me->y,me->z,3); } break; case BLT_CACTUS2: if(FindVictim(me->x>>FIXSHIFT,me->y>>FIXSHIFT,4,me->dx,me->dy,4,map,world)) { me->type=BLT_NONE; ExplodeParticles(PART_YELLOW,me->x,me->y,me->z,6); } break; case BLT_BOOMERANG: if(FindNewVictim(me->x>>FIXSHIFT,me->y>>FIXSHIFT,&me->target,12,me->dx,me->dy,7,map,world)) { ExplodeParticles(PART_DIRT,me->x,me->y,me->z,3); } if(me->timer<60 && ItemHitPlayer(me->x>>FIXSHIFT,me->y>>FIXSHIFT,12,0,0,0,map,world)) { // get 2 gems for catching it again player.money+=(1+player.wpnLevel); if(player.money>player.maxMoney) player.money=player.maxMoney; me->type=BLT_NONE; } break; case BLT_ICE: case BLT_ICE2: if(i=FreezeVictim(me->x>>FIXSHIFT,me->y>>FIXSHIFT,12,me->dx,me->dy,me->target,128,map,world)) { me->target=i; if(player.wpnLevel>0 && me->type!=BLT_ICE2) { for(i=0;i<player.wpnLevel*8;i++) { you=FireBullet(me->x,me->y,(byte)Random(256),BLT_ICE2); if(you) you->target=me->target; } } me->type=BLT_NONE; ExplodeParticles(PART_SNOW2,me->x,me->y,me->z,10); } break; case BLT_SUMFROST: if(FreezeVictim(me->x>>FIXSHIFT,me->y>>FIXSHIFT,12,me->dx,me->dy,65535,100*(player.firePower+1),map,world)) { me->type=BLT_NONE; ExplodeParticles(PART_SNOW2,me->x,me->y,me->z,10); } break; case BLT_BOMB: if(FindVictim(me->x>>FIXSHIFT,me->y>>FIXSHIFT,16,me->dx,me->dy,5,map,world)) { BulletRanOut(me,map,world); } break; case BLT_BADBOOM: if(FindGoodVictim(me->x>>FIXSHIFT,me->y>>FIXSHIFT,48,0,0,3,map,world)) { // ouch } break; case BLT_BOWLBOOM: if(FindVictims(me->x>>FIXSHIFT,me->y>>FIXSHIFT,24,me->dx,me->dy,6,map,world)) { // ouch } break; case BLT_GOODBOOM: if(FindVictims(me->x>>FIXSHIFT,me->y>>FIXSHIFT,48,0,0,6-3*(player.monsType==MONS_PLYRTHIEF),map,world)) { // ouch } CheckBoomRocks(map,me->x,me->y,48); break; case BLT_GOODBOOM2: if(FindVictims(me->x>>FIXSHIFT,me->y>>FIXSHIFT,128,0,0,20,map,world)) { // ouch } CheckBoomRocks(map,me->x,me->y,128); break; case BLT_SUMBOOM: i=30*(player.firePower+1)/11; if(FindVictims(me->x>>FIXSHIFT,me->y>>FIXSHIFT,128,0,0,i,map,world)) { // ouch } CheckBoomRocks(map,me->x,me->y,128); break; case BLT_SWAMPGAS: case BLT_SWAMPGAS2: if(b=FindGoodVictim(me->x>>FIXSHIFT,me->y>>FIXSHIFT,10,me->dx,me->dy,0,map,world)) { // 1 hearts/seconds of poison please if(b==2) PoisonPlayer(32*1); } break; case BLT_HOTPANTS: case BLT_THFFIRE: if(FindVictims(me->x>>FIXSHIFT,me->y>>FIXSHIFT,16,0,0,1,map,world)) { // ouch } break; case BLT_MISSILE: case BLT_WIND: if(FindGoodVictim(me->x>>FIXSHIFT,me->y>>FIXSHIFT,16,me->dx,me->dy,3,map,world)) { BulletRanOut(me,map,world); } break; case BLT_SLINGPOW: if(FindSlingVictim(me->x>>FIXSHIFT,me->y>>FIXSHIFT,3,player.firePower*2,map,world)) { ExplodeParticles(PART_HAMMER,me->x,me->y,0,16); } else { ExplodeParticles(PART_SNOW2,me->x,me->y,0,4); MakeNormalSound(SND_MUMMYSHOOT); } me->type=BLT_NONE; break; case BLT_ICESHARD: if(FindGoodVictim(me->x>>FIXSHIFT,me->y>>FIXSHIFT,4,me->dx/2,me->dy/2,0,map,world)) { player.invinc=0; // do not blink player.stone+=15; goodguy->dx+=me->dx/4; goodguy->dy+=me->dy/4; MakeSound(SND_FREEZE,me->x,me->y,SND_CUTOFF,1200); } break; case BLT_WATER: if(FindVictim(me->x>>FIXSHIFT,me->y>>FIXSHIFT,8,0,0,1,map,world)) { FireBullet(me->x-10*FIXAMT+Random(20*FIXAMT),me->y-10*FIXAMT+Random(20*FIXAMT),0,BLT_MISLSMOKE); MakeSound(SND_STEAM,me->x,me->y,SND_CUTOFF,600); me->type=BLT_NONE; } break; case BLT_CLAW: if(FindGoodVictim(me->x>>FIXSHIFT,me->y>>FIXSHIFT,8,0,0,3,map,world)) { ExplodeParticles(PART_SNOW2,me->x,me->y,0,10); me->type=BLT_NONE; } break; case BLT_SUMHEAL: if(FindSummonToHelp(me->x>>FIXSHIFT,me->y>>FIXSHIFT,16,2,map,world)) { MakeSound(SND_HEAL,me->x,me->y,SND_CUTOFF,600); ExplodeParticles(PART_SLIME,me->x,me->y,0,10); me->type=BLT_NONE; } break; } } inline void BulletFaceGuy(bullet_t *me,Guy *goodguy) { int desired; int diff,dir; if(goodguy->x<me->x-FIXAMT*32) { if(goodguy->y<me->y-FIXAMT*32) desired=5; else if(goodguy->y>me->y+FIXAMT*32) desired=3; else desired=4; } else if(goodguy->x>me->x+FIXAMT*32) { if(goodguy->y<me->y-FIXAMT*32) desired=7; else if(goodguy->y>me->y+FIXAMT*32) desired=1; else desired=0; } else { if(goodguy->y<me->y-FIXAMT*32) desired=6; else desired=2; } if(desired==me->facing) return; if(desired>me->facing) { diff=desired-me->facing; if(diff>4) { dir=-1; diff=8-diff; } else dir=1; } else { diff=me->facing-desired; if(diff>4) { dir=1; diff=8-diff; } else dir=-1; } me->facing=(me->facing+dir)&7; } inline void BulletFaceGuy2(bullet_t *me,Guy *goodguy) { int f; int diff,dir,desired,amt; f=me->facing; me->facing/=32; BulletFaceGuy(me,goodguy); desired=me->facing*32; me->facing=f; if(desired>me->facing) { diff=desired-me->facing; if(diff>128) { dir=-1; diff=256-diff; } else dir=1; amt=4; if(amt>diff) amt=diff; } else { diff=me->facing-desired; if(diff>128) { dir=1; diff=256-diff; } else dir=-1; amt=4; if(amt>diff) amt=diff; } me->facing+=dir*amt; } void CalcBulletFacing(bullet_t *me) { int dx,dy; dx=me->dx/(FIXAMT*4); dy=me->dy/(FIXAMT*4); if(dx==0) { if(dy<0) me->facing=192; else me->facing=64; } else if(dy==0) { if(dx<0) me->facing=128; else me->facing=0; } else { if(dx<0) { if(dy<0) me->facing=160; else me->facing=96; } else { if(dy<0) me->facing=224; else me->facing=32; } } } void BustLightning(int s,int e,char b,Map *map) { int x1,y1,x2,y2; int i; x1=0; y1=0; for(i=0;i<map->width*map->height;i++) { if(map->map[x1+y1*map->width].tag==s) break; x1++; if(x1==map->width) { x1=0; y1++; } } x2=0; y2=0; for(i=0;i<map->width*map->height;i++) { if(map->map[x2+y2*map->width].tag==e) break; x2++; if(x2==map->width) { x2=0; y2++; } } LightningBolt((x1*TILE_WIDTH+TILE_WIDTH/2)*FIXAMT, (y1*TILE_HEIGHT)*FIXAMT, (x2*TILE_WIDTH+TILE_WIDTH/2)*FIXAMT, (y2*TILE_HEIGHT)*FIXAMT); map->BrightTorch(x1,y1,b,8); map->BrightTorch(x2,y2,b,8); } void UpdateBullet(bullet_t *me,Map *map,world_t *world) { byte bustOrder[]={29,20,21,22,23,30,31,24,25,26,27,28,29}; int mapx,mapy; byte b,b2,b3,b4; bullet_t *you; word w; if(!me->type) return; reflect=0; mapx=(me->x/TILE_WIDTH)>>FIXSHIFT; mapy=(me->y/TILE_HEIGHT)>>FIXSHIFT; if(mapx>=0 && mapy>=0 && mapx<map->width && mapy<map->height) me->bright=map->map[mapx+mapy*map->width].templight; else me->bright=-32; b=0; if(me->type!=BLT_EVILFACE) { me->x+=me->dx; if(!BulletCanGo(me,me->x,me->y,map,8)) BulletHitWallX(me,map,world); else { me->y+=me->dy; if(!BulletCanGo(me,me->x,me->y,map,8)) BulletHitWallY(me,map,world); } } else { me->x+=me->dx; me->y+=me->dy; if(me->x<0 || me->x>=(map->width-1)*TILE_WIDTH*FIXAMT || me->y<0 || me->y>=(map->height-1)*TILE_HEIGHT*FIXAMT) me->type=BLT_NONE; } me->z+=me->dz; if(me->z<0) BulletHitFloor(me,map,world); // all gravity-affected bullets, get gravitized if(me->type==BLT_BALLLIGHTNING || me->type==BLT_ITEM || me->type==BLT_BOMB || me->type==BLT_ORBGRENADE || me->type==BLT_LOONYBALL || me->type==BLT_BOWLINGBALL || me->type==BLT_DEVILDOLL) me->dz-=FIXAMT; me->timer--; if(!me->timer) BulletRanOut(me,map,world); // special things like animation switch(me->type) { case BLT_SUMHEAL: if(me->timer>100) { } else { if(me->target==65535 || !GetGuyPos(me->target,&mapx,&mapy) || GetGuy(me->target)->hp==0) { me->target=LockOnSummon(me->x>>FIXSHIFT,me->y>>FIXSHIFT); } else { if(me->x>mapx) me->dx-=FIXAMT; else me->dx+=FIXAMT; if(me->y>mapy) me->dy-=FIXAMT; else me->dy+=FIXAMT; Clamp(&me->dx,FIXAMT*10); Clamp(&me->dy,FIXAMT*10); HitBadguys(me,map,world); } } me->anim++; if(me->anim>=16) { me->anim=0; } break; case BLT_WITCHPLAGUE: if(me->target==65535 || !GetGuyPos(me->target,&mapx,&mapy) || GetGuy(me->target)->hp==0) { me->target=LockOnEvil(me->x>>FIXSHIFT,me->y>>FIXSHIFT); } else { if(me->x>mapx) me->dx-=FIXAMT; else me->dx+=FIXAMT; if(me->y>mapy) me->dy-=FIXAMT; else me->dy+=FIXAMT; Clamp(&me->dx,FIXAMT*10); Clamp(&me->dy,FIXAMT*10); } me->anim++; b=15-SpellLevel(SPL_PLAGUE); if(me->anim>=b) { me->anim=0; FireBullet(me->x,me->y,(byte)Random(256),BLT_WITCHGAS); } ExplodeParticles(PART_YELLOW,me->x,me->y,me->z,1); break; case BLT_WITCHGAS: if(me->timer>=10) { me->anim++; if(me->anim>5*2) { me->anim=3*2; HitBadguys(me,map,world); } Dampen(&me->dx,FIXAMT/2); Dampen(&me->dy,FIXAMT/2); } else if(me->timer<6) { if(me->anim>0) me->anim--; } break; case BLT_WITCHICE: if(!GetGuyPos(me->target,&mapx,&mapy)) me->target=65535; else { if(me->x>mapx) me->dx-=FIXAMT/2; else me->dx+=FIXAMT/2; if(me->y>mapy) me->dy-=FIXAMT/2; else me->dy+=FIXAMT/2; Clamp(&me->dx,FIXAMT*14); Clamp(&me->dy,FIXAMT*14); b=me->facing; BulletFaceGuy2(me,GetGuy(me->target)); } me->anim=1-me->anim; if(me->anim) ExplodeParticles2(PART_SNOW2,me->x,me->y,me->z,1,1); HitBadguys(me,map,world); break; case BLT_WITCHSHOCK: me->x=goodguy->x; me->y=goodguy->y; me->anim++; if(me->anim>12-SpellLevel(SPL_SHOCK)) { me->anim=0; w=LockOnEvil(me->x>>FIXSHIFT,me->y>>FIXSHIFT); if(w!=65535) { bulletHittingType=BLT_WITCHSHOCK; GetGuy(w)->GetShot(0,0,1+(SpellLevel(SPL_SHOCK)>4),map,world); LightningBolt(goodguy->x,goodguy->y-FIXAMT*20,GetGuy(w)->x, GetGuy(w)->y-FIXAMT*10-GetGuy(w)->z); MakeSound(SND_ZAP,GetGuy(w)->x,GetGuy(w)->y,SND_CUTOFF,1000); } } // make sizzle around player constantly LightningBolt( goodguy->x-FIXAMT*32+Random(FIXAMT*64), goodguy->y-FIXAMT*52+Random(FIXAMT*64), goodguy->x-FIXAMT*32+Random(FIXAMT*64), goodguy->y-FIXAMT*52+Random(FIXAMT*64)); break; case BLT_WITCHSPEED: me->x=goodguy->x; me->y=goodguy->y; Burn(me->x,me->y,Random(FIXAMT*40)); if(player.speed<1) { player.speed=10; PowerupSpell(SPL_SPEED,SpellLevel(SPL_SPEED)+1); } break; case BLT_WITCHKABOOM: if(me->timer==59) { // one huge explosion FireBullet(me->x,me->y,0,BLT_GOODBOOM2); } b2=SpellLevel(SPL_KABOOM)*4; if(SpellLevel(SPL_KABOOM)>=4) b2+=(SpellLevel(SPL_KABOOM)-3)*4; b4=SpellLevel(SPL_KABOOM)*2; if(b2>b4) b3=b4; else b3=b2; if(me->timer==45 && b2>0) { // ring of lesser ones for(w=0;w<b3;w++) { b=256*w/b3; FireBullet(me->x+Cosine(b)*80,me->y+Sine(b)*80,0,BLT_GOODBOOM); } } b2-=b3; if(b2>b4) b3=b4; else b3=b2; if(me->timer==30 && b2>0) { // ring of lesser ones for(w=0;w<b3;w++) { b=256*w/b3; FireBullet(me->x+Cosine(b)*160,me->y+Sine(b)*160,0,BLT_GOODBOOM); } } b2-=b3; if(b2>b4) b3=b4; else b3=b2; if(me->timer==15 && b2>0) { // ring of lesser ones for(w=0;w<b3;w++) { b=256*w/b3; FireBullet(me->x+Cosine(b)*240,me->y+Sine(b)*240,0,BLT_GOODBOOM); } } b2-=b3; b3=b2; if(me->timer==1 && b2>0) { // ring of lesser ones for(w=0;w<b3;w++) { b=256*w/b3; FireBullet(me->x+Cosine(b)*320,me->y+Sine(b)*320,0,BLT_GOODBOOM); } } break; case BLT_WITCHBUZZSAW: me->facing+=SpellLevel(SPL_BUZZSAW)+2; if(me->facing<3) me->target=65535; me->x=goodguy->x+Cosine(me->facing)*48; me->y=goodguy->y+Sine(me->facing)*48; if(!opt.cheats[CH_FROGWPN]) MakeCircleParticle(me->x,me->y,me->z,8); HitBadguys(me,map,world); break; case BLT_WITCHBLAST: if(player.fireFlags&FF_GUIDED) { if(bulControl&CONTROL_UP) me->dy-=FIXAMT; if(bulControl&CONTROL_DN) me->dy+=FIXAMT; if(bulControl&CONTROL_LF) me->dx-=FIXAMT; if(bulControl&CONTROL_RT) me->dx+=FIXAMT; Clamp(&me->dx,FIXAMT*16); Clamp(&me->dy,FIXAMT*16); } if(player.fireFlags&FF_HOMING) { if(!GetGuyPos(me->target,&mapx,&mapy)) me->target=65535; else { if(me->x>mapx) me->dx-=FIXAMT; else me->dx+=FIXAMT; if(me->y>mapy) me->dy-=FIXAMT; else me->dy+=FIXAMT; Clamp(&me->dx,FIXAMT*14); Clamp(&me->dy,FIXAMT*14); } } if(!opt.cheats[CH_FROGWPN]) { if(player.monsType==MONS_PLYRSUMMON) { b=8; map->BrightTorch((me->x/TILE_WIDTH)>>FIXSHIFT, (me->y/TILE_HEIGHT)>>FIXSHIFT,2,4); } else { if(!opt.cheats[CH_HEAVYHIT]) b=SpellLevel(SPL_BLAST)*2+4; else b=SpellLevel(SPL_BLAST)*6+4; map->BrightTorch((me->x/TILE_WIDTH)>>FIXSHIFT, (me->y/TILE_HEIGHT)>>FIXSHIFT,SpellLevel(SPL_BLAST),4); } MakeCircleParticle2(me->x,me->y,me->z,b/2); MakeCircleParticle2(me->x+Cosine(me->facing)*b,me->y+Sine(me->facing)*b,me->z,b/2); MakeCircleParticle2(me->x+Cosine((me->facing+85)&255)*b,me->y+Sine((me->facing+85)&255)*b,me->z,b/2); MakeCircleParticle2(me->x+Cosine((me->facing+85*2)&255)*b,me->y+Sine((me->facing+85*2)&255)*b,me->z,b/2); } me->facing+=8; HitBadguys(me,map,world); break; case BLT_DEVILDOLL: if(player.fireFlags&FF_GUIDED) { if(bulControl&CONTROL_UP) me->dy-=FIXAMT; if(bulControl&CONTROL_DN) me->dy+=FIXAMT; if(bulControl&CONTROL_LF) me->dx-=FIXAMT; if(bulControl&CONTROL_RT) me->dx+=FIXAMT; Clamp(&me->dx,FIXAMT*16); Clamp(&me->dy,FIXAMT*16); } if(player.fireFlags&FF_HOMING) { if(!GetGuyPos(me->target,&mapx,&mapy)) me->target=65535; else { if(me->x>mapx) me->dx-=FIXAMT; else me->dx+=FIXAMT; if(me->y>mapy) me->dy-=FIXAMT; else me->dy+=FIXAMT; Clamp(&me->dx,FIXAMT*14); Clamp(&me->dy,FIXAMT*14); } } HitBadguys(me,map,world); break; case BLT_LOONYBALL: if(me->target==65535) { HitBadguys(me,map,world); Dampen(&me->dx,FIXAMT/16); Dampen(&me->dy,FIXAMT/16); Clamp(&me->dx,FIXAMT*16); Clamp(&me->dy,FIXAMT*16); if(me->anim<100) me->anim++; if(opt.cheats[CH_BEND] && ballSteerClock) { ballSteerClock--; b=bulControl; if(b&CONTROL_LF) me->dx-=FIXAMT/2; if(b&CONTROL_RT) me->dx+=FIXAMT/2; } } else { me->anim=0; if(!GetGuyPos(me->target,&mapx,&mapy)) { me->target=65535; } else { me->x=mapx; me->y=mapy+FIXAMT*16; me->z=FIXAMT*20+GetGuy(me->target)->z; me->dz=0; } } if(opt.cheats[CH_KICKCAT] && Random(600)==0) { MakeSound(SND_MEOW,me->x,me->y,SND_CUTOFF,500); } if(ballSoundClock) ballSoundClock--; break; case BLT_BOWLINGBALL: HitBadguys(me,map,world); if(me->y<FIXAMT*TILE_HEIGHT*3) { // went into the ball return deal GutterBall(); me->type=0; } b=bulControl; if(opt.cheats[CH_BEND]) { if(b&CONTROL_LF) me->dx-=FIXAMT/2; if(b&CONTROL_RT) me->dx+=FIXAMT/2; if(b&CONTROL_UP) me->dy-=FIXAMT/2; if(b&CONTROL_DN) me->dy+=FIXAMT/2; Clamp(&me->dx,FIXAMT*12); Clamp(&me->dy,FIXAMT*12); } else { if(b&CONTROL_LF) me->dx-=FIXAMT/8; if(b&CONTROL_RT) me->dx+=FIXAMT/8; } break; case BLT_ENERGY: me->anim=1-me->anim; // flip-flop animation HitBadguys(me,map,world); break; case BLT_BIGSHOT: me->anim=1-me->anim; // flip-flop animation me->facing+=16; // spin HitBadguys(me,map,world); break; case BLT_BALLLIGHTNING: if(player.fireFlags&FF_GUIDED) { if(bulControl&CONTROL_UP) me->dy-=FIXAMT; if(bulControl&CONTROL_DN) me->dy+=FIXAMT; if(bulControl&CONTROL_LF) me->dx-=FIXAMT; if(bulControl&CONTROL_RT) me->dx+=FIXAMT; Clamp(&me->dx,FIXAMT*16); Clamp(&me->dy,FIXAMT*16); } if(player.fireFlags&FF_HOMING) { if(!GetGuyPos(me->target,&mapx,&mapy)) me->target=65535; else { if(me->x>mapx) me->dx-=FIXAMT; else me->dx+=FIXAMT; if(me->y>mapy) me->dy-=FIXAMT; else me->dy+=FIXAMT; Clamp(&me->dx,FIXAMT*14); Clamp(&me->dy,FIXAMT*14); } } if(!opt.cheats[CH_FROGWPN]) { if(!opt.cheats[CH_HEAVYHIT]) MakeCircleParticle(me->x,me->y,me->z,player.firePower*2+4); else MakeCircleParticle(me->x,me->y,me->z,player.firePower*2+player.fireRate*2+player.fireRange*2+4); } HitBadguys(me,map,world); map->BrightTorch((me->x/TILE_WIDTH)>>FIXSHIFT, (me->y/TILE_HEIGHT)>>FIXSHIFT,player.firePower,4); break; case BLT_PSDSHOT: if(player.fireFlags&FF_GUIDED) { if(bulControl&CONTROL_UP) me->dy-=FIXAMT; if(bulControl&CONTROL_DN) me->dy+=FIXAMT; if(bulControl&CONTROL_LF) me->dx-=FIXAMT; if(bulControl&CONTROL_RT) me->dx+=FIXAMT; Clamp(&me->dx,FIXAMT*16); Clamp(&me->dy,FIXAMT*16); } if(player.fireFlags&FF_HOMING) { if(!GetGuyPos(me->target,&mapx,&mapy)) me->target=65535; else { if(me->x>mapx) me->dx-=FIXAMT; else me->dx+=FIXAMT; if(me->y>mapy) me->dy-=FIXAMT; else me->dy+=FIXAMT; Clamp(&me->dx,FIXAMT*14); Clamp(&me->dy,FIXAMT*14); } } if(!opt.cheats[CH_FROGWPN]) { if(!opt.cheats[CH_HEAVYHIT]) MakeCircleParticle(me->x,me->y,me->z,4+player.firePower/2); else MakeCircleParticle(me->x,me->y,me->z,6+player.fireRate*2+player.fireRange*2); } HitBadguys(me,map,world); break; case BLT_FLAMEWALL: if(me->timer>6) me->anim=(me->timer-6); else me->anim=(6-me->timer); if(me->anim>3) HitBadguys(me,map,world); break; case BLT_FLAMESHOT: if(me->anim>1) me->anim--; else me->anim=1-me->anim; HitBadguys(me,map,world); break; case BLT_EARTHSPIKE: case BLT_EARTHSPIKE2: if(me->timer>22 || me->timer<10) { me->anim++; if(me->anim==15) me->type=BLT_NONE; } if(me->anim==4) { FireBullet(me->x+Cosine(me->facing)*TILE_WIDTH,me->y+Sine(me->facing)*TILE_HEIGHT, ((me->facing+(256-16))+(byte)Random(33))&255,BLT_EARTHSPIKE); } if(me->anim>4 && me->anim<10) HitBadguys(me,map,world); break; case BLT_GASBLAST: if(me->timer>=10 && me->timer<=50) { me->anim++; if(me->anim>5) me->anim=3; Dampen(&me->dx,FIXAMT/16); Dampen(&me->dy,FIXAMT/16); HitBadguys(me,map,world); } else if(me->timer<6) { if(me->anim>0) me->anim--; } break; case BLT_MEGABOOM: me->anim++; if(me->anim<2) HitBadguys(me,map,world); break; case BLT_ITEM: HitBadguys(me,map,world); break; case BLT_WHOOPEE: if(me->timer>=10 && me->timer<=50) { me->anim++; if(me->anim>5*2) { me->anim=3*2; HitBadguys(me,map,world); } Dampen(&me->dx,FIXAMT); Dampen(&me->dy,FIXAMT); } else if(me->timer<6) { if(me->anim>0) me->anim--; } break; case BLT_WHOOPEE2: if(me->timer>=10 && me->timer<=110) { me->anim++; if(me->anim>5*2) { me->anim=3*2; HitBadguys(me,map,world); } Dampen(&me->dx,FIXAMT/2); Dampen(&me->dy,FIXAMT/2); } else if(me->timer<6) { if(me->anim>0) me->anim--; } break; case BLT_WHOOPEE3: if(me->timer>=10 && me->timer<=170) { me->anim++; if(me->anim>5*2) { me->anim=3*2; HitBadguys(me,map,world); } if(me->anim==4*2) // trigger twice as often HitBadguys(me,map,world); Dampen(&me->dx,FIXAMT/2); Dampen(&me->dy,FIXAMT/2); } else if(me->timer<6) { if(me->anim>0) me->anim--; } break; case BLT_SUMGAS: if(me->timer>=10 && me->timer<=(20+player.firePower*20)) { me->anim++; if(me->anim>5*2) me->anim=3*2; if((me->timer%(11-player.firePower))==0) HitBadguys(me,map,world); Dampen(&me->dx,FIXAMT/32); Dampen(&me->dy,FIXAMT/32); } else if(me->timer<6) { if(me->anim>0) me->anim--; } break; case BLT_BATGAS: if(me->timer>=10 && me->timer<=50) { me->anim++; if(me->anim>5*2) me->anim=3*2; if((me->timer&3)==0 || player.batLevel==255) HitBadguys(me,map,world); Dampen(&me->dx,FIXAMT/32); Dampen(&me->dy,FIXAMT/32); } else if(me->timer<6) { if(me->anim>0) me->anim--; } break; case BLT_CACTUS: case BLT_CACTUS2: case BLT_ICESHARD: case BLT_KNIFESHRP: HitBadguys(me,map,world); break; case BLT_BOOMERANG: me->anim++; if(me->anim>15) me->anim=0; if(me->timer<60) { // home in on player BulletFaceGuy(me,goodguy); me->dx+=Cosine(me->facing*32); me->dy+=Sine(me->facing*32); Clamp(&me->dx,FIXAMT*8); Clamp(&me->dy,FIXAMT*8); } HitBadguys(me,map,world); break; case BLT_ICE: case BLT_ICE2: HitBadguys(me,map,world); ExplodeParticles2(PART_SNOW2,me->x,me->y,me->z,1,1); break; case BLT_SUMFROST: HitBadguys(me,map,world); ExplodeParticles2(PART_SNOW2,me->x,me->y,me->z,1,1); break; case BLT_BATSHOT: case BLT_WOLFSHOT: HitBadguys(me,map,world); break; case BLT_BOMB: me->anim=me->timer/10; HitBadguys(me,map,world); break; case BLT_GOODBOOM: case BLT_BADBOOM: me->anim++; if(me->anim<2) HitBadguys(me,map,world); break; case BLT_BOWLBOOM: me->x-=me->dx; me->y-=me->dy; me->anim++; if(me->anim<2) HitBadguys(me,map,world); break; case BLT_GOODBOOM2: case BLT_SUMBOOM: me->anim++; if(me->anim<2) HitBadguys(me,map,world); break; case BLT_MISLSMOKE: me->anim++; break; case BLT_SWAMPGAS: case BLT_SWAMPGAS2: if(me->anim>0) { me->anim++; HitBadguys(me,map,world); return; // don't let the timer reset! } if(me->timer==1) { me->timer=3; switch(map->map[(me->x>>FIXSHIFT)/TILE_WIDTH+ ((me->y>>FIXSHIFT)/TILE_HEIGHT)*map->width].item) { case ITM_GASPIPELR: if(me->type==BLT_SWAMPGAS2) { map->map[(me->x>>FIXSHIFT)/TILE_WIDTH+ ((me->y>>FIXSHIFT)/TILE_HEIGHT)*map->width].item=0; FireBullet(me->x,me->y,0,BLT_GOODBOOM); } if(me->facing==0) me->x+=TILE_WIDTH*FIXAMT; else me->x-=TILE_WIDTH*FIXAMT; break; case ITM_GASPIPEUD: if(me->type==BLT_SWAMPGAS2) { map->map[(me->x>>FIXSHIFT)/TILE_WIDTH+ ((me->y>>FIXSHIFT)/TILE_HEIGHT)*map->width].item=0; FireBullet(me->x,me->y,0,BLT_GOODBOOM); } if(me->facing==2) me->y+=TILE_HEIGHT*FIXAMT; else me->y-=TILE_HEIGHT*FIXAMT; break; case ITM_GASPIPEDR: if(me->type==BLT_SWAMPGAS2) { map->map[(me->x>>FIXSHIFT)/TILE_WIDTH+ ((me->y>>FIXSHIFT)/TILE_HEIGHT)*map->width].item=0; FireBullet(me->x,me->y,0,BLT_GOODBOOM); } if(me->facing==4) { me->y+=TILE_HEIGHT*FIXAMT; me->facing=2; } else { me->x+=TILE_WIDTH*FIXAMT; me->facing=0; } break; case ITM_GASPIPEDL: if(me->type==BLT_SWAMPGAS2) { map->map[(me->x>>FIXSHIFT)/TILE_WIDTH+ ((me->y>>FIXSHIFT)/TILE_HEIGHT)*map->width].item=0; FireBullet(me->x,me->y,0,BLT_GOODBOOM); } if(me->facing==0) { me->y+=TILE_HEIGHT*FIXAMT; me->facing=2; } else { me->x-=TILE_WIDTH*FIXAMT; me->facing=4; } break; case ITM_GASPIPEUR: if(me->type==BLT_SWAMPGAS2) { map->map[(me->x>>FIXSHIFT)/TILE_WIDTH+ ((me->y>>FIXSHIFT)/TILE_HEIGHT)*map->width].item=0; FireBullet(me->x,me->y,0,BLT_GOODBOOM); } if(me->facing==4) { me->y-=TILE_HEIGHT*FIXAMT; me->facing=6; } else { me->x+=TILE_WIDTH*FIXAMT; me->facing=0; } break; case ITM_GASPIPEUL: if(me->type==BLT_SWAMPGAS2) { map->map[(me->x>>FIXSHIFT)/TILE_WIDTH+ ((me->y>>FIXSHIFT)/TILE_HEIGHT)*map->width].item=0; FireBullet(me->x,me->y,0,BLT_GOODBOOM); } if(me->facing==0) { me->y-=TILE_HEIGHT*FIXAMT; me->facing=6; } else { me->x-=TILE_WIDTH*FIXAMT; me->facing=4; } break; case ITM_GASSPARK: if(me->type==BLT_SWAMPGAS2) { map->map[(me->x>>FIXSHIFT)/TILE_WIDTH+ ((me->y>>FIXSHIFT)/TILE_HEIGHT)*map->width].item=0; FireBullet(me->x,me->y,0,BLT_GOODBOOM); } map->map[(me->x>>FIXSHIFT)/TILE_WIDTH+ ((me->y>>FIXSHIFT)/TILE_HEIGHT)*map->width].itemInfo=18; me->type=BLT_NONE; //me->anim=1; //me->timer=7; break; default: me->anim=1; me->timer=7; break; } if(!GasCanEnter(me->facing,(me->x>>FIXSHIFT)/TILE_WIDTH, (me->y>>FIXSHIFT)/TILE_HEIGHT,map)) { // vaporize if you can't go here me->type=BLT_NONE; } else { // if you're going through a pipe, make it steam b=map->map[(me->x>>FIXSHIFT)/TILE_WIDTH+ ((me->y>>FIXSHIFT)/TILE_HEIGHT)*map->width].item; if(b>=ITM_GASPIPELR && b<=ITM_GASPIPEUL) map->map[(me->x>>FIXSHIFT)/TILE_WIDTH+ ((me->y>>FIXSHIFT)/TILE_HEIGHT)*map->width].itemInfo=1; else if(me->type==BLT_SWAMPGAS2) { // make big boom if not going through a pipe FireBullet(me->x,me->y,0,BLT_GOODBOOM2); me->type=BLT_NONE; player.var[240]++; // and point out that you have finished } } } break; case BLT_HOTPANTS: Dampen(&me->dx,FIXAMT); Dampen(&me->dy,FIXAMT); if(me->anim>0) me->anim--; else me->anim=1; if(me->timer<6) me->anim=(6-me->timer)/2; if(me->target>0 && me->timer==16 && player.wpnLevel>0) { for(b=0;b<4;b++) { you=FireBullet(me->x,me->y,(byte)Random(256),BLT_HOTPANTS); if(you) you->target=me->target-1; } } if(me->anim==0) HitBadguys(me,map,world); break; case BLT_THFFIRE: Dampen(&me->dx,FIXAMT/4); Dampen(&me->dy,FIXAMT/4); if(me->anim>0) me->anim--; else me->anim=1; if(me->timer<6) me->anim=(6-me->timer)/2; if(me->target) me->target--; else { HitBadguys(me,map,world); me->target=2; } break; case BLT_SUMFLAME: Dampen(&me->dx,FIXAMT/8); Dampen(&me->dy,FIXAMT/8); if(me->anim>0) me->anim--; else me->anim=1; if(me->timer<6) me->anim=(6-me->timer)/2; if(me->anim==0) HitBadguys(me,map,world); break; case BLT_ORBGRENADE: me->anim++; break; case BLT_MISSILE: BulletFaceGuy2(me,goodguy); me->dx+=Cosine(me->facing)*2; me->dy+=Sine(me->facing)*2; Dampen(&me->dx,FIXAMT/2); Dampen(&me->dy,FIXAMT/2); Clamp(&me->dx,FIXAMT*8); Clamp(&me->dy,FIXAMT*8); HitBadguys(me,map,world); me->anim=1-me->anim; if(me->anim) FireBullet(me->x,me->y-FIXAMT*20,0,BLT_MISLSMOKE); break; case BLT_WIND: BulletFaceGuy2(me,goodguy); me->dx+=Cosine(me->facing)*2; me->dy+=Sine(me->facing)*2; Dampen(&me->dx,FIXAMT/2); Dampen(&me->dy,FIXAMT/2); Clamp(&me->dx,FIXAMT*6); Clamp(&me->dy,FIXAMT*6); HitBadguys(me,map,world); FireBullet(me->x,me->y-FIXAMT*20,0,BLT_MISLSMOKE); break; case BLT_LIGHTNING: w=LockOnEvil(me->x>>FIXSHIFT,me->y>>FIXSHIFT); if(w!=65535) { bulletHittingType=BLT_LIGHTNING; GetGuy(w)->GetShot(0,0,player.wpnLevel*2+1,map,world); LightningBolt(goodguy->x,goodguy->y-FIXAMT*20,GetGuy(w)->x, GetGuy(w)->y-FIXAMT*10-GetGuy(w)->z); MakeSound(SND_ZAP,GetGuy(w)->x,GetGuy(w)->y,SND_CUTOFF,1000); } else { // make sizzle around player if there was no target LightningBolt( goodguy->x-FIXAMT*32+Random(FIXAMT*64), goodguy->y-FIXAMT*52+Random(FIXAMT*64), goodguy->x-FIXAMT*32+Random(FIXAMT*64), goodguy->y-FIXAMT*52+Random(FIXAMT*64)); } me->type=BLT_NONE; // begone immediately break; case BLT_SLINGPOW: HitBadguys(me,map,world); break; case BLT_WATER: if(me->anim==0) { for(w=0;w<3;w++) { you=FireBullet(me->x-me->dx/2,me->y-me->dy/2,me->facing,BLT_WATER); if(you) { you->x+=-FIXAMT*8+Random(FIXAMT*16); you->y+=-FIXAMT*8+Random(FIXAMT*16); you->z=me->z-me->dz-FIXAMT*4+Random(FIXAMT*8); you->anim=1; } } me->anim=1; } HitBadguys(me,map,world); me->dz-=FIXAMT/2; break; case BLT_FOUNTAIN: FireBullet(me->x,me->y,me->facing,BLT_WATER); break; case BLT_PORTAL: switch(me->target) { case 0: SetNoSaving(1); ShakeScreen(10); // lighting up around the edges if(me->timer==20) { MakeNormalSound2(SND_ZOMBIESDEAD); MakeNormalSound2(SND_GRATE); me->timer=30; me->facing++; if(me->facing==12) { me->target=1; } } break; case 1: SetNoSaving(1); ShakeScreen(10); // shooting into the center if(me->timer==20) { MakeNormalSound2(SND_GRATE); me->timer=30; me->facing++; if(me->facing==24) { me->target=2; player.var[VAR_PORTALOPEN]=1; PlayerSetVar(VAR_QUESTDONE+QUEST_BUSTS,1); } } break; case 2: SetNoSaving(0); // removing the zappers if(me->timer==20) { me->timer=25; me->facing++; if(me->facing==36) { me->type=0; } } break; } if(me->anim==0) { if(me->facing<12) { for(w=0;w<=me->facing;w++) { BustLightning(bustOrder[w],bustOrder[w+1],me->facing*4,map); } } else { if(me->target<2) { // stop doing the circle lightning when the portal is forming for(w=0;w<=11;w++) { BustLightning(bustOrder[w],bustOrder[w+1],48,map); } } if(me->facing<24) { for(w=0;w<=me->facing-12;w++) { BustLightning(bustOrder[w],32,48,map); } } else { for(w=me->facing-24;w<=11;w++) { BustLightning(bustOrder[w],32,48,map); } } } } me->anim++; if(me->anim==2) me->anim=0; break; case BLT_EVILFACE: me->anim+=(byte)Random(3); if(me->anim>=6*16) me->anim=6*16-1; me->dx+=-FIXAMT/16+Random(FIXAMT/8); me->dy-=Random(FIXAMT/16); break; case BLT_WOLFSHOCK: w=LockOnEvil3(me->x>>FIXSHIFT,me->y>>FIXSHIFT,(player.fireRange+1)*TILE_HEIGHT); if(w!=65535) { bulletHittingType=BLT_WOLFSHOCK; GetGuy(w)->GetShot(0,0,(player.firePower+2)/3,map,world); LightningBolt(goodguy->x,goodguy->y-FIXAMT*20,GetGuy(w)->x, GetGuy(w)->y-FIXAMT*10-GetGuy(w)->z); MakeSound(SND_ZAP,GetGuy(w)->x,GetGuy(w)->y,SND_CUTOFF,1000); } else { // make sizzle around player if there was no target LightningBolt( goodguy->x-FIXAMT*32+Random(FIXAMT*64), goodguy->y-FIXAMT*52+Random(FIXAMT*64), goodguy->x-FIXAMT*32+Random(FIXAMT*64), goodguy->y-FIXAMT*52+Random(FIXAMT*64)); } me->type=BLT_NONE; // begone immediately break; case BLT_SUMSHOCK: w=LockOnEvil3(me->x>>FIXSHIFT,me->y>>FIXSHIFT,(player.firePower+1)*TILE_HEIGHT); if(w!=65535) { bulletHittingType=BLT_SUMSHOCK; GetGuy(w)->GetShot(0,0,1,map,world); LightningBolt(me->x,me->y-FIXAMT*20,GetGuy(w)->x,GetGuy(w)->y-FIXAMT*10-GetGuy(w)->z); MakeSound(SND_ZAP,GetGuy(w)->x,GetGuy(w)->y,SND_CUTOFF,1000); } else { // make sizzle around ghost if there was no target LightningBolt( me->x-FIXAMT*32+Random(FIXAMT*64), me->y-FIXAMT*52+Random(FIXAMT*64), me->x-FIXAMT*32+Random(FIXAMT*64), me->y-FIXAMT*52+Random(FIXAMT*64)); } me->type=BLT_NONE; // begone immediately break; case BLT_CLAW: HitBadguys(me,map,world); break; case BLT_THFKNIFE: if(player.fireFlags&FF_GUIDED) { if(bulControl&CONTROL_UP) me->dy-=FIXAMT; if(bulControl&CONTROL_DN) me->dy+=FIXAMT; if(bulControl&CONTROL_LF) me->dx-=FIXAMT; if(bulControl&CONTROL_RT) me->dx+=FIXAMT; Clamp(&me->dx,FIXAMT*16); Clamp(&me->dy,FIXAMT*16); CalcBulletFacing(me); } if(me->anim) me->anim--; else { me->anim=1; if((player.fireFlags&FF_HOMING) || player.spellXP[ITM_WBOOMERANG-ITM_WBOMB]) { word w; w=LockOnEvilNotYou(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->target); if(GetGuyPos(w,&mapx,&mapy)) { if(me->x>mapx) me->dx-=FIXAMT; else me->dx+=FIXAMT; if(me->y>mapy) me->dy-=FIXAMT; else me->dy+=FIXAMT; Clamp(&me->dx,FIXAMT*14); Clamp(&me->dy,FIXAMT*14); } CalcBulletFacing(me); } else { me->dx=Cosine(me->facing)*12; me->dy=Sine(me->facing)*12; } if(player.spellXP[ITM_WHOTPANTS-ITM_WBOMB] && Random(3)==0) { FireBullet(me->x,me->y,(byte)Random(256),BLT_THFFIRE); } } HitBadguys(me,map,world); break; case BLT_AURA: me->facing+=4; me->x=goodguy->x+Cosine(me->facing)*20; me->y=goodguy->y+Sine(me->facing)*20; break; } } void RenderBullet(bullet_t *me) { sprite_t *curSpr; switch(me->type) { case BLT_SUMHEAL: RenderSumHeal(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,me->bright); break; case BLT_EVILFACE: curSpr=bulletSpr->GetSprite(me->anim/16+137); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,255,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_GHOST); break; case BLT_LOONYBALL: case BLT_BOWLINGBALL: if(opt.cheats[CH_KICKCAT]) RenderItem(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,ITM_CAT,0,me->bright); else RenderItem(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,ITM_MYSORB,0,me->bright); break; case BLT_ENERGY: curSpr=bulletSpr->GetSprite(me->anim+10); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,255,me->bright,curSpr, DISPLAY_DRAWME); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,0,255,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_SHADOW); break; case BLT_BIGSHOT: curSpr=bulletSpr->GetSprite(me->anim+10); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,255,me->bright,curSpr, DISPLAY_DRAWME); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,0,255,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_SHADOW); // extra deals SprDraw((me->x+Cosine(me->facing)*10)>>FIXSHIFT, (me->y+Sine(me->facing)*10)>>FIXSHIFT,me->z>>FIXSHIFT,255,me->bright,curSpr, DISPLAY_DRAWME); SprDraw((me->x+Cosine(me->facing)*10)>>FIXSHIFT, (me->y+Sine(me->facing)*10)>>FIXSHIFT,0,255,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_SHADOW); SprDraw((me->x+Cosine(me->facing+86)*10)>>FIXSHIFT, (me->y+Sine(me->facing+86)*10)>>FIXSHIFT,me->z>>FIXSHIFT,255,me->bright,curSpr, DISPLAY_DRAWME); SprDraw((me->x+Cosine(me->facing+86)*10)>>FIXSHIFT, (me->y+Sine(me->facing+86)*10)>>FIXSHIFT,0,255,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_SHADOW); SprDraw((me->x+Cosine(me->facing+172)*10)>>FIXSHIFT, (me->y+Sine(me->facing+172)*10)>>FIXSHIFT,me->z>>FIXSHIFT,255,me->bright,curSpr, DISPLAY_DRAWME); SprDraw((me->x+Cosine(me->facing+172)*10)>>FIXSHIFT, (me->y+Sine(me->facing+172)*10)>>FIXSHIFT,0,255,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_SHADOW); break; case BLT_BALLLIGHTNING: case BLT_PSDSHOT: case BLT_WITCHBLAST: case BLT_WITCHBUZZSAW: if(opt.cheats[CH_FROGWPN]) { RenderItem(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,ITM_FROGDOLL,0,me->bright); } break; case BLT_DEVILDOLL: RenderItem(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,ITM_BATDOLL+me->anim,0,me->bright); break; case BLT_FLAMEWALL: curSpr=bulletSpr->GetSprite(me->anim/2); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,255,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_GLOW); break; case BLT_FLAMESHOT: curSpr=bulletSpr->GetSprite(me->anim); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,255,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_GLOW); break; case BLT_EARTHSPIKE: case BLT_EARTHSPIKE2: curSpr=bulletSpr->GetSprite(19-me->anim/2); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,255,me->bright,curSpr, DISPLAY_DRAWME); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,0,255,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_SHADOW); break; case BLT_GASBLAST: curSpr=bulletSpr->GetSprite(9-me->anim); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,255,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_GLOW); break; case BLT_MEGABOOM: case BLT_GOODBOOM2: case BLT_SUMBOOM: curSpr=bulletSpr->GetSprite(20+me->anim); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,255,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_GLOW); break; case BLT_ITEM: if(me->timer<30 && (me->timer&1)) return; if(opt.cheats[CH_FROGWPN]) { RenderItem(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,ITM_FROGDOLL,0,me->bright); } else RenderItem(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,me->anim,0,me->bright); break; case BLT_WHOOPEE: case BLT_WHOOPEE2: case BLT_WHOOPEE3: case BLT_SUMGAS: case BLT_BATGAS: curSpr=bulletSpr->GetSprite(164-(me->anim/2)); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,255,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_GLOW); break; case BLT_WITCHGAS: curSpr=bulletSpr->GetSprite(164-(me->anim/2)); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,255,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_GLOW); break; case BLT_CACTUS: curSpr=bulletSpr->GetSprite((me->facing/16)+30); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,255,me->bright,curSpr, DISPLAY_DRAWME); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,0,255,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_SHADOW); break; case BLT_BOOMERANG: curSpr=bulletSpr->GetSprite(me->anim+46); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,255,me->bright,curSpr, DISPLAY_DRAWME); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,0,255,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_SHADOW); break; case BLT_ICE: case BLT_ICE2: case BLT_SUMFROST: case BLT_WITCHICE: curSpr=bulletSpr->GetSprite((me->facing/16)+62); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,255,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_GLOW); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,0,255,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_SHADOW); break; case BLT_BATSHOT: curSpr=bulletSpr->GetSprite((me->facing/16)+62); OffSprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,0,4,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_OFFCOLOR); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,0,255,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_SHADOW); break; case BLT_WOLFSHOT: curSpr=bulletSpr->GetSprite((me->facing/16)+62); OffSprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,0,6,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_OFFCOLOR); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,0,255,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_SHADOW); break; case BLT_BOMB: curSpr=bulletSpr->GetSprite(95-me->anim); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,255,me->bright,curSpr, DISPLAY_DRAWME); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,0,255,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_SHADOW); break; case BLT_GOODBOOM: case BLT_BADBOOM: curSpr=bulletSpr->GetSprite(78+me->anim); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,255,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_GLOW); break; case BLT_BOWLBOOM: break; case BLT_SWAMPGAS: case BLT_SWAMPGAS2: case BLT_MISLSMOKE: if(me->anim>0) { curSpr=bulletSpr->GetSprite(85+me->anim/2); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,255,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_GLOW); } // else don't draw it at all break; case BLT_HOTPANTS: case BLT_SUMFLAME: case BLT_THFFIRE: curSpr=bulletSpr->GetSprite(me->anim); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,255,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_GLOW); break; case BLT_ORBGRENADE: RenderItem(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,ITM_MYSORB,0,me->bright); break; case BLT_MISSILE: curSpr=bulletSpr->GetSprite(me->facing/16+96); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,255,me->bright,curSpr, DISPLAY_DRAWME); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,0,255,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_SHADOW); break; case BLT_SLINGPOW: case BLT_WIND: // no image break; case BLT_ICESHARD: curSpr=bulletSpr->GetSprite((me->facing/16)+30); OffSprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,5,0,me->bright+6,curSpr, DISPLAY_DRAWME|DISPLAY_OFFCOLOR); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,0,255,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_SHADOW); break; case BLT_KNIFESHRP: curSpr=bulletSpr->GetSprite((me->facing/16)+30); OffSprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,5,0,me->bright+14,curSpr, DISPLAY_DRAWME|DISPLAY_OFFCOLOR); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,0,255,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_SHADOW); break; case BLT_WATER: curSpr=bulletSpr->GetSprite(136); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,255,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_GLOW); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,0,255,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_SHADOW); break; case BLT_CLAW: case BLT_THFKNIFE: curSpr=bulletSpr->GetSprite((me->facing/16)+143); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,255,me->bright,curSpr, DISPLAY_DRAWME); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,0,255,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_SHADOW); break; case BLT_CACTUS2: curSpr=bulletSpr->GetSprite((me->facing/16)+143); OffSprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,0,5,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_OFFCOLOR); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,0,255,me->bright,curSpr, DISPLAY_DRAWME|DISPLAY_SHADOW); break; case BLT_AURA: curSpr=bulletSpr->GetSprite((me->facing/16)+143); SprDraw(me->x>>FIXSHIFT,me->y>>FIXSHIFT,me->z>>FIXSHIFT,255,me->bright-8,curSpr, DISPLAY_DRAWME|DISPLAY_GLOW); break; } } void UpdateBullets(Map *map,world_t *world) { int i; static byte updFlip=0,thornFlip=0; updFlip++; if(updFlip==4) { updFlip=0; thornFlip++; if(opt.cheats[CH_THORNS] && thornFlip==2) { thornFlip=0; FireBullet(goodguy->x,goodguy->y,0,BLT_AURA); FireBullet(goodguy->x,goodguy->y,128,BLT_AURA); } } if(opt.cheats[CH_GUIDED] || player.worldNum==WORLD_BOWLING || player.worldNum==WORLD_LOONYBALL) bulControl=GetControls(); for(i=0;i<MAX_BULLETS;i++) if(bullet[i].type) { if(opt.cheats[CH_SLOMO] && !GoodBullet(bullet[i].type) && (updFlip&1)) { // don't update } else { if(GoodBullet(bullet[i].type)) UpdateBullet(&bullet[i],map,world); else { if(player.difficulty!=DIFF_BEGINNER || updFlip!=0) UpdateBullet(&bullet[i],map,world); if(player.difficulty==DIFF_LOONY && updFlip==0) UpdateBullet(&bullet[i],map,world); } } // vintage = double speed if(opt.cheats[CH_VINTAGE] && bullet[i].type) UpdateBullet(&bullet[i],map,world); // terror = double speed for ENEMY bullets if((player.cheatsOn&PC_TERROR) && bullet[i].type && !GoodBullet(bullet[i].type)) UpdateBullet(&bullet[i],map,world); // quick = double speed for FRIENDLY if((opt.cheats[CH_QUICK]) && bullet[i].type && GoodBullet(bullet[i].type)) UpdateBullet(&bullet[i],map,world); } } void RenderBullets(void) { int i; for(i=0;i<MAX_BULLETS;i++) if(bullet[i].type) RenderBullet(&bullet[i]); } void FireMe(bullet_t *me,int x,int y,byte facing,byte type) { int i; me->type=type; me->x=x; me->y=y; me->facing=facing; me->bright=0; me->dx=0; me->dy=0; me->dz=0; switch(me->type) { case BLT_SUMHEAL: me->target=65535; me->z=FIXAMT*20; me->dx=Cosine(me->facing)*6; me->dy=Sine(me->facing)*6; me->timer=120; me->anim=0; break; case BLT_WITCHPLAGUE: me->target=LockOnEvil(me->x>>FIXSHIFT,me->y>>FIXSHIFT); me->z=FIXAMT*20; me->dx=Cosine(me->facing)*4; me->dy=Sine(me->facing)*4; me->timer=60+SpellLevel(SPL_PLAGUE)*15; me->anim=0; break; case BLT_WITCHGAS: me->anim=0; me->timer=80; me->dx=Cosine(me->facing)*4; me->dy=Sine(me->facing)*4; break; case BLT_WITCHICE: me->anim=0; me->dx=Cosine(me->facing)*8; me->dy=Sine(me->facing)*8; me->z=FIXAMT*20; me->target=LockOnEvil(me->x>>FIXSHIFT,me->y>>FIXSHIFT); me->timer=60; break; case BLT_WITCHSHOCK: me->timer=(SpellLevel(SPL_SHOCK)+1)*90; break; case BLT_WITCHSPEED: me->timer=(SpellLevel(SPL_SPEED)+1)*60; break; case BLT_WITCHKABOOM: me->timer=60; break; case BLT_WITCHBLAST: if(player.monsType==MONS_PLYRSUMMON) { me->timer=6*3; } else { if(!opt.cheats[CH_HEAVYHIT]) me->timer=(SpellLevel(SPL_BLAST)+3)*3; else me->timer=6*3; } if(player.fireFlags&FF_GUIDED) me->timer=30*3; me->z=FIXAMT*20; me->dx=Cosine(me->facing)*11; me->dy=Sine(me->facing)*11; me->dz=0; if(player.fireFlags&FF_HOMING) me->target=LockOnEvil(me->x>>FIXSHIFT,me->y>>FIXSHIFT); break; case BLT_DEVILDOLL: me->timer=6*3; if(player.fireFlags&FF_GUIDED) me->timer=30*3; me->z=FIXAMT*20; me->dx=Cosine(me->facing)*11; me->dy=Sine(me->facing)*11; me->dz=-FIXAMT+Random(FIXAMT*6); if(opt.cheats[CH_FROGWPN]) me->anim=2; else me->anim=(byte)Random(8); if(player.fireFlags&FF_HOMING) me->target=LockOnEvil(me->x>>FIXSHIFT,me->y>>FIXSHIFT); break; case BLT_WITCHBUZZSAW: me->timer=SpellLevel(SPL_BUZZSAW)*30+60; me->z=FIXAMT*20; me->dx=0; me->dy=0; me->dz=0; break; case BLT_EVILFACE: me->anim=0; me->dx=-FIXAMT+Random(FIXAMT*2); me->dy=-FIXAMT-Random(FIXAMT*2); me->dz=0; me->z=40*FIXAMT; me->timer=30*10; break; case BLT_LOONYBALL: me->dx=0; me->dy=0; me->dz=0; me->z=50*FIXAMT; me->timer=100; me->target=65535; ballSoundClock=0; break; case BLT_BOWLINGBALL: me->dx=Cosine(me->facing)*8+goodguy->dx; me->dy=Sine(me->facing)*8+goodguy->dy; me->dz=0; me->z=FIXAMT*20; me->timer=30*4; break; case BLT_BALLLIGHTNING: if(!opt.cheats[CH_HEAVYHIT]) me->timer=(player.fireRange+3)*3; else me->timer=6*3; if(player.fireFlags&FF_GUIDED) me->timer=30*3; me->z=FIXAMT*20; // this uses only 8-way facings me->dx=Cosine(me->facing*32)*11; me->dy=Sine(me->facing*32)*11; me->dz=0; me->target=LockOnEvil(me->x>>FIXSHIFT,me->y>>FIXSHIFT); break; case BLT_PSDSHOT: if(!opt.cheats[CH_HEAVYHIT]) me->timer=(player.fireRange+3)*3; else me->timer=6*3; if(player.fireFlags&FF_GUIDED) me->timer=30*3; me->z=FIXAMT*20; me->dx=Cosine(me->facing)*11; me->dy=Sine(me->facing)*11; me->dz=0; if(player.fireFlags&FF_HOMING) me->target=LockOnEvil(me->x>>FIXSHIFT,me->y>>FIXSHIFT); break; case BLT_AURA: me->anim=0; me->timer=32; me->z=0; me->dx=0; me->dy=0; break; case BLT_ENERGY: me->anim=0; me->timer=60; me->z=FIXAMT*20; me->dx=Cosine(me->facing)*8; me->dy=Sine(me->facing)*8; me->dz=0; break; case BLT_BIGSHOT: me->anim=0; me->timer=60; me->z=FIXAMT*20; me->dx=Cosine(me->facing)*6; me->dy=Sine(me->facing)*6; me->dz=0; break; case BLT_FLAMEWALL: me->anim=0; me->timer=12; me->z=0; me->dx=0; me->dy=0; me->dz=0; MakeSound(SND_FIREBURN,me->x,me->y,SND_CUTOFF,600); break; case BLT_FLAMESHOT: me->anim=3; me->timer=60; me->z=0; me->dx=Cosine(me->facing)*7; me->dy=Sine(me->facing)*7; me->dz=0; MakeSound(SND_FIREBURN,me->x,me->y,SND_CUTOFF,600); break; case BLT_EARTHSPIKE: case BLT_EARTHSPIKE2: me->anim=0; me->timer=30; me->z=0; me->dx=0; me->dy=0; me->dz=0; break; case BLT_GASBLAST: me->anim=0; me->timer=60; me->z=FIXAMT*20; me->dx=Cosine(me->facing)*4; me->dy=Sine(me->facing)*4; me->dz=0; break; case BLT_MEGABOOM: MakeSound(SND_BIGBOOM,me->x,me->y,SND_CUTOFF,1200); me->anim=0; me->timer=10; me->z=FIXAMT*20; me->dx=0; me->dy=0; me->dz=0; break; case BLT_ITEM: me->anim=facing; me->timer=30*5; me->z=FIXAMT*20; me->facing=(byte)Random(256); me->bright=(byte)Random(5); me->dx=Cosine(me->facing)*me->bright; me->dy=Sine(me->facing)*me->bright; me->dz=Random(FIXAMT*4); if(me->anim>=ITM_BATDOLL && me->anim<=ITM_WOLFDOLL) { me->bright=(byte)Random(3); me->timer=30*20; me->dx=Cosine(me->facing)*me->bright; me->dy=Sine(me->facing)*me->bright; } me->bright=0; break; case BLT_WHOOPEE: case BLT_WHOOPEE2: case BLT_WHOOPEE3: me->anim=0; me->timer=60*(type-BLT_WHOOPEE+1); me->z=FIXAMT*20; me->dx=Cosine(me->facing)*2; me->dy=Sine(me->facing)*2; me->dz=0; break; case BLT_BATGAS: me->anim=0; me->timer=60; me->z=FIXAMT*20; me->facing=(byte)Random(256); me->dx=Cosine(me->facing)*2; me->dy=Sine(me->facing)*2; me->dz=0; break; case BLT_SUMGAS: me->anim=0; me->timer=30+player.firePower*10; me->z=FIXAMT*20; me->dx=Cosine(me->facing)*4; me->dy=Sine(me->facing)*4; me->dz=0; break; case BLT_CACTUS: case BLT_CACTUS2: me->anim=0; me->timer=30; me->z=FIXAMT*20; me->dx=Cosine(me->facing)*16; me->dy=Sine(me->facing)*16; me->dz=0; break; case BLT_KNIFESHRP: me->target=0; me->anim=0; me->timer=20; me->z=FIXAMT*20; me->dx=Cosine(me->facing)*16; me->dy=Sine(me->facing)*16; me->dz=0; break; case BLT_ICESHARD: me->anim=0; me->timer=30; me->z=FIXAMT*20; me->dx=Cosine(me->facing)*12; me->dy=Sine(me->facing)*12; me->dz=0; break; case BLT_BOOMERANG: me->target=-1; me->anim=0; me->timer=100; me->z=FIXAMT*20; me->dx=Cosine(me->facing)*8; me->dy=Sine(me->facing)*8; me->dz=0; break; case BLT_ICE: case BLT_ICE2: me->target=0; me->anim=0; me->timer=60; me->z=FIXAMT*20; me->dx=Cosine(me->facing)*12; me->dy=Sine(me->facing)*12; me->dz=0; break; case BLT_SUMFROST: me->target=0; me->anim=0; me->timer=30+player.firePower*10; me->z=FIXAMT*20; me->dx=Cosine(me->facing)*10; me->dy=Sine(me->facing)*10; me->dz=0; break; case BLT_BATSHOT: me->anim=0; me->timer=30; me->z=FIXAMT*20; me->dx=Cosine(me->facing)*12; me->dy=Sine(me->facing)*12; me->dz=0; break; case BLT_WOLFSHOT: me->anim=0; me->timer=30; me->z=FIXAMT*20; me->dx=Cosine(me->facing)*16; me->dy=Sine(me->facing)*16; me->dz=0; break; case BLT_BOMB: me->anim=0; me->timer=60; me->z=FIXAMT*30; me->dx=Cosine(me->facing)*6; me->dy=Sine(me->facing)*6; me->dz=0; break; case BLT_GOODBOOM: case BLT_BADBOOM: MakeSound(SND_BOOM,me->x,me->y,SND_CUTOFF,1200); me->anim=0; me->timer=6; me->z=FIXAMT*20; me->dx=0; me->dy=0; me->dz=0; break; case BLT_BOWLBOOM: me->anim=0; me->timer=6; me->z=FIXAMT*20; me->dx=0; me->dy=0; me->dz=0; break; case BLT_GOODBOOM2: case BLT_SUMBOOM: MakeSound(SND_BIGBOOM,me->x,me->y,SND_CUTOFF,1200); me->anim=0; me->timer=9; me->z=FIXAMT*20; me->dx=0; me->dy=0; me->dz=0; break; case BLT_SWAMPGAS: case BLT_SWAMPGAS2: me->anim=0; me->timer=3; me->z=FIXAMT*2; me->dx=0; me->dy=0; me->dz=0; break; case BLT_MISLSMOKE: me->anim=0; me->timer=7; me->z=FIXAMT*2; me->dx=0; me->dy=0; me->dz=0; break; case BLT_HOTPANTS: me->anim=0; me->timer=20+player.wpnLevel*6; me->z=0; me->dx=Cosine(me->facing)*8; me->dy=Sine(me->facing)*8; me->dz=0; me->target=player.wpnLevel; MakeSound(SND_FIREBURN,me->x,me->y,SND_CUTOFF,600); break; case BLT_THFFIRE: me->anim=0; me->timer=30; me->z=0; me->dx=Cosine(me->facing)*4; me->dy=Sine(me->facing)*4; me->dz=0; me->target=0; MakeSound(SND_FIREBURN,me->x,me->y,SND_CUTOFF,600); break; case BLT_SUMFLAME: me->anim=0; me->timer=20+player.firePower*6; me->z=0; me->dx=Cosine(me->facing)*(5+player.firePower/2); me->dy=Sine(me->facing)*(5+player.firePower/2); me->dz=0; MakeSound(SND_FIREBURN,me->x,me->y,SND_CUTOFF,600); break; case BLT_MISSILE: case BLT_WIND: me->anim=0; me->timer=60; me->z=FIXAMT*20; me->dx=0; me->dy=0; me->dz=0; break; case BLT_ORBGRENADE: me->anim=0; me->timer=120; me->z=FIXAMT*60; i=Random(8)+1; me->dx=Cosine(me->facing)*i; me->dy=Sine(me->facing)*i; me->dz=20*FIXAMT; break; case BLT_LIGHTNING: case BLT_WOLFSHOCK: case BLT_SUMSHOCK: me->timer=5; break; case BLT_SLINGPOW: me->timer=3; break; case BLT_FOUNTAIN: MakeSound(SND_WATERSPURT,me->x,me->y,SND_CUTOFF,200); me->timer=15; me->dx=0; me->dy=0; me->dz=0; break; case BLT_WATER: me->z=0; me->timer=60; me->anim=0; switch(me->facing) { case 0: me->dx=FIXAMT*19; me->dy=0; me->dz=FIXAMT*8; break; case 1: me->dx=0; me->dy=FIXAMT*17; me->dz=FIXAMT*6; break; case 2: me->dx=-FIXAMT*19; me->dy=0; me->dz=FIXAMT*8; break; case 3: me->dx=0; me->dy=- FIXAMT*17; me->dz=FIXAMT*6; break; } break; case BLT_PORTAL: me->anim=0; me->timer=30; me->target=0; me->facing=0; break; case BLT_CLAW: me->anim=0; me->timer=30*5; me->z=FIXAMT*20; me->dx=Cosine(me->facing)*12; me->dy=Sine(me->facing)*12; me->dz=0; break; case BLT_THFKNIFE: me->target=65535; me->anim=0; me->timer=30+30*(player.spellXP[ITM_WBOOMERANG-ITM_WBOMB]>0); me->z=FIXAMT*20; if(player.spellXP[ITM_WBOOMERANG-ITM_WBOMB]) { me->dx=Cosine(me->facing)*8; me->dy=Sine(me->facing)*8; } else { me->dx=Cosine(me->facing)*12; me->dy=Sine(me->facing)*12; } me->dz=0; break; } } bullet_t *FireBullet(int x,int y,byte facing,byte type) { int i; for(i=0;i<MAX_BULLETS;i++) if(!bullet[i].type) { FireMe(&bullet[i],x,y,facing,type); return &bullet[i]; break; } return NULL; } void FireBulletZ(int x,int y,int z,byte facing,byte type) { int i; for(i=0;i<MAX_BULLETS;i++) if(!bullet[i].type) { FireMe(&bullet[i],x,y,facing,type); bullet[i].z=z; break; } } // this only fires if there is room in the bullet list PAST a specific point // this is used for the Megabeam to ensure that all the laser bits stay lined up nicely void FireBulletAfter(int x,int y,byte facing,byte type,bullet_t *thisone) { int i,j,start; for(j=0;j<MAX_BULLETS;j++) if(&bullet[j]==thisone) { start=j+1; break; } for(i=start;i<MAX_BULLETS;i++) if(!bullet[i].type) { FireMe(&bullet[i],x,y,facing,type); break; } } void FireExactBullet(int x,int y,int z,int dx,int dy,int dz,byte anim,byte timer,byte facing,byte type) { int i; for(i=0;i<MAX_BULLETS;i++) if(!bullet[i].type) { bullet[i].x=x; bullet[i].y=y; bullet[i].z=z; bullet[i].bright=0; bullet[i].dx=dx; bullet[i].dy=dy; bullet[i].dz=dz; bullet[i].anim=anim; bullet[i].timer=timer; bullet[i].facing=facing; bullet[i].type=type; break; } } void ReflectShot(void) { reflect=1; } void BulletSwap(int sx,int sy,int width,int height,int dx,int dy) { int i; sx*=(TILE_WIDTH*FIXAMT); sy*=(TILE_HEIGHT*FIXAMT); dx*=(TILE_WIDTH*FIXAMT); dy*=(TILE_HEIGHT*FIXAMT); width*=(TILE_WIDTH*FIXAMT); height*=(TILE_HEIGHT*FIXAMT); for(i=0;i<MAX_BULLETS;i++) { if(bullet[i].type) { if(bullet[i].x>=sx && bullet[i].y>=sy && bullet[i].x<=(sx+width) && bullet[i].y<=(sy+height)) { // in target area, swap bullet[i].x+=(-sx+dx); bullet[i].y+=(-sy+dy); } else if(bullet[i].x>=dx && bullet[i].y>=dy && bullet[i].x<=(dx+width) && bullet[i].y<=(dy+height)) { // in other target area, swap bullet[i].x+=(-dx+sx); bullet[i].y+=(-dy+sy); } } } } byte Intersect(int rx,int ry,int rx2,int ry2,int r2x,int r2y,int r2x2,int r2y2) { return (rx<r2x2 && rx2>r2x && ry<r2y2 && ry2>r2y); } void GetKicked(bullet_t *me) { int myx,myy,myx2,myy2; int youx,youy,youx2,youy2; byte c; ScoreGoal(me,curMap); if(me->z>FIXAMT*40) return; // too high to be kicked! if(me->anim<10) return; if(me->z==0 && me->dx==0 && me->dy==0) { if(curWorld.terrain[curMap->map[(me->x/TILE_WIDTH)/FIXAMT+((me->y/TILE_HEIGHT)/FIXAMT)*curMap->width].floor].flags&TF_WATER) { player.oob++; NewMessage("Out of bounds!",60); MakeNormalSound(SND_PENALTYOPEN); me->type=BLT_NONE; FireBullet(((curMap->width/2)*TILE_WIDTH+TILE_WIDTH/2)*FIXAMT, ((curMap->height/2)*TILE_HEIGHT+TILE_HEIGHT/2)*FIXAMT,0,BLT_LOONYBALL); return; } } myx=(me->x>>FIXSHIFT)-8; myx2=(me->x>>FIXSHIFT)+8; myy=(me->y>>FIXSHIFT)-8; myy2=(me->y>>FIXSHIFT)+8; youx=goodguy->rectx+goodguy->x/FIXAMT; youx2=goodguy->rectx2+goodguy->x/FIXAMT; youy=goodguy->recty+goodguy->y/FIXAMT; youy2=goodguy->recty2+goodguy->y/FIXAMT; if(Intersect(myx,myy,myx2,myy2,youx,youy,youx2,youy2)) { c=bulControl; me->dx/=2; me->dy/=2; if(c&CONTROL_B2) { if(opt.cheats[CH_KICKCAT]) MakeSound(SND_CATKICK,me->x,me->y,SND_CUTOFF,300); else MakeSound(SND_BALLKICK,me->x,me->y,SND_CUTOFF,300); me->dx+=goodguy->dx*3/2; me->dy+=goodguy->dy*3/2; me->dz=FIXAMT*10; me->anim=0; ballSteerClock=60; } else { if(ballSoundClock==0) { if(opt.cheats[CH_KICKCAT]) MakeSound(SND_CATDRIBBLE+Random(2),me->x,me->y,SND_CUTOFF,300); else MakeSound(SND_BALLDRIBBLE,me->x,me->y,SND_CUTOFF,300); ballSoundClock=5; } me->dx=goodguy->dx; me->dy=goodguy->dy; } me->x+=me->dx; if(!Bulletable(me,curMap,(me->x/TILE_WIDTH)>>FIXSHIFT,(me->y/TILE_HEIGHT)>>FIXSHIFT)) BulletHitWallX(me,curMap,&curWorld); me->y+=me->dy; if(!Bulletable(me,curMap,(me->x/TILE_WIDTH)>>FIXSHIFT,(me->y/TILE_HEIGHT)>>FIXSHIFT)) BulletHitWallY(me,curMap,&curWorld); } // bounce off other players c=BallHitCheck(me); if(c) { if(ballSoundClock==0) { if(opt.cheats[CH_KICKCAT]) MakeSound(SND_CATDRIBBLE+Random(2),me->x,me->y,SND_CUTOFF,300); else MakeSound(SND_BALLDRIBBLE,me->x,me->y,SND_CUTOFF,300); ballSoundClock=5; } if(c==10) { // couldn't determine an angle me->facing=(byte)Random(256); me->dx/=2; me->dy/=2; me->dx+=Cosine(me->facing)*4; me->dy+=Sine(me->facing)*4; } else { c--; if(c!=2 && c!=6) { me->dx=-me->dx*3/4; } if(c!=0 && c!=4) { me->dy=-me->dy*3/4; } } } } void GetBallCoords(int *x,int *y,int *z) { int i; for(i=0;i<MAX_BULLETS;i++) { if(bullet[i].type==BLT_LOONYBALL) { *x=bullet[i].x; *y=bullet[i].y; *z=bullet[i].z; return; } } } void CatchBall(word id) { int i; for(i=0;i<MAX_BULLETS;i++) { if(bullet[i].type==BLT_LOONYBALL) { bullet[i].dx=0; bullet[i].dy=0; bullet[i].dz=0; bullet[i].target=id; ballSteerClock=0; return; } } } void ThrowBall(void) { int i; for(i=0;i<MAX_BULLETS;i++) { if(bullet[i].type==BLT_LOONYBALL) { if(opt.cheats[CH_KICKCAT]) MakeSound(SND_CATKICK,bullet[i].x,bullet[i].y,SND_CUTOFF,300); else MakeSound(SND_BALLKICK,bullet[i].x,bullet[i].y,SND_CUTOFF,300); bullet[i].dz=FIXAMT*6; bullet[i].dy=FIXAMT*10; bullet[i].dx=-FIXAMT*4+Random(FIXAMT*8); bullet[i].target=65535; ballSteerClock=0; return; } } } bullet_t *FindItemBullet(int x,int y) { int i,best,bestdist,d; best=-1; bestdist=9999999; for(i=0;i<MAX_BULLETS;i++) { if(bullet[i].type==BLT_ITEM) { d=abs(bullet[i].x-x)+abs(bullet[i].y-y); if(best==-1 || d<bestdist) { best=i; bestdist=abs(bullet[i].x-x)+abs(bullet[i].y-y); } } } if(best==-1) return NULL; else return &bullet[best]; }
f20cc8c98b1823a555f98e22ac023806eadc117a
b6300ede7aa80b18db15b1ca52a9f6e9271a9ecf
/CSC3224Game/Game/DemoCode/DemoGameObject.cpp
b9379a4c08de408c3b4488c72faa6fb37fe1dd7d
[]
no_license
AJagger/3224Game
1da1e052bdafed5cb5f06ce024cc3741224eb74b
e50acb7d42be7617ff42d8a7645b86eac4e66264
refs/heads/master
2020-12-30T14:12:20.402056
2017-05-19T10:15:40
2017-05-19T10:15:40
91,285,160
0
0
null
null
null
null
UTF-8
C++
false
false
3,625
cpp
/* CSC3224 Code * Author: Aidan Jagger | 130281034 * Class Description: * This class inherits from the base GameObject class and provides a few extra functions and variables for use in the game demo. * GameEntityType in particular is very useful for determining exactly what type of object it is. */ #include "stdafx.h" #include "DemoGameObject.h" DemoGameObject::DemoGameObject() { //entityType = UNINITIALISED; } // ////Configure the DemoGameObject with default values depending on the GameEntityType assigned to it. //DemoGameObject::DemoGameObject(GameEntityType type, int meshId, int textureId) //{ // if(type == STATIC_OBJECT) // { // ConfigureDefaultStatic(meshId, textureId); // } // else if(type == NPC) // { // ConfigureDefaultNPC(meshId, textureId); // } // else if (type == PLAYER) // { // ConfigureDefaultPlayer(meshId, textureId); // } // else if (type == PROJECTILE) // { // ConfigureDefaultProjectile(meshId, textureId); // } // else if (type == EFFECT) // { // ConfigureDefaultEffect(meshId, textureId); // } //} // //DemoGameObject::~DemoGameObject() //{ //} // //void DemoGameObject::ConfigureDefaultStatic(int meshId, int textureId) //{ // entityType = STATIC_OBJECT; // playerControlled = false; // hostile = false; // AIEnabled = false; // physicsEnabled = false; // collisionsEnabled = true; // staticObject = true; // entityName = "DefaultObject"; // // hasTarget = false; // targetObjectId = -1; // lifeTime = 0; // // position = Vector3(0, 0, 0); // movementVector = Vector2(0, 0); // rotation = 0; // // this->meshId = meshId; // this->textureId = textureId; //} // //void DemoGameObject::ConfigureDefaultNPC(int meshId, int textureId) //{ // entityType = NPC; // playerControlled = false; // hostile = false; // AIEnabled = true; // physicsEnabled = true; // collisionsEnabled = true; // staticObject = false; // entityName = "DefaultObject"; // // hasTarget = false; // targetObjectId = -1; // lifeTime = 0; // // position = Vector3(0, 0, 0); // movementVector = Vector2(0, 0); // rotation = 0; // // this->meshId = meshId; // this->textureId = textureId; //} // //void DemoGameObject::ConfigureDefaultPlayer(int meshId, int textureId) //{ // entityType = PLAYER; // playerControlled = true; // hostile = false; // AIEnabled = false; // physicsEnabled = true; // collisionsEnabled = true; // staticObject = false; // entityName = "DefaultPlayer"; // // hasTarget = false; // targetObjectId = -1; // lifeTime = 0; // // position = Vector3(0, 0, 0); // movementVector = Vector2(0, 0); // rotation = 0; // // this->meshId = meshId; // this->textureId = textureId; //} // //void DemoGameObject::ConfigureDefaultProjectile(int meshId, int textureId) //{ // entityType = PROJECTILE; // playerControlled = false; // hostile = false; // AIEnabled = true; // physicsEnabled = false; // collisionsEnabled = true; // staticObject = false; // entityName = "DefaultObject"; // // hasTarget = false; // targetObjectId = -1; // lifeTime = 0; // // position = Vector3(0, 0, 0); // movementVector = Vector2(0, 0); // rotation = 0; // // this->meshId = meshId; // this->textureId = textureId; //} // //void DemoGameObject::ConfigureDefaultEffect(int meshId, int textureId) //{ // entityType = EFFECT; // playerControlled = false; // hostile = false; // AIEnabled = false; // physicsEnabled = false; // collisionsEnabled = false; // staticObject = false; // entityName = "DefaultEffect"; // // hasTarget = false; // targetObjectId = -1; // lifeTime = 0; // // position = Vector3(0, 0, 0); // movementVector = Vector2(0, 0); // rotation = 0; // // this->meshId = meshId; // this->textureId = textureId; //}
389f3a9bec09c85cd9554acdeba0f1fa9f10f584
2a40ec9a2d67012945756281fe8d009ca7174033
/ConDisplay.cpp
24f6c3c4a9c654e7603a24292aef2bd08ff7b235
[]
no_license
AAAHQZ/AAA_Editor
c54be378b2a010474593da231b7c269d33796ef8
5016e1b2ec3b5d844b0b6481b06801ac8e800bb3
refs/heads/master
2020-03-15T11:10:50.830278
2018-05-04T09:46:10
2018-05-04T09:46:10
132,115,243
2
0
null
null
null
null
UTF-8
C++
false
false
5,944
cpp
#include "ConDisplay.h" ConDisplay::ConDisplay() { //ctor sw = false; hOut = GetStdHandle(STD_OUTPUT_HANDLE); GetConsoleScreenBufferInfo(hOut, &bInfo); SetConsoleTitle("EDITORv1.0"); size.X = DEFSIZEX; size.Y = DEFSIZEY; SetConsoleScreenBufferSize(hOut, size); rc = {0, 0, size.X-1,size.Y-1}; SetConsoleWindowInfo(hOut, true, &rc); } ConDisplay::~ConDisplay() { //dtor CloseHandle(hOut); } void ConDisplay::Display() { this->DisplayInterface(); this->DisplayPage(); this->DisplayData(); if(sw == false) this->DisplayCursor(); } void ConDisplay::Display1() { this->DisplayPage(); this->DisplayData(); if(sw == false) this->DisplayCursor(); } //------------------------------------------------------------------- //界面显示 //------------------------------------------------------------------- void ConDisplay::GetpED(EditData *p) { pED = p; } void ConDisplay::GetMsg(eMSG msg) { COORD p; WORD color = FOREGROUND_RED |FOREGROUND_GREEN |FOREGROUND_BLUE | FOREGROUND_INTENSITY ; if(sw == false) { p.X = 1; p.Y = DEFSIZEY - 2; sw = true; SetConsoleCursorPosition(hOut,p); } else { p.X = 1; p.Y = DEFSIZEY - 2; for(;p.X < DEFSIZEX-2;p.X++) { DrawData(p,color,'\0'); } p = pED->GetPos(); sw = false; SetConsoleCursorPosition(hOut,p); } } void ConDisplay::DisplayInterface() { COORD p,d; char ch; WORD color; color = FOREGROUND_RED |FOREGROUND_GREEN |FOREGROUND_BLUE | FOREGROUND_INTENSITY | BACKGROUND_BLUE;// 文本属性 p.X = 0; p.Y = 0; d.X = DEFSIZEX; d.Y = DEFSIZEY-3; DrawBox(p,d,color); DrawFrame(p,d); color = FOREGROUND_RED |FOREGROUND_GREEN |FOREGROUND_BLUE | FOREGROUND_INTENSITY | BACKGROUND_RED | BACKGROUND_BLUE;// 文本属性 p.Y = p.Y + d.Y; d.Y = 3; DrawBox(p,d,color); DrawFrame(p,d); color = FOREGROUND_RED |FOREGROUND_GREEN |FOREGROUND_BLUE | FOREGROUND_INTENSITY ; d.X = d.X - 2; d.Y = 1; p.X++; p.Y++; DrawBox(p,d,color); } void ConDisplay::DisplayPage() { COORD p; int num,n; char ch[3]; WORD color = FOREGROUND_RED |FOREGROUND_GREEN |FOREGROUND_BLUE | FOREGROUND_INTENSITY | BACKGROUND_BLUE; p.X = DEFSIZEX - 10; p.Y = DEFSIZEY- 4; DrawData(p,color,'P'); p.X++; DrawData(p,color,':'); num = pED->GetP(); if(num/100 != 0) { ch[0] = '0'+num%1000; } else { ch[0] = '0'; } if(num/10 != 0) { ch[1] = '0'+num%100; } else { ch[1] = '0'; } if(num/1 != 0) { ch[2] = '0'+num%10; } else { ch[2] = '0'; } for(n=0;n<3;n++) { p.X++; DrawData(p,color,ch[n]); } } void ConDisplay::DisplayData() { char ch; COORD p; p.X = 1; p.Y = 1; WORD color = FOREGROUND_RED |FOREGROUND_GREEN |FOREGROUND_BLUE | FOREGROUND_INTENSITY | BACKGROUND_BLUE; for(int i=0;i<DEFAULTSIZE;i++) { pED->GetElem(i+pED->GetP()*DEFAULTSIZE,ch); DrawData(p,color,ch); p.X++; if(p.X == DEFSIZEX-1) { p.X = 1; p.Y++; } } } void ConDisplay::Test() { COORD p,d; char ch; WORD color = FOREGROUND_RED |FOREGROUND_GREEN |FOREGROUND_BLUE | FOREGROUND_INTENSITY | BACKGROUND_BLUE;// 文本属性 p.X = 0; p.Y = 0; d.X = DEFSIZEX; d.Y = DEFSIZEY-3; DrawBox(p,d,color); DrawFrame(p,d); p.Y = p.Y + d.Y; d.Y = 3; color = FOREGROUND_RED |FOREGROUND_GREEN |FOREGROUND_BLUE | FOREGROUND_INTENSITY ;// 文本属性 DrawBox(p,d,color); DrawFrame(p,d); p.X = DEFSIZEX - 10; p.Y = DEFSIZEY- 4; DrawData(p,color,'P'); p.X++; DrawData(p,color,':'); p.X++; DrawData(p,color,'0'+pED->GetP()); p.X = 1; p.Y = 1; color = FOREGROUND_RED |FOREGROUND_GREEN |FOREGROUND_BLUE | FOREGROUND_INTENSITY | BACKGROUND_BLUE; for(int i=0;i<pED->GetLength();i++) { pED->GetElem(i,ch); DrawData(p,color,ch); p.X++; if(p.X == DEFSIZEX-1) { p.X = 1; p.Y++; } } } //------------------------------------------------------------------- //封装函数 //------------------------------------------------------------------- void ConDisplay::DrawBox(COORD prc, COORD drc, WORD color) { for (int i=0;i<drc.Y;i++) { FillConsoleOutputAttribute(hOut, color, drc.X, prc, &written); prc.Y++; } } void ConDisplay::DrawFrame(COORD prc, COORD drc) { char corner = '+'; char xedge = '-'; char yedge = '|'; COORD now = prc; for(int i=1;i < drc.X;i++) { now = prc; now.X = prc.X+i; WriteConsoleOutputCharacter(hOut, &xedge, 1, now, &written); now.Y = prc.Y+drc.Y-1; WriteConsoleOutputCharacter(hOut, &xedge, 1, now, &written); } for(int i=1;i < drc.Y;i++) { now = prc; now.Y = prc.Y+i; WriteConsoleOutputCharacter(hOut, &yedge, 1, now, &written); now.X = prc.X+drc.X-1; WriteConsoleOutputCharacter(hOut, &yedge, 1, now, &written); } now = prc; WriteConsoleOutputCharacter(hOut, &corner, 1, now, &written); now.X = prc.X + drc.X-1; WriteConsoleOutputCharacter(hOut, &corner, 1, now, &written); now.Y = prc.Y + drc.Y-1; WriteConsoleOutputCharacter(hOut, &corner, 1, now, &written); now.X = prc.X; WriteConsoleOutputCharacter(hOut, &corner, 1, now, &written); } void ConDisplay::DrawData(COORD now, WORD color,char dt) { WriteConsoleOutputCharacter(hOut, &dt, 1, now, &written); } void ConDisplay::DisplayResetCursor() { SetConsoleCursorPosition(hOut,{1,1}); } void ConDisplay::DisplayCursor() { SetConsoleCursorPosition(hOut,pED->GetPos()); }
ed45a45d44ab7735d3e69f096663bc22cb7b0f09
d30f9b49ea5d703970c65fb9ac20aa4b59ceaf4c
/src/qml-files.h
bed32207450c1c881d895b7d0e4e57be5d42dc35
[]
no_license
ZPJ8/qml-files
3bbdfdb0a4be75741c739e11e48bf7770fa900ee
324a3b7cfbb2cb928b919b033feabc1186fdae37
refs/heads/master
2020-06-27T07:54:36.421078
2016-03-04T15:01:16
2016-03-04T15:01:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
823
h
#include <QQmlExtensionPlugin> #include <qqml.h> #include "file_info.h" #include "dir.h" #include "file.h" #include "file_system_watcher.h" #include "standard_paths.h" class QmlFilesPlugin : public QQmlExtensionPlugin { Q_OBJECT Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QQmlExtensionInterface") public: void registerTypes(const char *uri) { qmlRegisterType<FileInfo>(uri, 1, 0, "FileInfo"); qmlRegisterType<FileInfoAttached>(); qmlRegisterType<Dir>(uri, 1, 0, "Dir"); qmlRegisterType<DirAttached>(); qmlRegisterType<StandardPaths>(uri, 1, 0, "StandardPaths"); qmlRegisterType<StandardPathsAttached>(); qmlRegisterType<FileSystemWatcher>(uri, 1, 0, "FileSystemWatcher"); qmlRegisterType<wQFile>(uri, 1, 0, "File"); }; };
cc112eda337e3b3d0ae5c1433d84fe944465f332
9c69d2eb7c47ed7bc6fe745b9fa2252a977444d1
/oolua/src/oolua_script.cpp
ea6d85e7f49dc150cf6dd1691e5dec39f694b6f0
[]
no_license
RMariowski/OOLua-Android-Build
44f64494725d83e437cdca325481eeb8b687cf34
a65915b9f26d70e4741b0cd69654ddc18b921cf9
refs/heads/master
2021-09-28T02:02:24.231904
2015-05-20T13:53:25
2015-05-20T13:53:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,065
cpp
/* The MIT License Copyright (c) 2009 - 2014 Liam Devine Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "oolua_script.h" #include "oolua_chunk.h" #include "oolua_open.h" #include "oolua_registration.h" namespace OOLUA { Script::Script() :call(), m_lua(0) { m_lua = luaL_newstate(); luaL_openlibs(m_lua); call.bind_script(m_lua);//bind the lua state to the function caller setup_user_lua_state(m_lua); } Script::~Script() { close_down(); } void Script::gc() { lua_gc(m_lua, LUA_GCCOLLECT, 0); } void Script::close_down() { if(m_lua) { lua_gc(m_lua, LUA_GCCOLLECT, 0); lua_close(m_lua); m_lua = 0; } } bool Script::load_chunk(std::string const& chunk) { return OOLUA::load_chunk(m_lua, chunk); } bool Script::run_chunk(std::string const& chunk) { return OOLUA::run_chunk(m_lua, chunk); } bool Script::run_file(std::string const & filename) { return OOLUA::run_file(m_lua, filename); } bool Script::load_file(std::string const & filename) { return OOLUA::load_file(m_lua, filename); } } // namespace OOLUA
026b470f12d103216b124fbebe40c9e4fd68e44e
bc221e80b1bffa8c29e790077f0c282f676a466c
/example/cppcon_2014/matrix/ring.hpp
b4202ee766e4315c14f03bb24e40f6e89cf21fc9
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
huis/hana
6fec4c07f34a258035c079d39eec80bddc105fbf
ac04435b60dc1d0d833e2022f9363cd4c7b433b9
refs/heads/master
2021-01-23T00:44:51.874423
2015-05-31T18:11:32
2015-05-31T22:57:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,100
hpp
/* @copyright Louis Dionne 2015 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_HANA_EXAMPLE_CPPCON_2014_MATRIX_RING_HPP #define BOOST_HANA_EXAMPLE_CPPCON_2014_MATRIX_RING_HPP #include "matrix.hpp" #include <boost/hana/detail/std/integral_constant.hpp> #include <boost/hana/foldable.hpp> #include <boost/hana/integral_constant.hpp> #include <boost/hana/sequence.hpp> #include <boost/hana/range.hpp> #include <boost/hana/ring.hpp> #include <boost/hana/tuple.hpp> #include <utility> namespace boost { namespace hana { template <unsigned R1, unsigned C1, unsigned R2, unsigned C2> struct mult_impl<cppcon::Matrix<R1, C1>, cppcon::Matrix<R2, C2>> { template <typename M1, typename M2> static constexpr decltype(auto) apply(M1&& m1, M2&& m2) { static_assert(C1 == R2, "wrong dimensions for matrix multiplication"); auto cols = cppcon::columns(std::forward<M2>(m2)); return unpack( transform(cppcon::rows(std::forward<M1>(m1)), [&](auto&& row) -> decltype(auto) { return zip.with(cppcon::detail::tuple_scalar_product, repeat<Tuple>(uint<R1>, std::forward<decltype(row)>(row)), cols ); } ), cppcon::matrix ); } }; template <unsigned R, unsigned C> struct one_impl<cppcon::Matrix<R, C>> { static constexpr decltype(auto) apply() { return unpack(range_c<unsigned, 0, R>, [](auto ...n) { return unpack(range_c<unsigned, 0, C>, [=](auto ...m) { auto row = [=](auto n) { return cppcon::row(if_(n == m, int_<1>, int_<0>)...); }; return cppcon::matrix(row(n)...); }); }); } }; }} #endif // !BOOST_HANA_EXAMPLE_CPPCON_2014_MATRIX_RING_HPP
ce1f3b0707b8e4df742c979314b772c3bdb2f947
e46bd22112c15d9558ad9531deef183849636d62
/LeetCode/1536 - Minimum Swaps to Arrange a Binary Grid.cpp
53014c56d2786331da51d7e95dfe332ebb001876
[]
no_license
jariasf/Online-Judges-Solutions
9082b89cc6d572477dbfb89ddd42f81ecdb2859a
81745281bd0099b8d215754022e1818244407721
refs/heads/master
2023-04-29T20:56:32.925487
2023-04-21T04:59:27
2023-04-21T04:59:27
11,259,169
34
43
null
2020-10-01T01:41:21
2013-07-08T16:23:08
C++
UTF-8
C++
false
false
1,156
cpp
/******************************************* ***Problema: Minimum Swaps to Arrange a Binary Grid ***ID: 1536 ***Juez: LeetCode ***Tipo: Suffix Counts + Sorting ***Autor: Jhosimar George Arias Figueroa *******************************************/ class Solution { public: int minSwaps(vector<vector<int>>& grid) { int n = grid.size(), res = 0; vector<int> arr(n); for( int i = 0 ; i < n ; ++i ){ for( int j = n - 1 ; j >= 0 ; --j ){ if( grid[i][j] == 0 ) arr[i]++; else break; } } for( int i = 0, k = n - 1 ; i < n && k >= 1 ; ++i, --k ){ int index = -1; for( int j = i ; j < n ; ++j ){ if( arr[j] >= k ){ index = j; break; } } if( index == -1 ){ res = -1; break; } for( int j = index; j > i ; --j ){ res++; swap(arr[j], arr[j - 1]); } } return res; } };
04d78150df8ac94305431951010dfaa0f4be9fda
6662312cfa6d924b49101109bb829cb435492901
/MenuButton.h
b7065c7397226992aceeb6abbb45d4d602a9a5f2
[]
no_license
carretero4/BaseCode
513861e26db621398b8a6fed9b98d621c6c28ed3
31c6a2cfa813362d2dafc79d3fcb592049e761b3
refs/heads/master
2021-01-14T14:33:32.560581
2016-01-25T22:41:52
2016-01-25T22:41:52
43,768,234
0
0
null
2015-10-06T17:57:05
2015-10-06T17:57:05
null
UTF-8
C++
false
false
705
h
#pragma once #include "GameObject.h" #include "InputHandler.h" #include "TextureManager.h" #include "Vector2D.h" //Clase que crea un game object del tipo boton class MenuButton : public GameObject { public: MenuButton(); MenuButton(const LoaderParams* pParams, void(*callback)()); virtual void load(const LoaderParams* pParams); virtual void draw(); virtual void update(); virtual void clean(); static GameObject * Create() { return new MenuButton(); } void setCallback(void(*callback)()) { m_callback = callback; } int getCallbackID() const { return m_callbackID; } private: enum button_state { MOUSE_OUT = 0, MOUSE_OVER = 1, CLICKED = 2 }; void(*m_callback)(); bool m_bReleased; };
0446682fb3c476ab7b429f2289d77fc73f37652c
f440bd4042ac3dfe77710ad63137b5aa2ed00b8d
/Arguments.h
8123743f3de10dcf38a71372de231899f8cd9737
[ "BSD-3-Clause" ]
permissive
jackburton79/bescreencapture
e04cd191ca17860e937af786699e655ecd5ecd43
5edbce4d7e5c0f4f2e535e3d717eb317c880059e
refs/heads/master
2023-06-01T02:56:44.428938
2023-05-26T10:59:59
2023-05-26T10:59:59
8,073,087
9
6
BSD-3-Clause
2023-01-03T07:37:16
2013-02-07T13:15:43
C++
UTF-8
C++
false
false
777
h
/* * Copyright 2005, Ingo Weinhold, [email protected]. * Distributed under the terms of the MIT License. */ #ifndef ARGUMENTS_H #define ARGUMENTS_H #include <Rect.h> class Arguments { public: Arguments(int defaultArgcNum, const char* const* defaultArgv); ~Arguments(); void Parse(int argc, const char* const* argv); bool RecordNow() const { return fRecordNow; } bool FullScreen() const { return fFullScreen; } bool UsageRequested() const { return fUsageRequested; } void GetShellArguments(int& argc, const char* const*& argv) const; private: void _SetShellArguments(int argc, const char* const* argv); bool fUsageRequested; int fShellArgumentCount; const char** fShellArguments; bool fRecordNow; bool fFullScreen; }; #endif // ARGUMENTS_H
67343e5eafea1384712e4ecee89abce9d8f60781
76aefba9da756337b9974219d570c285bfccfce3
/src/Mbed_Serial_Mouse.cpp
e02c279196f3e5f3840d2bae5de99aa33f52e246
[]
no_license
YukiMOB/ANTAM_LED_FeedBack
4bc2ccd50aabea932f8be04d139dd72c82e0b584
027e5bebc0bb0c54493bcd20b88ebf3ea312a427
refs/heads/master
2020-04-03T01:34:08.519996
2019-03-06T09:48:57
2019-03-06T09:48:57
130,301,375
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
5,450
cpp
#include "sys.h" #include "sub_method.h" HANDLE mbed_mouse; void serial_setup_mouse(); void recive_value(int *, int *, int *, int *); void serial_task_read(); void serial_exit_mouse(); char *buf;//受信した文字を文字列として受信する変数 int hip = 0;//bufに書き込んだ文字数 bool rec = false; double dx, dy; double proofreding_x = 0.024264188; double proofreding_y = 0.027281252; std::ofstream mouse;//マウス移動量をファイルに書き出す変数 DWORD start_time = 0;//データ取得開始時刻(スレッド開始時刻) //DWORD t1; DWORD t1, t2; void serial_setup_mouse() { bool check = false; //シリアルポートを接続(mbed_mouse) mbed_mouse = CreateFile(_T(COM_NUM_MBED_MOUSE), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (mbed_mouse == INVALID_HANDLE_VALUE) { std::cout << "mbed(mouse) PORT COULD NOT OPEN" << std::endl; } else { std::cout << "mbed(mouse) PORT OPEN" << std::endl; } //ブッファーの準備 check = SetupComm(mbed_mouse, 1024, 1024); if (!check) { std::cout << "mbed(mouse) COULD NOT SET UP BUFFER" << std::endl; CloseHandle(mbed_mouse); } else { std::cout << "mbed SET UP OK" << std::endl; } //ブッファの初期化 check = PurgeComm(mbed_mouse, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR); if (!check) { std::cout << "mbed(mouse) COULD NOT BUFFER CLER" << std::endl; CloseHandle(mbed_mouse); } else { std::cout << "mbed(mouse) BUFFER OK" << std::endl; } //シリアル通信のステータスを設定 DCB dcb_mouse; GetCommState(mbed_mouse, &dcb_mouse); dcb_mouse.DCBlength = sizeof(DCB); dcb_mouse.BaudRate = 57600; dcb_mouse.fBinary = TRUE; dcb_mouse.ByteSize = 8; dcb_mouse.fParity = NOPARITY; dcb_mouse.StopBits = ONESTOPBIT; //設定の適用 check = SetCommState(mbed_mouse, &dcb_mouse); if (!check) { std::cout << "mbed(mouse) SetCommState FAILED" << std::endl; CloseHandle(mbed_mouse); } else { std::cout << "mbed(mouse) SetCommOK" << std::endl; } } void serial_task_read() { buf = new char[255]; int x, y; int move_x = 0, move_y = 0; serial_setup_mouse(); while (1) { if (check_mode() == RELEASE_MODE && !rec) { rec = true; mouse = std::ofstream(mouse_filename); mouse << "time[ms]" << "," << "x" << "," << "y" << "," << "arc" << "," << "pos"<< std::endl; //mouse << std::endl; } recive_value(&x, &y, &move_x, &move_y); if (check_flag()) break; } serial_exit_mouse(); } void recive_value(int *x, int *y, int *move_x, int *move_y) { //データの受信 int length = 0; char c; DWORD errors;//エラー情報を格納する変数 COMSTAT comStat;//受信バッファのバイト数を格納する変数 ClearCommError(mbed_mouse, &errors, &comStat);//errosにエラー情報、comStatに受信バッファ情報を格納 length = comStat.cbInQue; // 受信したメッセージ長を取得する mtx.lock(); int angle = angle_target; int position = itos; mtx.unlock(); if (length > 0) { for (int i = 0; i < length; i++) { DWORD numberOfPut;//受信したメッセージ長 ReadFile(mbed_mouse, &c, 1, &numberOfPut, NULL); if (c == ',') { //x軸方向への移動量をintへ変換 *x = atoi(buf); memset(buf, 0, sizeof(buf)); hip = 0; }//改行コードならファイルへ値の書き出し else if (c == '\n') { //y軸方向への移動量をintへ変換 *y = atoi(buf); //ファイルの書き出し時刻 t1 = timeGetTime() - start_time; if (check_mode() == RELEASE_MODE) { //csvファイルへの書き出し *move_x += *x; *move_y += *y; dx = *x * proofreding_x; dy = *y * proofreding_y; //std::cout << "REC:" << (int64)t1 << ":" << *move_x << "," << *move_y << "," << get_angle() << std::endl; std::cout << "REC:" << (int64)t1 << ":" << *move_x << "," << *move_y << "," << angle << "," << position << std::endl; mouse << (int64)t1 << "," << *move_x << "," << *move_y << "," << angle << "," << position << std::endl; } else { //debug //std::cout << (int64)t1 << ":" << *x << "," << *y << std::endl; std::cout << (int64)t1 << ":" << *x << "," << *y << "," << angle << "," << position << std::endl; } memset(buf, 0, sizeof(buf)); hip = 0; }//デフォルトではbufに文字を格納 else { buf[hip] = c; hip++; } } } else { t2 = timeGetTime() - start_time; if ((t2 - t1) >= 8) { if (check_mode() == RELEASE_MODE) { //csvファイルへの書き出し //std::cout << "REC:" << (int64)t2 << ":" << *move_x << "," << *move_y << "," << get_angle() << std::endl; std::cout << "REC:" << (int64)t2 << ":" << *move_x << "," << *move_y << "," << angle << "," << position << std::endl; dx = 0; dy = 0; mouse << (int64)t2 << "," << *move_x << "," << *move_y << "," << angle << "," << position << std::endl; } else { std::cout << (int64)t2 << ":" << "0" << "," << "0" << "," << angle << "," << position << std::endl; } t1 = timeGetTime() - start_time; } else { Sleep(1); } } } void serial_exit_mouse() { bool check = false; check = PurgeComm(mbed_mouse, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR); if (!check) { std::cout << "COULD NOT CLER" << std::endl; } CloseHandle(mbed_mouse); std::cout << "close serial port Mouse" << std::endl; }
f5d2828813a28980bf6b3605f30ab6f5a96c4633
087543eee8b84c79c4dc2863150fcced168be0ea
/Level 4/Structures de donnees et Balayages/Emissions/main.cpp
1ae8d973ef96354591591b85de038ce264c66b83
[ "MIT" ]
permissive
zied-ati/France-ioi
42955296001c932c8781431f5c34d3f12d743412
6db69e67fcb5cf34fed6c5e685d2a9018eec3e7a
refs/heads/master
2022-03-27T23:26:16.336482
2020-01-06T15:36:56
2020-01-06T15:36:56
75,761,623
35
34
MIT
2020-01-06T15:36:58
2016-12-06T18:57:27
C++
UTF-8
C++
false
false
551
cpp
#include <bits/stdc++.h> #define N 100001 #define M 128 using namespace std; inline int MAX(int a,int b){return (a<b)?b:a;} typedef pair<int,int> ii; int tab[N]; int n,d,o,t; string a; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin>>n>>d; for(int i=0;i<n;++i) cin>>tab[i]; int prev=0,sum=0,cntmax=0; for(int i=0;i<n;++i) { sum+=tab[i]; while(sum>d) { sum-=tab[prev++]; } if(i-prev+1>cntmax) cntmax=i-prev+1; } cout<<cntmax<<endl; return 0; }
cda6e05af4aba34694266d3eddaae296df94b17c
be0282afa8dd436619c71d6118c9db455eaf1a29
/Intermediate/Build/Win64/Design3D/Inc/Engine/AssetManagerSettings.generated.h
7260fc4b74cbbf44d8cccefae23a6ffdf06e3622
[]
no_license
Quant2017/Design3D
0f915580b222af40ab911021cceef5c26375d7f9
94a22386be4aa37aa0f546354cc62958820a4bf6
refs/heads/master
2022-04-23T10:44:12.398772
2020-04-22T01:02:39
2020-04-22T01:02:39
262,966,755
1
0
null
2020-05-11T07:12:37
2020-05-11T07:12:36
null
UTF-8
C++
false
false
5,597
h
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/ObjectMacros.h" #include "UObject/ScriptMacros.h" PRAGMA_DISABLE_DEPRECATION_WARNINGS #ifdef ENGINE_AssetManagerSettings_generated_h #error "AssetManagerSettings.generated.h already included, missing '#pragma once' in AssetManagerSettings.h" #endif #define ENGINE_AssetManagerSettings_generated_h #define Engine_Source_Runtime_Engine_Classes_Engine_AssetManagerSettings_h_46_GENERATED_BODY \ friend struct Z_Construct_UScriptStruct_FPrimaryAssetRulesCustomOverride_Statics; \ ENGINE_API static class UScriptStruct* StaticStruct(); template<> ENGINE_API UScriptStruct* StaticStruct<struct FPrimaryAssetRulesCustomOverride>(); #define Engine_Source_Runtime_Engine_Classes_Engine_AssetManagerSettings_h_31_GENERATED_BODY \ friend struct Z_Construct_UScriptStruct_FPrimaryAssetRulesOverride_Statics; \ ENGINE_API static class UScriptStruct* StaticStruct(); template<> ENGINE_API UScriptStruct* StaticStruct<struct FPrimaryAssetRulesOverride>(); #define Engine_Source_Runtime_Engine_Classes_Engine_AssetManagerSettings_h_13_GENERATED_BODY \ friend struct Z_Construct_UScriptStruct_FAssetManagerRedirect_Statics; \ ENGINE_API static class UScriptStruct* StaticStruct(); template<> ENGINE_API UScriptStruct* StaticStruct<struct FAssetManagerRedirect>(); #define Engine_Source_Runtime_Engine_Classes_Engine_AssetManagerSettings_h_69_RPC_WRAPPERS #define Engine_Source_Runtime_Engine_Classes_Engine_AssetManagerSettings_h_69_RPC_WRAPPERS_NO_PURE_DECLS #define Engine_Source_Runtime_Engine_Classes_Engine_AssetManagerSettings_h_69_INCLASS_NO_PURE_DECLS \ private: \ static void StaticRegisterNativesUAssetManagerSettings(); \ friend struct Z_Construct_UClass_UAssetManagerSettings_Statics; \ public: \ DECLARE_CLASS(UAssetManagerSettings, UDeveloperSettings, COMPILED_IN_FLAGS(0 | CLASS_DefaultConfig | CLASS_Config), CASTCLASS_None, TEXT("/Script/Engine"), NO_API) \ DECLARE_SERIALIZER(UAssetManagerSettings) \ static const TCHAR* StaticConfigName() {return TEXT("Game");} \ #define Engine_Source_Runtime_Engine_Classes_Engine_AssetManagerSettings_h_69_INCLASS \ private: \ static void StaticRegisterNativesUAssetManagerSettings(); \ friend struct Z_Construct_UClass_UAssetManagerSettings_Statics; \ public: \ DECLARE_CLASS(UAssetManagerSettings, UDeveloperSettings, COMPILED_IN_FLAGS(0 | CLASS_DefaultConfig | CLASS_Config), CASTCLASS_None, TEXT("/Script/Engine"), NO_API) \ DECLARE_SERIALIZER(UAssetManagerSettings) \ static const TCHAR* StaticConfigName() {return TEXT("Game");} \ #define Engine_Source_Runtime_Engine_Classes_Engine_AssetManagerSettings_h_69_STANDARD_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API UAssetManagerSettings(const FObjectInitializer& ObjectInitializer); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UAssetManagerSettings) \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UAssetManagerSettings); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UAssetManagerSettings); \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API UAssetManagerSettings(UAssetManagerSettings&&); \ NO_API UAssetManagerSettings(const UAssetManagerSettings&); \ public: #define Engine_Source_Runtime_Engine_Classes_Engine_AssetManagerSettings_h_69_ENHANCED_CONSTRUCTORS \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API UAssetManagerSettings(UAssetManagerSettings&&); \ NO_API UAssetManagerSettings(const UAssetManagerSettings&); \ public: \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UAssetManagerSettings); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UAssetManagerSettings); \ DEFINE_DEFAULT_CONSTRUCTOR_CALL(UAssetManagerSettings) #define Engine_Source_Runtime_Engine_Classes_Engine_AssetManagerSettings_h_69_PRIVATE_PROPERTY_OFFSET #define Engine_Source_Runtime_Engine_Classes_Engine_AssetManagerSettings_h_66_PROLOG #define Engine_Source_Runtime_Engine_Classes_Engine_AssetManagerSettings_h_69_GENERATED_BODY_LEGACY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ Engine_Source_Runtime_Engine_Classes_Engine_AssetManagerSettings_h_69_PRIVATE_PROPERTY_OFFSET \ Engine_Source_Runtime_Engine_Classes_Engine_AssetManagerSettings_h_69_RPC_WRAPPERS \ Engine_Source_Runtime_Engine_Classes_Engine_AssetManagerSettings_h_69_INCLASS \ Engine_Source_Runtime_Engine_Classes_Engine_AssetManagerSettings_h_69_STANDARD_CONSTRUCTORS \ public: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #define Engine_Source_Runtime_Engine_Classes_Engine_AssetManagerSettings_h_69_GENERATED_BODY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ Engine_Source_Runtime_Engine_Classes_Engine_AssetManagerSettings_h_69_PRIVATE_PROPERTY_OFFSET \ Engine_Source_Runtime_Engine_Classes_Engine_AssetManagerSettings_h_69_RPC_WRAPPERS_NO_PURE_DECLS \ Engine_Source_Runtime_Engine_Classes_Engine_AssetManagerSettings_h_69_INCLASS_NO_PURE_DECLS \ Engine_Source_Runtime_Engine_Classes_Engine_AssetManagerSettings_h_69_ENHANCED_CONSTRUCTORS \ private: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS template<> ENGINE_API UClass* StaticClass<class UAssetManagerSettings>(); #undef CURRENT_FILE_ID #define CURRENT_FILE_ID Engine_Source_Runtime_Engine_Classes_Engine_AssetManagerSettings_h PRAGMA_ENABLE_DEPRECATION_WARNINGS
f8136e1c333438e1a449430ac8d251f8c3ae4a32
2a404871dd92ac73054dbedf99ec795492df9636
/GoBoat.ino
63bdb7a78db9ef388b4c1d343d7261595f5e95e0
[]
no_license
tmo324/goBoat
64dcdf7bbc27512fde7df43fc830f433df42f8a7
e826e4c137aa82e0590549f9b8ea059ebe7f4120
refs/heads/master
2020-06-11T15:55:58.462467
2019-06-27T03:32:59
2019-06-27T03:32:59
194,016,472
1
0
null
null
null
null
UTF-8
C++
false
false
2,521
ino
#include "IRremote.h" #include <SoftwareSerial.h> #include <dht.h> #include <Wire.h> #include <Servo.h> #define address 0x1E //0011110b, I2C 7bit address of HMC5883 byte servoPin = 7; // thruster Servo servo; dht DHT; char key; int In1 = 7; int In2 = 6; int In3 = 5; int In4 = 4; int redPin = 10; int greenPin = 9; int bluePin = 8; #define DHT11_PIN 11 void setup() { Serial.begin(57600); Serial.println("Boat Turned On"); pinMode(In1, OUTPUT); pinMode(In2, OUTPUT); pinMode(In3, OUTPUT); pinMode(In4, OUTPUT); pinMode(redPin, OUTPUT); pinMode(greenPin, OUTPUT); pinMode(bluePin, OUTPUT); Serial.println("Testing here"); } void loop() { if (Serial.available()) { key = (char)Serial.read(); switch (key) { case 'w': Serial.println("Printing w"); forward(); setColor(0, 255, 0); // Green Color break; case 's': Serial.println("Printing s"); backward(); setColor(255, 255, 255); // White Color break; case 'a': Serial.println("Printing LEFT"); left(); break; case 'd': Serial.println("Printing RIGHT"); right(); break; case 'o': Serial.println("Going straight"); straight(); break; case 'p': Serial.println("Stopping everthing"); stopEverything(); setColor(255, 0, 0); // Red Color break; case "t": checkDHT() } } } ////////////NAVITAGION FUNCTIONS BEGIN HERE///////////////////////// ////////////////////////////////////////////////////////////////// void forward() { digitalWrite(In1, HIGH); digitalWrite(In2, LOW); } void backward() { digitalWrite(In1, LOW); digitalWrite(In2, HIGH); } void straight() { digitalWrite(In3, LOW); digitalWrite(In4, LOW); } void stopEverything() { digitalWrite(In1, LOW); digitalWrite(In2, LOW); digitalWrite(In3, LOW); digitalWrite(In4, LOW); } void right() { digitalWrite(In3, HIGH); digitalWrite(In4, LOW); } void left() { digitalWrite(In3, LOW); digitalWrite(In4, HIGH); } void checkDHT() { int chk = DHT.read11(DHT11_PIN); Serial.print("Temperature = "); Serial.print(DHT.temperature); Serial.println("°C"); Serial.print("Humidity = "); Serial.print(DHT.humidity); Serial.println("%"); } void setColor(int redValue, int greenValue, int blueValue) { analogWrite(redPin, redValue); analogWrite(greenPin, greenValue); analogWrite(bluePin, blueValue); }
95c62534b53e51e2e2254052a04fb8554c5dfad2
3f20b85493041af095feb735c3ae33416aa77a2f
/src/ACO.h
3b643729bdb49fdf88773639222e5f608633c11a
[ "MIT" ]
permissive
ruslankerimov/ACO
83eca7e7dce826b2d553085037b90f8a588d9779
ace6a81c8e8a6af2791f83d5252ee66fdb7a68ea
refs/heads/master
2021-01-23T18:51:09.458887
2013-03-31T18:13:27
2013-03-31T18:13:27
8,237,993
1
1
null
null
null
null
UTF-8
C++
false
false
676
h
#ifndef ACO_H_INCLUDED #define ACO_H_INCLUDED #include <vector> #include <algorithm> #include <time.h> #include "ACOconfig.h" using namespace std; class ACO { private: struct Ant { vector <double> cords; vector <double> tau; double value; Ant(vector <double>, vector <double>, double); }; ACOconfig config; int dimension; vector <double> get_random_cords(); vector <double> get_random_neighbor_cords(vector <double>); static double get_random_double(double, double); static bool is_rand_inited; static bool compare(Ant *, Ant *); public: ACO(ACOconfig); vector <double> solve(); }; #endif
4e22c3bd71c241d8a68419ffb846fbf663158ce2
37e7e6d47ad6104882988064758fc9e2d555d1e7
/new3.cpp
490d429e87c19e2759a35a59783796e4df457342
[]
no_license
Manoj-Patkar/NewProject
1119e427378f6fe9e05de457da585de8e1a624ce
17220bd55331a8cbd0b0cfded5dd596ab4cacefb
refs/heads/master
2021-06-17T18:03:29.703345
2017-06-08T12:33:31
2017-06-08T12:33:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
900
cpp
#include<bits/stdc++.h> using namespace std; int max(int a,int b){ return a>b?a:b; } int eggdrop(int k,int n){ if(k==1 || k==0) return k; if(n==1) return k; int minval=INT_MAX,x,res; for(int i=1;i<=k;i++){ res=1+max(eggdrop(i-1,n-1),eggdrop(k-i,n)); if(res<minval) minval=res; } return minval; } int dyeggdrop(int n,int k){ int s[n+1][k+1]; int res,minval=INT_MAX; for(int i=1;i<=n;i++){ s[i][0]=0; s[i][1]=1; } for(int j=1;j<=k;j++) s[1][j]=j; for(int i=2;i<=n;i++){ for(int j=2;j<=k;j++){ s[i][j]=INT_MAX; for(int x=1;x<=j;x++){ res=1+max(s[i-1][x-1] ,s[i][j-x]); if(res<s[i][j]) s[i][j]=res; } } } return s[n][k]; } int main(){ cout<<dyeggdrop(2,10); }
30591601fb64388fdf94075908cf0fdf94e09197
0dca3325c194509a48d0c4056909175d6c29f7bc
/nlp-automl/src/model/GetPredictDocResult.cc
a1f25ef3932885e00da4391f9699001a3a6569ed
[ "Apache-2.0" ]
permissive
dingshiyu/aliyun-openapi-cpp-sdk
3eebd9149c2e6a2b835aba9d746ef9e6bef9ad62
4edd799a79f9b94330d5705bb0789105b6d0bb44
refs/heads/master
2023-07-31T10:11:20.446221
2021-09-26T10:08:42
2021-09-26T10:08:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,698
cc
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/nlp-automl/model/GetPredictDocResult.h> #include <json/json.h> using namespace AlibabaCloud::Nlp_automl; using namespace AlibabaCloud::Nlp_automl::Model; GetPredictDocResult::GetPredictDocResult() : ServiceResult() {} GetPredictDocResult::GetPredictDocResult(const std::string &payload) : ServiceResult() { parse(payload); } GetPredictDocResult::~GetPredictDocResult() {} void GetPredictDocResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); if(!value["ResultContent"].isNull()) resultContent_ = value["ResultContent"].asString(); if(!value["Status"].isNull()) status_ = std::stoi(value["Status"].asString()); if(!value["XLIFFInfo"].isNull()) xLIFFInfo_ = value["XLIFFInfo"].asString(); } int GetPredictDocResult::getStatus()const { return status_; } std::string GetPredictDocResult::getXLIFFInfo()const { return xLIFFInfo_; } std::string GetPredictDocResult::getResultContent()const { return resultContent_; }
5157df35a4f68e7e1818339e52633eab34dc6b80
2ee3a040a64035d0fb7cc094ec5af940d2f2f318
/HDU/HDU4067 Random Maze.cpp
c16340c22781f309650057c59bc8e953a8c6fc9f
[]
no_license
vawait/ACM
a9831a407cc670a6442989e615add81e69a8f374
7ca6a0bfd65da86b2276699aef9d062aa15781f6
refs/heads/master
2016-09-15T21:08:31.327852
2015-10-27T13:45:45
2015-10-27T13:45:45
25,562,611
3
2
null
null
null
null
UTF-8
C++
false
false
2,438
cpp
/* * Author: vawait * Created Time: 2015/7/22 17:03:24 * Problem: HDU4067 Random Maze */ #include<cstdio> #include<iostream> #include<cstring> #include<cstdlib> #include<cmath> #include<algorithm> #include<string> #include<map> #include<set> #include<vector> #include<queue> #include<stack> #include<ctime> using namespace std; #define rep(i, a, b) for (int i = (a); i <= (b); ++i) #define red(i, a, b) for (int i = (a); i >= (b); --i) #define clr( x , y ) memset(x,y,sizeof(x)) #define mp make_pair #define pb push_back #define x first #define y second #define sqr(x) ((x) * (x)) typedef long long lint; const int maxn = 110; int n , m , ans , sum , in[maxn] , out[maxn]; int t , S = 0 , T = 102 , as , at , a[maxn] , d[maxn] , pre[maxn] , f[maxn] , v[maxn]; struct nodd { int y , d , f , n; } b[110000]; void add(int x,int y,int d,int f) { b[++t].y = y; b[t].d = d; b[t].f = f; b[t].n = a[x]; a[x] = t; b[++t].y = x; b[t].d = 0; b[t].f = -f; b[t].n = a[y]; a[y] = t; } bool spfa() { queue < int > q; int x , y; q.push( S ); clr( d , 1 ); d[S] = 0; while ( !q.empty() ) { x = q.front(); q.pop(); v[x] = 0; for ( int p = a[x]; p; p = b[p].n ) if ( b[p].d && b[p].f + d[x] < d[y=b[p].y] ) { d[y] = d[x] + b[p].f; pre[y] = x; f[y] = p; if ( !v[y] ) v[y] = 1 , q.push( y ); } } if ( d[T] >= d[T+1] ) return 0; int mx = 2e9; for ( x = T; x != S; x = pre[x] ) mx = min( mx , b[f[x]].d ); for ( x = T; x != S; x = pre[x] ) b[f[x]].d -= mx , b[f[x]^1].d += mx; ans += d[T] * mx; sum -= mx; return 1; } void init() { int x , y , fa , fb; t = 1; clr( a , 0 ); clr( in , 0 ); clr( out , 0 ); ans = sum = 0; scanf("%d%d%d%d",&n,&m,&as,&at); rep(i,1,m) { scanf("%d%d%d%d",&x,&y,&fa,&fb); if ( fb > fa ) { add( x , y , 1 , fb - fa ); ans += fa; out[x] ++; in[y] ++; } else { add( y , x , 1 , fa - fb ); ans += fb; } } } void work() { in[as] ++; out[at] ++; rep(i,1,n) if ( in[i] > out[i] ) add( i , T , in[i] - out[i] , 0 ); else add( S , i , out[i] - in[i] , 0 ) , sum += out[i] - in[i]; while ( spfa() ) ; if ( sum ) puts("impossible"); else printf("%d\n",ans); } int main() { int t; cin >> t; rep(i,1,t) { printf("Case %d: ",i); init(); work(); } return 0; }
9d5c5f70180dbf74f7d56caf198495b095b68c92
602ea0c05970cbd766df068b003671c561f59661
/chrome/browser/ui/views/permission_bubble/chooser_bubble_ui.cc
65e4bdba9fd061dae87d789d3bcb57d579266a27
[ "BSD-3-Clause" ]
permissive
VitalyKononenko/chromium
088de78a639375b073cabb7665afc638334e8672
b8ad2cadb6a163269cd7851bc7962744743785bd
refs/heads/master
2023-03-01T10:15:00.815394
2019-08-15T19:51:40
2019-08-15T19:51:40
202,603,102
1
0
BSD-3-Clause
2019-08-15T19:54:34
2019-08-15T19:54:33
null
UTF-8
C++
false
false
7,610
cc
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/permission_bubble/chooser_bubble_ui.h" #include "base/strings/string16.h" #include "chrome/browser/chooser_controller/chooser_controller.h" #include "chrome/browser/ui/browser_dialogs.h" #include "chrome/browser/ui/permission_bubble/chooser_bubble_delegate.h" #include "chrome/browser/ui/views/bubble_anchor_util_views.h" #include "chrome/browser/ui/views/device_chooser_content_view.h" #include "chrome/browser/ui/views/front_eliding_title_label.h" #include "components/bubble/bubble_controller.h" #include "ui/views/bubble/bubble_dialog_delegate_view.h" #include "ui/views/bubble/bubble_frame_view.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/styled_label.h" #include "ui/views/controls/table/table_view_observer.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/window/dialog_client_view.h" using bubble_anchor_util::AnchorConfiguration; namespace { AnchorConfiguration GetChooserAnchorConfiguration(Browser* browser) { return bubble_anchor_util::GetPageInfoAnchorConfiguration(browser); } gfx::Rect GetChooserAnchorRect(Browser* browser) { return bubble_anchor_util::GetPageInfoAnchorRect(browser); } } // namespace /////////////////////////////////////////////////////////////////////////////// // View implementation for the chooser bubble. class ChooserBubbleUiViewDelegate : public views::BubbleDialogDelegateView, public views::TableViewObserver { public: ChooserBubbleUiViewDelegate( Browser* browser, std::unique_ptr<ChooserController> chooser_controller); ~ChooserBubbleUiViewDelegate() override; // views::View: void AddedToWidget() override; // views::WidgetDelegate: base::string16 GetWindowTitle() const override; // views::DialogDelegate: base::string16 GetDialogButtonLabel(ui::DialogButton button) const override; bool IsDialogButtonEnabled(ui::DialogButton button) const override; views::View* GetInitiallyFocusedView() override; std::unique_ptr<views::View> CreateExtraView() override; bool Accept() override; bool Cancel() override; bool Close() override; // views::TableViewObserver: void OnSelectionChanged() override; // Updates the anchor's arrow and view. Also repositions the bubble so it's // displayed in the correct location. void UpdateAnchor(Browser* browser); void set_bubble_reference(BubbleReference bubble_reference); void UpdateTableView() const; private: DeviceChooserContentView* device_chooser_content_view_; BubbleReference bubble_reference_; DISALLOW_COPY_AND_ASSIGN(ChooserBubbleUiViewDelegate); }; ChooserBubbleUiViewDelegate::ChooserBubbleUiViewDelegate( Browser* browser, std::unique_ptr<ChooserController> chooser_controller) : device_chooser_content_view_(nullptr) { // ------------------------------------ // | Chooser bubble title | // | -------------------------------- | // | | option 0 | | // | | option 1 | | // | | option 2 | | // | | | | // | | | | // | | | | // | -------------------------------- | // | [ Connect ] [ Cancel ] | // |----------------------------------| // | Get help | // ------------------------------------ SetLayoutManager(std::make_unique<views::FillLayout>()); device_chooser_content_view_ = new DeviceChooserContentView(this, std::move(chooser_controller)); AddChildView(device_chooser_content_view_); UpdateAnchor(browser); chrome::RecordDialogCreation(chrome::DialogIdentifier::CHOOSER_UI); } ChooserBubbleUiViewDelegate::~ChooserBubbleUiViewDelegate() {} void ChooserBubbleUiViewDelegate::AddedToWidget() { GetBubbleFrameView()->SetTitleView( CreateFrontElidingTitleLabel(GetWindowTitle())); } base::string16 ChooserBubbleUiViewDelegate::GetWindowTitle() const { return device_chooser_content_view_->GetWindowTitle(); } views::View* ChooserBubbleUiViewDelegate::GetInitiallyFocusedView() { return GetDialogClientView()->cancel_button(); } base::string16 ChooserBubbleUiViewDelegate::GetDialogButtonLabel( ui::DialogButton button) const { return device_chooser_content_view_->GetDialogButtonLabel(button); } bool ChooserBubbleUiViewDelegate::IsDialogButtonEnabled( ui::DialogButton button) const { return device_chooser_content_view_->IsDialogButtonEnabled(button); } std::unique_ptr<views::View> ChooserBubbleUiViewDelegate::CreateExtraView() { auto extra_view = device_chooser_content_view_->CreateExtraView(); return extra_view; } bool ChooserBubbleUiViewDelegate::Accept() { device_chooser_content_view_->Accept(); if (bubble_reference_) bubble_reference_->CloseBubble(BUBBLE_CLOSE_ACCEPTED); return true; } bool ChooserBubbleUiViewDelegate::Cancel() { device_chooser_content_view_->Cancel(); if (bubble_reference_) bubble_reference_->CloseBubble(BUBBLE_CLOSE_CANCELED); return true; } bool ChooserBubbleUiViewDelegate::Close() { device_chooser_content_view_->Close(); return true; } void ChooserBubbleUiViewDelegate::OnSelectionChanged() { DialogModelChanged(); } void ChooserBubbleUiViewDelegate::UpdateAnchor(Browser* browser) { AnchorConfiguration configuration = GetChooserAnchorConfiguration(browser); SetAnchorView(configuration.anchor_view); SetHighlightedButton(configuration.highlighted_button); if (!configuration.anchor_view) SetAnchorRect(GetChooserAnchorRect(browser)); SetArrow(configuration.bubble_arrow); } void ChooserBubbleUiViewDelegate::set_bubble_reference( BubbleReference bubble_reference) { bubble_reference_ = bubble_reference; } void ChooserBubbleUiViewDelegate::UpdateTableView() const { device_chooser_content_view_->UpdateTableView(); } ////////////////////////////////////////////////////////////////////////////// // ChooserBubbleUi ChooserBubbleUi::ChooserBubbleUi( Browser* browser, std::unique_ptr<ChooserController> chooser_controller) : browser_(browser), chooser_bubble_ui_view_delegate_(nullptr) { DCHECK(browser_); DCHECK(chooser_controller); chooser_bubble_ui_view_delegate_ = new ChooserBubbleUiViewDelegate(browser, std::move(chooser_controller)); } ChooserBubbleUi::~ChooserBubbleUi() { if (chooser_bubble_ui_view_delegate_ && chooser_bubble_ui_view_delegate_->GetWidget()) { chooser_bubble_ui_view_delegate_->GetWidget()->RemoveObserver(this); } } void ChooserBubbleUi::Show(BubbleReference bubble_reference) { chooser_bubble_ui_view_delegate_->set_bubble_reference(bubble_reference); chooser_bubble_ui_view_delegate_->UpdateAnchor(browser_); CreateAndShow(chooser_bubble_ui_view_delegate_); chooser_bubble_ui_view_delegate_->GetWidget()->AddObserver(this); chooser_bubble_ui_view_delegate_->UpdateTableView(); } void ChooserBubbleUi::Close() { if (chooser_bubble_ui_view_delegate_ && !chooser_bubble_ui_view_delegate_->GetWidget()->IsClosed()) { chooser_bubble_ui_view_delegate_->GetWidget()->Close(); } } void ChooserBubbleUi::UpdateAnchorPosition() { if (chooser_bubble_ui_view_delegate_) chooser_bubble_ui_view_delegate_->UpdateAnchor(browser_); } void ChooserBubbleUi::OnWidgetClosing(views::Widget* widget) { widget->RemoveObserver(this); chooser_bubble_ui_view_delegate_ = nullptr; }
c230defc5c98dac8de7199bc73566ec9d4ab97cf
e7f19ced317e449b63267ee285d623125c88e5fb
/vkradial/src/main/cpp/gli/sampler_cube_array.hpp
106e24c6baba1168d753e082b669ac5671afcff3
[]
no_license
playbar/androidvk
d27186f934a21e9176fb2adc6e07b410e580248e
564448b0dee4b9350af61e73840e0030efa24897
refs/heads/master
2021-01-19T21:52:11.086708
2019-12-11T08:43:26
2019-12-11T08:43:26
88,712,630
2
1
null
null
null
null
UTF-8
C++
false
false
3,047
hpp
/// @brief Include to sample cube map array textures. /// @file gli/sampler_cube_array.hpp #pragma once #include "sampler.hpp" #include "texture_cube_array.hpp" #include "core/mipmaps_compute.hpp" #include "core/convert_func.hpp" namespace gli { /// Cube map array texture sampler /// @tparam T Sampler can fetch, write and interpret any texture format but will expose and process the data through type T conversions. /// @tparam P Precision in term of ULPs template <typename T, precision P = defaultp> class sampler_cube_array : public sampler { private: typedef typename detail::interpolate<T>::type interpolate_type; public: typedef texture_cube_array texture_type; typedef typename texture_type::size_type size_type; typedef typename texture_type::extent_type extent_type; typedef interpolate_type level_type; typedef vec<2, interpolate_type, P> normalized_type; typedef vec<4, T, P> texel_type; sampler_cube_array(texture_type const& Texture, wrap Wrap, filter Mip = FILTER_NEAREST, filter Min = FILTER_NEAREST, texel_type const& BorderColor = texel_type(0, 0, 0, 1)); /// Access the sampler texture object texture_type const& operator()() const; /// Fetch a texel from the sampler texture texel_type texel_fetch(extent_type const& TexelCoord, size_type layer, size_type Face, size_type Level) const; /// Write a texel in the sampler texture void texel_write(extent_type const& TexelCoord, size_type layer, size_type Face, size_type Level, texel_type const& Texel); /// Clear the sampler texture with a uniform texel void clear(texel_type const& Texel); /// Sample the sampler texture at a specific level texel_type texture_lod(normalized_type const& SampleCoord, size_type layer, size_type Face, level_type Level) const; /// Generate all the mipmaps of the sampler texture from the texture base level void generate_mipmaps(filter Minification); /// Generate the mipmaps of the sampler texture from the texture base level to the texture max level included void generate_mipmaps(size_type BaseLayer, size_type MaxLayer, size_type BaseFace, size_type MaxFace, size_type BaseLevel, size_type MaxLevel, filter Minification); private: typedef typename detail::convert<texture_type, T, P>::func convert_type; typedef typename detail::convert<texture_type, T, P>::fetchFunc fetch_type; typedef typename detail::convert<texture_type, T, P>::writeFunc write_type; typedef typename detail::filterBase<detail::DIMENSION_2D, texture_type, interpolate_type, normalized_type, fetch_type, texel_type>::filterFunc filter_type; texture_type Texture; convert_type Convert; texel_type BorderColor; filter_type Filter; }; typedef sampler_cube_array<float> fsamplerCubeArray; typedef sampler_cube_array<double> dsamplerCubeArray; typedef sampler_cube_array<unsigned int> usamplerCubeArray; typedef sampler_cube_array<int> isamplerCubeArray; }//namespace gli #include "./core/sampler_cube_array.inl"
67e644e4a9ed7e2db98735ad9e7b346e6beadfad
be379c5decf2b8a8a7aac102e489563ae0da8593
/extern/irrogles/source/Irrlicht/CParticleAnimatedMeshSceneNodeEmitter.h
81ebb74872302ebe8a93820e3f36ba48b3b915d4
[]
no_license
codeman001/gsleveleditor
6050daf26d623af4f6ab9fa97f032d958fb4c5ae
d30e54874a4c7ae4fd0a364aa92a2082f73a5d7c
refs/heads/master
2021-01-10T13:09:01.347502
2013-05-12T09:14:47
2013-05-12T09:14:47
44,381,635
1
0
null
null
null
null
UTF-8
C++
false
false
6,414
h
// Copyright (C) 2002-2010 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #ifndef __C_PARTICLE_ANIMATED_MESH_SCENE_NODE_EMITTER_H_INCLUDED__ #define __C_PARTICLE_ANIMATED_MESH_SCENE_NODE_EMITTER_H_INCLUDED__ #include "IParticleAnimatedMeshSceneNodeEmitter.h" #include "irrArray.h" namespace irr { namespace scene { //! An animated mesh emitter class CParticleAnimatedMeshSceneNodeEmitter : public IParticleAnimatedMeshSceneNodeEmitter { public: //! constructor CParticleAnimatedMeshSceneNodeEmitter( IAnimatedMeshSceneNode* node, bool useNormalDirection = true, const core::vector3df& direction = core::vector3df(0.0f,0.0f,-1.0f), f32 normalDirectionModifier = 100.0f, s32 mbNumber = -1, bool everyMeshVertex = false, u32 minParticlesPerSecond = 20, u32 maxParticlesPerSecond = 40, const video::SColor& minStartColor = video::SColor(255,0,0,0), const video::SColor& maxStartColor = video::SColor(255,255,255,255), u32 lifeTimeMin = 2000, u32 lifeTimeMax = 4000, s32 maxAngleDegrees = 0, const core::dimension2df& minStartSize = core::dimension2df(5.0f,5.0f), const core::dimension2df& maxStartSize = core::dimension2df(5.0f,5.0f) ); //! Prepares an array with new particles to emitt into the system //! and returns how much new particles there are. virtual s32 emitt(u32 now, u32 timeSinceLastCall, SParticle*& outArray); //! Set Mesh to emit particles from virtual void setAnimatedMeshSceneNode( IAnimatedMeshSceneNode* node ); //! Set whether to use vertex normal for direction, or direction specified virtual void setUseNormalDirection( bool useNormalDirection ) { UseNormalDirection = useNormalDirection; } //! Set direction the emitter emits particles virtual void setDirection( const core::vector3df& newDirection ) { Direction = newDirection; } //! Set the amount that the normal is divided by for getting a particles direction virtual void setNormalDirectionModifier( f32 normalDirectionModifier ) { NormalDirectionModifier = normalDirectionModifier; } //! Sets whether to emit min<->max particles for every vertex per second, or to pick //! min<->max vertices every second virtual void setEveryMeshVertex( bool everyMeshVertex ) { EveryMeshVertex = everyMeshVertex; } //! Set minimum number of particles the emitter emits per second virtual void setMinParticlesPerSecond( u32 minPPS ) { MinParticlesPerSecond = minPPS; } //! Set maximum number of particles the emitter emits per second virtual void setMaxParticlesPerSecond( u32 maxPPS ) { MaxParticlesPerSecond = maxPPS; } //! Set minimum starting color for particles virtual void setMinStartColor( const video::SColor& color ) { MinStartColor = color; } //! Set maximum starting color for particles virtual void setMaxStartColor( const video::SColor& color ) { MaxStartColor = color; } //! Set the maximum starting size for particles virtual void setMaxStartSize( const core::dimension2df& size ) { MaxStartSize = size; }; //! Set the minimum starting size for particles virtual void setMinStartSize( const core::dimension2df& size ) { MinStartSize = size; }; //! Set the minimum particle life-time in milliseconds virtual void setMinLifeTime( u32 lifeTimeMin ) { MinLifeTime = lifeTimeMin; } //! Set the maximum particle life-time in milliseconds virtual void setMaxLifeTime( u32 lifeTimeMax ) { MaxLifeTime = lifeTimeMax; } //! Maximal random derivation from the direction virtual void setMaxAngleDegrees( s32 maxAngleDegrees ) { MaxAngleDegrees = maxAngleDegrees; } //! Get Mesh we're emitting particles from virtual const IAnimatedMeshSceneNode* getAnimatedMeshSceneNode() const { return Node; } //! Get whether to use vertex normal for direciton, or direction specified virtual bool isUsingNormalDirection() const { return UseNormalDirection; } //! Get direction the emitter emits particles virtual const core::vector3df& getDirection() const { return Direction; } //! Get the amount that the normal is divided by for getting a particles direction virtual f32 getNormalDirectionModifier() const { return NormalDirectionModifier; } //! Gets whether to emit min<->max particles for every vertex per second, or to pick //! min<->max vertices every second virtual bool getEveryMeshVertex() const { return EveryMeshVertex; } //! Get the minimum number of particles the emitter emits per second virtual u32 getMinParticlesPerSecond() const { return MinParticlesPerSecond; } //! Get the maximum number of particles the emitter emits per second virtual u32 getMaxParticlesPerSecond() const { return MaxParticlesPerSecond; } //! Get the minimum starting color for particles virtual const video::SColor& getMinStartColor() const { return MinStartColor; } //! Get the maximum starting color for particles virtual const video::SColor& getMaxStartColor() const { return MaxStartColor; } //! Get the maximum starting size for particles virtual const core::dimension2df& getMaxStartSize() const { return MaxStartSize; } //! Get the minimum starting size for particles virtual const core::dimension2df& getMinStartSize() const { return MinStartSize; } //! Get the minimum particle life-time in milliseconds virtual u32 getMinLifeTime() const { return MinLifeTime; } //! Get the maximum particle life-time in milliseconds virtual u32 getMaxLifeTime() const { return MaxLifeTime; } //! Maximal random derivation from the direction virtual s32 getMaxAngleDegrees() const { return MaxAngleDegrees; } private: IAnimatedMeshSceneNode* Node; IAnimatedMesh* AnimatedMesh; const IMesh* BaseMesh; s32 TotalVertices; u32 MBCount; s32 MBNumber; core::array<s32> VertexPerMeshBufferList; core::array<SParticle> Particles; core::vector3df Direction; f32 NormalDirectionModifier; u32 MinParticlesPerSecond, MaxParticlesPerSecond; video::SColor MinStartColor, MaxStartColor; u32 MinLifeTime, MaxLifeTime; core::dimension2df MaxStartSize, MinStartSize; u32 Time; u32 Emitted; s32 MaxAngleDegrees; bool EveryMeshVertex; bool UseNormalDirection; }; } // end namespace scene } // end namespace irr #endif // __C_PARTICLE_ANIMATED_MESH_SCENE_NODE_EMITTER_H_INCLUDED__
beb9ca00dafc886f40d06a8598fd29daf9e7c01a
676cc76c5dc02c9be1f4f79dada8a8ba409f7333
/VNS.h
94155046310d2f8115bfc5045b8fd4031a247861
[]
no_license
milossosic/MLP
a059364e4767fa742f21f07622eab0388cc982e2
9f6a7fbdd71a07339ea28d0a6bf40b76f96e810c
refs/heads/master
2016-09-06T20:04:19.871082
2014-07-20T10:48:23
2014-07-20T10:48:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
56
h
#pragma once class VNS { public: VNS(); ~VNS(); };
ac43fb88f9d7dee6786491e9e25984930955944b
d1bad56c9abef8b8156eda715438111c976ed6cd
/ms3/CustomerOrder.h
bd1f3b70b5376be0228ef38fc5d087596097e10d
[ "MIT" ]
permissive
mylorik/OOP345
d3a832bafe76aae1cafb574494d545199f4e801a
0034a803a7ee98e13ea36d805993d4727c3a09e4
refs/heads/master
2020-04-15T14:38:42.396718
2019-01-09T01:16:44
2019-01-09T01:16:44
164,759,625
0
0
null
null
null
null
UTF-8
C++
false
false
1,243
h
// Name: Artem Kulihina // Seneca Student ID: 128516168 // Seneca email: [email protected] // Date of completion: 25.11.2018 // // I confirm that I am the only author of this file // and the content was created entirely by me. #ifndef CUSTOMERORDER_H #define CUSTOMERORDER_H #include <utility> #include "Item.h" struct ItemInfo { std::string m_itemName; unsigned int m_serialNumber = 0; bool m_fillState = false; ItemInfo(std::string src) : m_itemName(std::move(src)){}; }; class CustomerOrder { std::string m_name; std::string m_product; unsigned int m_cntItem{}; ItemInfo** m_listItem{}; static size_t m_widthField; public: CustomerOrder(); explicit CustomerOrder(const std::string&); CustomerOrder(CustomerOrder&); CustomerOrder& operator=(CustomerOrder&) = delete; CustomerOrder(CustomerOrder&&) noexcept; // move constructor CustomerOrder& operator=(CustomerOrder&&) noexcept; // move assignment operator ~CustomerOrder(); bool getItemFillState(const std::string&) const; bool getOrderFillState() const; void fillItem(Item&, std::ostream&) const; // I think this member function should be const void display(std::ostream&) const; }; #endif //CUSTOMERORDER_H
f3e91e905edcb259643c8b0dbb9efe91e93ae71a
8ada5c56d043388342d05495a895f46d90722e3f
/Layer.hpp
678ddec8660c2969251eefe9cef6e6d5726c5535
[]
no_license
bruno-krinski/Multilayer-Perceptron
01fbe749c339078c22dac233974d1859d6a13504
261660737a5fc80e60001ba3c874dc9a6c57685b
refs/heads/master
2021-07-15T06:17:24.436831
2017-10-20T22:48:08
2017-10-20T22:48:08
107,452,633
0
0
null
null
null
null
UTF-8
C++
false
false
656
hpp
/* * Layer.hpp * * Created on: 18 de out de 2017 * Author: Bruno Alexandre Krinski */ #ifndef LAYER_HPP_ #define LAYER_HPP_ #include<iostream> #include<vector> #include<string> #include "Neuron.hpp" namespace nn { class Layer { private: unsigned int numNeurons; std::vector<float> input; std::vector<float> output; std::vector<Neuron> neurons; public: Layer(unsigned int nNeurons); virtual ~Layer(); void setInput(std::vector<float> in); void activate(); unsigned int size(); void write(); std::vector<Neuron> getNeurons(); void initWeights(unsigned int numWeights, float weight); }; } /* namespace nn */ #endif /* LAYER_HPP_ */
64a64f16c87fa6eaa60c0bf49e6378e8553d7c75
f3e29b588c794f863db00438961c1f237dfa55ce
/src/snapshot/serializer.h
a5131acbf9f9419e2afffdebe34c9d72f169e133
[ "BSD-3-Clause", "SunPro", "bzip2-1.0.6" ]
permissive
jackigal/v8
d9c04aa0c75e42abb5e753ddbde2b33d3aeb97f3
ec3928cea48d2b2004b9e30035a1999133645202
refs/heads/master
2021-01-19T09:38:29.521895
2017-04-10T03:00:42
2017-04-10T03:22:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,400
h
// Copyright 2016 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_SNAPSHOT_SERIALIZER_H_ #define V8_SNAPSHOT_SERIALIZER_H_ #include "src/isolate.h" #include "src/log.h" #include "src/objects.h" #include "src/snapshot/serializer-common.h" #include "src/snapshot/snapshot-source-sink.h" namespace v8 { namespace internal { class CodeAddressMap : public CodeEventLogger { public: explicit CodeAddressMap(Isolate* isolate) : isolate_(isolate) { isolate->logger()->addCodeEventListener(this); } ~CodeAddressMap() override { isolate_->logger()->removeCodeEventListener(this); } void CodeMoveEvent(AbstractCode* from, Address to) override { address_to_name_map_.Move(from->address(), to); } void CodeDisableOptEvent(AbstractCode* code, SharedFunctionInfo* shared) override {} const char* Lookup(Address address) { return address_to_name_map_.Lookup(address); } private: class NameMap { public: NameMap() : impl_() {} ~NameMap() { for (base::HashMap::Entry* p = impl_.Start(); p != NULL; p = impl_.Next(p)) { DeleteArray(static_cast<const char*>(p->value)); } } void Insert(Address code_address, const char* name, int name_size) { base::HashMap::Entry* entry = FindOrCreateEntry(code_address); if (entry->value == NULL) { entry->value = CopyName(name, name_size); } } const char* Lookup(Address code_address) { base::HashMap::Entry* entry = FindEntry(code_address); return (entry != NULL) ? static_cast<const char*>(entry->value) : NULL; } void Remove(Address code_address) { base::HashMap::Entry* entry = FindEntry(code_address); if (entry != NULL) { DeleteArray(static_cast<char*>(entry->value)); RemoveEntry(entry); } } void Move(Address from, Address to) { if (from == to) return; base::HashMap::Entry* from_entry = FindEntry(from); DCHECK(from_entry != NULL); void* value = from_entry->value; RemoveEntry(from_entry); base::HashMap::Entry* to_entry = FindOrCreateEntry(to); DCHECK(to_entry->value == NULL); to_entry->value = value; } private: static char* CopyName(const char* name, int name_size) { char* result = NewArray<char>(name_size + 1); for (int i = 0; i < name_size; ++i) { char c = name[i]; if (c == '\0') c = ' '; result[i] = c; } result[name_size] = '\0'; return result; } base::HashMap::Entry* FindOrCreateEntry(Address code_address) { return impl_.LookupOrInsert(code_address, ComputePointerHash(code_address)); } base::HashMap::Entry* FindEntry(Address code_address) { return impl_.Lookup(code_address, ComputePointerHash(code_address)); } void RemoveEntry(base::HashMap::Entry* entry) { impl_.Remove(entry->key, entry->hash); } base::HashMap impl_; DISALLOW_COPY_AND_ASSIGN(NameMap); }; void LogRecordedBuffer(AbstractCode* code, SharedFunctionInfo*, const char* name, int length) override { address_to_name_map_.Insert(code->address(), name, length); } NameMap address_to_name_map_; Isolate* isolate_; }; // There can be only one serializer per V8 process. class Serializer : public SerializerDeserializer { public: explicit Serializer(Isolate* isolate); ~Serializer() override; void EncodeReservations(List<SerializedData::Reservation>* out) const; void SerializeDeferredObjects(); Isolate* isolate() const { return isolate_; } SerializerReferenceMap* reference_map() { return &reference_map_; } RootIndexMap* root_index_map() { return &root_index_map_; } #ifdef OBJECT_PRINT void CountInstanceType(Map* map, int size); #endif // OBJECT_PRINT protected: class ObjectSerializer; class RecursionScope { public: explicit RecursionScope(Serializer* serializer) : serializer_(serializer) { serializer_->recursion_depth_++; } ~RecursionScope() { serializer_->recursion_depth_--; } bool ExceedsMaximum() { return serializer_->recursion_depth_ >= kMaxRecursionDepth; } private: static const int kMaxRecursionDepth = 32; Serializer* serializer_; }; virtual void SerializeObject(HeapObject* o, HowToCode how_to_code, WhereToPoint where_to_point, int skip) = 0; void VisitPointers(Object** start, Object** end) override; void PutRoot(int index, HeapObject* object, HowToCode how, WhereToPoint where, int skip); void PutSmi(Smi* smi); void PutBackReference(HeapObject* object, SerializerReference reference); void PutAttachedReference(SerializerReference reference, HowToCode how_to_code, WhereToPoint where_to_point); // Emit alignment prefix if necessary, return required padding space in bytes. int PutAlignmentPrefix(HeapObject* object); // Returns true if the object was successfully serialized as hot object. bool SerializeHotObject(HeapObject* obj, HowToCode how_to_code, WhereToPoint where_to_point, int skip); // Returns true if the object was successfully serialized as back reference. bool SerializeBackReference(HeapObject* obj, HowToCode how_to_code, WhereToPoint where_to_point, int skip); inline void FlushSkip(int skip) { if (skip != 0) { sink_.Put(kSkip, "SkipFromSerializeObject"); sink_.PutInt(skip, "SkipDistanceFromSerializeObject"); } } bool BackReferenceIsAlreadyAllocated(SerializerReference back_reference); // This will return the space for an object. SerializerReference AllocateLargeObject(int size); SerializerReference AllocateMap(); SerializerReference Allocate(AllocationSpace space, int size); int EncodeExternalReference(Address addr) { return external_reference_encoder_.Encode(addr); } bool HasNotExceededFirstPageOfEachSpace(); // GetInt reads 4 bytes at once, requiring padding at the end. void Pad(); // We may not need the code address map for logging for every instance // of the serializer. Initialize it on demand. void InitializeCodeAddressMap(); Code* CopyCode(Code* code); inline uint32_t max_chunk_size(int space) const { DCHECK_LE(0, space); DCHECK_LT(space, kNumberOfSpaces); return max_chunk_size_[space]; } const SnapshotByteSink* sink() const { return &sink_; } void QueueDeferredObject(HeapObject* obj) { DCHECK(reference_map_.Lookup(obj).is_back_reference()); deferred_objects_.Add(obj); } void OutputStatistics(const char* name); Isolate* isolate_; SnapshotByteSink sink_; ExternalReferenceEncoder external_reference_encoder_; SerializerReferenceMap reference_map_; RootIndexMap root_index_map_; int recursion_depth_; friend class Deserializer; friend class ObjectSerializer; friend class RecursionScope; friend class SnapshotData; private: CodeAddressMap* code_address_map_; // Objects from the same space are put into chunks for bulk-allocation // when deserializing. We have to make sure that each chunk fits into a // page. So we track the chunk size in pending_chunk_ of a space, but // when it exceeds a page, we complete the current chunk and start a new one. uint32_t pending_chunk_[kNumberOfPreallocatedSpaces]; List<uint32_t> completed_chunks_[kNumberOfPreallocatedSpaces]; uint32_t max_chunk_size_[kNumberOfPreallocatedSpaces]; // Number of maps that we need to allocate. uint32_t num_maps_; // We map serialized large objects to indexes for back-referencing. uint32_t large_objects_total_size_; uint32_t seen_large_objects_index_; List<byte> code_buffer_; // To handle stack overflow. List<HeapObject*> deferred_objects_; #ifdef OBJECT_PRINT static const int kInstanceTypes = 256; int* instance_type_count_; size_t* instance_type_size_; #endif // OBJECT_PRINT DISALLOW_COPY_AND_ASSIGN(Serializer); }; class Serializer::ObjectSerializer : public ObjectVisitor { public: ObjectSerializer(Serializer* serializer, HeapObject* obj, SnapshotByteSink* sink, HowToCode how_to_code, WhereToPoint where_to_point) : serializer_(serializer), object_(obj), sink_(sink), reference_representation_(how_to_code + where_to_point), bytes_processed_so_far_(0), code_has_been_output_(false) {} ~ObjectSerializer() override {} void Serialize(); void SerializeDeferred(); void VisitPointers(Object** start, Object** end) override; void VisitEmbeddedPointer(RelocInfo* target) override; void VisitExternalReference(Address* p) override; void VisitExternalReference(RelocInfo* rinfo) override; void VisitInternalReference(RelocInfo* rinfo) override; void VisitCodeTarget(RelocInfo* target) override; void VisitCodeEntry(Address entry_address) override; void VisitCell(RelocInfo* rinfo) override; void VisitRuntimeEntry(RelocInfo* reloc) override; private: bool TryEncodeDeoptimizationEntry(HowToCode how_to_code, Address target, int skip); void SerializePrologue(AllocationSpace space, int size, Map* map); enum ReturnSkip { kCanReturnSkipInsteadOfSkipping, kIgnoringReturn }; // This function outputs or skips the raw data between the last pointer and // up to the current position. It optionally can just return the number of // bytes to skip instead of performing a skip instruction, in case the skip // can be merged into the next instruction. int OutputRawData(Address up_to, ReturnSkip return_skip = kIgnoringReturn); void SerializeExternalString(); void SerializeExternalStringAsSequentialString(); bool SerializeExternalNativeSourceString( int builtin_count, v8::String::ExternalOneByteStringResource** resource_pointer, FixedArray* source_cache, int resource_index); Address PrepareCode(); Serializer* serializer_; HeapObject* object_; SnapshotByteSink* sink_; int reference_representation_; int bytes_processed_so_far_; bool code_has_been_output_; }; } // namespace internal } // namespace v8 #endif // V8_SNAPSHOT_SERIALIZER_H_
a8385db8f72ed3796181bdaa13fcaad0f0253399
1191f7d67a5c2629017877c894b8a8290a30d67d
/data-structure/maxheap.h
6a034152bdd795f0820510ffe96fe6e6263f60fa
[]
no_license
moutasdimitris/data-structure
051537fde131a3f1d4f7cfb95943ae77c6dc0083
0d548ab45e80e4aad96afb18f4aff622633de5fa
refs/heads/master
2020-05-18T19:42:22.454288
2019-06-20T19:54:13
2019-06-20T19:54:13
184,614,557
0
0
null
null
null
null
UTF-8
C++
false
false
484
h
// // Created by Windows on 2/5/2019. // #ifndef DATA_STRUCTURE_MAXHEAP_H #define DATA_STRUCTURE_MAXHEAP_H #include <vector> class maxheap { public: maxheap(); int find_max(); void insert(int key); void deleteMax(); int parent(int i); int left_child(int i); int right_child(int i); int getSize(); int print(int i); void swap(int& x, int& y); void max_heap(int i); private: std::vector <int> v; }; #endif //DATA_STRUCTURE_MAXHEAP_H
ae5045977c41a6b609c5b64cb263b4e94af1ff6d
3b9b4049a8e7d38b49e07bb752780b2f1d792851
/src/third_party/WebKit/Source/core/workers/MainThreadWorkletGlobalScope.h
14d4478f89943f38648e6c171749a6a6df24b718
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft" ]
permissive
webosce/chromium53
f8e745e91363586aee9620c609aacf15b3261540
9171447efcf0bb393d41d1dc877c7c13c46d8e38
refs/heads/webosce
2020-03-26T23:08:14.416858
2018-08-23T08:35:17
2018-09-20T14:25:18
145,513,343
0
2
Apache-2.0
2019-08-21T22:44:55
2018-08-21T05:52:31
null
UTF-8
C++
false
false
1,555
h
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MainThreadWorkletGlobalScope_h #define MainThreadWorkletGlobalScope_h #include "core/CoreExport.h" #include "core/dom/ExecutionContext.h" #include "core/frame/LocalFrameLifecycleObserver.h" #include "core/workers/WorkletGlobalScope.h" #include "core/workers/WorkletGlobalScopeProxy.h" namespace blink { class ConsoleMessage; class LocalFrame; class CORE_EXPORT MainThreadWorkletGlobalScope : public WorkletGlobalScope, public WorkletGlobalScopeProxy, public LocalFrameLifecycleObserver { public: ~MainThreadWorkletGlobalScope() override; bool isMainThreadWorkletGlobalScope() const final { return true; } // WorkletGlobalScopeProxy void evaluateScript(const String& source, const KURL& scriptURL) final; void terminateWorkletGlobalScope() final; using LocalFrameLifecycleObserver::frame; void addConsoleMessage(ConsoleMessage*) final; DEFINE_INLINE_VIRTUAL_TRACE() { WorkletGlobalScope::trace(visitor); LocalFrameLifecycleObserver::trace(visitor); } protected: MainThreadWorkletGlobalScope(LocalFrame*, const KURL&, const String& userAgent, PassRefPtr<SecurityOrigin>, v8::Isolate*); }; DEFINE_TYPE_CASTS(MainThreadWorkletGlobalScope, ExecutionContext, context, context->isMainThreadWorkletGlobalScope(), context.isMainThreadWorkletGlobalScope()); } // namespace blink #endif // MainThreadWorkletGlobalScope_h
1268a64845bad508c6bbc05ffd3d636affe33ca2
97eb17ce805e762982c1b09647ea3f251fa0ea0b
/Hoe3D/src/video.h
83da4b73885f99e6293043e2ff0bbce6203a0f07
[]
no_license
HeimdallTeam/Hoe3D
8ca6d434b298773abc3d8c324822df3b97f5d19a
62c6547ee5751ca6da31fa5379c6a0b78bafe5bd
refs/heads/master
2021-01-15T14:24:35.777027
2014-10-03T23:11:14
2014-10-03T23:11:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
328
h
#ifndef _HOE_VIDEO_PLAYER_H_ #define _HOE_VIDEO_PLAYER_H_ #include "hoe_texture.h" class HoeVideoPlayer { public: class HoeVideoTexture * m_tex; public: HoeVideoPlayer(); bool Load(const char * fname); void NextFrame(); const HoeTexture * GetTexture() { return m_tex; } }; #endif // _HOE_VIDEO_PLAYER_H_
9fb9b0637d32c853aa21b6a189e889c419170d0e
182adfdfa907d3efc0395e293dcdbc46898d88eb
/Temp/il2cppOutput/il2cppOutput/AssemblyU2DCSharpU2Dfirstpass_MP_MediaPickerResult2204006871.h
06655d1146870f6165bec11dc24fbeb2b9c27da5
[]
no_license
Launchable/1.1.3New
d1962418cd7fa184300c62ebfd377630a39bd785
625374fae90e8339cec0007d4d7202328bfa03d9
refs/heads/master
2021-01-19T07:40:29.930695
2017-09-15T17:20:45
2017-09-15T17:20:45
100,642,705
0
0
null
null
null
null
UTF-8
C++
false
false
1,313
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "AssemblyU2DCSharpU2Dfirstpass_SA_Common_Models_Res4287219743.h" // System.Collections.Generic.List`1<MP_MediaItem> struct List_1_t3394744161; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // MP_MediaPickerResult struct MP_MediaPickerResult_t2204006871 : public Result_t4287219743 { public: // System.Collections.Generic.List`1<MP_MediaItem> MP_MediaPickerResult::_SelectedmediaItems List_1_t3394744161 * ____SelectedmediaItems_1; public: inline static int32_t get_offset_of__SelectedmediaItems_1() { return static_cast<int32_t>(offsetof(MP_MediaPickerResult_t2204006871, ____SelectedmediaItems_1)); } inline List_1_t3394744161 * get__SelectedmediaItems_1() const { return ____SelectedmediaItems_1; } inline List_1_t3394744161 ** get_address_of__SelectedmediaItems_1() { return &____SelectedmediaItems_1; } inline void set__SelectedmediaItems_1(List_1_t3394744161 * value) { ____SelectedmediaItems_1 = value; Il2CppCodeGenWriteBarrier(&____SelectedmediaItems_1, value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
e72b1a86dd5b700a87bda879c6756256a6656e81
f2a796f122830b3221fc72fc46e259a607279247
/MapSV.h
0b6023db64351195a03c7d0aa02f1f2e8f348cde
[]
no_license
carlops22/estructura-proyecto2
53b020af3417f2bcc1282a797fed6226ee93d589
220bf551ffa1251256c62ae15d66397a988e34a6
refs/heads/main
2023-07-01T11:20:08.690389
2021-08-03T13:30:56
2021-08-03T13:30:56
387,921,324
1
0
null
null
null
null
UTF-8
C++
false
false
422
h
#ifndef MAPSV_H #define MAPSV_H #include <iostream> #include "ADTMap.h" #include<vector> using namespace std; class MapSV: public ADTMap{ private: vector<pair<string,int> > _array; int binBusqueda(string, int, int); int tam; public: MapSV(); ~MapSV(); void insert(pair<string,int>); void erase(string); int at(string); int size(); bool empty(); }; #endif
7213603cec3fc68da47c31ce50333f0823ecacf1
f6afa861caa2a8e03accb2667b3019c79d5de85b
/5. Longest Palindromic Substring.cpp
02b90a54b2151db2b03af93274781a37b1ff3045
[]
no_license
NEU-ZYXi/LeetCode-cpp
7a41c2ba5d857a0296366c5b53720d995c66e69e
95be4fdbfe614d810e131daf5fa0e001b947e6cd
refs/heads/master
2020-10-01T05:21:49.220772
2020-01-13T08:55:26
2020-01-13T08:55:26
227,467,384
0
0
null
null
null
null
UTF-8
C++
false
false
1,305
cpp
class Solution { public: string longestPalindrome(string s) { int n = s.size(); string ans = ""; vector<vector<bool>> dp(n, vector<bool>(n, false)); for (int j = 0; j < n; ++j) { for (int i = j; i >= 0; --i) { if (s[i] == s[j] && (j - i < 2 || dp[i + 1][j - 1])) { dp[i][j] = true; } if (dp[i][j] && ans.size() < j - i + 1) { ans = s.substr(i, j - i + 1); } } } return ans; } }; class Solution { public: string longestPalindrome(string s) { int n = s.size(); if (n < 2) { return s; } int i = 0, start = 0, max_len = 1; while (i < n && n - i > max_len / 2) { int left = i, right = i; while (right < n - 1 && s[right] == s[right + 1]) { right++; } i = right + 1; while (right < n - 1 && left > 0 && s[right + 1] == s[left - 1]) { left--; right++; } if (max_len < right - left + 1) { start = left; max_len = right - left + 1; } } return s.substr(start, max_len); } };
59d2a4ec2f401fa31925a55f19269e505cc1446d
d053e0e8687f122d120bcd0fa1f9076deb35afa5
/Olymp/CF/359/C_gavno.cpp
c559a2cd35f602b55cd4bcd0571878887d7c19e8
[]
no_license
shaihitdin/CP
e8911bc543932866d6fc83eb1d48d9cf79918c61
dc90082f3ebedaccbfb0818cc68539c887f86553
refs/heads/master
2021-01-11T17:10:20.356635
2017-10-05T08:53:56
2017-10-05T08:53:56
79,729,913
1
0
null
null
null
null
UTF-8
C++
false
false
874
cpp
/// Stupido del problemo #include <cstring> #include <vector> #include <map> #include <set> #include <bitset> #include <algorithm> #include <iostream> #include <cstdio> #include <cmath> #include <cassert> #include <cstdlib> #include <ctime> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef long double ld; const double EPS = 1e-9; const double PI = acos(-1); #define mp make_pair #define eb emplace_back #define pb push_back #define fe first #define se second const int oo = 1e9, bpr = 1e9 + 7, N = -1; inline ll calc (ll x, ll y) { } inline ll calc (ll x) { } int main() { #ifdef LOCAL freopen ("in", "r", stdin); #endif ios_base :: sync_with_stdio (0); cin.tie (0); cin >> t; while (t--) { cin >> n; for (int i = 1; i <= n; ++i) for (int j = 0; j < 3; ++j) cin >> p[i][j]; ll l = } return 0; }
2db79b403fbfdabbd21cdda6575f4e2fadbd92da
2e09bfc6c366e9ec1a4ab4c1b7b38ff6065e8796
/Assignment/C++/Lab3/Excerise4.cc
58dde1a7a2b7345f3a9c4c817861cadd9ca1c83e
[]
no_license
seoi2017/SleepWalker
7645b4578f00acc235bdd9018b3ecc1aa8cf47c6
1327041a7621c3049b368e8364b2fb0918d04d56
refs/heads/master
2023-02-11T16:23:06.329864
2021-01-05T14:02:58
2021-01-05T14:02:58
294,626,477
0
0
null
null
null
null
UTF-8
C++
false
false
557
cc
/* Environment: C++11 Course: SUSTech_C++ Problem ID: Lab3_Excerise4 */ #include <bits/stdc++.h> using namespace std; int main() { int a, b, c; double avg; char level; cout << "Enter the quiz, mid-term and fina scores:"; cin >> a >> b >> c; avg = ((double)a + b + c) / 3; if (avg >= 90) level = 'A'; else if (avg >= 70 && avg < 90) level = 'B'; else if (avg >= 50 && avg < 70) level = 'C'; else level = 'F'; printf("average score = %.4f, grade = %c\n", avg, level); return 0; }
e284b8d715c9d38792910e0daf02aa4e445f765f
bb4efc8889d33c147316ff2a2a962478e102bd26
/c/btp300-assignments/a3/a3test.cpp
5ac5877d3770d50ba33b1549030868c99609cbae
[]
no_license
tjduavis/bsd-toolkit
7fd0b24e9c9a72a5a64f80571b7ce01d4a61cd84
80deb263eca001bf23084e84db99c8cf02a0a333
refs/heads/master
2016-09-09T17:19:31.431634
2013-07-07T06:37:31
2013-07-07T06:37:31
11,229,216
1
1
null
null
null
null
UTF-8
C++
false
false
12,080
cpp
/*************************************************************************\ * File: a3test.cpp * * Originally written by Evan Weaver * * 18 Oct 2004 * * Updated by Chris Szalwinski * * 30 Oct 2005 * * Version 2.0 * * * * This is a test program for the classes in BTP300's third assignment. * * Compile this program with your console I/O routines and classes. * * For example, * * bcc32 a3main.cpp dtio.c Screen.cpp (Borland) * * cl a3main.cpp dtio.c Screen.cpp (VS .net) * * c++ -o a3main a3main.cpp dtio.c Screen.cpp -lcurses (AIX) * * c++ -o a3main a3main.cpp dtio.c Screen.cpp -lncurses (Linux) * * should probably work for you. * * * * Note that this program cannot verify that your routines are correct - * * you must run the program and observe whether or not it is working * * correctly. * * * * In particular, there are many little variations that are not tested but * * for which you are responsible. Just because your program passes this * * test does not mean that your program works perfectly. Your instructor * * will look especially closely at the code that isn't tested here. * * * * Be sure to check for updates every day until the due date, just in case * * there is some problem, er, ah, issue that needs to be addressed. * * * * IMPORTANT: if you changed the dtio code at all, you should document the * * changes, and provide the assignment 1 and 2 test results as well as the * * assignment 3 executables (i.e. you need to demonstrate that you did not * * break the assignment 2 code in getting this assignment code to work). * \*************************************************************************/ #include <cstdio> #include <cstring> using namespace std; #include "Screen.h" // newFie is derived from Field in order to test whether clone() does // what we shall need it to do in the future. class newFie: public Field { int row; int col; int len; bool edi; public: newFie(int r, int c, int l, const char *s = "", bool ed = true): Field(r, c, l, s, ed) { row = r; col = c; len = l; edi = ed; } Field *clone() const { return new newFie(row, col, len, "Derived cloning is ok", edi); } }; // message displays status messages on line 19 void message(const char *s) { dtioDisplay(s, 19, 5, 50); } // keyMessage returns a description of key code "key" that should be // used immediately: its address should not be stored for later use const char *keyMessage(int key) { int keys[] = {UP, DOWN, LEFT, RIGHT, PGUP, PGDN, ENTER, TAB, BACKSPACE, DEL, HOME, END, ESCAPE, INSERT, F(1), F(2), F(3), F(4), F(5), F(6), F(7), F(8), F(9), F(10), F(11), F(12) }; char *names[] = {"Up Arrow", "Down Arrow", "Left Arrow", "Right Arrow", "Page Up", "Page Down", "Enter", "Tab", "Backspace", "Delete", "Home", "End", "Escape", "Insert", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12"}; const int nKeys = 26; static char s[30]; if (' ' <= key && key <= '~') { // printable ASCII key s[0] = key; s[1] = '\0'; } else { // non-printable or non-ASCII key int i = 0; while (i < nKeys && key != keys[i]) i++; if (i < nKeys) strcpy(s, names[i]); else sprintf(s, "Unknown key : code %d", key); } return s; } // prompt displays the prompt for the tester on line 23 void prompt(const char* s) { dtioDisplay(s, 23, 9, 45); } // pause void pause() { prompt("Press any key to continue ... "); dtioGetchar(); prompt(""); } // displays on the "status line" a description of key followed by a message. void dispMessage(int key, char *s) { char msg[81]; sprintf(msg, "Key pressed <%s> %s", keyMessage(key), s); message(msg); } // result displays the result for the tester in column 55 void result(int row, const char* s) { dtioDisplay(s, row, 55, 24); } // check checks whether a field works correctly by letting the user edit it // and then displaying the key used to exit editing and the edited contents // on the "status line". void check(Field &f) { int key = f.edit(); dispMessage(key, (char *)f.data()); } // fieldTest tests the field class void fieldTest() { dtioDisplay("PERFORMING FIELD TESTS", 1, 29, 22); Field one(-10, -15, 17, "Upper Left CornerXXXX", false); // at (0, 0) result(4, "1 constructed"); Field two(2, 4000, 300, "Help!", false); // length 1! result(5, "2 constructed"); Field three(10, 10, 12, "Edit this : ", false); // normal label result(6, "3 constructed"); Field four(10, 22, 15, "This is a test of a Field");// This is a test result(7, "4 constructed"); Field five(four); // initially a copy of four result(8, "5 constructed"); Field six(13, 5, 4); // initially empty result(9, "6 constructed"); Field seven(17, 5, 6, "Done ?", false); // normal label result(10, "7 constructed"); Field eight(17, 12, 1, "n", true); // used to exit test loop result(11, "8 constructed"); newFie nine(5, 30, 25, "Derived Field", false); // test derived field result(12, "9 constructed"); Field *pten; // test clone() if (NULL == (pten = nine.clone())) // testing clone() message("Clone failed"); else { if (strcmp((char *)pten->data(), "Derived cloning is ok")) message("Clone incorrect"); else result(13, "cloning tested"); // see if editable() is doing the right thing if (one.editable() || two.editable() || !four.editable() || !eight.editable() || pten->editable()) message("editable() is incorrect"); else result(14, "editable() tested"); // make sure field two that doesn't fit was correctly placed - // "two" should start at the end of row 3, hence is 1 char long dtioDisplay("Should be an H here->", 2, dtioColumns() - 22, 21); // make sure non-editable fields can't be edited if (0 != one.edit() || 0 != two.edit() || 0 != three.edit()) message("Incorrect return value from non-edit edit()"); else result(15, "non-editable tested"); // show all ten fields one.display(); two.display(); three.display(); four.display(); five.display(); // overwrites four six.display(); seven.display(); eight.display(); nine.display(); pten->display(); // overwrites nine // edit each editable field in turn. bool first = true; dtioDisplay("^Field 1", 1, 0, 8); dtioDisplay("Field 2^", 3, dtioColumns() - 8, 8); dtioDisplay("^Field 3", 11, 10, 8); dtioDisplay("Field^7", 18, 0, 7); dtioDisplay("^Field 8", 18, 12, 8); do { // change four so it contains different data than five strcpy((char *)four.data(), "edit this!"); dtioDisplay("^Field 4", 11, 22, 8); prompt("Change the contents of Field 4 above"); check(four); dtioDisplay("", 11, 20, 25); dtioDisplay("^Field 5", first ? 11 : 14, first ? 22 : 5, 25); prompt("Change the contents of Field 5 above"); check(five); dtioDisplay("", first ? 11 : 14, first ? 20 : 5, 25); five = six; // next time five will be a copy of previous six if (first) dtioDisplay("^Field 6", 14, 5, 8); prompt("Enter something into Field 6 above"); check(six); prompt("Enter \'y\' into Field 8 to exit"); check(eight); prompt(""); first = false; // no longer the first time through this loop } while (*(char *)eight.data() != 'y'); delete pten; dtioDisplay("", 1, 0, 8); dtioDisplay("", 4, dtioColumns() - 8, 8); dtioDisplay("", 11, 10, 8); dtioDisplay("", 14, 5, 8); dtioDisplay("", 18, 0, 7); dtioDisplay("", 18, 12, 8); } result(16, "Field Tests Completed"); dtioDisplay("", 1, 29, 21); } // screenTest tests the Screen class void screenTest() { dtioDisplay("PERFORMING SCREEN TESTS", 1, 29, 23); Screen s1; int keyPressed; if (1 != s1.add(10, 30, 25, "Test Screen", false)) message("first add() has a problem"); else if (2 != s1.add(13, 10, 5, "Name:XXX", false)) message("second add() has a problem"); else if (3 != s1.add(13, 18, 30)) message("third add() has a problem"); else if (3 != s1.remove(-1)) message("first remove() has a problem"); else { s1.display(false); result(18, "three fields displayed"); pause(); // ensure that screens are copied OK Screen s2 = s1; result(19,"screen copied"); prompt("Enter something into the Name field above"); keyPressed = s1.edit(false); dispMessage(keyPressed, (char *)s1.getField(2)->data()); prompt(""); // change contents of field for next time strcpy((char *)s1.getField(2)->data(), "<-Name: should be gone"); result(20, "last field altered"); // remove the Name: label (field number 1) - the editable // field should now become field 1 if (2 == s1.remove(1)) { dtioDisplay("", 13, 10, 5); prompt("Edit the \'<-Name ...\' field above"); keyPressed = s1.edit(false); dispMessage(keyPressed, (char *)s1.getField(1)->data()); prompt(""); } else message("remove() has a problem"); result(21, "remove & edit tested"); } // lets make another screen, using += instead of add() Screen s3; // make sure that += returns a reference to the screen (s3 += Field(3, 20, 20, "Last Test", false)) += Field(5, 5, 4, "URL:", false); s3 += Field(5, 15, 40); s3 += Field(8, 5, 10, "IP Addr:", false); s3 += Field(8, 15, 40); s3 += Field(15, 5, 50, "", false); int field = 0; bool keepon = true; // const char *menu[] = {"Exit the program", "Continue editing"}; // do a data entry screen where only Enter (on the last editable // field) or Escape will stop the program, asking for user // confirmation before exiting. s3.display(false); prompt("Enter URL and IP Addr Fields, F1 for help"); do { switch (keyPressed = s3.edit(&field, false)) { case F(1): // used as a "help" key strcpy((char *)s3.getField(5)->data(), field == 2 ? "e.g. http://www.hahaha.com" : field == 4 ? "e.g. 123.123.123.2" : "Something is wrong!"); break; case ENTER: case ESCAPE: // exit keepon = false; break; default: // otherwise, just show the last key press and edit value strcpy((char *)s3.getField(5)->data(), keyMessage(keyPressed)); } } while (keepon); prompt(""); pause(); dtioDisplay("", 1, 29, 23); dtioDisplay("Screen Tests Completed", 22, 55, 22); message("Prepare a screen shot if the results look correct"); pause(); // done - let's get out and show the edited data on standard output. dtioStop(); printf("Host %s is %s\n", (char *)s3.getField(2)->data(), (char *)s3.getField(4)->data()); } int main() { dtioStart(); dtioClear(); if (dtioRows() < 20 || dtioColumns() < 60) { dtioStop(); printf("Screen is too small - need 20x60\n"); } else { dtioDisplay("Prompt : ", 23, 0, 9); fieldTest(); screenTest(); // dtioStop() is called here } return 0; }
7c724f8a34235e3a3f488e4c843d9ac07c8f7f2c
7e5be101928eb7ea43bc1a335d3475536f8a5bb2
/ACM - Onsite Contests/2013 Invitational/13成都邀请赛/K.cpp
358eddb3f09f8dc9551a56337c22945a89450212
[]
no_license
TaoSama/ICPC-Code-Library
f94d4df0786a8a1c175da02de0a3033f9bd103ec
ec80ec66a94a5ea1d560c54fe08be0ecfcfc025e
refs/heads/master
2020-04-04T06:19:21.023777
2018-11-05T18:22:32
2018-11-05T18:22:32
54,618,194
0
2
null
null
null
null
UTF-8
C++
false
false
2,021
cpp
// // Created by TaoSama on 2015-05-11 // Copyright (c) 2015 TaoSama. All rights reserved. // #include <algorithm> #include <cctype> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <string> #include <set> #include <vector> using namespace std; const int INF = 0x3f3f3f3f; const int MOD = 1e9 + 7; const int N = 1e6 + 10; int a[10], b[10]; char ss[N], tt[N]; void output() { for(int i = 0; i <= 9; ++i) cout << i << ' '; cout << endl; for(int i = 0; i <= 9; ++i) cout << a[i] << ' '; cout << endl; for(int i = 0; i <= 9; ++i) cout << b[i] << ' '; cout << endl; } int getFirst() { for(int k = 9; k >= 0; --k) { for(int i = 1; i <= 9; ++i) { for(int j = 1; j <= 9; ++j) { if((i + j) % 10 == k && a[i] && b[j]) { --a[i]; --b[j]; printf("%d", k); return k; } } } } return 10; } void getOther() { for(int k = 9; k >= 0; --k) { for(int i = 0; i <= 9; ++i) { for(int j = 0; j <= 9; ++j) { while((i + j) % 10 == k && a[i] && b[j]) { printf("%d", k); --a[i]; --b[j]; } } } } } int main() { #ifdef LOCAL freopen("in.txt", "r", stdin); // freopen("out.txt","w",stdout); #endif ios_base::sync_with_stdio(0); int t; scanf("%d", &t); int kase = 0; while(t--) { memset(a, 0, sizeof a); memset(b, 0, sizeof b); scanf("%s%s", ss, tt); for(int i = 0; ss[i]; ++i) { a[ss[i] - '0']++; b[tt[i] - '0']++; } //output(); printf("Case #%d: ", ++kase); //if(strlen(ss) == 1) // printf("%d", (ss[0] + tt[0] - 2 *'0') % 10); if(getFirst()) getOther(); printf("\n"); } return 0; }
b9b78c8087a7a17ad35115bc015f8846fa0f83bc
16d5cd8328ff8b31334afac4030754e59151c376
/source/http/header_names.h
38ba3f31f1e4daa669b794e6d82f8a25099b1aec
[ "MIT" ]
permissive
TorstenRobitzki/Sioux
c443083677b10a8796dedc3adc3f950e273758e5
709eef5ebab5fed896b0b36f0c89f0499954657d
refs/heads/master
2023-03-31T18:44:55.391134
2023-03-16T06:51:56
2023-03-16T06:51:56
5,154,565
19
9
MIT
2023-03-16T06:51:57
2012-07-23T16:51:12
C++
UTF-8
C++
false
false
612
h
// Copyright (c) Torrox GmbH & Co KG. All rights reserved. // Please note that the content of this file is confidential or protected by law. // Any unauthorised copying or unauthorised distribution of the information contained herein is prohibited. #ifndef SIOUX_SOURCE_HEADER_NAMES_H_ #define SIOUX_SOURCE_HEADER_NAMES_H_ namespace http { extern const char * const content_type_header; extern const char * const content_length_header; extern const char * const transfer_encoding_header; extern const char * const application_x_www_from_urlencded; } #endif /* SIOUX_SOURCE_HEADER_NAMES_H_ */
088851b360f0082f69e182343adbd0bdc967a5dc
1fe303a22628d325138e592d56a6060a95d029fc
/lab04/src/main.cpp
9887a86d96bc190a7850e956ff5b8b73a4624eab
[]
no_license
wcdbmv/TDS
1b31dc9a12b7165d50f707fb44451d4fd6cfe5a9
4f7296e0f3ba797cd2066c65e0501f5828ad19c8
refs/heads/master
2020-12-04T11:19:19.044252
2020-01-04T10:23:05
2020-01-04T10:23:05
231,743,951
0
0
null
null
null
null
UTF-8
C++
false
false
477
cpp
#include "calculator.h" int main() { std::string s(' ', 100); Calculator c("array"); double d = 0; while (std::cout << "\033[1;1H\033[J>>> ", std::getline(std::cin, s) && s != "exit") { d = c.calculate(s); if (d == DIVISION_BY_ZERO) std::cout << "[Division by zero]\n"; else if (d == DOUBLE_ERR) std::cout << "[Error while pars arg]\n"; else if (d != INFIX_ERR) std::cout << "\033[1;1H\033[JResult: " << d; puts("\n\n<press enter>"); getchar(); } }
b228d17431f164faf90a875652e5f5ea6b2fce24
d5f6d50de5d9c7bebe276948ede77bb95a8835bc
/c++/程序/第1章程序/s1_4/main.cpp
601cfc5bc56cf64df1995b25c4c890201109dd55
[]
no_license
cristiano-xw/c-plus
d54a1cd7f491cace6757f1dc46f5ebcae29a7e11
ea6d14cf1f1e60b3322a97c04d300af657e7b210
refs/heads/master
2023-06-28T08:51:49.628562
2021-08-02T03:18:53
2021-08-02T03:18:53
329,774,618
0
0
null
null
null
null
GB18030
C++
false
false
422
cpp
// 文件路径名:s1_4\main.cpp #include <iostream> using namespace std; int i=10; void fun() { int i=20; printf("局部变量 i=%d",i); //访问局部变量i printf(" ,全局变量 i=%d",::i); //访问全局变量i,在C语言中, //由于定义了局部变量 i,无法在 fun()函数内访问同名全局变量 i } int main() { fun(); return 0; // 返回值0, 返回操作系统 }
98ed8ac925ef912ab1bbb38892e3b025b42d6189
53cf1c2988bb33e93e14146aecd0821e1655f23c
/1/098_good.cpp
f6e10e69050827abb22cbcc54e3c340c2029e284
[]
no_license
cblhxx/leetcode
9d9a2e3bf4e8c0e19356616b7e8d14e5a66de380
5124bcdb5537851a1b70c7998d68d4d2ecca7db4
refs/heads/master
2020-05-23T09:46:20.364862
2019-06-26T12:02:52
2019-06-26T12:02:52
186,713,473
0
0
null
null
null
null
UTF-8
C++
false
false
745
cpp
#include <iostream> #include <vector> #include <unordered_map> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: bool solve(TreeNode* node, TreeNode* &prev) { if (node == NULL) return true; if (!solve(node->left, prev)) return false; if (prev != NULL && prev->val >= node->val) return false; return solve(node->right, node); } bool isValidBST(TreeNode* root) { if (root == NULL) return true; TreeNode* prev = NULL; return solve(root, prev); } }; int main() { Solution s; return 0; }
c8ad1f4202c4a5d25d1ffad8f539d341b2d2c49c
b04c15e0d61733c25159faf90cff79804e99171f
/TestCase/utilityLibrary/Encryption.h
2d790a692677d74ce33704a374213bbc02a240ed
[]
no_license
caowenjian/BJ
eb884de109c0d3d617fc67b6e114b8bbdbb24a04
497d1ba3252d21100ff5bfcd3fd0a86d9469725d
refs/heads/master
2021-07-16T04:58:09.376681
2020-09-11T09:13:29
2020-09-11T09:13:36
75,891,413
0
0
null
null
null
null
UTF-8
C++
false
false
231
h
#ifndef _ENCRTPTION_H #define _ENCRTPTION_H #include "globalDefine.h" NAMESPACE_BEGIN_T(utilityLibrary) UTILITYLIBRARY_API VTT_VOID Base64Encode(const std::string& input,std::string& output); NAMESPACE_END_T(utilityLibrary) #endif
ec2c2ed3001bd007c7b3c2144272c7a729a2a436
f1f41bdba4ab92c96f3d61ecb23abdc1f22cb46f
/IF/Classes/view/popup/DailyRwdView.cpp
1b8e88f7015a4b8cc3e94e362afbe626fada4dbc
[]
no_license
lineCode/dc208
fb1b9cc364e67e8728537a4d701493fef05359bf
b2e2ed7665289b29bed9b205d79cc7453d209e0b
refs/heads/master
2020-12-02T21:17:39.622688
2016-07-22T06:00:36
2016-07-22T06:00:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
53,983
cpp
// // DailyRwdView.cpp // IF // // Created by xxrdsg on 14-12-31. // // #include "DailyRwdView.h" #include "UIComponent.h" #include "PopupViewController.h" #include "ParticleController.h" #include "ToolController.h" #include "ActivityController.h" #include "RewardController.h" #include "TipsView.h" #include "UseToolView.h" #include "SoundController.h" #include "UserBindCommand.h" #include "FBUtilies.h" #include "YesNoDialog.h" #include "FeedRecordCommand.h" #include <spine/Json.h> #include "FunBuildController.h" #include "ChestUseView.h" #include "GuideController.h" DailyRwdView::DailyRwdView():m_touchNode(NULL),m_bgNode(NULL),m_scrollView(NULL){ ignoreAnchorPointForPosition(false); setAnchorPoint(Vec2(0,0)); CCSafeNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(DailyRwdView::afterGetFriendsInfo), MSG_FBFriendsList, NULL); CCSafeNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(DailyRwdView::loginSuccess), MSG_FBLoginSucess, NULL); CCSafeNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(DailyRwdView::bindSuccess), MSG_USER_BIND_OK, NULL); CCSafeNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(DailyRwdView::getInviteFriends), MSG_FBIviteFriends, NULL); CCSafeNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(DailyRwdView::getRequestFriends), MSG_FBRequestResult, NULL); } DailyRwdView::~DailyRwdView(){ CCSafeNotificationCenter::sharedNotificationCenter()->removeObserver(this, MSG_FBFriendsList); CCSafeNotificationCenter::sharedNotificationCenter()->removeObserver(this, MSG_FBIviteFriends); CCSafeNotificationCenter::sharedNotificationCenter()->removeObserver(this, MSG_FBLoginSucess); CCSafeNotificationCenter::sharedNotificationCenter()->removeObserver(this, MSG_USER_BIND_OK); CCSafeNotificationCenter::sharedNotificationCenter()->removeObserver(this, MSG_FBRequestResult); } void DailyRwdView::afterGetFriendsInfo(CCObject* param){ GameController::getInstance()->removeWaitInterface(); CCArray* friends = dynamic_cast<CCArray*>(param); if (friends) { m_friendDatas->removeAllObjects(); int num = friends->count(); string ids = ""; for (int i=0; i<num; i++) { auto dic = _dict(friends->objectAtIndex(i)); if(dic){ FBFriendInfo* info = FBFriendInfo::create(); info->id = dic->valueForKey("id")->getCString(); info->isCheck = true; info->name = dic->valueForKey("name")->getCString(); info->url = CCString::createWithFormat("https://graph.facebook.com/%s/picture?type=square",dic->valueForKey("id")->getCString())->getCString(); string devices = dic->valueForKey("devices")->getCString(); m_friendDatas->addObject(info); } } }else{ string installFriendsInfo = CCUserDefault::sharedUserDefault()->getStringForKey("installFriendsInfo", ""); if(installFriendsInfo!=""){ GlobalData::shared()->installFriendsInfo = installFriendsInfo; Json* fjson = Json_create(installFriendsInfo.c_str()); if (fjson) { int size = Json_getSize(fjson); CCLog("parse installFriendsInfo =%s",installFriendsInfo.c_str()); for (int i=0; i<size; i++) { Json *item = Json_getItemAt(fjson, i); string name = Json_getString(item,"name",""); string id = Json_getString(item,"id",""); string url = ""; FBFriendInfo* info = FBFriendInfo::create(); info->id = id; info->isCheck = true; info->name = name; info->url = CCString::createWithFormat("https://graph.facebook.com/%s/picture?type=square",id.c_str())->getCString(); m_friendDatas->addObject(info); } Json_dispose(fjson); } } } addFriends(); m_count += 1; } void DailyRwdView::loginSuccess(CCObject* p){ string m_facebookUid =CCUserDefault::sharedUserDefault()->getStringForKey("tmpFaceBook_uid", ""); if (m_facebookUid == "") { return; } string preuid = CCUserDefault::sharedUserDefault()->getStringForKey(FB_USERID,""); if(preuid!="" && preuid!=m_facebookUid){ CCCommonUtils::flyHint("", "", _lang("107078")); FBUtilies::fbLogout();//不是同一个号 return ; } string preuName = CCUserDefault::sharedUserDefault()->getStringForKey("tmpFaceBook_Name",""); string m_facebookName = CCUserDefault::sharedUserDefault()->getStringForKey("tmpFaceBook_Name",""); UserBindCommand* cmd = new UserBindCommand("",m_facebookUid,"","","",1,preuid,"",m_facebookName,preuName); cmd->sendAndRelease(); GameController::getInstance()->showWaitInterface(); } void DailyRwdView::bindSuccess(CCObject* p){ this->unschedule(schedule_selector(DailyRwdView::checkFriend)); this->schedule(schedule_selector(DailyRwdView::checkFriend),0.35); FBUtilies::getFBFriendList(); FBUtilies::inviteFriends(); } void DailyRwdView::getInviteFriends(CCObject* param){ if( getParent() == NULL ) return; GameController::getInstance()->removeWaitInterface(); CCArray* inviteFriends = dynamic_cast<CCArray*>(param); if(inviteFriends){ int num = inviteFriends->count(); string ids = ""; for (int i=0; i<num; i++) { auto dic = _dict(inviteFriends->objectAtIndex(i)); if(dic){ FBFriendInfo* info = FBFriendInfo::create(); info->id = dic->valueForKey("id")->getCString(); info->isCheck = true; info->name = dic->valueForKey("name")->getCString(); info->url = CCString::createWithFormat("https://graph.facebook.com/%s/picture?type=square",dic->valueForKey("id")->getCString())->getCString(); m_inviteDatas->addObject(info); } } }else{ string info = CCUserDefault::sharedUserDefault()->getStringForKey("inviteFriends", ""); if(info!=""){ GlobalData::shared()->inviteFriendsInfo = info; string friends = info; if(friends!=""){ Json* fjson = Json_create(friends.c_str()); CCLog("parse inviteFriends info =%s",info.c_str()); if (fjson) { int size = Json_getSize(fjson); for (int i=0; i<size; i++) { Json *item = Json_getItemAt(fjson, i); string name = Json_getString(item,"name",""); string id = Json_getString(item,"id",""); FBFriendInfo* info = FBFriendInfo::create(); info->id = id; info->isCheck = true; info->name = name; info->url = CCString::createWithFormat("https://graph.facebook.com/%s/picture?type=square",id.c_str())->getCString(); m_inviteDatas->addObject(info); } Json_dispose(fjson); } } } } addFriends(); m_count += 1; } void DailyRwdView::getRequestFriends(CCObject *data){ string fbRequestId = CCUserDefault::sharedUserDefault()->getStringForKey(FB_RequestID,""); int result = CCUserDefault::sharedUserDefault()->getIntegerForKey(FB_RequestResult, -1); //1成功 2错误 3取消 m_requestId = fbRequestId; if(m_requestId==""){ CCLog("m_requestId is null"); return ; } m_requestId.append("_feed"); string link(FB_LINK); link.append(m_requestId); int index = GlobalData::shared()->getRand(1,3); string fbIcon = getFBIcon(index); string caption = _lang("111076"); if(caption==""){ caption = _lang("107088"); } string desc = _lang("111076"); if(desc==""){ desc = _lang("107087"); } CCLog("fb fbRequestId=%s",fbRequestId.c_str()); //FBUtilies::fbPublishFeedDialog("Clash Of Kings",caption,desc,link,fbIcon,1); FeedRecordCommand* cmd = new FeedRecordCommand(fbRequestId); cmd->sendAndRelease(); this->getDailyReward(); } DailyRwdView* DailyRwdView::create(int type) { DailyRwdView* ret = new DailyRwdView(); if(ret && ret->init(type)){ ret->autorelease(); }else{ CC_SAFE_DELETE(ret); } return ret; } bool DailyRwdView::init(int type) { CCLoadSprite::doResourceByCommonIndex(11, true); setCleanFunction([](){ CCLoadSprite::doResourceByCommonIndex(11, false); }); CCNode* bg =NULL; m_viewType = type; if(m_viewType==1){ bg = CCBLoadFile("qiandaoPopView",this,this); GameController::getInstance()->callXCApi("action=loginDay_7rwd_pop"); FBUtilies::addEvent_loginDay_7rwd_pop(); m_selectBtn->setTouchPriority(0); m_friendBtn->setTouchPriority(0); m_rwdBtn->setTouchPriority(0); m_friendBtn->setOpacity(20); m_rwdBtn->getBackgroundSpriteForState(cocos2d::extension::Control::State::DISABLED)->setState(cocos2d::ui::Scale9Sprite::State::GRAY);//fusheng add }else{ bg = CCBLoadFile("qiandaoView",this,this); FBUtilies::addEvent_loginDay_7rwd_click(); GameController::getInstance()->callXCApi("action=loginDay_7rwd_click"); int dh = CCDirector::sharedDirector()->getWinSize().height - 852; if (CCCommonUtils::isIosAndroidPad()) { dh = CCDirector::sharedDirector()->getWinSize().height - 2048; } m_scNode->setPositionY(m_scNode->getPositionY() - dh); m_scNode->setContentSize(CCSize(m_scNode->getContentSize().width, m_scNode->getContentSize().height + dh)); if (PortActController::getInstance()->m_isNewTimeRwd ) { m_scNode->setContentSize(CCSize(m_scNode->getContentSize().width, m_scNode->getContentSize().height + 87)); m_shipPicNode->setPositionY(m_shipPicNode->getPositionY() + 87); } auto tsize = m_listNode->getContentSize(); // m_listBg->setPreferredSize(CCSize(tsize.width + 30, tsize.height + 35)); // m_bottomNode->setPositionY(m_bottomNode->getPositionY() - dh); if(m_bgNode){ m_bgNode->setPositionY(m_bgNode->getPositionY() - dh); auto tbg = CCLoadSprite::loadResource("bg0.png"); auto tBatchNode = CCSpriteBatchNode::createWithTexture(tbg->getTexture()); auto pic = CCLoadSprite::createSprite("bg0.png"); int maxHeight = CCDirector::sharedDirector()->getWinSize().height - pic->getContentSize().height+1100; int curHeight = 0; while(curHeight < maxHeight) { auto pic2Left = CCLoadSprite::createSprite("bg0.png"); pic2Left->setAnchorPoint(ccp(0, 0)); pic2Left->setPosition(ccp(0, curHeight)); tBatchNode->addChild(pic2Left); auto pic2Right = CCLoadSprite::createSprite("bg0.png"); pic2Right->setScaleX(-1); pic2Right->setAnchorPoint(ccp(1, 0)); pic2Right->setPosition(ccp(320, curHeight)); if (CCCommonUtils::isIosAndroidPad()) { pic2Left->setScaleX(2.4); pic2Right->setScaleX(2.4); pic2Right->setPosition(ccp(768, curHeight)); } tBatchNode->addChild(pic2Right); curHeight += pic2Left->getContentSize().height; } auto pic1Left = CCLoadSprite::createSprite("bg0.png"); curHeight = CCDirector::sharedDirector()->getWinSize().height - 300 - pic1Left->getContentSize().height; pic1Left->setPosition(ccp(0, curHeight)); pic1Left->setAnchorPoint(ccp(0, 0)); tBatchNode->addChild(pic1Left); auto pic1Right = CCLoadSprite::createSprite("bg0.png"); pic1Right->setScaleX(-1); pic1Right->setPosition(ccp(320, curHeight)); if (CCCommonUtils::isIosAndroidPad()) { pic1Left->setScaleX(2.4); pic1Right->setScaleX(2.4); pic1Right->setPosition(ccp(768, curHeight)); } pic1Right->setAnchorPoint(ccp(1, 0)); tBatchNode->addChild(pic1Right); tBatchNode->setPosition(0, 0); m_bgNode->addChild(tBatchNode); if(CCCommonUtils::isIosAndroidPad()) { tBatchNode->setScaleX(1536/640); } } m_selectBtn->setTouchPriority(Touch_Popup); m_friendBtn->setTouchPriority(Touch_Popup); m_rwdBtn->setTouchPriority(Touch_Popup); m_rwdBtn->getBackgroundSpriteForState(cocos2d::extension::Control::State::DISABLED)->setState(cocos2d::ui::Scale9Sprite::State::GRAY);//fusheng add m_scrollView = CCScrollView::create(m_scNode->getContentSize()); m_scrollView->setDirection(kCCScrollViewDirectionVertical); m_scrollView->setTouchPriority(Touch_Popup); m_scNode->addChild(m_scrollView); m_moveNode->removeFromParent(); m_moveNode->setPosition(320, 750); // if (CCCommonUtils::isIosAndroidPad()) // { // m_moveNode->setPosition(768, 0); // } m_scrollView->addChild(m_moveNode); m_scrollView->setContentSize(CCSize(m_scNode->getContentSize().width,900));//1350 m_scrollView->setContentOffset(ccp(0, m_scNode->getContentSize().height - 900)); // if (CCCommonUtils::isIosAndroidPad()) // { // m_scrollView->setContentSize(CCSize(m_scNode->getContentSize().width,600)); // m_scrollView->setContentOffset(ccp(0, m_scNode->getContentSize().height - 600)); // } if(m_tipTxt1){ m_tipTxt1->setString(_lang("111073")); } if(m_tipTxt2){ m_tipTxt2->setString(_lang("111074")); int h = 620 + m_tipTxt2->getContentSize().height * m_tipTxt2->getOriginScaleY(); m_moveNode->setPosition(320, h); m_scrollView->setContentSize(CCSize(m_scNode->getContentSize().width, h + 160));//1350 m_scrollView->setContentOffset(ccp(0, m_scNode->getContentSize().height - h - 160)); } m_tipTxt3->setString(_lang("111067")); m_tipTxt3->setVisible(false); m_selectBtn->setOpacity(20); m_friendBtn->setOpacity(20); } m_listPositionNodes->setVisible(false); m_friendTxt->setString(_lang("111064")); m_selectBtn->setSelected(true); m_selectSpr->setVisible(m_selectBtn->isVisible()); m_vipLabel->setString(_lang("111072")); setContentSize(bg->getContentSize()); m_friendNode->setVisible(false); m_data = CCArray::create(); m_tabView = CCMultiColTableView::create(this, m_listNode->getContentSize()); m_tabView->setDirection(kCCScrollViewDirectionVertical); m_tabView->setVerticalFillOrder(kCCTableViewFillTopDown); m_tabView->setMultiColTableViewDelegate(this); m_tabView->setTouchPriority(Touch_Popup_Item); m_listNode->addChild(m_tabView); m_waitInterface1 = NULL; m_waitInterface2 = NULL; CCCommonUtils::setButtonTitle(m_rwdBtn, _lang("111052").c_str()); m_itemId = PortActController::getInstance()->m_loginDay; if (PortActController::getInstance()->m_isRdLoginDay == 0 && PortActController::getInstance()->m_isVipRdLoginDay == 0) {//今天没有领取 if (m_itemId < PortActController::getInstance()->m_loginDayMap.size()) { m_itemId += 1; } } m_friendDatas = CCArray::create(); m_inviteDatas = CCArray::create(); m_showDatas = CCArray::create(); m_count = 0; m_sendId = ""; m_inviteNum = 0; m_notInstallNum = 0; m_installNum = 0; bool bVip = !GlobalData::shared()->isXiaoMiPlatForm(); string fbUid = CCUserDefault::sharedUserDefault()->getStringForKey(FB_USERID,""); if(FBUtilies::fbIsLogin() && fbUid!="" && !GlobalData::shared()->isXiaoMiPlatForm()){ this->unschedule(schedule_selector(DailyRwdView::checkFriend)); this->schedule(schedule_selector(DailyRwdView::checkFriend),0.5); FBUtilies::getFBFriendList(); FBUtilies::inviteFriends(); if(bVip==true && m_viewType==1){ bVip=false; } m_infoNode->setVisible(true); }else{ m_infoNode->setVisible(false); } m_vipLabel->setVisible(bVip); return true; } void DailyRwdView::checkFriend(float t_time){ if (m_count>=2) { this->unschedule(schedule_selector(DailyRwdView::checkFriend)); this->initFriend(); } } void DailyRwdView::resetTabViewPos() { int allLineNum = ceil(PortActController::getInstance()->m_loginDayMap.size() / 5.0); int curLine = (m_itemId - 1) / 5 + 1; int showLineNum = m_listNode->getContentSize().height / gridSizeForTable(NULL).height; if (curLine <= showLineNum) { m_tabView->setContentOffset(ccp(0, m_listNode->getContentSize().height - m_tabView->getContentSize().height)); } else { if (allLineNum - showLineNum < curLine) { m_tabView->setContentOffset(ccp(0, 0)); } else { m_tabView->setContentOffset(ccp(0, m_listNode->getContentSize().height - (allLineNum - curLine + 1) * gridSizeForTable(NULL).height)); } } m_friendNode->setVisible(false); } bool DailyRwdView::onTouchBegan(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent) { if(m_viewType==1 && m_touchNode) { return true; } return false; } void DailyRwdView::onTouchEnded(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent) { if(m_viewType==1 && m_touchNode) { if (!isTouchInside(m_touchNode, pTouch)) { CCSafeNotificationCenter::sharedNotificationCenter()->postNotification(MSG_CLOSING_RechargeACTVCell); PopupViewController::getInstance()->removeAllPopupView(); } } } void DailyRwdView::onTouchMoved(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent){ } void DailyRwdView::onEnter(){ CCNode::onEnter(); CCSafeNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(DailyRwdView::onRmvWaitInter1), PORT_LOGINRD_END, NULL); CCSafeNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(DailyRwdView::onRmvWaitInter2), PORT_VIP_LOGINRD_END, NULL); generateData(NULL); refreshRDData(); refreshTitle(); refreshBtnState(); resetTabViewPos(); if(m_viewType==1){ setSwallowsTouches(false); setTouchMode(Touch::DispatchMode::ONE_BY_ONE); setTouchEnabled(true); //CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, Touch_Default,false); } } void DailyRwdView::onExit(){ if (m_waitInterface1 != NULL) { m_waitInterface1->remove(); m_waitInterface1 = NULL; } if (m_waitInterface2 != NULL) { m_waitInterface2->remove(); m_waitInterface2 = NULL; } GlobalData::shared()->isBind = false; CCSafeNotificationCenter::sharedNotificationCenter()->removeObserver(this, PORT_LOGINRD_END); CCSafeNotificationCenter::sharedNotificationCenter()->removeObserver(this, PORT_VIP_LOGINRD_END); setTouchEnabled(false); this->unschedule(schedule_selector(DailyRwdView::checkFriend)); //CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this); CCNode::onExit(); } void DailyRwdView::generateData(CCObject *p) { m_data->removeAllObjects(); m_listNode->removeAllChildrenWithCleanup(true); CCSafeObject<CCSprite> positions[] = {m_CCSprite_0, m_CCSprite_1, m_CCSprite_2, m_CCSprite_3, m_CCSprite_4, m_CCSprite_5, m_CCSprite_6}; for (int i = 1; i <= PortActController::getInstance()->m_loginDayMap.size(); ++i) { //m_data->addObject(CCInteger::create(i)); DailyCell* cell =DailyCell::create(i,m_scNode); cell->setPosition(positions[i - 1]->getPosition() - ccp(0.0, m_CCSprite_0->getContentSize().height / 2.0)); m_listNode->addChild(cell); } //m_tabView->reloadData(); } void DailyRwdView::gridTouched(cocos2d::extension::CCMultiColTableView* table, CCTableViewCell* cell) { if (!this->isVisible()) { return; } DailyCell* dailyCell = dynamic_cast<DailyCell*>(cell); if (dailyCell && m_listNode->isVisible()) { dailyCell->cellTouchEnded(m_tabView->m_pCurTouch); } } CCSize DailyRwdView::gridSizeForTable(cocos2d::extension::CCMultiColTableView *table) { return CCSize(136+2 , 196 + 25); } CCTableViewCell* DailyRwdView::gridAtIndex(cocos2d::extension::CCMultiColTableView *table, ssize_t idx) { if (idx >= m_data->count()) { return NULL; } int itemId = dynamic_cast<CCInteger*>(m_data->objectAtIndex(idx))->getValue(); DailyCell* cell = (DailyCell*)table->dequeueGrid(); if (cell) { cell->setData(itemId); } else { cell = DailyCell::create(itemId,m_listNode); } return cell; } ssize_t DailyRwdView::numberOfCellsInTableView(cocos2d::extension::CCMultiColTableView *table) { return ceil(m_data->count()/5.0); } ssize_t DailyRwdView::numberOfGridsInCell(cocos2d::extension::CCMultiColTableView *multiTable) { return 5; } void DailyRwdView::refreshRDData() { //刷新奖励数据 // auto& arr = PortActController::getInstance()->m_loginDayMap[m_itemId].vipReward; // if(arr==NULL || arr->count()<=0) return ; // //数组只有一个元素 即只有一种vip奖励 // CCDictionary* item = _dict(arr->objectAtIndex(0)); // int type = item->valueForKey("type")->intValue(); // string name = ""; // string num = ""; // string info = ""; // if (type == R_GOODS) { // CCDictionary* value = _dict(item->objectForKey("value")); // num = value->valueForKey("num")->getCString(); // string toolId = value->valueForKey("id")->getCString(); // name = CCCommonUtils::getNameById(toolId); // } else { // name = RewardController::getInstance()->getNameByType(type, 0); // num = item->valueForKey("value")->getCString(); // } //m_vipLabel->setString(_lang_2("111050", num.c_str(), name.c_str())); } void DailyRwdView::onSelectClick(CCObject * pSender, CCControlEvent pCCControlEvent){ if(m_selectSpr->isVisible()){ YesNoDialog* dialog = YesNoDialog::showVariableTitle(_lang("111068").c_str(),CCCallFunc::create(this, callfunc_selector(DailyRwdView::yesFuns)),_lang("111066").c_str()); CCCommonUtils::setButtonTitle(dialog->m_btnCancel, _lang("111065").c_str()); dialog->showCancelButton(); }else{ m_selectSpr->setVisible(true); } } void DailyRwdView::yesFuns(){ m_selectSpr->setVisible(false); } void DailyRwdView::onCloseBtnClick(CCObject * pSender, CCControlEvent pCCControlEvent){ CCSafeNotificationCenter::sharedNotificationCenter()->postNotification(MSG_CLOSING_RechargeACTVCell); PopupViewController::getInstance()->removeAllPopupView(); } void DailyRwdView::onFriendClick(CCObject * pSender, CCControlEvent pCCControlEvent){ if(!m_friendNode->isVisible()){ m_friendNode->setVisible(true); m_listNode->setVisible(false); if(m_friendNode->getChildrenCount()<=1){ this->initFriend(); } }else{ m_friendNode->setVisible(false); m_listNode->setVisible(true); } } void DailyRwdView::initFriend(){ int num = m_showDatas->count(); if(m_friendNode->getChildrenCount()<=1){ int totalH = 10*36-5; for (int i=0; i<num; i++) { FBFriendInfo* info = dynamic_cast<FBFriendInfo*>(m_showDatas->objectAtIndex(i)); DailyFriendCell* cell = DailyFriendCell::create(info,m_scNode); int row = i/2; int col = i%2; cell->setPosition(ccp(col*300+20, totalH - (row+1)*36)); m_friendNode->addChild(cell); } } m_tipTxt3->setVisible(num<=0); } void DailyRwdView::addFriends(){ m_showDatas->removeAllObjects(); int inviteNum = 6; int installNum = 14; int total = 20; int num = m_friendDatas->count(); m_sendId = ""; m_installNum = 0; m_notInstallNum = 0; if(num>installNum){ for (int i=0; i<200; i++) { int rand = GlobalData::shared()->getRand(0,num-1); FBFriendInfo* info = dynamic_cast<FBFriendInfo*>(m_friendDatas->objectAtIndex(rand)); if (info == NULL || m_sendId.find(info->id)<m_sendId.length()) { continue; } if(m_showDatas->count()>=installNum){ break; } m_sendId.append(","); m_sendId.append(info->id); m_showDatas->addObject(info); } }else{ m_showDatas->addObjectsFromArray(m_friendDatas); } m_installNum = m_showDatas->count(); int num2 = m_inviteDatas->count(); int tNum = m_showDatas->count(); if(num2>inviteNum){ for (int i=0; i<100; i++) { int rand = GlobalData::shared()->getRand(0,num2-1); FBFriendInfo* info = dynamic_cast<FBFriendInfo*>(m_inviteDatas->objectAtIndex(rand)); if (info == NULL || m_sendId.find(info->id)<m_sendId.length()) { continue; } if(m_showDatas->count()>=(inviteNum+tNum)){ break; } m_sendId.append(","); m_sendId.append(info->id); m_showDatas->addObject(info); } m_notInstallNum = inviteNum; }else{ m_showDatas->addObjectsFromArray(m_inviteDatas); m_notInstallNum = m_inviteDatas->count(); } int prev = 0; if(m_showDatas->count()<total){ if(num>installNum){ prev = m_showDatas->count(); for (int i=0; i<m_friendDatas->count(); i++) { FBFriendInfo* info = dynamic_cast<FBFriendInfo*>(m_friendDatas->objectAtIndex(i)); if (info == NULL || m_sendId.find(info->id)<m_sendId.length()) { continue; } if(m_showDatas->count()>=total){ break; } m_sendId.append(","); m_sendId.append(info->id); m_showDatas->addObject(info); } m_installNum += (m_showDatas->count() - prev) ; }else if(num2>inviteNum){ prev = m_showDatas->count(); for (int i=0; i<m_inviteDatas->count(); i++) { FBFriendInfo* info = dynamic_cast<FBFriendInfo*>(m_inviteDatas->objectAtIndex(i)); if (info == NULL || m_sendId.find(info->id)<m_sendId.length()) { continue; } if(m_showDatas->count()>=total){ break; } m_sendId.append(","); m_sendId.append(info->id); m_showDatas->addObject(info); } m_notInstallNum += (m_showDatas->count() - prev) ; } } } SEL_CCControlHandler DailyRwdView::onResolveCCBCCControlSelector(cocos2d::CCObject * pTarget, const char * pSelectorName) { CCB_SELECTORRESOLVER_CCCONTROL_GLUE(this, "onClickRwdBtn", DailyRwdView::onClickRwdBtn); CCB_SELECTORRESOLVER_CCCONTROL_GLUE(this, "onClickTipBtn", DailyRwdView::onClickTipBtn); CCB_SELECTORRESOLVER_CCCONTROL_GLUE(this, "onSelectClick", DailyRwdView::onSelectClick); CCB_SELECTORRESOLVER_CCCONTROL_GLUE(this, "onFriendClick", DailyRwdView::onFriendClick); CCB_SELECTORRESOLVER_CCCONTROL_GLUE(this, "onCloseBtnClick", DailyRwdView::onCloseBtnClick); return NULL; } bool DailyRwdView::onAssignCCBMemberVariable(cocos2d::CCObject * pTarget, const char * pMemberVariableName, cocos2d::CCNode * pNode) { CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_bgNode", CCNode*, this->m_bgNode); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_shipPicNode", CCNode*, this->m_shipPicNode); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_topNode", CCNode*, this->m_topNode); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_titleLabel", CCLabelIF*, this->m_titleLabel); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_listBg", CCScale9Sprite*, this->m_listBg); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_listNode", CCNode*, this->m_listNode); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_dayNode", CCNode*, this->m_dayNode); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_bottomNode", CCNode*, this->m_bottomNode); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_vipLabel", CCLabelIF*, this->m_vipLabel); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_rwdBtn", CCControlButton*, this->m_rwdBtn); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_tipBtn", CCControlButton*, this->m_tipBtn); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_rwdList", CCNode*, this->m_rwdList); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_leftSpr", CCSprite*, this->m_leftSpr); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_rightSpr", CCSprite*, this->m_rightSpr); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_friendBtn", CCControlButton*, this->m_friendBtn); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_selectBtn", CCControlButton*, this->m_selectBtn); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_friendTxt", CCLabelIF*, this->m_friendTxt); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_friendNode", CCNode*, this->m_friendNode); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_selectSpr", CCSprite*, m_selectSpr); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_scNode", CCNode*, this->m_scNode); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_moveNode", CCNode*, this->m_moveNode); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_tipTxt1", CCLabelIF*, this->m_tipTxt1); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_tipTxt2", CCLabelIF*, this->m_tipTxt2); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_tipTxt3", CCLabelIF*, this->m_tipTxt3); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_infoNode", CCNode*, this->m_infoNode); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_touchNode", CCNode*, this->m_touchNode); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_listPositionNodes", CCNode*, this->m_listPositionNodes); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_CCSprite_0", CCSprite*, m_CCSprite_0); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_CCSprite_1", CCSprite*, m_CCSprite_1); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_CCSprite_2", CCSprite*, m_CCSprite_2); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_CCSprite_3", CCSprite*, m_CCSprite_3); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_CCSprite_4", CCSprite*, m_CCSprite_4); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_CCSprite_5", CCSprite*, m_CCSprite_5); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_CCSprite_6", CCSprite*, m_CCSprite_6); return false; } void DailyRwdView::onClickRwdBtn(CCObject * pSender, CCControlEvent pCCControlEvent) { GlobalData::shared()->isBind = true; m_inviteNum = 0; string fbUid = CCUserDefault::sharedUserDefault()->getStringForKey(FB_USERID,""); if (!m_selectSpr->isVisible() || !FBUtilies::fbIsLogin() || m_showDatas->count()<=0 || fbUid=="") { this->getDailyReward(); }else{ if(FBUtilies::fbIsLogin()){ string dialog = "111062"; string msg = _lang("111062"); if(msg==""){ dialog = "107077"; msg = _lang("107077"); } CCArray* arr = CCArray::create(); for (int i=0; i<m_showDatas->count(); i++) { FBFriendInfo* fInfo = dynamic_cast<FBFriendInfo*>(m_showDatas->objectAtIndex(i)); if(fInfo && fInfo->isCheck){ arr->addObject(CCString::create(fInfo->id)); } } m_inviteNum = arr->count(); FBUtilies::postFBSelectedFriendList(arr,msg,"1"); FBUtilies::appEventShareLog(CC_ITOA(GlobalData::shared()->playerInfo.selfServerId), GlobalData::shared()->playerInfo.level, FunBuildController::getInstance()->getMainCityLv(), dialog); }else{ m_count = 0; bool flag = FBUtilies::fbLogin(); if(!flag){ //todo 2.3 android 以下,直接领取 this->getDailyReward(); } } } } void DailyRwdView::getDailyReward(){ m_waitInterface1 = GameController::getInstance()->showWaitInterface(m_rwdBtn); if (PortActController::getInstance()->m_isRdLoginDay == 0) {//今天没有领取 if(m_inviteNum==0){ m_notInstallNum = 0; m_installNum = 0; } //获取奖励 PortActController::getInstance()->startGetCheckInRwd(0,m_inviteNum,m_notInstallNum,m_installNum); } else {//今天已领取 refreshBtnState(); if (m_waitInterface1 != NULL) { m_waitInterface1->remove(); m_waitInterface1 = NULL; } } } void DailyRwdView::onClickTipBtn(CCObject * pSender, CCControlEvent pCCControlEvent) { //tip string tips = _lang("111059") + "\n" + _lang("111060") + "\n" + _lang("111061"); if(GlobalData::shared()->isXiaoMiPlatForm()){ tips = _lang("111060") + "\n" + _lang("111061"); } PopupViewController::getInstance()->addPopupView(TipsView::create(tips, kCCTextAlignmentLeft)); } void DailyRwdView::onRmvWaitInter1(CCObject* params) { refreshTitle(); refreshBtnState(); if(m_waitInterface1 != NULL){ m_waitInterface1->remove(); m_waitInterface1 = NULL; } } void DailyRwdView::onRmvWaitInter2(CCObject* params) { refreshTitle(); refreshBtnState(); if(m_waitInterface2 != NULL){ m_waitInterface2->remove(); m_waitInterface2 = NULL; } } void DailyRwdView::refreshBtnState() { if (PortActController::getInstance()->m_isRdLoginDay) { m_rwdBtn->setEnabled(false); } else { m_rwdBtn->setEnabled(true); } } void DailyRwdView::refreshTitle() { int day = PortActController::getInstance()->m_loginDay; m_titleLabel->setString(_lang_1("111051", CC_ITOA(day))); m_leftSpr->setPositionX(-m_titleLabel->getContentSize().width * m_titleLabel->getOriginScaleX() * 0.5 - 10); m_rightSpr->setPositionX(m_titleLabel->getContentSize().width * m_titleLabel->getOriginScaleX() * 0.5 + 10); } void DailyRwdView::setListNodeVisible(bool st) { if (m_listNode) { m_listNode->setVisible(st); } } //class DailyCell DailyCell* DailyCell::create(int itemId,CCNode* clickArea) { auto ret = new DailyCell(clickArea); if (ret && ret->init(itemId)) { ret->autorelease(); } else { CC_SAFE_DELETE(ret); } return ret; } bool DailyCell::init(int itemId) { CCBLoadFile("qiandaoCell",this,this); setContentSize(CCSize(136+2, 196 + 25)); m_touchNode->setPosition(138 / 2, 25 + 196 / 2); setData(itemId); return true; } void DailyCell::setData(int itemId) { CCLoadSprite::doResourceByCommonIndex(11, true); setCleanFunction([](){ CCLoadSprite::doResourceByCommonIndex(11, false); }); m_flashSpr->setVisible(false); m_bgSpr = NULL; m_picSpr = NULL; m_numLabel->setString(""); m_dayLabel->setString(""); m_bgNode->removeAllChildren(); m_picNode->removeAllChildren(); setGlowVisible(false); m_itemId = itemId; //fusheng test // PortActController::getInstance()->m_loginDay = 7; // PortActController::getInstance()->m_isRdLoginDay = 0; // PortActController::getInstance()->m_isVipRdLoginDay = 1; if (!PortActController::getInstance()->m_loginDayMap[m_itemId].reward) { return; } auto& arr = PortActController::getInstance()->m_loginDayMap[m_itemId].reward; if(arr==nullptr || arr->count()<=0) return ; m_rdNode->setVisible(false); m_spr1->setVisible(false); m_spr2->setVisible(false); m_spr3->setVisible(false); if (m_itemId==1 || m_itemId==2 || m_itemId==3) { m_spr1->setVisible(true); }else if (m_itemId==6) { m_spr3->setVisible(true); }else { m_spr2->setVisible(true); } if (arr->count() > 1) { // m_particleNode->setScale(1.3); m_dayLabel->setString(_lang_1("111058", CC_ITOA(m_itemId))); m_rdNode->setVisible(true); if (m_itemId < PortActController::getInstance()->m_loginDay) { onRefreshBaoXiang(true); m_flashSpr->setVisible(true); } else if (m_itemId == PortActController::getInstance()->m_loginDay){ if (PortActController::getInstance()->m_isRdLoginDay == 0 && PortActController::getInstance()->m_isVipRdLoginDay == 1) { setGlowVisible(true); } else { onRefreshBaoXiang(true); m_flashSpr->setVisible(true); } } else if (m_itemId == (PortActController::getInstance()->m_loginDay + 1)){ if (PortActController::getInstance()->m_isRdLoginDay == 0 && PortActController::getInstance()->m_isVipRdLoginDay == 0) {//这一天啥奖也没领 setGlowVisible(true); } } else { } } else { //数组只有一个元素 即只有一种奖励 CCDictionary* item = _dict(arr->objectAtIndex(0)); int type = item->valueForKey("type")->intValue(); string pic = ""; string name = ""; string num = ""; string bg = "kuang"; if (type == R_GOODS) { CCDictionary* value = _dict(item->objectForKey("value")); num = value->valueForKey("num")->getCString(); string toolId = value->valueForKey("id")->getCString(); pic = CCCommonUtils::getIcon(toolId); name = CCCommonUtils::getNameById(toolId); } else if (type == R_EQUIP) { CCDictionary* value = _dict(item->objectForKey("value")); num = value->valueForKey("num")->getCString(); string toolId = value->valueForKey("id")->getCString(); pic = CCCommonUtils::getIcon(toolId); name = CCCommonUtils::getNameById(toolId); } else { pic = RewardController::getInstance()->getPicByType(type, 0); name = RewardController::getInstance()->getNameByType(type, 0); num = item->valueForKey("value")->getCString(); } int multiple = PortActController::getInstance()->m_loginDayMap[m_itemId].multiple; bg += CC_ITOA(multiple); bg += ".png"; m_bgSpr = CCLoadSprite::createSprite(bg.c_str()); m_picSpr = CCLoadSprite::createSprite(pic.c_str(), true , CCLoadSpriteType_GOODS); // if (CCCommonUtils::isIosAndroidPad()) // { // m_bgSpr->setScale(2.f); // CCCommonUtils::setSpriteMaxSize(m_picSpr, 90*2, true); // } // else // CCCommonUtils::setSpriteMaxSize(m_picSpr, 90, true); if(m_itemId == 7)//fusheng 第七天 特殊处理 { CCCommonUtils::setSpriteMaxSize(m_picSpr, 152, true); } else { CCCommonUtils::setSpriteMaxSize(m_picSpr, 110, true); } m_bgNode->addChild(m_bgSpr); m_picNode->addChild(m_picSpr); m_numLabel->setString(num); // int isShowDay = PortActController::getInstance()->m_loginDayMap[m_itemId].showDay; // if (true) {//isShowDay == 1 m_dayLabel->setString(_lang_1("111058", CC_ITOA(m_itemId))); m_dayLabel->setVisible(true); // } else { // m_dayLabel->setString(""); // m_dayLabel->setVisible(false); // } CCCommonUtils::setSpriteGray(m_bgSpr, false); CCCommonUtils::setSpriteGray(m_picSpr, false); if (m_itemId < PortActController::getInstance()->m_loginDay) { CCCommonUtils::setSpriteGray(m_bgSpr, true); CCCommonUtils::setSpriteGray(m_picSpr, true); m_dayLabel->setColor(ccWHITE); m_flashSpr->setVisible(true); setGlowVisible(false); } else if (m_itemId == PortActController::getInstance()->m_loginDay){ if (PortActController::getInstance()->m_isRdLoginDay == 0 && PortActController::getInstance()->m_isVipRdLoginDay == 1) { CCCommonUtils::setSpriteGray(m_bgSpr, false); CCCommonUtils::setSpriteGray(m_picSpr, false); m_flashSpr->setVisible(false); setGlowVisible(true); } else { CCCommonUtils::setSpriteGray(m_bgSpr, true); CCCommonUtils::setSpriteGray(m_picSpr, true); m_dayLabel->setColor(ccWHITE); m_flashSpr->setVisible(true); setGlowVisible(false); } } else if (m_itemId == (PortActController::getInstance()->m_loginDay + 1)){ if (PortActController::getInstance()->m_isRdLoginDay == 0 && PortActController::getInstance()->m_isVipRdLoginDay == 0) {//这一天啥奖也没领 CCCommonUtils::setSpriteGray(m_bgSpr, false); CCCommonUtils::setSpriteGray(m_picSpr, false); m_flashSpr->setVisible(false); setGlowVisible(true); } } else { } } } void DailyCell::onEnter() { CCNode::onEnter(); setTouchEnabled(true); //CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, Touch_Default, false); CCSafeNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(DailyCell::refreshRd), PORT_LOGINRD_END, NULL); } void DailyCell::onExit() { setTouchEnabled(false); CCSafeNotificationCenter::sharedNotificationCenter()->removeObserver(this, PORT_LOGINRD_END); CCNode::onExit(); } bool DailyCell::onTouchBegan(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent){ m_startPos = pTouch->getLocation(); if (!m_clickArea->isVisible() || !isTouchInside(m_clickArea, pTouch)) { return false; } return true; } void DailyCell::onTouchEnded(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent){ cellTouchEnded(pTouch); } void DailyCell::onTouchMoved(CCTouch *pTouch, CCEvent *pEvent){ } void DailyCell::cellTouchEnded(CCTouch* pTouch) { CCPoint pos = pTouch->getLocation(); CCNode* node = this->getParent(); if (isTouchInside(m_touchNode, pTouch) && fabs(pos.y - m_startPos.y) <=30 && node && node->isVisible()) { int dx = pTouch->getLocation().x - pTouch->getStartLocation().x; int dy = pTouch->getLocation().y - pTouch->getStartLocation().y; if (fabs(dx) > 10 || fabs(dy) > 10) { return; } else { SoundController::sharedSound()->playEffects(Music_Sfx_click_button); if(PortActController::getInstance()->m_loginDayMap.find(m_itemId) == PortActController::getInstance()->m_loginDayMap.end()){ return; } if(m_rdNode->isVisible()) { auto dict = CCDictionary::create(); auto itemEffectObj = CCDictionary::create(); CCArray* tmpArr = PortActController::getInstance()->m_loginDayMap[m_itemId].reward; if(tmpArr == NULL){ return; } auto newArr = CCArray::createWithArray(tmpArr); itemEffectObj->setObject(newArr, "reward"); auto tmparray = CCArray::create(); dict->setObject(itemEffectObj, "itemEffectObj"); dict->setObject(CCString::create(CC_ITOA(99999)), "day"); PopupViewController::getInstance()->addPopupView(ChestRDView::create(dict),false,false); } else { bool st = false; if (PortActController::getInstance()->m_isRdLoginDay == 0) { if (PortActController::getInstance()->m_isVipRdLoginDay == 0) { if (m_itemId == (PortActController::getInstance()->m_loginDay + 1)) { st = true; } } else { if (m_itemId == PortActController::getInstance()->m_loginDay) { st = true; } } } PopupViewController::getInstance()->addPopupView(DailyRwdPop::create(m_itemId)); // if (st) { // PortActController::getInstance()->startGetCheckInRwd(0); // } else { // PopupViewController::getInstance()->addPopupView(DailyRwdPop::create(m_itemId)); // } } } } } SEL_CCControlHandler DailyCell::onResolveCCBCCControlSelector(cocos2d::CCObject *pTarget, const char *pSelectorName) { return NULL; } void DailyCell::refreshRd(CCObject* params) { if(params) { int itemId = dynamic_cast<CCInteger*>(params)->getValue(); if (itemId != m_itemId) { } else { if (m_bgSpr) { CCCommonUtils::setSpriteGray(m_bgSpr, true); } if (m_picSpr) { CCCommonUtils::setSpriteGray(m_picSpr, true); } if (m_rdNode->isVisible()) { onRefreshBaoXiang(true); } m_dayLabel->setColor(ccWHITE); m_flashSpr->setVisible(true); setGlowVisible(false); } } } void DailyCell::onRefreshBaoXiang(bool st) { if (m_spr1->isVisible()) { CCCommonUtils::setSpriteGray(m_spr1, st); } if (m_spr2->isVisible()) { CCCommonUtils::setSpriteGray(m_spr2, st); } if (m_spr3->isVisible()) { CCCommonUtils::setSpriteGray(m_spr3, st); } CCCommonUtils::setSpriteGray(m_wenhao, st); if(st) m_dayLabel->setColor(ccWHITE); } void DailyCell::setGlowVisible(bool b) { if (b) { m_itemBG->setVisible(m_itemId != 7); m_particleNode->setVisible(m_itemId == 7); } else { m_itemBG->setVisible(b); m_particleNode->setVisible(b); } } bool DailyCell::onAssignCCBMemberVariable(cocos2d::CCObject *pTarget, const char *pMemberVariableName, cocos2d::CCNode *pNode) { CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_numBG", CCSprite*, m_numBG); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_itemBG", CCSprite*, m_itemBG); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_numLabel", CCLabelIF*, m_numLabel); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_dayLabel", CCLabelIF*, m_dayLabel); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_flashSpr", CCSprite*, m_flashSpr); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_bgNode", CCNode*, m_bgNode); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_picNode", CCNode*, m_picNode); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_particleNode", CCNode*, m_particleNode); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_touchNode", CCNode*, m_touchNode); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_rdNode", CCNode*, m_rdNode); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_spr1", CCSprite*, m_spr1); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_spr2", CCSprite*, m_spr2); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_spr3", CCSprite*, m_spr3); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_wenhao", CCSprite*, m_wenhao); return false; } ///pop DailyRwdPop* DailyRwdPop::create(int itemId) { auto ret = new DailyRwdPop(); if (ret && ret->init(itemId)) { ret->autorelease(); } else { CC_SAFE_DELETE(ret); } return ret; } bool DailyRwdPop::init(int itemId) { bool ret = false; if (!PopupBaseView::init()) { return ret; } setIsHDPanel(true); CCLoadSprite::doResourceByCommonIndex(11, true); setCleanFunction([](){ CCLoadSprite::doResourceByCommonIndex(11, false); }); CCBLoadFile("qiandaoTips", this, this); setContentSize(CCDirector::sharedDirector()->getWinSize()); m_itemId = itemId; if(PortActController::getInstance()->m_loginDayMap.find(m_itemId) == PortActController::getInstance()->m_loginDayMap.end()){ return false; } auto& arr = PortActController::getInstance()->m_loginDayMap[m_itemId].reward; //数组只有一个元素 即只有一种奖励 CCDictionary* item = _dict(arr->objectAtIndex(0)); int type = item->valueForKey("type")->intValue(); string pic = ""; string name = ""; string des = ""; string bg = "kuang"; int num = 0; if (type == R_GOODS) { CCDictionary* value = _dict(item->objectForKey("value")); num = value->valueForKey("num")->intValue(); string toolId = value->valueForKey("id")->getCString(); pic = CCCommonUtils::getIcon(toolId); name = CCCommonUtils::getNameById(toolId); des = (ToolController::getInstance()->getToolInfoById(atoi(toolId.c_str()))).des; } else { pic = RewardController::getInstance()->getPicByType(type, 0); name = RewardController::getInstance()->getNameByType(type, 0); num = item->valueForKey("num")->intValue(); } int multiple = PortActController::getInstance()->m_loginDayMap[m_itemId].multiple; bg += CC_ITOA(multiple); bg += ".png"; auto bgSpr = CCLoadSprite::createSprite(bg.c_str()); auto picSpr = CCLoadSprite::createSprite(pic.c_str()); CCCommonUtils::setSpriteMaxSize(picSpr, 90, true); m_bgNode->addChild(bgSpr); m_picNode->addChild(picSpr); if(num>1){ name.append(" X"); name.append(CC_ITOA(num)); } m_nameLabel->setString(name); m_desLabel->setString(_lang(des)); ret = true; return ret; } void DailyRwdPop::onEnter() { PopupBaseView::onEnter(); setTouchMode(Touch::DispatchMode::ONE_BY_ONE); setTouchEnabled(true); //CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, Touch_Default, false); } void DailyRwdPop::onExit() { setTouchEnabled(false); PopupBaseView::onExit(); } bool DailyRwdPop::onTouchBegan(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent) { return true; } void DailyRwdPop::onTouchEnded(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent) { if (isTouchInside(m_touchNode, pTouch)) { return; } PopupViewController::getInstance()->removePopupView(this); } SEL_CCControlHandler DailyRwdPop::onResolveCCBCCControlSelector(cocos2d::CCObject *pTarget, const char *pSelectorName) { return NULL; } bool DailyRwdPop::onAssignCCBMemberVariable(cocos2d::CCObject *pTarget, const char *pMemberVariableName, cocos2d::CCNode *pNode) { CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_touchNode", CCNode*, m_touchNode); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_bgNode", CCNode*, m_bgNode); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_picNode", CCNode*, m_picNode); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_nameLabel", CCLabelIF*, m_nameLabel); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_desLabel", CCLabelIF*, m_desLabel); return false; } //DailyFriendCell DailyFriendCell* DailyFriendCell::create(FBFriendInfo* info,CCNode* clickNode) { auto ret = new DailyFriendCell(info,clickNode); if (ret && ret->init()) { ret->autorelease(); } else { CC_SAFE_DELETE(ret); } return ret; } bool DailyFriendCell::init() { CCLoadSprite::doResourceByCommonIndex(11, true); auto node = CCBLoadFile("DailyFriendCell",this,this); setContentSize(node->getContentSize()); m_nameTxt->setString(m_info->name.c_str()); m_selectBtn->setSelected(m_info->isCheck); m_selectSpr->setVisible(m_selectBtn->isSelected()); return true; } void DailyFriendCell::onEnter() { CCNode::onEnter(); } void DailyFriendCell::onExit() { CCNode::onExit(); } void DailyFriendCell::onSelectClick(CCObject * pSender, CCControlEvent pCCControlEvent){ if (m_clickNode==NULL || !m_clickNode->isVisible()) { return ; } m_selectBtn->setSelected(!m_selectBtn->isSelected()); m_selectSpr->setVisible(m_selectBtn->isSelected()); if(m_selectSpr->isVisible()){ m_info->isCheck = true; }else{ m_info->isCheck = false; } } SEL_CCControlHandler DailyFriendCell::onResolveCCBCCControlSelector(cocos2d::CCObject *pTarget, const char *pSelectorName) { CCB_SELECTORRESOLVER_CCCONTROL_GLUE(this, "onSelectClick", DailyFriendCell::onSelectClick); return NULL; } bool DailyFriendCell::onAssignCCBMemberVariable(cocos2d::CCObject *pTarget, const char *pMemberVariableName, cocos2d::CCNode *pNode) { CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_nameTxt", CCLabelIFTTF*, m_nameTxt); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_selectBtn", CCControlButton*, m_selectBtn); CCB_MEMBERVARIABLEASSIGNER_GLUE_WEAK(this, "m_selectSpr", CCSprite*, m_selectSpr); return false; }
1f9778b0a4763509b35c22f75882cb708ac6ef45
0f2c7805ce608977387ba541be1a53a4217cc541
/chia_duahau.cpp
6009846d4cd28b977a714f8b71af57e4e54b7296
[]
no_license
datnguyen51/ContestTLU
00ceed27269f571c0d5f2514b058250a551faf04
87975d5bd31b5e4ad6ed367366e750f248272596
refs/heads/master
2020-04-05T15:06:18.612117
2018-11-26T10:58:05
2018-11-26T10:58:05
156,952,879
0
0
null
null
null
null
UTF-8
C++
false
false
205
cpp
#include <iostream> using namespace std; int main() { int n; cin>>n; if(1<=n && n<=100) { if(n%2==0 && n>2) cout<<"YES"<<endl; else cout<<"NO"<<endl; } else cout<<"NO"<<endl; return 0; }
939cd231e05a53f8a0e5a2fbbedbfbe52f622128
18612d2d5ae4f534868757055b81ce85be4e2bc0
/chapter4/Arduino/teste2.ino
75e082aae9143c8f43cd74e8b35cf2cad33a8f0d
[]
no_license
victoradriel/MasterDissertation
084f8f70196fe8ce23022d0fb0e21ffe37a1fab8
0cbdd4ef1e23a6de67f8828c944f16b6f0b7d778
refs/heads/master
2021-09-17T14:38:56.436796
2018-07-02T15:21:23
2018-07-02T15:21:23
139,447,943
0
0
null
null
null
null
UTF-8
C++
false
false
3,479
ino
/** author: Victor Adriel Primeiro teste: reconhecimento de padrões. Depois de explicados os significados dos parâmetros acompanhando o estímulo correspondente são impressos padrões e o usuário é inquirido a respeito de: - Quantos vibradores estão ativos; - Quais vibradores foram ativados (posição); - Qual informação transmitida (tacton). */ int vibDur = 1000; int peqIntrvl = 2000; int grdIntrvl = 6000; int qtdTactors = 9; void setup(){ for(int x=0; x<qtdTactors; x++){ pinMode(x+5, OUTPUT); } } void loop(){ teste(); delay(grdIntrvl*10); } void tactorOn(int x){ digitalWrite(x, HIGH); } void tactorOff(int x){ digitalWrite(x, LOW); } void patTrainn1(){ tactorOn(8); delay(vibDur); tactorOff(8); } void patTrainn2(){ tactorOn(9); delay(vibDur); tactorOff(9); } void patTrainn3(){ tactorOn(6); tactorOn(9); delay(vibDur); tactorOff(6); tactorOff(9); } void patTrainn4(){ tactorOn(6); delay(vibDur); tactorOff(6); } void patTrainn5(){ tactorOn(7); tactorOn(13); delay(vibDur); tactorOff(7); tactorOff(13); } void patTrainn6(){ tactorOn(11); tactorOn(12); tactorOn(13); delay(vibDur); tactorOff(11); tactorOff(12); tactorOff(13); } void patTrainn7(){ tactorOn(9); tactorOn(10); delay(vibDur); tactorOff(9); tactorOff(10); } void patTrainn8(){ tactorOn(9); tactorOn(12); delay(vibDur); tactorOff(9); tactorOff(12); } void patTrainn9(){ tactorOn(7); tactorOn(10); tactorOn(13); delay(vibDur); tactorOff(7); tactorOff(10); tactorOff(13); } void patTest3(){ tactorOn(7); delay(vibDur); tactorOff(7); } void patTest4(){ tactorOn(7); tactorOn(9); delay(vibDur); tactorOff(7); tactorOff(9); } void patTest5(){ tactorOn(7); tactorOn(11); delay(vibDur); tactorOff(7); tactorOff(11); } void patTest6(){ tactorOn(9); tactorOn(13); delay(vibDur); tactorOff(9); tactorOff(13); } void patTest7(){ tactorOn(7); tactorOn(11); tactorOn(13); delay(vibDur); tactorOff(7); tactorOff(11); tactorOff(13); } void patTest8(){ tactorOn(7); tactorOn(8); tactorOn(10); tactorOn(13); delay(vibDur); tactorOff(7); tactorOff(8); tactorOff(10); tactorOff(13); } void teste(){ // Teste delay(grdIntrvl); patTest3(); delay(peqIntrvl); patTest3(); delay(peqIntrvl); patTest3(); delay(grdIntrvl); patTest8(); delay(peqIntrvl); patTest8(); delay(peqIntrvl); patTest8(); delay(grdIntrvl); patTrainn5(); delay(peqIntrvl); patTrainn5(); delay(peqIntrvl); patTrainn5(); delay(grdIntrvl); patTest4(); delay(peqIntrvl); patTest4(); delay(peqIntrvl); patTest4(); delay(grdIntrvl); patTrainn1(); delay(peqIntrvl); patTrainn1(); delay(peqIntrvl); patTrainn1(); delay(grdIntrvl); patTrainn6(); delay(peqIntrvl); patTrainn6(); delay(peqIntrvl); patTrainn6(); delay(grdIntrvl); patTest5(); delay(peqIntrvl); patTest5(); delay(peqIntrvl); patTest5(); delay(grdIntrvl); patTest6(); delay(peqIntrvl); patTest6(); delay(peqIntrvl); patTest6(); delay(grdIntrvl); patTrainn2(); delay(peqIntrvl); patTrainn2(); delay(peqIntrvl); patTrainn2(); delay(grdIntrvl); patTest7(); delay(peqIntrvl); patTest7(); delay(peqIntrvl); patTest7(); delay(grdIntrvl); patTrainn3(); delay(peqIntrvl); patTrainn3(); delay(peqIntrvl); patTrainn3(); delay(grdIntrvl); patTrainn4(); delay(peqIntrvl); patTrainn4(); delay(peqIntrvl); patTrainn4(); }
c6f4b049f1de8791600ca62e53157fa9eb8cdf02
cf626791e70d1c26e157fc71240945b5087dc698
/speed_test/speed_test.ino
9df2d709f3c173616dcc70f1e7694b010bfb5736
[]
no_license
alpha6/HX711_endstop
2e91b131e20f41cefe56d6401ec76a08105aaaac
ccbdd2f96182436f081a7bcc6579a78ad2005151
refs/heads/master
2021-01-09T05:55:32.762404
2017-02-22T13:28:06
2017-02-22T13:28:06
80,865,744
4
1
null
null
null
null
UTF-8
C++
false
false
699
ino
#include <Q2HX711.h> const byte hx711_data_pin = A2; const byte hx711_clock_pin = A3; const int probe_pin = 7; const int readCount = 100; Q2HX711 hx711(hx711_data_pin, hx711_clock_pin); void setup() { // put your setup code here, to run once: Serial.begin(115200); delay(1000); } void loop() { // put your main code here, to run repeatedly: long startTime = millis(); for (int i = 0; i<readCount; i++) { hx711.read(); } long endTime = millis(); long timeDiff = endTime-startTime; div_t rps = div(timeDiff, readCount); char buffer [50]; sprintf(buffer, "Time per %d reads - %li. %i ms per request", readCount, timeDiff, rps.quot); Serial.println(buffer); }
80abdacd5f8235f81dab7288f9040ae45a2ac82f
394ef4ef657268024073e358c9b709966cc0f2d8
/Last week problems/Articulation points.cpp
1028ff52646046a824040c2f7292777bb3d38ad5
[]
no_license
svdhiren/DSA-practice
111573b98eecfd1ad908056ceca512855d21c191
b62c2546f0d1d6e5221ffbc2294469e821e11829
refs/heads/master
2023-06-20T02:11:20.808767
2021-07-17T13:52:30
2021-07-17T13:52:30
386,659,313
0
0
null
null
null
null
UTF-8
C++
false
false
1,970
cpp
#include<iostream> using namespace std; int v; void calculate(int G[20][20], int num[], int low[], int vis[], int cur, int p){ static int n=1; //Assigning the arrival time and checking for a back edge if any and updating. num[cur]=n; low[cur]=n++; for(int i=1;i<=v;i++){ if(G[cur][i]==1 && i!=p && vis[i]==1 && num[i]<low[cur]) low[cur]=num[i]; } // Loop for depth first traversal for(int i=1;i<=v;i++){ if(G[cur][i]==1 && vis[i]!=1) { vis[i]=1; calculate(G, num, low, vis, i, cur); } } //When the function returns; checking whether the "low" of the parent can be changed. if(low[cur] < low[p] && p!=0) low[p]=low[cur]; if(low[cur] >= num[p] && p!=0 && p!=1) cout<<p<<" "; //Incrementing the departure time; n++; } void print(int G[20][20]) { cout<<"\n"; for(int i=1;i<=v;i++) cout<<"\t"<<i; cout<<"\n"; for(int i=1;i<=v;i++){ cout<<i<<"\t"; for(int j=1;j<=v;j++) if(G[i][j]>=1) cout<<G[i][j]<<"\t"; else cout<<"\t"; cout<<"\n"; } } void print_num(int G[20][20], int num[], int low[]) { cout<<"\n\n"; cout<<"\tNum\tLow"<<"\n"; for(int i=1;i<=v;i++){ cout<<i<<"\t"; cout<<num[i]<<"\t"<<low[i]; cout<<"\n"; } } int main() { int G[20][20], vis[20], num[20], low[20], x , y; cout<<"Enter the number of nodes:"; cin>>v; for(int i=0;i<=v;i++) { for(int j=0;j<=v;j++) G[i][j]=0; num[i]=0; vis[i]=0; low[i]=0; } cout<<"Start entering the edges...\n"; while(1){ cout<<"Enter x : "; cin>>x; if(x==-1) break; cout<<"Enter y : "; cin>>y; G[x][y]=G[y][x]=1; cout<<"\n"; } print(G); vis[1]=1; calculate(G, num, low, vis, 1, 0); //print_num(G, num, low); } /* Input: 7 1 2 2 3 3 7 3 4 4 5 5 6 6 4 4 1 -1 */
46a096dea668a7d0e47965f4a93bb1d7b32a6ca1
5d06523d5c6da5f877e209d6d6dbfe45f5900f87
/PopUpWindow/PopUpWindow/PopUpWindow.h
92b552ab6d4fe2e750fe8e7b9f353f4345f052eb
[]
no_license
snandi76/Beautiful_CPP
9b889eb82ee8db687237a2eefa0f1fbccc826fa2
6f3107ade910c7a98106c027468db929f55ee678
refs/heads/master
2020-04-16T15:26:28.155375
2019-01-20T11:56:04
2019-01-20T11:56:04
165,702,829
0
0
null
null
null
null
UTF-8
C++
false
false
504
h
// PopUpWindow.h : main header file for the PROJECT_NAME application // #pragma once #ifndef __AFXWIN_H__ #error "include 'stdafx.h' before including this file for PCH" #endif #include "resource.h" // main symbols // CPopUpWindowApp: // See PopUpWindow.cpp for the implementation of this class // class CPopUpWindowApp : public CWinApp { public: CPopUpWindowApp(); // Overrides public: virtual BOOL InitInstance(); // Implementation DECLARE_MESSAGE_MAP() }; extern CPopUpWindowApp theApp;
6e145d6272d48ea49943564a8af09f4137077ccc
f0f0e9d7c3515d711be57f2c470016499eeb42d5
/1143.最长公共子序列.cpp
cbbb475963d54da67d920288424ac6bbd46a2a00
[]
no_license
IrvingW/leetcode_problems
506d39a8938abcfaf19eb64062c9e55fef700393
af648f0a9ebd911b19302f28abca929a0691890c
refs/heads/main
2023-06-13T03:34:42.576316
2021-07-14T08:36:53
2021-07-14T08:36:53
352,042,463
0
0
null
null
null
null
UTF-8
C++
false
false
2,139
cpp
/* * @lc app=leetcode.cn id=1143 lang=cpp * * [1143] 最长公共子序列 * * https://leetcode-cn.com/problems/longest-common-subsequence/description/ * * algorithms * Medium (62.39%) * Likes: 544 * Dislikes: 0 * Total Accepted: 118K * Total Submissions: 189.1K * Testcase Example: '"abcde"\n"ace"' * * 给定两个字符串 text1 和 text2,返回这两个字符串的最长 公共子序列 的长度。如果不存在 公共子序列 ,返回 0 。 * * 一个字符串的 子序列 * 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。 * * * 例如,"ace" 是 "abcde" 的子序列,但 "aec" 不是 "abcde" 的子序列。 * * * 两个字符串的 公共子序列 是这两个字符串所共同拥有的子序列。 * * * * 示例 1: * * * 输入:text1 = "abcde", text2 = "ace" * 输出:3 * 解释:最长公共子序列是 "ace" ,它的长度为 3 。 * * * 示例 2: * * * 输入:text1 = "abc", text2 = "abc" * 输出:3 * 解释:最长公共子序列是 "abc" ,它的长度为 3 。 * * * 示例 3: * * * 输入:text1 = "abc", text2 = "def" * 输出:0 * 解释:两个字符串没有公共子序列,返回 0 。 * * * * * 提示: * * * 1 * text1 和 text2 仅由小写英文字符组成。 * * */ #include <string> #include <vector> using namespace std; // @lc code=start class Solution { public: int longestCommonSubsequence(string text1, string text2) { int m = text1.length(); int n = text2.length(); if (m == 0 || n == 0) return 0; vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0)); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (text1[i] == text2[j]) { dp[i + 1][j + 1] = dp[i][j] + 1; } else { dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j]); } } } return dp[m][n]; } }; // @lc code=end
cb40879a46b9a69d105dcc7c0b3fd5dbc2db952c
1a8c27ced068195eb01db1dfcab2f9a6cb9663fa
/src.wsjcpp/wsjcpp_light_web_server/wsjcpp_light_web_http_response.cpp
d545bef17a21e83f9d8b3245ba9d81aa013f5d67
[ "MIT" ]
permissive
sea-kg/webhook-handler
1202347179caf0eed0254e57c41a54a35e4bfbc8
c6e3edbd12521911bf3ecf2afd624c6777ffaa35
refs/heads/master
2023-03-30T08:31:47.790756
2021-03-24T15:58:08
2021-03-24T15:58:08
166,463,808
2
0
MIT
2021-03-24T15:58:09
2019-01-18T19:44:19
C++
UTF-8
C++
false
false
9,150
cpp
#include "wsjcpp_light_web_http_response.h" #include <wsjcpp_core.h> #include <fstream> #include <unistd.h> #include <sstream> #include <sys/socket.h> // ---------------------------------------------------------------------- // WsjcppLightWebHttpResponse // enum for http responses std::map<int, std::string> *WsjcppLightWebHttpResponse::g_mapReponseDescription = nullptr; // ---------------------------------------------------------------------- WsjcppLightWebHttpResponse::WsjcppLightWebHttpResponse(int nSockFd) { TAG = "WsjcppLightWebHttpResponse"; if (WsjcppLightWebHttpResponse::g_mapReponseDescription == nullptr) { WsjcppLightWebHttpResponse::g_mapReponseDescription = new std::map<int, std::string>(); WsjcppLightWebHttpResponse::g_mapReponseDescription->insert(std::pair<int, std::string>(200,"HTTP/1.1 200 OK")); WsjcppLightWebHttpResponse::g_mapReponseDescription->insert(std::pair<int, std::string>(400, "HTTP/1.1 400 Bad Request")); WsjcppLightWebHttpResponse::g_mapReponseDescription->insert(std::pair<int, std::string>(403, "HTTP/1.1 403 Forbidden")); WsjcppLightWebHttpResponse::g_mapReponseDescription->insert(std::pair<int, std::string>(404, "HTTP/1.1 404 Not Found")); WsjcppLightWebHttpResponse::g_mapReponseDescription->insert(std::pair<int, std::string>(413, "HTTP/1.1 413 Payload Too Large")); WsjcppLightWebHttpResponse::g_mapReponseDescription->insert(std::pair<int, std::string>(500, "HTTP/1.1 500 Internal Server Error")); WsjcppLightWebHttpResponse::g_mapReponseDescription->insert(std::pair<int, std::string>(501, "HTTP/1.1 501 Not Implemented")); WsjcppLightWebHttpResponse::g_mapReponseDescription->insert(std::pair<int, std::string>(408, "HTTP/1.1 408 Request Time-out")); } m_nSockFd = nSockFd; m_bClosed = false; noCache(); long nSec = WsjcppCore::getCurrentTimeInSeconds(); m_sLastModified = WsjcppCore::formatTimeForWeb(nSec); m_nResponseCode = 500; m_sDataType = "text/html"; } // ---------------------------------------------------------------------- WsjcppLightWebHttpResponse &WsjcppLightWebHttpResponse::ok() { m_nResponseCode = 200; return *this; } // ---------------------------------------------------------------------- WsjcppLightWebHttpResponse &WsjcppLightWebHttpResponse::badRequest() { m_nResponseCode = 400; return *this; } // ---------------------------------------------------------------------- WsjcppLightWebHttpResponse &WsjcppLightWebHttpResponse::forbidden() { m_nResponseCode = 403; return *this; } // ---------------------------------------------------------------------- WsjcppLightWebHttpResponse &WsjcppLightWebHttpResponse::notFound() { m_nResponseCode = 404; return *this; } // ---------------------------------------------------------------------- WsjcppLightWebHttpResponse &WsjcppLightWebHttpResponse::payloadTooLarge() { m_nResponseCode = 413; return *this; } // ---------------------------------------------------------------------- WsjcppLightWebHttpResponse &WsjcppLightWebHttpResponse::internalServerError() { m_nResponseCode = 500; return *this; } // ---------------------------------------------------------------------- WsjcppLightWebHttpResponse &WsjcppLightWebHttpResponse::notImplemented() { m_nResponseCode = 501; return *this; } // ---------------------------------------------------------------------- WsjcppLightWebHttpResponse &WsjcppLightWebHttpResponse::requestTimeout() { m_nResponseCode = 408; return *this; } // ---------------------------------------------------------------------- WsjcppLightWebHttpResponse &WsjcppLightWebHttpResponse::noCache() { m_sCacheControl = "no-cache, no-store, must-revalidate"; return *this; } // ---------------------------------------------------------------------- WsjcppLightWebHttpResponse &WsjcppLightWebHttpResponse::cacheSec(int nCacheSec) { m_sCacheControl = "max-age=" + std::to_string(nCacheSec); return *this; } // ---------------------------------------------------------------------- std::string WsjcppLightWebHttpResponse::prepareHeaders(int nLength) { std::string sResponseCode = WsjcppLightWebHttpResponse::g_mapReponseDescription->at(m_nResponseCode); return sResponseCode + "\r\n" "Date: " + m_sLastModified + "\r\n" "Server: wsjcpp\r\n" "Access-Control-Allow-Origin: *\r\n" "Cache-Control: " + m_sCacheControl + "\r\n" "Last-Modified: " + m_sLastModified + "\r\n" // TODO generate data "Content-Length: " + std::to_string(nLength) + "\r\n" "Content-Type: " + m_sDataType + "\r\n" "Connection: Closed\r\n"; } // ---------------------------------------------------------------------- std::string WsjcppLightWebHttpResponse::detectTypeOfFile(const std::string &sFilePath) { // TODO cache: check file in cache std::string sFileExt = sFilePath.substr(sFilePath.find_last_of(".") + 1); std::string sType = "application/octet-stream"; if (sFileExt == "json") { sType = "application/json"; } else if (sFileExt == "css") { sType = "text/css"; } else if (sFileExt == "js") { sType = "text/javascript"; } else if (sFileExt == "html") { sType = "text/html"; } else if (sFileExt == "gif") { sType = "image/gif"; } else if (sFileExt == "ico") { sType = "image/x-icon"; } else if (sFileExt == "xml") { sType = "application/xml"; } else if (sFileExt == "png") { sType = "image/png"; } else if (sFileExt == "jpg" || sFileExt == "jpeg") { sType = "image/jpeg"; } else if (sFileExt == "svg") { sType = "image/svg+xml"; } return sType; } // ---------------------------------------------------------------------- void WsjcppLightWebHttpResponse::sendText(const std::string &sBody) { m_sDataType = "text/html"; std::string sResponse = prepareHeaders(sBody.length()) + "\r\n" + sBody; if (m_bClosed) { WsjcppLog::warn(TAG, "Already sended response"); return; } m_bClosed = true; WsjcppLog::info(TAG, "\nResponse: \n>>>\n" + sResponse + "\n<<<"); send(m_nSockFd, sResponse.c_str(), sResponse.length(),0); close(m_nSockFd); } // ---------------------------------------------------------------------- void WsjcppLightWebHttpResponse::sendJson(const nlohmann::json &json) { m_sDataType = "application/json"; std::string sBody = json.dump(); std::string sResponse = prepareHeaders(sBody.length()) + "\r\n" + sBody; if (m_bClosed) { WsjcppLog::warn(TAG, "Already sended response"); return; } m_bClosed = true; WsjcppLog::info(TAG, "\nResponse: \n>>>\n" + sResponse + "\n<<<"); send(m_nSockFd, sResponse.c_str(), sResponse.length(),0); close(m_nSockFd); } // ---------------------------------------------------------------------- void WsjcppLightWebHttpResponse::sendEmpty() { this->sendText(""); } // ---------------------------------------------------------------------- void WsjcppLightWebHttpResponse::sendOptions(const std::string &sOptions) { m_sDataType = "text/html"; std::string sResponse = prepareHeaders(0) + "Access-Control-Allow-Methods: " + sOptions + "\r\n\r\n"; if (m_bClosed) { WsjcppLog::warn(TAG, "Already sended response"); return; } m_bClosed = true; WsjcppLog::info(TAG, "\nResponse: \n>>>\n" + sResponse + "\n<<<"); send(m_nSockFd, sResponse.c_str(), sResponse.length(),0); close(m_nSockFd); } // ---------------------------------------------------------------------- void WsjcppLightWebHttpResponse::sendFile(const std::string &sFilePath) { // read data from file std::ifstream f(sFilePath, std::ios::binary | std::ios::ate); std::streamsize nSize = f.tellg(); f.seekg(0, std::ios::beg); char *pData = new char[nSize]; // std::vector<char> buffer(size); if (nSize > 10*1024*1024) { this->payloadTooLarge(); this->sendEmpty(); delete[] pData; return; } if (!f.read(pData, nSize)) { this->forbidden(); this->sendEmpty(); delete[] pData; return; // std::cout << sFilePath << "\n filesize: " << nSize << " bytes\n"; } this->sendBuffer(sFilePath, pData, nSize); delete[] pData; } // ---------------------------------------------------------------------- void WsjcppLightWebHttpResponse::sendBuffer(const std::string &sFilePath, const char *pBuffer, const int nBufferSize) { // TODO cache: check file in cache m_sDataType = detectTypeOfFile(sFilePath); std::string sResponse = prepareHeaders(nBufferSize) + "\r\n"; if (m_bClosed) { WsjcppLog::warn(TAG, "Already sended response"); // delete[] pData; return; } m_bClosed = true; write(m_nSockFd, sResponse.c_str(), sResponse.length()); write(m_nSockFd, pBuffer, nBufferSize); close(m_nSockFd); }
7c61e1f050abff11d1584e99e400a3d17bf138d6
8722f2da8bc1a6b3e16ce5759f67ca292c0a7341
/src/beast/beast/Config.h
95da9375b9f62125a9abe208234389364711c227
[ "MIT", "MIT-Wu", "ISC", "BSL-1.0" ]
permissive
waynezu/vpal20
010fbec860b6c4d8c775b8d637730580e842d597
8deef35521417cd4405d7bbadd030b89bd4fb91b
refs/heads/master
2020-12-25T21:35:01.584301
2014-10-27T03:58:56
2014-10-27T03:58:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,515
h
//------------------------------------------------------------------------------ /* Portions of this file are from Vpallab: https://github.com/vpallabs Copyright (c) 2013 - 2014 - Vpallab.com. Please visit http://www.vpallab.com/ This file is part of Beast: https://github.com/vinniefalco/Beast Copyright 2013, Vinnie Falco <[email protected]> Portions of this file are from JUCE. Copyright (c) 2013 - Raw Material Software Ltd. Please visit http://www.juce.com Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #ifndef BEAST_CONFIG_H_INCLUDED #define BEAST_CONFIG_H_INCLUDED // VFALCO NOTE this is analogous to <boost/config.hpp> // Assert to boost that we always have std::array support #define BOOST_ASIO_HAS_STD_ARRAY 1 #if !defined(BEAST_COMPILER_CONFIG) && !defined(BEAST_NO_COMPILER_CONFIG) && !defined(BEAST_NO_CONFIG) #include <beast/config/SelectCompilerConfig.h> #endif #ifdef BEAST_COMPILER_CONFIG #include BEAST_COMPILER_CONFIG #endif #if !defined(BEAST_STDLIB_CONFIG) && !defined(BEAST_NO_STDLIB_CONFIG) && !defined(BEAST_NO_CONFIG) && defined(__cplusplus) #include <beast/config/SelectStdlibConfig.h> #endif #ifdef BEAST_STDLIB_CONFIG #include BEAST_STDLIB_CONFIG #endif #if !defined(BEAST_PLATFORM_CONFIG) && !defined(BEAST_NO_PLATFORM_CONFIG) && !defined(BEAST_NO_CONFIG) #include <beast/config/SelectCompilerConfig.h> #endif #ifdef BEAST_PLATFORM_CONFIG #include BEAST_PLATFORM_CONFIG #endif // Legacy #include <beast/Version.h> #include <beast/config/PlatformConfig.h> #include <beast/config/CompilerConfig.h> #include <beast/config/StandardConfig.h> #include <beast/config/ConfigCheck.h> // Suffix #include <beast/config/Suffix.h> #endif
79cfff73d31b28cee8b478d5c39dacb9c7343250
cb93bcc328d66756cd22b58c8040489c1cfdfc04
/Project_Alice/Project/Alice_Engine/Engine_Struct.h
11846e48f97c3a387fad3815aee522d8a23d3e22
[]
no_license
haeunjung/Team_Project
ba9661729ed25be4a3fb22dc288dee05281b2613
ecd2b67c504af116a2e4f30114fe943f3a472e19
refs/heads/master
2018-10-30T11:20:50.980879
2018-10-05T11:18:09
2018-10-05T11:18:09
103,035,103
4
0
null
null
null
null
UHC
C++
false
false
11,776
h
#pragma once //#include "Engine_Macro.h" #include "Engine_Enum.h" WOOJUN_BEGIN // Resolution typedef struct DLL _tagResolution { unsigned int m_iWidth; unsigned int m_iHeight; // 생성자 _tagResolution() : m_iWidth(0), m_iHeight(0) {} _tagResolution(unsigned int _iW, unsigned int _iH) : m_iWidth(_iW), m_iHeight(_iH) {} // 복사생성자 _tagResolution(const _tagResolution& _Other) { *this = _Other; } // 대입연산자 void operator=(const _tagResolution& _Other) { m_iWidth = _Other.m_iWidth; m_iHeight = _Other.m_iHeight; } }RESOLUTION, *pROSOLUTION; // 버텍스 버퍼 typedef struct DLL _tagVertexBuffer { ID3D11Buffer* pBuffer; void* pData; unsigned int iCount; unsigned int iSize; D3D11_PRIMITIVE_TOPOLOGY ePrimitive; D3D11_USAGE eUsage; _tagVertexBuffer() : pBuffer(NULL), pData(NULL), iCount(0), iSize(0), ePrimitive(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST), eUsage(D3D11_USAGE_DEFAULT) { } }VERTEXBUFFER, *pVERTEXBUFFER; // 인덱스 버퍼 typedef struct DLL _tagIndexBuffer { ID3D11Buffer* pBuffer; void* pData; unsigned int iCount; unsigned int iSize; DXGI_FORMAT eFormat; D3D11_USAGE eUsage; _tagIndexBuffer() : pBuffer(NULL), pData(NULL), iCount(0), iSize(0), eFormat(DXGI_FORMAT_R32_UINT), eUsage(D3D11_USAGE_DEFAULT) { } }INDEXBUFFER, *pINDEXBUFFER; // Mesh Containger typedef struct DLL _tagMeshContainer { pVERTEXBUFFER pVtxBuffer; vector<pINDEXBUFFER> vecIndexBuffer; vector<class CMaterial*> vecMaterial; _tagMeshContainer() : pVtxBuffer(NULL) { } }MESHCONTAINER, *pMESHCONTAINER; // Transform 행렬 정보 구조체 typedef struct DLL __declspec(align(16)) _tagTransformCBuffer { XMMATRIX matWorld; XMMATRIX matView; XMMATRIX matProj; XMMATRIX matWV; XMMATRIX matWVP; XMMATRIX matVP; XMMATRIX matInvProj; XMMATRIX matInvView; XMMATRIX matInvVP; DxVector3 vPivot; float fEmpty1; DxVector3 vMeshSize; float fEmpty2; DxVector3 vMeshMin; float fEmpty3; DxVector3 vMeshMax; float fEmpty4; }TRANSFORMCBUFFER, *pTRANSFORMCBUFFER; // Color Vertex typedef struct DLL _tagVertexColor { DxVector3 vPos; DxVector4 vColor; _tagVertexColor() : vPos(0.0f, 0.0f, 0.0f), vColor(0.0f, 0.0f, 0.0f, 0.0f) { } _tagVertexColor(const _tagVertexColor& _Other) { *this = _Other; } _tagVertexColor(float x, float y, float z, float r, float g, float b, float a) : vPos(x, y, z), vColor(r, g, b, a) { } void operator =(const _tagVertexColor& _Other) { vPos = _Other.vPos; vColor = _Other.vColor; } }VERTEXCOLOR, *pVERTEXCOLOR; // 텍스쳐 버퍼 typedef struct DLL _tagVertexTexture { DxVector3 vPos; DxVector2 vUV; _tagVertexTexture() : vPos(0.f, 0.f, 0.f), vUV(0.f, 0.f) { } _tagVertexTexture(const _tagVertexTexture& vtx) { *this = vtx; } _tagVertexTexture(float x, float y, float z, float u, float v) : vPos(x, y, z), vUV(u, v) { } void operator =(const _tagVertexTexture& vtx) { vPos = vtx.vPos; vUV = vtx.vUV; } }VERTEXTEXTURE, *pVERTEXTEXTURE; // 텍츠쳐 노말 버퍼 typedef struct DLL _tagVertexNormalTexture { DxVector3 vPos; DxVector3 vNormal; DxVector2 vUV; _tagVertexNormalTexture() : vPos(0.f, 0.f, 0.f), vNormal(0.f, 0.f, 0.f), vUV(0.f, 0.f) { } _tagVertexNormalTexture(const _tagVertexNormalTexture& vtx) { *this = vtx; } _tagVertexNormalTexture(float x, float y, float z, float nx, float ny, float nz, float u, float v) : vPos(x, y, z), vNormal(nx, ny, nz), vUV(u, v) { } void operator =(const _tagVertexNormalTexture& vtx) { vPos = vtx.vPos; vNormal = vtx.vNormal; vUV = vtx.vUV; } }VERTEXNORMALTEXTURE, *pVERTEXNORMALTEXTURE; // 위치 버텍스 버퍼 typedef struct DLL _tagVertexPos { DxVector3 vPos; _tagVertexPos() : vPos(0.0f, 0.0f, 0.0f) { } _tagVertexPos(const _tagVertexPos& _Other) { *this = _Other; } _tagVertexPos(float x, float y, float z) : vPos(x, y, z) { } void operator =(const _tagVertexPos& _Other) { vPos = _Other.vPos; } }VERTEXPOS, *pVERTEXPOS; // 범프 버텍스 버퍼 typedef struct DLL _tagVertexBump { DxVector3 vPos; DxVector3 vNormal; DxVector2 vUV; DxVector3 vTangent; DxVector3 vBinormal; _tagVertexBump() : vPos(0.f, 0.f, 0.f), vNormal(0.f, 0.f, 0.f), vUV(0.f, 0.f), vTangent(0.f, 0.f, 0.f), vBinormal(0.f, 0.f, 0.f) { } _tagVertexBump(const _tagVertexBump& vtx) { *this = vtx; } _tagVertexBump(float x, float y, float z, float nx, float ny, float nz, float u, float v, float tx, float ty, float tz, float bx, float by, float bz) : vPos(x, y, z), vNormal(nx, ny, nz), vUV(u, v), vTangent(tx, ty, tz), vBinormal(bx, by, bz) { } void operator =(const _tagVertexBump& vtx) { vPos = vtx.vPos; vNormal = vtx.vNormal; vUV = vtx.vUV; vTangent = vtx.vTangent; vBinormal = vtx.vBinormal; } }VERTEXBUMP, *pVERTEXBUMP; // 애니메이션 범프 버텍스 버퍼 typedef struct DLL _tagVertexAniBump { DxVector3 vPos; DxVector3 vNormal; DxVector2 vUV; DxVector3 vTangent; DxVector3 vBinormal; DxVector4 vWeight; DxVector4 vIndices; _tagVertexAniBump() : vPos(0.f, 0.f, 0.f), vNormal(0.f, 0.f, 0.f), vUV(0.f, 0.f), vTangent(0.f, 0.f, 0.f), vBinormal(0.f, 0.f, 0.f), vWeight(0.f, 0.f, 0.f, 0.f), vIndices(0.f, 0.f, 0.f, 0.f) { } _tagVertexAniBump(const _tagVertexAniBump& vtx) { *this = vtx; } _tagVertexAniBump(float x, float y, float z, float nx, float ny, float nz, float u, float v, float tx, float ty, float tz, float bx, float by, float bz, float wx, float wy, float wz, float ww, float ix, float iy, float iz, float iw) : vPos(x, y, z), vNormal(nx, ny, nz), vUV(u, v), vTangent(tx, ty, tz), vBinormal(bx, by, bz), vWeight(wx, wy, wz, ww), vIndices(ix, iy, iz, iw) { } void operator =(const _tagVertexAniBump& vtx) { vPos = vtx.vPos; vNormal = vtx.vNormal; vUV = vtx.vUV; vTangent = vtx.vTangent; vBinormal = vtx.vBinormal; vWeight = vtx.vWeight; vIndices = vtx.vIndices; } }VERTEXANIBUMP, *pVERTEXANIBUMP; // 애니메이션 범프 버텍스 버퍼 typedef struct DLL _tagVertexAni { DxVector3 vPos; DxVector3 vNormal; DxVector2 vUV; DxVector4 vWeight; DxVector4 vIndices; _tagVertexAni() : vPos(0.f, 0.f, 0.f), vNormal(0.f, 0.f, 0.f), vUV(0.f, 0.f), vWeight(0.f, 0.f, 0.f, 0.f), vIndices(0.f, 0.f, 0.f, 0.f) { } _tagVertexAni(const _tagVertexAni& vtx) { *this = vtx; } _tagVertexAni(float x, float y, float z, float nx, float ny, float nz, float u, float v, float wx, float wy, float wz, float ww, float ix, float iy, float iz, float iw) : vPos(x, y, z), vNormal(nx, ny, nz), vUV(u, v), vWeight(wx, wy, wz, ww), vIndices(ix, iy, iz, iw) { } void operator =(const _tagVertexAni& vtx) { vPos = vtx.vPos; vNormal = vtx.vNormal; vUV = vtx.vUV; vWeight = vtx.vWeight; vIndices = vtx.vIndices; } }VERTEXANI, *pVERTEXANI; // Particle Vertex typedef struct _tagVertexParticle { DxVector3 vPos; DxVector3 vVelocity; DxVector2 vSize; float fLifeTime; float fCreateTime; unsigned int iType; float fLightRange; }VERTEXPARTICLE, *pVERTEXPARTICLE; // 상수버퍼 typedef struct DLL _tagConstBuffer { ID3D11Buffer* pBuffer; int iSize; int iRegister; }CONSTBUFFER, *pCONSTBUFFER; // 충돌체 컬러 상수버퍼 typedef struct DLL _tagColColorCBuffer { DxVector4 vColor; }COLCOLORCBUFFER, *pCOLCOLORCBUFFER; typedef struct DLL _tagSphereInfo { DxVector3 vCenter; float fRadius; _tagSphereInfo() : vCenter(0.0f, 0.0f, 0.0f), fRadius(0.0f) { } _tagSphereInfo(const _tagSphereInfo& _tSphere) { *this = _tSphere; } _tagSphereInfo(const DxVector3& _vCenter, float _fRadius) : vCenter(_vCenter), fRadius(_fRadius) { } _tagSphereInfo(float _fX, float _fY, float _fZ, float _fRadius) : vCenter(_fX, _fY, _fZ), fRadius(_fRadius) { } float Distance(const _tagSphereInfo& _tSphere) const { return vCenter.Distance(_tSphere.vCenter); } float Distance(const _tagSphereInfo* _tSphere) const { return Distance(*_tSphere); } }SPHEREINFO, *pSPHEREINFO; typedef struct DLL _tagAABBInfo { DxVector3 vCenter; DxVector3 vScale; COL_AABB_POS eColAABB; _tagAABBInfo() : vCenter(0.0f, 0.0f, 0.0f), vScale(0.0f, 0.0f, 0.0f), eColAABB(CAP_DEFAULT) { } _tagAABBInfo(const _tagAABBInfo& _tAABB) { *this = _tAABB; } _tagAABBInfo(const DxVector3& _vCenter, const DxVector3& _vLength) : vCenter(_vCenter), vScale(_vLength) { } }AABBINFO, *pAABBINFO; typedef struct _tagRectInfo { float fTop; float fBottom; float fLeft; float fRight; _tagRectInfo() : fLeft(0.0f), fTop(0.0f), fRight(0.0f), fBottom(0.0f) { } _tagRectInfo(float _fLeft, float _fTop, float _fRight, float _fBottom) : fLeft(_fLeft), fTop(_fTop), fRight(_fRight), fBottom(_fBottom) { } _tagRectInfo(const _tagRectInfo& _rc) { fLeft = _rc.fLeft; fTop = _rc.fTop; fRight = _rc.fRight; fBottom = _rc.fBottom; } void MoveRect(float _fX, float _fY) { fLeft += _fX; fTop += _fY; fRight += _fX; fBottom += _fY; } }RECTINFO, *PRECTINFO; typedef struct DLL _tagRay { DxVector3 vPos; DxVector3 vDir; DxVector3 vIntersect; bool bIntersect; }RAY, *pRAY; typedef struct DLL _tagTerrainInfo { vector<DxVector3> vecPos; UINT iNumW; UINT iNumH; }TERRAININFO, *pTERRAININFO; typedef struct DLL _tagLightInfo { DxVector4 vDiffuse; DxVector4 vAmbient; DxVector4 vSpecular; DxVector3 vAttenuation; // 감쇠상수 LIGHT_TYPE eType; }LIGHTINFO, *pLIGHTINFO; typedef struct DLL _tagLightCBuffr { DxVector4 vDiffuse; DxVector4 vAmbient; DxVector4 vSpecular; LIGHT_TYPE eType; DxVector3 vDir; DxVector3 vPos; float fRange; DxVector3 vAttenuation; float fSpot; }LIGHTCBUFFER, *pLIGHTCBUFFER; typedef struct DLL _tagMaterialInfo { DxVector4 vDiffuse; DxVector4 vAmbient; DxVector4 vSpecular; DxVector4 vEmissive; int iBump; int iSpecular; float fSpecularPower; int iEmpty; }MATERIALINFO, *pMATERIALINFO; // Effect CBuffer typedef struct DLL _tagEffectCBuffer { // SIMD 레지스터 사용이므로 // 128비트 단위로 맞춰야한다 // 안그러면 셰이더에 이상한값 세팅됨 DxVector3 vCenter; float fEmpty1; DxVector3 vCamAxisY; float fEmpty2; DxVector3 vCamPos; float fEmpty3; DxVector2 vSize; DxVector2 vEmpty4; }EFFECTCBUFFER, *pEFFECTCBUFFER; // Animation2D Clip typedef struct DLL _tagAnimationClip2D { string strName; class CTexture* pTexture; int iTexRegister; ANIMATION2D_TYPE eType; ANIMATION_OPTION eOption; int iFrameX; int iFrameY; int iFrameMaxX; int iFrameMaxY; float fFrameTime; float fLimitTime; int iLoopCount; float fLoopTime; }ANIMATIONCLIP2D, *pANIMATIONCLIP2D; // Animation2D CBuffer typedef struct DLL _tagAnimation2DCBuffer { ANIMATION2D_TYPE eType; int iFrameX; int iFrameY; int iFrameMaxX; int iFrameMaxY; DxVector3 vEmpty; }ANIMATION2DCBUFFER, *pANIMATION2DCBUFFER; typedef struct DLL _tagTerrainCBuffer { float fDetailLevel; int iSplatCount; DxVector2 vEmpty; }TERRAINCBUFFER, *pTERRAINCBUFFER; typedef struct DLL _tagRendererCBuffer { int iRegister; int iSize; void* pData; int iShaderType; }RENDERERCBUFFER, *pRENDERERCBUFFER; // Static Object Data typedef struct DLL _tagObjectData { string strKey; wstring wstrFileName; DxVector3 vPos; DxVector3 vScale; DxVector3 vRot; }OBJECTDATA, *pOBJECTDATA; typedef struct DLL _tagParticleCBuffer { DxVector3 vPos; float fDeltaTime; DxVector3 vCamAxisX; float fCreateTime; DxVector3 vCamAxisY; float fSpeed; float fGameTime; DxVector3 vCreateDir; }PARTICLECBUFFER, *PPARTICLECBUFFER; typedef struct DLL _tagMinionData { DxVector3 vPos; int iType; }MINIONDATA, *pMINIONDATA; WOOJUN_END
b4b311f497cc7eeccd5a8f94721a53f159741b5c
9e1f30e17e7d5e0330f20bd1443852878b31344a
/gift1.cc
703c10dc0b9986198f00fd5a2a02939d17628cad
[]
no_license
pwnall/usaco
4de13038817b9c7434031c48fc9746d3e9642449
9a9089a5b45c23de97ef8b0d8ec2de283fa1ebb9
refs/heads/master
2023-09-01T11:57:07.133618
2017-04-05T03:16:34
2017-04-05T03:16:37
85,672,416
1
1
null
null
null
null
UTF-8
C++
false
false
1,299
cc
/* PROG: gift1 LANG: C++11 */ #include <fstream> #include <iostream> #include <sstream> #include <string> #include <vector> #include <unordered_map> int main() { std::ofstream cout("gift1.out"); std::ifstream cin("gift1.in"); int n; std::string line_string; std::getline(cin, line_string); std::stringstream line(line_string); line >> n; std::vector<std::string> names; std::unordered_map<std::string, int> balances; for (int i = 0; i < n; ++i) { std::string name; std::getline(cin, name); balances[name] = 0; names.push_back(name); } for (int i = 0; i < n; ++i) { std::string giver; std::getline(cin, giver); std::getline(cin, line_string); line = std::stringstream(line_string); int sum, receiver_count; line >> sum >> receiver_count; int transfer; if (receiver_count == 0) { transfer = 0; balances[giver] += sum; } else { transfer = (sum / receiver_count); balances[giver] += sum % receiver_count - sum; } for (int j = 0; j < receiver_count; ++j) { std::string receiver; std::getline(cin, receiver); balances[receiver] += transfer; } } for (int i = 0; i < n; ++i) { cout << names[i] << " " << balances[names[i]] << std::endl; } return 0; }
fcb8d98a2816446b7a94db14c3bcd1ab94bd0d8a
32b153a64f3ab050945d78adb2da4ca48e21fcb0
/lis.cpp
6d32fb83722fd92209cfd91e2c99ca9d50dd1d88
[]
no_license
mohdarsh1786/code
b679d6c7fad99fa1311103e5fceb7ca2aecaf548
4c933aa15250edb2fd6e8af632a7cd68704c1763
refs/heads/master
2021-01-01T04:46:41.068150
2017-07-30T17:02:42
2017-07-30T17:02:42
97,240,246
0
0
null
null
null
null
UTF-8
C++
false
false
647
cpp
#include<bits/stdc++.h> using namespace std; int lis(vector<int> arr,int n) { int l[n]; for(int p=0;p<n;p++) { l[p]=1; } for(int i=1;i<n;i++) for(int j=0;j<i;j++) { if(arr[i]>arr[j] && l[i]<l[j]+1) { l[i]=l[j]+1; } } int max1=0; for(int p=0;p<n;p++) { if(max1<l[p]) max1=l[p]; } return max1; } int main() { int n,i; cin>>n; vector<int> arr(n); for(i=0;i<n;i++) cin>>arr[i]; int p=lis(arr,n); cout<<p; }
2d94e40a3ba8b2ff64da21937a5ec052b3f91f1a
348bfb528d6343c9c2a18406fc2b0e29bfc1deb5
/pistolji.h
ab41a41f60ddaa276fa02bc9a33d82457e3bf337
[]
no_license
Kraguljac23/samostalni_projekat_gta
37035f5bf4d7fbaec9654f3fd8e805ef312d9265
ed771fb7e4b0db07af7b7557b7a9c443026b93d5
refs/heads/master
2021-05-21T03:57:26.825964
2020-05-15T15:13:29
2020-05-15T15:13:29
252,532,175
0
0
null
null
null
null
UTF-8
C++
false
false
1,369
h
#ifndef PISTOLJI_H_INCLUDED #define PISTOLJI_H_INCLUDED #include "oruzje.h" enum tipPistolja{AUTOMATSKI, SINGLE, REVOLVER}; enum princip{CAPLOCK, SEMI}; class pistolji: public oruzje{ private: tipPistolja pis; bool laser; princip prc; public: pistolji():oruzje(){ tip = PISTOLJ; if(tipPistolja == AUTOMATSKI){ puc = AUTOMATSKI; prc = SEMI; }else if(tipPistolja == SINGLE){ puc = SINGLE; prc = SEMI; }else if(tipPistolja == REVOLVER){ puc = SINGLE; prc = CAPLOCK; } if(laser == true){ accuracy += 0.5; }else{ accuracy = 3.5; } cena = 900; range = 100; BrMunicije = 20; } pistolji(int c, int br,princip p, float d, tipPistolja p, TipOruzja t, TipPucanja p) : oruzje(c, br, p, t, d, r){ pis = p; laser = l; prc = pp; } pistolji(const pistolji &p):oruzje(p.cena, p.tip, p.puc, p.BrMunicije, p.damage, p.range){ pis = p.pis; prc = p.prc; } GettipPistplja()const {return pis;} void settipPistolja(tipPistolja p)(pis = p); getlaser()const {return laser;} void setlaser(bool l)(laser = l); getprincip()const {return prc;} void setprincip(princip p)(prc = p); }; #endif // PISTOLJI_H_INCLUDED
fba45aaaef0f2996228eacee2d9f1505588833b1
4384d7e8bf4028a8d665b7b6cbc78592fe80cece
/short_problems/C++/bubble_sort.cpp
fa3e3751c8aa13f25c708d6f61dfc784c8053077
[]
no_license
ionutRD/p-code
1d7da111dc4814ac0000281b99fe2288af35ce3c
969df759f805906c31e582ee6e36aeb9876fcb29
refs/heads/master
2022-11-11T02:55:58.412231
2022-11-07T10:36:55
2022-11-07T10:36:55
6,155,116
0
0
null
null
null
null
UTF-8
C++
false
false
1,118
cpp
#include <algorithm> #include <functional> #include <iostream> #include <iterator> #include <vector> using namespace std; template <typename RandomIt, typename Compare = less<typename RandomIt::value_type>> void bubble_sort(RandomIt first, RandomIt last, Compare comp = Compare()) { if (first == last) { return; } bool sorted = false; while (!sorted) { sorted = true; for (auto it = first; it != last - 1; ++it) { if (!comp(*it, *(it + 1))) { sorted = false; iter_swap(it, it + 1); } } } } int main() { vector<int> coll1 {1, 5, 8, 0, 3, 2}; bubble_sort(begin(coll1), end(coll1)); copy(begin(coll1), end(coll1), ostream_iterator<int>(cout, " ")); cout << endl; vector<int> coll2 {1}; bubble_sort(begin(coll2), end(coll2)); copy(begin(coll2), end(coll2), ostream_iterator<int>(cout, " ")); cout << endl; vector<int> coll3 {}; bubble_sort(begin(coll3), end(coll3)); copy(begin(coll3), end(coll3), ostream_iterator<int>(cout, " ")); cout << endl; return 0; }
4b5dab4d622a34de73de6073fc7cf46877f4d744
a5ff8f5e6b3c76149461ce6ea0978e34ba7e068a
/SpoutSDK/SpoutSDK/SpoutSDK.cpp
471e5950fc6839178e9f039585d8596c10f76cf6
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
felix2072/pytorch-CycleGAN-and-pix2pix
1d7c8824633f8a16d7e0f2b95c4d760937d141b5
4980106ceab5e1eb7bb20c2b492d007b6310d9e1
refs/heads/master
2023-04-01T14:12:23.232531
2021-04-12T16:46:47
2021-04-12T16:46:47
343,559,836
0
0
null
null
null
null
UTF-8
C++
false
false
58,509
cpp
// ================================================================ // // SpoutSDK // // The Main Spout class - used by Sender and Receiver classes // // Revisions : // // 14-07-14 - SelectSenderPanel - return true was missing. // 16-07-14 - deleted fbo & texture in SpoutCleanup - test for OpenGL context // - used CopyMemory in FlipVertical instead of memcpy // - cleanup // 18-07-14 - removed SpoutSDK local fbo and texture - used in the interop class now // 22-07-14 - added option for DX9 or DX11 // 25-07-14 - Malcolm Bechard mods to header to enable compilation as a dll // - ReceiveTexture - release receiver if the sender no longer exists // - ReceiveImage same change - to be tested // 27-07-14 - CreateReceiver - bUseActive flag instead of null name // 31-07-14 - Corrected DrawTexture aspect argument // 01-08-14 - TODO - work on OpenReceiver for memoryshare // 03-08-14 - CheckSpoutPanel allow for unregistered sender // 04-08-14 - revise CheckSpoutPanel // 05-08-14 - default true for setverticalsync in sender and receiver classes // 11-08-14 - fixed incorrect name arg in OpenReceiver for ReceiveTexture / ReceiveImage // 24-08-14 - changed back to WM_PAINT message instead of RedrawWindow due to FFGL receiver bug appearing again // 27-08-14 - removed texture init check from SelectSenderPanel // 29-08-14 - changed SelectSenderPanel to use revised SpoutPanel with user message support // 03.09.14 - cleanup // 15.09.14 - protect against null string copy in SelectSenderPanel // 22.09.14 - checking of bUseAspect function in CreateReceiver // 23.09.14 - test for DirectX 11 support in SetDX9 and GetDX9 // 24.09.14 - updated project file for DLL to include SpoutShareMemory class // 28.09.14 - Added GL format for SendImage and FlipVertical // - Added bAlignment (4 byte alignment) flag for SendImage // - Added Host FBO for SendTexture, DrawToSharedTexture // - Added Host FBO for ReceiveTexture // 11.10.14 - Corrected UpdateSender to recreate sender using CreateInterop // - Corrected SelectSenderpanel so that an un-initialized string is not used // 12.10.14 - Included SpoutPanel always bring to topmost in SelectSenderPanel // - allowed for change of sender size in DrawToSharedTexture // 15.10.14 - added debugging aid for texture access locks // 29.10.14 - changes to SendImage // 23.12.14 - added host fbo arg to ReceiveImage // 30.01.15 - Read SpoutPanel path from registry (dependent on revised installer) // Next path checked is module path, then current working directory // 06.02.15 - added #pragma comment(lib,.. for "Shell32.lib" and "Advapi32.lib" // 10.02.15 - added Optimus NvOptimusEnablement export to Spout.h - should apply to all apps including this SDK. // 22.02.15 - added FindFileVersion for future use // 24.05.15 - Registry read of sender name for CheckSpoutPanel (see SpoutPanel) // 29.05.15 - Included SetAdapter for multiple adapters - Franz Hildgen. // 01.06.15 - Read/Write DX9 mode from registry // 02.06.15 - Added GetAdapter, GetNumAdapters, GetAdapterName // 04.07.15 - corrected "const char *" arg for GetSenderInfo // 08.07.15 - Recompile for global DX9 flag // 01.08.15 - OpenReceiver - safety in case no opengl context // 22.08.15 - Change to CheckSpoutPanel to wait for SpoutPanel mutex to open and then close // 24.08.15 - Added GetHostPath to retrieve the path of the host that produced the sender // 01.09.15 - added MessageBox error warnings in InitSender for better user diagnostics // also added MessageBox warnings in SpoutGLDXinterop::CreateInterop // 09.09.15 - included g_ShareHandle in CheckSpoutPanel // - removed bMemoryShareInitOK becasue there is no single initialization any more // 12.09.15 - Incremented application sender name if one already exists with the same name // - Finalised revised SpoutMemoryShare class and functions // 15.09.15 - Disable memoryshare if the 2.005 installer has not set the "MemoryShare" key // to avoid problems with 2.004 apps. // - Change logic of OpenSpout so that fails for incompatible hardware // if memoryshare is not set. Only 2.005 apps can set memoryshare.\ // 19.09.15 - Changed GetImageSize to look for NULL sharehandle of a sender to determine // if it is memoryshare. Used by SpoutCam. // 22.09.15 - Fixed memoryshare sender update in UpdateSender // 25.09.15 - Changed SetMemoryShareMode for 2.005 - now will only set true for 2.005 and above // 09.10.15 - DrawToSharedTexture - invert default false instead of true // 10.10.15 - CreateSender - introduced a temporary DX shared texture for 2.005 memoryshare to prevent // a crash with existing 2.004 apps // 22.10.15 - Changed CheckSpoutPanel so that function variables are only created if SpoutPanel has been opened // 26.10.15 - Added bIsSending and bIsReceiving for safety release of sender in destructor. // 14.11.15 - changed functions to "const char *" where required // 18.11.15 - added CheckReceiver so that DrawSharedTexture can be used by a receiver // 24.11.15 - changes to CheckSpoutPanel to favour ActiveSender over the Registry sender name (used by VVVV) // - Reintroduced 250msec sleep after SpoutPanel activation // 29.11.15 - fixed const char problem in ReadPathFromRegistry // 18.01.16 - added CleanSenders before opening a new sender in case of orphaned sender names in the list // 10.02.16 - added RemovePathFromRegistry // 26.02.16 - recompile for Processing library 2.0.5.2 release // 06.03.16 - added GetSpoutSenderName() and IsSpoutInitialized() for access to globals // 17.03.16 - removed alignment argument from ReceiveImage // Check for bgra extensions in receiveimage and sendimage // Support only for rgba or bgra // Changed to const unsigned char for Sendimage buffer // 21.03.16 - Added glFormat and bInvert to SendImage // - Included LoadGLextensions in InitSender and InitReceiver for memoryshare mode. // 24.03.16 - Added HostFBO argument to WriteMemory and ReadMemory function calls. // 04.04.16 - Added HostFBO argument to SendImage - only used for texture share // Merge from Smokhov https://github.com/leadedge/Spout2/pull/14 // - Changed default invert flag for SendImage to true. // 24.04.16 - Added IsPBOavailable to test for PBO support. // 04.05.16 - SetPBOavailable(true/false) added to enable/disable pbo functions // 07.05.16 - SetPBOavailable changed to SetBufferMode // 18.06.16 - Add invert to ReceiveImage // 29.06.16 - Added ReportMemory() for debugging // - Changed OpenSpout to fail for DX9 if no hwnd // https://github.com/leadedge/Spout2/issues/18 // 03.07.16 - Fix dwFormat repeat declaration in InitSender // 15.01.17 - Add GetShareMode, SetShareMode // 18.01.17 - GetImageSize redundant for 2.006 // 22.01.17 - include zero char in SelectSenderPanel NULL arg checks // 25.05.17 - corrected SendImage UpdateSender to use passed width and height // // ================================================================ /* Copyright (c) 2014-2017, Lynn Jarvis. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "SpoutSDK.h" Spout::Spout() { /* // Debug console window FILE* pCout; AllocConsole(); freopen_s(&pCout, "CONOUT$", "w", stdout); printf("Spout::Spout()\n"); */ // printf("Spout::Spout()\n"); g_Width = 0; g_Height = 0; g_ShareHandle = 0; g_Format = 0; g_TexID = 0; g_hWnd = NULL; // handle to render window g_SharedMemoryName[0] = 0; // No name to start bDxInitOK = false; // Initialized in texture share mode bGLDXcompatible = false; // Not used bUseCPU = false; // Use CPU texture processing bMemory = false; // User or compatibility memoryshare mode bInitialized = false; // Has initialized or not bIsSending = false; // A sender bIsReceiving = false; // A receiver bChangeRequested = true; // set for initial bUseActive = false; // Use the active sender for CreateReceiver bSpoutPanelOpened = false; // Selection panel "spoutpanel.exe" opened bSpoutPanelActive = false; // The SpoutPanel window has been activated ZeroMemory(&m_ShExecInfo, sizeof(m_ShExecInfo)); } //--------------------------------------------------------- Spout::~Spout() { // Close the sender if it has not been done yet if(bInitialized && bIsSending && g_SharedMemoryName[0] > 0) { interop.senders.ReleaseSenderName(g_SharedMemoryName); } // This is the end, so cleanup and close directx or memoryshare SpoutCleanUp(true); // for debug // MessageBoxA(NULL, "~Spout Finished", "Spout", MB_OK); } // Public functions bool Spout::CreateSender(const char* sendername, unsigned int width, unsigned int height, DWORD dwFormat) { // printf("Spout::CreateSender [%s] (%dx%d)\n", sendername, width, height); // Make sure it has initialized // OpenSpout sets : bDxInitOK, bGLDXcompatible, bMemory, and bUseCPU if(!OpenSpout()) { printf("Spout::CreateSender - OpenSpout failed\n"); return false; } // Release any orphaned senders // the name exists in the list but the shared memory info does not CleanSenders(); // Set global sender name - TODO : check when strcpy_s(g_SharedMemoryName, 256, sendername); // Initialize as a sender in either texture, cpu or memoryshare mode return(InitSender(g_hWnd, sendername, width, height, dwFormat, bMemory)); } // end CreateSender // ------------------------------------------ // Update a sender // Used when a sender's texture changes size // The DirectX texture or memory map has to be re-created and the sender info updated // ------------------------------------------ bool Spout::UpdateSender(const char *sendername, unsigned int width, unsigned int height) { HANDLE hSharehandle = NULL; DWORD dwFormat = 0; unsigned int w, h; // Make sure it has initialized if(!bInitialized) return false; // If it is not the same sendername, quit if(strcmp(g_SharedMemoryName, sendername) != 0) return false; // printf("Spout::UpdateSender [%s] %dx%d\n", sendername, width, height); // Is the sender still there? - use local vars if(interop.senders.GetSenderInfo(sendername, w, h, hSharehandle, dwFormat)) { if(bDxInitOK) { // For texture and CPU modes, re-create the sender directX shared texture // with the new dimensions and update the sender info // No need to re-initialize DirectX, only the GLDX interop // which is re-registered for the new texture interop.CreateInterop(g_hWnd, sendername, width, height, dwFormat, false); // false means a sender } else { // Memoryshare has to update the sender information as well as the memory map size interop.senders.UpdateSender(sendername, width, height, NULL, 0); // Only the sender can update the memory map (see SpoutMemoryShare.cpp). interop.memoryshare.UpdateSenderMemorySize (sendername, width, height); } // // Get the new sender width, height and share handle into local globals // interop.senders.GetSenderInfo(g_SharedMemoryName, g_Width, g_Height, g_ShareHandle, g_Format); return true; } return false; } // end UpdateSender void Spout::ReleaseSender(DWORD dwMsec) { if(g_SharedMemoryName[0] > 0) interop.senders.ReleaseSenderName(g_SharedMemoryName); // if not registered it does not matter SpoutCleanUp(); bInitialized = false; // TODO - needs tracing bIsSending = false; Sleep(dwMsec); // TODO - needed ? } // 27.07-14 - change logic to allow an optional user flag to use the active sender bool Spout::CreateReceiver(char* sendername, unsigned int &width, unsigned int &height, bool bActive) { char UserName[256]; UserName[0] = 0; // OK to do this internally // Use the active sender if the user wants it or the sender name is not set if(bActive || sendername[0] == 0) { bUseActive = true; } else { // Try to find the sender with the name sent or over-ride with user flag strcpy_s(UserName, 256, sendername); bUseActive = false; // set global flag to use the active sender or not } // printf("Spout::CreateReceiver(%s) %dx%d, bActive = %d\n", UserName, width, height, bActive); // Make sure it has been initialized // OpenReceiver checks g_ShareHandle for NULL which indicates memoryshare sender // and also sets bGLDXcompatible, bDxInitOK, bUseCPU and bMemory if(OpenReceiver(UserName, width, height)) { strcpy_s(sendername, 256, UserName); // pass back the sendername used return true; } return false; } void Spout::ReleaseReceiver() { // can be done without a check here SpoutCleanUp(); bInitialized = false; // TODO - needs tracing bIsReceiving = false; Sleep(100); // Debugging aid, but leave for safety } // If the local texure has changed dimensions this will return false bool Spout::SendTexture(GLuint TextureID, GLuint TextureTarget, unsigned int width, unsigned int height, bool bInvert, GLuint HostFBO) { // width, g_Width should all be the same // (the application resets the size of any texture that is being sent out) if(width != g_Width || height != g_Height) return(UpdateSender(g_SharedMemoryName, width, height)); else return(interop.WriteTexture(TextureID, TextureTarget, width, height, bInvert, HostFBO)); } // end SendTexture // If the local texure has changed dimensions this will return false bool Spout::SendImage(const unsigned char* pixels, unsigned int width, unsigned int height, GLenum glFormat, bool bInvert, GLuint HostFBO) { // bool bResult = true; GLenum glformat = glFormat; // printf("SendImage(%d, %d) - format = %x, invert = %d\n", width, height, glFormat, bInvert); // width, g_Width should all be the same if(width != g_Width || height != g_Height) return(UpdateSender(g_SharedMemoryName, width, height)); // Only RGBA, BGRA, RGB, BGR supported if(!(glformat == GL_RGBA || glFormat == 0x80E1 || glformat == GL_RGB || glFormat == 0x80E0)) return false; // Check for BGRA support if(!IsBGRAavailable()) { // If the bgra extensions are not available and the user // provided GL_BGR_EXT or GL_BGRA_EXT do not use them if(glFormat == 0x80E0) glformat = GL_RGB; // GL_BGR_EXT if(glFormat == 0x80E1) glformat = GL_RGBA; // GL_BGRA_EXT } // Write the pixel data to the rgba shared texture from the user pixel format return(interop.WriteTexturePixels(pixels, width, height, glformat, bInvert, HostFBO)); } // end SendImage // // ReceiveTexture // bool Spout::ReceiveTexture(char* name, unsigned int &width, unsigned int &height, GLuint TextureID, GLuint TextureTarget, bool bInvert, GLuint HostFBO) { bool bConnected = true; // printf("Spout::ReceiveTexture(%s), %d, %d, [%x], [%x] (bInvert = %d)\n", name, width, height, TextureID, TextureTarget, bInvert); // // Test for sender change and user selection // // If not yet initialized, connects to the name provided or the active sender // if connected sets bConnected to true // the caller has to adjust any local textures etc. // if not connected sets bConnected to false // Returns false // // Calls CheckSpoutPanel to find if the user has selected another sender // // Checks that the sender identified by the global name is present - the size of that sender is returned // If the global name or the sender width and height have changed they are returned to the caller. // Sets bConnected to true if the sender is OK // the caller has to detect the change and adjust any local textures etc. // Sets bConnected to false if the sender is closed and the global sender name is reset // Returns false // // Otherwise no changes and returns true // if(!CheckReceiver(name, width, height, bConnected)) return bConnected; // Sender exists and everything matched. // Globals are now all current, so pass back the current name and size // so that there is no change found by the host. strcpy_s(name, 256, g_SharedMemoryName); width = g_Width; height = g_Height; if(TextureID > 0 && TextureTarget > 0) { // If a valid texture was passed, read the shared texture into it. // Otherwise skip it. All the other checks for name and size are already done. return(interop.ReadTexture(TextureID, TextureTarget, g_Width, g_Height, bInvert, HostFBO)); } else { // Just depend on the shared texture being updated and don't return one // e.g. can use DrawSharedTexture to use the shared texture directly // ReceiveTexture still does all the check for sender presence and size change etc. return true; } } // end ReceiveTexture bool Spout::ReceiveImage(char* name, unsigned int &width, unsigned int &height, unsigned char* pixels, GLenum glFormat, bool bInvert, GLuint HostFBO) { bool bConnected = true; GLenum glformat = glFormat; // printf("Spout::ReceiveImage (%dx%d) - format = %x\n", width, height, glFormat); // Only RGBA, BGRA, RGB and BGR supported if(!(glformat == GL_RGBA || glFormat == 0x80E1 || glFormat == GL_RGB || glFormat == 0x80E0)) return false; // Check for BGRA support if(!IsBGRAavailable()) { // If the bgra extensions are not available and the user // provided GL_BGR_EXT or GL_BGRA_EXT do not use them if(glFormat == 0x80E0) glformat = GL_RGB; // GL_BGR_EXT if(glFormat == 0x80E1) glformat = GL_RGBA; // GL_BGRA_EXT } // Test for sender change and user selection if(!CheckReceiver(name, width, height, bConnected)) return bConnected; // globals are all current, so pass back the current name and size strcpy_s(name, 256, g_SharedMemoryName); width = g_Width; height = g_Height; // Read the shared texture into the pixel buffer // Functions handle the formats supported return(interop.ReadTexturePixels(pixels, width, height, glformat, bInvert, HostFBO)); } // end ReceiveImage // // CheckReceiver // // If not yet inititalized, conects to the name provided or the active sender // if connected sets bConnected to true // if not connected sets bConnected to false // returns false // // Calls CheckSpoutPanel to find if the user has selected another sender // If so, changes globals g_SharedMemoryName, g_Width, g_Height, g_Format. // and the sender name will be different to that passed // If not, no changes to global name and size // // Checks that the sender identified by the global name is present // the size of that sender is returned // If the global name or the sender width and height have changed they are returned to the caller. // Sets bConnected to true if the sender is OK // the caller has to detect the change and adjust any local textures etc. // Sets bConnected to false if the sender is closed and the global sender name is reset // Returns false // // Otherwise drops through and returns true // bool Spout::CheckReceiver(char* name, unsigned int &width, unsigned int &height, bool &bConnected) { char newname[256]; unsigned int newWidth, newHeight; DWORD dwFormat; HANDLE hShareHandle; // Has it initialized yet ? if(!bInitialized) { // The name passed is the name to try to connect to unless the bUseActive flag is set // or the name is not initialized in which case it will try to find the active sender // Width and height are passed back as well if(name[0] != 0) strcpy_s(newname, 256, name); else newname[0] = 0; if(OpenReceiver(newname, newWidth, newHeight)) { // OpenReceiver will also set the global name, width, height and format // Pass back the new name, width and height to the caller // The change has to be detected by the application strcpy_s(name, 256, newname); width = newWidth; height = newHeight; bConnected = true; // user needs to check return false; } else { // Initialization failure - the sender is not there // Quit to let the app try again bConnected = false; return false; } } // endif not initialized // Check to see if SpoutPanel has been opened // If it has been opened, the globals are reset // (g_SharedMemoryName, g_Width, g_Height, g_Format) // and the sender name will be different to that passed CheckSpoutPanel(); // Set initial values to current globals to check for change with those passed in strcpy_s(newname, 256, g_SharedMemoryName); newWidth = g_Width; // width; newHeight = g_Height; // height; hShareHandle = g_ShareHandle; dwFormat = g_Format; // Is the sender there ? if(interop.senders.CheckSender(newname, newWidth, newHeight, hShareHandle, dwFormat)) { // The sender exists, but has the width, height, texture format changed from those passed in if(newWidth > 0 && newHeight > 0) { if(newWidth != width || newHeight != height || dwFormat != g_Format || strcmp(name, g_SharedMemoryName) != 0 ) { // test of original name allows for CheckSpoutPanel above // Re-initialize the receiver // OpenReceiver will also set the global name, width, height and format if(OpenReceiver(g_SharedMemoryName, newWidth, newHeight)) { g_Width = newWidth; g_Height = newHeight; g_ShareHandle = hShareHandle; // 09.09.15 g_Format = dwFormat; // 09.09.15 // Return the new sender name and dimensions // The change has to be detected by the application strcpy_s(name, 256, g_SharedMemoryName); width = g_Width; height = g_Height; bConnected = true; // user needs to check for changes return false; } // OpenReceiver OK else { // need what here bConnected = false; return false; } } // width, height, format or name have changed // The sender exists and there are no changes // Drop through to return true } // width and height are zero else { // need what here bConnected = false; return false; } } // endif CheckSender found a sender else { g_SharedMemoryName[0] = 0; // sender no longer exists // 01.06.15 - safety ReleaseReceiver(); // Start again bConnected = false; return false; } // CheckSender did not find the sender - probably closed // The sender exists and there are no changes bConnected = true; return true; } // Can be used without OpenGL context // Use before OpenReceiver and should not be called repeatedly // Redundant for Spout 2.006 - may be removed for future releases // Spout::GetSenderInfo is equivalent bool Spout::GetImageSize(char* name, unsigned int &width, unsigned int &height, bool &bMemoryMode) { char newname[256]; SharedTextureInfo TextureInfo; // Was initialized so get the sender details // Test to see whether the current sender is still there if(!interop.getSharedInfo(name, &TextureInfo)) { // Try the active sender if(interop.senders.GetActiveSender(newname)) { if(interop.getSharedInfo(newname, &TextureInfo)) { // Pass back the new name and size strcpy_s(name, 256, newname); width = TextureInfo.width; height = TextureInfo.height; // Check the sharehandle - if it is null, the sender is memoryshare if(TextureInfo.shareHandle == NULL) bMemoryMode = true; else bMemoryMode = false; return true; } } } // sender was running return false; } // end GetImageSize //--------------------------------------------------------- bool Spout::BindSharedTexture() { return(interop.BindSharedTexture()); } //--------------------------------------------------------- bool Spout::UnBindSharedTexture() { return(interop.UnBindSharedTexture()); } //--------------------------------------------------------- bool Spout::DrawSharedTexture(float max_x, float max_y, float aspect, bool bInvert, GLuint HostFBO) { return(interop.DrawSharedTexture(max_x, max_y, aspect, bInvert, HostFBO)); } //--------------------------------------------------------- // bool Spout::DrawToSharedTexture(GLuint TextureID, GLuint TextureTarget, unsigned int width, unsigned int height, float max_x, float max_y, float aspect, bool bInvert, GLuint HostFBO) { // Allow for change of sender size, even though the draw is independent of the // shared texture size, otherwise receivers will get a constant size for this sender if(!bMemory) { // width, g_Width should all be the same // width and height are the size of the texture that is being drawn to. if(width != g_Width || height != g_Height) { return(UpdateSender(g_SharedMemoryName, width, height)); } } return(interop.DrawToSharedTexture(TextureID, TextureTarget, width, height, max_x, max_y, aspect, bInvert, HostFBO)); } //--------------------------------------------------------- bool Spout::SetCPUmode(bool bCPU) { return (interop.SetCPUmode(bCPU)); } //--------------------------------------------------------- bool Spout::GetCPUmode() { return (interop.GetCPUmode()); } //--------------------------------------------------------- bool Spout::SetMemoryShareMode(bool bMem) { return (interop.SetMemoryShareMode(bMem)); } //--------------------------------------------------------- bool Spout::GetMemoryShareMode() { // Gets interop class global memoryshare flag and sets a flag in this class bMemory = interop.GetMemoryShareMode(); // set global flag - TODO : rename globals return bMemory; } //--------------------------------------------------------- int Spout::GetShareMode() { return interop.GetShareMode(); } //--------------------------------------------------------- bool Spout::SetShareMode(int mode) { return (interop.SetShareMode(mode)); } // // Maximum sender functions - for development testing only // int Spout::GetMaxSenders() { // // Gets the maximum senders allowed from the sendernames class // return(interop.senders.GetMaxSenders()); } void Spout::SetMaxSenders(int maxSenders) { // // Sets the maximum senders allowed // interop.senders.SetMaxSenders(maxSenders); } // Get the global sender name for this instance bool Spout::GetSpoutSenderName(char * sendername, int maxchars) { if(g_SharedMemoryName && g_SharedMemoryName[0] > 0) { strcpy_s(sendername, maxchars, g_SharedMemoryName); return true; } else { return false; } } // has the class been initialized bool Spout::IsSpoutInitialized() { return bInitialized; } // Are BGRA extensions supported bool Spout::IsBGRAavailable() { return interop.IsBGRAavailable(); } // Are PBO extensions supported bool Spout::IsPBOavailable() { return interop.IsPBOavailable(); } // Switch pbo functions on or off (default is off). void Spout::SetBufferMode(bool bActive) { interop.SetBufferMode(bActive); } bool Spout::GetBufferMode() { return interop.GetBufferMode(); } // SelectSenderPanel - used by a receiver // Optional message argument bool Spout::SelectSenderPanel(const char *message) { HANDLE hMutex1; HMODULE module; char UserMessage[512]; char path[MAX_PATH], drive[MAX_PATH], dir[MAX_PATH], fname[MAX_PATH]; if(message != NULL && message[0] != 0) strcpy_s(UserMessage, 512, message); // could be an arg or a user message else UserMessage[0] = 0; // make sure SpoutPanel does not see an un-initialized string // For a texture share receiver pop up SpoutPanel to allow the user to select a sender // The selected sender is then the "Active" sender and this receiver switches to it. // SpoutPanel.exe has to be in the same folder as this executable // This rather complicated process avoids having to use a dialog within a dll // which causes problems with FreeFrameGL plugins and Max eternals // First check whether the panel is already running // Try to open the application mutex. hMutex1 = OpenMutexA(MUTEX_ALL_ACCESS, 0, "SpoutPanel"); if (!hMutex1) { // No mutex, so not running, so can open it // See if there has been a Spout installation >= 2.002 with an install path for SpoutPanel.exe if(!ReadPathFromRegistry(path, "Software\\Leading Edge\\SpoutPanel", "InstallPath")) { // Path not registered so find the path of the host program // where SpoutPanel should have been copied module = GetModuleHandle(NULL); GetModuleFileNameA(module, path, MAX_PATH); _splitpath_s(path, drive, MAX_PATH, dir, MAX_PATH, fname, MAX_PATH, NULL, 0); _makepath_s(path, MAX_PATH, drive, dir, "SpoutPanel", ".exe"); // Does SpoutPanel.exe exist in this path ? if(!PathFileExistsA(path) ) { // Try the current working directory if(_getcwd(path, MAX_PATH)) { strcat_s(path, MAX_PATH, "\\SpoutPanel.exe"); // printf("SpoutPanel cwd [%s]\n", path); // Does SpoutPanel exist here? if(!PathFileExistsA(path) ) { return false; } } } } // printf("SpoutPanel path [%s]\n", path); // Spoutpanel exists // // Use ShellExecuteEx so we can test its return value later // ZeroMemory(&m_ShExecInfo, sizeof(m_ShExecInfo)); m_ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO); m_ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS; m_ShExecInfo.hwnd = NULL; m_ShExecInfo.lpVerb = NULL; m_ShExecInfo.lpFile = (LPCSTR)path; m_ShExecInfo.lpParameters = UserMessage; m_ShExecInfo.lpDirectory = NULL; m_ShExecInfo.nShow = SW_SHOW; m_ShExecInfo.hInstApp = NULL; ShellExecuteExA(&m_ShExecInfo); Sleep(125); // allow time for SpoutPanel to open 0.125s // Returns straight away here but multiple instances of SpoutPanel // are prevented in it's WinMain procedure by the mutex. // An infinite wait here causes problems. // The flag "bSpoutPanelOpened" is set here to indicate that the user // has opened the panel to select a sender. This flag is local to // this process so will not affect any other receiver instance // Then when the selection panel closes, sender name is tested bSpoutPanelOpened = true; } else { // We opened it so close it, otherwise it is never released CloseHandle(hMutex1); } // The mutex exists, so another instance is already running // Find the dialog window and bring it to the top // the spout dll dialog is opened as topmost anyway but pop it to // the front in case anything else has stolen topmost HWND hWnd = FindWindowA(NULL, (LPCSTR)"SpoutPanel"); if(IsWindow(hWnd)) { SetForegroundWindow(hWnd); // prevent other windows from hiding the dialog // and open the window wherever the user clicked SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_ASYNCWINDOWPOS | SWP_SHOWWINDOW | SWP_NOSIZE | SWP_NOMOVE); } return true; } // end selectSenderPanel // 22.02.15 - find the SpoutPanel version // http://stackoverflow.com/questions/940707/how-do-i-programatically-get-the-version-of-a-dll-or-exe-file // bool Spout::FindFileVersion(const char *FilePath, DWORD &versMS, DWORD &versLS) { DWORD dwSize = 0; unsigned char *pbVersionInfo = NULL; VS_FIXEDFILEINFO *pFileInfo = NULL; UINT puLenFileInfo = 0; // get the version info for the file requested dwSize = GetFileVersionInfoSizeA(FilePath, NULL ); if ( dwSize == 0 ) { printf("Error in GetFileVersionInfoSize: %d\n", GetLastError() ); return false; } pbVersionInfo = new BYTE[ dwSize ]; if ( !GetFileVersionInfoA( FilePath, 0, dwSize, pbVersionInfo ) ) { printf("Error in GetFileVersionInfo: %d\n", GetLastError() ); delete[] pbVersionInfo; return false; } if ( !VerQueryValueA( pbVersionInfo, "\\", (LPVOID*) &pFileInfo, &puLenFileInfo ) ) { printf("Error in VerQueryValue: %d\n", GetLastError() ); delete[] pbVersionInfo; return false; } versMS = pFileInfo->dwFileVersionMS; versLS = pFileInfo->dwFileVersionLS; /* printf("File Version: %d.%d.%d.%d\n", ( pFileInfo->dwFileVersionMS >> 16 ) & 0xffff, ( pFileInfo->dwFileVersionMS >> 0 ) & 0xffff, ( pFileInfo->dwFileVersionLS >> 16 ) & 0xffff, ( pFileInfo->dwFileVersionLS >> 0 ) & 0xffff ); printf("Product Version: %d.%d.%d.%d\n", ( pFileInfo->dwProductVersionMS >> 24 ) & 0xffff, ( pFileInfo->dwProductVersionMS >> 16 ) & 0xffff, ( pFileInfo->dwProductVersionLS >> 8 ) & 0xffff, ( pFileInfo->dwProductVersionLS >> 0 ) & 0xffff ); */ return true; } // ====================== int Spout::GetSenderCount() { std::set<string> SenderNameSet; if(interop.senders.GetSenderNames(&SenderNameSet)) { return((int)SenderNameSet.size()); } return 0; } // // Get a sender name given an index and knowing the sender count // index - in // sendername - out // sendernameMaxSize - in bool Spout::GetSenderName(int index, char* sendername, int sendernameMaxSize) { std::set<string> SenderNameSet; std::set<string>::iterator iter; string namestring; char name[256]; int i; if(interop.senders.GetSenderNames(&SenderNameSet)) { if(SenderNameSet.size() < (unsigned int)index) { return false; } i = 0; for(iter = SenderNameSet.begin(); iter != SenderNameSet.end(); iter++) { namestring = *iter; // the name string strcpy_s(name, 256, namestring.c_str()); // the 256 byte name char array if(i == index) { strcpy_s(sendername, sendernameMaxSize, name); // the passed name char array break; } i++; } return true; } return false; } // All of these can be directly in the Receiver class . TODO - Change/Test //--------------------------------------------------------- bool Spout::GetActiveSender(char* Sendername) { return interop.senders.GetActiveSender(Sendername); } //--------------------------------------------------------- bool Spout::SetActiveSender(const char* Sendername) { return interop.senders.SetActiveSender(Sendername); } bool Spout::GetSenderInfo(const char* sendername, unsigned int &width, unsigned int &height, HANDLE &dxShareHandle, DWORD &dwFormat) { return interop.senders.GetSenderInfo(sendername, width, height, dxShareHandle, dwFormat); } int Spout::GetVerticalSync() { return interop.GetVerticalSync(); } bool Spout::SetVerticalSync(bool bSync) { return interop.SetVerticalSync(bSync); } // ========================================================== // // LOCAL FUNCTIONS // // ========================================================== // bool Spout::OpenReceiver (char* theName, unsigned int& theWidth, unsigned int& theHeight) { char Sendername[256]; // user entered Sender name DWORD dwFormat = 0; HANDLE sharehandle = NULL; unsigned int width; unsigned int height; // printf("OpenReceiver (%s, %d , %d) - bUseActive = %d\n", theName, theWidth, theHeight, bUseActive); // If the name begins with a null character, or the bUseActive flag has been set if(theName[0] != 0 && !bUseActive) { // A valid name is sent and the user does not want to use the active sender strcpy_s(Sendername, 256, theName); } else { Sendername[0] = 0; } // Set initial size to that passed in width = theWidth; height = theHeight; // Find if the sender exists // Or, if a null name given, return the active sender if that exists if(!interop.senders.FindSender(Sendername, width, height, sharehandle, dwFormat)) { // Given name not found ? - has SpoutPanel been opened ? // the globals are reset if it has been if(CheckSpoutPanel()) { // set vars for below strcpy_s(Sendername, 256, g_SharedMemoryName); width = g_Width; height = g_Height; dwFormat = g_Format; } else { return false; } } // Make sure it has been initialized // OpenSpout sets bDxInitOK and bMemory if not compatible if(!OpenSpout()) { return false; } // Texture mode - sharehandle must not be NULL if(!bMemory && !sharehandle) return false; g_ShareHandle = sharehandle; if(bDxInitOK) { // Render window must be visible for initSharing to work // Safety in case no opengl context if(wglGetCurrentContext() == NULL || wglGetCurrentDC() == NULL) { return false; } g_hWnd = WindowFromDC(wglGetCurrentDC()); // Suggested : https://github.com/leadedge/Spout2/issues/18 // if(g_hWnd == NULL && interop.m_bUseDX9) { if(g_hWnd == NULL) { return false; } } // Set the global name, width, height and format strcpy_s(g_SharedMemoryName, 256, Sendername); g_Width = width; g_Height = height; g_Format = dwFormat; // Initialize a receiver in either memoryshare or texture mode // Use the global memory mode flag if(InitReceiver(g_hWnd, g_SharedMemoryName, g_Width, g_Height, bMemory)) { // InitReceiver can reset the globals so pass them back strcpy_s(theName, 256, g_SharedMemoryName); theWidth = g_Width; theHeight = g_Height; return true; } return false; } // end OpenReceiver void Spout::CleanSenders() { char name[512]; std::set<std::string> Senders; std::set<std::string>::iterator iter; std::string namestring; SharedTextureInfo info; // MessageBoxA(NULL,"Spout::CleanSenders()","ERROR",MB_OK|MB_ICONEXCLAMATION); // get the sender name list in shared memory into a local list interop.senders.GetSenderNames(&Senders); // Now we have a local set of names "Senders" // 27.12.13 - noted that if a Processing sketch is stopped by closing the window // all is OK and either the "stop" or "dispose" overrides work, but if STOP is used, // or the sketch is closed, neither the exit or dispose functions are called and // the sketch does not release the sender. // So here we run through again and check whether the sender exists and if it does not // release the sender from the local sender list if(Senders.size() > 0) { for(iter = Senders.begin(); iter != Senders.end(); iter++) { namestring = *iter; // the Sender name string strcpy_s(name, namestring.c_str()); // we have the name already, so look for it's info if(!interop.senders.getSharedInfo(name, &info)) { // Sender does not exist any more interop.senders.ReleaseSenderName(name); // release from the shared memory list } } } // Now we have cleaned up the list in shared memory Senders.clear(); } bool Spout::InitSender (HWND hwnd, const char* theSendername, unsigned int theWidth, unsigned int theHeight, DWORD theFormat, bool bMemoryMode) { char sendername[256]; // printf("Spout::Initsender [%s] (%dx%d) (bGLDXcompatible = %d, memorymode = %d)\n", theSendername, theWidth, theHeight, bGLDXcompatible, bMemoryMode); // Quit if there is no image size to initialize with if(theWidth == 0 || theHeight == 0) { MessageBoxA(NULL,"Cannot initialize sender with zero size.","ERROR",MB_OK|MB_ICONEXCLAMATION); return false; } // Does the sender already exist ? int i = 1; strcpy_s(sendername, 256, theSendername); if(interop.senders.FindSenderName(sendername)) { do { sprintf_s(sendername, 256, "%s_%d", theSendername, i); i++; } while (interop.senders.FindSenderName(sendername)); } // only try dx if the memory mode flag is not set if(!bMemoryMode) { // Initialize the GL/DX interop and create a new shared texture (false = sender) if(!interop.CreateInterop(hwnd, sendername, theWidth, theHeight, theFormat, false)) { // False for a sender printf("Spout::InitSender error 2\n"); return false; } bDxInitOK = true; bMemory = false; } else { // // Memoryshare mode // // If there is an OpenGL context, load the extensions now so that the fbo extensions work // From 2.005, OpenGL is used for Memoryshare as well, so if extensions fail to load, // nothing will not work anyway, so quit now. TODO : trace global flags for memoryshare if(!wglGetCurrentContext()) return false; if(!interop.LoadGLextensions()) return false; // // LJ DEBUG - temporary patch // // To prevent a crash with a 2.004 receiver, create an empty DirectX texture // // DirectX will be released by CleaunpInterop. // This is just a prevention in case with 2.005, memoryshare is set by the user or the // hardware is incompatible and then the user starts up an app that has been developed // with the Spout 2.004 SDK. Then the result will be black as it would have been anyway // until the mode is set back to texture share. // // This patch can be removed whan all apps convert to 2.005 or later. // HDC hdc; hdc = wglGetCurrentDC(); // OpenGl device context is needed if(!hdc) return false; g_hWnd = WindowFromDC(hdc); // OpenDirectX does not set any initialization flags for Texture or Memory share if(!interop.OpenDirectX(g_hWnd, GetDX9())) { return false; } // Now we have created the DirectX device so create an empty texture interop.m_dxShareHandle = NULL; // A sender creates a new texture with a new share handle DWORD dwFormat = 0; if(interop.GetDX9()) { dwFormat = (DWORD)D3DFMT_A8R8G8B8; if(!interop.spoutdx.CreateSharedDX9Texture(interop.m_pDevice, theWidth, theHeight, D3DFMT_A8R8G8B8, interop.m_dxTexture, interop.m_dxShareHandle)) { return false; } } else { dwFormat = (DWORD)DXGI_FORMAT_B8G8R8A8_UNORM; if(!interop.spoutdx.CreateSharedDX11Texture(interop.g_pd3dDevice, theWidth, theHeight, DXGI_FORMAT_B8G8R8A8_UNORM, &interop.g_pSharedTexture, interop.m_dxShareHandle)) { return false; } } // Now create a sender with a valid texture handle and format // For a 2.004 receiver the result will just be black // Memoryshare needs to create a sender separately if(!interop.senders.CreateSender(sendername, theWidth, theHeight, interop.m_dxShareHandle, dwFormat)) return false; if(!interop.memoryshare.CreateSenderMemory(sendername, theWidth, theHeight)) return false; bDxInitOK = false; bMemory = true; } // Set global name strcpy_s(g_SharedMemoryName, 256, sendername); // Get the sender width, height and share handle into local copy interop.senders.GetSenderInfo(g_SharedMemoryName, g_Width, g_Height, g_ShareHandle, g_Format); bInitialized = true; bIsSending = true; return true; } // end InitSender bool Spout::InitReceiver (HWND hwnd, char* theSendername, unsigned int theWidth, unsigned int theHeight, bool bMemoryMode) { char sendername[256]; unsigned int width = 0; unsigned int height = 0; DWORD format = 0; HANDLE sharehandle = NULL; UNREFERENCED_PARAMETER(bMemoryMode); // printf("InitReceiver (%s, %d, %d) bGLDXcompatible = %d, bMemoryMode = %d\n", theSendername, theWidth, theHeight, bGLDXcompatible, bMemoryMode); // Quit if there is no image size to initialize with if(theWidth == 0 || theHeight == 0) return false; // // ============== Set up for a RECEIVER ============ // if(theSendername[0] != 0) { strcpy_s(sendername, 256, theSendername); // working name local to this function } else { sendername[0] = 0; } // bChangeRequested is set when the Sender name, image size or share handle changes // or the user selects another Sender - everything has to be reset if already initialized if(bChangeRequested) { SpoutCleanUp(); bDxInitOK = false; // bMemory is Registry or user setting - do not touch it bInitialized = false; bChangeRequested = false; // only do it once } // Find the requested sender and return the name, width, height, sharehandle and format if(!interop.senders.FindSender(sendername, width, height, sharehandle, format)) { return false; } // only try dx if the memory mode flag is not set and sharehandle is not NULL if(!bMemory && sharehandle) { // Initialize the receiver interop (this will create globals local to the interop class) if(!interop.CreateInterop(hwnd, sendername, width, height, format, true)) // true meaning receiver return false; bDxInitOK = true; } else { // If there is an OpenGL context, load the extensions now // so that the fbo extensions work (See InitSender) if(!wglGetCurrentContext()) return false; if(!interop.LoadGLextensions()) return false; if(!interop.memoryshare.CreateSenderMemory(sendername, width, height)) return false; bDxInitOK = false; } // Set globals here g_Width = width; g_Height = height; g_ShareHandle = sharehandle; g_Format = format; strcpy_s(g_SharedMemoryName, 256, sendername); bInitialized = true; bIsReceiving = true; return true; } // end InitReceiver // // SpoutCleanup // void Spout::SpoutCleanUp(bool bExit) { // LJ DEBUG - should be OK for memoryshare because all handles will be NULL // This allows a dummy shared texture to be created for memoryshare to prevent // a crash with 2.004 receivers. // if(bDxInitOK) // printf("Spout::SpoutCleanUp\n"); interop.CleanupInterop(bExit); // true means it is the exit so don't call wglDXUnregisterObjectNV bDxInitOK = false; // 04.11.15 - Close memoryshare if created for data transfer // Has no effect if not created interop.memoryshare.CloseSenderMemory(); if(bMemory) interop.memoryshare.ReleaseSenderMemory(); // destroys sendermem object // bMemory - Registry or user setting - do not change it g_ShareHandle = NULL; g_Width = 0; g_Height= 0; g_Format = 0; // important - we no longer want the global shared memory name and need to reset it g_SharedMemoryName[0] = 0; // Set default for CreateReceiver bUseActive = false; // Important - everything is reset (see ReceiveTexture) bInitialized = false; bIsSending = false; bIsReceiving = false; } // // ========= USER SELECTION PANEL TEST ===== // // This is necessary because the exit code needs to be tested // bool Spout::CheckSpoutPanel() { // MessageBoxA(NULL, "CheckSpoutPanel()", "SpoutSDK", MB_OK); // If SpoutPanel has been activated, test if the user has clicked OK if(bSpoutPanelOpened) { // User has activated spout panel SharedTextureInfo TextureInfo; HANDLE hMutex = NULL; DWORD dwExitCode; char newname[256]; char activename[256]; bool bRet = false; // Must find the mutex to signify that SpoutPanel has opened // and then wait for the mutex to close hMutex = OpenMutexA(MUTEX_ALL_ACCESS, 0, "SpoutPanel"); // Has it been activated if(!bSpoutPanelActive) { // If the mutex has been found, set the active flag true and quit // otherwise on the next round it will test for the mutex closed if(hMutex) bSpoutPanelActive = true; } else if (!hMutex) { // It has now closed bSpoutPanelOpened = false; // Don't do this part again bSpoutPanelActive = false; // call GetExitCodeProcess() with the hProcess member of SHELLEXECUTEINFO // to get the exit code from SpoutPanel if(m_ShExecInfo.hProcess) { GetExitCodeProcess(m_ShExecInfo.hProcess, &dwExitCode); // Only act if exit code = 0 (OK) if(dwExitCode == 0) { // // SpoutPanel has been activated and OK clicked // // Sender name entry // // Check for an unregistered sender first because this will not have been set as active yet // Try to get the current sender name from the registry (24.05.15 instead of text file) // Text file method does not work if SpoutPanel is in the Program Files folder without Admin privileges // SpoutPanel now always writes the selected sender name to the registry // so this first check should always work newname[0] = 0; if(!ReadPathFromRegistry(newname, "Software\\Leading Edge\\SpoutPanel", "Sendername")) { // Otherwise try the text file method string line; HMODULE module; char path[MAX_PATH], drive[MAX_PATH], dir[MAX_PATH], fname[MAX_PATH]; // Find the path of the host program where SpoutPanel should have been copied module = GetModuleHandle(NULL); GetModuleFileNameA(module, path, MAX_PATH); _splitpath_s(path, drive, MAX_PATH, dir, MAX_PATH, fname, MAX_PATH, NULL, 0); _makepath_s(path, MAX_PATH, drive, dir, "spoutpanel", ".txt"); ifstream infile(path, ios::in); if (infile.is_open()) { if(getline(infile, line)) { strcpy_s(newname, 256, line.c_str()); } infile.close(); remove(path); } // 24.11.15 // Does the sender exist - if so register it if(newname[0] != 0) { if(interop.senders.getSharedInfo(newname, &TextureInfo)) { // Register in the list of senders and make it the active sender interop.senders.RegisterSenderName(newname); interop.senders.SetActiveSender(newname); } } } // Do we have a sender name from the registry or a text file ? if(newname[0] != 0) { // Here we can test the active sender which should have been set by SpoutPanel // instead of depending on the registry flush which might have returned the old name // They should both be the same - so most reliable might be the active sender if(interop.senders.GetActiveSender(activename)) { if(strcmp(activename, newname) != 0) { // different names strcpy_s(newname, activename); // use the acitev sender } } // Does the sender exist ? if(interop.senders.getSharedInfo(newname, &TextureInfo)) { strcpy_s(g_SharedMemoryName, 256, newname); g_Width = (unsigned int)TextureInfo.width; g_Height = (unsigned int)TextureInfo.height; g_Format = TextureInfo.format; // 24.11.15 - not needed if the sender exists - and it is already checked as active // Register in the list of senders and make it the active sender // interop.senders.RegisterSenderName(newname); // interop.senders.SetActiveSender(newname); bRet = true; // will pass on next call to receivetexture } } else { // No name in registry or text file, so get the active sender which is set by spoutpanel if(interop.senders.GetActiveSender(newname)) { // returns the active sender name if(interop.getSharedInfo(newname, &TextureInfo)) { strcpy_s(g_SharedMemoryName, 256, newname); g_Width = (unsigned int)TextureInfo.width; g_Height = (unsigned int)TextureInfo.height; g_Format = TextureInfo.format; bRet = true; // will pass on next call to receivetexture } } // no active sender } // no active sender or unregistered sender } // endif SpoutPanel OK } // got the exit code } // endif no mutex so SpoutPanel has closed CloseHandle(hMutex); return bRet; } // SpoutPanel has not been opened return false; } // ========= END USER SELECTION PANEL ===== bool Spout::OpenSpout() { HDC hdc; // From 2.005 OpenGL is used for Memoryshare as well, so load the extensions. // If extensions fail to load, FBO extensions are not available and nothing // will not work anyway, so quit now if(!interop.LoadGLextensions()) { // printf("OpenSpout : Extensions not loaded\n"); return false; } // LoadGLextensions has a check for availabilty of the GL/DX extensions // and switches to memoryshare mode if not supported // Retrieve memoryshare mode from interop class // This reads the user setting from the registry and // if GLDX extensions are available and makes an additional // compatibility test. // bMemory will be false for < 2.005 bool bMemoryShare = interop.GetMemoryShareMode(); // printf("OpenSpout - bGLDXcompatible = %d, bDxInitOK = %d, bMemoryShare = %d\n", bGLDXcompatible, bDxInitOK, bMemoryShare); // Safety return if already initialized if( (bDxInitOK && !bMemory) || (bMemory && !bDxInitOK) ) { // printf("OpenSpout : already initialized\n"); return true; } if(bMemoryShare) { // Memoryshare was user set, so return to use shared memory bDxInitOK = false; bMemory = true; } else { // If not memoryshare, initialize DirectX and prepare GLDX interop hdc = wglGetCurrentDC(); // OpenGl device context is needed if(!hdc) { MessageBoxA(NULL, "Cannot get GL device context", "OpenSpout", MB_OK); return false; } g_hWnd = WindowFromDC(hdc); // can be null for DX11 if(g_hWnd == NULL && GetDX9()) { // // DX9 device creation needs hwnd // https://github.com/leadedge/Spout2/issues/18 // MessageBoxA(NULL, "Cannot get hwnd to create DirectX 9 device", "OpenSpout", MB_OK); return false; } if(!interop.OpenDirectX(g_hWnd, GetDX9())) { // did the NVIDIA open interop extension work ? bDxInitOK = false; // DirectX initialization failed bMemory = true; // Default to memoryshare } } return true; } // This is a request from within a program and Spout might not have initialized yet. // If set OFF the DX9 setting is returned false only after a DX11 compatibility check bool Spout::SetDX9(bool bDX9) { return(interop.UseDX9(bDX9)); } // Just return the flag that has been set bool Spout::GetDX9() { return interop.GetDX9(); } // Set graphics adapter for Spout output bool Spout::SetAdapter(int index) { bool bRet = interop.SetAdapter(index); return bRet; } // Get current adapter index int Spout::GetAdapter() { return interop.GetAdapter(); } // Get the number of graphics adapters in the system int Spout::GetNumAdapters() { return interop.GetNumAdapters(); } // Get an adapter name bool Spout::GetAdapterName(int index, char *adaptername, int maxchars) { return interop.GetAdapterName(index, adaptername, maxchars); } // Get the path of the host that produced the sender bool Spout::GetHostPath(const char *sendername, char *hostpath, int maxchars) { return interop.GetHostPath(sendername, hostpath, maxchars); } bool Spout::WritePathToRegistry(const char *filepath, const char *subkey, const char *valuename) { HKEY hRegKey; LONG regres; char mySubKey[512]; // The required key strcpy_s(mySubKey, 512, subkey); // Does the key already exist ? regres = RegOpenKeyExA(HKEY_CURRENT_USER, mySubKey, NULL, KEY_ALL_ACCESS, &hRegKey); if(regres != ERROR_SUCCESS) { // Create a new key regres = RegCreateKeyExA(HKEY_CURRENT_USER, mySubKey, NULL, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS,NULL, &hRegKey, NULL); } if(regres == ERROR_SUCCESS && hRegKey != NULL) { // Write the path regres = RegSetValueExA(hRegKey, valuename, 0, REG_SZ, (BYTE*)filepath, ((DWORD)strlen(filepath) + 1)*sizeof(unsigned char)); RegCloseKey(hRegKey); } if(regres == ERROR_SUCCESS) return true; else return false; } bool Spout::ReadPathFromRegistry(char *filepath, const char *subkey, const char *valuename) { HKEY hRegKey; LONG regres; DWORD dwSize, dwKey; dwSize = MAX_PATH; // Does the key exist regres = RegOpenKeyExA(HKEY_CURRENT_USER, subkey, NULL, KEY_READ, &hRegKey); if(regres == ERROR_SUCCESS) { // Read the key Filepath value regres = RegQueryValueExA(hRegKey, valuename, NULL, &dwKey, (BYTE*)filepath, &dwSize); RegCloseKey(hRegKey); if(regres == ERROR_SUCCESS) return true; } // Just quit if the key does not exist return false; } bool Spout::RemovePathFromRegistry(const char *subkey, const char *valuename) { HKEY hRegKey; LONG regres; regres = RegOpenKeyExA(HKEY_CURRENT_USER, subkey, NULL, KEY_ALL_ACCESS, &hRegKey); if(regres == ERROR_SUCCESS) { regres = RegDeleteValueA(hRegKey, valuename); RegCloseKey(hRegKey); return true; } return false; } // For debugging only void Spout::UseAccessLocks(bool bUseLocks) { interop.spoutdx.bUseAccessLocks = bUseLocks; } int Spout::ReportMemory() { int nTotalAvailMemoryInKB = 0; int nCurAvailMemoryInKB = 0; glGetIntegerv(0x9048, &nTotalAvailMemoryInKB); glGetIntegerv(0x9049, &nCurAvailMemoryInKB); // printf("Memory used : Total [%i], Available [%i]\n", nTotalAvailMemoryInKB, nCurAvailMemoryInKB); return nCurAvailMemoryInKB; }
5e7b9620b6541954ff0341583d24dfc20c113614
c1976b1f0a5eeb0bd757cf6e65e2d50f54425bca
/src/carray.h
6b7921915392f0c3206d7b0c0c447046599b67f2
[ "MIT", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference" ]
permissive
SiriusTR/dle-experimental
1796aab0a6302d99c64e989170764fa370a2b6f1
2ee17b4277b68eef57960d5cf9762dd986eaa0d9
refs/heads/master
2020-04-17T17:45:17.134289
2020-03-08T23:25:37
2020-03-08T23:25:37
67,313,420
0
1
null
null
null
null
UTF-8
C++
false
false
12,279
h
#ifndef _CARRAY_H #define _CARRAY_H #ifdef HAVE_CONFIG_H #include <conf.h> #endif #include <string.h> #include <stdlib.h> #ifndef DBG # ifdef _DEBUG # define DBG 1 # else # define DBG 0 # endif #endif #define DBG_ARRAYS DBG #include "cquicksort.h" void ArrayError (const char* pszMsg); //----------------------------------------------------------------------------- template < class _T > class CDynamicArray : public CQuickSort < _T > { template < class _U > class CArrayData { public: _U* buffer; _U nil; uint length; uint pos; int nMode; bool bWrap; }; protected: CArrayData<_T> m_data; public: template < class _V > class Iterator { private: _V* m_start; _V* m_end; _V* m_p; CDynamicArray<_V>& m_a; public: Iterator () : m_p (null) {} Iterator (CDynamicArray<_V>& a) : m_a (a), m_p (null) {} operator bool() const { return m_p != null; } _V* operator*() const { return m_p; } Iterator& operator++() { if (m_p) { if (m_p < m_end) m_p++; else m_p = null; } return *this; } Iterator& operator--() { if (m_p) { if (m_p > m_end) m_p--; else m_p = null; } return *this; } _V* Start (void) { m_p = m_start = m_a.Start (); m_end = m_a.End (); } _V* End (void) { m_p = m_start = m_a.End (); m_end = m_a.Start (); } }; CDynamicArray () { Init (); } CDynamicArray (uint nLength) { Init (); Create (nLength); } template <size_t _N> CDynamicArray (_T const (&source) [_N]) : CDynamicArray (_N) { operator= ((_T*)source); } ~CDynamicArray() { Destroy (); } void Init (void) { m_data.buffer = reinterpret_cast<_T *> (null); m_data.length = 0; m_data.pos = 0; m_data.nMode = 0; m_data.bWrap = false; memset (&m_data.nil, 0, sizeof (m_data.nil)); } void Clear (ubyte filler = 0, uint count = 0xffffffff) { #if DBG_ARRAYS if ((count != 0xffffffff) && (count > 1000000)) { count = count; ArrayError ("array overflow\n"); } if ((count == 0xffffffff) && (m_data.length > 512 * 512 * 16 * 4)) { count = count; ArrayError ("array overflow\n"); } #endif if (m_data.buffer) memset (m_data.buffer, filler, sizeof (_T) * ((count < m_data.length) ? count : m_data.length)); } inline bool IsElement (_T* elem, bool bDiligent = false) { if (!m_data.buffer || (elem < m_data.buffer) || (elem >= m_data.buffer + m_data.length)) return false; // no buffer or element out of buffer if (bDiligent) { uint i = static_cast<uint> (reinterpret_cast<ubyte*> (elem) - reinterpret_cast<ubyte*> (m_data.buffer)); if (i % sizeof (_T)) return false; // elem in the buffer, but not properly aligned } return true; } #if DBG_ARRAYS inline int Index (_T* elem) { if (IsElement (elem)) return static_cast<int> (elem - m_data.buffer); ArrayError ("invalid array index\n"); return -1; } #else inline uint Index (_T* elem) { return uint (elem - m_data.buffer); } #endif #if DBG_ARRAYS inline _T* Pointer (uint i) const { if (!m_data.buffer || (i >= m_data.length)) { ArrayError ("invalid array handle or index\n"); return null; } return m_data.buffer + i; } #else inline _T* Pointer (uint i) const { return m_data.buffer + i; } #endif void Destroy (void) { if (m_data.buffer) { if (!m_data.nMode) { delete[] m_data.buffer; #if DBG_ARRAYS m_data.buffer = reinterpret_cast<_T *> (null); #endif } Init (); } } _T *Create (uint length) { if (m_data.length != length) { Destroy (); try { if ((m_data.buffer = new _T [length])) m_data.length = length; } catch(...) { #if DBG_ARRAYS ArrayError ("invalid buffer size\n"); #endif m_data.buffer = null; } } return m_data.buffer; } inline _T* Buffer (uint i = 0) { return m_data.buffer + i; } void SetBuffer (_T *buffer, int nMode = 0, uint length = 0xffffffff) { if (m_data.buffer != buffer) { if (!(m_data.buffer = buffer)) Init (); else { if (length != 0xffffffff) m_data.length = length; m_data.nMode = nMode; } } } _T* Resize (uint length, bool bCopy = true) { if (m_data.nMode == 2) return m_data.buffer; if (!m_data.buffer) return Create (length); _T* p; try { p = new _T [length]; } catch(...) { #if DBG_ARRAYS ArrayError ("invalid buffer size\n"); #endif p = null; } if (!p) return m_data.buffer; if (bCopy) { memcpy (p, m_data.buffer, ((length > m_data.length) ? m_data.length : length) * sizeof (_T)); Clear (); // hack to avoid d'tors } m_data.length = length; if (length > 0) m_data.pos %= length; else m_data.pos = 0; delete[] m_data.buffer; return m_data.buffer = p; } inline uint Length (void) const { return m_data.length; } inline _T* Current (void) const { return m_data.buffer ? m_data.buffer + m_data.pos : null; } inline size_t Size (void) const { return m_data.length * sizeof (_T); } #if DBG_ARRAYS inline _T& operator[] (uint i) { if (m_data.buffer && (i < m_data.length)) return m_data.buffer [i]; if (i == m_data.length) return m_data.nil; else { ArrayError ("invalid array handle or index\n"); return m_data.nil; } } #else inline _T& operator[] (uint i) { return m_data.buffer [i]; } #endif inline _T& operator= (CDynamicArray<_T>& source) { return Copy (source); } inline _T& operator= (_T* source) { if (m_data.buffer) memcpy (m_data.buffer, source, m_data.length * sizeof (_T)); return m_data.buffer [0]; } _T& Copy (CDynamicArray<_T>& source, uint offset = 0) { if (((static_cast<int> (m_data.length)) >= 0) && (static_cast<int> (source.m_data.length) > 0)) { if ((m_data.buffer && (m_data.length >= source.m_data.length + offset)) || Resize (source.m_data.length + offset, false)) { memcpy (m_data.buffer + offset, source.m_data.buffer, ((m_data.length - offset < source.m_data.length) ? m_data.length - offset : source.m_data.length) * sizeof (_T)); } } return m_data.buffer [0]; } inline _T& operator+ (CDynamicArray<_T>& source) { uint offset = m_data.length; if (m_data.buffer) Resize (m_data.length + source.m_data.length); return Copy (source, offset); } inline bool operator== (CDynamicArray<_T>& other) const { return (m_data.length == other.m_data.length) && !(m_data.length && memcmp (m_data.buffer, other.m_data.buffer)); } inline bool operator!= (CDynamicArray<_T>& other) const { return (m_data.length != other.m_data.length) || (m_data.length && memcmp (m_data.buffer, other.m_data.buffer)); } inline _T* Start (void) const { return m_data.buffer; } inline _T* End (void) const { return (m_data.buffer && m_data.length) ? m_data.buffer + m_data.length - 1 : null; } inline _T* operator++ (void) { if (!m_data.buffer) return null; if (m_data.pos < m_data.length - 1) m_data.pos++; else if (m_data.bWrap) m_data.pos = 0; else return null; return m_data.buffer + m_data.pos; } inline _T* operator-- (void) { if (!m_data.buffer) return null; if (m_data.pos > 0) m_data.pos--; else if (m_data.bWrap) m_data.pos = m_data.length - 1; else return null; return m_data.buffer + m_data.pos; } #if DBG_ARRAYS inline _T* operator+ (uint i) { if (m_data.buffer && (i < m_data.length)) return m_data.buffer + i; if (i == m_data.length) return null; else { ArrayError ("invalid array handle or index\n"); return null; } } #else inline _T* operator+ (uint i) { return m_data.buffer ? m_data.buffer + i : null; } #endif inline _T* operator- (uint i) { return m_data.buffer ? m_data.buffer - i : null; } CDynamicArray<_T>& ShareBuffer (CDynamicArray<_T>& child) { memcpy (&child.m_data, &m_data, sizeof (m_data)); if (!child.m_data.nMode) child.m_data.nMode = 1; return child; } inline bool operator! () const { return m_data.buffer == null; } inline uint Pos (void) const { return m_data.pos; } inline void Pos (uint pos) { m_data.pos = pos % m_data.length; } size_t Read (CFileManager& fp, uint nCount = 0, uint nOffset = 0) { if (!m_data.buffer) return -1; if (nOffset >= m_data.length) return -1; if (!nCount) nCount = m_data.length - nOffset; else if (nCount > m_data.length - nOffset) nCount = m_data.length - nOffset; return int (fp.Read (m_data.buffer + nOffset, sizeof (_T), nCount)); } size_t Write (CFileManager& fp, uint nCount = 0, uint nOffset = 0) { if (!m_data.buffer) return -1; if (nOffset >= m_data.length) return -1; if (!nCount) nCount = m_data.length - nOffset; else if (nCount > m_data.length - nOffset) nCount = m_data.length - nOffset; return int (fp.Write (m_data.buffer + nOffset, sizeof (_T), nCount)); } inline void SetWrap (bool bWrap) { m_data.bWrap = bWrap; } inline void SortAscending (int left = 0, int right = -1) { if (m_data.buffer) CQuickSort<_T>::SortAscending (m_data.buffer, left, (right >= 0) ? right : m_data.length - 1); } inline void SortDescending (int left = 0, int right = -1) { if (m_data.buffer) CQuickSort<_T>::SortDescending (m_data.buffer, left, (right >= 0) ? right : m_data.length - 1); } inline size_t Find (_T key) const { for (uint i = 0; i < m_data.length; i++) if (key == m_data.buffer [i]) return i; return -1; } inline size_t FindSorted (_T key) { size_t i = 0, j = size_t (m_data.length); _T t; do { m = (i + j) / 2; t = m_data.buffer [m]; if (key < t) r = m - 1; else if (key > t) l = m + 1; else return m; } while (i <= j); return -1; } #ifdef _WIN32 inline void SortAscending (comparator compare, int left = 0, int right = -1) { if (m_data.buffer) CQuickSort<_T>::SortAscending (m_data.buffer, left, (right >= 0) ? right : m_data.length - 1, compare); } inline void SortDescending (comparator compare, int left = 0, int right = -1) { if (m_data.buffer) CQuickSort<_T>::SortDescending (m_data.buffer, left, (right >= 0) ? right : m_data.length - 1, compare); } #endif }; //----------------------------------------------------------------------------- inline int operator- (char* v, CDynamicArray<char>& a) { return a.Index (v); } inline int operator- (ubyte* v, CDynamicArray<ubyte>& a) { return a.Index (v); } inline int operator- (short* v, CDynamicArray<short>& a) { return a.Index (v); } inline int operator- (ushort* v, CDynamicArray<ushort>& a) { return a.Index (v); } inline int operator- (int* v, CDynamicArray<int>& a) { return a.Index (v); } inline int operator- (uint* v, CDynamicArray<uint>& a) { return a.Index (v); } class CCharArray : public CDynamicArray<char> { public: inline char* operator= (const char* source) { uint l = uint (strlen (source) + 1); if ((l > this->m_data.length) && !this->Resize (this->m_data.length + l)) return null; memcpy (this->m_data.buffer, source, l); return this->m_data.buffer; } }; //class CByteArray : public CDynamicArray<ubyte> {}; //class CShortArray : public CDynamicArray<short> {}; //class CUShortArray : public CDynamicArray<ushort> {}; //class CIntArray : public CDynamicArray<int> {}; //class CUIntArray : public CDynamicArray<uint> {}; //class CFloatArray : public CDynamicArray<float> {}; //----------------------------------------------------------------------------- template < class _T, uint length > class CStaticArray : public CDynamicArray < _T > { template < class _U, uint _length > class CStaticArrayData { public: _U buffer [_length]; }; protected: CStaticArrayData< _T, length > m_staticData; public: CStaticArray () { Create (length); } _T *Create (uint _length) { this->SetBuffer (m_staticData.buffer, 2, _length); return m_data.buffer; } void Destroy (void) { } }; //----------------------------------------------------------------------------- #endif //_CARRAY_H
bab03a313b17888f22b3b7ff81fe65b7b00ceb5b
9a9307bf09d7afdc8f107296c32b14388945ef45
/car_controller/ros_lib/ros.h
049251d965cec138146271da5cfc53393f376ae0
[]
no_license
ghsecuritylab/robo_car
f9e7e748dee7eb3730c52abdc345bf75cd828d18
69b2e3892bed760f98787935b39b58bebc978882
refs/heads/master
2021-02-26T11:31:51.210368
2020-01-07T09:22:25
2020-01-07T09:22:25
245,521,374
0
0
null
2020-03-06T21:39:20
2020-03-06T21:39:19
null
UTF-8
C++
false
false
1,806
h
/* * Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote prducts derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef _ROS_H_ #define _ROS_H_ #include "ros/node_handle.h" #include "K64fHardware.h" namespace ros { typedef NodeHandle_<K64fHardware> NodeHandle; } #endif
1b0b9ca0706c52ec3f34f36db5ad9917352eb988
938c2a25ae905dad47f74367e2935278aa0d4961
/Recursion/intro.cpp
ac858b5e5238565310d0405b0e907dbc2c707e63
[]
no_license
rohitkadam0101/CPP_Advanced
f120deb8bbf219f92724f29fcae16ec29e1c13fa
aa02ec097d4e4a76b300b2e32a5364e439ae5642
refs/heads/master
2023-07-15T06:58:45.107525
2021-08-28T06:43:46
2021-08-28T06:43:46
400,722,713
0
0
null
null
null
null
UTF-8
C++
false
false
592
cpp
// factorial #include <iostream> using namespace std; // sum of n numbers int sum(int n){ if(n==0){ return 0; } return n+sum(n-1); } // nth fibonaci int fib(int n){ if(n==0|| n==1){ return n; } return fib(n-1)+fib(n-2); } // power n raised to p int pow(int a,int p){ if(p==0){ return 1; } return a* pow(a,p-1); } int fact(int n){ if(n==0){ return 1; } return n * fact(n-1); } int main(){ cout<<sum(4)<<endl; cout<<fib(6)<<endl; cout<<pow(2,4)<<endl; cout<<fact(5)<<endl; return 0; }
ef38ee84953714c61636d9bba9c6c92d361cec08
877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a
/app/src/main/cpp/dir7941/dir29315/dir29712/dir30926/dir33441/file33455.cpp
c9864e299f51cdce4b275d949b71fa51cd8beb48
[]
no_license
tgeng/HugeProject
829c3bdfb7cbaf57727c41263212d4a67e3eb93d
4488d3b765e8827636ce5e878baacdf388710ef2
refs/heads/master
2022-08-21T16:58:54.161627
2020-05-28T01:54:03
2020-05-28T01:54:03
267,468,475
0
0
null
null
null
null
UTF-8
C++
false
false
115
cpp
#ifndef file33455 #error "macro file33455 must be defined" #endif static const char* file33455String = "file33455";
bb810b1deed1cf296cafbb4a6e7084cc2c82d4c7
4d2bb672710ea8f0dd11bb9213db917bb54cca18
/Codeforces Round 327/Top Secret Task/main.cpp
149f218e66925f85764b390fac9ea759fa4c0012
[ "MIT" ]
permissive
sqc1999-oi/Codeforces
cd307c68e267d9a0eec83c7ff4b154eadbba1e9a
5551e0e4b9dc66bb77c697568f0584aac3dbefae
refs/heads/master
2021-06-14T23:47:49.765358
2017-04-16T09:31:58
2017-04-16T09:37:48
41,842,288
0
0
null
null
null
null
UTF-8
C++
false
false
1,005
cpp
#include <iostream> #include <algorithm> #include <cstring> #include <climits> using namespace std; const int N = 150; int q[N], f[2][N + 1][N*(N - 1) / 2 + 1]; int main() { ios::sync_with_stdio(false); int n, k, s; cin >> n >> k >> s; for (int i = 0; i < n; i++) cin >> q[i]; if (s >= (n*2 - k - 1)*k / 2) { sort(q, q + n); int sum = 0; for (int i = 0; i < k; i++) sum += q[i]; cout << sum; } else { memset(f[1], 0x3f, sizeof f[1]); f[1][0][0] = 0; int cu = 0; for (int i = 0; i < n; i++) { memset(f[cu], 0x3f, sizeof f[cu]); for (int j = 0; j <= k && j <= i; j++) for (int l = 0; l <= s && l <= (i*2 - j - 1)*j / 2; l++) { if (l + i - j <= s && j < k) f[cu][j + 1][l + i - j] = min(f[cu][j + 1][l + i - j], f[cu ^ 1][j][l] + q[i]); f[cu][j][l] = min(f[cu][j][l], f[cu ^ 1][j][l]); } cu ^= 1; } int ans = INT_MAX; for (int i = 0; i <= s; i++) ans = min(ans, f[cu ^ 1][k][i]); cout << ans; } }
4114a6d66434d31b3c36c205317e808f0173b510
d4d5a0bc519294e4b3f312048dd52cf9264b7e29
/UESTC/1932/14639492_AC_497ms_25216kB.cpp
572926fce31105ba052bb3fc28d14999ea290b10
[]
no_license
imhdx/My-all-code-of-Vjudge-Judge
fc625f83befbaeda7a033fd271fd4f61d295e807
b0db5247db09837be9866f39b183409f0a02c290
refs/heads/master
2020-04-29T08:16:24.607167
2019-07-24T01:17:15
2019-07-24T01:17:15
175,981,455
0
0
null
null
null
null
UTF-8
C++
false
false
1,442
cpp
#include <set> #include <map> #include <list> #include <deque> #include <cmath> #include <queue> #include <stack> #include <bitset> #include <vector> #include <string> #include <cstdio> #include <cstdlib> #include <iomanip> #include <cstring> #include <fstream> #include <iostream> #include <algorithm> using namespace std; const int maxn=1e6+5; int mn[maxn<<2]; int c[maxn]; int b[maxn]; void pushup(int rt) { mn[rt]=min(mn[rt<<1],mn[rt<<1|1]); } void build(int l,int r,int rt) { if(l==r) { if(l==1) mn[rt]=0; else mn[rt]=-1; return; } int m=l+(r-l)/2; build(l,m,rt<<1); build(m+1,r,rt<<1|1); pushup(rt); } void update(int pos,int be,int l,int r,int rt) { if(l==r) { mn[rt]=be; return; } int m=l+(r-l)/2; if(pos<=m) update(pos,be,l,m,rt<<1); else update(pos,be,m+1,r,rt<<1|1); pushup(rt); } int query(int l,int r,int rt,int tr) { if(l==r) { return l; } int m=l+(r-l)/2; if(mn[rt<<1]<tr) return query(l,m,rt<<1,tr); else return query(m+1,r,rt<<1|1,tr); } int main() { int n; scanf("%d",&n); build(1,n,1); for(int i=1; i<=n; i++) { scanf("%d",&c[i]); int ans=query(1,n,1,i-c[i]); printf("%d",ans); if(i!=n) printf(" "); update(ans,i,1,n,1); } printf("\n"); return 0; }
ab8b666696cc01b7799e3634f903858a026e63d7
1bf42e44294709ea1b7c6a494f2c4b801a48d8d2
/Coding/C++/addlargenum/stack.cpp
e8c62ba54a2a97b4cc1ea816ab6b3ac3f8d6cdbe
[]
no_license
Hadroncollider17/portfolio-2020
922afb715ec91c7f216688e74ed18746083ca7a1
2b93d7743afd91629e469068381d25f3f458b228
refs/heads/master
2022-12-08T13:29:30.292752
2020-08-31T08:38:13
2020-08-31T08:38:13
291,544,894
0
0
null
null
null
null
UTF-8
C++
false
false
773
cpp
//--------------------------------------------------------------------- // Name: Hayson Chu // Email: [email protected] // Class: CMPSC 122, Session 2 // Homework 4 // Due Date: Nov 6, 2019 // // Description: This program read a txt file and adds large numbers. // // Acknowledgement: //--------------------------------------------------------------------- #include <iostream> #include <string> #include "stack.h" using namespace std; bool Stack::IsEmpty() const{ return list.IsEmpty(); } void Stack::Push(char elem){ list.AddToHead(elem); } char Stack::Pop(){ return list.RemoveHead(); } char Stack::Top() const{ return list.GetHead(); } void Stack::Clear(){ while(!list.IsEmpty()) { char contain = Pop(); cout << contain; } }
6ad783fd75af24ee81b06bd05b4d3d49c4d9aed3
949127defa9d2cf4f81a5137ae2cd4f953297426
/camera/CameraWrapper.cpp
a1892109e4e9ddc2e102b65f6beea8c002b73817
[]
no_license
Liberations/multirom_device_xiaomi_libra
432ae0828075c25288ccfd5f2d105f96c3a9fcb7
6b056c96b9135985aa5ebb109486972d6b752783
refs/heads/master
2021-01-20T18:20:09.085857
2016-08-11T03:13:19
2016-08-11T03:13:19
60,863,978
0
5
null
null
null
null
UTF-8
C++
false
false
4,290
cpp
/* * Copyright (C) 2016, The CyanogenMod Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file CameraWrapper.cpp * * This file wraps a vendor camera module. * */ //#define LOG_NDEBUG 0 #define LOG_TAG "CameraWrapper" #include <cutils/log.h> #include <hardware/hardware.h> #include <hardware/camera.h> #include <utils/threads.h> #include <gui/SensorManager.h> static android::Mutex gCameraWrapperLock; static camera_module_t *gVendorModule = 0; static int camera_device_open(const hw_module_t *module, const char *name, hw_device_t **device); static int camera_get_number_of_cameras(void); static int camera_get_camera_info(int camera_id, struct camera_info *info); static struct hw_module_methods_t camera_module_methods = { .open = camera_device_open }; camera_module_t HAL_MODULE_INFO_SYM = { .common = { .tag = HARDWARE_MODULE_TAG, .module_api_version = CAMERA_MODULE_API_VERSION_1_0, .hal_api_version = HARDWARE_HAL_API_VERSION, .id = CAMERA_HARDWARE_MODULE_ID, .name = "MSM8992 Camera Wrapper", .author = "The CyanogenMod Project", .methods = &camera_module_methods, .dso = NULL, /* remove compilation warnings */ .reserved = {0}, /* remove compilation warnings */ }, .get_number_of_cameras = camera_get_number_of_cameras, .get_camera_info = camera_get_camera_info, .set_callbacks = NULL, /* remove compilation warnings */ .get_vendor_tag_ops = NULL, /* remove compilation warnings */ .open_legacy = NULL, /* remove compilation warnings */ .set_torch_mode = NULL, /* remove compilation warnings */ .init = NULL, /* remove compilation warnings */ .reserved = {0}, /* remove compilation warnings */ }; static int check_vendor_module() { int rv = 0; ALOGV("%s", __FUNCTION__); if (gVendorModule) return 0; rv = hw_get_module_by_class("camera", "vendor", (const hw_module_t**)&gVendorModule); if (rv) ALOGE("failed to open vendor camera module"); return rv; } static bool can_talk_to_sensormanager() { android::SensorManager& sensorManager( android::SensorManager::getInstanceForPackage(android::String16("camera"))); android::Sensor const * const * sensorList; return sensorManager.getSensorList(&sensorList) >= 0; } static int camera_device_open(const hw_module_t *module, const char *name, hw_device_t **device) { int rv = 0; int num_cameras = 0; int cameraid; android::Mutex::Autolock lock(gCameraWrapperLock); ALOGV("%s", __FUNCTION__); if (name == NULL || check_vendor_module() != android::NO_ERROR) { return -EINVAL; } // mm-qcamera-daemon blocks until initialization of sensorservice // and might miss V4L events generated by the HAL during that time, // causing HAL initialization failures. Avoid those failures by waiting // for sensorservice initialization before opening the HAL. if (!can_talk_to_sensormanager()) { ALOGE("Waiting for sensor service failed."); return android::NO_INIT; } return gVendorModule->common.methods->open( (const hw_module_t*)gVendorModule, name, device); } static int camera_get_number_of_cameras(void) { ALOGV("%s", __FUNCTION__); if (check_vendor_module()) return 0; return gVendorModule->get_number_of_cameras(); } static int camera_get_camera_info(int camera_id, struct camera_info *info) { ALOGV("%s", __FUNCTION__); if (check_vendor_module()) return 0; return gVendorModule->get_camera_info(camera_id, info); }
e114f56a02d878a5bf91b90545269a304f47f225
948d555823c2d123601ff6c149869be377521282
/SDK/SoT_BP_DamageZone_parameters.hpp
eb0674bc03c761510b360ab183580edb8c58827c
[]
no_license
besimbicer89/SoT-SDK
2acf79303c65edab01107ab4511e9b9af8ab9743
3a4c6f3b77c1045b7ef0cddd064350056ef7d252
refs/heads/master
2022-04-24T01:03:37.163407
2020-04-27T12:45:47
2020-04-27T12:45:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,982
hpp
#pragma once // SeaOfThieves (1.6.4) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function BP_DamageZone.BP_DamageZone_C.GetNumExternalHits struct ABP_DamageZone_C_GetNumExternalHits_Params { int NumExternalHits; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function BP_DamageZone.BP_DamageZone_C.OnRep_Rep_ExternalHitList struct ABP_DamageZone_C_OnRep_Rep_ExternalHitList_Params { }; // Function BP_DamageZone.BP_DamageZone_C.GetOrCreateDecalMID struct ABP_DamageZone_C_GetOrCreateDecalMID_Params { class UMaterialInstanceDynamic* DecalMID; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function BP_DamageZone.BP_DamageZone_C.Initialise struct ABP_DamageZone_C_Initialise_Params { }; // Function BP_DamageZone.BP_DamageZone_C.Update External Hits struct ABP_DamageZone_C_Update_External_Hits_Params { }; // Function BP_DamageZone.BP_DamageZone_C.Clear Decal Flags struct ABP_DamageZone_C_Clear_Decal_Flags_Params { }; // Function BP_DamageZone.BP_DamageZone_C.Add Deferred Decal struct ABP_DamageZone_C_Add_Deferred_Decal_Params { class UDecalComponent* Decal; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function BP_DamageZone.BP_DamageZone_C.KillDeferredDecal struct ABP_DamageZone_C_KillDeferredDecal_Params { class UDecalComponent* Decal; // (Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData) }; // Function BP_DamageZone.BP_DamageZone_C.RemoveDeferredDecals struct ABP_DamageZone_C_RemoveDeferredDecals_Params { }; // Function BP_DamageZone.BP_DamageZone_C.Set Repair Visibility struct ABP_DamageZone_C_Set_Repair_Visibility_Params { bool Visible; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function BP_DamageZone.BP_DamageZone_C.Add External Hit struct ABP_DamageZone_C_Add_External_Hit_Params { struct FHullDamageHit HitData; // (Parm) }; // Function BP_DamageZone.BP_DamageZone_C.CollectTaggedComponents struct ABP_DamageZone_C_CollectTaggedComponents_Params { }; // Function BP_DamageZone.BP_DamageZone_C.UserConstructionScript struct ABP_DamageZone_C_UserConstructionScript_Params { }; // Function BP_DamageZone.BP_DamageZone_C.AddExternalHit struct ABP_DamageZone_C_AddExternalHit_Params { struct FHullDamageHit Hit_Data; // (Parm) }; // Function BP_DamageZone.BP_DamageZone_C.ClearDecalFlags struct ABP_DamageZone_C_ClearDecalFlags_Params { }; // Function BP_DamageZone.BP_DamageZone_C.OnRepairableStateUpdate struct ABP_DamageZone_C_OnRepairableStateUpdate_Params { TEnumAsByte<ERepairableState>* InRepairableState; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function BP_DamageZone.BP_DamageZone_C.OnInitialise struct ABP_DamageZone_C_OnInitialise_Params { }; // Function BP_DamageZone.BP_DamageZone_C.OnDecalMaterialUpdatedToRepaired struct ABP_DamageZone_C_OnDecalMaterialUpdatedToRepaired_Params { }; // Function BP_DamageZone.BP_DamageZone_C.ExecuteUbergraph_BP_DamageZone struct ABP_DamageZone_C_ExecuteUbergraph_BP_DamageZone_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
8cd36011f7cbb252538753ceb472479350620bb5
ae9a04ae8c33623309f1110fbb03d7fdb883f2f7
/SharedPimplRect.h
bfc7c49ceb05d3d6ab02964a49fa2e7ce4fb4ab6
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
hicknhack-software/BenchPimpl
11cdb35552bc4e32089b3337cddf33ba0041bb78
3abb84b88ce05c9664f8451d3408098ac8486b86
refs/heads/master
2021-01-21T13:57:40.128366
2016-05-17T14:27:13
2016-05-17T14:27:13
46,477,361
1
0
null
null
null
null
UTF-8
C++
false
false
1,074
h
/* BenchPimpl * Copyright 2016 HicknHack Software GmbH * * The original code can be found at: * https://github.com/hicknhack-software/BenchPimpl * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "SharedPimplPoint.h" class SharedPimplRect : public SharedPimplPoint { public: SharedPimplRect(double x, double y, double w, double h); double width() const; double height() const; double sum() const; protected: class Implementation; SharedPimplRect(std::shared_ptr<Implementation>); };
1976808bf3ddcd158a3bf6f6b22b62bb3ef66976
876054689f05109cfd8b7353a5d68620d785c8da
/preflate_statistical_model.h
dd1876c626161e05a769919f641aabcb1bdb4e62
[ "Apache-2.0" ]
permissive
deus-libri/preflate
0bf6788eb0614b4a14b6f891a77c2defbb6f5040
609eefaa96ac6c51d7b1a3fb29e0ed94d0f3623e
refs/heads/master
2023-07-24T14:51:11.050222
2018-09-29T10:53:11
2018-09-29T10:53:11
125,667,838
32
2
null
null
null
null
UTF-8
C++
false
false
4,684
h
/* Copyright 2018 Dirk Steinke Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef PREFLATE_STATISTICS_COUNTER_H #define PREFLATE_STATISTICS_COUNTER_H #include <algorithm> struct PreflateStatisticsCounter { struct BlockPrediction { public: void incBlockType(const unsigned bt) { blockType[bt]++; } void incEOBPredictionWrong(const bool mispredicted) { EOBMisprediction[mispredicted]++; } void incNonZeroPadding(const bool nonzeropadding) { nonZeroPadding[nonzeropadding]++; } static unsigned totalModels() { return 3; } unsigned checkDefaultModels() const; void print(); private: unsigned blockType[3]; // stored, dynamic huff, static huff unsigned EOBMisprediction[2]; // no, yes unsigned nonZeroPadding[2]; // no, yes friend struct PreflateBlockPredictionModel; }; struct TreeCodePrediction { public: void incTreeCodeCountPredictionWrong(const bool mispredicted) { TCCountMisprediction[mispredicted]++; } void incTreeCodeLengthDiffToPrediction(const int len_diff) { TCBitlengthCorrection[std::max(std::min(len_diff, 3), -3) + 3]++; } void incLiteralCountPredictionWrong(const bool mispredicted) { LCountMisprediction[mispredicted]++; } void incDistanceCountPredictionWrong(const bool mispredicted) { DCountMisprediction[mispredicted]++; } void incLDCodeTypePredictionWrong(const unsigned codetype, const bool mispredicted) { LDTypeMisprediction[codetype][mispredicted]++; } void incLDCodeTypeReplacement(const unsigned replacement_codetype) { LDTypeReplacement[replacement_codetype]++; } void incLDCodeRepeatDiffToPrediction(const int len_diff) { LDRepeatCountCorrection[std::max(std::min(len_diff, 1), -1) + 1]++; } void incLDCodeLengthDiffToPrediction(const int len_diff) { LDBitlengthCorrection[std::max(std::min(len_diff, 4), -4) + 4]++; } static unsigned totalModels() { return 11; } unsigned checkDefaultModels() const; void print(); private: unsigned TCCountMisprediction[2]; // no, yes unsigned TCBitlengthCorrection[7]; // -x, -2, -1, 0, +1, +2, +x unsigned LCountMisprediction[2]; // no, yes unsigned DCountMisprediction[2]; // no, yes unsigned LDTypeMisprediction[4][2]; // types: BL,REP,REPZS,REPZL; no, yes unsigned LDTypeReplacement[4]; // replacement type: BL,REP,REPZS,REPZL unsigned LDRepeatCountCorrection[3]; // -x, 0, +x unsigned LDBitlengthCorrection[9]; // -x, -3, -2, -1, 0, +1, +2, +3, +x friend struct PreflateTreeCodePredictionModel; }; struct TokenPrediction { public: void incLiteralPredictionWrong(const bool mispredicted) { LITMisprediction[mispredicted]++; } void incReferencePredictionWrong(const bool mispredicted) { REFMisprediction[mispredicted]++; } void incLengthDiffToPrediction(const int len_diff) { LENCorrection[std::max(std::min(len_diff, 6), -6) + 6]++; } void incIrregularLength258Encoding(const bool irregular) { LEN258IrregularEncoding[irregular]++; } void incDistanceDiffToPredictionAfterIncorrectLengthPrediction(const int len_diff) { DISTAfterLenCorrection[std::min(len_diff, 3)]++; } void incDistanceDiffToPredictionAfterCorrectLengthPrediction(const int len_diff) { DISTOnlyCorrection[std::min(len_diff, 3)]++; } static unsigned totalModels() { return 6; } unsigned checkDefaultModels() const; void print(); private: unsigned LITMisprediction[2]; // no, yes unsigned REFMisprediction[2]; // no, yes unsigned LENCorrection[13]; // -x, -5, -4, -3, -2, -1, 0, +1, +2, +3, +4, +5, +x (bytes) unsigned LEN258IrregularEncoding[2]; // no, yes unsigned DISTAfterLenCorrection[4]; // +0, +1, +2, +x (hops) unsigned DISTOnlyCorrection[4]; // +0, +1, +2, +x (hops) friend struct PreflateTokenPredictionModel; }; public: PreflateStatisticsCounter() {} BlockPrediction block; TreeCodePrediction treecode; TokenPrediction token; void print(); }; #endif /* PREFLATE_STATISTICS_COUNTER_H */
db1b7bdbfe1d2017b968e04b069ab4188e26862a
661fb5bb3879612b53644bb6c2226d7b96f6dade
/Components/8272/i8272.cpp
288d68064b3e348182e938bfd1cad8bd797054bf
[ "MIT" ]
permissive
mattgodbolt/CLK
71e3574fae3923b86b395251eab0f4cdc3ce13b0
85085a637524dcf22e3990707ac0107a657bb1fd
refs/heads/master
2021-05-06T18:06:44.266823
2017-11-23T21:23:31
2017-11-23T21:23:31
111,944,831
2
0
null
2017-11-24T18:07:52
2017-11-24T18:07:52
null
UTF-8
C++
false
false
27,968
cpp
// // i8272.cpp // Clock Signal // // Created by Thomas Harte on 05/08/2017. // Copyright © 2017 Thomas Harte. All rights reserved. // #include "i8272.hpp" //#include "../../Storage/Disk/Encodings/MFM/Encoder.hpp" #include <cstdio> using namespace Intel::i8272; #define SetDataRequest() (main_status_ |= 0x80) #define ResetDataRequest() (main_status_ &= ~0x80) #define DataRequest() (main_status_ & 0x80) #define SetDataDirectionToProcessor() (main_status_ |= 0x40) #define SetDataDirectionFromProcessor() (main_status_ &= ~0x40) #define DataDirectionToProcessor() (main_status_ & 0x40) #define SetNonDMAExecution() (main_status_ |= 0x20) #define ResetNonDMAExecution() (main_status_ &= ~0x20) #define SetBusy() (main_status_ |= 0x10) #define ResetBusy() (main_status_ &= ~0x10) #define Busy() (main_status_ & 0x10) #define SetAbnormalTermination() (status_[0] |= 0x40) #define SetInvalidCommand() (status_[0] |= 0x80) #define SetReadyChanged() (status_[0] |= 0xc0) #define SetSeekEnd() (status_[0] |= 0x20) #define SetEquipmentCheck() (status_[0] |= 0x10) #define SetNotReady() (status_[0] |= 0x08) #define SetSide2() (status_[0] |= 0x04) #define SetEndOfCylinder() (status_[1] |= 0x80) #define SetDataError() (status_[1] |= 0x20) #define SetOverrun() (status_[1] |= 0x10) #define SetNoData() (status_[1] |= 0x04) #define SetNotWriteable() (status_[1] |= 0x02) #define SetMissingAddressMark() (status_[1] |= 0x01) #define SetControlMark() (status_[2] |= 0x40) #define ClearControlMark() (status_[2] &= ~0x40) #define ControlMark() (status_[2] & 0x40) #define SetDataFieldDataError() (status_[2] |= 0x20) #define SetWrongCyinder() (status_[2] |= 0x10) #define SetScanEqualHit() (status_[2] |= 0x08) #define SetScanNotSatisfied() (status_[2] |= 0x04) #define SetBadCylinder() (status_[2] |= 0x02) #define SetMissingDataAddressMark() (status_[2] |= 0x01) namespace { const uint8_t CommandReadData = 0x06; const uint8_t CommandReadDeletedData = 0x0c; const uint8_t CommandWriteData = 0x05; const uint8_t CommandWriteDeletedData = 0x09; const uint8_t CommandReadTrack = 0x02; const uint8_t CommandReadID = 0x0a; const uint8_t CommandFormatTrack = 0x0d; const uint8_t CommandScanLow = 0x11; const uint8_t CommandScanLowOrEqual = 0x19; const uint8_t CommandScanHighOrEqual = 0x1d; const uint8_t CommandRecalibrate = 0x07; const uint8_t CommandSeek = 0x0f; const uint8_t CommandSenseInterruptStatus = 0x08; const uint8_t CommandSpecify = 0x03; const uint8_t CommandSenseDriveStatus = 0x04; } i8272::i8272(BusHandler &bus_handler, Cycles clock_rate) : Storage::Disk::MFMController(clock_rate), bus_handler_(bus_handler) { posit_event(static_cast<int>(Event8272::CommandByte)); } bool i8272::is_sleeping() { return is_sleeping_ && Storage::Disk::MFMController::is_sleeping(); } void i8272::run_for(Cycles cycles) { Storage::Disk::MFMController::run_for(cycles); if(is_sleeping_) return; // check for an expired timer if(delay_time_ > 0) { if(cycles.as_int() >= delay_time_) { delay_time_ = 0; posit_event(static_cast<int>(Event8272::Timer)); } else { delay_time_ -= cycles.as_int(); } } // update seek status of any drives presently seeking if(drives_seeking_) { int drives_left = drives_seeking_; for(int c = 0; c < 4; c++) { if(drives_[c].phase == Drive::Seeking) { drives_[c].step_rate_counter += cycles.as_int(); int steps = drives_[c].step_rate_counter / (8000 * step_rate_time_); drives_[c].step_rate_counter %= (8000 * step_rate_time_); while(steps--) { // Perform a step. int direction = (drives_[c].target_head_position < drives_[c].head_position) ? -1 : 1; printf("Target %d versus believed %d\n", drives_[c].target_head_position, drives_[c].head_position); select_drive(c); get_drive().step(direction); if(drives_[c].target_head_position >= 0) drives_[c].head_position += direction; // Check for completion. if(seek_is_satisfied(c)) { drives_[c].phase = Drive::CompletedSeeking; drives_seeking_--; break; } } drives_left--; if(!drives_left) break; } } } // check for any head unloads if(head_timers_running_) { int timers_left = head_timers_running_; for(int c = 0; c < 8; c++) { int drive = (c >> 1); int head = c&1; if(drives_[drive].head_unload_delay[head] > 0) { if(cycles.as_int() >= drives_[drive].head_unload_delay[head]) { drives_[drive].head_unload_delay[head] = 0; drives_[drive].head_is_loaded[head] = false; head_timers_running_--; } else { drives_[drive].head_unload_delay[head] -= cycles.as_int(); } timers_left--; if(!timers_left) break; } } } // check for busy plus ready disabled if(is_executing_ && !get_drive().get_is_ready()) { posit_event(static_cast<int>(Event8272::NoLongerReady)); } is_sleeping_ = !delay_time_ && !drives_seeking_ && !head_timers_running_; if(is_sleeping_) update_sleep_observer(); } void i8272::set_register(int address, uint8_t value) { // don't consider attempted sets to the status register if(!address) return; // if not ready for commands, do nothing if(!DataRequest() || DataDirectionToProcessor()) return; if(expects_input_) { input_ = value; has_input_ = true; ResetDataRequest(); } else { // accumulate latest byte in the command byte sequence command_.push_back(value); posit_event(static_cast<int>(Event8272::CommandByte)); } } uint8_t i8272::get_register(int address) { if(address) { if(result_stack_.empty()) return 0xff; uint8_t result = result_stack_.back(); result_stack_.pop_back(); if(result_stack_.empty()) posit_event(static_cast<int>(Event8272::ResultEmpty)); return result; } else { return main_status_; } } #define BEGIN_SECTION() switch(resume_point_) { default: #define END_SECTION() } #define MS_TO_CYCLES(x) x * 8000 #define WAIT_FOR_EVENT(mask) resume_point_ = __LINE__; interesting_event_mask_ = static_cast<int>(mask); return; case __LINE__: #define WAIT_FOR_TIME(ms) resume_point_ = __LINE__; interesting_event_mask_ = static_cast<int>(Event8272::Timer); delay_time_ = MS_TO_CYCLES(ms); is_sleeping_ = false; update_sleep_observer(); case __LINE__: if(delay_time_) return; #define PASTE(x, y) x##y #define CONCAT(x, y) PASTE(x, y) #define FIND_HEADER() \ set_data_mode(DataMode::Scanning); \ CONCAT(find_header, __LINE__): WAIT_FOR_EVENT(static_cast<int>(Event::Token) | static_cast<int>(Event::IndexHole)); \ if(event_type == static_cast<int>(Event::IndexHole)) { index_hole_limit_--; } \ else if(get_latest_token().type == Token::ID) goto CONCAT(header_found, __LINE__); \ \ if(index_hole_limit_) goto CONCAT(find_header, __LINE__); \ CONCAT(header_found, __LINE__): (void)0;\ #define FIND_DATA() \ set_data_mode(DataMode::Scanning); \ CONCAT(find_data, __LINE__): WAIT_FOR_EVENT(static_cast<int>(Event::Token) | static_cast<int>(Event::IndexHole)); \ if(event_type == static_cast<int>(Event::Token)) { \ if(get_latest_token().type == Token::Byte || get_latest_token().type == Token::Sync) goto CONCAT(find_data, __LINE__); \ } #define READ_HEADER() \ distance_into_section_ = 0; \ set_data_mode(DataMode::Reading); \ CONCAT(read_header, __LINE__): WAIT_FOR_EVENT(Event::Token); \ header_[distance_into_section_] = get_latest_token().byte_value; \ distance_into_section_++; \ if(distance_into_section_ < 6) goto CONCAT(read_header, __LINE__); \ #define SET_DRIVE_HEAD_MFM() \ active_drive_ = command_[1]&3; \ active_head_ = (command_[1] >> 2)&1; \ status_[0] = (command_[1]&7); \ select_drive(active_drive_); \ get_drive().set_head(active_head_); \ set_is_double_density(command_[0] & 0x40); #define WAIT_FOR_BYTES(n) \ distance_into_section_ = 0; \ CONCAT(wait_bytes, __LINE__): WAIT_FOR_EVENT(Event::Token); \ if(get_latest_token().type == Token::Byte) distance_into_section_++; \ if(distance_into_section_ < (n)) goto CONCAT(wait_bytes, __LINE__); #define LOAD_HEAD() \ if(!drives_[active_drive_].head_is_loaded[active_head_]) { \ drives_[active_drive_].head_is_loaded[active_head_] = true; \ WAIT_FOR_TIME(head_load_time_); \ } else { \ if(drives_[active_drive_].head_unload_delay[active_head_] > 0) { \ drives_[active_drive_].head_unload_delay[active_head_] = 0; \ head_timers_running_--; \ } \ } #define SCHEDULE_HEAD_UNLOAD() \ if(drives_[active_drive_].head_is_loaded[active_head_]) {\ if(drives_[active_drive_].head_unload_delay[active_head_] == 0) { \ head_timers_running_++; \ is_sleeping_ = false; \ update_sleep_observer(); \ } \ drives_[active_drive_].head_unload_delay[active_head_] = MS_TO_CYCLES(head_unload_time_);\ } void i8272::posit_event(int event_type) { if(event_type == static_cast<int>(Event::IndexHole)) index_hole_count_++; if(event_type == static_cast<int>(Event8272::NoLongerReady)) { SetNotReady(); goto abort; } if(!(interesting_event_mask_ & event_type)) return; interesting_event_mask_ &= ~event_type; BEGIN_SECTION(); // Resets busy and non-DMA execution, clears the command buffer, sets the data mode to scanning and flows // into wait_for_complete_command_sequence. wait_for_command: expects_input_ = false; set_data_mode(Storage::Disk::MFMController::DataMode::Scanning); ResetBusy(); ResetNonDMAExecution(); command_.clear(); // Sets the data request bit, and waits for a byte. Then sets the busy bit. Continues accepting bytes // until it has a quantity that make up an entire command, then resets the data request bit and // branches to that command. wait_for_complete_command_sequence: SetDataRequest(); SetDataDirectionFromProcessor(); WAIT_FOR_EVENT(Event8272::CommandByte) SetBusy(); static const std::size_t required_lengths[32] = { 0, 0, 9, 3, 2, 9, 9, 2, 1, 9, 2, 0, 9, 6, 0, 3, 0, 9, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 9, 0, 0, }; if(command_.size() < required_lengths[command_[0] & 0x1f]) goto wait_for_complete_command_sequence; if(command_.size() == 9) { cylinder_ = command_[2]; head_ = command_[3]; sector_ = command_[4]; size_ = command_[5]; } ResetDataRequest(); status_[0] = status_[1] = status_[2] = 0; // If this is not clearly a command that's safe to carry out in parallel to a seek, end all seeks. switch(command_[0] & 0x1f) { case CommandReadData: case CommandReadDeletedData: case CommandWriteData: case CommandWriteDeletedData: case CommandReadTrack: case CommandReadID: case CommandFormatTrack: case CommandScanLow: case CommandScanLowOrEqual: case CommandScanHighOrEqual: is_access_command_ = true; break; default: is_access_command_ = false; break; } if(is_access_command_) { for(int c = 0; c < 4; c++) { if(drives_[c].phase == Drive::Seeking) { drives_[c].phase = Drive::NotSeeking; drives_seeking_--; } } // Establishes the drive and head being addressed, and whether in double density mode; populates the internal // cylinder, head, sector and size registers from the command stream. is_executing_ = true; if(!dma_mode_) SetNonDMAExecution(); SET_DRIVE_HEAD_MFM(); LOAD_HEAD(); if(!get_drive().get_is_ready()) { SetNotReady(); goto abort; } } // Jump to the proper place. switch(command_[0] & 0x1f) { case CommandReadData: case CommandReadDeletedData: goto read_data; case CommandWriteData: case CommandWriteDeletedData: goto write_data; case CommandReadTrack: goto read_track; case CommandReadID: goto read_id; case CommandFormatTrack: goto format_track; case CommandScanLow: goto scan_low; case CommandScanLowOrEqual: goto scan_low_or_equal; case CommandScanHighOrEqual: goto scan_high_or_equal; case CommandRecalibrate: goto recalibrate; case CommandSeek: goto seek; case CommandSenseInterruptStatus: goto sense_interrupt_status; case CommandSpecify: goto specify; case CommandSenseDriveStatus: goto sense_drive_status; default: goto invalid; } // Decodes drive, head and density, loads the head, loads the internal cylinder, head, sector and size registers, // and searches for a sector that meets those criteria. If one is found, inspects the instruction in use and // jumps to an appropriate handler. read_write_find_header: // Sets a maximum index hole limit of 2 then performs a find header/read header loop, continuing either until // the index hole limit is breached or a sector is found with a cylinder, head, sector and size equal to the // values in the internal registers. index_hole_limit_ = 2; // printf("Seeking %02x %02x %02x %02x\n", cylinder_, head_, sector_, size_); find_next_sector: FIND_HEADER(); if(!index_hole_limit_) { // Two index holes have passed wihout finding the header sought. // printf("Not found\n"); SetNoData(); goto abort; } index_hole_count_ = 0; // printf("Header\n"); READ_HEADER(); if(index_hole_count_) { // This implies an index hole was sighted within the header. Error out. SetEndOfCylinder(); goto abort; } if(get_crc_generator().get_value()) { // This implies a CRC error in the header; mark as such but continue. SetDataError(); } // printf("Considering %02x %02x %02x %02x [%04x]\n", header_[0], header_[1], header_[2], header_[3], get_crc_generator().get_value()); if(header_[0] != cylinder_ || header_[1] != head_ || header_[2] != sector_ || header_[3] != size_) goto find_next_sector; // Branch to whatever is supposed to happen next // printf("Proceeding\n"); switch(command_[0] & 0x1f) { case CommandReadData: case CommandReadDeletedData: goto read_data_found_header; case CommandWriteData: // write data case CommandWriteDeletedData: // write deleted data goto write_data_found_header; } // Performs the read data or read deleted data command. read_data: printf("Read [deleted] data [%02x %02x %02x %02x ... %02x %02x]\n", command_[2], command_[3], command_[4], command_[5], command_[6], command_[8]); read_next_data: goto read_write_find_header; // Finds the next data block and sets data mode to reading, setting an error flag if the on-disk deleted // flag doesn't match the sort the command was looking for. read_data_found_header: FIND_DATA(); ClearControlMark(); if(event_type == static_cast<int>(Event::Token)) { if(get_latest_token().type != Token::Data && get_latest_token().type != Token::DeletedData) { // Something other than a data mark came next — impliedly an ID or index mark. SetMissingAddressMark(); SetMissingDataAddressMark(); goto abort; // TODO: or read_next_data? } else { if((get_latest_token().type == Token::Data) != ((command_[0] & 0x1f) == CommandReadData)) { if(!(command_[0]&0x20)) { // SK is not set; set the error flag but read this sector before finishing. SetControlMark(); } else { // SK is set; skip this sector. goto read_next_data; } } } } else { // An index hole appeared before the data mark. SetEndOfCylinder(); goto abort; // TODO: or read_next_data? } distance_into_section_ = 0; set_data_mode(Reading); // Waits for the next token, then supplies it to the CPU by: (i) setting data request and direction; and (ii) resetting // data request once the byte has been taken. Continues until all bytes have been read. // // TODO: consider DTL. read_data_get_byte: WAIT_FOR_EVENT(static_cast<int>(Event::Token) | static_cast<int>(Event::IndexHole)); if(event_type == static_cast<int>(Event::Token)) { result_stack_.push_back(get_latest_token().byte_value); distance_into_section_++; SetDataRequest(); SetDataDirectionToProcessor(); WAIT_FOR_EVENT(static_cast<int>(Event8272::ResultEmpty) | static_cast<int>(Event::Token) | static_cast<int>(Event::IndexHole)); } switch(event_type) { case static_cast<int>(Event8272::ResultEmpty): // The caller read the byte in time; proceed as normal. ResetDataRequest(); if(distance_into_section_ < (128 << size_)) goto read_data_get_byte; break; case static_cast<int>(Event::Token): // The caller hasn't read the old byte yet and a new one has arrived SetOverrun(); goto abort; break; case static_cast<int>(Event::IndexHole): SetEndOfCylinder(); goto abort; break; } // read CRC, without transferring it, then check it WAIT_FOR_EVENT(Event::Token); WAIT_FOR_EVENT(Event::Token); if(get_crc_generator().get_value()) { // This implies a CRC error in the sector; mark as such and temrinate. SetDataError(); SetDataFieldDataError(); goto abort; } // check whether that's it: either the final requested sector has been read, or because // a sector that was [/wasn't] marked as deleted when it shouldn't [/should] have been if(sector_ != command_[6] && !ControlMark()) { sector_++; goto read_next_data; } // For a final result phase, post the standard ST0, ST1, ST2, C, H, R, N goto post_st012chrn; write_data: printf("Write [deleted] data [%02x %02x %02x %02x ... %02x %02x]\n", command_[2], command_[3], command_[4], command_[5], command_[6], command_[8]); if(get_drive().get_is_read_only()) { SetNotWriteable(); goto abort; } write_next_data: goto read_write_find_header; write_data_found_header: WAIT_FOR_BYTES(get_is_double_density() ? 22 : 11); begin_writing(true); write_id_data_joiner((command_[0] & 0x1f) == CommandWriteDeletedData, true); SetDataDirectionFromProcessor(); SetDataRequest(); expects_input_ = true; distance_into_section_ = 0; write_loop: WAIT_FOR_EVENT(Event::DataWritten); if(!has_input_) { SetOverrun(); goto abort; } write_byte(input_); has_input_ = false; distance_into_section_++; if(distance_into_section_ < (128 << size_)) { SetDataRequest(); goto write_loop; } printf("Wrote %d bytes\n", distance_into_section_); write_crc(); expects_input_ = false; WAIT_FOR_EVENT(Event::DataWritten); end_writing(); if(sector_ != command_[6]) { sector_++; goto write_next_data; } goto post_st012chrn; // Performs the read ID command. read_id: // Establishes the drive and head being addressed, and whether in double density mode. printf("Read ID [%02x %02x]\n", command_[0], command_[1]); // Sets a maximum index hole limit of 2 then waits either until it finds a header mark or sees too many index holes. // If a header mark is found, reads in the following bytes that produce a header. Otherwise branches to data not found. index_hole_limit_ = 2; FIND_HEADER(); if(!index_hole_limit_) { SetMissingAddressMark(); goto abort; } READ_HEADER(); // Sets internal registers from the discovered header and posts the standard ST0, ST1, ST2, C, H, R, N. cylinder_ = header_[0]; head_ = header_[1]; sector_ = header_[2]; size_ = header_[3]; goto post_st012chrn; // Performs read track. read_track: printf("Read track [%02x %02x %02x %02x]\n", command_[2], command_[3], command_[4], command_[5]); // Wait for the index hole. WAIT_FOR_EVENT(Event::IndexHole); sector_ = 0; index_hole_limit_ = 2; // While not index hole again, stream all sector contents until EOT sectors have been read. read_track_next_sector: FIND_HEADER(); if(!index_hole_limit_) { if(!sector_) { SetMissingAddressMark(); goto abort; } else { goto post_st012chrn; } } READ_HEADER(); FIND_DATA(); distance_into_section_ = 0; SetDataDirectionToProcessor(); read_track_get_byte: WAIT_FOR_EVENT(Event::Token); result_stack_.push_back(get_latest_token().byte_value); distance_into_section_++; SetDataRequest(); // TODO: other possible exit conditions; find a way to merge with the read_data version of this. WAIT_FOR_EVENT(static_cast<int>(Event8272::ResultEmpty)); ResetDataRequest(); if(distance_into_section_ < (128 << header_[2])) goto read_track_get_byte; sector_++; if(sector_ < command_[6]) goto read_track_next_sector; goto post_st012chrn; // Performs format [/write] track. format_track: printf("Format track\n"); if(get_drive().get_is_read_only()) { SetNotWriteable(); goto abort; } // Wait for the index hole. WAIT_FOR_EVENT(Event::IndexHole); index_hole_count_ = 0; begin_writing(true); // Write start-of-track. write_start_of_track(); WAIT_FOR_EVENT(Event::DataWritten); sector_ = 0; format_track_write_sector: write_id_joiner(); // Write the sector header, obtaining its contents // from the processor. SetDataDirectionFromProcessor(); SetDataRequest(); expects_input_ = true; distance_into_section_ = 0; format_track_write_header: WAIT_FOR_EVENT(static_cast<int>(Event::DataWritten) | static_cast<int>(Event::IndexHole)); switch(event_type) { case static_cast<int>(Event::IndexHole): SetOverrun(); goto abort; break; case static_cast<int>(Event::DataWritten): header_[distance_into_section_] = input_; write_byte(input_); has_input_ = false; distance_into_section_++; if(distance_into_section_ < 4) { SetDataRequest(); goto format_track_write_header; } break; } printf("W: %02x %02x %02x %02x, %04x\n", header_[0], header_[1], header_[2], header_[3], get_crc_generator().get_value()); write_crc(); // Write the sector body. write_id_data_joiner(false, false); write_n_bytes(128 << command_[2], command_[5]); write_crc(); // Write the prescribed gap. write_n_bytes(command_[4], get_is_double_density() ? 0x4e : 0xff); // Consider repeating. sector_++; if(sector_ < command_[3] && !index_hole_count_) goto format_track_write_sector; // Otherwise, pad out to the index hole. format_track_pad: write_byte(get_is_double_density() ? 0x4e : 0xff); WAIT_FOR_EVENT(static_cast<int>(Event::DataWritten) | static_cast<int>(Event::IndexHole)); if(event_type != static_cast<int>(Event::IndexHole)) goto format_track_pad; end_writing(); cylinder_ = header_[0]; head_ = header_[1]; sector_ = header_[2] + 1; size_ = header_[3]; goto post_st012chrn; scan_low: printf("Scan low unimplemented!!\n"); goto wait_for_command; scan_low_or_equal: printf("Scan low or equal unimplemented!!\n"); goto wait_for_command; scan_high_or_equal: printf("Scan high or equal unimplemented!!\n"); goto wait_for_command; // Performs both recalibrate and seek commands. These commands occur asynchronously, so the actual work // occurs in ::run_for; this merely establishes that seeking should be ongoing. recalibrate: seek: { int drive = command_[1]&3; select_drive(drive); // Increment the seeking count if this drive wasn't already seeking. if(drives_[drive].phase != Drive::Seeking) { drives_seeking_++; is_sleeping_ = false; update_sleep_observer(); } // Set currently seeking, with a step to occur right now (yes, it sounds like jamming these // in could damage your drive motor). drives_[drive].phase = Drive::Seeking; drives_[drive].step_rate_counter = 8000 * step_rate_time_; drives_[drive].steps_taken = 0; drives_[drive].seek_failed = false; main_status_ |= 1 << (command_[1]&3); // If this is a seek, set the processor-supplied target location; otherwise it is a recalibrate, // which means resetting the current state now but aiming to hit '-1' (which the stepping code // up in run_for understands to mean 'keep going until track 0 is active'). if(command_.size() > 2) { drives_[drive].target_head_position = command_[2]; printf("Seek to %02x\n", command_[2]); } else { drives_[drive].target_head_position = -1; drives_[drive].head_position = 0; printf("Recalibrate\n"); } // Check whether any steps are even needed; if not then mark as completed already. if(seek_is_satisfied(drive)) { drives_[drive].phase = Drive::CompletedSeeking; drives_seeking_--; } } goto wait_for_command; // Performs sense interrupt status. sense_interrupt_status: printf("Sense interrupt status\n"); { // Find the first drive that is in the CompletedSeeking state. int found_drive = -1; for(int c = 0; c < 4; c++) { if(drives_[c].phase == Drive::CompletedSeeking) { found_drive = c; break; } } // If a drive was found, return its results. Otherwise return a single 0x80. if(found_drive != -1) { drives_[found_drive].phase = Drive::NotSeeking; status_[0] = static_cast<uint8_t>(found_drive); main_status_ &= ~(1 << found_drive); SetSeekEnd(); result_stack_ = { drives_[found_drive].head_position, status_[0]}; } else { result_stack_ = { 0x80 }; } } goto post_result; // Performs specify. specify: // Just store the values, and terminate the command. printf("Specify\n"); step_rate_time_ = 16 - (command_[1] >> 4); // i.e. 1 to 16ms head_unload_time_ = (command_[1] & 0x0f) << 4; // i.e. 16 to 240ms head_load_time_ = command_[2] & ~1; // i.e. 2 to 254 ms in increments of 2ms if(!head_unload_time_) head_unload_time_ = 16; if(!head_load_time_) head_load_time_ = 2; dma_mode_ = !(command_[2] & 1); goto wait_for_command; sense_drive_status: printf("Sense drive status\n"); { int drive = command_[1] & 3; select_drive(drive); result_stack_= { static_cast<uint8_t>( (command_[1] & 7) | // drive and head number 0x08 | // single sided (get_drive().get_is_track_zero() ? 0x10 : 0x00) | (get_drive().get_is_ready() ? 0x20 : 0x00) | (get_drive().get_is_read_only() ? 0x40 : 0x00) ) }; } goto post_result; // Performs any invalid command. invalid: // A no-op, but posts ST0 (but which ST0?) result_stack_ = {0x80}; goto post_result; // Sets abnormal termination of the current command and proceeds to an ST0, ST1, ST2, C, H, R, N result phase. abort: end_writing(); SetAbnormalTermination(); goto post_st012chrn; // Posts ST0, ST1, ST2, C, H, R and N as a result phase. post_st012chrn: SCHEDULE_HEAD_UNLOAD(); result_stack_ = {size_, sector_, head_, cylinder_, status_[2], status_[1], status_[0]}; goto post_result; // Posts whatever is in result_stack_ as a result phase. Be aware that it is a stack — the // last thing in it will be returned first. post_result: printf("Result to %02x, main %02x: ", command_[0] & 0x1f, main_status_); for(std::size_t c = 0; c < result_stack_.size(); c++) { printf("%02x ", result_stack_[result_stack_.size() - 1 - c]); } printf("\n"); // Set ready to send data to the processor, no longer in non-DMA execution phase. is_executing_ = false; ResetNonDMAExecution(); SetDataRequest(); SetDataDirectionToProcessor(); // The actual stuff of unwinding result_stack_ is handled by ::get_register; wait // until the processor has read all result bytes. WAIT_FOR_EVENT(Event8272::ResultEmpty); // Reset data direction and end the command. goto wait_for_command; END_SECTION() } bool i8272::seek_is_satisfied(int drive) { return (drives_[drive].target_head_position == drives_[drive].head_position) || (drives_[drive].target_head_position == -1 && get_drive().get_is_track_zero()); } void i8272::set_dma_acknowledge(bool dack) { } void i8272::set_terminal_count(bool tc) { } void i8272::set_data_input(uint8_t value) { } uint8_t i8272::get_data_output() { return 0xff; }
4fb1289b111cba90c0dac65cb20afe01ff7818f7
341612fd3fe8162b7f96a523dcfd8be197e04312
/Logic_Game/Logic_Game/Player.cpp
c88b509133d22a6bcf77b7ffd6cd613c04a490b3
[]
no_license
Miklakapi/Logic_Game
f45f3a0aac8851d6f15adb2762ac1d2c9313ef0c
421b9e4152b2e3148873b78b38f1017269190543
refs/heads/master
2022-05-28T02:52:17.612643
2022-03-22T21:59:23
2022-03-22T21:59:23
169,990,507
0
0
null
null
null
null
UTF-8
C++
false
false
4,434
cpp
#include "Player.hpp" Player::Player(Vector2f position, string textureFile){ rect = new IntRect[12]; *(rect + 0) = { 0,0,80,80 }; *(rect + 1) = { 80,0,80,80 }; *(rect + 2) = { 160,0,80,80 }; *(rect + 3) = { 0,80,80,80 }; *(rect + 4) = { 80,80,80,80 }; *(rect + 5) = { 160,80,80,80 }; // *(rect + 6) = { 240,0,80,80 }; *(rect + 7) = { 320,0,80,80 }; *(rect + 8) = { 400,0,80,80 }; *(rect + 9) = { 240,80,80,80 }; *(rect + 10) = { 320,80,80,80 }; *(rect + 11) = { 400,80,80,80 }; setPlayerTexture(textureFile); setSize(Vector2f{ 80,80 }); setPosition(Vector2f{ 0,0 }); reset(); } void Player::setStage(int stage) { if (stage > 5 || stage < 0) stage = 0; clockStage.restart(); setTextureRect(*(rect + stage)); this->stage = stage; } void Player::setPlayerTexture(string textureFile) { texture.loadFromFile(textureFile); setTexture(&texture); } void Player::setLive(bool live) { if (!live) { setTextureRect(*(rect + stage + 6)); } clockStage.restart(); this->live = live; } bool Player::getLive() { return live; } Clock Player::getClock() { return clockStage; } bool Player::movePlayer(Direction direction, Map& map, SlidingBlock* block, int number, Mirror* mirror, int number2, Door* door, int number3, ShootingBlock* blockS, int number4, LaserMachine* machine, int number5, LaserReceiver* receiver, int number6) { if (!live || moveNr != 10) return false; if (direction == Player::Direction::None) return false; VectorConverter vec(getPosition()); switch (direction) { case Player::Up: vec = vec.convert(vec.asXY().x, vec.asXY().y - 1); break; case Player::Down: vec = vec.convert(vec.asXY().x, vec.asXY().y + 1); break; case Player::Left: vec = vec.convert(vec.asXY().x - 1, vec.asXY().y); break; case Player::Right: vec = vec.convert(vec.asXY().x + 1, vec.asXY().y); break; } if (map.getType(vec.asNumber()) == Square::Type::Wall) return false; for (int i = 0; i < number; i++) { if ((block + i)->getExist() && (block + i)->getPosition() == vec.asVector2f()) return true; } for (int i = 0; i < number2; i++) { if ((mirror + i)->getExist() && (mirror + i)->getPosition() == vec.asVector2f()) return true; } for (int i = 0; i < number3; i++) { if (!(door + i)->isOpen() && (door + i)->getPosition() == vec.asVector2f()) return false; } for (int i = 0; i < number4; i++) { if ((blockS + i)->getPosition() == vec.asVector2f()) return false; } for (int i = 0; i < number5; i++) { if ((machine + i)->getPosition() == vec.asVector2f()) return false; } for (int i = 0; i < number6; i++) { if((receiver+i)->getPosition() == vec.asVector2f()) return false; } this->direction = direction; moveNr = 0; return false; } void Player::movePlayer(Player::Direction direction) { if (!live || moveNr != 10) return; if (direction == Player::Direction::None) return; this->direction = direction; moveNr = 0; } void Player::run(ShootingBlock* block, int number) { if (live && clockStage.getElapsedTime().asSeconds() >= 0.05) { clockStage.restart(); setStage(++stage); } if (clockMove.getElapsedTime().asSeconds() >= 0.06 && moveNr < 10 && live) { clockMove.restart(); switch (direction) { case Direction::Up: move(Vector2f{ 0, -8 }); break; case Direction::Down: move(Vector2f{ 0, 8 }); break; case Direction::Left: move(Vector2f{ -8, 0 }); break; case Direction::Right: move(Vector2f{ 8, 0 }); break; } moveNr++; } else if (!live && moveNr != -1) { if (clockStage.getElapsedTime().asSeconds() >= 0.5) { setTextureRect(IntRect{ 0,0,1,1 }); moveNr = -1; } } if (live) { for (int i = 0; i < number; i++) { ShootingBlock::Type type = (block + i)->getType(); int nr(0); if (type < 4) nr = 1; else if (type < 10 && type > 3) nr = 2; else if (type < 14 && type > 9) nr = 3; else if (type == 14) nr = 4; for (int j = 0; j < nr; j++) { if (((block + i)->getMine() + j)->getExist()) { Vector2f pos = ((block + i)->getMine() + j)->getPosition(); if (pos.x < getPosition().x + 80 && pos.x + 12 > getPosition().x && pos.y < getPosition().y + 80 && pos.y + 12 > getPosition().y) { setLive(false); } } } } } } void Player::draw(RenderWindow& window) { window.draw(*this); } void Player::reset() { live = true; moveNr = 10; clockMove.restart(); direction = Direction::None; setStage(0); } Player::~Player() { delete [] rect; }
fe76d58668884c831e9e416616826f37599bbef2
7dd9a7c5316dc4ae1b9524f214928b9c96c03dc3
/cpp_behavior_tree/BehaviorTree/ParallelNode.h
1fc34074147926805feea45b1f95bc5e72bb33e4
[]
no_license
NVSL/TAZI
035ae70b7fc9d424a47ae79434ff888880c87a6c
ac7887b1491a1c8af7373a42cd7fb81284acc396
refs/heads/master
2021-01-18T09:39:20.984516
2017-04-13T19:14:44
2017-04-13T19:14:44
44,073,629
3
0
null
null
null
null
UTF-8
C++
false
false
384
h
// ParallelNode.h #ifndef _PARALLELNODE_h #define _PARALLELNODE_h #if defined(ARDUINO) && ARDUINO >= 100 #include "arduino.h" #else #include "WProgram.h" #endif #include "InternalNode.h" class ParallelNode: public InternalNode { public: ParallelNode(NodeList children, int numberOfChildren) : InternalNode(children, numberOfChildren) {}; uint8_t tick(); }; #endif
57104aa55b2c478c1a06773efef281b96c72eb27
d878e9d4da44fe031ff734e4e19f08dc51339ac8
/SessionGroup.h
023d73bf35dc4295a06621ddc6c154518373fadd
[]
no_license
cmguo/just-just-dispatch
27910f9b7118b0e3b14dfbb9f6b2f0a33e38de5a
151af58802b0b42390b4f39b220d69c904214246
refs/heads/master
2022-11-24T05:21:39.730457
2017-07-05T10:02:21
2017-07-05T10:02:21
280,885,464
0
0
null
null
null
null
GB18030
C++
false
false
3,751
h
// SessionGroup.h #ifndef _JUST_DISPATCH_SESSION_GROUP_H_ #define _JUST_DISPATCH_SESSION_GROUP_H_ #include "just/dispatch/DispatchBase.h" namespace just { namespace dispatch { class Session; struct Request; class TaskDispatcher; class SessionGroup { public: enum StatusEnum { waiting, openning, openned, working, bufferring, }; public: SessionGroup( framework::string::Url const & url, TaskDispatcher & dispatcher); public: Request * request(); void response( boost::system::error_code const & ec); void close( boost::system::error_code const & ec, std::vector<Session *> & orphans); public: TaskDispatcher & dispatcher() const { return dispatcher_; } public: framework::string::Url const & url() const { return url_; } bool busy() const { return status_ == openning || status_ == working || status_ == bufferring; } bool ready() const { return status_ == openned || status_ == working || status_ == bufferring; } bool empty() const { return current_ == NULL; } Session * first() const { return first_; } Session * current() const { return current_; } Session * next() const { return current_; } public: bool accept( framework::string::Url const & url); /* 排队该会话,可能踢掉前面的会话中的请求 当前影片没有被另一个影片踢掉(正在取消中) 不改变影片状态,可能会改变当前会话和等待会话 下列情形返回值为true 1、需要取消当前会话 2、没有当前会话,需要处理后续请求 */ bool queue_session( Session * ses); bool active_session( Session * ses); /* 下列情形返回值为true 1、当前会话被关闭 */ bool close_session( Session * ses); Session * find_session( size_t id, Session *& main_ses) const; public: static Request * open_request; static Request * switch_request; static Request * buffer_request; static Request * cancel_request; static Request * delete_request; static Session * delete_session; private: framework::string::Url url_; TaskDispatcher & dispatcher_; private: StatusEnum status_; Session * first_; Session * current_; Session * next_; bool buffer_finish_; std::vector<Session *> kick_outs_; }; } // namespace dispatch } // namespace just #endif // _JUST_DISPATCH_SESSION_GROUP_H_
0e535070dd3c333bd470aedb0835234d34be956f
06eb60c98f4d106fc3bb3d0b7e990828b87d714d
/Source/WebCore/accessibility/AccessibilitySVGRoot.cpp
5fd2628577667a12a1a07d236db2acc3b7b019c3
[]
no_license
snyh/dui
9486a81d97ec1173b161b6aef8fcea21066aebff
c4464629f1efdecae792ed3abc2a7fc9ce9b88db
refs/heads/master
2021-01-25T08:28:55.224303
2013-10-23T00:42:02
2013-10-23T00:42:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,385
cpp
/* * Copyright (C) 2012 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "accessibility/AccessibilitySVGRoot.h" #include "rendering/RenderObject.h" namespace WebCore { AccessibilitySVGRoot::AccessibilitySVGRoot(RenderObject* renderer) : AccessibilityRenderObject(renderer) , m_parent(0) { } AccessibilitySVGRoot::~AccessibilitySVGRoot() { } PassRefPtr<AccessibilitySVGRoot> AccessibilitySVGRoot::create(RenderObject* renderer) { return adoptRef(new AccessibilitySVGRoot(renderer)); } AccessibilityObject* AccessibilitySVGRoot::parentObject() const { // If a parent was set because this is a remote SVG resource, use that // but otherwise, we should rely on the standard render tree for the parent. if (m_parent) return m_parent; return AccessibilityRenderObject::parentObject(); } } // namespace WebCore
8b26e87f71d1725b8da0306ec4844541dbeb45ce
8aae83bf0124d35c2c6f2881e61cc9407cb75850
/original/list/linkedlist.hpp
7e93535b756085c6c90517a5848a96eec5a30843
[]
no_license
mjy9088/MTL-CPP
e2a16727b5b2f831bd45e8f3b352c2e3e762c116
2bc974bb0a88f93b5f4f0f1fee63fb85aa6c800e
refs/heads/master
2020-05-01T14:20:28.531476
2019-06-18T14:58:51
2019-06-18T14:58:51
177,517,128
0
0
null
null
null
null
UTF-8
C++
false
false
463
hpp
#ifndef __mtl_list_linkedlist #define __mtl_list_linkedlist #include "../list.hpp" namespace MTL { template<typename T> class LinkedList : public List<T> { private: class Node; size_t len; LinkedList<T>::Node *head, *tail; public: LinkedList(); ~LinkedList(); size_t length(); void set(size_t idx, T value); virtual T get(size_t idx); size_t append(T value); bool iterate(bool (*func)(T &value)); void prepend(T value); }; } #endif
72a7c7454fc642d8c78920f157b86aa453f25366
a2b8419c478e98daffcd08a43c9914d76c330e41
/pna/util/pcap_wrap/c/pna_pcap.c
942e598a9395689b9e57d2c231fc3c849899bb4e
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
pcrowley/OSF
e45077f55e5ab8e136449c51a55bb827042d8091
7c568c4b550dd02e8d14f86c112b6190fa9ccf50
refs/heads/master
2021-01-25T03:27:57.672035
2013-11-04T16:01:50
2013-11-04T16:01:50
3,777,304
3
0
null
null
null
null
UTF-8
C++
false
false
3,752
c
/* * This C file should allow for prototyping potential PNA hooks. * It takes a PCAP file as input, does some preliminary work on a packet * (getting it setup similarly to how it would be passed by the PNA). * The only thing you should need to write is the monitor_hook() function * and any helpers you need associated with it. */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <signal.h> #include <pcap.h> #include <netinet/in.h> #include <netinet/if_ether.h> #include <netinet/ip.h> #include <netinet/udp.h> #include <netinet/tcp.h> #include "pna.h" /* monitor prototypes */ void monitor_init(void); void monitor_hook(struct session_key *, int, struct packet *, unsigned long *); void monitor_release(void); /* local prototypes */ void pna_callback(u_char *, const struct pcap_pkthdr *, const u_char *); void sigint_handler(int); uint pkt_count = 0; /** * Callback for pcap_dispatch, handles a single packet then returns */ void pna_callback(u_char *user, const struct pcap_pkthdr *h, const u_char *bytes) { int i = 0; int len = h->caplen; char *data = (char *)bytes; struct ethhdr *eh; struct iphdr *ih; struct udphdr *uh; struct tcphdr *th; struct session_key key; unsigned int temp; int dir = 0; unsigned long pipe_data = -1; struct packet pkt = { h->caplen, bytes, NULL, NULL, NULL, NULL }; pkt_count += 1; /* we just assume it's Ethernet */ eh = (struct ethhdr *)data; data += sizeof(*eh); pkt.eth_hdr = eh; key.l3_protocol = ntohs(eh->h_proto); if (key.l3_protocol != ETH_P_IP) { return; } /* extract l3 info */ ih = (struct iphdr *)data; data += ((ih->ihl & 0x0f) << 2); pkt.ip_hdr = ih; key.l4_protocol = ih->protocol; key.local_ip = ntohl(ih->saddr); key.remote_ip = ntohl(ih->daddr); /* extract l4 info */ if (ih->protocol == IPPROTO_TCP) { th = (struct tcphdr *)data; data += (th->doff << 2); pkt.tcp_hdr = th; key.local_port = ntohs(th->source); key.remote_port = ntohs(th->dest); } else if (ih->protocol == IPPROTO_UDP) { uh = (struct udphdr *)data; pkt.udp_hdr = uh; data += sizeof(*uh); key.local_port = ntohs(uh->source); key.remote_port = ntohs(uh->dest); } else { return; } pkt.payload = data; /* localize */ temp = key.local_ip & PNA_MASK; if (temp == (PNA_PREFIX & PNA_MASK)) { // local_ip is local, do nothing dir = PNA_DIR_OUTBOUND; } else { // remote_ip is local, swap ips and ports temp = key.local_ip; key.local_ip = key.remote_ip; key.remote_ip = temp; temp = key.local_port; key.local_port = key.remote_port; key.remote_port = temp; dir = PNA_DIR_INBOUND; } monitor_hook(&key, dir, &pkt, &pipe_data); } int go = 1; /** * Ctrl-C handler */ void sigint_handler(int signal) { printf(" detected, shutting down\n"); go = 0; } int main(int argc, char **argv) { char errbuf[PCAP_ERRBUF_SIZE]; pcap_t *pcap; if (argc != 2) { printf("usage: %s <file>\n", argv[0]); exit(1); } char *datafile = argv[1]; if (0 != access(datafile, F_OK)) { printf("file does not exist (%s)\n", datafile); exit(1); } monitor_init(); /* set up PCAP file */ signal(SIGINT, &sigint_handler); pcap = pcap_open_offline(datafile, errbuf); while (go) { if (0 == pcap_dispatch(pcap, 1, &pna_callback, NULL)) { break; } } monitor_release(); printf("Processed %d packets\n", pkt_count); }
[ "root@ubuntu.(none)" ]
root@ubuntu.(none)
fac330a7c105179c50f30f0378e468b8a4214814
d20cd8d62e96ef9200126a8933d6cfc0363c8f7c
/src/category/tasks/encode.cc
36e1c20b098e68d757d784c1ba114f4c7150d072
[ "Apache-2.0" ]
permissive
Pandinosaurus/legate.pandas
565f9783ce8b87b5bc557b4de480af278b7e6eb4
9875e6f22c67c89f6fceed09e5d55d0126db2b70
refs/heads/master
2023-07-19T06:08:23.953705
2021-07-09T00:30:35
2021-07-09T00:30:35
358,820,890
0
0
Apache-2.0
2021-08-08T06:14:49
2021-04-17T08:05:54
C++
UTF-8
C++
false
false
3,273
cc
/* Copyright 2021 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <unordered_map> #include "category/tasks/encode.h" namespace legate { namespace pandas { namespace category { /*static*/ void EncodeTask::cpu_variant(const Legion::Task *task, const std::vector<Legion::PhysicalRegion> &regions, Legion::Context context, Legion::Runtime *runtime) { Deserializer ctx{task, regions}; EncodeTaskArgs args; deserialize(ctx, args); if (args.in.empty()) { args.out.make_empty(); return; } auto dict_size = args.dict.num_elements(); auto dict_offsets = args.dict.child(0).raw_column_read<int32_t>(); auto dict_chars = args.dict.child(1).raw_column_read<int8_t>(); std::unordered_map<std::string, int32_t> dict; dict.reserve(dict_size); for (size_t i = 0; i < dict_size; ++i) { auto lo = dict_offsets[i]; auto hi = dict_offsets[i + 1]; std::string value{&dict_chars[lo], &dict_chars[hi]}; dict[value] = i; } const size_t size = args.in.num_elements(); auto in_offsets = args.in.child(0).raw_column_read<int32_t>(); auto in_chars = args.in.child(1).raw_column_read<int8_t>(); args.out.allocate(size, true); auto out = args.out.child(0).raw_column<uint32_t>(); if (args.in.nullable()) { auto in_b = args.in.read_bitmask(); auto out_b = args.out.bitmask(); for (size_t i = 0; i < size; ++i) if (in_b.get(i)) { auto lo = in_offsets[i]; auto hi = in_offsets[i + 1]; std::string value{&in_chars[lo], &in_chars[hi]}; auto finder = dict.find(value); if (finder != dict.end()) { out[i] = dict[value]; out_b.set(i); } else out_b.set(i, false); } else out_b.set(i, false); } else if (args.out.nullable()) { auto out_b = args.out.bitmask(); for (size_t i = 0; i < size; ++i) { auto lo = in_offsets[i]; auto hi = in_offsets[i + 1]; std::string value{&in_chars[lo], &in_chars[hi]}; auto finder = dict.find(value); if (finder != dict.end()) { out[i] = dict[value]; out_b.set(i); } else out_b.set(i, false); } } else { for (size_t i = 0; i < size; ++i) { auto lo = in_offsets[i]; auto hi = in_offsets[i + 1]; std::string value{&in_chars[lo], &in_chars[hi]}; #ifdef DEBUG_PANDAS assert(dict.find(value) != dict.end()); #endif out[i] = dict[value]; } } } static void __attribute__((constructor)) register_tasks(void) { EncodeTask::register_variants(); } } // namespace category } // namespace pandas } // namespace legate
352aa3bf28f63f6b11b2f4238b0acf637bfd43cf
5aada02ffc285f21e43f84a7e5e38dc3947a283f
/spoj/kamalcode1.cpp
08a65c330dc03cb301ebb70615caff5dfa2d3e76
[]
no_license
Surya00/Codeforces
c372957dee42c850fd6607092f2726cdb080f68b
39fdef655f3e7a474086b542a5ec5a87559d236b
refs/heads/master
2021-01-22T23:21:11.812112
2017-04-09T10:43:40
2017-04-09T10:43:40
85,629,063
0
0
null
null
null
null
UTF-8
C++
false
false
889
cpp
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include<cstring> #include<stdlib.h> #include <bits/stdc++.h> using namespace std; int main() { long long int a,b,n,m ,sum,c,i,p,j,t,r,v,z,k; char C[101]; long long int flag=0; cin>>t; p=0; while(t--){ p=p+1; cin>>C; k=strlen(C); flag=0; c=0; for(i=k-1;i>=0;i--){ if(C[i]=='-'){ flag=1; c=c+1; while(C[i-1]=='-'){ i=i-1; } } if(flag==1 && C[i]=='+'){ c=c+1; while(C[i-1]=='+'){ i=i-1; } } } cout<<"Case #"<<p<<": "<<c<<"\n"; } return 0; }
23324a70b3f55ce92f75fe452f8345e6a5efd9cb
75ded73f89a5d83f2406997e0ad8ac49a46fff4c
/src/qt/signverifymessagedialog.cpp
d8f3925034d15d8119d0192f54ca8b2dfe718071
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
aureus22/aureus-sourcecode
d0be30359efc67ac97b8a398b8da1f3176a8fd78
ea67fa36d5b03a8d112f61026fd329ed21958a9f
refs/heads/master
2021-01-11T08:17:37.749024
2016-12-14T15:20:23
2016-12-14T15:20:23
76,404,906
5
4
null
2016-12-17T17:33:15
2016-12-13T22:47:42
C++
UTF-8
C++
false
false
8,979
cpp
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "signverifymessagedialog.h" #include "ui_signverifymessagedialog.h" #include "addressbookpage.h" #include "base58.h" #include "guiutil.h" #include "init.h" #include "main.h" #include "optionsmodel.h" #include "walletmodel.h" #include "wallet.h" #include <QClipboard> #include <string> #include <vector> SignVerifyMessageDialog::SignVerifyMessageDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SignVerifyMessageDialog), model(0) { ui->setupUi(this); #if (QT_VERSION >= 0x040700) /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->addressIn_SM->setPlaceholderText(tr("Enter a Aureus address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)")); ui->signatureOut_SM->setPlaceholderText(tr("Click \"Sign Message\" to generate signature")); ui->addressIn_VM->setPlaceholderText(tr("Enter a Aureus address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)")); ui->signatureIn_VM->setPlaceholderText(tr("Enter Aureus signature")); #endif GUIUtil::setupAddressWidget(ui->addressIn_SM, this); GUIUtil::setupAddressWidget(ui->addressIn_VM, this); ui->addressIn_SM->installEventFilter(this); ui->messageIn_SM->installEventFilter(this); ui->signatureOut_SM->installEventFilter(this); ui->addressIn_VM->installEventFilter(this); ui->messageIn_VM->installEventFilter(this); ui->signatureIn_VM->installEventFilter(this); ui->signatureOut_SM->setFont(GUIUtil::bitcoinAddressFont()); ui->signatureIn_VM->setFont(GUIUtil::bitcoinAddressFont()); } SignVerifyMessageDialog::~SignVerifyMessageDialog() { delete ui; } void SignVerifyMessageDialog::setModel(WalletModel *model) { this->model = model; } void SignVerifyMessageDialog::setAddress_SM(const QString &address) { ui->addressIn_SM->setText(address); ui->messageIn_SM->setFocus(); } void SignVerifyMessageDialog::setAddress_VM(const QString &address) { ui->addressIn_VM->setText(address); ui->messageIn_VM->setFocus(); } void SignVerifyMessageDialog::showTab_SM(bool fShow) { ui->tabWidget->setCurrentIndex(0); if (fShow) this->show(); } void SignVerifyMessageDialog::showTab_VM(bool fShow) { ui->tabWidget->setCurrentIndex(1); if (fShow) this->show(); } void SignVerifyMessageDialog::on_addressBookButton_SM_clicked() { if (model && model->getAddressTableModel()) { AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::ReceivingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { setAddress_SM(dlg.getReturnValue()); } } } void SignVerifyMessageDialog::on_pasteButton_SM_clicked() { setAddress_SM(QApplication::clipboard()->text()); } void SignVerifyMessageDialog::on_signMessageButton_SM_clicked() { /* Clear old signature to ensure users don't get confused on error with an old signature displayed */ ui->signatureOut_SM->clear(); CBitcoinAddress addr(ui->addressIn_SM->text().toStdString()); if (!addr.IsValid()) { ui->addressIn_SM->setValid(false); ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again.")); return; } CKeyID keyID; if (!addr.GetKeyID(keyID)) { ui->addressIn_SM->setValid(false); ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again.")); return; } WalletModel::UnlockContext ctx(model->requestUnlock()); if (!ctx.isValid()) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("Wallet unlock was cancelled.")); return; } CKey key; if (!pwalletMain->GetKey(keyID, key)) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("Private key for the entered address is not available.")); return; } CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << ui->messageIn_SM->document()->toPlainText().toStdString(); std::vector<unsigned char> vchSig; if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig)) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signing failed.") + QString("</nobr>")); return; } ui->statusLabel_SM->setStyleSheet("QLabel { color: green; }"); ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signed.") + QString("</nobr>")); ui->signatureOut_SM->setText(QString::fromStdString(EncodeBase64(&vchSig[0], vchSig.size()))); } void SignVerifyMessageDialog::on_copySignatureButton_SM_clicked() { QApplication::clipboard()->setText(ui->signatureOut_SM->text()); } void SignVerifyMessageDialog::on_clearButton_SM_clicked() { ui->addressIn_SM->clear(); ui->messageIn_SM->clear(); ui->signatureOut_SM->clear(); ui->statusLabel_SM->clear(); ui->addressIn_SM->setFocus(); } void SignVerifyMessageDialog::on_addressBookButton_VM_clicked() { if (model && model->getAddressTableModel()) { AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { setAddress_VM(dlg.getReturnValue()); } } } void SignVerifyMessageDialog::on_verifyMessageButton_VM_clicked() { CBitcoinAddress addr(ui->addressIn_VM->text().toStdString()); if (!addr.IsValid()) { ui->addressIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again.")); return; } CKeyID keyID; if (!addr.GetKeyID(keyID)) { ui->addressIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again.")); return; } bool fInvalid = false; std::vector<unsigned char> vchSig = DecodeBase64(ui->signatureIn_VM->text().toStdString().c_str(), &fInvalid); if (fInvalid) { ui->signatureIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The signature could not be decoded.") + QString(" ") + tr("Please check the signature and try again.")); return; } CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << ui->messageIn_VM->document()->toPlainText().toStdString(); CPubKey pubkey; if (!pubkey.RecoverCompact(Hash(ss.begin(), ss.end()), vchSig)) { ui->signatureIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The signature did not match the message digest.") + QString(" ") + tr("Please check the signature and try again.")); return; } if (!(CBitcoinAddress(pubkey.GetID()) == addr)) { ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verification failed.") + QString("</nobr>")); return; } ui->statusLabel_VM->setStyleSheet("QLabel { color: green; }"); ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verified.") + QString("</nobr>")); } void SignVerifyMessageDialog::on_clearButton_VM_clicked() { ui->addressIn_VM->clear(); ui->signatureIn_VM->clear(); ui->messageIn_VM->clear(); ui->statusLabel_VM->clear(); ui->addressIn_VM->setFocus(); } bool SignVerifyMessageDialog::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::FocusIn) { if (ui->tabWidget->currentIndex() == 0) { /* Clear status message on focus change */ ui->statusLabel_SM->clear(); /* Select generated signature */ if (object == ui->signatureOut_SM) { ui->signatureOut_SM->selectAll(); return true; } } else if (ui->tabWidget->currentIndex() == 1) { /* Clear status message on focus change */ ui->statusLabel_VM->clear(); } } return QDialog::eventFilter(object, event); }
6e7b8f0dfd421a4767d830c3f52c4af70ee0e59d
f68c1a09ade5d969f3973246747466e4a540ff74
/src/prod/src/data/txnreplicator/logrecordlib/LogHeadRecord.h
67d68326c12142132947496339f6530a0b6ba68b
[ "MIT" ]
permissive
GitTorre/service-fabric
ab38752d4cc7c8f2ee03553372c0f3e05911ff67
88da19dc5ea8edfe1c9abebe25a5c5079995db63
refs/heads/master
2021-04-09T10:57:45.678751
2018-08-20T19:17:28
2018-08-20T19:17:28
125,401,516
0
0
MIT
2018-03-15T17:13:53
2018-03-15T17:13:52
null
UTF-8
C++
false
false
3,877
h
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #pragma once namespace Data { namespace LogRecordLib { // // This log record type has an index back into the current head of the log // It is an abstract type and has valid derived objects // class LogHeadRecord : public PhysicalLogRecord { K_FORCE_SHARED_WITH_INHERITANCE(LogHeadRecord) public: _declspec(property(get = get_indexingLogRecord, put = set_indexingLogRecord)) IndexingLogRecord::SPtr HeadRecord; IndexingLogRecord::SPtr get_indexingLogRecord() const { return logHeadRecord_; } void set_indexingLogRecord(__in IndexingLogRecord & head) { logHeadRecord_ = &head; } _declspec(property(get = get_currentLogHeadEpoch)) TxnReplicator::Epoch & LogHeadEpoch; TxnReplicator::Epoch const & get_currentLogHeadEpoch() const { return logHeadEpoch_; } _declspec(property(get = get_currentLogHeadLsn)) LONG64 LogHeadLsn; LONG64 get_currentLogHeadLsn() const { return logHeadLsn_; } _declspec(property(get = get_currentLogHeadPsn)) LONG64 LogHeadPsn; LONG64 get_currentLogHeadPsn() const { return logHeadPsn_; } __declspec(property(get = get_currentLogHeadRecordOffset)) ULONG64 LogHeadRecordOffset; ULONG64 get_currentLogHeadRecordOffset() const { return logHeadRecordOffset_; } __declspec(property(get = get_currentLogHeadRecordPosition)) ULONG64 LogHeadRecordPosition; ULONG64 get_currentLogHeadRecordPosition() const { return RecordPosition - logHeadRecordOffset_; } virtual bool FreePreviousLinksLowerThanPsn( __in LONG64 newHeadPsn, __in InvalidLogRecords & invalidLogRecords) override; bool Test_Equals(__in LogRecord const & other) const override; protected: // // Used during recovery // LogHeadRecord( __in LogRecordType::Enum recordType, __in ULONG64 recordPosition, __in LONG64 lsn, __in PhysicalLogRecord & invalidPhysicalLogRecord, __in IndexingLogRecord & invalidIndexingLogRecord); LogHeadRecord( __in LogRecordType::Enum recordType, __in IndexingLogRecord & logHeadRecord, __in LONG64 lsn, __in_opt PhysicalLogRecord * const lastLinkedPhysicalRecord, __in PhysicalLogRecord & invalidPhysicalLogRecord); void Read( __in Utilities::BinaryReader & binaryReader, __in bool isPhysicalRead) override; void Write( __in Utilities::BinaryWriter & binaryWriter, __inout Utilities::OperationData & operationData, __in bool isPhysicalWrite) override; private: static const ULONG DiskSpaceUsed; void UpdateApproximateDiskSize(); LONG64 logHeadLsn_; LONG64 logHeadPsn_; ULONG64 logHeadRecordOffset_; TxnReplicator::Epoch logHeadEpoch_; // The following fields are not persisted IndexingLogRecord::SPtr logHeadRecord_; }; } }
66f2d73bf74cccd6469e732e47aed94c39f77230
cec628def1aad94ccbefa814d2a0dbd51588e9bd
/cnd.completion/test/unit/data/org/netbeans/modules/cnd/completion/cplusplus/hyperlink/BasicHyperlinkTestCase/IZ175123.cc
d9825e9560ff801d0ff293af9ca3d92a6da68142
[]
no_license
emilianbold/netbeans-releases
ad6e6e52a896212cb628d4522a4f8ae685d84d90
2fd6dc84c187e3c79a959b3ddb4da1a9703659c7
refs/heads/master
2021-01-12T04:58:24.877580
2017-10-17T14:38:27
2017-10-17T14:38:27
78,269,363
30
15
null
2020-10-13T08:36:08
2017-01-07T09:07:28
null
UTF-8
C++
false
false
126
cc
int IZ175123_main () { if (int const * p = 0) // Parse error: "unable to resolve identifier" { } return (0); }
c6b6ed8e2bd9fe94da238d3ec2bc840599d21c08
de32b4eae6ccfb1b7450de75ea8870aed7131238
/Assignment2/Assignment2Source/SceneWriter.cpp
27fd8faad0f455f2bf1eeecede5fc208f4258fab
[]
no_license
adamtcroft/uwcppadvanced
4e1a2e21f716e2767511b31fe92252b5c20c32bb
52305e224319b0d18ab70f764425c23cbaa6e3aa
refs/heads/master
2020-06-19T22:37:19.505190
2019-12-22T03:37:26
2019-12-22T03:37:26
196,899,367
0
0
null
null
null
null
UTF-8
C++
false
false
1,869
cpp
#include "SceneWriter.h" Xml::HElement Framework::SceneWriter::writeScene(Scene& scene) { Xml::HElement result = std::make_unique<Xml::Element>(); result->setName("Scene"); result->setAttribute("width", std::to_string(scene.getWidth())); result->setAttribute("height", std::to_string(scene.getHeight())); for (auto layerIterator = scene.begin(); layerIterator != scene.end(); layerIterator++) { writeLayers(layerIterator, result); } return result; } void Framework::SceneWriter::writeLayers(LayerIterator iterator, Xml::HElement scene) { Xml::HElement layer = std::make_shared<Xml::Element>(); layer->setName("Layer"); layer->setAttribute("alias", iterator->getAlias()); scene->addChild(layer); for (auto pgIterator = iterator->begin(); pgIterator != iterator->end(); pgIterator++) { writePlacedGraphics(pgIterator, layer); } } void Framework::SceneWriter::writePlacedGraphics(PlacedGraphicIterator iterator, Xml::HElement layer) { Xml::HElement pgChild = std::make_shared<Xml::Element>(); pgChild->setName("PlacedGraphic"); VG::Point p = iterator->getPlacementPoint(); pgChild->setAttribute("x", std::to_string(p.getX())); pgChild->setAttribute("y", std::to_string(p.getY())); layer->addChild(pgChild); Xml::HElement vgChild = std::make_shared<Xml::Element>(); vgChild->setName("VectorGraphic"); VG::HVectorGraphic vg = iterator->getGraphic(); vgChild->setAttribute("closed", (vg->isClosed() == true ? "true" : "false")); pgChild->addChild(vgChild); int count = 0; while (count < vg->getPointCount()) { VG::Point childPoint = vg->getPoint(count); Xml::HElement point = std::make_unique<Xml::Element>(); point->setName("Point"); point->setAttribute("x", std::to_string(childPoint.getX())); point->setAttribute("y", std::to_string(childPoint.getY())); vgChild->addChild(point); count++; } }
3baba597db781de25df56c4098ced78ea69e0ddc
e0f8455f221055c9d677f44b7d28d23e313686dc
/display.cpp
feb5b85056ee5ceeb7980c418bccad540f922c7b
[]
no_license
shigosenCCneko/AVR-PS-2keyboardTinyFMSynth
1e2fce7b0208fdbb496f29b00b57d5405505aaaa
fbf0746f34d33c5e11ffd74a9717b9d8ecdb0858
refs/heads/master
2023-02-24T19:24:57.462086
2021-01-31T13:55:06
2021-01-31T13:55:06
334,621,364
0
0
null
null
null
null
UTF-8
C++
false
false
4,917
cpp
#include <avr/io.h> #include "display.h" #include "FMTONE.h" #include "changeParameter.h" #include <avr/pgmspace.h> int posx[2][8]; int posy[2][8]; const char op1[] PROGMEM = "OP1"; const char op2[] PROGMEM = "OP2"; const char save_text[] PROGMEM = "Save=F2"; const char load_text[] PROGMEM = "Load=F1"; const char mul_mes[] PROGMEM = "ML="; extern FmOperator fm_operator[ ]; void drawOperatorWave(uint8_t no) { signed char *rp = no == 0 ? fm_operator[0].wave_tbl : fm_operator[1].wave_tbl ; int ofs = no == 0 ? 190 : 70; SetColor(BLACK); MoveTo(1, ofs - 29); FillRect(72, 49); SetColor(YELLOW); for (int i = 3; i < 60; i = i + 4) { PlotPoint(i, ofs); } SetColor(GREEN); for (uint8_t x = 0; x < 64; x++) { PlotPoint(x / 2 + 15, (rp[x] >> 1) / 2 + ofs); } } void DispForm() { SetColor(GREEN); drawOperatorWave(0); drawOperatorWave(1); SetColor(BLUE); MoveTo(80, 15); FillRect(158, 80); MoveTo(80, 135); FillRect(158, 80); drawEnvelope(0, WHITE); drawEnvelope(1, WHITE); drawMul(0); drawMul(1); } uint8_t conv_time(uint8_t val) { for (int i = 0; i < 16; i++) { if (val == envelope_cnt[i]) { return envelope_time[i]; } } return 1; } void drawEnvelope(uint8_t no, int color) { int yofs = no == 0 ? 135 : 15; int xofs = 80; int xpos = 80; int x, y; int cnt = 1; const int xdiv = 1; int tlv; signed char *rp = no == 0 ? fm_operator[0].wave_tbl : fm_operator[1].wave_tbl ; FmOperator *op = no == 0 ? &(fm_operator[0]) : &(fm_operator[1]); // SetColor(BLUE); // MoveTo(80,yofs); // FillRect(158,80); SetColor(BLUE); x = posx[no][1]; y = posy[no][1]; MoveTo(x, y); for (int i = 2; i < posx[no][0]; i++) { x = posx[no][i]; y = posy[no][i]; DrawTo(x, y); MoveTo(x, y); } SetColor(color); y = op->tl; tlv = y; /* Atack */ x = conv_time( op->atk); y = y / 4 + yofs; x = x / xdiv + xpos; MoveTo(xpos, yofs); posx[no][cnt] = xpos; posy[no][cnt++] = yofs; posx[no][cnt] = x; posy[no][cnt++] = y; DrawTo(x, y); MoveTo(x, y); xpos = x; /* Decy */ y = (op->sul) * tlv / SUSDIV; x = conv_time( op->decy); if (x != 255) { y = y / 4 + yofs; x = x / xdiv + xpos; posx[no][cnt] = x; posy[no][cnt++] = y; DrawTo(x, y); MoveTo(x, y); xpos = x; /* sus */ y = (op->sul) * op->sul / SUSDIV; x = conv_time( op->sus); if (x != 255) { y = y / 4 + yofs; x = x / xdiv / 2 + xpos; posx[no][cnt] = x; posy[no][cnt++] = y; DrawTo(x, y); MoveTo(x, y); xpos = x; /* release */ x = conv_time( op->rel); x = x / xdiv + xpos; y = yofs; posx[no][cnt] = x; posy[no][cnt++] = y; DrawTo(x, y); } else { //y = op->sul; y = (op->sul) * op->tl / SUSDIV; y = y / 4 + yofs; x = 50 + xpos; posx[no][cnt] = x; posy[no][cnt++] = y; DrawTo(x, y); MoveTo(x, y); xpos = x; x = conv_time( op->rel); x = x / xdiv * 2 + xpos; y = yofs; posx[no][cnt] = x; posy[no][cnt++] = y; DrawTo(x, y); } } else { /* attack to release*/ y = op->tl; y = y / 4 + yofs; x = 80 + xpos; posx[no][cnt] = x; posy[no][cnt++] = y; DrawTo(x, y); MoveTo(x, y); xpos = x; x = conv_time( op->rel); x = x / xdiv * 4 + xpos; y = yofs; posx[no][cnt] = x; posy[no][cnt++] = y; DrawTo(x, y); } posx[no][0] = cnt; } void selectOp(uint8_t no) { int color1, color2; color1 = no == 0 ? WHITE : GRAY; color2 = no == 1 ? WHITE : GRAY; SetColor(color2); MoveTo(0, 0); DrawTo(239, 0); DrawTo(239, 119); MoveTo(239, 0); DrawTo(239, 119); MoveTo(0, 0); DrawTo(0, 119); SetColor(color1); MoveTo(0, 120); DrawTo(0, 239); DrawTo(239, 239); //MoveTo(239,239); DrawTo(239, 120); SetColor(WHITE); MoveTo(0, 120); DrawTo(239, 120); SetColor(color1); MoveTo(4, 222); PlotText(op1); SetColor(color2); MoveTo(4, 102); PlotText(op2); } void drawMul(uint8_t no){ uint8_t mul = no == 0 ? fm_operator[0].mul : fm_operator[1].mul; uint8_t yofs = no == 0? 130:10; char c; MoveTo(5,yofs); SetColor(GRAY); PlotText(mul_mes); if(mul >= 10){ c ='1'; mul -= 10; }else{ c = ' '; } MoveTo(40,yofs); PlotChar(c); MoveTo(52,yofs); PlotChar('0'+mul); } //----------------------------------------------------------------- void disp_savemode(){ SetColor(WHITE); MoveTo(20,150); PlotText(save_text); MoveTo(20,100); PlotText(load_text); } const char saveEnd[] PROGMEM = "save"; const char loadEnd[] PROGMEM = "load"; void disp_saved(){ SetColor(WHITE); MoveTo(20,60); PlotText(saveEnd); } void disp_loaded(){ SetColor(WHITE); MoveTo(20,60); PlotText(loadEnd); }
[ "Keiji Katahira" ]
Keiji Katahira
1e51e339193d4de498fd8d347fe028c41e9425c9
12b43e22449cce87dcc506f094837797d0d9cda4
/Battleship_V5/Model.cpp
4733d41b99a2d7b0fab53cc8367e1841fffa6024
[]
no_license
ennbelle/CSC17B_Battleship_Group1
b0424848aa040c9fba172e4e0b64c79d8289a638
9e3b33c08a9777db7cf4b5a06402265eb26ca9b1
refs/heads/main
2023-08-21T11:30:26.317830
2021-10-31T20:58:03
2021-10-31T20:58:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
139
cpp
#include "Model.h" Model::Model(){ playerNum = 0; } PlayerData Model::returnPlayerData(int playerNum){ return player[playerNum]; }
abee55b78a568738daaa603fc6be335031ff7aca
19eb97436a3be9642517ea9c4095fe337fd58a00
/private/shell/ext/intern/util.cpp
8f5c949fcf8adc83f2fe152869ccbead4343f342
[]
no_license
oturan-boga/Windows2000
7d258fd0f42a225c2be72f2b762d799bd488de58
8b449d6659840b6ba19465100d21ca07a0e07236
refs/heads/main
2023-04-09T23:13:21.992398
2021-04-22T11:46:21
2021-04-22T11:46:21
360,495,781
2
0
null
null
null
null
UTF-8
C++
false
false
557
cpp
/***************************************************************************** * * util.cpp - Shared stuff that operates on all classes * *****************************************************************************/ #include "priv.h" #include "util.h" HINSTANCE g_hinst; /* My instance handle */ #ifndef UNICODE BSTR AllocBStrFromString(LPTSTR psz) { OLECHAR wsz[INFOTIPSIZE]; // assumes INFOTIPSIZE number of chars max SHAnsiToUnicode(psz, wsz, ARRAYSIZE(wsz)); return SysAllocString(wsz); } #endif
886f817a1a466da8b48eb78725782da531e3d923
562f3894559a2d49c162ab576477d6c6bbb6e325
/CS232_P2_Atkins/driver.cpp
20177499dbbc2316f4a1750ee045e89569560c26
[]
no_license
atkinsja/Graph_Part2
de1ffa2ed93dae276acbe9a102f90563f8a91abd
020e9c38db5ab7a9f0b976ea6d125a7aa5ac92bb
refs/heads/master
2023-01-24T16:26:08.645624
2020-12-16T21:34:19
2020-12-16T21:34:19
322,107,457
0
0
null
null
null
null
UTF-8
C++
false
false
22,230
cpp
/************************************************************************************************** * * File name : driver.cpp * * Programmer: Jeremy Atkins * * Driver file initializing a Maze object and setting up a menu allowing the user to manipulate * the graph by adding and removing vertices and edges, as well as printing the graph either * simply, breadth first, or depth first. Also includes the ability to find the shortest * path between two nodes using Dijkstra's algorithm, as well as functions to find the * minimum spanning tree using Prim's algorithm and the shortest paths from a source * to all other vertices using Ford's algorithm to handle negative edge weights. * * Date Written: in the past * * Date Last Revised: 4/8/2019 ****************************************************************************************************/ #include <iostream> #include <string> #include "graph.h" using namespace std; int main() { int choice; //menu option int subChoice; double distance; //shortest path //main graph Graph<vertex<string, int>, edgeRep<string, int>> graph; //vertices and the edge passed to the graph by the user vertex<string, int> firstVertex; vertex<string, int> secondVertex; edgeRep<string, int> edge; //start main menu do-while do { //menu options cout << "Graph Options." << endl; cout << "1. Read a graph from a file." << endl; cout << "2. Print the graph." << endl; cout << "3. Test if a vertex is in the graph." << endl; cout << "4. Test if an edge is in the graph." << endl; cout << "5. Add a vertex." << endl; cout << "6. Add an edge." << endl; cout << "7. Delete a vertex." << endl; cout << "8. Delete an edge." << endl; cout << "9. Traverse the graph." << endl; cout << "10. Find the shortest path between two vertices." << endl; cout << "11. Find the minimum spanning tree of the graph." << endl; cout << "12. Exit." << endl; //user input cout << "Enter the number of the option to select: "; cin >> choice; //menu validation while (cin.fail() || cin.peek() != '\n') { cin.clear(); cin.ignore(200, '\n'); cout << "\n\nIncorrect input.\nPlease enter an valid option number: " << endl; cin >> choice; } //start main menu switch switch (choice) { //get graph from file case 1: graph.GetGraph(); cout << "\n\n" << endl; break; //end main menu case 1 getting the graph //print the vertices and edges of the graph case 2: graph.SimplePrintGraph(); cout << "\n\n" << endl; break; //end main menu case 2 printing the graph //test if a vertex is in the graph case 3: //vertex to test cout << "\nEnter the name of the vertex to test (-1 to cancel): "; cin >> firstVertex.name; //allow for returning to main menu if (firstVertex.name == "-1") { cout << "\n\n" << endl; break; } //if the vertex is in the graph if (graph.isVertex(firstVertex) != -1) cout << firstVertex.name << " is in the graph.\n\n" << endl; //if the vertex is not in the graph else cout << firstVertex.name << " is not in the graph.\n\n" << endl; break; //end main menu case 3 testing a vertex //test if an edge is in the graph case 4: //start sub menu for edges do { //sub menu options cout << "\nTesting if an edge is in the graph." << endl; cout << "1. Unidirectional Edge." << endl; cout << "2. Bidirectional Edge." << endl; cout << "3. Return" << endl; //sub menu selection cout << "Enter the number of the option to select: "; cin >> subChoice; //menu validation while (cin.fail() || cin.peek() != '\n') { cin.clear(); cin.ignore(200, '\n'); cout << "\n\nIncorrect input.\nPlease enter an valid option number: " << endl; cin >> subChoice; } //start sub menu switch switch (subChoice) { //test if an edge is unidirectional case 1: cout << "\nEnter the names of the two vertices to determine if a unidirectional edge exists between them. (-1 to cancel):" << endl; cout << "Vertex 1: "; cin >> firstVertex.name; //first vertex entered is not in the graph if (firstVertex.name == "-1") { cout << "\n\n" << endl; break; } //allow for returning to menu if (graph.isVertex(firstVertex) == -1) { cout << firstVertex.name << " is not in the graph.\n\n" << endl; break; } cout << "Vertex 2: "; cin >> secondVertex.name; //allow for returning to menu if (secondVertex.name == "-1") { cout << "\n\n" << endl; break; } //second vertex entered is not in the graph if (graph.isVertex(secondVertex) == -1) { cout << secondVertex.name << " is not in the graph.\n\n" << endl; break; } //unidirectional edge exists between vertices if (graph.isUniEdge(firstVertex, secondVertex) == 1) cout << "\n\nA unidirectional edge exists between " << firstVertex.name << " and " << secondVertex.name << endl; //unidirectional edge does not exist between vertices else cout << "\n\nNo unidirectional edge exists between " << firstVertex.name << " and " << secondVertex.name << endl; cout << "\n\n" << endl; break; //end sub menu case 1 test unidirectional edge //test if an edge is bidirectional case 2: cout << "\nEnter the names of the two vertices to determine if a bidirectional exists between them. (-1 to cancel):" << endl; cout << "Vertex 1: "; cin >> firstVertex.name; //allow for returning to menu if (firstVertex.name == "-1") { cout << "\n\n" << endl; break; } //first vertex entered is not in the graph if (graph.isVertex(firstVertex) == -1) { cout << firstVertex.name << " is not in the graph.\n\n" << endl; break; } cout << "Vertex 2: "; cin >> secondVertex.name; //allow for returning to menu if (secondVertex.name == "-1") { cout << "\n\n" << endl; break; } //second vertex entered is not in the graph if (graph.isVertex(secondVertex) == -1) { cout << secondVertex.name << " is not in the graph.\n\n" << endl; break; } //bidirectional edge exists between vertices if (graph.isBiDirEdge(firstVertex, secondVertex) == 1) cout << "\n\nA bidirectional edge exists between " << firstVertex.name << " and " << secondVertex.name << endl; //bidirectional edge does not exist between vertices else cout << "\n\nNo bidirectional edge exists between " << firstVertex.name << " and " << secondVertex.name << endl; cout << "\n\n" << endl; break; //end sub menu case 2 test bidirectional edge //return to main menu case 3: cout << "\n\n"; break; //end sub menu case 3 //invalid sub menu option default: cout << "Invalid selection. Please enter a valid option." << endl; } //end sub menu switch } while (subChoice != 3); //end sub menu do-while break; //end main menu case 4 testing an edge //add a vertex to the graph case 5: //vertex to add cout << "Enter the name of the vertex to add (-1 to cancel): "; cin >> firstVertex.name; //allow for returning to the menu if (firstVertex.name == "-1") { cout << "\n\n" << endl; break; } //add the vertex to the graph if (graph.AddVertex(firstVertex) == 0) cout << firstVertex.name << " added to the graph." << endl; cout << "\n\n" << endl; break; //end main menu case 5 adding a vertex //add an edge to the graph case 6: //start sub menu do-while do { //sub menu options cout << "\nAdding an edge to the graph." << endl; cout << "1. Add a unidirectional edge." << endl; cout << "2. Add a bidirectional edge." << endl; cout << "3. Return." << endl; //sub menu selection cout << "Enter the number of the option to select: "; cin >> subChoice; //sub menu validation while (cin.fail() || cin.peek() != '\n') { cin.clear(); cin.ignore(200, '\n'); cout << "\n\nIncorrect input.\nPlease enter an valid option number: " << endl; cin >> subChoice; } //start sub menu switch switch (subChoice) { //add a unidirectional edge to the graph case 1: cout << "Enter the names of the two vertices to add a unidirectional edge between. (-1 to cancel)" << endl; //vertex to start the edge from cout << "Starting vertex: "; cin >> firstVertex.name; //allow for returning to menu if (firstVertex.name == "-1") { cout << "\n\n" << endl; break; } //vertex to end the edge at cout << "Ending vertex: "; cin >> secondVertex.name; //allow for returning to menu if (secondVertex.name == "-1") { cout << "\n\n" << endl; break; } //distance between the vertices or the weight of the edge cout << "Enter the distance between the two vertices: "; edge.name = firstVertex.name; cin >> edge.weight; //add the edge if (graph.AddUniEdge(firstVertex, secondVertex, edge) == 1) cout << "\n\nUnidirectional edge added between " << firstVertex.name << " and " << secondVertex.name << endl; cout << "\n\n" << endl; break; //end sub menu case 1 adding a unidirectional edge //add a bidirectional edge to the graph case 2: cout << "Enter the names of the two vertices to add a bidirectional edge between. (-1 to cancel):" << endl; //first vertex to add the edge between cout << "Vertex 1: "; cin >> firstVertex.name; //allow returning to the menu if (firstVertex.name == "-1") { cout << "\n\n" << endl; break; } //second vertex to add the edge between cout << "Vertex 2: "; cin >> secondVertex.name; //allow returning to the menu if (secondVertex.name == "-1") { cout << "\n\n" << endl; break; } //distance between the vertices or the weight of the edge cout << "Enter the distance between the two vertices: "; edge.name = firstVertex.name; cin >> edge.weight; //add the edge graph.AddBiDirEdge(firstVertex, secondVertex, edge); cout << "\n\nBidirectional edge added between " << firstVertex.name << " and " << secondVertex.name << endl; cout << "\n\n" << endl; break; //end sub menu case 2 adding a bidirectional edge //return to the main menu case 3: cout << "\n\n"; break; //end sub menu case 3 //invalid sub menu option default: cout << "Invalid selection. Please enter a valid option." << endl; break; } } while (subChoice != 3); //end sub menu do-while break; //end main menu case 6 adding an edge //delete a vertex case 7: //vertex to delete cout << "Enter the name of the vertex to delete (-1 to cancel): "; cin >> firstVertex.name; //allow for returning to the main menu if (firstVertex.name == "-1") { cout << "\n\n" << endl; break; } //if the vertex is not in the graph, return to sub menu if (graph.isVertex(firstVertex) == -1) { cout << firstVertex.name << " is not in the graph.\n\n" << endl; break; } //delete the vertex if (graph.DeleteVertex(firstVertex) == 0) cout << "\n\n" << firstVertex.name << " deleted." << endl; cout << "\n\n" << endl; break; //end main menu case 7 deleting a vertex //delete an edge case 8: do { //sub menu options cout << "\nDeleting an edge from the graph." << endl; cout << "1. Delete a unidirectional edge." << endl; cout << "2. Delete a bidirectional edge." << endl; cout << "3. Return." << endl; //sub menu selection cout << "Enter the number of the option to select: "; cin >> subChoice; //sub menu validation while (cin.fail() || cin.peek() != '\n') { cin.clear(); cin.ignore(200, '\n'); cout << "\n\nIncorrect input.\nPlease enter an valid option number: " << endl; cin >> subChoice; } //start sub menu switch switch (subChoice) { //delete a unidirectional edge case 1: //the starting vertex of the edge to delete cout << "Enter the names of the two vertices to delete a unidirectional edge between. (-1 to cancel):" << endl; cout << "Vertex 1: "; cin >> firstVertex.name; //allow for returning to sub menu if (firstVertex.name == "-1") { cout << "\n\n" << endl; break; } //if the vertex is not in the graph, return to sub menu if (graph.isVertex(firstVertex) == -1) { cout << firstVertex.name << " is not in the graph.\n\n" << endl; break; } //the ending vertex of the edge to delete cout << "Vertex 2: "; cin >> secondVertex.name; //allow for returning to sub menu if (secondVertex.name == "-1") { cout << "\n\n" << endl; break; } //if the vertex is not in the graph, return to sub menu if (graph.isVertex(secondVertex) == -1) { cout << secondVertex.name << " is not in the graph.\n\n" << endl; break; } //delete the edge if (graph.DeleteUniEdge(firstVertex, secondVertex) == 1) cout << "\n\nEdge deleted between " << firstVertex.name << " and " << secondVertex.name << endl; break; //end sub menu case 1 deleting a unidirectional edge //delete a bidirectional edge case 2: //the starting vertex of the edge to delete cout << "Enter the names of the two vertices to delete a bidirectional edge between. (-1 to cancel):" << endl; cout << "Vertex 1: "; cin >> firstVertex.name; //allow for returning to sub menu if (firstVertex.name == "-1") { cout << "\n\n" << endl; break; } //if the vertex is not in the graph, return to sub menu if (graph.isVertex(firstVertex) == -1) { cout << firstVertex.name << " is not in the graph.\n\n" << endl; break; } //the ending vertex of the edge to delete cout << "Vertex 2: "; cin >> secondVertex.name; //allow for returning to the sub menu if (secondVertex.name == "-1") { cout << "\n\n" << endl; break; } //if the vertex is not in the graph, return to the sub menu if (graph.isVertex(secondVertex) == -1) { cout << secondVertex.name << " is not in the graph.\n\n" << endl; break; } //delete the edge if (graph.DeleteBiDirEdge(firstVertex, secondVertex) == 1) cout << "\n\nEdge deleted between " << firstVertex.name << " and " << secondVertex.name << endl; cout << "\n\n" << endl; break; //end sub menu case 2 deleting a bidirectional edge //return to the main menu case 3: cout << "\n\n"; break; //invalid sub menu option default: cout << "Invalid selection. Please enter a valid option." << endl; break; } } while (subChoice != 3); //end sub menu do-while break; //end main menu case 8 deleting an edge //graph traversals case 9: //start sub menu do-while do { //traversal options cout << "\nTraversing the graph" << endl; cout << "1. Breadth First Traversal." << endl; cout << "2. Depth First Traversal." << endl; cout << "3. Return." << endl; //traversal selection cout << "Enter the number of the option to select: "; cin >> subChoice; //sub menu validation while (cin.fail() || cin.peek() != '\n') { cin.clear(); cin.ignore(200, '\n'); cout << "\n\nIncorrect input.\nPlease enter an valid option number: " << endl; cin >> subChoice; } //start sub menu switch switch (subChoice) { //breadth first traversal case 1: //the vertex to start the traversal at cout << "Breadth first traversal:" << endl; cout << "Enter the name of the vertex to start at (-1 to cancel): "; cin >> firstVertex.name; //allow for returning to the sub menu if (firstVertex.name == "-1") { cout << "\n\n" << endl; break; } //if the vertex is not in the graph, return to the sub menu if (graph.isVertex(firstVertex) == -1) { cout << firstVertex.name << " is not in the graph.\n\n" << endl; break; } //perform the breadth first traversal cout << "\n\nThe Breadth First Traversal of the graph is: " << endl; graph.BFTraversal(firstVertex); cout << "\n\n" << endl; break; //end sub menu case 1 breadth first traversal //depth first traversal case 2: //the vertex to start the traversal at cout << "Depth first traversal:" << endl; cout << "Enter the name of the vertex to start at (-1 to cancel): "; cin >> firstVertex.name; //allow for returning to the sub menu if (firstVertex.name == "-1") { cout << "\n\n" << endl; break; } //if the vertex is not in the graph, return to the sub menu if (graph.isVertex(firstVertex) == -1) { cout << firstVertex.name << " is not in the graph.\n\n" << endl; break; } //perform the depth first traversal cout << "\n\nThe Depth First Traveral of the graph is: " << endl; graph.DFTraversal(firstVertex); cout << "\n\n" << endl; break; //end sub menu case 2 depth first traversal //return to the main menu case 3: cout << "\n\n"; break; //invalid sub menu option default: cout << "Invalid selection. Please enter a valid option." << endl; break; } } while (subChoice != 3); //end traversal do-while break; //end main menu case 9 traversals //shortest path algorithms case 10: //start sub menu do-while do { //shortest path options cout << "\nFinding the shortest path between two vertices in the graph." << endl; cout << "1. Using Dijkstra's Algorithm. (May not work for negative edge weights)" << endl; cout << "2. Using Ford's Algorithm." << endl; cout << "3. Return." << endl; //shortest path algorithm selection cout << "Enter the number of the option to select: "; cin >> subChoice; //sub menu validation while (cin.fail() || cin.peek() != '\n') { cin.clear(); cin.ignore(200, '\n'); cout << "\n\nIncorrect input.\nPlease enter an valid option number: " << endl; cin >> subChoice; } //start sub menu switch switch (subChoice) { //Dijkstra's algorithm case 1: //the starting vertex cout << "Enter the names of the two vertices to find the shortest path between them. (-1 to cancel)"; cout << "\nVertex 1: "; cin >> firstVertex.name; //allow for returning to the sub menu if (firstVertex.name == "-1") { cout << "\n\n" << endl; break; } //if the vertex is not in the graph, return to the sub menu if (graph.isVertex(firstVertex) == -1) { cout << firstVertex.name << " is not in the graph.\n\n" << endl; break; } //the ending vertex cout << "Vertex 2: "; cin >> secondVertex.name; //allow for returning to the sub menu if (secondVertex.name == "-1") { cout << "\n\n" << endl; break; } //if the vertex is not in the graph, return to the sub menu if (graph.isVertex(secondVertex) == -1) { cout << secondVertex.name << " is not in the graph.\n\n" << endl; break; } //find the shortest path between the starting vertex and the ending vertex distance = graph.ShortestDistance(firstVertex, secondVertex); //if the distance is not -1, a path exists //print the path if (distance != -1) cout << "\n\nThe shortest distance between " << firstVertex.name << " and " << secondVertex.name << " is " << distance << "\n\n" << endl; //a path does not exist else cout << "\n\nThe shortest distance between " << firstVertex.name << " and " << secondVertex.name << " is nonexistant.\n\n" << endl; break; //end Dijkstra's algorithm //Ford's algorithm case 2: //the starting vertex cout << "Enter the names of the two vertices to find the shortest path between them. (-1 to cancel)"; cout << "\nVertex 1: "; cin >> firstVertex.name; //allow for returning to the sub menu if (firstVertex.name == "-1") { cout << "\n\n" << endl; break; } //if the vertex is not in the graph, return to the sub menu if (graph.isVertex(firstVertex) == -1) { cout << firstVertex.name << " is not in the graph.\n\n" << endl; break; } //find all of the shortest paths graph.FordShortestPath(firstVertex); break; //end Ford's algorithm //return to the main menu case 3: cout << "\n\n"; break; //invalid sub menu selection default: cout << "Invalid selection. Please enter a valid option." << endl; break; } } while (subChoice != 3); //end shortest path sub menu do-while break; //end main menu case 10 shortest paths //minimum spanning tree algorithm case 11: //starting vertex cout << "Enter the name of the starting vertex to find the minimum spanning tree from. (-1 to cancel): " << endl; cin >> firstVertex.name; //allow for returning to the main menu if (firstVertex.name == "-1") { cout << "\n\n" << endl; break; } //if the vertex is not in the graph, return to the main menu if (graph.isVertex(firstVertex) == -1) { cout << firstVertex.name << " is not in the graph.\n\n" << endl; break; } //find the minimum spanning tree using Prim's algorithm graph.MST(firstVertex); break; //end main menu case 11 minimum spanning tree //exit the program case 12: cout << "Exitting." << endl; break; //invalid main menu option default: cout << "\n\nPlease enter a valid option number: " << endl; break; } } while (choice != 12); //end main menu do-while return 0; }
508350c40f7faf779c3f663c0cbcd66a87f44773
578057387314e1796fb3b16cb95b71f7a23410d6
/tests/unittests/lit_cases/test_popart/test_sce_none_log_prob_popart.cc
2181ac19508a7074995204ec0e4509a6c2d76479
[ "Apache-2.0" ]
permissive
alibaba/heterogeneity-aware-lowering-and-optimization
986b417eb8e4d229fc8cc6e77bb4eff5c6fa654d
966d4aa8f72f42557df58a4f56a7d44b88068e80
refs/heads/master
2023-08-28T22:15:13.439329
2023-01-06T00:39:07
2023-01-06T07:26:38
289,420,807
256
94
Apache-2.0
2023-06-13T10:38:25
2020-08-22T04:45:46
C++
UTF-8
C++
false
false
2,201
cc
//===-test_sce_none_log_prob_popart.cc-----------------------------------------------------------===// // // Copyright (C) 2019-2020 Alibaba Group Holding Limited. // // 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. // ============================================================================= // clang-format off // Testing CXX Code Gen using ODLA API on popart // RUN: %halo_compiler -target cxx -o %data_path/test_sce_none_log_prob/test_data_set_0/input_0.cc -x onnx -emit-data-as-c %data_path/test_sce_none_log_prob/test_data_set_0/input_0.pb // RUN: %halo_compiler -target cxx -o %data_path/test_sce_none_log_prob/test_data_set_0/output_0.cc -x onnx -emit-data-as-c %data_path/test_sce_none_log_prob/test_data_set_0/output_0.pb // RUN: %halo_compiler -target cxx -o %data_path/test_sce_none_log_prob/test_data_set_0/output_1.cc -x onnx -emit-data-as-c %data_path/test_sce_none_log_prob/test_data_set_0/output_1.pb // RUN: %halo_compiler -target cxx -o %data_path/test_sce_none_log_prob/test_data_set_0/input_1.cc -x onnx -emit-data-as-c %data_path/test_sce_none_log_prob/test_data_set_0/input_1.pb // RUN: %halo_compiler -target cxx -batch-size 1 %halo_compile_flags %data_path/test_sce_none_log_prob/model.onnx -o %t.cc // RUN: %cxx -c -fPIC -o %t.o %t.cc -I%odla_path/include // RUN: %cxx -g %s %t.o %t.bin -I%T -I%odla_path/include -I%unittests_path -I%data_path/test_sce_none_log_prob/test_data_set_0 %odla_link %device_link -lodla_popart -o %t_popart.exe -Wno-deprecated-declarations // RUN: %t_popart.exe 0.0001 0 popart %data_path/test_sce_none_log_prob | FileCheck %s // CHECK: Result Pass // clang-format on // XFAIL: * #include "test_sce_none_log_prob_popart.cc.tmp.main.cc.in"