text
stringlengths
8
6.88M
#ifndef RAYTRACING_HPP #define RAYTRACING_HPP #include "main.hpp" using namespace std; RT_Vec3 ray_trace(const Ray& ray, int left) { // background RT_Vec3 color(0.0f, 0.0f, 0.0f); double distance = MAX_DISTANCE; double shade = 1.0f; int IntersectionObject = -1; INTERSECTION_TYPE tmp; for (int k = 0; k < object_list.size(); k++) { RT_Object* obj = object_list.at(k); if ((tmp = obj->isIntersected(ray, distance)) != MISS) IntersectionObject = k; } if (IntersectionObject == -1) return color; // Now there is a intersection point RT_Object* obj = object_list.at(IntersectionObject); RT_Vec3 point = ray.get_point(distance); RT_Vec3 tmpColor; RT_Vec3 objMaterial = obj->getKa(); color = RT_Vec3(globalLight.x * objMaterial.x, globalLight.y * objMaterial.y, globalLight.z * objMaterial.z); for (int k = 0; k < light_list.size(); k++) { LightSource* ls = light_list.at(k); bool flag = true; RT_Vec3 curr_objRayDirection = \ ls->get_light_dir(point) * (-1.0f); RT_Vec3 tracePoint = point; while (flag && shade >= EPSILON) { flag = false; Ray curr_objRay(tracePoint + curr_objRayDirection * EPSILON, \ curr_objRayDirection); int tmpIntersectionObject = -1; distance = MAX_DISTANCE; for (int t = 0; t < object_list.size(); t++) { RT_Object* obj = object_list.at(t); if ((tmp = obj->isIntersected(curr_objRay, distance)) != MISS) tmpIntersectionObject = t; } if (tmpIntersectionObject != -1) { shade *= object_list.at(\ tmpIntersectionObject)->getTransparency(); tracePoint=curr_objRay.get_point(distance); flag = true; } } if (shade < EPSILON) shade = 0.0f; tmpColor = ls->color_calc(obj, point, cam_position); tmpColor *= shade; color += tmpColor; } if (left == 0) return color * (1-obj->getReflectivity() - \ obj->getTransparency()); RT_Vec3 normal = obj->getNormal(point); normal.normalize(); RT_Vec3 rd = ray.get_direction(); RT_Vec3 transparentRayDirection = rd; Ray transparentRay(point + transparentRayDirection * EPSILON, \ transparentRayDirection); RT_Vec3 transparentColor = ray_trace(transparentRay, left - 1); // Reflect RT_Vec3 reflectRayDirection = rd-normal * (rd * normal) * 2.0f; Ray reflectRay(point + reflectRayDirection * EPSILON, \ reflectRayDirection); RT_Vec3 reflectColor = ray_trace(reflectRay, left - 1); color = color * (1-obj->getReflectivity() - obj->getTransparency()) + \ RT_Vec3(objMaterial.x * reflectColor.x, \ objMaterial.y * reflectColor.y, \ objMaterial.z*reflectColor.z) * obj->getReflectivity() + \ RT_Vec3(objMaterial.x * transparentColor.x, \ objMaterial.y * transparentColor.y, \ objMaterial.z * transparentColor.z) * \ obj->getTransparency(); return color; } #endif
/* * Stopping Times * Copyright (C) Leonardo Marchetti 2011 <leonardomarchetti@gmail.com> */ #include "tester.h" #include <iostream> #include <cstdlib> #include <cstdio> #include "test-de-solver.h" #include "test-maximizer.h" #include "logger.h" using namespace StoppingTimes; using namespace StoppingTimes::Testing; void createTests(Tester *tester); int main(int argc, char* argv[]){ if(argc>1){ Tester *tester = new Tester(); createTests(tester); tester->loadAll(argv[1]); Logger *logger; if(argc>2) logger = new Logger(argv[2]); else logger = new Logger(); tester->runAll(logger); delete(logger); delete(tester); } return 0; } void createTests(Tester *tester){ int i=0; tester->add(new TestDESolver(++i)); tester->add(new TestDESolver(++i)); tester->add(new TestMaximizer(++i)); tester->add(new TestMaximizer(++i)); tester->add(new TestMaximizer(++i)); }
#include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <ctime> #include <memory.h> #include <cmath> #include <string> #include <cstring> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> #include <complex> #include <cassert> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; const int N = 111111; int p[N]; vector<int> g[N]; LL f[N][2]; int w[N]; const int MOD = 1000000007; void dfs(int x) { w[x] = 1; for (int i = 0; i < g[i].size(); ++i) { dfs(g[x][i]); w[x] += w[g[x][i]]; } LL ansp1 = 0; LL ansp2 = 0; f[x][0] = 1; f[x][1] = 0; for (int i = 0; i < g[i].size(); ++i) { int y = g[x][i]; for (int j = 0; j < 2; ++j) { LL fp0 = f[x][0], fp1 = f[x][1]; ansp0 += (fp0 * f[y][0] + fp1 * f[y][1] + fp1 * f[y][1]) % MOD; ansp1 += (fp0 * f[y][0] + fp1 * f[y][1] + fp1 * f[y][1]) % MOD; f[x][0] = (fp0 * f[y][0] + fp1 * f[y][1] + fp0) % MOD; f[x][1] = (fp1 * f[y][0] + fp0 * f[y][1] + fp1) % MOD; } } } int main() { freopen(".in", "r", stdin); freopen(".out", "w", stdout); int n; scanf("%d", &n); for (int i = 2; i <= n; ++i) { scanf("%d", &p[i]); g[p[i]].push_back(i); } dfs(1); cout << f[1] << endl; return 0; }
/*Write a function to determine the number of bits required to convert integer A to integer B*/ #include <iostream> using namespace std; int bitsToChange(int A, int B){ int n = A & B; int sum = 0; int max= A>B? A : B; for(int i=0; max!=0; i++){ sum +=((n>>i)+1)%2; max>>=1; } return sum; } int theirBitsToChange(int A, int B){ int sum=0; for(int c= A^B; c!=0; c>>1) sum += c&1; return sum; } int main(){ int from = 31; int to = 14; cout<<"Bits to change from "<<from<<" to "<<to<<" given by my function: "<<bitsToChange(from, to)<<endl; cout<<"Bits to change from "<<from<<" to "<<to<<" given by the book's function: "<<bitsToChange(from, to)<<endl; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- ** ** Copyright (C) 2000-2008 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Yngve Pettersen ** */ #include "core/pch.h" #if defined(_NATIVE_SSL_SUPPORT_) #include "modules/libssl/sslbase.h" #include "modules/libssl/protocol/sslbaserec.h" #include "modules/libssl/base/sslciphspec.h" #include "modules/libssl/protocol/sslmac.h" #include "modules/libssl/methods/sslcipher.h" #include "modules/libssl/sslrand.h" #include "modules/libssl/debug/tstdump2.h" #include "modules/libcrypto/include/OpRandomGenerator.h" #ifdef _DEBUG #define _SSL_DEBUG #ifdef _SSL_DEBUG #ifdef YNP_WORK #define TST_DUMP #endif #endif #endif SSL_Record_Base *SSL_Record_Base::Encrypt(SSL_CipherSpec *cipher) { uint32 blocksize; if(cipher == NULL || (blocksize = cipher->Method->InputBlockSize()) == 0) { RaiseAlert(SSL_Fatal, SSL_InternalError); return NULL; } OpStackAutoPtr<SSL_Record_Base> encrypt_target(InitEncryptTarget()); if(ErrorRaisedFlag) return NULL; LoadAndWritableList crypt_source; SSL_secure_varvector32 IV; SSL_secure_varvector16 payload_data; SSL_secure_varvector16 MAC_data; SSL_secure_varvector16 pad_data; crypt_source.ForwardTo(this); if(encrypt_target->IV_field && blocksize > 1) { crypt_source.AddItem(&IV); // Keep the IV from the previous record (option 2b from RFC 4346) IV.SetEnableRecord(TRUE); IV.FixedLoadLength(TRUE); SSL_RND(IV, blocksize); } crypt_source.AddItem(&payload_data); payload_data.SetExternal(GetDirect()); payload_data.Resize(GetLength()); payload_data.FixedLoadLength(TRUE); crypt_source.AddItem(&MAC_data); MAC_data.Resize(cipher->MAC->Size()); MAC_data.FixedLoadLength(TRUE); if(ErrorRaisedFlag) return NULL; if(blocksize > 1) { uint16 plen = payload_data.GetLength() + MAC_data.GetLength(); uint16 elen = cipher->Method->Calc_BufferSize(plen); uint16 paddinglength = (elen-plen); if(paddinglength == 0) paddinglength = blocksize; uint8 pad_char = (uint8) (paddinglength-1); crypt_source.AddItem(&pad_data); pad_data.Resize(paddinglength); pad_data.Blank(pad_char); pad_data.FixedLoadLength(TRUE); } { SSL_ContentType r_type; SSL_ProtocolVersion r_ver; r_type = GetType(); r_ver = GetVersion(); encrypt_target->SetType(r_type); encrypt_target->SetVersion(r_ver); if(MAC_data.GetLength()) { SSL_TRAP_AND_RAISE_ERROR_THIS(cipher->MAC->CalculateRecordMAC_L(cipher->Sequence_number, r_ver, r_type, payload_data,pad_data.GetDirect(), pad_data.GetLength(), MAC_data)); } } SSL_secure_varvector16 tempdata; SSL_TRAP_AND_RAISE_ERROR_THIS(crypt_source.WriteRecordL(&tempdata)); if(ErrorRaisedFlag) return NULL; cipher->Method->EncryptVector(tempdata, *encrypt_target); cipher->Sequence_number++; if(ErrorRaisedFlag || cipher->Method->Error()) return NULL; return encrypt_target.release(); } SSL_Record_Base *SSL_Record_Base::Decrypt(SSL_CipherSpec *cipher) { uint16 blocksize; if(cipher == NULL || (blocksize = cipher->Method->InputBlockSize()) == 0) { RaiseAlert(SSL_Fatal, SSL_InternalError); return NULL; } SSL_secure_varvector16 tempdata; tempdata.ForwardTo(this); UINT mac_hash_size = cipher->MAC->Size(); // Counter measure for paper "Lucky Thirteen: Breaking the TLS and DTLS Record Protocols" // Sanity check the cipher text length. // Lucky Thirteen step 1 if(blocksize > 1) { UINT mimmimum_cipher_length = MAX(blocksize, mac_hash_size + 1); if (IV_field) mimmimum_cipher_length += blocksize; if (GetLength() < mimmimum_cipher_length) { RaiseAlert(SSL_Fatal, SSL_Decryption_Failed); return NULL; } } cipher->Method->DecryptVector(*this, tempdata); if(ErrorRaisedFlag || cipher->Method->Error()) return NULL; #ifdef TST_DUMP DumpTofile(tempdata, tempdata.GetLength() ,"Decrypt outputdata (includes padding): ","sslcrypt.txt"); #endif OP_MEMORY_VAR uint16 plainlength = tempdata.GetLength(); // The padding length byte as given in the stream UINT8 padlen = 0; OP_MEMORY_VAR uint16 paddinglength = 0; const byte * OP_MEMORY_VAR source = tempdata.GetDirect(); { BOOL length_OK = TRUE; if(blocksize == 1) { if(plainlength != GetLength()) length_OK = FALSE; } else// if(blocksize != 1) { if(plainlength % blocksize != 0) length_OK = FALSE; else if(IV_field) { if(plainlength < blocksize) length_OK = FALSE; } } if(!length_OK) { RaiseAlert(SSL_Fatal, SSL_Decryption_Failed); return NULL; } } if(IV_field && blocksize > 1) { plainlength -= blocksize; source += blocksize; } int original_plainlength = plainlength; OpStackAutoPtr<SSL_Record_Base> decrypt_target(InitDecryptTarget(cipher)); if(ErrorRaisedFlag) return NULL; OP_MEMORY_VAR BOOL padding_failure = FALSE; if(blocksize > 1) { if(plainlength == 0) { RaiseAlert(SSL_Fatal, SSL_Illegal_Parameter); return NULL; } padlen = source[plainlength-1]; paddinglength = padlen + 1; // Lucky Thirteen counter measure step 3 if (mac_hash_size + padlen + 1 > plainlength) { for(UINT16 i = 0;i < 256; i++) { // Dummy check, to avoid timing differences. if(source[i] != padlen ) //dummy check padding_failure = TRUE; } padding_failure = TRUE; paddinglength = 0; } else if(version >= SSL_ProtocolVersion(3,2) && paddinglength >0) { // Lucky Thirteen counter measure step 4 uint16 i; for(i= plainlength - paddinglength;i<plainlength;i++) { if(source[i] != padlen ) { padding_failure = TRUE; paddinglength = 0; // Pretending the padding was OK, to counter timing attacks against the MAC. } } BOOL dummy = FALSE; // Dummy check, to avoid timing differences. for(UINT16 i= 0; i < 256 - padlen - 1; i++) { if(source[i] != padlen ) // dummy check padding_failure = dummy; } } plainlength -= paddinglength; } SSL_secure_varvector16 MAC_data_master; SSL_secure_varvector16 MAC_data_calculated; ForwardToThis(MAC_data_master,MAC_data_calculated); decrypt_target->ForwardTo(this); uint16 MAC_size = cipher->MAC->Size(); uint16 read_MAC_size = cipher->MAC->Size(); if(plainlength<MAC_size) { read_MAC_size = 0; } uint16 payload_len = plainlength - read_MAC_size; source = decrypt_target->Set(source, payload_len); #ifdef TST_DUMP DumpTofile(*decrypt_target, decrypt_target->GetLength() ,"Decrypt outputdata (without MAC and padding): ","sslcrypt.txt"); #endif source = MAC_data_master.Set(source, read_MAC_size); #ifdef TST_DUMP DumpTofile(MAC_data_master, MAC_size,"Decryptstep received MAC","sslcrypt.txt"); #endif if(ErrorRaisedFlag) return NULL; { SSL_ContentType r_type; SSL_ProtocolVersion r_ver; r_type = GetType(); r_ver = GetVersion(); decrypt_target->SetType(r_type); decrypt_target->SetVersion(r_ver); if(MAC_size) { SSL_TRAP_AND_RAISE_ERROR_THIS(cipher->MAC->CalculateRecordMAC_L(cipher->Sequence_number, r_ver, r_type, *decrypt_target.get(), source, paddinglength, MAC_data_calculated)); if(blocksize > 1) { OP_ASSERT(payload_len == original_plainlength - padlen - 1 - read_MAC_size); // Extra mac check done for Lucky Thirteen counter measure step 3, 4 and 5 // Extra dummy operations to avoid timing attacks on the padding. int L1 = 13 + original_plainlength - MAC_size; int L2 = 13 + original_plainlength - padlen - 1 - MAC_size; int number_of_extra_dummy_mac_compressions = (int)op_ceil((L1 - 55)/64.) - (int)op_ceil((L2 - 55)/64.); OP_ASSERT(L1 >= 0 && L2 >= 0 && number_of_extra_dummy_mac_compressions >= 0); // Add some random noise on top. number_of_extra_dummy_mac_compressions += g_libcrypto_random_generator->GetUint8() & 15; for (int i = 0; i < number_of_extra_dummy_mac_compressions; i++) cipher->MAC->CalculateHash(source, 1); } RaiseAlert(cipher->MAC); if(ErrorRaisedFlag) return NULL; if(plainlength<MAC_size) { RaiseAlert(SSL_Fatal, SSL_Illegal_Parameter); return NULL; } #ifdef TST_DUMP DumpTofile(MAC_data_calculated, MAC_size,"Decryptstep calculated MAC : ","sslcrypt.txt"); DumpTofile(MAC_data_master, MAC_size,"Decryptstep received MAC","sslcrypt.txt"); #endif OP_ASSERT(MAC_data_calculated.GetLength() == MAC_data_master.GetLength()); BOOL mac_check_success = (MAC_data_calculated.GetLength() == MAC_data_master.GetLength()); // Constant time mac check int mac_check_size = MIN(MAC_data_calculated.GetLength(), MAC_data_master.GetLength()); for (int j = 0; j < mac_check_size; j++) { if (MAC_data_calculated.GetDirect()[j] != MAC_data_master.GetDirect()[j]) mac_check_success = FALSE; } if (padding_failure || !mac_check_success) decrypt_target->RaiseAlert(SSL_Fatal, SSL_Bad_Record_MAC); } } cipher->Sequence_number++; if(ErrorRaisedFlag) return NULL; return decrypt_target.release(); } #endif
#include<bits/stdc++.h> using namespace std; int f[50]; map<int,int> mp; int main(){ f[0]=2; f[1]=3; mp[2]=1; mp[3]=1; for(int i=2;i<50;i++){ f[i]=f[i-1]+f[i-2]; mp[f[i]]=1; } int n; while(scanf("%d",&n)!=EOF&&n){ if(mp[n]==1) printf("Second win\n"); else printf("First win\n"); } return 0; }
/* =========================================================================== Copyright (C) 2017 waYne (CAM) =========================================================================== */ #pragma once #ifndef ELYSIUM_DATA_MODEL_ENTITY #define ELYSIUM_DATA_MODEL_ENTITY #ifndef ELYSIUM_CORE_OBJECT #include "../../../Core/01-Shared/Elysium.Core/Object.hpp" #endif #ifndef ELYSIUM_DATA_DESCRIPTION_ENTITYDESCRIPTOR #include "EntityDescriptor.hpp" #endif #ifndef ELYSIUM_DATA_MODEL_COMPONENT #include "Component.hpp" #endif namespace Elysium { namespace Data { namespace Model { class EXPORT Entity : public Elysium::Core::Object { public: ~Entity(); private: Entity(Elysium::Data::Description::EntityDescriptor* EntityDescriptor); Elysium::Data::Description::EntityDescriptor* _EntityDescriptor; std::vector<Component*> _Components; }; } } } #endif
#pragma once #include <iberbar/Gui/Element/BlendColor.h> #include <iberbar/Gui/RenderElement.h> namespace iberbar { namespace Renderer { class CFont; } namespace Gui { class __iberbarGuiApi__ CElementStateLabel : public CRenderElement { public: CElementStateLabel( void ); ~CElementStateLabel(); protected: CElementStateLabel( const CElementStateLabel& element ); public: virtual CElementStateLabel* Clone() const override { return new CElementStateLabel( *this ); } virtual void Refresh() override; virtual void Update( float nElapsedTime ) override; virtual void Render() override; public: void SetFont( Renderer::CFont* pFont ); void SetColor( int state, const CColor4B& color ) { m_BlendColor.SetColor( state, color ); } void SetTextA( const char* strText ); void SetTextW( const wchar_t* strText ); void SetTextAlignHorizental( UAlignHorizental nAlign ) { m_nAlignHorizental = nAlign; } void SetTextAlignVertical( UAlignVertical nAlign ) { m_nAlignVertical = nAlign; } protected: Renderer::CFont* m_pFont; float m_BlendColorRate; UAlignHorizental m_nAlignHorizental; UAlignVertical m_nAlignVertical; std::wstring m_strText; BlendColor m_BlendColor; }; IBERBAR_UNKNOWN_PTR_DECLARE( CElementStateLabel ); } }
// // Created by roy on 12/13/18. // #ifndef PROJECTPART1_COMMAND_H #define PROJECTPART1_COMMAND_H #include <string> using namespace std; /** * Interface of executable commands. */ class Command { public: virtual int execute() = 0; }; #endif //PROJECTPART1_COMMAND_H
#include "transformcomponent.h" namespace sge { namespace entity { namespace component { TransformComponent::TransformComponent(const math::mat4& transform) : transform(transform) { } } } }
#include <chuffed/globals/dag.h> #include <iostream> using namespace std; DAGPropagator::DAGPropagator(int _r, vec<BoolView>& _vs, vec<BoolView>& _es, vec<vec<edge_id> >& _in, vec<vec<edge_id> >& _out, vec<vec<int> >& _en) : DReachabilityPropagator(_r, _vs, _es, _in, _out, _en) { if (!getNodeVar(get_root_idx()).isFixed()) { getNodeVar(get_root_idx()).setVal(true); } // build the Tint array reachability = new Tint*[nbNodes()]; int tints = nbNodes() / sizeof(int); tints += (nbNodes() % sizeof(int) == 0) ? 0 : 1; tints = nbNodes(); for (int i = 0; i < nbNodes(); i++) { reachability[i] = new Tint[tints]; for (int j = 0; j < tints; j++) { reachability[i][j] = 0; } // reachability[i][i/sizeof(int)] |= (1 << sizeof(int)-(i % sizeof(int))); reachability[i][i] = 1; } succs = vector<TrailedSuccList>(); preds = vector<TrailedPredList>(); for (int i = 0; i < nbNodes(); i++) { succs.emplace_back(nbNodes()); preds.emplace_back(nbNodes()); } } DAGPropagator::~DAGPropagator() { for (int i = 0; i < nbNodes(); i++) { delete[] reachability[i]; } delete[] reachability; } void DAGPropagator::connectTo(int source, int dest) { /* for (int i = 0; i < nbNodes(); i++) { if (reachable(i,source)) { for (int j = 0; j < nbNodes(); j++) reachability[i][j] |= reachability[dest][j]; } reachability[source][i] |= reachability[dest][i]; }*/ if (succs[source].get(dest)) { return; } std::pair<node_id, node_id> dd(dest, dest); succs[source].add(dd); preds[dest].add(source); std::pair<int, int> d_ptc(-1, -1); TrailedPredList::const_iterator it_p; for (it_p = preds[source].begin(); it_p != preds[source].end(); ++it_p) { succs[*it_p].get(source, &d_ptc); // d_ptc == how to go from p to source assert(d_ptc.second != -1); d_ptc.first = dest; // d_ptc == go from p to dest the same... succs[*it_p].add(d_ptc); // ...way you go from p tou source preds[dest].add(*it_p); // p preceeds dest } TrailedSuccList::const_iterator it_s; for (it_s = succs[dest].begin(); it_s != succs[dest].end(); ++it_s) { int s = (*it_s).first; std::pair<int, int> s_to_d(s, dest); succs[source].add(s_to_d); // go from source to s through dest preds[s].add(source); // sorce preceeds s for (it_p = preds[source].begin(); it_p != preds[source].end(); ++it_p) { succs[*it_p].get(source, &d_ptc); // d_ptc == how to go from p to source assert(d_ptc.second != -1); d_ptc.first = s; // d_ptc == go from p to s the same... succs[*it_p].add(d_ptc); // ...way you go from p to source preds[s].add(*it_p); // p preceeds s } } } bool DAGPropagator::propagateNewEdge(int e) { if (!DReachabilityPropagator::propagateNewEdge(e)) { return false; } if (!check_cycle(e)) { return false; } TrailedSuccList::const_iterator succ_taile = succs[getTail(e)].end(); connectTo(getTail(e), getHead(e)); processed_e[e] = true; // Only checking the new ones for (; succ_taile != succs[getTail(e)].end(); succ_taile++) { int n = (*succ_taile).first; for (int i : ou[n]) { prevent_cycle(i); } } /* //Check all reachable for (int n = 0; n < nbNodes(); n++) { if (reachable(n,getTail(e))) { for (int i = 0; i < in[n].size(); i++) { assert(!prevent_cycle(in[n][i])); //Assert because already cehcked before } } } */ /* cout <<"Start "<<e<<endl; for (int i = 0; i < nbNodes(); i++) { for (int j = 0; j < nbNodes(); j++) { cout << reachability[i][j]<<","; } cout <<endl; }*/ return true; } bool DAGPropagator::propagateNewNode(int n) { if (!DReachabilityPropagator::propagateNewNode(n)) { return false; } for (int i : in[n]) { prevent_cycle(i); } for (int i : ou[n]) { prevent_cycle(i); } processed_n[n] = true; return true; } void DAGPropagator::findPathFromTo(int u, int v, vec<Lit>& path) { assert(u != v); // 1-edge paths: int e = findEdge(u, v); if (e != -1 && getEdgeVar(e).isFixed() && getEdgeVar(e).isTrue()) { path.push(getEdgeVar(e).getValLit()); return; } vec<Lit> path2; if (path.size() == 1) { path2.push(); } int current = u; while (current != v) { std::pair<int, int> pair; bool ok = succs[current].get(v, &pair); assert(ok); edge_id e = findEdge(current, pair.second); assert(e != -1); assert(getEdgeVar(e).isFixed()); assert(getEdgeVar(e).isTrue()); path.push(getEdgeVar(e).getValLit()); current = pair.second; } // Longer paths: /* bool found_v = false; stack<node_id> s; s.push(u); vector<bool> vis = vector<bool>(nbNodes(), false); vector<int> parent = vector<int>(nbNodes(), -1); parent[u] = u; while(!s.empty()) { int curr = s.top(); s.pop(); vis[curr] = true; for (int i = 0; i < ou[curr].size(); i++) { int e = ou[curr][i]; if (!getEdgeVar(e).isFixed() || getEdgeVar(e).isFalse()) continue; int o = getHead(e); if (!vis[o]) { s.push(o); parent[o] = curr; if (o == v) { found_v = true; break; } } } if (found_v) break; assert(!found_v); } assert(parent[v] != -1); assert(found_v); int curr = v; while (curr != u) { int e = findEdge(parent[curr],curr); assert(e != -1); assert(getEdgeVar(e).isFixed() && getEdgeVar(e).isTrue()); //cout <<e<<" "; path2.push(getEdgeVar(e).getValLit()); curr = parent[curr]; } assert(path.size() == path2.size()); */ } bool DAGPropagator::check_cycle(int e) { if (reachable(getHead(e), getTail(e))) { if (so.lazy) { /*cout <<"Edges in: "; for (int i = 0; i < nbEdges(); i++) { if(getEdgeVar(i).isFixed() && getEdgeVar(i).isTrue()) cout <<i<<" "; } cout <<endl;*/ vec<Lit> psfail; // cout <<"Path: "; findPathFromTo(getHead(e), getTail(e), psfail); psfail.push(getEdgeVar(e).getValLit()); // cout <<endl; assert(psfail.size() > 0); Clause* expl = Clause_new(psfail); expl->temp_expl = 1; sat.rtrail.last().push(expl); sat.confl = expl; } return false; } return true; } bool DAGPropagator::prevent_cycle(int e) { if (!getEdgeVar(e).isFixed()) { if (reachable(getHead(e), getTail(e))) { Clause* r = nullptr; if (so.lazy) { vec<Lit> ps; ps.push(); findPathFromTo(getHead(e), getTail(e), ps); r = Reason_new(ps); } getEdgeVar(e).setVal(false, r); return true; } } return false; } bool DAGPropagator::propagate() { processed_e = vector<bool>(nbEdges(), false); processed_n = vector<bool>(nbNodes(), false); if (!DReachabilityPropagator::propagate()) { return false; } set<int>::iterator it; for (it = new_edge.begin(); it != new_edge.end(); ++it) { if (!processed_e[*it]) { if (!propagateNewEdge(*it)) { return false; } } } for (it = new_node.begin(); it != new_node.end(); ++it) { if (!processed_n[*it]) { if (!propagateNewNode(*it)) { return false; } } } return true; } bool DAGPropagator::checkFinalSatisfied() { if (!DReachabilityPropagator::checkFinalSatisfied()) { return false; } vector<int> v = vector<int>(nbNodes(), 0); assert(check_correctness(get_root_idx(), v)); return check_correctness(get_root_idx(), v); } bool DAGPropagator::check_correctness(int r, vector<int>& v) { v[r] = -1; // cout <<"Visiting "<<r<<endl; for (int e : ou[r]) { if (getEdgeVar(e).isFixed() && getEdgeVar(e).isTrue()) { int hd = getHead(e); assert(hd != r); if (v[hd] == 0) { if (!check_correctness(hd, v)) { return false; } } else if (v[hd] == -1) { // cout <<"I saw "<<getHead(ou[r][i])<<" "<<v[ou[r][i]]<<endl; return false; } } } v[r] = 1; return true; } void dag(int r, vec<BoolView>& _vs, vec<BoolView>& _es, vec<vec<edge_id> >& _in, vec<vec<edge_id> >& _out, vec<vec<int> >& _en) { auto* dag = new DAGPropagator(r, _vs, _es, _in, _out, _en); // if (so.check_prop) // engine.propagators.push(dag); }
#include <iostream> #include <vector> using namespace std; int n, t, count; long long temp; vector<pair<long long, long long>> seq; bool visited[1000001]; void genPrime() { int prev; for (long long i = 2; i * i <= 1000001; i++) { if (!visited[i]) { for (long long j = i * i; j <= 1000001; j += i) visited[j] = true; } } count = 0; int inc = 1; while (count < 50001) { prev = 2; for (long long i = inc; i < 1000001; i += inc) if (!visited[i]) { temp = prev * i; if (temp <= 1000000000) { seq.push_back(make_pair(temp, i)); prev = i; count++; } else break; } inc++; // cout << count << endl; } } int main() { const clock_t begin_time = clock(); genPrime(); vector<pair<long long, long long>>::iterator prm; cin >> t; for (int i = 0; i < t; i++) { cin >> n; count = 0; for (prm = seq.begin() + 1; count != n - 1; count++, prm++) cout << prm->first << " "; cout << 2 * (--prm)->second << endl; } std::cout << float( clock () - begin_time ) / CLOCKS_PER_SEC; }
#include "AboutWindow.h" #include "ui_AboutWindow.h" AboutWindow::AboutWindow(QWidget *parent) : QDialog(parent), ui(new Ui::AboutWindow) { ui->setupUi(this); QString d = __DATE__; d.append(" "); d.append(__TIME__); this->ui->compilationLabel->setText(d); } AboutWindow::~AboutWindow() { delete ui; }
#include <bits/stdc++.h> using namespace std; #define For(x) for(int i = 0; i < x; i++) #define For2(x) for(int j = 0; j < x; j++) #define For3(x) for(int k = 0; k < x; k++) #define Forv(vector) for(auto& i : vector) #define Forv2(vector) for(auto& j : vector) #define show(vector) for(auto& abcd : vector){cout<<abcd<<"\n";} #define pb push_back typedef long long ll; typedef vector<int> vi; typedef pair<int, int> pi; ofstream fout ("feast.out"); ifstream fin ("feast.in"); int main(){ ll t,a,b; fin>>t>>a>>b; bool dp[t+1][2]; memset(dp,false,sizeof(dp)); dp[0][0] = true; dp[0][1] = true; For(t+1){ if(dp[i][0]){ if(i+a < t+1){ dp[i+a][0] = true; ll x = (i+a)/2; ll in = trunc(x); dp[in][1] = true; } if(i+b < t+1){ dp[i+b][0] = true; ll x = (i+b)/2; ll in = trunc(x); dp[in][1] = true; } } } For(t+1){ if(dp[i][1]){ if(i+a < t+1){ dp[i+a][1] = true; } if(i+b < t+1){ dp[i+b][1] = true; } } } ll maxm = 0; For(t+1){ if(dp[i][0] || dp[i][1]){ maxm = i; } } For(t+1){ cout<<dp[i][0]<<' '<<dp[i][1]<<'\n'; } fout<<maxm<<'\n'; }
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <queue> #include <set> using namespace std; struct ListNode{ int val; ListNode* next; ListNode(int x):val(x),next(NULL){} }; void printLL(ListNode* head){ ListNode* temp = head; while(temp!=NULL){ cout<<temp->val<<"->"; temp = temp->next; } } ListNode* addNode(ListNode* head, int val){ if(head==NULL){ head = new ListNode(val); } else{ ListNode* temp = head; while(temp->next!=NULL){ temp = temp->next; } temp->next = new ListNode(val); } return head; } void print(vector<int>&v){ int n = v.size(); for(int i =0;i<n;i++){ cout<<v[i]<<" "; } } ListNode* reverse(ListNode*A){ ListNode* prev = NULL; ListNode* curr = A; ListNode* next = A->next; if(A==NULL){ return A; } while(curr->next!=NULL){ curr->next = prev; prev = curr; curr = next; next = next->next; } curr->next = prev; A = curr; return A; } void reverseBetween(ListNode* A, int m, int n){ ListNode* t1 = A; ListNode* t2,*t4=NULL; ListNode* t3 = A; if(A==NULL||A->next==NULL){ return; } while(m!=1){ t4 = t1; t1 = t1->next; m--; } while(n!=1){ t3 = t3->next; n--; } if(t1==A&&t3->next==NULL){ return reverse(A); } if(t4!=NULL){ t4->next = NULL; } if(t3->next==NULL){ ListNode* T = reverse(t1); if(t4!=NULL){ t4->next = T; } } else{ t2 = t3->next; t3->next = NULL; ListNode* T = reverse(t1); // printLL(T); if(t4==NULL){ A = T; } if(t4!=NULL){ t4->next = T; } t1->next = t2; } // return A; printLL(A); } int main(){ ListNode *head1 = NULL; ListNode *head; int n1,n2; cin>>n1; for(int i =0;i<n1;i++){ int val; cin>>val; head1 = addNode(head1,val); } reverseBetween(head1,1,4); }
#pragma once #define GLUT_DISABLE_ATEXIT_HACK #include <stdlib.h> #include <GL/GLUT.H> #include <math.h> #include <iostream> #include <GL/GLAUX.H> #include <Windows.h> #include <random> #include <time.h> #include "Color.h" #include <Windows.h> #include <windef.h> #include <vector> #include <map> #include <set> #include <queue> #include <list> #include <algorithm> #include <numeric> #pragma comment(lib,"glaux.lib") const float PI = 3.141592653; #define random(x) (rand() % (x)) #define sqr(x) ((x) * (x)) #define jiao2hu(x) (((float)x) / ((float)180) * PI ) //decide which scene to be drawn #define MENU 0 #define GAME 1 #define EXIT 2 #define UNFINISHED 3 #define TEST 4 extern int flag; #define MAINWINDOWPOSX 100 #define MAINWINDOWPOSY 100 #define MAINWINDOWSIZX 600 #define MAINWINDOWSIZY 600 #define DRAWPARA 100 #define TABLETOP -0.2 #define TABLEHEIGHT 0.1 #define TABLERADIUS 0.8
#pragma once #include "Mesh.h" #include "SimpleShader.h" #include "Camera.h" #include <wrl/client.h> // Used for ComPtr class Sky { public: // Constructor that loads a DDS cube map file Sky( const wchar_t* cubemapDDSFile, Mesh* mesh, SimpleVertexShader* skyVS, SimplePixelShader* skyPS, Microsoft::WRL::ComPtr<ID3D11SamplerState> samplerOptions, Microsoft::WRL::ComPtr<ID3D11Device> device, Microsoft::WRL::ComPtr<ID3D11DeviceContext> context ); // Constructor that loads 6 textures and makes a cube map Sky( const wchar_t* right, const wchar_t* left, const wchar_t* up, const wchar_t* down, const wchar_t* front, const wchar_t* back, Mesh* mesh, SimpleVertexShader* skyVS, SimplePixelShader* skyPS, Microsoft::WRL::ComPtr<ID3D11SamplerState> samplerOptions, Microsoft::WRL::ComPtr<ID3D11Device> device, Microsoft::WRL::ComPtr<ID3D11DeviceContext> context ); ~Sky(); void Draw(Camera* camera); // public IBL methods Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> GetIBLIrradianceMap(); Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> GetIBLConvolvedSpecularMap(); Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> GetIBLBRDFLookUpTexture(); int GetIBLMipLevelCount(); private: void InitRenderStates(); // private IBL methods void IBLCreateIrradianceMap( SimpleVertexShader* fullscreenVS, SimplePixelShader* irradiancePS); void IBLCreateConvolvedSpecularMap( SimpleVertexShader* fullscreenVS, SimplePixelShader* specularConvolvedPS); void IBLCreateBRDFLookUpTexture( SimpleVertexShader* fullscreenVS, SimplePixelShader* irradiancePS); // Helper for creating a cubemap from 6 individual textures Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> CreateCubemap( const wchar_t* right, const wchar_t* left, const wchar_t* up, const wchar_t* down, const wchar_t* front, const wchar_t* back); // Skybox related resources SimpleVertexShader* skyVS; SimplePixelShader* skyPS; Mesh* skyMesh; Microsoft::WRL::ComPtr<ID3D11RasterizerState> skyRasterState; Microsoft::WRL::ComPtr<ID3D11DepthStencilState> skyDepthState; Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> skySRV; Microsoft::WRL::ComPtr<ID3D11SamplerState> samplerOptions; Microsoft::WRL::ComPtr<ID3D11DeviceContext> context; Microsoft::WRL::ComPtr<ID3D11Device> device; // For IBL Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> IBLIrradianceCubeMap; Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> IBLConvolvedSpecularCubeMap; Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> BRDFLookUpTexture; int totalIBLSpecularMapMipLevels; const int IBLSpecularMipLevelsToSkip = 3; const int IBLCubeMapFaceSize = 256; const int LookUpTextureSize = 256; };
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 2004-2011 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * Tord Akerbęk */ #include "core/pch.h" #ifdef PREFS_DOWNLOAD #include "modules/prefsloader/prefsloadmanager.h" #include "modules/prefsloader/prefsloader.h" #include "modules/prefs/prefsmanager/prefsmanager.h" #include "modules/prefs/prefsmanager/collections/pc_core.h" #include "modules/hardcore/mem/mem_man.h" #include "modules/hardcore/mh/messages.h" #include "modules/util/opfile/opfile.h" #include "modules/util/opstrlst.h" # ifdef DOM_BROWSERJS_SUPPORT # include "modules/dom/src/userjs/browserjs_key.h" # include "modules/libssl/tools/signed_textfile.h" # endif // DOM_BROWSERJS_SUPPORT XMLTokenHandler::Result PrefsLoader::HandleToken(XMLToken &token) { switch (token.GetType()) { case XMLToken::TYPE_STag: case XMLToken::TYPE_ETag: case XMLToken::TYPE_EmptyElemTag: if (token.GetType() != XMLToken::TYPE_ETag) { HandleStartElement(token.GetName().GetLocalPart(), token.GetName().GetLocalPartLength(), token.GetAttributes(), token.GetAttributesCount()); } if (token.GetType() != XMLToken::TYPE_STag) HandleEndElement(token.GetName().GetLocalPart(), token.GetName().GetLocalPartLength()); } return RESULT_OK; } PrefsLoader::PrefsLoader(OpEndChecker *end) : m_descriptor(NULL), m_prl_parser(NULL), m_parseno(0), // Run a primary parsing to check the hostnames and verify signature m_clean_all_update(FALSE), m_checker(end), m_parse_blocked(FALSE) { m_hostnames.Empty(); if (!m_checker) m_parseno = 1; // Skip the primary parsing when there is no signature and no confirm dialog } OP_STATUS PrefsLoader::Construct(URL url) { m_serverURL.SetURL(url); // This may be an external prefs server. Some kind of validity checker should be present. // In wich case the parsed material should be checked return OpStatus::OK; } OP_STATUS PrefsLoader::Construct(const OpStringC &host) { OpString serverURLstr; RETURN_IF_ERROR(serverURLstr.Set(g_pccore->GetStringPref(PrefsCollectionCore::PreferenceServer))); if (!host.IsEmpty()) { RETURN_IF_ERROR(serverURLstr.Append("?host=")); RETURN_IF_ERROR(serverURLstr.Append(host)); } URL url = g_url_api->GetURL(serverURLstr.CStr()); if (url.IsEmpty()) { return OpStatus::ERR_NO_MEMORY; } m_serverURL.SetURL(url); // This is an internal prefs server. We can assume that the content is safe and the validity checker is not compulsory. return OpStatus::OK; } PrefsLoader::~PrefsLoader() { if (!IsDead()) { URL_ID url_id = m_serverURL->Id(); FinishLoading(url_id); } } OP_STATUS PrefsLoader::StartLoading() { MessageHandler *mmh = g_main_message_handler; CommState stat = m_serverURL->Load(mmh, URL(),FALSE,FALSE,FALSE,FALSE); if(stat == COMM_REQUEST_FAILED) return OpStatus::ERR; URL_ID url_id = m_serverURL->Id(); OP_STATUS rc = OpStatus::OK; if (OpStatus::IsError(rc = mmh->SetCallBack(this, MSG_URL_DATA_LOADED, url_id)) || OpStatus::IsError(rc = mmh->SetCallBack(this, MSG_URL_MOVED, url_id)) || OpStatus::IsError(rc = mmh->SetCallBack(this, MSG_URL_LOADING_FAILED, url_id))) { mmh->UnsetCallBacks(this); } return rc; } void PrefsLoader::LoadData(URL_ID url_id) { if(m_parse_blocked) return; if (!m_descriptor) m_descriptor = m_serverURL->GetDescriptor(g_main_message_handler, TRUE); if (!m_descriptor) return; m_parse_blocked = TRUE; BOOL more(TRUE); unsigned long buf_len = 0; while (more && ((buf_len = m_descriptor->RetrieveData(more)) > 0)) { const uni_char *data_buf = reinterpret_cast<const uni_char *>(m_descriptor->GetBuffer()); ParseResponse(data_buf, UNICODE_DOWNSIZE(buf_len), more?TRUE:FALSE); m_descriptor->ConsumeData(buf_len); } m_parse_blocked = FALSE; if (m_serverURL->Status(TRUE) == URL_LOADED) { if(m_parseno == 0) { if (m_clean_all_update) { // If the clean_all attribute is used on the preferences element // then any existing hostname override can be affected by this update. // Since the m_hostnames string we pass to ->IsEnd() might end up in // a "Do you want to install updated overrides for these hosts?"-type // of dialog with APPROVE/DENY buttons, it's important that we signal // the scope of the update correctly. m_hostnames.Set("*"); } // if endchecker is present, it is responsible for stopping or continuing the parser. if(m_checker && m_checker->IsEnd(m_hostnames.CStr())) ; else { // Parse one more time to retrieve the preference values m_parseno++; delete m_descriptor; m_descriptor = m_serverURL->GetDescriptor(g_main_message_handler, TRUE); if (!m_descriptor) return; delete m_prl_parser; m_prl_parser = NULL; more = TRUE; buf_len = 0; while (more && ((buf_len = m_descriptor->RetrieveData(more)) > 0)) { const uni_char *data_buf = reinterpret_cast<const uni_char *>(m_descriptor->GetBuffer()); ParseResponse(data_buf, UNICODE_DOWNSIZE(buf_len), more?TRUE:FALSE); m_descriptor->ConsumeData(buf_len); } } } FinishLoading(url_id); } } OP_STATUS PrefsLoader::FinishLoading(URL_ID url_id) { delete m_descriptor; m_descriptor = NULL; g_main_message_handler->RemoveCallBacks(this, url_id); MarkDead(); Commit(); if(m_checker) m_checker->Dispose(); m_checker = NULL; m_serverURL.UnsetURL(); delete m_prl_parser; m_prl_parser = NULL; return OpStatus::OK; } BOOL PrefsLoader::ParseResponse(const uni_char* buffer, int length, BOOL more) { if (!m_prl_parser) { while (length && uni_isspace(*buffer)) { buffer++; length--; } URL empty_url; XMLParser::Make(m_prl_parser, this, g_main_message_handler, this, empty_url); m_cur_level = 0; } m_parse_error = FALSE; if (!m_prl_parser->IsFinished() && !m_parse_error) { m_prl_parser->Parse(buffer, length, more); if (m_prl_parser->IsFailed()) m_parse_error = TRUE; } if (!more) { delete m_prl_parser; m_prl_parser = NULL; } return FALSE; } void PrefsLoader::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2) { switch(msg) { case MSG_URL_LOADING_FAILED: FinishLoading(par2); break; case MSG_URL_DATA_LOADED: LoadData(par1); break; case MSG_URL_MOVED: { MessageHandler *mmh = g_main_message_handler; mmh->UnsetCallBack(this, MSG_URL_DATA_LOADED); mmh->UnsetCallBack(this, MSG_URL_LOADING_FAILED); mmh->UnsetCallBack(this, MSG_URL_MOVED); mmh->SetCallBack(this, MSG_URL_DATA_LOADED, par2); mmh->SetCallBack(this, MSG_URL_LOADING_FAILED, par2); mmh->SetCallBack(this, MSG_URL_MOVED, par2); } break; } } void PrefsLoader::HandleStartElement(const uni_char *name, int name_len, XMLToken::Attribute *atts, int atts_len) { OP_STATUS rc = OpStatus::OK; XMLToken::Attribute *atts_end = atts + atts_len; ElementType type = GetElmType(name, name_len); if(m_parseno == 0) // primary parsing { if(type == ELM_HOST) { // Store hostname for now while (atts < atts_end) { if(GetAttType(atts) == ATT_NAME) { if (!m_hostnames.IsEmpty()) { if (OpStatus::IsError(rc = m_hostnames.Append(" ", 1))) break; } rc = m_hostnames.Append(atts->GetValue(), atts->GetValueLength()); if (OpStatus::IsError(rc)) break; } atts++; } } else if (type == ELM_PREFERENCES) { while (atts < atts_end) { if (GetAttType(atts) == ATT_CLEAN_ALL && atts->GetValueLength() == 1 && atts->GetValue()[0] == '1') m_clean_all_update = TRUE; atts++; } } } else // secondary parsing { switch (type) { case ELM_HOSTNAMES: m_elm_type[++m_cur_level] = ELM_HOSTNAMES; // This element is deprecated break; case ELM_PREFERENCES: while (atts < atts_end) { if (GetAttType(atts) == ATT_CLEAN_ALL && atts->GetValueLength() == 1 && atts->GetValue()[0] == '1') { OP_MEMORY_VAR BOOL removed_any = FALSE; TRAPD(rc, removed_any = g_prefsManager->RemoveOverridesAllHostsL(/* from_user== */ FALSE)); if (OpStatus::IsSuccess(rc) && removed_any) m_has_changes = TRUE; } atts++; } break; case ELM_HOST: { BOOL clean = FALSE; BOOL has_name = FALSE; m_elm_type[++m_cur_level] = ELM_HOST; while (atts < atts_end) { if(GetAttType(atts) == ATT_NAME) { rc = m_current_host.Set(atts->GetValue(), atts->GetValueLength()); if (OpStatus::IsError(rc)) { break; } has_name = TRUE; } else if(GetAttType(atts) == ATT_CLEAN) { if (atts->GetValueLength() == 1 && atts->GetValue()[0] == '1') { clean = TRUE; } } atts++; } // When the attributes are read, if(clean && has_name && OpStatus::IsSuccess(rc)) { // Remove all overrides on this host. OP_MEMORY_VAR BOOL success = FALSE; TRAP(rc, success = g_prefsManager->RemoveOverridesL(m_current_host.CStr(), FALSE)); // m_has_changes == TRUE ensures that the PLoader base class will CommitL our changes to g_prefsManager when Commit() is called. m_has_changes = m_has_changes || success; } } break; case ELM_SECTION: m_elm_type[++m_cur_level] = ELM_SECTION; while (atts < atts_end) { if(GetAttType(atts) == ATT_NAME) { rc = m_current_section.Set(atts->GetValue(), atts->GetValueLength()); if (OpStatus::IsError(rc)) { break; } } atts++; } break; case ELM_PREF: { OpString8 pref_name; OpString pref_value; while (atts < atts_end) { if(GetAttType(atts) == ATT_NAME) { if(IsAcceptedPref(atts)) rc = pref_name.Set(atts->GetValue(), atts->GetValueLength()); else rc = OpStatus::ERR; } else if(GetAttType(atts) == ATT_VALUE) { rc = pref_value.Set(atts->GetValue(), atts->GetValueLength()); } else rc = OpStatus::ERR; if(OpStatus::IsError(rc)) { break; } atts++; } // Record the new pref if(OpStatus::IsSuccess(rc)) { OP_MEMORY_VAR BOOL success = FALSE; if(m_current_host.IsEmpty()) { TRAP(rc, success = g_prefsManager->WritePreferenceL(m_current_section.CStr(),pref_name.CStr(),pref_value)); } else { TRAP(rc, success = g_prefsManager->OverridePreferenceL(m_current_host.CStr(),m_current_section.CStr(),pref_name.CStr(),pref_value,FALSE)); } // m_has_changes == TRUE ensures that the PLoader base class will CommitL our changes to g_prefsManager when Commit() is called. m_has_changes = m_has_changes || success; } break; } #ifdef PREFS_FILE_DOWNLOAD case ELM_FILE: { OpString8 pref_name; OpString file_from, file_to, name_to; while (atts < atts_end) { if(GetAttType(atts) == ATT_NAME) { if(IsAcceptedPref(atts)) rc = pref_name.Set(atts->GetValue(), atts->GetValueLength()); else rc = OpStatus::ERR; } else if(GetAttType(atts) == ATT_FROM) { rc = file_from.Set(atts->GetValue(), atts->GetValueLength()); } else if((GetAttType(atts) == ATT_TO) || (GetAttType(atts) == ATT_VALUE)) { rc = file_to.Set(atts->GetValue(), atts->GetValueLength()); } else rc = OpStatus::ERR; if(OpStatus::IsError(rc)) { break; } atts++; } if (OpStatus::IsSuccess(rc)) { if(IsAcceptedFile(file_to)) // Download the file rc = g_PrefsLoadManager->InitFileLoader(m_current_host, m_current_section, pref_name, file_from, file_to); } break; } case ELM_DELETE_FILE: { OpString file_name; while (atts < atts_end) { if(GetAttType(atts) == ATT_VALUE) { rc = file_name.Set(atts->GetValue(), atts->GetValueLength()); } else rc = OpStatus::ERR; if(OpStatus::IsError(rc)) { break; } atts++; } if(!IsAcceptedFile(file_name)) rc = OpStatus::ERR; // Delete the file if (OpStatus::IsSuccess(rc)) { OpFile f; if(OpStatus::IsSuccess(rc = f.Construct(file_name.CStr(),OPFILE_PREFSLOAD_FOLDER))) rc = f.Delete(); } break; } #endif // PREFS_FILE_DOWNLOAD } // switch } // secondary parsing // Signal errors globally, as we cannot do much here. // FIXME: OOM: Or can we? if (OpStatus::IsRaisable(rc)) { g_memory_manager->RaiseCondition(rc); } } void PrefsLoader::HandleEndElement(const uni_char *name, int name_len) { ElementType type = GetElmType(name, name_len); switch (type) { case ELM_SECTION: m_current_section.Empty(); break; case ELM_HOST: m_current_host.Empty(); break; } if (m_cur_level > 0 && m_elm_type[m_cur_level] == type) --m_cur_level; } PrefsLoader::ElementType PrefsLoader::GetElmType(const uni_char *name, int name_len) { switch (name_len) { case 4: if (uni_strni_eq_upper(name, "HOST", 4)) return ELM_HOST; else if (uni_strni_eq_upper(name, "PREF", 4)) return ELM_PREF; else if (uni_strni_eq_upper(name, "FILE", 4)) return ELM_FILE; break; case 7: if (uni_strni_eq_upper(name, "SECTION", 7)) return ELM_SECTION; break; case 9: if (uni_strni_eq_upper(name, "HOSTNAMES", 9)) // deprecated return ELM_HOSTNAMES; break; case 11: if (uni_strni_eq_upper(name, "DELETE-FILE", 11)) return ELM_DELETE_FILE; else if (uni_strni_eq_upper(name, "PREFERENCES", 11)) return ELM_PREFERENCES; break; } return ELM_UNKNOWN; } PrefsLoader::AttributeType PrefsLoader::GetAttType(XMLToken::Attribute *att) { const uni_char *name = att->GetName().GetLocalPart(); switch (att->GetName().GetLocalPartLength()) { case 2: if (uni_strni_eq_upper(name, "TO", 2)) return ATT_TO; break; case 4: if (uni_strni_eq_upper(name, "NAME", 4)) return ATT_NAME; else if (uni_strni_eq_upper(name, "FROM", 4)) return ATT_FROM; break; case 5: if (uni_strni_eq_upper(name, "VALUE", 5)) return ATT_VALUE; else if (uni_strni_eq_upper(name, "CLEAN", 5)) return ATT_CLEAN; break; case 9: if (uni_strni_eq_upper(name, "CLEAN_ALL", 9)) return ATT_CLEAN_ALL; break; } return ATT_UNKNOWN; } BOOL PrefsLoader::IsAcceptedPref(XMLToken::Attribute *att) { /* Whitelist of preferences accepted for download. Should only * be changed after consulting with QA. */ const uni_char *name = att->GetValue(); switch (att->GetValueLength()) { #ifdef SELFTEST case 5: return uni_strni_eq_upper(name, "SCALE", 5); #endif #ifdef USE_SPDY case 9: return uni_strni_eq_upper(name, "USE SPDY2", 9) || uni_strni_eq_upper(name, "USE SPDY3", 9); #endif case 13: return uni_strni_eq_upper(name, "DOCUMENT MODE", 13); case 14: return uni_strni_eq_upper(name, "LOCAL CSS FILE", 14); case 16: return uni_strni_eq_upper(name, "BROWSER CSS FILE", 16); case 17: return uni_strni_eq_upper(name, "MINIMUM FONT SIZE", 17) || uni_strni_eq_upper(name, "ENABLE PIPELINING", 17); case 18: return uni_strni_eq_upper(name, "SPOOF USERAGENT ID", 18); case 19: return uni_strni_eq_upper(name, "COMPATMODE OVERRIDE", 19); case 22: return uni_strni_eq_upper(name, "MINIMUM SECURITY LEVEL", 22); case 24: return uni_strni_eq_upper(name, "DELAYED SCRIPT EXECUTION", 24); case 29: return uni_strni_eq_upper(name, "AUTOCOMPLETEOFF DISABLES WAND", 29); default: return FALSE; } } BOOL PrefsLoader::IsAcceptedFile(OpString &name) { if(name.Find("..") == KNotFound) return TRUE; return FALSE; } #endif
#include "greenSegmentation.hpp" void GreenSegmentation::run(cv::Mat imgTop, cv::Mat imgBot, PerceptionData *data) { #ifdef DEBUG_PERCEPTION //Create an image vector, put the desired images inside it and atualize the perception data debugImages with it. debugImgVector.assign(1, imgTop); debugImgVector.push_back(imgBot); #endif //*********************************************************************************** //* This method uses chromacity filter to segmentate the green region of the field. * //*********************************************************************************** cv::Mat topChromacity(imgTop.rows,imgTop.cols,CV_8UC3); cv::Mat botChromacity(imgBot.rows,imgBot.cols,CV_8UC3); cv::Vec3b BGRPixel; for (int i = 0; i < imgTop.rows; i++) { for (int j = 0; j < imgTop.cols; j++) { BGRPixel = imgTop.at<cv::Vec3b>(i,j); if(BGRPixel[0]+BGRPixel[1]+BGRPixel[2] > 0){ topChromacity.at<cv::Vec3b>(i,j)[0] = (255*BGRPixel[0]/(BGRPixel[0]+BGRPixel[1]+BGRPixel[2])); topChromacity.at<cv::Vec3b>(i,j)[1] = (255*BGRPixel[1]/(BGRPixel[0]+BGRPixel[1]+BGRPixel[2])); topChromacity.at<cv::Vec3b>(i,j)[2] = (255*BGRPixel[2]/(BGRPixel[0]+BGRPixel[1]+BGRPixel[2])); } BGRPixel = imgBot.at<cv::Vec3b>(i,j); if(BGRPixel[0]+BGRPixel[1]+BGRPixel[2] > 0){ botChromacity.at<cv::Vec3b>(i,j)[0] = (255*BGRPixel[0]/(BGRPixel[0]+BGRPixel[1]+BGRPixel[2])); botChromacity.at<cv::Vec3b>(i,j)[1] = (255*BGRPixel[1]/(BGRPixel[0]+BGRPixel[1]+BGRPixel[2])); botChromacity.at<cv::Vec3b>(i,j)[2] = (255*BGRPixel[2]/(BGRPixel[0]+BGRPixel[1]+BGRPixel[2])); } } } #ifdef DEBUG_PERCEPTION //Create an image vector, put the desired images inside it and atualize the perception data debugImages with it. debugImgVector.push_back(topChromacity); debugImgVector.push_back(botChromacity); #endif #ifdef DEBUG_PERCEPTION std::pair<std::map<std::string,std::vector<cv::Mat> >::iterator, bool> debugInsertion; debugInsertion = data->debugImages.insert(std::make_pair("greenSegmentation", debugImgVector)); if(!debugInsertion.second){ data->debugImages["greenSegmentation"] = debugImgVector; } #endif } void GreenSegmentation::updateData(PerceptionData *data) { }
//------------------------------------------------------------------------------ /* This file is part of rippled: https://github.com/ripple/rippled Copyright (c) 2012, 2013 Ripple Labs Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #ifndef RIPPLE_PEERFINDER_STORESQDB_H_INCLUDED #define RIPPLE_PEERFINDER_STORESQDB_H_INCLUDED namespace ripple { namespace PeerFinder { /** Database persistence for PeerFinder using SQLite */ class StoreSqdb : public Store , public LeakChecked <StoreSqdb> { private: Journal m_journal; sqdb::session m_session; public: enum { // This determines the on-database format of the data currentSchemaVersion = 2 }; explicit StoreSqdb (Journal journal = Journal()) : m_journal (journal) { } ~StoreSqdb () { } Error open (File const& file) { Error error (m_session.open (file.getFullPathName ())); m_journal.info << "Opening database at '" << file.getFullPathName() << "'"; if (!error) error = init (); if (!error) error = update (); return error; } void loadLegacyEndpoints ( std::vector <IPAddress>& list) { list.clear (); Error error; // Get the count std::size_t count; if (! error) { m_session.once (error) << "SELECT COUNT(*) FROM PeerFinder_LegacyEndpoints " ,sqdb::into (count) ; } if (error) { report (error, __FILE__, __LINE__); return; } list.reserve (count); { std::string s; sqdb::statement st = (m_session.prepare << "SELECT ipv4 FROM PeerFinder_LegacyEndpoints " ,sqdb::into (s) ); if (st.execute_and_fetch (error)) { do { IPAddress ep (IPAddress::from_string (s)); if (! ep.empty()) list.push_back (ep); } while (st.fetch (error)); } } if (error) { report (error, __FILE__, __LINE__); } } void updateLegacyEndpoints ( std::vector <LegacyEndpoint const*> const& list) { typedef std::vector <LegacyEndpoint const*> List; Error error; sqdb::transaction tr (m_session); m_session.once (error) << "DELETE FROM PeerFinder_LegacyEndpoints"; if (! error) { std::string s; sqdb::statement st = (m_session.prepare << "INSERT INTO PeerFinder_LegacyEndpoints ( " " ipv4 " ") VALUES ( " " ? " ");" ,sqdb::use (s) ); for (List::const_iterator iter (list.begin()); !error && iter != list.end(); ++iter) { IPAddress const& ep ((*iter)->address); s = ep.to_string(); st.execute_and_fetch (error); } } if (! error) { error = tr.commit(); } if (error) { tr.rollback (); report (error, __FILE__, __LINE__); } } // Convert any existing entries from an older schema to the // current one, if approrpriate. // Error update () { Error error; sqdb::transaction tr (m_session); // get version int version (0); if (!error) { m_session.once (error) << "SELECT " " version " "FROM SchemaVersion WHERE " " name = 'PeerFinder'" ,sqdb::into (version) ; if (! error) { if (!m_session.got_data()) version = 0; m_journal.info << "Opened version " << version << " database"; } } if (!error && version != currentSchemaVersion) { m_journal.info << "Updateding database to version " << currentSchemaVersion; } if (!error && (version < 2)) { if (!error) m_session.once (error) << "DROP TABLE IF EXISTS LegacyEndpoints"; if (!error) m_session.once (error) << "DROP TABLE IF EXISTS PeerFinderLegacyEndpoints"; } if (!error) { int const version (currentSchemaVersion); m_session.once (error) << "INSERT OR REPLACE INTO SchemaVersion (" " name " " ,version " ") VALUES ( " " 'PeerFinder', ? " ")" ,sqdb::use(version); } if (!error) error = tr.commit(); if (error) { tr.rollback(); report (error, __FILE__, __LINE__); } return error; } private: Error init () { Error error; sqdb::transaction tr (m_session); if (! error) { m_session.once (error) << "PRAGMA encoding=\"UTF-8\""; } if (! error) { m_session.once (error) << "CREATE TABLE IF NOT EXISTS SchemaVersion ( " " name TEXT PRIMARY KEY, " " version INTEGER" ");" ; } if (! error) { m_session.once (error) << "CREATE TABLE IF NOT EXISTS PeerFinder_LegacyEndpoints ( " " id INTEGER PRIMARY KEY AUTOINCREMENT, " " ipv4 TEXT UNIQUE NOT NULL " ");" ; } if (! error) { m_session.once (error) << "CREATE INDEX IF NOT EXISTS " " PeerFinder_LegacyEndpoints_Index ON PeerFinder_LegacyEndpoints " " ( " " ipv4 " " ); " ; } if (! error) { error = tr.commit(); } if (error) { tr.rollback (); report (error, __FILE__, __LINE__); } return error; } void report (Error const& error, char const* fileName, int lineNumber) { if (error) { m_journal.error << "Failure: '"<< error.getReasonText() << "' " << " at " << Debug::getSourceLocation (fileName, lineNumber); } } }; } } #endif
#include "GnSystemPCH.h" #include "GnWCharFunctions.h" //GNFORCEINLINE gsize GnWStrlen(const gwchar* GNRESTRICT str) //{ // return wcslen(str); //} // //GNFORCEINLINE gwchar* GnWStrcpy(gwchar* GNRESTRICT dest, const gwchar* GNRESTRICT src, size_t destSize) //{ //#ifdef __GNUC__ // return wcscpy(dest, src); //#else // wcscpy_s(dest, destSize, src); // return dest; //#endif //} // //GNFORCEINLINE gwchar* GnWStrncpy(gwchar* GNRESTRICT dest, const gwchar* GNRESTRICT src, size_t strLength // , size_t destSize) //{ //#ifdef __GNUC__ // return wcsncpy(dest, src, strLength); //#else // wcsncpy_s(dest, destSize, src, strLength); // return dest; //#endif // //} // //GNFORCEINLINE gint GnWSprintf(gwchar* GNRESTRICT buffer, gsize bufferSize, const gwchar* GNRESTRICT format // , ...) //{ //#ifdef __GNUC__ // __darwin_va_list args; //#else // va_list args; //#endif // // va_start( args, format ); // gint ret = vswprintf(buffer, bufferSize, format, args); // va_end(args); // return ret; //} // //GNFORCEINLINE gwchar* GnWStrtok(gwchar* GNRESTRICT pcString, const gwchar* GNRESTRICT pcDelimit // , gwchar** GNRESTRICT ppcContext) //{ //#ifdef __GNUC__ // return wcstok(pcString, pcDelimit, ppcContext); //#else // return wcstok_s(pcString, pcDelimit, ppcContext); //#endif //} // //GNFORCEINLINE gint GnWStrcmp(const gwchar* GNRESTRICT pStr1, const gwchar* GNRESTRICT pStr2) //{ // return wcscmp(pStr1, pStr2); //} // //GNFORCEINLINE gint GnWStricmp(const gwchar* GNRESTRICT pStr1, const gwchar* GNRESTRICT pStr2) //{ //#ifdef WIN32 // return _wcsicmp(pStr1, pStr2); //#else // return wcsicmp(pStr1, pStr2); //#endif //} // //GNFORCEINLINE const gwchar* GnWStrstr(const gwchar* GNRESTRICT pStr1, const gwchar* GNRESTRICT pStr2) //{ // return wcsstr(pStr1, pStr2); //}
#ifndef __UIGIF_H__ #define __UIGIF_H__ #pragma once namespace UiLib { #define EVENT_TIEM_ID 100 class UILIB_API CGifUI : public CLabelUI { public: CGifUI(); ~CGifUI(); LPCTSTR GetClass() const; LPVOID GetInterface(LPCTSTR pstrName); void DoPaint(HDC hDC, const RECT& rcPaint); void DoEvent(TEventUI& event); void SetAttribute(LPCTSTR pstrName, LPCTSTR pstrValue); void SetNormalGifFile(LPCTSTR sImagePath); private: void InitGifImage(CDuiString strPath); void DeleteGif(); void OnTimer( UINT_PTR idEvent ); void DrawFrame( HDC hDC ); // 绘制GIF每帧 private: Image *m_pGifImage; UINT m_nFrameCount; // gif图片总帧数 UINT m_nFramePosition; // 当前放到第几帧 PropertyItem* m_pPropertyItem; // 帧与帧之间间隔时间 CDuiString m_strImagePath; }; } // namespace UiLib #endif // __UIGIF_H__
#include "interpreter.h" #include <unordered_map> #include <iostream> #include <sstream> #include <fstream> #include <cstring> //************************************************************ bool isRGBValid(fp_t r, fp_t g, fp_t b){ return in(0, r, 256) && in(0, g, 256) && in(0, b, 256); } //************************************************************ void Interpreter::analyze(const std::string &filename, Drawer &drawer){ std::ifstream reader(filename, std::ios::binary); if(!reader) throw FileNotOpen(filename); internal_drawer = &drawer; std::unordered_map< std::string, void(Interpreter::*)(const std::vector<fp_t>&)> handlers({ // Basic shapes. {"L", &Interpreter::processLine}, {"C", &Interpreter::processCircle}, {"D", &Interpreter::processDisk}, {"A", &Interpreter::processArc}, {"S", &Interpreter::processCircularSector}, // Additional shapes. {"E", &Interpreter::processEllipse}, {"R", &Interpreter::processRectangle}, {"P", &Interpreter::processRegularPolygon} }); this->line_no = 0; while(reader.good()){ ++line_no; const int BUFSIZE = 256; char line[BUFSIZE]; reader.getline(line, BUFSIZE, '\n'); std::size_t len = strlen(line); // Handle CRLF format. if(line[len-1] == '\r') line[(len--)-1] = '\0'; std::istringstream ss{line}; std::string token; ss >> token; if(token.empty()) continue; //skip empty line if(token[0] == '#') continue; //skip comments this->current_instruction = token; auto handler_itr = handlers.find(token); if(handler_itr == handlers.end()) throw UnknownInstruction(token, line_no); // Read all arguments. std::vector<fp_t> args; fp_t f; e_ProcessingStatus err = GOOD; while(!err){ err = readFromStream(ss, f); if(err != FAIL) args.push_back(f); else throw InvalidArgType(this->current_instruction, line_no); } // Execute instruction - draw an object. (this->*handler_itr->second)(args); if(!reader.good()) break; } reader.close(); internal_drawer = nullptr; } //************************************************************ void Interpreter::processLine(const std::vector<fp_t> &args){ const int ARGCOUNT = 7; Point a, b; Colour c; if(args.size() != ARGCOUNT) throw InvalidArgCount( this->current_instruction, this->line_no, ARGCOUNT, args.size() ); a = Point(args[0], args[1]); b = Point(args[2], args[3]); if(!isRGBValid(args[4], args[5], args[6])) throw InvalidArgType(this->current_instruction, this->line_no); c = Colour(args[4], args[5], args[6]); internal_drawer->drawLine(a, b, c); } //************************************************************ void Interpreter::processCircle(const std::vector<fp_t> &args){ const int ARGCOUNT = 6; Point s; uint16_t r; Colour c; if(args.size() != ARGCOUNT) throw InvalidArgCount( this->current_instruction, this->line_no, ARGCOUNT, args.size() ); s = Point(args[0], args[1]); if(args[2] < 0.0f) throw InvalidArgType(this->current_instruction, this->line_no); r = args[2]; if(!isRGBValid(args[3], args[4], args[5])) throw InvalidArgType(this->current_instruction, this->line_no); c = Colour(args[3], args[4], args[5]); internal_drawer->drawCircle(s, r, c); } //************************************************************ void Interpreter::processDisk(const std::vector<fp_t> &args){ const int ARGCOUNT = 6; Point s; uint16_t r; Colour c; if(args.size() != ARGCOUNT) throw InvalidArgCount( this->current_instruction, this->line_no, ARGCOUNT, args.size() ); s = Point(args[0], args[1]); if(args[2] < 0.0f) throw InvalidArgType(this->current_instruction, this->line_no); r = args[2]; if(!isRGBValid(args[3], args[4], args[5])) throw InvalidArgType(this->current_instruction, this->line_no); c = Colour(args[3], args[4], args[5]); internal_drawer->drawDisk(s, r, c); } //************************************************************ void Interpreter::processArc(const std::vector<fp_t> &args){ const int ARGCOUNT = 8; Point s; uint16_t r; fp_t a1, a2; Colour c; if(args.size() != ARGCOUNT) throw InvalidArgCount( this->current_instruction, this->line_no, ARGCOUNT, args.size() ); s = Point(args[0], args[1]); if(args[2] < 0.0f) throw InvalidArgType(this->current_instruction, this->line_no); r = args[2]; a1 = args[3]; a2 = args[4]; if(!isRGBValid(args[5], args[6], args[7])) throw InvalidArgType(this->current_instruction, this->line_no); c = Colour(args[5], args[6], args[7]); internal_drawer->drawArc(s, r, a1, a2, c); } //************************************************************ void Interpreter::processCircularSector(const std::vector<fp_t> &args){ const int ARGCOUNT = 8; Point s; uint16_t r; fp_t a1, a2; Colour c; if(args.size() != ARGCOUNT) throw InvalidArgCount( this->current_instruction, this->line_no, ARGCOUNT, args.size() ); s = Point(args[0], args[1]); if(args[2] < 0.0f) throw InvalidArgType(this->current_instruction, this->line_no); r = args[2]; a1 = args[3]; a2 = args[4]; if(!isRGBValid(args[5], args[6], args[7])) throw InvalidArgType(this->current_instruction, this->line_no); c = Colour(args[5], args[6], args[7]); internal_drawer->drawCircularSector(s, r, a1, a2, c); } //************************************************************ void Interpreter::processEllipse(const std::vector<fp_t> &args){ const int ARGCOUNT = 7; Point s; uint16_t a, b; Colour c; if(args.size() != ARGCOUNT) throw InvalidArgCount( this->current_instruction, this->line_no, ARGCOUNT, args.size() ); s = Point(args[0], args[1]); if(args[2] < 0.0f || args[3] < 0.0f) throw InvalidArgType(this->current_instruction, this->line_no); a = args[2]; b = args[3]; if(!isRGBValid(args[4], args[5], args[6])) throw InvalidArgType(this->current_instruction, this->line_no); c = Colour(args[4], args[5], args[6]); internal_drawer->drawEllipse(s, a, b, c); } //************************************************************ void Interpreter::processRectangle(const std::vector<fp_t> &args){ const int ARGCOUNT = 7; Point a, b; Colour c; if(args.size() != ARGCOUNT) throw InvalidArgCount( this->current_instruction, this->line_no, ARGCOUNT, args.size() ); a = Point(args[0], args[1]); b = Point(args[2], args[3]); if(!isRGBValid(args[4], args[5], args[6])) throw InvalidArgType(this->current_instruction, this->line_no); c = Colour(args[4], args[5], args[6]); internal_drawer->drawRectangle(a, b, c); } //************************************************************ void Interpreter::processRegularPolygon(const std::vector<fp_t> &args){ const int ARGCOUNT = 7; Point s; int n; fp_t side; Colour c; if(args.size() != ARGCOUNT) throw InvalidArgCount( this->current_instruction, this->line_no, ARGCOUNT, args.size() ); s = Point(args[0], args[1]); n = args[2]; side = args[3]; if(!isRGBValid(args[4], args[5], args[6])) throw InvalidArgType(this->current_instruction, this->line_no); c = Colour(args[4], args[5], args[6]); internal_drawer->drawRegularPolygon(s, n, side, c); } //************************************************************
/* * CharMemCache.cpp * * Created on: Jun 29, 2017 * Author: root */ #include "CharMemCache.h" #include "Log/Logger.h" #include "util.h" #include "SvrConfig.h" CCharMemCache * CCharMemCache::m_instance = 0; CacheTimeOut::CacheTimeOut() { } CacheTimeOut::~CacheTimeOut() { } void CacheTimeOut::AddCacheTimeout(int64 charid, DWORD64 time) { GUARD(CSimLock, obj, &m_timeLock); m_cacheTime[charid] = time; } void CacheTimeOut::AddDelCacheTimeout(int64 charid, DWORD64 time) { GUARD(CSimLock, obj, &m_timeLock); m_delCacheTime[charid] = time; } void CacheTimeOut::DeleteTimeout(int64 charid) { GUARD(CSimLock, obj, &m_timeLock); map<int64, DWORD64>::iterator it = m_cacheTime.find(charid); if(it != m_cacheTime.end()) { m_cacheTime.erase(it); } } void CacheTimeOut::DelCacheTime(int64 charid) { GUARD(CSimLock, obj, &m_timeLock); map<int64, DWORD64>::iterator itDel = m_delCacheTime.find(charid); if(itDel != m_delCacheTime.end()) { m_delCacheTime.erase(itDel); } } int CacheTimeOut::svr() { vector<int64> timeout; vector<int64> deltimeout; while(!m_flag) { { GUARD(CSimLock, obj, &m_timeLock); if(m_cacheTime.size() == 0 && m_delCacheTime.size() == 0 ) { obj.UnLock(); sleep(10); continue; } DWORD64 nowTime = CUtil::GetNowSecond(); map<int64, DWORD64>::iterator itDel = m_delCacheTime.begin(); for(; itDel!=m_delCacheTime.end(); ) { if(itDel->second <= nowTime) { deltimeout.push_back(itDel->first); m_cacheTime.erase(itDel->first); m_delCacheTime.erase(itDel++); } else { ++itDel; } } map<int64, DWORD64>::iterator it = m_cacheTime.begin(); for(; it!=m_cacheTime.end(); ++it) { if(it->second <= nowTime) { it->second = nowTime + SAVE_CHARCACHE_TODB; timeout.push_back(it->first); } } obj.UnLock(); } CCharMemCache::GetInstance()->SaveCacheToDB(timeout); CCharMemCache::GetInstance()->SaveCacheAndDelete(deltimeout); timeout.clear(); deltimeout.clear(); sleep(10); } return 0; } CCharMemCache::CCharMemCache() { if(m_timeout.Start(1)) { LOG_FATAL(FILEINFO, "Char memory cache thread start error"); } } CCharMemCache::~CCharMemCache() { m_timeout.End(); } int CCharMemCache::AddNewPlayer(int64 charid, Smart_Ptr<PlayerDBMgr> &player) { GUARD_WRITE(CRWLock, obj, &m_playerLock); m_allPlayer[charid] = player; obj.UnLock(); m_timeout.AddCacheTimeout(charid, CUtil::GetNowSecond() + SAVE_CHARCACHE_TODB); return 0; } bool CCharMemCache::IsPlayerInCache(int64 charid) { GUARD_READ(CRWLock, obj, &m_playerLock); map<int64,Smart_Ptr<PlayerDBMgr> >::iterator it = m_allPlayer.find(charid); if(it == m_allPlayer.end()) { return false; } return true; } void CCharMemCache::SaveCacheToDB(const std::vector<int64>& chars) { GUARD_READ(CRWLock, obj, &m_playerLock); vector<int64>::const_iterator itVec = chars.begin(); for(; itVec!=chars.end(); ++itVec) { map<int64,Smart_Ptr<PlayerDBMgr> >::iterator it = m_allPlayer.find(*itVec); if(it != m_allPlayer.end()) { if(it->second.Get()==NULL) continue; int res = it->second->SavePlayerStruct(*itVec); if(res==-1) { LOG_ERROR(FILEINFO, "save player info error,charID=%lld", *itVec); } } } } void CCharMemCache::SaveCacheAndDelete(const std::vector<int64>& chars) { GUARD_WRITE(CRWLock, obj, &m_playerLock); vector<int64>::const_iterator itVecDel = chars.begin(); for(; itVecDel!=chars.end(); ++itVecDel) { map<int64,Smart_Ptr<PlayerDBMgr> >::iterator it = m_allPlayer.find(*itVecDel); if(it != m_allPlayer.end()) { if(it->second.Get()) it->second->SavePlayerStruct(*itVecDel); m_allPlayer.erase(it); } } } bool CCharMemCache::SaveCacheToDB(int64 charid) { GUARD_READ(CRWLock, obj, &m_playerLock); map<int64,Smart_Ptr<PlayerDBMgr> >::iterator it = m_allPlayer.find(charid); if(it != m_allPlayer.end()) { int res = -1; res = it->second->SavePlayerStruct(charid); if(res == 1) { } else if(res == -1) { return false; } } else { return false; } return true; } void CCharMemCache::SaveCacheAndDelete(int64 charid) { GUARD_WRITE(CRWLock, obj, &m_playerLock); map<int64,Smart_Ptr<PlayerDBMgr> >::iterator it = m_allPlayer.find(charid); if(it != m_allPlayer.end()) { it->second->SavePlayerStruct(charid); m_allPlayer.erase(it); obj.UnLock(); m_timeout.DeleteTimeout(charid); } } void CCharMemCache::SaveToCache(PlayerInfo::SaveTypeInfo *info) { GUARD_WRITE(CRWLock, obj, &m_playerLock); map<int64,Smart_Ptr<PlayerDBMgr> >::iterator it = m_allPlayer.find(GET_PLAYER_CHARID(info->id())); if(it != m_allPlayer.end()) { for(int i=0; i<eCharStructMax; ++i) { if((info->type() >> i) & 0x1) { switch(i) { case eBaseInfo: { it->second->AddStruct(i, const_cast<PlayerInfo::BaseInfo *>(&info->bsinfo())); break; } default : { break; } } } } if(info->isdel()) { m_timeout.AddDelCacheTimeout(GET_PLAYER_CHARID(info->id()),CUtil::GetNowSecond() + DELETE_CHARCACHE_TIMEOUT); it->second->SetFlag(eBaseInfo, true); it->second->SavePlayerStruct(GET_PLAYER_CHARID(info->id())); obj.UnLock(); } } } bool CCharMemCache::GetPlayerInfo(int64 charid, PlayerInfo::PlayerInfo *info) { GUARD_READ(CRWLock, obj, &m_playerLock); map<int64,Smart_Ptr<PlayerDBMgr> >::iterator it = m_allPlayer.find(charid); if(it != m_allPlayer.end()) { it->second->GetPlayerInfo(info); } else { return false; } obj.UnLock(); m_timeout.DelCacheTime(charid); return true; } bool CCharMemCache::GetPlayerInfo(int id, int64 charid, google::protobuf::Message *content) { GUARD_READ(CRWLock, obj, &m_playerLock); map<int64,Smart_Ptr<PlayerDBMgr> >::iterator it = m_allPlayer.find(charid); if(it != m_allPlayer.end()) { it->second->GetPlayerInfo(id, content); } else { return false; } obj.UnLock(); m_timeout.DelCacheTime(charid); return true; }
//2016-12-09 //2016-12-10 //2016-12-11 #pragma once #include "HSRIFF.hpp" #include <mmreg.h> /* 以下クラス定義 */ //__CHSRiffReaderBaseTemplate<Type> //__CHSRiffReaderBaseTemplate<Type> template <typename Type> class __CHSWaveReaderBaseTemplate : public __CHSRiffReaderBaseTemplate<Type> { private: union LocalFormatData { WAVEFORMATEX wfex; PCMWAVEFORMAT pcm_format; ADPCMWAVEFORMAT adpcm_format; IMAADPCMWAVEFORMAT imaadpcm_format; WAVEFORMATEXTENSIBLE extensible_format; }; THSRiffChunkInfo formatChunkInfo; THSRiffChunkInfo dataChunkInfo; LocalFormatData localFormatData; bool AdditionalCheckProcess ( void ) { if ( this->CheckType ( "WAVE" ) ) { if ( this->GetChunkInfo ( "fmt" , &this->formatChunkInfo ) ) { if ( this->GetChunkInfo ( "data" , &this->dataChunkInfo ) ) { memset ( &this->localFormatData , 0 , sizeof ( LocalFormatData ) ); if ( this->ReadFormatChunk ( &this->localFormatData , 0 , sizeof ( LocalFormatData ) ) ) { return true; } } } } return false; } void __WaveReaderInit ( void ) { memset ( &this->formatChunkInfo , 0 , sizeof ( THSRiffChunkInfo ) ); memset ( &this->dataChunkInfo , 0 , sizeof ( THSRiffChunkInfo ) ); } public: __CHSWaveReaderBaseTemplate ( ) : __CHSRiffReaderBaseTemplate<Type> (){ this->__WaveReaderInit ( ); } __CHSWaveReaderBaseTemplate (T *lpszFilePath ) : __CHSRiffReaderBaseTemplate<Type>(){ this->__WaveReaderInit ( ); this->Open ( lpszFilePath ); } uint32_t GetDataChunkSize ( void ) { return this->dataChunkInfo.Header.DataSize; } uint32_t ReadDataChunk ( void *lpData , uint32_t offset , uint32_t readsize ) { return this->ReadChunkData ( "data" , lpData , offset , readsize ); } uint32_t GetFormatChunkSize ( void ) { return this->formatChunkInfo.Header.DataSize; } uint32_t ReadFormatChunk ( void *lpData , uint32_t offset , uint32_t readsize ) { return this->ReadChunkData ( "fmt" , lpData , offset , readsize ); } bool HasExtendedFormatData ( void ) { return ( this->localFormatData.wfex.cbSize != 0 ); } uint32_t GetExtendedFormatDataSize ( void ) { return this->localFormatData.wfex.cbSize; } uint32_t ReadExtendedFormatData ( void *lpData , uint32_t offset , uint32_t readsize ) { return this->ReadChunkData ( "fmt" , lpData , offset + sizeof(WAVEFORMATEX) , readsize ); } bool GetFormat ( WAVEFORMATEX *lpwfex ) { if ( lpwfex ) { *lpwfex = this->localFormatData.wfex; return true; } return false; } bool GetFormat ( PCMWAVEFORMAT *lppcm_format ) { if ( lppcm_format ) { *lppcm_format = this->localFormatData.pcm_format; return true; } return false; } bool GetFormat ( ADPCMWAVEFORMAT *lpadpcm_format ) { if ( lpadpcm_format ) { *lpadpcm_format = this->localFormatData.adpcm_format; return true; } return false; } bool GetFormat ( IMAADPCMWAVEFORMAT *lpimaadpcm_format ) { if ( lpimaadpcm_format ) { *lpimaadpcm_format = this->localFormatData.imaadpcm_format; return true; } return false; } bool GetFormat ( WAVEFORMATEXTENSIBLE *lpextensible_format ) { if ( lpextensible_format ) { *lpextensible_format = this->localFormatData.extensible_format; return true; } return false; } }; using CHSWaveReaderA = __CHSWaveReaderBaseTemplate<char>; using CHSWaveReaderW = __CHSWaveReaderBaseTemplate<wchar_t>; //__CHSRiffWriterBaseTemplate<Type> template <typename Type> class __CHSWaveWriterBaseTemplate : public __CHSRiffWriterBaseTemplate<Type> { private: virtual bool CreateAdditionalProcess ( void ) { return this->WriteRiffType("WAVE"); } public: bool BeginDataChunk ( void ) { return this->BeginChunk ( "data" ); } bool AdditionalDataChunkContent ( void *lpData , uint32_t size ) { uint32_t currentChunk = *reinterpret_cast< uint32_t* >( this->m_ChunkInfo.Header.Name ); if ( currentChunk == HSRIFF_MAGICNUMBER_DATACHUNK ) { return this->AdditionalChunkData ( lpData , size ); } return false; } bool EndDataChunk ( void ) { uint32_t currentChunk = *reinterpret_cast< uint32_t* >( this->m_ChunkInfo.Header.Name ); if ( currentChunk == HSRIFF_MAGICNUMBER_DATACHUNK ) { return this->EndChunk ( ); } return false; } bool WriteFormatChunk ( WAVEFORMATEX wfex ) { return this->WriteFormatChunkType ( wfex ); } bool WriteFormatChunk ( PCMWAVEFORMAT pcm_format ) { return this->WriteFormatChunkType ( pcm_format ); } bool WriteFormatChunk ( ADPCMWAVEFORMAT adpcm_format ) { return this->WriteFormatChunkType ( adpcm_format ); } bool WriteFormatChunk ( IMAADPCMWAVEFORMAT imaadpcm_format ) { return this->WriteFormatChunkType ( imaadpcm_format ); } bool WriteFormatChunk ( WAVEFORMATEXTENSIBLE extensible_format ) { return this->WriteFormatChunkType ( extensible_format ); } bool WriteFormatChunkCostom ( void *lpFormat , uint32_t size ) { return this->WriteChunk ( "fmt" , lpFormat , size ); } template<typename U> bool WriteFormatChunkType ( U Format ) { return this->WriteChunkType( "fmt" , Format ); } }; using CHSWaveWriterA = __CHSWaveWriterBaseTemplate<char>; using CHSWaveWriterW = __CHSWaveWriterBaseTemplate<wchar_t>;
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/ObjectMacros.h" #include "UObject/ScriptMacros.h" PRAGMA_DISABLE_DEPRECATION_WARNINGS #ifdef SCIFISIDESCROLLER_SciFiSideScrollerGameMode_generated_h #error "SciFiSideScrollerGameMode.generated.h already included, missing '#pragma once' in SciFiSideScrollerGameMode.h" #endif #define SCIFISIDESCROLLER_SciFiSideScrollerGameMode_generated_h #define SciFiSideScroller_Source_SciFiSideScroller_SciFiSideScrollerGameMode_h_12_SPARSE_DATA #define SciFiSideScroller_Source_SciFiSideScroller_SciFiSideScrollerGameMode_h_12_RPC_WRAPPERS #define SciFiSideScroller_Source_SciFiSideScroller_SciFiSideScrollerGameMode_h_12_RPC_WRAPPERS_NO_PURE_DECLS #define SciFiSideScroller_Source_SciFiSideScroller_SciFiSideScrollerGameMode_h_12_INCLASS_NO_PURE_DECLS \ private: \ static void StaticRegisterNativesASciFiSideScrollerGameMode(); \ friend struct Z_Construct_UClass_ASciFiSideScrollerGameMode_Statics; \ public: \ DECLARE_CLASS(ASciFiSideScrollerGameMode, AGameModeBase, COMPILED_IN_FLAGS(0 | CLASS_Transient | CLASS_Config), CASTCLASS_None, TEXT("/Script/SciFiSideScroller"), SCIFISIDESCROLLER_API) \ DECLARE_SERIALIZER(ASciFiSideScrollerGameMode) #define SciFiSideScroller_Source_SciFiSideScroller_SciFiSideScrollerGameMode_h_12_INCLASS \ private: \ static void StaticRegisterNativesASciFiSideScrollerGameMode(); \ friend struct Z_Construct_UClass_ASciFiSideScrollerGameMode_Statics; \ public: \ DECLARE_CLASS(ASciFiSideScrollerGameMode, AGameModeBase, COMPILED_IN_FLAGS(0 | CLASS_Transient | CLASS_Config), CASTCLASS_None, TEXT("/Script/SciFiSideScroller"), SCIFISIDESCROLLER_API) \ DECLARE_SERIALIZER(ASciFiSideScrollerGameMode) #define SciFiSideScroller_Source_SciFiSideScroller_SciFiSideScrollerGameMode_h_12_STANDARD_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ SCIFISIDESCROLLER_API ASciFiSideScrollerGameMode(const FObjectInitializer& ObjectInitializer); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(ASciFiSideScrollerGameMode) \ DECLARE_VTABLE_PTR_HELPER_CTOR(SCIFISIDESCROLLER_API, ASciFiSideScrollerGameMode); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(ASciFiSideScrollerGameMode); \ private: \ /** Private move- and copy-constructors, should never be used */ \ SCIFISIDESCROLLER_API ASciFiSideScrollerGameMode(ASciFiSideScrollerGameMode&&); \ SCIFISIDESCROLLER_API ASciFiSideScrollerGameMode(const ASciFiSideScrollerGameMode&); \ public: #define SciFiSideScroller_Source_SciFiSideScroller_SciFiSideScrollerGameMode_h_12_ENHANCED_CONSTRUCTORS \ private: \ /** Private move- and copy-constructors, should never be used */ \ SCIFISIDESCROLLER_API ASciFiSideScrollerGameMode(ASciFiSideScrollerGameMode&&); \ SCIFISIDESCROLLER_API ASciFiSideScrollerGameMode(const ASciFiSideScrollerGameMode&); \ public: \ DECLARE_VTABLE_PTR_HELPER_CTOR(SCIFISIDESCROLLER_API, ASciFiSideScrollerGameMode); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(ASciFiSideScrollerGameMode); \ DEFINE_DEFAULT_CONSTRUCTOR_CALL(ASciFiSideScrollerGameMode) #define SciFiSideScroller_Source_SciFiSideScroller_SciFiSideScrollerGameMode_h_12_PRIVATE_PROPERTY_OFFSET #define SciFiSideScroller_Source_SciFiSideScroller_SciFiSideScrollerGameMode_h_9_PROLOG #define SciFiSideScroller_Source_SciFiSideScroller_SciFiSideScrollerGameMode_h_12_GENERATED_BODY_LEGACY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ SciFiSideScroller_Source_SciFiSideScroller_SciFiSideScrollerGameMode_h_12_PRIVATE_PROPERTY_OFFSET \ SciFiSideScroller_Source_SciFiSideScroller_SciFiSideScrollerGameMode_h_12_SPARSE_DATA \ SciFiSideScroller_Source_SciFiSideScroller_SciFiSideScrollerGameMode_h_12_RPC_WRAPPERS \ SciFiSideScroller_Source_SciFiSideScroller_SciFiSideScrollerGameMode_h_12_INCLASS \ SciFiSideScroller_Source_SciFiSideScroller_SciFiSideScrollerGameMode_h_12_STANDARD_CONSTRUCTORS \ public: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #define SciFiSideScroller_Source_SciFiSideScroller_SciFiSideScrollerGameMode_h_12_GENERATED_BODY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ SciFiSideScroller_Source_SciFiSideScroller_SciFiSideScrollerGameMode_h_12_PRIVATE_PROPERTY_OFFSET \ SciFiSideScroller_Source_SciFiSideScroller_SciFiSideScrollerGameMode_h_12_SPARSE_DATA \ SciFiSideScroller_Source_SciFiSideScroller_SciFiSideScrollerGameMode_h_12_RPC_WRAPPERS_NO_PURE_DECLS \ SciFiSideScroller_Source_SciFiSideScroller_SciFiSideScrollerGameMode_h_12_INCLASS_NO_PURE_DECLS \ SciFiSideScroller_Source_SciFiSideScroller_SciFiSideScrollerGameMode_h_12_ENHANCED_CONSTRUCTORS \ private: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS template<> SCIFISIDESCROLLER_API UClass* StaticClass<class ASciFiSideScrollerGameMode>(); #undef CURRENT_FILE_ID #define CURRENT_FILE_ID SciFiSideScroller_Source_SciFiSideScroller_SciFiSideScrollerGameMode_h PRAGMA_ENABLE_DEPRECATION_WARNINGS
/************************************************************************************** Programme: point.cpp Acteur: Kponaho Anne-Laure Magnane Date de création: 07/04/21 But du programme: Definition des fonctions de l'objet point* **************************************************************************************/ #include "point.h" point::point() { _x = _y = 0; _color = 15; } point::point(int x, int y) { _x = x; _y = y; _color = 15; } point::~point() { _x = _y = _color = 0; } point::point(const point& p) { _x = p._x; _y = p._y; _color = p._color; } void point::setX(int x) { _x = x; } void point::setY(int y) { _y = y; } void point::setColor(int color) { _color = color; } void point::setPosition(int x, int y) { setX(x); setY(y); } int point::getX() const { return _x; } int point::getY() const { return _y; } int point::getColor() const { return _color; } const point& point::operator=(const point& p) { _x = p._x; _y = p._y; _color = p._color; return *this; } bool point::operator==(const point& p) const { if (p._x == _x && p._y == _y) { return true; } return false; } bool point::operator!=(const point& p) const { return !(operator==(p)); } point point::operator+(const point& p) { point result; //l’appel de l’operator+ peut se faire aussi result._x = _x + p._x; result._y = _y + p._y; return result; } point point::operator-(const point& p) { point result; //l’appel de l’operator+ peut se faire aussi result._x = _x - p._x; result._y = _y - p._y; return result; } void point::read(istream& input) { char temp; input >> temp >> _x >> temp >> _y >> temp; } void point::print(ostream& output) const { output << "(" << _x << "," << _y << ")"; } void point::draw(ostream& output) const { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), _color); gotoxy(_x, _y); output << "*"; //on dessine une petite étoile, à mettre ds le draw SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7); } float distance(const point& p1, const point& p2) { return sqrt((p1._x + p2._x) * (p1._y + p2._y)); } void viderBuffer() { cin.clear(); cin.seekg(0, ios::end); if (!cin.fail()) cin.ignore(); else cin.clear(); } istream& operator>>(istream& input, point& p) { p.read(input); return input; } ostream& operator<<(ostream& output, point& p) { p.print(output); return output; } void gotoxy(int xpos, int ypos) { COORD scrn; HANDLE hOuput = GetStdHandle(STD_OUTPUT_HANDLE); scrn.X = xpos; scrn.Y = ypos; SetConsoleCursorPosition(hOuput, scrn); }
#include <bits/stdc++.h> using namespace std; int main(){ string s, t, r; cin >> s >> t; r = s + t; int n = stoi(r); for(int i=1; i<=1000; i++){ if(n == i*i){ cout << "Yes" << endl; return 0; } } cout << "No" << endl; return 0; }
// Fill out your copyright notice in the Description page of Project Settings. #include "TankMovementComponent.h" #include "TankTrack.h" #include "DrawDebugHelpers.h" void UTankMovementComponent::Initialise(UTankTrack* LeftTrackToSet, UTankTrack* RightTrackToSet) { if (!ensureAlways (LeftTrackToSet && RightTrackToSet)) return; LeftTrack = LeftTrackToSet; RightTrack = RightTrackToSet; } // TODO PREVENT DOUBLE SPEED WHEN TWO INPUTS ARE GIVEN void UTankMovementComponent::IntendMoveFoward(float Throw) { if (!ensureAlways(LeftTrack && RightTrack)) return; LeftTrack->AddThrottle(Throw); RightTrack->AddThrottle(Throw); } void UTankMovementComponent::IntendMoveClockwise(float Throw) { if (!ensureAlways(LeftTrack && RightTrack)) return; LeftTrack->AddThrottle(Throw); RightTrack->AddThrottle(-Throw); } void UTankMovementComponent::RequestDirectMove(const FVector& MoveVelocity, bool bForceMaxSpeed) { UE_LOG(LogTemp, Warning, TEXT("movevelocity of %s: %s"), *GetOwner()->GetName(), *MoveVelocity.ToString()); FVector AIForwardIntetion = MoveVelocity.GetSafeNormal(); FVector TankFoward = GetOwner()->GetActorForwardVector().GetSafeNormal() ; float FowardIntention = FVector::DotProduct(AIForwardIntetion, TankFoward); FVector RotateIntention = FVector::CrossProduct(AIForwardIntetion, TankFoward); IntendMoveClockwise(RotateIntention.Z); IntendMoveFoward(FowardIntention); }
#define PI 3.1415926535 // pi #include <dfr_tank.h> #include <SoftwareSerial.h> #include "Enes100.h" // Global variables float theta; // tank angle in rad float targetTheta; // Enter the target angle in the space here int minMotorValue = 160; // minimum input value which will produce a turning movement in the tank float k = (255 - minMotorValue) / PI; // proportional controller for turning speed (“gain”) float errTheta; // variable to hold the error in theta float errX; // variable to hold the error in x float errY; // variable to hold the error in y int motorRate = 0; int dist; // resistance value provided by distance sensor float xMission; // variable to hold x location of mission site float yMission; // variable to hold y location of mission site float xPos; // tank x coordinate in m float yPos; // tank y coordinate in m boolean early = true; /* establish motor control ports */ int leftD = 4; int leftS = 5; int rightS = 6; int rightD = 7; int missionState; // value which sets the OSV operational mode /* missionState values 0 in start orientation 1 moving up and down in start 2 moving left and right 3 navigated 4 3 move forward until a specific y coord 4 move forward until an obstacle is detected 5 perform mission elements */ DFRTank tank; Enes100 enes("JediArms", WATER, 114, 8, 9); //REPLACE INPUT3 WITH MARKER ID void setup() { Serial.begin(9600); //enes.println("RF WORKS"); // SoftwareSerial mySerial(8, 9); tank.init(); enes.retrieveDestination(); // get site location xMission = enes.destination.x; yMission = enes.destination.y; enes.print("Mission y = "); enes.println(yMission); enes.updateLocation(); // get tank position theta = enes.location.theta; xPos = enes.location.x; yPos = enes.location.y; missionState = 0; enes.println("SETUP INITIALIZED"); } void loop() { enes.updateLocation(); theta = enes.location.theta; xPos = enes.location.x; yPos = enes.location.y; if (missionState == 0) { enes.println("missionState=0"); if (yPos < yMission) // tank is below destination { targetTheta = PI / 2; missionState = 1; } else if (yPos > yMission) // tank is above destination { targetTheta = 3 * PI / 2; missionState = 1; } else // tank is at same y coord as destination { targetTheta = 0; missionState = 2; } turnTo(targetTheta); } else if (missionState == 1) { enes.println("missionState=1"); enes.updateLocation(); yPos = enes.location.y; errY = yPos - yMission; enes.print("Error in y: "); enes.println(errY); while (errY > .05 || errY < -.05) { digitalWrite(leftD, HIGH); digitalWrite(rightD, HIGH); analogWrite(leftS, 255); analogWrite(rightS, 255); delay (250); analogWrite(leftS, 0); analogWrite(rightS, 0); delay(250); enes.updateLocation(); yPos = enes.location.y; errY = yPos - yMission; turnTo(targetTheta); } enes.print("Reached destination yPos of "); enes.println(yPos); if(early) { missionState = 2; } else { missionState = 3; } } else if (missionState == 2) { early = false; turnTo(0); enes.println("missionState=2"); enes.updateLocation(); xPos = enes.location.x; errX = xMission - xPos; //boolean hitObstacle = false; while (errX > .05 || errX < -.05) { dist = analogRead(6); if (dist > 200) { turnTo(3 * PI / 2); digitalWrite(leftD, HIGH); digitalWrite(rightD, HIGH); analogWrite(leftS, 255); analogWrite(rightS, 255); delay(1000); turnTo(0); enes.println("Hit obstacle"); } else { turnTo(calcHeading()); digitalWrite(leftD, HIGH); digitalWrite(rightD, HIGH); analogWrite(leftS, 255); analogWrite(rightS, 255); delay(300); analogWrite(leftS, 0); analogWrite(rightS, 0); delay(100); /*digitalWrite(leftD, HIGH); digitalWrite(rightD, HIGH); analogWrite(leftS, 255); analogWrite(rightS, 255); delay(250); analogWrite(leftS, 0); analogWrite(rightS, 0); delay(250); */ } enes.updateLocation(); xPos = enes.location.x; enes.print("XPOS = "); enes.println(xPos); errX = xPos - xMission; delay(100); enes.print("Error in x: "); enes.println(errX); /*if(errX <.05) { enes.println("Reached x coord of destination"); missionState = 3; } */ } analogWrite(leftS, 0); analogWrite(rightS, 0); //missionState = 5; } /*else if(missionState==3) { enes.navigated(); missionState= -1; } */ else if(missionState==5) { while(calcDistance()>.05) { turnTo(calcHeading()); digitalWrite(leftD, HIGH); digitalWrite(rightD, HIGH); analogWrite(leftS, 255); analogWrite(rightS, 255); delay(100); } missionState = 3; analogWrite(leftS, 0); analogWrite(rightS, 0); } } float calcHeading() { float desiredHeading; enes.updateLocation(); xPos = enes.location.x; yPos = enes.location.y; desiredHeading = atan((yMission-yPos)/(xMission-xPos)); enes.print("Turning to "); enes.println(desiredHeading); return desiredHeading; } float calcDistance() { float distance; enes.updateLocation(); xPos = enes.location.x; yPos = enes.location.y; distance = sqrt(((yMission-yPos)*(yMission-yPos))+((xMission-xPos)*(xMission-xPos))); return distance; } /* turns the OSV to angle theta_desired when missionState == 1 */ void turnTo(float thetaDesired) { boolean turnCompleted = false; /* calculates the error in theta */ while (!turnCompleted) { enes.updateLocation(); theta = enes.location.theta;// update theta if ((theta - thetaDesired <= PI) && (theta - thetaDesired >= 0)) { errTheta = (theta - thetaDesired); // compute error TURN RIGHT (POSITIVE) } else if (theta - thetaDesired > PI) { errTheta = -((2 * PI - theta) + thetaDesired); // compute error TURN LEFT (NEGATIVE) } else if ((theta - thetaDesired >= -PI) && (theta - thetaDesired < 0)) { errTheta = (theta - thetaDesired); // compute error TURN LEFT (NEGATIVE) } else if (theta - thetaDesired < -PI) { errTheta = ((2 * PI - thetaDesired) + theta); // compute error TURN RIGHT (POSITIVE) } /* turns tank to desired angle theta */ if (errTheta > 0.05 || errTheta < -0.05) // only compute if not converged { if (abs(errTheta) < .1) { motorRate = minMotorValue; } else { motorRate = minMotorValue + abs(errTheta) * k; } if (errTheta < 0) { digitalWrite(leftD, LOW); digitalWrite(rightD, HIGH); } else { digitalWrite(leftD, HIGH); digitalWrite(rightD, LOW); } analogWrite(leftS, motorRate); analogWrite(rightS, motorRate); enes.println(errTheta); } else { analogWrite(rightS, 0); analogWrite(leftS, 0); turnCompleted = true; } delay(250); analogWrite(rightS, 0); analogWrite(leftS, 0); delay(250); enes.updateLocation(); theta = enes.location.theta;// update theta } enes.print("Reached target angle of "); enes.println(thetaDesired); } /* Steps: 1 orient and get to proper y pos in starting zone 2 travel straight in x direction A obstacle detection B obstacle avoidance C obstacle passing 3 travel to mission site */
#include "vectorChapter17.h" vector:: vector (int s) // Конструктор : sz{s}, elem { new double[s]} // Выделение памяти { for (int i = 0; i<s; ++i) elem[i] = 0; }
// Copyright Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/GeneratedCppIncludes.h" #include "ShooterStarter/ShooterStarterPlayerController.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodeShooterStarterPlayerController() {} // Cross Module References SHOOTERSTARTER_API UClass* Z_Construct_UClass_AShooterStarterPlayerController_NoRegister(); SHOOTERSTARTER_API UClass* Z_Construct_UClass_AShooterStarterPlayerController(); ENGINE_API UClass* Z_Construct_UClass_APlayerController(); UPackage* Z_Construct_UPackage__Script_ShooterStarter(); UMG_API UClass* Z_Construct_UClass_UUserWidget_NoRegister(); COREUOBJECT_API UClass* Z_Construct_UClass_UClass(); // End Cross Module References void AShooterStarterPlayerController::StaticRegisterNativesAShooterStarterPlayerController() { } UClass* Z_Construct_UClass_AShooterStarterPlayerController_NoRegister() { return AShooterStarterPlayerController::StaticClass(); } struct Z_Construct_UClass_AShooterStarterPlayerController_Statics { static UObject* (*const DependentSingletons[])(); #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[]; #endif #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_HUDScreen_MetaData[]; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_HUDScreen; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_RestartDelay_MetaData[]; #endif static const UE4CodeGen_Private::FFloatPropertyParams NewProp_RestartDelay; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_HUDClass_MetaData[]; #endif static const UE4CodeGen_Private::FClassPropertyParams NewProp_HUDClass; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_WinScreenClass_MetaData[]; #endif static const UE4CodeGen_Private::FClassPropertyParams NewProp_WinScreenClass; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_LoseScreenClass_MetaData[]; #endif static const UE4CodeGen_Private::FClassPropertyParams NewProp_LoseScreenClass; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; static const FCppClassTypeInfoStatic StaticCppClassTypeInfo; static const UE4CodeGen_Private::FClassParams ClassParams; }; UObject* (*const Z_Construct_UClass_AShooterStarterPlayerController_Statics::DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_APlayerController, (UObject* (*)())Z_Construct_UPackage__Script_ShooterStarter, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AShooterStarterPlayerController_Statics::Class_MetaDataParams[] = { { "Comment", "/**\n * \n */" }, { "HideCategories", "Collision Rendering Utilities|Transformation" }, { "IncludePath", "ShooterStarterPlayerController.h" }, { "ModuleRelativePath", "ShooterStarterPlayerController.h" }, }; #endif #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AShooterStarterPlayerController_Statics::NewProp_HUDScreen_MetaData[] = { { "EditInline", "true" }, { "ModuleRelativePath", "ShooterStarterPlayerController.h" }, }; #endif const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_AShooterStarterPlayerController_Statics::NewProp_HUDScreen = { "HUDScreen", nullptr, (EPropertyFlags)0x0040000000080008, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AShooterStarterPlayerController, HUDScreen), Z_Construct_UClass_UUserWidget_NoRegister, METADATA_PARAMS(Z_Construct_UClass_AShooterStarterPlayerController_Statics::NewProp_HUDScreen_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_AShooterStarterPlayerController_Statics::NewProp_HUDScreen_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AShooterStarterPlayerController_Statics::NewProp_RestartDelay_MetaData[] = { { "Category", "ShooterStarterPlayerController" }, { "ModuleRelativePath", "ShooterStarterPlayerController.h" }, }; #endif const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_AShooterStarterPlayerController_Statics::NewProp_RestartDelay = { "RestartDelay", nullptr, (EPropertyFlags)0x0040000000000001, UE4CodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AShooterStarterPlayerController, RestartDelay), METADATA_PARAMS(Z_Construct_UClass_AShooterStarterPlayerController_Statics::NewProp_RestartDelay_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_AShooterStarterPlayerController_Statics::NewProp_RestartDelay_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AShooterStarterPlayerController_Statics::NewProp_HUDClass_MetaData[] = { { "Category", "ShooterStarterPlayerController" }, { "ModuleRelativePath", "ShooterStarterPlayerController.h" }, }; #endif const UE4CodeGen_Private::FClassPropertyParams Z_Construct_UClass_AShooterStarterPlayerController_Statics::NewProp_HUDClass = { "HUDClass", nullptr, (EPropertyFlags)0x0044000000000001, UE4CodeGen_Private::EPropertyGenFlags::Class, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AShooterStarterPlayerController, HUDClass), Z_Construct_UClass_UUserWidget_NoRegister, Z_Construct_UClass_UClass, METADATA_PARAMS(Z_Construct_UClass_AShooterStarterPlayerController_Statics::NewProp_HUDClass_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_AShooterStarterPlayerController_Statics::NewProp_HUDClass_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AShooterStarterPlayerController_Statics::NewProp_WinScreenClass_MetaData[] = { { "Category", "ShooterStarterPlayerController" }, { "ModuleRelativePath", "ShooterStarterPlayerController.h" }, }; #endif const UE4CodeGen_Private::FClassPropertyParams Z_Construct_UClass_AShooterStarterPlayerController_Statics::NewProp_WinScreenClass = { "WinScreenClass", nullptr, (EPropertyFlags)0x0044000000000001, UE4CodeGen_Private::EPropertyGenFlags::Class, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AShooterStarterPlayerController, WinScreenClass), Z_Construct_UClass_UUserWidget_NoRegister, Z_Construct_UClass_UClass, METADATA_PARAMS(Z_Construct_UClass_AShooterStarterPlayerController_Statics::NewProp_WinScreenClass_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_AShooterStarterPlayerController_Statics::NewProp_WinScreenClass_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AShooterStarterPlayerController_Statics::NewProp_LoseScreenClass_MetaData[] = { { "Category", "ShooterStarterPlayerController" }, { "ModuleRelativePath", "ShooterStarterPlayerController.h" }, }; #endif const UE4CodeGen_Private::FClassPropertyParams Z_Construct_UClass_AShooterStarterPlayerController_Statics::NewProp_LoseScreenClass = { "LoseScreenClass", nullptr, (EPropertyFlags)0x0044000000000001, UE4CodeGen_Private::EPropertyGenFlags::Class, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AShooterStarterPlayerController, LoseScreenClass), Z_Construct_UClass_UUserWidget_NoRegister, Z_Construct_UClass_UClass, METADATA_PARAMS(Z_Construct_UClass_AShooterStarterPlayerController_Statics::NewProp_LoseScreenClass_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_AShooterStarterPlayerController_Statics::NewProp_LoseScreenClass_MetaData)) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_AShooterStarterPlayerController_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AShooterStarterPlayerController_Statics::NewProp_HUDScreen, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AShooterStarterPlayerController_Statics::NewProp_RestartDelay, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AShooterStarterPlayerController_Statics::NewProp_HUDClass, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AShooterStarterPlayerController_Statics::NewProp_WinScreenClass, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AShooterStarterPlayerController_Statics::NewProp_LoseScreenClass, }; const FCppClassTypeInfoStatic Z_Construct_UClass_AShooterStarterPlayerController_Statics::StaticCppClassTypeInfo = { TCppClassTypeTraits<AShooterStarterPlayerController>::IsAbstract, }; const UE4CodeGen_Private::FClassParams Z_Construct_UClass_AShooterStarterPlayerController_Statics::ClassParams = { &AShooterStarterPlayerController::StaticClass, "Game", &StaticCppClassTypeInfo, DependentSingletons, nullptr, Z_Construct_UClass_AShooterStarterPlayerController_Statics::PropPointers, nullptr, UE_ARRAY_COUNT(DependentSingletons), 0, UE_ARRAY_COUNT(Z_Construct_UClass_AShooterStarterPlayerController_Statics::PropPointers), 0, 0x009002A4u, METADATA_PARAMS(Z_Construct_UClass_AShooterStarterPlayerController_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_AShooterStarterPlayerController_Statics::Class_MetaDataParams)) }; UClass* Z_Construct_UClass_AShooterStarterPlayerController() { static UClass* OuterClass = nullptr; if (!OuterClass) { UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_AShooterStarterPlayerController_Statics::ClassParams); } return OuterClass; } IMPLEMENT_CLASS(AShooterStarterPlayerController, 1922675053); template<> SHOOTERSTARTER_API UClass* StaticClass<AShooterStarterPlayerController>() { return AShooterStarterPlayerController::StaticClass(); } static FCompiledInDefer Z_CompiledInDefer_UClass_AShooterStarterPlayerController(Z_Construct_UClass_AShooterStarterPlayerController, &AShooterStarterPlayerController::StaticClass, TEXT("/Script/ShooterStarter"), TEXT("AShooterStarterPlayerController"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(AShooterStarterPlayerController); PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif
// Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. // If target is not found in the array, return [-1, -1]. // You must write an algorithm with O(log n) runtime complexity. class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { vector<int> res; int n = nums.size(); if(n < 1) { res.push_back(-1); res.push_back(-1); return res; } int a = lower_bound(nums.begin(), nums.end(), target) - nums.begin(); int b = upper_bound(nums.begin(), nums.end(), target) - nums.begin()-1; cout << a << " " << b << endl; // return res; if(a >= n || nums[a] != target){ res.push_back(-1); res.push_back(-1); return res; } res.push_back(a); res.push_back(b); return res; } };
#include "used_rolename_merger.hpp" #include "tools/log.hpp" #include "utils/assert.hpp" #include "proto/data_global.pb.h" namespace nora { void used_rolename_merger::start() { ASSERT(st_); st_->async_call( [this] { ILOG << "merge used_rolenames begin"; load(); }); } void used_rolename_merger::load() { ASSERT(st_->check_in_thread()); loading_count_ += 2; auto from_db_msg = make_shared<db::message>("load_used_rolenames", db::message::req_type::rt_select, [this] (const auto& msg) { this->on_db_load_done(msg); }); from_db_->push_message(from_db_msg, st_); auto to_db_msg = make_shared<db::message>("load_used_rolenames", db::message::req_type::rt_select, [this] (const auto& msg) { this->on_db_load_done(msg); }); to_db_->push_message(to_db_msg, st_); } void used_rolename_merger::on_db_load_done(const shared_ptr<db::message>& msg) { ASSERT(st_->check_in_thread()); loading_count_ -= 1; for (const auto& i : msg->results()) { ASSERT(i.size() == 1); const auto& data = boost::any_cast<string>(i[0]); pd::used_rolename_array used_rolenames; used_rolenames.ParseFromString(data); for (const auto& name : used_rolenames.used_names()) { used_rolenames_.insert(name); } } if (loading_count_ == 0) { auto db_msg = make_shared<db::message>("update_used_rolenames", db::message::req_type::rt_update, [this] (const auto& msg) { TOOL_TLOG << "merge used_rolenames done"; if (done_cb_) { done_cb_(); } }); pd::used_rolename_array used_rolenames; for (const auto& name : used_rolenames_) { used_rolenames.add_used_names(name); } string data; used_rolenames.SerializeToString(&data); db_msg->push_param(data); to_db_->push_message(db_msg, st_); } } }
// Fill out your copyright notice in the Description page of Project Settings. #include "ButtonInteractorComponent.h" #include "ActionComponent.h" bool UButtonInteractorComponent::Interact(UObjectInfo* info) { GetOwner()->FindComponentByClass<UActionComponent>()->DoAction(); return true; }
// // Created by jerry on 2/17/2021. // #ifndef COMP345_WINTER2021_PLAYERDRIVER_H #define COMP345_WINTER2021_PLAYERDRIVER_H namespace player{ int main(); } #endif //COMP345_WINTER2021_PLAYERDRIVER_H
#include "log_serverd.hpp" #include "log.hpp" #include "utils/service_thread.hpp" #include "utils/process_utils.hpp" #include "utils/time_utils.hpp" #include "config/options_ptts.hpp" #include "config/utils.hpp" using namespace nora; int main(int argc, char **argv) { srand(time(0)); deamonize(argv); write_pid_file("log_serverd_pid"); PTTS_LOAD(options); auto ptt = PTTS_GET_COPY(options, 1u); init_log_for_log_server("log_serverd", ptt.level()); PTTS_MVP(options); auto st = make_shared<service_thread>("main"); clock::instance().start(st); auto lsd = make_shared<log_serverd::log_serverd>(st); st->async_call( [lsd] { lsd->start(); }); LOG_ILOG << "start"; st->run(); return 0; }
/* The MIT License (MIT) Copyright (c) 2017 Paul Marc Liu Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef CONTROLLER_HPP_ #define CONTROLLER_HPP_ #include "model.hpp" class CKnight_Controller { private: CModel_Data *data; public: /** * * @param in */ CKnight_Controller(CModel_Data *in); /** * Will search all paths from start to end * * @param start * @param end * @return */ int MakeMove(BoardPosition start, BoardPosition end); /** * Will check whether this is a valid move * @param start * @param end * @return */ int IsValidKnightMove(BoardPosition start, BoardPosition end); /** * * @param index * @param start * @param next * @return */ int GetNextPositionAtIndex(int index, BoardPosition start, BoardPosition *next); // visited? /** * * @param index * @param start * @return */ BoardPosition GetRawNextPositionFromIndex(int index, BoardPosition start); /** * * @param start * @param end * @param next * @return */ int ComputeMoveFromDistance(BoardPosition start, BoardPosition end, BoardPosition *next); /** * */ void ClearMatrices(void){ data->ClearMatrices(); } /** * * @param in * @param value * @return */ int Set_At(BoardPosition in, char value){ return data->Set_At(in, value); } // Compute direction index /** * * @param start * @param end * @param next * @return */ int ComputeDirectionIndex(BoardPosition start, BoardPosition end, BoardPosition *next); /** * * @param end */ void ComputeEndMoves(BoardPosition end){ data->ComputeEndMoves(end); } /** * * @return */ int Max_Rows(void){return data->Max_Rows();} /** * * @return */ int Max_Cols(void){return data->Max_Cols();} }; #endif /* CONTROLLER_HPP_ */
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> using namespace std; typedef long long LL; const LL mod = 1000000007; LL p[100]; void init() { p[0] = 1; for (int i = 1;i <= 50; i++) p[i] = p[i-1]*i%mod; } LL exgcd(LL a,LL b,LL &x,LL &y) { if (b == 0) {x = 1;y = 0;return a;} LL d = exgcd(b,a%b,y,x); y -= a/b*x; return d; } LL inv(LL a) { LL x,y; LL d = exgcd(a,mod,x,y); return (x%mod + mod)%mod; } int main() { init(); int t,n,m,k; scanf("%d",&t); for (int ca = 1;ca <= t;ca++) { scanf("%d%d%d",&n,&m,&k); int a,b; a = ((n+1)*(m+1)) >> 1,b = (n+1)*(m+1) - a; LL ans = 0; for (int i = 1;i < k; i++) { LL mul = p[k]*inv(p[i])%mod*inv(p[k-i])%mod; //printf("%lld %lld %lld\n",p[k],inv(p[i]),inv(p[k-i])); for (int j = 1;j <= a; j++) mul = mul*(LL)i%mod; for (int j = 1;j <= b; j++) mul = mul*(LL)(k-i)%mod; ans = (ans + mul)%mod; cout << ans << endl; } if (k == 1 && n == 0 && m == 0) ans = 1; printf("Case %d: %lld\n",ca,ans); } return 0; }
#ifndef FORMSTANDARDDEVIATION_H #define FORMSTANDARDDEVIATION_H #include <QWidget> namespace Ui { class FormStandardDeviation; } class FormStandardDeviation : public QWidget { Q_OBJECT public: explicit FormStandardDeviation(QWidget *parent = 0); ~FormStandardDeviation(); private: Ui::FormStandardDeviation *ui; signals: void numStandardDeviationsChanged(double); }; #endif // FORMSTANDARDDEVIATION_H
#include "mainwindow.h" #include "mdialog.h" #include <QApplication> #include <iostream> using namespace std; int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; MDialog dialog; if (dialog.exec() == QDialog::Accepted) { w.show(); a.exec(); } cout << "程序结束运行" << endl; return 0; }
#include <iostream> #include "LList.h" //---------------------------------------------------- // constructor & destructor //---------------------------------------------------- LList::LList() { head = NULL; cout << "LList: constructed!\n"; } LList::~LList() { if (head != NULL) delete head; // deletes each node using recursion cout << "LList: destructed!\n"; } //---------------------------------------------------- // search //---------------------------------------------------- // Given: key to search for // Returns: pointer to a node in the list found to have // the given search key, or NULL for not found //---------------------------------------------------- node * LList::search(int srchKey) { node * p = head; // p points to the head node while (p != NULL) { if (p->key == srchKey) // if p's node has key = searchKey return p; // return pointer to node where its key = searchKey else p = p->next; // point to the next thing } return NULL; // searchKey was not found in list or list was empty } // search() //---------------------------------------------------- // findNode //---------------------------------------------------- // Given: a key to search for // Searches for a node with the given key, and if // found, invokes the print() method in the found node. // Otherwise, prints "not found" //---------------------------------------------------- void LList::findNode(int srchKey) { node * p; p = search(srchKey); // will return a pointer to a node // or NULL if node not found if (p != NULL) p->print(); else cout << "not found\n"; } // findNode() //---------------------------------------------------- // getb4 //---------------------------------------------------- // Given: a pointer to a node in the list // Returns: returns a pointer to the thing who has a // pointer r, OR returns NULL when r is // the head or not found in the list //---------------------------------------------------- node * LList::getb4(node * r) { if (r == head || head == NULL || r == NULL) return NULL; // if LList is empty, return NULL // if r=head, then no node is pointing to inputed node, // so return NULL as well. if node is not in list, return NULL as well! else { node * p = head; while (p != NULL) { if (p->next == r) return p; // pointer to the node such that node->next = r else p = p->next; // p->next wasnt r. update p and try again. } } return NULL; // r not found. returning NULL } // getb4() //---------------------------------------------------- // insert //---------------------------------------------------- // Given: key and data for a new node // Purpose: Allocates/populates a new node // When a node with the same key already exists: // the current/old node is replaced by the new one // and the old one is placed on the new one's // duplicate list (it's NEXT should be set to NULL, // since it is no longer "in the list") // Otherwise, the new node is prepended to the head // of the list. //---------------------------------------------------- void LList::insert(int k, string d) { node * p = search(k); // returns pointer to node with node->key = k // will return NULL if not found or empty list if (head == NULL) { node * newNode = new node(k, d); // list was empty. make new node and prepend to list head = newNode; } else if (p == NULL) { node * newNode = new node(k, d); // key not found in list and list not empty. // prepend to current list. newNode->next = head; head = newNode; } else if (p == head) { node * newNode = new node(k,d); // node with same key is the first node. make // a stack with the curr node and replace with // insert node. insert node will point to prev // node with same key value. newNode->next = p->next; newNode->dup = p; p->next = NULL; head = newNode; } else { node * newNode = new node(k,d); // same key value node inside but not top of list. // make a stack with curr node and replace with // insert node. insert node will point to prev node // with same key value. newNode->next = p->next; newNode->dup = p; p->next = NULL; getb4(p)->next = newNode; } } // insert() //---------------------------------------------------- // remove //---------------------------------------------------- // Given: a pointer to a node in the list to be removed // BUT NOT DELETED/DESTROYED // Returns: TRUE - when the node was successfully removed // FALSE - when the given node is NULL or the node // is not actually in the list. // Simply removes the node from the linked list. // (including setting the NEXT pointer in the node to NULL) //---------------------------------------------------- bool LList::remove(node * r) { if (r == NULL) return false; // cannot remove a node that aint a node else if (r == head) { head = r->next; // remove first node in list r->next = NULL; return true; } else if (search(r->key) != NULL) { node * before = getb4(r); // remove node in middle of list before->next = r->next; r->next = NULL; return true; } else return false; // didnt end up removing anything } // remove() //---------------------------------------------------- // drop //---------------------------------------------------- // Given: key of a node to drop // Returns: TRUE when a node was found and deleted // FALSE when a node with the given key not found, // or the remove() fails. // Searches for a node in the list with the given key: // When found, removes and deletes the node //---------------------------------------------------- bool LList::drop(int k) { node * dropNode; dropNode = search(k); // will return node to drop or NULL if not in list or empty list if (dropNode == NULL) return false; // cannot drop nothing bool didRemove = remove(dropNode); // bool value to see if remove(dropNode) succeeded if (didRemove == true) { delete dropNode; // delete dropNode return true; // successful drop } else return false; // remove failed } // drop() //---------------------------------------------------- // max //---------------------------------------------------- // Returns: a pointer to the node with the highest key // or NULL when there list is empty. node * LList::max() { if (head == NULL) return NULL; // no max of an empty list else { node * p = head; int MAX = -100000; // sentinal value to see if list has a max while (p != NULL) { if (p->key > MAX) MAX = p->key; // update MAX p = p->next; // try next node } if (MAX == -100000) return NULL; // no MAX was found else return search(MAX); // MAX was found. return node with key=MAX } } // max() //---------------------------------------------------- // sort //---------------------------------------------------- // Sorts the list in ascending order by key values void LList::sort() { if (head == NULL) return; // cant sort an empty list else { node * t = NULL; node * m; while (head != NULL) { // Get max from LList. LList will never be empty when getting m (while() condition takes care of this) // Also, m != NULL since non-empty LList always has a max. m = max(); if (m == head) head = m->next; // head points to m. move the head to the node after m. else getb4(m)->next = m->next; // a node points to m. move that node to point to m->next. m->next = t; // t is current head of temporary list. make m point to what t points to. t = m; // then make t point to m so m ends up prepending to our temporary list. } head = t; // t points to sorted list. so make head point to that list. } // t is deallocated but list is sorted since we set head=t. } // sort() //---------------------------------------------------- // print //---------------------------------------------------- // prints each node in the list, or EMPTY when there // are no nodes to print //---------------------------------------------------- void LList::print() { if (head == NULL) cout << "EMPTY\n\n"; else { node * p = head; while (p != NULL) { p->print(); p = p->next; } cout << endl; } } // print()
// // Created by gurumurt on 4/11/18. // #ifndef OPENCLDISPATCHER_BASE_KERNEL_H #define OPENCLDISPATCHER_BASE_KERNEL_H #endif //OPENCLDISPATCHER_BASE_KERNEL_H #include "headers.h" #include "globals.h" class base_kernel{ public: string name,kernel_src; cl_kernel kernel; short no_of_argument; short no_of_parameter; Param_Type param_type[]; };
/*! * \file DevMenu.h * * \author Shiyang Ao * \date November 2016 * * Developer's menu */ #pragma once namespace Hourglass { class MenuItem { public: std::string text; virtual void Increase() {} virtual void Decrease() {} virtual std::string GetValString() const { return ""; } }; template <typename T> class DevMenuVar : public MenuItem { public: T* Var; T Min; T Max; T Step; DevMenuVar(T* pVar, T min, T max, T step) : Var(pVar), Min(min), Max(max), Step(step) { } void Increase() { if (Var) *Var += min(Step, Max - *Var); } void Decrease() { if (Var) *Var -= min(Step, *Var - Min); } std::string GetValString() const { std::stringstream ss; ss << *Var; return ss.str(); } }; template<> class DevMenuVar<bool> : public MenuItem { public: bool* Var; bool Min; bool Max; bool Step; DevMenuVar(bool* pVar, bool min, bool max, bool step) : Var(pVar), Min(min), Max(max), Step(step) { } void Increase() { if (Var) *Var = !*Var; } void Decrease() { if (Var) *Var = !*Var; } std::string GetValString() const { return *Var ? "true" : "false"; } }; class DevMenu { public: void Init(); void Shutdown(); void AddMenuItem(const char* text); template<typename T> void AddMenuVar(const char* text, T* pVar, T min, T max, T step) { MenuItem* item = new DevMenuVar<T>(pVar, min, max, step); item->text = text; m_MenuItems.push_back(item); } void AddMenuVarBool(const char* text, bool* pVar) { AddMenuVar<bool>(text, pVar, false, false, false); } // Update user input void Update(); // Draw current menu and all it's sub items // Return: total lines drawn int Draw(int left = 0, int top = 0); void SetEnable(bool enable) { m_Enabled = enable; } bool IsEnabled() const { return m_Enabled; } private: // Check if user presses or holds a key bool IsKeyDownOrRepeat(int keycode); float m_KeyRepeatTime; std::vector<MenuItem*> m_MenuItems; int m_SelMenu; bool m_Enabled; }; extern DevMenu g_DevMenu; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2007 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * @file * @author Owner: Karianne Ekern (karie) * @author Co-owner: Adam Minchinton (adamm) * */ #include "core/pch.h" #include "adjunct/quick/sync/SyncNoteItems.h" #include "adjunct/quick/managers/SyncManager.h" #include "modules/sync/sync_coordinator.h" #include "adjunct/quick/Application.h" #include "adjunct/desktop_util/string/stringutils.h" #include "modules/stdlib/util/opdate.h" #include "modules/formats/base64_decode.h" #include "modules/pi/OpLocale.h" #include "modules/prefs/prefsmanager/collections/pc_files.h" #include "modules/img/imagedump.h" #ifdef MSWIN #include "platforms/windows/user_fun.h" #endif #define SYNC_NOTES_DELAY (30*1000) // 30 seconds /************************************************************************************ ** ** SyncNoteItems - responsible for syncing of notes ** ** Sends each item to the sync module _when_ it is changed/added/removed ** ** ************************************************************************************/ /** * - On all Inconsistencies -> Should set dirty flag (DoCompleteSync preference) * - Use cases: * - Non-existant previous -> Set dirty flag. * - Parent is not a folder -> Use parents parent as parent. If this is not a folder either. -> Use case 1? * - Previous and parent don't match -> Insert after previous * **/ // TODO: How to handle type = trash. Currently only sending it when an item has IsTrashFolder // but not doing anything on receiving items, really relying still on the unique GUID // In particular: Trash folder for notes won't work correctly. //#define SYNC_CLIENT_DEBUG //////////////////////////////////////////////////////////////////////////////////////// SyncNoteItems::SyncNoteItems() : m_is_receiving_items(FALSE) ,m_has_delayed_timer(FALSE) { } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// SyncNoteItems::~SyncNoteItems() { if (g_hotlist_manager) { HotlistModel* notes_model = g_hotlist_manager->GetNotesModel(); if (notes_model) notes_model->RemoveModelListener(this); } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// OP_STATUS SyncNoteItems::SyncDataInitialize(OpSyncDataItem::DataItemType type) { if (type == OpSyncDataItem::DATAITEM_NOTE) { OpFile notes_file; TRAPD(rc, g_pcfiles->GetFileL(PrefsCollectionFiles::NoteListFile, notes_file)); g_sync_manager->BackupFile(notes_file); return OpStatus::OK; } OP_ASSERT(FALSE); // Shouldn't get any other data type return OpStatus::ERR; } // Process incoming items OP_STATUS SyncNoteItems::SyncDataAvailable(OpSyncCollection *new_items, OpSyncDataError& data_error) { OP_STATUS status = OpStatus::OK; BOOL do_dirty_sync = FALSE; if(new_items && new_items->First()) { OpSyncItemIterator iter(new_items->First()); do { OpSyncItem *current = iter.GetDataItem(); OP_ASSERT(current); if(current) { status = ProcessSyncItem(current, do_dirty_sync); if (OpStatus::IsError(status) || do_dirty_sync) { if (do_dirty_sync) { data_error = SYNC_DATAERROR_INCONSISTENCY; } break; // Don't process more items } } } while (iter.Next()); } return status; } OP_STATUS SyncNoteItems::SyncDataFlush(OpSyncDataItem::DataItemType type, BOOL first_sync, BOOL is_dirty) { switch(type) { case OpSyncDataItem::DATAITEM_NOTE: { OP_ASSERT(g_sync_coordinator->GetSupports( SYNC_SUPPORTS_NOTE )); if (!g_sync_coordinator->GetSupports( SYNC_SUPPORTS_NOTE)) return OpStatus::ERR; SendAllItems(is_dirty, HotlistModel::NoteRoot); break; } default: { OP_ASSERT(FALSE); return OpStatus::ERR; } } return OpStatus::OK; } void SyncNoteItems::EnableNoteListening(BOOL enable) { OP_ASSERT(g_hotlist_manager); HotlistModel* model = g_hotlist_manager->GetNotesModel(); if (!model) { return; } if (enable) model->AddModelListener(this); else model->RemoveModelListener(this); } /*********************************************************************** * * OnSyncDataSupportsChanged * * * ***********************************************************************/ OP_STATUS SyncNoteItems::SyncDataSupportsChanged(OpSyncDataItem::DataItemType type, BOOL has_support) { OP_ASSERT(g_hotlist_manager); if (type == OpSyncDataItem::DATAITEM_NOTE) { EnableNoteListening(has_support); OpStatus::Ignore(SendModifiedNotes()); } else { OP_ASSERT(FALSE); return OpStatus::ERR; } return OpStatus::OK; } ////////////////////////////////////////////////////////////////// OpSyncDataItem::DataItemType SyncNoteItems::GetSyncTypeFromItemType( HotlistModelItem* model_item ) { if (!model_item || !model_item->GetModel()) return OpSyncDataItem::DATAITEM_GENERIC; INT32 model_type = model_item->GetModel()->GetModelType(); if (model_type == HotlistModel::NoteRoot) { if (model_item->IsFolder()) { return OpSyncDataItem::DATAITEM_NOTE_FOLDER; } else if (model_item->IsSeparator()) { return OpSyncDataItem::DATAITEM_NOTE_SEPARATOR; } else if (model_item->IsNote()) { return OpSyncDataItem::DATAITEM_NOTE; } else { OP_ASSERT(FALSE); } } return OpSyncDataItem::DATAITEM_GENERIC; } // HotlistModelListener interface methods /***************************************************************************** ** ** HotlistItemChanged ** ** @param HotlistModelItem* model_item ** @param OpSyncDataItem::DataItemStatus status ** @param BOOL dirty ** @param UINT32 changed_flags ** @param BOOL delayed_triggered - TRUE if this is called from a delayed triggered update ** *****************************************************************************/ /* NOTE: Elements that aren't sent from the client to the server are interpreted as 'not changed'. That is, Empty fields needs to be sent. Missing fields will be interpreted as not-to-be-changed. Exception: Previous/Parent: If they are not present, the server will interpret it as being first in its folder / being in root folder. That is, missing parent/previous's should _not_ be sent. NOTE: For changed items we send only the fields that actually changed, not all fields. For removed items we send only the id and action For added items we send all fields (TODO: Could change to send only set fields on added items) */ OP_STATUS SyncNoteItems::HotlistItemChanged(HotlistModelItem* model_item, OpSyncDataItem::DataItemStatus status, BOOL dirty, UINT32 changed_flag, BOOL delayed_triggered) { OpSyncItem *sync_item = NULL; OP_STATUS sync_status = OpStatus::OK; OpString data; if ( !model_item || !model_item->GetModel()) { return OpStatus::OK; } // Check if syncing has been turned off for this model if ( !model_item->GetModel()->GetModelIsSynced()) { return OpStatus::OK; } BOOL is_add = changed_flag & HotlistModel::FLAG_ADDED; #ifdef SYNC_CLIENT_DEBUG if (model_item->GetName().HasContent()) { OpString8 name; name.Set(model_item->GetName().CStr()); OpString8 guid; guid.Set(model_item->GetUniqueGUID().CStr()); fprintf( stderr,"\n [Link] HotlistItemChanged(%s[%x], status=%d, dirty=%d, flag=%x)\n", name.CStr(), guid.CStr(), status, dirty, changed_flag); } #endif OpSyncDataItem::DataItemType type = GetSyncTypeFromItemType(model_item); INT32 model_type = model_item->GetModel()->GetModelType(); // Check if supports notes // Must check the model_type not the item type since folders are in notes if (model_type == HotlistModel::NoteRoot && !g_sync_manager->SupportsType(SyncManager::SYNC_NOTES)) return OpStatus::OK; if (model_type == HotlistModel::NoteRoot) { // Generate the unique id if it's not there if (!model_item->GetUniqueGUID().HasContent()) { OP_ASSERT(!"Item added to sync does not have a unique GUID ! \n"); OpString guid; // generate a default unique ID if(OpStatus::IsSuccess(StringUtils::GenerateClientID(guid))) { model_item->SetUniqueGUID(guid.CStr(), model_type); model_item->GetModel()->SetDirty(TRUE); } } RETURN_IF_ERROR(data.Set(model_item->GetUniqueGUID())); OP_ASSERT(model_item->GetUniqueGUID().HasContent()); // Must have a GUID if (!data.HasContent()) return OpStatus::ERR; if(delayed_triggered) { // reset some data model_item->SetChangedFields(0); model_item->SetLastSyncStatus(OpSyncDataItem::DATAITEM_ACTION_NONE); } else { // Send deleted items right away if(model_type == HotlistModel::NoteRoot && status != OpSyncDataItem::DATAITEM_ACTION_DELETED) { // start the timer and collect all changes for an item every now and then model_item->SetChangedFields(model_item->GetChangedFields() | changed_flag); // Added state should not be changed to modified if (model_item->GetLastSyncStatus() != OpSyncDataItem::DATAITEM_ACTION_ADDED) model_item->SetLastSyncStatus(status); return StartTimeout(); } } sync_status = g_sync_coordinator->GetSyncItem(&sync_item, type, OpSyncItem::SYNC_KEY_ID, data.CStr()); if(OpStatus::IsSuccess(sync_status)) { sync_item->SetStatus(status); DEBUG_LINK(UNI_L("%s: id '%s', status: %d, name: '%s' outgoing\n"), model_item->IsNote() ? UNI_L("NT") : UNI_L("BM"), model_item->GetUniqueGUID().CStr(), status, model_item->GetName().CStr()); // Don't set fields if item is deleted if (status != OpSyncDataItem::DATAITEM_ACTION_DELETED) { // NOTE: Parent and previous MUST always be sent!! SYNC_RETURN_IF_ERROR(SetParent(model_item, sync_item), sync_item); SYNC_RETURN_IF_ERROR(SetPrevious(model_item, sync_item), sync_item); // If Trash folder, set type = trash if (model_item->GetIsTrashFolder()) { SYNC_RETURN_IF_ERROR(sync_item->SetData(OpSyncItem::SYNC_KEY_TYPE, UNI_L("trash")), sync_item); } if (model_item->GetTarget().HasContent()) { SYNC_RETURN_IF_ERROR(sync_item->SetData(OpSyncItem::SYNC_KEY_TARGET, model_item->GetTarget().CStr()), sync_item); } // Notes, note folders if(model_item->IsNote()) { if ( changed_flag & HotlistModel::FLAG_URL || is_add ) { SYNC_RETURN_IF_ERROR(sync_item->SetData(OpSyncItem::SYNC_KEY_URI, model_item->GetUrl().CStr()), sync_item); } } if (model_item->IsFolder()) { if ( changed_flag & HotlistModel::FLAG_NAME || is_add ) { SYNC_RETURN_IF_ERROR(sync_item->SetData(OpSyncItem::SYNC_KEY_TITLE, model_item->GetName().CStr()), sync_item); } } // Notes only if (model_item->IsNote()) { if ( changed_flag & HotlistModel::FLAG_NAME || is_add ) { SYNC_RETURN_IF_ERROR(sync_item->SetData(OpSyncItem::SYNC_KEY_CONTENT, model_item->GetName().CStr()), sync_item); } } //////////////////////////////////////////////////////////////////////////////////////////////////// // Notes, Folders if ( changed_flag & HotlistModel::FLAG_CREATED || is_add ) { SYNC_RETURN_IF_ERROR(SetCreated(model_item, sync_item), sync_item); } } // end !deleted /* When commiting the item, if the item has been removed or added, the item that was before it previously needs to have its previous updated 1) hotlist_item was added: next_items previous is hotlist_item 2) hotlist_item was moved from here (or removed): next items previous is hotlist_items old previous 3) Hotlist_item was moved to : FLAG_MOVED_TO: must update the items next_items previous The moved from is handled separately in OnHotlistItemMovedFrom */ // moved, removed, added // if ( flag_changed & HotlistModel::FLAG_MOVED_TO, MOVED_FROM, ADDED, REMOVED ) BOOL added = FALSE; HotlistModelItem* next_item = model_item->GetSiblingItem(); OpSyncDataItem::DataItemType next_type = GetSyncTypeFromItemType(next_item); if (sync_item->GetStatus() == OpSyncDataItem::DATAITEM_ACTION_ADDED) { // We know there's a previous when adding if (next_item && model_item) { SYNC_RETURN_IF_ERROR(sync_item->CommitItem(dirty, !dirty), sync_item); #ifdef SYNC_CLIENT_DEBUG fprintf( stderr, "Item added. Commit item and Update its next(%s)s previous to be me\n", uni_down_strdup(next_item->GetName().CStr())); #endif SYNC_RETURN_IF_ERROR(g_sync_coordinator->UpdateItem(next_type, next_item->GetUniqueGUID().CStr(), OpSyncItem::SYNC_KEY_PREV, model_item->GetUniqueGUID().CStr()), sync_item); added = TRUE; } } else if (sync_item->GetStatus() == OpSyncDataItem::DATAITEM_ACTION_DELETED) { HotlistModelItem* my_previous = model_item->GetPreviousItem(); if (next_item && my_previous) { #ifdef SYNC_CLIENT_DEBUG fprintf( stderr, "Item deleted. Commit item and Update its next(%s)s previous to my_previous\n", uni_down_strdup(next_item->GetName().CStr())); #endif SYNC_RETURN_IF_ERROR(sync_item->CommitItem(dirty, !dirty), sync_item); SYNC_RETURN_IF_ERROR(g_sync_coordinator->UpdateItem(next_type, next_item->GetUniqueGUID().CStr(), OpSyncItem::SYNC_KEY_PREV, my_previous->GetUniqueGUID().CStr()), sync_item); added = TRUE; } else if (next_item) { #ifdef SYNC_CLIENT_DEBUG fprintf( stderr, "Item deleted. Commit item and Update its nexts (%s) previous to nothing\n", uni_down_strdup(next_item->GetName().CStr())); #endif SYNC_RETURN_IF_ERROR(sync_item->CommitItem(dirty, !dirty), sync_item); SYNC_RETURN_IF_ERROR(g_sync_coordinator->UpdateItem(next_type, next_item->GetUniqueGUID().CStr(), OpSyncItem::SYNC_KEY_PREV, UNI_L("")), sync_item); added = TRUE; } } /* This is a possible move to - TODO: Only do this when we KNOW it's a move-to */ else if (sync_item->GetStatus() == OpSyncDataItem::DATAITEM_ACTION_MODIFIED && (changed_flag & HotlistModel::FLAG_MOVED_TO)) { if (next_item && model_item) { #ifdef SYNC_CLIENT_DEBUG fprintf( stderr, " Item moved_to. Commit item and update its next (%s) to having me as previous \n", uni_down_strdup(next_item->GetName().CStr())); #endif SYNC_RETURN_IF_ERROR(sync_item->CommitItem(dirty, !dirty), sync_item); SYNC_RETURN_IF_ERROR(g_sync_coordinator->UpdateItem(next_type, next_item->GetUniqueGUID().CStr(), OpSyncItem::SYNC_KEY_PREV, model_item->GetUniqueGUID().CStr()), sync_item); added = TRUE; } } // Any change but a move, add, delete should go here. // And: Fallback for add, remove, modified if (!added) { #ifdef SYNC_CLIENT_DEBUG fprintf( stderr, " Default CommitItem \n"); #endif SYNC_RETURN_IF_ERROR(sync_item->CommitItem(dirty, !dirty), sync_item); } } } if(sync_item) { g_sync_coordinator->ReleaseSyncItem(sync_item); } return sync_status; } // HotlistModelListener functions /**************************************************************************** ** ** OnHotlistItemMovedFrom ** ** @param HotlistModelItem* model_item - the item that moved from its old ** position ** ** When moving an item from a position, ** sync module needs to know that its next got a new previous. ** The previous can be NULL, if the item is first in its folder ** ** No need to commit item, since if it is moved somewhere it will be ** commited when moved _to_. ** ****************************************************************************/ void SyncNoteItems::OnHotlistItemMovedFrom(HotlistModelItem* model_item) { if (!model_item) { return; } //#if 0 if (IsProcessingIncomingItems()) { return; } //#endif INT32 model_type = model_item->GetModel()->GetModelType(); if (model_type == HotlistModel::NoteRoot) { HotlistModelItem* next_item = model_item->GetSiblingItem(); HotlistModelItem* my_previous = model_item->GetPreviousItem(); OpSyncDataItem::DataItemType next_type = GetSyncTypeFromItemType(next_item); // model_item? #ifdef SYNC_CLIENT_DEBUG fprintf( stderr, " OnHotlistItemMovedFrom(%s[%s]. Update my next to have my previous as its previous\n", uni_down_strdup(model_item->GetName().CStr()), uni_down_strdup(model_item->GetUniqueGUID().CStr())); #endif // SYNC_CLIENT_DEBUG if (next_item) { if (my_previous) { // Next items new previous is my_previous OpStatus::Ignore(g_sync_coordinator->UpdateItem(next_type, next_item->GetUniqueGUID().CStr(), OpSyncItem::SYNC_KEY_PREV, my_previous->GetUniqueGUID().CStr())); } else { // Next item now has no previous OpStatus::Ignore(g_sync_coordinator->UpdateItem(next_type, next_item->GetUniqueGUID().CStr(), OpSyncItem::SYNC_KEY_PREV, UNI_L(""))); } } } } ////// Helper methods to set fields on the sync item from the hotlist item ////// /********************************************************************** ** ** SetParent ** Adds attribute parent to sync_item, based on item's parent ** **********************************************************************/ OP_STATUS SyncNoteItems::SetParent(HotlistModelItem* item, OpSyncItem* sync_item) { if (!item || !sync_item) return OpStatus::ERR_NULL_POINTER; OpString parentGuid; HotlistModelItem* parent = item->GetParentFolder(); if (parent && item && /*parent == item*/ (parent->GetIndex() == item->GetIndex())) { #ifdef SYNC_CLIENT_DEBUG OpString8 parent_guid; OpString8 guid; parent_guid.Set(parent->GetUniqueGUID().CStr()); guid.Set(item->GetUniqueGUID().CStr()); if (parent->GetUniqueGUID().Compare(item->GetUniqueGUID()) == 0) fprintf( stderr, " Item %s cannot be parent of item %s\n", parent_guid.CStr(), guid.CStr()); #endif OP_ASSERT(!"Parent cannot be item itself \n"); return OpStatus::ERR; } if (parent) { parentGuid.Set( parent->GetUniqueGUID() ); #ifdef SYNC_CLIENT_DEBUG fprintf( stderr, " item %s has parent %s\n", uni_down_strdup(item->GetUniqueGUID()), uni_down_strdup(parentGuid)); #endif RETURN_IF_ERROR(sync_item->SetData(OpSyncItem::SYNC_KEY_PARENT, parentGuid.CStr())); } else { RETURN_IF_ERROR(sync_item->SetData(OpSyncItem::SYNC_KEY_PARENT, UNI_L(""))); } return OpStatus::OK; } /************************************************************************ ** ** SetPrevious ** ** Adds attribute previous to sync_item, based on item's previous ** ************************************************************************/ OP_STATUS SyncNoteItems::SetPrevious(HotlistModelItem* item, OpSyncItem* sync_item) { if (!item || !sync_item) return OpStatus::ERR_NULL_POINTER; OpString previousGuid; HotlistModelItem* previous = item->GetPreviousItem(); if (previous && item && (previous->GetIndex() == item->GetIndex())) { OP_ASSERT(!"Previous cannot be item itself"); return OpStatus::ERR; } if (previous) { previousGuid.Set(previous->GetUniqueGUID()); RETURN_IF_ERROR(sync_item->SetData(OpSyncItem::SYNC_KEY_PREV, previousGuid.CStr())); } else { RETURN_IF_ERROR(sync_item->SetData(OpSyncItem::SYNC_KEY_PREV, UNI_L(""))); } return OpStatus::OK; } /************************************************************************ ** ** SetCreated ** ** Set created attribute on sync_item from item ** ************************************************************************/ OP_STATUS SyncNoteItems::SetCreated(HotlistModelItem* item, OpSyncItem* sync_item) { if (!item || !sync_item) return OpStatus::ERR_NULL_POINTER; OpString createdDate; time_t cdate = item->GetCreated(); if (cdate > 0) { OP_STATUS status = SyncUtil::CreateRFC3339Date( cdate, createdDate); if (OpStatus::IsSuccess(status)) { RETURN_IF_ERROR(sync_item->SetData(OpSyncItem::SYNC_KEY_CREATED, createdDate.CStr())); } } return OpStatus::OK; } /************************************************************************* ** ** ProcessSyncItem ** ** Process OpSyncItem* item; build the corresponding hotlistmodelItem ** and change or add or remove it from the hotlistmodel as appropriate. ** ** Called when synchronization has completed. ** Updates "local" synced items. ** ** Note; The SyncManager will ask for a set the dirty flag to ask ** for a complete sync if ProcessSyncItem returns OpStatus::ERR ** **************************************************************************/ // TODO: Only set the fields that actually changed OP_STATUS SyncNoteItems::ProcessSyncItem(OpSyncItem *item, BOOL& dirty) { if (!item) return OpStatus::ERR_NULL_POINTER; QuickSyncLock lock(m_is_receiving_items, TRUE, FALSE); OpSyncDataItem::DataItemType type = item->GetType(); HotlistGenericModel* model = NULL; if (type == OpSyncDataItem::DATAITEM_NOTE || type == OpSyncDataItem::DATAITEM_NOTE_FOLDER || type == OpSyncDataItem::DATAITEM_NOTE_SEPARATOR) { if(!g_sync_manager->SupportsType(SyncManager::SYNC_NOTES)) { return OpStatus::OK; } model = g_hotlist_manager->GetNotesModel(); } else { return OpStatus::ERR; } // No reason to build item and do all the processing if it's a delete. if(item->GetStatus() == OpSyncDataItem::DATAITEM_ACTION_DELETED) { OpString itemGuid; RETURN_IF_ERROR(item->GetData(OpSyncItem::SYNC_KEY_ID, itemGuid)); HotlistModelItem* deleted_item = model->GetByUniqueGUID(itemGuid); if (!deleted_item) { // it doesn't exist already, so we do nothing if it's deleted return OpStatus::OK; } else { // Should we handle non deletable items being deleted in items from server // OP_ASSERT(deleted_item->GetIsDeletable()); BOOL deleted = model->DeleteItem(deleted_item, FALSE); if ( !deleted ) { OP_ASSERT(!"Failed deleting item \n"); } model->SetDirty(TRUE); return OpStatus::OK; } } // Don't want notifications about favicons added during processing incoming items model->SetIsSyncing(TRUE); HotlistManager::ItemData item_data; double created_date = 0; OpString previousGuid; OpString parentGuid; OP_STATUS build_status = OpStatus::ERR; if (type == OpSyncDataItem::DATAITEM_NOTE || type == OpSyncDataItem::DATAITEM_NOTE_FOLDER || type == OpSyncDataItem::DATAITEM_NOTE_SEPARATOR) { build_status = BuildNotesItem(item, item_data, created_date, previousGuid, parentGuid); } if (OpStatus::IsError(build_status)) { model->SetIsSyncing(FALSE); return build_status; } // TODO: Handle Trash folder. HotlistModelItem *synced_item = NULL; HotlistModelItem *parent = 0; HotlistModelItem *previous = 0; BOOL no_parent = FALSE; BOOL no_previous = FALSE; if (parentGuid.HasContent()) { parent = model->GetByUniqueGUID(parentGuid); if (parent && !parent->IsFolder()) // If parent is not folder, use parents parent as parent { DEBUG_LINK(UNI_L("Error: Parent '%s' not a folder \n"), parent->GetName().CStr()); parent = parent->GetParentFolder(); } // If no parentGuid -> Insert in root } else { no_parent = TRUE; // Item is in root folder } if (previousGuid.HasContent()) { previous = model->GetByUniqueGUID(previousGuid); } else { no_previous = TRUE; // Item is first in its parent } if (!no_parent && !parent) // Has parent, but parent does not exist -> error { dirty = TRUE; #if defined(_DEBUG) && (defined(_MACINTOSH_) || defined(_UNIX_DESKTOP_)) OpString8 guid; guid.Set(parentGuid.CStr()); fprintf( stderr, " ** USE CASE 1 **: Non-existent parent %s\n", guid.CStr()); #endif DEBUG_LINK(UNI_L("Error: Non-existing parent id '%s'\n"), parentGuid.CStr()); /* No parent: Drop processing this item, and set dirty flag */ model->SetIsSyncing(FALSE); return OpStatus::OK; } else if (!no_previous && !previous) // has previous, but previous does not exist -> error { dirty = TRUE; #if defined(_DEBUG) && (defined(_MACINTOSH_) || defined(_UNIX_DESKTOP_)) OpString8 guid; guid.Set(previousGuid.CStr()); fprintf( stderr, " ** USE CASE 2 **: Non-existent previous %s\n", guid.CStr()); #endif DEBUG_LINK(UNI_L("Error: Non-existing previous id '%s'\n"), previousGuid.CStr()); #ifdef SYNC_CLIENT_DEBUG OpString8 name; name.Set(item_data.name.CStr()); if (item_data.name.HasContent()) fprintf( stderr, " Item %s \n", name.CStr()); #endif model->SetIsSyncing(FALSE); return OpStatus::OK; } synced_item = model->GetByUniqueGUID(item_data.unique_guid); /************ synced_item does not exist on client **********************************************************/ if(!synced_item) { #ifdef SYNC_CLIENT_DEBUG OpString8 guid; guid.Set(item_data.unique_guid.CStr()); fprintf( stderr, " Item %s does not exist on client \n", guid.CStr()); #endif DEBUG_LINK(UNI_L("BM: NEW id '%s', name: '%s', folder: '%s', NEW from server\n"), item_data.unique_guid.CStr(), item_data.name.CStr(), item_data.folder.CStr()); // Neither parent nor previous -> First in root if (no_previous && no_parent) { OP_ASSERT(model); if (OpStatus::IsError(CreateItemFirst(model, type, item_data, NULL))) { #if defined(_DEBUG) && (defined(_MACINTOSH_) || defined(_UNIX_DESKTOP_)) fprintf( stderr, " ERROR: ProcessSyncItem: Couldn't create item \n"); #endif model->SetIsSyncing(FALSE); return OpStatus::ERR; } } /* If there is a previous set, make a new item that is this previous' next */ /* If not, insert the item first in the parent folder */ /* If neither previous or parent, insert item first in root ( case above) */ else if (previous) { OP_ASSERT(!no_previous); /* Check if parent matches. If not, set dirty flag */ if (parent && previous->GetParentFolder() != parent) { dirty = TRUE; #if defined(_DEBUG) && (defined(_MACINTOSH_) || defined(_UNIX_DESKTOP_)) fprintf( stderr, " ** USE CASE 7 **: Previous and parent does not match \n"); #endif DEBUG_LINK(UNI_L("Error: Previous and parent does not match \n")); } OP_ASSERT(model); if (OpStatus::IsError(CreateItemOrdered(model, type, item_data, previous))) { #if defined(_DEBUG) && (defined(_MACINTOSH_) || defined(_UNIX_DESKTOP_)) fprintf( stderr, " ERROR: ProcessSyncItem Couldn't create item \n"); #endif // Ask for complete sync. Dont proceed. model->SetIsSyncing(FALSE); return OpStatus::ERR; } } else if (parent && parent->IsFolder()) { OP_ASSERT(!no_parent); OP_ASSERT(model); if (OpStatus::IsError(CreateItemFirst(model, type, item_data, parent))) { // Couldn't create item #if defined(_DEBUG) && (defined(_MACINTOSH_) || defined(_UNIX_DESKTOP_)) fprintf( stderr, " ERROR: ProcessSyncItem: Couldn't create item \n"); #endif // Don't do further sync. But ask for complete sync instead. model->SetIsSyncing(FALSE); return OpStatus::ERR; } } else if (parent) // Parent not a folder: Current use case solution: Use parents parent as items parent { #if defined(_DEBUG) && (defined(_MACINTOSH_) || defined(_UNIX_DESKTOP_)) fprintf( stderr, " ** USE CASE 4 **: Parent not a folder \n"); #endif DEBUG_LINK(UNI_L("Error: Parent '%s' not a folder \n"), parent->GetName().CStr()); parent = parent->GetParentFolder(); dirty = TRUE; // TODO: FIX FOR NOTES!! if (!parent->IsFolder() || (type == OpSyncDataItem::DATAITEM_NOTE_FOLDER && !parent->GetSubfoldersAllowed())) // parents parent is not a folder either, handle like use case 1 // Handle same way if parent has subfolders not allowed { #if defined(_DEBUG) && (defined(_MACINTOSH_) || defined(_UNIX_DESKTOP_)) fprintf( stderr, " ** USE CASE 4 -> 1 **: Parents parent not a folder \n"); #endif // DEBUG_LINK(UNI_L("And parents parent not a folder \n")); model->SetIsSyncing(FALSE); return OpStatus::OK; } } else { OP_ASSERT(!"We should not be here \n"); #if defined(_DEBUG) && (defined(_MACINTOSH_) || defined(_UNIX_DESKTOP_)) OpString8 guid; guid.Set(item_data.unique_guid.CStr()); fprintf( stderr, " New Item with GUID %s\n", guid.CStr()); fprintf( stderr, " previous=%p, parent=%p, no_previous=%d, no_parent=%d\n", previous,parent,no_previous, no_parent); #endif } HotlistModelItem* bm_item = model->GetByUniqueGUID( item_data.unique_guid ); if (bm_item) { /********* Set created field *********/ if (item_data.created.HasContent() && created_date > 0) { bm_item->SetCreated( (INT32)created_date ); } OpString data; OP_STATUS status = item->GetData(OpSyncItem::SYNC_KEY_TARGET, data); if (OpStatus::IsSuccess(status) && data.HasContent()) { bm_item->SetTarget(data.CStr()); } status = item->GetData(OpSyncItem::SYNC_KEY_MOVE_IS_COPY, data); if (OpStatus::IsSuccess(status) && data.HasContent()) { INT32 copy = uni_atoi(data.CStr()); bm_item->SetHasMoveIsCopy(copy != 0); } status = item->GetData(OpSyncItem::SYNC_KEY_DELETABLE, data); if (OpStatus::IsSuccess(status) && data.HasContent()) { INT32 deletable = uni_atoi(data.CStr()); bm_item->SetIsDeletable(deletable != 0); } status = item->GetData(OpSyncItem::SYNC_KEY_SUB_FOLDERS_ALLOWED, data); if (OpStatus::IsSuccess(status) && data.HasContent()) { INT32 subfolder = uni_atoi(data.CStr()); bm_item->SetSubfoldersAllowed(subfolder != 0); } status = item->GetData(OpSyncItem::SYNC_KEY_SEPARATORS_ALLOWED, data); if (OpStatus::IsSuccess(status) && data.HasContent()) { INT32 separator = uni_atoi(data.CStr()); bm_item->SetSeparatorsAllowed(separator != 0); } status = item->GetData(OpSyncItem::SYNC_KEY_MAX_ITEMS, data); if (OpStatus::IsSuccess(status) && data.HasContent()) { INT32 max_items = uni_atoi(data.CStr()); if (max_items >= 0) { bm_item->SetMaxItems(max_items); } } } model->SetDirty(TRUE); } else /*********** Item already exists on client **********************************/ { if ( previous && previous->GetParentFolder() == synced_item || parent && parent->GetParentFolder() == synced_item) { model->SetIsSyncing(FALSE); m_is_receiving_items = FALSE; return OpStatus::OK; } #ifdef SYNC_CLIENT_DEBUG OpString8 guid; guid.Set(item_data.unique_guid.CStr()); fprintf( stderr, " Bookmark %s does exist on client \n", guid.CStr()); #endif DEBUG_LINK(UNI_L("BM: OLD id '%s', name: '%s', folder: '%s', (existing) from server\n"), item_data.unique_guid.CStr(), item_data.name.CStr(), item_data.folder.CStr()); switch(item->GetStatus()) { case OpSyncDataItem::DATAITEM_ACTION_ADDED: case OpSyncDataItem::DATAITEM_ACTION_MODIFIED: { // If no previous - > first in parent // If no parent - > in root folder #ifdef SYNC_CLIENT_DEBUG OpString8 name; name.Set(item_data.name.CStr()); fprintf( stderr, " Item %s moved to new position or changed\n", name.CStr()); #endif // 1. Moved to position first in folder or root if (!previous) // Was _moved_ to being first in its folder { #ifdef SYNC_CLIENT_DEBUG fprintf( stderr, " No previous. reparenting \n"); #endif // Only move if it actually moved to a new position if ( synced_item->GetPreviousItem() != NULL || synced_item->GetParentFolder() != parent ) { model->Reparent(synced_item, parent, TRUE, synced_item->GetIsTrashFolder()); } } // 2. New previous item (diff from old previous, or had no previous before) // Reorder, new previous (and possibly parent) item else if (previous && synced_item->GetPreviousItem() != previous) { #ifdef SYNC_CLIENT_DEBUG if (synced_item->GetName().HasContent()) { OpString8 name; OpString8 prev_name; name.Set(synced_item->GetName().CStr()); prev_name.Set(previous->GetName().CStr()); fprintf( stderr, " Item %s has new previous %s\n", name.CStr(), prev_name.CStr()); } #endif if (parent) { OP_ASSERT(parent == previous->GetParentFolder()); } #ifdef SYNC_CLIENT_DEBUG fprintf( stderr, " Reorder item -----------\n"); #endif model->Reorder(synced_item, previous, synced_item->GetIsTrashFolder()); } // 3. New parent, previous unchanged else if (parent && synced_item->GetParentFolder() != parent) // Reparent, insert first in parent { #ifdef SYNC_CLIENT_DEBUG fprintf( stderr, " item has new parent. same previous \n"); #endif // No previous data sent model->Reparent(synced_item, parent, TRUE, synced_item->GetIsTrashFolder() ); } else if (!parent && synced_item->GetParentFolder()) { // has previous and previous is unchanged // !parent OR (has parent and parent is unchanged) // model->Reorder(bookmark, previous, bookmark->GetIsTrashFolder()); } synced_item = model->GetByUniqueGUID(item_data.unique_guid); // We have to set all the data we get from the server INT32 flag = HotlistModel::FLAG_UNKNOWN; if( synced_item && !g_hotlist_manager->SetItemValue(synced_item, item_data, TRUE, flag)) { OP_ASSERT(FALSE); } } break; default: // No action defined. What do we do? OP_ASSERT(FALSE); model->SetIsSyncing(FALSE); return OpStatus::ERR; } OP_STATUS status; OpString data; /********* Set visited field *********/ if (synced_item) { status = item->GetData(OpSyncItem::SYNC_KEY_TARGET, data); if (OpStatus::IsSuccess(status) && data.HasContent()) { synced_item->SetTarget(data.CStr()); } status = item->GetData(OpSyncItem::SYNC_KEY_MOVE_IS_COPY, data); if (OpStatus::IsSuccess(status) && data.HasContent()) { INT32 copy = uni_atoi(data.CStr()); // 0 eller 1 synced_item->SetHasMoveIsCopy(copy != 0); } status = item->GetData(OpSyncItem::SYNC_KEY_DELETABLE, data); if (OpStatus::IsSuccess(status) && data.HasContent()) { INT32 deletable = uni_atoi(data.CStr()); // 0 eller 1 synced_item->SetIsDeletable(deletable != 0); } status = item->GetData(OpSyncItem::SYNC_KEY_SUB_FOLDERS_ALLOWED, data); if (OpStatus::IsSuccess(status) && data.HasContent()) { INT32 subfolder = uni_atoi(data.CStr()); synced_item->SetSubfoldersAllowed(subfolder != 0); } status = item->GetData(OpSyncItem::SYNC_KEY_SEPARATORS_ALLOWED, data); if (OpStatus::IsSuccess(status) && data.HasContent()) { INT32 separator = uni_atoi(data.CStr()); synced_item->SetSeparatorsAllowed(separator != 0); } } status = item->GetData(OpSyncItem::SYNC_KEY_MAX_ITEMS, data); if (OpStatus::IsSuccess(status) && data.HasContent()) { INT32 max_items = uni_atoi(data.CStr()); if (max_items >= 0) { synced_item->SetMaxItems(max_items); } } model->SetDirty(TRUE); } model->SetIsSyncing(FALSE); return OpStatus::OK; } /******************************************************************** ** ** SendAllItems ** ** Sends all items to the sync module ** To be used on first login and when doing a dirty sync ** ** @param dirty - should be TRUE if doing a dirty sync ** ********************************************************************/ OP_STATUS SyncNoteItems::SendAllItems(BOOL dirty, INT32 model_type) { HotlistModel *model = 0; if (model_type == HotlistModel::NoteRoot) { model = g_hotlist_manager->GetNotesModel(); } else { return OpStatus::ERR; } HotlistModelItem *item; INT32 i; for (i = 0; i < model->GetItemCount(); i++) { item = model->GetItemByIndex(i); // Generate the unique id if it's not there if (!item->GetUniqueGUID().HasContent()) { OP_ASSERT(!"Item added to sync does not have a unique GUID ! \n"); OpString guid; // generate a default unique ID if(OpStatus::IsSuccess(StringUtils::GenerateClientID(guid))) { item->SetUniqueGUID(guid.CStr(), model_type); } } if (!item->GetUniqueGUID().HasContent()) return OpStatus::ERR; // Last param, delay_triggered, must be TRUE, to force us to give the items to the sync module at once. RETURN_IF_ERROR(HotlistItemChanged(item, OpSyncDataItem::DATAITEM_ACTION_ADDED, dirty, HotlistModel::FLAG_UNKNOWN, TRUE)); } return OpStatus::OK; } /************************************************************************ ** ** BuildNotesItem - Processes an incoming notes model item ** ** Build the ItemData from the OpSyncItem received from the sync module ** ** @param OpSyncItem* item - item to set fields from ** @param HotlistManager::ItemData& item_data - item to set fields on ** @param double& created_date - holds created date on return ** @param OpString& previousGuid - holds Guid of items previous on return, ** empty if it doesnt have a previous ** @param OpString& parentGuid - holds Guid of items parent on return, ** empty if it doesnt have a parent ** ************************************************************************/ OP_STATUS SyncNoteItems::BuildNotesItem(OpSyncItem* item, HotlistManager::ItemData& item_data, double& created_date, OpString& previousGuid, OpString& parentGuid) { if (!item) return OpStatus::OK; OpString data; created_date = 0; OpSyncDataItem::DataItemType type = item->GetType(); OP_STATUS status = item->GetData(OpSyncItem::SYNC_KEY_ID, data); RETURN_IF_ERROR(item_data.unique_guid.Set(data)); status = item->GetData(OpSyncItem::SYNC_KEY_CREATED, data); /** * Created won't be set in item->SetItemValue * Created will be set to current time in NewBookmark * So we use SetCreated on the note to set it after ev. call to NewNote **/ if (OpStatus::IsSuccess(status) && data.HasContent()) { created_date = OpDate::ParseRFC3339Date(data.CStr()); // returns op_nan if not valid date if(!created_date) { // no date, what now? } } status = item->GetData(OpSyncItem::SYNC_KEY_PARENT, data); if (OpStatus::IsSuccess(status) && data.HasContent()) { status = parentGuid.Set(data); if (OpStatus::IsError(status)) { return OpStatus::ERR; } } status = item->GetData(OpSyncItem::SYNC_KEY_PREV, data); if (OpStatus::IsSuccess(status) && data.HasContent()) { status = previousGuid.Set(data); if (OpStatus::IsError(status)) return OpStatus::ERR; } status = item->GetData(OpSyncItem::SYNC_KEY_CONTENT, data); if (OpStatus::IsSuccess(status)) { OpStatus::Ignore(item_data.name.Set(data)); } if (type == OpSyncDataItem::DATAITEM_NOTE) { status = item->GetData(OpSyncItem::SYNC_KEY_URI, data); if (OpStatus::IsSuccess(status)) { OpStatus::Ignore(item_data.url.Set(data)); } } else if (type == OpSyncDataItem::DATAITEM_NOTE_FOLDER) { status = item->GetData(OpSyncItem::SYNC_KEY_TITLE, data); if (OpStatus::IsSuccess(status)) { OpStatus::Ignore(item_data.name.Set(data)); } } // Not syncing note icon return OpStatus::OK; } // HotlistModelListener methods /*************************************************************************** ** ** OnHotlistItemAdded ** ** @param HotlistModelItem* item - the item that has been added ** ** In old world, this will start they sync timer. ** **************************************************************************/ void SyncNoteItems::OnHotlistItemAdded(HotlistModelItem* item) { // OP_ASSERT(item->GetStatus() == HotlistModelItem::STATUS_NEW); if (!item) return; // Don't re-add items we're receiving if (IsProcessingIncomingItems()) { return; } // New world: Send item to sync module HotlistItemChanged(item, OpSyncDataItem::DATAITEM_ACTION_ADDED, FALSE, HotlistModel::FLAG_ADDED); } /*************************************************************************** ** ** OnHotlistItemChanged ** ** @param HotlistModelItem* item - the changed item ** @param UINT32 changed_flag - hold which changed happened ** **************************************************************************/ void SyncNoteItems::OnHotlistItemChanged(HotlistModelItem* item, BOOL moved_as_child, UINT32 changed_flag) { if (!item) return; if (IsProcessingIncomingItems() || moved_as_child) { return; } // New world: Give Item to the sync module HotlistItemChanged(item, OpSyncDataItem::DATAITEM_ACTION_MODIFIED, FALSE, changed_flag); } /*************************************************************************** ** ** OnHotlistItemRemoved ** ** @param HotlistModelItem* item - the item that is to be removed ** ** Even in old world: Add immediately to Sync when removed, or the ** removal will be lost. ** **************************************************************************/ void SyncNoteItems::OnHotlistItemRemoved(HotlistModelItem* item, BOOL removed_as_child) { if (IsProcessingIncomingItems() || !item || removed_as_child) return; // if the item was removed because it's parent was, do not send the delete // if (flag & HotlistModel::FLAG_CHILD) // return; // Send item to sync module HotlistItemChanged(item, OpSyncDataItem::DATAITEM_ACTION_DELETED, FALSE, HotlistModel::FLAG_REMOVED); } ////////////////////////////////////////////////////////////// /// Methods to create new incomings item in hotlist model /********************************************************************** ** CreateItemOrdered ** ** @param HotlistModel* model - model to create new item in ** @param type - Type of item to Create ** @param HotlistManager::ItemData& item_data - fields of new item ** @param HotlistModel* previous - ** ** Creates a new item with ItemData item_data after item previous in ** model ** ** ***********************************************************************/ OP_STATUS SyncNoteItems::CreateItemOrdered(HotlistGenericModel* model, OpSyncDataItem::DataItemType type, const HotlistManager::ItemData& item_data, HotlistModelItem* previous ) { if (!model) { return OpStatus::ERR_NULL_POINTER; } OpString name; OpTreeModelItem::Type hotlist_item_type; // Translate sync item type to hotlist item type switch ( type ) { case OpSyncDataItem::DATAITEM_NOTE: hotlist_item_type = OpTreeModelItem::NOTE_TYPE; break; case OpSyncDataItem::DATAITEM_NOTE_FOLDER: hotlist_item_type = OpTreeModelItem::FOLDER_TYPE; break; case OpSyncDataItem::DATAITEM_NOTE_SEPARATOR: hotlist_item_type = OpTreeModelItem::SEPARATOR_TYPE; break; default: OP_ASSERT(FALSE); return OpStatus::ERR; } if (!g_hotlist_manager->NewItemOrdered(model, hotlist_item_type, &item_data, previous )) { OP_ASSERT(FALSE); } return OpStatus::OK; } /****************************************************************************** ** CreateItemFirst ** ** @param HotlistModel* model - model to create new item in ** @param OpSyncDataItem::DataItemType type - type of item to create ** @param HotlistManager::ItemData& item_data - fields of new item ** HotlistModelItem* parent - Item should be inserted first in parent. ** If parent NULL, it should be inserted in root folder. ** *****************************************************************************/ OP_STATUS SyncNoteItems::CreateItemFirst(HotlistGenericModel* model, OpSyncDataItem::DataItemType type, const HotlistManager::ItemData& item_data, HotlistModelItem* parent) { if (!model) { return OpStatus::ERR_NULL_POINTER; } OpTreeModelItem::Type hotlist_item_type; // Translate sync item type to hotlist item type switch ( type ) { case OpSyncDataItem::DATAITEM_NOTE: hotlist_item_type = OpTreeModelItem::NOTE_TYPE; break; case OpSyncDataItem::DATAITEM_NOTE_FOLDER: hotlist_item_type = OpTreeModelItem::FOLDER_TYPE; break; case OpSyncDataItem::DATAITEM_NOTE_SEPARATOR: hotlist_item_type = OpTreeModelItem::SEPARATOR_TYPE; break; default: OP_ASSERT(FALSE); return OpStatus::ERR; } if(!g_hotlist_manager->NewItemFirstInFolder(model, hotlist_item_type, &item_data, parent)) { OP_ASSERT(FALSE); } return OpStatus::OK; } void SyncNoteItems::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2) { OP_ASSERT(msg == MSG_DELAYED_SYNCHRONIZATION); if(msg == MSG_DELAYED_SYNCHRONIZATION) { // unset the callback. If the user edits more, it'll be set again m_has_delayed_timer = FALSE; g_main_message_handler->UnsetCallBack(this, MSG_DELAYED_SYNCHRONIZATION); OpStatus::Ignore(SendModifiedNotes()); } } // start a delayed trigger used for sending notes to the server after a certain time interval OP_STATUS SyncNoteItems::StartTimeout() { if(m_has_delayed_timer) { // we already have a timer going. This is more efficient than checking if the message is in the message queue return OpStatus::OK; } if (!g_main_message_handler->HasCallBack(this, MSG_DELAYED_SYNCHRONIZATION, 0)) { RETURN_IF_ERROR(g_main_message_handler->SetCallBack(this, MSG_DELAYED_SYNCHRONIZATION, 0)); } g_main_message_handler->RemoveDelayedMessage(MSG_DELAYED_SYNCHRONIZATION, 0, 0); m_has_delayed_timer = TRUE; g_main_message_handler->PostDelayedMessage(MSG_DELAYED_SYNCHRONIZATION, 0, 0, SYNC_NOTES_DELAY); return OpStatus::OK; } // This should actully only send changed items (not adds or deletes) OP_STATUS SyncNoteItems::SendModifiedNotes() { HotlistModel* notes_model = g_hotlist_manager->GetNotesModel(); if (notes_model) { // send off modified but not yet synchronized items INT32 count = notes_model->GetItemCount(); for(INT32 i = 0; i < count; i++) { HotlistModelItem* item = notes_model->GetItemByIndex(i); if(item) { if (item->GetLastSyncStatus() != OpSyncDataItem::DATAITEM_ACTION_NONE) { OP_STATUS status = HotlistItemChanged(item, item->GetLastSyncStatus(), FALSE, item->GetChangedFields(), TRUE); if(OpStatus::IsError(status)) { return status; } } } } } return OpStatus::OK; }
#include "sanity.hh" #include "address.hh" using namespace std; namespace S6M { void Address::pack(ByteBuffer *bb) const { switch (type) { case SOCKS6_ADDR_IPV4: { in_addr *rawIPv4 = bb->get<in_addr>(); *rawIPv4 = get<in_addr>(u); break; } case SOCKS6_ADDR_IPV6: { in6_addr *rawIPv6 = bb->get<in6_addr>(); *rawIPv6 = get<in6_addr>(u); break; } case SOCKS6_ADDR_DOMAIN: get<Padded<String>>(u).pack(bb); break; } } Address::Address(SOCKS6AddressType type, ByteBuffer *bb) : type(type) { switch (type) { case SOCKS6_ADDR_IPV4: { u = *bb->get<in_addr>(); break; } case SOCKS6_ADDR_IPV6: { u = *bb->get<in6_addr>(); break; } case SOCKS6_ADDR_DOMAIN: u = Padded<String>(bb); break; default: throw BadAddressTypeException(); } } }
#ifndef WIDGETSCROLLBAR_HH_ #define WIDGETSCROLLBAR_HH_ #include <pgscrollbar.h> /** This class is used to derive the ParaGUI's scroll bar and fix/customize some * behaviour. Fixes are: * 1) Drag buttons size correlates to the page size and scroll area. * 2) When scroll size is zero, the drag button doesn't position itself on top * of the left/top-most scroll button */ class WidgetScrollBar : public PG_ScrollBar { public: WidgetScrollBar(PG_Widget *parent, const PG_Rect &rect = PG_Rect::null, ScrollDirection direction = VERTICAL, int id = -1, const std::string &style = "Scrollbar"); virtual ~WidgetScrollBar() { } /** This will overwrite the function in a STATIC way. */ void SetRange(Uint32 min, Uint32 max); protected: virtual void RecalcPositions(); private: void calculate_position_and_size(Sint16 start_pos, Uint16 total_size, Sint16 &position, Uint16 &size); void calculate_borders(Sint16 &position, Uint16 &size); }; #endif /*WIDGETSCROLLBAR_HH_*/
//Enunt: // Daca intr-un algoritm exista: char a = '4' // int b = 8 // bool c = false // evaluati expresiile: (b>15) or c // a>= '0'and a<='9' // not c or (a = 'a') // (a > b) and c #include <iostream> #include <string> // operatii cu std::string int main() { char a = '4'; int b = 8; bool c = false; // cele doua exemple de mai jos fac aceeasi lucru // exemplu de evaluare indirecta (mai putin frumoasa dar mai clara) std::cout << "(b > 15) or c: "; if ((b > 15) || c) std::cout << "true"; else std::cout << "false"; std::cout << std::endl << std::endl; // evaluare directa (simplificata pe o linie si frumoasa) - scrie true si false in loc de 0 si 1 std::cout << "(b > 15) or c: " << std::string(((b > 15) || c) ? "true" : "false") << std::endl; std::cout << "a >= '0' and a <= '9': " << std::string((a >= '0' && a <= '9') ? "true" : "false") << std::endl; std::cout << "not c or (a = 'a'): " << std::string((!c || (a = 'a')) ? "true" : "false") << std::endl; std::cout << "(a > b) and c: " << std::string(((a > b ) && c) ? "true" : "false") << std::endl; std::cout << std::endl; system("pause"); return 0; }
#ifndef __NODE_MERGE_SCAN_H #define __NODE_MERGE_SCAN_H #include <ros/ros.h> #include <laser_geometry/laser_geometry.h> #include <tf/transform_broadcaster.h> #include <sensor_msgs/PointCloud.h> #include <sensor_msgs/LaserScan.h> #include <tf/transform_listener.h> #include <vector> #include <string> #include <boost/make_shared.hpp> using namespace std; class MergeLidarScan { public: MergeLidarScan() : node_rate(1) {} ~MergeLidarScan() {} bool isOK() {return nh.ok();} void LoadRosParam() { ros::param::get("/lidar_left/pose", pose_lidar_left); ros::param::get("/lidar_right/pose", pose_lidar_right); ros::param::get("/lidar_left/frame_id", frame_lidar_left); ros::param::get("/lidar_right/frame_id", frame_lidar_right); pub_point_cloud = nh.advertise<sensor_msgs::PointCloud>("transfer_point_cloud", 1); sub_lidar_left = nh.subscribe(frame_lidar_left, 5, &MergeLidarScan::callback_lidar_left, this); sub_lidar_right = nh.subscribe(frame_lidar_right, 5, &MergeLidarScan::callback_lidar_right, this); } void UpdateTF() { tf::Transform tfmLeft; tfmLeft.setOrigin(tf::Vector3(pose_lidar_left[0], pose_lidar_left[1], pose_lidar_left[2])); tf::Quaternion qLeft; qLeft.setRPY(0.0, 0.0, pose_lidar_left[3]); tfmLeft.setRotation(qLeft); stmLeft = tf::StampedTransform(tfmLeft, ros::Time::now(), "transfer", frame_lidar_left); tf::Transform tfmRight; tfmRight.setOrigin(tf::Vector3(pose_lidar_right[0], pose_lidar_right[1], pose_lidar_right[2])); tf::Quaternion qRight; qRight.setRPY(0.0, 0.0, pose_lidar_right[3]); tfmRight.setRotation(qRight); stmRight = tf::StampedTransform(tfmRight, ros::Time::now(), "transfer", frame_lidar_right); } void callback_lidar_left(const sensor_msgs::LaserScan msg) { sensor_msgs::PointCloud pcd; ROS_WARN("----- callback scan left: 0"); try { tflLeft.waitForTransform(frame_lidar_left, frame_merge_scan, ros::Time::now(), ros::Duration(30.0)); ROS_WARN("----- callback scan left: 1"); projector_.transformLaserScanToPointCloud(frame_merge_scan, msg, pcd, tflLeft); ROS_WARN("----- callback scan left: 2"); pcd_merge_raw[msg.header.frame_id] = boost::make_shared<sensor_msgs::PointCloud>(pcd); ROS_WARN("----- callback scan left: 3"); } catch (tf::TransformException exp) { ROS_WARN("Failed to transform coordinateL: %s", exp.what()); } } void callback_lidar_right(const sensor_msgs::LaserScan msg) { sensor_msgs::PointCloud pcd; try { tflLeft.waitForTransform(frame_lidar_right, frame_merge_scan, ros::Time::now(), ros::Duration(0.1)); projector_.transformLaserScanToPointCloud(frame_merge_scan, msg, pcd, tflRight); pcd_merge_raw[msg.header.frame_id] = boost::make_shared<sensor_msgs::PointCloud>(pcd); } catch (tf::TransformException exp) { ROS_WARN("Failed to transform Right Lidar frame into transfer coordinate"); } } void publish_pcd_merge() { cloud_points.clear(); map<string, sensor_msgs::PointCloudPtr>::iterator iter; for (iter = pcd_merge_raw.begin(); iter != pcd_merge_raw.end(); iter++) { string frame_id = iter->first; for (auto &pt : iter->second->points) { // add limition on points if necessary cloud_points.push_back(pt); } } if (cloud_points.size() > 0) { sensor_msgs::PointCloudPtr msg_pc(new sensor_msgs::PointCloud); msg_pc->header.frame_id = frame_merge_scan; msg_pc->header.stamp = ros::Time::now(); msg_pc->points.assign(cloud_points.begin(), cloud_points.end()); pub_point_cloud.publish(msg_pc); } } void single_loop() { ros::spinOnce(); UpdateTF(); broadcaster.sendTransform(stmLeft); broadcaster.sendTransform(stmRight); publish_pcd_merge(); node_rate.sleep(); } private: ros::NodeHandle nh; ros::Rate node_rate; tf::TransformBroadcaster broadcaster; tf::StampedTransform stmLeft; tf::StampedTransform stmRight; laser_geometry::LaserProjection projector_; tf::TransformListener tflLeft; tf::TransformListener tflRight; ros::Publisher pub_point_cloud; ros::Subscriber sub_lidar_left; ros::Subscriber sub_lidar_right; vector<double> pose_lidar_left; // Lidar pose [x, y, z, yaw] vector<double> pose_lidar_right; const string frame_merge_scan = "transfer"; string frame_lidar_left; // frame ID of Lidar string frame_lidar_right; map<string, sensor_msgs::PointCloudPtr> pcd_merge_raw; vector<geometry_msgs::Point32> cloud_points; }; #endif
// Generated from D:/4IF/PLD-COMP/Compilateur01\fichierAntlr.g4 by ANTLR 4.7 #include "fichierAntlrVisitor.h" #include "fichierAntlrParser.h" using namespace antlrcpp; using namespace antlr4; fichierAntlrParser::fichierAntlrParser(TokenStream *input) : Parser(input) { _interpreter = new atn::ParserATNSimulator(this, _atn, _decisionToDFA, _sharedContextCache); } fichierAntlrParser::~fichierAntlrParser() { delete _interpreter; } std::string fichierAntlrParser::getGrammarFileName() const { return "fichierAntlr.g4"; } const std::vector<std::string>& fichierAntlrParser::getRuleNames() const { return _ruleNames; } dfa::Vocabulary& fichierAntlrParser::getVocabulary() const { return _vocabulary; } //----------------- ProgrammeContext ------------------------------------------------------------------ fichierAntlrParser::ProgrammeContext::ProgrammeContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } size_t fichierAntlrParser::ProgrammeContext::getRuleIndex() const { return fichierAntlrParser::RuleProgramme; } void fichierAntlrParser::ProgrammeContext::copyFrom(ProgrammeContext *ctx) { ParserRuleContext::copyFrom(ctx); } //----------------- Programme_normalContext ------------------------------------------------------------------ std::vector<fichierAntlrParser::DeclarationContext *> fichierAntlrParser::Programme_normalContext::declaration() { return getRuleContexts<fichierAntlrParser::DeclarationContext>(); } fichierAntlrParser::DeclarationContext* fichierAntlrParser::Programme_normalContext::declaration(size_t i) { return getRuleContext<fichierAntlrParser::DeclarationContext>(i); } std::vector<fichierAntlrParser::FonctionContext *> fichierAntlrParser::Programme_normalContext::fonction() { return getRuleContexts<fichierAntlrParser::FonctionContext>(); } fichierAntlrParser::FonctionContext* fichierAntlrParser::Programme_normalContext::fonction(size_t i) { return getRuleContext<fichierAntlrParser::FonctionContext>(i); } std::vector<fichierAntlrParser::MainContext *> fichierAntlrParser::Programme_normalContext::main() { return getRuleContexts<fichierAntlrParser::MainContext>(); } fichierAntlrParser::MainContext* fichierAntlrParser::Programme_normalContext::main(size_t i) { return getRuleContext<fichierAntlrParser::MainContext>(i); } fichierAntlrParser::Programme_normalContext::Programme_normalContext(ProgrammeContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Programme_normalContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitProgramme_normal(this); else return visitor->visitChildren(this); } fichierAntlrParser::ProgrammeContext* fichierAntlrParser::programme() { ProgrammeContext *_localctx = _tracker.createInstance<ProgrammeContext>(_ctx, getState()); enterRule(_localctx, 0, fichierAntlrParser::RuleProgramme); size_t _la = 0; auto onExit = finally([=] { exitRule(); }); try { size_t alt; _localctx = dynamic_cast<ProgrammeContext *>(_tracker.createInstance<fichierAntlrParser::Programme_normalContext>(_localctx)); enterOuterAlt(_localctx, 1); setState(37); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 0, _ctx); while (alt != 2 && alt != atn::ATN::INVALID_ALT_NUMBER) { if (alt == 1) { setState(34); declaration(); } setState(39); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 0, _ctx); } setState(43); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 1, _ctx); while (alt != 2 && alt != atn::ATN::INVALID_ALT_NUMBER) { if (alt == 1) { setState(40); fonction(); } setState(45); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 1, _ctx); } setState(49); _errHandler->sync(this); _la = _input->LA(1); while ((((_la & ~ 0x3fULL) == 0) && ((1ULL << _la) & ((1ULL << fichierAntlrParser::T__5) | (1ULL << fichierAntlrParser::T__45) | (1ULL << fichierAntlrParser::T__46) | (1ULL << fichierAntlrParser::T__47) | (1ULL << fichierAntlrParser::T__48))) != 0)) { setState(46); main(); setState(51); _errHandler->sync(this); _la = _input->LA(1); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- MainContext ------------------------------------------------------------------ fichierAntlrParser::MainContext::MainContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } size_t fichierAntlrParser::MainContext::getRuleIndex() const { return fichierAntlrParser::RuleMain; } void fichierAntlrParser::MainContext::copyFrom(MainContext *ctx) { ParserRuleContext::copyFrom(ctx); } //----------------- Main_parametrevoidContext ------------------------------------------------------------------ fichierAntlrParser::Type_fonctionContext* fichierAntlrParser::Main_parametrevoidContext::type_fonction() { return getRuleContext<fichierAntlrParser::Type_fonctionContext>(0); } fichierAntlrParser::BlocContext* fichierAntlrParser::Main_parametrevoidContext::bloc() { return getRuleContext<fichierAntlrParser::BlocContext>(0); } std::vector<fichierAntlrParser::DeclarationContext *> fichierAntlrParser::Main_parametrevoidContext::declaration() { return getRuleContexts<fichierAntlrParser::DeclarationContext>(); } fichierAntlrParser::DeclarationContext* fichierAntlrParser::Main_parametrevoidContext::declaration(size_t i) { return getRuleContext<fichierAntlrParser::DeclarationContext>(i); } fichierAntlrParser::Main_parametrevoidContext::Main_parametrevoidContext(MainContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Main_parametrevoidContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitMain_parametrevoid(this); else return visitor->visitChildren(this); } //----------------- Main_sansparametreContext ------------------------------------------------------------------ fichierAntlrParser::Type_fonctionContext* fichierAntlrParser::Main_sansparametreContext::type_fonction() { return getRuleContext<fichierAntlrParser::Type_fonctionContext>(0); } fichierAntlrParser::BlocContext* fichierAntlrParser::Main_sansparametreContext::bloc() { return getRuleContext<fichierAntlrParser::BlocContext>(0); } std::vector<fichierAntlrParser::DeclarationContext *> fichierAntlrParser::Main_sansparametreContext::declaration() { return getRuleContexts<fichierAntlrParser::DeclarationContext>(); } fichierAntlrParser::DeclarationContext* fichierAntlrParser::Main_sansparametreContext::declaration(size_t i) { return getRuleContext<fichierAntlrParser::DeclarationContext>(i); } fichierAntlrParser::Main_sansparametreContext::Main_sansparametreContext(MainContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Main_sansparametreContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitMain_sansparametre(this); else return visitor->visitChildren(this); } //----------------- Main_avecparametreContext ------------------------------------------------------------------ fichierAntlrParser::Type_fonctionContext* fichierAntlrParser::Main_avecparametreContext::type_fonction() { return getRuleContext<fichierAntlrParser::Type_fonctionContext>(0); } fichierAntlrParser::ParametreContext* fichierAntlrParser::Main_avecparametreContext::parametre() { return getRuleContext<fichierAntlrParser::ParametreContext>(0); } fichierAntlrParser::BlocContext* fichierAntlrParser::Main_avecparametreContext::bloc() { return getRuleContext<fichierAntlrParser::BlocContext>(0); } std::vector<fichierAntlrParser::DeclarationContext *> fichierAntlrParser::Main_avecparametreContext::declaration() { return getRuleContexts<fichierAntlrParser::DeclarationContext>(); } fichierAntlrParser::DeclarationContext* fichierAntlrParser::Main_avecparametreContext::declaration(size_t i) { return getRuleContext<fichierAntlrParser::DeclarationContext>(i); } fichierAntlrParser::Main_avecparametreContext::Main_avecparametreContext(MainContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Main_avecparametreContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitMain_avecparametre(this); else return visitor->visitChildren(this); } fichierAntlrParser::MainContext* fichierAntlrParser::main() { MainContext *_localctx = _tracker.createInstance<MainContext>(_ctx, getState()); enterRule(_localctx, 2, fichierAntlrParser::RuleMain); size_t _la = 0; auto onExit = finally([=] { exitRule(); }); try { setState(96); _errHandler->sync(this); switch (getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 6, _ctx)) { case 1: { _localctx = dynamic_cast<MainContext *>(_tracker.createInstance<fichierAntlrParser::Main_avecparametreContext>(_localctx)); enterOuterAlt(_localctx, 1); setState(52); type_fonction(); setState(53); match(fichierAntlrParser::T__0); setState(54); match(fichierAntlrParser::T__1); setState(55); parametre(); setState(56); match(fichierAntlrParser::T__2); setState(57); match(fichierAntlrParser::T__3); setState(61); _errHandler->sync(this); _la = _input->LA(1); while ((((_la & ~ 0x3fULL) == 0) && ((1ULL << _la) & ((1ULL << fichierAntlrParser::T__45) | (1ULL << fichierAntlrParser::T__46) | (1ULL << fichierAntlrParser::T__47))) != 0)) { setState(58); declaration(); setState(63); _errHandler->sync(this); _la = _input->LA(1); } setState(64); bloc(); setState(65); match(fichierAntlrParser::T__4); break; } case 2: { _localctx = dynamic_cast<MainContext *>(_tracker.createInstance<fichierAntlrParser::Main_sansparametreContext>(_localctx)); enterOuterAlt(_localctx, 2); setState(67); type_fonction(); setState(68); match(fichierAntlrParser::T__0); setState(69); match(fichierAntlrParser::T__1); setState(70); match(fichierAntlrParser::T__2); setState(71); match(fichierAntlrParser::T__3); setState(75); _errHandler->sync(this); _la = _input->LA(1); while ((((_la & ~ 0x3fULL) == 0) && ((1ULL << _la) & ((1ULL << fichierAntlrParser::T__45) | (1ULL << fichierAntlrParser::T__46) | (1ULL << fichierAntlrParser::T__47))) != 0)) { setState(72); declaration(); setState(77); _errHandler->sync(this); _la = _input->LA(1); } setState(78); bloc(); setState(79); match(fichierAntlrParser::T__4); break; } case 3: { _localctx = dynamic_cast<MainContext *>(_tracker.createInstance<fichierAntlrParser::Main_parametrevoidContext>(_localctx)); enterOuterAlt(_localctx, 3); setState(81); type_fonction(); setState(82); match(fichierAntlrParser::T__0); setState(83); match(fichierAntlrParser::T__1); setState(84); match(fichierAntlrParser::T__5); setState(85); match(fichierAntlrParser::T__2); setState(86); match(fichierAntlrParser::T__3); setState(90); _errHandler->sync(this); _la = _input->LA(1); while ((((_la & ~ 0x3fULL) == 0) && ((1ULL << _la) & ((1ULL << fichierAntlrParser::T__45) | (1ULL << fichierAntlrParser::T__46) | (1ULL << fichierAntlrParser::T__47))) != 0)) { setState(87); declaration(); setState(92); _errHandler->sync(this); _la = _input->LA(1); } setState(93); bloc(); setState(94); match(fichierAntlrParser::T__4); break; } } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- FonctionContext ------------------------------------------------------------------ fichierAntlrParser::FonctionContext::FonctionContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } size_t fichierAntlrParser::FonctionContext::getRuleIndex() const { return fichierAntlrParser::RuleFonction; } void fichierAntlrParser::FonctionContext::copyFrom(FonctionContext *ctx) { ParserRuleContext::copyFrom(ctx); } //----------------- Fonction_avecparametreContext ------------------------------------------------------------------ fichierAntlrParser::Type_fonctionContext* fichierAntlrParser::Fonction_avecparametreContext::type_fonction() { return getRuleContext<fichierAntlrParser::Type_fonctionContext>(0); } tree::TerminalNode* fichierAntlrParser::Fonction_avecparametreContext::NOM() { return getToken(fichierAntlrParser::NOM, 0); } fichierAntlrParser::ParametreContext* fichierAntlrParser::Fonction_avecparametreContext::parametre() { return getRuleContext<fichierAntlrParser::ParametreContext>(0); } fichierAntlrParser::BlocContext* fichierAntlrParser::Fonction_avecparametreContext::bloc() { return getRuleContext<fichierAntlrParser::BlocContext>(0); } std::vector<fichierAntlrParser::DeclarationContext *> fichierAntlrParser::Fonction_avecparametreContext::declaration() { return getRuleContexts<fichierAntlrParser::DeclarationContext>(); } fichierAntlrParser::DeclarationContext* fichierAntlrParser::Fonction_avecparametreContext::declaration(size_t i) { return getRuleContext<fichierAntlrParser::DeclarationContext>(i); } fichierAntlrParser::Fonction_avecparametreContext::Fonction_avecparametreContext(FonctionContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Fonction_avecparametreContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitFonction_avecparametre(this); else return visitor->visitChildren(this); } //----------------- Fonction_parametrevoidContext ------------------------------------------------------------------ fichierAntlrParser::Type_fonctionContext* fichierAntlrParser::Fonction_parametrevoidContext::type_fonction() { return getRuleContext<fichierAntlrParser::Type_fonctionContext>(0); } tree::TerminalNode* fichierAntlrParser::Fonction_parametrevoidContext::NOM() { return getToken(fichierAntlrParser::NOM, 0); } fichierAntlrParser::BlocContext* fichierAntlrParser::Fonction_parametrevoidContext::bloc() { return getRuleContext<fichierAntlrParser::BlocContext>(0); } std::vector<fichierAntlrParser::DeclarationContext *> fichierAntlrParser::Fonction_parametrevoidContext::declaration() { return getRuleContexts<fichierAntlrParser::DeclarationContext>(); } fichierAntlrParser::DeclarationContext* fichierAntlrParser::Fonction_parametrevoidContext::declaration(size_t i) { return getRuleContext<fichierAntlrParser::DeclarationContext>(i); } fichierAntlrParser::Fonction_parametrevoidContext::Fonction_parametrevoidContext(FonctionContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Fonction_parametrevoidContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitFonction_parametrevoid(this); else return visitor->visitChildren(this); } //----------------- Fonction_sansparametreContext ------------------------------------------------------------------ fichierAntlrParser::Type_fonctionContext* fichierAntlrParser::Fonction_sansparametreContext::type_fonction() { return getRuleContext<fichierAntlrParser::Type_fonctionContext>(0); } tree::TerminalNode* fichierAntlrParser::Fonction_sansparametreContext::NOM() { return getToken(fichierAntlrParser::NOM, 0); } fichierAntlrParser::BlocContext* fichierAntlrParser::Fonction_sansparametreContext::bloc() { return getRuleContext<fichierAntlrParser::BlocContext>(0); } std::vector<fichierAntlrParser::DeclarationContext *> fichierAntlrParser::Fonction_sansparametreContext::declaration() { return getRuleContexts<fichierAntlrParser::DeclarationContext>(); } fichierAntlrParser::DeclarationContext* fichierAntlrParser::Fonction_sansparametreContext::declaration(size_t i) { return getRuleContext<fichierAntlrParser::DeclarationContext>(i); } fichierAntlrParser::Fonction_sansparametreContext::Fonction_sansparametreContext(FonctionContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Fonction_sansparametreContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitFonction_sansparametre(this); else return visitor->visitChildren(this); } fichierAntlrParser::FonctionContext* fichierAntlrParser::fonction() { FonctionContext *_localctx = _tracker.createInstance<FonctionContext>(_ctx, getState()); enterRule(_localctx, 4, fichierAntlrParser::RuleFonction); size_t _la = 0; auto onExit = finally([=] { exitRule(); }); try { setState(142); _errHandler->sync(this); switch (getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 10, _ctx)) { case 1: { _localctx = dynamic_cast<FonctionContext *>(_tracker.createInstance<fichierAntlrParser::Fonction_avecparametreContext>(_localctx)); enterOuterAlt(_localctx, 1); setState(98); type_fonction(); setState(99); match(fichierAntlrParser::NOM); setState(100); match(fichierAntlrParser::T__1); setState(101); parametre(); setState(102); match(fichierAntlrParser::T__2); setState(103); match(fichierAntlrParser::T__3); setState(107); _errHandler->sync(this); _la = _input->LA(1); while ((((_la & ~ 0x3fULL) == 0) && ((1ULL << _la) & ((1ULL << fichierAntlrParser::T__45) | (1ULL << fichierAntlrParser::T__46) | (1ULL << fichierAntlrParser::T__47))) != 0)) { setState(104); declaration(); setState(109); _errHandler->sync(this); _la = _input->LA(1); } setState(110); bloc(); setState(111); match(fichierAntlrParser::T__4); break; } case 2: { _localctx = dynamic_cast<FonctionContext *>(_tracker.createInstance<fichierAntlrParser::Fonction_sansparametreContext>(_localctx)); enterOuterAlt(_localctx, 2); setState(113); type_fonction(); setState(114); match(fichierAntlrParser::NOM); setState(115); match(fichierAntlrParser::T__1); setState(116); match(fichierAntlrParser::T__2); setState(117); match(fichierAntlrParser::T__3); setState(121); _errHandler->sync(this); _la = _input->LA(1); while ((((_la & ~ 0x3fULL) == 0) && ((1ULL << _la) & ((1ULL << fichierAntlrParser::T__45) | (1ULL << fichierAntlrParser::T__46) | (1ULL << fichierAntlrParser::T__47))) != 0)) { setState(118); declaration(); setState(123); _errHandler->sync(this); _la = _input->LA(1); } setState(124); bloc(); setState(125); match(fichierAntlrParser::T__4); break; } case 3: { _localctx = dynamic_cast<FonctionContext *>(_tracker.createInstance<fichierAntlrParser::Fonction_parametrevoidContext>(_localctx)); enterOuterAlt(_localctx, 3); setState(127); type_fonction(); setState(128); match(fichierAntlrParser::NOM); setState(129); match(fichierAntlrParser::T__1); setState(130); match(fichierAntlrParser::T__5); setState(131); match(fichierAntlrParser::T__2); setState(132); match(fichierAntlrParser::T__3); setState(136); _errHandler->sync(this); _la = _input->LA(1); while ((((_la & ~ 0x3fULL) == 0) && ((1ULL << _la) & ((1ULL << fichierAntlrParser::T__45) | (1ULL << fichierAntlrParser::T__46) | (1ULL << fichierAntlrParser::T__47))) != 0)) { setState(133); declaration(); setState(138); _errHandler->sync(this); _la = _input->LA(1); } setState(139); bloc(); setState(140); match(fichierAntlrParser::T__4); break; } } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- ParametreContext ------------------------------------------------------------------ fichierAntlrParser::ParametreContext::ParametreContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } size_t fichierAntlrParser::ParametreContext::getRuleIndex() const { return fichierAntlrParser::RuleParametre; } void fichierAntlrParser::ParametreContext::copyFrom(ParametreContext *ctx) { ParserRuleContext::copyFrom(ctx); } //----------------- Parametre_tableauContext ------------------------------------------------------------------ fichierAntlrParser::Type_varContext* fichierAntlrParser::Parametre_tableauContext::type_var() { return getRuleContext<fichierAntlrParser::Type_varContext>(0); } tree::TerminalNode* fichierAntlrParser::Parametre_tableauContext::NOM() { return getToken(fichierAntlrParser::NOM, 0); } tree::TerminalNode* fichierAntlrParser::Parametre_tableauContext::CHIFFRE() { return getToken(fichierAntlrParser::CHIFFRE, 0); } fichierAntlrParser::Parametre_tableauContext::Parametre_tableauContext(ParametreContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Parametre_tableauContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitParametre_tableau(this); else return visitor->visitChildren(this); } //----------------- Parametre_normalContext ------------------------------------------------------------------ fichierAntlrParser::Type_varContext* fichierAntlrParser::Parametre_normalContext::type_var() { return getRuleContext<fichierAntlrParser::Type_varContext>(0); } tree::TerminalNode* fichierAntlrParser::Parametre_normalContext::NOM() { return getToken(fichierAntlrParser::NOM, 0); } fichierAntlrParser::Parametre_normalContext::Parametre_normalContext(ParametreContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Parametre_normalContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitParametre_normal(this); else return visitor->visitChildren(this); } fichierAntlrParser::ParametreContext* fichierAntlrParser::parametre() { ParametreContext *_localctx = _tracker.createInstance<ParametreContext>(_ctx, getState()); enterRule(_localctx, 6, fichierAntlrParser::RuleParametre); auto onExit = finally([=] { exitRule(); }); try { setState(153); _errHandler->sync(this); switch (getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 11, _ctx)) { case 1: { _localctx = dynamic_cast<ParametreContext *>(_tracker.createInstance<fichierAntlrParser::Parametre_normalContext>(_localctx)); enterOuterAlt(_localctx, 1); setState(144); type_var(); setState(145); match(fichierAntlrParser::NOM); break; } case 2: { _localctx = dynamic_cast<ParametreContext *>(_tracker.createInstance<fichierAntlrParser::Parametre_tableauContext>(_localctx)); enterOuterAlt(_localctx, 2); setState(147); type_var(); setState(148); match(fichierAntlrParser::NOM); setState(149); match(fichierAntlrParser::T__6); setState(150); match(fichierAntlrParser::CHIFFRE); setState(151); match(fichierAntlrParser::T__7); break; } } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- VariableContext ------------------------------------------------------------------ fichierAntlrParser::VariableContext::VariableContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } size_t fichierAntlrParser::VariableContext::getRuleIndex() const { return fichierAntlrParser::RuleVariable; } void fichierAntlrParser::VariableContext::copyFrom(VariableContext *ctx) { ParserRuleContext::copyFrom(ctx); } //----------------- Variable_simpleContext ------------------------------------------------------------------ tree::TerminalNode* fichierAntlrParser::Variable_simpleContext::NOM() { return getToken(fichierAntlrParser::NOM, 0); } fichierAntlrParser::Variable_simpleContext::Variable_simpleContext(VariableContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Variable_simpleContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitVariable_simple(this); else return visitor->visitChildren(this); } //----------------- Variable_tableauContext ------------------------------------------------------------------ tree::TerminalNode* fichierAntlrParser::Variable_tableauContext::NOM() { return getToken(fichierAntlrParser::NOM, 0); } fichierAntlrParser::ExprContext* fichierAntlrParser::Variable_tableauContext::expr() { return getRuleContext<fichierAntlrParser::ExprContext>(0); } fichierAntlrParser::Variable_tableauContext::Variable_tableauContext(VariableContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Variable_tableauContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitVariable_tableau(this); else return visitor->visitChildren(this); } fichierAntlrParser::VariableContext* fichierAntlrParser::variable() { VariableContext *_localctx = _tracker.createInstance<VariableContext>(_ctx, getState()); enterRule(_localctx, 8, fichierAntlrParser::RuleVariable); auto onExit = finally([=] { exitRule(); }); try { setState(161); _errHandler->sync(this); switch (getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 12, _ctx)) { case 1: { _localctx = dynamic_cast<VariableContext *>(_tracker.createInstance<fichierAntlrParser::Variable_simpleContext>(_localctx)); enterOuterAlt(_localctx, 1); setState(155); match(fichierAntlrParser::NOM); break; } case 2: { _localctx = dynamic_cast<VariableContext *>(_tracker.createInstance<fichierAntlrParser::Variable_tableauContext>(_localctx)); enterOuterAlt(_localctx, 2); setState(156); match(fichierAntlrParser::NOM); setState(157); match(fichierAntlrParser::T__6); setState(158); expr(0); setState(159); match(fichierAntlrParser::T__7); break; } } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- AffectationContext ------------------------------------------------------------------ fichierAntlrParser::AffectationContext::AffectationContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } size_t fichierAntlrParser::AffectationContext::getRuleIndex() const { return fichierAntlrParser::RuleAffectation; } void fichierAntlrParser::AffectationContext::copyFrom(AffectationContext *ctx) { ParserRuleContext::copyFrom(ctx); } //----------------- Affectation_plusegalContext ------------------------------------------------------------------ fichierAntlrParser::VariableContext* fichierAntlrParser::Affectation_plusegalContext::variable() { return getRuleContext<fichierAntlrParser::VariableContext>(0); } fichierAntlrParser::ExprContext* fichierAntlrParser::Affectation_plusegalContext::expr() { return getRuleContext<fichierAntlrParser::ExprContext>(0); } fichierAntlrParser::Affectation_plusegalContext::Affectation_plusegalContext(AffectationContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Affectation_plusegalContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitAffectation_plusegal(this); else return visitor->visitChildren(this); } //----------------- Affectation_plusplusavantContext ------------------------------------------------------------------ fichierAntlrParser::VariableContext* fichierAntlrParser::Affectation_plusplusavantContext::variable() { return getRuleContext<fichierAntlrParser::VariableContext>(0); } fichierAntlrParser::Affectation_plusplusavantContext::Affectation_plusplusavantContext(AffectationContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Affectation_plusplusavantContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitAffectation_plusplusavant(this); else return visitor->visitChildren(this); } //----------------- Affectation_ouegalContext ------------------------------------------------------------------ fichierAntlrParser::VariableContext* fichierAntlrParser::Affectation_ouegalContext::variable() { return getRuleContext<fichierAntlrParser::VariableContext>(0); } fichierAntlrParser::ExprContext* fichierAntlrParser::Affectation_ouegalContext::expr() { return getRuleContext<fichierAntlrParser::ExprContext>(0); } fichierAntlrParser::Affectation_ouegalContext::Affectation_ouegalContext(AffectationContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Affectation_ouegalContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitAffectation_ouegal(this); else return visitor->visitChildren(this); } //----------------- Affectation_supegalContext ------------------------------------------------------------------ fichierAntlrParser::VariableContext* fichierAntlrParser::Affectation_supegalContext::variable() { return getRuleContext<fichierAntlrParser::VariableContext>(0); } fichierAntlrParser::ExprContext* fichierAntlrParser::Affectation_supegalContext::expr() { return getRuleContext<fichierAntlrParser::ExprContext>(0); } fichierAntlrParser::Affectation_supegalContext::Affectation_supegalContext(AffectationContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Affectation_supegalContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitAffectation_supegal(this); else return visitor->visitChildren(this); } //----------------- Affectation_plusplusapresContext ------------------------------------------------------------------ fichierAntlrParser::VariableContext* fichierAntlrParser::Affectation_plusplusapresContext::variable() { return getRuleContext<fichierAntlrParser::VariableContext>(0); } fichierAntlrParser::Affectation_plusplusapresContext::Affectation_plusplusapresContext(AffectationContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Affectation_plusplusapresContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitAffectation_plusplusapres(this); else return visitor->visitChildren(this); } //----------------- Affectation_divegalContext ------------------------------------------------------------------ fichierAntlrParser::VariableContext* fichierAntlrParser::Affectation_divegalContext::variable() { return getRuleContext<fichierAntlrParser::VariableContext>(0); } fichierAntlrParser::ExprContext* fichierAntlrParser::Affectation_divegalContext::expr() { return getRuleContext<fichierAntlrParser::ExprContext>(0); } fichierAntlrParser::Affectation_divegalContext::Affectation_divegalContext(AffectationContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Affectation_divegalContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitAffectation_divegal(this); else return visitor->visitChildren(this); } //----------------- Affectation_foisegalContext ------------------------------------------------------------------ fichierAntlrParser::VariableContext* fichierAntlrParser::Affectation_foisegalContext::variable() { return getRuleContext<fichierAntlrParser::VariableContext>(0); } fichierAntlrParser::ExprContext* fichierAntlrParser::Affectation_foisegalContext::expr() { return getRuleContext<fichierAntlrParser::ExprContext>(0); } fichierAntlrParser::Affectation_foisegalContext::Affectation_foisegalContext(AffectationContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Affectation_foisegalContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitAffectation_foisegal(this); else return visitor->visitChildren(this); } //----------------- Affectation_moinsmoinsapresContext ------------------------------------------------------------------ fichierAntlrParser::VariableContext* fichierAntlrParser::Affectation_moinsmoinsapresContext::variable() { return getRuleContext<fichierAntlrParser::VariableContext>(0); } fichierAntlrParser::Affectation_moinsmoinsapresContext::Affectation_moinsmoinsapresContext(AffectationContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Affectation_moinsmoinsapresContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitAffectation_moinsmoinsapres(this); else return visitor->visitChildren(this); } //----------------- Affectation_pourcentegalContext ------------------------------------------------------------------ fichierAntlrParser::VariableContext* fichierAntlrParser::Affectation_pourcentegalContext::variable() { return getRuleContext<fichierAntlrParser::VariableContext>(0); } fichierAntlrParser::ExprContext* fichierAntlrParser::Affectation_pourcentegalContext::expr() { return getRuleContext<fichierAntlrParser::ExprContext>(0); } fichierAntlrParser::Affectation_pourcentegalContext::Affectation_pourcentegalContext(AffectationContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Affectation_pourcentegalContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitAffectation_pourcentegal(this); else return visitor->visitChildren(this); } //----------------- Affectation_egalContext ------------------------------------------------------------------ fichierAntlrParser::VariableContext* fichierAntlrParser::Affectation_egalContext::variable() { return getRuleContext<fichierAntlrParser::VariableContext>(0); } fichierAntlrParser::ExprContext* fichierAntlrParser::Affectation_egalContext::expr() { return getRuleContext<fichierAntlrParser::ExprContext>(0); } fichierAntlrParser::Affectation_egalContext::Affectation_egalContext(AffectationContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Affectation_egalContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitAffectation_egal(this); else return visitor->visitChildren(this); } //----------------- Affectation_etegalContext ------------------------------------------------------------------ fichierAntlrParser::VariableContext* fichierAntlrParser::Affectation_etegalContext::variable() { return getRuleContext<fichierAntlrParser::VariableContext>(0); } fichierAntlrParser::ExprContext* fichierAntlrParser::Affectation_etegalContext::expr() { return getRuleContext<fichierAntlrParser::ExprContext>(0); } fichierAntlrParser::Affectation_etegalContext::Affectation_etegalContext(AffectationContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Affectation_etegalContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitAffectation_etegal(this); else return visitor->visitChildren(this); } //----------------- Affectation_moinsmoinsavantContext ------------------------------------------------------------------ fichierAntlrParser::VariableContext* fichierAntlrParser::Affectation_moinsmoinsavantContext::variable() { return getRuleContext<fichierAntlrParser::VariableContext>(0); } fichierAntlrParser::Affectation_moinsmoinsavantContext::Affectation_moinsmoinsavantContext(AffectationContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Affectation_moinsmoinsavantContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitAffectation_moinsmoinsavant(this); else return visitor->visitChildren(this); } //----------------- Affectation_infegalContext ------------------------------------------------------------------ fichierAntlrParser::VariableContext* fichierAntlrParser::Affectation_infegalContext::variable() { return getRuleContext<fichierAntlrParser::VariableContext>(0); } fichierAntlrParser::ExprContext* fichierAntlrParser::Affectation_infegalContext::expr() { return getRuleContext<fichierAntlrParser::ExprContext>(0); } fichierAntlrParser::Affectation_infegalContext::Affectation_infegalContext(AffectationContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Affectation_infegalContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitAffectation_infegal(this); else return visitor->visitChildren(this); } //----------------- Affectation_moinsegalContext ------------------------------------------------------------------ fichierAntlrParser::VariableContext* fichierAntlrParser::Affectation_moinsegalContext::variable() { return getRuleContext<fichierAntlrParser::VariableContext>(0); } fichierAntlrParser::ExprContext* fichierAntlrParser::Affectation_moinsegalContext::expr() { return getRuleContext<fichierAntlrParser::ExprContext>(0); } fichierAntlrParser::Affectation_moinsegalContext::Affectation_moinsegalContext(AffectationContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Affectation_moinsegalContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitAffectation_moinsegal(this); else return visitor->visitChildren(this); } fichierAntlrParser::AffectationContext* fichierAntlrParser::affectation() { AffectationContext *_localctx = _tracker.createInstance<AffectationContext>(_ctx, getState()); enterRule(_localctx, 10, fichierAntlrParser::RuleAffectation); auto onExit = finally([=] { exitRule(); }); try { setState(213); _errHandler->sync(this); switch (getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 13, _ctx)) { case 1: { _localctx = dynamic_cast<AffectationContext *>(_tracker.createInstance<fichierAntlrParser::Affectation_plusplusapresContext>(_localctx)); enterOuterAlt(_localctx, 1); setState(163); variable(); setState(164); match(fichierAntlrParser::T__8); break; } case 2: { _localctx = dynamic_cast<AffectationContext *>(_tracker.createInstance<fichierAntlrParser::Affectation_plusplusavantContext>(_localctx)); enterOuterAlt(_localctx, 2); setState(166); match(fichierAntlrParser::T__8); setState(167); variable(); break; } case 3: { _localctx = dynamic_cast<AffectationContext *>(_tracker.createInstance<fichierAntlrParser::Affectation_moinsmoinsapresContext>(_localctx)); enterOuterAlt(_localctx, 3); setState(168); variable(); setState(169); match(fichierAntlrParser::T__9); break; } case 4: { _localctx = dynamic_cast<AffectationContext *>(_tracker.createInstance<fichierAntlrParser::Affectation_moinsmoinsavantContext>(_localctx)); enterOuterAlt(_localctx, 4); setState(171); match(fichierAntlrParser::T__9); setState(172); variable(); break; } case 5: { _localctx = dynamic_cast<AffectationContext *>(_tracker.createInstance<fichierAntlrParser::Affectation_egalContext>(_localctx)); enterOuterAlt(_localctx, 5); setState(173); variable(); setState(174); match(fichierAntlrParser::T__10); setState(175); expr(0); break; } case 6: { _localctx = dynamic_cast<AffectationContext *>(_tracker.createInstance<fichierAntlrParser::Affectation_etegalContext>(_localctx)); enterOuterAlt(_localctx, 6); setState(177); variable(); setState(178); match(fichierAntlrParser::T__11); setState(179); expr(0); break; } case 7: { _localctx = dynamic_cast<AffectationContext *>(_tracker.createInstance<fichierAntlrParser::Affectation_ouegalContext>(_localctx)); enterOuterAlt(_localctx, 7); setState(181); variable(); setState(182); match(fichierAntlrParser::T__12); setState(183); expr(0); break; } case 8: { _localctx = dynamic_cast<AffectationContext *>(_tracker.createInstance<fichierAntlrParser::Affectation_plusegalContext>(_localctx)); enterOuterAlt(_localctx, 8); setState(185); variable(); setState(186); match(fichierAntlrParser::T__13); setState(187); expr(0); break; } case 9: { _localctx = dynamic_cast<AffectationContext *>(_tracker.createInstance<fichierAntlrParser::Affectation_moinsegalContext>(_localctx)); enterOuterAlt(_localctx, 9); setState(189); variable(); setState(190); match(fichierAntlrParser::T__14); setState(191); expr(0); break; } case 10: { _localctx = dynamic_cast<AffectationContext *>(_tracker.createInstance<fichierAntlrParser::Affectation_foisegalContext>(_localctx)); enterOuterAlt(_localctx, 10); setState(193); variable(); setState(194); match(fichierAntlrParser::T__15); setState(195); expr(0); break; } case 11: { _localctx = dynamic_cast<AffectationContext *>(_tracker.createInstance<fichierAntlrParser::Affectation_divegalContext>(_localctx)); enterOuterAlt(_localctx, 11); setState(197); variable(); setState(198); match(fichierAntlrParser::T__16); setState(199); expr(0); break; } case 12: { _localctx = dynamic_cast<AffectationContext *>(_tracker.createInstance<fichierAntlrParser::Affectation_pourcentegalContext>(_localctx)); enterOuterAlt(_localctx, 12); setState(201); variable(); setState(202); match(fichierAntlrParser::T__17); setState(203); expr(0); break; } case 13: { _localctx = dynamic_cast<AffectationContext *>(_tracker.createInstance<fichierAntlrParser::Affectation_infegalContext>(_localctx)); enterOuterAlt(_localctx, 13); setState(205); variable(); setState(206); match(fichierAntlrParser::T__18); setState(207); expr(0); break; } case 14: { _localctx = dynamic_cast<AffectationContext *>(_tracker.createInstance<fichierAntlrParser::Affectation_supegalContext>(_localctx)); enterOuterAlt(_localctx, 14); setState(209); variable(); setState(210); match(fichierAntlrParser::T__19); setState(211); expr(0); break; } } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- ExprContext ------------------------------------------------------------------ fichierAntlrParser::ExprContext::ExprContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } size_t fichierAntlrParser::ExprContext::getRuleIndex() const { return fichierAntlrParser::RuleExpr; } void fichierAntlrParser::ExprContext::copyFrom(ExprContext *ctx) { ParserRuleContext::copyFrom(ctx); } //----------------- Expr_infegalContext ------------------------------------------------------------------ std::vector<fichierAntlrParser::ExprContext *> fichierAntlrParser::Expr_infegalContext::expr() { return getRuleContexts<fichierAntlrParser::ExprContext>(); } fichierAntlrParser::ExprContext* fichierAntlrParser::Expr_infegalContext::expr(size_t i) { return getRuleContext<fichierAntlrParser::ExprContext>(i); } fichierAntlrParser::Expr_infegalContext::Expr_infegalContext(ExprContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Expr_infegalContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitExpr_infegal(this); else return visitor->visitChildren(this); } //----------------- Expr_nombreContext ------------------------------------------------------------------ tree::TerminalNode* fichierAntlrParser::Expr_nombreContext::NOMBRE() { return getToken(fichierAntlrParser::NOMBRE, 0); } fichierAntlrParser::Expr_nombreContext::Expr_nombreContext(ExprContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Expr_nombreContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitExpr_nombre(this); else return visitor->visitChildren(this); } //----------------- Expr_diffegalContext ------------------------------------------------------------------ std::vector<fichierAntlrParser::ExprContext *> fichierAntlrParser::Expr_diffegalContext::expr() { return getRuleContexts<fichierAntlrParser::ExprContext>(); } fichierAntlrParser::ExprContext* fichierAntlrParser::Expr_diffegalContext::expr(size_t i) { return getRuleContext<fichierAntlrParser::ExprContext>(i); } fichierAntlrParser::Expr_diffegalContext::Expr_diffegalContext(ExprContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Expr_diffegalContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitExpr_diffegal(this); else return visitor->visitChildren(this); } //----------------- Expr_vagueContext ------------------------------------------------------------------ fichierAntlrParser::ExprContext* fichierAntlrParser::Expr_vagueContext::expr() { return getRuleContext<fichierAntlrParser::ExprContext>(0); } fichierAntlrParser::Expr_vagueContext::Expr_vagueContext(ExprContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Expr_vagueContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitExpr_vague(this); else return visitor->visitChildren(this); } //----------------- Expr_etContext ------------------------------------------------------------------ std::vector<fichierAntlrParser::ExprContext *> fichierAntlrParser::Expr_etContext::expr() { return getRuleContexts<fichierAntlrParser::ExprContext>(); } fichierAntlrParser::ExprContext* fichierAntlrParser::Expr_etContext::expr(size_t i) { return getRuleContext<fichierAntlrParser::ExprContext>(i); } fichierAntlrParser::Expr_etContext::Expr_etContext(ExprContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Expr_etContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitExpr_et(this); else return visitor->visitChildren(this); } //----------------- Expr_infContext ------------------------------------------------------------------ std::vector<fichierAntlrParser::ExprContext *> fichierAntlrParser::Expr_infContext::expr() { return getRuleContexts<fichierAntlrParser::ExprContext>(); } fichierAntlrParser::ExprContext* fichierAntlrParser::Expr_infContext::expr(size_t i) { return getRuleContext<fichierAntlrParser::ExprContext>(i); } fichierAntlrParser::Expr_infContext::Expr_infContext(ExprContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Expr_infContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitExpr_inf(this); else return visitor->visitChildren(this); } //----------------- Expr_parentheseContext ------------------------------------------------------------------ fichierAntlrParser::ExprContext* fichierAntlrParser::Expr_parentheseContext::expr() { return getRuleContext<fichierAntlrParser::ExprContext>(0); } fichierAntlrParser::Expr_parentheseContext::Expr_parentheseContext(ExprContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Expr_parentheseContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitExpr_parenthese(this); else return visitor->visitChildren(this); } //----------------- Expr_additionContext ------------------------------------------------------------------ std::vector<fichierAntlrParser::ExprContext *> fichierAntlrParser::Expr_additionContext::expr() { return getRuleContexts<fichierAntlrParser::ExprContext>(); } fichierAntlrParser::ExprContext* fichierAntlrParser::Expr_additionContext::expr(size_t i) { return getRuleContext<fichierAntlrParser::ExprContext>(i); } fichierAntlrParser::Expr_additionContext::Expr_additionContext(ExprContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Expr_additionContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitExpr_addition(this); else return visitor->visitChildren(this); } //----------------- Expr_ouContext ------------------------------------------------------------------ std::vector<fichierAntlrParser::ExprContext *> fichierAntlrParser::Expr_ouContext::expr() { return getRuleContexts<fichierAntlrParser::ExprContext>(); } fichierAntlrParser::ExprContext* fichierAntlrParser::Expr_ouContext::expr(size_t i) { return getRuleContext<fichierAntlrParser::ExprContext>(i); } fichierAntlrParser::Expr_ouContext::Expr_ouContext(ExprContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Expr_ouContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitExpr_ou(this); else return visitor->visitChildren(this); } //----------------- Expr_supContext ------------------------------------------------------------------ std::vector<fichierAntlrParser::ExprContext *> fichierAntlrParser::Expr_supContext::expr() { return getRuleContexts<fichierAntlrParser::ExprContext>(); } fichierAntlrParser::ExprContext* fichierAntlrParser::Expr_supContext::expr(size_t i) { return getRuleContext<fichierAntlrParser::ExprContext>(i); } fichierAntlrParser::Expr_supContext::Expr_supContext(ExprContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Expr_supContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitExpr_sup(this); else return visitor->visitChildren(this); } //----------------- Expr_etetContext ------------------------------------------------------------------ std::vector<fichierAntlrParser::ExprContext *> fichierAntlrParser::Expr_etetContext::expr() { return getRuleContexts<fichierAntlrParser::ExprContext>(); } fichierAntlrParser::ExprContext* fichierAntlrParser::Expr_etetContext::expr(size_t i) { return getRuleContext<fichierAntlrParser::ExprContext>(i); } fichierAntlrParser::Expr_etetContext::Expr_etetContext(ExprContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Expr_etetContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitExpr_etet(this); else return visitor->visitChildren(this); } //----------------- Expr_infinfContext ------------------------------------------------------------------ std::vector<fichierAntlrParser::ExprContext *> fichierAntlrParser::Expr_infinfContext::expr() { return getRuleContexts<fichierAntlrParser::ExprContext>(); } fichierAntlrParser::ExprContext* fichierAntlrParser::Expr_infinfContext::expr(size_t i) { return getRuleContext<fichierAntlrParser::ExprContext>(i); } fichierAntlrParser::Expr_infinfContext::Expr_infinfContext(ExprContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Expr_infinfContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitExpr_infinf(this); else return visitor->visitChildren(this); } //----------------- Expr_fonctionContext ------------------------------------------------------------------ tree::TerminalNode* fichierAntlrParser::Expr_fonctionContext::NOM() { return getToken(fichierAntlrParser::NOM, 0); } std::vector<fichierAntlrParser::ExprContext *> fichierAntlrParser::Expr_fonctionContext::expr() { return getRuleContexts<fichierAntlrParser::ExprContext>(); } fichierAntlrParser::ExprContext* fichierAntlrParser::Expr_fonctionContext::expr(size_t i) { return getRuleContext<fichierAntlrParser::ExprContext>(i); } fichierAntlrParser::Expr_fonctionContext::Expr_fonctionContext(ExprContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Expr_fonctionContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitExpr_fonction(this); else return visitor->visitChildren(this); } //----------------- Expr_charContext ------------------------------------------------------------------ tree::TerminalNode* fichierAntlrParser::Expr_charContext::CHAR() { return getToken(fichierAntlrParser::CHAR, 0); } fichierAntlrParser::Expr_charContext::Expr_charContext(ExprContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Expr_charContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitExpr_char(this); else return visitor->visitChildren(this); } //----------------- Expr_egalegalContext ------------------------------------------------------------------ std::vector<fichierAntlrParser::ExprContext *> fichierAntlrParser::Expr_egalegalContext::expr() { return getRuleContexts<fichierAntlrParser::ExprContext>(); } fichierAntlrParser::ExprContext* fichierAntlrParser::Expr_egalegalContext::expr(size_t i) { return getRuleContext<fichierAntlrParser::ExprContext>(i); } fichierAntlrParser::Expr_egalegalContext::Expr_egalegalContext(ExprContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Expr_egalegalContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitExpr_egalegal(this); else return visitor->visitChildren(this); } //----------------- Expr_chiffreContext ------------------------------------------------------------------ tree::TerminalNode* fichierAntlrParser::Expr_chiffreContext::CHIFFRE() { return getToken(fichierAntlrParser::CHIFFRE, 0); } fichierAntlrParser::Expr_chiffreContext::Expr_chiffreContext(ExprContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Expr_chiffreContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitExpr_chiffre(this); else return visitor->visitChildren(this); } //----------------- Expr_variableContext ------------------------------------------------------------------ fichierAntlrParser::VariableContext* fichierAntlrParser::Expr_variableContext::variable() { return getRuleContext<fichierAntlrParser::VariableContext>(0); } fichierAntlrParser::Expr_variableContext::Expr_variableContext(ExprContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Expr_variableContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitExpr_variable(this); else return visitor->visitChildren(this); } //----------------- Expr_ououContext ------------------------------------------------------------------ std::vector<fichierAntlrParser::ExprContext *> fichierAntlrParser::Expr_ououContext::expr() { return getRuleContexts<fichierAntlrParser::ExprContext>(); } fichierAntlrParser::ExprContext* fichierAntlrParser::Expr_ououContext::expr(size_t i) { return getRuleContext<fichierAntlrParser::ExprContext>(i); } fichierAntlrParser::Expr_ououContext::Expr_ououContext(ExprContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Expr_ououContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitExpr_ouou(this); else return visitor->visitChildren(this); } //----------------- Expr_divisionContext ------------------------------------------------------------------ std::vector<fichierAntlrParser::ExprContext *> fichierAntlrParser::Expr_divisionContext::expr() { return getRuleContexts<fichierAntlrParser::ExprContext>(); } fichierAntlrParser::ExprContext* fichierAntlrParser::Expr_divisionContext::expr(size_t i) { return getRuleContext<fichierAntlrParser::ExprContext>(i); } fichierAntlrParser::Expr_divisionContext::Expr_divisionContext(ExprContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Expr_divisionContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitExpr_division(this); else return visitor->visitChildren(this); } //----------------- Expr_modContext ------------------------------------------------------------------ std::vector<fichierAntlrParser::ExprContext *> fichierAntlrParser::Expr_modContext::expr() { return getRuleContexts<fichierAntlrParser::ExprContext>(); } fichierAntlrParser::ExprContext* fichierAntlrParser::Expr_modContext::expr(size_t i) { return getRuleContext<fichierAntlrParser::ExprContext>(i); } fichierAntlrParser::Expr_modContext::Expr_modContext(ExprContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Expr_modContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitExpr_mod(this); else return visitor->visitChildren(this); } //----------------- Expr_supegalContext ------------------------------------------------------------------ std::vector<fichierAntlrParser::ExprContext *> fichierAntlrParser::Expr_supegalContext::expr() { return getRuleContexts<fichierAntlrParser::ExprContext>(); } fichierAntlrParser::ExprContext* fichierAntlrParser::Expr_supegalContext::expr(size_t i) { return getRuleContext<fichierAntlrParser::ExprContext>(i); } fichierAntlrParser::Expr_supegalContext::Expr_supegalContext(ExprContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Expr_supegalContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitExpr_supegal(this); else return visitor->visitChildren(this); } //----------------- Expr_soustractionContext ------------------------------------------------------------------ std::vector<fichierAntlrParser::ExprContext *> fichierAntlrParser::Expr_soustractionContext::expr() { return getRuleContexts<fichierAntlrParser::ExprContext>(); } fichierAntlrParser::ExprContext* fichierAntlrParser::Expr_soustractionContext::expr(size_t i) { return getRuleContext<fichierAntlrParser::ExprContext>(i); } fichierAntlrParser::Expr_soustractionContext::Expr_soustractionContext(ExprContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Expr_soustractionContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitExpr_soustraction(this); else return visitor->visitChildren(this); } //----------------- Expr_affectationContext ------------------------------------------------------------------ fichierAntlrParser::AffectationContext* fichierAntlrParser::Expr_affectationContext::affectation() { return getRuleContext<fichierAntlrParser::AffectationContext>(0); } fichierAntlrParser::Expr_affectationContext::Expr_affectationContext(ExprContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Expr_affectationContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitExpr_affectation(this); else return visitor->visitChildren(this); } //----------------- Expr_exclamationContext ------------------------------------------------------------------ fichierAntlrParser::ExprContext* fichierAntlrParser::Expr_exclamationContext::expr() { return getRuleContext<fichierAntlrParser::ExprContext>(0); } fichierAntlrParser::Expr_exclamationContext::Expr_exclamationContext(ExprContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Expr_exclamationContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitExpr_exclamation(this); else return visitor->visitChildren(this); } //----------------- Expr_multiplicationContext ------------------------------------------------------------------ std::vector<fichierAntlrParser::ExprContext *> fichierAntlrParser::Expr_multiplicationContext::expr() { return getRuleContexts<fichierAntlrParser::ExprContext>(); } fichierAntlrParser::ExprContext* fichierAntlrParser::Expr_multiplicationContext::expr(size_t i) { return getRuleContext<fichierAntlrParser::ExprContext>(i); } fichierAntlrParser::Expr_multiplicationContext::Expr_multiplicationContext(ExprContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Expr_multiplicationContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitExpr_multiplication(this); else return visitor->visitChildren(this); } //----------------- Expr_supsupContext ------------------------------------------------------------------ std::vector<fichierAntlrParser::ExprContext *> fichierAntlrParser::Expr_supsupContext::expr() { return getRuleContexts<fichierAntlrParser::ExprContext>(); } fichierAntlrParser::ExprContext* fichierAntlrParser::Expr_supsupContext::expr(size_t i) { return getRuleContext<fichierAntlrParser::ExprContext>(i); } fichierAntlrParser::Expr_supsupContext::Expr_supsupContext(ExprContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Expr_supsupContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitExpr_supsup(this); else return visitor->visitChildren(this); } //----------------- Expr_chapeauContext ------------------------------------------------------------------ std::vector<fichierAntlrParser::ExprContext *> fichierAntlrParser::Expr_chapeauContext::expr() { return getRuleContexts<fichierAntlrParser::ExprContext>(); } fichierAntlrParser::ExprContext* fichierAntlrParser::Expr_chapeauContext::expr(size_t i) { return getRuleContext<fichierAntlrParser::ExprContext>(i); } fichierAntlrParser::Expr_chapeauContext::Expr_chapeauContext(ExprContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Expr_chapeauContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitExpr_chapeau(this); else return visitor->visitChildren(this); } fichierAntlrParser::ExprContext* fichierAntlrParser::expr() { return expr(0); } fichierAntlrParser::ExprContext* fichierAntlrParser::expr(int precedence) { ParserRuleContext *parentContext = _ctx; size_t parentState = getState(); fichierAntlrParser::ExprContext *_localctx = _tracker.createInstance<ExprContext>(_ctx, parentState); fichierAntlrParser::ExprContext *previousContext = _localctx; size_t startState = 12; enterRecursionRule(_localctx, 12, fichierAntlrParser::RuleExpr, precedence); size_t _la = 0; auto onExit = finally([=] { unrollRecursionContexts(parentContext); }); try { size_t alt; enterOuterAlt(_localctx, 1); setState(242); _errHandler->sync(this); switch (getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 16, _ctx)) { case 1: { _localctx = _tracker.createInstance<Expr_chiffreContext>(_localctx); _ctx = _localctx; previousContext = _localctx; setState(216); match(fichierAntlrParser::CHIFFRE); break; } case 2: { _localctx = _tracker.createInstance<Expr_nombreContext>(_localctx); _ctx = _localctx; previousContext = _localctx; setState(217); match(fichierAntlrParser::NOMBRE); break; } case 3: { _localctx = _tracker.createInstance<Expr_charContext>(_localctx); _ctx = _localctx; previousContext = _localctx; setState(218); match(fichierAntlrParser::CHAR); break; } case 4: { _localctx = _tracker.createInstance<Expr_parentheseContext>(_localctx); _ctx = _localctx; previousContext = _localctx; setState(219); match(fichierAntlrParser::T__1); setState(220); expr(0); setState(221); match(fichierAntlrParser::T__2); break; } case 5: { _localctx = _tracker.createInstance<Expr_vagueContext>(_localctx); _ctx = _localctx; previousContext = _localctx; setState(223); match(fichierAntlrParser::T__20); setState(224); expr(23); break; } case 6: { _localctx = _tracker.createInstance<Expr_exclamationContext>(_localctx); _ctx = _localctx; previousContext = _localctx; setState(225); match(fichierAntlrParser::T__21); setState(226); expr(22); break; } case 7: { _localctx = _tracker.createInstance<Expr_variableContext>(_localctx); _ctx = _localctx; previousContext = _localctx; setState(227); variable(); break; } case 8: { _localctx = _tracker.createInstance<Expr_affectationContext>(_localctx); _ctx = _localctx; previousContext = _localctx; setState(228); affectation(); break; } case 9: { _localctx = _tracker.createInstance<Expr_fonctionContext>(_localctx); _ctx = _localctx; previousContext = _localctx; setState(229); match(fichierAntlrParser::NOM); setState(230); match(fichierAntlrParser::T__1); setState(239); _errHandler->sync(this); _la = _input->LA(1); if ((((_la & ~ 0x3fULL) == 0) && ((1ULL << _la) & ((1ULL << fichierAntlrParser::T__1) | (1ULL << fichierAntlrParser::T__8) | (1ULL << fichierAntlrParser::T__9) | (1ULL << fichierAntlrParser::T__20) | (1ULL << fichierAntlrParser::T__21) | (1ULL << fichierAntlrParser::NOM) | (1ULL << fichierAntlrParser::CHIFFRE) | (1ULL << fichierAntlrParser::NOMBRE) | (1ULL << fichierAntlrParser::CHAR))) != 0)) { setState(231); expr(0); setState(236); _errHandler->sync(this); _la = _input->LA(1); while (_la == fichierAntlrParser::T__38) { setState(232); match(fichierAntlrParser::T__38); setState(233); expr(0); setState(238); _errHandler->sync(this); _la = _input->LA(1); } } setState(241); match(fichierAntlrParser::T__2); break; } } _ctx->stop = _input->LT(-1); setState(300); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 18, _ctx); while (alt != 2 && alt != atn::ATN::INVALID_ALT_NUMBER) { if (alt == 1) { if (!_parseListeners.empty()) triggerExitRuleEvent(); previousContext = _localctx; setState(298); _errHandler->sync(this); switch (getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 17, _ctx)) { case 1: { auto newContext = _tracker.createInstance<Expr_multiplicationContext>(_tracker.createInstance<ExprContext>(parentContext, parentState)); _localctx = newContext; pushNewRecursionContext(newContext, startState, RuleExpr); setState(244); if (!(precpred(_ctx, 21))) throw FailedPredicateException(this, "precpred(_ctx, 21)"); setState(245); match(fichierAntlrParser::T__22); setState(246); expr(22); break; } case 2: { auto newContext = _tracker.createInstance<Expr_divisionContext>(_tracker.createInstance<ExprContext>(parentContext, parentState)); _localctx = newContext; pushNewRecursionContext(newContext, startState, RuleExpr); setState(247); if (!(precpred(_ctx, 20))) throw FailedPredicateException(this, "precpred(_ctx, 20)"); setState(248); match(fichierAntlrParser::T__23); setState(249); expr(21); break; } case 3: { auto newContext = _tracker.createInstance<Expr_modContext>(_tracker.createInstance<ExprContext>(parentContext, parentState)); _localctx = newContext; pushNewRecursionContext(newContext, startState, RuleExpr); setState(250); if (!(precpred(_ctx, 19))) throw FailedPredicateException(this, "precpred(_ctx, 19)"); setState(251); match(fichierAntlrParser::T__24); setState(252); expr(20); break; } case 4: { auto newContext = _tracker.createInstance<Expr_additionContext>(_tracker.createInstance<ExprContext>(parentContext, parentState)); _localctx = newContext; pushNewRecursionContext(newContext, startState, RuleExpr); setState(253); if (!(precpred(_ctx, 18))) throw FailedPredicateException(this, "precpred(_ctx, 18)"); setState(254); match(fichierAntlrParser::T__25); setState(255); expr(19); break; } case 5: { auto newContext = _tracker.createInstance<Expr_soustractionContext>(_tracker.createInstance<ExprContext>(parentContext, parentState)); _localctx = newContext; pushNewRecursionContext(newContext, startState, RuleExpr); setState(256); if (!(precpred(_ctx, 17))) throw FailedPredicateException(this, "precpred(_ctx, 17)"); setState(257); match(fichierAntlrParser::T__26); setState(258); expr(18); break; } case 6: { auto newContext = _tracker.createInstance<Expr_infinfContext>(_tracker.createInstance<ExprContext>(parentContext, parentState)); _localctx = newContext; pushNewRecursionContext(newContext, startState, RuleExpr); setState(259); if (!(precpred(_ctx, 16))) throw FailedPredicateException(this, "precpred(_ctx, 16)"); setState(260); match(fichierAntlrParser::T__27); setState(261); expr(17); break; } case 7: { auto newContext = _tracker.createInstance<Expr_supsupContext>(_tracker.createInstance<ExprContext>(parentContext, parentState)); _localctx = newContext; pushNewRecursionContext(newContext, startState, RuleExpr); setState(262); if (!(precpred(_ctx, 15))) throw FailedPredicateException(this, "precpred(_ctx, 15)"); setState(263); match(fichierAntlrParser::T__28); setState(264); expr(16); break; } case 8: { auto newContext = _tracker.createInstance<Expr_etContext>(_tracker.createInstance<ExprContext>(parentContext, parentState)); _localctx = newContext; pushNewRecursionContext(newContext, startState, RuleExpr); setState(265); if (!(precpred(_ctx, 14))) throw FailedPredicateException(this, "precpred(_ctx, 14)"); setState(266); match(fichierAntlrParser::T__29); setState(267); expr(15); break; } case 9: { auto newContext = _tracker.createInstance<Expr_ouContext>(_tracker.createInstance<ExprContext>(parentContext, parentState)); _localctx = newContext; pushNewRecursionContext(newContext, startState, RuleExpr); setState(268); if (!(precpred(_ctx, 13))) throw FailedPredicateException(this, "precpred(_ctx, 13)"); setState(269); match(fichierAntlrParser::T__30); setState(270); expr(14); break; } case 10: { auto newContext = _tracker.createInstance<Expr_chapeauContext>(_tracker.createInstance<ExprContext>(parentContext, parentState)); _localctx = newContext; pushNewRecursionContext(newContext, startState, RuleExpr); setState(271); if (!(precpred(_ctx, 12))) throw FailedPredicateException(this, "precpred(_ctx, 12)"); setState(272); match(fichierAntlrParser::T__31); setState(273); expr(13); break; } case 11: { auto newContext = _tracker.createInstance<Expr_etetContext>(_tracker.createInstance<ExprContext>(parentContext, parentState)); _localctx = newContext; pushNewRecursionContext(newContext, startState, RuleExpr); setState(274); if (!(precpred(_ctx, 11))) throw FailedPredicateException(this, "precpred(_ctx, 11)"); setState(275); match(fichierAntlrParser::T__32); setState(276); expr(12); break; } case 12: { auto newContext = _tracker.createInstance<Expr_ououContext>(_tracker.createInstance<ExprContext>(parentContext, parentState)); _localctx = newContext; pushNewRecursionContext(newContext, startState, RuleExpr); setState(277); if (!(precpred(_ctx, 10))) throw FailedPredicateException(this, "precpred(_ctx, 10)"); setState(278); match(fichierAntlrParser::T__33); setState(279); expr(11); break; } case 13: { auto newContext = _tracker.createInstance<Expr_infContext>(_tracker.createInstance<ExprContext>(parentContext, parentState)); _localctx = newContext; pushNewRecursionContext(newContext, startState, RuleExpr); setState(280); if (!(precpred(_ctx, 9))) throw FailedPredicateException(this, "precpred(_ctx, 9)"); setState(281); match(fichierAntlrParser::T__34); setState(282); expr(10); break; } case 14: { auto newContext = _tracker.createInstance<Expr_infegalContext>(_tracker.createInstance<ExprContext>(parentContext, parentState)); _localctx = newContext; pushNewRecursionContext(newContext, startState, RuleExpr); setState(283); if (!(precpred(_ctx, 8))) throw FailedPredicateException(this, "precpred(_ctx, 8)"); setState(284); match(fichierAntlrParser::T__18); setState(285); expr(9); break; } case 15: { auto newContext = _tracker.createInstance<Expr_supContext>(_tracker.createInstance<ExprContext>(parentContext, parentState)); _localctx = newContext; pushNewRecursionContext(newContext, startState, RuleExpr); setState(286); if (!(precpred(_ctx, 7))) throw FailedPredicateException(this, "precpred(_ctx, 7)"); setState(287); match(fichierAntlrParser::T__35); setState(288); expr(8); break; } case 16: { auto newContext = _tracker.createInstance<Expr_supegalContext>(_tracker.createInstance<ExprContext>(parentContext, parentState)); _localctx = newContext; pushNewRecursionContext(newContext, startState, RuleExpr); setState(289); if (!(precpred(_ctx, 6))) throw FailedPredicateException(this, "precpred(_ctx, 6)"); setState(290); match(fichierAntlrParser::T__19); setState(291); expr(7); break; } case 17: { auto newContext = _tracker.createInstance<Expr_egalegalContext>(_tracker.createInstance<ExprContext>(parentContext, parentState)); _localctx = newContext; pushNewRecursionContext(newContext, startState, RuleExpr); setState(292); if (!(precpred(_ctx, 5))) throw FailedPredicateException(this, "precpred(_ctx, 5)"); setState(293); match(fichierAntlrParser::T__36); setState(294); expr(6); break; } case 18: { auto newContext = _tracker.createInstance<Expr_diffegalContext>(_tracker.createInstance<ExprContext>(parentContext, parentState)); _localctx = newContext; pushNewRecursionContext(newContext, startState, RuleExpr); setState(295); if (!(precpred(_ctx, 4))) throw FailedPredicateException(this, "precpred(_ctx, 4)"); setState(296); match(fichierAntlrParser::T__37); setState(297); expr(5); break; } } } setState(302); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 18, _ctx); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Return_Context ------------------------------------------------------------------ fichierAntlrParser::Return_Context::Return_Context(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } size_t fichierAntlrParser::Return_Context::getRuleIndex() const { return fichierAntlrParser::RuleReturn_; } void fichierAntlrParser::Return_Context::copyFrom(Return_Context *ctx) { ParserRuleContext::copyFrom(ctx); } //----------------- Return_normalContext ------------------------------------------------------------------ fichierAntlrParser::ExprContext* fichierAntlrParser::Return_normalContext::expr() { return getRuleContext<fichierAntlrParser::ExprContext>(0); } fichierAntlrParser::Return_normalContext::Return_normalContext(Return_Context *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Return_normalContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitReturn_normal(this); else return visitor->visitChildren(this); } fichierAntlrParser::Return_Context* fichierAntlrParser::return_() { Return_Context *_localctx = _tracker.createInstance<Return_Context>(_ctx, getState()); enterRule(_localctx, 14, fichierAntlrParser::RuleReturn_); size_t _la = 0; auto onExit = finally([=] { exitRule(); }); try { _localctx = dynamic_cast<Return_Context *>(_tracker.createInstance<fichierAntlrParser::Return_normalContext>(_localctx)); enterOuterAlt(_localctx, 1); setState(303); match(fichierAntlrParser::T__39); setState(305); _errHandler->sync(this); _la = _input->LA(1); if ((((_la & ~ 0x3fULL) == 0) && ((1ULL << _la) & ((1ULL << fichierAntlrParser::T__1) | (1ULL << fichierAntlrParser::T__8) | (1ULL << fichierAntlrParser::T__9) | (1ULL << fichierAntlrParser::T__20) | (1ULL << fichierAntlrParser::T__21) | (1ULL << fichierAntlrParser::NOM) | (1ULL << fichierAntlrParser::CHIFFRE) | (1ULL << fichierAntlrParser::NOMBRE) | (1ULL << fichierAntlrParser::CHAR))) != 0)) { setState(304); expr(0); } setState(307); match(fichierAntlrParser::T__40); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Break_Context ------------------------------------------------------------------ fichierAntlrParser::Break_Context::Break_Context(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } size_t fichierAntlrParser::Break_Context::getRuleIndex() const { return fichierAntlrParser::RuleBreak_; } void fichierAntlrParser::Break_Context::copyFrom(Break_Context *ctx) { ParserRuleContext::copyFrom(ctx); } //----------------- Break_normalContext ------------------------------------------------------------------ fichierAntlrParser::Break_normalContext::Break_normalContext(Break_Context *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Break_normalContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitBreak_normal(this); else return visitor->visitChildren(this); } fichierAntlrParser::Break_Context* fichierAntlrParser::break_() { Break_Context *_localctx = _tracker.createInstance<Break_Context>(_ctx, getState()); enterRule(_localctx, 16, fichierAntlrParser::RuleBreak_); auto onExit = finally([=] { exitRule(); }); try { _localctx = dynamic_cast<Break_Context *>(_tracker.createInstance<fichierAntlrParser::Break_normalContext>(_localctx)); enterOuterAlt(_localctx, 1); setState(309); match(fichierAntlrParser::T__41); setState(310); match(fichierAntlrParser::T__40); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- InstructionContext ------------------------------------------------------------------ fichierAntlrParser::InstructionContext::InstructionContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } size_t fichierAntlrParser::InstructionContext::getRuleIndex() const { return fichierAntlrParser::RuleInstruction; } void fichierAntlrParser::InstructionContext::copyFrom(InstructionContext *ctx) { ParserRuleContext::copyFrom(ctx); } //----------------- Instruction_exprContext ------------------------------------------------------------------ fichierAntlrParser::ExprContext* fichierAntlrParser::Instruction_exprContext::expr() { return getRuleContext<fichierAntlrParser::ExprContext>(0); } fichierAntlrParser::Instruction_exprContext::Instruction_exprContext(InstructionContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Instruction_exprContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitInstruction_expr(this); else return visitor->visitChildren(this); } //----------------- Instruction_whileContext ------------------------------------------------------------------ fichierAntlrParser::Structure_whileContext* fichierAntlrParser::Instruction_whileContext::structure_while() { return getRuleContext<fichierAntlrParser::Structure_whileContext>(0); } fichierAntlrParser::Instruction_whileContext::Instruction_whileContext(InstructionContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Instruction_whileContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitInstruction_while(this); else return visitor->visitChildren(this); } //----------------- Instruction_returnContext ------------------------------------------------------------------ fichierAntlrParser::Return_Context* fichierAntlrParser::Instruction_returnContext::return_() { return getRuleContext<fichierAntlrParser::Return_Context>(0); } fichierAntlrParser::Instruction_returnContext::Instruction_returnContext(InstructionContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Instruction_returnContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitInstruction_return(this); else return visitor->visitChildren(this); } //----------------- Instruction_breakContext ------------------------------------------------------------------ fichierAntlrParser::Break_Context* fichierAntlrParser::Instruction_breakContext::break_() { return getRuleContext<fichierAntlrParser::Break_Context>(0); } fichierAntlrParser::Instruction_breakContext::Instruction_breakContext(InstructionContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Instruction_breakContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitInstruction_break(this); else return visitor->visitChildren(this); } //----------------- Instruction_ifContext ------------------------------------------------------------------ fichierAntlrParser::Structure_ifContext* fichierAntlrParser::Instruction_ifContext::structure_if() { return getRuleContext<fichierAntlrParser::Structure_ifContext>(0); } fichierAntlrParser::Instruction_ifContext::Instruction_ifContext(InstructionContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Instruction_ifContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitInstruction_if(this); else return visitor->visitChildren(this); } fichierAntlrParser::InstructionContext* fichierAntlrParser::instruction() { InstructionContext *_localctx = _tracker.createInstance<InstructionContext>(_ctx, getState()); enterRule(_localctx, 18, fichierAntlrParser::RuleInstruction); auto onExit = finally([=] { exitRule(); }); try { setState(319); _errHandler->sync(this); switch (_input->LA(1)) { case fichierAntlrParser::T__42: { _localctx = dynamic_cast<InstructionContext *>(_tracker.createInstance<fichierAntlrParser::Instruction_ifContext>(_localctx)); enterOuterAlt(_localctx, 1); setState(312); structure_if(); break; } case fichierAntlrParser::T__44: { _localctx = dynamic_cast<InstructionContext *>(_tracker.createInstance<fichierAntlrParser::Instruction_whileContext>(_localctx)); enterOuterAlt(_localctx, 2); setState(313); structure_while(); break; } case fichierAntlrParser::T__1: case fichierAntlrParser::T__8: case fichierAntlrParser::T__9: case fichierAntlrParser::T__20: case fichierAntlrParser::T__21: case fichierAntlrParser::NOM: case fichierAntlrParser::CHIFFRE: case fichierAntlrParser::NOMBRE: case fichierAntlrParser::CHAR: { _localctx = dynamic_cast<InstructionContext *>(_tracker.createInstance<fichierAntlrParser::Instruction_exprContext>(_localctx)); enterOuterAlt(_localctx, 3); setState(314); expr(0); setState(315); match(fichierAntlrParser::T__40); break; } case fichierAntlrParser::T__39: { _localctx = dynamic_cast<InstructionContext *>(_tracker.createInstance<fichierAntlrParser::Instruction_returnContext>(_localctx)); enterOuterAlt(_localctx, 4); setState(317); return_(); break; } case fichierAntlrParser::T__41: { _localctx = dynamic_cast<InstructionContext *>(_tracker.createInstance<fichierAntlrParser::Instruction_breakContext>(_localctx)); enterOuterAlt(_localctx, 5); setState(318); break_(); break; } default: throw NoViableAltException(this); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- BlocContext ------------------------------------------------------------------ fichierAntlrParser::BlocContext::BlocContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } size_t fichierAntlrParser::BlocContext::getRuleIndex() const { return fichierAntlrParser::RuleBloc; } void fichierAntlrParser::BlocContext::copyFrom(BlocContext *ctx) { ParserRuleContext::copyFrom(ctx); } //----------------- Bloc_normalContext ------------------------------------------------------------------ std::vector<fichierAntlrParser::InstructionContext *> fichierAntlrParser::Bloc_normalContext::instruction() { return getRuleContexts<fichierAntlrParser::InstructionContext>(); } fichierAntlrParser::InstructionContext* fichierAntlrParser::Bloc_normalContext::instruction(size_t i) { return getRuleContext<fichierAntlrParser::InstructionContext>(i); } fichierAntlrParser::Bloc_normalContext::Bloc_normalContext(BlocContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Bloc_normalContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitBloc_normal(this); else return visitor->visitChildren(this); } fichierAntlrParser::BlocContext* fichierAntlrParser::bloc() { BlocContext *_localctx = _tracker.createInstance<BlocContext>(_ctx, getState()); enterRule(_localctx, 20, fichierAntlrParser::RuleBloc); size_t _la = 0; auto onExit = finally([=] { exitRule(); }); try { _localctx = dynamic_cast<BlocContext *>(_tracker.createInstance<fichierAntlrParser::Bloc_normalContext>(_localctx)); enterOuterAlt(_localctx, 1); setState(324); _errHandler->sync(this); _la = _input->LA(1); while ((((_la & ~ 0x3fULL) == 0) && ((1ULL << _la) & ((1ULL << fichierAntlrParser::T__1) | (1ULL << fichierAntlrParser::T__8) | (1ULL << fichierAntlrParser::T__9) | (1ULL << fichierAntlrParser::T__20) | (1ULL << fichierAntlrParser::T__21) | (1ULL << fichierAntlrParser::T__39) | (1ULL << fichierAntlrParser::T__41) | (1ULL << fichierAntlrParser::T__42) | (1ULL << fichierAntlrParser::T__44) | (1ULL << fichierAntlrParser::NOM) | (1ULL << fichierAntlrParser::CHIFFRE) | (1ULL << fichierAntlrParser::NOMBRE) | (1ULL << fichierAntlrParser::CHAR))) != 0)) { setState(321); instruction(); setState(326); _errHandler->sync(this); _la = _input->LA(1); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- DeclarationContext ------------------------------------------------------------------ fichierAntlrParser::DeclarationContext::DeclarationContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } size_t fichierAntlrParser::DeclarationContext::getRuleIndex() const { return fichierAntlrParser::RuleDeclaration; } void fichierAntlrParser::DeclarationContext::copyFrom(DeclarationContext *ctx) { ParserRuleContext::copyFrom(ctx); } //----------------- Declaration_tableauContext ------------------------------------------------------------------ fichierAntlrParser::Type_varContext* fichierAntlrParser::Declaration_tableauContext::type_var() { return getRuleContext<fichierAntlrParser::Type_varContext>(0); } tree::TerminalNode* fichierAntlrParser::Declaration_tableauContext::NOM() { return getToken(fichierAntlrParser::NOM, 0); } fichierAntlrParser::ExprContext* fichierAntlrParser::Declaration_tableauContext::expr() { return getRuleContext<fichierAntlrParser::ExprContext>(0); } fichierAntlrParser::Declaration_tableauContext::Declaration_tableauContext(DeclarationContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Declaration_tableauContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitDeclaration_tableau(this); else return visitor->visitChildren(this); } //----------------- Declaration_definitionContext ------------------------------------------------------------------ fichierAntlrParser::Type_varContext* fichierAntlrParser::Declaration_definitionContext::type_var() { return getRuleContext<fichierAntlrParser::Type_varContext>(0); } tree::TerminalNode* fichierAntlrParser::Declaration_definitionContext::NOM() { return getToken(fichierAntlrParser::NOM, 0); } fichierAntlrParser::ExprContext* fichierAntlrParser::Declaration_definitionContext::expr() { return getRuleContext<fichierAntlrParser::ExprContext>(0); } fichierAntlrParser::Declaration_definitionContext::Declaration_definitionContext(DeclarationContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Declaration_definitionContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitDeclaration_definition(this); else return visitor->visitChildren(this); } //----------------- Declaration_normaleContext ------------------------------------------------------------------ fichierAntlrParser::Type_varContext* fichierAntlrParser::Declaration_normaleContext::type_var() { return getRuleContext<fichierAntlrParser::Type_varContext>(0); } std::vector<tree::TerminalNode *> fichierAntlrParser::Declaration_normaleContext::NOM() { return getTokens(fichierAntlrParser::NOM); } tree::TerminalNode* fichierAntlrParser::Declaration_normaleContext::NOM(size_t i) { return getToken(fichierAntlrParser::NOM, i); } fichierAntlrParser::Declaration_normaleContext::Declaration_normaleContext(DeclarationContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Declaration_normaleContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitDeclaration_normale(this); else return visitor->visitChildren(this); } //----------------- Declaration_definitiontableau_charContext ------------------------------------------------------------------ fichierAntlrParser::Type_varContext* fichierAntlrParser::Declaration_definitiontableau_charContext::type_var() { return getRuleContext<fichierAntlrParser::Type_varContext>(0); } tree::TerminalNode* fichierAntlrParser::Declaration_definitiontableau_charContext::NOM() { return getToken(fichierAntlrParser::NOM, 0); } fichierAntlrParser::ExprContext* fichierAntlrParser::Declaration_definitiontableau_charContext::expr() { return getRuleContext<fichierAntlrParser::ExprContext>(0); } std::vector<tree::TerminalNode *> fichierAntlrParser::Declaration_definitiontableau_charContext::CHAR() { return getTokens(fichierAntlrParser::CHAR); } tree::TerminalNode* fichierAntlrParser::Declaration_definitiontableau_charContext::CHAR(size_t i) { return getToken(fichierAntlrParser::CHAR, i); } fichierAntlrParser::Declaration_definitiontableau_charContext::Declaration_definitiontableau_charContext(DeclarationContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Declaration_definitiontableau_charContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitDeclaration_definitiontableau_char(this); else return visitor->visitChildren(this); } //----------------- Declaration_definitiontableau_nombreContext ------------------------------------------------------------------ fichierAntlrParser::Type_varContext* fichierAntlrParser::Declaration_definitiontableau_nombreContext::type_var() { return getRuleContext<fichierAntlrParser::Type_varContext>(0); } tree::TerminalNode* fichierAntlrParser::Declaration_definitiontableau_nombreContext::NOM() { return getToken(fichierAntlrParser::NOM, 0); } fichierAntlrParser::ExprContext* fichierAntlrParser::Declaration_definitiontableau_nombreContext::expr() { return getRuleContext<fichierAntlrParser::ExprContext>(0); } std::vector<tree::TerminalNode *> fichierAntlrParser::Declaration_definitiontableau_nombreContext::NOMBRE() { return getTokens(fichierAntlrParser::NOMBRE); } tree::TerminalNode* fichierAntlrParser::Declaration_definitiontableau_nombreContext::NOMBRE(size_t i) { return getToken(fichierAntlrParser::NOMBRE, i); } fichierAntlrParser::Declaration_definitiontableau_nombreContext::Declaration_definitiontableau_nombreContext(DeclarationContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Declaration_definitiontableau_nombreContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitDeclaration_definitiontableau_nombre(this); else return visitor->visitChildren(this); } fichierAntlrParser::DeclarationContext* fichierAntlrParser::declaration() { DeclarationContext *_localctx = _tracker.createInstance<DeclarationContext>(_ctx, getState()); enterRule(_localctx, 22, fichierAntlrParser::RuleDeclaration); size_t _la = 0; auto onExit = finally([=] { exitRule(); }); try { setState(387); _errHandler->sync(this); switch (getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 25, _ctx)) { case 1: { _localctx = dynamic_cast<DeclarationContext *>(_tracker.createInstance<fichierAntlrParser::Declaration_normaleContext>(_localctx)); enterOuterAlt(_localctx, 1); setState(327); type_var(); setState(328); match(fichierAntlrParser::NOM); setState(333); _errHandler->sync(this); _la = _input->LA(1); while (_la == fichierAntlrParser::T__38) { setState(329); match(fichierAntlrParser::T__38); setState(330); match(fichierAntlrParser::NOM); setState(335); _errHandler->sync(this); _la = _input->LA(1); } setState(336); match(fichierAntlrParser::T__40); break; } case 2: { _localctx = dynamic_cast<DeclarationContext *>(_tracker.createInstance<fichierAntlrParser::Declaration_definitionContext>(_localctx)); enterOuterAlt(_localctx, 2); setState(338); type_var(); setState(339); match(fichierAntlrParser::NOM); setState(340); match(fichierAntlrParser::T__10); setState(341); expr(0); setState(342); match(fichierAntlrParser::T__40); break; } case 3: { _localctx = dynamic_cast<DeclarationContext *>(_tracker.createInstance<fichierAntlrParser::Declaration_tableauContext>(_localctx)); enterOuterAlt(_localctx, 3); setState(344); type_var(); setState(345); match(fichierAntlrParser::NOM); setState(346); match(fichierAntlrParser::T__6); setState(347); expr(0); setState(348); match(fichierAntlrParser::T__7); setState(349); match(fichierAntlrParser::T__40); break; } case 4: { _localctx = dynamic_cast<DeclarationContext *>(_tracker.createInstance<fichierAntlrParser::Declaration_definitiontableau_nombreContext>(_localctx)); enterOuterAlt(_localctx, 4); setState(351); type_var(); setState(352); match(fichierAntlrParser::NOM); setState(353); match(fichierAntlrParser::T__6); setState(354); expr(0); setState(355); match(fichierAntlrParser::T__7); setState(356); match(fichierAntlrParser::T__10); setState(357); match(fichierAntlrParser::T__3); setState(358); match(fichierAntlrParser::NOMBRE); setState(363); _errHandler->sync(this); _la = _input->LA(1); while (_la == fichierAntlrParser::T__38) { setState(359); match(fichierAntlrParser::T__38); setState(360); match(fichierAntlrParser::NOMBRE); setState(365); _errHandler->sync(this); _la = _input->LA(1); } setState(366); match(fichierAntlrParser::T__4); setState(367); match(fichierAntlrParser::T__40); break; } case 5: { _localctx = dynamic_cast<DeclarationContext *>(_tracker.createInstance<fichierAntlrParser::Declaration_definitiontableau_charContext>(_localctx)); enterOuterAlt(_localctx, 5); setState(369); type_var(); setState(370); match(fichierAntlrParser::NOM); setState(371); match(fichierAntlrParser::T__6); setState(372); expr(0); setState(373); match(fichierAntlrParser::T__7); setState(374); match(fichierAntlrParser::T__10); setState(375); match(fichierAntlrParser::T__3); setState(376); match(fichierAntlrParser::CHAR); setState(381); _errHandler->sync(this); _la = _input->LA(1); while (_la == fichierAntlrParser::T__38) { setState(377); match(fichierAntlrParser::T__38); setState(378); match(fichierAntlrParser::CHAR); setState(383); _errHandler->sync(this); _la = _input->LA(1); } setState(384); match(fichierAntlrParser::T__4); setState(385); match(fichierAntlrParser::T__40); break; } } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Structure_ifContext ------------------------------------------------------------------ fichierAntlrParser::Structure_ifContext::Structure_ifContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } size_t fichierAntlrParser::Structure_ifContext::getRuleIndex() const { return fichierAntlrParser::RuleStructure_if; } void fichierAntlrParser::Structure_ifContext::copyFrom(Structure_ifContext *ctx) { ParserRuleContext::copyFrom(ctx); } //----------------- Structureif_normalContext ------------------------------------------------------------------ fichierAntlrParser::ExprContext* fichierAntlrParser::Structureif_normalContext::expr() { return getRuleContext<fichierAntlrParser::ExprContext>(0); } fichierAntlrParser::Else_Context* fichierAntlrParser::Structureif_normalContext::else_() { return getRuleContext<fichierAntlrParser::Else_Context>(0); } fichierAntlrParser::BlocContext* fichierAntlrParser::Structureif_normalContext::bloc() { return getRuleContext<fichierAntlrParser::BlocContext>(0); } fichierAntlrParser::InstructionContext* fichierAntlrParser::Structureif_normalContext::instruction() { return getRuleContext<fichierAntlrParser::InstructionContext>(0); } fichierAntlrParser::Structureif_normalContext::Structureif_normalContext(Structure_ifContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Structureif_normalContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitStructureif_normal(this); else return visitor->visitChildren(this); } fichierAntlrParser::Structure_ifContext* fichierAntlrParser::structure_if() { Structure_ifContext *_localctx = _tracker.createInstance<Structure_ifContext>(_ctx, getState()); enterRule(_localctx, 24, fichierAntlrParser::RuleStructure_if); auto onExit = finally([=] { exitRule(); }); try { _localctx = dynamic_cast<Structure_ifContext *>(_tracker.createInstance<fichierAntlrParser::Structureif_normalContext>(_localctx)); enterOuterAlt(_localctx, 1); setState(389); match(fichierAntlrParser::T__42); setState(390); match(fichierAntlrParser::T__1); setState(391); expr(0); setState(392); match(fichierAntlrParser::T__2); setState(398); _errHandler->sync(this); switch (_input->LA(1)) { case fichierAntlrParser::T__3: { setState(393); match(fichierAntlrParser::T__3); setState(394); bloc(); setState(395); match(fichierAntlrParser::T__4); break; } case fichierAntlrParser::T__1: case fichierAntlrParser::T__8: case fichierAntlrParser::T__9: case fichierAntlrParser::T__20: case fichierAntlrParser::T__21: case fichierAntlrParser::T__39: case fichierAntlrParser::T__41: case fichierAntlrParser::T__42: case fichierAntlrParser::T__44: case fichierAntlrParser::NOM: case fichierAntlrParser::CHIFFRE: case fichierAntlrParser::NOMBRE: case fichierAntlrParser::CHAR: { setState(397); instruction(); break; } default: throw NoViableAltException(this); } setState(400); else_(); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Else_Context ------------------------------------------------------------------ fichierAntlrParser::Else_Context::Else_Context(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } size_t fichierAntlrParser::Else_Context::getRuleIndex() const { return fichierAntlrParser::RuleElse_; } void fichierAntlrParser::Else_Context::copyFrom(Else_Context *ctx) { ParserRuleContext::copyFrom(ctx); } //----------------- Else_normalContext ------------------------------------------------------------------ fichierAntlrParser::BlocContext* fichierAntlrParser::Else_normalContext::bloc() { return getRuleContext<fichierAntlrParser::BlocContext>(0); } fichierAntlrParser::InstructionContext* fichierAntlrParser::Else_normalContext::instruction() { return getRuleContext<fichierAntlrParser::InstructionContext>(0); } fichierAntlrParser::Else_normalContext::Else_normalContext(Else_Context *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Else_normalContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitElse_normal(this); else return visitor->visitChildren(this); } fichierAntlrParser::Else_Context* fichierAntlrParser::else_() { Else_Context *_localctx = _tracker.createInstance<Else_Context>(_ctx, getState()); enterRule(_localctx, 26, fichierAntlrParser::RuleElse_); auto onExit = finally([=] { exitRule(); }); try { _localctx = dynamic_cast<Else_Context *>(_tracker.createInstance<fichierAntlrParser::Else_normalContext>(_localctx)); enterOuterAlt(_localctx, 1); setState(410); _errHandler->sync(this); switch (getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 28, _ctx)) { case 1: { setState(402); match(fichierAntlrParser::T__43); setState(408); _errHandler->sync(this); switch (_input->LA(1)) { case fichierAntlrParser::T__3: { setState(403); match(fichierAntlrParser::T__3); setState(404); bloc(); setState(405); match(fichierAntlrParser::T__4); break; } case fichierAntlrParser::T__1: case fichierAntlrParser::T__8: case fichierAntlrParser::T__9: case fichierAntlrParser::T__20: case fichierAntlrParser::T__21: case fichierAntlrParser::T__39: case fichierAntlrParser::T__41: case fichierAntlrParser::T__42: case fichierAntlrParser::T__44: case fichierAntlrParser::NOM: case fichierAntlrParser::CHIFFRE: case fichierAntlrParser::NOMBRE: case fichierAntlrParser::CHAR: { setState(407); instruction(); break; } default: throw NoViableAltException(this); } break; } } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Structure_whileContext ------------------------------------------------------------------ fichierAntlrParser::Structure_whileContext::Structure_whileContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } size_t fichierAntlrParser::Structure_whileContext::getRuleIndex() const { return fichierAntlrParser::RuleStructure_while; } void fichierAntlrParser::Structure_whileContext::copyFrom(Structure_whileContext *ctx) { ParserRuleContext::copyFrom(ctx); } //----------------- Structurewhile_normalContext ------------------------------------------------------------------ fichierAntlrParser::ExprContext* fichierAntlrParser::Structurewhile_normalContext::expr() { return getRuleContext<fichierAntlrParser::ExprContext>(0); } fichierAntlrParser::BlocContext* fichierAntlrParser::Structurewhile_normalContext::bloc() { return getRuleContext<fichierAntlrParser::BlocContext>(0); } fichierAntlrParser::InstructionContext* fichierAntlrParser::Structurewhile_normalContext::instruction() { return getRuleContext<fichierAntlrParser::InstructionContext>(0); } fichierAntlrParser::Structurewhile_normalContext::Structurewhile_normalContext(Structure_whileContext *ctx) { copyFrom(ctx); } antlrcpp::Any fichierAntlrParser::Structurewhile_normalContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitStructurewhile_normal(this); else return visitor->visitChildren(this); } fichierAntlrParser::Structure_whileContext* fichierAntlrParser::structure_while() { Structure_whileContext *_localctx = _tracker.createInstance<Structure_whileContext>(_ctx, getState()); enterRule(_localctx, 28, fichierAntlrParser::RuleStructure_while); auto onExit = finally([=] { exitRule(); }); try { _localctx = dynamic_cast<Structure_whileContext *>(_tracker.createInstance<fichierAntlrParser::Structurewhile_normalContext>(_localctx)); enterOuterAlt(_localctx, 1); setState(412); match(fichierAntlrParser::T__44); setState(413); match(fichierAntlrParser::T__1); setState(414); expr(0); setState(415); match(fichierAntlrParser::T__2); setState(421); _errHandler->sync(this); switch (_input->LA(1)) { case fichierAntlrParser::T__3: { setState(416); match(fichierAntlrParser::T__3); setState(417); bloc(); setState(418); match(fichierAntlrParser::T__4); break; } case fichierAntlrParser::T__1: case fichierAntlrParser::T__8: case fichierAntlrParser::T__9: case fichierAntlrParser::T__20: case fichierAntlrParser::T__21: case fichierAntlrParser::T__39: case fichierAntlrParser::T__41: case fichierAntlrParser::T__42: case fichierAntlrParser::T__44: case fichierAntlrParser::NOM: case fichierAntlrParser::CHIFFRE: case fichierAntlrParser::NOMBRE: case fichierAntlrParser::CHAR: { setState(420); instruction(); break; } default: throw NoViableAltException(this); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Type_varContext ------------------------------------------------------------------ fichierAntlrParser::Type_varContext::Type_varContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } size_t fichierAntlrParser::Type_varContext::getRuleIndex() const { return fichierAntlrParser::RuleType_var; } antlrcpp::Any fichierAntlrParser::Type_varContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitType_var(this); else return visitor->visitChildren(this); } fichierAntlrParser::Type_varContext* fichierAntlrParser::type_var() { Type_varContext *_localctx = _tracker.createInstance<Type_varContext>(_ctx, getState()); enterRule(_localctx, 30, fichierAntlrParser::RuleType_var); size_t _la = 0; auto onExit = finally([=] { exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(423); _la = _input->LA(1); if (!((((_la & ~ 0x3fULL) == 0) && ((1ULL << _la) & ((1ULL << fichierAntlrParser::T__45) | (1ULL << fichierAntlrParser::T__46) | (1ULL << fichierAntlrParser::T__47))) != 0))) { _errHandler->recoverInline(this); } else { _errHandler->reportMatch(this); consume(); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Type_fonctionContext ------------------------------------------------------------------ fichierAntlrParser::Type_fonctionContext::Type_fonctionContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } size_t fichierAntlrParser::Type_fonctionContext::getRuleIndex() const { return fichierAntlrParser::RuleType_fonction; } antlrcpp::Any fichierAntlrParser::Type_fonctionContext::accept(tree::ParseTreeVisitor *visitor) { if (auto parserVisitor = dynamic_cast<fichierAntlrVisitor*>(visitor)) return parserVisitor->visitType_fonction(this); else return visitor->visitChildren(this); } fichierAntlrParser::Type_fonctionContext* fichierAntlrParser::type_fonction() { Type_fonctionContext *_localctx = _tracker.createInstance<Type_fonctionContext>(_ctx, getState()); enterRule(_localctx, 32, fichierAntlrParser::RuleType_fonction); size_t _la = 0; auto onExit = finally([=] { exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(425); _la = _input->LA(1); if (!((((_la & ~ 0x3fULL) == 0) && ((1ULL << _la) & ((1ULL << fichierAntlrParser::T__5) | (1ULL << fichierAntlrParser::T__45) | (1ULL << fichierAntlrParser::T__46) | (1ULL << fichierAntlrParser::T__47) | (1ULL << fichierAntlrParser::T__48))) != 0))) { _errHandler->recoverInline(this); } else { _errHandler->reportMatch(this); consume(); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } bool fichierAntlrParser::sempred(RuleContext *context, size_t ruleIndex, size_t predicateIndex) { switch (ruleIndex) { case 6: return exprSempred(dynamic_cast<ExprContext *>(context), predicateIndex); default: break; } return true; } bool fichierAntlrParser::exprSempred(ExprContext *_localctx, size_t predicateIndex) { switch (predicateIndex) { case 0: return precpred(_ctx, 21); case 1: return precpred(_ctx, 20); case 2: return precpred(_ctx, 19); case 3: return precpred(_ctx, 18); case 4: return precpred(_ctx, 17); case 5: return precpred(_ctx, 16); case 6: return precpred(_ctx, 15); case 7: return precpred(_ctx, 14); case 8: return precpred(_ctx, 13); case 9: return precpred(_ctx, 12); case 10: return precpred(_ctx, 11); case 11: return precpred(_ctx, 10); case 12: return precpred(_ctx, 9); case 13: return precpred(_ctx, 8); case 14: return precpred(_ctx, 7); case 15: return precpred(_ctx, 6); case 16: return precpred(_ctx, 5); case 17: return precpred(_ctx, 4); default: break; } return true; } // Static vars and initialization. std::vector<dfa::DFA> fichierAntlrParser::_decisionToDFA; atn::PredictionContextCache fichierAntlrParser::_sharedContextCache; // We own the ATN which in turn owns the ATN states. atn::ATN fichierAntlrParser::_atn; std::vector<uint16_t> fichierAntlrParser::_serializedATN; std::vector<std::string> fichierAntlrParser::_ruleNames = { "programme", "main", "fonction", "parametre", "variable", "affectation", "expr", "return_", "break_", "instruction", "bloc", "declaration", "structure_if", "else_", "structure_while", "type_var", "type_fonction" }; std::vector<std::string> fichierAntlrParser::_literalNames = { "", "'main'", "'('", "')'", "'{'", "'}'", "'void'", "'['", "']'", "'++'", "'--'", "'='", "'&='", "'|='", "'+='", "'-='", "'*='", "'/='", "'%='", "'<='", "'>='", "'~'", "'!'", "'*'", "'/'", "'%'", "'+'", "'-'", "'<<'", "'>>'", "'&'", "'|'", "'^'", "'&&'", "'||'", "'<'", "'>'", "'=='", "'!='", "','", "'return'", "';'", "'break'", "'if'", "'else'", "'while'", "'char'", "'int64_t'", "'int32_t'", "'int'" }; std::vector<std::string> fichierAntlrParser::_symbolicNames = { "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "Include", "EspaceBlanc", "CommentaireBlock", "CommentaireLigne", "NOM", "LETTRE", "CHIFFRE", "NOMBRE", "CHAR", "SYMBOLE" }; dfa::Vocabulary fichierAntlrParser::_vocabulary(_literalNames, _symbolicNames); std::vector<std::string> fichierAntlrParser::_tokenNames; fichierAntlrParser::Initializer::Initializer() { for (size_t i = 0; i < _symbolicNames.size(); ++i) { std::string name = _vocabulary.getLiteralName(i); if (name.empty()) { name = _vocabulary.getSymbolicName(i); } if (name.empty()) { _tokenNames.push_back("<INVALID>"); } else { _tokenNames.push_back(name); } } _serializedATN = { 0x3, 0x608b, 0xa72a, 0x8133, 0xb9ed, 0x417c, 0x3be7, 0x7786, 0x5964, 0x3, 0x3d, 0x1ae, 0x4, 0x2, 0x9, 0x2, 0x4, 0x3, 0x9, 0x3, 0x4, 0x4, 0x9, 0x4, 0x4, 0x5, 0x9, 0x5, 0x4, 0x6, 0x9, 0x6, 0x4, 0x7, 0x9, 0x7, 0x4, 0x8, 0x9, 0x8, 0x4, 0x9, 0x9, 0x9, 0x4, 0xa, 0x9, 0xa, 0x4, 0xb, 0x9, 0xb, 0x4, 0xc, 0x9, 0xc, 0x4, 0xd, 0x9, 0xd, 0x4, 0xe, 0x9, 0xe, 0x4, 0xf, 0x9, 0xf, 0x4, 0x10, 0x9, 0x10, 0x4, 0x11, 0x9, 0x11, 0x4, 0x12, 0x9, 0x12, 0x3, 0x2, 0x7, 0x2, 0x26, 0xa, 0x2, 0xc, 0x2, 0xe, 0x2, 0x29, 0xb, 0x2, 0x3, 0x2, 0x7, 0x2, 0x2c, 0xa, 0x2, 0xc, 0x2, 0xe, 0x2, 0x2f, 0xb, 0x2, 0x3, 0x2, 0x7, 0x2, 0x32, 0xa, 0x2, 0xc, 0x2, 0xe, 0x2, 0x35, 0xb, 0x2, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x7, 0x3, 0x3e, 0xa, 0x3, 0xc, 0x3, 0xe, 0x3, 0x41, 0xb, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x7, 0x3, 0x4c, 0xa, 0x3, 0xc, 0x3, 0xe, 0x3, 0x4f, 0xb, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x7, 0x3, 0x5b, 0xa, 0x3, 0xc, 0x3, 0xe, 0x3, 0x5e, 0xb, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x5, 0x3, 0x63, 0xa, 0x3, 0x3, 0x4, 0x3, 0x4, 0x3, 0x4, 0x3, 0x4, 0x3, 0x4, 0x3, 0x4, 0x3, 0x4, 0x7, 0x4, 0x6c, 0xa, 0x4, 0xc, 0x4, 0xe, 0x4, 0x6f, 0xb, 0x4, 0x3, 0x4, 0x3, 0x4, 0x3, 0x4, 0x3, 0x4, 0x3, 0x4, 0x3, 0x4, 0x3, 0x4, 0x3, 0x4, 0x3, 0x4, 0x7, 0x4, 0x7a, 0xa, 0x4, 0xc, 0x4, 0xe, 0x4, 0x7d, 0xb, 0x4, 0x3, 0x4, 0x3, 0x4, 0x3, 0x4, 0x3, 0x4, 0x3, 0x4, 0x3, 0x4, 0x3, 0x4, 0x3, 0x4, 0x3, 0x4, 0x3, 0x4, 0x7, 0x4, 0x89, 0xa, 0x4, 0xc, 0x4, 0xe, 0x4, 0x8c, 0xb, 0x4, 0x3, 0x4, 0x3, 0x4, 0x3, 0x4, 0x5, 0x4, 0x91, 0xa, 0x4, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x5, 0x5, 0x9c, 0xa, 0x5, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x5, 0x6, 0xa4, 0xa, 0x6, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x5, 0x7, 0xd8, 0xa, 0x7, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x7, 0x8, 0xed, 0xa, 0x8, 0xc, 0x8, 0xe, 0x8, 0xf0, 0xb, 0x8, 0x5, 0x8, 0xf2, 0xa, 0x8, 0x3, 0x8, 0x5, 0x8, 0xf5, 0xa, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x7, 0x8, 0x12d, 0xa, 0x8, 0xc, 0x8, 0xe, 0x8, 0x130, 0xb, 0x8, 0x3, 0x9, 0x3, 0x9, 0x5, 0x9, 0x134, 0xa, 0x9, 0x3, 0x9, 0x3, 0x9, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xb, 0x3, 0xb, 0x3, 0xb, 0x3, 0xb, 0x3, 0xb, 0x3, 0xb, 0x3, 0xb, 0x5, 0xb, 0x142, 0xa, 0xb, 0x3, 0xc, 0x7, 0xc, 0x145, 0xa, 0xc, 0xc, 0xc, 0xe, 0xc, 0x148, 0xb, 0xc, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x7, 0xd, 0x14e, 0xa, 0xd, 0xc, 0xd, 0xe, 0xd, 0x151, 0xb, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x7, 0xd, 0x16c, 0xa, 0xd, 0xc, 0xd, 0xe, 0xd, 0x16f, 0xb, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x7, 0xd, 0x17e, 0xa, 0xd, 0xc, 0xd, 0xe, 0xd, 0x181, 0xb, 0xd, 0x3, 0xd, 0x3, 0xd, 0x3, 0xd, 0x5, 0xd, 0x186, 0xa, 0xd, 0x3, 0xe, 0x3, 0xe, 0x3, 0xe, 0x3, 0xe, 0x3, 0xe, 0x3, 0xe, 0x3, 0xe, 0x3, 0xe, 0x3, 0xe, 0x5, 0xe, 0x191, 0xa, 0xe, 0x3, 0xe, 0x3, 0xe, 0x3, 0xf, 0x3, 0xf, 0x3, 0xf, 0x3, 0xf, 0x3, 0xf, 0x3, 0xf, 0x5, 0xf, 0x19b, 0xa, 0xf, 0x5, 0xf, 0x19d, 0xa, 0xf, 0x3, 0x10, 0x3, 0x10, 0x3, 0x10, 0x3, 0x10, 0x3, 0x10, 0x3, 0x10, 0x3, 0x10, 0x3, 0x10, 0x3, 0x10, 0x5, 0x10, 0x1a8, 0xa, 0x10, 0x3, 0x11, 0x3, 0x11, 0x3, 0x12, 0x3, 0x12, 0x3, 0x12, 0x2, 0x3, 0xe, 0x13, 0x2, 0x4, 0x6, 0x8, 0xa, 0xc, 0xe, 0x10, 0x12, 0x14, 0x16, 0x18, 0x1a, 0x1c, 0x1e, 0x20, 0x22, 0x2, 0x4, 0x3, 0x2, 0x30, 0x32, 0x4, 0x2, 0x8, 0x8, 0x30, 0x33, 0x2, 0x1e5, 0x2, 0x27, 0x3, 0x2, 0x2, 0x2, 0x4, 0x62, 0x3, 0x2, 0x2, 0x2, 0x6, 0x90, 0x3, 0x2, 0x2, 0x2, 0x8, 0x9b, 0x3, 0x2, 0x2, 0x2, 0xa, 0xa3, 0x3, 0x2, 0x2, 0x2, 0xc, 0xd7, 0x3, 0x2, 0x2, 0x2, 0xe, 0xf4, 0x3, 0x2, 0x2, 0x2, 0x10, 0x131, 0x3, 0x2, 0x2, 0x2, 0x12, 0x137, 0x3, 0x2, 0x2, 0x2, 0x14, 0x141, 0x3, 0x2, 0x2, 0x2, 0x16, 0x146, 0x3, 0x2, 0x2, 0x2, 0x18, 0x185, 0x3, 0x2, 0x2, 0x2, 0x1a, 0x187, 0x3, 0x2, 0x2, 0x2, 0x1c, 0x19c, 0x3, 0x2, 0x2, 0x2, 0x1e, 0x19e, 0x3, 0x2, 0x2, 0x2, 0x20, 0x1a9, 0x3, 0x2, 0x2, 0x2, 0x22, 0x1ab, 0x3, 0x2, 0x2, 0x2, 0x24, 0x26, 0x5, 0x18, 0xd, 0x2, 0x25, 0x24, 0x3, 0x2, 0x2, 0x2, 0x26, 0x29, 0x3, 0x2, 0x2, 0x2, 0x27, 0x25, 0x3, 0x2, 0x2, 0x2, 0x27, 0x28, 0x3, 0x2, 0x2, 0x2, 0x28, 0x2d, 0x3, 0x2, 0x2, 0x2, 0x29, 0x27, 0x3, 0x2, 0x2, 0x2, 0x2a, 0x2c, 0x5, 0x6, 0x4, 0x2, 0x2b, 0x2a, 0x3, 0x2, 0x2, 0x2, 0x2c, 0x2f, 0x3, 0x2, 0x2, 0x2, 0x2d, 0x2b, 0x3, 0x2, 0x2, 0x2, 0x2d, 0x2e, 0x3, 0x2, 0x2, 0x2, 0x2e, 0x33, 0x3, 0x2, 0x2, 0x2, 0x2f, 0x2d, 0x3, 0x2, 0x2, 0x2, 0x30, 0x32, 0x5, 0x4, 0x3, 0x2, 0x31, 0x30, 0x3, 0x2, 0x2, 0x2, 0x32, 0x35, 0x3, 0x2, 0x2, 0x2, 0x33, 0x31, 0x3, 0x2, 0x2, 0x2, 0x33, 0x34, 0x3, 0x2, 0x2, 0x2, 0x34, 0x3, 0x3, 0x2, 0x2, 0x2, 0x35, 0x33, 0x3, 0x2, 0x2, 0x2, 0x36, 0x37, 0x5, 0x22, 0x12, 0x2, 0x37, 0x38, 0x7, 0x3, 0x2, 0x2, 0x38, 0x39, 0x7, 0x4, 0x2, 0x2, 0x39, 0x3a, 0x5, 0x8, 0x5, 0x2, 0x3a, 0x3b, 0x7, 0x5, 0x2, 0x2, 0x3b, 0x3f, 0x7, 0x6, 0x2, 0x2, 0x3c, 0x3e, 0x5, 0x18, 0xd, 0x2, 0x3d, 0x3c, 0x3, 0x2, 0x2, 0x2, 0x3e, 0x41, 0x3, 0x2, 0x2, 0x2, 0x3f, 0x3d, 0x3, 0x2, 0x2, 0x2, 0x3f, 0x40, 0x3, 0x2, 0x2, 0x2, 0x40, 0x42, 0x3, 0x2, 0x2, 0x2, 0x41, 0x3f, 0x3, 0x2, 0x2, 0x2, 0x42, 0x43, 0x5, 0x16, 0xc, 0x2, 0x43, 0x44, 0x7, 0x7, 0x2, 0x2, 0x44, 0x63, 0x3, 0x2, 0x2, 0x2, 0x45, 0x46, 0x5, 0x22, 0x12, 0x2, 0x46, 0x47, 0x7, 0x3, 0x2, 0x2, 0x47, 0x48, 0x7, 0x4, 0x2, 0x2, 0x48, 0x49, 0x7, 0x5, 0x2, 0x2, 0x49, 0x4d, 0x7, 0x6, 0x2, 0x2, 0x4a, 0x4c, 0x5, 0x18, 0xd, 0x2, 0x4b, 0x4a, 0x3, 0x2, 0x2, 0x2, 0x4c, 0x4f, 0x3, 0x2, 0x2, 0x2, 0x4d, 0x4b, 0x3, 0x2, 0x2, 0x2, 0x4d, 0x4e, 0x3, 0x2, 0x2, 0x2, 0x4e, 0x50, 0x3, 0x2, 0x2, 0x2, 0x4f, 0x4d, 0x3, 0x2, 0x2, 0x2, 0x50, 0x51, 0x5, 0x16, 0xc, 0x2, 0x51, 0x52, 0x7, 0x7, 0x2, 0x2, 0x52, 0x63, 0x3, 0x2, 0x2, 0x2, 0x53, 0x54, 0x5, 0x22, 0x12, 0x2, 0x54, 0x55, 0x7, 0x3, 0x2, 0x2, 0x55, 0x56, 0x7, 0x4, 0x2, 0x2, 0x56, 0x57, 0x7, 0x8, 0x2, 0x2, 0x57, 0x58, 0x7, 0x5, 0x2, 0x2, 0x58, 0x5c, 0x7, 0x6, 0x2, 0x2, 0x59, 0x5b, 0x5, 0x18, 0xd, 0x2, 0x5a, 0x59, 0x3, 0x2, 0x2, 0x2, 0x5b, 0x5e, 0x3, 0x2, 0x2, 0x2, 0x5c, 0x5a, 0x3, 0x2, 0x2, 0x2, 0x5c, 0x5d, 0x3, 0x2, 0x2, 0x2, 0x5d, 0x5f, 0x3, 0x2, 0x2, 0x2, 0x5e, 0x5c, 0x3, 0x2, 0x2, 0x2, 0x5f, 0x60, 0x5, 0x16, 0xc, 0x2, 0x60, 0x61, 0x7, 0x7, 0x2, 0x2, 0x61, 0x63, 0x3, 0x2, 0x2, 0x2, 0x62, 0x36, 0x3, 0x2, 0x2, 0x2, 0x62, 0x45, 0x3, 0x2, 0x2, 0x2, 0x62, 0x53, 0x3, 0x2, 0x2, 0x2, 0x63, 0x5, 0x3, 0x2, 0x2, 0x2, 0x64, 0x65, 0x5, 0x22, 0x12, 0x2, 0x65, 0x66, 0x7, 0x38, 0x2, 0x2, 0x66, 0x67, 0x7, 0x4, 0x2, 0x2, 0x67, 0x68, 0x5, 0x8, 0x5, 0x2, 0x68, 0x69, 0x7, 0x5, 0x2, 0x2, 0x69, 0x6d, 0x7, 0x6, 0x2, 0x2, 0x6a, 0x6c, 0x5, 0x18, 0xd, 0x2, 0x6b, 0x6a, 0x3, 0x2, 0x2, 0x2, 0x6c, 0x6f, 0x3, 0x2, 0x2, 0x2, 0x6d, 0x6b, 0x3, 0x2, 0x2, 0x2, 0x6d, 0x6e, 0x3, 0x2, 0x2, 0x2, 0x6e, 0x70, 0x3, 0x2, 0x2, 0x2, 0x6f, 0x6d, 0x3, 0x2, 0x2, 0x2, 0x70, 0x71, 0x5, 0x16, 0xc, 0x2, 0x71, 0x72, 0x7, 0x7, 0x2, 0x2, 0x72, 0x91, 0x3, 0x2, 0x2, 0x2, 0x73, 0x74, 0x5, 0x22, 0x12, 0x2, 0x74, 0x75, 0x7, 0x38, 0x2, 0x2, 0x75, 0x76, 0x7, 0x4, 0x2, 0x2, 0x76, 0x77, 0x7, 0x5, 0x2, 0x2, 0x77, 0x7b, 0x7, 0x6, 0x2, 0x2, 0x78, 0x7a, 0x5, 0x18, 0xd, 0x2, 0x79, 0x78, 0x3, 0x2, 0x2, 0x2, 0x7a, 0x7d, 0x3, 0x2, 0x2, 0x2, 0x7b, 0x79, 0x3, 0x2, 0x2, 0x2, 0x7b, 0x7c, 0x3, 0x2, 0x2, 0x2, 0x7c, 0x7e, 0x3, 0x2, 0x2, 0x2, 0x7d, 0x7b, 0x3, 0x2, 0x2, 0x2, 0x7e, 0x7f, 0x5, 0x16, 0xc, 0x2, 0x7f, 0x80, 0x7, 0x7, 0x2, 0x2, 0x80, 0x91, 0x3, 0x2, 0x2, 0x2, 0x81, 0x82, 0x5, 0x22, 0x12, 0x2, 0x82, 0x83, 0x7, 0x38, 0x2, 0x2, 0x83, 0x84, 0x7, 0x4, 0x2, 0x2, 0x84, 0x85, 0x7, 0x8, 0x2, 0x2, 0x85, 0x86, 0x7, 0x5, 0x2, 0x2, 0x86, 0x8a, 0x7, 0x6, 0x2, 0x2, 0x87, 0x89, 0x5, 0x18, 0xd, 0x2, 0x88, 0x87, 0x3, 0x2, 0x2, 0x2, 0x89, 0x8c, 0x3, 0x2, 0x2, 0x2, 0x8a, 0x88, 0x3, 0x2, 0x2, 0x2, 0x8a, 0x8b, 0x3, 0x2, 0x2, 0x2, 0x8b, 0x8d, 0x3, 0x2, 0x2, 0x2, 0x8c, 0x8a, 0x3, 0x2, 0x2, 0x2, 0x8d, 0x8e, 0x5, 0x16, 0xc, 0x2, 0x8e, 0x8f, 0x7, 0x7, 0x2, 0x2, 0x8f, 0x91, 0x3, 0x2, 0x2, 0x2, 0x90, 0x64, 0x3, 0x2, 0x2, 0x2, 0x90, 0x73, 0x3, 0x2, 0x2, 0x2, 0x90, 0x81, 0x3, 0x2, 0x2, 0x2, 0x91, 0x7, 0x3, 0x2, 0x2, 0x2, 0x92, 0x93, 0x5, 0x20, 0x11, 0x2, 0x93, 0x94, 0x7, 0x38, 0x2, 0x2, 0x94, 0x9c, 0x3, 0x2, 0x2, 0x2, 0x95, 0x96, 0x5, 0x20, 0x11, 0x2, 0x96, 0x97, 0x7, 0x38, 0x2, 0x2, 0x97, 0x98, 0x7, 0x9, 0x2, 0x2, 0x98, 0x99, 0x7, 0x3a, 0x2, 0x2, 0x99, 0x9a, 0x7, 0xa, 0x2, 0x2, 0x9a, 0x9c, 0x3, 0x2, 0x2, 0x2, 0x9b, 0x92, 0x3, 0x2, 0x2, 0x2, 0x9b, 0x95, 0x3, 0x2, 0x2, 0x2, 0x9c, 0x9, 0x3, 0x2, 0x2, 0x2, 0x9d, 0xa4, 0x7, 0x38, 0x2, 0x2, 0x9e, 0x9f, 0x7, 0x38, 0x2, 0x2, 0x9f, 0xa0, 0x7, 0x9, 0x2, 0x2, 0xa0, 0xa1, 0x5, 0xe, 0x8, 0x2, 0xa1, 0xa2, 0x7, 0xa, 0x2, 0x2, 0xa2, 0xa4, 0x3, 0x2, 0x2, 0x2, 0xa3, 0x9d, 0x3, 0x2, 0x2, 0x2, 0xa3, 0x9e, 0x3, 0x2, 0x2, 0x2, 0xa4, 0xb, 0x3, 0x2, 0x2, 0x2, 0xa5, 0xa6, 0x5, 0xa, 0x6, 0x2, 0xa6, 0xa7, 0x7, 0xb, 0x2, 0x2, 0xa7, 0xd8, 0x3, 0x2, 0x2, 0x2, 0xa8, 0xa9, 0x7, 0xb, 0x2, 0x2, 0xa9, 0xd8, 0x5, 0xa, 0x6, 0x2, 0xaa, 0xab, 0x5, 0xa, 0x6, 0x2, 0xab, 0xac, 0x7, 0xc, 0x2, 0x2, 0xac, 0xd8, 0x3, 0x2, 0x2, 0x2, 0xad, 0xae, 0x7, 0xc, 0x2, 0x2, 0xae, 0xd8, 0x5, 0xa, 0x6, 0x2, 0xaf, 0xb0, 0x5, 0xa, 0x6, 0x2, 0xb0, 0xb1, 0x7, 0xd, 0x2, 0x2, 0xb1, 0xb2, 0x5, 0xe, 0x8, 0x2, 0xb2, 0xd8, 0x3, 0x2, 0x2, 0x2, 0xb3, 0xb4, 0x5, 0xa, 0x6, 0x2, 0xb4, 0xb5, 0x7, 0xe, 0x2, 0x2, 0xb5, 0xb6, 0x5, 0xe, 0x8, 0x2, 0xb6, 0xd8, 0x3, 0x2, 0x2, 0x2, 0xb7, 0xb8, 0x5, 0xa, 0x6, 0x2, 0xb8, 0xb9, 0x7, 0xf, 0x2, 0x2, 0xb9, 0xba, 0x5, 0xe, 0x8, 0x2, 0xba, 0xd8, 0x3, 0x2, 0x2, 0x2, 0xbb, 0xbc, 0x5, 0xa, 0x6, 0x2, 0xbc, 0xbd, 0x7, 0x10, 0x2, 0x2, 0xbd, 0xbe, 0x5, 0xe, 0x8, 0x2, 0xbe, 0xd8, 0x3, 0x2, 0x2, 0x2, 0xbf, 0xc0, 0x5, 0xa, 0x6, 0x2, 0xc0, 0xc1, 0x7, 0x11, 0x2, 0x2, 0xc1, 0xc2, 0x5, 0xe, 0x8, 0x2, 0xc2, 0xd8, 0x3, 0x2, 0x2, 0x2, 0xc3, 0xc4, 0x5, 0xa, 0x6, 0x2, 0xc4, 0xc5, 0x7, 0x12, 0x2, 0x2, 0xc5, 0xc6, 0x5, 0xe, 0x8, 0x2, 0xc6, 0xd8, 0x3, 0x2, 0x2, 0x2, 0xc7, 0xc8, 0x5, 0xa, 0x6, 0x2, 0xc8, 0xc9, 0x7, 0x13, 0x2, 0x2, 0xc9, 0xca, 0x5, 0xe, 0x8, 0x2, 0xca, 0xd8, 0x3, 0x2, 0x2, 0x2, 0xcb, 0xcc, 0x5, 0xa, 0x6, 0x2, 0xcc, 0xcd, 0x7, 0x14, 0x2, 0x2, 0xcd, 0xce, 0x5, 0xe, 0x8, 0x2, 0xce, 0xd8, 0x3, 0x2, 0x2, 0x2, 0xcf, 0xd0, 0x5, 0xa, 0x6, 0x2, 0xd0, 0xd1, 0x7, 0x15, 0x2, 0x2, 0xd1, 0xd2, 0x5, 0xe, 0x8, 0x2, 0xd2, 0xd8, 0x3, 0x2, 0x2, 0x2, 0xd3, 0xd4, 0x5, 0xa, 0x6, 0x2, 0xd4, 0xd5, 0x7, 0x16, 0x2, 0x2, 0xd5, 0xd6, 0x5, 0xe, 0x8, 0x2, 0xd6, 0xd8, 0x3, 0x2, 0x2, 0x2, 0xd7, 0xa5, 0x3, 0x2, 0x2, 0x2, 0xd7, 0xa8, 0x3, 0x2, 0x2, 0x2, 0xd7, 0xaa, 0x3, 0x2, 0x2, 0x2, 0xd7, 0xad, 0x3, 0x2, 0x2, 0x2, 0xd7, 0xaf, 0x3, 0x2, 0x2, 0x2, 0xd7, 0xb3, 0x3, 0x2, 0x2, 0x2, 0xd7, 0xb7, 0x3, 0x2, 0x2, 0x2, 0xd7, 0xbb, 0x3, 0x2, 0x2, 0x2, 0xd7, 0xbf, 0x3, 0x2, 0x2, 0x2, 0xd7, 0xc3, 0x3, 0x2, 0x2, 0x2, 0xd7, 0xc7, 0x3, 0x2, 0x2, 0x2, 0xd7, 0xcb, 0x3, 0x2, 0x2, 0x2, 0xd7, 0xcf, 0x3, 0x2, 0x2, 0x2, 0xd7, 0xd3, 0x3, 0x2, 0x2, 0x2, 0xd8, 0xd, 0x3, 0x2, 0x2, 0x2, 0xd9, 0xda, 0x8, 0x8, 0x1, 0x2, 0xda, 0xf5, 0x7, 0x3a, 0x2, 0x2, 0xdb, 0xf5, 0x7, 0x3b, 0x2, 0x2, 0xdc, 0xf5, 0x7, 0x3c, 0x2, 0x2, 0xdd, 0xde, 0x7, 0x4, 0x2, 0x2, 0xde, 0xdf, 0x5, 0xe, 0x8, 0x2, 0xdf, 0xe0, 0x7, 0x5, 0x2, 0x2, 0xe0, 0xf5, 0x3, 0x2, 0x2, 0x2, 0xe1, 0xe2, 0x7, 0x17, 0x2, 0x2, 0xe2, 0xf5, 0x5, 0xe, 0x8, 0x19, 0xe3, 0xe4, 0x7, 0x18, 0x2, 0x2, 0xe4, 0xf5, 0x5, 0xe, 0x8, 0x18, 0xe5, 0xf5, 0x5, 0xa, 0x6, 0x2, 0xe6, 0xf5, 0x5, 0xc, 0x7, 0x2, 0xe7, 0xe8, 0x7, 0x38, 0x2, 0x2, 0xe8, 0xf1, 0x7, 0x4, 0x2, 0x2, 0xe9, 0xee, 0x5, 0xe, 0x8, 0x2, 0xea, 0xeb, 0x7, 0x29, 0x2, 0x2, 0xeb, 0xed, 0x5, 0xe, 0x8, 0x2, 0xec, 0xea, 0x3, 0x2, 0x2, 0x2, 0xed, 0xf0, 0x3, 0x2, 0x2, 0x2, 0xee, 0xec, 0x3, 0x2, 0x2, 0x2, 0xee, 0xef, 0x3, 0x2, 0x2, 0x2, 0xef, 0xf2, 0x3, 0x2, 0x2, 0x2, 0xf0, 0xee, 0x3, 0x2, 0x2, 0x2, 0xf1, 0xe9, 0x3, 0x2, 0x2, 0x2, 0xf1, 0xf2, 0x3, 0x2, 0x2, 0x2, 0xf2, 0xf3, 0x3, 0x2, 0x2, 0x2, 0xf3, 0xf5, 0x7, 0x5, 0x2, 0x2, 0xf4, 0xd9, 0x3, 0x2, 0x2, 0x2, 0xf4, 0xdb, 0x3, 0x2, 0x2, 0x2, 0xf4, 0xdc, 0x3, 0x2, 0x2, 0x2, 0xf4, 0xdd, 0x3, 0x2, 0x2, 0x2, 0xf4, 0xe1, 0x3, 0x2, 0x2, 0x2, 0xf4, 0xe3, 0x3, 0x2, 0x2, 0x2, 0xf4, 0xe5, 0x3, 0x2, 0x2, 0x2, 0xf4, 0xe6, 0x3, 0x2, 0x2, 0x2, 0xf4, 0xe7, 0x3, 0x2, 0x2, 0x2, 0xf5, 0x12e, 0x3, 0x2, 0x2, 0x2, 0xf6, 0xf7, 0xc, 0x17, 0x2, 0x2, 0xf7, 0xf8, 0x7, 0x19, 0x2, 0x2, 0xf8, 0x12d, 0x5, 0xe, 0x8, 0x18, 0xf9, 0xfa, 0xc, 0x16, 0x2, 0x2, 0xfa, 0xfb, 0x7, 0x1a, 0x2, 0x2, 0xfb, 0x12d, 0x5, 0xe, 0x8, 0x17, 0xfc, 0xfd, 0xc, 0x15, 0x2, 0x2, 0xfd, 0xfe, 0x7, 0x1b, 0x2, 0x2, 0xfe, 0x12d, 0x5, 0xe, 0x8, 0x16, 0xff, 0x100, 0xc, 0x14, 0x2, 0x2, 0x100, 0x101, 0x7, 0x1c, 0x2, 0x2, 0x101, 0x12d, 0x5, 0xe, 0x8, 0x15, 0x102, 0x103, 0xc, 0x13, 0x2, 0x2, 0x103, 0x104, 0x7, 0x1d, 0x2, 0x2, 0x104, 0x12d, 0x5, 0xe, 0x8, 0x14, 0x105, 0x106, 0xc, 0x12, 0x2, 0x2, 0x106, 0x107, 0x7, 0x1e, 0x2, 0x2, 0x107, 0x12d, 0x5, 0xe, 0x8, 0x13, 0x108, 0x109, 0xc, 0x11, 0x2, 0x2, 0x109, 0x10a, 0x7, 0x1f, 0x2, 0x2, 0x10a, 0x12d, 0x5, 0xe, 0x8, 0x12, 0x10b, 0x10c, 0xc, 0x10, 0x2, 0x2, 0x10c, 0x10d, 0x7, 0x20, 0x2, 0x2, 0x10d, 0x12d, 0x5, 0xe, 0x8, 0x11, 0x10e, 0x10f, 0xc, 0xf, 0x2, 0x2, 0x10f, 0x110, 0x7, 0x21, 0x2, 0x2, 0x110, 0x12d, 0x5, 0xe, 0x8, 0x10, 0x111, 0x112, 0xc, 0xe, 0x2, 0x2, 0x112, 0x113, 0x7, 0x22, 0x2, 0x2, 0x113, 0x12d, 0x5, 0xe, 0x8, 0xf, 0x114, 0x115, 0xc, 0xd, 0x2, 0x2, 0x115, 0x116, 0x7, 0x23, 0x2, 0x2, 0x116, 0x12d, 0x5, 0xe, 0x8, 0xe, 0x117, 0x118, 0xc, 0xc, 0x2, 0x2, 0x118, 0x119, 0x7, 0x24, 0x2, 0x2, 0x119, 0x12d, 0x5, 0xe, 0x8, 0xd, 0x11a, 0x11b, 0xc, 0xb, 0x2, 0x2, 0x11b, 0x11c, 0x7, 0x25, 0x2, 0x2, 0x11c, 0x12d, 0x5, 0xe, 0x8, 0xc, 0x11d, 0x11e, 0xc, 0xa, 0x2, 0x2, 0x11e, 0x11f, 0x7, 0x15, 0x2, 0x2, 0x11f, 0x12d, 0x5, 0xe, 0x8, 0xb, 0x120, 0x121, 0xc, 0x9, 0x2, 0x2, 0x121, 0x122, 0x7, 0x26, 0x2, 0x2, 0x122, 0x12d, 0x5, 0xe, 0x8, 0xa, 0x123, 0x124, 0xc, 0x8, 0x2, 0x2, 0x124, 0x125, 0x7, 0x16, 0x2, 0x2, 0x125, 0x12d, 0x5, 0xe, 0x8, 0x9, 0x126, 0x127, 0xc, 0x7, 0x2, 0x2, 0x127, 0x128, 0x7, 0x27, 0x2, 0x2, 0x128, 0x12d, 0x5, 0xe, 0x8, 0x8, 0x129, 0x12a, 0xc, 0x6, 0x2, 0x2, 0x12a, 0x12b, 0x7, 0x28, 0x2, 0x2, 0x12b, 0x12d, 0x5, 0xe, 0x8, 0x7, 0x12c, 0xf6, 0x3, 0x2, 0x2, 0x2, 0x12c, 0xf9, 0x3, 0x2, 0x2, 0x2, 0x12c, 0xfc, 0x3, 0x2, 0x2, 0x2, 0x12c, 0xff, 0x3, 0x2, 0x2, 0x2, 0x12c, 0x102, 0x3, 0x2, 0x2, 0x2, 0x12c, 0x105, 0x3, 0x2, 0x2, 0x2, 0x12c, 0x108, 0x3, 0x2, 0x2, 0x2, 0x12c, 0x10b, 0x3, 0x2, 0x2, 0x2, 0x12c, 0x10e, 0x3, 0x2, 0x2, 0x2, 0x12c, 0x111, 0x3, 0x2, 0x2, 0x2, 0x12c, 0x114, 0x3, 0x2, 0x2, 0x2, 0x12c, 0x117, 0x3, 0x2, 0x2, 0x2, 0x12c, 0x11a, 0x3, 0x2, 0x2, 0x2, 0x12c, 0x11d, 0x3, 0x2, 0x2, 0x2, 0x12c, 0x120, 0x3, 0x2, 0x2, 0x2, 0x12c, 0x123, 0x3, 0x2, 0x2, 0x2, 0x12c, 0x126, 0x3, 0x2, 0x2, 0x2, 0x12c, 0x129, 0x3, 0x2, 0x2, 0x2, 0x12d, 0x130, 0x3, 0x2, 0x2, 0x2, 0x12e, 0x12c, 0x3, 0x2, 0x2, 0x2, 0x12e, 0x12f, 0x3, 0x2, 0x2, 0x2, 0x12f, 0xf, 0x3, 0x2, 0x2, 0x2, 0x130, 0x12e, 0x3, 0x2, 0x2, 0x2, 0x131, 0x133, 0x7, 0x2a, 0x2, 0x2, 0x132, 0x134, 0x5, 0xe, 0x8, 0x2, 0x133, 0x132, 0x3, 0x2, 0x2, 0x2, 0x133, 0x134, 0x3, 0x2, 0x2, 0x2, 0x134, 0x135, 0x3, 0x2, 0x2, 0x2, 0x135, 0x136, 0x7, 0x2b, 0x2, 0x2, 0x136, 0x11, 0x3, 0x2, 0x2, 0x2, 0x137, 0x138, 0x7, 0x2c, 0x2, 0x2, 0x138, 0x139, 0x7, 0x2b, 0x2, 0x2, 0x139, 0x13, 0x3, 0x2, 0x2, 0x2, 0x13a, 0x142, 0x5, 0x1a, 0xe, 0x2, 0x13b, 0x142, 0x5, 0x1e, 0x10, 0x2, 0x13c, 0x13d, 0x5, 0xe, 0x8, 0x2, 0x13d, 0x13e, 0x7, 0x2b, 0x2, 0x2, 0x13e, 0x142, 0x3, 0x2, 0x2, 0x2, 0x13f, 0x142, 0x5, 0x10, 0x9, 0x2, 0x140, 0x142, 0x5, 0x12, 0xa, 0x2, 0x141, 0x13a, 0x3, 0x2, 0x2, 0x2, 0x141, 0x13b, 0x3, 0x2, 0x2, 0x2, 0x141, 0x13c, 0x3, 0x2, 0x2, 0x2, 0x141, 0x13f, 0x3, 0x2, 0x2, 0x2, 0x141, 0x140, 0x3, 0x2, 0x2, 0x2, 0x142, 0x15, 0x3, 0x2, 0x2, 0x2, 0x143, 0x145, 0x5, 0x14, 0xb, 0x2, 0x144, 0x143, 0x3, 0x2, 0x2, 0x2, 0x145, 0x148, 0x3, 0x2, 0x2, 0x2, 0x146, 0x144, 0x3, 0x2, 0x2, 0x2, 0x146, 0x147, 0x3, 0x2, 0x2, 0x2, 0x147, 0x17, 0x3, 0x2, 0x2, 0x2, 0x148, 0x146, 0x3, 0x2, 0x2, 0x2, 0x149, 0x14a, 0x5, 0x20, 0x11, 0x2, 0x14a, 0x14f, 0x7, 0x38, 0x2, 0x2, 0x14b, 0x14c, 0x7, 0x29, 0x2, 0x2, 0x14c, 0x14e, 0x7, 0x38, 0x2, 0x2, 0x14d, 0x14b, 0x3, 0x2, 0x2, 0x2, 0x14e, 0x151, 0x3, 0x2, 0x2, 0x2, 0x14f, 0x14d, 0x3, 0x2, 0x2, 0x2, 0x14f, 0x150, 0x3, 0x2, 0x2, 0x2, 0x150, 0x152, 0x3, 0x2, 0x2, 0x2, 0x151, 0x14f, 0x3, 0x2, 0x2, 0x2, 0x152, 0x153, 0x7, 0x2b, 0x2, 0x2, 0x153, 0x186, 0x3, 0x2, 0x2, 0x2, 0x154, 0x155, 0x5, 0x20, 0x11, 0x2, 0x155, 0x156, 0x7, 0x38, 0x2, 0x2, 0x156, 0x157, 0x7, 0xd, 0x2, 0x2, 0x157, 0x158, 0x5, 0xe, 0x8, 0x2, 0x158, 0x159, 0x7, 0x2b, 0x2, 0x2, 0x159, 0x186, 0x3, 0x2, 0x2, 0x2, 0x15a, 0x15b, 0x5, 0x20, 0x11, 0x2, 0x15b, 0x15c, 0x7, 0x38, 0x2, 0x2, 0x15c, 0x15d, 0x7, 0x9, 0x2, 0x2, 0x15d, 0x15e, 0x5, 0xe, 0x8, 0x2, 0x15e, 0x15f, 0x7, 0xa, 0x2, 0x2, 0x15f, 0x160, 0x7, 0x2b, 0x2, 0x2, 0x160, 0x186, 0x3, 0x2, 0x2, 0x2, 0x161, 0x162, 0x5, 0x20, 0x11, 0x2, 0x162, 0x163, 0x7, 0x38, 0x2, 0x2, 0x163, 0x164, 0x7, 0x9, 0x2, 0x2, 0x164, 0x165, 0x5, 0xe, 0x8, 0x2, 0x165, 0x166, 0x7, 0xa, 0x2, 0x2, 0x166, 0x167, 0x7, 0xd, 0x2, 0x2, 0x167, 0x168, 0x7, 0x6, 0x2, 0x2, 0x168, 0x16d, 0x7, 0x3b, 0x2, 0x2, 0x169, 0x16a, 0x7, 0x29, 0x2, 0x2, 0x16a, 0x16c, 0x7, 0x3b, 0x2, 0x2, 0x16b, 0x169, 0x3, 0x2, 0x2, 0x2, 0x16c, 0x16f, 0x3, 0x2, 0x2, 0x2, 0x16d, 0x16b, 0x3, 0x2, 0x2, 0x2, 0x16d, 0x16e, 0x3, 0x2, 0x2, 0x2, 0x16e, 0x170, 0x3, 0x2, 0x2, 0x2, 0x16f, 0x16d, 0x3, 0x2, 0x2, 0x2, 0x170, 0x171, 0x7, 0x7, 0x2, 0x2, 0x171, 0x172, 0x7, 0x2b, 0x2, 0x2, 0x172, 0x186, 0x3, 0x2, 0x2, 0x2, 0x173, 0x174, 0x5, 0x20, 0x11, 0x2, 0x174, 0x175, 0x7, 0x38, 0x2, 0x2, 0x175, 0x176, 0x7, 0x9, 0x2, 0x2, 0x176, 0x177, 0x5, 0xe, 0x8, 0x2, 0x177, 0x178, 0x7, 0xa, 0x2, 0x2, 0x178, 0x179, 0x7, 0xd, 0x2, 0x2, 0x179, 0x17a, 0x7, 0x6, 0x2, 0x2, 0x17a, 0x17f, 0x7, 0x3c, 0x2, 0x2, 0x17b, 0x17c, 0x7, 0x29, 0x2, 0x2, 0x17c, 0x17e, 0x7, 0x3c, 0x2, 0x2, 0x17d, 0x17b, 0x3, 0x2, 0x2, 0x2, 0x17e, 0x181, 0x3, 0x2, 0x2, 0x2, 0x17f, 0x17d, 0x3, 0x2, 0x2, 0x2, 0x17f, 0x180, 0x3, 0x2, 0x2, 0x2, 0x180, 0x182, 0x3, 0x2, 0x2, 0x2, 0x181, 0x17f, 0x3, 0x2, 0x2, 0x2, 0x182, 0x183, 0x7, 0x7, 0x2, 0x2, 0x183, 0x184, 0x7, 0x2b, 0x2, 0x2, 0x184, 0x186, 0x3, 0x2, 0x2, 0x2, 0x185, 0x149, 0x3, 0x2, 0x2, 0x2, 0x185, 0x154, 0x3, 0x2, 0x2, 0x2, 0x185, 0x15a, 0x3, 0x2, 0x2, 0x2, 0x185, 0x161, 0x3, 0x2, 0x2, 0x2, 0x185, 0x173, 0x3, 0x2, 0x2, 0x2, 0x186, 0x19, 0x3, 0x2, 0x2, 0x2, 0x187, 0x188, 0x7, 0x2d, 0x2, 0x2, 0x188, 0x189, 0x7, 0x4, 0x2, 0x2, 0x189, 0x18a, 0x5, 0xe, 0x8, 0x2, 0x18a, 0x190, 0x7, 0x5, 0x2, 0x2, 0x18b, 0x18c, 0x7, 0x6, 0x2, 0x2, 0x18c, 0x18d, 0x5, 0x16, 0xc, 0x2, 0x18d, 0x18e, 0x7, 0x7, 0x2, 0x2, 0x18e, 0x191, 0x3, 0x2, 0x2, 0x2, 0x18f, 0x191, 0x5, 0x14, 0xb, 0x2, 0x190, 0x18b, 0x3, 0x2, 0x2, 0x2, 0x190, 0x18f, 0x3, 0x2, 0x2, 0x2, 0x191, 0x192, 0x3, 0x2, 0x2, 0x2, 0x192, 0x193, 0x5, 0x1c, 0xf, 0x2, 0x193, 0x1b, 0x3, 0x2, 0x2, 0x2, 0x194, 0x19a, 0x7, 0x2e, 0x2, 0x2, 0x195, 0x196, 0x7, 0x6, 0x2, 0x2, 0x196, 0x197, 0x5, 0x16, 0xc, 0x2, 0x197, 0x198, 0x7, 0x7, 0x2, 0x2, 0x198, 0x19b, 0x3, 0x2, 0x2, 0x2, 0x199, 0x19b, 0x5, 0x14, 0xb, 0x2, 0x19a, 0x195, 0x3, 0x2, 0x2, 0x2, 0x19a, 0x199, 0x3, 0x2, 0x2, 0x2, 0x19b, 0x19d, 0x3, 0x2, 0x2, 0x2, 0x19c, 0x194, 0x3, 0x2, 0x2, 0x2, 0x19c, 0x19d, 0x3, 0x2, 0x2, 0x2, 0x19d, 0x1d, 0x3, 0x2, 0x2, 0x2, 0x19e, 0x19f, 0x7, 0x2f, 0x2, 0x2, 0x19f, 0x1a0, 0x7, 0x4, 0x2, 0x2, 0x1a0, 0x1a1, 0x5, 0xe, 0x8, 0x2, 0x1a1, 0x1a7, 0x7, 0x5, 0x2, 0x2, 0x1a2, 0x1a3, 0x7, 0x6, 0x2, 0x2, 0x1a3, 0x1a4, 0x5, 0x16, 0xc, 0x2, 0x1a4, 0x1a5, 0x7, 0x7, 0x2, 0x2, 0x1a5, 0x1a8, 0x3, 0x2, 0x2, 0x2, 0x1a6, 0x1a8, 0x5, 0x14, 0xb, 0x2, 0x1a7, 0x1a2, 0x3, 0x2, 0x2, 0x2, 0x1a7, 0x1a6, 0x3, 0x2, 0x2, 0x2, 0x1a8, 0x1f, 0x3, 0x2, 0x2, 0x2, 0x1a9, 0x1aa, 0x9, 0x2, 0x2, 0x2, 0x1aa, 0x21, 0x3, 0x2, 0x2, 0x2, 0x1ab, 0x1ac, 0x9, 0x3, 0x2, 0x2, 0x1ac, 0x23, 0x3, 0x2, 0x2, 0x2, 0x20, 0x27, 0x2d, 0x33, 0x3f, 0x4d, 0x5c, 0x62, 0x6d, 0x7b, 0x8a, 0x90, 0x9b, 0xa3, 0xd7, 0xee, 0xf1, 0xf4, 0x12c, 0x12e, 0x133, 0x141, 0x146, 0x14f, 0x16d, 0x17f, 0x185, 0x190, 0x19a, 0x19c, 0x1a7, }; atn::ATNDeserializer deserializer; _atn = deserializer.deserialize(_serializedATN); size_t count = _atn.getNumberOfDecisions(); _decisionToDFA.reserve(count); for (size_t i = 0; i < count; i++) { _decisionToDFA.emplace_back(_atn.getDecisionState(i), i); } } fichierAntlrParser::Initializer fichierAntlrParser::_init;
// Created on: 1997-02-06 // Created by: Kernel // Copyright (c) 1997-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Storage_HeaderData_HeaderFile #define _Storage_HeaderData_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <Standard_Integer.hxx> #include <TColStd_SequenceOfAsciiString.hxx> #include <TColStd_SequenceOfExtendedString.hxx> #include <Storage_Error.hxx> #include <Standard_Transient.hxx> class Storage_BaseDriver; class Storage_HeaderData; DEFINE_STANDARD_HANDLE(Storage_HeaderData, Standard_Transient) class Storage_HeaderData : public Standard_Transient { public: Standard_EXPORT Storage_HeaderData(); Standard_EXPORT Standard_Boolean Read (const Handle(Storage_BaseDriver)& theDriver); //! return the creation date Standard_EXPORT TCollection_AsciiString CreationDate() const; //! return the Storage package version Standard_EXPORT TCollection_AsciiString StorageVersion() const; //! get the version of the schema Standard_EXPORT TCollection_AsciiString SchemaVersion() const; //! get the schema's name Standard_EXPORT TCollection_AsciiString SchemaName() const; //! set the version of the application Standard_EXPORT void SetApplicationVersion (const TCollection_AsciiString& aVersion); //! get the version of the application Standard_EXPORT TCollection_AsciiString ApplicationVersion() const; //! set the name of the application Standard_EXPORT void SetApplicationName (const TCollection_ExtendedString& aName); //! get the name of the application Standard_EXPORT TCollection_ExtendedString ApplicationName() const; //! set the data type Standard_EXPORT void SetDataType (const TCollection_ExtendedString& aType); //! returns data type Standard_EXPORT TCollection_ExtendedString DataType() const; //! add <theUserInfo> to the user information Standard_EXPORT void AddToUserInfo (const TCollection_AsciiString& theUserInfo); //! return the user information Standard_EXPORT const TColStd_SequenceOfAsciiString& UserInfo() const; //! add <theUserInfo> to the user information Standard_EXPORT void AddToComments (const TCollection_ExtendedString& aComment); //! return the user information Standard_EXPORT const TColStd_SequenceOfExtendedString& Comments() const; //! the number of persistent objects //! Return: //! the number of persistent objects readed Standard_EXPORT Standard_Integer NumberOfObjects() const; Standard_EXPORT Storage_Error ErrorStatus() const; Standard_EXPORT TCollection_AsciiString ErrorStatusExtension() const; Standard_EXPORT void ClearErrorStatus(); friend class Storage_Schema; DEFINE_STANDARD_RTTIEXT(Storage_HeaderData,Standard_Transient) public: Standard_EXPORT void SetNumberOfObjects (const Standard_Integer anObjectNumber); Standard_EXPORT void SetStorageVersion (const TCollection_AsciiString& aVersion); void SetStorageVersion (const Standard_Integer theVersion) { SetStorageVersion (TCollection_AsciiString (theVersion)); } Standard_EXPORT void SetCreationDate (const TCollection_AsciiString& aDate); Standard_EXPORT void SetSchemaVersion (const TCollection_AsciiString& aVersion); Standard_EXPORT void SetSchemaName (const TCollection_AsciiString& aName); private: Standard_EXPORT void SetErrorStatus (const Storage_Error anError); Standard_EXPORT void SetErrorStatusExtension (const TCollection_AsciiString& anErrorExt); Standard_Integer myNBObj; TCollection_AsciiString myStorageVersion; TCollection_AsciiString mySchemaVersion; TCollection_AsciiString mySchemaName; TCollection_AsciiString myApplicationVersion; TCollection_ExtendedString myApplicationName; TCollection_ExtendedString myDataType; TCollection_AsciiString myDate; TColStd_SequenceOfAsciiString myUserInfo; TColStd_SequenceOfExtendedString myComments; Storage_Error myErrorStatus; TCollection_AsciiString myErrorStatusExt; }; #endif // _Storage_HeaderData_HeaderFile
#include "types.h" #include "../include/catch.hpp" TEST_CASE("byte size") { REQUIRE(sizeof(core::byte) == 1); } TEST_CASE("byte extreme values") { REQUIRE((core::byte)(core::BYTE_MAX + 1) == core::BYTE_MIN); REQUIRE((core::byte)(core::BYTE_MIN - 1) == core::BYTE_MAX); }
class Category_660 { duplicate = 585; }; class Category_520 { duplicate = 585; };
// // Fiber.h // Landru // // Created by Nick Porcino on 10/29/14. // // #include "LandruActorVM/Exception.h" #include "LandruActorVM/FnContext.h" #include "LandruActorVM/MachineDefinition.h" #include "LandruActorVM/Property.h" #include "LandruActorVM/State.h" #include "LandruActorVM/VMContext.h" #include "LandruActorVM/WiresTypedData.h" #include <iostream> #include <memory> #include <string> #include <vector> /****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2014 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #ifndef CAF_COMPARABLE_HPP #define CAF_COMPARABLE_HPP namespace caf { namespace detail { /** * Barton–Nackman trick implementation. * `Subclass` must provide a compare member function that compares * to instances of `T` and returns an integer x with: * - `x < 0</tt> if <tt>*this < other * - `x > 0</tt> if <tt>*this > other * - `x == 0</tt> if <tt>*this == other */ template <class Subclass, class T = Subclass> class comparable { friend bool operator==(const Subclass& lhs, const T& rhs) { return lhs.compare(rhs) == 0; } friend bool operator==(const T& lhs, const Subclass& rhs) { return rhs.compare(lhs) == 0; } friend bool operator!=(const Subclass& lhs, const T& rhs) { return lhs.compare(rhs) != 0; } friend bool operator!=(const T& lhs, const Subclass& rhs) { return rhs.compare(lhs) != 0; } friend bool operator<(const Subclass& lhs, const T& rhs) { return lhs.compare(rhs) < 0; } friend bool operator>(const Subclass& lhs, const T& rhs) { return lhs.compare(rhs) > 0; } friend bool operator<(const T& lhs, const Subclass& rhs) { return rhs > lhs; } friend bool operator>(const T& lhs, const Subclass& rhs) { return rhs < lhs; } friend bool operator<=(const Subclass& lhs, const T& rhs) { return lhs.compare(rhs) <= 0; } friend bool operator>=(const Subclass& lhs, const T& rhs) { return lhs.compare(rhs) >= 0; } friend bool operator<=(const T& lhs, const Subclass& rhs) { return rhs >= lhs; } friend bool operator>=(const T& lhs, const Subclass& rhs) { return rhs <= lhs; } }; template <class Subclass> class comparable<Subclass, Subclass> { friend bool operator==(const Subclass& lhs, const Subclass& rhs) { return lhs.compare(rhs) == 0; } friend bool operator!=(const Subclass& lhs, const Subclass& rhs) { return lhs.compare(rhs) != 0; } friend bool operator<(const Subclass& lhs, const Subclass& rhs) { return lhs.compare(rhs) < 0; } friend bool operator<=(const Subclass& lhs, const Subclass& rhs) { return lhs.compare(rhs) <= 0; } friend bool operator>(const Subclass& lhs, const Subclass& rhs) { return lhs.compare(rhs) > 0; } friend bool operator>=(const Subclass& lhs, const Subclass& rhs) { return lhs.compare(rhs) >= 0; } }; } // namespace details } // namespace caf #endif // CAF_COMPARABLE_HPP namespace Landru { struct InvalidId { constexpr InvalidId() {} }; // Id class inspired by libcaf's node_id class Id : caf::detail::comparable<Id>, caf::detail::comparable<Id, InvalidId> { uint32_t _pid; unsigned char _uuid[16]; public: Id(); Id(const Id&); Id(const InvalidId&); ~Id() = default; Id& operator=(const Id&); Id& operator=(const InvalidId&); // Barton–Nackman comparable implementation. // `Subclass` must provide a compare member function that compares // to instances of `T` and returns an integer x with: // - `x < 0</tt> if <tt>*this < other // - `x > 0</tt> if <tt>*this > other // - `x == 0</tt> if <tt>*this == other int compare(const Id& other) const; int compare(const InvalidId&) const; }; class Fiber { Id _id; int scopeLevel = 1; // In the future, 0 will mean continuations at machine scope, specified outside of a state // higher levels will indicate within hierarchies of states const char * _currentState = nullptr; // this will always point to a string in the machine definition public: Fiber(std::shared_ptr<MachineDefinition> m, VMContext *); ~Fiber(); const Id& id() const { return _id; } const char * id_str() const { return "@TODO"; } void gotoState(FnContext& run, const char* name, bool raiseIfStateNotFound) { auto state = machineDefinition->states.find(name); if (state == machineDefinition->states.end()) { if (raiseIfStateNotFound) { VM_RAISE("main not found on machine"); } return; } _currentState = state->first.c_str(); run.clearContinuations(this, scopeLevel); run.run(state->second->instructions); } const char * currentState() const { return _currentState; } template <typename T> T top() { if (stack.empty() || stack.back().empty()) { VM_RAISE("stack underflow"); } std::shared_ptr<Wires::TypedData>& data = stack.back().back(); if (data->type() != typeid(T)) return 0; Wires::Data<T>* val = reinterpret_cast<Wires::Data<T>*>(data.get()); return val->value(); } std::shared_ptr<Wires::TypedData> topVar() const { if (stack.empty() || stack.back().empty()) { VM_RAISE("stack underflow"); } return stack.back().back(); } template <typename T> T pop() { if (stack.empty() || stack.back().empty()) { VM_RAISE("stack underflow"); } std::shared_ptr<Wires::TypedData>& data = stack.back().back(); if (!data) { VM_RAISE("nullptr on stack (variable not found?)"); } if (data->type() == typeid(T)) { Wires::Data<T>* val = reinterpret_cast<Wires::Data<T>*>(data.get()); T result = val->value(); stack.back().pop_back(); return result; } Wires::Data<T>* val = dynamic_cast<Wires::Data<T>*>(data.get()); if (!val) { VM_RAISE("Wrong type on stack to pop"); } T result= val->value(); stack.back().pop_back(); return result; } std::shared_ptr<Wires::TypedData> popVar() { if (stack.empty() || stack.back().empty()) { VM_RAISE("stack underflow"); } std::shared_ptr<Wires::TypedData> result = stack.back().back(); stack.back().pop_back(); return result; } template <typename T> T back(int i) { if (stack.empty()) { VM_RAISE("stack underflow"); } int sz = (int) stack.back().size(); if (sz + i < 0) { VM_RAISE("stack underflow"); } std::shared_ptr<Wires::TypedData>& data = stack.back()[sz + i]; if (data->type() != typeid(T)) return T(0); Wires::Data<T>* val = reinterpret_cast<Wires::Data<T>*>(data.get()); return val->value(); } template <typename T> void push(const T& val) { stack.back().push_back(std::make_shared<Wires::Data<T>>(val)); } void pushVar(std::shared_ptr<Wires::TypedData> v) { stack.back().push_back(v); } std::shared_ptr<Wires::TypedData> push_local(const std::string& name, const std::string& type, TypeFactory tf, std::shared_ptr<Wires::TypedData> v) { locals.push_back(std::move(std::make_shared<Property>(name, type, tf, v))); return (*locals.rbegin())->data; } void pop_local() { locals.pop_back(); } std::shared_ptr<MachineDefinition> machineDefinition; //std::map<std::string, std::shared_ptr<Property>> properties; // vector, because local scopes push back their local variables, and pop them on exit std::vector<std::shared_ptr<Property>> locals; typedef std::vector<std::shared_ptr<Wires::TypedData>> Stack; std::vector<Stack> stack; }; }
#include<iostream> using namespace std; int main() { int i,S,B,l,r,x,y; int na[100003],pa[100003]; while(1) { cin>>S>>B; if(S==0&&B==0) break; for(i=0;i<S+2;i++) { na[i]=i;pa[i]=i; } while(B--) { cin>>l>>r; x=na[r+1];y=pa[l-1]; while(x!=na[x])x=na[x]; while(y!=pa[y])y=pa[y]; na[l]=na[r]=x; pa[l]=pa[r]=y; if(pa[l]<1)cout<<"* "; else cout<<pa[l]<<" "; if(na[r]>S)cout<<"*"<<endl; else cout<<na[r]<<endl; } cout<<"-"<<endl; } }
#include <iberbar/RHI/D3D11/ShaderVariables.h> #include <iberbar/RHI/D3D11/ShaderReflection.h> #include <iberbar/RHI/D3D11/Device.h> namespace iberbar { namespace RHI { namespace D3D11 { template < typename T, UShaderVariableType tVarType > FORCEINLINE void TShaderVariableTable_SetValue( const CShaderReflection* pDecl, const char* strName, const T& value, uint8* pBuffer ) { const CShaderReflectionVariable* pVarDeclNode = pDecl->GetVariableByName( strName ); if ( pVarDeclNode == nullptr ) return; if ( pVarDeclNode->GetTypeInternal()->GetVariableType() != tVarType ) return; T* ptr = (T*)( pBuffer + pVarDeclNode->GetOffset() ); *ptr = value; } template < typename T, UShaderVariableType tVarType, UShaderVariableClass tVarClass > FORCEINLINE void TShaderVariableTable_SetValue( const CShaderReflection* pDecl, const char* strName, const T& value, uint8* pBuffer ) { const CShaderReflectionVariable* pVarDeclNode = pDecl->GetVariableByName( strName ); if ( pVarDeclNode == nullptr ) return; if ( pVarDeclNode->GetTypeInternal()->GetVariableType() != tVarType ) return; T* ptr = (T*)( pBuffer + pVarDeclNode->GetOffset() ); *ptr = value; } #ifdef _DEBUG template < typename T > FORCEINLINE void TShaderVariableTable_SetValue_Debug( const CShaderReflection* pDecl, const char* strName, uint8* pBuffer, std::unordered_map<std::string, UShaderVariant>& VarsDebug ) { auto iter = VarsDebug.find( strName ); if ( iter == VarsDebug.end() ) { auto pDeclNode = pDecl->GetVariableByName( strName ); if ( pDeclNode == nullptr ) return; UShaderVariant VarDebug; VarDebug.VarReflection = pDeclNode; VarDebug.VarData._v_void = (T*)( pBuffer + pDeclNode->GetOffset() ); VarsDebug.insert( std::make_pair( strName, VarDebug ) ); } } #endif //#ifdef _DEBUG // template < typename T > // FORCEINLINE void TShaderVariableTable_SetValue_Debug( // const CShaderReflection* pDecl, // const char* strName, // uint8* pBuffer, // std::unordered_map<std::string, UShaderVariant>& VarsDebug ) // { // auto iter = VarsDebug.find( strName ); // if ( iter == VarsDebug.end() ) // { // auto pDeclNode = pDecl->GetVariableByName( strName ); // if ( pDeclNode == nullptr ) // return; // UShaderVariant VarDebug; // VarDebug.VarReflection = pDeclNode; // VarDebug.VarData._v_void = (T*)( pBuffer + pDeclNode->GetOffset() ); // VarsDebug.insert( std::make_pair( strName, VarDebug ) ); // } // } //#endif } } } // //iberbar::RHI::D3D11::CUniformMemoryBuffer::CUniformMemoryBuffer() // : m_pMemory( nullptr ) // , m_nMemorySize( 0 ) // , m_Heads() //{ //} // // //iberbar::RHI::D3D11::CUniformMemoryBuffer::~CUniformMemoryBuffer() //{ // SAFE_DELETE( m_pMemory ); //} // // //void iberbar::RHI::D3D11::CUniformMemoryBuffer::SetShader( CShader* pShader ) //{ // CShaderReflection* pReflection = pShader->GetReflectionInternal(); // uint32 nBufferSizeTotal = pReflection->GetBufferSizeTotal(); // int nBufferCount = pReflection->GetBufferCountInternal(); // // SAFE_DELETE( m_pMemory ); // m_nMemorySize = 0; // m_Heads.clear(); // // if ( nBufferSizeTotal > 0 && nBufferCount > 0 ) // { // // m_pMemory = new uint8[ nBufferSizeTotal ]; // m_nMemorySize = nBufferSizeTotal; // m_Heads.resize( nBufferCount ); // // const CShaderReflectionBuffer* pShaderReflectionBuffer = nullptr; // for ( int i = 0; i < nBufferCount; i++ ) // { // pShaderReflectionBuffer = pReflection->GetBufferByIndexInternal( i ); // m_Heads[ i ] = (m_pMemory + pShaderReflectionBuffer->GetOffset() ); // } // } //} iberbar::RHI::D3D11::CShaderVariableTable::CShaderVariableTable( CDevice* pDevice ) : m_pDevice( pDevice ) , m_pShader( nullptr ) , m_pCommonMemory( nullptr ) //, m_CommonMemory() //, m_Buffers() , m_Textures() , m_SamplerStates() //#ifdef _DEBUG // , m_VarsDebug() //#endif { assert( m_pDevice ); m_pDevice->AddRef(); } iberbar::RHI::D3D11::CShaderVariableTable::~CShaderVariableTable() { //m_Buffers.clear(); UNKNOWN_SAFE_RELEASE_NULL( m_pShader ); SAFE_DELETE_ARRAY( m_pCommonMemory ); } void iberbar::RHI::D3D11::CShaderVariableTable::SetShader( IShader* pShader ) { if ( m_pShader != pShader ) { UNKNOWN_SAFE_RELEASE_NULL( m_pShader ); m_SamplerStates.clear(); m_Textures.clear(); SAFE_DELETE_ARRAY( m_pCommonMemory ); m_pShader = (CShader*)pShader; UNKNOWN_SAFE_ADDREF( m_pShader ); if ( m_pShader != nullptr ) { CShaderReflection* pReflection = m_pShader->GetReflectionInternal(); m_Textures.resize( pReflection->GetTextureCountTotal() ); m_SamplerStates.resize( pReflection->GetSamplerCountTotal() ); uint32 nBufferSizeTotal = pReflection->GetBufferSizeTotal(); int nBufferCount = pReflection->GetBufferCountInternal(); if ( nBufferSizeTotal > 0 && nBufferCount > 0 ) { m_pCommonMemory = new uint8[ nBufferSizeTotal ]; m_nCommonMemorySize = nBufferSizeTotal; } } } } void iberbar::RHI::D3D11::CShaderVariableTable::SetBool( const char* strName, bool value ) { if ( m_pCommonMemory == nullptr ) return; TShaderVariableTable_SetValue<uint32, UShaderVariableType::VT_Boolean>( m_pShader->GetReflectionInternal(), strName, ( value == false ) ? 0 : 1, m_pCommonMemory ); #ifdef _DEBUG TShaderVariableTable_SetValue_Debug<int32>( m_pShader->GetReflectionInternal(), strName, m_pCommonMemory, m_VarsDebug ); #endif } void iberbar::RHI::D3D11::CShaderVariableTable::SetInt( const char* strName, int value ) { if ( m_pCommonMemory == nullptr ) return; TShaderVariableTable_SetValue<int32, UShaderVariableType::VT_Int>( m_pShader->GetReflectionInternal(), strName, value, m_pCommonMemory ); #ifdef _DEBUG TShaderVariableTable_SetValue_Debug<int32>( m_pShader->GetReflectionInternal(), strName, m_pCommonMemory, m_VarsDebug ); #endif } void iberbar::RHI::D3D11::CShaderVariableTable::SetFloat( const char* strName, float value ) { if ( m_pCommonMemory == nullptr ) return; TShaderVariableTable_SetValue<float, UShaderVariableType::VT_Float>( m_pShader->GetReflectionInternal(), strName, value, m_pCommonMemory ); #ifdef _DEBUG TShaderVariableTable_SetValue_Debug<int32>( m_pShader->GetReflectionInternal(), strName, m_pCommonMemory, m_VarsDebug ); #endif } void iberbar::RHI::D3D11::CShaderVariableTable::SetVector( const char* strName, const DirectX::XMFLOAT4& value ) { if ( m_pCommonMemory == nullptr ) return; TShaderVariableTable_SetValue<DirectX::XMFLOAT4, UShaderVariableType::VT_Void, UShaderVariableClass::SVC_Vector>( m_pShader->GetReflectionInternal(), strName, value, m_pCommonMemory ); #ifdef _DEBUG TShaderVariableTable_SetValue_Debug<int32>( m_pShader->GetReflectionInternal(), strName, m_pCommonMemory, m_VarsDebug ); #endif } void iberbar::RHI::D3D11::CShaderVariableTable::SetMatrix( const char* strName, const DirectX::XMFLOAT4X4& value ) { if ( m_pCommonMemory == nullptr ) return; TShaderVariableTable_SetValue<DirectX::XMFLOAT4X4, UShaderVariableType::VT_Float, UShaderVariableClass::SVC_Matrix>( m_pShader->GetReflectionInternal(), strName, value, m_pCommonMemory ); #ifdef _DEBUG TShaderVariableTable_SetValue_Debug<int32>( m_pShader->GetReflectionInternal(), strName, m_pCommonMemory, m_VarsDebug ); #endif } void iberbar::RHI::D3D11::CShaderVariableTable::SetTexture( const char* strName, ITexture* pTexture ) { const CShaderReflectionBindResource* pReflectionVar = m_pShader->GetReflectionInternal()->GetTextureByName( strName ); if ( pReflectionVar == nullptr ) return; m_Textures[ pReflectionVar->GetBindPoint() ] = (CTexture*)pTexture; } void iberbar::RHI::D3D11::CShaderVariableTable::SetSamplerState( const char* strName, const UTextureSamplerState& SamplerDesc ) { const CShaderReflectionBindResource* pReflectionVar = m_pShader->GetReflectionInternal()->GetSamplerByName( strName ); if ( pReflectionVar == nullptr ) return; TSmartRefPtr<CSamplerState> pSampleState; CResult cRet = m_pDevice->CreateSamplerState( (ISamplerState**)(&pSampleState), SamplerDesc ); if ( cRet.IsOK() == false ) { return; } m_SamplerStates[ pReflectionVar->GetBindPoint() ] = pSampleState; } bool iberbar::RHI::D3D11::CShaderVariableTable::Compare( IShaderVariableTable* pVariableTable ) { CShaderVariableTable* pOther = (CShaderVariableTable*)pVariableTable; if ( m_nCommonMemorySize != pOther->m_nCommonMemorySize ) return false; if ( m_SamplerStates.size() != pOther->m_SamplerStates.size() ) return false; if ( m_Textures.size() != pOther->m_Textures.size() ) return false; if ( memcmp( m_pCommonMemory, pOther->m_pCommonMemory, m_nCommonMemorySize ) != 0 ) return false; for ( size_t i = 0, s = m_SamplerStates.size(); i < s; i++ ) { if ( m_SamplerStates[ i ] != pOther->m_SamplerStates[ i ] ) return false; } for ( size_t i = 0, s = m_Textures.size(); i < s; i++ ) { if ( m_Textures[ i ] != pOther->m_Textures[ i ] ) return false; } return true; }
// This file was generated based on /Users/r0xstation/18app/src/.uno/ux13/app18.unoproj.g.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.String.h> #include <Uno.UX.Property-1.h> namespace g{namespace Uno{namespace UX{struct PropertyObject;}}} namespace g{namespace Uno{namespace UX{struct Selector;}}} namespace g{struct app18_CollapsibleEntry_Description_Property;} namespace g{struct CollapsibleEntry;} namespace g{ // internal sealed class app18_CollapsibleEntry_Description_Property :420 // { ::g::Uno::UX::Property1_type* app18_CollapsibleEntry_Description_Property_typeof(); void app18_CollapsibleEntry_Description_Property__ctor_3_fn(app18_CollapsibleEntry_Description_Property* __this, ::g::CollapsibleEntry* obj, ::g::Uno::UX::Selector* name); void app18_CollapsibleEntry_Description_Property__Get1_fn(app18_CollapsibleEntry_Description_Property* __this, ::g::Uno::UX::PropertyObject* obj, uString** __retval); void app18_CollapsibleEntry_Description_Property__New1_fn(::g::CollapsibleEntry* obj, ::g::Uno::UX::Selector* name, app18_CollapsibleEntry_Description_Property** __retval); void app18_CollapsibleEntry_Description_Property__get_Object_fn(app18_CollapsibleEntry_Description_Property* __this, ::g::Uno::UX::PropertyObject** __retval); void app18_CollapsibleEntry_Description_Property__Set1_fn(app18_CollapsibleEntry_Description_Property* __this, ::g::Uno::UX::PropertyObject* obj, uString* v, uObject* origin); void app18_CollapsibleEntry_Description_Property__get_SupportsOriginSetter_fn(app18_CollapsibleEntry_Description_Property* __this, bool* __retval); struct app18_CollapsibleEntry_Description_Property : ::g::Uno::UX::Property1 { uWeak< ::g::CollapsibleEntry*> _obj; void ctor_3(::g::CollapsibleEntry* obj, ::g::Uno::UX::Selector name); static app18_CollapsibleEntry_Description_Property* New1(::g::CollapsibleEntry* obj, ::g::Uno::UX::Selector name); }; // } } // ::g
// // CommStation.cpp // SAD // // Created by Marquez, Richard A on 4/9/15. // Copyright (c) 2015 Richard Marquez. All rights reserved. // #include "CommStation.h" CommStation& CommStation::getInstance() { static CommStation instance; return instance; } CommStation::CommStation() { this->drone = Drone::getInstance(); // Establish connection with base SoftwareSerial* bluetoothSerial; bluetoothSerial = new SoftwareSerial(BT_TX_PIN, BT_RX_PIN); bluetoothSerial->begin(BAUD_RATE); this->serial = bluetoothSerial; } bool CommStation::isAvailable() { bool result = false; if (serial->isListening()) { result = true; } else { // TODO: clear cache } return result; } bool CommStation::isBusy() { bool result = false; if (serial->peek() != -1) { result = true; } return result; } Command CommStation::getCmd() { Command cmd; if (serial->available()) { serial->flush(); cmd.code = serial->read(); cmd.argument = 10; } return cmd; } void CommStation::sendString(String str) { serial->write(str.c_str()); } // Format: "([number of rangefinders]|[range1 distance],[range1 angle]|[range2 distance],[range2 angle]|...)" void CommStation::sendPacket(Packet packet) { int rangefinderCount = packet.RFData.size(); String str = START_TOKEN + String(rangefinderCount); for (int i = 0; i < rangefinderCount; ++i) { str += VAL_SET_TOKEN + String(packet.RFData[i].centimeters) + VAL_SEPARATOR + String(packet.RFData[i].angle); } str += String(BEGIN_HEADING) + int(packet.heading) + END_HEADING; str += END_TOKEN; sendString(str); }
// KC Text Adventure Framework - (c) Rachel J. Morris, 2012 - 2013. zlib license. Moosader.com #include "GameState.h" #include "../IOUtils/GameIO.h" #include "../IOUtils/Utils.h" #include <vector> bool GameState::Init(lua_State* state) { m_state = state; m_location.Init( state ); m_item.Init( state ); m_notebook.Init( state ); m_people.Init( state, m_notebook ); m_lua.Init( state ); m_movedLastTurn = true; return true; } bool GameState::MainLoop() { std::string choice; bool commandSuccess = false; m_notebook.AddItemToNotebook( "person.richardson", "Richardson" ); m_notebook.AddItemToNotebook( "location.kenagypark", "Kenagy Park" ); while ( 1 ) { if ( m_ptrMission->HandleMissionSwitch() ) { // Returns true on quit. return false; } commandSuccess = false; if ( m_movedLastTurn ) { DisplayHud(); m_movedLastTurn = false; } GIO::Out( "\n\t"); GIO::Out( m_ptrMission->GetWhatsNextPrompt() ); GIO::Out( "\n\t>> " ); choice = GIO::GetUserInput(); choice = Utils::ToLower( choice ); if ( choice == "quit" || choice == "exit" ) { // TODO: Fix state changing to not be based on a bool. GIO::OutLine( "\nI had had enough of this bullshit.\nI turned in my badge and gun an' decided to retire t' Florida.\n" ); return false; } else { // Weird code block TODO: cleanup commandSuccess = TryToMove( choice ); commandSuccess = ( commandSuccess ) ? commandSuccess : TryToGetHelp( choice ); commandSuccess = ( commandSuccess ) ? commandSuccess : TryToExamine( choice ); commandSuccess = ( commandSuccess ) ? commandSuccess : TryToTalk( choice ); commandSuccess = ( commandSuccess ) ? commandSuccess : TryNotebook( choice ); commandSuccess = ( commandSuccess ) ? commandSuccess : TryLua( choice ); if ( !commandSuccess ) { GIO::OutLine(); GIO::OutLine( m_ptrMission->GetBadCommandResponse() ); } } } return 0; // This shouldn't happen. :P } void GameState::SetMissionPtr( Mission& msn ) { m_ptrMission = &msn; } std::string GameState::Name() { return "Game"; } bool GameState::TryToGetHelp( const std::string& command ) { if ( Utils::StringContains( command, "help" ) ) { DisplayHelp(); return true; } return false; } bool GameState::TryLua( const std::string& command ) { if ( Utils::StringContains( command, "lua" ) ) { m_lua.DoLuaCommand(); return true; } return false; } bool GameState::TryToMove( const std::string& command ) { bool moved = false; if ( Utils::StringContains( command, "north" ) || Utils::StringContains( command, "south" ) || Utils::StringContains( command, "east" ) || Utils::StringContains( command, "west" ) ) { moved = m_location.Move( command ); if ( moved ) { m_movedLastTurn = true; } else { GIO::OutLine( "Cannot move " + command + "\n" ); m_movedLastTurn = false; } } return moved; } bool GameState::TryToExamine( const std::string& command ) { if ( Utils::StringContains( command, "examine" ) || Utils::StringContains( command, "look" ) ) { std::vector<std::string> examineCommands; examineCommands = Utils::SplitString( command, ' ' ); if ( examineCommands.size() == 1 ) { // EXAMINE ROOM m_location.DisplayLocationInfoBrief(); m_item.DisplayItemsOnMap( m_location.GetLocationRoomKey() ); m_people.DisplayPeopleOnMap( m_location.GetLocationRoomKey() ); } else { std::string examineWord; for ( unsigned int i = 1; i < examineCommands.size(); i++ ) { if ( i != 1 ) { examineWord += " "; } examineWord += examineCommands[i]; } if ( m_item.ItemExistsAndIsOnMap( examineWord, m_location.GetLocationRoomKey() ) && m_item.DisplayItemDescription( examineWord ) ) { // TODO: Clean up m_item.SetItemCollected( examineWord ); m_notebook.AddItemToNotebook( "item." + m_item.GetItemKey(examineWord), examineWord ); } else if ( m_people.PersonExistsAndIsOnMap( examineWord, m_location.GetLocationRoomKey() ) && m_people.DisplayPersonDescription( examineWord ) ) { m_notebook.AddItemToNotebook( "person." + m_item.GetItemKey(examineWord), examineWord ); } else { GIO::OutLine( "I looked for a \"" + examineWord + "\" but could not find any." ); } } return true; } return false; } bool GameState::TryToTalk( const std::string& command ) { std::vector<std::string> talkCommand; talkCommand = Utils::SplitString( command, ' ' ); if ( Utils::StringContains( command, "talk" ) && talkCommand.size() >= 1 ) { std::string talkTo; for ( unsigned int i = 1; i < talkCommand.size(); i++ ) { if ( i != 1 ) { talkTo += " "; } talkTo += talkCommand[i]; if ( m_people.StartDialogWith( talkTo, m_location.GetLocationRoomKey() ) ) { GIO::OutLine(); return true; } else { // TODO: If user knows about a person/item, say something different besides "it doesn't exist". GIO::OutLine( "I couldn't find a " + talkTo + "." ); return false; } } } return false; } bool GameState::TryNotebook( const std::string& command ) { if ( Utils::StringContains( command, "notebook" ) || Utils::StringContains( command, "note" ) ) { m_notebook.DisplayNotebookContents(); } return false; } void GameState::DisplayHelp() { GIO::ClearScreen(); GIO::DisplayHorizBar( "HELP" ); GIO::OutLine( "Welcome to K.C. Noire. Here is the help file." ); GIO::OutLine( "On most screens, you will see a header HUD. This displays available commands." ); GIO::OutLine( "To reiterate, the possible commands you can use are:" ); GIO::OutLine( "*\t NORTH, SOUTH, EAST, and WEST to move around\n\t when you're not in a car or talking to somebody." ); GIO::OutLine( "*\t EXAMINE to look at the entire room,\n\t or EXAMINE ITEMNAME to look at a person or item." ); GIO::OutLine( "*\t TALK PERSONNAME to talk to a person in the room with you" ); GIO::OutLine( "*\t NOTEBOOK to view the contents of your notebook.\n\t It holds a list of Locations, People, and Items." ); GIO::OutLine( "*\t QUIT will quit your game." ); GIO::DisplayHorizBar(); GIO::OutLine( "Press ENTER to continue" ); Utils::WaitForEnter(); GIO::ClearScreen(); GIO::DisplayHorizBar( "HELP" ); GIO::OutLine( "There are also a couple areas with a different command set.\nThis is the Dialog and Car areas." ); GIO::OutLine( "\nIn a car, you will see a numeric list of locations.\nTo move to a certain location, enter ONLY the number and hit ENTER." ); GIO::OutLine( "\nWhile talking to somebody, you will see a numeric list of notebook entries.\nTo talk about a certain item, enter ONLY the number and hit ENTER." ); GIO::OutLine( "\n" ); GIO::OutLine( "To play the game, walk around to different areas. Examine the items and people in each area." ); GIO::OutLine( "Talk to people about the evidence you've found. Your goal is to figure out" ); GIO::OutLine( "WHO killed Richardson, and WHY they did it." ); GIO::OutLine( "Once a character tells you about a new location, it will be accessible from the CAR." ); GIO::OutLine( "To get to the CAR, you need to walk there. For example," ); GIO::OutLine( "In Kenagy Park, the CAR is adjacent to the Parking Lot ROOM." ); GIO::DisplayHorizBar(); } void GameState::DisplayHud() { GIO::ClearScreen(); GIO::DisplayHorizBar( "COMMANDS" ); GIO::OutLine( "NORTH, SOUTH, EAST, WEST, EXAMINE [ITEM], TALK [PERSON], NOTEBOOK | QUIT" ); GIO::DisplayHorizBar(); m_location.DisplayLocationInfo(); m_item.DisplayItemsOnMap( m_location.GetLocationRoomKey() ); m_people.DisplayPeopleOnMap( m_location.GetLocationRoomKey() ); GIO::DisplayHorizBar(); }
#include <stdio.h> #include "gc_detect_leaks.h" int main() { GC_find_leak = 1; char *a; while(1){ a = (char*)malloc(100); //t1.c line7 //free(a); CHECK_LEAKS(); } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2000-2008 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Yngve Pettersen ** */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #include "core/pch.h" #if defined(_NATIVE_SSL_SUPPORT_) #include "modules/libssl/sslbase.h" // Modified from PEM_read_bio BOOL load_PEM_certificates2(SSL_varvector32 &data_source, SSL_varvector32 &pem_content) { pem_content.Resize(0); OpString8 sourcestring; if(OpStatus::IsError(sourcestring.Set((const char *)data_source.GetDirect(), data_source.GetLength()))) return FALSE; if(sourcestring.Length() == 0) return FALSE; int nohead=0; size_t line_len=0; const unsigned char *pemname = NULL; size_t pemname_len = 0; const unsigned char *source = (unsigned char *) sourcestring.CStr(); while(*source != '\0') { BOOL found = FALSE; for (;*source != '\0';) { line_len= op_strcspn((const char *)source, "\r\n"); if (op_strncmp((const char *)source,"-----BEGIN ",11) == 0) { if (op_strncmp((const char *)source+line_len-5 ,"-----",5) != 0) { source += line_len; if(*source == '\r') source++; if(*source == '\n') source++; continue; } pemname = source+11; pemname_len = line_len -11 -5; if((pemname_len == STRINGLENGTH("CERTIFICATE") && op_strncmp((const char *) pemname,"CERTIFICATE", pemname_len) == 0) || (pemname_len == STRINGLENGTH("X509 CERTIFICATE") && op_strncmp((const char *) pemname,"X509 CERTIFICATE", pemname_len)== 0) || (pemname_len == STRINGLENGTH("X509 CRL") && op_strncmp((const char *) pemname,"X509 CRL", pemname_len)== 0) || (pemname_len >= STRINGLENGTH("PKCS12") && op_strncmp((const char *) pemname,"PKCS12", 6) == 0)) found = TRUE; source += line_len; if(*source == '\r') source++; if(*source == '\n') source++; break; } source += line_len; if(*source == '\r') source++; if(*source == '\n') source++; } const unsigned char *content_start = source; for (;*source != '\0';) { line_len= op_strcspn((const char *) source, "\r\n"); if(line_len == 0) { source += line_len; if(*source == '\r') source++; if(*source == '\n') source++; break; } if (op_strncmp((const char *) source,"-----END ",9) == 0) { source += line_len; if(*source == '\r') source++; if(*source == '\n') source++; nohead = TRUE; break; } source += line_len; if(*source == '\r') source++; if(*source == '\n') source++; } line_len=0; if (found) { if(nohead) source = content_start; unsigned long content_len = 0; const unsigned char *src_content = source; while(*source != '\0') { line_len= op_strcspn((const char *) source, "\r\n"); if (op_strncmp((const char *) source,"-----END ",9) == 0) { break; } source += line_len; content_len += line_len; if(*source == '\r') { source++; content_len++; } if(*source == '\n') { source++; content_len++; } } if(*source) { // Always "-----END " if(line_len == 9+5+pemname_len && op_strncmp((const char *) source+9, (const char *) pemname, pemname_len) == 0 && op_strncmp((const char *) source+9+pemname_len, "-----",5) == 0) { unsigned long read_pos=0; BOOL warning = FALSE; pem_content.Resize((content_len/4)*3); if(!pem_content.Valid()) return FALSE; extern unsigned long GeneralDecodeBase64(const unsigned char *source, unsigned long len, unsigned long &read_pos, unsigned char *target, BOOL &warning, unsigned long max_write_len=0, unsigned char *decode_buf=NULL, unsigned int *decode_len=NULL); unsigned long decoded_len = GeneralDecodeBase64(src_content, content_len, read_pos, pem_content.GetDirect(), warning); OP_ASSERT(read_pos == content_len); pem_content.Resize(decoded_len); return TRUE; } } } // Previous line source += line_len; if(*source == '\r') source++; if(*source == '\n') source++; } return FALSE; } #endif
#ifndef CODE_GENERATOR #define CODE_GENERATOR #include "include.h" #include "utils.h" #include "opengl_function.h" class code_generator { public: void init(unordered_map<string, opengl_function>* functions, string& out_host, string& out_guest); void generate_code(); private: void generate_video_call_table_(); void generate_gl_table_header_(); void generate_gl_table_source_(); void generate_host_header_(int index); void generate_guest_header_(int index); void generate_host_source_(int index); void generate_guest_source_(int index); string sizeof_param_(opengl_function::param& p, bool is_host); string sizeof_array_(opengl_function::param& p); string get_type_(string type, int num_pointers); void print_autogenerated_info(ofstream& file); static const int QUEUE_SIZE; struct library_files { ofstream host_header; ofstream host_source; ofstream guest_header; ofstream guest_source; }; library_files library_[NUM_LIBRARIES]; ofstream video_call_table_; ofstream gl_table_header_; ofstream gl_table_source_; unordered_map<string, opengl_function>* functions_; string out_host_; string out_guest_; }; #endif // CODE_GENERATOR
#include "Term.h" istream& operator >>(istream& is, Term& x) { do { cout << "\n Nhap Ky han:"; is >> x.Kyhan; if (x.Kyhan < 1) { cout << "\n ky han khong hop le!"; } } while (x.Kyhan<1); // Goi nhap cua cha poiter Saving *cha = static_cast<Saving *>(&x);//ep kieu is >> *cha; return is; } ostream& operator <<(ostream& os, Term x) { //xuat cha Saving cha = static_cast<Saving >(x); os << "\n ky han:" << x.Kyhan; os << cha; return os; } double Term::TinhTienLai() { if (Kyhan >= ThangDaGui) { return TienGui*Laisuat / 100 * ThangDaGui; } return 0; } Term::Term() { } Term::~Term() { }
#include <bhand_test/utils.h> double err_thres = 1e-2; void PRINT_INFO_MSG(const std::string &msg) { std::cerr << "\033[1m\033[34m" << "[INFO]: " << msg << "\033[0m\n"; } void PRINT_ERR_MSG(const std::string &msg) { std::cerr << "\033[1m\033[31m" << "[ERROR]: " << msg << "\033[0m\n"; } void parseArgs(std::string &robot_descr_name, std::vector<std::string> &base_link, std::vector<std::vector<std::string>> &tool_link, std::vector<double> &ctrl_cycle, std::vector<arma::vec> &q1, std::vector<arma::vec> &q2, std::vector<double> &time_duration, std::vector<bool> &use_sim) { ros::NodeHandle nh("~"); if (!nh.getParam("robot_description_name",robot_descr_name)) throw std::ios_base::failure("Failed to read parameter \"robot_description_name\"."); int k = 0; try{ while (true) { std::string bl; std::vector<std::string> tl; double cc; std::vector<double> j1; std::vector<double> j2; double td; bool usim; std::ostringstream oss; oss << "_" << k+1; std::string suffix = oss.str(); if (!nh.getParam("base_link"+suffix,bl)) throw std::ios_base::failure("Failed to read parameter \"base_link" + suffix + "\"."); if (!nh.getParam("tool_link"+suffix,tl)) throw std::ios_base::failure("Failed to read parameter \"tool_link" + suffix + "\"."); if (!nh.getParam("ctrl_cycle"+suffix,cc)) throw std::ios_base::failure("Failed to read parameter \"ctrl_cycle" + suffix + "\"."); if (!nh.getParam("q1"+suffix,j1)) throw std::ios_base::failure("Failed to read parameter \"q1" + suffix + "\"."); if (!nh.getParam("q2"+suffix,j2)) throw std::ios_base::failure("Failed to read parameter \"q2" + suffix + "\"."); if (!nh.getParam("time_duration"+suffix,td)) throw std::ios_base::failure("Failed to read parameter \"time_duration" + suffix + "\"."); if (!nh.getParam("use_sim"+suffix,usim)) throw std::ios_base::failure("Failed to read parameter \"use_sim" + suffix + "\"."); base_link.push_back(bl); tool_link.push_back(tl); ctrl_cycle.push_back(cc); q1.push_back(j1); q2.push_back(j2); time_duration.push_back(td); use_sim.push_back(usim); k++; } } catch(std::exception &e) { if (k==0) { std::cerr << "[ERROR]: " << e.what() << "\n"; exit(-1); } } } void jointsTrajectory(const arma::vec &qT, double total_time, bhand_::RobotHand *robot) { // ====================================================== // =========== Set Joints trajectory ================= // ====================================================== std::cerr << "=====================================\n"; PRINT_INFO_MSG("==> Moving with Joints Trajectory..."); bool reached_target = robot->setJointsTrajectory(qT, total_time); if (reached_target) PRINT_INFO_MSG("==> Reached target pose!"); else PRINT_ERR_MSG("==> Failed to reach target pose!\n"); if (!robot->isOk()) { PRINT_ERR_MSG("==> " + robot->getErrMsg()); robot->enable(); } std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } void jointPositionControl(const arma::vec &qT, double total_time, bhand_::RobotHand *robot) { // ====================================================== // =========== Joint Position Control ================ // ====================================================== std::cerr << "=====================================\n"; PRINT_INFO_MSG("==> Setting the robot to JOINT_POS_CONTROL..."); robot->setMode(bhand_::JOINT_POS_CONTROL); PRINT_INFO_MSG("==> Moving with joint position control..."); robot->update(); double Ts = robot->getCtrlCycle(); arma::vec q = robot->getJointsPosition(); arma::vec q0 = q; double t = 0; while (arma::norm(qT-q)>err_thres && robot->isOk()) { if (!ros::ok()) exit(-1); t += Ts; arma::vec q_ref = bhand_::get5thOrder(t, q0, qT, total_time)[0]; robot->setJointsPosition(q_ref); robot->update(); q = robot->getJointsPosition(); } if (!robot->isOk()) { PRINT_ERR_MSG("[ERROR]: " + robot->getErrMsg()); robot->enable(); } else PRINT_INFO_MSG("==> Reached target pose!"); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } void jointVelocityControl(const arma::vec &qT, double total_time, bhand_::RobotHand *robot) { // ====================================================== // =========== Joint Velocity Control ================ // ====================================================== std::cerr << "=====================================\n"; PRINT_INFO_MSG("==> Setting the robot to JOINT_VEL_CONTROL..."); robot->setMode(bhand_::JOINT_VEL_CONTROL); PRINT_INFO_MSG("==> Moving with joint velocity control..."); robot->update(); double Ts = robot->getCtrlCycle(); arma::vec q = robot->getJointsPosition(); arma::vec q0 = q; double k_click = 0.1; double t = 0; while (arma::norm(qT-q)>err_thres && robot->isOk()) { if (!ros::ok()) exit(-1); t += Ts; arma::vec q_ref = bhand_::get5thOrder(t, q0, qT, total_time)[0]; arma::vec dq_ref = bhand_::get5thOrder(t, q0, qT, total_time)[1]; robot->setJointsVelocity(dq_ref + k_click*(q_ref-q)); robot->update(); q = robot->getJointsPosition(); } if (!robot->isOk()) { PRINT_ERR_MSG("[ERROR]: " + robot->getErrMsg()); robot->enable(); } else PRINT_INFO_MSG("==> Reached target pose!"); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } void freedrive(bhand_::RobotHand *robot) { // ========================================= // =========== FREEDIRVE ================ // ========================================= std::cerr << "=====================================\n"; PRINT_INFO_MSG("==> Setting the robot to FREEDRIVE..."); robot->setMode(bhand_::FREEDRIVE); PRINT_INFO_MSG("==> The robot is in FREEDIRVE. Move it wherever you want. Press ctrl+C to exit..."); while (ros::ok() && robot->isOk()) { robot->update(); } if (!robot->isOk()) { PRINT_INFO_MSG("[ERROR]: " + robot->getErrMsg()); robot->enable(); } } void robotRun(ExecArgs *args) { arma::vec q1 = args->q1; arma::vec q2 = args->q2; double time_duration = args->total_time; bhand_::RobotHand *bhand_robot = args->robot; // =========== Set Joints trajectory ================= jointsTrajectory(q1, time_duration, bhand_robot); // =========== Joint Position Control ================ jointPositionControl(q2, time_duration, bhand_robot); // =========== Joint Velocity Control ================ jointVelocityControl(q1, time_duration, bhand_robot); // =========== FREEDIRVE ================ // sync all robots before stop publishing... // if (use_sim) jState_pub.stop(); // stop publishing in freedrive when using SimRobot freedrive(bhand_robot); }
#include <iostream> #include <vector> using namespace std; class Solution { public: vector<vector<int>> permute(vector<int>& nums) { vector<vector<int>> curs(1, {nums[nums.size() - 1]}); for(int i = nums.size() - 2; i >= 0; i--){ vector<vector<int>> prevs = curs; curs.clear(); for(int j = 0; j < prevs.size(); j++){ for(int k = 0; k <= prevs[0].size(); k++){ vector<int> prev = prevs[j]; prev.emplace(prev.begin() + k, nums[i]); curs.push_back(prev); } } } return curs; } }; int main(void){ vector<int> nums = {1, 2, 3}; Solution sol; vector<vector<int>> res = sol.permute(nums); for(vector<int>& resNums: res){ for(int num: resNums){ cout << num << " "; } cout << endl; } return 0; }
#include "AttackEnemyInfo.h" #include "game_scene/GameScene.h" static int AttackEnemyInfoCount = 0; AttackEnemyInfo::AttackEnemyInfo() :m_bloodPro(NULL) ,m_level(NULL) ,m_nickName(NULL) ,m_widget(NULL) { log("AttackEnemyInfo:%d",AttackEnemyInfoCount++); } AttackEnemyInfo::~AttackEnemyInfo() { log("AttackEnemyInfo:%d",AttackEnemyInfoCount--); } bool AttackEnemyInfo::init() { if (!Layer::init()) { return false; } m_widget = dynamic_cast<Layout*>(GUIReader::getInstance()->widgetFromJsonFile("ui/enemyInfo/enemyInfo.json")); if (m_widget) { this->addChild(m_widget); } Vector<Node*> v1 = m_widget->getChildren(); m_nickName = dynamic_cast<Text*>(v1.at(1));//static_cast<Text*>(root->getChildByName("Label_EnemyName")); if (m_nickName) { //string str = ToUTF8::getInstance()->WStrToUTF8(L"暂无信息"); m_nickName->setString("暂无信息"); log("AttackEnemyInfo::init()="); } m_level = dynamic_cast<TextAtlas*>(v1.at(0));//(m_widget->getChildByName("enemy_Level")); if (m_level) { // m_level->setStringValue("100"); m_level->setString("100"); } m_bloodPro = dynamic_cast<LoadingBar*>(v1.at(2));//(root->getChildByName("LoadingBar_blood")); if (m_bloodPro) { } return true; } void AttackEnemyInfo::updateAttackInfo(float delay) { if (GAME_SCENE->getSelected() == NULL) return; if (m_bloodPro) { int progress = 100*GAME_SCENE->getSelected()->getBlood()/GAME_SCENE->getSelected()->getBloodCap(); if (progress < 0) progress = 0; m_bloodPro->setPercent(progress); } } void AttackEnemyInfo::showAttackInfo(Monomer* sender) { if (GAME_SCENE->getSelected() == NULL) return; if (!this->isVisible()) { this->setVisible(true); m_widget->setTouchEnabled(true); } this->schedule(schedule_selector(AttackEnemyInfo::updateAttackInfo)); } void AttackEnemyInfo::hide() { this->unschedule(schedule_selector(AttackEnemyInfo::updateAttackInfo)); this->setVisible(false); m_widget->setTouchEnabled(false); }
#include "Application.h" #include "SHARPENER_KNIFE.h" #include "ModuleParticles.h" #include "ModuleCollision.h" #include "ModuleEnemies.h" #include "ModuleRender.h" #include "ModuleKatana.h" #include "ModuleAyin.h" #include "ModuleSceneTemple.h" #include "ModuleInterface.h" #include "SDL\include\SDL_timer.h" SHARPENER_KNIFE::SHARPENER_KNIFE(int x, int y, int type) : Enemy(x, y, type) { //IDLE idle.PushBack({ 1092, 534, 87, 72 }); idle.PushBack({ 1016, 534, 76, 72 }); idle.PushBack({ 931, 534, 85, 73 }); idle.PushBack({ 851, 534, 80, 73 }); idle.PushBack({ 767, 534, 83, 73 }); idle.PushBack({ 685, 534, 81, 72 }); idle.speed = 0.15f; //GO SHOOT shoot.PushBack({ 891, 610, 96, 71 }); shoot.PushBack({ 793, 610, 98, 74 }); shoot.PushBack({ 691, 610, 101, 71 }); shoot.speed = 0.1f; //RETURN SHOOT return_shoot.PushBack({ 691, 610, 101, 71 }); return_shoot.PushBack({ 793, 610, 98, 74 }); return_shoot.PushBack({ 891, 610, 96, 71 }); return_shoot.speed = 0.1f; //START SPIN spin.PushBack({ 1122, 705, 44, 85 }); spin.PushBack({ 996, 610, 48, 87 }); spin.PushBack({ 1047, 610, 76, 88 }); spin.PushBack({ 688, 701, 106, 87 }); spin.PushBack({ 798, 700, 107, 88 }); spin.PushBack({ 1009, 702, 106, 89 }); spin.PushBack({ 911, 700, 93, 88 }); spin.PushBack({ 688, 701, 106, 87 }); spin.PushBack({ 798, 700, 107, 88 }); spin.PushBack({ 1009, 702, 106, 89 }); spin.PushBack({ 911, 700, 93, 88 }); spin.PushBack({ 688, 701, 106, 87 }); spin.PushBack({ 798, 700, 107, 88 }); spin.PushBack({ 1009, 702, 106, 89 }); spin.PushBack({ 911, 700, 93, 88 }); spin.PushBack({ 688, 701, 106, 87 }); spin.PushBack({ 798, 700, 107, 88 }); spin.PushBack({ 1009, 702, 106, 89 }); spin.PushBack({ 911, 700, 93, 88 }); spin.PushBack({ 688, 701, 106, 87 }); spin.PushBack({ 798, 700, 107, 88 }); spin.PushBack({ 1009, 702, 106, 89 }); spin.PushBack({ 911, 700, 93, 88 }); spin.PushBack({ 688, 701, 106, 87 }); spin.PushBack({ 798, 700, 107, 88 }); spin.PushBack({ 1009, 702, 106, 89 }); spin.PushBack({ 911, 700, 93, 88 }); spin.PushBack({ 1047, 610, 76, 88 }); spin.PushBack({ 996, 610, 48, 87 }); spin.PushBack({ 1122, 705, 44, 85 }); spin.speed = 0.2f; spin.loop = false; //SPIN FORWARD spin_forward.PushBack({ 1122, 705, 44, 85 }); spin_forward.PushBack({ 996, 610, 48, 87 }); spin_forward.PushBack({ 1047, 610, 76, 88 }); spin_forward.PushBack({ 688, 701, 106, 87 }); spin_forward.PushBack({ 798, 700, 107, 88 }); spin_forward.PushBack({ 1009, 702, 106, 89 }); spin_forward.PushBack({ 911, 700, 93, 88 }); spin_forward.PushBack({ 688, 701, 106, 87 }); spin_forward.PushBack({ 798, 700, 107, 88 }); spin_forward.PushBack({ 1009, 702, 106, 89 }); spin_forward.PushBack({ 911, 700, 93, 88 }); spin_forward.PushBack({ 688, 701, 106, 87 }); spin_forward.PushBack({ 798, 700, 107, 88 }); spin_forward.PushBack({ 1009, 702, 106, 89 }); spin_forward.PushBack({ 911, 700, 93, 88 }); spin_forward.PushBack({ 688, 701, 106, 87 }); spin_forward.PushBack({ 798, 700, 107, 88 }); spin_forward.PushBack({ 1009, 702, 106, 89 }); spin_forward.PushBack({ 911, 700, 93, 88 }); spin_forward.PushBack({ 688, 701, 106, 87 }); spin_forward.PushBack({ 798, 700, 107, 88 }); spin_forward.PushBack({ 1009, 702, 106, 89 }); spin_forward.PushBack({ 911, 700, 93, 88 }); spin_forward.PushBack({ 688, 701, 106, 87 }); spin_forward.PushBack({ 798, 700, 107, 88 }); spin_forward.PushBack({ 1009, 702, 106, 89 }); spin_forward.PushBack({ 911, 700, 93, 88 }); spin_forward.speed = 0.3f; //SPIN BACKWARD spin_backward.PushBack({ 688, 701, 106, 87 }); spin_backward.PushBack({ 798, 700, 107, 88 }); spin_backward.PushBack({ 1009, 702, 106, 89 }); spin_backward.PushBack({ 911, 700, 93, 88 }); spin_backward.PushBack({ 688, 701, 106, 87 }); spin_backward.PushBack({ 798, 700, 107, 88 }); spin_backward.PushBack({ 1009, 702, 106, 89 }); spin_backward.PushBack({ 911, 700, 93, 88 }); spin_backward.PushBack({ 688, 701, 106, 87 }); spin_backward.PushBack({ 798, 700, 107, 88 }); spin_backward.PushBack({ 1009, 702, 106, 89 }); spin_backward.PushBack({ 911, 700, 93, 88 }); spin_backward.PushBack({ 688, 701, 106, 87 }); spin_backward.PushBack({ 798, 700, 107, 88 }); spin_backward.PushBack({ 1009, 702, 106, 89 }); spin_backward.PushBack({ 911, 700, 93, 88 }); spin_backward.PushBack({ 688, 701, 106, 87 }); spin_backward.PushBack({ 798, 700, 107, 88 }); spin_backward.PushBack({ 1009, 702, 106, 89 }); spin_backward.PushBack({ 911, 700, 93, 88 }); spin_backward.PushBack({ 688, 701, 106, 87 }); spin_backward.PushBack({ 798, 700, 107, 88 }); spin_backward.PushBack({ 1009, 702, 106, 89 }); spin_backward.PushBack({ 911, 700, 93, 88 }); spin_backward.PushBack({ 1047, 610, 76, 88 }); spin_backward.PushBack({ 996, 610, 48, 87 }); spin_backward.PushBack({ 1122, 705, 44, 85 }); spin_backward.speed = 0.3f; animation = &spin; //sharpener_state state = SPAWN_SHARPENER; collider = App->collision->AddCollider({ 0, 0, 80, 70 }, COLLIDER_TYPE::COLLIDER_ENEMY_SHARPENER_KNIFE, (Module*)App->enemies); original_pos_x = x; original_pos_y = y; } void SHARPENER_KNIFE::Move() { if (App->inter->enemies_movement) { CheckState(); PerformActions(); //position.x -= 1; /*if (spin.Finished()) { animation = &idle; } else if (animation == &idle) { position.x += 1; }*/ /*position = original_pos + path.GetCurrentPosition(&animation);*/ /*void CheckState(); void PerformActions(); */ //shootTimer++; //if (shootTimer == 100) { // if (App->katana->position.x < position.x && App->katana->position.y < position.y) // { // App->particles->AddParticle(App->particles->enemy_bullet, position.x, position.y + 10, COLLIDER_ENEMY_SHOT); // } // else if (App->katana->position.x < position.x && App->katana->position.y > position.y) { // App->particles->AddParticle(App->particles->enemy_bullet, position.x, position.y + 10, COLLIDER_ENEMY_SHOT); // } // else if (App->katana->position.x > position.x && App->katana->position.y < position.y) { // App->particles->AddParticle(App->particles->enemy_bullet, position.x, position.y + 10, COLLIDER_ENEMY_SHOT); // } // else if (App->katana->position.x > position.x && App->katana->position.y > position.y) { // App->particles->AddParticle(App->particles->enemy_bullet, position.x, position.y + 10, COLLIDER_ENEMY_SHOT); // } // //shootTimer = 0; //} } } void SHARPENER_KNIFE::CheckState() { switch (state) { case SPAWN_SHARPENER: position.x += int(App->scene_temple->speed); if (spin.Finished()) { spin.Reset(); state = GO_BACKWARD_SHARPENER; } break; case GO_BACKWARD_SHARPENER: position.x += 2; if(position.x >= App->render->camera.x + (App->render->camera.w) - 101){ state = SHOOT_SHARPENER; } break; case SHOOT_SHARPENER: position.x += int(App->scene_temple->speed); if (shoot.Finished()) { shoot.Reset(); Shoot(); state = RETURN_SHOOT_SHARPENER; } break; case RETURN_SHOOT_SHARPENER: position.x += int(App->scene_temple->speed); if (return_shoot.Finished()) { return_shoot.Reset(); state = IDLE_FORWARD; } break; case IDLE_FORWARD: if (position.x < App->render->camera.x + (App->render->camera.w) - 200) { position.x += int(App->scene_temple->speed); state = GO_SPIN_SHARPENER; App->particles->AddEmmiter(SHARPENER_BURST, &position); } break; case GO_SPIN_SHARPENER: if (going_forward) { if (position.x < App->render->camera.x +(App->render->camera.w)-200) { going_forward = false; } else { //position.x -= 1; } } else { if (position.x >= App->render->camera.x + (App->render->camera.w) - 101) { state = IDLE_SHARPENER; } else { position.x += 2; } } break; case IDLE_SHARPENER: position.x += int(App->scene_temple->speed); if (time_delay) { time_entry = SDL_GetTicks(); time_delay = false; } time_current = SDL_GetTicks() - time_entry; if (time_current > 1500) { if (active_shoot) { state = FAREWELL_SHARPENER; time_entry = SDL_GetTicks(); } else { state = FULL_SHOOT_SHARPENER; time_entry = SDL_GetTicks(); } } break; case FULL_SHOOT_SHARPENER: position.x += int(App->scene_temple->speed); active_shoot = true; if (shoot.Finished()) { shoot.Reset(); Shoot(); //App->particles->AddParticle(App->particles->sharpener_bullet, position.x, position.y - 30, COLLIDER_ENEMY_SHOT); state = IDLE_SHARPENER; } break; case FAREWELL_SHARPENER: position.x += 2; position.y -= 2; break; } } void SHARPENER_KNIFE::PerformActions() { switch (state) { case SPAWN_SHARPENER: animation = &spin; break; case GO_BACKWARD_SHARPENER: animation = &idle; break; case SHOOT_SHARPENER: animation = &shoot; break; case RETURN_SHOOT_SHARPENER: animation = &return_shoot; break; case IDLE_FORWARD: animation = &idle; break; case GO_SPIN_SHARPENER: animation = &spin; if (spin.Finished()) { //spin.Reset(); animation = &idle; } break; case IDLE_SHARPENER: animation = &idle; break; case FULL_SHOOT_SHARPENER: animation = &shoot; break; case FAREWELL_SHARPENER: animation = &idle; break; } } void SHARPENER_KNIFE::Shoot() { for (int i = 0; i < ammo; i++) { Particle* p = new Particle(App->particles->enemy_bullet); p->born = SDL_GetTicks(); p->position.x = int(position.x) + i * 6; p->position.y = int(position.y) + i * 2; p->speed.x = (App->katana->position.x - p->position.x) / 60.f; p->speed.y = (App->katana->position.y - p->position.y) / 60.f; p->collider = App->collision->AddCollider(p->anim.GetCurrentFrame(), COLLIDER_ENEMY_SHOT, App->particles); App->particles->AddParticle(p); } }
#include"Vec2.hpp" #include<iostream> namespace GPEngine { namespace GPMath { Vec2::Vec2() : x(0.0f), y(0.0f) { } Vec2::Vec2(float _x,float _y) : x(_x),y(_y) { } Vec2::Vec2(float scalar) : x(scalar), y(scalar) { } Vec2::~Vec2() { } Vec2::Vec2(const Vec2 &other) :x(other.x),y(other.y) { } Vec2& Vec2::operator = (const Vec2 &other) { if(this==&other) return *this; this->x = other.x; this->y = other.y; return *this; } Vec2 Vec2::operator + (const Vec2 &other) const { return Vec2(x + other.x , y + other.y); } Vec2 Vec2::operator - (const Vec2 &other)const { return Vec2(x - other.x , y - other.y); } Vec2 Vec2::normalize()const { float len = length(); return Vec2(x/len , y/len); } float Vec2::length() const { return sqrt(x*x + y*y); } float Vec2::dot(const Vec2 &other)const { return (x*other.x + y*other.y); } } }
#include <vector> #include <iostream> #include <utility> #include <string> #include <algorithm> #include "Верхний колонтитул.h" #include <fstream> #include <set> #include <string> using namespace std; template <typename T> set<vector<T>> CreateSets(const vector<T>& sets) { set<vector<T>> result; for (int i = 0; i < sets.size(); i++) { vector<T> vect(sets.size()); fill(vect.begin(), vect.end(), sets[i]); for (int j = 0; j < sets.size(); j++) { for (int k = 0; k < sets.size(); k++) { if (j == 0 && k == 0) result.insert(vect); vect[i] = sets[k]; sort(vect.begin(), vect.end()); result.insert(vect); vect[j] = sets[k]; sort(vect.begin(), vect.end()); result.insert(vect); } } } return result; } int main() { vector<string> sets; ifstream in("tests.txt"); if (in) { string line; while (getline(in, line)) { sets = tiit::modify(line); cout << "Vhodnoe mnojestvo = {" << line << "}" << endl; for (const auto& set_ : CreateSets(sets)) { tiit::PrintVector(set_); cout << endl; } cout << endl << endl; } } system("pause"); return 0; }
//https://projecteuler.net/problem=7 //Solution: 104743 #include <iostream> #include <math.h> using namespace std; bool isPrime(int n) { if (n < 2) return 0; for (int i = 2; i <= sqrt(n); i++) { if (n % i == 0) return 0; } return 1; } int findNthPrime(int n) { int prime = 1; int i = 2; while (prime <= n) { if (isPrime(i)) prime++; i++; } return --i; } int main() { cout << findNthPrime(10001); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2005 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef SVG_MATRIX_H #define SVG_MATRIX_H #include "modules/svg/svg_number.h" #include "modules/svg/src/SVGRect.h" #include "modules/svg/src/SVGObject.h" #include "modules/svg/src/SVGNumberPair.h" class SVGBoundingBox; class VEGATransform; #define SVG_MATRIX_IDENTITY_CHECKS /** * The SVGMatrix class describes an affine transformation matrix. * The matrix is 3x3 and looks like: * [a c e] * [b d f] * [0 0 1] * * The values of [a b c d e f] are stored in this class. */ class SVGMatrix { public: SVGMatrix() { LoadIdentity(); } /** * Set this transform to the identity transform, [1 0 0 0 1 0] */ void LoadIdentity(); /** * Set this transform to translate to (x,y), [1 0 x 0 1 y] * @param x The x coordinate to translate to * @param y The y coordinate to translate to */ void LoadTranslation(SVGNumber x, SVGNumber y); /** * Set this transform to scale, scale can be different for the x- and y-axis. * @param x Scale for the x-axis * @param y Scale for the y-axis */ void LoadScale(SVGNumber x, SVGNumber y); /** * Set this transform to rotate by deg degrees * @param deg Degrees */ void LoadRotation(SVGNumber deg); /** * Set this transform to rotate by deg degrees around the point (x, y) * @param deg Degrees */ void LoadRotation(SVGNumber deg, SVGNumber x, SVGNumber y); /** * Set this transform to skew the x-axis by deg degrees. * @param deg Degrees */ void LoadSkewX(SVGNumber deg); /** * Set this transform to skew the y-axis by deg degrees. * @param deg Degrees */ void LoadSkewY(SVGNumber deg); /** * Multiply by the translation matrix T(tx,ty). * * Same as: * SVGMatrix m; * m.LoadTranslation(tx, ty); * this->Multiply(&m); */ void MultTranslation(SVGNumber tx, SVGNumber ty) { // B = T(tx,ty) [1 0 0 1 tx ty] // A = this // A = B*A values[4] += tx; values[5] += ty; } /** * Multiply by the scaling matrix S(x,y). * * Same as: * SVGMatrix m; * m.LoadScale(x, y); * this->Multiply(&m); */ void MultScale(SVGNumber x, SVGNumber y); /** * Multiplicate this matrix with another from the left. * this = A * other = B * A = BA */ void Multiply(const SVGMatrix& other); /** * Post-Multiply by the translation matrix T(x,y). * * Same as: * SVGMatrix m; * m.LoadTranslation(x, y); * this->PostMultiply(&m); */ void PostMultTranslation(SVGNumber x, SVGNumber y); /** * Post-Multiply by the scaling matrix S(x,y). * * Same as: * SVGMatrix m; * m.LoadScale(x, y); * this->PostMultiply(&m); */ void PostMultScale(SVGNumber x, SVGNumber y); /** * Multiplicate this matrix with another from the right. * this = A * other = B * A = AB */ void PostMultiply(const SVGMatrix &other); void SetValues(const SVGNumber a, const SVGNumber b, const SVGNumber c, const SVGNumber d, const SVGNumber e, const SVGNumber f); /** * Copy another matrix */ void Copy(const SVGMatrix& matrix); /** * Copy to a VEGATransform */ void CopyToVEGATransform(VEGATransform& vega_xfrm) const; SVGNumber operator[](int idx) const { OP_ASSERT(idx >= 0 && idx < 6); return values[idx]; } SVGNumber& operator[](int idx) { OP_ASSERT(idx >= 0 && idx < 6); return values[idx]; } /** * Apply the transform to a coordinate. * @param c The coordinate to transform (most often in user space) * @return The transformed coordinate (most often in viewport space) */ SVGNumberPair ApplyToCoordinate(const SVGNumberPair& c) const; /** * Apply the transform to a coordinate. * @param x The x coordinate to transform (most often in user space) * @param y The y coordinate to transform (most often in user space) * @return The transformed coordinate (most often in viewport space) */ SVGNumberPair ApplyToCoordinate(SVGNumber x, SVGNumber y) const { return ApplyToCoordinate(SVGNumberPair(x,y)); } void ApplyToCoordinate(SVGNumber* x, SVGNumber* y) const { SVGNumberPair t = ApplyToCoordinate(SVGNumberPair(*x,*y)); *x = t.x; *y = t.y; } /** * Applies the transform to the boundingbox and returns the new boundingbox. * This method doesn't check if the boundingbox is empty, that's the responsibility * of the caller. * @param bbox The boundingbox (in user space) * @return The transformed boundingbox */ SVGBoundingBox ApplyToNonEmptyBoundingBox(const SVGBoundingBox& bbox) const; /** * Applies the transform to the boundingbox and returns the new boundingbox. * @param bbox The boundingbox (in user space) * @return The transformed boundingbox */ SVGBoundingBox ApplyToBoundingBox(const SVGBoundingBox& bbox) const { if (bbox.IsEmpty()) return bbox; else return ApplyToNonEmptyBoundingBox(bbox); } /** * Applies the transform to the rectangle and returns the new rectangle. * @param rect The rectangle (in user space) * @return The transformed rect */ SVGRect ApplyToRect(const SVGRect& rect) const; /** * Gets the expansion factor, i.e. the square root of the factor * by which the affine transform affects area. In an affine transform * composed of scaling, rotation, shearing, and translation, returns * the amount of scaling. * * This is useful for setting linewidths for stroke operations since * some implementations scale the linewidth value according to the currently * used transformation matrix. * * @return the expansion factor. */ SVGNumber GetExpansionFactor() const; /** * Gets the expansion factor squared. * * @return the expansion factor^2 */ SVGNumber GetExpansionFactorSquared() const; BOOL operator==(const SVGMatrix& other) const; /** * Invert the matrix. * * @return TRUE if the matrix was invertable, otherwise FALSE (leaves the matrix unmodified) */ BOOL Invert(); BOOL IsIdentity() const; /** * Checks if the transform is a rotation n*(pi/2), has x/y-scale = 1 * and if any translation can be represented by integers. */ BOOL IsAlignedAndNonscaled() const; /** * Check if the transform is a translation and (positive) scale */ BOOL IsScaledTranslation() const; private: // The values will be explicitly set in the constructor so // we want to avoid setting the values twice. struct UnintializedSVGNumber : public SVGNumber { UnintializedSVGNumber() : SVGNumber(SVGNumber::UNINITIALIZED_SVGNUMBER) {} void operator=(int value) { SVGNumber::operator=(value); } void operator=(SVGNumber value) { SVGNumber::operator=(value); } }; UnintializedSVGNumber values[6]; }; class SVGMatrixObject : public SVGObject { public: SVGMatrixObject() : SVGObject(SVGOBJECT_MATRIX) {} virtual SVGObject *Clone() const; virtual OP_STATUS LowLevelGetStringRepresentation(TempBuffer* buffer) const { OP_ASSERT(0); return OpStatus::ERR; } virtual BOOL IsEqual(const SVGObject& other) const; virtual BOOL InitializeAnimationValue(SVGAnimationValue &animation_value); SVGMatrix matrix; }; #endif // SVG_MATRIX_H
// BEGIN CUT HERE // PROBLEM STATEMENT // // You are given an int N. The factorial of N is defined as // N*(N-1)*(N-2)*...*1. Compute the factorial of N and // remove all of its rightmost zero digits. If the result is // more than K digits long, return the last K digits as a // string. Otherwise, return the entire result as a string. // // // DEFINITION // Class:KLastNonZeroDigits // Method:getKDigits // Parameters:int, int // Returns:string // Method signature:string getKDigits(int N, int K) // // // CONSTRAINTS // -N will be between 1 and 20, inclusive. // -K will be between 1 and 9, inclusive. // // // EXAMPLES // // 0) // 10 // 3 // // Returns: "288" // // You would first compute the factorial of 10, which is // 10*9*8*7*6*5*4*3*2*1=3628800. You would then remove all // rightmost zeros to get 36288. Finally, you would return // the last 3 digits as a string: "288". // // 1) // 6 // 1 // // Returns: "2" // // The factorial of 6 is 720. // // 2) // 6 // 3 // // Returns: "72" // // // // 3) // 7 // 2 // // Returns: "04" // // The factorial of 7 is 5040. We remove the last zero to get // "504". The last 2 digits of "504" are "04". // // 4) // 20 // 9 // // Returns: "200817664" // // // // 5) // 1 // 1 // // Returns: "1" // // // // END CUT HERE #line 80 "KLastNonZeroDigits.cpp" #include <string> #include <vector> #include <iostream> #include <sstream> #include <algorithm> #include <numeric> #include <functional> #include <map> #include <set> #include <cassert> #include <list> #include <deque> #include <iomanip> #include <cstring> #include <cmath> #include <cstdio> #include <cctype> using namespace std; #define fi(n) for(int i=0;i<(n);i++) #define fj(n) for(int j=0;j<(n);j++) #define f(i,a,b) for(int (i)=(a);(i)<(b);(i)++) typedef vector <int> VI; typedef vector <string> VS; typedef vector <VI> VVI; void mul(int *buf, int *len, int n ) { int c = 0; fi(*len){ int t = (buf[i] * n + c); buf[i] = t % 10; c = t / 10; } while (c) { buf[*len] = c % 10; c /= 10; *len = *len + 1; } } class KLastNonZeroDigits { public: string getKDigits(int N, int K) { int ans[1000]; memset(ans, 0, sizeof(ans)); ans[0] = 1; int len = 1; int c = 0; f(i,1,N+1) { mul(ans, &len, i); } int st = 0; fi(len) { if (ans[i] != 0) break; st++; } int lim = min(st + K, len); reverse(ans + st, ans + lim); string ret; f(i,st,lim) ret += ans[i] + '0'; return ret; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arg0 = 10; int Arg1 = 3; string Arg2 = "288"; verify_case(0, Arg2, getKDigits(Arg0, Arg1)); } void test_case_1() { int Arg0 = 6; int Arg1 = 1; string Arg2 = "2"; verify_case(1, Arg2, getKDigits(Arg0, Arg1)); } void test_case_2() { int Arg0 = 6; int Arg1 = 3; string Arg2 = "72"; verify_case(2, Arg2, getKDigits(Arg0, Arg1)); } void test_case_3() { int Arg0 = 7; int Arg1 = 2; string Arg2 = "04"; verify_case(3, Arg2, getKDigits(Arg0, Arg1)); } void test_case_4() { int Arg0 = 20; int Arg1 = 9; string Arg2 = "200817664"; verify_case(4, Arg2, getKDigits(Arg0, Arg1)); } void test_case_5() { int Arg0 = 1; int Arg1 = 1; string Arg2 = "1"; verify_case(5, Arg2, getKDigits(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { KLastNonZeroDigits ___test; ___test.run_test(-1); } // END CUT HERE
//: C02:Numconv.cpp // Kod zrodlowy pochodzacy z ksiazki // "Thinking in C++. Edycja polska" // (c) Bruce Eckel 2000 // Informacje o prawie autorskim znajduja sie w pliku Copyright.txt // Zamiana liczby dziesietnej na osemkowa i szesnastkowa #include <iostream> using namespace std; int main() { int number; cout << "Wprowadz liczbe dziesietna: "; cin >> number; cout << "wartosc w zapisie osemkowym = 0" << oct << number << endl; cout << "wartosc w zapisie szesnastkowym = 0x" << hex << number << endl; } ///:~
#pragma once #ifndef POSIZIONE_H #define POSIZIONE_H class Posizione { public: Posizione(); Posizione(double x, double y, double z); double getX(); double getY(); double getZ(); void setX(double x1); void setY(double y1); void setZ(double z1); private: double x; double y; double z; }; #endif
#pragma once #include <iberbar\Base\Lua\LuaBase.h> #include <iberbar\Base\Unknown.h> namespace iberbar { class CLuaStateRef : public CUnknown { IBERBAR_UNKNOWN_CLONE_DISABLED( CLuaStateRef ); public: CLuaStateRef( void ); ~CLuaStateRef(); inline lua_State* get() { return m_pLuaState; } void initial() { m_pLuaState = luaL_newstate(); luaL_openlibs( m_pLuaState ); } void destroy() { if ( m_pLuaState ) { lua_close( m_pLuaState ); m_pLuaState = NULL; } } private: lua_State * m_pLuaState; }; IBERBAR_UNKNOWN_PTR_DECLARE( CLuaStateRef ); }
// Nama : Naufal Dean Anugrah // NIM : 13518123 // Tanggal : 6 Februari 2020 // Topik : Inheritance #include <iostream> #include "Rekening.h" using namespace std; // Konstruktor untuk menginisialisasi saldo // Set saldo 0.0 apabila saldo bernilai negatif Rekening::Rekening(double saldo) { this->saldo = (saldo < 0.0) ? (0.0) : (saldo); } // Getter, Setter void Rekening::setSaldo(double saldo) { this->saldo = saldo; } double Rekening::getSaldo() const { return this->saldo; } // Member Function // Tambahkan sejumlah nominal uang ke saldo void Rekening::simpanUang(double deltaSaldo) { this->saldo += deltaSaldo; } // Kurangkan sejumlah nominal uang dari saldo apabila saldo mencukupi (tidak negatif setelah dikurangkan) // Kembalikan boolean yang mengindikasikan apakah uang berhasil ditarik atau tidak bool Rekening::tarikUang(double deltaSaldo) { if (this->saldo < deltaSaldo) { return false; } else { this->saldo -= deltaSaldo; return true; } }
#include <algorithm> #include <iostream> #include <vector> int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); int a; std::cin >> a; static int dp[1000001]; for (int i = 2; i <= a; ++i) { dp[i] = dp[i - 1] + 1; if (!(i % 2)) { dp[i] = std::min(dp[i], dp[i / 2] + 1); } if (!(i % 3)) { dp[i] = std::min(dp[i], dp[i / 3] + 1); } } std::cout << dp[a] << '\n'; return 0; }
#pragma once #include "global.h" #ifndef MAIN_H #define MAIN_H #include "game.h" enum class GameState {INTRO, INTROMENU, LOADSCREEN, PLAY, MENU, CREDIT, EXIT}; class GameObject { private: GameState _gameState; bool _gameStateLoaded; float _FPS; public: GameObject(); void Run(); void Init(); void Loop(); void DrawScreen(); void ProcessInput(); void GameStep(); SDL_Event event; Game game; }; #endif
#include "engine/net/CommonNet.hpp" void CommonNet::SendDataPosVelDeg(ENetPeer* peer, int x, int y, int velX, int velY, int deg){ char send_data[1024] = {'\0'}; sprintf(send_data, "0|%d|%d|%d|%d|%d", x, y, velX, velY, deg); SendPacket(peer, send_data); } void CommonNet::SendDataThrowablePosVel(ENetPeer* peer, int x, int y, int velX, int velY, double angle, int type){ char send_data[1024] = {'\0'}; sprintf(send_data, "2|%d|%d|%d|%d|%d|%f", x, y, velX, velY, type, angle); SendPacket(peer, send_data); } void CommonNet::SendHit(ENetPeer* peer, int damage, int currentRoundNum){ char send_data[1024] = {'\0'}; sprintf(send_data, "3|%d|%d", damage, currentRoundNum); SendPacket(peer, send_data); } void CommonNet::SendBombState(int state){ char send_data[1024] = {'\0'}; sprintf(send_data, "4|%d", state); SendPacket(peer, send_data); } void CommonNet::SendBombLocation(std::pair <int, int> location){ char send_data[1024] = {'\0'}; sprintf(send_data, "5|%d|%d", location.first, location.second); SendPacket(peer, send_data); } void CommonNet::SendPacket(ENetPeer* peer, const char* data) { // Create the packet using enet_packet_create and the data we want to send // We are using the flag ENET_PACKET_FLAG_RELIABLE that acts a bit like TCP. // That is to say, it'll make sure the packet makes it to the destination. ENetPacket* packet = enet_packet_create(data, strlen(data) + 1, ENET_PACKET_FLAG_RELIABLE); // Finally, send the packet to the peer on channel 0! enet_peer_send(peer, 0, packet); } int CommonNet::getPing(){ return peer->roundTripTime; } std::vector<int> CommonNet::Parsedata(char* data){ // std::cout<<data<<"\n"; int data_type; sscanf(data, "%d|", &data_type); switch(data_type){ case 0: { int x, y, velX, velY, deg; sscanf(data, "0|%d|%d|%d|%d|%d", &x, &y, &velX, &velY, &deg); return{0, x, y, velX, velY, deg}; } case 1: { char map_arr[1024]; int total_len; sscanf(data, "1|%d|%s", &total_len, map_arr); std::vector<int> ret_vec(total_len+1); ret_vec[0] = 1; for (int i=1; i<total_len+1; i++){ ret_vec[i] = (map_arr[i-1]=='1' ? 1:0); } return ret_vec; } case 2: { int x, y, velX, velY, type; double angle; sscanf(data, "2|%d|%d|%d|%d|%d|%lf", &x, &y, &velX, &velY, &type, &angle); return{2, x, y, velX, velY, type, (int)(angle*1e8)}; } case 3: { int damage, currRoundNum; sscanf(data, "3|%d|%d", &damage, &currRoundNum); return{3, damage, currRoundNum}; } case 4: { int state; sscanf(data, "4|%d", &state); return {4, state}; } case 5: { int x, y; sscanf(data, "5|%d|%d", &x, &y); return {5, x, y}; } case 6: { int x; sscanf(data, "6|%d", &x); return {6, x}; } case 7: { return {7}; } case 8: { return {8}; } case 9: { int x; sscanf(data, "9|%d", &x); return {9, x}; } default: return {}; } } bool CommonNet::isConnected(){ pthread_mutex_lock(&mutex); bool conn_val = connected; pthread_mutex_unlock(&mutex); return conn_val; } void CommonNet::setConnected(){ pthread_mutex_lock(&mutex); connected = true; pthread_mutex_unlock(&mutex); } void CommonNet::setNotConnected(){ pthread_mutex_lock(&mutex); connected = false; pthread_mutex_unlock(&mutex); }
#pragma once #if defined(__GNUC__) && defined(__GXX_EXPERIMENTAL_CXX0X__) #else #error "This file requires compiler support for c++11" #endif #include <cstddef> #include <chrono> template<typename Function, typename... Args> double time_invocation(std::size_t num_trials, Function &&f, Args&&... args) { auto start = std::chrono::high_resolution_clock::now(); for(std::size_t i = 0; i < num_trials; ++i) { f(std::forward<Args&&>(args)...); } auto end = std::chrono::high_resolution_clock::now(); // return mean duration in msecs return std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count(); }
// Copyright (c) 2011-2014 Bryce Adelstein-Lelbach // Copyright (c) 2007-2014 Hartmut Kaiser // Copyright (c) 2013-2014 Thomas Heller // Copyright (c) 2013-2014 Patricia Grubel // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <pika/barrier.hpp> #include <pika/functional/bind.hpp> #include <pika/init.hpp> #include <pika/thread.hpp> #include "htts2.hpp" #include <fmt/ostream.h> #include <fmt/printf.h> #include <atomic> #include <chrono> #include <cstdint> #include <functional> #include <iostream> #include <string> #include <vector> template <typename BaseClock = std::chrono::steady_clock> struct pika_driver : htts2::driver { pika_driver(int argc, char** argv) : htts2::driver(argc, argv, true) // , count_(0) { } void run() { std::vector<std::string> const cfg = {"pika.os_threads=" + std::to_string(osthreads_), "pika.run_pika_main!=0", "pika.commandline.allow_unknown!=1"}; pika::util::detail::function<int(pika::program_options::variables_map & vm)> f; pika::program_options::options_description desc; pika::init_params init_args; init_args.cfg = cfg; init_args.desc_cmdline = desc; using std::placeholders::_1; pika::init(std::function<int(pika::program_options::variables_map&)>( pika::util::detail::bind(&pika_driver::run_impl, std::ref(*this), _1)), argc_, argv_, init_args); } private: int run_impl(pika::program_options::variables_map&) { // Cold run //kernel(); // Hot run results_type results = kernel(); print_results(results); return pika::finalize(); } pika::threads::detail::thread_result_type payload_thread_function( pika::threads::detail::thread_restart_state = pika::threads::detail::thread_restart_state::signaled) { htts2::payload<BaseClock>(this->payload_duration_ /* = p */); //++count_; return pika::threads::detail::thread_result_type( pika::threads::detail::thread_schedule_state::terminated, pika::threads::detail::invalid_thread_id); } void stage_tasks(std::uint64_t target_osthread) { std::uint64_t const this_osthread = pika::get_worker_thread_num(); // This branch is very rarely taken (I've measured); this only occurs // if we are unlucky enough to be stolen from our intended queue. if (this_osthread != target_osthread) { // Reschedule in an attempt to correct. pika::threads::detail::thread_init_data data( pika::threads::detail::make_thread_function_nullary(pika::util::detail::bind( &pika_driver::stage_tasks, std::ref(*this), target_osthread)), nullptr // No pika-thread name. , pika::execution::thread_priority::normal // Place in the target OS-thread's queue. , pika::execution::thread_schedule_hint(target_osthread)); pika::threads::detail::register_work(data); } for (std::uint64_t i = 0; i < this->tasks_; ++i) { using std::placeholders::_1; pika::threads::detail::thread_init_data data( pika::util::detail::bind( &pika_driver::payload_thread_function, std::ref(*this), _1), nullptr // No pika-thread name. , pika::execution::thread_priority::normal // Place in the target OS-thread's queue. , pika::execution::thread_schedule_hint(target_osthread)); pika::threads::detail::register_work(data); } } void wait_for_tasks(pika::barrier<>& finished) { std::uint64_t const pending_count = pika::threads::get_thread_count(pika::execution::thread_priority::normal, pika::threads::detail::thread_schedule_state::pending); if (pending_count == 0) { std::uint64_t const all_count = pika::threads::get_thread_count(pika::execution::thread_priority::normal); if (all_count != 1) { pika::threads::detail::thread_init_data data( pika::threads::detail::make_thread_function_nullary(pika::util::detail::bind( &pika_driver::wait_for_tasks, std::ref(*this), std::ref(finished))), nullptr, pika::execution::thread_priority::low); register_work(data); return; } } finished.arrive_and_drop(); } using results_type = double; results_type kernel() { /////////////////////////////////////////////////////////////////////// //count_ = 0; results_type results; std::uint64_t const this_osthread = pika::get_worker_thread_num(); htts2::timer<BaseClock> t; /////////////////////////////////////////////////////////////////////// // Warmup Phase for (std::uint64_t i = 0; i < this->osthreads_; ++i) { if (this_osthread == i) continue; pika::threads::detail::thread_init_data data( pika::threads::detail::make_thread_function_nullary( pika::util::detail::bind(&pika_driver::stage_tasks, std::ref(*this), i)), nullptr // No pika-thread name. , pika::execution::thread_priority::normal // Place in the target OS-thread's queue. , pika::execution::thread_schedule_hint(i)); pika::threads::detail::register_work(data); } stage_tasks(this_osthread); /////////////////////////////////////////////////////////////////////// // Compute + Cooldown Phase // The use of an atomic and live waiting here does not add any noticeable // overhead, as compared to the more complicated continuation-style // detection method that checks the thread_manager internal counters // (I've measured). Using this technique is preferable as it is more // comparable to the other implementations (especially qthreads). // do { // pika::this_thread::suspend(); // } while (count_ < (this->tasks_ * this->osthreads_)); // Schedule a low-priority thread; when it is executed, it checks to // make sure all the tasks (which are normal priority) have been // executed, and then it pika::barrier<> finished(2); pika::threads::detail::thread_init_data data( pika::threads::detail::make_thread_function_nullary(pika::util::detail::bind( &pika_driver::wait_for_tasks, std::ref(*this), std::ref(finished))), nullptr, pika::execution::thread_priority::low); register_work(data); finished.arrive_and_wait(); // w_M [nanoseconds] results = static_cast<double>(t.elapsed()); return results; /////////////////////////////////////////////////////////////////////// } void print_results(results_type results) const { if (this->io_ == htts2::csv_with_headers) std::cout << "OS-threads (Independent Variable)," << "Tasks per OS-thread (Control Variable) [tasks/OS-threads]," << "Payload Duration (Control Variable) [nanoseconds]," << "Total Walltime [nanoseconds]" << "\n"; fmt::print(std::cout, "{},{},{},{:.14g}\n", this->osthreads_, this->tasks_, this->payload_duration_, results); } // std::atomic<std::uint64_t> count_; }; int main(int argc, char** argv) { pika_driver<> d(argc, argv); d.run(); return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2009 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #ifndef WEBSERVERPREFS_H #define WEBSERVERPREFS_H #ifdef WIDGET_RUNTIME_SUPPORT # ifdef WIDGET_RUNTIME_UNITE_SUPPORT #include "modules/util/opstring.h" #include "modules/webserver/webserver-api.h" class WebServerSettingsContext; /** * The "persistence" layer of a web server manager. * * @author Wojciech Dzierzanowski (wdzierzanowski) */ class WebServerPrefs { public: static OP_STATUS WriteIsStarted(BOOL started); static BOOL ReadIsConfigured(); static OP_STATUS WriteIsConfigured(BOOL configured); static OP_STATUS WriteUsername(const OpStringC& username); static OpStringC ReadDeviceName(); static OP_STATUS WriteDeviceName(const OpStringC& device_name); static OP_STATUS ReadSharedSecret(OpString8& shared_secret); static OP_STATUS WriteSharedSecret(const OpStringC& shared_secret); static WebserverListeningMode ReadListeningMode(); #ifdef PREFS_CAP_UPNP_ENABLED static BOOL ReadIsUPnPEnabled(); static OP_STATUS WriteIsUPnPEnabled(BOOL enabled); #endif // PREFS_CAP_UPNP_ENABLED static int ReadMaxUploadRate(); static OP_STATUS WriteMaxUploadRate(int rate); static OP_STATUS ReadAll(WebServerSettingsContext& settings); static OP_STATUS WriteAll(const WebServerSettingsContext& settings); }; # endif // WIDGET_RUNTIME_UNITE_SUPPORT #endif // WIDGET_RUNTIME_SUPPORT #endif // WEBSERVERPREFS_H
#pragma once #include "CoreMinimal.h" #include "Widget/ClosableWnd/ClosableWnd.h" #include "Struct/ShopItemInfo/ShopItemInfo.h" #include "Enum/TradeSeller.h" #include "TradeWnd.generated.h" DECLARE_MULTICAST_DELEGATE_OneParam(FTradeWndButtonSignature, class UTradeWnd *) UCLASS() class ARPG_API UTradeWnd : public UClosableWnd { GENERATED_BODY() public : // 구매 / 판매 버튼이 클릭되었을 경우 호출되는 대리자 FTradeWndButtonSignature OnTradeButtonClickedEvent; private : // 연결된 슬롯 객체를 나타냅니다. class UItemSlot* ConnectedItemSlot; // 판매자를 나타냅니다. ETradeSeller TradeSeller; // 판매 아이템 정보 FShopItemInfo* ShopItemInfo; private : UPROPERTY(meta = (BindWidget)) class UTextBlock * Text_ItemCost; UPROPERTY(meta = (BindWidget)) class UTextBlock * Text_TradeButton; UPROPERTY(meta = (BindWidget)) class UEditableTextBox * EditableTextBox_TradeCount; UPROPERTY(meta = (BindWidget)) class UTextBlock * Text_Result; UPROPERTY(meta = (BindWidget)) class UButton * Button_Trade; UPROPERTY(meta = (BindWidget)) class UButton * Button_Cancel; protected : virtual void NativeConstruct() override; public : // 교환 창을 초기화합니다. void InitializeTradeWnd( ETradeSeller tradeSeller, class UItemSlot* connectedItemSlot, FShopItemInfo* shopItemInfo = nullptr); private : UFUNCTION() void OnTradeButtonClicked(); UFUNCTION() void OnTradeCountTextChanged(const FText& Text); public : // 입력한 문자열이 비어있는지 확인합니다. bool IsInputTextEmpty() const; // 입력한 개수를 int32 형식으로 반환합니다. int32 GetInputTradeCount() const; FORCEINLINE class UItemSlot* GetConnectedItemSlot() const { return ConnectedItemSlot; } FORCEINLINE FShopItemInfo* GetShopItemInfo() const { return ShopItemInfo; } };
#include "StdAfx.h" #include "Show.h" namespace ui { Show* Show::Create() { return new (std::nothrow) Show(); } Show* Show::Clone() const { return Show::Create(); } InstantAction* Show::Reverse() const { return Hide::Create(); } void Show::Update(float time) { InstantAction::Update(time); if (target_) { target_->SetVisible(true); } } }
/* * @lc app=leetcode.cn id=69 lang=cpp * * [69] x 的平方根 */ // @lc code=start #include<iostream> #include<algorithm> #include<cmath> using namespace std; class Solution { public: long long f(long long x, long long t){ long long ans = x*x - t; return ans; } int mySqrt(int x) { if(x==0 || x==1)return x; int l=1,r=x/2; int m=0; while(l<=r){ m = (l+r)/2; if(f(m,x)<0){ l = m + 1; } else if(f(m,x)>0){ r = m - 1; }else{ return m; } } return r; // return int(sqrt(x)); } }; // @lc code=end
/********************************************************* * Copyright (C) 2017 Daniel Enriquez (camus_mm@hotmail.com) * All Rights Reserved * * You may use, distribute and modify this code under the * following terms: * ** Do not claim that you wrote this software * ** A mention would be appreciated but not needed * ** I do not and will not provide support, this software is "as is" * ** Enjoy, learn and share. *********************************************************/ #include "GLRT.h" #include "TextureGL.h" GLRT::~GLRT() { if ( pDepthTexture ) delete pDepthTexture; for ( auto& pColorText : vColorTextures ) delete pColorText; } bool GLRT::LoadAPIRT() { GLint cfmt, dfmt; cfmt = GL_RGB; dfmt = GL_DEPTH_COMPONENT; GLuint fbo; GLuint dtex; glGenFramebuffers( 1, &fbo ); glBindFramebuffer( GL_FRAMEBUFFER, fbo ); glGenTextures( 1, &dtex ); glBindTexture( GL_TEXTURE_2D, dtex ); //glTexImage2D( GL_TEXTURE_2D, 0, dfmt, w, h, 0, dfmt, GL_UNSIGNED_INT, NULL ); glTexImage2D( GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32F, w, h, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); glFramebufferTexture2D( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, dtex, 0 ); TextureGL *pTextureDepth = new TextureGL(); pTextureDepth->id = dtex; this->pDepthTexture = pTextureDepth; DepthTexture = dtex; #if defined(USING_OPENGL_ES30) int Attachments[8]; Attachments[0] = GL_COLOR_ATTACHMENT0; for ( int i = 1; i<8; i++ ) { Attachments[i] = GL_COLOR_ATTACHMENT1 + (i - 1); } #endif for ( int i = 0; i < number_RT; i++ ) { GLuint ctex; glGenTextures( 1, &ctex ); glBindTexture( GL_TEXTURE_2D, ctex ); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB16F, w, h, 0, GL_RGB, GL_FLOAT, NULL ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); TextureGL *pTextureColor = new TextureGL(); glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, ctex, 0 ); pTextureColor->id = ctex; vColorTextures.push_back( pTextureColor ); vFrameBuffers.push_back( fbo ); vGLColorTex.push_back( ctex ); } return true; }
#include <iostream> #include <set> typedef long long ll; ll list[200001]; int main() { std::cin.sync_with_stdio(false); std::cin.tie(NULL); int n, ans = 0; std::cin >> n; for(int i = 1; i <= n; i++) { std::cin >> list[i]; } std::set<ll> s; ll sum = 0; s.insert(0); for(int i = 1; i <= n; i++) { sum += list[i]; if(s.find(sum) == s.end()) { s.insert(sum); } else { ans++; s.clear(); sum = list[i]; s.insert(0); s.insert(sum); } } std::cout << ans << '\n'; return 0; }
//--------------------------------------------------------------------------- #include "GetDetailProcess.h" #include "HallHandler.h" #include "PlayerManager.h" #include "GameCmd.h" #include "ProcessManager.h" REGISTER_PROCESS(CLIENT_MSG_TABLEDET, GetDetailProcess) //--------------------------------------------------------------------------- int GetDetailProcess::doRequest(CDLSocketHandler* client, InputPacket* pPacket, Context* pt ) { HallHandler* clientHandler = reinterpret_cast <HallHandler*> (client); Player* player = PlayerManager::getInstance()->getPlayer(clientHandler->uid); OutputPacket packet; packet.Begin(CLIENT_MSG_TABLEDET, player->id); packet.WriteInt(player->id); packet.WriteInt(player->tid); packet.End(); printf("Send GetDetailProcess Packet to Server\n"); printf("Data Send: id=[%d]\n", player->id); printf("Data Send: tid=[%d]\n",player->tid); return this->send(client,&packet); } int GetDetailProcess::doResponse(CDLSocketHandler* client, InputPacket* inputPacket, Context* pt ) { int error_code = inputPacket->ReadShort(); string error_mag = inputPacket->ReadString(); printf("Recv GetDetailProcess Packet From Server\n"); printf("Data Recv: error_code=[%d]\n",error_code); printf("Data Recv: error_msg=[%s]\n",error_mag.c_str()); if(error_code < 0) return EXIT; //Player* player = this->getPlayer(); printf("Data Recv: uid=[%d] \n", inputPacket->ReadInt()); short pstatus = inputPacket->ReadShort(); //player->status = pstatus; printf("Data Recv: pstatus=[%d] \n", pstatus); printf("Data Recv: tid=[%d] \n", inputPacket->ReadInt()); short tstatus = inputPacket->ReadShort(); //player->table_status = tstatus; printf("Data Recv: tstatus=[%d] \n", tstatus); printf("Data Recv: limittime=[%d] \n", inputPacket->ReadShort()); printf("Data Recv: seatid=[%d] \n", inputPacket->ReadShort()); printf("Data Recv: viptype=[%d] \n", inputPacket->ReadShort()); printf("Data Recv: money=[%ld] \n", inputPacket->ReadInt64()); printf("Data Recv: winnum=[%d] \n", inputPacket->ReadInt()); printf("Data Recv: losenum=[%d] \n", inputPacket->ReadInt()); printf("Data Recv: tienum=[%d] \n", inputPacket->ReadInt()); printf("Data Recv: MoneyCount=[%ld] \n", inputPacket->ReadInt64()); printf("Data Recv: nwin=[%d] \n", inputPacket->ReadShort()); printf("Data Recv: nlose=[%d] \n", inputPacket->ReadShort()); printf("Data Recv: betplayer=[%ld] \n", inputPacket->ReadInt64()); printf("Data Recv: betbanker=[%ld] \n", inputPacket->ReadInt64()); printf("Data Recv: bettie=[%ld] \n", inputPacket->ReadInt64()); printf("Data Recv: betKplayer=[%ld] \n", inputPacket->ReadInt64()); printf("Data Recv: betKbanker=[%ld] \n", inputPacket->ReadInt64()); printf("Data Recv: Bankerid=[%d] \n", inputPacket->ReadInt()); printf("Data Recv: Bankerseatid=[%d] \n", inputPacket->ReadShort()); printf("Data Recv: bankerNum=[%d] \n", inputPacket->ReadByte()); printf("Data Recv: bankerMoney=[%ld] \n", inputPacket->ReadInt64()); printf("Data Recv: table betplayer=[%ld] \n", inputPacket->ReadInt64()); printf("Data Recv: table betbanker=[%ld] \n", inputPacket->ReadInt64()); printf("Data Recv: table bettie=[%ld] \n", inputPacket->ReadInt64()); printf("Data Recv: table betKplayer=[%ld] \n", inputPacket->ReadInt64()); printf("Data Recv: table betKbanker=[%ld] \n", inputPacket->ReadInt64()); printf("Data Recv: playerlimit=[%ld] \n", inputPacket->ReadInt64()); printf("Data Recv: bankerlimit=[%ld] \n", inputPacket->ReadInt64()); printf("Data Recv: tielimit=[%ld] \n", inputPacket->ReadInt64()); printf("Data Recv: Kplayerlimit=[%ld] \n", inputPacket->ReadInt64()); printf("Data Recv: Kbankerlimit=[%ld] \n", inputPacket->ReadInt64()); return 0; }
#include "MenuTexture.hpp" #include "ImageDimensions.hpp" #include "Util/Logger.hpp" #include "Util/Paths.hpp" #include <inc/main.h> #include <filesystem> namespace fs = std::filesystem; namespace { std::map<std::string, SMenuTexture> textures; } const std::map<std::string, SMenuTexture>& MenuTexture::GetTextures() { return textures; } void MenuTexture::UpdateTextures() { auto imgPath = Paths::GetModPath() / "img"; LOG(INFO, "Loading images in {}", imgPath.string()); for (auto& file : fs::directory_iterator(imgPath)) { std::string fileName = file.path().string(); auto stem = file.path().stem().string(); LOG(INFO, "Loading {}", fileName); LOG(INFO, " Stem: {}", stem); if (textures.find(stem) != textures.end()) { LOG(INFO, " Skip: Image already registered"); continue; } auto dims = ImageDimensions::GetIMGDimensions(fileName); if (!dims) { LOG(ERROR, " Skip: Failed to get image size"); continue; } int handle = createTexture(fileName.c_str()); auto result = textures.emplace( stem, SMenuTexture(fileName, handle, dims->Width, dims->Height)); if (result.second) { LOG(INFO, " Emplaced {} with id [{}]", stem, result.first->second.Handle); } else { LOG(ERROR, " Failed to emplace {}", stem); } } std::vector<std::string> filesToErase; for (const auto& [stem, texture] : textures) { if (!fs::exists(texture.Filename)) { filesToErase.push_back(stem); LOG(INFO, "Removing stale file handle {} / {}", stem, texture.Filename); } } for (const auto& file : filesToErase) { textures.erase(file); } }
/* Copyright (c) 2007-2022 Xavier Leclercq Released under the MIT License See https://github.com/ishiko-cpp/test-framework/blob/main/LICENSE.txt */ #include "TestSequenceTests.h" using namespace Ishiko; TestSequenceTests::TestSequenceTests(const TestNumber& number, const TestContext& context) : TestSequence(number, "TestSequence tests", context) { append<HeapAllocationErrorsTest>("Constructor test 1", ConstructorTest1); append<HeapAllocationErrorsTest>("append test 1", AppendTest1); append<HeapAllocationErrorsTest>("append test 2", AppendTest2); append<HeapAllocationErrorsTest>("getResult test 1", GetResultTest1); append<HeapAllocationErrorsTest>("getResult test 2", GetResultTest2); append<HeapAllocationErrorsTest>("getResult test 3", GetResultTest3); append<HeapAllocationErrorsTest>("getResult test 4", GetResultTest4); append<HeapAllocationErrorsTest>("getResult test 5", GetResultTest5); append<HeapAllocationErrorsTest>("getResult test 6", GetResultTest6); } void TestSequenceTests::ConstructorTest1(Test& test) { TestSequence seq(TestNumber(1), "Sequence"); ISHIKO_TEST_PASS(); } void TestSequenceTests::AppendTest1(Test& test) { // Creating test sequence TestSequence seq(TestNumber(1), "Sequence"); // Creating test std::shared_ptr<Test> simpleTest = std::make_shared<Test>(TestNumber(1), "Test", TestResult::passed); // Append test to sequence seq.append(simpleTest); // Check the test sequence ISHIKO_TEST_FAIL_IF_NEQ(seq.size(), 1); ISHIKO_TEST_FAIL_IF_NEQ(seq[0].name(), "Test"); ISHIKO_TEST_FAIL_IF_NEQ(simpleTest->number(), TestNumber(1, 1)); ISHIKO_TEST_PASS(); } void TestSequenceTests::AppendTest2(Test& test) { // Creating test sequence TestSequence seq(TestNumber(1), "Sequence"); // Create and append a test to the sequence in one go using the templated append function seq.append<Test>("Test", TestResult::passed); // Check the test sequence ISHIKO_TEST_FAIL_IF_NEQ(seq.size(), 1); ISHIKO_TEST_FAIL_IF_NEQ(seq[0].name(), "Test"); ISHIKO_TEST_FAIL_IF_NEQ(seq[0].number(), TestNumber(1, 1)); ISHIKO_TEST_PASS(); } void TestSequenceTests::GetResultTest1(Test& test) { TestSequence seq(TestNumber(1), "Sequence"); ISHIKO_TEST_FAIL_IF_NEQ(seq.result(), TestResult::unknown); ISHIKO_TEST_PASS(); } void TestSequenceTests::GetResultTest2(Test& test) { // Creating test sequence TestSequence seq(TestNumber(1), "Sequence"); // Creating test std::shared_ptr<Test> simpleTest = std::make_shared<Test>(TestNumber(1), "Test", TestResult::passed); // Append test to sequence seq.append(simpleTest); // Run the sequence to update the test result seq.run(); ISHIKO_TEST_FAIL_IF_NEQ(seq.result(), TestResult::passed); ISHIKO_TEST_PASS(); } void TestSequenceTests::GetResultTest3(Test& test) { // Creating test sequence TestSequence seq(TestNumber(1), "Sequence"); // Creating first test (passes) std::shared_ptr<Test> test1 = std::make_shared<Test>(TestNumber(1), "Test", TestResult::passed); seq.append(test1); // Creating second test (fails) std::shared_ptr<Test> test2 = std::make_shared<Test>(TestNumber(1), "Test", TestResult::failed); seq.append(test2); // Run the sequence to update the test result seq.run(); ISHIKO_TEST_FAIL_IF_NEQ(seq.result(), TestResult::failed); ISHIKO_TEST_PASS(); } void TestSequenceTests::GetResultTest4(Test& test) { // Creating test sequence TestSequence seq(TestNumber(1), "Sequence"); // Creating first test (skipped) std::shared_ptr<Test> test1 = std::make_shared<Test>(TestNumber(1), "Test", TestResult::skipped); seq.append(test1); // Run the sequence to update the test result seq.run(); ISHIKO_TEST_FAIL_IF_NEQ(seq.result(), TestResult::skipped); ISHIKO_TEST_PASS(); } void TestSequenceTests::GetResultTest5(Test& test) { // Creating test sequence TestSequence seq(TestNumber(1), "Sequence"); // Creating first test (skipped) std::shared_ptr<Test> test1 = std::make_shared<Test>(TestNumber(1), "Test", TestResult::skipped); seq.append(test1); // Creating second test (fails) std::shared_ptr<Test> test2 = std::make_shared<Test>(TestNumber(2), "Test", TestResult::failed); seq.append(test2); // Run the sequence to update the test result seq.run(); ISHIKO_TEST_FAIL_IF_NEQ(seq.result(), TestResult::failed); ISHIKO_TEST_PASS(); } void TestSequenceTests::GetResultTest6(Test& test) { // Creating test sequence TestSequence seq(TestNumber(1), "Sequence"); // Creating first test (passed) std::shared_ptr<Test> test1 = std::make_shared<Test>(TestNumber(1), "Test", TestResult::passed); seq.append(test1); // Creating second test (skipped) std::shared_ptr<Test> test2 = std::make_shared<Test>(TestNumber(2), "Test", TestResult::skipped); seq.append(test2); // Run the sequence to update the test result seq.run(); ISHIKO_TEST_FAIL_IF_NEQ(seq.result(), TestResult::passed); ISHIKO_TEST_PASS(); }
#ifndef CVUTILS_h #define CVUTILS_h using namespace std; #include <opencv/cv.h> #include <opencv/cxcore.h> #include <opencv/highgui.h> #include <vector> #include <cstdlib> #include <stdio.h> /* printf */ #include <stdlib.h> /* system, NULL, EXIT_FAILURE */ using std::abs; class CvUtils { private: public: static void createMask(IplImage * theMask, CvRect maskRegion, int zeroImage) { CvPoint topLeft, bottomRight; if(theMask!=NULL) { if(zeroImage) { cvZero(theMask); } topLeft.x = cvRound((maskRegion.x )); topLeft.y = cvRound((maskRegion.y )); bottomRight.x = cvRound((maskRegion.x + maskRegion.width)); bottomRight.y = cvRound((maskRegion.y + maskRegion.height)); cvRectangle(theMask,topLeft,bottomRight,CV_RGB(255,255,255),-1,8,0); } } static IplImage* Sub_Image(IplImage *image, CvRect roi) { IplImage *result; // sub-image result = cvCreateImage( cvSize(roi.width, roi.height), image->depth, image->nChannels ); cvSetImageROI(image,roi); cvCopy(image,result,0); cvResetImageROI(image); // release image ROI return result; } static CvRect getEncRect(CvRect *roi, int dst_width, int dst_height) { int centerX = 0, centerY=0; int encTlRectX = 0; int encTlRectY = 0; getRectCenter(roi,&centerX,&centerY); encTlRectX = cvRound(centerX-(dst_width*0.5)); encTlRectY = cvRound(centerY-(dst_height*0.5)); return cvRect(encTlRectX,encTlRectY,dst_width,dst_height); } static CvRect* getLargestRect(vector <CvRect*>& rects) { int largestArea = 0; int largestAreaIndex = -1; for (int i=0; i<rects.size(); i++) { CvRect *thisRect = rects.at(i); int thisArea = thisRect->x * thisRect->y; if (thisArea > largestArea) { largestArea = thisArea; largestAreaIndex = i; } } if (largestAreaIndex > -1) { return rects.at(largestAreaIndex); } return 0; } static void getRectCenter(CvRect *roi, int * centerX, int * centerY) { *centerX = cvRound((roi->x + roi->width*0.5)); *centerY = cvRound((roi->y + roi->height*0.5)); } static CvPoint getRectCenterPoint(CvRect *roi) { CvPoint centerPoint = cvPoint( cvRound(roi->x + roi->width/2), cvRound(roi->y + roi->height/2) ); return centerPoint; } static void rotateWithQuadrangle(IplImage *src, IplImage *dst, float angle, CvPoint *center) { // Calcola matrice di rotazione... float m[6]; CvMat M = cvMat(2, 3, CV_32F, m); int w = src->width; int h = src->height; m[0] = (float)(cos(-angle*2*CV_PI/180.)); m[1] = (float)(sin(-angle*2*CV_PI/180.)); m[3] = -m[1]; m[4] = m[0]; //m[2] = w*0.5f; //m[5] = h*0.5f; m[2] = center->x; m[5] = center->y; cvGetQuadrangleSubPix( src, dst, &M); } }; #endif
// Created by: Peter KURNEV // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _BOPTools_AlgoTools3D_HeaderFile #define _BOPTools_AlgoTools3D_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Standard_Integer.hxx> class TopoDS_Edge; class TopoDS_Face; class gp_Dir; class Geom_Surface; class Geom2d_Curve; class gp_Pnt; class IntTools_Context; class gp_Pnt2d; class TopoDS_Shape; //! The class contains handy static functions //! dealing with the topology //! This is the copy of BOPTools_AlgoTools3D.cdl file class BOPTools_AlgoTools3D { public: DEFINE_STANDARD_ALLOC //! Makes the edge <theESplit> seam edge for the face <theFace> basing on the surface properties (U and V periods) Standard_EXPORT static Standard_Boolean DoSplitSEAMOnFace (const TopoDS_Edge& theESplit, const TopoDS_Face& theFace); //! Makes the split edge <theESplit> seam edge for the face <theFace> basing on the positions //! of 2d curves of the original edge <theEOrigin>. Standard_EXPORT static Standard_Boolean DoSplitSEAMOnFace (const TopoDS_Edge& theEOrigin, const TopoDS_Edge& theESplit, const TopoDS_Face& theFace); //! Computes normal to the face <aF> for the point on the edge <aE> //! at parameter <aT>.<br> //! <theContext> - storage for caching the geometrical tools Standard_EXPORT static void GetNormalToFaceOnEdge (const TopoDS_Edge& aE, const TopoDS_Face& aF, const Standard_Real aT, gp_Dir& aD, const Handle(IntTools_Context)& theContext = Handle(IntTools_Context)()); //! Computes normal to the face <aF> for the point on the edge <aE> //! at arbitrary intermediate parameter.<br> //! <theContext> - storage for caching the geometrical tools Standard_EXPORT static void GetNormalToFaceOnEdge (const TopoDS_Edge& aE, const TopoDS_Face& aF, gp_Dir& aD, const Handle(IntTools_Context)& theContext = Handle(IntTools_Context)()); //! Returns 1 if scalar product aNF1* aNF2>0.<br> //! Returns 0 if directions aNF1 aNF2 coincide<br> //! Returns -1 if scalar product aNF1* aNF2<0. Standard_EXPORT static Standard_Integer SenseFlag (const gp_Dir& aNF1, const gp_Dir& aNF2); //! Compute normal <aD> to surface <aS> in point (U,V) //! Returns TRUE if directions aD1U, aD1V coincide Standard_EXPORT static Standard_Boolean GetNormalToSurface (const Handle(Geom_Surface)& aS, const Standard_Real U, const Standard_Real V, gp_Dir& aD); //! Computes normal to the face <aF> for the 3D-point that //! belongs to the edge <aE> at parameter <aT>.<br> //! Output:<br> //! aPx - the 3D-point where the normal computed<br> //! aD - the normal;<br> //! Warning:<br> //! The normal is computed not exactly in the point on the //! edge, but in point that is near to the edge towards to //! the face material (so, we'll have approx. normal);<br> //! The point is computed using PointNearEdge function, //! with the shifting value BOPTools_AlgoTools3D::MinStepIn2d(), //! from the edge, but if this value is too big, //! the point will be computed using Hatcher (PointInFace function).<br> //! Returns TRUE in case of success. Standard_EXPORT static Standard_Boolean GetApproxNormalToFaceOnEdge (const TopoDS_Edge& aE, const TopoDS_Face& aF, const Standard_Real aT, gp_Pnt& aPx, gp_Dir& aD, const Handle(IntTools_Context)& theContext); //! Computes normal to the face <aF> for the 3D-point that //! belongs to the edge <aE> at parameter <aT>.<br> //! Output:<br> //! aPx - the 3D-point where the normal computed<br> //! aD - the normal;<br> //! Warning:<br> //! The normal is computed not exactly in the point on the //! edge, but in point that is near to the edge towards to //! the face material (so, we'll have approx. normal);<br> //! The point is computed using PointNearEdge function //! with the shifting value <aDt2D> from the edge;<br> //! No checks on this value will be done.<br> //! Returns TRUE in case of success. Standard_EXPORT static Standard_Boolean GetApproxNormalToFaceOnEdge (const TopoDS_Edge& theE, const TopoDS_Face& theF, const Standard_Real aT, gp_Pnt& aP, gp_Dir& aDNF, const Standard_Real aDt2D); //! Computes normal to the face <aF> for the 3D-point that //! belongs to the edge <aE> at parameter <aT>.<br> //! Output:<br> //! aPx - the 3D-point where the normal computed<br> //! aD - the normal;<br> //! Warning:<br> //! The normal is computed not exactly in the point on the //! edge, but in point that is near to the edge towards to //! the face material (so, we'll have approx. normal);<br> //! The point is computed using PointNearEdge function //! with the shifting value <aDt2D> from the edge, //! but if this value is too big the point will be //! computed using Hatcher (PointInFace function).<br> //! Returns TRUE in case of success. Standard_EXPORT static Standard_Boolean GetApproxNormalToFaceOnEdge (const TopoDS_Edge& theE, const TopoDS_Face& theF, const Standard_Real aT, const Standard_Real aDt2D, gp_Pnt& aP, gp_Dir& aDNF, const Handle(IntTools_Context)& theContext); //! Compute the point <aPx>, (<aP2D>) that is near to //! the edge <aE> at parameter <aT> towards to the //! material of the face <aF>. The value of shifting in //! 2D is <aDt2D><br> //! If the value of shifting is too big the point //! will be computed using Hatcher (PointInFace function).<br> //! Returns error status:<br> //! 0 - in case of success;<br> //! 1 - <aE> does not have 2d curve on the face <aF>;<br> //! 2 - the computed point is out of the face. Standard_EXPORT static Standard_Integer PointNearEdge (const TopoDS_Edge& aE, const TopoDS_Face& aF, const Standard_Real aT, const Standard_Real aDt2D, gp_Pnt2d& aP2D, gp_Pnt& aPx, const Handle(IntTools_Context)& theContext); //! Compute the point <aPx>, (<aP2D>) that is near to //! the edge <aE> at parameter <aT> towards to the //! material of the face <aF>. The value of shifting in //! 2D is <aDt2D>. No checks on this value will be done.<br> //! Returns error status:<br> //! 0 - in case of success;<br> //! 1 - <aE> does not have 2d curve on the face <aF>. Standard_EXPORT static Standard_Integer PointNearEdge (const TopoDS_Edge& aE, const TopoDS_Face& aF, const Standard_Real aT, const Standard_Real aDt2D, gp_Pnt2d& aP2D, gp_Pnt& aPx); //! Computes the point <aPx>, (<aP2D>) that is near to //! the edge <aE> at parameter <aT> towards to the //! material of the face <aF>. The value of shifting in //! 2D is dt2D=BOPTools_AlgoTools3D::MinStepIn2d()<br> //! If the value of shifting is too big the point will be computed //! using Hatcher (PointInFace function).<br> //! Returns error status:<br> //! 0 - in case of success;<br> //! 1 - <aE> does not have 2d curve on the face <aF>;<br> //! 2 - the computed point is out of the face. Standard_EXPORT static Standard_Integer PointNearEdge (const TopoDS_Edge& aE, const TopoDS_Face& aF, const Standard_Real aT, gp_Pnt2d& aP2D, gp_Pnt& aPx, const Handle(IntTools_Context)& theContext); //! Compute the point <aPx>, (<aP2D>) that is near to //! the edge <aE> at arbitrary parameter towards to the //! material of the face <aF>. The value of shifting in //! 2D is dt2D=BOPTools_AlgoTools3D::MinStepIn2d().<br> //! If the value of shifting is too big the point will be computed //! using Hatcher (PointInFace function).<br> //! Returns error status:<br> //! 0 - in case of success;<br> //! 1 - <aE> does not have 2d curve on the face <aF>;<br> //! 2 - the computed point is out of the face. Standard_EXPORT static Standard_Integer PointNearEdge (const TopoDS_Edge& aE, const TopoDS_Face& aF, gp_Pnt2d& aP2D, gp_Pnt& aPx, const Handle(IntTools_Context)& theContext); //! Returns simple step value that is used in 2D-computations //! = 1.e-5 Standard_EXPORT static Standard_Real MinStepIn2d(); //! Returns TRUE if the shape <aS> does not contain //! geometry information (e.g. empty compound) Standard_EXPORT static Standard_Boolean IsEmptyShape (const TopoDS_Shape& aS); //! Get the edge <aER> from the face <aF> that is the same as //! the edge <aE> Standard_EXPORT static void OrientEdgeOnFace (const TopoDS_Edge& aE, const TopoDS_Face& aF, TopoDS_Edge& aER); //! Computes arbitrary point <theP> inside the face <theF>.<br> //! <theP2D> - 2D representation of <theP> //! on the surface of <theF><br> //! Returns 0 in case of success. Standard_EXPORT static Standard_Integer PointInFace (const TopoDS_Face& theF, gp_Pnt& theP, gp_Pnt2d& theP2D, const Handle(IntTools_Context)& theContext); //! Computes a point <theP> inside the face <theF> //! using starting point taken by the parameter <theT> //! from the 2d curve of the edge <theE> on the face <theF> //! in the direction perpendicular to the tangent vector //! of the 2d curve of the edge.<br> //! The point will be distanced on <theDt2D> from the 2d curve. //! <theP2D> - 2D representation of <theP> //! on the surface of <theF><br> //! Returns 0 in case of success. Standard_EXPORT static Standard_Integer PointInFace (const TopoDS_Face& theF, const TopoDS_Edge& theE, const Standard_Real theT, const Standard_Real theDt2D, gp_Pnt& theP, gp_Pnt2d& theP2D, const Handle(IntTools_Context)& theContext); //! Computes a point <theP> inside the face <theF> //! using the line <theL> so that 2D point //! <theP2D>, 2D representation of <theP> //! on the surface of <theF>, lies on that line.<br> //! Returns 0 in case of success. Standard_EXPORT static Standard_Integer PointInFace (const TopoDS_Face& theF, const Handle(Geom2d_Curve)& theL, gp_Pnt& theP, gp_Pnt2d& theP2D, const Handle(IntTools_Context)& theContext, const Standard_Real theDt2D = 0.0); protected: private: }; #endif // _BOPTools_AlgoTools3D_HeaderFile
// 0927_6.cpp : 定义控制台应用程序的入口点。 //亲和数 //220的所有真约数(即不是自身的约数)之和为: //1 + 2 + 4 + 5 + 10 + 11 + 20 + 22 + 44 + 55 + 110=284。 //而284的所有真约数为1、2、4、71、 142,加起来恰好为220。 //输入数据第一行包含一个数M,接下有M行,每行一个实例,包含两个整数A,B; 其中 0 <= A,B <= 600000 //对于每个测试实例,如果A和B是亲和数的话输出YES,否则输出NO。 #include<iostream> #include<algorithm> using namespace std; int isDivisor(int x) { int i; int sum1 = 0; int sum2 = 0; for (i = 1; i < x; i++) { if (x%i == 0) sum1 += i; } for (i = 1; i < sum1; i++) { if (sum1%i == 0) sum2 += i; } if (sum2 == x) return 1; else return 0; } int main() { int m; cin >> m; while (m--) { int a, b; cin >> a >> b; if (a < 0 || b>600000) break; if (isDivisor(a) && isDivisor(b)) cout << "YES" << endl; else cout << "NO" << endl; } return 0; }
/* Copyright (c) 2015, M. Kerber, D. Morozov, A. Nigmetov All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. You are under no obligation whatsoever to provide any bug fixes, patches, or upgrades to the features, functionality or performance of the source code (Enhancements) to anyone; however, if you choose to make your Enhancements available either publicly, or directly to copyright holder, without imposing a separate written license agreement for such Enhancements, then you hereby grant the following license: a non-exclusive, royalty-free perpetual license to install, use, modify, prepare derivative works, incorporate into other computer software, distribute, and sublicense such enhancements or derivative works thereof, in binary and source code form. */ #ifndef AUCTION_ORACLE_BASE_HPP #define AUCTION_ORACLE_BASE_HPP #include <assert.h> #include <algorithm> #include <functional> #include <iterator> #include "def_debug_ws.h" #include "auction_oracle.h" #ifdef FOR_R_TDA #undef DEBUG_AUCTION #endif namespace hera { namespace ws { template<class Real, class PointContainer> AuctionOracleBase<Real, PointContainer>::AuctionOracleBase(const PointContainer& _bidders, const PointContainer& _items, const AuctionParams<Real>& params) : bidders(_bidders), items(_items), num_bidders_(_bidders.size()), num_items_(_items.size()), prices(items.size(), Real(0.0)), wasserstein_power(params.wasserstein_power), internal_p(params.internal_p), dim(params.dim) { assert(bidders.size() == items.size() ); } template<class Real, class PointContainer> Real AuctionOracleBase<Real, PointContainer>::get_value_for_bidder(size_t bidder_idx, size_t item_idx) const { return std::pow(dist_lp<Real>(bidders[bidder_idx], items[item_idx], internal_p, dim), wasserstein_power) + get_price(item_idx); } template<class Real, class PointContainer> Real AuctionOracleBase<Real, PointContainer>::get_value_for_diagonal_bidder(size_t item_idx) const { return get_cost_for_diagonal_bidder(item_idx) + get_price(item_idx); } template<class Real, class PointContainer> Real AuctionOracleBase<Real, PointContainer>::get_cost_for_diagonal_bidder(size_t item_idx) const { return std::pow(items[item_idx].persistence_lp(internal_p), wasserstein_power); } template<class Real> std::ostream& operator<< (std::ostream& output, const DebugOptimalBid<Real>& db) { output << "best_item_value = " << db.best_item_value; output << "; best_item_idx = " << db.best_item_idx; output << "; second_best_item_value = " << db.second_best_item_value; output << "; second_best_item_idx = " << db.second_best_item_idx; return output; } } // ws } // hera #endif
#include<bits/stdc++.h> using namespace std; const int MAXN=200010; #define maxn 200005 using ll=long long; template<class T>struct Segtree { #define ls (o<<1) #define rs (o<<1)|1 T data[MAXN<<2]; T lazy[MAXN<<2]; void pushup(int o) { data[o]=data[ls]+data[rs]; } void setlazy(int o,int m,T v) { lazy[o]+=v; data[o]+=m*v; } void pushdown(int o,int m) { if(lazy[o]) { setlazy(ls,m-(m>>1),lazy[o]); setlazy(rs,m>>1,lazy[o]); lazy[o]=0; } } void build(int o,int l,int r) { lazy[o]=0; if(l==r) { data[o]=0; return; } int mid=(l+r)>>1; build(ls,l,mid); build(rs,mid+1,r); pushup(o); } void update(int o,int l,int r,int x,int y,T v) { if(l>=x && r<=y) { setlazy(o,r-l+1,v); return; } pushdown(o,r-l+1); int mid=(l+r)>>1; if(x<=mid) update(ls,l,mid,x,y,v); if(y>mid) update(rs,mid+1,r,x,y,v); pushup(o); } void updateone(int o,int l,int r,int index,T v) { if(l==r) { data[o]+=v; return; } int mid=(l+r)>>1; if(index<=mid) updateone(ls,l,mid,index,v); else updateone(rs,mid+1,r,index,v); pushup(o); } T query(int o,int l,int r,int x,int y) { if(l>=x && r<=y) { return data[o]; } pushdown(o,r-l+1); int mid=(l+r)>>1; if(y<=mid) return query(ls,l,mid,x,y); if(x>mid) return query(rs,mid+1,r,x,y); return query(ls,l,mid,x,y)+query(rs,mid+1,r,x,y); } }; Segtree<long long> tree; ll a[maxn]; int cnt[maxn]; int main(){ int l,r; int n,q; cin>>n>>q; for(int i=1;i<=n;i++) cin>>a[i]; tree.build(1,1,n); for(int i=0;i<q;i++){ cin>>l>>r; cout<<111; tree.update(1,1,n,l,r,1); } cout<<222; for(int i=0;i<n;i++){ int t=tree.query(1,1,n,i,i); cnt[i]=t; cout<<t<<"\n"; } sort(a,a+n); sort(cnt,cnt+n); ll ans=0; for(int i=0;i<n;i++){ ans+=(ll)a[i]*cnt[i]; } cout<<ans<<"\n"; return 0; }
/* * leds.cpp * * Created: 15.03.2020 12:43:54 * Author: pavel */ #include <avr/io.h> #include "pins.h" uint8_t get_active_relay(void); uint8_t get_power_enabled(void); uint8_t prev; void led_init(void) { prev = 0x00; } void led_output(void) { uint8_t cur = (1 << (get_active_relay()-1)); if(get_power_enabled()==0xFF) cur |= 0b00001000; if(prev!= cur) { //off LED_PORT &= ~(1<<MODE0_LED_PIN) & ~(1<<MODE1_LED_PIN) & ~(1<<MODE2_LED_PIN) & ~(1<<POWER_LED_PIN); //new LED_PORT |= cur; } prev = cur; }
#pragma once #include "Deque.h" #ifndef _UTIL_INCLUDED #define _UTIL_INCLUDED #include "Util.h" #endif // ! _UTIL_INCLUDED class Simple2TieredVector : public ArrayDataStructure { public: Simple2TieredVector(int32_t size); Simple2TieredVector(void); ~Simple2TieredVector(void); int32_t getElemAt(int32_t); void insertElemAt(int32_t, int32_t); int32_t removeElemAt(int32_t); void insertLast(int32_t); int32_t removeLast(void); }; class BitTrickSimple2TieredVector : public ArrayDataStructure { public: BitTrickSimple2TieredVector(void); ~BitTrickSimple2TieredVector(void); int32_t getElemAt(int32_t); void insertElemAt(int32_t, int32_t); int32_t removeElemAt(int32_t); void insertLast(int32_t); int32_t removeLast(void); }; class Deque2TieredVector : public ArrayDataStructure { public: Deque2TieredVector(int32_t size); Deque2TieredVector(void); ~Deque2TieredVector(void); int32_t getElemAt(int32_t); void insertElemAt(int32_t, int32_t); int32_t removeElemAt(int32_t); void insertLast(int32_t); int32_t removeLast(void); };
#include <avr/io.h> #include "display.h" #include "FMTONE.h" #include "changeParameter.h" #include <avr/pgmspace.h> int posx[2][8]; int posy[2][8]; const char op1[] PROGMEM = "OP1"; const char op2[] PROGMEM = "OP2"; const char save_text[] PROGMEM = "Save=F2"; const char load_text[] PROGMEM = "Load=F1"; const char mul_mes[] PROGMEM = "ML="; extern FmOperator fm_operator[ ]; void drawOperatorWave(uint8_t no) { signed char *rp = no == 0 ? fm_operator[0].wave_tbl : fm_operator[1].wave_tbl ; int ofs = no == 0 ? 190 : 70; SetColor(BLACK); MoveTo(1, ofs - 29); FillRect(72, 49); SetColor(YELLOW); for (int i = 3; i < 60; i = i + 4) { PlotPoint(i, ofs); } SetColor(GREEN); for (uint8_t x = 0; x < 64; x++) { PlotPoint(x / 2 + 15, (rp[x] >> 1) / 2 + ofs); } } void DispForm() { SetColor(GREEN); drawOperatorWave(0); drawOperatorWave(1); SetColor(BLUE); MoveTo(80, 15); FillRect(158, 80); MoveTo(80, 135); FillRect(158, 80); drawEnvelope(0, WHITE); drawEnvelope(1, WHITE); drawMul(0); drawMul(1); } uint8_t conv_time(uint8_t val) { for (int i = 0; i < 16; i++) { if (val == envelope_cnt[i]) { return envelope_time[i]; } } return 1; } void drawEnvelope(uint8_t no, int color) { int yofs = no == 0 ? 135 : 15; int xofs = 80; int xpos = 80; int x, y; int cnt = 1; const int xdiv = 1; int tlv; signed char *rp = no == 0 ? fm_operator[0].wave_tbl : fm_operator[1].wave_tbl ; FmOperator *op = no == 0 ? &(fm_operator[0]) : &(fm_operator[1]); // SetColor(BLUE); // MoveTo(80,yofs); // FillRect(158,80); SetColor(BLUE); x = posx[no][1]; y = posy[no][1]; MoveTo(x, y); for (int i = 2; i < posx[no][0]; i++) { x = posx[no][i]; y = posy[no][i]; DrawTo(x, y); MoveTo(x, y); } SetColor(color); y = op->tl; tlv = y; /* Atack */ x = conv_time( op->atk); y = y / 4 + yofs; x = x / xdiv + xpos; MoveTo(xpos, yofs); posx[no][cnt] = xpos; posy[no][cnt++] = yofs; posx[no][cnt] = x; posy[no][cnt++] = y; DrawTo(x, y); MoveTo(x, y); xpos = x; /* Decy */ y = (op->sul) * tlv / SUSDIV; x = conv_time( op->decy); if (x != 255) { y = y / 4 + yofs; x = x / xdiv + xpos; posx[no][cnt] = x; posy[no][cnt++] = y; DrawTo(x, y); MoveTo(x, y); xpos = x; /* sus */ y = (op->sul) * op->sul / SUSDIV; x = conv_time( op->sus); if (x != 255) { y = y / 4 + yofs; x = x / xdiv / 2 + xpos; posx[no][cnt] = x; posy[no][cnt++] = y; DrawTo(x, y); MoveTo(x, y); xpos = x; /* release */ x = conv_time( op->rel); x = x / xdiv + xpos; y = yofs; posx[no][cnt] = x; posy[no][cnt++] = y; DrawTo(x, y); } else { //y = op->sul; y = (op->sul) * op->tl / SUSDIV; y = y / 4 + yofs; x = 50 + xpos; posx[no][cnt] = x; posy[no][cnt++] = y; DrawTo(x, y); MoveTo(x, y); xpos = x; x = conv_time( op->rel); x = x / xdiv * 2 + xpos; y = yofs; posx[no][cnt] = x; posy[no][cnt++] = y; DrawTo(x, y); } } else { /* attack to release*/ y = op->tl; y = y / 4 + yofs; x = 80 + xpos; posx[no][cnt] = x; posy[no][cnt++] = y; DrawTo(x, y); MoveTo(x, y); xpos = x; x = conv_time( op->rel); x = x / xdiv * 4 + xpos; y = yofs; posx[no][cnt] = x; posy[no][cnt++] = y; DrawTo(x, y); } posx[no][0] = cnt; } void selectOp(uint8_t no) { int color1, color2; color1 = no == 0 ? WHITE : GRAY; color2 = no == 1 ? WHITE : GRAY; SetColor(color2); MoveTo(0, 0); DrawTo(239, 0); DrawTo(239, 119); MoveTo(239, 0); DrawTo(239, 119); MoveTo(0, 0); DrawTo(0, 119); SetColor(color1); MoveTo(0, 120); DrawTo(0, 239); DrawTo(239, 239); //MoveTo(239,239); DrawTo(239, 120); SetColor(WHITE); MoveTo(0, 120); DrawTo(239, 120); SetColor(color1); MoveTo(4, 222); PlotText(op1); SetColor(color2); MoveTo(4, 102); PlotText(op2); } void drawMul(uint8_t no){ uint8_t mul = no == 0 ? fm_operator[0].mul : fm_operator[1].mul; uint8_t yofs = no == 0? 130:10; char c; MoveTo(5,yofs); SetColor(GRAY); PlotText(mul_mes); if(mul >= 10){ c ='1'; mul -= 10; }else{ c = ' '; } MoveTo(40,yofs); PlotChar(c); MoveTo(52,yofs); PlotChar('0'+mul); } //----------------------------------------------------------------- void disp_savemode(){ SetColor(WHITE); MoveTo(20,150); PlotText(save_text); MoveTo(20,100); PlotText(load_text); } const char saveEnd[] PROGMEM = "save"; const char loadEnd[] PROGMEM = "load"; void disp_saved(){ SetColor(WHITE); MoveTo(20,60); PlotText(saveEnd); } void disp_loaded(){ SetColor(WHITE); MoveTo(20,60); PlotText(loadEnd); }
#include <iostream> #include <string.h> #include <set> using namespace std; int main() { int t, n, curSize, prevSize; string s, bestPref; bool failed; set<int> bestIdx; cin >> t; for (int i = 0; i < t; i++) { cin >> n; cin >> s; // get all the possible places bestIdx.clear(); for (int j = 1; j < n; j++) { if (s[0] == s[j]) bestIdx.insert(j); } if (bestIdx.size() == 0) { cout << s << endl; continue; } curSize = 2; while (true) { failed = false; for (int idx : bestIdx) { // cout << curSize << " " << idx << endl; if (idx + curSize > n || s.substr(idx, curSize) != s.substr(0, curSize)) { failed = true; break; } } if (failed) { bestPref = s.substr(0, curSize - 1); break; } curSize++; } cout << bestPref << endl; } }
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * */ #include "core/pch.h" #include "ViewixOpPlatformViewers.h" #include "modules/pi/OpSystemInfo.h" #include "adjunct/desktop_pi/DesktopOpSystemInfo.h" #include "platforms/viewix/src/FileHandlerManagerUtilities.h" namespace { // Sole purpose of this class is to clear specific environment // variables and restore them once function returns. // Use it only through STORE_OP_ENV macro. struct op_env_val { op_env_val(const char *name) { init_status = key.Set(name); if (OpStatus::IsSuccess(init_status)) init_status = val.Set(op_getenv(name)); if (OpStatus::IsSuccess(init_status)) unsetenv(key.CStr()); } ~op_env_val() { if (OpStatus::IsSuccess(init_status)) OpStatus::Ignore(g_env.Set(key.CStr(), val.CStr())); } OP_STATUS init_status; OpString8 key; OpString val; }; }; #if defined(STORE_OP_ENV) #error #else #define STORE_OP_ENV(x) \ op_env_val x(#x); \ if (OpStatus::IsError(x.init_status)) \ return x.init_status; #endif OP_STATUS OpPlatformViewers::Create(OpPlatformViewers** new_platformviewers) { OP_ASSERT(new_platformviewers != NULL); *new_platformviewers = new ViewixOpPlatformViewers(); if(*new_platformviewers == NULL) return OpStatus::ERR_NO_MEMORY; return OpStatus::OK; } OP_STATUS ViewixOpPlatformViewers::OpenInDefaultBrowser(const uni_char* url) { // Now, when we want to open default browser, we need to clear environment. // Otherwise, if opera is set as default browser, xdg-open // may send request back to origin process. // see DSK-310055 STORE_OP_ENV(OPERA_DIR); STORE_OP_ENV(OPERA_PERSONALDIR); STORE_OP_ENV(OPERA_BINARYDIR); STORE_OP_ENV(OPERA_HOME); // xdg-open is recommended by freedesktop.org way of opening pages // in default browser, but DEs prefer to use their own launchers. // see DSK-272180 if (FileHandlerManagerUtilities::isKDERunning()) { return g_op_system_info->ExecuteApplication(UNI_L("kioclient exec"), url); } else if (FileHandlerManagerUtilities::isGnomeRunning()) { return g_op_system_info->ExecuteApplication(UNI_L("gnome-open"), url); } else { return g_op_system_info->ExecuteApplication(UNI_L("xdg-open"), url); } } OP_STATUS ViewixOpPlatformViewers::OpenInOpera(const uni_char* url) { OP_ASSERT(NULL != url); if ( !(url && *url) ) { return OpStatus::ERR; } OpString command; OP_ASSERT(g_op_system_info); RETURN_IF_ERROR(g_op_system_info->GetBinaryPath(&command)); // Opera profile environment variables need to be cleared otherwise call // will go back to origin process. STORE_OP_ENV(OPERA_PERSONALDIR); STORE_OP_ENV(OPERA_HOME); return g_op_system_info->ExecuteApplication(command.CStr(), url); } #undef STORE_OP_ENV