blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
0907cbf57607e673534aa6b145879da50b16f732
954d4ab5ebff02b681ca8ca398bfe2772a88e563
/ACorePoly/PolyLib/SegmentSolver.cpp
f9e6426ad0881f3eb92b4e077d568a41e2dc8df9
[]
no_license
aaalex88/ACorePoly
ba812f935274da698143ca222384074d8d6282a8
62e88bc377066529c3c35d5f3b51da1f1730e596
refs/heads/master
2021-01-22T03:39:29.570496
2016-03-21T15:43:15
2016-03-21T15:43:15
25,196,817
0
0
null
null
null
null
UTF-8
C++
false
false
1,032
cpp
SegmentSolver.cpp
#include <stdafx.h> #include "SegmentSolver.h" namespace ACorePolyLib { SegmentSolver::SegmentSolver(const SegmentOptParams & params, const SignalDescription & desc) { m_desc.desc = desc; m_desc.cores.resize(params.param.size()); for (size_t i = 0; i < params.param.size(); ++i) { m_solvers.push_back( shared_ptr<ACoreSolver>( new ACoreSolver(m_desc.cores[i], params.param[i], desc) ) ); } } SegmentSolver::~SegmentSolver() { } int SegmentSolver::GetDim() const { int res = 0; for (size_t i = 0; i < m_solvers.size(); ++i) { res += m_solvers[i]->GetDim(); } return res; } void SegmentSolver::FillBasis(int N, double * basis) const { for (size_t i = 0; i < m_solvers.size(); ++i) { m_solvers[i]->FillBasis(N, basis); basis += N * m_solvers[i]->GetDim(); } } SegmentDescription & SegmentSolver::ReadResult(double * res) { for (size_t i = 0; i < m_solvers.size(); ++i) { m_solvers[i]->ReadResults(res); res += m_solvers[i]->GetDim(); } return m_desc; } }
4d5723aa517db69082eecd87c7659f342706fbea
47fc025917d53c0a05dcf2dd6f03685f31c28d7e
/CPP-Pool/D13/ex02/Woody.cpp
6772df8e1d6d5d13eac1ba928dbf71abb5006f0a
[]
no_license
PilowEpi/Tek2Project
05a266874c1767c6b26fd1ccfead8f525df64f99
781a01632d0d18ebdd9e7b56bac25c45aa4f6b29
refs/heads/main
2023-08-11T19:32:40.942625
2021-09-11T13:28:09
2021-09-11T13:28:09
405,377,729
0
0
null
null
null
null
UTF-8
C++
false
false
222
cpp
Woody.cpp
/* ** EPITECH PROJECT, 2020 ** CPOOL D13 ** File description: ** CPOOL D13 */ #include "Woody.hpp" #include "Toy.hpp" Woody::Woody(const std::string &name, const std::string &ascii) : Toy(Toy::WOODY, name, ascii) { }
15346739c7cb8ba49502c7723890c3869bff208b
de98f880e307627d5ce93dcad1397bd4813751dd
/3libs/ut/include/OXPropertyDescriptionPane.h
2d083ae55bbce498bcc0ae96a1615e1b9d7e7dfc
[]
no_license
weimingtom/sls
7d44391bc0c6ae66f83ddcb6381db9ae97ee0dd8
d0d1de9c05ecf8bb6e4eda8a260c7a2f711615dd
refs/heads/master
2021-01-10T22:20:55.638757
2011-03-19T06:23:49
2011-03-19T06:23:49
44,464,621
2
0
null
null
null
null
UTF-8
C++
false
false
1,493
h
OXPropertyDescriptionPane.h
#if !defined(AFX_OXPROPERTYDESCRIPTIONPANE_H__D6507A74_8D1F_48BB_B820_099366191D16__INCLUDED_) #define AFX_OXPROPERTYDESCRIPTIONPANE_H__D6507A74_8D1F_48BB_B820_099366191D16__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // OXPropertyDescriptionPane.h : header file // #include "OXDllExt.h" // Version: 9.3 ///////////////////////////////////////////////////////////////////////////// // COXPropertyDescriptionPane window class OX_CLASS_DECL COXPropertyDescriptionPane : public CWnd { // Construction public: COXPropertyDescriptionPane(); // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(COXPropertyDescriptionPane) //}}AFX_VIRTUAL // Implementation public: void SetDescription(LPCTSTR lpszProperty, LPCTSTR lpszDescription); virtual ~COXPropertyDescriptionPane(); // Generated message map functions protected: CFont m_fontProperty; CFont m_fontDescription; CString m_strDescription; CString m_strProperty; //{{AFX_MSG(COXPropertyDescriptionPane) afx_msg void OnPaint(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_OXPROPERTYDESCRIPTIONPANE_H__D6507A74_8D1F_48BB_B820_099366191D16__INCLUDED_)
a40110fe699ace08a4c8a3c14207dfe5cf43981d
d6a4115db819adee535d74febd4f9e12f8ba4e69
/deegen/deegen_stencil_fixup_cross_reference_helper.cpp
991c0a5a9d882175bda532b9863d1505a11583b9
[ "Apache-2.0" ]
permissive
luajit-remake/luajit-remake
292c174be79034bffea77000debd4535c68d78bc
443b6cd442d3e471add261263297e3490b207b0e
refs/heads/master
2023-06-15T13:13:49.561304
2023-06-08T04:55:18
2023-06-08T06:59:03
496,533,267
910
25
null
2022-11-27T07:36:17
2022-05-26T08:04:39
C++
UTF-8
C++
false
false
3,850
cpp
deegen_stencil_fixup_cross_reference_helper.cpp
#include "deegen_stencil_fixup_cross_reference_helper.h" namespace dast { void DeegenStencilFixupCrossRefHelper::RunOnFunction(llvm::Function* mainFn, llvm::GlobalValue* gvToReplace, llvm::Instruction* replacementValue) { using namespace llvm; ReleaseAssert(llvm_value_has_type<void*>(replacementValue)); // Figure out all ConstantExpr users that uses 'gvToReplace' // std::unordered_set<Constant*> cstUsers; cstUsers.insert(gvToReplace); { std::queue<Constant*> worklist; worklist.push(gvToReplace); while (!worklist.empty()) { Constant* cst = worklist.front(); worklist.pop(); for (User* u : cst->users()) { if (isa<Constant>(u)) { if (isa<ConstantExpr>(u)) { ConstantExpr* ce = cast<ConstantExpr>(u); if (!cstUsers.count(ce)) { cstUsers.insert(ce); worklist.push(ce); } } else { // This shouldn't happen for our module.. // fprintf(stderr, "[ERROR] Unexpected non-ConstantExpr use of constant, a bug?\n"); cst->dump(); mainFn->getParent()->dump(); abort(); } } } } } // Replace every use of constant in 'cstUsers' // std::unordered_map<Constant*, Instruction*> replacementMap; replacementMap[gvToReplace] = replacementValue; std::function<Instruction*(Constant*, Instruction*)> handleConstant = [&](Constant* cst, Instruction* insertBefore) WARN_UNUSED -> Instruction* { if (replacementMap.count(cst)) { Instruction* inst = replacementMap[cst]; ReleaseAssert(inst != nullptr); return inst; } ReleaseAssert(isa<ConstantExpr>(cst)); ConstantExpr* ce = cast<ConstantExpr>(cst); Instruction* inst = ce->getAsInstruction(insertBefore); ReleaseAssert(inst != nullptr); // Expanding ConstantExpr should never result in cycle. Fire assert if a cycle is detected. // replacementMap[cst] = nullptr; for (Use& u : inst->operands()) { Value* val = u.get(); if (isa<Constant>(val)) { Constant* c = cast<Constant>(val); if (cstUsers.count(c)) { Instruction* replacement = handleConstant(c, inst /*insertBefore*/); u.set(replacement); } } } replacementMap[cst] = inst; return inst; }; std::vector<Instruction*> instList; for (BasicBlock& bb : *mainFn) { for (Instruction& inst : bb) { instList.push_back(&inst); } } Instruction* insPt = replacementValue->getNextNode(); ReleaseAssert(insPt != nullptr); for (Instruction* inst : instList) { for (Use& u : inst->operands()) { Value* val = u.get(); if (isa<Constant>(val)) { Constant* c = cast<Constant>(val); if (cstUsers.count(c)) { Instruction* replacement = handleConstant(c, insPt /*insertBefore*/); u.set(replacement); } } } } gvToReplace->removeDeadConstantUsers(); // Catch bugs as early as possible if any of the crap above went wrong.. // ValidateLLVMFunction(mainFn); } } // namespace dast
6b5ad83f71e64b47fc46143dffc15962077ace11
3e9edb829449c3f7841620c741627cad6a864ee6
/time.cpp
202431dfbef943aa58f8d65ad4a8128b49055433
[]
no_license
R-Aswathama/Codechef-question
0df6b2ae91ce1e0c2451f66307d7c6dbb150c876
d4c2dd98f6fb33b8c8eceda36167026a72bfefcd
refs/heads/master
2023-04-03T20:36:10.432353
2021-05-02T04:36:12
2021-05-02T04:36:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
278
cpp
time.cpp
#include<iostream> using namespace std; int main() { short n,h,x,a=0; cin>>n>>h>>x; short t[n]; for(short i=0;i<n;i++) { cin>>t[i]; } for(short i=0;i<n;i++) { t[i]+=x; if(t[i]>=h) { a=1; break; } } if(a==1) cout<<"YES"; else { cout<<"NO"; } }
baf9b6a30d51db18327a146bdca7e0e657a0ef97
db96b049c8e27f723fcb2f3a99291e631f1a1801
/include/objtools/pubseq_gateway/impl/cassandra/cass_query_list.hpp
c07b29db50c5155926c741409672a2dcfa90640d
[]
no_license
Watch-Later/ncbi-cxx-toolkit-public
1c3a2502b21c7c5cee2c20c39e37861351bd2c05
39eede0aea59742ca4d346a6411b709a8566b269
refs/heads/master
2023-08-15T14:54:41.973806
2021-10-04T04:03:02
2021-10-04T04:03:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,271
hpp
cass_query_list.hpp
#ifndef CASS_QUERY_LIST__HPP #define CASS_QUERY_LIST__HPP #include <memory> #include <objtools/pubseq_gateway/impl/cassandra/cass_driver.hpp> #include <objtools/pubseq_gateway/impl/cassandra/mpmc_w.hpp> BEGIN_IDBLOB_SCOPE USING_NCBI_SCOPE; class CCassQueryList; using TCassQueryListTickCB = function<void()>; class ICassQueryListConsumer { public: ICassQueryListConsumer() = default; ICassQueryListConsumer(const ICassQueryListConsumer&) = delete; ICassQueryListConsumer(ICassQueryListConsumer&&) = delete; ICassQueryListConsumer& operator=(const ICassQueryListConsumer&) = delete; ICassQueryListConsumer& operator=(ICassQueryListConsumer&&) = delete; virtual ~ICassQueryListConsumer() = default; virtual bool Start(shared_ptr<CCassQuery> query, CCassQueryList& list, size_t query_idx) = 0; virtual bool Finish(shared_ptr<CCassQuery>, CCassQueryList&, size_t /*query_idx*/) { return true; } virtual bool ProcessRow(shared_ptr<CCassQuery> query, CCassQueryList& list, size_t query_idx) = 0; virtual void Reset(shared_ptr<CCassQuery>, CCassQueryList&, size_t /*query_idx*/) {} virtual void Failed(shared_ptr<CCassQuery> query, CCassQueryList& list, size_t query_idx, const exception* e) = 0; }; class CCassQueryList { public: static constexpr const unsigned int kDfltMaxQuery = 128; static constexpr const uint64_t kReadyPushWaitTimeout = 500000; static constexpr const uint64_t kReadyPopWaitTimeout = 500; static constexpr const size_t kNotifyQueueLen = 2048; static constexpr const unsigned int kResetRelaxTime = 10; static shared_ptr<CCassQueryList> Create(shared_ptr<CCassConnection> cass_conn) noexcept; virtual ~CCassQueryList(); CCassQueryList& SetMaxQueries(size_t max_queries); CCassQueryList& SetKeyspace(const string& keyspace); CCassQueryList& SetTickCB(TCassQueryListTickCB cb); string GetKeyspace() const; size_t GetMaxQueries() const; bool HasError() const; size_t NumberOfActiveQueries() const; size_t NumberOfBusySlots() const; size_t NumberOfPendingSlots() const; string ToString() const; void Finalize(); void Cancel(const exception* e = nullptr); void Cancel(ICassQueryListConsumer* consumer, const exception* e = nullptr); void Execute(unique_ptr<ICassQueryListConsumer> consumer, int retry_count, bool post_async = false); bool HasEmptySlot(); void Yield(bool wait); shared_ptr<CCassQuery> Extract(size_t slot_index); protected: CCassQueryList() : m_cnt(0), m_has_error(false), m_max_queries(kDfltMaxQuery), m_yield_in_progress(false), m_attached_slots(0), m_owning_thread{} {} private: enum SQrySlotState { ssAvailable, ssAttached, ssReadingRow, ssReseting, ssReleasing, ssLast = ssReleasing + 1 }; static string SQrySlotStateStr[ssLast]; struct SQrySlot { unique_ptr<ICassQueryListConsumer> m_consumer; shared_ptr<CCassQuery> m_qry; size_t m_index; int m_retry_count; SQrySlotState m_state; }; class CQryNotification : public CCassDataCallbackReceiver { public: CQryNotification(shared_ptr<CCassQueryList> query_list, size_t index); virtual void OnData() override; private: weak_ptr<CCassQueryList> m_query_list; size_t m_index; }; struct SPendingSlot { unique_ptr<ICassQueryListConsumer> m_consumer; int m_retry_count; }; void Tick(); SQrySlot* CheckSlots(bool discard, bool wait = true); SQrySlot* CheckSlot(size_t index, bool discard); void CheckPending(SQrySlot* slot); void AttachSlot(SQrySlot* slot, SPendingSlot&& pending_slot); void DetachSlot(SQrySlot* slot); void ReadRows(SQrySlot* slot); void Release(SQrySlot* slot); void CheckAccess(); weak_ptr<CCassQueryList> m_self_weak; shared_ptr<CCassConnection> m_cass_conn; vector<SQrySlot> m_query_arr; mpmc_bounded_queue_w<size_t, kNotifyQueueLen> m_ready; int64_t m_cnt; bool m_has_error; size_t m_max_queries; vector<SPendingSlot> m_pending_arr; vector<shared_ptr<CQryNotification>> m_notification_arr; TCassQueryListTickCB m_tick_cb; atomic_bool m_yield_in_progress; string m_keyspace; atomic_size_t m_attached_slots; atomic<thread::id> m_owning_thread; }; class CCassOneExecConsumer : public ICassQueryListConsumer { public: CCassOneExecConsumer(function<bool(CCassQuery& query, CCassQueryList& list)> cb, function<void(CCassQuery& query, CCassQueryList& list, bool succeeded)> finish_cb = nullptr) : m_cb(cb), m_finish_cb(finish_cb), m_is_failed(false), m_is_started(false), m_is_finished(false) {} CCassOneExecConsumer(const CCassOneExecConsumer&) = delete; CCassOneExecConsumer(CCassOneExecConsumer&&) = delete; CCassOneExecConsumer& operator=(const CCassOneExecConsumer&) = delete; CCassOneExecConsumer& operator=(CCassOneExecConsumer&&) = delete; virtual bool Start(shared_ptr<CCassQuery> query, CCassQueryList& list, size_t /*qry_index*/) override { assert(!m_is_started); assert(!m_is_finished); m_is_started = true; return m_cb(*query, list); } virtual bool Finish(shared_ptr<CCassQuery> query, CCassQueryList& list, size_t /*qry_index*/) { assert(m_is_started); assert(!m_is_finished); m_is_finished = true; if (m_finish_cb) m_finish_cb(*query, list, !m_is_failed); return true; } virtual bool ProcessRow(shared_ptr<CCassQuery>, CCassQueryList&, size_t /*qry_index*/) { assert(false); return true; } virtual void Reset(shared_ptr<CCassQuery>, CCassQueryList&, size_t /*qry_index*/) { } virtual void Failed(shared_ptr<CCassQuery>, CCassQueryList&, size_t /*qry_index*/, const exception*) { m_is_failed = true; } private: function<bool(CCassQuery& query, CCassQueryList& list)> m_cb; function<void(CCassQuery& query, CCassQueryList& list, bool succeeded)> m_finish_cb; bool m_is_failed; bool m_is_started; bool m_is_finished; }; END_IDBLOB_SCOPE #endif
d98388928b33f4222d2bfda30d4c771e8d616983
325e7186e0d915c86517aae6ce01e3e488484561
/Include/LBFL/LBGraph/LineSpec.hpp
fc076441501d2fbfbe918072c0d5ddb4e3972639
[]
no_license
LawrenceBuckingham/SimilarityProjection
03fe227539b1420f348cf0bdaf499ade3b0f117e
f441c4df637acba255a08cc97126a7de503fceb1
refs/heads/main
2023-02-09T02:31:46.030678
2020-12-28T03:29:10
2020-12-28T03:29:10
315,176,779
0
0
null
null
null
null
UTF-8
C++
false
false
2,062
hpp
LineSpec.hpp
#pragma once #include <FL/Fl.H> #include <FL/Fl_Widget.H> #include <FL/fl_draw.H> #include <memory> #include <string> #include <vector> using namespace std; namespace LBGraph { class LineSpec { protected: /** The border color for the point markers. */ Fl_Color colour = FL_BLACK; /** * The thickness of the marker border line, measured in pixels. If zero, a reasonable * system-specific default thickness is used. */ int thickness = 0; /** The FLTK line style of the marker border line. Copied from FLTK documentation: A bitmask which is a bitwise-OR of a line style, a cap style, and a join style. If you don't specify a dash type you will get a solid line. If you don't specify a cap or join type you will get a system-defined default of whatever value is fastest. */ int style = FL_SOLID; /** Byte pattern for dashes, encoded in a ASCIIZ string. */ string dashes = ""; public: LineSpec( Fl_Color colour = FL_BLACK, int thickness = 0, int style = FL_SOLID, const string &dashes = "") : colour(colour), thickness(thickness), style(style), dashes(dashes) { } /** Destructor. */ virtual ~LineSpec() {} void Colour(Fl_Color colour) { this->colour = colour; } Fl_Color Colour() { return colour; } void Thickness(int thickness) { this->thickness = thickness; } int Thickness() { return this->thickness; } void Style(int style) { this->style = style; } int Style() { return this->style; } string &Dashes() { return this->dashes; } /** * Gets a useable default line specifier. Colour is black, thickness is zero (yielding a FLTK default thickness), style is solid and dash pattern is an empty sequence. * @returns a shared pointer to a global default line specifier. */ static LineSpec *Default() { static LineSpec *instance(new LineSpec()); return instance; } /** * Gets a copy of this object. * @returns A newly created clone of the present object. */ LineSpec *Clone() const { return new LineSpec(this->colour, this->thickness, this->style, this->dashes); } }; } // namespace HBGraph
aa82ce7a5b07e972ba5e2d63a69e97c3c46bea93
135e0ddb881e8e5e4a6bae738e26eb2f951110e2
/src/armory/inc/map/grid.hpp
70ea4ce09bc4757dc7a0e5ed199ee4ce0d374f9f
[]
permissive
MadMcCrow/ARMORY
cc87199401d0a5128c5c9bf9570e8aaa46bf6fd9
a1841a6986a7fdf295043d055ebab477dd2cf137
refs/heads/main
2023-06-22T20:02:30.035121
2023-06-20T16:46:23
2023-06-20T16:46:23
316,828,385
2
1
MIT
2023-06-14T21:27:57
2020-11-28T21:52:34
C++
UTF-8
C++
false
false
2,084
hpp
grid.hpp
/// Copyright (c) 2023 Noé Perard-Gayot (MadMcCrow) /// This work is licensed under the terms of the MIT license. For a copy see <https://opensource.org/licenses/MIT> #ifndef ARMORY_GRID_H #define ARMORY_GRID_H // Godot #include <godot_cpp/core/class_db.hpp> #include <godot_cpp/classes/ref_counted.hpp> // Armory #include "macros.hpp" #include "cell.hpp" using namespace godot; namespace ARMORY { /** * @class MapGrid * @brief 2D Grid to contain @see MapCell * * @todo maybe change to inherit from Resource * @todo maybe use Vector2i for position * @todo maybe replace MapCell by Ref<MapCell> */ class MapGrid : public RefCounted { GDCLASS(MapGrid, RefCounted); public: MapGrid(int x = 0, int y = 0); virtual ~MapGrid(); /** Set grid size, and update cells */ void set_grid_size(int x, int y); /** get cell element at position */ MapCell& elem_at(const int& x, const int& y); /** get cell element at position, const version */ const MapCell& elem_at(const int& x, const int& y) const; protected: /** turn a 2d position into an index */ int get_index(const int& x, const int& y) const; private: /** size */ int _size_x = 0; int _size_y = 0; /** * whether the grid loops around * @todo maybe we'll switch to a ENUM for readability. */ bool _loop = false; /** Array of cells */ std::vector<MapCell> _cells; public: // Godot-API functions static void _bind_methods(); inline Vector2i get_size() const { return Vector2i(_size_x, _size_y); } inline void set_size(const Vector2i& size) { set_grid_size(size.x, size.y); } inline void set_cell(const Vector2i& pos, const MapCell& cell) { elem_at(pos.x, pos.y).set_data(cell.get_data()); } inline const MapCell& get_cell(const Vector2i& pos, const MapCell& cell) {return elem_at(pos.x, pos.y); } }; }; #endif /* ARMORY_GRID_H */
69e9be8c1e67db7e6b184cff713de6c726061af1
2d3dffb6fcc4364c7b16d64bf1cde7c24c3167b8
/Estructuras de datos con C++/lista sencilla(info String)/TDAListaSencilla.h
ad62920fb59a77e0366f02d2cdc6b5d3462b9b80
[]
no_license
juanjosegdoj/Ejercicios-Estructuras-de-Datos
d68d56603fc9252b3c893782c73942ea2821d8e8
97d07bb59f26a29e2205b68b52aadb30c3f5b8d1
refs/heads/master
2020-03-20T12:44:21.355158
2018-06-15T04:11:32
2018-06-15T04:11:32
137,439,409
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
3,300
h
TDAListaSencilla.h
#include "TDANodo.h" #include <iostream> using namespace std; /*Nodo Incio de la Lista*/ struct TDALista{ Nodo *inicio; Nodo *actual; } ; /* Por LUz Mery. Crea la Lista, moviendo siempre la posición actial al elemento ingresado*/ TDALista *crearLista(TDALista *c, string dato){ Nodo *aux; aux = crearNodo(dato); if (c==NULL){ c= new TDALista(); c->inicio = c->actual = aux; } else { c->actual->sig = aux; c->actual=aux; } return c; } void ImprimirLista(TDALista *c){ if (c==NULL){ cout<<"\n"<<"La lista no está creada"; } else { Nodo *aux; aux=c->inicio; while (aux != NULL){ cout<<"\n"<<aux->info; aux=aux->sig; } } cout<<"\n"; } int longitud(TDALista *c){ int cont; if(c==NULL){ cont=0; }else{ c->actual=c->inicio; while(c->actual!=NULL){ c->actual=c->actual->sig; cont++; } c->actual=c->inicio; while (c->actual->sig!=NULL) c->actual=c->actual->sig; return cont; } } TDALista *InsertOrden(TDALista *c, string dato){ if (c == NULL){ c = crearLista(c, dato); cout<<"se crea la lista"<<endl; } else { cout << "Prontos a ingresar nodo\n"; Nodo *aux, *auxAnt, *auxNew; aux=c->inicio; auxAnt = aux; auxNew = crearNodo(dato); cout << "Recorriendo lista: "<<aux->info <<" ---- "<<auxNew->info<<endl; int cont = 0; while (aux!=NULL && aux->info < auxNew->info ){ cont++; cout << "poscion "<< cont << endl; auxAnt = aux; aux=aux->sig; } if (aux==NULL){ c->actual->sig = auxNew; c->actual = auxNew; } else { if (auxNew->info < c->inicio->info){ auxNew->sig = c->inicio; c->inicio=auxNew; } else { auxNew->sig= auxAnt->sig; auxAnt->sig=auxNew; } } } return c; } int buscar(string elemento, TDALista*c){ // retorna 1 o 0 si existe un elemento en la lista sencilla int encontrado; if (c==NULL){ encontrado= 0; } else{ Nodo *aux=c->inicio; while(aux!=NULL && !encontrado){ if(aux->info==elemento){ encontrado=1; } aux = aux ->sig; } } return encontrado; } string elemEnPos(int index, TDALista*c){ // el elemento en una posción ingresada if (c==NULL){ return "NULL"; } if(longitud(c)<=index){ return "NULL"; } else{ Nodo *aux=c->inicio; for(int i=0; i<index; i++){ aux = aux ->sig; } return aux->info; } } Nodo *BuscarElementNODO(string elemento, TDALista*c){ // retorna el nodo donde fue encontrado el elemento Nodo *aux; bool encontrado = false; if (c==NULL){ return NULL; } else{ aux=c->inicio; while(aux!=NULL && !encontrado){ if(aux->info==elemento){ encontrado = true; }else aux = aux ->sig; } } if (encontrado) return aux; else return NULL; } TDALista *eliminarElemento(string elemento, TDALista*c){ if ( longitud(c) == 0){ return c; } Nodo *aux; bool encontrado = false; if (c==NULL){ return NULL; } else{ aux=c->inicio; while(aux!=NULL && !encontrado){ if(aux->info==elemento){ encontrado = true; }else aux = aux ->sig; } } if (encontrado) return c; else return NULL; }
08bd341a2ba3f5068fdba853d91ab437512e10fb
ebc144cd5658eabdb1b7c549741d2718ebe6ff85
/Simulator/Edges/Neuro/AllSTDPSynapses.cpp
92e7f355b3bb3d1a52e6fe995a2e619c5401cb2d
[ "Apache-2.0" ]
permissive
UWB-Biocomputing/Graphitti
175a8fa442fc61341338efea504adb797136c339
6c392438d9e5367b0ddfee9c7fb257df27a05bf4
refs/heads/master
2023-09-04T09:04:24.244967
2023-08-07T23:55:00
2023-08-07T23:55:00
273,115,663
8
22
Apache-2.0
2023-09-13T20:22:13
2020-06-18T01:41:41
C++
UTF-8
C++
false
false
19,730
cpp
AllSTDPSynapses.cpp
/** * @file AllSTDPSynapses.cpp * * @ingroup Simulator/Edges * * @brief A container of all STDP synapse data */ #include "AllSTDPSynapses.h" #include "AllSpikingNeurons.h" #include "AllVertices.h" #include "ParameterManager.h" AllSTDPSynapses::AllSTDPSynapses() : AllSpikingSynapses() { defaultSTDPgap_ = 0; tauspost_I_ = 0; tauspre_I_ = 0; tauspost_E_ = 0; tauspre_E_ = 0; taupos_I_ = 0; tauneg_I_ = 0; taupos_E_ = 0; tauneg_E_ = 0; Wex_I_ = 0; Wex_E_ = 0; Aneg_I_ = 0; Aneg_E_ = 0; Apos_I_ = 0; Apos_E_ = 0; } AllSTDPSynapses::AllSTDPSynapses(const int numVertices, const int maxEdges) : AllSpikingSynapses(numVertices, maxEdges) { setupEdges(numVertices, maxEdges); } /// Setup the internal structure of the class (allocate memories and initialize them). void AllSTDPSynapses::setupEdges() { setupEdges(Simulator::getInstance().getTotalVertices(), Simulator::getInstance().getMaxEdgesPerVertex()); } /// Setup the internal structure of the class (allocate memories and initialize them). /// /// @param numVertices Total number of vertices in the network. /// @param maxEdges Maximum number of synapses per neuron. void AllSTDPSynapses::setupEdges(const int numVertices, const int maxEdges) { AllSpikingSynapses::setupEdges(numVertices, maxEdges); BGSIZE maxTotalSynapses = maxEdges * numVertices; if (maxTotalSynapses != 0) { Wex_.assign(maxTotalSynapses, 0); Aneg_.assign(maxTotalSynapses, 0); Apos_.assign(maxTotalSynapses, 0); mupos_.assign(maxTotalSynapses, 0); muneg_.assign(maxTotalSynapses, 0); taupos_.assign(maxTotalSynapses, 0); tauneg_.assign(maxTotalSynapses, 0); tauspre_.assign(maxTotalSynapses, 0); STDPgap_.assign(maxTotalSynapses, 0); tauspost_.assign(maxTotalSynapses, 0); totalDelayPost_.assign(maxTotalSynapses, 0); delayQueuePost_.assign(maxTotalSynapses, 0); delayIndexPost_.assign(maxTotalSynapses, 0); delayQueuePostLength_.assign(maxTotalSynapses, 0); } } /// Initializes the queues for the Synapse. /// /// @param iEdg index of the synapse to set. void AllSTDPSynapses::initSpikeQueue(const BGSIZE iEdg) { AllSpikingSynapses::initSpikeQueue(iEdg); int &total_delay = totalDelayPost_[iEdg]; uint32_t &delayQueue = delayQueuePost_[iEdg]; int &delayIdx = delayIndexPost_[iEdg]; int &ldelayQueue = delayQueuePostLength_[iEdg]; uint32_t size = total_delay / (sizeof(uint8_t) * 8) + 1; assert(size <= BYTES_OF_DELAYQUEUE); delayQueue = 0; delayIdx = 0; ldelayQueue = LENGTH_OF_DELAYQUEUE; } /// Loads out all parameters from the config file. /// Registered to OperationManager as Operation::loadParameters void AllSTDPSynapses::loadParameters() { AllSpikingSynapses::loadParameters(); ParameterManager::getInstance().getBGFloatByXpath("//STDPgap/text()", defaultSTDPgap_); ParameterManager::getInstance().getBGFloatByXpath("//tauspost/i/text()", tauspost_I_); ParameterManager::getInstance().getBGFloatByXpath("//tauspost/e/text()", tauspost_E_); ParameterManager::getInstance().getBGFloatByXpath("//tauspre/i/text()", tauspre_I_); ParameterManager::getInstance().getBGFloatByXpath("//tauspre/e/text()", tauspre_E_); ParameterManager::getInstance().getBGFloatByXpath("//taupos/i/text()", taupos_I_); ParameterManager::getInstance().getBGFloatByXpath("//taupos/e/text()", taupos_E_); ParameterManager::getInstance().getBGFloatByXpath("//tauneg/i/text()", tauneg_I_); ParameterManager::getInstance().getBGFloatByXpath("//tauneg/e/text()", tauneg_E_); ParameterManager::getInstance().getBGFloatByXpath("//Wex/i/text()", Wex_I_); ParameterManager::getInstance().getBGFloatByXpath("//Wex/e/text()", Wex_E_); ParameterManager::getInstance().getBGFloatByXpath("//Aneg/i/text()", Aneg_I_); ParameterManager::getInstance().getBGFloatByXpath("//Aneg/e/text()", Aneg_E_); ParameterManager::getInstance().getBGFloatByXpath("//Apos/i/text()", Apos_I_); ParameterManager::getInstance().getBGFloatByXpath("//Apos/e/text()", Apos_E_); } /// Prints out all parameters to logging file. /// Registered to OperationManager as Operation::printParameters void AllSTDPSynapses::printParameters() const { AllSpikingSynapses::printParameters(); LOG4CPLUS_DEBUG(edgeLogger_, "\n\t---AllSTDPSynapses Parameters---" << endl << "\tEdges type: AllSTDPSynapses" << endl << endl << "\tSTDP gap" << defaultSTDPgap_ << endl << "\n\tTauspost value: [" << " I: " << tauspost_I_ << ", " << " E: " << tauspost_E_ << "]" << endl << "\n\tTauspre value: [" << " I: " << tauspre_I_ << ", " << " E: " << tauspre_E_ << "]" << endl << "\n\tTaupos value: [" << " I: " << taupos_I_ << ", " << " E: " << taupos_E_ << "]" << endl << "\n\tTau negvalue: [" << " I: " << tauneg_I_ << ", " << " E: " << tauneg_E_ << "]" << endl << "\n\tWex value: [" << " I: " << Wex_I_ << ", " << " E: " << Wex_E_ << "]" << endl << "\n\tAneg value: [" << " I: " << Aneg_I_ << ", " << " E: " << Aneg_E_ << "]" << endl << "\n\tApos value: [" << " I: " << Apos_I_ << ", " << " E: " << Apos_E_ << "]" << endl); } /// Sets the data for Synapse to input's data. /// /// @param input istream to read from. /// @param iEdg Index of the synapse to set. void AllSTDPSynapses::readEdge(istream &input, const BGSIZE iEdg) { AllSpikingSynapses::readEdge(input, iEdg); // input.ignore() so input skips over end-of-line characters. input >> totalDelayPost_[iEdg]; input.ignore(); input >> delayQueuePost_[iEdg]; input.ignore(); input >> delayIndexPost_[iEdg]; input.ignore(); input >> delayQueuePostLength_[iEdg]; input.ignore(); input >> tauspost_[iEdg]; input.ignore(); input >> tauspre_[iEdg]; input.ignore(); input >> taupos_[iEdg]; input.ignore(); input >> tauneg_[iEdg]; input.ignore(); input >> STDPgap_[iEdg]; input.ignore(); input >> Wex_[iEdg]; input.ignore(); input >> Aneg_[iEdg]; input.ignore(); input >> Apos_[iEdg]; input.ignore(); input >> mupos_[iEdg]; input.ignore(); input >> muneg_[iEdg]; input.ignore(); } /// Write the synapse data to the stream. /// /// @param output stream to print out to. /// @param iEdg Index of the synapse to print out. void AllSTDPSynapses::writeEdge(ostream &output, const BGSIZE iEdg) const { AllSpikingSynapses::writeEdge(output, iEdg); output << totalDelayPost_[iEdg] << ends; output << delayQueuePost_[iEdg] << ends; output << delayIndexPost_[iEdg] << ends; output << delayQueuePostLength_[iEdg] << ends; output << tauspost_[iEdg] << ends; output << tauspre_[iEdg] << ends; output << taupos_[iEdg] << ends; output << tauneg_[iEdg] << ends; output << STDPgap_[iEdg] << ends; output << Wex_[iEdg] << ends; output << Aneg_[iEdg] << ends; output << Apos_[iEdg] << ends; output << mupos_[iEdg] << ends; output << muneg_[iEdg] << ends; } /// Reset time varying state vars and recompute decay. /// /// @param iEdg Index of the synapse to set. /// @param deltaT Inner simulation step duration void AllSTDPSynapses::resetEdge(const BGSIZE iEdg, const BGFLOAT deltaT) { AllSpikingSynapses::resetEdge(iEdg, deltaT); } /// Create a Synapse and connect it to the model. /// /// @param synapses The synapse list to reference. /// @param iEdg Index of the synapse to set. /// @param srcVertex Coordinates of the source Neuron. /// @param destVertex Coordinates of the destination Neuron. /// @param sumPoint Summation point address. /// @param deltaT Inner simulation step duration. /// @param type Type of the Synapse to create. void AllSTDPSynapses::createEdge(const BGSIZE iEdg, int srcVertex, int destVertex, BGFLOAT *sumPoint, const BGFLOAT deltaT, edgeType type) { totalDelayPost_[iEdg] = 0; // Apr 12th 2020 move this line so that when AllSpikingSynapses::createEdge() is called, inside this method the initSpikeQueue() method can be called successfully AllSpikingSynapses::createEdge(iEdg, srcVertex, destVertex, sumPoint, deltaT, type); // May 1st 2020 // Use constants from Froemke and Dan (2002). // Spike-timing-dependent synaptic modification induced by natural spike trains. Nature 416 (3/2002) //Apos_[iEdg] = 0.005; //Aneg_[iEdg] = -(1.05*0.005); Apos_[iEdg] = Apos_E_; Aneg_[iEdg] = Aneg_E_; STDPgap_[iEdg] = defaultSTDPgap_; tauspost_[iEdg] = tauspost_E_; tauspre_[iEdg] = tauspre_E_; taupos_[iEdg] = taupos_E_; tauneg_[iEdg] = tauneg_E_; Wex_[iEdg] = Wex_E_; // this is based on overlap of 2 neurons' radii (r=4) of outgrowth, scale it by SYNAPSE_STRENGTH_ADJUSTMENT. mupos_[iEdg] = 0; muneg_[iEdg] = 0; } #if !defined(USE_GPU) /// Advance one specific Synapse. /// /// @param iEdg Index of the Synapse to connect to. /// @param neurons The Neuron list to search from. void AllSTDPSynapses::advanceEdge(const BGSIZE iEdg, AllVertices &neurons) { // If the synapse is inhibitory or its weight is zero, update synapse state using AllSpikingSynapses::advanceEdge method //LOG4CPLUS_DEBUG(edgeLogger_, "iEdg : " << iEdg ); BGFLOAT &W = W_[iEdg]; /* if (W <= 0.0) { AllSpikingSynapses::advanceEdge(iEdg, neurons); return; } */ BGFLOAT &decay = decay_[iEdg]; BGFLOAT &psr = psr_[iEdg]; BGFLOAT &summationPoint = *(summationPoint_[iEdg]); // is an input in the queue? bool fPre = isSpikeQueue(iEdg); bool fPost = isSpikeQueuePost(iEdg); if (fPre || fPost) { const BGFLOAT taupos = taupos_[iEdg]; const BGFLOAT tauneg = tauneg_[iEdg]; const int total_delay = totalDelay_[iEdg]; BGFLOAT deltaT = Simulator::getInstance().getDeltaT(); AllSpikingNeurons &spNeurons = dynamic_cast<AllSpikingNeurons &>(neurons); // pre and post neurons index int idxPre = sourceVertexIndex_[iEdg]; int idxPost = destVertexIndex_[iEdg]; uint64_t spikeHistory, spikeHistory2; BGFLOAT delta; BGFLOAT epre, epost; if (fPre) { // preSpikeHit // spikeCount points to the next available position of spike_history, // so the getSpikeHistory w/offset = -2 will return the spike time // just one before the last spike. spikeHistory = spNeurons.getSpikeHistory(idxPre, -2); epre = 1.0; epost = 1.0; // call the learning function stdpLearning() for each pair of // pre-post spikes int offIndex = -1; // last spike while (true) { spikeHistory = spNeurons.getSpikeHistory(idxPost, offIndex); if (spikeHistory == numeric_limits<unsigned long>::max()) break; // delta is the spike interval between pre-post spikes // (include pre-synaptic transmission delay) delta = -static_cast<BGFLOAT>(g_simulationStep - spikeHistory) * deltaT; /* LOG4CPLUS_DEBUG(fileLogger_,"\nAllSTDPSynapses::advanceSynapse: fPre" << endl << "\tiEdg: " << iEdg << endl << "\tidxPre: " << idxPre << endl << "\tidxPost: " << idxPost << endl << "\tspikeHistory: " << spikeHistory << endl << "\tepre: " << epre << endl << "\tepost: " << epost << endl << "\tg_simulationStep: " << g_simulationStep << endl << "\tdelta: " << delta << endl << endl); */ if (delta <= -3.0 * tauneg) break; stdpLearning(iEdg, delta, epost, epre, idxPre, idxPost); --offIndex; } changePSR(iEdg, deltaT); } if (fPost) { // postSpikeHit // spikeCount points to the next available position of spike_history, // so the getSpikeHistory w/offset = -2 will return the spike time // just one before the last spike. spikeHistory = spNeurons.getSpikeHistory(idxPost, -2); epost = 1.0; epre = 1; // call the learning function stdpLearning() for each pair of // post-pre spikes int offIndex = -1; // last spike while (true) { spikeHistory = spNeurons.getSpikeHistory(idxPre, offIndex); if (spikeHistory == numeric_limits<unsigned long>::max()) break; if (spikeHistory + total_delay > g_simulationStep) { --offIndex; continue; } // delta is the spike interval between post-pre spikes delta = static_cast<BGFLOAT>(g_simulationStep - spikeHistory - total_delay) * deltaT; /* LOG4CPLUS_DEBUG(fileLogger_,"\nAllSTDPSynapses::advanceSynapse: fPost" << endl << "\tiEdg: " << iEdg << endl << "\tidxPre: " << idxPre << endl << "\tidxPost: " << idxPost << endl << "\tspikeHistory: " << spikeHistory << endl << "\tg_simulationStep: " << g_simulationStep << endl << "\tepre: " << epre << endl << "\tepost: " << epost << endl << "\tdelta: " << delta << endl << endl); */ if (delta >= 3.0 * taupos) break; stdpLearning(iEdg, delta, epost, epre, idxPre, idxPost); --offIndex; } } } // decay the post spike response psr *= decay; // and apply it to the summation point #ifdef USE_OMP #pragma omp atomic #endif summationPoint += psr; #ifdef USE_OMP //PAB: atomic above has implied flush (following statement generates error -- can't be member variable) //#pragma omp flush (summationPoint) #endif } BGFLOAT AllSTDPSynapses::synapticWeightModification(const BGSIZE iEdg, BGFLOAT synapticWeight, double delta) { BGFLOAT STDPgap = STDPgap_[iEdg]; BGFLOAT muneg = muneg_[iEdg]; BGFLOAT mupos = mupos_[iEdg]; BGFLOAT tauneg = tauneg_[iEdg]; BGFLOAT taupos = taupos_[iEdg]; BGFLOAT Aneg = Aneg_[iEdg]; BGFLOAT Apos = Apos_[iEdg]; BGFLOAT Wex = Wex_[iEdg]; BGFLOAT &W = W_[iEdg]; edgeType type = type_[iEdg]; BGFLOAT dw = 0; BGFLOAT oldW = W; // BGFLOAT modDelta = fabs(delta); if (delta < -STDPgap) { // depression dw = pow(fabs(W) / Wex, muneg) * Aneg * exp(delta / tauneg); // normalize } else if (delta > STDPgap) { // potentiation dw = pow(fabs(Wex - fabs(W)) / Wex, mupos) * Apos * exp(-delta / taupos); // normalize } return dw; } /// Adjust synapse weight according to the Spike-timing-dependent synaptic modification /// induced by natural spike trains /// /// @param iEdg Index of the synapse to set. /// @param delta Pre/post synaptic spike interval. /// @param epost Params for the rule given in Froemke and Dan (2002). /// @param epre Params for the rule given in Froemke and Dan (2002). /// @param srcVertex Index of source neuron /// @param destVertex Index of destination neuron void AllSTDPSynapses::stdpLearning(const BGSIZE iEdg, double delta, double epost, double epre, int srcVertex, int destVertex) { BGFLOAT STDPgap = STDPgap_[iEdg]; BGFLOAT muneg = muneg_[iEdg]; BGFLOAT mupos = mupos_[iEdg]; BGFLOAT tauneg = tauneg_[iEdg]; BGFLOAT taupos = taupos_[iEdg]; BGFLOAT Aneg = Aneg_[iEdg]; BGFLOAT Apos = Apos_[iEdg]; BGFLOAT Wex = Wex_[iEdg]; BGFLOAT &W = W_[iEdg]; edgeType type = type_[iEdg]; BGFLOAT oldW = W; // BGFLOAT modDelta = fabs(delta); if (delta <= fabs(STDPgap)) { return; } // dw is the fractional change in synaptic strength; add 1.0 to become the scaling ratio //dw = 1.0 + dw * epre * epost; BGFLOAT dw = 1.0 + synapticWeightModification(iEdg, W, delta); // if scaling ratio is less than zero, set it to zero so this synapse, its // strength is always zero // TODO: Where is the code for this? // current weight multiplies dw (scaling ratio) to generate new weight if (dw != 0.0) W *= dw; // if new weight is bigger than Wex (maximum allowed weight), then set it to Wex if (fabs(W) > Wex) { W = edgSign(type) * Wex; } /* LOG4CPLUS_DEBUG(edgeLogger_, endl << "iEdg value " << iEdg << "; source:" << srcVertex << "; dest:" << destVertex << "; delta:" << delta << "; oldW:" << oldW << " ;W:" << W << endl); */ } /// Checks if there is an input spike in the queue (for back propagation). /// /// @param iEdg Index of the Synapse to connect to. /// @return true if there is an input spike event. bool AllSTDPSynapses::isSpikeQueuePost(const BGSIZE iEdg) { uint32_t &delayQueue = delayQueuePost_[iEdg]; int &delayIdx = delayIndexPost_[iEdg]; int &ldelayQueue = delayQueuePostLength_[iEdg]; bool r = delayQueue & (0x1 << delayIdx); delayQueue &= ~(0x1 << delayIdx); if (++delayIdx >= ldelayQueue) { delayIdx = 0; } return r; } /// Prepares Synapse for a spike hit (for back propagation). /// /// @param iEdg Index of the Synapse to connect to. void AllSTDPSynapses::postSpikeHit(const BGSIZE iEdg) { uint32_t &delay_queue = delayQueuePost_[iEdg]; int &delayIdx = delayIndexPost_[iEdg]; int &ldelayQueue = delayQueuePostLength_[iEdg]; int &total_delay = totalDelayPost_[iEdg]; // Add to spike queue // calculate index where to insert the spike into delayQueue int idx = delayIdx + total_delay; if (idx >= ldelayQueue) { idx -= ldelayQueue; } // set a spike assert(!(delay_queue & (0x1 << idx))); delay_queue |= (0x1 << idx); } #endif // !defined(USE_GPU) /// Check if the back propagation (notify a spike event to the pre neuron) /// is allowed in the synapse class. /// /// @retrun true if the back propagation is allowed. bool AllSTDPSynapses::allowBackPropagation() { return true; } /// Prints SynapsesProps data. void AllSTDPSynapses::printSynapsesProps() const { AllSpikingSynapses::printSynapsesProps(); for (int i = 0; i < maxEdgesPerVertex_ * countVertices_; i++) { if (W_[i] != 0.0) { cout << "total_delayPost[" << i << "] = " << totalDelayPost_[i]; cout << " tauspost_: " << tauspost_[i]; cout << " tauspre_: " << tauspre_[i]; cout << " taupos_: " << taupos_[i]; cout << " tauneg_: " << tauneg_[i]; cout << " STDPgap_: " << STDPgap_[i]; cout << " Wex_: " << Wex_[i]; cout << " Aneg_: " << Aneg_[i]; cout << " Apos_: " << Apos_[i]; cout << " mupos_: " << mupos_[i]; cout << " muneg_: " << muneg_[i] << endl; } } }
4e3b8b5ccce7b02d71ded49411c82faa504c663d
00491554bae3be54908decc2ab485d0f9a42190b
/q6.cpp
e52a8b669c5418e2dca38e988618661e2f77c378
[]
no_license
pranjalisingh22/akku
da20bf6ea13f42dbf027fbd0609c84029255a1a9
c3e5dbc686e80d0af27f16da47d02f27a99125b8
refs/heads/master
2020-03-25T20:42:10.328317
2018-11-18T17:47:17
2018-11-18T17:47:17
144,141,654
0
0
null
null
null
null
UTF-8
C++
false
false
594
cpp
q6.cpp
//printing the sum of digits of any number. #include<iostream> //including library using namespace std; //defining use of cout dunction void f(int n,int z) //defining function { /*as long as n is not 0 divide n by 10 and add the remainder to a temporary variable also discard the decimal part of n after dividing */ if(n!=0) //exit condition { z= z+ (n%10); n = n/10; f(n,z); //tailend recursion } else { cout<<"the sum of digits of given number is: "<<z;//printing the output } } int main() { int n; cout<<"please enter the number: "; cin>>n; f(n,0); return 0; }
35f539861d1ba45dede677fda6f3e5e2af5d8130
3445eed3395fc283e4c5bd3cf7d783caa2e626bf
/lwlog/src/details/pattern/formatter.h
fe19b202122ed3baa32970cf4b07ad2e2f7156dd
[ "MIT" ]
permissive
ChristianPanov/lwlog
e122353a258d8dc3eefd473ce7b5cf9cf97236b5
0c8016131fc6a09db64d362ae21799df6409c100
refs/heads/master
2023-08-05T00:14:40.563981
2023-08-01T10:29:03
2023-08-01T10:29:03
189,701,142
192
22
MIT
2022-01-14T01:19:37
2019-06-01T06:57:30
C++
UTF-8
C++
false
false
408
h
formatter.h
#pragma once namespace lwlog::details { struct formatter { virtual ~formatter() = default; virtual void format(std::string&, const record&) const = 0; template<typename T> static void format_attribute(std::string& pattern, const flag_pair& flags, T value); template<typename T> static void format_attribute(std::string& pattern, std::string_view flag, T value); }; } #include "formatter_impl.h"
155300dc1c9a629534a4160c60a48cb24ca1f858
6d258d9abc888d6c4640b77afa23355f9bafb5a0
/c++11/thread/this_get_id.cpp
d17f269ae9d1c990225520c0c35b2d6d6cfa5b84
[]
no_license
ohwada/MAC_cpp_Samples
e281130c8fd339ec327d4fad6d8cdf4e9bab4edc
74699e40343f13464d64cf5eb3e965140a6b31a2
refs/heads/master
2023-02-05T00:50:47.447668
2023-01-28T05:09:34
2023-01-28T05:09:34
237,116,830
15
1
null
null
null
null
UTF-8
C++
false
false
340
cpp
this_get_id.cpp
/** * this_get_id.cpp * 2022-06-01 K.OHWADA */ // g++ this_get_id.cpp -std=c++11 // https://cpprefjp.github.io/reference/thread/this_thread/get_id.html #include <iostream> #include <thread> /** * main */ int main() { std::cout << "thread_id=" << std::this_thread::get_id() << std::endl; return 0; } // thread_id=0x1119ecdc0
f6e063aa34580dc58e442b366037f6d4e66ff1da
d142829a061b5418d582c2dc39326ceffad3734e
/findkthofsearchtree/findkthtree.cpp
e6a1fc6e468d35cac3c3e10cf160e5caf56c2fcd
[]
no_license
Cauahu/hihoCoder-training
662f3ac531916e1b4613ea5645a7fca130559156
252f327c3f8ec803721f35b1d65204dde93c4b31
refs/heads/master
2021-01-15T15:32:30.308033
2016-08-08T02:48:28
2016-08-08T02:48:28
54,168,241
0
1
null
2020-10-02T05:30:02
2016-03-18T02:44:41
C++
UTF-8
C++
false
false
512
cpp
findkthtree.cpp
#include <iostream> using namespace std; struct TreeNode { int val; struct TreeNode * left; struct TreeNode * right; }; void preorder(TreeNode* pRoot, vector<TreeNode*> &vec) { if(pRoot == NULL) return; preorder(pRoot->left, vec); vec.push_back(pRoot); preorder(pRoot->right, vec); } TreeNode* kthnode(TreeNode* pRoot, int k) { if (pRoot == NULL || k < 1) { return NULL; } vector<TreeNode*> vec; preorder(pRoot, vec); if (k > vec.size()) { /* code */ return NULL; } return vec[k-1]; }
0c0a690bedd5d3a0807e35df971c21ef8b3fb8b3
185a0c0c02f33f37b2570fd6eee6c5b5f89624f7
/Simplex03/cdn/individual.h
c0e01347b30601cf52663a1d0eaa65147522cdbf
[]
no_license
Waydrow/CodeCraft
5c340c6a5bd74ca72a20b8afebebd75224f1690f
8512d9d5e0e2bc5f717c778af0577e86c621273b
refs/heads/master
2021-06-17T00:49:27.680577
2017-04-26T10:32:20
2017-04-26T10:32:20
84,938,259
1
0
null
null
null
null
UTF-8
C++
false
false
1,451
h
individual.h
#ifndef _INDIVIDUAL_ #define _INDIVIDUAL_ #include <bitset> // 个体类 class Individual { public: int cost; // 花费 double fitness; // 适应度 bitset<BITSIZE> bitIn; // 一个个体 int gen[1300]; public: // constructor Individual() {} // 由 0/1 串置换为十进制编码 void updateRealPlan() { int nn = 0; for (int i = 0; i < nodesNum * 3; i += 3) { int x = 0; for (int j = 2; j >= 0; j--) { x += bitIn[i+j] * pow(2, 2-j); } gen[nn++] = x; } } // 由十进制编码置换为 0/1 串 void updateBinaryPlan() { int nn = 0; for (int i = 0; i < nodesNum; i++) { int x = gen[i]; for (int j = 2; j >= 0; j--) { if (x & (1 << j)) { bitIn[nn++] = 1; } else { bitIn[nn++] = 0; } } } } // return server num int count() { int x = 0; for (int i = 0; i < nodesNum; i++) { if (gen[i]) { x++; } } return x; } // show this individual's info void show() { for (int i = 0; i < nodesNum; i++) { cout << bitIn[i] << " "; } cout << endl << "COST: " << cost << " FITNESS: "<< fitness << " Server Num: " << bitIn.count() << endl; } }; #endif
a3fd3452f8b60c7ef8dff10713d5d412fb9280a8
88824a3b0abb54c99c171e9d9dc030e8c8e5c342
/ch5/clist.cc
55a8d28c2b064c058361a407658c006b9e2234d7
[]
no_license
gamgyul/data_structure
bf87197d0ff95496649297a9777f92a952c19fdc
0d63f60f54aff82c5c6f940bb2b1f17e2af98a8e
refs/heads/master
2020-07-15T12:27:03.741567
2019-12-16T13:02:21
2019-12-16T13:02:21
205,561,599
0
0
null
null
null
null
UTF-8
C++
false
false
1,632
cc
clist.cc
#include "clist.h" Ch5CList::Ch5CList(){ tail = NULL; cur = NULL; before = NULL; } Ch5CList::~Ch5CList(){ } void Ch5CList::LInsert(LData data){ Node* tmp = new Node; tmp->data = data; if(tail == NULL){ tail = tmp; tmp->next = tmp; } else{ tmp->next =tail->next; tail->next = tmp; tail = tmp; } num_of_data++; } void Ch5CList::LInsertFirst(LData data){ Node* tmp = new Node; tmp->data = data; if(tail == NULL){ tail = tmp; tmp->next = tmp; } else{ tmp->next =tail->next; tail->next = tmp; } num_of_data++; } bool Ch5CList::LFirst(LData *datap){ if(tail == NULL) return false; cur = tail->next; datap = &cur->data; return true; } bool Ch5CList::LFirst(LData &data){ if(tail == NULL) return false; cur = tail->next; data = cur->data; return true; } bool Ch5CList::LNext(LData *datap){ if(tail == NULL) return false; before = cur; cur = cur->next; datap = &cur->data; return true; } bool Ch5CList::LNext(LData &data){ if(tail == NULL) return false; before = cur; cur = cur->next; data = cur->data; return true; } LData Ch5CList::LRemove(){ Node *tmp; LData rdata; tmp =cur; rdata = tmp->data; if(cur == cur->next){ cur = NULL; } else if(cur == tail){ tail = before; } before->next = cur->next; delete (tmp); cur = before; num_of_data--; return rdata; } int Ch5CList::LCount(){ return num_of_data; }
1ada562464cb86e2fa044f6119b5ff59a52f3023
3c441771e32023092acff40fe9de9cec5f8612d4
/OpenGL/Plane.h
10590c39fe53ea12df89b257f770f7bc956952bf
[]
no_license
nandos13/PhysicsEngineCPP
c3f5abe593e61af8bd9cd48d2b51943ac2414b21
56fb6ed43e0a93d9d6b2b14482627b5c41bcda5a
refs/heads/master
2021-01-23T01:50:47.071081
2017-07-17T09:30:37
2017-07-17T09:30:37
92,893,611
0
0
null
null
null
null
UTF-8
C++
false
false
323
h
Plane.h
#pragma once #include "PhysicsObject.h" class Plane : public PhysicsObject { friend class Physics; protected: glm::vec2 m_normal; public: Plane(const glm::vec2 pos, const glm::vec2 normal); ~Plane(); virtual void Update(const float deltaTime); virtual void Draw() const; const glm::vec2 GetNormal() const; };
4325f38296d0f0a83165604caac544daf9cd2e4d
d40b62dc181cb1f1b2853f439797552aac47112a
/game.h
0ebfd4e2f8e201aaff120cf34c0fd9e2c70a2d2b
[]
no_license
VladimirCourse/TicTacToe
7fbad96f47ab82f71a5155f6a5da6f955ab9b851
30816606feb4b67d35589382746c98c7fa00308f
refs/heads/master
2021-01-10T15:23:05.251381
2016-02-23T15:21:16
2016-02-23T15:21:16
52,381,411
0
0
null
null
null
null
UTF-8
C++
false
false
697
h
game.h
#ifndef GAME_H #define GAME_H #include <QObject> #include <QDebug> #include "constraints.h" #include "bot.h" class Game : public QObject{ Q_OBJECT private: Bot m_bot; bool m_currentPlayer; int m_field[FIELD_SIZE][FIELD_SIZE]; int m_moveCount; int m_winType; int m_winPoint; bool checkEnd(); void move(int x, int y); public: explicit Game(QObject *parent = 0); bool isEnded(); bool isPlayerWin(); bool playerMove(int x, int y); int getWinType(); int getWinPoint(); QString getBotAction(); void getField(int field[FIELD_SIZE][FIELD_SIZE]); void restart(); void setBotType(bool type); ~Game(); }; #endif // GAME_H
d96c5b5a7a6878fcca1b49db5d9c174eb958ab9c
ea7f49f4bb6c1d5384f2487b6886625b8b279aa4
/test_map/robot.hpp
06258062c23398f5d3a9e38ba2277254795ead71
[]
no_license
Ekleog/TIPE
e121386476e7a4401853f6e453ea756972882772
c39993b5395962b11db2c33c9123842827209632
refs/heads/master
2020-05-24T15:38:44.682064
2014-01-04T14:58:49
2014-01-04T14:58:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
735
hpp
robot.hpp
#ifndef TEST_MAP_ROBOT_HPP_INCLUDED_ #define TEST_MAP_ROBOT_HPP_INCLUDED_ 0 namespace lg { namespace test_map { class robot { float x_, y_, bx_, by_; // robot x, y, beacon x, y public: robot(float x, float y, float bx, float by) : x_(x), y_(y), bx_(bx), by_(by) { } void move(float dx, float dy) { x_ += dx; y_ += dy; } void move_beacon(float dx, float dy) { bx_ += dx; by_ += dy; } float sense() const { float dx = x_ - bx_, dy = y_ - by_; return dx * dx + dy * dy; } float x() const { return x_; } float y() const { return y_; } float beacon_x() const { return bx_; } float beacon_y() const { return by_; } }; }} #endif
28abcd2d3f7d4ebe1bd2d899bd06fb64ceb23d60
7992352e97f30be6054c2aec3a2c4348a275e0ee
/src/pathconverter.h
d1346cde48a36ba5b5cf11dd1f80ac93e2f7fbf4
[]
no_license
RyosukeHonda/PathPlanning
c68025762d51e36e907627d20c2c0fab771341cb
5e0e7a8bebc320d06ff50b7548750bd335c6a524
refs/heads/master
2021-01-01T18:09:53.629103
2017-08-06T14:37:27
2017-08-06T14:37:27
98,265,128
1
1
null
null
null
null
UTF-8
C++
false
false
767
h
pathconverter.h
#ifndef PATHCONVERTER_H_ #define PATHCONVERTER_H_ #include <string> #include <sstream> #include <iostream> #include <fstream> #include <math.h> #include <vector> #include "spline.h" #include "helper.h" #include "jmt.h" class PathConverter{ public: //Import waypoints data into memory PathConverter(std::string file_path, double distance); // from frenet coordinate to cartesian coordinate std::vector<double> convert_sd_to_xy(double s, double d); // Generate path from the calculated jerk minimizing trajectory XYPoints generate_path(JMT jmt_s, JMT jmt_d, double t,int n); private: double distance; tk::spline x_spline; tk::spline y_spline; tk::spline dx_spline; tk::spline dy_spline; }; #endif // PATHCONVERTER_H_
d9b0856d56da5c655fc2e521ca1181c1b62c89ad
33cc75a925b12133bc78fe0f307140878bb093b6
/cf/1028/A/main.cpp
8f50e70cec788b76e4a97eced260c549c3f3af10
[]
no_license
redeff/cmp
05603369f404cff25d168105b1f1c7a956fd07b8
8974bacf61b6c73d1cb5d3b5aa33c12af0d687d0
refs/heads/master
2021-05-08T01:10:47.542693
2019-10-13T22:19:32
2019-10-13T22:19:32
107,782,810
0
0
null
null
null
null
UTF-8
C++
false
false
462
cpp
main.cpp
#include <bits/stdc++.h> using namespace std; typedef long long int ll; int main() { ll n, m; cin >> n >> m; ll x = 0; ll y = 0; ll total = 0; for(int i = 0; i < n; ++i) { string s; cin >> s; for(int j = 0; j < m; ++j) { if(s[j] == 'B') { x += i; y += j; total++; } } } cout << 1 + x/total << " " << 1 + y/total << endl; }
7e9126ac4148101eb0ffd56e15bff90518002860
71b2597cb54b13a9ba2f8ea228a3baa2803a54a1
/utils/debug.cc
4696aad83e4921c026f4e2f781522db333a27f14
[ "Apache-2.0" ]
permissive
wurikiji/forestdb-flash
875b582b6225b49cc1a18f65a07f33fcb44b269c
8248dfd677572577bb523890fdab86ed146a3292
refs/heads/master
2021-09-22T19:09:58.049467
2017-08-22T05:11:46
2017-08-22T05:11:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,047
cc
debug.cc
#include "debug.h" #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include "time_utils.h" #include "backtrace.h" #include "breakpad.h" #include "fdb_internal.h" #define N_DBG_SWITCH (256) static uint8_t _global_dbg_switch[N_DBG_SWITCH]; static void* _global_dbg_addr[N_DBG_SWITCH]; static uint64_t _global_dbg_uint64_t[N_DBG_SWITCH]; fdb_fatal_error_callback fatal_error_callback = nullptr; // minidump_dir used by breakpad static const char* minidump_dir = nullptr; // LCOV_EXCL_START void _dbg_sw_set(int n) { _global_dbg_switch[n] = 1; } void _dbg_sw_clear(int n) { _global_dbg_switch[n] = 0; } void _dbg_set_addr(int n, void *addr) { _global_dbg_addr[n] = addr; } void * _dbg_get_addr(int n) { return _global_dbg_addr[n]; } void _dbg_set_uint64_t(int n, uint64_t val) { _global_dbg_uint64_t[n] = val; } uint64_t _dbg_get_uint64_t(int n) { return _global_dbg_uint64_t[n]; } int _dbg_is_sw_set(int n) { return _global_dbg_switch[n]; } void _dbg_set_minidump_dir(const char *pathname) { minidump_dir = pathname; } static void write_callback(void *ctx, const char *frame) { fprintf(stderr, "\t%s\n", frame); } void fdb_assert_die(const char* expression, const char* file, int line, uint64_t val, uint64_t expected) { fprintf(stderr, "assertion failed [%s] at %s:%u (%p != %p)\n", expression, file, line, (void*)val, (void*)expected); fprintf(stderr, "Called from:\n"); print_backtrace(write_callback, nullptr); fflush(stderr); // Invoke the fatal error callback if registered. if (fatal_error_callback != nullptr) { fatal_error_callback(); } char *hang_process = getenv("HANG_ON_ASSERTION"); if (hang_process) { fprintf(stderr, "Hanging process..."); fprintf(stderr, "\n"); while (1) { usleep(1000); } } // Initialize breakpad to create minidump for the // following abort initialize_breakpad(minidump_dir); abort(); } // LCOV_EXCL_STOP
068f0632d81268d89c7daa7ffb7c90473c242ef4
baca38a1e2f2e94108d205d2a6c70e84bcc64642
/PUSH/PlayerBall.cpp
d5043b3b1b024e7e6fd8f4c6bd40b98dcebda04f
[]
no_license
arata-nvm/Edge-of-Tomorrrow
6564470c291d221b0735fb981cae942e9f74a633
a220994dab431de48e872a83c85db8a69bc707c5
refs/heads/master
2020-09-03T14:46:23.533105
2019-11-02T14:41:12
2019-11-02T14:41:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
786
cpp
PlayerBall.cpp
#include "PlayerBall.hpp" PlayerBall::PlayerBall(P2World& world, Rect stageRect, int size) : Ball::Ball(world, stageRect, size) { } Vec2 PlayerBall::getPos() const { return body.getPos(); } void PlayerBall::update() { int scale = 15; if (KeyUp.pressed() || KeyW.pressed() || KeyK.pressed()) { body.applyLinearImpulse(Vec2(0, -scale)); } if (KeyLeft.pressed() || KeyA.pressed() || KeyH.pressed()) { body.applyLinearImpulse(Vec2(-scale, 0)); } if (KeyDown.pressed() || KeyS.pressed() || KeyJ.pressed()) { body.applyLinearImpulse(Vec2(0, scale)); } if (KeyRight.pressed() || KeyD.pressed() || KeyL.pressed()) { body.applyLinearImpulse(Vec2(scale, 0)); } body.setVelocity(body.getVelocity() * 0.99); } void PlayerBall::draw() const { body.draw(Palette::Pink); }
9da9f2cc62882fa56048fa8205b70c5bcbd41d9e
b21f3d57ec44877cfd8e3bb64cc387f826b55d0a
/RSALib/Main.cpp
baa45b3cd31d6f152e1255bbaa1b8e7ba6cc4f13
[]
no_license
Bhavya/RSALib
721ed626497ec282d2fac4432e5bec9c35b75ec0
59baf9511058feae2da755a236baf1559e8f567d
refs/heads/master
2021-01-11T23:23:53.736923
2017-01-11T07:12:48
2017-01-11T07:12:48
78,577,548
1
0
null
null
null
null
UTF-8
C++
false
false
209
cpp
Main.cpp
#include <iostream> #include <conio.h> #include "RSA.h" using namespace std; int main(int argc, char* argv[]) { //Example here. RSA Alice; RSA Bob; cout << "Hello World" << endl; getch(); return 0; }
a7575388649e4cef713df6ddcd12ab2645dd9a71
c254c37b30fba0c41b3157dd5581e03035df43c1
/C++ Solutions/URI/2143 - The Return of Radar.cpp
f4db2e382756bfc33734e86e6600a48cfaf2318d
[]
no_license
AntonioSanchez115/Competitive-Programming
12c8031bbb0c82d99b4615d414f5eb727ac5a113
49dac0119337a45fe8cbeae50d7d8563140a3119
refs/heads/master
2022-02-14T10:51:19.125143
2022-01-26T07:59:34
2022-01-26T07:59:34
186,081,160
1
0
null
null
null
null
UTF-8
C++
false
false
256
cpp
2143 - The Return of Radar.cpp
#include <bits/stdc++.h> using namespace std; int main() { int t; while(cin>>t && t!=0){ int n; for(int i=0;i<t;i++){ cin>>n; cout<<((n%2==0)?((n-2)*2+2):((n-1)*2+1))<<'\n'; } } return 0; }
1b1567f22c58150d15bfea98f2dd7ec5da515482
5099b2f4e87d81171339a5da83bfcb77b862e136
/lib/src/checkers/helper/clangtojson.cpp
9d3b529b6f8ef25bfc5e8f35b9c17ea6f79330d9
[ "MIT", "NCSA" ]
permissive
USECAP/ci-tools
32617652a46bc09bdef4f1332d11c3fbccc6e561
ad2300e3297266ff3ee6ed9118ccd16fc05291e3
refs/heads/master
2020-03-20T19:42:37.580757
2018-06-21T10:41:36
2018-06-21T12:42:07
137,649,996
0
0
null
null
null
null
UTF-8
C++
false
false
1,185
cpp
clangtojson.cpp
#include "clangtojson.h" #include <clang/AST/AST.h> using namespace nlohmann; using namespace clang; namespace { std::vector<json> createParameterObjects(const FunctionDecl *F, const SourceManager &SM) { std::vector<json> params; params.reserve(F->param_size()); std::transform(F->param_begin(), F->param_end(), std::back_inserter(params), [&](ParmVarDecl *P) -> nlohmann::json { return ToJson(P, SM); }); return params; } } // end anonymous namespace json ToJson(const FunctionDecl *F, const SourceManager &SM) { return { {"name", F->getQualifiedNameAsString()}, {"visible", F->getVisibility()}, {"location", ToJson(F->getSourceRange(), SM)}, {"parameters", createParameterObjects(F, SM)} }; } json ToJson(SourceRange SR, const SourceManager &SM) { return {SR.getBegin().printToString(SM), SR.getEnd().printToString(SM)}; } json ToJson(const ParmVarDecl *P, const SourceManager &SM) { return { {"name", P->getQualifiedNameAsString()}, {"type", P->getType().getAsString()}, {"location", ToJson(P->getSourceRange(), SM)} }; }
8ce5f055d482fd8648e35839df78f17cbe36a130
1bdb9b8baf341e71bde5c471d293e082c3def401
/GameTemplate/Game/Game.h
5c15a2de9ea60609834914369438d39b67597881
[]
no_license
TakuyaI/GameSeisaku
6f8fc5915eeba5f84ea3e4c4808f9761712fff99
e82f46324ad23e54e4225670d3afcd07fe6a8fa8
refs/heads/master
2020-06-27T12:37:03.837654
2019-09-26T07:25:14
2019-09-26T07:25:14
199,956,212
0
0
null
null
null
null
UTF-8
C++
false
false
272
h
Game.h
#pragma once class GameCamera; #include "IGameObject.h" #include "Player.h" #include "BackGround.h" #include "GameCamera.h" class Game : public IGameObject { public: Game(); ~Game(); void Update(); private: Player* player; BackGround* back; GameCamera* gc; };
12d9ce25f9ddd63f641d1b79be3cec4eb8b9ffad
17310661cbaea41d68baea32c2a977f80f46751f
/Source/CollisionWar/SRC/Game/Battle/Physics/PhysActorSonClass/DetonationActor.cpp
5bf411251d68b3e09236a6abbb00f8753dbb0ba1
[]
no_license
VectorL1990/CollisionWarBackup
5540807c23193215d0a50e4826978d5f2430c243
8e263ab498f9097c57f6a1ef78719607b66cfc9f
refs/heads/main
2023-04-10T15:17:05.678311
2021-04-23T08:16:05
2021-04-23T08:16:05
357,766,090
0
0
null
2021-04-23T08:16:05
2021-04-14T03:51:57
C++
GB18030
C++
false
false
4,899
cpp
DetonationActor.cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "CollisionWar.h" #include "../PhysCalculator.h" #include "Kismet/KismetMaterialLibrary.h" #include "DetonationActor.h" ADetonationActor::ADetonationActor() { PrimaryActorTick.bCanEverTick = true; /*m_pFixComponent = CreateDefaultSubobject<USphereComponent>(TEXT("FixComponent")); m_pFixComponent->SetSimulatePhysics(false); m_pFixComponent->SetCollisionProfileName(TEXT("OverlapAll")); m_pFixComponent->bGenerateOverlapEvents = true; m_pFixComponent->SetSphereRadius(10); RootComponent = m_pFixComponent;*/ m_physGeoType = EPhysGeoType::PGT_DetonationActor; //m_physActorLifeTime = 0; //m_isCollectable = true; m_pAttachEquipInfo = NULL; } void ADetonationActor::Tick(float DeltaSeconds) { if (m_detonationState != 1) return; if (m_curDetonationTime >= m_detonationInfo.detonationTime) { //要爆炸了 m_isGeoValid = false; UGameplayStatics::SpawnEmitterAtLocation(m_pPhysCalculator, m_pTransformPS[1], GetActorLocation(), GetActorRotation(), true); ABasePhysGeo* pPhysGeo = GetWorld()->SpawnActor<ABasePhysGeo>(m_mutateGeoClass, GetActorLocation(), GetActorRotation()); if (m_pPhysCalculator) m_pPhysCalculator->AddPhysGeo(pPhysGeo, m_pHost, m_campFlag); m_detonationState = 2; } else { m_curDetonationTime += DeltaSeconds; UMaterialInterface* pMaterialInterface = m_pBasicSMComponent->GetMaterial(0); if (!pMaterialInterface) return; UMaterialInstanceDynamic* pMI = Cast<UMaterialInstanceDynamic>(pMaterialInterface); if (!pMI) return; float detonationIndex = m_curDetonationTime / m_detonationInfo.detonationTime; pMI->SetScalarParameterValue(FName("EmissionScale"), detonationIndex); if (m_pWaitReactionGeos.Num() <= 0 || !m_pPhysCalculator) return; for (int32 i = 0; i < m_pWaitReactionGeos.Num(); i++) { if (!m_pWaitReactionGeos[i] || m_pWaitReactionGeos[i]->m_pRootGeos.Contains(this) || m_pRootGeos.Contains(m_pWaitReactionGeos[i])) continue; GeoReaction(m_pWaitReactionGeos[i]); } m_pWaitReactionGeos.Empty(); } } void ADetonationActor::SetSMComponent(UStaticMeshComponent* pSMComponent) { if (!pSMComponent) return; m_pBasicSMComponent = pSMComponent; } /* void ADetonationActor::UpdateProjectileMovement(float dT) { }*/ void ADetonationActor::InitialDetonationActor() { if (m_detonationInfo.detonationType == 0) m_detonationState = 1; UMaterialInstanceDynamic* pMI = UKismetMaterialLibrary::CreateDynamicMaterialInstance(this, m_pPhysCalculator->m_pCWSingleton->m_detonationMaterial); m_pBasicSMComponent->SetMaterial(0, pMI); } void ADetonationActor::ActivateDetonation(class AActor* otherActor, class UPrimitiveComponent* OtherComp) { if (m_detonationInfo.detonationType == 0 || m_detonationState == 1) return; if (!otherActor || !OtherComp) return; //生成引爆提示特效 if (OtherComp) { if (OtherComp->ComponentHasTag(FName(TEXT("BaseCharacter")))) { ABaseCharacter* pCharacter = Cast<ABaseCharacter>(otherActor); if (!pCharacter) return; if (m_detonationInfo.detonationCharacterType == 0 && pCharacter->m_characterType == 1) m_detonationState = 1; else if (m_detonationInfo.detonationCharacterType == 1 && pCharacter->m_characterType == 0) m_detonationState = 1; } } } void ADetonationActor::OnBaseComponentBeginOverlap(class AActor* otherActor, class UPrimitiveComponent* OtherComp) { if (otherActor && otherActor == this) return; if (OtherComp) { if (OtherComp->ComponentHasTag(FName(TEXT("BaseCharacter")))) { ABaseCharacter* pCharacter = Cast<ABaseCharacter>(otherActor); if (!pCharacter) return; if (!m_pOverlapCharacters.Contains(pCharacter)) m_pOverlapCharacters.Add(pCharacter); ActivateDetonation(otherActor, OtherComp); } if (OtherComp->ComponentHasTag(FName(TEXT("BasePhysGeo")))) { ABasePhysGeo* pGeo = Cast<ABasePhysGeo>(otherActor); if (pGeo->m_pBasicComponent->ComponentHasTag(FName(TEXT("TimeDilation")))) { if (!m_timeDilationParams.Contains(GetName())) { for (int32 i = 0; i < pGeo->m_effectParamList.Num(); i++) { if (pGeo->m_effectParamList[i].effectName != "TimeDilation" || (pGeo->m_effectParamList[i].effectExertType == 0 && pGeo->m_campFlag == m_campFlag)) continue; m_timeDilationParams.Add(pGeo->GetName(), pGeo->m_effectParamList[i].duration); if (CustomTimeDilation >= ((float)pGeo->m_effectParamList[i].effectValues[0]) / 100.f) CustomTimeDilation = ((float)pGeo->m_effectParamList[i].effectValues[0]) / 100.f; break; } } } if (!pGeo || !pGeo->m_isGeoValid || OtherComp->ComponentHasTag(FName(TEXT("PhysPolygon"))) || OtherComp->ComponentHasTag(FName(TEXT("PhysPoint"))) || (m_isOneTimeReaction && m_hasTriggerReaction) || (pGeo->m_isOneTimeReaction && pGeo->m_hasTriggerReaction)) return; m_pWaitReactionGeos.Add(pGeo); } } }
4216ff6cccd74be634c9b6c0d18ead3c136e4a36
d9c905b07b75b73c423e870fe582f0d3008cde34
/30.cpp
3b4388f44d37dcef1df8b64d197a38dfb8535246
[]
no_license
pablo-mirtor/TAIS
0c6f34898de8b4bf45eda3712efd9bd451c2cdcd
c8bc23542070eb5bd051e5cc8473f08c15584e5a
refs/heads/master
2020-07-27T02:24:54.469670
2019-11-14T19:04:06
2019-11-14T19:04:06
208,836,099
0
0
null
null
null
null
UTF-8
C++
false
false
1,644
cpp
30.cpp
// Pablo Miranda Torres #include <iostream> #include <fstream> #include <vector> #include "Grafo.h" using namespace std; class grafoBipartito{ private: vector<bool> marked; vector<int> valor; //grafo que asigna valores a los nodos (1 un color, 2 otro, 0 sin asignar) bool bipartito; void dfs(Grafo const & g, int v){ for(int i : g.ady(v)){ marked[v] = true; if(valor[i] == 0){ if(valor[v] == 1) valor[i] = 2; else valor[i] = 1; } else if(valor[i] == valor[v]) bipartito = false; if(!marked[i]) dfs(g,i); } } public: grafoBipartito(){}; //Coste O(V+E) por algoritmo dfs grafoBipartito(Grafo const & g) : marked(g.V(), false) , valor(g.V(), 0), bipartito(true) { for(int i = 0; i < g.V(); ++i){ if(!marked[i]){ valor[i] = 1; dfs(g, i); } } } bool esBipartito() const {return bipartito;} }; bool resuelveCaso() { int V, E; std::cin>> V >> E; if (!cin) return false; Grafo grafo = Grafo(V); for(int i = 0; i < E; i++){ int v1, v2; cin>>v1>>v2; grafo.ponArista(v1,v2); } grafoBipartito gb(grafo); if(gb.esBipartito()) cout << "SI\n"; else cout << "NO\n"; return true; } int main() { #ifndef DOMJUDGE std::ifstream in("../Casos/30.txt"); auto cinbuf = std::cin.rdbuf(in.rdbuf()); #endif while (resuelveCaso()); #ifndef DOMJUDGE std::cin.rdbuf(cinbuf); #endif return 0; }
0c7def01722def02ce4f94e37179fe03e109e002
fbec58fa85c55f9278a72829db65c4845a394ad3
/Shiny/Threading/Thread.h
88d3014d3331a741f99995bd5b7a21ce3845e51f
[]
no_license
ekalchev/Shiny
02da492a469f1c57e2b6962102c9346984bc8525
d0e2355bd80d355ff142d36c945bb08fca417d7a
refs/heads/master
2021-01-10T21:59:47.168543
2014-12-01T18:13:44
2014-12-01T18:13:44
27,392,665
1
0
null
null
null
null
UTF-8
C++
false
false
767
h
Thread.h
/////////////////////////////////////////////////////////////////////////////// // File: Thread.h // Author: Emil Kalchev // E-mail: developer@engineer.bg /////////////////////////////////////////////////////////////////////////////// #ifndef __THREAD__ #define __THREAD__ #include <windows.h> class Task; class TaskManager; class Thread; class Semaphore; class Thread { private: HANDLE thread; DWORD dwGenericThread; volatile bool bWorking; TaskManager* taskManager; int id; Task *task; Semaphore *semaphore; private: static DWORD WINAPI threadFunc(LPVOID param); public: Thread(); ~Thread(); void Create(TaskManager* man,Semaphore* sem); bool isWorking(); void Destroy(); }; inline bool Thread::isWorking() { return bWorking; } #endif
254c9a6a140f1b657378737c9e9973e0a68d5285
0ff2f10af8f14e1dbc777816b2f3a8eea9c4de4e
/FrameInfo.cpp
459e74f3c8bf3653748725a7c1532471e4055513
[]
no_license
jupengfei-github/Frame-Animation-Based-SurfaceFlinger
71279b92b28a31249670aaed6e6f7c4e1ad7ec49
f7b886096b790b92bc87eac18b88e04a5841fc3b
refs/heads/master
2020-03-24T20:08:23.357329
2018-07-31T04:19:07
2019-01-19T13:30:49
142,961,653
7
0
null
null
null
null
UTF-8
C++
false
false
10,892
cpp
FrameInfo.cpp
/* * Copyright (C) 2018-2024 The Surface Frame-Animation 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. */ #include <regex> #include <sstream> #include <fstream> #include <androidfw/ZipFileRO.h> #include <androidfw/Asset.h> #include <androidfw/AssetManager.h> #include <androidfw/ResourceTypes.h> #include <cutils/properties.h> #include "FrameInfo.h" #include "FrameDisplay.h" using namespace std; using namespace android; namespace frame_animation { /* String -> T */ template<typename T> T lexical_cast(const string& s) { T rt; istringstream iss(s); iss>>rt; return rt; } /* desc file key/value */ const string FrameInfo::DESC_KEY_MODE = "mode"; const string FrameInfo::DESC_KEY_RESOLUTION = "resolution"; const string FrameInfo::DESC_KEY_RATE = "rate"; const string FrameInfo::DESC_KEY_FRAMES = "frames"; const string FrameInfo::DESC_KEY_FRAME_PATH = "frame_path"; const string FrameInfo::FRAME_MODE_REVERSE_STR = "reverse"; const string FrameInfo::FRAME_MODE_REPEATE_STR = "repeat"; const string FrameInfo::FRAME_MODE_NORMAL_STR = "normal"; /* PROP */ const string FrameInfo::PROP_SDK_VERSION = "ro.build.version.sdk"; /* desc file name */ const string FrameInfo::ENTRY_DESC = "desc.txt"; int FrameInfo::count() { return info.frames.size(); } AnimMode FrameInfo::mode() { return info.mode; } int FrameInfo::rate() { return info.rate; } Size FrameInfo::size() { return info.size; } AnimMode FrameInfo::frame_mode (const string& value) const { if (value == FRAME_MODE_NORMAL_STR) return FRAME_MODE_NORMAL; else if (value == FRAME_MODE_REPEATE_STR) return FRAME_MODE_REPEATE; else if (value == FRAME_MODE_REVERSE_STR) return FRAME_MODE_REVERSE; else return FRAME_MODE_NORMAL; } void FrameInfo::dump () const { FPLog.I()<<"FrameInfo : "<<endl; FPLog.I()<<"Path : "<<info.frame_path<<endl; FPLog.I()<<"Mode : "<<info.mode<<endl; FPLog.I()<<"Rate : "<<info.rate<<endl; FPLog.I()<<"Size : ["<<info.size.width<<"x"<<info.size.height<<"]"<<endl; } void FrameInfo::parse_desc_item(const string& key, const string& value) { if (key == DESC_KEY_RESOLUTION) { regex resolution_regex("(\\d+)x(\\d+)"); smatch result; if (regex_search(value, result, resolution_regex)) { info.size.width = lexical_cast<int>(string(result[1].first, result[1].second)); info.size.height = lexical_cast<int>(string(result[2].first, result[2].second)); } else FPLog.E()<<"invalide resoution : "<<value<<endl; } else if (key == DESC_KEY_RATE) info.rate = lexical_cast<int>(value); else if (key == DESC_KEY_FRAMES) { regex frame_regex("[\\w\\.]+"); smatch frame_match; string ite_value = value; while (regex_search(ite_value, frame_match, frame_regex)) { info.frames.push_back(string(frame_match[0].first, frame_match[0].second)); ite_value = frame_match.suffix().str(); } } else if (key == DESC_KEY_FRAME_PATH) info.frame_path = value; else if (key == DESC_KEY_MODE) info.mode = frame_mode(value); else FPLog.E()<<"illegal desc item : "<<value<<endl; } void FrameInfo::parse_anim_info () { string anim_str = parse_anim_file(); regex item_pattern("\\s*(\\w+)\\s*:\\s*\\[([^\\[\\]]+)\\]"); smatch item_match; string ite_str = anim_str; while (regex_search(ite_str, item_match, item_pattern)) { string key_item(item_match[1].first, item_match[1].second); string value_item(item_match[2].first, item_match[2].second); parse_desc_item(key_item, value_item); ite_str = item_match.suffix().str(); } max_frame = info.frames.size(); dump(); } shared_ptr<FrameInfo> FrameInfo::create_from_type (const string& path, AnimResType type) { shared_ptr<FrameInfo> frame_info; if (FRAME_RES_TYPE_APK == type) { shared_ptr<AssetManager> assetManager(new AssetManager()); String8 s8_path(path.c_str(), path.length()); if (!assetManager->addAssetPath(s8_path, nullptr)) throw new parse_exception("parse_apk_frame addAssetPath fail"); const ResTable_config config = default_resource_config(); assetManager->setConfiguration(config); frame_info = shared_ptr<FrameInfo>(new ApkFrameInfo(assetManager)); } else if (FRAME_RES_TYPE_ZIP == type) { shared_ptr<ZipFileRO> zip_file(ZipFileRO::open(path.c_str())); if (!zip_file.get()) throw parse_exception("open " + path + " fail"); frame_info = shared_ptr<FrameInfo>(new ZipFrameInfo(zip_file)); } else if (FRAME_RES_TYPE_DIR == type) { frame_info = shared_ptr<FrameInfo>(new DIRFrameInfo(path)); } else throw new parse_exception("unknown anim_res_type " + path); frame_info->parse_anim_info(); return frame_info; } ResTable_config FrameInfo::default_resource_config () { char prop_value[PROPERTY_VALUE_MAX]; ResTable_config config; DisplayMetrics dm; /* any */ config.mnc = 0; config.mcc = 0; strncpy(config.language, "en", 2); strncpy(config.country, "US", 2); config.density = dm.density(); config.orientation = ResTable_config::ORIENTATION_PORT; config.touchscreen = ResTable_config::TOUCHSCREEN_FINGER; config.keyboard = ResTable_config::KEYBOARD_NOKEYS; config.navigation = ResTable_config::NAVIGATION_NONAV; config.inputFlags = ResTable_config::KEYSHIDDEN_YES; config.screenWidth = dm.width(); config.screenHeight = dm.height(); property_get(PROP_SDK_VERSION.c_str(), prop_value, "4"); config.sdkVersion = atoi(prop_value); config.minorVersion = 0; config.screenLayout = ResTable_config::LAYOUTDIR_LTR; config.uiMode = ResTable_config::UI_MODE_TYPE_NORMAL; config.smallestScreenWidthDp = ResTable_config::SCREENSIZE_NORMAL; config.screenWidthDp = 0; config.screenHeightDp = 0; config.screenLayout2 = ResTable_config::SCREENROUND_NO; config.colorMode = ResTable_config::HDR_NO; return config; } // ------------------------------------------------ shared_ptr<istream> ZipFrameInfo::frame (int idx) { if (idx >= max_frame) { FPLog.E()<<"frame ignore overflow frame index cur_frame="<<idx<<" max_frame="<<max_frame<<endl; idx = max_frame - 1; } string frame_name = info.frames[idx]; return shared_ptr<istream>(new istream(new ZipStreamBuf(zip_file, info.frame_path + "/" + frame_name))); } string ZipFrameInfo::parse_anim_file () { ZipEntryRO desc = zip_file->findEntryByName(ENTRY_DESC.c_str()); if (desc == nullptr) throw parse_exception("find entry " + ENTRY_DESC + " fail"); auto_ptr<FileMap> file_map(zip_file->createEntryFileMap(desc)); string desc_str(static_cast<char*>(file_map->getDataPtr()), file_map->getDataLength()); delete file_map.release(); zip_file->releaseEntry(desc); return desc_str; } // ----------------------------------------------- const string ApkFrameInfo::APK_PACKAGE = "animation"; const string ApkFrameInfo::APK_NAME = "desc"; const string ApkFrameInfo::APK_DESC_TYPE = "raw"; const string ApkFrameInfo::APK_ANIM_TYPE = "drawable"; shared_ptr<istream> ApkFrameInfo::frame (int idx) { const ResTable& resTable = assetManager->getResources(); if (idx >= max_frame) { FPLog.E()<<"frame ignore overflow frame index cur_frame="<<idx<<" max_frame="<<max_frame<<endl; idx = max_frame -1; } string name = info.frames[idx]; String16 s16_name = String16(name.c_str(), name.length()); String16 s16_type = String16(APK_ANIM_TYPE.c_str()); String16 s16_pkg = String16(APK_PACKAGE.c_str()); uint32_t id = resTable.identifierForName(s16_name, s16_name.size(), s16_type, s16_type.size(), s16_pkg, s16_pkg.size()); Res_value value; ssize_t index = resTable.getResource(id, &value); const ResStringPool *strPool = resTable.getTableStringBlock(index); size_t len; const char* str = strPool->string8At(value.data, &len); string real_path(str, len); shared_ptr<Asset> asset(assetManager->openNonAsset(real_path.c_str(), Asset::ACCESS_STREAMING)); return shared_ptr<istream>(new istream(new ResStreamBuf(asset))); } string ApkFrameInfo::parse_anim_file () { const ResTable& resTable = assetManager->getResources(); String16 s16_name(APK_NAME.c_str()); String16 s16_type(APK_DESC_TYPE.c_str()); String16 s16_pkg(APK_PACKAGE.c_str()); uint32_t id = resTable.identifierForName(s16_name, s16_name.size(), s16_type, s16_type.size(), s16_pkg, s16_pkg.size()); if (id == 0) { FPLog.E()<<"obtain identifier "<<APK_NAME<<" fail"; return string(); } Res_value value; ssize_t index = resTable.getResource(id, &value); const ResStringPool *stringPool = resTable.getTableStringBlock(index); size_t len; const char *str = stringPool->string8At(value.data, &len); string real_path(str, len); auto_ptr<Asset> asset(assetManager->openNonAsset(real_path.c_str(), Asset::ACCESS_STREAMING)); string desc_str(static_cast<const char*>(asset->getBuffer(true)), asset->getLength()); asset->close(); return desc_str; } // ---------------------------------------------- shared_ptr<istream> DIRFrameInfo::frame (int idx) { if (idx >= max_frame) { FPLog.E()<<"next_frame ignore overflow frame index cur_frame="<<idx<<" max_frame="<<max_frame<<endl; idx = max_frame -1; } string frame_name = info.frames[idx]; string path = parent_path + "/" + info.frame_path + "/" + frame_name; shared_ptr<istream> ifm(new ifstream(path)); if (!ifm->good()) { FPLog.E()<<"frame open "<<path<<" failed"<<endl; return shared_ptr<istream>(nullptr); } return ifm; } string DIRFrameInfo::parse_anim_file () { string path = parent_path + "/" + ENTRY_DESC; ifstream ifm(path); if (!ifm.good()) { FPLog.E()<<"parse_dir_frame open "<<path<<" fail"<<endl; ifm.close(); return string(); } string desc_str; string tmp; while (ifm>>tmp) { desc_str += tmp; } ifm.close(); return desc_str; } }; //namespace frame_animation
281381ff369fbf9c014b00ae4883db701e644399
cf24ffc50dcf66994b13ad39619382109f31ecab
/Client.cpp
9790717b8995220f707b34ee04938a99eac45724
[]
no_license
lamentae/Insurance
319a6a6eded8d7c87688e3144f83df596133ddd8
31b559573e35a4a80878e711485051b88ae7d8e5
refs/heads/master
2020-07-16T15:17:31.701601
2016-11-16T17:35:50
2016-11-16T17:35:50
73,944,589
0
0
null
null
null
null
UTF-8
C++
false
false
497
cpp
Client.cpp
#include "Client.h" #include <iostream> using namespace std; int Client::total_client_id = 123456; Client::Client(string pname, Date bday) { name = pname; birth_date = bday; client_id = total_client_id; total_client_id++; } Client::~Client() { } void Client::print() { cout << name<< endl; cout <<"DOB:"; birth_date.print(); cout<<endl; cout << "Client ID: " << client_id<<endl; } int Client::getclient_id() { return client_id; }
dd01f5237cdbef2d90184f7503d5d22961f7b927
66c192974698f7844e6331c70144d09416090f39
/Day05/ex02/PresidentialPardonForm.hpp
d492973382541f28a25b1fedd730574b5d62402c
[]
no_license
Ymarji/cpp_picine
a29a2cef43de5410631226ac4b8e7779acdd9911
1dc03a50b0723eb90648b7e3e6be8daf9fa8aff4
refs/heads/main
2023-08-04T08:04:22.381071
2021-09-24T12:54:33
2021-09-24T12:54:33
378,615,927
1
0
null
null
null
null
UTF-8
C++
false
false
1,406
hpp
PresidentialPardonForm.hpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* PresidentialPardonForm.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ymarji <ymarji@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/09/02 13:40:19 by ymarji #+# #+# */ /* Updated: 2021/09/03 16:53:59 by ymarji ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef PRESIDENTIALPARDONFORM_HPP #define PRESIDENTIALPARDONFORM_HPP #include "Form.hpp" class PresidentialPardonForm: public Form { private: public: PresidentialPardonForm(); PresidentialPardonForm(std::string); PresidentialPardonForm(PresidentialPardonForm const &); virtual void formWork() const; PresidentialPardonForm &operator=(PresidentialPardonForm const &); virtual ~PresidentialPardonForm(); }; #endif /* PRESIDENTIALPARDONFORM_HPP */
7a7daedcab87bec1817fb73adcfe7779a59a78d0
7b62c2553d22c9e29a58c6d6ce66ed479942eb0e
/main.cpp
e2ae1d3a812f22913aeca543e4922c3e732064ba
[]
no_license
AnthonyB-04/Lab_1
b76502d8c75ff1f17c3712e7356fc63a51fc560f
f997dd7c2f45f15f2b9ba311a395e6d9dc779b4c
refs/heads/master
2021-03-01T17:18:12.224556
2020-03-08T11:42:15
2020-03-08T11:42:15
245,801,760
0
0
null
null
null
null
UTF-8
C++
false
false
1,047
cpp
main.cpp
#include <iostream> #include "fun.h" #include <cstdlib> #include <ctime> using namespace std; int main() { cout<<"Lab2-1_masyv_K-14_Anton_Budnyk"<<endl; int a[N]; for (int i = 0; i < N; i++) { a[i] = 0; cout << a[i] << "\t"; if ((i + 1) % 5 == 0) cout << "\n"; } cout<<"\n"<<"1 - заповнити масив псевдовипадковими числами"<<endl; cout<<"2 - введіть числа за допомогою клавіатури"<<endl; int k; cin>>k; vubir(k); cout << "Ваш масив заповнений. Натисніть: " << endl; cout <<"1.Якщо ви хочете додати элемент після першого максимального елемента та після кожного мінімального елемента 2.Якщо ви хочете сортувати методом bubblesort по зрастанню "<<endl; int b; cin >> b; SortArray(b); int c; cin >> c; return 0; }
e7e20435a39ddbc8a8ff1cab69fe0a0d5f508c05
03bda519e5248e292ee3ef0727a559d1372a00c5
/Lab3/dft_example/dft_main.cpp
ac0993ad2c9e7f48e72555e3b07949fef2701502
[]
no_license
dlimit7/Multimedia_Signal_Proc
850cb9634ba63510a573160f73081ff258d198ac
239e6c3f48e91bfcbc9b335898b790b1553a41c7
refs/heads/master
2020-03-28T03:17:08.212475
2019-02-15T05:41:18
2019-02-15T05:41:18
147,634,335
0
0
null
null
null
null
UTF-8
C++
false
false
5,887
cpp
dft_main.cpp
/*****************************************************************************/ // File: dft_main.cpp // Author: David Taubman // Last Revised: 28 August, 2007 /*****************************************************************************/ // Copyright 2007, David Taubman, The University of New South Wales (UNSW) /*****************************************************************************/ #include <math.h> #include "io_bmp.h" #include "image_comps.h" #include "dft.h" /* ========================================================================= */ /* Global Functions */ /* ========================================================================= */ /*****************************************************************************/ /* main */ /*****************************************************************************/ int main(int argc, char *argv[]) { if (argc != 3) { fprintf(stderr,"Usage: %s <in bmp file> <out bmp file>\n",argv[0]); return -1; } int err_code=0; try { // Read the input image bmp_in in; if ((err_code = bmp_in__open(&in,argv[1])) != 0) throw err_code; int width = in.cols, height = in.rows; int n, num_comps = in.num_components; my_image_comp *input_comps = new my_image_comp[num_comps]; for (n=0; n < num_comps; n++) input_comps[n].init(height,width,0); // No boundary extension required int r, c; // Declare row index io_byte *line = new io_byte[width*num_comps]; for (r=height-1; r >= 0; r--) { // "r" holds the true row index we are reading, since the image is // stored upside down in the BMP file. if ((err_code = bmp_in__get_line(&in,line)) != 0) throw err_code; for (n=0; n < num_comps; n++) { io_byte *src = line+n; // Points to first sample of component n float *dst = input_comps[n].buf + r * input_comps[n].stride; for (c=0; c < width; c++, src+=num_comps) dst[c] = (float) *src; // The cast to type "float" is not // strictly required here, since bytes can always be // converted to floats without any loss of information. } } bmp_in__close(&in); // Allocate storage for the output image my_image_comp *output_comps = new my_image_comp[num_comps]; for (n=0; n < num_comps; n++) output_comps[n].init(height,width,0); // No extension required // Allocate storage for DFT buffers int max_dim = height; if (max_dim < width) max_dim = width; float *dft_real = new float[height*width]; float *dft_imag = new float[height*width]; // Process the image, plane by plane. for (n=0; n < num_comps; n++) { // First copy all samples to the `dft_real' buffer int stride = input_comps[n].stride; for (r=0; r < height; r++) for (c=0; c < width; c++) { dft_real[r*width+c] = input_comps[n].buf[r*stride+c]; dft_imag[r*width+c] = 0.0F; } // Next, perform the 2D DFT // Put your code here // Write DFT magnitudes to the output image, possibly using a log // function to see the values more clearly. // Put your code here // Normalize the output image so that the maximum value is 255 // and clip to avoid negative values. float max_val = 0.0F; for (r=0; r < height; r++) for (c=0; c < width; c++) { float val = output_comps[n].buf[r*stride+c]; if (val > max_val) max_val = val; } float scale = 1.0F; if (max_val > 0.0F) scale = 255.0F / max_val; for (r=0; r < height; r++) for (c=0; c < width; c++) output_comps[n].buf[r*stride+c] *= scale; } // Write the image back out again bmp_out out; if ((err_code = bmp_out__open(&out,argv[2],width,height,num_comps)) != 0) throw err_code; for (r=height-1; r >= 0; r--) { // "r" holds the true row index we are writing, since the image is // written upside down in BMP files. for (n=0; n < num_comps; n++) { io_byte *dst = line+n; // Points to first sample of component n float *src = output_comps[n].buf + r * output_comps[n].stride; for (c=0; c < width; c++, dst+=num_comps) *dst = (io_byte) src[c]; } bmp_out__put_line(&out,line); } bmp_out__close(&out); delete[] line; delete[] input_comps; delete[] output_comps; delete[] dft_real; delete[] dft_imag; } catch (int exc) { if (exc == IO_ERR_NO_FILE) fprintf(stderr,"Cannot open supplied input or output file.\n"); else if (exc == IO_ERR_FILE_HEADER) fprintf(stderr,"Error encountered while parsing BMP file header.\n"); else if (exc == IO_ERR_UNSUPPORTED) fprintf(stderr,"Input uses an unsupported BMP file format.\n Current " "simple example supports only 8-bit and 24-bit data.\n"); else if (exc == IO_ERR_FILE_TRUNC) fprintf(stderr,"Input or output file truncated unexpectedly.\n"); else if (exc == IO_ERR_FILE_NOT_OPEN) fprintf(stderr,"Trying to access a file which is not open!(?)\n"); return -1; } return 0; }
90e3f9efaa6058c8ef768ab08b2071d43c063cc0
786de89be635eb21295070a6a3452f3a7fe6712c
/AppUtils/tags/V00-00-01/src/AppBase.cpp
c66e8d08f8c4bf33d25b4c2a93204ae972dca6b7
[]
no_license
connectthefuture/psdmrepo
85267cfe8d54564f99e17035efe931077c8f7a37
f32870a987a7493e7bf0f0a5c1712a5a030ef199
refs/heads/master
2021-01-13T03:26:35.494026
2015-09-03T22:22:11
2015-09-03T22:22:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,183
cpp
AppBase.cpp
//-------------------------------------------------------------------------- // File and Version Information: // $Id$ // // Description: // Class AppBase... // // Author List: // Andrei Salnikov // //------------------------------------------------------------------------ #include "Lusi/Lusi.h" //----------------------- // This Class's Header -- //----------------------- #include "AppUtils/AppBase.h" //----------------- // C/C++ Headers -- //----------------- #include <iostream> //------------------------------- // Collaborating Class Headers -- //------------------------------- //----------------------------------------------------------------------- // Local Macros, Typedefs, Structures, Unions and Forward Declarations -- //----------------------------------------------------------------------- namespace { /** * removes dirname from the path name */ std::string fixAppName ( const std::string& appName ) { std::string::size_type idx = appName.rfind('/') ; if ( idx != std::string::npos ) { return std::string ( appName, idx+1 ) ; } else { return appName ; } } } // ---------------------------------------- // -- Public Function Member Definitions -- // ---------------------------------------- namespace AppUtils { //---------------- // Constructors -- //---------------- AppBase::AppBase ( const std::string& appName ) : _cmdline( ::fixAppName(appName) ) , _optVerbose( 'v', "verbose", "verbose output, multiple allowed", 1 ) , _optQuiet( 'q', "quiet", "quieter output, multiple allowed", 0 ) { } //-------------- // Destructor -- //-------------- AppBase::~AppBase () { } /** * Run the application */ int AppBase::run ( int argc, char** argv ) { // parse command line, set all options and arguments bool ok = _cmdline.parse ( argc, argv ) ; if ( ! ok ) { std::cerr << "Error parsing command line: " << _cmdline.getErrorString() << "\n" ; _cmdline.usage( std::cerr ) ; this->moreUsage ( std::cerr ) ; return 2 ; } else if ( _cmdline.helpWanted() ) { _cmdline.usage( std::cout ) ; this->moreUsage ( std::cout ) ; return 0 ; } int stat = preRunApp() ; if ( stat != 0 ) return stat ; // call subclass for some real stuff stat = this->runApp() ; if ( stat != 0 ) return stat ; stat = postRunApp() ; if ( stat != 0 ) return stat ; return 0 ; } /** * add command line option or argument, typically called from subclass constructor */ bool AppBase::addOption ( AppCmdOptBase& option ) { return _cmdline.addOption ( option ) ; } bool AppBase::addArgument ( AppCmdArgBase& arg ) { return _cmdline.addArgument ( arg ) ; } /** * print some additional info after the usage information is printed. */ void AppBase::moreUsage ( std::ostream& out ) const { } /** * Method called before runApp, can be overriden in subclasses. * Usually if you override it, call base class method too. */ int AppBase::preRunApp () { return 0 ; } /** * Method called after runApp, can be overriden in subclasses. * Usually if you override it, call base class method too. */ int AppBase::postRunApp () { return 0 ; } } // namespace AppUtils
c001a80ec3d66281bc5863c2abb4b34c8e367468
0c7e20a002108d636517b2f0cde6de9019fdf8c4
/Sources/Elastos/Packages/Service/Telephony/src/elastos/droid/teleservice/phone/CCdmaCallOptions.cpp
752708de428767a2254a41d8cbce61a8cd68c26c
[ "Apache-2.0" ]
permissive
kernal88/Elastos5
022774d8c42aea597e6f8ee14e80e8e31758f950
871044110de52fcccfbd6fd0d9c24feefeb6dea0
refs/heads/master
2021-01-12T15:23:52.242654
2016-10-24T08:20:15
2016-10-24T08:20:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,188
cpp
CCdmaCallOptions.cpp
#include "elastos/droid/teleservice/phone/CCdmaCallOptions.h" #include "elastos/droid/teleservice/phone/PhoneGlobals.h" #include "R.h" #include "Elastos.Droid.Internal.h" #include "Elastos.Droid.Preference.h" using Elastos::Droid::Internal::Telephony::IPhone; using Elastos::Droid::Internal::Telephony::IPhoneConstants; using Elastos::Droid::Preference::IPreference; using Elastos::Droid::TeleService::R; namespace Elastos { namespace Droid { namespace TeleService { namespace Phone { const String CCdmaCallOptions::TAG("CdmaCallOptions"); const String CCdmaCallOptions::BUTTON_VP_KEY("button_voice_privacy_key"); CAR_OBJECT_IMPL(CCdmaCallOptions) CCdmaCallOptions::CCdmaCallOptions() : DBG(IPhoneGlobals::DBG_LEVEL >= 2) { } CCdmaCallOptions::constructor() { return PreferenceActivity::constructor(); } ECode CCdmaCallOptions::OnCreate( /* [in] */ IBundle* icicle) { PreferenceActivity::OnCreate(icicle); AddPreferencesFromResource(R::xml::cdma_call_privacy); AutoPtr<IPreference> preference; FindPreference(BUTTON_VP_KEY, (IPreference**)&preference); mButtonVoicePrivacy = ICheckBoxPreference::Probe(preference); AutoPtr<IPhone> phone = PhoneGlobals::GetPhone(); Int32 type; phone->GetPhoneType(&type); AutoPtr<IResources> resources; GetResources((IResources**)&resources); Boolean res; resources->GetBoolean(R::bool_::config_voice_privacy_disable, &res); if (type != IPhoneConstants::PHONE_TYPE_CDMA || res) { //disable the entire screen AutoPtr<IPreferenceScreen> screen; GetPreferenceScreen((IPreferenceScreen**)&screen); IPreference::Probe(screen)->SetEnabled(FALSE); } return NOERROR; } ECode CCdmaCallOptions::OnPreferenceTreeClick( /* [in] */ IPreferenceScreen* preferenceScreen, /* [in] */ IPreference* preference, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) String key; preference->GetKey(&key); if (key.Equals(BUTTON_VP_KEY)) { *result = TRUE; return NOERROR; } *result = FALSE; return NOERROR; } } // namespace Phone } // namespace TeleService } // namespace Droid } // namespace Elastos
1571b3088d64f7d603581b3988b6d4336debd574
4cb1072aa6cf376bf42959d0b456a9e6de5dce86
/examples/ConstTester/ConstTester.ino
e25bdcb062e8dafb6b5c879d2692fc3949adfce6
[ "BSD-3-Clause" ]
permissive
lathoub/Array
bd99243488738ec2432eacf8b60719e55762d03d
5461cf3ac06f90a247062120b29d75b4be083c5a
refs/heads/master
2021-01-01T13:15:23.313086
2020-02-09T11:53:03
2020-02-09T11:53:03
239,295,304
0
0
NOASSERTION
2020-02-09T11:45:54
2020-02-09T11:45:53
null
UTF-8
C++
false
false
1,598
ino
ConstTester.ino
#include <Arduino.h> #include <Streaming.h> #include <Array.h> const long BAUD = 115200; const size_t ELEMENT_COUNT = 5; const size_t INDEX = 2; const size_t DELAY = 500; void setup() { Serial.begin(BAUD); delay(DELAY); } void loop() { const size_t c_style_array[ELEMENT_COUNT] = {15,14,13,12,11}; Array<size_t,ELEMENT_COUNT> array(c_style_array); array[2] = 28; Serial << "array:" << array << endl; delay(DELAY); Serial << "array[" << INDEX << "] = " << array[INDEX] << endl; delay(DELAY); size_t * array_data_ptr = array.data(); Serial << "array_data_ptr[" << INDEX << "] = " << array_data_ptr[INDEX] << endl; delay(DELAY); Serial << endl; delay(DELAY); const Array<size_t,ELEMENT_COUNT> const_array(c_style_array); Serial << "const_array:" << const_array << endl; delay(DELAY); Serial << "const_array[" << INDEX << "] = " << const_array[INDEX] << endl; delay(DELAY); const size_t * const_array_data_ptr = const_array.data(); Serial << "const_array_data_ptr[" << INDEX << "] = " << const_array_data_ptr[INDEX] << endl; delay(DELAY); Serial << endl; delay(DELAY); const Array<size_t,ELEMENT_COUNT> const_array_copy(const_array); Serial << "const_array_copy:" << const_array_copy << endl; delay(DELAY); Serial << "const_array_copy[" << INDEX << "] = " << const_array_copy[INDEX] << endl; delay(DELAY); const size_t * const_array_copy_data_ptr = const_array_copy.data(); Serial << "const_array_copy_data_ptr[" << INDEX << "] = " << const_array_copy_data_ptr[INDEX] << endl; delay(DELAY); Serial << endl; delay(DELAY); }
52f21465a1a518c8620b9435fba837dd55048695
c3aeb514d43a343d3a4f9df75ee98e248c8278f7
/test/container.cpp
fa75ffb51bc81a697f0bcf36bc09d26eddc2bdb9
[ "MIT" ]
permissive
potswa/cxx_function
c43666133fe58c566fdea61ad160201fc2dc0324
677a1b37954d7867619d49075179be3116728b8a
refs/heads/master
2021-01-10T04:36:14.258994
2020-04-27T13:00:56
2020-04-27T13:25:11
36,355,366
54
9
MIT
2020-04-27T13:27:33
2015-05-27T08:58:14
C++
UTF-8
C++
false
false
2,746
cpp
container.cpp
#include <map> #include "cxx_function.hpp" #include <cassert> std::map< int, std::ptrdiff_t > pool_total; std::ptrdiff_t global_total = 0; struct accounting { int id; static int next_id; accounting() : id( next_id ++ ) {} std::ptrdiff_t total() const { return pool_total[ id ]; } }; int accounting::next_id = 0; bool operator == ( accounting const & lhs, accounting const & rhs ) { return lhs.id == rhs.id; } bool operator != ( accounting const & lhs, accounting const & rhs ) { return lhs.id != rhs.id; } template< typename t > struct accountant : accounting { typedef t value_type; t * allocate( std::size_t n ) { n *= sizeof (t); pool_total[ id ] += n; global_total += n; return static_cast< t * >( ::operator new( n ) ); } void deallocate( t * p, std::size_t n ) { n *= sizeof (t); pool_total[ id ] -= n; global_total -= n; assert ( pool_total[ id ] >= 0 ); assert ( global_total >= 0 ); ::operator delete( p ); } accountant select_on_container_copy_construction() const { return {}; } accountant() = default; template< typename u > accountant( accountant< u > const & o ) : accounting( o ) {} }; template< std::size_t n > struct immovable { char weight[ n ]; immovable() = default; immovable( immovable const & ) = default; immovable( immovable && ) {} }; int main() { cxx_function::function_container< accountant<void>, accounting() > q; immovable< 5 > c5; auto five = [c5] { (void) c5; return accounting{}; }; static_assert ( sizeof five == 5, "" ); q = five; assert ( q.get_allocator().total() == 5 ); auto r = q; assert ( q.get_allocator().total() == 5 ); assert ( global_total == 10 ); q = [q] { return q.get_allocator(); }; // Copy, then overwrite q. assert ( q.get_allocator().total() == sizeof (q) ); assert ( global_total == 10 + sizeof (q) ); cxx_function::function< accounting() > f; f = q; // Use q's allocator for a new wrapper targeting a container with a five. assert ( q.get_allocator().total() == 2 * sizeof (q) ); assert ( global_total == 15 + 2 * sizeof (q) ); f.assign( five, q.get_allocator() ); assert ( q.get_allocator().total() == 5 + sizeof (q) ); q = f; r = std::move( q ); cxx_function::unique_function_container< accountant<void>, accounting() > s = r; s = std::move( r ); #if __GNUC__ && defined(__has_warning) # if __has_warning("-Wself-move") # pragma GCC diagnostic ignored "-Wself-move" # endif #endif s = std::move( s ); assert ( s != nullptr ); }
6a2c9f73d3f0965d0568821f28253f87c0df19c0
67fc10f71b4dd3e9956eb2e4b871d2abc659acb6
/iteration 4/Prototype/DeplacementMulti-alpha/serveurEliminator/entitylight.h
e8c524886fa402c54821bb2e9970507b42396421
[]
no_license
Batyan/Eliminator
84418a9520aed260e78fcdf66406864f353778c1
1b7f7ff9457cf013da0f575fc4a88913aebfee31
refs/heads/master
2021-01-19T06:06:18.674091
2013-12-04T22:11:29
2013-12-04T22:11:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
133
h
entitylight.h
#ifndef ENTITYLIGHT_H #define ENTITYLIGHT_H class EntityLight { public: EntityLight(); int id; }; #endif // ENTITYLIGHT_H
4fd41692510952baa67095f7884953ccdee311a7
cf07db979d8de0adac27de8fd8abb686477e2fd1
/RavageRebuild/include/OpenGL/RavIndexBufferOpenGL.h
c23afa0bd5f06a8736abefa6a06502873bea96d6
[]
no_license
YuraTim/Ravage
208f653779f3a04b29d076135f295984b381582c
939b5b477e4fe5fe3c347bfcf177a210a598c4ff
refs/heads/master
2021-01-10T14:39:33.264966
2016-04-07T15:33:12
2016-04-07T15:33:12
55,705,817
0
0
null
null
null
null
UTF-8
C++
false
false
819
h
RavIndexBufferOpenGL.h
#ifndef RAVINDEXBUFFEROPENGL_H_INCLUDED #define RAVINDEXBUFFEROPENGL_H_INCLUDED #include "RavBase.h" #include "RavIndexBuffer.h" #include "OpenGL\RavLibrariesOpenGL.h" namespace Ravage { class IndexBufferOpenGL : public IndexBuffer { public: virtual ~IndexBufferOpenGL(); bool create(unsigned size, IndexBufferType type, GraphicResourceType pool); virtual void setBuffer(Byte* buffer, unsigned size); virtual Byte* lock(unsigned offset = 0, unsigned size = 0, LockingFlag flag = LOCK_READ_WRITE); virtual void unlock(); virtual IndexBufferType getBufferType() const; inline GLuint getBufferID() const { return mBuffer; } private: GLuint mBuffer; unsigned mSize; GraphicResourceType mPool; IndexBufferType mType; }; } #endif /* RAVINDEXBUFFEROPENGL_H_INCLUDED */
07c70edde3f1556d53a8f6c0c4ec7b574c7721bb
4084cbee083516f2dc0b4e3224298d415bb4bb01
/CCS_projects/BLDC/src/BLDC/ADC.cpp
891b944b53d2d5d9a097a7df7b8a9df1a4ba86d5
[]
no_license
relliky/OptimusPi_r1
6da097da23edd6be9e42c89684717a1e6c22e50c
e58f5edf76d428211ee07b0567e450e0f6f7b704
refs/heads/master
2021-01-20T02:16:32.865388
2015-05-05T00:50:13
2015-05-05T00:50:13
25,427,460
0
0
null
null
null
null
UTF-8
C++
false
false
10,280
cpp
ADC.cpp
/* * ADC.cpp * * Created on: 10 Jul 2014 * Author: Matt * * Configures either the ADC0 or ADC1 peripherals and contains an ISR for each. */ #include "ADC.h" #include "BLDC.h" static ADCClass* ADC0; static ADCClass* ADC1; /** * Constructor * * @param channel - either 0 or 1, maps to ADC0 and ADC1 * @param CommutationTimerPointer - pointer to the motors commutation timer object, allows the ADC interrupt to control the timer based on the detection of ZC events * @param motorPointer - pointer to the parent motor object, allowing the ADC interrupt to change the motor state */ ADCClass::ADCClass(uint32_t channel, CommutationControllerClass* CommutationTimerPointer, BLDCClass* motorPointer) : LED(channel), commutationFilter(1, 3), halfDCFilter(1, 255) { CommutationTimer = CommutationTimerPointer; motorParent = motorPointer; ZCDetectedFlag = false; acquisitionCounter = 0; halfDC = 0; acquisitionEnabled = false; configurePeripherals(channel); } ADCClass::~ADCClass() { this->releasePeripherals(); } /** * Populates the abstracted register values to configure the object for ADC0 */ void ADCClass::initAsADC0() { SYSCTL_PERIPH_ADC = SYSCTL_PERIPH_ADC0; SYSCTL_PERIPH_GPIO = SYSCTL_PERIPH_GPIOE; GPIO_PORT_BASE = GPIO_PORTE_BASE; GPIO_PIN_A = GPIO_PIN_0; GPIO_PIN_B = GPIO_PIN_1; GPIO_PIN_C = GPIO_PIN_2; PWM_BASE = PWM0_BASE; ADC_BASE = ADC0_BASE; ADC_TRIGGER_PWM = ADC_TRIGGER_PWM0; ADC_CTL_A = ADC_CTL_CH3; ADC_CTL_B = ADC_CTL_CH2; ADC_CTL_C = ADC_CTL_CH1; INT_ADCnSS0_TM4C123 = INT_ADC0SS0_TM4C123; ADC0 = this; } /** * Populates the abstracted register values to configure the object for ADC1 */ void ADCClass::initAsADC1() { SYSCTL_PERIPH_ADC = SYSCTL_PERIPH_ADC1; SYSCTL_PERIPH_GPIO = SYSCTL_PERIPH_GPIOD; GPIO_PORT_BASE = GPIO_PORTD_BASE; GPIO_PIN_A = GPIO_PIN_0; GPIO_PIN_B = GPIO_PIN_1; GPIO_PIN_C = GPIO_PIN_2; PWM_BASE = PWM1_BASE; ADC_BASE = ADC1_BASE; ADC_TRIGGER_PWM = ADC_TRIGGER_PWM1; ADC_CTL_A = ADC_CTL_CH7; ADC_CTL_B = ADC_CTL_CH6; ADC_CTL_C = ADC_CTL_CH5; INT_ADCnSS0_TM4C123 = INT_ADC1SS0_TM4C123; ADC1 = this; } /** * Configures the required peripherals to configure the ADC module and related systems * @param channel - either 0 or 1 */ void ADCClass::configurePeripherals(uint32_t channel) { channel ? initAsADC1() : initAsADC0(); // Enable the ADC peripheral SysCtlPeripheralEnable(SYSCTL_PERIPH_ADC); // Enable the required GPIO port peripheral if it isn't already SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIO); // Configure the pin type of the required pins GPIOPinTypeADC(GPIO_PORT_BASE, GPIO_PIN_A | GPIO_PIN_B | GPIO_PIN_C); // Enable trigger generation in the appropiate PWM module, triggering at the center of the PWM high period PWMGenIntTrigEnable(PWM_BASE, PWM_GEN_0, PWM_TR_CNT_LOAD); // Enable PWM trigger generation at center of high period // Enable ADC hardware oversampling // ADCHardwareOversampleConfigure(ADC_BASE, 2); //Enable 2x hardware oversampling, currently fucks everything // Configure the ADC sequence, sequence 0, triggering off the sister PWM module, highest priority ADCSequenceConfigure(ADC_BASE, 0, ADC_TRIGGER_PWM, 0); // Register one of the two static interrupt handlers to the peripheral ADCIntRegister(ADC_BASE, 0, channel ? ISR1Static : ISR0Static); // Set the interrupt priority IntPrioritySet(INT_ADCnSS0_TM4C123, 1); // @TODO - What should this actually be? // Enable the ADC sequence, starts sampling on the PWM trigger but doesn't generate interrupts yet ADCSequenceEnable(ADC_BASE, 0); } /** * Disables used peripherals. @TODO Currently this doesn't really work as intended, as many peripherals are shared and therefore * cannot be blindly disabled. */ void ADCClass::releasePeripherals() { ADCIntDisable(ADC_BASE, 0); ADCSequenceDisable(ADC_BASE, 0); ADCIntUnregister(ADC_BASE, 0); SysCtlPeripheralDisable(SYSCTL_PERIPH_ADC); } /** * Function to reset the ADC to a state equal to that just after the object has been constructed */ void ADCClass::reset() { ZCDetectedFlag = false; acquisitionCounter = 0; ZC.reset(); commutationFilter.reset(); halfDCFilter.reset(); } /** * Enables the ADC conversion interrupt, generating an interrupt every time a sample conversion completes */ void ADCClass::enableInterrupt() { ADCIntEnable(ADC_BASE, 0); } /** * Disable the ADC conversion interrupt */ void ADCClass::disableInterrupt() { ADCIntDisable(ADC_BASE, 0); } /** * Function used to tell the ADC peripheral which motor phase needs to be sampled, achieved by * selecting the correct ADC channel depending on the value of phase. * * @param phase - A, B, or C */ void ADCClass::setPhase(phase_t phase) { switch (phase) { case A: ADCSequenceStepConfigure(ADC_BASE, 0, 0, ADC_CTL_A | ADC_CTL_END | ADC_CTL_IE); break; case B: ADCSequenceStepConfigure(ADC_BASE, 0, 0, ADC_CTL_B | ADC_CTL_END | ADC_CTL_IE); break; case C: ADCSequenceStepConfigure(ADC_BASE, 0, 0, ADC_CTL_C | ADC_CTL_END | ADC_CTL_IE); break; } /* * Commented code below was an attempt to sample all three channels at once, allowing the value of the DC * bus voltage to be measured every cycle, however this doesn't work, probably due to three ADC samples * not fitting inside the PWM high period for low duty cycles. */ /*switch(phase) { case A: ADCSequenceStepConfigure(ADC_BASE, 0, 0, ADC_CTL_A); ADCSequenceStepConfigure(ADC_BASE, 0, 1, ADC_CTL_B); ADCSequenceStepConfigure(ADC_BASE, 0, 2, ADC_CTL_C | ADC_CTL_END | ADC_CTL_IE); break; case B: ADCSequenceStepConfigure(ADC_BASE, 0, 0, ADC_CTL_B); ADCSequenceStepConfigure(ADC_BASE, 0, 1, ADC_CTL_A); ADCSequenceStepConfigure(ADC_BASE, 0, 2, ADC_CTL_C | ADC_CTL_END | ADC_CTL_IE); break; case C: ADCSequenceStepConfigure(ADC_BASE, 0, 0, ADC_CTL_C); ADCSequenceStepConfigure(ADC_BASE, 0, 1, ADC_CTL_B); ADCSequenceStepConfigure(ADC_BASE, 0, 2, ADC_CTL_A | ADC_CTL_END | ADC_CTL_IE); break; }*/ } /** * Has a ZC been detected since the flag was last cleared? * * @return */ bool ADCClass::getZCDetectedFlag() { return ZCDetectedFlag; } /** * Clears the ZC detected flag, called upon commutation to a new step. */ void ADCClass::clearZCDetectedFlag() { ZCDetectedFlag = false; } /** * Function to set the expected slope of the BEMF signal * * @param newDirection - either rising or falling */ void ADCClass::setZCDirection(zeroCrossingDirection_t newDirection) { ZC.setZCDirection(newDirection); } /** * Clears the acquisition counter, used during the acquisition phase where the ADC interrupt is searching * for two consecutive zero crossing events. This is called by the commutation controller when it commutates * before a ZC has been detected, aka when a ZC is missed. */ void ADCClass::clearAcquisitionCounter() { acquisitionCounter = 0; commutationFilter.reset(); } void ADCClass::enableAcquisition() { acquisitionEnabled = true; } void ADCClass::disableAcquisition() { acquisitionEnabled = false; } /** * Static interrupt handler. Being static allows a fixed address to be registered with the interrupt * vector table, while being a member of the ADCClass allows access to the private ISR function, allowing * the static function to redirect execution to the ISR member function with the correct this pointer. * * This only works as intended if the static ADC0 pointer defined at the top of this file is correctly * populated with the pointer to the object managing the ADC0 peripheral. */ interrupt void ADCClass::ISR0Static() { ADC0->ISR(); } /** * Static interrupt handler. Being static allows a fixed address to be registered with the interrupt * vector table, while being a member of the ADCClass allows access to the private ISR function, allowing * the static function to redirect execution to the ISR member function with the correct this pointer. * * This only works as intended if the static ADC1 pointer defined at the top of this file is correctly * populated with the pointer to the object managing the ADC0 peripheral. */ interrupt void ADCClass::ISR1Static() { ADC1->ISR(); } /** * The main interrupt handler. All zero crossing evaluation and subsequent state progression is performed here. */ void ADCClass::ISR() { ADCIntClear(ADC_BASE, 0); // Grab the sampled ADC data and the current commutation timer value ADCSequenceDataGet(ADC_BASE, 0, ADCValue); // Store the current commutation timer value uint32_t timerValue = CommutationTimer->getValue(); // halfDC = halfDCFilter.iterate((ADCValue[1] + ADCValue[2]) / 2); halfDC = (ADCValue[1] + ADCValue[2]) / 2; switch (motorParent->getControlState()) { /** * In the openloop state we are simply checking for the presence of a valid zero crossing event during the * current commutation cycle, with the goal of detecting enough consecutive crossings to assume we have the * desired amount of phase lag for closed loop commutation to be attempted. If a ZC is detected during a cycle * the variable acquisitionCounter is incremented, if none is detected then acquisitionCounter is zeroed. * If two consecutive ZCs are detected the commutation timer is loaded with a timeout value equal to double * that of the current count since the last commutation event and the motor state is advanced to closed loop. * * Acquisition is only enabled after a numeber of cycles, as there is no point looking for a ZC event when the * motor speed is low. */ case openloop: if (acquisitionEnabled) { // Check for ZC, assuming it hasn't already been detected in this commutation cycle if (ZC.ZCDetected(ADCValue[0], &timerValue, HALF_DC) && !ZCDetectedFlag) { ZCDetectedFlag = true; acquisitionCounter++; if (acquisitionCounter == 2) { CommutationTimer->setTimeoutValue(2 * commutationFilter.iterate(timerValue)); motorParent->setState(closedloop); } } } break; /** * In the closed loop state we are looking for a valid ZC event, setting the commutation timer * timeout value when a ZC occurs. */ case closedloop: if (ZC.ZCDetected(ADCValue[0], &timerValue, HALF_DC) && !ZCDetectedFlag) { CommutationTimer->setTimeoutValue(2 * commutationFilter.iterate(timerValue)); ZCDetectedFlag = true; } break; } }
eee52a12f1f171dbef7c71c63b8385fa5d76a4b5
8413273bab84228dad6ff5247f6d581b7796d142
/sample/sdl_gui/guichan/core/image/particle/particleemitterprop.h
87122d0224514764bbd6d4f6f6bbcf3679fc100c
[]
no_license
pdpdds/yuzaos
91b6f5bb51583da3827594489fc700821bc5cd6a
ce3b6d0907f7be470fcbc408382a20e2b75e9ef2
refs/heads/master
2023-05-01T09:51:21.007740
2023-04-27T08:37:42
2023-04-27T08:37:42
289,303,507
28
5
null
2021-03-20T14:58:37
2020-08-21T15:30:10
C
UTF-8
C++
false
false
3,158
h
particleemitterprop.h
/* * Aethyra * Copyright (C) 2006 The Mana World Development Team * * This file is part of Aethyra based on original code * from The Mana World. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <cmath> /** * Returns a random numeric value that is larger than or equal min and smaller * than max */ enum ChangeFunc { FUNC_NONE, FUNC_SINE, FUNC_SAW, FUNC_TRIANGLE, FUNC_SQUARE }; template <typename T> struct ParticleEmitterProp { ParticleEmitterProp(): changeFunc(FUNC_NONE) { } void set(const T &min, const T &max) { minVal=min; maxVal=max; } void set(const T &val) { set(val, val); } void setFunction(ChangeFunc func, const T &amplitude, const int period, const int phase) { changeFunc = func; changeAmplitude = amplitude; changePeriod = period; changePhase = phase; } T value(int tick) { tick += changePhase; T val = (T) (minVal + (maxVal - minVal) * (rand() / ((double) RAND_MAX + 1))); switch (changeFunc) { case FUNC_SINE: val += (T) std::sin(M_PI * 2 * ((double) (tick % changePeriod) / (double) changePeriod)) * changeAmplitude; break; case FUNC_SAW: val += (T) (changeAmplitude * ((double) (tick % changePeriod) / (double) changePeriod)) * 2 - changeAmplitude; break; case FUNC_TRIANGLE: if ((tick % changePeriod) * 2 < changePeriod) val += changeAmplitude - (T)((tick % changePeriod) / (double) changePeriod) * changeAmplitude * 4; else // I have no idea why this works but it does val += changeAmplitude * -3 + (T)((tick % changePeriod) / (double) changePeriod) * changeAmplitude * 4; break; case FUNC_SQUARE: if ((tick % changePeriod) * 2 < changePeriod) val += changeAmplitude; else val -= changeAmplitude; break; case FUNC_NONE: default: //nothing break; } return val; } T minVal; T maxVal; ChangeFunc changeFunc; T changeAmplitude; int changePeriod; int changePhase; };
5a861404da5a69ec1d8384a70ef3f38f20bcfecf
48cbfca9b2d5f7f0b368b7a896833d5e9f19f671
/Luogu/P1025 数的划分.cpp
2edb8819de4aa16d02c8e0cfb7fd74def5f09b3d
[]
no_license
Luckyblock233/OI-code
8a9099b106968dd087cb1b95ca7516bd6b7a5457
319993be9ec5eb642e2844db63e1c4f59fd8f0e8
refs/heads/master
2020-08-16T08:50:36.339838
2019-10-17T13:14:24
2019-10-17T13:14:24
215,478,816
0
0
null
null
null
null
GB18030
C++
false
false
866
cpp
P1025 数的划分.cpp
//算法:DFS回溯 //思路:dfs传输要拆分的数s与答案中数的个数t //以答案中最后的数为起点,循环找不大于s的数i, //保证新的数小于前面的数, (为避免重复答案) //若s-i>=0 ,则使s-i,并使答案中第t个数为i //若此时s为0,就可以使方案+1 //不为0,就继续搜索下一个t位置 #include<cstdio> using namespace std; int n,k,tot; int ans[10000]={1,1}; void dfs(int s,int t); int main() { scanf("%d%d",&n,&k); dfs(n,1); printf("%d",tot); } void dfs(int s,int t) { if(t>k || s<t) return ; for(int i=ans[t-1];i<=s;i++)//搜s个数 if(s-i>=0)//满足条件 { ans[t]=i;//加入答案 s-=i;//减去 if(t==k && s==0) tot++;//结束条件 else dfs(s,t+1);//继续搜索 s+=i;//回溯,使s+i,返回状态 } return ; }
a247471f19d5149379c5d115f4b47a218f9b72fb
97069fdb6772617ce4ec3ebeeea7d3eecd9d7d0d
/src/generators/basic_generator.cpp
159c32dfcdedd8d8f5ef85393f931d22e694e64d
[ "MIT" ]
permissive
gitter-badger/autoprogrammer
3204a5ff115d5b8933e02e73feeb9e3b8c37599b
f42327661a661166f4f21c4ce9f330fcd56c45ac
refs/heads/master
2020-04-03T07:16:56.392193
2018-09-04T18:49:39
2018-09-04T18:49:39
155,098,134
0
0
MIT
2018-10-28T17:43:07
2018-10-28T17:43:07
null
UTF-8
C++
false
false
4,277
cpp
basic_generator.cpp
#include "basic_generator.h" #include <clang/AST/ASTContext.h> #include <clang/Basic/SourceManager.h> #include <clang/Basic/FileManager.h> #include <clang/Rewrite/Frontend/Rewriters.h> #include <clang/Rewrite/Core/Rewriter.h> #include <clang/Format/Format.h> #include <fstream> #include <sstream> namespace codegen { BasicGenerator::BasicGenerator(const Options &opts) : m_options(opts) { } void BasicGenerator::OnCompilationStarted() { } bool BasicGenerator::Validate() { return true; } enum class FileState { Good, Bad, NoFile }; FileState OpenGeneratedFile(const std::string& fileName, std::ofstream& fileStream, std::ostream*& targetStream) { if (fileName == "stdout") { targetStream = &std::cout; return FileState::Good; } if (fileName.empty()) return FileState::NoFile; fileStream.open(fileName, std::ios_base::out | std::ios_base::trunc); if (!fileStream.good()) return FileState::Bad; targetStream = &fileStream; return FileState::Good; } bool BasicGenerator::GenerateOutput(const clang::ASTContext* astContext, clang::SourceManager* sourceManager) { if (!clang::format::getPredefinedStyle(m_options.formatStyleName, clang::format::FormatStyle::LK_Cpp, &m_formatStyle)) { std::cout << "Can't load style with name: " << m_options.formatStyleName << std::endl; } bool result = true; if (!m_options.outputHeaderName.empty()) { result = GenerateOutputFile(m_options.outputHeaderName, "fl-codegen-output-header.h", astContext, sourceManager, [this](auto& stream) { this->WriteHeaderPreamble(stream); this->WriteHeaderContent(stream); this->WriteHeaderPostamble(stream); return true; }); } if (!result) return false; if (!m_options.outputSourceName.empty()) { result = GenerateOutputFile(m_options.outputSourceName, "fl-codegen-output-source.cpp", astContext, sourceManager, [this](auto& stream) { this->WriteSourcePreamble(stream); this->WriteSourceContent(stream); this->WriteSourcePostamble(stream); return true; }); } return result; } bool BasicGenerator::GenerateOutputFile(const std::string& fileName, std::string tmpFileId, const clang::ASTContext* astContext, clang::SourceManager* sourceManager, std::function<bool (CppSourceStream&)> generator) { using namespace clang; std::ostringstream targetHeaderOs; { CppSourceStream stream(targetHeaderOs); if (!generator(stream)) return false; } auto fileContent = targetHeaderOs.str(); tooling::Range fileRange(0, static_cast<unsigned>(fileContent.size())); auto replaces = format::reformat(m_formatStyle, fileContent, {fileRange}); auto formattingResult = tooling::applyAllReplacements(fileContent, replaces); if (!formattingResult) return false; std::string formattedContent = formattingResult.get(); std::ofstream outHdrFile; std::ostream* targetOs; auto hdrFileState = OpenGeneratedFile(fileName, outHdrFile, targetOs); if (hdrFileState == FileState::Bad) { std::cerr << "Can't open output file for writing: " << fileName << std::endl; return false; } *targetOs << formattedContent; return true; } bool BasicGenerator::IsFromInputFiles(const clang::SourceLocation& loc, const clang::ASTContext* context) const { auto& sm = context->getSourceManager(); auto ploc = sm.getPresumedLoc(loc, false); std::string locFilename = ploc.getFilename(); return m_options.inputFiles.count(locFilename) != 0; } bool BasicGenerator::IsFromUpdatingFile(const clang::SourceLocation& loc, const clang::ASTContext* context) const { auto& sm = context->getSourceManager(); auto ploc = sm.getPresumedLoc(loc, false); std::string locFilename = ploc.getFilename(); return m_options.fileToUpdate == locFilename; } void BasicGenerator::WriteExtraHeaders(CppSourceStream& os) { for (auto& h : m_options.extraHeaders) { os << "#include "; bool quoted = h[0] != '<'; os << (quoted ? "\"" : "") << h << (quoted ? "\"" : "") << "\n"; } } } // codegen
98441aff972dd8c55846cc616967794deb13edf3
716d419a478280af5c00dcfb339b30e9750d6e6e
/Live/Classes/HUD/HUDBar.h
d8b46e10f81ba78637f7b0c045a19789811019a9
[]
no_license
hinataiswaifu/live
87220ceece33da4f5b9f7042e0760df2d114a35b
4f05a5a123ca8d9a7e95710d1e0d85ac79eadf1d
refs/heads/master
2021-09-05T08:49:21.087601
2017-12-01T05:00:20
2017-12-01T05:00:20
105,398,524
3
2
null
2017-11-22T17:03:41
2017-09-30T20:23:22
C++
UTF-8
C++
false
false
849
h
HUDBar.h
#pragma once #include "cocos2d.h" class HUDBar : public cocos2d::Layer { public: HUDBar(const std::string& _title, double max, int x, int y, cocos2d::Sprite* bar_sprite); ~HUDBar(); // static method to create instance of HUDBar static HUDBar* createLayer(const std::string& title, double max); virtual void draw(cocos2d::Renderer* renderer, const cocos2d::Mat4& transform, bool transformUpdated); // Setters void updateMax(double max); void updateCurr(double curr); void setTitle(const std::string& _title); // Update views void update(); private: // Components of a HUDBar cocos2d::Label* m_label; cocos2d::ProgressTimer* m_bar; // Stored properties std::string m_title; std::string m_sprite_file; double m_max_value; double m_curr_value; };
f8a79b4be109a5d2706ca892c59a8802fe7f93be
b9b90ec865e4e12e47f72b64e4a00c29fa7e61fb
/cflw代码库/cflw图形_dx纹理.cpp
e0a13ecb2bcd3654de09ce7583941ed3fafe4d2f
[ "MIT" ]
permissive
cflw/cflw_cpp
b8d06d0ad8b1d7b439150c41177b519613f25ebb
b77d4f83e158f80fcf56552256978fc726b54cac
refs/heads/master
2023-02-15T16:58:02.613386
2023-01-27T13:06:14
2023-01-27T13:06:14
143,597,047
13
1
null
null
null
null
UTF-8
C++
false
false
16,868
cpp
cflw图形_dx纹理.cpp
#include <cassert> #include <unordered_map> #include <unordered_set> #include "cflw图形_dx纹理.h" namespace std { template<> struct hash<GUID> { size_t operator()(const GUID &a) const { const size_t v0 = a.Data1; const size_t v1 = (size_t)a.Data2 * (size_t)a.Data3; const size_t v2 = (size_t)a.Data4[0] * (size_t)a.Data4[1] * (size_t)a.Data4[2] * (size_t)a.Data4[3] * (size_t)a.Data4[4] * (size_t)a.Data4[5] * (size_t)a.Data4[6] * (size_t)a.Data4[7]; return v0 ^ v1 ^ v2; } }; } namespace cflw::图形::dx纹理 { C图像工厂::~C图像工厂() { m工厂.Reset(); CoUninitialize(); } HRESULT C图像工厂::f初始化() { CoInitializeEx(nullptr, COINIT_MULTITHREADED); HRESULT hr = CoCreateInstance(CLSID_WICImagingFactory1, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&m工厂)); if (FAILED(hr)) { return hr; } return S_OK; } HRESULT C图像工厂::f读取图像(const std::wstring_view &a文件, IWICBitmapFrameDecode **a帧) const { HRESULT hr; ComPtr<IWICBitmapDecoder> v解码器; hr = m工厂->CreateDecoderFromFilename(a文件.data(), 0, GENERIC_READ, WICDecodeMetadataCacheOnDemand, &v解码器); if (FAILED(hr)) { return hr; } hr = v解码器->GetFrame(0, a帧); if (FAILED(hr)) { return hr; } return S_OK; } std::unique_ptr<std::byte[]> C图像工厂::f复制像素数据(IWICBitmapSource *a帧, size_t *ap像素大小, size_t *ap行距, size_t *ap图像大小) const { const WICBitmapPlaneDescription v描述 = f取图像描述(a帧); const size_t v像素大小 = f像素大小(v描述.Format); const size_t v一排大小 = v描述.Width * v像素大小; const size_t v数据大小 = v一排大小 * v描述.Height; std::unique_ptr<std::byte[]> v数据 = std::make_unique<std::byte[]>(v数据大小); a帧->CopyPixels(0, (UINT)v一排大小, (UINT)v数据大小, (BYTE*)v数据.get()); if (ap像素大小) { *ap像素大小 = v像素大小; } if (ap行距) { *ap行距 = v一排大小; } if (ap图像大小) { *ap图像大小 = v数据大小; } return v数据; } WICBitmapPlaneDescription C图像工厂::f取图像描述(IWICBitmapSource *a帧) const { WICBitmapPlaneDescription v; a帧->GetPixelFormat(&v.Format); a帧->GetSize(&v.Width, &v.Height); return v; } size_t C图像工厂::f像素大小(const GUID &guid) const { HRESULT hr; ComPtr<IWICComponentInfo> v组件信息; hr = m工厂->CreateComponentInfo(guid, &v组件信息); if (FAILED(hr)) { return 0; } WICComponentType v类型; v组件信息->GetComponentType(&v类型); if (v类型 != WICPixelFormat) { return 0; } ComPtr<IWICPixelFormatInfo> v格式信息; hr = v组件信息.As(&v格式信息); if (FAILED(hr)) { return 0; } UINT bpp; v格式信息->GetBitsPerPixel(&bpp); return bpp; } HRESULT C图像工厂::f图像尺寸变换(IWICBitmapSource *a帧, size_t a宽, size_t a高, IWICBitmapScaler **a输出) const { HRESULT hr; ComPtr<IWICBitmapScaler> v缩放; hr = m工厂->CreateBitmapScaler(&v缩放); if (FAILED(hr)) { return hr; } hr = v缩放->Initialize(a帧, a宽, a高, WICBitmapInterpolationModeFant); if (FAILED(hr)) { return hr; } *a输出 = v缩放.Detach(); return S_OK; } HRESULT C图像工厂::f图像格式变换(IWICBitmapSource *a图像, const GUID &a格式, IWICFormatConverter **a输出) const { HRESULT hr; ComPtr<IWICFormatConverter> v转换; hr = m工厂->CreateFormatConverter(&v转换); if (FAILED(hr)) { return hr; } hr = v转换->Initialize(a图像, a格式, WICBitmapDitherTypeErrorDiffusion, nullptr, 0, WICBitmapPaletteTypeCustom); if (FAILED(hr)) { return hr; } *a输出 = v转换.Detach(); return S_OK; } ComPtr<IWICBitmapSource> C图像工厂::f高级读取(const std::wstring_view &a文件名, const std::function<GUID(const GUID &)> &af格式) const { ComPtr<IWICBitmapFrameDecode> v图像; HRESULT hr = f读取图像(a文件名, &v图像); if (FAILED(hr)) { return nullptr; } //格式转换并复制数据 const WICBitmapPlaneDescription v描述 = f取图像描述(v图像.Get()); const GUID v图像格式 = af格式(v描述.Format); if (v图像格式 == v描述.Format) { return v图像; } ComPtr<IWICFormatConverter> v格式转换; hr = f图像格式变换(v图像.Get(), v图像格式, &v格式转换); if (FAILED(hr)) { return nullptr; } return v格式转换; } std::unique_ptr<C只读纹理> C图像工厂::fc纹理(IWICBitmapSource *a源) const { std::unique_ptr<C只读纹理> v纹理 = std::make_unique<C只读纹理>(); v纹理->mp数据 = f复制像素数据(a源, &v纹理->m像素大小, &v纹理->m行距, nullptr); if (!v纹理->mp数据) { return nullptr; } const WICBitmapPlaneDescription v描述 = f取图像描述(a源); v纹理->m宽 = v描述.Width; v纹理->m高 = v描述.Height; v纹理->m格式 = 格式::f到dxgi(v描述.Format); return v纹理; } std::unique_ptr<C只读纹理> C图像工厂::f一键读取(const std::wstring_view &a文件名) const { auto v源 = f高级读取(a文件名, 格式::f到通用格式); return fc纹理(v源.Get()); } //============================================================================= // 格式 //============================================================================= namespace 格式 { bool f检查srgb(IWICBitmapFrameDecode *a图像) { HRESULT hr; ComPtr<IWICMetadataQueryReader> v读元数据; hr = a图像->GetMetadataQueryReader(&v读元数据); if (FAILED(hr)) { return false; } GUID v格式; hr = v读元数据->GetContainerFormat(&v格式); if (FAILED(hr)) { return false; } bool v = false; PROPVARIANT v值; PropVariantInit(&v值); if (memcmp(&v格式, &GUID_ContainerFormatPng, sizeof(GUID)) == 0) { hr = v读元数据->GetMetadataByName(L"/sRGB/RenderingIntent", &v值); if (SUCCEEDED(hr)) { if (v值.vt == VT_UI1) { v = true; } } } else { hr = v读元数据->GetMetadataByName(L"System.Image.ColorSpace", &v值); if (SUCCEEDED(hr)) { if (v值.vt == VT_UI2 && v值.uiVal == 1) { v = true; } } } PropVariantClear(&v值); return v; } DXGI_FORMAT f到dxgi(const GUID &guid) { static const std::unordered_map<GUID, DXGI_FORMAT> v图像格式 = { {GUID_WICPixelFormat128bppRGBAFloat, DXGI_FORMAT_R32G32B32A32_FLOAT}, {GUID_WICPixelFormat64bppRGBAHalf, DXGI_FORMAT_R16G16B16A16_FLOAT}, {GUID_WICPixelFormat64bppRGBA, DXGI_FORMAT_R16G16B16A16_UNORM}, {GUID_WICPixelFormat32bppRGBA, DXGI_FORMAT_R8G8B8A8_UNORM}, {GUID_WICPixelFormat32bppBGRA, DXGI_FORMAT_B8G8R8A8_UNORM}, // DXGI 1.1 {GUID_WICPixelFormat32bppBGR, DXGI_FORMAT_B8G8R8X8_UNORM}, // DXGI 1.1 {GUID_WICPixelFormat32bppRGBA1010102XR, DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM}, // DXGI 1.1 {GUID_WICPixelFormat32bppRGBA1010102, DXGI_FORMAT_R10G10B10A2_UNORM}, #ifdef DXGI_1_2_FORMATS {GUID_WICPixelFormat16bppBGRA5551, DXGI_FORMAT_B5G5R5A1_UNORM}, {GUID_WICPixelFormat16bppBGR565, DXGI_FORMAT_B5G6R5_UNORM}, #endif // DXGI_1_2_FORMATS {GUID_WICPixelFormat32bppGrayFloat, DXGI_FORMAT_R32_FLOAT}, {GUID_WICPixelFormat16bppGrayHalf, DXGI_FORMAT_R16_FLOAT}, {GUID_WICPixelFormat16bppGray, DXGI_FORMAT_R16_UNORM}, {GUID_WICPixelFormat8bppGray, DXGI_FORMAT_R8_UNORM}, {GUID_WICPixelFormat8bppAlpha, DXGI_FORMAT_A8_UNORM}, }; if (auto v格式 = v图像格式.find(guid); v格式 != v图像格式.end()) { return v格式->second; } return DXGI_FORMAT_UNKNOWN; } GUID f到通用格式(const GUID &guid) { static const std::unordered_map<GUID, GUID> v图像转换 = { // 注意目标GUID在这个转换表必须是那些直接支持的格式(段)中的一个。 {GUID_WICPixelFormatBlackWhite, GUID_WICPixelFormat8bppGray}, // DXGI_FORMAT_R8_UNORM {GUID_WICPixelFormat1bppIndexed, GUID_WICPixelFormat32bppRGBA}, // DXGI_FORMAT_R8G8B8A8_UNORM {GUID_WICPixelFormat2bppIndexed, GUID_WICPixelFormat32bppRGBA}, // DXGI_FORMAT_R8G8B8A8_UNORM {GUID_WICPixelFormat4bppIndexed, GUID_WICPixelFormat32bppRGBA}, // DXGI_FORMAT_R8G8B8A8_UNORM {GUID_WICPixelFormat8bppIndexed, GUID_WICPixelFormat32bppRGBA}, // DXGI_FORMAT_R8G8B8A8_UNORM {GUID_WICPixelFormat2bppGray, GUID_WICPixelFormat8bppGray}, // DXGI_FORMAT_R8_UNORM {GUID_WICPixelFormat4bppGray, GUID_WICPixelFormat8bppGray}, // DXGI_FORMAT_R8_UNORM {GUID_WICPixelFormat16bppGrayFixedPoint, GUID_WICPixelFormat16bppGrayHalf}, // DXGI_FORMAT_R16_FLOAT {GUID_WICPixelFormat32bppGrayFixedPoint, GUID_WICPixelFormat32bppGrayFloat}, // DXGI_FORMAT_R32_FLOAT #ifdef DXGI_1_2_FORMATS {GUID_WICPixelFormat16bppBGR555, GUID_WICPixelFormat16bppBGRA5551}, // DXGI_FORMAT_B5G5R5A1_UNORM #else {GUID_WICPixelFormat16bppBGR555, GUID_WICPixelFormat32bppRGBA}, // DXGI_FORMAT_R8G8B8A8_UNORM {GUID_WICPixelFormat16bppBGRA5551, GUID_WICPixelFormat32bppRGBA}, // DXGI_FORMAT_R8G8B8A8_UNORM {GUID_WICPixelFormat16bppBGR565, GUID_WICPixelFormat32bppRGBA}, // DXGI_FORMAT_R8G8B8A8_UNORM #endif // DXGI_1_2_FORMATS {GUID_WICPixelFormat32bppBGR101010, GUID_WICPixelFormat32bppRGBA1010102}, // DXGI_FORMAT_R10G10B10A2_UNORM {GUID_WICPixelFormat24bppBGR, GUID_WICPixelFormat32bppRGBA}, // DXGI_FORMAT_R8G8B8A8_UNORM {GUID_WICPixelFormat24bppRGB, GUID_WICPixelFormat32bppRGBA}, // DXGI_FORMAT_R8G8B8A8_UNORM {GUID_WICPixelFormat32bppPBGRA, GUID_WICPixelFormat32bppRGBA}, // DXGI_FORMAT_R8G8B8A8_UNORM {GUID_WICPixelFormat32bppPRGBA, GUID_WICPixelFormat32bppRGBA}, // DXGI_FORMAT_R8G8B8A8_UNORM {GUID_WICPixelFormat48bppRGB, GUID_WICPixelFormat64bppRGBA}, // DXGI_FORMAT_R16G16B16A16_UNORM {GUID_WICPixelFormat48bppBGR, GUID_WICPixelFormat64bppRGBA}, // DXGI_FORMAT_R16G16B16A16_UNORM {GUID_WICPixelFormat64bppBGRA, GUID_WICPixelFormat64bppRGBA}, // DXGI_FORMAT_R16G16B16A16_UNORM {GUID_WICPixelFormat64bppPRGBA, GUID_WICPixelFormat64bppRGBA}, // DXGI_FORMAT_R16G16B16A16_UNORM {GUID_WICPixelFormat64bppPBGRA, GUID_WICPixelFormat64bppRGBA}, // DXGI_FORMAT_R16G16B16A16_UNORM {GUID_WICPixelFormat48bppRGBFixedPoint, GUID_WICPixelFormat64bppRGBAHalf}, // DXGI_FORMAT_R16G16B16A16_FLOAT {GUID_WICPixelFormat48bppBGRFixedPoint, GUID_WICPixelFormat64bppRGBAHalf}, // DXGI_FORMAT_R16G16B16A16_FLOAT {GUID_WICPixelFormat64bppRGBAFixedPoint, GUID_WICPixelFormat64bppRGBAHalf}, // DXGI_FORMAT_R16G16B16A16_FLOAT {GUID_WICPixelFormat64bppBGRAFixedPoint, GUID_WICPixelFormat64bppRGBAHalf}, // DXGI_FORMAT_R16G16B16A16_FLOAT {GUID_WICPixelFormat64bppRGBFixedPoint, GUID_WICPixelFormat64bppRGBAHalf}, // DXGI_FORMAT_R16G16B16A16_FLOAT {GUID_WICPixelFormat64bppRGBHalf, GUID_WICPixelFormat64bppRGBAHalf}, // DXGI_FORMAT_R16G16B16A16_FLOAT {GUID_WICPixelFormat48bppRGBHalf, GUID_WICPixelFormat64bppRGBAHalf}, // DXGI_FORMAT_R16G16B16A16_FLOAT {GUID_WICPixelFormat128bppPRGBAFloat, GUID_WICPixelFormat128bppRGBAFloat}, // DXGI_FORMAT_R32G32B32A32_FLOAT {GUID_WICPixelFormat128bppRGBFloat, GUID_WICPixelFormat128bppRGBAFloat}, // DXGI_FORMAT_R32G32B32A32_FLOAT {GUID_WICPixelFormat128bppRGBAFixedPoint, GUID_WICPixelFormat128bppRGBAFloat}, // DXGI_FORMAT_R32G32B32A32_FLOAT {GUID_WICPixelFormat128bppRGBFixedPoint, GUID_WICPixelFormat128bppRGBAFloat}, // DXGI_FORMAT_R32G32B32A32_FLOAT {GUID_WICPixelFormat32bppRGBE, GUID_WICPixelFormat128bppRGBAFloat}, // DXGI_FORMAT_R32G32B32A32_FLOAT {GUID_WICPixelFormat32bppCMYK, GUID_WICPixelFormat32bppRGBA}, // DXGI_FORMAT_R8G8B8A8_UNORM {GUID_WICPixelFormat64bppCMYK, GUID_WICPixelFormat64bppRGBA}, // DXGI_FORMAT_R16G16B16A16_UNORM {GUID_WICPixelFormat40bppCMYKAlpha, GUID_WICPixelFormat64bppRGBA}, // DXGI_FORMAT_R16G16B16A16_UNORM {GUID_WICPixelFormat80bppCMYKAlpha, GUID_WICPixelFormat64bppRGBA}, // DXGI_FORMAT_R16G16B16A16_UNORM #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) {GUID_WICPixelFormat32bppRGB, GUID_WICPixelFormat32bppRGBA}, // DXGI_FORMAT_R8G8B8A8_UNORM {GUID_WICPixelFormat64bppRGB, GUID_WICPixelFormat64bppRGBA}, // DXGI_FORMAT_R16G16B16A16_UNORM {GUID_WICPixelFormat64bppPRGBAHalf, GUID_WICPixelFormat64bppRGBAHalf}, // DXGI_FORMAT_R16G16B16A16_FLOAT #endif }; if (auto v格式 = v图像转换.find(guid); v格式 != v图像转换.end()) { return v格式->second; } return guid; } DXGI_FORMAT f到srgb(DXGI_FORMAT a格式) { static const std::unordered_map<DXGI_FORMAT, DXGI_FORMAT> v转换表 = { {DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB}, {DXGI_FORMAT_BC1_UNORM, DXGI_FORMAT_BC1_UNORM_SRGB}, {DXGI_FORMAT_BC2_UNORM, DXGI_FORMAT_BC2_UNORM_SRGB}, {DXGI_FORMAT_BC3_UNORM, DXGI_FORMAT_BC3_UNORM_SRGB}, {DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_B8G8R8A8_UNORM_SRGB}, {DXGI_FORMAT_B8G8R8X8_UNORM, DXGI_FORMAT_B8G8R8X8_UNORM_SRGB}, {DXGI_FORMAT_BC7_UNORM, DXGI_FORMAT_BC7_UNORM_SRGB} }; if (auto v目标格式 = v转换表.find(a格式); v目标格式 != v转换表.end()) { return v目标格式->second; } return a格式; } bool fi通用格式(const GUID &a格式) { static const std::unordered_set<GUID> v格式表 = { GUID_WICPixelFormat128bppRGBAFloat, GUID_WICPixelFormat64bppRGBAHalf, GUID_WICPixelFormat64bppRGBA, GUID_WICPixelFormat32bppRGBA, GUID_WICPixelFormat32bppBGRA, // DXGI 1.1 GUID_WICPixelFormat32bppBGR, // DXGI 1.1 GUID_WICPixelFormat32bppRGBA1010102XR, // DXGI 1.1 GUID_WICPixelFormat32bppRGBA1010102, #ifdef DXGI_1_2_FORMATS GUID_WICPixelFormat16bppBGRA5551, GUID_WICPixelFormat16bppBGR565, #endif // DXGI_1_2_FORMATS GUID_WICPixelFormat32bppGrayFloat, GUID_WICPixelFormat16bppGrayHalf, GUID_WICPixelFormat16bppGray, GUID_WICPixelFormat8bppGray, GUID_WICPixelFormat8bppAlpha, }; return v格式表.count(a格式) != 0; } GUID f不转换(const GUID &a) { return a; } } //namespace 格式 //============================================================================= // 纹理接口 //============================================================================= size_t I纹理::fg面积() const { return this->fg宽() * this->fg高(); } size_t I纹理::fg行距() const { return this->fg宽() * this->fg像素大小(); } size_t I纹理::fg图像大小() const { return this->fg面积() * this->fg像素大小(); } S纹理描述 I纹理::fg描述() const { return S纹理描述{this->fg宽(), this->fg高(), this->fg像素大小(), this->fg格式()}; } //============================================================================= // 常量纹理 //============================================================================= size_t C只读纹理::fg宽() const { return m宽; } size_t C只读纹理::fg高() const { return m高; } size_t C只读纹理::fg像素大小() const { return m像素大小; } size_t C只读纹理::fg面积() const { return m宽 * m高; } size_t C只读纹理::fg行距() const { return m宽 * m像素大小; } size_t C只读纹理::fg图像大小() const { return fg面积() * m像素大小; } DXGI_FORMAT C只读纹理::fg格式() const { return m格式; } const std::byte *C只读纹理::fg数据() const { return mp数据.get(); } //============================================================================= // 自定义纹理 //============================================================================= void C自定义纹理::f初始化(size_t a宽, size_t a高) { m宽 = a宽; m高 = a高; mp像素 = std::make_unique<数学::S颜色[]>(m宽 * a高); } size_t C自定义纹理::fg宽() const { return m宽; } size_t C自定义纹理::fg高() const { return m高; } size_t C自定义纹理::fg像素大小() const { return c像素大小; } size_t C自定义纹理::fg面积() const { return m宽 * m高; } size_t C自定义纹理::fg行距() const { return m宽 * c像素大小; } size_t C自定义纹理::fg图像大小() const { return fg面积() * c像素大小; } DXGI_FORMAT C自定义纹理::fg格式() const { return c格式; } const std::byte *C自定义纹理::fg数据() const { return (std::byte*)fg颜色数据(); } const 数学::S颜色 *C自定义纹理::fg颜色数据() const { return mp像素.get(); } 数学::S颜色 &C自定义纹理::fg像素(size_t u, size_t v) { return mp像素[v * m宽 + u]; } const 数学::S颜色 &C自定义纹理::fg像素(size_t u, size_t v) const { return mp像素[v * m宽 + u]; } 数学::S颜色 C自定义纹理::f线性采样(float u, float v) const { const float v限制u = 数学::f求余(u, (float)m宽); const float v限制v = 数学::f求余(v, (float)m高); const float v地板u = floor(u); const float v地板v = floor(v); const size_t u0 = (size_t)v地板u; const size_t u1 = (size_t)(v地板u + 1); const size_t v0 = (size_t)v地板v; const size_t v1 = (size_t)(v地板v + 1); const float v差值u = v限制u - v地板u; const 数学::S颜色 v颜色0 = 数学::f插值<数学::S颜色>(fg像素(u0, v0), fg像素(u0, v0), v差值u); const 数学::S颜色 v颜色1 = 数学::f插值<数学::S颜色>(fg像素(u0, v1), fg像素(u0, v1), v差值u); const float v差值v = v限制v - v地板v; return 数学::f插值<数学::S颜色>(v颜色0, v颜色1, v差值v); } } //namespace cflw::图形
d5b3f704005aea29e2853f998129ae83ae941e50
5885fd1418db54cc4b699c809cd44e625f7e23fc
/neerc-2012-cf100134/c-hull.cpp
9fca702f3407d269e3e4c7a94fac745b6b3df9ce
[]
no_license
ehnryx/acm
c5f294a2e287a6d7003c61ee134696b2a11e9f3b
c706120236a3e55ba2aea10fb5c3daa5c1055118
refs/heads/master
2023-08-31T13:19:49.707328
2023-08-29T01:49:32
2023-08-29T01:49:32
131,941,068
2
0
null
null
null
null
UTF-8
C++
false
false
1,351
cpp
c-hull.cpp
#include <bits/stdc++.h> using namespace std; #define FILENAME "caravan" #define nl '\n' typedef long long ll; typedef long double ld; typedef complex<ld> pt; ld cp(const pt& a, const pt& b) { return imag(conj(a)*b); } int main() { ios::sync_with_stdio(0); cin.tie(0); #ifdef ONLINE_JUDGE freopen(FILENAME ".in", "r", stdin); freopen(FILENAME ".out", "w", stdout); #endif int n; cin >> n; vector<pair<int,int>> v; for(int i=0; i<n; i++) { int l, r; cin >> l >> r; v.emplace_back(l, r); } sort(v.begin(), v.end()); vector<pt> hull; tuple<ld,int,int> best(1e19, -1, -1); for(int i=n-1; i>=0; i--) { pt top(i+1, v[i].second); pt bot(i, v[i].first); while(hull.size() >= 2 && cp(hull.back() - top, hull[hull.size()-2] - top) < 0) { hull.pop_back(); } hull.push_back(top); int l = 0; int r = hull.size() - 1; while(l < r) { int m = (l+r) / 2; pt p = hull[m]; if(cp(p-bot, hull[m+1]-p) < 0) { l = m+1; } else { r = m; } } best = min(best, {(hull[r].imag()-bot.imag())/(hull[r].real()-bot.real()), i, (int)hull[r].real()}); } auto [_, li, ri] = best; int num = v[ri-1].second - v[li].first; int den = ri-li; int g = __gcd(num, den); num /= g; den /= g; cout << num << "/" << den << endl; return 0; }
fddf6ecd65456e6e5c97d9b0f1b0a6f686115f5c
a879f1ff4679ed01a204069c5b4874720f4444d9
/To_offer/13机器人的运动范围.cpp
d9d8c14ce1b91097c67ee733836daf7b9b4f3b2f
[]
no_license
yuki9965/my-algorithm
fa4ba363e4f010ea793297ee7b2bfa48f807e003
5a4cb53ad7da95250bdfd2a82268c8e083ee0ecd
refs/heads/master
2023-01-28T07:58:54.840455
2020-12-09T13:58:00
2020-12-09T13:58:00
278,879,408
0
0
null
null
null
null
UTF-8
C++
false
false
1,844
cpp
13机器人的运动范围.cpp
#include<iostream> #include<vector> #include<string.h> #include<algorithm> using namespace std; /* 地上有一个m行n列的方格,从坐标 [0,0] 到坐标 [m-1,n-1] 。 一个机器人从坐标 [0, 0] 的格子开始移动,它每次可以向左、右、上、下移动一格 (不能移动到方格外),也不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格 [35, 37] ,因为3+5+3+7=18。 但它不能进入方格 [35, 38],因为3+5+3+8=19。请问该机器人能够到达多少个格子? 示例 1: 输入:m = 2, n = 3, k = 1 输出:3 示例 1: 输入:m = 3, n = 1, k = 0 输出:1 提示: 1 <= n,m <= 100 0 <= k <= 20 */ //回溯,判断条件 int movingCount(int m, int n, int k) { if(k < 0 || m <= 0 || n <= 0) return 0; bool *visited = new bool[m * n]; //标记数组 memset(visited, 0, m * n); int count = backtrack(k, m, n, 0, 0, visited); delete[] visited; return count; } int backtrack(int k, int rows, int cols, int row, int col, bool *visited){ int count = 0; if(row >= 0 && row < rows && col >= 0 && col < cols && !visited[row*cols + col] && check(k, row, col)){ visited[row * cols + col] = 1; count = 1 + backtrack(k, rows, cols, row + 1, col, visited) + backtrack(k, rows, cols, row - 1, col, visited) + backtrack(k, rows, cols, row, col - 1, visited) + backtrack(k, rows, cols, row, col + 1, visited); } return count; } bool check(int k, int row, int col){ int sum = 0; while(row > 0 || col > 0){ sum = sum + row % 10 + col % 10; row = row / 10; col = col / 10; } return sum <= k ? true : false; }
08a68de64f372f91d3dcaa48bbffce5d50f942d4
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5753053697277952_0/C++/K0stIa/a.cpp
1d053e28cb8158a94a9c1df669bf2ec8c91e5952
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
1,411
cpp
a.cpp
#include <assert.h> #include <memory.h> #include <algorithm> #include <cmath> #include <cstdio> #include <iostream> #include <limits> #include <map> #include <numeric> #include <queue> #include <set> #include <sstream> #include <string> #include <vector> using namespace std; #define pb push_back #define INF 1011111111 #define FOR(i, a, b) for (int _n(b), i(a); i < _n; i++) #define rep(i, n) FOR(i, 0, n) #define CL(a, v) memset((a), (v), sizeof(a)) #define mp make_pair #define X first #define Y second #define all(c) (c).begin(), (c).end() #define SORT(c) sort(all(c)) typedef long long ll; typedef vector<int> VI; typedef pair<int, int> pii; /*** TEMPLATE CODE ENDS HERE */ int main() { #ifdef LOCAL_HOST freopen("A-small-attempt0.in", "r", stdin); freopen("output.txt", "w", stdout); #endif cout.sync_with_stdio(0); cin.tie(0); int T; cin >> T; FOR(tt, 1, T + 1) { cout << "Case #" << tt << ": "; int n; cin >> n; VI p(n); rep(i, n) cin >> p[i]; int M = *max_element(all(p)); for (; M > 0; --M) { VI idx; rep(i, n) if (p[i] == M) { idx.pb(i); p[i]--; } int k = 0; if (idx.size() & 1) { cout << char('A' + idx[k++]) << " "; } while (k < (int)idx.size()) { cout << char('A' + idx[k++]); cout << char('A' + idx[k++]) << " "; } } cout << endl; } return 0; }
0c0751b934047b16a8651e19af39e671d4c95153
6cc012c8aca549af905eb22eb1bbb7b999408602
/src/rviz_sim/MAV.h
873d0678f2de4e81280c18152fbcdb678384470b
[ "MIT" ]
permissive
elikos/elikos_sim
4a4c56e02a2bec85de757dfb5866ece1ee672838
a139d321c7ae239b445b4ff09ae2ca9833a9f6ee
refs/heads/master
2021-03-27T10:04:04.631966
2018-05-30T14:11:26
2018-05-30T15:05:17
116,184,652
0
0
null
null
null
null
UTF-8
C++
false
false
1,432
h
MAV.h
#ifndef SIM_MAV_H #define SIM_MAV_H #include <elikos_lib/pid.hpp> #include <visualization_msgs/Marker.h> #include "defines.cpp" namespace elikos_sim { class MAV { public: MAV(double simulationSpeed, ros::Duration cycleTime); ~MAV(); void setVelXYPID(double kp, double ki, double kd); void setVelZPID(double kp, double ki, double kd); void setVelXYMax(double vel); void setVelZMax(double vel); std::string getName(); tf::Transform getTransform(); void move(); void collide(); void poseCallback(const geometry_msgs::PoseStamped::ConstPtr& msg); visualization_msgs::Marker getVizMarker(); visualization_msgs::Marker getSetpointMarker(); private: std::string Name; ros::Duration cycleTime; double x, y, z, yaw, z_sp, yaw_sp, vel_xy_max, vel_z, vel_z_sp, simSpeed; tf::Vector3 vel_xy, vel_xy_sp, xy_sp, direction; tf::Transform transform_; tf::Vector3 v; tf::Quaternion q; void refreshTransform(); Pid<double>* vel_x_pid, * vel_y_pid, * vel_z_pid; /* ************************************************************************************************* * *** HIDDEN CONSTRUCTORS (do not implement) * ************************************************************************************************* */ MAV(); MAV& operator= (const MAV&); MAV (const MAV&); }; } // namespace elikos_sim #endif // SIM_MAV_H
900e03da67fc7033f652261d035b22e66c401d8a
c1ea96689777813eab008d7a2f6e0a0e6fecbe23
/test_by_itoda.cpp
3a50e0b6d2e0d41b02bf109f2147dbc275c2054d
[]
no_license
kotit/sandbox
fc7ee558dc59d7848d9dfcac59b66674b8b7d285
a659ccfdf6440d0f5fbf1ebd6db4d21746f2611a
refs/heads/master
2021-01-17T22:50:45.166662
2013-02-14T14:32:12
2013-02-14T14:32:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
169
cpp
test_by_itoda.cpp
#include <iostream> int main(){ std::cerr << "hello, git world!" << std::endl; //asdf;lkjasdf;lkjasdf;lkj //hogehoge //piyopiyo //foo //bar return 0; }
f06f3e1b2286ab37da5c37bfb64813618c81a838
770718eaaa68c772c22613b5c745c1eff85f7c1a
/bai9/stack_point.cpp
8844d9f37d8a227bfd59aeebbd53a4eaebd00026
[]
no_license
duongptit14/GiaiNganHangCTDLGT
f77a280d753f89f139a581af4c8866b1eaca46e2
b5461e1a212e7e3bd84d86e15f83ba37ad8ac842
refs/heads/master
2021-01-10T12:26:36.944302
2017-12-28T07:11:36
2017-12-28T07:11:36
55,380,105
0
0
null
null
null
null
UTF-8
C++
false
false
1,020
cpp
stack_point.cpp
#include <iostream> using namespace std; struct Node { int value; Node *next; }; class Stack { public: Node *st; Stack() { st = NULL; } Node* create_node(int x) { Node* tmp = new Node(); if( tmp == NULL ) { cout << "Khong du bo nho"; return 0; } tmp->value = x; tmp->next = NULL; return tmp; } void init() { st = NULL; } bool empty() { return st==NULL; } void pop() { st = st->next; } void push( int x) { Node *tmp ; tmp = create_node(x); if( st == NULL ) { st = tmp; st->next = NULL; } else { tmp->next =st; st = tmp; } } int top() { return st->value; } void show() { Node* tmp = new Node(); tmp = st; if(tmp == NULL) { cout << "Stack rong"; return ; } while(tmp!=NULL) { cout << tmp->value << " "; tmp = tmp->next; } } }; int main() { Stack st; st.push(1); st.push(2); st.push(3); st.show(); cout << st.top() << endl; st.pop(); st.show(); return 0; }
162c69509c8e5f931b1d8d945a12ebda6233e5b7
1430544f26e55fdd3724bfbf28e620ea44ef6789
/Softwares/Brennand/serialconnection.h
3e018eb33adaccb323cefbb8f1d5f3fceef5c291
[]
no_license
pedrojlsilva/Armorial-Suassuna
e89e7ca0b2ef35516db61d95729249c75c06a41e
67c5b08f60c1c575c7eb2fe3b3fff298cf3c2796
refs/heads/master
2020-08-30T14:58:59.713075
2019-09-15T20:22:09
2019-09-15T20:22:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
469
h
serialconnection.h
#ifndef SERIALCONNECTION_H #define SERIALCONNECTION_H #include <QDebug> #include <QSerialPort> #include <QSerialPortInfo> class serialConnection{ public: serialConnection(QSerialPort *myDev); ~serialConnection(); QStringList loadPorts(); bool connect(QString Port, uint32_t bd); bool disconnect(void); qint64 write(const char *cmd); QString read(); QString read(int TamanhoBuffer); protected: QSerialPort *devSerial; }; #endif
0b5ffd1566044cca0972f0c821e9c48e0b168369
3c0e8203d9136d5e6ded361a6c0a7c059ffedb5e
/src/osal/win32/OS_Socket_win32.cpp
fb10f6ff6f282d47b8ccd50603d651abbfcc42d9
[]
no_license
gnosis2148/vcore
895a5b719f79c0565c72a7ef01068e13208266e6
4c294033e02bcba1fa8fa213d40a6a1b3a062b03
refs/heads/master
2020-04-15T22:49:42.707235
2011-02-04T16:44:19
2011-02-04T16:44:19
1,294,761
0
0
null
null
null
null
UTF-8
C++
false
false
2,654
cpp
OS_Socket_win32.cpp
/*----------------------------------------------------------* OS_SocketWin32.cpp Platform-specific socket implementation *-----------------------------------------------------------*/ //-------------------- Include files ------------------------- #include <win32/OS_Socket_win32.h> int OS_SocketWin32::Create () { m_sock = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP); if (m_sock < 0) return -1; return 0; } int OS_SocketWin32::Bind (int nMaxConnections) { m_bIsValid = false; SOCKADDR_IN serverInfo; serverInfo.sin_family = AF_INET; serverInfo.sin_addr.s_addr = INADDR_ANY; // Since this socket is listening for connections, // any local address will do serverInfo.sin_port = htons(m_nDestPortNum); // Convert integer 8888 to network-byte order // and insert into the port field // Bind the socket to our local server address int nret = bind(m_sock, (LPSOCKADDR)&serverInfo, sizeof(struct sockaddr)); if (nret == SOCKET_ERROR) { nret = WSAGetLastError(); return -1; } int val = 1; nret = setsockopt (m_sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&val, sizeof(val)); if (nret == SOCKET_ERROR) { nret = WSAGetLastError(); return -1; } nret = listen (m_sock, nMaxConnections); if (nret == SOCKET_ERROR) { nret = WSAGetLastError(); return -1; } m_bIsValid = true; return 0; } int OS_SocketWin32::AddToSet (void* pSet) { FD_SET* pset = (FD_SET*)pSet; FD_SET (m_sock, pSet); return 0; } bool OS_SocketWin32::IsInSet (void* pSet) { FD_SET* pset = (FD_SET*)pSet; return FD_ISSET (m_sock, pset)?true:false; } int OS_SocketWin32::Connect () { m_bIsValid = false; SOCKADDR_IN serverInfo; serverInfo.sin_family = AF_INET; serverInfo.sin_addr.s_addr = inet_addr(m_szHostName); // Since this socket is listening for connections, // any local address will do serverInfo.sin_port = htons(m_nDestPortNum); // Convert integer 8888 to network-byte order // and insert into the port field // Bind the socket to our local server address int nret = connect(m_sock, (LPSOCKADDR)&serverInfo, sizeof(serverInfo)); if (nret < 0) return -1; m_bIsValid = true; return 0; } int OS_SocketWin32::Close () { closesocket (m_sock); ResetState (); return 0; } OS_Socket* OS_SocketWin32::Accept () { OS_SocketWin32* pNewSock = new OS_SocketWin32 (); pNewSock->m_sock = accept (m_sock, NULL, NULL); if (pNewSock->m_sock < 0) { delete pNewSock; return NULL; } pNewSock->m_bIsValid = true; return pNewSock; } int OS_SocketWin32::Read (void* pDestBuffer, int nMaxBytesToRead) { int rc = recv (m_sock, (char*)pDestBuffer, nMaxBytesToRead, 0); return rc; }
7aed75f5b3ab2e59610521250f5db4e0177f7085
ca1568ca9e25b2fd0be8cb061622fed9ae0da016
/IrrlichtBulletIntegration/IrrlichtBulletIntegration.cpp
4cce9870a54b528c0f75e2d94e9c066a7a97348b
[]
no_license
mahmoudgalal/Irrlicht-Bullet-Integration
3bab65333b143191672d8f3af58e2465513b8552
4c4ad2f5b2fea010b57f2ee70ba9e321d7c2de05
refs/heads/master
2020-04-04T21:23:49.564840
2019-12-17T07:12:22
2019-12-17T07:12:22
156,284,439
11
3
null
null
null
null
UTF-8
C++
false
false
13,969
cpp
IrrlichtBulletIntegration.cpp
/**************************************** Copyright 2018 Mahmoud Galal ****************************************/ #include "baseheader.h" #include "InputEventHandler.h" #ifdef _IRR_WINDOWS_ #pragma comment(lib, "Irrlicht.lib") #pragma comment(linker, "/subsystem:windows /ENTRY:mainCRTStartup") //BulletDynamics.lib BulletCollision.lib LinearMath.lib #pragma comment(lib, "BulletDynamics.lib") #pragma comment(lib, "BulletCollision.lib") #pragma comment(lib, "LinearMath.lib") #endif #include "physicsutils.h" int lastFPS = -1; //Debug text view IGUIStaticText* textNode; //Physics////////////////////// btDiscreteDynamicsWorld* dynamicsWorld; btSequentialImpulseConstraintSolver* solver; btBroadphaseInterface* overlappingPairCache; btCollisionDispatcher* dispatcher; btDefaultCollisionConfiguration* collisionConfiguration; //keep track of the shapes, we release memory at exit. //make sure to re-use collision shapes among rigid bodies whenever possible! btAlignedObjectArray<btCollisionShape*> collisionShapes; ////////////////////////////////////////////// /* Initializes Bullet Physics.... */ void initializePhysics(){ ///-----initialization_start----- ///collision configuration contains default setup for memory, collision setup. Advanced users can create their own configuration. collisionConfiguration = new btDefaultCollisionConfiguration(); ///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded) dispatcher = new btCollisionDispatcher(collisionConfiguration); ///btDbvtBroadphase is a good general purpose broadphase. You can also try out btAxis3Sweep. overlappingPairCache = new btDbvtBroadphase(); ///the default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded) solver = new btSequentialImpulseConstraintSolver; dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, overlappingPairCache, solver, collisionConfiguration); dynamicsWorld->setGravity(btVector3(0, -10, 0)); ///-----initialization_end----- } /** Free Physics **/ void destroyPhysics(){ ///-----cleanup_start----- int i; for (i = dynamicsWorld->getNumConstraints() - 1; i >= 0; i--) { dynamicsWorld->removeConstraint(dynamicsWorld->getConstraint(i)); } //remove the rigidbodies from the dynamics world and delete them for (i = dynamicsWorld->getNumCollisionObjects() - 1; i >= 0; i--) { btCollisionObject* obj = dynamicsWorld->getCollisionObjectArray()[i]; btRigidBody* body = btRigidBody::upcast(obj); if (body && body->getMotionState()) { delete body->getMotionState(); } dynamicsWorld->removeCollisionObject(obj); delete obj; } //delete collision shapes for (int j = 0; j < collisionShapes.size(); j++) { btCollisionShape* shape = collisionShapes[j]; collisionShapes[j] = 0; delete shape; } //delete dynamics world delete dynamicsWorld; //delete solver delete solver; //delete broadphase delete overlappingPairCache; //delete dispatcher delete dispatcher; delete collisionConfiguration; //next line is optional: it will be cleared by the destructor when the array goes out of scope collisionShapes.clear(); } /** Creates a ground Physics object **/ void createPhysicsGroundObject(){ //the ground is a cube of side 100 at position y = -56. //the sphere will hit it at y = -6, with center at -5 { btCollisionShape* groundShape = new btBoxShape(btVector3(btScalar(150.), btScalar(1.), btScalar(150.))); collisionShapes.push_back(groundShape); btTransform groundTransform; groundTransform.setIdentity(); groundTransform.setOrigin(btVector3(0, -56, 0)); btScalar mass(0.); //rigidbody is dynamic if and only if mass is non zero, otherwise static bool isDynamic = (mass != 0.f); btVector3 localInertia(0, 0, 0); if (isDynamic) groundShape->calculateLocalInertia(mass, localInertia); //using motionstate is optional, it provides interpolation capabilities, and only synchronizes 'active' objects btDefaultMotionState* myMotionState = new btDefaultMotionState(groundTransform); btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, myMotionState, groundShape, localInertia); btRigidBody* body = new btRigidBody(rbInfo); body->setUserIndex(5); body->setFriction(1); //add the body to the dynamics world dynamicsWorld->addRigidBody(body); } } /** Drops a physics box **/ void createPhysicsBox(ISceneManager* scenemgr,IVideoDriver* driver){ //create a dynamic rigidbody btCollisionShape* colShape = createBoxShape(btVector3(5,5,5)); //btCollisionShape* colShape = new btBoxShape(btScalar(1.)); collisionShapes.push_back(colShape); /// Create Dynamic Objects btTransform startTransform; startTransform.setIdentity(); btScalar mass(3.f); startTransform.setOrigin(btVector3(10, 40, 20)); btQuaternion quat(btVector3(0.4,.02,.1),67); startTransform.setRotation(quat); btRigidBody* body = createRigidBody(dynamicsWorld,mass,startTransform,colShape);// new btRigidBody(rbInfo); body->setFriction(1); body->setUserIndex(10); IMeshSceneNode* cubeNode = scenemgr->addCubeSceneNode(10.0f,NULL,-1,vector3df(0,3,10)); cubeNode->setMaterialType(EMT_SOLID); cubeNode->setMaterialTexture(0,driver->getTexture("../media/box1.jpg")); cubeNode->setMaterialFlag(video::EMF_LIGHTING, false); cubeNode->setVisible(false); //saving the visual node to the physics node body->setUserPointer(cubeNode); } /** Fires a box from the camera position to the lookat **/ void createPhysicsBoxFromEye(ISceneManager* scenemgr,IVideoDriver* driver,vector3df& position,vector3df& lookat){ //create a dynamic rigidbody btCollisionShape* colShape = new btBoxShape(btVector3(5,5,5)); //btCollisionShape* colShape = new btBoxShape(btScalar(1.)); collisionShapes.push_back(colShape); /// Create Dynamic Objects btTransform startTransform; startTransform.setIdentity(); btScalar mass(6.f); //rigidbody is dynamic if and only if mass is non zero, otherwise static bool isDynamic = (mass != 0.f); btVector3 localInertia(0, 0, 0); if (isDynamic) colShape->calculateLocalInertia(mass, localInertia); startTransform.setOrigin(btVector3(position.X, position.Y, position.Z)); btQuaternion quat(btVector3(0.4,.02,.1),67); startTransform.setRotation(quat); //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform); btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, myMotionState, colShape, localInertia); btRigidBody* body = new btRigidBody(rbInfo); body->setUserIndex(10); body->setDamping(0.01,0.01); ISceneNode* cubeNode = scenemgr->addCubeSceneNode(10.0f,NULL,-1,vector3df(0,3,10)); cubeNode->setMaterialType(EMT_SOLID); cubeNode->setMaterialTexture(0,driver->getTexture("../media/box.jpg")); cubeNode->setMaterialFlag(video::EMF_LIGHTING, false); cubeNode->setVisible(false); body->setUserPointer(cubeNode); body->setFriction(1); btVector3 force(lookat.X,lookat.Y,lookat.Z); dynamicsWorld->addRigidBody(body); body->applyImpulse(250*force,btVector3(0.,0.,0.)); } //Starts physics simulation void stepPhysicsWorld(float timestep){ dynamicsWorld->stepSimulation(timestep*2, 10); } // update 3d objects transformations with the Physics results void renderPhysicsObjectsPose(){ //print positions of all objects int numOfObjects = dynamicsWorld->getNumCollisionObjects(); stringw str = L"Number of physics objects:"; str+=numOfObjects; str+= L"\nPress C to drop a box\n"; str+= L"Press H to Create a Chain\n"; str+= L"Press E to Fire a box\n"; textNode->setText(str.c_str()); for (int j = numOfObjects - 1; j >= 0; j--) { btCollisionObject* obj = dynamicsWorld->getCollisionObjectArray()[j]; btRigidBody* body = btRigidBody::upcast(obj); btTransform trans; if (body && body->getMotionState()) { body->getMotionState()->getWorldTransform(trans); ISceneNode* cube = reinterpret_cast<ISceneNode*>( body->getUserPointer()); if(cube != NULL){//update cubes only btVector3 origin = trans.getOrigin(); //update rotation btQuaternion rot = trans.getRotation(); quaternion q(rot.getX(),rot.getY(),rot.getZ(),rot.getW()); vector3df Euler; q.toEuler(Euler); Euler *= RADTODEG; cube->setPosition(vector3df(origin.getX(),origin.getY(),origin.getZ())); cube->setRotation(Euler); cube->setVisible(true); } } else { trans = obj->getWorldTransform(); } } } /* Create a hanging chain of boxes with joints between parts */ void createChain(int chainitemscount,btVector3& suspensionPoint,ISceneManager* scenemgr,IVideoDriver* driver){ //create a few dynamic rigidbodies // Re-using the same collision is better for memory usage and performance btBoxShape* colShape = createBoxShape(btVector3(4,4,1)); collisionShapes.push_back(colShape); /// Create Dynamic Objects btTransform startTransform; startTransform.setIdentity(); btScalar mass(1.f); //rigidbody is dynamic if and only if mass is non zero, otherwise static bool isDynamic = (mass != 0.f); btVector3 localInertia(0,0,0); if (isDynamic) colShape->calculateLocalInertia(mass,localInertia); btAlignedObjectArray<btRigidBody*> boxes; int lastBoxIndex = chainitemscount-1; for(int i=0;i<chainitemscount;++i) { startTransform.setOrigin(btVector3( btScalar(suspensionPoint.x()), btScalar(suspensionPoint.y()+i*2), btScalar(suspensionPoint.z()) ) ); boxes.push_back(createRigidBody(dynamicsWorld, (i ==lastBoxIndex)?0:mass,startTransform,colShape)); IMeshSceneNode* cubeNode = scenemgr->addCubeSceneNode(8.0f,NULL,-1,vector3df(0,0,0),vector3df(0,0,0), vector3df(1,1,0.25f)); cubeNode->setMaterialType(EMT_SOLID); cubeNode->setMaterialTexture(0,driver->getTexture("../media/steel-box.jpg")); cubeNode->setMaterialFlag(video::EMF_LIGHTING, false); boxes[i]->setUserPointer(cubeNode); } //add N-1 spring constraints for(int i=0;i<chainitemscount-1;++i) { btRigidBody* b1 = boxes[i]; btRigidBody* b2 = boxes[i+1]; btPoint2PointConstraint* leftSpring = new btPoint2PointConstraint(*b1, *b2, btVector3(-2,4,0), btVector3(-2,-4,0)); dynamicsWorld->addConstraint(leftSpring); btPoint2PointConstraint* rightSpring = new btPoint2PointConstraint(*b1, *b2, btVector3(2,4,0), btVector3(2,-4,0)); dynamicsWorld->addConstraint(rightSpring); } } int main(int argc,char* argv[]) { //Start physics initializePhysics(); //Adding earth createPhysicsGroundObject(); //Key event handler InputEventHandler myEventHandler; // start up the irrlicht engine IrrlichtDevice *device = createDevice(video::EDT_DIRECT3D9, dimension2d<u32>(800,600), 32, false, false, false, &myEventHandler); IVideoDriver* driver = device->getVideoDriver(); ISceneManager* scenemgr = device->getSceneManager(); IGUIEnvironment* guienv = device->getGUIEnvironment(); ICameraSceneNode* cameraNode; device->setWindowCaption(L"Irrlicht - Bullet Integration"); //Ground//// IAnimatedMesh* hillPlaneMesh = scenemgr->addHillPlaneMesh( "myHill", core::dimension2d<f32>(30,30), core::dimension2d<u32>(10,10), 0, 0, core::dimension2d<f32>(0,0), core::dimension2d<f32>(10,10)); ISceneNode* planeNode = scenemgr->addAnimatedMeshSceneNode(hillPlaneMesh); planeNode->setMaterialTexture(0, driver->getTexture("../media/stones.jpg")); planeNode->setMaterialFlag(video::EMF_LIGHTING, false); planeNode->setPosition(core::vector3df(0,-55,0)); // add a first person shooter style user controlled camera cameraNode = scenemgr->addCameraSceneNodeFPS(NULL,20.0f,0.02f); cameraNode->setPosition(vector3df(0,10,-70)); textNode = guienv->addStaticText(L"Irrlicht - Bullet Integration Demo", rect<s32>(10,10,260,driver->getScreenSize().Height/4), true); u32 then = device->getTimer()->getTime(); // draw everything while(device->run() && driver /*&& device->isWindowActive()*/) { const u32 now = device->getTimer()->getTime(); //update Physics renderPhysicsObjectsPose(); //Close app if(myEventHandler.IsKeyDown(KEY_SPACE)) break; // Drop a Box if(myEventHandler.IsKeyDown(KEY_KEY_C)){ createPhysicsBox(scenemgr,driver); myEventHandler.ResetCode(KEY_KEY_C); } //Create hanging chain if(myEventHandler.IsKeyDown(KEY_KEY_H)){ createChain(10,btVector3(10+(-30+rand()%100 ),10,20 +(10+rand()%30 )) ,scenemgr,driver); myEventHandler.ResetCode(KEY_KEY_H); } //Fire a box if(myEventHandler.IsKeyDown(KEY_KEY_E)){ vector3df lookat = cameraNode->getTarget(); vector3df pose = cameraNode->getPosition(); createPhysicsBoxFromEye(scenemgr,driver,pose,(lookat-pose).normalize()); myEventHandler.ResetCode(KEY_KEY_E); } driver->beginScene(true, true, video::SColor(255,0,0,255)); scenemgr->drawAll(); guienv->drawAll(); driver->endScene(); // display frames per second in window title int fps = driver->getFPS(); if (lastFPS != fps) { stringw str = L"Irrlicht-Bullet Engine Integration ["; str += driver->getName(); str += "] FPS:"; str += fps; device->setWindowCaption(str.c_str()); lastFPS = fps; } const f32 frameDeltaTime = (f32)(now - then) / 1000.f; // Time in seconds //Simulate Physics stepPhysicsWorld(frameDeltaTime); then = now; } // delete device device->drop(); //Clean destroyPhysics(); return 0; }
f470decbe5029590e2bc0ae30724d53acbd76f92
a362c5dc87cdfc2ef2de12344ca319060943dcdf
/Algoritmica/Practica3/p3.hpp
dad74421aa137b07a5235fefbe5e91d5630026e1
[]
no_license
i72pehej/UNI
29f52a6558468adf107d8b8e167f77505befcdc8
3d78a6495d9884c12cf5b236443c906a6b63dab2
refs/heads/master
2020-08-06T01:34:21.620312
2020-02-07T13:16:16
2020-02-07T13:16:16
212,785,877
1
0
null
null
null
null
UTF-8
C++
false
false
2,141
hpp
p3.hpp
#ifndef P3_HPP #define P3_HPP #include <stdio.h> #include <stdlib.h> #include <string> #include <iostream> #include <cmath> #include "funcionesbajonivel.cpp" using namespace std; //////////////////////////////////////////////////////////////////////////////// // Clase que representa un entero grande class Entero { private: string entero_; // Numero entero en formato de string int tamMin_; // Tamaño minimo del entero grande public: ////////////////////////// CONSTRUCTOR ///////////////////////////////////// inline Entero (string cad = "") { setEntero(cad); } ////////////////////////////// OBSERVADORES //////////////////////////////// inline string getEntero() { return entero_; } inline int getEnteroInt() { return (atoi(this->getEntero().c_str())); } inline int getTamMin() { return tamMin_; } inline int getTam() { string entero = this->getEntero(); return (entero.length() - 1); } inline int es_cero() { string entero = this->getEntero(); string aux; for (size_t i = 0; i < entero.length(); i++) { if (entero[i] != '\0') { aux = entero[i]; int auxInt = atoi(aux.c_str()); if (auxInt != 0) { return 0; } } } return 1; } ////////////////////////////// MODIFICADORES /////////////////////////////// inline void setEntero(const string cad) { entero_ = cad; } ////////////////////////////// SOBRECARGA ////////////////////////////////// Entero operator + (Entero e2); Entero operator * (Entero e2); friend inline istream &operator >> (istream &stream, Entero &entrada) { stream >> entrada.entero_; return stream; } friend inline ostream &operator << (ostream &stream, Entero &salida) { stream << salida.getEntero(); return stream; } inline Entero operator = (Entero e2) { this->setEntero(e2.getEntero()); return *this; } }; //////////////////////////////////////////////////////////////////////////////// #endif
590ca04f73b2ff1bb935b25bb9aee2dffc9a6edd
13a81410aee1d06647554acbdd216b30c6fa3dfb
/core/silkworm/trie/hash_builder.cpp
83e657a177399bc7015f19017ca442d3f1b6b552
[ "Apache-2.0" ]
permissive
gelfand/silkworm
de1e3ad0627231453af61916eae26eb4104df3b8
cc995126e45c48a5c45d6be287a8515f843e602a
refs/heads/master
2023-08-27T10:45:55.027824
2021-09-06T16:57:10
2021-09-06T16:57:10
403,340,245
0
0
Apache-2.0
2021-09-05T15:12:42
2021-09-05T15:12:41
null
UTF-8
C++
false
false
9,307
cpp
hash_builder.cpp
/* Copyright 2020-2021 The Silkworm Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 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 "hash_builder.hpp" #include <algorithm> #include <bitset> #include <cassert> #include <cstring> #include <utility> #include <ethash/keccak.hpp> #include <silkworm/common/cast.hpp> #include <silkworm/common/util.hpp> #include <silkworm/rlp/encode.hpp> namespace silkworm::trie { Bytes unpack_nibbles(ByteView packed) { Bytes out(2 * packed.length(), '\0'); for (size_t i{0}; i < packed.length(); ++i) { out[2 * i] = packed[i] >> 4; out[2 * i + 1] = packed[i] & 0xF; } return out; } static Bytes encode_path(ByteView path, bool terminating) { Bytes res(path.length() / 2 + 1, '\0'); bool odd{path.length() % 2 != 0}; if (!terminating && !odd) { res[0] = 0x00; } else if (!terminating && odd) { res[0] = 0x10; } else if (terminating && !odd) { res[0] = 0x20; } else if (terminating && odd) { res[0] = 0x30; } if (odd) { res[0] |= path[0]; for (size_t i{1}; i < res.length(); ++i) { res[i] = (path[2 * i - 1] << 4) + path[2 * i]; } } else { for (size_t i{1}; i < res.length(); ++i) { res[i] = (path[2 * i - 2] << 4) + path[2 * i - 1]; } } return res; } static Bytes leaf_node_rlp(ByteView path, ByteView value) { Bytes encoded_path{encode_path(path, /*terminating=*/true)}; Bytes rlp; rlp::Header h; h.list = true; h.payload_length = rlp::length(encoded_path) + rlp::length(value); rlp::encode_header(rlp, h); rlp::encode(rlp, encoded_path); rlp::encode(rlp, value); return rlp; } static Bytes extension_node_rlp(ByteView path, ByteView child_ref) { Bytes encoded_path{encode_path(path, /*terminating=*/false)}; Bytes rlp; rlp::Header h; h.list = true; h.payload_length = rlp::length(encoded_path) + child_ref.length(); rlp::encode_header(rlp, h); rlp::encode(rlp, encoded_path); rlp.append(child_ref); return rlp; } static Bytes node_ref(ByteView rlp) { if (rlp.length() < kHashLength) { return Bytes{rlp}; } Bytes rlp_wrapped_hash(kHashLength + 1, '\0'); rlp_wrapped_hash[0] = rlp::kEmptyStringCode + kHashLength; const ethash::hash256 hash{keccak256(rlp)}; std::memcpy(&rlp_wrapped_hash[1], hash.bytes, kHashLength); return rlp_wrapped_hash; } void HashBuilder::add(ByteView packed, ByteView value) { Bytes key{unpack_nibbles(packed)}; assert(key > key_); if (!key_.empty()) { gen_struct_step(key_, key, value_); } key_ = key; value_ = value; } void HashBuilder::finalize() { if (!key_.empty()) { gen_struct_step(key_, {}, value_); key_.clear(); value_.clear(); } } evmc::bytes32 HashBuilder::root_hash() { return root_hash(/*auto_finalize=*/true); } evmc::bytes32 HashBuilder::root_hash(bool auto_finalize) { if (auto_finalize) { finalize(); } if (stack_.empty()) { return kEmptyRoot; } const Bytes& node_ref{stack_.back()}; evmc::bytes32 res{}; if (node_ref.length() == kHashLength + 1) { std::memcpy(res.bytes, &node_ref[1], kHashLength); } else { res = bit_cast<evmc_bytes32>(keccak256(node_ref)); } return res; } // https://github.com/ledgerwatch/erigon/blob/devel/docs/programmers_guide/guide.md#generating-the-structural-information-from-the-sequence-of-keys void HashBuilder::gen_struct_step(ByteView current, const ByteView succeeding, const ByteView value) { for (bool build_extensions{false};; build_extensions = true) { const bool preceding_exists{!groups_.empty()}; // Calculate the prefix of the smallest prefix group containing current const size_t preceding_len{groups_.empty() ? 0 : groups_.size() - 1}; const size_t common_prefix_len{prefix_length(succeeding, current)}; const size_t len{std::max(preceding_len, common_prefix_len)}; assert(len < current.length()); // Add the digit immediately following the max common prefix const uint8_t extra_digit{current[len]}; if (groups_.size() <= len) { groups_.resize(len + 1); } groups_[len] |= 1u << extra_digit; if (tree_masks_.size() < current.length()) { tree_masks_.resize(current.length()); hash_masks_.resize(current.length()); } size_t from{len}; if (!succeeding.empty() || preceding_exists) { ++from; } const ByteView short_node_key{current.substr(from)}; if (!build_extensions) { stack_.push_back(node_ref(leaf_node_rlp(short_node_key, value))); } else if (!short_node_key.empty()) { // extension node if (node_collector && from > 0) { // See node/silkworm/trie/intermediate_hashes.hpp const uint16_t flag = 1u << current[from - 1]; // DB trie can't use hash of an extension node hash_masks_[from - 1] &= ~flag; if (tree_masks_[current.length() - 1]) { // Propagate tree_masks flag along the extension node tree_masks_[from - 1] |= flag; } } stack_.back() = node_ref(extension_node_rlp(short_node_key, stack_.back())); hash_masks_.resize(from); tree_masks_.resize(from); } // Check for the optional part if (preceding_len <= common_prefix_len && !succeeding.empty()) { return; } // Close the immediately encompassing prefix group, if needed if (!succeeding.empty() || preceding_exists) { // branch node std::vector<Bytes> child_hashes{branch_ref(groups_[len], hash_masks_[len])}; // See node/silkworm/trie/intermediate_hashes.hpp if (node_collector) { if (len > 0) { hash_masks_[len - 1] |= 1u << current[len - 1]; } bool store_in_intermediate_hashes{tree_masks_[len] || hash_masks_[len]}; if (store_in_intermediate_hashes) { if (len > 0) { tree_masks_[len - 1] |= 1u << current[len - 1]; // register myself in parent bitmap } std::vector<evmc::bytes32> hashes(child_hashes.size()); for (size_t i{0}; i < child_hashes.size(); ++i) { assert(child_hashes[i].size() == kHashLength + 1); std::memcpy(hashes[i].bytes, &child_hashes[i][1], kHashLength); } Node n{groups_[len], tree_masks_[len], hash_masks_[len], hashes}; if (len == 0) { n.set_root_hash(root_hash(/*auto_finalize=*/false)); } node_collector(current.substr(0, len), n); } } } groups_.resize(len); tree_masks_.resize(len); hash_masks_.resize(len); if (preceding_len == 0) { return; } // Update current key for the build_extensions iteration current = current.substr(0, preceding_len); while (!groups_.empty() && groups_.back() == 0) { groups_.pop_back(); } } } // Takes children from the stack and replaces them with branch node ref. std::vector<Bytes> HashBuilder::branch_ref(uint16_t state_mask, uint16_t hash_mask) { assert_subset(hash_mask, state_mask); std::vector<Bytes> child_hashes; child_hashes.reserve(std::bitset<16>(hash_mask).count()); const size_t first_child_idx{stack_.size() - std::bitset<16>(state_mask).count()}; rlp::Header h; h.list = true; h.payload_length = 1; // for the nil value added below for (size_t i{first_child_idx}, digit{0}; digit < 16; ++digit) { if (state_mask & (1u << digit)) { h.payload_length += stack_[i++].length(); } else { h.payload_length += 1; } } Bytes rlp{}; rlp::encode_header(rlp, h); for (size_t i{first_child_idx}, digit{0}; digit < 16; ++digit) { if (state_mask & (1u << digit)) { if (hash_mask & (1u << digit)) { child_hashes.push_back(stack_[i]); } rlp.append(stack_[i++]); } else { rlp.push_back(rlp::kEmptyStringCode); } } // branch nodes with values are not supported rlp.push_back(rlp::kEmptyStringCode); stack_.resize(first_child_idx + 1); stack_.back() = node_ref(rlp); return child_hashes; } } // namespace silkworm::trie
06ab54f6a060cafb7f9ed5b9ec5b953979c18eca
bc459bcddd023ef777196c34cedb8ae7e1ea68d2
/day5.cc
85e2e0b68f16654e29900039b18427df023d0742
[]
no_license
toastwaffle/AoC2019
ad610e4d5af30aba199579f1d8dec3b0d4795085
c55a577a9665ce5a33060e4fbaa3593f02bbe48e
refs/heads/master
2020-09-25T23:20:16.696652
2019-12-15T20:52:45
2019-12-15T20:52:45
226,111,193
0
0
null
null
null
null
UTF-8
C++
false
false
206
cc
day5.cc
#include <iostream> #include "intcode.h" int main() { std::string filename = "/home/samuel/aoc/day5.txt"; int result = intcode::RunProgram(filename); std::cout << "HALT: " << result << std::endl; }
052210798b0f8d5bffd334f4a6d91eae84e765a3
f8467e34ffc36e7c2330c5e99b875235548c07ee
/ChatServer/ChatServer.h
0a47f3c684485823460f958655f8d9d6839f8715
[]
no_license
wchy1993/IOCP-chatting-room
1c08180bd560d0287086dfe05765a25b2aa54896
8b5cfc40be2a04a923acc82554bff403eac37fbb
refs/heads/master
2020-05-21T06:14:48.779917
2019-05-10T07:28:14
2019-05-10T07:28:14
185,939,740
0
0
null
null
null
null
GB18030
C++
false
false
869
h
ChatServer.h
#if !defined(AFX_CHATSERVER1_H__F6365C1E_C996_4A39_A4BE_505DA39112AC__INCLUDED_) #define AFX_CHATSERVER1_H__F6365C1E_C996_4A39_A4BE_505DA39112AC__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <afxtempl.h> #include "IOCPServer.h" #include "servercommand.h" class CChatServer : public CIOCPServer { public: CChatServer(); virtual ~CChatServer(); protected: virtual BOOL ClientExit(LPCLIENTCONTEXT lpContext); virtual void ProcessReceiveData(LPCLIENTCONTEXT lpContext, CBuffer &buffer); //call back void UserMessageFunc(USERINFO &userSrc,USERINFO &userDest, CString strSpeak); void LoginFunc(USERINFO &user); private: MAPUSER m_mapUsers; CServerCommand<CChatServer> m_cmd; //合法指令 CRITICAL_SECTION m_cs; //互斥变量 }; #endif // !defined(AFX_CHATSERVER1_H__F6365C1E_C996_4A39_A4BE_505DA39112AC__INCLUDED_)
e791a56b67216b01126ffe4da86b5c037d1d942b
f3f15ebb1af5f041ed3edcf920669e9938e42ae1
/UltraSonicSensor/SensorCommsServer.h
fe992b48d8c78416c932486d7c7599fb31f124e9
[]
no_license
Stepper-Motor-Control/MotorControl
f0197aca6cd1eba56b2a68f5f01ca589e068047b
8f45b22583b23b4ba7817e64b195827488d5e390
refs/heads/master
2023-03-06T07:18:01.006755
2021-02-21T04:50:34
2021-02-21T04:50:34
340,816,086
1
0
null
2021-02-21T04:50:35
2021-02-21T04:23:28
C++
UTF-8
C++
false
false
1,465
h
SensorCommsServer.h
#ifndef SENSOR_COMMS_SERVER_H #define SENSOR_COMMS_SERVER_H #include <wiringPi.h> #include <iostream> #include <vector> #include <string.h> #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <mqueue.h> #include <fcntl.h> #include <pthread.h> #include <stdlib.h> #include <unistd.h> #include <mqueue.h> #include <sys/stat.h> #include <errno.h> #include "Comms.h" #include "Client.h" #include "Sensor.h" #include "LcdDisplay.h" #include "StepperMotor.h" using namespace std; class SensorCommsServer { public: // SensorCommsServer() ; SensorCommsServer(Sensor & sensor); ~SensorCommsServer(void); bool GetStatus(void) { return m_Status; } void SetStatus(bool status) { m_Status = status; } int32_t Wait(void); Client *m_pClientCommsTcp; double GetDistance(void) { return m_refSensor.GetDistance();} void DispData(const char *pData, int32_t line); private: uint32_t m_debug; bool m_Status; void Lock(void) { pthread_mutex_lock(&m_lock); } void UnLock(void) { pthread_mutex_unlock(&m_lock); } // Parameters for creating threads pthread_mutex_t m_lock; pthread_attr_t m_attr; pthread_t m_threads; static void *ProcessData(void *pContext); static const int32_t PORT_TO_CONNECT = 8889; Sensor & m_refSensor; LcdDisplay *m_pLcdDisplay; StepperMotor *m_StepperMotor; }; #endif
48a1417a47513fe28f249d7b217b9e4cbaddb04c
c0daac8c93d6c36261883b9a5b9efe12e861a434
/TestPinb/OOP/Object.h
5fbd241b4586a6aa21eaee5f4051cea694bb9b3f
[ "BSD-3-Clause" ]
permissive
cafiorin/PinballOOP
1b485be028319dd178415a417d6df41cbe7c6383
1f8fc5a18bfa186daf3cdc719af9fb79aa42abfa
refs/heads/master
2021-06-08T22:51:32.329275
2019-09-11T16:21:00
2019-09-11T16:21:00
93,624,142
1
0
null
null
null
null
UTF-8
C++
false
false
1,080
h
Object.h
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * BSD 3-Clause License /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * Code by Cassius Fiorin - cafiorin@gmail.com http://pinballhomemade.blogspot.com.br * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef Object__INCLUDED_ #define Object__INCLUDED_ #include "defines.h" class HardwareSerial; class Pinball; class Object { public: Object(); virtual ~Object() {}; #ifdef DEBUGMESSAGES int getId() { return m_Id; } bool operator==(Object& Obj) { if (&Obj != NULL) return (Obj.m_Id == static_cast<const Object&>(*this).m_Id); } bool operator!=(const Object& Obj) { return !(Obj.m_Id != static_cast<const Object&>(*this).m_Id); } void LogMessage(const __FlashStringHelper *szMessage); #endif // DEBUGMESSAGES virtual bool NotifyEvent(Object *sender, uint8_t event, uint8_t value); protected: #ifdef DEBUGMESSAGES uint8_t m_Id; #endif static HardwareSerial *m_Serial; static Pinball *m_Pinball; #ifdef DEBUGMESSAGES private: static uint8_t m_Ids; #endif }; #endif
ec383be1fcad874a2a366a19b2bee17a9a3aa57f
e7137f8554be83fba1408c404c5eab8a4133fb04
/src/Pp.cpp
d0eddfbe7fd019dc8a99defa6ff906b7c8ec94cf
[]
no_license
antiphon/rfhc
0b9f7aeec5bbbd842918a3c621989b08db80248e
0623bd00aaf914a5b16f9c2fa25db65d47e22ccf
refs/heads/master
2016-09-03T07:00:53.655094
2015-06-11T10:00:26
2015-06-11T10:00:26
37,250,533
0
0
null
null
null
null
UTF-8
C++
false
false
6,754
cpp
Pp.cpp
#include "Pp.h" /********************************************************************************************/ Pp::Pp() { } /********************************************************************************************/ Pp::~Pp() { } /********************************************************************************************/ void Pp::Init(SEXP Argspp) { int i, *type; double *x, *y, *m, *m2; Point *p; tor = 0; toroidal = &tor; distances_calculated=0; this->distancep = &Pp::distance_calc; this->nndistancep = &Pp::nndistance_calc; this->m = length(getListElement(Argspp, "x")); x = REAL(getListElement(Argspp, "x")); y = REAL(getListElement(Argspp, "y")); type = INTEGER(getListElement(Argspp, "types")); m = REAL(getListElement(Argspp, "mass")); m2 = REAL(getListElement(Argspp, "mass2")); windowArea = REAL(getListElement(Argspp, "area"))[0]; points.clear(); for(i=0; i < this->size(); i++) { p = new Point(x[i],y[i],type[i]); p->setId(&i); p->setMass(&(m[i])); p->setMass2(&(m2[i])); points.push_back(*p); } this->m = points.size(); this->ntypes = type[this->size()]; xlim = REAL(getListElement(getListElement(Argspp, "window") ,"x")); ylim = REAL(getListElement(getListElement(Argspp, "window") ,"y")); zlim = new double [2];zlim[0]=0; zlim[1]=0; } /********************************************************************************************/ double Pp::getX(int i) {return this->points[i].getX();} double Pp::getY(int i) {return this->points[i].getY();} double Pp::getZ(int i) {return this->points[i].getZ();} int Pp::getT(int i) {return this->points[i].getT();} int Pp::size() {return this->m; } int Pp::nsize(int *i){return this->points[*i].nsize();} int Pp::getCluster(int i){return this->points[i].getCluster();} double Pp::getMass(int *i){return this->points[*i].getMass();} void Pp::setMass(int *i, double *x){this->points[*i].setMass(x);} double Pp::getMass2(int *i){return this->points[*i].getMass2();} void Pp::setMass2(int *i, double *x){this->points[*i].setMass2(x);} int Pp::getNtypes(){return this->ntypes;} double Pp::getWindowArea(){return this->windowArea;} /********************************************************************************************/ void Pp::movePoint(int *i, double *x, double *y){this->points[*i].move(x, y);} void Pp::clearNeighbourhood(int *i) {this->points[*i].clearNeighbourhood();} /********************************************************************************************/ void Pp::distance_precalc() { int i,j; double d; distMatrix.resize(m); for(i=0;i<m;i++)distMatrix.at(i).resize(m); for(i=0; i<m-1;i++){ for(j=i;j<m;j++){ d=distance_calc(&i, &j); distMatrix.at(i).at(j)=d; distMatrix.at(j).at(i)=d; } } distances_calculated = 1; this->distancep = &Pp::distance_fetch; } /********************************************************************************************/ double Pp::distance(int *i, int *j) { return (this->*distancep)(i, j); } /********************************************************************************************/ double Pp::distance_fetch(int *i, int *j) { return distMatrix.at(*i).at(*j); } /********************************************************************************************/ double Pp::distance_calc(int *i, int *j) { if(*i==*j) return 0.0; if(*this->toroidal) return sqrt( pow( fminf( this->xlim[1]-this->xlim[0]-fabs(getX(*i)-getX(*j)) , fabs(getX(*i)-getX(*j)) ) ,2.0) + pow( fminf( this->ylim[1]-this->ylim[0]-fabs(getY(*i)-getY(*j)) , fabs(getY(*i)-getY(*j)) ) ,2.0) + pow( fminf( this->zlim[1]-this->zlim[0]-fabs(getZ(*i)-getZ(*j)) , fabs(getZ(*i)-getZ(*j)) ) ,2.0) ); else return sqrt( pow( getX(*i)- getX(*j) ,2.0) + pow( getY(*i)- getY(*j) ,2.0) + pow( getZ(*i)- getZ(*j) ,2.0) ); } /********************************************************************************************/ void Pp::distance_update(int *i) { if(distances_calculated==0)distance_precalc(); double d; int j; for(j=0; j<m;j++) { d = distance_calc(i, &j); distMatrix.at(*i).at(j)=d; distMatrix.at(j).at(*i)=d; } } /********************************************************************************************/ /********************************************************************************************/ void Pp::nndistance_precalc() { int i; double nnd; nndistvector.resize(m); for(i=0; i<m;i++){ nnd=nndistance_calc(&i); nndistvector.at(i)=nnd; } nndistances_calculated = 1; this->nndistancep = &Pp::nndistance_fetch; } /********************************************************************************************/ double Pp::nndistance(int *i) { return (this->*nndistancep)(i); } /********************************************************************************************/ double Pp::nndistance_calc(int *i) { double *dists = new double[m]; double d; for(int j=0;j<m;j++)dists[j]=distance(i, &j); qsort( dists, m, sizeof(double), compare_doubles); d=dists[1]; delete [] dists; return d; } /********************************************************************************************/ double Pp::nndistance_fetch(int *i) { return nndistvector.at(*i); } /********************************************************************************************/ /********************************************************************************************/ void Pp::addPoint(double x, double y) { int i = points.size()+1,t=0; double z=0; Point *p; p = new Point(x, y, t); p->setId(&i); p->setMass(&z); p->setMass2(&z); points.push_back(*p); this->m++; delete p; } /********************************************************************************************/ void Pp::deletePoint(int i){ points.erase(points.begin()+i); m--; } /********************************************************************************************/ void Pp::addNeighbour(int *i, int *j) { this->points.at(*i).addNeighbour(j); } /********************************************************************************************/ void Pp::removeNeighbour(int *i, int *j) { this->points.at(*i).getNeighbour(j); } /********************************************************************************************/ int Pp::getNeighbour(int *i, int *j) { return this->points.at(*i).getNeighbour(j); } /********************************************************************************************/ void Pp::setCluster(int *i, int *j) { this->points.at(*i).setCluster(j); } /**********************************************************************************/ int compare_doubles(const void *a, const void *b) { const double *da = (const double *) a; const double *db = (const double *) b; return (*da > *db) - (*da < *db); } // EOF
b0e85ef78169267079e2a5f330170c42ec214e5e
04c7e417de26b1a962525ad54accf3a405b7aa7b
/15_Separation_Files/15_Separation_Files.cpp
c557df28fb44facb4e53b65d9b9166e1a0200022
[]
no_license
sw609/Cpp_Learning
31fa85f920989bcf6a18a7549cfb262b98e9613d
f53131510bbc1e2c7f69ec5cebe4a01d24d92a08
refs/heads/master
2020-04-06T16:34:22.485911
2018-11-29T01:31:30
2018-11-29T01:31:30
157,625,073
0
0
null
null
null
null
UTF-8
C++
false
false
129
cpp
15_Separation_Files.cpp
#include<iostream> #include"burrito.h" #include"burrito.cpp" using namespace std; int main(){ Burrito bo; return 0; }
13076ca836eeaff28e8fcdd75dc9fe2ceb05ea90
39786e931bc53b68d397e12e161e7f36359e335a
/src/ipclib/ipclib.h
8b6c8bd6910280081757c9f1011ef2f9ec95c17e
[]
no_license
YAlex1/examination_arrival
d66644f7a68fd679aa427fdb72657d4c9a31e75b
08f5dbfec89bdaf1004911f688821a82ccbfb854
refs/heads/main
2023-01-05T23:39:44.299872
2020-11-05T22:25:54
2020-11-05T22:25:54
309,970,023
0
0
null
null
null
null
UTF-8
C++
false
false
435
h
ipclib.h
#pragma once #include <memory> #include "ipccomm.h" namespace Ipc { /* *@brief This is factory method, which creates an instance of IPC Communicator object * in dynamic memory (heap) region. */ template<typename T> typename IpcComm<T>::pointer_type getIpcCommunicator(char mode, std::string fifo_path = cIpcCommFifoPath) { return std::unique_ptr<IpcComm<T> >(new IpcComm<T>(mode, fifo_path)); } } // namespace Ipc
a848ed68f0694432247ae87774a50e1de2fcad56
9ad49ca220daf4f510224ca59fa1a60bddb85280
/giving tree of errors 3.0.cpp
eb0ce59e791fe11f74142ef4df8a2acf5c0e8895
[]
no_license
bencimp/giving-tree-of-errors
d7b4f3eec7cfaa1033dc0119fb26577ba2429a25
1ae12399c6783df5afb9a682787c143807ba47a0
refs/heads/main
2023-07-27T12:49:08.150630
2021-09-10T20:24:27
2021-09-10T20:24:27
403,611,540
1
0
null
null
null
null
UTF-8
C++
false
false
6,831
cpp
giving tree of errors 3.0.cpp
#include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <string> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include <climits> #include <cstring> #include <cstdlib> #include <fstream> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> #include <unordered_map> #include <regex> #include <unordered_set> //By Ben Cimperman using namespace std; string recurThroughTree(unordered_map<char, vector<char>> map, char key); int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ //Since the definition of this is recursive, I imagine that the solution will likely be recursive, at least when it comes to printing. //This problem has n parts, as far as I see from an initial glance. //The first part is parsing the input into a binary tree and storing it. Preliminarily, I'm thinking about using a Vector or other linearly-arranged array-like container where children of node n can // be stored in slots 2n and 2n+1. This makes it very quick to check for the presence of any children, and overall is pretty quick and not space-inefficient. //The second part is error checking. // E1 (Invalid Input) is pretty trivial to check for using a regular expression. // E2 (Duplicate Pairs) could be checked for in a number of ways, and won't be too great of a challenge. Doing it time efficiently, however, may be a different story. Naive solution would be a // nested for loop, I'm gonna go with a hashmap for lower time complexity. // E3 (Too Many Children) is pretty simple to solve: you could either use a map, or you could check for an open slot in the implementation I discussed in the first part when you try to assign a new // member to the slot. // E4 (Multiple Roots) // E5 (Looping Structure) might be a tough one to run time-efficiently. It may also make sense to implement this in a //The third part is printing it in lexicographically smallest order. This could be done by checking to ensure that they are inserted in this order and recursively moving the children to new slots, or // by sorting the input first, although that may be a bigger headache than it's worth. Another way of accomplishing this would be through checking at print time which is lexicographically smaller // and simply calling the recursive print function on the smaller first. This solution is naive, though, and may add additional time complexity. //Take input string input; getline(cin, input); //This regex checks for error 1 and prints an error and returns 0 if there is not a match. regex error1 ("(\\([A-Z],[A-Z]\\)\\s?)+\\n?"); if(!(regex_match(input, error1))){ cout << "E1"; return 0; } //This splits the input (which we have just sanitized) into strings and pushes them into a "staging" vector. vector<string> stageVec; string hold; stringstream myStream(input); while(!myStream.eof()){ getline(myStream, hold, ' '); stageVec.push_back(hold); } //This unordered map checks for error 2, printing an error if there are any duplicate entries. unordered_map<string, int> error2; for(unsigned int x = 0; x < stageVec.size(); x ++){ error2[stageVec[x]] += 1; if (error2[stageVec[x]] == 2){ cout << "E2"; return 0; } } //This unordered map checks for error 3 by counting the number of children for each node and rejecting if it has more than three. This test abuses the fact that I've sanitized my inputs already by // just looking at the second character in the element of stageVec we grab. Cheeky! unordered_map<char, int> error3; for(unsigned int x = 0; x < stageVec.size(); x ++){ error3[stageVec[x][1]] += 1; if (error3[stageVec[x][1]] > 2){ cout << "E3"; return 0; } } //This unordered map checks for error 4 using an unordered set to collect all of the names of nodes, and then checking to see if that node has any parents using yet another unordered map. unordered_set<char> nodeNames; for (unsigned int x = 0; x < stageVec.size(); x ++){ nodeNames.insert(stageVec[x][1]); nodeNames.insert(stageVec[x][3]); } unordered_map<char, vector<char>> error4; for(unsigned int x = 0; x < stageVec.size(); x ++){ error4[stageVec[x][3]].push_back(stageVec[x][1]); } bool foundRoot = false; char root; for (auto x : nodeNames){ if (error4.find(x) == error4.end()){ if (foundRoot == false){ foundRoot = true; root = x; } else{ cout << "E4"; return 0; } } } //This test is for error 5. An interesting property of cycles in input is that they will all come about when a node has more than one parent. So, if we check each node to ensure it only has one // parent using a test very similar to test three, we will avoid input loops entirely. if (root == NULL){ cout << "E5"; return 0; } unordered_map<char, int> error5; for(unsigned int x = 0; x < stageVec.size(); x ++){ error5[stageVec[x][3]] += 1; if (error5[stageVec[x][1]] > 1){ cout << "E5"; return 0; } } //This function parses and prints the tree. unordered_map<char, vector<char>> map; for(unsigned int x = 0; x < stageVec.size(); x ++){ map[stageVec[x][1]].push_back(stageVec[x][3]); } cout << "(" + recurThroughTree(map, root) + ")"; return 0; } string recurThroughTree(unordered_map<char, vector<char>> map, char key){ //find() the key. This initially caused much consternation, because I was getting a rather confusing segfault. Turns out, since nodes without children don't have entries in the map. string pass(1,key); auto holder = map.find(key); if(holder == map.end()){ return pass; } auto valueVec = holder->second; //if it has one child, call recurThroughTree, passing in the child if(valueVec.size() == 1){ return pass + "(" + recurThroughTree(map, valueVec[0]) + ")"; } //if it has two children (which it must to have reached this point), sort them lexicographically, then call recurseThroughTree on them in order else{ if(valueVec[0] < valueVec[1]) return pass + "(" + recurThroughTree(map, valueVec[0]) + ")("+ recurThroughTree(map, valueVec[1]) + ")"; if(valueVec[0] > valueVec[1]) return pass + "(" + recurThroughTree(map, valueVec[1]) + ")("+ recurThroughTree(map, valueVec[0]) + ")"; } return ""; }
b9fbd4dddb5c2d57162d700a950e8b6b754a3834
b7affb57d4bc5d5d15ac594fb62733f6211feade
/Windows/glfw_mini_01/GUI/GUI.Layout.cpp
c7fe8f11d87aa0a7ed36c9b6e3daf9f2c6baa116
[]
no_license
geordieboy83/dark-water
a979f467c03440928f7e0d85c1a7c5377caca65a
1e3c4c4742318b674a98896160b7ea1015c4c193
refs/heads/master
2021-01-22T11:38:07.455961
2013-01-19T20:26:49
2013-01-19T20:26:49
39,701,021
0
0
null
null
null
null
UTF-8
C++
false
false
20,756
cpp
GUI.Layout.cpp
#include "GUI.Layout.h" extern FontSystem *GUIFonts; extern UITexturing* GUITextures; extern UIScreens* GUIScreens; extern UIEvents* GUIEvents; extern SoundSystem* GUISounds; void LayoutSwitch::switch_layout() { source->set_active(false); target->set_active(true); Button* b=source->get_button(trigger_id); if(b->fire) b->fire(); b->reset(); GUIScreens->current=target; } void LayoutSwitch::update() { } void Layout::play_bgm() { if(!GUISounds) return; if(!bgm_playing){ BGM=GUISounds->ambientloop(BGM_ID); bgm_playing=true; } } void Layout::stop_bgm() { if(!GUISounds) return; GUISounds->stop(BGM); bgm_playing=false; } bool Layout::update() { if(has_bgm&&!bgm_playing) play_bgm(); bool flag=update_internals(); compile_report(); return flag; } void Layout::compile_report() { booleans.clear(); floats.clear(); strings.clear(); ints.clear(); for(map<string,Layout>::iterator i=tabbed_layouts.begin(); i!=tabbed_layouts.end(); i++) { i->second.compile_report(); map<string,bool>* tab_bools=i->second.get_bools(); booleans.insert(tab_bools->begin(),tab_bools->end()); map<string,float>* tab_floats=i->second.get_floats(); floats.insert(tab_floats->begin(),tab_floats->end()); map<string,string>* tab_strings=i->second.get_strings(); strings.insert(tab_strings->begin(),tab_strings->end()); map<string,int>* tab_ints=i->second.get_ints(); ints.insert(tab_ints->begin(),tab_ints->end()); } for(int i=0; i<sliders.size(); i++){ floats.insert(floats.begin(),pair<string,float>(sliders[i].get_ID(),sliders[i].get_value())); ints.insert(ints.begin(),pair<string,int>(sliders[i].get_ID(),sliders[i].get_int())); } for(int i=0; i<buttonarrays.size(); i++){ strings.insert(strings.begin(),pair<string,string>(buttonarrays[i].get_ID(),buttonarrays[i].get_active())); } for(int i=0; i<buttons.size(); i++){ booleans.insert(booleans.begin(),pair<string,bool>(buttons[i].get_ID(),buttons[i].get_value())); } for(int i=0; i<menus_static.size(); i++){ List* l = dynamic_cast<List*>(menus_static[i]); if(l==NULL) { map<string,bool>* flags=menus_static[i]->get_flags(); } else { strings.insert(strings.begin(),pair<string,string>(l->get_ID(),l->get_selection())); } } for(int i=0; i<menus_floating.size(); i++){ List* l = dynamic_cast<List*>(menus_floating[i]); if(l==NULL) { map<string,bool>* flags=menus_floating[i]->get_flags(); } else { strings.insert(strings.begin(),pair<string,string>(l->get_ID(),l->get_selection())); } } for(int i=0; i<consoles.size(); i++){ strings.insert(strings.begin(),pair<string,string>(consoles[i].get_ID(),consoles[i].get_content())); } } bool Layout::update_internals() { if(!active) return false; bool flag=false, flag2=false; for(int i=0; i<menus_floating.size(); i++){ flag2=menus_floating[i]->update(); flag=flag||flag2; } if(flag) return true; for(int i=0; i<consoles.size(); i++){ flag2=consoles[i].update(); flag=flag||flag2; } if(flag) return true; for(int i=0; i<menus_static.size(); i++){ flag2=menus_static[i]->update(); flag=flag||flag2; } if(flag) return true; for(int i=0; i<sliders.size(); i++){ flag2=sliders[i].update(); flag=flag||flag2; } if(flag) return true; flag2=tabs.update(); flag=flag||flag2; map<string,Layout>::iterator i; if(flag){ for(i=tabbed_layouts.begin(); i!=tabbed_layouts.end(); i++){ i->second.set_active(tabs.get_active()==i->second.ID); } return true; } if(tabs.number_of_buttons()!=NULL&&tabs.get_active()!=""){ flag2=tabbed_layouts[tabs.get_active()].update(); flag=flag||flag2; } if(flag) return true; for(int i=0; i<buttonarrays.size(); i++){ flag2=buttonarrays[i].update(); flag=flag||flag2; } if(flag) return true; for(int i=0; i<buttons.size(); i++){ flag2=buttons[i].update(); flag=flag||flag2; } for(int i=0; i<switches.size(); i++){ Button* btn=get_button(switches[i].trigger_id); if(btn->get_value()) switches[i].switch_layout(); } if(flag) return true; return false; } void Layout::display() { if(!active) return; glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); for(int i=0; i<quads.size(); i++){ display_quad(i); } tabs.display(); map<string,Layout>::iterator i=tabbed_layouts.begin(); for(int i=0; i<sliders.size(); i++){ sliders[i].display(); } for(int i=0; i<buttonarrays.size(); i++){ buttonarrays[i].display(); } for(int i=0; i<buttons.size(); i++){ buttons[i].display(); } for(int i=0; i<menus_static.size(); i++){ menus_static[i]->display(); } if(tabs.number_of_buttons()!=NULL&&tabs.get_active()!="") tabbed_layouts[tabs.get_active()].display(); for(int i=0; i<texts.size(); i++){ texts[i].display(); } for(int i=0; i<consoles.size(); i++){ consoles[i].display(); } for(int i=0; i<menus_floating.size(); i++){ menus_floating[i]->display(); } glDisable(GL_BLEND); } Layout::~Layout() { for(int i=0; i<menus_static.size(); i++) delete menus_static[i]; for(int i=0; i<menus_floating.size(); i++) delete menus_floating[i]; } void Layout::display_quad(int index) { if(quads[index].texture_id!="NONE") { glBindTexture(GL_TEXTURE_2D,GUITextures->get(quads[index].texture_id)); } else glBindTexture(GL_TEXTURE_2D,0); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glColor3f(0,0,1); glBegin(GL_QUADS); glTexCoord2i(0,0); glVertex2f(quads[index].lower_left.x,quads[index].lower_left.y); glTexCoord2i(1,0); glVertex2i(quads[index].upper_right.x,quads[index].lower_left.y); glTexCoord2i(1,1); glVertex2i(quads[index].upper_right.x,quads[index].upper_right.y); glTexCoord2i(0,1); glVertex2i(quads[index].lower_left.x,quads[index].upper_right.y); glEnd(); } void Layout::add_tab(string id, Layout& tab) { tabs.add_button(Button(id)); tab.set_ID(id); tabbed_layouts.insert(tabbed_layouts.begin(),pair<string,Layout>(id, tab)); if(tabbed_layouts.size()==1) activate_tab(id); else { tabs.get_button(id)->reset(); tabbed_layouts[id].set_active(false); } } void Layout::add_tab(Button& head, Layout& tab) { string id=head.get_ID(); tabs.add_button(head); tab.set_ID(id); tabbed_layouts.insert(tabbed_layouts.begin(),pair<string,Layout>(id, tab)); if(tabbed_layouts.size()==1) activate_tab(id); else { tabs.get_button(id)->reset(); tabbed_layouts[id].set_active(false); } } void Layout::activate_tab(string ID) { if(ID=="") return; tabs.get_button(ID)->force_active(); tabbed_layouts[ID].set_active(true); tabs.set_active(ID); } bool Layout::save_configuration(string filename) { ofstream out(filename); if(!out) return false; save(out); out.close(); return true; } bool Layout::save(ofstream& out) { int w, h; glfwGetWindowSize(&w,&h); out << "LAYOUT" << endl; out << ID << endl; out << "BEGIN" << endl; out << w << endl << h << endl; out << "QUADS" << endl << quads.size() << endl; for(int i=0; i<quads.size(); i++){ save_quad(out,&quads[i]); } out << "TEXTS" << endl << texts.size() << endl; for(int i=0; i<texts.size(); i++){ save_text(out, &texts[i]); } out << "SLIDERS" << endl << sliders.size() << endl; for(int i=0; i<sliders.size(); i++){ save_slider(out,&sliders[i]); } out << "BUTTONS" << endl << buttons.size() << endl; for(int i=0; i<buttons.size(); i++){ save_button(out,&buttons[i]); } out << "BUTTONARRAYS" << endl << buttonarrays.size() << endl; for(int i=0; i<buttonarrays.size(); i++){ save_buttonarray(out,&buttonarrays[i]); } out << "STATIC MENUS" << endl << menus_static.size() << endl; for(int i=0; i<menus_static.size(); i++) { List* l = dynamic_cast<List*>(menus_static[i]); if(l!=NULL) save_list(out, l); else save_menu(out, menus_static[i]); } out << "FLOATING MENUS" << endl << menus_floating.size() << endl; for(int i=0; i<menus_floating.size(); i++) { List* l = dynamic_cast<List*>(menus_floating[i]); if(l!=NULL) save_list(out, l); else save_menu(out, menus_floating[i]); } vector<string> tbs=tabs.get_button_ids(); out << "TABS" << endl << tbs.size() << endl; out << "ACTIVE" << endl << tabs.get_active() << endl; for(int i=0; i<tbs.size(); i++){ Tab t=get_tab(tbs[i]); save_tab(out,&t); } out << "SWITCHES" << endl << switches.size() << endl; for(int i=0; i<switches.size(); i++) { save_switch(out, &switches[i]); } out << ID << " ENDS" << endl; return true; } void Layout::save_switch(ofstream& out, LayoutSwitch* lsw) { out<< "SWITCH" << endl << lsw->trigger_id << endl << lsw->target->get_ID() << endl; } void Layout::save_text(ofstream& out, Text* t) { out << "TEXT" << endl; out << t->text << endl << t->font << endl << t->font_size << endl << t->origin.x << endl << t->origin.y << endl; out << t->text_colour.r << endl << t->text_colour.g << endl << t->text_colour.b << endl << t->text_colour.a << endl; } void Layout::save_slider(ofstream& out, Slider* sl) { out << "SLIDER" << endl; int x, y; sl->get_control()->get_size(x,y); out << sl->get_ID() << endl << x << endl << y << endl << sl->get_bar_height_factor() << endl << sl->get_from().x << endl << sl->get_from().y << endl << sl->get_to().x << endl << sl->get_to().y << endl << sl->get_value() << endl << sl->get_bar_texture() << endl << sl->get_control_texture() << endl; } void Layout::save_quad(ofstream& out, Quad* q) { out << "QUAD" << endl; out << q->lower_left.x << endl << q->lower_left.y << endl << q->upper_right.x << endl << q->upper_right.y << endl << q->texture_id << endl; } void Layout::save_button(ofstream& out, Button* b) { int x, y; b->get_size(x,y); out << "BUTTON" << endl; out << b->get_ID() << endl << b->get_font_id() << endl << b->get_font_size() << endl; if(b->is_unclickable()) out << "UNCLICKABLE" << endl; else out << "NON_UNCLICKABLE" << endl; if(b->is_sticky()) out << "STICKY" << endl; else out << "NON_STICKY" << endl; if(b->is_round()) out << "ROUND" << endl; else out << "SQUARE" << endl; if(b->is_invisible()) out << "INVISIBLE" << endl; else out << "VISIBLE" << endl; if(b->is_textbox()) out << "TEXTBOX" << endl; else out << "REGULAR" << endl; out << b->get_text() << endl << b->get_origin().x << endl << b->get_origin().y << endl << x << endl << y << endl; for(int i=BTN_INACTIVE;i<BTN_STATES;i++){ out << i << endl << b->get_texture(i) << endl; if(b->has_display(i)) out << "NOT NULL" << endl; else out << "NULL" << endl; } } void Layout::save_buttonarray(ofstream& out, ButtonArray* ba) { vector<string> btns=ba->get_button_ids(); out << "BUTTONARRAY" << endl << ba->get_ID() << endl << btns.size() << endl << ba->get_active() << endl; for(int i=0;i<btns.size(); i++){ save_button(out, ba->get_button(btns[i])); } } void Layout::save_menu(ofstream& out, Menu* m) { out << "MENU" << endl; out << m->get_ID() << endl << m->get_origin().x << endl << m->get_origin().y << endl << m->get_font() << endl << m->get_font_size() << endl << m->get_menumap() << endl; for(int i=BTN_INACTIVE;i<BTN_STATES;i++){ out << i << endl; out << m->get_texture(i) << endl; if(m->has_display(i)) out << "NOT NULL" << endl; else out << "NULL" << endl; } } void Layout::save_list(ofstream& out, List* l) { out << "LIST" << endl; out << l->get_ID() << endl << l->get_origin().x << endl << l->get_origin().y << endl << l->get_font() << endl << l->get_font_size() << endl << l->get_menumap() << endl; out << "CHOICE" << endl << l->get_selection() << endl; for(int i=BTN_INACTIVE;i<BTN_STATES;i++){ out << i << endl; out << l->get_texture(i) << endl; if(l->has_display(i)) out << "NOT NULL" << endl; else out << "NULL" << endl; } } void Layout::save_tab(ofstream& out, Tab* t) { out<< "TAB" << endl << t->tab_header->get_ID() << endl; out<<"TAB HEADER"<< endl; save_button(out,t->tab_header); out<<"TAB BODY" << endl; t->tab_layout->save(out); } bool Layout::load_configuration(string filename) { ifstream in(filename); if(!in) return false; reset(); load(in); in.close(); compile_report(); return true; } bool Layout::load_configuration(ifstream& filename) { reset(); load(filename); compile_report(); return true; } bool Layout::load(ifstream& in) { int w, h; glfwGetWindowSize(&w,&h); string s; getline(in, s); if(s!="LAYOUT") return false; getline(in,ID); getline(in,s); if(s!="BEGIN") return fail(); int layout_x, layout_y; float xfactor, yfactor; getline(in,s); layout_x=atoi(s.c_str()); getline(in,s); layout_y=atoi(s.c_str()); xfactor=(float)w/(float)layout_x; yfactor=(float)w/(float)layout_x; getline(in,s); if(s!="QUADS") return fail(); getline(in,s); int multitude=atoi(s.c_str()); for(int i=0; i<multitude; i++){ Quad q=load_quad(in, xfactor, yfactor); add_quad(q.lower_left.x,q.lower_left.y,q.upper_right.x-q.lower_left.x,q.upper_right.y-q.lower_left.y,q.texture_id); } getline(in,s); if(s!="TEXTS") return fail(); getline(in,s); multitude=atoi(s.c_str()); for(int i=0; i<multitude; i++){ add_text(load_text(in, xfactor, yfactor)); } getline(in,s); if(s!="SLIDERS") return fail(); getline(in,s); multitude=atoi(s.c_str()); for(int i=0; i<multitude; i++){ add_slider(load_slider(in, xfactor, yfactor)); } getline(in,s); if(s!="BUTTONS") return fail(); getline(in,s); multitude=atoi(s.c_str()); for(int i=0; i<multitude; i++){ add_button(load_button(in, xfactor, yfactor)); } getline(in,s); if(s!="BUTTONARRAYS") return fail(); getline(in,s); multitude=atoi(s.c_str()); for(int i=0; i<multitude; i++){ add_buttonarray(load_buttonarray(in, xfactor, yfactor)); } getline(in,s); if(s!="STATIC MENUS") return fail(); getline(in,s); multitude=atoi(s.c_str()); for(int i=0; i<multitude; i++){ add_static_menu(load_menu(in, xfactor, yfactor)); } getline(in,s); if(s!="FLOATING MENUS") return fail(); getline(in,s); multitude=atoi(s.c_str()); for(int i=0; i<multitude; i++){ add_floating_menu(load_menu(in, xfactor, yfactor)); } getline(in,s); if(s!="TABS") return fail(); getline(in,s); multitude=atoi(s.c_str()); getline(in,s); if(s!="ACTIVE") return fail(); getline(in,s); for(int i=0; i<multitude; i++){ load_tab(in, xfactor, yfactor); } activate_tab(s); getline(in,s); if(s!="SWITCHES") return fail(); getline(in,s); multitude=atoi(s.c_str()); for(int i=0; i<multitude; i++) { load_switch(in); } getline(in,s); string s2=ID+" ENDS"; if(s!=s2) return fail(); return true; } LayoutSwitch Layout::load_switch(ifstream &in) { string s, trigger, target; getline(in,s); getline(in,trigger); getline(in,target); return *(add_switch(trigger, target)); } Text Layout::load_text(ifstream& in, float xfactor, float yfactor)//, Text* t) { string txt, font,s; int font_size; Pixel v; getline(in,s); getline(in,txt); getline(in,font); getline(in,s); font_size=atoi(s.c_str()); getline(in,s); v.x=atof(s.c_str())*xfactor; getline(in,s); v.y=atof(s.c_str())*yfactor; float r,g,b,a; getline(in,s); r=atof(s.c_str()); getline(in,s); g=atof(s.c_str()); getline(in,s); b=atof(s.c_str()); getline(in,s); a=atof(s.c_str()); Text t(txt,font,font_size*yfactor,v); t.set_colour(r,g,b,a); return t; } Slider Layout::load_slider(ifstream& in, float xfactor, float yfactor)//, Slider* sl) { Pixel from, to; int x, y; float value, barheight; string id,s; getline(in,s); getline(in,id); getline(in,s); x=atoi(s.c_str())*xfactor; getline(in,s); y=atoi(s.c_str())*yfactor; getline(in,s); barheight=atof(s.c_str()); getline(in,s); from.x=atof(s.c_str())*xfactor; getline(in,s); from.y=atof(s.c_str())*yfactor; getline(in,s); to.x=atof(s.c_str())*xfactor; getline(in,s); to.y=atof(s.c_str())*yfactor; getline(in,s); value=atof(s.c_str()); Slider sl(id,from,to,value,x,y,barheight); getline(in,s); sl.set_bar_texture(s); getline(in,s); sl.set_control_texture(s); return sl; } Quad Layout::load_quad(ifstream& in, float xfactor, float yfactor) { float llx, lly, urx, ury; string s, tex_id; getline(in,s); getline(in,s); llx=atof(s.c_str())*xfactor; getline(in,s); lly=atof(s.c_str())*yfactor; getline(in,s); urx=atof(s.c_str())*xfactor; getline(in,s); ury=atof(s.c_str())*yfactor; getline(in,tex_id); return Quad(llx,lly,urx-llx,ury-lly,tex_id); } Button Layout::load_button(ifstream& in, float xfactor, float yfactor) { int x, y, fontsize; string ID, font_id, text, s; Pixel v; bool unclickable, round, sticky, invisible, textbox; getline(in,s); getline(in, ID); getline(in, font_id); getline(in, s); fontsize=atoi(s.c_str())*yfactor; getline(in, s); if(s=="UNCLICKABLE") unclickable=true; else unclickable=false; getline(in, s); if(s=="STICKY") sticky=true; else sticky=false; getline(in, s); if(s=="ROUND") round=true; else round=false; getline(in, s); if(s=="INVISIBLE") invisible=true; else invisible=false; getline(in, s); if(s=="TEXTBOX") textbox=true; else textbox=false; getline(in, text); getline(in, s); v.x=atof(s.c_str())*xfactor; getline(in, s); v.y=atof(s.c_str())*yfactor; getline(in, s); x=atoi(s.c_str())*xfactor; getline(in, s); y=atoi(s.c_str())*yfactor; Button b(ID,text); b.set_size(x,y); b.set_font(font_id, fontsize); b.set_origin(v); if(round) b.set_round(); else b.set_square(); if(unclickable) b.set_unclickable(); else b.set_non_unclickable(); if(sticky) b.set_sticky(); else b.set_non_sticky(); if(invisible) b.invisibility(); else b.visibility(); b.set_textbox(textbox); for(int i=BTN_INACTIVE;i<BTN_STATES;i++){ getline(in, s); getline(in, s); b.set_texture(i,s); getline(in, s); if(s=="NULL") b.set_display(i,NULL); } b.set_size(x,y); return b; } ButtonArray Layout::load_buttonarray(ifstream& in, float xfactor, float yfactor) { string active, s, id; int buttons; getline(in,s); getline(in,id); getline(in,s); buttons=atoi(s.c_str()); getline(in, active); ButtonArray ba(id); for(int i=0; i<buttons; i++){ ba.add_button(load_button(in, xfactor, yfactor)); } ba.set_active(active); return ba; } Menu* Layout::load_menu(ifstream& in, float xfactor, float yfactor) { string s, ID, menumap, font, header; Pixel v; int font_size; getline(in,header); getline(in,ID); getline(in, s); v.x=atof(s.c_str())*xfactor; getline(in, s); v.y=atof(s.c_str())*yfactor; getline(in, font); getline(in, s); font_size=atoi(s.c_str())*yfactor; getline(in, menumap); Menu* m; if(header=="MENU") { m=new Menu(ID,menumap,font,font_size); m->set_origin(v); } else if(header=="LIST") { m=new List(ID,menumap,font,font_size); m->set_origin(v); getline(in,s); getline(in,s); ((List*)m)->set_selection(s); } else m=NULL; for(int i=BTN_INACTIVE;i<BTN_STATES;i++){ getline(in, s); getline(in, s); m->set_texture(i,s); getline(in, s); if(s=="NULL") m->set_display(i,NULL); } return m; } void Layout::load_tab(ifstream& in, float xfactor, float yfactor) { string s,ID; getline(in, s); if(s!="TAB") return; getline(in,ID); add_tab(ID,Layout(ID)); Tab t=get_tab(ID); getline(in,s); if(s!="TAB HEADER") return; Button b=load_button(in,xfactor,yfactor); *(t.tab_header)=b; getline(in, s); if(s!="TAB BODY") return; t.tab_layout->load_configuration(in); } void Layout::reset() { ID=""; quads.clear(); buttonarrays.clear(); buttons.clear(); tabs.reset(); tabbed_layouts.clear(); switches.clear(); texts.clear(); for(int i=0; i<menus_floating.size(); i++) delete menus_floating[i]; menus_floating.clear(); for(int i=0; i<menus_static.size(); i++) delete menus_static[i]; menus_static.clear(); } LayoutSwitch* Layout::add_switch(string id, string target) { switches.push_back(LayoutSwitch()); LayoutSwitch* lsw=&switches.back(); lsw->trigger_id=id; lsw->target=GUIScreens->get(target); lsw->source=this; get_button(id)->set_sticky(); return lsw; }
b674ca9bad1ea361dac161db8415790c33726c0a
28bb5aaedd62c29561b6b36427e9647be25d0b8b
/src/sorting.cpp
dbd7f5f0d2e5db39a4fe7abd981e44f8724d8f26
[ "MIT" ]
permissive
KirovVerst/algorithms
6bae489057572c36bce61add3980679b5085d9b7
eb00b14539566cbfcabf7afea35031f7dd5e8536
refs/heads/master
2021-01-21T14:15:59.476162
2017-07-30T20:35:53
2017-07-30T20:35:53
95,256,414
0
0
null
null
null
null
UTF-8
C++
false
false
3,313
cpp
sorting.cpp
#include "sorting.h" #include <utility> #include <cmath> typedef bool (*Comparator)(const double &, const double &); bool lower_than(const double &a, const double &b) { return a < b; } bool larger_than(const double &a, const double &b) { return a > b; } std::pair<int, int> quick_sort_partition(double *arr, int low, int high, Comparator &comparator) { std::pair<int, int> bounds; if (high - low <= 1) { if (arr[high] < arr[low]) std::swap(arr[high], arr[low]); bounds.first = low; bounds.second = high; return bounds; } int mid = low; double pivot = arr[high]; while (mid <= high) { if (arr[mid] == pivot) { mid++; } else if (comparator(pivot, arr[mid])) { std::swap(arr[low++], arr[mid++]); } else { std::swap(arr[mid], arr[high--]); } } bounds.first = low; bounds.second = mid - 1; return bounds; } void quick_sort(double *arr, int l, int r, Comparator &comparator) { if (l >= r) { return; } int k = (l + r) / 2; std::swap(arr[r], arr[k]); std::pair<int, int> bounds = quick_sort_partition(arr, l, r, comparator); quick_sort(arr, l, bounds.first - 1, comparator); quick_sort(arr, bounds.second + 1, r, comparator); } void quick_sort(double *arr, int size, bool is_asc) { Comparator comparator = is_asc ? larger_than : lower_than; quick_sort(arr, 0, size - 1, comparator); } void insertion_sort(double *arr, int size, bool is_asc) { Comparator comparator = is_asc ? larger_than : lower_than; for (int i = 1; i < size; i++) { double key = arr[i]; int j = i - 1; while (j >= 0 && comparator(key, arr[j])) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key; } } void selection_sort(double *arr, int size, bool is_asc) { Comparator comparator = is_asc ? larger_than : lower_than; for (int i = 0; i < size - 1; i++) { int index = i; for (int j = i + 1; j < size; j++) { if (comparator(arr[index], arr[j])) { index = j; } } std::swap(arr[index], arr[i]); } } void merge(double *arr, int left, int split, int right, Comparator &comparator) { int temp_size = right - left; double *t = new double[temp_size]; int pos1 = left, pos2 = split, pos3 = 0; while ((pos1 < split) && (pos2 < right)) { if (comparator(arr[pos1], arr[pos2])) { t[pos3++] = arr[pos1++]; } else { t[pos3++] = arr[pos2++]; } } while (pos1 < split) { t[pos3++] = arr[pos1++]; } while (pos2 < right) { t[pos3++] = arr[pos2++]; } for (pos3 = 0; pos3 < temp_size; pos3++) { arr[left + pos3] = t[pos3]; } delete[] t; } void merge_sort(double *arr, int l, int r, Comparator &comparator) { if (r - l <= 1) { return; } int split = (l + r) / 2; merge_sort(arr, l, split, comparator); merge_sort(arr, split, r, comparator); merge(arr, l, split, r, comparator); }; void merge_sort(double *arr, int size, bool is_asc) { Comparator comparator = is_asc ? lower_than : larger_than; merge_sort(arr, 0, size, comparator); }
eecf8db01720725d7b3c8965f9e35b67b7baf302
481c120311b7e53d6d385a7218f4fa0918b93c52
/src/ReconstructionExample.cc
39a380f0815d52ac0a0e289338b88291d182a092
[]
no_license
faltovaj/FCC_calo_analysis_cpp
dcae0d7962a642d45fde86d1b690e971d7d04027
d781da859b8f44d2c225f07ac8d9725a736ee510
refs/heads/master
2021-06-24T05:47:16.996960
2020-11-23T11:49:55
2020-11-23T11:49:55
54,208,766
0
7
null
2020-11-23T11:49:56
2016-03-18T14:47:25
Python
UTF-8
C++
false
false
4,185
cc
ReconstructionExample.cc
#include "ReconstructionExample.h" // podio specific includes #include "podio/EventStore.h" #include "podio/ROOTReader.h" #include "datamodel/CaloClusterCollection.h" #include "datamodel/PositionedCaloHitCollection.h" #include "TVector3.h" // STL #include <vector> #include <iostream> #include <cmath> ReconstructionExample::ReconstructionExample(const std::string& aCluserCollName, const std::string& aPosHitCollName, int aEventToAnalyse, double aEnergy, double aEtaMax, int aNoEta, int aNoPhi, double aDEta, double aDPhi): m_clusterCollName(aCluserCollName), m_posHitCollName(aPosHitCollName), m_eventToAnalyse(aEventToAnalyse), m_energy(aEnergy), m_etaMax(aEtaMax), m_noEta(aNoEta), m_noPhi(aNoPhi), m_dEta(aDEta), m_dPhi(aDPhi) { Initialize_histos(); } ReconstructionExample::~ReconstructionExample(){} void ReconstructionExample::Initialize_histos() { hAllCellEnergy = new TH2F("all cells","calo towers (50 GeV e^{-})",m_noEta,-m_etaMax,m_etaMax,m_noPhi,-M_PI-0.5*m_dPhi,M_PI+0.5*m_dPhi); hClusterEnergy = new TH2F("cluster","cluster seeds (50 GeV e^{-})",m_noEta,-m_etaMax,m_etaMax,m_noPhi,-M_PI-0.5*m_dPhi,M_PI+0.5*m_dPhi); hClusterCellEnergy = new TH2F("cells associated to clusters","cells in reconstructed cluster (50 GeV e^{-})",m_noEta,-m_etaMax,m_etaMax,m_noPhi,-M_PI-0.5*m_dPhi,M_PI+0.5*m_dPhi); m_histograms.push_back(hAllCellEnergy); m_histograms.push_back(hClusterCellEnergy); m_histograms.push_back(hClusterEnergy); } void ReconstructionExample::processEvent(podio::EventStore& aStore, int aEventId, bool aVerbose) { if (aEventId != m_eventToAnalyse) { return; } // Get the collections const fcc::CaloClusterCollection* clusters(nullptr); const fcc::PositionedCaloHitCollection* cells(nullptr); bool testClusters = aStore.get(m_clusterCollName, clusters); bool testCells = aStore.get(m_posHitCollName, cells); // cells associated to the reconstructed cluster std::vector<uint64_t> cellIds; // Get clusters reconstructed in an event if (testClusters) { if (aVerbose) { std::cout << "Number of clusters: " << clusters->size() << std::endl; } //Loop through the collection for (const auto iclu = clusters->begin(); iclu != clusters->end(); ++iclu) { if (aVerbose) { std::cout << "Cluster reconstructed at " << iclu->core().position.x << " , " << iclu->core().position.y << " , " << iclu->core().position.z << " with energy " << iclu->core().energy << " GeV" << std::endl; } TVector3 pos (iclu->core().position.x, iclu->core().position.y, iclu->core().position.z); float phi = pos.Phi(); float eta = pos.Eta(); hClusterEnergy->Fill(eta, phi, iclu->core().energy); // get cells hat are associated to that cluster int cellsNo = iclu->hits_size(); for (int icell = 0; icell < cellsNo; icell++) { cellIds.push_back(iclu->hits(icell).core().cellId); } } } else { std::cout << "No Cluster Collection in the event." << std::endl; } // Get cells if (testCells) { if (aVerbose) { std::cout << "Number of cells: " << cells->size() << std::endl; } //Loop through the collection for (const auto icell = cells->begin(); icell != cells->end(); ++icell) { if (aVerbose) { std::cout << "Cell id: " << icell->core().cellId << " at " << icell->position().x << " , " << icell->position().y << " , " << icell->position().z << " with energy " << icell->core().energy << " GeV" << std::endl; } TVector3 position(icell->position().x, icell->position().y, icell->position().z); float phiCell = position.Phi(); float etaCell = position.Eta(); hAllCellEnergy->Fill(etaCell, phiCell, icell->core().energy); if(std::find(cellIds.begin(), cellIds.end(), icell->core().cellId) != cellIds.end()) { hClusterCellEnergy->Fill(etaCell, phiCell, icell->core().energy); } } } else { std::cout << "No Cell Collection in the event." << std::endl; } } void ReconstructionExample::finishLoop(int aNumEvents, bool aVerbose) {}
d91b07fb79f55d3615afe48f50865b0b018b6c2d
916517d4d547694c687733d25b387313ce188f96
/mcbPlatformSupport/crypto/mcbSHA.cpp
2be13cd9299f727a91b5ce8b72fe10957dd84ab2
[ "MIT" ]
permissive
radif/mcbPlatformSupport
a8bab97f5b0941751670330359c9219e47075ebf
8dad83c848dbb6aa51b67cf5986a555b30bcbe98
refs/heads/master
2020-12-20T00:38:06.710983
2019-05-29T18:58:02
2019-05-29T18:58:02
11,956,372
1
3
null
null
null
null
UTF-8
C++
false
false
12,153
cpp
mcbSHA.cpp
// // mcbSHA.cpp // crypto // // Created by Radif Sharafullin on 1/20/14. // Copyright (c) 2014 Radif Sharafullin. All rights reserved. // #include "mcbSHA.h" #include <vector> #if __BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__ #error this code has only been tested on little endian machines #endif #define shr64(x,n) ((x & 0xFFFFFFFFFFFFFFFFULL) >> n) #define rotr64(x,n) (shr64(x,n) | (x << (64 - n))) #define shr32(x,n) ((x & 0xFFFFFFFF) >> n) #define rotr32(x,n) (shr32(x,n) | (x << (32 - n))) namespace mcb{namespace PlatformSupport{namespace crypto{ typedef unsigned int uint; typedef unsigned long long ullint; static inline std::string fromDecimal(ullint n, const ullint b, const uint length){ static const std::string chars("0123456789abcdefghijklmnopqrstuvwxyz"); std::string result; for (int pass(0); pass<length; ++pass){ result=chars.at(n%b)+result; n/=b; } return result; } namespace sha512helpers{ static const ullint K[80] = { 0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL, 0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL, 0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL, 0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL, 0xd807aa98a3030242ULL, 0x12835b0145706fbeULL, 0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL, 0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL, 0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL, 0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL, 0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL, 0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL, 0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL, 0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL, 0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL, 0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL, 0x06ca6351e003826fULL, 0x142929670a0e6e70ULL, 0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL, 0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL, 0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL, 0x81c2c92e47edaee6ULL, 0x92722c851482353bULL, 0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL, 0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL, 0xd192e819d6ef5218ULL, 0xd69906245565a910ULL, 0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL, 0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL, 0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL, 0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL, 0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL, 0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL, 0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL, 0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL, 0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL, 0xca273eceea26619cULL, 0xd186b8c721c0c207ULL, 0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL, 0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL, 0x113f9804bef90daeULL, 0x1b710b35131c471bULL, 0x28db77f523047d84ULL, 0x32caab7b40c72493ULL, 0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL, 0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL, 0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL }; static void makeblock(std::vector<ullint>& ret, const std::string & p_msg){ ullint cur(0); int ind(0); for(uint i(0); i<p_msg.size(); ++i){ cur = (cur<<8) | (unsigned char)p_msg[i]; if(i%8==7){ ret.at(ind++)=cur; cur=0; } } } struct Block{ std::vector<ullint> msg; Block():msg(16, 0){} Block(const std::string & p_msg):msg(16, 0){ makeblock(msg, p_msg); } }; static void split(std::vector<Block>& blks, const std::string& msg){ for(uint i(0); i<msg.size(); i+=128) makeblock(blks[i/128].msg, msg.substr(i, 128)); } static std::string mynum(ullint x){ std::string ret; for(uint i(0); i<8; ++i) ret+=char(0); for(uint i(8); i>=1; --i) //big endian machine assumed ??? ret += ((char*)(&x))[i-1]; return ret; } static inline ullint ch(ullint x, ullint y, ullint z){ return (x&y) ^ (~x&z); } static inline ullint maj(ullint x, ullint y, ullint z){ return (x&y) ^ (y&z) ^ (z&x); } static inline ullint fn0(ullint x){ return rotr64(x, 28) ^ rotr64(x, 34) ^ rotr64(x, 39); } static inline ullint fn1(ullint x){ return rotr64(x, 14) ^ rotr64(x, 18) ^ rotr64(x, 41); } static inline ullint sigma0(ullint x){ return rotr64(x, 1) ^ rotr64(x, 8) ^ shr64(x, 7); } static inline ullint sigma1(ullint x){ return rotr64(x, 19) ^ rotr64(x, 61) ^ shr64(x, 6); } } std::string sha512(const std::string & str){ using namespace sha512helpers; std::string msg_arr(str); msg_arr += (char)(1<<7); uint cur_len((uint)str.size()*8 + 8); uint reqd_len((uint)((str.size()*8)/1024+1) *1024); uint pad_len(reqd_len - cur_len - 128); std::string pad(pad_len/8, char(0)); msg_arr+=pad; std::string len_str(mynum(str.size()*8)); msg_arr+=len_str; uint num_blk((uint)msg_arr.size()*8/1024); std::vector<Block> M(num_blk, Block()); split(M, msg_arr); ullint H[]={ 0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL, 0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL, 0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL, 0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL }; for(uint i(0); i<num_blk; ++i){ std::vector<ullint> W(80, 0); for(uint t(0); t<16; ++t) W[t] = M[i].msg[t]; for(uint t(16); t<80; ++t) W[t] = sigma1(W[t-2]) + W[t-7] + sigma0(W[t-15]) + W[t-16]; ullint work[8]; for(uint i(0); i<8; ++i) work[i] = H[i]; for(uint t(0); t<80; ++t){ ullint t1, t2; t1 = work[7] + fn1(work[4]) + ch(work[4], work[5], work[6]) + K[t] + W[t]; t2 = fn0(work[0]) + maj(work[0], work[1], work[2]); work[7] = work[6]; work[6] = work[5]; work[5] = work[4]; work[4] = work[3] + t1; work[3] = work[2]; work[2] = work[1]; work[1] = work[0]; work[0] = t1 + t2; } for(uint i(0); i<8; ++i) H[i] = work[i] + H[i]; } std::string retVal; for(uint i(0); i<8; ++i) retVal+=fromDecimal(H[i], 16, 16); return retVal; } namespace sha256helpers{ static const uint K[]= { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2}; static void makeblock(std::vector<uint>& ret, const std::string & p_msg){ uint cur(0); int ind(0); for(uint i(0); i<p_msg.size(); ++i){ cur = (cur<<8) | (unsigned char)p_msg[i]; if(i%4==3){ ret.at(ind++)=cur; cur=0; } } } struct Block{ std::vector<uint> msg; Block():msg(16, 0) {} Block(std::string p_msg):msg(16, 0){ makeblock(msg, p_msg); } }; static void split(std::vector<Block>& blks, const std::string& msg){ for(uint i(0); i<msg.size(); i+=64){ try{ makeblock(blks[i/64].msg, msg.substr(i, 64)); } catch(...){ } } } static std::string mynum(uint x){ std::string ret; for(uint i(0); i<4; ++i) ret+=char(0); for(uint i(4); i>=1; --i) //big endian machine assumed ??? ret += ((char*)(&x))[i-1]; return ret; } static inline uint ch(uint x, uint y, uint z){ return (x&y) ^ (~x&z); } static inline uint maj(uint x, uint y, uint z){ return (x&y) ^ (y&z) ^ (z&x); } static inline uint fn0(uint x){ return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); } static inline uint fn1(uint x){ return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); } static inline uint sigma0(uint x){ return rotr32(x, 7) ^ rotr32(x, 18) ^ shr32(x, 3); } static inline uint sigma1(uint x){ return rotr32(x, 17) ^ rotr32(x, 19) ^ shr32(x, 10); } } std::string sha256(const std::string & str){ using namespace sha256helpers; std::string msg_arr(str); msg_arr+=(char)(1<<7); uint cur_len((uint)str.size()*8 + 8); uint reqd_len((uint)((str.size()*8)/512+1) *512); uint pad_len((uint)reqd_len - cur_len - 64); std::string pad(pad_len/8, char(0)); msg_arr += pad; std::string len_str(mynum((uint)str.size()*8)); msg_arr = msg_arr + len_str; uint num_blk((uint)msg_arr.size()*8/512); std::vector<Block> M(num_blk, Block()); split(M, msg_arr); uint H[]={0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; for(uint i(0); i<num_blk; ++i){ std::vector<uint> W(64, 0); for(uint t(0); t<16; ++t) W[t] = M[i].msg[t]; for(uint t(16); t<64; ++t) W[t] = sigma1(W[t-2]) + W[t-7] + sigma0(W[t-15]) + W[t-16]; uint work[8]; for(uint i(0); i<8; ++i) work[i] = H[i]; for(uint t(0); t<64; ++t){ uint t1, t2; t1 = work[7] + fn1(work[4]) + ch(work[4], work[5], work[6]) + K[t] + W[t]; t2 = fn0(work[0]) + maj(work[0], work[1], work[2]); work[7] = work[6]; work[6] = work[5]; work[5] = work[4]; work[4] = work[3] + t1; work[3] = work[2]; work[2] = work[1]; work[1] = work[0]; work[0] = t1 + t2; } for(uint i(0); i<8; ++i) H[i] = work[i] + H[i]; } std::string retVal; for(uint i(0); i<8; ++i) retVal+=fromDecimal(H[i], 16, 8); return retVal; } }}}
4fc632e7e037f5b075a981b47234a32eeab30a75
a9481c2069749fd88f0772289e53804a212f617c
/QuadGS/Common/Messages/GS_FC_Control/Msg_NewSetpoint.h
71ee961a2b40750e057291226e1af1be94e25638
[]
no_license
mlundh/QuadSys
a7e0527943505262733382093024e43aa553372e
630a7ba17434d27cbc1b2e460035e0006651d1a0
refs/heads/master
2023-01-23T15:42:48.159595
2023-01-18T13:50:46
2023-01-18T13:50:46
164,338,347
0
0
null
null
null
null
UTF-8
C++
false
false
1,050
h
Msg_NewSetpoint.h
#ifndef QUADGS_MESSAGE_MSG_NEWSETPOINT_H_ #define QUADGS_MESSAGE_MSG_NEWSETPOINT_H_ #include "QGS_ModuleMsg.h" namespace QuadGS { class Msg_NewSetpoint: public QGS_ModuleMsg<Msg_NewSetpoint> { public: Msg_NewSetpoint(QGS_ModuleMsgBase& msg); Msg_NewSetpoint(const msgAddr_t destination, state_data_t setpoint, uint8_t priority, uint8_t validFor); Msg_NewSetpoint(const Msg_NewSetpoint& msg); virtual ~Msg_NewSetpoint(); virtual void dispatch(QGS_MessageHandlerBase* handler) { this->dynamicDispatch(handler,this); } typedef std::unique_ptr<Msg_NewSetpoint> ptr; virtual BinaryOStream& stream(BinaryOStream& os) const; virtual BinaryIStream& stream(BinaryIStream& is); state_data_t getSetpoint() const; void setSetpoint(state_data_t setpoint); uint8_t getPriority() const; void setPriority(uint8_t priority); uint8_t getValidfor() const; void setValidfor(uint8_t validFor); private: state_data_t mSetpoint; uint8_t mPriority; uint8_t mValidfor; }; } #endif /* QUADGS_MESSAGE_MSG_NEWSETPOINT_H_ */
428ec8c5f43a0da60d7a0a79f7ca65a501e13560
c44fd1b6e22663b4468bc3e9275a87ad6a98b0b9
/wxWidgets_TestApp/wxPolarPlot.cpp
fb8b6c6065bdd81e67d8276818d5480dbd3fa301
[]
no_license
ThomasJowett/wxWidgets_TestApp
b64b706c4b6dfefb16457357a7074aaa9af42f57
180dc004c0e313cbfea5ed69c748060ab2b233c3
refs/heads/master
2021-08-06T14:34:57.516996
2021-07-26T08:33:04
2021-07-26T08:33:04
205,603,615
0
0
null
null
null
null
MacCentralEurope
C++
false
false
14,532
cpp
wxPolarPlot.cpp
#include "stdafx.h" ///////////////////////////////////////////////////////////////////////////// // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" // for all others, include the necessary headers (this file is usually all you // need because it includes almost all "standard" wxWidgets headers) #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "Plot.h" #include "PolarPlotData.h" #include "wxPolarPlot.h" #include "wx/dcbuffer.h" // ---------------------------------------------------------------------------- wxPolarPlot::wxPolarPlot(wxWindow* parent, PolarPlotData* graphData, wxPlotStyle* plotStyle, bool useTitle, bool useLegend, bool isLinear, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxString& name) : wxPanel(parent, id, pos, size, style, name), m_GraphData(graphData), m_PlotStyle(plotStyle), m_useTitle(useTitle), m_useLegend(useLegend), m_IsLinear(isLinear) { //Bind the events Bind(wxEVT_PAINT, &wxPolarPlot::OnPaint, this); Bind(wxEVT_SIZE, &wxPolarPlot::OnSize, this); Bind(wxEVT_ERASE_BACKGROUND, &wxPolarPlot::OnEraseBackground, this); } // ---------------------------------------------------------------------------- wxPolarPlot::~wxPolarPlot(void) { } // ---------------------------------------------------------------------------- void wxPolarPlot::OnPaint(wxPaintEvent& WXUNUSED(event)) { wxBufferedPaintDC dc(this); wxGCDC gdc(dc); dc.SetBackgroundMode(wxTRANSPARENT); wxSize sz = GetClientSize(); dc.Clear(); int margin = 10; int width = sz.x - margin - margin; int height = sz.y - margin - margin; // ----------------------------------------------------------------- // Step 1. Drawing the grid area // Step 2. Drawing the Plots if (m_IsLinear) { int linearGridBorderX = 60; int linearGridBorderY = 20; wxRect linearGridRect = wxRect(linearGridBorderX, linearGridBorderY, width - linearGridBorderX, height - linearGridBorderY - 20); DrawLinearGridWithCaptions(&gdc, linearGridRect); DrawLinearPlots(&gdc, linearGridRect); } else { int polarGridBorder = 20; wxRect polarGridRect = wxRect(polarGridBorder, polarGridBorder, width - polarGridBorder, height - polarGridBorder); DrawPolarGridLines(&gdc, polarGridRect); DrawPolarPlots(&gdc, polarGridRect); DrawPolarGridCaptions(&gdc, polarGridRect); } // Step 3. Drawing the title // if (m_useTitle) { wxFont font = wxFont(14, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD, false, wxT("Arial")); dc.SetTextForeground(m_PlotStyle->TitleColour); dc.SetFont(font); dc.DrawText(m_GraphData->Title(), margin * 3, margin * 2); } // ----------------------------------------------------------------- } // ---------------------------------------------------------------------------- void wxPolarPlot::DrawLinearGridWithCaptions(wxDC* dc, wxRect gridArea) { wxBrush* gridBrush = wxTheBrushList->FindOrCreateBrush(m_PlotStyle->BackgroundColour, wxBRUSHSTYLE_SOLID); dc->SetBrush(*gridBrush); wxPen* gridPen = wxThePenList->FindOrCreatePen(m_PlotStyle->GridLineColour, m_PlotStyle->GridLineWidth, m_PlotStyle->GridLineStyle); dc->SetPen(*gridPen); int dx = gridArea.width / (m_VerticalGridLines); int dy = gridArea.height / (m_HorizontalGridLines); dc->DrawRectangle(gridArea); wxFont font(10, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, wxT("Arial")); dc->SetTextForeground(m_PlotStyle->CaptionsColour); dc->SetFont(font); int xFinal = 0; int yFinal = 0; wxString capTxt; capTxt = wxString::Format(wxT("%d"), -180); dc->DrawText(capTxt, gridArea.GetLeft() - 8, gridArea.GetBottom()); for (int i = 1; i < m_VerticalGridLines; i++) { // Draw a vertical line int xStart = gridArea.GetLeft() + i * dx; int yStart = gridArea.GetTop(); int xEnd = xStart; int yEnd = gridArea.GetBottom(); xFinal = xStart; yFinal = yEnd; dc->DrawLine(xStart, yStart, xEnd, yEnd); capTxt = wxString::Format(wxT("%2.0f"), -180 + (360.0 / (double)(m_VerticalGridLines)) * ((double)i)); dc->DrawText(capTxt, xStart - 8, yEnd); } capTxt = wxString::Format(wxT("%d"), 180); dc->DrawText(capTxt, gridArea.GetRight() - 8, yFinal); dy = gridArea.height / (m_HorizontalGridLines); capTxt = wxString::Format(wxT("%2.1f"), 0.0); dc->DrawText(capTxt, gridArea.GetLeft() - 24, gridArea.GetBottom() - 8); for (int i = 1; i < m_HorizontalGridLines; i++) { // Draw a horizontal line int xStart = gridArea.GetLeft(); int yStart = gridArea.GetBottom() - i * dy; int xEnd = gridArea.GetRight(); int yEnd = yStart; xFinal = xStart; dc->DrawLine(xStart, yStart, xEnd, yEnd); capTxt = wxString::Format(wxT("%2.1f"), (double)i / 10.0); dc->DrawText(capTxt, gridArea.GetLeft() - 24, yStart - 8); } capTxt = wxString::Format(wxT("%2.1f"), 1.0); dc->DrawText(capTxt, gridArea.GetLeft() - 24, gridArea.GetTop() - 8); dc->DrawText(m_GraphData->XAxisLabel(), gridArea.width / 2 + 40, gridArea.GetBottom() + 15); dc->DrawRotatedText(m_GraphData->YAxisLabel(), gridArea.GetLeft() - 44, gridArea.height, 90); } // ---------------------------------------------------------------------------- void wxPolarPlot::DrawPolarGridLines(wxDC* dc, wxRect gridArea) { wxBrush* gridBrush = wxTheBrushList->FindOrCreateBrush(m_PlotStyle->BackgroundColour, wxBRUSHSTYLE_SOLID); dc->SetBrush(*gridBrush); wxPen* gridPen = wxThePenList->FindOrCreatePen(m_PlotStyle->GridLineColour, m_PlotStyle->GridLineWidth, m_PlotStyle->GridLineStyle); dc->SetPen(*gridPen); int centerPointX = gridArea.GetLeft() + gridArea.width / 2.0; int centerPointY = gridArea.GetTop() + gridArea.height / 2.0; int dx = min(gridArea.height, gridArea.width) / 2.0 / (m_HorizontalGridLines); // Draw concentric circles int radius = 0; for (int i = 0; i < (m_HorizontalGridLines); i++) { radius = (double)min(gridArea.height, gridArea.width) / 2.0 - i * dx; dc->DrawCircle(centerPointX, centerPointY, radius); } int xStart = centerPointX; int yStart = centerPointY; // Draw radius lines radius = min(gridArea.height, gridArea.width) / 2.0; for (int i = 0; i <= (m_VerticalGridLines); i++) { double angle = 0.0 + i * M_PI / (m_VerticalGridLines / 2.0f); int xEnd = centerPointX + radius * cos(angle); int yEnd = centerPointY - radius * sin(angle); dc->DrawLine(xStart, yStart, xEnd, yEnd); } } // ---------------------------------------------------------------------------- void wxPolarPlot::DrawLinearPlots(wxDC* dc, wxRect gridArea) { wxPen* gridPen = wxThePenList->FindOrCreatePen(m_PlotStyle->GridLineColour, m_PlotStyle->GridLineWidth, m_PlotStyle->GridLineStyle); dc->SetPen(*gridPen); double xMin = -180.0; double xMax = 180.0; double yMin = 0.0; double yMax = 1.0; int dx = gridArea.width / m_VerticalGridLines; int dy = gridArea.height / m_HorizontalGridLines; double xScale = (xMax - xMin) / gridArea.width; double yScale = (yMax - yMin) / gridArea.height; int plotsInTotal = m_GraphData->NumberOfPlots(); for (auto plot : m_GraphData->PlotData()) { if (!plot.IsVisible) continue; dc->SetBrush(*plot.Brush); int xPrevious = gridArea.GetLeft(); int yPrevious = gridArea.GetBottom(); int xEnd = xPrevious; int yEnd = yPrevious; wxPen* plotPen = wxThePenList->FindOrCreatePen(plot.Brush->GetColour(), m_PlotStyle->PlotLineWidth, m_PlotStyle->PlotLineStyle); dc->SetPen(*plotPen); wxPoint point; wxPoint* points = new wxPoint[plot.PlotValues.size() + 2]; size_t i = 1; for (std::pair<double, double> plotValue : plot.PlotValues) { double currentX = plotValue.first; double currentY = plotValue.second; point.x = gridArea.GetLeft() + (currentX + xMax) / xScale; point.y = gridArea.GetTop() + (yMax - currentY) / yScale; points[i] = point; dc->DrawCircle(point, m_PlotStyle->PlotLineWidth * 1.5f); i++; } double lastToEnd = xMax - plot.PlotValues.back().first; double minToFirst = plot.PlotValues.front().first - xMin; double alpha = lastToEnd / (minToFirst + lastToEnd); double endYValue = (plot.PlotValues.front().second * alpha) + (plot.PlotValues.back().second * (1 - alpha)); points[0] = wxPoint(gridArea.GetLeft(), gridArea.GetTop() + (yMax - endYValue) / yScale); points[i] = wxPoint(gridArea.GetLeft() + (xMax * 2) / xScale, gridArea.GetTop() + (yMax - endYValue) / yScale); dc->DrawLines(plot.PlotValues.size() + 2, points); //dc->DrawSpline(plot.PlotValues.size() + 1, points); if (plot.PlotValues.back().first > 179.0) dc->DrawCircle(points[0], m_PlotStyle->PlotLineWidth * 1.5f); if (plot.PlotValues.front().first < -179) dc->DrawCircle(points[i], m_PlotStyle->PlotLineWidth * 1.5f); } } // ---------------------------------------------------------------------------- void wxPolarPlot::DrawPolarPlots(wxDC* dc, wxRect gridArea) { wxPen* gridPen = wxThePenList->FindOrCreatePen(m_PlotStyle->GridLineColour, m_PlotStyle->GridLineWidth, m_PlotStyle->GridLineStyle); dc->SetPen(*gridPen); double xMin = -180.0; double xMax = 180.0; double yMin = 0.0; double yMax = 1.0; int dx = gridArea.width / (m_VerticalGridLines); int dy = gridArea.height / (m_HorizontalGridLines); double xScale = (xMax - xMin) / gridArea.width; double yScale = (yMax - yMin) / gridArea.height; int plotsInTotal = m_GraphData->NumberOfPlots(); for (auto plot : m_GraphData->PlotData()) { if (!plot.IsVisible) continue; int centerPointX = gridArea.GetLeft() + gridArea.width / 2.0; int centerPointY = gridArea.GetTop() + gridArea.height / 2.0; dc->SetBrush(*plot.Brush); wxPen* plotPen = wxThePenList->FindOrCreatePen(plot.Brush->GetColour(), m_PlotStyle->PlotLineWidth, m_PlotStyle->PlotLineStyle); dc->SetPen(*plotPen); wxPoint point; wxPoint* points = new wxPoint[plot.PlotValues.size() + 1]; int i = 0; double radius; for (std::pair<double, double> plotValue : plot.PlotValues) { double azimuth = wxDegToRad(plotValue.first); double ro = plotValue.second; double angle = (0.0 + azimuth) + (M_PI / 2); radius = min(gridArea.height, gridArea.width) / 2.0 * ro; point.x = centerPointX + radius * cos(angle); point.y = centerPointY - radius * sin(angle); dc->DrawCircle(point, m_PlotStyle->PlotLineWidth * 1.5f); points[i] = point; dc->DrawPoint(point); i++; } //the last point should be equal to the first point to complete the loop points[i] = points[0]; //dc->DrawSpline(plotValues.size(), points); dc->DrawLines(plot.PlotValues.size() + 1, points); } } // ---------------------------------------------------------------------------- void wxPolarPlot::DrawPolarGridCaptions(wxDC* dc, wxRect gridArea) { wxFont font(8, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, wxT("Arial")); dc->SetTextForeground(m_PlotStyle->CaptionsColour); dc->SetFont(font); wxString capTxt; int dx = min(gridArea.height, gridArea.width) / 2.0 / (m_HorizontalGridLines); int centerPointX = gridArea.GetLeft() + gridArea.width / 2.0; int centerPointY = gridArea.GetTop() + gridArea.height / 2.0; capTxt = wxString::Format(wxT("%d"), 0); int radius = min(gridArea.height, gridArea.width) / 2.0; dc->DrawText(capTxt, centerPointX - 5, centerPointY - (radius + 15)); for (int i = 1; i < m_VerticalGridLines; i++) { double angle = 0.0 + i * (M_PI * 2.0) / (m_VerticalGridLines)+(M_PI / 2); int xEnd = centerPointX + radius * cos(angle); int yEnd = centerPointY - radius * sin(angle); double degree = i * 360.0 / (m_VerticalGridLines); if (degree > 180) degree -= 360; capTxt = wxString::Format(wxT("%2.0f"), degree); if (degree <= 90.0 && degree >= 0.0) dc->DrawText(capTxt, xEnd - 20, yEnd - 10); else if (degree <= 180.0 && degree >= 0.0) dc->DrawText(capTxt, xEnd - 20, yEnd + 5); else if (degree <= -90) dc->DrawText(capTxt, xEnd + 4, yEnd); else dc->DrawText(capTxt, xEnd + 5, yEnd - 10); } radius = 0; for (int i = 1; i < m_HorizontalGridLines; i++) { radius = min(gridArea.height, gridArea.width) / 2.0 - i * dx; double angle = wxDegToRad(32); int xEnd = centerPointX + radius * cos(angle); int yEnd = centerPointY - radius * sin(angle); capTxt = wxString::Format(wxT("%2.1f"), 1.0 - ((double)i) / 10.0); dc->DrawText(capTxt, xEnd - 3, yEnd - 15); } } //PLOT LEGEND ------------------------------------------------------------------------------------------------------------------------ wxPlotLegend::wxPlotLegend(wxWindow* parent, PolarPlotData* graphData, wxPlotStyle* plotStyle, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxString& name) : wxScrolledWindow(parent, id), m_GraphData(graphData), m_PlotStyle(plotStyle) { wxSize parentSize = parent->GetSize(); SetScrollbars(1, 1, 0, m_GraphData->NumberOfPlots() * 16, 0, 0); Bind(wxEVT_PAINT, &wxPlotLegend::OnPaint, this); Bind(wxEVT_SIZE, &wxPlotLegend::OnSize, this); } wxPlotLegend::~wxPlotLegend(void) { } void wxPlotLegend::OnPaint(wxPaintEvent& WXUNUSED(event)) { if (m_GraphData->NumberOfPlots() == 0) return; wxBufferedPaintDC dc(this); PrepareDC(dc); // DoPrepareDC(dc); - This sets the device contextís deviceorigin // Alternatively, you can override the OnDraw virtual function; // wxWindow creates a paint device context and calls DoPrepareDC for you before calling your OnDraw function wxGCDC gdc(dc); dc.Clear(); wxSize sz = GetClientSize(); auto width = sz.x; auto height = sz.y; const int ZoneNumberThreshold = 10; const int legendRectWidth = 20; const int legendRectShift = 10; const int legentYShift = 0; const int legentY2ndShift = 0; int legendRectHalfWidth = legendRectWidth / 2; wxFont font(9, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, wxT("Arial")); gdc.SetFont(font); int graphVisibleCount = m_GraphData->NumberOfPlots(); int xLegend = 20; int yLegend = 10; int delta = 16; int graphCount = 1; for (Plot plot : m_GraphData->PlotData()) { gdc.SetBrush(*plot.Brush); wxString nameTxt = wxString::Format(wxT("%s"), plot.Name); wxPen* plotPen = wxThePenList->FindOrCreatePen(plot.Brush->GetColour(), m_PlotStyle->PlotLineWidth, m_PlotStyle->PlotLineStyle); gdc.SetPen(*plotPen); gdc.DrawText(nameTxt, xLegend + legendRectWidth + legendRectShift, yLegend - 6); gdc.DrawLine(xLegend - legendRectHalfWidth, yLegend, xLegend + legendRectHalfWidth, yLegend); gdc.DrawCircle(xLegend, yLegend, m_PlotStyle->PlotLineWidth * 1.5f); yLegend += delta; graphCount++; } }
583145733a7af8be47aa61a78c3ee22e209fb292
92b203f70d24d27e1113626d60b59f0f54e1e535
/08_RollOneDieWithSlowdown/08_RollOneDieWithSlowdown.ino
5693a4657d7e4f4c1383a9e9f02fece0f2809a6a
[]
no_license
hwiguna/HariFun_173_Four_Digit_Dice
3cdcec0322cdf8f5d4f47f3ddc3d9da89398367a
7a6e20987d47db57da53277360e94283a73860b3
refs/heads/master
2020-04-23T10:10:16.641350
2019-03-06T14:28:23
2019-03-06T14:28:23
171,094,592
0
0
null
null
null
null
UTF-8
C++
false
false
3,435
ino
08_RollOneDieWithSlowdown.ino
// Roll one dice immediately, don't worry about the roll effect yet // Hari Wiguna, 2019 #include <TimerOne.h> //== Input Pins == byte rollButton = A5; byte upButton = A4; byte downButton = A3; //== Four-digit 7-Segment Display == byte digit0 = 2; byte digit1 = 3; byte digit2 = 4; byte digit3 = 5; byte segmentA = 12; byte segmentB = 11; byte segmentC = 10; byte segmentD = 9; byte segmentE = 8; byte segmentF = 7; byte segmentG = 6; byte digitMap[] = {digit0, digit1, digit2, digit3}; byte segmentMap[] = {segmentA, segmentB, segmentC, segmentD, segmentE, segmentF, segmentG}; byte charMap[] = { B11111100, // 0 B01100000, // 1 B11011010, // 2 B11110010, // 3 B01100110, // 4 B10110110, // 5 B10111110, // 6 B11100000, // 7 B11111110, // 8 B11110110, // 9 }; volatile unsigned long curValue = 0; volatile byte curDigitIndex = 0; //-- Roll slowdown effect variables -- unsigned long startingSpeed = 30; unsigned long startingDeceleration = 1; unsigned long actionDelay = 0; unsigned long decelerationRate = 0; void SetupInputs() { pinMode(rollButton, INPUT_PULLUP); pinMode(upButton, INPUT_PULLUP); pinMode(downButton, INPUT_PULLUP); } void SetupOutputs() { //== Setup 7-segment display == pinMode(digit0, OUTPUT); digitalWrite(digit0, LOW); pinMode(digit1, OUTPUT); digitalWrite(digit1, LOW); pinMode(digit2, OUTPUT); digitalWrite(digit2, LOW); pinMode(digit3, OUTPUT); digitalWrite(digit3, LOW); pinMode(segmentA, OUTPUT); pinMode(segmentB, OUTPUT); pinMode(segmentC, OUTPUT); pinMode(segmentD, OUTPUT); pinMode(segmentE, OUTPUT); pinMode(segmentF, OUTPUT); pinMode(segmentG, OUTPUT); } void DrawDigit(byte value) { for (byte bitIndex = 0; bitIndex < 7; bitIndex++) { // Note that we only use bits 0-6, NOT 0-7 digitalWrite( segmentMap[bitIndex], !bitRead(charMap[value], 7 - bitIndex) ); } } void RefreshDigit() { // Note that curDigitIndex zero is rightmost on the display (least significant digit) digitalWrite(digitMap[curDigitIndex], LOW); // Turn off previous digit curDigitIndex++ ;// What's the next digit? if (curDigitIndex > 3) curDigitIndex = 0; // Cycle back to zero if we're about to go beyond the four digits of our display String curValueStr = "0000" + String(curValue); // Left pad with zeroes, to make sure we're at least 4 digits int digitValue = curValueStr.charAt( curValueStr.length()-1-curDigitIndex) - '0'; // What's the value of digit at position curDigitIndex? DrawDigit(digitValue); // Draw value at curDigitIndex digitalWrite(digitMap[curDigitIndex], HIGH); // Turn ON current digit } void setup() { SetupInputs(); SetupOutputs(); //-- Setup Timer -- Timer1.initialize(4000); // in microseconds Timer1.attachInterrupt(RefreshDigit); randomSeed(analogRead(0)); // Always start with a new seed at boot up } void loop() { if (digitalRead(rollButton) == LOW) { actionDelay = startingSpeed; decelerationRate = startingDeceleration; while (actionDelay < 200) { noInterrupts(); // Turn off refresh - in effect turn off all digits except for current digit delay(actionDelay); // wait for a second curValue = random(1, 7); // Pick a new number interrupts(); // Show that # delay(actionDelay); // wait for a second actionDelay += decelerationRate; // keep increasing actionDelay decelerationRate+=2; } } }
671cd8b055a891ad5a31d1d3ef186a724cc3ea63
81495b25f46059b55f2576a5bdcf51bbfe57f859
/result/BaseHealthParams.h
e746394f03da505f99b90495bda103fab77df75e
[ "CC-BY-4.0" ]
permissive
chaytanyasinha/gwadoc
fae2699271497383f318da34684e91d159432fc9
403a226aa7e8dc32fa2d00a016c679f9bdddb990
refs/heads/master
2022-12-02T11:37:29.569481
2020-07-31T12:11:00
2020-07-31T12:11:00
270,653,667
0
0
CC-BY-4.0
2020-06-08T12:07:10
2020-06-08T12:07:10
null
UTF-8
C++
false
false
295
h
BaseHealthParams.h
#pragma once namespace Nacos { class BaseHealthParams { private: int Max = 0; int Min = 0; double Factor = 0; public: int getMax() const; void setMax(int value); int getMin() const; void setMin(int value); double getFactor() const; void setFactor(double value); }; }
eef46bb1a6efc8a4e71d97ef7704cbf00eb6d55a
eefb836e9ec761c2b1f102b4007ed7ab6380c7a2
/code/delta/core/modules/shle/libSceGnmDriver/libSceGnmDebugReset.cpp
133367eadc1543d7f15573b96884a64c59b08663
[]
no_license
RyuDanuer/ps4delta
be6ee054ca3ae59159ecbcc59addb77c6f60c85f
e3ee468357fa0fbbd428d52034fc84e76b851c4c
refs/heads/master
2020-09-25T05:18:15.631545
2019-12-02T20:13:54
2019-12-02T20:13:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
239
cpp
libSceGnmDebugReset.cpp
// Copyright (C) 2019 Force67 // This file was generated on Sat Sep 7 22:01:25 2019 #include "../../ModuleLinker.h" int unk_RNPAItiMLIg() { UNIMPLEMENTED_FUNC; return 0; } int unk_xMMot887QXE() { UNIMPLEMENTED_FUNC; return 0; }
cb2ee1c5c8da17294d965ff98a8baaf34e5cdada
dfe6e2174e392adb298942e18b64cee3c7c9ce14
/BodyPartSelect/FGTakeAim.cpp
9c840465ec1a2465a56652a4ee0c8641581932f9
[]
no_license
ThanksJupiter/Portfolio
c5b9e2276aaf5594ef1112fa828626ea0d8fd539
75b0544049851ad660dfff18986b7fc2f6f84918
refs/heads/master
2020-04-17T15:05:33.771036
2019-01-21T22:27:17
2019-01-21T22:27:17
166,684,762
0
0
null
null
null
null
UTF-8
C++
false
false
1,439
cpp
FGTakeAim.cpp
#include "FGTakeAim.h" #include "Character/FGCharacter.h" #include "Components/FGCombatComponent.h" #include "Kismet/GameplayStatics.h" #include "Lua/FGLuaContext.h" #include "UI/Widgets/FGBodyPartSelectorWidget.h" #include "Engine/World.h" bool UFGTakeAim::Initialize(TWeakObjectPtr<UWorld> NewWorld, class AFGCharacter* NewCaster) { bool Success = Super::Initialize(NewWorld, NewCaster); if (BodyPartSelectWidgetClass) { BodyPartSelectWidget = CreateWidget<UFGBodyPartSelectorWidget>(World->GetWorld(), BodyPartSelectWidgetClass); if (BodyPartSelectWidget) { BodyPartSelectWidget->AddToViewport(); BodyPartSelectWidget->Hide(); } } bShouldShowMenu = true; return Success; } EFGAbilityUseErrorType UFGTakeAim::HandleAbilityUse(class AFGCharacter* Target) { if (bShouldShowMenu) { bShouldShowMenu = false; OnAbilityUsed.Broadcast(this); BodyPartSelectWidget->Display(); BodyPartSelectWidget->OnPartSelected.AddDynamic(this, &UFGTakeAim::OnBodyPartSelected); UGameplayStatics::SetGlobalTimeDilation(World->GetWorld(), GetLuaContext()->GetNumber("TimeDilation")); } return EFGAbilityUseErrorType::ET_None; } void UFGTakeAim::OnBodyPartSelected(EFGBodyPart SelectedPart) { bShouldShowMenu = true; Caster->CombatComp->CurrentBodyPartTarget = SelectedPart; UGameplayStatics::SetGlobalTimeDilation(World->GetWorld(), 1); BodyPartSelectWidget->Hide(); BodyPartSelectWidget->OnPartSelected.Clear(); }
7c3fafad598b542a1f863cc4d03816e988d78d57
7f38e0eae30328f15cc6c101254f679f348f32db
/new.cpp
281ffe79ee775e74f8e663c747dfa8cddd34cba6
[]
no_license
Adhithiyan03/BattleShip-Game-using-C-
374349eee3e4060883e838f383c7d993911deb71
fd81a014498cfc3e97f386e4e73f3237fca8d3ad
refs/heads/main
2023-06-06T13:00:22.933831
2021-07-03T15:55:37
2021-07-03T15:55:37
382,653,049
0
0
null
null
null
null
UTF-8
C++
false
false
4,709
cpp
new.cpp
#include<bits/stdc++.h> using namespace std; void instructions()//this is the instruction function. { cout<<"WELCOME TO THE BATTLE SHIP GAME."<<endl<<"THE INSTRUCTIONS ARE SIMPLE."<<endl; cout<<"1.This is a two player game."<<"the players can together decide the size of the five ships."<<endl; cout<<"2.Then player wil have select the pos of ship by giving the first coordinate of ship and telling the direction in whih the ship is placed."<<endl; cout<<"3.Now the scond player comes to attack by selcting coordinates of ship."; cout<<"For each correct guess player recieve 2 point and negative of 1 for wrong guess"<<endl; cout<<"after all ship are attacked the score of player 2 is exibhited."<<endl; cout<<"now the vice versa happens and the one with higher score is declared as the winner."<<endl; cout<<" NOTE:players should not use the same coordinates for attacking or choosing his area"<<endl; cout<<"HAVE FUN"<<endl; } class player//created a class for players { public: string d[10][30]; void start()//member functiom start() command to start the game { cout<<"Let's start the game"<<endl; } int pos()//decides the position {int sum=0; string bf[10][30]; for(int i=0;i<10;i++) { for(int j=0;j<30;j++) { bf[i][j]="-";//all the elements will be - until selected } } int ship[5];//array for the size of the 5 ships cout<<"\nplayer 1 should start\n"<<endl; cout<<"choose preferable size for 5 ships:"<<endl;//size here refers to how much space a ship occupies for(int i=0;i<5;i++) { cin>>ship[i]; if(ship[i]<10) {sum+=ship[i];} else { cout<<"size less than 10"<<endl; i=i-1; } } for(int i=0;i<5;i++)//assigning pos to the ship {int xco,yco; cout<<"enter the starting x coordinates(no more than 10!!):"<<endl; cin>>xco; cout<<"enter the starting y coordinates(no more than 30!!):"<<endl; cin>>yco; int ch; if(bf[xco][yco]=="-") { cout<<"enter the direction in which u would want keep ur ship no"<<i<<endl<<"1 for left"<<endl<<" 2 for right"<<endl<<" 3 for down"<<endl<<" 4 for up:"; cout<<endl; cin>>ch; int size=ship[i]; switch(ch) { case 1:{ for(int j=0;j<size;j++) { bf[xco][yco-j]="X";//if selected the element becomes X } break; } case 2:{ for(int j=0;j<size;j++) { bf[xco][yco+j]="X"; } break; }case 3:{ for(int j=0;j<size;j++) { bf[xco-j][yco]="X"; } break; }case 4:{ for(int j=0;j<size;j++) { bf[xco+j][yco]="X"; } break; } default: { cout<<"no such direction exists"<<endl; } }} else{ cout<<"retry again"<<endl; i=i-1; }} for(int i=0;i<10;i++) { for(int j=0;j<30;j++) { cout<<bf[i][j]; } cout<<endl; } system("PAUSE"); cout<<"\ncheck the input given\n"<<endl; cout<<"now press any key so that enemy can't see ur battleship.\n"<<endl ; system("CLS"); cout<<"player 2 can starting attacking his enemy battleships"<<endl; //give command to start attacking ships {int game=1; string a[10][30]; for(int i=0;i<10;i++) { for(int j=0;j<30;j++) {a[i][j]="-"; } } int score=0; while(game) { int no=0; int x,y; cout<<"select the x coordinate to attack(not more than 10!!):"<<endl; cin>>x; cout<<"select the y coordinates to attack(not more than 30!!):"<<endl; cin>>y; if(bf[x][y]=="X")//if attacked at correct pos element will change from X to O { cout<<"the enemy ship is hit!!"<<endl; a[x][y]="O"; score+=2; } else { cout<<"missed!!"<<endl; a[x][y]="+";//wrong place results in + score=score-1; } for(int i=0;i<10;i++) { for(int j=0;j<30;j++) { cout<<a[i][j]; } cout<<endl; } for(int i=0;i<10;i++) { for(int j=0;j<30;j++) {if(a[i][j]=="O") { no+=1; } } } if(no==sum) { game=0; return score; } } }} }; int main()//main function {int cont=1; while(cont==1) { instructions(); player p1,p2; p1.start(); string name1,name2; cout<<"enter player 1's name:"<<endl; cin>>name1; cout<<"enter player 2's name:"<<endl; cin>>name2; int a=p1.pos(); cout<<"the score of "<<name2<<" is:"<<a<<endl; system("PAUSE"); cout<<"after checking the scores hit any key to continue the game"<<endl; system("CLS"); int b=p2.pos(); cout<<"the score of "<<name1<<" is:"<<b<<endl; if(a>b) { cout<<"the winner is player two"<<name2<<endl; } else if(b>a) { cout<<"the winner is player one"<<endl; } else { cout<<"match drawn"<<endl; } int want; cout<<"do u wish to play again?"<<endl; cout<<"1.to restart"<<endl;//if u wish to play again cout<<"2.Enough for now"<<endl; cin>>want; if(want==1) { cont=1; } else { cont=0; } } }
126985c5dc425cffd2f69ffc9143304ff211fcb6
338f16b907cdca5d99f6fc4ee978b3dede217615
/src/master/contender/standalone.cpp
f5b839212e3f3e767cc3c236ec181b58aff9b721
[ "Apache-2.0", "GPL-2.0-or-later", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-protobuf", "LGPL-2.1-only", "PSF-2.0", "BSL-1.0", "MIT", "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ]
permissive
apache/mesos
24c92eb34ea9cbb2912d6471815a433c9942e0c9
8856d6fba11281df898fd65b0cafa1e20eb90fe8
refs/heads/master
2023-08-28T06:36:36.458732
2023-01-13T21:00:06
2023-01-14T00:29:23
11,469,439
4,860
2,034
Apache-2.0
2023-04-12T06:10:25
2013-07-17T07:00:13
C++
UTF-8
C++
false
false
2,019
cpp
standalone.cpp
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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 "master/contender/standalone.hpp" #include <mesos/master/contender.hpp> #include <process/future.hpp> using namespace process; namespace mesos { namespace master { namespace contender { StandaloneMasterContender::~StandaloneMasterContender() { if (promise != nullptr) { promise->set(Nothing()); // Leadership lost. delete promise; } } void StandaloneMasterContender::initialize(const MasterInfo& masterInfo) { // We don't really need to store the master in this basic // implementation so we just restore an 'initialized' flag to make // sure it is called. initialized = true; } Future<Future<Nothing>> StandaloneMasterContender::contend() { if (!initialized) { return Failure("Initialize the contender first"); } if (promise != nullptr) { LOG(INFO) << "Withdrawing the previous membership before recontending"; promise->set(Nothing()); delete promise; } // Directly return a future that is always pending because it // represents a membership/leadership that is not going to be lost // until we 'withdraw'. promise = new Promise<Nothing>(); return promise->future(); } } // namespace contender { } // namespace master { } // namespace mesos {
3d474183584e2a13848abdf51c0c48dd73371649
12ff767ff71029d973d9107e27397972679dbdf2
/Majority Element.cpp
46a7f7fa4e77c57499f5c3835b2b0890796ac592
[]
no_license
Anant123321/Practise-In-C
073e29562f66026694303a9463fd5601a4494df7
11366f0a84b2edc67211af18e6c7fb114eb32159
refs/heads/master
2022-04-02T06:45:00.166959
2020-01-26T04:57:54
2020-01-26T04:57:54
198,355,701
1
0
null
null
null
null
UTF-8
C++
false
false
737
cpp
Majority Element.cpp
#include <iostream> using namespace std; #include <bits/stdc++.h> int main() { int testCases; cin >> testCases; for(int t=0;t<testCases;t++) { int size; cin >> size; int arr[size],flag=0; for(int i=0; i<size ;i++) { cin>>arr[i]; } if(size==1)cout<<arr[0]<<endl; else { sort(arr,arr+size); for(int i=0 ; i<=size/2 ; i++) { if(arr[i]==arr[i+(size/2)]) { cout<<arr[i]<<endl; flag=1; break; } } if(!flag) cout<<"-1"<<endl; } } //code return 0; }
80d4f065d129cb21e86ca1d5034a81c00f1934b9
2d9f20e8247fb0b457628391c6a6941f756fba2e
/server/lib/GameServer/Block.hpp
4c4432b562cdc7e389f015a7c14f8dfc247dbf64
[]
no_license
ProjectB/ProjectB
e1644a56714b26ce93b21b32d1c9a6fb0d08e592
35f04106d1ecb79730d755e79e707130046da563
refs/heads/master
2020-12-25T19:14:41.580589
2015-03-22T20:24:56
2015-03-22T20:24:56
5,298,007
0
0
null
null
null
null
UTF-8
C++
false
false
602
hpp
Block.hpp
/* * Block.hpp * * Created on: Jan 25, 2015 * Author: kodo */ #ifndef BLOCK_HPP_ #define BLOCK_HPP_ #include "GenObj.hpp" using namespace std; #include <string> class Block : public GenObject { public: /* GETTERS && SETTERS */ short int getHP() const; void setHP(short int); void decreaseHP(short int); std::string getObjectState() const; /* GETTERS && SETTERS */ Block(bool, std::string, int, int, int, int); ~Block(); private: short int HP; //Hit Points bool isBreakable; //TODO: ARRAY OF ITENS INSIDE std::string generateObjectState() const; }; #endif /* BLOCK_HPP_ */
f742c94f20e3408abf715b3c790a7d471e85c0c2
c6e5be4e1f7c350e3094af3f19730e99b7dc5b55
/ConsoleGameProject/SReferenceDemoScene.cpp
c576c110db1e542b06c6b9aa6f47b1d529ef6dc4
[]
no_license
ounols/Simple-Console-Game-Framework
7d6a77697efd54aa7b5aa1cf7fb0d6a3ec8de15f
2293a72706a8e0b27e736aa2566ea7ba1e0b3521
refs/heads/main
2023-06-27T01:16:41.019122
2021-07-27T20:26:20
2021-07-27T20:26:20
390,114,378
0
0
null
null
null
null
UHC
C++
false
false
1,182
cpp
SReferenceDemoScene.cpp
#include "SReferenceDemoScene.h" #include <math.h> //2. SReference의 오브젝트를 생성자에서 동적할당합니다. SReferenceDemoScene::SReferenceDemoScene() { //2. m_object = new CTexture("demo.bmp"); //일반적인 포인터 m_object2 = new CTexture("demo.bmp"); } //4. 이 씬이 끝나면 SReference가 자동적으로 사라집니다. SReferenceDemoScene::~SReferenceDemoScene() { //자동적으로 사라지기 때문에 //delete함수를 호출할 필요가 없음 //delete m_object.get() //일반적인 포인터는 //스스로 메모리를 해제할 수 없으므로 //직접 메모리 해체를 해야함 delete m_object2; } void SReferenceDemoScene::Update(int deltaTime) { Super::Update(deltaTime); //코드내용 } //3. SReference의 오브젝트를 참조하여 이미지를 그립니다. void SReferenceDemoScene::Render(int deltaTime) { Super::Render(deltaTime); int moveY = 140 + sinf(deltaTime / 100.f) * 100; //3. RenderBitmap(m_object.get(), moveY, 100); // 일반적인 포인터로 함수에 참조값 전달 // (이미 위에서 이미지를 출력했으므로 주석처리) //RenderBitmap(m_object2, moveY, 100); }
33cef168e122f306a62e877d3a0286d361973e2f
c265334a3da99139cc829cb7a47e962dfbff728d
/Final Project C++/Contact.h
0856cb1e38ccd8f2ed791edd810014d3ffe6cd31
[]
no_license
shukiel/CPP_FinalProject
249cd1d2b869b6be13104fcc1346f424bd910d38
1f281bd81d3f62d9e6c1ff2a22e26bbce19e215a
refs/heads/master
2016-09-12T04:24:05.112367
2016-05-28T22:48:27
2016-05-28T22:48:27
55,903,302
0
0
null
null
null
null
UTF-8
C++
false
false
1,237
h
Contact.h
#ifndef __CONTACT_H #define __CONTACT_H #include <iostream> using namespace std; class Contact { protected: char* m_name; char* m_phoneNum; char* m_address; public: Contact(const char* name, const char* phoneNum, const char* address); Contact(const Contact& other) : m_name(NULL), m_phoneNum(NULL), m_address(NULL) { *this = other; } Contact() { } virtual ~Contact(); void setName(const char* name) { m_name = _strdup(name); } void setPhoneNum(const char* phoneNum) { m_phoneNum = _strdup(phoneNum); } void setAddress(const char* address) { m_address = _strdup(address); } const char* getName() const { return m_name; } const char* getPhoneNum() const { return m_phoneNum; } const char* getAddress() const { return m_address; } bool operator==(const Contact& other) const { return strcmp(getName(), other.getName()) == 0 && strcmp(getPhoneNum(), other.getPhoneNum()) == 0; } bool operator!=(const Contact& other) const { return !(*this == other); } const Contact& operator=(const Contact& other); friend ostream& operator<<(ostream& os, const Contact& contact); friend istream& operator>>(istream& in, Contact& contact); virtual void toOs(ostream& os) const; }; #endif
a0173eeeb5cb145aa50e068d6382f26329956d51
1485517c4b25284fc1e4ef15a84b38769791b42a
/01.coding_algorithm/04.std_c++/day01/dbg_assert/debug.hpp
3eb49ab300136c7f020dd084f415a260558b7f40
[]
no_license
lilongbin/esd
846870965d538cf8fa2a11b7b14e54fc894bcab9
30d3777912c2bd4fa3bedb1d85b8c83f45195227
refs/heads/master
2022-05-03T11:19:57.836540
2022-03-30T05:12:36
2022-03-30T05:12:36
40,183,070
0
0
null
null
null
null
UTF-8
C++
false
false
858
hpp
debug.hpp
/***************************************** * Copyright (C) 2018 * Ltd. All rights reserved. * * File name : debug.hpp * Author : longbin * Created date: 2018-08-09 21:57:32 * Description : * *******************************************/ #ifndef __DEBUG_HPP__ #define __DEBUG_HPP__ #include <iostream> #include <execinfo.h> /* include <execinfo.h> to use this macro */ #define DBG_ASSERT(x) do { \ if (x) { break; } \ std::cout << "\r\n------ " << __FILE__ << " " << __LINE__ << " ------" << endl;\ void *pptrace_raw[32] = {0}; \ char **pptrace_str = NULL; \ int trace_num = 0, i = 0; \ trace_num = backtrace(pptrace_raw, 32); \ pptrace_str = (char **)backtrace_symbols(pptrace_raw, trace_num); \ for (i = 0; i < trace_num; i++) { std::cout << pptrace_str[i] << endl; } \ if (pptrace_str) { delete pptrace_str; } \ } while (0); #endif
52ba7885c2a59b02cda80470eb7ff9acfc13e86d
f08db7a0c05a2d1666a940c49f88a5724e4b00fb
/Example_Code/Header_files/extractfeaturesfromimages.cpp
0e0269a0130d12ae0bbdbee9e3eff5a587bd5ed7
[]
no_license
XezXey/Classification-of-Motorcycles
daf35612ed82c58d76701190b9cd9e57f2c5e240
029b13fb8b46acd18b9abcf5717ba29fb9e60b64
refs/heads/master
2021-01-23T09:41:02.022577
2018-04-15T09:26:13
2018-04-15T09:26:13
102,592,571
1
0
null
null
null
null
UTF-8
C++
false
false
9,798
cpp
extractfeaturesfromimages.cpp
// extractfeaturesfromimages.cpp : Defines the entry point for the console application. // This Program start coding at 2/9/2017 15:59 GMT+7 /* Process: 1. This Program will take set of images and use cascade detection for detect the plate of motorcycle 2. Draw the Rectangle of the ROI(region of interest) 3. export only the ROI of image */ #include "stdafx.h" #include "extractfeaturesfromimages.h" #include "opencv2/opencv.hpp" #include "opencv2/objdetect.hpp" #include "opencv2/highgui.hpp" #include "opencv2/imgproc.hpp" #include <algorithm> #include <iostream> #include <stdio.h> #include <cstring> #include <string> //#define DEBUG #define PROCESS using namespace std; using namespace cv; /** Function Headers */ void detect_save_display(Mat motorcycle_frameame); string generate_filename(string filename, int filenum); int image_processing(String input_filename); int video_processing(String input_filename); string save_roi_file(Mat motorcycle_roi, int filenum); vector<Point> check_correct_tl_br(Point tl, Point br); vector<int> check_correct_w_h(Point tl_rect_roi, int width, int height); /** Global variables */ String motorcycle_plate_cascade_name = "cascade_motor_plate.xml"; CascadeClassifier motorcycle_plate_cascade; String window_name_capture = "Capture - Motorcycle Plate detection"; String window_roi = "ROI - Motorcycle"; String filename = ""; int image_size_x = 640, image_size_y = 480; int image_size_export_x = 64, image_size_export_y = 128; int origin_point = 0; int width_shift = 30; int height_shift = 25; int video_processing(String input_filename) { VideoCapture capt_input_video(input_filename); if (!capt_input_video.isOpened()) { return -1; } Size img_size(image_size_x, image_size_y); for (;;) { Mat motorcycle_frame; capt_input_video >> motorcycle_frame; // get a new frame from camera //Flip video in to right direction transpose(motorcycle_frame, motorcycle_frame); flip(motorcycle_frame, motorcycle_frame, 1); //1 is flip the video around resize(motorcycle_frame, motorcycle_frame, img_size); //Resize the image into 640x480 imshow(window_name_capture, motorcycle_frame); detect_save_display(motorcycle_frame); if (waitKey(1) > 0 || motorcycle_frame.empty()) { //delay 25 ms before show a next frame. break; } } // the camera will be deinitialized automatically in VideoCapture destructor; return 0; } int image_processing(String input_filename) { Mat motorcycle_roi; Size img_size(image_size_x, image_size_y); Mat motorcycle_image; motorcycle_image = imread(input_filename); if (!motorcycle_image.data) { cout << "Could not open or find the image" << endl; return -1; } resize(motorcycle_image, motorcycle_image, img_size); detect_save_display(motorcycle_image); return 0; } //generate_filename function will delete the extension of filename and add a filenum to make it difference and can be save string generate_filename(string filename, int filenum) { size_t len_filename_extension = 4; filename.erase(filename.length() - len_filename_extension, len_filename_extension); filename += "_plate_" + to_string(filenum); /* #ifdef DEBUG cout << filenum << endl; cout << "Plate no." << to_string(filenum) << endl; cout << "Generated filename : " << filename << endl; #endif */ return filename; } string save_roi_file(Mat motorcycle_roi, int filenum) { //Generate filename for saving multiple files in case of there are more than one plate can detected. char buffer_filename[50]; char saved_filename[50]; strcpy_s(buffer_filename, generate_filename(filename, (int)filenum).c_str()); sprintf_s(saved_filename, "%s.JPG", buffer_filename); /* #ifdef DEBUG cout << "****************************************************************" << endl; cout << "Filename : " << generate_filename(filename, (int)filenum).c_str() << endl; #endif // DEBUG */ imwrite(saved_filename, motorcycle_roi); return string(saved_filename); } /** @function detect_save_display */ void detect_save_display(Mat motorcycle_frame) { string saved_filename; vector<Rect> plates; Mat motorcycle_grey; //Convert to Gray Scale for processing cvtColor(motorcycle_frame, motorcycle_grey, COLOR_BGR2GRAY); equalizeHist(motorcycle_grey, motorcycle_grey); //-- Detect motorcycle plates motorcycle_plate_cascade.detectMultiScale(motorcycle_grey, plates, 1.1, 2, 0 | CASCADE_SCALE_IMAGE, Size(30, 30)); Mat motorcycle_frame_original = motorcycle_frame.clone(); //After use cascade dectection we get the ROI //plates.size() is number of ROI #ifdef PROCESS if (plates.size() != 0) { cout << "=====================================================================================" << endl; cout << "Filename : " << filename << endl; cout << "We have : " << plates.size() << " plates." << endl; cout << "=====================================================================================" << endl; } #endif for (size_t i = 0; i < plates.size(); i++) { //Delete old Rectangle and draw it on a new image motorcycle_frame = motorcycle_frame_original; //Declare 2 Point of top-left corner and bottom right corner for drawing a rectangle of ROI //Now use 1:1 scale up for covering the ROI //tl is top left corner //br is bottom right corner Point tl_rect_roi(plates[i].x - plates[i].width - width_shift, plates[i].y - plates[i].height - height_shift); Point br_rect_roi(plates[i].x + (2 * plates[i].width), plates[i].y + (2 * plates[i].height)); cout << plates[i].size() << " " << plates[i].x << " " << plates[i].y << " " << plates[i].width << " " << plates[i].height << endl; //Point tl_rect_roi(plates[i].x, plates[i].y); //Point br_rect_roi(plates[i].x, plates[i].y); vector<Point> tl_br_corrected = check_correct_tl_br(tl_rect_roi, br_rect_roi); tl_rect_roi = tl_br_corrected[0]; br_rect_roi = tl_br_corrected[1]; //Draw the lines around the ROI by using red color with thickness = 2 , lineType is 8 and no shift //1. draw by use tl_rect_roi and br_rect_roi //2. draw by use roi that get an information from tl_rect_roi, br_rect_roi and some estimate how big it is // multiple 3 cause i use the 1:1 of plate so we will get the full image from tl and br point that need // to triple extended //Use 2 lines for check that it's the same lines on same roi //rectangle(motorcycle_frame, tl_rect_roi, br_rect_roi, Scalar(0, 0, 255), 2, 8, 0); //Rect roi(tl_rect_roi.x, tl_rect_roi.y, (plates[i].width), (plates[i].height)); //We Use tl(x,y) to draw and RoI and control size by using width and height vector<int> width_height_corrected = check_correct_w_h(tl_rect_roi, plates[i].width, plates[i].height); //Rect roi(tl_rect_roi.x, tl_rect_roi.y, (plates[i].width * 3) + 30, (plates[i].height * 3) + 40); Rect roi(tl_rect_roi.x, tl_rect_roi.y, width_height_corrected[0], width_height_corrected[1]); #ifdef DEBUG cout << width_height_corrected[0] << " " << width_height_corrected[1] << endl; rectangle(motorcycle_frame, roi, Scalar(128, 128, 255), 2, 8, 0); #endif Mat motorcycle_roi; motorcycle_roi = motorcycle_frame_original(roi); #ifdef DEBUG cout << "**********************Plate[" << i + 1 << "]********************** " << endl; cout << "Filename : " << generate_filename(filename, (int)i + 1) << ".JPG" << endl; cout << "Image size : "; cout << "Width = " << motorcycle_frame.size().width; cout << ", Height = " << motorcycle_frame.size().height << endl; cout << "Plate No.: " << " x " << "y " << "width " << "height " << endl; cout << "Plate[" << i + 1 << "] : " << plates[i].x << " " << plates[i].y << " " << plates[i].width << " " << plates[i].height << endl; cout << "Each Plate Value [" << i + 1 << "] : " << plates[i] << endl; cout << "topcorner_rect_roi : " << tl_rect_roi << endl; cout << "bottomcorner_rect_roi : " << br_rect_roi << endl; cout << "Corrected TL : " << tl_rect_roi << endl; cout << "Corrected BR : " << br_rect_roi << endl; cout << "Region of Interest size : " << motorcycle_roi.size() << endl; cout << "=====================================================================================" << endl; #endif Size img_size(image_size_export_x, image_size_export_y); resize(motorcycle_roi, motorcycle_roi, img_size); saved_filename = save_roi_file(motorcycle_roi, (int)i+1); imshow(window_name_capture, motorcycle_frame); //Display all ROI #ifdef DEBUG imshow(saved_filename, motorcycle_roi); #endif #ifdef PROCESS if (plates.size() != 0) { cout << "Filename : " << saved_filename << ".JPG" << endl; cout << "==============================================================================" << endl; } #endif } //-- Show the output (ROI that can detect on the image by using motorcylce_cascade.xml) //imshow(window_name, motorcycle_frame_original); } vector<Point> check_correct_tl_br(Point tl, Point br) { if (tl.x <= origin_point) tl.x = origin_point; if (tl.y <= origin_point) tl.y = origin_point; if (br.x >= image_size_x) br.x = image_size_x - 1; if (br.y >= image_size_y) br.y = image_size_y - 1; return { tl, br }; } vector<int> check_correct_w_h(Point tl_rect_roi, int width, int height) { int width_shift = 30; int height_shift = 25; //Width check and adjust into proper size if ((width * 3) + width_shift > image_size_x || tl_rect_roi.x + (width * 3) + width_shift > image_size_x) width = image_size_x - tl_rect_roi.x; else width = (width * 3) + width_shift; //Height check and adjust into proper size and auto get rid of license plate if ((height) + height_shift > image_size_y || tl_rect_roi.y + (height) + height_shift > image_size_y) height = image_size_y - tl_rect_roi.y; else height = (height) + height_shift; return { width, height }; }
3688c70860ab5f11ba06b7f2c25cbb7871528960
d2efd85bb8e0e98625267d894f5bb8ce672df7b1
/rabbit/String.cpp
0ae72864e573ea6a226d7003e4a5fb38984337b7
[]
no_license
rabbit-repos/rabbit-lang
78d14bcf6414b72c537118992c8d957d07302b6e
ab719613f5469295e2f318d51e645f143efd8972
refs/heads/master
2021-07-17T09:25:53.106905
2017-10-11T22:51:01
2017-10-11T22:51:01
105,410,172
1
0
null
null
null
null
UTF-8
C++
false
false
6,001
cpp
String.cpp
#include "pch.h" #include "String.h" #include "StringData.h" #include "CharUtility.h" String::String() { myData = null; #ifdef _DEBUG myOwner = null; #endif mySize = 0; } String::String(ConstRef<StringData> aString) : String() { myData = aString.GetAddress(); mySize = aString.Size(); #ifdef _DEBUG myOwner = &aString; ++aString.myNumReferences; #endif } String::String(ConstRef<String> aString, Const<i32> aNumberOfCharacters) : String() { if (aNumberOfCharacters > aString.Size()) abort(); myData = aString.GetAddress(); } String::String(ConstPtr<StringData> aOwner, ConstPtr<Char> aDataPoint, Const<i32> aSize) : String() { #ifdef _DEBUG myOwner = aOwner; if (myOwner) ++myOwner->myNumReferences; #else (aOwner); #endif if (aSize > 0) { myData = aDataPoint; mySize = aSize; } else { myData = null; mySize = 0; } } String::String(ConstPtr<Char> aString) { #ifdef _DEBUG myOwner = null; #endif if (aString) { myData = aString; mySize = static_cast<i32>(wcslen(aString)); } else { myData = null; mySize = 0; } } String String::MakeView(Const<i32> aStart, Const<i32> aLength) const { #ifdef _DEBUG return String(myOwner, &myData[aStart], aLength); #else return String(null, &myData[aStart], aLength); #endif } String String::ChopLeft(Const<i32> aEnd) const { #ifdef _DEBUG if (aEnd < 0 || aEnd > mySize) abort(); #endif return MakeView(0, aEnd); } String String::ChopRight(Const<i32> aBegin) const { #ifdef _DEBUG if (aBegin < 0 || aBegin > mySize) abort(); #endif return MakeView(aBegin, mySize - aBegin); } bool String::FindFirst(Const<Char> aChar, Out<i32> aIndex, Const<i32> aBeginAt /*= 0*/) const { Const<i32> n = Size(); for (i32 i = aBeginAt; i < n; ++i) { if ((*this)[i] == aChar) { aIndex = i; return true; } } return false; } bool String::FindLast(Const<Char> aChar, Out<i32> aIndex, Const<i32> aBeginAt /*= MaxOf<i32>*/) const { for (i32 i = Min(Size() - 1, aBeginAt); i >= 0; --i) { if ((*this)[i] == aChar) { aIndex = i; return true; } } return false; } bool String::CopyTo(Ptr<Char> aData, Const<i32> aLength) const { if (mySize + 1 >= aLength) return false; memcpy(aData, myData, mySize * sizeof Char); aData[mySize] = L'\0'; return true; } String::~String() { #ifdef _DEBUG if (myOwner) --myOwner->myNumReferences; myData = null; myOwner = null; mySize = -1; #endif } i32 String::Size() const { return mySize; } bool String::IsEmpty() const { return mySize == 0; } ConstPtr<Char> String::GetAddress() const { return myData; } std::string String::ToASCII() const { std::string str; if (Size() > 0) { Const<i32> n = Size(); str.resize(n); for (i32 i=0; i<n; ++i) { str[i] = static_cast<char>((*this)[i]); } } return str; } std::wstring String::ToWideString() const { std::wstring str; if (Size() > 0) { str.resize(Size()); memcpy(&str[0], GetAddress(), sizeof Char * Size()); } return str; } ConstRef<Char> String::operator[](Const<i32> aIndex) const { #ifdef _DEBUG if (aIndex < 0 || aIndex >= mySize) abort(); #endif return myData[aIndex]; } String String::SubString(Const<i32> aStart, Const<i32> aLength) const { #ifdef _DEBUG if (aStart < 0 || aStart + aLength > mySize) abort(); #endif return MakeView(aStart, aLength); } String String::Trim() const { if (!mySize) return String(); i32 start = 0; while (start < mySize && CharUtility::IsWhiteSpace(myData[start])) ++start; i32 end = mySize - 1; while (end > 0 && CharUtility::IsWhiteSpace(myData[end])) --end; return MakeView(start, end - start + 1); } bool String::BeginsWith(ConstRef<String> aString) const { if (aString.Size() > mySize) return false; for (i32 i = 0; i < aString.Size(); ++i) if ((*this)[i] != aString[i]) return false; return true; } bool String::EndsWith(ConstRef<String> aString) const { if (aString.Size() > mySize) return false; Const<i32> start = mySize - aString.Size(); for (i32 i = 0; i < aString.Size(); ++i) if ((*this)[start + i] != aString[i]) return false; return true; } bool String::Equals(ConstRef<String> aOther) const { return *this == aOther; } bool String::EqualsIgnoreCase(ConstRef<String> aOther) const { if (Size() != aOther.Size()) return false; for (i32 i = 0, n = Size(); i < n; ++i) if (myData[i] != aOther[i] && CharUtility::ToLower(myData[i]) != CharUtility::ToLower(aOther[i])) return false; return true; } bool String::operator==(ConstPtr<char> aOther) const { Const<i32> length = static_cast<i32>(strlen(aOther)); if (length != Size()) return false; for (i32 i = 0; i < length; ++i) if (static_cast<Char>(aOther[i]) != myData[i]) return false; return true; } bool String::operator!=(ConstPtr<char> aOther) const { return !(*this == aOther); } bool String::operator==(ConstPtr<wchar_t> aOther) const { return wcscmp(static_cast<ConstPtr<Char>>(aOther), myData) == 0; } bool String::operator!=(ConstPtr<wchar_t> aOther) const { return !(*this == aOther); } bool String::operator==(ConstRef<String> aOther) const { if (Size() != aOther.Size()) return false; return memcmp(GetAddress(), aOther.GetAddress(), Size() * sizeof Char) == 0; } bool String::operator!=(ConstRef<String> aOther) const { return !(*this == aOther); } Ref<std::wostream> operator<<(Ref<std::wostream> aOut, ConstRef<String> aString) { aOut.write(aString.GetAddress(), aString.Size()); return aOut; } Ref<std::ostream> operator<<(Ref<std::ostream> aOut, ConstRef<String> aString) { for (i32 i=0; i<aString.Size(); ++i) aOut.write(reinterpret_cast<ConstPtr<char>>(&aString[i]), 1); return aOut; } void String::Clear() { *this = String(); }
46ec8e60bd35209a40da1e1133236b29ce3c83f4
d63b4e5366014e4c4ccfbec921960618a7aac136
/Multiplayer/Source/Multiplayer/Private/MultiplayerGI.cpp
8be0e60ca951dbe5e5c6562d05df92edef9253a5
[]
no_license
jobunk/MultiplayerPlugin
dc5b13e6ddda25597021ed41023027ec760d1d44
38e1d115eb4294be3b5f34ebd5ed78f2f9debad5
refs/heads/master
2020-03-19T00:51:21.645069
2018-10-10T11:31:24
2018-10-10T11:31:24
135,505,833
1
0
null
null
null
null
UTF-8
C++
false
false
134
cpp
MultiplayerGI.cpp
// Copyright 2018, Institute for Artificial Intelligence - University of Bremen #include "MultiplayerGI.h" #include "Multiplayer.h"
a264e7342d70128cd610869b7505cfb1ef1b150c
e14dcfc986eacc33b08920bd12766f7aa39aabae
/Classes/CharacterCreator.hpp
6e4411bbc424ad1d63779f0c1852ebe08c19c523
[]
no_license
tempdban/ClashRoyale
c186083562da9fe99e8ca58c95b75072ac134054
79db9ba39bd7306c7501109fc4ee89846f72edf3
refs/heads/master
2021-01-18T10:52:08.194621
2016-04-23T07:07:08
2016-04-23T07:07:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
695
hpp
CharacterCreator.hpp
// // CharacterCreator.hpp // ClashRoyale // // Created by 贾佳菊 on 16/4/7. // // #ifndef CharacterCreator_hpp #define CharacterCreator_hpp #include <stdio.h> #include "Knight.hpp" #include "Fatty.hpp" inline Character *createCharacter(const CharacterName &name, const Side &side, BattleLayer *battleLayer){ if (name == CharacterName::Knight){ Knight *knight = Knight::createKnight(side, battleLayer); return knight; }else if (name == CharacterName::Fatty){ Fatty *fatty = Fatty::createFatty(side, battleLayer); return fatty; }else{ CCLOG("%s, No Name!", __func__); return nullptr; } } #endif /* CharacterCreator_hpp */
858ae4670b6e830e384873d026c2145602e3b343
c50849a706cc2398c32e6b6caaa61b6a6bba50ee
/Skyscrapers/permutation.cpp
736e691f00bde956bbc5988d3be23c97a9eabf48
[]
no_license
SandroWissmann/Skyscrapers
a84e1185fa53318fd6dfd4460aa180e5bf8e07df
15d8f24044d249fcdcb12eecca21d8aff1457c17
refs/heads/main
2023-04-01T20:54:51.575603
2021-03-30T14:25:35
2021-03-30T14:25:35
338,653,413
0
0
null
2021-03-29T15:22:51
2021-02-13T19:33:30
C++
UTF-8
C++
false
false
1,818
cpp
permutation.cpp
#include "permutation.h" #include "permutation/cluepair.h" #include "permutation/permutations.h" #include "permutation/slice.h" #include "shared/board.h" #include "shared/row.h" #include "shared/rowclues.h" #include <cassert> #include <chrono> namespace permutation { std::vector<std::vector<int>> SolvePuzzle(const std::vector<int> &clues, std::vector<std::vector<int>> startingGrid, int) { assert(clues.size() % 4 == 0); std::size_t boardSize = clues.size() / 4; auto rowClues = getRowClues(clues, boardSize); Board board{boardSize}; board.insert(rowClues); board.insert(startingGrid); if (board.isSolved()) { return board.skyscrapers2d(); } solveBoard(board, clues); return board.skyscrapers2d(); } std::vector<std::vector<int>> SolvePuzzle(const std::vector<int> &clues) { return SolvePuzzle(clues, std::vector<std::vector<int>>{}, 0); } void solveBoard(Board &board, const std::vector<int> &clues) { auto cluePairs = makeCluePairs(clues); Permutations permutations(board.size(), Span{&cluePairs[0], cluePairs.size()}, Span{&board.mRows[0], board.mRows.size()}); std::vector<Slice> slices = makeSlices(permutations, board.mRows, cluePairs, board.size()); for (;;) { bool allFull = true; for (std::size_t i = 0; i < slices.size(); ++i) { if (slices[i].isSolved()) { continue; } slices[i].solveFromPossiblePermutations(board.size()); slices[i].guessSkyscraperOutOfNeighbourNopes(); if (!slices[i].isSolved()) { allFull = false; } } if (allFull) { break; } } } } // namespace permutation
de8d16f5a4869dec7d8b3963a62ee222ec23e29c
af24b7c9849912dbb890feae9a7fe1c7c4764aeb
/unfinished/CounterGame.cpp
44b121e19415b77f2fa8e3177f21986beeec096b
[]
no_license
armandwayoff/Competitive-Programming-Practice
08f93c36901bcaccfa3bfc4ca93167fd7a8d612d
a9f879480c7f9ec1aebd89fd06be9c7d60ad36ef
refs/heads/master
2023-03-30T04:47:04.077906
2021-03-27T13:47:11
2021-03-27T13:47:11
268,369,837
1
0
null
null
null
null
UTF-8
C++
false
false
305
cpp
CounterGame.cpp
string counterGame(long n) { int count = 0; while (n > 1) { if ((n & (n - 1)) == 0) { n /= 2; count++; } else { n -= (1 << int(log2(n))); count++; } } if (count % 2 == 0) { return "Richard"; } else { return "Louise"; } }
28380990d5d3bd5f97db81e5044a93713e8a1a5f
48a6469d1aea78bc1cc008aa6ea04ad3e22ddf76
/UPETool/DlgXPInstall.cpp
2cfedbd00be519f1f551622a578db65977cfdde0
[]
no_license
trustyboy/UWinInstall
28748c27cd1d140ff50fa4dcbe02b51bdd2e9fd3
65cea459b99d5c709961398e29f5edffeaf0e38c
refs/heads/master
2023-03-15T22:48:23.029416
2018-03-16T18:36:01
2018-03-16T18:36:01
null
0
0
null
null
null
null
GB18030
C++
false
false
9,147
cpp
DlgXPInstall.cpp
// DlgXPInstall.cpp : 实现文件 // #include "stdafx.h" #include "UPETool.h" #include "DlgXPInstall.h" #include "afxdialogex.h" #include "DlgConfirmWithDefault.h" #include "ComfirmDlgModule.h" #include "RebootNoticeModule.h" #include "ShutdownNoticeModule.h" #include "DriverInfo.h" #include <vector> #include "PartionInfo.h" #include "util/StringEx.h" #include "UserMsg.h" #include "util.h" #include "CmdExecuter.h" #include "util/File.h" #include "util/Logger.h" // CDlgXPInstall 对话框 IMPLEMENT_DYNAMIC(CDlgXPInstall, CDialogEx) CDlgXPInstall::CDlgXPInstall(CWnd* pParent /*=NULL*/) : CDialogEx(CDlgXPInstall::IDD, pParent) , m_strDestPartionName(_T("")) , m_strPartionId(_T("")) , m_strSourceMain(_T("")) , m_strSourceSub(_T("")) , m_bIsFormat(FALSE) , m_bIsBoot(FALSE) , m_strKey1(_T("")) , m_strKey2(_T("")) , m_strKey3(_T("")) , m_strKey4(_T("")) , m_strKey5(_T("")) , m_bReboot(FALSE) , m_bHalt(FALSE) { m_hThread = NULL; } CDlgXPInstall::~CDlgXPInstall() { } void CDlgXPInstall::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, IDC_STATIC_DEST_PARTION_NAME, m_strDestPartionName); DDX_Text(pDX, IDC_STATIC_DEST_PARTION_ID, m_strPartionId); DDX_Text(pDX, IDC_STATIC_SOURCE_MAIN, m_strSourceMain); DDX_Text(pDX, IDC_STATIC_SOURCE_SUB, m_strSourceSub); DDX_Check(pDX, IDC_CHECK_FORMAT, m_bIsFormat); DDX_Check(pDX, IDC_CHECK_BOOT, m_bIsBoot); DDX_Control(pDX, IDC_COMBO_FORMAT_TYPE, m_comboForamtType); DDX_Control(pDX, IDC_COMBO2, m_comboBoot); DDX_Text(pDX, IDC_EDIT_KEY1, m_strKey1); DDV_MaxChars(pDX, m_strKey1, 5); DDX_Text(pDX, IDC_EDIT_KEY2, m_strKey2); DDV_MaxChars(pDX, m_strKey2, 5); DDX_Text(pDX, IDC_EDIT_KEY3, m_strKey3); DDV_MaxChars(pDX, m_strKey3, 5); DDX_Text(pDX, IDC_EDIT_KEY4, m_strKey4); DDV_MaxChars(pDX, m_strKey4, 5); DDX_Text(pDX, IDC_EDIT_KEY5, m_strKey5); DDV_MaxChars(pDX, m_strKey5, 5); DDX_Check(pDX, IDC_CHECK_REBOOT, m_bReboot); DDX_Check(pDX, IDC_CHECK_SHUTDOWN, m_bHalt); } BEGIN_MESSAGE_MAP(CDlgXPInstall, CDialogEx) ON_BN_CLICKED(IDOK, &CDlgXPInstall::OnBnClickedOk) ON_MESSAGE(WM_INSTALL_XP_RESULT,&CDlgXPInstall::OnFinishInstall) ON_BN_CLICKED(IDCANCEL, &CDlgXPInstall::OnBnClickedCancel) END_MESSAGE_MAP() // CDlgXPInstall 消息处理程序 BOOL CDlgXPInstall::OnInitDialog() { CDialogEx::OnInitDialog(); // TODO: 在此添加额外的初始化 m_bIsFormat = TRUE; m_bIsBoot = TRUE; m_bReboot = TRUE; m_bHalt = FALSE; m_comboForamtType.AddString(_T("NTFS [自动]")); m_comboForamtType.AddString(_T("FAT32 [自动]")); m_comboForamtType.AddString(_T("自定义 [手动]")); m_comboForamtType.SetCurSel(0); std::vector<CDriverInfo> arr; CPartionInfo::GetPartionsInfo(arr); BOOL bFirstValide = TRUE; for(int i=0; i!=arr.size(); i++) { CDriverInfo dv = arr[i]; wstring str = dv.m_PartionName.substr(0,2).c_str(); if (str[0] == L'X' || str[0] == L'Z') { continue; } if (bFirstValide) { str += L" [推荐]"; bFirstValide = FALSE; } m_comboBoot.AddString(str.c_str()); } m_comboBoot.SetCurSel(0); UpdateData(FALSE); return TRUE; // return TRUE unless you set the focus to a control // 异常: OCX 属性页应返回 FALSE } BOOL CDlgXPInstall::PreTranslateMessage(MSG* pMsg) { // TODO: 在此添加专用代码和/或调用基类 if(pMsg->message == WM_KEYDOWN && (pMsg->wParam == VK_ESCAPE) || (pMsg->wParam == VK_RETURN)) return TRUE; return CDialogEx::PreTranslateMessage(pMsg); } void CDlgXPInstall::OnBnClickedOk() { // TODO: 在此添加控件通知处理程序代码 //CDialogEx::OnOK(); // lllll-mmmmm-nnnnn-ooooo-ppppp UpdateData(TRUE); m_strKeyTotal = m_strKey1 + _T("-") + m_strKey2 + _T("-") + m_strKey3 + _T("-") + m_strKey4 + _T("-") + m_strKey5; m_hThread = AfxBeginThread(ThreadFunXpSetup,this)->m_hThread; GetDlgItem(IDOK)->EnableWindow(FALSE); } UINT CDlgXPInstall::ThreadFunXpSetup( LPVOID lpThreadParam ) { CDlgXPInstall* pDlg = (CDlgXPInstall*) lpThreadParam; UINT result = pDlg->doXpSetup(); return result; } UINT CDlgXPInstall::doXpSetup() { if (m_bIsFormat) { int FmtSel = m_comboForamtType.GetCurSel(); if (FmtSel == -1) { LOG_INFO("发生逻辑错误,当前选中的格式化方式未定义"); return 1; } ETypeFormatXP eFormatType = (ETypeFormatXP)FmtSel; //格式化 ASSERT(EFT_NTFS == eFormatType || EFT_USERDEFINE == eFormatType || EFT_FAT32 == eFormatType); if (eFormatType == EFT_USERDEFINE) { LOG_WARN("客户选中了自定义模式,不做任何格式化。"); } else { //PostMessage(WM_MYMSG_IMAGEX_INSTALL_TOTAL_PROGRESS,STEP_START_FORMAT); ASSERT(m_strDestPartionName.GetLength() >= 2); //C: CString TargetPartion = m_strDestPartionName.Left(2); std::wstring wstrCmdLine = L"/c format.com /q /x /y "; wstrCmdLine += (LPCWSTR)TargetPartion; if (eFormatType == EFT_NTFS) { LOG_INFO("用户选择了NTFS格式化"); wstrCmdLine += L" /fs:NTFS"; } else if (eFormatType == EFT_FAT32) { LOG_INFO("用户选择了FAT32格式化"); wstrCmdLine += L" /fs:FAT32"; } // X:\\Windows\\system32\\cmd.exe /c format.com /q /x /y C: /fs:NTFS CCmdExecuter exec; std::wstring Result; INT cmdR = exec.ExecCommandWithResultText(L"X:\\Windows\\system32\\cmd.exe",wstrCmdLine.c_str(),Result); LOG_INFO("执行格式化的结果为:%d",cmdR); //PostMessage(WM_MYMSG_IMAGEX_INSTALL_TOTAL_PROGRESS,STEP_END_FORMAT,cmdR); if (cmdR != 0) { PostMessage(WM_INSTALL_XP_RESULT,XP_INSTALL_ERR_FORMAT,1); return cmdR; } } } // Current work path : [Z:\\I386\\] /* bootsect.exe /nt52 C: */ WCHAR szCurPath[MAX_PATH] = {0}; GetCurrentDirectoryW(MAX_PATH,szCurPath); SetCurrentDirectoryW(L"Z:\\I386\\"); //sif文件保存了KEY,将他替换为用户输入的KEY std::wstring sifPath = L"X:\\Temp\\winnt.sif"; CUtil::ExtractResource(MAKEINTRESOURCE(IDR_BIN_XP_SIF),L"BIN",sifPath.c_str(),NULL); FileReader fr(String::fromStdWString(sifPath)); if (!fr.open()) { SetCurrentDirectoryW(szCurPath); LOG_ERROR("读取释放的sif文件时发生了错误%d",GetLastError()); PostMessage(WM_INSTALL_XP_RESULT,XP_INSTALL_ERR_EXTRACT_SIF,1); return 1; }else{ // 替换key std::string strContentOfSif = fr.read(); fr.close(); std::string toReplace = "lllll-mmmmm-nnnnn-ooooo-ppppp"; std::string replaceText = String::fromStdWString((LPCTSTR)m_strKeyTotal); String TempContent(strContentOfSif); TempContent.replace(toReplace,replaceText); strContentOfSif = TempContent; // 保存回去 FileWriter fw(String::fromStdWString(sifPath)); if (!fw.open()) { LOG_ERROR("写入安装序列号时发生了错误%d",GetLastError()); PostMessage(WM_INSTALL_XP_RESULT,XP_INSTALL_ERR_EXTRACT_SIF,2); return 1; }else{ fw.write(strContentOfSif); fw.close(); } } std::wstring commandLine = L"Z:\\I386\\winnt32.exe /s:\"Z:\\i386\" /unattend:\""; commandLine += sifPath; commandLine += L"\" /makelocalsource /tempdrive:C /syspart:C"; CExtractCmdExecuter ex; INT Iresult = ex.ExecCommand(NULL,commandLine.c_str()); if (Iresult != 0) { SetCurrentDirectoryW(szCurPath); LOG_ERROR("安装系统时发生了错误,执行winnt32返回了错误%d",Iresult); PostMessage(WM_INSTALL_XP_RESULT,XP_INSTALL_ERR_INSTALL,Iresult); return Iresult; } CExtractCmdExecuter booter; booter.Extract(IDR_BIN_BOOTSECT,L"BIN",L"bootsect.exe"); commandLine = L"bootsect.exe /nt52 C:"; Iresult = booter.ExecCommand(NULL,commandLine.c_str()); if (Iresult != 0) { SetCurrentDirectoryW(szCurPath); LOG_ERROR("安装系统时发生了错误,执行bootsect返回了错误%d",Iresult); PostMessage(WM_INSTALL_XP_RESULT,XP_INSTALL_ERR_BOOT_SECT,Iresult); return Iresult; } SetCurrentDirectoryW(szCurPath); PostMessage(WM_INSTALL_XP_RESULT,XP_INSTALL_SUCCESS,Iresult); return Iresult; } LRESULT CDlgXPInstall::OnFinishInstall( WPARAM wParam,LPARAM lParam ) { switch (wParam) { case XP_INSTALL_ERR_EXTRACT_SIF: if (lParam == 1) { MessageBox(_T("因无法正常读取序列号文件,安装系统失败了。")); } else if (lParam == 2) { MessageBox(_T("因无法正常写入序列号,安装系统失败了。")); }else{ ASSERT(0); } break; case XP_INSTALL_ERR_INSTALL: { MessageBox(_T("安装失败")); } break; case XP_INSTALL_ERR_BOOT_SECT: MessageBox(_T("因添加引导发生了错误,安装失败。")); break; case XP_INSTALL_SUCCESS: { IComfirmDlgModule* pModule = NULL; if (m_bReboot) { pModule = new CRebootNoticeModule; } else if (m_bHalt) { pModule = new CShutdownNoticeModule; } if (pModule) { CDlgConfirmWithDefault dlg(pModule, NULL); if (dlg.DoModal() == IDCANCEL) { EndDialog(IDCANCEL); }else EndDialog(IDOK); delete pModule; } } break; default: break; } GetDlgItem(IDOK)->EnableWindow(TRUE); return 1; } void CDlgXPInstall::OnBnClickedCancel() { // TODO: 在此添加控件通知处理程序代码 if (m_hThread) { TerminateProcess(m_hThread,1); WaitForSingleObject(m_hThread,1000); } CDialogEx::OnCancel(); }
af33072aa26cb6547b3d480089951389e1e3bdf7
43a277517abfeb8d7a3b11a5054ee6b0b8b35a58
/src/ripplevaultappui.cpp
747b7addd5fc898a5fccb15f8d6672e0e175f927
[]
no_license
deepakprabhakara/ripplevault
79f87099373aa2ea63229fe3cb8c05f30a857bd6
565786fb3a3f4c9721c79b581e86cfc69594dc2e
refs/heads/master
2021-01-20T12:21:19.350565
2010-10-25T19:32:42
2010-10-25T19:32:42
1,023,312
1
0
null
null
null
null
UTF-8
C++
false
false
390,227
cpp
ripplevaultappui.cpp
/******************************************************************* Copyright(c) 2000-2005 PurpleACE Wireless Solutions Pvt. Ltd. www.purpleace.com #708, A Wing, Carlton Towers, Airport Road, Bangalore - 560017, India All rights reserved. This software is the confidential and proprietary information of PurpleACE Wireless Solutions Pvt. Ltd. ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only in accordance with the terms of the license Agreement you entered into with PurpleACE Wireless Solutions Pvt. Ltd.. Project Name : Ripple Vault Symbian Client Module Name : RippleVaultAppUi.cpp Language used : C++ Coding Standard : Symbian Coding Standards Author : Ezhil,Deepak Date Created : 14-01-2004 Rational Rose Model Name : Use Case Document Name : Use Case Realization Document Name : Test Case Document Name : Abbreviations : Description : Main file for RippleVault APP Code Reviews Code Reviewed By : Code Reviewed Date : Recommendations : ***************************************************************/ /********************* MACRO __UIQ__ is for UIQ builds, otherwise by default S60 build WAP_PT is for WAP stack client, otherwise Internet APN build by default NOKIA6600 is for Symbian 7 specific build. Videosengine6600 is specifically for Symbian 7 & 8 phones due to the difference in the way videos are saved on these phones. The above MACRO's are defined in the .mmp files in group folder */ #ifndef __UIQ__ // series 60 #include <avkon.hrh> #include <bautils.h> #include <akntitle.h> #include <apselect.h> #include <eikmenup.h> #include <intconninit.h> #include <RippleVault.rsg> #include <aplistitemlist.h> #include <aknmessagequerydialog.h> #include <aknnotewrappers.h> #include "HelpView.h" #include "FindBoxView.h" #include "RegisterView.h" #include "TestFileView2.h" #include "RippleVault.hrh" #include "PhotoListView.h" #include "UnRegisterView.h" #include "ManualSmsListView.h" //#include "MainScreenListView.h" //#include "MainSubScreenListView.h" #include "AknExSettingListView.h" //#include "SetupWizardListView.h" #include "SelectiveSmsListView.h" //#include <apdatahandler.h> //#include <CommDbConnPref.h> //#include <apaccesspointitem.h> #else #ifdef __S80__ #include "UnRegisterView.h" //#include "RegisterView.h" #include "SmsListView.h" #include "PhotoListView.h" #include "StatusScreenView.h" #include "ContactsView.h" #include "VideoListView.h" #include "imsi.h" #include "CheckNetwork.h" //#include <eikenv.h> //#include <eikon.rsg> //#include <apgtask.h> #include <eikcmbox.h> #include<eikmfne.h> #include <plpvariant.h> #include <AgentClient.h> #include <ckninfo.h> #include <eikchkbx.h> #include<eikbutb.h> #include <RippleVault_series80.rsg> #include "ripplevault_series80.hrh" #include <etel3rdparty.h> #include <eikhopbt.h> #include <eikmfne.h> #include <eikmenub.h> #include <cknconf.h> #else //UIQ #include <commdb.h> #include <badesca.h> #include <cdbover.h> #include <cntitem.h> #include <bautils.h> #include <cntfldst.h> #include <eikcmbox.h> #include <eiktxlbm.h> #include <eikmenub.h> #include <eikchlst.h> #include <cdbstore.h> #include <plpvariant.h> #include <QikIpeditor.h> #include <AgentClient.h> #include <QikNumberEditor.h> #include <QikTimeEditor.h> #include <RippleVault_uiq.rsg> #include <qikvertoptionbuttonlist.h> #include "RippleVault_uiq.hrh" #include <qikon.hrh> #include <mtclreg.h>//for sms #include <smsclnt.h> #include <txtrich.h> #include <smuthdr.h> #include <eiklabel.h> #include <eikchkbx.h> #include<eikbutb.h> #include "UnRegisterView_Uiq.h" //#include "MainScreenView_Uiq.h" #include "MainScreenListBox.h" #include "PhotoScreenView_Uiq.h" #include "MediaScreenListBox.h" #include "VideoScreenView_Uiq.h" #include "SmsScreenView_Uiq.h" #include "StatusScreenView_Uiq.h" #include "ContactsScreenView_Uiq.h" #endif #endif #ifndef __UIQ__ #include <e32base.h> #include <gulicon.h> #include <akniconarray.h> #include <AVKON.mbg> #include "marking.mbg" #endif #include "RippleVault.pan" #include "RippleVaultAppUi.h" //#include "SmsTimer.h" #include "PhotosEngine.h" #include "PhotosTimer.h" #include "ContactsTimer.h" #include "SmsBackupTimer.h" #include "WriteSmsAO.h" //#include "SmsBackupAO.h" #include "VideosEngine.h" //#include "dnsresolver.h" #include "socketsenginewriter.h" #include <AgentClient.h> #include <cdbcols.h> #include <commdb.h> #include <cdbover.h> #include <cdbstore.h> #include <eikspane.h> #include <f32file.h> #include <s32file.h> #include <d32dbms.h> #include <etel.h> #include <cdbcols.h> #include <apparc.h> #include <eikenv.h> #include <eikapp.h> #include <cdbcols.h> #include <apgcli.h> #ifndef __S80__ #include <etelagsm.h> #endif #include <etelmm.h> #include <utf.h> //deepak #include "CopyContactsAO.h" #include "ChangesContactsAO.h" #include "SMSEngine.h" #include "SmsSimEngine.h" //#include "BillingEngine.h" #include "smsfile.h" #include "List.h" #include "RecordContactDB.h" #include <cntdb.h> //_____________________ #ifdef __WINSCW__ #define EMULATOR #endif /* #ifdef __UIQ__ //P800 Photo Path _LIT(KDir1,"c:\\documents\\media files\\image\\unfiled"); _LIT(KDir2,"d:\\media files\\image\\unfiled"); _LIT(KDir3,"c:\\documents\\media files\\video\\unfiled"); _LIT(KDir4,"d:\\media files\\video\\unfiled"); _LIT(KDir5,"c:\\documents\\media files\\image\\Sony Ericsson"); _LIT(KDir6,"d:\\media files\\image\\Sony Ericsson"); _LIT(KDir7,"c:\\documents\\media files\\video\\Sony Ericsson"); _LIT(KDir8,"d:\\media files\\video\\Sony Ericsson"); _LIT(KFolder1,"c:\\documents\\media files\\image\\unfiled\\"); _LIT(KFolder2,"d:\\media files\\image\\unfiled\\"); _LIT(KFolder3,"c:\\documents\\media files\\video\\unfiled\\"); _LIT(KFolder4,"d:\\media files\\video\\unfiled\\"); _LIT(KImageFolder1,"c:\\documents\\media files\\image\\unfiled\\*"); _LIT(KImageFolder2,"d:\\media files\\image\\unfiled\\*"); _LIT(KVideoFolder1,"c:\\documents\\media files\\video\\unfiled\\*"); _LIT(KVideoFolder2,"d:\\media files\\video\\unfiled\\*"); #else _LIT(KDir1,"c:\\Nokia\\Images"); _LIT(KDir2,"e:\\Images"); _LIT(KDir3,"c:\\Nokia\\Videos"); _LIT(KDir4,"e:\\Videos"); _LIT(KImageFolder1,"c:\\Nokia\\Images\\*"); _LIT(KImageFolder2,"e:\\Images\\*"); _LIT(KVideoFolder1,"c:\\Nokia\\Videos\\*"); _LIT(KVideoFolder2,"e:\\Videos\\*"); _LIT(KFolder1,"c:\\Nokia\\Images\\"); _LIT(KFolder2,"e:\\Images\\"); _LIT(KFolder3,"c:\\Nokia\\Videos\\"); _LIT(KFolder4,"e:\\Videos\\"); #endif */ class CPhotosTimer; class CContactsTimer; class CSmsBackupTimer; class CWriteSmsAO; //class CSmsBackupAO; class CPhotosEngine; class CVideosEngine; // ================= MEMBER FUNCTIONS ======================= // --------------------------------------------------------- // CRippleVaultAppUi::GetIMEIFromPhoneL() // Retreives IMEI number // --------------------------------------------------------- void CRippleVaultAppUi::GetIMEIFromPhoneL() { #ifdef __WINS__ iIMEIPhone.Copy(_L("1234567890")); #elif __UIQ__ TPlpVariantMachineId aId; PlpVariant::GetMachineIdL(aId); iIMEIPhone.Copy(aId); #else //Series 60 TBuf<255> tsyName; // Read the TSY name from CommsDB CCommsDatabase* db = CCommsDatabase::NewL(EDatabaseTypeUnspecified); CleanupStack::PushL(db); CCommsDbTableView* table = db->OpenTableLC(TPtrC(MODEM)); table->GotoFirstRecord(); table->ReadTextL(TPtrC(MODEM_TSY_NAME),tsyName); // Cleanup - CommsDB no longer needed CleanupStack::PopAndDestroy(2); // table,db if (!tsyName.Length()) { User::Leave(KErrNotFound); } // Connect to the ETel server RTelServer telServer; User::LeaveIfError(telServer.Connect()); CleanupClosePushL(telServer); // Make sure our TSY is loaded User::LeaveIfError(telServer.LoadPhoneModule(tsyName)); // Get the number of registered phones TInt numberOfPhones; User::LeaveIfError(telServer.EnumeratePhones(numberOfPhones)); TInt aPhoneId=0; // Get the phone name RTelServer::TPhoneInfo phoneInfo; User::LeaveIfError(telServer.GetPhoneInfo(aPhoneId,phoneInfo)); // Open the phone by name RBasicGsmPhone phone; User::LeaveIfError(phone.Open(telServer,phoneInfo.iName)); CleanupClosePushL(phone); // Get Phone Info RBasicGsmPhone::TId id; User::LeaveIfError(phone.GetGsmPhoneId(id)); // Close the Phone handle, no longer needed CleanupStack::PopAndDestroy(); // phone // Return the retrieved IMEI Number iIMEIPhone.Copy(id.iSerialNumber); // Cleanup telServer.UnloadPhoneModule(tsyName); CleanupStack::PopAndDestroy(); // telServer #endif } void CRippleVaultAppUi::ConstructL() { #ifdef __NOKIA6600__ BaseConstructL(EAknEnableSkin); // support themes on sym7 onwards #else BaseConstructL(); #endif TBuf<128> name; name = CRippleVaultAppUi::ApplicationDriveAndPath(); name.Append(KTempFile); #ifdef __LOGME__ iLogSession.Connect(); TInt err=LogFile.Open(iLogSession,name,EFileStreamText|EFileWrite|EFileShareAny); if (err==KErrNotFound) err=LogFile.Create(iLogSession,name,EFileStreamText|EFileWrite|EFileShareAny); else { LogFile.Seek(ESeekEnd,0); } #endif #ifdef __LOGME__ LogText.Copy(_L("Log Started\n\n\n")); WriteLogFile(LogText); #endif //////////////////////////////// //for packets photo GetIMEIFromPhoneL(); iPhotosEngine1 = NULL; iPhotosEngine2 = NULL; iVideosEngine1 = NULL; iVideosEngine2 = NULL; iPhotosTimer = NULL; iContactsTimer = NULL; iSmsBackupTimer = NULL; iWriteSmsAO = NULL; // iSmsBackupAO = NULL; iWaitDialog = NULL; #ifdef __UIQ__ //#ifndef __S80__ iPhotosEngine3 = NULL; iPhotosEngine4 = NULL; iVideosEngine3 = NULL; iVideosEngine4 = NULL; //#endif #endif iChangeNotifier = NULL; iSMSEngine = NULL; iSmsSimEngine = NULL; // iBillingEngine = NULL; iCopyAO = NULL; iChangesAO = NULL; iContactsHandler = NULL; iContactsDB = NULL; iRipplePhotos = 0; iApnCount = -1; #ifdef __LOGME__ LogText.Copy(_L("Log Started2\n\n\n")); WriteLogFile(LogText); #endif //UPGRADE TBool upgflag = CheckUpgradeFile(); RegisterContactsChangeHandler(); iPhotosDB = CPhotosDB::NewL(); //TBuf<128> name; name.Copy(_L("")); name = CRippleVaultAppUi::ApplicationDriveAndPath(); name.Append(KDatabaseName); if (iPhotosDB->CreateDbL(name) != KErrNone) { // assume db exists iPhotosDB->OpenDbL(name); } iVersion.Copy(_L("")); iOs.Copy(_L("")); iUserNames.Copy(_L("")); iMobileNo.Copy(_L("")); iPassword.Copy(_L("")); // iCharge.Copy(_L("")); iRegUrl.Copy(_L("")); iPublishUrl.Copy(_L("")); iContactsUrl.Copy(_L("")); iSmsUrl.Copy(_L("")); // iChargeClient.Copy(_L("")); // iChargePhoto.Copy(_L("")); // iChargeVideo.Copy(_L("")); iWapUrl.Copy(_L("")); iPlanUrl.Copy(_L("")); iAlbumUrl.Copy(_L("")); iStatusUrl.Copy(_L("")); iGateWay.Copy(_L("")); iAccessPoints.Copy(_L("")); LoadParamsFromConfigFile(); GetImsiNumber(); CheckLockFile(); if(upgflag) iPhotosDB->SaveUpgradeStatus(0, iVersion); // iDNSResolver = new CDNSResolver; // TBuf<80> path; // path.Copy(ApplicationDriveAndPath()); // path.Append(_L("dns.txt")); // iDNSResolver->Init(path); TInt ports; TInt modes; TInt desc; TInt roam; TInt autostart; //TInt ccount; TInt securegallery; TInt upload; #ifdef __LOGME__ LogText.Copy(_L("Log Started10\n\n\n")); WriteLogFile(LogText); #endif GetContactsSettingsFromDB(roam,upload); iContactsHandler->iContactsRoaming = roam; iContactsHandler->iContactsUpload = upload; GetSettingsFromDB(iServerAddr, ports, autostart); GetPhotosSettingsFromDB(modes, desc, roam, securegallery); TInt smstype; TTime time; TInt smsroam; GetSmsSettingsFromDB(smstype, time, smsroam); //GetContactsUploadSettingsFromDB(ccount); iPort=ports; iMode=modes; iDescription=desc; iRoaming=roam; iAutostart = autostart; //iContactsCount = ccount; iContactsCount = 0; iConnection = 0; iSecureGallery = securegallery; iSmsMode = smstype; iSmsTime = time; iSmsRoam = smsroam; iSmsValue = 0; iContactsTimerState = 0; //iApnCount = 2; iSmsFile = CSmsFile::NewL(*this); iSmsNotif.HomeTime(); TTimeIntervalHours hours(6); iSmsNotif - hours; #ifdef __UIQ__ #ifdef __S80__ iUnRegisterView = NULL; //iRegisterView = NULL; iSmsListView = NULL; iPhotoListView = NULL; iStatusScreenView = NULL; iProgressBall = NULL; iContactsListView = NULL; iVideoListView = NULL; #else iUnRegisterView = NULL; //iMainScreenView = NULL; iPhotoListView = NULL; iVideoListView = NULL; iSmsListView = NULL; iStatusScreenView = NULL; iContactsScreenView = NULL; #endif iMainScreenValue = 0; #ifdef __S80__ iCBA = CEikButtonGroupContainer::Current(); #endif if(RegFileExists()) { DefaultAccessPoint(); ReadUserName(); //DeleteFolderFromDB(*(iEikonEnv->AllocReadResourceL(R_DEFAULT_ALBUM_OTHER))); //CheckAndSaveFolderToDB(*(iEikonEnv->AllocReadResourceL(R_DEFAULT_ALBUM))); ShowWindow(KViewIdStatusScreen); //mainscreen view ImsiCheck(); } else { ShowWindow(KViewIdUnregisterScreen); //unregisterview TInt Reg; Reg = ChooseAccessPoint(); AutoRegisterRipple(); } #else // Series 60 code //Show=0; Show=1; CEikStatusPane* statusPane=iEikonEnv->AppUiFactory()->StatusPane(); statusPane->SwitchLayoutL(R_AVKON_STATUS_PANE_LAYOUT_USUAL); StatusPane()->MakeVisible(ETrue); CAknTitlePane* tp=(CAknTitlePane*)statusPane->ControlL(TUid::Uid(EEikStatusPaneUidTitle)); tp->SetTextL(*(iEikonEnv->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH))); // Set the text string. CUnRegisterView* UnRegView = new (ELeave) CUnRegisterView; CleanupStack::PushL( UnRegView ); UnRegView->iPhotosAppUi = this; UnRegView->ConstructL(); AddViewL( UnRegView ); // transfer ownership to CAknViewAppUi CleanupStack::Pop(); CRegisterView* RegView = new (ELeave) CRegisterView; CleanupStack::PushL( RegView ); RegView->iPhotosAppUi = this; iRegView = RegView; RegView->ConstructL(); AddViewL( RegView ); // transfer ownership to CAknViewAppUi CleanupStack::Pop(); CAknExSettingListView* view = new( ELeave ) CAknExSettingListView; CleanupStack::PushL( view ); view->iPhotosAppUi = this; AddViewL( view ); // transfer ownership to CAknViewAppUi CleanupStack::Pop(); // view /* CSetupWizardListView* setupview = new( ELeave ) CSetupWizardListView; CleanupStack::PushL( setupview ); setupview->iPhotosAppUi = this; AddViewL( setupview ); // transfer ownership to CAknViewAppUi CleanupStack::Pop(); // view CAknExContactsSettingListView* contactsview = new( ELeave ) CAknExContactsSettingListView; CleanupStack::PushL( contactsview ); contactsview->iContactsAppUi = this; AddViewL( contactsview ); // transfer ownership to CAknViewAppUi CleanupStack::Pop(); // view CAknExPhotosSettingListView* photosview = new( ELeave ) CAknExPhotosSettingListView; CleanupStack::PushL( photosview ); photosview->iContactsAppUi = this; AddViewL( photosview );// transfer ownership to CAknViewAppUi CleanupStack::Pop(); // view CAknExSmsSettingListView* smsview = new( ELeave ) CAknExSmsSettingListView; CleanupStack::PushL( smsview ); smsview->iContactsAppUi = this; AddViewL( smsview ); // transfer ownership to CAknViewAppUi CleanupStack::Pop(); // view */ CTestFileView2* view2 = new (ELeave) CTestFileView2; CleanupStack::PushL( view2 ); view2->ConstructL(); AddViewL( view2 ); // transfer ownership to CAknViewAppUi CleanupStack::Pop(); // view2 CPhotoListView* photolist = new (ELeave) CPhotoListView; CleanupStack::PushL( photolist ); photolist->iPhotosAppUi = this; photolist->ConstructL(); AddViewL( photolist ); // transfer ownership to CAknViewAppUi CleanupStack::Pop(); // photolist CFindBoxView* findview = new (ELeave) CFindBoxView; CleanupStack::PushL( findview ); findview->iPhotosAppUi = this; findview->ConstructL(); AddViewL( findview ); // transfer ownership to CAknViewAppUi CleanupStack::Pop(); CHelpView* help = new (ELeave) CHelpView; CleanupStack::PushL( help ); help->iPhotosAppUi = this; help->ConstructL(); AddViewL( help ); // transfer ownership to CAknViewAppUi CleanupStack::Pop(); CManualSmsListView* manualsms = new (ELeave) CManualSmsListView; CleanupStack::PushL( manualsms ); manualsms->iPhotosAppUi = this; manualsms->ConstructL(); AddViewL( manualsms ); // transfer ownership to CAknViewAppUi CleanupStack::Pop(); CSelectiveSmsListView* selectivesms = new (ELeave) CSelectiveSmsListView; CleanupStack::PushL( selectivesms ); selectivesms->iPhotosAppUi = this; selectivesms->ConstructL(); AddViewL( selectivesms ); // transfer ownership to CAknViewAppUi CleanupStack::Pop(); /*CMainScreenListView* mainScreen = new (ELeave) CMainScreenListView; CleanupStack::PushL( mainScreen ); mainScreen->iPhotosAppUi = this; mainScreen->ConstructL(); AddViewL( mainScreen ); // transfer ownership to CAknViewAppUi CleanupStack::Pop(); CMainSubScreenListView* mainSubScreen = new (ELeave) CMainSubScreenListView; CleanupStack::PushL( mainSubScreen ); mainSubScreen->iPhotosAppUi = this; mainSubScreen->ConstructL(); AddViewL( mainSubScreen ); // transfer ownership to CAknViewAppUi CleanupStack::Pop(); */ if(RegFileExists()) { DefaultAccessPoint(); ReadUserName(); //DeleteFolderFromDB(*(iEikonEnv->AllocReadResourceL(R_DEFAULT_ALBUM_OTHER))); //CheckAndSaveFolderToDB(*(iEikonEnv->AllocReadResourceL(R_DEFAULT_ALBUM))); iPrevViewId = KViewIdStatusScreen; SetDefaultViewL(*RegView); } else { iPrevViewId = KViewIdUnregisterScreen; SetDefaultViewL(*UnRegView); } iMainScreenValue = 1; #endif // ifdef __UIQ__ iContactsFlag = 0; if(ReadImsiNumber()) { if (AutoStartFileExists() && RegFileExists()) Show=2; else Show=1; } } CRippleVaultAppUi::CRippleVaultAppUi() { //iScheduled = 0; } CRippleVaultAppUi::~CRippleVaultAppUi() { #ifdef __UIQ__ #ifdef __S80__ if (iUnRegisterView) { RemoveFromStack(iUnRegisterView); delete iUnRegisterView; iUnRegisterView = NULL; } /* if (iRegisterView) { RemoveFromStack(iRegisterView); delete iRegisterView; iRegisterView = NULL; } */ if (iStatusScreenView) { RemoveFromStack(iStatusScreenView); delete iStatusScreenView; iStatusScreenView = NULL; } if (iSmsListView) { RemoveFromStack(iSmsListView); delete iSmsListView; iSmsListView = NULL; } if (iPhotoListView) { RemoveFromStack(iPhotoListView); delete iPhotoListView; iPhotoListView = NULL; } if(iProgressBall != NULL) { delete iProgressBall; iProgressBall = NULL; } if (iContactsListView) { RemoveFromStack(iContactsListView); delete iContactsListView; iContactsListView = NULL; } if (iVideoListView) { RemoveFromStack(iVideoListView); delete iVideoListView; iVideoListView = NULL; } if( iPhotosEngine3 != NULL) { delete iPhotosEngine3; iPhotosEngine3=NULL; } if( iPhotosEngine4 != NULL) { delete iPhotosEngine4; iPhotosEngine4=NULL; } if( iVideosEngine3 != NULL) { delete iVideosEngine3; iVideosEngine3=NULL; } if( iVideosEngine4 != NULL) { delete iVideosEngine4; iVideosEngine4=NULL; } #else if( iPhotosEngine3 != NULL) { delete iPhotosEngine3; iPhotosEngine3=NULL; } if( iPhotosEngine4 != NULL) { delete iPhotosEngine4; iPhotosEngine4=NULL; } if( iVideosEngine3 != NULL) { delete iVideosEngine3; iVideosEngine3=NULL; } if( iVideosEngine4 != NULL) { delete iVideosEngine4; iVideosEngine4=NULL; } if (iUnRegisterView) { RemoveFromStack(iUnRegisterView); delete iUnRegisterView; iUnRegisterView = NULL; } /*if (iMainScreenView) { RemoveFromStack(iMainScreenView->ListBox()); RemoveFromStack(iMainScreenView); delete iMainScreenView; iMainScreenView = NULL; }*/ if (iPhotoListView) { RemoveFromStack(iPhotoListView->ListBox()); RemoveFromStack(iPhotoListView); delete iPhotoListView; iPhotoListView = NULL; } if (iVideoListView) { RemoveFromStack(iVideoListView->ListBox()); RemoveFromStack(iVideoListView); delete iVideoListView; iVideoListView = NULL; } if (iSmsListView) { RemoveFromStack(iSmsListView->ListBox()); RemoveFromStack(iSmsListView); delete iSmsListView; iSmsListView = NULL; } if (iStatusScreenView) { RemoveFromStack(iStatusScreenView); delete iStatusScreenView; iStatusScreenView = NULL; } if (iContactsScreenView) { RemoveFromStack(iContactsScreenView); delete iContactsScreenView; iContactsScreenView = NULL; } #endif #endif if( iSocketWriterPublish != NULL) { delete iSocketWriterPublish; iSocketWriterPublish = NULL; } if( iSocketWriterShare != NULL) { delete iSocketWriterShare; iSocketWriterShare = NULL; } if( iSocketWriterSMS != NULL) { delete iSocketWriterSMS; iSocketWriterSMS = NULL; } /*if( iSocketWriterUpgrade != NULL) { delete iSocketWriterUpgrade; iSocketWriterUpgrade = NULL; }*/ if( iPhotosEngine1 != NULL) { delete iPhotosEngine1; iPhotosEngine1=NULL; } if( iPhotosEngine2 != NULL) { delete iPhotosEngine2; iPhotosEngine2=NULL; } if( iPhotosTimer != NULL) { delete iPhotosTimer; iPhotosTimer=NULL; } if( iContactsTimer != NULL) { delete iContactsTimer; iContactsTimer=NULL; } if( iSmsBackupTimer != NULL) { delete iSmsBackupTimer; iSmsBackupTimer=NULL; } if( iWriteSmsAO != NULL) { delete iWriteSmsAO; iWriteSmsAO=NULL; } /*if( iSmsBackupAO != NULL) { delete iSmsBackupAO; iSmsBackupAO=NULL; }*/ if( iVideosEngine1 != NULL) { delete iVideosEngine1; iVideosEngine1=NULL; } if( iVideosEngine2 != NULL) { delete iVideosEngine2; iVideosEngine2=NULL; } if( iPhotosDB != NULL) { delete iPhotosDB; iPhotosDB = NULL; } if(iSmsFile) { delete iSmsFile; } if(iSmsSimEngine != NULL) { iSmsSimEngine->Disconnect(); delete iSmsSimEngine; iSmsSimEngine = NULL; } /* if(iBillingEngine != NULL) { iBillingEngine->Disconnect(); delete iBillingEngine; iBillingEngine = NULL; } */ #ifdef __LOGME__ LogFile.Close(); iLogSession.Close(); #endif } void CRippleVaultAppUi::DynInitMenuPaneL(TInt aResourceId, CEikMenuPane* aMenuPane) { #ifdef __UIQ__ //#ifdef __S80__ //#else //if(aResourceId == R_STATUSSCREEN_MENU) if(aResourceId == R_CASCADE_OTHER_LIST) { /* TBool pending; pending = EFalse; if(((iPendingCountContacts + iPendingCountPhotos + iPendingCountVideos) > 0) && (iStatusCode == NETWORK_STATUS_RUNNING || iStatusCode == NETWORK_STATUS_FAILED)) pending = ETrue; if(!isQueuedInfo) pending = EFalse; */ //aMenuPane->SetItemDimmed(ESendToWeb, !pending); //aMenuPane->SetItemDimmed(EAboutErrorCode, !isError); aMenuPane->SetItemDimmed(EUpgradeClient, !isUpgrade); TBool queued; if(iPhotosDB->PhotosRowCount() == 0 && iPhotosDB->VideosRowCount() == 0) queued = ETrue; else queued = EFalse; aMenuPane->SetItemDimmed(EQueueList, queued ); TBuf<128> path; path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KResumeFile); RFs fs1; fs1.Connect(); if (BaflUtils::FileExists(fs1, path)) //suspended aMenuPane->SetItemTextL(ESuspend, R_TEXT_SUSPEND); else aMenuPane->SetItemTextL(ESuspend, R_TEXT_RESUME); fs1.Close(); //aMenuPane->SetItemDimmed(EShowUploadCount, !isQueuedInfo); //aMenuPane->SetItemDimmed(EClearMediaQueue, !(iPendingCountPhotos+iPendingCountVideos) || !isQueuedInfo); } //#endif #endif } void CRippleVaultAppUi::HandleCommandL(TInt aCommand) { #ifdef __UIQ__ TInt err; CEikDialog* dialog; switch (aCommand) { case EAdvanced: dialog = new (ELeave) CAdvancedDialog(*this); err = dialog->ExecuteLD(R_ADVANCED_DIALOG); if(err!=0) { if(!RegFileExists()) { break; } } break; case EAccessPointSetting: { AccessPointSettings(); } break; case ESharingClient: { MailNames.Copy(_L("")); MailId.Copy(_L("")); albumName.Copy(_L("")); iMessage.Copy(_L("")); iStoragePath = 3; ShowWindow(KViewIdContactsViewScreen); DeleteWindow(KViewIdStatusScreen); } break; case EShareAlbum: { MailNames.Copy(_L("")); MailId.Copy(_L("")); albumName.Copy(_L("")); iMessage.Copy(_L("")); iStoragePath = 2; ShowWindow(KViewIdContactsViewScreen); DeleteWindow(KViewIdStatusScreen); } break; case TBack: case TScreenBack: { //ShowWindow(0); //DeleteWindow(1); //SendToBackground(); CaseMinimize(); } break; case EChangePassword: { dialog = new (ELeave) CChangePassword(*this); err = dialog->ExecuteLD(R_CHANGE_PASSWORD); break; } case TRVHelp: {/* HBufC* myTitle = iEikonEnv->AllocReadResourceLC(R_HELP_DIALOG_TITLE); TBuf<1024> text; text.Copy(*(iEikonEnv->AllocReadResourceL(R_TEXT_HELP_RIPPLE_VAULT))); iEikonEnv->InfoWinL(*myTitle ,text ); CleanupStack::PopAndDestroy(1);*/ #ifdef __S80__ CCknInfoDialog::RunDlgLD(*(iEikonEnv->AllocReadResourceL(R_HELP_DIALOG_TITLE)), *(iEikonEnv->AllocReadResourceL(R_TEXT_HELP_RIPPLE_VAULT))); #else //iEikonEnv CEikDialog* dialog; dialog = new (ELeave) CCustomMessageDialog(*(iEikonEnv->AllocReadResourceL(R_TEXT_HELP_RIPPLE_VAULT)), R_HELP_DIALOG_TITLE); dialog->ExecuteLD(R_EIK_DIALOG_CONTINUE_INFO); #endif } break; case TCBHelp: {/* HBufC* myTitle = iEikonEnv->AllocReadResourceLC(R_HELP_DIALOG_TITLE); TBuf<1024> text; text.Copy(*(iEikonEnv->AllocReadResourceL(R_TEXT_HELP_CONTACTSBACKUP))); iEikonEnv->InfoWinL(*myTitle ,text ); CleanupStack::PopAndDestroy(1);*/ #ifdef __S80__ CCknInfoDialog::RunDlgLD(*(iEikonEnv->AllocReadResourceL(R_HELP_DIALOG_TITLE)), *(iEikonEnv->AllocReadResourceL(R_TEXT_HELP_CONTACTSBACKUP))); #else CEikDialog* dialog; dialog = new (ELeave) CCustomMessageDialog(*(iEikonEnv->AllocReadResourceL(R_TEXT_HELP_CONTACTSBACKUP)), R_HELP_DIALOG_TITLE); dialog->ExecuteLD(R_EIK_DIALOG_CONTINUE_INFO); #endif } break; case TRCHelp: { /*HBufC* myTitle = iEikonEnv->AllocReadResourceLC(R_HELP_DIALOG_TITLE); TBuf<1024> text; text.Copy(*(iEikonEnv->AllocReadResourceL(R_TEXT_HELP_RESTORECONTACTS))); iEikonEnv->InfoWinL(*myTitle ,text ); CleanupStack::PopAndDestroy(1);*/ #ifdef __S80__ CCknInfoDialog::RunDlgLD(*(iEikonEnv->AllocReadResourceL(R_HELP_DIALOG_TITLE)), *(iEikonEnv->AllocReadResourceL(R_TEXT_HELP_RESTORECONTACTS))); #else CEikDialog* dialog; dialog = new (ELeave) CCustomMessageDialog(*(iEikonEnv->AllocReadResourceL(R_TEXT_HELP_RESTORECONTACTS)), R_HELP_DIALOG_TITLE); dialog->ExecuteLD(R_EIK_DIALOG_CONTINUE_INFO); #endif } break; case TPBHelp: { /*HBufC* myTitle = iEikonEnv->AllocReadResourceLC(R_HELP_DIALOG_TITLE); TBuf<1024> text; text.Copy(*(iEikonEnv->AllocReadResourceL(R_TEXT_HELP_PUBLISHBACKUP))); iEikonEnv->InfoWinL(*myTitle ,text ); CleanupStack::PopAndDestroy(1);*/ #ifdef __S80__ CCknInfoDialog::RunDlgLD(*(iEikonEnv->AllocReadResourceL(R_HELP_DIALOG_TITLE)), *(iEikonEnv->AllocReadResourceL(R_TEXT_HELP_PUBLISHBACKUP))); #else CEikDialog* dialog; dialog = new (ELeave) CCustomMessageDialog(*(iEikonEnv->AllocReadResourceL(R_TEXT_HELP_PUBLISHBACKUP)), R_HELP_DIALOG_TITLE); dialog->ExecuteLD(R_EIK_DIALOG_CONTINUE_INFO); #endif } break; case TSMSHelp: { /*HBufC* myTitle = iEikonEnv->AllocReadResourceLC(R_HELP_DIALOG_TITLE); TBuf<1024> text; text.Copy(*(iEikonEnv->AllocReadResourceL(R_TEXT_HELP_SMSBACKUP))); iEikonEnv->InfoWinL(*myTitle ,text ); CleanupStack::PopAndDestroy(1);*/ #ifdef __S80__ CCknInfoDialog::RunDlgLD(*(iEikonEnv->AllocReadResourceL(R_HELP_DIALOG_TITLE)), *(iEikonEnv->AllocReadResourceL(R_TEXT_HELP_SMSBACKUP))); #else CEikDialog* dialog; dialog = new (ELeave) CCustomMessageDialog(*(iEikonEnv->AllocReadResourceL(R_TEXT_HELP_SMSBACKUP)), R_HELP_DIALOG_TITLE); dialog->ExecuteLD(R_EIK_DIALOG_CONTINUE_INFO); #endif } break; case TVPVHelp: { /*HBufC* myTitle = iEikonEnv->AllocReadResourceLC(R_HELP_DIALOG_TITLE); TBuf<1024> text; text.Copy(*(iEikonEnv->AllocReadResourceL(R_TEXT_HELP_VIEWPHOTOSVIDEOS))); iEikonEnv->InfoWinL(*myTitle ,text ); CleanupStack::PopAndDestroy(1);*/ #ifdef __S80__ CCknInfoDialog::RunDlgLD(*(iEikonEnv->AllocReadResourceL(R_HELP_DIALOG_TITLE)), *(iEikonEnv->AllocReadResourceL(R_TEXT_HELP_VIEWPHOTOSVIDEOS))); #else CEikDialog* dialog; dialog = new (ELeave) CCustomMessageDialog(*(iEikonEnv->AllocReadResourceL(R_TEXT_HELP_VIEWPHOTOSVIDEOS)), R_HELP_DIALOG_TITLE); dialog->ExecuteLD(R_EIK_DIALOG_CONTINUE_INFO); #endif } break; /* case ESendToWeb: { if(iPendingCountContacts>0) { UpdateContactsManually(); } if(iPendingCountPhotos>0 || iPendingCountVideos>0) { ScheduleToSend(); } } break; case EAboutErrorCode: { if(isError) { switch(iErrCode) { case NETWORK_ERRCODE_PARSING: ShowMessageBoxFromResource(R_TEXT_NETWORK_ERRCODE_PARSING); break; case NETWORK_ERRCODE_FAILED: ShowMessageBoxFromResource(R_TEXT_NETWORK_ERRCODE_FAILED); break; case NETWORK_ERRCODE_TIMEDOUT: ShowMessageBoxFromResource(R_TEXT_NETWORK_ERRCODE_TIMEDOUT); break; case NETWORK_ERRCODE_MSISDNMISMATCH: ShowMessageBoxFromResource(R_TEXT_NETWORK_ERRCODE_MSISDNMISMATCH); break; case NETWORK_ERRCODE_IMEIMISMATCH: ShowMessageBoxFromResource(R_TEXT_NETWORK_ERRCODE_IMEIMISMATCH); break; case NETWORK_ERRCODE_ACCSUSPENDED: ShowMessageBoxFromResource(R_TEXT_NETWORK_ERRCODE_ACCSUSPENDED); break; default: break; } } } break; case EHelp: { ShowMessageBoxFromResource(R_STATUSTEXT_HELP); } break; case EShowUploadCount: { TBuf<250> uploadcount; TBuf<50> message; TBuf<50> formatBuf; TInt album; TInt photos; TInt videos; TInt albumshares; //TInt photoshares; //TInt videoshares; TInt ccount; TInt smscount; GetUploadSettingsFromDB(album, photos, videos, albumshares); GetContactsUploadSettingsFromDB(ccount); GetSmsUploadSettingsFromDB(smscount); message.Copy(_L("")); formatBuf.Copy(_L("")); formatBuf.Append(*(iEikonEnv->AllocReadResourceL(R_STATUSTEXT_CONTACTS_UPLOADED))); message.Format(formatBuf, ccount); uploadcount.Append(message); uploadcount.Append(_L("\n")); message.Copy(_L("")); formatBuf.Copy(_L("")); formatBuf.Append(*(iEikonEnv->AllocReadResourceL(R_STATUSTEXT_SMS_UPLOADED))); message.Format(formatBuf, smscount); uploadcount.Append(message); uploadcount.Append(_L("\n")); message.Copy(_L("")); formatBuf.Copy(_L("")); formatBuf.Append(*(iEikonEnv->AllocReadResourceL(R_STATUSTEXT_ALBUMS))); message.Format(formatBuf, album, albumshares); uploadcount.Append(message); uploadcount.Append(_L("\n")); message.Copy(_L("")); formatBuf.Copy(_L("")); formatBuf.Append(*(iEikonEnv->AllocReadResourceL(R_STATUSTEXT_PHOTOS_UPLOADED))); message.Format(formatBuf, photos); uploadcount.Append(message); uploadcount.Append(_L("\n")); message.Copy(_L("")); formatBuf.Copy(_L("")); formatBuf.Append(*(iEikonEnv->AllocReadResourceL(R_STATUSTEXT_VIDEOS_UPLOADED))); message.Format(formatBuf, videos); uploadcount.Append(message); //uploadcount.Append(_L("\n")); //CEikonEnv::Static()->InfoWinL(*(iEikonEnv->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH)),uploadcount); CEikDialog* dialog; dialog = new (ELeave) CCustomMessageDialog(uploadcount, R_EXAMPLE_RIPPLE_PUBLISH); dialog->ExecuteLD(R_EIK_DIALOG_CONTINUE_INFO); } break;*/ case EUpgradeClient: { CopyUpgradeFile(); } break; case EClearMediaQueue: { ClearMediaQueue(); } break; #ifdef __S80__ case EEikCmdExit: case TStop: //Exit(); User::Exit(EEikCmdExit); //PromptForSecureExit(); break; //iImageFlag = 1; //ShowSettingsDialog(); //ShowWindow(1); //break; case ERegister: AutoRegisterRipple(); //ShowRegisterDialog(); //break; break; /*case EMainScreenOpen: { ActivateWindow(); } break; */ case ESmsScreenBack: { ShowWindow(KViewIdStatusScreen); DeleteWindow(KViewIdSmsList); SaveChoice(1); } break; case EPhotoScreenBack: { /*TInt8 choice=0; GetChoice(choice); */ if(iPhotoListView != NULL) {/* if(choice == 0) { ShowWindow(KViewIdVideoList); DeleteWindow(KViewIdPhotoList); } else {*/ ShowWindow(KViewIdStatusScreen); DeleteWindow(KViewIdPhotoList); //} } else if(iVideoListView != NULL) { ShowWindow(KViewIdStatusScreen); DeleteWindow(KViewIdVideoList); //if(choice == 0) //{ // CallSetupWizardStep12(); //} } } break; case EPhotoSelect: { if(iPhotoListView != NULL) iPhotoListView->MarkUnMarkSelectedItem(); else if(iVideoListView != NULL) iVideoListView->MarkUnMarkSelectedItem(); } break; case EPhotoSelectAll: { if(iPhotoListView != NULL) iPhotoListView->MarkAllItems(); else if(iVideoListView != NULL) iVideoListView->MarkAllItems(); } break; case EPhotoUnSelectAll: { if(iPhotoListView != NULL) iPhotoListView->UnMarkAllItems(); else if(iVideoListView != NULL) iVideoListView->UnMarkAllItems(); } break; case EPhotoSelectFolder: { if(iPhotoListView != NULL) iPhotoListView->SelectFolder(); else if(iVideoListView != NULL) iVideoListView->SelectFolder(); } break; case ESmsSelect: { if(iSmsListView != NULL) iSmsListView->MarkUnMarkSelectedItem(); } break; case ESmsSelectAll: { if(iSmsListView != NULL) iSmsListView->MarkAllItems(); } break; case ESmsUnSelectAll: { if(iSmsListView != NULL) iSmsListView->UnMarkAllItems(); } break; case ESendSel: { if(iSmsListView != NULL) iSmsListView->SendSelected(); else if(iPhotoListView != NULL) { TInt PhotoSendMode; PhotoSendMode = iPhotoListView->IsImageSelected(); if(PhotoSendMode == 1) { iPhotoListView->SendPhotoToServer(); } else { ShowMessageBoxFromResource(R_EXAMPLE_TEXT_NOTSEL); } } else if(iVideoListView != NULL) { TInt PhotoSendMode; PhotoSendMode = iVideoListView->IsImageSelected(); if(PhotoSendMode == 1) { iVideoListView->SendVideoToServer(); } else { ShowMessageBoxFromResource(R_EXAMPLE_TEXT_NOTSEL1); } } } break; case EContactsAdd: { if(iContactsListView != NULL) iContactsListView->AddContacts(); } break; case EContactsDel: { if(iContactsListView != NULL) iContactsListView->DeleteContacts(); } break; case EContactsBack: { ShowWindow(KViewIdStatusScreen); DeleteWindow(KViewIdContactsViewScreen); } break; case EContactsSend: { if(iContactsListView != NULL) iContactsListView->ShareContacts(); } break; //// NEW UI case EBackupPhoneBook: { UpdateContactsManually(); } break; case EBackupPhotos: { ShowWindow(KViewIdPhotoList); DeleteWindow(KViewIdStatusScreen); //main screen } break; case EBackupVideos: { ShowWindow(KViewIdVideoList); DeleteWindow(KViewIdStatusScreen); //main screen } break; case EBackupSMS: { if(PendingSMS()) { ShowMessageBoxFromResource(R_SMS_SENDTOWEB_BUSY); } else{ //manually sms backup ShowWindow(KViewIdSmsList); DeleteWindow(KViewIdStatusScreen); //main screen } } break; case ESettingsPhoneBook: { dialog = new (ELeave) CContactsSettingDialog(*this); err = dialog->ExecuteLD(R_CONTACTS_SETTINGS); if(err) { if(iSettingsScreenValue == 1) { dialog = new (ELeave) CContactsUploadSettingDialog(*this); err = dialog->ExecuteLD(R_CONTACTS_UPLOAD_SETTINGS); } } } break; case ESettingsPhotos: { dialog = new (ELeave) CPhotosSettingDialog(*this); err = dialog->ExecuteLD(R_PHOTOS_SETTINGS); } break; case ESettingsSMS: { dialog = new (ELeave) CSmsSettingDialog(*this); err = dialog->ExecuteLD(R_SMS_SETTINGS); if(err) if(iSmsMode == 0) { MailNames.Copy(_L("")); MailId.Copy(_L("")); albumName.Copy(_L("")); iMessage.Copy(_L("")); iStoragePath = 1; ShowWindow(KViewIdContactsViewScreen); DeleteWindow(KViewIdStatusScreen); } } break; case ESettingsAntitheft: { //iPhotosAppUi->iSettingsScreenValue = 4; //iPhotosAppUi->ActivateView(KViewIdSettingsScreen); ShowMessageBoxFromResource(R_ANTITHEFT_INTEREST); } break; case ESettingsGeneral: { dialog = new (ELeave) CAdvancedDialog(*this); err = dialog->ExecuteLD(R_ADVANCED_DIALOG); if(err!=0) { if(!RegFileExists()) { break; } } break; } case ESuspend: { CaseSuspend(); } break; #else case EEikCmdExit: User::Exit(EEikCmdExit); //PromptForSecureExit(); //Exit(); break; case EPhotoSelId: { if(iImageFlag == 1) { iImageFlag = 2; iPhotoListView->ResetData(); CQikAppUi* appUi = STATIC_CAST(CQikAppUi*, iEikonEnv->AppUi()); appUi->SetToolbarL(R_PHOTOLIST_TOOLBAR_MEMORY); TInt err; err = iPhotoListView->Start(KDirMMCPhoto); if(err == -1) ShowMessageBoxFromResource(R_WEBUPLOAD_NOPHOTOIMAGE); } else if(iImageFlag == 2) { iImageFlag = 1; iPhotoListView->ResetData(); CQikAppUi* appUi = STATIC_CAST(CQikAppUi*, iEikonEnv->AppUi()); appUi->SetToolbarL(R_PHOTOLIST_TOOLBAR_PHONE); TInt err; err = iPhotoListView->Start(KDirPhonePhoto); if(err == -1) ShowMessageBoxFromResource(R_WEBUPLOAD_NOPHOTOIMAGE); } else if(iImageFlag == 3) { iImageFlag = 4; iVideoListView->ResetData(); CQikAppUi* appUi = STATIC_CAST(CQikAppUi*, iEikonEnv->AppUi()); appUi->SetToolbarL(R_PHOTOLIST_TOOLBAR_MEMORY); TInt err; err = iVideoListView->Start(KDirMMCVideo); if(err == -1) ShowMessageBoxFromResource(R_WEBUPLOAD_NOVIDEOIMAGE); } else if(iImageFlag == 4) { iImageFlag = 3; iVideoListView->ResetData(); CQikAppUi* appUi = STATIC_CAST(CQikAppUi*, iEikonEnv->AppUi()); appUi->SetToolbarL(R_PHOTOLIST_TOOLBAR_PHONE); TInt err; err = iVideoListView->Start(KDirPhoneVideo); if(err == -1) ShowMessageBoxFromResource(R_WEBUPLOAD_NOVIDEOIMAGE); } } break; case ESmsSelId: { if(iImageFlag == 5) { iImageFlag = 6; CQikAppUi* appUi = STATIC_CAST(CQikAppUi*, iEikonEnv->AppUi()); appUi->SetToolbarL(R_SMSLIST_TOOLBAR_MEMORY); iSmsListView->ChangeScreen(); iSmsListView->ResetData(); /*if(iSmsListView->iSentItemsFlag == EFalse) { iSmsListView->iSentItemsFlag = ETrue; iSmsListView->Start(1); } else { iSmsListView->ResetData(); }*/ } else if(iImageFlag == 6) { iImageFlag = 5; CQikAppUi* appUi = STATIC_CAST(CQikAppUi*, iEikonEnv->AppUi()); appUi->SetToolbarL(R_SMSLIST_TOOLBAR_PHONE); iSmsListView->ChangeScreen(); iSmsListView->ResetData(); /*if(iSmsListView->iInboxItemsFlag == EFalse) { iSmsListView->iInboxItemsFlag = ETrue; iSmsListView->Start(0); } else { iSmsListView->ResetData(); }*/ } } break; case TListBack: { TInt val = 0; if(iImageFlag == 1 || iImageFlag == 2) { val = iPhotoListView->IsImageSelected(); } else if(iImageFlag == 3 || iImageFlag == 4) { val = iVideoListView->IsImageSelected(); } else if(iImageFlag == 5 || iImageFlag == 6) { val = iSmsListView->IsSmsSelected(); } if (val == 1) { if(CEikonEnv::Static()->QueryWinL(*(iEikonEnv->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH)),*(iEikonEnv->AllocReadResourceL(R_TEXT_CANCEL_BACKUP)))) ShowView(); } else ShowView(); } break; case EMarkSel: { if(iImageFlag == 1 || iImageFlag == 2) iPhotoListView->MarkUnMarkSelectedItem(); else if(iImageFlag == 3 || iImageFlag == 4) iVideoListView->MarkUnMarkSelectedItem(); else if(iImageFlag == 5 || iImageFlag == 6) iSmsListView->MarkUnMarkSelectedItem(); } break; case EMarkAll: { if(iImageFlag == 1 || iImageFlag == 2) iPhotoListView->MarkAllItems(); else if(iImageFlag == 3 || iImageFlag == 4) iVideoListView->MarkAllItems(); else if(iImageFlag == 5 || iImageFlag == 6) iSmsListView->MarkAllItems(); } break; case EUnMarkAll: { if(iImageFlag == 1 || iImageFlag == 2) iPhotoListView->UnMarkAllItems(); else if(iImageFlag == 3 || iImageFlag == 4) iVideoListView->UnMarkAllItems(); else if(iImageFlag == 5 || iImageFlag == 6) iSmsListView->UnMarkAllItems(); } break; case ESendSel: { TInt PhotoSendMode; if(iImageFlag == 1 || iImageFlag == 2) { if(iPhotoListView->GetCount() == 0) iPhotoListView->MarkSelectedPhoto(); PhotoSendMode = iPhotoListView->IsImageSelected(); if(PhotoSendMode == 1) { TBuf<150> msg; TInt count = iPhotoListView->GetCount(); msg.Copy(_L("")); msg.AppendNum(count); if(iImageFlag == 1 || iImageFlag == 2) msg.Append(*(iEikonEnv->AllocReadResourceL(R_IMAGES_CONFIRM_PHOTOS))); else if(iImageFlag == 3 || iImageFlag == 4) msg.Append(*(iEikonEnv->AllocReadResourceL(R_IMAGES_CONFIRM_VIDEOS))); msg.Append(*(iEikonEnv->AllocReadResourceL(R_IMAGES_CONFIRM))); if(CEikonEnv::Static()->QueryWinL(*(iEikonEnv->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH)),msg)) iPhotoListView->SendPhotoToServer(); } else { ShowMessageBoxFromResource(R_EXAMPLE_TEXT_NOTSEL); } } else if(iImageFlag == 3 || iImageFlag == 4) { if(iVideoListView->GetCount() == 0) iVideoListView->MarkSelectedVideo(); PhotoSendMode = iVideoListView->IsImageSelected(); if(PhotoSendMode == 1) { TBuf<150> msg; TInt count = iVideoListView->GetCount(); msg.Copy(_L("")); msg.AppendNum(count); if(iImageFlag == 1 || iImageFlag == 2) msg.Append(*(iEikonEnv->AllocReadResourceL(R_IMAGES_CONFIRM_PHOTOS))); else if(iImageFlag == 3 || iImageFlag == 4) msg.Append(*(iEikonEnv->AllocReadResourceL(R_IMAGES_CONFIRM_VIDEOS))); msg.Append(*(iEikonEnv->AllocReadResourceL(R_IMAGES_CONFIRM))); if(CEikonEnv::Static()->QueryWinL(*(iEikonEnv->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH)),msg)) iVideoListView->SendVideoToServer(); } else { ShowMessageBoxFromResource(R_EXAMPLE_TEXT_NOTSEL1); } } else if(iImageFlag == 5 || iImageFlag == 6) { if(iSmsListView->GetCount() == 0) iSmsListView->MarkSelectedSms(); PhotoSendMode = iSmsListView->IsSmsSelected(); if(PhotoSendMode == 1) { TBuf<150> msg; TInt count = iSmsListView->GetCount(); msg.Copy(_L("")); msg.AppendNum(count); msg.Append(*(iEikonEnv->AllocReadResourceL(R_SMS_CONFIRM))); msg.Append(*(iEikonEnv->AllocReadResourceL(R_IMAGES_CONFIRM))); if(CEikonEnv::Static()->QueryWinL(*(iEikonEnv->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH)),msg)) iSmsListView->SendSmsToServer(); } else { ShowMessageBoxFromResource(R_TEXT_SELECT_MESSAGE_FIRST); } } break; } break; /*case TScreenBack: { if(iMainScreenValue == 1 || iMainScreenValue == 2 || iMainScreenValue == 3 || iMainScreenValue == 4 || iMainScreenValue == 5) { iMainScreenValue = 0; iMainScreenView->UpdateListBoxL(iMainScreenValue); CQikAppUi* appUi = STATIC_CAST(CQikAppUi*, iEikonEnv->AppUi()); appUi->SetToolbarL(R_REGISTER_TOOLBAR); } else if(iMainScreenValue == 6) { iMainScreenValue = 0; ShowWindow(KViewIdRegisterScreen); //main screen DeleteWindow(KViewIdStatusScreen); //status screen } } break; */ case TRegister: dialog = new (ELeave) CRegisterDialog(*this); err = dialog->ExecuteLD(R_REGISTER_DIALOG); if(err!=0) { } break; case TAlreadyRegister: { AutoRegisterRipple(); //AlbumSynchingComplete(); } break; case EViewAlbum: OpenBrowser(); break; /* case EChangePlan: { ChangePlan(); } break;*/ case ESharing: if(iContactsScreenView != NULL) { TInt err; if(iStoragePath == 4) { err = iContactsScreenView->AddNewDatatoDB(); if(err == 1) { iStoragePath = 1; CQikAppUi* appUi = STATIC_CAST(CQikAppUi*, iEikonEnv->AppUi()); appUi->SetToolbarL(R_SELECTIVECONTACTSLIST_TOOLBAR); iContactsScreenView->ResetData(); } } else { if(iStoragePath == 1) { if(iContactsScreenView->GetStoredContactsCount() == 0) { iEikonEnv->InfoMsg(*(iEikonEnv->AllocReadResourceL(R_SELECT_RECEPIENT))); } else { //TInt8 choice=0; //GetChoice(choice); /*if(choice == 0) { err = 0; ShowWindow(KViewIdRegisterScreen); DeleteWindow(KViewIdContactsViewScreen); CallSetupWizardStep17(); } else{*/ err = 1; ShowWindow(KViewIdStatusScreen); DeleteWindow(KViewIdContactsViewScreen); //} } } else err = iContactsScreenView->SendSharingXml(); /* if(err == 1) { ShowWindow(1); DeleteWindow(6); }*/ } } break; case ECancel: if(iContactsScreenView != NULL) { if(iStoragePath == 1) { iSmsMode = 1; SaveSmsSettingsToDB(iSmsMode,iSmsTime,iSmsRoam); /*TInt8 choice=0; GetChoice(choice); if(choice == 0) { err = 0; ShowWindow(KViewIdRegisterScreen); DeleteWindow(KViewIdContactsViewScreen); CallSetupWizardStep17(); } else{*/ err = 1; ShowWindow(KViewIdStatusScreen); DeleteWindow(KViewIdContactsViewScreen); //} } else if(iStoragePath == 4) { iStoragePath = 1; iContactsScreenView->ResetData(); CQikAppUi* appUi = STATIC_CAST(CQikAppUi*, iEikonEnv->AppUi()); appUi->SetToolbarL(R_SELECTIVECONTACTSLIST_TOOLBAR); } else { ShowWindow(KViewIdStatusScreen); DeleteWindow(KViewIdContactsViewScreen); } } break; case ESelectAdd: if(iContactsScreenView != NULL) { iStoragePath = 4; iContactsScreenView->AddContacts(); CQikAppUi* appUi = STATIC_CAST(CQikAppUi*, iEikonEnv->AppUi()); appUi->SetToolbarL(R_CONTACTSLIST_TOOLBAR); } break; case ESelectDelete: if(iContactsScreenView != NULL) { iContactsScreenView->DeleteContacts(); } break; case TStop: //User::Exit(EEikCmdExit); #ifdef __S80__ User::Exit(EEikCmdExit); #else PromptForSecureExit(); #endif break; //// NEW UI case EBackupPhoneBook: { UpdateContactsManually(); } break; case EBackupPhotos: { iImageFlag = 1; ShowWindow(KViewIdPhotoList); //photo screen DeleteWindow(KViewIdStatusScreen); //main screen } break; case EBackupVideos: { iImageFlag = 3; ShowWindow(KViewIdVideoList); //video screen DeleteWindow(KViewIdStatusScreen); //main screen } break; case EBackupSMS: { if(PendingSMS()) { ShowMessageBoxFromResource(R_SMS_SENDTOWEB_BUSY); } else{ //manually sms backup iImageFlag = 5; ShowWindow(KViewIdSmsList); //sms screen DeleteWindow(KViewIdStatusScreen); //main screen } } break; case ESettingsPhoneBook: { dialog = new (ELeave) CContactsSettingDialog(*this); err = dialog->ExecuteLD(R_CONTACTS_SETTINGS); if(err) { if(iSettingsScreenValue == 1) { dialog = new (ELeave) CContactsUploadSettingDialog(*this); err = dialog->ExecuteLD(R_CONTACTS_UPLOAD_SETTINGS); } } } break; case ESettingsPhotos: { dialog = new (ELeave) CPhotosSettingDialog(*this); err = dialog->ExecuteLD(R_PHOTOS_SETTINGS); } break; case ESettingsSMS: { dialog = new (ELeave) CSmsSettingDialog(*this); err = dialog->ExecuteLD(R_SMS_SETTINGS); if(err) if(iSmsMode == 0) { MailNames.Copy(_L("")); MailId.Copy(_L("")); albumName.Copy(_L("")); iMessage.Copy(_L("")); iStoragePath = 1; ShowWindow(KViewIdContactsViewScreen); DeleteWindow(KViewIdStatusScreen); } } break; case ESettingsAntitheft: { //iPhotosAppUi->iSettingsScreenValue = 4; //iPhotosAppUi->ActivateView(KViewIdSettingsScreen); ShowMessageBoxFromResource(R_ANTITHEFT_INTEREST); } break; case ESettingsGeneral: { dialog = new (ELeave) CAdvancedDialog(*this); err = dialog->ExecuteLD(R_ADVANCED_DIALOG); if(err!=0) { if(!RegFileExists()) { break; } } break; } case ESuspend: { CaseSuspend(); } break; #endif default: break; } #else // Series 60 code switch(aCommand) { case EEikCmdExit: #ifdef __LOGME__ LogText.Copy(_L("EEikCmdExit")); WriteLogFile(LogText); #endif #ifndef __NOKIA_SYM8__ User::Exit(EEikCmdExit); #endif //Exit(); break; case EExit: case EAknSoftkeyExit://Personal Photo //Exit(); PromptForSecureExit(); break; case ESettings: iRipplePhotos = 2; iSettingsScreenValue = 0; iPrevViewId = KViewIdSettingsScreen; ActivateLocalViewL(KViewIdSettingsScreen); break; case EUnRegHide: SendToBackground(); break; case EHide: iRipplePhotos = 2; //iPrevViewId = KViewIdEmptyScreen; ActivateLocalViewL(KViewIdEmptyScreen); SendToBackground(); break; case ERegView: iPrevViewId = KViewIdStatusScreen; ActivateLocalViewL(KViewIdStatusScreen); break; case EUnRegView: iPrevViewId = KViewIdUnregisterScreen ; ActivateLocalViewL(KViewIdUnregisterScreen); break; // case ERecommend: // //ActivateLocalViewL(TUid::Uid(6)); // break; case EFindView: iPrevViewId = KViewIdFindBox; ActivateLocalViewL(KViewIdFindBox); break; case Esmsbackup: iPrevViewId = KViewIdSmsList; ActivateLocalViewL(KViewIdSmsList); break; // case EMailView: // ActivateLocalViewL(TUid::Uid(8)); // break; case EMainView: iPrevViewId = KViewIdStatusScreen; ActivateLocalViewL(KViewIdStatusScreen); break; case EMainSubView: iPrevViewId = KViewIdStatusScreen; ActivateLocalViewL(KViewIdStatusScreen); break; case EHelp: iPrevViewId = KViewIdHelp; ActivateLocalViewL(KViewIdHelp); break; /* case EAbout: { TBuf<80> msg; msg.Copy(_L("Version ")); msg.Append(iVersion); CAknMessageQueryDialog* abtdlg = CAknMessageQueryDialog::NewL(msg); abtdlg->PrepareLC(R_ABOUT_QUERY); if (abtdlg->RunLD()) { } break; } case EChangePlan: { ChangePlan(); } break;*/ // case EUpgrade: // { // if(IsNetworkInProgress()) // CEikonEnv::Static ()->AlertWin(_L("Network Busy")); // else // CheckUpgrade(); // } // break; default: break; } #endif } void CRippleVaultAppUi::BringToForeground() { #ifdef __LOGME__ LogText.Copy(_L("\nBringToForeground\n")); WriteLogFile(LogText); #endif Show=0; #ifdef __UIQ__ // TUid id = { 3 }; // ActivateViewL(iAppEmptyView->ViewId()); // CQikAppUi* appUi = STATIC_CAST(CQikAppUi*, iEikonEnv->AppUi()); // appUi->SetToolbarL(R_EXAMPLE_TOOLBAR1); // iAppView1->MakeVisible(EFalse); // Construct en empty TApaTask object // giving it a reference to the Window Server session TApaTask task(iEikonEnv->WsSession( )); // Initialise the object with the window group id of // our application (so that it represent our app) task.SetWgId(CEikonEnv::Static()->RootWin().Identifier()); // Request window server to bring our application // to foreground task.BringToForeground(); #else HideView(); ActivateLocalViewL(KViewIdEmptyScreen); TApaTask task(iEikonEnv->WsSession( )); // Initialise the object with the window group id of // our application (so that it represent our app) task.SetWgId(CEikonEnv::Static()->RootWin().Identifier()); // Request window server to bring our application // to foreground task.BringToForeground(); #endif } void CRippleVaultAppUi::SendToBackground() { #ifdef __LOGME__ LogText.Copy(_L("\nSendToBackground\n")); WriteLogFile(LogText); #endif Show=1; #ifndef __UIQ__ CEikStatusPane* statusPane=iEikonEnv->AppUiFactory()->StatusPane(); statusPane->SwitchLayoutL(R_AVKON_STATUS_PANE_LAYOUT_EMPTY); #else //TUid id = { 3 }; //ActivateViewL(iAppView1->ViewId()); #endif // Construct en empty TApaTask object // giving it a reference to the Window Server session TApaTask task(iEikonEnv->WsSession( )); // Initialise the object with the window group id of // our application (so that it represent our app) task.SetWgId(CEikonEnv::Static()->RootWin().Identifier()); task.SendToBackground(); } TBool CRippleVaultAppUi::AutoStartFileExists() { RFs Autofs; TBool ret; Autofs.Connect(); TBuf<128> path; path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KAutoStartFile); if (BaflUtils::FileExists(Autofs, path)) { BaflUtils::DeleteFile(Autofs, path); ret = TRUE; } else ret = FALSE; Autofs.Close(); return ret; } void CRippleVaultAppUi::HandleForegroundEventL(TBool aForeground) { #ifndef __UIQ__ CAknAppUi::HandleForegroundEventL(aForeground); if(aForeground) { if(Show==1) { CEikStatusPane* statusPane=iEikonEnv->AppUiFactory()->StatusPane(); statusPane->SwitchLayoutL(R_AVKON_STATUS_PANE_LAYOUT_USUAL); if(RegFileExists()) { iRipplePhotos = 0; //ActivateLocalViewL(TUid::Uid(2)); //ActivateLocalViewL(TUid::Uid(4)); //ActivateLocalViewL(TUid::Uid(15)); //ActivateLocalViewL(KViewIdEmptyScreen); TInt8 choice=0; GetChoice(choice); if(/*(iPrevViewId == KViewIdMainScreen || iPrevViewId == KViewIdSubScreen) &&*/ CheckIfPending() && choice == 1) ActivateLocalViewL(KViewIdStatusScreen); else ActivateLocalViewL(iPrevViewId); } else{ iPrevViewId = KViewIdUnregisterScreen; ActivateLocalViewL(KViewIdUnregisterScreen); } } else if(Show==2) { ActivateLocalViewL(TUid::Uid(2)); SendToBackground(); } else if(Show==0) { //HideView(); //ActivateLocalViewL(KViewIdEmptyScreen); //HideView(); } } #else /*if(aForeground) { TInt val = ReturnScreenValue(); if((val == KViewIdRegisterScreen) && CheckIfPending()) { //CEikonEnv::Static ()->AlertWin(_L("1")); iMainScreenValue = 6; ShowWindow(KViewIdStatusScreen); //status screen DeleteWindow(val); ShowStatusScreen(); } }*/ #endif } CDesCArray* CRippleVaultAppUi::ReturnText() { CDesCArray* textArray = iCoeEnv->ReadDesCArrayResourceL(R_AKNEXQUERY_SUB_POPUP_FOLDER); return textArray; } CDesCArray* CRippleVaultAppUi::ReturnTextForImage() { CDesCArray* textArray = iCoeEnv->ReadDesCArrayResourceL(R_SUB_POPUP_FOLDER); return textArray; } CDesCArray* CRippleVaultAppUi::FolderExist() { CDesCArray* textArray = iCoeEnv->ReadDesCArrayResourceL(R_AKNEXQUERY_FOLDER_EXIST); return textArray; } void CRippleVaultAppUi::AddPhotoRecord(TDesC& aFilename, TInt8 aPublic, TDesC& aComment, TDesC& aDesc, TInt8 aNew, TInt aFileSize) { #ifdef __LOGME__ LogText.Copy(_L("filename=")); LogText.Append(aFilename); LogText.Append(_L("\n")); WriteLogFile(LogText); #endif if(!iPhotosDB->CheckIfPhotoExists(aFilename)) { #ifdef __LOGME__ LogText.Copy(_L("filesize=")); LogText.AppendNum(aFileSize); LogText.Append(_L("\n")); WriteLogFile(LogText); #endif // public/private type to be passed TInt num_packets; if (aFileSize % (PUBLISH_PACKET_SIZE*1024) == 0) num_packets = aFileSize/(PUBLISH_PACKET_SIZE*1024); else num_packets = (aFileSize/(PUBLISH_PACKET_SIZE*1024)) + 1; TBuf<1024> status; status.Copy(_L("")); for(TInt i=0; i< num_packets && i<1024;++i) { status.Append(_L("0")); } iPhotosDB->AddRecord(aFilename, aPublic, aComment, aDesc, KPhoto, aNew, status); } } void CRippleVaultAppUi::AddVideoRecord(TDesC& aFilename, TInt8 aPublic, TDesC& aComment, TDesC& aDesc, TInt8 aNew, TInt aFileSize) { if(!iPhotosDB->CheckIfPhotoExists(aFilename)) { #ifdef __LOGME__ LogText.Copy(_L("filename=")); LogText.Append(aFilename); LogText.Append(_L("\n")); WriteLogFile(LogText); #endif // public/private type to be passed TInt num_packets; if (aFileSize % (PUBLISH_PACKET_SIZE*1024) == 0) num_packets = aFileSize/(PUBLISH_PACKET_SIZE*1024); else num_packets = (aFileSize/(PUBLISH_PACKET_SIZE*1024)) + 1; TBuf<1024> status; status.Copy(_L("")); for(TInt i=0; i< num_packets && i<1024;++i) { status.Append(_L("0")); } iPhotosDB->AddRecord(aFilename, aPublic, aComment, aDesc, KVideo, aNew, status); } } void CRippleVaultAppUi::SendToServer() { #ifdef __LOGME__ LogText.Copy(_L("SendToServer 1\n")); WriteLogFile(LogText); #endif if(iSocketWriterPublish == NULL) { iSocketWriterPublish = CSocketsEngineWriter::NewL(*this); iSocketWriterPublish->SetServerName(iServerAddr); iSocketWriterPublish->SetPort(iPort); iSocketWriterPublish->ConnectToServer(); #ifdef __LOGME__ LogText.Copy(_L("SendToServer 2\n")); WriteLogFile(LogText); #endif } } void CRippleVaultAppUi::ScheduleToSend() { #ifdef __LOGME__ LogText.Copy(_L("ScheduleToSend 1\n")); WriteLogFile(LogText); #endif TInt network; network = CheckNetwork(); if(network == NETWORK_ROAMING) { if(iRoaming == DISABLED) { RoamingDisabledDialogPublish(); return; } } if( iPhotosTimer == NULL) { iPhotosTimer = CPhotosTimer::NewL(*this); iPhotosTimer->Start(); } if (iSocketWriterPublishStatus!=NULL || iSocketWriterPublish!=NULL)//iScheduled) { return; } // Initialize send //iScheduled = 1; // get the photo/video entry from the file. // start sending once connected //SendToServer(); #ifdef __LOGME__ LogText.Copy(_L("ScheduleToSend 2\n")); WriteLogFile(LogText); #endif if(iPhotosDB->RowCount() > 0) { iConnectionStatus = 1; CheckSubscriptionStatus(iConnectionStatus); } } void CRippleVaultAppUi::MoreFilesToUpload() { TInt count; count = iPhotosDB->RowCount(); #ifdef __LOGME__ LogText.Copy(_L("MoreFilesToUpload 1\n")); WriteLogFile(LogText); #endif while(count > 0) { TInt8 type; TInt8 photo; TInt8 isNew; TBuf<128> afileName; TBuf<128> folderName; TBuf<128> descName; TBuf<1024> status; #ifdef __LOGME__ LogText.Copy(_L("MoreFilesToUpload 2\n")); WriteLogFile(LogText); #endif TInt err; err = iPhotosDB->GetRecord(afileName, type, folderName, descName, photo, isNew, status); #ifdef __LOGME__ LogText.Copy(_L("MFTU FileName=")); LogText.Append(afileName); LogText.Append(_L("\n")); WriteLogFile(LogText); #endif if(err == 0) { if(CheckMediaExists(afileName)) { #ifdef __LOGME__ LogText.Copy(_L("Media Exists\n")); WriteLogFile(LogText); #endif count = -1; } else { #ifdef __LOGME__ LogText.Copy(_L("Media Not Exists\n")); WriteLogFile(LogText); #endif iPhotosDB->DeleteNonExistantRecord(); count = iPhotosDB->RowCount(); } #ifdef __LOGME__ LogText.Copy(_L("Media Checked\n")); WriteLogFile(LogText); #endif } else { #ifdef __LOGME__ LogText.Copy(_L("File not Opened\n")); WriteLogFile(LogText); #endif count = 0; } #ifdef __LOGME__ LogText.Copy(_L("MoreFilesToUpload 3\n")); WriteLogFile(LogText); #endif } if(iSocketWriterPublish != NULL) { iSocketWriterPublish->Disconnect(); delete iSocketWriterPublish; iSocketWriterPublish = NULL; } #ifdef __LOGME__ LogText.Copy(_L("MoreFilesToUpload 4\n")); WriteLogFile(LogText); #endif if(count == -1) { SendToServer(); } else { CloseConnection(); //GetAlbumSynchingXML(); } } TInt CRippleVaultAppUi::CheckMediaExists(TDesC& aFilename) { RFs file; file.Connect(); if(BaflUtils::FileExists(file,aFilename)) { #ifdef __LOGME__ LogText.Copy(_L("CheckMediaExists 1\n")); WriteLogFile(LogText); #endif file.Close(); return 1; } else { #ifdef __LOGME__ LogText.Copy(_L("CheckMediaExists 2\n")); WriteLogFile(LogText); #endif file.Close(); return 0; } } // iSocketWriter will call this first time when protocol header is // sent completely. Calls with buffer and length. Sends the buffer // Once send is complete, calls this function again. // When this function returns 0, it means end of image/video file. // Call next - GetProtocolEndDataXML, send it. TInt CRippleVaultAppUi::GetMoreDataFromFile(TDes8& aData, TInt aMaxLen) { //if (iFileDes. // read data from filedesc into aData // return the length of data read TInt pos = 0; iFileDes.Seek(ESeekCurrent,pos); //LogText.Copy(_L("\n\nbefore reading pos=")); //LogText.AppendNum(pos); //LogText.Append(_L("\n\n")); //WriteLogFile(LogText); TInt ret = iFileDes.Read(aData, aMaxLen); if(ret != KErrNone || ret == KErrOverflow || ret == KErrGeneral) { return 0; } if (ret == 0) { return aData.Length(); } return 0; } void CRippleVaultAppUi::SendBillingSMS() { //From: MSISDN //To: short code //I=Subscription keyword (will be an 8 digit number) B (billing type)=MO T (type)=S (subscribe) IMSI=666666 // Billing Short Code: "billing_short_code=" // Billing Subscription Keyword: "billing_sub_keyword=" // Billing Type: "billing_bill_type=" /// Billing Registration Type: "billing_reg_type=" TBuf<30> ShortCode; TBuf<30> SubscriptionKeyword; TBuf<30> BillingType; TBuf<30> BillingRegType; ShortCode.Copy(_L("")); SubscriptionKeyword.Copy(_L("")); BillingType.Copy(_L("")); BillingRegType.Copy(_L("")); TBuf<60> tmpstr; tmpstr.Copy(_L("billing_short_code")); LoadFromConfigFile(ShortCode, tmpstr); tmpstr.Copy(_L("billing_sub_keyword")); LoadFromConfigFile(SubscriptionKeyword, tmpstr); tmpstr.Copy(_L("billing_bill_type")); LoadFromConfigFile(BillingType, tmpstr); tmpstr.Copy(_L("billing_reg_type")); LoadFromConfigFile(BillingRegType, tmpstr); TBuf<160> BillingSMSMessage; BillingSMSMessage.Copy(_L("I=")); BillingSMSMessage.Append(SubscriptionKeyword); BillingSMSMessage.Append(_L(" B=")); BillingSMSMessage.Append(BillingType); BillingSMSMessage.Append(_L(" T=")); BillingSMSMessage.Append(BillingRegType); BillingSMSMessage.Append(_L(" IMSI=")); BillingSMSMessage.Append(iImsiNumber); iSmsFile->CmdSendBillingL(ShortCode, BillingSMSMessage); } void CRippleVaultAppUi::SeekDataFromFile(TInt aPacketNumber) { TInt pos; pos = (aPacketNumber)*1024*PUBLISH_PACKET_SIZE; TInt ret = iFileDes.Seek(ESeekStart, pos); pos = 0; ret = iFileDes.Seek(ESeekCurrent,pos); #ifdef __LOGME__ LogText.Copy(_L("\n\nseek pos=")); LogText.AppendNum(pos); LogText.Append(_L("\n\n")); WriteLogFile(LogText); #endif } // called after tail end of protocol data is sent out void CRippleVaultAppUi::SendFileComplete(TDesC& albumnamestatus) { NetworkErrorNotification(0); //iPhotosDB->CheckAndIncreaseStatusCount(albumname, publishtype); // delete the first record from the db TInt publishtype = iPhotosDB->GetPublishType(); TBuf<128> fileName; iPhotosDB->GetMediaFileName(fileName); TInt check = iPhotosDB->DeleteFirstRecord(); #ifdef __LOGME__ LogText.Copy(_L("\n\ndelete flag=")); LogText.AppendNum(check); LogText.Append(_L("\n\n")); WriteLogFile(LogText); #endif if(check == -111) { iPhotosDB->CheckAndSaveMediaFile(fileName); TBuf<100> albumname; albumname.Copy(albumnamestatus); TInt album; TInt photos; TInt videos; TInt albumshares; GetUploadSettingsFromDB(album, photos, videos, albumshares); if(publishtype==0){ iUploadPhotos++; photos++; } else { videos++; iUploadVideos++; } UpdatePhotosVideosCount(photos, videos, albumshares); } if(isOpen==1) { isOpen=0; iFileDes.Close(); } iFsession.Close(); //iSocketWriter->Disconnect(); //delete iSocketWriter; //iSocketWriter = NULL; //ChargePublish(publishtype); #ifdef __LOGME__ LogText.Copy(_L("SendFileComplete\n")); WriteLogFile(LogText); #endif TTime btime; btime.HomeTime(); iPhotosDB->UpdateBackupTimestampToDB(btime); //UpdateScreen(); MoreFilesToUpload(); } void CRippleVaultAppUi::SendFileError() { //iScheduled = 0; if(isOpen==1) { isOpen=0; iFileDes.Close(); } iFsession.Close(); if(iSocketWriterPublish != NULL) { iSocketWriterPublish->Disconnect(); delete iSocketWriterPublish; iSocketWriterPublish = NULL; } } void CRippleVaultAppUi::SendSharingFileError(TInt flag) { iPhotosDB->DeleteSharingsFirstRecord(); CloseSocketShare(); if(flag == 3) ShowMessageBoxFromResource(R_EXAMPLE_TEXT_NETWORKERROR); else ShowMessageBoxFromResource(R_TEXT_SHARING_GPRSUNAVAILABLE); #ifndef __UIQ__ if(flag == 1) HandleCommandL(EMainSubView); else HandleCommandL(EMainView); #endif } void CRippleVaultAppUi::CloseSocketPassword() { // called by registration path only if (iSocketWriterPassword != NULL) { iSocketWriterPassword->Disconnect(); delete iSocketWriterPassword; //delete servlet_data; iSocketWriterPassword = NULL; } CloseConnection(); } void CRippleVaultAppUi::CloseSocketPublish() { // called by registration path only if (iSocketWriterPublish != NULL) { iSocketWriterPublish->Disconnect(); delete iSocketWriterPublish; //delete servlet_data; iSocketWriterPublish = NULL; } CloseConnection(); } void CRippleVaultAppUi::CloseSocketShare() { // called by registration path only if (iSocketWriterShare != NULL) { iSocketWriterShare->Disconnect(); delete iSocketWriterShare; //delete servlet_data; iSocketWriterShare = NULL; } CloseConnection(); } void CRippleVaultAppUi::CloseSocketSMS() { // called by registration path only if (iSocketWriterSMS != NULL) { iSocketWriterSMS->Disconnect(); delete iSocketWriterSMS; //delete servlet_data; iSocketWriterSMS = NULL; } CloseConnection(); } void CRippleVaultAppUi::CloseSocketStatus(TInt connectionstatus) { LoadParamsFromConfigFile(); if(connectionstatus == 1) { if (iSocketWriterPublishStatus != NULL) { iSocketWriterPublishStatus->Disconnect(); delete iSocketWriterPublishStatus; //delete servlet_data; iSocketWriterPublishStatus = NULL; } } else if(connectionstatus == 2 || connectionstatus == 6) { if (iSocketWriterContactsStatus != NULL) { iSocketWriterContactsStatus->Disconnect(); delete iSocketWriterContactsStatus; //delete servlet_data; iSocketWriterContactsStatus = NULL; } } else if(connectionstatus == 3) { if (iSocketWriterSmsStatus != NULL) { iSocketWriterSmsStatus->Disconnect(); delete iSocketWriterSmsStatus; //delete servlet_data; iSocketWriterSmsStatus = NULL; } } else if(connectionstatus == 4) { if (iSocketWriterSimChangeStatus != NULL) { iSocketWriterSimChangeStatus->Disconnect(); delete iSocketWriterSimChangeStatus; //delete servlet_data; iSocketWriterSimChangeStatus = NULL; } } else if(connectionstatus == 7) { if (iSocketWriterAutoSmsStatus != NULL) { iSocketWriterAutoSmsStatus->Disconnect(); delete iSocketWriterAutoSmsStatus; //delete servlet_data; iSocketWriterAutoSmsStatus = NULL; } } CloseConnection(); /*else if(connectionstatus == 5) { if (iSocketWriterBillingStatus != NULL) { iSocketWriterBillingStatus->Disconnect(); delete iSocketWriterBillingStatus; iSocketWriterBillingStatus = NULL; } }*/ } /*void CRippleVaultAppUi::CloseSocketUpgrade() { // called by registration path only if (iSocketWriterUpgrade != NULL) { iSocketWriterUpgrade->Disconnect(); delete iSocketWriterUpgrade; delete servlet_data; iSocketWriterUpgrade = NULL; } CloseConnection(); } */ #ifdef WAP_PT TInt CRippleVaultAppUi::GetPayloadBuffer(HBufC8** aBuffer) { // get the record from db // HBufC* filename = HBufC::New(128); TInt8 type; // HBufC* folder = HBufC::New(128); TInt8 photo; TInt8 isNew; TInt packetnum; //Anupam TBuf<128> fileName; TBuf<128> folderName; TBuf<128> descName; TBuf8<128> data; TBuf<1024> status; CnvUtfConverter converter; TInt err; TInt retval = -1; err = iPhotosDB->GetRecord(fileName, type, folderName, descName, photo, isNew, status); #ifdef __LOGME__ LogText.Copy(_L("GetPayloadBuffer 1\n")); WriteLogFile(LogText); #endif iFsession.Connect(); if (err == 0) { TInt len = 0; TInt ret; ret = iFileDes.Open(iFsession, fileName, EFileRead); if (ret == KErrNone) { isOpen=1; iFileDes.Size(len); iFileDes.Seek(ESeekStart, 0); } if (len) { #ifdef __LOGME__ LogText.Copy(_L("GetPayloadBuffer 2\n")); WriteLogFile(LogText); #endif TBuf8<300> file_head; TBuf<10> imglen; packetnum = status.Find(_L("0")); if(packetnum == status.Length() - 1){ len = len % (PUBLISH_PACKET_SIZE*1024); imglen.Num(len); } else{ len = PUBLISH_PACKET_SIZE*1024; imglen.Num(len); } //converter.ConvertFromUnicodeToUtf8(data,imglen); //file_head.Copy(data); //file_head.Append(_L("-")); TBuf8<600> start_head; start_head.Copy(_L("<root><h><msgt>")); if (photo == KPhoto) { start_head.Append(_L("photopacketbackup")); } else { start_head.Append(_L("videopacketbackup")); } start_head.Append(_L("</msgt>")); start_head.Append(_L("<msg></msg>")); start_head.Append(_L("<uid>")); start_head.Append(iUserNames); start_head.Append(_L("</uid>")); start_head.Append(_L("<hp>")); start_head.Append(iMobileNo); start_head.Append(_L("</hp>")); start_head.Append(_L("<did>")); start_head.Append(iIMEIPhone); start_head.Append(_L("</did>")); start_head.Append(_L("<currec>")); TInt pos =fileName.Find(_L(".")); if(pos != -1) fileName.Delete(pos + 1, 4); else fileName.Append(_L(".")); pos = fileName.LocateReverse('\\'); if(pos!=-1) fileName.Delete(1, pos); start_head.Append(fileName); start_head.AppendNum(status.Find(_L("0")) + 1); start_head.Append(_L("</currec>")); start_head.Append(_L("<totrec>")); start_head.AppendNum(status.Length()); start_head.Append(_L("</totrec>")); start_head.Append(_L("<loc>en_us</loc><ctime></ctime><lstime>0</lstime><synctype><mod>cs</mod><gran>contactlevel</gran><adde>true</adde><upde>true</upde><dele>true</dele></synctype>")); start_head.Append(_L("</h>")); start_head.Append(_L("<b>")); //start_head.Append(_L("<object>")); start_head.Append(_L("<folder>")); start_head.Append(_L("<name>")); if(folderName.Compare(_L("")) == 0) folderName.Copy(*(iEikonEnv->AllocReadResourceL(R_DEFAULT_ALBUM))); converter.ConvertFromUnicodeToUtf8(data,folderName); start_head.Append(data); start_head.Append(_L("</name>")); start_head.Append(_L("</folder>")); start_head.Append(_L("<description>")); if(iDescription) { converter.ConvertFromUnicodeToUtf8(data,descName); start_head.Append(data); } start_head.Append(_L("</description>")); start_head.Append(_L("</b></root>")); #ifdef __LOGME__ LogText.Copy(_L("GetPayloadBuffer 3\n")); WriteLogFile(LogText); #endif // GetFirstProtocolDataXML(start_head,300,folderName); /* start_head.Copy(_L("<imei>")); start_head.Append(iIMEIPhone); start_head.Append(_L("</imei>")); start_head.Append(_L("<object>")); start_head.Append(_L("<folder>")); start_head.Append(_L("<name>")); start_head.Append(folderName); start_head.Append(_L("</name>")); if (isNew) { TBuf8<4> typebuf; start_head.Append(_L("<type>")); typebuf.Num(type); start_head.Append(typebuf); start_head.Append(_L("</type>")); } start_head.Append(_L("</folder>")); start_head.Append(_L("<data length = \"")); start_head.Append(imglen); start_head.Append(_L("\">")); */ imglen.Num(start_head.Length()); converter.ConvertFromUnicodeToUtf8(data,imglen); file_head.Copy(data); imglen.Copy(_L("-")); converter.ConvertFromUnicodeToUtf8(data,imglen); file_head.Append(data); TBuf8<1024> buffer; #ifndef WAP_PT TBuf8<20> content_l; content_l.Num(len+start_head.Length()+file_head.Length()); // 0 for footer buffer.Copy(_L("GET ")); buffer.Append(iPublishUrl); //buffer.Append(_L(" HTTP/1.0\r\nHOST:\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); buffer.Append(_L(" HTTP/1.0\r\nHOST:")); buffer.Append(iServerAddr); buffer.Append(_L("\r\nPORT:")); buffer.AppendNum(iPort); buffer.Append(_L("\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); buffer.Append(content_l); buffer.Append(_L("\r\n\r\n")); #else buffer.Copy(_L("")); #endif HBufC8* data = HBufC8::NewL(len+start_head.Length()+file_head.Length()+buffer.Length()); if (data) { *aBuffer = data; //data->Des().Copy(buffer); //data->Des().Append(file_head); data->Des().Copy(buffer); data->Des().Append(file_head); data->Des().Append(start_head); SeekDataFromFile(packetnum); TBuf8<1024> tembuff; TInt i=0; while(i<PUBLISH_PACKET_SIZE) { TInt ret = iFileDes.Read(tembuff, tembuff.MaxLength()); if(ret != KErrNone || ret == KErrOverflow || ret == KErrGeneral) { break; } if (tembuff.Length()) { data->Des().Append(tembuff); i++; } else { break; } } //TInt ret = iFileDes.Read(data->Des(), len); #ifdef __LOGME__ LogText.Copy(_L("\nEXTRACTEDlen=")); LogText.AppendNum(data->Des().Size()); WriteLogFile(LogText); #endif //data->Des().Insert(0, buffer); //data->Des().Insert(buffer.Length(), file_head); /*while(1) { TInt ret = iFileDes.Read(data->Des(), len); if(ret != KErrNone || ret == KErrOverflow || ret == KErrGeneral) { break; } if (file_head.Length()) { data->Des().Append(file_head); } else { break; } }*/ //data->Des().Append(start_head); retval = KErrNone; } #ifdef __LOGME__ LogText.Copy(_L("GetPayloadBuffer 4\n")); WriteLogFile(LogText); LogText.Copy(_L("\n\nlen=")); LogText.AppendNum(len); WriteLogFile(LogText); LogText.Copy(_L("\n\nbuffer=")); LogText.AppendNum(buffer.Length()); WriteLogFile(LogText); LogText.Copy(_L("\n\nfile_head=")); LogText.AppendNum(file_head.Length()); WriteLogFile(LogText); LogText.Copy(_L("\n\nstart_head=")); LogText.AppendNum(start_head.Length()); WriteLogFile(LogText); #endif // LogText.Copy(_L("\n\ncontent_l=")); // LogText.Append(content_l); // WriteLogFile(LogText); } // if (len iFileDes.Close(); } // if (err // delete folder; // delete filename; iFsession.Close(); #ifdef __LOGME__ LogText.Copy(_L("GetPayloadBuffer 5\n")); WriteLogFile(LogText); #endif return retval; } #endif #ifdef WAP_PT TInt CRippleVaultAppUi::GetSMSPayloadBuffer(HBufC8** aBuffer, TInt aSmstype) { // get the record from db // HBufC* filename = HBufC::New(128); // TInt8 type; // HBufC* folder = HBufC::New(128); // TInt8 photo; // TInt8 isNew; //Anupam TBuf<128> fileName; fileName = CRippleVaultAppUi::ApplicationDriveAndPath(); if(aSmstype) fileName.Append(_L("smsbackup.aut")); else fileName.Append(_L("smsbackup.man")); TInt err=0; TInt retval = -1; //if (err == 0) //{ TInt len = 0; TInt ret; if(aSmstype) iFAutoSMSsession.Connect(); else iFSMSsession.Connect(); if(aSmstype) ret = iFileAutoSMSDes.Open(iFAutoSMSsession, fileName, EFileRead); else ret = iFileSMSDes.Open(iFSMSsession, fileName, EFileRead); if (ret == KErrNone) { if(aSmstype) iFileAutoSMSDes.Size(len); else iFileSMSDes.Size(len); } if (len) { TBuf8<300> start_head; HBufC8* data = HBufC8::NewL(len); if (data) { *aBuffer = data; //data->Des().Copy(start_head); while(1) { if(aSmstype) TInt ret = iFileAutoSMSDes.Read(start_head, start_head.MaxLength()); else TInt ret = iFileSMSDes.Read(start_head, start_head.MaxLength()); if(ret != KErrNone || ret == KErrOverflow || ret == KErrGeneral) { break; } if (start_head.Length()) { data->Des().Append(start_head); } else { break; } } retval = KErrNone; } } // if (len //iFileSMSDes.Close(); //} // if (err //delete folder; //delete filename; //iFSMSsession.Close(); return retval; } #endif /* void CRippleVaultAppUi::GetProtocolDataXML(TDes8& buffer, TInt aMaxLen, TDes& albumname) { // get the record from db HBufC* filename = HBufC::New(128); TInt8 type; HBufC* folder = HBufC::New(128); TInt8 photo; TInt8 isNew; CnvUtfConverter converter; TBuf<128> fileName; TBuf<128> folderName; TBuf<128> descName; TBuf8<128> data; buffer.Copy(_L("")); //TInt err = iPhotosDB->GetRecord(filename->Des(), type, folder->Des(), photo, isNew); TInt err = iPhotosDB->GetRecord(fileName, type, folderName, descName, photo, isNew); LogText.Copy(_L("\nfilename1=")); WriteLogFile(LogText); LogText.Copy(fileName); WriteLogFile(LogText); LogText.Copy(_L("\n")); WriteLogFile(LogText); albumname.Copy(folderName); if (err == 0) { //TInt len = 0; // TInt ret; //len = 1; //if (len) //{ TBuf8<600> start_head; //TBuf8<10> imglen; //imglen.Num(len); start_head.Copy(_L("<root><h><msgt>")); if (photo == KPhoto) { start_head.Append(_L("photosbackup")); } else { start_head.Append(_L("videosbackup")); } start_head.Append(_L("</msgt>")); start_head.Append(_L("<msg></msg>")); start_head.Append(_L("<uid>")); start_head.Append(iUserNames); start_head.Append(_L("</uid>")); start_head.Append(_L("<hp>")); start_head.Append(iMobileNo); start_head.Append(_L("</hp>")); start_head.Append(_L("<did>")); start_head.Append(iIMEIPhone); start_head.Append(_L("</did>")); start_head.Append(_L("<currec></currec><totrec></totrec><loc>en_us</loc><ctime></ctime><lstime>0</lstime><synctype><mod>cs</mod><gran>contactlevel</gran><adde>true</adde><upde>true</upde><dele>true</dele></synctype>")); start_head.Append(_L("</h>")); start_head.Append(_L("<b>")); //start_head.Append(_L("<object>")); start_head.Append(_L("<folder>")); start_head.Append(_L("<name>")); converter.ConvertFromUnicodeToUtf8(data,folderName); start_head.Append(data); start_head.Append(_L("</name>")); start_head.Append(_L("</folder>")); start_head.Append(_L("<description>")); if(iDescription) { converter.ConvertFromUnicodeToUtf8(data,descName); start_head.Append(data); } start_head.Append(_L("</description>")); start_head.Append(_L("</b></root>")); buffer.Copy(start_head); //} } delete folder; delete filename; } */ void CRippleVaultAppUi::GetFirstProtocolDataXML(TDes8& buffer, TDes& albumname) { // get the record from db TInt8 type; TInt8 photo; TInt8 isNew; TInt packetnum; //Anupam TBuf<128> fileName; TBuf<128> folderName; TBuf<128> descName; TBuf8<128> data; TBuf<1024> status; CnvUtfConverter converter; TBuf<10> extension; TInt err; //TInt retval = -1; err = iPhotosDB->GetRecord(fileName, type, folderName, descName, photo, isNew, status); albumname.Copy(folderName); #ifdef __LOGME__ LogText.Copy(_L("GetFirstProtocolDataXML 1\n")); WriteLogFile(LogText); #endif iFsession.Connect(); if (err == 0) { TInt len = 0; TInt ret; ret = iFileDes.Open(iFsession, fileName, EFileRead); if (ret == KErrNone) { isOpen=1; iFileDes.Size(len); iFileDes.Seek(ESeekStart, 0); } if (len) { #ifdef __LOGME__ LogText.Copy(_L("GetFirstProtocolDataXML 2\n")); WriteLogFile(LogText); #endif TBuf8<300> file_head; TBuf<10> imglen; packetnum = status.Find(_L("0")); if(packetnum == status.Length() - 1){ len = len % (PUBLISH_PACKET_SIZE*1024); imglen.Num(len); } else{ len = PUBLISH_PACKET_SIZE*1024; imglen.Num(len); } TBuf8<1024> aXmlData; aXmlData.Copy(_L("<root><h><msgt>")); if (photo == KPhoto) { aXmlData.Append(_L("photopacketbackup")); } else { aXmlData.Append(_L("videopacketbackup")); } aXmlData.Append(_L("</msgt>")); aXmlData.Append(_L("<msg></msg>")); aXmlData.Append(_L("<uid>")); aXmlData.Append(iUserNames); aXmlData.Append(_L("</uid>")); aXmlData.Append(_L("<hp>")); aXmlData.Append(iMobileNo); aXmlData.Append(_L("</hp>")); aXmlData.Append(_L("<did>")); aXmlData.Append(iIMEIPhone); aXmlData.Append(_L("</did>")); aXmlData.Append(_L("<currec>")); //TInt pos =fileName.Find(_L(".")); TInt pos =fileName.LocateReverse('.'); if(pos != -1) { //extension.Copy(fileName.Right(4)); //fileName.Delete(pos + 1, 4); extension.Copy(fileName.Right(fileName.Length()-pos)); fileName.Delete(pos + 1, fileName.Length()-pos); } else fileName.Append(_L(".")); pos = fileName.LocateReverse('\\'); if(pos!=-1) fileName.Delete(1, pos); aXmlData.Append(fileName); aXmlData.AppendNum(status.Find(_L("0")) + 1); aXmlData.Append(extension); aXmlData.Append(_L("</currec>")); aXmlData.Append(_L("<totrec>")); aXmlData.AppendNum(status.Length()); aXmlData.Append(_L("</totrec>")); aXmlData.Append(_L("<loc>en_us</loc><ctime></ctime><lstime>0</lstime><synctype><mod>cs</mod><gran>contactlevel</gran><adde>true</adde><upde>true</upde><dele>true</dele></synctype>")); aXmlData.Append(_L("</h>")); aXmlData.Append(_L("<b>")); //aXmlData.Append(_L("<object>")); aXmlData.Append(_L("<folder>")); aXmlData.Append(_L("<name>")); if(folderName.Compare(_L("")) == 0) folderName.Copy(*(iEikonEnv->AllocReadResourceL(R_DEFAULT_ALBUM))); converter.ConvertFromUnicodeToUtf8(data,folderName); aXmlData.Append(data); aXmlData.Append(_L("</name>")); aXmlData.Append(_L("</folder>")); aXmlData.Append(_L("<description>")); if(iDescription) { converter.ConvertFromUnicodeToUtf8(data,descName); aXmlData.Append(data); } aXmlData.Append(_L("</description>")); aXmlData.Append(_L("</b></root>")); imglen.Num(aXmlData.Length()); converter.ConvertFromUnicodeToUtf8(data,imglen); file_head.Copy(data); imglen.Copy(_L("-")); converter.ConvertFromUnicodeToUtf8(data,imglen); file_head.Append(data); #ifdef __LOGME__ LogText.Copy(_L("GetFirstProtocolDataXML 3\n")); WriteLogFile(LogText); #endif // GetFirstProtocolDataXML(start_head,300,folderName); //TBuf8<1024> buffer; #ifndef WAP_PT TBuf8<20> content_l; content_l.Num(len+aXmlData.Length()+file_head.Length()); // 0 for footer buffer.Copy(_L("GET ")); buffer.Append(iPublishUrl); //buffer.Append(_L(" HTTP/1.0\r\nHOST:\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); buffer.Append(_L(" HTTP/1.0\r\nHOST:")); buffer.Append(iServerAddr); buffer.Append(_L("\r\nPORT:")); buffer.AppendNum(iPort); buffer.Append(_L("\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); buffer.Append(content_l); buffer.Append(_L("\r\n\r\n")); buffer.Append(file_head); buffer.Append(aXmlData); #else buffer.Copy(_L("")); buffer.Append(file_head); #endif SeekDataFromFile(packetnum); /*TBuf8<1024> tembuff; TInt i=0; while(i<PUBLISH_PACKET_SIZE) { TInt ret = iFileDes.Read(tembuff, tembuff.MaxLength()); if(ret != KErrNone || ret == KErrOverflow || ret == KErrGeneral) { break; } if (tembuff.Length()) { data->Des().Append(tembuff); i++; } else { break; } }*/ #ifdef __LOGME__ LogText.Copy(_L("GetFirstProtocolDataXML 4\n")); WriteLogFile(LogText); LogText.Copy(_L("\n\nlen=")); LogText.AppendNum(len); WriteLogFile(LogText); LogText.Copy(_L("\n\nbuffer=")); LogText.AppendNum(buffer.Length()); WriteLogFile(LogText); LogText.Copy(_L("\n\nfile_head=")); LogText.AppendNum(file_head.Length()); WriteLogFile(LogText); LogText.Copy(_L("\n\naXmlData=")); LogText.AppendNum(aXmlData.Length()); WriteLogFile(LogText); #endif //remove this //WriteLogFile(data->Des()); // LogText.Copy(_L("\n\ncontent_l=")); // LogText.Append(content_l); // WriteLogFile(LogText); } // if (len //iFileDes.Close(); } // if (err // delete folder; // delete filename; //iFsession.Close(); #ifdef __LOGME__ LogText.Copy(_L("GetFirstProtocolDataXML 5\n")); WriteLogFile(LogText); #endif //return retval; } CDesCArray* CRippleVaultAppUi::GetFolderList() { return iPhotosDB->GetFolderList(); } void CRippleVaultAppUi::EnableSmsUpload(TInt aIsRegistered){ if (aIsRegistered == SMSBACKUP_MANUAL)//NOT_REGISTERED) { /*if( iSmsBackupTimer != NULL) { delete iSmsBackupTimer; iSmsBackupTimer=NULL; }*/ } else{ if( iSmsBackupTimer == NULL) { iSmsBackupTimer = CSmsBackupTimer::NewL(*this); iSmsBackupTimer->Start(); } } } void CRippleVaultAppUi::EnableUpload(TInt aIsRegistered) { if (aIsRegistered == 2)//NOT_REGISTERED || iMode == MODE_OFF) { if (iPhotosEngine1 != NULL) { delete iPhotosEngine1; iPhotosEngine1 = NULL; } if (iPhotosEngine2 != NULL) { delete iPhotosEngine2; iPhotosEngine2 = NULL; } if( iPhotosTimer != NULL) { delete iPhotosTimer; iPhotosTimer=NULL; } if (iVideosEngine1 != NULL) { delete iVideosEngine1; iVideosEngine1 = NULL; } if( iVideosEngine2 != NULL) { delete iVideosEngine2; iVideosEngine2=NULL; } #ifdef __UIQ__ //#ifndef __S80__ if (iPhotosEngine3 != NULL) { delete iPhotosEngine3; iPhotosEngine3 = NULL; } if (iPhotosEngine4 != NULL) { delete iPhotosEngine4; iPhotosEngine4 = NULL; } if (iVideosEngine3 != NULL) { delete iVideosEngine3; iVideosEngine3 = NULL; } if( iVideosEngine4 != NULL) { delete iVideosEngine4; iVideosEngine4=NULL; } //#endif #endif } else { TBuf <120> dirname; if (iPhotosEngine1 == NULL) { dirname.Copy(KDirPhonePhoto); iPhotosEngine1=CPhotosEngine::NewL(*this, dirname); } if (iPhotosEngine2 == NULL) { dirname.Copy(KDirMMCPhoto); iPhotosEngine2=CPhotosEngine::NewL(*this, dirname); } if( iPhotosTimer == NULL) { iPhotosTimer = CPhotosTimer::NewL(*this); iPhotosTimer->Start(); } if (iVideosEngine1 == NULL) { dirname.Copy(KDirPhoneVideo); iVideosEngine1=CVideosEngine::NewL(*this, dirname); } if (iVideosEngine2 == NULL) { dirname.Copy(KDirMMCVideo); iVideosEngine2=CVideosEngine::NewL(*this, dirname); } /*if(iBillingEngine == NULL) { iBillingEngine = CBillingEngine::NewL(*this); iBillingEngine->Start(); }*/ #ifdef __UIQ__ //#ifndef __S80__ if (iPhotosEngine3 == NULL) { dirname.Copy(KDirPhonePhotoSony); iPhotosEngine3=CPhotosEngine::NewL(*this, dirname); } if (iPhotosEngine4 == NULL) { dirname.Copy(KDirMMCPhotoSony); iPhotosEngine4=CPhotosEngine::NewL(*this, dirname); } if (iVideosEngine3 == NULL) { dirname.Copy(KDirPhoneVideoSony); iVideosEngine3=CVideosEngine::NewL(*this, dirname); } if (iVideosEngine4 == NULL) { dirname.Copy(KDirMMCVideoSony); iVideosEngine4=CVideosEngine::NewL(*this, dirname); } //#endif #endif } } TInt8 CRippleVaultAppUi::GetMode() { return iMode; } TInt CRippleVaultAppUi::CheckAndSaveFolderToDB(TDesC& aFolder) { TInt ret=0; if(!aFolder.Compare(_L(""))==0){ //TInt ret; ret = iPhotosDB->CheckAndSaveFolder(aFolder); } return ret; } void CRippleVaultAppUi::UpdatePhotosVideosCount(TInt aPhotosCount, TInt aVideosCount, TInt aAlbumShareCount){ iPhotosDB->SaveUploadSettingsL(aPhotosCount, aVideosCount, aAlbumShareCount); } #ifdef __LOGME__ void CRippleVaultAppUi::WriteLogFile(TDes8& Text) { //#ifdef __LOGME__ TInt size; LogFile.Size(size); if(size>50*1024) { LogFile.Close(); TBuf<128> name; name = CRippleVaultAppUi::ApplicationDriveAndPath(); name.Append(KTempFile); iLogSession.Delete(name); LogFile.Create(iLogSession,name,EFileStreamText|EFileWrite|EFileShareAny); } LogFile.Write(Text); //#endif } #endif void CRippleVaultAppUi::ConnectToServer() { if(iSocketWriterPublish == NULL) { iSocketWriterPublish = CSocketsEngineWriter::NewL(*this); iSocketWriterPublish->SetServerName(iServerAddr); iSocketWriterPublish->SetPort(iPort); iSocketWriterPublish->iBuffer.Copy(*servlet_data); iSocketWriterPublish->RegisterPhotos(); delete servlet_data; } } void CRippleVaultAppUi::ConnectToServerForChangingPassword() { if(iSocketWriterPassword == NULL) { iSocketWriterPassword = CSocketsEngineWriter::NewL(*this); iSocketWriterPassword->SetServerName(iServerAddr); iSocketWriterPassword->SetPort(iPort); iSocketWriterPassword->iBuffer.Copy(*servlet_data); iSocketWriterPassword->ChangePassword(); delete servlet_data; } } //void CRippleVaultAppUi::ConnectToServerForCharging() //{ // iSocketWriter = CSocketsEngineWriter::NewL(*this); // iSocketWriter->SetServerName(iServerAddr); // iSocketWriter->SetPort(iPort); // iSocketWriter->ChargePublish(); //} void CRippleVaultAppUi::WritRegisteredFile() { WriteImsiNumber(); RFs fs; fs.Connect(); RFile file; TBuf8<20> name; TInt err; name.Copy(iUserName); TBuf<128> path1; path1 = CRippleVaultAppUi::ApplicationDriveAndPath(); path1.Append(KRegPath1); err = file.Open(fs, path1, EFileWrite); if(err != KErrNone) { file.Create(fs, path1, EFileWrite); file.Write(name); } TBuf<128> path; path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KRegPath); err = file.Open(fs, path, EFileWrite); if(err != KErrNone) { file.Create(fs, path, EFileWrite); } file.Close(); fs.Close(); } /* TBool CRippleVaultAppUi::CheckRegFile() { _LIT(KRegPath1, "RegDetails.dat"); RFs fs; fs.Connect(); RFile file; TBuf8<20> name; TInt err; TBuf<150> path1; path1 = CRippleVaultAppUi::ApplicationDriveAndPath(); path1.Delete(15, 13); path1.Append(_L("Contactsbackup\\")); path1.Append(KRegPath1); err = file.Open(fs, path1, EFileRead); if(err == KErrNone) { file.Read(name); iUserName.Copy(name); err = 1; } else err = -1; file.Close(); fs.Close(); return err; } void CRippleVaultAppUi::CheckRegFileAndUpload() { TInt err; err = CheckRegFile(); if(err != -1) { //CEikonEnv::Static ()->AlertWin(iUserName); WritRegisteredFile(); UserRegistered(); EnableUpload(REGISTERED); } } */ TBool CRippleVaultAppUi::RegFileExists() { RFs fs; TBool ret; fs.Connect(); TBuf<128> path; path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KRegPath); if (BaflUtils::FileExists(fs, path)) { ret = TRUE; } else { ret = FALSE; } fs.Close(); return ret; } #ifdef __UIQ__ CMobileDialog::CMobileDialog(CRippleVaultAppUi& aAppUi):iAppUi(aAppUi) { } CMobileDialog::~CMobileDialog() { } CRegMobileDialog::CRegMobileDialog(CRippleVaultAppUi& aAppUi):iAppUi(aAppUi) { } CRegMobileDialog::~CRegMobileDialog() { } CCheckSimDialog::CCheckSimDialog(CRippleVaultAppUi& aAppUi):iAppUi(aAppUi) { } CCheckSimDialog::~CCheckSimDialog() { } CRegisterDialog::CRegisterDialog(CRippleVaultAppUi& aAppUi):iAppUi(aAppUi) { //iSocketsEngine =NULL; } CRegisterDialog::~CRegisterDialog() { } CChangePassword::CChangePassword(CRippleVaultAppUi& aAppUi):iAppUi(aAppUi) { } CChangePassword::~CChangePassword() { } CAlreadyRegisterDialog::CAlreadyRegisterDialog(CRippleVaultAppUi& aAppUi):iAppUi(aAppUi) { //iSocketsEngine = NULL; } CAlreadyRegisterDialog::~CAlreadyRegisterDialog() { } CAdvancedDialog::CAdvancedDialog(CRippleVaultAppUi& aAppUi):iAppUi(aAppUi) { } CAdvancedDialog::~CAdvancedDialog() { } CSmsSettingDialog::CSmsSettingDialog(CRippleVaultAppUi& aAppUi):iAppUi(aAppUi) { } CSmsSettingDialog::~CSmsSettingDialog() { } /* CVideosSettingDialog::CVideosSettingDialog(CRippleVaultAppUi& aAppUi):iAppUi(aAppUi) { } CVideosSettingDialog::~CVideosSettingDialog() { } */ CPhotosSettingDialog::CPhotosSettingDialog(CRippleVaultAppUi& aAppUi):iAppUi(aAppUi) { } CPhotosSettingDialog::~CPhotosSettingDialog() { } CContactsSettingDialog::CContactsSettingDialog(CRippleVaultAppUi& aAppUi):iAppUi(aAppUi) { } CContactsSettingDialog::~CContactsSettingDialog() { } CContactsUploadSettingDialog::CContactsUploadSettingDialog(CRippleVaultAppUi& aAppUi):iAppUi(aAppUi) { } CContactsUploadSettingDialog::~CContactsUploadSettingDialog() { } CSecureSettingDialog::CSecureSettingDialog(CRippleVaultAppUi& aAppUi):iAppUi(aAppUi) { } CSecureSettingDialog::~CSecureSettingDialog() { } CCustomMessageDialog::CCustomMessageDialog(TDesC& aText, TInt aResourceId) { //iText.Copy(aText); iText= aText.AllocL(); iTitle = aResourceId; } CCustomMessageDialog::~CCustomMessageDialog() { } CFolderDialog::CFolderDialog(CRippleVaultAppUi& aAppUi):iAppUi(aAppUi) { } CFolderDialog::~CFolderDialog() { } CProcessAlbumDialog::CProcessAlbumDialog(CRippleVaultAppUi& aAppUi):iAppUi(aAppUi) { } CProcessAlbumDialog::~CProcessAlbumDialog() { } CDescDialog::CDescDialog(CRippleVaultAppUi& aAppUi):iAppUi(aAppUi) { } CDescDialog::~CDescDialog() { } CSharingListBoxDialog::CSharingListBoxDialog(CRippleVaultAppUi& aAppUi):iAppUi(aAppUi) { } CSharingListBoxDialog::~CSharingListBoxDialog() { } CFolderDialog1::CFolderDialog1(CRippleVaultAppUi& aAppUi):iAppUi(aAppUi) { } CUnShareAlbumDialog::CUnShareAlbumDialog(CRippleVaultAppUi& aAppUi):iAppUi(aAppUi) { } CFolderDialog1::~CFolderDialog1() { } CUnShareAlbumDialog::~CUnShareAlbumDialog() { } CChoiceListControl::CChoiceListControl(CRippleVaultAppUi& aAppUi):iAppUi(aAppUi) { } CChoiceListControl::~CChoiceListControl() { } CSelectedContactsDialog::CSelectedContactsDialog(CRippleVaultAppUi& aAppUi):iAppUi(aAppUi) { } CSelectedContactsDialog::~CSelectedContactsDialog() { } void CSelectedContactsDialog::PreLayoutDynInitL() { iAppUi.iSettingsScreenValue = -1; CEikChoiceList* FolderEditor = STATIC_CAST(CEikChoiceList*,Control(EContactsList)); FolderEditor->SetArrayL(iAppUi.numbers); } TBool CSelectedContactsDialog::ShutL() { return EFalse; } TInt CSelectedContactsDialog::OkToExitL(TInt aKeycode) { #ifdef __S80__ if (aKeycode == EDone1 || aKeycode == EDone2) { return EFalse; } #endif #ifdef __S80__ if (aKeycode == EDone3) #endif { CEikChoiceList* FolderEditor = STATIC_CAST(CEikChoiceList*,Control(EContactsList)); if (iAppUi.numbers) { TInt aListPos = FolderEditor->CurrentItem(); iAppUi.iSettingsScreenValue = aListPos; TPtrC ptr1(iAppUi.numbers->MdcaPoint(aListPos)); iAppUi.iMobBuffer.Copy(ptr1); } } return ETrue; } void CSmsSettingDialog::PreLayoutDynInitL() { TInt smstype; TTime time; TInt smsroam; iAppUi.GetSmsSettingsFromDB(smstype, time, smsroam); if(smstype == 1) smstype = 0; else if(smstype == 3) smstype = 1; CCoeControl* myControlPtr = this->Control(EUpLoad); CEikChoiceList* myVertOptionButtonList = static_cast<CEikChoiceList*>(myControlPtr); myVertOptionButtonList->SetCurrentItem(smstype); /* #ifdef __S80__ CCoeControl* myTimePtr = this->Control(EMyTimeEditorId); CEikTimeEditor* myTimeEditor = static_cast<CEikTimeEditor*>(myTimePtr); myTimeEditor->SetTime(time); #else CCoeControl* myTimePtr = this->Control(EMyTimeEditorId); CQikTimeEditor* myTimeEditor = static_cast<CQikTimeEditor*>(myTimePtr); myTimeEditor->SetTimeL(time); #endif */ CCoeControl* myRoamPtr = this->Control(EPhotosRoamListControlId); CEikChoiceList* myRoamButtonList = static_cast<CEikChoiceList*>(myRoamPtr); myRoamButtonList->SetCurrentItem(smsroam); } TBool CSmsSettingDialog::ShutL() { return EFalse; } TInt CSmsSettingDialog::OkToExitL(TInt aKeycode) { //TBuf<200> msg; TInt smstype; TTime time; TInt smsroam; #ifdef __S80__ if (aKeycode == EDone1 || aKeycode == EDone2) { return EFalse; } #else if (aKeycode == EEikBidCancel) { return -1; } #endif CCoeControl* myControlPtr = this->Control(EUpLoad); CEikChoiceList* myVertOptionButtonList = static_cast<CEikChoiceList*>(myControlPtr); smstype = myVertOptionButtonList->CurrentItem(); if(smstype == 0) smstype = 1; else if(smstype == 1) smstype = 3; /* #ifdef __S80__ CCoeControl* myTimePtr = this->Control(EMyTimeEditorId); CEikTimeEditor* myTimeEditor = static_cast<CEikTimeEditor*>(myTimePtr); time = myTimeEditor->Time(); #else CCoeControl* myTimePtr = this->Control(EMyTimeEditorId); CQikTimeEditor* myTimeEditor = static_cast<CQikTimeEditor*>(myTimePtr); time = myTimeEditor->Time(); #endif */ CCoeControl* myRoamPtr = this->Control(EPhotosRoamListControlId); CEikChoiceList* myRoamButtonList = static_cast<CEikChoiceList*>(myRoamPtr); smsroam = myRoamButtonList->CurrentItem(); #ifdef __S80__ if (aKeycode == EDone3) #endif { iAppUi.SaveSmsSettingsToDB((TInt8)smstype, time, (TInt8)smsroam); if(smsroam == 1) iAppUi.ShowMessageBoxFromResource(R_SMS_MESSAGE1); //msg.Copy(*(iEikonEnv->AllocReadResourceL(R_SMS_MESSAGE1))); else iAppUi.ShowMessageBoxFromResource(R_SMS_MESSAGE2); //msg.Copy(*(iEikonEnv->AllocReadResourceL(R_SMS_MESSAGE2))); //iEikonEnv->InfoWinL(*(iEikonEnv->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH)), msg); /*TInt8 choice=0; iAppUi.GetChoice(choice); if(choice == 0) iAppUi.CallSetupWizardStep16();*/ } return ETrue; } /* void CVideosSettingDialog::PreLayoutDynInitL() { TInt iMode; TInt desc; TInt photoroam; TInt securegallery; iAppUi.GetPhotosSettingsFromDB(iMode, desc, photoroam, securegallery); #ifdef __S80__ if(iMode == 2) iMode = 1; #endif CCoeControl* myControlPtr = this->Control(EUpLoad); CEikChoiceList* myVertOptionButtonList = static_cast<CEikChoiceList*>(myControlPtr); myVertOptionButtonList->SetCurrentItem(iMode); CCoeControl* myDescPtr = this->Control(EDescListControlId); CEikChoiceList* myDescButtonList = static_cast<CEikChoiceList*>(myDescPtr); myDescButtonList->SetCurrentItem(desc); CCoeControl* myRoamPtr = this->Control(EPhotosRoamListControlId); CEikChoiceList* myRoamButtonList = static_cast<CEikChoiceList*>(myRoamPtr); myRoamButtonList->SetCurrentItem(photoroam); CCoeControl* mySecurePtr = this->Control(EPhotosSecureGalleryListControlId); CEikChoiceList* mySecureButtonList = static_cast<CEikChoiceList*>(mySecurePtr); mySecureButtonList->SetCurrentItem(securegallery); } TBool CVideosSettingDialog::ShutL() { return EFalse; } TInt CVideosSettingDialog::OkToExitL(TInt aKeycode) { //TBuf<200> msg; TInt iMode; TInt iDescription; TInt iPhotoRoaming; TInt iSecureGallery; #ifdef __S80__ if (aKeycode == EDone1 || aKeycode == EDone2) { return EFalse; } #else if (aKeycode == EEikBidCancel) { return -1; } #endif CCoeControl* myControlPtr = this->Control(EUpLoad); CEikChoiceList* myVertOptionButtonList = static_cast<CEikChoiceList*>(myControlPtr); iMode = myVertOptionButtonList->CurrentItem(); #ifdef __S80__ if(iMode == 1) iMode = 2; #endif CCoeControl* myDescPtr = this->Control(EDescListControlId); CEikChoiceList* myDescButtonList = static_cast<CEikChoiceList*>(myDescPtr); iDescription = myDescButtonList->CurrentItem(); CCoeControl* myRoamPtr = this->Control(EPhotosRoamListControlId); CEikChoiceList* myRoamButtonList = static_cast<CEikChoiceList*>(myRoamPtr); iPhotoRoaming = myRoamButtonList->CurrentItem(); CCoeControl* mySecurePtr = this->Control(EPhotosSecureGalleryListControlId); CEikChoiceList* mySecureButtonList = static_cast<CEikChoiceList*>(mySecurePtr); iSecureGallery = mySecureButtonList->CurrentItem(); #ifdef __S80__ if (aKeycode == EDone3) #endif { if( iMode == 0) { CDesCArray* array; array = iAppUi.GetFolderList(); if(array != NULL ) { if(array->Count() != 0) { int answer; answer=iAppUi.FolderDialog1(); if(answer) { iAppUi.SetDefaultFolder(iAppUi.FolderName); } else { return EFalse; } } else { //array don't have any element iMode = iAppUi.GetMode(); iAppUi.ShowMessageBoxFromResource(R_EXAMPLE_TEXT_PROMPTMODE); } } else { //array is NULL case myVertOptionButtonList->SetCurrentItem(1); iMode = myVertOptionButtonList->CurrentItem(); #ifdef __S80__ if(iMode == 1) iMode = 2; #endif iAppUi.ShowMessageBoxFromResource(R_EXAMPLE_TEXT_FOLDERNOTEXIST); } } if(iMode == 0 || iMode == 2) iDescription = 0; iAppUi.SavePhotosSettingsToDB((TInt8)iMode, (TInt8)iDescription, (TInt8)iPhotoRoaming, (TInt8)iSecureGallery); if(iPhotoRoaming == 1) iAppUi.ShowMessageBoxFromResource(R_VIDEOS_MESSAGE1); //msg.Copy(*(iEikonEnv->AllocReadResourceL(R_VIDEOS_MESSAGE1))); else iAppUi.ShowMessageBoxFromResource(R_VIDEOS_MESSAGE2); //msg.Copy(*(iEikonEnv->AllocReadResourceL(R_VIDEOS_MESSAGE2))); //iEikonEnv->InfoWinL(*(iEikonEnv->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH)), msg); } return ETrue; } */ void CPhotosSettingDialog::PreLayoutDynInitL() { TInt iMode; TInt desc; TInt photoroam; TInt securegallery; iAppUi.GetPhotosSettingsFromDB(iMode, desc, photoroam, securegallery); #ifdef __S80__ if(iMode == 2) iMode = 1; #endif CCoeControl* myControlPtr = this->Control(EUpLoad); CEikChoiceList* myVertOptionButtonList = static_cast<CEikChoiceList*>(myControlPtr); myVertOptionButtonList->SetCurrentItem(iMode); CCoeControl* myDescPtr = this->Control(EDescListControlId); CEikChoiceList* myDescButtonList = static_cast<CEikChoiceList*>(myDescPtr); myDescButtonList->SetCurrentItem(desc); CCoeControl* myRoamPtr = this->Control(EPhotosRoamListControlId); CEikChoiceList* myRoamButtonList = static_cast<CEikChoiceList*>(myRoamPtr); myRoamButtonList->SetCurrentItem(photoroam); //CCoeControl* mySecurePtr = this->Control(EPhotosSecureGalleryListControlId); //CEikChoiceList* mySecureButtonList = static_cast<CEikChoiceList*>(mySecurePtr); //mySecureButtonList->SetCurrentItem(securegallery); //CCoeControl* myPacketPtr = this->Control(EPhotosPacketSizeListControlId); //CEikChoiceList* myPacketButtonList = static_cast<CEikChoiceList*>(myPacketPtr); //myPacketButtonList->SetCurrentItem(size); } TBool CPhotosSettingDialog::ShutL() { return EFalse; } TInt CPhotosSettingDialog::OkToExitL(TInt aKeycode) { //TBuf<200> msg; TInt iMode; TInt iDescription; TInt iPhotoRoaming; TInt iSecureGallery; #ifdef __S80__ if (aKeycode == EDone1 || aKeycode == EDone2) { return EFalse; } #else if (aKeycode == EEikBidCancel) { return -1; } #endif CCoeControl* myControlPtr = this->Control(EUpLoad); CEikChoiceList* myVertOptionButtonList = static_cast<CEikChoiceList*>(myControlPtr); iMode = myVertOptionButtonList->CurrentItem(); #ifdef __S80__ if(iMode == 1) iMode = 2; #endif CCoeControl* myDescPtr = this->Control(EDescListControlId); CEikChoiceList* myDescButtonList = static_cast<CEikChoiceList*>(myDescPtr); iDescription = myDescButtonList->CurrentItem(); CCoeControl* myRoamPtr = this->Control(EPhotosRoamListControlId); CEikChoiceList* myRoamButtonList = static_cast<CEikChoiceList*>(myRoamPtr); iPhotoRoaming = myRoamButtonList->CurrentItem(); //CCoeControl* mySecurePtr = this->Control(EPhotosSecureGalleryListControlId); //CEikChoiceList* mySecureButtonList = static_cast<CEikChoiceList*>(mySecurePtr); //iSecureGallery = mySecureButtonList->CurrentItem(); //CCoeControl* myPacketPtr = this->Control(EPhotosPacketSizeListControlId); //CEikChoiceList* myPacketButtonList = static_cast<CEikChoiceList*>(myPacketPtr); //iPacketSize = myPacketButtonList->CurrentItem(); #ifdef __S80__ if (aKeycode == EDone3) #endif { if( iMode == 0) { CDesCArray* array; array = iAppUi.GetFolderList(); if(array != NULL ) { if(array->Count() != 0) { int answer; answer=iAppUi.FolderDialog1(); if(answer) { iAppUi.SetDefaultFolder(iAppUi.FolderName); } else { return EFalse; } } else { //array don't have any element iMode = iAppUi.GetMode(); iAppUi.ShowMessageBoxFromResource(R_EXAMPLE_TEXT_PROMPTMODE); } } else { //array is NULL case myVertOptionButtonList->SetCurrentItem(1); iMode = myVertOptionButtonList->CurrentItem(); #ifdef __S80__ if(iMode == 1) iMode = 2; #endif iAppUi.ShowMessageBoxFromResource(R_EXAMPLE_TEXT_FOLDERNOTEXIST); } } if(iMode == 0 || iMode == 2) iDescription = 0; iAppUi.SavePhotosSettingsToDB((TInt8)iMode, (TInt8)iDescription, (TInt8)iPhotoRoaming, (TInt8)iSecureGallery); if(iPhotoRoaming == 1) iAppUi.ShowMessageBoxFromResource(R_PHOTOS_MESSAGE1); //msg.Copy(*(iEikonEnv->AllocReadResourceL(R_PHOTOS_MESSAGE1))); else iAppUi.ShowMessageBoxFromResource(R_PHOTOS_MESSAGE2); //msg.Copy(*(iEikonEnv->AllocReadResourceL(R_PHOTOS_MESSAGE2))); //iEikonEnv->InfoWinL(*(iEikonEnv->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH)), msg); /*TInt8 choice=0; iAppUi.GetChoice(choice); if(choice == 0) iAppUi.CallSetupWizardStep10();*/ } return ETrue; } void CSecureSettingDialog::PreLayoutDynInitL() { TInt secureStart; TBuf<20>friendNumber; TBuf<200> secureText; TInt alarm; iAppUi.GetSecureSettingsFromFile(secureStart, friendNumber, secureText, alarm); CCoeControl* mySecurePtr = this->Control(ESecureAutoId); CEikChoiceList* mySecureList = static_cast<CEikChoiceList*>(mySecurePtr); mySecureList->SetCurrentItem(secureStart); CEikRichTextEditor* R1; R1 = STATIC_CAST(CEikRichTextEditor*,Control(ESecureMobileId)); R1->SetTextL(&friendNumber); CEikRichTextEditor* R2; R2 = STATIC_CAST(CEikRichTextEditor*,Control(ESecureTextId)); R2->SetTextL(&secureText); } TBool CSecureSettingDialog::ShutL() { return EFalse; } TInt CSecureSettingDialog::OkToExitL(TInt aKeycode) { TInt secureStart; TBuf<20>friendNumber; TBuf<200> secureText; //TBuf<300> msg; #ifdef __S80__ if (aKeycode == EDone1 || aKeycode == EDone2) { return EFalse; } #endif CCoeControl* mySecurePtr = this->Control(ESecureAutoId); CEikChoiceList* mySecureList = static_cast<CEikChoiceList*>(mySecurePtr); secureStart = mySecureList->CurrentItem(); #ifdef __S80__ if (aKeycode == EDone3) #endif { CEikRichTextEditor* R1=STATIC_CAST(CEikRichTextEditor*,Control(ESecureMobileId)); R1->GetText(friendNumber); CEikRichTextEditor* R2=STATIC_CAST(CEikRichTextEditor*,Control(ESecureTextId)); R2->GetText(secureText); if(secureStart == 1) iAppUi.ShowMessageBoxFromResource(R_SECURE_MESSAGE1); //msg.Copy(*(iEikonEnv->AllocReadResourceL(R_SECURE_MESSAGE1))); else iAppUi.ShowMessageBoxFromResource(R_SECURE_MESSAGE2); //msg.Copy(*(iEikonEnv->AllocReadResourceL(R_SECURE_MESSAGE2))); //iEikonEnv->InfoWinL(*(iEikonEnv->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH)), msg); iAppUi.SaveSecureSettingsToFile(secureStart, friendNumber, secureText, 1); } return ETrue; } void CCustomMessageDialog::PreLayoutDynInitL() { this->SetTitleL(iTitle); CEikLabel* label = (CEikLabel*)Control(ECustomMessageDialog); label->SetTextL(iText->Des()); } TBool CCustomMessageDialog::ShutL() { return EFalse; } TInt CCustomMessageDialog::OkToExitL(TInt aKeycode) { return ETrue; } void CContactsSettingDialog::PreLayoutDynInitL() { TInt contactroam; TInt contactupload; iAppUi.iSettingsScreenValue = 0; iAppUi.GetContactsSettingsFromDB(contactroam, contactupload); iAppUi.iContactsHandler->iContactsRoaming = contactroam; iAppUi.iContactsHandler->iContactsUpload = contactupload; CCoeControl* myControlPtr = this->Control(EContactsUploadControlId); CEikChoiceList* myVertOptionButtonList = static_cast<CEikChoiceList*>(myControlPtr); myVertOptionButtonList->SetCurrentItem(contactupload); CCoeControl* myControlPtr1 = this->Control(EContactsRoamListControlId); CEikChoiceList* myVertOptionButtonList1 = static_cast<CEikChoiceList*>(myControlPtr1); myVertOptionButtonList1->SetCurrentItem(contactroam); } TBool CContactsSettingDialog::ShutL() { return EFalse; } TInt CContactsSettingDialog::OkToExitL(TInt aKeycode) { TInt iContactRoaming; //TBuf<200> msg; #ifdef __S80__ if (aKeycode == EDone1 || aKeycode == EDone2) { return EFalse; } #else if (aKeycode == EEikBidCancel) { return -1; } #endif CCoeControl* myControlPtr = this->Control(EContactsUploadControlId); CEikChoiceList* myVertOptionButtonList = static_cast<CEikChoiceList*>(myControlPtr); iAppUi.iContactsHandler->iContactsUpload = myVertOptionButtonList->CurrentItem(); CCoeControl* myControlPtr1 = this->Control(EContactsRoamListControlId); CEikChoiceList* myVertOptionButtonList1 = static_cast<CEikChoiceList*>(myControlPtr1); iAppUi.iContactsHandler->iContactsRoaming = myVertOptionButtonList1->CurrentItem(); #ifdef __S80__ if (aKeycode == EDone3) #endif { //iAppUi.SaveContactsSettingsToDB((TInt8)iContactRoaming); if(iContactRoaming == 1) iAppUi.ShowMessageBoxFromResource(R_CONTACTS_MESSAGE1); //msg.Copy(*(iEikonEnv->AllocReadResourceL(R_CONTACTS_MESSAGE1))); else iAppUi.ShowMessageBoxFromResource(R_CONTACTS_MESSAGE2); //msg.Copy(*(iEikonEnv->AllocReadResourceL(R_CONTACTS_MESSAGE2))); //iEikonEnv->InfoWinL(*(iEikonEnv->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH)), msg); if(iAppUi.iContactsHandler->iContactsUpload == 1) { iAppUi.iSettingsScreenValue = 1; } else { iAppUi.SaveContactsSettingsToDB(iAppUi.iContactsHandler->iContactsRoaming,iAppUi.iContactsHandler->iContactsUpload); } } return ETrue; } void CChoiceListControl::PreLayoutDynInitL() { iAppUi.iSettingsScreenValue = 0; CCoeControl* myControlPtr = this->Control(EChoiceListControlId); #ifdef __S80__ CEikChoiceList* myVertOptionButtonList = static_cast<CEikChoiceList*>(myControlPtr); myVertOptionButtonList->SetCurrentItem(0); #else CQikVertOptionButtonList* myVertOptionButtonList = static_cast<CQikVertOptionButtonList*>(myControlPtr); myVertOptionButtonList->SetButtonById(0); #endif } TBool CChoiceListControl::ShutL() { return EFalse; } // --------------------------------------------------------- // CChoiceListControl::OkToExitL(TInt /*aKeycode*/) // // --------------------------------------------------------- TInt CChoiceListControl::OkToExitL(TInt aKeycode) { #ifdef __S80__ if (aKeycode == EDone1 || aKeycode == EDone2) { return EFalse; } #endif #ifdef __S80__ CCoeControl* myControlPtr = this->Control(EChoiceListControlId); CEikChoiceList* myVertOptionButtonList = static_cast<CEikChoiceList*>(myControlPtr); TInt iModelData = myVertOptionButtonList->CurrentItem(); #else CCoeControl* myControlPtr = this->Control(EChoiceListControlId); CQikVertOptionButtonList* myVertOptionButtonList = static_cast<CQikVertOptionButtonList*>(myControlPtr); TInt iModelData = myVertOptionButtonList->LabeledButtonId(); #endif #ifdef __S80__ if (aKeycode == EDone3) #endif { if(iModelData == 0) { iAppUi.iSettingsScreenValue = 1; } else if(iModelData == 1) { iAppUi.iSettingsScreenValue = 2; } } return ETrue; } // --------------------------------------------------------- // CMobileDialog::PreLayoutDynInitL() // // --------------------------------------------------------- void CMobileDialog::PreLayoutDynInitL() { TBuf<20> buf1; buf1.Zero(); buf1.Copy(_L("")); CEikRichTextEditor* R1; R1 = STATIC_CAST(CEikRichTextEditor*,Control(EMobileNumber)); R1->SetTextL(&buf1); } TBool CMobileDialog::ShutL() { return EFalse; } void CContactsUploadSettingDialog::PreLayoutDynInitL() { TInt days; TInt contactstime; TInt syncstate = 0; iAppUi.GetConatctsTimeFromDB(contactstime, days, syncstate); if(days == 0) days = 14; #ifdef __S80__ CCoeControl* myControlPtr = this->Control(EContactsUpload); CEikNumberEditor* myNumberEditor = static_cast<CEikNumberEditor*>(myControlPtr); myNumberEditor->SetNumber(days); #else CCoeControl* myControlPtr = this->Control(EContactsUpload); CQikNumberEditor* myNumberEditor = static_cast<CQikNumberEditor*>(myControlPtr); myNumberEditor->SetValueL(days); #endif } TInt CContactsUploadSettingDialog::OkToExitL(TInt aKeycode) { TInt days=0; TInt time=0; TInt syncstate = 0; #ifdef __S80__ // Get a pointer to the control. CCoeControl* myControlPtr = this->Control(EContactsUpload); CEikNumberEditor* myNumberEditor = static_cast<CEikNumberEditor*>(myControlPtr); days = myNumberEditor->Number(); #else // Get a pointer to the control. CCoeControl* myControlPtr = this->Control(EContactsUpload); CQikNumberEditor* myNumberEditor = static_cast<CQikNumberEditor*>(myControlPtr); days = myNumberEditor->Value(); #endif iAppUi.SaveConatctsTimeToDB(time, days, syncstate); iAppUi.SaveContactsSettingsToDB(iAppUi.iContactsHandler->iContactsRoaming,iAppUi.iContactsHandler->iContactsUpload); return ETrue; } // --------------------------------------------------------- // CMobileDialog::OkToExitL(TInt /*aKeycode*/) // // --------------------------------------------------------- TInt CMobileDialog::OkToExitL(TInt /*aKeycode*/) { TBuf<20> mobilenumber; //get the phonenumber CEikRichTextEditor* richTextEditor=STATIC_CAST(CEikRichTextEditor*,Control(EMobileNumber)); richTextEditor->GetText(mobilenumber); iAppUi.iTempMbNum.Copy(mobilenumber); return ETrue; } // --------------------------------------------------------- // CRegMobileDialog::PreLayoutDynInitL() // // --------------------------------------------------------- void CRegMobileDialog::PreLayoutDynInitL() { TBuf<20> buf1; buf1.Zero(); buf1.Copy(_L("")); CEikRichTextEditor* R1; R1 = STATIC_CAST(CEikRichTextEditor*,Control(EMobileNumber)); R1->SetTextL(&buf1); } TBool CRegMobileDialog::ShutL() { return EFalse; } // --------------------------------------------------------- // CRegMobileDialog::OkToExitL(TInt /*aKeycode*/) // // --------------------------------------------------------- TInt CRegMobileDialog::OkToExitL(TInt /*aKeycode*/) { TBuf<20> mobilenumber; //get the phonenumber CEikRichTextEditor* richTextEditor=STATIC_CAST(CEikRichTextEditor*,Control(EMobileNumber)); richTextEditor->GetText(mobilenumber); iAppUi.iMobileNo.Copy(mobilenumber); return ETrue; } // --------------------------------------------------------- // CCheckSimDialog::PreLayoutDynInitL() // // --------------------------------------------------------- void CCheckSimDialog::PreLayoutDynInitL() { TBuf<20> buf1; buf1.Zero(); buf1.Copy(_L("")); CEikRichTextEditor* R1; R1 = STATIC_CAST(CEikRichTextEditor*,Control(EUserName)); R1->SetTextL(&buf1); iAppUi.iSettingsScreenValue = 0; } TBool CCheckSimDialog::ShutL() { return EFalse; } // --------------------------------------------------------- // CCheckSimDialog::OkToExitL(TInt /*aKeycode*/) // // --------------------------------------------------------- TInt CCheckSimDialog::OkToExitL(TInt /*aKeycode*/) { TBuf<20> userid; TBuf<20> password; //get the userid CEikRichTextEditor* richTextEditor=STATIC_CAST(CEikRichTextEditor*,Control(EUserName)); richTextEditor->GetText(userid); //get the phonenumber CEikRichTextEditor* richTextEditor1=STATIC_CAST(CEikRichTextEditor*,Control(EPhoneNumber)); richTextEditor1->GetText(password); //iAppUi.GetUserSettings(pword); //iAppUi.GetUserSettings(iUserNames, iPassword, iMobileNo); if(userid.Compare(iAppUi.iUserNames)==0 && password.Compare(iAppUi.iPassword)==0) iAppUi.iSettingsScreenValue = 1; else iAppUi.iSettingsScreenValue = 0; return ETrue; } // --------------------------------------------------------- // CChangePassword::PreLayoutDynInitL() // // --------------------------------------------------------- void CChangePassword::PreLayoutDynInitL() { } TBool CChangePassword::ShutL() { return EFalse; } // --------------------------------------------------------- // CChangePassword::OkToExitL(TInt /*aKeycode*/) // // --------------------------------------------------------- TInt CChangePassword::OkToExitL(TInt /*aKeycode*/) { TBuf<20> newpassword; TBuf<20> oldpassword; CEikRichTextEditor* richTextEditor=STATIC_CAST(CEikRichTextEditor*,Control(EUserName)); richTextEditor->GetText(oldpassword); //get the phonenumber CEikRichTextEditor* richTextEditor1=STATIC_CAST(CEikRichTextEditor*,Control(EPhoneNumber)); richTextEditor1->GetText(newpassword); if (newpassword.Length() < 6) { iAppUi.ShowMessageBoxFromResource(R_TEXT_PASSWORD_WRONGLENGTH); return EFalse; } if(iAppUi.CheckPasswordField(newpassword)) { iAppUi.ShowMessageBoxFromResource(R_TEXT_INVALID_PASSWORD); return EFalse; } if (oldpassword.Length() && newpassword.Length()) { if(oldpassword.Compare(iAppUi.iPassword) == 0) { iAppUi.iNewPassword.Copy(newpassword); iAppUi.ChangePassword(); } else { iAppUi.ShowMessageBoxFromResource(R_TEXT_INVALID_PASSWORD); } } else { return EFalse; } return ETrue; } // --------------------------------------------------------- // CRegisterDialog::PreLayoutDynInitL() // // --------------------------------------------------------- void CRegisterDialog::PreLayoutDynInitL() { TBuf<30> buf1; buf1.Copy(iAppUi.iUserNames); CEikRichTextEditor* R1; R1 = STATIC_CAST(CEikRichTextEditor*,Control(EUserName)); R1->SetTextL(&buf1); } TBool CRegisterDialog::ShutL() { return EFalse; } // --------------------------------------------------------- // CRegisterDialog::OkToExitL(TInt /*aKeycode*/) // // --------------------------------------------------------- TInt CRegisterDialog::OkToExitL(TInt /*aKeycode*/) { TBuf<20> username1; TBuf<20> phonenumber1; //get the username CEikRichTextEditor* richTextEditor=STATIC_CAST(CEikRichTextEditor*,Control(EUserName)); richTextEditor->GetText(username1); //get the phonenumber richTextEditor=STATIC_CAST(CEikRichTextEditor*,Control(EPhoneNumber)); richTextEditor->GetText(phonenumber1); if (phonenumber1.Length() < 6) { iAppUi.ShowMessageBoxFromResource(R_TEXT_PASSWORD_WRONGLENGTH); return EFalse; } if(iAppUi.CheckPasswordField(phonenumber1)) { iAppUi.ShowMessageBoxFromResource(R_TEXT_INVALID_PASSWORD); return EFalse; } if (username1.Length() && phonenumber1.Length()) { if(iAppUi.CheckSpecialChars(username1,phonenumber1)) { //RegisterRipple(username1, phonenumber1); username1.LowerCase(); iAppUi.iUserNames.Copy(username1); iAppUi.iUserName.Copy(username1); iAppUi.iPassword.Copy(phonenumber1); if(iAppUi.iSettingsScreenValue == 1) iAppUi.NewUser(); else if(iAppUi.iSettingsScreenValue == 2) iAppUi.ExistingUser(); } else return EFalse; } else { return EFalse; } return ETrue; } // --------------------------------------------------------- // CAlreadyRegisterDialog::PreLayoutDynInitL() // // --------------------------------------------------------- void CAlreadyRegisterDialog::PreLayoutDynInitL() { TBuf<20> buf1; TBuf<20> buf2; TBuf<20> buf3; buf1.Zero(); buf2.Zero(); buf3.Zero(); buf1.Copy(iAppUi.iUserNames); CEikRichTextEditor* R1; R1 = STATIC_CAST(CEikRichTextEditor*,Control(EUserName)); R1->SetTextL(&buf1); CEikRichTextEditor* R2; R2 = STATIC_CAST(CEikRichTextEditor*,Control(EPhoneNumber)); R2->SetTextL(&buf2); //CEikRichTextEditor* R3; //R3 = STATIC_CAST(CEikRichTextEditor*,Control(EPassword)); //R3->SetTextL(&buf3); } TBool CAlreadyRegisterDialog::ShutL() { return EFalse; } // --------------------------------------------------------- // CAlreadyRegisterDialog::OkToExitL(TInt /*aKeycode*/) // // --------------------------------------------------------- TInt CAlreadyRegisterDialog::OkToExitL(TInt /*aKeycode*/) { TBuf<20> username1; TBuf<20> phonenumber1; TBuf<20> password1; //get the username CEikRichTextEditor* richTextEditor=STATIC_CAST(CEikRichTextEditor*,Control(EUserName)); richTextEditor->GetText(username1); //get the phonenumber //richTextEditor=STATIC_CAST(CEikRichTextEditor*,Control(EPhoneNumber)); //richTextEditor->GetText(phonenumber1); //get the phonenumber richTextEditor=STATIC_CAST(CEikRichTextEditor*,Control(EPhoneNumber)); richTextEditor->GetText(password1); if (password1.Length() < 6) { iAppUi.ShowMessageBoxFromResource(R_TEXT_PASSWORD_WRONGLENGTH); return EFalse; } if(iAppUi.CheckPasswordField(password1)) { iAppUi.ShowMessageBoxFromResource(R_TEXT_INVALID_PASSWORD); return EFalse; } if (username1.Compare(_L("")) == 0 || password1.Compare(_L("")) == 0) { return EFalse; } if (1)//username1.Compare(password1) == 0) { iAppUi.iUserNames.LowerCase(); iAppUi.iUserName.Copy(iAppUi.iUserNames); iAppUi.iPassword.Copy(password1); iAppUi.ExistingUser(); //RegisterRipple(username1, password1, phonenumber1); return ETrue; } else { CEikonEnv::Static ()->AlertWin(*(iEikonEnv->AllocReadResourceL(R_TEXT_PASSWORD_INCORRECT))); return EFalse; } return ETrue; } // --------------------------------------------------------- // CAdvancedDialog::PreLayoutDynInitL() // // --------------------------------------------------------- void CAdvancedDialog::PreLayoutDynInitL() { TInt iPort; TBuf<80> ip; TInt autostart; iAppUi.GetSettingsFromDB(ip, iPort, autostart); CCoeControl* myAutoPtr = this->Control(EAutoListControlId); CEikChoiceList* myAutoButtonList = static_cast<CEikChoiceList*>(myAutoPtr); myAutoButtonList->SetCurrentItem(autostart); } TBool CAdvancedDialog::ShutL() { return EFalse; } // --------------------------------------------------------- // CAdvancedDialog::OkToExitL(TInt aKeycode) // // --------------------------------------------------------- TInt CAdvancedDialog::OkToExitL(TInt aKeycode) { TBuf<80> ipAddress; TInt portValue; TInt iAutostart; #ifdef __S80__ if (aKeycode == EDone1 || aKeycode == EDone2) { return EFalse; } #else if (aKeycode == EEikBidCancel) { return -1; } #endif iAppUi.GetSettingsFromDB(ipAddress, portValue, iAutostart); CCoeControl* myAutoPtr = this->Control(EAutoListControlId); CEikChoiceList* myAutoButtonList = static_cast<CEikChoiceList*>(myAutoPtr); iAutostart = myAutoButtonList->CurrentItem(); #ifdef __S80__ if (aKeycode == EDone3) #endif { iAppUi.SaveSettingsToDB(ipAddress, (TUint16)portValue, (TInt8)iAutostart); } return ETrue; } // --------------------------------------------------------- // CAlreadyRegisterDialog::RegisterRipple(TDes& aUser, TDes& aPasswd, TDes& aPhone) // // --------------------------------------------------------- /* void CAlreadyRegisterDialog::RegisterRipple(TDes& aUser, TDes& aPasswd, TDes& aPhone) { //Already Registered TBuf8<1024> iRBuffer; iAppUi.iUserName.Copy(aUser); iAppUi.iUserNames.Copy(aUser); iAppUi.iMobileNo.Copy(aPhone); iAppUi.iPassword.Copy(aPasswd); iRBuffer.Copy(_L("<root>")); HBufC* currTime; TTime ctime; ctime.HomeTime(); currTime = GetTimeStamp(ctime); iRBuffer.Append(_L("<h>")); iRBuffer.Append(_L("<msgt>")); iRBuffer.Append(_L("eu")); iRBuffer.Append(_L("</msgt>")); iRBuffer.Append(_L("<msg></msg>")); iRBuffer.Append(_L("<uid>")); iRBuffer.Append(aUser); iRBuffer.Append(_L("</uid>")); iRBuffer.Append(_L("<hp>")); iRBuffer.Append(iAppUi.iMobileNo); iRBuffer.Append(_L("</hp>")); iRBuffer.Append(_L("<did>")); iRBuffer.Append(iAppUi.PhoneImei()); iRBuffer.Append(_L("</did>")); iRBuffer.Append(_L("<currec>")); iRBuffer.AppendNum(1); iRBuffer.Append(_L("</currec>")); iRBuffer.Append(_L("<totrec>")); iRBuffer.AppendNum(1); iRBuffer.Append(_L("</totrec>")); iRBuffer.Append(_L("<loc>en_us</loc>")); iRBuffer.Append(_L("<ctime>")); iRBuffer.Append(*currTime); iRBuffer.Append(_L("</ctime>")); iRBuffer.Append(_L("<lstime>")); iRBuffer.Append(_L("0")); iRBuffer.Append(_L("</lstime>")); iRBuffer.Append(_L("<synctype><mod>cs</mod><gran>contactlevel</gran>\ <adde>true</adde><upde>true</upde><dele>true</dele></synctype>")); iRBuffer.Append(_L("</h>")); iRBuffer.Append(_L("<b>")); iRBuffer.Append(_L("<hp>")); iRBuffer.Append(aPhone); iRBuffer.Append(_L("</hp>")); iRBuffer.Append(_L("<username>")); iRBuffer.Append(aUser); iRBuffer.Append(_L("</username>")); iRBuffer.Append(_L("<password>")); iRBuffer.Append(aPasswd); iRBuffer.Append(_L("</password>")); iRBuffer.Append(_L("</b>")); iRBuffer.Append(_L("</root>")); HBufC8* content_data; content_data=iRBuffer.AllocL(); TBuf8<10> content_l; content_l.Num(content_data->Length()); //iRBuffer.Copy(_L("GET /ripple/rippleservlet HTTP/1.0\r\nHOST:\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); iRBuffer.Append(_L(" HTTP/1.0\r\nHOST:")); iRBuffer.Append(iAppUi.iServerAddr); iRBuffer.Append(_L("\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); iRBuffer.Append(content_l); iRBuffer.Append(_L("\r\n\r\n")); iRBuffer.Append(*content_data); if (iSocketsEngine != NULL) { iSocketsEngine->Disconnect(); delete iSocketsEngine; iSocketsEngine = NULL; } // servername and port from iContactsAppUi iSocketsEngine = CSocketsEngineWriter::NewL(iAppUi); iSocketsEngine->SetServerName(iAppUi.ServerAddr()); iSocketsEngine->SetPort(iAppUi.ServerPort()); iSocketsEngine->iBuffer.Copy(iRBuffer); iSocketsEngine->Register(1); delete content_data; } */ // --------------------------------------------------------- // CRegisterDialog::RegisterRipple(TDes& aUser, TDes& aPhone ) // // --------------------------------------------------------- /* void CRegisterDialog::RegisterRipple(TDes& aUser, TDes& aPhone ) { //New User TBuf8<1024> iRBuffer; iAppUi.iUserName.Copy(aUser); iAppUi.iUserNames.Copy(aUser); iAppUi.iMobileNo.Copy(aPhone); iRBuffer.Copy(_L("<root>")); HBufC* currTime; TTime ctime; ctime.HomeTime(); currTime = GetTimeStamp(ctime); iRBuffer.Append(_L("<h>")); iRBuffer.Append(_L("<msgt>")); iRBuffer.Append(_L("reg")); iRBuffer.Append(_L("</msgt>")); iRBuffer.Append(_L("<msg></msg>")); iRBuffer.Append(_L("<uid>")); iRBuffer.Append(aUser); iRBuffer.Append(_L("</uid>")); iRBuffer.Append(_L("<hp>")); iRBuffer.Append(iAppUi.iMobileNo); iRBuffer.Append(_L("</hp>")); iRBuffer.Append(_L("<did>")); iRBuffer.Append(iAppUi.PhoneImei()); iRBuffer.Append(_L("</did>")); iRBuffer.Append(_L("<currec>")); iRBuffer.AppendNum(1); iRBuffer.Append(_L("</currec>")); iRBuffer.Append(_L("<totrec>")); iRBuffer.AppendNum(1); iRBuffer.Append(_L("</totrec>")); iRBuffer.Append(_L("<loc>en_us</loc>")); iRBuffer.Append(_L("<ctime>")); iRBuffer.Append(*currTime); iRBuffer.Append(_L("</ctime>")); iRBuffer.Append(_L("<lstime>")); iRBuffer.Append(_L("0")); iRBuffer.Append(_L("</lstime>")); iRBuffer.Append(_L("<synctype><mod>cs</mod><gran>contactlevel</gran>\ <adde>true</adde><upde>true</upde><dele>true</dele></synctype>")); iRBuffer.Append(_L("</h>")); iRBuffer.Append(_L("<b>")); iRBuffer.Append(_L("<hp>")); iRBuffer.Append(aPhone); iRBuffer.Append(_L("</hp>")); iRBuffer.Append(_L("<username>")); iRBuffer.Append(aUser); iRBuffer.Append(_L("</username>")); //iRBuffer.Append(_L("</registration>")); iRBuffer.Append(_L("</b>")); iRBuffer.Append(_L("</root>")); HBufC8* content_data; content_data=iRBuffer.AllocL(); TBuf8<10> content_l; content_l.Num(content_data->Length()); //iRBuffer.Copy(_L("GET /ripple/rippleservlet HTTP/1.0\r\nHOST:\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); iRBuffer.Append(_L(" HTTP/1.0\r\nHOST:")); iRBuffer.Append(iAppUi.iServerAddr); iRBuffer.Append(_L("\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); iRBuffer.Append(content_l); iRBuffer.Append(_L("\r\n\r\n")); iRBuffer.Append(*content_data); if (iSocketsEngine != NULL) { iSocketsEngine->Disconnect(); delete iSocketsEngine; iSocketsEngine = NULL; } // servername and port from iPhotosAppUi iSocketsEngine = CSocketsEngineWriter::NewL(iAppUi); iSocketsEngine->SetServerName(iAppUi.ServerAddr()); iSocketsEngine->SetPort(iAppUi.ServerPort()); iSocketsEngine->iBuffer.Copy(iRBuffer); iSocketsEngine->Register(0); delete content_data; } */ // --------------------------------------------------------- // CFolderDialog::PreLayoutDynInitL() // // --------------------------------------------------------- void CFolderDialog::PreLayoutDynInitL() { //FolderList = new (ELeave) CDesCArrayFlat(20); FolderList=iAppUi.GetFolderList(); /*CEikChoiceList* FolderEditor = STATIC_CAST(CEikChoiceList*,Control(EFolderList)); FolderEditor->SetArrayL(FolderList); CEikRichTextEditor* richTextEditor=STATIC_CAST(CEikRichTextEditor*,Control(EFolderName)); richTextEditor->MakeVisible(EFalse);*/ CCoeControl* myControlPtr = this->Control(EFolderList); CEikComboBox* myComboBox = static_cast<CEikComboBox*>(myControlPtr); // Set the control with the array identified by the specified id. myComboBox->SetArray(FolderList); } TBool CFolderDialog::ShutL() { return EFalse; } // --------------------------------------------------------- // CFolderDialog::OkToExitL(TInt aKeycode) // // --------------------------------------------------------- TInt CFolderDialog::OkToExitL(TInt aKeycode) { // TBuf<20> Name; TBuf<20> Name1; #ifdef __S80__ if (aKeycode == EDone1 || aKeycode == EDone2) { return EFalse; } #endif //get the fodlername CEikComboBox* FolderEditor = STATIC_CAST(CEikComboBox*,Control(EFolderList)); FolderEditor->GetText(Name1); #ifdef __S80__ if(aKeycode == EDone3 && Name1.Length()==0) return EFalse; #else if(Name1.Length()==0) return EFalse; #endif iAppUi.FolderName.Copy(Name1); /*CEikRichTextEditor* richTextEditor=STATIC_CAST(CEikRichTextEditor*,Control(EFolderName)); richTextEditor->GetText(Name); CEikChoiceList* FolderEditor = STATIC_CAST(CEikChoiceList*,Control(EFolderList)); if (FolderList) { TInt aListPos = FolderEditor->CurrentItem(); if ( aListPos > 0) { Name1.Copy((*FolderList)[aListPos]); } else { Name1.Copy((*FolderList)[0]); } }*/ /*if(iAppUi.GetMode() == 0) { CDesCArray* array; TInt aPos; TInt flg = 0; array = iAppUi.GetFolderList(); if(array != NULL) { if(array->Find(Name1, aPos) == 0) { iAppUi.FolderName.Copy(Name1); flg = 0; } else { iAppUi.ShowMessageBoxFromResource(R_EXAMPLE_TEXT_FOLDERNOTEXIST); flg = 1; } } else { iAppUi.ShowMessageBoxFromResource(R_EXAMPLE_TEXT_FOLDERNOTEXIST); flg = 1; } if( flg == 1) { return EFalse; } } else { if (Name.Length()) { iAppUi.FolderName.Copy(Name); } else { if (FolderList) { TInt item = FolderEditor->CurrentItem(); if ( item > 0) { iAppUi.FolderName.Copy((*FolderList)[item]); } else { iAppUi.FolderName.Copy((*FolderList)[0]); } } else { return EFalse; } } }*/ return ETrue; } void CProcessAlbumDialog::PreLayoutDynInitL() { iAppUi.iSettingsScreenValue = -1; } TBool CProcessAlbumDialog::ShutL() { return EFalse; } // --------------------------------------------------------- // CFolderDialog::OkToExitL(TInt aKeycode) // // --------------------------------------------------------- TInt CProcessAlbumDialog::OkToExitL(TInt aKeycode) { #ifdef __S80__ if (aKeycode == EDone1 || aKeycode == EDone2) { return EFalse; } #endif CCoeControl* myAutoPtr = this->Control(EProcessImageListId); CEikChoiceList* myAutoButtonList = static_cast<CEikChoiceList*>(myAutoPtr); iAppUi.iSettingsScreenValue = myAutoButtonList->CurrentItem(); return ETrue; } // --------------------------------------------------------- // CFolderDialog1::PreLayoutDynInitL() // // --------------------------------------------------------- void CFolderDialog1::PreLayoutDynInitL() { //FolderList = new (ELeave) CDesCArrayFlat(20); FolderList=iAppUi.GetFolderList(); CEikChoiceList* FolderEditor = STATIC_CAST(CEikChoiceList*,Control(EFolderList)); FolderEditor->SetArrayL(FolderList); } TBool CFolderDialog1::ShutL() { return EFalse; } // --------------------------------------------------------- // CFolderDialog1::OkToExitL(TInt aKeycode) // // --------------------------------------------------------- TInt CFolderDialog1::OkToExitL(TInt aKeycode) { TBuf<20> Name1; #ifdef __S80__ if (aKeycode == EDone1 || aKeycode == EDone2) { return EFalse; } #endif CEikChoiceList* FolderEditor = STATIC_CAST(CEikChoiceList*,Control(EFolderList)); if (FolderList) { TInt aListPos = FolderEditor->CurrentItem(); if ( aListPos > 0) { Name1.Copy((*FolderList)[aListPos]); } else { Name1.Copy((*FolderList)[0]); } } #ifdef __S80__ if (aKeycode == EDone3) #endif { if(iAppUi.GetMode() == 0) { CDesCArray* array; TInt aPos; TInt flg = 0; array = iAppUi.GetFolderList(); if(array != NULL) { if(array->Find(Name1, aPos) == 0) { iAppUi.FolderName.Copy(Name1); flg = 0; } else { iAppUi.ShowMessageBoxFromResource(R_EXAMPLE_TEXT_FOLDERNOTEXIST); flg = 1; } } else { iAppUi.ShowMessageBoxFromResource(R_EXAMPLE_TEXT_FOLDERNOTEXIST); flg = 1; } if( flg == 1) { return EFalse; } } } return ETrue; } // --------------------------------------------------------- // CUnShareAlbumDialog::PreLayoutDynInitL() // // --------------------------------------------------------- void CUnShareAlbumDialog::PreLayoutDynInitL() { //FolderList = new (ELeave) CDesCArrayFlat(20); FolderList=iAppUi.GetFolderList(); CEikChoiceList* FolderEditor = STATIC_CAST(CEikChoiceList*,Control(EFolderList)); FolderEditor->SetArrayL(FolderList); } TBool CUnShareAlbumDialog::ShutL() { return EFalse; } // --------------------------------------------------------- // CUnShareAlbumDialog::OkToExitL(TInt aKeycode) // // --------------------------------------------------------- TInt CUnShareAlbumDialog::OkToExitL(TInt aKeycode) { #ifdef __S80__ if (aKeycode == EDone1 || aKeycode == EDone2) { return EFalse; } #endif #ifdef __S80__ if (aKeycode == EDone3) #endif { CEikChoiceList* FolderEditor = STATIC_CAST(CEikChoiceList*,Control(EFolderList)); if (FolderList) { TInt aListPos = FolderEditor->CurrentItem(); if ( aListPos > 0) { iAppUi.albumName.Copy((*FolderList)[aListPos]); } else { iAppUi.albumName.Copy((*FolderList)[0]); } #ifdef __S80__ if(CCknConfirmationDialog::RunDlgLD(*(iEikonEnv->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH)),*(iEikonEnv->AllocReadResourceL(R_TEXT_UNSHARE_ALBUM_CONFIRM)))) iAppUi.GetUnSharingAlbumXML(); #else CEikDialog* dialog; dialog = new (ELeave) CCustomMessageDialog(*(iEikonEnv->AllocReadResourceL(R_TEXT_UNSHARE_ALBUM_CONFIRM)), R_EXAMPLE_RIPPLE_PUBLISH); if(dialog->ExecuteLD(R_EIK_DIALOG_YESNO_INFO)) iAppUi.GetUnSharingAlbumXML(); #endif } } return ETrue; } // --------------------------------------------------------- // CSharingListBoxDialog::PreLayoutDynInitL() // // --------------------------------------------------------- void CSharingListBoxDialog::PreLayoutDynInitL() { FolderList=iAppUi.GetFolderList(); CEikChoiceList* FolderEditor = STATIC_CAST(CEikChoiceList*,Control(EFolderList)); FolderEditor->SetArrayL(FolderList); } TBool CSharingListBoxDialog::ShutL() { return EFalse; } // --------------------------------------------------------- // CSharingListBoxDialog::OkToExitL(TInt aKeycode) // // --------------------------------------------------------- TInt CSharingListBoxDialog::OkToExitL(TInt aKeycode) { #ifdef __S80__ if (aKeycode == EDone1 || aKeycode == EDone2) { return EFalse; } #endif #ifdef __S80__ if (aKeycode == EDone3) #endif { CEikChoiceList* FolderEditor = STATIC_CAST(CEikChoiceList*,Control(EFolderList)); if (FolderList) { TInt aListPos = FolderEditor->CurrentItem(); if ( aListPos > 0) { iAppUi.albumName.Copy((*FolderList)[aListPos]); } else { iAppUi.albumName.Copy((*FolderList)[0]); } } CEikRichTextEditor* richTextEditor=STATIC_CAST(CEikRichTextEditor*,Control(ESendNames)); richTextEditor->GetText(iAppUi.iMessage); } return ETrue; } // --------------------------------------------------------- // CDescDialog::PreLayoutDynInitL() // // --------------------------------------------------------- void CDescDialog::PreLayoutDynInitL() { } TBool CDescDialog::ShutL() { return EFalse; } // --------------------------------------------------------- // CDescDialog::OkToExitL(TInt aKeycode) // // --------------------------------------------------------- TInt CDescDialog::OkToExitL(TInt aKeycode) { TBuf<150> Name; //get the descname CEikRichTextEditor* richTextEditor=STATIC_CAST(CEikRichTextEditor*,Control(EDescName)); richTextEditor->GetText(Name); iAppUi.DescName.Copy(Name); return ETrue; } // --------------------------------------------------------- // CAdvancedDialog::SetAccessPoints() // // --------------------------------------------------------- //void CAdvancedDialog::SetAccessPoints() //{ // RGenericAgent netAgent1; // if (netAgent1.Open() == KErrNone) // { // // CCommsDbConnectionPrefTableView::TCommDbIapConnectionPref pref; // // pref.iRanking = 1; // pref.iDirection = ECommDbConnectionDirectionOutgoing; // pref.iDialogPref = ECommDbDialogPrefDoNotPrompt; // // CCommsDbConnectionPrefTableView::TCommDbIapBearer bearer; // bearer.iBearerSet = ECommDbBearerGPRS; // // bearer.iIapId = 12; // pref.iBearer = bearer; // // CCommDbOverrideSettings* aSettings; // // aSettings = CCommDbOverrideSettings::NewL(CCommDbOverrideSettings::EParamListFull); // aSettings->SetConnectionPreferenceOverride(pref); // // } //} // --------------------------------------------------------- // CAdvancedDialog::GetAccessPoints() // // --------------------------------------------------------- /* void CAdvancedDialog::GetAccessPoints() { int count=1; int val; RGenericAgent netAgent; if (netAgent.Open() == KErrNone) { TBuf<50> Name; TBuf<50> test; TUint32 ida=0; TUint32 ida1=0; TBuf<20> TableName; TableName.Copy(_L("IAP")); TBuf<20> ColName1; ColName1.Copy(_L("Id")); TBuf<20> ColName2; ColName2.Copy(_L("Name")); CleanupClosePushL(netAgent); CCommsDatabase* db=CCommsDatabase::NewL(EDatabaseTypeIAP); CleanupStack::PushL(db); CCommsDbConnectionPrefTableView* view1 = db->OpenConnectionPrefTableViewOnRankLC(ECommDbConnectionDirectionOutgoing,1); CCommsDbConnectionPrefTableView::TCommDbIapConnectionPref pref; if(view1->GotoFirstRecord()!=KErrNotFound) { view1->ReadConnectionPreferenceL(pref); ida=pref.iBearer.iIapId; } CCommsDbTableView* view = db->OpenTableLC(TableName); if(view->GotoFirstRecord()!=KErrNotFound) { do { view->ReadUintL(ColName1, ida1); view->ReadTextL(ColName2, Name); if(ida==ida1) { array->InsertL(0,Name); ApNum[0]=ida1; val=ApNum[0]; test.AppendNum(val); } else { array->AppendL(Name); ApNum[count]=ida1; val=ApNum[count]; test.AppendNum(val); count++; } } while(view->GotoNextRecord()!=KErrNotFound); } CleanupStack::PopAndDestroy(4); // view, db, netAgent } } */ // --------------------------------------------------------- // CRippleVaultAppUi::FolderDialog() // // --------------------------------------------------------- TInt CRippleVaultAppUi::FolderDialog() { CEikDialog* folderdialog; TInt err; //TBuf<30> temp; folderdialog = new (ELeave) CFolderDialog(*this); //err = dialog->ExecuteLD(R_FOLDER_DIALOG); folderdialog->PrepareLC(R_FOLDER_DIALOG); //iPhotoCount = iPhotoCount * 3; // TInt price; // TLex lex(iCharge); // lex.Val(price); // iPhotoCount = iPhotoCount * price; // temp.Copy(_L("Charge ")); // temp.AppendNum(iPhotoCount); // temp.Append(_L(" Pesos")); //temp.Copy(_L("Select Album:")); //folderdialog->SetTitleL(temp); err = folderdialog->RunLD(); return err; } TInt CRippleVaultAppUi::ProcessAlbum() { CEikDialog* folderdialog; TInt err; folderdialog = new (ELeave) CProcessAlbumDialog(*this); folderdialog->PrepareLC(R_PROCESS_IMAGE_DIALOG); err = folderdialog->RunLD(); return iSettingsScreenValue; } // --------------------------------------------------------- // CRippleVaultAppUi::FolderDialog1() // // --------------------------------------------------------- TInt CRippleVaultAppUi::FolderDialog1() { CEikDialog* folderdialog1; TInt err; folderdialog1 = new (ELeave) CFolderDialog1(*this); err = folderdialog1->ExecuteLD(R_FOLDER_DIALOG1); return err; } // --------------------------------------------------------- // CRippleVaultAppUi::SharingListBoxDialog() // // --------------------------------------------------------- void CRippleVaultAppUi::SharingListBoxDialog(TInt aCount) { CEikDialog* sharelistdialog; TInt err; sharelistdialog = new (ELeave) CSharingListBoxDialog(*this); err = sharelistdialog->ExecuteLD(R_SHARING_LISTBOX_DIALOG); if(err) { SaveMails(albumName,MailNames,MailId,iMessage,aCount); GetSharingAlbumXML(); } } // --------------------------------------------------------- // CRippleVaultAppUi::DescDialog() // // --------------------------------------------------------- TInt CRippleVaultAppUi::DescDialog() { CEikDialog* descdialog; TInt err; descdialog = new (ELeave) CDescDialog(*this); err = descdialog->ExecuteLD(R_DESC_DIALOG); return err; } // --------------------------------------------------------- // CRippleVaultAppUi::GetTimeStamp(TTime& aTime) // // --------------------------------------------------------- /* HBufC* CRegisterDialog::GetTimeStamp(TTime& aTime) { TBuf<256> timestamp; TDateTime janNineteenSeventy(1970,EJanuary,0,00,00,00,000000); TTime timejan(janNineteenSeventy); TTimeIntervalMicroSeconds interval = aTime.MicroSecondsFrom(timejan); TInt64 k; k=interval.Int64()/1000; timestamp.Num(k); HBufC* ts = NULL; ts = timestamp.AllocLC(); CleanupStack::Pop(); return (ts); } // --------------------------------------------------------- // CRippleVaultAppUi::GetTimeStamp(TTime& aTime) // // --------------------------------------------------------- HBufC* CAlreadyRegisterDialog::GetTimeStamp(TTime& aTime) { TBuf<256> timestamp; TDateTime janNineteenSeventy(1970,EJanuary,0,00,00,00,000000); TTime timejan(janNineteenSeventy); TTimeIntervalMicroSeconds interval = aTime.MicroSecondsFrom(timejan); TInt64 k; k=interval.Int64()/1000; timestamp.Num(k); HBufC* ts = NULL; ts = timestamp.AllocLC(); CleanupStack::Pop(); return (ts); } */ // --------------------------------------------------------- // CRippleVaultAppUi::GetTextFieldFromFieldSet(CContactItemFieldSet& aFieldSet, const TUid aField,TDesC& name) // // --------------------------------------------------------- void CRippleVaultAppUi::GetTextFieldFromFieldSet(CContactItemFieldSet& aFieldSet, const TUid aField,TDesC& name) { TInt index = aFieldSet.Find(aField); if ((index >= 0) && (index < aFieldSet.Count())) { CContactItemField& textfield = aFieldSet[index]; CContactTextField* textValue = textfield.TextStorage(); ((TDes&)name).Copy(textValue->Text()); } } #endif // --------------------------------------------------------- // CRippleVaultAppUi::SelectAccess() // // --------------------------------------------------------- void CRippleVaultAppUi::SelectAccess() { TUint32 aIAPId=0; /* #ifndef __UIQ__ CIntConnectionInitiator *iInitConn; iInitConn = CIntConnectionInitiator::NewL(); iInitConn->GetActiveIap(aIAPId); #endif */ if(aIAPId ==0 ) { //TBuf<150> msg; //msg.Copy(*(iEikonEnv->AllocReadResourceL(R_VAULT_MESSAGE))); #ifndef __UIQ__ CAknMessageQueryDialog* dlg = CAknMessageQueryDialog::NewL(*(iEikonEnv->AllocReadResourceL(R_VAULT_MESSAGE))); dlg->PrepareLC(R_ACCESS_POINT); dlg->RunLD(); #else //TBuf<150> msgtitle; //msgtitle.Copy(*(iEikonEnv->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH))); //iEikonEnv->InfoWinL(*(iEikonEnv->AllocReadResourceL(R_TEXT_SETUP_WIZARD)), *(iEikonEnv->AllocReadResourceL(R_VAULT_MESSAGE))); #ifdef __S80__ CCknInfoDialog::RunDlgLD(*(iEikonEnv->AllocReadResourceL(R_TEXT_SETUP_WIZARD)), *iEikonEnv->AllocReadResourceL(R_VAULT_MESSAGE)); #else CEikDialog* dialog; dialog = new (ELeave) CCustomMessageDialog(*(iEikonEnv->AllocReadResourceL(R_VAULT_MESSAGE)), R_TEXT_SETUP_WIZARD); dialog->ExecuteLD(R_EIK_DIALOG_CONTINUE_INFO); #endif #endif #ifndef __UIQ__ CAknMessageQueryDialog* dlg1 = CAknMessageQueryDialog::NewL(*(iEikonEnv->AllocReadResourceL(R_VAULT_MESSAGE1))); dlg1->PrepareLC(R_ACCESS_POINT); dlg1->SetHeaderTextL(*(iEikonEnv->AllocReadResourceL(R_SETUP_WIZARD_STEP_1))); dlg1->RunLD(); #else //TBuf<150> msgtitle; //msgtitle.Copy(*(iEikonEnv->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH))); //iEikonEnv->InfoWinL(*(iEikonEnv->AllocReadResourceL(R_SETUP_WIZARD_STEP_1)), *(iEikonEnv->AllocReadResourceL(R_VAULT_MESSAGE1))); #ifdef __S80__ CCknInfoDialog::RunDlgLD(*(iEikonEnv->AllocReadResourceL(R_SETUP_WIZARD_STEP_1)), *iEikonEnv->AllocReadResourceL(R_VAULT_MESSAGE1)); #else CEikDialog* dialog1; dialog1 = new (ELeave) CCustomMessageDialog(*(iEikonEnv->AllocReadResourceL(R_VAULT_MESSAGE1)), R_TEXT_SETUP_WIZARD); dialog1->ExecuteLD(R_EIK_DIALOG_CONTINUE_INFO); #endif #endif // TRequestStatus status; RGenericAgent netAgent; if (netAgent.Open() == KErrNone) { CleanupClosePushL(netAgent); //KillBrowser(); if(netAgent.Stop()==KErrNone)//; { CCommsDatabase* db=CCommsDatabase::NewL(EDatabaseTypeIAP); CleanupStack::PushL(db); CCommsDbConnectionPrefTableView* // view = db->OpenConnectionPrefTableViewOnRankLC(ECommDbConnectionDirectionOutgoing,0); view = db->OpenConnectionPrefTableInRankOrderLC(ECommDbConnectionDirectionOutgoing); if(view->GotoFirstRecord()!=KErrNotFound) { // TBuf8<40> log; // log.Copy(_L("startaccess")); // WriteLogFile(log); /*view->UpdateDialogPrefL(ECommDbDialogPrefPrompt); TRequestStatus status1; netAgent.StartOutgoing(status1); User::WaitForRequest(status1);*/ view->UpdateDialogPrefL(ECommDbDialogPrefDoNotPrompt); } CleanupStack::PopAndDestroy(3); // view, db, netAgent } else{ CleanupStack::PopAndDestroy(); // netAgent } } } } void CRippleVaultAppUi::SelectAccessSettings() { TUint32 aIAPId=0; if(aIAPId ==0 ) { RGenericAgent netAgent; if (netAgent.Open() == KErrNone) { CleanupClosePushL(netAgent); if(netAgent.Stop()==KErrNone)//; { CCommsDatabase* db=CCommsDatabase::NewL(EDatabaseTypeIAP); CleanupStack::PushL(db); CCommsDbConnectionPrefTableView* // view = db->OpenConnectionPrefTableViewOnRankLC(ECommDbConnectionDirectionOutgoing,0); view = db->OpenConnectionPrefTableInRankOrderLC(ECommDbConnectionDirectionOutgoing); if(view->GotoFirstRecord()!=KErrNotFound) { // TBuf8<40> log; // log.Copy(_L("startaccess")); // WriteLogFile(log); view->UpdateDialogPrefL(ECommDbDialogPrefPrompt); TRequestStatus status1; netAgent.StartOutgoing(status1); User::WaitForRequest(status1); view->UpdateDialogPrefL(ECommDbDialogPrefDoNotPrompt); } CleanupStack::PopAndDestroy(3); // view, db, netAgent } else{ CleanupStack::PopAndDestroy(); // netAgent } } } } // --------------------------------------------------------- // CRippleVaultAppUi::UserRegistered() // Called after registration is complete // --------------------------------------------------------- void CRippleVaultAppUi::UserRegistered() { TTime btime; btime.HomeTime(); iPhotosDB->UpdateBackupTimestampToDB(btime); iSetupWizardScreenValue = 1; CreateInitUploadFileL(); SaveApnID(iApnID); #ifdef __UIQ__ #ifdef __S80__ iMode = MODE_OFF; #else iMode = MODE_PROMPT; #endif iDescription=0; iRoaming=0; iSecureGallery=1; //GetSmsSettingsFromDB(iSmsMode,iSmsTime,iSmsRoam); TInt smstype; TTime time; TInt smsroam; TInt iContactRoaming=0; TInt iContactsUpload=0; GetSmsSettingsFromDB(smstype, time, smsroam); iSmsMode = smstype; iSmsTime = time; iSmsRoam = smsroam; iSmsMode = 1; iSmsRoam = 0; iContactRoaming = 0; _LIT(KTimeString,"12:00.00am"); TInt returnvalue=iSmsTime.Parse(KTimeString); SaveSettingsToDB(iServerAddr, iPort, iAutostart); SaveContactsSettingsToDB((TInt8)iContactRoaming, (TInt8)iContactsUpload); SavePhotosSettingsToDB(iMode, iDescription, iRoaming, iSecureGallery); SaveSmsSettingsToDB(iSmsMode,iSmsTime,iSmsRoam); /*TInetAddr Addr; TInt port; TInt autostart; GetSettingsFromDB(iServerAddr, port, autostart); iPort = port; Addr.Input(iServerAddr); iAutostart = autostart; SaveSettingsToDB(iServerAddr, iPort, iAutostart);*/ ShowWindow(KViewIdStatusScreen); //main screen DeleteWindow(KViewIdUnregisterScreen); //unregisterview /*iSettingsString.Copy(_L("")); TBuf<60> tmpstr; tmpstr.Copy(_L("settings")); LoadFromConfigFile(iSettingsString,tmpstr ); if(iSettingsString.Length() == 0){ CallSetupWizardStep1(); } else{ SaveChoice(1); SaveSettingsString(); }*/ CallSetupWizardUploadAll(); //SaveChoice(1); #else //iPrevViewId = TUid::Uid(15); iPrevViewId = KViewIdStatusScreen; //TInetAddr Addr; //TInt port; //TInt mode; TInt desc=1; TInt roam=0; TInt autostart = 1; TInt securegallery = 1; #ifdef __LOGME__ LogText.Copy(_L("serverip1=")); LogText.Append(iServerAddr); LogText.Append(_L("\n")); WriteLogFile(LogText); #endif // GetSettingsFromDB(iServerAddr, port, mode, desc, roam, autostart); //GetSettingsFromDB(iServerAddr, port, autostart); //GetPhotosSettingsFromDB(mode, desc, roam, securegallery); #ifdef __LOGME__ LogText.Copy(_L("serverip2=")); LogText.Append(iServerAddr); LogText.Append(_L("\n")); WriteLogFile(LogText); #endif //iPort = port; //Addr.Input(iServerAddr); iMode = MODE_PROMPT; iDescription=desc; iRoaming=roam; iAutostart = autostart; iSecureGallery = securegallery; iSmsMode = 1; iSmsRoam = 0; _LIT(KTimeString,"12:00.00am"); TInt returnvalue=iSmsTime.Parse(KTimeString); #ifdef __LOGME__ LogText.Copy(_L("serverip3=")); LogText.Append(iServerAddr); LogText.Append(_L("\n")); WriteLogFile(LogText); #endif SaveSettingsToDB(iServerAddr, iPort, iAutostart); SavePhotosSettingsToDB(iMode, iDescription, iRoaming, iSecureGallery); SaveSmsSettingsToDB(iSmsMode,iSmsTime,iSmsRoam); ActivateLocalViewL(KViewIdStatusScreen); //iPrevViewId = TUid::Uid(15); //ActivateLocalViewL(TUid::Uid(15)); #endif } // --------------------------------------------------------- // CRippleVaultAppUi::SetTitle() // set the app title // --------------------------------------------------------- /* void CRippleVaultAppUi::SetTitle() { #ifndef __UIQ__ CEikStatusPane* statusPane=iEikonEnv->AppUiFactory()->StatusPane(); statusPane->SwitchLayoutL(R_AVKON_STATUS_PANE_LAYOUT_USUAL); CAknTitlePane* tp=(CAknTitlePane*)statusPane->ControlL(TUid::Uid(EEikStatusPaneUidTitle)); //tp->SetTextL(_L("Ripple Vault")); tp->SetTextL(*(iEikonEnv->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH))); #endif } */ // --------------------------------------------------------- // CRippleVaultAppUi::ActivateView(TInt aViewId) // active view given an id // --------------------------------------------------------- void CRippleVaultAppUi::ActivateView(TUid aViewId) { #ifndef __UIQ__ if(aViewId != KViewIdEmptyScreen) iPrevViewId = aViewId;//TUid::Uid(aViewId); //ActivateLocalViewL(TUid::Uid(aViewId)); ActivateLocalViewL(aViewId); #endif } // --------------------------------------------------------- // CRippleVaultAppUi::ShowMessageBoxFromResource(TInt aResourceId) // show message box from resource // --------------------------------------------------------- void CRippleVaultAppUi::ShowMessageBoxFromResource(TInt aResourceId) { //HBufC* message; //message = iEikonEnv->AllocReadResourceL(aResourceId); #ifndef __UIQ__ CAknMessageQueryDialog* verdlg = CAknMessageQueryDialog::NewL(*iEikonEnv->AllocReadResourceL(aResourceId)); verdlg->PrepareLC(R_ABOUT_QUERY); verdlg->RunLD(); #else //CEikonEnv::Static()->InfoWinL(*(iEikonEnv->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH)),*iEikonEnv->AllocReadResourceL(aResourceId)); #ifdef __S80__ CCknInfoDialog::RunDlgLD(*(iEikonEnv->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH)), *iEikonEnv->AllocReadResourceL(aResourceId)); #else CEikDialog* dialog; dialog = new (ELeave) CCustomMessageDialog(*(iEikonEnv->AllocReadResourceL(aResourceId)), R_EXAMPLE_RIPPLE_PUBLISH); dialog->ExecuteLD(R_EIK_DIALOG_CONTINUE_INFO); #endif #endif // CEikonEnv::Static ()->InfoWinL(_L("Ripple Vault:"),*message); //delete message; } // --------------------------------------------------------- // CRippleVaultAppUi::CheckPasswordField(TDesC& password) // check if password is numeric // --------------------------------------------------------- #ifdef __UIQ__ TInt CRippleVaultAppUi::CheckPasswordField(TDesC& password) { TInt length; TInt flag=0; length = password.Length(); for(int i=0; i<length; i++) { if(password[i] == '1' || password[i] == '2' || password[i] == '3' || password[i] == '4' || password[i] == '5' || password[i] == '6' || password[i] == '7' || password[i] == '8' || password[i] == '9' || password[i] == '0') { flag = 0; } else { flag = 1; break; } } if(flag == 0) { return 0; } else return 0; } #endif // --------------------------------------------------------- // CRippleVaultAppUi::ImageFolderPath() // Return iStoragePath // --------------------------------------------------------- TInt CRippleVaultAppUi::ImageFolderPath() { return iStoragePath; } // --------------------------------------------------------------------------- // CRippleVaultAppUi::ApplicationDriveAndPath() // // Get the application path and drive. It must be done differently in the // development environment and in the device. // --------------------------------------------------------------------------- // TFileName CRippleVaultAppUi::ApplicationDriveAndPath() { #if 1 //#define EMULATOR //For testing TFileName appfullname(CEikonEnv::Static()->EikAppUi()->Application()->AppFullName()); TParse parse; #ifdef __UIQ__ #ifdef __WINSCW__ // On development environment the AppFullName points to z drive. // Replace it to point to C drive, which is writable by our application. parse.Set(_L("c:"), &appfullname, NULL); #else // In device use the application fullname directly. parse.Set(appfullname, NULL, NULL); #endif #else //series 60 code. #ifdef EMULATOR // On development environment the AppFullName points to z drive. // Replace it to point to C drive, which is writable by our application. parse.Set(_L("c:"), &appfullname, NULL); #else // In device use the application fullname directly. parse.Set(appfullname, NULL, NULL); #endif #endif//__UIQ__ TFileName fn = parse.DriveAndPath(); // Make sure the path exists (create if not). This is needed in EMULATOR. BaflUtils::EnsurePathExistsL(CCoeEnv::Static()->FsSession(), fn); #else TFileName fn; fn.Copy(_L("c:\\system\\apps\\RippleVault\\")); #endif return fn; } // --------------------------------------------------------- // CRippleVaultAppUi::LoadFromConfigFile(TDes& aValue, TDesC& aParam) // Load Parameter value from Config File // --------------------------------------------------------- TBool CRippleVaultAppUi::LoadFromConfigFile(TDes& aValue, TDesC& aParam) { RFs fs; RFile file; TBool ret = FALSE; fs.Connect(); TBuf<128> path; path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KConfigFile); if (BaflUtils::FileExists(fs, path)) { TInt err = file.Open(fs, path, EFileRead|EFileShareAny); if (err == KErrNone) { TBuf8<2> buf; TBuf<2> buf16; TBuf<150> line; TBuf<150> param; param.Copy(aParam); param.Append(_L("=")); TInt len = param.Length(); line.Copy(_L("")); TInt count = 0; do { /*TInt readErr = */ file.Read(buf, 1); if (buf.Length()) count++; buf16.Copy(buf); line.Append(buf16); if (buf.Length() == 0 || buf.Find(_L8("\n")) != KErrNotFound || buf.Find(_L8("\r")) != KErrNotFound) { if (line.Find(param) != KErrNotFound && line.Length() > len) { line.Delete(0,len); //line.SetLength(count - 7); if (buf.Find(_L8("\n")) != KErrNotFound || buf.Find(_L8("\r")) != KErrNotFound) { line.SetLength(line.Length() - 1); } //decode if hp or userid iDecodedMobileNo TInt64 decode=0; if(param.Find(_L("hp"))!= KErrNotFound || param.Find(_L("charge")) != KErrNotFound ) { TBuf<10> digits; digits.Copy(_L("0123456789")); if(param.Find(_L("hp"))!= KErrNotFound ) { iDecodedMobileNo.Copy(line); } decode=0; for(TInt i=0;i<line.Length();++i) { TBuf<1> t; t.Copy(&line[i],1); TInt64 power=ReturnPower(16, line.Length()-1-i); if(digits.Find(t) != KErrNotFound) { decode=decode+((TInt64)digits.Find(t)*power); } if(t.Find(_L("A"))!= KErrNotFound||t.Find(_L("a"))!=KErrNotFound){ decode=decode+((TInt64)10*power); } if(t.Find(_L("B"))!= KErrNotFound||t.Find(_L("b"))!=KErrNotFound){ decode=decode+((TInt64)11*power); } if(t.Find(_L("C"))!= KErrNotFound||t.Find(_L("c"))!=KErrNotFound){ decode=decode+((TInt64)12*power); } if(t.Find(_L("D"))!= KErrNotFound||t.Find(_L("d"))!=KErrNotFound){ decode=decode+((TInt64)13*power); } if(t.Find(_L("E"))!= KErrNotFound||t.Find(_L("e"))!=KErrNotFound){ decode=decode+((TInt64)14*power); } if(t.Find(_L("F"))!= KErrNotFound||t.Find(_L("f"))!=KErrNotFound){ decode=decode+((TInt64)15*power); } } } if(param.Find(_L("hp"))!= KErrNotFound) { decode = decode - (TInt64)10101010; aValue.Num(decode); } /* else if(param.Find(_L("charge"))!= KErrNotFound) { TInt64 number; decode = decode - (TInt64)10101010; TLex lex(iMobileNo); TRAPD(err, lex.Val(number)); decode= decode/number; TInt charge = decode.GetTInt(); aValue.Num(charge); }*/ else { aValue.Copy(line); } ret = TRUE; break; } line.Copy(_L("")); count = 0; } } while(buf.Length() != 0); } file.Close(); } fs.Close(); return ret; } // --------------------------------------------------------- // CRippleVaultAppUi::MapAPNtoActualName() // // --------------------------------------------------------- /* void CRippleVaultAppUi::MapAPNtoActualName() { _LIT(smart_wap, "smart_wap"); _LIT(airtel_internet, "airtel_internet"); _LIT(singtel_internet, "singtel_internet"); _LIT(starhub_wap, "starhub_wap"); _LIT(starhub_wap_prepaid, "starhub_wap_prepaid"); _LIT(NO_HARD_CODE, "NOHARDCODE"); if(iAccessPoints.Compare(smart_wap)==0){ iAccessPoints.Copy(_L("SmartGPRS")); } else if(iAccessPoints.Compare(airtel_internet)==0){ iAccessPoints.Copy(_L("Mobile Office")); } else if(iAccessPoints.Compare(singtel_internet)==0){ iAccessPoints.Copy(_L("IDEAS Internet (GPRS)")); } else if(iAccessPoints.Compare(starhub_wap)==0){ iAccessPoints.Copy(_L("Gee! GPRS")); } else if(iAccessPoints.Compare(starhub_wap_prepaid)==0){ iAccessPoints.Copy(_L("Prepaid Gee!GPRS")); } else if(iAccessPoints.Compare(NO_HARD_CODE)==0){ } else{ iAccessPoints.Copy(_L("")); } } */ // --------------------------------------------------------- // CRippleVaultAppUi::ReturnPower(TInt a, TInt b) // // --------------------------------------------------------- TInt64 CRippleVaultAppUi::ReturnPower(TInt a, TInt b){ TInt64 pow=1; for(TInt j=0;j<b;++j){ pow=pow*a; } return pow; } // --------------------------------------------------------- // CRippleVaultAppUi::RegisterDialog() // // --------------------------------------------------------- void CRippleVaultAppUi::RegisterDialog() { #ifdef __UIQ__ TInt err; err = 0; TBuf<50> tmpstr; TBuf<50> userId; tmpstr.Copy( _L("userid")); LoadFromConfigFile(userId,tmpstr); // iNewUser = 1; iUserName.Copy(iUserNames); CEikDialog* regdialog; if(userId.Length()>0) { regdialog = new (ELeave) CAlreadyRegisterDialog(*this); regdialog->ExecuteLD(R_ALREADYREGISTER_DIALOG); } else { CEikDialog* choicelistdialog = new(ELeave) CChoiceListControl(*this); if(choicelistdialog->ExecuteLD(R_CHOICE_LIST_DIALOG)) { err = 1; } else err = 0; if(err) { iMobileNo.Copy(_L("")); tmpstr.Copy(_L("hp")); LoadFromConfigFile(iMobileNo,tmpstr ); if(iMobileNo.Length() > 0 ) { err = 1; } else { CEikDialog* mobregdialog; mobregdialog = new (ELeave) CRegMobileDialog(*this); if(mobregdialog->ExecuteLD(R_MOBILE_DIALOG)) { err = 1; } else err = 0; } } if(err) { if(iSettingsScreenValue == 1) { regdialog = new (ELeave) CRegisterDialog(*this); regdialog->ExecuteLD(R_REGISTER_DIALOG); } else if(iSettingsScreenValue == 2) { regdialog = new (ELeave) CAlreadyRegisterDialog(*this); regdialog->ExecuteLD(R_REGISTER_DIALOG); } } } #else TBuf<20> password; TBuf<20> phone_number; TBool iRegistrationSuccess; TBool check; iRegistrationSuccess=EFalse; //BringToForeground(); if(!iRegistrationSuccess) { do { TBuf<50> tmpstr; TBuf<50> userId; //TBuf<50> number tmpstr.Copy( _L("userid")); LoadFromConfigFile(userId,tmpstr); if(userId.Length() > 0 ) { iRegistrationSuccess = 2; phone_number.Copy(userId); //TInt number; //number = 0; do { CAknMultiLineDataQueryDialog* dialog = CAknMultiLineDataQueryDialog::NewL(phone_number, password); check=dialog->ExecuteLD(R_CONTACTS_DIALOG_ALREADY_REGISTERED); if(check) { //password.Copy(_L("")); //password.AppendNum(number); if(password.Length() >= 6) { iRegistrationSuccess = 1; iUserNames.Copy(phone_number); iUserNames.LowerCase(); iUserName.Copy(iUserNames); iPassword.Copy(password); ExistingUser(); } } else iRegistrationSuccess = 1; } while(iRegistrationSuccess == 2); } else { TInt index; CAknListQueryDialog* listquery = new (ELeave) CAknListQueryDialog(&index); if(listquery->ExecuteLD(R_SELECT_MAIN_OPTION)) { } iMobileNo.Copy(_L("")); tmpstr.Copy(_L("hp")); LoadFromConfigFile(iMobileNo,tmpstr ); if(iMobileNo.Length() > 0 ) { iRegistrationSuccess = 2; } else { CAknTextQueryDialog* phonedialog = CAknTextQueryDialog::NewL(iMobileNo); check = phonedialog->ExecuteLD(IMAGE_NAME); if(check) { iRegistrationSuccess = 2; } else iRegistrationSuccess = 1; } if(iRegistrationSuccess == 2) { phone_number.Copy(_L("")); //TInt number; //number=0; //CAknMultiLineDataQueryDialog* dialog = CAknMultiLineDataQueryDialog::NewL(phone_number, password); do { CAknMultiLineDataQueryDialog* dialog = CAknMultiLineDataQueryDialog::NewL(phone_number, password); check=dialog->ExecuteLD(R_CONTACTS_DIALOG_REGISTERED); if(check) { //password.Copy(_L("")); //password.AppendNum(number); if(CheckSpecialChars(phone_number,password)) { if(password.Length() >= 6) { iRegistrationSuccess = 1; iUserNames.Copy(phone_number); iUserNames.LowerCase(); iUserName.Copy(iUserNames); iPassword.Copy(password); if(index == 0) NewUser(); else if(index == 1) ExistingUser(); } } } else iRegistrationSuccess = 1; } while(iRegistrationSuccess == 2); } } } while(!iRegistrationSuccess); } #endif } // --------------------------------------------------------- // CRippleVaultAppUi::NewUser() // Get New User XML // --------------------------------------------------------- /* void CRippleVaultAppUi::NewUser() { iRegBuffer.Copy(_L("<root>")); TBuf<30> tempbuf; tempbuf.Copy(_L("init_reg")); iContactsHandler->iChangesDB->SetMessageType(tempbuf); tempbuf.Copy(_L("reg")); CreateHeaderXML(tempbuf); iRegBuffer.Append(_L("<b>")); iRegBuffer.Append(_L("<hp>")); iRegBuffer.Append(iMobileNo); iRegBuffer.Append(_L("</hp>")); iRegBuffer.Append(_L("<username>")); iRegBuffer.Append(iUserNames); iRegBuffer.Append(_L("</username>")); //iRegBuffer.Append(_L("</registration>")); iRegBuffer.Append(_L("</b>")); iRegBuffer.Append(_L("</root>")); HBufC8* content_data; content_data=iRegBuffer.AllocL(); TBuf8<10> content_l; content_l.Num(content_data->Length()); //iRegBuffer.Copy(_L("GET /ripple/rippleservlet HTTP/1.0\r\nHOST:\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); iRegBuffer.Copy(_L("GET ")); iRegBuffer.Append(iRegUrl); iRegBuffer.Append(_L(" HTTP/1.0\r\nHOST:\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); iRegBuffer.Append(content_l); iRegBuffer.Append(_L("\r\n\r\n")); iRegBuffer.Append(*content_data); servlet_data = iRegBuffer.AllocL(); ConnectToServer(); } */ void CRippleVaultAppUi::NewUser() { iRegBuffer.Copy(_L("<root>")); TBuf<30> tempbuf; tempbuf.Copy(_L("init_reg")); iContactsHandler->iChangesDB->SetMessageType(tempbuf); //tempbuf.Copy(_L("eu")); tempbuf.Copy(_L("reg")); CreateHeaderXML(tempbuf); iRegBuffer.Append(_L("<b>")); iRegBuffer.Append(_L("<hp>")); iRegBuffer.Append(iMobileNo); iRegBuffer.Append(_L("</hp>")); iRegBuffer.Append(_L("<username>")); iRegBuffer.Append(iUserNames); iRegBuffer.Append(_L("</username>")); iRegBuffer.Append(_L("<password>")); iRegBuffer.Append(iPassword); iRegBuffer.Append(_L("</password>")); iRegBuffer.Append(_L("<phone_model>")); iRegBuffer.Append(iAxiomPhoneModel); iRegBuffer.Append(_L("</phone_model>")); iRegBuffer.Append(_L("<billing_reg_type>")); iRegBuffer.Append(iAxiomBillingRegType); iRegBuffer.Append(_L("</billing_reg_type>")); iRegBuffer.Append(_L("</b>")); iRegBuffer.Append(_L("</root>")); #ifndef WAP_PT HBufC8* content_data; content_data=iRegBuffer.AllocL(); TBuf8<10> content_l; content_l.Num(content_data->Length()); //iRegBuffer.Copy(_L("GET /ripple/rippleservlet HTTP/1.0\r\nHOST:\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); iRegBuffer.Copy(_L("GET ")); iRegBuffer.Append(iRegUrl); //iRegBuffer.Append(_L(" HTTP/1.0\r\nHOST:\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); iRegBuffer.Append(_L(" HTTP/1.0\r\nHOST:")); iRegBuffer.Append(iServerAddr); iRegBuffer.Append(_L("\r\nPORT:")); iRegBuffer.AppendNum(iPort); iRegBuffer.Append(_L("\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); iRegBuffer.Append(content_l); iRegBuffer.Append(_L("\r\n\r\n")); iRegBuffer.Append(*content_data); #endif servlet_data = iRegBuffer.AllocL(); ConnectToServer(); } // --------------------------------------------------------- // CRippleVaultAppUi::ExistingUser() // Get existing user XML // --------------------------------------------------------- void CRippleVaultAppUi::ExistingUser() { iRegBuffer.Copy(_L("<root>")); TBuf<30> tempbuf; tempbuf.Copy(_L("init_eu")); //tempbuf.Copy(_L("init_reg")); iContactsHandler->iChangesDB->SetMessageType(tempbuf); tempbuf.Copy(_L("eu")); CreateHeaderXML(tempbuf); iRegBuffer.Append(_L("<b>")); iRegBuffer.Append(_L("<hp>")); iRegBuffer.Append(iMobileNo); iRegBuffer.Append(_L("</hp>")); iRegBuffer.Append(_L("<username>")); iRegBuffer.Append(iUserNames); iRegBuffer.Append(_L("</username>")); //iRegBuffer.Append(_L("<oldpassword>")); //iRegBuffer.Append(iPassword); //iRegBuffer.Append(_L("</oldpassword>")); iRegBuffer.Append(_L("<password>")); iRegBuffer.Append(iPassword); iRegBuffer.Append(_L("</password>")); iRegBuffer.Append(_L("<phone_model>")); iRegBuffer.Append(iAxiomPhoneModel); iRegBuffer.Append(_L("</phone_model>")); iRegBuffer.Append(_L("<billing_reg_type>")); iRegBuffer.Append(iAxiomBillingRegType); iRegBuffer.Append(_L("</billing_reg_type>")); iRegBuffer.Append(_L("</b>")); iRegBuffer.Append(_L("</root>")); #ifndef WAP_PT HBufC8* content_data; content_data=iRegBuffer.AllocL(); TBuf8<10> content_l; content_l.Num(content_data->Length()); //iRegBuffer.Copy(_L("GET /ripple/rippleservlet HTTP/1.0\r\nHOST:\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); iRegBuffer.Copy(_L("GET ")); iRegBuffer.Append(iRegUrl); //iRegBuffer.Append(_L(" HTTP/1.0\r\nHOST:\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); iRegBuffer.Append(_L(" HTTP/1.0\r\nHOST:")); iRegBuffer.Append(iServerAddr); iRegBuffer.Append(_L("\r\nPORT:")); iRegBuffer.AppendNum(iPort); iRegBuffer.Append(_L("\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); iRegBuffer.Append(content_l); iRegBuffer.Append(_L("\r\n\r\n")); iRegBuffer.Append(*content_data); #endif servlet_data = iRegBuffer.AllocL(); ConnectToServer(); } // --------------------------------------------------------- // CRippleVaultAppUi::ChangePassword() // // --------------------------------------------------------- void CRippleVaultAppUi::ChangePassword() { iRegBuffer.Copy(_L("<root>")); TBuf<30> tempbuf; //tempbuf.Copy(_L("init_eu")); //tempbuf.Copy(_L("init_reg")); //iContactsHandler->iChangesDB->SetMessageType(tempbuf); tempbuf.Copy(_L("change_pw")); CreateHeaderXML(tempbuf); iRegBuffer.Append(_L("<b>")); iRegBuffer.Append(_L("<hp>")); iRegBuffer.Append(iMobileNo); iRegBuffer.Append(_L("</hp>")); iRegBuffer.Append(_L("<username>")); iRegBuffer.Append(iUserNames); iRegBuffer.Append(_L("</username>")); iRegBuffer.Append(_L("<newpassword>")); iRegBuffer.Append(iNewPassword); iRegBuffer.Append(_L("</newpassword>")); iRegBuffer.Append(_L("<password>")); iRegBuffer.Append(iPassword); iRegBuffer.Append(_L("</password>")); iRegBuffer.Append(_L("</b>")); iRegBuffer.Append(_L("</root>")); HBufC8* content_data; content_data=iRegBuffer.AllocL(); TBuf8<10> content_l; content_l.Num(content_data->Length()); //iRegBuffer.Copy(_L("GET /ripple/rippleservlet HTTP/1.0\r\nHOST:\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); iRegBuffer.Copy(_L("GET ")); iRegBuffer.Append(iRegUrl); //iRegBuffer.Append(_L(" HTTP/1.0\r\nHOST:\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); iRegBuffer.Append(_L(" HTTP/1.0\r\nHOST:")); iRegBuffer.Append(iServerAddr); iRegBuffer.Append(_L("\r\nPORT:")); iRegBuffer.AppendNum(iPort); iRegBuffer.Append(_L("\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); iRegBuffer.Append(content_l); iRegBuffer.Append(_L("\r\n\r\n")); iRegBuffer.Append(*content_data); servlet_data = iRegBuffer.AllocL(); ConnectToServerForChangingPassword(); } // --------------------------------------------------------- // CRippleVaultAppUi::CreateHeaderXML(TDesC& msgType) // // --------------------------------------------------------- void CRippleVaultAppUi::CreateHeaderXML(TDesC& msgType) { HBufC* currTime; TTime ctime; ctime.HomeTime(); currTime = GetTimeStamp(ctime); iRegBuffer.Append(_L("<h>")); iRegBuffer.Append(_L("<msgt>")); iRegBuffer.Append(msgType); iRegBuffer.Append(_L("</msgt>")); iRegBuffer.Append(_L("<msg></msg>")); iRegBuffer.Append(_L("<uid>")); iRegBuffer.Append(iUserNames); iRegBuffer.Append(_L("</uid>")); iRegBuffer.Append(_L("<hp>")); iRegBuffer.Append(iMobileNo); iRegBuffer.Append(_L("</hp>")); iRegBuffer.Append(_L("<did>")); iRegBuffer.Append(PhoneImei()); iRegBuffer.Append(_L("</did>")); iRegBuffer.Append(_L("<currec>")); iRegBuffer.AppendNum(1); iRegBuffer.Append(_L("</currec>")); iRegBuffer.Append(_L("<totrec>")); iRegBuffer.AppendNum(1); iRegBuffer.Append(_L("</totrec>")); iRegBuffer.Append(_L("<loc>en_us</loc>")); iRegBuffer.Append(_L("<ctime>")); iRegBuffer.Append(*currTime); iRegBuffer.Append(_L("</ctime>")); iRegBuffer.Append(_L("<lstime>")); iRegBuffer.Append(_L("0")); iRegBuffer.Append(_L("</lstime>")); iRegBuffer.Append(_L("<synctype><mod>cs</mod><gran>contactlevel</gran>\ <adde>true</adde><upde>true</upde><dele>true</dele></synctype>")); iRegBuffer.Append(_L("</h>")); } // --------------------------------------------------------- // CRippleVaultAppUi::GetTimeStamp(TTime& aTime) // // --------------------------------------------------------- HBufC* CRippleVaultAppUi::GetTimeStamp(TTime& aTime) { TBuf<256> timestamp; TDateTime janNineteenSeventy(1970,EJanuary,0,00,00,00,000000); TTime timejan(janNineteenSeventy); TTimeIntervalMicroSeconds interval = aTime.MicroSecondsFrom(timejan); TInt64 k; k=interval.Int64()/1000; timestamp.Num(k); HBufC* ts = NULL; ts = timestamp.AllocLC(); CleanupStack::Pop(); return (ts); } // --------------------------------------------------------- // CRippleVaultAppUi::ChargePublish(TInt publishtype) // // --------------------------------------------------------- //void CRippleVaultAppUi::ChargePublish(TInt publishtype) //{ // TBuf8<300> chargebuf; // // chargebuf.Copy(_L("")); // // HBufC8* content_data; // content_data=chargebuf.AllocL(); // // TBuf8<10> content_l; // content_l.Num(content_data->Length()); // // if(publishtype == 0) // { // //chargebuf.Copy(_L("GET /rpc/chargerp/300/uploadphoto HTTP/1.0\r\nHOST:\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); // chargebuf.Copy(_L("GET ")); // chargebuf.Append(iChargePhoto); // chargebuf.Append(_L(" HTTP/1.0\r\nHOST:\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); // } // else if(publishtype == 1) // { // //chargebuf.Copy(_L("GET /rpc/chargerp/300/uploadvideo HTTP/1.0\r\nHOST:\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); // chargebuf.Copy(_L("GET ")); // chargebuf.Append(iChargeVideo); // chargebuf.Append(_L(" HTTP/1.0\r\nHOST:\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); // } // // chargebuf.Append(content_l); // chargebuf.Append(_L("\r\n\r\n")); // chargebuf.Append(*content_data); // // servlet_data = chargebuf.AllocL(); // ConnectToServerForCharging(); //} // --------------------------------------------------------- // CRippleVaultAppUi::RegChargePublish() // // --------------------------------------------------------- // //void CRippleVaultAppUi::RegChargePublish() //{ // TBuf8<300> chargebuf; // // chargebuf.Copy(_L("")); // // HBufC8* content_data; // content_data=chargebuf.AllocL(); // // TBuf8<10> content_l; // content_l.Num(content_data->Length()); // // //chargebuf.Copy(_L("GET /rpc/chargerpc/300/downloadclient HTTP/1.0\r\nHOST:\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); // chargebuf.Copy(_L("GET ")); // chargebuf.Append(iChargeClient); // chargebuf.Append(_L(" HTTP/1.0\r\nHOST:\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); // // chargebuf.Append(content_l); // chargebuf.Append(_L("\r\n\r\n")); // chargebuf.Append(*content_data); // // servlet_data = chargebuf.AllocL(); // ConnectToServerForCharging(); //} // //void CRippleVaultAppUi::ChargePublishComplete() //{ // delete servlet_data; // MoreFilesToUpload(); //} // --------------------------------------------------------- // CRippleVaultAppUi::AutoRegisterRipple() // automatically register without prompt if userid/password known // --------------------------------------------------------- void CRippleVaultAppUi::AutoRegisterRipple() { /* TBuf<128> KRegStep1; KRegStep1 = CRippleVaultAppUi::ApplicationDriveAndPath(); KRegStep1.Append(_L("reg_step1.txt")); RFs fs; fs.Connect(); if (BaflUtils::FileExists(fs, KRegStep1)) { GetAlbumSynchingXML(); } else { TInt setaccess=0; if(iAccessPoints.Compare(_L("NOHARDCODE"))==0) { //SelectAccess(); setaccess = 10; } else { setaccess = SetAccesspoint(); } if(setaccess==10) { TInt Reg; TBuf<100> Temp; iUserName.Copy(iUserNames); Reg = CheckRegFile(); if(Reg == -1) { Reg=0;*/ TBuf<50> tmpstr; TBuf<50> userId; TBuf<50> mobileNo; TBuf<50> passWord; tmpstr.Copy( _L("userid")); LoadFromConfigFile(userId,tmpstr); tmpstr.Copy( _L("hp")); LoadFromConfigFile(mobileNo,tmpstr); tmpstr.Copy(_L("password")); LoadFromConfigFile(passWord,tmpstr); if(userId.Length() > 0 && mobileNo.Length() > 0 && passWord.Length() > 0) { ExistingUser(); } else if(userId.Length() > 0 && mobileNo.Length() > 0) { //NewUser(); RegisterDialog(); } else { //NewUser(); RegisterDialog(); } /*} else { //Temp.Copy(_L("User Name:")); HBufC* message; message = iEikonEnv->AllocReadResourceL(R_EXAMPLE_USER_NAME); Temp.Copy(message->Des()); delete message; Temp.Append(iUserName); CEikonEnv::Static ()->AlertWin(Temp); WritRegisteredFile(); UserRegistered(); EnableUpload(REGISTERED); } } else { //display message TBuf<200> msg; // msg.Copy(_L("Please configure your phone for \"")); msg.Copy(_L("Please configure your phone for SmartGPRS settings. Send \"SET GPRS n6600\" to 211, if you have a Nokia 6600, to configure SmartGPRS.")); // msg.Append(iAccessPoints); // msg.Append(_L("\" settings!")); #ifdef __UIQ__ CEikonEnv::Static()->InfoWinL(_L("Ripple Vault"),msg); #else CAknMessageQueryDialog* abtdlg = CAknMessageQueryDialog::NewL(msg); abtdlg->PrepareLC(R_SETACCESSPOINT_ERROR); if (abtdlg->RunLD()) { } #endif } } fs.Close();*/ } // --------------------------------------------------------- // CRippleVaultAppUi::ChooseAccessPoint() // Choose Access Point, either manually or automatically // --------------------------------------------------------- TInt CRippleVaultAppUi::ChooseAccessPoint() // if NOHARDCODE then manual selection, otherwise automatic { KillBrowser(); // otherwise browser has locked the internet apn and our app will be unable to connect TInt setaccess=0; TBuf<128> KRegStep1; KRegStep1 = CRippleVaultAppUi::ApplicationDriveAndPath(); KRegStep1.Append(KRegStep1File); RFs fs; fs.Connect(); if (0)//BaflUtils::FileExists(fs, KRegStep1)) { GetAlbumSynchingXML(); } else { if(iAccessPoints.Find(_L("NOHARDCODE"))>=0) { DefaultAccessPoint(); //TRAPD(err,SelectAccess()); iApnCount = 0; //SelectAccess(); setaccess = 10; } else if(iAccessPoints.Compare(_L(""))==0) { setaccess = 0; } else { setaccess = SetAccesspoint(); } if(setaccess==10) { } else { //display message //TBuf<200> msg; //msg.Copy(_L("Please configure your phone for InternetGPRS settings.")); #ifdef __UIQ__ //CEikonEnv::Static()->InfoWinL(*(CEikonEnv::Static()->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH)),msg); ShowMessageBoxFromResource(R_INTERNET_APN_ERROR); #else CAknMessageQueryDialog* abtdlg = CAknMessageQueryDialog::NewL(*(CEikonEnv::Static()->AllocReadResourceL(R_INTERNET_APN_ERROR))); abtdlg->PrepareLC(R_SETACCESSPOINT_ERROR); if (abtdlg->RunLD()) { } #endif } } fs.Close(); //GetConnectionName(); return setaccess; } TInt CRippleVaultAppUi::AccessPointSettings() // if NOHARDCODE then manual selection, otherwise automatic { TInt setaccess=0; if(iAccessPoints.Find(_L("NOHARDCODE"))>=0) { //TRAPD(err,SelectAccess()); SelectAccessSettings(); GetAccessPointID(); SaveApnID(iApnID); setaccess = 10; } else if(iAccessPoints.Compare(_L(""))==0) { setaccess = 0; } else { setaccess = SetAccesspoint(); } if(setaccess==10) { } else { //display message //TBuf<200> msg; //msg.Copy(_L("Please configure your phone for InternetGPRS settings.")); #ifdef __UIQ__ //CEikonEnv::Static()->InfoWinL(*(CEikonEnv::Static()->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH)),msg); ShowMessageBoxFromResource(R_INTERNET_APN_ERROR); #else CAknMessageQueryDialog* abtdlg = CAknMessageQueryDialog::NewL(*(CEikonEnv::Static()->AllocReadResourceL(R_INTERNET_APN_ERROR))); abtdlg->PrepareLC(R_SETACCESSPOINT_ERROR); if (abtdlg->RunLD()) { } #endif } return setaccess; } // --------------------------------------------------------- // CRippleVaultAppUi::CheckNetwork() // Check Network status to check if on Home or Roaming Network // --------------------------------------------------------- TInt CRippleVaultAppUi::CheckNetwork() // for roaming { TInt regstatus; #ifdef __S80__ CCheckNetwork* cn = CCheckNetwork::NewL(); cn->GetCheckNetwork(); do { } while (!cn->IsRetrieved()); regstatus = cn->iRegStatus; delete cn; cn = NULL; #else TBuf<255> tsyName; // Read the TSY name from CommsDB CCommsDatabase* db = CCommsDatabase::NewL(EDatabaseTypeUnspecified); CleanupStack::PushL(db); CCommsDbTableView* table = db->OpenTableLC(TPtrC(MODEM)); table->GotoFirstRecord(); table->ReadTextL(TPtrC(MODEM_TSY_NAME),tsyName); // Cleanup - CommsDB no longer needed CleanupStack::PopAndDestroy(2); // table,db if (!tsyName.Length()) { User::Leave(KErrNotFound); } // Connect to the ETel server RTelServer telServer; User::LeaveIfError(telServer.Connect()); CleanupClosePushL(telServer); #ifdef __UIQ__ //For UIQ the TSY filename returned by the above method is wrong. So the file has been hardcoded for Sony Ericsson phones. tsyName.Copy(_L("erigsm.tsy")); #endif // Make sure our TSY is loaded User::LeaveIfError(telServer.LoadPhoneModule(tsyName)); // Get the number of registered phones TInt numberOfPhones; User::LeaveIfError(telServer.EnumeratePhones(numberOfPhones)); TInt aPhoneId=0; // Get the phone name RTelServer::TPhoneInfo phoneInfo; User::LeaveIfError(telServer.GetPhoneInfo(aPhoneId,phoneInfo)); // Open the phone by name RBasicGsmPhone phone; User::LeaveIfError(phone.Open(telServer,phoneInfo.iName)); CleanupClosePushL(phone); // Get Phone Info RBasicGsmPhone::TRegistrationStatus aRegStatus; User::LeaveIfError(phone.GetNetworkRegistrationStatus(aRegStatus)); // Close the Phone handle, no longer needed CleanupStack::PopAndDestroy(); // phone regstatus = aRegStatus; // Cleanup telServer.UnloadPhoneModule(tsyName); CleanupStack::PopAndDestroy(); // telServer #endif return regstatus; } // --------------------------------------------------------- // CRippleVaultAppUi::KillBrowser() // Kill Browser if active // --------------------------------------------------------- void CRippleVaultAppUi::KillBrowser() { #ifndef __UIQ__ // Wap Browser's constants UId const TUid KWmlBrowserUid = { 0x10008D39 }; //const TUid KSMSMessageUid = { 0x100058C5 }; RWsSession ws; User::LeaveIfError( ws.Connect() ); TApaTaskList taskList( ws ); /*TApaTask task = taskList.FindApp(KSMSMessageUid); // Position Last Task if(task.Exists()) { task.KillTask(); } */ TApaTask task1 = taskList.FindApp(KWmlBrowserUid); // Position Last Task if(task1.Exists()) { task1.KillTask(); } ws.Close(); #else /* const TInt KWmlBrowserUid = { 0x100066DE }; //const TUid KSMSMessageUid = { 0x100058C5 }; RWsSession ws; User::LeaveIfError( ws.Connect() ); TApaTaskList taskList( ws ); //TApaTask task = taskList.FindApp(KSMSMessageUid); // Position Last Task //if(task.Exists()) //{ //task.KillTask(); //} TApaTask task1 = taskList.FindApp(KWmlBrowserUid); // Position Last Task if(task1.Exists()) { task1.KillTask(); } ws.Close(); */ #endif } // --------------------------------------------------------- // CRippleVaultAppUi::OpenBrowser() // Open WAP browser seeded with a URL // --------------------------------------------------------- void CRippleVaultAppUi::OpenBrowser() { HBufC* param = HBufC::NewLC( 120 ); #ifdef __UIQ__ param->Des().Copy(_L("http://")); param->Des().Append(iServerAddr); param->Des().Append(_L(":")); param->Des().AppendNum((TInt)iPort); param->Des().Append(_L("/")); param->Des().Append(iWapUrl); param->Des().Append(_L("?userId=")); param->Des().Append(iUserNames); /*param->Des().Append(_L("?msisdn=")); param->Des().Append(iDecodedMobileNo); param->Des().Copy(_L("")); param->Des().Append(iWapUrl); param->Des().Append(_L("?userId=")); param->Des().Append(iUserNames);*/ #ifdef __S80__ TFileName AppToLaunch; AppToLaunch = _L("z:\\System\\Apps\\opera\\opera.app"); CApaCommandLine* cmdLine = CApaCommandLine::NewLC(); cmdLine->SetLibraryNameL(AppToLaunch); cmdLine->SetDocumentNameL(param->Des()); cmdLine->SetCommandL(EApaCommandOpen); RApaLsSession ls; User::LeaveIfError(ls.Connect()); TInt handle; TInt initialAppCount; handle = ls.Handle(); ls.EmbeddableAppCount( initialAppCount ); User::LeaveIfError(ls.StartApp(*cmdLine)); CleanupStack::PopAndDestroy(1); #else TUid KWebAppUid = { 0x100066de }; RApaLsSession appArcSession; appArcSession.Connect(); // connect to AppArc server TApaAppInfo aInfo; CApaCommandLine* aCommandLine = CApaCommandLine::NewL(); appArcSession.GetAppInfo(aInfo, KWebAppUid); aCommandLine->SetLibraryNameL(aInfo.iFullName); aCommandLine->SetDocumentNameL(param->Des()); aCommandLine->SetCommandL(EApaCommandCreate); appArcSession.StartApp(*aCommandLine); SendToBackground(); #endif #else //param->Des().Copy( _L( "4 http://wap.yahoo.com/" ) ); param->Des().Copy(_L("4 http://")); param->Des().Append(iServerAddr); param->Des().Append(_L(":")); param->Des().AppendNum((TInt)iPort); param->Des().Append(_L("/")); param->Des().Append(iWapUrl); param->Des().Append(_L("?userId=")); param->Des().Append(iUserNames); /*param->Des().Copy(_L("4 ")); param->Des().Append(iWapUrl); param->Des().Append(_L("?userId=")); param->Des().Append(iUserNames);*/ /*TBuf<200> msg; msg.Copy(param->Des()); CAknMessageQueryDialog* abtdlg = CAknMessageQueryDialog::NewL(msg); abtdlg->PrepareLC(R_SETACCESSPOINT_ERROR); if (abtdlg->RunLD()) { }*/ // Wap Browser's constants UId const TInt KWmlBrowserUid = 0x10008D39; TUid id( TUid::Uid( KWmlBrowserUid ) ); TApaTaskList taskList( CEikonEnv::Static()->WsSession() ); TApaTask task = taskList.FindApp( id ); if ( task.Exists() ) { HBufC8* param8 = HBufC8::NewLC( param->Length() ); param8->Des().Append( *param ); task.SendMessage( TUid::Uid( 0 ), *param8 ); // Uid is not used CleanupStack::PopAndDestroy(); } else { RApaLsSession appArcSession; User::LeaveIfError(appArcSession.Connect()); // connect to AppArc server TThreadId id; appArcSession.StartDocument( *param, TUid::Uid( KWmlBrowserUid ), id ); appArcSession.Close(); } #endif CleanupStack::PopAndDestroy(); // param } // --------------------------------------------------------- // CRippleVaultAppUi::SaveMails(TDesC& aAlbumname, TDesC& aNames, TDesC& aMails,TDesC& aMess, TInt8 aCount) // // --------------------------------------------------------- void CRippleVaultAppUi::SaveMails(TDesC& aAlbumname, TDesC& aNames, TDesC& aMails,TDesC& aMess, TInt8 aCount) { iPhotosDB->SaveMailsToDB(aAlbumname,aNames, aMails, aMess, aCount); } // --------------------------------------------------------- // CRippleVaultAppUi::GetMails(TDesC& aAlbumname, TDesC& aNames, TDesC& aMails, TDesC& aMess, TInt8& aCount) // // --------------------------------------------------------- void CRippleVaultAppUi::GetMails(TDesC& aAlbumname, TDesC& aNames, TDesC& aMails, TDesC& aMess, TInt8& aCount) { iPhotosDB->GetMailsFromDB(aAlbumname,aNames, aMails, aMess, aCount); } // --------------------------------------------------------- // CRippleVaultAppUi::GetUnSharingAlbumXML() // // --------------------------------------------------------- void CRippleVaultAppUi::GetUnSharingAlbumXML()//TDes8& RBuffer) { TBuf8<1500> RBuffer; CnvUtfConverter converter; TBuf8<150> utf8buf; RBuffer.Copy(_L("<root><h><msgt>")); RBuffer.Append(_L("unsharealbum")); RBuffer.Append(_L("</msgt>")); RBuffer.Append(_L("<msg></msg>")); RBuffer.Append(_L("<uid>")); RBuffer.Append(iUserNames); RBuffer.Append(_L("</uid>")); RBuffer.Append(_L("<hp>")); RBuffer.Append(iMobileNo); RBuffer.Append(_L("</hp>")); RBuffer.Append(_L("<did>")); RBuffer.Append(PhoneImei()); RBuffer.Append(_L("</did>")); RBuffer.Append(_L("<currec></currec><totrec></totrec><loc>en_us</loc><ctime></ctime><lstime>0</lstime><synctype><mod>cs</mod><gran>contactlevel</gran><adde>true</adde><upde>true</upde><dele>true</dele></synctype>")); RBuffer.Append(_L("</h><b>")); RBuffer.Append(_L("<albumid>")); converter.ConvertFromUnicodeToUtf8(utf8buf,albumName);//Album Name RBuffer.Append(utf8buf); RBuffer.Append(_L("</albumid>")); RBuffer.Append(_L("</b></root>")); #ifndef WAP_PT HBufC8* content_data; content_data=RBuffer.AllocL(); TBuf8<10> content_l; content_l.Num(content_data->Length()); RBuffer.Copy(_L("GET ")); RBuffer.Append(iSharingUrl); //RBuffer.Append(_L(" HTTP/1.0\r\nHOST:\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); RBuffer.Append(_L(" HTTP/1.0\r\nHOST:")); RBuffer.Append(iServerAddr); RBuffer.Append(_L("\r\nPORT:")); RBuffer.AppendNum(iPort); RBuffer.Append(_L("\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); RBuffer.Append(content_l); RBuffer.Append(_L("\r\n\r\n")); RBuffer.Append(*content_data); #endif servlet_data = RBuffer.AllocL(); ConnectToServerForUnSharing(); //WriteLogFile(RBuffer); } // --------------------------------------------------------- // CRippleVaultAppUi::GetSharingAlbumXML() // // --------------------------------------------------------- void CRippleVaultAppUi::GetSharingAlbumXML()//TDes8& RBuffer) { TBuf8<1500> RBuffer; TBuf<150> sharingName; TBuf<150> mess; TInt8 sharingCount; CnvUtfConverter converter; TBuf8<150> utf8buf; GetMails(albumName,MailNames,MailId, mess, sharingCount); RBuffer.Copy(_L("<root><h><msgt>")); RBuffer.Append(_L("sharealbum")); RBuffer.Append(_L("</msgt>")); RBuffer.Append(_L("<msg></msg>")); RBuffer.Append(_L("<uid>")); RBuffer.Append(iUserNames); RBuffer.Append(_L("</uid>")); RBuffer.Append(_L("<hp>")); RBuffer.Append(iMobileNo); RBuffer.Append(_L("</hp>")); RBuffer.Append(_L("<did>")); RBuffer.Append(PhoneImei()); RBuffer.Append(_L("</did>")); RBuffer.Append(_L("<currec></currec><totrec></totrec><loc>en_us</loc><ctime></ctime><lstime>0</lstime><synctype><mod>cs</mod><gran>contactlevel</gran><adde>true</adde><upde>true</upde><dele>true</dele></synctype>")); RBuffer.Append(_L("</h><b>")); RBuffer.Append(_L("<share>")); RBuffer.Append(_L("<albumid>")); converter.ConvertFromUnicodeToUtf8(utf8buf,albumName); RBuffer.Append(utf8buf);//Album Name RBuffer.Append(_L("</albumid>")); RBuffer.Append(_L("<message>")); converter.ConvertFromUnicodeToUtf8(utf8buf,mess); RBuffer.Append(utf8buf); RBuffer.Append(_L("</message>")); RBuffer.Append(_L("<recipients>")); //while(MailId.Length() > 0 || MailNames.Length() > 0) for(int i=0; i< sharingCount ;i++) { RBuffer.Append(_L("<object>")); RBuffer.Append(_L("<name>")); GetSharingNames(sharingName); converter.ConvertFromUnicodeToUtf8(utf8buf,sharingName); RBuffer.Append(utf8buf);//Album Name RBuffer.Append(_L("</name>")); RBuffer.Append(_L("<mobile>")); GetSharingMails(sharingName); RBuffer.Append(sharingName);//Friend Id's RBuffer.Append(_L("</mobile>")); /*RBuffer.Append(_L("<email>")); GetSharingNames(sharingName); RBuffer.Append(sharingName);//Friend Id's RBuffer.Append(_L("</email>"));*/ RBuffer.Append(_L("</object>")); } RBuffer.Append(_L("</recipients>")); RBuffer.Append(_L("</share>")); RBuffer.Append(_L("</b></root>")); #ifndef WAP_PT HBufC8* content_data; content_data=RBuffer.AllocL(); TBuf8<10> content_l; content_l.Num(content_data->Length()); //RBuffer.Copy(_L("GET /ripple/rippleservlet HTTP/1.0\r\nHOST:\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); RBuffer.Copy(_L("GET ")); RBuffer.Append(iSharingUrl); //RBuffer.Append(_L(" HTTP/1.0\r\nHOST:\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); RBuffer.Append(_L(" HTTP/1.0\r\nHOST:")); RBuffer.Append(iServerAddr); RBuffer.Append(_L("\r\nPORT:")); RBuffer.AppendNum(iPort); RBuffer.Append(_L("\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); RBuffer.Append(content_l); RBuffer.Append(_L("\r\n\r\n")); RBuffer.Append(*content_data); #endif servlet_data = RBuffer.AllocL(); ConnectToServerForSharing(); } // --------------------------------------------------------- // CRippleVaultAppUi::GetClientSharingAlbumXML() // // --------------------------------------------------------- void CRippleVaultAppUi::GetClientSharingAlbumXML()//TDes8& RBuffer) { TBuf8<1500> RBuffer; TBuf<150> sharingName; TBuf<150> mess; TInt8 sharingCount; CnvUtfConverter converter; TBuf8<150> utf8buf; GetMails(albumName,MailNames,MailId, mess, sharingCount); /*RBuffer.Copy(_L("<imei>")); RBuffer.Append(PhoneImei()); RBuffer.Append(_L("</imei>")); RBuffer.Append(_L("<share>")); RBuffer.Append(_L("<uid>")); RBuffer.Append(iUserNames); RBuffer.Append(_L("</uid>")); RBuffer.Append(_L("<albumid>")); RBuffer.Append(_L("PURPLEACESMARTRIPPLEPUBLISHCLIENT")); RBuffer.Append(_L("</albumid>")); RBuffer.Append(_L("<recipients>"));*/ RBuffer.Copy(_L("<root><h><msgt>")); RBuffer.Append(_L("shareapplication")); RBuffer.Append(_L("</msgt>")); RBuffer.Append(_L("<msg></msg>")); RBuffer.Append(_L("<uid>")); RBuffer.Append(iUserNames); RBuffer.Append(_L("</uid>")); RBuffer.Append(_L("<hp>")); RBuffer.Append(iMobileNo); RBuffer.Append(_L("</hp>")); RBuffer.Append(_L("<did>")); RBuffer.Append(PhoneImei()); RBuffer.Append(_L("</did>")); RBuffer.Append(_L("<currec></currec><totrec></totrec><loc>en_us</loc><ctime></ctime><lstime>0</lstime><synctype><mod>cs</mod><gran>contactlevel</gran><adde>true</adde><upde>true</upde><dele>true</dele></synctype>")); RBuffer.Append(_L("</h><b>")); RBuffer.Append(_L("<share>")); RBuffer.Append(_L("<recipients>")); for(int i=0; i< sharingCount ;i++) { RBuffer.Append(_L("<object>")); RBuffer.Append(_L("<name>")); GetSharingNames(sharingName); converter.ConvertFromUnicodeToUtf8(utf8buf,sharingName); RBuffer.Append(utf8buf);//Album Name RBuffer.Append(_L("</name>")); RBuffer.Append(_L("<mobile>")); GetSharingMails(sharingName); RBuffer.Append(sharingName);//Friend Id's RBuffer.Append(_L("</mobile>")); /*RBuffer.Append(_L("<email>")); GetSharingNames(sharingName); RBuffer.Append(sharingName);//Friend Id's RBuffer.Append(_L("</email>"));*/ RBuffer.Append(_L("</object>")); } RBuffer.Append(_L("</recipients>")); RBuffer.Append(_L("</share>")); RBuffer.Append(_L("</b></root>")); #ifndef WAP_PT HBufC8* content_data; content_data=RBuffer.AllocL(); TBuf8<10> content_l; content_l.Num(content_data->Length()); //RBuffer.Copy(_L("GET /ripple/rippleservlet HTTP/1.0\r\nHOST:\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); RBuffer.Copy(_L("GET ")); RBuffer.Append(iSharingUrl); //RBuffer.Append(_L(" HTTP/1.0\r\nHOST:\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); RBuffer.Append(_L(" HTTP/1.0\r\nHOST:")); RBuffer.Append(iServerAddr); RBuffer.Append(_L("\r\nPORT:")); RBuffer.AppendNum(iPort); RBuffer.Append(_L("\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); RBuffer.Append(content_l); RBuffer.Append(_L("\r\n\r\n")); RBuffer.Append(*content_data); #endif servlet_data = RBuffer.AllocL(); albumName.Copy(_L("")); ConnectToServerForSharing(); } // --------------------------------------------------------- // CRippleVaultAppUi::GetAlbumSynchingXML() // // --------------------------------------------------------- void CRippleVaultAppUi::GetAlbumSynchingXML()//TDes8& RBuffer) { //CloseSocketPublish(); if(!RegFileExists()) { TBuf<128> KRegStep1; KRegStep1 = CRippleVaultAppUi::ApplicationDriveAndPath(); KRegStep1.Append(KRegStep1File); RFs fs; RFile file; fs.Connect(); TInt err = file.Replace(fs, KRegStep1, EFileStreamText|EFileWrite|EFileShareAny); if (err == KErrNone) { file.Close(); } fs.Close(); } TBuf8<1024> RBuffer; RBuffer.Copy(_L("<root><h><msgt>")); RBuffer.Append(_L("albumsynch")); RBuffer.Append(_L("</msgt>")); RBuffer.Append(_L("<msg></msg>")); RBuffer.Append(_L("<uid>")); RBuffer.Append(iUserNames); RBuffer.Append(_L("</uid>")); RBuffer.Append(_L("<hp>")); RBuffer.Append(iMobileNo); RBuffer.Append(_L("</hp>")); RBuffer.Append(_L("<did>")); RBuffer.Append(PhoneImei()); RBuffer.Append(_L("</did>")); RBuffer.Append(_L("<currec></currec><totrec></totrec><loc>en_us</loc><ctime></ctime><lstime>0</lstime><synctype><mod>cs</mod><gran>contactlevel</gran><adde>true</adde><upde>true</upde><dele>true</dele></synctype>")); RBuffer.Append(_L("</h><b></b></root>")); #ifndef WAP_PT HBufC8* content_data; content_data=RBuffer.AllocL(); TBuf8<10> content_l; content_l.Num(content_data->Length()); //RBuffer.Copy(_L("GET /ripple/rippleservlet HTTP/1.0\r\nHOST:\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); RBuffer.Copy(_L("GET ")); //RBuffer.Append(_L("/ripple/publishreghomework")); RBuffer.Append(iAlbumUrl); //RBuffer.Append(_L(" HTTP/1.0\r\nHOST:\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); RBuffer.Append(_L(" HTTP/1.0\r\nHOST:")); RBuffer.Append(iServerAddr); RBuffer.Append(_L("\r\nPORT:")); RBuffer.AppendNum(iPort); RBuffer.Append(_L("\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); RBuffer.Append(content_l); RBuffer.Append(_L("\r\n\r\n")); RBuffer.Append(*content_data); //delete servlet_data; //delete iSocketWriterPublish; #endif servlet_data = RBuffer.AllocL(); ConnectToServerForAlbumSynching(); } // --------------------------------------------------------- // CRippleVaultAppUi::GetSharingNames(TDes& buffer) // // --------------------------------------------------------- void CRippleVaultAppUi::GetSharingNames(TDes& buffer) { TInt pos; pos = MailId.Locate(';'); #ifndef __UIQ__ buffer.Copy(&MailId[0],pos-3); #else buffer.Copy(&MailId[0],pos); #endif pos++; if(pos<MailId.Length()) MailId.Delete(0,pos); } // --------------------------------------------------------- // CRippleVaultAppUi::GetSharingMails(TDes& buffer) // // --------------------------------------------------------- void CRippleVaultAppUi::GetSharingMails(TDes& buffer) { TInt pos; pos = MailNames.Locate(';'); if(pos == KErrNotFound) return; buffer.Copy(&MailNames[0],pos); pos++; if(pos<=MailNames.Length()) MailNames.Delete(0,pos); } // --------------------------------------------------------- // CRippleVaultAppUi::MoreSharingFilesToUpload(TInt flag) // // --------------------------------------------------------- void CRippleVaultAppUi::MoreSharingFilesToUpload(TInt flag) { if(flag == 0)// success for tell a friend { ShowMessageBoxFromResource(R_TEXT_SHARING_APPLICATION_SUCCESS); } else if(flag == 1)// success for album share { ShowMessageBoxFromResource(R_TEXT_SHARING_ALBUM_SUCCESS); } else if(flag == 2)//failure for tell a friend { //ShowMessageBoxFromResource(R_TEXT_SHARING_ALBUM_SUCCESS); } else if(flag == 3)//failure for album share if album empty { ShowMessageBoxFromResource(R_TEXT_SHARING_ALBUM_EMPTY); } else if(flag == 4)//failure for album share if album already shared { ShowMessageBoxFromResource(R_TEXT_SHARING_ALBUM_ALREADY_SHARED); } else if(flag == 5)//failure for album share if mboile not valid { ShowMessageBoxFromResource(R_TEXT_SHARING_ALBUM_INVALID_NUMBER); } else if(flag == 6)//failure for album share if album already shared & rest { ShowMessageBoxFromResource(R_TEXT_SHARING_ALBUM_ALREADY_SHARED_REST); } else if(flag == 7)//failure for album share if mboile not valid & rest { ShowMessageBoxFromResource(R_TEXT_SHARING_ALBUM_INVALID_NUMBER_REST); } else//failure for album share if junk data { ShowMessageBoxFromResource(R_TEXT_SHARING_ALBUM_FAILED); } if (iPhotosDB->RowCountForSharing()) { if(iSocketWriterShare != NULL) { iSocketWriterShare->Disconnect(); delete iSocketWriterShare; iSocketWriterShare = NULL; } CloseConnection(); //SendToServer(); //ConnectToServerForSharing(); TBuf<150> mess; TInt8 sharingCount; GetMails(albumName,MailNames,MailId, mess, sharingCount); if(albumName.Compare(_L("")) == 0) { GetClientSharingAlbumXML(); } else { GetSharingAlbumXML(); } //iConnectionStatus = 2; //CheckSubscriptionStatus(iConnectionStatus); } else { #ifdef __LOGME__ LogText.Copy(_L("moresharing 1\n")); WriteLogFile(LogText); #endif //iScheduled = 0; if(iSocketWriterShare != NULL) { iSocketWriterShare->Disconnect(); delete iSocketWriterShare; iSocketWriterShare = NULL; } CloseConnection(); #ifdef __LOGME__ LogText.Copy(_L("moresharing 2\n")); WriteLogFile(LogText); #endif #ifndef __UIQ__ if(flag == 1 || flag == 3) HandleCommandL(EMainSubView); else HandleCommandL(EMainView); #else ShowWindow(KViewIdStatusScreen); DeleteWindow(KViewIdContactsViewScreen); #endif //GetAlbumSynchingXML(); } } // --------------------------------------------------------- // CRippleVaultAppUi::SendSharingFileComplete(TInt flag) // // --------------------------------------------------------- // called after tail end of protocol data is sent out void CRippleVaultAppUi::SendSharingFileComplete(TInt flag) { /*#ifndef __UIQ__ if(flag == 1) HandleCommandL(EMainSubView); else HandleCommandL(EMainView); #endif*/ iPhotosDB->DeleteSharingsFirstRecord(); //iPhotosDB->AlbumShareStatus(albumName); MoreSharingFilesToUpload(flag); } // --------------------------------------------------------- // CRippleVaultAppUi::SendUnSharingFileComplete() // // --------------------------------------------------------- void CRippleVaultAppUi::SendUnSharingFileComplete() { ShowMessageBoxFromResource(R_TEXT_UNSHARING_ALBUM_SUCCESS); iSocketWriterShare->Disconnect(); delete iSocketWriterShare; iSocketWriterShare = NULL; CloseConnection(); #ifndef __UIQ__ HandleCommandL(EMainSubView); #endif } // --------------------------------------------------------- // CRippleVaultAppUi::ChangePasswordComplete() // // --------------------------------------------------------- void CRippleVaultAppUi::ChangePasswordComplete() { CloseSocketPassword(); SaveUserSettingsToDB(iUserNames, iNewPassword, iMobileNo); TBuf8<150> aValue; TBuf8<150> aParam; aParam.Copy(_L("password")); aValue.Copy(iNewPassword); EditConfigFile(aValue, aParam); ShowMessageBoxFromResource(R_TEXT_CHANGE_PASSWORD_SUCCESS); } // --------------------------------------------------------- // CRippleVaultAppUi::AlbumSynchingComplete() // // --------------------------------------------------------- void CRippleVaultAppUi::AlbumSynchingComplete() { if(!RegFileExists()) { TBuf<128> KRegStep1; KRegStep1 = CRippleVaultAppUi::ApplicationDriveAndPath(); KRegStep1.Append(KRegStep1File); RFs fs1; fs1.Connect(); //delete file //fs1.Delete(KRegStep1); BaflUtils::DeleteFile(fs1, KRegStep1); fs1.Close(); SaveUserSettingsToDB(iUserNames, iPassword, iMobileNo); WritRegisteredFile(); WritUserDetailsToFile(); // EnableUpload(iMode); // EnableSmsUpload(iSmsMode); // EnableContactsUpload(NOT_REGISTERED); UserRegistered(); //UpdateSmsTimestamp(); CloseSocketPublish(); } else { CloseSocketPublish(); //SendToServer(); MoreFilesToUpload(); } /* if(iSocketWriterPublish) { iSocketWriterPublish->Disconnect(); delete iSocketWriterPublish; iSocketWriterPublish=NULL; }*/ // RegChargePublish(); } void CRippleVaultAppUi::WritUserDetailsToFile() { TBuf<60> tmpstr; TBuf<60> pwd; tmpstr.Copy( _L("password")); LoadFromConfigFile(pwd,tmpstr); if(pwd.Compare(_L("")) == 0) { //_LIT(KConfigFile,"config.txt"); RFs fs; fs.Connect(); RFile file; TBuf8<20> name; TInt err; name.Copy(_L("\npassword=")); name.Append(iPassword); name.Append(_L("\n")); TBuf<128> path; path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KConfigFile); err = file.Open(fs, path, EFileWrite); if(err == KErrNone) { file.Seek(ESeekEnd,0); file.Write(name); } file.Close(); fs.Close(); } } // --------------------------------------------------------- // CRippleVaultAppUi::ConnectToServerForSharing() // // --------------------------------------------------------- void CRippleVaultAppUi::ConnectToServerForSharing() { iSocketWriterShare = CSocketsEngineWriter::NewL(*this); iSocketWriterShare->SetServerName(iServerAddr); iSocketWriterShare->SetPort(iPort); iSocketWriterShare->iBuffer.Copy(*servlet_data); iSocketWriterShare->ShareFolders(); delete servlet_data; } // --------------------------------------------------------- // CRippleVaultAppUi::ConnectToServerForUnSharing() // // --------------------------------------------------------- void CRippleVaultAppUi::ConnectToServerForUnSharing() { iSocketWriterShare = CSocketsEngineWriter::NewL(*this); iSocketWriterShare->SetServerName(iServerAddr); iSocketWriterShare->SetPort(iPort); iSocketWriterShare->iBuffer.Copy(*servlet_data); iSocketWriterShare->UnShareFolders(); delete servlet_data; } // --------------------------------------------------------- // CRippleVaultAppUi::ConnectToServerForAlbumSynching() // // --------------------------------------------------------- void CRippleVaultAppUi::ConnectToServerForAlbumSynching() { iSocketWriterPublish = CSocketsEngineWriter::NewL(*this); iSocketWriterPublish->SetServerName(iServerAddr); iSocketWriterPublish->SetPort(iPort); iSocketWriterPublish->iBuffer.Copy(*servlet_data); iSocketWriterPublish->SynchAlbumsForEditing(); delete servlet_data; } // --------------------------------------------------------- // CRippleVaultAppUi::ConnectToServerForChangingNumber() // // --------------------------------------------------------- void CRippleVaultAppUi::ConnectToServerForChangingNumber() { LogText.Copy(_L("ConnectToServerForChangingNumber\n")); WriteLogFile(LogText); if(iSmsSimEngine != NULL) { iSmsSimEngine->Disconnect(); delete iSmsSimEngine; iSmsSimEngine = NULL; } UpdateSimcard(); //iConnectionStatus = 4; //CheckSubscriptionStatus(iConnectionStatus); } // --------------------------------------------------------- // CRippleVaultAppUi::ListAlbums() // // --------------------------------------------------------- #ifndef __UIQ__ TInt CRippleVaultAppUi::ListAlbums() { CDesCArray* array; array = GetFolderList(); if (array) { CAknListQueryDialog* dlg; TInt index=0; dlg = new(ELeave) CAknListQueryDialog(&index); dlg->PrepareLC(R_AKNEXQUERY_LIST_SINGLE_PANE); dlg->SetItemTextArray(array); dlg->SetOwnershipType(ELbmDoesNotOwnItemArray); if(dlg->RunLD()) { TPtrC ptr1(array->MdcaPoint(index)); albumName.Copy(ptr1); //iPhotosAppUi->GetMails(iPhotosAppUi->albumName,iPhotosAppUi->MailNames,iPhotosAppUi->MailId, message); //AppUi()->HandleCommandL(EMailView); iStoragePath = 3; //HandleCommandL(EFindView); delete array; return 1; } else { delete array; return 0; } } else { ShowMessageBoxFromResource(R_TEXT_NOALBUMS); return 0; } } #endif // --------------------------------------------------------- // CRippleVaultAppUi::SetAccesspoint() // Set the active access point, given the APN Name // --------------------------------------------------------- TInt CRippleVaultAppUi::SetAccesspoint() { TInt flag=1; //RGenericAgent netAgent; //if (netAgent.Open() == KErrNone) { TBuf<50> Name; TBuf<50> Name2; TBuf<50> apnname; TUint32 ida1=0; TBuf<20> TableName; TBuf<20> IAPTableName; //netAgent.Stop(); TableName.Copy(_L("OutgoingGPRS")); IAPTableName.Copy(_L("IAP")); TBuf<20> ColName1; ColName1.Copy(_L("Id")); TBuf<20> ColName2; ColName2.Copy(_L("APN")); TBuf<20> ColName3; ColName3.Copy(_L("Name")); //CleanupClosePushL(netAgent); CCommsDatabase* db=CCommsDatabase::NewL(EDatabaseTypeIAP); CleanupStack::PushL(db); CCommsDbTableView* view = db->OpenTableLC(TableName); if(iApnCount == -1) { iApnCount = 0; if(view->GotoFirstRecord()!=KErrNotFound) { do { view->ReadTextL(ColName2, apnname); view->ReadTextL(ColName3, Name); if(apnname.Compare(iAccessPoints)==0) //match { iApnCount++; } } while(view->GotoNextRecord()!=KErrNotFound); } } TInt apncount =0; if(view->GotoFirstRecord()!=KErrNotFound) { do { view->ReadTextL(ColName2, apnname); view->ReadTextL(ColName3, Name); if(apnname.Compare(iAccessPoints)==0) //match { apncount++; if(apncount == iApnCount) { //LogText.Copy(Name); //WriteLogFile(LogText); flag=25; break; } } } while(view->GotoNextRecord()!=KErrNotFound); } if(flag==25) { CCommsDbTableView* view3 = db->OpenTableLC(IAPTableName); if(view3->GotoFirstRecord()!=KErrNotFound) { do { view3->ReadUintL(ColName1, ida1); view3->ReadTextL(ColName3, Name2); if(Name.Compare(Name2)==0) //match { flag=2; iApnConnectionName.Copy(Name); break; } } while(view3->GotoNextRecord()!=KErrNotFound); } CleanupStack::PopAndDestroy(); } if(flag==2) { CCommsDbConnectionPrefTableView* view1 = db->OpenConnectionPrefTableViewOnRankLC(ECommDbConnectionDirectionOutgoing,1); CCommsDbConnectionPrefTableView::TCommDbIapConnectionPref pref; if(view1->GotoFirstRecord()!=KErrNotFound) { view1->ReadConnectionPreferenceL(pref); if(pref.iBearer.iIapId==ida1)// default access point same as the one we want so do nothing { iApnID = ida1; flag = 10; view1->UpdateDialogPrefL(ECommDbDialogPrefDoNotPrompt); } else { iApnID = ida1; CCommsDbConnectionPrefTableView::TCommDbIapConnectionPref aPref; aPref.iBearer.iIapId = ida1; aPref.iDirection = ECommDbConnectionDirectionOutgoing; aPref.iDialogPref = ECommDbDialogPrefDoNotPrompt; aPref.iBearer.iBearerSet = ECommDbBearerGPRS; aPref.iRanking = 1; TRAPD(leaveCode,view1->ChangeConnectionPreferenceRankL(0)); // call a function TRAPD(leaveCode1,view1->InsertConnectionPreferenceL(aPref, EFalse)); // call a function flag = 10; } } else { iApnID = ida1; CCommsDbConnectionPrefTableView::TCommDbIapConnectionPref aPref; aPref.iBearer.iIapId = ida1; aPref.iDirection = ECommDbConnectionDirectionOutgoing; aPref.iDialogPref = ECommDbDialogPrefDoNotPrompt; aPref.iBearer.iBearerSet = ECommDbBearerGPRS; aPref.iRanking = 1; TRAPD(leaveCode1,view1->InsertConnectionPreferenceL(aPref, EFalse)); // call a function flag = 10; } CleanupStack::PopAndDestroy(); } CleanupStack::PopAndDestroy(2); // view, db, netAgent } return flag; } // --------------------------------------------------------- // CRippleVaultAppUi::GetCount(TInt& photocount, TInt& videocount) // // --------------------------------------------------------- void CRippleVaultAppUi::GetCount(TInt& photocount, TInt& videocount) { CDir *dirList; TInt err; RFs session; session.Connect(); if(BaflUtils::FileExists(session, KFolderPhonePhoto)) { err = session.GetDir(KFilesPhonePhoto, KEntryAttNormal, ESortByDate, dirList); photocount = dirList->Count(); } if(BaflUtils::FileExists(session, KFolderMMCPhoto)) { err = session.GetDir(KFilesMMCPhoto, KEntryAttNormal, ESortByDate, dirList); photocount = photocount + dirList->Count(); } if(BaflUtils::FileExists(session, KFolderPhoneVideo)) { err = session.GetDir(KFilesPhoneVideo, KEntryAttNormal, ESortByDate, dirList); videocount = dirList->Count(); } if(BaflUtils::FileExists(session, KFolderMMCVideo)) { err = session.GetDir(KFilesMMCVideo, KEntryAttNormal, ESortByDate, dirList); videocount = videocount + dirList->Count(); } session.Close(); } // --------------------------------------------------------- // CRippleVaultAppUi::AddPhotos() // // --------------------------------------------------------- void CRippleVaultAppUi::AddPhotos() { TInt err=1; RFs session; TBuf<100> filepath; TBuf<100> filepath1; TBuf<30> foldername; TBuf<30> description; CheckAndSaveFolderToDB(*(iEikonEnv->AllocReadResourceL(R_DEFAULT_ALBUM))); foldername.Copy(*(iEikonEnv->AllocReadResourceL(R_DEFAULT_ALBUM))); if(err) { session.Connect(); for(int j=0; j<2 ; j++) { if(j==0) { filepath.Copy(KFilesPhonePhoto); filepath1.Copy(KFolderPhonePhoto); } else if(j==1) { filepath.Copy(KFilesMMCPhoto); filepath1.Copy(KFolderMMCPhoto); } if(BaflUtils::FileExists(session, filepath1)) { CDir *dirList; err = session.GetDir(filepath, KEntryAttNormal, ESortByDate, dirList); CleanupStack::PushL(dirList); if (err != KErrNone) // if error, just return, dir must not exist return; for(int i=0; i<dirList->Count() ; i++) { TParse fullentry; ////// TBuf<160> imageFile; fullentry.Set((*dirList)[i].iName, &filepath, NULL); imageFile.Copy(fullentry.FullName()); //if(j==0 || j==1) AddPhotoRecord(imageFile, EFalse, foldername,description, 0, (*dirList)[i].iSize); //else if(j==2 || j==3) // AddVideoRecord(imageFile, EFalse, foldername,description, 0, (*dirList)[i].iSize); } CleanupStack::PopAndDestroy(); // delete dirList } } session.Close(); //ScheduleToSend(); } } void CRippleVaultAppUi::AddVideos() { TInt err=1; RFs session; TBuf<100> filepath; TBuf<100> filepath1; TBuf<30> foldername; TBuf<30> description; CheckAndSaveFolderToDB(*(iEikonEnv->AllocReadResourceL(R_DEFAULT_ALBUM))); foldername.Copy(*(iEikonEnv->AllocReadResourceL(R_DEFAULT_ALBUM))); if(err) { session.Connect(); for(int j=0; j<2 ; j++) { if(j==0) { filepath.Copy(KFilesPhoneVideo); filepath1.Copy(KFolderPhoneVideo); } else if(j==1) { filepath.Copy(KFilesMMCVideo); filepath1.Copy(KFolderMMCVideo); } if(BaflUtils::FileExists(session, filepath1)) { CDir *dirList; err = session.GetDir(filepath, KEntryAttNormal, ESortByDate, dirList); CleanupStack::PushL(dirList); if (err != KErrNone) // if error, just return, dir must not exist return; for(int i=0; i<dirList->Count() ; i++) { TParse fullentry; ////// TBuf<160> imageFile; fullentry.Set((*dirList)[i].iName, &filepath, NULL); imageFile.Copy(fullentry.FullName()); //if(j==0 || j==1) // AddPhotoRecord(imageFile, EFalse, foldername,description, 0, (*dirList)[i].iSize); //else if(j==2 || j==3) AddVideoRecord(imageFile, EFalse, foldername,description, 0, (*dirList)[i].iSize); } CleanupStack::PopAndDestroy(); // delete dirList } } session.Close(); //ScheduleToSend(); } } // --------------------------------------------------------- // CRippleVaultAppUi::AddTimeStampToFileL(TBuf<256>* timestamp) // // --------------------------------------------------------- void CRippleVaultAppUi::AddTimeStampToFileL(TBuf<256>* timestamp) { RFs fs; RFile file; TBuf8<256> ts; ts.Copy(*timestamp); fs.Connect(); TBuf<128> path; path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KTimeStampFile); TInt err = file.Replace(fs,path ,EFileWrite); HBufC8* data; data = ts.AllocL(); if (err == KErrNone) { User::LeaveIfError(file.Write(*data)); file.Flush(); file.Close(); } delete data; data = NULL; fs.Close(); } // --------------------------------------------------------- // CRippleVaultAppUi::ChangesToBeStoredL(TTime& aCDBTime, TTime& aRippleTime) // // --------------------------------------------------------- //-------------------------------------------------- //On booting, check whether changes need to be stored //-------------------------------------------------- TBool CRippleVaultAppUi::ChangesToBeStoredL(TTime& aCDBTime, TTime& aRippleTime) { TBool returnStatus = EFalse; RFs fs; RFile file; fs.Connect(); // If time stamp file exists check whether it is newer // than that of Contacts DB TBuf<128> path; path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KTimeStampFile); if (BaflUtils::FileExists(fs, path)) { TInt err = file.Open(fs, path, EFileRead); if (err == KErrNone) { // Modification time of Ripple TBuf8<256> rippleTimeStamp; User::LeaveIfError(file.Read(rippleTimeStamp)); TInt64 rippleVal; TBuf<50> str; str.Copy(rippleTimeStamp); TLex lex(str); lex.Val(rippleVal); //RFile cdbFile; // Contact database file CContactDatabase *database; // Contact database TBuf<256> cdbFileName; // Contact db file name database = CContactDatabase::OpenL(); if (database->FindContactFile(cdbFileName)) { TTime cdbTime; fs.Modified(cdbFileName, cdbTime); TDateTime janNineteenSeventy (1970,EJanuary,0,00,00,00,000000); TTime timejan(janNineteenSeventy); TTimeIntervalMicroSeconds interval = cdbTime.MicroSecondsFrom(timejan); TInt64 cdbVal; cdbVal = interval.Int64()/1000; TTimeIntervalMicroSeconds rms= rippleVal * 1000; // Modification time of timestamp file // should always be greater than or equal // to that of contacts DB if (rippleVal < cdbVal) { aRippleTime = TTime(timejan) + rms; aCDBTime = cdbTime; returnStatus = ETrue; } //cdbFile.Close(); //} } delete database; database = NULL; //returnStatus = ETrue; } file.Close(); } fs.Close(); //Print(_L("Exiting ChangesToBeStoredL")); return returnStatus; } // --------------------------------------------------------- // CRippleVaultAppUi::RegisterContactsChangeHandler() // // --------------------------------------------------------- void CRippleVaultAppUi::RegisterContactsChangeHandler() { TRAPD(leaveCode, iContactsDB = CContactDatabase::OpenL()); if (leaveCode != KErrNotFound) { iContactsHandler = CContactsHandler::NewL(this); LoadIPPort(); } } // --------------------------------------------------------- // CRippleVaultAppUi::ReadUserName() // // --------------------------------------------------------- void CRippleVaultAppUi::ReadUserName() { GetUserSettings(iUserNames, iPassword, iMobileNo); iUserName.Copy(iUserNames); /*_LIT(KRegPath1, "RegDetails.dat"); RFs fs; RFile file; fs.Connect(); TBuf<128> path; path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KRegPath1); TInt err = file.Open(fs, path, EFileRead); if (err == KErrNone) { TBuf8<20> userName; User::LeaveIfError(file.Read(userName)); iUserName.Copy(userName); iUserNames.Copy(userName); } file.Close(); fs.Close();*/ } // --------------------------------------------------------- // CRippleVaultAppUi::EnableContactsUpload(TInt aIsRegistered) // // --------------------------------------------------------- void CRippleVaultAppUi::EnableContactsUpload(TInt aIsRegistered) { #ifndef __WINS__ if(iSMSEngine == NULL) { iSMSEngine = CSMSEngine::NewL(*this); iSMSEngine->Start(); } #endif if(iCopyAO == NULL && aIsRegistered == NOT_REGISTERED) // new user { iCopyAO = new (ELeave) CCopyContactsAO(*this); iCopyAO->StartL(); } if(iChangeNotifier== NULL) { iChangeNotifier = CContactChangeNotifier::NewL(*iContactsDB, iContactsHandler); } } // --------------------------------------------------------- // CRippleVaultAppUi::LoadIPPort() // // --------------------------------------------------------- void CRippleVaultAppUi::LoadIPPort() { //TInetAddr ipAddr; TInt portNo; //iListBox->SaveSettingsToDB(); GetContactsSettingsFromDB(iServerAddr , portNo); iPort = portNo; //ipAddr.Output(iServerAddr); } // --------------------------------------------------------- // CRippleVaultAppUi::GetUploadSettingsFromDB(TInt& aAlbum, TInt& aPhoto, TInt& aVideo, TInt& aAlbumShares) // // --------------------------------------------------------- //DB void CRippleVaultAppUi::GetUploadSettingsFromDB(TInt& aAlbum, TInt& aPhoto, TInt& aVideo, TInt& aAlbumShares) { TInt album = 0; TInt photo = 0; TInt video = 0; TInt albumshares = 0; iPhotosDB->GetUploadSettings(album, photo, video, albumshares); aAlbum = album; aPhoto = photo; aVideo = video; aAlbumShares = albumshares; } // --------------------------------------------------------- // CRippleVaultAppUi::GetSettingsFromDB(TDes& aIP, TInt& aPort, TInt& aMode, TInt& aDesc, TInt& aRoam, TInt& aAutostart) // // --------------------------------------------------------- //void CRippleVaultAppUi::GetSettingsFromDB(TDes& aIP, TInt& aPort, TInt& aMode, TInt& aDesc, TInt& aRoam, TInt& aAutostart) //{ //// TUint32 ip = 0; // TUint16 port = 0; // TInt8 mode = 0; // TInt8 desc = 1; // TInt8 roam = 0; // TInt8 autostart=1; // // iPhotosDB->GetSettings(aIP, port, mode, iDefaultFolder, desc, roam, autostart); // // aPort = port; // aMode = mode; // aDesc = desc; // aRoam = roam; // aAutostart = autostart; //} // --------------------------------------------------------- // CRippleVaultAppUi::GetContactsSettingsFromDB(TDes& aIP, TInt& aPort ) // // --------------------------------------------------------- void CRippleVaultAppUi::GetContactsSettingsFromDB(TDes& aIP, TInt& aPort ) { // TUint32 ip = 0; TUint16 port = 0; if(iContactsHandler != NULL) iContactsHandler->iChangesDB->GetSettings(aIP, port ); aPort = port; /* TBuf<16> buf; buf.NumUC(ip); aIP.Input(buf); */ } // --------------------------------------------------------- // CRippleVaultAppUi::GetContactsSettingsFromDB(TInt& aRoam) // // --------------------------------------------------------- void CRippleVaultAppUi::GetContactsSettingsFromDB(TInt& aRoam, TInt& aUpload) { TInt8 roam = 0; TInt8 upload=0; if(iContactsHandler != NULL) iContactsHandler->iChangesDB->GetSettings(roam, upload); aRoam = roam; aUpload = upload; } // --------------------------------------------------------- // CRippleVaultAppUi::SaveContactsSettingsToDB(TDesC& aIP, TUint16 aPort ) // // --------------------------------------------------------- void CRippleVaultAppUi::SaveContactsSettingsToDB(TDesC& aIP, TUint16 aPort ) { iContactsHandler->iChangesDB->SaveSettingsL(aIP, aPort); // save server config /* TInetAddr addr; TBuf<16> buf; buf.NumUC(aIP); addr.Input(buf); addr.Output(buf); */ // iServerAddr.Copy(aIP); // iPort = aPort; } // --------------------------------------------------------- // CRippleVaultAppUi::SaveContactsSettingsToDB(TInt8 aDesc) // // --------------------------------------------------------- void CRippleVaultAppUi::SaveContactsSettingsToDB(TInt8 aDesc, TInt8 aUpload) { iContactsHandler->iContactsUpload = aUpload; iContactsHandler->iContactsRoaming = aDesc; iContactsHandler->iChangesDB->SaveSettingsL(aDesc, aUpload); TTime oldtime; TTime newtime; iPhotosDB->GetContactsSettingsTimestampFromDB(oldtime, newtime); oldtime = newtime; newtime.UniversalTime(); iPhotosDB->UpdateContactsSettingsTimestampToDB(oldtime, newtime); } // --------------------------------------------------------- // CRippleVaultAppUi::SaveSettingsToDB(TDes& aIP, TUint16 aPort, TInt8 aAutostart)//, TInt8 aMode, TInt8 aDesc, TInt8 aRoam) // // --------------------------------------------------------- void CRippleVaultAppUi::SaveSettingsToDB(TDes& aIP, TUint16 aPort, TInt8 aAutostart)//, TInt8 aMode, TInt8 aDesc, TInt8 aRoam) { iPhotosDB->SaveSettingsL(aIP, aPort, aAutostart);//, aMode, iDefaultFolder, aDesc, aRoam); iContactsHandler->iChangesDB->SaveSettingsL(aIP, aPort); TBuf<128> KAutostartSetting; KAutostartSetting = CRippleVaultAppUi::ApplicationDriveAndPath(); KAutostartSetting.Append(KAutostartSettings); // _LIT(KAutostartSetting, "C:\\System\\Apps\\RippleVault\\astart.txt"); //Create AutostartSetting.cfg or delete it according to iAutostart variable // if exists dont autostart else do RFs fs; RFile file; fs.Connect(); if(aAutostart==0){ TInt err = file.Replace(fs, KAutostartSetting, EFileStreamText|EFileWrite|EFileShareAny); if (err == KErrNone) { file.Close(); } } else{ //delete file fs.Delete(KAutostartSetting); } fs.Close(); iServerAddr.Copy(aIP); iPort = aPort; iAutostart = aAutostart; // iMode = aMode; // iDescription = aDesc; // iRoaming = aRoam; TTime oldtime; TTime newtime; iPhotosDB->GetGeneralSettingsTimestampFromDB(oldtime, newtime); oldtime = newtime; newtime.UniversalTime(); iPhotosDB->UpdateGeneralSettingsTimestampToDB(oldtime, newtime); } // --------------------------------------------------------- // CRippleVaultAppUi::SavePhotosSettingsToDB(TInt8 aMode, TInt8 aDesc, TInt8 aRoam, TInt8 aSecureGallery) // // --------------------------------------------------------- void CRippleVaultAppUi::SavePhotosSettingsToDB(TInt8 aMode, TInt8 aDesc, TInt8 aRoam, TInt8 aSecureGallery) { iPhotosDB->SaveSettingsL(aMode, iDefaultFolder, aDesc, aRoam, aSecureGallery); // iServerAddr.Copy(aIP); // iPort = aPort; iMode = aMode; iDescription = aDesc; iRoaming = aRoam; iSecureGallery = aSecureGallery; EnableUpload(iMode); TTime oldtime; TTime newtime; iPhotosDB->GetPublishSettingsTimestampFromDB(oldtime, newtime); oldtime = newtime; newtime.UniversalTime(); iPhotosDB->UpdatePublishSettingsTimestampToDB(oldtime, newtime); } // --------------------------------------------------------- // CRippleVaultAppUi::SaveSmsSettingsToDB(TInt8 aSmsMode, TTime aSmsTime, TInt8 aSmsRoam) // // --------------------------------------------------------- void CRippleVaultAppUi::SaveSmsSettingsToDB(TInt8 aSmsMode, TTime aSmsTime, TInt8 aSmsRoam) { iPhotosDB->SaveSettingsL(aSmsMode, aSmsTime, aSmsRoam); iSmsMode = aSmsMode; iSmsTime = aSmsTime; iSmsRoam = aSmsRoam; EnableSmsUpload(iSmsMode); TTime oldtime; TTime newtime; iPhotosDB->GetSmsSettingsTimestampFromDB(oldtime, newtime); oldtime = newtime; newtime.UniversalTime(); iPhotosDB->UpdateSmsSettingsTimestampToDB(oldtime, newtime); } // --------------------------------------------------------- // CRippleVaultAppUi::GetSettingsFromDB(TDes& aIP, TInt& aPort, TInt& aAuto)//, TInt& aMode, TInt& aDesc, TInt& aRoam) // // --------------------------------------------------------- void CRippleVaultAppUi::GetSettingsFromDB(TDes& aIP, TInt& aPort, TInt& aAuto)//, TInt& aMode, TInt& aDesc, TInt& aRoam) { // TUint32 ip = 0; TUint16 port = 0; TInt8 autostart = 1; // TInt8 mode = 0; // TInt8 desc = 0; // TInt8 roam = 0; iPhotosDB->GetSettings(aIP, port, autostart);//, mode, iDefaultFolder, desc, roam); // GetContactsSettingsFromDB(aIP, port); aPort = port; aAuto = autostart; // aMode = mode; // aDesc = desc; // aRoam = roam; } // --------------------------------------------------------- // CRippleVaultAppUi::GetPhotosSettingsFromDB(TInt& aMode, TInt& aDesc, TInt& aRoam, TInt& aSecureGallery) // // --------------------------------------------------------- void CRippleVaultAppUi::GetPhotosSettingsFromDB(TInt& aMode, TInt& aDesc, TInt& aRoam, TInt& aSecureGallery) { // TUint32 ip = 0; // TUint16 port = 0; TInt8 mode = 0; TInt8 desc = 1; TInt8 roam = 0; TInt8 securegallery = 1; // TInt8 autostart = 1; iPhotosDB->GetSettings(mode, iDefaultFolder, desc, roam, securegallery); // aPort = port; aMode = mode; aDesc = desc; aRoam = roam; aSecureGallery = securegallery; // aStart = autostart; } // --------------------------------------------------------- // CRippleVaultAppUi::GetSmsSettingsFromDB(TInt& aSmsMode, TTime& aSmsTime, TInt& aSmsRoam) // // --------------------------------------------------------- void CRippleVaultAppUi::GetSmsSettingsFromDB(TInt& aSmsMode, TTime& aSmsTime, TInt& aSmsRoam) { TInt8 smsMode = 1; TTime smsTime; TInt8 roam = 0; iPhotosDB->GetSettings(smsMode, smsTime, roam); aSmsMode = smsMode; aSmsTime = smsTime; aSmsRoam = roam; } void CRippleVaultAppUi::SaveTempContactsUploadSettingsToDB(TInt aCount) { iContactsHandler->iChangesDB->SaveTempUploadSettings(aCount); //UpdateScreen(); } void CRippleVaultAppUi::GetTempContactsUploadSettingsFromDB(TInt& aCount) { TInt count = 0; iContactsHandler->iChangesDB->GetTempUploadSettings(count); aCount = count; } // --------------------------------------------------------- // CRippleVaultAppUi::SaveContactsUploadSettingsToDB(TInt aCount) // // --------------------------------------------------------- void CRippleVaultAppUi::SaveContactsUploadSettingsToDB(TInt aCount) { iContactsHandler->iChangesDB->SaveUploadSettings(aCount); } // --------------------------------------------------------- // CRippleVaultAppUi::GetContactsUploadSettingsFromDB(TInt& aCount) // // --------------------------------------------------------- void CRippleVaultAppUi::GetContactsUploadSettingsFromDB(TInt& aCount) { TInt count = 0; iContactsHandler->iChangesDB->GetUploadSettings(count); aCount = count; } // --------------------------------------------------------- // CRippleVaultAppUi::SaveSmsUploadSettingsToDB(TInt aCount) // // --------------------------------------------------------- void CRippleVaultAppUi::SaveSmsUploadSettingsToDB(TInt aCount) { iPhotosDB->SaveSmsCountL(aCount); } // --------------------------------------------------------- // CRippleVaultAppUi::GetSmsUploadSettingsFromDB(TInt& aCount) // // --------------------------------------------------------- void CRippleVaultAppUi::GetSmsUploadSettingsFromDB(TInt& aCount) { TInt count = 0; iPhotosDB->GetSmsCountL(count); aCount = count; } // --------------------------------------------------------- // CRippleVaultAppUi::HideView() // // --------------------------------------------------------- void CRippleVaultAppUi::HideView() { #ifndef __UIQ__ CEikStatusPane* statusPane=iEikonEnv->AppUiFactory()->StatusPane(); statusPane->SwitchLayoutL(R_AVKON_STATUS_PANE_LAYOUT_EMPTY); #endif } #ifdef __UIQ__ // --------------------------------------------------------- // CRippleVaultAppUi::ShowContactsDialog(TDesC& fname) // show the contacts list for UIQ // --------------------------------------------------------- TInt CRippleVaultAppUi::ShowContactsDialog(TDesC& fname) { CEikDialog* selectedcontactsdialog; TInt err; selectedcontactsdialog = new (ELeave) CSelectedContactsDialog(*this); //err = selectedcontactsdialog->ExecuteLD(R_SELECTEDCONTACTS_DIALOG); selectedcontactsdialog->PrepareLC(R_SELECTEDCONTACTS_DIALOG); selectedcontactsdialog->SetTitleL(fname); err = selectedcontactsdialog->RunLD(); return err; } #endif // --------------------------------------------------------- // CRippleVaultAppUi::GetImsiNumber() // Get the IMSI number // --------------------------------------------------------- void CRippleVaultAppUi::GetImsiNumber() { #ifdef __UIQ__ #ifdef __S80__ CIMSI* imsi = CIMSI::NewL(); imsi->GetIMSI(); do { } while (!imsi->IsRetrieved()); iImsiNumber.Copy(imsi->retrievedIMSI); delete imsi; imsi = NULL; #else RFs fs; fs.Connect(); RFile file; _LIT(KImsiFileName,"C:\\System\\data\\imsi.txt"); TInt res = file.Open(fs,KImsiFileName, EFileShareReadersOnly|EFileStreamText); if(res != KErrNone) { //gConsole->Printf(_L("Open failed: %d\n"),res); } else { TBuf8<128> buf; file.Read(buf); file.Close(); fs.Close(); iImsiNumber.Copy(buf); } #endif #else TBuf<255> KTsyName; // Read the TSY name from CommsDB CCommsDatabase* db = CCommsDatabase::NewL(EDatabaseTypeUnspecified); CleanupStack::PushL(db); CCommsDbTableView* table = db->OpenTableLC(TPtrC(MODEM)); table->GotoFirstRecord(); table->ReadTextL(TPtrC(MODEM_TSY_NAME),KTsyName); // Cleanup - CommsDB no longer needed CleanupStack::PopAndDestroy(2); // table,db if (!KTsyName.Length()) { User::Leave(KErrNotFound); } RTelServer server; CleanupClosePushL(server); User::LeaveIfError(server.Connect()); //Load in the phone device driver User::LeaveIfError(server.LoadPhoneModule(KTsyName)); //Find the number of phones available from the tel server TInt numberPhones; User::LeaveIfError(server.EnumeratePhones(numberPhones)); //Check there are available phones if (numberPhones < 1) User::Leave(KErrNotFound); //Get info about the first available phone RTelServer::TPhoneInfo info; User::LeaveIfError(server.GetPhoneInfo(0, info)); #ifdef __NOKIA6600__ RMobilePhone phone; CleanupClosePushL(phone); User::LeaveIfError(phone.Open(server, info.iName)); TRequestStatus status; RMobilePhone::TMobilePhoneSubscriberId aIMSI; phone.GetSubscriberId(status,aIMSI); User::WaitForRequest(status); iImsiNumber.Copy(aIMSI); #else //Use this info to open a connection to the phone, the phone is identified by its name RAdvGsmPhone phone; CleanupClosePushL(phone); User::LeaveIfError(phone.Open(server, info.iName)); TRequestStatus satus; RAdvGsmPhone::TSubscriberId imsiNumber; phone.GetSubscriberId(satus, imsiNumber); User::WaitForRequest(satus); // imsiNumber is a TBuf which contains the IMSI number iImsiNumber.Copy(imsiNumber); #endif CleanupStack::PopAndDestroy();//phone, line //Unload the phone device driver server.UnloadPhoneModule(KTsyName); //Close the connection to the tel server and remove it from the cleanup stack CleanupStack::PopAndDestroy(); #endif } // --------------------------------------------------------- // CRippleVaultAppUi::ImsiCheck() // Check is SIM card has been changed // --------------------------------------------------------- void CRippleVaultAppUi::ImsiCheck() { TBuf<50> file; if(ReadImsiNumber()) { iSmsValue = -1; UpLoadDatas(); } else { //TInt ret = CheckUserId(); TInt ret = 1; if(ret == 1) { TBuf<600> msg; msg.Copy(*(iEikonEnv->AllocReadResourceL(R_RIPPLE_SIM))); msg.Append(iMobileNo); msg.Append(*(iEikonEnv->AllocReadResourceL(R_RIPPLE_SIM1))); #ifndef __UIQ__ CAknMessageQueryDialog* abtdlg = CAknMessageQueryDialog::NewL(msg); abtdlg->PrepareLC(R_SIM_INFO); if (abtdlg->RunLD()) #else #ifdef __S80__ if(CCknConfirmationDialog::RunDlgLD(*(iEikonEnv->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH)),msg)) #else CEikDialog* dialog; dialog = new (ELeave) CCustomMessageDialog(msg, R_EXAMPLE_RIPPLE_PUBLISH); if(dialog->ExecuteLD(R_EIK_DIALOG_YESNO_INFO)) #endif #endif { //sendsms file.Copy(iMobileNo); iTempMbNum.Copy(iMobileNo); if(iSmsSimEngine == NULL) { iSmsSimEngine = CSmsSimEngine::NewL(*this); iSmsSimEngine->Start(); } iSmsFile->CmdSendL(file,file,0); #ifndef __UIQ__ iWaitDialog = new(ELeave)CAknWaitDialog( (REINTERPRET_CAST(CEikDialog**,&(iWaitDialog)))); iWaitDialog->SetTone( CAknNoteDialog::EConfirmationTone ); iWaitDialog->ExecuteLD(R_SMS_DIALOG); #endif } else { //TBuf<600> msg; //msg.Copy(*(iEikonEnv->AllocReadResourceL(R_MSISDN_CHANGE_MESSAGE))); #ifndef __UIQ__ CAknMessageQueryDialog* abtdlg = CAknMessageQueryDialog::NewL(*(iEikonEnv->AllocReadResourceL(R_MSISDN_CHANGE_MESSAGE))); abtdlg->PrepareLC(R_MESSAGE_INFO); if (abtdlg->RunLD()) #else #ifdef __S80__ //if(CCknConfirmationDialog::RunDlgLD(*(iEikonEnv->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH)),*(iEikonEnv->AllocReadResourceL(R_MSISDN_CHANGE_MESSAGE)))) CCknInfoDialog::RunDlgLD(*(iEikonEnv->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH)), *iEikonEnv->AllocReadResourceL(R_MSISDN_CHANGE_MESSAGE)); #else CEikDialog* dialog; //dialog = new (ELeave) CCustomMessageDialog(*(iEikonEnv->AllocReadResourceL(R_MSISDN_CHANGE_MESSAGE)), R_EXAMPLE_RIPPLE_PUBLISH); //if(dialog->ExecuteLD(R_EIK_DIALOG_YESNO_INFO)); dialog = new (ELeave) CCustomMessageDialog(*(iEikonEnv->AllocReadResourceL(R_MSISDN_CHANGE_MESSAGE)), R_EXAMPLE_RIPPLE_PUBLISH); dialog->ExecuteLD(R_EIK_DIALOG_CONTINUE_INFO); #endif #endif { } StopSecure(); User::Exit(EEikCmdExit); //ExitApplication(); /*#ifndef __UIQ__ TBuf<30> number; number.Copy(_L("")); CAknTextQueryDialog* dialog1 = CAknTextQueryDialog::NewL(number); if(dialog1->ExecuteLD(R_MOBILE_NUMBER)) { //sendsms file.Copy(number); iTempMbNum.Copy(number); if(iSmsSimEngine == NULL) { iSmsSimEngine = CSmsSimEngine::NewL(*this); iSmsSimEngine->Start(); } iSmsFile->CmdSendL(file,file,0); } else { ImsiCheck(); } #else CEikDialog* mobdialog; mobdialog = new (ELeave) CMobileDialog(*this); if(mobdialog->ExecuteLD(R_MOBILE_DIALOG)) { //sendsms file.Copy(iTempMbNum); if(iSmsSimEngine == NULL) { iSmsSimEngine = CSmsSimEngine::NewL(*this); iSmsSimEngine->Start(); } iSmsFile->CmdSendL(file,file,0); } else { ImsiCheck(); } #endif */ } } else if(ret == 0) { //TBuf<100> msg; //msg.Copy(*(CEikonEnv::Static()->AllocReadResourceL(R_TEXT_INVALID_USERID_PASSWORD))); #ifndef __UIQ__ /*CAknMessageQueryDialog* abtdlg = CAknMessageQueryDialog::NewL(msg); abtdlg->PrepareLC(R_ABOUT_QUERY); abtdlg->RunLD(); */ ShowMessageBoxFromResource(R_TEXT_INVALID_USERID_PASSWORD); HandleCommandL(EExit); #else //CEikonEnv::Static ()->InfoWinL(*(CEikonEnv::Static()->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH)),msg); ShowMessageBoxFromResource(R_TEXT_INVALID_USERID_PASSWORD); HandleCommandL(TStop); #endif } else { #ifndef __UIQ__ HandleCommandL(EExit); #else HandleCommandL(TStop); #endif } } } // --------------------------------------------------------- // CRippleVaultAppUi::ReadSecureImsiNumber() // Check IMSI number in Scure Folder with IMSI number of SIM // --------------------------------------------------------- TBool CRippleVaultAppUi::ReadSecureImsiNumber() { RFs fs; fs.Connect(); RFile file; TBuf8<20> name; TBuf<20> imsi; TInt err; TBuf<150> path1; path1.Copy(_L("c:\\system\\secure\\")); path1.Append(KIMSIFile); err = file.Open(fs, path1, EFileRead|EFileShareAny); //imsi.Copy(iImsiNumber); if(err == KErrNone) { file.Read(name); imsi.Copy(name); } file.Close(); fs.Close(); if(imsi.Compare(_L("")) == 0) err = 2; else { //if(imsi.Compare(iImsiNumber) == 0) if((imsi.Find(iImsiNumber) >= 0 || iImsiNumber.Find(imsi) >= 0) && imsi.Length() >= 10 && iImsiNumber.Length() >= 10) //new check err = 1; else err = 0; } return err; } // --------------------------------------------------------- // CRippleVaultAppUi::ReadImsiNumber() // Check IMSI number in DB with IMSI number of SIM // --------------------------------------------------------- TBool CRippleVaultAppUi::ReadImsiNumber() { // _LIT(KRegPath1, "Imsi.txt"); RFs fs; fs.Connect(); RFile file; TBuf8<20> name; TBuf<20> imsi; TInt err; TBuf<150> path1; path1 = CRippleVaultAppUi::ApplicationDriveAndPath(); path1.Append(KIMSIFile); err = file.Open(fs, path1, EFileRead|EFileShareAny); if(err == KErrNone) { file.Read(name); imsi.Copy(name); } file.Close(); fs.Close(); //if(imsi.Compare(iImsiNumber) == 0) if((imsi.Find(iImsiNumber) >= 0 || iImsiNumber.Find(imsi) >= 0) && imsi.Length() >= 10 && iImsiNumber.Length() >= 10) //new check err = 1; else err = 0; return err; } // --------------------------------------------------------- // CRippleVaultAppUi::WriteImsiNumber() // Write IMSI number to DB // --------------------------------------------------------- void CRippleVaultAppUi::WriteImsiNumber() { //_LIT(KRegPath1, "Imsi.txt"); RFs fs; fs.Connect(); RFile file; TInt err; TBuf<150> path1; TBuf8<50> name; name.Copy(iImsiNumber); path1 = CRippleVaultAppUi::ApplicationDriveAndPath(); path1.Append(KIMSIFile); err = file.Open(fs, path1, EFileWrite); if (err == KErrNotFound) file.Create(fs, path1, EFileWrite); file.Write(name); file.Close(); fs.Close(); } // --------------------------------------------------------- // CRippleVaultAppUi::ExitApplication() // Exits application after confirm message // --------------------------------------------------------- void CRippleVaultAppUi::ExitApplication() { #ifndef __UIQ__ CAknMessageQueryDialog* abtdlg = CAknMessageQueryDialog::NewL(*(iEikonEnv->AllocReadResourceL(R_MSISDN_CHANGE_MESSAGE))); abtdlg->PrepareLC(R_MESSAGE_INFO); if (abtdlg->RunLD()) #else #ifdef __S80__ //if(CCknConfirmationDialog::RunDlgLD(*(iEikonEnv->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH)),*(iEikonEnv->AllocReadResourceL(R_MSISDN_CHANGE_MESSAGE)))) CCknInfoDialog::RunDlgLD(*(iEikonEnv->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH)), *iEikonEnv->AllocReadResourceL(R_MSISDN_CHANGE_MESSAGE)); #else CEikDialog* dialog; //dialog = new (ELeave) CCustomMessageDialog(*(iEikonEnv->AllocReadResourceL(R_MSISDN_CHANGE_MESSAGE)), R_EXAMPLE_RIPPLE_PUBLISH); //if(dialog->ExecuteLD(R_EIK_DIALOG_YESNO_INFO)); dialog = new (ELeave) CCustomMessageDialog(*(iEikonEnv->AllocReadResourceL(R_MSISDN_CHANGE_MESSAGE)), R_EXAMPLE_RIPPLE_PUBLISH); dialog->ExecuteLD(R_EIK_DIALOG_CONTINUE_INFO); #endif #endif { } if(iSmsSimEngine != NULL) { iSmsSimEngine->Disconnect(); delete iSmsSimEngine; iSmsSimEngine = NULL; } //StopSecure(); User::Exit(EEikCmdExit); //TBuf<100> msg; //msg.Copy(*(iEikonEnv->AllocReadResourceL(R_RIPPLE_CLOSE))); /* #ifndef __UIQ__ CAknMessageQueryDialog* abtdlg = CAknMessageQueryDialog::NewL(*(iEikonEnv->AllocReadResourceL(R_RIPPLE_CLOSE))); abtdlg->PrepareLC(R_SIM_INFO); if (abtdlg->RunLD()) #else #ifdef __S80__ if(CCknConfirmationDialog::RunDlgLD(*(iEikonEnv->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH)),*(iEikonEnv->AllocReadResourceL(R_RIPPLE_CLOSE)))) #else CEikDialog* dialog; dialog = new (ELeave) CCustomMessageDialog(*(iEikonEnv->AllocReadResourceL(R_RIPPLE_CLOSE)), R_EXAMPLE_RIPPLE_PUBLISH); if(dialog->ExecuteLD(R_EIK_DIALOG_YESNO_INFO)) #endif #endif { if(iSmsSimEngine != NULL) { iSmsSimEngine->Disconnect(); delete iSmsSimEngine; iSmsSimEngine = NULL; } #ifndef __UIQ__ if(iWaitDialog == NULL) HandleCommandL(EExit); #else HandleCommandL(TStop); #endif } else { #ifndef __UIQ__ if(iSmsSimEngine != NULL) { iSmsSimEngine->Disconnect(); delete iSmsSimEngine; iSmsSimEngine = NULL; } #endif ImsiCheck(); } */ } // --------------------------------------------------------- // CRippleVaultAppUi::ShowView() // Photos/Videos Gallery for UIQ // --------------------------------------------------------- #ifdef __UIQ__ void CRippleVaultAppUi::ShowView() { TInt8 choice=0; GetChoice(choice); if(iImageFlag == 1 || iImageFlag == 2) { /*if(choice == 0) { iImageFlag = 3; ShowWindow(KViewIdVideoList); //video screen DeleteWindow(KViewIdPhotoList); //photo screen } else {*/ ShowWindow(KViewIdStatusScreen); //main screen DeleteWindow(KViewIdPhotoList); //photo screen //} } else if(iImageFlag == 3 || iImageFlag == 4) { ShowWindow(KViewIdStatusScreen); //main screen DeleteWindow(KViewIdVideoList); //video screen //if(choice == 0) //{ // CallSetupWizardStep12(); //} } else if(iImageFlag == 5 || iImageFlag == 6) { ShowWindow(KViewIdStatusScreen); //main screen DeleteWindow(KViewIdSmsList); //sms screen //SaveChoice(1); } } // --------------------------------------------------------- // CRippleVaultAppUi::ShowToolBar() // Shows sub screen for UIQ // --------------------------------------------------------- /* void CRippleVaultAppUi::ShowToolBar() { #ifndef __S80__ CQikAppUi* appUi = STATIC_CAST(CQikAppUi*, iEikonEnv->AppUi()); appUi->SetToolbarL(R_SCREENLIST_TOOLBAR); //iMainScreenView->UpdateListBoxL(iMainScreenValue); #endif } */ void CRippleVaultAppUi::SecureDialog() { CEikDialog* dialog; dialog = new (ELeave) CSecureSettingDialog(*this); dialog->ExecuteLD(R_SECURE_SETTINGS); } /* void CRippleVaultAppUi::ShowSettingsScreen(TInt aIndex) { #ifndef __S80__ TInt err; CEikDialog* dialog; if( iMainScreenValue == 1)//contacts { if( aIndex == 1)//send to vault { //iConnectionStatus = 2; //CheckSubscriptionStatus(iConnectionStatus); } else if( aIndex == 2)//settings { dialog = new (ELeave) CContactsSettingDialog(*this); err = dialog->ExecuteLD(R_CONTACTS_SETTINGS); } } else if( iMainScreenValue == 2)//photos { if( aIndex == 1)//send to vault { iImageFlag = 1; ShowWindow(KViewIdPhotoList); //photo screen DeleteWindow(KViewIdStatusScreen); //main screen } else if( aIndex == 3)//sharing { MailNames.Copy(_L("")); MailId.Copy(_L("")); albumName.Copy(_L("")); iMessage.Copy(_L("")); iStoragePath = 2; ShowWindow(KViewIdContactsViewScreen); DeleteWindow(KViewIdStatusScreen); } else if( aIndex == 4)//unsharing { dialog = new (ELeave) CUnShareAlbumDialog(*this); err = dialog->ExecuteLD(R_FOLDER_DIALOG1); } else if( aIndex == 5)//settings { dialog = new (ELeave) CPhotosSettingDialog(*this); err = dialog->ExecuteLD(R_PHOTOS_SETTINGS); } } else if( iMainScreenValue == 3)//Videos { if( aIndex == 1)//send to vault { iImageFlag = 3; ShowWindow(KViewIdVideoList); //video screen DeleteWindow(KViewIdStatusScreen); //main screen } else if( aIndex == 3)//sharing { MailNames.Copy(_L("")); MailId.Copy(_L("")); albumName.Copy(_L("")); iMessage.Copy(_L("")); iStoragePath = 2; ShowWindow(KViewIdContactsViewScreen); DeleteWindow(KViewIdStatusScreen); } else if( aIndex == 4)//unsharing { dialog = new (ELeave) CUnShareAlbumDialog(*this); dialog->ExecuteLD(R_FOLDER_DIALOG1); } else if( aIndex == 5)//settings { dialog = new (ELeave) CVideosSettingDialog(*this); err = dialog->ExecuteLD(R_VIDEOS_SETTINGS); } } else if( iMainScreenValue == 4)//sms { if( aIndex == 1)//send to vault { iImageFlag = 5; ShowWindow(KViewIdSmsList); //sms screen DeleteWindow(KViewIdStatusScreen); //main screen } else if( aIndex == 3)//settings { dialog = new (ELeave) CSmsSettingDialog(*this); err = dialog->ExecuteLD(R_SMS_SETTINGS); if(err) if(iSmsMode == 0) { MailNames.Copy(_L("")); MailId.Copy(_L("")); albumName.Copy(_L("")); iMessage.Copy(_L("")); iStoragePath = 1; ShowWindow(KViewIdContactsViewScreen); DeleteWindow(KViewIdStatusScreen); } } } #endif } */ // --------------------------------------------------------- // CRippleVaultAppUi::ShowStatusScreen() // Show Status Screen for UIQ // --------------------------------------------------------- void CRippleVaultAppUi::ShowStatusScreen() { TBuf<50> iLabelTitle; // example label TBuf<50> iLabelPendingItems; // example label TBuf<50> iLabelContactsCount; // example label TBuf<50> iLabelPhotosCount; // example label TBuf<50> iLabelVersion; // example label TBuf<50> iLabelAppStatus; // example label TBuf<50> iLabelErrStatus; // example label TBuf<50> iLabelUploadedItems; // example label TBuf<50> iLabelUploadedContactsCount; // example label TBuf<50> iLabelUploadedPhotosCount; // example label isDoingSomething = EFalse; isQueuedInfo = EFalse; TBuf<50> message; TBuf<50> formatBuf; TInt ccounttemp; TInt pendingitems=0; GetTempContactsUploadSettingsFromDB(ccounttemp); //get temp contacts count GetContactsParams(pendingitems); // get total contacts count iPendingCountContacts = pendingitems - ccounttemp; ccounttemp = 0; //pendingitems = iPhotosAppUi->iPhotosDB->RowCount(); // get media pending count iPendingCountPhotos = iPhotosDB->PhotosRowCount(); iPendingCountVideos = iPhotosDB->VideosRowCount(); //pendingitems -= ccounttemp; // subtract sent items if(iPendingCountContacts<0) // negative items make no sense:-) iPendingCountContacts = 0; //iPendingCount = pendingitems; iPendingCountSms = iSmsCount + iAutoSmsCount; iLabelTitle.Copy(*(iEikonEnv->AllocReadResourceL(R_EXAMPLE_RUNNING))); TBuf<50> dum; TInt code; code = GetNetworkStatusCode(dum); if((iPendingCountContacts + iPendingCountPhotos + iPendingCountVideos + iPendingCountSms > 0) || code != NETWORK_STATUS_RUNNING) { isQueuedInfo = ETrue; message.Copy(_L("")); //formatBuf.Copy(_L("")); message.Append(*(iEikonEnv->AllocReadResourceL(R_STATUSTEXT_ITEMS_PENDING))); //message.Format(formatBuf, pendingitems); iLabelPendingItems.Copy(message); //------------------------- message.Copy(_L("")); iLabelContactsCount.Copy(message); if(iPendingCountContacts>0 || (iPendingCountContacts == 0 && !isQueuedInfo)){ ccounttemp++; formatBuf.Copy(_L("")); formatBuf.Append(*(iEikonEnv->AllocReadResourceL(R_STATUSTEXT_CONTACTS_UPLOADED))); message.Format(formatBuf, iPendingCountContacts); iLabelContactsCount.Append(message); } message.Copy(_L("")); iLabelPhotosCount.Copy(message); if(iPendingCountSms>0 || (iPendingCountSms == 0 && !isQueuedInfo)){ ccounttemp++; formatBuf.Copy(_L("")); formatBuf.Append(*(iEikonEnv->AllocReadResourceL(R_STATUSTEXT_SMS_UPLOADED))); message.Format(formatBuf, iPendingCountSms); //#ifdef __S80__ if(ccounttemp == 2) iLabelContactsCount.Append(_L(", ")); iLabelContactsCount.Append(message); /*#else if(ccounttemp == 1) iLabelContactsCount.Append(message); else iLabelPhotosCount.Append(message); #endif*/ } message.Copy(_L("")); if(iPendingCountPhotos>0 || (iPendingCountPhotos == 0 && !isQueuedInfo)){ ccounttemp++; formatBuf.Copy(_L("")); formatBuf.Append(*(iEikonEnv->AllocReadResourceL(R_STATUSTEXT_PHOTOS_UPLOADED))); message.Format(formatBuf, iPendingCountPhotos); //#ifdef __S80__ if(ccounttemp == 2) iLabelContactsCount.Append(_L(", ")); if(ccounttemp > 2) iLabelPhotosCount.Append(message); else iLabelContactsCount.Append(message); /*#else if(ccounttemp > 2) iLabelPhotosCount.Append(_L(", ")); if(ccounttemp > 1) iLabelPhotosCount.Append(message); else iLabelContactsCount.Append(message); #endif*/ } message.Copy(_L("")); if(iPendingCountVideos>0 || (iPendingCountVideos == 0 && !isQueuedInfo)){ ccounttemp++; formatBuf.Copy(_L("")); formatBuf.Append(*(iEikonEnv->AllocReadResourceL(R_STATUSTEXT_VIDEOS_UPLOADED))); message.Format(formatBuf, iPendingCountVideos); //#ifdef __S80__ if(ccounttemp == 2) iLabelContactsCount.Append(_L(", ")); else if (ccounttemp == 4) iLabelPhotosCount.Append(_L(", ")); if(ccounttemp > 2) iLabelPhotosCount.Append(message); else iLabelContactsCount.Append(message); /*#else if(ccounttemp > 2) iLabelPhotosCount.Append(_L(", ")); if(ccounttemp > 1) iLabelPhotosCount.Append(message); else iLabelContactsCount.Append(message); #endif*/ } //} if((iPendingCountContacts + iPendingCountPhotos + iPendingCountVideos + iPendingCountSms == 0) && isQueuedInfo) { iLabelContactsCount.Copy(*(iEikonEnv->AllocReadResourceL(R_STATUSTEXT_ZEROITEMS))); } TInt album; TInt albumshares; GetUploadSettingsFromDB(album, iPendingCountPhotos, iPendingCountVideos, albumshares); GetContactsUploadSettingsFromDB(iPendingCountContacts); GetSmsUploadSettingsFromDB(iPendingCountSms); //------------------------- } else { isQueuedInfo = EFalse; TInt album; TInt albumshares; GetUploadSettingsFromDB(album, iPendingCountPhotos, iPendingCountVideos, albumshares); GetContactsUploadSettingsFromDB(iPendingCountContacts); GetSmsUploadSettingsFromDB(iPendingCountSms); //message.Copy(_L("")); //formatBuf.Copy(_L("")); //message.Append(*(iEikonEnv->AllocReadResourceL(R_STATUSTEXT_ITEMS_UPLOADED))); //message.Format(formatBuf, pendingitems); iLabelTitle.Copy(*(iEikonEnv->AllocReadResourceL(R_STATUSTEXT_LASTSYNCH))); } iLabelUploadedItems.Copy(*(iEikonEnv->AllocReadResourceL(R_STATUSTEXT_ITEMS_UPLOADED))); //{ message.Copy(_L("")); iLabelUploadedContactsCount.Copy(message); ccounttemp = 0; if(iPendingCountContacts>0 || (iPendingCountContacts == 0 && !isQueuedInfo)){ ccounttemp++; formatBuf.Copy(_L("")); formatBuf.Append(*(iEikonEnv->AllocReadResourceL(R_STATUSTEXT_CONTACTS_UPLOADED))); message.Format(formatBuf, iPendingCountContacts); iLabelUploadedContactsCount.Append(message); } message.Copy(_L("")); if(iPendingCountSms>0 || (iPendingCountSms == 0 && !isQueuedInfo)){ ccounttemp++; formatBuf.Copy(_L("")); formatBuf.Append(*(iEikonEnv->AllocReadResourceL(R_STATUSTEXT_SMS_UPLOADED))); message.Format(formatBuf, iPendingCountSms); //#ifdef __S80__ if(ccounttemp == 2) iLabelUploadedContactsCount.Append(_L(", ")); iLabelUploadedContactsCount.Append(message); /*#else if(ccounttemp == 1) iLabelUploadedContactsCount.Append(message); else iLabelUploadedPhotosCount.Append(message); #endif*/ } message.Copy(_L("")); iLabelUploadedPhotosCount.Copy(message); if(iPendingCountPhotos>0 || (iPendingCountPhotos == 0 && !isQueuedInfo)){ ccounttemp++; formatBuf.Copy(_L("")); formatBuf.Append(*(iEikonEnv->AllocReadResourceL(R_STATUSTEXT_PHOTOS_UPLOADED))); message.Format(formatBuf, iPendingCountPhotos); //#ifdef __S80__ if(ccounttemp == 2) iLabelUploadedContactsCount.Append(_L(", ")); if(ccounttemp > 2) iLabelUploadedPhotosCount.Append(message); else iLabelUploadedContactsCount.Append(message); /*#else if(ccounttemp > 2) iLabelUploadedPhotosCount.Append(_L(", ")); if(ccounttemp > 1) iLabelUploadedPhotosCount.Append(message); else iLabelUploadedContactsCount.Append(message); #endif*/ } message.Copy(_L("")); if(iPendingCountVideos>0 || (iPendingCountVideos == 0 && !isQueuedInfo)){ ccounttemp++; formatBuf.Copy(_L("")); formatBuf.Append(*(iEikonEnv->AllocReadResourceL(R_STATUSTEXT_VIDEOS_UPLOADED))); message.Format(formatBuf, iPendingCountVideos); //#ifdef __S80__ if(ccounttemp == 2) iLabelUploadedContactsCount.Append(_L(", ")); else if (ccounttemp == 4) iLabelUploadedPhotosCount.Append(_L(", ")); if(ccounttemp > 2) iLabelUploadedPhotosCount.Append(message); else iLabelUploadedContactsCount.Append(message); /*#else if(ccounttemp > 2) iLabelUploadedPhotosCount.Append(_L(", ")); if(ccounttemp > 1) iLabelUploadedPhotosCount.Append(message); else iLabelUploadedContactsCount.Append(message); #endif*/ } //} //else if((iPendingCountContacts + iPendingCountPhotos + iPendingCountVideos + iPendingCountSms == 0) && isQueuedInfo) { iLabelUploadedContactsCount.Copy(*(iEikonEnv->AllocReadResourceL(R_STATUSTEXT_ZEROITEMS))); } message.Copy(_L("v")); message.Append(iVersion); iLabelVersion.Copy(message); message.Copy(_L("")); // Application status iStatusCode = GetNetworkStatusCode(message); if(iStatusCode != NETWORK_STATUS_FAILED && iStatusCode != NETWORK_STATUS_RUNNING) { isDoingSomething = ETrue; } if(message.Compare(_L("")) == 0){ message.Copy(*(iEikonEnv->AllocReadResourceL(R_STATUSTEXT_RUNNING))); } if(!ReadImsiNumber()){ isDoingSomething = EFalse; message.Copy(*(iEikonEnv->AllocReadResourceL(R_TEXT_NETWORK_STATUS_SUSPENDED_SIMCHANGE))); } iLabelAppStatus.Copy(message); if(!isQueuedInfo) { isDoingSomething = EFalse; TBuf<160> message; TTime btime; iPhotosDB->GetBackupTimestampFromDB(btime); TDateTime aDateTime = btime.DateTime(); _LIT(KFormatTxt,"%d/%d/%d %S:%S:%S "); TBuf<2> ampm; TInt hour = aDateTime.Hour(); if(hour>12) { hour=hour-12; ampm.Copy(_L("pm")); } else if(hour == 12) { ampm.Copy(_L("pm")); } else if(hour == 0) { hour = 12; ampm.Copy(_L("am")); } else { ampm.Copy(_L("am")); } message.Copy(_L("")); TInt min = aDateTime.Minute(); TInt sec = aDateTime.Second(); TBuf<2> hourbuf; TBuf<2> minbuf; TBuf<2> secbuf; hourbuf.Copy(_L("")); minbuf.Copy(_L("")); secbuf.Copy(_L("")); if(hour < 10) { hourbuf.Append(_L("0")); hourbuf.AppendNum(hour); } else hourbuf.AppendNum(hour); if(min < 10) { minbuf.Append(_L("0")); minbuf.AppendNum(min); } else minbuf.AppendNum(min); if(sec < 10) { secbuf.Append(_L("0")); secbuf.AppendNum(sec); } else secbuf.AppendNum(sec); message.Format(KFormatTxt, aDateTime.Day()+1, TInt(aDateTime.Month()+1), aDateTime.Year(), &hourbuf, &minbuf, &secbuf); message.Append(ampm); #ifdef __LOGME__ LogText.Copy(_L("\nBackup Time=")); LogText.Append(message); LogText.Append(_L("\n")); WriteLogFile(LogText); #endif iLabelAppStatus.Copy(message); } isError = EFalse; message.Copy(_L("")); iErrCode = GetNetworkErrorCode(message); if(iErrCode!=0) isError = ETrue; isUpgrade = EFalse; TInt8 choice; TBuf<50> vers; GetUpgradeStatus(choice, vers); if(choice == 1) { isUpgrade = ETrue; formatBuf.Copy(_L("")); formatBuf.Append(*(iEikonEnv->AllocReadResourceL(R_TEXT_UPGRADE_AVAILABLE))); message.Copy(_L("")); message.Format(formatBuf, &vers); } iLabelErrStatus.Copy(message); //ShowWindow(5); //status screen //DeleteWindow(1); //main screen iStatusScreenView->ApplicationStatus(iLabelTitle, iLabelVersion, iLabelAppStatus, iLabelPendingItems, iLabelContactsCount, iLabelPhotosCount, iLabelErrStatus, isDoingSomething, isQueuedInfo, iLabelUploadedItems, iLabelUploadedContactsCount, iLabelUploadedPhotosCount); /*TBool pending; pending = EFalse; if(((iPendingCountContacts + iPendingCountPhotos + iPendingCountVideos) > 0) && (iStatusCode == NETWORK_STATUS_RUNNING || iStatusCode == NETWORK_STATUS_FAILED)) pending = ETrue; if(!isQueuedInfo) pending = EFalse; */ // aMenuPane->SetItemDimmed(ESendToWeb, !pending); // aMenuPane->SetItemDimmed(EAboutErrorCode, !isError); #ifdef __S80__ iCBA->SetCommandSetL(R_STATUSSCREEN_CBA); //iCBA->DimCommand(ESendToWeb, !pending); //iCBA->DimCommand(EAboutErrorCode, !isError); //iCBA->DimCommand(EShowUploadCount, !isQueuedInfo); iCBA->DrawNow(); #endif } #endif // --------------------------------------------------------- // CRippleVaultAppUi::EnablePhotosUpload() // checks DB and connects to server for photos/videos upload // --------------------------------------------------------- void CRippleVaultAppUi::EnablePhotosUpload() { //CEikonEnv::Static ()->AlertWin(_L("helpme")); if (iPhotosDB->RowCount()) { if(iSocketWriterPublish == NULL) { //SendToServer(); iConnectionStatus = 1; CheckSubscriptionStatus(iConnectionStatus); } } } // --------------------------------------------------------- // CRippleVaultAppUi::DeleteFolderFromDB(TDesC& aFolder) // Delete album // --------------------------------------------------------- TInt CRippleVaultAppUi::DeleteFolderFromDB(TDesC& aFolder) { TInt ret; ret = iPhotosDB->CheckAndDeleteFolder(aFolder); return ret; } // --------------------------------------------------------- // CRippleVaultAppUi::EditFolderFromDB(TDesC& aOldFolder, TDesC& aNewFolder) // Edit album // --------------------------------------------------------- TInt CRippleVaultAppUi::EditFolderFromDB(TDesC& aOldFolder, TDesC& aNewFolder) { TInt ret; ret = iPhotosDB->CheckAndEditFolder(aOldFolder, aNewFolder); return ret; } // --------------------------------------------------------- // CRippleVaultAppUi::CheckBillingStatus(TInt aStatus) // Gets Billing Status XML // --------------------------------------------------------- /* void CRippleVaultAppUi::CheckBillingStatus(TInt aStatus) { TBuf8<1024> RBuffer; HBufC* synctime; TBuf<30> time; TInt err; RBuffer.Copy(_L("<root><h><msgt>")); RBuffer.Append(_L("mo_sent")); RBuffer.Append(_L("</msgt>")); RBuffer.Append(_L("<msg></msg>")); RBuffer.Append(_L("<uid>")); RBuffer.Append(iUserNames); RBuffer.Append(_L("</uid>")); RBuffer.Append(_L("<hp>")); RBuffer.Append(iMobileNo); RBuffer.Append(_L("</hp>")); RBuffer.Append(_L("<did>")); RBuffer.Append(PhoneImei()); RBuffer.Append(_L("</did>")); RBuffer.Append(_L("<currec></currec><totrec></totrec><loc>en_us</loc><ctime></ctime><lstime>0</lstime><synctype><mod>cs</mod><gran>contactlevel</gran><adde>true</adde><upde>true</upde><dele>true</dele></synctype>")); RBuffer.Append(_L("</h><b>")); RBuffer.Append(_L("<last-sync-timestamp>")); GetSubStatusSyncTime(time); RBuffer.Append(time); RBuffer.Append(_L("</last-sync-timestamp>")); RBuffer.Append(_L("</b></root>")); HBufC8* content_data; content_data=RBuffer.AllocL(); TBuf8<10> content_l; content_l.Num(content_data->Length()); RBuffer.Copy(_L("GET ")); RBuffer.Append(iStatusUrl); //RBuffer.Append(_L(" HTTP/1.0\r\nHOST:\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); RBuffer.Append(_L(" HTTP/1.0\r\nHOST:")); RBuffer.Append(iServerAddr); RBuffer.Append(_L("\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); RBuffer.Append(content_l); RBuffer.Append(_L("\r\n\r\n")); RBuffer.Append(*content_data); servlet_data = RBuffer.AllocL(); ConnectToServerForSubscription(aStatus); //WriteLogFile(RBuffer); } */ void CRippleVaultAppUi::UpdateContacts(TInt mode) { TInt network; network = CheckNetwork(); if(network == NETWORK_ROAMING) { #ifdef __LOGME__ LogText.Copy(_L("UpdateContacts 1\n")); WriteLogFile(LogText); #endif if(iContactsHandler->iContactsRoaming == 1) { #ifdef __LOGME__ LogText.Copy(_L("UpdateContacts 2\n")); WriteLogFile(LogText); #endif if(iContactsHandler->iSocketsEngine == NULL ) { #ifdef __LOGME__ LogText.Copy(_L("UpdateContacts 3\n")); WriteLogFile(LogText); #endif if(mode == 0){ #ifdef __LOGME__ LogText.Copy(_L("status sub for contacts\n")); WriteLogFile(LogText); #endif iConnectionStatus = 2; } else{ #ifdef __LOGME__ LogText.Copy(_L("status sub for incremental contacts change\n")); WriteLogFile(LogText); #endif iConnectionStatus = 6; } CheckSubscriptionStatus(iConnectionStatus); } } } else { #ifdef __LOGME__ LogText.Copy(_L("UpdateContacts 4\n")); WriteLogFile(LogText); #endif if(iContactsHandler->iSocketsEngine == NULL ) { #ifdef __LOGME__ LogText.Copy(_L("UpdateContacts 5\n")); WriteLogFile(LogText); #endif if(mode == 0){ #ifdef __LOGME__ LogText.Copy(_L("status sub for contacts\n")); WriteLogFile(LogText); #endif iConnectionStatus = 2; } else{ #ifdef __LOGME__ LogText.Copy(_L("status sub for incremental contacts change\n")); WriteLogFile(LogText); #endif iConnectionStatus = 6; } CheckSubscriptionStatus(iConnectionStatus); } } } void CRippleVaultAppUi::UpdateContactsManually() { TInt network; network = CheckNetwork(); TBuf<128> path; path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KInitUploadFile); RFs fs1; fs1.Connect(); //delete file //fs1.Delete(KRegStep1); if(network == NETWORK_ROAMING) { #ifdef __LOGME__ LogText.Copy(_L("UpdateContacts 1\n")); WriteLogFile(LogText); #endif if(iContactsHandler->iContactsRoaming == 1) { #ifdef __LOGME__ LogText.Copy(_L("UpdateContacts 4\n")); WriteLogFile(LogText); #endif if(!BaflUtils::FileExists(fs1, path)) { iConnectionStatus = 2; CheckSubscriptionStatus(iConnectionStatus); } ShowMessageBoxFromResource(R_TEXT_CONTACTS_SENDTOWEB); } else { RoamingDisabledDialogContacts(); } } else { #ifdef __LOGME__ LogText.Copy(_L("UpdateContacts 4\n")); WriteLogFile(LogText); #endif if(!BaflUtils::FileExists(fs1, path)) { iConnectionStatus = 2; CheckSubscriptionStatus(iConnectionStatus); } ShowMessageBoxFromResource(R_TEXT_CONTACTS_SENDTOWEB); } fs1.Close(); } // --------------------------------------------------------- // CRippleVaultAppUi::CheckSubscriptionStatus(TInt aStatus) // Gets Subscription Status XML // --------------------------------------------------------- void CRippleVaultAppUi::CheckSubscriptionStatus(TInt aStatus) { #ifdef __LOGME__ LogText.Copy(_L("CheckSubscriptionStatus 1\n")); WriteLogFile(LogText); #endif TBuf8<1024> RBuffer; //HBufC* synctime; //TTime time; TBuf<30> time; TInt err; RBuffer.Copy(_L("<root><h><msgt>")); RBuffer.Append(_L("prof_update")); RBuffer.Append(_L("</msgt>")); RBuffer.Append(_L("<msg></msg>")); RBuffer.Append(_L("<uid>")); RBuffer.Append(iUserNames); RBuffer.Append(_L("</uid>")); RBuffer.Append(_L("<hp>")); RBuffer.Append(iMobileNo); RBuffer.Append(_L("</hp>")); RBuffer.Append(_L("<did>")); RBuffer.Append(PhoneImei()); RBuffer.Append(_L("</did>")); RBuffer.Append(_L("<currec></currec><totrec></totrec><loc>en_us</loc><ctime></ctime><lstime>0</lstime><synctype><mod>cs</mod><gran>contactlevel</gran><adde>true</adde><upde>true</upde><dele>true</dele></synctype>")); RBuffer.Append(_L("</h><b>")); RBuffer.Append(_L("<last-sync-timestamp>")); GetSubStatusSyncTime(time); //TBuf<30> tempbuf; //tempbuf.Copy(time); //CEikonEnv::Static ()->AlertWin(tempbuf); //synctime = GetTimeStamp(time); //RBuffer.Append(*synctime); RBuffer.Append(time); RBuffer.Append(_L("</last-sync-timestamp>")); RBuffer.Append(_L("<user-prof>")); RBuffer.Append(_L("<param name=\"payment-type\" value=\"")); RBuffer.Append(iConnectionType); RBuffer.Append(_L("\"/>")); err = ReadImsiNumber(); if(!err) { RBuffer.Append(_L("<param name=\"imsi\" value=\"")); RBuffer.Append(iImsiNumber); RBuffer.Append(_L("\"/>")); RBuffer.Append(_L("<param name=\"msisdn\" value=\"")); //RBuffer.Append(iMobileNo); RBuffer.Append(iTempMbNum); RBuffer.Append(_L("\"/>")); } GetSettingsString(); RBuffer.Append(_L("<param name=\"settings\" value=\"")); RBuffer.Append(iSettingsString); RBuffer.Append(_L("\"/>")); RBuffer.Append(_L("</user-prof>")); RBuffer.Append(_L("<sys-prof>")); RBuffer.Append(_L("</sys-prof>")); RBuffer.Append(_L("</b></root>")); #ifndef WAP_PT HBufC8* content_data; content_data=RBuffer.AllocL(); TBuf8<10> content_l; content_l.Num(content_data->Length()); RBuffer.Copy(_L("GET ")); RBuffer.Append(iStatusUrl); //RBuffer.Append(_L(" HTTP/1.0\r\nHOST:\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); RBuffer.Append(_L(" HTTP/1.0\r\nHOST:")); RBuffer.Append(iServerAddr); RBuffer.Append(_L("\r\nPORT:")); RBuffer.AppendNum(iPort); RBuffer.Append(_L("\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); RBuffer.Append(content_l); RBuffer.Append(_L("\r\n\r\n")); RBuffer.Append(*content_data); #endif servlet_data = RBuffer.AllocL(); #ifdef __LOGME__ LogText.Copy(_L("\nCheckSubscriptionStatus 2. iServerAddr=")); WriteLogFile(LogText); LogText.Copy(iServerAddr); WriteLogFile(LogText); #endif ConnectToServerForSubscription(aStatus); //WriteLogFile(RBuffer); //LogText.Copy(_L("\n")); //WriteLogFile(LogText); } // --------------------------------------------------------- // CRippleVaultAppUi::ConnectToServerForSubscription(TInt aStatus) // Connects to server for Status Subscription // --------------------------------------------------------- void CRippleVaultAppUi::ConnectToServerForSubscription(TInt aStatus) { #ifdef __LOGME__ LogText.Copy(_L("ConnectToServerForSubscription\n")); WriteLogFile(LogText); #endif if(aStatus == 1) { #ifdef __LOGME__ LogText.Copy(_L("iSocketWriterPublishStatus 1\n")); WriteLogFile(LogText); #endif if(iSocketWriterPublishStatus == NULL) { iSocketWriterPublishStatus = CSocketsEngineWriter::NewL(*this); iSocketWriterPublishStatus->SetServerName(iServerAddr); iSocketWriterPublishStatus->SetPort(iPort); iSocketWriterPublishStatus->iBuffer.Copy(*servlet_data); iSocketWriterPublishStatus->SubscriptionStatus(aStatus); delete servlet_data; } //LogText.Copy(_L("iSocketWriterPublishStatus 2\n")); //WriteLogFile(LogText); } else if(aStatus == 2 || aStatus == 6) { #ifdef __LOGME__ LogText.Copy(_L("iSocketWriterContactsStatus 1\n")); WriteLogFile(LogText); #endif if(iSocketWriterContactsStatus == NULL) { iSocketWriterContactsStatus = CSocketsEngineWriter::NewL(*this); iSocketWriterContactsStatus->SetServerName(iServerAddr); iSocketWriterContactsStatus->SetPort(iPort); iSocketWriterContactsStatus->iBuffer.Copy(*servlet_data); iSocketWriterContactsStatus->SubscriptionStatus(aStatus); delete servlet_data; } //LogText.Copy(_L("iSocketWriterContactsStatus 2\n")); //WriteLogFile(LogText); } else if(aStatus == 3) { #ifdef __LOGME__ LogText.Copy(_L("iSocketWriterSmsStatus 1\n")); WriteLogFile(LogText); #endif if(iSocketWriterSmsStatus == NULL) { iSocketWriterSmsStatus = CSocketsEngineWriter::NewL(*this); iSocketWriterSmsStatus->SetServerName(iServerAddr); iSocketWriterSmsStatus->SetPort(iPort); iSocketWriterSmsStatus->iBuffer.Copy(*servlet_data); iSocketWriterSmsStatus->SubscriptionStatus(aStatus); delete servlet_data; } //LogText.Copy(_L("iSocketWriterSmsStatus 2\n")); //WriteLogFile(LogText); } else if(aStatus == 4) { #ifdef __LOGME__ LogText.Copy(_L("iSocketWriterSimChangeStatus 1\n")); WriteLogFile(LogText); #endif if(iSocketWriterSimChangeStatus == NULL) { iSocketWriterSimChangeStatus = CSocketsEngineWriter::NewL(*this); iSocketWriterSimChangeStatus->SetServerName(iServerAddr); iSocketWriterSimChangeStatus->SetPort(iPort); iSocketWriterSimChangeStatus->iBuffer.Copy(*servlet_data); iSocketWriterSimChangeStatus->SubscriptionStatus(aStatus); delete servlet_data; } } else if(aStatus == 7) { #ifdef __LOGME__ LogText.Copy(_L("iSocketWriterAutoSmsStatus 1\n")); WriteLogFile(LogText); #endif if(iSocketWriterAutoSmsStatus == NULL) { iSocketWriterAutoSmsStatus = CSocketsEngineWriter::NewL(*this); iSocketWriterAutoSmsStatus->SetServerName(iServerAddr); iSocketWriterAutoSmsStatus->SetPort(iPort); iSocketWriterAutoSmsStatus->iBuffer.Copy(*servlet_data); iSocketWriterAutoSmsStatus->SubscriptionStatus(aStatus); delete servlet_data; } //LogText.Copy(_L("iSocketWriterSmsStatus 2\n")); //WriteLogFile(LogText); } /*else if(aStatus == 5) { if(iSocketWriterBillingStatus == NULL) { iSocketWriterBillingStatus = CSocketsEngineWriter::NewL(*this); iSocketWriterBillingStatus->SetServerName(iServerAddr); iSocketWriterBillingStatus->SetPort(iPort); iSocketWriterBillingStatus->iBuffer.Copy(*servlet_data); iSocketWriterBillingStatus->BillingStatus(aStatus); delete servlet_data; } }*/ } // --------------------------------------------------------- // CRippleVaultAppUi::GetSmsXML(TInt smsbackuptype) // gets the SMS backup XML // --------------------------------------------------------- void CRippleVaultAppUi::GetSmsXML(TInt smsbackuptype) { TInt network; network = CheckNetwork(); if(network == NETWORK_ROAMING) { if(iSmsRoam == DISABLED) { return; } } iAutoSmsBackupType = smsbackuptype; //ConnectToServerForSms(smsbackuptype); iConnectionStatus = 7; CheckSubscriptionStatus(iConnectionStatus); } // --------------------------------------------------------- // CRippleVaultAppUi::UploadSmsManually(TInt smsbackuptype) // gets the SMS backup XML // --------------------------------------------------------- void CRippleVaultAppUi::UploadSmsManually(TInt smsbackuptype) { if(iWriteSmsAO != NULL) { delete iWriteSmsAO; iWriteSmsAO = NULL; } TInt network; network = CheckNetwork(); if(network == NETWORK_ROAMING) { if(iSmsRoam == DISABLED) { RoamingDisabledDialogSms(); return; } } iSmsBackupType = smsbackuptype; //ConnectToServerForSms(smsbackuptype); iConnectionStatus = 3; CheckSubscriptionStatus(iConnectionStatus); } // --------------------------------------------------------- // CRippleVaultAppUi::ConnectToServerForSms(TInt smsbackuptype) // Connects to server for SMS upload // --------------------------------------------------------- void CRippleVaultAppUi::ConnectToServerForSms(TInt smsbackuptype) { if(smsbackuptype) { if(iSocketWriterAutoSMS == NULL) { iSocketWriterAutoSMS = CSocketsEngineWriter::NewL(*this); iSocketWriterAutoSMS->SetServerName(iServerAddr); iSocketWriterAutoSMS->SetPort(iPort); iSocketWriterAutoSMS->SendSmsData(smsbackuptype); } } else { if(iSocketWriterSMS == NULL) { iSocketWriterSMS = CSocketsEngineWriter::NewL(*this); iSocketWriterSMS->SetServerName(iServerAddr); iSocketWriterSMS->SetPort(iPort); iSocketWriterSMS->SendSmsData(smsbackuptype); } } } // --------------------------------------------------------- // CRippleVaultAppUi::UpdateSmsTimestamp() // Updates SMS last synch timestamp // --------------------------------------------------------- /*void CRippleVaultAppUi::UpdateInboxSmsTimestamp() { iPhotosDB->UpdateSmsTimestampToDB(); }*/ void CRippleVaultAppUi::UpdateInboxSmsTimestamp(TTime aTime) { iPhotosDB->UpdateSmsTimestampToDB(aTime); } void CRippleVaultAppUi::UpdateSentItemsSmsTimestamp(TTime aTime) { iPhotosDB->UpdateSentItemsSmsTimestampToDB(aTime); } void CRippleVaultAppUi::GetSentItemsSmsTimestamp(TTime& aTime) { iPhotosDB->GetSentItemsSmsTimestampFromDB(aTime); } // --------------------------------------------------------- // CRippleVaultAppUi::GetSmsTimestamp(TTime& aTime) // Gets SMS last synch timestamp // --------------------------------------------------------- void CRippleVaultAppUi::GetInboxSmsTimestamp(TTime& aTime) { iPhotosDB->GetSmsTimestampFromDB(aTime); } // --------------------------------------------------------- // CRippleVaultAppUi::SaveSubStatusSyncTime(TDesC& aTime) // Saves Subscription Status last synch time to DB // --------------------------------------------------------- void CRippleVaultAppUi::SaveSubStatusSyncTime(TDesC& aTime) { iPhotosDB->SaveSubStatusSyncTimeToDB(aTime); } // --------------------------------------------------------- // CRippleVaultAppUi::GetSubStatusSyncTime(TDesC& aTime) // Gets Subscription Status last synch time from DB // --------------------------------------------------------- void CRippleVaultAppUi::GetSubStatusSyncTime(TDesC& aTime) { iPhotosDB->GetSubStatusSyncTimeFromDB(aTime); } // --------------------------------------------------------- // CRippleVaultAppUi::SaveSelectiveSmsMails(TDesC& aNames, TDesC& aMails, TInt8 aCount) // saves recipients for Selective SMS // --------------------------------------------------------- void CRippleVaultAppUi::SaveSelectiveSmsMails(TDesC& /*aNames*/, TDesC& /*aMails*/, TInt8 aCount) { TBuf<150> names; TBuf<150> mobileno; for(int i=0; i< aCount ;i++) { GetSharingNames(names); GetSharingMails(mobileno); iPhotosDB->SaveSelectiveSmsToDB(names, mobileno); } } // --------------------------------------------------------- // CRippleVaultAppUi::GetSmsMobileList() // gets list of mobile numbers for Selective SMS // --------------------------------------------------------- CDesCArray* CRippleVaultAppUi::GetSmsMobileList() { return iPhotosDB->GetSmsMobileList(); } // --------------------------------------------------------- // CRippleVaultAppUi::GetSmsNameList() // get list of recipients for Selective SMS // --------------------------------------------------------- CDesCArray* CRippleVaultAppUi::GetSmsNameList() { return iPhotosDB->GetSmsNameList(); } // --------------------------------------------------------- // CRippleVaultAppUi::DeleteContactsForSms(TInt pos) // deletes recipients for Selective SMS // --------------------------------------------------------- void CRippleVaultAppUi::DeleteContactsForSms(TInt pos) { iPhotosDB->DeleteContactsForSmsFromDB(pos); } // --------------------------------------------------------- // CRippleVaultAppUi::UploadSms() // Uploads SMS ie. automatic backup after timer expires // --------------------------------------------------------- void CRippleVaultAppUi::UploadSms() { TInt val=1; if(iSmsBackupTimer != NULL) { iSmsBackupTimer->UploadSms(val); } else { iSmsBackupTimer = CSmsBackupTimer::NewL(*this); iSmsBackupTimer->UploadSms(val); } } // --------------------------------------------------------- // CRippleVaultAppUi::GetSMSProtocolDataXML(TDes8& buffer, TInt aMaxLen, TInt aSmstype) // Gets SMS XML // --------------------------------------------------------- void CRippleVaultAppUi::GetSMSProtocolDataXML(TDes8& buffer, TInt /*aMaxLen*/, TInt aSmstype) { TInt len = 0; TInt ret; if(aSmstype) iFAutoSMSsession.Connect(); else iFSMSsession.Connect(); TBuf<50> FileName; FileName = CRippleVaultAppUi::ApplicationDriveAndPath(); if(aSmstype) FileName.Append(_L("smsbackup.aut")); else FileName.Append(_L("smsbackup.man")); //ret = iFileDes.Open(iFsession, filename->Des(), EFileRead|EFileStream); if(aSmstype) ret = iFileAutoSMSDes.Open(iFAutoSMSsession, FileName, EFileRead|EFileStream); else ret = iFileSMSDes.Open(iFSMSsession, FileName, EFileRead|EFileStream); if (ret == KErrNone) { if(aSmstype) iFileAutoSMSDes.Size(len); else iFileSMSDes.Size(len); TBuf8<10> imglen; imglen.Num(len); //TBuf<200> smstempbuf; //RBuffer.Copy(_L("GET /ripple/rippleservlet HTTP/1.0\r\nHOST:\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); buffer.Copy(_L("GET ")); buffer.Append(iSmsUrl); // buffer.Append(_L(" HTTP/1.0\r\nHOST:\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); buffer.Append(_L(" HTTP/1.0\r\nHOST:")); buffer.Append(iServerAddr); buffer.Append(_L("\r\nPORT:")); buffer.AppendNum(iPort); buffer.Append(_L("\r\nContent-Type:application/x-www-form-urlencoded\r\nContent-Length:")); buffer.Append(imglen); buffer.Append(_L("\r\n\r\n")); //smsBuffer.Append(); //buffer = smsBuffer.AllocL(); } } // --------------------------------------------------------- // CRippleVaultAppUi::GetMoreSMSDataFromFile(TDes8& aData, TInt aMaxLen) // gets data from the SMS backup file // --------------------------------------------------------- TInt CRippleVaultAppUi::GetMoreSMSDataFromFile(TDes8& aData, TInt aMaxLen, TInt aSmsType) { //if (iFileDes. // read data from filedesc into aData // return the length of data read TInt ret; if(aSmsType) ret = iFileAutoSMSDes.Read(aData, aMaxLen); else ret = iFileSMSDes.Read(aData, aMaxLen); if(ret != KErrNone || ret == KErrOverflow || ret == KErrGeneral) { return 0; } if (ret == 0) { return aData.Length(); } return 0; } // --------------------------------------------------------- // CRippleVaultAppUi::SendSmsFileComplete(TInt aSmstype) // Sms Upload completed successfully // --------------------------------------------------------- void CRippleVaultAppUi::SendSmsFileComplete(TInt aSmstype) { if(aSmstype != 0) { #ifdef __LOGME__ LogText.Copy(_L("SendSmsFileComplete 44\n")); WriteLogFile(LogText); #endif UpdateInboxSmsTimestamp(iSmsBackupTimer->iLastInboxSms); UpdateSentItemsSmsTimestamp(iSmsBackupTimer->iLastSentItemsSms); } NetworkErrorNotification(0); //iPhotosDB->CheckAndIncreaseStatusCount(albumname, publishtype); /* if(aSmstype != 2) { TInt count; GetSmsUploadSettingsFromDB(count); count+=iSmsCount; SaveSmsUploadSettingsToDB(count); }*/ iUploadSms += (iAutoSmsCount + iSmsCount); if(aSmstype) iAutoSmsCount = 0; else iSmsCount=0; TTime btime; btime.HomeTime(); iPhotosDB->UpdateBackupTimestampToDB(btime); //UpdateScreen(); TBuf<50> FileName; FileName = CRippleVaultAppUi::ApplicationDriveAndPath(); if(aSmstype){ FileName.Append(_L("smsbackup.aut")); iFileAutoSMSDes.Close(); iFAutoSMSsession.Delete(FileName); iFAutoSMSsession.Close(); } else{ FileName.Append(_L("smsbackup.man")); iFileSMSDes.Close(); iFSMSsession.Delete(FileName); iFSMSsession.Close(); } if(aSmstype) { if (iSocketWriterAutoSMS != NULL) { iSocketWriterAutoSMS->Disconnect(); delete iSocketWriterAutoSMS; iSocketWriterAutoSMS = NULL; } } else{ if (iSocketWriterSMS != NULL) { iSocketWriterSMS->Disconnect(); delete iSocketWriterSMS; iSocketWriterSMS = NULL; } } CloseConnection(); if(aSmstype == 2) iSmsBackupTimer->UploadSms(3); //selective sms else if(aSmstype == 1 || aSmstype == 5) iSmsBackupTimer->UploadSms(2); /*if(iSmsBackupAO != NULL) { delete iSmsBackupAO; iSmsBackupAO = NULL; }*/ } // --------------------------------------------------------- // CRippleVaultAppUi::SendSmsFileError(TInt aSmstype) // Sms Upload failed due to an error // --------------------------------------------------------- void CRippleVaultAppUi::SendSmsFileError(TInt aSmstype) { TBuf<50> FileName; FileName = CRippleVaultAppUi::ApplicationDriveAndPath(); if(aSmstype){ FileName.Append(_L("smsbackup.aut")); iFileAutoSMSDes.Close(); iFAutoSMSsession.Delete(FileName); iFAutoSMSsession.Close(); iAutoSmsCount = 0; } else{ FileName.Append(_L("smsbackup.man")); iFileSMSDes.Close(); iFSMSsession.Delete(FileName); iFSMSsession.Close(); iSmsCount = 0; } if(aSmstype) { if (iSocketWriterAutoSMS != NULL) { iSocketWriterAutoSMS->Disconnect(); delete iSocketWriterAutoSMS; iSocketWriterAutoSMS = NULL; } } else { if (iSocketWriterSMS != NULL) { iSocketWriterSMS->Disconnect(); delete iSocketWriterSMS; iSocketWriterSMS = NULL; } } /*if(iSmsBackupAO != NULL) { delete iSmsBackupAO; iSmsBackupAO = NULL; }*/ if(!aSmstype || aSmstype == 5) { if( iSmsBackupTimer == NULL) { iSmsBackupTimer = CSmsBackupTimer::NewL(*this); iSmsBackupTimer->InsertSms(*(iEikonEnv->AllocReadResourceL(R_TEXT_SMSBACKUP_INBOXSMS))); delete iSmsBackupTimer; iSmsBackupTimer = NULL; } else { iSmsBackupTimer->InsertSms(*(iEikonEnv->AllocReadResourceL(R_TEXT_SMSBACKUP_INBOXSMS))); } //UpdateScreen(); } } // --------------------------------------------------------- // CRippleVaultAppUi::SendSubStatusError(TInt aStatus) // Subscription Status failed due to an error // --------------------------------------------------------- void CRippleVaultAppUi::SendSubStatusError(TInt aStatus) { /* if(aStatus == 1) { //InsertSms(*(iEikonEnv->AllocReadResourceL(R_TEXT_PUBLISHBACKUP_INBOXSMS))); if( iSmsBackupTimer == NULL) { iSmsBackupTimer = CSmsBackupTimer::NewL(*this); iSmsBackupTimer->InsertSms(*(iEikonEnv->AllocReadResourceL(R_TEXT_PUBLISHBACKUP_INBOXSMS))); delete iSmsBackupTimer; iSmsBackupTimer == NULL; } else { iSmsBackupTimer->InsertSms(*(iEikonEnv->AllocReadResourceL(R_TEXT_SMSBACKUP_INBOXSMS))); } } else if(aStatus == 2) { //InsertSms(*(iEikonEnv->AllocReadResourceL(R_TEXT_CONTACTSBACKUP_INBOXSMS))); if( iSmsBackupTimer == NULL) { iSmsBackupTimer = CSmsBackupTimer::NewL(*this); iSmsBackupTimer->InsertSms(*(iEikonEnv->AllocReadResourceL(R_TEXT_CONTACTSBACKUP_INBOXSMS))); delete iSmsBackupTimer; iSmsBackupTimer == NULL; } else { iSmsBackupTimer->InsertSms(*(iEikonEnv->AllocReadResourceL(R_TEXT_SMSBACKUP_INBOXSMS))); } }*/ //else if(aStatus == 3 && iSmsBackupType == 0) { iSmsCount = 0; //InsertSms(*(iEikonEnv->AllocReadResourceL(R_TEXT_SMSBACKUP_INBOXSMS))); if( iSmsBackupTimer == NULL) { iSmsBackupTimer = CSmsBackupTimer::NewL(*this); iSmsBackupTimer->InsertSms(*(iEikonEnv->AllocReadResourceL(R_TEXT_SMSBACKUP_INBOXSMS))); delete iSmsBackupTimer; iSmsBackupTimer = NULL; } else { iSmsBackupTimer->InsertSms(*(iEikonEnv->AllocReadResourceL(R_TEXT_SMSBACKUP_INBOXSMS))); } /*if( iSmsBackupAO != NULL) { delete iSmsBackupAO; iSmsBackupAO=NULL; }*/ //UpdateScreen(); } else if(aStatus == 7) { iAutoSmsCount = 0; if(iAutoSmsBackupType == 5) { if( iSmsBackupTimer == NULL) { iSmsBackupTimer = CSmsBackupTimer::NewL(*this); iSmsBackupTimer->InsertSms(*(iEikonEnv->AllocReadResourceL(R_TEXT_SMSBACKUP_INBOXSMS))); delete iSmsBackupTimer; iSmsBackupTimer = NULL; } else { iSmsBackupTimer->InsertSms(*(iEikonEnv->AllocReadResourceL(R_TEXT_SMSBACKUP_INBOXSMS))); } } } } // --------------------------------------------------------- // CRippleVaultAppUi::GetChoice(TInt8& aChoice) // Gets flag which tells if setup wizard has been completed // --------------------------------------------------------- void CRippleVaultAppUi::GetChoice(TInt8& aChoice) { iPhotosDB->GetChoice(aChoice); /*TBuf<128> path; path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KSetupWizardFile); RFs fs1; fs1.Connect(); if(BaflUtils::FileExists(fs1, path)) //setup wizard { aChoice = 0; } else { aChoice = 1; } fs1.Close(); */ } // --------------------------------------------------------- // CRippleVaultAppUi::SaveChoice(TInt8 aChoice) // Saves flag after setup wizard is complete // --------------------------------------------------------- void CRippleVaultAppUi::SaveChoice(TInt8 aChoice) { iPhotosDB->SaveChoice(aChoice); /*TBuf<128> path; path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KSetupWizardFile); RFs fs1; fs1.Connect(); if(BaflUtils::FileExists(fs1, path)) //setup wizard { if(aChoice) BaflUtils::DeleteFile(fs1, path); } fs1.Close();*/ } // --------------------------------------------------------- // CRippleVaultAppUi::CallSetupWizardStep1(){ // Setup Wizard // --------------------------------------------------------- /* void CRippleVaultAppUi::CallSetupWizardStep1(){ iSetupWizardScreenValue = 1; //TBuf<1000> msg; //msg.Copy(*(iEikonEnv->AllocReadResourceL(R_SETUPMESSAGE_CONTACTS))); //TBuf<60> tembuf; //tembuf.Copy(*(iEikonEnv->AllocReadResourceL(R_TEXT_SETUP_WIZARD))); //tembuf.Append(_L(" 1/3")); #ifdef __UIQ__ //CEikonEnv::Static()->InfoWinL(*(iEikonEnv->AllocReadResourceL(R_SETUP_WIZARD_STEP_3)),*(iEikonEnv->AllocReadResourceL(R_SETUPMESSAGE_CONTACTS))); #ifdef __S80__ CCknInfoDialog::RunDlgLD(*(iEikonEnv->AllocReadResourceL(R_SETUP_WIZARD_STEP_3)), *iEikonEnv->AllocReadResourceL(R_SETUPMESSAGE_CONTACTS)); #else CEikDialog* dialog; dialog = new (ELeave) CCustomMessageDialog(*(iEikonEnv->AllocReadResourceL(R_SETUPMESSAGE_CONTACTS)), R_SETUP_WIZARD_STEP_3); dialog->ExecuteLD(R_EIK_DIALOG_CONTINUE_INFO); #endif //{ CallSetupWizardStep4(); //} #else CAknMessageQueryDialog* abtdlg = CAknMessageQueryDialog::NewL(*(iEikonEnv->AllocReadResourceL(R_SETUPMESSAGE_CONTACTS))); abtdlg->PrepareLC(R_MESSAGE_INFO); abtdlg->SetHeaderTextL(*(iEikonEnv->AllocReadResourceL(R_SETUP_WIZARD_STEP_3))); if (abtdlg->RunLD()){ CallSetupWizardStep4(); } #endif } // --------------------------------------------------------- // CRippleVaultAppUi::CallSetupWizardStep4() // Setup Wizard // --------------------------------------------------------- void CRippleVaultAppUi::CallSetupWizardStep4(){ #ifdef __UIQ__ CEikDialog* contactsdialog; contactsdialog = new (ELeave) CContactsSettingDialog(*this); contactsdialog->ExecuteLD(R_CONTACTS_SETTINGS); CallSetupWizardStep5(); #else iSettingsScreenValue = 1; ActivateView(KViewIdEmptyScreen); ActivateView(KViewIdSetupWizard); #endif } // --------------------------------------------------------- // CRippleVaultAppUi::CallSetupWizardStep5() // Setup Wizard // --------------------------------------------------------- void CRippleVaultAppUi::CallSetupWizardStep5(){ if(iSetupWizardScreenValue < 5) { RFs fs; fs.Connect(); TBuf<128> path; path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KContactSetupWizard); if (BaflUtils::FileExists(fs, path)) { EnableContactsUpload(NOT_REGISTERED); BaflUtils::DeleteFile(fs, path); } fs.Close(); } iSetupWizardScreenValue = 5; //TBuf<1000> msg; //msg.Copy(*(iEikonEnv->AllocReadResourceL(R_SETUPMESSAGE_CONTACTS_4))); //TBuf<60> tembuf; //tembuf.Copy(*(iEikonEnv->AllocReadResourceL(R_TEXT_SETUP_WIZARD))); //tembuf.Append(_L(" 1/3")); #ifdef __UIQ__ //CEikonEnv::Static()->InfoWinL(*(iEikonEnv->AllocReadResourceL(R_SETUP_WIZARD_STEP_4)),*(iEikonEnv->AllocReadResourceL(R_SETUPMESSAGE_PUBLISH))); #ifdef __S80__ CCknInfoDialog::RunDlgLD(*(iEikonEnv->AllocReadResourceL(R_SETUP_WIZARD_STEP_4)), *iEikonEnv->AllocReadResourceL(R_SETUPMESSAGE_PUBLISH)); #else CEikDialog* dialog; dialog = new (ELeave) CCustomMessageDialog(*(iEikonEnv->AllocReadResourceL(R_SETUPMESSAGE_PUBLISH)), R_SETUP_WIZARD_STEP_4); dialog->ExecuteLD(R_EIK_DIALOG_CONTINUE_INFO); #endif CallSetupWizardStep9(); #else CAknMessageQueryDialog* abtdlg = CAknMessageQueryDialog::NewL(*(iEikonEnv->AllocReadResourceL(R_SETUPMESSAGE_PUBLISH))); abtdlg->PrepareLC(R_MESSAGE_INFO); abtdlg->SetHeaderTextL(*(iEikonEnv->AllocReadResourceL(R_SETUP_WIZARD_STEP_4))); if (abtdlg->RunLD()){ CallSetupWizardStep9(); } else{ //CallSetupWizardStep3(); } #endif } // --------------------------------------------------------- // CRippleVaultAppUi::CallSetupWizardStep9() // Setup Wizard // --------------------------------------------------------- void CRippleVaultAppUi::CallSetupWizardStep9(){ CheckAndSaveFolderToDB(*(iEikonEnv->AllocReadResourceL(R_DEFAULT_ALBUM))); #ifdef __UIQ__ CEikDialog* photosdialog; photosdialog = new (ELeave) CPhotosSettingDialog(*this); photosdialog->ExecuteLD(R_PHOTOS_SETTINGS); CallSetupWizardStep11(); #else iSettingsScreenValue = 2; ActivateView(KViewIdEmptyScreen); ActivateView(KViewIdSetupWizard); #endif } // --------------------------------------------------------- // CRippleVaultAppUi::CallSetupWizardStep11() // Setup Wizard // --------------------------------------------------------- void CRippleVaultAppUi::CallSetupWizardStep11(){ //TBuf<50> tempbuf; //tempbuf.Copy(_L("Backup")); //CheckAndSaveFolderToDB(*(iEikonEnv->AllocReadResourceL(R_DEFAULT_ALBUM))); #ifdef __UIQ__ #ifdef __S80__ if(CCknConfirmationDialog::RunDlgLD(*(iEikonEnv->AllocReadResourceL(R_SETUP_WIZARD_STEP_5)),*(iEikonEnv->AllocReadResourceL(R_TEXT_UPLOAD_PUBLISH)))) #else CEikDialog* dialog; dialog = new (ELeave) CCustomMessageDialog(*(iEikonEnv->AllocReadResourceL(R_TEXT_UPLOAD_PUBLISH)), R_SETUP_WIZARD_STEP_5); if(dialog->ExecuteLD(R_EIK_DIALOG_YESNO_INFO)) #endif { iSettingsScreenValue = 0; iImageFlag = 1; ShowWindow(KViewIdPhotoList); //photo screen DeleteWindow(KViewIdRegisterScreen); //main screen } else { CallSetupWizardStep12(); } #else CAknMessageQueryDialog* abtdlg = CAknMessageQueryDialog::NewL(*(iEikonEnv->AllocReadResourceL(R_TEXT_UPLOAD_PUBLISH))); abtdlg->PrepareLC(R_GALLERY_INFO); abtdlg->SetHeaderTextL(*(iEikonEnv->AllocReadResourceL(R_SETUP_WIZARD_STEP_5))); if (abtdlg->RunLD()) { iRipplePhotos = 1; iStoragePath = 0; ActivateView(KViewIdPhotoList); } else CallSetupWizardStep12(); #endif } // --------------------------------------------------------- // CRippleVaultAppUi::CallSetupWizardStep12() // Setup Wizard // --------------------------------------------------------- void CRippleVaultAppUi::CallSetupWizardStep12(){ iSetupWizardScreenValue = 12; //TBuf<1000> msg; //msg.Copy(*(iEikonEnv->AllocReadResourceL(R_SETUPMESSAGE_SMS))); //TBuf<60> tembuf; //tembuf.Copy(*(iEikonEnv->AllocReadResourceL(R_SETUP_WIZARD_STEP_6))); //tembuf.Append(_L(" 3/3")); #ifdef __UIQ__ //CEikonEnv::Static()->InfoWinL(*(iEikonEnv->AllocReadResourceL(R_SETUP_WIZARD_STEP_6)),*(iEikonEnv->AllocReadResourceL(R_SETUPMESSAGE_SMS))); #ifdef __S80__ CCknInfoDialog::RunDlgLD(*(iEikonEnv->AllocReadResourceL(R_SETUP_WIZARD_STEP_6)), *iEikonEnv->AllocReadResourceL(R_SETUPMESSAGE_SMS)); #else CEikDialog* dialog; dialog = new (ELeave) CCustomMessageDialog(*(iEikonEnv->AllocReadResourceL(R_SETUPMESSAGE_SMS)), R_SETUP_WIZARD_STEP_6); dialog->ExecuteLD(R_EIK_DIALOG_CONTINUE_INFO); #endif CallSetupWizardStep15(); #else CAknMessageQueryDialog* abtdlg = CAknMessageQueryDialog::NewL(*(iEikonEnv->AllocReadResourceL(R_SETUPMESSAGE_SMS))); abtdlg->PrepareLC(R_MESSAGE_INFO); abtdlg->SetHeaderTextL(*(iEikonEnv->AllocReadResourceL(R_SETUP_WIZARD_STEP_6))); if (abtdlg->RunLD()){ CallSetupWizardStep15(); } else{ //CallSetupWizardStep10(); } #endif } // --------------------------------------------------------- // CRippleVaultAppUi::CallSetupWizardStep15() // Setup Wizard // --------------------------------------------------------- void CRippleVaultAppUi::CallSetupWizardStep15(){ #ifdef __UIQ__ CEikDialog* smssettingdialog; smssettingdialog = new (ELeave) CSmsSettingDialog(*this); TInt err = smssettingdialog->ExecuteLD(R_SMS_SETTINGS); if(iSmsMode == 0) { MailNames.Copy(_L("")); MailId.Copy(_L("")); albumName.Copy(_L("")); iMessage.Copy(_L("")); iStoragePath = 1; ShowWindow(KViewIdContactsViewScreen); DeleteWindow(KViewIdRegisterScreen); } else{ CallSetupWizardStep17(); } #else iSettingsScreenValue = 3; ActivateView(KViewIdEmptyScreen); ActivateView(KViewIdSetupWizard); #endif } // --------------------------------------------------------- // CRippleVaultAppUi::CallSetupWizardStep17() // Setup Wizard // --------------------------------------------------------- void CRippleVaultAppUi::CallSetupWizardStep17(){ TInt rid; if(iSmsMode == SMSBACKUP_SELECTIVE) rid = R_SETUPWIZARD_SMSBACKUPALL_SELECTIVE; else if(iSmsMode == SMSBACKUP_SCHEDULED || iSmsMode == SMSBACKUP_SCHEDULED_HOURLY) rid = R_SETUPWIZARD_SMSBACKUPALL_AUTO; else rid = R_TEXT_UPLOAD_SMS; #ifdef __UIQ__ #ifdef __S80__ if(CCknConfirmationDialog::RunDlgLD(*(iEikonEnv->AllocReadResourceL(R_SETUP_WIZARD_STEP_7)),*(iEikonEnv->AllocReadResourceL(rid)))) #else CEikDialog* dialog; dialog = new (ELeave) CCustomMessageDialog(*(iEikonEnv->AllocReadResourceL(rid)), R_SETUP_WIZARD_STEP_7); if(dialog->ExecuteLD(R_EIK_DIALOG_YESNO_INFO)) #endif { iSettingsScreenValue = 0; //TTime aTime; //aTime.HomeTime(); //UpdateInboxSmsTimestamp(aTime); //UpdateSentItemsSmsTimestamp(aTime); if(iSmsMode == SMSBACKUP_SELECTIVE || iSmsMode == SMSBACKUP_SCHEDULED || iSmsMode == SMSBACKUP_SCHEDULED_HOURLY) { TInt val=1; iSmsBackupTimer->UploadSms(val); SaveChoice(1); iMainScreenValue = 6; #ifdef __S80__ ShowWindow(KViewIdStatusScreen); //status screen if(iRegisterView != NULL) { iRegisterView->ShowStatusScreen(); } #else ShowWindow(KViewIdStatusScreen); //status screen DeleteWindow(KViewIdRegisterScreen); ShowStatusScreen(); #endif } else { iImageFlag = 5; ShowWindow(KViewIdSmsList); //sms screen DeleteWindow(KViewIdRegisterScreen); //main screen } } else { if(iSmsMode == SMSBACKUP_SELECTIVE || iSmsMode == SMSBACKUP_SCHEDULED || iSmsMode == SMSBACKUP_SCHEDULED_HOURLY) { TTime aTime; aTime.HomeTime(); UpdateInboxSmsTimestamp(aTime); UpdateSentItemsSmsTimestamp(aTime); } SaveChoice(1); iMainScreenValue = 6; #ifdef __S80__ ShowWindow(KViewIdStatusScreen); //status screen if(iRegisterView != NULL) { iRegisterView->ShowStatusScreen(); } #else ShowWindow(KViewIdStatusScreen); //status screen DeleteWindow(KViewIdRegisterScreen); ShowStatusScreen(); #endif } #else CAknMessageQueryDialog* abtdlg = CAknMessageQueryDialog::NewL(*(iEikonEnv->AllocReadResourceL(rid))); abtdlg->PrepareLC(R_GALLERY_INFO); abtdlg->SetHeaderTextL(*(iEikonEnv->AllocReadResourceL(R_SETUP_WIZARD_STEP_7))); if (abtdlg->RunLD()) { //TTime aTime; //aTime.HomeTime(); //UpdateInboxSmsTimestamp(aTime); //UpdateSentItemsSmsTimestamp(aTime); if(iSmsMode == SMSBACKUP_SELECTIVE || iSmsMode == SMSBACKUP_SCHEDULED || iSmsMode == SMSBACKUP_SCHEDULED_HOURLY) { TInt val=1; iSmsBackupTimer->UploadSms(val); SaveChoice(1); ActivateView(KViewIdStatusScreen); //ActivateView(KViewIdMainScreen); } else { iStoragePath = 0; ActivateView(KViewIdEmptyScreen); ActivateView(KViewIdSmsList); } } else { if(iSmsMode == SMSBACKUP_SELECTIVE || iSmsMode == SMSBACKUP_SCHEDULED || iSmsMode == SMSBACKUP_SCHEDULED_HOURLY) { TTime aTime; aTime.HomeTime(); UpdateInboxSmsTimestamp(aTime); UpdateSentItemsSmsTimestamp(aTime); } SaveChoice(1); //ActivateView(KViewIdMainScreen); ActivateView(KViewIdStatusScreen); } #endif } */ // --------------------------------------------------------- // CRippleVaultAppUi::LoadParamsFromConfigFile() // Loads parameters from the config file // --------------------------------------------------------- void CRippleVaultAppUi::LoadParamsFromConfigFile() { TBuf<60> tmpstr; tmpstr.Copy( _L("version")); LoadFromConfigFile(iVersion,tmpstr); tmpstr.Copy(_L("os")); LoadFromConfigFile(iOs, tmpstr); tmpstr.Copy(_L("phone_model")); LoadFromConfigFile(iAxiomPhoneModel, tmpstr); tmpstr.Copy(_L("billing_reg_type")); LoadFromConfigFile(iAxiomBillingRegType, tmpstr); tmpstr.Copy( _L("userid")); LoadFromConfigFile(iUserNames,tmpstr); tmpstr.Copy(_L("hp")); LoadFromConfigFile(iMobileNo,tmpstr ); tmpstr.Copy(_L("password")); LoadFromConfigFile(iPassword,tmpstr ); //tmpstr.Copy(_L("charge")); //LoadFromConfigFile(iCharge,tmpstr ); tmpstr.Copy(_L("registration_url")); LoadFromConfigFile(iRegUrl,tmpstr ); tmpstr.Copy(_L("media_pkt_upload_url")); LoadFromConfigFile(iPublishUrl,tmpstr ); tmpstr.Copy(_L("sharing_url")); LoadFromConfigFile(iSharingUrl,tmpstr ); tmpstr.Copy(_L("contacts_url")); LoadFromConfigFile(iContactsUrl,tmpstr ); tmpstr.Copy(_L("sms_backup_url")); LoadFromConfigFile(iSmsUrl,tmpstr ); tmpstr.Copy(_L("apn")); LoadFromConfigFile(iAccessPoints,tmpstr ); tmpstr.Copy(_L("sub_update_url")); LoadFromConfigFile(iPlanUrl,tmpstr ); tmpstr.Copy(_L("album_synch_url")); LoadFromConfigFile(iAlbumUrl,tmpstr ); tmpstr.Copy(_L("sub_status_check")); LoadFromConfigFile(iStatusUrl,tmpstr ); tmpstr.Copy(_L("connection_type")); LoadFromConfigFile(iConnectionType,tmpstr ); //MapAPNtoActualName(); // tmpstr.Copy(_L("chargeclient")); // LoadFromConfigFile(iChargeClient,tmpstr ); // iChargeClient.Copy(_L("/rpc/chargerpc/3000/downloadclient")); // tmpstr.Copy(_L("chargephoto")); //LoadFromConfigFile(iChargePhoto,tmpstr ); // iChargePhoto.Copy(_L("/rpc/chargerp/")); // iChargePhoto.Append(iCharge); // iChargePhoto.Append(_L("00/uploadphoto")); // tmpstr.Copy(_L("chargevideo")); // LoadFromConfigFile(iChargeVideo,tmpstr ); // iChargeVideo.Copy(_L("/rpc/chargerp/")); // iChargeVideo.Append(iCharge); // iChargeVideo.Append(_L("00/uploadvideo")); tmpstr.Copy(_L("media_gallery_url")); LoadFromConfigFile(iWapUrl,tmpstr ); tmpstr.Copy(_L("gateway")); LoadFromConfigFile(iGateWay,tmpstr ); tmpstr.Copy(_L("settings")); LoadFromConfigFile(iSettingsString,tmpstr ); iUserName.Copy(iUserNames); } // --------------------------------------------------------- // CRippleVaultAppUi::SendSmsForClientSharing() // Sends SMS for "Tell a Friend" recommendation // --------------------------------------------------------- void CRippleVaultAppUi::SendSmsForClientSharing() { TBuf<150> sharingName; TBuf<150> mess; TInt8 sharingCount; TBuf<300> smstext; TBuf<300> formatBuf; //formatBuf.Copy(iUserNames); smstext.Append(*(iEikonEnv->AllocReadResourceL(R_TEXT_TELL_FRIEND))); formatBuf.Format(smstext, &iUserNames); smstext.Copy(formatBuf); GetMails(albumName,MailNames,MailId, mess, sharingCount); //for(int i=0; i< sharingCount ;i++) //{ GetSharingMails(sharingName); iSmsFile->CmdSendL(sharingName,smstext,1); //} //iPhotosDB->DeleteSharingsFirstRecord(); } // --------------------------------------------------------- // CRippleVaultAppUi::EditConfigFile(TDes8& aValue, TDesC8& aParam) // edits config file // --------------------------------------------------------- void CRippleVaultAppUi::EditConfigFile(TDes8& aValue, TDesC8& aParam) { RFs fs,fs1; RFile file,file1; //_LIT(KConfigFile,"config.txt"); _LIT(KConfigFile1,"tempconfig.txt"); TBuf8<150> tempbuf; fs.Connect(); fs1.Connect(); TBuf<128> path; path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KConfigFile); TBuf<128> path1; path1 = CRippleVaultAppUi::ApplicationDriveAndPath(); path1.Append(KConfigFile1); if (BaflUtils::FileExists(fs, path)) { TInt err = file.Open(fs, path, EFileRead); TInt err1 = file1.Open(fs1, path1, EFileWrite); if(err1 != KErrNone) file1.Create(fs1, path1, EFileWrite); if (err == KErrNone) { TBuf8<2> buf; TBuf<2> buf16; TBuf<150> line; TBuf<150> param; param.Copy(aParam); param.Append(_L("=")); TInt len = param.Length(); line.Copy(_L("")); TInt count = 0; do { file.Read(buf, 1); if (buf.Length()) count++; buf16.Copy(buf); line.Append(buf16); if (buf.Length() == 0 || buf.Find(_L8("\n")) != KErrNotFound || buf.Find(_L8("\r")) != KErrNotFound) { if (line.Find(param) == KErrNotFound) { tempbuf.Copy(line); file1.Write(tempbuf); } else { tempbuf.Copy(_L("")); tempbuf.Append(aParam); tempbuf.Append(_L("=")); tempbuf.Append(aValue); tempbuf.Append(_L("\n")); file1.Write(tempbuf); } if (line.Find(param) != KErrNotFound && line.Length() > len) { line.Delete(0,len); //line.SetLength(count - 7); if (buf.Find(_L8("\n")) != KErrNotFound || buf.Find(_L8("\r")) != KErrNotFound) { line.SetLength(line.Length() - 1); } } line.Copy(_L("")); count = 0; } } while(buf.Length() != 0); } } file.Close(); file1.Close(); fs.Delete(path); BaflUtils::RenameFile(fs1, path1, path,0); fs.Close(); fs1.Close(); } // --------------------------------------------------------- // CRippleVaultAppUi::UpLoadDatas() // Enables contacts, photos/videos and sms upload // --------------------------------------------------------- void CRippleVaultAppUi::UpLoadDatas() { if(iSmsValue == -1) { //GetConnectionName(); EnableUpload(iMode); EnableSmsUpload(iSmsMode); if(iContactsFlag == 0) { TTime aCDBTime, aRippleTime; //added by Deepak TBuf<128> path; path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KInitUploadFile); RFs fs1; fs1.Connect(); //delete file //fs1.Delete(KRegStep1); if(BaflUtils::FileExists(fs1, path)) { EnableContactsUpload(NOT_REGISTERED); } else if (ChangesToBeStoredL(aCDBTime, aRippleTime)) { iChangesAO = new (ELeave) CChangesContactsAO(*this); iChangesAO->StartL(aCDBTime, aRippleTime); }else{ if(iContactsHandler->iContactsUpload == 0) { //iContactsHandler->SyncToServer(); iConnectionStatus = 2; CheckSubscriptionStatus(iConnectionStatus); } } EnableContactsUpload(REGISTERED); } } } // --------------------------------------------------------- // CRippleVaultAppUi::SaveUserSettingsToDB(TDes& aUserName, TDes& aPassWord, TDes& aMobileNo) // Saves username, password and phone number to DB // --------------------------------------------------------- void CRippleVaultAppUi::SaveUserSettingsToDB(TDes& aUserName, TDes& aPassWord, TDes& aMobileNo) { iUserName.Copy(aUserName); iUserNames.Copy(iUserName); iPassword.Copy(aPassWord); iMobileNo.Copy(aMobileNo); iPhotosDB->SaveUserSettingsL(aUserName, aPassWord, aMobileNo); } // --------------------------------------------------------- // CRippleVaultAppUi::GetUserSettings(TDes& aUserName, TDes& aPassWord, TDes& aMobileNo) // Gets username, password and phone number from DB // --------------------------------------------------------- void CRippleVaultAppUi::GetUserSettings(TDes& aUserName, TDes& aPassWord, TDes& aMobileNo) { iPhotosDB->GetUserSettings(aUserName, aPassWord, aMobileNo); } // --------------------------------------------------------- // CRippleVaultAppUi::CheckUserId() // Checks userid/password details // --------------------------------------------------------- TInt CRippleVaultAppUi::CheckUserId() { TBuf<50> userid; TBuf<50> password; userid.Copy(_L("")); password.Copy(_L("")); #ifndef __UIQ__ CAknMultiLineDataQueryDialog* dialog = CAknMultiLineDataQueryDialog::NewL(userid, password); if(dialog->ExecuteLD(R_CONTACTS_DIALOG_REGISTERED)) { if(userid.Compare(iUserNames)==0 && password.Compare(iPassword)==0) return 1; else return 0; } return -1; #else CEikDialog* simdialog; simdialog = new (ELeave) CCheckSimDialog(*this); if(simdialog->ExecuteLD(R_REGISTER_DIALOG)) { return iSettingsScreenValue; } else return -1; #endif } // --------------------------------------------------------- // CRippleVaultAppUi::UpdateSimcard() // Updates SIM card details after SIM card change validation // --------------------------------------------------------- void CRippleVaultAppUi::UpdateSimcard() { iMobileNo.Copy(iTempMbNum); SaveUserSettingsToDB(iUserNames, iPassword, iMobileNo); WriteImsiNumber(); UpLoadDatas(); TBuf8<150> aValue; TBuf8<150> aParam; aParam.Copy(_L("userid")); aValue.Copy(iUserNames); EditConfigFile(aValue, aParam); aParam.Copy(_L("hp")); TBuf<50> tgt; tgt.Copy(iTempMbNum); TInt64 num; TLex lex(tgt); lex.Val(num); num = num + 10101010; tgt.NumUC(num,EHex); aValue.Copy(tgt); EditConfigFile(aValue, aParam); /*TBuf<60> tmpstr; tmpstr.Copy( _L("userid")); LoadFromConfigFile(iUserNames,tmpstr); iUserName.Copy(iUserNames); if(iUserName.Compare(_L("")) == 0) ReadUserName(); tmpstr.Copy(_L("hp")); LoadFromConfigFile(iMobileNo,tmpstr );*/ } // --------------------------------------------------------- // CRippleVaultAppUi::GetSettingsString() // Prepares the Settings string to send to server // --------------------------------------------------------- void CRippleVaultAppUi::GetSettingsString() { iSettingsString.Copy(_L("")); TInt ports; TInt autostart; TInt contactsroam; TInt modes; TInt desc; TInt roam; TInt securegallery; TInt smstype; TTime time; TInt smsroam; TInt upload; GetSettingsFromDB(iServerAddr, ports, autostart); GetContactsSettingsFromDB(contactsroam, upload); GetPhotosSettingsFromDB(modes, desc, roam, securegallery); GetSmsSettingsFromDB(smstype, time, smsroam); iSettingsString.AppendNum(autostart); iSettingsString.AppendNum(contactsroam); iSettingsString.AppendNum(modes); iSettingsString.AppendNum(desc); iSettingsString.AppendNum(roam); iSettingsString.AppendNum(securegallery); iSettingsString.AppendNum(smstype); iSettingsString.AppendNum(smsroam); iSettingsString.Append(_L("|")); TBuf<30> dateString; _LIT(KDateString5,"%-B%:0%J%:1%T%:2%S%:3%+B"); time.FormatL(dateString,KDateString5); iSettingsString.Append(dateString); iSettingsString.Append(_L("|")); } // --------------------------------------------------------- // CRippleVaultAppUi::SaveSettingsString() // Saves from Settings String to DB // --------------------------------------------------------- void CRippleVaultAppUi::SaveSettingsString() { CheckAndSaveFolderToDB(*(iEikonEnv->AllocReadResourceL(R_DEFAULT_ALBUM))); if(iSettingsString.Length() == 0) return; /* RFs fs; fs.Connect(); TBuf<128> path; path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KContactSetupWizard); if (BaflUtils::FileExists(fs, path)) { EnableContactsUpload(NOT_REGISTERED); BaflUtils::DeleteFile(fs, path); } fs.Close(); */ //ShowMessageBoxFromResource(R_SECUREWIZARD_SKIP); TBuf<1> t; t.Copy(&iSettingsString[0],1); if(t.Find(_L("0"))!=KErrNotFound) { iAutostart = 0; } else { iAutostart = 1; } t.Copy(&iSettingsString[1],1); if(t.Find(_L("0"))!=KErrNotFound) { iContactsHandler->iContactsRoaming = 0; } else { iContactsHandler->iContactsRoaming = 1; } t.Copy(&iSettingsString[2],1); if(t.Find(_L("0"))!=KErrNotFound) { iMode = 0; SetDefaultFolder(*(iEikonEnv->AllocReadResourceL(R_DEFAULT_ALBUM))); } else if(t.Find(_L("1"))!=KErrNotFound) { iMode = 1; } else { iMode = 2; } t.Copy(&iSettingsString[3],1); if(t.Find(_L("0"))!=KErrNotFound) { iDescription = 0; } else { iDescription = 1; } t.Copy(&iSettingsString[4],1); if(t.Find(_L("0"))!=KErrNotFound) { iRoaming = 0; } else { iRoaming = 1; } t.Copy(&iSettingsString[5],1); if(t.Find(_L("0"))!=KErrNotFound) { iSecureGallery = 0; } else { iSecureGallery = 1; } t.Copy(&iSettingsString[6],1); if(t.Find(_L("0"))!=KErrNotFound) { iSmsMode = 0; } else if(t.Find(_L("1"))!=KErrNotFound) { iSmsMode = 1; } else if(t.Find(_L("2"))!=KErrNotFound) { iSmsMode = 2; } else { iSmsMode = 3; } t.Copy(&iSettingsString[7],1); if(t.Find(_L("0"))!=KErrNotFound) { iSmsRoam = 0; } else { iSmsRoam = 1; } TBuf<30> dateString; dateString.Copy(&iSettingsString[9], iSettingsString.Length() - 10); TInt returnvalue=iSmsTime.Parse(dateString); SaveSettingsToDB(iServerAddr, iPort, iAutostart); SaveContactsSettingsToDB(iContactsHandler->iContactsRoaming, iContactsHandler->iContactsUpload); SavePhotosSettingsToDB(iMode, iDescription, iRoaming, iSecureGallery); SaveSmsSettingsToDB(iSmsMode,iSmsTime,iSmsRoam); } void CRippleVaultAppUi::RoamingDisabledDialogSms() { ShowMessageBoxFromResource(R_TEXT_ROAMINGDISABLED_SMS); } void CRippleVaultAppUi::RoamingDisabledDialogPublish() { ShowMessageBoxFromResource(R_TEXT_ROAMINGDISABLED_PUBLISH); } void CRippleVaultAppUi::RoamingDisabledDialogContacts() { ShowMessageBoxFromResource(R_TEXT_ROAMINGDISABLED_CONTACTS); } void CRippleVaultAppUi::CloseConnection() { #ifdef __LOGME__ LogText.Copy(_L("CloseConnection\n")); WriteLogFile(LogText); #endif #ifdef WAP_PT //LogText.Copy(_L("CloseConnection\n")); //WriteLogFile(LogText); if( iSocketWriterPublish == NULL && iSocketWriterShare == NULL && iSocketWriterSMS == NULL && iSocketWriterPublishStatus == NULL && iSocketWriterContactsStatus == NULL && iSocketWriterSmsStatus == NULL && iSocketWriterSimChangeStatus == NULL && iSocketWriterAutoSMS == NULL && iSocketWriterAutoSmsStatus == NULL && iContactsHandler->iSocketsEngine == NULL && iSocketWriterPassword == NULL ) { CheckSuccessfullSms(); if(iConnection == 1) { RGenericAgent netAgent; TBool active; if (netAgent.Open() == KErrNone) { CleanupClosePushL(netAgent); netAgent.NetworkActive(active); if(active) { //LogText.Copy(_L("Stopped Connection\n")); //WriteLogFile(LogText); iConnection = 0; TRAPD(err, netAgent.Stop()); if(err==KErrNone) { } else{ } } CleanupStack::PopAndDestroy(); // netAgent } } } #endif if( iSocketWriterPublish == NULL /*&& iSocketWriterShare == NULL*/ && iSocketWriterSMS == NULL && iSocketWriterPublishStatus == NULL && iSocketWriterContactsStatus == NULL && iSocketWriterSmsStatus == NULL /*&& iSocketWriterSimChangeStatus == NULL*/ && iSocketWriterAutoSMS == NULL && iSocketWriterAutoSmsStatus == NULL && iContactsHandler->iSocketsEngine == NULL /*&& iSocketWriterPassword == NULL*/ ) { CheckSuccessfullSms(); NetworkStatusNotification(NETWORK_STATUS_RUNNING); } else if(iContactsHandler->iSocketsEngine != NULL || iSocketWriterContactsStatus != NULL) { NetworkStatusNotification(NETWORK_STATUS_UPLOADING_CONTACTS); } else if(iSocketWriterPublish != NULL || iSocketWriterPublishStatus != NULL) { NetworkStatusNotification(NETWORK_STATUS_UPLOADING_MEDIA); } else if(iSocketWriterSMS != NULL || iSocketWriterSmsStatus != NULL || iSocketWriterAutoSMS != NULL || iSocketWriterAutoSmsStatus != NULL) { NetworkStatusNotification(NETWORK_STATUS_UPLOADING_SMS); } } void CRippleVaultAppUi::SaveSecureSettingsToFile(TInt8 aSecureMode, TDes& aFriendNumber, TDes& aText, TInt8 aAlarmMode) { #ifndef __S80__ RFs fs; fs.Connect(); RFile file; TBuf8<200> name; //TInt err; TBuf<128> path; path.Copy(_L("c:\\system\\secure\\secure.txt")); name.Copy(_L("")); name.Copy(_L("autolock=")); name.AppendNum(aSecureMode); name.Append(_L("\n")); name.Append(_L("fpn=")); name.Append(aFriendNumber); name.Append(_L("\n")); name.Append(_L("text=")); name.Append(aText); name.Append(_L("\n")); name.Append(_L("alarm=")); name.AppendNum(aAlarmMode); name.Append(_L("\n")); if (BaflUtils::FileExists(fs, path)) { BaflUtils::DeleteFile(fs, path); } file.Create(fs, path, EFileWrite); file.Write(name); file.Close(); fs.Close(); TTime oldtime; TTime newtime; iPhotosDB->GetSecureSettingsTimestampFromDB(oldtime, newtime); oldtime = newtime; newtime.UniversalTime(); iPhotosDB->UpdateSecureSettingsTimestampToDB(oldtime, newtime); #endif } void CRippleVaultAppUi::GetSecureSettingsFromFile(TInt& aSecureMode, TDes& aFriendNumber, TDes& aText, TInt& aAlarmMode) { TBuf<60> tmpstr; TBuf<20> mode; tmpstr.Copy(_L("autolock")); LoadFromSecureFile(mode,tmpstr ); if(mode.Compare(_L("1")) == 0) aSecureMode = 1; else aSecureMode = 0; tmpstr.Copy(_L("fpn")); LoadFromSecureFile(aFriendNumber,tmpstr ); tmpstr.Copy(_L("text")); LoadFromSecureFile(aText,tmpstr ); tmpstr.Copy(_L("alarm")); LoadFromSecureFile(mode,tmpstr ); if(mode.Compare(_L("1")) == 0) aAlarmMode = 1; else aAlarmMode = 0; } TBool CRippleVaultAppUi::LoadFromSecureFile(TDes& aValue, TDesC& aParam) { RFs fs; RFile file; TBool ret = FALSE; fs.Connect(); TBuf<128> path; path.Copy(_L("c:\\system\\secure\\secure.txt")); if (BaflUtils::FileExists(fs, path)) { TInt err = file.Open(fs, path, EFileRead); if (err == KErrNone) { TBuf8<2> buf; TBuf<2> buf16; TBuf<150> line; TBuf<150> param; param.Copy(aParam); param.Append(_L("=")); TInt len = param.Length(); line.Copy(_L("")); TInt count = 0; do { /*TInt readErr = */ file.Read(buf, 1); if (buf.Length()) count++; buf16.Copy(buf); line.Append(buf16); if (buf.Length() == 0 || buf.Find(_L8("\n")) != KErrNotFound || buf.Find(_L8("\r")) != KErrNotFound) { if (line.Find(param) != KErrNotFound && line.Length() > len) { line.Delete(0,len); //line.SetLength(count - 7); if (buf.Find(_L8("\n")) != KErrNotFound || buf.Find(_L8("\r")) != KErrNotFound) { line.SetLength(line.Length() - 1); } aValue.Copy(line); ret = TRUE; break; } line.Copy(_L("")); count = 0; } } while(buf.Length() != 0); } file.Close(); } fs.Close(); return ret; } TInt CRippleVaultAppUi::CheckLockFile() { RFs fs; fs.Connect(); TInt val = 0; TBuf<128> path; path.Copy(_L("c:\\system\\secure\\lock.dat")); if (BaflUtils::FileExists(fs, path)) { val = 1; User::Exit(EEikCmdExit); } else { TInt secureStart; TInt alarmStart; TBuf<20>friendNumber; TBuf<200> secureText; GetSecureSettingsFromFile(secureStart, friendNumber, secureText, alarmStart); TInt ret = ReadSecureImsiNumber(); //TInt ret1 = BaflUtils::FileExists(fs, path); if(ret != 2) if(secureStart == 1 && ret == 0) { val = 1; User::Exit(EEikCmdExit); } } fs.Close(); return val; } #ifdef __UIQ__ #ifdef __S80__ // --------------------------------------------------------- // CRippleVaultAppUi::SaveSelectiveSmsMails(TDesC& aNames, TDesC& aMails, TInt8 aCount) // saves recipients for Selective SMS // --------------------------------------------------------- void CRippleVaultAppUi::SaveSelectiveSmsMailsForS80(TDesC& aNames, TDesC& aMails) { iPhotosDB->SaveSelectiveSmsToDB(aNames, aMails); } void CRippleVaultAppUi::ShowWindow(TInt view) { if(view == 0)//unregister view { TRect rect = ClientRect(); rect.iBr.iX = rect.iTl.iX + rect.Width(); if(iUnRegisterView == NULL) { iUnRegisterView = CUnRegisterView::NewL( rect, *this); AddToStackL(iUnRegisterView); iCBA->SetCommandSetL(R_RIPPLEVAULT_CBA); iCBA->DrawNow(); CEikMenuBar* menuBar = iEikonEnv->AppUiFactory()->MenuBar(); menuBar->ChangeMenuBarL(0, R_UNREG_MENUBAR, EFalse); } } /* else if(view == 1)//Register view { if(iRegisterView == NULL) { iRegisterView = CRegisterView::NewL(ClientRect(), *this); AddToStackL(iRegisterView); CEikMenuBar* menuBar = iEikonEnv->AppUiFactory()->MenuBar(); menuBar->ChangeMenuBarL(0, R_REGISTER_MENUBAR, EFalse); iCBA->SetCommandSetL(R_REGISTER_CBA); iCBA->DrawNow(); } }*/ else if(view == 2)//photolist view { if(iPhotoListView == NULL) { iPhotoListView = CPhotoListView::NewL(ClientRect(), *this); AddToStackL(iPhotoListView); iCBA->SetCommandSetL(R_PHOTO_CBA); iCBA->DrawNow(); CEikMenuBar* menuBar = iEikonEnv->AppUiFactory()->MenuBar(); menuBar->ChangeMenuBarL(0, R_PHOTOLIST_MENUBAR, EFalse); } } else if(view == 3)//sms listview { if(iSmsListView == NULL) { iSmsListView = CSmsListView::NewL(ClientRect(), *this); AddToStackL(iSmsListView); iCBA->SetCommandSetL(R_SMS_CBA); iCBA->DrawNow(); CEikMenuBar* menuBar = iEikonEnv->AppUiFactory()->MenuBar(); menuBar->ChangeMenuBarL(0, R_SMSLIST_MENUBAR, EFalse); } } else if(view == 4)//status screen view { // TRect rect = ClientRect(); // rect.iTl.iX = rect.iTl.iX + rect.Width()/3; // rect.iTl.iY = rect.iTl.iY + 5; TRect rect = ClientRect(); rect.iBr.iX = rect.iTl.iX + rect.Width(); if( iStatusScreenView == NULL) { iStatusScreenView = CStatusScreenView::NewL( rect, *this); AddToStackL(iStatusScreenView); //iRegisterView->ShowStatusScreen(); ShowStatusScreen(); CEikMenuBar* menuBar = iEikonEnv->AppUiFactory()->MenuBar(); menuBar->ChangeMenuBarL(0, R_STATUSSCREEN_MENUBAR, EFalse); } } else if(view == 5)//contacts screen view { if(iContactsListView == NULL) { iContactsListView = CContactsView::NewL(ClientRect(), *this); AddToStackL(iContactsListView); iCBA->SetCommandSetL(R_CONTACTS_CBA); iCBA->DimCommand(EContactsDel, ETrue); iCBA->DimCommand(EContactsAdd, EFalse); if(iStoragePath == 1) iCBA->DimCommand(EContactsSend, ETrue); iCBA->DrawNow(); } } else if(view == 6)//videolist view { if(iVideoListView == NULL) { iVideoListView = CVideoListView::NewL(ClientRect(), *this); AddToStackL(iVideoListView); iCBA->SetCommandSetL(R_PHOTO_CBA); iCBA->DrawNow(); CEikMenuBar* menuBar = iEikonEnv->AppUiFactory()->MenuBar(); menuBar->ChangeMenuBarL(0, R_PHOTOLIST_MENUBAR, EFalse); } } } /* void CRippleVaultAppUi::ActivateWindow() { TInt err; CEikDialog* dialog; TInt view; view = iRegisterView->GetMainScreenCurrentItemIndex(); TInt view1; view1 = iRegisterView->GetMainSubScreenCurrentItemIndex(); if(view1 == -1) //focus is on mainscreen { iRegisterView->SelectSubScreen(); } else if(view == 0 && view1 == 0)//show contacts view contacts { ShowMessageBoxFromResource(R_TEXT_FEATURE_CONSTRUCTION_VIEW_CONTACTS); } else if (view == 0 && view1 == 1) //show send to web { iConnectionStatus = 2; CheckSubscriptionStatus(iConnectionStatus); ShowMessageBoxFromResource(R_TEXT_CONTACTS_SENDTOWEB); //iRegisterView->ShowStatusScreen(); ShowWindow(KViewIdStatusScreen); //DeleteWindow(1); } else if (view == 0 && view1 == 2) //show contacts settings { dialog = new (ELeave) CContactsSettingDialog(*this); err = dialog->ExecuteLD(R_CONTACTS_SETTINGS); } else if(view == 1 && view1 == 0)//show photo view gallery { TInt ret=0; if(iSecureGallery) //ret = CheckUserId(); ret = PasswordDialog(); else ret = 1; if(ret == 1) OpenBrowser(); } else if(view == 1 && view1 == 1)//show photo list { ShowWindow(KViewIdPhotoList); DeleteWindow(KViewIdRegisterScreen); } else if(view == 1 && view1 == 2)//show share album for photos { MailNames.Copy(_L("")); MailId.Copy(_L("")); albumName.Copy(_L("")); iMessage.Copy(_L("")); iStoragePath = 2; ShowWindow(KViewIdContactsViewScreen); DeleteWindow(KViewIdRegisterScreen); } else if(view == 1 && view1 == 3)//show unshare album for photos { dialog = new (ELeave) CUnShareAlbumDialog(*this); dialog->ExecuteLD(R_FOLDER_DIALOG1); } else if(view == 1 && view1 == 4)//show photo settings { dialog = new (ELeave) CPhotosSettingDialog(*this); err = dialog->ExecuteLD(R_PHOTOS_SETTINGS); //ShowPhotosSettingsDialog(); } else if(view == 2 && view1 == 0)//show video view gallery { TInt ret=0; if(iSecureGallery) //ret = CheckUserId(); ret = PasswordDialog(); else ret = 1; if(ret == 1) OpenBrowser(); } else if(view == 2 && view1 == 1)//show video list { ShowWindow(KViewIdVideoList); DeleteWindow(KViewIdRegisterScreen); } else if(view == 2 && view1 == 2)//show share album for videos { MailNames.Copy(_L("")); MailId.Copy(_L("")); albumName.Copy(_L("")); iMessage.Copy(_L("")); iStoragePath = 2; ShowWindow(KViewIdContactsViewScreen); DeleteWindow(KViewIdRegisterScreen); } else if(view == 2 && view1 == 3)//show unshare album for videos { dialog = new (ELeave) CUnShareAlbumDialog(*this); dialog->ExecuteLD(R_FOLDER_DIALOG1); } else if(view == 2 && view1 == 4)//show video settings { dialog = new (ELeave) CPhotosSettingDialog(*this); err = dialog->ExecuteLD(R_PHOTOS_SETTINGS); //ShowPhotosSettingsDialog(); } else if(view == 3 && view1 == 0)//show sms view messages { ShowMessageBoxFromResource(R_TEXT_FEATURE_CONSTRUCTION_VIEW_MESSAGES); } else if(view == 3 && view1 == 1)//show sms list { if(PendingSMS()) { ShowMessageBoxFromResource(R_SMS_SENDTOWEB_BUSY); ShowWindow(KViewIdStatusScreen); } else { ShowWindow(KViewIdSmsList); DeleteWindow(KViewIdRegisterScreen); } } else if(view == 3 && view1 == 2)//show sms settings { dialog = new (ELeave) CSmsSettingDialog(*this); err = dialog->ExecuteLD(R_SMS_SETTINGS); if(err) if(iSmsMode == 0) { MailNames.Copy(_L("")); MailId.Copy(_L("")); albumName.Copy(_L("")); iMessage.Copy(_L("")); iStoragePath = 1; ShowWindow(KViewIdContactsViewScreen); DeleteWindow(KViewIdRegisterScreen); } } } */ void CRippleVaultAppUi::DeleteWindow(TInt val) { if(val == 0) { if (iUnRegisterView) { RemoveFromStack(iUnRegisterView); delete iUnRegisterView; iUnRegisterView = NULL; } } /* else if(val == 1) { if (iRegisterView) { RemoveFromStack(iRegisterView); delete iRegisterView; iRegisterView = NULL; } }*/ else if(val == 2) { if (iPhotoListView) { RemoveFromStack(iPhotoListView); delete iPhotoListView; iPhotoListView = NULL; } } else if(val == 3) { if (iSmsListView) { RemoveFromStack(iSmsListView); delete iSmsListView; iSmsListView = NULL; } } else if(val == 4) { if (iStatusScreenView) { RemoveFromStack(iStatusScreenView); delete iStatusScreenView; iStatusScreenView = NULL; } //iCBA->SetCommandSetL(R_REGISTER_CBA); //iCBA->DrawNow(); } else if(val == 5) { if (iContactsListView) { RemoveFromStack(iContactsListView); delete iContactsListView; iContactsListView = NULL; } } else if(val == 6) { if (iVideoListView) { RemoveFromStack(iVideoListView); delete iVideoListView; iVideoListView = NULL; } } } TInt CRippleVaultAppUi::ReturnScreenValue() { TInt val; //// if (iUnRegisterView) { val = 0; } /* else if (iRegisterView) { val = 1; }*/ else if (iPhotoListView) { val = 2; } else if (iSmsListView) { val = 3; } else if (iStatusScreenView) { val = 4; } else if (iContactsListView) { val = 5; } else if (iVideoListView) { val = 6; } return val; } #else void CRippleVaultAppUi::ShowWindow(TInt aVal) { if(aVal == 0)//unregister view { if(iUnRegisterView == NULL) { iUnRegisterView = CUnRegisterView::NewL( ClientRect(), *this); AddToStackL(iUnRegisterView); CQikAppUi* appUi = STATIC_CAST(CQikAppUi*, iEikonEnv->AppUi()); appUi->SetToolbarL(R_UNREGISTER_TOOLBAR); CEikMenuBar* menuBar = iEikonEnv->AppUiFactory()->MenuBar(); menuBar->ChangeMenuBarL(0, R_UNREG_MENUBAR, EFalse); } } /*else if(aVal == 1)//MainScreen view { if(iMainScreenView == NULL) { iMainScreenView = CMainScreenView::NewL(ClientRect(), *this); AddToStackL(iMainScreenView); AddToStackL(iMainScreenView->ListBox()); iMainScreenView->UpdateListBoxL(iMainScreenValue); CQikAppUi* appUi = STATIC_CAST(CQikAppUi*, iEikonEnv->AppUi()); if(iMainScreenValue == 0) appUi->SetToolbarL(R_REGISTER_TOOLBAR); else appUi->SetToolbarL(R_SCREENLIST_TOOLBAR); CEikMenuBar* menuBar = iEikonEnv->AppUiFactory()->MenuBar(); menuBar->ChangeMenuBarL(0, R_REGISTER_MENUBAR, EFalse); } }*/ else if(aVal == 2)//photolist view { if(iPhotoListView == NULL) { iPhotoListView = CPhotoScreenView::NewL(ClientRect(), *this); AddToStackL(iPhotoListView); AddToStackL(iPhotoListView->ListBox()); TInt err; if(iImageFlag == 1) { CQikAppUi* appUi = STATIC_CAST(CQikAppUi*, iEikonEnv->AppUi()); appUi->SetToolbarL(R_PHOTOLIST_TOOLBAR_PHONE); err = iPhotoListView->Start(KDirPhonePhoto); } else if(iImageFlag == 2) { CQikAppUi* appUi = STATIC_CAST(CQikAppUi*, iEikonEnv->AppUi()); appUi->SetToolbarL(R_PHOTOLIST_TOOLBAR_MEMORY); err = iPhotoListView->Start(KDirMMCPhoto); } CEikMenuBar* menuBar = iEikonEnv->AppUiFactory()->MenuBar(); menuBar->ChangeMenuBarL(0, R_PHOTOLIST_MENUBAR, EFalse); if(err == -1) ShowMessageBoxFromResource(R_WEBUPLOAD_NOPHOTOIMAGE); } } else if(aVal == 3)//videolist view { if(iVideoListView == NULL) { iVideoListView = CVideoScreenView::NewL(ClientRect(), *this); AddToStackL(iVideoListView); AddToStackL(iVideoListView->ListBox()); TInt err; if(iImageFlag == 3) { CQikAppUi* appUi = STATIC_CAST(CQikAppUi*, iEikonEnv->AppUi()); appUi->SetToolbarL(R_PHOTOLIST_TOOLBAR_PHONE); err = iVideoListView->Start(KDirPhoneVideo); } else if(iImageFlag == 4) { CQikAppUi* appUi = STATIC_CAST(CQikAppUi*, iEikonEnv->AppUi()); appUi->SetToolbarL(R_PHOTOLIST_TOOLBAR_MEMORY); err = iVideoListView->Start(KDirMMCVideo); } CEikMenuBar* menuBar = iEikonEnv->AppUiFactory()->MenuBar(); menuBar->ChangeMenuBarL(0, R_PHOTOLIST_MENUBAR, EFalse); if(err == -1) ShowMessageBoxFromResource(R_WEBUPLOAD_NOVIDEOIMAGE); } } else if(aVal == 4)//smslist view { if(iSmsListView == NULL) { iSmsListView = CSmsScreenView::NewL(ClientRect(), *this); AddToStackL(iSmsListView); AddToStackL(iSmsListView->ListBox()); TInt err; if(iImageFlag == 5) { CQikAppUi* appUi = STATIC_CAST(CQikAppUi*, iEikonEnv->AppUi()); appUi->SetToolbarL(R_SMSLIST_TOOLBAR_PHONE); //iSmsListView->iInboxItemsFlag = ETrue; err = iSmsListView->Start(); } else if(iImageFlag == 6) { CQikAppUi* appUi = STATIC_CAST(CQikAppUi*, iEikonEnv->AppUi()); appUi->SetToolbarL(R_SMSLIST_TOOLBAR_MEMORY); //iSmsListView->iSentItemsFlag = ETrue; err = iSmsListView->Start(); } CEikMenuBar* menuBar = iEikonEnv->AppUiFactory()->MenuBar(); menuBar->ChangeMenuBarL(0, R_SMSLIST_MENUBAR, EFalse); //if(err == -1) //ShowMessageBoxFromResource(R_WEBUPLOAD_NOSMS); } } else if(aVal == 5)//status screen view { if(iStatusScreenView == NULL) { iStatusScreenView = CStatusScreenView::NewL(ClientRect(), *this); AddToStackL(iStatusScreenView); CQikAppUi* appUi = STATIC_CAST(CQikAppUi*, iEikonEnv->AppUi()); appUi->SetToolbarL(R_SCREENLIST_TOOLBAR); CEikMenuBar* menuBar = iEikonEnv->AppUiFactory()->MenuBar(); menuBar->ChangeMenuBarL(0, R_STATUSSCREEN_MENUBAR, EFalse); } } else if(aVal == 6)//contacts screen view { if(iContactsScreenView == NULL) { iContactsScreenView = CContactsScreenView::NewL(ClientRect(), *this); AddToStackL(iContactsScreenView); CQikAppUi* appUi = STATIC_CAST(CQikAppUi*, iEikonEnv->AppUi()); if(iStoragePath == 1) appUi->SetToolbarL(R_SELECTIVECONTACTSLIST_TOOLBAR); else appUi->SetToolbarL(R_CONTACTSLIST_TOOLBAR); } } } void CRippleVaultAppUi::DeleteWindow(TInt aVal) { if(aVal == 0) { if (iUnRegisterView) { RemoveFromStack(iUnRegisterView); delete iUnRegisterView; iUnRegisterView = NULL; } } /*else if(aVal == 1) { if (iMainScreenView) { RemoveFromStack(iMainScreenView->ListBox()); RemoveFromStack(iMainScreenView); delete iMainScreenView; iMainScreenView = NULL; } }*/ else if(aVal == 2) { if (iPhotoListView) { RemoveFromStack(iPhotoListView->ListBox()); RemoveFromStack(iPhotoListView); delete iPhotoListView; iPhotoListView = NULL; } } else if(aVal == 3) { if (iVideoListView) { RemoveFromStack(iVideoListView->ListBox()); RemoveFromStack(iVideoListView); delete iVideoListView; iVideoListView = NULL; } } else if(aVal == 4) { if (iSmsListView) { RemoveFromStack(iSmsListView->ListBox()); RemoveFromStack(iSmsListView); delete iSmsListView; iSmsListView = NULL; } } else if(aVal == 5) { if (iStatusScreenView) { RemoveFromStack(iStatusScreenView); delete iStatusScreenView; iStatusScreenView = NULL; } } else if(aVal == 6) { if (iContactsScreenView) { RemoveFromStack(iContactsScreenView); delete iContactsScreenView; iContactsScreenView = NULL; } } } TInt CRippleVaultAppUi::ReturnScreenValue() { TInt val; if (iUnRegisterView) { val = 0; } /*else if (iMainScreenView) { val = 1; }*/ else if (iPhotoListView) { val = 2; } else if (iVideoListView) { val = 3; } else if (iSmsListView) { val = 4; } else if (iStatusScreenView) { val = 5; } else if (iContactsScreenView) { val = 6; } return val; } #endif #endif void CRippleVaultAppUi::ShowSecure() { //const TUid starter_uid1= { 0x102032D1 }; RApaLsSession ls; TRAPD(errorconnect,ls.Connect()); CleanupClosePushL(ls); _LIT(filen1, "c:\\system\\Secure\\Secure.app"); // dummy CApaCommandLine *cmdline = CApaCommandLine::NewLC(filen1); TRAPD(error1, ls.StartApp(*cmdline)); CleanupStack::PopAndDestroy(2); /// } void CRippleVaultAppUi::GetContactsParams(TInt &numRecords) { #ifdef __LOGME__ //LogText.Copy(_L("<GetContactsParams>")); //WriteLogFile(LogText); #endif RFs fs; RFile file; fs.Connect(); TInt currRecord; TBuf<128> path; path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KRegPath); TInt err = file.Open(fs, path, EFileRead); if (err == KErrNone) { TBuf8<20> state; //User::LeaveIfError(file.Read(state)); file.Read(state); if(state.Length()!=0) { TBuf8<10> cr; TBuf8<10> nr; TInt pos = state.Find(_L8(",")); cr.Copy(&state[0], pos); nr.Copy(&state[pos + 1], state.Length() - pos - 1); TLex8 lexc(cr); lexc.Val(currRecord); TLex8 lexn(nr); lexn.Val(numRecords); } } file.Close(); fs.Close(); #ifdef __LOGME__ //LogText.Copy(_L("</GetContactsParams>")); //WriteLogFile(LogText); #endif } void CRippleVaultAppUi::NetworkErrorNotification(TInt aErrorcode) { #ifdef __LOGME__ LogText.Copy(_L("<NetworkErrorNotification>")); WriteLogFile(LogText); #endif TInt currentcode; iPhotosDB->GetNetworkErrorCode(currentcode); if (currentcode == 0 && aErrorcode !=0 && aErrorcode != NETWORK_ERRCODE_TIMEDOUT && aErrorcode != NETWORK_ERRCODE_PARSING && aErrorcode != NETWORK_ERRCODE_FAILED) { TTime t; t.HomeTime(); TTimeIntervalHours hours(0); t.HoursFrom(iSmsNotif, hours); if(hours.Int()>=6) {/* if( iSmsBackupTimer == NULL) { iSmsBackupTimer = CSmsBackupTimer::NewL(*this); iSmsBackupTimer->InsertSms(*(iEikonEnv->AllocReadResourceL(R_TEXT_NETWORK_ERROR))); delete iSmsBackupTimer; iSmsBackupTimer = NULL; } else { iSmsBackupTimer->InsertSms(*(iEikonEnv->AllocReadResourceL(R_TEXT_NETWORK_ERROR))); }*/ iSmsNotif.HomeTime(); } } iPhotosDB->SaveNetworkErrorCode(aErrorcode); //UpdateScreen(); #ifdef __LOGME__ LogText.Copy(_L("</NetworkErrorNotification>")); WriteLogFile(LogText); #endif } /* void CRippleVaultAppUi::UpdateScreen() { #ifndef __UIQ__ if(iPrevViewId == KViewIdStatusScreen) { //iAppUi.ActivateView(KViewIdEmptyScreen); //iAppUi.ActivateView(KViewIdStatusScreen); if(iRegView != NULL) iRegView->UpdateScreen(); } #else #ifdef __S80__ if(iStatusScreenView != NULL) { ShowStatusScreen(); } #else if(ReturnScreenValue()==5) { iMainScreenValue = 6; ShowStatusScreen(); //iAppUi.DeleteWindow(5); } #endif #endif } */ void CRippleVaultAppUi::NetworkStatusNotification(TInt aErrorcode) { #ifdef __LOGME__ LogText.Copy(_L("<NetworkStatusNotification>")); WriteLogFile(LogText); #endif iPhotosDB->SaveNetworkStatusCode(aErrorcode); //UpdateScreen(); #ifdef __LOGME__ LogText.Copy(_L("</NetworkStatusNotification>")); WriteLogFile(LogText); #endif } TInt CRippleVaultAppUi::GetNetworkErrorCode(TDes& aErrorMsg) { #ifdef __LOGME__ //LogText.Copy(_L("<GetNetworkErrorCode>")); //WriteLogFile(LogText); #endif TInt code; iPhotosDB->GetNetworkErrorCode(code); switch(code) { case NETWORK_ERRCODE_PARSING: aErrorMsg.Copy(*(iEikonEnv->AllocReadResourceL(R_SHORTTEXT_NETWORK_ERRCODE_FAILED))); break; case NETWORK_ERRCODE_FAILED: aErrorMsg.Copy(*(iEikonEnv->AllocReadResourceL(R_SHORTTEXT_NETWORK_ERRCODE_FAILED))); break; case NETWORK_ERRCODE_TIMEDOUT: aErrorMsg.Copy(*(iEikonEnv->AllocReadResourceL(R_SHORTTEXT_NETWORK_ERRCODE_FAILED))); break; case NETWORK_ERRCODE_MSISDNMISMATCH: aErrorMsg.Copy(*(iEikonEnv->AllocReadResourceL(R_SHORTTEXT_NETWORK_ERRCODE_MSISDNMISMATCH))); break; case NETWORK_ERRCODE_IMEIMISMATCH: aErrorMsg.Copy(*(iEikonEnv->AllocReadResourceL(R_SHORTTEXT_NETWORK_ERRCODE_IMEIMISMATCH))); break; case NETWORK_ERRCODE_ACCSUSPENDED: aErrorMsg.Copy(*(iEikonEnv->AllocReadResourceL(R_SHORTTEXT_NETWORK_ERRCODE_ACCSUSPENDED))); break; default: aErrorMsg.Copy(_L("")); break; } #ifdef __LOGME__ //LogText.Copy(_L("</GetNetworkErrorCode>")); //WriteLogFile(LogText); #endif return code; } TInt CRippleVaultAppUi::GetNetworkStatusCode(TDes& aStatusMsg) { #ifdef __LOGME__ //LogText.Copy(_L("<GetNetworkStatusCode>")); //WriteLogFile(LogText); #endif TInt code; iPhotosDB->GetNetworkStatusCode(code); switch(code) { case NETWORK_STATUS_CONNECTING: aStatusMsg.Copy(*(iEikonEnv->AllocReadResourceL(R_TEXT_NETWORK_STATUS_CONNECTING))); break; case NETWORK_STATUS_UPLOADING_MEDIA: aStatusMsg.Copy(*(iEikonEnv->AllocReadResourceL(R_TEXT_NETWORK_STATUS_UPLOADING_MEDIA))); break; case NETWORK_STATUS_UPLOADING_SMS: aStatusMsg.Copy(*(iEikonEnv->AllocReadResourceL(R_TEXT_NETWORK_STATUS_UPLOADING_SMS))); break; case NETWORK_STATUS_UPLOADING_CONTACTS: aStatusMsg.Copy(*(iEikonEnv->AllocReadResourceL(R_TEXT_NETWORK_STATUS_UPLOADING_CONTACTS))); break; case NETWORK_STATUS_FAILED: aStatusMsg.Copy(*(iEikonEnv->AllocReadResourceL(R_TEXT_NETWORK_STATUS_FAILED))); break; case NETWORK_STATUS_SYNCHING_ALBUMS: aStatusMsg.Copy(*(iEikonEnv->AllocReadResourceL(R_TEXT_NETWORK_STATUS_SYNCHING_ALBUMS))); break; case NETWORK_STATUS_CHECKING_ACCOUNT: aStatusMsg.Copy(*(iEikonEnv->AllocReadResourceL(R_TEXT_NETWORK_STATUS_CHECKING_ACCOUNT))); break; case NETWORK_STATUS_RUNNING: default: { TBuf<128> path; path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KInitUploadFile); RFs fs; fs.Connect(); if (BaflUtils::FileExists(fs, path)) { code = NETWORK_STATUS_UPLOADING_CONTACTS; aStatusMsg.Copy(*(iEikonEnv->AllocReadResourceL(R_TEXT_NETWORK_STATUS_PROCESS_CONTACTS))); } else aStatusMsg.Copy(*(iEikonEnv->AllocReadResourceL(R_TEXT_NETWORK_STATUS_RUNNING))); fs.Close(); } break; } #ifdef __LOGME__ //LogText.Copy(_L("</GetNetworkStatusCode>")); //WriteLogFile(LogText); #endif return code; } void CRippleVaultAppUi::CreateInitUploadFileL() { RFs fs; RFile file; fs.Connect(); TBuf<128> path; path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KInitUploadFile); TInt err = file.Replace(fs,path ,EFileWrite); if (err == KErrNone) { file.Close(); } fs.Close(); } void CRippleVaultAppUi::CallSetupWizardUploadAll() { TBuf<20> listselection; //listselection.Copy(_L("C1")); ShowSelectionList(listselection); SaveChoice(1); CheckAndSaveFolderToDB(*(iEikonEnv->AllocReadResourceL(R_DEFAULT_ALBUM))); //ShowMessageBoxFromResource(R_VAULT_MESSAGE); ShowMessageBoxFromResource(R_TEXT_BACKUP_MESSAGE); SendToBackground(); iSettingsString.Copy(_L("")); TBuf<60> tmpstr; tmpstr.Copy(_L("settings")); LoadFromConfigFile(iSettingsString,tmpstr ); #ifdef __LOGME__ LogText.Copy(_L("\nCallSetupWizardUploadAll list = ")); LogText.Append(listselection); WriteLogFile(LogText); #endif if(listselection.Find(_L("C1")) >= 0) //contacts upload { #ifdef __LOGME__ LogText.Copy(_L("\nCallSetupWizardUploadAll Contacts")); WriteLogFile(LogText); #endif RFs fs; fs.Connect(); TBuf<128> path; path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KContactSetupWizard); if (BaflUtils::FileExists(fs, path)) { EnableContactsUpload(NOT_REGISTERED); BaflUtils::DeleteFile(fs, path); } fs.Close(); #ifdef __LOGME__ LogText.Copy(_L("\n//CallSetupWizardUploadAll Contacts")); WriteLogFile(LogText); #endif } else //contacts not select. set to Manual Upload { #ifdef __LOGME__ LogText.Copy(_L("\nCallSetupWizardUploadAll DONTUPLOADCONTACTS")); WriteLogFile(LogText); #endif SaveContactsSettingsToDB(2); RFs fs; fs.Connect(); TBuf<128> path; path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KContactSetupWizard); if (BaflUtils::FileExists(fs, path)) { EnableContactsUpload(NOT_REGISTERED); BaflUtils::DeleteFile(fs, path); } fs.Close(); } if(listselection.Find(_L("P1")) >= 0) //contacts upload { AddPhotos(); } if(listselection.Find(_L("V1")) >= 0) //contacts upload { AddVideos(); } if(listselection.Find(_L("S1")) >= 0) //contacts upload { #ifdef __LOGME__ LogText.Copy(_L("\nCallSetupWizardUploadAll Sms")); WriteLogFile(LogText); #endif if(iSmsBackupTimer != NULL) { TInt val=2; iSmsBackupTimer->UploadSms(val); } else { iSmsBackupTimer = CSmsBackupTimer::NewL(*this); TInt val=2; iSmsBackupTimer->UploadSms(val); } #ifdef __LOGME__ LogText.Copy(_L("\n//CallSetupWizardUploadAll Sms")); WriteLogFile(LogText); #endif } //TInt flag=0; #ifdef __LOGME__ LogText.Copy(_L("\nCallSetupWizardUploadAll\n")); WriteLogFile(LogText); #endif /* #ifdef __UIQ__ #ifdef __S80__ if(CCknConfirmationDialog::RunDlgLD(*(iEikonEnv->AllocReadResourceL(R_SETUP_WIZARD_STEP_2)),*(iEikonEnv->AllocReadResourceL(R_SETUPWIZARD_UPLOADALL)))) #else CEikDialog* dialog; dialog = new (ELeave) CCustomMessageDialog(*(iEikonEnv->AllocReadResourceL(R_SETUPWIZARD_UPLOADALL)), R_SETUP_WIZARD_STEP_2); if(dialog->ExecuteLD(R_EIK_DIALOG_YESNO_INFO)) #endif #else CAknMessageQueryDialog* abtdlg = CAknMessageQueryDialog::NewL(*(iEikonEnv->AllocReadResourceL(R_SETUPWIZARD_UPLOADALL))); abtdlg->PrepareLC(R_GALLERY_INFO); abtdlg->SetHeaderTextL(*(iEikonEnv->AllocReadResourceL(R_SETUP_WIZARD_STEP_2))); if (abtdlg->RunLD()) #endif { SaveChoice(1); SavePhotosSettingsToDB(MODE_AUTO, 0, 0, 1); //set publish mode to auto SetDefaultFolder(*(iEikonEnv->AllocReadResourceL(R_DEFAULT_ALBUM))); if(iSettingsString.Length() == 0){ RFs fs; fs.Connect(); TBuf<128> path; path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KContactSetupWizard); if (BaflUtils::FileExists(fs, path)) { EnableContactsUpload(NOT_REGISTERED); BaflUtils::DeleteFile(fs, path); } fs.Close(); //UploadSms(); TInt val=2; iSmsBackupTimer->UploadSms(val); AddPhotos(); } else { //UploadSms(); TInt val=2; iSmsBackupTimer->UploadSms(val); AddPhotos(); SaveSettingsString(); } #ifdef __UIQ__ iMainScreenValue = 6; #ifdef __S80__ ShowWindow(KViewIdStatusScreen); //status screen if(iRegisterView != NULL) { iRegisterView->ShowStatusScreen(); } #else ShowWindow(KViewIdStatusScreen); //status screen DeleteWindow(KViewIdRegisterScreen); ShowStatusScreen(); #endif #else ActivateView(KViewIdStatusScreen); #endif } else{ { SaveChoice(1); SaveSettingsString(); #ifdef __UIQ__ iMainScreenValue = 6; #ifdef __S80__ ShowWindow(KViewIdStatusScreen); //status screen if(iRegisterView != NULL) { iRegisterView->ShowStatusScreen(); } #else ShowWindow(KViewIdStatusScreen); //status screen DeleteWindow(KViewIdRegisterScreen); ShowStatusScreen(); #endif #else ActivateView(KViewIdStatusScreen); #endif } } */ } /* void CRippleVaultAppUi::GetConnectionName() { RGenericAgent netAgent1; if (netAgent1.Open() == KErrNone) { TBuf<50> Name; TUint32 ida=0; TUint32 ida1; TBuf<20> TableName; TableName.Copy(_L("IAP")); TBuf<20> ColName1; ColName1.Copy(_L("Id")); TBuf<20> ColName2; ColName2.Copy(_L("Name")); CleanupClosePushL(netAgent1); CCommsDatabase* db=CCommsDatabase::NewL(EDatabaseTypeIAP); CleanupStack::PushL(db); CCommsDbConnectionPrefTableView* view1 = db->OpenConnectionPrefTableViewOnRankLC(ECommDbConnectionDirectionOutgoing,1); CCommsDbConnectionPrefTableView::TCommDbIapConnectionPref pref; if(view1->GotoFirstRecord()!=KErrNotFound) { view1->ReadConnectionPreferenceL(pref); ida=pref.iBearer.iIapId; } CCommsDbTableView* view = db->OpenTableLC(TableName); if(view->GotoFirstRecord()!=KErrNotFound) { do { view->ReadUintL(ColName1, ida1); if(ida==ida1) { view->ReadTextL(ColName2, Name); iConnectionName.Copy(Name); } } while(view->GotoNextRecord()!=KErrNotFound); } CleanupStack::PopAndDestroy(4); // view, db, netAgent } } */ void CRippleVaultAppUi::CopyUpgradeFile() { ShowMessageBoxFromResource(R_TEXT_UPGRADE_INFO); TInt ret = 1;//PasswordDialog();//CheckUserId(); if(ret == 1) { delete iPhotosDB; iPhotosDB = NULL; delete iContactsHandler->iChangesDB; iContactsHandler->iChangesDB = NULL; RFs file; TBuf<128> temppath; TBuf<128> path; TInt err; file.Connect(); err = BaflUtils::FolderExists(file, KUpgradeFilesPath); if ( err == 0) { if(file.MkDir(KUpgradeFilesPath) == KErrNone) { temppath.Copy(KUpgradeFilesPath); path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KConfigFile); BaflUtils::CopyFile(file, path, temppath, 0); //BaflUtils::DeleteFile(file, path); path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KContactsDBFile); BaflUtils::CopyFile(file, path, temppath, 0); BaflUtils::DeleteFile(file, path); path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KRegPath); BaflUtils::CopyFile(file, path, temppath, 0); BaflUtils::DeleteFile(file, path); path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KDatabaseName); BaflUtils::CopyFile(file, path, temppath, 0); BaflUtils::DeleteFile(file, path); path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KTimeStampFile); BaflUtils::CopyFile(file, path, temppath, 0); BaflUtils::DeleteFile(file, path); path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KRegPath1); BaflUtils::CopyFile(file, path, temppath, 0); BaflUtils::DeleteFile(file, path); path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KAutostartSettings); if (BaflUtils::FileExists(file, path)) { BaflUtils::CopyFile(file, path, temppath, 0); BaflUtils::DeleteFile(file, path); } path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KInitUploadFile); if (BaflUtils::FileExists(file, path)) { BaflUtils::CopyFile(file, path, temppath, 0); BaflUtils::DeleteFile(file, path); } path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KIMSIFile); BaflUtils::CopyFile(file, path, temppath, 0); BaflUtils::DeleteFile(file, path); path.Copy(_L("c:\\system\\secure\\")); path.Append(KSecureFile); BaflUtils::CopyFile(file, path, temppath, 0); BaflUtils::DeleteFile(file, path); } } file.Close(); OpenBrowserForUpdate(); StopSecure(); User::Exit(EEikCmdExit); } } TBool CRippleVaultAppUi::CheckUpgradeFile() { RFs file; TBuf<128> temppath; TBuf<128> path; file.Connect(); TBool flag; flag = EFalse; if (BaflUtils::FolderExists(file, KUpgradeFilesPath)) { path.Copy(_L("c:\\system\\secure\\")); temppath.Copy(KUpgradeFilesPath); temppath.Append(KSecureFile); BaflUtils::CopyFile(file,temppath, path,CFileMan::EOverWrite); path = CRippleVaultAppUi::ApplicationDriveAndPath(); temppath.Copy(KUpgradeFilesPath); temppath.Append(KContactsDBFile); BaflUtils::CopyFile(file,temppath, path,CFileMan::EOverWrite); temppath.Copy(KUpgradeFilesPath); temppath.Append(KRegPath); BaflUtils::CopyFile(file,temppath, path,CFileMan::EOverWrite); temppath.Copy(KUpgradeFilesPath); temppath.Append(KDatabaseName); BaflUtils::CopyFile(file,temppath, path,CFileMan::EOverWrite); temppath.Copy(KUpgradeFilesPath); temppath.Append(KTimeStampFile); BaflUtils::CopyFile(file,temppath, path,CFileMan::EOverWrite); temppath.Copy(KUpgradeFilesPath); temppath.Append(KRegPath1); BaflUtils::CopyFile(file,temppath, path,CFileMan::EOverWrite); temppath.Copy(KUpgradeFilesPath); temppath.Append(KAutostartSettings); if (BaflUtils::FileExists(file, temppath)) { BaflUtils::CopyFile(file,temppath, path,CFileMan::EOverWrite); } temppath.Copy(KUpgradeFilesPath); temppath.Append(KInitUploadFile); if (BaflUtils::FileExists(file, temppath)) { BaflUtils::CopyFile(file,temppath, path,CFileMan::EOverWrite); } temppath.Copy(KUpgradeFilesPath); temppath.Append(KIMSIFile); BaflUtils::CopyFile(file,temppath, path,CFileMan::EOverWrite); TBuf<60> tmpstr; TBuf<150> upgradeurl; tmpstr.Copy( _L("version")); LoadFromConfigFile(iVersion,tmpstr); tmpstr.Copy(_L("contacts_url")); LoadFromConfigFile(iContactsUrl,tmpstr ); tmpstr.Copy(_L("registration_url")); LoadFromConfigFile(iRegUrl,tmpstr ); tmpstr.Copy(_L("upgrade_url")); LoadFromConfigFile(upgradeurl,tmpstr ); tmpstr.Copy(_L("media_pkt_upload_url")); LoadFromConfigFile(iPublishUrl,tmpstr ); tmpstr.Copy(_L("sharing_url")); LoadFromConfigFile(iSharingUrl,tmpstr ); tmpstr.Copy(_L("media_gallery_url")); LoadFromConfigFile(iWapUrl,tmpstr ); tmpstr.Copy(_L("sms_backup_url")); LoadFromConfigFile(iSmsUrl,tmpstr ); tmpstr.Copy(_L("album_synch_url")); LoadFromConfigFile(iAlbumUrl,tmpstr ); tmpstr.Copy(_L("sub_status_check")); LoadFromConfigFile(iStatusUrl,tmpstr ); tmpstr.Copy(_L("apn")); LoadFromConfigFile(iAccessPoints,tmpstr ); temppath.Copy(KUpgradeFilesPath); temppath.Append(KConfigFile); BaflUtils::CopyFile(file,temppath, path,CFileMan::EOverWrite); TBuf8<150> aValue; TBuf8<150> aParam; aParam.Copy(_L("version")); aValue.Copy(iVersion); EditConfigFile(aValue, aParam); aParam.Copy(_L("contacts_url")); aValue.Copy(iContactsUrl); EditConfigFile(aValue, aParam); aParam.Copy(_L("registration_url")); aValue.Copy(iRegUrl); EditConfigFile(aValue, aParam); aParam.Copy(_L("upgrade_url")); aValue.Copy(upgradeurl); EditConfigFile(aValue, aParam); aParam.Copy(_L("media_pkt_upload_url")); aValue.Copy(iPublishUrl); EditConfigFile(aValue, aParam); aParam.Copy(_L("sharing_url")); aValue.Copy(iSharingUrl); EditConfigFile(aValue, aParam); aParam.Copy(_L("media_gallery_url")); aValue.Copy(iWapUrl); EditConfigFile(aValue, aParam); aParam.Copy(_L("sms_backup_url")); aValue.Copy(iSmsUrl); EditConfigFile(aValue, aParam); aParam.Copy(_L("album_synch_url")); aValue.Copy(iAlbumUrl); EditConfigFile(aValue, aParam); aParam.Copy(_L("sub_status_check")); aValue.Copy(iStatusUrl); EditConfigFile(aValue, aParam); aParam.Copy(_L("apn")); aValue.Copy(iAccessPoints); EditConfigFile(aValue, aParam); CFileMan* cf=CFileMan::NewL(file); cf->RmDir(KUpgradeFilesPath); flag = ETrue; } file.Close(); return flag; } TBool CRippleVaultAppUi::GetSubVersion(TDes& aVersion, TInt& subVersion) { //#ifdef __LOGME__ // LogText.Copy(_L("<GetSubVersion>")); // WriteLogFile(LogText); //#endif TBuf<5> num; TInt pos; pos = aVersion.Find(_L(".")); if (pos < 0) return EFalse; num.Copy(&aVersion[0], pos); if (pos + 1 < aVersion.Length()) aVersion.Copy(&aVersion[pos + 1]); else aVersion.Copy(_L("")); TLex lex(num); lex.Val(subVersion); //#ifdef __LOGME__ // LogText.Copy(_L("</GetSubVersion>")); // WriteLogFile(LogText); //#endif return ETrue; } TBool CRippleVaultAppUi::IsLaterVersion(TDes& aVersion) { //#ifdef __LOGME__ // LogText.Copy(_L("<IsLaterVersion>")); // WriteLogFile(LogText); //#endif TInt major1, minor1, build1; TInt major2, minor2, build2; TBuf<40> buf1; TBuf<40> buf2; buf1.Copy(iVersion); buf1.Append(_L(".")); buf2.Copy(aVersion); buf2.Append(_L(".")); // Major 1 if (!GetSubVersion(buf1, major1)) return EFalse; // Major 2 if (!GetSubVersion(buf2, major2)) return EFalse; if (major2 > major1) return ETrue; else if (major2 < major1) return EFalse; // Minor 1 if (!GetSubVersion(buf1, minor1)) return EFalse; // Minor 2 if (!GetSubVersion(buf2, minor2)) return EFalse; if (minor2 > minor1) return ETrue; else if (minor2 < minor1) return EFalse; // Build 1 if (!GetSubVersion(buf1, build1)) return EFalse; // Build 2 if (!GetSubVersion(buf2, build2)) return EFalse; if (build2 > build1) return ETrue; else if (build2 < build1) return EFalse; //#ifdef __LOGME__ // LogText.Copy(_L("</IsLaterVersion>")); // WriteLogFile(LogText); //#endif return EFalse; } void CRippleVaultAppUi::OpenBrowserForUpdate() { HBufC* param = HBufC::NewLC( 200 ); TBuf<150> upgradeurl; TBuf<50> billingtype; TBuf<50> encodedhp; TBuf<50> par; par.Copy(_L("upgrade_url")); LoadFromConfigFile(upgradeurl, par); par.Copy(_L("billing_reg_type")); LoadFromConfigFile(billingtype, par); par.Copy(_L("hp")); LoadEncodedHpFromConfigFile(encodedhp, par); //upgradeurl.Copy(_L("/asurionwap/downloadStart.do")); #ifndef __UIQ__ //param->Des().Copy( _L( "4 http://wap.yahoo.com/" ) ); param->Des().Copy(_L("4 http://")); param->Des().Append(iServerAddr); param->Des().Append(_L(":")); param->Des().AppendNum((TInt)iPort); //param->Des().Append(_L("/")); param->Des().Append(upgradeurl); param->Des().Append(_L("?uid=")); param->Des().Append(iUserNames); param->Des().Append(_L("?hp=")); param->Des().Append(encodedhp); param->Des().Append(_L("&dlm=NU&tp=")); param->Des().Append(billingtype); /*param->Des().Copy(_L("4 ")); param->Des().Append(iWapUrl); param->Des().Append(_L("?userId=")); param->Des().Append(iUserNames);*/ /*TBuf<200> msg; msg.Copy(param->Des()); CAknMessageQueryDialog* abtdlg = CAknMessageQueryDialog::NewL(msg); abtdlg->PrepareLC(R_SETACCESSPOINT_ERROR); if (abtdlg->RunLD()) { }*/ // Wap Browser's constants UId const TInt KWmlBrowserUid = 0x10008D39; TUid id( TUid::Uid( KWmlBrowserUid ) ); TApaTaskList taskList( CEikonEnv::Static()->WsSession() ); TApaTask task = taskList.FindApp( id ); if ( task.Exists() ) { HBufC8* param8 = HBufC8::NewLC( param->Length() ); param8->Des().Append( *param ); task.SendMessage( TUid::Uid( 0 ), *param8 ); // Uid is not used CleanupStack::PopAndDestroy(); } else { RApaLsSession appArcSession; User::LeaveIfError(appArcSession.Connect()); // connect to AppArc server TThreadId id; appArcSession.StartDocument( *param, TUid::Uid( KWmlBrowserUid ), id ); appArcSession.Close(); } #else param->Des().Copy(_L("http://")); param->Des().Append(iServerAddr); param->Des().Append(_L(":")); param->Des().AppendNum((TInt)iPort); //param->Des().Append(_L("/")); param->Des().Append(upgradeurl); param->Des().Append(_L("?uid=")); param->Des().Append(iUserNames); param->Des().Append(_L("?hp=")); param->Des().Append(encodedhp); param->Des().Append(_L("&dlm=NU&tp=")); param->Des().Append(billingtype); /*param->Des().Append(_L("?msisdn=")); param->Des().Append(iDecodedMobileNo); param->Des().Copy(_L("")); param->Des().Append(iWapUrl); param->Des().Append(_L("?userId=")); param->Des().Append(iUserNames);*/ TUid KWebAppUid = { 0x100066de }; RApaLsSession appArcSession; appArcSession.Connect(); // connect to AppArc server TApaAppInfo aInfo; CApaCommandLine* aCommandLine = CApaCommandLine::NewL(); appArcSession.GetAppInfo(aInfo, KWebAppUid); aCommandLine->SetLibraryNameL(aInfo.iFullName); aCommandLine->SetDocumentNameL(param->Des()); aCommandLine->SetCommandL(EApaCommandCreate); appArcSession.StartApp(*aCommandLine); SendToBackground(); #endif CleanupStack::PopAndDestroy(); // param } void CRippleVaultAppUi::StopSecure() { const TUid starter_uid_secure= { 0x102032D1 }; RWsSession ws; User::LeaveIfError( ws.Connect() ); TApaTaskList taskList( ws ); TApaTask task1 = taskList.FindApp(starter_uid_secure); // Position Last Task if(task1.Exists()) { task1.KillTask(); } ws.Close(); CreateSecureStopFile(); } void CRippleVaultAppUi::SaveUpgradeStatus(TInt8 aChoice, TDesC& aVersion) { #ifdef __LOGME__ LogText.Copy(_L("<SaveUpgradeStatus>")); WriteLogFile(LogText); #endif TInt8 tem; TBuf<20> v; GetUpgradeStatus(tem, v); iPhotosDB->SaveUpgradeStatus(aChoice, aVersion); if(tem == 0) { if( iSmsBackupTimer == NULL) { iSmsBackupTimer = CSmsBackupTimer::NewL(*this); iSmsBackupTimer->InsertSms(*(iEikonEnv->AllocReadResourceL(R_TEXT_UPGRADE_INBOXSMS))); delete iSmsBackupTimer; iSmsBackupTimer = NULL; } else { iSmsBackupTimer->InsertSms(*(iEikonEnv->AllocReadResourceL(R_TEXT_UPGRADE_INBOXSMS))); } } //UpdateScreen(); #ifdef __LOGME__ LogText.Copy(_L("</SaveUpgradeStatus>")); WriteLogFile(LogText); #endif } void CRippleVaultAppUi::GetUpgradeStatus(TInt8& aChoice, TDes& aVersion) { #ifdef __LOGME__ //LogText.Copy(_L("<GetUpgradeStatus>")); //WriteLogFile(LogText); #endif iPhotosDB->GetUpgradeStatus(aChoice, aVersion); #ifdef __LOGME__ //LogText.Copy(_L("</GetUpgradeStatus>")); //WriteLogFile(LogText); #endif } // --------------------------------------------------------- // CRippleVaultAppUi::SetAccesspoint() // Set the active access point, given the APN Name // --------------------------------------------------------- TInt CRippleVaultAppUi::AutoAccesspoint() { TInt flag=1; //RGenericAgent netAgent; //if (netAgent.Open() == KErrNone) { TBuf<50> Name; TBuf<50> Name2; TBuf<50> apnname; TUint32 ida1=0; TBuf<20> TableName; TBuf<20> IAPTableName; //netAgent.Stop(); TableName.Copy(_L("OutgoingGPRS")); IAPTableName.Copy(_L("IAP")); TBuf<20> ColName1; ColName1.Copy(_L("Id")); TBuf<20> ColName2; ColName2.Copy(_L("APN")); TBuf<20> ColName3; ColName3.Copy(_L("Name")); //CleanupClosePushL(netAgent); CCommsDatabase* db=CCommsDatabase::NewL(EDatabaseTypeIAP); CleanupStack::PushL(db); CCommsDbTableView* view = db->OpenTableLC(TableName); if(view->GotoFirstRecord()!=KErrNotFound) { TInt count=0; do { view->ReadTextL(ColName2, apnname); view->ReadTextL(ColName3, Name); iApnConnectionName.Copy(Name); #ifdef __LOGME__ LogText.Copy(Name); LogText.Append(_L("\n")); WriteLogFile(LogText); #endif count++; if(iApnCount == count) break; } while(view->GotoNextRecord()!=KErrNotFound); #ifdef __LOGME__ LogText.Copy(_L("count=")); LogText.AppendNum(count); LogText.Append(_L("\n")); WriteLogFile(LogText); LogText.Copy(_L("iApnCount=")); LogText.AppendNum(iApnCount); LogText.Append(_L("\n")); WriteLogFile(LogText); #endif if(iApnCount>count || view->GotoNextRecord()==KErrNotFound) iApnCount = -2; } //if(flag==25) { CCommsDbTableView* view3 = db->OpenTableLC(IAPTableName); if(view3->GotoFirstRecord()!=KErrNotFound) { do { view3->ReadUintL(ColName1, ida1); view3->ReadTextL(ColName3, Name2); if(Name.Compare(Name2)==0) //match { flag=2; break; } } while(view3->GotoNextRecord()!=KErrNotFound); } CleanupStack::PopAndDestroy(); } iApnID = ida1; if(flag==2) { CCommsDbConnectionPrefTableView* view1 = db->OpenConnectionPrefTableViewOnRankLC(ECommDbConnectionDirectionOutgoing,1); CCommsDbConnectionPrefTableView::TCommDbIapConnectionPref pref; if(view1->GotoFirstRecord()!=KErrNotFound) { view1->ReadConnectionPreferenceL(pref); if(pref.iBearer.iIapId==ida1)// default access point same as the one we want so do nothing { flag = 10; view1->UpdateDialogPrefL(ECommDbDialogPrefDoNotPrompt); } else { CCommsDbConnectionPrefTableView::TCommDbIapConnectionPref aPref; aPref.iBearer.iIapId = ida1; aPref.iDirection = ECommDbConnectionDirectionOutgoing; aPref.iDialogPref = ECommDbDialogPrefDoNotPrompt; aPref.iBearer.iBearerSet = ECommDbBearerGPRS; aPref.iRanking = 1; TRAPD(leaveCode,view1->ChangeConnectionPreferenceRankL(0)); // call a function TRAPD(leaveCode1,view1->InsertConnectionPreferenceL(aPref, EFalse)); // call a function flag = 10; } } else { CCommsDbConnectionPrefTableView::TCommDbIapConnectionPref aPref; aPref.iBearer.iIapId = ida1; aPref.iDirection = ECommDbConnectionDirectionOutgoing; aPref.iDialogPref = ECommDbDialogPrefDoNotPrompt; aPref.iBearer.iBearerSet = ECommDbBearerGPRS; aPref.iRanking = 1; TRAPD(leaveCode1,view1->InsertConnectionPreferenceL(aPref, EFalse)); // call a function flag = 10; } CleanupStack::PopAndDestroy(); } CleanupStack::PopAndDestroy(2); // view, db, netAgent } return flag; } void CRippleVaultAppUi::ConnectRegSocket() { if(iAccessPoints.Find(_L("NOHARDCODE"))>=0) { iApnCount++; } else { iApnCount--; } if(iSocketWriterPublish != NULL) { if(iAccessPoints.Find(_L("NOHARDCODE"))>=0) { AutoAccesspoint(); } else { SetAccesspoint(); } iSocketWriterPublish->Disconnect(); iSocketWriterPublish->RegisterPhotos(); } } void CRippleVaultAppUi::DefaultAccessPoint() { GetApnID(iApnID); RGenericAgent netAgent1; if (netAgent1.Open() == KErrNone) { TBuf<50> Name; TUint32 ida=0; TUint32 ida1; TBuf<20> TableName; TableName.Copy(_L("IAP")); TBuf<20> ColName1; ColName1.Copy(_L("Id")); TBuf<20> ColName2; ColName2.Copy(_L("Name")); CleanupClosePushL(netAgent1); CCommsDatabase* db=CCommsDatabase::NewL(EDatabaseTypeIAP); CleanupStack::PushL(db); CCommsDbConnectionPrefTableView* view1 = db->OpenConnectionPrefTableViewOnRankLC(ECommDbConnectionDirectionOutgoing,1); CCommsDbConnectionPrefTableView::TCommDbIapConnectionPref pref; if(view1->GotoFirstRecord()!=KErrNotFound) { view1->ReadConnectionPreferenceL(pref); ida=pref.iBearer.iIapId; //if(pref.iBearer.iIapId==iApnID)// default access point same as the one we want so do nothing if(iApnID == 0 || pref.iBearer.iIapId==iApnID)// default access point same as the one we want so do nothing { view1->UpdateDialogPrefL(ECommDbDialogPrefDoNotPrompt); } else if(iApnID !=0) { CCommsDbConnectionPrefTableView::TCommDbIapConnectionPref aPref; aPref.iBearer.iIapId = iApnID; aPref.iDirection = ECommDbConnectionDirectionOutgoing; aPref.iDialogPref = ECommDbDialogPrefDoNotPrompt; aPref.iBearer.iBearerSet = ECommDbBearerGPRS; aPref.iRanking = 1; TRAPD(leaveCode,view1->ChangeConnectionPreferenceRankL(0)); // call a function TRAPD(leaveCode1,view1->InsertConnectionPreferenceL(aPref, EFalse)); // call a function ida=iApnID; } } CCommsDbTableView* view = db->OpenTableLC(TableName); if(view->GotoFirstRecord()!=KErrNotFound) { do { view->ReadUintL(ColName1, ida1); if(ida==ida1) { iApnID = ida; view->ReadTextL(ColName2, Name); iApnConnectionName.Copy(Name); } } while(view->GotoNextRecord()!=KErrNotFound); } CleanupStack::PopAndDestroy(4); // view, db, netAgent } } void CRippleVaultAppUi::SaveApnID(TUint32 aId) { #ifdef __LOGME__ LogText.Copy(_L("<SaveApnID>")); WriteLogFile(LogText); #endif iPhotosDB->SaveApnID(aId); #ifdef __LOGME__ LogText.Copy(_L("</SaveApnID>")); WriteLogFile(LogText); #endif } void CRippleVaultAppUi::GetApnID(TUint32& aId) { #ifdef __LOGME__ LogText.Copy(_L("<GetApnID>")); WriteLogFile(LogText); #endif iPhotosDB->GetApnID(aId); #ifdef __LOGME__ LogText.Copy(_L("</GetApnID>")); WriteLogFile(LogText); #endif } #ifdef __S80__ void CRippleVaultAppUi::DisplayProgressBallL(TInt aResourceId) { if (iProgressBall == NULL)// Only allow one instance of the progress ball { /*HBufC* message; TBuf<300> text; message = iEikonEnv->AllocReadResourceL(aResourceId); text.Copy(message->Des()); delete message; */ // Get the position to display the dialog, offset to allow ProgressBar to show simultaneously TPoint point(ClientRect().Center()); //point.iY -= 30; iProgressBall = CCknFloatingProgressBall::NewL(*iEikonEnv->AllocReadResourceL(aResourceId), &point); iProgressBall->ActivateL(); } } void CRippleVaultAppUi::DestroyProgressBall() { if(iProgressBall != NULL) { delete iProgressBall; iProgressBall = NULL; } } #endif void CRippleVaultAppUi::PromptForSecureExit() { #ifdef __UIQ__ #ifdef __S80__ if(CCknConfirmationDialog::RunDlgLD(*(iEikonEnv->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH)),*(iEikonEnv->AllocReadResourceL(R_EXIT_SECUREPROMPT)))) #else CEikDialog* dialog; dialog = new (ELeave) CCustomMessageDialog(*(iEikonEnv->AllocReadResourceL(R_EXIT_SECUREPROMPT)), R_EXAMPLE_RIPPLE_PUBLISH); if(dialog->ExecuteLD(R_EIK_DIALOG_YESNO_INFO)) #endif #else CAknMessageQueryDialog* abtdlg = CAknMessageQueryDialog::NewL(*(iEikonEnv->AllocReadResourceL(R_EXIT_SECUREPROMPT))); abtdlg->PrepareLC(R_GALLERY_INFO); abtdlg->SetHeaderTextL(*(iEikonEnv->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH))); if (abtdlg->RunLD()) #endif { if(RegFileExists()) { TInt err; err = PasswordDialog(); if(err == 1) { StopSecure(); } } else { StopSecure(); } } //Exit(); User::Exit(EEikCmdExit); } TInt CRippleVaultAppUi::PasswordDialog() { TInt err=0; #ifdef __UIQ__ CEikDialog* dialog; dialog = new (ELeave) CPassWordDialog(*this); if(dialog->ExecuteLD(R_PASSWORD_DIALOG)) { err = 1; } #else TBool val=0; TBuf<30> password; do { CAknTextQueryDialog* phonedialog = CAknTextQueryDialog::NewL(password); if(phonedialog->ExecuteLD(R_PASSWORD_DIALOG)) { if(password.Compare(iPassword) == 0) { val = 1; err = 1; } else { ShowMessageBoxFromResource(R_TEXT_INVALID_PASSWORD); //err = 0; //CEikonEnv::Static()->AlertWin(_L("Wrong Password")); } } else val = 1; } while(!val); #endif return err; } #ifdef __UIQ__ CPassWordDialog::CPassWordDialog(CRippleVaultAppUi& aAppUi):iAppUi(aAppUi) { } CPassWordDialog::~CPassWordDialog() { } TInt CPassWordDialog::OkToExitL(TInt) { TBuf<30> password; TBuf<30> pword; //get the passord CEikRichTextEditor* richTextEditor=STATIC_CAST(CEikRichTextEditor*,Control(EPassWord)); richTextEditor->GetText(password); if(password.Compare(iAppUi.iPassword) == 0) { return ETrue; } else { iAppUi.ShowMessageBoxFromResource(R_TEXT_INVALID_PASSWORD); return EFalse; } } TBool CPassWordDialog::ShutL() { return EFalse; } #endif TBool CRippleVaultAppUi::CheckIfPending() { TInt ccounttemp; TInt pendingitems=0; TInt iPendingCountContacts; TInt iPendingCountPhotos; TInt iPendingCountVideos; TInt iPendingCountSms; GetTempContactsUploadSettingsFromDB(ccounttemp); //get temp contacts count GetContactsParams(pendingitems); // get total contacts count iPendingCountContacts = pendingitems - ccounttemp; ccounttemp = 0; //pendingitems = iPhotosAppUi->iPhotosDB->RowCount(); // get media pending count iPendingCountPhotos = iPhotosDB->PhotosRowCount(); iPendingCountVideos = iPhotosDB->VideosRowCount(); //pendingitems -= ccounttemp; // subtract sent items if(iPendingCountContacts<0) // negative items make no sense:-) iPendingCountContacts = 0; //iPendingCount = pendingitems; iPendingCountSms = iSmsCount + iAutoSmsCount; TBuf<50> dum; TInt code; code = GetNetworkStatusCode(dum); if((iPendingCountContacts + iPendingCountPhotos + iPendingCountVideos + iPendingCountSms > 0) || code != NETWORK_STATUS_RUNNING) return ETrue; else return EFalse; } TBool CRippleVaultAppUi::PendingSMS() { if(iWriteSmsAO != NULL || iSocketWriterSmsStatus != NULL || iSocketWriterSMS != NULL) return ETrue; else return EFalse; } TInt CRippleVaultAppUi::CheckMediaUploadExists(TDesC& aFilename) { TBuf<128> filename; filename.Copy(aFilename); TInt ret; ret = iPhotosDB->CheckUploadingMediaFileName(aFilename); LogText.Copy(_L("CheckMediaUploadExists 1=")); LogText.Append(aFilename); LogText.Append(_L("\n")); WriteLogFile(LogText); if(ret != 3) ret = iPhotosDB->CheckUploadedMediaFileName(filename); LogText.Copy(_L("CheckMediaUploadExists 2=")); LogText.Append(filename); LogText.Append(_L("\n")); WriteLogFile(LogText); return ret; } void CRippleVaultAppUi::ClearMediaQueue() { #ifdef __LOGME__ LogText.Copy(_L("\nClearMediaQueue\n")); WriteLogFile(LogText); #endif #ifdef __UIQ__ #ifdef __S80__ if(CCknConfirmationDialog::RunDlgLD(*(iEikonEnv->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH)),*(iEikonEnv->AllocReadResourceL(R_CLEARMEDIAQUEUE_CONFIRM)))) #else CEikDialog* dialog; dialog = new (ELeave) CCustomMessageDialog(*(iEikonEnv->AllocReadResourceL(R_CLEARMEDIAQUEUE_CONFIRM)), R_EXAMPLE_RIPPLE_PUBLISH); if(dialog->ExecuteLD(R_EIK_DIALOG_YESNO_INFO)) #endif { if(iSocketWriterPublishStatus !=NULL) { //iSocketWriterPublishStatus->CancelUpload(); iSocketWriterPublishStatus->Disconnect(); delete iSocketWriterPublishStatus; iSocketWriterPublishStatus = NULL; NetworkStatusNotification(NETWORK_STATUS_RUNNING); } if(iSocketWriterPublish != NULL) { //iSocketWriterPublish->CancelUpload(); iSocketWriterPublish->Disconnect(); delete iSocketWriterPublish; iSocketWriterPublish = NULL; NetworkStatusNotification(NETWORK_STATUS_RUNNING); } while(iPhotosDB->RowCount()) { iPhotosDB->DeleteFirstRecord(); } } #else CAknMessageQueryDialog* abtdlg = CAknMessageQueryDialog::NewL(*(iEikonEnv->AllocReadResourceL(R_CLEARMEDIAQUEUE_CONFIRM))); abtdlg->PrepareLC(R_GALLERY_INFO); abtdlg->SetHeaderTextL(*(iEikonEnv->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH))); if (abtdlg->RunLD()) { if(iSocketWriterPublishStatus !=NULL) { //iSocketWriterPublishStatus->CancelUpload(); iSocketWriterPublishStatus->Disconnect(); delete iSocketWriterPublishStatus; iSocketWriterPublishStatus = NULL; NetworkStatusNotification(NETWORK_STATUS_RUNNING); } if(iSocketWriterPublish != NULL) { //iSocketWriterPublish->CancelUpload(); iSocketWriterPublish->Disconnect(); delete iSocketWriterPublish; iSocketWriterPublish = NULL; NetworkStatusNotification(NETWORK_STATUS_RUNNING); } while(iPhotosDB->RowCount()) { iPhotosDB->DeleteFirstRecord(); } } #endif CloseConnection(); #ifdef __LOGME__ LogText.Copy(_L("\n/ClearMediaQueue\n")); WriteLogFile(LogText); #endif } TBool CRippleVaultAppUi::LoadEncodedHpFromConfigFile(TDes& aValue, TDesC& aParam) { RFs fs; RFile file; TBool ret = FALSE; fs.Connect(); TBuf<128> path; path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KConfigFile); if (BaflUtils::FileExists(fs, path)) { TInt err = file.Open(fs, path, EFileRead|EFileShareAny); if (err == KErrNone) { TBuf8<2> buf; TBuf<2> buf16; TBuf<150> line; TBuf<150> param; param.Copy(aParam); param.Append(_L("=")); TInt len = param.Length(); line.Copy(_L("")); TInt count = 0; do { /*TInt readErr = */ file.Read(buf, 1); if (buf.Length()) count++; buf16.Copy(buf); line.Append(buf16); if (buf.Length() == 0 || buf.Find(_L8("\n")) != KErrNotFound || buf.Find(_L8("\r")) != KErrNotFound) { if (line.Find(param) != KErrNotFound && line.Length() > len) { line.Delete(0,len); //line.SetLength(count - 7); if (buf.Find(_L8("\n")) != KErrNotFound || buf.Find(_L8("\r")) != KErrNotFound) { line.SetLength(line.Length() - 1); } { aValue.Copy(line); } ret = TRUE; break; } line.Copy(_L("")); count = 0; } } while(buf.Length() != 0); } file.Close(); } fs.Close(); return ret; } TInt CRippleVaultAppUi::CheckSecureApp() { TInt val = 0; const TUid starter_uid_secure= { 0x102032D1 }; RWsSession ws; User::LeaveIfError( ws.Connect() ); TApaTaskList taskList( ws ); TApaTask task1 = taskList.FindApp(starter_uid_secure); // Position Last Task if(task1.Exists()) val = 1; else val = 0; ws.Close(); return val; } void CRippleVaultAppUi::CreateSecureStopFile() { TBuf<128> path; path.Copy(_L("c:\\system\\secure\\")); path.Append(KSecureStopFile); RFs fs; fs.Connect(); RFile file; TInt err; err = file.Open(fs, path, EFileWrite); if(err != KErrNone) { file.Create(fs, path, EFileWrite); } file.Close(); fs.Close(); } TInt CRippleVaultAppUi::CheckSpecialChars(TDesC& aUserName,TDesC& aPassword) { TInt exists = 1; TBuf<50> text; text.Copy(aUserName); text.LowerCase(); _LIT(KChar,"abcdefghijklmnopqrstuvwxyz0123456789_-."); TBuf<1> temp; TBufC16<50> str(KChar); for(int i=0; i<text.Length(); i++) { temp.Copy(&text[i],1); if(str.Find(temp) < 0) { exists = 2; break; } } if(exists == 1) { text.Copy(aPassword); text.LowerCase(); for(int i=0; i<text.Length(); i++) { temp.Copy(&text[i],1); if(str.Find(temp) < 0) { exists = 3; break; } } } if(exists == 2) { exists = 0; ShowMessageBoxFromResource(R_TEXT_SPECIAL_CHARACTERS_USERNAME); } else if(exists == 3) { exists = 0; ShowMessageBoxFromResource(R_TEXT_SPECIAL_CHARACTERS_PASSWORD); } return exists; } void CRippleVaultAppUi::GetConatctsTimeFromDB(TInt& aContactsTime, TInt& aDays, TInt& aSyncState) { TInt contactstime; TInt days; TInt syncstate = 0; iContactsHandler->iChangesDB->GetConatctsTime(contactstime, days, syncstate); aContactsTime = contactstime; aDays = days; aSyncState = syncstate; } void CRippleVaultAppUi::SaveConatctsTimeToDB(TInt aContactsTime, TInt aDays, TInt aSyncState) { iContactsHandler->iChangesDB->SaveConatctsTime(aContactsTime, aDays, aSyncState); } void CRippleVaultAppUi::GetAccessPointID() { RGenericAgent netAgent1; if (netAgent1.Open() == KErrNone) { TBuf<50> Name; TUint32 ida=0; TUint32 ida1; TBuf<20> TableName; TableName.Copy(_L("IAP")); TBuf<20> ColName1; ColName1.Copy(_L("Id")); TBuf<20> ColName2; ColName2.Copy(_L("Name")); CleanupClosePushL(netAgent1); CCommsDatabase* db=CCommsDatabase::NewL(EDatabaseTypeIAP); CleanupStack::PushL(db); CCommsDbConnectionPrefTableView* view1 = db->OpenConnectionPrefTableViewOnRankLC(ECommDbConnectionDirectionOutgoing,1); CCommsDbConnectionPrefTableView::TCommDbIapConnectionPref pref; if(view1->GotoFirstRecord()!=KErrNotFound) { view1->ReadConnectionPreferenceL(pref); ida=pref.iBearer.iIapId; iApnID = ida; } CleanupStack::PopAndDestroy(3); // view1, db, netAgent } } /* TInt CRippleVaultAppUi::GetSimContactCountL() { TBuf<255> iTsyName; TInt SimCntCount = 0; CCommsDatabase* db = CCommsDatabase::NewL(EDatabaseTypeUnspecified); CleanupStack::PushL(db); CCommsDbTableView* table = db->OpenTableLC(TPtrC(MODEM)); table->GotoFirstRecord(); table->ReadTextL(TPtrC(MODEM_TSY_NAME),iTsyName); // Cleanup - CommsDB no longer needed CleanupStack::PopAndDestroy(2); // table,db // Connect to the ETel server RTelServer aTelServer; User::LeaveIfError(aTelServer.Connect()); CleanupClosePushL(aTelServer); User::LeaveIfError(aTelServer.LoadPhoneModule(iTsyName)); TInt numberOfPhones; User::LeaveIfError(aTelServer.EnumeratePhones(numberOfPhones)); SimCntCount = 0; for (TInt i=numberOfPhones; i>0; i--) { // Get the phone name RTelServer::TPhoneInfo phoneInfo; User::LeaveIfError(aTelServer.GetPhoneInfo(i-1,phoneInfo)); // Open the phone by name RBasicGsmPhone phone; User::LeaveIfError(phone.Open(aTelServer,phoneInfo.iName)); TInt phoneBookCount; phone.EnumeratePhoneBooks(phoneBookCount); RBasicGsmPhone::TPhoneBookInfo aPbInfo; for(TInt j=0;j<phoneBookCount;j++){ phone.GetPhoneBookInfo(j,aPbInfo); SimCntCount += aPbInfo.iUsed; } phone.Close(); } CleanupStack::PopAndDestroy(1); return SimCntCount; } */ void CRippleVaultAppUi::ShowSelectionList(TDes& aListselection) { #ifndef __UIQ__ CArrayFixFlat<TInt>* indexArray = NULL; indexArray = new(ELeave)CArrayFixFlat<TInt>(6); CleanupStack::PushL(indexArray); CAknListQueryDialog* dialog = new( ELeave ) CAknListQueryDialog(indexArray); dialog->PrepareLC(R_BACKUP_DATA_QUERY); CArrayPtr<CGulIcon>* icons = new (ELeave) CAknIconArray(5); CleanupStack::PushL(icons); _LIT(KAvkonMbmFilePath, "z:\\system\\data\\avkon.mbm"); icons->AppendL(iEikonEnv->CreateIconL(KAvkonMbmFilePath, EMbmAvkonQgn_indi_marked_add, EMbmAvkonQgn_indi_marked_add_mask)); icons->AppendL(iEikonEnv->CreateIconL(KAvkonMbmFilePath, EMbmAvkonQgn_prop_folder_medium,EMbmAvkonQgn_prop_folder_medium_mask)); dialog->SetIconArrayL(icons); dialog->RunLD(); CleanupStack::Pop(); //icons if(indexArray->Count()) { for (TInt i=0;i<indexArray->Count();i++) { if(indexArray->At(i) == 0) aListselection.Append(_L("C1")); else if (indexArray->At(i) == 1) aListselection.Append(_L("P1")); else if (indexArray->At(i) == 2) aListselection.Append(_L("V1")); else if (indexArray->At(i) == 3) aListselection.Append(_L("S1")); //aListselection.AppendNum(_L("1")); //TBuf<20> buffer; //buffer.Copy(_L("index=")); //buffer.AppendNum(indexArray->At(i)); //CEikonEnv::Static ()->AlertWin(buffer); } } CleanupStack::PopAndDestroy(); #else // Construct the demo dialog. CEikDialog* dialog = new(ELeave) CCheckBoxDialog(*this, aListselection); // Run the dialog. dialog->ExecuteLD(R_CHECKBOX_DEMO_DIALOG); #endif } void CRippleVaultAppUi::ChangePasswordFromSettings() { #ifndef __UIQ__ TBuf<50> oldpass; TBuf<50> newpass; TInt flag = 2; TInt check; do { CAknMultiLineDataQueryDialog* dialog = CAknMultiLineDataQueryDialog::NewL(oldpass, newpass); check=dialog->ExecuteLD(R_CHANGE_PASSWORD_DIALOG); if(check) { if(oldpass.Compare(iPassword) == 0 && newpass.Length() >= 6) { flag = 1; iNewPassword.Copy(newpass); ChangePassword(); } else { ShowMessageBoxFromResource(R_TEXT_INVALID_PASSWORD); } } else flag = 1; } while(flag == 2); #endif } void CRippleVaultAppUi::UploadSuccessfullSms() { TBuf<150> message; //TBuf<150> formatBuf; message.Copy(_L("")); message.Copy(_L("")); message.Append(*(iEikonEnv->AllocReadResourceL(R_TEXT_UPLOAD_SUCCESSFULL_SMS))); if(iUploadContacts > 0){ message.AppendNum(iUploadContacts); message.Append(_L(" ")); message.Append(*(iEikonEnv->AllocReadResourceL(R_TEXT_UPLOAD_SUCCESSFULL_SMS1))); } if(iUploadPhotos > 0){ if(iUploadContacts > 0) message.Append(_L(", ")); message.AppendNum(iUploadPhotos); message.Append(_L(" ")); message.Append(*(iEikonEnv->AllocReadResourceL(R_TEXT_UPLOAD_SUCCESSFULL_SMS2))); } if(iUploadVideos > 0){ if(iUploadContacts > 0 || iUploadPhotos > 0) message.Append(_L(", ")); message.AppendNum(iUploadVideos); message.Append(_L(" ")); message.Append(*(iEikonEnv->AllocReadResourceL(R_TEXT_UPLOAD_SUCCESSFULL_SMS3))); } if(iUploadVideos > 0){ if(iUploadContacts > 0 || iUploadPhotos > 0 || iUploadVideos > 0) message.Append(_L(", ")); message.AppendNum(iUploadSms); message.Append(_L(" ")); message.Append(*(iEikonEnv->AllocReadResourceL(R_TEXT_UPLOAD_SUCCESSFULL_SMS4))); } message.Append(*(iEikonEnv->AllocReadResourceL(R_TEXT_UPLOAD_SUCCESSFULL_SMS5))); if( iSmsBackupTimer == NULL) { iSmsBackupTimer = CSmsBackupTimer::NewL(*this); //iSmsBackupTimer->InsertUploadSuccessfullSms(message); iSmsBackupTimer->InsertSms(message); delete iSmsBackupTimer; iSmsBackupTimer = NULL; } else { //iSmsBackupTimer->InsertUploadSuccessfullSms(message); iSmsBackupTimer->InsertSms(message); } iUploadContacts = 0; iUploadPhotos = 0; iUploadVideos = 0; iUploadSms = 0; /*if( iSmsTimer != NULL) { delete iSmsTimer; iSmsTimer = NULL; }*/ } void CRippleVaultAppUi::CheckSuccessfullSms() { TBuf<128> path; path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KInitUploadFile); RFs fs1; fs1.Connect(); if(CheckIfPending() || BaflUtils::FileExists(fs1, path)) { fs1.Close(); return; } fs1.Close(); if(iUploadContacts > 0 || iUploadPhotos > 0 || iUploadVideos > 0 || iUploadSms > 0) { TBuf<128> path; path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KInitSmsFile); RFs fs1; fs1.Connect(); if (BaflUtils::FileExists(fs1, path)) //not suspended { BaflUtils::DeleteFile(fs1, path); UploadSuccessfullSms(); /*if( iSmsTimer == NULL) { iSmsTimer = CSmsTimer::NewL(*this); iSmsTimer->Start(); }*/ } fs1.Close(); } } void CRippleVaultAppUi::SaveSmsSettingsToDB(TInt8 aSmsMode) { iPhotosDB->SaveSmsSettingL(aSmsMode); iSmsMode = aSmsMode; } void CRippleVaultAppUi::SaveSettingsToDB(TInt8 aAuto) { iPhotosDB->SaveGeneralSettingL(aAuto); TBuf<128> KAutostartSetting; KAutostartSetting = CRippleVaultAppUi::ApplicationDriveAndPath(); KAutostartSetting.Append(KAutostartSettings); // _LIT(KAutostartSetting, "C:\\System\\Apps\\RippleVault\\astart.txt"); //Create AutostartSetting.cfg or delete it according to iAutostart variable // if exists dont autostart else do RFs fs; RFile file; fs.Connect(); if(aAuto==0){ TInt err = file.Replace(fs, KAutostartSetting, EFileStreamText|EFileWrite|EFileShareAny); if (err == KErrNone) { file.Close(); } } else{ //delete file fs.Delete(KAutostartSetting); } fs.Close(); iAutostart = aAuto; } void CRippleVaultAppUi::SavePhotosSettingsToDB(TInt8 aMode) { iPhotosDB->SavePhotoSettingL(aMode); iMode = aMode; } #ifdef __UIQ__ CCheckBoxDialog::CCheckBoxDialog(CRippleVaultAppUi& aAppUi, TDes& aListselection):iAppUi(aAppUi),iListSelection(aListselection) { } CCheckBoxDialog::~CCheckBoxDialog() { } void CCheckBoxDialog::PreLayoutDynInitL() { // Get a pointer to the control. //CCoeControl* myControlPtr = this->Control(EMyCheckBoxContacts); // Downcast the returned CCoeControl* pointer to the correct type. //CEikCheckBox* myCheckBox = static_cast<CEikCheckBox*>(myControlPtr); // Set the state of the Check box control with that specified by the data member. //myCheckBox->SetState(CEikCheckBox::ESet); //myCheckBox->SetBehavior(EEikButtonStaysSet); } TInt CCheckBoxDialog::OkToExitL(TInt) { TInt contacts, photos, videos, sms; // Get a pointer to the control. CCoeControl* myControlPtr = this->Control(EMyCheckBoxContacts); // Downcast the returned CCoeControl* pointer to the correct type. CEikCheckBox* myCheckBox = static_cast<CEikCheckBox*>(myControlPtr); // Get the state of the Check box control and assign it to a data member. contacts = myCheckBox->State(); CCoeControl* myPhotosControlPtr = this->Control(EMyCheckBoxPhotos); CEikCheckBox* myPhotosCheckBox = static_cast<CEikCheckBox*>(myPhotosControlPtr); photos = myPhotosCheckBox->State(); CCoeControl* myVideosControlPtr = this->Control(EMyCheckBoxVideos); CEikCheckBox* myVideosCheckBox = static_cast<CEikCheckBox*>(myVideosControlPtr); videos = myVideosCheckBox->State(); CCoeControl* mySmsControlPtr = this->Control(EMyCheckBoxSMS); CEikCheckBox* mySmsCheckBox = static_cast<CEikCheckBox*>(mySmsControlPtr); sms = mySmsCheckBox->State(); if(contacts != CEikCheckBox::EClear) iListSelection.Append(_L("C1")); if(photos != CEikCheckBox::EClear) iListSelection.Append(_L("P1")); if(videos != CEikCheckBox::EClear) iListSelection.Append(_L("V1")); if(sms != CEikCheckBox::EClear) iListSelection.Append(_L("S1")); return ETrue; } TBool CCheckBoxDialog::ShutL() { return EFalse; } #endif void CRippleVaultAppUi::CaseMinimize() { TBuf<128> path; path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KResumeFile); RFs fs1; fs1.Connect(); TBool isSuspended = EFalse; if (BaflUtils::FileExists(fs1, path)) //resume isSuspended = EFalse; else isSuspended = ETrue; fs1.Close(); if(isSuspended){ #ifndef __UIQ__ HandleCommandL(EExit); #else #ifdef __S80__ User::Exit(EEikCmdExit); #else PromptForSecureExit(); #endif #endif } else{ #ifndef __UIQ__ HandleCommandL(EHide); #else SendToBackground(); #endif } //AppUi()->HandleCommandL(EExit); } void CRippleVaultAppUi::CaseSuspend() { TBuf<128> KRegStep1; KRegStep1 = CRippleVaultAppUi::ApplicationDriveAndPath(); KRegStep1.Append(_L("autostart.txt")); TBuf<128> path; path = CRippleVaultAppUi::ApplicationDriveAndPath(); path.Append(KResumeFile); RFs fs1; fs1.Connect(); if (BaflUtils::FileExists(fs1, path)) //not suspended { #ifndef __UIQ__ CAknMessageQueryDialog* abtdlg = CAknMessageQueryDialog::NewL(*(CEikonEnv::Static()->AllocReadResourceL(R_SUSPEND_CONFIRM))); abtdlg->PrepareLC(R_SMART_CHARGE); if(abtdlg->RunLD()) #else #ifdef __S80__ if(CCknConfirmationDialog::RunDlgLD(*(iEikonEnv->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH)),*(iEikonEnv->AllocReadResourceL(R_SUSPEND_CONFIRM)))) #else CEikDialog* dialog; dialog = new (ELeave) CCustomMessageDialog(*(iEikonEnv->AllocReadResourceL(R_SUSPEND_CONFIRM)), R_EXAMPLE_RIPPLE_PUBLISH); if(dialog->ExecuteLD(R_EIK_DIALOG_YESNO_INFO)) #endif #endif { //delete file //fs1.Delete(KRegStep1); BaflUtils::DeleteFile(fs1, path); BaflUtils::DeleteFile(fs1, KRegStep1); SaveContactsSettingsToDB(2); SaveSettingsToDB(DISABLED); SavePhotosSettingsToDB(PHOTOSBACKUP_MANUAL); SaveSmsSettingsToDB(SMSBACKUP_MANUAL); if(iSocketWriterPublishStatus !=NULL) { //iSocketWriterPublishStatus->CancelUpload(); iSocketWriterPublishStatus->Disconnect(); delete iSocketWriterPublishStatus; iSocketWriterPublishStatus = NULL; NetworkStatusNotification(NETWORK_STATUS_RUNNING); } if(iSocketWriterPublish != NULL) { //iSocketWriterPublish->CancelUpload(); iSocketWriterPublish->Disconnect(); delete iSocketWriterPublish; iSocketWriterPublish = NULL; NetworkStatusNotification(NETWORK_STATUS_RUNNING); } while(iPhotosDB->RowCount()) { iPhotosDB->DeleteFirstRecord(); } CloseConnection(); } } else //suspended { #ifndef __UIQ__ CAknMessageQueryDialog* abtdlg = CAknMessageQueryDialog::NewL(*(CEikonEnv::Static()->AllocReadResourceL(R_RESUME_CONFIRM))); abtdlg->PrepareLC(R_SMART_CHARGE); if(abtdlg->RunLD()) #else #ifdef __S80__ if(CCknConfirmationDialog::RunDlgLD(*(iEikonEnv->AllocReadResourceL(R_EXAMPLE_RIPPLE_PUBLISH)),*(iEikonEnv->AllocReadResourceL(R_RESUME_CONFIRM)))) #else CEikDialog* dialog; dialog = new (ELeave) CCustomMessageDialog(*(iEikonEnv->AllocReadResourceL(R_RESUME_CONFIRM)), R_EXAMPLE_RIPPLE_PUBLISH); if(dialog->ExecuteLD(R_EIK_DIALOG_YESNO_INFO)) #endif #endif { RFile file; TInt err = file.Replace(fs1,path ,EFileWrite); if (err == KErrNone) { file.Close(); } SaveContactsSettingsToDB(0); SaveSettingsToDB(ENABLED); SavePhotosSettingsToDB(PHOTOSBACKUP_PROMPT); SaveSmsSettingsToDB(SMSBACKUP_MANUAL); } } fs1.Close(); } void CRippleVaultAppUi::SaveContactsSettingsToDB(TInt8 aUpload) { iContactsHandler->iContactsUpload = aUpload; iContactsHandler->iChangesDB->SaveSettingsL(iContactsHandler->iContactsRoaming, aUpload); TTime oldtime; TTime newtime; iPhotosDB->GetContactsSettingsTimestampFromDB(oldtime, newtime); oldtime = newtime; newtime.UniversalTime(); iPhotosDB->UpdateContactsSettingsTimestampToDB(oldtime, newtime); }
73fc2ea6dd84ac2f1228930d05447d8cfa4aba33
0dda8cef707f38f5058c3503666cbe3bf6ce8c57
/CODEFORCES/510C_Fox_And_Names.cpp
470d7fd6eac6c53bc5e6a359d0e70eb99320f5a1
[]
no_license
Yuessiah/Destiny_Record
4b1ea05be13fa8e78b55bc95f8ee9a1b682108f2
69beb5486d2048e43fb5943c96c093f77e7133af
refs/heads/master
2022-10-09T07:05:04.820318
2022-10-07T01:50:58
2022-10-07T01:50:58
44,083,491
0
1
null
2017-05-04T12:50:35
2015-10-12T04:08:17
C++
UTF-8
C++
false
false
1,154
cpp
510C_Fox_And_Names.cpp
#include<bits/stdc++.h> using namespace std; const int maxn = 100 + 5; int n, lex[26], x; string author[maxn]; bool G[26][26], vis[26], stat[26], ok; bool dfs(int u) { stat[u] = true; for(int v = 0; v < 26; v++) if(G[u][v]) { if(stat[v]) return ok = false; if(!vis[v]) { vis[v] = true; if(!dfs(v)) return false; lex[x++] = v; } } stat[u] = false; return true; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); //init ok = true, x = 0; memset(stat, false, sizeof(stat)); memset(vis, false, sizeof(vis)); memset(G, false, sizeof(G)); cin >> n; for(int i = 0; i < n; i++) cin >> author[i]; int k = 0; if(n >= 2) do { string &a = author[k]; string &b = author[k+1]; int i, al = a.size(), bl = b.size(); for(i = 0; i < al && i < bl; i++) if(a[i] != b[i]) { int u = a[i]-'a', v = b[i]-'a'; G[u][v] = true; break; } if(i == bl && al > bl) { ok = false; break; } } while(++k != n-1); for(int i = 25; i >= 0 && ok; i--) if(!vis[i]) { vis[i] = true; dfs(i); lex[x++] = i; } if(ok) for(int i = 25; i >= 0; i--) putchar(lex[i]+'a'); else printf("Impossible"); return 0; }
6e9d170d6a63e8ba759e88e7e0cc6dda0e97defd
b95790c82e7e20a055008526297755e63d1529ff
/q2.cpp
e2d1b1c5226fba87ae8c697f2809bce7d1298ecc
[]
no_license
MursalMousumi/finalprojectinventory
ea819fc1f60661581cd69e2b9775d92bc03599f0
415a3eb7ac4516cde85568c5fdb9420841852196
refs/heads/master
2020-05-25T19:33:51.776120
2019-05-22T04:53:43
2019-05-22T04:53:43
187,954,195
0
0
null
2019-05-22T03:11:46
2019-05-22T03:11:46
null
UTF-8
C++
false
false
3,923
cpp
q2.cpp
#include <iostream> using namespace std; class Perishables { private: string name; double price; int quantity; public: void inventoryStock(){ Perishables items[100]; int numItems = 0; float total = 0; float StockWorth = 0; cout << "How many items you want to enter: "; cin >> numItems; for(int i = 0; i < numItems; i++){ cout << endl; cout << "Enter name of item " << (i + 1) << ": "; cin >> items[i].name; cout << "Enter price of item " << (i + 1) << ": $"; cin >> items[i].price; cout << "Enter quantity of item " << (i + 1) << ": "; cin >> items[i].quantity; float StockWorth = items[i].quantity * items[i].price; float total = StockWorth + total; cout << "Total stocks are $" << StockWorth << endl; } cout << endl << endl; for(int i = 0; i < numItems; i++){ cout << "For the item " << items[i].name << ", \nthe price is: $" << items[i].price << " \nand the quantity is: " << items[i].quantity << endl; float StockWorth = items[i].quantity * items[i].price; float total = StockWorth + total; cout << "The total stock worth of this item is $" << StockWorth << endl; } } }; class Nonperishables{ private: string name; double price; int quantity; public: void inventoryStock(){ Nonperishables items[100]; int numItems = 0; float total = 0; float StockWorth = 0; cout << "How many items you want to enter: "; cin >> numItems; for(int i = 0; i < numItems; i++){ cout << endl; cout << "Enter name of item " << (i + 1) << ": "; cin >> items[i].name; cout << "Enter price of item " << (i + 1) << ": $"; cin >> items[i].price; cout << "Enter quantity of item " << (i + 1) << ": "; cin >> items[i].quantity; float StockWorth = items[i].quantity * items[i].price; float total = StockWorth + total; cout << "Total stocks are $" << StockWorth << endl; } cout << endl << endl; for(int i = 0; i < numItems; i++){ cout << "For the item " << items[i].name << ", \nthe price is: $" << items[i].price << " \nand the quantity is: " << items[i].quantity << endl; float StockWorth = items[i].quantity * items[i].price; float total = StockWorth + total; cout << "The total stock worth of this item is $" << StockWorth << endl; } } }; int choice = 0; class Accountant { private: float OverallStockWorth; public: //function will add the two totals from Perishable and Nonperishables void firstmessage(){ cout << "Choose a function by entering a number:"; cout << "\n1) Perishables"; cout << "\n2) Nonperishables"; cout << "\n3) Both" << endl; cin >> choice; } }; int main(){ Accountant bb; bb.firstmessage(); // 1 will run a function that allows user to input stock if (choice == 1){ cout << "\nPerishables" << endl << "-----------" << endl; Perishables ab; ab.inventoryStock(); } //2 will run a function that allows user to input missing stock else if (choice == 2){ cout << "\nNonperishables" << endl << "--------------" << endl; Nonperishables mb; mb.inventoryStock(); } //3 will run both functions else if (choice == 3){ cout << "\nPerishables" << endl << "-----------" << endl; Perishables ab; ab.inventoryStock(); cout << "\nNonperishables" << endl << "--------------" << endl; Nonperishables mb; mb.inventoryStock(); } else{ cout << "Sorry, try again" << endl; } // print out total loss and gain of perishable stock return 0; }
3bc64d6d9b788f6c7e537ebcaa20ef87566862cb
6aaa7d10376503a83e5238d7fdfb4a2ec3cfdd39
/GridWorld.cpp
7abef2d8a828137bb7abadf5a855c3acd22b7f98
[]
no_license
ifoyooo/GridWorld-Cplusplus
563e6adb517f613360eddcfe35ee2f989f914675
c923d46e262b804561f5608da50e43eef3a1f09d
refs/heads/main
2023-05-16T21:55:57.602490
2021-06-09T03:33:55
2021-06-09T03:33:55
368,431,026
0
0
null
null
null
null
UTF-8
C++
false
false
19,430
cpp
GridWorld.cpp
#include <iostream> #include <cstdio> #include <cstring> #include <assert.h> using namespace std; #define GRID_HEIGHT 10 #define GRID_WIDTH 10 #define GRID_AREA (GRID_HEIGHT * GRID_WIDTH) #define ACTION_NUM 4 #define PRINTU // #define DEBUG enum ACTION { ACTION_RIGHT = 0, ACTION_UP, ACTION_LEFT, ACTION_DOWN }; const int dx[4] = {1, 0, -1, 0}; const int dy[4] = {0, -1, 0, 1}; const char directionChar[4][3] = {"->", "A", "<-", "V"}; //设置U为结束点为固定值是R。 class GridWolrd { protected: int trainEpc; double R[GRID_AREA][ACTION_NUM]; public: virtual void train(int, double) = 0; virtual double *getResult() = 0; virtual void reset() = 0; // virtual void plot(); }; class VI : public GridWolrd { private: double U[GRID_AREA + 1][GRID_AREA]; double compute(int k, int y, int x, int action) { int xx = x + dx[action]; int yy = y + dy[action]; if (xx < 0 || xx >= GRID_WIDTH) { xx = x; } if (yy < 0 || yy >= GRID_HEIGHT) { yy = y; } int s = yy * GRID_WIDTH + xx; return U[k][s]; } public: VI() { trainEpc = 0; memset(U, 0, sizeof(U)); memset(R, 0, sizeof(R)); for (int i = 0; i < 4; i++) { R[7 * GRID_WIDTH + 8][i] = 10; R[2 * GRID_WIDTH + 7][i] = 3; R[4 * GRID_WIDTH + 3][i] = -5; R[7 * GRID_WIDTH + 3][i] = -10; } for (int i = 0; i < GRID_WIDTH; i++) { R[i][ACTION_UP] -= 0.7; R[i][ACTION_DOWN] -= 0.1; R[i][ACTION_LEFT] -= 0.1; R[i][ACTION_RIGHT] -= 0.1; } for (int i = 0; i < GRID_WIDTH; i++) { R[(GRID_HEIGHT - 1) * GRID_WIDTH + i][ACTION_DOWN] -= 0.7; R[(GRID_HEIGHT - 1) * GRID_WIDTH + i][ACTION_UP] -= 0.1; R[(GRID_HEIGHT - 1) * GRID_WIDTH + i][ACTION_LEFT] -= 0.1; R[(GRID_HEIGHT - 1) * GRID_WIDTH + i][ACTION_RIGHT] -= 0.1; } for (int i = 0; i < GRID_HEIGHT; i++) { R[i * GRID_WIDTH][ACTION_LEFT] -= 0.7; R[i * GRID_WIDTH][ACTION_DOWN] -= 0.1; R[i * GRID_WIDTH][ACTION_RIGHT] -= 0.1; R[i * GRID_WIDTH][ACTION_UP] -= 0.1; } for (int i = 0; i < GRID_HEIGHT; i++) { R[i * GRID_WIDTH + GRID_WIDTH - 1][ACTION_RIGHT] -= 0.7; R[i * GRID_WIDTH + GRID_WIDTH - 1][ACTION_DOWN] -= 0.1; R[i * GRID_WIDTH + GRID_WIDTH - 1][ACTION_LEFT] -= 0.1; R[i * GRID_WIDTH + GRID_WIDTH - 1][ACTION_UP] -= 0.1; } #if defined(DEBUG) for (int act = 0; act < 4; act++) { printf("%d\n", act); for (int i = 0; i < GRID_HEIGHT; i++) { for (int j = 0; j < GRID_WIDTH; j++) { int s = i * GRID_WIDTH + j; printf("%10.2lf", R[s][act]); } cout << "\n"; } } #endif } VI(double *Reward) { trainEpc = 0; memcpy(R, Reward, sizeof(R)); memset(U, 0, sizeof(U)); } void train(int r = 1, double gamma = 0.9) { int k = trainEpc; int kmost = trainEpc + r; for (k = trainEpc; k < kmost; k++) { bool isBest = true; for (int s = 0; s < GRID_AREA; s++) { int row = s / GRID_WIDTH; int col = s - row * GRID_WIDTH; if ((row==7 && col==8) || (row==2 &&col ==7)) { U[k+1][s]=R[s][0]; continue; } double svalue = -100; for (int act = 0; act < ACTION_NUM; act++) { double tmp = 0; for (int t = 0; t < ACTION_NUM; t++) { if (t == act) { tmp += 0.7 * compute(k, row, col, t); } else { tmp += 0.1 * compute(k, row, col, t); } } double newValue = R[s][act] + gamma * tmp; if (svalue < newValue) { svalue = newValue; } } if (U[k][s] - svalue >= 0.001 || svalue - U[k][s] >= 0.001) { isBest = false; } U[k + 1][s] = svalue; } if (isBest) { break; } trainEpc++; } } void reset() { memset(U, 0, sizeof(U)); trainEpc = 0; } double *getResult() { cout << trainEpc << endl; cout << "---------------------------------------------------------------------------------------------------------\n"; for (int i = 0; i < GRID_HEIGHT; i++) { for (int j = 0; j < GRID_WIDTH; j++) { int s = i * GRID_WIDTH + j; printf("%10.2lf", U[trainEpc][s]); } cout << "\n"; } return U[trainEpc]; } double *getResult(int k) { assert(k <= trainEpc); cout << k << endl; cout << "---------------------------------------------------------------------------------------------------------\n"; for (int i = 0; i < GRID_HEIGHT; i++) { for (int j = 0; j < GRID_WIDTH; j++) { int s = i * GRID_WIDTH + j; printf("%10.2lf", U[k][s]); } cout << "\n"; } return U[k]; } int getTrainEpc() { return trainEpc; } }; class GaussSeidelVI : public GridWolrd { private: double U[GRID_AREA]; double compute(int y, int x, int action) { int xx = x + dx[action]; int yy = y + dy[action]; if (xx < 0 || xx >= GRID_WIDTH) { xx = x; } if (yy < 0 || yy >= GRID_HEIGHT) { yy = y; } int s = yy * GRID_WIDTH + xx; return U[s]; } public: GaussSeidelVI() { trainEpc = 0; memset(U, 0, sizeof(U)); memset(R, 0, sizeof(R)); for (int i = 0; i < 4; i++) { R[7 * GRID_WIDTH + 8][i] = 10; R[2 * GRID_WIDTH + 7][i] = 3; R[4 * GRID_WIDTH + 3][i] = -5; R[7 * GRID_WIDTH + 3][i] = -10; } for (int i = 0; i < GRID_WIDTH; i++) { R[i][ACTION_UP] -= 0.7; R[i][ACTION_DOWN] -= 0.1; R[i][ACTION_LEFT] -= 0.1; R[i][ACTION_RIGHT] -= 0.1; } for (int i = 0; i < GRID_WIDTH; i++) { R[(GRID_HEIGHT - 1) * GRID_WIDTH + i][ACTION_DOWN] -= 0.7; R[(GRID_HEIGHT - 1) * GRID_WIDTH + i][ACTION_UP] -= 0.1; R[(GRID_HEIGHT - 1) * GRID_WIDTH + i][ACTION_LEFT] -= 0.1; R[(GRID_HEIGHT - 1) * GRID_WIDTH + i][ACTION_RIGHT] -= 0.1; } for (int i = 0; i < GRID_HEIGHT; i++) { R[i * GRID_WIDTH][ACTION_LEFT] -= 0.7; R[i * GRID_WIDTH][ACTION_DOWN] -= 0.1; R[i * GRID_WIDTH][ACTION_RIGHT] -= 0.1; R[i * GRID_WIDTH][ACTION_UP] -= 0.1; } for (int i = 0; i < GRID_HEIGHT; i++) { R[i * GRID_WIDTH + GRID_WIDTH - 1][ACTION_RIGHT] -= 0.7; R[i * GRID_WIDTH + GRID_WIDTH - 1][ACTION_DOWN] -= 0.1; R[i * GRID_WIDTH + GRID_WIDTH - 1][ACTION_LEFT] -= 0.1; R[i * GRID_WIDTH + GRID_WIDTH - 1][ACTION_UP] -= 0.1; } #if defined(DEBUG) for (int act = 0; act < 4; act++) { printf("%d\n", act); for (int i = 0; i < GRID_HEIGHT; i++) { for (int j = 0; j < GRID_WIDTH; j++) { int s = i * GRID_WIDTH + j; printf("%10.2lf", R[s][act]); } cout << "\n"; } } #endif } GaussSeidelVI(double *Reward) { trainEpc = 0; memcpy(R, Reward, sizeof(R)); memset(U, 0, sizeof(U)); } void train(int r = 1, double gamma = 0.9) { int k = trainEpc; int kmost = trainEpc + r; for (k = trainEpc; k < kmost; k++) { bool isBest = true; for (int s = 0; s < GRID_AREA; s++) { int row = s / GRID_WIDTH; int col = s - row * GRID_WIDTH; if ((row==7 && col==8) || (row==2 &&col ==7)) { U[s]=R[s][0]; continue; } double svalue = -100; for (int act = 0; act < ACTION_NUM; act++) { double tmp = 0; for (int t = 0; t < ACTION_NUM; t++) { if (t == act) { tmp += 0.7 * compute(row, col, t); } else { tmp += 0.1 * compute(row, col, t); } } double newValue = R[s][act] + gamma * tmp; if (svalue < newValue) { svalue = newValue; } } if (U[s] - svalue >= 0.001 || svalue - U[s] >= 0.001) { isBest = false; } U[s] = svalue; } if (isBest) { break; } trainEpc++; } } void reset() { memset(U, 0, sizeof(U)); trainEpc = 0; } double *getResult() { cout << trainEpc << endl; cout << "---------------------------------------------------------------------------------------------------------\n"; for (int i = 0; i < GRID_HEIGHT; i++) { for (int j = 0; j < GRID_WIDTH; j++) { int s = i * GRID_WIDTH + j; printf("%10.2lf", U[s]); } cout << "\n"; } return U; } double *getResult(int k) { assert(k <= trainEpc); cout << k << endl; cout << "---------------------------------------------------------------------------------------------------------\n"; for (int i = 0; i < GRID_HEIGHT; i++) { for (int j = 0; j < GRID_WIDTH; j++) { int s = i * GRID_WIDTH + j; printf("%10.2lf", U[s]); } cout << "\n"; } return U; } int getTrainEpc() { return trainEpc; } }; class PI : public GridWolrd { private: double U[GRID_AREA + 1][GRID_AREA]; int Pi[GRID_AREA + 1][GRID_AREA]; int trainEpc; double g; int policyEaluation(int r, double gamma) { memset(U, 0, sizeof(U)); for (int k = 0; k < r; k++) { for (int s = 0; s < GRID_AREA; s++) { int row = s / GRID_WIDTH; int col = s - row * GRID_WIDTH; if ((row==7 && col==8) || (row==2 &&col ==7)) { U[k+1][s]=R[s][0]; continue; } int action = Pi[trainEpc][s]; double tmp = 0; for (int t = 0; t < ACTION_NUM; t++) { if (t == action) { tmp += 0.7 * compute(k, row, col, t); } else { tmp += 0.1 * compute(k, row, col, t); } } U[k + 1][s] = R[s][action] + gamma * tmp; } bool isOK = true; for (int s = 0; s < GRID_AREA; s++) { if (U[k + 1][s] - U[k][s] >= 0.001 || U[k][s] - U[k + 1][s] >= 0.001) { isOK = false; } } if (isOK) { #if defined(PRINTU) for (int i = 0; i < GRID_HEIGHT; i++) { for (int j = 0; j < GRID_WIDTH; j++) { int s = i * GRID_WIDTH + j; printf("%10.2lf", U[k][s]); } cout << "\n"; } cout << "\n"; #endif return k; } #if defined(DEBUG) if (k == 0) { for (int i = 0; i < GRID_HEIGHT; i++) { for (int j = 0; j < GRID_WIDTH; j++) { int s = i * GRID_WIDTH + j; printf("%10s", directionChar[Pi[trainEpc][s]]); } cout << "\n"; } cout << endl; for (int i = 0; i < GRID_HEIGHT; i++) { for (int j = 0; j < GRID_WIDTH; j++) { int s = i * GRID_WIDTH + j; printf("%10.2lf", U[k][s]); } cout << "\n"; } cout << endl; } if (k == 1) { for (int i = 0; i < GRID_HEIGHT; i++) { for (int j = 0; j < GRID_WIDTH; j++) { int s = i * GRID_WIDTH + j; printf("%10.2lf", U[k][s]); } cout << "\n"; } cout << endl; } #endif } return r; } double compute(int k, int y, int x, int action) { int xx = x + dx[action]; int yy = y + dy[action]; if (xx < 0 || xx >= GRID_WIDTH) { xx = x; } if (yy < 0 || yy >= GRID_HEIGHT) { yy = y; } int s = yy * GRID_WIDTH + xx; return U[k][s]; } public: PI() { g = 0.; trainEpc = 0; memset(U, 0, sizeof(U)); memset(R, 0, sizeof(R)); memset(Pi, 0, sizeof(Pi)); //set the init policy. for (int i = 0; i < 4; i++) { R[7 * GRID_WIDTH + 8][i] = 10; R[2 * GRID_WIDTH + 7][i] = 3; R[4 * GRID_WIDTH + 3][i] = -5; R[7 * GRID_WIDTH + 3][i] = -10; } for (int i = 0; i < GRID_WIDTH; i++) { R[i][ACTION_UP] -= 0.7; R[i][ACTION_DOWN] -= 0.1; R[i][ACTION_LEFT] -= 0.1; R[i][ACTION_RIGHT] -= 0.1; } for (int i = 0; i < GRID_WIDTH; i++) { R[(GRID_HEIGHT - 1) * GRID_WIDTH + i][ACTION_DOWN] -= 0.7; R[(GRID_HEIGHT - 1) * GRID_WIDTH + i][ACTION_UP] -= 0.1; R[(GRID_HEIGHT - 1) * GRID_WIDTH + i][ACTION_LEFT] -= 0.1; R[(GRID_HEIGHT - 1) * GRID_WIDTH + i][ACTION_RIGHT] -= 0.1; } for (int i = 0; i < GRID_HEIGHT; i++) { R[i * GRID_WIDTH][ACTION_LEFT] -= 0.7; R[i * GRID_WIDTH][ACTION_DOWN] -= 0.1; R[i * GRID_WIDTH][ACTION_RIGHT] -= 0.1; R[i * GRID_WIDTH][ACTION_UP] -= 0.1; } for (int i = 0; i < GRID_HEIGHT; i++) { R[i * GRID_WIDTH + GRID_WIDTH - 1][ACTION_RIGHT] -= 0.7; R[i * GRID_WIDTH + GRID_WIDTH - 1][ACTION_DOWN] -= 0.1; R[i * GRID_WIDTH + GRID_WIDTH - 1][ACTION_LEFT] -= 0.1; R[i * GRID_WIDTH + GRID_WIDTH - 1][ACTION_UP] -= 0.1; } } void train(int r, double gamma) { g = gamma; int k = trainEpc; int kmost = trainEpc + r; for (; k < kmost; k++) { bool isBest = true; #if defined(DEBUG) cout << "trainEpc:" << trainEpc << endl; #endif int evalEpc = policyEaluation(GRID_AREA, gamma); #if defined(DEBUG) cout << "evalEpc:" << evalEpc << endl; #endif for (int s = 0; s < GRID_AREA; s++) { int row = s / GRID_WIDTH; int col = s - row * GRID_WIDTH; double svalue = -100; int action = ACTION_RIGHT; for (int act = 0; act < ACTION_NUM; act++) { double tmp = 0; for (int t = 0; t < ACTION_NUM; t++) { if (t == act) { tmp += 0.7 * compute(evalEpc, row, col, t); } else { tmp += 0.1 * compute(evalEpc, row, col, t); } } double newValue = R[s][act] + gamma * tmp; if (svalue < newValue) { action = act; svalue = newValue; } } Pi[k + 1][s] = action; if (Pi[k][s] != action) { isBest = false; } } if (isBest) { break; } trainEpc++; } } void reset() { memset(U, 0, sizeof(U)); memset(Pi, 0, sizeof(Pi)); trainEpc = 0; } double *getResult() { cout << "trainEpc" << trainEpc << endl; cout << "---------------------------------------------------------------------------------------------------------\n"; for (int i = 0; i < GRID_HEIGHT; i++) { for (int j = 0; j < GRID_WIDTH; j++) { int s = i * GRID_WIDTH + j; printf("%10s", directionChar[Pi[trainEpc][s]]); } cout << "\n"; } return U[policyEaluation(GRID_AREA, g)]; } }; void draw(double *data) { FILE *fp = fopen("data.txt", "w"); if (fp == NULL) { cerr << "文件夹打开失败\n"; exit(-1); } for (int i = 0; i < GRID_HEIGHT; i++) { for (int j = 0; j < GRID_WIDTH; j++) { int s = i * GRID_WIDTH + j; fprintf(fp, "%10.2lf", data[s]); } fprintf(fp, "\n"); } } int main() { VI vi; vi.train(100); double *data; //38轮收敛 cout << vi.getTrainEpc() << endl; vi.getResult(); vi.getResult(0); vi.getResult(1); vi.getResult(2); vi.getResult(3); vi.getResult(4); GaussSeidelVI gvi; gvi.train(100); //28轮收敛 cout << gvi.getTrainEpc() << endl; data = gvi.getResult(); draw(data); //仅5轮就收敛了。 PI pi; pi.train(99, 0.9); pi.getResult(); }
b408c305d58ca6c5a595263b1db89aa166481e74
c2cb548aaff4c9346bd859cd27ac79068d340d45
/MOG/distribuciones-ordenadas/distribuciones-ordenadas.cpp
0e6b51fe4949a40a458821f5c55d2310485788d2
[]
no_license
arnabxero/online-judges-problem-solutions
28997ab7e14bd1c2861b393e04b093c89f87cce9
506fe0c29742ceeb152f2698a30f7b32994a0e3e
refs/heads/master
2023-09-01T09:42:35.746179
2021-10-04T23:15:11
2021-10-04T23:15:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,150
cpp
distribuciones-ordenadas.cpp
// Problem name: B - Distribuciones Ordenadas // Problem link: https://matcomgrader.com/problem/9238/distribuciones-ordenadas/ // Submission link: https://matcomgrader.com/submission/120635/ #include <bits/stdc++.h> #define MOD (int)(1e9 + 7) #define mod(x) (((x) % MOD + MOD) % MOD) #define endl '\n' using namespace std; typedef long long ll; struct terna{ ll gcd, x, y; terna(ll gcd, ll x, ll y) : gcd(gcd), x(x), y(y){ } }; terna extGCD(ll a, ll b){ ll x = 0, y = 1, x2 = 1, y2 = 0, temp, q; while(b){ temp = b; q = a / b; b = a % b; a = temp; temp = x; x = x2 - q * x; x2 = temp; temp = y; y = y2 - q * y; y2 = temp; } return terna(a, x2, y2); } ll modInv(ll a){ return mod(extGCD(a, MOD).x); } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; ll num = 1, den = 1, ans; for(int i = 2 ; i <= n ; den = mod(den * i++)); for(int i = n ; i <= (n << 1) - 1 ; num = mod(num * i++)); ans = mod(num * modInv(den)); cout << mod(mod(2 * ans) - n) << endl; return 0; }
9eb1ee6ad2a1ca0615a0f3f1e2789e7cd17fdd49
16c2b8eae3103348a7a8a8addb08071d5a4e70e2
/view/ingredientpage.cpp
08d09eb6e783493f53d1f07d2c3e34730b076998
[ "MIT" ]
permissive
lcala99/MakeIThome
f1bae8497c03f34e142a677a4591fc4012de0619
dc8767391bb64c96e5374670d7ceb494050b081b
refs/heads/main
2023-07-31T13:41:38.559305
2021-09-21T14:22:54
2021-09-21T14:22:54
408,850,298
0
0
null
null
null
null
UTF-8
C++
false
false
2,487
cpp
ingredientpage.cpp
#include "ingredientpage.h" IngredientPage::IngredientPage(QWidget*parent,const Vettore<Ingrediente>& lista): QWidget(parent), ingr(lista){ mainLayout = new QVBoxLayout(this); cart = new QListWidget(this); addList(); connect(back, &QPushButton::clicked, this, &IngredientPage::showHomePage); connect(switchToCarrello, &QPushButton::clicked, this, &IngredientPage::showCarrelloPage); } void IngredientPage::addList(){ this->setMinimumSize(920,800); QLabel* title = new QLabel("Lista della spesa"); title->setFont(QFont("Verdana", 20)); back = new QPushButton(); switchToCarrello = new QPushButton(); QPixmap turnBackImg = QPixmap(":/icons/foto/home.png"); QPixmap SwitchImg = QPixmap(":/icons/foto/iconcart.png"); QWidget* header = new Header(back, title, switchToCarrello, turnBackImg, SwitchImg); for(Vettore<Ingrediente>::Iteratore it=ingr.begin(); it!=ingr.end(); it++){ QWidget* w= new QWidget; QHBoxLayout* oggettoLista = new QHBoxLayout(w); //nome ingrediente std::string aux = it->getNome(); QString* saveNome = new QString(aux.c_str()); QLabel* nome = new QLabel(*saveNome); nome->setStyleSheet("font-size: 24px;"); QLabel* quantityLabel = new QLabel("Quantità: "); quantityLabel->setStyleSheet("font-size: 24px;"); quantity = new QLabel(); quantity->setNum(int(it->getQuantita())); quantity->setStyleSheet("font-size: 24px;"); QLabel* unit = new QLabel(); if(it->IsLiquido()) unit->setText("ml"); else unit->setText("gr"); unit->setStyleSheet("font-size: 24px"); oggettoLista->addWidget(nome); oggettoLista->addWidget(quantityLabel); oggettoLista->addWidget(quantity); oggettoLista->addWidget(unit); oggettoLista->setAlignment(quantity, Qt::AlignCenter); oggettoLista->setAlignment(quantityLabel, Qt::AlignRight); oggettoLista->setAlignment(unit, Qt::AlignLeft); QListWidgetItem* item = new QListWidgetItem; item->setSizeHint(QSize(cart->sizeHint().width(),80)); cart->addItem(item); cart->setItemWidget(item, w); } mainLayout->addWidget(header); mainLayout->addWidget(cart); } void IngredientPage::setLista(Vettore<Ingrediente> v){ ingr=v; } void IngredientPage::showHomePage(){ emit toHomePage(); } void IngredientPage::showCarrelloPage(){ emit toCarrelloPage(); }
8cd703151a8b95089260ba6fa204c3d1934f760a
42948d207eb8e3f35c797840fec871056caa0503
/VertexChameleon/MayaPCH.cpp
d4e119274f99c5db7ae9b1f1d594644d1029d71c
[ "MIT" ]
permissive
friedererdmann/MayaPlugin-VertexChameleon
6edb0d08312163dc0392efb5cf6ebe75d0f27606
a0fe0781bc90564d172f440b5c2eca6677667c8a
refs/heads/master
2023-04-05T21:06:41.399867
2021-05-10T17:03:24
2021-05-10T17:03:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
502
cpp
MayaPCH.cpp
// // Vertex Chameleon Maya Plugin Source Code // Copyright (C) 2007-2014 RenderHeads Ltd. // // This source is available for distribution and/or modification // only under the terms of the MIT license. All rights reserved. // // The source is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // FITNESS FOR A PARTICULAR PURPOSE. See the MIT license // for more details. // #define MNoVersionString #include "MayaPCH.h"
0a72eb9866027be5936e4cf3239ef89b52e0fd08
5885fd1418db54cc4b699c809cd44e625f7e23fc
/codeforces/1515/i-lca.cpp
cba4dfd2d4be58eb49bf47118a03592f53c27484
[]
no_license
ehnryx/acm
c5f294a2e287a6d7003c61ee134696b2a11e9f3b
c706120236a3e55ba2aea10fb5c3daa5c1055118
refs/heads/master
2023-08-31T13:19:49.707328
2023-08-29T01:49:32
2023-08-29T01:49:32
131,941,068
2
0
null
null
null
null
UTF-8
C++
false
false
4,957
cpp
i-lca.cpp
#include <bits/stdc++.h> using namespace std; #define _USE_MATH_DEFINES %:include "data_structure/segment_tree.h" %:include "data_structure/fenwick_tree.h" //#define FILENAME sadcactus #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; template <typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; typedef long long ll; typedef long double ld; typedef complex<ld> pt; constexpr char nl = '\n'; constexpr ll INF = 0x3f3f3f3f; constexpr ll INFLL = 0x3f3f3f3f3f3f3f3f; constexpr ll MOD = 998244353; constexpr ld EPS = 1e-9L; random_device _rd; mt19937 rng(_rd()); const int L = 18; const int N = 1 << 18; struct Sum { ll value; Sum() = default; ll get() const { return value; } void put(ll v) { value += v; } void pull(const Sum& a, const Sum& b) { value = a.value + b.value; } bool contains(ll& cap) { if(value <= cap) { cap -= value; return false; } else { return true; } } static ll default_value() { return 0; } static ll merge(ll a, ll b) { return a + b; } }; struct Node { ll value, lazy; Node() = default; ll get() const { return value; } void put(ll v) { value += v; lazy += v; } void pull(const Node& a, const Node& b) { value = min(a.value, b.value); } void push(Node& a, Node& b) { if(lazy) { a.put(lazy); b.put(lazy); lazy = 0; } } bool contains(ll cap) { return value <= cap; } }; // double-check correctness // read limits carefully // characterize valid solutions int main() { cin.tie(0)->sync_with_stdio(0); cout << fixed << setprecision(10); #if defined(ONLINE_JUDGE) && defined(FILENAME) freopen(FILENAME ".in", "r", stdin); freopen(FILENAME ".out", "w", stdout); #endif int n, m; cin >> n >> m; vector<ll> a(n); vector<int> w(n), v(n); vector<tuple<int,int,int>> order; for(int i=0; i<n; i++) { cin >> a[i] >> w[i] >> v[i]; order.emplace_back(-v[i], w[i], i); } sort(begin(order), end(order)); vector<int> remap(n); for(int i=0; i<n; i++) { remap[get<2>(order[i])] = i; } // build trees vector values(L, segment_tree<Sum, ll>(n)); vector weights(L, segment_tree<Sum, ll>(n)); //vector values(L, fenwick_tree<ll>(n)); //vector weights(L, fenwick_tree<ll>(n)); vector equal(L, segment_tree<Node, ll>(n)); for(int i=0; i<n; i++) { // (v[i], w[i]) at remap[i] int id = remap[i]; ll weight = a[i] * w[i]; ll value = a[i] * v[i]; for(int j=0; j<L; j++) { if(w[i] < 1 << j) { values[j].update_point(id, value); weights[j].update_point(id, weight); //values[j].update(id, value); //weights[j].update(id, weight); equal[j].update(id, n-1, weight); } if(1 << j <= w[i] && w[i] < 1 << (j+1)) { equal[j].update(id, id, w[i] + (a[i] == 0 ? INFLL : 0)); } else { equal[j].update(id, id, INFLL); } } } function<void(int,int)> update = [&](int i, ll cnt) { int id = remap[i]; ll weight = cnt * w[i]; ll value = cnt * v[i]; for(int j=0; j<L; j++) { if(w[i] < 1 << j) { values[j].update_point(id, value); weights[j].update_point(id, weight); //values[j].update(id, value); //weights[j].update(id, weight); equal[j].update(id, n-1, weight); } if(1 << j <= w[i] && w[i] < 1 << (j+1)) { if(a[i] + cnt == 0) { equal[j].update(id, id, INFLL); } else if(a[i] == 0) { equal[j].update(id, id, -INFLL); } } } a[i] += cnt; }; // solver function<ll(int,ll,int)> solve = [&](int lvl, ll cap, int s) -> ll { if(lvl < 0 || s >= n) return 0; if(cap < 1 << lvl) return solve(lvl - 1, cap, s); ll prefix = weights[lvl].query(0, s - 1); int small = weights[lvl].search_left(s, n - 1, cap); //int small = weights[lvl].lower_bound(cap + prefix + 1); int big = equal[lvl].search_left(s, n - 1, cap + prefix); if(small == n && big == n) { // take everything return values[lvl].query(s, n - 1); } else if(big < small) { // take the big one int j = get<2>(order[big]); cap -= weights[lvl].query(s, big) + w[j]; return values[lvl].query(s, big) + v[j] + solve(lvl - 1, cap, big + 1); } else { // take the small ones int j = get<2>(order[small]); cap -= weights[lvl].query(s, small - 1); ll take = cap / w[j]; return values[lvl].query(s, small - 1) + take * v[j] + solve(lvl - 1, cap - take * w[j], small + 1); } }; for(int i=0; i<m; i++) { int t; cin >> t; if(t == 1) { int k, d; cin >> k >> d; update(d - 1, k); } else if(t == 2) { int k, d; cin >> k >> d; update(d - 1, -k); } else { ll cap; cin >> cap; cout << solve(L - 1, cap, 0) << nl; } } return 0; }
32097eb51bbb293d503598266a1dde2dadca9b8e
2c255e8f64d987a609ef6bb175ba60633bdff81e
/game/region.h
652d647aef48f74d884b65386ce1c39e8d62e738
[]
no_license
agrum/ksir
5b3ed2d4157eef1519cd109f330bc06cf4373337
6e4e2b2b789a55afc998ddaec452524c2b507ee3
refs/heads/master
2016-09-06T17:24:01.463791
2013-10-27T05:32:05
2013-10-27T05:32:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
454
h
region.h
#ifndef REGION_H #define REGION_H #include <QString> #include <QList> namespace ksir { class Territory; class Region { public: Region(const QString& p_name); const QList<const Territory*>& territoryList(); bool addTerritory(const Territory* p_territory); unsigned int reinforcement(); private: QString m_name; unsigned int m_reinforcement; bool m_reinforcementComputed; QList<const Territory*> m_territoryList; }; } #endif // REGION_H
e920d46ce294a817ad84d39de7e43176748300ac
2c78de0b151238b1c0c26e6a4d1a36c7fa09268c
/MDProcess/MDAFormat/Executor.cpp
4e673482c8bb267d135dc09ed07f314645b1f6de
[]
no_license
bravesoftdz/realwork
05a3b308cef59bed8a9efda4212849c391b4b267
19b446ce8ad2adf82ab8ce7988bc003221accad2
refs/heads/master
2021-06-07T23:57:22.429896
2016-11-01T18:30:21
2016-11-01T18:30:21
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
2,701
cpp
Executor.cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Модуль: "w:/MDProcess/MDAFormat/Executor.cpp" // генератор файлов реализации C++ (.cpp) // Generated from UML model, root element: <<LibExecutor::Class>> MDProcess::MDAFormat::LibSupport::Executor // // пока нет документации // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "shared/Core/sys/std_inc.h" #include "ace/Signal.h" #include "MDProcess/MDAFormat/Executor.h" // by <<uses>> dependencies #include "MDProcess/MDAFormat/ModelPartDef/ModelPart.h" #include "MDProcess/MDAFormat/AdditionalPartDef/AdditionalPart.h" #include "MDProcess/MDAFormat/RootFile/ModelRoot.h" namespace MDAFormat { ////////////////////////////////////////////////////////////////////////////////////////// // main execute method void Executor::execute_ () { try { ACE_Sig_Action ((ACE_SignalHandler)Executor::handle_control, SIGTERM); ACE_Sig_Action ((ACE_SignalHandler)Executor::handle_control, SIGINT); ACE_Sig_Action ((ACE_SignalHandler)Executor::handle_control, SIGQUIT); //#UC START# *48ABDF5E022E* /*Core::Box<ModelPartDef::RootPackage> uml_package; try { Core::GDS::StopWatch ex ("ModelPartDef parse"); ModelPartDef::ModelPart parser ("W:/example.uml"); uml_package = parser.root_package (); std::ofstream out ("W:/example_out.uml", std::ios_base::out); out << *uml_package; } catch (antlr::ANTLRException& ex) { LOG_E (("%s", ex.toString ())); } Core::Box<AdditionalPartDef::Package> umla_package; try { Core::GDS::StopWatch ex ("AdditionalPartDef parse"); AdditionalPartDef::AdditionalPart parser ("W:/example.umla"); umla_package = parser.package (); std::ofstream out ("W:/example_out.umla", std::ios_base::out); out << *umla_package; } catch (antlr::ANTLRException& ex) { LOG_E (("%s", ex.toString ())); }*/ //#UC END# *48ABDF5E022E* ExecutorBase::execute_ (); return; } CATCH_AND_LOG ("in execute") this->set_current_status(Core::Root::ES_ERROR); } void Executor::finalize () { //#UC START# *48ABDF5E022E_FINI* //#UC END# *48ABDF5E022E_FINI* } void Executor::handle_control (int sig) { //#UC START# *48ABDF5E022E_HANDLE_CONTROl* //TODO: write your code for handle Ctrl-C //#UC END# *48ABDF5E022E_HANDLE_CONTROl* } } // namespace MDAFormat ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////