blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
a0dd47af1b552d19f3583c8095e67390cde686ca
c824d97cc1208744e4453bac916dcc24dc77a377
/libcaf_core/src/type_erased_value.cpp
6392f29a4c3bd63d2d4a6602762335f894baa512
[ "BSL-1.0" ]
permissive
DePizzottri/actor-framework
1a033440660c4ea507b743b0d46a46de7fd30df6
bdbd19541b1e1e6ec0abe16bcf7db90d73c649d2
refs/heads/master
2021-01-24T00:23:18.672012
2018-04-28T13:04:21
2018-04-28T13:04:21
59,172,681
0
0
null
2017-03-07T04:22:26
2016-05-19T04:04:18
C++
UTF-8
C++
false
false
1,799
cpp
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2016 * * 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. * ******************************************************************************/ #include "caf/type_erased_value.hpp" namespace caf { type_erased_value::~type_erased_value() { // nop } bool type_erased_value::matches(uint16_t nr, const std::type_info* ptr) const { auto tp = type(); if (tp.first != nr) return false; if (nr == 0) return ptr != nullptr ? *tp.second == *ptr : false; return true; } } // namespace caf
[ "dominik.charousset@haw-hamburg.de" ]
dominik.charousset@haw-hamburg.de
8c55a2fee42abd7569c14942316464bb6ff980c0
5a9e00549b34e729aee373786fd4c8bc26b85670
/main.cpp
83e08d26faa9533da9241bdd80f45fe7a56f09fb
[]
no_license
pelikenmag/tetris
5b11b8513be64e1cc1074845a1661d6ca52b460b
2bee8cf822df1c4a6e87a975cf8628129793a766
refs/heads/master
2021-01-20T04:24:56.948643
2014-09-02T17:41:13
2014-09-02T17:41:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,700
cpp
#include "tetris.h" int main(){ Field gamefield; Shape myshape; st_MERGEME mergeme; SDL_Event event_handle; gamefield.Init(FIELD_SIZE_N,FIELD_SIZE_M); int i,j,x=DEFAULT_X,y=DEFAULT_Y,mergeresult,protox=x; char arrow; bool quit=false; myshape.Generate(SHAPE_STICK); DrawWorld window2D; window2D.Init(); while (!quit){ while (1){ mergeme.shape=myshape.GetShape();mergeme.sn=myshape.GetShapeN();mergeme.sm=myshape.GetShapeM(); mergeme.x=x;mergeme.y=y; mergeresult=gamefield.Merge(mergeme); if (mergeresult==FIELD_OK) break; if (mergeresult==FIELD_BORDER || mergeresult==FIELD_BORDER|FIELD_BOTTOM){ std::cout<<"Border!"<<endl; x=protox; } if (mergeresult==FIELD_BOTTOM){ std::cout<<"Bottom!"<<endl; myshape.Generate(SHAPE_ANGLE); x=DEFAULT_X;y=DEFAULT_Y; } } int *filled_lines=gamefield.FindFilledLines(); if (filled_lines){ gamefield.DelFilledLines(filled_lines); gamefield.NormalizeLines(filled_lines); } gamefield.CreateShowField(mergeme); protox=x; window2D.Draw(gamefield); while(SDL_PollEvent(&event_handle)!=0){ if (event_handle.type==SDL_QUIT){ quit=true; break; } if(event_handle.type==SDL_KEYDOWN) switch(event_handle.key.keysym.sym){ case SDLK_LEFT: x--; break; case SDLK_RIGHT: x++; break; case SDLK_DOWN: y++; break; case SDLK_UP: myshape.Rotate(); break; default: break; } } } return 0; }
[ "pelikenmag@gmail.com" ]
pelikenmag@gmail.com
8f76b106331437044891d34a5ff1c9d03cc99d29
595f3608b6563f5cf162159704d7175326bb576f
/Src/AmrTask/rts_impls/mpi/PackageQueue.H
9d6eb4f092a129436dc26d026ff9ebf5dcb794d5
[ "BSD-2-Clause" ]
permissive
ChrisDeGrendele/amrex
b89ca9f5a3b475ee730ed5371f318eae2841e8b5
586ea4491d9920d4bb0b925cf3809cb1de1df493
refs/heads/master
2020-06-02T18:17:16.998018
2019-05-31T20:50:55
2019-05-31T20:50:55
191,254,393
0
0
NOASSERTION
2019-06-10T22:29:00
2019-06-10T22:28:59
null
UTF-8
C++
false
false
1,409
h
#ifndef P_PACKAGEQUEUE_H #define P_PACKAGEQUEUE_H #include <PerillaConfig.H> #include <pthread.h> #include <mpi.h> class Package { private: int source, destination; public: double *databuf; int bufSize; pthread_mutex_t packageLock; volatile bool completed; //message transfer is done volatile bool served; //message transfer request has been served but may have not completed volatile bool notified; MPI_Request request; //!for MPI Package(); ~Package(); Package(int size); Package(int src, int dest); Package(int src, int dest, int size); void setPackageSource(int src); void setPackageDestination(int dest); void completeRequest(void); void completeRequest(bool lockIgnore); bool checkRequest(void); void generatePackage(int size); }; class PackageQueue { private: Package *buffer[perilla::MSG_QUEUE_DEFAULT_MAXSIZE]; volatile int n; volatile int front; volatile int rear; volatile int prear; int max_size; public: pthread_mutex_t queueLock; PackageQueue(); ~PackageQueue(); int queueSize(void); int queueSize(bool lockIgnore); void enqueue(Package* package); void enqueue(Package* package, bool lockIgnore); Package* dequeue(void); Package* dequeue(bool lockIgnore); Package* getRear(void); Package* getRear(bool lockIgnore); Package* getFront(void); Package* getFront(bool lockIgnore); void emptyQueue(); }; #endif
[ "tannguyen@lbl.gov" ]
tannguyen@lbl.gov
1829e9a55811d0596400923fd7a80e179c26a823
d2e0ec84698d691195500365ad6dca0b4737b72d
/skse64/skse64/ScaleformCallbacks.cpp
579a5f07de57b19c9b28abdb2114a28c56af44ed
[ "MIT" ]
permissive
michaeljdietz/NpcVoiceActivation
26fc9c170710b8f0a05ed9841369f3a036c0605e
df62efc5e6ed9510e4f9423561071d7119a3a44b
refs/heads/master
2020-03-14T12:30:39.768955
2018-04-30T19:52:09
2018-04-30T19:52:09
131,613,327
2
2
null
null
null
null
UTF-8
C++
false
false
776
cpp
#include "ScaleformCallbacks.h" #include <typeinfo> UInt32 g_GFxFunctionHandler_count = 0; GFxFunctionHandler::GFxFunctionHandler() { g_GFxFunctionHandler_count++; } GFxFunctionHandler::~GFxFunctionHandler() { g_GFxFunctionHandler_count--; } FunctionHandlerCache g_functionHandlerCache; RelocAddr<FxDelegateHandler::Callback> PlaySoundCallback(0x00906320); FxResponseArgsList::FxResponseArgsList() { args.values = nullptr; args.size = 0; args.capacity = 0; } FxResponseArgsList::~FxResponseArgsList() { Clear(); } void FxResponseArgsList::Clear() { if (args.values) { for (UInt32 i = 0; i < args.size; i++) args.values[i].CleanManaged(); ScaleformHeap_Free(args.values); args.values = NULL; args.size = 0; } }
[ "michael.dietz@shelterlogic.com" ]
michael.dietz@shelterlogic.com
26e9b32a0ac602db8e05eda995c6c0f156ce56bc
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/squid/hunk_7122.cpp
991bdd2b94171fb3b70dab6a4f627fa1a9a37504
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
573
cpp
{ *var = 0; } - + +static void +dump_size_t(size_t var) +{ + printf("%d bytes", (int) var); +} + +static void +dump_kb_size_t(size_t var) +{ + printf("%d KB", (int) var); +} + +static void +parse_size_t(size_t *var) +{ + parseBytesLine(var, B_BYTES_STR); +} + +static void +parse_kb_size_t(size_t *var) +{ + parseBytesLine(var, B_KBYTES_STR); +} + +static void +free_size_t(size_t *var) +{ + *var = 0; +} + +#define free_kb_size_t free_size_t +#define free_mb_size_t free_size_t +#define free_gb_size_t free_size_t static void dump_ushort(u_short var)
[ "993273596@qq.com" ]
993273596@qq.com
60ba4e52aa3bb3c4f4a26f8e64dec172f8aca84b
e116d3e1069e483cd60cd2c56765b16cb0c875b0
/addons/cirkit-addon-reversible/src/cli/commands/lpqx.hpp
237335ca9725629464d486dc3d76221658046010
[ "MIT" ]
permissive
alexandrecrsilva/cirkit
0be24a3157e32a2a44ce042a72ef02f774136fb0
c88215ffb18c05ff9f56b9b99327834b34054f80
refs/heads/master
2020-04-07T09:57:32.149641
2018-11-18T03:01:54
2018-11-18T03:01:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,927
hpp
/* CirKit: A circuit toolkit * Copyright (C) 2009-2015 University of Bremen * Copyright (C) 2015-2017 EPFL * * 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. */ /** * @file lpqx.hpp * * @brief Formulate the linear programming problem for a ibm qx architecture * * @author Alexandre++ * @2 */ #ifndef CLI_LPQX_COMMAND_HPP #define CLI_LPQX_COMMAND_HPP #include <vector> #include <cli/cirkit_command.hpp> namespace cirkit { class lpqx_command : public cirkit_command { public: lpqx_command( const environment::ptr& env ); log_opt_t log() const; protected: rules_t validity_rules() const; bool execute(); private: std::string filename; unsigned int architecture = 4; unsigned int version = 2; }; } #endif // Local Variables: // c-basic-offset: 2 // eval: (c-set-offset 'substatement-open 0) // eval: (c-set-offset 'innamespace 0) // End:
[ "aamaralalmeida@gmail.com" ]
aamaralalmeida@gmail.com
4e6e65085367f2ec055ce29f970ef74d52f007d3
5bccf2d2118008c0af6a51a92a042e967e4f2abe
/Support/Modules/GSRoot/Win32GDIPlusInterface.hpp
c0c959e80d8eca39799f2dbc44bbf0e4322f7707
[ "Apache-2.0" ]
permissive
graphisoft-python/DGLib
fa42fadebedcd8daaddde1e6173bd8c33545041d
66d8717eb4422b968444614ff1c0c6c1bf50d080
refs/heads/master
2020-06-13T21:38:18.089834
2020-06-12T07:27:54
2020-06-12T07:27:54
194,795,808
3
0
Apache-2.0
2020-06-12T07:27:55
2019-07-02T05:45:00
C++
UTF-8
C++
false
false
643
hpp
// ***************************************************************************** // File: Win32GDIPlusInterface.hpp // // Description: Includes GDIPlus Headers // // Namespace: - // // Contact person: MM // // SG compatible // ***************************************************************************** #if !defined (WIN32GDIPLUSINTERFACE_HPP) #define WIN32GDIPLUSINTERFACE_HPP #pragma once // -- Includes ----------------------------------------------------------------- #include "Win32Interface.hpp" #pragma warning (push) #pragma warning (disable : 4995) #include <oleidl.h> #include <gdiplus.h> #pragma warning (pop) #endif
[ "445212619@qqcom" ]
445212619@qqcom
9335d8776df15af44e60a09854464205f254f46a
f29124740362de0f137ebe665421555ff2f3f5e0
/Minuit3/stdafx.cpp
4d25dc47e9b595acba208b812f74c466a56645cb
[]
no_license
salvato/Minuit3
5ddbeca869137adb1015fd6188915874a579c03f
1443216bd526643571802b2391f9d7ae796fb97e
refs/heads/master
2020-04-27T00:33:21.606255
2019-03-05T11:55:54
2019-03-05T11:55:54
173,937,555
0
0
null
null
null
null
ISO-8859-13
C++
false
false
213
cpp
// stdafx.cpp : file di origine che include solo le inclusioni standard // Minuit3.pch sarą l'intestazione precompilata // stdafx.obj conterrą le informazioni sui tipi precompilati #include "stdafx.h"
[ "noreply@github.com" ]
salvato.noreply@github.com
e3651344e542830057edd500b615c6e7531ae04a
9ab11e1e76fb7654ba1e247d035da873f4256d6a
/Sources/RainbowEngine/UI/include/UI/Widgets/InputFields/InputSingleScalar.h
ddbe95f3f502937f144e804b2adab42db6f632d5
[]
no_license
Tekh-ops/RainbowEngine
f7e565ddcbdcab0e8fb663d8e51988b73895698f
5d1dc91d15fc988d7eacdd23900d0d5c398d5f1b
refs/heads/master
2023-04-03T13:55:10.200479
2021-04-01T15:14:48
2021-04-01T15:14:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,738
h
#pragma once #include <Tools/Eventing/Event.h> #include "UI/Widgets/DataWidget.h" namespace UI::Widgets::InputFields { /** * Input widget of generic type */ template <typename T> class InputSingleScalar : public DataWidget<T> { static_assert(std::is_scalar<T>::value, "Invalid InputSingleScalar T (Scalar expected)"); public: /** * Constructor * @param p_dataType * @param p_defaultValue * @param p_step * @param p_fastStep * @param p_label * @param p_format * @param p_selectAllOnClick */ InputSingleScalar ( ImGuiDataType p_dataType, T p_defaultValue, T p_step, T p_fastStep, const std::string& p_label, const std::string& p_format, bool p_selectAllOnClick ) : DataWidget<T>(value), m_dataType(p_dataType), value(p_defaultValue), step(p_step), fastStep(p_fastStep), label(p_label), format(p_format), selectAllOnClick(p_selectAllOnClick) {} protected: void _Draw_Impl() override { T previousValue = value; ImGuiInputTextFlags flags = ImGuiInputTextFlags_EnterReturnsTrue; if (selectAllOnClick) flags |= ImGuiInputTextFlags_AutoSelectAll; bool enterPressed = ImGui::InputScalar((label + this->m_widgetID).c_str(), m_dataType, &value, step != 0.0f ? &step : nullptr, fastStep != 0.0f ? &fastStep : nullptr, format.c_str(), flags); if (previousValue != value) { ContentChangedEvent.Invoke(value); this->NotifyChange(); } if (enterPressed) EnterPressedEvent.Invoke(value); } public: T value; T step; T fastStep; std::string label; std::string format; bool selectAllOnClick; Tools::Eventing::Event<T> ContentChangedEvent; Tools::Eventing::Event<T> EnterPressedEvent; private: ImGuiDataType m_dataType; }; }
[ "43663573+leoandtt@users.noreply.github.com" ]
43663573+leoandtt@users.noreply.github.com
3f15420462f9b715113b92dd8748ea6bfad71f4c
87d9f453831f38ca5dc45b74f8b31cb8093b4da0
/cppVersion/Maximum Subarray.cpp
55857c7918256967b3d37cd970d070664d17df6c
[ "MIT" ]
permissive
ChinoMars/LeetCodeSolution
a46cb8ce4690164ca7988232bff726b8740542bd
604fc5e387582ecec85d0431bbddb542af2b92fa
refs/heads/master
2020-05-21T00:08:44.124489
2015-10-30T02:00:14
2015-10-30T02:00:14
35,195,112
2
0
null
null
null
null
UTF-8
C++
false
false
395
cpp
class Solution { public: int maxSubArray(vector<int>& nums) { int len = nums.size(); int fnlsum = INT_MIN, tmpsum = 0; for(int i = 0; i < len; ++i) { tmpsum = tmpsum>=0 ? tmpsum+nums[i] : nums[i]; fnlsum = max(fnlsum,tmpsum); } return fnlsum; } };
[ "chinomask@gmail.com" ]
chinomask@gmail.com
dbec0ae167e90e5023eac29a07e211765f2d5f3e
9611083d0317ce148f7a007550118cfb347ac845
/PROJECTS/2016_09_AQUAPHONEIA/Flowsensor_Thibodeau/arduino/old_versions/Aquaphoenia-Flowsensor-0.7/Aquaphoenia-Flowsensor-0.7.ino
25618609df69484812733addd3d6a32daeaa5029
[]
no_license
navid/TML-depo
957f65bfbb9f62c5089ee5396437329f9868fb3e
08e215db1bd7967de74d5f200a1e4f839cf8d7b9
refs/heads/master
2023-02-08T22:04:02.402584
2023-02-07T03:28:28
2023-02-07T03:28:28
45,488,866
3
4
null
2017-11-01T18:21:18
2015-11-03T19:02:47
Max
UTF-8
C++
false
false
2,741
ino
//-------------------------------------- // DECLARING STUFF //-------------------------------------- // Timer variables int ONE_SECOND = 62500; int TIME_DIV = 4; //int RESET_COUNT = 65536 - (ONE_SECOND / TIME_DIV); int RESET_COUNT = 49910; //4Hz // Testing variables volatile bool isr_flag = false; volatile bool test_pin_val = 0; int count = 0; int test_pin = 7; // Flow Sensor Variables int num_sensors = 5; volatile int flow_pin[5] = {2,3,4,5,6}; volatile int flow_pin_new_state[5] = {0,0,0,0,0}; volatile int flow_pin_old_state[5] = {0,0,0,0,0}; volatile int flow_pulse_count[5] = {0,0,0,0,0}; //====================================== // SETUP FUNCTION //====================================== void setup() { cli(); //disable interrupts // test pin setup pinMode(test_pin,OUTPUT); digitalWrite(test_pin,LOW); // setup input pins for (int p=0;p<num_sensors;p++) { pinMode(flow_pin[p],INPUT); } // initialize Timer1 TCCR1A = 0; // set entire TCCR1A register to 0 TCCR1B = 0; // set entire TCCR1B register to 0 // (as we do not know the initial values) // enable Timer1 overflow interrupt: TIMSK1 |= (1 << TOIE1); // Preload with value 3036 //use 64886 for 100Hz //use 64286 for 50 Hz //use 34286 for 2 Hz TCNT1=RESET_COUNT; // Set CS10 bit so timer runs at clock speed: (no prescaling) TCCR1B |= (1 << CS12); // Sets bit CS12 in TCCR1B Serial.begin(9600); Serial.print(0); sei(); } //====================================== // TIMER INTERRUPT //====================================== //This is the timer overflow interrupt //This is where we will determine the input pulse states //and keep a count of the number of pulses ISR(TIMER1_OVF_vect) { isr_flag = true; test_pin_val = HIGH; digitalWrite(test_pin,test_pin_val); TCNT1=RESET_COUNT; // reload the timer preload } //====================================== // MAIN LOOP //====================================== void loop() { //------this happens when the timer overflows if (isr_flag == true) { for (int p=0;p<num_sensors;p++) { Serial.write(flow_pulse_count[p]); flow_pulse_count[p] = 0; isr_flag = false; } } //-------this happens all the time as fast as possible // poll each sensor input for (int p=0;p<num_sensors;p++) { // read the input value flow_pin_new_state[p] = digitalRead(flow_pin[p]); //is it different? Looking for a rising edge if ((flow_pin_new_state[p] == HIGH) && (flow_pin_old_state[p] == LOW)) { flow_pulse_count[p] += TIME_DIV; test_pin_val = LOW; digitalWrite(test_pin,test_pin_val); } flow_pin_old_state[p] = flow_pin_new_state[p]; } }
[ "navid.nav@gmail.com" ]
navid.nav@gmail.com
a2a99dd1230df8b2d1eccc32b8378a5b8b3fcd28
684c9beb8bd972daeabe5278583195b9e652c0c5
/src/cobalt/script/mozjs-45/mozjs_data_view.h
64b0228616e65a49904c4b2918d13a13f8b1bf06
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
elgamar/cobalt-clone
a7d4e62630218f0d593fa74208456dd376059304
8a7c8792318a721e24f358c0403229570da8402b
refs/heads/master
2022-11-27T11:30:31.314891
2018-10-26T15:54:41
2018-10-26T15:55:22
159,339,577
2
4
null
2022-11-17T01:03:37
2018-11-27T13:27:44
C++
UTF-8
C++
false
false
4,203
h
// Copyright 2018 The Cobalt Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef COBALT_SCRIPT_MOZJS_45_MOZJS_DATA_VIEW_H_ #define COBALT_SCRIPT_MOZJS_45_MOZJS_DATA_VIEW_H_ #include "base/logging.h" #include "cobalt/script/data_view.h" #include "cobalt/script/mozjs-45/mozjs_array_buffer.h" #include "cobalt/script/mozjs-45/mozjs_user_object_holder.h" #include "cobalt/script/mozjs-45/type_traits.h" #include "cobalt/script/mozjs-45/weak_heap_object.h" #include "third_party/mozjs-45/js/src/jsapi.h" #include "third_party/mozjs-45/js/src/jsfriendapi.h" namespace cobalt { namespace script { namespace mozjs { class MozjsDataView final : public DataView { public: using BaseType = DataView; MozjsDataView(JSContext* context, JS::HandleValue value) : context_(context), weak_heap_object_(context, value) { DCHECK(value.isObject()); DCHECK(JS_IsDataViewObject(&value.toObject())); } JSObject* handle() const { return weak_heap_object_.GetObject(); } const JS::Value& value() const { return weak_heap_object_.GetValue(); } bool WasCollected() const { return weak_heap_object_.WasCollected(); } void Trace(JSTracer* js_tracer) { weak_heap_object_.Trace(js_tracer); } Handle<ArrayBuffer> Buffer() const override { JSAutoRequest auto_request(context_); JS::RootedObject array_buffer_view(context_, weak_heap_object_.GetObject()); bool is_shared_memory; JSObject* object = JS_GetArrayBufferViewBuffer(context_, array_buffer_view, &is_shared_memory); JS::RootedValue value(context_); value.setObject(*object); return Handle<ArrayBuffer>( new MozjsUserObjectHolder<MozjsArrayBuffer>(context_, value)); } size_t ByteOffset() const override { return JS_GetDataViewByteOffset(weak_heap_object_.GetObject()); } size_t ByteLength() const override { return JS_GetDataViewByteLength(weak_heap_object_.GetObject()); } void* RawData() const override { JS::AutoCheckCannotGC no_gc; return JS_GetDataViewData(weak_heap_object_.GetObject(), no_gc); } protected: JSContext* context_; WeakHeapObject weak_heap_object_; }; template <> struct TypeTraits<DataView> { using ConversionType = MozjsUserObjectHolder<MozjsDataView>; using ReturnType = const ScriptValue<DataView>*; }; inline void ToJSValue(JSContext* context, const ScriptValue<DataView>* array_buffer_view_value, JS::MutableHandleValue out_value) { TRACK_MEMORY_SCOPE("Javascript"); if (!array_buffer_view_value) { out_value.set(JS::NullValue()); return; } const auto* mozjs_array_buffer_view_value = base::polymorphic_downcast<const MozjsUserObjectHolder<MozjsDataView>*>( array_buffer_view_value); out_value.setObject(*mozjs_array_buffer_view_value->js_object()); } inline void FromJSValue( JSContext* context, JS::HandleValue value, int conversion_flags, ExceptionState* exception_state, MozjsUserObjectHolder<MozjsDataView>* out_array_buffer_view) { TRACK_MEMORY_SCOPE("Javascript"); DCHECK_EQ(0, conversion_flags); DCHECK(out_array_buffer_view); if (!value.isObject()) { exception_state->SetSimpleException(kNotObjectType); return; } if (!JS_IsDataViewObject(&value.toObject())) { exception_state->SetSimpleException(kTypeError, "Expected object of type DataView"); return; } *out_array_buffer_view = MozjsUserObjectHolder<MozjsDataView>(context, value); } } // namespace mozjs } // namespace script } // namespace cobalt #endif // COBALT_SCRIPT_MOZJS_45_MOZJS_DATA_VIEW_H_
[ "aabtop@google.com" ]
aabtop@google.com
1271239ec4b48ba565f775e79b0b2770cd71f835
bc3b19735701983322449ad28281971f5e6a9c6d
/Player.h
c41c50c547c71bd5573de292ea2b6aa844ffbb4f
[]
no_license
ykh09242/TileGame
5553dd490321ab33c64b71d8c0a1b5d277156087
5f1cdd966659cbd8d87f0b5e3a1b9a893d99634f
refs/heads/master
2020-03-21T21:51:43.327512
2018-07-03T08:28:47
2018-07-03T08:28:47
138,686,034
0
0
null
null
null
null
UTF-8
C++
false
false
214
h
#pragma once class Player { public: string shape; Vector2 pos; int move; bool turnEnd; private: bool item; public: Player(string shape, Vector2 startPos, int move = 1); public: void Moving(Map* map); };
[ "phk09242@gmail.com" ]
phk09242@gmail.com
0880399f98ab642e3233fe261d9672cce48e07a3
b7593b8540740813b210fbec7dca2fe1833d9594
/Timer.h
90e98d7ce37858f16c27f434a1d63b1fe27632f2
[]
no_license
samrbutler/FeyndDiagram
0193ffe450a5576a3985b49638d087f725e5ea86
fefd0d991f55feae646bdae9a1f8178012fe8431
refs/heads/master
2023-03-10T21:13:09.221548
2021-02-17T16:16:09
2021-02-17T16:16:09
299,690,606
0
0
null
null
null
null
UTF-8
C++
false
false
414
h
#pragma once #include <chrono> #include <iostream> #include <string> class Timer { using clock_t = std::chrono::high_resolution_clock; using second_t = std::chrono::duration<double, std::ratio<1> >; std::chrono::time_point<clock_t> m_beg; public: Timer() : m_beg(clock_t::now()) {}; void reset() { m_beg = clock_t::now(); } double elapsed() const; void lap(std::string prefix = "Time elapsed: "); };
[ "sam.r.butler@outlook.com" ]
sam.r.butler@outlook.com
06e81d526f954c6efc67d218631b48b633e80ab1
329bf38920ae26cf6699a659d0a875b43cd4764e
/STM8L101F3P6/utils/queue/queue.cpp
ee50db313f29bb51ce231e75e1bb044bb3121a25
[]
no_license
amitandgithub/STM8L101F3_FW
ae012d6417ca1c11bbab66734529f7fbe07b4957
787e802665b199f2183fc8fad19b4189661f613e
refs/heads/master
2022-01-23T00:12:38.080393
2021-12-25T04:42:02
2021-12-25T04:42:02
199,318,490
0
0
null
2019-09-06T04:57:37
2019-07-28T17:39:52
C
UTF-8
C++
false
false
2,218
cpp
/****************** ** FILE: queue.c ** ** DESCRIPTION: ** queue implementation ** ** CREATED: 8/5/2019, by Amit Chaudhary ******************/ #include"queue.hpp" queue::Queue_Status_t queue::QueueInit(Queue_t* pQueue) { if(pQueue) { pQueue->WriteHead = pQueue->Capacity - 1; // rear pQueue->ReadHead = 0; // front return QUEUE_OK; } return QUEUE_INVALID_PARAMS; } queue::Queue_Status_t queue::QueueFull(Queue_t* pQueue) { if(pQueue == 0) return QUEUE_INVALID_PARAMS; if(pQueue->Size == pQueue->Capacity) return QUEUE_FULL; else return QUEUE_OK; } queue::Queue_Status_t queue::QueueEmpty(Queue_t* pQueue) { if(pQueue == 0) return QUEUE_INVALID_PARAMS; if(pQueue->Size == 0) return QUEUE_EMPTY; else return QUEUE_OK; } queue::Queue_Status_t queue::AvailableEnteries(Queue_t* pQueue, QueueSize_t* pAvailableData) { if(pQueue == 0) return QUEUE_INVALID_PARAMS; *pAvailableData = pQueue->Size; return QUEUE_OK; } /** * Enqueue/Insert an element to the queue. */ queue::Queue_Status_t queue::QueueWrite(Queue_t* pQueue,QueueSize_t data) { Queue_Status_t status; status = QueueFull(pQueue); if (status != QUEUE_OK) { return status; } pQueue->WriteHead += 1;// (pQueue->WriteHead + 1) % CAPACITY; if(pQueue->WriteHead == pQueue->Capacity) pQueue->WriteHead = 0; // Increment queue size pQueue->Size++; // Enqueue new element to queue pQueue->Buf[pQueue->WriteHead] = data; // Successfully enqueued element to queue return QUEUE_OK; } /** * Dequeue/Remove an element from the queue. */ queue::Queue_Status_t queue::QueueRead(Queue_t* pQueue, QueueSize_t* pdata) { Queue_Status_t status; status = QueueEmpty(pQueue); // Queue is empty, throw Queue underflow error if (status != QUEUE_OK) { return status; } // Dequeue element from queue *pdata = pQueue->Buf[pQueue->ReadHead]; // Ensure front never crosses array bounds pQueue->ReadHead +=1;// (front + 1) % CAPACITY; if(pQueue->ReadHead == pQueue->Capacity) pQueue->ReadHead = 0; // Decrease queue size pQueue->Size--; return QUEUE_OK; }
[ "amit4u.com@gmail.com" ]
amit4u.com@gmail.com
638b97491d2610206cf1d2496e9cf939e7468971
adfcd15da351a38af5713ea4e138160e1744bc1e
/src/Pool.h
0f93b6fd913b5d3d93a66a0301c0508420eb9e42
[ "BSD-2-Clause" ]
permissive
natecollins/vecs
05ea013a89d4c6a3a5a76bec288212ba797dbc4c
b003b8f856acd20c8d02cfea89baed119b8cd794
refs/heads/master
2020-03-23T01:24:48.192243
2018-07-14T04:30:55
2018-07-14T04:30:55
140,915,974
0
0
null
null
null
null
UTF-8
C++
false
false
1,793
h
#ifndef POOL_H_ #define POOL_H_ #include <cstdint> #include <cstdlib> #include <deque> #include <vector> #include <tuple> #include <atomic> #include "entdef.h" namespace vecs { class Pool { friend class Domain; private: // Spinlock for allocations/de-allocations std::atomic_flag spinlock; // Assignment allocation size; e.g. 32 const std::size_t block_size; // Allocation chunk size; e.g. 65536 const std::size_t chunk_size; // Allocated chunks std::vector<char*> chunks; // Freed Blocks availability std::vector<char*> blocks; // Top of stack char* top; public: Pool(std::size_t block_size, std::size_t chunk_size=65536); virtual ~Pool(); void lock(); void unlock(); std::size_t getChunkSize() const; std::size_t getBlocksPerChunk() const; std::size_t getBlockSize() const; std::size_t getCurrentBlockMax() const; /** * Allocate more memory chunks */ void reserve(std::size_t chunk_count=1, bool bypass_lock=false); template<typename T> T* allocate(); template<typename T> void release(T* ptr); }; template<typename T> T* Pool::allocate() { void* mem = nullptr; lock(); if (blocks.size() != 0) { mem = (void*)blocks.back(); blocks.pop_back(); } else { if ((top + block_size) > (chunks.back() + chunk_size)) { reserve(1, true); top = chunks.back(); } mem = (void*)top; top += block_size; } unlock(); return static_cast<T*>(mem); } template<typename T> void Pool::release(T *ptr) { // Call Component virtual deconstructor ptr->~T(); // Mark memory as available lock(); blocks.push_back( (char*)ptr ); unlock(); } } #endif // POOL_H_
[ "npcollins@gmail.com" ]
npcollins@gmail.com
0d2de1cd68d86ba5beae70eb86b90f6ce81f3175
33eaafc0b1b10e1ae97a67981fe740234bc5d592
/tests/RandomSAT/z3-master/src/math/euclid/euclidean_solver.cpp
af11d43044ded464574903c7fa76fb8d10d7c9b5
[ "MIT" ]
permissive
akinanop/mvl-solver
6c21bec03422bb2366f146cb02e6bf916eea6dd0
bfcc5b243e43bddcc34aba9c34e67d820fc708c8
refs/heads/master
2021-01-16T23:30:46.413902
2021-01-10T16:53:23
2021-01-10T16:53:23
48,694,935
6
2
null
2016-08-30T10:47:25
2015-12-28T13:55:32
C++
UTF-8
C++
false
false
29,230
cpp
/*++ Copyright (c) 2011 Microsoft Corporation Module Name: euclidean_solver.cpp Abstract: Euclidean Solver with support for explanations. Author: Leonardo de Moura (leonardo) 2011-07-08. Revision History: --*/ #include"euclidean_solver.h" #include"numeral_buffer.h" #include"heap.h" struct euclidean_solver::imp { typedef unsigned var; typedef unsigned justification; typedef unsynch_mpq_manager numeral_manager; typedef numeral_buffer<mpz, numeral_manager> mpz_buffer; typedef numeral_buffer<mpq, numeral_manager> mpq_buffer; typedef svector<justification> justification_vector; static const justification null_justification = UINT_MAX; #define null_var UINT_MAX #define null_eq_idx UINT_MAX typedef svector<var> var_vector; typedef svector<mpz> mpz_vector; typedef svector<mpq> mpq_vector; struct elim_order_lt { unsigned_vector & m_solved; elim_order_lt(unsigned_vector & s):m_solved(s) {} bool operator()(var x1, var x2) const { return m_solved[x1] < m_solved[x2]; } }; typedef heap<elim_order_lt> var_queue; // queue used for scheduling variables for applying substitution. static unsigned pos(unsigned_vector const & xs, unsigned x_i) { if (xs.empty()) return UINT_MAX; int low = 0; int high = xs.size() - 1; while (true) { int mid = low + ((high - low) / 2); var x_mid = xs[mid]; if (x_i > x_mid) { low = mid + 1; if (low > high) return UINT_MAX; } else if (x_i < x_mid) { high = mid - 1; if (low > high) return UINT_MAX; } else { return mid; } } } /** Equation as[0]*xs[0] + ... + as[n-1]*xs[n-1] + c = 0 with justification bs[0]*js[0] + ... + bs[m-1]*js[m-1] */ struct equation { mpz_vector m_as; var_vector m_xs; mpz m_c; // justification mpq_vector m_bs; justification_vector m_js; unsigned size() const { return m_xs.size(); } unsigned js_size() const { return m_js.size(); } var x(unsigned i) const { return m_xs[i]; } var & x(unsigned i) { return m_xs[i]; } mpz const & a(unsigned i) const { return m_as[i]; } mpz & a(unsigned i) { return m_as[i]; } mpz const & c() const { return m_c; } mpz & c() { return m_c; } var j(unsigned i) const { return m_js[i]; } var & j(unsigned i) { return m_js[i]; } mpq const & b(unsigned i) const { return m_bs[i]; } mpq & b(unsigned i) { return m_bs[i]; } unsigned pos_x(unsigned x_i) const { return pos(m_xs, x_i); } }; typedef ptr_vector<equation> equations; typedef svector<unsigned> occs; numeral_manager * m_manager; bool m_owns_m; equations m_equations; equations m_solution; svector<bool> m_parameter; unsigned_vector m_solved; // null_eq_idx if var is not solved, otherwise the position in m_solution vector<occs> m_occs; // occurrences of the variable in m_equations. unsigned m_inconsistent; // null_eq_idx if not inconsistent, otherwise it is the index of an unsatisfiable equality in m_equations. unsigned m_next_justification; mpz_buffer m_decompose_buffer; mpz_buffer m_as_buffer; mpq_buffer m_bs_buffer; var_vector m_tmp_xs; mpz_buffer m_tmp_as; mpq_buffer m_tmp_bs; var_vector m_norm_xs_vector; mpz_vector m_norm_as_vector; mpq_vector m_norm_bs_vector; var_queue m_var_queue; // next candidate unsigned m_next_eq; var m_next_x; mpz m_next_a; bool m_next_pos_a; numeral_manager & m() const { return *m_manager; } bool solved(var x) const { return m_solved[x] != null_eq_idx; } template<typename Numeral> void sort_core(svector<Numeral> & as, unsigned_vector & xs, numeral_buffer<Numeral, numeral_manager> & buffer) { std::sort(xs.begin(), xs.end()); unsigned num = as.size(); for (unsigned i = 0; i < num; i++) { m().swap(as[i], buffer[xs[i]]); } } template<typename Numeral> void sort(svector<Numeral> & as, unsigned_vector & xs, numeral_buffer<Numeral, numeral_manager> & buffer) { unsigned num = as.size(); for (unsigned i = 0; i < num; i++) { m().set(buffer[xs[i]], as[i]); } sort_core(as, xs, buffer); } equation * mk_eq(unsigned num, mpz const * as, var const * xs, mpz const & c, unsigned num_js, mpq const * bs, justification const * js, bool sort = true) { equation * new_eq = alloc(equation); for (unsigned i = 0; i < num; i++) { m().set(m_as_buffer[xs[i]], as[i]); new_eq->m_as.push_back(mpz()); new_eq->m_xs.push_back(xs[i]); } sort_core(new_eq->m_as, new_eq->m_xs, m_as_buffer); m().set(new_eq->m_c, c); for (unsigned i = 0; i < num_js; i++) { m().set(m_bs_buffer[js[i]], bs[i]); new_eq->m_bs.push_back(mpq()); new_eq->m_js.push_back(js[i]); } if (sort) sort_core(new_eq->m_bs, new_eq->m_js, m_bs_buffer); return new_eq; } template<typename Numeral> void div(svector<Numeral> & as, mpz const & g) { unsigned n = as.size(); for (unsigned i = 0; i < n; i++) m().div(as[i], g, as[i]); } void normalize_eq(unsigned eq_idx) { if (inconsistent()) return; equation & eq = *(m_equations[eq_idx]); TRACE("euclidean_solver", tout << "normalizing:\n"; display(tout, eq); tout << "\n";); unsigned num = eq.size(); if (num == 0) { // c == 0 inconsistency if (!m().is_zero(eq.c())) { TRACE("euclidean_solver", tout << "c = 0 inconsistency detected\n";); m_inconsistent = eq_idx; } else { del_eq(&eq); m_equations[eq_idx] = 0; } return; } mpz g; mpz a; m().set(g, eq.a(0)); m().abs(g); for (unsigned i = 1; i < num; i++) { if (m().is_one(g)) break; m().set(a, eq.a(i)); m().abs(a); m().gcd(g, a, g); } if (m().is_one(g)) return; if (!m().divides(g, eq.c())) { // g does not divide c TRACE("euclidean_solver", tout << "gcd inconsistency detected\n";); m_inconsistent = eq_idx; return; } div(eq.m_as, g); div(eq.m_bs, g); m().del(g); m().del(a); TRACE("euclidean_solver", tout << "after normalization:\n"; display(tout, eq); tout << "\n";); } bool is_better(mpz const & a, var x, unsigned eq_sz) { SASSERT(m().is_pos(a)); if (m_next_x == null_var) return true; if (m().lt(a, m_next_a)) return true; if (m().lt(m_next_a, a)) return false; if (m_occs[x].size() < m_occs[m_next_x].size()) return true; if (m_occs[x].size() > m_occs[m_next_x].size()) return false; return eq_sz < m_equations[m_next_eq]->size(); } void updt_next_candidate(unsigned eq_idx) { if (!m_equations[eq_idx]) return; mpz abs_a; equation const & eq = *(m_equations[eq_idx]); unsigned num = eq.size(); for (unsigned i = 0; i < num; i++) { mpz const & a = eq.a(i); m().set(abs_a, a); m().abs(abs_a); if (is_better(abs_a, eq.x(i), num)) { m().set(m_next_a, abs_a); m_next_x = eq.x(i); m_next_eq = eq_idx; m_next_pos_a = m().is_pos(a); } } m().del(abs_a); } /** \brief Select next variable to be eliminated. Return false if there is not variable to eliminate. The result is in m_next_x variable to be eliminated m_next_eq id of the equation containing x m_next_a absolute value of the coefficient of x in eq. m_next_pos_a true if the coefficient of x is positive in eq. */ bool select_next_var() { while (!m_equations.empty() && m_equations.back() == 0) m_equations.pop_back(); if (m_equations.empty()) return false; SASSERT(!m_equations.empty() && m_equations.back() != 0); m_next_x = null_var; unsigned eq_idx = m_equations.size(); while (eq_idx > 0) { --eq_idx; updt_next_candidate(eq_idx); // stop as soon as possible // TODO: use heuristics if (m_next_x != null_var && m().is_one(m_next_a)) return true; } CTRACE("euclidean_solver_bug", m_next_x == null_var, display(tout);); SASSERT(m_next_x != null_var); return true; } template<typename Numeral> void del_nums(svector<Numeral> & as) { unsigned sz = as.size(); for (unsigned i = 0; i < sz; i++) m().del(as[i]); as.reset(); } void del_eq(equation * eq) { m().del(eq->c()); del_nums(eq->m_as); del_nums(eq->m_bs); dealloc(eq); } void del_equations(equations & eqs) { unsigned sz = eqs.size(); for (unsigned i = 0; i < sz; i++) { if (eqs[i]) del_eq(eqs[i]); } } /** \brief Store the "solved" variables in xs into m_var_queue. */ void schedule_var_subst(unsigned num, var const * xs) { for (unsigned i = 0; i < num; i++) { if (solved(xs[i])) m_var_queue.insert(xs[i]); } } void schedule_var_subst(var_vector const & xs) { schedule_var_subst(xs.size(), xs.c_ptr()); } /** \brief Store as1*xs1 + k*as2*xs2 into new_as*new_xs If UpdateOcc == true, Then, 1) for each variable x occurring in xs2 but not in xs1: - eq_idx is added to m_occs[x] 2) for each variable that occurs in xs1 and xs2 and the resultant coefficient is zero, - eq_idx is removed from m_occs[x] IF x != except_var If UpdateQueue == true Then, 1) for each variable x occurring in xs2 but not in xs1: - if x is solved, then x is inserted into m_var_queue 2) for each variable that occurs in xs1 and xs2 and the resultant coefficient is zero, - if x is solved, then x is removed from m_var_queue */ template<typename Numeral, bool UpdateOcc, bool UpdateQueue> void addmul(svector<Numeral> const & as1, var_vector const & xs1, mpz const & k, svector<Numeral> const & as2, var_vector const & xs2, numeral_buffer<Numeral, numeral_manager> & new_as, var_vector & new_xs, unsigned eq_idx = null_eq_idx, var except_var = null_var) { Numeral new_a; SASSERT(as1.size() == xs1.size()); SASSERT(as2.size() == xs2.size()); new_as.reset(); new_xs.reset(); unsigned sz1 = xs1.size(); unsigned sz2 = xs2.size(); unsigned i1 = 0; unsigned i2 = 0; while (true) { if (i1 == sz1) { // copy remaining entries from as2*xs2 while (i2 < sz2) { var x2 = xs2[i2]; if (UpdateOcc) m_occs[x2].push_back(eq_idx); if (UpdateQueue && solved(x2)) m_var_queue.insert(x2); new_as.push_back(Numeral()); m().mul(k, as2[i2], new_as.back()); new_xs.push_back(x2); i2++; } break; } if (i2 == sz2) { // copy remaining entries from as1*xs1 while (i1 < sz1) { new_as.push_back(as1[i1]); new_xs.push_back(xs1[i1]); i1++; } break; } var x1 = xs1[i1]; var x2 = xs2[i2]; if (x1 < x2) { new_as.push_back(as1[i1]); new_xs.push_back(xs1[i1]); i1++; } else if (x1 > x2) { if (UpdateOcc) m_occs[x2].push_back(eq_idx); if (UpdateQueue && solved(x2)) m_var_queue.insert(x2); new_as.push_back(Numeral()); m().mul(k, as2[i2], new_as.back()); new_xs.push_back(x2); i2++; } else { m().addmul(as1[i1], k, as2[i2], new_a); TRACE("euclidean_solver_add_mul", tout << "i1: " << i1 << ", i2: " << i2 << " new_a: " << m().to_string(new_a) << "\n"; tout << "as1: " << m().to_string(as1[i1]) << ", k: " << m().to_string(k) << ", as2: " << m().to_string(as2[i2]) << "\n";); if (m().is_zero(new_a)) { // variable was canceled if (UpdateOcc && x1 != except_var) m_occs[x1].erase(eq_idx); if (UpdateQueue && solved(x1) && m_var_queue.contains(x1)) m_var_queue.erase(x1); } else { new_as.push_back(new_a); new_xs.push_back(x1); } i1++; i2++; } } m().del(new_a); } template<bool UpdateOcc, bool UpdateQueue> void apply_solution(var x, mpz_vector & as, var_vector & xs, mpz & c, mpq_vector & bs, justification_vector & js, unsigned eq_idx = null_eq_idx, var except_var = null_var) { SASSERT(solved(x)); unsigned idx = pos(xs, x); if (idx == UINT_MAX) return; mpz const & a1 = as[idx]; SASSERT(!m().is_zero(a1)); equation const & eq2 = *(m_solution[m_solved[x]]); SASSERT(eq2.pos_x(x) != UINT_MAX); SASSERT(m().is_minus_one(eq2.a(eq2.pos_x(x)))); TRACE("euclidean_solver_apply", tout << "applying: " << m().to_string(a1) << " * "; display(tout, eq2); tout << "\n"; for (unsigned i = 0; i < xs.size(); i++) tout << m().to_string(as[i]) << "*x" << xs[i] << " "; tout << "\n";); addmul<mpz, UpdateOcc, UpdateQueue>(as, xs, a1, eq2.m_as, eq2.m_xs, m_tmp_as, m_tmp_xs, eq_idx, except_var); m().addmul(c, a1, eq2.m_c, c); m_tmp_as.swap(as); m_tmp_xs.swap(xs); SASSERT(as.size() == xs.size()); TRACE("euclidean_solver_apply", for (unsigned i = 0; i < xs.size(); i++) tout << m().to_string(as[i]) << "*x" << xs[i] << " "; tout << "\n";); addmul<mpq, false, false>(bs, js, a1, eq2.m_bs, eq2.m_js, m_tmp_bs, m_tmp_xs); m_tmp_bs.swap(bs); m_tmp_xs.swap(js); SASSERT(pos(xs, x) == UINT_MAX); } void apply_solution(mpz_vector & as, var_vector & xs, mpz & c, mpq_vector & bs, justification_vector & js) { m_var_queue.reset(); schedule_var_subst(xs); while (!m_var_queue.empty()) { var x = m_var_queue.erase_min(); apply_solution<false, true>(x, as, xs, c, bs, js); } } void apply_solution(equation & eq) { apply_solution(eq.m_as, eq.m_xs, eq.m_c, eq.m_bs, eq.m_js); } void display(std::ostream & out, equation const & eq) const { unsigned num = eq.js_size(); for (unsigned i = 0; i < num; i ++) { if (i > 0) out << " "; out << m().to_string(eq.b(i)) << "*j" << eq.j(i); } if (num > 0) out << " "; out << "|= "; num = eq.size(); for (unsigned i = 0; i < num; i++) { out << m().to_string(eq.a(i)) << "*x" << eq.x(i) << " + "; } out << m().to_string(eq.c()) << " = 0"; } void display(std::ostream & out, equations const & eqs) const { unsigned num = eqs.size(); for (unsigned i = 0; i < num; i++) { if (eqs[i]) { display(out, *(eqs[i])); out << "\n"; } } } void display(std::ostream & out) const { if (inconsistent()) { out << "inconsistent: "; display(out, *(m_equations[m_inconsistent])); out << "\n"; } out << "solution set:\n"; display(out, m_solution); out << "todo:\n"; display(out, m_equations); } void add_occs(unsigned eq_idx) { equation const & eq = *(m_equations[eq_idx]); unsigned sz = eq.size(); for (unsigned i = 0; i < sz; i++) m_occs[eq.x(i)].push_back(eq_idx); } imp(numeral_manager * m): m_manager(m == 0 ? alloc(numeral_manager) : m), m_owns_m(m == 0), m_decompose_buffer(*m_manager), m_as_buffer(*m_manager), m_bs_buffer(*m_manager), m_tmp_as(*m_manager), m_tmp_bs(*m_manager), m_var_queue(16, elim_order_lt(m_solved)) { m_inconsistent = null_eq_idx; m_next_justification = 0; m_next_x = null_var; m_next_eq = null_eq_idx; } ~imp() { m().del(m_next_a); del_equations(m_equations); del_equations(m_solution); if (m_owns_m) dealloc(m_manager); } var mk_var(bool parameter) { var x = m_solved.size(); m_parameter.push_back(parameter); m_solved.push_back(null_eq_idx); m_occs.push_back(occs()); m_as_buffer.push_back(mpz()); m_var_queue.reserve(x+1); return x; } justification mk_justification() { justification r = m_next_justification; m_bs_buffer.push_back(mpq()); m_next_justification++; return r; } void assert_eq(unsigned num, mpz const * as, var const * xs, mpz const & c, justification j) { if (inconsistent()) return; equation * eq; if (j == null_justification) { eq = mk_eq(num, as, xs, c, 0, 0, 0); } else { mpq one(1); eq = mk_eq(num, as, xs, c, 1, &one, &j); } TRACE("euclidean_solver", tout << "new-eq:\n"; display(tout, *eq); tout << "\n";); unsigned eq_idx = m_equations.size(); m_equations.push_back(eq); apply_solution(*eq); normalize_eq(eq_idx); add_occs(eq_idx); TRACE("euclidean_solver", tout << "asserted:\n"; display(tout, *eq); tout << "\n";); } justification_vector const & get_justification() const { SASSERT(inconsistent()); return m_equations[m_inconsistent]->m_js; } template<typename Numeral> void neg_coeffs(svector<Numeral> & as) { unsigned sz = as.size(); for (unsigned i = 0; i < sz; i++) { m().neg(as[i]); } } void substitute_most_recent_solution(var x) { SASSERT(!m_solution.empty()); equation & eq = *(m_solution.back()); TRACE("euclidean_solver", tout << "applying solution for x" << x << "\n"; display(tout, eq); tout << "\n";); occs & use_list = m_occs[x]; occs::iterator it = use_list.begin(); occs::iterator end = use_list.end(); for (; it != end; ++it) { unsigned eq_idx = *it; // remark we don't want to update the use_list of x while we are traversing it. equation & eq2 = *(m_equations[eq_idx]); TRACE("euclidean_solver", tout << "eq before substituting x" << x << "\n"; display(tout, eq2); tout << "\n";); apply_solution<true, false>(x, eq2.m_as, eq2.m_xs, eq2.m_c, eq2.m_bs, eq2.m_js, eq_idx, x); TRACE("euclidean_solver", tout << "eq after substituting x" << x << "\n"; display(tout, eq2); tout << "\n";); normalize_eq(eq_idx); if (inconsistent()) break; } use_list.reset(); } void elim_unit() { SASSERT(m().is_one(m_next_a)); equation & eq = *(m_equations[m_next_eq]); TRACE("euclidean_solver", tout << "eliminating equation with unit coefficient:\n"; display(tout, eq); tout << "\n";); if (m_next_pos_a) { // neg coeffs... to make sure that m_next_x is -1 neg_coeffs(eq.m_as); neg_coeffs(eq.m_bs); m().neg(eq.m_c); } unsigned sz = eq.size(); for (unsigned i = 0; i < sz; i++) { m_occs[eq.x(i)].erase(m_next_eq); } m_solved[m_next_x] = m_solution.size(); m_solution.push_back(&eq); m_equations[m_next_eq] = 0; substitute_most_recent_solution(m_next_x); } void decompose(bool pos_a, mpz const & abs_a, mpz const & a_i, mpz & new_a_i, mpz & r_i) { mpz abs_a_i; bool pos_a_i = m().is_pos(a_i); m().set(abs_a_i, a_i); if (!pos_a_i) m().neg(abs_a_i); bool new_pos_a_i = pos_a_i; if (pos_a) new_pos_a_i = !new_pos_a_i; m().div(abs_a_i, abs_a, new_a_i); if (m().divides(abs_a, a_i)) { m().reset(r_i); } else { if (pos_a_i) m().submul(a_i, abs_a, new_a_i, r_i); else m().addmul(a_i, abs_a, new_a_i, r_i); } if (!new_pos_a_i) m().neg(new_a_i); m().del(abs_a_i); } void decompose_and_elim() { m_tmp_xs.reset(); mpz_buffer & buffer = m_decompose_buffer; buffer.reset(); var p = mk_var(true); mpz new_a_i; equation & eq = *(m_equations[m_next_eq]); TRACE("euclidean_solver", tout << "decompositing equation for x" << m_next_x << "\n"; display(tout, eq); tout << "\n";); unsigned sz = eq.size(); unsigned j = 0; for (unsigned i = 0; i < sz; i++) { var x_i = eq.x(i); if (x_i == m_next_x) { m().set(new_a_i, -1); buffer.push_back(new_a_i); m_tmp_xs.push_back(m_next_x); m_occs[x_i].erase(m_next_eq); } else { decompose(m_next_pos_a, m_next_a, eq.a(i), new_a_i, eq.m_as[j]); buffer.push_back(new_a_i); m_tmp_xs.push_back(x_i); if (m().is_zero(eq.m_as[j])) { m_occs[x_i].erase(m_next_eq); } else { eq.m_xs[j] = x_i; j++; } } } SASSERT(j < sz); // add parameter: p to new equality, and m_next_pos_a * m_next_a * p to current eq m().set(new_a_i, 1); buffer.push_back(new_a_i); m_tmp_xs.push_back(p); m().set(eq.m_as[j], m_next_a); if (!m_next_pos_a) m().neg(eq.m_as[j]); eq.m_xs[j] = p; j++; unsigned new_sz = j; // shrink current eq for (; j < sz; j++) m().del(eq.m_as[j]); eq.m_as.shrink(new_sz); eq.m_xs.shrink(new_sz); // ajust c mpz new_c; decompose(m_next_pos_a, m_next_a, eq.m_c, new_c, eq.m_c); // create auxiliary equation equation * new_eq = mk_eq(m_tmp_xs.size(), buffer.c_ptr(), m_tmp_xs.c_ptr(), new_c, 0, 0, 0, false); // new_eq doesn't need to normalized, since it has unit coefficients TRACE("euclidean_solver", tout << "decomposition: new parameter x" << p << " aux eq:\n"; display(tout, *new_eq); tout << "\n"; display(tout, eq); tout << "\n";); m_solved[m_next_x] = m_solution.size(); m_solution.push_back(new_eq); substitute_most_recent_solution(m_next_x); m().del(new_a_i); m().del(new_c); } bool solve() { if (inconsistent()) return false; TRACE("euclidean_solver", tout << "solving...\n"; display(tout);); while (select_next_var()) { CTRACE("euclidean_solver_bug", m_next_x == null_var, display(tout);); TRACE("euclidean_solver", tout << "eliminating x" << m_next_x << "\n";); if (m().is_one(m_next_a) || m().is_minus_one(m_next_a)) elim_unit(); else decompose_and_elim(); TRACE("euclidean_solver", display(tout);); if (inconsistent()) return false; } return true; } bool inconsistent() const { return m_inconsistent != null_eq_idx; } bool is_parameter(var x) const { return m_parameter[x]; } void normalize(unsigned num, mpz const * as, var const * xs, mpz const & c, mpz & a_prime, mpz & c_prime, justification_vector & js) { TRACE("euclidean_solver", tout << "before applying solution set\n"; for (unsigned i = 0; i < num; i++) { tout << m().to_string(as[i]) << "*x" << xs[i] << " "; } tout << "\n";); m_norm_xs_vector.reset(); m_norm_as_vector.reset(); for (unsigned i = 0; i < num; i++) { m_norm_xs_vector.push_back(xs[i]); m_norm_as_vector.push_back(mpz()); m().set(m_norm_as_vector.back(), as[i]); } sort(m_norm_as_vector, m_norm_xs_vector, m_as_buffer); m_norm_bs_vector.reset(); js.reset(); m().set(c_prime, c); apply_solution(m_norm_as_vector, m_norm_xs_vector, c_prime, m_norm_bs_vector, js); TRACE("euclidean_solver", tout << "after applying solution set\n"; for (unsigned i = 0; i < m_norm_as_vector.size(); i++) { tout << m().to_string(m_norm_as_vector[i]) << "*x" << m_norm_xs_vector[i] << " "; } tout << "\n";); // compute gcd of the result m_norm_as_vector if (m_norm_as_vector.empty()) { m().set(a_prime, 0); } else { mpz a; m().set(a_prime, m_norm_as_vector[0]); m().abs(a_prime); unsigned sz = m_norm_as_vector.size(); for (unsigned i = 1; i < sz; i++) { if (m().is_one(a_prime)) break; m().set(a, m_norm_as_vector[i]); m().abs(a); m().gcd(a_prime, a, a_prime); } m().del(a); } // REMARK: m_norm_bs_vector contains the linear combination of the justifications. It may be useful if we // decided (one day) to generate detailed proofs for this step. del_nums(m_norm_as_vector); del_nums(m_norm_bs_vector); } }; euclidean_solver::euclidean_solver(numeral_manager * m): m_imp(alloc(imp, m)) { } euclidean_solver::~euclidean_solver() { dealloc(m_imp); } euclidean_solver::numeral_manager & euclidean_solver::m() const { return m_imp->m(); } void euclidean_solver::reset() { numeral_manager * m = m_imp->m_manager; bool owns_m = m_imp->m_owns_m; m_imp->m_owns_m = false; dealloc(m_imp); m_imp = alloc(imp, m); m_imp->m_owns_m = owns_m; } euclidean_solver::var euclidean_solver::mk_var() { return m_imp->mk_var(false); } euclidean_solver::justification euclidean_solver::mk_justification() { return m_imp->mk_justification(); } void euclidean_solver::assert_eq(unsigned num, mpz const * as, var const * xs, mpz const & c, justification j) { m_imp->assert_eq(num, as, xs, c, j); } bool euclidean_solver::solve() { return m_imp->solve(); } euclidean_solver::justification_vector const & euclidean_solver::get_justification() const { return m_imp->get_justification(); } bool euclidean_solver::inconsistent() const { return m_imp->inconsistent(); } bool euclidean_solver::is_parameter(var x) const { return m_imp->is_parameter(x); } void euclidean_solver::normalize(unsigned num, mpz const * as, var const * xs, mpz const & c, mpz & a_prime, mpz & c_prime, justification_vector & js) { return m_imp->normalize(num, as, xs, c, a_prime, c_prime, js); } void euclidean_solver::display(std::ostream & out) const { m_imp->display(out); }
[ "nikaponens@gmail.com" ]
nikaponens@gmail.com
c687408876c520061be8235999944711d40863c6
308f3cb8a30fcacd8851cc2ed979949b643cf1d9
/bzoj__orzliyicheng/p1237.cpp
9a552c45fea54165cab3c3206e0ace5591729bc0
[]
no_license
szh-bash/ACM
9a49859644d077bcb40f90dbac33d88649e7b0f3
3ddab1ab8f9b8a066f012f2978ee9519d00aec54
refs/heads/master
2022-08-08T19:20:09.912359
2022-07-20T10:43:57
2022-07-20T10:43:57
98,170,219
5
0
null
null
null
null
UTF-8
C++
false
false
889
cpp
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; typedef long long ll; const ll inf=10000000000009LL; #define abs(x) (((x)<0)?(-(x)):(x)) #define A(x,y) ((x==y)?inf:abs((x)-(y))) ll n,a[100005],b[100005],f[100005]; char buf[2000000],*p=buf; inline int getint(){ ll r=0; while(*p<'0'||*p>'9')p++; while(*p>='0'&&*p<='9')r=r*10+*p++-48;return r; }int main(){ fread(p,1,2000000,stdin); n=getint(); for(ll i=1;i<=n;i++)a[i]=getint(),b[i]=getint(); sort(a+1,a+n+1); sort(b+1,b+n+1); f[1]=A(a[1],b[1]); f[2]=min(f[1]+A(a[2],b[2]),A(a[1],b[2])+A(a[2],b[1])); for(ll i=3;i<=n;i++)f[i]=min(f[i-1]+A(a[i],b[i]),min(f[i-2]+A(a[i-1],b[i])+A(a[i],b[i-1]),min(f[i-3]+A(a[i],b[i-1])+A(a[i-1],b[i-2])+A(a[i-2],b[i]),f[i-3]+A(a[i],b[i-2])+A(a[i-1],b[i])+A(a[i-2],b[i-1])))); printf("%lld\n",f[n]==inf?-1LL:f[n]); return 0; }
[ "342333349@qq.com" ]
342333349@qq.com
904e9b852ca21ca230939af2f5cca46d8778e20a
fa3a850e413f7ba655eed6ad009e075e0f0e3286
/cpp_d06_2019/hospital/KoalaDoctorList.hpp
606313c6c86e139e66199c085883cc2ba866547e
[]
no_license
Pavlograd/Piscine-CPP-2020
fa31d3f45fdafddb88215c0a48a35076a0706100
3cdd6a1a9d4354aa48aada4834a7d2edbd5f2f59
refs/heads/master
2022-11-12T02:07:09.912933
2020-07-05T19:35:19
2020-07-05T19:35:19
277,366,066
0
0
null
null
null
null
UTF-8
C++
false
false
640
hpp
/* ** EPITECH PROJECT, 2020 ** KoalaDoctorList ** File description: ** KoalaDoctorList */ #ifndef KoalaDoctorList_Ex05 #define KoalaDoctorList_Ex05 #include "KoalaDoctor.hpp" #include <list> class KoalaDoctorList { public: KoalaDoctorList(KoalaDoctor *koala); ~KoalaDoctorList(); bool isEnd(); void append(KoalaDoctorList *newNode); KoalaDoctor *getFromName(std::string koalaName); KoalaDoctorList *remove(KoalaDoctorList *toRemove); KoalaDoctorList *removeFromName(std::string koalaName); void dump(); protected: private: KoalaDoctor *m_koala; KoalaDoctorList *next; }; #endif /* !KoalaDoctorList_Ex05 */
[ "noreply@github.com" ]
Pavlograd.noreply@github.com
f2ba86b536158bc9c8d8f1536468b0dcddc82612
4eb4242f67eb54c601885461bac58b648d91d561
/algorithm/poj/2337/code.cc
83707f4d5504837a6677c71b0068c72b069ca86e
[]
no_license
biebipan/coding
630c873ecedc43a9a8698c0f51e26efb536dabd1
7709df7e979f2deb5401d835d0e3b119a7cd88d8
refs/heads/master
2022-01-06T18:52:00.969411
2018-07-18T04:30:02
2018-07-18T04:30:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,088
cc
// Copyright 2013 Jike Inc. All Rights Reserved. // Author: Liqiang Guo(guoliqiang@jike.com) // I just want to GH to hss~ // Date : 2013-11-13 19:10:49 // File : code.cc // Brief : /* * 单词作为边,节点是26个字符,这样的构图才是可以用 * 欧拉路来做的 * Accepted 424K 47MS * */ #include "base/public/common_ojhead.h" namespace algorithm { const int MAXN = 30; const int MAXM = 1010; const int N = MAXN; int M = 0; int begin = 0; struct Edge { int v; int visited; std::string str; bool operator < (const Edge & e2) const { return str < e2.str; } }; std::vector<Edge> head[MAXN]; int in[MAXN]; int out[MAXN]; int root[MAXN]; int used[MAXN]; std::stack<std::string> stack; int find(int k) { if (root[k] == k) return root[k]; return root[k] = find(root[k]); } void unit(int x, int y) { int tx = find(x); int ty = find(y); root[tx] = root[ty]; } bool Connect() { int cnt = 0; for (int i = 0; i < N; i++) { if (used[i] && find(i) == i) cnt++; } return cnt == 1 ? true : false; } bool Key(int & key) { int in_num = 0; int out_num = 0; for (int i = 0; i < N; i++) { if (used[i]) { if (in[i] == out[i]) continue; else if (in[i] - out[i] == 1) in_num++; else if (out[i] - in[i] == 1) { out_num++; key = i; } else { return false; } } } if (in_num == 1 && out_num == 1) return true; else if (in_num == 0 && out_num == 0) { for (int i = 0; i < N; i++) { if (used[i]) { key = i; break; } } return true; } else { return false; } } // NB void Fleury(int key) { for (int i = 0; i < head[key].size(); i++) { if (head[key][i].visited == 0) { head[key][i].visited = 1; Fleury(head[key][i].v); stack.push(head[key][i].str); } } } void Path() { printf("%s", stack.top().c_str()); stack.pop(); while(!stack.empty()) { printf(".%s", stack.top().c_str()); stack.pop(); } printf("\n"); } void Read() { int c = 0; scanf("%d", &c); getchar(); for (int i = 0; i < c; i++) { int n = 0; scanf("%d", &n); getchar(); char temp[25]; memset(in, 0, sizeof(in)); memset(out, 0, sizeof(out)); memset(used, 0, sizeof(used)); for (int i = 0; i < N; i++) { root[i] = i; head[i].clear(); } for (int j = 0; j < n; j++) { scanf("%s", temp); getchar(); int len = strlen(temp); int u = temp[0] - 'a'; int v = temp[len - 1] - 'a'; Edge t; t.v = v; t.visited = 0; t.str = std::string(temp); head[u].push_back(t); unit(v, u); in[v]++; out[u]++; used[u] = used[v] = 1; } for (int i = 0; i < N; i++) { if (used[i]) std::sort(head[i].begin(), head[i].end()); } int key = 0; if (!Connect() || !Key(key)) { printf("***\n"); } else { Fleury(key); Path(); } } } } // namespace algorithm using namespace algorithm; int main(int argc, char** argv) { FROMFILE; Read(); return 0; }
[ "guoliqiang2006@126.com" ]
guoliqiang2006@126.com
185c576c41ae5ab485510ba6776760d6ef6ddf5a
ae99db8a12c4e22a6e844100144babc5f452a152
/DSA/Leetcode/121.cc
dfd64d9e69b72d5ec468427340e3af15e6f4cf23
[ "MIT" ]
permissive
zhmz90/Lan
6d7591344029b80e16c39b41cddce500bcf32418
d7bb1b38ecb5a082276efaafdadca8d9700fbc27
refs/heads/master
2021-01-21T12:53:58.281744
2017-07-21T11:54:45
2017-07-21T11:54:45
48,616,087
0
0
null
null
null
null
UTF-8
C++
false
false
1,359
cc
/** 121. Best Time to Buy and Sell Stock Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. Example 1: Input: [7, 1, 5, 3, 6, 4] Output: 5 max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price) Example 2: Input: [7, 6, 4, 3, 1] Output: 0 In this case, no transaction is done, i.e. max profit = 0. */ #include <iostream> #include <vector> #include <algorithm> using namespace std; class Solution { public: int maxProfit(vector<int>& prices) { int buy=0,sell=0; if (prices.size() <= 1) return 0; buy = prices[0], sell = buy; vector<int> profits{}; for (auto iter=prices.begin()+1,end=prices.end(); iter!=end; iter++){ if (*iter < buy) { profits.push_back(sell-buy); buy = *iter; sell = *iter; } if (*iter > sell) sell = *iter; } profits.push_back(sell-buy); // for (auto p: profits) cout<<p<<" "; cout<<endl; return *max_element(profits.begin(),profits.end()); } }; int main(){ Solution solu; vector<int> prices{7,1,5,3,6,4}; for (auto p: prices) cout<<p<<" "; cout<<endl; cout<<solu.maxProfit(prices)<<endl; return 0; }
[ "zhmz90@gmail.com" ]
zhmz90@gmail.com
05b37699a4808e786a867a58d6833c6554d5df4b
ffd9e6bb9e3ceb48f07ad48a9ea5f7816a9db7c0
/src/primitives/block.h
9fa1861fe64e638a86067166244d0a49b3a478c6
[ "MIT" ]
permissive
weigun/MagnaChain-dev-master
0a26a48cbd617b4a6e2bc610d27b779d4022e18b
a7587b10072cca03a6c7a6a44cba1b6f2a202af6
refs/heads/master
2020-05-01T16:21:32.855483
2019-03-23T06:42:01
2019-03-23T06:42:01
175,793,168
0
0
MIT
2019-03-15T09:50:45
2019-03-15T09:50:42
null
UTF-8
C++
false
false
4,601
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Copyright (c) 2016-2019 The MagnaChain Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef MAGNACHAIN_PRIMITIVES_BLOCK_H #define MAGNACHAIN_PRIMITIVES_BLOCK_H #include "primitives/transaction.h" #include "io/serialize.h" #include "coding/uint256.h" const int MAX_GROUP_NUM = 16; /** Nodes collect new transactions into a block, hash them into a hash tree, * and scan through nonce values to make the block's hash satisfy proof-of-work * requirements. When they solve the proof-of-work, they broadcast the block * to everyone and the block is added to the block chain. The first transaction * in the block is a special one that creates a new coin owned by the creator * of the block. */ class MCBlockHeader { public: // header int32_t nVersion; uint256 hashPrevBlock; uint256 hashMerkleRoot; uint256 hashMerkleRootWithData; uint256 hashMerkleRootWithPrevData; uint32_t nTime; uint32_t nBits; uint32_t nNonce; // this value in bitcion are added for make different hash, we use to indicate the amount of miner's address MCOutPoint prevoutStake; MCScript vchBlockSig; MCBlockHeader() { SetNull(); } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { READWRITE(this->nVersion); READWRITE(hashPrevBlock); READWRITE(hashMerkleRoot); READWRITE(hashMerkleRootWithData); READWRITE(hashMerkleRootWithPrevData); READWRITE(nTime); READWRITE(nBits); READWRITE(nNonce); READWRITE(prevoutStake); if (!(s.GetType() & SER_WITHOUT_SIGN)) READWRITE(vchBlockSig); } void SetNull() { nVersion = 0; hashPrevBlock.SetNull(); hashMerkleRoot.SetNull(); hashMerkleRootWithData.SetNull(); hashMerkleRootWithPrevData.SetNull(); nTime = 0; nBits = 0; nNonce = 0; vchBlockSig.clear(); prevoutStake.SetNull(); } bool IsNull() const { return (nBits == 0); } uint256 GetHash() const; uint256 GetHashNoSignData() const; int64_t GetBlockTime() const { return (int64_t)nTime; } }; class MCBlock : public MCBlockHeader { public: // network and disk std::vector<MCTransactionRef> vtx; std::vector<uint16_t> groupSize; std::vector<ContractPrevData> prevContractData; // memory only mutable bool fChecked; MCBlock() { SetNull(); } MCBlock(const MCBlockHeader &header) { SetNull(); *((MCBlockHeader*)this) = header; } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { READWRITE(*(MCBlockHeader*)this); READWRITE(vtx); READWRITE(groupSize); READWRITE(prevContractData); } void SetNull() { MCBlockHeader::SetNull(); vtx.clear(); groupSize.clear(); prevContractData.clear(); fChecked = false; } MCBlockHeader GetBlockHeader() const { MCBlockHeader block; block.nVersion = nVersion; block.hashPrevBlock = hashPrevBlock; block.hashMerkleRoot = hashMerkleRoot; block.hashMerkleRootWithData = hashMerkleRootWithData; block.hashMerkleRootWithPrevData = hashMerkleRootWithPrevData; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; return block; } }; /** Describes a place in the block chain to another node such that if the * other node doesn't have the same branch, it can find a recent common trunk. * The further back it is, the further before the fork it may be. */ struct MCBlockLocator { std::vector<uint256> vHave; MCBlockLocator() {} MCBlockLocator(const std::vector<uint256>& vHaveIn) : vHave(vHaveIn) {} ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { int nVersion = s.GetVersion(); if (!(s.GetType() & SER_GETHASH)) READWRITE(nVersion); READWRITE(vHave); } void SetNull() { vHave.clear(); } bool IsNull() const { return vHave.empty(); } }; #endif // MAGNACHAIN_PRIMITIVES_BLOCK_H
[ "weigun@weigun.com" ]
weigun@weigun.com
4cdaa9370b5fb6d0b40ad7bbfeb3f246dc9ef91b
16c6035c8b20b58937e527081ddeb10f508e9034
/ros_ws/devel/include/piksi_rtk_msgs/ImuRawMulti.h
b703ad07c8ffe7ca6086169b170b00d7f24bdfcd
[ "MIT" ]
permissive
njoubert/tgdriver
77d082ab9a6537327de74276eb81f8cba6ebb323
e46ce6d89488116136a56805abfafe3b0d979ee1
refs/heads/master
2020-07-04T08:46:35.637633
2019-08-04T06:15:03
2019-08-04T06:15:03
192,004,866
0
0
null
null
null
null
UTF-8
C++
false
false
8,186
h
// Generated by gencpp from file piksi_rtk_msgs/ImuRawMulti.msg // DO NOT EDIT! #ifndef PIKSI_RTK_MSGS_MESSAGE_IMURAWMULTI_H #define PIKSI_RTK_MSGS_MESSAGE_IMURAWMULTI_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> #include <std_msgs/Header.h> namespace piksi_rtk_msgs { template <class ContainerAllocator> struct ImuRawMulti_ { typedef ImuRawMulti_<ContainerAllocator> Type; ImuRawMulti_() : header() , tow(0) , tow_f(0) , acc_x(0) , acc_y(0) , acc_z(0) , gyr_x(0) , gyr_y(0) , gyr_z(0) { } ImuRawMulti_(const ContainerAllocator& _alloc) : header(_alloc) , tow(0) , tow_f(0) , acc_x(0) , acc_y(0) , acc_z(0) , gyr_x(0) , gyr_y(0) , gyr_z(0) { (void)_alloc; } typedef ::std_msgs::Header_<ContainerAllocator> _header_type; _header_type header; typedef uint32_t _tow_type; _tow_type tow; typedef uint8_t _tow_f_type; _tow_f_type tow_f; typedef int16_t _acc_x_type; _acc_x_type acc_x; typedef int16_t _acc_y_type; _acc_y_type acc_y; typedef int16_t _acc_z_type; _acc_z_type acc_z; typedef int16_t _gyr_x_type; _gyr_x_type gyr_x; typedef int16_t _gyr_y_type; _gyr_y_type gyr_y; typedef int16_t _gyr_z_type; _gyr_z_type gyr_z; typedef boost::shared_ptr< ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator> const> ConstPtr; }; // struct ImuRawMulti_ typedef ::piksi_rtk_msgs::ImuRawMulti_<std::allocator<void> > ImuRawMulti; typedef boost::shared_ptr< ::piksi_rtk_msgs::ImuRawMulti > ImuRawMultiPtr; typedef boost::shared_ptr< ::piksi_rtk_msgs::ImuRawMulti const> ImuRawMultiConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator> & v) { ros::message_operations::Printer< ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace piksi_rtk_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': True} // {'sensor_msgs': ['/opt/ros/melodic/share/sensor_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/melodic/share/geometry_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/melodic/share/std_msgs/cmake/../msg'], 'piksi_rtk_msgs': ['/home/gecko/Code/tgdriver/ros_ws/src/ethz_piksi_ros/piksi_rtk_msgs/msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator> const> : TrueType { }; template<class ContainerAllocator> struct MD5Sum< ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator> > { static const char* value() { return "e32f07f6279690082bb3d37f42a5fc90"; } static const char* value(const ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0xe32f07f627969008ULL; static const uint64_t static_value2 = 0x2bb3d37f42a5fc90ULL; }; template<class ContainerAllocator> struct DataType< ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator> > { static const char* value() { return "piksi_rtk_msgs/ImuRawMulti"; } static const char* value(const ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator> > { static const char* value() { return "# Raw data from the Inertial Measurement Unit, containing accelerometer and gyroscope readings.\n" "\n" "Header header\n" "\n" "uint32 tow # Milliseconds since start of GPS week. If the high bit is set, the time is unknown or invalid.\n" "uint8 tow_f # Milliseconds since start of GPS week, fractional part.\n" "int16 acc_x # Acceleration in the body frame X axis.\n" "int16 acc_y # Acceleration in the body frame Y axis.\n" "int16 acc_z # Acceleration in the body frame Z axis.\n" "int16 gyr_x # Angular rate around the body frame X axis.\n" "int16 gyr_y # Angular rate around the body frame Y axis.\n" "int16 gyr_z # Angular rate around the body frame Z axis.\n" "\n" "================================================================================\n" "MSG: std_msgs/Header\n" "# Standard metadata for higher-level stamped data types.\n" "# This is generally used to communicate timestamped data \n" "# in a particular coordinate frame.\n" "# \n" "# sequence ID: consecutively increasing ID \n" "uint32 seq\n" "#Two-integer timestamp that is expressed as:\n" "# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n" "# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n" "# time-handling sugar is provided by the client library\n" "time stamp\n" "#Frame this data is associated with\n" "string frame_id\n" ; } static const char* value(const ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.header); stream.next(m.tow); stream.next(m.tow_f); stream.next(m.acc_x); stream.next(m.acc_y); stream.next(m.acc_z); stream.next(m.gyr_x); stream.next(m.gyr_y); stream.next(m.gyr_z); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct ImuRawMulti_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator>& v) { s << indent << "header: "; s << std::endl; Printer< ::std_msgs::Header_<ContainerAllocator> >::stream(s, indent + " ", v.header); s << indent << "tow: "; Printer<uint32_t>::stream(s, indent + " ", v.tow); s << indent << "tow_f: "; Printer<uint8_t>::stream(s, indent + " ", v.tow_f); s << indent << "acc_x: "; Printer<int16_t>::stream(s, indent + " ", v.acc_x); s << indent << "acc_y: "; Printer<int16_t>::stream(s, indent + " ", v.acc_y); s << indent << "acc_z: "; Printer<int16_t>::stream(s, indent + " ", v.acc_z); s << indent << "gyr_x: "; Printer<int16_t>::stream(s, indent + " ", v.gyr_x); s << indent << "gyr_y: "; Printer<int16_t>::stream(s, indent + " ", v.gyr_y); s << indent << "gyr_z: "; Printer<int16_t>::stream(s, indent + " ", v.gyr_z); } }; } // namespace message_operations } // namespace ros #endif // PIKSI_RTK_MSGS_MESSAGE_IMURAWMULTI_H
[ "ottotechnogecko@gmail.com" ]
ottotechnogecko@gmail.com
845e398f5a8050062ee9de1415d037caf0c5fa41
c76bca6811a24c4434209bcc0d5736118886e88c
/week8/assignment/Main.cpp
cfc28219387a49af89b199dc4a8106ce0f116684
[]
no_license
Ellard24/CS162
bb2c161f844beef11d2306839144854679d2a481
8335e6b9c700f467763bf1b230102db3e9b57539
refs/heads/master
2021-01-10T17:13:29.458696
2016-03-17T17:20:07
2016-03-17T17:20:07
54,130,981
0
0
null
null
null
null
UTF-8
C++
false
false
6,796
cpp
/***************************************************************************************************** **Author: Ellard Gerritsen van der Hoop **Description: This program will ask users to input what fighters they want to put against each other. ** The program will then create these fighters with appropriate stats and put them through ** a combat scenario. Winners stay in the LineUp and losers get moved to the LoserPile. **Input: All input is taken during runtime **Output: Displays all actions regarding combat between the fighters to the screen. Displays score and winners as well. *****************************************************************************************/ #include "Creature.h" #include "Barbarian.h" #include "Blue.h" #include "Goblin.h" #include "Reptile.h" #include "Shadow.h" #include "Game.h" #include <time.h> #include <iostream> #include "Queue.h" #include "Stack.h" using namespace std; void display(Queue &q, int size); void combat1(Queue &p1, Queue &p2, Stack &sp1, int &total1, int &total2, Combat &game1); /****************************************************************** **Function: Main **Description: Sets time seed, initializes options, creates Game, and then calls other functions that handle the combat. Queue and Stack is also made that allows fighters to be moved to corresponding struct **Parameters: - **Pre-Conditions:- **Post-Conditions: Fighters will be created and pitted against each other ********************************************************************/ int main() { srand(time(0)); cout << "This program pits a variety of creatures against each other in a Fantasy Combat Game" << endl; cout << "Two players will have the option to pick their LineUp and then battle it out" << endl; cout << "Player 1 will decide the size of the LineUp and then both players can pick from 5 monsters" << endl; cout << endl; cout << endl; int lineSize = 0; int totalP1 = 0; int totalP2 = 0; cout << "Player1: Please decide the size of the LineUp" << endl; cin >> lineSize; Queue p1LineUp; Queue p2LineUp; Stack p1Loser; Stack p2Loser; Combat game; cout << "Player 1 picks first" << endl; display(p1LineUp, lineSize); cout << "Player 2 now gets to pick" << endl; display(p2LineUp, lineSize); combat1(p1LineUp, p2LineUp, p1Loser, totalP1, totalP2, game); cout << "Losing Pile" << endl; p1Loser.display(); cout << endl; //send rest of winning team to pile and then pick out last 3 to pick first, second , third place if (p1LineUp.getSize() > 0) { while (p1LineUp.getSize() > 0) { p1Loser.addFighter(p1LineUp.returnFront()); p1LineUp.removeFighter(); } } if (p2LineUp.getSize() > 0) { while (p2LineUp.getSize() > 0) { p1Loser.addFighter(p2LineUp.returnFront()); p2LineUp.removeFighter(); } } //Deletes last 3 nodes from stack cout << "First Place: " << endl; cout << p1Loser.returnWinners(); cout << endl; cout << "Second Place: " << endl; cout << p1Loser.returnWinners(); cout << endl; cout << "Third Place: " << endl; cout << p1Loser.returnWinners(); cout << endl; //Player 1 total score cout << "Player 1's total score is " << totalP1 << endl; //Player 2 total score cout << "Player 2's total score is " << totalP2 << endl; if (totalP1 > totalP2) cout << "Player 1 wins" << endl; else if (totalP2 > totalP1) cout << "Player 2 wins" << endl; else cout << "Its a tie, which isnt possible" << endl; return 0; } /****************************************************************** **Function: Display **Description: Displays the instructions and lets user pick fighters **Parameters: Queue &q, int size **Pre-Conditions: Queue needs to exist, and size needs to be initialized **Post-Conditions: Parameters are used to create fighters ********************************************************************/ void display(Queue &q, int size) { int count = size; do { int selection = 0; string displayName; cout << "Select the fighter type that you want to add (" << count << " fighters remaining):" << endl; cout << "1. Barbarian" << endl; cout << "2. BlueMen" << endl; cout << "3. Reptile Men" << endl; cout << "4. Goblin" << endl; cout << "5. The Shadow" << endl; cout << "Selection: " << endl; cin >> selection; if (selection > 0 && selection < 6) { if (selection == 1) { q.addFighter(new Barbarian); q.display(); cout << endl; } if (selection == 2) { q.addFighter(new Blue); q.display(); cout << endl; } if (selection == 3) { q.addFighter(new Reptile); q.display(); cout << endl; } if (selection == 4) { q.addFighter(new Goblin); q.display(); cout << endl; } if (selection == 5) { q.addFighter(new Shadow); q.display(); cout << endl; } count--; } } while (count > 0); } /********************************************************** **Function: combat1 **Description: Takes care of the combat. Moves fighters to appropriate struct based on performance. Keeps track of score **Parameters: Queue &p1, Queue &p2, Stack &sp1, int &total1, int &total2, Combat &game1 **Pre-Conditions: All Queues and Stack needs to be created, totals initialized, and game initialized **Post-Conditions: Combat determines which player will win. ****************************************************************/ void combat1(Queue &p1, Queue &p2, Stack &sp1,int &total1, int &total2, Combat &game1) { while (p1.getSize() > 0 && p2.getSize() > 0) { game1.attack1(p1.returnFront(), p2.returnFront()); if (p1.returnFront()->getStrength() <= 0) { cout << p2.returnFront()->getName() << " wins this round" << endl; sp1.addFighter(p1.returnFront()); p1.removeFighter(); cout << p2.returnFront()->getName() << " drinks a potion" << endl; p2.returnFront()->drinkPotion(); p2.returnFront()->increaseScore(); total2++; if (p2.getSize() > 1) p2.moveBack(); } else { cout << p1.returnFront()->getName() << " wins this round" << endl; sp1.addFighter(p2.returnFront()); p2.removeFighter(); cout << p1.returnFront()->getName() << " drinks a potion" << endl; p1.returnFront()->drinkPotion(); p1.returnFront()->increaseScore(); total1++; if (p1.getSize() > 1) p1.moveBack(); } cout << "Do you want to see the current score? Type 'yes' if you want " << endl; string scoreChoice; cin >> scoreChoice; if (scoreChoice == "yes") { cout << "Team One's Current Score: " << total1 << endl; cout << "Team Two's Current Score: " << total2 << endl; } else { cout << "Next round is starting" << endl; } } }
[ "egvdh@comcast.net" ]
egvdh@comcast.net
cea0d5569a18a621c0adca0c86705e137e5e9aec
e0548caf7bd8153f8d991b7d7c1bed487402f0bc
/semestr-5/Algorytmy i struktury danych 1/PRO/programy-z-cwiczen/2019/C07/ID03P06/C07_ID03P06_0001/include/TabInt01.h
d35ed144317ad8076de84fd129371b57ff7ed087
[]
no_license
Ch3shireDev/WIT-Zajecia
58d9ca03617ba07bd25ce439aeeca79533f0bcb6
3cd4f7dea6abdf7126c44a1d856ca5b6002813ca
refs/heads/master
2023-09-01T11:32:12.636305
2023-08-28T16:48:03
2023-08-28T16:48:03
224,985,239
19
24
null
2023-07-02T20:54:18
2019-11-30T08:57:27
C
UTF-8
C++
false
false
758
h
#ifndef TABINT01_H #define TABINT01_H ///213.135.46.21:7070 ///\\sz240\temp\PRO #include <iostream> #include<ctime> using std::cout; using std::cin; using std::string; using std::endl; using std::to_string; using std::ostream; ///********************************** ///********************************** class TabInt01{ public: TabInt01(int=0); TabInt01(const TabInt01&); TabInt01& operator=(const TabInt01&); ~TabInt01(); int Length(); int* PT(); int& Value(int); int& operator[](int); private: int sT; int *pT; friend ostream& operator<<(ostream&, TabInt01&); }; ///********************************** #endif // TABINT01_H
[ "thesmilingcatofcheshire@gmail.com" ]
thesmilingcatofcheshire@gmail.com
3806098444e7b001fa171d3d3fe45ebcafe5df26
68843a3957f49255aa0aacd7dc99a541a38e3c72
/STEP1/Scene.h
298f4f4e3589fe19d7707b49f0903546f2d58dc8
[]
no_license
gamorejon/cell-ray
61fec3e9c7df7146c77ce76ef0cd0df984709208
8f567f6c3741cf75d4bb2a0d67b53c0b050cfc6b
refs/heads/master
2021-01-19T12:12:34.567177
2012-08-10T21:47:16
2012-08-10T21:47:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,139
h
#ifndef SCENE_H #define SCENE_H #include <vector> #include <cmath> using namespace std; #include <altivec.h> #include "SceneObject.h" #include "ColorGroup.h" #include "Intersection.h" #include "Light.h" #include "AltivecUtils.h" #include "VectorSInt.h" class Scene { private: SceneObject** objects; Light** lights; ColorGroup* ambientColor; int objectsSize; int lightsSize; VertexGroup* lightV; VertexGroup* reflectionStart; VertexGroup* centers; VectorSInt* minIndexVec; ColorGroup* surfaceColorGroup; vector float getSpec(int index) { if (index == -1) { return negativeZero(); } else { return getSceneObject(index)->getSpecularReflection(); } } vector float getPt(int index, int number) { if (index == -1) { return negativeZero(); } else { VertexGroup* center = getSceneObject(index)->getCenter(); switch (number) { case 1: return center->x; case 2: return center->y; case 3: return center->z; default: return negativeZero(); } } } vector float getDiff(int index, int number) { if (index == -1) { return negativeZero(); } else { ColorGroup* diff = getSceneObject(index)->getDiffusionColor(); switch (number) { case 1: return diff->r; case 2: return diff->g; case 3: return diff->b; default: return negativeZero(); } } } public: Scene(Light** _lights, int _lightsSize, SceneObject** _objects, int _objectsSize, Color* _ambientColor) { lights = _lights; lightsSize = _lightsSize; objects = _objects; objectsSize = _objectsSize; ambientColor = new ColorGroup(*_ambientColor); Color zero = Color(); surfaceColorGroup = new ColorGroup(zero); lightV = new VertexGroup(Vertex()); reflectionStart = new VertexGroup(Vertex()); centers = new VertexGroup(Vertex()); minIndexVec = new VectorSInt(); delete _ambientColor; } ~Scene() { /* cout << "Beginning scene delete" << endl; for (int i = 0; i < objectsSize; i++) { cout << "Deleting object " << i << endl; // delete objects[i]; cout << "Deleted object " << i << endl; } for (int i = 0; i < lightsSize; i++) { cout << "Deleting light " << i << endl; // delete lights[i]; } cout << "Deleting[] objects" << endl; delete[] objects; delete[] lights; delete ambientColor; cout << "After ambientColor" << endl; delete lightV; delete reflectionStart; delete centers; delete minIndexVec; delete surfaceColorGroup; cout << "End scene delete" << endl;*/ } SceneObject* getSceneObject(int index) { return objects[index]; } Light* getLight(int index) { return lights[index]; } int getSceneObjectsSize() { return objectsSize; } int getLightsSize() { return lightsSize; } void getIntersection(Ray* ray, Intersection& intersection) { vector float distance = negativeZero(); vector int minIndex = vec_splat_s32(-1); vector float minDistance = splatScalar(1000.0f); vector unsigned int boolZero = vec_splat_u32(0); vector bool int anyHit = (vector bool int)boolZero; SceneObject* object; // TODO: keeping the SceneObject is Sphere specific, and not good. for (int i = 0; i < getSceneObjectsSize(); i++) { object = getSceneObject(i); vector bool int hit = object->isIntersected(ray, reflectionStart, intersection.hit); if (vec_all_eq(hit, boolZero)) { continue; } anyHit = vec_or(hit, anyHit); distance = vec_and(ray->start->distance2(*reflectionStart), hit); vector bool int distCmp = vec_and(vec_cmplt(distance, minDistance), hit); vector int iSplat = splatScalar(i); minIndex = vec_sel(minIndex, iSplat, distCmp); minDistance = vec_sel(minDistance, distance, distCmp); VertexGroup* refStart = intersection.reflection->start; refStart->x = vec_sel(refStart->x, reflectionStart->x, distCmp); refStart->y = vec_sel(refStart->y, reflectionStart->y, distCmp); refStart->z = vec_sel(refStart->z, reflectionStart->z, distCmp); } intersection.hit = vec_and(anyHit, intersection.hit); if (vec_any_gt(intersection.hit, boolZero)) { minIndexVec->vec = minIndex; intersection.minIndex = minIndexVec; int m1 = minIndexVec->points[0]; int m2 = minIndexVec->points[1]; int m3 = minIndexVec->points[2]; int m4 = minIndexVec->points[3]; vector float _13x = vec_mergeh(getPt(m1, 1), getPt(m3, 1)); vector float _13y = vec_mergeh(getPt(m1, 2), getPt(m3, 2)); vector float _13z = vec_mergeh(getPt(m1, 3), getPt(m3, 3)); vector float _24x = vec_mergeh(getPt(m2, 1), getPt(m4, 1)); vector float _24y = vec_mergeh(getPt(m2, 2), getPt(m4, 2)); vector float _24z = vec_mergeh(getPt(m2, 3), getPt(m4, 3)); centers->x = vec_mergeh(_13x, _24x); centers->y = vec_mergel(_13y, _24y); centers->z = vec_mergeh(_13z, _24z); object->getReflection(ray, intersection.reflection, intersection.normal, centers); } } ColorGroup* surfaceColor(Intersection &intersection) { surfaceColorGroup->zero(); for (int i = 0; i < getLightsSize(); i++) { Light* light = getLight(i); updateSurfaceColor(*surfaceColorGroup, light, intersection); } return surfaceColorGroup; } void updateSurfaceColor(ColorGroup& surfaceColor, Light* light, Intersection& intersection) { VectorSInt* minIndex = intersection.minIndex; VertexGroup* pos = light->pos; VertexGroup* start = intersection.reflection->start; lightV->x = vec_sub(pos->x, start->x); lightV->y = vec_sub(pos->y, start->y); lightV->z = vec_sub(pos->z, start->z); lightV->normalize(); /* Ray lightRay; Intersection lightIntersection; lightRay.start->copy(*intersection.reflection->start); lightRay.direction->copy(*lightV); getIntersection(&lightRay, lightIntersection); vector bool int lightObstructed = vec_nor(lightIntersection.hit, lightIntersection.hit); if (vec_all_ne(lightIntersection.hit, boolZero())) { return; }*/ vector float negZero = negativeZero(); vector float epsilon = vectorEpsilon(); vector float intensityDiffusion = lightV->dot(*intersection.normal); if (vec_all_lt(intensityDiffusion, epsilon)) { // the light and the normal are perpindicular - or worse (?) return; } vector bool int intenseGtZero = vec_cmpgt(intensityDiffusion, epsilon); vector float ldot = lightV->dot(*intersection.reflection->direction); vector bool int ldotGtZero = vec_cmpgt(ldot, negativeZero()); vector float intensityReflection = vec_and(pow(ldot, light->shininess), ldotGtZero); int m1 = minIndex->points[0]; int m2 = minIndex->points[1]; int m3 = minIndex->points[2]; int m4 = minIndex->points[3]; vector float spec = vec_mergeh(vec_mergeh(getSpec(m1), getSpec(m3)), vec_mergeh(getSpec(m2), getSpec(m4))); vector float specResult = vec_madd(intensityReflection, spec, negZero); vector float _13r = vec_mergeh(getDiff(m1, 1), getDiff(m3, 1)); vector float _13g = vec_mergeh(getDiff(m1, 2), getDiff(m3, 2)); vector float _13b = vec_mergeh(getDiff(m1, 3), getDiff(m3, 3)); vector float _24r = vec_mergeh(getDiff(m2, 1), getDiff(m4, 1)); vector float _24g = vec_mergeh(getDiff(m2, 2), getDiff(m4, 2)); vector float _24b = vec_mergeh(getDiff(m2, 3), getDiff(m4, 3)); surfaceColor.r = vec_add(vec_and(vec_madd(intensityDiffusion, vec_madd(vec_mergeh(_13r, _24r), light->rgb->r, negZero), specResult), intenseGtZero), surfaceColor.r); surfaceColor.g = vec_add(vec_and(vec_madd(intensityDiffusion, vec_madd(vec_mergeh(_13g, _24g), light->rgb->g, negZero), specResult), intenseGtZero), surfaceColor.g); surfaceColor.b = vec_add(vec_and(vec_madd(intensityDiffusion, vec_madd(vec_mergeh(_13b, _24b), light->rgb->b, negZero), specResult), intenseGtZero), surfaceColor.b); } ColorGroup* getAmbientColor() { return ambientColor; } }; #endif
[ "gamorejon@gmail.com" ]
gamorejon@gmail.com
2b085414a8218ce467d66ee7369032148ade9b2f
e1923c6dbede9cf6cca4c95346a2e0544e1d8c12
/src/main.cpp
6d081f4c7b2eb9c3c2ced72eb9ee5ad6ae0c1213
[]
no_license
TolimanStaR/Ex09
8015ac669fa8f4fa3520ee2f75a708d690617d57
0ef19457137799c4f0ee7a5fb751dfa7c41ccd2b
refs/heads/main
2023-02-11T17:04:20.500084
2021-01-13T20:20:08
2021-01-13T20:20:08
328,803,915
0
0
null
2021-01-11T22:09:56
2021-01-11T22:09:56
null
UTF-8
C++
false
false
233
cpp
// Copyright 2021 Toliman #include "../include/MyStack.h" signed main() { MyStack<int> s(3); s.push(1); s.push(3); MyStack<int> t(3); t.push(8924389); t.push(89489); MyStack<int> u(t); return 0; }
[ "dadyryaev@edu.hse.ru" ]
dadyryaev@edu.hse.ru
20dfa3809caa970f7b91ddf1dba3b03bbd6e3fb2
cd7fdd7cca834eb7649973908b8ff7d40580e756
/Plugins/AdvancedSessions/AdvancedSessions/Intermediate/Build/Win64/UE4/Inc/AdvancedSessions/AdvancedFriendsLibrary.generated.h
5cdad9e936280f276994de7a57a446b75d39e811
[ "MIT" ]
permissive
jackychew77/FYP
09cb03ea326e7aed0ad190bd6f13a38153ff4095
4ba57241a1d960f6ff3cb40c375aeb29982efa0d
refs/heads/master
2022-09-22T22:12:54.900880
2020-05-28T08:30:06
2020-05-28T08:30:06
206,222,682
0
0
null
null
null
null
UTF-8
C++
false
false
10,575
h
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/ObjectMacros.h" #include "UObject/ScriptMacros.h" PRAGMA_DISABLE_DEPRECATION_WARNINGS class APlayerController; struct FBPUniqueNetId; struct FBPOnlineRecentPlayer; struct FBPFriendInfo; enum class EBlueprintResultSwitch : uint8; #ifdef ADVANCEDSESSIONS_AdvancedFriendsLibrary_generated_h #error "AdvancedFriendsLibrary.generated.h already included, missing '#pragma once' in AdvancedFriendsLibrary.h" #endif #define ADVANCEDSESSIONS_AdvancedFriendsLibrary_generated_h #define LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_RPC_WRAPPERS \ \ DECLARE_FUNCTION(execIsAFriend) \ { \ P_GET_OBJECT(APlayerController,Z_Param_PlayerController); \ P_GET_STRUCT(FBPUniqueNetId,Z_Param_UniqueNetId); \ P_GET_UBOOL_REF(Z_Param_Out_IsFriend); \ P_FINISH; \ P_NATIVE_BEGIN; \ UAdvancedFriendsLibrary::IsAFriend(Z_Param_PlayerController,Z_Param_UniqueNetId,Z_Param_Out_IsFriend); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execGetStoredRecentPlayersList) \ { \ P_GET_STRUCT(FBPUniqueNetId,Z_Param_UniqueNetId); \ P_GET_TARRAY_REF(FBPOnlineRecentPlayer,Z_Param_Out_PlayersList); \ P_FINISH; \ P_NATIVE_BEGIN; \ UAdvancedFriendsLibrary::GetStoredRecentPlayersList(Z_Param_UniqueNetId,Z_Param_Out_PlayersList); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execGetStoredFriendsList) \ { \ P_GET_OBJECT(APlayerController,Z_Param_PlayerController); \ P_GET_TARRAY_REF(FBPFriendInfo,Z_Param_Out_FriendsList); \ P_FINISH; \ P_NATIVE_BEGIN; \ UAdvancedFriendsLibrary::GetStoredFriendsList(Z_Param_PlayerController,Z_Param_Out_FriendsList); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execGetFriend) \ { \ P_GET_OBJECT(APlayerController,Z_Param_PlayerController); \ P_GET_STRUCT(FBPUniqueNetId,Z_Param_FriendUniqueNetId); \ P_GET_STRUCT_REF(FBPFriendInfo,Z_Param_Out_Friend); \ P_FINISH; \ P_NATIVE_BEGIN; \ UAdvancedFriendsLibrary::GetFriend(Z_Param_PlayerController,Z_Param_FriendUniqueNetId,Z_Param_Out_Friend); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execSendSessionInviteToFriend) \ { \ P_GET_OBJECT(APlayerController,Z_Param_PlayerController); \ P_GET_STRUCT_REF(FBPUniqueNetId,Z_Param_Out_FriendUniqueNetId); \ P_GET_ENUM_REF(EBlueprintResultSwitch,Z_Param_Out_Result); \ P_FINISH; \ P_NATIVE_BEGIN; \ UAdvancedFriendsLibrary::SendSessionInviteToFriend(Z_Param_PlayerController,Z_Param_Out_FriendUniqueNetId,(EBlueprintResultSwitch&)(Z_Param_Out_Result)); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execSendSessionInviteToFriends) \ { \ P_GET_OBJECT(APlayerController,Z_Param_PlayerController); \ P_GET_TARRAY_REF(FBPUniqueNetId,Z_Param_Out_Friends); \ P_GET_ENUM_REF(EBlueprintResultSwitch,Z_Param_Out_Result); \ P_FINISH; \ P_NATIVE_BEGIN; \ UAdvancedFriendsLibrary::SendSessionInviteToFriends(Z_Param_PlayerController,Z_Param_Out_Friends,(EBlueprintResultSwitch&)(Z_Param_Out_Result)); \ P_NATIVE_END; \ } #define LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_RPC_WRAPPERS_NO_PURE_DECLS \ \ DECLARE_FUNCTION(execIsAFriend) \ { \ P_GET_OBJECT(APlayerController,Z_Param_PlayerController); \ P_GET_STRUCT(FBPUniqueNetId,Z_Param_UniqueNetId); \ P_GET_UBOOL_REF(Z_Param_Out_IsFriend); \ P_FINISH; \ P_NATIVE_BEGIN; \ UAdvancedFriendsLibrary::IsAFriend(Z_Param_PlayerController,Z_Param_UniqueNetId,Z_Param_Out_IsFriend); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execGetStoredRecentPlayersList) \ { \ P_GET_STRUCT(FBPUniqueNetId,Z_Param_UniqueNetId); \ P_GET_TARRAY_REF(FBPOnlineRecentPlayer,Z_Param_Out_PlayersList); \ P_FINISH; \ P_NATIVE_BEGIN; \ UAdvancedFriendsLibrary::GetStoredRecentPlayersList(Z_Param_UniqueNetId,Z_Param_Out_PlayersList); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execGetStoredFriendsList) \ { \ P_GET_OBJECT(APlayerController,Z_Param_PlayerController); \ P_GET_TARRAY_REF(FBPFriendInfo,Z_Param_Out_FriendsList); \ P_FINISH; \ P_NATIVE_BEGIN; \ UAdvancedFriendsLibrary::GetStoredFriendsList(Z_Param_PlayerController,Z_Param_Out_FriendsList); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execGetFriend) \ { \ P_GET_OBJECT(APlayerController,Z_Param_PlayerController); \ P_GET_STRUCT(FBPUniqueNetId,Z_Param_FriendUniqueNetId); \ P_GET_STRUCT_REF(FBPFriendInfo,Z_Param_Out_Friend); \ P_FINISH; \ P_NATIVE_BEGIN; \ UAdvancedFriendsLibrary::GetFriend(Z_Param_PlayerController,Z_Param_FriendUniqueNetId,Z_Param_Out_Friend); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execSendSessionInviteToFriend) \ { \ P_GET_OBJECT(APlayerController,Z_Param_PlayerController); \ P_GET_STRUCT_REF(FBPUniqueNetId,Z_Param_Out_FriendUniqueNetId); \ P_GET_ENUM_REF(EBlueprintResultSwitch,Z_Param_Out_Result); \ P_FINISH; \ P_NATIVE_BEGIN; \ UAdvancedFriendsLibrary::SendSessionInviteToFriend(Z_Param_PlayerController,Z_Param_Out_FriendUniqueNetId,(EBlueprintResultSwitch&)(Z_Param_Out_Result)); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execSendSessionInviteToFriends) \ { \ P_GET_OBJECT(APlayerController,Z_Param_PlayerController); \ P_GET_TARRAY_REF(FBPUniqueNetId,Z_Param_Out_Friends); \ P_GET_ENUM_REF(EBlueprintResultSwitch,Z_Param_Out_Result); \ P_FINISH; \ P_NATIVE_BEGIN; \ UAdvancedFriendsLibrary::SendSessionInviteToFriends(Z_Param_PlayerController,Z_Param_Out_Friends,(EBlueprintResultSwitch&)(Z_Param_Out_Result)); \ P_NATIVE_END; \ } #define LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_INCLASS_NO_PURE_DECLS \ private: \ static void StaticRegisterNativesUAdvancedFriendsLibrary(); \ friend struct Z_Construct_UClass_UAdvancedFriendsLibrary_Statics; \ public: \ DECLARE_CLASS(UAdvancedFriendsLibrary, UBlueprintFunctionLibrary, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/AdvancedSessions"), NO_API) \ DECLARE_SERIALIZER(UAdvancedFriendsLibrary) #define LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_INCLASS \ private: \ static void StaticRegisterNativesUAdvancedFriendsLibrary(); \ friend struct Z_Construct_UClass_UAdvancedFriendsLibrary_Statics; \ public: \ DECLARE_CLASS(UAdvancedFriendsLibrary, UBlueprintFunctionLibrary, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/AdvancedSessions"), NO_API) \ DECLARE_SERIALIZER(UAdvancedFriendsLibrary) #define LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_STANDARD_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API UAdvancedFriendsLibrary(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UAdvancedFriendsLibrary) \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UAdvancedFriendsLibrary); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UAdvancedFriendsLibrary); \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API UAdvancedFriendsLibrary(UAdvancedFriendsLibrary&&); \ NO_API UAdvancedFriendsLibrary(const UAdvancedFriendsLibrary&); \ public: #define LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_ENHANCED_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API UAdvancedFriendsLibrary(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()) : Super(ObjectInitializer) { }; \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API UAdvancedFriendsLibrary(UAdvancedFriendsLibrary&&); \ NO_API UAdvancedFriendsLibrary(const UAdvancedFriendsLibrary&); \ public: \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UAdvancedFriendsLibrary); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UAdvancedFriendsLibrary); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UAdvancedFriendsLibrary) #define LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_PRIVATE_PROPERTY_OFFSET #define LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_25_PROLOG #define LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_GENERATED_BODY_LEGACY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_PRIVATE_PROPERTY_OFFSET \ LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_RPC_WRAPPERS \ LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_INCLASS \ LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_STANDARD_CONSTRUCTORS \ public: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #define LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_GENERATED_BODY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_PRIVATE_PROPERTY_OFFSET \ LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_RPC_WRAPPERS_NO_PURE_DECLS \ LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_INCLASS_NO_PURE_DECLS \ LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_ENHANCED_CONSTRUCTORS \ private: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS template<> ADVANCEDSESSIONS_API UClass* StaticClass<class UAdvancedFriendsLibrary>(); #undef CURRENT_FILE_ID #define CURRENT_FILE_ID LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h PRAGMA_ENABLE_DEPRECATION_WARNINGS
[ "jacky_chew629@live.com.my" ]
jacky_chew629@live.com.my
5c796659b9b0dc8b7115a2dad76cc117339d68c5
de984a13290408a3dc42fecdbf65a04c3bc4ccb5
/shadowmapping-master/ShaderDefault.cpp
2fd024625ac9de8f10106d853f20db4bc2b4dc8e
[]
no_license
HerrAndersson/3DProject
d39e5243bcb49b896bf3a30955b9479772ca94fc
7c5254cd3987d53243284d92c382bcbd2129ee5b
refs/heads/master
2021-01-21T03:29:49.108644
2016-04-28T22:45:14
2016-04-28T22:45:14
57,338,388
0
0
null
2016-04-28T22:43:25
2016-04-28T22:43:23
null
UTF-8
C++
false
false
3,723
cpp
#include "ShaderDefault.h" using namespace DirectX; using namespace std; ShaderDefault::ShaderDefault(ID3D11Device* device, LPCWSTR vertexShaderFilename, LPCWSTR pixelShaderFilename ) : ShaderBase(device) { D3D11_INPUT_ELEMENT_DESC inputDesc[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 20, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; CreateMandatoryShaders(device, vertexShaderFilename, pixelShaderFilename, inputDesc, ARRAYSIZE(inputDesc)); D3D11_BUFFER_DESC matrixBufferDesc; HRESULT hr; //Setup the description of the dynamic matrix constant buffer that is in the vertex shader. matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC; matrixBufferDesc.ByteWidth = sizeof(MatrixBuffer); matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; matrixBufferDesc.MiscFlags = 0; matrixBufferDesc.StructureByteStride = 0; //Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. hr = device->CreateBuffer(&matrixBufferDesc, NULL, &matrixBuffer); if (FAILED(hr)) { throw std::runtime_error("Shader default matrix buffer failed"); } //Create texture sampler D3D11_SAMPLER_DESC samplerDesc; ZeroMemory(&samplerDesc, sizeof(D3D11_SAMPLER_DESC)); samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_BORDER; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_BORDER; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_BORDER; samplerDesc.BorderColor[0] = 1.0f; samplerDesc.BorderColor[1] = 1.0f; samplerDesc.BorderColor[2] = 1.0f; samplerDesc.BorderColor[3] = 1.0f; samplerDesc.MinLOD = 0.f; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; samplerDesc.MipLODBias = 0.f; samplerDesc.MaxAnisotropy = 0; samplerDesc.ComparisonFunc = D3D11_COMPARISON_LESS_EQUAL; samplerDesc.Filter = D3D11_FILTER_COMPARISON_MIN_MAG_MIP_POINT; hr = device->CreateSamplerState(&samplerDesc, &samplerState); if (FAILED(hr)) { throw std::runtime_error("Shader default sampler failed"); } } ShaderDefault::~ShaderDefault() { matrixBuffer->Release(); samplerState->Release(); } void ShaderDefault::UseShader(ID3D11DeviceContext* deviceContext) { deviceContext->VSSetShader(vertexShader, nullptr, 0); deviceContext->HSSetShader(hullShader, nullptr, 0); deviceContext->DSSetShader(domainShader, nullptr, 0); deviceContext->GSSetShader(geometryShader, nullptr, 0); deviceContext->PSSetShader(pixelShader, nullptr, 0); deviceContext->PSSetSamplers(0, 1, &samplerState); } void ShaderDefault::SetBuffers(ID3D11DeviceContext* deviceContext, XMMATRIX& worldMatrix, XMMATRIX& viewMatrix, XMMATRIX& projectionMatrix, XMMATRIX& lightVP) { HRESULT hr; D3D11_MAPPED_SUBRESOURCE mappedResource; XMMATRIX wm = XMMatrixTranspose(worldMatrix); XMMATRIX vm = XMMatrixTranspose(viewMatrix); XMMATRIX pm = XMMatrixTranspose(projectionMatrix); XMMATRIX lvp = XMMatrixTranspose(lightVP); hr = deviceContext->Map(matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource); MatrixBuffer* matrixDataBuffer = (MatrixBuffer*)mappedResource.pData; //Copy the matrices into the constant buffer. matrixDataBuffer->world = wm; matrixDataBuffer->view = vm; matrixDataBuffer->projection = pm; matrixDataBuffer->lightVP = lvp; deviceContext->Unmap(matrixBuffer, 0); int bufferNumber = 0; deviceContext->VSSetConstantBuffers(bufferNumber, 1, &matrixBuffer); deviceContext->IASetInputLayout(inputLayout); } void* ShaderDefault::operator new(size_t i) { return _mm_malloc(i, 16); } void ShaderDefault::operator delete(void* p) { _mm_free(p); }
[ "anderssonjonas94@gmail.com" ]
anderssonjonas94@gmail.com
8d60a08a5aafdba0384cff343d51e3d838ac3426
99143df5e2ef15f8f9b7e90c320a61ce93a1ffe8
/Burgh/StatDisplay.h
2fc5f386b9c0a964d2788107856f446490bbb03b
[]
no_license
MrGodin/IceCaves
af55f600cc70277d3b3332b3844966e2f7ec155d
ee6aafc60170b329329ae7918746dfb235610fda
refs/heads/master
2020-05-30T17:48:44.221679
2015-08-11T20:16:53
2015-08-11T20:16:53
40,512,793
0
0
null
2015-08-11T20:16:53
2015-08-11T00:30:06
C++
UTF-8
C++
false
false
1,464
h
#pragma once #include "GuiFrame.h" #include "GuiTextControl.h" class StatDisplay : public GuiFrame { private: protected: GuiText* pFps = NULL; GuiText* pWorldPos = NULL; public: StatDisplay(GuiFrameDesc desc) : GuiFrame(desc) { } ~StatDisplay() { SAFE_DELETE(pFps); SAFE_DELETE(pWorldPos); } void Update(float fps,Vec2F pos) { TString str = "Fps: "; str += TString(fps); pFps->SetText(str.w_char()); str = "Player Pos X :("; str += TString(pos.x); str += TString(") - Y :("); str += TString(pos.y); str += TString(")"); pWorldPos->SetText(str.w_char()); } virtual HRESULT Rasterize()override { DrawFrame(); pFps->Rasterize(); pWorldPos->Rasterize(); return S_OK; } void Create() { GuiFrameDesc fpsDesc; fpsDesc.originX = frameDesc.originX + 16; fpsDesc.originY = frameDesc.originY + 16; pFps = new GuiText(fpsDesc, "What", TEXTALIGN_LEFT); pFps->SetColor(Color(255, 0, 255, 0)); pFps->SetFont(pFont); pFps->AlignText(); fpsDesc.originX = frameDesc.originX + 16; fpsDesc.originY = fpsDesc.originY + 18; pWorldPos = new GuiText(fpsDesc, "What", TEXTALIGN_LEFT); pWorldPos->SetColor(Color(255, 0, 255, 0)); pWorldPos->SetFont(pFont); pWorldPos->AlignText(); } void Resize(long x, long y, long w, long h) { frameDesc.originX = x; frameDesc.originY = y; frameDesc.width = w; frameDesc.height = h; Init(); SAFE_DELETE(pFps); SAFE_DELETE(pWorldPos); Create(); } };
[ "benwold@telus.net" ]
benwold@telus.net
f77d99738b9417fca4e9bc674fe5a49d6db9eb81
5898d3bd9e4cb58043b40fa58961c7452182db08
/part4/ch30/30-4-3-5-error_code-mapping/src/my_future_errc.h
bc8df3b4eb69405a5fc5257af02893748e32cead
[]
no_license
sasaki-seiji/ProgrammingLanguageCPP4th
1e802f3cb15fc2ac51fa70403b95f52878223cff
2f686b385b485c27068328c6533926903b253687
refs/heads/master
2020-04-04T06:10:32.942026
2017-08-10T11:35:08
2017-08-10T11:35:08
53,772,682
2
0
null
null
null
null
UTF-8
C++
false
false
718
h
/* * my_future_errc.h * * Created on: 2017/08/06 * Author: sasaki */ #ifndef MY_FUTURE_ERRC_H_ #define MY_FUTURE_ERRC_H_ #include <system_error> #include <string> using namespace std; enum class my_future_errc { broken_promise = 1, future_already_retrieved, promise_already_satisfied, no_state }; class my_future_cat : public error_category { public: const char* name() const noexcept override { return "future"; } string message(int ec) const override; }; const error_category& my_future_category() noexcept; error_code make_error_code(my_future_errc e) noexcept; namespace std { template<> struct is_error_code_enum<my_future_errc> : public true_type { }; } #endif /* MY_FUTURE_ERRC_H_ */
[ "sasaki-seiji@msj.biglobe.ne.jp" ]
sasaki-seiji@msj.biglobe.ne.jp
dbd100284e494eb7106787771442f8c1b84a2ebc
c4979d123ddfd01c3a4251b1d84fd4797684242d
/src/business/management_server/actions/server_list_request_action.h
0668d4e3c718fa84ff5ca928a70b4e3f59559b30
[]
no_license
evandropoa/open-carom3d-server
e9a3aedae46610ea062e3a19e785779b13cfdc6e
9c3d5af8cb9e79c4650f85607d47d9afa0be3f50
refs/heads/master
2022-11-07T06:29:12.170550
2020-06-09T06:29:46
2020-06-09T06:29:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
547
h
// // Created by CGR on 15/05/2020. // #ifndef __OPEN_CAROM3D_SERVER_SERVER_LIST_REQUEST_H__ #define __OPEN_CAROM3D_SERVER_SERVER_LIST_REQUEST_H__ #include <business/util/abstract_action.h> namespace business { namespace management { class ServerListRequestAction : public AbstractAction<void> { public: bool validate(const ActionData &action) override { return true; } void execute(const ActionData &action, User &user, const void *unused) override; }; }} #endif //__OPEN_CAROM3D_SERVER_SERVER_LIST_REQUEST_H__
[ "cesargreche@gmail.com" ]
cesargreche@gmail.com
da6d22d1fc4c47fc7bd7aed4c5dde096d9940929
3dbec36a6c62cad3e5c6ec767b13f4038baa5f79
/cpp-lang/qt/quick/integratingqml/backend.h
97c13707fa5e68b95fa22e9b37e7f8ab7a9cee83
[]
no_license
reposhelf/playground
50a2e54436e77e7e6cad3a44fd74c0acc22a553a
47ddd204a05ec269e4816c2d45a13e5bc6d3e73a
refs/heads/master
2022-04-22T13:50:24.222822
2020-04-10T15:59:30
2020-04-10T15:59:30
254,675,772
0
0
null
null
null
null
UTF-8
C++
false
false
463
h
#ifndef BACKEND_H #define BACKEND_H #include <QObject> #include <QString> class BackEnd : public QObject { Q_OBJECT Q_PROPERTY(QString userName READ userName WRITE setUserName NOTIFY userNameChanged) public: explicit BackEnd(QObject *parent = nullptr); QString userName() const { return m_userName; } void setUserName(const QString &userName); signals: void userNameChanged(); private: QString m_userName; }; #endif // BACKEND_H
[ "vladimironiuk@gmail.com" ]
vladimironiuk@gmail.com
dcbd68892c41f860cf6f1ae91a48bd16bccf7391
bb6ebff7a7f6140903d37905c350954ff6599091
/ui/app_list/views/apps_grid_view.cc
d7da61bd4191ed9c8d016eb58df39c7834f90923
[ "BSD-3-Clause" ]
permissive
PDi-Communication-Systems-Inc/lollipop_external_chromium_org
faa6602bd6bfd9b9b6277ce3cd16df0bd26e7f2f
ccadf4e63dd34be157281f53fe213d09a8c66d2c
refs/heads/master
2022-12-23T18:07:04.568931
2016-04-11T16:03:36
2016-04-11T16:03:36
53,677,925
0
1
BSD-3-Clause
2022-12-09T23:46:46
2016-03-11T15:49:07
C++
UTF-8
C++
false
false
73,690
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/app_list/views/apps_grid_view.h" #include <algorithm> #include <set> #include <string> #include "base/guid.h" #include "ui/app_list/app_list_constants.h" #include "ui/app_list/app_list_folder_item.h" #include "ui/app_list/app_list_item.h" #include "ui/app_list/app_list_switches.h" #include "ui/app_list/views/app_list_drag_and_drop_host.h" #include "ui/app_list/views/app_list_folder_view.h" #include "ui/app_list/views/app_list_item_view.h" #include "ui/app_list/views/apps_grid_view_delegate.h" #include "ui/app_list/views/page_switcher.h" #include "ui/app_list/views/pulsing_block_view.h" #include "ui/app_list/views/top_icon_animation_view.h" #include "ui/compositor/scoped_layer_animation_settings.h" #include "ui/events/event.h" #include "ui/gfx/animation/animation.h" #include "ui/views/border.h" #include "ui/views/view_model_utils.h" #include "ui/views/widget/widget.h" #if defined(USE_AURA) #include "ui/aura/window.h" #include "ui/aura/window_event_dispatcher.h" #if defined(OS_WIN) #include "ui/views/win/hwnd_util.h" #endif // defined(OS_WIN) #endif // defined(USE_AURA) #if defined(OS_WIN) #include "base/command_line.h" #include "base/files/file_path.h" #include "base/win/shortcut.h" #include "ui/base/dragdrop/drag_utils.h" #include "ui/base/dragdrop/drop_target_win.h" #include "ui/base/dragdrop/os_exchange_data.h" #include "ui/base/dragdrop/os_exchange_data_provider_win.h" #include "ui/gfx/win/dpi.h" #endif namespace app_list { namespace { // Distance a drag needs to be from the app grid to be considered 'outside', at // which point we rearrange the apps to their pre-drag configuration, as a drop // then would be canceled. We have a buffer to make it easier to drag apps to // other pages. const int kDragBufferPx = 20; // Padding space in pixels for fixed layout. const int kLeftRightPadding = 20; const int kTopPadding = 1; // Padding space in pixels between pages. const int kPagePadding = 40; // Preferred tile size when showing in fixed layout. const int kPreferredTileWidth = 88; const int kPreferredTileHeight = 98; // Width in pixels of the area on the sides that triggers a page flip. const int kPageFlipZoneSize = 40; // Delay in milliseconds to do the page flip. const int kPageFlipDelayInMs = 1000; // How many pages on either side of the selected one we prerender. const int kPrerenderPages = 1; // The drag and drop proxy should get scaled by this factor. const float kDragAndDropProxyScale = 1.5f; // Delays in milliseconds to show folder dropping preview circle. const int kFolderDroppingDelay = 150; // Delays in milliseconds to show re-order preview. const int kReorderDelay = 120; // Delays in milliseconds to show folder item reparent UI. const int kFolderItemReparentDelay = 50; // Radius of the circle, in which if entered, show folder dropping preview // UI. const int kFolderDroppingCircleRadius = 15; // RowMoveAnimationDelegate is used when moving an item into a different row. // Before running the animation, the item's layer is re-created and kept in // the original position, then the item is moved to just before its target // position and opacity set to 0. When the animation runs, this delegate moves // the layer and fades it out while fading in the item at the same time. class RowMoveAnimationDelegate : public gfx::AnimationDelegate { public: RowMoveAnimationDelegate(views::View* view, ui::Layer* layer, const gfx::Rect& layer_target) : view_(view), layer_(layer), layer_start_(layer ? layer->bounds() : gfx::Rect()), layer_target_(layer_target) { } virtual ~RowMoveAnimationDelegate() {} // gfx::AnimationDelegate overrides: virtual void AnimationProgressed(const gfx::Animation* animation) OVERRIDE { view_->layer()->SetOpacity(animation->GetCurrentValue()); view_->layer()->ScheduleDraw(); if (layer_) { layer_->SetOpacity(1 - animation->GetCurrentValue()); layer_->SetBounds(animation->CurrentValueBetween(layer_start_, layer_target_)); layer_->ScheduleDraw(); } } virtual void AnimationEnded(const gfx::Animation* animation) OVERRIDE { view_->layer()->SetOpacity(1.0f); view_->SchedulePaint(); } virtual void AnimationCanceled(const gfx::Animation* animation) OVERRIDE { view_->layer()->SetOpacity(1.0f); view_->SchedulePaint(); } private: // The view that needs to be wrapped. Owned by views hierarchy. views::View* view_; scoped_ptr<ui::Layer> layer_; const gfx::Rect layer_start_; const gfx::Rect layer_target_; DISALLOW_COPY_AND_ASSIGN(RowMoveAnimationDelegate); }; // ItemRemoveAnimationDelegate is used to show animation for removing an item. // This happens when user drags an item into a folder. The dragged item will // be removed from the original list after it is dropped into the folder. class ItemRemoveAnimationDelegate : public gfx::AnimationDelegate { public: explicit ItemRemoveAnimationDelegate(views::View* view) : view_(view) { } virtual ~ItemRemoveAnimationDelegate() { } // gfx::AnimationDelegate overrides: virtual void AnimationProgressed(const gfx::Animation* animation) OVERRIDE { view_->layer()->SetOpacity(1 - animation->GetCurrentValue()); view_->layer()->ScheduleDraw(); } private: scoped_ptr<views::View> view_; DISALLOW_COPY_AND_ASSIGN(ItemRemoveAnimationDelegate); }; // ItemMoveAnimationDelegate observes when an item finishes animating when it is // not moving between rows. This is to ensure an item is repainted for the // "zoom out" case when releasing an item being dragged. class ItemMoveAnimationDelegate : public gfx::AnimationDelegate { public: ItemMoveAnimationDelegate(views::View* view) : view_(view) {} virtual void AnimationEnded(const gfx::Animation* animation) OVERRIDE { view_->SchedulePaint(); } virtual void AnimationCanceled(const gfx::Animation* animation) OVERRIDE { view_->SchedulePaint(); } private: views::View* view_; DISALLOW_COPY_AND_ASSIGN(ItemMoveAnimationDelegate); }; // Gets the distance between the centers of the |rect_1| and |rect_2|. int GetDistanceBetweenRects(gfx::Rect rect_1, gfx::Rect rect_2) { return (rect_1.CenterPoint() - rect_2.CenterPoint()).Length(); } // Returns true if the |item| is an folder item. bool IsFolderItem(AppListItem* item) { return (item->GetItemType() == AppListFolderItem::kItemType); } bool IsOEMFolderItem(AppListItem* item) { return IsFolderItem(item) && (static_cast<AppListFolderItem*>(item))->folder_type() == AppListFolderItem::FOLDER_TYPE_OEM; } } // namespace #if defined(OS_WIN) // Interprets drag events sent from Windows via the drag/drop API and forwards // them to AppsGridView. // On Windows, in order to have the OS perform the drag properly we need to // provide it with a shortcut file which may or may not exist at the time the // drag is started. Therefore while waiting for that shortcut to be located we // just do a regular "internal" drag and transition into the synchronous drag // when the shortcut is found/created. Hence a synchronous drag is an optional // phase of a regular drag and non-Windows platforms drags are equivalent to a // Windows drag that never enters the synchronous drag phase. class SynchronousDrag : public ui::DragSourceWin { public: SynchronousDrag(AppsGridView* grid_view, AppListItemView* drag_view, const gfx::Point& drag_view_offset) : grid_view_(grid_view), drag_view_(drag_view), drag_view_offset_(drag_view_offset), has_shortcut_path_(false), running_(false), canceled_(false) {} void set_shortcut_path(const base::FilePath& shortcut_path) { has_shortcut_path_ = true; shortcut_path_ = shortcut_path; } bool running() { return running_; } bool CanRun() { return has_shortcut_path_ && !running_; } void Run() { DCHECK(CanRun()); // Prevent the synchronous dragger being destroyed while the drag is // running. scoped_refptr<SynchronousDrag> this_ref = this; running_ = true; ui::OSExchangeData data; SetupExchangeData(&data); // Hide the dragged view because the OS is going to create its own. drag_view_->SetVisible(false); // Blocks until the drag is finished. Calls into the ui::DragSourceWin // methods. DWORD effects; DoDragDrop(ui::OSExchangeDataProviderWin::GetIDataObject(data), this, DROPEFFECT_MOVE | DROPEFFECT_LINK, &effects); // If |drag_view_| is NULL the drag was ended by some reentrant code. if (drag_view_) { // Make the drag view visible again. drag_view_->SetVisible(true); drag_view_->OnSyncDragEnd(); grid_view_->EndDrag(canceled_ || !IsCursorWithinGridView()); } } void EndDragExternally() { CancelDrag(); drag_view_ = NULL; } private: // Overridden from ui::DragSourceWin. virtual void OnDragSourceCancel() OVERRIDE { canceled_ = true; } virtual void OnDragSourceDrop() OVERRIDE { } virtual void OnDragSourceMove() OVERRIDE { grid_view_->UpdateDrag(AppsGridView::MOUSE, GetCursorInGridViewCoords()); } void SetupExchangeData(ui::OSExchangeData* data) { data->SetFilename(shortcut_path_); gfx::ImageSkia image(drag_view_->GetDragImage()); gfx::Size image_size(image.size()); drag_utils::SetDragImageOnDataObject( image, drag_view_offset_ - drag_view_->GetDragImageOffset(), data); } HWND GetGridViewHWND() { return views::HWNDForView(grid_view_); } bool IsCursorWithinGridView() { POINT p; GetCursorPos(&p); return GetGridViewHWND() == WindowFromPoint(p); } gfx::Point GetCursorInGridViewCoords() { POINT p; GetCursorPos(&p); ScreenToClient(GetGridViewHWND(), &p); gfx::Point grid_view_pt(p.x, p.y); grid_view_pt = gfx::win::ScreenToDIPPoint(grid_view_pt); views::View::ConvertPointFromWidget(grid_view_, &grid_view_pt); return grid_view_pt; } AppsGridView* grid_view_; AppListItemView* drag_view_; gfx::Point drag_view_offset_; bool has_shortcut_path_; base::FilePath shortcut_path_; bool running_; bool canceled_; DISALLOW_COPY_AND_ASSIGN(SynchronousDrag); }; #endif // defined(OS_WIN) AppsGridView::AppsGridView(AppsGridViewDelegate* delegate) : model_(NULL), item_list_(NULL), delegate_(delegate), folder_delegate_(NULL), page_switcher_view_(NULL), cols_(0), rows_per_page_(0), selected_view_(NULL), drag_view_(NULL), drag_start_page_(-1), #if defined(OS_WIN) use_synchronous_drag_(true), #endif drag_pointer_(NONE), drop_attempt_(DROP_FOR_NONE), drag_and_drop_host_(NULL), forward_events_to_drag_and_drop_host_(false), page_flip_target_(-1), page_flip_delay_in_ms_(kPageFlipDelayInMs), bounds_animator_(this), activated_folder_item_view_(NULL), dragging_for_reparent_item_(false) { SetPaintToLayer(true); // Clip any icons that are outside the grid view's bounds. These icons would // otherwise be visible to the user when the grid view is off screen. layer()->SetMasksToBounds(true); SetFillsBoundsOpaquely(false); pagination_model_.SetTransitionDurations(kPageTransitionDurationInMs, kOverscrollPageTransitionDurationMs); pagination_model_.AddObserver(this); page_switcher_view_ = new PageSwitcher(&pagination_model_); AddChildView(page_switcher_view_); } AppsGridView::~AppsGridView() { // Coming here |drag_view_| should already be canceled since otherwise the // drag would disappear after the app list got animated away and closed, // which would look odd. DCHECK(!drag_view_); if (drag_view_) EndDrag(true); if (model_) model_->RemoveObserver(this); pagination_model_.RemoveObserver(this); if (item_list_) item_list_->RemoveObserver(this); // Make sure |page_switcher_view_| is deleted before |pagination_model_|. view_model_.Clear(); RemoveAllChildViews(true); } void AppsGridView::SetLayout(int icon_size, int cols, int rows_per_page) { icon_size_.SetSize(icon_size, icon_size); cols_ = cols; rows_per_page_ = rows_per_page; SetBorder(views::Border::CreateEmptyBorder( kTopPadding, kLeftRightPadding, 0, kLeftRightPadding)); } void AppsGridView::ResetForShowApps() { activated_folder_item_view_ = NULL; ClearDragState(); layer()->SetOpacity(1.0f); SetVisible(true); // Set all views to visible in case they weren't made visible again by an // incomplete animation. for (int i = 0; i < view_model_.view_size(); ++i) { view_model_.view_at(i)->SetVisible(true); } CHECK_EQ(item_list_->item_count(), static_cast<size_t>(view_model_.view_size())); } void AppsGridView::SetModel(AppListModel* model) { if (model_) model_->RemoveObserver(this); model_ = model; if (model_) model_->AddObserver(this); Update(); } void AppsGridView::SetItemList(AppListItemList* item_list) { if (item_list_) item_list_->RemoveObserver(this); item_list_ = item_list; if (item_list_) item_list_->AddObserver(this); Update(); } void AppsGridView::SetSelectedView(views::View* view) { if (IsSelectedView(view) || IsDraggedView(view)) return; Index index = GetIndexOfView(view); if (IsValidIndex(index)) SetSelectedItemByIndex(index); } void AppsGridView::ClearSelectedView(views::View* view) { if (view && IsSelectedView(view)) { selected_view_->SchedulePaint(); selected_view_ = NULL; } } void AppsGridView::ClearAnySelectedView() { if (selected_view_) { selected_view_->SchedulePaint(); selected_view_ = NULL; } } bool AppsGridView::IsSelectedView(const views::View* view) const { return selected_view_ == view; } void AppsGridView::EnsureViewVisible(const views::View* view) { if (pagination_model_.has_transition()) return; Index index = GetIndexOfView(view); if (IsValidIndex(index)) pagination_model_.SelectPage(index.page, false); } void AppsGridView::InitiateDrag(AppListItemView* view, Pointer pointer, const ui::LocatedEvent& event) { DCHECK(view); if (drag_view_ || pulsing_blocks_model_.view_size()) return; drag_view_ = view; drag_view_init_index_ = GetIndexOfView(drag_view_); drag_view_offset_ = event.location(); drag_start_page_ = pagination_model_.selected_page(); ExtractDragLocation(event, &drag_start_grid_view_); drag_view_start_ = gfx::Point(drag_view_->x(), drag_view_->y()); } void AppsGridView::StartSettingUpSynchronousDrag() { #if defined(OS_WIN) if (!delegate_ || !use_synchronous_drag_) return; // Folders can't be integrated with the OS. if (IsFolderItem(drag_view_->item())) return; // Favor the drag and drop host over native win32 drag. For the Win8/ash // launcher we want to have ashes drag and drop over win32's. if (drag_and_drop_host_) return; // Never create a second synchronous drag if the drag started in a folder. if (IsDraggingForReparentInRootLevelGridView()) return; synchronous_drag_ = new SynchronousDrag(this, drag_view_, drag_view_offset_); delegate_->GetShortcutPathForApp(drag_view_->item()->id(), base::Bind(&AppsGridView::OnGotShortcutPath, base::Unretained(this), synchronous_drag_)); #endif } bool AppsGridView::RunSynchronousDrag() { #if defined(OS_WIN) if (!synchronous_drag_) return false; if (synchronous_drag_->CanRun()) { if (IsDraggingForReparentInHiddenGridView()) folder_delegate_->SetRootLevelDragViewVisible(false); synchronous_drag_->Run(); synchronous_drag_ = NULL; return true; } else if (!synchronous_drag_->running()) { // The OS drag is not ready yet. If the root grid has a drag view because // a reparent has started, ensure it is visible. if (IsDraggingForReparentInHiddenGridView()) folder_delegate_->SetRootLevelDragViewVisible(true); } #endif return false; } void AppsGridView::CleanUpSynchronousDrag() { #if defined(OS_WIN) if (synchronous_drag_) synchronous_drag_->EndDragExternally(); synchronous_drag_ = NULL; #endif } #if defined(OS_WIN) void AppsGridView::OnGotShortcutPath( scoped_refptr<SynchronousDrag> synchronous_drag, const base::FilePath& path) { // Drag may have ended before we get the shortcut path or a new drag may have // begun. if (synchronous_drag_ != synchronous_drag) return; // Setting the shortcut path here means the next time we hit UpdateDrag() // we'll enter the synchronous drag. // NOTE we don't Run() the drag here because that causes animations not to // update for some reason. synchronous_drag_->set_shortcut_path(path); DCHECK(synchronous_drag_->CanRun()); } #endif bool AppsGridView::UpdateDragFromItem(Pointer pointer, const ui::LocatedEvent& event) { DCHECK(drag_view_); gfx::Point drag_point_in_grid_view; ExtractDragLocation(event, &drag_point_in_grid_view); UpdateDrag(pointer, drag_point_in_grid_view); if (!dragging()) return false; // If a drag and drop host is provided, see if the drag operation needs to be // forwarded. gfx::Point location_in_screen = drag_point_in_grid_view; views::View::ConvertPointToScreen(this, &location_in_screen); DispatchDragEventToDragAndDropHost(location_in_screen); if (drag_and_drop_host_) drag_and_drop_host_->UpdateDragIconProxy(location_in_screen); return true; } void AppsGridView::UpdateDrag(Pointer pointer, const gfx::Point& point) { if (folder_delegate_) UpdateDragStateInsideFolder(pointer, point); // EndDrag was called before if |drag_view_| is NULL. if (!drag_view_) return; if (RunSynchronousDrag()) return; gfx::Vector2d drag_vector(point - drag_start_grid_view_); if (!dragging() && ExceededDragThreshold(drag_vector)) { drag_pointer_ = pointer; // Move the view to the front so that it appears on top of other views. ReorderChildView(drag_view_, -1); bounds_animator_.StopAnimatingView(drag_view_); // Stopping the animation may have invalidated our drag view due to the // view hierarchy changing. if (!drag_view_) return; StartSettingUpSynchronousDrag(); if (!dragging_for_reparent_item_) StartDragAndDropHostDrag(point); } if (drag_pointer_ != pointer) return; last_drag_point_ = point; const Index last_drop_target = drop_target_; DropAttempt last_drop_attempt = drop_attempt_; CalculateDropTarget(last_drag_point_, false); if (IsPointWithinDragBuffer(last_drag_point_)) MaybeStartPageFlipTimer(last_drag_point_); else StopPageFlipTimer(); gfx::Point page_switcher_point(last_drag_point_); views::View::ConvertPointToTarget(this, page_switcher_view_, &page_switcher_point); page_switcher_view_->UpdateUIForDragPoint(page_switcher_point); if (!EnableFolderDragDropUI()) { if (last_drop_target != drop_target_) AnimateToIdealBounds(); drag_view_->SetPosition(drag_view_start_ + drag_vector); return; } // Update drag with folder UI enabled. if (last_drop_target != drop_target_ || last_drop_attempt != drop_attempt_) { if (drop_attempt_ == DROP_FOR_REORDER) { folder_dropping_timer_.Stop(); reorder_timer_.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(kReorderDelay), this, &AppsGridView::OnReorderTimer); } else if (drop_attempt_ == DROP_FOR_FOLDER) { reorder_timer_.Stop(); folder_dropping_timer_.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(kFolderDroppingDelay), this, &AppsGridView::OnFolderDroppingTimer); } // Reset the previous drop target. SetAsFolderDroppingTarget(last_drop_target, false); } drag_view_->SetPosition(drag_view_start_ + drag_vector); } void AppsGridView::EndDrag(bool cancel) { // EndDrag was called before if |drag_view_| is NULL. if (!drag_view_) return; // Coming here a drag and drop was in progress. bool landed_in_drag_and_drop_host = forward_events_to_drag_and_drop_host_; if (forward_events_to_drag_and_drop_host_) { DCHECK(!IsDraggingForReparentInRootLevelGridView()); forward_events_to_drag_and_drop_host_ = false; drag_and_drop_host_->EndDrag(cancel); if (IsDraggingForReparentInHiddenGridView()) { folder_delegate_->DispatchEndDragEventForReparent( true /* events_forwarded_to_drag_drop_host */, cancel /* cancel_drag */); } } else { if (IsDraggingForReparentInHiddenGridView()) { // Forward the EndDrag event to the root level grid view. folder_delegate_->DispatchEndDragEventForReparent( false /* events_forwarded_to_drag_drop_host */, cancel /* cancel_drag */); EndDragForReparentInHiddenFolderGridView(); return; } if (!cancel && dragging()) { // Regular drag ending path, ie, not for reparenting. CalculateDropTarget(last_drag_point_, true); if (IsValidIndex(drop_target_)) { if (!EnableFolderDragDropUI()) { MoveItemInModel(drag_view_, drop_target_); } else { if (drop_attempt_ == DROP_FOR_REORDER) MoveItemInModel(drag_view_, drop_target_); else if (drop_attempt_ == DROP_FOR_FOLDER) MoveItemToFolder(drag_view_, drop_target_); } } } } if (drag_and_drop_host_) { // If we had a drag and drop proxy icon, we delete it and make the real // item visible again. drag_and_drop_host_->DestroyDragIconProxy(); if (landed_in_drag_and_drop_host) { // Move the item directly to the target location, avoiding the "zip back" // animation if the user was pinning it to the shelf. int i = drop_target_.slot; gfx::Rect bounds = view_model_.ideal_bounds(i); drag_view_->SetBoundsRect(bounds); } // Fade in slowly if it landed in the shelf. SetViewHidden(drag_view_, false /* show */, !landed_in_drag_and_drop_host /* animate */); } // The drag can be ended after the synchronous drag is created but before it // is Run(). CleanUpSynchronousDrag(); SetAsFolderDroppingTarget(drop_target_, false); ClearDragState(); AnimateToIdealBounds(); StopPageFlipTimer(); // If user releases mouse inside a folder's grid view, burst the folder // container ink bubble. if (folder_delegate_ && !IsDraggingForReparentInHiddenGridView()) folder_delegate_->UpdateFolderViewBackground(false); } void AppsGridView::StopPageFlipTimer() { page_flip_timer_.Stop(); page_flip_target_ = -1; } AppListItemView* AppsGridView::GetItemViewAt(int index) const { DCHECK(index >= 0 && index < view_model_.view_size()); return static_cast<AppListItemView*>(view_model_.view_at(index)); } void AppsGridView::SetTopItemViewsVisible(bool visible) { int top_item_count = std::min(static_cast<int>(kNumFolderTopItems), view_model_.view_size()); for (int i = 0; i < top_item_count; ++i) GetItemViewAt(i)->SetVisible(visible); } void AppsGridView::ScheduleShowHideAnimation(bool show) { // Stop any previous animation. layer()->GetAnimator()->StopAnimating(); // Set initial state. SetVisible(true); layer()->SetOpacity(show ? 0.0f : 1.0f); ui::ScopedLayerAnimationSettings animation(layer()->GetAnimator()); animation.AddObserver(this); animation.SetTweenType( show ? kFolderFadeInTweenType : kFolderFadeOutTweenType); animation.SetTransitionDuration(base::TimeDelta::FromMilliseconds( show ? kFolderTransitionInDurationMs : kFolderTransitionOutDurationMs)); layer()->SetOpacity(show ? 1.0f : 0.0f); } void AppsGridView::InitiateDragFromReparentItemInRootLevelGridView( AppListItemView* original_drag_view, const gfx::Rect& drag_view_rect, const gfx::Point& drag_point) { DCHECK(original_drag_view && !drag_view_); DCHECK(!dragging_for_reparent_item_); // Create a new AppListItemView to duplicate the original_drag_view in the // folder's grid view. AppListItemView* view = new AppListItemView(this, original_drag_view->item()); AddChildView(view); drag_view_ = view; drag_view_->SetPaintToLayer(true); // Note: For testing purpose, SetFillsBoundsOpaquely can be set to true to // show the gray background. drag_view_->SetFillsBoundsOpaquely(false); drag_view_->SetIconSize(icon_size_); drag_view_->SetBoundsRect(drag_view_rect); drag_view_->SetDragUIState(); // Hide the title of the drag_view_. // Hide the drag_view_ for drag icon proxy. SetViewHidden(drag_view_, true /* hide */, true /* no animate */); // Add drag_view_ to the end of the view_model_. view_model_.Add(drag_view_, view_model_.view_size()); drag_start_page_ = pagination_model_.selected_page(); drag_start_grid_view_ = drag_point; drag_view_start_ = gfx::Point(drag_view_->x(), drag_view_->y()); // Set the flag in root level grid view. dragging_for_reparent_item_ = true; } void AppsGridView::UpdateDragFromReparentItem(Pointer pointer, const gfx::Point& drag_point) { DCHECK(drag_view_); DCHECK(IsDraggingForReparentInRootLevelGridView()); UpdateDrag(pointer, drag_point); } bool AppsGridView::IsDraggedView(const views::View* view) const { return drag_view_ == view; } void AppsGridView::ClearDragState() { drop_attempt_ = DROP_FOR_NONE; drag_pointer_ = NONE; drop_target_ = Index(); drag_start_grid_view_ = gfx::Point(); drag_start_page_ = -1; drag_view_offset_ = gfx::Point(); if (drag_view_) { drag_view_->OnDragEnded(); if (IsDraggingForReparentInRootLevelGridView()) { const int drag_view_index = view_model_.GetIndexOfView(drag_view_); CHECK_EQ(view_model_.view_size() - 1, drag_view_index); DeleteItemViewAtIndex(drag_view_index); } } drag_view_ = NULL; dragging_for_reparent_item_ = false; } void AppsGridView::SetDragViewVisible(bool visible) { DCHECK(drag_view_); SetViewHidden(drag_view_, !visible, true); } void AppsGridView::SetDragAndDropHostOfCurrentAppList( ApplicationDragAndDropHost* drag_and_drop_host) { drag_and_drop_host_ = drag_and_drop_host; } void AppsGridView::Prerender(int page_index) { Layout(); int start = std::max(0, (page_index - kPrerenderPages) * tiles_per_page()); int end = std::min(view_model_.view_size(), (page_index + 1 + kPrerenderPages) * tiles_per_page()); for (int i = start; i < end; i++) { AppListItemView* v = static_cast<AppListItemView*>(view_model_.view_at(i)); v->Prerender(); } } bool AppsGridView::IsAnimatingView(views::View* view) { return bounds_animator_.IsAnimating(view); } gfx::Size AppsGridView::GetPreferredSize() const { const gfx::Insets insets(GetInsets()); const gfx::Size tile_size = gfx::Size(kPreferredTileWidth, kPreferredTileHeight); const int page_switcher_height = page_switcher_view_->GetPreferredSize().height(); return gfx::Size( tile_size.width() * cols_ + insets.width(), tile_size.height() * rows_per_page_ + page_switcher_height + insets.height()); } bool AppsGridView::GetDropFormats( int* formats, std::set<OSExchangeData::CustomFormat>* custom_formats) { // TODO(koz): Only accept a specific drag type for app shortcuts. *formats = OSExchangeData::FILE_NAME; return true; } bool AppsGridView::CanDrop(const OSExchangeData& data) { return true; } int AppsGridView::OnDragUpdated(const ui::DropTargetEvent& event) { return ui::DragDropTypes::DRAG_MOVE; } void AppsGridView::Layout() { if (bounds_animator_.IsAnimating()) bounds_animator_.Cancel(); CalculateIdealBounds(); for (int i = 0; i < view_model_.view_size(); ++i) { views::View* view = view_model_.view_at(i); if (view != drag_view_) view->SetBoundsRect(view_model_.ideal_bounds(i)); } views::ViewModelUtils::SetViewBoundsToIdealBounds(pulsing_blocks_model_); const int page_switcher_height = page_switcher_view_->GetPreferredSize().height(); gfx::Rect rect(GetContentsBounds()); rect.set_y(rect.bottom() - page_switcher_height); rect.set_height(page_switcher_height); page_switcher_view_->SetBoundsRect(rect); } bool AppsGridView::OnKeyPressed(const ui::KeyEvent& event) { bool handled = false; if (selected_view_) handled = selected_view_->OnKeyPressed(event); if (!handled) { const int forward_dir = base::i18n::IsRTL() ? -1 : 1; switch (event.key_code()) { case ui::VKEY_LEFT: MoveSelected(0, -forward_dir, 0); return true; case ui::VKEY_RIGHT: MoveSelected(0, forward_dir, 0); return true; case ui::VKEY_UP: MoveSelected(0, 0, -1); return true; case ui::VKEY_DOWN: MoveSelected(0, 0, 1); return true; case ui::VKEY_PRIOR: { MoveSelected(-1, 0, 0); return true; } case ui::VKEY_NEXT: { MoveSelected(1, 0, 0); return true; } default: break; } } return handled; } bool AppsGridView::OnKeyReleased(const ui::KeyEvent& event) { bool handled = false; if (selected_view_) handled = selected_view_->OnKeyReleased(event); return handled; } void AppsGridView::ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) { if (!details.is_add && details.parent == this) { // The view being delete should not have reference in |view_model_|. CHECK_EQ(-1, view_model_.GetIndexOfView(details.child)); if (selected_view_ == details.child) selected_view_ = NULL; if (activated_folder_item_view_ == details.child) activated_folder_item_view_ = NULL; if (drag_view_ == details.child) EndDrag(true); bounds_animator_.StopAnimatingView(details.child); } } void AppsGridView::Update() { DCHECK(!selected_view_ && !drag_view_); view_model_.Clear(); if (!item_list_ || !item_list_->item_count()) return; for (size_t i = 0; i < item_list_->item_count(); ++i) { views::View* view = CreateViewForItemAtIndex(i); view_model_.Add(view, i); AddChildView(view); } UpdatePaging(); UpdatePulsingBlockViews(); Layout(); SchedulePaint(); } void AppsGridView::UpdatePaging() { int total_page = view_model_.view_size() && tiles_per_page() ? (view_model_.view_size() - 1) / tiles_per_page() + 1 : 0; pagination_model_.SetTotalPages(total_page); } void AppsGridView::UpdatePulsingBlockViews() { const int existing_items = item_list_ ? item_list_->item_count() : 0; const int available_slots = tiles_per_page() - existing_items % tiles_per_page(); const int desired = model_->status() == AppListModel::STATUS_SYNCING ? available_slots : 0; if (pulsing_blocks_model_.view_size() == desired) return; while (pulsing_blocks_model_.view_size() > desired) { views::View* view = pulsing_blocks_model_.view_at(0); pulsing_blocks_model_.Remove(0); delete view; } while (pulsing_blocks_model_.view_size() < desired) { views::View* view = new PulsingBlockView( gfx::Size(kPreferredTileWidth, kPreferredTileHeight), true); pulsing_blocks_model_.Add(view, 0); AddChildView(view); } } views::View* AppsGridView::CreateViewForItemAtIndex(size_t index) { // The drag_view_ might be pending for deletion, therefore view_model_ // may have one more item than item_list_. DCHECK_LE(index, item_list_->item_count()); AppListItemView* view = new AppListItemView(this, item_list_->item_at(index)); view->SetIconSize(icon_size_); view->SetPaintToLayer(true); view->SetFillsBoundsOpaquely(false); return view; } AppsGridView::Index AppsGridView::GetIndexFromModelIndex( int model_index) const { return Index(model_index / tiles_per_page(), model_index % tiles_per_page()); } int AppsGridView::GetModelIndexFromIndex(const Index& index) const { return index.page * tiles_per_page() + index.slot; } void AppsGridView::SetSelectedItemByIndex(const Index& index) { if (GetIndexOfView(selected_view_) == index) return; views::View* new_selection = GetViewAtIndex(index); if (!new_selection) return; // Keep current selection. if (selected_view_) selected_view_->SchedulePaint(); EnsureViewVisible(new_selection); selected_view_ = new_selection; selected_view_->SchedulePaint(); selected_view_->NotifyAccessibilityEvent( ui::AX_EVENT_FOCUS, true); } bool AppsGridView::IsValidIndex(const Index& index) const { return index.page >= 0 && index.page < pagination_model_.total_pages() && index.slot >= 0 && index.slot < tiles_per_page() && GetModelIndexFromIndex(index) < view_model_.view_size(); } AppsGridView::Index AppsGridView::GetIndexOfView( const views::View* view) const { const int model_index = view_model_.GetIndexOfView(view); if (model_index == -1) return Index(); return GetIndexFromModelIndex(model_index); } views::View* AppsGridView::GetViewAtIndex(const Index& index) const { if (!IsValidIndex(index)) return NULL; const int model_index = GetModelIndexFromIndex(index); return view_model_.view_at(model_index); } void AppsGridView::MoveSelected(int page_delta, int slot_x_delta, int slot_y_delta) { if (!selected_view_) return SetSelectedItemByIndex(Index(pagination_model_.selected_page(), 0)); const Index& selected = GetIndexOfView(selected_view_); int target_slot = selected.slot + slot_x_delta + slot_y_delta * cols_; if (selected.slot % cols_ == 0 && slot_x_delta == -1) { if (selected.page > 0) { page_delta = -1; target_slot = selected.slot + cols_ - 1; } else { target_slot = selected.slot; } } if (selected.slot % cols_ == cols_ - 1 && slot_x_delta == 1) { if (selected.page < pagination_model_.total_pages() - 1) { page_delta = 1; target_slot = selected.slot - cols_ + 1; } else { target_slot = selected.slot; } } // Clamp the target slot to the last item if we are moving to the last page // but our target slot is past the end of the item list. if (page_delta && selected.page + page_delta == pagination_model_.total_pages() - 1) { int last_item_slot = (view_model_.view_size() - 1) % tiles_per_page(); if (last_item_slot < target_slot) { target_slot = last_item_slot; } } int target_page = std::min(pagination_model_.total_pages() - 1, std::max(selected.page + page_delta, 0)); SetSelectedItemByIndex(Index(target_page, target_slot)); } void AppsGridView::CalculateIdealBounds() { gfx::Rect rect(GetContentsBounds()); if (rect.IsEmpty()) return; gfx::Size tile_size(kPreferredTileWidth, kPreferredTileHeight); gfx::Rect grid_rect(gfx::Size(tile_size.width() * cols_, tile_size.height() * rows_per_page_)); grid_rect.Intersect(rect); // Page width including padding pixels. A tile.x + page_width means the same // tile slot in the next page. const int page_width = grid_rect.width() + kPagePadding; // If there is a transition, calculates offset for current and target page. const int current_page = pagination_model_.selected_page(); const PaginationModel::Transition& transition = pagination_model_.transition(); const bool is_valid = pagination_model_.is_valid_page(transition.target_page); // Transition to right means negative offset. const int dir = transition.target_page > current_page ? -1 : 1; const int transition_offset = is_valid ? transition.progress * page_width * dir : 0; const int total_views = view_model_.view_size() + pulsing_blocks_model_.view_size(); int slot_index = 0; for (int i = 0; i < total_views; ++i) { if (i < view_model_.view_size() && view_model_.view_at(i) == drag_view_) { if (EnableFolderDragDropUI() && drop_attempt_ == DROP_FOR_FOLDER) ++slot_index; continue; } Index view_index = GetIndexFromModelIndex(slot_index); if (drop_target_ == view_index) { if (EnableFolderDragDropUI() && drop_attempt_ == DROP_FOR_FOLDER) { view_index = GetIndexFromModelIndex(slot_index); } else if (!EnableFolderDragDropUI() || drop_attempt_ == DROP_FOR_REORDER) { ++slot_index; view_index = GetIndexFromModelIndex(slot_index); } } // Decides an x_offset for current item. int x_offset = 0; if (view_index.page < current_page) x_offset = -page_width; else if (view_index.page > current_page) x_offset = page_width; if (is_valid) { if (view_index.page == current_page || view_index.page == transition.target_page) { x_offset += transition_offset; } } const int row = view_index.slot / cols_; const int col = view_index.slot % cols_; gfx::Rect tile_slot( gfx::Point(grid_rect.x() + col * tile_size.width() + x_offset, grid_rect.y() + row * tile_size.height()), tile_size); if (i < view_model_.view_size()) { view_model_.set_ideal_bounds(i, tile_slot); } else { pulsing_blocks_model_.set_ideal_bounds(i - view_model_.view_size(), tile_slot); } ++slot_index; } } void AppsGridView::AnimateToIdealBounds() { const gfx::Rect visible_bounds(GetVisibleBounds()); CalculateIdealBounds(); for (int i = 0; i < view_model_.view_size(); ++i) { views::View* view = view_model_.view_at(i); if (view == drag_view_) continue; const gfx::Rect& target = view_model_.ideal_bounds(i); if (bounds_animator_.GetTargetBounds(view) == target) continue; const gfx::Rect& current = view->bounds(); const bool current_visible = visible_bounds.Intersects(current); const bool target_visible = visible_bounds.Intersects(target); const bool visible = current_visible || target_visible; const int y_diff = target.y() - current.y(); if (visible && y_diff && y_diff % kPreferredTileHeight == 0) { AnimationBetweenRows(view, current_visible, current, target_visible, target); } else if (visible || bounds_animator_.IsAnimating(view)) { bounds_animator_.AnimateViewTo(view, target); bounds_animator_.SetAnimationDelegate( view, scoped_ptr<gfx::AnimationDelegate>( new ItemMoveAnimationDelegate(view))); } else { view->SetBoundsRect(target); } } } void AppsGridView::AnimationBetweenRows(views::View* view, bool animate_current, const gfx::Rect& current, bool animate_target, const gfx::Rect& target) { // Determine page of |current| and |target|. -1 means in the left invisible // page, 0 is the center visible page and 1 means in the right invisible page. const int current_page = current.x() < 0 ? -1 : current.x() >= width() ? 1 : 0; const int target_page = target.x() < 0 ? -1 : target.x() >= width() ? 1 : 0; const int dir = current_page < target_page || (current_page == target_page && current.y() < target.y()) ? 1 : -1; scoped_ptr<ui::Layer> layer; if (animate_current) { layer = view->RecreateLayer(); layer->SuppressPaint(); view->SetFillsBoundsOpaquely(false); view->layer()->SetOpacity(0.f); } gfx::Rect current_out(current); current_out.Offset(dir * kPreferredTileWidth, 0); gfx::Rect target_in(target); if (animate_target) target_in.Offset(-dir * kPreferredTileWidth, 0); view->SetBoundsRect(target_in); bounds_animator_.AnimateViewTo(view, target); bounds_animator_.SetAnimationDelegate( view, scoped_ptr<gfx::AnimationDelegate>( new RowMoveAnimationDelegate(view, layer.release(), current_out))); } void AppsGridView::ExtractDragLocation(const ui::LocatedEvent& event, gfx::Point* drag_point) { #if defined(USE_AURA) && !defined(OS_WIN) // Use root location of |event| instead of location in |drag_view_|'s // coordinates because |drag_view_| has a scale transform and location // could have integer round error and causes jitter. *drag_point = event.root_location(); // GetWidget() could be NULL for tests. if (GetWidget()) { aura::Window::ConvertPointToTarget( GetWidget()->GetNativeWindow()->GetRootWindow(), GetWidget()->GetNativeWindow(), drag_point); } views::View::ConvertPointFromWidget(this, drag_point); #else // For non-aura, root location is not clearly defined but |drag_view_| does // not have the scale transform. So no round error would be introduced and // it's okay to use View::ConvertPointToTarget. *drag_point = event.location(); views::View::ConvertPointToTarget(drag_view_, this, drag_point); #endif } void AppsGridView::CalculateDropTarget(const gfx::Point& drag_point, bool use_page_button_hovering) { if (EnableFolderDragDropUI()) { CalculateDropTargetWithFolderEnabled(drag_point, use_page_button_hovering); return; } int current_page = pagination_model_.selected_page(); gfx::Point point(drag_point); if (!IsPointWithinDragBuffer(drag_point)) { point = drag_start_grid_view_; current_page = drag_start_page_; } if (use_page_button_hovering && page_switcher_view_->bounds().Contains(point)) { gfx::Point page_switcher_point(point); views::View::ConvertPointToTarget(this, page_switcher_view_, &page_switcher_point); int page = page_switcher_view_->GetPageForPoint(page_switcher_point); if (pagination_model_.is_valid_page(page)) { drop_target_.page = page; drop_target_.slot = tiles_per_page() - 1; } } else { gfx::Rect bounds(GetContentsBounds()); const int drop_row = (point.y() - bounds.y()) / kPreferredTileHeight; const int drop_col = std::min(cols_ - 1, (point.x() - bounds.x()) / kPreferredTileWidth); drop_target_.page = current_page; drop_target_.slot = std::max(0, std::min( tiles_per_page() - 1, drop_row * cols_ + drop_col)); } // Limits to the last possible slot on last page. if (drop_target_.page == pagination_model_.total_pages() - 1) { drop_target_.slot = std::min( (view_model_.view_size() - 1) % tiles_per_page(), drop_target_.slot); } } void AppsGridView::CalculateDropTargetWithFolderEnabled( const gfx::Point& drag_point, bool use_page_button_hovering) { gfx::Point point(drag_point); if (!IsPointWithinDragBuffer(drag_point)) { point = drag_start_grid_view_; } if (use_page_button_hovering && page_switcher_view_->bounds().Contains(point)) { gfx::Point page_switcher_point(point); views::View::ConvertPointToTarget(this, page_switcher_view_, &page_switcher_point); int page = page_switcher_view_->GetPageForPoint(page_switcher_point); if (pagination_model_.is_valid_page(page)) drop_attempt_ = DROP_FOR_NONE; } else { DCHECK(drag_view_); // Try to find the nearest target for folder dropping or re-ordering. drop_target_ = GetNearestTileForDragView(); } } void AppsGridView::OnReorderTimer() { if (drop_attempt_ == DROP_FOR_REORDER) AnimateToIdealBounds(); } void AppsGridView::OnFolderItemReparentTimer() { DCHECK(folder_delegate_); if (drag_out_of_folder_container_ && drag_view_) { folder_delegate_->ReparentItem(drag_view_, last_drag_point_); // Set the flag in the folder's grid view. dragging_for_reparent_item_ = true; // Do not observe any data change since it is going to be hidden. item_list_->RemoveObserver(this); item_list_ = NULL; } } void AppsGridView::OnFolderDroppingTimer() { if (drop_attempt_ == DROP_FOR_FOLDER) SetAsFolderDroppingTarget(drop_target_, true); } void AppsGridView::UpdateDragStateInsideFolder(Pointer pointer, const gfx::Point& drag_point) { if (IsUnderOEMFolder()) return; if (IsDraggingForReparentInHiddenGridView()) { // Dispatch drag event to root level grid view for re-parenting folder // folder item purpose. DispatchDragEventForReparent(pointer, drag_point); return; } // Regular drag and drop in a folder's grid view. folder_delegate_->UpdateFolderViewBackground(true); // Calculate if the drag_view_ is dragged out of the folder's container // ink bubble. gfx::Rect bounds_to_folder_view = ConvertRectToParent(drag_view_->bounds()); gfx::Point pt = bounds_to_folder_view.CenterPoint(); bool is_item_dragged_out_of_folder = folder_delegate_->IsPointOutsideOfFolderBoundary(pt); if (is_item_dragged_out_of_folder) { if (!drag_out_of_folder_container_) { folder_item_reparent_timer_.Start( FROM_HERE, base::TimeDelta::FromMilliseconds(kFolderItemReparentDelay), this, &AppsGridView::OnFolderItemReparentTimer); drag_out_of_folder_container_ = true; } } else { folder_item_reparent_timer_.Stop(); drag_out_of_folder_container_ = false; } } bool AppsGridView::IsDraggingForReparentInRootLevelGridView() const { return (!folder_delegate_ && dragging_for_reparent_item_); } bool AppsGridView::IsDraggingForReparentInHiddenGridView() const { return (folder_delegate_ && dragging_for_reparent_item_); } gfx::Rect AppsGridView::GetTargetIconRectInFolder( AppListItemView* drag_item_view, AppListItemView* folder_item_view) { gfx::Rect view_ideal_bounds = view_model_.ideal_bounds( view_model_.GetIndexOfView(folder_item_view)); gfx::Rect icon_ideal_bounds = folder_item_view->GetIconBoundsForTargetViewBounds(view_ideal_bounds); AppListFolderItem* folder_item = static_cast<AppListFolderItem*>(folder_item_view->item()); return folder_item->GetTargetIconRectInFolderForItem( drag_item_view->item(), icon_ideal_bounds); } bool AppsGridView::IsUnderOEMFolder() { if (!folder_delegate_) return false; return folder_delegate_->IsOEMFolder(); } void AppsGridView::DispatchDragEventForReparent(Pointer pointer, const gfx::Point& drag_point) { folder_delegate_->DispatchDragEventForReparent(pointer, drag_point); } void AppsGridView::EndDragFromReparentItemInRootLevel( bool events_forwarded_to_drag_drop_host, bool cancel_drag) { // EndDrag was called before if |drag_view_| is NULL. if (!drag_view_) return; DCHECK(IsDraggingForReparentInRootLevelGridView()); bool cancel_reparent = cancel_drag || drop_attempt_ == DROP_FOR_NONE; if (!events_forwarded_to_drag_drop_host && !cancel_reparent) { CalculateDropTarget(last_drag_point_, true); if (IsValidIndex(drop_target_)) { if (drop_attempt_ == DROP_FOR_REORDER) { ReparentItemForReorder(drag_view_, drop_target_); } else if (drop_attempt_ == DROP_FOR_FOLDER) { ReparentItemToAnotherFolder(drag_view_, drop_target_); } } SetViewHidden(drag_view_, false /* show */, true /* no animate */); } // The drag can be ended after the synchronous drag is created but before it // is Run(). CleanUpSynchronousDrag(); SetAsFolderDroppingTarget(drop_target_, false); if (cancel_reparent) { CancelFolderItemReparent(drag_view_); } else { // By setting |drag_view_| to NULL here, we prevent ClearDragState() from // cleaning up the newly created AppListItemView, effectively claiming // ownership of the newly created drag view. drag_view_->OnDragEnded(); drag_view_ = NULL; } ClearDragState(); AnimateToIdealBounds(); StopPageFlipTimer(); } void AppsGridView::EndDragForReparentInHiddenFolderGridView() { if (drag_and_drop_host_) { // If we had a drag and drop proxy icon, we delete it and make the real // item visible again. drag_and_drop_host_->DestroyDragIconProxy(); } // The drag can be ended after the synchronous drag is created but before it // is Run(). CleanUpSynchronousDrag(); SetAsFolderDroppingTarget(drop_target_, false); ClearDragState(); } void AppsGridView::OnFolderItemRemoved() { DCHECK(folder_delegate_); item_list_ = NULL; } void AppsGridView::StartDragAndDropHostDrag(const gfx::Point& grid_location) { // When a drag and drop host is given, the item can be dragged out of the app // list window. In that case a proxy widget needs to be used. // Note: This code has very likely to be changed for Windows (non metro mode) // when a |drag_and_drop_host_| gets implemented. if (!drag_view_ || !drag_and_drop_host_) return; gfx::Point screen_location = grid_location; views::View::ConvertPointToScreen(this, &screen_location); // Determine the mouse offset to the center of the icon so that the drag and // drop host follows this layer. gfx::Vector2d delta = drag_view_offset_ - drag_view_->GetLocalBounds().CenterPoint(); delta.set_y(delta.y() + drag_view_->title()->size().height() / 2); // We have to hide the original item since the drag and drop host will do // the OS dependent code to "lift off the dragged item". DCHECK(!IsDraggingForReparentInRootLevelGridView()); drag_and_drop_host_->CreateDragIconProxy(screen_location, drag_view_->item()->icon(), drag_view_, delta, kDragAndDropProxyScale); SetViewHidden(drag_view_, true /* hide */, true /* no animation */); } void AppsGridView::DispatchDragEventToDragAndDropHost( const gfx::Point& location_in_screen_coordinates) { if (!drag_view_ || !drag_and_drop_host_) return; if (GetLocalBounds().Contains(last_drag_point_)) { // The event was issued inside the app menu and we should get all events. if (forward_events_to_drag_and_drop_host_) { // The DnD host was previously called and needs to be informed that the // session returns to the owner. forward_events_to_drag_and_drop_host_ = false; drag_and_drop_host_->EndDrag(true); } } else { if (IsFolderItem(drag_view_->item())) return; // The event happened outside our app menu and we might need to dispatch. if (forward_events_to_drag_and_drop_host_) { // Dispatch since we have already started. if (!drag_and_drop_host_->Drag(location_in_screen_coordinates)) { // The host is not active any longer and we cancel the operation. forward_events_to_drag_and_drop_host_ = false; drag_and_drop_host_->EndDrag(true); } } else { if (drag_and_drop_host_->StartDrag(drag_view_->item()->id(), location_in_screen_coordinates)) { // From now on we forward the drag events. forward_events_to_drag_and_drop_host_ = true; // Any flip operations are stopped. StopPageFlipTimer(); } } } } void AppsGridView::MaybeStartPageFlipTimer(const gfx::Point& drag_point) { if (!IsPointWithinDragBuffer(drag_point)) StopPageFlipTimer(); int new_page_flip_target = -1; if (page_switcher_view_->bounds().Contains(drag_point)) { gfx::Point page_switcher_point(drag_point); views::View::ConvertPointToTarget(this, page_switcher_view_, &page_switcher_point); new_page_flip_target = page_switcher_view_->GetPageForPoint(page_switcher_point); } // TODO(xiyuan): Fix this for RTL. if (new_page_flip_target == -1 && drag_point.x() < kPageFlipZoneSize) new_page_flip_target = pagination_model_.selected_page() - 1; if (new_page_flip_target == -1 && drag_point.x() > width() - kPageFlipZoneSize) { new_page_flip_target = pagination_model_.selected_page() + 1; } if (new_page_flip_target == page_flip_target_) return; StopPageFlipTimer(); if (pagination_model_.is_valid_page(new_page_flip_target)) { page_flip_target_ = new_page_flip_target; if (page_flip_target_ != pagination_model_.selected_page()) { page_flip_timer_.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(page_flip_delay_in_ms_), this, &AppsGridView::OnPageFlipTimer); } } } void AppsGridView::OnPageFlipTimer() { DCHECK(pagination_model_.is_valid_page(page_flip_target_)); pagination_model_.SelectPage(page_flip_target_, true); } void AppsGridView::MoveItemInModel(views::View* item_view, const Index& target) { int current_model_index = view_model_.GetIndexOfView(item_view); DCHECK_GE(current_model_index, 0); int target_model_index = GetModelIndexFromIndex(target); if (target_model_index == current_model_index) return; item_list_->RemoveObserver(this); item_list_->MoveItem(current_model_index, target_model_index); view_model_.Move(current_model_index, target_model_index); item_list_->AddObserver(this); if (pagination_model_.selected_page() != target.page) pagination_model_.SelectPage(target.page, false); } void AppsGridView::MoveItemToFolder(views::View* item_view, const Index& target) { const std::string& source_item_id = static_cast<AppListItemView*>(item_view)->item()->id(); AppListItemView* target_view = static_cast<AppListItemView*>(GetViewAtSlotOnCurrentPage(target.slot)); const std::string& target_view_item_id = target_view->item()->id(); // Make change to data model. item_list_->RemoveObserver(this); std::string folder_item_id = model_->MergeItems(target_view_item_id, source_item_id); item_list_->AddObserver(this); if (folder_item_id.empty()) { LOG(ERROR) << "Unable to merge into item id: " << target_view_item_id; return; } if (folder_item_id != target_view_item_id) { // New folder was created, change the view model to replace the old target // view with the new folder item view. size_t folder_item_index; if (item_list_->FindItemIndex(folder_item_id, &folder_item_index)) { int target_view_index = view_model_.GetIndexOfView(target_view); gfx::Rect target_view_bounds = target_view->bounds(); DeleteItemViewAtIndex(target_view_index); views::View* target_folder_view = CreateViewForItemAtIndex(folder_item_index); target_folder_view->SetBoundsRect(target_view_bounds); view_model_.Add(target_folder_view, target_view_index); AddChildView(target_folder_view); } else { LOG(ERROR) << "Folder no longer in item_list: " << folder_item_id; } } // Fade out the drag_view_ and delete it when animation ends. int drag_view_index = view_model_.GetIndexOfView(drag_view_); view_model_.Remove(drag_view_index); bounds_animator_.AnimateViewTo(drag_view_, drag_view_->bounds()); bounds_animator_.SetAnimationDelegate( drag_view_, scoped_ptr<gfx::AnimationDelegate>( new ItemRemoveAnimationDelegate(drag_view_))); UpdatePaging(); } void AppsGridView::ReparentItemForReorder(views::View* item_view, const Index& target) { item_list_->RemoveObserver(this); model_->RemoveObserver(this); AppListItem* reparent_item = static_cast<AppListItemView*>(item_view)->item(); DCHECK(reparent_item->IsInFolder()); const std::string source_folder_id = reparent_item->folder_id(); AppListFolderItem* source_folder = static_cast<AppListFolderItem*>(item_list_->FindItem(source_folder_id)); int target_model_index = GetModelIndexFromIndex(target); // Remove the source folder view if there is only 1 item in it, since the // source folder will be deleted after its only child item removed from it. if (source_folder->ChildItemCount() == 1u) { const int deleted_folder_index = view_model_.GetIndexOfView(activated_folder_item_view()); DeleteItemViewAtIndex(deleted_folder_index); // Adjust |target_model_index| if it is beyond the deleted folder index. if (target_model_index > deleted_folder_index) --target_model_index; } // Move the item from its parent folder to top level item list. // Must move to target_model_index, the location we expect the target item // to be, not the item location we want to insert before. int current_model_index = view_model_.GetIndexOfView(item_view); syncer::StringOrdinal target_position; if (target_model_index < static_cast<int>(item_list_->item_count())) target_position = item_list_->item_at(target_model_index)->position(); model_->MoveItemToFolderAt(reparent_item, "", target_position); view_model_.Move(current_model_index, target_model_index); RemoveLastItemFromReparentItemFolderIfNecessary(source_folder_id); item_list_->AddObserver(this); model_->AddObserver(this); UpdatePaging(); } void AppsGridView::ReparentItemToAnotherFolder(views::View* item_view, const Index& target) { DCHECK(IsDraggingForReparentInRootLevelGridView()); AppListItemView* target_view = static_cast<AppListItemView*>(GetViewAtSlotOnCurrentPage(target.slot)); if (!target_view) return; // Make change to data model. item_list_->RemoveObserver(this); AppListItem* reparent_item = static_cast<AppListItemView*>(item_view)->item(); DCHECK(reparent_item->IsInFolder()); const std::string source_folder_id = reparent_item->folder_id(); AppListFolderItem* source_folder = static_cast<AppListFolderItem*>(item_list_->FindItem(source_folder_id)); // Remove the source folder view if there is only 1 item in it, since the // source folder will be deleted after its only child item merged into the // target item. if (source_folder->ChildItemCount() == 1u) DeleteItemViewAtIndex( view_model_.GetIndexOfView(activated_folder_item_view())); AppListItem* target_item = target_view->item(); // Move item to the target folder. std::string target_id_after_merge = model_->MergeItems(target_item->id(), reparent_item->id()); if (target_id_after_merge.empty()) { LOG(ERROR) << "Unable to reparent to item id: " << target_item->id(); item_list_->AddObserver(this); return; } if (target_id_after_merge != target_item->id()) { // New folder was created, change the view model to replace the old target // view with the new folder item view. const std::string& new_folder_id = reparent_item->folder_id(); size_t new_folder_index; if (item_list_->FindItemIndex(new_folder_id, &new_folder_index)) { int target_view_index = view_model_.GetIndexOfView(target_view); DeleteItemViewAtIndex(target_view_index); views::View* new_folder_view = CreateViewForItemAtIndex(new_folder_index); view_model_.Add(new_folder_view, target_view_index); AddChildView(new_folder_view); } else { LOG(ERROR) << "Folder no longer in item_list: " << new_folder_id; } } RemoveLastItemFromReparentItemFolderIfNecessary(source_folder_id); item_list_->AddObserver(this); // Fade out the drag_view_ and delete it when animation ends. int drag_view_index = view_model_.GetIndexOfView(drag_view_); view_model_.Remove(drag_view_index); bounds_animator_.AnimateViewTo(drag_view_, drag_view_->bounds()); bounds_animator_.SetAnimationDelegate( drag_view_, scoped_ptr<gfx::AnimationDelegate>( new ItemRemoveAnimationDelegate(drag_view_))); UpdatePaging(); } // After moving the re-parenting item out of the folder, if there is only 1 item // left, remove the last item out of the folder, delete the folder and insert it // to the data model at the same position. Make the same change to view_model_ // accordingly. void AppsGridView::RemoveLastItemFromReparentItemFolderIfNecessary( const std::string& source_folder_id) { AppListFolderItem* source_folder = static_cast<AppListFolderItem*>(item_list_->FindItem(source_folder_id)); if (!source_folder || source_folder->ChildItemCount() != 1u) return; // Delete view associated with the folder item to be removed. DeleteItemViewAtIndex( view_model_.GetIndexOfView(activated_folder_item_view())); // Now make the data change to remove the folder item in model. AppListItem* last_item = source_folder->item_list()->item_at(0); model_->MoveItemToFolderAt(last_item, "", source_folder->position()); // Create a new item view for the last item in folder. size_t last_item_index; if (!item_list_->FindItemIndex(last_item->id(), &last_item_index) || last_item_index > static_cast<size_t>(view_model_.view_size())) { NOTREACHED(); return; } views::View* last_item_view = CreateViewForItemAtIndex(last_item_index); view_model_.Add(last_item_view, last_item_index); AddChildView(last_item_view); } void AppsGridView::CancelFolderItemReparent(AppListItemView* drag_item_view) { // The icon of the dragged item must target to its final ideal bounds after // the animation completes. CalculateIdealBounds(); gfx::Rect target_icon_rect = GetTargetIconRectInFolder(drag_item_view, activated_folder_item_view_); gfx::Rect drag_view_icon_to_grid = drag_item_view->ConvertRectToParent(drag_item_view->GetIconBounds()); drag_view_icon_to_grid.ClampToCenteredSize( gfx::Size(kPreferredIconDimension, kPreferredIconDimension)); TopIconAnimationView* icon_view = new TopIconAnimationView( drag_item_view->item()->icon(), target_icon_rect, false); /* animate like closing folder */ AddChildView(icon_view); icon_view->SetBoundsRect(drag_view_icon_to_grid); icon_view->TransformView(); } void AppsGridView::CancelContextMenusOnCurrentPage() { int start = pagination_model_.selected_page() * tiles_per_page(); int end = std::min(view_model_.view_size(), start + tiles_per_page()); for (int i = start; i < end; ++i) { AppListItemView* view = static_cast<AppListItemView*>(view_model_.view_at(i)); view->CancelContextMenu(); } } void AppsGridView::DeleteItemViewAtIndex(int index) { views::View* item_view = view_model_.view_at(index); view_model_.Remove(index); if (item_view == drag_view_) drag_view_ = NULL; delete item_view; } bool AppsGridView::IsPointWithinDragBuffer(const gfx::Point& point) const { gfx::Rect rect(GetLocalBounds()); rect.Inset(-kDragBufferPx, -kDragBufferPx, -kDragBufferPx, -kDragBufferPx); return rect.Contains(point); } void AppsGridView::ButtonPressed(views::Button* sender, const ui::Event& event) { if (dragging()) return; if (strcmp(sender->GetClassName(), AppListItemView::kViewClassName)) return; if (delegate_) { // Always set the previous activated_folder_item_view_ to be visible. This // prevents a case where the item would remain hidden due the // |activated_folder_item_view_| changing during the animation. We only // need to track |activated_folder_item_view_| in the root level grid view. if (!folder_delegate_) { if (activated_folder_item_view_) activated_folder_item_view_->SetVisible(true); AppListItemView* pressed_item_view = static_cast<AppListItemView*>(sender); if (IsFolderItem(pressed_item_view->item())) activated_folder_item_view_ = pressed_item_view; else activated_folder_item_view_ = NULL; } delegate_->ActivateApp(static_cast<AppListItemView*>(sender)->item(), event.flags()); } } void AppsGridView::OnListItemAdded(size_t index, AppListItem* item) { EndDrag(true); views::View* view = CreateViewForItemAtIndex(index); view_model_.Add(view, index); AddChildView(view); UpdatePaging(); UpdatePulsingBlockViews(); Layout(); SchedulePaint(); } void AppsGridView::OnListItemRemoved(size_t index, AppListItem* item) { EndDrag(true); DeleteItemViewAtIndex(index); UpdatePaging(); UpdatePulsingBlockViews(); Layout(); SchedulePaint(); } void AppsGridView::OnListItemMoved(size_t from_index, size_t to_index, AppListItem* item) { EndDrag(true); view_model_.Move(from_index, to_index); UpdatePaging(); AnimateToIdealBounds(); } void AppsGridView::TotalPagesChanged() { } void AppsGridView::SelectedPageChanged(int old_selected, int new_selected) { if (dragging()) { CalculateDropTarget(last_drag_point_, true); Layout(); MaybeStartPageFlipTimer(last_drag_point_); } else { ClearSelectedView(selected_view_); Layout(); } } void AppsGridView::TransitionStarted() { CancelContextMenusOnCurrentPage(); } void AppsGridView::TransitionChanged() { // Update layout for valid page transition only since over-scroll no longer // animates app icons. const PaginationModel::Transition& transition = pagination_model_.transition(); if (pagination_model_.is_valid_page(transition.target_page)) Layout(); } void AppsGridView::OnAppListModelStatusChanged() { UpdatePulsingBlockViews(); Layout(); SchedulePaint(); } void AppsGridView::SetViewHidden(views::View* view, bool hide, bool immediate) { ui::ScopedLayerAnimationSettings animator(view->layer()->GetAnimator()); animator.SetPreemptionStrategy( immediate ? ui::LayerAnimator::IMMEDIATELY_SET_NEW_TARGET : ui::LayerAnimator::BLEND_WITH_CURRENT_ANIMATION); view->layer()->SetOpacity(hide ? 0 : 1); } void AppsGridView::OnImplicitAnimationsCompleted() { if (layer()->opacity() == 0.0f) SetVisible(false); } bool AppsGridView::EnableFolderDragDropUI() { // Enable drag and drop folder UI only if it is at the app list root level // and the switch is on and the target folder can still accept new items. return model_->folders_enabled() && !folder_delegate_ && CanDropIntoTarget(drop_target_); } bool AppsGridView::CanDropIntoTarget(const Index& drop_target) { views::View* target_view = GetViewAtSlotOnCurrentPage(drop_target.slot); if (!target_view) return true; AppListItem* target_item = static_cast<AppListItemView*>(target_view)->item(); // Items can be dropped into non-folders (which have no children) or folders // that have fewer than the max allowed items. // OEM folder does not allow to drag/drop other items in it. return target_item->ChildItemCount() < kMaxFolderItems && !IsOEMFolderItem(target_item); } // TODO(jennyz): Optimize the calculation for finding nearest tile. AppsGridView::Index AppsGridView::GetNearestTileForDragView() { Index nearest_tile; nearest_tile.page = -1; nearest_tile.slot = -1; int d_min = -1; // Calculate the top left tile |drag_view| intersects. gfx::Point pt = drag_view_->bounds().origin(); CalculateNearestTileForVertex(pt, &nearest_tile, &d_min); // Calculate the top right tile |drag_view| intersects. pt = drag_view_->bounds().top_right(); CalculateNearestTileForVertex(pt, &nearest_tile, &d_min); // Calculate the bottom left tile |drag_view| intersects. pt = drag_view_->bounds().bottom_left(); CalculateNearestTileForVertex(pt, &nearest_tile, &d_min); // Calculate the bottom right tile |drag_view| intersects. pt = drag_view_->bounds().bottom_right(); CalculateNearestTileForVertex(pt, &nearest_tile, &d_min); const int d_folder_dropping = kFolderDroppingCircleRadius + kPreferredIconDimension / 2; const int d_reorder = kReorderDroppingCircleRadius + kPreferredIconDimension / 2; // If user drags an item across pages to the last page, and targets it // to the last empty slot on it, push the last item for re-ordering. if (IsLastPossibleDropTarget(nearest_tile) && d_min < d_reorder) { drop_attempt_ = DROP_FOR_REORDER; nearest_tile.slot = nearest_tile.slot - 1; return nearest_tile; } if (IsValidIndex(nearest_tile)) { if (d_min < d_folder_dropping) { views::View* target_view = GetViewAtSlotOnCurrentPage(nearest_tile.slot); if (target_view && !IsFolderItem(static_cast<AppListItemView*>(drag_view_)->item())) { // If a non-folder item is dragged to the target slot with an item // sitting on it, attempt to drop the dragged item into the folder // containing the item on nearest_tile. drop_attempt_ = DROP_FOR_FOLDER; return nearest_tile; } else { // If the target slot is blank, or the dragged item is a folder, attempt // to re-order. drop_attempt_ = DROP_FOR_REORDER; return nearest_tile; } } else if (d_min < d_reorder) { // Entering the re-order circle of the slot. drop_attempt_ = DROP_FOR_REORDER; return nearest_tile; } } // If |drag_view| is not entering the re-order or fold dropping region of // any items, cancel any previous re-order or folder dropping timer, and // return itself. drop_attempt_ = DROP_FOR_NONE; reorder_timer_.Stop(); folder_dropping_timer_.Stop(); // When dragging for reparent a folder item, it should go back to its parent // folder item if there is no drop target. if (IsDraggingForReparentInRootLevelGridView()) { DCHECK(activated_folder_item_view_); return GetIndexOfView(activated_folder_item_view_); } return GetIndexOfView(drag_view_); } void AppsGridView::CalculateNearestTileForVertex(const gfx::Point& vertex, Index* nearest_tile, int* d_min) { Index target_index; gfx::Rect target_bounds = GetTileBoundsForPoint(vertex, &target_index); if (target_bounds.IsEmpty() || target_index == *nearest_tile) return; // Do not count the tile, where drag_view_ used to sit on and is still moving // on top of it, in calculating nearest tile for drag_view_. views::View* target_view = GetViewAtSlotOnCurrentPage(target_index.slot); if (target_index == drag_view_init_index_ && !target_view && !IsDraggingForReparentInRootLevelGridView()) { return; } int d_center = GetDistanceBetweenRects(drag_view_->bounds(), target_bounds); if (*d_min < 0 || d_center < *d_min) { *d_min = d_center; *nearest_tile = target_index; } } gfx::Rect AppsGridView::GetTileBoundsForPoint(const gfx::Point& point, Index *tile_index) { // Check if |point| is outside of contents bounds. gfx::Rect bounds(GetContentsBounds()); if (!bounds.Contains(point)) return gfx::Rect(); // Calculate which tile |point| is enclosed in. int x = point.x(); int y = point.y(); int col = (x - bounds.x()) / kPreferredTileWidth; int row = (y - bounds.y()) / kPreferredTileHeight; gfx::Rect tile_rect = GetTileBounds(row, col); // Check if |point| is outside a valid item's tile. Index index(pagination_model_.selected_page(), row * cols_ + col); *tile_index = index; return tile_rect; } gfx::Rect AppsGridView::GetTileBounds(int row, int col) const { gfx::Rect bounds(GetContentsBounds()); gfx::Size tile_size(kPreferredTileWidth, kPreferredTileHeight); gfx::Rect grid_rect(gfx::Size(tile_size.width() * cols_, tile_size.height() * rows_per_page_)); grid_rect.Intersect(bounds); gfx::Rect tile_rect( gfx::Point(grid_rect.x() + col * tile_size.width(), grid_rect.y() + row * tile_size.height()), tile_size); return tile_rect; } bool AppsGridView::IsLastPossibleDropTarget(const Index& index) const { int last_possible_slot = view_model_.view_size() % tiles_per_page(); return (index.page == pagination_model_.total_pages() - 1 && index.slot == last_possible_slot + 1); } views::View* AppsGridView::GetViewAtSlotOnCurrentPage(int slot) { if (slot < 0) return NULL; // Calculate the original bound of the tile at |index|. int row = slot / cols_; int col = slot % cols_; gfx::Rect tile_rect = GetTileBounds(row, col); for (int i = 0; i < view_model_.view_size(); ++i) { views::View* view = view_model_.view_at(i); if (view->bounds() == tile_rect && view != drag_view_) return view; } return NULL; } void AppsGridView::SetAsFolderDroppingTarget(const Index& target_index, bool is_target_folder) { AppListItemView* target_view = static_cast<AppListItemView*>( GetViewAtSlotOnCurrentPage(target_index.slot)); if (target_view) target_view->SetAsAttemptedFolderTarget(is_target_folder); } } // namespace app_list
[ "mrobbeloth@pdiarm.com" ]
mrobbeloth@pdiarm.com
62f2c03046d409d07addc69ef2566f1d59190278
5f17573507d160aa087b02d0f00d97be7a603f6c
/319c.cpp
efe802d35c90df985aa1c2bf61c6c3d4fd686578
[]
no_license
nishnik/Competitive-Programming
33590ea882e449947befc36594fd20c720c05049
cab12301ca7343b6e5f4464fcfbb84b437379da8
refs/heads/master
2021-01-10T05:43:44.252506
2016-02-23T14:14:03
2016-02-23T14:14:03
52,363,354
0
0
null
null
null
null
UTF-8
C++
false
false
2,005
cpp
#include <bits/stdc++.h> //usage getline(cin,str_name); #define rep(i, n) for(__typeof(n) i = 0; i < (n); i++) #define rrep(i, n) for(__typeof(n) i = (n) - 1; i >= 0; --i) #define rep1(i, n) for(__typeof(n) i = 1; i <= (n); i++) #define FOR(i, a, b) for(__typeof(b) i = (a); i <= (b); i++) #define forstl(i, s) for (__typeof ((s).end ()) i = (s).begin (); i != (s).end (); ++i) #define all(a) a.begin(),a.end() #define rall(a) a.rbegin(),a.rend() #define ll long long #define vi vector<int> #define vvi vector<vi > #define vl vector<long> #define vvl vector<vl > #define vll vector<long long> #define vvll vector<vll > #define mp make_pair /* Usage: Just create an instance of it at the start of the block of which you want to measure running time. Reliable up to millisecond scale. You don't need to do anything else, even works with freopen. */ class TimeTracker { clock_t start, end; public: TimeTracker() { start = clock(); } ~TimeTracker() { end = clock(); //fprintf(stderr, "%.3lf s\n", (double)(end - start) / CLOCKS_PER_SEC); } }; using namespace std; int main() { ios::sync_with_stdio(false); int n; cin>>n; vector<int> arr(n+1,0); int count=0; for(int i=2;i<n+1;i++) { if(arr[i]==0) { int flag=-1; for(int j=i-1;j>=2;j--) { /*if(i==16 && j==8) cout<<"---"<<arr[j]<< */ if(i%j==0 && arr[j]!=1 && arr[i/j]==1 ) { arr[j]=1; flag=j; break; } } int q; if(flag==-1) {arr[i]=1;q=i;} else {q=flag;} count++; for(int j=i-1;j>=2;j--) { if(q*j<=n && arr[j]==1) arr[q*j]=2; } } } cout<<count<<"\n"; for(int i=2;i<=n ;i++) { if(arr[i]==1) cout<<i<<" "; } }
[ "nishantiam@gmail.com" ]
nishantiam@gmail.com
7219bf2a0c913ae407ae363b504d8f6ee6025afa
5552798e3562cad0b615b6141f8ea33214bba861
/C++/Codeforces/newyearpermu.cpp
fcb3ea8b95d3e153f8ca3ba46986d22498ea5867
[]
no_license
YashSharma/C-files
3922994cf7f0f5947173aa2b26a7dc399919267b
3d7107e16c428ee056814b33ca9b89ab113b0753
refs/heads/master
2016-08-12T09:16:25.499792
2015-12-20T08:24:47
2015-12-20T08:24:47
48,312,664
0
0
null
null
null
null
UTF-8
C++
false
false
1,817
cpp
#include<iostream> #include<stdio.h> #include<algorithm> using namespace std; static int a[302][302]; bool visited[302]={0}; static int test[302]; static int position[302]; static int p[302]; int pos=0; void tovisit(int n,int size) { int flag=0,i=n,j; visited[i]=1; for(j=0;j<size;j++) { if(visited[j]==0) { if(a[i][j]==1) { test[pos]=p[j]; position[pos++]=j; tovisit(j,size); } } } } int bfs(int size) { int i,j,flag=0; sort(position,position+pos); sort(test,test+pos); for(i=0;i<pos;i++) { p[position[i]]=test[i]; } for(i=0;i<size;i++) { if(!visited[i]) { for(j=0;j<size;j++) { if(!visited[j]) { if(a[i][j]==1) { pos=0; test[pos]=p[i]; position[pos++]=i; flag=1; tovisit(i,size); break; } } } if(flag) return 1; } } return 0; } int main() { int n,ret=1,i,j,flag=0; char st[302]; scanf("%d",&n); for(i=0;i<n;i++) { visited[i]=0; } for(i=0;i<n;i++) { scanf("%d",&p[i]); } for(i=0;i<n;i++) { cin>>st; for(j=0;j<n;j++) { if(st[j]=='0') a[i][j]=0; else a[i][j]=1; } } for(i=0;i<n;i++) { for(j=0;j<n;j++) { if(a[i][j]==1) { test[pos]=p[i]; position[pos++]=i; tovisit(i,n); flag=1; break; } } if(flag) break; visited[i]=1; } while(ret) { ret=bfs(n); } for(i=0;i<n;i++) { printf("%d ",p[i]); } printf("\n"); return 0; }
[ "Apple@Yash-MacBook-Air.local" ]
Apple@Yash-MacBook-Air.local
49d1263a08328d29d957c9eebdd1cdc9bdcce858
aae79375bee5bbcaff765fc319a799f843b75bac
/atcoder/abc_146/c.cpp
fd9ace2d78b1d2116d12758ede9a195fdda288f5
[]
no_license
firewood/topcoder
b50b6a709ea0f5d521c2c8870012940f7adc6b19
4ad02fc500bd63bc4b29750f97d4642eeab36079
refs/heads/master
2023-08-17T18:50:01.575463
2023-08-11T10:28:59
2023-08-11T10:28:59
1,628,606
21
6
null
null
null
null
UTF-8
C++
false
false
571
cpp
// C. #include <iostream> #include <sstream> #include <algorithm> #include <vector> #include <cmath> using namespace std; typedef long long LL; int main(int argc, char* argv[]) { cout.precision(20); #ifdef _MSC_VER while (true) #endif { LL a, b, x = -1; cin >> a >> b >> x; if (x < 0) return 0; LL left = 0, right = 1000000001LL; while (right - left > 1) { LL mid = (right + left) / 2; LL cost = a * mid + b * to_string(mid).length(); if (cost > x) { right = mid; } else { left = mid; } } cout << left << endl; } return 0; }
[ "karamaki@gmail.com" ]
karamaki@gmail.com
0e4b2a0a52ae40c1f56ea562c0f94d4041e84553
801f7ed77fb05b1a19df738ad7903c3e3b302692
/refactoringOptimisation/differentiatedCAD/occt-min-topo-src/src/BRepAlgo/BRepAlgo_Tool.cxx
8d2110caae2643d9b6070da561c56dbf30523c1a
[]
no_license
salvAuri/optimisationRefactoring
9507bdb837cabe10099d9481bb10a7e65331aa9d
e39e19da548cb5b9c0885753fe2e3a306632d2ba
refs/heads/master
2021-01-20T03:47:54.825311
2017-04-27T11:31:24
2017-04-27T11:31:24
89,588,404
0
1
null
null
null
null
UTF-8
C++
false
false
2,850
cxx
// Created on: 1995-10-23 // Created by: Yves FRICAUD // Copyright (c) 1995-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. #include <BRep_Builder.hxx> #include <BRep_Tool.hxx> #include <BRepAlgo_Tool.hxx> #include <TopExp.hxx> #include <TopoDS.hxx> #include <TopoDS_Edge.hxx> #include <TopoDS_Iterator.hxx> #include <TopoDS_Shape.hxx> #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx> #include <TopTools_ListOfShape.hxx> //======================================================================= //function : Deboucle3D //purpose : //======================================================================= TopoDS_Shape BRepAlgo_Tool::Deboucle3D(const TopoDS_Shape& S, const TopTools_MapOfShape& Boundary) { TopoDS_Shape SS; switch ( S.ShapeType()) { case TopAbs_FACE: { } break; case TopAbs_SHELL: { // if the shell contains free borders that do not belong to the // free borders of caps ( Boundary) it is removed. TopTools_IndexedDataMapOfShapeListOfShape Map; TopExp::MapShapesAndAncestors(S,TopAbs_EDGE,TopAbs_FACE,Map); Standard_Boolean JeGarde = Standard_True; for ( Standard_Integer i = 1; i <= Map.Extent() && JeGarde; i++) { if (Map(i).Extent() < 2) { const TopoDS_Edge& anEdge = TopoDS::Edge(Map.FindKey(i)); if (!Boundary.Contains(anEdge) && !BRep_Tool::Degenerated(anEdge) ) JeGarde = Standard_False; } } if ( JeGarde) SS = S; } break; case TopAbs_COMPOUND: case TopAbs_SOLID: { // iterate on sub-shapes and add non-empty. TopoDS_Iterator it(S); TopoDS_Shape SubShape; Standard_Boolean NbSub = 0; BRep_Builder B; if (S.ShapeType() == TopAbs_COMPOUND) { B.MakeCompound(TopoDS::Compound(SS)); } else { B.MakeSolid(TopoDS::Solid(SS)); } for ( ; it.More(); it.Next()) { const TopoDS_Shape& CurS = it.Value(); SubShape = Deboucle3D(CurS,Boundary); if ( !SubShape.IsNull()) { B.Add(SS, SubShape); NbSub++; } } if (NbSub == 0) { #ifdef OCCT_DEBUG cout << "No subhape in shape!" << endl; #endif SS = TopoDS_Shape(); } } break; default: break; } return SS; }
[ "salvatore.auriemma@opencascade.com" ]
salvatore.auriemma@opencascade.com
16152f2e9078375555eae45332d38bc7062b4de0
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/collectd/gumtree/collectd_repos_function_2399_collectd-5.6.3.cpp
a2e27d80cc1731941381a6c20d3e8c9945c6cf98
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
932
cpp
int parse_identifier_vl(const char *str, value_list_t *vl) /* {{{ */ { char str_copy[6 * DATA_MAX_NAME_LEN]; char *host = NULL; char *plugin = NULL; char *plugin_instance = NULL; char *type = NULL; char *type_instance = NULL; int status; if ((str == NULL) || (vl == NULL)) return (EINVAL); sstrncpy(str_copy, str, sizeof(str_copy)); status = parse_identifier(str_copy, &host, &plugin, &plugin_instance, &type, &type_instance); if (status != 0) return (status); sstrncpy(vl->host, host, sizeof(vl->host)); sstrncpy(vl->plugin, plugin, sizeof(vl->plugin)); sstrncpy(vl->plugin_instance, (plugin_instance != NULL) ? plugin_instance : "", sizeof(vl->plugin_instance)); sstrncpy(vl->type, type, sizeof(vl->type)); sstrncpy(vl->type_instance, (type_instance != NULL) ? type_instance : "", sizeof(vl->type_instance)); return (0); }
[ "993273596@qq.com" ]
993273596@qq.com
05e3a0a1e6de3db461fa4c0fe23f100de76a3ee1
45a26f28a29ab6dd9d3bcf315117d814f50808b1
/src/AppleSMBIOS/AppleSMBIOS-41/AppleSMBIOS.cpp
a26a5c96df9e4f1d39bf1ffb5388ce011f6669e8
[]
no_license
zeborrego/opensource.apple.com
0eb9161029ce8440dbdc4b5157b3927a6e381f8d
88cbaab4a42e97cbbfe6b660f2f0945536821be6
refs/heads/master
2021-07-06T17:16:28.241638
2017-10-02T11:58:56
2017-10-02T11:58:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
34,266
cpp
/* * Copyright (c) 1998-2009 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * The contents of this file constitute Original Code as defined in and * are subject to the Apple Public Source License Version 2.0 (the * "License"). You may not use this file except in compliance with the * License. Please obtain a copy of the License at * http://www.apple.com/publicsource and read it before using this file. * * This Original Code and all software distributed under the License are * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the * License for the specific language governing rights and limitations * under the License. * * @APPLE_LICENSE_HEADER_END@ */ #include <i386/cpuid.h> #include <IOKit/IOPlatformExpert.h> #include <IOKit/IOMemoryDescriptor.h> #include <IOKit/IODeviceTreeSupport.h> #include <IOKit/pci/IOPCIBridge.h> // IOPCIAddressSpace #include <IOKit/acpi/IOACPIPlatformDevice.h> #include <string.h> #include <libkern/version.h> #include "AppleSMBIOS.h" #if DEBUG #define DEBUG_LOG(args...) IOLog(args) #else #define DEBUG_LOG(args...) #endif //--------------------------------------------------------------------------- // SMBPackedStrings class class SMBPackedStrings { protected: const char * _start; const char * _limit; public: SMBPackedStrings( const SMBStructHeader * header, const void * limit ); SMBPackedStrings( const SMBStructHeader * header ); const char * stringAtIndex( UInt8 index, UInt8 * length = 0 ) const; void setDataProperty( IORegistryEntry * entry, const char * key, UInt8 index ) const; void setStringProperty( IORegistryEntry * entry, const char * key, UInt8 index ) const; }; SMBPackedStrings::SMBPackedStrings( const SMBStructHeader * header, const void * limit ) { _start = (const char *) header + header->length; _limit = (const char *) limit; } SMBPackedStrings::SMBPackedStrings( const SMBStructHeader * header ) { _start = (const char *) header + header->length; const char * cp = _start; // Find the double null at the end of the record while( cp[0] || cp[1]) cp++; _limit = &cp[1]; } const char * SMBPackedStrings::stringAtIndex( UInt8 index, UInt8 * length ) const { const char * last = 0; const char * next = _start; if ( length ) *length = 0; while ( index-- ) { last = 0; for ( const char * cp = next; cp < _limit; cp++ ) { if ( *cp == '\0' ) { last = next; next = cp + 1; break; } } if ( last == 0 ) break; } if ( last ) { while (*last == ' ') last++; if (length) { UInt8 len; for ( len = next - last - 1; len && last[len - 1] == ' '; len-- ) ; *length = len; // number of chars not counting the terminating NULL } } return last ? last : ""; } void SMBPackedStrings::setDataProperty( IORegistryEntry * entry, const char * key, UInt8 index ) const { UInt8 length; const char * string = SMBPackedStrings::stringAtIndex(index, &length); if (length) { OSData * data = OSData::withCapacity(length + 1); if (data) { data->appendBytes(string, length); data->appendByte('\0', 1); entry->setProperty(key, data); data->release(); } } } void SMBPackedStrings::setStringProperty( IORegistryEntry * entry, const char * key, UInt8 index ) const { UInt8 length; const char * string = SMBPackedStrings::stringAtIndex(index, &length); if (length) { OSString * strObj = OSString::withCString(string); if (strObj) { entry->setProperty(key, strObj); strObj->release(); } } } #define super IOService OSDefineMetaClassAndStructors( AppleSMBIOS, IOService ) //--------------------------------------------------------------------------- bool AppleSMBIOS::start( IOService * provider ) { OSSerializer * serializer; if (super::start(provider) != true || IOService::getResourceService() == 0 || IOService::getResourceService()->getProperty("SMBIOS")) { return false; } SMBIOSTable = NULL; SMBIOSTableLength = 0; fSlotQueueHead = IONew(queue_head_t, 1); if (!fSlotQueueHead) return false; queue_init(fSlotQueueHead); // Get the IOPlatformExpertDevice fRoot = getServiceRoot(); if (!provider || !fRoot) return false; // Serialize SMBIOS structures to user-space on demand serializer = OSSerializer::forTarget((void *) this, &serializeSMBIOS); if (!serializer) return false; setProperty("SMBIOS", serializer); memInfoSource = kNoMemoryInfo; memSlotsData = OSData::withCapacity(kMemDataSize); memTypesData = OSData::withCapacity(kMemDataSize); memSizesData = OSData::withCapacity(kMemDataSize); memSpeedData = OSData::withCapacity(kMemDataSize); memInfoData = OSData::withCapacity(kMemDataSize); memManufData = OSData::withCapacity(kMemDataSize); memSerialData = OSData::withCapacity(kMemDataSize); memPartData = OSData::withCapacity(kMemDataSize); memSizeTotal = 0; if (!memSlotsData || !memTypesData || !memSizesData || !memSpeedData || !memInfoData || !memManufData || !memSerialData || !memPartData) return false; if (!findSMBIOSTableEFI()) { return false; } // Update device tree updateDeviceTree(); publishResource("SMBIOS"); registerService(); return true; } //--------------------------------------------------------------------------- #define RELEASE(x) do { if (x) { (x)->release(); (x) = 0; } } while(0) void AppleSMBIOS::free( void ) { RELEASE( memSlotsData ); RELEASE( memTypesData ); RELEASE( memSizesData ); RELEASE( memSpeedData ); RELEASE( memInfoData ); RELEASE( memManufData ); RELEASE( memSerialData ); RELEASE( memPartData ); RELEASE( fDMIMemoryMap ); if (fSlotQueueHead) { SystemSlotEntry * slotEntry; while (!queue_empty(fSlotQueueHead)) { queue_remove_first(fSlotQueueHead, slotEntry, SystemSlotEntry *, chain); IODelete(slotEntry, SystemSlotEntry, 1); } IODelete(fSlotQueueHead, queue_head_t, 1); fSlotQueueHead = 0; } super::free(); } //--------------------------------------------------------------------------- bool AppleSMBIOS:: serializeSMBIOS( void * target, void * refcon, OSSerialize * s ) { AppleSMBIOS * me = (AppleSMBIOS *) target; OSData * data; IOMemoryMap * map; bool ok = false; map = me->fDMIMemoryMap; if (map) { data = OSData::withBytesNoCopy( (void *) map->getVirtualAddress(), map->getLength()); if (data) { ok = data->serialize(s); data->release(); } } return ok; } //--------------------------------------------------------------------------- static UInt8 checksum8( void * start, UInt length ) { UInt8 csum = 0; UInt8 * cp = (UInt8 *) start; for (UInt i = 0; i < length; i++) csum += *cp++; return csum; } #define kGenericPCISlotName "PCI Slot" //--------------------------------------------------------------------------- OSData * AppleSMBIOS:: getSlotNameWithSlotId( int slotId ) { char name[80]; SystemSlotEntry * slot = 0; SystemSlotEntry * iter; queue_iterate(fSlotQueueHead, iter, SystemSlotEntry *, chain) { if ((iter->slotID & 0xff) == slotId) { slot = iter; break; } } if (slot && slot->slotName) { strncpy(name, slot->slotName, sizeof(name)); } else { // No matching SlotId, return a generic PCI slot name snprintf(name, sizeof(name), "%s %u", kGenericPCISlotName, slotId); } name[sizeof(name) - 1] = '\0'; return OSData::withBytes(name, strlen(name) + 1); } #define EFI_SMBIOS_TABLE \ "/efi/configuration-table/EB9D2D31-2D88-11D3-9A16-0090273FC14D" //--------------------------------------------------------------------------- bool AppleSMBIOS::findSMBIOSTableEFI( void ) { IORegistryEntry * tableEntry; OSData * tableData; UInt64 tableAddr; IOMemoryDescriptor * epsMemory; SMBEntryPoint eps; IOMemoryDescriptor * dmiMemory = 0; IOItemCount dmiStructureCount = 0; tableEntry = fromPath(EFI_SMBIOS_TABLE, gIODTPlane); if (tableEntry) { tableAddr = 0; tableData = OSDynamicCast(OSData, tableEntry->getProperty("table")); if (tableData && (tableData->getLength() <= sizeof(tableAddr))) { bcopy(tableData->getBytesNoCopy(), &tableAddr, tableData->getLength()); // For SnowLeopard and beyond include the kIOMemoryMapperNone option. #if VERSION_MAJOR >= 10 IOOptionBits options = kIODirectionOutIn | kIOMemoryMapperNone; #else IOOptionBits options = kIODirectionOutIn; #endif epsMemory = IOMemoryDescriptor::withAddressRange( (mach_vm_address_t) tableAddr, (mach_vm_size_t) sizeof(eps), options, NULL ); if (epsMemory) { bzero(&eps, sizeof(eps)); epsMemory->readBytes(0, &eps, sizeof(eps)); setProperty("SMBIOS-EPS", (void *) &eps, sizeof(eps)); if (memcmp(eps.anchor, "_SM_", 4) == 0) { UInt8 csum; csum = checksum8(&eps, sizeof(eps)); DEBUG_LOG("DMI checksum = 0x%x\n", csum); DEBUG_LOG("DMI tableLength = %d\n", eps.dmi.tableLength); DEBUG_LOG("DMI tableAddress = 0x%x\n", (uint32_t) eps.dmi.tableAddress); DEBUG_LOG("DMI structureCount = %d\n", eps.dmi.structureCount); DEBUG_LOG("DMI bcdRevision = %x\n", eps.dmi.bcdRevision); if (csum == 0 && eps.dmi.tableLength && eps.dmi.structureCount) { dmiStructureCount = eps.dmi.structureCount; dmiMemory = IOMemoryDescriptor::withPhysicalAddress( eps.dmi.tableAddress, eps.dmi.tableLength, kIODirectionOutIn ); } else { DEBUG_LOG("No DMI structure found\n"); } } epsMemory->release(); epsMemory = 0; } } tableEntry->release(); } if ( dmiMemory ) { fDMIMemoryMap = dmiMemory->map(); if (fDMIMemoryMap) { SMBIOSTable = (void *) fDMIMemoryMap->getVirtualAddress(); SMBIOSTableLength = fDMIMemoryMap->getLength(); decodeSMBIOSTable((void *) fDMIMemoryMap->getVirtualAddress(), fDMIMemoryMap->getLength(), dmiStructureCount ); } dmiMemory->release(); dmiMemory = 0; } return (fDMIMemoryMap != 0); } //--------------------------------------------------------------------------- void AppleSMBIOS:: adjustPCIDeviceEFI( IOService * pciDevice ) { IOACPIPlatformDevice * acpiDevice; UInt32 slotNum; OSString * acpiPath; IORegistryEntry * acpiEntry = NULL; // Does PCI device have an ACPI alias? // N : not built-in, no slot name, exit // Y : goto next // // Does ACPI device have a _SUN object? // N : it's a built in PCI device // Y : indicates a slot (not built-in), goto next // // Match _SUN value against SlotId in SMBIOS PCI slot structures do { acpiPath = OSDynamicCast(OSString, pciDevice->getProperty("acpi-path")); if (!acpiPath) break; acpiEntry = fromPath(acpiPath->getCStringNoCopy()); if (!acpiEntry) break; if (!acpiEntry->metaCast("IOACPIPlatformDevice")) break; acpiDevice = (IOACPIPlatformDevice *) acpiEntry; if (acpiDevice->evaluateInteger("_SUN", &slotNum) == kIOReturnSuccess) { OSObject * name = getSlotNameWithSlotId(slotNum); if (name) { pciDevice->setProperty("AAPL,slot-name", name); name->release(); } } else if (acpiDevice->validateObject("_RMV") == kIOReturnSuccess) { // no slot name? } else { char dummy = '\0'; pciDevice->setProperty("built-in", &dummy, 1); } } while (false); if (acpiEntry) acpiEntry->release(); } //--------------------------------------------------------------------------- IOReturn AppleSMBIOS:: callPlatformFunction( const char * functionName, bool waitForFunction, void * param1, void * param2, void * param3, void * param4 ) { if (!functionName) return kIOReturnBadArgument; // AdjustPCIBridge function is called by the ACPI // platform driver, but is not useful on EFI systems. if (!strcmp(functionName, "AdjustPCIDevice")) { IOService * device = (IOService *) param1; if (device) { adjustPCIDeviceEFI(device); return kIOReturnSuccess; } } return kIOReturnUnsupported; } //--------------------------------------------------------------------------- void AppleSMBIOS::decodeSMBIOSTable( const void * tableData, UInt16 tableLength, UInt16 structureCount ) { const SMBStructHeader * header; const UInt8 * next = (const UInt8 *) tableData; const UInt8 * end = next + tableLength; while ( structureCount-- && (end > next + sizeof(SMBStructHeader)) ) { header = (const SMBStructHeader *) next; if (header->length > end - next) break; decodeSMBIOSStructure( header, end ); // Skip the formatted area of the structure. next += header->length; // Skip the unformatted structure area at the end (strings). // Look for a terminating double NULL. for ( ; end > next + sizeof(SMBStructHeader); next++ ) { if ( next[0] == 0 && next[1] == 0 ) { next += 2; break; } } } } //--------------------------------------------------------------------------- void AppleSMBIOS:: decodeSMBIOSStructure( const SMBStructHeader * structureHeader, const void * tableBoundary ) { const union SMBStructUnion { SMBBIOSInformation bios; SMBSystemInformation system; SMBBaseBoard baseBoard; SMBMemoryModule memoryModule; SMBSystemSlot slot; SMBPhysicalMemoryArray memoryArray; SMBMemoryDevice memoryDevice; SMBFirmwareVolume fv; SMBMemorySPD spd; } * u = (const SMBStructUnion *) structureHeader; SMBPackedStrings strings = SMBPackedStrings( structureHeader, tableBoundary ); switch ( structureHeader->type ) { case kSMBTypeBIOSInformation: processSMBIOSStructureType0( &u->bios, &strings ); break; case kSMBTypeSystemInformation: processSMBIOSStructureType1( &u->system, &strings ); break; case kSMBTypeBaseBoard: processSMBIOSStructureType2( &u->baseBoard, &strings ); break; case kSMBTypeMemoryModule: processSMBIOSStructureType6( &u->memoryModule, &strings ); break; case kSMBTypeSystemSlot: processSMBIOSStructureType9( &u->slot, &strings ); break; case kSMBTypePhysicalMemoryArray: processSMBIOSStructureType16( &u->memoryArray, &strings ); break; case kSMBTypeMemoryDevice: processSMBIOSStructureType17( &u->memoryDevice, &strings ); break; case kSMBTypeFirmwareVolume: processSMBIOSStructureType128( &u->fv, &strings ); break; case kSMBTypeMemorySPD: processSMBIOSStructureType130( &u->spd, &strings ); break; } } //--------------------------------------------------------------------------- bool AppleSMBIOS::findSMBIOSStructure( SMBAnchor * anchor, uint8_t inType, uint32_t minSize ) { const SMBStructHeader * header; const uint8_t * next; const uint8_t * end; bool found = false; if (!fDMIMemoryMap || !anchor) return false; if (anchor->next == NULL) next = (const UInt8 *) fDMIMemoryMap->getVirtualAddress(); else next = anchor->next; end = (const UInt8 *) fDMIMemoryMap->getVirtualAddress() + fDMIMemoryMap->getLength(); while (end > next + sizeof(SMBStructHeader)) { header = (const SMBStructHeader *) next; if (header->length > end - next) break; // Skip the formatted area of the structure next += header->length; // Skip the unformatted structure area at the end (strings). // Look for a terminating double NULL. for ( ; end > next + sizeof(SMBStructHeader); next++ ) { if ( next[0] == 0 && next[1] == 0 ) { next += 2; break; } } if ((header->type == inType) && (header->length >= minSize)) { anchor->header = header; anchor->next = next; anchor->end = end; found = true; break; } } return found; } //--------------------------------------------------------------------------- void AppleSMBIOS::processSMBIOSStructureType0( const SMBBIOSInformation * bios, SMBPackedStrings * strings ) { char location[9]; if (bios->header.length < sizeof(SMBBIOSInformation)) return; if (!fROMNode) { fROMNode = OSTypeAlloc( IOService ); if (fROMNode && (false == fROMNode->init())) { fROMNode->release(); fROMNode = 0; } } if (fROMNode) { snprintf(location, sizeof(location), "%x", bios->startSegment << 4); fROMNode->setLocation(location); strings->setDataProperty(fROMNode, "vendor", bios->vendor); strings->setDataProperty(fROMNode, "version", bios->version); strings->setDataProperty(fROMNode, "release-date", bios->releaseDate); strings->setDataProperty(fROMNode, "characteristics", bios->characteristics); fROMNode->setProperty("rom-size", (bios->romSize + 1) * 0x10000, 32 ); } } //--------------------------------------------------------------------------- void AppleSMBIOS::processSMBIOSStructureType1( const SMBSystemInformation * sys, SMBPackedStrings * strings ) { UInt8 serialNumberLength; if (sys->header.length < 8) return; strings->setDataProperty(fRoot, "manufacturer", sys->manufacturer); strings->setDataProperty(fRoot, "product-name", sys->productName); strings->setDataProperty(fRoot, "version", sys->version); // Platform driver took care of this. if (fRoot->getProperty(kIOPlatformSerialNumberKey)) return; const char *serialNumberString = strings->stringAtIndex( sys->serialNumber, &serialNumberLength); if ((serialNumberLength >= 3) && (serialNumberLength < 30)) { // Map 11 or 12 digit serial number string read from SMBIOS to a // 43-byte "serial-number" data object. Must also handle systems // without a valid serial number string, e.g. "System Serial#". OSData * data = OSData::withCapacity(43); if (data) { int clen = (12 == serialNumberLength) ? 4 : 3; data->appendBytes(serialNumberString + (serialNumberLength - clen), clen); data->appendBytes('\0', 13 - clen); data->appendBytes(serialNumberString, serialNumberLength); data->appendBytes('\0', 43 - 13 - serialNumberLength); fRoot->setProperty("serial-number", data); data->release(); } } strings->setStringProperty(fRoot, kIOPlatformSerialNumberKey, sys->serialNumber); } //--------------------------------------------------------------------------- void AppleSMBIOS::processSMBIOSStructureType2( const SMBBaseBoard * baseBoard, SMBPackedStrings * strings ) { if (baseBoard->header.length < sizeof(SMBBaseBoard)) { kprintf("AppleSMBIOS: invalid type 2 record size: %d, expected %ld\n", baseBoard->header.length, sizeof(SMBBaseBoard)+1); return; } // If this type 2 record is for the processor and memory board then it is // a riser card. Grab the serial number and publish it to the registry. if ((baseBoard->boardType & kSMBBaseBoardProcessorMemoryModule) == kSMBBaseBoardProcessorMemoryModule) { UInt8 length = 0; strings->stringAtIndex(baseBoard->serialNumber, &length); if (length == 0) IOLog("AppleSMBIOS: processor/memory board serial number is empty\n"); else strings->setStringProperty(fRoot, "processor-memory-board-serial-number", baseBoard->serialNumber); } } //--------------------------------------------------------------------------- void AppleSMBIOS::processSMBIOSStructureType6( const SMBMemoryModule * memory, SMBPackedStrings * strings ) { UInt8 socketLength; const char * socketString; UInt8 memorySize; union { UInt64 ull; UInt32 ul[2]; } memoryBytes; if (memory->header.length < sizeof(SMBMemoryModule)) return; if (memInfoSource == kMemoryDeviceInfo) return; memInfoSource = kMemoryModuleInfo; // update memSlotsData socketString = strings->stringAtIndex( memory->socketDesignation, &socketLength ); if ( socketString ) { if (memSlotsData->getLength() == 0) memSlotsData->appendBytes(" ", 4); if (socketLength) memSlotsData->appendBytes( socketString, socketLength ); memSlotsData->appendByte('\0', 1); } // update memTypesData memTypesData->appendBytes("DRAM", 5); // update memSizesData memorySize = memory->enabledSize & 0x7F; if (memorySize >= kSMBMemoryModuleSizeNotDeterminable) memoryBytes.ull = 0; else memoryBytes.ull = (1ULL << memorySize) * (1024 * 1024); memSizeTotal += memoryBytes.ull; memSizesData->appendBytes( &memoryBytes.ul[1], 4 ); memSizesData->appendBytes( &memoryBytes.ul[0], 4 ); } //--------------------------------------------------------------------------- void AppleSMBIOS::processSMBIOSStructureType9( const SMBSystemSlot * slot, SMBPackedStrings * strings ) { SystemSlotEntry * slotEntry; if (slot->header.length < 12) return; slotEntry = IONew(SystemSlotEntry, 1); if (slotEntry) { memset(slotEntry, 0, sizeof(*slotEntry)); slotEntry->slotID = slot->slotID; slotEntry->slotType = slot->slotType; slotEntry->slotUsage = slot->currentUsage; slotEntry->slotName = strings->stringAtIndex(slot->slotDesignation); queue_enter(fSlotQueueHead, slotEntry, SystemSlotEntry *, chain); } DEBUG_LOG("Slot type %x, width %x, usage %x, ID %x, char1 %x\n", slot->slotType, slot->slotDataBusWidth, slot->currentUsage, slot->slotID, slot->slotCharacteristics1); } //--------------------------------------------------------------------------- void AppleSMBIOS::processSMBIOSStructureType16( const SMBPhysicalMemoryArray * memory, SMBPackedStrings * strings ) { if (memory->header.length < sizeof(SMBPhysicalMemoryArray)) return; if ((memory->arrayUse == kSMBMemoryArrayUseSystemMemory) && ((memory->errorCorrection == kSMBMemoryArrayErrorCorrectionTypeSingleBitECC) || (memory->errorCorrection == kSMBMemoryArrayErrorCorrectionTypeMultiBitECC))) { memECCEnabled = true; } } //--------------------------------------------------------------------------- void AppleSMBIOS::processSMBIOSStructureType17( const SMBMemoryDevice * memory, SMBPackedStrings * strings ) { UInt8 deviceLocatorLength; const char * deviceLocatorString; UInt8 bankLocatorLength; const char * bankLocatorString; UInt8 stringLength; const char * string; UInt8 memoryType; union { UInt64 ull; UInt32 ul[2]; } memoryBytes; if (memory->header.length < 21) return; if (memInfoSource == kMemoryModuleInfo) { memSlotsData->initWithCapacity(kMemDataSize); memTypesData->initWithCapacity(kMemDataSize); memSizesData->initWithCapacity(kMemDataSize); memSpeedData->initWithCapacity(kMemDataSize); memManufData->initWithCapacity(kMemDataSize); memSerialData->initWithCapacity(kMemDataSize); memPartData->initWithCapacity(kMemDataSize); memSizeTotal = 0; } memInfoSource = kMemoryDeviceInfo; // update memSlotsData deviceLocatorString = strings->stringAtIndex( memory->deviceLocator, &deviceLocatorLength ); bankLocatorString = strings->stringAtIndex( memory->bankLocator, &bankLocatorLength ); // Device location is mandatory, but bank location is optional. if (!memory->deviceLocator || !deviceLocatorLength ) { // Dummy device location string deviceLocatorString = "Location"; deviceLocatorLength = strlen(deviceLocatorString); } if ( deviceLocatorLength ) { if ( memSlotsData->getLength() == 0 ) memSlotsData->appendBytes(" ", 4); if ( bankLocatorLength ) { memSlotsData->appendBytes( bankLocatorString, bankLocatorLength ); memSlotsData->appendByte('/', 1); } memSlotsData->appendBytes( deviceLocatorString, deviceLocatorLength ); memSlotsData->appendByte('\0', 1); } // update memTypesData memoryType = memory->memoryType; if ( memoryType > kSMBMemoryDeviceTypeCount - 1 ) memoryType = 0x02; // unknown type memTypesData->appendBytes( SMBMemoryDeviceTypes[memoryType], strlen(SMBMemoryDeviceTypes[memoryType]) + 1 ); // update memSizesData memoryBytes.ull = (memory->memorySize & 0x7fff) * 1024; if ((memory->memorySize & 0x8000) == 0) memoryBytes.ull *= 1024; memSizeTotal += memoryBytes.ull; memSizesData->appendBytes( &memoryBytes.ul[1], 4 ); memSizesData->appendBytes( &memoryBytes.ul[0], 4 ); if (memory->header.length >= 27) { char speedText[16]; snprintf(speedText, sizeof(speedText), "%u MHz", memory->memorySpeed); memSpeedData->appendBytes(speedText, strlen(speedText) + 1); } string = strings->stringAtIndex( memory->manufacturer, &stringLength ); memManufData->appendBytes( string, stringLength + 1 ); string = strings->stringAtIndex( memory->serialNumber, &stringLength ); memSerialData->appendBytes( string, stringLength + 1 ); string = strings->stringAtIndex( memory->partNumber, &stringLength ); memPartData->appendBytes( string, stringLength + 1 ); // What about "available", "mem-info" prop? } //--------------------------------------------------------------------------- void AppleSMBIOS::processSMBIOSStructureType128( const SMBFirmwareVolume * fv, SMBPackedStrings * strings ) { const FW_REGION_INFO * regionInfo = NULL; if (fv->header.length < sizeof(SMBFirmwareVolume)) return; for (int i = 0; i < fv->RegionCount; i++) { if (fv->RegionType[i] == FW_REGION_MAIN) { regionInfo = &fv->FlashMap[i]; break; } } if (regionInfo && (regionInfo->EndAddress > regionInfo->StartAddress)) { if (!fROMNode) { fROMNode = OSTypeAlloc( IOService ); if (fROMNode && (false == fROMNode->init())) { fROMNode->release(); fROMNode = 0; } } if (fROMNode) { fROMNode->setProperty("fv-main-address", regionInfo->StartAddress, 32 ); fROMNode->setProperty("fv-main-size", regionInfo->EndAddress - regionInfo->StartAddress + 1, 32 ); } } } //--------------------------------------------------------------------------- void AppleSMBIOS::processSMBIOSStructureType130( const SMBMemorySPD * spd, SMBPackedStrings * strings ) { unsigned int dataSize; if(spd->Offset > 127) return; // Only care about the first 128 bytes of spd data dataSize = (spd->Size + spd->Offset) > 128 ? 128 - spd->Offset : spd->Size; memInfoData->appendBytes(spd->Data, dataSize); } //--------------------------------------------------------------------------- void AppleSMBIOS::updateDeviceTree( void ) { SMBAnchor anchor; uint32_t busSpeedMTs = 0; uint32_t itcSpeedMTs = 0; uint32_t cpuSpeedMHz = 0; SMBWord cpuType = 0; IOService * memoryNode = OSTypeAlloc( IOService ); if (memoryNode && (false == memoryNode->init())) { memoryNode->release(); memoryNode = 0; } if (memoryNode) { memoryNode->setName("memory"); //memoryNode->setLocation("0"); memoryNode->setProperty( "slot-names", memSlotsData ); memoryNode->setProperty( "dimm-types", memTypesData ); memoryNode->setProperty( "reg", memSizesData ); if (memSpeedData->getLength()) { memoryNode->setProperty( "dimm-speeds", memSpeedData ); } if (memInfoData->getLength() == 0) { memInfoData->appendBytes(0, (memSizesData->getLength() / 8) * 128); } memoryNode->setProperty( "dimm-info", memInfoData ); if (memManufData->getLength()) memoryNode->setProperty( "dimm-manufacturer", memManufData ); if (memSerialData->getLength()) memoryNode->setProperty( "dimm-serial-number", memSerialData ); if (memPartData->getLength()) memoryNode->setProperty( "dimm-part-number", memPartData ); memoryNode->setProperty( "ecc-enabled", memECCEnabled ? kOSBooleanTrue : kOSBooleanFalse ); memoryNode->attachToParent( fRoot, gIODTPlane ); memoryNode->release(); } // Update max_mem kernel variable with the total size of installed RAM if (memSizeTotal && (memSizeTotal > max_mem)) { UInt32 bootMaxMem = 0; if (PE_parse_boot_argn("maxmem", &bootMaxMem, sizeof(bootMaxMem)) && bootMaxMem) { UInt64 limit = ((UInt64) bootMaxMem) * 1024ULL * 1024ULL; if (memSizeTotal > limit) memSizeTotal = limit; } max_mem = memSizeTotal; } if (fROMNode) { fROMNode->setName("rom"); fROMNode->attachToParent( fRoot, gIODTPlane ); fROMNode->release(); fROMNode = 0; } // Fetch Processor Type from Type 131 structure (optional). SMB_ANCHOR_RESET(&anchor); if (findSMBIOSStructure(&anchor, kSMBTypeOemProcessorType, sizeof(SMBOemProcessorType))) { const SMBOemProcessorType * processorType = (const SMBOemProcessorType *) anchor.header; cpuType = processorType->ProcessorType; DEBUG_LOG("SMBIOS: processor type = 0x%04x\n", cpuType); } // Fetch bus transfer rate from Type 132 structure (optional). SMB_ANCHOR_RESET(&anchor); if (findSMBIOSStructure(&anchor, kSMBTypeOemProcessorBusSpeed, sizeof(SMBOemProcessorBusSpeed))) { const SMBOemProcessorBusSpeed * speed = (const SMBOemProcessorBusSpeed *) anchor.header; busSpeedMTs = itcSpeedMTs = speed->ProcessorBusSpeed; DEBUG_LOG("SMBIOS: Bus speed (MT/s) = %u\n", busSpeedMTs); } // Fetch cpu and bus nominal frequencies. SMB_ANCHOR_RESET(&anchor); if (findSMBIOSStructure(&anchor, kSMBTypeProcessorInformation, kSMBProcessorInformationMinSize)) { const SMBProcessorInformation * cpuInfo = (const SMBProcessorInformation *) anchor.header; cpuSpeedMHz = cpuInfo->maximumClock; DEBUG_LOG("SMBIOS: CPU speed (MHz) = %u\n", cpuSpeedMHz); if (busSpeedMTs == 0) { busSpeedMTs = cpuInfo->externalClock; busSpeedMTs *= 4; // Assume quad-pumped FSB DEBUG_LOG("SMBIOS: FSB speed (MT/s) = %u\n", busSpeedMTs); } } if (busSpeedMTs) { uint64_t rateInTs = ((uint64_t) busSpeedMTs) * 1000000ULL; gPEClockFrequencyInfo.bus_frequency_hz = rateInTs; gPEClockFrequencyInfo.bus_frequency_min_hz = rateInTs; gPEClockFrequencyInfo.bus_frequency_max_hz = rateInTs; gPEClockFrequencyInfo.bus_clock_rate_hz = (rateInTs < (1ULL << 32)) ? (uint32_t) rateInTs : 0xFFFFFFFF; } if (cpuSpeedMHz) { uint64_t rateInHz = ((uint64_t) cpuSpeedMHz) * 1000000ULL; gPEClockFrequencyInfo.cpu_frequency_max_hz = rateInHz; gPEClockFrequencyInfo.cpu_frequency_min_hz = rateInHz; gPEClockFrequencyInfo.cpu_frequency_hz = rateInHz; gPEClockFrequencyInfo.cpu_clock_rate_hz = rateInHz; } if (cpuType || itcSpeedMTs) { IORegistryEntry * cpus; IORegistryEntry * child; IORegistryIterator * iter; cpus = IORegistryEntry::fromPath("/cpus", gIODTPlane); if (cpus && itcSpeedMTs) { uint64_t rateInTs = ((uint64_t) itcSpeedMTs) * 1000000ULL; cpus->setProperty( "interconnect-speed", &rateInTs, sizeof(rateInTs)); } if (cpus && cpuType) { iter = IORegistryIterator::iterateOver( cpus, gIODTPlane ); if (iter) { while ((child = iter->getNextObject())) { child->setProperty( "cpu-type", (void *) &cpuType, sizeof(cpuType)); } iter->release(); } } if (cpus) cpus->release(); } }
[ "mattl@cnuk.org" ]
mattl@cnuk.org
6e538136c6970fe02384f1287b6c63029c411c32
729ae3d19e80f5ca0f48cfa010784a92531ad6b9
/mak_dic_zzj.cpp
f375e65f374bc79650e871f30094fe1019af4e90
[]
no_license
zhenjizhang/NLP
a77264c79b0db885035dc88b2b089a675a3bebfb
5b587caa7c28acc1882d299c6daef9e85e867bb8
refs/heads/master
2021-06-25T04:44:19.861951
2017-09-12T10:14:35
2017-09-12T10:14:35
103,254,862
0
0
null
null
null
null
UTF-8
C++
false
false
1,178
cpp
#include <iostream> #include <map> #include <vector> #include <string> #include <fstream> using namespace std; const char *Train_text = "TrainData.txt"; const char *dic_text = "dic.txt"; // struct dic_word // { // int num; // string word; // double rate; // } map <string, double> dic_word; map <string, double> :: iterator dic_it; bool tag = true; int main() { ifstream fileI(Train_text); string word_temp; double word_count = 0; double count = 0; while(tag) { fileI >> word_temp; if(dic_word.find(word_temp) == dic_word.end()) //判断是不是新词 { word_count = 1; dic_word.insert(pair<string, double>(word_temp, word_count)); cout << "if-1\n"; } else //不是新词 { dic_word.find(word_temp) -> second += 1; cout << "else-1\n"; } if(fileI.eof()) //文件,循环跳出 { tag = false; cout <<"------------------------------------------\n"; } count ++; cout << count << "\n"; } fileI.close(); ofstream fileO(dic_text); fileO << count << "\n"; for(dic_it = dic_word.begin(); dic_it != dic_word.end(); dic_it++) { fileO << dic_it -> first << " " << dic_it -> second << "\n"; } fileO.close(); return 0; }
[ "noreply@github.com" ]
zhenjizhang.noreply@github.com
f295d6c4d31e87a46505c3bbe1f2dabcf80787ab
b76289396b22eda191f25744a600fac2abaf8850
/third-party/fizz/src/fizz/protocol/BrotliCertificateCompressor.cpp
9aeb6cb4c6d10a37b0b0b89543aeb60898e27b4c
[ "BSD-3-Clause", "MIT", "PHP-3.01", "Zend-2.0" ]
permissive
fengjixuchui/hhvm
cb8cece7afd025fb8cdf8479c2a0696f38730949
bbbb1782fa258b8dd526ffc7e8ba0f6115931bff
refs/heads/master
2023-03-15T15:55:46.355422
2023-01-27T13:59:08
2023-01-27T13:59:08
175,142,159
0
1
NOASSERTION
2021-11-03T11:22:20
2019-03-12T05:34:16
C++
UTF-8
C++
false
false
2,151
cpp
/* * Copyright (c) 2018-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include <brotli/encode.h> #include <fizz/protocol/BrotliCertificateCompressor.h> using namespace folly; namespace fizz { BrotliCertificateCompressor::BrotliCertificateCompressor( int compressLevel, int windowSize) : level_(compressLevel), windowSize_(windowSize) {} BrotliCertificateCompressor::BrotliCertificateCompressor() : level_(kDefaultCompressionLevel), windowSize_(kDefaultWindowSize) {} CertificateCompressionAlgorithm BrotliCertificateCompressor::getAlgorithm() const { return CertificateCompressionAlgorithm::brotli; } namespace { namespace brotli1 { std::unique_ptr<IOBuf> brotliCompressImpl(int level, int windowSize, folly::ByteRange input) { size_t upperBound = ::BrotliEncoderMaxCompressedSize(input.size()); if (upperBound == 0) { throw std::runtime_error( "Failed to compress certificate: could not calculate upper bound"); } size_t size = input.size(); auto compressed = IOBuf::create(upperBound); if (!BrotliEncoderCompress( level, windowSize, BROTLI_MODE_GENERIC, input.size(), input.data(), &size, compressed->writableTail())) { throw std::runtime_error("Failed to compress certificate"); } // |size|, if the BrotliEncoderCompress call succeeds, is modified to contain // the compressed size. compressed->append(size); return compressed; } } // namespace brotli1 using brotli1::brotliCompressImpl; } // namespace CompressedCertificate BrotliCertificateCompressor::compress( const CertificateMsg& cert) { auto encoded = encode(cert); auto encodedRange = encoded->coalesce(); auto compressedCert = brotliCompressImpl(level_, windowSize_, encodedRange); CompressedCertificate cc; cc.uncompressed_length = encodedRange.size(); cc.algorithm = getAlgorithm(); cc.compressed_certificate_message = std::move(compressedCert); return cc; } } // namespace fizz
[ "atry@fb.com" ]
atry@fb.com
fcf5c0a3f82b704b3266ded483a7d5d8eae8d7cd
74e7667ad65cbdaa869c6e384fdd8dc7e94aca34
/MicroFrameworkPK_v4_1/BuildOutput/public/debug/Client/stubs/spot_net_security_native_Microsoft_SPOT_Net_Security_SslNative.h
0767fe1527105eabf5fcfb4f2a0f65bd3dcbed2c
[ "BSD-3-Clause", "OpenSSL", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
gezidan/NETMF-LPC
5093ab223eb9d7f42396344ea316cbe50a2f784b
db1880a03108db6c7f611e6de6dbc45ce9b9adce
refs/heads/master
2021-01-18T10:59:42.467549
2011-06-28T08:11:24
2011-06-28T08:11:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,534
h
//----------------------------------------------------------------------------- // // ** WARNING! ** // This file was generated automatically by a tool. // Re-running the tool will overwrite this file. // You should copy this file to a custom location // before adding any customization in the copy to // prevent loss of your changes when the tool is // re-run. // //----------------------------------------------------------------------------- #ifndef _SPOT_NET_SECURITY_NATIVE_MICROSOFT_SPOT_NET_SECURITY_SSLNATIVE_H_ #define _SPOT_NET_SECURITY_NATIVE_MICROSOFT_SPOT_NET_SECURITY_SSLNATIVE_H_ namespace Microsoft { namespace SPOT { namespace Net { namespace Security { struct SslNative { // Helper Functions to access fields of managed object // Declaration of stubs. These functions are implemented by Interop code developers static INT32 SecureServerInit( INT32 param0, INT32 param1, UNSUPPORTED_TYPE param2, double param3, HRESULT &hr ); static INT32 SecureClientInit( INT32 param0, INT32 param1, UNSUPPORTED_TYPE param2, double param3, HRESULT &hr ); static void UpdateCertificates( INT32 param0, UNSUPPORTED_TYPE param1, double param2, HRESULT &hr ); static void SecureAccept( INT32 param0, UNSUPPORTED_TYPE param1, HRESULT &hr ); static void SecureConnect( INT32 param0, LPCSTR param1, UNSUPPORTED_TYPE param2, HRESULT &hr ); static INT32 SecureRead( UNSUPPORTED_TYPE param0, CLR_RT_TypedArray_UINT8 param1, INT32 param2, INT32 param3, INT32 param4, HRESULT &hr ); static INT32 SecureWrite( UNSUPPORTED_TYPE param0, CLR_RT_TypedArray_UINT8 param1, INT32 param2, INT32 param3, INT32 param4, HRESULT &hr ); static INT32 SecureCloseSocket( UNSUPPORTED_TYPE param0, HRESULT &hr ); static INT32 ExitSecureContext( INT32 param0, HRESULT &hr ); static void ParseCertificate( CLR_RT_TypedArray_UINT8 param0, LPCSTR param1, LPCSTR * param2, LPCSTR * param3, UNSUPPORTED_TYPE * param4, float param5, HRESULT &hr ); static INT32 DataAvailable( UNSUPPORTED_TYPE param0, HRESULT &hr ); }; } } } } #endif //_SPOT_NET_SECURITY_NATIVE_MICROSOFT_SPOT_NET_SECURITY_SSLNATIVE_H_
[ "psampaio.isel@gmail.com" ]
psampaio.isel@gmail.com
875d556f40fc399e6c1c5e0ad045babc620e15db
42707f98a26a505aac0286e5e95a29d2f68646fa
/Array/Rotations/Pair in sorted and rotated array.cpp
6e935427b19b9e6b5560c1132529c3948c0795de
[]
no_license
binarydevelop/GeeksforGeeks_Data-Structures
c323b5d070305ab30565bd775841640871c9c206
88b2352912017485ba88c2c7c9814efb5b2b52b8
refs/heads/master
2023-01-13T22:50:26.701023
2020-11-12T03:31:52
2020-11-12T03:31:52
266,951,840
0
0
null
null
null
null
UTF-8
C++
false
false
999
cpp
#include<iostream> using namespace std; bool pairInSortedRotated(int arr[], int n, int x) { // Find the pivot element int i; for (i=0; i<n-1; i++) // 18 here is the pivot as arr[i](68)>arr[i+1](18) if (arr[i] > arr[i+1]) // 20 43 68 18 break; int l = (i+1)%n; //mod n because if the value is less thhan n then it will return the same number else if it's greater than n then the remainder will be the result int r = i; while (l != r) { if (arr[l] + arr[r] == x) return true; // move to the higher sum if (arr[l] + arr[r] < x) l = (l + 1)%n; else // Move to the lower sum side r = (n + r - 1)%n; // we are adding n because once r gets to 0 it will go to negative indexes but when we add n and %n it is confirmed that it will be in range of 0 to n-1 and hence not going out of the bound; } return false; }
[ "binarydevelop@gmail.com" ]
binarydevelop@gmail.com
9020bc876f3e0a79c3fb260e519cafb3e59fd191
530822b710300825d0395b10feaa067a0236e3b4
/C++_Primer_Exercises/Dealing_with_Data/SecondsToHoursMinutesAndSecondsConverter.h
826dd4c1c7e79de7562f204c43be07d3df1ede7f
[]
no_license
Rick-Addiction/CPlusPlus_Studies
b29ebdbefd588e099bc69346de6dd3678f33772f
491d94eeae4d33481ece8046729c7c69bab98836
refs/heads/master
2020-08-05T20:57:38.730135
2020-07-04T18:24:19
2020-07-04T18:24:19
212,707,313
0
0
null
null
null
null
UTF-8
C++
false
false
184
h
#ifndef SECONDSTOHOURSMINUTESANDSECONDS_H #define SECONDSTOHOURSMINUTESANDSECONDS_H #include <iostream> #include <string> void SecondsToHoursMinutesAndSecondsConverter(); #endif
[ "henrique.rachti@gmail.com" ]
henrique.rachti@gmail.com
10ab0c981932fc9421d1b8118993572b0913b8fa
64cb681c4430d699035e24bdc6e29019c72b0f94
/renderdoc/driver/d3d8/d3d8_resources.cpp
23fb32d1bb2a8cbe2bfff48418351fa004f8b524
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
new-TonyWang/renderdoc
ebd7d0e338b0e56164930915ebce4c0f411f2977
ac9c37e2e9ba4b9ab6740c020e65681eceba45dd
refs/heads/v1.x
2023-07-09T17:03:11.345913
2021-08-18T02:54:41
2021-08-18T02:54:41
379,597,382
0
0
MIT
2021-08-18T03:15:31
2021-06-23T12:35:00
C++
UTF-8
C++
false
false
3,245
cpp
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2019-2021 Baldur Karlsson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ #include "d3d8_resources.h" #undef D3D8_TYPE_MACRO #define D3D8_TYPE_MACRO(iface) WRAPPED_POOL_INST(CONCAT(Wrapped, iface)); ALL_D3D8_TYPES; std::map<ResourceId, WrappedIDirect3DVertexBuffer8::BufferEntry> WrappedD3DBuffer8<IDirect3DVertexBuffer8, D3DVERTEXBUFFER_DESC>::m_BufferList; std::map<ResourceId, WrappedIDirect3DIndexBuffer8::BufferEntry> WrappedD3DBuffer8<IDirect3DIndexBuffer8, D3DINDEXBUFFER_DESC>::m_BufferList; D3D8ResourceType IdentifyTypeByPtr(IUnknown *ptr) { if(ptr == NULL) return Resource_Unknown; #undef D3D8_TYPE_MACRO #define D3D8_TYPE_MACRO(iface) \ if(UnwrapHelper<iface>::IsAlloc(ptr)) \ return UnwrapHelper<iface>::GetTypeEnum(); ALL_D3D8_TYPES; RDCERR("Unknown type for ptr 0x%p", ptr); return Resource_Unknown; } TrackedResource8 *GetTracked(IUnknown *ptr) { if(ptr == NULL) return NULL; #undef D3D8_TYPE_MACRO #define D3D8_TYPE_MACRO(iface) \ if(UnwrapHelper<iface>::IsAlloc(ptr)) \ return (TrackedResource8 *)GetWrapped((iface *)ptr); ALL_D3D8_TYPES; return NULL; } template <> IUnknown *Unwrap(IUnknown *ptr) { if(ptr == NULL) return NULL; #undef D3D8_TYPE_MACRO #define D3D8_TYPE_MACRO(iface) \ if(UnwrapHelper<iface>::IsAlloc(ptr)) \ return (IUnknown *)GetWrapped((iface *)ptr)->GetReal(); ALL_D3D8_TYPES; RDCERR("Unknown type of ptr 0x%p", ptr); return NULL; } template <> ResourceId GetResID(IUnknown *ptr) { if(ptr == NULL) return ResourceId(); TrackedResource8 *res = GetTracked(ptr); if(res == NULL) { RDCERR("Unknown type of ptr 0x%p", ptr); return ResourceId(); } return res->GetResourceID(); } template <> D3D8ResourceRecord *GetRecord(IUnknown *ptr) { if(ptr == NULL) return NULL; TrackedResource8 *res = GetTracked(ptr); if(res == NULL) { RDCERR("Unknown type of ptr 0x%p", ptr); return NULL; } return res->GetResourceRecord(); }
[ "baldurk@baldurk.org" ]
baldurk@baldurk.org
2100826e4ac5369f09a0893aa300609afd0d9d03
93574cdfec6227131bda78ec7c2a687f7bb43edf
/c++/balanced-binary-tree.cpp
0c3a50cee9f6131b85306f35db5688f2ffa18af4
[]
no_license
fyang26/leetcode
642cd051fe29fb26c8c24921c5fc1504554bbe67
2f7d2aa174a719d93bd42790f3c216f6f0173d5b
refs/heads/master
2021-01-10T11:08:33.920393
2016-04-27T00:59:05
2016-04-27T00:59:05
43,520,536
0
0
null
null
null
null
UTF-8
C++
false
false
618
cpp
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isBalanced(TreeNode* root) { if (!root) return true; int diff = abs(getdepth(root->left) - getdepth(root->right)); if (diff>1) return false; else return isBalanced(root->left) && isBalanced(root->right); } int getdepth(TreeNode *root) { if (!root) return 0; return max(getdepth(root->left), getdepth(root->right)) + 1; } };
[ "fyang@umiacs.umd.edu" ]
fyang@umiacs.umd.edu
6b97bd0d6558c838bc2f760509df9b9e4320190f
ea86bc50922e5d96a78575e400aadaf7f888590e
/ds/chap3/decode_string/solu.cpp
9d6d92eee0a7cfd929fcb80e2a6d619baa282ee2
[]
no_license
EvergreenHZ/See-Let-Pointer-Fly
527d5d6ae35fc26d298bc07dd921c53c3307d082
68c088995f1a8ea951b6144bdbd1a0923c0be90c
refs/heads/master
2020-03-07T04:42:58.077212
2018-10-22T11:56:21
2018-10-22T11:56:21
127,274,299
0
0
null
null
null
null
UTF-8
C++
false
false
3,715
cpp
#include <string> #include <iostream> #include <vector> #include <stack> using namespace std; class Solution { public: string decodeString(string s) { if (!isValid(s)) return ""; stack<string> _stack; stack<int> _nstack; string result; string tmp; int n=0; for (int i=0; i<s.size(); i++) { if ( isNum(s[i]) ) { n = 0; for(; isNum(s[i]); i++ ) { n = n*10 + s[i] - '0'; } } if (s[i] == '[') { tmp=""; _stack.push(tmp); _nstack.push(n); } else if (s[i] == ']') { n = _nstack.top(); tmp=""; for (; n>0; n--) { tmp += _stack.top(); // cat n times } _stack.pop(); _nstack.pop(); if ( ! _stack.empty() ) { _stack.top() += tmp; }else { result += tmp; } } else { if ( ! _stack.empty() ) { // collect chars _stack.top() += s[i]; } else { result += s[i]; // deal with char directly } } } return result; } private: //only check the following rules: // 1) the number must be followed by '[' // 2) the '[' and ']' must be matched. bool isValid(string& s) { stack<char> _stack; for (int i=0; i<s.size(); i++) { if ( isNum(s[i]) ) { for(; isNum(s[i]); i++); if (s[i] != '[') { return false; } _stack.push('['); continue; } else if (s[i] == ']' ) { if ( _stack.top() != '[' ) return false; _stack.pop(); } } return (_stack.size() == 0); } bool isNum(char ch) { return (ch>='0' && ch<='9'); } }; int main() { Solution solu; cout << solu.decodeString(string("3[a]2[bc]")) << endl; // 输出 aaabcbc cout << solu.decodeString(string("3[a2[c]]")) << endl; // 输出 accaccacc cout << solu.decodeString(string("2[abc]3[cd]ef")) << endl; // 输出 abcabccdcdcdef }
[ "huaizhixtp@163.com" ]
huaizhixtp@163.com
959cc315edc842a06c3bc56a5f9f2e5010d28558
25fa0e6825f56a140aaaaf9ebe43dccbc7d31a0b
/CPP_SimpleGames/Guess_My_Number/BackgroundInfo/forLoopCounters.cpp
174ebdbcbc0367fee4a2df192d10484bf98cea27
[]
no_license
JoshuaTPierce/Learning_Repo1
0342e42d6db846dd1be74ead4116d4fc247c590a
9a5a34bf04bfe6699420976dedcd295ca79335b4
refs/heads/master
2020-03-25T02:48:29.923672
2018-08-31T13:11:54
2018-08-31T13:11:54
143,308,470
0
0
null
null
null
null
UTF-8
C++
false
false
737
cpp
// Counter // Demonstrates for loops #include <iostream> using namespace std; int main(){ cout << "Counting forward:\n"; for (int i = 0; i < 10; ++i) { cout << i << " "; } cout << "\n\nCounting backward:\n"; for (int i = 9; i >= 0; --i) { cout << i << " "; } cout << "\n\nCounting by fives:\n"; for (int i = 0; i <= 50; i += 5){ cout << i << " "; } cout << "\n\nCounting with null statements:\n"; int count = 0; for ( ; count < 10; ) { cout << count << " "; ++count; } cout << "\n\nCounting with nested for loops:\n"; const int ROWS = 5; const int COLUMNS = 3; for (int i = 0; i < ROWS; ++i) { for (int j = 0; j < COLUMNS; ++j) { cout << i << "," << j << " "; } } cout << endl; return 0; }
[ "joshua.pierce@licor.com" ]
joshua.pierce@licor.com
f1335a743daadbbbd90c1fa57d3644f0ff223907
7e6aac751bb9c43f53785134b3b6c1f9c603f37d
/generator/booking_dataset.cpp
caeaff88d181c86f12f10e36849a59d5099c8236
[ "Apache-2.0" ]
permissive
psokol/omim
cc2e95bb21d9ebe453e83517ec96cd5b3d383306
8c0c85aac64841c08ed8892b55022bcc69300f4d
refs/heads/master
2020-12-25T17:45:18.633298
2016-06-30T22:14:03
2016-06-30T22:14:03
60,401,992
0
0
null
2016-06-04T08:59:57
2016-06-04T08:59:57
null
UTF-8
C++
false
false
7,769
cpp
#include "generator/booking_dataset.hpp" #include "indexer/search_delimiters.hpp" #include "indexer/search_string_utils.hpp" #include "geometry/distance_on_sphere.hpp" #include "base/logging.hpp" #include "base/string_utils.hpp" #include "std/fstream.hpp" #include "std/iostream.hpp" #include "std/sstream.hpp" namespace generator { namespace { bool CheckForValues(string const & value) { for (char const * val : {"hotel", "apartment", "camp_site", "chalet", "guest_house", "hostel", "motel", "resort"}) { if (value == val) return true; } return false; } } // namespace BookingDataset::Hotel::Hotel(string const & src) { vector<string> rec(FieldsCount()); strings::SimpleTokenizer token(src, "\t"); for (size_t i = 0; token && i < rec.size(); ++i, ++token) rec[i] = *token; strings::to_uint(rec[Index(Fields::Id)], id); strings::to_double(rec[Index(Fields::Latitude)], lat); strings::to_double(rec[Index(Fields::Longtitude)], lon); name = rec[Index(Fields::Name)]; address = rec[Index(Fields::Address)]; strings::to_uint(rec[Index(Fields::Stars)], stars); strings::to_uint(rec[Index(Fields::PriceCategory)], priceCategory); strings::to_double(rec[Index(Fields::RatingBooking)], ratingBooking); strings::to_double(rec[Index(Fields::RatingUsers)], ratingUser); descUrl = rec[Index(Fields::DescUrl)]; strings::to_uint(rec[Index(Fields::Type)], type); } ostream & operator<<(ostream & s, BookingDataset::Hotel const & h) { return s << "Name: " << h.name << "\t Address: " << h.address << "\t lat: " << h.lat << " lon: " << h.lon; } BookingDataset::BookingDataset(string const & dataPath) { LoadHotels(dataPath); size_t counter = 0; for (auto const & hotel : m_hotels) { TBox b(TPoint(hotel.lat, hotel.lon), TPoint(hotel.lat, hotel.lon)); m_rtree.insert(std::make_pair(b, counter)); ++counter; } } bool BookingDataset::BookingFilter(OsmElement const & e) const { return Filter(e, [&](OsmElement const & e) { return MatchWithBooking(e); }); } bool BookingDataset::TourismFilter(OsmElement const & e) const { return Filter(e, [&](OsmElement const & e) { return true; }); } BookingDataset::Hotel const & BookingDataset::GetHotel(size_t index) const { ASSERT_GREATER(m_hotels.size(), index, ()); return m_hotels[index]; } vector<size_t> BookingDataset::GetNearestHotels(double lat, double lon, size_t limit, double maxDistance /* = 0.0 */) const { namespace bgi = boost::geometry::index; vector<size_t> indexes; for_each(bgi::qbegin(m_rtree, bgi::nearest(TPoint(lat, lon), limit)), bgi::qend(m_rtree), [&](TValue const & v) { auto const & hotel = m_hotels[v.second]; double const dist = ms::DistanceOnEarth(lat, lon, hotel.lat, hotel.lon); if (maxDistance != 0.0 && dist > maxDistance /* max distance in meters */) return; indexes.emplace_back(v.second); }); return indexes; } bool BookingDataset::MatchByName(string const & osmName, vector<size_t> const & bookingIndexes) const { return false; // Match name. // vector<strings::UniString> osmTokens; // NormalizeAndTokenizeString(name, osmTokens, search::Delimiters()); // // cout << "\n------------- " << name << endl; // // bool matched = false; // for (auto const & index : indexes) // { // vector<strings::UniString> bookingTokens; // NormalizeAndTokenizeString(m_hotels[index].name, bookingTokens, search::Delimiters()); // // map<size_t, vector<pair<size_t, size_t>>> weightPair; // // for (size_t j = 0; j < osmTokens.size(); ++j) // { // for (size_t i = 0; i < bookingTokens.size(); ++i) // { // size_t distance = strings::EditDistance(osmTokens[j].begin(), osmTokens[j].end(), // bookingTokens[i].begin(), // bookingTokens[i].end()); // if (distance < 3) // weightPair[distance].emplace_back(i, j); // } // } // // if (!weightPair.empty()) // { // cout << m_hotels[e.second] << endl; // matched = true; // } // } } void BookingDataset::BuildFeatures(function<void(OsmElement *)> const & fn) const { for (auto const & hotel : m_hotels) { OsmElement e; e.type = OsmElement::EntityType::Node; e.id = 1; e.lat = hotel.lat; e.lon = hotel.lon; e.AddTag("name", hotel.name); e.AddTag("ref:sponsored", strings::to_string(hotel.id)); e.AddTag("website", hotel.descUrl); e.AddTag("rating:sponsored", strings::to_string(hotel.ratingUser)); e.AddTag("stars", strings::to_string(hotel.stars)); e.AddTag("price_rate", strings::to_string(hotel.priceCategory)); e.AddTag("addr:full", hotel.address); switch (hotel.type) { case 19: case 205: e.AddTag("tourism", "motel"); break; case 21: case 206: case 212: e.AddTag("tourism", "resort"); break; case 3: case 23: case 24: case 25: case 202: case 207: case 208: case 209: case 210: case 216: case 220: case 223: e.AddTag("tourism", "guest_house"); break; case 14: case 204: case 213: case 218: case 219: case 226: case 222: e.AddTag("tourism", "hotel"); break; case 211: case 224: case 228: e.AddTag("tourism", "chalet"); break; case 13: case 225: case 203: e.AddTag("tourism", "hostel"); break; case 215: case 221: case 227: case 2: case 201: e.AddTag("tourism", "apartment"); break; case 214: e.AddTag("tourism", "camp_site"); break; default: e.AddTag("tourism", "hotel"); break; } fn(&e); } } // static double BookingDataset::ScoreByLinearNormDistance(double distance) { distance = my::clamp(distance, 0, kDistanceLimitInMeters); return 1.0 - distance / kDistanceLimitInMeters; } void BookingDataset::LoadHotels(string const & path) { m_hotels.clear(); if (path.empty()) return; ifstream src(path); if (!src.is_open()) { LOG(LERROR, ("Error while opening", path, ":", strerror(errno))); return; } for (string line; getline(src, line);) m_hotels.emplace_back(line); } bool BookingDataset::MatchWithBooking(OsmElement const & e) const { string name; for (auto const & tag : e.Tags()) { if (tag.key == "name") { name = tag.value; break; } } if (name.empty()) return false; // Find |kMaxSelectedElements| nearest values to a point. auto const bookingIndexes = GetNearestHotels(e.lat, e.lon, kMaxSelectedElements, kDistanceLimitInMeters); bool matched = false; for (size_t const j : bookingIndexes) { auto const & hotel = GetHotel(j); double const distanceMeters = ms::DistanceOnEarth(e.lat, e.lon, hotel.lat, hotel.lon); double score = ScoreByLinearNormDistance(distanceMeters); matched = score > kOptimalThreshold; if (matched) break; } return matched; } bool BookingDataset::Filter(OsmElement const & e, function<bool(OsmElement const &)> const & fn) const { if (e.type != OsmElement::EntityType::Node) return false; if (e.Tags().empty()) return false; bool matched = false; for (auto const & tag : e.Tags()) { if (tag.key == "tourism" && CheckForValues(tag.value)) { matched = fn(e); break; } } // TODO: Need to write file with dropped osm features. return matched; } } // namespace generator
[ "yershov@corp.mail.ru" ]
yershov@corp.mail.ru
c372f73b9fd5119e174357e458eaf8b3f6bba794
03c01f0a10c844c3432f499e59271e31898f3a3a
/Shovels and Swords.cpp
8c95eb6ae87095231ae98c242fb188c0825e5307
[]
no_license
AmirFaruk75/Codeforces
ae2fba252a236be2baafe27d75008ecdb95febdb
3a381547543a8fd557afaa68c4ed576bcb662906
refs/heads/main
2023-03-07T22:56:45.179559
2021-02-23T16:31:58
2021-02-23T16:31:58
341,608,698
0
0
null
null
null
null
UTF-8
C++
false
false
758
cpp
#include<bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); int t,a,b,i,j,c,d,e,f,g,h; cin>>t; for(i=0;i<t;i++) { cin>>a>>b; if(a>=b) { c=a/2; if(b<c) { cout<<b<<endl; } else{ d=b-c; e=a%2; f=d+e; g=f/3; cout<<c+g<<endl; } } else{ c=b/2; if(a<c) { cout<<a<<endl; } else{ d=a-c; e=b%2; f=e+d; g=f/3; cout<<c+g; } } } }
[ "noreply@github.com" ]
AmirFaruk75.noreply@github.com
fb20e5b5f06ae8930e678e73feb40274709ded12
ef620e1a2c22758ffc835ebb12e9d1a7a9b7fb0d
/connect4solver/Constants.MoveData.h
f4fd778c8f1e66810b2644ebae7bf58c879d9254
[]
no_license
dfoverdx/connect4solver
e3eb3f0fc12b6419cda50634cb53c0dad01b7f0b
036b0b953af618b45fd933ce0f5417e38321cc11
refs/heads/master
2021-08-06T14:57:48.939912
2017-11-01T20:57:32
2017-11-01T20:57:32
107,034,998
0
0
null
null
null
null
UTF-8
C++
false
false
2,205
h
#pragma once #include "Constants.h" #include "Helpers.h" #include "MoveData.CompilerFlagTypedefs.h" namespace connect4solver { namespace moveDataConstants { constexpr MoveDataBase MOVES_TO_WIN_MASK_BITS = RequiredBits<BOARD_SIZE>::value; constexpr MoveDataBase IS_FINISHED_MASK_BITS = 1; constexpr MoveDataBase IS_SYMMETRIC_MASK_BITS = 1; constexpr MoveDataBase REF_COUNT_MASK_BITS = RequiredBits<BOARD_WIDTH>::value; constexpr MoveDataBase WORKER_THREAD_ID_MASK_BITS = 4; #define makeIndex(prevMask) prevMask##_MASK_INDEX + prevMask##_MASK_BITS constexpr MoveDataBase MOVES_TO_WIN_MASK_INDEX = 0; constexpr MoveDataBase IS_SYMMETRIC_MASK_INDEX = makeIndex(MOVES_TO_WIN); constexpr MoveDataBase IS_FINISHED_MASK_INDEX = makeIndex(IS_SYMMETRIC); constexpr MoveDataBase REF_COUNT_MASK_INDEX = makeIndex(IS_FINISHED); constexpr MoveDataBase WORKER_THREAD_ID_MASK_INDEX = makeIndex(REF_COUNT); #undef makeIndex #if !BF #define makeMask(maskName) constexpr MoveDataBase maskName##_MASK = ((1 << maskName##_MASK_BITS) - 1) << maskName##_MASK_INDEX makeMask(MOVES_TO_WIN); // ---- ---- --11 1111 makeMask(IS_SYMMETRIC); // ---- ---- -1-- ---- makeMask(IS_FINISHED); // ---- ---- 1--- ---- makeMask(REF_COUNT); // ---- -111 ---- ---- makeMask(WORKER_THREAD_ID); // -111 1--- ---- ---- constexpr MoveDataBase REF_COUNT_1 = 0x1 << REF_COUNT_MASK_INDEX; // ---- ---1 ---- ---- constexpr MoveDataBase FINISH_MASK = // -111 1--- 1111 1111 IS_FINISHED_MASK | WORKER_THREAD_ID_MASK | MOVES_TO_WIN_MASK; constexpr MoveDataBase BLACK_LOST_MASK = // -111 1--- 111- 1-1- IS_FINISHED_MASK | WORKER_THREAD_ID_MASK | BLACK_LOST << MOVES_TO_WIN_MASK_INDEX; #undef makeMask #endif } }
[ "thinkin.arbys@gmail.com" ]
thinkin.arbys@gmail.com
fe78a0dae67da977156383ae71393014e60bda8c
aaf04ff1e0ec94e769103faf6b74e4f3570337c5
/sdks/spirit/boost/mpl/iter_fold_if.hpp
dc3791f7d882293b1bff07abb3da13eb455f4e91
[]
no_license
jacob-meacham/Ego
815ac6cb63f2fbf28e924f66729ca36147881000
682ae352fde6e08ad728899d81ab9a2039ccc27c
refs/heads/master
2021-01-01T05:36:49.656269
2015-12-27T19:40:11
2015-12-27T19:40:11
10,834,409
1
0
null
null
null
null
UTF-8
C++
false
false
3,131
hpp
#ifndef BOOST_MPL_ITER_FOLD_IF_HPP_INCLUDED #define BOOST_MPL_ITER_FOLD_IF_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2003-2004 // Copyright Eric Friedman 2003 // // 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) // // See http://www.boost.org/libs/mpl for documentation. // $Source$ // $Date: 2004-09-02 17:41:37 +0200 (gio, 02 set 2004) $ // $Revision: 24874 $ #include <boost/mpl/begin_end.hpp> #include <boost/mpl/logical.hpp> #include <boost/mpl/always.hpp> #include <boost/mpl/eval_if.hpp> #include <boost/mpl/if.hpp> #include <boost/mpl/pair.hpp> #include <boost/mpl/apply.hpp> #include <boost/mpl/aux_/iter_fold_if_impl.hpp> #include <boost/mpl/aux_/na_spec.hpp> #include <boost/mpl/aux_/lambda_support.hpp> #include <boost/mpl/aux_/config/forwarding.hpp> #include <boost/mpl/aux_/config/workaround.hpp> #include <boost/type_traits/is_same.hpp> namespace boost { namespace mpl { namespace aux { template< typename Predicate, typename LastIterator > struct iter_fold_if_pred { template< typename State, typename Iterator > struct apply #if !defined(BOOST_MPL_CFG_NO_NESTED_FORWARDING) : and_< not_< is_same<Iterator,LastIterator> > , apply1<Predicate,Iterator> > { #else { typedef and_< not_< is_same<Iterator,LastIterator> > , apply1<Predicate,Iterator> > type; #endif }; }; } // namespace aux template< typename BOOST_MPL_AUX_NA_PARAM(Sequence) , typename BOOST_MPL_AUX_NA_PARAM(State) , typename BOOST_MPL_AUX_NA_PARAM(ForwardOp) , typename BOOST_MPL_AUX_NA_PARAM(ForwardPredicate) , typename BOOST_MPL_AUX_NA_PARAM(BackwardOp) , typename BOOST_MPL_AUX_NA_PARAM(BackwardPredicate) > struct iter_fold_if { typedef typename begin<Sequence>::type first_; typedef typename end<Sequence>::type last_; typedef typename eval_if< is_na<BackwardPredicate> , if_< is_na<BackwardOp>, always<false_>, always<true_> > , identity<BackwardPredicate> >::type backward_pred_; // cwpro8 doesn't like 'cut-off' type here (use typedef instead) #if !BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3003)) && !BOOST_WORKAROUND(__IBMCPP__, BOOST_TESTED_AT(600)) struct result_ : #else typedef #endif aux::iter_fold_if_impl< first_ , State , ForwardOp , protect< aux::iter_fold_if_pred< ForwardPredicate,last_ > > , BackwardOp , backward_pred_ > #if !BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3003)) && !BOOST_WORKAROUND(__IBMCPP__, BOOST_TESTED_AT(600)) { }; #else result_; #endif public: typedef pair< typename result_::state , typename result_::iterator > type; BOOST_MPL_AUX_LAMBDA_SUPPORT( 6 , iter_fold_if , (Sequence,State,ForwardOp,ForwardPredicate,BackwardOp,BackwardPredicate) ) }; BOOST_MPL_AUX_NA_SPEC(6, iter_fold_if) }} #endif // BOOST_MPL_ITER_FOLD_IF_HPP_INCLUDED
[ "jmeacham@palantir.com" ]
jmeacham@palantir.com
e3f09a6e12cf874ccd86c0ebf2aae36398d78c32
12043db0f57f5d9402a99507648bcbb4d9417452
/Programming_Abstractions/Chapter_10/Exercise_01/Exercise_01/editor_test.cpp
bca7a401e559b6f5574d89bd617f8a866165e029
[]
no_license
daniellozuz/CPP
a8afb1ae3353bd483cf953fac8a70b0b1446023c
fdc8957158522fc27aa55a44b3e45333157b843f
refs/heads/master
2021-05-12T08:31:17.581023
2018-03-07T23:41:45
2018-03-07T23:41:45
117,283,294
0
0
null
null
null
null
UTF-8
C++
false
false
906
cpp
#include "EditorBuffer.h" #include <iostream> #include <string> using namespace std; void execute_command(EditorBuffer &buffer, string line); int main(void) { EditorBuffer buffer; while (true) { cout << "*"; string command; getline(cin, command); if (command != "") execute_command(buffer, command); buffer.display(); } return 0; } void execute_command(EditorBuffer &buffer, string line) { switch (toupper(line[0])) { case 'I': for (int i = 1; i < line.length(); i++) buffer.insert_character(line[i]); break; case 'D': buffer.delete_character(); break; case 'F': buffer.move_cursor_forward(); break; case 'B': buffer.move_cursor_backward(); break; case 'J': buffer.move_cursor_to_start(); break; case 'E': buffer.move_cursor_to_end(); break; case 'Q': exit(0); default: cout << "Illegal command" << endl; break; } }
[ "daniel.zuziak@gmail.com" ]
daniel.zuziak@gmail.com
94ab6f6f037184890b6fdae9e8ad06e216f77de8
da4cc98ed821ec4c41a0a29c926c0a97df3c0bff
/demo/framework-dx11/unorderedaccessiblebatch.h
20c7875ec7b68b7ec4a038af80cc9eed7654b74d
[ "MIT" ]
permissive
rokuz/GraphicsDemo
514d308ad147214480b53e58c47cfccb558a9cbd
41300287cc9d2f7e4e0656348809db5b3c939ced
refs/heads/master
2023-04-06T20:15:11.159235
2023-03-31T21:32:13
2023-03-31T21:32:13
17,832,703
11
4
null
null
null
null
UTF-8
C++
false
false
1,642
h
/* * Copyright (c) 2014 Roman Kuznetsov * * 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 (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #pragma once namespace framework { class UnorderedAccessBuffer; class RenderTarget; struct UnorderedAccessibleBatch { ID3D11UnorderedAccessView* elements[D3D11_PS_CS_UAV_REGISTER_COUNT]; unsigned int initialValues[D3D11_PS_CS_UAV_REGISTER_COUNT]; int elementsNumber; UnorderedAccessibleBatch(); void add(std::shared_ptr<UnorderedAccessBuffer> buffer, unsigned int initialValue = -1); void add(std::shared_ptr<RenderTarget> renderTarget, unsigned int initialValue = -1); }; }
[ "r.kuznetsow@gmail.com" ]
r.kuznetsow@gmail.com
b9f57c0639e3cc260af0bdeffb3e5207d7908338
2de9e70c7b44b05f9029d8966bc2491378ed805f
/indie/object/IPowerUp.hpp
315a5733f773c0ab79af18a035e6be9e3506032a
[]
no_license
Zoryi/indie_studio
67cf3ffec17e71982642aeb6ebdd481565ec4e9d
bd2931d55bf09a8ae45c59e74b5a25e27daa873a
refs/heads/master
2020-04-07T17:10:11.940514
2018-11-21T14:25:17
2018-11-21T14:25:17
158,558,080
0
0
null
null
null
null
UTF-8
C++
false
false
238
hpp
// // EPITECH PROJECT, 2018 // indie_studio // File description: // IPowerUp.hpp // #ifndef POWERUP_HPP_ #define POWERUP_HPP_ # include "IObject.hpp" class IPowerUp : public IObject { public: virtual ~IPowerUp() = default; }; #endif
[ "romain.devalle@epitech.eu" ]
romain.devalle@epitech.eu
351201f6c09a3c555bb0219e57cd5624c1ff0d71
1588f7002ebfaceb9c382c73fce67ab435d0e840
/utils/src/PointNormal/NormalEstimator.h
e040ed5a8875721e368acf837d85a25e21cf37b6
[]
no_license
akosiorek/Tagger3D
ff04ac94a7f3bc9c0a189cc972e7cd3dcdb900ae
6459f41517710168080badbfc09e3ea1625c6a09
refs/heads/master
2016-09-05T19:47:32.612709
2014-10-14T18:46:44
2014-10-14T18:46:44
12,671,025
4
0
null
null
null
null
UTF-8
C++
false
false
890
h
/* * Tagger3D : NormalEstimator.h * * Created on: 28 lip 2013 * Author: Adam Kosiorek * Description: */ #ifndef NORMALESTIMATOR_H_ #define NORMALESTIMATOR_H_ #include "PointNormal.h" #include <pcl/features/normal_3d_omp.h> namespace Tagger3D { class NormalEstimator: public PointNormal { public: NormalEstimator() = delete; NormalEstimator(const std::map<std::string, std::string> &configMap); virtual ~NormalEstimator() = default; NormalCloud::Ptr computeNormals(const ColorCloud::Ptr &cloud); NormalVec computeNormals(const ColorVec &clouds); private: void createNormalEstimator(); std::unique_ptr<pcl::NormalEstimationOMP<pcl::PointXYZRGB, pcl::Normal>> normalEstimator; // Config keys const std::string normalRadius = moduleName + "normalRadius"; const std::string kNN = moduleName + "kNN"; }; } /* namespace Tagger3D */ #endif /* NORMALESTIMATOR_H_ */
[ "Kosiorek.Adam@gmail.com" ]
Kosiorek.Adam@gmail.com
7af69f5df3114533e65f12e0f9063824674a974c
f481aeb897c81095bf5bc544f9368aa78457694b
/1103.cpp
5a0178fa188414437eb8e1355b5127cc39ca30a6
[]
no_license
channyHuang/leetcodeOJ
78b10f31f9a6c6571124208efe85201a3690f2da
b41e9c3c076074b6ab9349455b0cf40c270df41f
refs/heads/master
2023-01-28T15:31:29.346320
2023-01-18T03:43:10
2023-01-18T03:43:10
221,703,848
0
0
null
null
null
null
UTF-8
C++
false
false
438
cpp
class Solution { public: vector<int> distributeCandies(int candies, int num_people) { vector<int> res; res.resize(num_people); int n = 1, pos = 0; while (candies >= n) { res[pos++] += n; if (pos >= num_people) pos -= num_people; candies -= n; n++; } if (candies == 0) return res; res[pos] += candies; return res; } };
[ "349117102@qq.com" ]
349117102@qq.com
6e4bd73023694c8ba3f433e67544c9c54efccb04
dd129fb6461d1b44dceb196caaa220e9f8398d18
/topics/shared-memory/cat-mmap.cc
442112c34208b3b218af5ab20f37f266448cde09
[]
no_license
jfasch/jf-linux-trainings
3af777b4c603dd5c3f6832c0034be44a062b493a
aebff2e6e0f98680aa14e1b7ad4a22e73a6f31b4
refs/heads/master
2020-04-29T19:13:33.398276
2020-03-29T20:45:33
2020-03-29T20:45:33
176,347,614
0
1
null
2019-10-01T06:02:49
2019-03-18T18:35:28
C++
UTF-8
C++
false
false
683
cc
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/mman.h> #include <stdlib.h> #include <unistd.h> #include <iostream> #include <cassert> int main(int argc, char** argv) { if (argc != 2) { std::cerr << "Usage: " << argv[0] << " <filename>" << std::endl; exit(1); } int fd = open(argv[1], O_RDONLY); if (fd == -1) { perror("open"); exit(1); } // determine file size, mmap, and finally output off_t len = lseek(fd, 0, SEEK_END); void *mem = mmap(NULL, len, PROT_READ, MAP_PRIVATE, fd, 0); ssize_t nwritten = write(STDOUT_FILENO, mem, len); assert(nwritten == len); return 0; }
[ "jf@faschingbauer.co.at" ]
jf@faschingbauer.co.at
7b8642e5d85671ce529dcac2a3788cd258953f5b
e2df82085ac658a7ca7c974919f3809e89d646bb
/LibWebRtcUsingExample/Include/rtc_base/signalthread.h
2c11da4507c4eece4f18dae6e93aaa9f879d5cd7
[ "Apache-2.0", "MIT" ]
permissive
HATTER-LONG/NoteBook_WebRtcLearning
7c846cf548804361123ff9cd6017cc05b3b9a559
834c94c82646e57d53fa5f1cc8210dda3799b78f
refs/heads/master
2023-06-30T21:45:56.672079
2021-08-07T08:46:34
2021-08-07T08:46:34
338,822,304
3
2
null
2021-02-14T14:33:08
2021-02-14T14:22:12
null
UTF-8
C++
false
false
5,398
h
/* * Copyright 2004 The WebRTC Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef RTC_BASE_SIGNALTHREAD_H_ #define RTC_BASE_SIGNALTHREAD_H_ #include <string> #include "rtc_base/checks.h" #include "rtc_base/constructormagic.h" #include "rtc_base/nullsocketserver.h" #include "rtc_base/sigslot.h" #include "rtc_base/thread.h" namespace rtc { /////////////////////////////////////////////////////////////////////////////// // SignalThread - Base class for worker threads. The main thread should call // Start() to begin work, and then follow one of these models: // Normal: Wait for SignalWorkDone, and then call Release to destroy. // Cancellation: Call Release(true), to abort the worker thread. // Fire-and-forget: Call Release(false), which allows the thread to run to // completion, and then self-destruct without further notification. // Periodic tasks: Wait for SignalWorkDone, then eventually call Start() // again to repeat the task. When the instance isn't needed anymore, // call Release. DoWork, OnWorkStart and OnWorkStop are called again, // on a new thread. // The subclass should override DoWork() to perform the background task. By // periodically calling ContinueWork(), it can check for cancellation. // OnWorkStart and OnWorkDone can be overridden to do pre- or post-work // tasks in the context of the main thread. /////////////////////////////////////////////////////////////////////////////// class SignalThread : public sigslot::has_slots<>, protected MessageHandler { public: SignalThread(); // Context: Main Thread. Call before Start to change the worker's name. bool SetName(const std::string& name, const void* obj); // Context: Main Thread. Call to begin the worker thread. void Start(); // Context: Main Thread. If the worker thread is not running, deletes the // object immediately. Otherwise, asks the worker thread to abort processing, // and schedules the object to be deleted once the worker exits. // SignalWorkDone will not be signalled. If wait is true, does not return // until the thread is deleted. void Destroy(bool wait); // Context: Main Thread. If the worker thread is complete, deletes the // object immediately. Otherwise, schedules the object to be deleted once // the worker thread completes. SignalWorkDone will be signalled. void Release(); // Context: Main Thread. Signalled when work is complete. sigslot::signal1<SignalThread *> SignalWorkDone; enum { ST_MSG_WORKER_DONE, ST_MSG_FIRST_AVAILABLE }; protected: ~SignalThread() override; Thread* worker() { return &worker_; } // Context: Main Thread. Subclass should override to do pre-work setup. virtual void OnWorkStart() { } // Context: Worker Thread. Subclass should override to do work. virtual void DoWork() = 0; // Context: Worker Thread. Subclass should call periodically to // dispatch messages and determine if the thread should terminate. bool ContinueWork(); // Context: Worker Thread. Subclass should override when extra work is // needed to abort the worker thread. virtual void OnWorkStop() { } // Context: Main Thread. Subclass should override to do post-work cleanup. virtual void OnWorkDone() { } // Context: Any Thread. If subclass overrides, be sure to call the base // implementation. Do not use (message_id < ST_MSG_FIRST_AVAILABLE) void OnMessage(Message* msg) override; private: enum State { kInit, // Initialized, but not started kRunning, // Started and doing work kReleasing, // Same as running, but to be deleted when work is done kComplete, // Work is done kStopping, // Work is being interrupted }; class Worker : public Thread { public: explicit Worker(SignalThread* parent) : Thread(std::unique_ptr<SocketServer>(new NullSocketServer())), parent_(parent) {} ~Worker() override; void Run() override; bool IsProcessingMessages() override; private: SignalThread* parent_; RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(Worker); }; class RTC_SCOPED_LOCKABLE EnterExit { public: explicit EnterExit(SignalThread* t) RTC_EXCLUSIVE_LOCK_FUNCTION(t->cs_) : t_(t) { t_->cs_.Enter(); // If refcount_ is zero then the object has already been deleted and we // will be double-deleting it in ~EnterExit()! (shouldn't happen) RTC_DCHECK_NE(0, t_->refcount_); ++t_->refcount_; } ~EnterExit() RTC_UNLOCK_FUNCTION() { bool d = (0 == --t_->refcount_); t_->cs_.Leave(); if (d) delete t_; } private: SignalThread* t_; RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(EnterExit); }; void Run(); void OnMainThreadDestroyed(); Thread* main_; Worker worker_; CriticalSection cs_; State state_; int refcount_; RTC_DISALLOW_COPY_AND_ASSIGN(SignalThread); }; /////////////////////////////////////////////////////////////////////////////// } // namespace rtc #endif // RTC_BASE_SIGNALTHREAD_H_
[ "caolei6767@gmail.com" ]
caolei6767@gmail.com
060031cfc46e091203d2239c3131a08e473d4555
6d763845a081a6c5c372a304c3bae1ccd949e6fa
/day04/ex00/Cow.hpp
eb9ae99ba327530b7b9a000213f3313dc4ce3aad
[]
no_license
hmiso/CPP_modules
cc5539764b10d9005aea0ccdf894c0fd2562a649
e0608a810ef6bbb7cb29461721f6248e0c3b88eb
refs/heads/master
2023-02-28T09:12:49.284788
2021-02-06T14:40:33
2021-02-06T14:40:33
322,648,779
0
0
null
null
null
null
UTF-8
C++
false
false
1,093
hpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Cow.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hmiso <hmiso@student.21-school.ru> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/11 13:34:41 by hmiso #+# #+# */ /* Updated: 2021/01/11 13:35:32 by hmiso ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef COW_HPP #define COW_HPP #include "Victim.hpp" class Cow : public Victim { private: std::string name; public: Cow(std::string name); void getPolymorphed() const; virtual ~Cow(); }; #endif
[ "macbook@MacBook-Pro-MacBook.local" ]
macbook@MacBook-Pro-MacBook.local
5608a9b97c922f6b022755c0efbe466851850b70
a45067a48af5e720dc6144b39685d3b1fba0432f
/offer/3.cpp
9887a24e63a104e17a8908f64453cccfff5a1619
[]
no_license
lihao779/linuxsys
b8cb1d5a42a2a32fb648a094c4332e68ca501f71
c445ff7d11ae546f3ca71aa430c7f788cf7e2e39
refs/heads/master
2023-05-29T17:28:54.924952
2021-06-15T14:26:03
2021-06-15T14:26:03
305,936,508
0
0
null
null
null
null
UTF-8
C++
false
false
1,052
cpp
#include <stdio.h> #if 0 bool IsHavenum(int array[3][3], int row, int col, int num) { int temprow = 0; int tempcol = col - 1; int temp = -1; while(temprow <= row - 1 && tempcol >= 0) { temp = array[temprow][tempcol]; if(temp == num) return true; else if(temp > num) tempcol--; else temprow++; } return false; } #endif bool IsHavenum(int array[][3], int row, int col, int num) { int temprow = row - 1; int tempcol = 0; while(array != NULL && temprow >= 0 && tempcol <= col - 1) { int temp = array[temprow][tempcol]; if(temp == num) return true; else if(temp > num) temprow--; else tempcol++; } return false; } int main() { int array[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int row , col; row = col = 3; if(IsHavenum(array, row, col, 7)) { printf("have 7\n"); } else printf("not have 7\n"); return 0; }
[ "3024978915@qq.com" ]
3024978915@qq.com
8533a4336175f9ee5d1e6bed19a9c3cb8da6e237
10377d9a5b1e2d451d07bb64d3981e936e1035d7
/include/NumCpp/Functions/greater_equal.hpp
4dc88fa5a4259b16380c0ef78614bc69fa62a6c5
[ "MIT" ]
permissive
faichele/NumCpp
03ac79cde618d6dfe08c3352fff7d235527a130f
7c8fc50fbe44b80eaa105f0f9258120abddfcec2
refs/heads/master
2020-12-29T16:25:21.426391
2020-01-20T05:23:34
2020-01-20T05:23:34
238,668,660
0
0
MIT
2020-02-06T11:02:13
2020-02-06T11:02:12
null
UTF-8
C++
false
false
2,004
hpp
/// @file /// @author David Pilger <dpilger26@gmail.com> /// [GitHub Repository](https://github.com/dpilger26/NumCpp) /// @version 1.2 /// /// @section License /// Copyright 2019 David Pilger /// /// 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. /// /// @section Description /// Functions for working with NdArrays /// #pragma once #include "NumCpp/NdArray.hpp" namespace nc { //============================================================================ // Method Description: /// Return the truth value of (x1 >= x2) element-wise. /// /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.greater_equal.html /// /// /// @param inArray1 /// @param inArray2 /// @return /// NdArray /// template<typename dtype> NdArray<bool> greater_equal(const NdArray<dtype>& inArray1, const NdArray<dtype>& inArray2) { return inArray1 >= inArray2; } }
[ "dpilger26@gmail.com" ]
dpilger26@gmail.com
c4335096b953f9efeeea3d64b018ea0722800ac8
452cd2da6d866568579e8f82477295bb44ea03d6
/Example/main_writer.cc
96e0a87353f22dc15e37532e111bb566846610d9
[]
no_license
nlurkin/XMLPreProcessor
7cfd57cd3d1811aa5fcb329f401c6c47c7a796e8
f45c19e498e907d4d9ac7161df3975d53c7b00ea
refs/heads/master
2021-05-16T02:49:11.190499
2015-06-25T11:43:44
2015-06-25T11:43:44
34,051,860
1
1
null
2020-02-29T21:39:51
2015-04-16T11:26:01
Python
UTF-8
C++
false
false
628
cc
/* * main_writer.cc * * Created on: 18 Apr 2015 * Author: nlurkin */ #include "XMLConfWriter.h" #include "ex_struct.h" #include <iostream> #include <cstring> using namespace std; int main(){ XMLConfWriter writer; exampleStruct test; test.version = 42; strcpy(test.name, "my_example"); test.my_substruct.my_double = 5.5; writer.createDocument("exampleStruct"); writer.addPathAsHex("exampleStruct.version", test.version); writer.addPath("exampleStruct.name", test.name); writer.addPath("exampleStruct.my_substruct.my_double", test.my_substruct.my_double); writer.writeDocument("example_writer.xml"); }
[ "nlurkin@debian" ]
nlurkin@debian
bc4ccf67679f8c45dcf9ad364da3b32ec2050bf9
ed5669151a0ebe6bcc8c4b08fc6cde6481803d15
/test/magma-1.6.0/src/dpotrf_panel_batched.cpp
e64f1fb9539f78834c00c86f9eb55a16ac12c48b
[]
no_license
JieyangChen7/DVFS-MAGMA
1c36344bff29eeb0ce32736cadc921ff030225d4
e7b83fe3a51ddf2cad0bed1d88a63f683b006f54
refs/heads/master
2021-09-26T09:11:28.772048
2018-05-27T01:45:43
2018-05-27T01:45:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,424
cpp
/* -- MAGMA (version 1.6.0) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver November 2013 @author Azzam Haidar @author Tingxing Dong @generated from zpotrf_panel_batched.cpp normal z -> d, Sat Nov 15 19:54:09 2014 */ #include "common_magma.h" #include "batched_kernel_param.h" //////////////////////////////////////////////////////////////////////////////////////// extern "C" magma_int_t magma_dpotrf_panel_batched( magma_uplo_t uplo, magma_int_t n, magma_int_t nb, double** dA_array, magma_int_t ldda, double** dX_array, magma_int_t dX_length, double** dinvA_array, magma_int_t dinvA_length, double** dW0_displ, double** dW1_displ, double** dW2_displ, double** dW3_displ, double** dW4_displ, magma_int_t *info_array, magma_int_t gbstep, magma_int_t batchCount, cublasHandle_t myhandle) { //=============================================== // panel factorization //=============================================== if(n<nb){ printf("magma_dpotrf_panel error n < nb %d < %d \n",(int) n, (int) nb); return -101; } #if 0 magma_dpotf2_batched( uplo, n, nb, dA_array, ldda, dW1_displ, dW2_displ, dW3_displ, dW4_displ, info_array, gbstep, batchCount, myhandle); #else magma_dpotf2_batched( uplo, nb, nb, dA_array, ldda, dW1_displ, dW2_displ, dW3_displ, dW4_displ, info_array, gbstep, batchCount, myhandle); if((n-nb) > 0){ magma_ddisplace_pointers(dW0_displ, dA_array, ldda, nb, 0, batchCount); magmablas_dtrsm_work_batched(MagmaRight, MagmaLower, MagmaConjTrans, MagmaNonUnit, 1, n-nb, nb, MAGMA_D_ONE, dA_array, ldda, dW0_displ, ldda, dX_array, n-nb, dinvA_array, dinvA_length, dW1_displ, dW2_displ, dW3_displ, dW4_displ, 0, batchCount); } #endif return 0; } //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// extern "C" magma_int_t magma_dpotrf_recpanel_batched( magma_uplo_t uplo, magma_int_t m, magma_int_t n, magma_int_t min_recpnb, double** dA_array, magma_int_t ldda, double** dX_array, magma_int_t dX_length, double** dinvA_array, magma_int_t dinvA_length, double** dW0_displ, double** dW1_displ, double** dW2_displ, double** dW3_displ, double** dW4_displ, magma_int_t *info_array, magma_int_t gbstep, magma_int_t batchCount, cublasHandle_t myhandle) { // Quick return if possible if (m ==0 || n == 0) { return 1; } if (uplo == MagmaUpper) { printf("Upper side is unavailable \n"); return -100; } if(m<n){ printf("error m < n %d < %d \n", (int) m, (int) n); return -101; } double **dA_displ = NULL; magma_malloc((void**)&dA_displ, batchCount * sizeof(*dA_displ)); double alpha = MAGMA_D_NEG_ONE; double beta = MAGMA_D_ONE; magma_int_t panel_nb = n; if(panel_nb <= min_recpnb){ //printf("calling bottom panel recursive with m=%d nb=%d\n",m,n); // panel factorization magma_ddisplace_pointers(dA_displ, dA_array, ldda, 0, 0, batchCount); //magma_dpotrf_rectile_batched(uplo, m, panel_nb, 16, magma_dpotrf_panel_batched( uplo, m, panel_nb, dA_displ, ldda, dX_array, dX_length, dinvA_array, dinvA_length, dW0_displ, dW1_displ, dW2_displ, dW3_displ, dW4_displ, info_array, gbstep, batchCount, myhandle); } else{ // split A over two [A A2] // panel on A1, update on A2 then panel on A1 magma_int_t n1 = n/2; magma_int_t n2 = n-n1; magma_int_t m1 = m; magma_int_t m2 = m-n1; magma_int_t p1 = 0; magma_int_t p2 = n1; // panel on A1 //printf("calling recursive panel on A1 with m=%d nb=%d min_recpnb %d\n",m1,n1,min_recpnb); magma_ddisplace_pointers(dA_displ, dA_array, ldda, p1, p1, batchCount); magma_dpotrf_recpanel_batched( uplo, m1, n1, min_recpnb, dA_displ, ldda, dX_array, dX_length, dinvA_array, dinvA_length, dW0_displ, dW1_displ, dW2_displ, dW3_displ, dW4_displ, info_array, gbstep, batchCount, myhandle); // update A2 //printf("calling update A2 with m=%d n=%d k=%d\n",m2,n2,n1); magma_ddisplace_pointers(dA_displ, dA_array, ldda, p1+n1, p1, batchCount); magma_ddisplace_pointers(dW0_displ, dA_array, ldda, p1+n1, p2, batchCount); magmablas_dgemm_batched(MagmaNoTrans, MagmaConjTrans, m2, n2, n1, alpha, dA_displ, ldda, dA_displ, ldda, beta, dW0_displ, ldda, batchCount); // panel on A2 //printf("calling recursive panel on A2 with m=%d nb=%d min_recpnb %d\n",m2,n2,min_recpnb); magma_ddisplace_pointers(dA_displ, dA_array, ldda, p2, p2, batchCount); magma_dpotrf_recpanel_batched( uplo, m2, n2, min_recpnb, dA_displ, ldda, dX_array, dX_length, dinvA_array, dinvA_length, dW0_displ, dW1_displ, dW2_displ, dW3_displ, dW4_displ, info_array, gbstep, batchCount, myhandle); } magma_free(dA_displ); return 0; } //////////////////////////////////////////////////////////////////////////////////////// extern "C" magma_int_t magma_dpotrf_rectile_batched( magma_uplo_t uplo, magma_int_t m, magma_int_t n, magma_int_t min_recpnb, double** dA_array, magma_int_t ldda, double** dX_array, magma_int_t dX_length, double** dinvA_array, magma_int_t dinvA_length, double** dW0_displ, double** dW1_displ, double** dW2_displ, double** dW3_displ, double** dW4_displ, magma_int_t *info_array, magma_int_t gbstep, magma_int_t batchCount, cublasHandle_t myhandle) { //magma_int_t DEBUG=0; // Quick return if possible if (m ==0 || n == 0) { return 1; } if (uplo == MagmaUpper) { printf("Upper side is unavailable \n"); return -100; } if(m<n){ printf("error m < n %d < %d \n", (int) m, (int) n); return -101; } double **dA_displ = NULL; magma_malloc((void**)&dA_displ, batchCount * sizeof(*dA_displ)); double alpha = MAGMA_D_NEG_ONE; double beta = MAGMA_D_ONE; magma_int_t panel_nb = n; if(panel_nb <= min_recpnb){ // if(DEBUG==1) printf("calling bottom panel recursive with n=%d\n",(int) panel_nb); // panel factorization magma_ddisplace_pointers(dA_displ, dA_array, ldda, 0, 0, batchCount); magma_dpotrf_panel_batched( uplo, m, panel_nb, dA_displ, ldda, dX_array, dX_length, dinvA_array, dinvA_length, dW0_displ, dW1_displ, dW2_displ, dW3_displ, dW4_displ, info_array, gbstep, batchCount, myhandle); } else{ // split A over two [A11 A12; A21 A22; A31 A32] // panel on tile A11, // trsm on A21, using A11 // update on A22 then panel on A22. // finally a trsm on [A31 A32] using the whole [A11 A12; A21 A22] magma_int_t n1 = n/2; magma_int_t n2 = n-n1; magma_int_t p1 = 0; magma_int_t p2 = n1; // panel on A11 //if(DEBUG==1) printf("calling recursive panel on A11=A(%d,%d) with n=%d min_recpnb %d\n",(int) p1, (int) p1, (int) n1, (int) min_recpnb); magma_ddisplace_pointers(dA_displ, dA_array, ldda, p1, p1, batchCount); magma_dpotrf_rectile_batched( uplo, n1, n1, min_recpnb, dA_displ, ldda, dX_array, dX_length, dinvA_array, dinvA_length, dW0_displ, dW1_displ, dW2_displ, dW3_displ, dW4_displ, info_array, gbstep, batchCount, myhandle); // TRSM on A21 //if(DEBUG==1) printf("calling trsm on A21=A(%d,%d) using A11==A(%d,%d) with m=%d k=%d \n",p2,p1,p1,p1,n2,n1); magma_ddisplace_pointers(dA_displ, dA_array, ldda, p1, p1, batchCount); magma_ddisplace_pointers(dW0_displ, dA_array, ldda, p2, p1, batchCount); magmablas_dtrsm_work_batched(MagmaRight, MagmaLower, MagmaConjTrans, MagmaNonUnit, 1, n2, n1, MAGMA_D_ONE, dA_displ, ldda, dW0_displ, ldda, dX_array, n2, dinvA_array, dinvA_length, dW1_displ, dW2_displ, dW3_displ, dW4_displ, 0, batchCount); // update A22 //if(DEBUG==1) printf("calling update A22=A(%d,%d) using A21==A(%d,%d) with m=%d n=%d k=%d\n",p2,p2,p2,p1,n2,n2,n1); magma_ddisplace_pointers(dA_displ, dA_array, ldda, p2, p1, batchCount); magma_ddisplace_pointers(dW0_displ, dA_array, ldda, p2, p2, batchCount); magmablas_dgemm_batched(MagmaNoTrans, MagmaConjTrans, n2, n2, n1, alpha, dA_displ, ldda, dA_displ, ldda, beta, dW0_displ, ldda, batchCount); // panel on A22 //if(DEBUG==1) printf("calling recursive panel on A22=A(%d,%d) with n=%d min_recpnb %d\n",p2,p2,n2,min_recpnb); magma_ddisplace_pointers(dA_displ, dA_array, ldda, p2, p2, batchCount); magma_dpotrf_rectile_batched( uplo, n2, n2, min_recpnb, dA_displ, ldda, dX_array, dX_length, dinvA_array, dinvA_length, dW0_displ, dW1_displ, dW2_displ, dW3_displ, dW4_displ, info_array, gbstep, batchCount, myhandle); } if(m>n){ // TRSM on A3: //if(DEBUG==1) printf("calling trsm AT THE END on A3=A(%d,%d): using A1222==A(%d,%d) with m=%d k=%d \n",n,0,0,0,m-n,n); magma_ddisplace_pointers(dA_displ, dA_array, ldda, 0, 0, batchCount); magma_ddisplace_pointers(dW0_displ, dA_array, ldda, n, 0, batchCount); magmablas_dtrsm_work_batched(MagmaRight, MagmaLower, MagmaConjTrans, MagmaNonUnit, 1, m-n, n, MAGMA_D_ONE, dA_displ, ldda, dW0_displ, ldda, dX_array, m-n, dinvA_array, dinvA_length, dW1_displ, dW2_displ, dW3_displ, dW4_displ, 0, batchCount); } magma_free(dA_displ); return 0; }
[ "cjy7117@gmail.com" ]
cjy7117@gmail.com
1609244a1ad6c2cde27161dc0aac7fd20ea32d1c
b289812c11c6847107fe07066e7a5e09133f4245
/Candy/candy.cpp
e8be4caae1df9da5188146fee7c51c85e16bef39
[ "MIT" ]
permissive
somnusfish/leetcode
ccff146ac84eed6a92dabc600e7d4fd3f8981234
eae387efd76159bc63948235fd1cb7d56f45335e
refs/heads/master
2020-12-24T16:25:04.543885
2016-04-27T02:13:50
2016-04-27T02:13:50
35,150,389
3
0
null
null
null
null
UTF-8
C++
false
false
1,296
cpp
class Solution { public: int candy(vector<int>& ratings) { if(ratings.size()==0){ return 0; } if(ratings.size()==1){ return 1; } int * candyArray = new int[ratings.size()]; int peak = 0; int nadir = 0; candyArray[0] = 1; for(int i=0; i<ratings.size(); i++){ if(ratings[i] == ratings[i-1]){ candyArray[i] = 1; } else if(ratings[i] > ratings[i-1]){ candyArray[i] = candyArray[i-1]+1; } else{ candyArray[i] = candyArray[i-1]-1; } if(((i!=ratings.size()-1) && (ratings[i]<=ratings[i+1])) || (i==ratings.size()-1)){ int j=i; int shift = 1-candyArray[i]; while((j>=0) && (ratings[j] < ratings[j-1])){ candyArray[j] += shift; j--; } if(shift>0){ candyArray[j] += shift; } } } int sum = 0; for(int i=0; i<ratings.size(); i++){ cout << candyArray[i] << " "; sum += candyArray[i]; } return sum; } };
[ "somnusfish@gmail.com" ]
somnusfish@gmail.com
85099beff0ad7fc2c14257bcd30f2f0dac5e2c5e
81cfe1dbd19df9e1dcb944bb9fec44238af153fc
/contest_grafos/ga.cpp
4d9cbcbdb81c2daaa7beac941cf6294df100d700
[]
no_license
weirdfish23/icpc
a3807bd4d93e8546ed818c0a0627e7ac405c1477
5464f928bca6e38cbb6fec945899af0f1d97ee90
refs/heads/master
2020-07-07T20:41:11.012953
2019-09-28T03:25:27
2019-09-28T03:25:27
203,472,187
0
0
null
null
null
null
UTF-8
C++
false
false
186
cpp
#include <iostream> using namespace std; int main (){ cout << 200000 << endl; for(int i=1; i<=200000; ++i){ cout << i << " "; } cout << endl; return 0; }
[ "jjcabrerarios@gmail.com" ]
jjcabrerarios@gmail.com
a24d659b48edceb135204aaf79f01278ec2a4a61
01a2c436a1b8c9f2518ae2b0165b69603a6d8c52
/date/main.cpp
c14536bc9ea8c0826b211c031c563d6f6b6969fa
[]
no_license
0x81-sh/cpp-composition-article
5c50905b6a76f05d528aaa84cad01f9af85e4bfb
88de3e072798ab86c0fc788091b418afedaa65f7
refs/heads/master
2023-06-01T09:10:00.210917
2021-06-17T15:12:35
2021-06-17T15:12:35
377,873,192
0
0
null
null
null
null
UTF-8
C++
false
false
1,188
cpp
#include <iostream> #include <cassert> #include "Date.h" void testIsLeapYear(const Date &date, bool expected); void testAdd(Date &source, int days, const Date &expected); void testDiff(Date &source, const Date &comparison, int expected); int main() { testIsLeapYear(Date(1, 1, 0), true); testIsLeapYear(Date(1, 1, 420), true); testIsLeapYear(Date(1, 1, 1000), false); testIsLeapYear(Date(1, 1, 2001), false); Date *testDate = new Date(); testAdd(*testDate, 366, Date(1, 1, 2001)); testAdd(*testDate, 1, Date(2, 1, 2001)); testAdd(*testDate, 30, Date(1, 2, 2001)); delete(testDate); Date *testDiffDate = new Date(1, 1, 2020); testDiff(*testDiffDate, Date(1, 1, 2019), 365); testDiff(*testDiffDate, Date(1, 2, 2020), 31); testDiff(*testDiffDate, Date(2, 1, 2020), 1); delete(testDiffDate); } void testIsLeapYear(const Date &date, bool expected) { assert(date.isLeapYear() == expected); } void testAdd(Date &source, int days, const Date &expected) { source.add(days); assert(source == expected); } void testDiff(Date &source, const Date &comparison, int expected) { assert(source.diff(comparison) == expected); }
[ "ulrich.barnstedt@gmail.com" ]
ulrich.barnstedt@gmail.com
7e701d07e3a6c36f5795c283e7e071080c91083c
79901169d636e19ca57096af214d73a2922e6b86
/Marvel vs Capcom/Helper/VectorHelper.cpp
1f3acf81bcd15ea06f9a4ada75405106285bc415
[]
no_license
delpinor/taller7542
d46ac3dabdfb4f35ad93cddf1f90ad913df4e2b1
36930692fe62cd2ee86d080aee2e29ad156079e5
refs/heads/master
2022-04-22T02:26:18.830009
2019-04-30T13:17:29
2019-04-30T13:17:29
257,655,906
0
0
null
null
null
null
UTF-8
C++
false
false
344
cpp
/* * VectorHelper.cpp * * Created on: Apr 12, 2019 * Author: dev73 */ #include "VectorHelper.h" #include "StringHelper.h" bool VectorHelper::contiene(std::vector<string> *vec, std::string valor){ if (std::find(vec->begin(), vec->end(), StringHelper::toLower(valor)) != vec->end()){ return true; } else{ return false; } }
[ "rodrigo.sluciano1988@gmail.com" ]
rodrigo.sluciano1988@gmail.com
48b76467e110e111fb084e93618c193837a080be
d001f6e23300a9b1845c890a3ae65c775e93eee0
/RF2Dlg.cpp
cb0aaef3765f72a2b9cb61c1445f4a36c424323c
[]
no_license
JohanVanTol/NHMFLMeasure
7ba15c7900d58cd4797fa8634e213c878f99b9e4
ff5264f7255e223c968158464d7eef2b61a9e210
refs/heads/master
2020-03-28T06:31:28.486519
2018-10-18T15:01:42
2018-10-18T15:01:42
147,841,053
0
0
null
2018-09-10T16:58:33
2018-09-07T15:21:04
C++
UTF-8
C++
false
false
12,403
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include <math.h> #include "RF2Dlg.h" #include "SMB100A.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" extern SMY02* RF2; TRF2Dialog *RF2Dialog; //--------------------------------------------------------------------------- __fastcall TRF2Dialog::TRF2Dialog(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TRF2Dialog::FormActivate(TObject *Sender) { // When the form is activated, we should update all // information from the oscillator GetAllData(); } //--------------------------------------------------------------------------- void __fastcall TRF2Dialog::FMRadioButtonClick(TObject *Sender) { if (FMRadioButton->Checked == true) { FMUnitLabel->Caption = "kHz"; FMExtDCRadioButton->Enabled = true; FMDualDCRadioButton->Enabled = true; } } //--------------------------------------------------------------------------- void __fastcall TRF2Dialog::PMRadioButtonClick(TObject *Sender) { if (PMRadioButton->Checked == true) { FMUnitLabel->Caption = "rad"; if (FMExtDCRadioButton->Checked) FMExtACRadioButton->Checked = true; if (FMDualDCRadioButton->Checked) FMDualACRadioButton->Checked = true; FMExtDCRadioButton->Enabled = false; FMDualDCRadioButton->Enabled = false; } } //--------------------------------------------------------------------------- void __fastcall TRF2Dialog::ErrorButtonClick(TObject *Sender) { char message[60]; int error = RF2->IsError(message, 59); ErrorEdit->Text = message; } //--------------------------------------------------------------------------- int TRF2Dialog::GetAllData() { // SEction Current settings double freq = RF2->GetFreq(); FreqEdit->Text = FloatToStrF(freq, ffFixed, 12,4); double power = RF2->GetPower(); if (power < -140) { PowerEdit->Text = "-120.0"; PowerCheckBox->Checked = false; PowerEdit->Enabled = false; } else { PowerEdit->Text = FloatToStrF(power, ffFixed, 12, 1); PowerEdit->Enabled = true; PowerCheckBox->Checked = true; } double AFfreq = RF2->GetAFfreq(); ModFreqEdit->Text = FloatToStrF(AFfreq, ffFixed, 12, 3); // Section Sweep parameters double StartFreq = RF2->GetStartFreq(); StartFreqEdit->Text = FloatToStrF(StartFreq, ffFixed, 12,3); double StopFreq = RF2->GetStopFreq(); StopFreqEdit->Text = FloatToStrF(StopFreq, ffFixed, 12,3); double Step = RF2->GetStep(); if (Step < 0.001) Step = 0.001; //if Step < 1Hz Step = 1Hz StepEdit->Text = FloatToStrF(Step, ffFixed, 12,3); int NSteps = ceil(1000*(StopFreq-StartFreq)/Step); NStepsEdit->Text = AnsiString(NSteps); /* int Time = RF2->GetStepTime(); DwellEdit->Text = AnsiString(Time); int Sweep = RF2->GetSweepType(); switch (Sweep) { case 1: SweepLabel->Caption = "Sweep ON"; break; case 2: SweepLabel->Caption = "Sweep RESET"; break; default: SweepLabel->Caption = "Sweep OFF"; break; } // Section Modulation double modul = 0.0; int AM = RF2->GetAM(&modul); AMEdit->Enabled = true; AMOffRadioButton->Checked = true; AMEdit->Text = FloatToStrF(modul, ffFixed, 5,1); switch (AM) { case 0: AMEdit->Enabled = false; AMOffRadioButton->Checked = true; break; case 1: AMIntRadioButton->Checked = true; AMEdit->Enabled = true; break; case 2: AMExtAcRadioButton->Checked = true; AMEdit->Enabled = true; break; case 3: AMExtDcRadioButton->Checked = true; AMEdit->Enabled = true; break; case 4: AMDualACRadioButton->Checked = true; AMEdit->Enabled = true; break; case 5: AMDualDCRadioButton->Checked = true; AMEdit->Enabled = true; break; default:AMEdit->Enabled = false; AMOffRadioButton->Enabled = true; break; } int FM = RF2->GetFM(&modul); FMEdit->Enabled = true; FMRadioButton->Checked = true; FMOFFRadioButton->Checked = true; FMEdit->Text = FloatToStrF(modul, ffFixed, 5,1); switch (FM) { case 0: FMEdit->Enabled = false; FMRadioButton->Checked = false; FMOFFRadioButton->Checked = true; break; case 1: FMIntRadioButton->Checked = true; FMEdit->Enabled = true; break; case 2: FMExtACRadioButton->Checked = true; FMEdit->Enabled = true; break; case 3: FMExtDCRadioButton->Checked = true; FMEdit->Enabled = true; break; case 4: FMDualACRadioButton->Checked = true; FMEdit->Enabled = true; break; case 5: FMDualDCRadioButton->Checked = true; FMEdit->Enabled = true; break; default:FMEdit->Enabled = false; FMOFFRadioButton->Enabled = true; FMRadioButton->Checked = false; break; } int PM = RF2->GetPM(&modul); PMRadioButton->Checked = false; if (PM != 0) { FMUnitLabel->Caption = "rad"; FMEdit->Enabled = true; PMRadioButton->Checked = true; FMOFFRadioButton->Checked = true; FMEdit->Text = FloatToStrF(modul, ffFixed, 5,1); if (PM != 0) FMUnitLabel->Caption = "rad"; switch (PM) { case 0: FMEdit->Enabled = false; FMRadioButton->Checked = false; FMOFFRadioButton->Checked = true; break; case 1: FMIntRadioButton->Checked = true; FMEdit->Enabled = true; break; case 2: FMExtACRadioButton->Checked = true; FMEdit->Enabled = true; break; case 3: FMDualACRadioButton->Checked = true; FMEdit->Enabled = true; break; default:FMEdit->Enabled = false; FMOFFRadioButton->Enabled = true; FMRadioButton->Checked = false; break; } } return 0; */ } int TRF2Dialog::SetAllData() { RF2->SetFreq(FreqEdit->Text.ToDouble()); RF2->SetPower(PowerEdit->Text.ToDouble()); RF2->SetAFfreq(ModFreqEdit->Text.ToDouble()); RF2->SetStartFreq(StartFreqEdit->Text.ToDouble()); RF2->SetStopFreq(StopFreqEdit->Text.ToDouble()); RF2->SetStep(StepEdit->Text.ToDouble()); RF2->SetStepTime(DwellEdit->Text.ToInt()); /* int AM = 0; if (AMIntRadioButton->Checked) AM=1; if (AMExtAcRadioButton->Checked) AM=2; if (AMExtDcRadioButton->Checked) AM=3; if (AMDualACRadioButton->Checked) AM=4; if (AMDualDCRadioButton->Checked) AM=5; RF2->SetAM(AM,AMEdit->Text.ToDouble()); int FM = 0; if (FMIntRadioButton->Checked) FM=1; if (FMExtACRadioButton->Checked) FM=2; if (FMExtDCRadioButton->Checked) FM=3; if (FMDualACRadioButton->Checked) FM=4; if (FMDualDCRadioButton->Checked) FM=5; if (FMRadioButton->Checked) RF2->SetFM(FM,FMEdit->Text.ToDouble()); if (PMRadioButton->Checked) RF2->SetPM(FM,FMEdit->Text.ToDouble()); */ } void __fastcall TRF2Dialog::SetButtonClick(TObject *Sender) { SetAllData(); } //--------------------------------------------------------------------------- void __fastcall TRF2Dialog::CalcelButtonClick(TObject *Sender) { Close(); } //--------------------------------------------------------------------------- void __fastcall TRF2Dialog::OKButtonClick(TObject *Sender) { SetAllData(); Close(); } //--------------------------------------------------------------------------- void __fastcall TRF2Dialog::FreqEditChange(TObject *Sender) { try { double test = FreqEdit->Text.ToDouble(); } catch (const EConvertError &E) { FreqEdit->Text = "999.0"; } } //--------------------------------------------------------------------------- void __fastcall TRF2Dialog::AMOffRadioButtonClick(TObject *Sender) { if ( AMOffRadioButton->Checked) AMEdit->Enabled = false; } //--------------------------------------------------------------------------- void __fastcall TRF2Dialog::AMIntRadioButtonClick(TObject *Sender) { if ( AMIntRadioButton->Checked) AMEdit->Enabled = true; } //--------------------------------------------------------------------------- void __fastcall TRF2Dialog::AMExtAcRadioButtonClick(TObject *Sender) { if ( AMExtAcRadioButton->Checked) AMEdit->Enabled = true; } //--------------------------------------------------------------------------- void __fastcall TRF2Dialog::AMExtDcRadioButtonClick(TObject *Sender) { if ( AMExtDcRadioButton->Checked) AMEdit->Enabled = true; } //--------------------------------------------------------------------------- void __fastcall TRF2Dialog::AMDualACRadioButtonClick(TObject *Sender) { if ( AMDualACRadioButton->Checked) AMEdit->Enabled = true; } //--------------------------------------------------------------------------- void __fastcall TRF2Dialog::AMDualDCRadioButtonClick(TObject *Sender) { if ( AMDualDCRadioButton->Checked) AMEdit->Enabled = true; } //--------------------------------------------------------------------------- void __fastcall TRF2Dialog::FMOFFRadioButtonClick(TObject *Sender) { if ( FMOFFRadioButton->Checked) FMEdit->Enabled = false; } //--------------------------------------------------------------------------- void __fastcall TRF2Dialog::FMIntRadioButtonClick(TObject *Sender) { if ( FMIntRadioButton->Checked) FMEdit->Enabled = true; } //--------------------------------------------------------------------------- void __fastcall TRF2Dialog::FMExtACRadioButtonClick(TObject *Sender) { if ( FMExtACRadioButton->Checked) FMEdit->Enabled = true; } //--------------------------------------------------------------------------- void __fastcall TRF2Dialog::FMExtDCRadioButtonClick(TObject *Sender) { if ( FMExtDCRadioButton->Checked) FMEdit->Enabled = true; } //--------------------------------------------------------------------------- void __fastcall TRF2Dialog::FMDualACRadioButtonClick(TObject *Sender) { if ( FMDualACRadioButton->Checked) FMEdit->Enabled = true; } //--------------------------------------------------------------------------- void __fastcall TRF2Dialog::FMDualDCRadioButtonClick(TObject *Sender) { if ( FMDualDCRadioButton->Checked) FMEdit->Enabled = true; } //--------------------------------------------------------------------------- int TRF2Dialog::CalculateNSteps() { double steps = StopFreqEdit->Text.ToDouble()-StartFreqEdit->Text.ToDouble(); if (StepEdit->Text.ToDouble() >0.001) steps /= 0.001*StepEdit->Text.ToDouble(); else steps = 1.0; return ceil(steps); } double TRF2Dialog::CalculateStep() { double step = StopFreqEdit->Text.ToDouble()-StartFreqEdit->Text.ToDouble(); if (NStepsEdit->Text.ToDouble() > 0) step /= 0.001*(NStepsEdit->Text.ToInt()); else step = 1.0; return step; } void __fastcall TRF2Dialog::StartFreqEditExit(TObject *Sender) { NStepsEdit->Text = CalculateNSteps(); } //--------------------------------------------------------------------------- void __fastcall TRF2Dialog::StepEditExit(TObject *Sender) { NStepsEdit->Text = CalculateNSteps(); } //--------------------------------------------------------------------------- void __fastcall TRF2Dialog::StopFreqEditExit(TObject *Sender) { NStepsEdit->Text = CalculateNSteps(); } //--------------------------------------------------------------------------- void __fastcall TRF2Dialog::NStepsEditExit(TObject *Sender) { StepEdit->Text = FloatToStrF(CalculateStep(), ffFixed, 12,3); } //--------------------------------------------------------------------------- void __fastcall TRF2Dialog::SweepStartButtonClick(TObject *Sender) { SetAllData(); RF2->SetSweepType(1); SweepLabel->Caption = "Sweep ON"; } //--------------------------------------------------------------------------- void __fastcall TRF2Dialog::StopSweepButtonClick(TObject *Sender) { RF2->SetSweepType(0); SweepLabel->Caption = "Sweep OFF"; } //--------------------------------------------------------------------------- void __fastcall TRF2Dialog::SweepResetButtonClick(TObject *Sender) { RF2->SetSweepType(2); SweepLabel->Caption = "Sweep RESET"; }
[ "noreply@github.com" ]
JohanVanTol.noreply@github.com
0d7a825b2da17835934b1528662bfc1fc771c9eb
85049d73764926d9d8cbf068504d3cec0abfc85d
/course/cs106b/1176/midterm/p2/student_70.cpp
0349929084bd25ee5f8771796310d0a632437f07
[]
no_license
tofergregg/CodeReview
a13f3ff30e586d11d63f2c02246bb6ca1206a4fa
5fc04c818b017b30466ac53e5b1be1d8ef9336a3
refs/heads/master
2021-01-21T07:00:42.726665
2018-06-10T00:43:50
2018-06-10T00:43:50
91,594,286
0
0
null
2017-07-24T05:04:33
2017-05-17T15:52:14
C++
UTF-8
C++
false
false
1,504
cpp
string decode(string seq) { int min = 1; while(seq.size()!=0) { if(seq[0]='I') { Queue<int> solution; solution.enqueue(min); } else { Stack<int> solution; solution.push(min); } } } I give up. This problem is retardedly hard. there is some obvious thing I am not seeing i know 100% how stacks and queues work but I still cant figure this out I feel like a double-ended queue would help but we don't have that example: IIIIIIID should be 234567891 how am I supposed to know, when at the first I, that I need to begin with a 2 instead of a 1. Maybe I use a queue, and I pile up 1-8 for all the Is, then when I see the D take the 1 from the front of the queue and use it. But then consider the example DDDDDDDI which should be 876543219. THe only way to maintain this is with a stack. i.e. I start with 1 and for every D keep adding to the top until I get to 8 and then use the remaining 9 for the I. It makes no sense to me I can either use a stack OR a queue but not both. I thought about this problem for 45 minutes and have no work to show except these thoughts. Maybe if I encounter an I I use a queue and if I encounter a D I use a stack and mantain each respective container until I run out of Is or Ds and switch to the other. But then I don't understand how to retroactively fix previously generated numbers in O(n) time. I think you have to use a stack or a queue depending on the first character, but I am literally out of time at this point and cannot implement a solution.
[ "tofergregg@gmail.com" ]
tofergregg@gmail.com
3f4694f690c492589c35e8eefa55aa300c672c7a
99e578a2e5b42ba1540683ce1e0497537267858b
/src/base/track.cc
6570ba63c3c8f18158fe532a07badb684d1bbd8c
[ "BSD-3-Clause" ]
permissive
ThakurSarveshGit/privacy_preserving_sfm
ffa551e086c30620b6b66a20e50b0d65aab1cf93
c2f1e8a58251eae5af7eba7ede3f15534f944f1a
refs/heads/master
2023-06-03T20:45:45.294563
2021-06-09T07:33:25
2021-06-09T07:33:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,513
cc
// Copyright (c) 2020, ETH Zurich and UNC Chapel Hill. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of ETH Zurich and UNC Chapel Hill nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Authors: Johannes L. Schoenberger (jsch-at-demuc-dot-de) // Viktor Larsson (viktor.larsson@inf.ethz.ch) // Marcel Geppert (marcel.geppert@inf.ethz.ch) #include "base/track.h" namespace colmap { Track::Track() {} TrackElement::TrackElement() : image_id(kInvalidImageId), line_idx(kInvalidLineIdx) {} TrackElement::TrackElement(const image_t image_id, const point2D_t line_idx) : image_id(image_id), line_idx(line_idx) {} void Track::DeleteElement(const image_t image_id, const point2D_t line_idx) { elements_.erase( std::remove_if(elements_.begin(), elements_.end(), [image_id, line_idx](const TrackElement& element) { return element.image_id == image_id && element.line_idx == line_idx; }), elements_.end()); } } // namespace colmap
[ "marcel.geppert@inf.ethz.ch" ]
marcel.geppert@inf.ethz.ch
5bb53334518deefcfcc547c724ee4adb5b438194
6bdeefa16065fcad160c47c188c3de44ecaea6aa
/Codeforces/1037/G/b.cpp
8e83fae07805a2cdf2403dc3818015ab05316d43
[]
no_license
DolaBMOon/CodeerStf
6fdbe830cab3d4e23035537ce0cbb6ef8d3a89cb
3ee7b66e1c28c48fae72a5f65a9b8270c41127da
refs/heads/master
2021-09-25T16:27:51.952473
2018-10-24T06:35:20
2018-10-24T06:35:20
146,592,777
0
0
null
null
null
null
UTF-8
C++
false
false
3,181
cpp
#include<iostream> #include<algorithm> #include<cstdio> #include<cstring> #include<cassert> #include<vector> #include<unordered_map> using namespace std; #define Whats(x) cout<<#x<<" is "<<(x)<<endl #define DivHim() cout<<">>>>>>>>>>>>>>>"<<endl #define DivHer() cout<<"<<<<<<<<<<<<<<<"<<endl #define Oops() cout<<"!!!!!!!!!!!!!!!"<<endl /* -<Unlimited Blade Works>- */ #define Pir pair<int,int> #define fir first #define sec second const int N=1e5+10; const int ALPHA=27; const int MAXSG=30; char s[N]; int id[N],n,m; int ed[ALPHA][ALPHA],np[N][ALPHA],sgsm[ALPHA][N],pre[N][ALPHA],nxt[N][ALPHA]; vector<int> p[ALPHA][ALPHA],rp[ALPHA][ALPHA],sg[ALPHA][ALPHA]; void Append(int x,int y,int l,int r) { int nw=++ed[x][y]; if(nw==1) { p[x][y].emplace_back(0); rp[x][y].emplace_back(0); sg[x][y].emplace_back(0); } p[x][y].emplace_back(l); rp[x][y].emplace_back(r); np[l][y]=nw; sg[x][y].emplace_back(-1); } unordered_map<int,int> memo[N]; int GetAns(int l,int r) { if(l==r) return 1; if(l>r) return 0; if(memo[l].count(r)) return memo[l][r]; int &res=memo[l][r]; int x=id[l-1],y=id[r+1],t; if((t=np[l-1][y])&&rp[x][y][t]==r+1) return res=sg[x][y][t]; bool vis[MAXSG]={false}; for(int i=1,il,ir,w;i<ALPHA;++i)if((il=nxt[l-1][i])&&il<=r) { ir=pre[r+1][i]; if(!np[ir][i]&&il!=ir) np[ir][i]=np[pre[ir][i]][i]+1; w=GetAns(l,il-1)^GetAns(ir+1,r)^sgsm[i][np[ir][i]-1]^sgsm[i][np[il][i]-1]; vis[w]=true; for(;vis[res];++res); } return res; } void Fix(int x,int y,int rk) { int &res=sg[x][y][rk]; if(~res) return; int l=p[x][y][rk]+1,r=rp[x][y][rk]-1; if(l==r) return (void)(res=1); else if(l>r) return (void)(res=0); bool vis[MAXSG]={false}; memset(vis,0,sizeof vis); res=0; for(int i=1,il,ir,w,t;i<ALPHA;++i)if((il=nxt[l-1][i])&&il<=r) { w=0; ir=pre[r+1][i]; if(l!=il) { t=np[l-1][i]; Fix(x,i,t); w^=sg[x][i][t]; } if(r!=ir) { t=np[ir][y]; Fix(i,y,t); w^=sg[i][y][t]; } if(!np[ir][i]&&il!=ir) np[ir][i]=np[pre[ir][i]][i]+1; for(int j=np[il][i],jj=np[ir][i];j<jj;++j) { Fix(i,i,j); w^=sg[i][i][j]; } vis[w]=true; for(;vis[res];++res); } } void Prework() { for(int i=1;i<=n;++i) id[i]=s[i]-'a'+1; for(int i=1;i<ALPHA;++i) for(int j=1;j<ALPHA;++j) for(int k=1,l=0;k<=n;++k) { if(l&&id[k]==j) { Append(i,j,l,k); l=0; } if(id[k]==i) l=k; } for(int i=1;i<=n;++i) if(!ed[0][id[i]]) Append(0,id[i],0,i); for(int i=n;i>=1;--i) if(!ed[id[i]][0]) Append(id[i],0,i,n+1); for(int i=2;i<=n+1;++i) { for(int j=1;j<ALPHA;++j) pre[i][j]=pre[i-1][j]; pre[i][id[i-1]]=i-1; } for(int i=n-1;i>=0;--i) { for(int j=1;j<ALPHA;++j) nxt[i][j]=nxt[i+1][j]; nxt[i][id[i+1]]=i+1; } for(int i=0;i<ALPHA;++i) for(int j=0;j<ALPHA;++j)if(i||j) for(int k=1,kk=ed[i][j];k<=kk;++k) Fix(i,j,k); for(int i=1,*s;i<ALPHA;++i) { vector<int> &a=sg[i][i]; s=sgsm[i]; for(int j=1,jj=ed[i][i];j<=jj;++j) s[j]=s[j-1]^a[j]; } } int main() { scanf("%s%d",s+1,&m); n=strlen(s+1); Prework(); for(int i=1,l,r;i<=m;++i) { scanf("%d%d",&l,&r); puts(GetAns(l,r)?"Alice":"Bob"); } return 0; }
[ "dolabmoon@gmali.com" ]
dolabmoon@gmali.com
34483e5efaae0f464e494d6d232b289c88a1d550
ef057bfab67839f83a95608f94877c630953093a
/Animations.cpp
c13547f1ca3b335940053106363f2e7026313fce
[]
no_license
henry-dv/Animations
d617e4ae16668958a3aa8fc7f4c91c2ddc8e17d8
723b7547e9bc48c943ddfc3f6d951ccc7bed9a5c
refs/heads/master
2023-02-11T01:34:23.186419
2021-01-02T19:22:42
2021-01-02T19:22:42
326,255,025
0
0
null
null
null
null
UTF-8
C++
false
false
2,005
cpp
/* Animations.cpp - Fancy animations for an Adafruit_NeoPixel strip. Created by Henry Lehmann, December 30, 2020. Released into the public domain. */ #include "Arduino.h" #include "Colors.h" #include "Animations.h" Animations::Animations(Adafruit_NeoPixel* strip) { this->strip = strip; e_MyAnimation = e_breathe; myAnimation = breathe; myColor = colors.RED; } void Animations::nextFrame(unsigned long ticks) { myAnimation(ticks); } void Animations::cycleAnimation() { setAnimation((E_Animations)((this->e_MyAnimation + 1) % ANIMATION_COUNT)); } E_Animations Animations::getAnimation() { return this->e_MyAnimation; } void Animations::setAnimation(E_Animations newAnimation) { this->e_MyAnimation = newAnimation; switch (this->e_MyAnimation) { case e_breathe: myAnimation = breathe; break; case e_christmasTime: myAnimation = christmasTime; break; case e_plainColor: myAnimation = plainColor; break; case e_strobo: myAnimation = strobo; break; default: break; } } uint32_t Animations::getColor() { return this->myColor; } void Animations::setColor(uint32_t newColor) { this->myColor = newColor; } //-------Actual Animations------- void Animations::breathe(unsigned long ticks) { unsigned int myticks = ticks >> 4; if ((myticks / 256) % 2 == 0) strip.fill(colors.hsbToRgb(195, 255, myticks % 256)); else strip.fill(colors.hsbToRgb(195, 255, 255 - (myticks % 256))); } void Animations::christmasTime(unsigned long ticks) { unsigned short myticks = ticks >> 10; for (int i = 0; i < LED_COUNT; i++) { if ((i + myticks) % 2 == 0) { strip.setPixelColor(i, colors.RED); } else { strip.setPixelColor(i, colors.GREEN); } } } void Animations::plainColor(unsigned long ticks) { strip.fill(myColor); } void Animations::strobo(unsigned long ticks) { unsigned short myticks = ticks >> 6; if (myticks % 2 == 0) strip.fill(colors.WHITE); else strip.clear(); }
[ "34438247+henry-dv@users.noreply.github.com" ]
34438247+henry-dv@users.noreply.github.com
6f8b08e7802cd14b3056be1217c407ea6982f40e
87ef03375ec4a32b7defdbdb1fbd1ed8dbb4dcbd
/Hcv/LocHist/ImgDataGradMgr_LocHist.h
b02047271d2f2de976a04d71909736edbba90537
[]
no_license
Haytham-Magdi/CppLib
192fb2008907c3d0ae2bb34bb8c066c1d86a4c6f
c8a1ba6bca656574196ba19a75c1cbdc4b829b7c
refs/heads/master
2020-09-20T10:54:57.022052
2017-01-23T05:27:52
2017-01-23T05:27:52
66,259,819
0
0
null
null
null
null
UTF-8
C++
false
false
2,721
h
#pragma once #include <Lib\Cpp\Common\commonLib.h> #include <Lib\Cpp\Math\mathLib.h> #include <Lib\Hcv\CvIncludes.h> #include <Lib\Hcv\Types.h> #include <Lib\Hcv\error.h> #include <vector> #include <Lib\Hcv\Channel.h> #include <Lib\Hcv\Image.h> #include <Lib\Hcv\IImgDataGradMgr.h> #include <Lib\Hcv\LocHist\ImgDataMgr_2_LocHist.h> namespace Hcv { //using namespace Hcpl::Math; class ImgDataGradMgr_LocHist_Factory : public IImgDataGradMgr_Factory { public: virtual IImgDataGradMgr * CreateImgDataGradMgr( IImgDataMgr_2Ref a_imgData, ImageNbrMgrRef a_nbrMgr ); }; typedef Hcpl::ObjRef< ImgDataGradMgr_LocHist_Factory > ImgDataGradMgr_LocHist_FactoryRef; class ImgDataGradMgr_LocHist : public IImgDataGradMgr { public: ImgDataGradMgr_LocHist( IImgDataMgr_2Ref a_imgData, ImageNbrMgrRef a_nbrMgr ); virtual IImgDataMgr_2Ref GetSrcImgDataMgr() { return m_imgDataMgr; } virtual F32ImageRef GetGradImg_H() { return m_gradImg_H; } virtual F32ImageRef GetGradImg_V() { return m_gradImg_V; } virtual F32ImageRef GetConflictImg_H() { ThrowHcvException(); return NULL; } virtual F32ImageRef GetConflictImg_V() { ThrowHcvException(); return NULL; } virtual ImageNbrMgrRef GetNbrMgr() { return m_nbrMgr; } virtual int GetAprSiz() { return m_nAprSiz; } virtual F32ImageRef GetGradImg_ByNormIdx( int a_nNormIdx ); virtual F32ImageRef GetConfImg_ByNormIdx( int a_nNormIdx ); virtual float GetMaxDif() { return S_GetMaxDif(); } static float S_GetMaxDif() { return 550; } protected: void PrepareData(); void PrepareSharpStuff(); float CalcDif( int a_nIdx_1, int a_nIdx_2 ); F32ImageRef GenGradImg( FixedVector< ImageNbrMgr::PixIndexNbr > & a_rNbrArr ); float CalcConf( int a_nIdx_E, int a_nIdx_1, int a_nIdx_2 ); F32ImageRef GenConfImg( FixedVector< ImageNbrMgr::PixIndexNbr > & a_rNbrArr ); protected: IImgDataMgr_2Ref m_imgDataMgr; F32ImageRef m_srcMeanImg; F32ColorVal * m_srcMean_Buf; F32ImageRef m_srcStanDevImg; float * m_srcStanDev_Buf; F32ImageRef m_srcAvgSqrMagImg; float * m_srcAvgMagSqr_Buf; ImgDataMgr_2_LocHist * m_pDataMgr_LH; Hcpl::CommonArrCollBuff< ImgDataSrc_LocHist::ClustShare > * m_pPixShareArrColl_Tot; ImgDataSrc_LocHist::ClustHisto * m_pClustHisto; F32ImageRef m_gradImg_H; F32ImageRef m_gradImg_V; float * m_conf_Sharp_Buf; F32ImageRef m_confImg_H; F32ImageRef m_confImg_V; ImageNbrMgrRef m_nbrMgr; int m_nAprSiz; bool m_bSrcExDataDone; IImgDataMgr_2Ref m_sharp_IDM; IImgDataGradMgrRef m_sharp_GM; }; typedef Hcpl::ObjRef< ImgDataGradMgr_LocHist > ImgDataGradMgr_LocHistRef; }
[ "haytham.magdi@hotmail.com" ]
haytham.magdi@hotmail.com
81710e3803eb8eba46dd8947c905b3a3412d3139
e4f90ba52e0f85412a372ca1f0e073f1b8bce1af
/DSA/DSAttractors.cpp
c8b3820dd3a93c8179c158dc4d6a2f2287877a5d
[]
no_license
3bab/DSAttractors
a68f0f21e2a02fc75980a754dc94d2ec20a148b1
2292decde7affa1e26931111074b5a4729ee6f8e
refs/heads/master
2023-08-13T06:42:29.137062
2021-10-05T09:56:37
2021-10-05T09:56:37
295,835,007
0
0
null
null
null
null
UTF-8
C++
false
false
22,269
cpp
#include "DSAttractors.h" using namespace sf; using namespace std; DSAttractors::DSAttractors() { setupText(); view.setCenter(Vector2f(0.0f, 0.0f)); view.setSize(Vector2f(static_cast<float>(screenWidth / 10), static_cast<float>(screenHeight / 10))); attractorConfig = { {10.0f, 30.0f, 8 / 3}, {1.24f, 1.1f, 4.4f, 3.21f}, {0.95f, 0.7f, 0.6f, 3.5f, 0.25f, 0.1f}, {0.3f, 1.0f}, {5.0f, -10.0f, -0.38f}, {1.4f}, {0.001f, 0.2f, 1.1f}, {0.4f, 0.175f}, {1.5f}, {0.2f} }; colours = { Color(115, 62, 101, 42), // 42 Color(255, 126, 210, 127), Color(109, 193, 202, 179), Color(135, 216, 10, 203), Color(125, 26, 133, 99), Color(8, 161, 163, 57), Color(134, 184, 38, 183), Color(132, 159, 149, 188), Color(100, 195, 167, 160), Color(190, 242, 126, 252), }; trailColoursParams = { {61.3f, 62.1f, 33.9f}, {-65.5125f, -27.8521f, -97.0907f}, {-47.3382f, -49.5409f, -33.8347f}, {-12.9346f, -76.7609f, 70.7356f}, {-12.0673f, 51.6949f, 97.4566f}, {93.4094f, -16.196f, 40.8949f}, {-37.5288f, -31.3912f, -48.0061f}, {-5.6245f, -49.0192f, 19.271f}, {98.011f, -81.8857f, -80.084f}, {44.3435f, -93.5679f, -52.0752f}, }; cout << "\n\n\n"; for (unsigned c = 0; c < colours.size(); c++) { cout << static_cast<int>(colours[c].r) << " " << static_cast<int>(colours[c].g) << " " << static_cast<int>(colours[c].b) << " " << static_cast<int>(colours[c].a) << endl; cout << trailColoursParams[c][0] << " " << trailColoursParams[c][1] << " " << trailColoursParams[c][2] << endl; } circle.resize(numPoints); point.resize(numPoints); trail.resize(numPoints); // Create trial trackers for (unsigned i = 0; i < numPoints; i++) { j.push_back(0); } createBalls(); // Create lineStrip object with two vertices. The first line should start with a first point. line.setPrimitiveType(LinesStrip); line.append(Vector2f(point[0].x, point[0].y)); line.append(Vector2f(point[0].x, point[0].y)); initiateCamera(); } void DSAttractors::initiateCamera() {// Set Camera switch (attractorIndex) { case 0: { camPosition = {0, 0, -50}; camAngle = {0, 0, 0}; break; } case 1: { camPosition = {1.07676f, 0.3f, -0.447995f}; camAngle = {0.1f, 4.84f, 0.0f}; break; } case 2: { camPosition = {2.25, 0, 0.75}; camAngle = {0, -PI / 2, 0}; break; } case 3: { camPosition = {-7.5, 5, -15}; camAngle = {0, PI / 6, 0}; break; } case 4: { camPosition = {51.310f, -4.8f, 25.151f}; camAngle = {-0.16f, -2.1f, 0.0f}; break; } case 5: { camPosition = {-23.357f, -16.4f, -20.731f}; camAngle = {-0.5f, -5.48f, 0.0f}; break; } case 6: { camPosition = {1.0216f, -5.7f, 6.1861f}; camAngle = {-0.16f, 3.34f, 0.0f}; break; } case 7: { camPosition = {0, 0, -0.5}; camAngle = {0, 0, -0.134f}; break; } case 8: { camPosition = {-0.14397f, -8.4f, -1.3497f}; camAngle = {-1.66f, -2.94f, 0}; break; } case 9: { camPosition = {7.1565f, 4.2f, 2.6844f}; camAngle = {0.48f, -1.92f, 0}; break; } } } void DSAttractors::createBalls() { for (unsigned i = 0; i < numPoints; i++) { // Create balls circle[i].setRadius(0.5f); circle[i].setOrigin(circle[i].getRadius(), circle[i].getRadius()); circle[i].setFillColor(colours[attractorIndex]); // Set initial positions point[i] = {getRandomNumber(1.0f, 1.0f), getRandomNumber(1.0f, 1.0f), getRandomNumber(1.0f, 1.0f)}; // Create trails trail[i].resize(trailLength); for (auto &pos : trail[i]) { pos = point[i]; } } } void DSAttractors::setupText() { font.loadFromFile("/Users/gintas.palionis/CLionProjects/DSAttractors/arial.ttf"); text.setFont(font); text.setFillColor(Color(100, 0, 0, 255)); text.setString(attractorNames[attractorIndex]); text.setScale(0.1f, 0.1f); text.setPosition(Vector2f(-85, -45)); text.setStyle(0); } void DSAttractors::input(RenderWindow &window) { while (window.pollEvent(event)) { // Window if (Keyboard::isKeyPressed(Keyboard::Escape)) endSubProgram = true; if (Keyboard::isKeyPressed(Keyboard::F)) { isFullscreen = !isFullscreen; window.create(VideoMode(static_cast<int>(screenWidth), static_cast<int>(screenHeight)), "Coding Projects", (isFullscreen ? Style::Fullscreen : Style::Default), ContextSettings()); window.setPosition(Vector2i(0, 0)); window.setVerticalSyncEnabled(true); window.setFramerateLimit(60); } if ((Keyboard::isKeyPressed(Keyboard::H) || Keyboard::isKeyPressed(Keyboard::G)) && inputTimer >= 0.1) { inputTimer = 0; if (Keyboard::isKeyPressed(Keyboard::H)) { attractorIndex++; if (attractorIndex == attractorConfig.size()) attractorIndex--; } else { attractorIndex--; if (attractorIndex == -1) attractorIndex++; } switch (attractorIndex) { case 0: { camPosition = {0, 0, -50}; camAngle = {0, 0, 0}; break; } case 1: { camPosition = {1.07676f, 0.3f, -0.447995f}; camAngle = {0.1f, 4.84f, 0.0f}; break; } case 2: { camPosition = {2.25, 0, 0.75}; camAngle = {0, -PI / 2, 0}; break; } case 3: { camPosition = {-7.5, 5, -15}; camAngle = {0, PI / 6, 0}; break; } case 4: { camPosition = {51.310f, -4.8f, 25.151f}; camAngle = {-0.16f, -2.1f, 0}; break; } case 5: { camPosition = {-23.357f, -16.4f, -20.731f}; camAngle = {-0.5f, -5.48f, 0.0f}; break; } case 6: { camPosition = {1.0216f, -5.7f, 6.1861f}; camAngle = {-0.16f, 3.34f, 0.0f}; break; } case 7: { camPosition = {0, 0, -0.5}; camAngle = {0, 0, 0}; break; } case 8: { camPosition = {-0.1439f, -8.4f, -1.3497f}; camAngle = {-1.66f, -2.94f, 0}; break; } case 9: { camPosition = {7.1565f, 4.2f, 2.6844f}; camAngle = {0.48f, -1.92f, 0}; break; } } const float max = 0.001f; const float min = -max; for (unsigned i = 0; i < numPoints; i++) { circle[i].setFillColor(colours[attractorIndex]); point[i] = {getRandomNumber(min, max), getRandomNumber(min, max), getRandomNumber(min, max)}; } for (unsigned i = 0; i < numPoints; i++) { for (auto &pos : trail[i]) pos = point[i]; } text.setString(attractorNames[attractorIndex]); } } } void DSAttractors::update() { /// Calculate timeStep timeStep = clock.getElapsedTime().asSeconds(); inputTimer += timeStep; clock.restart(); timeStep *= speed; // Slow down or speed up time. // Update position according to chosen equation attractorIndex vector<float> &attractorParams = attractorConfig.at(attractorIndex); switch (attractorIndex) { case 0: { for (unsigned i = 0; i < numPoints; i++) { point[i].x += static_cast<float>(attractorParams[0] * (point[i].y - point[i].x) * timeStep); point[i].y += static_cast<float>((point[i].x * (attractorParams[1] - point[i].z) - point[i].y) * timeStep); point[i].z += static_cast<float>((point[i].x * point[i].y - attractorParams[2] * point[i].z) * timeStep); } break; } case 1: { for (unsigned i = 0; i < numPoints; i++) { float h1 = 0.5f * (abs(point[i].x + 1) - abs(point[i].x - 1)); float h2 = 0.5f * (abs(point[i].y + 1) - abs(point[i].y - 1)); float h3 = 0.5f * (abs(point[i].z + 1) - abs(point[i].z - 1)); point[i].x += static_cast<float>( (-point[i].x + attractorParams[0] * h1 - attractorParams[3] * h2 - attractorParams[3] * h3) * timeStep); point[i].y += static_cast<float>( (-point[i].y - attractorParams[3] * h1 + attractorParams[1] * h2 - attractorParams[2] * h3) * timeStep); point[i].z += static_cast<float>( (-point[i].z - attractorParams[3] * h1 + attractorParams[2] * h2 + h3) * timeStep); } break; } case 2: { for (unsigned i = 0; i < numPoints; i++) { point[i].x += static_cast<float>( ((point[i].z - attractorParams[1]) * point[i].x - attractorParams[3] * point[i].y) * timeStep); point[i].y += static_cast<float>( (attractorParams[3] * point[i].x + (point[i].z - attractorParams[1]) * point[i].y) * timeStep); point[i].z += static_cast<float>( (attractorParams[2] + attractorParams[0] * point[i].z - (point[i].z * point[i].z * point[i].z) / 3 - (point[i].x * point[i].x + point[i].y * point[i].y) * (1 + attractorParams[4] * point[i].z) + attractorParams[5] * point[i].z * point[i].x * point[i].x * point[i].x) * timeStep); } break; } case 3: { for (unsigned i = 0; i < numPoints; i++) { point[i].x += static_cast<float>((point[i].x * (4 - point[i].y) + attractorParams[0] * point[i].z) * timeStep); point[i].y += static_cast<float>((-point[i].y * (1 - point[i].x * point[i].x)) * timeStep); point[i].z += static_cast<float>( (-point[i].x * (1.5 - point[i].z * attractorParams[1]) - 0.05 * point[i].z) * timeStep); } break; } case 4: { for (unsigned i = 0; i < numPoints; i++) { point[i].x += static_cast<float>((attractorParams[0] * point[i].x - point[i].y * point[i].z) * timeStep * 0.25f); point[i].y += static_cast<float>((attractorParams[1] * point[i].y + point[i].x * point[i].z) * timeStep * 0.25f); point[i].z += static_cast<float>((attractorParams[2] * point[i].z + point[i].x * point[i].y / 3) * timeStep * 0.25f); } break; } case 5: { for (unsigned i = 0; i < numPoints; i++) { point[i].x += static_cast<float>( (-attractorParams[0] * point[i].x - 4 * point[i].y - 4 * point[i].z - point[i].y * point[i].y) * timeStep); point[i].y += static_cast<float>( (-attractorParams[0] * point[i].y - 4 * point[i].z - 4 * point[i].x - point[i].z * point[i].z) * timeStep); point[i].z += static_cast<float>( (-attractorParams[0] * point[i].z - 4 * point[i].x - 4 * point[i].y - point[i].x * point[i].x) * timeStep); } break; } case 6: { for (unsigned i = 0; i < numPoints; i++) { point[i].x += static_cast<float>( ((1 / attractorParams[1] - attractorParams[0]) * point[i].x + point[i].z + point[i].x * point[i].y) * timeStep); point[i].y += static_cast<float>((-attractorParams[1] * point[i].y - point[i].x * point[i].x) * timeStep); point[i].z += static_cast<float>((-point[i].x - attractorParams[2] * point[i].z) * timeStep); } break; } case 7: { for (unsigned i = 0; i < numPoints; i++) { point[i].x += static_cast<float>( (-attractorParams[0] * point[i].x + point[i].y + 10.0f * point[i].y * point[i].z) * timeStep); point[i].y += static_cast<float>((-point[i].x - 0.4 * point[i].y + 5.0f * point[i].x * point[i].z) * timeStep); point[i].z += static_cast<float>((attractorParams[1] * point[i].z - 5.0f * point[i].x * point[i].y) * timeStep); } break; } case 8: { for (unsigned i = 0; i < numPoints; i++) { point[i].x += static_cast<float>((point[i].y) * timeStep); point[i].y += static_cast<float>((-point[i].x + point[i].y * point[i].z) * timeStep); point[i].z += static_cast<float>((attractorParams[0] - point[i].y * point[i].y) * timeStep); } break; } case 9: { for (unsigned i = 0; i < numPoints; i++) { point[i].x += static_cast<float>((-attractorParams[0] * point[i].x + sin(point[i].y)) * timeStep); point[i].y += static_cast<float>((-attractorParams[0] * point[i].y + sin(point[i].z)) * timeStep); point[i].z += static_cast<float>((-attractorParams[0] * point[i].z + sin(point[i].x)) * timeStep); } break; } } // Move Left and Right if (Keyboard::isKeyPressed(Keyboard::A)) { camPosition.x -= sin(camAngle[1] + PI / 2.0f) * 0.25f; camPosition.z -= cos(camAngle[1] + PI / 2.0f) * 0.25f; } if (Keyboard::isKeyPressed(Keyboard::D)) { camPosition.x += sin(camAngle[1] + PI / 2.0f) * 0.25f; camPosition.z += cos(camAngle[1] + PI / 2.0f) * 0.25f; } // Move Forwards and Backwards if (Keyboard::isKeyPressed(Keyboard::S)) { camPosition.z -= cos(camAngle[1]) * 0.25f; camPosition.x -= sin(camAngle[1]) * 0.25f; } if (Keyboard::isKeyPressed(Keyboard::W)) { camPosition.z += cos(camAngle[1]) * 0.25f; camPosition.x += sin(camAngle[1]) * 0.25f; } // Move Up and Down if (Keyboard::isKeyPressed(Keyboard::LShift)) camPosition.y += 0.1f; if (Keyboard::isKeyPressed(Keyboard::Space)) camPosition.y -= 0.1f; /// Update Camera Angle // Look Left and Right if (Keyboard::isKeyPressed(Keyboard::Left)) camAngle[1] -= 0.003f; if (Keyboard::isKeyPressed(Keyboard::Right)) camAngle[1] += 0.003f; // Look Up and Down if (Keyboard::isKeyPressed(Keyboard::Up)) camAngle[0] += 0.003f; if (Keyboard::isKeyPressed(Keyboard::Down)) camAngle[0] -= 0.003f; /// Compute Rotation Matrixes rotMatrixX = { {1, 0, 0}, {0, cos(camAngle[0]), sin(camAngle[0])}, {0, -sin(camAngle[0]), cos(camAngle[0])} }; rotMatrixY = { {cos(camAngle[1]), 0, -sin(camAngle[1])}, {0, 1, 0}, {sin(camAngle[1]), 0, cos(camAngle[1])} }; rotMatrixZ = { {cos(camAngle[2]), sin(camAngle[2]), 0}, {-sin(camAngle[2]), cos(camAngle[2]), 0}, {0, 0, 1} }; // Change speed if (Keyboard::isKeyPressed(Keyboard::PageUp)) speed += 0.025f; if (Keyboard::isKeyPressed(Keyboard::PageDown)) speed -= 0.025f; } void DSAttractors::draw(RenderWindow &window) { // For every point for (unsigned g = 0; g < numPoints; g++) { /// Draw circle // Projection maths Vector3f d; d = point[g] - camPosition; d = rotMatrixX * (rotMatrixY * (rotMatrixZ * d)); // Only if the point is infront of the camera if (d.z >= 0) { projectedPoint = { displayPosition.z * d.x / d.z + displayPosition.x, displayPosition.z * d.y / d.z + displayPosition.y }; circle[g].setPosition(Vector2f(projectedPoint.x, projectedPoint.y)); window.draw(circle[g]); } /// Draw trail /* The point of this algorithm is to use indexes in a clever manner in order to avoid shifting every previous position one across in "trail" every frame, which takes a lot of time. It flows like a "shifting" >for< loop. */ trail[g][j[g]] = point[g]; // Add most recent position to trail at index j[g] j[g]++; // j[g] incremented every frame, shifting the beginning of the for loop. if (j[g] == trail[g].size() - 1) { // If j[g] gets to the final index, set it to 0 j[g] = 0; trail[g][trail[g].size() - 1] = trail[g][trail[g].size() - 2]; // This has to be done. } int k = 0; // Index that goes from 0 to numPoints, used for colour // Starting from the index i right after j[g], then from 0 all the way to j[g]. int i = j[g] + 1; while (i != j[g]) { // Project the front end of the trail Vector3f d1; d1 = trail[g][i] - camPosition; d1 = rotMatrixX * (rotMatrixY * (rotMatrixZ * d1)); Vector2f proj1; proj1 = {displayPosition.z * d1.x / d1.z + displayPosition.x, displayPosition.z * d1.y / d1.z + displayPosition.y}; line[0].position = proj1; // Project the back end of the trail Vector3f d2; if (i == 0) d2 = trail[g][trail[g].size() - 2] - camPosition; else d2 = trail[g][i - 1] - camPosition; d2 = rotMatrixX * (rotMatrixY * (rotMatrixZ * d2)); Vector2f proj2; proj2 = {displayPosition.z * d2.x / d2.z + displayPosition.x, displayPosition.z * d2.y / d2.z + displayPosition.y}; line[1].position = proj2; // Calculate trail colours Color fade; fade = Color( clamp(colours[attractorIndex].r + trailColoursParams[attractorIndex][0] * Magnitude(line[1].position - line[0].position)), clamp(colours[attractorIndex].g + trailColoursParams[attractorIndex][1] * Magnitude(line[1].position - line[0].position)), clamp(colours[attractorIndex].b + trailColoursParams[attractorIndex][2] * Magnitude(line[1].position - line[0].position)), 0 + static_cast<Uint8>((k * 255 / trail[g].size()))); line[0].color = fade; line[1].color = fade; // Draw if both the front and end of the trail are in front of the camera if (d1.z >= 0 && d2.z >= 0) window.draw(line); // Increment counters i++; if (i == trail[g].size()) // Set i to 0 once it gets to the end of "trail" i = 0; k++; } } text.setString(attractorNames[attractorIndex]); text.setScale(0.1f, 0.1f); text.setPosition(Vector2f(-85, -45)); window.draw(text); /// UNCOMMENT FOR ON-SCREEN COORDINATES /* for (unsigned i = 0; i < numPoints; i++) { string coordinate_string = "(" + to_string(static_cast<int>(point[i].x)) + ", " + to_string(static_cast<int>(point[i].y)) + ", " + to_string(static_cast<int>(point[i].z)) + ")"; text.setString(coordinate_string); text.setPosition(circle[i].getPosition() + Vector2f(1.0f, -5.0f)); window.draw(text); } */ window.display(); window.clear(Color(0, 0, 0, 255)); } void DSAttractors::run(RenderWindow &window) { window.setView(view); while (window.isOpen() && !endSubProgram) { this->input(window); // Get Input this->update(); // Update Graphics this->draw(window); // Draw Graphics } window.setView(View(Vector2f(static_cast<float>(screenWidth / 2), static_cast<float>(screenHeight / 2)), Vector2f(static_cast<float>(screenWidth), static_cast<float>(screenHeight)))); } DSAttractors::~DSAttractors() {}
[ "gintas.palionis@gmail.com" ]
gintas.palionis@gmail.com
b24c6649ce457c9828ea65170ede2780c4b8d4e1
666765fbc0275e8dd38580ba7911b199b74c7d2c
/tests/UnitTests/TestTransfersSubscription.cpp
32c0c2681cdc2928eb6a718b34426e4f0e28e59d
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
nixtechie49/4xbitcoin
66b579580662db6280836eb0b02068e0b5b9fe5c
a92535b8f04d56705aaf82581200870823deef5b
refs/heads/master
2020-04-28T18:31:26.314639
2019-03-13T19:29:58
2019-03-13T19:29:58
175,481,543
0
0
null
2019-03-13T18:58:06
2019-03-13T18:58:05
null
UTF-8
C++
false
false
4,876
cpp
/* * Copyright (c) 2018-2019, The Mybtcfx Developers. * Portions Copyright (c) 2012-2017, The CryptoNote Developers, The Bytecoin Developers. * * This file is part of 4xBIT. * * This file is subject to the terms and conditions defined in the * file 'LICENSE', which is part of this source code package. */ #include "gtest/gtest.h" #include <tuple> #include "CryptoNoteCore/TransactionApi.h" #include "Logging/ConsoleLogger.h" #include "Transfers/TransfersSubscription.h" #include "Transfers/TypeHelpers.h" #include "ITransfersContainer.h" #include "TransactionApiHelpers.h" #include "TransfersObserver.h" using namespace CryptoNote; namespace { const uint32_t UNCONFIRMED_TRANSACTION_HEIGHT = std::numeric_limits<uint32_t>::max(); const uint32_t UNCONFIRMED = std::numeric_limits<uint32_t>::max(); std::error_code createError() { return std::make_error_code(std::errc::invalid_argument); } class TransfersSubscriptionTest : public ::testing::Test { public: TransfersSubscriptionTest() : currency(CurrencyBuilder(m_logger).currency()), account(generateAccountKeys()), syncStart(SynchronizationStart{ 0, 0 }), sub(currency, m_logger, AccountSubscription{ account, syncStart, 10 }) { sub.addObserver(&observer); } std::shared_ptr<ITransactionReader> addTransaction(uint64_t amount, uint32_t height, uint32_t outputIndex) { TestTransactionBuilder b1; auto unknownSender = generateAccountKeys(); b1.addTestInput(amount, unknownSender); auto outInfo = b1.addTestKeyOutput(amount, outputIndex, account); auto tx = std::shared_ptr<ITransactionReader>(b1.build().release()); std::vector<TransactionOutputInformationIn> outputs = { outInfo }; sub.addTransaction(TransactionBlockInfo{ height, 100000 }, *tx, outputs); return tx; } Logging::ConsoleLogger m_logger; Currency currency; AccountKeys account; SynchronizationStart syncStart; TransfersSubscription sub; TransfersObserver observer; }; } TEST_F(TransfersSubscriptionTest, getInitParameters) { ASSERT_EQ(syncStart.height, sub.getSyncStart().height); ASSERT_EQ(syncStart.timestamp, sub.getSyncStart().timestamp); ASSERT_EQ(account.address, sub.getAddress()); ASSERT_EQ(account, sub.getKeys()); } TEST_F(TransfersSubscriptionTest, addTransaction) { auto tx1 = addTransaction(10000, 1, 0); auto tx2 = addTransaction(10000, 2, 1); // this transaction should not be added, so no notification auto tx = createTransaction(); addTestInput(*tx, 20000); sub.addTransaction(TransactionBlockInfo{ 2, 100000 }, *tx, {}); ASSERT_EQ(2, sub.getContainer().transactionsCount()); ASSERT_EQ(2, observer.updated.size()); ASSERT_EQ(tx1->getTransactionHash(), observer.updated[0]); ASSERT_EQ(tx2->getTransactionHash(), observer.updated[1]); } TEST_F(TransfersSubscriptionTest, onBlockchainDetach) { addTransaction(10000, 10, 0); auto txHash = addTransaction(10000, 11, 1)->getTransactionHash(); ASSERT_EQ(2, sub.getContainer().transactionsCount()); sub.onBlockchainDetach(11); ASSERT_EQ(1, sub.getContainer().transactionsCount()); ASSERT_EQ(1, observer.deleted.size()); ASSERT_EQ(txHash, observer.deleted[0]); } TEST_F(TransfersSubscriptionTest, onError) { auto err = createError(); addTransaction(10000, 10, 0); addTransaction(10000, 11, 1); ASSERT_EQ(2, sub.getContainer().transactionsCount()); sub.onError(err, 12); ASSERT_EQ(2, sub.getContainer().transactionsCount()); ASSERT_EQ(1, observer.errors.size()); ASSERT_EQ(std::make_tuple(12, err), observer.errors[0]); sub.onError(err, 11); ASSERT_EQ(1, sub.getContainer().transactionsCount()); // one transaction should be detached ASSERT_EQ(2, observer.errors.size()); ASSERT_EQ(std::make_tuple(12, err), observer.errors[0]); ASSERT_EQ(std::make_tuple(11, err), observer.errors[1]); } TEST_F(TransfersSubscriptionTest, advanceHeight) { ASSERT_TRUE(sub.advanceHeight(10)); ASSERT_FALSE(sub.advanceHeight(9)); // can't go backwards } TEST_F(TransfersSubscriptionTest, markTransactionConfirmed) { auto txHash = addTransaction(10000, UNCONFIRMED_TRANSACTION_HEIGHT, UNCONFIRMED)->getTransactionHash(); ASSERT_EQ(1, sub.getContainer().transactionsCount()); ASSERT_EQ(1, observer.updated.size()); // added sub.markTransactionConfirmed(TransactionBlockInfo{ 10, 100000 }, txHash, { 1 }); ASSERT_EQ(2, observer.updated.size()); // added + updated ASSERT_EQ(txHash, observer.updated[0]); } TEST_F(TransfersSubscriptionTest, deleteUnconfirmedTransaction) { auto txHash = addTransaction(10000, UNCONFIRMED_TRANSACTION_HEIGHT, UNCONFIRMED)->getTransactionHash(); ASSERT_EQ(1, sub.getContainer().transactionsCount()); sub.deleteUnconfirmedTransaction(txHash); ASSERT_EQ(0, sub.getContainer().transactionsCount()); ASSERT_EQ(1, observer.deleted.size()); ASSERT_EQ(txHash, observer.deleted[0]); }
[ "33263353+mybtcfx@users.noreply.github.com" ]
33263353+mybtcfx@users.noreply.github.com
b1f99e3664070b0b1904a62226a09dbf5f226dfd
ffa427f7667d7fc05c4e872966cbb272242d3c19
/arc/000/030/arc033/b/main.cpp
cbda9a52f0002a9a31b0cfe79adee3bc47a73bf3
[]
no_license
kubonits/atcoder
10fb6c9477c9b5ff7f963224a2c851aaf10b4b65
5aa001aab4aaabdac2de8c1abd624e3d1c08d3e3
refs/heads/master
2022-10-02T06:42:32.535800
2022-08-29T15:44:55
2022-08-29T15:44:55
160,827,483
0
0
null
null
null
null
UTF-8
C++
false
false
720
cpp
#include <algorithm> #include <iomanip> #include <iostream> using namespace std; int main() { int n, m, a[100000], b[100000]; double cnt1 = 0.0, cnt2 = 0.0; cin >> n >> m; for (int i = 0; i < n; i++) { cin >> a[i]; } for (int i = 0; i < m; i++) { cin >> b[i]; } sort(a, a + n); sort(b, b + m); int ap = 0, bp = 0; while (ap < n || bp < m) { if (ap == n) { bp++; cnt1++; } else if (bp == m) { ap++; cnt1++; } else if (a[ap] > b[bp]) { bp++; cnt1++; } else if (a[ap] < b[bp]) { ap++; cnt1++; } else { ap++; bp++; cnt1++; cnt2++; } } cout << fixed << setprecision(7) << cnt2 / cnt1 << endl; }
[ "kouhei.08.10.09.s@gmail.com" ]
kouhei.08.10.09.s@gmail.com
36e33e9f80f6ad5f240e4953e0f367be28da17ba
ef87493adfa9386136dcf007c7f9e2bf131553a6
/CGJ_Team/CGJ_Team/Object.h
975ddc6837be6bc1d5abfdd23ef7ddca370dbec6
[]
no_license
megax37/Tanks
b3ec17b75cb5430cae96af6243428ac0b3b3adaa
74270618ca3424c201adde1b9f88b716d0e9a33c
refs/heads/master
2020-06-16T13:03:09.580438
2017-01-21T02:23:34
2017-01-21T02:23:34
75,099,604
0
0
null
null
null
null
UTF-8
C++
false
false
138
h
#ifndef _OBJECT_ #define _OBJECT_ class Object { public: void virtual update(int elapsedTime) = 0; void virtual move() = 0; }; #endif
[ "velkan14@gmail.com" ]
velkan14@gmail.com
eade68ffa3eddf2dcf48c12abe6cf4dd64c611eb
5e9c396ea5d81dce62ef4e6f260db21385608922
/src/tests/unit_tests/core/utest_CH_linalg.cpp
e61bfa12240205e6e30df6bca1f83afc5a25391a
[ "BSD-3-Clause" ]
permissive
gvvynplaine/chrono
357b30f896eb6c1dcabcebd0d88f10fab3faff20
a3c0c8735eb069d5c845a7b508a048b58e022ce0
refs/heads/develop
2023-01-05T08:43:13.115419
2020-07-09T08:24:34
2020-07-09T08:24:34
278,308,549
0
0
BSD-3-Clause
2020-10-30T12:17:47
2020-07-09T08:33:24
null
UTF-8
C++
false
false
8,105
cpp
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban // ============================================================================= // // Tests for miscellaneous linear algebra support. // // ============================================================================= #include "chrono/core/ChMatrix.h" #include "chrono/core/ChMatrixMBD.h" #include "chrono/core/ChTransform.h" #include "gtest/gtest.h" using std::cout; using std::endl; using namespace chrono; const double ABS_ERR = 1e-10; TEST(LinearAlgebraTest, create_assign) { ChMatrixDynamic<> Md1(5, 7); ChMatrixDynamic<> Md2(4, 4); ChMatrixNM<double, 4, 4> Ms; ChMatrix33<> A33(Q_from_AngY(0.4)); Ms.setConstant(0.1); // Fill a matrix with an element ASSERT_DOUBLE_EQ(Ms.maxCoeff(), 0.1); ASSERT_DOUBLE_EQ(Ms.minCoeff(), 0.1); Md1.setRandom(); // initialize with random numbers double e32 = Md1(3, 2); Md1.transposeInPlace(); // transpose the matrix in place ASSERT_DOUBLE_EQ(Md1(2, 3), e32); Md1.resize(2, 2); // resize Md1.setZero(); // set all elements to zero ASSERT_DOUBLE_EQ(Md1.maxCoeff(), 0.0); ASSERT_DOUBLE_EQ(Md1.minCoeff(), 0.0); Md2.setIdentity(); // Create a diagonal matrix Md2 *= 3; ASSERT_DOUBLE_EQ(Md2.trace(), 4 * 3.0); ChMatrixDynamic<> M1(Md2); // Copy constructor ChMatrixDynamic<> M2(-M1); // The - unary operator returns a negated matrix ChMatrixDynamic<> M3(8, 4); // 8x4 uninitialized matrix M3 = M1; // Copy (resize as needed) M3 = M1.transpose(); // transposed copy. ASSERT_TRUE((M3 + M2.transpose()).isZero()); ChMatrix33<> B33(1.0); cout << "3x3 identity matrix\n" << B33 << endl; ASSERT_DOUBLE_EQ(B33.trace(), 3.0); } TEST(LinearAlgebraTest, operations) { ChMatrixNM<double, 2, 3> A; ChMatrixDynamic<double> B(2, 3); A.setRandom(); B.setRandom(); ChMatrixDynamic<> sum1(A + B); ChMatrixDynamic<> sum2 = A + B; ChMatrixDynamic<> sum3 = A; sum3 += B; ASSERT_TRUE(sum2 == sum1); ASSERT_TRUE(sum3 == sum1); // Different ways to do subtraction.. ChMatrixDynamic<> diff1 = A - B; ChMatrixDynamic<> diff2 = A; diff2 -= B; ASSERT_TRUE(diff1 == diff2); // Multiplication with scalar ChMatrixDynamic<> ms1 = A * 10; ChMatrixNM<double, 2, 3> ms2 = 10 * A; ChMatrixDynamic<> ms3 = A; ms3 *= 10; ASSERT_TRUE(ms2 == ms1); ASSERT_TRUE(ms3 == ms1); // Matrix multiplications ChMatrixDynamic<> C(3, 2); ChMatrixDynamic<> D(2, 3); C << 1, 2, 3, 4, 5, 6; D << 1, 2, 3, 4, 5, 6; ChMatrix33<> R(Q_from_AngX(CH_C_PI_2)); ChMatrixDynamic<double> CD = C * D; ChMatrixDynamic<double> CD_t = D.transpose() * C.transpose(); ChMatrixDynamic<> RC = R * C; ChMatrixDynamic<> DR = D * R; cout << R << "\n"; cout << "rot * matrix\n" << R * C << endl; cout << "matrix * rot\n" << D * R << endl; ASSERT_TRUE(CD.transpose() == CD_t); ASSERT_DOUBLE_EQ(RC(1, 0), -C(2, 0)); ASSERT_DOUBLE_EQ(DR(1, 2), -D(1, 1)); // Component-wise matrix multiplication and division ChMatrixDynamic<> C_times_D = C.array() * D.transpose().array(); ChMatrixDynamic<> C_div_D = C.array() / D.transpose().array(); cout << "C\n" << C << endl; cout << "D'\n" << D.transpose() << endl; cout << "C_times_D' (component-wise)\n" << C_times_D << endl; cout << "C_div_D' (component-wise)\n" << C_div_D << endl; // Assigning matrix rows ChMatrix33<> J; J << 10, 20, 30, 40, 50, 60, 70, 80, 90; cout << "3x3 matrix J\n" << J << endl; ChVectorN<double, 10> V; V.setZero(); V.segment(3, 3) = J.row(0); cout << "Place row0 in V starting at index 3\n" << V.transpose() << endl; V.segment(7, 3) = J.row(1); cout << "Place row1 in V starting at index 7\n" << V.transpose() << endl; } TEST(LinearAlgebraTest, vector_rotation) { ChQuaternion<> q(1, 2, 3, 4); ChMatrix33<> A(q.GetNormalized()); ChVector<> v1(1, 2, 3); ChVector<> v2 = A * v1; ChVector<> v3 = A.transpose() * v2; cout << A << endl; cout << v1 << endl; cout << v2 << endl; cout << v3 << endl; ASSERT_TRUE(v3.Equals(v1, 1e-8)); } TEST(LinearAlgebraTest, extensions) { ChMatrixNM<double, 2, 3> A; A.setRandom(); cout << "random 2x3 matrix A:\n" << A << endl; A.fillDiagonal(10.1); cout << "fill diagonal with 10.1:\n" << A << endl; A.fill(2.1); cout << "fill entire matrix with 2.1:\n" << A << endl; ChMatrixNM<double, 2, 3> B(A); B(1, 2) += 0.01; cout << "matrix B = A with B(1,2) incremented by 0.01\n" << B << endl; cout << "|A-B| < 0.1? " << A.equals(B, 0.1) << endl; cout << "|A-B| < 0.001? " << A.equals(B, 0.001) << endl; ASSERT_TRUE(A.equals(B, 0.1)); ASSERT_FALSE(A.equals(B, 0.001)); ChVectorDynamic<> v(3); v << 2, 3, 4; ChVectorDynamic<> w(3); w << 0.1, 0.2, 0.3; double wrms_ref = std::sqrt((0.2 * 0.2 + 0.6 * 0.6 + 1.2 * 1.2) / 3); cout << "||v||_wrms, w = " << v.wrmsNorm(w) << endl; cout << "||v + v||_wrms, w = " << (v + v).wrmsNorm(w) << endl; ASSERT_NEAR(v.wrmsNorm(w), wrms_ref, ABS_ERR); ASSERT_NEAR((v + v).wrmsNorm(w), 2 * wrms_ref, ABS_ERR); cout << "v + v + 1: " << (v + v) + 1 << endl; cout << "1 + v: " << 1 + v << endl; } TEST(LinearAlgebraTest, pasting) { ChMatrixDynamic<> A(4, 6); A.setRandom(); cout << A << "\n\n"; ChMatrixNM<double, 2, 3> B; B << 1, 2, 3, 4, 5, 6; cout << B << "\n\n"; ChMatrixNM<double, 5, 7> C; C.setZero(); C.block<2, 3>(1, 1) << 10, 20, 30, 40, 50, 60; cout << C << "\n\n"; ChMatrixDynamic<> X = A; X.block<2, 3>(1, 2) = B; cout << X << "\n\n"; ASSERT_DOUBLE_EQ(X(1, 2), B(0, 0)); ASSERT_DOUBLE_EQ(X(1, 3), B(0, 1)); ASSERT_DOUBLE_EQ(X(1, 4), B(0, 2)); X.block<2, 3>(1, 2) += C.block<2, 3>(1, 1); cout << X << "\n\n"; ASSERT_DOUBLE_EQ(X(1, 2), B(0, 0) + C(1, 1)); ASSERT_DOUBLE_EQ(X(1, 3), B(0, 1) + C(1, 2)); ASSERT_DOUBLE_EQ(X(1, 4), B(0, 2) + C(1, 3)); } TEST(LinearAlgebraTest, custom_matrices) { ChMatrix34<> G = Eigen::Matrix<double, 3, 4>::Ones(3, 4); ChQuaternion<> q(1, 2, 3, 4); ChVector<> v = G * q; cout << v << endl; ChMatrix43<> Gt2 = 2 * G.transpose(); cout << Gt2 << endl; q = Gt2 * v; cout << q << endl; q = G.transpose() * v; cout << q << endl; ChMatrix33<> rot(Q_from_AngX(CH_C_PI / 6)); cout << rot << endl; cout << rot.transpose() << endl; ChMatrix34<> res1 = rot * G; ChMatrix34<> res2 = rot * Gt2.transpose(); ChMatrix43<> res3 = Gt2 * rot; ChMatrix43<> res4 = G.transpose() * rot; ASSERT_TRUE(2 * res1 == res2); ASSERT_TRUE(res3 == 2 * res4); ChMatrix44<> A44; A44.setRandom(); ChQuaternion<> q2 = A44 * q; ChStarMatrix44<> X(ChQuaternion<>(1, 2, 3, 4)); cout << "4x4 star matrix X:\n" << X << endl; ASSERT_TRUE(X(1, 2) == -4); X.semiTranspose(); cout << "Semi-transpose X:\n" << X << endl; ASSERT_TRUE(X(1, 2) == 4); X.semiNegate(); cout << "Semi-negate X:\n" << X << endl; ASSERT_TRUE(X(1, 2) == -4); } TEST(LinearAlgebraTest, solve) { ChMatrixNM<double, 3, 3> A; Eigen::Vector3d b; A << 1, 2, 3, 4, 5, 6, 7, 8, 10; b << 3, 3, 4; cout << "matrix A:\n" << A << endl; cout << "vector b:\n" << b << endl; Eigen::Vector3d x = A.colPivHouseholderQr().solve(b); cout << "solution:\n" << x << endl; cout << "Ax-b:\n" << A * x - b << endl; ASSERT_NEAR((A * x - b).norm(), 0.0, ABS_ERR); }
[ "serban@wisc.edu" ]
serban@wisc.edu
e79b4f30995cfb7dff0ef66853b9e22413dd5890
7917fec06701ba93b7f3253507e3d1307fb8157d
/Landing Prediction UE4 Tensorflow/Source/TFGameBase/TFGameBaseGameModeBase.h
1632a0f5d61b3c0335764842542fe5862b0d5d88
[]
no_license
the-muses-ltd/Cassie
e13bdaca05d79b5aae4b48d1b8e5a2cced5151c3
74bdbf70d40867b68075a5999333af29da809ef2
refs/heads/main
2023-02-04T05:56:20.380965
2020-12-22T10:49:20
2020-12-22T10:49:20
312,335,813
3
0
null
null
null
null
UTF-8
C++
false
false
320
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/GameModeBase.h" #include "TFGameBaseGameModeBase.generated.h" /** * */ UCLASS() class TFGAMEBASE_API ATFGameBaseGameModeBase : public AGameModeBase { GENERATED_BODY() };
[ "alicep35@gmail.com" ]
alicep35@gmail.com
5456f37cb5385ab0a9376214e5ac355c42da21db
9de6af0ff9eb15e857c0c0ecffb6108418a80750
/Ninja_Platformer/src/App.cpp
70a815e60825ec6b51201b09d14114bd299d759c
[ "MIT" ]
permissive
Alejandro-Casanova/Advanced-C-and-Graphics
70157dc13ac0da2f36937c96ce73ddd9b2e73c2a
e7876b23e1cde3368c73fb7e34ebcbc3cb141704
refs/heads/master
2023-02-11T16:26:15.143673
2020-12-24T17:44:59
2020-12-24T17:44:59
289,323,683
0
0
null
null
null
null
UTF-8
C++
false
false
375
cpp
#include "App.h" #include <Bengine/include/ScreenList.h> App::App() { //ctor } App::~App() { //dtor } void App::onInit(){ } void App::addScreens(){ m_gameplayScreen = std::make_unique<GameplayScreen>(&m_window); m_screenList->addScreen(m_gameplayScreen.get()); m_screenList->setScreen(m_gameplayScreen->getScreenIndex()); } void App::onExit(){ }
[ "36633619+Alejandro-Casanova@users.noreply.github.com" ]
36633619+Alejandro-Casanova@users.noreply.github.com
12ffc4313dc8491e2b01d43047c021f498f7574f
7ab7b7da369587e9bb76a0b1f26928e24a78c67d
/src/modules/airspeed_selector/airspeed_selector_main.cpp
f483d7e30ee54bf4890d9f020045ee7f1bc83e01
[ "BSD-3-Clause" ]
permissive
a4aleem/Firmware
f0dff97eecac7e8b3a71c2404bcba2d0a0435efa
2fa3ee9336353c337906056efe6a77dc9a30dfe9
refs/heads/master
2020-07-17T15:51:49.244222
2019-08-30T04:40:22
2019-08-30T04:40:22
206,047,341
1
0
BSD-3-Clause
2019-09-03T10:06:35
2019-09-03T10:06:34
null
UTF-8
C++
false
false
23,380
cpp
/**************************************************************************** * * Copyright (c) 2018 PX4 Development Team. 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 PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include <drivers/drv_hrt.h> #include <ecl/airdata/WindEstimator.hpp> #include <matrix/math.hpp> #include <parameters/param.h> #include <perf/perf_counter.h> #include <px4_module.h> #include <px4_module_params.h> #include <px4_work_queue/ScheduledWorkItem.hpp> #include <lib/airspeed/airspeed.h> #include <AirspeedValidator.hpp> #include <systemlib/mavlink_log.h> #include <uORB/Subscription.hpp> #include <uORB/topics/airspeed.h> #include <uORB/topics/airspeed_validated.h> #include <uORB/topics/estimator_status.h> #include <uORB/topics/mavlink_log.h> #include <uORB/topics/parameter_update.h> #include <uORB/topics/vehicle_acceleration.h> #include <uORB/topics/vehicle_air_data.h> #include <uORB/topics/vehicle_attitude.h> #include <uORB/topics/vehicle_land_detected.h> #include <uORB/topics/vehicle_local_position.h> #include <uORB/topics/vehicle_status.h> #include <uORB/topics/vtol_vehicle_status.h> #include <uORB/topics/wind_estimate.h> using namespace time_literals; static constexpr uint32_t SCHEDULE_INTERVAL{100_ms}; /**< The schedule interval in usec (10 Hz) */ using matrix::Dcmf; using matrix::Quatf; using matrix::Vector2f; using matrix::Vector3f; class AirspeedModule : public ModuleBase<AirspeedModule>, public ModuleParams, public px4::ScheduledWorkItem { public: AirspeedModule(); ~AirspeedModule(); /** @see ModuleBase */ static int task_spawn(int argc, char *argv[]); /** @see ModuleBase */ static int custom_command(int argc, char *argv[]); /** @see ModuleBase */ static int print_usage(const char *reason = nullptr); /* run the main loop */ void Run() override; int print_status() override; private: static constexpr int MAX_NUM_AIRSPEED_SENSORS = 3; /**< Support max 3 airspeed sensors */ orb_advert_t _airspeed_validated_pub {nullptr}; /**< airspeed validated topic*/ orb_advert_t _wind_est_pub[MAX_NUM_AIRSPEED_SENSORS + 1] {}; /**< wind estimate topic (for each airspeed validator + purely sideslip fusion) */ orb_advert_t _mavlink_log_pub {nullptr}; /**< mavlink log topic*/ uORB::Subscription _estimator_status_sub{ORB_ID(estimator_status)}; uORB::Subscription _param_sub{ORB_ID(parameter_update)}; uORB::Subscription _vehicle_acceleration_sub{ORB_ID(vehicle_acceleration)}; uORB::Subscription _vehicle_air_data_sub{ORB_ID(vehicle_air_data)}; uORB::Subscription _vehicle_attitude_sub{ORB_ID(vehicle_attitude)}; uORB::Subscription _vehicle_land_detected_sub{ORB_ID(vehicle_land_detected)}; uORB::Subscription _vehicle_local_position_sub{ORB_ID(vehicle_local_position)}; uORB::Subscription _vehicle_status_sub{ORB_ID(vehicle_status)}; uORB::Subscription _vtol_vehicle_status_sub{ORB_ID(vtol_vehicle_status)}; estimator_status_s _estimator_status {}; parameter_update_s _parameter_update {}; vehicle_acceleration_s _accel {}; vehicle_air_data_s _vehicle_air_data {}; vehicle_attitude_s _vehicle_attitude {}; vehicle_land_detected_s _vehicle_land_detected {}; vehicle_local_position_s _vehicle_local_position {}; vehicle_status_s _vehicle_status {}; vtol_vehicle_status_s _vtol_vehicle_status {}; WindEstimator _wind_estimator_sideslip; /**< wind estimator instance only fusing sideslip */ wind_estimate_s _wind_estimate_sideslip {}; /**< wind estimate message for wind estimator instance only fusing sideslip */ int _airspeed_sub[MAX_NUM_AIRSPEED_SENSORS] {}; /**< raw airspeed topics subscriptions. Max 3 airspeeds sensors. */ int _number_of_airspeed_sensors{0}; /**< number of airspeed sensors in use (detected during initialization)*/ AirspeedValidator *_airspeed_validator{nullptr}; /**< airspeedValidator instances (one for each sensor, assigned dynamically during startup) */ int _valid_airspeed_index{-1}; /**< index of currently chosen (valid) airspeed sensor */ int _prev_airspeed_index{-1}; /**< previously chosen airspeed sensor index */ bool _initialized{false}; /**< module initialized*/ bool _vehicle_local_position_valid{false}; /**< local position (from GPS) valid */ bool _in_takeoff_situation{true}; /**< in takeoff situation (defined as not yet stall speed reached) */ float _ground_minus_wind_TAS{0.0f}; /**< true airspeed from groundspeed minus windspeed */ float _ground_minus_wind_EAS{0.0f}; /**< true airspeed from groundspeed minus windspeed */ bool _scale_estimation_previously_on{false}; /**< scale_estimation was on in the last cycle */ perf_counter_t _perf_elapsed{}; perf_counter_t _perf_interval{}; DEFINE_PARAMETERS( (ParamFloat<px4::params::ARSP_W_P_NOISE>) _param_west_w_p_noise, (ParamFloat<px4::params::ARSP_SC_P_NOISE>) _param_west_sc_p_noise, (ParamFloat<px4::params::ARSP_TAS_NOISE>) _param_west_tas_noise, (ParamFloat<px4::params::ARSP_BETA_NOISE>) _param_west_beta_noise, (ParamInt<px4::params::ARSP_TAS_GATE>) _param_west_tas_gate, (ParamInt<px4::params::ARSP_BETA_GATE>) _param_west_beta_gate, (ParamInt<px4::params::ARSP_SCALE_EST>) _param_west_scale_estimation_on, (ParamFloat<px4::params::ARSP_ARSP_SCALE>) _param_west_airspeed_scale, (ParamFloat<px4::params::COM_TAS_FS_INNOV>) _tas_innov_threshold, /**< innovation check threshold */ (ParamFloat<px4::params::COM_TAS_FS_INTEG>) _tas_innov_integ_threshold, /**< innovation check integrator threshold */ (ParamInt<px4::params::COM_TAS_FS_T1>) _checks_fail_delay, /**< delay to declare airspeed invalid */ (ParamInt<px4::params::COM_TAS_FS_T2>) _checks_clear_delay, /**< delay to declare airspeed valid again */ (ParamFloat<px4::params::COM_ASPD_STALL>) _airspeed_stall /**< stall speed*/ ) int start(); void update_params(); /**< update parameters */ void poll_topics(); /**< poll all topics required beside airspeed (e.g. current temperature) */ void update_wind_estimator_sideslip(); /**< update the wind estimator instance only fusing sideslip */ void update_ground_minus_wind_airspeed(); /**< update airspeed estimate based on groundspeed minus windspeed */ void select_airspeed_and_publish(); /**< select airspeed sensor (or groundspeed-windspeed) */ void publish_wind_estimates(); /**< publish wind estimator states (from all wind estimators running) */ }; AirspeedModule::AirspeedModule(): ModuleParams(nullptr), ScheduledWorkItem(px4::wq_configurations::lp_default) { // initialise parameters update_params(); _perf_elapsed = perf_alloc_once(PC_ELAPSED, "airspeed_selector elapsed"); _perf_interval = perf_alloc_once(PC_INTERVAL, "airspeed_selector interval"); } AirspeedModule::~AirspeedModule() { ScheduleClear(); for (int i = 0; i < MAX_NUM_AIRSPEED_SENSORS; i++) { if (_wind_est_pub[i] != nullptr) { orb_unadvertise(_wind_est_pub[i]); } } orb_unadvertise(_airspeed_validated_pub); perf_free(_perf_elapsed); perf_free(_perf_interval); if (_airspeed_validator != nullptr) { delete[] _airspeed_validator; } } int AirspeedModule::task_spawn(int argc, char *argv[]) { AirspeedModule *dev = new AirspeedModule(); // check if the trampoline is called for the first time if (!dev) { PX4_ERR("alloc failed"); return PX4_ERROR; } _object.store(dev); if (dev) { dev->ScheduleOnInterval(SCHEDULE_INTERVAL, 10000); _task_id = task_id_is_work_queue; return PX4_OK; } return PX4_ERROR; } void AirspeedModule::Run() { perf_count(_perf_interval); perf_begin(_perf_elapsed); /* the first time we run through here, initialize N airspeedValidator * instances (N = number of airspeed sensors detected) */ if (!_initialized) { for (int i = 0; i < MAX_NUM_AIRSPEED_SENSORS; i++) { if (orb_exists(ORB_ID(airspeed), i) != 0) { continue; } _number_of_airspeed_sensors = i + 1; } _airspeed_validator = new AirspeedValidator[_number_of_airspeed_sensors]; if (_number_of_airspeed_sensors > 0) { for (int i = 0; i < _number_of_airspeed_sensors; i++) { _airspeed_sub[i] = orb_subscribe_multi(ORB_ID(airspeed), i); _valid_airspeed_index = 0; // set index to first sensor _prev_airspeed_index = 0; // set index to first sensor } } _initialized = true; } parameter_update_s update; if (_param_sub.update(&update)) { update_params(); } poll_topics(); update_wind_estimator_sideslip(); update_ground_minus_wind_airspeed(); if (_airspeed_validator != nullptr) { bool armed = (_vehicle_status.arming_state == vehicle_status_s::ARMING_STATE_ARMED); bool fixed_wing = !_vtol_vehicle_status.vtol_in_rw_mode; bool in_air = !_vehicle_land_detected.landed; /* Prepare data for airspeed_validator */ struct airspeed_validator_update_data input_data = {}; input_data.timestamp = hrt_absolute_time(); input_data.lpos_vx = _vehicle_local_position.vx; input_data.lpos_vy = _vehicle_local_position.vy; input_data.lpos_vz = _vehicle_local_position.vz; input_data.lpos_valid = _vehicle_local_position_valid; input_data.lpos_evh = _vehicle_local_position.evh; input_data.lpos_evv = _vehicle_local_position.evv; input_data.att_q[0] = _vehicle_attitude.q[0]; input_data.att_q[1] = _vehicle_attitude.q[1]; input_data.att_q[2] = _vehicle_attitude.q[2]; input_data.att_q[3] = _vehicle_attitude.q[3]; input_data.air_pressure_pa = _vehicle_air_data.baro_pressure_pa; input_data.accel_z = _accel.xyz[2]; input_data.vel_test_ratio = _estimator_status.vel_test_ratio; input_data.mag_test_ratio = _estimator_status.mag_test_ratio; /* iterate through all airspeed sensors, poll new data from them and update their validators */ for (int i = 0; i < _number_of_airspeed_sensors; i++) { /* poll airspeed data */ airspeed_s airspeed_raw = {}; orb_copy(ORB_ID(airspeed), _airspeed_sub[i], &airspeed_raw); // poll raw airspeed topic of the i-th sensor input_data.airspeed_indicated_raw = airspeed_raw.indicated_airspeed_m_s; input_data.airspeed_true_raw = airspeed_raw.true_airspeed_m_s; input_data.airspeed_timestamp = airspeed_raw.timestamp; input_data.air_temperature_celsius = airspeed_raw.air_temperature_celsius; /* update in_fixed_wing_flight for the current airspeed sensor validator */ /* takeoff situation is active from start till one of the sensors' IAS or groundspeed_EAS is above stall speed */ if (airspeed_raw.indicated_airspeed_m_s > _airspeed_stall.get() || _ground_minus_wind_EAS > _airspeed_stall.get()) { _in_takeoff_situation = false; } /* reset takeoff_situation to true when not in air or not in fixed-wing mode */ if (!in_air || !fixed_wing) { _in_takeoff_situation = true; } input_data.in_fixed_wing_flight = (armed && fixed_wing && in_air && !_in_takeoff_situation); /* push input data into airspeed validator */ _airspeed_validator[i].update_airspeed_validator(input_data); } } select_airspeed_and_publish(); perf_end(_perf_elapsed); if (should_exit()) { exit_and_cleanup(); } } void AirspeedModule::update_params() { updateParams(); /* update wind estimator (sideslip fusion only) parameters */ _wind_estimator_sideslip.set_wind_p_noise(_param_west_w_p_noise.get()); _wind_estimator_sideslip.set_tas_scale_p_noise(_param_west_sc_p_noise.get()); _wind_estimator_sideslip.set_tas_noise(_param_west_tas_noise.get()); _wind_estimator_sideslip.set_beta_noise(_param_west_beta_noise.get()); _wind_estimator_sideslip.set_tas_gate(_param_west_tas_gate.get()); _wind_estimator_sideslip.set_beta_gate(_param_west_beta_gate.get()); /* update airspeedValidator parameters */ for (int i = 0; i < _number_of_airspeed_sensors; i++) { _airspeed_validator[i].set_wind_estimator_wind_p_noise(_param_west_w_p_noise.get()); _airspeed_validator[i].set_wind_estimator_tas_scale_p_noise(_param_west_sc_p_noise.get()); _airspeed_validator[i].set_wind_estimator_tas_noise(_param_west_tas_noise.get()); _airspeed_validator[i].set_wind_estimator_beta_noise(_param_west_beta_noise.get()); _airspeed_validator[i].set_wind_estimator_tas_gate(_param_west_tas_gate.get()); _airspeed_validator[i].set_wind_estimator_beta_gate(_param_west_beta_gate.get()); _airspeed_validator[i].set_wind_estimator_scale_estimation_on(_param_west_scale_estimation_on.get()); /* Only apply manual entered airspeed scale to first airspeed measurement */ _airspeed_validator[0].set_airspeed_scale(_param_west_airspeed_scale.get()); _airspeed_validator[i].set_tas_innov_threshold(_tas_innov_threshold.get()); _airspeed_validator[i].set_tas_innov_integ_threshold(_tas_innov_integ_threshold.get()); _airspeed_validator[i].set_checks_fail_delay(_checks_fail_delay.get()); _airspeed_validator[i].set_checks_clear_delay(_checks_clear_delay.get()); _airspeed_validator[i].set_airspeed_stall(_airspeed_stall.get()); } /* when airspeed scale estimation is turned on and the airspeed is valid, then set the scale inside the wind estimator to -1 such that it starts to estimate it */ if (!_scale_estimation_previously_on && _param_west_scale_estimation_on.get()) { if (_valid_airspeed_index >= 0) { _airspeed_validator[0].set_airspeed_scale( -1.0f); // set it to a negative value to start estimation inside wind estimator } else { mavlink_and_console_log_info(&_mavlink_log_pub, "Airspeed: can't estimate scale as no valid sensor."); _param_west_scale_estimation_on.set(0); // reset this param to 0 as estimation was not turned on _param_west_scale_estimation_on.commit_no_notification(); } /* If one sensor is valid and we switched out of scale estimation, then publish message and change the value of param ARSP_ARSP_SCALE */ } else if (_scale_estimation_previously_on && !_param_west_scale_estimation_on.get()) { if (_valid_airspeed_index >= 0) { _param_west_airspeed_scale.set(_airspeed_validator[_valid_airspeed_index].get_EAS_scale()); _param_west_airspeed_scale.commit_no_notification(); _airspeed_validator[_valid_airspeed_index].set_airspeed_scale(_param_west_airspeed_scale.get()); mavlink_and_console_log_info(&_mavlink_log_pub, "Airspeed: estimated scale (ARSP_ARSP_SCALE): %0.2f", (double)_airspeed_validator[_valid_airspeed_index].get_EAS_scale()); } else { mavlink_and_console_log_info(&_mavlink_log_pub, "Airspeed: can't estimate scale as no valid sensor."); } } _scale_estimation_previously_on = _param_west_scale_estimation_on.get(); } void AirspeedModule::poll_topics() { _estimator_status_sub.update(&_estimator_status); _vehicle_acceleration_sub.update(&_accel); _vehicle_air_data_sub.update(&_vehicle_air_data); _vehicle_attitude_sub.update(&_vehicle_attitude); _vehicle_land_detected_sub.update(&_vehicle_land_detected); _vehicle_status_sub.update(&_vehicle_status); _vtol_vehicle_status_sub.update(&_vtol_vehicle_status); _vehicle_local_position_sub.update(&_vehicle_local_position); _vehicle_local_position_valid = (hrt_absolute_time() - _vehicle_local_position.timestamp < 1_s) && (_vehicle_local_position.timestamp > 0) && _vehicle_local_position.v_xy_valid; } void AirspeedModule::update_wind_estimator_sideslip() { bool att_valid = true; // TODO: check if attitude is valid const hrt_abstime time_now_usec = hrt_absolute_time(); /* update wind and airspeed estimator */ _wind_estimator_sideslip.update(time_now_usec); if (_vehicle_local_position_valid && att_valid) { Vector3f vI(_vehicle_local_position.vx, _vehicle_local_position.vy, _vehicle_local_position.vz); Quatf q(_vehicle_attitude.q); /* sideslip fusion */ _wind_estimator_sideslip.fuse_beta(time_now_usec, vI, q); } /* fill message for publishing later */ _wind_estimate_sideslip.timestamp = time_now_usec; float wind[2]; _wind_estimator_sideslip.get_wind(wind); _wind_estimate_sideslip.windspeed_north = wind[0]; _wind_estimate_sideslip.windspeed_east = wind[1]; float wind_cov[2]; _wind_estimator_sideslip.get_wind_var(wind_cov); _wind_estimate_sideslip.variance_north = wind_cov[0]; _wind_estimate_sideslip.variance_east = wind_cov[1]; _wind_estimate_sideslip.tas_innov = _wind_estimator_sideslip.get_tas_innov(); _wind_estimate_sideslip.tas_innov_var = _wind_estimator_sideslip.get_tas_innov_var(); _wind_estimate_sideslip.beta_innov = _wind_estimator_sideslip.get_beta_innov(); _wind_estimate_sideslip.beta_innov_var = _wind_estimator_sideslip.get_beta_innov_var(); _wind_estimate_sideslip.tas_scale = _wind_estimator_sideslip.get_tas_scale(); } void AirspeedModule::update_ground_minus_wind_airspeed() { /* calculate airspeed estimate based on groundspeed-windspeed to use as fallback */ float TAS_north = _vehicle_local_position.vx - _wind_estimate_sideslip.windspeed_north; float TAS_east = _vehicle_local_position.vy - _wind_estimate_sideslip.windspeed_east; float TAS_down = _vehicle_local_position.vz; // no wind estimate in z _ground_minus_wind_TAS = sqrtf(TAS_north * TAS_north + TAS_east * TAS_east + TAS_down * TAS_down); _ground_minus_wind_EAS = calc_EAS_from_TAS(_ground_minus_wind_TAS, _vehicle_air_data.baro_pressure_pa, _vehicle_air_data.baro_temp_celcius); } void AirspeedModule::select_airspeed_and_publish() { /* airspeed index: / 0: first airspeed sensor valid / 1: second airspeed sensor valid / -1: airspeed sensor(s) invalid, but groundspeed-windspeed estimate valid / -2: airspeed invalid (sensors and groundspeed-windspeed estimate invalid) */ bool find_new_valid_index = false; /* find new valid index if airspeed currently invalid (but we have sensors) */ if ((_number_of_airspeed_sensors > 0 && _prev_airspeed_index < 0) || (_prev_airspeed_index >= 0 && !_airspeed_validator[_prev_airspeed_index].get_airspeed_valid()) || _prev_airspeed_index == -2) { find_new_valid_index = true; } if (find_new_valid_index) { _valid_airspeed_index = -1; for (int i = 0; i < _number_of_airspeed_sensors; i++) { if (_airspeed_validator[i].get_airspeed_valid()) { _valid_airspeed_index = i; break; } } } if (_valid_airspeed_index < 0 && !_vehicle_local_position_valid) { _valid_airspeed_index = -2; } /* publish critical message (and log) in index has changed */ if (_valid_airspeed_index != _prev_airspeed_index) { mavlink_log_critical(&_mavlink_log_pub, "Airspeed: switched from sensor %i to %i", _prev_airspeed_index, _valid_airspeed_index); } _prev_airspeed_index = _valid_airspeed_index; /* fill out airspeed_validated message for publishing it */ airspeed_validated_s airspeed_validated = {}; airspeed_validated.timestamp = hrt_absolute_time(); airspeed_validated.true_ground_minus_wind_m_s = NAN; airspeed_validated.indicated_ground_minus_wind_m_s = NAN; airspeed_validated.indicated_airspeed_m_s = NAN; airspeed_validated.equivalent_airspeed_m_s = NAN; airspeed_validated.true_airspeed_m_s = NAN; airspeed_validated.selected_airspeed_index = _valid_airspeed_index; switch (_valid_airspeed_index) { case -2: break; case -1: airspeed_validated.true_ground_minus_wind_m_s = _ground_minus_wind_TAS; airspeed_validated.indicated_ground_minus_wind_m_s = _ground_minus_wind_EAS; break; default: airspeed_validated.indicated_airspeed_m_s = _airspeed_validator[_valid_airspeed_index].get_IAS(); airspeed_validated.equivalent_airspeed_m_s = _airspeed_validator[_valid_airspeed_index].get_EAS(); airspeed_validated.true_airspeed_m_s = _airspeed_validator[_valid_airspeed_index].get_TAS(); airspeed_validated.true_ground_minus_wind_m_s = _ground_minus_wind_TAS; airspeed_validated.indicated_ground_minus_wind_m_s = _ground_minus_wind_EAS; break; } /* publish airspeed validated topic */ int instance; orb_publish_auto(ORB_ID(airspeed_validated), &_airspeed_validated_pub, &airspeed_validated, &instance, ORB_PRIO_DEFAULT); /* publish sideslip-only-fusion wind topic */ orb_publish_auto(ORB_ID(wind_estimate), &_wind_est_pub[0], &_wind_estimate_sideslip, &instance, ORB_PRIO_LOW); /* publish the wind estimator states from all airspeed validators */ for (int i = 0; i < _number_of_airspeed_sensors; i++) { wind_estimate_s wind_est = _airspeed_validator[i].get_wind_estimator_states(hrt_absolute_time()); orb_publish_auto(ORB_ID(wind_estimate), &_wind_est_pub[i + 1], &wind_est, &instance, ORB_PRIO_LOW); } } int AirspeedModule::custom_command(int argc, char *argv[]) { if (!is_running()) { int ret = AirspeedModule::task_spawn(argc, argv); if (ret) { return ret; } } return print_usage("unknown command"); } int AirspeedModule::print_usage(const char *reason) { if (reason) { PX4_WARN("%s\n", reason); } PRINT_MODULE_DESCRIPTION( R"DESCR_STR( ### Description This module provides a single airspeed_validated topic, containing an indicated (IAS), equivalend (EAS), true airspeed (TAS) and the information if the estimation currently is invalid and if based sensor readings or on groundspeed minus windspeed. Supporting the input of multiple "raw" airspeed inputs, this module automatically switches to a valid sensor in case of failure detection. For failure detection as well as for the estimation of a scale factor from IAS to EAS, it runs several wind estimators and also publishes those. )DESCR_STR"); PRINT_MODULE_USAGE_NAME("airspeed_estimator", "estimator"); PRINT_MODULE_USAGE_COMMAND("start"); PRINT_MODULE_USAGE_DEFAULT_COMMANDS(); return 0; } int AirspeedModule::print_status() { perf_print_counter(_perf_elapsed); perf_print_counter(_perf_interval); int instance = 0; uORB::SubscriptionData<airspeed_validated_s> est{ORB_ID(airspeed_validated), (uint8_t)instance}; est.update(); PX4_INFO("Number of airspeed sensors: %i", _number_of_airspeed_sensors); print_message(est.get()); return 0; } extern "C" __EXPORT int airspeed_selector_main(int argc, char *argv[]); int airspeed_selector_main(int argc, char *argv[]) { return AirspeedModule::main(argc, argv); }
[ "bapstroman@gmail.com" ]
bapstroman@gmail.com
8784c08929767b821170990ad43b1272e89fb222
981fcc98d4509488697c932ca5fa5e554a98ea7a
/image_util/Bounds.cpp
912319056a116315333ece08e370d27aaf40bc3e
[]
no_license
marknemm/Switchless
fe50c43f492bd101167d3db9976f6a85c63a63b0
1214eddcf17ba88f8cadb0e8303041311b291057
refs/heads/master
2020-03-15T13:52:43.304353
2018-05-04T18:46:50
2018-05-04T18:46:50
132,177,327
0
0
null
null
null
null
UTF-8
C++
false
false
338
cpp
#include "Bounds.h" using namespace cv; cv::Rect Bounds::qRectToCvRect(const QRect &qRect) { cv::Rect cvRect(qRect.x(), qRect.y(), qRect.width(), qRect.height()); return cvRect; } QRect Bounds::cvRectToQRect(const cv::Rect &cvRect) { return QRect(cvRect.x, cvRect.y, cvRect.width, cvRect.height); } Bounds::Bounds(){}
[ "marknemm@buffalo.edu" ]
marknemm@buffalo.edu
462a3599fb0a92544d863106b4ec44f4c35586dd
a8ee1337ed14fb4d47fea6510cdceb535c818e6c
/src/qt/statisticspage.cpp
4c11b6396e719573e899cb53c90b1c1403074016
[ "MIT" ]
permissive
Jspike1/SpikePrivateCoin
26e88438fdbe8c94ace6606501b2decdc76bb73c
3f5e2a571ad9a20c47e94907ef70265b37aa7c5b
refs/heads/master
2021-01-19T19:39:50.232345
2015-08-07T17:40:11
2015-08-07T17:40:11
39,851,648
0
2
null
2015-08-07T17:40:11
2015-07-28T18:43:51
C++
UTF-8
C++
false
false
5,115
cpp
#include "statisticspage.h" #include "ui_statisticspage.h" #include "main.h" #include "wallet.h" #include "init.h" #include "base58.h" #include "clientmodel.h" #include "bitcoinrpc.h" #include <sstream> #include <string> using namespace json_spirit; StatisticsPage::StatisticsPage(QWidget *parent) : QWidget(parent), ui(new Ui::StatisticsPage) { ui->setupUi(this); setFixedSize(400, 420); connect(ui->startButton, SIGNAL(pressed()), this, SLOT(updateStatistics())); } int heightPrevious = -1; int connectionPrevious = -1; int volumePrevious = -1; double rewardPrevious = -1; double netPawratePrevious = -1; double pawratePrevious = -1; double hardnessPrevious = -1; double hardnessPrevious2 = -1; int stakeminPrevious = -1; int stakemaxPrevious = -1; QString stakecPrevious = ""; void StatisticsPage::updateStatistics() { double pHardness = GetDifficulty(); double pHardness2 = GetDifficulty(GetLastBlockIndex(pindexBest, true)); int pPawrate = GetPoWMHashPS(); double pPawrate2 = 0.000; int nHeight = pindexBest->nHeight; double nSubsidy = 10; uint64_t nMinWeight = 0, nMaxWeight = 0, nWeight = 0; pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight); uint64_t nNetworkWeight = GetPoSKernelPS(); int64_t volume = ((pindexBest->nMoneySupply)/100000000); int peers = this->model->getNumConnections(); pPawrate2 = (double)pPawrate; QString height = QString::number(nHeight); QString stakemin = QString::number(nMinWeight); QString stakemax = QString::number(nNetworkWeight); QString phase = ""; if (pindexBest->nHeight < 1000) { phase = "Proof of Work"; } else if (pindexBest->nHeight < 2000) { phase = "Prof Of Work - Proof of Stake"; } else if (pindexBest->nHeight > 2000) { phase = "Proof of Stake"; } QString subsidy = QString::number(nSubsidy, 'f', 6); QString hardness = QString::number(pHardness, 'f', 6); QString hardness2 = QString::number(pHardness2, 'f', 6); QString pawrate = QString::number(pPawrate2, 'f', 3); QString Qlpawrate = model->getLastBlockDate().toString(); QString QPeers = QString::number(peers); QString qVolume = QLocale(QLocale::English).toString((qlonglong)volume); if(nHeight > heightPrevious) { ui->heightBox->setText("<b><font color=\"green\">" + height + "</font></b>"); } else { ui->heightBox->setText(height); } if(0 > stakeminPrevious) { ui->minBox->setText("<b><font color=\"green\">" + stakemin + "</font></b>"); } else { ui->minBox->setText(stakemin); } if(0 > stakemaxPrevious) { ui->maxBox->setText("<b><font color=\"green\">" + stakemax + "</font></b>"); } else { ui->maxBox->setText(stakemax); } if(phase != stakecPrevious) { ui->cBox->setText("<b><font color=\"green\">" + phase + "</font></b>"); } else { ui->cBox->setText(phase); } if(pHardness > hardnessPrevious) { ui->diffBox->setText("<b><font color=\"green\">" + hardness + "</font></b>"); } else { ui->diffBox->setText(hardness); } if(pHardness2 > hardnessPrevious2) { ui->diffBox2->setText("<b><font color=\"green\">" + hardness2 + "</font></b>"); } else { ui->diffBox2->setText(hardness2); } if(pPawrate2 > netPawratePrevious) { ui->pawrateBox->setText("<b><font color=\"green\">" + pawrate + " MH/s</font></b>"); } else { ui->pawrateBox->setText(pawrate + " MH/s"); } if(Qlpawrate != pawratePrevious) { ui->localBox->setText("<b><font color=\"green\">" + Qlpawrate + "</font></b>"); } else { ui->localBox->setText(Qlpawrate); } if(peers > connectionPrevious) { ui->connectionBox->setText("<b><font color=\"green\">" + QPeers + "</font></b>"); } else { ui->connectionBox->setText(QPeers); } if(volume > volumePrevious) { ui->volumeBox->setText("<b><font color=\"green\">" + qVolume + " SPC" + "</font></b>"); } else { ui->volumeBox->setText(qVolume + " SPC"); } updatePrevious(nHeight, nMinWeight, nNetworkWeight, phase, nSubsidy, pHardness, pHardness2, pPawrate2, Qlpawrate, peers, volume); } void StatisticsPage::updatePrevious(int nHeight, int nMinWeight, int nNetworkWeight, QString phase, double nSubsidy, double pHardness, double pHardness2, double pPawrate2, QString Qlpawrate, int peers, int volume) { heightPrevious = nHeight; stakeminPrevious = nMinWeight; stakemaxPrevious = nNetworkWeight; stakecPrevious = phase; rewardPrevious = nSubsidy; hardnessPrevious = pHardness; hardnessPrevious2 = pHardness2; netPawratePrevious = pPawrate2; pawratePrevious = Qlpawrate; connectionPrevious = peers; volumePrevious = volume; } void StatisticsPage::setModel(ClientModel *model) { updateStatistics(); this->model = model; } StatisticsPage::~StatisticsPage() { delete ui; }
[ "info@sandersonlinetrading.nl" ]
info@sandersonlinetrading.nl
df1daeada37d4ab7bfae77c41d26a838555e1ed2
7a1663ae38245aa82d7be716ca33052a6ce1090f
/binding/matlab/Matlab_segmentCoM.h
a55362a495751dbec5dfc5095071b6e95f4e7f83
[ "MIT" ]
permissive
vincentdelpech/biorbd
9d10b22782723bc9b654e667b4e48298bef68cb5
0d7968e75e182f067a4d4c24cc15fa9a331ca792
refs/heads/master
2020-07-11T21:31:42.198425
2019-10-03T15:01:21
2019-10-03T15:01:21
204,647,893
0
0
MIT
2019-08-27T09:40:55
2019-08-27T07:40:52
null
UTF-8
C++
false
false
1,937
h
#ifndef BIORBD_MATLAB_SEGMENT_COM_H #define BIORBD_MATLAB_SEGMENT_COM_H #include <mex.h> #include "BiorbdModel.h" #include "class_handle.h" #include "processArguments.h" void Matlab_segmentCOM( int, mxArray *plhs[], int nrhs, const mxArray*prhs[] ){ // Verifier les arguments d'entrée checkNombreInputParametres(nrhs, 3, 4, "3 arguments are required (+1 optional) where the 2nd is the handler on the model, 3rd is the Q and 4th is the index of body segment"); // Recevoir le model biorbd::Model * model = convertMat2Ptr<biorbd::Model>(prhs[1]); unsigned int nQ = model->nbQ(); // Get the number of DoF // Recevoir Q biorbd::rigidbody::GeneralizedCoordinates Q = *getParameterQ(prhs, 2, nQ).begin(); // Recevoir le numéro du segment (optionnel) int i(0); if (nrhs==4) i = getInteger(prhs, 3); i -= 1; // -1 car le segment 0 est numéroté 1 sous matlab // Trouver la position du CoM if (i==-1){ std::vector<biorbd::rigidbody::NodeBone> COM = model->CoMbySegment(Q,true); // Create a matrix for the return argument plhs[0] = mxCreateDoubleMatrix( 3, model->nbBone(), mxREAL); // Remplir l'output double *tp = mxGetPr(plhs[0]); for (unsigned int j=0; j<model->nbBone(); ++j) for (unsigned int k=0; k<3; ++k) tp[3*j+k] = COM[j][k]; // Transférer le tout dans un tableau de sortie } else { biorbd::rigidbody::NodeBone COM = model->CoMbySegment(Q,static_cast<unsigned int>(i),true); // Create a matrix for the return argument plhs[0] = mxCreateDoubleMatrix( 3, 1, mxREAL); // Remplir l'output double *tp = mxGetPr(plhs[0]); for (unsigned int k=0; k<3; ++k) tp[k] = COM[k]; // Transférer le tout dans un tableau de sortie } return; } #endif // BIORBD_MATLAB_SEGMENT_COM_H
[ "pariterre@hotmail.com" ]
pariterre@hotmail.com
2fa9054b71d3ed180255c09d30aa724fed625665
603eefc58befb614aae826b7340f02a43980c108
/Source/Library/RTCOP/DependentCode/ExecuteLayerdObjectFinalizer.h
f7d16915356710269db4afe046b89c606697c8e3
[]
no_license
tanigawaikuta/RTCOP
b5e6c7b58e02b0620af1715e77d2ebe270c74dfe
fbb5f8e08a824b3c4f20279bcc52b9cd67e62f44
refs/heads/master
2023-05-13T08:31:56.069954
2021-06-01T07:36:47
2021-06-01T07:36:47
277,475,195
3
1
null
2021-06-01T07:36:51
2020-07-06T07:40:58
C#
UTF-8
C++
false
false
814
h
//================================================================================ // ExecuteLayerdObjectFinalizer.h // // 役割: レイヤードなオブジェクトのファイナライザを実行するための関数を提供する。 // この関数の実装は、プラットフォームによって異なる。 //================================================================================ #ifndef __RTCOP_DEPENDENTCODE_EXECUTELAYERDOBJECTFINALIZER__ #define __RTCOP_DEPENDENTCODE_EXECUTELAYERDOBJECTFINALIZER__ namespace RTCOP { namespace DependentCode { // LayerdObjectのFinalizer実行 void ExecuteLayerdObjectFinalizer(void* layerdObject, volatile void* finalizer); } // namespace DependentCode {} } // namespace RTCOP {} #endif // !__RTCOP_DEPENDENTCODE_EXECUTELAYERDOBJECTFINALIZER__
[ "tanigawaikuta@gmail.com" ]
tanigawaikuta@gmail.com
1c812224916c80381ebea9df26b1d096204317cb
2d1f82fe5c4818ef1da82d911d0ed81a0b41ec85
/codeforces/gym/Petrozavodsk Winter Training Camp, Saratov SU Contest 2017/CF101741L.cpp
76cda8e79a3950308eb986ef72dda7ef6e6d6854
[]
no_license
OrigenesZhang/-1s
d12bad12dee37d4bb168647d7b888e2e198e8e56
08a88e4bb84b67a44eead1b034a42f5338aad592
refs/heads/master
2020-12-31T00:43:17.972520
2020-12-23T14:56:38
2020-12-23T14:56:38
80,637,191
4
1
null
null
null
null
UTF-8
C++
false
false
2,824
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> pii; #define FOR(i, a, b) for (int (i) = (a); (i) <= (b); (i)++) #define ROF(i, a, b) for (int (i) = (a); (i) >= (b); (i)--) #define REP(i, n) FOR(i, 0, (n)-1) #define sqr(x) ((x) * (x)) #define all(x) (x).begin(), (x).end() #define reset(x, y) memset(x, y, sizeof(x)) #define uni(x) (x).erase(unique(all(x)), (x).end()) #define BUG(x) cerr << #x << " = " << (x) << endl #define pb push_back #define eb emplace_back #define mp make_pair #define _1 first #define _2 second #define chkmin(a, b) a = min(a, b) #define chkmax(a, b) a = max(a, b) const int maxn = 212345; vector<int> G[maxn], adj[maxn]; vector<pii> T[maxn]; vector<int> lis[maxn]; int n, m; int u[maxn], v[maxn], w[maxn], pre[maxn], deg[maxn], ans[maxn], dep[maxn]; int anc[maxn][20]; ll f[maxn]; int lca(int a, int b) { if (dep[a] > dep[b]) swap(a, b); ROF(i, 18, 0) if (dep[anc[b][i]] >= dep[a]) b = anc[b][i]; if (a == b) return a; ROF(i, 18, 0) if (anc[a][i] != anc[b][i]) a = anc[a][i], b = anc[b][i]; return anc[a][0]; } int dfs(int x, int i) { int tot = 0; for (auto _ : T[x]) { int j = _._1, y = _._2; tot += dfs(y, j); } tot++; return ans[i] = tot; } int main() { scanf("%d%d", &n, &m); FOR(i, 1, m) { scanf("%d%d%d", u + i, v + i, w + i); G[u[i]].eb(i); G[v[i]].eb(i); } reset(f, 0x3f); f[1] = 0; set<pair<ll, int>> q; q.emplace(f[1], 1); while (!q.empty()) { auto now = *q.begin(); q.erase(q.begin()); ll d = now._1; int x = now._2; if (f[x] != d) continue; for (auto i : G[x]) { int y = u[i] ^ v[i] ^ x, c = w[i]; if (f[y] > f[x] + c) { pre[y] = i; f[y] = f[x] + c; q.emplace(f[y], y); } } } set<int> s; FOR(i, 1, n) if (pre[i]) { int j = u[pre[i]] ^ v[pre[i]] ^ i; adj[j].eb(pre[i]); deg[i]++; s.emplace(pre[i]); } FOR(i, 1, m) if (!s.count(i)) { int x = u[i], y = v[i], c = w[i]; if (f[x] > f[y]) swap(x, y); if (f[y] == f[x] + c) { adj[x].eb(i); deg[y]++; } } queue<int> que; que.emplace(1); dep[1] = 1; while (!que.empty()) { int x = que.front(); que.pop(); for (auto i : adj[x]) { int y = u[i] ^ v[i] ^ x; lis[y].eb(x); if (!--deg[y]) { if (lis[y].size() == 1) { T[x].eb(i, y); anc[y][0] = x; dep[y] = dep[x] + 1; } else { int a = lca(lis[y][0], lis[y][1]); FOR(j, 2, int(lis[y].size()) - 1) a = lca(a, lis[y][j]); T[a].eb(0, y); anc[y][0] = a; dep[y] = dep[a] + 1; } FOR(j, 1, 18) anc[y][j] = anc[anc[y][j - 1]][j - 1]; que.emplace(y); } } } dfs(1, 0); FOR(i, 1, m) printf("%d\n", ans[i]); }
[ "zhangbin199807@gmail.com" ]
zhangbin199807@gmail.com
0238a389cce0ed8f818fceac574fc5edaf0c5c22
0782f9e1df8b7eb0e0e9be12b0dd596c5a117887
/include/Bloco.h
61b9c3335bb015ce04e5daca093c2046dda017e2
[]
no_license
gtroja/qjgo
4084642c23aa6af3c8ae661cad0abb5930159d24
e0b7b71be85c84b75fc8977f11e8ea401ebb4f4b
refs/heads/master
2020-07-01T15:09:21.791333
2019-10-02T04:06:50
2019-10-02T04:06:50
74,335,723
0
0
null
null
null
null
UTF-8
C++
false
false
682
h
#ifndef BLOCO_H #define BLOCO_H #include "Defines.h" #include "Coordenada.h" #include "Terreno.h" class Bloco{ public: Bloco(); //int setLimites(Bloco* lim); int mover(coordenada c); int crescer(coordenada c); int setPosicao(coordenada p); int setTamanho(coordenada t); //bool estaDentro(coordenada d); //bool estaDentro(Bloco *b); //bool estaFora(Bloco *b); Bloco colisao(Bloco* b); Bloco colisao(Terreno* t); coordenada getPosicao(); coordenada getTamanho(); //int verificaLimites(); protected: //bool estaEntre(coordenada la, coordenada lb, coordenada p); //bool estaDentro(Bloco b, coordenada p); coordenada posicao; coordenada tamanho; }; #endif
[ "guilhermetrojan@alunos.utfpr.edu.br" ]
guilhermetrojan@alunos.utfpr.edu.br
38cc2f39ff5486a4e0f5677e7c6cc296d47cfabe
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/collectd/old_hunk_285.cpp
7bcf7c053e8d38039e38765ed439e6cf86d7baa4
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
225
cpp
CPY_RELEASE_THREADS } static PyObject *cpy_register_generic(cpy_callback_t **list_head, PyObject *args, PyObject *kwds) { cpy_callback_t *c; const char *name = NULL; PyObject *callback = NULL, *data = NULL, *mod = NULL;
[ "993273596@qq.com" ]
993273596@qq.com
5ff9891947ecb8f5e01cfd81b9d4930aab72fe49
4c93ca76318969f1624a0e77749bcdea3e7809d3
/~9999/1289_트리의 가중치_2.cpp
5ef7c132a38cef45ad2582540959349a25cd86c6
[]
no_license
root-jeong/BOJ
080925f6cfbb5dcbdf13c4c3a3c7e0a444908e6e
ec1ef5ad322597883b74d276078da8a508f164a8
refs/heads/master
2022-04-03T22:33:44.866564
2020-01-08T12:21:19
2020-01-08T12:21:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
569
cpp
#include <iostream> #include <vector> using namespace std; vector<pair<int, int> > vec[100001]; int DIV = 1000000007; long long total; long long dfs(int now, int prev) { long long tmp; long long ret = 1; for (const auto & x : vec[now]) { if (x.first != prev) { tmp = dfs(x.first,now )* x.second % DIV; total += (tmp * ret) % DIV; ret += (tmp + ret) % DIV; } } } int main() { int N; int a, b, wei; cin >> N; for (int i = 0; i < N; i++) { cin >> a >> b >> wei; vec[a].push_back(make_pair(b, wei)); vec[b].push_back(make_pair(a, wei)); } }
[ "gjek136@naver.com" ]
gjek136@naver.com
1e23c85e2ac4cbeabaf47240458593e953d56482
1917cc3414598031b02f6530a48af20ccc5dd2a6
/kodilib/src/widgets/KButton.cpp
1bc5bb1eba1f7db39bbf65e2564646c48e74fe75
[ "LicenseRef-scancode-warranty-disclaimer", "Unlicense" ]
permissive
Mistress-Anna/kiki
8cebcf4b7b737bb214bbea8908bbdc61bc325cb5
2f615044d72de6b3ca869e2230abdd0aced2aa00
refs/heads/master
2022-04-29T16:34:45.812039
2018-06-24T09:13:39
2020-01-04T23:38:22
42,407,357
2
1
Unlicense
2022-03-16T08:11:09
2015-09-13T18:23:04
C++
UTF-8
C++
false
false
1,911
cpp
/* * KButton.cpp * kodisein */ #include "KButton.h" #include "KConsole.h" #include "KColor.h" KDL_CLASS_INTROSPECTION_2 (KButton, KLabel, KNotificationObject) // -------------------------------------------------------------------------------------------------------- KButton::KButton ( const std::string & n ) : KLabel(n) { flags[KDL_WIDGET_FLAG_FIXED_SIZE] = false; flags[KDL_WIDGET_FLAG_FRAMED] = true; } // -------------------------------------------------------------------------------------------------------- void KButton::setPicked ( bool p ) { if (p) activate(); //picked = p; } // -------------------------------------------------------------------------------------------------------- void KButton::activate() { picked = true; notifyReceivers(); notifyReceivers(true); notifyReceivers(text); } // -------------------------------------------------------------------------------------------------------- void KButton::deactivate () { picked = false; notifyReceivers(false); } // -------------------------------------------------------------------------------------------------------- KColor * KButton::getFGColor () const { if (fg_color) return fg_color; if (parent) return parent->getFGColor(); return NULL; } // -------------------------------------------------------------------------------------------------------- KColor * KButton::getBGColor () const { if (bg_color) return bg_color; if (parent) return parent->getBGColor(); return NULL; } // -------------------------------------------------------------------------------------------------------- void KButton::render () { glPushAttrib(GL_CURRENT_BIT | GL_LIGHTING_BIT); if (picked) { glColor4f(1.0, 1.0, 1.0, 1.0); } else if (getFGColor()) { getFGColor()->glColor(); } KLabel::render(); glPopAttrib(); }
[ "monsterkodi@users.sourceforge.net" ]
monsterkodi@users.sourceforge.net
cd50527672973dec7d2f37fa822b8b9ab666da98
e12b5ffa7153c58c16e25cd4475189f56e4eb9d1
/Explanation2/P2296.cpp
c94cf6dd032edcf1efdab30c6fee22ac83a6784a
[]
no_license
hhhnnn2112-Home/NOI-ACcode-Explanation
ef1cdf60504b3bd01ba96f93519dde5aa1aec7ad
821b08584b804a2ae425f3f7294cc99bd87c9f5b
refs/heads/main
2023-02-01T02:20:00.421990
2020-12-15T10:11:22
2020-12-15T10:11:22
321,634,613
1
0
null
2020-12-15T10:36:22
2020-12-15T10:36:21
null
UTF-8
C++
false
false
1,235
cpp
#include<bits/stdc++.h> using namespace std; int a[400050],b[400050]; struct edge { int ver,nxt; }z[400050],f[400050]; int head1[400050],head2[400050],cnt; void add1(int x,int y) { cnt++; z[cnt]=(edge){y,head1[x]}; head1[x]=cnt; } void add2(int x,int y) { cnt++; f[cnt]=(edge){y,head2[x]}; head2[x]=cnt; } int n,m; int s,t; void dfs(int x,int fa) { a[x]=1; for(int i=head2[x];i;i=f[i].nxt) { int y=f[i].ver; if(!a[y]) { dfs(y,x); } } } int d[100050]; void bfs(int st) { if(!b[st]) { printf("-1"); exit(0); } queue<int> q; q.push(st); d[st]=1; while(!q.empty()) { int x=q.front(); q.pop(); for(int i=head1[x];i;i=z[i].nxt) { int y=z[i].ver; if(b[y]&&!d[y]) { d[y]=d[x]+1; q.push(y); } } } } int main() { scanf("%d%d",&n,&m); for(int i=1;i<=m;i++) { int x,y; scanf("%d%d",&x,&y); if(a==b)continue; add1(x,y); add2(y,x); } scanf("%d%d",&s,&t); dfs(t,0); for(int i=1;i<=n;i++) { if(!a[i])continue; b[i]=1; for(int j=head1[i];j;j=z[j].nxt) { int y=z[j].ver; if(!a[y]) { b[i]=0; break; } } } bfs(s); printf("%d",d[t]-1); return 0; }
[ "48145116+hhhnnn2112@users.noreply.github.com" ]
48145116+hhhnnn2112@users.noreply.github.com
4521879a270666d0870c36ab4a573d7255bebd28
3233accbde095c41593861c9d5b44d0f7959c721
/1394camera/1394camera/1394CamFMR.cpp
5ab2d848ee3a714ff6e912102d5da36baa3d4f9b
[]
no_license
iamchucky/tdloc
6cf4a76f0ab7f19bb2cb5db7150a8750943cba34
d30cce12c626260df86885770033323156aa6224
refs/heads/master
2021-01-19T16:23:40.961659
2011-05-19T18:22:49
2011-05-19T18:22:49
1,204,147
0
0
null
null
null
null
UTF-8
C++
false
false
20,564
cpp
/**\file 1394CamFMR.cpp * \brief Implements Format, Mode, Rate manipulation for the C1394Camera class. * \ingroup camfmr */ ////////////////////////////////////////////////////////////////////// // // Version 6.4 // // Copyright 8/2006 // // Christopher Baker // Robotics Institute // Carnegie Mellon University // Pittsburgh, PA // // Copyright 5/2000 // // Iwan Ulrich // Robotics Institute // Carnegie Mellon University // Pittsburgh, PA // // This file is part of the CMU 1394 Digital Camera Driver // // The CMU 1394 Digital Camera Driver is free software; you can redistribute // it and/or modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; either version 2.1 of the License, // or (at your option) any later version. // // The CMU 1394 Digital Camera Driver is distributed in the hope that it will // be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the CMU 1394 Digital Camera Driver; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // ////////////////////////////////////////////////////////////////////// #include "pch.h" /** \defgroup camfmr Video Format Controls * \ingroup camcore * \brief Protected accessors and mutators for manipulation of video settings. */ /**\brief Set the Video Format * \ingroup camfmr * \param format The format in [0,7] that you wish to use * \return * - CAM_SUCCESS: Format selection is successful. * - CAM_ERROR_NOT_INITIALIZED: No camera celected and/or camera not initialized * - CAM_ERROR_BUSY: The camera is actively acquiring images * - CAM_ERROR: WriteRegister() has failed, use GetLastError() to find out why. * * For a valid format selection, the first valid mode and rate will be automatically * selected to maintain internal consistency. */ int C1394Camera::SetVideoFormat(unsigned long format) { DWORD dwRet; int ret = CAM_ERROR; DllTrace(DLL_TRACE_ENTER,"ENTER SetVideoFormat (%d)\n",format); if (!m_pName || !m_cameraInitialized) { DllTrace(DLL_TRACE_ERROR,"SetVideoFormat: Camera is not initialized\n"); ret = CAM_ERROR_NOT_INITIALIZED; goto _exit; } if(m_hDeviceAcquisition != INVALID_HANDLE_VALUE) { DllTrace(DLL_TRACE_ERROR,"SetVideoFormat: Camera is busy\n"); ret = CAM_ERROR_BUSY; goto _exit; } if(this->HasVideoFormat(format)) { // shift it over into the most significant bits if(dwRet = WriteQuadlet(0x608, format << 29)) { DllTrace(DLL_TRACE_ERROR,"SetVideoFormat: error %08x on WriteRegister\n",dwRet); ret = CAM_ERROR; } else { m_videoFormat = format; // update parameters is a little funky, but leave it anyway UpdateParameters(); ret = CAM_SUCCESS; } } else { DllTrace(DLL_TRACE_ERROR,"SetVideoFormat: Format %d not supported\n",format); ret = CAM_ERROR_INVALID_VIDEO_SETTINGS; } _exit: DllTrace(DLL_TRACE_EXIT,"EXIT SetVideoFormat (%d)\n",ret); return ret; } /**\brief Set the Video Mode * \ingroup camfmr * \param mode The desired mode in [0,7] that you wish to set * \return * - CAM_SUCCESS: Mode selection completed. * - CAM_ERROR_NOT_INITIALIZED: No camera celected and/or camera not initialized * - CAM_ERROR_BUSY: The camera is actively acquiring images * - CAM_ERROR: WriteRegister has failed, use GetLastError() to find out why. * * This function is invalid for Format 7 * * For a valid mode selection, the first valid framerate will be selected for consistency */ int C1394Camera::SetVideoMode(unsigned long mode) { DWORD dwRet; int ret = CAM_ERROR; DllTrace(DLL_TRACE_ENTER,"ENTER SetVideoMode (%d)\n",mode); if (!m_pName || !m_cameraInitialized) { DllTrace(DLL_TRACE_ERROR,"SetVideoMode: Camera is not initialized\n"); ret = CAM_ERROR_NOT_INITIALIZED; goto _exit; } if(m_hDeviceAcquisition != INVALID_HANDLE_VALUE) { DllTrace(DLL_TRACE_ERROR,"SetVideoMode: Camera is busy\n"); ret = CAM_ERROR_BUSY; goto _exit; } if(this->HasVideoMode(m_videoFormat,mode)) { if(dwRet = WriteQuadlet(0x604, mode << 29)) { DllTrace(DLL_TRACE_ERROR,"SetVideoMode: error %08x on WriteRegister\n",dwRet); ret = CAM_ERROR; } else { m_videoMode = mode; UpdateParameters(); ret = CAM_SUCCESS; } } else { DllTrace(DLL_TRACE_ERROR,"SetVideoMode: mode %d is not supported under format %d\n",mode,m_videoFormat); ret = CAM_ERROR_INVALID_VIDEO_SETTINGS; } _exit: DllTrace(DLL_TRACE_EXIT,"EXIT SetVideoMode (%d)\n",ret); return ret; } /**\brief Set the Video Frame Rate * \ingroup camfmr * \param rate The desired frame rate in [0,7] that you wish to set * \return * - CAM_SUCCESS: All good. * - CAM_ERROR_NOT_INITIALIZED: No camera celected and/or camera not initialized * - CAM_ERROR_BUSY: The camera is actively acquiring images * - CAM_ERROR: WriteRegister has failed, use GetLastError() to find out why. * * This function is invalid for Format 7 */ int C1394Camera::SetVideoFrameRate(unsigned long rate) { DWORD dwRet; int ret = CAM_ERROR; DllTrace(DLL_TRACE_ENTER,"ENTER SetVideoFramteRate (%d)\n",rate); if (!m_pName || !m_cameraInitialized) { DllTrace(DLL_TRACE_ERROR,"SetVideoFrameRate: Camera is not initialized\n"); ret = CAM_ERROR_NOT_INITIALIZED; goto _exit; } if(m_hDeviceAcquisition != INVALID_HANDLE_VALUE) { DllTrace(DLL_TRACE_ERROR,"SetVideoFrameRate: Camera is busy\n"); ret = CAM_ERROR_BUSY; goto _exit; } if(m_videoFormat != 7) { if(this->HasVideoFrameRate(m_videoFormat,m_videoMode,rate)) { if(dwRet = WriteQuadlet(0x600, rate << 29)) { DllTrace(DLL_TRACE_ERROR,"SetVideoFrameRate: error %08x on WriteRegister\n",dwRet); ret = CAM_ERROR; } else { m_videoFrameRate = rate; UpdateParameters(); ret = CAM_SUCCESS; } } else { DllTrace(DLL_TRACE_ERROR,"SetVideoFrameRate: rate %d unsupported\n",rate); ret = CAM_ERROR_INVALID_VIDEO_SETTINGS; } } else { DllTrace(DLL_TRACE_ERROR,"SetVideoFramerate: it is not meaningful to set the framerate for format 7\n"); ret = CAM_ERROR_INVALID_VIDEO_SETTINGS; } _exit: DllTrace(DLL_TRACE_EXIT,"EXIT SetVideoFrameRate (%d)\n",ret); return ret; } /**\brief get the current video format. * \ingroup camfmr * \return The current format, -1 if none selected. */ int C1394Camera::GetVideoFormat() { return m_videoFormat; } /**\brief get the current video mode. * \ingroup camfmr * \return The current format, -1 if none selected. */ int C1394Camera::GetVideoMode() { return m_videoMode; } /**\brief get the current video format. * \ingroup camfmr * \return The current format, -1 if none selected. */ int C1394Camera::GetVideoFrameRate() { return m_videoFrameRate; } /**\brief Reads the format register and fills in m_InqVideoFormats * \ingroup camfmr * \return TRUE if the checks were successful, FALSE on a Read error */ BOOL C1394Camera::InquireVideoFormats() { DWORD dwRet; // Read video formats at 0x100 m_InqVideoFormats = 0; if(dwRet = ReadQuadlet(0x100,&m_InqVideoFormats)) { DllTrace(DLL_TRACE_ERROR,"InquireVideoFormats: Error %08x on ReadRegister(0x100)\n",dwRet); return FALSE; } else { DllTrace(DLL_TRACE_CHECK,"InquireVideoFormats: We have 0x%08x\n",m_InqVideoFormats); //return TRUE; ///AAAAAAH! } // Read the current video format at 0x608 if(dwRet = ReadQuadlet(0x608,(unsigned long *) &this->m_videoFormat)) { DllTrace(DLL_TRACE_ERROR,"InquireVideoFormats: error %08x on ReadRegister\n",dwRet); this->m_videoFormat = -1; return FALSE; } else { this->m_videoFormat >>= 29; this->m_videoFormat &= 0x7; DllTrace(DLL_TRACE_CHECK,"InquireVideoFormats: Read current format as %d\n",m_videoFormat); } return TRUE; } /**\brief Check whether the provided camera settings are valid * \ingroup camfmr * \param format The format to check * \return Whether the settings are supported by the camera */ BOOL C1394Camera::HasVideoFormat(unsigned long format) { BOOL bRet; if(format >= 8) { DllTrace(DLL_TRACE_WARNING,"HasVideoFormat: Invalid Format: %d\n",format); return FALSE; } bRet = (m_InqVideoFormats >> (31-format)) & 0x01; // QUIRK Check: All Formats must have at least one valid mode. if(bRet && ((m_InqVideoModes[format] & 0xFF000000) == 0)) { DllTrace(DLL_TRACE_ALWAYS,"HasVideoFormat: QUIRK: Format %d presence in V_FORMAT_INQ (%08x) disagrees with V_MODE_INQ_%d(%08x)\n", format,m_InqVideoFormats,format,m_InqVideoModes[format]); bRet = FALSE; } return bRet; } /**\brief Reads the mode registers and fills in m_InqVideoModes * \ingroup camfmr * \return TRUE if the checks were successful, FALSE on a Read error */ BOOL C1394Camera::InquireVideoModes() { ULONG format; DWORD dwRet; for (format=0; format<8; format++) { m_InqVideoModes[format] = 0xFF000000; if (this->HasVideoFormat(format)) { // inquire video mode for current format DllTrace(DLL_TRACE_CHECK,"InquireVideoModes: Checking Format %d\n",format); if(dwRet = ReadQuadlet(0x180+format*4,&m_InqVideoModes[format])) { DllTrace(DLL_TRACE_ERROR,"InquireVideoModes, Error %08x on ReadRegister(%03x)\n",dwRet,0x180+format*4); return FALSE; } else { DllTrace(DLL_TRACE_CHECK,"InquireVideoModes: We have %08x for format %d\n",m_InqVideoModes[format],format); } } else { m_InqVideoModes[format] = 0; } } // Read the current video mode at 0x604 if(dwRet = ReadQuadlet(0x604,(unsigned long *) &this->m_videoMode)) { DllTrace(DLL_TRACE_ERROR,"InquireVideoModes: error %08x on ReadRegister\n",dwRet); this->m_videoMode = -1; return FALSE; } else { this->m_videoMode >>= 29; this->m_videoMode &= 0x7; DllTrace(DLL_TRACE_CHECK,"InquireVideoModes: Read current Mode as %d\n",m_videoMode); } return TRUE; } /**\brief Check whether the provided camera settings are valid * \ingroup camfmr * \param format The format to check * \param mode The mode to check * \return Whether the settings are supported by the camera */ BOOL C1394Camera::HasVideoMode(unsigned long format, unsigned long mode) { BOOL bRet; if(format >= 8 || mode >= 8) { DllTrace(DLL_TRACE_WARNING,"HasVideoMode: Invalid Format,Mode: %d,%d\n",format,mode); return FALSE; } bRet = (m_InqVideoModes[format] >> (31-mode)) & 0x01; // QUIRK Check: All Modes must have at least one valid framerate. if(format < 3 && bRet && ((m_InqVideoRates[format][mode] & 0xFF000000) == 0)) { DllTrace(DLL_TRACE_ALWAYS, "HasVideoFormat: QUIRK: Mode %d:%d presence in V_MODE_INQ_%d(%08x) disagrees with V_RATE_INQ_%d_%d = %08x\n", format,mode,format,m_InqVideoModes[format],format,mode,m_InqVideoRates[format][mode]); bRet = FALSE; } return bRet; } /**\brief Reads the rate registers and fills in m_InqVideoRates * \ingroup camfmr * \return TRUE if the checks were successful, FALSE on a Read error */ BOOL C1394Camera::InquireVideoRates() { ULONG format, mode; DWORD dwRet; for (format=0; format<8; format++) { for (mode=0; mode<8; mode++) { m_InqVideoRates[format][mode] = 0xFF000000; if(this->HasVideoMode(format,mode)) { // inquire video mode for current format if(dwRet = ReadQuadlet(0x200+format*32+mode*4,&m_InqVideoRates[format][mode])) { DllTrace(DLL_TRACE_ERROR,"InquireVideoRates, Error %08x on ReadRegister(%03x)\n",dwRet,0x200+format*32+mode*4); return FALSE; } else { DllTrace(DLL_TRACE_CHECK,"InquireVideoRates: We have %08x for %d,%d\n",m_InqVideoRates[format][mode],format,mode); if(format <= 2) { // Quirk-Check the rates against m_maxSpeed; ULONG rate; ULONG isomaxBPF= 1000 * m_maxSpeed; ULONG absmaxBPF= 1250 * m_maxSpeed; for(rate=0; rate<8; rate++) { if(this->HasVideoFrameRate(format,mode,rate)) { ULONG BPF = 4 * dc1394GetQuadletsPerPacket(format,mode,rate); if(BPF > isomaxBPF) { if(BPF < absmaxBPF) { DllTrace(DLL_TRACE_ALWAYS,"QUIRK: Camera reports supported mode %d,%d,%d which may work at but otherwise exceeds strict 1394 bus spec at %d00mbps\n", format,mode,rate,m_maxSpeed); } DllTrace(DLL_TRACE_WARNING,"InquireVideoRates: Warning: disabling mode %d,%d,%d which exceeds available bandwidth at %d00mbps\n"); m_InqVideoRates[format][mode] &= ~(0x80000000 >> rate); } } } } } } else { m_InqVideoRates[format][mode] = 0; } } } // Read the current video rate at 0x600 if(dwRet = ReadQuadlet(0x600,(unsigned long *) &this->m_videoFrameRate)) { DllTrace(DLL_TRACE_ERROR,"InquireVideoFrameRates: error %08x on ReadRegister\n",dwRet); this->m_videoFrameRate = -1; return FALSE; } else { this->m_videoFrameRate >>= 29; this->m_videoFrameRate &= 0x7; DllTrace(DLL_TRACE_CHECK,"InquireVideoFrameRates: Read current FrameRate as %d\n",m_videoFrameRate); } return TRUE; } /**\brief Check whether the provided camera settings are valid * \ingroup camfmr * \param format The format to check * \param mode The mode to check * \param rate The rate to check * \return Whether the settings are supported by the camera * * The notion of video frame rate does not apply to any but the first three video formats */ BOOL C1394Camera::HasVideoFrameRate(unsigned long format, unsigned long mode, unsigned long rate) { if(format >= 3 || mode >= 8 || rate >= 8) { DllTrace(DLL_TRACE_WARNING,"HasVideoFrameRate: Invalid Format,Mode,Rate: %d,%d,%d\n",format,mode,rate); return FALSE; } return (m_InqVideoRates[format][mode] >> (31-rate)) & 0x01; } /**\brief Retrieve the width and height of the currently configured video mode * \ingroup camfmr * \param pWidth Receives the width, in pixels, of the current video mode, zero if none selected * \param pHeight Receives the height, in pixels, of the current video mode, zero if none selected */ void C1394Camera::GetVideoFrameDimensions(unsigned long *pWidth, unsigned long *pHeight) { if(!pWidth || !pHeight) { DllTrace(DLL_TRACE_ERROR,"GetVideoFrameDimensions: Invalid Argument(s) %08x %08x\n",pWidth,pHeight); } else { *pWidth = m_width; *pHeight = m_height; } } /**\brief retrieve the effective data depth, in bits of the current video mode * \param depth Where to put it * * For IIDC 1.31 cameras, this tells us basically how many bits per channel * in the image data are actually representative of the image. For instance, * many 16-bit formats actually produce 12-bit data */ void C1394Camera::GetVideoDataDepth(unsigned short *depth) { if(depth == NULL) return; switch(this->m_videoFormat) { case 0: case 1: case 2: if(this->m_StatusVideoDepth != 0) { *depth = (unsigned short)((this->m_StatusVideoDepth >> 24) & 0x00FF); } else { if( this->m_colorCode == COLOR_CODE_Y16 || this->m_colorCode == COLOR_CODE_RGB16 || this->m_colorCode == COLOR_CODE_RAW16 || this->m_colorCode == COLOR_CODE_Y16_SIGNED || this->m_colorCode == COLOR_CODE_RGB16_SIGNED) *depth = 16; else *depth = 8; } break; case 7: this->m_pControlSize->GetDataDepth(depth); break; default: *depth = 0; } } /**\brief Maintains internal consistency of variables surrounding current video settings * \param UpdateOnly If TRUE, then no active changes are made to the settings, values are simply * retrieved. Default is FALSE, causing a full sanity enforcement. * \ingroup camfmr * * This ensures that a valid combination of format,mode,and rate are selected and * populates m_width, m_height, m_maxBytes, m_maxBufferSize accordingly. Since this both * calls and is called by the various SetVideoBlah functions and the ControlSize class, care * must be take to avoid recursive stupidity. */ void C1394Camera::UpdateParameters(BOOL UpdateOnly) { VIDEO_MODE_DESCRIPTOR desc; ULONG qpp; if(!UpdateOnly && !CheckVideoSettings()) { int i; DllTrace(DLL_TRACE_WARNING, "UpdateParameters: Video settings (%d,%d,%d) are invalid, seeking nearest neighbor\n", m_videoFormat, m_videoMode, m_videoFrameRate); if(!this->HasVideoFormat(m_videoFormat)) { for(i=0; i<8; i++) { if(i != 6 && this->HasVideoFormat(i)) { this->SetVideoFormat(i); break; } } return; } if(!this->HasVideoMode(m_videoFormat,m_videoMode)) { for(i=0; i<8; i++) { if(this->HasVideoMode(m_videoFormat,i)) { this->SetVideoMode(i); break; } } return; } if(m_videoFormat != 7) { if(!this->HasVideoFrameRate(m_videoFormat,m_videoMode,m_videoFrameRate)) { for(i=0; i<8; i++) { if(this->HasVideoFrameRate(m_videoFormat,m_videoMode,i)) { this->SetVideoFrameRate(i); break; } } return; } } else { m_videoFrameRate = -1; } if(!CheckVideoSettings()) { DllTrace(DLL_TRACE_ERROR,"UpdateParameters: Unable to select a valid format!\n"); return; } DllTrace(DLL_TRACE_CHECK,"UpdateParameters: Auto-selected %d,%d,%d\n", m_videoFormat,m_videoMode,m_videoFrameRate); } // now update the critical members if (m_videoFormat != 7) { if(dc1394GetModeDescriptor(m_videoFormat,m_videoMode,&desc) < 0) m_width = m_height = 0; m_width = desc.width; m_height = desc.height; m_colorCode = desc.colorcode; m_maxBufferSize = dc1394GetBufferSize(m_videoFormat, m_videoMode); qpp = dc1394GetQuadletsPerPacket(m_videoFormat,m_videoMode,m_videoFrameRate); m_maxBytes = 4 * qpp; // update the video depth register this->m_StatusVideoDepth = 0; this->ReadQuadlet(0x0630,&this->m_StatusVideoDepth); } else { unsigned short w,h,bpp; unsigned long ppf,bpf,n; unsigned long offset = this->m_InqVideoRates[this->m_videoFormat][this->m_videoMode]; offset <<= 2; offset |= 0xf0000000; if(!UpdateOnly && m_pControlSize->SetOffset(offset) != CAM_SUCCESS) { DllTrace(DLL_TRACE_ERROR,"UpdateParameters: Error on ControlSize::SetOffset"); ///\todo: something smarter in UpdateParameters when ControlSize::SetOffset fails return; } this->m_pControlSize->GetSize(&w,&h); this->m_pControlSize->GetBytesPerPacket(&bpp); this->m_pControlSize->GetPacketsPerFrame(&ppf); this->m_pControlSize->GetBytesPerFrame(&bpf,NULL); // what if we have images > 4GB? this->m_pControlSize->GetColorCode(&this->m_colorCode); // now for a little sanity checking for quirky cameras n = dc1394GetBitsPerPixel(this->m_colorCode); n *= w * h; n /= 8; if(bpf < n) { DllTrace(DLL_TRACE_ALWAYS, "QUIRK: format 7 reported bytes per frame (%d) is less than computed bytes per frame (%d)\n", bpf,n); bpf = n; } n = (bpf + bpp - 1)/bpp; if(ppf != n) { DllTrace(DLL_TRACE_ALWAYS, "QUIRK: format 7 reported packets per frame (%d) is incorrect (should be %d)\n", ppf,n); ppf = n; } m_maxBytes = bpp; m_width = w; m_height = h; m_maxBufferSize = bpp * ppf; DllTrace(DLL_TRACE_CHECK,"UpdateParameters: Format 7 (%dx%d,%d:%d)\n", w,h,bpp * ppf, bpp); } DllTrace(DLL_TRACE_CHECK,"UpdateParameters: Using %dx%d, %d:%d\n", m_width,m_height,m_maxBufferSize,m_maxBytes); } /** \brief Check to make sure the selected video settings are valid * \return boolean true if things are okay */ bool C1394Camera::CheckVideoSettings() { bool bRet = false; if(m_cameraInitialized) { if(m_videoFormat != 7) bRet = (this->HasVideoFrameRate(m_videoFormat,m_videoMode,m_videoFrameRate) == TRUE); else bRet = (this->HasVideoMode(m_videoFormat,m_videoMode) == TRUE); // check the status register for the hell of it if(StatusVideoErrors(TRUE) && bRet) { DllTrace(DLL_TRACE_WARNING,"CheckVideoSettings: WARNING: Camera is angry about %d,%d,%d, but video flags disagree\n", m_videoFormat, m_videoMode, m_videoFrameRate); } } return bRet; } /**\brief Return whether there are video errors according to the error register * \param Refresh Boolean whether to re-read the registers or simply probe the bits * \return boolean state of the Video Error Register, if Valid */ bool C1394Camera::StatusVideoErrors(BOOL Refresh) { if(!this->m_cameraInitialized || (this->m_InqBasicFunc & 0x40000000) == 0) return false; if(Refresh == TRUE) { if(this->ReadQuadlet(0x628,&this->m_StatusVideoError) != CAM_SUCCESS) return false; } return (m_StatusVideoError & 0x80000000) != 0; }
[ "yangchuck@gmail.com" ]
yangchuck@gmail.com
bcb23788265b1c147d12b7549a090326f5708646
91f0a562bd2672febf99040d4bca1b8fcfd2c179
/misakalovelibrary/src/main/cpp/libeditcore/video_effect_core.h
7d5092361fd7159a1ba71fbef7758c826462038b
[]
no_license
JabamiLight/MisakaLove
5af77bfb77bbc628e356532b2397caa13115ddc1
c2d9a7426345141cfc8440a710881f56f8f4ebb8
refs/heads/master
2020-03-23T09:56:07.448090
2019-02-12T03:02:49
2019-02-12T03:02:49
141,415,756
1
2
null
null
null
null
UTF-8
C++
false
false
1,362
h
// // Created by TY on 2018/7/25. // #ifndef MISAKALOVE_VIDEO_EFFECT_PROGRAM_H #define MISAKALOVE_VIDEO_EFFECT_PROGRAM_H #define LOG_TAG "VideoEffectCore" #include "../opengl/program.h" #include <list> #include <GLES2/gl2ext.h> #include "common/camera_preview_program.h" #include "../libcommon/CommonTools.h" #include "../3rdparty/facedet/detector.h" #include "filter/cool_filter.h" #include "../3rdparty/facedet/face.h" #include "beauty/beauty_filter.h" #include <map> #define EFFECT_FILTER 1 #define EFFECT_BEAUTY 2 #define EFFECT_STICKER 3 using namespace std; class VideoEffectCore { private: map<int,Program*> filterPrograms; Program* copyCommonProgram; GLuint* processTextureIds; GLuint cameraTextureId; uint8_t processTextureIndex=0; GLuint FBO; jint degress; bool isVFilp; int textureWidth,textureHeight; public: void init(jint textureWidth, bool textureHeight, int i, int i1); void initTexture(); void initPbo(); void process(); void addFilter(Program *program, int i); GLuint getAfterTextureId(); GLuint getESTextureId(); virtual ~VideoEffectCore(); void clearFilter(); /** * 设置人脸数据给program */ void setFaceInfo(Face* face); void *ptr; void setBeautyPara(BeautyPara &i); }; #endif //MISAKALOVE_VIDEO_EFFECT_PROGRAM_H
[ "568478312@qq.com" ]
568478312@qq.com
46b7fc5ae6a4000d2c5040e174a45462fa3c98cc
1c711f642328e5195cbbb61760a83f4a8ff6977a
/assets/src/AtCoder/238/c.cpp
723b81498cd4ecab58366118d69ed5d7e5bc9a6f
[]
no_license
liuxueyang/liuxueyang.github.io
29d85b989e5938e964b70c9616a418e13003212e
86e10cb6137d930c2ac81f2ae20318eb1354f2b5
refs/heads/master
2023-03-07T13:06:17.366563
2023-03-01T14:41:41
2023-03-01T14:41:41
17,851,538
2
0
null
2023-01-31T04:00:56
2014-03-18T02:46:21
C++
UTF-8
C++
false
false
1,864
cpp
// Date: Sat Feb 12 15:25:13 2022 #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <climits> #include <iostream> #include <sstream> #include <string> #include <vector> #include <queue> #include <stack> #include <map> #include <set> #include <algorithm> #include <utility> #include <functional> using namespace std; const int INF = 0x3f3f3f3f, MOD = 1e9 + 7; const double eps = 1e-8; const int dir[8][2] = { {0, 1}, {0, -1}, {1, 0}, {-1, 0}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}, }; typedef long long ll; typedef unsigned long long ull; typedef vector<int> VI; typedef pair<int, int> PII; const ull Pr = 131; #define LN ListNode #define LNP ListNode* #define TN TreeNode #define TNP TreeNode* #ifdef _DEBUG struct ListNode { int val; ListNode *next; ListNode() : val(0), next(nullptr) {} ListNode(int val) : val(val), next(nullptr) {} ListNode(int val, ListNode *next) : val(val), next(next) {} }; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; #endif const ull M = 998244353; ull get(ull n, ull a0) { ull res = 0; res = (n % M) * (a0 % M) % M; if (n & 1) { res += ((n - 1) / 2 % M) * (n % M) % M; } else { res += (n / 2 % M) * ((n - 1) % M) % M; } return res % M; } int main(void) { #ifdef _DEBUG freopen("c.in", "r", stdin); #endif std::ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); ull n; while (cin >> n) { ull k = 10, k1 = 1, res = 0; while (k <= n) { res = (res + get(k - k1, 1)) % M; k1 = k; k *= 10; } res = (res + get(n - k1 + 1, 1)) % M; cout << res << endl; } return 0; }
[ "liuxueyang457@gmail.com" ]
liuxueyang457@gmail.com
5c812ce865e1a9d3224ebbcc21aecec818b84fa9
f8f903486ebca5bfa1f304c0d4308c494f4331b1
/test/keyframe_test.cpp
2a62ed453ee705630a4aede0e7c69779249a0ef6
[]
no_license
utomore/ncuipc
530ad1a7aa8389b24256d8413cd5afb512f72dcf
6301d63ea8ac7db679dee9b5a0f9e2a0b6266f7c
refs/heads/master
2021-09-20T23:49:13.344028
2018-08-17T03:35:17
2018-08-17T03:35:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,123
cpp
#include "tako/common_include.hpp" #include <string> #include <vector> #include <iostream> //DBoW3 #include "DBoW3/DBoW3.h" using namespace std; using namespace cv; int main(int argc, char **argv) { //read the image cout << "read images" << endl; vector<Mat> images; for (int i = 0; i < 10; i++) { string path = "./data2/"+to_string(i+1)+".png"; images.push_back( imread(path, 0) ); } //detect ORB features cout<<"detecting ORB feature " <<endl; Ptr< Feature2D > detector = ORB::create(); vector<Mat> descriptors; cout<<"detecting image ...."<<endl; for(Mat& image:images) { cout<<"image run ..." <<endl; vector<KeyPoint> keypoints; Mat descriptor; detector->detectAndCompute( image, Mat(), keypoints, descriptor); descriptors.push_back(descriptor); } //create vocabulary cout<< " creating Vocabulary " <<endl; DBoW3::Vocabulary vocab; vocab.create( descriptors ); cout<<"vocabulary info:" <<vocab<<endl; vocab.save("vocabulary.yml.gz"); cout<<"done"<<endl; return 0 ; }
[ "lhm.stu@gmail.com" ]
lhm.stu@gmail.com
cdd28cce38118074ab91be4cad7bfbb4cbe6791e
254cb2f933e9ead5df3c36a59c7280db481ec885
/TapToExit/main.cpp
d3860ace33d97eec1853e10522078951a107783a
[ "MIT" ]
permissive
KennFatt/Kyoote
d253953ab1b4dc5dd7f0802474fd828f70223529
7b9ec2ef980e8a39fb76662c6259c8c77019b97b
refs/heads/master
2021-04-08T00:17:27.326682
2020-03-20T17:46:55
2020-03-20T17:46:55
248,719,263
0
0
null
null
null
null
UTF-8
C++
false
false
98
cpp
#include "src/application.h" int main(int argc, char **argv) { Application app(argc, argv); }
[ "clashofklen@gmail.com" ]
clashofklen@gmail.com
23d5832e4ae7cfe5443ef701961f082f0e23e33c
ee3039b27532d09c0c435ea7b92e29c70246c66e
/opencv/learnOpencv/001-030/029-快速的图像边缘滤波算法.cpp
73c5cea64d53d71177f00f805e03d2e8559648d8
[]
no_license
Alvazz/fanfuhan_ML_OpenCV
e8b37acc406462b9aaca9c5e6844d1db5aa3c944
dacfdaf87356e857d3ff18c5e0a4fd5a50855324
refs/heads/master
2022-04-05T06:15:31.778227
2020-02-07T01:40:07
2020-02-07T01:40:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
421
cpp
#include <iostream> #include <opencv2/opencv.hpp> using namespace std; using namespace cv; /* * 快速的图像边缘滤波算法 */ int main() { Mat src = imread("../images/test.png"); if (src.empty()) { cout << "could not load image.." << endl; } imshow("input", src); Mat dst; edgePreservingFilter(src, dst, 1, 60, 0.44); imshow("result", dst); waitKey(0); return 0; }
[ "gitea@fake.local" ]
gitea@fake.local
3af2f1c6176db72ee508d728cdae2e4b979c4744
2bc4762a1a424f195c9b20b6d89d14763f11b010
/playlist.cpp
8a3b67b0630965cc78ead1b1ce4f09376a82f066
[]
no_license
Danile71/winsaplayer_sources
a6b66ceaca6514418980fa7655a9af8a09a5b0e5
ca607d79788b10ed6775b916497d6b9866e9c0f9
refs/heads/master
2021-08-06T10:31:16.043194
2017-11-05T07:27:53
2017-11-05T07:27:53
109,423,755
0
0
null
null
null
null
UTF-8
C++
false
false
961
cpp
#include "include/playlist.h" #define null "" __fastcall TXml::TXml() { List=new TStringList(); PList=new TStringList(); } AnsiString __fastcall TXml::GetAutor(AnsiString str) { AnsiString ret,strt="no name"; if(str.Pos("<title>")) { ret=""; for(int i=str.Pos("<title>")+7;i<str.Pos("</title>");i++)ret=ret+str[i]; return ret; } else return strt; } void __fastcall TXml::AddSong(AnsiString str) { AnsiString newstr; if(str.Pos("media src=")) { newstr=null; for(int a=str.Pos("media src=")+11;a<str.Pos("/>")-1;a++) { newstr=newstr+str[a]; }//for media if(newstr.Pos("&apos;")) {newstr.Insert("'",newstr.Pos("&apos;"));newstr.Delete(newstr.Pos("&apos;"),6);} PList->Add(newstr); }//if src //PList->Add(); } void __fastcall TXml::LoadFromFile(AnsiString FileName) { AnsiString str; List->LoadFromFile(FileName); for(int i=0;i<List->Count;i++) { //Autor=GetAutor(List->Strings[i]); AddSong(List->Strings[i]); } }
[ "danile71@gmail.com" ]
danile71@gmail.com