blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9382e63d573a91866cf1586b47641464a040980b | ae17935a125a7bc02ff9f3f3b48842f27a633063 | /apps/server/main2.cpp | 7358f590e5155722f49326db29e4cb8c28e37a10 | [
"MIT"
] | permissive | JensKlimke/cmake | 3d9b82ec1e363c6919cd51b75137bd150292ed52 | 929314b194c60816e19a3b2911ee9f238f0d168a | refs/heads/master | 2021-07-13T15:41:13.623734 | 2020-07-15T06:02:34 | 2020-07-15T06:02:34 | 183,462,298 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,092 | cpp | #include <iostream>
#include <cxxopts.hpp>
int main(int argc, char* argv[]) {
cxxopts::Options options("MyProgram", "One line description of MyProgram");
options.add_options()
("d,debug", "Enable debugging") // a bool parameter
("i,integer", "Int param", cxxopts::value<int>())
("f,file", "File name", cxxopts::value<std::string>())
("v,verbose", "Verbose output", cxxopts::value<bool>()->default_value("false"))
("h,help", "Show help")
;
auto result = options.parse(argc, argv);
if (result.count("help"))
{
std::cout << options.help() << std::endl;
exit(0);
}
bool debug = result["debug"].as<bool>();
std::string bar;
if (result.count("file"))
bar = result["file"].as<std::string>();
int foo = result["integer"].as<int>();
std::cout << "debug: " << (debug ? "yes" : "no") << std::endl;
std::cout << "bar: " << bar << std::endl;
std::cout << "foo: " << foo << std::endl;
std::cout << "Hello, World!" << std::endl;
return 0;
} | [
"jens.klimke@rwth-aachen.de"
] | jens.klimke@rwth-aachen.de |
bcd367f3c02a4ab7d6f1a504dda71aca10da0d71 | 2bd8497a36b527157834ed1de87ee76a7cb8b6bb | /MCPManager.cpp | b9d7cd29585ec5821f02de5cbaf0dd6fae6884a1 | [] | no_license | beaumontmike/737-Max-8-Cockpit-Plugin | 7d48d18c60035b7c76c6593711e100b8ab4e4c1b | a8e73ccc853a08e9892300463a774919f40e8a94 | refs/heads/master | 2020-04-16T23:09:44.095035 | 2019-01-16T09:29:48 | 2019-01-16T09:29:48 | 166,000,752 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,635 | cpp | //
// MCP Manager.cpp
// 737_Cockpit_Plugin
//
// Created by Michael Beaumont on 2019-01-10.
//
#include "MCPManager.hpp"
namespace Cockpit {
MCPManager::MCPManager() {
return;
}
MCPManager::MCPManager(SerialPort *t_port) {
this->m_serial_port = t_port;
}
void MCPManager::serialBegin() {
this->m_serial_port->openPort();
}
float MCPManager::deferredInit() {
// Init Commands
this->m_xp_commands.push_back(Command("laminar/B738/autopilot/flight_director_toggle", "AP_FD_CP_PRESS"));
this->m_xp_commands.push_back(Command("laminar/B738/autopilot/flight_director_fo_toggle", "AP_FD_FO_PRESS"));
this->m_xp_commands.push_back(Command("laminar/B738/autopilot/autothrottle_arm_toggle", "AP_ATH_ARM_PRESS"));
this->m_xp_commands.push_back(Command("laminar/B738/autopilot/speed_press", "AP_ATH_SPD_PRESS"));
this->m_xp_commands.push_back(Command("laminar/B738/autopilot/n1_press", "AP_ATH_N1_PRESS"));
this->m_xp_commands.push_back(Command("laminar/B738/autopilot/lvl_chg_press", "AP_ATH_FLC_PRESS"));
this->m_xp_commands.push_back(Command("laminar/B738/autopilot/hdg_sel_press", "AP_HDG_SEL_PRESS"));
this->m_xp_commands.push_back(Command("laminar/B738/autopilot/lnav_press", "AP_HDG_LNAV_PRESS"));
this->m_xp_commands.push_back(Command("sim/autopilot/altitude_hold", "AP_ALT_HLD_PRESS"));
this->m_xp_commands.push_back(Command("sim/autopilot/alt_vs", "AP_ALT_VSPD_PRESS"));
this->m_xp_commands.push_back(Command("laminar/B738/autopilot/cmd_a_press", "AP_CMD_A_PRESS"));
this->m_xp_commands.push_back(Command("laminar/B738/autopilot/cmd_b_press", "AP_CMD_B_PRESS"));
this->m_xp_commands.push_back(Command("laminar/B738/autopilot/cws_a_press", "AP_CWS_A_PRESS"));
this->m_xp_commands.push_back(Command("laminar/B738/autopilot/cws_b_press", "AP_CWS_B_PRESS"));
// Init Integer Datarefs
this->m_xp_int_datarefs.push_back(IntegerDataRef("laminar/B738/autopilot/cmd_a_status", this->m_serial_port, "AP_CMD_A"));
this->m_xp_int_datarefs.push_back(IntegerDataRef("laminar/B738/autopilot/cmd_b_status", this->m_serial_port,"AP_CMD_B"));
this->m_xp_int_datarefs.push_back(IntegerDataRef("laminar/B738/autopilot/hdg_sel_status", this->m_serial_port,"AP_HDG_SEL"));
this->writeFlightLoop(true);
return 0;
}
float MCPManager::readFlightLoop() {
if(this->m_serial_port->hasData()) {
// Reading data from serial device.
std::string data(this->m_serial_port->readData());
// Loop through commands and look for a match, break loop if found.
for(int inx = 0; inx < this->m_xp_commands.size(); ++inx) {
if(this->m_xp_commands[inx].parse(data)) break;
}
}
return -1; // Do every flightLoop call.
};
float MCPManager::writeFlightLoop(bool t_override_change_check) {
if(this->m_serial_port->writeable()) {
// Loop through datarefs, which will update the panel if necessary.
for(int inx = 0; inx < this->m_xp_int_datarefs.size(); ++inx) {
this->m_xp_int_datarefs[inx].updatePanel(t_override_change_check);
}
}
return -1;
}
} // namespace Cockpit
| [
"beaumontmike@outlook.com"
] | beaumontmike@outlook.com |
3a121fca7ee97613922d9ccc6da582ec364c8429 | 48b23a49c093e8303b90ed6335e61d64362e40af | /pavlov-viacheslav/src/pavlov03/src/GraphScreen.cpp | 38c5e9620cc6a9a6d8d67828898c0a08e70e0194 | [
"MIT"
] | permissive | zeienko-vitalii/se-cpp | e5b7d1d8800e2a5c777e76cc9cfd30d898400282 | 54a5dfb2e98af099fbfaef129a7fe03a7b815d6f | refs/heads/master | 2021-08-15T15:22:30.559011 | 2017-11-17T22:37:45 | 2017-11-17T22:37:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,154 | cpp | /**
* @file GraphScreen.cpp
* GraphScreen functions realization.
* @author pavlov-vs
* @version 0.1.1
* @date 2017.09.09
*/
#include<iostream>
#include "GraphScreen.h"
GraphScreen::GraphScreen() {
cout << "GraphScreen default constructor\n";
}
GraphScreen::~GraphScreen() {
cout << "GraphScreen destructor\n";
}
void GraphScreen::setDataSource(Window* data) {
this->data = data;
}
void GraphScreen::printData(const Window& data) {
for (int i = 0; i < data.width(); i++)
cout << "1";
for (int i = 0; i < data.height(); i++) {
cout << "\n1";
for (int j = 1; j < data.width() - 1; j++)
cout << " ";
cout << "1";
}
cout << "\n";
for (int i = 0; i < data.width(); i++)
cout << "1";
cout << "\n";
}
void GraphScreen::printData() {
printData(*this->data);
}
void GraphScreen::showHeader() {
cout << "\n|--------------------------\n";
cout << "Graph screen output\n";
}
void GraphScreen::showContent() {
cout << "WindowId" << (*this->data).getWindowId() << endl;
printData();
}
void GraphScreen::showFooter() {
cout << "|--------------------------\n\n";
}
| [
"slavutichp@gmail.com"
] | slavutichp@gmail.com |
accd1cf6cb946433f7de54c1a0d8eba9167e26d8 | 2f45b99b684f62b2e9413a302a22a7677c22580c | /external/chromium/base/lazy_instance.h | 7b1bdc41f241f4a558557005f4a10ed1a1087df7 | [
"BSD-3-Clause"
] | permissive | b2gdev/Android-JB-4.1.2 | 05e15a4668781cd9c9f63a1fa96bf08d9bdf91de | e66aea986bbf29ff70e5ec4440504ca24f8104e1 | refs/heads/user | 2020-04-06T05:44:17.217452 | 2018-04-13T15:43:57 | 2018-04-13T15:43:57 | 35,256,753 | 3 | 12 | null | 2020-03-09T00:08:24 | 2015-05-08T03:32:21 | null | UTF-8 | C++ | false | false | 6,730 | h | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// The LazyInstance<Type, Traits> class manages a single instance of Type,
// which will be lazily created on the first time it's accessed. This class is
// useful for places you would normally use a function-level static, but you
// need to have guaranteed thread-safety. The Type constructor will only ever
// be called once, even if two threads are racing to create the object. Get()
// and Pointer() will always return the same, completely initialized instance.
// When the instance is constructed it is registered with AtExitManager. The
// destructor will be called on program exit.
//
// LazyInstance is completely thread safe, assuming that you create it safely.
// The class was designed to be POD initialized, so it shouldn't require a
// static constructor. It really only makes sense to declare a LazyInstance as
// a global variable using the base::LinkerInitialized constructor.
//
// LazyInstance is similar to Singleton, except it does not have the singleton
// property. You can have multiple LazyInstance's of the same type, and each
// will manage a unique instance. It also preallocates the space for Type, as
// to avoid allocating the Type instance on the heap. This may help with the
// performance of creating the instance, and reducing heap fragmentation. This
// requires that Type be a complete type so we can determine the size.
//
// Example usage:
// static LazyInstance<MyClass> my_instance(base::LINKER_INITIALIZED);
// void SomeMethod() {
// my_instance.Get().SomeMethod(); // MyClass::SomeMethod()
//
// MyClass* ptr = my_instance.Pointer();
// ptr->DoDoDo(); // MyClass::DoDoDo
// }
#ifndef BASE_LAZY_INSTANCE_H_
#define BASE_LAZY_INSTANCE_H_
#pragma once
#include <new> // For placement new.
#include "base/atomicops.h"
#include "base/base_api.h"
#include "base/basictypes.h"
#include "base/third_party/dynamic_annotations/dynamic_annotations.h"
#include "base/threading/thread_restrictions.h"
namespace base {
template <typename Type>
struct DefaultLazyInstanceTraits {
static const bool kAllowedToAccessOnNonjoinableThread = false;
static Type* New(void* instance) {
// Use placement new to initialize our instance in our preallocated space.
// The parenthesis is very important here to force POD type initialization.
return new (instance) Type();
}
static void Delete(void* instance) {
// Explicitly call the destructor.
reinterpret_cast<Type*>(instance)->~Type();
}
};
template <typename Type>
struct LeakyLazyInstanceTraits {
static const bool kAllowedToAccessOnNonjoinableThread = true;
static Type* New(void* instance) {
return DefaultLazyInstanceTraits<Type>::New(instance);
}
// Rather than define an empty Delete function, we make Delete itself
// a null pointer. This allows us to completely sidestep registering
// this object with an AtExitManager, which allows you to use
// LeakyLazyInstanceTraits in contexts where you don't have an
// AtExitManager.
static void (*Delete)(void* instance);
};
template <typename Type>
void (*LeakyLazyInstanceTraits<Type>::Delete)(void* instance) = NULL;
// We pull out some of the functionality into a non-templated base, so that we
// can implement the more complicated pieces out of line in the .cc file.
class BASE_API LazyInstanceHelper {
protected:
enum {
STATE_EMPTY = 0,
STATE_CREATING = 1,
STATE_CREATED = 2
};
explicit LazyInstanceHelper(LinkerInitialized /*unused*/) {/* state_ is 0 */}
// Declaring a destructor (even if it's empty) will cause MSVC to register a
// static initializer to register the empty destructor with atexit().
// Check if instance needs to be created. If so return true otherwise
// if another thread has beat us, wait for instance to be created and
// return false.
bool NeedsInstance();
// After creating an instance, call this to register the dtor to be called
// at program exit and to update the state to STATE_CREATED.
void CompleteInstance(void* instance, void (*dtor)(void*));
base::subtle::Atomic32 state_;
private:
DISALLOW_COPY_AND_ASSIGN(LazyInstanceHelper);
};
template <typename Type, typename Traits = DefaultLazyInstanceTraits<Type> >
class LazyInstance : public LazyInstanceHelper {
public:
explicit LazyInstance(LinkerInitialized x) : LazyInstanceHelper(x) { }
// Declaring a destructor (even if it's empty) will cause MSVC to register a
// static initializer to register the empty destructor with atexit().
Type& Get() {
return *Pointer();
}
Type* Pointer() {
if (!Traits::kAllowedToAccessOnNonjoinableThread)
base::ThreadRestrictions::AssertSingletonAllowed();
// We will hopefully have fast access when the instance is already created.
if ((base::subtle::NoBarrier_Load(&state_) != STATE_CREATED) &&
NeedsInstance()) {
// Create the instance in the space provided by |buf_|.
instance_ = Traits::New(buf_);
// Traits::Delete will be null for LeakyLazyInstanceTraits
void (*dtor)(void*) = Traits::Delete;
CompleteInstance(this, (dtor == NULL) ? NULL : OnExit);
}
// This annotation helps race detectors recognize correct lock-less
// synchronization between different threads calling Pointer().
// We suggest dynamic race detection tool that "Traits::New" above
// and CompleteInstance(...) happens before "return instance_" below.
// See the corresponding HAPPENS_BEFORE in CompleteInstance(...).
ANNOTATE_HAPPENS_AFTER(&state_);
return instance_;
}
bool operator==(Type* p) {
switch (base::subtle::NoBarrier_Load(&state_)) {
case STATE_EMPTY:
return p == NULL;
case STATE_CREATING:
return static_cast<int8*>(static_cast<void*>(p)) == buf_;
case STATE_CREATED:
return p == instance_;
default:
return false;
}
}
private:
// Adapter function for use with AtExit. This should be called single
// threaded, so don't use atomic operations.
// Calling OnExit while the instance is in use by other threads is a mistake.
static void OnExit(void* lazy_instance) {
LazyInstance<Type, Traits>* me =
reinterpret_cast<LazyInstance<Type, Traits>*>(lazy_instance);
Traits::Delete(me->instance_);
me->instance_ = NULL;
base::subtle::Release_Store(&me->state_, STATE_EMPTY);
}
int8 buf_[sizeof(Type)]; // Preallocate the space for the Type instance.
Type *instance_;
DISALLOW_COPY_AND_ASSIGN(LazyInstance);
};
} // namespace base
#endif // BASE_LAZY_INSTANCE_H_
| [
"ruvindad@zone24x7.com"
] | ruvindad@zone24x7.com |
74497d5e1dc25c15110a148d01a07e3abf39f614 | 287072b999b3221210071237b1d67d02855cdae5 | /Lab_2/src_A/pipeline_checkpoint.cpp | de9c5137d1767c90a4a3ffc4c8dc14a124c932d1 | [] | no_license | bbruen3/ECE6100 | c66689bfb6f639079b45dca0b4848960150b7207 | 1dbd5308bf56615de238b303d87ccf1cf4f0a79a | refs/heads/master | 2023-08-13T18:17:37.505101 | 2021-10-07T03:59:00 | 2021-10-07T03:59:00 | 414,451,885 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,755 | cpp | // --------------------------------------------------------------------- //
// You will need to modify this file. //
// You may add any code you need, as long as you correctly implement the //
// required pipe_cycle_*() functions already listed in this file. //
// In part B, you will also need to implement pipe_check_bpred(). //
// --------------------------------------------------------------------- //
// pipeline.cpp
// Implements functions to simulate a pipelined processor.
#include "pipeline.h"
#include <cstdlib>
#include <stdio.h>
#include <unistd.h>
#include <iostream>
/**
* Read a single trace record from the trace file and use it to populate the
* given fetch_op.
*
* You should not modify this function.
*
* @param p the pipeline whose trace file should be read
* @param fetch_op the PipelineLatch struct to populate
*/
void pipe_get_fetch_op(Pipeline *p, PipelineLatch *fetch_op)
{
TraceRec *trace_rec = &fetch_op->trace_rec;
uint8_t *trace_rec_buf = (uint8_t *)trace_rec;
size_t bytes_read_total = 0;
ssize_t bytes_read_last = 0;
size_t bytes_left = sizeof(*trace_rec);
// Read a total of sizeof(TraceRec) bytes from the trace file.
while (bytes_left > 0)
{
bytes_read_last = read(p->trace_fd, trace_rec_buf, bytes_left);
if (bytes_read_last <= 0)
{
// EOF or error
break;
}
trace_rec_buf += bytes_read_last;
bytes_read_total += bytes_read_last;
bytes_left -= bytes_read_last;
}
// Check for error conditions.
if (bytes_left > 0 || trace_rec->op_type >= NUM_OP_TYPES)
{
fetch_op->valid = false;
p->halt_op_id = p->last_op_id;
if (p->last_op_id == 0)
{
p->halt = true;
}
if (bytes_read_last == -1)
{
fprintf(stderr, "\n");
perror("Couldn't read from pipe");
return;
}
if (bytes_read_total == 0)
{
// No more trace records to read
return;
}
// Too few bytes read or invalid op_type
fprintf(stderr, "\n");
fprintf(stderr, "Error: Invalid trace file\n");
return;
}
// Got a valid trace record!
fetch_op->valid = true;
fetch_op->stall = false;
fetch_op->is_mispred_cbr = false;
fetch_op->op_id = ++p->last_op_id;
}
/**
* Allocate and initialize a new pipeline.
*
* You should not need to modify this function.
*
* @param trace_fd the file descriptor from which to read trace records
* @return a pointer to a newly allocated pipeline
*/
Pipeline *pipe_init(int trace_fd)
{
printf("\n** PIPELINE IS %d WIDE **\n\n", PIPE_WIDTH);
// Allocate pipeline.
Pipeline *p = (Pipeline *)calloc(1, sizeof(Pipeline));
// Initialize pipeline.
p->trace_fd = trace_fd;
p->halt_op_id = (uint64_t)(-1) - 3;
// Allocate and initialize a branch predictor if needed.
if (BPRED_POLICY != BPRED_PERFECT)
{
p->b_pred = new BPred(BPRED_POLICY);
}
return p;
}
/**
* Print out the state of the pipeline latches for debugging purposes.
*
* You may use this function to help debug your pipeline implementation, but
* please remove calls to this function before submitting the lab.
*
* @param p the pipeline
*/
void pipe_print_state(Pipeline *p)
{
printf("\n--------------------------------------------\n");
printf("Cycle count: %lu, retired instructions: %lu\n",
(unsigned long)p->stat_num_cycle,
(unsigned long)p->stat_retired_inst);
// Print table header
for (uint8_t latch_type = 0; latch_type < NUM_LATCH_TYPES; latch_type++)
{
switch (latch_type)
{
case IF_LATCH:
printf(" IF: ");
break;
case ID_LATCH:
printf(" ID: ");
break;
case EX_LATCH:
printf(" EX: ");
break;
case MA_LATCH:
printf(" MA: ");
break;
default:
printf(" ------ ");
}
}
printf("\n");
// Print row for each lane in pipeline width
for (uint8_t i = 0; i < PIPE_WIDTH; i++)
{
for (uint8_t latch_type = 0; latch_type < NUM_LATCH_TYPES;
latch_type++)
{
if (p->pipe_latch[latch_type][i].valid)
{
printf(" %6lu ",
(unsigned long)p->pipe_latch[latch_type][i].op_id);
}
else
{
printf(" ------ ");
}
}
printf("\n");
}
printf("\n");
}
/**
* Simulate one cycle of all stages of a pipeline.
*
* You should not need to modify this function except for debugging purposes.
* If you add code to print debug output in this function, remove it or comment
* it out before you submit the lab.
*
* @param p the pipeline to simulate
*/
void pipe_cycle(Pipeline *p)
{
p->stat_num_cycle++;
// In hardware, all pipeline stages execute in parallel, and each pipeline
// latch is populated at the start of the next clock cycle.
// In our simulator, we simulate the pipeline stages one at a time in
// reverse order, from the Write Back stage (WB) to the Fetch stage (IF).
// We do this so that each stage can read from the latch before it and
// write to the latch after it without needing to "double-buffer" the
// latches.
// Additionally, it means that earlier pipeline stages can know about
// stalls triggered in later pipeline stages in the same cycle, as would be
// the case with hardware stall signals asserted by combinational logic.
std::cout << "BEGIN" << std::endl;
pipe_cycle_WB(p);
pipe_cycle_MA(p);
pipe_cycle_EX(p);
pipe_cycle_ID(p);
pipe_cycle_IF(p);
// You can uncomment the following line to print out the pipeline state
// after each clock cycle for debugging purposes.
// Make sure you comment it out or remove it before you submit the lab.
pipe_print_state(p);
for (unsigned int i = 0; i < PIPE_WIDTH; i++) {
std::cout << "valid: " << p->pipe_latch[IF_LATCH][i].valid << " " << p->pipe_latch[ID_LATCH][i].valid << " " << p->pipe_latch[EX_LATCH][i].valid << " "<< p->pipe_latch[MA_LATCH][i].valid << std::endl;
std::cout << "stall: " << p->pipe_latch[IF_LATCH][i].stall << " " << p->pipe_latch[ID_LATCH][i].stall << " " << p->pipe_latch[EX_LATCH][i].stall << " "<< p->pipe_latch[MA_LATCH][i].stall << std::endl;
}
std::cout << "END" << std::endl << std::endl;
}
/**
* Simulate one cycle of the Write Back stage (WB) of a pipeline.
*
* Some skeleton code has been provided for you. You must implement anything
* else you need for the pipeline simulation to work properly.
*
* @param p the pipeline to simulate
*/
void pipe_cycle_WB(Pipeline *p)
{
for (unsigned int i = 0; i < PIPE_WIDTH; i++)
{
if (p->pipe_latch[MA_LATCH][i].valid)
{
p->stat_retired_inst++;
if (p->pipe_latch[MA_LATCH][i].op_id >= p->halt_op_id)
{
// Halt the pipeline if we've reached the end of the trace.
p->halt = true;
}
}
}
}
/**
* Simulate one cycle of the Memory Access stage (MA) of a pipeline.
*
* Some skeleton code has been provided for you. You must implement anything
* else you need for the pipeline simulation to work properly.
*
* @param p the pipeline to simulate
*/
void pipe_cycle_MA(Pipeline *p)
{
for (unsigned int i = 0; i < PIPE_WIDTH; i++)
{
// Copy each instruction from the EX latch to the MA latch.
p->pipe_latch[MA_LATCH][i] = p->pipe_latch[EX_LATCH][i];
p->pipe_latch[MA_LATCH][i].valid = p->pipe_latch[EX_LATCH][i].valid;
}
}
/**
* Simulate one cycle of the Execute stage (EX) of a pipeline.
*
* Some skeleton code has been provided for you. You must implement anything
* else you need for the pipeline simulation to work properly.
*
* @param p the pipeline to simulate
*/
void pipe_cycle_EX(Pipeline *p)
{
for (unsigned int i = 0; i < PIPE_WIDTH; i++)
{
// Copy each instruction from the ID latch to the EX latch.
p->pipe_latch[EX_LATCH][i] = p->pipe_latch[ID_LATCH][i];
p->pipe_latch[EX_LATCH][i].valid = p->pipe_latch[ID_LATCH][i].valid;
}
}
/**
* Simulate one cycle of the Instruction Decode stage (ID) of a pipeline.
*
* Some skeleton code has been provided for you. You must implement anything
* else you need for the pipeline simulation to work properly.
*
* @param p the pipeline to simulate
*/
void pipe_cycle_ID(Pipeline *p)
{
for (unsigned int i = 0; i < PIPE_WIDTH; i++)
{
// Copy each instruction from the IF latch to the ID latch.
p->pipe_latch[ID_LATCH][i] = p->pipe_latch[IF_LATCH][i];
p->pipe_latch[ID_LATCH][i].stall = false;
}
for (unsigned int i = 0; i < PIPE_WIDTH; i++)
{
//Track reasons for stalling
bool stall_src1_ma = false;
bool stall_src2_ma = false;
bool stall_cc_ma = false;
bool stall_src1_ex = false;
bool stall_src2_ex = false;
bool stall_cc_ex = false;
bool stall_cc_id = false;
bool stall_src1_id = false;
bool stall_src2_id = false;
for (unsigned int ii = 0; ii < PIPE_WIDTH; ii++) {
//Check for a colission between the EX dest reg and the first src reg for ID
if (p->pipe_latch[EX_LATCH][ii].trace_rec.dest_reg == p->pipe_latch[ID_LATCH][i].trace_rec.src1_reg && p->pipe_latch[ID_LATCH][i].trace_rec.src1_needed && p->pipe_latch[EX_LATCH][ii].trace_rec.dest_needed && p->pipe_latch[EX_LATCH][ii].valid) {
stall_src1_ex = true;
}
//Check for a colission between the EX dest reg and the second src reg for ID
if (p->pipe_latch[EX_LATCH][ii].trace_rec.dest_reg == p->pipe_latch[ID_LATCH][i].trace_rec.src2_reg && p->pipe_latch[ID_LATCH][i].trace_rec.src2_needed && p->pipe_latch[EX_LATCH][ii].trace_rec.dest_needed && p->pipe_latch[EX_LATCH][ii].valid) {
stall_src2_ex = true;
}
//Check for a colission between the EX cc_write reg and the cc_read ID
//if (p->pipe_latch[EX_LATCH][ii].trace_rec.cc_write == p->pipe_latch[ID_LATCH][i].trace_rec.cc_read && p->pipe_latch[EX_LATCH][ii].valid) {
if (p->pipe_latch[EX_LATCH][ii].trace_rec.cc_write && p->pipe_latch[ID_LATCH][i].trace_rec.cc_read && p->pipe_latch[EX_LATCH][ii].valid) {
stall_cc_ex = true;
}
//Check for a colission between the MA dest reg and the first src reg for ID
if (p->pipe_latch[MA_LATCH][ii].trace_rec.dest_reg == p->pipe_latch[ID_LATCH][i].trace_rec.src1_reg && p->pipe_latch[ID_LATCH][i].trace_rec.src1_needed && p->pipe_latch[MA_LATCH][ii].trace_rec.dest_needed && p->pipe_latch[MA_LATCH][ii].valid) {
stall_src1_ma = true;
}
//Check for a colission between the MA dest reg and the second src reg for ID
if (p->pipe_latch[MA_LATCH][ii].trace_rec.dest_reg == p->pipe_latch[ID_LATCH][i].trace_rec.src2_reg && p->pipe_latch[ID_LATCH][i].trace_rec.src2_needed && p->pipe_latch[MA_LATCH][ii].trace_rec.dest_needed && p->pipe_latch[MA_LATCH][ii].valid) {
stall_src2_ma = true;
}
//Check for a colission between the MA cc_write reg and the cc_read ID
//if (p->pipe_latch[MA_LATCH][ii].trace_rec.cc_write == p->pipe_latch[ID_LATCH][i].trace_rec.cc_read && p->pipe_latch[MA_LATCH][ii].valid) {
if (p->pipe_latch[MA_LATCH][ii].trace_rec.cc_write && p->pipe_latch[ID_LATCH][i].trace_rec.cc_read && p->pipe_latch[MA_LATCH][ii].valid) {
stall_cc_ma = true;
}
if (PIPE_WIDTH > 1) {
if (p->pipe_latch[ID_LATCH][ii].op_id < p->pipe_latch[ID_LATCH][i].op_id) {
if (p->pipe_latch[ID_LATCH][ii].trace_rec.cc_write && p->pipe_latch[ID_LATCH][i].trace_rec.cc_read) {
stall_cc_id = true;
}
if (p->pipe_latch[ID_LATCH][ii].trace_rec.dest_reg == p->pipe_latch[ID_LATCH][i].trace_rec.src1_reg && p->pipe_latch[ID_LATCH][i].trace_rec.src1_needed && p->pipe_latch[ID_LATCH][ii].trace_rec.dest_needed ) {
stall_src1_id = true;
}
if (p->pipe_latch[ID_LATCH][ii].trace_rec.dest_reg == p->pipe_latch[ID_LATCH][i].trace_rec.src2_reg && p->pipe_latch[ID_LATCH][i].trace_rec.src2_needed && p->pipe_latch[ID_LATCH][ii].trace_rec.dest_needed ) {
stall_src1_id = true;
}
}
}
}
if (ENABLE_MEM_FWD)
{
// TODO: Handle forwarding from the MA stage.
if (stall_src1_ma) {
unsigned int youngest = 256;
for (unsigned int j = 0; j < PIPE_WIDTH; j++) {
if (p->pipe_latch[MA_LATCH][j].trace_rec.dest_reg==p->pipe_latch[ID_LATCH][i].trace_rec.src1_reg && p->pipe_latch[MA_LATCH][j].trace_rec.dest_needed && p->pipe_latch[MA_LATCH][j].valid) {
if (youngest==256) {
youngest = j;
} else {
if (p->pipe_latch[MA_LATCH][j].op_id > p->pipe_latch[MA_LATCH][youngest].op_id) {
youngest = j;
}
}
}
}
if (youngest != 256) {
stall_src1_ma = false;
}
}
if (stall_src2_ma) {
unsigned int youngest = 256;
for (unsigned int j = 0; j < PIPE_WIDTH; j++) {
if (p->pipe_latch[MA_LATCH][j].trace_rec.dest_reg==p->pipe_latch[ID_LATCH][i].trace_rec.src2_reg && p->pipe_latch[MA_LATCH][j].trace_rec.dest_needed && p->pipe_latch[MA_LATCH][j].valid) {
if (youngest==256) {
youngest = j;
} else {
if (p->pipe_latch[MA_LATCH][j].op_id > p->pipe_latch[MA_LATCH][youngest].op_id) {
youngest = j;
}
}
}
}
if (youngest != 256) {
stall_src2_ma = false;
}
}
if (stall_cc_ma) {
unsigned int youngest = 256;
for (unsigned int j = 0; j < PIPE_WIDTH; j++) {
if (p->pipe_latch[MA_LATCH][j].trace_rec.cc_write && p->pipe_latch[ID_LATCH][i].trace_rec.cc_read && p->pipe_latch[MA_LATCH][j].valid) {
if (youngest==256) {
youngest = j;
} else {
if (p->pipe_latch[MA_LATCH][j].op_id > p->pipe_latch[MA_LATCH][youngest].op_id) {
youngest = j;
}
}
}
}
if (youngest != 256) {
stall_cc_ma = false;
}
}
/*
for (unsigned int ii = 0; ii < PIPE_WIDTH; ii++) {
if (stall_src1_ma) {
if (p->pipe_latch[ID_LATCH][i].trace_rec.src1_reg == p->pipe_latch[MA_LATCH][ii].trace_rec.dest_reg && p->pipe_latch[MA_LATCH][ii].valid && p->pipe_latch[MA_LATCH][ii].trace_rec.dest_needed && p->pipe_latch[ID_LATCH][i].trace_rec.src1_needed ) {
stall_src1_ma = false;
}
}
if (stall_src2_ma) {
if (p->pipe_latch[ID_LATCH][i].trace_rec.src2_reg == p->pipe_latch[MA_LATCH][ii].trace_rec.dest_reg && p->pipe_latch[MA_LATCH][ii].valid && p->pipe_latch[MA_LATCH][ii].trace_rec.dest_needed && p->pipe_latch[ID_LATCH][i].trace_rec.src2_needed ) {
stall_src2_ma = false;
}
}
if (stall_cc_ma) {
if (p->pipe_latch[ID_LATCH][i].trace_rec.cc_read && p->pipe_latch[MA_LATCH][ii].trace_rec.cc_write && p->pipe_latch[MA_LATCH][ii].valid) {
stall_cc_ma = false;
}
}
}*/
}
if (ENABLE_EXE_FWD)
{
// TODO: Handle forwarding from the EX stage.
// Rishov: New implementation based on youngest instruction in EX.
if (stall_src1_ex) {
unsigned int youngest = 256;
for (unsigned int j = 0; j < PIPE_WIDTH; j++) {
if (p->pipe_latch[EX_LATCH][j].trace_rec.dest_reg==p->pipe_latch[ID_LATCH][i].trace_rec.src1_reg && p->pipe_latch[EX_LATCH][j].trace_rec.dest_needed && p->pipe_latch[EX_LATCH][j].valid) {
if (youngest==256) {
youngest = j;
} else {
if (p->pipe_latch[EX_LATCH][j].op_id > p->pipe_latch[EX_LATCH][youngest].op_id) {
youngest = j;
}
}
}
}
if (youngest != 256) {
if (p->pipe_latch[EX_LATCH][youngest].trace_rec.op_type!=OP_LD) {
stall_src1_ex = false;
}
}
}
std::cout << "Before stall_src2_ex " << stall_src2_ex << std::endl;
if (stall_src2_ex) {
unsigned int youngest = 256;
for (unsigned int j = 0; j < PIPE_WIDTH; j++) {
if (p->pipe_latch[EX_LATCH][j].trace_rec.dest_reg==p->pipe_latch[ID_LATCH][i].trace_rec.src2_reg && p->pipe_latch[EX_LATCH][j].trace_rec.dest_needed && p->pipe_latch[EX_LATCH][j].valid) {
if (youngest==256) {
youngest = j;
} else {
if (p->pipe_latch[EX_LATCH][j].op_id > p->pipe_latch[EX_LATCH][youngest].op_id) {
youngest = j;
}
}
}
}
if (p->pipe_latch[ID_LATCH][0].op_id == 4689) {
std::cout << "IN stall_src2_ex 4689 pipe " << i << std::endl;
std::cout << "youngest: " << youngest << std::endl;
std::cout << stall_src2_ex << std::endl;
}
if (youngest != 256) {
bool ld = false;
if (p->pipe_latch[EX_LATCH][youngest].trace_rec.op_type==OP_LD) {
ld = true;
}
std::cout << "Before reset " << ld << std::endl;
if (p->pipe_latch[EX_LATCH][youngest].trace_rec.op_type!=OP_LD) {
std::cout << "In reset" << std::endl;
stall_src2_ex = false;
}
std::cout << "After reset" << std::endl;
}
if (p->pipe_latch[EX_LATCH][0].op_id == 4689) {
std::cout << stall_src2_ex << std::endl;
}
}
if (stall_cc_ex) {
unsigned int youngest = 256;
for (unsigned int j = 0; j < PIPE_WIDTH; j++) {
if (p->pipe_latch[EX_LATCH][j].trace_rec.cc_write && p->pipe_latch[ID_LATCH][i].trace_rec.cc_read && p->pipe_latch[EX_LATCH][j].valid) {
if (youngest==256) {
youngest = j;
} else {
if (p->pipe_latch[EX_LATCH][j].op_id > p->pipe_latch[EX_LATCH][youngest].op_id) {
youngest = j;
}
}
}
}
if (youngest != 256) {
if (p->pipe_latch[EX_LATCH][youngest].trace_rec.op_type!=OP_LD) {
stall_cc_ex = false;
}
}
}
/*
for (unsigned int ii = 0; ii < PIPE_WIDTH; ii++) {
if (!p->pipe_latch[EX_LATCH][ii].trace_rec.op_type==OP_LD) {
if (stall_src1_ex) {
if (p->pipe_latch[ID_LATCH][i].trace_rec.src1_reg == p->pipe_latch[EX_LATCH][ii].trace_rec.dest_reg && p->pipe_latch[EX_LATCH][ii].valid && p->pipe_latch[EX_LATCH][ii].trace_rec.dest_needed && p->pipe_latch[ID_LATCH][i].trace_rec.src1_needed) {
//if (p->pipe_latch[EX_LATCH][ii].trace_rec.dest_reg == p->pipe_latch[ID_LATCH][i].trace_rec.src1_reg && p->pipe_latch[ID_LATCH][i].trace_rec.src2_needed && p->pipe_latch[EX_LATCH][ii].valid) {
stall_src1_ex = false;
}
}
if (stall_src2_ex) {
if (p->pipe_latch[ID_LATCH][i].trace_rec.src2_reg == p->pipe_latch[EX_LATCH][ii].trace_rec.dest_reg && p->pipe_latch[EX_LATCH][ii].valid && p->pipe_latch[EX_LATCH][ii].trace_rec.dest_needed && p->pipe_latch[ID_LATCH][i].trace_rec.src2_needed) {
//if (p->pipe_latch[EX_LATCH][ii].trace_rec.dest_reg == p->pipe_latch[ID_LATCH][i].trace_rec.src2_reg && p->pipe_latch[ID_LATCH][i].trace_rec.src2_needed && p->pipe_latch[EX_LATCH][ii].valid) {
stall_src2_ex = false;
}
}
if (stall_cc_ex) {
if (p->pipe_latch[ID_LATCH][i].trace_rec.cc_read && p->pipe_latch[EX_LATCH][ii].trace_rec.cc_write && p->pipe_latch[EX_LATCH][ii].valid) {
stall_cc_ex = false;
}
}
} else {
for (unsigned int j = 0; j < PIPE_WIDTH; j++) {
if (p->pipe_latch[EX_LATCH][j].op_id < p->pipe_latch[EX_LATCH][ii].op_id && !p->pipe_latch[EX_LATCH][j].trace_rec.op_type==OP_LD) {
if (stall_src1_ex && p->pipe_latch[EX_LATCH][j].trace_rec.dest_reg==p->pipe_latch[EX_LATCH][ii].trace_rec.dest_reg && p->pipe_latch[EX_LATCH][j].trace_rec.dest_needed && p->pipe_latch[EX_LATCH][j].trace_rec.dest_reg == p->pipe_latch[ID_LATCH][i].trace_rec.src1_reg && p->pipe_latch[ID_LATCH][i].trace_rec.src1_needed && p->pipe_latch[EX_LATCH][j].valid)
}
}
}
}*/
}
if (stall_src1_ex || stall_src1_ma || stall_src2_ex || stall_src2_ma || stall_cc_ex || stall_cc_ma || stall_cc_id || stall_src1_id || stall_src2_id || !p->pipe_latch[ID_LATCH][i].op_id>1) {
p->pipe_latch[ID_LATCH][i].valid = false;
} else {
p->pipe_latch[ID_LATCH][i].valid = true;
}
if (!p->pipe_latch[IF_LATCH][i].valid) {
p->pipe_latch[ID_LATCH][i].valid = false;
}
if (stall_src1_ex || stall_src2_ex) {
std::cout << "EX stall " << stall_src1_ex << " " << stall_src2_ex << std::endl;
if (p->pipe_latch[IF_LATCH][0].op_id==4689 && i==0) {
bool dest0 = false;
bool dest1 = false;
if (p->pipe_latch[ID_LATCH][0].trace_rec.src2_reg==p->pipe_latch[EX_LATCH][0].trace_rec.dest_reg) {
dest0 = true;
}
if (p->pipe_latch[ID_LATCH][0].trace_rec.src2_reg==p->pipe_latch[EX_LATCH][1].trace_rec.dest_reg) {
dest1 = true;
}
bool ld = false;
if (p->pipe_latch[EX_LATCH][1].trace_rec.op_type==OP_LD) {
ld = true;
}
bool src2_needed0 = p->pipe_latch[ID_LATCH][0].trace_rec.src2_needed;
bool dest_needed0 = p->pipe_latch[EX_LATCH][0].trace_rec.dest_needed;
bool src2_needed1 = p->pipe_latch[ID_LATCH][1].trace_rec.src2_needed;
bool dest_needed1 = p->pipe_latch[EX_LATCH][1].trace_rec.dest_needed;
bool younger = false;
if (p->pipe_latch[EX_LATCH][1].op_id > p->pipe_latch[EX_LATCH][0].op_id) {
younger = true;
}
std::cout << "src2: " << stall_src2_ex << " " << dest0 << " " << src2_needed0 << " " << dest_needed0 << " " << dest1 << " " << src2_needed1 << " " << dest_needed1 << " " << ld << " " << younger << std::endl;
}
//std::cout << p->pipe_latch[ID_LATCH][i].trace_rec.src1_reg << " " << p->pipe_latch[ID_LATCH][i].trace_rec.src2_reg << " " << p->pipe_latch[EX_LATCH][i].trace_rec.dest_reg <<std::endl;
}
bool ex_pipe0 = p->pipe_latch[EX_LATCH][0].trace_rec.cc_write;
bool ex_pipe1 = p->pipe_latch[EX_LATCH][1].trace_rec.cc_write;
bool ma_pipe0 = p->pipe_latch[MA_LATCH][0].trace_rec.cc_write;
bool ma_pipe1 = p->pipe_latch[MA_LATCH][1].trace_rec.cc_write;
if (stall_cc_ex) {
if (PIPE_WIDTH > 1) {
std::cout << "EX stall CC " << p->pipe_latch[ID_LATCH][i].op_id << " " << ex_pipe0 << " " << ex_pipe1 << std::endl;
} else {
std::cout << "EX stall CC " << p->pipe_latch[ID_LATCH][i].op_id << std::endl;
}
//std::cout << p->pipe_latch[ID_LATCH][i].trace_rec.cc_read << " " << p->pipe_latch[EX_LATCH][i].trace_rec.cc_write << std::endl;
}
if (stall_src1_ma || stall_src2_ma) {
std::cout << "MA stall" << stall_src1_ma << " " << stall_src2_ma << std::endl;
//std::cout << p->pipe_latch[ID_LATCH][i].trace_rec.src1_reg << " " << p->pipe_latch[ID_LATCH][i].trace_rec.src2_reg << " " << p->pipe_latch[MA_LATCH][i].trace_rec.dest_reg <<std::endl;
}
if (stall_cc_ma) {
if (PIPE_WIDTH > 1) {
std::cout << "MA stall CC " << p->pipe_latch[ID_LATCH][i].op_id << " " << ma_pipe0 << " " << ma_pipe1 << std::endl;
} else {
std::cout << "MA stall CC " << p->pipe_latch[ID_LATCH][i].op_id << std::endl;
}
//std::cout << p->pipe_latch[ID_LATCH][i].trace_rec.cc_read << " " << p->pipe_latch[MA_LATCH][i].trace_rec.cc_write << std::endl;
}
/*
if (p->pipe_latch[ID_LATCH][i].trace_rec.op_type==OP_CBR ) {
std::cout << "PIPE " << i << " ID OP_ID: " << p->pipe_latch[ID_LATCH][i].op_id << " " << "BRANCH" << " " << stall_src1_ex << " " << stall_src2_ex << " " << stall_cc_ex << " " << stall_src1_ma << " " << stall_src2_ma << " " << stall_cc_ma << " " << p->pipe_latch[ID_LATCH][i].valid << std::endl;
}*/
}
/*
for (unsigned int i = 0; i < PIPE_WIDTH; i++) {
//After all data stalls have been set, we can check to see if there are age related stalls that need to be implemented
for (unsigned int ii = 0; ii < PIPE_WIDTH; ii++) {
if (i != ii) {
if(p->pipe_latch[ID_LATCH][i].op_id < p->pipe_latch[ID_LATCH][ii].op_id && p->pipe_latch[ID_LATCH][ii].stall) {
//p->pipe_latch[ID_LATCH][i].stall = true;
p->pipe_latch[ID_LATCH][i].valid = false;
}
}
}
}*/
}
/**
* Simulate one cycle of the Instruction Fetch stage (IF) of a pipeline.
*
* Some skeleton code has been provided for you. You must implement anything
* else you need for the pipeline simulation to work properly.
*
* @param p the pipeline to simulate
*/
void pipe_cycle_IF(Pipeline *p)
{
for (unsigned int i = 0; i < PIPE_WIDTH; i++)
{
if (!p->pipe_latch[ID_LATCH][i].valid && !p->pipe_latch[EX_LATCH][i].valid && !p->pipe_latch[MA_LATCH][i].valid && p->pipe_latch[IF_LATCH][i].op_id < PIPE_WIDTH) {
//if (!p->pipe_latch[ID_LATCH][i].valid && !p->pipe_latch[EX_LATCH][i].valid) {
p->pipe_latch[IF_LATCH][i].stall = false;
} else if (!p->pipe_latch[ID_LATCH][i].valid) {
p->pipe_latch[IF_LATCH][i].stall = true;
} else {
p->pipe_latch[IF_LATCH][i].stall = false;
}
if (PIPE_WIDTH > 1) {
for (unsigned int j = 0; j < PIPE_WIDTH; j++) {
if (!p->pipe_latch[ID_LATCH][j].valid && p->pipe_latch[IF_LATCH][j].op_id < p->pipe_latch[IF_LATCH][i].op_id) {
p->pipe_latch[IF_LATCH][i].stall = true;
p->pipe_latch[ID_LATCH][i].valid = false;
//std::cout << "IF valid check " << p->pipe_latch[IF_LATCH][i].op_id << " " << j << " " << i << " " << p->pipe_latch[ID_LATCH][j].valid << " " << (p->pipe_latch[IF_LATCH][j].op_id < p->pipe_latch[IF_LATCH][i].op_id) << std::endl;
}
}
}
/*bool ma_cc = false;
bool ex_cc = false;
bool if_cc = false;
if (p->pipe_latch[MA_LATCH][i].trace_rec.cc_write && p->pipe_latch[MA_LATCH][i].valid ) {
ma_cc = true;
}
if (p->pipe_latch[EX_LATCH][i].trace_rec.cc_write && p->pipe_latch[EX_LATCH][i].valid ) {
ex_cc = true;
}
if (p->pipe_latch[IF_LATCH][i].trace_rec.cc_read ) {
if_cc = true;
}*/
/*
if (p->pipe_latch[IF_LATCH][i].trace_rec.op_type==OP_LD ) {
std::cout << "PIPE " << i << " OP_ID: " << p->pipe_latch[IF_LATCH][i].op_id << " " << "LOAD" << " " << if_cc << " " << ex_cc << " " << ma_cc << std::endl;
} else if (p->pipe_latch[IF_LATCH][i].trace_rec.op_type==OP_ST ) {
std::cout << "PIPE " << i << " OP_ID: " << p->pipe_latch[IF_LATCH][i].op_id << " " << "STORE" << " " << if_cc << " " << ex_cc << " " << ma_cc << std::endl;
} else if (p->pipe_latch[IF_LATCH][i].trace_rec.op_type==OP_ALU ) {
std::cout << "PIPE " << i << " OP_ID: " << p->pipe_latch[IF_LATCH][i].op_id << " " << "ALU" << " " << if_cc << " " << ex_cc << " " << ma_cc << std::endl;
} else if (p->pipe_latch[IF_LATCH][i].trace_rec.op_type==OP_CBR ) {
std::cout << "PIPE " << i << " OP_ID: " << p->pipe_latch[IF_LATCH][i].op_id << " " << "BRANCH" << " " << if_cc << " " << ex_cc << " " << ma_cc << std::endl;
} else if (p->pipe_latch[IF_LATCH][i].trace_rec.op_type==OP_OTHER ) {
std::cout << "PIPE " << i << " OP_ID: " << p->pipe_latch[IF_LATCH][i].op_id << " " << "OTHER" << " " << if_cc << " " << ex_cc << " " << ma_cc << std::endl;
}*/
//std::cout << "IF " << p->pipe_latch[ID_LATCH][i].valid << std::endl;
if (!p->pipe_latch[IF_LATCH][i].stall) {
// Read an instruction from the trace file.
PipelineLatch fetch_op;
pipe_get_fetch_op(p, &fetch_op);
// Handle branch (mis)prediction.
if (BPRED_POLICY != BPRED_PERFECT)
{
pipe_check_bpred(p, &fetch_op);
}
// Copy the instruction to the IF latch.
p->pipe_latch[IF_LATCH][i] = fetch_op;
if (p->pipe_latch[IF_LATCH][i].op_id == 1) {
p->pipe_latch[ID_LATCH][i].valid = false;
//std::cout << "IF valid 2" << std::endl;
}
}
//std::cout << "PIPE " << i << "IF end" << p->pipe_latch[ID_LATCH][i].valid << std::endl;
}
/*
for (unsigned int i = 0; i < PIPE_WIDTH; i++) {
std::cout << "PIPE " << i << "IF independent look" << p->pipe_latch[ID_LATCH][i].valid << std::endl;
}*/
}
/**
* If the instruction just fetched is a conditional branch, check for a branch
* misprediction, update the branch predictor, and set appropriate flags in the
* pipeline.
*
* You must implement this function in part B of the lab.
*
* @param p the pipeline
* @param fetch_op the pipeline latch containing the operation fetched
*/
void pipe_check_bpred(Pipeline *p, PipelineLatch *fetch_op)
{
// TODO: For a conditional branch instruction, get a prediction from the
// branch predictor.
// TODO: If the branch predictor mispredicted, mark the fetch_op
// accordingly.
// TODO: Immediately update the branch predictor.
// TODO: If needed, stall the IF stage by setting the flag
// p->fetch_cbr_stall.
}
| [
"bbruen@us.ibm.com"
] | bbruen@us.ibm.com |
b5145af3b103f8535cbfef5c864ed5c9a50bce69 | 932575acb68a8308f62e651d8eb04378f3085b5d | /C++_Test1027/C++_Test1027/重写.cpp | fde0fc000c1fa2a111a0c7911b291542920df65b | [] | no_license | adong001/C-DS-CPP | 308b54ab4e3061461074dc0b592591e743558942 | 2df3b1a61adb4bfc28cc421b2fd475af1ffd40d3 | refs/heads/master | 2023-01-21T05:09:07.463759 | 2020-11-15T01:38:47 | 2020-11-15T01:38:47 | 191,345,672 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 682 | cpp | //#define _CRT_SECURE_NO_WARNINGS 1
//#include<iostream>
//using namespace std;
//
//class Base
//{
//public:
// int m_a ;
// virtual void func()
// {
// cout << "Base" << endl;
// }
//
// virtual~Base()
// {
// cout << "~Base" << endl;
// }
//};
//
//class Test : public Base
//{
//public:
// int m_b;
// virtual void func()
// {
// cout << "Test" << endl;
// }
//
// virtual~Test()
// {
// cout << "~Test" << endl;
// }
//
//
//};
//
//int main4()
//{
// Base* B1 = new Base;
// Base* B2 = new Test;
// delete B1;
// delete B2;
// //T.~Test();
// /*Base B;
// Test T;
// Base* Bptr = &T;
// T.func();
// Bptr->func();
// B.func();*/
// system("pause");
// return 0;
//} | [
"1792095378@qq.com"
] | 1792095378@qq.com |
73eefa3deb5457f90572b61abf3a9f877c20fd3d | 85dd65c6be7c217dc8ce03a615aabb8b2b08f6be | /Projects/cube_demo/ColorCone.h | cb9fae35085a6c9f8cc37cd1b73486701d31277a | [
"MIT"
] | permissive | AlexLamson/ledcube | 996a70a6f22cf9279e8b4cb4de323bbf4db1be49 | 66ae1e468bcfe0f9930e22773504ca474c987b52 | refs/heads/master | 2022-03-27T22:12:45.142924 | 2022-02-28T20:40:46 | 2022-02-28T20:40:46 | 130,425,742 | 4 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 304 | h | /*
* ColorCone.h
*
* Created on: Nov 2, 2018
* Author: raffc
*/
#ifndef COLORCONE_H_
#define COLORCONE_H_
#include "Demo.h"
#include "Arduino.h"
class ColorCone: public Demo {
private:
byte hue = 0;
public:
ColorCone();
void initialize();
void tick();
};
#endif /* COLORCONE_H_ */
| [
"crharfifs@gmail.com"
] | crharfifs@gmail.com |
ecfbbcdc959ec74c3dccca638df3c6d0fbcc99b1 | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/git/hunk_7672.cpp | 3a8ee1b88277096956f720dd418cd6641cacb241 | [] | 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 | putchar(',');
}
if (white_space_at_end)
- printf("white space at end");
+ printf("whitespace at end");
printf(":%s ", reset);
emit_line_with_ws(1, set, reset, ws, line, len,
data->ws_rule); | [
"993273596@qq.com"
] | 993273596@qq.com |
59fb860372c238823f54a575d45472c45c183388 | a173bce5da38c6cb202631780e715087394fddbb | /ch6/4-4/hello.cc | 8f5d1fa224d1b24c6af3e690ba8b80a58b89ced3 | [] | no_license | chai2010/wasm-book-code | 1d9293f0ae26db4da7722527f44ee4f7279c5100 | 7d3e4a23d5e958870d0c15177aabad67fde52f8d | refs/heads/master | 2023-08-17T08:38:52.017164 | 2023-06-26T17:47:20 | 2023-06-26T17:47:20 | 172,828,644 | 56 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 157 | cc | #include <emscripten.h>
int main() {
emscripten_run_script(R"(
function print(s) {
console.log("print:", s);
}
print("hello");
)");
return 0;
}
| [
"chaishushan@gmail.com"
] | chaishushan@gmail.com |
740a765b9181106e1108e990ccaa821b5e4c07e9 | 901d1e324696f083618e9e24c541d31cf5faa630 | /Source/MGS/Item.cpp | 3bee878a4b42bd826110703f02323fc1c48a2baa | [] | no_license | LochNessy64/MGS | 4c2cbdaf786aca8f4af89208853b5550038032a4 | 961e0c4f085bd49bb777a332d34689de0cc61c9d | refs/heads/master | 2020-02-26T15:08:59.636227 | 2017-01-18T08:07:05 | 2017-01-18T08:07:05 | 68,567,579 | 0 | 0 | null | 2016-11-24T08:14:55 | 2016-09-19T03:55:30 | C++ | UTF-8 | C++ | false | false | 8,177 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "MGS.h"
#include "Blueprint/UserWidget.h"
#include "Blueprint/WidgetLayoutLibrary.h"
#include "Item.h"
#define LOCTEXT_NAMESPACE "Mgs Namespace"
AItem::AItem()
{
PrimaryActorTick.bCanEverTick = true;
NoCollisionTimer = new FTimerHandle();
PickupFailTimer = new FTimerHandle();
bWasCollected = false;
bIsDisplayTextSet = false;
bDidItemPickupFail = false;
PickupSound = LoadObject<USoundWave>(NULL, TEXT("/Game/Audio/0x0CUnreal.0x0CUnreal"), NULL, LOAD_None, NULL);
bIsActive = false;
ItemMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Item Mesh"));
RootComponent = ItemMesh;
ItemName = LOCTEXT("Item Name Key", "ITEM NAME");
ItemMesh->SetCollisionProfileName("OverlapAllDynamic");
/*UE_LOG(LogTemp, Warning, TEXT("Current ItemMesh collision preset: %s"), *(ItemMesh->GetCollisionProfileName().ToString()));
UE_LOG(LogTemp, Warning, TEXT("Current Actor collision enabled: %s"), this->GetActorEnableCollision() ? TEXT("true") : TEXT("false"));*/
//this->
//ItemMesh->bGenerateOverlapEvents = true;
TriggerSphere = CreateDefaultSubobject<USphereComponent>(TEXT("Trigger Sphere"));
TriggerSphere->InitSphereRadius(105.0f);
TriggerSphere->SetupAttachment(RootComponent);
bIsNameVisible = true;
PrereqText = FText::FromString("PRE-REQUISITE TEXT");
ItemFullMessage = FText::FromString(ItemName.ToString() + " FULL");
TurnRate = FRotator(0.0f, 0.0f, 180.0f);
TriggerSphere->bGenerateOverlapEvents = true;
TriggerSphere->OnComponentBeginOverlap.AddDynamic(this, &AItem::OnOverlapBegin);
//TriggerSphere->OnComponentEndOverlap.AddDynamic(this, &AItem::OnOverlapEnd);
EndDelegate.BindUFunction(this, FName("OnOverlapEnd"));
OnActorEndOverlap.Add( EndDelegate);
TriggerSphereRadius = TriggerSphere->GetScaledSphereRadius() ;
}
void AItem::BeginPlay()
{
Super::BeginPlay();
}
void AItem::Tick(float DeltaSeconds)
{
Super::Tick(DeltaSeconds);
IdleAnimation(DeltaSeconds);
if (bDidItemPickupFail)
{
if (GetPickupFailTimer()->IsValid())
{
CantCollectAnimation(DeltaSeconds);
if (GetPickupFailTimerElapsed() == -1.0f && GetPickupFailTimerRemaining() == -1.0f)
{
bDidItemPickupFail = false;
GetPickupFailTimer()->Invalidate();
SetActorLocation(OriginalLocation);
//bIsDisplayTextSet = false;
}
}
}
}
void AItem::Init(FString ItemName, EItemType TypeOfItem)
{
Type = TypeOfItem;
//this->ItemName = ItemName; ///Is this really correct?
}
EItemType AItem::GetItemType()
{
return Type;
}
bool AItem::CheckIfNameVisible()
{
return bIsNameVisible;
}
//TODO: Fill this out with print out of all vars
FString AItem::ToString()
{
return FString();
}
void AItem::SetItemType(EItemType NewType)
{
Type = NewType;
}
void AItem::SetNameVisibility(bool NewNameVisibility)
{
bIsNameVisible = NewNameVisibility;
}
bool AItem::IsActive()
{
return bIsActive;
}
void AItem::SetActive(bool newActiveState)
{
bIsActive = newActiveState;
}
//TODO: Fill this out to make mesh hidden, and show appropriate text
bool AItem::WasCollected()
{
return bWasCollected;
}
void AItem::SetCollected(bool NewCollectState)
{
bWasCollected = NewCollectState;
}
bool AItem::DidItemPickupFail()
{
return bDidItemPickupFail;
}
FText AItem::GetItemName()
{
return ItemName;
}
void AItem::SetItemName(FText NewName)
{
ItemName = NewName;
}
FText AItem::GetItemFullText()
{
return ItemFullMessage;
}
void AItem::SetItemFullText(FText NewFullText)
{
ItemFullMessage = NewFullText;
}
FText AItem::GetPrereqText()
{
return PrereqText;
}
void AItem::SetPrereqText(FText NewPrereqText)
{
PrereqText = NewPrereqText;
}
//TODO: Fill this out
//this is called in WasCollected to check if inventory is full or not
bool AItem::IsInventoryItemFull(UIItem *InvItem)
{
return false;
}
void AItem::IdleAnimation(float DeltaSeconds)
{
AddActorWorldRotation(TurnRate * DeltaSeconds);
}
void AItem::CantCollectAnimation(float DeltaSeconds)
{
SetActorLocation(FMath::Lerp(GetActorLocation(), BoundingVectors[FMath::RandRange(0, BoundingVectors.Num() - 1)], 0.5f));
//UE_LOG(LogTemp, Warning, TEXT("DeltaSeconds: %f"), DeltaSeconds);
}
void AItem::OnOverlapBegin(UPrimitiveComponent * OverlappedComp, AActor * OtherActor, UPrimitiveComponent * OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult & SweepResult)
{
if (Cast<ACharacter>(OtherActor))
{
UE_LOG(LogTemp, Warning, TEXT("Beginning Overlap"));
OriginalLocation = GetActorLocation();
UE_LOG(LogTemp, Warning, TEXT("Original Location: %f"), OriginalLocation.X);
//TODO: Add logic to check if user inventory is full
//If inventory full, play full animation
if (!bDidItemPickupFail)
{
SwitchCollision();
if (!GetNoCollisionTimer()->IsValid())
{
GetWorldTimerManager().ValidateHandle(*NoCollisionTimer);
}
SetNoCollisionTimer(3.0f);
if (!GetPickupFailTimer()->IsValid())
{
GetWorldTimerManager().ValidateHandle(*PickupFailTimer);
}
SetPickupFailTimer(0.5f);
if (BoundingVectors.Num() == 0)
{
BoundingVectors.Push(FVector(OriginalLocation.X + TriggerSphereRadius / 4, OriginalLocation.Y, OriginalLocation.Z));
BoundingVectors.Push(FVector(OriginalLocation.X - TriggerSphereRadius / 4, OriginalLocation.Y, OriginalLocation.Z));
BoundingVectors.Push(FVector(OriginalLocation.X, OriginalLocation.Y + TriggerSphereRadius / 4, OriginalLocation.Z));
BoundingVectors.Push(FVector(OriginalLocation.X, OriginalLocation.Y - TriggerSphereRadius / 4, OriginalLocation.Z));
}
bDidItemPickupFail = true;
}
//else collect item
// CollectItem();
}
}
void AItem::SwitchCollision()
{
//this->SetActorEnableCollision(!GetActorEnableCollision());
//ItemMesh->bGenerateOverlapEvents = !(ItemMesh->bGenerateOverlapEvents);
//TriggerSphere->bGenerateOverlapEvents = !TriggerSphere->bGenerateOverlapEvents;
}
void AItem::OnOverlapEnd(UPrimitiveComponent * OverlappedComp, AActor * OtherActor, UPrimitiveComponent * OtherComp, int32 OtherBodyIndex)
{
UE_LOG(LogTemp, Warning, TEXT("End Overlap"));
if (Cast<ACharacter>(OtherActor))
{
if (GetNoCollisionTimerElapsed() == -1.0f && GetNoCollisionTimerRemaining() == -1.0f)
{
UE_LOG(LogTemp, Warning, TEXT("Switching collision because player went outside bounds"));
//SwitchCollision();
}
}
}
void AItem::CollectItem()
{
bWasCollected = true;
//this 'paragraph' will probably need to move to it's own function
ItemMesh->SetHiddenInGame(!(ItemMesh->bHiddenInGame));
this->SetActorEnableCollision(!GetActorEnableCollision());
ItemMesh->bGenerateOverlapEvents = !(ItemMesh->bGenerateOverlapEvents);
TriggerSphere->bGenerateOverlapEvents = !TriggerSphere->bGenerateOverlapEvents;
//SetActorHiddenInGame(true);
TriggerSphere->bHiddenInGame = true;
SetActorTickEnabled(false);
UGameplayStatics::PlaySound2D(GetWorld(), PickupSound);
//UE_LOG(LogTemp, Warning, TEXT("Current Actor collision enabled: %s"), this->GetActorEnableCollision() ? TEXT("true") : TEXT("false"));
}
void AItem::SetNoCollisionTimer(float Duration)
{
GetWorldTimerManager().SetTimer(*NoCollisionTimer, Duration, false);
}
FTimerHandle* AItem::GetNoCollisionTimer()
{
return NoCollisionTimer;
}
float AItem::GetNoCollisionTimerElapsed()
{
return GetWorldTimerManager().GetTimerElapsed(*NoCollisionTimer);
}
float AItem::GetNoCollisionTimerRemaining()
{
return GetWorldTimerManager().GetTimerRemaining(*NoCollisionTimer);
}
void AItem::SetPickupFailTimer(float Duration)
{
GetWorldTimerManager().SetTimer(*PickupFailTimer, Duration, false);
}
FTimerHandle * AItem::GetPickupFailTimer()
{
return PickupFailTimer;
}
float AItem::GetPickupFailTimerElapsed()
{
return GetWorldTimerManager().GetTimerElapsed(*PickupFailTimer);
}
float AItem::GetPickupFailTimerRemaining()
{
return GetWorldTimerManager().GetTimerRemaining(*PickupFailTimer);
}
bool AItem::GetIsDisplayTextSet()
{
return bIsDisplayTextSet;
}
void AItem::SetIsDisplayTextSet(bool NewState)
{
bIsDisplayTextSet = NewState;
}
FVector AItem::GetOriginalLocation()
{
return OriginalLocation;
}
#undef LOCTEXT_NAMESPACE
| [
"v.valencia5903@gmail.com"
] | v.valencia5903@gmail.com |
b6bd3528f7761d1eb6c906b2d1318af7ab12eae1 | 7ccccd69629354409566ba01d93572a4da0ba364 | /Desarrollo/BulletTest/BulletTest/IA/StatesIA/BuscarVida.h | 19563efc4cbddd6340b3da8fe6a351c8fbe87e97 | [] | no_license | Juliyo/LastBullet | eac779d78f0e8d62eb71ac4ecaa838e828825736 | 4f93b5260eaba275aa47c3ed13a93e7d7e60c0e9 | refs/heads/master | 2021-09-11T12:27:29.583652 | 2018-01-18T14:14:52 | 2018-01-18T14:14:52 | 104,806,970 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 375 | h | #pragma once
#include "StateIA.h"
class BuscarVida :
public StateIA
{
public:
static BuscarVida& i() {
static BuscarVida singleton;
return singleton;
}
virtual void Enter(Enemy_Bot* pEnemy);
virtual void Execute(Enemy_Bot* pEnemy);
virtual void Exit(Enemy_Bot* pEnemy);
virtual std::string getStateName() { return "BuscarVida"; }
private:
BuscarVida() {};
};
| [
"julio17795@hotmail.com"
] | julio17795@hotmail.com |
90ef873cca949a9b670bdace363d82498271ba73 | d17b8c418f619acf257da9bc873ee32c92a05735 | /ContraRemake/Client/Sound/Sound.cpp | 94bdb3ee6cf409e93f51c16cdefc6a4f21727448 | [] | no_license | Giova262/Taller-de-Programacion-I | 1195c0bc5e050aa96d66eb875b0582ac6a7c27fb | 174d00f1e173de7a684ad25b86bc8f525d3ef2fb | refs/heads/master | 2020-03-27T20:57:43.185540 | 2018-11-23T14:01:02 | 2018-11-23T14:01:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,029 | cpp | /*
* Sound.cpp
*
* Created on: Nov 2, 2018
* Author: giova
*/
#include "Sound.hh"
Sound::Sound() {
if(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 1, 8192) < 0){
LOGGER_ERROR("Falló al iniciar SDL_Mixer");
}
musicLogin = Mix_LoadMUS("../Sonidos/musica/login.mp3");
musicLevel1= Mix_LoadMUS("../Sonidos/musica/Stage1.mp3");
musicLevel2= Mix_LoadMUS("../Sonidos/musica/Stage2.mp3");
musicLevel3= Mix_LoadMUS("../Sonidos/musica/Stage3.mp3");
gameover= Mix_LoadMUS("../Sonidos/musica/gameOver.mp3");
stageclear= Mix_LoadMUS("../Sonidos/musica/stageclear.mp3");
boss= Mix_LoadMUS("../Sonidos/musica/boss.mp3");
item= Mix_LoadWAV("../Sonidos/effects/item.wav");
dead = Mix_LoadWAV("../Sonidos/player/dead.wav");
enemy_dead = Mix_LoadWAV("../Sonidos/enemys/enemyDead.wav");
bullet1 = Mix_LoadWAV("../Sonidos/bullet/bulletNormal.wav");
bullet2 = Mix_LoadWAV("../Sonidos/bullet/bulletTriple.wav");
bullet3 = Mix_LoadWAV("../Sonidos/bullet/hadoken.wav");
}
void Sound::play(int type, int subtype , int loops , int volumen){
switch(type){
case 0:{
if(subtype == 0){
Mix_PlayMusic(musicLogin,-1);
Mix_VolumeMusic(volumen);
}
if(subtype == 1){
Mix_PlayMusic(musicLevel1,-1);
Mix_VolumeMusic(volumen);
}
if(subtype == 2){
Mix_PlayMusic(musicLevel2,-1);
Mix_VolumeMusic(volumen);
}
if(subtype == 3){
Mix_PlayMusic(musicLevel3,-1);
Mix_VolumeMusic(volumen);
}
break;
}
case 1:{
if(subtype == 0){
Mix_PlayChannel(2,item,loops);
Mix_VolumeChunk(item, volumen);
}
if(subtype == 1){
Mix_HaltMusic();
Mix_PlayMusic(gameover,0);
Mix_VolumeMusic(volumen);
}
if(subtype == 2){
Mix_HaltMusic();
Mix_PlayMusic(stageclear,0);
Mix_VolumeMusic(volumen);
}
if(subtype == 3){
Mix_HaltMusic();
Mix_PlayMusic(boss,-1);
Mix_VolumeMusic(volumen);
}
break;
}
case 2:{
if(subtype == 0){
Mix_PlayChannel(4,enemy_dead, loops);
Mix_VolumeChunk(enemy_dead, volumen-20);
}
break;
}
case 3:{
if(subtype == 0){
Mix_PlayChannel(2,dead, loops);
Mix_VolumeChunk(dead, volumen+10);
}
break;
}
case 4:{
if(subtype == 0){
Mix_PlayChannel(3,bullet1, loops);
Mix_VolumeChunk(bullet1, volumen);
}
if(subtype == 1){
Mix_PlayChannel(3,bullet2, loops);
Mix_VolumeChunk(bullet2, volumen);
}
if(subtype == 2){
Mix_PlayChannel(3,bullet1, loops);
Mix_VolumeChunk(bullet1, volumen);
}
if(subtype == 3){
Mix_PlayChannel(3,bullet3, loops);
Mix_VolumeChunk(bullet3, volumen);
}
break;
}
}
}
void Sound::stopMusic(){
Mix_HaltMusic();
}
void Sound::destroy(){
Mix_FreeMusic(musicLogin);
Mix_FreeMusic(musicLevel1);
Mix_FreeMusic(musicLevel2);
Mix_FreeMusic(musicLevel3);
Mix_FreeChunk(bullet1);
Mix_Quit();
}
Sound::~Sound() {
// TODO Auto-generated destructor stub
}
| [
"masterpat45@gmail.com"
] | masterpat45@gmail.com |
d99e44ebe01fa78ce5257e1fbd7ac9a93eb7a004 | 5aa8a54280f446fa38b841922e1cd9c99e8e862f | /Upsolving/BAPC-18/i.cpp | c209bc6c0aa179467cd47ef029645ca892d247f9 | [] | no_license | lucasturci/Competitive_Programming | 72a458f8ed11a434d067f9cdf749b934da369339 | 8323aa16bcded05d2de83d057c51ace5fd63cfca | refs/heads/master | 2021-06-15T02:17:14.141431 | 2021-02-02T00:50:53 | 2021-02-02T00:50:53 | 130,897,029 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,881 | cpp | #include <bits/stdc++.h>
#define pb push_back
#define fi first
#define se second
#define eb emplace_back
using namespace std;
typedef long long ll;
typedef pair<int, int> ii;
const int N = 100007, inf = 0x3f3f3f3f;
vector<int> e[N], w[N];
int p[N];
int much[N];
ll dist[12][N];
int n, m;
struct ed {
int v;
int cap, f;
ll temp;
int version;
ed() {}
ed(int a, ll b, ll c, ll x) {
v = a;
cap = b;
f = c;
temp = x;
version = 0;
}
};
// pro flow
ed arestas[2 * (N * 12 + N + 12)];
int cur = 0;
int d[N + 20], ptr[N + 20];
vector<int> edges[N + 20];
void add_edge(int u, int v, ll cap, ll temp) {
arestas[cur] = ed(v, cap, 0, temp);
edges[u].pb(cur);
cur++;
arestas[cur] = ed(u, cap, cap, temp);
edges[v].pb(cur);
cur++;
}
int version;
ll maxt;
int bfs(int s, int t) {
int u, v;
queue<int> q;
memset(d, 0x3f, sizeof d);
q.push(s);
d[s] = 0;
while(q.size()) {
u = q.front();
q.pop();
for(int i = 0; i < edges[u].size(); ++i) {
int p = edges[u][i];
v = arestas[p].v;
if(arestas[p].temp > maxt) break;
if(arestas[p].version != version) {
arestas[p].version = version;
arestas[p].f = p%2 == 0? 0 : arestas[p].cap;
}
if(d[v] == inf and arestas[p].f < arestas[p].cap) {
d[v] = d[u] + 1;
q.push(v);
}
}
}
return d[t] < inf;
}
int dfs(int u, int f, int t) {
if(f == 0) return 0;
if(u == t) return f;
int v, p, tot;
for(int& i = ptr[u]; i < edges[u].size(); ++i) {
p = edges[u][i];
v = arestas[p].v;
if(arestas[p].temp > maxt) break;
if(arestas[p].version != version) {
arestas[p].version = version;
arestas[p].f = p%2 == 0? 0 : arestas[p].cap;
}
if(d[v] == d[u] + 1) {
tot = dfs(v, min(f, arestas[p].cap - arestas[p].f), t);
if(tot) {
arestas[p].f += tot;
arestas[p^1].f -= tot;
return tot;
}
}
}
return 0;
}
ll flow(int s, int t) {
ll f = 0;
while(bfs(s, t)) {
memset(ptr, 0, sizeof ptr);
while(ll tot = dfs(s, inf, t)) {
f += tot;
}
}
return f;
}
void dijkstra(int i, int s) {
priority_queue<pair<ll, int> > pq;
memset(dist[i], 0x3f, sizeof dist[i]);
pq.push(make_pair(0, s));
dist[i][s] = 0;
int u;
ll d;
while(pq.size()) {
d = pq.top().fi;
u = pq.top().se;
pq.pop();
d = -d;
if(d > dist[i][u]) continue;
for(int j = 0; j < e[u].size(); ++j) {
int v = e[u][j];
int c = w[u][j];
if(dist[i][v] > dist[i][u] + c) {
dist[i][v] = dist[i][u] + c;
pq.push(make_pair(-dist[i][v], v));
}
}
}
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int S;
cin >> n >> m >> S;
ll people = 0;
for(int i = 1; i <= n; ++i) {
cin >> p[i];
people += p[i];
}
for(int i = 0; i < m; ++i) {
int u, v, c; cin >> u >> v >> c;
e[u].pb(v);
e[v].pb(u);
w[u].pb(c);
w[v].pb(c);
}
vector<int> shelters;
for(int i = 0; i < S; ++i) {
int a, c; cin >> a >> c;
shelters.pb(a);
much[i] = c;
}
for(int i = 0; i < S; ++i) {
dijkstra(i, shelters[i]);
}
ll l = 0, r = 100000000000000ll;
ll ans, mid, x;
int s, t;
// limpa o grafo do flow
s = 0;
t = n + S + 1;
for(int i = 1; i <= n; ++i) {
add_edge(s, i, p[i], 0);
}
for(int i = 1; i <= n; ++i) {
for(int j = 0; j < S; ++j) {
add_edge(i, n + 1 + j, inf, dist[j][i]);
}
}
for(int i = 0; i < S; ++i) {
add_edge(n + 1 + i, t, much[i], 0);
}
for(int i = 0; i <= t; ++i) {
sort(edges[i].begin(), edges[i].end(), [=](int a, int b) {
return arestas[a].temp < arestas[b].temp;
});
}
while(l <= r) {
mid = l + (r - l)/2;
maxt = mid;
// faz o grafo do flow, colocando aresta so onde o custo eh menor ou igual a mid
// ve se o flow eh igual a todo mundo
x = flow(s, t);
if(x == people) {
ans = mid;
r = mid - 1;
} else {
l = mid + 1;
}
version++;
}
cout << ans << endl;
} | [
"lucas.turci@gmail.com"
] | lucas.turci@gmail.com |
a9d2300924007464b9caa1db824357a6e9ee05c9 | f6aa816de1d2e8e4ac69d0bb93e9d9604cb80e88 | /tests/tableDetectionTest.cpp | db6b13de40eeee4394cd4cb5b0642df501f0b2ea | [] | no_license | lxj0276/track | d2f334a5d417fddd3bf55cd3a891672c4aad0d3c | d4c40b5dba68b8d54afbd7ab1a3d6e069e0d2729 | refs/heads/master | 2021-04-06T04:08:23.186865 | 2018-02-19T14:20:16 | 2018-02-19T14:20:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 677 | cpp | #include <iostream>
#include <vector>
#include <sstream>
#include <opencv2/opencv.hpp>
#include "test_engine.hpp"
#include "detect_table.hpp"
using namespace std;
using namespace cv;
using vvr = vector<vector<Rect> >;
int main(int argc, char** argv){
vector<string> files = files_in_folder(string(argv[1]));
for (string file : files){
vvr gt, cells;
vector<string> text;
getGroundTruth(file, gt, cells, text);
save(file+pdf, file+tiff);
for (int i = 0; i < gt.size(); i++){
stringstream ss;
ss << file << "_" << i << tiff;
vector<Rect> d = detect_tables(ss.str());
cout << compare(gt[i], d) << endl;
}
}
return 0;
}
| [
"josefssonhenrik@hotmail.com"
] | josefssonhenrik@hotmail.com |
05a6f8142b68471cc6c217eb2289994cf995e6ee | 5ee0eb940cfad30f7a3b41762eb4abd9cd052f38 | /Case_save/case2/100/phi | cf4ecad400daae737744b144c982085e5208c778 | [] | no_license | mamitsu2/aircond5_play4 | 052d2ff593661912b53379e74af1f7cee20bf24d | c5800df67e4eba5415c0e877bdeff06154d51ba6 | refs/heads/master | 2020-05-25T02:11:13.406899 | 2019-05-20T04:56:10 | 2019-05-20T04:56:10 | 187,570,146 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,486 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 6
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class surfaceScalarField;
location "100";
object phi;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [1 0 -1 0 0 0 0];
internalField nonuniform List<scalar>
852
(
-0.00376484
0.00382313
-0.00530579
0.00154051
-0.00554375
0.00023754
-0.00447152
-0.00107263
-0.00255008
-0.00192182
-0.000430112
-0.00212034
0.00135296
-0.00178346
0.00265087
-0.00129829
0.00349891
-0.000848437
0.00396577
-0.000467278
0.00410002
-0.00013468
0.0039208
0.000178785
0.003391
0.000529369
0.00232588
0.0010647
0.00232834
-0.00110459
0.00110727
-0.0014569
0.000352068
-0.000860141
-0.000596992
8.45929e-05
-0.000944962
0.000963185
-0.000878817
0.00163105
-0.000668094
0.00202001
-0.000389181
0.0022042
-0.000184427
0.00231181
-0.000107837
0.00238927
-7.77082e-05
0.00244737
-5.83414e-05
0.00249091
-4.37983e-05
0.00251771
-2.70647e-05
0.00251114
6.28844e-06
0.00243197
7.88856e-05
0.00221354
0.000218137
0.00180544
0.000407794
0.00115585
0.000649266
0.00115859
-0.00260044
0.00658496
-0.00379776
0.00273738
-0.0037175
0.000156825
-0.00243098
-0.00235958
-0.000746322
-0.0036069
0.00079823
-0.0036653
0.0020806
-0.00306622
0.00305385
-0.00227191
0.0037042
-0.00149915
0.00405189
-0.00081532
0.00413872
-0.000221889
0.00399815
0.000318951
0.003671
0.000856093
0.0032997
0.00143559
0.00360486
0.0020228
0.00175699
0.00184746
0.00175664
-0.000471164
0.00158704
-2.9952e-05
-8.94049e-05
0.000723329
-0.00135051
0.00126686
-0.00148872
0.00172724
-0.00133943
0.00208606
-0.00102714
0.00217554
-0.000478893
0.00219455
-0.000203659
0.00221411
-0.00012762
0.00223036
-9.4197e-05
0.00224173
-6.99452e-05
0.0022501
-5.24226e-05
0.00225537
-3.26057e-05
0.0022497
1.16901e-05
0.00218984
0.000138449
0.00193769
0.000469984
0.00150142
0.000843756
0.000903773
0.00124658
0.00207073
-0.00164528
0.00848014
-0.00230799
0.00339959
-0.00148378
-0.000667932
2.56149e-05
-0.00386946
0.00134265
-0.00492443
0.00235767
-0.00468081
0.00316176
-0.00387078
0.00374449
-0.00285507
0.00409812
-0.00185317
0.00424373
-0.000961288
0.00421532
-0.000193823
0.00405003
0.000483867
0.00380359
0.00110214
0.00354801
0.00169077
0.00328053
0.00228989
0.00235424
0.00277339
0.00411058
0.00123104
0.000370703
0.00204631
-0.000904934
0.00220023
-0.00150468
0.00235841
-0.00164714
0.002514
-0.00149527
0.00276508
-0.00127845
0.00228611
0.00208238
0.00195469
0.00186042
0.00179039
0.00173787
0.00170515
0.00171671
0.00185501
0.00151732
0.000807362
0.00114167
0.00121907
0.000662737
0.00172518
0.00274713
-0.00119803
0.0100056
-0.000406971
0.002608
0.00142094
-0.00249638
0.00282306
-0.00527209
0.00364138
-0.00574329
0.00413318
-0.00517319
0.00439587
-0.00413404
0.00449221
-0.00295195
0.00446233
-0.00182376
0.00433673
-0.000836102
0.00412479
1.77472e-05
0.00386301
0.000745287
0.00361057
0.00135419
0.00342334
0.00187761
0.00336703
0.0023458
0.00352534
0.00261471
0.00496389
0.0026717
0.00375974
0.00121905
0.00391974
0.000210423
0.00370483
-0.000690281
0.00341987
-0.00121999
0.00314535
-0.00137288
0.00290097
-0.00125115
0.002555
-0.00093273
0.00290347
-0.000348891
0.00298666
-8.35966e-05
0.00295672
2.95231e-05
0.00285478
0.000101523
0.00269314
0.000161213
0.00247336
0.00021935
0.0021832
0.000289728
0.00178905
0.000393697
0.00121474
0.000573843
0.00104402
0.000977758
0.000784464
0.00147829
0.000474777
0.00203452
0.00324051
-0.000800605
0.0112132
0.00171366
9.31073e-05
0.00491715
-0.00570041
0.00598711
-0.00634258
0.00608401
-0.00584078
0.00578913
-0.00487896
0.00533044
-0.00367604
0.00482678
-0.00244897
0.00434153
-0.0013391
0.00387116
-0.000366228
0.00343393
0.000454569
0.00309384
0.001085
0.00289023
0.00155742
0.00285013
0.00191731
0.00302167
0.00217387
0.00339926
0.00223676
0.00398853
0.00208209
0.00401322
0.00119404
0.0040173
0.000206045
0.00378756
-0.000460845
0.00340502
-0.000837747
0.00298294
-0.000951112
0.0025869
-0.00085541
0.00225781
-0.000603937
0.00215079
-0.000242171
0.00203841
2.84843e-05
0.00189116
0.000176466
0.00173572
0.000256657
0.00157937
0.000317251
0.00141678
0.000381626
0.00123775
0.00046843
0.00103183
0.000599287
0.000815903
0.000789431
0.000697795
0.00109552
0.000667431
0.0015083
0.00060815
0.00209346
0.00106743
0.00278089
-0.000710627
0.00177759
-0.00126523
0.000553771
-0.00122072
0.00774901
0.00395348
0.0108347
-0.00299306
0.0102898
-0.00515605
0.00916088
-0.00521421
0.00785809
-0.00453865
0.00647256
-0.00349418
0.00515815
-0.00236242
0.00403122
-0.00132283
0.00306859
-0.000377165
0.00229896
0.000402809
0.00181903
0.000934044
0.00161171
0.00129194
0.00159936
0.0015694
0.00173974
0.00177657
0.00202237
0.00189086
0.00240734
0.00185143
0.00288547
0.0016036
0.00313885
0.00094032
0.00308049
0.000264063
0.00282754
-0.000208227
0.00245644
-0.000466988
0.00204355
-0.000538565
0.00164734
-0.000459541
0.00131295
-0.000269886
0.00108067
-1.02296e-05
0.000914354
0.000194463
0.000784914
0.000305566
0.000675384
0.000365845
0.000582679
0.000409614
0.000507026
0.000456933
0.000451095
0.00052401
0.000421821
0.000628203
0.000429663
0.000781225
0.000530788
0.000994029
0.00077875
0.00125998
0.00116018
0.00171167
0.00179812
0.00214259
0.0021337
0.0014417
0.00179018
0.000896892
0.000625007
0.0119359
-0.00737581
0.012822
-0.00387962
0.0107383
-0.00307281
0.00816174
-0.00263841
0.00594678
-0.00232453
0.00396952
-0.00151778
0.00232497
-0.000718765
0.00103877
-3.7487e-05
0.000206006
0.000454899
-0.000141769
0.000750119
-0.000191246
0.000983129
-9.45656e-05
0.00119489
0.000105159
0.00136931
0.000391725
0.00148963
0.000751869
0.00153034
0.00115333
0.00144959
0.00154841
0.00120814
0.00172942
0.000758925
0.00166772
0.000325383
0.00144203
1.70826e-05
0.00111969
-0.000145028
0.000759427
-0.000178679
0.000408976
-0.000109469
0.000108316
3.03972e-05
-9.44423e-05
0.000192154
-0.000207428
0.000307074
-0.000274604
0.000372371
-0.000314934
0.000405806
-0.00032875
0.000423062
-0.000307958
0.000435772
-0.00023961
0.000455291
-0.000106914
0.000495132
0.000103049
0.00057088
0.000398652
0.000698051
0.000803262
0.000854993
0.00135609
0.00115847
0.00214858
0.00134974
0.00276285
0.000827082
0.00283154
0.000827844
0.00351806
-0.000709045
-0.0059128
-0.00166064
-0.00292888
-1.71381e-05
-0.00471766
-0.000361543
-0.00229493
-0.00111079
-0.00157596
-0.0017062
-0.000922989
-0.00206037
-0.000365193
-0.00217924
8.08296e-05
-0.00213098
0.000406131
-0.00201871
0.000637416
-0.00184968
0.000813694
-0.0016174
0.00096224
-0.00132798
0.0010795
-0.000990912
0.00115218
-0.00062271
0.00116174
-0.00025976
0.00108623
3.40747e-05
0.000913877
0.000143751
0.00064882
7.23598e-05
0.000396346
-0.000120359
0.000209378
-0.000374911
0.000109106
-0.00064757
9.35624e-05
-0.00089452
0.000137062
-0.00107652
0.000211979
-0.00117667
0.00029189
-0.00122076
0.000350764
-0.00123018
0.000381396
-0.00121218
0.000387405
-0.00116252
0.000373012
-0.00107
0.000342865
-0.000920478
0.000305379
-0.000701108
0.00027537
-0.000403595
0.000272973
-2.50617e-05
0.000319124
0.000401008
0.000428527
0.000918905
0.000640183
0.00151382
0.000754449
0.00171889
0.000621645
0.000786144
0.00176023
0.00455402
-0.00489319
-0.00778155
-0.00456786
-0.00793191
-0.00348644
-0.00337696
-0.00362399
-0.00143898
-0.00381346
-0.000734063
-0.00386942
-0.000309759
-0.00380087
1.17862e-05
-0.00365205
0.000256834
-0.00345611
0.000441025
-0.00322565
0.000582803
-0.00295935
0.000695526
-0.00266064
0.000780368
-0.00234048
0.000831604
-0.00201955
0.000840371
-0.00173215
0.000798372
-0.00152298
0.000704245
-0.00144209
0.000567454
-0.00147797
0.000431756
-0.00159418
0.000325122
-0.00174696
0.000261415
-0.00189543
0.000241574
-0.00201302
0.000254202
-0.00208659
0.000285093
-0.00211573
0.000320593
-0.00211414
0.000348746
-0.00209763
0.000364463
-0.00207858
0.000367943
-0.00206831
0.000362327
-0.00208079
0.000354924
-0.00213551
0.000359685
-0.00225836
0.000397791
-0.00248122
0.000495419
-0.00284531
0.000682802
-0.00341502
0.000997826
-0.00424442
0.00146919
-0.00548775
0.00199739
-0.00717061
0.00230412
-0.00710396
0.00169317
-0.00229611
-0.00100507
-0.000775082
-0.00371561
-0.000666982
-0.00452732
-0.000627825
-0.00485355
-0.000408373
-0.00496317
-0.000200671
-0.0049342
-1.76898e-05
-0.00481607
0.000138211
-0.00464125
0.000265723
-0.00442612
0.000367196
-0.00417913
0.000448065
-0.00390928
0.000510053
-0.00362976
0.000551607
-0.00335938
0.000569506
-0.00312231
0.000560797
-0.00294353
0.000524964
-0.00284317
0.000466581
-0.00281387
0.000401945
-0.00283397
0.000344718
-0.00287681
0.000303754
-0.00291783
0.000282105
-0.00294117
0.000277062
-0.00293994
0.000283385
-0.00291475
0.000294929
-0.00287249
0.000306032
-0.00282242
0.000313932
-0.0027739
0.000318967
-0.00273614
0.00032411
-0.00271703
0.000335359
-0.00272089
0.00036309
-0.00274715
0.000423594
-0.00279201
0.000539823
-0.00284979
0.000740153
-0.00290094
0.00104855
-0.00288867
0.00145651
-0.00276885
0.00187716
-0.00225602
0.00179089
-0.000774097
0.000210827
-0.00301406
-0.00364724
0.00287338
-0.00486712
0.000552318
-0.00549929
3.76946e-06
-0.00581887
-8.93528e-05
-0.00595139
-6.87023e-05
-0.00595937
-1.02519e-05
-0.00588169
6.0002e-05
-0.00574117
0.000124681
-0.0055537
0.000179202
-0.0053306
0.000224454
-0.00508235
0.000261282
-0.00482075
0.000289482
-0.00455982
0.000308045
-0.00431523
0.000315667
-0.00410217
0.000311354
-0.00393205
0.000295924
-0.00380498
0.000274332
-0.00371271
0.000251912
-0.00364266
0.000233177
-0.0035819
0.000220826
-0.00352065
0.000215297
-0.00345326
0.000215485
-0.00337795
0.000219113
-0.00329583
0.000223412
-0.0032089
0.000226501
-0.00311855
0.000228106
-0.00302473
0.000229784
-0.00292494
0.000235068
-0.00281199
0.000249641
-0.00267072
0.000281824
-0.00247609
0.000344709
-0.00219597
0.000459559
-0.0017893
0.000641417
-0.00117006
0.00083682
-0.000129418
0.000836075
0.0013186
0.000342434
0.00222017
-0.000691224
-0.00073268
-0.00783823
-0.0103023
-0.00743574
-0.00689435
-0.0069029
-0.00700471
-0.00708588
-0.00710864
-0.00706122
-0.00694932
-0.00678326
-0.00657243
-0.00632539
-0.00605091
-0.00575873
-0.00545992
-0.00516651
-0.00488967
-0.00463558
-0.004405
-0.00419416
-0.00399653
-0.00380516
-0.00361418
-0.00342005
-0.003222
-0.00302112
-0.00281875
-0.00261464
-0.002405
-0.00218031
-0.00192276
-0.00160141
-0.00116412
-0.000543767
0.000273084
0.00108929
0.00140975
0.000692985
)
;
boundaryField
{
floor
{
type calculated;
value nonuniform List<scalar>
29
(
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
-3.07526e-06
-8.70341e-06
-1.40038e-05
-1.89504e-05
-2.83785e-06
-2.92923e-06
-8.874e-06
-1.49648e-05
-1.52022e-05
)
;
}
ceiling
{
type calculated;
value nonuniform List<scalar>
43
(
7.86096e-06
6.64545e-06
6.24576e-06
1.03202e-05
1.17247e-05
1.18636e-05
1.18869e-05
1.19247e-05
1.20004e-05
1.22077e-05
1.25615e-05
1.30525e-05
1.36738e-05
1.44218e-05
1.52923e-05
1.62776e-05
1.73608e-05
1.85082e-05
1.96652e-05
2.07709e-05
2.17725e-05
2.26382e-05
2.33617e-05
2.3955e-05
2.44345e-05
2.48074e-05
2.50633e-05
2.51776e-05
2.51209e-05
2.48684e-05
2.44032e-05
2.37172e-05
2.28134e-05
2.17212e-05
2.05362e-05
1.94465e-05
1.93538e-05
2.14341e-05
2.4922e-05
3.0124e-05
-2.96735e-05
-4.11769e-05
-1.72329e-06
)
;
}
sWall
{
type calculated;
value uniform -0.000219044;
}
nWall
{
type calculated;
value nonuniform List<scalar> 6(-4.52374e-05 -5.59555e-05 -6.18905e-05 -5.67168e-05 -6.17801e-05 -7.05066e-05);
}
sideWalls
{
type empty;
value nonuniform 0();
}
glass1
{
type calculated;
value nonuniform List<scalar> 9(-5.87361e-05 -0.000161839 -0.000250361 -0.000327852 -0.000407474 -0.000489776 -0.000607036 -0.00075469 -0.000990788);
}
glass2
{
type calculated;
value nonuniform List<scalar> 2(-0.000250178 -0.000254247);
}
sun
{
type calculated;
value uniform 0;
}
heatsource1
{
type calculated;
value nonuniform List<scalar> 3(2.03851e-07 2.03519e-07 2.03668e-07);
}
heatsource2
{
type calculated;
value nonuniform List<scalar> 4(5.13058e-08 5.1519e-08 0 0);
}
Table_master
{
type calculated;
value nonuniform List<scalar> 9(-1.53389e-07 -1.53611e-07 -1.53665e-07 -1.53687e-07 -1.53691e-07 -1.53682e-07 -1.53661e-07 -1.53625e-07 -1.53532e-07);
}
Table_slave
{
type calculated;
value nonuniform List<scalar> 9(1.53037e-07 1.5305e-07 1.53005e-07 1.52971e-07 1.52964e-07 1.52978e-07 1.53013e-07 1.53071e-07 1.53164e-07);
}
inlet
{
type calculated;
value uniform -0.00615198;
}
outlet
{
type calculated;
value nonuniform List<scalar> 2(0.00804881 0.00245681);
}
}
// ************************************************************************* //
| [
"mitsuaki.makino@tryeting.jp"
] | mitsuaki.makino@tryeting.jp | |
783a3b88f2b56975dd2f086dd02ced6cf3c8cc4d | 5bd4fa05d80dec401a1c8da361a8cde30c6c1876 | /Top Level/ESP32/Main_Code_2_Robot_1/convTwosComp.ino | ef1938b3f2cd9e29481cd96751db00760c184e60 | [] | no_license | infrareadyrobotics/Robocup2019 | 37dd70dcb72dbafd5f1860539d42fa1bcaa00c7b | f4e65dbcacf2639c65821e3ad16078841aace49c | refs/heads/master | 2020-06-10T11:30:48.544582 | 2019-07-07T08:14:20 | 2019-07-07T08:14:20 | 193,640,624 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 163 | ino | //Convert to int from two's complement
int convTwosComp(int b) { //Convert from 2's complement
if (b & 0x80) {
b = -1 * ((b ^ 0xff) + 1);
}
return b;
}
| [
"31533893+QuickStick123@users.noreply.github.com"
] | 31533893+QuickStick123@users.noreply.github.com |
e70d09b1d7d1ff4ff43de62a15869daaab78cc2e | 8630006b8a455e964a32d136cab3301f24040b93 | /Engine/PIL/Threads/Mutex.h | 3994422da2c4ff698110dc2db3f153b987c97584 | [] | no_license | NickCullen/vici | f66f8a88f0d8220abc5f39de1282f5354d20417f | 8a1378edca4259af60930a8ce565a9418630a8d6 | refs/heads/master | 2021-01-15T15:33:21.614800 | 2016-07-14T19:32:59 | 2016-07-14T19:32:59 | 28,966,385 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 57 | h | #pragma once
#include <mutex>
#define VMutex std::mutex | [
"nmcullen91@gmail.com"
] | nmcullen91@gmail.com |
2b2744ffcf6f055e0d411604e6add8a14dd1f848 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/git/gumtree/git_old_log_2957.cpp | 4f0ff6a5cbed237f4aebf87ab232f91b8e3c1219 | [] | 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 | 62 | cpp | error("Writing %s failed: %s", path,
strerror(errno)); | [
"993273596@qq.com"
] | 993273596@qq.com |
966c005324bc5680e62e93e81176792a1bccc7a2 | 911979f76cec93f1e819f0617dbee74b7074dfcf | /OpenCV/DrawLine.cpp | 60a31f75caa626356c45d063fa20fdec04c67ad0 | [] | no_license | bigbiggo999/CodeClub | f52faa43c184295d6f0c0d4a632850c4a34968d6 | 3b62ecede182b7697f11f5d2dc2cb63f5c3ccc01 | refs/heads/master | 2022-02-23T21:05:19.626018 | 2019-09-18T15:52:17 | 2019-09-18T15:52:17 | 110,957,705 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,339 | cpp | #include <iostream>
#include "opencv2/opencv.hpp"
#include <opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
using namespace std;
using namespace cv;
int main(int argc, char* argv[]) {
//Mat im(600,800, CV_8UC1);
Mat im(600,800,CV_8UC3);
namedWindow("image");
int k,j;
/**
*用at方法给每个像素设置值
for(int i=0;i<im.rows;i++){
for(int j=0;j<im.cols;j++){
im.at<uchar>(i,j)=0;
}
}
*/
/**
*用迭代器方法给每个像素设置值
MatIterator_<uchar> Mbegin,Mend;
for(Mbegin=im.begin<uchar>(),Mend=im.end<uchar>();Mbegin!=Mend;Mbegin++){
*Mbegin=255;
}
*/
/**
*用指针方法给每个像素设置值
*/
for(int i=0;i<im.rows;i++){
Vec3b *p = im.ptr<Vec3b>(i);
for(int j=0;j<im.cols;j++){
p[j][0]=0;
p[j][1]=0;
p[j][2]=0;
}
}
if( im.empty()){
cout << "Can not load image." << endl;
return -1;
}
int i=100;
Vec3b *p=im.ptr<Vec3b>(i);
Vec3b *p2=im.ptr<Vec3b>(i+1);
Vec3b *p3=im.ptr<Vec3b>(i+2);
for( j=0,k=0;j<im.cols-600;j++){
p[j][0]=0;
p[j][1]=0;
p[j][2]=255;
p2[j][0]=0;
p2[j][1]=0;
p2[j][2]=255;
p3[j][0]=0;
p3[j][1]=0;
p3[j][2]=255;
cvWaitKey(5);
imshow("image", im);
if(j>20){
while(k<j-20){
p[k][0]=0;
p[k][1]=0;
p[k][2]=0;
p2[k][0]=0;
p2[k][1]=0;
p2[k][2]=0;
p3[k][0]=0;
p3[k][1]=0;
p3[k][2]=0;
k++;
}
}
}
while(k<j){
p[k][0]=0;
p[k][1]=0;
p[k][2]=0;
p2[k][0]=0;
p2[k][1]=0;
p2[k][2]=0;
p3[k][0]=0;
p3[k][1]=0;
p3[k][2]=0;
k++;
cvWaitKey(5);
imshow("image", im);
}
k=j;
for(;i<im.rows;i++){
Vec3b *p=im.ptr<Vec3b>(i);
j=k;
for(;j<k+7;j++){
p[j][0]=0;
p[j][1]=0;
p[j][2]=255;
}
cvWaitKey(5);
imshow("image", im);
}
waitKey(0);
return 0;
}
| [
"bigbiggo999@gmail.com"
] | bigbiggo999@gmail.com |
a035dc90adc1a4d1e1ee8ca4117fa1f664e83b05 | 0e3e023ff2f4c9c804d7522f4ca68acb70d63c5b | /shadow.cpp | 23f81bd28eac40aaf7bbb1ad3766a86fad369fcc | [] | no_license | gonatama/syuusyoku | 736262ecfb887f4255a45564c9c3f3a8053e1bb9 | 4e92b3abfe40c3e270a24f777740d27f9cc6f7e1 | refs/heads/master | 2020-04-16T22:09:21.295643 | 2019-02-28T06:16:53 | 2019-02-28T06:16:53 | 165,955,441 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 11,485 | cpp | //=============================================================================
//
// 影処理 [shadow.cpp]
// Author :
//
//=============================================================================
#include "shadow.h"
//*****************************************************************************
// マクロ定義
//*****************************************************************************
#define TEXTURE_SHADOW "data/TEXTURE/shadow000.jpg" // 読み込むテクスチャファイル名
#define SHADOW_SIZE_X (50.0f) // 弾の幅
#define SHADOW_SIZE_Z (50.0f) // 弾の高さ
#define MAX_SHADOW (128) // 影最大数
//*****************************************************************************
// 構造体定義
//*****************************************************************************
typedef struct
{
D3DXMATRIX mtxWorld; // ワールドマトリックス
D3DXVECTOR3 pos; // 位置
D3DXVECTOR3 rot; // 回転
bool bUse; // 使用しているかどうか
} SHADOW;
//*****************************************************************************
// プロトタイプ宣言
//*****************************************************************************
HRESULT MakeVertexShadow(LPDIRECT3DDEVICE9 pDevice);
//*****************************************************************************
// グローバル変数
//*****************************************************************************
LPDIRECT3DTEXTURE9 g_pD3DTextureShadow = NULL; // テクスチャへのポインタ
LPDIRECT3DVERTEXBUFFER9 g_pD3DVtxBuffShadow = NULL; // 頂点バッファインターフェースへのポインタ
SHADOW g_aShadow[MAX_SHADOW]; // 影ワーク
//=============================================================================
// 初期化処理
//=============================================================================
HRESULT InitShadow(void)
{
LPDIRECT3DDEVICE9 pDevice = GetDevice();
// 頂点情報の作成
MakeVertexShadow(pDevice);
// テクスチャの読み込み
D3DXCreateTextureFromFile(pDevice, // デバイスへのポインタ
TEXTURE_SHADOW, // ファイルの名前
&g_pD3DTextureShadow); // 読み込むメモリー
for(int nCntShadow = 0; nCntShadow < MAX_SHADOW; nCntShadow++)
{
g_aShadow[nCntShadow].pos = D3DXVECTOR3(0.0f, 0.1f, 0.0f);
g_aShadow[nCntShadow].rot = D3DXVECTOR3(0.0f, 0.0f, 0.0f);
g_aShadow[nCntShadow].bUse = false;
}
return S_OK;
}
//=============================================================================
// 終了処理
//=============================================================================
void UninitShadow(void)
{
if(g_pD3DTextureShadow != NULL)
{// テクスチャの開放
g_pD3DTextureShadow->Release();
g_pD3DTextureShadow = NULL;
}
if(g_pD3DVtxBuffShadow != NULL)
{// 頂点バッファの開放
g_pD3DVtxBuffShadow->Release();
g_pD3DVtxBuffShadow = NULL;
}
}
//=============================================================================
// 更新処理
//=============================================================================
void UpdateShadow(void)
{
}
//=============================================================================
// 描画処理
//=============================================================================
void DrawShadow(void)
{
LPDIRECT3DDEVICE9 pDevice = GetDevice();
D3DXMATRIX mtxRot, mtxTranslate;
#if 0
D3DXQUATERNION quat;
D3DXVECTOR3 vecUpObj, vecUpField, outVec;
float fDotProduct,fRot;
#endif
// 減算合成
pDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_REVSUBTRACT); // 結果 = 転送先(DEST) - 転送元(SRC)
pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
// Z比較なし
pDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
for(int nCntShadow = 0; nCntShadow < MAX_SHADOW; nCntShadow++)
{
if(g_aShadow[nCntShadow].bUse)
{
// ワールドマトリックスの初期化
D3DXMatrixIdentity(&g_aShadow[nCntShadow].mtxWorld);
#if 0
// 回転を反映
D3DXQuaternionIdentity(&quat);
vecUpObj = D3DXVECTOR3(0.0f, 1.0f, 0.0f); // オブジェクトの上方向
vecUpField = D3DXVECTOR3(0.0f, 1.0f, 0.0f); // 地面の法線
// オブジェクトの上方向と地面の法線の外積から回転軸を求める
D3DXVec3Cross(&outVec, &vecUpObj, &vecUpField);
// オブジェクトの上方向と地面の法線のなす角を求める
fDotProduct = D3DXVec3Dot(&vecUpObj, &vecUpField);
fRot = acosf(fDotProduct / (sqrtf(vecUpObj.x * vecUpObj.x + vecUpObj.y * vecUpObj.y + vecUpObj.z * vecUpObj.z)
* sqrtf(vecUpField.x * vecUpField.x + vecUpField.y * vecUpField.y + vecUpField.z * vecUpField.z)));
// 回転軸となす角からクォータニオンを求め、回転マトリックスを算出
D3DXQuaternionRotationAxis(&quat, &outVec, fRot);
D3DXMatrixRotationQuaternion(&mtxRot, &quat);
D3DXMatrixMultiply(&g_mtxWorldShadow, &g_mtxWorldShadow, &mtxRot);
#endif
// 回転を反映
D3DXMatrixRotationYawPitchRoll(&mtxRot, g_aShadow[nCntShadow].rot.y, g_aShadow[nCntShadow].rot.x, g_aShadow[nCntShadow].rot.z);
D3DXMatrixMultiply(&g_aShadow[nCntShadow].mtxWorld, &g_aShadow[nCntShadow].mtxWorld, &mtxRot);
// 移動を反映
D3DXMatrixTranslation(&mtxTranslate, g_aShadow[nCntShadow].pos.x,
g_aShadow[nCntShadow].pos.y,
g_aShadow[nCntShadow].pos.z);
D3DXMatrixMultiply(&g_aShadow[nCntShadow].mtxWorld,
&g_aShadow[nCntShadow].mtxWorld, &mtxTranslate);
// ワールドマトリックスの設定
pDevice->SetTransform(D3DTS_WORLD, &g_aShadow[nCntShadow].mtxWorld);
// 頂点バッファをレンダリングパイプラインに設定
pDevice->SetStreamSource(0, g_pD3DVtxBuffShadow, 0, sizeof(VERTEX_3D));
// 頂点フォーマットの設定
pDevice->SetFVF(FVF_VERTEX_3D);
// テクスチャの設定
pDevice->SetTexture(0, g_pD3DTextureShadow);
// ポリゴンの描画
pDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, (nCntShadow * 4), NUM_POLYGON);
}
}
// 通常ブレンド
pDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD); // 結果 = 転送元(SRC) + 転送先(DEST)
pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
// Z比較あり
pDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_LESSEQUAL);
}
//=============================================================================
// 頂点情報の作成
//=============================================================================
HRESULT MakeVertexShadow(LPDIRECT3DDEVICE9 pDevice)
{
// オブジェクトの頂点バッファを生成
if(FAILED(pDevice->CreateVertexBuffer(sizeof(VERTEX_3D) * NUM_VERTEX * MAX_SHADOW, // 頂点データ用に確保するバッファサイズ(バイト単位)
D3DUSAGE_WRITEONLY, // 頂点バッファの使用法
FVF_VERTEX_3D, // 使用する頂点フォーマット
D3DPOOL_MANAGED, // リソースのバッファを保持するメモリクラスを指定
&g_pD3DVtxBuffShadow, // 頂点バッファインターフェースへのポインタ
NULL))) // NULLに設定
{
return E_FAIL;
}
{//頂点バッファの中身を埋める
VERTEX_3D *pVtx;
// 頂点データの範囲をロックし、頂点バッファへのポインタを取得
g_pD3DVtxBuffShadow->Lock(0, 0, (void**)&pVtx, 0);
for(int nCntShadow = 0; nCntShadow < MAX_SHADOW; nCntShadow++, pVtx += 4)
{
// 頂点座標の設定
pVtx[0].vtx = D3DXVECTOR3(-SHADOW_SIZE_X / 2, 0.0f, SHADOW_SIZE_Z / 2);
pVtx[1].vtx = D3DXVECTOR3(SHADOW_SIZE_X / 2, 0.0f, SHADOW_SIZE_Z / 2);
pVtx[2].vtx = D3DXVECTOR3(-SHADOW_SIZE_X / 2, 0.0f, -SHADOW_SIZE_Z / 2);
pVtx[3].vtx = D3DXVECTOR3(SHADOW_SIZE_X / 2, 0.0f, -SHADOW_SIZE_Z / 2);
// 法線の設定
pVtx[0].nor = D3DXVECTOR3(0.0f, 1.0f, 0.0f);
pVtx[1].nor = D3DXVECTOR3(0.0f, 1.0f, 0.0f);
pVtx[2].nor = D3DXVECTOR3(0.0f, 1.0f, 0.0f);
pVtx[3].nor = D3DXVECTOR3(0.0f, 1.0f, 0.0f);
// 反射光の設定
pVtx[0].diffuse = D3DXCOLOR(0.5f, 0.5f, 0.5f, 0.5f);
pVtx[1].diffuse = D3DXCOLOR(0.5f, 0.5f, 0.5f, 0.5f);
pVtx[2].diffuse = D3DXCOLOR(0.5f, 0.5f, 0.5f, 0.5f);
pVtx[3].diffuse = D3DXCOLOR(0.5f, 0.5f, 0.5f, 0.5f);
// テクスチャ座標の設定
pVtx[0].tex = D3DXVECTOR2(0.0f, 0.0f);
pVtx[1].tex = D3DXVECTOR2(1.0f, 0.0f);
pVtx[2].tex = D3DXVECTOR2(0.0f, 1.0f);
pVtx[3].tex = D3DXVECTOR2(1.0f, 1.0f);
}
// 頂点データをアンロックする
g_pD3DVtxBuffShadow->Unlock();
}
return S_OK;
}
//=============================================================================
// 頂点座標の設定
//=============================================================================
void SetVertexShadow(int nIdxShadow, float fSizeX, float fSizeZ)
{
{//頂点バッファの中身を埋める
VERTEX_3D *pVtx;
// 頂点データの範囲をロックし、頂点バッファへのポインタを取得
g_pD3DVtxBuffShadow->Lock(0, 0, (void**)&pVtx, 0);
pVtx += (nIdxShadow * 4);
// 頂点座標の設定
pVtx[0].vtx = D3DXVECTOR3(-fSizeX / 2, 0.0f, fSizeZ / 2);
pVtx[1].vtx = D3DXVECTOR3(fSizeX / 2, 0.0f, fSizeZ / 2);
pVtx[2].vtx = D3DXVECTOR3(-fSizeX / 2, 0.0f, -fSizeZ / 2);
pVtx[3].vtx = D3DXVECTOR3(fSizeX / 2, 0.0f, -fSizeZ / 2);
// 頂点データをアンロックする
g_pD3DVtxBuffShadow->Unlock();
}
}
//=============================================================================
// 頂点カラーの設定
//=============================================================================
void SetColorShadow(int nIdxShadow, D3DXCOLOR col)
{
{//頂点バッファの中身を埋める
VERTEX_3D *pVtx;
// 頂点データの範囲をロックし、頂点バッファへのポインタを取得
g_pD3DVtxBuffShadow->Lock(0, 0, (void**)&pVtx, 0);
pVtx += (nIdxShadow * 4);
// 頂点座標の設定
pVtx[0].diffuse =
pVtx[1].diffuse =
pVtx[2].diffuse =
pVtx[3].diffuse = col;
// 頂点データをアンロックする
g_pD3DVtxBuffShadow->Unlock();
}
}
//=============================================================================
// 影の作成
//=============================================================================
int CreateShadow(D3DXVECTOR3 pos, float fSizeX, float fSizeZ)
{
int nIdxShadow = -1;
for(int nCntShadow = 0; nCntShadow < MAX_SHADOW; nCntShadow++)
{
if(!g_aShadow[nCntShadow].bUse)
{
g_aShadow[nCntShadow].pos = pos;
g_aShadow[nCntShadow].rot = D3DXVECTOR3(0.0f, 0.0f, 0.0f);
g_aShadow[nCntShadow].bUse = true;
SetVertexShadow(nCntShadow, fSizeX, fSizeZ);
nIdxShadow = nCntShadow;
break;
}
}
return nIdxShadow;
}
//=============================================================================
// 影の破棄
//=============================================================================
void ReleaseShadow(int nIdxShadow)
{
if(nIdxShadow >= 0 && nIdxShadow < MAX_SHADOW)
{
g_aShadow[nIdxShadow].bUse = false;
}
}
//=============================================================================
// 位置の設定
//=============================================================================
void SetPositionShadow(int nIdxShadow, D3DXVECTOR3 pos)
{
g_aShadow[nIdxShadow].pos = pos;
}
| [
"try.to.avoid@gmail.com"
] | try.to.avoid@gmail.com |
b0239923cede84959815c8103ad4f7dd7acd8ec8 | 2922f5512a4741f1cc084a0857704fa2c88fcce9 | /engqtest/plotter_code/coll2d.cpp | 29f7a801ba5f3e67bfd5efa0937204d1ebc16799 | [] | no_license | RickKoenig/engq | 3544a7c01ff6b05c732a19607ee5424e0086e7f3 | 87ea08727bc0aea508221f0210e1f8f52ef066b9 | refs/heads/master | 2023-07-26T06:35:31.377976 | 2022-04-05T05:52:53 | 2022-04-05T05:52:53 | 242,048,482 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,196 | cpp | //#define BOX2BOX
//#define CIRCLE2BOX
//#define CIRCLE2CIRCLE
#define COLLUTILS
//#define BOXPOINT
#ifdef COLLUTILS
//#define OLDPLANK2PLANK
//#define NEWCP
void calcbox2box()
{
calcpr(box0);
calcpr(box1);
//acollide = util_plank2plank(box0,box1,abestcp,abestpendir,penm);
#ifdef BOXPOINT
pcollide = util_point2plank(point0,box1);
ldist = util_point2line(point0,la,lb);
}
// dot product of 2 vectors
float sdot2vv(const pointf2& a,const pointf2& b)
{
return a.x*b.x + a.y*b.y;
}
// product of scalar with vector
pointf2 vmul2sv(float s,const pointf2& v)
{
return pointf2x(s * v.x,s * v.y);
}
pointf2 vadd2vv(const pointf2& a,const pointf2& b)
{
return pointf2x(a.x+b.x,a.y+b.y);
}
pointf2 vsub2vv(const pointf2& a,const pointf2& b)
{
return pointf2x(a.x-b.x,a.y-b.y);
}
float scross2vv(const pointf2& a,const pointf2& b)
{
return a.x*b.y - a.y*b.x;
}
float dist2(const pointf2& a,const pointf2& b)
{
float dx = a.x - b.x;
float dy = a.y - b.y;
return dx*dx + dy*dy;
}
float dist(const pointf2& a,const pointf2& b)
{
return sqrtf(dist2(a,b));
}
// intersection of 2 lines
bool getintersection2d(const pointf2& la,const pointf2& lb,const pointf2& lc,const pointf2& ld,pointf2* i0)
{
float e = lb.x - la.x;
float f = lc.x - ld.x;
float g = lc.x - la.x;
float h = lb.y - la.y;
float j = lc.y - ld.y;
float k = lc.y - la.y;
float det = e*j - f*h;
if (det == 0)
return false;
det = 1/det;
float t0 = (g*j - f*k)*det;
float t1 = -(g*h - e*k)*det;
if (t0>=0 && t0<=1 && t1>=0 && t1<=1) {
if (i0) {
i0->x = la.x + (lb.x - la.x)*t0;
i0->y = la.y + (lb.y - la.y)*t0;
}
return true;
}
return false;
}
bool normalize2d(pointf2& v)
{
float d2 = v.x*v.x + v.y*v.y;
if (d2 == 0) {
v.x = 1; // point in some direction if a zero vector
v.y = 0;
return false;
}
float id = 1.0f/sqrtf(d2);
v.x *= id;
v.y *= id;
return true;
}
#define NRECTPOINTS 4
struct box {
pointf2 pos;
float rot;
pointf2 size; // w,h;
pointf2 p[NRECTPOINTS];
pointf2 pr[NRECTPOINTS];
};
struct circle {
pointf2 pos;
float rad;
};
/*#define MAXPOINTS 16
struct poly {
S32 npoints;
pointf2 p[MAXPOINTS];
};
*/
#ifdef BOX2BOX
struct box box0 = {{3.5f,3},PI/8,{5,3}};
struct box box1 = {{7,3},0,{3,5}};
//struct box box0 = {{5.7f,2.3f},PI/8,{5,3}};
//struct box box1 = {{7,3},0,{3,5}};
#endif
#ifdef CIRCLE2BOX
struct circle cir0 = {{5.5f,1.5f},1};
struct box box0 = {{3.5f,3},PI/8,{5,3}};
#endif
#ifdef CIRCLE2CIRCLE
struct circle cir0 = {{4,1.5f},1};
struct circle cir1 = {{5.5f,1.5f},1};
#endif
#ifdef BOXPOINT
struct pointf2 point0 = {1,-1};
struct pointf2 la = {3,4};
struct pointf2 lb = {5,7};
#endif
pointf2 rotpoint(const pointf2& p,float rot)
{
pointf2 rp;
float cr = cosf(rot);
float sr = sinf(rot);
rp.x = cr*p.x - sr*p.y;
rp.y = sr*p.x + cr*p.y;
return rp;
}
void calcpr(box& b)
{
b.p[0].x = -.5f*b.size.x;
b.p[0].y = .5f*b.size.y;
b.p[1].x = .5f*b.size.x;
b.p[1].y = .5f*b.size.y;
b.p[2].x = .5f*b.size.x;
b.p[2].y = -.5f*b.size.y;
b.p[3].x = -.5f*b.size.x;
b.p[3].y = -.5f*b.size.y;
S32 i;
for (i=0;i<NRECTPOINTS;++i) {
b.pr[i] = rotpoint(b.p[i],b.rot);
b.pr[i] = vadd2vv(b.pr[i],b.pos);
}
}
pointf2 is[3]; // handle overflow on intersection
pointf2 la0;
pointf2 la1;
pointf2 lb0;
pointf2 lb1;
pointf2 abestcp;
pointf2 abestpendir;
S32 acollide;
S32 ninside;
pointf2 insides[2];
S32 nainside,nbinside;
S32 pcollide;
float penm;
#ifdef BOXPOINT
float ldist;
#endif
#ifdef OLDPLANK2PLANK
// returns distance
float util_point2line(const pointf2& p,const pointf2& la,const pointf2& lb,pointf2* nrmr)
{
pointf2 nrm = vsub2vv(la,lb);
nrm = pointf2x(nrm.y,-nrm.x);
normalize2d(nrm);
float d = sdot2vv(nrm,la) - sdot2vv(nrm,p);
if (nrmr)
*nrmr = nrm;
return fabsf(d);
// return d;
}
#endif
bool util_point2plank(const pointf2& p,const box& b)
{
S32 i;
pointf2 vs[NRECTPOINTS];
S32 sgn = 0;
for (i=0;i<NRECTPOINTS;++i) {
vs[i] = vsub2vv(b.pr[i],p);
}
for (i=0;i<NRECTPOINTS;++i) {
float c = scross2vv(vs[i],vs[(i + 1)%NRECTPOINTS]);
if (sgn == 0) {
if (c >= 0) {
sgn = 1;
} else {
sgn = -1;
}
} else {
if (sgn == 1 && c < 0)
return false;
if (sgn == -1 && c >= 0)
return false;
}
}
return true;
}
#if 0
#if 1
// only handle 1 point inside box and 2 intersections case
bool util_plank2plank(const box& a,const box& b,pointf2& bestcp,pointf2& bestpendir,float& penm)
{
// find intersections
pointi2 isidx[2];
S32 i,j;
S32 k = 0;
for (i=0;i<NRECTPOINTS;++i) {
la0 = a.pr[i];
la1 = a.pr[(i + 1)%NRECTPOINTS];
for (j=0;j<NRECTPOINTS;++j) {
lb0 = b.pr[j];
lb1 = b.pr[(j + 1)%NRECTPOINTS];
if (getintersection2d(la0,la1,lb0,lb1,0)) {
if (k >= 2) {
return false;
}
isidx[k].x = i;
isidx[k].y = j;
++k;
}
}
}
if (k != 2)
return false;
// find out which verts are inside other box
S32 aidx,bidx;
ninside = nainside = nbinside = 0;
for (i=0;i<NRECTPOINTS;++i) {
if (util_point2plank(a.pr[i],b)) {
if (ninside >= 1)
return false;
insides[ninside++] = a.pr[i];
aidx = i;
++nainside;
}
}
for (i=0;i<NRECTPOINTS;++i) {
if (util_point2plank(b.pr[i],a)) {
if (ninside >= 1)
return false;
insides[ninside++] = b.pr[i];
bidx = i;
++nbinside;
}
}
if (ninside != 1)
return false;
// 1 vert inside box, find out closest line to it
const pointf2* lns;
const pointf2& pt = insides[0]; // the point inside a box
if (nainside)
lns = b.pr; // a point from 'a' inside 'b'
else
lns = a.pr; // a point from 'b' inside 'a'
// do some checks
if (nainside) {
if (isidx[0].y != isidx[1].y) // is intersection on same line?
return false;
i = isidx[0].y; // this is the line
// check the point for usage in intersections
S32 di = isidx[0].x - isidx[1].x;
S32 pi;
if (di < 0)
di += NRECTPOINTS;
if (di == 1) {
pi = isidx[0].x;
} else if (di == 3) {
pi = isidx[1].x;
} else
return false; // not right line
if (pi != aidx)
return false; // not right point
} else { // nbinside
if (isidx[0].x != isidx[1].x) // is intersection on same line?
return false;
i = isidx[0].x; // this is the line
// check the point for usage in intersections
S32 di = isidx[0].y - isidx[1].y;
S32 pi;
if (di < 0)
di += NRECTPOINTS;
if (di == 1) {
pi = isidx[0].y;
} else if (di == 3) {
pi = isidx[1].y;
} else
return false; // not right line
if (pi != bidx)
return false; // not right point
}
j = (i + 1)%NRECTPOINTS;
penm = util_point2line(pt,lns[i],lns[j],&bestpendir);
bestcp = pt;
if (nbinside) {
bestcp.x = penm*bestpendir.x + bestcp.x;
bestcp.y = penm*bestpendir.y + bestcp.y;
bestpendir.x = -bestpendir.x;
bestpendir.y = -bestpendir.y;
}
return true;
}
#else
bool util_plank2plank(const box& a,const box& b,pointf2& bestcp,pointf2& bestpendir,float& penm)
{
S32 i,j;
S32 k = 0;
for (i=0;i<NRECTPOINTS;++i) {
la0 = a.pr[i];
la1 = a.pr[(i + 1)%NRECTPOINTS];
for (j=0;j<NRECTPOINTS;++j) {
lb0 = b.pr[j];
lb1 = b.pr[(j + 1)%NRECTPOINTS];
if (getintersection2d(la0,la1,lb0,lb1,&is[k])) {
++k;
if (k > 2) {
return false;
}
}
}
}
if (k != 2)
return false;
bestcp.x = (is[0].x + is[1].x)/2;
bestcp.y = (is[0].y + is[1].y)/2;
bestpendir.x = is[1].y - is[0].y;
bestpendir.y = is[0].x - is[1].x;
if (!normalize2d(bestpendir))
return false;
// reuse la0
/* la0.x = bestcp.x - a.pos.x;
la0.y = bestcp.y - a.pos.y;
if (sdot2vv(la0,bestpendir) > 0) {
bestpendir.x = -bestpendir.x;
bestpendir.y = -bestpendir.y;
} */
// find verts inside plank (1 or 2)
ninside = nainside = nbinside = 0;
for (i=0;i<NRECTPOINTS;++i) {
if (util_point2plank(a.pr[i],b)) {
if (ninside >= 2)
return false;
insides[ninside++] = a.pr[i];
++nainside;
}
}
for (i=0;i<NRECTPOINTS;++i) {
if (util_point2plank(b.pr[i],a)) {
if (ninside >= 2)
return false;
insides[ninside++] = b.pr[i];
++nbinside;
}
}
if (!ninside)
return false;
if (ninside == 1) {
float d = util_point2line(insides[0],is[0],is[1]);
penm = d;
//bestcp = insides[0];
/* if (nbinside) {
bestpendir.x = -bestpendir.x;
bestpendir.y = -bestpendir.y;
} */
// bestcp.x = insides[0].x + penm*bestpendir.x;
// bestcp.y = insides[0].y + penm*bestpendir.y;
bestcp.x = insides[0].x;
bestcp.y = insides[0].y;
if (nbinside) {
bestcp.x = insides[0].x + penm*bestpendir.x;
bestcp.y = insides[0].y + penm*bestpendir.y;
bestpendir.x = -bestpendir.x;
bestpendir.y = -bestpendir.y;
}
return true;
} else {
return false;
}
}
#endif
#endif
void drawbox(const box& b)
{
S32 i;
for (i=0;i<NRECTPOINTS;++i) {
drawfline(b.pr[i],b.pr[(i+1)%NRECTPOINTS],C32BLACK);
pointi2 pi = math2screen(b.pr[i]);
outtextxybf32(B32,pi.x-8,pi.y+10,C32BLACK,C32LIGHTCYAN,"%d",i);
}
}
void drawcircle(const circle& c)
{
drawfcircle(c.pos,C32BLACK,math2screen(c.rad));
}
#ifndef OLDPLANK2PLANK
// Minkowski difference
void drawboxsm(const box& a,const box& b)
{
S32 i,j;
for (j=0;j<NRECTPOINTS;++j) {
for (i=0;i<NRECTPOINTS;++i) {
pointf2x sa(a.pr[j].x-b.pr[i].x,a.pr[j].y-b.pr[i].y);
pointf2x sb(a.pr[j].x-b.pr[(i+1)%NRECTPOINTS].x,a.pr[j].y-b.pr[(i+1)%NRECTPOINTS].y);
drawfline(sa,sb,C32BLACK);
pointi2 pi = math2screen(sa);
outtextxybf32(B32,pi.x-8,pi.y+10,C32BLACK,C32YELLOW,"%d,%d",j,i);
}
}
for (j=0;j<NRECTPOINTS;++j) {
for (i=0;i<NRECTPOINTS;++i) {
pointf2x sa(a.pr[j].x-b.pr[i].x,a.pr[j].y-b.pr[i].y);
pointf2x sb(a.pr[(j+1)%NRECTPOINTS].x-b.pr[i].x,a.pr[(j+1)%NRECTPOINTS].y-b.pr[i].y);
drawfline(sa,sb,C32BLACK);
}
}
}
// assume not same point, return 0 to almost 4
float cheapatan2delta(const pointf2& from,const pointf2& to)
{
float dx = to.x - from.x;
float dy = to.y - from.y;
float ax = abs(dx);
float ay = abs(dy);
float ang = dy/(ax+ay);
if (dx<0)
ang = 2 - ang;
else if (dy<0)
ang = 4 + ang;
return ang;
}
float penline(const pointf2& p,const pointf2& la,const pointf2& lb)
{
pointf2x n(lb.y - la.y,la.x - lb.x);
normalize2d(n);
float da = sdot2vv(la,n);
float d = sdot2vv(p,n);
return d - da;
}
bool box2boxscan(const box& a,const box& b,pointf2& cp,pointf2& abestpendir,float& penm)
// TODO do AABB early out
//void box2boxscan(const box& a, const box& b)
{
pointi2 move[4] = {{0,1},{0,-1},{1,0},{-1,0}};
pointf2 arr[NRECTPOINTS][NRECTPOINTS];
S32 i,j;
// build 2d array of differences
pointf2 wp;
for (j=0;j<NRECTPOINTS;++j) {
for (i=0;i<NRECTPOINTS;++i) {
pointf2x diff(a.pr[i].x-b.pr[j].x,a.pr[i].y-b.pr[j].y);
arr[j][i] = diff;
}
}
S32 wi,wj; // walk
wi = wj = 0;
wp = arr[0][0];
// find lowest y value, then lowest x value (incase of 2 or more lowest y values)
for (j=0;j<NRECTPOINTS;++j) {
for (i=0;i<NRECTPOINTS;++i) {
const pointf2& cp2 = arr[j][i];
if (cp2.y < wp.y || (cp2.y == wp.y && cp2.x < wp.x)) { // there should be no points at the same place
wi = i;
wj = j;
wp = cp2;
}
}
}
pointi2x wloc(wi,wj);
S32 widx = 0;
pointi2 warr[NRECTPOINTS+NRECTPOINTS];
bool hilits[NRECTPOINTS+NRECTPOINTS]; // used just for drawing
::fill(hilits,hilits+NRECTPOINTS+NRECTPOINTS,false);
warr[widx++] = wloc;
float wang = 0;
// walk thru the points, doing gift wrapping
while(widx < 8) {
// try the 4 'nearest' points (by connection, not distance)
S32 k,bestk=0;
S32 nwi,nwj;
float bestang = 5; // bigger than any angle 0-4
for (k=0;k<4;++k) { // use the one with the lowest angle
nwi = (wi + move[k].x + NRECTPOINTS)%NRECTPOINTS;
nwj = (wj + move[k].y + NRECTPOINTS)%NRECTPOINTS;
const pointf2& pdest = arr[nwj][nwi];
float ang = cheapatan2delta(wp,pdest);
if (ang <= bestang && ang >= wang) {
bestk = k;
bestang = ang;
}
}
nwi = (wi + move[bestk].x + NRECTPOINTS)%NRECTPOINTS;
nwj = (wj + move[bestk].y + NRECTPOINTS)%NRECTPOINTS;
warr[widx++] = pointi2x(nwi,nwj);
wi = nwi;
wj = nwj;
wp = arr[wj][wi];
wang = bestang;
}
float bestpen = 1e20f;
int bestidx = 0;
bool coll = false;
pointf2 bestnrm;
// got 8 points, find if inside and if so find closest line with 2 points
for (i=0;i<NRECTPOINTS+NRECTPOINTS;++i) {
j = (i+1)%(NRECTPOINTS+NRECTPOINTS);
pointf2 p0 = arr[warr[i].y][warr[i].x];
pointf2 p1 = arr[warr[j].y][warr[j].x];
pointf2 pd = vsub2vv(p1,p0);
pointf2x nrm(pd.y,-pd.x);
normalize2d(nrm);
float d = sdot2vv(nrm,p0);
if (d <= 0) { // no collision
coll = false;
break;
}
float d1 = sdot2vv(p0,pd);
float d2 = sdot2vv(p1,pd);
if (d < bestpen && ((d1 >= 0 && d2<= 0) || (d1 <= 0 && d2 >= 0))) {
// left of line segment and a line from point intersects line segment at 90 degrees
bestpen = d;
bestidx = i;
bestnrm = nrm;
coll = true;
}
}
if (coll) {
i = bestidx;
j = (i+1)%(NRECTPOINTS+NRECTPOINTS);
hilits[i] = true;
hilits[j] = true;
pointf2 collpoint = vmul2sv(bestpen,bestnrm);
drawfpoint(collpoint,C32LIGHTMAGENTA);
bestnrm.x = -bestnrm.x;
bestnrm.y = -bestnrm.y;
abestpendir = bestnrm;
penm = bestpen;
#ifdef NEWCP // better for deeper penetrations
// pick a more central collision point
pointf2x paccum(0,0);
S32 pcnt = 0;
// use all points inside and intersections
for (i=0;i<NRECTPOINTS;++i) {
if (util_point2plank(b.pr[i],a)) {
paccum.x += b.pr[i].x;
paccum.y += b.pr[i].y;
++pcnt;
}
}
for (i=0;i<NRECTPOINTS;++i) {
if (util_point2plank(a.pr[i],b)) {
paccum.x += a.pr[i].x;
paccum.y += a.pr[i].y;
++pcnt;
}
}
for (i=0;i<NRECTPOINTS;++i) {
const pointf2& la0 = a.pr[i];
const pointf2& la1 = a.pr[(i + 1)%NRECTPOINTS];
for (j=0;j<NRECTPOINTS;++j) {
const pointf2& lb0 = b.pr[j];
const pointf2& lb1 = b.pr[(j + 1)%NRECTPOINTS];
pointf2 is;
if (getintersection2d(la0,la1,lb0,lb1,&is)) {
paccum.x += is.x;
paccum.y += is.y;
++pcnt;
}
}
}
if (!pcnt)
error("pcnt == 0");
cp.x = paccum.x / pcnt;
cp.y = paccum.y / pcnt;
#else
if (warr[i].x == warr[j].x) { // same point in a
cp = a.pr[warr[i].x];
} else if (warr[i].y == warr[j].y) { // same point in b
cp = b.pr[warr[i].y];
cp.x -= penm * bestnrm.x;
cp.y -= penm * bestnrm.y;
} else { // what ??
//cp = pointf2x(3,3);
error("can't find penpoint");
}
#endif
}
// show point walk and hilits closest line if inside
for (i=0;i<NRECTPOINTS+NRECTPOINTS;++i) {
pointi2 pi=math2screen(arr[warr[i].y][warr[i].x]);
bool hilit = hilits[i];
C32 col = hilit ? C32LIGHTGREEN : C32YELLOW;
outtextxybf32(B32,pi.x-8,pi.y+18,C32BLACK,col,"Wi %d",i);
}
return coll;
}
#endif
bool circle2boxscan(const circle& b,const box& a,pointf2& cp,pointf2& abestpendir,float& penm)
{
// TODO do AABB early out
cp = pointf2x(1,1);
// abestpendir = pointf2x(1,0);
penm = 2;
int bestidx = 0;
bool coll = false;
pointf2 bestnrm;
float bestpen = 1e20f;
int i,j;
// for (i=0;i<1;++i) {
for (i=0;i<NRECTPOINTS;++i) {
j = (i+1)%(NRECTPOINTS);
pointf2 p0 = a.pr[i];
pointf2 p1 = a.pr[j];
pointf2 pd = vsub2vv(p1,p0);
pointf2x nrm(pd.y,-pd.x);
normalize2d(nrm);
float d = sdot2vv(nrm,p0); // line in d,nrm format
float pen = sdot2vv(nrm,b.pos) - d + b.rad;
if (pen <= 0) {
coll = false;
break; // no collision
}
float d1 = sdot2vv(p0,pd);
float d2 = sdot2vv(p1,pd);
float dp = sdot2vv(b.pos,pd);
// if (pen < bestpen) {
if (pen < bestpen && ((d1 >= dp && d2<= dp) || (d1 <= dp && d2 >= dp))) {
// left of line segment and a line from point intersects line segment at 90 degrees
bestpen = pen;
bestidx = i;
bestnrm = nrm;
coll = true;
}
}
if (!coll && i == NRECTPOINTS) { // check corners
float bestdist2 = 1e20f;
pointf2 bestpnt;
for (i=0;i<NRECTPOINTS;++i) {
pointf2 del = vsub2vv(a.pr[i],b.pos);
float dist2 = del.x*del.x + del.y*del.y;
if (dist2 >= b.rad*b.rad)
continue;
if (dist2 < bestdist2) {
bestdist2 = dist2;
bestpnt = a.pr[i];
bestidx = i;
coll = true;
}
}
if (coll) {
bestnrm = vsub2vv(a.pr[bestidx],b.pos);
normalize2d(bestnrm); // this might be wrong, could be 0
bestpen = b.rad - sqrtf(bestdist2);
}
}
if (coll) {
penm = bestpen;
cp = vmul2sv(b.rad,bestnrm);
cp = vadd2vv(cp,b.pos);
bestnrm.x = -bestnrm.x;
bestnrm.y = -bestnrm.y;
abestpendir = bestnrm;
}
return coll;
}
bool circle2circlescan(const circle& a,const circle& b,pointf2& cp,pointf2& nrm,float& penm)
{
pointf2 del = vsub2vv(a.pos,b.pos);
float dist2 = del.x*del.x + del.y*del.y;
float rsum = a.rad + b.rad;
if (dist2 >= rsum*rsum)
return false;
nrm = del;
normalize2d(nrm);
cp = vmul2sv(-a.rad,nrm);
cp = vadd2vv(cp,a.pos);
penm = rsum - sqrtf(dist2);
return true;
}
#endif
void drawcollutils()
#ifdef BOX2BOX
{
drawbox(box0);
drawbox(box1);
#ifdef OLDPLANK2PLANK
acollide = util_plank2plank(box0,box1,abestcp,abestpendir,penm);
#else
drawboxsm(box0,box1);
//box2boxscan(box0,box1);
acollide = box2boxscan(box0,box1,abestcp,abestpendir,penm);
#endif
if (acollide) {
drawfpoint(abestcp,C32RED);
pointf2x penp(abestcp.x + penm*abestpendir.x,abestcp.y + penm*abestpendir.y);
drawfline(abestcp,penp,C32GREEN);
drawfpoint(penp,C32LIGHTRED);
/* if (ninside > 0) {
//pointf2 op = vmul2sv(penm,abestpendir);
//op = vadd2vv(op,insides[0]);
//drawfpoint(op,C32LIGHTRED);
drawfpoint(insides[0],C32LIGHTBLUE);
}
if (ninside > 1) {
drawfpoint(insides[1],C32LIGHTBLUE);
} */
}
#ifdef BOXPOINT
C32 col;
if (pcollide) {
col = C32RED;
} else {
col = C32GREEN;
}
drawfpoint(point0,col);
drawflinec(la,lb,C32BROWN);
#endif
#endif
#ifdef CIRCLE2BOX
drawbox(box0);
drawcircle(cir0);
acollide = circle2boxscan(cir0,box0,abestcp,abestpendir,penm);
if (acollide) {
drawfpoint(abestcp,C32RED);
pointf2x penp(abestcp.x + penm*abestpendir.x,abestcp.y + penm*abestpendir.y);
drawfline(abestcp,penp,C32GREEN);
drawfpoint(penp,C32LIGHTRED);
}
#endif
#ifdef CIRCLE2CIRCLE
drawcircle(cir0);
drawcircle(cir1);
acollide = circle2circlescan(cir0,cir1,abestcp,abestpendir,penm);
if (acollide) {
drawfpoint(abestcp,C32RED);
pointf2x penp(abestcp.x + penm*abestpendir.x,abestcp.y + penm*abestpendir.y);
drawfline(abestcp,penp,C32GREEN);
drawfpoint(penp,C32LIGHTRED);
}
#endif
#endif
| [
"mkoeni@sbcglobal.net"
] | mkoeni@sbcglobal.net |
d8536d793e054f21c98814d88a7e20e4b5b37e89 | aca6e30c88a30f84724c042da02cd77b95c7ba26 | /UltraFastMathematics.cpp | 69b7e1aa953ec8ffdff9c38be0920f55297b8232 | [] | no_license | AmreshSharma01/Competitive-Programming | ba67c6b03f11b91d84f6d564b8d0e1caf9240aa1 | e3a0b4523aa4e43a8b28f760f1f0f83e8b37ef26 | refs/heads/master | 2023-07-08T05:49:28.375753 | 2021-08-02T16:13:02 | 2021-08-02T16:13:02 | 274,864,344 | 1 | 0 | null | 2020-08-14T03:33:34 | 2020-06-25T08:20:54 | C++ | UTF-8 | C++ | false | false | 800 | cpp | #include<bits/stdc++.h>
using namespace std;
int main(){
int T;
cin>>T;
while(T--){
string s1,s2;
cin>>s1>>s2;
char final_key[s1.size()];
for(int i = 0; i<s1.size(); i++)
{
final_key[i] = (s1[i] ^ s2[i])+'0';
cout<<final_key[i];
}
cout<<endl;
}
return 0;
}
/*
#include <iostream>
#include <string>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--){
string s1, s2;
cin >> s1 >> s2;
for (int i = 0; i < s1.length(); ++i)
{
if (s1[i] == s2[i])
{
s1[i] = '0';
}
else
{
s1[i] = '1';
}
}
cout << s1 << endl;
}
return 0;
}
*/ | [
"noreply@github.com"
] | noreply@github.com |
e21593a287b706808316402140fdba2b7c9ba31a | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/git/new_hunk_3043.cpp | b4210086f053e056e22e1b6017b211bb44157a4d | [] | 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 | 969 | cpp |
/*
* Write sha1 into the open lockfile, then close the lockfile. On
* errors, rollback the lockfile, fill in *err and
* return -1.
*/
static int write_ref_to_lockfile(struct ref_lock *lock,
const unsigned char *sha1, struct strbuf *err)
{
static char term = '\n';
struct object *o;
o = parse_object(sha1);
if (!o) {
strbuf_addf(err,
"Trying to write ref %s with nonexistent object %s",
lock->ref_name, sha1_to_hex(sha1));
unlock_ref(lock);
return -1;
}
if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
strbuf_addf(err,
"Trying to write non-commit object %s to branch %s",
sha1_to_hex(sha1), lock->ref_name);
unlock_ref(lock);
return -1;
}
if (write_in_full(lock->lk->fd, sha1_to_hex(sha1), 40) != 40 ||
write_in_full(lock->lk->fd, &term, 1) != 1 ||
close_ref(lock) < 0) {
strbuf_addf(err,
"Couldn't write %s", lock->lk->filename.buf);
unlock_ref(lock);
return -1;
}
return 0;
| [
"993273596@qq.com"
] | 993273596@qq.com |
49ed265b572af8c6990854e2f3c3637880af8461 | 98756cbdb5798ae019a8bd8b6db5a395097dbf9b | /Source/FirstCPPUnrealGame/DamageableActor.h | 678cb446d103b4898403e55e5ee36d015e7eda03 | [] | no_license | ABitulescu/FirstCPPUnrealGame | eafabc63b33b6ea445633822327d6cda7bdbe3ab | 35b27bfa3b3fce02cc99ae254fe64e997f71dd1f | refs/heads/master | 2022-09-15T03:28:33.671526 | 2020-05-28T10:02:44 | 2020-05-28T10:02:44 | 267,556,388 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 729 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "DamageableActor.generated.h"
UCLASS()
class FIRSTCPPUNREALGAME_API ADamageableActor : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
ADamageableActor();
UFUNCTION(BlueprintImplementableEvent, Category = "Attack")
void onTakeAttack();
UPROPERTY(EditAnywhere, Category = "Attack")
bool isAttackable{ true };
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
void takeAttack();
};
| [
"40036459+ABitulescu@users.noreply.github.com"
] | 40036459+ABitulescu@users.noreply.github.com |
09e61f4a95bac743ba1077da6a1309d3372867d4 | 14ed0e02ccc01ccbb7e1044f635259f39686da5b | /aa2-11-rpt04/sketch07_map/sketch07_map.ino | d0d4572b0621e9a1399ee9acd112e52a10a6f68a | [] | no_license | leejs8041/aa2-11-new | 951a22fc8b0b72af280b2d9773e7ed6d055f1e77 | f01227a78852b1da046be5ebf125881a6122bc5d | refs/heads/master | 2023-01-20T01:06:56.755940 | 2020-12-02T07:40:01 | 2020-12-02T07:40:01 | 294,039,073 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 407 | ino | void setup()
{
Serial.begin(9600);
}
void loop()
{
int sensorValue = analogRead(A0);
float voltage = f_map(sensorValue, 0,1023,0.0,5.0);
Serial.print("AA14AA11,Present value(0~5.0):");
Serial.println(voltage);
delay(500);
}
float f_map(long x, long in_min, long in_max, float out_min, float out_max)
{
return (x- in_min)*(out_max - out_min)/(in_max- in_min)+out_min;
}
| [
"noreply@github.com"
] | noreply@github.com |
983f8c3d6ac6676d4ed7d4b30e17cf62a55ac56d | 3f4e21cc5b22512b199c2e183b7329986296f885 | /15331220_刘沅昊_HW7_v0/src/model.h | 8cb78d91428ffa7a5ad6c400e6d17eed0b0825df | [] | no_license | HisBeard/CG_2019 | 13fb4b39738bd7c60b6fa197dfaf38a885b951b1 | de3e239a5c1292e0d9e5f787f671017537034351 | refs/heads/master | 2020-05-19T17:06:30.908820 | 2019-05-29T07:04:47 | 2019-05-29T07:04:47 | 185,126,875 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,748 | h | #ifndef MODEL_H
#define MODEL_H
#include <glad/glad.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include "stb_image.h"
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include "mesh.h"
#include "shader.h"
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <map>
#include <vector>
using namespace std;
unsigned int TextureFromFile(const char *path, const string &directory, bool gamma = false);
class Model
{
public:
/* Model Data */
vector<Texture> textures_loaded; // stores all the textures loaded so far, optimization to make sure textures aren't loaded more than once.
vector<Mesh> meshes;
string directory;
bool gammaCorrection;
/* Functions */
// constructor, expects a filepath to a 3D model.
Model(string const &path, bool gamma = false) : gammaCorrection(gamma)
{
loadModel(path);
}
// draws the model, and thus all its meshes
void Draw(Shader shader)
{
for (unsigned int i = 0; i < meshes.size(); i++)
meshes[i].Draw(shader);
}
private:
/* Functions */
// loads a model with supported ASSIMP extensions from file and stores the resulting meshes in the meshes vector.
void loadModel(string const &path)
{
// read file via ASSIMP
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_CalcTangentSpace);
// check for errors
if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) // if is Not Zero
{
cout << "ERROR::ASSIMP:: " << importer.GetErrorString() << endl;
return;
}
// retrieve the directory path of the filepath
directory = path.substr(0, path.find_last_of('/'));
// process ASSIMP's root node recursively
processNode(scene->mRootNode, scene);
}
// processes a node in a recursive fashion. Processes each individual mesh located at the node and repeats this process on its children nodes (if any).
void processNode(aiNode *node, const aiScene *scene)
{
// process each mesh located at the current node
for (unsigned int i = 0; i < node->mNumMeshes; i++)
{
// the node object only contains indices to index the actual objects in the scene.
// the scene contains all the data, node is just to keep stuff organized (like relations between nodes).
aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
meshes.push_back(processMesh(mesh, scene));
}
// after we've processed all of the meshes (if any) we then recursively process each of the children nodes
for (unsigned int i = 0; i < node->mNumChildren; i++)
{
processNode(node->mChildren[i], scene);
}
}
Mesh processMesh(aiMesh *mesh, const aiScene *scene)
{
// data to fill
vector<Vertex> vertices;
vector<unsigned int> indices;
vector<Texture> textures;
// Walk through each of the mesh's vertices
for (unsigned int i = 0; i < mesh->mNumVertices; i++)
{
Vertex vertex;
glm::vec3 vector; // we declare a placeholder vector since assimp uses its own vector class that doesn't directly convert to glm's vec3 class so we transfer the data to this placeholder glm::vec3 first.
// positions
vector.x = mesh->mVertices[i].x;
vector.y = mesh->mVertices[i].y;
vector.z = mesh->mVertices[i].z;
vertex.Position = vector;
// normals
vector.x = mesh->mNormals[i].x;
vector.y = mesh->mNormals[i].y;
vector.z = mesh->mNormals[i].z;
vertex.Normal = vector;
// texture coordinates
if (mesh->mTextureCoords[0]) // does the mesh contain texture coordinates?
{
glm::vec2 vec;
// a vertex can contain up to 8 different texture coordinates. We thus make the assumption that we won't
// use models where a vertex can have multiple texture coordinates so we always take the first set (0).
vec.x = mesh->mTextureCoords[0][i].x;
vec.y = mesh->mTextureCoords[0][i].y;
vertex.TexCoords = vec;
}
else
vertex.TexCoords = glm::vec2(0.0f, 0.0f);
// tangent
vector.x = mesh->mTangents[i].x;
vector.y = mesh->mTangents[i].y;
vector.z = mesh->mTangents[i].z;
vertex.Tangent = vector;
// bitangent
vector.x = mesh->mBitangents[i].x;
vector.y = mesh->mBitangents[i].y;
vector.z = mesh->mBitangents[i].z;
vertex.Bitangent = vector;
vertices.push_back(vertex);
}
// now wak through each of the mesh's faces (a face is a mesh its triangle) and retrieve the corresponding vertex indices.
for (unsigned int i = 0; i < mesh->mNumFaces; i++)
{
aiFace face = mesh->mFaces[i];
// retrieve all indices of the face and store them in the indices vector
for (unsigned int j = 0; j < face.mNumIndices; j++)
indices.push_back(face.mIndices[j]);
}
// process materials
aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];
// we assume a convention for sampler names in the shaders. Each diffuse texture should be named
// as 'texture_diffuseN' where N is a sequential number ranging from 1 to MAX_SAMPLER_NUMBER.
// Same applies to other texture as the following list summarizes:
// diffuse: texture_diffuseN
// specular: texture_specularN
// normal: texture_normalN
// 1. diffuse maps
vector<Texture> diffuseMaps = loadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse");
textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());
// 2. specular maps
vector<Texture> specularMaps = loadMaterialTextures(material, aiTextureType_SPECULAR, "texture_specular");
textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());
// 3. normal maps
std::vector<Texture> normalMaps = loadMaterialTextures(material, aiTextureType_HEIGHT, "texture_normal");
textures.insert(textures.end(), normalMaps.begin(), normalMaps.end());
// 4. height maps
std::vector<Texture> heightMaps = loadMaterialTextures(material, aiTextureType_AMBIENT, "texture_height");
textures.insert(textures.end(), heightMaps.begin(), heightMaps.end());
// return a mesh object created from the extracted mesh data
return Mesh(vertices, indices, textures);
}
// checks all material textures of a given type and loads the textures if they're not loaded yet.
// the required info is returned as a Texture struct.
vector<Texture> loadMaterialTextures(aiMaterial *mat, aiTextureType type, string typeName)
{
vector<Texture> textures;
for (unsigned int i = 0; i < mat->GetTextureCount(type); i++)
{
aiString str;
mat->GetTexture(type, i, &str);
// check if texture was loaded before and if so, continue to next iteration: skip loading a new texture
bool skip = false;
for (unsigned int j = 0; j < textures_loaded.size(); j++)
{
if (std::strcmp(textures_loaded[j].path.data(), str.C_Str()) == 0)
{
textures.push_back(textures_loaded[j]);
skip = true; // a texture with the same filepath has already been loaded, continue to next one. (optimization)
break;
}
}
if (!skip)
{ // if texture hasn't been loaded already, load it
Texture texture;
texture.id = TextureFromFile(str.C_Str(), this->directory);
texture.type = typeName;
texture.path = str.C_Str();
textures.push_back(texture);
textures_loaded.push_back(texture); // store it as texture loaded for entire model, to ensure we won't unnecesery load duplicate textures.
}
}
return textures;
}
};
unsigned int TextureFromFile(const char *path, const string &directory, bool gamma)
{
string filename = string(path);
filename = directory + '/' + filename;
unsigned int textureID;
glGenTextures(1, &textureID);
int width, height, nrComponents;
unsigned char *data = stbi_load(filename.c_str(), &width, &height, &nrComponents, 0);
if (data)
{
GLenum format;
if (nrComponents == 1)
format = GL_RED;
else if (nrComponents == 3)
format = GL_RGB;
else if (nrComponents == 4)
format = GL_RGBA;
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
stbi_image_free(data);
}
else
{
std::cout << "Texture failed to load at path: " << path << std::endl;
stbi_image_free(data);
}
return textureID;
}
#endif | [
"noreply@github.com"
] | noreply@github.com |
8960ba9400b9f4b41e45ffaa1eede67308ea5981 | dccd1058e723b6617148824dc0243dbec4c9bd48 | /aoj/vol26/2609.cpp | 5ab3e57a972cee3d2af33e3d5c4f9d3df73bc17d | [] | no_license | imulan/procon | 488e49de3bcbab36c624290cf9e370abfc8735bf | 2a86f47614fe0c34e403ffb35108705522785092 | refs/heads/master | 2021-05-22T09:24:19.691191 | 2021-01-02T14:27:13 | 2021-01-02T14:27:13 | 46,834,567 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,308 | cpp | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i))
#define all(x) (x).begin(),(x).end()
#define pb push_back
#define fi first
#define se second
#define dbg(x) cout<<#x" = "<<((x))<<endl
template<class T,class U> ostream& operator<<(ostream& o, const pair<T,U> &p){o<<"("<<p.fi<<","<<p.se<<")";return o;}
template<class T> ostream& operator<<(ostream& o, const vector<T> &v){o<<"[";for(T t:v){o<<t<<",";}o<<"]";return o;}
const int N = 1000100;
int main(){
ll w,h,v,t,x,y,p,q;
cin >>w >>h >>v >>t >>x >>y >>p >>q;
ll r = v*t;
ll y1 = q, y2 = h+(h-q);
vector<ll> yy;
for(int i=-N/2; i<=N/2; ++i){
yy.pb(y1+h*i*2);
yy.pb(y2+h*i*2);
}
sort(all(yy));
ll ans = 0;
for(int i=-N; i<=N; ++i){
ll X = w*i;
if(i%2==0) X+=p;
else X+=w-p;
if(abs(X-x) > r) continue;
ll D = r*r - (X-x)*(X-x);
if(D<0) continue;
ll ly = y-(ll)sqrt(D);
ll ry = y+(ll)sqrt(D);
int lidx = lower_bound(all(yy), ly) - yy.begin();
int ridx = upper_bound(all(yy), ry) - yy.begin();
ans += ridx-lidx;
// printf(" %d: [%d] %d ~ [%d] %d\n",i,lidx,yy[lidx],ridx,yy[ridx]);
}
cout << ans << endl;
return 0;
}
| [
"k0223.teru@gmail.com"
] | k0223.teru@gmail.com |
c95b8d59a57008e1ee7bbe08c0229b50d0089d16 | 1621a7afe0fb50fa048f920aceb379febb55ed86 | /G4RicochetMC/RMCsources/CosmogenicSourceMessenger.hh | d5cb66c95073354aa6656e97c7784102ac4887f3 | [] | no_license | spitzj/RicochetMC | 15d4a94e1b7d265258362acbe06453d17c962eba | f3a124047808f5c674e94d6f190a119335e019c1 | refs/heads/master | 2021-01-21T11:46:28.559199 | 2012-02-13T18:57:20 | 2012-02-13T18:57:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,461 | hh | #ifndef CosmogenicSourceMessenger_hh
#define CosmogenicSourceMessenger_hh
////////////////////////////////////////////////////////////////////////
// //
// File: CosmogenicSourceMessenger.hh //
// Description: User interface for cosmic ray generators //
// //
// Author: Adam Anderson (MIT) //
// Adapted from: Dennis Wright (SLAC) //
// Date: 13 February 2012 //
// //
////////////////////////////////////////////////////////////////////////
#include "G4UImessenger.hh"
#include "globals.hh"
class CosmogenicSource;
class G4ParticleTable;
class G4UIdirectory;
class G4UIcmdWithADoubleAndUnit;
class G4UIcmdWithAnInteger;
class G4UIcmdWithoutParameter;
class CosmogenicSourceMessenger : public G4UImessenger {
public:
CosmogenicSourceMessenger(CosmogenicSource* fPtclGun);
~CosmogenicSourceMessenger();
//void SetNewValue(G4UIcommand *command, G4String newValues);
private:
CosmogenicSource* fParticleGun;
G4UIdirectory* gunDirectory;
G4UIcmdWithADoubleAndUnit* depthCmd;
G4UIcmdWithAnInteger* verbosityCmd;
G4UIcmdWithoutParameter* genTestCmd;
};
#endif
| [
"adama@mit.edu"
] | adama@mit.edu |
0cd6061636ab52ff006aaae89900267f5e720783 | 4a1b388fc7254e7f8fa2b72df9d61999bf7df341 | /Source/rclUE/Private/Srvs/ROS2SetMap.cpp | 4fb172a3725eff32f610d2abc3b525e9dbe0bb15 | [
"Apache-2.0"
] | permissive | rapyuta-robotics/rclUE | a2055cf772d7ca4d7c36e991ee9c8920e0475fd2 | 7613773cd4c1226957603d705d68a2d2b4a69166 | refs/heads/devel | 2023-08-19T04:06:31.306109 | 2023-07-24T15:23:29 | 2023-07-24T15:23:29 | 334,819,367 | 75 | 17 | Apache-2.0 | 2023-09-06T02:34:56 | 2021-02-01T03:29:17 | C++ | UTF-8 | C++ | false | false | 1,376 | cpp | // Copyright 2023 Rapyuta Robotics Co., Ltd.
// This code has been autogenerated from nav_msgs/srv/SetMap.srv - do not modify
#include "Srvs/ROS2SetMap.h"
const rosidl_service_type_support_t* UROS2SetMapSrv::GetTypeSupport() const
{
return ROSIDL_GET_SRV_TYPE_SUPPORT(nav_msgs, srv, SetMap);
}
void UROS2SetMapSrv::Init()
{
nav_msgs__srv__SetMap_Request__init(&SetMap_req);
nav_msgs__srv__SetMap_Response__init(&SetMap_res);
}
void UROS2SetMapSrv::Fini()
{
nav_msgs__srv__SetMap_Request__fini(&SetMap_req);
nav_msgs__srv__SetMap_Response__fini(&SetMap_res);
}
void UROS2SetMapSrv::SetRequest(const FROSSetMapReq& Request)
{
Request.SetROS2(SetMap_req);
}
void UROS2SetMapSrv::GetRequest(FROSSetMapReq& Request) const
{
Request.SetFromROS2(SetMap_req);
}
void UROS2SetMapSrv::SetResponse(const FROSSetMapRes& Response)
{
Response.SetROS2(SetMap_res);
}
void UROS2SetMapSrv::GetResponse(FROSSetMapRes& Response) const
{
Response.SetFromROS2(SetMap_res);
}
void* UROS2SetMapSrv::GetRequest()
{
return &SetMap_req;
}
void* UROS2SetMapSrv::GetResponse()
{
return &SetMap_res;
}
FString UROS2SetMapSrv::SrvRequestToString() const
{
/* TODO: Fill here */
checkNoEntry();
return FString();
}
FString UROS2SetMapSrv::SrvResponseToString() const
{
/* TODO: Fill here */
checkNoEntry();
return FString();
}
| [
"noreply@github.com"
] | noreply@github.com |
6d1c974379cf1fc1bb30f6308ebc07d8faf4eae7 | f3c95ff74e43f4ad0a9e152c1c741825529afd25 | /eaeae/script_build.cpp | 189e1fdc18405cc9e0a9243d7a0e797966dbc07d | [] | no_license | nakul-jindal/Modern-Cryptology | bd361821489851bb6e6467b70de4f23ef113e9c7 | 6c418ddc40f1c0501e947e802e3984870c0704e2 | refs/heads/main | 2023-06-10T07:47:02.913601 | 2021-07-03T21:41:07 | 2021-07-03T21:41:07 | 382,711,835 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,972 | cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
//auto-generate a script which will send 1 lakh inputs to the ssh server
std::ofstream script;
script.open("script_game.sh");
script << "#!/usr/bin/expect\n";
//log file stores output of the game screen
script << "log_file -a game_outputs.log\n";
script << "spawn ssh student@65.0.124.36\n";
//string sshpwd, gpname, gppwd, infile;
/*cout << "Enter your SSH Password : ";
cin >> sshpwd;
cout << "\nEnter your team name : ";
cin >> gpname;
cout << "\nEnter your team pwd : ";
cin >> gppwd;*/
script << "expect \"student@65.0.124.36's password:\"\n";
script << "send -- \"";
script << "caesar";
script << "\\r\"\n\n";
script << "expect \"group name:\"\n";
script << "send -- \"";
script << "Conundrum";
script << "\\r\"\n\n";
script << "expect \"word:\"\n";
script << "send -- \"";
script << "qwerty";
script << "\\r\"\n\n";
script << "expect \"at:\"\n";
script << "send -- \"5\\r\"\n\n";
script << "expect \"> \"\n";
script << "send -- \"go\\r\"\n\n";
script << "expect \"> \"\n";
script << "send -- \"wave\\r\"\n\n";
script << "expect \"> \"\n";
script << "send -- \"dive\\r\"\n\n";
script << "expect \"> \"\n";
script << "send -- \"go\\r\"\n\n";
script << "expect \"> \"\n";
script << "send -- \"read\\r\"\n\n";
for (int i=1;i<=8;i++){
std::ifstream input_random;
input_random.open("inputs" + to_string(i) + ".txt");
std::string line;
if (input_random.is_open())
{
while (std::getline(input_random, line))
{
script << "expect \"> \"\n";
script << "send -- \"";
script << line;
script << "\\r\"\n\n";
script << "expect \"> \"\n";
script << "send -- \"c\\r\"\n\n";
}
input_random.close();
}
}
script.close();
} | [
"nakul199529@gmail.com"
] | nakul199529@gmail.com |
e97b36a4ed20ac6051a49385079ce5555f255b1f | 4dee9e335470591de3e904ac92728c83862d389e | /backup/LifeTime_Muon_Polarized.cpp | a0297573bce059955a092fffa7c7caf44819e077 | [] | no_license | denglert/HelicityCalcFW | 8fd366e0e390913eadbba56b1e1d41fc3e54cf77 | d3af6a3e16b11c08cf9e7d1ef7d1988bf5c2cc91 | refs/heads/master | 2021-01-21T04:41:32.966073 | 2016-07-17T18:34:01 | 2016-07-17T18:34:01 | 44,928,151 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,736 | cpp | #include <iostream>
#include <cmath>
#include <TH3D.h>
#include <TVector3.h>
#include <TLorentzVector.h>
#include "HelicityFW.h"
#include "FortranInterface.h"
#include "PhysConst.h"
#include "UtilFunctions.h"
#include "PhaseSpaceTools.h"
#include "cuba.h"
//////////////////////////////
// -- Cuba configuration -- //
//////////////////////////////
#define USERDATA NULL
#define NCOMP 1
#define NVEC 1
#define EPSREL 1e-3
#define EPSABS 1e-12
#define VERBOSE 2
#define LAST 4
#define SEED 0
#define MINEVAL 0
#define MAXEVAL 100000
#define NSTART 1000
#define NINCREASE 500
#define NBATCH 1000
#define GRIDNO 0
#define STATEFILE NULL
#define SPIN NULL
#define NNEW 1000
#define NMIN 2
#define FLATNESS 25.
#define KEY1 47
#define KEY2 1
#define KEY3 1
#define MAXPASS 5
#define BORDER 0.
#define MAXCHISQ 10.
#define MINDEVIATION .25
#define NGIVEN 0
#define LDXGIVEN NDIM
#define NEXTRA 0
#define KEY 0
#define NDIM 5
#define x1 xx[0]
#define x2 xx[1]
#define x3 xx[2]
#define x4 xx[3]
#define x5 xx[4]
#define f ff[0]
////////////////////////
// -- Input values -- //
////////////////////////
//const double M = 1.77682;
const double M = 0.1056583715;
//const double M = 10.0;
//const double M = 1.0;
//const double m1 = 0.000510998928;
const double m1 = 0.00000;
const double m2 = 0.00000;
const double m3 = 0.00000;
const double BR = 1.00000;
const double muon_p = 0.05;
const double muon_theta = 0.234*M_PI;
const double muon_phi = 0.923*M_PI;
const double gamma_PDG = hbar_c / c_tau_muon;
const double gamma_formula = pow(M,5.0) * G_Fermi * G_Fermi / 192.0 / pow(M_PI,3.0);
const double ctau_formula = hbar_c/gamma_formula;
// Flags and bits
const int k0_flag = 1; // 1 - custom, 2 - physical
const int polvec_flag = 2; // 1 - custom, 2 - physical
const bool bit_addpolarized = true;
const bool BitBoostBack = true;
/////////////////////
// -- Integrand -- //
/////////////////////
static int Integrand(const int *ndim, const cubareal xx[],
const int *ncomp, cubareal ff[], void *userdata)
{
ThreeBodyDecay muon(M, m1, m2, m3);
muon.SetMotherMPThetaPhi(M,muon_p,muon_theta,muon_phi);
muon.SetBitBoostBack(BitBoostBack);
TLorentzVector *P = muon.P;
TLorentzVector *p1 = muon.p[0];
TLorentzVector *p2 = muon.p[1];
TLorentzVector *p3 = muon.p[2];
// Auxiliary vector(s)
TLorentzVector k0;
TLorentzVector k0_custom (0.0, 0.0, 1.0, 1.0);
TLorentzVector k0_physical;
double Energy = P->E();
double pmagnitude = P->P();
k0_physical[3] = 1;
for (int i = 0; i<3; i++)
{ k0_physical[i] = (*P)[i]/pmagnitude; }
for (int nu = 0; nu<4; nu++)
{ k0_physical[nu] = k0_physical[nu]/(Energy+pmagnitude); }
if ( k0_flag == 1)
{ k0 = k0_custom; }
if ( k0_flag == 2)
{ k0 = k0_physical; }
double Pk0 = P->Dot(k0);
// Spin polarization vector
TLorentzVector polvec;
// Custom spin polarization vector with p and k0
if (polvec_flag == 1)
{
for(int nu = 0; nu<4; nu++)
{ polvec[nu] = ( (*P)[nu]/M) - (M/Pk0)*k0[nu]; }
}
// Helicity spin polarization vector
// Note:
// This should be equivalent to the custom pol. vector
// when choosing physical k0
//
// Default:
if (polvec_flag == 2)
{
TVector3 phat(1.0,0.0,0.0);
phat.SetPhi(muon_phi);
phat.SetTheta(muon_theta);
double gamma = P->Gamma();
polvec = TLorentzVector(phat,P->Beta());
for(int nu = 0; nu<4; nu++)
{ polvec[nu] = polvec[nu]*gamma; }
}
// Custom:
// Polarization vector defined in the rest frame
// if (polvec_flag == 2)
// {
//
// TVector3 phat(1.0,0.0,0.0);
// phat.SetPhi(muon_phi);
// phat.SetTheta(muon_theta);
//
// polvec = TLorentzVector(phat,0);
//
// }
// if (polvec_flag == 2)
// {
// polvec[3] = pmagnitude*pmagnitude;
//
// for (int i = 0; i<3; i++)
// {
// polvec[i] = Energy*(*P)[i];
// }
//
// for(int nu = 0; nu<4; nu++)
// { polvec[nu] = polvec[nu]/M/pmagnitude; }
// }
//
//polvec[0] = 1/sqrt(2);
//polvec[1] = 1/sqrt(2);
//polvec[2] = 0;
//polvec[3] = 0;
///////////////////////////////////////////////
double weight = muon.GetPhaseSpaceWeight(x1,x2,x3,x4,x5);
// Default
//double amp_unpolarized = 128*P->Dot( (*p3) ) * p1->Dot( (*p2) );
//double amp_polarized = 128*M*(polvec*(*p3)) * ( (*p1) * (*p2) );
//
//TVector3 phat(1.0,0.0,0.0);
//phat.SetPhi(0.12);
//phat.SetTheta(2.1);
//
//polvec = TLorentzVector(phat,0);
// Testing
double amp_unpolarized = 128*P->Dot( (*p3) ) * p1->Dot( (*p2) );
double amp_polarized = -128*M*(polvec*(*p3)) * ( (*p1) * (*p2) );
//double amp_polarized = 128*M*(polvec*(*p3)) * ( (*p1) * (*p2) );
//double amp_polarized = 1e5*M*(polvec*(*p2));
//double amp = amp_unpolarized + amp_polarized;
double amp;
if ( bit_addpolarized == false)
{
amp = amp_unpolarized;
}
if ( bit_addpolarized == true)
{
amp = amp_unpolarized + amp_polarized;
}
// amp = (polvec*(*p3));
// amp = 128*M*(polvec[0]*(*p3)[0]+polvec[1]*(*p3)[1]+polvec[2]*(*p3)[2]);
//
//
TVector3 phat(1.0,0.0,0.0);
phat.SetPhi(0.0);
phat.SetTheta(0.0);
polvec = TLorentzVector(phat,0);
// TVector3 phat(1.0,0.0,0.0);
// phat.SetPhi(0.34);
// phat.SetTheta(1.2);
//
// polvec = TLorentzVector(phat,0);
double amp_unpolarized1 = 64*P->Gamma()*(1-P->Beta())*M*p3->E() *p1->Dot((*p2));
double amp_polarized1 = -64*P->Gamma()*(1-P->Beta())*M*polvec.Dot((*p3))*p1->Dot((*p2));
double amp_unpolarized2 = 64*P->Gamma()*(1+P->Beta())*M*p3->E() *p1->Dot((*p2));
double amp_polarized2 = +64*P->Gamma()*(1+P->Beta())*M*polvec.Dot((*p3))*p1->Dot((*p2));
//amp_unpolarized2 = 0;
//amp_polarized2 = 0;
//double integrand = amp_unpolarized1 + amp_polarized1 + amp_unpolarized2 + amp_polarized2;
double integrand = 2*(amp_unpolarized2 + amp_polarized2);
//double integrand = amp_unpolarized2 + amp_polarized2;
f = integrand*weight;
// TVector3 Boostvec = P->BoostVector();
// p3->Boost(-Boostvec);
// p1->Boost(-Boostvec);
// p2->Boost(-Boostvec);
// Default
// f = amp*weight;
// amp_unpolarized = 128*P->Dot( (*p3))* p1->Dot( (*p2) );
// f = amp_unpolarized*weight;
// f = 128*M*(polvec*(*p2))*weight;
// Without matrix element
// f = weight;
return 0;
};
////////////////////////
// -- Main program -- //
////////////////////////
int main()
{
////
int comp, nregions, neval, fail;
cubareal integral[NCOMP], error[NCOMP], prob[NCOMP];
ThreeBodyDecay muon(M, m1, m2, m3);
muon.SetMotherMPThetaPhi(M,muon_p,muon_theta,muon_phi);
TLorentzVector *P = muon.P;
double PSConst = muon.GetPSConst();
#if 1
printf("###############################################\n");
printf("### --- Muon decay lifetime calculation --- ###\n");
printf("###############################################\n");
printf("-------------------- Vegas test --------------------\n");
Vegas(NDIM, NCOMP, Integrand, USERDATA, NVEC,
EPSREL, EPSABS, VERBOSE, SEED,
MINEVAL, MAXEVAL, NSTART, NINCREASE, NBATCH,
GRIDNO, STATEFILE, SPIN,
&neval, &fail, integral, error, prob);
printf("VEGAS RESULT:\tneval %d\tfail %d\n",
neval, fail);
comp = 0;
printf("VEGAS RESULT:\t%.8f +- %.8f\tp = %.3f\n",
(double)integral[comp], (double)error[comp], (double)prob[comp]);
#endif
double result = (double)integral[comp];
double result_wogamma = result * PSConst * G_Fermi * G_Fermi / M / 2.0 / 2.0 ;
result = result * PSConst * G_Fermi * G_Fermi / P->E() / 2.0 / 2.0 ;
double ratio_formula = result/gamma_formula;
double ratio_PDG = result/gamma_PDG;
double tau = hbar/result;
double ctau = tau*c;
printf("\n\n");
printf("--------------------------\n");
printf("--- Physical constants ---\n");
printf("--------------------------\n");
printf("\n");
printf("hbar: %12.6e [GeV s]\n", hbar);
printf("c: %12.6e [m/s]\n", c);
printf("hbar*c: %12.6e [GeV fm]\n", hbar_c);
printf("G_Fermi: %12.6e [GeV^{-2}]\n", G_Fermi);
printf("\n");
printf("Muon constants:\n");
printf("m (muon): %12.6f [GeV]\n", M);
printf("c_tau: %12.6e [fm]\n", c_tau_muon);
printf("Gamma(PDG) = hbarc/c_tau = %12.6e [GeV]\n", gamma_PDG);
printf("\n");
printf("Other masses:\n");
printf("m (elec): %12.6f [GeV]\n", m1);
printf("m (nu_e): %12.6f [GeV]\n", m2);
printf("m (nu_m): %12.6f [GeV]\n", m3);
printf("\n");
printf("-------------------------\n");
printf("--- Decay process ---\n");
printf("-------------------------\n");
printf("\n");
printf("(muon)- ---> (electron)- (nu_mu) (nu_electronbar)\n");
printf(" p ---> q k1 k2 \n");
printf("\n");
printf("Initial Muon Configuration:\n");
printf("|pvec|: %12.6f [GeV/c]\n", muon_p);
printf("theta: %12.6f \n", muon_theta);
printf("phi: %12.6f \n", muon_phi);
printf("gamma: %12.6f \n", P->Gamma());
printf("beta: %12.6f \n", P->Beta());
printf("Four-momentum (p):\n");
displayTLorentzVector(P);
printf("\n");
TLorentzVector k0_custom (0.0, 0.0, 1.0, 1.0);
TLorentzVector k0_physical;
TLorentzVector k0;
double Energy = P->E();
double pmagnitude = P->P();
k0_physical[3] = 1;
for (int i = 0; i<3; i++)
{ k0_physical[i] = (*P)[i]/pmagnitude; }
for (int nu = 0; nu<4; nu++)
{ k0_physical[nu] = k0_physical[nu]/(Energy+pmagnitude); }
if ( k0_flag == 1)
{ k0 = k0_custom; }
if ( k0_flag == 2)
{ k0 = k0_physical; }
printf("Auxiliary vector k0\n");
displayTLorentzVector(&k0);
printf("\n");
// Spin polarization vector
TLorentzVector polvec;
double Pk0 = P->Dot(k0);
// Custom spin polarization vector with p and k0
if (polvec_flag == 1)
{
for(int nu = 0; nu<4; nu++)
{ polvec[nu] = ( (*P)[nu]/M) - (M/Pk0)*k0[nu]; }
}
// Helicity spin polarization vector
// Note:
// This should be equivalent to the custom pol. vector
// when choosing physical k0
if (polvec_flag == 2)
{
TVector3 phat(1.0,0.0,0.0);
phat.SetPhi(muon_phi);
phat.SetTheta(muon_theta);
double gamma = P->Gamma();
polvec = TLorentzVector(phat,P->Beta());
for(int nu = 0; nu<4; nu++)
{ polvec[nu] = polvec[nu]*gamma; }
}
printf("Spin polarization vector\n");
if ( polvec_flag == 1 )
{
printf("s^{mu} = P^{mu}/M - (m/Pk0)*k0^{mu}\n");
}
if ( polvec_flag == 2 )
{
printf("s^{mu} = ( |pvec|^2 , p0 pvec) / (m |pvec|))\n");
}
displayTLorentzVector(&polvec);
printf("polvec*P (orthogonality check): %12.6e", polvec*(*P));
printf("\n");
printf("Unpolarized amplitude:\n");
printf("(general form)\n");
printf("128*G_Fermi^{2}*(p k2)*(q k1)\n");
printf("(in the rest frame of muon)\n");
printf("128*G_Fermi^{2}*M*E2*(q k1)\n");
printf("Polarized amplitude:\n");
printf("+/- M*(s k2) (q k1)\n");
printf("\n");
printf("Other factors:\n");
printf("- From normalization:\n");
printf(" 1.0/(2*E) = 1.0/2*M (in the rest frame)\n");
printf("- Spin averaging for the muon:\n");
printf(" 1.0/2.0\n");
printf("\n");
printf("ThreeBodyDecay class\n");
printf("PSConstant (formula) s23_length/pow(M_PI,3.0)/128.0\n");
printf("PSConstant (numval): %12.6e \n", PSConst);
printf("\n");
printf("Gamma(formula): G_Fermi^{2}*m_mu^{5}/(192*pi^{3})\n");
printf("tau(our result): hbar/Gamma(our result)\n");
printf("\n");
printf("-------------------------\n");
printf("--- Numerical results ---\n");
printf("-------------------------\n");
printf("Note: our result are quoted in the LAB frame, while the PDG\n");
printf(" and the formula are calculated in the muon rest frame!\n");
printf("\n");
printf("Important flags:\n", bit_addpolarized);
printf("k0_type: %d (1 = custom (see above), 2 = physical)\n", k0_flag);
printf("spin_polarization: %d (1 = computed with k0, 2 = helicity)\n", polvec_flag);
printf("Polarized component added?: %d (0 = no, 1 = yes)\n", bit_addpolarized);
printf("\n");
printf("Gamma(PDG): %12.6e [GeV] (note: this is the total gamma!)\n", gamma_PDG);
printf("Gamma(formula): %12.6e [GeV]\n", gamma_formula);
printf("Gamma(our result without gamma factor): %12.6e [GeV]\n", result_wogamma);
printf("Gamma(our result): %12.6e [GeV]\n", result);
printf("\n");
printf(" tau(our result): %12.6e s\n\n", tau);
printf("ctau(PDG): %12.6e m\n", c_tau_muon*1e-15);
printf("ctau(formula): %12.6e m\n", ctau_formula*1e-15);
printf("ctau(our result): %12.6e m\n", ctau);
printf("\n");
printf("Muon\n");
printf("beta: %12.6f\n", P->Beta());
printf("gamma: %12.6f\n", P->Gamma());
printf("ctau ratio: (our result ctau)/(formula ctau rest frame) %12.6f\n", ctau/ctau_formula/1e-15);
printf("ratio of the above two values: %12.6f\n", P->Gamma()/(ctau/ctau_formula/1e-15));
printf("!!! COMPARE THE ABOVE !!! gamma vs. ctau ratio\n");
#if 0
printf("\n-------------------- Suave test --------------------\n");
Suave(NDIM, NCOMP, Integrand, USERDATA, NVEC,
EPSREL, EPSABS, VERBOSE | LAST, SEED,
MINEVAL, MAXEVAL, NNEW, NMIN, FLATNESS,
STATEFILE, SPIN,
&nregions, &neval, &fail, integral, error, prob);
printf("SUAVE RESULT:\tnregions %d\tneval %d\tfail %d\n",
nregions, neval, fail);
for( comp = 0; comp < NCOMP; ++comp )
printf("SUAVE RESULT:\t%.8f +- %.8f\tp = %.3f\n",
(double)integral[comp], (double)error[comp], (double)prob[comp]);
#endif
#if 0
printf("\n------------------- Divonne test -------------------\n");
Divonne(NDIM, NCOMP, Integrand, USERDATA, NVEC,
EPSREL, EPSABS, VERBOSE, SEED,
MINEVAL, MAXEVAL, KEY1, KEY2, KEY3, MAXPASS,
BORDER, MAXCHISQ, MINDEVIATION,
NGIVEN, LDXGIVEN, NULL, NEXTRA, NULL,
STATEFILE, SPIN,
&nregions, &neval, &fail, integral, error, prob);
printf("DIVONNE RESULT:\tnregions %d\tneval %d\tfail %d\n",
nregions, neval, fail);
for( comp = 0; comp < NCOMP; ++comp )
printf("DIVONNE RESULT:\t%.8f +- %.8f\tp = %.3f\n",
(double)integral[comp], (double)error[comp], (double)prob[comp]);
#endif
#if 0
printf("\n-------------------- Cuhre test --------------------\n");
Cuhre(NDIM, NCOMP, Integrand, USERDATA, NVEC,
EPSREL, EPSABS, VERBOSE | LAST,
MINEVAL, MAXEVAL, KEY,
STATEFILE, SPIN,
&nregions, &neval, &fail, integral, error, prob);
printf("CUHRE RESULT:\tnregions %d\tneval %d\tfail %d\n",
nregions, neval, fail);
for( comp = 0; comp < NCOMP; ++comp )
printf("CUHRE RESULT:\t%.8f +- %.8f\tp = %.3f\n",
(double)integral[comp], (double)error[comp], (double)prob[comp]);
#endif
return 0;
}
| [
"englert.david@gmail.com"
] | englert.david@gmail.com |
17bacc2d3086022042a1ff3efd5d00d986d8c664 | 5612363ec266865bf4ad40634d6a58b46a61322a | /RoseCommon/stb.h | 17f1476898b2d3005f468fd8921d5eee8380edf2 | [] | no_license | DrakiaXYZ/RoseTools | 14063e01bdd0e21040729622fbed406435ce387c | cfd37f9b57eb863f9496b99b0b26abf441c92a46 | refs/heads/master | 2023-03-16T12:41:41.332821 | 2012-05-19T05:42:35 | 2012-05-19T05:42:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 385 | h | #include "binaryFile.hpp"
#include <iostream>
#include <vector>
using namespace std;
class STB {
public:
STB(string file);
string getCell(int row, int col);
int getRowCount() {return rowCount;};
int getColCount() {return colCount;};
private:
vector< vector<string> > table;
int rowCount;
int colCount;
string idColName;
char formatKey[5];
};
| [
"Contact@TheDgtl.net"
] | Contact@TheDgtl.net |
454b86608390a0d77ca1028ff32720c01e6f4c99 | 7039b78e3a71f1652b9969690552aa7897883be5 | /3rdparty/tesseract/src/wordrec/params_model.cpp | 90975af86c2cbcb1aa3ee4fd97060c9a3ab0f9fe | [
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | permissive | thigiacmaytinh/opencv342 | 4c2fbf28d2586e81c45c9369d448fe234c3c3f51 | 9256fe601088a60d1c91cb0d040d2d929966c2e7 | refs/heads/master | 2020-03-28T18:48:29.843617 | 2019-05-17T09:45:01 | 2019-05-17T09:45:01 | 148,914,179 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,400 | cpp | ///////////////////////////////////////////////////////////////////////
// File: params_model.cpp
// Description: Trained language model parameters.
// Author: David Eger
// Created: Mon Jun 11 11:26:42 PDT 2012
//
// (C) Copyright 2012, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#include "params_model.h"
#include <ctype.h>
#include <cmath>
#include <cstdio>
#include "bitvector.h"
#include "tprintf.h"
namespace tesseract {
// Scale factor to apply to params model scores.
static const float kScoreScaleFactor = 100.0f;
// Minimum cost result to return.
static const float kMinFinalCost = 0.001f;
// Maximum cost result to return.
static const float kMaxFinalCost = 100.0f;
void ParamsModel::Print() {
for (int p = 0; p < PTRAIN_NUM_PASSES; ++p) {
tprintf("ParamsModel for pass %d lang %s\n", p, lang_.string());
for (int i = 0; i < weights_vec_[p].size(); ++i) {
tprintf("%s = %g\n", kParamsTrainingFeatureTypeName[i],
weights_vec_[p][i]);
}
}
}
void ParamsModel::Copy(const ParamsModel &other_model) {
for (int p = 0; p < PTRAIN_NUM_PASSES; ++p) {
weights_vec_[p] = other_model.weights_for_pass(
static_cast<PassEnum>(p));
}
}
// Given a (modifiable) line, parse out a key / value pair.
// Return true on success.
bool ParamsModel::ParseLine(char *line, char** key, float *val) {
if (line[0] == '#')
return false;
int end_of_key = 0;
while (line[end_of_key] && !isspace(line[end_of_key])) end_of_key++;
if (!line[end_of_key]) {
tprintf("ParamsModel::Incomplete line %s\n", line);
return false;
}
line[end_of_key++] = 0;
*key = line;
if (sscanf(line + end_of_key, " %f", val) != 1)
return false;
return true;
}
// Applies params model weights to the given features.
// Assumes that features is an array of size PTRAIN_NUM_FEATURE_TYPES.
// The cost is set to a number that can be multiplied by the outline length,
// as with the old ratings scheme. This enables words of different length
// and combinations of words to be compared meaningfully.
float ParamsModel::ComputeCost(const float features[]) const {
float unnorm_score = 0.0;
for (int f = 0; f < PTRAIN_NUM_FEATURE_TYPES; ++f) {
unnorm_score += weights_vec_[pass_][f] * features[f];
}
return ClipToRange(-unnorm_score / kScoreScaleFactor,
kMinFinalCost, kMaxFinalCost);
}
bool ParamsModel::Equivalent(const ParamsModel &that) const {
float epsilon = 0.0001;
for (int p = 0; p < PTRAIN_NUM_PASSES; ++p) {
if (weights_vec_[p].size() != that.weights_vec_[p].size()) return false;
for (int i = 0; i < weights_vec_[p].size(); i++) {
if (weights_vec_[p][i] != that.weights_vec_[p][i] &&
fabs(weights_vec_[p][i] - that.weights_vec_[p][i]) > epsilon)
return false;
}
}
return true;
}
bool ParamsModel::LoadFromFile(
const char *lang,
const char *full_path) {
TFile fp;
if (!fp.Open(full_path, nullptr)) {
tprintf("Error opening file %s\n", full_path);
return false;
}
return LoadFromFp(lang, &fp);
}
bool ParamsModel::LoadFromFp(const char *lang, TFile *fp) {
const int kMaxLineSize = 100;
char line[kMaxLineSize];
BitVector present;
present.Init(PTRAIN_NUM_FEATURE_TYPES);
lang_ = lang;
// Load weights for passes with adaption on.
GenericVector<float> &weights = weights_vec_[pass_];
weights.init_to_size(PTRAIN_NUM_FEATURE_TYPES, 0.0);
while (fp->FGets(line, kMaxLineSize) != nullptr) {
char *key = nullptr;
float value;
if (!ParseLine(line, &key, &value))
continue;
int idx = ParamsTrainingFeatureByName(key);
if (idx < 0) {
tprintf("ParamsModel::Unknown parameter %s\n", key);
continue;
}
if (!present[idx]) {
present.SetValue(idx, true);
}
weights[idx] = value;
}
bool complete = (present.NumSetBits() == PTRAIN_NUM_FEATURE_TYPES);
if (!complete) {
for (int i = 0; i < PTRAIN_NUM_FEATURE_TYPES; i++) {
if (!present[i]) {
tprintf("Missing field %s.\n", kParamsTrainingFeatureTypeName[i]);
}
}
lang_ = "";
weights.truncate(0);
}
return complete;
}
bool ParamsModel::SaveToFile(const char *full_path) const {
const GenericVector<float> &weights = weights_vec_[pass_];
if (weights.size() != PTRAIN_NUM_FEATURE_TYPES) {
tprintf("Refusing to save ParamsModel that has not been initialized.\n");
return false;
}
FILE *fp = fopen(full_path, "wb");
if (!fp) {
tprintf("Could not open %s for writing.\n", full_path);
return false;
}
bool all_good = true;
for (int i = 0; i < weights.size(); i++) {
if (fprintf(fp, "%s %f\n", kParamsTrainingFeatureTypeName[i], weights[i])
< 0) {
all_good = false;
}
}
fclose(fp);
return all_good;
}
} // namespace tesseract
| [
"vohungvi@vohungvi.com"
] | vohungvi@vohungvi.com |
207e233600ec2f0be9deeeeae279f5babf91a3f8 | 76b4a57de3801096e401ceac6cd0f939c0703d9d | /Software/Arduino/libraries/M5Stack-master/examples/Advanced/WIFI/OTAUpload/OTAUpload.ino | 52cd422e2cfcfeefc2f8de30a57659e1416b2d3a | [
"MIT"
] | permissive | flyonspeed/OnSpeed-Gen2 | e6edd87cda783db30484d32e2b51713f0484386c | ac7e4c5c4c36c88b9005b848a5dc6489577884f1 | refs/heads/master | 2023-08-17T02:37:30.756859 | 2023-04-17T01:02:08 | 2023-04-17T01:02:08 | 216,622,791 | 20 | 9 | MIT | 2023-04-03T14:22:36 | 2019-10-21T17:11:04 | C | UTF-8 | C++ | false | false | 2,404 | ino | /*
*******************************************************************************
* Copyright (c) 2021 by M5Stack
* Equipped with M5Core sample source code
* 配套 M5Core 示例源代码
* Visit the website for more information:https://docs.m5stack.com/en/core/gray
* 获取更多资料请访问:https://docs.m5stack.com/zh_CN/core/gray
*
* describe:OTA Upload. 隔空传输程序
* date:2021/7/30
*******************************************************************************
PC and M5Core can only be used on the same wifi. 电脑和M5Core需在同一wifi下才可使用
When the OTA is ready, restart the Arduino client from Tools > Ports > Network ports to instantly transmit the program wirelessly.
OTA 准备好后重启Arduino客户端在工具->端口->网络端口,即刻无线传输程序
*/
#include <M5Stack.h>
#include <WiFi.h>
#include <ArduinoOTA.h>
// Set the name and password of the wifi to be connected. 配置所连接wifi的名称和密码
const char* ssid = "M5wifi";
const char* password = "1234";
void setup() {
M5.begin(); //Init M5Core. 初始化 M5Core
M5.Power.begin();
WiFi.begin(ssid, password); //Connect wifi and return connection status. 连接wifi并返回连接状态
M5.lcd.print("Waiting Wifi Connect");
while (WiFi.status() != WL_CONNECTED) { //If the wifi connection fails. 若wifi未连接成功
delay(1000);
M5.lcd.print(".");
}
M5.lcd.println("\nWiFi Connected!");
M5.lcd.print("WiFi Connect To: ");
M5.lcd.println(WiFi.SSID()); //Output Network name. 输出网络名称
M5.lcd.print("IP address: ");
M5.lcd.println(WiFi.localIP()); //Output IP Address. 输出IP地址
ArduinoOTA.setHostname("M5Core"); //Set the network port name. 设置网络端口名称
ArduinoOTA.setPassword("666666"); //Set the network port connection password. 设置网络端口连接的密码
ArduinoOTA.begin(); //Initialize the OTA. 初始化OTA
M5.lcd.println("OTA ready!"); //M5.lcd port output format string. 串口输出格式化字符串
}
void loop() {
ArduinoOTA.handle(); //Continuously check for update requests. 持续检测是否有更新请求
M5.update();
if(M5.BtnA.isPressed()){ //if BtnA is Pressed. 如果按键A按下
ArduinoOTA.end(); //Ends the ArduinoOTA service. 结束OTA服务
M5.lcd.println("OTA End!");
delay(200);
}
} | [
"53226948+flyonspeed@users.noreply.github.com"
] | 53226948+flyonspeed@users.noreply.github.com |
326d9e29259fa5da38278e95e63fea57f6b0dd16 | 818c117039e1f7be9c50d13dbcd0100433016f02 | /qzfem/mindlinshelllaminated.cpp | 43ef5ee63b89ac5e97018c3477ae82f717318abe | [] | no_license | qzcad/qzcad-tree | d4484f6200b56956c13f5190dd0ef8c37de30306 | fb6a59ddf561cb1fc393ba5342107db0e0ffaad7 | refs/heads/master | 2022-07-03T21:47:11.725300 | 2022-06-09T12:05:27 | 2022-06-09T12:05:27 | 21,324,656 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,513 | cpp | #include "mindlinshelllaminated.h"
#include <iostream>
#include <math.h>
#include "consoleprogress.h"
MindlinShellLaminated::MindlinShellLaminated(Mesh3D *mesh,
const std::vector<double> &thickness,
const std::vector<DoubleMatrix> &planeStressMatrix,
const std::list<FemCondition *> &conditions,
double alphaT) :
MindlinShellBending(mesh, thickness[0], planeStressMatrix[0], conditions, alphaT)
{
thickness_ = thickness;
D_ = planeStressMatrix;
unsigned layers_count = D_.size();
Dc_.resize(layers_count);
for (unsigned i = 0; i < layers_count; i++)
{
Dc_[i].resize(2, 2);
Dc_[i] (0, 1) = Dc_[i] (1, 0) = 0.0;
Dc_[i] (0, 0) = D_[i] (2, 2);
Dc_[i] (1, 1) = D_[i] (2, 2);
}
thickness_func_ = NULL;
}
MindlinShellLaminated::MindlinShellLaminated(Mesh3D *mesh,
const std::vector<double> &thickness,
const std::vector<DoubleMatrix> &D,
const std::vector<DoubleMatrix> &Dc,
const std::list<FemCondition *> &conditions,
double alphaT) :
MindlinShellBending(mesh, thickness[0], D[0], Dc[0], conditions, alphaT)
{
thickness_ = thickness;
D_ = D;
Dc_ = Dc;
thickness_func_ = NULL;
}
MindlinShellLaminated::MindlinShellLaminated(Mesh3D *mesh,
std::function<std::vector<double> (double, double, double)> thickness,
const std::vector<DoubleMatrix> &planeStressMatrix,
const std::list<FemCondition *> &conditions,
double alphaT) :
MindlinShellBending(mesh, 1.0, planeStressMatrix[0], conditions, alphaT)
{
D_ = planeStressMatrix;
unsigned layers_count = D_.size();
Dc_.resize(layers_count);
for (unsigned i = 0; i < layers_count; i++)
{
Dc_[i].resize(2, 2);
Dc_[i] (0, 1) = Dc_[i] (1, 0) = 0.0;
Dc_[i] (0, 0) = D_[i] (2, 2);
Dc_[i] (1, 1) = D_[i] (2, 2);
}
thickness_func_ = thickness;
}
MindlinShellLaminated::MindlinShellLaminated(Mesh3D *mesh,
std::function<std::vector<double> (double, double, double)> thickness,
const std::vector<DoubleMatrix> &D,
const std::vector<DoubleMatrix> &Dc,
const std::list<FemCondition *> &conditions,
double alphaT) :
MindlinShellBending(mesh, 1.0, D[0], Dc[0], conditions, alphaT)
{
D_ = D;
Dc_ = Dc;
thickness_func_ = thickness;
}
void MindlinShellLaminated::buildGlobalMatrix()
{
const double kappa = 5.0 / 6.0;
UInteger elementsCount = mesh_->elementsCount(); // количество элементов
DoubleVector gxi; // координаты квадратур Гаусса
DoubleVector geta;
DoubleVector gweight; // весовые коэффициенты квадратур
int gaussPoints = 0; // количество точек квадратур
int line_count = 5; // количество точек квадратур при интегрировании вдоль линии
DoubleVector line_points;
DoubleVector line_weights;
quadrature(line_count, line_points, line_weights);
UInteger elementNodes = 0; // количество узлов в элементе
if (dynamic_cast<TriangleMesh3D*>(mesh_) != NULL)
{
elementNodes = 3;
gaussPoints = 4;
quadrature(gaussPoints, gxi, geta, gweight);
}
else if (dynamic_cast<QuadrilateralMesh3D*>(mesh_) != NULL)
{
gaussPoints = line_count * line_count;
gxi.resize(gaussPoints);
geta.resize(gaussPoints);
gweight.resize(gaussPoints);
elementNodes = 4;
for (int i = 0; i < line_count; i++)
{
for (int j = 0; j < line_count; j++)
{
gxi[i * line_count + j] = line_points[i];
geta[i * line_count + j] = line_points[j];
gweight[i * line_count + j] = line_weights[i] * line_weights[j];
}
}
}
unsigned layers_count = D_.size();
std::vector<double> thickness = thickness_;
double H = 0.0; // толщина
for (unsigned i = 0; i < layers_count; i++)
{
std::cout << "D[" << i << "]:" << std::endl;
D_[i].print();
std::cout << "Dc["<< i << "]:" << std::endl;
Dc_[i].print();
if (!thickness_.empty())
H += thickness_[i];
}
if (!thickness_.empty())
std::cout << "Thickness: " << H << std::endl;
else
std::cout << "The laminated shell with a variable thickness." << std::endl;
// построение глобальной матрицы жесткости
std::cout << "Stiffness Matrix...";
ConsoleProgress progressBar(elementsCount);
for (UInteger elNum = 0; elNum < elementsCount; elNum++)
{
++progressBar;
DoubleMatrix local(freedom_ * elementNodes, freedom_ * elementNodes, 0.0);
ElementPointer element = mesh_->element(elNum);
Point3D A = *(dynamic_cast<const Point3D *>(mesh_->node(element->vertexNode(0))));
Point3D B = *(dynamic_cast<const Point3D *>(mesh_->node(element->vertexNode(1))));
Point3D C = *(dynamic_cast<const Point3D *>(mesh_->node(element->vertexNode(2))));
DoubleMatrix lambda = cosinuses(A, B, C);
DoubleMatrix lambdaT = lambda.transpose();
DoubleMatrix T(freedom_ * elementNodes, freedom_ * elementNodes, 0.0);
for (UInteger i = 0; i <= (freedom_ * elementNodes - 3); i += 3)
{
for (UInteger ii = 0; ii < 3; ii++)
for (UInteger jj = 0; jj < 3; jj++)
T(ii + i, jj + i) = lambda(ii, jj);
}
DoubleVector x(elementNodes);
DoubleVector y(elementNodes);
// извлечение координат узлов
for (UInteger i = 0; i < elementNodes; i++)
{
Point3D point = *(dynamic_cast<const Point3D *>(mesh_->node(element->vertexNode(i))));
Point3D pp = point - A;
x[i] = lambda(0, 0) * pp.x() + lambda(0, 1) * pp.y() + lambda(0, 2) * pp.z();
y[i] = lambda(1, 0) * pp.x() + lambda(1, 1) * pp.y() + lambda(1, 2) * pp.z();
}
for (int ig = 0; ig < gaussPoints; ig++)
{
double xi = gxi(ig);
double eta = geta(ig);
double w = gweight(ig);
// значения функций формы
DoubleVector N(elementNodes);
// значения производных функций формы
DoubleVector dNdX(elementNodes);
DoubleVector dNdY(elementNodes);
// якобиан
double jacobian = 1.0;
if (dynamic_cast<TriangleMesh3D*>(mesh_) != NULL)
{
jacobian = isoTriangle3(xi, eta, x, y, N, dNdX, dNdY);
}
else if (dynamic_cast<QuadrilateralMesh3D*>(mesh_) != NULL)
{
jacobian = isoQuad4(xi, eta, x, y, N, dNdX, dNdY);
}
//
DoubleMatrix Bm(3, freedom_ * elementNodes, 0.0);
DoubleMatrix Bf(3, freedom_ * elementNodes, 0.0);
DoubleMatrix Bc(2, freedom_ * elementNodes, 0.0);
for (UInteger i = 0; i < elementNodes; i++)
{
Bm(0, i * freedom_) = dNdX(i);
Bm(1, i * freedom_ + 1) = dNdY(i);
Bm(2, i * freedom_) = dNdY(i); Bm(2, i * freedom_ + 1) = dNdX(i);
Bf(0, i * freedom_ + 3) = dNdX(i);
Bf(1, i * freedom_ + 4) = dNdY(i);
Bf(2, i * freedom_ + 3) = dNdY(i); Bf(2, i * freedom_ + 4) = dNdX(i);
Bc(0, i * freedom_ + 2) = dNdX(i); Bc(0, i * freedom_ + 3) = N(i);
Bc(1, i * freedom_ + 2) = dNdY(i); Bc(1, i * freedom_ + 4) = N(i);
}
if (thickness_func_ != NULL)
{
double xLocal = x * N;
double yLocal = y * N;
Point3D pl(lambdaT(0, 0) * xLocal + lambdaT(0, 1) * yLocal,
lambdaT(1, 0) * xLocal + lambdaT(1, 1) * yLocal,
lambdaT(2, 0) * xLocal + lambdaT(2, 1) * yLocal);
Point3D pLocal = pl + A;
thickness = thickness_func_(pLocal.x(), pLocal.y(), pLocal.z());
H = 0.0;
for (double h: thickness)
H += h;
}
double z0 = -H / 2.0;
double z1 = 0.0;
for (unsigned i = 0; i < layers_count; i++)
{
z1 = z0 + thickness[i];
local += jacobian * w * (z1 - z0) * (Bm.transpose() * D_[i] * Bm);
local += jacobian * w * (z1*z1 - z0*z0) / 2.0 * (Bm.transpose() * D_[i] * Bf);
local += jacobian * w * (z1*z1 - z0*z0) / 2.0 * (Bf.transpose() * D_[i] * Bm);
local += jacobian * w * (z1*z1*z1 - z0*z0*z0) / 3.0 * (Bf.transpose() * D_[i] * Bf);
local += jacobian * w * kappa * (z1 - z0) * (Bc.transpose() * Dc_[i] * Bc);
z0 = z1;
}
} // ig
DoubleMatrix surf = T.transpose() * local * T;
// Ансамблирование
assembly(element, surf);
} //for elNum
}
void MindlinShellLaminated::processSolution(const DoubleVector &displacement)
{
UInteger nodesCount = mesh_->nodesCount(); // количество узлов сетки
UInteger elementsCount = mesh_->elementsCount(); // количество элементов
UInteger elementNodes = 0; // количество узлов в элементе
if (dynamic_cast<TriangleMesh3D*>(mesh_) != NULL)
{
elementNodes = 3;
}
else if (dynamic_cast<QuadrilateralMesh3D*>(mesh_) != NULL)
{
elementNodes = 4;
}
unsigned layers_count = D_.size();
double H = 0.0; // толщина
for (unsigned i = 0; i < layers_count; i++)
{
std::cout << "D[" << i << "]:" << std::endl;
D_[i].print();
std::cout << "Dc["<< i << "]:" << std::endl;
Dc_[i].print();
if (!thickness_.empty()) H += thickness_[i];
}
std::vector<double> xxx(nodesCount);
std::vector<double> yyy(nodesCount);
std::vector<double> zzz(nodesCount);
std::vector<double> theta_x(nodesCount);
std::vector<double> theta_y(nodesCount);
std::vector<double> theta_z(nodesCount);
for (UInteger i = 0; i < nodesCount; i++)
{
xxx[i] = displacement[freedom_ * i];
yyy[i] = displacement[freedom_ * i + 1UL];
zzz[i] = displacement[freedom_ * i + 2UL];
theta_x[i] = displacement[freedom_ * i + 3UL];
theta_y[i] = displacement[freedom_ * i + 4UL];
theta_z[i] = displacement[freedom_ * i + 5UL];
}
mesh_->addDataVector("X", xxx);
mesh_->addDataVector("Y", yyy);
mesh_->addDataVector("Z", zzz);
mesh_->addDataVector("Theta X", theta_x);
mesh_->addDataVector("Theta Y", theta_y);
mesh_->addDataVector("Theta Z", theta_z);
// вычисление напряжений
std::vector<double> SigmaX(nodesCount, 0.0);
std::vector<double> SigmaY(nodesCount, 0.0);
std::vector<double> SigmaZ(nodesCount, 0.0);
std::vector<double> TauXY(nodesCount, 0.0);
std::vector<double> TauXZ(nodesCount, 0.0);
std::vector<double> TauYZ(nodesCount, 0.0);
std::vector<double> mises(nodesCount, 0.0);
double xi[elementNodes];
double eta[elementNodes];
if (dynamic_cast<TriangleMesh3D*>(mesh_) != NULL)
{
xi[0] = 0.0; eta[0] = 0.0;
xi[1] = 1.0; eta[1] = 0.0;
xi[2] = 0.0; eta[2] = 1.0;
}
else if (dynamic_cast<QuadrilateralMesh3D*>(mesh_) !=NULL)
{
xi[0] = -1.0; eta[0] = -1.0;
xi[1] = 1.0; eta[1] = -1.0;
xi[2] = 1.0; eta[2] = 1.0;
xi[3] = -1.0; eta[3] = 1.0;
}
std::cout << "Stresses Recovery...";
ConsoleProgress progressBar(elementsCount);
for (UInteger elNum = 0; elNum < elementsCount; elNum++)
{
++progressBar;
ElementPointer element = mesh_->element(elNum);
Point3D A = *(dynamic_cast<const Point3D *>(mesh_->node(element->vertexNode(0))));
Point3D B = *(dynamic_cast<const Point3D *>(mesh_->node(element->vertexNode(1))));
Point3D C = *(dynamic_cast<const Point3D *>(mesh_->node(element->vertexNode(2))));
DoubleMatrix lambda = cosinuses(A, B, C);
DoubleMatrix T(freedom_ * elementNodes, freedom_ * elementNodes, 0.0);
for (UInteger i = 0; i <= (freedom_ * elementNodes - 3); i += 3)
{
for (UInteger ii = 0; ii < 3; ii++)
for (UInteger jj = 0; jj < 3; jj++)
T(ii + i, jj + i) = lambda(ii, jj);
}
DoubleMatrix lambdaT = lambda.transpose();
DoubleVector x(elementNodes);
DoubleVector y(elementNodes);
// извлечение координат узлов
for (UInteger i = 0; i < elementNodes; i++)
{
Point3D point = *(dynamic_cast<const Point3D *>(mesh_->node(element->vertexNode(i))));
Point3D pp = point - A;
x[i] = lambda(0, 0) * pp.x() + lambda(0, 1) * pp.y() + lambda(0, 2) * pp.z();
y[i] = lambda(1, 0) * pp.x() + lambda(1, 1) * pp.y() + lambda(1, 2) * pp.z();
}
for (UInteger inode = 0; inode < elementNodes; inode++)
{
DoubleVector N(elementNodes);
DoubleVector dNdX(elementNodes);
DoubleVector dNdY(elementNodes);
DoubleVector dis((size_type)(freedom_ * elementNodes), 0.0);
DoubleVector sigma_membrane((size_type)3, 0.0);
DoubleVector sigma_plate((size_type)3, 0.0);
DoubleVector sigma((size_type)3, 0.0);
DoubleVector tau((size_type)2, 0.0);
// якобиан
if (dynamic_cast<TriangleMesh3D*>(mesh_) != NULL)
{
isoTriangle3(xi[inode], eta[inode], x, y, N, dNdX, dNdY);
}
else if (dynamic_cast<QuadrilateralMesh3D*>(mesh_) != NULL)
{
isoQuad4(xi[inode], eta[inode], x, y, N, dNdX, dNdY);
}
//
DoubleMatrix Bm(3, freedom_ * elementNodes, 0.0);
DoubleMatrix Bf(3, freedom_ * elementNodes, 0.0);
DoubleMatrix Bc(2, freedom_ * elementNodes, 0.0);
for (UInteger i = 0; i < elementNodes; i++)
{
Bm(0, i * freedom_) = dNdX(i);
Bm(1, i * freedom_ + 1) = dNdY(i);
Bm(2, i * freedom_) = dNdY(i); Bm(2, i * freedom_ + 1) = dNdX(i);
Bf(0, i * freedom_ + 3) = dNdX(i);
Bf(1, i * freedom_ + 4) = dNdY(i);
Bf(2, i * freedom_ + 3) = dNdY(i); Bf(2, i * freedom_ + 4) = dNdX(i);
Bc(0, i * freedom_ + 2) = dNdX(i); Bc(0, i * freedom_ + 3) = N(i);
Bc(1, i * freedom_ + 2) = dNdY(i); Bc(1, i * freedom_ + 4) = N(i);
}
for (UInteger i = 0; i < elementNodes; i++)
{
dis(freedom_ * i) = displacement[freedom_ * element->vertexNode(i)];
dis(freedom_ * i + 1) = displacement[freedom_ * element->vertexNode(i) + 1UL];
dis(freedom_ * i + 2) = displacement[freedom_ * element->vertexNode(i) + 2UL];
dis(freedom_ * i + 3) = displacement[freedom_ * element->vertexNode(i) + 3UL];
dis(freedom_ * i + 4) = displacement[freedom_ * element->vertexNode(i) + 4UL];
dis(freedom_ * i + 5) = displacement[freedom_ * element->vertexNode(i) + 5UL];
}
DoubleVector dLocal = T * dis;
sigma_membrane = (D_[layers_count - 1] * Bm) * dLocal;
if (thickness_func_ != NULL)
{
double xLocal = x * N;
double yLocal = y * N;
Point3D pl(lambdaT(0, 0) * xLocal + lambdaT(0, 1) * yLocal,
lambdaT(1, 0) * xLocal + lambdaT(1, 1) * yLocal,
lambdaT(2, 0) * xLocal + lambdaT(2, 1) * yLocal);
// вычисление объемных сил
Point3D pLocal = pl + A;
std::vector<double> thickness = thickness_func_(pLocal.x(), pLocal.y(), pLocal.z());
H = 0.0;
for (double h: thickness)
H += h;
}
sigma_plate = H / 2.0 * ((D_[layers_count - 1] * Bf) * dLocal);
sigma[0] = sigma_membrane[0] + sigma_plate[0];
sigma[1] = sigma_membrane[1] + sigma_plate[1];
sigma[2] = sigma_membrane[2] + sigma_plate[2];
tau = (Dc_[layers_count - 1] * Bc) * dLocal;
DoubleMatrix localSigma(3, 3, 0.0);
localSigma(0, 0) = sigma(0); localSigma(0, 1) = sigma(2); localSigma(0, 2) = tau(0);
localSigma(1, 0) = sigma(2); localSigma(1, 1) = sigma(1); localSigma(1, 2) = tau(1);
localSigma(2, 0) = tau(0); localSigma(2, 1) = tau(1); localSigma(2, 2) = 0.0;
DoubleMatrix SG = lambdaT * localSigma * lambda;
double von = sqrt(0.5) * sqrt((SG(0, 0) - SG(1, 1)) * (SG(0, 0) - SG(1, 1)) +
(SG(1, 1) - SG(2, 2)) * (SG(1, 1) - SG(2, 2)) +
(SG(2, 2) - SG(0, 0)) * (SG(2, 2) - SG(0, 0)) +
6.0 * (SG(0, 1) * SG(0, 1) + SG(1, 2) * SG(1, 2) + SG(0, 2) * SG(0, 2)));
SigmaX[element->vertexNode(inode)] += SG(0, 0);
SigmaY[element->vertexNode(inode)] += SG(1, 1);
SigmaZ[element->vertexNode(inode)] += SG(2, 2);
TauXY[element->vertexNode(inode)] += SG(0, 1);
TauXZ[element->vertexNode(inode)] += SG(0, 2);
TauYZ[element->vertexNode(inode)] += SG(1, 2);
mises[element->vertexNode(inode)] += von;
}
} //for elNum
for (UInteger i = 0; i < nodesCount; i++)
{
SigmaX[i] /= (double)mesh_->adjacentCount(i);
SigmaY[i] /= (double)mesh_->adjacentCount(i);
SigmaZ[i] /= (double)mesh_->adjacentCount(i);
TauXY[i] /= (double)mesh_->adjacentCount(i);
TauXZ[i] /= (double)mesh_->adjacentCount(i);
TauYZ[i] /= (double)mesh_->adjacentCount(i);
mises[i] /= (double)mesh_->adjacentCount(i);
}
mesh_->addDataVector("Sigma X", SigmaX);
mesh_->addDataVector("Sigma Y", SigmaY);
mesh_->addDataVector("Sigma Z", SigmaZ);
mesh_->addDataVector("Tau XY", TauXY);
mesh_->addDataVector("Tau XZ", TauXZ);
mesh_->addDataVector("Tau YZ", TauYZ);
mesh_->addDataVector("von Mises", mises);
}
| [
"choporov@list.ru"
] | choporov@list.ru |
3b3e77e61f1e239deebdd32c10c3eee50817ced2 | b36f34b6a24d019d624d1cc74f5b29062eef2ba4 | /frameworks/3rd/dragonbones/src/dragonBones/model/SkinData.cpp | e3b18835951d84808beae775fa7a4524e0507af1 | [
"MIT"
] | permissive | zhongfq/cocos-lua | f49c1639f2c9a2a7678f9ed67e58114986ac882f | c2cf0f36ac0f0c91fb3456b555cacd8e8587be46 | refs/heads/main | 2023-08-17T17:13:05.705639 | 2023-08-17T06:06:36 | 2023-08-17T06:06:36 | 192,316,318 | 165 | 63 | MIT | 2023-08-14T23:59:30 | 2019-06-17T09:27:37 | C | UTF-8 | C++ | false | false | 1,041 | cpp | #include "SkinData.h"
#include "DisplayData.h"
DRAGONBONES_NAMESPACE_BEGIN
void SkinData::_onClear()
{
for (const auto& pair : displays)
{
for (const auto display : pair.second)
{
if (display != nullptr)
{
display->returnToPool();
}
}
}
name = "";
displays.clear();
parent = nullptr;
}
void SkinData::addDisplay(const std::string& slotName, DisplayData* value)
{
if (value != nullptr)
{
value->parent = this;
}
displays[slotName].push_back(value); // TODO clear prev
}
DisplayData* SkinData::getDisplay(const std::string& slotName, const std::string& displayName)
{
const auto slotDisplays = getDisplays(slotName);
if (slotDisplays != nullptr)
{
for (const auto display : *slotDisplays)
{
if (display != nullptr && display->name == displayName)
{
return display;
}
}
}
return nullptr;
}
DRAGONBONES_NAMESPACE_END
| [
"anzehao@ixianlai.com"
] | anzehao@ixianlai.com |
83c20258a1f15ff95100c7b4e55ad0a4683eafe4 | 969ed26bb44f94ca4226aa66af0cd5cb0c2c3537 | /launcher/Launcher.h | 5e5ab7b492655d6992a8620b0282ae0fe3ac6916 | [
"BSD-2-Clause"
] | permissive | kidaa/SeventhUmbral | 2e87295278d8b0067d118799ac0e32bded07a476 | 5c7651ac2cd9d9f5c1f7969932c15ccdf6d8848c | refs/heads/master | 2020-04-30T11:07:27.364028 | 2015-05-16T00:56:11 | 2015-05-16T00:56:11 | 35,638,361 | 0 | 0 | null | 2015-05-14T21:38:28 | 2015-05-14T21:38:28 | null | UTF-8 | C++ | false | false | 115 | h | #pragma once
class CLauncher
{
public:
static void Launch(const char*, const char*, const char*);
private:
};
| [
"kidakadeshia@gmail.com"
] | kidakadeshia@gmail.com |
858edb2edab4ed7e86e017f2db63e0effa13ae43 | 0917d321501a8213fafa58618f35c2409959e877 | /NatsuLib/natRefObj.h | cfab05266db38e0b4a7a321cc8c92967b03cff76 | [] | no_license | huwenshayu/NatsuLib | 880e5b687fae9e770b6b6c287fcca185518162e3 | b542c7af34d6f81026105f1a023a35e97a66aec3 | refs/heads/master | 2020-12-10T04:30:19.922819 | 2017-03-01T09:30:24 | 2017-03-01T09:31:09 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 17,450 | h | ////////////////////////////////////////////////////////////////////////////////
/// @file natRefObj.h
/// @brief 引用计数对象相关
////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "natType.h"
#include <cassert>
#include <mutex>
#include <atomic>
#include <memory>
#ifdef TraceRefObj
#include "natUtil.h"
#include <typeinfo>
#endif
namespace NatsuLib
{
////////////////////////////////////////////////////////////////////////////////
/// @brief 引用计数接口
////////////////////////////////////////////////////////////////////////////////
struct natRefObj
{
virtual ~natRefObj() = default;
virtual size_t GetRefCount() const volatile noexcept = 0;
virtual nBool TryAddRef() const volatile = 0;
virtual void AddRef() const volatile = 0;
virtual nBool Release() const volatile = 0;
};
template <typename T>
class natRefPointer;
template <typename T>
class natWeakRefPointer;
namespace detail_
{
template <typename Dst, typename Src, typename = Dst>
struct static_cast_or_dynamic_cast_helper
{
static Dst Do(Src& src)
{
return dynamic_cast<Dst>(static_cast<Src&&>(src));
}
};
template <typename Dst, typename Src>
struct static_cast_or_dynamic_cast_helper<Dst, Src, decltype(static_cast<Dst>(std::declval<Src>()))>
{
static constexpr Dst Do(Src& src) noexcept
{
return static_cast<Dst>(static_cast<Src&&>(src));
}
};
template <typename Dst, typename Src>
constexpr Dst static_cast_or_dynamic_cast(Src&& src)
{
return static_cast_or_dynamic_cast_helper<Dst, Src>::Do(src);
}
template <typename Base = natRefObj>
class RefCountBase
: public Base
{
public:
nBool IsUnique() const volatile noexcept
{
return GetRefCount() == 1;
}
virtual size_t GetRefCount() const volatile noexcept
{
return m_RefCount.load(std::memory_order_relaxed);
}
virtual nBool TryAddRef() const volatile
{
auto oldValue = m_RefCount.load(std::memory_order_relaxed);
assert(static_cast<std::ptrdiff_t>(oldValue) >= 0);
do
{
if (oldValue == 0)
{
return false;
}
} while (!m_RefCount.compare_exchange_strong(oldValue, oldValue + 1, std::memory_order_relaxed, std::memory_order_relaxed));
return true;
}
virtual void AddRef() const volatile
{
assert(static_cast<std::ptrdiff_t>(m_RefCount.load(std::memory_order_relaxed)) > 0);
m_RefCount.fetch_add(1, std::memory_order_relaxed);
}
virtual nBool Release() const volatile
{
assert(static_cast<std::ptrdiff_t>(m_RefCount.load(std::memory_order_relaxed)) > 0);
return m_RefCount.fetch_sub(1, std::memory_order_relaxed) == 1;
}
protected:
constexpr RefCountBase() noexcept
: m_RefCount(1)
{
}
constexpr RefCountBase(RefCountBase const&) noexcept
: RefCountBase()
{
}
RefCountBase& operator=(RefCountBase const&) noexcept
{
return *this;
}
~RefCountBase()
{
assert(RefCountBase::GetRefCount() <= 1);
}
private:
mutable std::atomic<size_t> m_RefCount;
};
template <typename Owner>
class WeakRefView final
: public RefCountBase<natRefObj>
{
public:
constexpr explicit WeakRefView(std::add_pointer_t<Owner> owner) noexcept
: m_Mutex{}, m_Owner{ owner }
{
}
nBool IsOwnerAlive() const
{
const std::lock_guard<std::mutex> lock{ m_Mutex };
const auto owner = m_Owner;
return owner && static_cast<const volatile RefCountBase*>(owner)->GetRefCount() > 0;
}
void ClearOwner()
{
const std::lock_guard<std::mutex> lock{ m_Mutex };
m_Owner = nullptr;
}
template <typename T>
natRefPointer<T> LockOwner() const
{
const std::lock_guard<std::mutex> lock{ m_Mutex };
const auto other = static_cast_or_dynamic_cast<std::add_pointer_t<T>>(m_Owner);
if (!other)
{
return {};
}
if (!static_cast<std::add_cv_t<decltype(m_Owner)>>(m_Owner)->TryAddRef())
{
return {};
}
return { other };
}
private:
mutable std::mutex m_Mutex;
std::add_pointer_t<Owner> m_Owner;
};
}
////////////////////////////////////////////////////////////////////////////////
/// @brief 引用计数实现
/// @note 使用模板防止菱形继承
////////////////////////////////////////////////////////////////////////////////
template <typename T, typename Deleter = std::default_delete<T>>
class natRefObjImpl
: public detail_::RefCountBase<T>
{
static_assert(std::is_base_of<natRefObj, T>::value, "T should inherit from natRefObj.");
template <typename T_>
friend class natWeakRefPointer;
typedef detail_::RefCountBase<T> Base;
public:
typedef Deleter SelfDeleter;
typedef detail_::WeakRefView<natRefObjImpl> WeakRefView;
constexpr natRefObjImpl() noexcept
: m_View{ nullptr }
{
#ifdef TraceRefObj
OutputDebugString(natUtil::FormatString("Type %s created at (%p)\n"_nv, nStringView{ typeid(*this).name() }, this).c_str());
#endif
}
constexpr natRefObjImpl(natRefObjImpl const&) noexcept
: m_View{ nullptr }
{
}
natRefObjImpl& operator=(natRefObjImpl const&) noexcept
{
return *this;
}
virtual ~natRefObjImpl()
{
#ifdef TraceRefObj
OutputDebugString(natUtil::FormatString("Type %s destroyed at (%p)\n"_nv, nStringView{ typeid(*this).name() }, this).c_str());
#endif
const auto view = m_View.load(std::memory_order_consume);
if (view)
{
if (static_cast<const volatile detail_::RefCountBase<natRefObj>*>(view)->Release())
{
delete view;
}
else
{
view->ClearOwner();
}
}
}
nBool Release() const volatile override
{
const auto result = Base::Release();
if (result)
{
SelfDeleter{}(const_cast<natRefObjImpl*>(this));
}
return result;
}
template <typename U>
natRefPointer<U> ForkRef() noexcept
{
return forkRefImpl<U>(this);
}
template <typename U>
natRefPointer<const U> ForkRef() const noexcept
{
return forkRefImpl<const U>(this);
}
template <typename U>
natRefPointer<volatile U> ForkRef() volatile noexcept
{
return forkRefImpl<volatile U>(this);
}
template <typename U>
natRefPointer<const volatile U> ForkRef() const volatile noexcept
{
return forkRefImpl<const volatile U>(this);
}
template <typename U>
natWeakRefPointer<U> ForkWeakRef() noexcept
{
return forkWeakRefImpl<U>(this);
}
template <typename U>
natWeakRefPointer<const U> ForkWeakRef() const noexcept
{
return forkWeakRefImpl<const U>(this);
}
template <typename U>
natWeakRefPointer<volatile U> ForkWeakRef() volatile noexcept
{
return forkWeakRefImpl<volatile U>(this);
}
template <typename U>
natWeakRefPointer<const volatile U> ForkWeakRef() const volatile noexcept
{
return forkWeakRefImpl<const volatile U>(this);
}
private:
template <typename CVU, typename CVT>
static natRefPointer<CVU> forkRefImpl(CVT* pThis)
{
const auto other = detail_::static_cast_or_dynamic_cast<CVU*>(pThis);
if (!other)
{
return {};
}
return natRefPointer<CVU>{ other };
}
template <typename CVU, typename CVT>
static natWeakRefPointer<CVU> forkWeakRefImpl(CVT* pThis)
{
const auto other = detail_::static_cast_or_dynamic_cast<CVU*>(pThis);
if (!other)
{
return {};
}
return natWeakRefPointer<CVU>{ other };
}
WeakRefView* createWeakRefView() const volatile
{
auto view = m_View.load(std::memory_order_consume);
if (!view)
{
const auto newView = new WeakRefView(const_cast<natRefObjImpl*>(this));
if (m_View.compare_exchange_strong(view, newView, std::memory_order_release, std::memory_order_consume))
{
view = newView;
}
else
{
delete newView;
}
}
return view;
}
mutable std::atomic<WeakRefView*> m_View;
};
////////////////////////////////////////////////////////////////////////////////
/// @brief 强引用指针实现
/// @note 仅能用于引用计数对象
////////////////////////////////////////////////////////////////////////////////
template <typename T>
class natRefPointer final
{
public:
constexpr natRefPointer(std::nullptr_t = nullptr) noexcept
: m_pPointer(nullptr)
{
}
constexpr explicit natRefPointer(T* ptr) noexcept
: m_pPointer(ptr)
{
if (m_pPointer)
{
static_cast<const volatile natRefObj*>(m_pPointer)->AddRef();
}
}
constexpr natRefPointer(natRefPointer const& other) noexcept
: m_pPointer(other.m_pPointer)
{
if (m_pPointer)
{
m_pPointer->AddRef();
}
}
constexpr natRefPointer(natRefPointer && other) noexcept
: m_pPointer(other.m_pPointer)
{
other.m_pPointer = nullptr;
}
~natRefPointer()
{
SafeRelease(m_pPointer);
}
void Reset(std::nullptr_t = nullptr) noexcept
{
natRefPointer{}.swap(*this);
}
void Reset(T* ptr) noexcept
{
natRefPointer{ ptr }.swap(*this);
}
template <typename U>
void Reset(natRefPointer<U> const& other) noexcept
{
natRefPointer{ other }.swap(*this);
}
template <typename U>
void Reset(natRefPointer<U> && other) noexcept
{
natRefPointer{ other }.swap(*this);
}
void Reset(natRefPointer const& other) noexcept
{
natRefPointer{ other }.swap(*this);
}
void Reset(natRefPointer && other) noexcept
{
natRefPointer{ std::move(other) }.swap(*this);
}
template <typename U>
nBool operator==(natRefPointer<U> const& other) const noexcept
{
return m_pPointer == other.Get();
}
template <typename U>
nBool operator!=(natRefPointer<U> const& other) const noexcept
{
return m_pPointer != other.Get();
}
template <typename U>
nBool operator<(natRefPointer<U> const& other) const noexcept
{
return m_pPointer < other.Get();
}
template <typename U>
nBool operator>(natRefPointer<U> const& other) const noexcept
{
return m_pPointer > other.Get();
}
template <typename U>
nBool operator<=(natRefPointer<U> const& other) const noexcept
{
return m_pPointer <= other.Get();
}
template <typename U>
nBool operator>=(natRefPointer<U> const& other) const noexcept
{
return m_pPointer >= other.Get();
}
natRefPointer& operator=(natRefPointer const& other)&
{
return Reset(other.m_pPointer);
}
natRefPointer& operator=(natRefPointer && other)& noexcept
{
std::swap(m_pPointer, other.m_pPointer);
return *this;
}
natRefPointer& operator=(std::nullptr_t)
{
SafeRelease(m_pPointer);
return *this;
}
T* operator->() const
{
assert(m_pPointer && "m_pPointer is nullptr.");
return m_pPointer;
}
T& operator*() const
{
assert(m_pPointer && "m_pPointer is nullptr.");
return *m_pPointer;
}
T** operator&()
{
Reset(nullptr);
return &m_pPointer;
}
operator T*() const
{
return m_pPointer;
}
T* Get() const
{
return m_pPointer;
}
size_t GetRefCount() const noexcept
{
const auto ptr = m_pPointer;
if (!ptr)
{
return 0;
}
return static_cast<const volatile natRefObj*>(ptr)->GetRefCount();
}
void swap(natRefPointer& other) noexcept
{
const auto ptr = m_pPointer;
m_pPointer = other.m_pPointer;
other.m_pPointer = ptr;
}
template <typename P>
operator natRefPointer<P>() const;
private:
T* m_pPointer;
};
template <typename T, typename ...Arg>
NATINLINE natRefPointer<T> make_ref(Arg &&... args)
{
T* pRefObj = new T(std::forward<Arg>(args)...);
natRefPointer<T> Ret(pRefObj);
SafeRelease(pRefObj);
return std::move(Ret);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief 弱引用指针实现
/// @note 仅能用于引用计数对象
////////////////////////////////////////////////////////////////////////////////
template <typename T>
class natWeakRefPointer
{
template <typename>
friend class natWeakRefPointer;
typedef typename T::WeakRefView WeakRefView;
static WeakRefView* GetViewFrom(const volatile T* item)
{
if (!item)
{
return nullptr;
}
const auto view = item->createWeakRefView();
view->AddRef();
return view;
}
public:
typedef std::add_pointer_t<T> pointer;
constexpr natWeakRefPointer(std::nullptr_t = nullptr) noexcept
: m_View{}
{
}
explicit natWeakRefPointer(pointer ptr)
: natWeakRefPointer(GetViewFrom(ptr))
{
}
template <typename U, std::enable_if_t<std::is_convertible<typename natWeakRefPointer<U>::pointer, pointer>::value, int> = 0>
natWeakRefPointer(natRefPointer<U> const& other) noexcept
: natWeakRefPointer(GetViewFrom(other.Get()))
{
}
template <typename U, std::enable_if_t<std::is_convertible<typename natWeakRefPointer<U>::pointer, pointer>::value, int> = 0>
natWeakRefPointer(natWeakRefPointer<U> const& other) noexcept
:natWeakRefPointer(other.fork())
{
}
template <typename U, std::enable_if_t<std::is_convertible<typename natWeakRefPointer<U>::pointer, pointer>::value, int> = 0>
natWeakRefPointer(natWeakRefPointer<U> && other) noexcept
: natWeakRefPointer(other.release())
{
}
natWeakRefPointer(natWeakRefPointer const& other) noexcept
: natWeakRefPointer(other.fork())
{
}
natWeakRefPointer(natWeakRefPointer && other) noexcept
: natWeakRefPointer(other.release())
{
}
~natWeakRefPointer()
{
SafeRelease(m_View);
}
natWeakRefPointer& operator=(natWeakRefPointer const& other) noexcept
{
Reset(other);
return *this;
}
natWeakRefPointer& operator=(natWeakRefPointer && other) noexcept
{
Reset(std::move(other));
return *this;
}
nBool IsExpired() const noexcept
{
const auto view = m_View;
if (!view)
{
return true;
}
return !view->IsOwnerAlive();
}
size_t WeakCount() const noexcept
{
const auto view = m_View;
if (!view)
{
return 0;
}
return view->GetRefCount() - 1; // 本体自带1个对WeakRefView的引用
}
template <typename U = T>
natRefPointer<U> Lock() const noexcept
{
const auto view = m_View;
if (!view)
{
return {};
}
return view->template LockOwner<U>();
}
void Reset(std::nullptr_t = nullptr) noexcept
{
natWeakRefPointer{}.swap(*this);
}
void Reset(pointer ptr) noexcept
{
natWeakRefPointer{ ptr }.swap(*this);
}
template <typename U>
void Reset(natRefPointer<U> const& other) noexcept
{
natWeakRefPointer{ other }.swap(*this);
}
template <typename U>
void Reset(natWeakRefPointer<U> const& other) noexcept
{
natWeakRefPointer{ other }.swap(*this);
}
template <typename U>
void Reset(natWeakRefPointer<U> && other) noexcept
{
natWeakRefPointer{ std::move(other) }.swap(*this);
}
void Reset(natWeakRefPointer const& other) noexcept
{
natWeakRefPointer{ other }.swap(*this);
}
void Reset(natWeakRefPointer && other) noexcept
{
natWeakRefPointer{ std::move(other) }.swap(*this);
}
void swap(natWeakRefPointer& other) noexcept
{
const auto view = m_View;
m_View = other.m_View;
other.m_View = view;
}
template <typename U>
nBool operator==(natWeakRefPointer<U> const& other) const noexcept
{
return m_View == other.m_View;
}
template <typename U>
nBool operator!=(natWeakRefPointer<U> const& other) const noexcept
{
return m_View != other.m_View;
}
template <typename U>
nBool operator<(natWeakRefPointer<U> const& other) const noexcept
{
return m_View < other.m_View;
}
template <typename U>
nBool operator>(natWeakRefPointer<U> const& other) const noexcept
{
return m_View > other.m_View;
}
template <typename U>
nBool operator<=(natWeakRefPointer<U> const& other) const noexcept
{
return m_View <= other.m_View;
}
template <typename U>
nBool operator>=(natWeakRefPointer<U> const& other) const noexcept
{
return m_View >= other.m_View;
}
// Workaround
size_t GetHashCode() const noexcept
{
return std::hash<WeakRefView*>{}(m_View);
}
private:
WeakRefView* m_View;
constexpr explicit natWeakRefPointer(WeakRefView* view) noexcept
: m_View{ view }
{
}
WeakRefView* fork() const
{
const auto view = m_View;
if (view)
{
static_cast<const volatile natRefObj*>(m_View)->AddRef();
}
return view;
}
WeakRefView* release() noexcept
{
return std::exchange(m_View, nullptr);
}
};
}
template <typename T>
NATINLINE void swap(NatsuLib::natRefPointer<T>& lhs, NatsuLib::natRefPointer<T>& rhs) noexcept
{
lhs.swap(rhs);
}
template <typename T>
NATINLINE void swap(NatsuLib::natWeakRefPointer<T>& lhs, NatsuLib::natWeakRefPointer<T>& rhs) noexcept
{
lhs.swap(rhs);
}
namespace std
{
template <typename T>
struct hash<NatsuLib::natRefPointer<T>>
{
size_t operator()(NatsuLib::natRefPointer<T> const& ptr) const
{
return hash<T*>{}(ptr.Get());
}
};
template <typename T>
struct hash<NatsuLib::natWeakRefPointer<T>>
{
size_t operator()(NatsuLib::natWeakRefPointer<T> const& ptr) const
{
return ptr.GetHashCode();
}
};
}
#include "natException.h"
namespace NatsuLib
{
template <typename T>
template <typename P>
natRefPointer<T>::operator natRefPointer<P>() const
{
if (!m_pPointer)
{
return {};
}
const auto pTarget = detail_::static_cast_or_dynamic_cast<P*>(m_pPointer);
if (pTarget)
{
return natRefPointer<P> { pTarget };
}
nat_Throw(natException, "Type P cannot be converted to T."_nv);
}
}
| [
"jxhzq1996@126.com"
] | jxhzq1996@126.com |
30977cb869710bf854322d442327ad7574497069 | d1414cc6d1993cfef3d3e217de874c9e614ccce8 | /Calculator/symbol_table.h | 0e36d1f0043f0f426848fa4cef9c95730f19bf6a | [] | no_license | hanchaoqi/Calculator | e726516e48410a61b0888be97fa2c7525b797dd8 | 04ead9ede934e735b2bd260134ede0fa614cb6aa | refs/heads/master | 2021-01-09T21:43:39.192994 | 2015-11-22T09:12:58 | 2015-11-22T09:12:58 | 46,160,374 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 393 | h | #include "token.h"
class Variable{
public:
string name;
char flag;
double value;
Variable(string n, double v, char f) :name(n), value(v), flag(f){}
};
class Symbol_table{
public:
Symbol_table();
double get(string name);
void set(string name, double value);
bool is_declared(string name);
double declare(string name, double value, char flag);
private:
vector<Variable> var_table;
}; | [
"hanchao_qi@qq.com"
] | hanchao_qi@qq.com |
8560953a78118a5e0ade66057c3afd4c814184a9 | bfb1c7ff905065f0e3914b66c9a932bc811640a5 | /.svn/pristine/85/8560953a78118a5e0ade66057c3afd4c814184a9.svn-base | 13165ea899a6dccecc3ac25e18f7d76742847978 | [] | no_license | djskual/savegame-manager-gx | 1ddcdcfcdaf7a4043b7fd756136ec8cca0fbf5f3 | ae3cb59cb5bbae91bf65d48cb61961ed49d896d3 | refs/heads/master | 2020-06-03T05:11:20.735987 | 2015-04-14T13:16:49 | 2015-04-14T13:16:49 | 33,944,551 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 18,072 | /****************************************************************************
* Copyright (C) 2011
* by Dj_Skual
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any
* damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any
* purpose, including commercial applications, and to alter it and
* redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you
* must not claim that you wrote the original software. If you use
* this software in a product, an acknowledgment in the product
* documentation would be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and
* must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*
* filecustombrowser.cpp
*
* for SaveGame Manager GX 2011
***************************************************************************/
#include <algorithm>
#include <gccore.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wiiuse/wpad.h>
#include <malloc.h>
#include "filecustombrowser.h"
#include "CCustomList.hpp"
#include "../DeviceControls/DeviceHandler.hpp"
#include "../Prompts/PromptWindows.h"
#include "../Prompts/SelectBrowser.h"
#include "../Language/gettext.h"
#include "../FileOperations/fileops.h"
#include "../Settings/CSettings.h"
#include "../Saves/SaveTools.h"
#include "../Saves/DataBin/DataBinTools.h"
#include "../Text/wstring.hpp"
#include "../Tools/StringTools.h"
#include "../XML/GameTDB.hpp"
#include "../menu.h"
/****************************************************************************
* FileCustomBrowser Class to parse directories on the fly
***************************************************************************/
FileCustomBrowser::FileCustomBrowser()
:Browser()
{
Filter = 0;
browserList.clear();
gettingList = false;
listChanged = false;
dir = NULL;
FilterLang = false;
FilterTheme = false;
FilterFont = false;
FilterSound = false;
//!Reset and prepare browser
ResetBrowser();
}
/****************************************************************************
* Destructor
***************************************************************************/
FileCustomBrowser::~FileCustomBrowser()
{
for(u32 i = 0; i < browserList.size(); ++i)
delete browserList.at(i);
browserList.clear();
}
void FileCustomBrowser::AddEntry()
{
CustomEntryStruct * newEntry = new CustomEntryStruct;
newEntry->filename = " ";
newEntry->displayname = " ";
newEntry->isdir = false;
newEntry->ismii = false;
newEntry->issave = false;
newEntry->isdatabin = false;
newEntry->isNotInstalled = false;
browserList.push_back(newEntry);
}
/****************************************************************************
* BrowsePath
* Displays a list of files on the selected path
***************************************************************************/
int FileCustomBrowser::BrowsePath(std::string path)
{
if(path.empty())
return -1;
BrowserRootDir.assign(path);
BrowserRootDir.erase(BrowserRootDir.find_first_of("/")+1);
BrowserDir.assign(path);
while(BrowserDir[BrowserDir.size()-1] == '/')
BrowserDir.erase(BrowserDir.size()-1, 1);
BrowserDir.erase(0, BrowserDir.find_first_of("/")+1);
ParseDirectory(); //! Parse root directory
return browserList.size();
}
/****************************************************************************
* BrowseDevice
* Displays a list of files on the selected device
***************************************************************************/
int FileCustomBrowser::BrowseDevice(int device)
{
if(device < 0 || device >= MAXDEVICES)
return -1;
BrowserDir.clear();
BrowserRootDir.assign(fmt("%s:/", DeviceName[device]));
ParseDirectory(); //! Parse root directory
return browserList.size();
}
/****************************************************************************
* Enter the current selected directory
***************************************************************************/
int FileCustomBrowser::EnterSelDir()
{
if((browserList.at(BrowserSelIndex)->filename).empty())
return -1;
int dirlength = BrowserDir.size();
int filelength = (browserList.at(BrowserSelIndex)->filename).size();
if((dirlength+filelength+1) > MAXPATHLEN)
return -1;
if(dirlength == 0)
BrowserDir.assign(browserList.at(BrowserSelIndex)->filename);
else
BrowserDir.assign(fmt("%s/%s", BrowserDir.c_str(), (browserList.at(BrowserSelIndex)->filename).c_str()));
listChanged = true;
return 1;
}
/****************************************************************************
* Leave the current directory
***************************************************************************/
int FileCustomBrowser::LeaveCurDir()
{
int pos = BrowserDir.find_last_of("/");
if(pos != (int) std::string::npos)
BrowserDir.erase(pos);
else
BrowserDir.clear();
listChanged = true;
return 1;
}
/****************************************************************************
* UpdateDirName()
* Update curent directory name for file browser
***************************************************************************/
int FileCustomBrowser::UpdateDirName()
{
if((browserList.at(BrowserSelIndex)->filename).empty())
return -1;
if(!(browserList.at(BrowserSelIndex)->filename).compare(".."))
{
return LeaveCurDir();
}
return EnterSelDir();
}
/****************************************************************************
* SetPageIndex
* not inline for later mutex purpose
***************************************************************************/
void FileCustomBrowser::SetPageIndex(int ind)
{
BrowserPageIndex = ind;
}
/****************************************************************************
* SetSelectedIndex
* not inline for later mutex purpose
***************************************************************************/
void FileCustomBrowser::SetSelectedIndex(int ind)
{
BrowserSelIndex = ind;
}
/****************************************************************************
* Get the current full path
***************************************************************************/
std::string FileCustomBrowser::GetCurrentPath()
{
currentpath.assign(BrowserRootDir);
currentpath += BrowserDir;
return currentpath;
}
/****************************************************************************
* Get the current full path with filename
***************************************************************************/
std::string FileCustomBrowser::GetCurrentSelectedFilepath()
{
currentpath.clear();
if((browserList.at(BrowserSelIndex)->filename).size())
{
currentpath.assign(BrowserRootDir);
currentpath += BrowserDir;
currentpath += "/";
currentpath += browserList.at(BrowserSelIndex)->filename;
}
return currentpath;
}
/****************************************************************************
* Get the current item structure
***************************************************************************/
ItemStruct * FileCustomBrowser::GetItemStruct(int pos)
{
if(pos < 0 || pos >= (int) browserList.size() || (browserList.at(pos)->filename).empty())
return NULL;
ItemStruct * Item = new ItemStruct;
memset(Item, 0, sizeof(ItemStruct));
Item->itempath = (char *) malloc(BrowserRootDir.size()+BrowserDir.size()+(browserList.at(pos)->filename).size()+2);
if(Item->itempath)
sprintf(Item->itempath, "%s%s/%s", BrowserRootDir.c_str(), BrowserDir.c_str(), (browserList.at(pos)->filename).c_str());
Item->isdir = browserList.at(pos)->isdir;
Item->itemindex = pos;
return Item;
}
/****************************************************************************
* ResetBrowser()
* Clears the file browser memory, and allocates one initial entry
***************************************************************************/
void FileCustomBrowser::ResetBrowser()
{
for(u32 i = 0; i < browserList.size(); ++i)
delete browserList.at(i);
browserList.clear();
BrowserSelIndex = 0;
BrowserPageIndex = 0;
}
/****************************************************************************
* FileSortCallback
*
* Quick sort callback to sort file entries with the following order:
* .
* ..
* <dirs>
* <files>
***************************************************************************/
static bool FileSortCallback(const CustomEntryStruct *f1, const CustomEntryStruct *f2)
{
//! Special case for implicit directories
if(((CustomEntryStruct *)f1)->displayname[0] == '.' || ((CustomEntryStruct *)f2)->displayname[0] == '.')
{
if(((CustomEntryStruct *)f1)->displayname.compare(".") == 0) { return true; }
if(((CustomEntryStruct *)f2)->displayname.compare(".") == 0) { return false; }
if(((CustomEntryStruct *)f1)->displayname.compare("..") == 0) { return true; }
if(((CustomEntryStruct *)f2)->displayname.compare("..") == 0) { return false; }
}
//! If one is a file and one is a directory the directory is first
if(((CustomEntryStruct *)f1)->isdir && !(((CustomEntryStruct *)f2)->isdir)) return true;
if(!(((CustomEntryStruct *)f1)->isdir) && ((CustomEntryStruct *)f2)->isdir) return false;
return (stricmp(((CustomEntryStruct *)f1)->displayname.c_str(), ((CustomEntryStruct *)f2)->displayname.c_str()) < 0);
}
/****************************************************************************
* SetFilterCustom()
* Set filters for custum browsing
***************************************************************************/
void FileCustomBrowser::SetFilterCustom(short Type)
{
if(Type == LANGBROWSER)
FilterLang = true;
if(Type == THEMEPATHBROWSER)
FilterTheme = true;
if(Type == FONTBROWSER)
FilterFont = true;
if(Type == SOUNDBROWSER)
FilterSound = true;
}
/***************************************************************************
* Get Mii Name
**************************************************************************/
std::string FileCustomBrowser::GetMiiDeviceName(const char * miipath)
{
std::string name;
FILE *fp = fopen(miipath,"rb");
if(fp == NULL)
return "";
fseek(fp , 2, SEEK_SET);
u16* namedata = (u16*)memalign(32, 20);
memset(namedata, 0, sizeof(namedata));
fread(namedata,1,20,fp);
fclose(fp);
wchar_t wname[20];
memset(wname, 0, 20);
u32 i = 0;
for (i = 0; i < 20; i++){
wname[i] = (wchar_t)namedata[i];
}
free(namedata);
namedata = NULL;
wString *ws_name = new wString(wname);
name.assign(ws_name->toUTF8());
delete ws_name;
return name;
}
/****************************************************************************
* ParseDirEntries
*
* Update current directory and set new entry list and entrynum
***************************************************************************/
void FileCustomBrowser::ParseDirEntries(bool ResetPosition)
{
if(!dir)
return;
char filename[MAXPATHLEN];
struct stat filestat;
struct dirent * dirent = NULL;
int i = 0;
std::string Path = currentpath;
if(Path[Path.size()-1] == '/')
Path.erase(Path.size()-1, 1);
while ((dirent = readdir(dir)) != 0)
{
snprintf(filename, sizeof(filename), "%s/%s", Path.c_str(), dirent->d_name);
if(stat(filename, &filestat) != 0)
continue;
snprintf(filename, sizeof(filename), dirent->d_name);
if(strcmp(filename,".") == 0)
continue;
//! Hide System Files
if(filename[0] == '.' && strcmp(filename,"..") != 0)
continue;
else if(filename[0] == '$')
continue;
else if(strcasecmp(filename,"thumb.db") == 0)
continue;
//! Filters
if((Filter & FILTER_DIRECTORIES) && (filestat.st_mode & S_IFDIR))
continue;
if((Filter & FILTER_FILES) && !(filestat.st_mode & S_IFDIR))
continue;
char *fileext = strrchr(filename, '.');
if (FilterLang && !(filestat.st_mode & S_IFDIR) && (Settings.FileExtensions.CompareLanguageFiles(fileext) != 0))
continue;
if (FilterFont && !(filestat.st_mode & S_IFDIR) && (Settings.FileExtensions.CompareFont(fileext) != 0))
continue;
if (FilterSound && !(filestat.st_mode & S_IFDIR) && (Settings.FileExtensions.CompareAudio(fileext) != 0))
continue;
if (FilterTheme && (filestat.st_mode & S_IFDIR) && (strcasecmp(filename,"tmp") == 0))
continue;
if(i >= (int)browserList.size())
AddEntry();
(browserList.at(i)->filename).assign(filename);
(browserList.at(i)->displayname).assign(filename);
browserList.at(i)->ismii = (!(filestat.st_mode & S_IFDIR) && !(Settings.FileExtensions.CompareMiiFiles(fileext))) ? true : false;
browserList.at(i)->issave = false;
browserList.at(i)->isNotInstalled = false;
browserList.at(i)->isdir = (filestat.st_mode & S_IFDIR) ? true : false;
//! Check if dir is a decompressed save
if( browserList.at(i)->isdir == true &&
browserList.at(i)->filename.size() == 16)
{
char savepath[MAXPATHLEN];
strcpy(savepath, fmt("%s%s/%s", BrowserRootDir.c_str(), BrowserDir.c_str(), (browserList.at(i)->filename).c_str()));
//! Get save infos
if( CheckSave(savepath) == true )
{
//! flag this as a save
browserList.at(i)->isdir = false;
browserList.at(i)->issave = true;
//! Check if the save is already installed
browserList.at(i)->isNotInstalled = !CheckIfInstalled(StrToHex64(browserList.at(i)->filename.c_str()));
//! Get name of the save
(browserList.at(i)->displayname).assign(GetDeviceName(savepath));
}
}
//! Check if .bin is a compressed save
else if (!browserList.at(i)->isdir &&
!Settings.FileExtensions.CompareBinaryFiles(fileext))
{
char databinpath[MAXPATHLEN];
strcpy(databinpath, fmt("%s%s/%s", BrowserRootDir.c_str(), BrowserDir.c_str(), (browserList.at(i)->filename).c_str()));
SaveInfos * infos = GetSaveInfos(databinpath);
if(infos)
{
browserList.at(i)->isdatabin = true;
browserList.at(i)->displayname.assign(infos->name);
browserList.at(i)->isNotInstalled = !CheckIfInstalled(infos->tid);
if(Settings.GameTDBTitles)
{
std::string Title;
std::string Filepath = Settings.GameTDBPath;
if(Filepath[Filepath.size()-1] != '/')
Filepath += '/';
Filepath += "wiitdb.xml";
GameTDB * XML_DB = new GameTDB(Filepath.c_str());
XML_DB->SetLanguageCode(Settings.GameTDBLanguageCode);
if(XML_DB->GetTitle(infos->ID, Title))
browserList.at(i)->displayname.assign(Title);
delete XML_DB;
}
delete infos;
}
}
//! Get Mii infos
if(browserList.at(i)->ismii == true)
{
char miipath[MAXPATHLEN];
strcpy(miipath, fmt("%s%s/%s", BrowserRootDir.c_str(), BrowserDir.c_str(), (browserList.at(i)->filename).c_str()));
(browserList.at(i)->displayname).assign(GetMiiDeviceName(miipath));
}
i++;
}
closedir(dir); //! close directory
dir = NULL;
if(!browserList.empty())
{
for(u32 cnt = 0; cnt < browserList.size(); cnt++)
{
CustomList.SetFile (cnt,
browserList.at(cnt)->filename,
browserList.at(cnt)->displayname,
browserList.at(cnt)->isdir,
browserList.at(cnt)->ismii,
browserList.at(cnt)->issave,
browserList.at(cnt)->isdatabin,
browserList.at(cnt)->isNotInstalled);
}
CustomList.LoadTitlesFromGameTDB();
}
u32 currPageIndex = BrowserPageIndex;
u32 currSelIndex = BrowserSelIndex;
ResetBrowser();
if(!ResetPosition)
{
BrowserPageIndex = currPageIndex;
BrowserSelIndex = currSelIndex;
}
}
/***************************************************************************
* Refresh Browser
**************************************************************************/
void FileCustomBrowser::Refresh()
{
ParseDirectory(false);
}
/***************************************************************************
* Browse subdirectories
**************************************************************************/
int FileCustomBrowser::ParseDirectory(bool ResetPosition)
{
gettingList = true;
ResetBrowser();
std::string fulldir(BrowserRootDir);
fulldir += BrowserDir;
//! open the directory
dir = opendir(fulldir.c_str());
if(dir == NULL)
{
//! if we can't open the dir, try opening the root dir
BrowserDir.clear();
fulldir = BrowserRootDir;
dir = opendir(fulldir.c_str());
if(dir == NULL)
return -1;
}
currentpath = fulldir;
ParseDirEntries(ResetPosition);
FilterList();
gettingList = false;
return browserList.size();
}
void FileCustomBrowser::FilterList()
{
wString oldFilter(CustomList.GetCurrentFilter());
CustomList.FilterList(oldFilter.c_str());
for(int i=0; i < CustomList.GetFilteredCount(); i++)
{
if(i >= (int)browserList.size())
AddEntry();
(browserList.at(i)->filename).assign(CustomList.GetFilename(i));
(browserList.at(i)->displayname).assign(CustomList.GetDisplayname(i));
browserList.at(i)->isdir = CustomList.GetIsDir(i);
browserList.at(i)->ismii = CustomList.GetIsMii(i);
browserList.at(i)->issave = CustomList.GetIsSave(i);
browserList.at(i)->isdatabin = CustomList.GetIsDataBin(i);
browserList.at(i)->isNotInstalled = CustomList.GetIsNotInstalled(i);
}
CustomList.ResetFiltered();
std::sort(browserList.begin(), browserList.end(), FileSortCallback);
for(u32 cnt = 0; cnt < browserList.size(); cnt++)
{
CustomList.SetFilteredFile(cnt,
browserList.at(cnt)->filename,
browserList.at(cnt)->displayname,
browserList.at(cnt)->isdir,
browserList.at(cnt)->ismii,
browserList.at(cnt)->issave,
browserList.at(cnt)->isdatabin,
browserList.at(cnt)->isNotInstalled);
}
}
/****************************************************************************
* ChangeDirectory
*
* Update current directory and set new entry list if directory has changed
***************************************************************************/
int FileCustomBrowser::ChangeDirectory()
{
if(!UpdateDirName())
return -1;
ParseDirectory();
return browserList.size();
}
| [
"dj_skual@hotmail.com"
] | dj_skual@hotmail.com | |
6bfa37fb1f60569518ee21356db2a528d5a212ed | b63d8ddd336447845615e11afeb0172a6269a4fa | /plugins/api/src/data_object_finalize.cpp | fa2d839925f506b10af8ef27398011be158875f1 | [
"BSD-3-Clause"
] | permissive | louislau86/irods | ea7e21ce49e2f4bc9882ea8ae6eb35e32c15a67f | ee116cbc7cf90f6b0960e596b0b7ebf97877393b | refs/heads/master | 2023-02-12T07:44:27.311654 | 2021-01-14T20:49:32 | 2021-01-15T01:43:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,330 | cpp | #include "api_plugin_number.h"
#include "irods_configuration_keywords.hpp"
#include "rodsDef.h"
#include "rcConnect.h"
#include "rodsErrorTable.h"
#include "rodsPackInstruct.h"
#include "client_api_whitelist.hpp"
#include "apiHandler.hpp"
#include <functional>
#include <stdexcept>
#ifdef RODS_SERVER
//
// Server-side Implementation
//
#include "data_object_finalize.h"
#include "catalog.hpp"
#include "catalog_utilities.hpp"
#include "irods_exception.hpp"
#include "irods_get_full_path_for_config_file.hpp"
#include "irods_get_l1desc.hpp"
#include "irods_logger.hpp"
#include "irods_query.hpp"
#include "irods_re_serialization.hpp"
#include "irods_rs_comm_query.hpp"
#include "irods_server_api_call.hpp"
#include "irods_stacktrace.hpp"
#include "miscServerFunct.hpp"
#include "objDesc.hpp"
#include "rodsConnect.h"
#define IRODS_FILESYSTEM_ENABLE_SERVER_SIDE_API
#include "filesystem.hpp"
#include "json.hpp"
#include "fmt/format.h"
#include "nanodbc/nanodbc.h"
#include <cstdlib>
#include <string>
#include <string_view>
#include <tuple>
#include <chrono>
#include <system_error>
namespace {
// clang-format off
namespace fs = irods::experimental::filesystem;
namespace ic = irods::experimental::catalog;
using log = irods::experimental::log;
using json = nlohmann::json;
using operation = std::function<int(rsComm_t*, bytesBuf_t*, bytesBuf_t**)>;
// clang-format on
const auto& cmap = ic::data_objects::column_mapping_operators;
auto make_error_object(const std::string& _error_msg) -> json
{
return json{{"error_message", _error_msg}};
} // make_error_object
auto to_bytes_buffer(const std::string& _s) -> bytesBuf_t*
{
constexpr auto allocate = [](const auto bytes) noexcept
{
return std::memset(std::malloc(bytes), 0, bytes);
};
const auto buf_size = _s.length() + 1;
auto* buf = static_cast<char*>(allocate(sizeof(char) * buf_size));
std::strncpy(buf, _s.c_str(), _s.length());
auto* bbp = static_cast<bytesBuf_t*>(allocate(sizeof(bytesBuf_t)));
bbp->len = buf_size;
bbp->buf = buf;
return bbp;
} // to_bytes_buffer
auto call_data_object_finalize(
irods::api_entry* _api,
rsComm_t* _comm,
bytesBuf_t* _input,
bytesBuf_t** _output) -> int
{
return _api->call_handler<bytesBuf_t*, bytesBuf_t**>(_comm, _input, _output);
} // call_data_object_finalize
auto validate_after_values(json& _after) -> void
{
// clang-format off
using clock_type = fs::object_time_type::clock;
using duration_type = fs::object_time_type::duration;
// clang-format on
if (std::string_view{SET_TIME_TO_NOW_KW} == _after.at("modify_ts")) {
const auto now = std::chrono::time_point_cast<duration_type>(clock_type::now());
_after["modify_ts"] = fmt::format("{:011}", now.time_since_epoch().count());
}
} // validate_after_values
auto set_replica_state(
nanodbc::connection& _db_conn,
std::string_view _data_id,
const json& _before,
const json& _after) -> void
{
std::string sql{"update R_DATA_MAIN set"};
for (auto&& c : cmap) {
sql += fmt::format(" {} = ?,", c.first);
}
sql.pop_back();
sql += " where data_id = ? and resc_id = ?";
log::database::debug("statement:[{}]", sql);
nanodbc::statement statement{_db_conn};
prepare(statement, sql);
log::database::debug("before:{}", _before.dump());
log::database::debug("after:{}", _after.dump());
// Reserve the size ahead of time to prevent pointer invalidation.
// Need to store the bind values in a variable which will outlive
// the bind operation scope.
std::vector<ic::bind_type> bind_values;
bind_values.reserve(cmap.size());
// Bind values to the statement.
std::size_t index = 0;
for (auto&& c : cmap) {
const auto& key = c.first;
const auto& bind_fcn = c.second;
ic::bind_parameters bp{statement, index, _after, key, bind_values};
bind_fcn(bp);
index++;
}
const auto data_id = std::stoul(_data_id.data());
log::database::trace("binding data_id:[{}] at [{}]", data_id, index);
statement.bind(index++, &data_id);
const auto resc_id = std::stoul(_before.at("resc_id").get<std::string>());
log::database::trace("binding resc_id:[{}] at [{}]", resc_id, index);
statement.bind(index, &resc_id);
execute(statement);
} // set_replica_state
auto set_data_object_state(
nanodbc::connection& _db_conn,
nanodbc::transaction& _trans,
std::string_view _data_id,
json& _replicas) -> void
{
try {
for (auto&& r : _replicas) {
auto& after = r.at("after");
validate_after_values(after);
set_replica_state(_db_conn, _data_id, r.at("before"), after);
}
log::database::debug("committing transaction");
_trans.commit();
}
catch (const nanodbc::database_error& e) {
THROW(SYS_LIBRARY_ERROR, e.what());
}
catch (const std::exception& e) {
THROW(SYS_INTERNAL_ERR, e.what());
}
} // set_data_object_state
auto rs_data_object_finalize(
rsComm_t* _comm,
bytesBuf_t* _input,
bytesBuf_t** _output) -> int
{
try {
if (!ic::connected_to_catalog_provider(*_comm)) {
log::api::trace("Redirecting request to catalog service provider ...");
auto host_info = ic::redirect_to_catalog_provider(*_comm);
std::string_view json_input(static_cast<const char*>(_input->buf), _input->len);
char* json_output = nullptr;
const auto ec = rc_data_object_finalize(host_info.conn, json_input.data(), &json_output);
*_output = to_bytes_buffer(json_output);
return ec;
}
ic::throw_if_catalog_provider_service_role_is_invalid();
}
catch (const irods::exception& e) {
std::string_view msg = e.what();
log::api::error(msg.data());
*_output = to_bytes_buffer(make_error_object(msg.data()).dump());
return e.code();
}
json input;
try {
input = json::parse(std::string(static_cast<const char*>(_input->buf), _input->len));
log::database::debug("json input:[{}]", input.dump());
}
catch (const json::parse_error& e) {
std::string_view msg = e.what();
log::api::error({{"log_message", "Failed to parse input into JSON"},
{"error_message", msg.data()}});
const auto err_info = make_error_object(msg.data());
*_output = to_bytes_buffer(err_info.dump());
return INPUT_ARG_NOT_WELL_FORMED_ERR;
}
std::string data_id;
json replicas;
try {
data_id = input.at("data_id").get<std::string>();
replicas = input.at("replicas");
}
catch (const json::type_error& e) {
*_output = to_bytes_buffer(make_error_object(e.what()).dump());
return SYS_INVALID_INPUT_PARAM;
}
catch (const std::exception& e) {
*_output = to_bytes_buffer(make_error_object(e.what()).dump());
return SYS_INVALID_INPUT_PARAM;
}
nanodbc::connection db_conn;
try {
std::tie(std::ignore, db_conn) = ic::new_database_connection();
}
catch (const std::exception& e) {
log::database::error(e.what());
return SYS_CONFIG_FILE_ERR;
}
return ic::execute_transaction(db_conn, [&](auto& _trans) -> int
{
try {
set_data_object_state(db_conn, _trans, data_id, replicas);
*_output = to_bytes_buffer("{}");
return 0;
}
catch (const irods::exception& e) {
log::database::error(e.what());
*_output = to_bytes_buffer(make_error_object(e.what()).dump());
return e.code();
}
});
} // rs_data_object_finalize
const operation op = rs_data_object_finalize;
#define CALL_DATA_OBJECT_FINALIZE call_data_object_finalize
} // anonymous namespace
#else // RODS_SERVER
//
// Client-side Implementation
//
namespace {
using operation = std::function<int(rsComm_t*, bytesBuf_t*, bytesBuf_t**)>;
const operation op{};
#define CALL_DATA_OBJECT_FINALIZE nullptr
} // anonymous namespace
#endif // RODS_SERVER
// The plugin factory function must always be defined.
extern "C"
auto plugin_factory(const std::string& _instance_name,
const std::string& _context) -> irods::api_entry*
{
#ifdef RODS_SERVER
irods::client_api_whitelist::instance().add(DATA_OBJECT_FINALIZE_APN);
#endif // RODS_SERVER
// clang-format off
irods::apidef_t def{DATA_OBJECT_FINALIZE_APN, // API number
RODS_API_VERSION, // API version
NO_USER_AUTH, // Client auth
NO_USER_AUTH, // Proxy auth
"BytesBuf_PI", 0, // In PI / bs flag
"BytesBuf_PI", 0, // Out PI / bs flag
op, // Operation
"data_object_finalize", // Operation name
nullptr, // Null clear function
(funcPtr) CALL_DATA_OBJECT_FINALIZE};
// clang-format on
auto* api = new irods::api_entry{def};
api->in_pack_key = "BytesBuf_PI";
api->in_pack_value = BytesBuf_PI;
api->out_pack_key = "BytesBuf_PI";
api->out_pack_value = BytesBuf_PI;
return api;
}
| [
"terrellrussell@gmail.com"
] | terrellrussell@gmail.com |
78ed3a6bf9888b0209156bba2673aebbb60b3fc6 | 2588952b4a4430368da692052a0bb1599824c2c3 | /QPrint/statusbar.h | 7b5b4c45dcd36c2d6b40a884a41a2fa9a5bce2ce | [] | no_license | yasriady/Queue | 310202923d51781694aa17c0af7f7e0fd355b482 | ffed40b87ea013837a7b0131a42d492e17852395 | refs/heads/master | 2020-09-20T17:06:43.206454 | 2017-11-18T01:40:49 | 2017-11-18T01:40:49 | 66,907,338 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 747 | h | //--------------------------------------------------------
// file name :
// author : Dedy Yasriady
// version : v1.00
// copyright : Btm, 2016
// description : c/c++, Qt application
//--------------------------------------------------------
#ifndef STATUSBAR_H
#define STATUSBAR_H
#include <QObject>
#include <QStatusBar>
#include "statusbarwidget.h"
#include <Inc/StatusBar>
#define SB ui->statusBar->sbWidget()
class StatusBar : public DStatusBar
{
public:
explicit StatusBar(QWidget *parent = Q_NULLPTR);
virtual ~StatusBar();
void updateUi();
protected:
void showEvent(QShowEvent *);
private:
StatusBarWidget *m_sbWidget;
public:
StatusBarWidget *sbWidget() const;
};
#endif // STATUSBAR_H
| [
"yasriady@yahoo.com"
] | yasriady@yahoo.com |
d42ad90d942cb196b5a0c6fbaf12687d5aac2c43 | d6fc5e23b73d997800727a65e366210d5c4f12ac | /MayaPlugins/HiMaya/plugin_main.cpp | a1d229e516563a15fca7a20560ca0d7c0d42ae6b | [] | no_license | kingmax/mayaProgrammingA | b5ce126798fdc618213f0584b36912b4cf8305e9 | f89d49c6a2607b571b5fa979c9987f645fbe8da9 | refs/heads/master | 2020-03-23T19:26:15.386091 | 2019-01-07T16:51:59 | 2019-01-07T16:51:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 540 | cpp | #include <maya/MGlobal.h>
#include <maya/MFnPlugin.h>
#include "hi_maya.h"
MStatus initializePlugin(MObject obj)
{
MFnPlugin plugin(obj, "kingmax_res@163.com | 184327932@qq.com | iJasonLee@WeChat", "2018.07.23.01");
MStatus status;
status = plugin.registerCommand("HiMaya", HiMaya::creator);
CHECK_MSTATUS_AND_RETURN_IT(status);
return status;
}
MStatus uninitializePlugin(MObject obj)
{
MFnPlugin plugin(obj);
MStatus status;
status = plugin.deregisterCommand("HiMaya");
CHECK_MSTATUS_AND_RETURN_IT(status);
return status;
} | [
"kingmax_res@163.com"
] | kingmax_res@163.com |
1d1ba252794cf3be179302508286719b87061405 | 27ecdeb729b64e378033f6b920fbe3ec443a626b | /1111/1111E.cpp | 7ed83449b46fd14cc6501458fcafc50a22fe0a46 | [] | no_license | MtTsai/Codeforces | 1095bb3055166f469cc1d8e843cfc7f32ce183af | bc1d487bba780146a9f94a3ba7b7818ce34f7250 | refs/heads/master | 2020-04-21T21:30:01.159515 | 2019-04-21T16:23:41 | 2019-04-21T16:24:11 | 169,880,798 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,191 | cpp | #include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;
int n, q;
int k, m, r;
unordered_map<int, vector<int>> m;
unordered_map<int, bool> vis;
vector<int> dfs(int cur, unordered_set<int> &a) {
vector<int> p(m, 0);
vis[cur] = true;
for (auto dst: m[cur]) {
if (!vis[dst]) {
vector<int> p_child = dfs(dst, a);
vector<int> tmp(m);
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
if (i + j < m) {
p[i]
}
}
}
}
}
if (a.count(cur)) {
}
vis[cur] = false;
}
int main() {
cin >> n >> q;
for (int i = 0; i < n - 1; i++) {
int u, v;
cin >> u >> v;
m[u].push_back(v);
m[v].push_back(u);
vis[u] = vis[v] = false;
}
for (int i = 0; i < q; i++) {
cin >> k >> m >> r;
unordered_set<int> a;
for (int j = 0; j < k; j++) {
int t;
cin >> t;
a.insert(t);
}
vector<int> p = dfs(r, a);
}
return 0;
}
| [
"a17653aw96801@gmail.com"
] | a17653aw96801@gmail.com |
8149285f5560b9e312e3140f3800233d62f03bb6 | 945690d92480889fb40e84dc2b32a23569ef21b9 | /ATK/IO/OutWavFilter.cpp | 9c0bc8b81323cfbcc793f308f4b050d36741dba2 | [
"BSD-3-Clause"
] | permissive | joaorossi/AudioTK | 93fe2602587bfefa5deaaf6031d6d03e9cdfc627 | d0ce1c1d50149e4205707d26be2be382dd1dca18 | refs/heads/master | 2021-01-01T04:47:06.220677 | 2017-07-06T20:05:40 | 2017-07-06T20:05:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,270 | cpp | /**
* \file OutWavFilter.cpp
*/
#include "OutWavFilter.h"
#include <cstring>
#include <stdexcept>
#include <ATK/Core/Utilities.h>
namespace
{
template<typename DataType1, typename DataType2>
void convert(std::vector<std::vector<DataType1> >& outputs, const std::vector<char>& inputs)
{
int nbChannels = outputs.size();
int64_t size = outputs[0].size();
for(int j = 0; j < nbChannels; ++j)
{
ATK::ConversionUtilities<DataType2, DataType1>::convert_array(reinterpret_cast<const DataType2*>(inputs.data() + j * sizeof(DataType2)), outputs[j].data(), size, nbChannels);
}
}
}
namespace ATK
{
template<typename DataType>
OutWavFilter<DataType>::OutWavFilter(const std::string& filename)
:TypedBaseFilter<DataType>(0, 0)
{
wavstream.open(filename.c_str(), std::ios_base::binary);
if(!wavstream.good())
{
throw std::runtime_error("Could not WAV file " + filename);
}
}
template<typename DataType>
void OutWavFilter<DataType>::process_impl(std::size_t size) const
{
std::size_t nb_inputs = converted_inputs.size();
std::vector<DataType> buffer(nb_inputs * size);
for(std::size_t i = 0; i < size; ++i)
{
for(std::size_t j = 0; j < nb_inputs; ++j)
{
buffer[j + i * nb_inputs] = converted_inputs[j][i];
}
}
wavstream.write(reinterpret_cast<const char*>(buffer.data()), buffer.size() * sizeof(DataType));
write_header();
}
template<typename DataType>
void OutWavFilter<DataType>::set_nb_input_ports(std::size_t nb_ports)
{
Parent::set_nb_input_ports(nb_ports);
setup();
}
template<typename DataType>
void OutWavFilter<DataType>::setup()
{
write_header();
}
template<typename DataType>
void OutWavFilter<DataType>::write_header() const
{
WavHeader header;
WavFormat format;
WavData data;
std::strncpy(header.FileTypeBlocID, "RIFF", 4);
std::strncpy(header.FileFormatID, "WAVE", 4);
std::strncpy(format.FormatBlocID, "fmt ", 4);
std::strncpy(data.DataBlocID, "data", 4);
format.AudioFormat = WavTraits<DataType>::get_wav_type();
format.Frequence = static_cast<int32_t>(input_sampling_rate);
format.BitsPerSample = sizeof(DataType)* 8;
format.BytePerBloc = format.NbChannels * format.BitsPerSample / 8;
format.BytePerSec = static_cast<int32_t>(format.BytePerBloc * input_sampling_rate);
format.NbChannels = static_cast<int16_t>(nb_input_ports);
std::size_t total_size = wavstream.tellp();
std::size_t bloc_size = sizeof(WavFormat);
std::size_t data_size = total_size - sizeof(WavFormat) - sizeof(WavHeader) - sizeof(WavData);
wavstream.seekp(0);
header.FileSize = static_cast<std::int32_t>(total_size - 8);
format.BlocSize = static_cast<std::int32_t>(bloc_size - 8);
data.DataSize = static_cast<std::int32_t>(data_size);
wavstream.write(reinterpret_cast<char*>(&header), sizeof(WavHeader));
wavstream.write(reinterpret_cast<char*>(&format), sizeof(WavFormat));
wavstream.write(reinterpret_cast<char*>(&data), sizeof(WavData));
wavstream.seekp(0, std::ios_base::end);
}
template class OutWavFilter<std::int16_t>;
template class OutWavFilter<float>;
template class OutWavFilter<double>;
}
| [
"matthieu.brucher@gmail.com"
] | matthieu.brucher@gmail.com |
799347c5569246b46049108a128d0ec60e1c2776 | 6a16bbbc11bbd2385ab9e8605de69e215c5e8181 | /src/config/knossos-config.cpp | 766309a2e8f066128dcae4e9bd0db7e15e3d4c41 | [] | no_license | foo/mouse-retina | 389b87fa0106f436a7ff3ba88a4eb6a8d2b785a9 | e307d3784b6142c3dabea71bfaae1b6118645f86 | refs/heads/master | 2021-01-23T18:21:56.254712 | 2013-06-13T12:45:04 | 2013-06-13T12:45:04 | 9,939,670 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,861 | cpp | #include "knossos-config.hpp"
knossos_config::knossos_config(const std::string& directory)
{
std::ifstream conf(directory + "/knossos.conf");
parse_file(conf);
}
void knossos_config::parse_file(std::ifstream& in)
{
std::string line;
while(std::getline(in, line))
{
std::istringstream iss(line);
std::string variable;
if (!(iss >> variable))
continue; // in case of empty line
bool parse_line_successful = true;
if(variable == "experiment")
parse_line_successful = parse_experiment_var(iss);
else if(variable == "scale")
parse_line_successful = parse_scale_var(iss);
else if(variable == "boundary")
parse_line_successful = parse_boundary_var(iss);
else if(variable == "magnification")
parse_line_successful = parse_magnification_var(iss);
else
{
std::cerr
<< "Parse config: unknown variable: <"
<< variable << ">" << std::endl;
exit(0);
}
if(!parse_line_successful)
{
std::cerr
<< "Parse config: error reading line:\n\t"
<< line << std::endl;
exit(0);
}
}
}
void knossos_config::print_config() const
{
std::cout << "experiment name " << experiment_name << ";\n"
<< "scale x " << scale_x << ";\n"
<< "scale y " << scale_y << ";\n"
<< "scale z " << scale_z << ";\n"
<< "boundary x " << boundary_x << ";\n"
<< "boundary y " << boundary_y << ";\n"
<< "boundary z " << boundary_z << ";\n"
<< "magnification " << magnification << ";"
<< std::endl;
}
bool knossos_config::parse_experiment_var(std::istringstream& iss)
{
std::string secondary_variable;
iss >> secondary_variable;
// first character of third string is "
iss.ignore(1, '\"');
iss >> experiment_name;
// last two characters of third string are ";
experiment_name.resize(experiment_name.size() - 2);
return iss.good();
}
bool knossos_config::parse_scale_var(std::istringstream& iss)
{
std::string secondary_variable;
iss >> secondary_variable;
if(secondary_variable == "x")
{
iss >> scale_x;
return iss.good();
}
else if(secondary_variable == "y")
{
iss >> scale_y;
return iss.good();
}
else if(secondary_variable == "z")
{
iss >> scale_z;
return iss.good();
}
else
{
return false;
}
}
bool knossos_config::parse_boundary_var(std::istringstream& iss)
{
std::string secondary_variable;
iss >> secondary_variable;
if(secondary_variable == "x")
{
iss >> boundary_x;
return iss.good();
}
else if(secondary_variable == "y")
{
iss >> boundary_y;
return iss.good();
}
else if(secondary_variable == "z")
{
iss >> boundary_z;
return iss.good();
}
else
return false;
}
bool knossos_config::parse_magnification_var(std::istringstream& iss)
{
iss >> magnification;
return iss.good();
}
| [
"maciek.pacut@gmail.com"
] | maciek.pacut@gmail.com |
77ef1c9f3fdbfda11883d22a37427a74bb8a2b9a | 31ba4644568aed5f1865474f666ae7d87664312f | /new_fitter/src/junoB12_simplified.cc | 0f9288aa6dd9af72992019be950a96897e2290d2 | [] | no_license | YMTheory/energyModel_Fit | 11bf4a3350fb770f075585b16bc4adc9ec64802c | db6b236827d934ddf713e54d7f744d23fba102c5 | refs/heads/master | 2022-08-13T08:07:30.594576 | 2022-07-21T10:08:16 | 2022-07-21T10:08:16 | 253,709,247 | 0 | 0 | null | 2021-03-16T01:29:52 | 2020-04-07T06:42:00 | C++ | UTF-8 | C++ | false | false | 8,862 | cc | #include "junoB12_simplified.hh"
#include "electronQuench.hh"
#include "electronCerenkov.hh"
#include "electronResponse.hh"
#include "junoParameters.hh"
#include <TFile.h>
#include <TTree.h>
#include <TH1D.h>
#include <iostream>
using namespace std;
junoB12_simplified::junoB12_simplified(int nBinsData, double fitMinPE, double fitMaxPE)
{
m_nBin = 1500;
m_nBinData = nBinsData;
m_fitMinPE = fitMinPE;
m_fitMaxPE = fitMaxPE;
m_eMin = 0;
m_eMax = 15;
m_peMin = 0;
m_peMax = 3000;
m_loadData = false;
m_loadTheo = false;
}
junoB12_simplified::~junoB12_simplified()
{
delete gaus;
}
void junoB12_simplified::Initialize()
{
m_eBinWidth = (m_eMax - m_eMin) / m_nBin;
m_peBinWidth = (m_peMax - m_peMin) / m_nBin;
for (int i=0; i<m_nBin; i++) {
m_eBinCenter[i] = m_eBinWidth/2. + m_eBinWidth * i; // energy region
m_peBinCenter[i] = m_peBinWidth /2. + m_peBinWidth*i; // p.e. region
}
LoadDataSpec();
LoadTheoSpec();
electronResponse::loadElecResol();
gaus = new TF1("gaus", "1/(TMath::Sqrt(2*TMath::Pi())*[1]) * TMath::Exp(-(x-[0])*(x-[0])/2/[1]/[1])", -100, 30000);
}
void junoB12_simplified::LoadDataSpec()
{ // load in totpe definition
TH1D* sigH = new TH1D("B12_data", "", m_nBinData, m_peMin, m_peMax);
//TFile* ff = new TFile("./data/spectrum/data/B12_data_G4_J19.root", "read");
//TFile* ff = new TFile("./data/spectrum/data/B12_totpe_gendecay_J19.root", "read");
//TFile* ff = new TFile("/junofs/users/miaoyu/energy_model/production/J19v1r0-Pre4/B12/B12_totpe_LS_v7.root");
//if(!ff) cout << "No such B12 data file " << endl;
//TFile* ff = new TFile("./data/spectrum/data/B12_totpe_LS_tao.root", "read");
TFile* ff = new TFile("./data/spectrum/data/B12_totpe_LS_dyb.root", "read");
//TTree* tt = (TTree*)ff->Get("michel");
TTree* tt = (TTree*)ff->Get("B12");
double m_totpe;
tt->SetBranchAddress("totpe", &m_totpe);
for(int i=0; i<tt->GetEntries(); i++) {
tt->GetEntry(i);
//double tmp_Evis = m_totpe / scale;
//sigH->Fill(tmp_Evis);
sigH->Fill(m_totpe);
}
for (int i=0; i<m_nBinData; i++) {
double content = sigH->GetBinContent(i+1);
double error = sigH->GetBinError (i+1);
m_peData [i] = content;
m_peDataErr[i] = error;
}
delete sigH;
delete tt;
delete ff;
m_loadData = true;
cout << endl;
cout << "********************************" << endl;
cout << " Load B12 MC Data " << endl;
cout << "********************************" << endl;
cout << endl;
}
void junoB12_simplified::LoadTheoSpec()
{
// load in energy region
TH1D* simH = new TH1D("B12_edep", "", m_nBin, m_eMin, m_eMax);
TFile* ff = new TFile("/junofs/users/miaoyu/energy_model/production/J19v1r0-Pre4/B12/B12_edep_LS_v7.root");
//TFile* ff = new TFile("./data/spectrum/theo/B12_edep_gendecay_J19.root");
//TFile* ff = new TFile("./data/spectrum/theo/B12_edep_G4_J19.root");
if (!ff) cout << "No such B12 theo file !" << endl;
TTree* tt = (TTree*)ff->Get("michel");
double m_edep;
tt->SetBranchAddress("edep", &m_edep);
for(int i=0; i<tt->GetEntries(); i++) {
tt->GetEntry(i);
simH->Fill(m_edep);
}
for(int i=0; i<m_nBin; i++) {
m_eTru[i] = simH->GetBinContent(i);
}
delete simH;
delete tt;
delete ff;
m_loadTheo = true;
cout << endl;
cout << "********************************" << endl;
cout << " Load B12 Theo Data " << endl;
cout << "********************************" << endl;
cout << endl;
}
void junoB12_simplified::ApplyResponse()
{
// add LS nonlinearity
if (not m_loadData) LoadDataSpec();
if (not m_loadTheo) LoadTheoSpec();
electronResponse::SetParameters();
for (int i=0; i<m_nBin; i++) {
m_eVis[i] = 0;
}
int newBin;
int newBinLow, newBinHig;
double bias;
for (int i=0; i<m_nBin; i++) {
double eTru = m_eBinCenter[i];
double tmp_pe = electronQuench::ScintillatorPE(eTru) + electronCerenkov::getCerPE(eTru);
// consider resolution:
//double tmp_sigma = electronResponse::fElecResol->Eval(eTru);
double tmp_sigma;
//tmp_sigma = electronResponse::gElecResol->Eval(tmp_pe);
//tmp_sigma = electronResponse::fEvisSigma->Eval(tmp_pe);
//tmp_sigma = electronResponse::fEvisNew->Eval(tmp_pe);
tmp_sigma = electronResponse::fEvisNew->Eval(tmp_pe);
//if (junoParameters::pesigmaMode == "kTotal" ) {
// //tmp_sigma = TMath::Power(electronResponse::fElecResol->Eval(eTru), 2);
// tmp_sigma = electronResponse::fElecResol->Eval(eTru);
//} else if (junoParameters::pesigmaMode == "kNPE" ) {
// tmp_sigma = electronResponse::fNPESigma->Eval(tmp_pe); // consider sigma-NPE relationship
//} else if (junoParameters::pesigmaMode == "kSeparate") {
// double sctpe = electronQuench::ScintillatorPE(eTru);
// double cerpe = electronCerenkov::getCerPE(eTru);
// double p = (sctpe) / (sctpe + cerpe);
// //tmp_sigma = TMath::Sqrt (( electronResponse::fSctPESigma->Eval(sctpe) + electronResponse::fCerPESigma->Eval(cerpe) ) / (1 - 2*p*(1-p)));
// tmp_sigma = TMath::Sqrt( (2-p)/p * electronResponse::fSctPESigma->Eval(sctpe) + electronResponse::fCerPESigma->Eval(cerpe) );
//}
//put a faked poisson fluctuation into the fitter ...
//tmp_sigma = TMath::Sqrt(tmp_pe) ;
gaus->SetParameter(0, tmp_pe);
gaus->SetParameter(1, tmp_sigma);
int minBin = int((tmp_pe-5.0*tmp_sigma)/m_peBinWidth);
int maxBin = int((tmp_pe+5.0*tmp_sigma)/m_peBinWidth);
//if (minBin < 0) minBin = 0;
//if(maxBin > m_nBin) maxBin = m_nBin;
for (int j=minBin; j<maxBin; j++) {
if (j<0 or j>m_nBin) continue;
double tmp_center = m_peBinWidth /2 + m_peBinWidth * j;
double prob = gaus->Eval(tmp_center);
m_eVis[j] += prob * m_eTru[i];
}
}
}
void junoB12_simplified::Normalize()
{
// Normalize spectrum for data and pred
int rebin = m_nBin / m_nBinData;
double binWidthData = m_peBinWidth * rebin;
double nTheo = 0;
double nData = 0;
for (int i = 0; i < m_nBinData; i++)
{
m_peTheo[i] = 0;
for (int j = 0; j < rebin; j++){
m_peTheo[i] += m_eVis[i*rebin+j];
}
if(i*binWidthData>m_fitMinPE && i*binWidthData<m_fitMaxPE) // fitting range [3MeV, 12MeV]
{
nTheo += m_peTheo[i];
nData += m_peData[i];
}
}
double scale = 1;
if( nTheo!=0 ) { scale = nData/nTheo; }
for (int i = 0; i < m_nBinData; i++)
{
m_peTheo[i] *= scale;
}
for (int i = 0; i < m_nBinData; i++)
{
m_eVis [i] *= scale;
}
}
double junoB12_simplified::GetChi2()
{
ApplyResponse();
Normalize();
double chi2 = 0;
int rebin = m_nBin / m_nBinData;
double binWidthData = m_peBinWidth * rebin;
int m_nData = 0;
for(int i=0; i < m_nBinData; i++) {
if(i*binWidthData<m_fitMinPE or binWidthData*i>m_fitMaxPE) continue;
if( m_peDataErr[i]!=0 ) {
chi2 += pow( (m_peData[i] - m_peTheo[i])/m_peDataErr[i], 2);
m_nData++;
}
}
//cout << "simplified B12 chi2: " << chi2 << " with nData : " << m_nData << endl;
//if(nDoF>0) chi2 /= double(m_nData - nDoF);
return chi2;
}
void junoB12_simplified::Plot()
{
TH1D* hData = new TH1D("hData", "", m_nBinData, m_peMin, m_peMax);
TH1D* hTheo = new TH1D("hTheo", "", m_nBinData, m_peMin, m_peMax);
TH1D* hRela = new TH1D("hRela", "", m_nBinData, m_peMin, m_peMax);
hData->SetStats(0);
hData->SetLineColor(kBlue+1);
hData->SetLineWidth(2);
hData->SetMarkerSize(0.8);
hData->SetMarkerStyle(20);
hData->SetMarkerColor(kBlue+1);
hTheo->SetStats(0);
hTheo->SetLineColor(kRed+1);
hTheo->SetLineWidth(2);
hTheo->SetMarkerSize(0.8);
hTheo->SetMarkerStyle(20);
hTheo->SetMarkerColor(kRed+1);
hRela->SetStats(0);
hRela->SetLineColor(kPink+2);
hRela->SetLineWidth(2);
hRela->SetMarkerSize(0.8);
hRela->SetMarkerStyle(20);
for(int i=0; i<m_nBinData; i++) {
hData->SetBinContent(i+1, m_peData[i]);
hTheo->SetBinContent(i+1, m_peTheo[i]);
if(m_peTheo[i]!=0) {
hRela->SetBinContent(i+1, m_peData[i]/m_peTheo[i]);
hRela->SetBinError(i+1, m_peDataErr[i]/m_peTheo[i]);
} else {
hRela->SetBinContent(i+1, 0);
hRela->SetBinError(i+1, 0);
}
}
TFile* out = new TFile("spectrum.root", "recreate");
hData->Write();
hTheo->Write();
hRela->Write();
out->Close();
}
| [
"932899789@qq.com"
] | 932899789@qq.com |
d69c8bfba8d55b41d864b7e909f74eb8a2167bef | 749e36171eb184f5a3941b129040edca63679f6e | /src/GlobalStash.cpp | c6ea303cab1c0f65b690e105da4ea572058cd380 | [
"MIT"
] | permissive | droidream/dukv8 | 822d9d3ea65d6cb9603cdd5c495de02ae3262bf4 | 2eb03526b680ad50055e5499141fe45f70a6bbfe | refs/heads/master | 2021-01-10T12:19:05.401428 | 2015-06-03T04:56:49 | 2015-06-03T04:56:49 | 36,780,487 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,889 | cpp | //
// Created by Jiang Lu on 6/2/15.
//
#include <dukv8/GlobalStash.h>
#include <dukv8/Isolate.h>
namespace v8 {
namespace internal {
GlobalStash::GlobalStash(const char *name) : name_(name) {
Isolate *isolate = Isolate::GetCurrent();
duk_context *ctx = isolate->GetDukContext();
// 每个 global 对象对应一个 stash 对象
duk_push_global_stash(ctx);
duk_get_prop_string(ctx, -1, name_);
if (duk_is_undefined(ctx, -1)) {
duk_pop(ctx);
// Create a new array with one `0` at index `0`.
duk_push_array(ctx);
duk_push_int(ctx, 0);
duk_put_prop_index(ctx, -2, 0);
// Store it as "name_" in the heap stash
duk_put_prop_string(ctx, -2, name_);
} else {
duk_pop(ctx);
}
duk_pop(ctx);
}
int GlobalStash::AddObject(void *ptr) {
Isolate *isolate = Isolate::GetCurrent();
duk_context *ctx = isolate->GetDukContext();
// Get the "refs" array in the heap stash
duk_push_global_stash(ctx);
duk_get_prop_string(ctx, -1, name_);
duk_remove(ctx, -2);
int type = duk_get_type(ctx, -1);
int freeSlot;
// freeSlot = scopeList[0]
duk_get_prop_index(ctx, -1, 0); // <scopeList> <scopeList[0]>
freeSlot = duk_get_int(ctx, -1);
duk_pop(ctx); // <scopeList>
if (freeSlot != 0) {
// scopeList[0] = scopeList[freeSlot]
duk_get_prop_index(ctx, -1, (duk_uarridx_t) freeSlot); // <scopeList> <scopeList[freeSlot]>
duk_put_prop_index(ctx, -2, 0); // <scopeList>
} else {
// freeSlot = scopeList.length;
freeSlot = (int) duk_get_length(ctx, -1);
}
duk_push_heapptr(ctx, ptr); // <scopeList> <scope>
// scopeList[freeSlot] = scope
duk_put_prop_index(ctx, -2, (duk_uarridx_t) freeSlot); // <scopeList>
// Remove the refs array from the stack.
duk_pop(ctx); //
return freeSlot;
}
void GlobalStash::RemoveObject(int index) {
if (!index) return;
Isolate *isolate = Isolate::GetCurrent();
duk_context *ctx = isolate->GetDukContext();
// Get the "refs" array in the heap stash
duk_push_global_stash(ctx);
duk_get_prop_string(ctx, -1, name_);
duk_remove(ctx, -2);
// scopeList[scopeIndex] = scopeList[0]
duk_get_prop_index(ctx, -1, 0); // <scopeList> <scopeList[0]>
duk_put_prop_index(ctx, -2, (duk_uarridx_t) index);
// scopeList[0] = scopeIndex
duk_push_int(ctx, index); // <scopeList> <scopeIndex>
duk_put_prop_index(ctx, -2, 0); // <scopeList>
duk_pop(ctx); //
}
}
}
| [
"droidream@gmail.com"
] | droidream@gmail.com |
45332f2a34f214c46cb645ee73238ec0077b7b9a | 7fa5cd65b7e8da4946be2d975625b2613c1c9477 | /test/TestOramDeterministicSetup.cpp | fd4bf2754a82f2618c99553ff01cbe9c868edafd | [
"MIT"
] | permissive | young-du/PathORAM | 93b0bf23b70cc888d78b25bb8cb72e4a461c52dd | 23d18b23153adf2e4a689e26d4bd05dc7db2497e | refs/heads/master | 2022-11-12T22:39:42.853314 | 2020-06-24T23:19:08 | 2020-06-24T23:19:08 | 274,751,717 | 0 | 0 | MIT | 2020-06-24T19:23:57 | 2020-06-24T19:23:57 | null | UTF-8 | C++ | false | false | 3,766 | cpp | #include "catch.h"
#include "Bucket.h"
#include "ServerStorage.h"
#include "OramInterface.h"
#include "RandForOramInterface.h"
#include "RandomForOram.h"
#include "UntrustedStorageInterface.h"
#include "OramReadPathEviction.h"
#include "OramDeterministic.h"
TEST_CASE("Test deterministic ORAM setup very small numBlocks")
{
int bucketSize = 2;
int numBlocks = 1;
Bucket::setMaxSize(bucketSize);
UntrustedStorageInterface* storage = new ServerStorage();
RandForOramInterface* random = new RandomForOram();
OramInterface* oram = new OramDeterministic(storage, random, bucketSize, numBlocks);
REQUIRE(oram->getNumBlocks() == 1);
REQUIRE(oram->getNumLevels() == 1);
REQUIRE(oram->getNumLeaves() == 1);
REQUIRE(oram->getNumBuckets() == 1);
Bucket::resetState();
ServerStorage::is_initialized = false;
ServerStorage::is_capacity_set = false;
RandomForOram::is_initialized = false;
RandomForOram::bound = -1;
}
TEST_CASE("Test deterministic ORAM setup small numBlocks")
{
int bucketSize = 2;
int numBlocks = 32;
Bucket::setMaxSize(bucketSize);
UntrustedStorageInterface* storage = new ServerStorage();
RandForOramInterface* random = new RandomForOram();
OramInterface* oram = new OramDeterministic(storage, random, bucketSize, numBlocks);
REQUIRE(oram->getNumBlocks() == 32);
REQUIRE(oram->getNumLevels() == 6);
REQUIRE(oram->getNumLeaves() == 32);
REQUIRE(oram->getNumBuckets() == 63);
Bucket::resetState();
ServerStorage::is_initialized = false;
ServerStorage::is_capacity_set = false;
RandomForOram::is_initialized = false;
RandomForOram::bound = -1;
}
TEST_CASE("Test deterministic ORAM setup larger numBlocks")
{
int bucketSize = 2;
int numBlocks = 1024;
Bucket::setMaxSize(bucketSize);
UntrustedStorageInterface* storage = new ServerStorage();
RandForOramInterface* random = new RandomForOram();
OramInterface* oram = new OramDeterministic(storage, random, bucketSize, numBlocks);
REQUIRE(oram->getNumBlocks() == 1024);
REQUIRE(oram->getNumLevels() == 11);
REQUIRE(oram->getNumLeaves() == 1024);
REQUIRE(oram->getNumBuckets() == 2047);
Bucket::resetState();
ServerStorage::is_initialized = false;
ServerStorage::is_capacity_set = false;
RandomForOram::is_initialized = false;
RandomForOram::bound = -1;
}
TEST_CASE("Test deterministic ORAM setup very large numBlocks")
{
int bucketSize = 2;
int numBlocks = 1048576;
Bucket::setMaxSize(bucketSize);
UntrustedStorageInterface* storage = new ServerStorage();
RandForOramInterface* random = new RandomForOram();
OramInterface* oram = new OramDeterministic(storage, random, bucketSize, numBlocks);
REQUIRE(oram->getNumBlocks() == 1048576);
REQUIRE(oram->getNumLevels() == 21);
REQUIRE(oram->getNumLeaves() == 1048576);
REQUIRE(oram->getNumBuckets() == 2097151);
Bucket::resetState();
ServerStorage::is_initialized = false;
ServerStorage::is_capacity_set = false;
RandomForOram::is_initialized = false;
RandomForOram::bound = -1;
}
TEST_CASE("Test deterministic ORAM setup numBlocks not power of 2")
{
int bucketSize = 2;
int numBlocks = 30;
Bucket::setMaxSize(bucketSize);
UntrustedStorageInterface* storage = new ServerStorage();
RandForOramInterface* random = new RandomForOram();
OramInterface* oram = new OramDeterministic(storage, random, bucketSize, numBlocks);
REQUIRE(oram->getNumBlocks() == 30);
REQUIRE(oram->getNumLevels() == 6);
REQUIRE(oram->getNumLeaves() == 32);
REQUIRE(oram->getNumBuckets() == 63);
Bucket::resetState();
ServerStorage::is_initialized = false;
ServerStorage::is_capacity_set = false;
RandomForOram::is_initialized = false;
RandomForOram::bound = -1;
} | [
"harjasleen_malvai@brown.edu"
] | harjasleen_malvai@brown.edu |
6aaf148d24fec78280aa907bb2ba561541bc9873 | 8ade3d20f78abfa461af79cd346882beaca07edc | /closures/erp_closures/production/schedulermw.h | 7e1451a577d49d842a8500b2bf8222a3b433b1d5 | [] | no_license | eboladev/smarterp | 337867fa215eb6042cdfdb894b8cbd2e766b98c3 | 94e7af29485885fb3f1e9a900dea54903a817b0a | refs/heads/master | 2020-12-29T00:55:51.144001 | 2014-05-30T05:07:22 | 2014-05-30T05:07:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 528 | h | #ifndef SCHEDULERMW_H
#define SCHEDULERMW_H
#include <QMainWindow>
#include <QDate>
namespace Ui {
class SchedulerMW;
}
class SchedulerMW : public QMainWindow
{
Q_OBJECT
public:
explicit SchedulerMW(QWidget *parent = 0);
~SchedulerMW();
private slots:
void on_calDate_clicked(const QDate &date);
void reloadSchedule();
void on_cmdAddOrder_clicked();
void on_cmdDeleteFromSchedule_clicked();
void on_cmdPrintSchedule_clicked();
private:
Ui::SchedulerMW *ui;
};
#endif // SCHEDULERMW_H
| [
"joejoshw@gmail.com"
] | joejoshw@gmail.com |
aaada3b63c22a6bb0bfbf02c7b06b169f1f79292 | 0de49375998eae6d969fc307a7f6e9d05dd08df4 | /trunk/bridgenet/src/secudpneter.cpp | 4feaccab19d023d3e3e8b092bd5c67c3a52e89f2 | [] | no_license | BGCX261/zombie3-svn-to-git | de2c2bcc98ba0fcbab6b89eb0473e58a66389958 | 9d4f17931083ad785fc9c9bdf7d768a7f40496c0 | refs/heads/master | 2021-01-13T14:04:36.426528 | 2015-08-25T15:51:49 | 2015-08-25T15:51:49 | 41,497,983 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,330 | cpp | // C++ implementation file "SecUdpNeter.cpp" for class SecUdpNeter generated by Poseidon for UML.
// Poseidon for UML is developed by Gentleware (http://www.gentleware.com).
// Generated with velocity template engine (http://jakarta.apache.org/velocity).
#include "myfilelog.hxx"
#include "loghelper.hxx"
#include "udpsocketexception.hxx"
#include "udpserversocket.hxx"
#include "was_api.h"
#include "udpsocket.hxx"
#include "udpbridgenet.hxx"
#include "secudpneter.hxx"
SecUdpNeter::SecUdpNeter(tUInt32 timingoutms,FileLog* filelog)
:Thread(),
_imsg_que(),
_omsg_que(),
_unacknowledged_osmg_list(),
_failed_omsg_que(),
_ever_received_imsg_list(),
_socket(NULL),
_listen_port(0),
_timingoutms(timingoutms),
_is_shutdown_requested(FALSE),
_filelog(filelog)
{
}
SecUdpNeter::SecUdpNeter(tUInt32 port,tUInt32 timingoutms,FileLog* filelog)
:Thread(),
_imsg_que(),
_omsg_que(),
_unacknowledged_osmg_list(),
_failed_omsg_que(),
_ever_received_imsg_list(),
_socket(NULL),
_listen_port(port),
_timingoutms(timingoutms),
_is_shutdown_requested(FALSE),
_filelog(filelog)
{
}
SecUdpNeter::SecUdpNeter(UdpSocket* udpsocket,tUInt32 timingoutms,FileLog* filelog)
:Thread(),
_imsg_que(),
_omsg_que(),
_unacknowledged_osmg_list(),
_failed_omsg_que(),
_ever_received_imsg_list(),
_socket(udpsocket),
_listen_port(0),
_timingoutms(timingoutms),
_is_shutdown_requested(FALSE),
_filelog(filelog)
{}
void SecUdpNeter::Shutdown(void)
{
_is_shutdown_requested = TRUE;
}
void SecUdpNeter::SendTo(tBridgeMsg* omsg, string remote_host, tUInt32 remote_port)
{
omsg->rhost = remote_host;
omsg->rport = remote_port;
_omsg_que.Push(omsg);
}
tBool SecUdpNeter::Recv(tBridgeMsg** imsg)
{
if ((*imsg)=_imsg_que.Pop())
return TRUE;
else
return FALSE;
}
tBool SecUdpNeter::AnyOMsgFailed(void) const
{
return (!_failed_omsg_que.Empty());
}
string SecUdpNeter::PeerLocalAddress(void)
{
UdpSocket* socket = new UdpSocket();
string localhost = socket->PeerLocalHost();
delete socket;
return localhost;
}
void SecUdpNeter::Execute(Thread::Arg arg)
{
UdpBridgeNet* bridgenet;
tBridgeMsg* imsg;
tBridgeMsg* omsg;
tByte* msg;
tUInt32 len;
tBridgeMsg* bmsg;
tUnacknowledgedOMsg* unacknowledgedomsg;
tBridgeUnacknowledgedMsgListIter unacknowledgedomsglistiter;
BridgeNet::tBridgeNetStatus res;
tBool is_external_socket=TRUE;
tBool isbusy;
tUInt32 counter=0;
LOGINFO("SecUdpNeter starting up...");
try
{
if (!_socket)
{
is_external_socket = FALSE;
if (_listen_port)
_socket = new UdpServerSocket(_listen_port);
else
_socket = new UdpSocket();
}
}
catch (UdpSocketException& e)
{
LOGERROR("SecUdpNeter::Execute:Failed to create the UdpSocket:"<<e.Description());
if (_socket)
{
_socket->Close();
delete _socket;
_socket = NULL;
}
Shutdown();
}
bridgenet = new UdpBridgeNet(_filelog);
bridgenet->SetUdpSocket(_socket);
while (!_is_shutdown_requested)
{
isbusy = FALSE;
res = bridgenet->ReceiveMsg(&imsg);
if(res==BridgeNet::eMsgAvailable)
{
isbusy = TRUE;
if (imsg->tom==E_WAS_MSG_ACKNOWLEDGE)
{
LOGDEBUG("SecUdpNeter::Execute:Omsg #"<<imsg->tid<<" is acknowledged from '"<<imsg->rhost<<"::"<<imsg->rport<<"'.");
unacknowledgedomsglistiter = _unacknowledged_osmg_list.begin();
while (unacknowledgedomsglistiter!=_unacknowledged_osmg_list.end())
{
unacknowledgedomsg = *unacknowledgedomsglistiter;
if (unacknowledgedomsg->omsg->tid == imsg->tid)
{
ReleaseBridgeMsg(&(unacknowledgedomsg->omsg));
delete unacknowledgedomsg;
unacknowledgedomsg = NULL;
_unacknowledged_osmg_list.erase(unacknowledgedomsglistiter);
break;
}
else
unacknowledgedomsglistiter++;
}
ReleaseBridgeMsg(&imsg); //release the acknowledge imsg.
}
else
{
LOGDEBUG("SecUdpNeter::Execute:Received a msg #"<<imsg->tid<<" from '"<<imsg->rhost<<"::"<<imsg->rport<<"'.");
/** acknowledge it.*/
msg = was_write_msg(&len, E_WAS_MSG_FIRST_PART, E_WAS_MSG_ACKNOWLEDGE,imsg->tid, X_WAS_RSPC_OK,
E_WAS_TAG_ID_NONE);
assert(msg);
bmsg = CreateBridgeMsg();
bmsg->rhost = imsg->rhost;
bmsg->rport = imsg->rport;
bmsg->lom = len;
bmsg->mpi = E_WAS_MSG_FIRST_PART;
bmsg->tid = imsg->tid;
bmsg->rspc= X_WAS_RSPC_OK;
bmsg->msg = msg;
bmsg->tom = E_WAS_MSG_ACKNOWLEDGE;
bmsg->isReceived = FALSE;
_omsg_que.Push(bmsg);
if(IsMsgEverReceived(imsg))
{
LOGDEBUG("SecUdpNeter::Execute:The imsg #"<<imsg->tid<<" from "<<imsg->rhost<<"::"<<imsg->rport<<" is ever received,just abandon it.");
ReleaseBridgeMsg(&imsg);
}
else
{
/** register it as ever received.*/
RegisterIMsgAsEverReceived(imsg);
/** save it.*/
_imsg_que.Push(imsg);
}
}
}
/** send and move it to unacknowledged omsg list waiting for the acknowledge from peer.*/
if ((omsg=_omsg_que.Pop()))
{
isbusy = TRUE;
if (!bridgenet->SendBridgeMsg(omsg))
{
LOGWARNING("SecUdpNeter::Execute:Failed to send Omsg #"<<omsg->tid<<" at first time,just repush it for sending again.");
_omsg_que.Push(omsg);
}
else
{
if (omsg->tom!=E_WAS_MSG_ACKNOWLEDGE)
{
LOGDEBUG("SecUdpNeter::Execute:Omsg #"<<omsg->tid<<" has been sent to '"<<omsg->rhost<<"::"<<omsg->rport<<"'.");
unacknowledgedomsg = new tUnacknowledgedOMsg;
unacknowledgedomsg->omsg = omsg;
unacknowledgedomsg->tick_counter=0;
_unacknowledged_osmg_list.push_front(unacknowledgedomsg);
}
else
{
LOGDEBUG("SecUdpNeter::Execute:Acknowledge msg #"<<omsg->tid<<" has been sent to '"<<omsg->rhost<<"::"<<omsg->rport<<"'.");
ReleaseBridgeMsg(&omsg);
}
}
}
/** Check if the sending omsg failed,then move to failed msg que or send again.*/
if (++counter==_timingoutms/10)
{
counter = 0;
/** check if any unacknowledged omsg failed,if so move to the failure que.*/
unacknowledgedomsglistiter = _unacknowledged_osmg_list.begin();
while (unacknowledgedomsglistiter!=_unacknowledged_osmg_list.end())
{
unacknowledgedomsg = *unacknowledgedomsglistiter;
if (_timingoutms/1000 == unacknowledgedomsg->tick_counter)
{
LOGDEBUG("SecUdpNeter::Execute:Omsg #"<<unacknowledgedomsg->omsg->tid<<" to '"<<unacknowledgedomsg->omsg->rhost<<"::"<<unacknowledgedomsg->omsg->rport<<"' failed.");
/** if failed, move to failure que.*/
_failed_omsg_que.Push(unacknowledgedomsg->omsg);
unacknowledgedomsglistiter = _unacknowledged_osmg_list.erase(unacknowledgedomsglistiter);
delete unacknowledgedomsg;
unacknowledgedomsg = NULL;
}
else
{
unacknowledgedomsglistiter++;
/** send it again.*/
bridgenet->SendBridgeMsg(unacknowledgedomsg->omsg);
unacknowledgedomsg->tick_counter++;
LOGDEBUG("SecUdpNeter::Execute:Omsg #"<<unacknowledgedomsg->omsg->tid<<" to '"<<unacknowledgedomsg->omsg->rhost<<"::"<<unacknowledgedomsg->omsg->rport<<"' has been resent "<<unacknowledgedomsg->tick_counter<<" times.");
}
}
}
if (!isbusy)
Thread::Yield();
}
LOGDEBUG("SecUdpNeter::Execute:Shutdown signal received.");
if (!is_external_socket && _socket)
{
_socket->Close();
delete _socket;
_socket = NULL;
}
if (bridgenet)
{
delete bridgenet;
bridgenet = NULL;
}
/** clear the msgs later.*/
LOGINFO("SecUdpNeter shutdowned.");
}
tBool SecUdpNeter::IsMsgEverReceived(tBridgeMsg* imsg) const
{
tBool ret = FALSE;
tMsgBasicInfoListConstIter iter = _ever_received_imsg_list.begin();
while (iter!=_ever_received_imsg_list.end())
{
if ((*iter)->ip.compare(imsg->rhost)==0 && (*iter)->port==imsg->rport && (*iter)->tid==imsg->tid)
{
ret = TRUE;
break;
}
else
iter++;
}
return ret;
}
void SecUdpNeter::RegisterIMsgAsEverReceived(tBridgeMsg* imsg)
{
tMsgBasicInfo* basicinfo = new tMsgBasicInfo;
basicinfo->ip = imsg->rhost;
basicinfo->port = imsg->rport;
basicinfo->tid = imsg->tid;
_ever_received_imsg_list.push_front(basicinfo);
} | [
"you@example.com"
] | you@example.com |
b6eb00921d93f2ad2dc6f4c4209619d1e4330d83 | 8d2ce459b5f03e2982ba764c5cc383b63f6b19c0 | /1302缩进格式/1302.cpp | 17d465637a613e04156a0dc53fe6aa8c7bf8d50f | [] | no_license | elicassion/SJTU_OnlineJudge | 37a2eebdd4f1d41c23090be79e1771fb8a96bad4 | 532289168c782aca8444ff45764432c9863be2b3 | refs/heads/master | 2021-01-10T12:33:39.186794 | 2016-04-12T12:44:52 | 2016-04-12T12:44:52 | 36,080,058 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,304 | cpp | #include<iostream>
#include<fstream>
#include<iomanip>
#include<cstdlib>
#include<ctime>
#include<cstring>
#include<string>
#include<cmath>
#include<algorithm>
#include<cstdio>
#define FOR(i,bg,ed) for(int i=bg;i<=ed;++i)
#define RFOR(i,bg,ed) for(int i=bg;i>=ed;--i)
#define MSET(a,i) memset(a,i,sizeof(a))
#define CIa1(a,i) cin>>a[i]
#define CIa2(a,i,j) cin>>a[i][j]
#define COa1(a,i) cout<<a[i]<<' '
#define COa2(a,i,j) cout<<a[i][j]<<' '
#define SCIa1(a,i) scanf("%d",&a[i])
#define SCIa2(a,i,j) scanf("%d",&a[i][j])
#define SCOa1(a,i) printf("%d ",a[i])
#define SCOa2(a,i,j) printf("%d ",a[i][j])
#define RFF(s) freopen(s,"r",stdin)
#define WFF(s) freopen(s,"w",stdout)
using namespace std;
int T;
int crw[10001]={0};//ctrowwords
int maxl[200]={0};
int row=0;
string words[10001];
int wordsl[10001]={0};
void init()
{
MSET(crw,0);
MSET(maxl,0);
MSET(wordsl,0);
FOR(i,1,10000)
words[i]="";
row=0;
string s="";
while (1)
{
getline(cin,s);
if (s=="@")
break;
row++;
int l=s.length();
int i=0;
while (i<=l-1)
{
while (s[i]==' ' && i+1<=l-1)
i++;
string tmpword="";
int tmpwordl=0;
while(s[i]!=' ' && i<=l-1)
{
tmpword+=s[i];
i++;
tmpwordl++;
}
if (tmpword!="")
{
crw[row]++;
int wordl=tmpwordl+1;
wordsl[row]+=wordl;
words[row]+=tmpword+" ";
if (wordl>maxl[crw[row]])
maxl[crw[row]]=wordl;
}
}
//cout<<"FUCK"<<endl;
}
}
void pt()
{
FOR(i,1,row)
{
int l=wordsl[i];
int lj=0;
int ct=1;
FOR(j,0,l-1)
{
printf("%c",words[i][j]);s
if (words[i][j]==' ')
{
FOR(k,1,maxl[ct]-(j-lj+1))
{
printf(" ");
}
lj=j+1;
ct++;
}
}
printf("\n");
}
}
int main()
{
//RFF("1305.in");
//WFF("t.out");
cin>>T;
getchar();
FOR(i,1,T)
{
init();
pt();
}
return 0;
}
| [
"elicassion@sjtu.edu.cn"
] | elicassion@sjtu.edu.cn |
553b2204614b7020c7ba12b5df3203877fdc69a9 | 2c9bc9ac4d2707a04129373bdac239a4612322e3 | /AnotherTree.cpp | 14bd95d66d3c54008dab422a12a908dfeefb2020 | [] | no_license | Akashnishad17/javap | ce0e88112ac13f718c0a0d5377c25d6f39270add | ec8e615f9a5a6ded26ba25f421c69784d5b5528e | refs/heads/master | 2023-02-22T12:02:15.928222 | 2023-02-11T09:07:37 | 2023-02-11T09:07:37 | 214,708,604 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,535 | cpp | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define endl "\n"
#define f first
#define s second
#define ar array
#define pb push_back
#define forn(i, n) for(int i = 0; i < int(n); i++)
#define fore(i, l, r) for(int i = l; i <r; i++)
using vi = vector<int>;
template<typename T>
istream &operator>>(istream &in, vector<T> &vec) {
for (auto &x : vec) {
in >> x;
}
return in;
}
const int MXN = 2e5 + 2;
vi g[MXN];
int ans[MXN];
int leaf[MXN];
vector<pair<int,int>> queries[MXN];
unordered_map<int,vector<int>*> level[MXN];
void dfsleaf(int u){
if(g[u].size()==0){
leaf[u]=1;
}
for(auto i:g[u]){
dfsleaf(i);
leaf[u]+=leaf[i];
}
}
void merge(int x,int y){
if(queries[x].size()<queries[y].size()){
swap(queries[x],queries[y]);
}
for(auto i:queries[y]){
queries[x].pb(i);
}
}
void dfs(int u,int lvl){
if(g[u].size()==0||leaf[u]==1){
return;
}
int sz = g[u].size();
if(g[u].size()==1){
merge(g[u][0],u);
swap(level[lvl+1],level[lvl]);
}
else {
for (auto &i:level[lvl]) {
if (i.f % sz != 0) {
auto v=*i.s;
for(auto x:v) {
ans[x] += i.f;
}
} else {
level[lvl+1][i.f/sz]=i.s;
}
}
for (auto &i:queries[u]) {
if (i.f % sz != 0) {
ans[i.s] += i.f;
} else {
if(level[lvl+1].count(i.f/sz)==0){
level[lvl+1][i.f/sz]=new vector<int>();
}
level[lvl+1][i.f/sz]->pb(i.s);
}
}
}
for(auto i:g[u]){
dfs(i,lvl+1);
}
if(g[u].size()==1){
swap(level[lvl+1],level[lvl]);
}
else{
for (auto &i:queries[u]) {
if (i.f % sz != 0) {
} else {
level[lvl+1][i.f/sz]->pop_back();
}
}
}
level[lvl+1].clear();
}
void terminator() {
int n;
cin>>n;
forn(i,n-1){
int u;
cin>>u;
g[u].pb(i+2);
}
dfsleaf(1);
int q;
cin>>q;
for(int i=0;i<q;i++){
ll v,k;
cin>>v>>k;
queries[v].pb({k,i});
}
dfs(1,1);
forn(i,q){
cout<<ans[i]<<endl;
}
}
int32_t main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t = 1, tc = 1;
while (t--) {
terminator();
tc++;
}
return 0;
} | [
"akashnishad2017@gmail.com"
] | akashnishad2017@gmail.com |
ef5c7364440730121d73f6cfb1c08fe6e2f871ba | 9424cfe19b1db4e60ab9ff483fd67d3ad4ec81bd | /include/Shared/NetProtocol.h | 0b007cfff9f1e7fb4fd67374ea2ae8b9b760a180 | [] | no_license | kiwon0905/PT | 64c51d4a93c50cb1bf810750fc1696a1a951b87e | facab17f518e22bd36fd91f0cf83a73c2fc491b6 | refs/heads/master | 2021-01-18T14:09:54.148016 | 2016-10-15T22:13:26 | 2016-10-15T22:13:26 | 16,738,395 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 780 | h | #pragma once
#include <SFML/Network.hpp>
enum class Cl : sf::Int32
{
RequestJoin,
Ready,
Chat, //name, msg
GameEvent
};
enum class Sv : sf::Int32
{
Yes,
No,
ReplyJoin,
PlayerJoined,
PlayerDisconnected,
Chat,
LoadGame,
StartGame,
GameMapData,
PlayersData,
GameEvent
};
//packet operators for enum
template <typename Enum>
typename std::enable_if<std::is_enum<Enum>::value, sf::Packet&>::type
operator<< (sf::Packet& packet, Enum t)
{
return packet << static_cast<typename std::underlying_type<Enum>::type>(t);
}
template <typename Enum>
typename std::enable_if<std::is_enum<Enum>::value, sf::Packet&>::type
operator>> (sf::Packet& packet, Enum & t)
{
typename std::underlying_type<Enum>::type i;
packet >> i;
t = static_cast<Enum>(i);
return packet;
} | [
"kiwon0905@gmail.com"
] | kiwon0905@gmail.com |
18a43397918787c82036a706f084ecadcb4ffb12 | 67f988dedfd8ae049d982d1a8213bb83233d90de | /external/chromium/chrome/browser/policy/logging_work_scheduler_unittest.cc | 6e792b64a131ea12622fbc7048b79d4f183e8a1f | [
"BSD-3-Clause"
] | permissive | opensourceyouthprogramming/h5vcc | 94a668a9384cc3096a365396b5e4d1d3e02aacc4 | d55d074539ba4555e69e9b9a41e5deb9b9d26c5b | refs/heads/master | 2020-04-20T04:57:47.419922 | 2019-02-12T00:56:14 | 2019-02-12T00:56:14 | 168,643,719 | 1 | 1 | null | 2019-02-12T00:49:49 | 2019-02-01T04:47:32 | C++ | UTF-8 | C++ | false | false | 2,942 | cc | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/policy/logging_work_scheduler.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "content/public/test/test_browser_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
using content::BrowserThread;
namespace policy {
class LoggingWorkSchedulerTest : public testing::Test {
public:
LoggingWorkSchedulerTest()
: ui_thread_(BrowserThread::UI, &loop_) {
}
virtual ~LoggingWorkSchedulerTest() {
}
virtual void TearDown() {
scheduler1_.reset();
scheduler2_.reset();
logger_.reset();
}
protected:
void Callback1() {
logger_->RegisterEvent();
if (count1_ > 0) {
count1_--;
scheduler1_->PostDelayedWork(
base::Bind(&LoggingWorkSchedulerTest::Callback1,
base::Unretained(this)), delay1_);
}
}
void Callback2() {
logger_->RegisterEvent();
if (count2_ > 0) {
count2_--;
scheduler2_->PostDelayedWork(
base::Bind(&LoggingWorkSchedulerTest::Callback2,
base::Unretained(this)), delay2_);
}
}
protected:
scoped_ptr<EventLogger> logger_;
// The first scheduler will fire |count1_| events with |delay1_| pauses
// between each.
scoped_ptr<LoggingWorkScheduler> scheduler1_;
int count1_;
int delay1_;
// The second scheduler will fire |count2_| events with |delay2_| pauses
// between each.
scoped_ptr<LoggingWorkScheduler> scheduler2_;
int count2_;
int delay2_;
MessageLoop loop_;
private:
content::TestBrowserThread ui_thread_;
DISALLOW_COPY_AND_ASSIGN(LoggingWorkSchedulerTest);
};
TEST_F(LoggingWorkSchedulerTest, LoggerTest) {
logger_.reset(new EventLogger);
scheduler1_.reset(new LoggingWorkScheduler(logger_.get()));
scheduler2_.reset(new LoggingWorkScheduler(logger_.get()));
// Configure the first scheduler to fire at 0, 30, 60, 90, 120.
count1_ = 4;
delay1_ = 30;
// Configure the first scheduler to fire at 0, 40, 80, 120.
count2_ = 3;
delay2_ = 40;
Callback1();
Callback2();
loop_.RunUntilIdle();
std::vector<int64> events;
logger_->Swap(&events);
EXPECT_EQ(9u, events.size());
EXPECT_EQ(0, events[0]);
EXPECT_EQ(0, events[1]);
EXPECT_EQ(30, events[2]);
EXPECT_EQ(40, events[3]);
EXPECT_EQ(60, events[4]);
EXPECT_EQ(80, events[5]);
EXPECT_EQ(90, events[6]);
EXPECT_EQ(120, events[7]);
EXPECT_EQ(120, events[8]);
EXPECT_EQ(0, EventLogger::CountEvents(events, 0, 0));
EXPECT_EQ(2, EventLogger::CountEvents(events, 0, 1));
EXPECT_EQ(4, EventLogger::CountEvents(events, 30, 51));
EXPECT_EQ(7, EventLogger::CountEvents(events, 0, 120));
EXPECT_EQ(7, EventLogger::CountEvents(events, 1, 120));
}
} // namespace policy
| [
"rjogrady@google.com"
] | rjogrady@google.com |
694f4a2aebf6a0fc81daf6e019ffb48376f6e151 | 1585c7e187eec165138edbc5f1b5f01d3343232f | /СПиОС/PiChat/PiChat/PiChat/PiChat.cpp | ef696d2da4243a9a3e223085a2bcefa504148ae7 | [] | no_license | a-27m/vssdb | c8885f479a709dd59adbb888267a03fb3b0c3afb | d86944d4d93fd722e9c27cb134256da16842f279 | refs/heads/master | 2022-08-05T06:50:12.743300 | 2011-06-23T08:35:44 | 2011-06-23T08:35:44 | 82,612,001 | 1 | 0 | null | 2021-03-29T08:05:33 | 2017-02-20T23:07:03 | C# | UTF-8 | C++ | false | false | 3,085 | cpp | // PiChat.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "PiChat.h"
#include "MainFrm.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CPiChatApp
BEGIN_MESSAGE_MAP(CPiChatApp, CWinApp)
ON_COMMAND(ID_APP_ABOUT, &CPiChatApp::OnAppAbout)
END_MESSAGE_MAP()
// CPiChatApp construction
CPiChatApp::CPiChatApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
// The one and only CPiChatApp object
CPiChatApp theApp;
// CPiChatApp initialization
BOOL CPiChatApp::InitInstance()
{
// InitCommonControlsEx() is required on Windows XP if an application
// manifest specifies use of ComCtl32.dll version 6 or later to enable
// visual styles. Otherwise, any window creation will fail.
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// Set this to include all the common control classes you want to use
// in your application.
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinApp::InitInstance();
// Initialize OLE libraries
if (!AfxOleInit())
{
AfxMessageBox(IDP_OLE_INIT_FAILED);
return FALSE;
}
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need
// Change the registry key under which our settings are stored
// TODO: You should modify this string to be something appropriate
// such as the name of your company or organization
SetRegistryKey(_T("Local AppWizard-Generated Applications"));
// To create the main window, this code creates a new frame window
// object and then sets it as the application's main window object
CMainFrame* pFrame = new CMainFrame;
if (!pFrame)
return FALSE;
m_pMainWnd = pFrame;
// create and load the frame with its resources
pFrame->LoadFrame(IDR_MAINFRAME,
WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, NULL,
NULL);
// The one and only window has been initialized, so show and update it
pFrame->ShowWindow(SW_SHOW);
pFrame->UpdateWindow();
// call DragAcceptFiles only if there's a suffix
// In an SDI app, this should occur after ProcessShellCommand
return TRUE;
}
// CPiChatApp message handlers
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()
// App command to run the dialog
void CPiChatApp::OnAppAbout()
{
CAboutDlg aboutDlg;
aboutDlg.DoModal();
}
// CPiChatApp message handlers
| [
"Axell@bf672a44-3a04-1d4a-850b-c2a239875c8c"
] | Axell@bf672a44-3a04-1d4a-850b-c2a239875c8c |
1a2733c20bc2f53f0eeed9318ff7f04ca66e17c9 | 0e9394230899fd0df0c891a83131883f4451bcb9 | /test/function/simd/is_lessgreater.cpp | b097ed25f4b35451eae6563cf82d78a16edb1ae1 | [
"BSL-1.0"
] | permissive | WillowOfTheBorder/boost.simd | f75764485424490302291fbe9856d10eb55cdbf6 | 561316cc54bdc6353ca78f3b6d7e9120acd11144 | refs/heads/master | 2022-05-02T07:07:29.560118 | 2016-04-21T12:53:10 | 2016-04-21T12:53:10 | 59,155,554 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,476 | cpp | //==================================================================================================
/*!
@file
Copyright 2016 NumScale SAS
Copyright 2016 J.T. Lapreste
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#include <boost/simd/pack.hpp>
#include <boost/simd/function/is_lessgreater.hpp>
#include <boost/simd/constant/nan.hpp>
#include <boost/simd/meta/cardinal_of.hpp>
#include <boost/simd/logical.hpp>
#include <simd_test.hpp>
template <typename T, std::size_t N, typename Env>
void test(Env& $)
{
namespace bs = boost::simd;
using p_t = bs::pack<T, N>;
namespace bs = boost::simd;
namespace bd = boost::dispatch;
using pl_t = bs::pack<bs::logical<T>, N>;
bs::logical<T> b[N];
T a1[N], a2[N];
for(std::size_t i = 0; i < N; ++i)
{
a1[i] = (i%2) ? T(i) : bs::Nan<T>();
a2[i] = (i%2) ? T(i+N) : T(-(i+N));
b[i] = bs::is_lessgreater(a1[i], a2[i]);
}
p_t aa1(&a1[0], &a1[N]);
p_t aa2(&a2[0], &a2[N]);
pl_t bb(&b[0], &b[N]);
STF_IEEE_EQUAL(bs::is_lessgreater(aa1, aa2), bb);
}
STF_CASE_TPL("Check is_lessgreater on pack" , STF_NUMERIC_TYPES)
{
namespace bs = boost::simd;
using p_t = bs::pack<T>;
static const std::size_t N = bs::cardinal_of<p_t>::value;
test<T, N>($);
test<T, N/2>($);
test<T, N*2>($);
}
| [
"charly.chevalier@numscale.com"
] | charly.chevalier@numscale.com |
918dfe61c293bdc24fce65ec83579895cf08d399 | dcb75b10a352d9cfc0ae31f28679a2d56b10b875 | /Source/Mordhau/VelocityBoxComponent.cpp | ec14977c8649064717baa9d70933dd08d8a3fd15 | [] | no_license | Net-Slayer/Mordhau_uSDK | df5a096c21eb43e910c9b90c69ece495384608e0 | c4ff76b5d7462fc6ccad176bd8f1db2efdd2c910 | refs/heads/master | 2023-04-28T02:48:14.072100 | 2021-12-15T16:35:08 | 2021-12-15T16:35:08 | 301,417,546 | 3 | 1 | null | 2021-08-23T13:23:29 | 2020-10-05T13:26:39 | C++ | UTF-8 | C++ | false | false | 118 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "VelocityBoxComponent.h"
| [
"talon_hq@outlook.com"
] | talon_hq@outlook.com |
07a28532043be227ce5f02e069f74a8ceaf8640f | 006789571d7df823ab4730ed1ab9e71e23acfadb | /LiveShader/LiveShader.cpp | 3a882e51071dc58a4fff37dbe880b43ca4350166 | [] | no_license | PetrosGiannopoulos/LiveShaderCodeEditor | 819fdb30a2897166f9cf236f0ecf301a929134e0 | 16779692eff8978622350cb60d4e55028693e724 | refs/heads/master | 2020-08-05T00:08:04.540377 | 2020-02-08T21:10:11 | 2020-02-08T21:10:11 | 212,324,668 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,685 | cpp | // LiveShader.cpp : Defines the entry point for the console application.
//
#include <iostream>
#include "Graphics.h"
using namespace std;
void resizeWrapper(GLFWwindow* window, int width, int height);
void mouseWrapper(GLFWwindow* window, double xpos, double ypos);
void scrollWrapper(GLFWwindow* window, double xpos, double ypos);
void keyWrapper(GLFWwindow* window, int key, int scancode, int action, int mods);
void characterWrapper(GLFWwindow* window, unsigned int keycode);
Graphics *graphics;
int main()
{
graphics = new Graphics();
glfwSetFramebufferSizeCallback(graphics->window, resizeWrapper);
glfwSetCursorPosCallback(graphics->window, mouseWrapper);
glfwSetScrollCallback(graphics->window, scrollWrapper);
glfwSetKeyCallback(graphics->window, keyWrapper);
glfwSetCharCallback(graphics->window, characterWrapper);
glfwSetInputMode(graphics->window,GLFW_STICKY_KEYS, 1);
graphics->mainLoop();
graphics->terminate();
system("pause");
return 0;
}
void resizeWrapper(GLFWwindow* window, int width, int height) {
graphics->framebuffer_resize_callback(window, width, height);
}
void mouseWrapper(GLFWwindow* window, double xpos, double ypos) {
graphics->mouse_callback(window, xpos, ypos);
}
void scrollWrapper(GLFWwindow* window, double xoffset, double yoffset) {
graphics->scroll_callback(window, xoffset, yoffset);
}
void keyWrapper(GLFWwindow* window, int key, int scancode, int action, int mods) {
graphics->key_callback(window, key, scancode, action, mods);
}
void characterWrapper(GLFWwindow* window, unsigned int keycode) {
graphics->character_callback(window, keycode);
}
| [
"noreply@github.com"
] | noreply@github.com |
4c73ba8de658dbcb301e1ec67ed2ff16171b89f8 | f3fc5b2f6cd2b4c199696bc6ce02c7850a8b1363 | /src/hdt_adroit_driver/include/hdt_adroit_driver/hdt_adroit_coms.h | 8780a3069425b1ec9023236d1d3e8ed39b42d4d9 | [] | no_license | sagivald/hdt_rlb_vr | 67ddeed46337381b3dd831ccd1661fc7529b8c34 | 897a0bb4e7626ad20cfec65a0e2e0047c230b09c | refs/heads/master | 2021-09-14T04:19:40.191201 | 2018-05-08T12:18:48 | 2018-05-08T12:18:48 | 105,557,898 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,464 | h | #ifndef hdt_adroit_coms_h
#define hdt_adroit_coms_h
#include "AdroitComs.h"
#define ROS_NAME "hdt_adroit_coms"
#define SAMPLE_RATE 50.0
#define SAMPLE_PERIOD 1.0/SAMPLE_RATE
#define DEBUG_MSG_RATE 2*500/SAMPLE_RATE
#define HDT_TELEM_TOPIC "/hdt_adroit_coms/hdt_telem"
#define JOINT_TELEM_TOPIC "/hdt_adroit_coms/joint_telem"
#define JOINT_CMD_TOPIC "/hdt_adroit_coms/joint_cmd"
#define HDT_JOINT_CMD_TOPIC "/hdt_adroit_coms/hdt_joint_cmd"
#define DRIVE_ERROR_TOPIC "/hdt_adroit_coms/drive_error"
#define MAX_DRIVE_CURRENT 13.5
#define COMS_READY_SERVICE "/hdt_adroit_coms/coms_ready"
#define WRITE_PARAM_SERVICE "/hdt_adroit_coms/write_drive_param"
#define READ_PARAM_SERVICE "/hdt_adroit_coms/read_drive_param"
#define APP_LOAD_SERVICE "/hdt_adroit_coms/app_load"
#define STATE_SELECT_SERVICE "/hdt_adroit_coms/state_select"
#define GET_STATUS_SERVICE "/hdt_adroit_coms/get_status"
#define COMMIT_SERVICE "/hdt_adroit_coms/commit"
#define INIT_WAIT_TIME 1000000
#define JOINT_CMD_TIMEOUT 0.5
// coms interface class
class AdroitInterface: public AdroitComs {
public:
AdroitInterface() : AdroitComs(0) {};
~AdroitInterface() {};
virtual int Init(void) = 0;
virtual int SendMsg(AdroitMsg *adroit_msg) = 0;
virtual int ReceiveMsg(AdroitMsg *msg) = 0;
virtual int Write(void) = 0;
private:
};
#endif // hdt_adroit_coms_h
| [
"yossicohen2000@gmail.com"
] | yossicohen2000@gmail.com |
17f5d0929a7beecf3251b151f710b83e00934113 | 772ba9a64bde2ef4fb1eea1d330a378bfcd5bcab | /ReverseWordsInString/ReverseWordsInString/main.cpp | 2d4a5454d1080edded3d49d5bc61f39595ea14fa | [] | no_license | chrisbangun/Cplusplus | 821b83f226d31f2b6345c6670a7d7a58d5d071e6 | ec5d6dd789e53076d76b652a0e007e1671899abf | refs/heads/master | 2021-06-16T22:34:40.530477 | 2017-07-11T16:25:33 | 2017-07-11T16:25:33 | 39,341,540 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 536 | cpp | //
// main.cpp
// ReverseWordsInString
//
// Created by Adi Bangun on 17/06/2015.
// Copyright (c) 2015 Adi Bangun. All rights reserved.
//
#include <iostream>
using namespace std;
void printLexio(int n,int k){
for(int i=0;i<9;i++){
if(k<=n){
cout << k << endl;
k*=10;
printLexio(n,k);
k/=10;
k++;
}
else{
return ;
}
}
}
int main(int argc, char ** argv){
int n;
cin >> n;
printLexio(n,1);
return 0;
}
| [
"adibangun@Adis-MacBook-Pro.local"
] | adibangun@Adis-MacBook-Pro.local |
7a2e183b14eafdd1389b575ccd46d655185d2c69 | 694c83dbfbfa1350c62f4ba654e07d5b1409aff4 | /main.cpp | abf432b37a502b766e10b849067d3c6727f5fd7c | [] | no_license | manojsatya/GitTest | 9b986c7bcfbbea72ebf3589939ec3459b9015106 | 4fdcf1e359455867194c747035de8c939ea0ee03 | refs/heads/master | 2016-09-05T15:02:41.965144 | 2015-05-06T22:02:34 | 2015-05-06T22:02:34 | 35,184,347 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 153 | cpp | #include <iostream>
using namespace std;
int main (){
std::cout << "Hello World" << std::endl;
std::cout << "Good one" << std::endl;
return 0;
}
| [
"manoj@ubuntu.(none)"
] | manoj@ubuntu.(none) |
5d109a204426037d799c9912b8d10431385529ca | ac45d8b97e0cc3647990445d4be1184b38f6bea3 | /leetcode/trapping-rain-water.cpp | 21fc80a2d39ecb9e10798ee9f31bd0aca7b7a3c3 | [] | no_license | ytong3/coding_practice | 20d7071ace8121555fd97edfa82af4108551acf4 | 9d7fd7677bb2c84875bffa9b8f2620b43a4bad13 | refs/heads/master | 2021-01-10T01:09:17.308678 | 2014-03-25T17:34:49 | 2014-03-25T17:34:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 776 | cpp | //A similar approach to Stock III.
//The key observation is to divide the problem to subproblems of finding the water held in each bar! Divide and Conquer is really the way to go in many cases!
class Solution {
public:
int trap(int A[], int n) {
if (n<2) return 0;
//get the highest bar on the left for each bar (inclusive)
int left[n];
int right[n];
left[0]=A[0];
for (int i=1;i<n;i++){
left[i]=max(left[i-1],A[i]);
}
right[n-1]=A[n-1];
for (int i=n-2;i>=0;i--){
right[i]=max(right[i+1],A[i]);
}
int res(0);
for (int i=0;i<n;i++){
res+=min(left[i],right[i])-A[i];
}
return res;
}
}; | [
"ytong3@utk.edu"
] | ytong3@utk.edu |
8ab6856887b24ba1b352e1e5d438b2a003581dbe | fafce52a38479e8391173f58d76896afcba07847 | /uppsrc/ide/Annotations.cpp | d61398952666f25abdce7ab4954c6ba9d16beb54 | [
"BSD-2-Clause"
] | permissive | Sly14/upp-mirror | 253acac2ec86ad3a3f825679a871391810631e61 | ed9bc6028a6eed422b7daa21139a5e7cbb5f1fb7 | refs/heads/master | 2020-05-17T08:25:56.142366 | 2015-08-24T18:08:09 | 2015-08-24T18:08:09 | 41,750,819 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,288 | cpp | #include "ide.h"
void AssistEditor::Annotate(const String& filename)
{
int fi = GetSourceFileIndex(filename);
CppBase& base = CodeBase();
ClearAnnotations();
for(int j = 0; j < base.GetCount(); j++) {
String nest = base.GetKey(j);
if(*nest != '@') { // Annotations of anonymous structures not suported
const Array<CppItem>& n = base[j];
for(int k = 0; k < n.GetCount(); k++) {
const CppItem& m = n[k];
if(m.file == fi) {
String coderef = MakeCodeRef(nest, m.qitem);
SetAnnotation(m.line - 1,
GetRefLinks(coderef).GetCount() ? IdeImg::tpp_doc()
: IdeImg::tpp_pen(),
coderef);
}
}
}
}
}
bool IsCodeItem(RichText& txt, int i)
{
static Uuid codeitem = CodeItemUuid();
static Uuid stritem = StructItemUuid();
if(i < txt.GetPartCount() && txt.IsPara(i)) {
Uuid style = txt.GetParaStyle(i);
return style == codeitem || style == stritem;
}
return false;
}
bool IsBeginEnd(RichText& txt, int i)
{
static Uuid begin = BeginUuid();
static Uuid end = EndUuid();
if(i < txt.GetPartCount() && txt.IsPara(i)) {
Uuid style = txt.GetParaStyle(i);
return style == begin || style == end;
}
return false;
}
bool AssistEditor::GetAnnotationRefs(Vector<String>& tl, String& coderef, int q)
{
if(annotation_popup.IsOpen())
annotation_popup.Close();
if(q < 0)
q = GetActiveAnnotationLine();
if(q < 0)
return false;
coderef = GetAnnotation(q);
if(IsNull(coderef))
return false;
tl = GetRefLinks(coderef);
return true;
}
bool AssistEditor::GetAnnotationRef(String& t, String& coderef, int q)
{
Vector<String> tl;
if(!GetAnnotationRefs(tl, coderef, q))
return false;
if(tl.GetCount() == 0)
return true;
String path = theide ? theide->editfile : Null;
int mi = 0;
int m = 0;
for(int i = 0; i < tl.GetCount(); i++) {
int mm = GetMatchLen(tl[i], path);
if(mm > m) {
mi = i;
m = mm;
}
}
t = tl[mi];
return true;
}
void AssistEditor::SyncAnnotationPopup()
{
String coderef;
String tl;
if(!GetAnnotationRef(tl, coderef))
return;
if(tl.GetCount()) {
static String last_path;
static RichText topic_text;
String path = GetTopicPath(tl);
if(path != last_path)
topic_text = ParseQTF(ReadTopic(LoadFile(path)).text);
RichText result;
String cr = coderef;
for(int pass = 0; pass < 2; pass++) {
for(int i = 0; i < topic_text.GetPartCount(); i++)
if(IsCodeItem(topic_text, i) && topic_text.Get(i).format.label == cr) {
while(i > 0 && IsCodeItem(topic_text, i)) i--;
if(!IsCodeItem(topic_text, i)) i++;
while(IsCodeItem(topic_text, i))
result.Cat(topic_text.Get(i++));
while(i < topic_text.GetPartCount() && !IsCodeItem(topic_text, i)
&& !IsBeginEnd(topic_text, i)) {
if(topic_text.IsPara(i))
result.Cat(topic_text.Get(i++));
else {
RichTable table(topic_text.GetTable(i++), 1);
result.CatPick(pick(table));
}
}
pass = 2;
break;
}
if(pass == 0 && !LegacyRef(cr))
break;
}
result.SetStyles(topic_text.GetStyles());
annotation_popup.Pick(pick(result), GetRichTextStdScreenZoom());
}
else
if(SyncRefsFinished)
annotation_popup.SetQTF("[A1 [@b* " + DeQtf(coderef) + "]&Not documented yet - click to document");
else
annotation_popup.SetQTF("[A1 [@b* " + DeQtf(coderef) + "]&Documentation not loaded yet");
Rect r = GetLineScreenRect(GetActiveAnnotationLine());
int h = annotation_popup.GetHeight(580);
h = min(h, 550);
int y = r.top - h - 16;
if(y < GetWorkArea().top)
y = r.bottom;
annotation_popup.SetRect(r.left, y, 600, h + 16);
annotation_popup.Ctrl::PopUp(this, false, false, true);
}
void AssistEditor::OpenTopic(String topic, String create, bool before)
{
if(theide)
theide->OpenTopic(topic, create, before);
}
void AssistEditor::NewTopic(String group, String coderef)
{
if(!theide)
return;
String ef = theide->editfile;
String n = GetFileTitle(ef);
theide->EditFile(AppendFileName(PackageDirectory(theide->GetActivePackage()), group + ".tpp"));
if(!theide->designer)
return;
TopicEditor *te = dynamic_cast<TopicEditor *>(&theide->designer->DesignerCtrl());
if(!te)
return;
String scope, item;
SplitCodeRef(coderef, scope, item);
if(!te->NewTopicEx(IsNull(scope) ? n : Join(Split(scope, ':'), "_"), coderef))
theide->EditFile(ef);
}
void AssistEditor::EditAnnotation(bool fastedit)
{
if(!SyncRefsFinished)
return;
String coderef;
Vector<String> tl;
if(!GetAnnotationRefs(tl, coderef))
return;
SetCursor(GetPos(GetActiveAnnotationLine()));
if(tl.GetCount() > 1) {
MenuBar bar;
for(int i = 0; i < tl.GetCount(); i++)
bar.Add(tl[i], THISBACK3(OpenTopic, tl[i] + '#' + coderef, String(), false));
bar.Execute();
return;
}
if(tl.GetCount()) {
OpenTopic(tl[0] + '#' + coderef, String(), false);
return;
}
String scope, item;
SplitCodeRef(coderef, scope, item);
const CppItem *m = GetCodeRefItem(coderef);
int access = m ? m->access : 0;
VectorMap<String, String> tpp;
int backi = 0;
for(int pass = 0; pass < 2; pass++) {
for(int i = GetCursorLine(); pass ? i < GetLineCount() : i >= 0; pass ? i++ : i--) {
String coderef2;
if(GetAnnotationRefs(tl, coderef2, i) && tl.GetCount()) {
String scope2, item2;
SplitCodeRef(coderef2, scope2, item2);
m = GetCodeRefItem(coderef2);
if(scope2 == scope && m && m->access == access && tl.GetCount() == 1 && fastedit) {
OpenTopic(tl[0] + '#' + coderef2, coderef, false);
return;
}
for(int j = 0; j < tl.GetCount(); j++)
if(tpp.Find(tl[j]) < 0)
tpp.Add(tl[j], coderef2);
}
}
if(pass == 0)
backi = tpp.GetCount();
}
MenuBar bar;
if(tpp.GetCount()) {
for(int i = 0; i < tpp.GetCount(); i++) {
String l = tpp.GetKey(i);
bar.Add(l, THISBACK3(OpenTopic, l + '#' + tpp[i], coderef, i >= backi));
}
bar.Separator();
}
bar.Add("New reference topic..", THISBACK2(NewTopic, "src", coderef));
bar.Add("New implementation topic..", THISBACK2(NewTopic, "srcimp", coderef));
bar.Execute();
}
| [
"cxl@05275033-79c2-2956-22f4-0a99e774df92"
] | cxl@05275033-79c2-2956-22f4-0a99e774df92 |
e7c1b5b236fa4eb38d105e294043d4283667ab73 | d349229fd67b4fe60b5365821de446672f4cbf60 | /red/4_web_server_stats/stats.h | d7db059433b9159dcf7883920120ae75bbc75c8c | [] | no_license | Rokenrosh/c_plus_plus_specialization | 938978d3871ed5f29dedc6103bad2ee940c94d7d | 34889ce7307094219ecabe00a228f8cfa1713df1 | refs/heads/master | 2023-01-27T20:18:40.528493 | 2020-12-07T20:00:22 | 2020-12-07T20:00:22 | 292,908,233 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 459 | h | #pragma once
#include "http_request.h"
#include <string_view>
#include <map>
#include <algorithm>
using namespace std;
class Stats {
public:
Stats();
void AddMethod(string_view method);
void AddUri(string_view uri);
const map<string_view, int>& GetMethodStats() const;
const map<string_view, int>& GetUriStats() const;
private:
map<string_view, int> method_stats, uri_stats;
};
HttpRequest ParseRequest(string_view line);
| [
"noreply@github.com"
] | noreply@github.com |
bbfba248d7aeb4e9150d5d49dc5ab6314c9aa584 | e3ab710ada6ac68f169b4e1ee68bf8b94f959cc6 | /thrift/lib/cpp2/protocol/NimbleProtocol.h | 5f3e8a7b7740fcbf5e9a755d68db43942a4ecc6a | [
"Apache-2.0"
] | permissive | blockspacer/fbthrift | 073d55d97de499de6f2e52cb871670f156d10794 | d83845a575f5e2ac9d7cfdff44dc0c57a00c9d0a | refs/heads/master | 2020-08-06T12:15:44.687620 | 2019-10-05T06:25:52 | 2019-10-05T06:27:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,604 | h | /*
* Copyright 2019-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <folly/io/Cursor.h>
#include <folly/portability/GFlags.h>
#include <thrift/lib/cpp/protocol/TProtocol.h>
#include <thrift/lib/cpp/util/BitwiseCast.h>
#include <thrift/lib/cpp2/protocol/Protocol.h>
#include <thrift/lib/cpp2/protocol/ProtocolReaderWireTypeInfo.h>
#include <thrift/lib/cpp2/protocol/nimble/Decoder.h>
#include <thrift/lib/cpp2/protocol/nimble/Encoder.h>
#include <thrift/lib/cpp2/protocol/nimble/NimbleTypes.h>
DECLARE_int32(thrift_cpp2_protocol_reader_string_limit);
DECLARE_int32(thrift_cpp2_protocol_reader_container_limit);
namespace apache {
namespace thrift {
using folly::io::Cursor;
class NimbleProtocolReader;
class NimbleProtocolWriter {
public:
using ProtocolReader = NimbleProtocolReader;
static constexpr bool kSortKeys() {
return false;
}
uint32_t writeMessageBegin(
const std::string& name,
MessageType messageType,
int32_t seqid);
uint32_t writeMessageEnd();
uint32_t writeStructBegin(const char* name);
uint32_t writeStructEnd();
uint32_t writeFieldBegin(const char* name, TType fieldType, int16_t fieldId);
uint32_t writeFieldEnd();
uint32_t writeFieldStop();
uint32_t writeMapBegin(TType keyType, TType valType, uint32_t size);
uint32_t writeMapEnd();
uint32_t writeCollectionBegin(TType elemType, uint32_t size);
uint32_t writeListBegin(TType elemType, uint32_t size);
uint32_t writeListEnd();
uint32_t writeSetBegin(TType elemType, uint32_t size);
uint32_t writeSetEnd();
uint32_t writeBool(bool value);
uint32_t writeByte(int8_t byte);
uint32_t writeI16(int16_t i16);
uint32_t writeI32(int32_t i32);
uint32_t writeI64(int64_t i64);
uint32_t writeDouble(double dub);
uint32_t writeFloat(float flt);
uint32_t writeString(folly::StringPiece str);
uint32_t writeBinary(folly::StringPiece str);
uint32_t writeBinary(folly::ByteRange str);
uint32_t writeBinary(const std::unique_ptr<folly::IOBuf>& str);
uint32_t writeBinary(const folly::IOBuf& str);
uint32_t writeSerializedData(const std::unique_ptr<folly::IOBuf>& /*data*/);
/**
* Functions that return the serialized size
*/
uint32_t serializedMessageSize(const std::string& name) const;
uint32_t
serializedFieldSize(const char* name, TType fieldType, int16_t fieldId) const;
uint32_t serializedStructSize(const char* name) const;
uint32_t serializedSizeMapBegin(TType keyType, TType valType, uint32_t size)
const;
uint32_t serializedSizeMapEnd() const;
uint32_t serializedSizeListBegin(TType elemType, uint32_t size) const;
uint32_t serializedSizeListEnd() const;
uint32_t serializedSizeSetBegin(TType elemType, uint32_t size) const;
uint32_t serializedSizeSetEnd() const;
uint32_t serializedSizeStop() const;
uint32_t serializedSizeBool(bool = false) const;
uint32_t serializedSizeByte(int8_t = 0) const;
uint32_t serializedSizeI16(int16_t = 0) const;
uint32_t serializedSizeI32(int32_t = 0) const;
uint32_t serializedSizeI64(int64_t = 0) const;
uint32_t serializedSizeDouble(double = 0.0) const;
uint32_t serializedSizeFloat(float = 0) const;
uint32_t serializedSizeString(folly::StringPiece str) const;
uint32_t serializedSizeBinary(folly::StringPiece str) const;
uint32_t serializedSizeBinary(folly::ByteRange v) const;
uint32_t serializedSizeBinary(std::unique_ptr<folly::IOBuf> const& v) const;
uint32_t serializedSizeBinary(folly::IOBuf const& v) const;
uint32_t serializedSizeZCBinary(folly::StringPiece str) const;
uint32_t serializedSizeZCBinary(folly::ByteRange v) const;
uint32_t serializedSizeZCBinary(
std::unique_ptr<folly::IOBuf> const& /*v*/) const;
uint32_t serializedSizeZCBinary(folly::IOBuf const& /*v*/) const;
uint32_t serializedSizeSerializedData(
std::unique_ptr<folly::IOBuf> const& /*data*/) const;
std::unique_ptr<folly::IOBuf> finalize() {
return encoder_.finalize();
}
private:
/*
* The encoder that manipulates the underlying field and content streams.
*/
detail::Encoder encoder_;
};
class NimbleProtocolReader {
using NimbleType = detail::nimble::NimbleType;
public:
using ProtocolWriter = NimbleProtocolWriter;
explicit NimbleProtocolReader(
int32_t string_limit = FLAGS_thrift_cpp2_protocol_reader_string_limit,
int32_t container_limit =
FLAGS_thrift_cpp2_protocol_reader_container_limit)
: string_limit_(string_limit), container_limit_(container_limit) {
if (string_limit_ <= 0) {
string_limit_ = INT32_MAX;
}
if (container_limit_ <= 0) {
container_limit_ = INT32_MAX;
}
}
static constexpr bool kUsesFieldNames() {
return false;
}
static constexpr bool kOmitsContainerSizes() {
return false;
}
void setInput(const folly::io::Cursor& cursor) {
decoder_.setInput(cursor);
}
/**
* Reading functions
*/
void
readMessageBegin(std::string& name, MessageType& messageType, int32_t& seqid);
void readMessageEnd();
void readStructBegin(const std::string& name);
void readStructEnd();
void
readFieldBegin(std::string& name, NimbleType& fieldType, int16_t& fieldId);
void readFieldEnd();
void readMapBegin(NimbleType& keyType, NimbleType& valType, uint32_t& size);
void readMapEnd();
void readListBegin(NimbleType& elemType, uint32_t& size);
void readListEnd();
void readSetBegin(NimbleType& elemType, uint32_t& size);
void readSetEnd();
void readBool(bool& value);
void readBool(std::vector<bool>::reference value);
void readByte(int8_t& byte);
void readI16(int16_t& i16);
void readI32(int32_t& i32);
void readI64(int64_t& i64);
void readDouble(double& dub);
void readFloat(float& flt);
template <typename StrType>
void readString(StrType& str);
template <typename StrType>
void readBinary(StrType& str);
void readBinary(std::unique_ptr<folly::IOBuf>& str);
void readBinary(folly::IOBuf& str);
void skip(NimbleType /*type*/) {}
bool peekMap() {
return false;
}
bool peekSet() {
return false;
}
bool peekList() {
return false;
}
const Cursor& getCursor() const {
throw std::logic_error(
"NimbleProtocolReader doesn't expose the underlying cursor.");
}
size_t getCursorPosition() const {
return 0;
}
struct StructReadState {
int16_t fieldId;
detail::nimble::NimbleType nimbleType;
void readStructBegin(NimbleProtocolReader* iprot) {
iprot->readStructBegin("");
}
void readStructEnd(NimbleProtocolReader* /*iprot*/) {}
void readFieldBegin(NimbleProtocolReader* iprot) {
iprot->advanceToNextFieldSlow(*this);
}
FOLLY_NOINLINE void readFieldBeginNoInline(
NimbleProtocolReader* /*iprot*/) {}
void readFieldEnd(NimbleProtocolReader* /*iprot*/) {}
FOLLY_ALWAYS_INLINE bool advanceToNextField(
NimbleProtocolReader* iprot,
int32_t currFieldId,
int32_t nextFieldId,
TType nextFieldType) {
return iprot->advanceToNextField(
currFieldId, nextFieldId, nextFieldType, *this);
}
void afterAdvanceFailure(NimbleProtocolReader* iprot) {
iprot->advanceToNextFieldSlow(*this);
}
bool atStop() {
// Note that this might not correspond to a fieldID of 0 (and in fact,
// never should); it's only safe to look at the type in this instance.
// This makes advanceToNextFieldSlow slightly simpler, since it lets it
// unconditionally set the field ID to the adjusted field ID indicated by
// the high bits.
return nimbleType == detail::nimble::NimbleType::STOP;
}
FOLLY_ALWAYS_INLINE bool isCompatibleWithType(
NimbleProtocolReader* iprot,
TType expectedFieldType) {
return iprot->isCompatibleWithType(expectedFieldType, *this);
}
[[noreturn]] inline void skip(NimbleProtocolReader* iprot) {
iprot->skip(*this);
}
std::string& fieldName() {
throw std::logic_error("NimbleProtocol doesn't support field names");
}
template <typename StructTraits>
void fillFieldTraitsFromName() {
throw std::logic_error("NimbleProtocol doesn't support field names");
}
};
protected:
FOLLY_ALWAYS_INLINE bool advanceToNextField(
int32_t currFieldId,
int32_t nextFieldId,
TType type,
StructReadState& state);
void advanceToNextFieldSlow(StructReadState& state);
FOLLY_ALWAYS_INLINE bool isCompatibleWithType(
TType expectedFieldType,
StructReadState& state);
/* The actual method that does skip when there is a mismatch */
[[noreturn]] void skip(StructReadState& state);
private:
detail::Decoder decoder_;
int32_t string_limit_;
int32_t container_limit_;
};
namespace detail {
template <class Protocol>
struct ProtocolReaderStructReadState;
template <>
struct ProtocolReaderStructReadState<NimbleProtocolReader>
: NimbleProtocolReader::StructReadState {};
template <>
struct ProtocolReaderWireTypeInfo<NimbleProtocolReader> {
using WireType = nimble::NimbleType;
static WireType fromTType(apache::thrift::protocol::TType ttype) {
return nimble::ttypeToNimbleType(ttype);
}
static WireType defaultValue() {
return nimble::NimbleType::STOP;
}
};
} // namespace detail
template <>
inline void skip<NimbleProtocolReader, detail::nimble::NimbleType>(
NimbleProtocolReader& /* prot */,
detail::nimble::NimbleType /* arg_type */) {
// Fool the noreturn warning; we can't add the annotation without breaking
// interface compatibility.
volatile bool b = true;
if (b) {
throw std::runtime_error("Not implemented yet");
}
}
template <>
inline void skip_n<NimbleProtocolReader, detail::nimble::NimbleType>(
NimbleProtocolReader& /* prot */,
std::uint32_t /* n */,
std::initializer_list<detail::nimble::NimbleType> /* types*/) {
volatile bool b = true;
if (b) {
throw std::runtime_error("Not implemented yet");
}
}
} // namespace thrift
} // namespace apache
#include <thrift/lib/cpp2/protocol/NimbleProtocol-inl.h>
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
a7a8dd8cc2fd5bfeb0a72419263b2fa6bcf43f97 | ba9485e8ea33acee24dc7bd61049ecfe9f8b8930 | /ac/abc188/C/main.cpp | 9716b23f27afc58a0d66e6aeb29563414062fd6e | [] | no_license | diohabara/competitive_programming | a0b90a74b0b923a636b9c82c75b690fef11fe8a4 | 1fb493eb44ce03e289d1245bf7d3dc450f513135 | refs/heads/master | 2021-12-11T22:43:40.925262 | 2021-11-06T12:56:49 | 2021-11-06T12:56:49 | 166,757,685 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 752 | cpp | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
const ll MOD = 1e9 + 7;
const ll INF = 1e18;
ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }
ll lcm(ll a, ll b) { return a / gcd(a, b) * b; }
int main() {
// input
int N;
cin >> N;
vector<int> A(1 << N);
rep(i, 1 << N) cin >> A[i];
// solve
unordered_map<int, int> indexOfRate;
rep(i, A.size()) { indexOfRate[A[i]] = (i + 1); }
while (A.size() != 2) {
vector<int> tmpVec(A.size() / 2);
for (int i = 0; i < A.size() / 2; i++) {
tmpVec[i] = max(A[2 * i], A[2 * i + 1]);
}
A = tmpVec;
}
int lastLoser = *min_element(A.begin(), A.end());
cout << indexOfRate[lastLoser] << endl;
}
| [
"diohabara@gmail.com"
] | diohabara@gmail.com |
3954c7397861d49372970b4a3c3efe82c3040507 | 7fda176ef12ccf4299159f41bf4dbe1d98f0daab | /src/cd++/model/model.h | 9b026796b672c6cfc253c16245b321bb5b079863 | [
"MIT"
] | permissive | SimulationEverywhere/CDPP_ExtendedStates-codename-Santi | d18bb4c04e2b51d9952567db878db824cc010b49 | 140085e43ce3a60ead8f806d2f7d19f7df431709 | refs/heads/master | 2022-08-24T14:23:10.098163 | 2022-08-15T18:14:23 | 2022-08-15T18:14:23 | 150,471,965 | 5 | 6 | MIT | 2022-08-15T18:08:16 | 2018-09-26T18:29:24 | C++ | UTF-8 | C++ | false | false | 4,965 | h | /*******************************************************************
*
* DESCRIPTION: class Model(base class for Amtomic and Coupled)
*
* AUTHOR: Amir Barylko & Jorge Boyoglonian
* Version 2: Daniel Rodriguez
* Version 3: Alejandro Troccoli
*
* EMAIL: mailto://amir@dc.uba.ar
* mailto://jbeyoglo@dc.uba.ar
* mailto://drodrigu@dc.uba.ar
* mailto://atroccol@dc.uba.ar
*
* DATE: 27/6/1998
* DATE: 27/2/1999 (v2)
*
*******************************************************************/
#ifndef __MODEL_H
#define __MODEL_H
/** include files **/
#include <string> // Template std::string
#include <map>
#include "machineid.h" //type MachineId
#include "port.h" // class Port
#include "VTime.h" // class VTime
#include "portlist.h"
#include "pprocadm.h"
#include "modelstate.h" //class ModelState
#include "value.h"
/** foward declarations **/
class ModelAdmin ;
class MessageAdmin ;
class Coupled ;
class Root ;
class Simulator ;
class ParallelSimulator;
class Processor ;
class ParallelProcessor;
class Coordinator ;
class SendPortNode ;
/** type definitions **/
typedef std::map<MachineId, ProcId, std::less <MachineId> > ModelPartition;
/** definitions **/
#define MODEL_NAME "Model"
class Model
{
public:
virtual ~Model(); // Destructor
virtual std::string className() const = 0;
virtual Port &addInputPort( const std::string & );
virtual Port &addOutputPort( const std::string & );
virtual const PortList &inputPorts() const
{return inputList;}
virtual const PortList &outputPorts() const
{return outputList;}
virtual PortList &inputPorts()
{return inputList;}
virtual PortList &outputPorts()
{return outputList;}
Port & port( const std::string & );
Port & port( const PortId & );
const VTime &nextChange() const
{return processor().nextChange();}
const VTime &lastChange() const
{return processor().lastChange();}
const ModelId &id() const
{return ident;}
const std::string &description() const
{return descript;}
const std::string asString() const
{return description() + "(" + id() + ")";}
const Model *parent() const
{return parentModel;}
Model &parent( Model *p )
{parentModel = p; return *this;}
bool operator <( const Model &model ) const
{return this->id() < model.id();}
// Model Partition Management Methods
Model &addMachine( const MachineId &mid );
Model &setMachineProcId( const MachineId &mid, const ProcId &pid);
const ProcId &procInMachine( const MachineId &mid) const;
const MachineId& machineForProcId( const ProcId &proc ) const;
const ProcId &localProc() const
{ return local_proc;}
const ProcId &masterId() const;
bool isLocalMaster() const;
const ModelPartition &modelPartition() const
{ return model_partition; }
//Id of the parent processor
const ProcId &parentId() const
{return parent_id;}
Model &parentId( const ProcId &mid )
{parent_id = mid; return *this;}
virtual unsigned long totalProcCount() const = 0;
virtual unsigned long localProcCount() const = 0;
protected:
friend class Processor ;
friend class ParallelProcessorAdmin;
friend class ParallelProcessor;
friend class Simulator ;
friend class ParallelMCellCoordinator;
friend class ParallelSCellCoordinator;
friend class ParallelSimulator;
friend class SendPortNode ;
friend class ParallelMainSimulator;
friend class ParallelRoot;
friend class ParallelModelAdmin;
Model( const std::string &name = "Model" ) ; // Default constructor
Model &nextChange( const VTime & );
Model &lastChange( const VTime & );
Model &id( const ModelId &mid )
{ident = mid; return *this;}
Model &sendOutput( const VTime &time, const Port &port, const double &value )
{processor().sendOutput( time, port, Real(value) ); return *this;}
Model &sendOutput( const VTime &time, const Port &port, const AbstractValue &value )
{processor().sendOutput( time, port, value ); return *this;}
Model &sendOutput( const VTime &time, const Port & port , BasicMsgValue *value)
{processor().sendOutput( time, port, value ); return *this;}
ParallelProcessor &processor() const;
Model &processor( ParallelProcessor * );
virtual ModelState* allocateState()
{return new ModelState;}
virtual ParallelProcessor& createParallelProcessor() = 0;
//This function will be called for each model after the processor
//has been initialized. This means each model with an associated
//has it's state available. It should be used, for instance, to
//load the initial values for cells, or the external events for
//the root.
virtual void afterProcessorInitialize(){};
private:
friend class ModelAdmin ;
friend class MessageAdmin ;
friend class Coupled ;
friend class Root ;
ModelId ident ;
ProcId local_proc; //For efficient retrieval
ProcId parent_id ;
Model *parentModel;
ParallelProcessor *proc;
std::string descript ;
ModelPartition model_partition;
PortList inputList ;
PortList outputList ;
}; // class Model
#endif //__MODEL_H
| [
"lukius@gmail.com"
] | lukius@gmail.com |
dfde70a7b8d02423cb00e662e8afa2691b28b6ae | a74c66c6aa47ba3be46fcb369961cd9783c5bcc4 | /test2.cpp | 525ee0a5cd17191f92df88955852c99b15d73433 | [] | no_license | windcry1/scpc.me | 54636fc0bdcc1d16f50d05eed19ffda5a4d7afbb | e194dfdd390a4df405cf7e383276ef8edadc73ea | refs/heads/master | 2020-12-04T10:21:59.916140 | 2020-01-07T13:25:49 | 2020-01-07T13:25:49 | 231,725,427 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 585 | cpp | #include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char a[100000];
char b[100000];
int arr[100000];
int brr[100000];
scanf("%s%s",a,b);
int len1=strlen(a);
int len2=strlen(b);
for(int i=0;i<=len1-1;i++)
{
arr[len1-i-1]=a[i]-'0';
}
for(int i=0;i<=len2-1;i++)
{
brr[len2-i-1]=b[i]-'0';
}
int max=0;
if(len1>len2)max=len1;
else max=len2;
for(int i=0;i<max;i++)
{
arr[i]+=brr[i];
if(arr[i]>=10)arr[i+1]++,arr[i]-=10;
}
if(arr[max]>0)printf("%d",arr[max]);
for(int i=max-1;i>=0;i--)
{
printf("%d",arr[i]);
}
printf("\n");
return 0;
}
| [
"lanceyu120@gmail.com"
] | lanceyu120@gmail.com |
1ccd3e1ff057e2e836f2568b62a978646eeef08d | 367be98d4ed7dde14d05f988c1606aaa60a60eb3 | /tests/api/mpi/comm/comm_idup.cc | 0a840eb17e7e5530b728857cf22fd63de97b1535 | [
"BSD-3-Clause"
] | permissive | nlslatt/sst-macro | acd3f043468cd13ab0843dff85493737ea5a843f | c0feb7e8d12bde3f0b1a505452276473f9b07ca3 | refs/heads/master | 2021-01-15T12:15:40.773962 | 2016-04-07T21:30:26 | 2016-04-07T21:39:55 | 59,328,703 | 0 | 0 | null | 2016-05-20T21:54:18 | 2016-05-20T21:54:17 | null | UTF-8 | C++ | false | false | 4,467 | cc | /* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil ; -*- */
/*
* (C) 2012 by Argonne National Laboratory.
* See COPYRIGHT in top-level directory.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sstmac/replacements/mpi.h>
#include "mpitest.h"
namespace comm_idup {
/* This is a temporary #ifdef to control whether we test this functionality. A
* configure-test or similar would be better. Eventually the MPI-3 standard
* will be released and this can be gated on a MPI_VERSION check */
#if !defined(USE_STRICT_MPI) && defined(MPICH2)
#define TEST_IDUP 1
#endif
/* assert-like macro that bumps the err count and emits a message */
#define check(x_) \
do { \
if (!(x_)) { \
++errs; \
if (errs < 10) { \
fprintf(stderr, "check failed: (%s), line %d\n", #x_, __LINE__); \
} \
} \
} while (0)
int comm_idup(int argc, char **argv)
{
int errs = 0;
int i;
int rank, size, lrank, lsize, rsize;
int buf[2];
MPI_Comm newcomm, ic, localcomm;
MPI_Request rreq;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
if (size < 2) {
printf("this test requires at least 2 processes\n");
MPI_Abort(MPI_COMM_WORLD, 1);
}
#ifdef TEST_IDUP
/* test plan: make rank 0 wait in a blocking recv until all other processes
* have posted their MPIX_Comm_idup ops, then post last. Should ensure that
* idup doesn't block on the non-zero ranks, otherwise we'll get a deadlock.
*/
if (rank == 0) {
for (i = 1; i < size; ++i) {
buf[0] = 0x01234567;
buf[1] = 0x89abcdef;
MPI_Recv(buf, 2, MPI_INT, i, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
}
MPIX_Comm_idup(MPI_COMM_WORLD, &newcomm, &rreq);
MPI_Wait(&rreq, MPI_STATUS_IGNORE);
}
else {
MPIX_Comm_idup(MPI_COMM_WORLD, &newcomm, &rreq);
buf[0] = rank;
buf[1] = size + rank;
MPI_Ssend(buf, 2, MPI_INT, 0, 0, MPI_COMM_WORLD);
MPI_Wait(&rreq, MPI_STATUS_IGNORE);
}
/* do some communication to make sure that newcomm works */
buf[0] = rank;
buf[1] = 0xfeedface;
MPI_Allreduce(&buf[0], &buf[1], 1, MPI_INT, MPI_SUM, newcomm);
check(buf[1] == (size * (size-1) / 2));
MPI_Comm_free(&newcomm);
/* now construct an intercomm and make sure we can dup that too */
MPI_Comm_split(MPI_COMM_WORLD, rank % 2, rank, &localcomm);
MPI_Intercomm_create(localcomm, 0, MPI_COMM_WORLD, (rank == 0 ? 1 : 0), 1234, &ic);
MPI_Comm_free(&localcomm);
MPI_Comm_rank(ic, &lrank);
MPI_Comm_size(ic, &lsize);
MPI_Comm_remote_size(ic, &rsize);
/* Similar to above pattern, but all non-local-rank-0 processes send to
* remote rank 0. Both sides participate in this way. */
if (lrank == 0) {
for (i = 1; i < rsize; ++i) {
buf[0] = 0x01234567;
buf[1] = 0x89abcdef;
MPI_Recv(buf, 2, MPI_INT, i, 0, ic, MPI_STATUS_IGNORE);
}
MPIX_Comm_idup(ic, &newcomm, &rreq);
MPI_Wait(&rreq, MPI_STATUS_IGNORE);
}
else {
MPIX_Comm_idup(ic, &newcomm, &rreq);
buf[0] = lrank;
buf[1] = lsize + lrank;
MPI_Ssend(buf, 2, MPI_INT, 0, 0, ic);
MPI_Wait(&rreq, MPI_STATUS_IGNORE);
}
/* do some communication to make sure that newcomm works */
buf[0] = lrank;
buf[1] = 0xfeedface;
MPI_Allreduce(&buf[0], &buf[1], 1, MPI_INT, MPI_SUM, newcomm);
check(buf[1] == (rsize * (rsize-1) / 2));
MPI_Comm_free(&newcomm);
MPI_Comm_free(&ic);
#endif /* TEST_IDUP */
MPI_Reduce((rank == 0 ? MPI_IN_PLACE : &errs), &errs, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
if (rank == 0) {
if (errs) {
printf("found %d errors\n", errs);
}
else {
printf(" No Errors\n");
}
}
MPI_Finalize();
return 0;
}
}
| [
"jjwilke@s940740ca.ca.sandia.gov"
] | jjwilke@s940740ca.ca.sandia.gov |
2576fed39a88d3ee2c9767e64b018e0989cfb2d0 | 3b89e0c8a240688ad76d0d222fe67619e924c773 | /detection/laser_detectors/srl_laser_detectors/src/srl_laser_detectors/segments/segment_utils.cpp | b6212f828a4cee25c2cac7e62b297f56c4fdbbfc | [
"BSD-3-Clause"
] | permissive | LCAS/spencer_people_tracking | 14d07aee5752d33726fa781616a0b5d52a66bdb4 | 2d227a703ab3e306815e6dc19d76ec69858c8235 | refs/heads/master | 2021-01-20T15:09:55.562447 | 2018-09-22T12:14:32 | 2018-09-22T12:14:32 | 90,725,575 | 3 | 3 | null | 2018-09-22T12:09:53 | 2017-05-09T09:08:28 | C++ | UTF-8 | C++ | false | false | 6,069 | cpp | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2014-2015, Timm Linder, Social Robotics Lab, University of Freiburg
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <srl_laser_detectors/segments/segment_utils.h>
#include <limits>
#include <boost/foreach.hpp>
#define foreach BOOST_FOREACH
using namespace std;
namespace srl_laser_detectors {
void SegmentUtils::extractSegments(const sensor_msgs::LaserScan::ConstPtr& laserscan, const srl_laser_segmentation::LaserscanSegmentation::ConstPtr& segmentation, Segments& segments)
{
//
// Convert points of laserscan into Cartesian coordinates
//
const size_t numPoints = laserscan->ranges.size();
vector<Point2D> pointsInCartesianCoords; pointsInCartesianCoords.reserve(numPoints);
vector<bool> isPointValid; isPointValid.reserve(numPoints);
for(size_t pointIndex = 0; pointIndex < numPoints; pointIndex++) {
double phi = laserscan->angle_min + laserscan->angle_increment * pointIndex + M_PI_2;
double rho = laserscan->ranges[pointIndex];
Point2D point;
if(rho > laserscan->range_max || rho < laserscan->range_min) {
// Out-of-range measurement, set x and y to NaN
// NOTE: We cannot omit the measurement completely since this would screw up point indices
point(0) = point(1) = numeric_limits<double>::quiet_NaN();
isPointValid.push_back(false);
}
else {
point(0) = sin(phi) * rho;
point(1) = -cos(phi) * rho;
isPointValid.push_back(true);
}
pointsInCartesianCoords.push_back(point);
}
//
// Build segments by collecting Cartesian coordinates of all points per segment
//
segments.clear();
segments.reserve(segmentation->segments.size());
foreach(const srl_laser_segmentation::LaserscanSegment& inputSegment, segmentation->segments) {
size_t numPointsInSegment = inputSegment.measurement_indices.size();
Segment segment;
segment.points.reserve(numPointsInSegment);
segment.ranges.reserve(numPointsInSegment);
segment.indices.reserve(numPointsInSegment);
// These are used to calculate the median
Point2D pointSum = Point2D::Zero();
vector<double> xs, ys;
xs.reserve(numPointsInSegment);
ys.reserve(numPointsInSegment);
size_t numValidInSegment = 0;
foreach(unsigned int pointIndex, inputSegment.measurement_indices) {
if(isPointValid[pointIndex]) { // include only valid measurements in segment
const Point2D& point = pointsInCartesianCoords[pointIndex];
segment.points.push_back( point );
segment.ranges.push_back( laserscan->ranges[pointIndex] );
segment.indices.push_back( pointIndex );
// for calculating mean, median
pointSum += point;
xs.push_back(point(0));
ys.push_back(point(1));
numValidInSegment++;
}
}
// Skip segments without valid points
if(0 == numValidInSegment) continue;
// Calculate mean, median of segment
segment.mean = pointSum / (double) numValidInSegment;
sort(xs.begin(), xs.end());
sort(ys.begin(), ys.end());
if(numValidInSegment & 1) {
segment.median(0) = xs[ (numValidInSegment-1) / 2 ];
segment.median(1) = ys[ (numValidInSegment-1) / 2 ];
}
else {
segment.median(0) = ( xs[numValidInSegment/2-1] + xs[numValidInSegment/2] ) / 2.0;
segment.median(1) = ( ys[numValidInSegment/2-1] + ys[numValidInSegment/2] ) / 2.0;
}
// Set points that directly precede and succeed the segment
size_t firstIndex = inputSegment.measurement_indices.front();
if(firstIndex == 0 || !isPointValid[firstIndex-1]) {
segment.precedingPoint.setConstant(numeric_limits<double>::quiet_NaN());
}
else {
segment.precedingPoint = pointsInCartesianCoords[firstIndex-1];
}
size_t lastIndex = inputSegment.measurement_indices.back();
if(lastIndex >= numPoints -1 || !isPointValid[lastIndex+1]) {
segment.succeedingPoint.setConstant(numeric_limits<double>::quiet_NaN());
}
else {
segment.succeedingPoint = pointsInCartesianCoords[lastIndex+1];
}
// Store the segment
segments.push_back(segment);
}
}
} // end of namespace srl_laser_detectors
| [
"linder@cs.uni-freiburg.de"
] | linder@cs.uni-freiburg.de |
1417948c47e15010df29f22224e2c7ef0a585521 | 38693c6738138ef2a760612bbc8903f00aebd989 | /wxCustomButtons/src/custom_button.cpp | ab0cc554b22470b9d3bfb1f2ecb089cc247a96c6 | [] | no_license | deyan-hadzhiev/wxCustomButton | 330d272000a1612eaa245b9be79fe7c94f62a6fb | 72c33e8ac750ca0cd84637c63dff3dce772e2576 | refs/heads/master | 2021-01-16T19:14:23.907650 | 2014-01-10T22:01:57 | 2014-01-10T22:01:57 | 13,284,118 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,535 | cpp | #include "custom_button.h"
#include "mainframe.h"
bool wxCustomButton::altDown = false;
wxCustomButton::wxCustomButton( MainFrame* mf, wxWindow* parent, wxWindowID winid, wxString lbl, wxPoint pos, wxSize sz)
: wxPanel( parent, winid, pos, sz, wxTAB_TRAVERSAL | wxWANTS_CHARS),
mainFrame( mf),
parent( parent),
focused( false),
hovered( false),
position( pos),
size( sz),
wholeLabel(),
headerLabel(),
defaultCharStr(),
tailLabel(),
defaultChar()
{
parseLabel( lbl);
connectEvents( winid);
}
void wxCustomButton::connectEvents( wxWindowID id)
{
Connect( id, wxEVT_LEFT_DOWN, wxMouseEventHandler( wxCustomButton::OnMouseDown));
Connect( id, wxEVT_LEFT_UP, wxMouseEventHandler( wxCustomButton::OnMouseRelease));
Connect( id, wxEVT_ENTER_WINDOW, wxMouseEventHandler( wxCustomButton::OnEnterHover));
Connect( id, wxEVT_LEAVE_WINDOW, wxMouseEventHandler( wxCustomButton::OnLeftHover));
Connect( id, wxEVT_CHAR, wxKeyEventHandler( wxCustomButton::OnCharEvent));
Connect( id, wxEVT_KEY_DOWN, wxKeyEventHandler( wxCustomButton::OnKeyPress));
Connect( id, wxEVT_KEY_UP, wxKeyEventHandler( wxCustomButton::OnKeyRelease));
Connect( id, wxEVT_SET_FOCUS, wxFocusEventHandler( wxCustomButton::OnSetFocus));
Connect( id, wxEVT_KILL_FOCUS, wxFocusEventHandler( wxCustomButton::OnKillFocus));
Connect( id, wxEVT_PAINT, wxPaintEventHandler( wxCustomButton::OnPaint));
Connect( id, wxEVT_NC_PAINT, wxPaintEventHandler( wxCustomButton::OnPaint));
}
//
//bool wxCustomButton::ProcessEvent( wxEvent& evt)
//{
// if( evt.GetEventType() == wxEVT_KEY_DOWN || evt.GetEventType() == wxEVT_CHAR)
// {
// wxKeyEvent& keyEvent = dynamic_cast<wxKeyEvent&>( evt);
// informMainFrame( "Process key event function %d");
// if( keyEvent.GetKeyCode() == WXK_RETURN)
// {
// wxCommandEvent clicked( wxEVT_COMMAND_BUTTON_CLICKED, evt.GetId());
// mainFrame->AddPendingEvent( clicked);
// return true;
// }
// }
// if( evt.GetEventType() == wxEVT_NAVIGATION_KEY)
// {
// wxNavigationKeyEvent& keyEvent = dynamic_cast<wxNavigationKeyEvent&>( evt);
// informMainFrame( "Process navigation key event function %d");
// }
//
// return wxPanel::ProcessEvent( evt);
//}
void wxCustomButton::parseLabel( const wxString& input)
{
wxChar defChar( '&');
int defCharIdx = input.Find( defChar);
if( defCharIdx >= 0)
{
headerLabel = input.BeforeFirst( defChar);
defaultCharStr = input.AfterFirst( defChar).GetChar(0);
tailLabel = input.AfterFirst( defChar).Mid( 1);
defaultChar = defaultCharStr.GetChar( 0);
wholeLabel = headerLabel + defaultCharStr + tailLabel;
}
else
{
wholeLabel = input;
headerLabel = "";
defaultCharStr = "";
tailLabel = "";
defaultChar = '\0';
}
}
void wxCustomButton::render( wxDC& dc)
{
dc.SetPen( *wxTRANSPARENT_PEN);
wxColour backgroundColour = wxColour( COLOUR_ACTIVE_TEXT);
if( focused) backgroundColour = wxColour( COLOUR_BLUE_TEXT);
if( hovered) backgroundColour = wxColour( COLOUR_PURPLE_TEXT);
dc.SetBrush( wxBrush( backgroundColour));
dc.DrawRectangle( wxPoint( 0, 0), size);
wxFont textFont = parent != NULL ? parent->GetFont() : wxSystemSettings::GetFont( wxSystemFont::wxSYS_DEFAULT_GUI_FONT);
dc.SetFont( textFont);
wxSize labelExtent = dc.GetTextExtent( wholeLabel);
int textX = ( size.GetWidth() - labelExtent.GetWidth())/2;
int textY = ( size.GetHeight() - labelExtent.GetHeight())/2;
dc.DrawText( wholeLabel, textX, textY);
}
void wxCustomButton::SetLabel( const wxString& newLbl)
{
parseLabel( newLbl);
paintNow();
}
void wxCustomButton::paintNow()
{
//informMainFrame( "Custom painted button no: %d");
wxClientDC dc( this);
render( dc);
}
void wxCustomButton::OnPaint( wxPaintEvent& evt)
{
//informMainFrame( "Event painted button no: %d");
wxPaintDC dc( this);
render( dc);
}
void wxCustomButton::OnMouseDown( wxMouseEvent& evt)
{
informMainFrame( "Mouse down event on: %d");
}
void wxCustomButton::OnMouseRelease( wxMouseEvent& evt)
{
informMainFrame( "Mouse up event on: %d");
wxCommandEvent clicked( wxEVT_COMMAND_BUTTON_CLICKED, evt.GetId());
mainFrame->AddPendingEvent( clicked);
}
void wxCustomButton::OnEnterHover( wxMouseEvent& evt)
{
informMainFrame( "Mouse hover over: %d");
hovered = true;
paintNow();
}
void wxCustomButton::OnLeftHover( wxMouseEvent& evt)
{
informMainFrame( "Mouse left hover: %d");
hovered = false;
paintNow();
}
void wxCustomButton::OnCharEvent( wxKeyEvent& evt)
{
char formatedStr[MAX_INFO_STRING_LEN] = "";
sprintf( formatedStr, "Char event key %d, event on button no: %d", evt.GetKeyCode(), evt.GetId());
informMainFrame( formatedStr);
evt.ResumePropagation( wxEVENT_PROPAGATE_MAX);
evt.Skip();
}
void wxCustomButton::OnKeyPress( wxKeyEvent& evt)
{
char formatedStr[MAX_INFO_STRING_LEN] = "";
sprintf( formatedStr, "Pressed key %d, event on button no: %d", evt.GetKeyCode(), evt.GetId());
informMainFrame( formatedStr);
int keyCode = evt.GetKeyCode();
if( keyCode == WXK_RETURN || keyCode == WXK_NUMPAD_ENTER || keyCode == WXK_SPACE)
{
wxCommandEvent clicked( wxEVT_COMMAND_BUTTON_CLICKED, evt.GetId());
mainFrame->AddPendingEvent( clicked);
}
else if( keyCode == WXK_RIGHT || keyCode == WXK_DOWN || ( keyCode == WXK_TAB && !evt.ShiftDown()))
{
wxNavigationKeyEvent next;
next.SetDirection( true);
parent->AddPendingEvent( next);
}
else if( keyCode == WXK_LEFT || keyCode == WXK_UP || ( keyCode == WXK_TAB && evt.ShiftDown()))
{
wxNavigationKeyEvent next;
next.SetDirection( false);
parent->AddPendingEvent( next);
}
else
{
evt.SetEventType( wxEVT_CHAR);
parent->AddPendingEvent( evt);
mainFrame->AddPendingEvent( evt);
}
}
void wxCustomButton::OnKeyRelease( wxKeyEvent& evt)
{
char formatedStr[MAX_INFO_STRING_LEN] = "";
sprintf( formatedStr, "Released key %d, event on button no: %d", evt.GetKeyCode(), evt.GetId());
informMainFrame( formatedStr);
parent->AddPendingEvent( evt);
mainFrame->AddPendingEvent( evt);
}
void wxCustomButton::OnSetFocus( wxFocusEvent& evt)
{
informMainFrame( "Focused set on button: %d");
focused = true;
paintNow();
}
void wxCustomButton::OnKillFocus( wxFocusEvent& evt)
{
informMainFrame( "Focus killed on button: %d");
focused = false;
paintNow();
}
void wxCustomButton::informMainFrame( const char* str)
{
if( str != NULL && mainFrame != NULL)
{
if( strchr( str, '%') == NULL)
{
mainFrame->ChangeAdditionalInfo( str);
}
else
{
char formatedStr[MAX_INFO_STRING_LEN] = "";
sprintf( formatedStr, str, GetId());
mainFrame->ChangeAdditionalInfo( formatedStr);
}
}
} | [
"deyan.z.hadzhiev@gmail.com"
] | deyan.z.hadzhiev@gmail.com |
db5b8f85667061951209b9e4da643ea34ba13996 | d6bdb561d4844b87a0e4a487c37f7519c8714c4e | /Source/BattleOfDistantHoriz/GameActors/TunnelUnit.cpp | 12ab50f77dde63aad5ad50cb558dd20740b716e7 | [] | no_license | mpulcinelli/BattleOfDistantHorizon | 374c1caf7c72ae9e892ef08ba79cb410c99bb9b3 | d0c39b75cb1c3d34c971dc4c057d475f9a9693bd | refs/heads/main | 2023-05-22T18:22:24.389135 | 2021-06-13T02:35:40 | 2021-06-13T02:35:40 | 367,941,059 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,669 | cpp | #include "TunnelUnit.h"
#include "Components/SceneComponent.h"
#include "Components/StaticMeshComponent.h"
#include "Engine/StaticMesh.h"
#include "UObject/ConstructorHelpers.h"
#include "Components/SceneComponent.h"
#include "Components/BoxComponent.h"
#include "BattleOfDistantHoriz/Characters/SpaceShipPawn.h"
#include "Kismet/KismetMathLibrary.h"
#include "BattleOfDistantHoriz/Pickups/StarPickUp.h"
#include "BattleOfDistantHoriz/Pickups/FuelPickUp.h"
#include "Components/PointLightComponent.h"
#include "Components/ArrowComponent.h"
// Sets default values
ATunnelUnit::ATunnelUnit()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
USceneComponent *RootComp = CreateDefaultSubobject<USceneComponent>(TEXT("RootComp"));
TunnelUnitMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("TunnelUnitMesh"));
EndTrigger = CreateDefaultSubobject<UBoxComponent>(TEXT("EndTrigger"));
AreaToSpawn = CreateDefaultSubobject<UBoxComponent>(TEXT("AreaToSpawn"));
AreaToSpawnFuelPickUp = CreateDefaultSubobject<UBoxComponent>(TEXT("AreaToSpawnFuelPickUp"));
PoitLight01 = CreateDefaultSubobject<UPointLightComponent>(TEXT("PoitLight01"));
PoitLight02 = CreateDefaultSubobject<UPointLightComponent>(TEXT("PoitLight02"));
PoitLight03 = CreateDefaultSubobject<UPointLightComponent>(TEXT("PoitLight03"));
PoitLight04 = CreateDefaultSubobject<UPointLightComponent>(TEXT("PoitLight04"));
PoitLight05 = CreateDefaultSubobject<UPointLightComponent>(TEXT("PoitLight05"));
ArrowPositionNextBlock = CreateDefaultSubobject<UArrowComponent>(TEXT("ArrowPositionNextBlock"));
static ConstructorHelpers::FObjectFinder<UStaticMesh> SM_TUNNEL_UNIT_OPEN(TEXT("/Game/Geometry/Meshes/SM_Tunnel_Open_4800"));
//static ConstructorHelpers::FObjectFinder<UStaticMesh> SM_TUNNEL_UNIT_OPEN(TEXT("/Game/Geometry/Meshes/Tunnel_Reto_4800"));
RootComponent = RootComp;
TunnelUnitMesh->SetupAttachment(RootComp);
EndTrigger->SetupAttachment(RootComp);
AreaToSpawn->SetupAttachment(RootComp);
AreaToSpawnFuelPickUp->SetupAttachment(RootComp);
TunnelUnitMesh->SetCollisionProfileName(FName("BlockAll"));
PoitLight01->SetupAttachment(RootComp);
PoitLight02->SetupAttachment(RootComp);
PoitLight03->SetupAttachment(RootComp);
PoitLight04->SetupAttachment(RootComp);
PoitLight05->SetupAttachment(RootComp);
PoitLight01->SetRelativeLocation(FVector(-1230.000000, 2270.0, 0.000000));
PoitLight02->SetRelativeLocation(FVector(1230.000000, 2270.0, 0.000000));
PoitLight03->SetRelativeLocation(FVector(1230.000000, -2270.0, 0.000000));
PoitLight04->SetRelativeLocation(FVector(-1230.000000, -2270.0, 0.000000));
PoitLight05->SetRelativeLocation(FVector(0.000000, 10.000000, 2170.000000));
PoitLight01->SetIntensity(100000.0);
PoitLight02->SetIntensity(100000.0);
PoitLight03->SetIntensity(100000.0);
PoitLight04->SetIntensity(100000.0);
PoitLight05->SetIntensity(100000.0);
PoitLight01->SetVisibility(false);
PoitLight02->SetVisibility(false);
PoitLight03->SetVisibility(false);
PoitLight04->SetVisibility(false);
PoitLight05->SetVisibility(false);
PoitLight01->SetAttenuationRadius(16000.0);
PoitLight02->SetAttenuationRadius(16000.0);
PoitLight03->SetAttenuationRadius(16000.0);
PoitLight04->SetAttenuationRadius(16000.0);
PoitLight05->SetAttenuationRadius(16000.0);
PoitLight01->SetSourceRadius(2300.0);
PoitLight02->SetSourceRadius(2300.0);
PoitLight03->SetSourceRadius(2300.0);
PoitLight04->SetSourceRadius(2300.0);
PoitLight05->SetSourceRadius(2300.0);
PoitLight01->SetSoftSourceRadius(1500.0);
PoitLight02->SetSoftSourceRadius(1500.0);
PoitLight03->SetSoftSourceRadius(1500.0);
PoitLight04->SetSoftSourceRadius(1500.0);
PoitLight05->SetSoftSourceRadius(1500.0);
PoitLight01->SetSourceLength(2000.0);
PoitLight02->SetSourceLength(2000.0);
PoitLight03->SetSourceLength(2000.0);
PoitLight04->SetSourceLength(2000.0);
PoitLight05->SetSourceLength(2000.0);
PoitLight01->SetMobility(EComponentMobility::Stationary);
PoitLight02->SetMobility(EComponentMobility::Stationary);
PoitLight03->SetMobility(EComponentMobility::Stationary);
PoitLight04->SetMobility(EComponentMobility::Stationary);
PoitLight05->SetMobility(EComponentMobility::Stationary);
EndTrigger->SetRelativeLocation(FVector(2338.0f, 0.0f, 0.0f));
EndTrigger->SetRelativeScale3D(FVector(10.0f, 70.0f, 70.0f));
EndTrigger->SetGenerateOverlapEvents(true);
EndTrigger->SetCollisionProfileName(FName("BoxEndTriggerProfile"));
AreaToSpawn->SetRelativeLocation(FVector(0.0f, 0.0f, 0.0f));
AreaToSpawn->SetRelativeScale3D(FVector(70.0f, 70.0f, 70.0f));
AreaToSpawn->SetGenerateOverlapEvents(true);
AreaToSpawn->SetCollisionProfileName(FName("BoxSpawnProfile"));
AreaToSpawnFuelPickUp->SetRelativeLocation(FVector(0.000000, 0.000000, -2247.000000));
AreaToSpawnFuelPickUp->SetRelativeScale3D(FVector(61.250000, 61.250000, 1.000000));
AreaToSpawnFuelPickUp->SetGenerateOverlapEvents(false);
AreaToSpawnFuelPickUp->SetCollisionProfileName(FName("BoxSpawnFuelProfile"));
ArrowPositionNextBlock->SetRelativeLocation(FVector(2400.000000, 0.000000, -2400.000000));
ArrowPositionNextBlock->SetRelativeScale3D(FVector(1.0f, 1.0f, 1.0f));
if (SM_TUNNEL_UNIT_OPEN.Object != nullptr)
{
TunnelUnitMesh->SetStaticMesh(SM_TUNNEL_UNIT_OPEN.Object);
}
}
void ATunnelUnit::BeginPlay()
{
Super::BeginPlay();
ShuffleLight(FMath::RandRange(0, 1));
EndTrigger->OnComponentBeginOverlap.AddDynamic(this, &ATunnelUnit::EndTriggerBeginOverlap);
FVector RandPoint;
GetRandomPointIn3DBoxSpace(RandPoint, AreaToSpawn);
FActorSpawnParameters SpawnInfo;
SpawnInfo.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
FRotator RotationToSpawn;
auto start = GetWorld()->SpawnActor<AStarPickUp>(RandPoint, RotationToSpawn, SpawnInfo);
if (start != nullptr)
{
ListOfCreatedActors.Add(start);
start->AttachToActor(this, FAttachmentTransformRules::KeepWorldTransform);
}
FVector RandPointToFuel;
GetRandomPointIn3DBoxSpace(RandPointToFuel, AreaToSpawnFuelPickUp);
auto fuel = GetWorld()->SpawnActor<AFuelPickUp>(RandPointToFuel, RotationToSpawn, SpawnInfo);
if (fuel != nullptr)
{
ListOfCreatedActors.Add(fuel);
fuel->AttachToActor(this, FAttachmentTransformRules::KeepWorldTransform);
}
}
void ATunnelUnit::BeginDestroy()
{
Super::BeginDestroy();
}
void ATunnelUnit::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
void ATunnelUnit::EndTriggerBeginOverlap(class UPrimitiveComponent *OverlappedComp, class AActor *Other, class UPrimitiveComponent *OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult &SweepResult)
{
if(bIsPendingKill)return;
auto isPlayer = Cast<ASpaceShipPawn>(Other);
if (isPlayer != nullptr)
{
for (auto &itm : ListOfCreatedActors)
{
itm->SetLifeSpan(0.5);
}
// Destroi o túnel.
SetLifeSpan(0.5);
bIsPendingKill=true;
}
}
void ATunnelUnit::ShuffleLight(int OptShuffle)
{
switch (OptShuffle)
{
case 0:
PoitLight01->SetVisibility(FMath::RandBool());
PoitLight01->SetLightColor(GetRandColor());
PoitLight02->SetVisibility(FMath::RandBool());
PoitLight02->SetLightColor(GetRandColor());
PoitLight03->SetVisibility(FMath::RandBool());
PoitLight03->SetLightColor(GetRandColor());
PoitLight04->SetVisibility(FMath::RandBool());
PoitLight04->SetLightColor(GetRandColor());
PoitLight05->SetVisibility(FMath::RandBool());
PoitLight05->SetLightColor(GetRandColor());
break;
default:
break;
case 1:
int32 opt = FMath::RandRange(1, 5);
switch (opt)
{
case 1:
PoitLight01->SetVisibility(FMath::RandBool());
PoitLight01->SetLightColor(GetRandColor());
break;
case 2:
PoitLight02->SetVisibility(FMath::RandBool());
PoitLight02->SetLightColor(GetRandColor());
break;
case 3:
PoitLight03->SetVisibility(FMath::RandBool());
PoitLight03->SetLightColor(GetRandColor());
break;
case 4:
PoitLight04->SetVisibility(FMath::RandBool());
PoitLight04->SetLightColor(GetRandColor());
break;
case 5:
PoitLight05->SetVisibility(FMath::RandBool());
PoitLight05->SetLightColor(GetRandColor());
break;
default:
break;
}
}
}
void ATunnelUnit::GetRandomPointIn3DBoxSpace(FVector &RandomPoint, UBoxComponent *BoundingBox)
{
RandomPoint = UKismetMathLibrary::RandomPointInBoundingBox(BoundingBox->Bounds.Origin, BoundingBox->Bounds.BoxExtent);
} | [
"mpulcinelli@gmail.com"
] | mpulcinelli@gmail.com |
2a9a688da2aefb6722da5e83977a881a23f05699 | 2d669fa7a179b394c967306b1465b413f909d6aa | /ChessPossibleMoves/BoardFunctions.h | 06a83a933ae463533f3c098ffabb4f1683a1bd37 | [] | no_license | Kornelcius/Chess | 6f3111c3ad91974a70c8564697c5d814edec9a96 | 4fa8fd44d9c94cf0f12c43fe203d075cfb07b5c0 | refs/heads/main | 2023-03-17T17:05:59.289711 | 2021-02-24T10:16:51 | 2021-02-24T10:16:51 | 341,013,185 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 646 | h | #pragma once
#include "Piece.h"
#include <vector>
extern Piece ChessBoard[8][8];
void initializeBoard();
void printBoard();
Position chooseFigure();
std::vector<Position> getMoves(int x, int y);
std::vector<Position> getMovesForType(int x, int y, std::string type);
std::vector<Position> getMovesForKing(int x, int y);
std::vector<Position> getMovesForQueen(int x, int y);
std::vector<Position> getMovesForRook(int x, int y);
std::vector<Position> getMovesForBishop(int x, int y);
std::vector<Position> getMovesForKnight(int x, int y);
std::vector<Position> getMovesForPawn(int x, int y);
void printPositionInChessBoardCoordinates(Position pos); | [
"bartosz.kordala@gmail.com"
] | bartosz.kordala@gmail.com |
049fd4f837b0fd8324d879a67e69b5dec6923ac4 | 76ce6d3927bc8e70ccff648f84a40a2769d1a4ff | /c++/c++primer_2/03/03_32a/main.cpp | 1034dd553f4ef1b6b83b85830b4238ca41feaff7 | [] | no_license | coderfamer/linuxstudy | a4fb7463df868d170dc4815ea35d371996a7c8f4 | 87b57ab4847a5229025cff70a595d1abfbade4a3 | refs/heads/master | 2021-07-18T06:00:33.153485 | 2020-04-03T09:59:57 | 2020-04-03T09:59:57 | 101,067,959 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 612 | cpp | #include <iostream>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
vector<int> v1(a, a+10);
for (auto s : v1)
{
cout << s << " ";
}
cout << endl;
vector<int> v2 = v1;
int b[10];
for (int i=0; i<10; i++)
{
cout << " a[" << i << "]" << " = " << a[i] << endl;
b[i] = a[i];
cout << " b[" << i << "]" << " = " << b[i] << endl;
cout << "v1[" << i << "]" << " = " << v1[i] << endl;
cout << "v2[" << i << "]" << " = " << v2[i] << endl;
}
return 0;
}
| [
"13625611069@163.com"
] | 13625611069@163.com |
f88e620fef110a25bc1d50cb0e66c7555f6e0631 | 54bf7148574a620a1cf6045aca0217ce1dad3090 | /CompillerAgain/boolean.cpp | 91c3fb22b9f3a3a221b2c7d855e5668b3a74b7c8 | [] | no_license | frezzerovshik/Compiler | ea4aa05251b974e602f1fe5fd97606b5c50b4b9b | f345aaa94f80c0e70c3c442c50fe2a34c04cb315 | refs/heads/master | 2020-12-12T11:15:20.960835 | 2020-01-22T21:20:56 | 2020-01-22T21:20:56 | 216,276,586 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,465 | cpp | #include "boolean.h"
#include "terminal.h"
#include "factor.h"
#include "logic.h"
#include "compare.h"
boolean::boolean()
{
setFlag(false);
}
boolean::~boolean()
{
}
// <boolean>::=<factor><logic><factor> | <factor> <compare> <factor> | true |false
void boolean::deriving(int pos) {
bool flag = false;
if (lexStream[pos].type == KEY_WORD &&
(KeyWords[lexStream[pos].numInValidTable].val == "true" ||
KeyWords[lexStream[pos].numInValidTable].val == "false") &&
lexStream[pos + 1].type != DIVIDE
) {
symbol* newLeaf = new terminal(KeyWords[lexStream[pos].numInValidTable].val);
newLeaf->setParent(this);
_childs.push_back(newLeaf);
}
else {
symbol* newNode_op1 = new factor;
newNode_op1->setParent(this);
_childs.push_back(newNode_op1);
newNode_op1->deriving(pos);
int index = pos;
for (int i = 0; i < lexStream.size(); ++i) {
if (lexStream[i].type == DIVIDE &&
((Dividers[lexStream[i].numInValidTable].val == "&" && Dividers[lexStream[i+1].numInValidTable].val == "&")||
(Dividers[lexStream[i].numInValidTable].val == "|" && Dividers[lexStream[i+1].numInValidTable].val == "|"))) {
symbol* newNodeOperator = new logic;
newNodeOperator->setParent(this);
_childs.push_back(newNodeOperator);
newNodeOperator->deriving(i);
index = i + 1;
flag = true;
break;
}
else {
if (lexStream[i].type == DIVIDE &&
((Dividers[lexStream[i].numInValidTable].val == ">" && Dividers[lexStream[i + 1].numInValidTable].val == "=") ||
(Dividers[lexStream[i].numInValidTable].val == "<" && Dividers[lexStream[i + 1].numInValidTable].val == "=") ||
(Dividers[lexStream[i].numInValidTable].val == "!" && Dividers[lexStream[i + 1].numInValidTable].val == "=") ||
(Dividers[lexStream[i].numInValidTable].val == "=" && Dividers[lexStream[i + 1].numInValidTable].val == "=") ||
(Dividers[lexStream[i].numInValidTable].val == "<") ||
(Dividers[lexStream[i].numInValidTable].val == ">")
)) {
symbol* newNodeOperator = new compare;
newNodeOperator->setParent(this);
_childs.push_back(newNodeOperator);
newNodeOperator->deriving(i);
index = i + 1;
flag = true;
break;
}
else {
flag = false;
}
}
}
if (flag == true) {
symbol* newNode_op2 = new factor;
newNode_op2->setParent(this);
_childs.push_back(newNode_op2);
newNode_op2->deriving(index );
}
else {
throw 1;
}
}
cout << "boolean" << endl;
} | [
"frezzy12349@gmail.com"
] | frezzy12349@gmail.com |
993d21564ffd8389589b77e8adb5630236603132 | bdfc337fc95b034af4116e084bf6cdb9b7b085ea | /Recursion/recursion03.cpp | eff2938cc998c7ab417b34566798fd20f2f6b5e3 | [] | no_license | JUDONGHYEOK/JinwolAlgorithm | 9957bdb44fc5f7ba590aac6d12e0bbac74660931 | 08682f5305929d89da7a4e18192dec59a01955cd | refs/heads/master | 2023-03-17T20:09:13.493862 | 2021-03-14T08:16:20 | 2021-03-14T08:16:20 | 338,572,799 | 2 | 1 | null | 2021-03-14T08:16:20 | 2021-02-13T12:44:41 | Java | UTF-8 | C++ | false | false | 221 | cpp | #include<iostream>
#include<string>
using namespace std;
bool three(int a,int b){
if(a<10){
cout<<b;
return (a==3||a==6||a==9);
}
three(a,b++);
}
int main(){
int number=1234567;
} | [
"65863017+JUDONGHYEOK@users.noreply.github.com"
] | 65863017+JUDONGHYEOK@users.noreply.github.com |
6868fb03fc433842c811ab400709c03d75162bbf | e3d89f0fbfed8281e682cff6fb047fb14be50061 | /arduino/imu_rosserial/imu_rosserial.ino | 0266260ee94f54a7a7d3b2ba11d0a8ad69fb8cdf | [
"MIT"
] | permissive | tranqkhue/bugcar | 4fc850e7efd4490d2f42284e9e56f2cb0df5f16d | ee934cb51a191167756e519a2c2a313cc783f0a7 | refs/heads/main | 2023-03-11T12:38:06.993727 | 2021-02-21T09:39:04 | 2021-02-21T09:39:04 | 322,543,832 | 0 | 0 | MIT | 2021-02-21T09:39:05 | 2020-12-18T09:07:24 | null | UTF-8 | C++ | false | false | 17,044 | ino | //#define USE_USBCON //For Leonardo/Pro Micro with MEGA32U4 microcontroller
//https://answers.ros.org/question/61863/rosserial_python-cant-connect-to-arduino-leonardo/
#include "I2Cdev.h"
#include "Wire.h"
#include "MPU6050_6Axis_MotionApps20.h"
#include <ros.h>
#include <sensor_msgs/Imu.h>
//================================================================================================================
//ROS handler
ros::NodeHandle_<ArduinoHardware, 1, 1, 16, 407> nh; //Limit NodeHandle
//ROS buffer memory for Arduino-based device with low RAM
//http://wiki.ros.org/rosserial/Overview/Limitations
//https://answers.ros.org/question/28890/using-rosserial-for-a-atmega168arduino-based-motorcontroller/
//http://wiki.ros.org/rosserial_arduino/Tutorials/NodeHandle%20and%20ArduinoHardware
//Minimum buffer: 312bytes
//Baudrate 115200 is set in ArduinoHardware.h
sensor_msgs::Imu imu_msg;
ros::Publisher imu_pub("imu",&imu_msg);
uint32_t seq;
//=================================================================================================================
//================================================================================================================
/*
0 | +/- 2g | 8192 LSB/mg
1 | +/- 4g | 4096 LSB/mg
2 | +/- 8g | 2048 LSB/mg
3 | +/- 16g | 1024 LSB/mg
and those the one you can use in the function setFullScaleGyroRange()
0 = +/- 250 degrees/sec
1 = +/- 500 degrees/sec
2 = +/- 1000 degrees/sec
*/
float accel_scale = 1.196289e-3;
//scale = scale(g) / resolution, scale(g) = 8(g), resolution 16 bit
//gyro does not have scale since the output is already degree/s
//scale is to convert degree to radian;
float gyro_scale = 0.01745329251;
//radians/s
//================================================================================================================
//================================================================================================================
MPU6050 mpu; //MPU-9250 is basically a MPU-6050 with an external compass bypass via I2C
#define INTERRUPT_PIN 8
bool blinkState = false;
bool dmpReady = false; // set true if DMP init was successful
uint8_t mpuIntStatus; // holds actual interrupt status byte from MPU
uint8_t devStatus; // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize; // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount; // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer
int16_t data[10];
int16_t mx, my, mz;
// orientation/motion vars
Quaternion q; // [w, x, y, z] quaternion container
VectorInt16 aa; // [x, y, z] accel sensor measurements
VectorInt16 aaReal; // [x, y, z] gravity-free accel sensor measurements
VectorInt16 Gyro;
VectorFloat gravity; // [x, y, z] gravity vector
VectorInt16 mag;
//Value for calibration
//int16_t ax, ay, az;
//int16_t gx, gy, gz;
//int mean_ax,mean_ay,mean_az,mean_gx,mean_gy,mean_gz,state=0;
int ax_offset,ay_offset,az_offset,gx_offset,gy_offset,gz_offset=0;
//int acel_deadzone=8; //Acelerometer error allowed, make it lower to get more precision, but sketch may not converge (default:8)
//int gyro_deadzone=1; //Giro error allowed, make it lower to get more precision, but sketch may not converge (default:1)
//int buffersize=1000; //Amount of readings used to average, make it higher to get more precision but sketch will be slower (default:1000)
uint8_t mode = 0x11;
int16_t COEFF_X, COEFF_Y, COEFF_Z;
// ================================================================
// === INTERRUPT DETECTION ROUTINE ===
// ================================================================
volatile bool mpuInterrupt = false; // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
mpuInterrupt = true;
}
//================================================================================================================
//================================================ FUNCTIONS =================================================
//================================================================================================================
/*
void meansensors(){
long i=0,buff_ax=0,buff_ay=0,buff_az=0,buff_gx=0,buff_gy=0,buff_gz=0;
while (i<(buffersize+101)){
// read raw accel/gyro measurements from device
mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
if (i>100 && i<=(buffersize+100)){ //First 100 measures are discarded
buff_ax=buff_ax+ax;
buff_ay=buff_ay+ay;
buff_az=buff_az+az;
buff_gx=buff_gx+gx;
buff_gy=buff_gy+gy;
buff_gz=buff_gz+gz;
}
if (i==(buffersize+100)){
mean_ax=buff_ax/buffersize;
mean_ay=buff_ay/buffersize;
mean_az=buff_az/buffersize;
mean_gx=buff_gx/buffersize;
mean_gy=buff_gy/buffersize;
mean_gz=buff_gz/buffersize;
}
i++;
delay(2); //Needed so we don't get repeated measures
}
}
//================================================================================================================
//================================================================================================================
void calibration(){
ax_offset=-mean_ax/8;
ay_offset=-mean_ay/8;
az_offset=(16384-mean_az)/8;
gx_offset=-mean_gx/4;
gy_offset=-mean_gy/4;
gz_offset=-mean_gz/4;
while (1){
int ready=0;
mpu.setXAccelOffset(ax_offset);
mpu.setYAccelOffset(ay_offset);
mpu.setZAccelOffset(az_offset);
mpu.setXGyroOffset(gx_offset);
mpu.setYGyroOffset(gy_offset);
mpu.setZGyroOffset(gz_offset);
meansensors();
////Serial.println("...");
if (abs(mean_ax)<=acel_deadzone) ready++;
else ax_offset=ax_offset-mean_ax/acel_deadzone;
if (abs(mean_ay)<=acel_deadzone) ready++;
else ay_offset=ay_offset-mean_ay/acel_deadzone;
if (abs(16384-mean_az)<=acel_deadzone) ready++;
else az_offset=az_offset+(16384-mean_az)/acel_deadzone;
if (abs(mean_gx)<=gyro_deadzone) ready++;
else gx_offset=gx_offset-mean_gx/(gyro_deadzone+1);
if (abs(mean_gy)<=gyro_deadzone) ready++;
else gy_offset=gy_offset-mean_gy/(gyro_deadzone+1);
if (abs(mean_gz)<=gyro_deadzone) ready++;
else gz_offset=gz_offset-mean_gz/(gyro_deadzone+1);
if (ready==6) break;
}
}
*/
//================================================================================================================
//================================================================================================================
void simpleI2CWrite(uint8_t Addr, uint8_t Reg, uint8_t _data, bool timeout = false) {
Wire.beginTransmission(Addr);
Wire.write(Reg);
Wire.write(_data);
Wire.endTransmission();
if(timeout) delay(50);
}
//================================================================================================================
//================================================================================================================
int simpleI2CRead(uint8_t Addr, uint8_t Reg, uint8_t data_len, int16_t *_data){
Wire.beginTransmission(Addr);
Wire.write(Reg);
Wire.endTransmission();
Wire.beginTransmission(Addr);
int _numBytes = Wire.requestFrom(Addr, data_len);
if(_numBytes == data_len){
for(int count = 0; Wire.available(); count++) _data[count] = Wire.read();
Wire.endTransmission();
return 1;
}
else {
Wire.endTransmission();
return -1;
}
}
//================================================================================================================
//================================================================================================================
void magInitialize() {
// disable bypass mode
mpu.setI2CMasterModeEnabled(false);
mpu.setI2CBypassEnabled(true);
mpu.setSleepEnabled(false);
// set AKG8963 power down
simpleI2CWrite(0x0C, 0x0A, 0x00, true);
// get sensitivity adjustment values
// apply formula from datasheet
int16_t COEFF[3];
simpleI2CRead(0x0C, 0x10, 3, COEFF);
COEFF_X = (((float)COEFF[0]-128.0f)*0.5f)/128.0f+1.0f;
COEFF_Y = (((float)COEFF[1]-128.0f)*0.5f)/128.0f+1.0f;
COEFF_Z = (((float)COEFF[2]-128.0f)*0.5f)/128.0f+1.0f;
// set AKG8963 to desired operation mode
simpleI2CWrite(0x0C, 0x0A, mode, true);
// get sensitivity adjustment values
}
//================================================================================================================
//================================================== MAIN ===================================================
//================================================================================================================
void setup() {
while (!Serial) ;
//ROS Init
nh.initNode();
nh.advertise(imu_pub);
Wire.begin();
Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
//Serial.begin(115200);
//while (!//Serial); // wait for Leonardo enumeration, others continue immediately
////Serial.println(F("Initializing I2C devices..."));
mpu.initialize();
pinMode(INTERRUPT_PIN, INPUT);
mpu.setFullScaleAccelRange(2); //Set scale
mpu.setFullScaleGyroRange(1); //Set scale
// verify connection
//Serial.println(F("Testing device connections..."));
//Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));
// wait for ready
//Serial.println(F("\nSend any character to begin DMP programming and demo: "));
//while (Serial.available() && Serial.read()); // empty buffer
//while (!Serial.available()); // wait for data
//while (Serial.available() && Serial.read()); // empty buffer again
// load and configure the DMP
//Serial.println(F("Initializing DMP..."));
devStatus = mpu.dmpInitialize();
//Calibration
// supply your own gyro offsets here, scaled for min sensitivity
// mpu.setXGyroOffset(220);
// mpu.setYGyroOffset(76);
// mpu.setZGyroOffset(-85);
// mpu.setZAccelOffset(1788); // 1688 factory default for my test chip
// reset offsets
mpu.setXAccelOffset(0);
mpu.setYAccelOffset(0);
mpu.setZAccelOffset(0);
mpu.setXGyroOffset(0);
mpu.setYGyroOffset(0);
mpu.setZGyroOffset(0);
//meansensors();
//calibration();
mpu.setXAccelOffset(ax_offset);
mpu.setYAccelOffset(ay_offset);
mpu.setZAccelOffset(az_offset);
mpu.setXGyroOffset(gx_offset);
mpu.setYGyroOffset(gy_offset);
mpu.setZGyroOffset(gz_offset);
// make sure it worked (returns 0 if so)
if (devStatus == 0) {
// turn on the DMP, now that it's ready
mpu.CalibrateAccel(6);
mpu.CalibrateGyro(6);
//Serial.println(F("Enabling DMP..."));
mpu.setDMPEnabled(true);
// enable Arduino interrupt detection
//Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
mpuIntStatus = mpu.getIntStatus();
// set our DMP Ready flag so the main loop() function knows it's okay to use it
//Serial.println(F("DMP ready! Waiting for first interrupt..."));
dmpReady = true;
// get expected DMP packet size for later comparison
packetSize = mpu.dmpGetFIFOPacketSize();
} else {
// ERROR!
// 1 = initial memory load failed
// 2 = DMP configuration updates failed
// (if it's going to break, usually the code will be 1)
//Serial.print(F("DMP Initialization failed (code "));
//Serial.print(devStatus);
//Serial.println(F(")"));
}
magInitialize();
seq = 0;
delay(20);
}
//================================================================================================================
//================================================================================================================
void loop() {
// if programming failed, don't try to do anything
if (!dmpReady) return;
// reset interrupt flag and get INT_STATUS byte
mpuInterrupt = false;
mpuIntStatus = mpu.getIntStatus();
// get current FIFO count
fifoCount = mpu.getFIFOCount();
// check for overflow (this should never happen unless our code is too inefficient)
if ((mpuIntStatus & _BV(MPU6050_INTERRUPT_FIFO_OFLOW_BIT)) || fifoCount >= 1024) {
// reset so we can continue cleanly
mpu.resetFIFO();
//Serial.println(F("FIFO overflow!"));
//FIFO overflow usually happens if enable external compass reading!
// otherwise, check for DMP data ready interrupt (this should happen frequently)
} else if (mpuIntStatus & _BV(MPU6050_INTERRUPT_DMP_INT_BIT)) {
imu_msg.header.stamp = nh.now();
imu_msg.header.frame_id = 1;
imu_msg.header.seq = seq;
seq++;
// wait for correct available data length, should be a VERY short wait
while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
// read a packet from FIFO
mpu.getFIFOBytes(fifoBuffer, packetSize);
// track FIFO count here in case there is > 1 packet available
// (this lets us immediately read more without waiting for an interrupt)
fifoCount -= packetSize;
/*
// set I2C Bypass mode
mpu.setI2CBypassEnabled(true);
// reset single measurement mode if mode == 0x11
if(1) simpleI2CWrite(0x0C, 0x0A, 0x11, true);
// get magnetometer data
data[10] = simpleI2CRead(0x0C, 0x03, 7, data);
if(data[10] == 1) { // continue if data size is equal to number of bytes to receive
/* check AKG8963 STATUS 2 (overflown) written to data[6]
* if overflown (0x18) and discard data
* else (0x10) | (0x08) sensor working normal
*/
/*
if((data[6] | 0x10) == 0x10) {
mx = (COEFF_X*(uint16_t)(data[1] << 8 | data[0]))*0.6; //uT
my = (COEFF_Y*(uint16_t)(data[3] << 8 | data[2]))*0.6;
mz = (COEFF_Z*(uint16_t)(data[5] << 8 | data[4]))*0.6;
//Serial.print("Mag x/y/z: ");
//Serial.print(mx); Serial.print("\t");
//Serial.print(my); Serial.print("\t");
//Serial.print(mz); Serial.print("\n");
}
else {
//Serial.println("Sensor overflown! (STATUS 2): 0x"); Serial.println(data[6], HEX);
}
} //else { //Serial.println("Failed to receive bytes from all registers"); }
*/
// display quaternion values in easy matrix form: w x y z
mpu.dmpGetQuaternion(&q, fifoBuffer);
imu_msg.orientation.x = q.x;
imu_msg.orientation.y = q.y;
imu_msg.orientation.z = q.z;
imu_msg.orientation.w = q.w;
//Why multiplication by 2? I test it, and I don't know why
mpu.dmpGetGyro(&Gyro, fifoBuffer);
imu_msg.angular_velocity.x = Gyro.x * gyro_scale;
imu_msg.angular_velocity.y = Gyro.y * gyro_scale;
imu_msg.angular_velocity.z = Gyro.z * gyro_scale;
mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
mpu.dmpGetAccel(&aa, fifoBuffer);
imu_msg.linear_acceleration.x = aaReal.x * accel_scale;
imu_msg.linear_acceleration.y = aaReal.y * accel_scale;
imu_msg.linear_acceleration.z = aaReal.z * accel_scale;
/*
mpu.dmpGetQuaternion(&q, fifoBuffer);
Serial.print("quat\t");
Serial.print(q.w);
Serial.print("\t");
Serial.print(q.x);
Serial.print("\t");
Serial.print(q.y);
Serial.print("\t");
Serial.println(q.z);
// display angular acceleration
mpu.dmpGetGyro(&Gyro, fifoBuffer);
Serial.print("gyro\t");
Serial.print(Gyro.x * gyro_scale);
Serial.print("\t");
Serial.print(Gyro.y * gyro_scale);
Serial.print("\t");
Serial.println(Gyro.z * gyro_scale);
// display real acceleration, adjusted to remove gravity
mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
mpu.dmpGetAccel(&aa, fifoBuffer);
Serial.print("areal\t");
Serial.print(aaReal.x * accel_scale);
Serial.print("\t");
Serial.print(aaReal.y * accel_scale);
Serial.print("\t");
Serial.println(aaReal.z * accel_scale);
*/
imu_pub.publish(&imu_msg);
nh.spinOnce();
delay(2);
}
}
| [
"14338@student.vgu.edu.vn"
] | 14338@student.vgu.edu.vn |
90b2c6f167fedead37d44982534136505ea0be23 | ba4c8a718594f43fb2c5a2ec11c066274ec70445 | /openCV/sources/modules/gpu/src/error.cpp | fc8573750a7a40179d4e820822cdd1aae668b918 | [
"BSD-3-Clause"
] | permissive | jayparekhjp/openCV-Facial-Recognition | d7d83e1cd93a878d91e129dd5f754a50fde973a2 | c351d55863bbc40c3225f55152dcd044f778119f | refs/heads/master | 2020-04-02T03:18:43.346991 | 2018-10-20T23:45:42 | 2018-10-20T23:45:42 | 153,957,654 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 11,863 | cpp | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "precomp.hpp"
using namespace cv;
using namespace cv::gpu;
using namespace std;
#ifdef HAVE_CUDA
namespace
{
#define error_entry(entry) { entry, #entry }
struct ErrorEntry
{
int code;
string str;
};
struct ErrorEntryComparer
{
int code;
ErrorEntryComparer(int code_) : code(code_) {};
bool operator()(const ErrorEntry& e) const { return e.code == code; }
};
string getErrorString(int code, const ErrorEntry* errors, size_t n)
{
size_t idx = find_if(errors, errors + n, ErrorEntryComparer(code)) - errors;
const string& msg = (idx != n) ? errors[idx].str : string("Unknown error code");
ostringstream ostr;
ostr << msg << " [Code = " << code << "]";
return ostr.str();
}
//////////////////////////////////////////////////////////////////////////
// NPP errors
const ErrorEntry npp_errors [] =
{
#if defined (_MSC_VER)
error_entry( NPP_NOT_SUFFICIENT_COMPUTE_CAPABILITY ),
#endif
#if NPP_VERSION < 5500
error_entry( NPP_BAD_ARG_ERROR ),
error_entry( NPP_COEFF_ERROR ),
error_entry( NPP_RECT_ERROR ),
error_entry( NPP_QUAD_ERROR ),
error_entry( NPP_MEMFREE_ERR ),
error_entry( NPP_MEMSET_ERR ),
error_entry( NPP_MEM_ALLOC_ERR ),
error_entry( NPP_HISTO_NUMBER_OF_LEVELS_ERROR ),
error_entry( NPP_MIRROR_FLIP_ERR ),
error_entry( NPP_INVALID_INPUT ),
error_entry( NPP_POINTER_ERROR ),
error_entry( NPP_WARNING ),
error_entry( NPP_ODD_ROI_WARNING ),
#else
error_entry( NPP_INVALID_HOST_POINTER_ERROR ),
error_entry( NPP_INVALID_DEVICE_POINTER_ERROR ),
error_entry( NPP_LUT_PALETTE_BITSIZE_ERROR ),
error_entry( NPP_ZC_MODE_NOT_SUPPORTED_ERROR ),
error_entry( NPP_MEMFREE_ERROR ),
error_entry( NPP_MEMSET_ERROR ),
error_entry( NPP_QUALITY_INDEX_ERROR ),
error_entry( NPP_HISTOGRAM_NUMBER_OF_LEVELS_ERROR ),
error_entry( NPP_CHANNEL_ORDER_ERROR ),
error_entry( NPP_ZERO_MASK_VALUE_ERROR ),
error_entry( NPP_QUADRANGLE_ERROR ),
error_entry( NPP_RECTANGLE_ERROR ),
error_entry( NPP_COEFFICIENT_ERROR ),
error_entry( NPP_NUMBER_OF_CHANNELS_ERROR ),
error_entry( NPP_COI_ERROR ),
error_entry( NPP_DIVISOR_ERROR ),
error_entry( NPP_CHANNEL_ERROR ),
error_entry( NPP_STRIDE_ERROR ),
error_entry( NPP_ANCHOR_ERROR ),
error_entry( NPP_MASK_SIZE_ERROR ),
error_entry( NPP_MIRROR_FLIP_ERROR ),
error_entry( NPP_MOMENT_00_ZERO_ERROR ),
error_entry( NPP_THRESHOLD_NEGATIVE_LEVEL_ERROR ),
error_entry( NPP_THRESHOLD_ERROR ),
error_entry( NPP_CONTEXT_MATCH_ERROR ),
error_entry( NPP_FFT_FLAG_ERROR ),
error_entry( NPP_FFT_ORDER_ERROR ),
error_entry( NPP_SCALE_RANGE_ERROR ),
error_entry( NPP_DATA_TYPE_ERROR ),
error_entry( NPP_OUT_OFF_RANGE_ERROR ),
error_entry( NPP_DIVIDE_BY_ZERO_ERROR ),
error_entry( NPP_MEMORY_ALLOCATION_ERR ),
error_entry( NPP_RANGE_ERROR ),
error_entry( NPP_BAD_ARGUMENT_ERROR ),
error_entry( NPP_NO_MEMORY_ERROR ),
error_entry( NPP_ERROR_RESERVED ),
error_entry( NPP_NO_OPERATION_WARNING ),
error_entry( NPP_DIVIDE_BY_ZERO_WARNING ),
error_entry( NPP_WRONG_INTERSECTION_ROI_WARNING ),
#endif
error_entry( NPP_NOT_SUPPORTED_MODE_ERROR ),
error_entry( NPP_ROUND_MODE_NOT_SUPPORTED_ERROR ),
error_entry( NPP_RESIZE_NO_OPERATION_ERROR ),
error_entry( NPP_LUT_NUMBER_OF_LEVELS_ERROR ),
error_entry( NPP_TEXTURE_BIND_ERROR ),
error_entry( NPP_WRONG_INTERSECTION_ROI_ERROR ),
error_entry( NPP_NOT_EVEN_STEP_ERROR ),
error_entry( NPP_INTERPOLATION_ERROR ),
error_entry( NPP_RESIZE_FACTOR_ERROR ),
error_entry( NPP_HAAR_CLASSIFIER_PIXEL_MATCH_ERROR ),
error_entry( NPP_MEMCPY_ERROR ),
error_entry( NPP_ALIGNMENT_ERROR ),
error_entry( NPP_STEP_ERROR ),
error_entry( NPP_SIZE_ERROR ),
error_entry( NPP_NULL_POINTER_ERROR ),
error_entry( NPP_CUDA_KERNEL_EXECUTION_ERROR ),
error_entry( NPP_NOT_IMPLEMENTED_ERROR ),
error_entry( NPP_ERROR ),
error_entry( NPP_NO_ERROR ),
error_entry( NPP_SUCCESS ),
error_entry( NPP_WRONG_INTERSECTION_QUAD_WARNING ),
error_entry( NPP_MISALIGNED_DST_ROI_WARNING ),
error_entry( NPP_AFFINE_QUAD_INCORRECT_WARNING ),
error_entry( NPP_DOUBLE_SIZE_WARNING )
};
const size_t npp_error_num = sizeof(npp_errors) / sizeof(npp_errors[0]);
//////////////////////////////////////////////////////////////////////////
// NCV errors
const ErrorEntry ncv_errors [] =
{
error_entry( NCV_SUCCESS ),
error_entry( NCV_UNKNOWN_ERROR ),
error_entry( NCV_CUDA_ERROR ),
error_entry( NCV_NPP_ERROR ),
error_entry( NCV_FILE_ERROR ),
error_entry( NCV_NULL_PTR ),
error_entry( NCV_INCONSISTENT_INPUT ),
error_entry( NCV_TEXTURE_BIND_ERROR ),
error_entry( NCV_DIMENSIONS_INVALID ),
error_entry( NCV_INVALID_ROI ),
error_entry( NCV_INVALID_STEP ),
error_entry( NCV_INVALID_SCALE ),
error_entry( NCV_INVALID_SCALE ),
error_entry( NCV_ALLOCATOR_NOT_INITIALIZED ),
error_entry( NCV_ALLOCATOR_BAD_ALLOC ),
error_entry( NCV_ALLOCATOR_BAD_DEALLOC ),
error_entry( NCV_ALLOCATOR_INSUFFICIENT_CAPACITY ),
error_entry( NCV_ALLOCATOR_DEALLOC_ORDER ),
error_entry( NCV_ALLOCATOR_BAD_REUSE ),
error_entry( NCV_MEM_COPY_ERROR ),
error_entry( NCV_MEM_RESIDENCE_ERROR ),
error_entry( NCV_MEM_INSUFFICIENT_CAPACITY ),
error_entry( NCV_HAAR_INVALID_PIXEL_STEP ),
error_entry( NCV_HAAR_TOO_MANY_FEATURES_IN_CLASSIFIER ),
error_entry( NCV_HAAR_TOO_MANY_FEATURES_IN_CASCADE ),
error_entry( NCV_HAAR_TOO_LARGE_FEATURES ),
error_entry( NCV_HAAR_XML_LOADING_EXCEPTION ),
error_entry( NCV_NOIMPL_HAAR_TILTED_FEATURES ),
error_entry( NCV_WARNING_HAAR_DETECTIONS_VECTOR_OVERFLOW ),
error_entry( NPPST_SUCCESS ),
error_entry( NPPST_ERROR ),
error_entry( NPPST_CUDA_KERNEL_EXECUTION_ERROR ),
error_entry( NPPST_NULL_POINTER_ERROR ),
error_entry( NPPST_TEXTURE_BIND_ERROR ),
error_entry( NPPST_MEMCPY_ERROR ),
error_entry( NPPST_MEM_ALLOC_ERR ),
error_entry( NPPST_MEMFREE_ERR ),
error_entry( NPPST_INVALID_ROI ),
error_entry( NPPST_INVALID_STEP ),
error_entry( NPPST_INVALID_SCALE ),
error_entry( NPPST_MEM_INSUFFICIENT_BUFFER ),
error_entry( NPPST_MEM_RESIDENCE_ERROR ),
error_entry( NPPST_MEM_INTERNAL_ERROR )
};
const size_t ncv_error_num = sizeof(ncv_errors) / sizeof(ncv_errors[0]);
//////////////////////////////////////////////////////////////////////////
// CUFFT errors
#ifdef HAVE_CUFFT
const ErrorEntry cufft_errors[] =
{
error_entry( CUFFT_INVALID_PLAN ),
error_entry( CUFFT_ALLOC_FAILED ),
error_entry( CUFFT_INVALID_TYPE ),
error_entry( CUFFT_INVALID_VALUE ),
error_entry( CUFFT_INTERNAL_ERROR ),
error_entry( CUFFT_EXEC_FAILED ),
error_entry( CUFFT_SETUP_FAILED ),
error_entry( CUFFT_INVALID_SIZE ),
error_entry( CUFFT_UNALIGNED_DATA )
};
const int cufft_error_num = sizeof(cufft_errors) / sizeof(cufft_errors[0]);
#endif
//////////////////////////////////////////////////////////////////////////
// CUBLAS errors
#ifdef HAVE_CUBLAS
const ErrorEntry cublas_errors[] =
{
error_entry( CUBLAS_STATUS_SUCCESS ),
error_entry( CUBLAS_STATUS_NOT_INITIALIZED ),
error_entry( CUBLAS_STATUS_ALLOC_FAILED ),
error_entry( CUBLAS_STATUS_INVALID_VALUE ),
error_entry( CUBLAS_STATUS_ARCH_MISMATCH ),
error_entry( CUBLAS_STATUS_MAPPING_ERROR ),
error_entry( CUBLAS_STATUS_EXECUTION_FAILED ),
error_entry( CUBLAS_STATUS_INTERNAL_ERROR )
};
const int cublas_error_num = sizeof(cublas_errors) / sizeof(cublas_errors[0]);
#endif
}
namespace cv
{
namespace gpu
{
void nppError(int code, const char *file, const int line, const char *func)
{
string msg = getErrorString(code, npp_errors, npp_error_num);
cv::gpu::error(msg.c_str(), file, line, func);
}
void ncvError(int code, const char *file, const int line, const char *func)
{
string msg = getErrorString(code, ncv_errors, ncv_error_num);
cv::gpu::error(msg.c_str(), file, line, func);
}
#ifdef HAVE_CUFFT
void cufftError(int code, const char *file, const int line, const char *func)
{
string msg = getErrorString(code, cufft_errors, cufft_error_num);
cv::gpu::error(msg.c_str(), file, line, func);
}
#endif
#ifdef HAVE_CUBLAS
void cublasError(int code, const char *file, const int line, const char *func)
{
string msg = getErrorString(code, cublas_errors, cublas_error_num);
cv::gpu::error(msg.c_str(), file, line, func);
}
#endif
}
}
#endif
| [
"thatindiangeek@gmail.com"
] | thatindiangeek@gmail.com |
7f4691976309053bb78deb646a28b9173b35bd81 | 0c420e8b97af7a1dacb668b1b8ef1180a8d47588 | /Backup2306/+EvApplication/EvApplication/StationMapping.h | 5d83a872a506f682aaf4cbc29e56319795c4970f | [] | no_license | Spritutu/Halcon_develop | 9da18019b3fefac60f81ed94d9ce0f6b04ce7bbe | f2ea3292e7a13d65cab5cb5a4d507978ca593b66 | refs/heads/master | 2022-11-04T22:17:35.137845 | 2020-06-22T17:30:19 | 2020-06-22T17:30:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,636 | h | #pragma once
#include "resource.h"
#include "afxwin.h"
#include "Application.h"
#include "LightHandler.h"
#include "LightControl.h"
#include "PictureCtrl.h"
#define MAX_DIE_FOVS 40//40
#define MAX_DIE_MAP_FOVS 40
// CStationMapping dialog
class CStationMapping : public CDialogEx
{
DECLARE_DYNAMIC(CStationMapping)
public:
CStationMapping(CWnd* pParent = NULL); // standard constructor
virtual ~CStationMapping();
// Dialog Data
enum { IDD = IDD_STATION_MAP_DLG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
DECLARE_MESSAGE_MAP()
public:
CApplication* pApp;
CPictureCtrl *m_diePicCtrl;
CRgn* m_prgnPositionSelection;
BOOL* m_bPosSelection;
CRgn* m_prgnDieMapPositionSel;
BOOL* m_bDieMapPosSel;
CBrush m_brushCheck;
CBrush m_brushUncheck;
CBrush m_brushBorder;
CComboBox m_ctrlCameraID;
CListBox m_ctrlDieMap;
CListBox m_ctrlDieMapPosID;
CRect m_rectPositionSelections;
CRect m_rectDieMapPosSel;
int m_nPosSelectionCount;
int m_nDieMapSelCount;
int m_nCurSelectedDieMapPosID;
//double m_dZMotorRelativeMoveDisp;
CString m_strZMotorRelativeMoveDisp;
int m_nZMotorPosDisp;
double m_dZMotorScanMaxDisp;
double m_dZMotorRelativeMove[3];
int m_nZMotorPos[3];
double m_dZMotorScanMax[3];
BOOL m_bRelativeCheck[3];
BOOL m_bLightDlgOpen;
CStringArray m_strDieMapContents[3];//// max. 3 tracks;
CStringArray m_strDiePosIDContents[3][8];//// max. 3 tracks; max. 8 FOVs
CStringArray m_strPulseValue[3];//// max. 3 tracks;
void Initialize();
void StationMappingFile(BOOL bRead=TRUE);
void UpAndDownZMotorServoButton(BOOL bEnable);
void ResetListBoxContents();
void ScrollBarEnable(BOOL bHorizontal);
void NavigateListBoxContents(int nRow, BOOL bDown, BOOL bKeyDown=FALSE);
void MoveToFOVPosAndSetLight();
void RemoveFromDieMapPosId(int nTrack, int nSel);
void ClearAll();
void SetFOVPositionToMotionCtrl(int nTrack, int nFOV, BOOL bHome);
int SetZPositionValues(int nTrack, int nFOV, int nDoc, CString strSel);
void SetLightValues(int nTrack, int nDocCount, int nFOV, CString strSel, CString strPulse);
public:
virtual BOOL OnInitDialog();
afx_msg void OnPaint();
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
//afx_msg void OnRButtonDown(UINT nFlags, CPoint point);
afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point);
afx_msg int OnVKeyToItem(UINT nKey, CListBox* pListBox, UINT nIndex);
afx_msg void OnTimer(UINT_PTR nIDEvent);
afx_msg void OnSelchangeSmCamidCombo();
afx_msg void OnBnClickedSmSelectallButton();
afx_msg void OnBnClickedSmDieMapAddMfcbutton();
afx_msg void OnBnClickedSmDieMapRemoveMfcbutton();
afx_msg void OnBnClickedSmDieMapRetakeMfcbutton();
//afx_msg void OnDblclkSmDieMapList();
afx_msg void OnSelchangeSmDieMapList();
afx_msg void OnBnClickedSmDieMapSwapMfcbutton();
afx_msg void OnBnClickedSmDieMapPosmoveSetlightButton();
afx_msg void OnBnClickedSmDieMapPosidRemoveMfcbutton();
afx_msg void OnBnClickedSmDieMapLivecamLightButton();
afx_msg void OnBnClickedSmSaveAllTeachButton();
afx_msg void OnBnClickedSmSaveOneTeachButton();
afx_msg void OnBnClickedSmLoadTeachButton();
afx_msg void OnBnClickedSmSetImgIdButton();
afx_msg void OnUpdateSmStartEdit();
afx_msg void OnUpdateSmMaxEdit();
afx_msg void OnUpdateSmZMtrServoEdit();
afx_msg void OnClickedSmZMtrServoCheck();
afx_msg void OnBnClickedSmZMtrServoUpMfcbutton();
afx_msg void OnBnClickedSmZMtrServoDownMfcbutton();
afx_msg void OnBnClickedOk();
afx_msg void OnBnClickedCancel();
afx_msg void OnClose();
afx_msg void OnBnClickedSmNeglectMfcbutton();
afx_msg void OnBnClickedSmSaveTeachImageAllButton();
};
| [
"huynhbuutu@gmail.com"
] | huynhbuutu@gmail.com |
dbefd1fada1a9347c7994afcbd8db74ac14cec79 | 3b35be12f239c6d22b59942052a87a442c6fcbe4 | /src/memory_manager.cpp | 6db06476486ec4b7400efaf5ad9ffb7fa02252db | [
"Apache-2.0"
] | permissive | yutiansut/rmm | 0f8848d9cec8bd700815cb5668a7a257b00a159c | bf26308344d112106ef631f9d528c6fa6d588dc2 | refs/heads/branch-0.9 | 2020-06-19T14:49:49.850018 | 2019-07-03T03:08:59 | 2019-07-03T03:08:59 | 196,750,717 | 0 | 0 | Apache-2.0 | 2019-07-13T17:54:04 | 2019-07-13T17:52:31 | C++ | UTF-8 | C++ | false | false | 4,226 | cpp | /*
* Copyright (c) 2018, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "rmm/detail/memory_manager.hpp"
namespace rmm
{
/** -----------------------------------------------------------------------*
* Record a memory manager event in the log.
*
* @param[in] event The type of event (Alloc, Realloc, or Free)
* @param[in] DeviceId The device to which this event applies.
* @param[in] ptr The device pointer being allocated or freed.
* @param[in] t The timestamp to record.
* @param[in] size The size of allocation (only needed for Alloc/Realloc).
* @param[in] stream The stream on which the allocation is happening
* (only needed for Alloc/Realloc).
* ----------------------------------------------------------------------**/
void Logger::record(MemEvent_t event, int deviceId, void* ptr,
TimePt start, TimePt end,
size_t freeMem, size_t totalMem,
size_t size, cudaStream_t stream,
std::string filename,
unsigned int line)
{
std::lock_guard<std::mutex> guard(log_mutex);
if (Alloc == event)
current_allocations.insert(ptr);
else if (Free == event)
current_allocations.erase(ptr);
events.push_back({event, deviceId, ptr, size, stream,
freeMem, totalMem, current_allocations.size(),
start, end, filename, line});
}
/** -----------------------------------------------------------------------*
* @brief Output a comma-separated value string of the current log to the
* provided ostream
*
* @param[in] csv The output stream to put the CSV log string into.
* ----------------------------------------------------------------------**/
void Logger::to_csv(std::ostream &csv)
{
csv << "Event Type,Device ID,Address,Stream,Size (bytes),Free Memory,"
<< "Total Memory,Current Allocs,Start,End,Elapsed,Location\n";
for (auto& e : events)
{
auto event_str = "Alloc";
if (e.event == Realloc) event_str = "Realloc";
if (e.event == Free) event_str = "Free";
std::chrono::duration<double> elapsed = e.end-e.start;
csv << event_str << "," << e.deviceId << "," << e.ptr << ","
<< e.stream << "," << e.size << "," << e.freeMem << ","
<< e.totalMem << "," << e.currentAllocations << ","
<< std::chrono::duration<double>(e.start-base_time).count() << ","
<< std::chrono::duration<double>(e.end-base_time).count() << ","
<< elapsed.count() << "," << e.filename << ":" << e.line
<< std::endl;
}
}
/** ---------------------------------------------------------------------------*
* @brief Clear the log
* --------------------------------------------------------------------------**/
void Logger::clear()
{
std::lock_guard<std::mutex> guard(log_mutex);
events.clear();
}
rmmError_t Manager::registerStream(cudaStream_t stream) {
std::lock_guard<std::mutex> guard(streams_mutex);
if (registered_streams.empty() || 0 == registered_streams.count(stream)) {
registered_streams.insert(stream);
if (stream && usePoolAllocator()) // don't register the null stream with CNMem
RMM_CHECK_CNMEM( cnmemRegisterStream(stream) );
}
return RMM_SUCCESS;
}
}
| [
"mharris@nvidia.com"
] | mharris@nvidia.com |
cdc88d47a583b222c42c5365506e71cf6acc6f24 | e7e497b20442a4220296dea1550091a457df5a38 | /main_project/feed/FeedDispatcherN/src/ExpressionParser.cpp | b69a24e602104df32bbafbaa457c6011a19d1cbc | [] | no_license | gunner14/old_rr_code | cf17a2dedf8dfcdcf441d49139adaadc770c0eea | bb047dc88fa7243ded61d840af0f8bad22d68dee | refs/heads/master | 2021-01-17T18:23:28.154228 | 2013-12-02T23:45:33 | 2013-12-02T23:45:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 51,942 | cpp | /*
* test.cpp
*
* Created on: Apr 8, 2010
* Author: yejingwei
*/
#include "ExpressionParser.h"
#include <iostream>
#include <sstream>
#include <boost/tuple/tuple.hpp>
#include <exception>
#include <set>
#include <stdexcept>
#include <ostream>
#include <algorithm>
#include <boost/lexical_cast.hpp>
#include <QueryRunner.h>
#include <DbDescriptor.h>
#include "ServiceI.h"
#include "FriendRankCacheAdapter.h"
#include "BuddyByIdReplicaAdapter.h"
#include "ad/gj_cache/src/UserCacheClientPlus.h"
#include "feed/Degrade/src/Degrade.h"
using namespace std;
using namespace xce::feed;
using namespace xce::socialgraph;
using namespace com::xiaonei::xce;
using namespace xce::buddy;
using namespace MyUtil;
set<int> Parser::CalculateIds() {
MCE_DEBUG("Parser::CalculateIds()");
size_t index = 0;
// TempResultPtr temp_result = new TempResult();//保存中间结果
set<int> result;
vector<FactorPtr>::iterator fit = factors_.begin();
if(factors_.size()==0) {
MCE_WARN("Parser::CalculateIds --> factors NULL")
return result;
}
(*fit)->Plus(result);//对于第一个factor,加上一个空的ids,没有影响
MCE_DEBUG("Parser::CalculateIds --> After calculating factor :" << index << ",result size = " << result.size());
++fit;
++index;
vector<Op>::iterator oit = ops_.begin();
while (fit != factors_.end()) {
char op = (*oit).op_type();
switch (op) {
case '+':
(*fit)->Plus(result);
break;
case '-':
if(result.empty()){ //空的话,-结果还是空
break;
}
(*fit)->Minus(result);
break;
case '&':
if(result.empty()){//空的话,&结果还是空
break;
}
(*fit)->And(result);
break;
}
MCE_DEBUG("Parser::CalculateIds --> After calculating factor :" << index << ",result size = " << result.size());
++oit;
++fit;
++index;
}
return result;
}
bool Parser::Init(string & expr) {
MCE_DEBUG("Parser::Init --> expression = " << expr);
expr_str_ = expr;
return true;
}
vector<FactorPtr> Parser::Tokenize() {
MCE_INFO("Parser::Tokenize --> expr = " << expr_str_ );
if(expr_str_.size() == 0) {
MCE_WARN("Parser::Tokenize --> expr NULL");
return factors_;
}
size_t pos = 0;
while (pos < expr_str_.size()) {
char tmpchar = expr_str_[pos];
if (kOpTypes.find(tmpchar) != string::npos) {//字符是操作符
Op tmpOp(tmpchar);
ops_.push_back(tmpOp);
++pos;
} else if (kFactorTypes.find(tmpchar) != string::npos) {//字符是因子类型符号
factors_.push_back(ScanFactor(pos));
} else {
ostringstream oss;
oss << "Parser::Tokenize() --> wrong charactor : '" << tmpchar
<< "',at position:" << pos << ",expression:" << expr_str_;
string s = oss.str();
throw logic_error(s);
}
}
ostringstream foss;
foss << "Parser::Tokenize --> factors are :";
for (vector<FactorPtr>::iterator sit = factors_.begin(); sit
!= factors_.end(); ++sit) {
// if ((*sit)->type() != 'J')
foss << (*sit)->type() << " " << (*sit)->param_id() << ",";
// else
// foss << (*sit)->type() << " " << (*sit)->param_idL() << ",";
}
MCE_DEBUG(foss.str());
ostringstream eoss;
eoss << "Parser::Tokenize --> operators are :";
if (ops_.size() == 0) {
eoss << " empty ";
} else {
for (vector<Op>::iterator sit = ops_.begin(); sit != ops_.end(); ++sit) {
eoss << sit->op_type() << ",";
}
}
MCE_DEBUG(eoss.str());
return factors_;
}
FactorPtr Parser::ScanFactor(size_t & pos) {
char tmpchar = expr_str_[pos];
/* MCE_DEBUG("Parser::ScanFactor() --> tmpchar = " << tmpchar);*/
switch (tmpchar) {
case 'f': {
return new FriendFactor(tmpchar, ScanInteger(pos));
}
case 'u': {
return new UserFactor(tmpchar, ScanInteger(pos));
}
case 'a': {
return new AppFactor(tmpchar, ScanInteger(pos));
}
case 'A': {
return new AppFanFactor(tmpchar, ScanInteger(pos));
}
case 'p': {
return new PageFactor(tmpchar, ScanInteger(pos));
}
case 's': {
return new HighSchoolFactor(tmpchar, ScanInteger(pos));
}
case 'g': {
return new MiniGroupFactor(tmpchar, ScanInteger(pos));
}
case 'v': {
return new FollowFactor(tmpchar, ScanInteger(pos));
}
case 'z': {
return new XiaoZuFactor(tmpchar, ScanInteger(pos));
}
case 'x': {
return new MiniSiteFactor(tmpchar, ScanInteger(pos));
}
case 'c': {
return new CheWenFactor(tmpchar, ScanInteger(pos));
}
case 'j': {
return new GuangJieFactor(tmpchar, ScanInteger(pos));
}
//shilong.li 2012-07-23
//case 'J': {
//ID is long type
// size_t start = expr_str_.find("(", pos);
// size_t end = expr_str_.find(")", pos);
// if (start > end) {
// throw logic_error("Parser::ScanInteger() --> start larger than end");
// }
// pos = end + 1;
// string longstr = expr_str_.substr(start + 1, end - start - 1);
// long value = boost::lexical_cast<long>(longstr);
//return new GuangJieTopicFactor(tmpchar, value);
//return new GuangJieTopicFactor(tmpchar, ScanLong(pos));
// }
case 't': {
return new TagFactor(tmpchar, ScanInteger(pos));
}
//shilong.li 2012-07-23
// case 'b': {
// return new AlbumFactor(tmpchar, ScanLong(pos));
// }
default:
throw logic_error("Parser::ScanFactor() --> wrong factor type = " + tmpchar);
return NULL;
}
}
Ice::Long Parser::ScanLong(size_t & pos) {//扫描因子括弧内的数字
size_t start = expr_str_.find("(", pos);
size_t end = expr_str_.find(")", pos);
if (start > end) {
throw logic_error("Parser::ScanInteger() --> start larger than end");
}
pos = end + 1;
string intstr = expr_str_.substr(start + 1, end - start - 1);
Ice::Long value = boost::lexical_cast<Ice::Long>(intstr);
/* MCE_DEBUG("Parser::ScanInteger() --> pos = " << pos << ", integer value = " << value);*/
return value;
}
int Parser::ScanInteger(size_t & pos) {//扫描因子括弧内的数字
size_t start = expr_str_.find("(", pos);
size_t end = expr_str_.find(")", pos);
if (start > end) {
throw logic_error("Parser::ScanInteger() --> start larger than end");
}
pos = end + 1;
string intstr = expr_str_.substr(start + 1, end - start - 1);
int value = boost::lexical_cast<int>(intstr);
/* MCE_DEBUG("Parser::ScanInteger() --> pos = " << pos << ", integer value = " << value);*/
return value;
}
void Parser::PrintIds() {
MCE_DEBUG( "ids_'s size is :" << expr_ids_.size() );
for (set<int>::iterator itr = expr_ids_.begin(); itr != expr_ids_.end(); ++itr) {
MCE_DEBUG( *itr << " ");
}
}
//--------------------------------------------------------------------------
void AppFactor::Plus(set<int> & result) {
if ( !DegradeManager::instance().IsEnable("FeedDispatcher::module_AppExpr") ) {
return;
}
string head = GenerateSQL();
Statement sql;
sql << head;
mysqlpp::StoreQueryResult res;
try {
res = QueryRunner(instance_, CDbRServer, table_).store(sql);
} catch (Ice::Exception& e) {
MCE_WARN(" AppFactor::Plus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" AppFactor::Plus --> error:" << e.what());
}
if (!res) {
MCE_WARN("StoryQueryResult wrong");
return;
}
for (size_t i = 0; i < res.size(); ++i) {
result.insert(res.at(i)["user_id"]);
}
}
void AppFactor::Minus(set<int> & result) {
if ( !DegradeManager::instance().IsEnable("FeedDispatcher::module_AppExpr") ) {
return;
}
string head = GenerateSQL();
Statement sql;
sql << head;
sql << " AND user_id IN (";
set<int>::iterator itr = result.begin();
sql << *itr;
for (++itr; itr != result.end(); ++itr) {
sql << "," << *itr;
}
sql << ")";
mysqlpp::StoreQueryResult res;
try {
res = QueryRunner(instance_, CDbRServer, table_).store(sql);
} catch (Ice::Exception& e) {
MCE_WARN(" AppFactor::Plus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" AppFactor::Plus --> error:" << e.what());
}
if (!res) {
MCE_WARN("StoryQueryResult wrong");
return;
}
for (size_t i = 0; i < res.size(); ++i) {
result.erase(res.at(i)["user_id"]);
}
}
void AppFactor::And(set<int> & result) {
if ( !DegradeManager::instance().IsEnable("FeedDispatcher::module_AppExpr") ) {
return;
}
string head = GenerateSQL();
Statement sql;
sql << head;
sql << " AND user_id IN (";
set<int>::iterator itr = result.begin();
sql << *itr;
for (++itr; itr != result.end(); ++itr) {
sql << "," << *itr;
}
sql << ")";
mysqlpp::StoreQueryResult res;
try {
res = QueryRunner(instance_, CDbRServer, table_).store(sql);
} catch (Ice::Exception& e) {
MCE_WARN(" AppFactor::Plus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" AppFactor::Plus --> error:" << e.what());
}
MCE_DEBUG("AppFactor::And");
result.clear();
if (!res) {
MCE_WARN("StoryQueryResult wrong");
return;
}
for (size_t i = 0; i < res.size(); ++i) {
result.insert(res.at(i)["user_id"]);
}
}
string AppFactor::GenerateSQL() { //app
ostringstream tablestream;
tablestream << "app_user_" << (param_id_ % 100);
table_ = tablestream.str();
ostringstream oss;
oss << "SELECT user_id FROM " << table_ << " WHERE app_id = " << param_id_ << " ";
string tmpstr = oss.str();
return tmpstr;
}
//--------------------------------------------------------------------------
void AppFanFactor::Plus(set<int> & result) {
if ( !DegradeManager::instance().IsEnable("FeedDispatcher::module_AppFansExpr") ) {
return;
}
string head = GenerateSQL();
Statement sql;
sql << head;
mysqlpp::StoreQueryResult res;
try {
res = QueryRunner(instance_, CDbRServer, table_).store(sql);
} catch (Ice::Exception& e) {
MCE_WARN(" AppFanFactor::Plus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" AppFanFactor::Plus --> error:" << e.what());
}
for (size_t i = 0; i < res.size(); ++i) {
result.insert(res.at(i)["user_id"]);
}
}
void AppFanFactor::Minus(set<int> & result) {
if ( !DegradeManager::instance().IsEnable("FeedDispatcher::module_AppFansExpr") ) {
return;
}
string head = GenerateSQL();
Statement sql;
sql << head;
sql << " AND user_id IN (";
set<int>::iterator itr = result.begin();
sql << *itr;
for (++itr; itr != result.end(); ++itr) {
sql << "," << *itr;
}
sql << ")";
mysqlpp::StoreQueryResult res;
try {
res = QueryRunner(instance_, CDbRServer, table_).store(sql);
} catch (Ice::Exception& e) {
MCE_WARN(" AppFanFactor::Plus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" AppFanFactor::Plus --> error:" << e.what());
}
if (!res) {
MCE_WARN("StoryQueryResult wrong");
return;
}
for (size_t i = 0; i < res.size(); ++i) {
result.erase(res.at(i)["user_id"]);
}
}
void AppFanFactor::And(set<int> & result) {
if ( !DegradeManager::instance().IsEnable("FeedDispatcher::module_AppFansExpr") ) {
return;
}
string head = GenerateSQL();
Statement sql;
sql << head;
sql << " AND user_id IN (";
set<int>::iterator itr = result.begin();
sql << *itr;
for (++itr; itr != result.end(); ++itr) {
sql << "," << *itr;
}
sql << ")";
mysqlpp::StoreQueryResult res;
try {
res = QueryRunner(instance_, CDbRServer, table_).store(sql);
} catch (Ice::Exception& e) {
MCE_WARN(" AppFanFactor::Plus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" AppFanFactor::Plus --> error:" << e.what());
}
result.clear();
if (!res) {
MCE_WARN("StoryQueryResult wrong");
return;
}
for (size_t i = 0; i < res.size(); ++i) {
result.insert(res.at(i)["user_id"]);
}
}
string AppFanFactor::GenerateSQL() { //app fans
ostringstream tab;
tab << "app_fans" << "_" << (param_id_ % 100);
table_ = tab.str();
ostringstream sql;
sql << "SELECT user_id FROM " << table_ << " WHERE app_id=" << param_id_ << " ";
string tmpstr = sql.str();
return tmpstr;
}
//--------------------------------------------------------------------------
void PageFactor::Plus(set<int> & result) {
if ( !DegradeManager::instance().IsEnable("FeedDispatcher::module_PageExpr") ) {
return;
}
string head = GenerateSQL();
Statement sql;
sql << head;
mysqlpp::StoreQueryResult res;
try {
res = QueryRunner(instance_, CDbRServer, table_).store(sql);
} catch (Ice::Exception& e) {
MCE_WARN(" PageFactor::Plus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" PageFactor::Plus --> error:" << e.what());
}
for (size_t i = 0; i < res.size(); ++i) {
result.insert(res.at(i)["user_id"]);
}
}
void PageFactor::Minus(set<int> & result) {
if ( !DegradeManager::instance().IsEnable("FeedDispatcher::module_PageExpr") ) {
return;
}
string head = GenerateSQL();
Statement sql;
sql << head;
sql << " AND user_id IN (";
set<int>::iterator itr = result.begin();
sql << *itr;
for (++itr; itr != result.end(); ++itr) {
sql << "," << *itr;
}
sql << ")";
mysqlpp::StoreQueryResult res;
try {
res = QueryRunner(instance_, CDbRServer, table_).store(sql);
} catch (Ice::Exception& e) {
MCE_WARN(" PageFactor::Plus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" PageFactor::Plus --> error:" << e.what());
}
if (!res) {
MCE_WARN("StoryQueryResult wrong");
return;
}
for (size_t i = 0; i < res.size(); ++i) {
result.erase(res.at(i)["user_id"]);
}
}
void PageFactor::And(set<int> & result) {
if ( !DegradeManager::instance().IsEnable("FeedDispatcher::module_PageExpr") ) {
return;
}
string head = GenerateSQL();
Statement sql;
sql << head;
sql << " AND user_id IN (";
set<int>::iterator itr = result.begin();
sql << *itr;
for (++itr; itr != result.end(); ++itr) {
sql << "," << *itr;
}
sql << ")";
mysqlpp::StoreQueryResult res;
try {
res = QueryRunner(instance_, CDbRServer, table_).store(sql);
} catch (Ice::Exception& e) {
MCE_WARN(" PageFactor::Plus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" PageFactor::Plus --> error:" << e.what());
}
result.clear();
if (!res) {
MCE_WARN("StoryQueryResult wrong");
return;
}
for (size_t i = 0; i < res.size(); ++i) {
result.insert(res.at(i)["user_id"]);
}
}
string PageFactor::GenerateSQL() {
ServiceI &service = ServiceI::instance();
Ice::PropertiesPtr props = service.getCommunicator()->getProperties();
instance_ = props->getPropertyWithDefault("Service.Database.PageFans",
"page_fans");
table_ = props->getPropertyWithDefault("Service.table.PageFans", "page_fans");
ostringstream pageFansTab;
pageFansTab << table_ << "_" << (param_id_ % 100);
table_ = pageFansTab.str();
ostringstream sql;
sql << "SELECT user_id FROM " << pageFansTab.str() << " WHERE page_id="
<< param_id_ << " AND state=0";
string tmpstr = sql.str();
//MCE_DEBUG("PageFactor::GenerateSQL --> the sql head = " << tmpstr);
return tmpstr;
}
//--------------------------------------------------------------------------
void FollowFactor::Plus(set<int> & result) {
string head = GenerateSQL();
Statement sql;
sql << head;
mysqlpp::StoreQueryResult res;
try {
res = QueryRunner(instance_, CDbRServer, table_).store(sql);
} catch (Ice::Exception& e) {
MCE_WARN(" PageFactor::Plus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" PageFactor::Plus --> error:" << e.what());
}
for (size_t i = 0; i < res.size(); ++i) {
result.insert(res.at(i)["follower_id"]);
}
}
void FollowFactor::Minus(set<int> & result) {
string head = GenerateSQL();
Statement sql;
sql << head;
sql << " AND follower_id IN (";
set<int>::iterator itr = result.begin();
sql << *itr;
for (++itr; itr != result.end(); ++itr) {
sql << "," << *itr;
}
sql << ")";
mysqlpp::StoreQueryResult res;
try {
res = QueryRunner(instance_, CDbRServer, table_).store(sql);
} catch (Ice::Exception& e) {
MCE_WARN(" PageFactor::Plus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" PageFactor::Plus --> error:" << e.what());
}
if (!res) {
MCE_WARN("StoryQueryResult wrong");
return;
}
for (size_t i = 0; i < res.size(); ++i) {
result.erase(res.at(i)["follower_id"]);
}
}
void FollowFactor::And(set<int> & result) {
string head = GenerateSQL();
Statement sql;
sql << head;
sql << " AND follower_id IN (";
set<int>::iterator itr = result.begin();
sql << *itr;
for (++itr; itr != result.end(); ++itr) {
sql << "," << *itr;
}
sql << ")";
mysqlpp::StoreQueryResult res;
try {
res = QueryRunner(instance_, CDbRServer, table_).store(sql);
} catch (Ice::Exception& e) {
MCE_WARN(" PageFactor::Plus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" PageFactor::Plus --> error:" << e.what());
}
result.clear();
if (!res) {
MCE_WARN("StoryQueryResult wrong");
return;
}
for (size_t i = 0; i < res.size(); ++i) {
result.insert(res.at(i)["follower_id"]);
}
}
string FollowFactor::GenerateSQL() {
ServiceI &service = ServiceI::instance();
Ice::PropertiesPtr props = service.getCommunicator()->getProperties();
instance_ = props->getPropertyWithDefault("Service.Database.VFollows",
"page");
table_ = props->getPropertyWithDefault("Service.table.VFollows", "v_follow_list");
//ostringstream pageFansTab;
//pageFansTab << table_ << "_" << (param_id_ % 100);
//table_ = pageFansTab.str();
ostringstream sql;
sql << "SELECT follower_id FROM " << table_ << " WHERE v_id="
<< param_id_;
string tmpstr = sql.str();
//MCE_DEBUG("PageFactor::GenerateSQL --> the sql head = " << tmpstr);
return tmpstr;
}
//--------------------------------------------------------------------------
void FriendFactor::Plus(set<int> & result) {
//string head = GenerateSQL();
//Statement sql;
//sql << head;
//mysqlpp::StoreQueryResult res;
int count = 0;
int begin = 0;
int limit = 5000;
MyUtil::IntSeq friends;
do {
try {
//res = QueryRunner(instance_, CDbRServer, table_).store(sql);
friends.clear();
friends = adapter::BuddyByIdCacheAdapter::instance().getFriendListAsc(param_id_,begin,limit);
} catch (Ice::Exception& e) {
MCE_WARN(" FriendFactor::Plus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" FriendFactor::Plus --> error:" << e.what());
} catch (...) {
MCE_WARN(" FriendFactor::Plis --> unkown error");
}
for (size_t i = 0; i < friends.size(); ++i) {
result.insert(friends[i]);
}
MCE_INFO("FriendFactor::Plus --> uid:"<<param_id_<<" conut:"<<count<<" begin:"<<begin<<" friends size:"<<friends.size()<<" result size:"<<result.size());
count++;
begin += limit;
} while(friends.size() >= limit );
}
void FriendFactor::Minus(set<int> & result) {
/*string head = GenerateSQL();
Statement sql;
sql << head;
sql << " AND guest IN (";
set<int>::iterator itr = result.begin();
sql << *itr;
for (++itr; itr != result.end(); ++itr) {
sql << "," << *itr;
}
sql << ")";
mysqlpp::StoreQueryResult res;*/
int count = 0;
int begin = 0;
int limit = 5000;
MyUtil::IntSeq friends;
do {
try {
// res = QueryRunner(instance_, CDbRServer, table_).store(sql);
friends.clear();
friends = adapter::BuddyByIdCacheAdapter::instance().getFriendListAsc(param_id_,begin,limit);
} catch (Ice::Exception& e) {
MCE_WARN(" FriendFactor::Minus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" FriendFactor::Minus --> error:" << e.what());
} catch (...) {
MCE_WARN(" FriendFactor::Minus --> unkown error");
}
for (size_t i = 0; i < friends.size(); ++i) {
if (result.find( friends[i]) == result.end())
continue;
result.erase(friends[i]);
}
if (result.empty()) {
MCE_INFO("FriendFactor::Minus --> result has EMPTY so break loop;");
break;
}
MCE_INFO("FriendFactor::Minus --> uid:"<<param_id_<<" conut:"<<count<<" begin:"<<begin<<" friends size:"<<friends.size()<<" result size:"<<result.size());
count++;
begin += limit;
}while( friends.size() >= limit);
}
void FriendFactor::And(set<int> & result) {
/*
string head = GenerateSQL();
Statement sql;
sql << head;
sql << " AND guest IN (";
set<int>::iterator itr = result.begin();
sql << *itr;
for (++itr; itr != result.end(); ++itr) {
sql << "," << *itr;
}
sql << ")";
mysqlpp::StoreQueryResult res;*/
int count = 0;
int begin = 0;
int limit = 5000;
MyUtil::IntSeq friends;
set<int> and_result;
do {
try {
//res = QueryRunner(instance_, CDbRServer, table_).store(sql);
friends.clear();
friends = adapter::BuddyByIdCacheAdapter::instance().getFriendListAsc(param_id_,begin,limit);
} catch (Ice::Exception& e) {
MCE_WARN(" FriendFactor::And --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" FriendFactor::And --> error:" << e.what());
} catch(...) {
MCE_INFO(" FriendFactor::And --> unkown error");
}
for (size_t i = 0; i < friends.size(); ++i) {
if (result.find(friends[i]) != result.end() ){
and_result.insert(friends[i]);
}
}
if (and_result.size() == result.size() ) {
MCE_INFO("FriendFactor::And --> result size has FULL so break");
break;
}
MCE_INFO("FriendFactor::And --> uid:"<<param_id_<<" conut:"<<count<<" begin:"<<begin<<" friends size:"<<friends.size()<<"and_result size:"<<and_result.size()<<" result size:"<<result.size());
count++;
begin += limit;
}while(friends.size() >= limit);
result.swap(and_result);
}
string FriendFactor::GenerateSQL() {
ServiceI &service = ServiceI::instance();
Ice::PropertiesPtr props = service.getCommunicator()->getProperties();
instance_ = props->getPropertyWithDefault("Service.Database.Relation",
"xfeed_relation");
table_ = props->getPropertyWithDefault("Service.table.Relation", "relation_");
ostringstream tablename;
tablename << table_ << (param_id_ % 100); //表名
ostringstream sql;
sql << "SELECT guest FROM " << tablename.str() << " WHERE host=" << param_id_
<< " ";
table_ = tablename.str();
return sql.str();
}
//--------------------------------------------------------------------------
void HighSchoolFactor::Plus(set<int> & result) {
string head = GenerateSQL();
Statement sql;
sql << head;
mysqlpp::StoreQueryResult res;
try {
res = QueryRunner(instance_, CDbRServer, table_).store(sql);
} catch (Ice::Exception& e) {
MCE_WARN(" HighSchoolFactor::Plus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" HighSchoolFactor::Plus --> error:" << e.what());
}
ostringstream oss;
for (size_t i = 0; i < res.size(); ++i) {
result.insert(res.at(i)["uid"]);
oss << res.at(i)["uid"] << ",";
}
//MCE_DEBUG("FriendFactor::Plus --> result ids --> " << oss.str());
}
void HighSchoolFactor::Minus(set<int> & result) {
string head = GenerateSQL();
Statement sql;
sql << head;
sql << " AND uid IN (";
set<int>::iterator itr = result.begin();
sql << *itr;
for (++itr; itr != result.end(); ++itr) {
sql << "," << *itr;
}
sql << ")";
mysqlpp::StoreQueryResult res;
try {
res = QueryRunner(instance_, CDbRServer, table_).store(sql);
} catch (Ice::Exception& e) {
MCE_WARN(" HighSchoolFactor::Plus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" HighSchoolFactor::Plus --> error:" << e.what());
}
if (!res) {
MCE_WARN("StoryQueryResult wrong");
return;
}
for (size_t i = 0; i < res.size(); ++i) {
result.erase(res.at(i)["uid"]);
}
}
void HighSchoolFactor::And(set<int> & result) {
string head = GenerateSQL();
Statement sql;
sql << head;
sql << " AND uid IN (";
set<int>::iterator itr = result.begin();
sql << *itr;
for (++itr; itr != result.end(); ++itr) {
sql << "," << *itr;
}
sql << ")";
mysqlpp::StoreQueryResult res;
try {
res = QueryRunner(instance_, CDbRServer, table_).store(sql);
} catch (Ice::Exception& e) {
MCE_WARN(" HighSchoolFactor::Plus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" HighSchoolFactor::Plus --> error:" << e.what());
}
result.clear();
if (!res) {
MCE_WARN("StoryQueryResult wrong");
return;
}
for (size_t i = 0; i < res.size(); ++i) {
result.insert(res.at(i)["uid"]);
}
}
string HighSchoolFactor::GenerateSQL() {
ServiceI &service = ServiceI::instance();
Ice::PropertiesPtr props = service.getCommunicator()->getProperties();
instance_ = props->getPropertyWithDefault("Service.Database.HIGHSCHOOL",
"high_school_page");
table_ = props->getPropertyWithDefault("Service.Table.ASP_MEMBER",
"asp_member");
ostringstream sql;
sql << "SELECT uid FROM " << table_ << " WHERE pid=" << param_id_
<< " AND status=0 AND stage <= 30 ";
return sql.str();
}
//--------------------------------------------------------------------------
void MiniGroupFactor::Plus(set<int> & result) {
if ( !DegradeManager::instance().IsEnable("FeedDispatcher::module_MiniGroupExpr") ) {
return;
}
string head = GenerateSQL();
Statement sql;
sql << head ;
mysqlpp::StoreQueryResult res;
try {
res = QueryRunner(instance_, CDbRServer, table_).store(sql);
} catch (Ice::Exception& e) {
MCE_WARN(" MiniGroupFactor::Plus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" MiniGroupFactor::Plus --> error:" << e.what());
}
ostringstream oss;
for (size_t i = 0; i < res.size(); ++i) {
result.insert(res.at(i)["member_id"]);
// oss << res.at(i)["uid"] << ",";
}
//MCE_DEBUG("FriendFactor::Plus --> result ids --> " << oss.str());
}
void MiniGroupFactor::Minus(set<int> & result) {
if ( !DegradeManager::instance().IsEnable("FeedDispatcher::module_MiniGroupExpr") ) {
return;
}
string head = GenerateSQL();
Statement sql;
sql << head;
sql << " AND member_id IN (";
set<int>::iterator itr = result.begin();
sql << *itr;
for (++itr; itr != result.end(); ++itr) {
sql << "," << *itr;
}
sql << ")";
mysqlpp::StoreQueryResult res;
try {
res = QueryRunner(instance_, CDbRServer, table_).store(sql);
} catch (Ice::Exception& e) {
MCE_WARN(" MiniGroupFactor::Plus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" MiniGroupFactor::Plus --> error:" << e.what());
}
if (!res) {
MCE_WARN("StoryQueryResult wrong");
return;
}
for (size_t i = 0; i < res.size(); ++i) {
result.erase(res.at(i)["member_id"]);
}
}
void MiniGroupFactor::And(set<int> & result) {
if ( !DegradeManager::instance().IsEnable("FeedDispatcher::module_MiniGroupExpr") ) {
return;
}
string head = GenerateSQL();
Statement sql;
sql << head;
sql << " AND member_id IN (";
set<int>::iterator itr = result.begin();
sql << *itr;
for (++itr; itr != result.end(); ++itr) {
sql << "," << *itr;
}
sql << ")";
mysqlpp::StoreQueryResult res;
try {
res = QueryRunner(instance_, CDbRServer, table_).store(sql);
} catch (Ice::Exception& e) {
MCE_WARN(" MiniGroupFactor::Plus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" MiniGroupFactor::Plus --> error:" << e.what());
}
result.clear();
if (!res) {
MCE_WARN("StoryQueryResult wrong");
return;
}
for (size_t i = 0; i < res.size(); ++i) {
result.insert(res.at(i)["member_id"]);
}
}
string MiniGroupFactor::GenerateSQL() {
instance_ = "minigroup";//TODO
ostringstream tmp;
tmp << "minigroup_member_" << param_id_ % 100;
table_ = tmp.str();
ostringstream sql;
sql << "SELECT member_id FROM " << table_ << " WHERE minigroup_id = " << param_id_ << " and access_id in (1,2,3) " ;
return sql.str();
}
//--------------------------------------------------------------------------
void UserFactor::Plus(set<int> & result) {
int intId = (int)param_id_;
result.insert(intId);
}
void UserFactor::Minus(set<int> & result) {
int intId = (int)param_id_;
result.erase(intId);
}
void UserFactor::And(set<int> & result) {
int intId = (int)param_id_;
if (result.find(intId) != result.end()) {
result.clear();
result.insert(intId);
} else {
result.clear();
}
}
//-------------------------------------------------------------------------
void XiaoZuFactor::Plus(set<int> & result) {
if ( !DegradeManager::instance().IsEnable("FeedDispatcher::module_XiaoZuExpr") ) {
return;
}
string head = GenerateSQL();
Statement sql;
sql << head ;
mysqlpp::StoreQueryResult res;
try {
res = QueryRunner(instance_, CDbRServer, table_).store(sql);
} catch (Ice::Exception& e) {
MCE_WARN(" MiniGroupFactor::Plus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" MiniGroupFactor::Plus --> error:" << e.what());
}
ostringstream oss;
for (size_t i = 0; i < res.size(); ++i) {
result.insert(res.at(i)["member_id"]);
// oss << res.at(i)["uid"] << ",";
}
//MCE_DEBUG("FriendFactor::Plus --> result ids --> " << oss.str());
}
void XiaoZuFactor::Minus(set<int> & result) {
if ( !DegradeManager::instance().IsEnable("FeedDispatcher::module_XiaoZuExpr") ) {
return;
}
string head = GenerateSQL();
Statement sql;
sql << head;
sql << " AND member_id IN (";
set<int>::iterator itr = result.begin();
sql << *itr;
for (++itr; itr != result.end(); ++itr) {
sql << "," << *itr;
}
sql << ")";
mysqlpp::StoreQueryResult res;
try {
res = QueryRunner(instance_, CDbRServer, table_).store(sql);
} catch (Ice::Exception& e) {
MCE_WARN(" MiniGroupFactor::Plus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" MiniGroupFactor::Plus --> error:" << e.what());
}
if (!res) {
MCE_WARN("StoryQueryResult wrong");
return;
}
for (size_t i = 0; i < res.size(); ++i) {
result.erase(res.at(i)["member_id"]);
}
}
void XiaoZuFactor::And(set<int> & result) {
if ( !DegradeManager::instance().IsEnable("FeedDispatcher::module_XiaoZuExpr") ) {
return;
}
string head = GenerateSQL();
Statement sql;
sql << head;
sql << " AND member_id IN (";
set<int>::iterator itr = result.begin();
sql << *itr;
for (++itr; itr != result.end(); ++itr) {
sql << "," << *itr;
}
sql << ")";
mysqlpp::StoreQueryResult res;
try {
res = QueryRunner(instance_, CDbRServer, table_).store(sql);
} catch (Ice::Exception& e) {
MCE_WARN(" MiniGroupFactor::Plus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" MiniGroupFactor::Plus --> error:" << e.what());
}
result.clear();
if (!res) {
MCE_WARN("StoryQueryResult wrong");
return;
}
for (size_t i = 0; i < res.size(); ++i) {
result.insert(res.at(i)["member_id"]);
}
}
string XiaoZuFactor::GenerateSQL() {
instance_ = "forum";
ostringstream tmp;
tmp << "forum_member_" << param_id_%100;
table_ = tmp.str();
ostringstream sql;
sql << "SELECT member_id FROM " << table_ << " WHERE forum_id=" << param_id_ << " and access_id in (1,2,3) " ;
return sql.str();
}
//---------------------------------------------------------------
void MiniSiteFactor::Plus(set<int> & result) {
if ( !DegradeManager::instance().IsEnable("FeedDispatcher::module_MiniSiteExpr") ) {
return;
}
string head = GenerateSQL();
Statement sql;
sql << head ;
mysqlpp::StoreQueryResult res;
try {
res = QueryRunner(instance_, CDbRServer, table_).store(sql);
} catch (Ice::Exception& e) {
MCE_WARN(" MiniSiteFactor::Plus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" MiniSiteFactor::Plus --> error:" << e.what());
}
ostringstream oss;
for (size_t i = 0; i < res.size(); ++i) {
result.insert(res.at(i)["follower_id"]);
// oss << res.at(i)["uid"] << ",";
}
//MCE_DEBUG("FriendFactor::Plus --> result ids --> " << oss.str());
}
void MiniSiteFactor::Minus(set<int> & result) {
if ( !DegradeManager::instance().IsEnable("FeedDispatcher::module_MiniSiteExpr") ) {
return;
}
string head = GenerateSQL();
Statement sql;
sql << head;
sql << " AND follower_id IN (";
set<int>::iterator itr = result.begin();
sql << *itr;
for (++itr; itr != result.end(); ++itr) {
sql << "," << *itr;
}
sql << ")";
mysqlpp::StoreQueryResult res;
try {
res = QueryRunner(instance_, CDbRServer, table_).store(sql);
} catch (Ice::Exception& e) {
MCE_WARN(" MiniSiteFactor::Plus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" MiniSiteFactor::Plus --> error:" << e.what());
}
if (!res) {
MCE_WARN("StoryQueryResult wrong");
return;
}
for (size_t i = 0; i < res.size(); ++i) {
result.erase(res.at(i)["follower_id"]);
}
}
void MiniSiteFactor::And(set<int> & result) {
if ( !DegradeManager::instance().IsEnable("FeedDispatcher::module_MiniSiteExpr") ) {
return;
}
string head = GenerateSQL();
Statement sql;
sql << head;
sql << " AND follower_id IN (";
set<int>::iterator itr = result.begin();
sql << *itr;
for (++itr; itr != result.end(); ++itr) {
sql << "," << *itr;
}
sql << ")";
mysqlpp::StoreQueryResult res;
try {
res = QueryRunner(instance_, CDbRServer, table_).store(sql);
} catch (Ice::Exception& e) {
MCE_WARN(" MiniSiteFactor::Plus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" MiniSiteFactor::Plus --> error:" << e.what());
}
result.clear();
if (!res) {
MCE_WARN("StoryQueryResult wrong");
return;
}
for (size_t i = 0; i < res.size(); ++i) {
result.insert(res.at(i)["follower_id"]);
}
}
string MiniSiteFactor::GenerateSQL() {
instance_ = "minisite_site_follower";
ostringstream table_oss;
table_oss <<"minisite_site_follower_"<<param_id_ % 100;
table_ = table_oss.str();
ostringstream sql;
sql << "SELECT follower_id FROM "<<table_<< " WHERE site_id=" << param_id_ ;
return sql.str();
}
//---------------------------------------------------------------
void CheWenFactor::Plus(set<int> & result) {
if ( !DegradeManager::instance().IsEnable("FeedDispatcher::module_CheWenExpr") ) {
return;
}
string head = GenerateSQL();
Statement sql;
sql << head ;
mysqlpp::StoreQueryResult res;
try {
res = QueryRunner(instance_, CDbRServer, table_).store(sql);
} catch (Ice::Exception& e) {
MCE_WARN(" MiniSiteFactor::Plus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" MiniSiteFactor::Plus --> error:" << e.what());
}
ostringstream oss;
for (size_t i = 0; i < res.size(); ++i) {
result.insert(res.at(i)["renren_id"]);
// oss << res.at(i)["uid"] << ",";
}
//MCE_DEBUG("FriendFactor::Plus --> result ids --> " << oss.str());
}
void CheWenFactor::Minus(set<int> & result) {
if ( !DegradeManager::instance().IsEnable("FeedDispatcher::module_CheWenExpr") ) {
return;
}
string head = GenerateSQL();
Statement sql;
sql << head;
sql << " AND renren_id IN (";
set<int>::iterator itr = result.begin();
sql << *itr;
for (++itr; itr != result.end(); ++itr) {
sql << "," << *itr;
}
sql << ")";
mysqlpp::StoreQueryResult res;
try {
res = QueryRunner(instance_, CDbRServer, table_).store(sql);
} catch (Ice::Exception& e) {
MCE_WARN(" MiniSiteFactor::Plus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" MiniSiteFactor::Plus --> error:" << e.what());
}
if (!res) {
MCE_WARN("StoryQueryResult wrong");
return;
}
for (size_t i = 0; i < res.size(); ++i) {
result.erase(res.at(i)["renren_id"]);
}
}
void CheWenFactor::And(set<int> & result) {
if ( !DegradeManager::instance().IsEnable("FeedDispatcher::module_CheWenExpr") ) {
return;
}
string head = GenerateSQL();
Statement sql;
sql << head;
sql << " AND renren_id IN (";
set<int>::iterator itr = result.begin();
sql << *itr;
for (++itr; itr != result.end(); ++itr) {
sql << "," << *itr;
}
sql << ")";
mysqlpp::StoreQueryResult res;
try {
res = QueryRunner(instance_, CDbRServer, table_).store(sql);
} catch (Ice::Exception& e) {
MCE_WARN(" MiniSiteFactor::Plus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" MiniSiteFactor::Plus --> error:" << e.what());
}
result.clear();
if (!res) {
MCE_WARN("StoryQueryResult wrong");
return;
}
for (size_t i = 0; i < res.size(); ++i) {
result.insert(res.at(i)["renren_id"]);
}
}
string CheWenFactor::GenerateSQL() {
instance_ = "chewen_user";
table_ = "cw_followed_";
ostringstream tablename;
tablename << table_ << (param_id_ % 10); //表名
ostringstream sql;
sql << "SELECT renren_id FROM " << tablename.str() << " WHERE map_renren_id=" << param_id_;
return sql.str();
}
void TagFactor::Plus(set<int> & result) {
mysqlpp::StoreQueryResult res;
Statement sql;
string head;
ostringstream sql_tail;
struct timeval t_begin,t_end;
long t_cost;
int batch_size = 10000;
int i_count = 0;
int cur_max_id = 0;
head = GenerateSQL();
gettimeofday(&t_begin,NULL);//start time
if ( !DegradeManager::instance().IsEnable("FeedDispatcher::module_MiniSiteTagExpr") ) {
return;
}
do {
struct timeval t1,t2;
gettimeofday(&t1,NULL);
sql_tail <<" AND follower_id > "<<cur_max_id<<" ORDER BY follower_id LIMIT " << batch_size;
sql<<head<<sql_tail.str();
try {
res = QueryRunner(instance_, CDbRServer, table_).store(sql);
} catch (Ice::Exception& e) {
MCE_WARN(" TagFactor::Plus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" TagFactor::Plus --> error:" << e.what());
}
for (size_t i = 0; i < res.size(); ++i) {
int id = res.at(i)["follower_id"];
result.insert(id);
if (cur_max_id < id) {
cur_max_id = id;
}
}
i_count++;
sql_tail.str("");
sql.clear();
gettimeofday(&t2,NULL);
float tc = (t2.tv_sec - t1.tv_sec)*1000 + (t2.tv_usec - t1.tv_usec)*1.0 / (1000*1.0);
MCE_DEBUG("TagFactor::Plus --> cur_max_id:"<<cur_max_id<<" i_count:"<<i_count<<" time cost:"<<tc<<" ms");
} while (res.size() >=batch_size);
gettimeofday(&t_end,NULL);//end time
t_cost = ( t_end.tv_sec - t_begin.tv_sec )*1000 + ( t_end.tv_usec - t_begin.tv_usec )/1000;
MCE_INFO("TagFactor::Plus -->result size:"<<result.size()<<" time cost:"<<t_cost<<"ms");
}
void TagFactor::Minus(set<int> & result) {
mysqlpp::StoreQueryResult res;
Statement sql;
string head;
ostringstream sql_tail;
struct timeval t_begin,t_end;
long t_cost;
int batch_size = 10000;
int i_count = 0;
int cur_max_id = 0;
head = GenerateSQL();
gettimeofday(&t_begin,NULL);//start time
if ( !DegradeManager::instance().IsEnable("FeedDispatcher::module_MiniSiteTagExpr") ) {
return;
}
do {
struct timeval t1,t2;
gettimeofday(&t1,NULL);
sql_tail <<" AND follower_id >"<<cur_max_id<<" ORDER BY follower_id LIMIT "<< batch_size;
sql<<head<<sql_tail.str();
try {
res = QueryRunner(instance_, CDbRServer, table_).store(sql);
} catch (Ice::Exception& e) {
MCE_WARN(" MiniSiteFactor::Minus --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" MiniSiteFactor::Minus --> error:" << e.what());
}
for (size_t i = 0; i < res.size(); ++i) {
int id = res.at(i)["follower_id"];
if (result.find(id) != result.end()) {
result.erase(id);
}
if (cur_max_id < id) {
cur_max_id = id;
}
}
i_count++;
sql_tail.str("");
sql.clear();
gettimeofday(&t2,NULL);
float tc = (t2.tv_sec - t1.tv_sec)*1000 + (t2.tv_usec - t1.tv_usec)*1.0 / (1000*1.0);
MCE_DEBUG("TagFactor::Minus --> cur_max_id:"<<cur_max_id<<" i_count:"<<i_count<<" time cost:"<<tc<<" ms");
} while (res.size() >=batch_size);
gettimeofday(&t_end,NULL);//end time
t_cost = ( t_end.tv_sec - t_begin.tv_sec )*1000 + ( t_end.tv_usec - t_begin.tv_usec )/1000;
MCE_INFO("TagFactor::Minus -->result size:"<<result.size()<<" time cost:"<<t_cost<<"ms");
}
void TagFactor::And(set<int> & result) {
mysqlpp::StoreQueryResult res;
set<int> res_swap;
Statement sql;
string head;
ostringstream sql_tail;
struct timeval t_begin,t_end;
long t_cost;
int batch_size = 10000;
int i_count = 0;
int cur_max_id = 0;
head = GenerateSQL();
gettimeofday(&t_begin,NULL);//start time
if ( !DegradeManager::instance().IsEnable("FeedDispatcher::module_MiniSiteTagExpr") ) {
return;
}
do {
struct timeval t1,t2;
gettimeofday(&t1,NULL);
sql_tail <<" AND follower_id >"<<cur_max_id<<" ORDER BY follower_id LIMIT "<< batch_size;
sql<<head<<sql_tail.str();
try {
res = QueryRunner(instance_, CDbRServer, table_).store(sql);
} catch (Ice::Exception& e) {
MCE_WARN(" TagFactor::And --> error:" << e);
} catch (std::exception& e) {
MCE_WARN(" TagFactor::And --> error:" << e.what());
}
for (size_t i = 0; i < res.size(); ++i) {
int id = res.at(i)["follower_id"];
if (result.find(id) != result.end()) {
res_swap.insert(id);
}
if (cur_max_id < id) {
cur_max_id = id;
}
}
i_count++;
sql_tail.str("");
sql.clear();
gettimeofday(&t2,NULL);
float tc = (t2.tv_sec - t1.tv_sec)*1000 + (t2.tv_usec - t1.tv_usec)*1.0 / (1000*1.0);
MCE_DEBUG("TagFactor::And --> cur_max_id:"<<cur_max_id<<" i_count:"<<i_count<<" time cost:"<<tc<<" ms");
} while (res.size() >=batch_size);
gettimeofday(&t_end,NULL);//end time
result.swap(res_swap);
t_cost = ( t_end.tv_sec - t_begin.tv_sec )*1000 + ( t_end.tv_usec - t_begin.tv_usec )/1000;
MCE_INFO("TagFactor::And -->result size:"<<result.size()<<" time cost:"<<t_cost<<" ms");
}
string TagFactor::GenerateSQL() {
instance_ = "minisite";
table_ = "tag_follower";
ostringstream tablename;
tablename<< table_ ;
ostringstream sql;
sql << "SELECT follower_id FROM " << tablename.str() << " WHERE tag_id=" << param_id_ ;
return sql.str();
}
void GuangJieFactor::Plus(set<int> & result) {
struct timeval begin,end;
vector<int64_t> followers;
int64_t uid = param_id_;
int64_t index = 0;
int limit = 10000;
int count = 0;
gettimeofday(&begin,NULL);
if ( !DegradeManager::instance().IsEnable("FeedDispatcher::module_GuangJieExpr") ) {
return;
}
do {
try{
followers.clear();
xce::ad::UserCacheClientPlus::instance().GetFansByIndex(followers,uid,index,limit);
if (followers.size() > 0) {
int len = followers.size();
index = followers[len-1];
}
count++;
} catch(std::exception& e) {
MCE_WARN("GuangJieFator::plus --> error: "<<e.what()<<" followers size:"<<followers.size()<<" uid:"<<uid<<" limit:"<<limit);
} catch(...) {
MCE_WARN("GuangJieFator::plus --> error unkown followers size:"<<followers.size()<<" uid:"<<uid<<" limit:"<<limit);
}
for (vector<int64_t>::iterator i = followers.begin(); i != followers.end(); ++i) {
result.insert(*i);
}
MCE_INFO("GuangJieFactor::Plus --> uid:"<<uid<<" count:"<<count<<" index:"<<index<<" followers size:"<<followers.size()<<" result size:"<<result.size());
if(count >=100) {
MCE_WARN("GuangJieFactor::Plus --> Exceed the limit count:"<<count<<" uid:"<<uid);
break;
}
}while(followers.size() >= limit);
gettimeofday(&end,NULL);
float ts = (end.tv_sec - begin.tv_sec)*1000 + (end.tv_usec - begin.tv_usec)/1000;
MCE_INFO("GuangJieFactor::Plus --> OK uid:"<<uid<<" result size:"<<result.size()<<" time cost:"<<ts<<" ms");
}
void GuangJieFactor::Minus(set<int> & result) {
struct timeval begin,end;
vector<int64_t> followers;
int64_t uid = param_id_;
int64_t index = 0;
int limit = 10000;
int count = 0;
gettimeofday(&begin,NULL);
if ( !DegradeManager::instance().IsEnable("FeedDispatcher::module_GuangJieExpr") ) {
return;
}
do {
try{
followers.clear();
xce::ad::UserCacheClientPlus::instance().GetFansByIndex(followers,uid,index,limit);
if (followers.size() > 0 ) {
int len = followers.size();
index = followers[len -1];
}
count++;
} catch(std::exception& e) {
MCE_WARN(" GuangJieFactor::Minus --> error:" << e.what());
} catch(...) {
MCE_WARN("GuangJieFactor::Minus -->error ");
}
for (vector<int64_t>::iterator i = followers.begin(); i != followers.end(); ++i) {
if ( result.find(*i) == result.end())
continue;
result.erase(*i);
}
MCE_INFO("GuangJieFactor::Minus --> uid:"<<uid<<" count:"<<count<<" index:"<<index<<" followers size:"<<followers.size()<<" result size:"<<result.size());
// 如果resualt已经为空,没必要继续执行
if ( result.empty() ) {
MCE_INFO("GuangJieFactor::Minus --> result has EMPTY! uid:"<<uid<<" count:"<<count<<" index:"<<index);
break;
}
if(count >=100) {
MCE_WARN("GuangJieFactor::Plus --> Exceed the limit count:"<<count<<" uid:"<<uid);
break;
}
} while(followers.size() >= limit);
gettimeofday(&end,NULL);
float ts = (end.tv_sec - begin.tv_sec)*1000 + (end.tv_usec - begin.tv_usec)/1000;
MCE_INFO("GuangJieFactor::Minus --> OK uid:"<<uid<<" result size:"<<result.size()<<" time cost:"<<ts<<" ms");
}
void GuangJieFactor::And(set<int> & result) {
struct timeval begin,end;
vector<int64_t> followers;
set<int> and_result;
int64_t uid = param_id_;
int64_t index = 0;
int limit = 10000;
int count = 0;
gettimeofday(&begin,NULL);
if ( !DegradeManager::instance().IsEnable("FeedDispatcher::module_GuangJieExpr") ) {
return;
}
do {
try{
followers.clear();
xce::ad::UserCacheClientPlus::instance().GetFansByIndex(followers,uid,index,limit);
if (followers.size() > 0 ) {
int len = followers.size();
index = followers[len - 1];
}
count++;
} catch(std::exception& e) {
MCE_WARN(" GuangJieFactor::And --> error:" << e.what());
} catch(...) {
MCE_WARN("GuangJieFactor::And -->error ");
}
for (vector<int64_t>::iterator i = followers.begin(); i != followers.end(); ++i) {
set<int>::iterator sit = result.find(*i);
if (sit != result.end()){
and_result.insert(*i);
}
}
MCE_INFO("GuangJieFactor::And --> uid:"<<uid<<" count:"<<count<<" index:"<<index<<" followers size:"<<followers.size()<<" result size:"<<result.size());
if (and_result.size() == result.size()) {
MCE_INFO("GuangJieFactor::And --> and_result has FULL! uid:"<<uid<<" count:"<<count<<" index"<<index);
break;
}
if(count >=100) {
MCE_WARN("GuangJieFactor::Plus --> Exceed the limit count:"<<count<<" uid:"<<uid);
break;
}
} while(followers.size() >= limit);
result.swap(and_result);
gettimeofday(&end,NULL);
float ts = (end.tv_sec - begin.tv_sec)*1000 + (end.tv_usec - begin.tv_usec)/1000;
MCE_INFO("GuangJieFactor::And --> OK uid:"<<uid<<" result size:"<<result.size()<<" time cost:"<<ts<<" ms");
}
//shilong.li 2012-07-23
/*
void GuangJieTopicFactor::Plus(set<int> & result) {
vector<int64_t> followers;
int64_t uid = param_id_;
//int64_t uid = param_idL_;
int limit = 2000;
try{
xce::ad::UserCacheClientPlus::instance().GetTopicFollower(followers,uid,limit);
} catch(std::exception& e) {
MCE_WARN(" GuangJieTopicFactor::plus --> error:" << e.what());
} catch(...) {
MCE_WARN("GuangJieTopicFactor::plus -->error ");
}
if (followers.empty()) {
MCE_INFO("GuangJieTopicFactor::Plus --> GetTopicFollower return empty");
return;
}
MCE_INFO("GuangJieTopicFactor::Plus -->GetTopicFollower return size:"<<followers.size());
for (vector<int64_t>::iterator i = followers.begin(); i != followers.end(); ++i) {
result.insert(*i);
}
MCE_INFO("GuangJieTopicFactor -->Plus result size;"<<result.size());
}
void GuangJieTopicFactor::Minus(set<int> & result) {
vector<int64_t> followers;
int64_t uid = param_id_;
//int64_t uid = param_idL_;
int limit = 2000;
try{
xce::ad::UserCacheClientPlus::instance().GetTopicFollower(followers,uid,limit);
} catch(std::exception& e) {
MCE_WARN(" GuangJieTopicFactor::Minus --> error:" << e.what());
} catch(...) {
MCE_WARN("GuangJieTopicFactor::Minus -->error ");
}
if (followers.empty()) {
MCE_INFO("GuangJieTopicFactor::Minus -->GetTopicFollower return empty");
return;
}
MCE_INFO("GuangJieTopicFactor::Minus -->GetTopicFollower return size:"<<followers.size());
for (vector<int64_t>::iterator i = followers.begin(); i != followers.end(); ++i) {
if ( result.find(*i) == result.end())
continue;
result.erase(*i);
}
MCE_INFO("GuangJieTopicFactor::Minus --> result size:"<<result.size());
}
void GuangJieTopicFactor::And(set<int> & result) {
vector<int64_t> followers;
set<int> and_result;
int64_t uid = param_id_;
//int64_t uid = param_idL_;
int limit = 2000;
try{
xce::ad::UserCacheClientPlus::instance().GetTopicFollower(followers,uid,limit);
} catch(std::exception& e) {
MCE_WARN(" GuangJieTopicFactor::And --> error:" << e.what());
} catch(...) {
MCE_WARN("GuangJieTopicFactor::And -->error ");
}
if (followers.empty()) {
MCE_INFO("GuangJieTopicFactor::And -->GetTopicFollower return empty");
return;
}
MCE_INFO("GuangJieTopicFactor::And -->GetTopicFollower return size:"<<followers.size());
for (vector<int64_t>::iterator i = followers.begin(); i != followers.end(); ++i) {
set<int>::iterator sit = result.find(*i);
if (sit != result.end()){
and_result.insert(*i);
}
}
result.swap(and_result);
MCE_INFO("GuangJieTopicFactor::And -->And reuslt size:"<< result.size());
}
void AlbumFactor::Plus(set<int> & result) {
vector<int64_t> fans;
int64_t album_id = param_id_;
int limit = 20000;
try{
xce::ad::UserCacheClientPlus::instance().GetAlbumFans(fans, album_id, 0, limit);
} catch(std::exception& e) {
MCE_WARN(" AlbumFactor::plus --> error:" << e.what());
} catch(...) {
MCE_WARN("AlbumFactor::plus -->error ");
}
if (fans.empty()) {
MCE_WARN("AlbumFactor::Plus -->GetFans return empty");
return;
}
MCE_DEBUG("AlbumFactor::Plus -->GetFans size:"<<fans.size() << " album_id:" << album_id);
for (vector<int64_t>::iterator i = fans.begin(); i != fans.end(); ++i) {
result.insert(*i);
}
MCE_INFO("AlbumFactor -->Plus result size;"<<result.size());
}
void AlbumFactor::Minus(set<int> & result) {
vector<int64_t> fans;
int64_t album_id = param_id_;
int limit = 20000;
try{
xce::ad::UserCacheClientPlus::instance().GetAlbumFans(fans, album_id, 0, limit);
} catch(std::exception& e) {
MCE_WARN(" AlbumFactor::Minus --> error:" << e.what());
} catch(...) {
MCE_WARN("AlbumFactor::Minus -->error ");
}
if (fans.empty()) {
MCE_WARN("AlbumFactor::Minus -->GetFans return empty");
return;
}
MCE_DEBUG("AlbumFactor::Minus -->GetFans size:"<<fans.size()<< " album_id:" << album_id);
for (vector<int64_t>::iterator i = fans.begin(); i != fans.end(); ++i) {
result.erase(*i);
}
MCE_INFO("AlbumFactor -->Minus result size:"<<result.size());
}
void AlbumFactor::And(set<int> & result) {
vector<int64_t> fans;
set<int> and_result;
int64_t album_id = param_id_;
int limit = 20000;
try{
xce::ad::UserCacheClientPlus::instance().GetAlbumFans(fans, album_id, 0, limit);
} catch(std::exception& e) {
MCE_WARN(" AlbumFactor::And --> error:" << e.what());
} catch(...) {
MCE_WARN("AlbumFactor::And -->error ");
}
if (fans.empty()) {
MCE_WARN("AlbumFactor::And -->GetFans return empty");
return;
}
MCE_DEBUG("AlbumFactor::And -->GetFans size:"<<fans.size()<< " album_id:" << album_id);
for (vector<int64_t>::iterator i = fans.begin(); i != fans.end(); ++i) {
set<int>::iterator sit = result.find(*i);
if (sit != result.end()){
and_result.insert(*i);
}
}
result.swap(and_result);
MCE_INFO("AlbumFactor::And -->And Reusalt size:"<< result.size());
}*/
| [
"liyong19861014@gmail.com"
] | liyong19861014@gmail.com |
ecafb1fd4e643c37c6ca496c7cb95699141a8c57 | 88ae8695987ada722184307301e221e1ba3cc2fa | /third_party/icu/source/common/ubidi.cpp | eb40a212e17e9e4296cfc8d8ecf8672b3a44cc75 | [
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"BSD-3-Clause",
"LicenseRef-scancode-unicode",
"ICU",
"LicenseRef-scancode-unknown-license-reference",
"GPL-3.0-or-later",
"NTP",
"GPL-2.0-or-later",
"LicenseRef-scancode-autoconf-simple-exception",
"Autoconf-exception-generic",
... | permissive | iridium-browser/iridium-browser | 71d9c5ff76e014e6900b825f67389ab0ccd01329 | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | refs/heads/master | 2023-08-03T16:44:16.844552 | 2023-07-20T15:17:00 | 2023-07-23T16:09:30 | 220,016,632 | 341 | 40 | BSD-3-Clause | 2021-08-13T13:54:45 | 2019-11-06T14:32:31 | null | UTF-8 | C++ | false | false | 122,221 | cpp | // © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
******************************************************************************
*
* Copyright (C) 1999-2015, International Business Machines
* Corporation and others. All Rights Reserved.
*
******************************************************************************
* file name: ubidi.c
* encoding: UTF-8
* tab size: 8 (not used)
* indentation:4
*
* created on: 1999jul27
* created by: Markus W. Scherer, updated by Matitiahu Allouche
*
*/
#include "cmemory.h"
#include "unicode/utypes.h"
#include "unicode/ustring.h"
#include "unicode/uchar.h"
#include "unicode/ubidi.h"
#include "unicode/utf16.h"
#include "ubidi_props.h"
#include "ubidiimp.h"
#include "uassert.h"
/*
* General implementation notes:
*
* Throughout the implementation, there are comments like (W2) that refer to
* rules of the BiDi algorithm, in this example to the second rule of the
* resolution of weak types.
*
* For handling surrogate pairs, where two UChar's form one "abstract" (or UTF-32)
* character according to UTF-16, the second UChar gets the directional property of
* the entire character assigned, while the first one gets a BN, a boundary
* neutral, type, which is ignored by most of the algorithm according to
* rule (X9) and the implementation suggestions of the BiDi algorithm.
*
* Later, adjustWSLevels() will set the level for each BN to that of the
* following character (UChar), which results in surrogate pairs getting the
* same level on each of their surrogates.
*
* In a UTF-8 implementation, the same thing could be done: the last byte of
* a multi-byte sequence would get the "real" property, while all previous
* bytes of that sequence would get BN.
*
* It is not possible to assign all those parts of a character the same real
* property because this would fail in the resolution of weak types with rules
* that look at immediately surrounding types.
*
* As a related topic, this implementation does not remove Boundary Neutral
* types from the input, but ignores them wherever this is relevant.
* For example, the loop for the resolution of the weak types reads
* types until it finds a non-BN.
* Also, explicit embedding codes are neither changed into BN nor removed.
* They are only treated the same way real BNs are.
* As stated before, adjustWSLevels() takes care of them at the end.
* For the purpose of conformance, the levels of all these codes
* do not matter.
*
* Note that this implementation modifies the dirProps
* after the initial setup, when applying X5c (replace FSI by LRI or RLI),
* X6, N0 (replace paired brackets by L or R).
*
* In this implementation, the resolution of weak types (W1 to W6),
* neutrals (N1 and N2), and the assignment of the resolved level (In)
* are all done in one single loop, in resolveImplicitLevels().
* Changes of dirProp values are done on the fly, without writing
* them back to the dirProps array.
*
*
* This implementation contains code that allows to bypass steps of the
* algorithm that are not needed on the specific paragraph
* in order to speed up the most common cases considerably,
* like text that is entirely LTR, or RTL text without numbers.
*
* Most of this is done by setting a bit for each directional property
* in a flags variable and later checking for whether there are
* any LTR characters or any RTL characters, or both, whether
* there are any explicit embedding codes, etc.
*
* If the (Xn) steps are performed, then the flags are re-evaluated,
* because they will then not contain the embedding codes any more
* and will be adjusted for override codes, so that subsequently
* more bypassing may be possible than what the initial flags suggested.
*
* If the text is not mixed-directional, then the
* algorithm steps for the weak type resolution are not performed,
* and all levels are set to the paragraph level.
*
* If there are no explicit embedding codes, then the (Xn) steps
* are not performed.
*
* If embedding levels are supplied as a parameter, then all
* explicit embedding codes are ignored, and the (Xn) steps
* are not performed.
*
* White Space types could get the level of the run they belong to,
* and are checked with a test of (flags&MASK_EMBEDDING) to
* consider if the paragraph direction should be considered in
* the flags variable.
*
* If there are no White Space types in the paragraph, then
* (L1) is not necessary in adjustWSLevels().
*/
/* to avoid some conditional statements, use tiny constant arrays */
static const Flags flagLR[2]={ DIRPROP_FLAG(L), DIRPROP_FLAG(R) };
static const Flags flagE[2]={ DIRPROP_FLAG(LRE), DIRPROP_FLAG(RLE) };
static const Flags flagO[2]={ DIRPROP_FLAG(LRO), DIRPROP_FLAG(RLO) };
#define DIRPROP_FLAG_LR(level) flagLR[(level)&1]
#define DIRPROP_FLAG_E(level) flagE[(level)&1]
#define DIRPROP_FLAG_O(level) flagO[(level)&1]
#define DIR_FROM_STRONG(strong) ((strong)==L ? L : R)
#define NO_OVERRIDE(level) ((level)&~UBIDI_LEVEL_OVERRIDE)
/* UBiDi object management -------------------------------------------------- */
U_CAPI UBiDi * U_EXPORT2
ubidi_open(void)
{
UErrorCode errorCode=U_ZERO_ERROR;
return ubidi_openSized(0, 0, &errorCode);
}
U_CAPI UBiDi * U_EXPORT2
ubidi_openSized(int32_t maxLength, int32_t maxRunCount, UErrorCode *pErrorCode) {
UBiDi *pBiDi;
/* check the argument values */
if(pErrorCode==NULL || U_FAILURE(*pErrorCode)) {
return NULL;
} else if(maxLength<0 || maxRunCount<0) {
*pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
return NULL; /* invalid arguments */
}
/* allocate memory for the object */
pBiDi=(UBiDi *)uprv_malloc(sizeof(UBiDi));
if(pBiDi==NULL) {
*pErrorCode=U_MEMORY_ALLOCATION_ERROR;
return NULL;
}
/* reset the object, all pointers NULL, all flags false, all sizes 0 */
uprv_memset(pBiDi, 0, sizeof(UBiDi));
/* allocate memory for arrays as requested */
if(maxLength>0) {
if( !getInitialDirPropsMemory(pBiDi, maxLength) ||
!getInitialLevelsMemory(pBiDi, maxLength)
) {
*pErrorCode=U_MEMORY_ALLOCATION_ERROR;
}
} else {
pBiDi->mayAllocateText=true;
}
if(maxRunCount>0) {
if(maxRunCount==1) {
/* use simpleRuns[] */
pBiDi->runsSize=sizeof(Run);
} else if(!getInitialRunsMemory(pBiDi, maxRunCount)) {
*pErrorCode=U_MEMORY_ALLOCATION_ERROR;
}
} else {
pBiDi->mayAllocateRuns=true;
}
if(U_SUCCESS(*pErrorCode)) {
return pBiDi;
} else {
ubidi_close(pBiDi);
return NULL;
}
}
/*
* We are allowed to allocate memory if memory==NULL or
* mayAllocate==true for each array that we need.
* We also try to grow memory as needed if we
* allocate it.
*
* Assume sizeNeeded>0.
* If *pMemory!=NULL, then assume *pSize>0.
*
* ### this realloc() may unnecessarily copy the old data,
* which we know we don't need any more;
* is this the best way to do this??
*/
U_CFUNC UBool
ubidi_getMemory(BidiMemoryForAllocation *bidiMem, int32_t *pSize, UBool mayAllocate, int32_t sizeNeeded) {
void **pMemory = (void **)bidiMem;
/* check for existing memory */
if(*pMemory==NULL) {
/* we need to allocate memory */
if(mayAllocate && (*pMemory=uprv_malloc(sizeNeeded))!=NULL) {
*pSize=sizeNeeded;
return true;
} else {
return false;
}
} else {
if(sizeNeeded<=*pSize) {
/* there is already enough memory */
return true;
}
else if(!mayAllocate) {
/* not enough memory, and we must not allocate */
return false;
} else {
/* we try to grow */
void *memory;
/* in most cases, we do not need the copy-old-data part of
* realloc, but it is needed when adding runs using getRunsMemory()
* in setParaRunsOnly()
*/
if((memory=uprv_realloc(*pMemory, sizeNeeded))!=NULL) {
*pMemory=memory;
*pSize=sizeNeeded;
return true;
} else {
/* we failed to grow */
return false;
}
}
}
}
U_CAPI void U_EXPORT2
ubidi_close(UBiDi *pBiDi) {
if(pBiDi!=NULL) {
pBiDi->pParaBiDi=NULL; /* in case one tries to reuse this block */
if(pBiDi->dirPropsMemory!=NULL) {
uprv_free(pBiDi->dirPropsMemory);
}
if(pBiDi->levelsMemory!=NULL) {
uprv_free(pBiDi->levelsMemory);
}
if(pBiDi->openingsMemory!=NULL) {
uprv_free(pBiDi->openingsMemory);
}
if(pBiDi->parasMemory!=NULL) {
uprv_free(pBiDi->parasMemory);
}
if(pBiDi->runsMemory!=NULL) {
uprv_free(pBiDi->runsMemory);
}
if(pBiDi->isolatesMemory!=NULL) {
uprv_free(pBiDi->isolatesMemory);
}
if(pBiDi->insertPoints.points!=NULL) {
uprv_free(pBiDi->insertPoints.points);
}
uprv_free(pBiDi);
}
}
/* set to approximate "inverse BiDi" ---------------------------------------- */
U_CAPI void U_EXPORT2
ubidi_setInverse(UBiDi *pBiDi, UBool isInverse) {
if(pBiDi!=NULL) {
pBiDi->isInverse=isInverse;
pBiDi->reorderingMode = isInverse ? UBIDI_REORDER_INVERSE_NUMBERS_AS_L
: UBIDI_REORDER_DEFAULT;
}
}
U_CAPI UBool U_EXPORT2
ubidi_isInverse(UBiDi *pBiDi) {
if(pBiDi!=NULL) {
return pBiDi->isInverse;
} else {
return false;
}
}
/* FOOD FOR THOUGHT: currently the reordering modes are a mixture of
* algorithm for direct BiDi, algorithm for inverse BiDi and the bizarre
* concept of RUNS_ONLY which is a double operation.
* It could be advantageous to divide this into 3 concepts:
* a) Operation: direct / inverse / RUNS_ONLY
* b) Direct algorithm: default / NUMBERS_SPECIAL / GROUP_NUMBERS_WITH_R
* c) Inverse algorithm: default / INVERSE_LIKE_DIRECT / NUMBERS_SPECIAL
* This would allow combinations not possible today like RUNS_ONLY with
* NUMBERS_SPECIAL.
* Also allow to set INSERT_MARKS for the direct step of RUNS_ONLY and
* REMOVE_CONTROLS for the inverse step.
* Not all combinations would be supported, and probably not all do make sense.
* This would need to document which ones are supported and what are the
* fallbacks for unsupported combinations.
*/
U_CAPI void U_EXPORT2
ubidi_setReorderingMode(UBiDi *pBiDi, UBiDiReorderingMode reorderingMode) {
if ((pBiDi!=NULL) && (reorderingMode >= UBIDI_REORDER_DEFAULT)
&& (reorderingMode < UBIDI_REORDER_COUNT)) {
pBiDi->reorderingMode = reorderingMode;
pBiDi->isInverse = (UBool)(reorderingMode == UBIDI_REORDER_INVERSE_NUMBERS_AS_L);
}
}
U_CAPI UBiDiReorderingMode U_EXPORT2
ubidi_getReorderingMode(UBiDi *pBiDi) {
if (pBiDi!=NULL) {
return pBiDi->reorderingMode;
} else {
return UBIDI_REORDER_DEFAULT;
}
}
U_CAPI void U_EXPORT2
ubidi_setReorderingOptions(UBiDi *pBiDi, uint32_t reorderingOptions) {
if (reorderingOptions & UBIDI_OPTION_REMOVE_CONTROLS) {
reorderingOptions&=~UBIDI_OPTION_INSERT_MARKS;
}
if (pBiDi!=NULL) {
pBiDi->reorderingOptions=reorderingOptions;
}
}
U_CAPI uint32_t U_EXPORT2
ubidi_getReorderingOptions(UBiDi *pBiDi) {
if (pBiDi!=NULL) {
return pBiDi->reorderingOptions;
} else {
return 0;
}
}
U_CAPI UBiDiDirection U_EXPORT2
ubidi_getBaseDirection(const UChar *text,
int32_t length){
int32_t i;
UChar32 uchar;
UCharDirection dir;
if( text==NULL || length<-1 ){
return UBIDI_NEUTRAL;
}
if(length==-1) {
length=u_strlen(text);
}
for( i = 0 ; i < length; ) {
/* i is incremented by U16_NEXT */
U16_NEXT(text, i, length, uchar);
dir = u_charDirection(uchar);
if( dir == U_LEFT_TO_RIGHT )
return UBIDI_LTR;
if( dir == U_RIGHT_TO_LEFT || dir ==U_RIGHT_TO_LEFT_ARABIC )
return UBIDI_RTL;
}
return UBIDI_NEUTRAL;
}
/* perform (P2)..(P3) ------------------------------------------------------- */
/**
* Returns the directionality of the first strong character
* after the last B in prologue, if any.
* Requires prologue!=null.
*/
static DirProp
firstL_R_AL(UBiDi *pBiDi) {
const UChar *text=pBiDi->prologue;
int32_t length=pBiDi->proLength;
int32_t i;
UChar32 uchar;
DirProp dirProp, result=ON;
for(i=0; i<length; ) {
/* i is incremented by U16_NEXT */
U16_NEXT(text, i, length, uchar);
dirProp=(DirProp)ubidi_getCustomizedClass(pBiDi, uchar);
if(result==ON) {
if(dirProp==L || dirProp==R || dirProp==AL) {
result=dirProp;
}
} else {
if(dirProp==B) {
result=ON;
}
}
}
return result;
}
/*
* Check that there are enough entries in the array pointed to by pBiDi->paras
*/
static UBool
checkParaCount(UBiDi *pBiDi) {
int32_t count=pBiDi->paraCount;
if(pBiDi->paras==pBiDi->simpleParas) {
if(count<=SIMPLE_PARAS_COUNT)
return true;
if(!getInitialParasMemory(pBiDi, SIMPLE_PARAS_COUNT * 2))
return false;
pBiDi->paras=pBiDi->parasMemory;
uprv_memcpy(pBiDi->parasMemory, pBiDi->simpleParas, SIMPLE_PARAS_COUNT * sizeof(Para));
return true;
}
if(!getInitialParasMemory(pBiDi, count * 2))
return false;
pBiDi->paras=pBiDi->parasMemory;
return true;
}
/*
* Get the directional properties for the text, calculate the flags bit-set, and
* determine the paragraph level if necessary (in pBiDi->paras[i].level).
* FSI initiators are also resolved and their dirProp replaced with LRI or RLI.
* When encountering an FSI, it is initially replaced with an LRI, which is the
* default. Only if a strong R or AL is found within its scope will the LRI be
* replaced by an RLI.
*/
static UBool
getDirProps(UBiDi *pBiDi) {
const UChar *text=pBiDi->text;
DirProp *dirProps=pBiDi->dirPropsMemory; /* pBiDi->dirProps is const */
int32_t i=0, originalLength=pBiDi->originalLength;
Flags flags=0; /* collect all directionalities in the text */
UChar32 uchar;
DirProp dirProp=0, defaultParaLevel=0; /* initialize to avoid compiler warnings */
UBool isDefaultLevel=IS_DEFAULT_LEVEL(pBiDi->paraLevel);
/* for inverse BiDi, the default para level is set to RTL if there is a
strong R or AL character at either end of the text */
UBool isDefaultLevelInverse=isDefaultLevel && (UBool)
(pBiDi->reorderingMode==UBIDI_REORDER_INVERSE_LIKE_DIRECT ||
pBiDi->reorderingMode==UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL);
int32_t lastArabicPos=-1;
int32_t controlCount=0;
UBool removeBiDiControls = (UBool)(pBiDi->reorderingOptions &
UBIDI_OPTION_REMOVE_CONTROLS);
enum State {
NOT_SEEKING_STRONG, /* 0: not contextual paraLevel, not after FSI */
SEEKING_STRONG_FOR_PARA, /* 1: looking for first strong char in para */
SEEKING_STRONG_FOR_FSI, /* 2: looking for first strong after FSI */
LOOKING_FOR_PDI /* 3: found strong after FSI, looking for PDI */
};
State state;
DirProp lastStrong=ON; /* for default level & inverse BiDi */
/* The following stacks are used to manage isolate sequences. Those
sequences may be nested, but obviously never more deeply than the
maximum explicit embedding level.
lastStack is the index of the last used entry in the stack. A value of -1
means that there is no open isolate sequence.
lastStack is reset to -1 on paragraph boundaries. */
/* The following stack contains the position of the initiator of
each open isolate sequence */
int32_t isolateStartStack[UBIDI_MAX_EXPLICIT_LEVEL+1];
/* The following stack contains the last known state before
encountering the initiator of an isolate sequence */
State previousStateStack[UBIDI_MAX_EXPLICIT_LEVEL+1];
int32_t stackLast=-1;
if(pBiDi->reorderingOptions & UBIDI_OPTION_STREAMING)
pBiDi->length=0;
defaultParaLevel=pBiDi->paraLevel&1;
if(isDefaultLevel) {
pBiDi->paras[0].level=defaultParaLevel;
lastStrong=defaultParaLevel;
if(pBiDi->proLength>0 && /* there is a prologue */
(dirProp=firstL_R_AL(pBiDi))!=ON) { /* with a strong character */
if(dirProp==L)
pBiDi->paras[0].level=0; /* set the default para level */
else
pBiDi->paras[0].level=1; /* set the default para level */
state=NOT_SEEKING_STRONG;
} else {
state=SEEKING_STRONG_FOR_PARA;
}
} else {
pBiDi->paras[0].level=pBiDi->paraLevel;
state=NOT_SEEKING_STRONG;
}
/* count paragraphs and determine the paragraph level (P2..P3) */
/*
* see comment in ubidi.h:
* the UBIDI_DEFAULT_XXX values are designed so that
* their bit 0 alone yields the intended default
*/
for( /* i=0 above */ ; i<originalLength; ) {
/* i is incremented by U16_NEXT */
U16_NEXT(text, i, originalLength, uchar);
flags|=DIRPROP_FLAG(dirProp=(DirProp)ubidi_getCustomizedClass(pBiDi, uchar));
dirProps[i-1]=dirProp;
if(uchar>0xffff) { /* set the lead surrogate's property to BN */
flags|=DIRPROP_FLAG(BN);
dirProps[i-2]=BN;
}
if(removeBiDiControls && IS_BIDI_CONTROL_CHAR(uchar))
controlCount++;
if(dirProp==L) {
if(state==SEEKING_STRONG_FOR_PARA) {
pBiDi->paras[pBiDi->paraCount-1].level=0;
state=NOT_SEEKING_STRONG;
}
else if(state==SEEKING_STRONG_FOR_FSI) {
if(stackLast<=UBIDI_MAX_EXPLICIT_LEVEL) {
/* no need for next statement, already set by default */
/* dirProps[isolateStartStack[stackLast]]=LRI; */
flags|=DIRPROP_FLAG(LRI);
}
state=LOOKING_FOR_PDI;
}
lastStrong=L;
continue;
}
if(dirProp==R || dirProp==AL) {
if(state==SEEKING_STRONG_FOR_PARA) {
pBiDi->paras[pBiDi->paraCount-1].level=1;
state=NOT_SEEKING_STRONG;
}
else if(state==SEEKING_STRONG_FOR_FSI) {
if(stackLast<=UBIDI_MAX_EXPLICIT_LEVEL) {
dirProps[isolateStartStack[stackLast]]=RLI;
flags|=DIRPROP_FLAG(RLI);
}
state=LOOKING_FOR_PDI;
}
lastStrong=R;
if(dirProp==AL)
lastArabicPos=i-1;
continue;
}
if(dirProp>=FSI && dirProp<=RLI) { /* FSI, LRI or RLI */
stackLast++;
if(stackLast<=UBIDI_MAX_EXPLICIT_LEVEL) {
isolateStartStack[stackLast]=i-1;
previousStateStack[stackLast]=state;
}
if(dirProp==FSI) {
dirProps[i-1]=LRI; /* default if no strong char */
state=SEEKING_STRONG_FOR_FSI;
}
else
state=LOOKING_FOR_PDI;
continue;
}
if(dirProp==PDI) {
if(state==SEEKING_STRONG_FOR_FSI) {
if(stackLast<=UBIDI_MAX_EXPLICIT_LEVEL) {
/* no need for next statement, already set by default */
/* dirProps[isolateStartStack[stackLast]]=LRI; */
flags|=DIRPROP_FLAG(LRI);
}
}
if(stackLast>=0) {
if(stackLast<=UBIDI_MAX_EXPLICIT_LEVEL)
state=previousStateStack[stackLast];
stackLast--;
}
continue;
}
if(dirProp==B) {
if(i<originalLength && uchar==CR && text[i]==LF) /* do nothing on the CR */
continue;
pBiDi->paras[pBiDi->paraCount-1].limit=i;
if(isDefaultLevelInverse && lastStrong==R)
pBiDi->paras[pBiDi->paraCount-1].level=1;
if(pBiDi->reorderingOptions & UBIDI_OPTION_STREAMING) {
/* When streaming, we only process whole paragraphs
thus some updates are only done on paragraph boundaries */
pBiDi->length=i; /* i is index to next character */
pBiDi->controlCount=controlCount;
}
if(i<originalLength) { /* B not last char in text */
pBiDi->paraCount++;
if(checkParaCount(pBiDi)==false) /* not enough memory for a new para entry */
return false;
if(isDefaultLevel) {
pBiDi->paras[pBiDi->paraCount-1].level=defaultParaLevel;
state=SEEKING_STRONG_FOR_PARA;
lastStrong=defaultParaLevel;
} else {
pBiDi->paras[pBiDi->paraCount-1].level=pBiDi->paraLevel;
state=NOT_SEEKING_STRONG;
}
stackLast=-1;
}
continue;
}
}
/* Ignore still open isolate sequences with overflow */
if(stackLast>UBIDI_MAX_EXPLICIT_LEVEL) {
stackLast=UBIDI_MAX_EXPLICIT_LEVEL;
state=SEEKING_STRONG_FOR_FSI; /* to be on the safe side */
}
/* Resolve direction of still unresolved open FSI sequences */
while(stackLast>=0) {
if(state==SEEKING_STRONG_FOR_FSI) {
/* no need for next statement, already set by default */
/* dirProps[isolateStartStack[stackLast]]=LRI; */
flags|=DIRPROP_FLAG(LRI);
break;
}
state=previousStateStack[stackLast];
stackLast--;
}
/* When streaming, ignore text after the last paragraph separator */
if(pBiDi->reorderingOptions & UBIDI_OPTION_STREAMING) {
if(pBiDi->length<originalLength)
pBiDi->paraCount--;
} else {
pBiDi->paras[pBiDi->paraCount-1].limit=originalLength;
pBiDi->controlCount=controlCount;
}
/* For inverse bidi, default para direction is RTL if there is
a strong R or AL at either end of the paragraph */
if(isDefaultLevelInverse && lastStrong==R) {
pBiDi->paras[pBiDi->paraCount-1].level=1;
}
if(isDefaultLevel) {
pBiDi->paraLevel=static_cast<UBiDiLevel>(pBiDi->paras[0].level);
}
/* The following is needed to resolve the text direction for default level
paragraphs containing no strong character */
for(i=0; i<pBiDi->paraCount; i++)
flags|=DIRPROP_FLAG_LR(pBiDi->paras[i].level);
if(pBiDi->orderParagraphsLTR && (flags&DIRPROP_FLAG(B))) {
flags|=DIRPROP_FLAG(L);
}
pBiDi->flags=flags;
pBiDi->lastArabicPos=lastArabicPos;
return true;
}
/* determine the paragraph level at position index */
U_CFUNC UBiDiLevel
ubidi_getParaLevelAtIndex(const UBiDi *pBiDi, int32_t pindex) {
int32_t i;
for(i=0; i<pBiDi->paraCount; i++)
if(pindex<pBiDi->paras[i].limit)
break;
if(i>=pBiDi->paraCount)
i=pBiDi->paraCount-1;
return (UBiDiLevel)(pBiDi->paras[i].level);
}
/* Functions for handling paired brackets ----------------------------------- */
/* In the isoRuns array, the first entry is used for text outside of any
isolate sequence. Higher entries are used for each more deeply nested
isolate sequence. isoRunLast is the index of the last used entry. The
openings array is used to note the data of opening brackets not yet
matched by a closing bracket, or matched but still susceptible to change
level.
Each isoRun entry contains the index of the first and
one-after-last openings entries for pending opening brackets it
contains. The next openings entry to use is the one-after-last of the
most deeply nested isoRun entry.
isoRun entries also contain their current embedding level and the last
encountered strong character, since these will be needed to resolve
the level of paired brackets. */
static void
bracketInit(UBiDi *pBiDi, BracketData *bd) {
bd->pBiDi=pBiDi;
bd->isoRunLast=0;
bd->isoRuns[0].start=0;
bd->isoRuns[0].limit=0;
bd->isoRuns[0].level=GET_PARALEVEL(pBiDi, 0);
UBiDiLevel t = GET_PARALEVEL(pBiDi, 0) & 1;
bd->isoRuns[0].lastStrong = bd->isoRuns[0].lastBase = t;
bd->isoRuns[0].contextDir = (UBiDiDirection)t;
bd->isoRuns[0].contextPos=0;
if(pBiDi->openingsMemory) {
bd->openings=pBiDi->openingsMemory;
bd->openingsCount=pBiDi->openingsSize / sizeof(Opening);
} else {
bd->openings=bd->simpleOpenings;
bd->openingsCount=SIMPLE_OPENINGS_COUNT;
}
bd->isNumbersSpecial=bd->pBiDi->reorderingMode==UBIDI_REORDER_NUMBERS_SPECIAL ||
bd->pBiDi->reorderingMode==UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL;
}
/* paragraph boundary */
static void
bracketProcessB(BracketData *bd, UBiDiLevel level) {
bd->isoRunLast=0;
bd->isoRuns[0].limit=0;
bd->isoRuns[0].level=level;
bd->isoRuns[0].lastStrong=bd->isoRuns[0].lastBase=level&1;
bd->isoRuns[0].contextDir=(UBiDiDirection)(level&1);
bd->isoRuns[0].contextPos=0;
}
/* LRE, LRO, RLE, RLO, PDF */
static void
bracketProcessBoundary(BracketData *bd, int32_t lastCcPos,
UBiDiLevel contextLevel, UBiDiLevel embeddingLevel) {
IsoRun *pLastIsoRun=&bd->isoRuns[bd->isoRunLast];
DirProp *dirProps=bd->pBiDi->dirProps;
if(DIRPROP_FLAG(dirProps[lastCcPos])&MASK_ISO) /* after an isolate */
return;
if(NO_OVERRIDE(embeddingLevel)>NO_OVERRIDE(contextLevel)) /* not a PDF */
contextLevel=embeddingLevel;
pLastIsoRun->limit=pLastIsoRun->start;
pLastIsoRun->level=embeddingLevel;
pLastIsoRun->lastStrong=pLastIsoRun->lastBase=contextLevel&1;
pLastIsoRun->contextDir=(UBiDiDirection)(contextLevel&1);
pLastIsoRun->contextPos=(UBiDiDirection)lastCcPos;
}
/* LRI or RLI */
static void
bracketProcessLRI_RLI(BracketData *bd, UBiDiLevel level) {
IsoRun *pLastIsoRun=&bd->isoRuns[bd->isoRunLast];
int16_t lastLimit;
pLastIsoRun->lastBase=ON;
lastLimit=pLastIsoRun->limit;
bd->isoRunLast++;
pLastIsoRun++;
pLastIsoRun->start=pLastIsoRun->limit=lastLimit;
pLastIsoRun->level=level;
pLastIsoRun->lastStrong=pLastIsoRun->lastBase=level&1;
pLastIsoRun->contextDir=(UBiDiDirection)(level&1);
pLastIsoRun->contextPos=0;
}
/* PDI */
static void
bracketProcessPDI(BracketData *bd) {
IsoRun *pLastIsoRun;
bd->isoRunLast--;
pLastIsoRun=&bd->isoRuns[bd->isoRunLast];
pLastIsoRun->lastBase=ON;
}
/* newly found opening bracket: create an openings entry */
static UBool /* return true if success */
bracketAddOpening(BracketData *bd, UChar match, int32_t position) {
IsoRun *pLastIsoRun=&bd->isoRuns[bd->isoRunLast];
Opening *pOpening;
if(pLastIsoRun->limit>=bd->openingsCount) { /* no available new entry */
UBiDi *pBiDi=bd->pBiDi;
if(!getInitialOpeningsMemory(pBiDi, pLastIsoRun->limit * 2))
return false;
if(bd->openings==bd->simpleOpenings)
uprv_memcpy(pBiDi->openingsMemory, bd->simpleOpenings,
SIMPLE_OPENINGS_COUNT * sizeof(Opening));
bd->openings=pBiDi->openingsMemory; /* may have changed */
bd->openingsCount=pBiDi->openingsSize / sizeof(Opening);
}
pOpening=&bd->openings[pLastIsoRun->limit];
pOpening->position=position;
pOpening->match=match;
pOpening->contextDir=pLastIsoRun->contextDir;
pOpening->contextPos=pLastIsoRun->contextPos;
pOpening->flags=0;
pLastIsoRun->limit++;
return true;
}
/* change N0c1 to N0c2 when a preceding bracket is assigned the embedding level */
static void
fixN0c(BracketData *bd, int32_t openingIndex, int32_t newPropPosition, DirProp newProp) {
/* This function calls itself recursively */
IsoRun *pLastIsoRun=&bd->isoRuns[bd->isoRunLast];
Opening *qOpening;
DirProp *dirProps=bd->pBiDi->dirProps;
int32_t k, openingPosition, closingPosition;
for(k=openingIndex+1, qOpening=&bd->openings[k]; k<pLastIsoRun->limit; k++, qOpening++) {
if(qOpening->match>=0) /* not an N0c match */
continue;
if(newPropPosition<qOpening->contextPos)
break;
if(newPropPosition>=qOpening->position)
continue;
if(newProp==qOpening->contextDir)
break;
openingPosition=qOpening->position;
dirProps[openingPosition]=newProp;
closingPosition=-(qOpening->match);
dirProps[closingPosition]=newProp;
qOpening->match=0; /* prevent further changes */
fixN0c(bd, k, openingPosition, newProp);
fixN0c(bd, k, closingPosition, newProp);
}
}
/* process closing bracket */
static DirProp /* return L or R if N0b or N0c, ON if N0d */
bracketProcessClosing(BracketData *bd, int32_t openIdx, int32_t position) {
IsoRun *pLastIsoRun=&bd->isoRuns[bd->isoRunLast];
Opening *pOpening, *qOpening;
UBiDiDirection direction;
UBool stable;
DirProp newProp;
pOpening=&bd->openings[openIdx];
direction=(UBiDiDirection)(pLastIsoRun->level&1);
stable=true; /* assume stable until proved otherwise */
/* The stable flag is set when brackets are paired and their
level is resolved and cannot be changed by what will be
found later in the source string.
An unstable match can occur only when applying N0c, where
the resolved level depends on the preceding context, and
this context may be affected by text occurring later.
Example: RTL paragraph containing: abc[(latin) HEBREW]
When the closing parenthesis is encountered, it appears
that N0c1 must be applied since 'abc' sets an opposite
direction context and both parentheses receive level 2.
However, when the closing square bracket is processed,
N0b applies because of 'HEBREW' being included within the
brackets, thus the square brackets are treated like R and
receive level 1. However, this changes the preceding
context of the opening parenthesis, and it now appears
that N0c2 must be applied to the parentheses rather than
N0c1. */
if((direction==0 && pOpening->flags&FOUND_L) ||
(direction==1 && pOpening->flags&FOUND_R)) { /* N0b */
newProp=static_cast<DirProp>(direction);
}
else if(pOpening->flags&(FOUND_L|FOUND_R)) { /* N0c */
/* it is stable if there is no containing pair or in
conditions too complicated and not worth checking */
stable=(openIdx==pLastIsoRun->start);
if(direction!=pOpening->contextDir)
newProp= static_cast<DirProp>(pOpening->contextDir); /* N0c1 */
else
newProp= static_cast<DirProp>(direction); /* N0c2 */
} else {
/* forget this and any brackets nested within this pair */
pLastIsoRun->limit= static_cast<uint16_t>(openIdx);
return ON; /* N0d */
}
bd->pBiDi->dirProps[pOpening->position]=newProp;
bd->pBiDi->dirProps[position]=newProp;
/* Update nested N0c pairs that may be affected */
fixN0c(bd, openIdx, pOpening->position, newProp);
if(stable) {
pLastIsoRun->limit= static_cast<uint16_t>(openIdx); /* forget any brackets nested within this pair */
/* remove lower located synonyms if any */
while(pLastIsoRun->limit>pLastIsoRun->start &&
bd->openings[pLastIsoRun->limit-1].position==pOpening->position)
pLastIsoRun->limit--;
} else {
int32_t k;
pOpening->match=-position;
/* neutralize lower located synonyms if any */
k=openIdx-1;
while(k>=pLastIsoRun->start &&
bd->openings[k].position==pOpening->position)
bd->openings[k--].match=0;
/* neutralize any unmatched opening between the current pair;
this will also neutralize higher located synonyms if any */
for(k=openIdx+1; k<pLastIsoRun->limit; k++) {
qOpening=&bd->openings[k];
if(qOpening->position>=position)
break;
if(qOpening->match>0)
qOpening->match=0;
}
}
return newProp;
}
/* handle strong characters, digits and candidates for closing brackets */
static UBool /* return true if success */
bracketProcessChar(BracketData *bd, int32_t position) {
IsoRun *pLastIsoRun=&bd->isoRuns[bd->isoRunLast];
DirProp *dirProps, dirProp, newProp;
UBiDiLevel level;
dirProps=bd->pBiDi->dirProps;
dirProp=dirProps[position];
if(dirProp==ON) {
UChar c, match;
int32_t idx;
/* First see if it is a matching closing bracket. Hopefully, this is
more efficient than checking if it is a closing bracket at all */
c=bd->pBiDi->text[position];
for(idx=pLastIsoRun->limit-1; idx>=pLastIsoRun->start; idx--) {
if(bd->openings[idx].match!=c)
continue;
/* We have a match */
newProp=bracketProcessClosing(bd, idx, position);
if(newProp==ON) { /* N0d */
c=0; /* prevent handling as an opening */
break;
}
pLastIsoRun->lastBase=ON;
pLastIsoRun->contextDir=(UBiDiDirection)newProp;
pLastIsoRun->contextPos=position;
level=bd->pBiDi->levels[position];
if(level&UBIDI_LEVEL_OVERRIDE) { /* X4, X5 */
uint16_t flag;
int32_t i;
newProp=level&1;
pLastIsoRun->lastStrong=newProp;
flag=DIRPROP_FLAG(newProp);
for(i=pLastIsoRun->start; i<idx; i++)
bd->openings[i].flags|=flag;
/* matching brackets are not overridden by LRO/RLO */
bd->pBiDi->levels[position]&=~UBIDI_LEVEL_OVERRIDE;
}
/* matching brackets are not overridden by LRO/RLO */
bd->pBiDi->levels[bd->openings[idx].position]&=~UBIDI_LEVEL_OVERRIDE;
return true;
}
/* We get here only if the ON character is not a matching closing
bracket or it is a case of N0d */
/* Now see if it is an opening bracket */
if(c)
match= static_cast<UChar>(u_getBidiPairedBracket(c)); /* get the matching char */
else
match=0;
if(match!=c && /* has a matching char */
ubidi_getPairedBracketType(c)==U_BPT_OPEN) { /* opening bracket */
/* special case: process synonyms
create an opening entry for each synonym */
if(match==0x232A) { /* RIGHT-POINTING ANGLE BRACKET */
if(!bracketAddOpening(bd, 0x3009, position))
return false;
}
else if(match==0x3009) { /* RIGHT ANGLE BRACKET */
if(!bracketAddOpening(bd, 0x232A, position))
return false;
}
if(!bracketAddOpening(bd, match, position))
return false;
}
}
level=bd->pBiDi->levels[position];
if(level&UBIDI_LEVEL_OVERRIDE) { /* X4, X5 */
newProp=level&1;
if(dirProp!=S && dirProp!=WS && dirProp!=ON)
dirProps[position]=newProp;
pLastIsoRun->lastBase=newProp;
pLastIsoRun->lastStrong=newProp;
pLastIsoRun->contextDir=(UBiDiDirection)newProp;
pLastIsoRun->contextPos=position;
}
else if(dirProp<=R || dirProp==AL) {
newProp= static_cast<DirProp>(DIR_FROM_STRONG(dirProp));
pLastIsoRun->lastBase=dirProp;
pLastIsoRun->lastStrong=dirProp;
pLastIsoRun->contextDir=(UBiDiDirection)newProp;
pLastIsoRun->contextPos=position;
}
else if(dirProp==EN) {
pLastIsoRun->lastBase=EN;
if(pLastIsoRun->lastStrong==L) {
newProp=L; /* W7 */
if(!bd->isNumbersSpecial)
dirProps[position]=ENL;
pLastIsoRun->contextDir=(UBiDiDirection)L;
pLastIsoRun->contextPos=position;
}
else {
newProp=R; /* N0 */
if(pLastIsoRun->lastStrong==AL)
dirProps[position]=AN; /* W2 */
else
dirProps[position]=ENR;
pLastIsoRun->contextDir=(UBiDiDirection)R;
pLastIsoRun->contextPos=position;
}
}
else if(dirProp==AN) {
newProp=R; /* N0 */
pLastIsoRun->lastBase=AN;
pLastIsoRun->contextDir=(UBiDiDirection)R;
pLastIsoRun->contextPos=position;
}
else if(dirProp==NSM) {
/* if the last real char was ON, change NSM to ON so that it
will stay ON even if the last real char is a bracket which
may be changed to L or R */
newProp=pLastIsoRun->lastBase;
if(newProp==ON)
dirProps[position]=newProp;
}
else {
newProp=dirProp;
pLastIsoRun->lastBase=dirProp;
}
if(newProp<=R || newProp==AL) {
int32_t i;
uint16_t flag=DIRPROP_FLAG(DIR_FROM_STRONG(newProp));
for(i=pLastIsoRun->start; i<pLastIsoRun->limit; i++)
if(position>bd->openings[i].position)
bd->openings[i].flags|=flag;
}
return true;
}
/* perform (X1)..(X9) ------------------------------------------------------- */
/* determine if the text is mixed-directional or single-directional */
static UBiDiDirection
directionFromFlags(UBiDi *pBiDi) {
Flags flags=pBiDi->flags;
/* if the text contains AN and neutrals, then some neutrals may become RTL */
if(!(flags&MASK_RTL || ((flags&DIRPROP_FLAG(AN)) && (flags&MASK_POSSIBLE_N)))) {
return UBIDI_LTR;
} else if(!(flags&MASK_LTR)) {
return UBIDI_RTL;
} else {
return UBIDI_MIXED;
}
}
/*
* Resolve the explicit levels as specified by explicit embedding codes.
* Recalculate the flags to have them reflect the real properties
* after taking the explicit embeddings into account.
*
* The BiDi algorithm is designed to result in the same behavior whether embedding
* levels are externally specified (from "styled text", supposedly the preferred
* method) or set by explicit embedding codes (LRx, RLx, PDF, FSI, PDI) in the plain text.
* That is why (X9) instructs to remove all not-isolate explicit codes (and BN).
* However, in a real implementation, the removal of these codes and their index
* positions in the plain text is undesirable since it would result in
* reallocated, reindexed text.
* Instead, this implementation leaves the codes in there and just ignores them
* in the subsequent processing.
* In order to get the same reordering behavior, positions with a BN or a not-isolate
* explicit embedding code just get the same level assigned as the last "real"
* character.
*
* Some implementations, not this one, then overwrite some of these
* directionality properties at "real" same-level-run boundaries by
* L or R codes so that the resolution of weak types can be performed on the
* entire paragraph at once instead of having to parse it once more and
* perform that resolution on same-level-runs.
* This limits the scope of the implicit rules in effectively
* the same way as the run limits.
*
* Instead, this implementation does not modify these codes, except for
* paired brackets whose properties (ON) may be replaced by L or R.
* On one hand, the paragraph has to be scanned for same-level-runs, but
* on the other hand, this saves another loop to reset these codes,
* or saves making and modifying a copy of dirProps[].
*
*
* Note that (Pn) and (Xn) changed significantly from version 4 of the BiDi algorithm.
*
*
* Handling the stack of explicit levels (Xn):
*
* With the BiDi stack of explicit levels, as pushed with each
* LRE, RLE, LRO, RLO, LRI, RLI and FSI and popped with each PDF and PDI,
* the explicit level must never exceed UBIDI_MAX_EXPLICIT_LEVEL.
*
* In order to have a correct push-pop semantics even in the case of overflows,
* overflow counters and a valid isolate counter are used as described in UAX#9
* section 3.3.2 "Explicit Levels and Directions".
*
* This implementation assumes that UBIDI_MAX_EXPLICIT_LEVEL is odd.
*
* Returns normally the direction; -1 if there was a memory shortage
*
*/
static UBiDiDirection
resolveExplicitLevels(UBiDi *pBiDi, UErrorCode *pErrorCode) {
DirProp *dirProps=pBiDi->dirProps;
UBiDiLevel *levels=pBiDi->levels;
const UChar *text=pBiDi->text;
int32_t i=0, length=pBiDi->length;
Flags flags=pBiDi->flags; /* collect all directionalities in the text */
DirProp dirProp;
UBiDiLevel level=GET_PARALEVEL(pBiDi, 0);
UBiDiDirection direction;
pBiDi->isolateCount=0;
if(U_FAILURE(*pErrorCode)) { return UBIDI_LTR; }
/* determine if the text is mixed-directional or single-directional */
direction=directionFromFlags(pBiDi);
/* we may not need to resolve any explicit levels */
if((direction!=UBIDI_MIXED)) {
/* not mixed directionality: levels don't matter - trailingWSStart will be 0 */
return direction;
}
if(pBiDi->reorderingMode > UBIDI_REORDER_LAST_LOGICAL_TO_VISUAL) {
/* inverse BiDi: mixed, but all characters are at the same embedding level */
/* set all levels to the paragraph level */
int32_t paraIndex, start, limit;
for(paraIndex=0; paraIndex<pBiDi->paraCount; paraIndex++) {
if(paraIndex==0)
start=0;
else
start=pBiDi->paras[paraIndex-1].limit;
limit=pBiDi->paras[paraIndex].limit;
level= static_cast<UBiDiLevel>(pBiDi->paras[paraIndex].level);
for(i=start; i<limit; i++)
levels[i]=level;
}
return direction; /* no bracket matching for inverse BiDi */
}
if(!(flags&(MASK_EXPLICIT|MASK_ISO))) {
/* no embeddings, set all levels to the paragraph level */
/* we still have to perform bracket matching */
int32_t paraIndex, start, limit;
BracketData bracketData;
bracketInit(pBiDi, &bracketData);
for(paraIndex=0; paraIndex<pBiDi->paraCount; paraIndex++) {
if(paraIndex==0)
start=0;
else
start=pBiDi->paras[paraIndex-1].limit;
limit=pBiDi->paras[paraIndex].limit;
level= static_cast<UBiDiLevel>(pBiDi->paras[paraIndex].level);
for(i=start; i<limit; i++) {
levels[i]=level;
dirProp=dirProps[i];
if(dirProp==BN)
continue;
if(dirProp==B) {
if((i+1)<length) {
if(text[i]==CR && text[i+1]==LF)
continue; /* skip CR when followed by LF */
bracketProcessB(&bracketData, level);
}
continue;
}
if(!bracketProcessChar(&bracketData, i)) {
*pErrorCode=U_MEMORY_ALLOCATION_ERROR;
return UBIDI_LTR;
}
}
}
return direction;
}
{
/* continue to perform (Xn) */
/* (X1) level is set for all codes, embeddingLevel keeps track of the push/pop operations */
/* both variables may carry the UBIDI_LEVEL_OVERRIDE flag to indicate the override status */
UBiDiLevel embeddingLevel=level, newLevel;
UBiDiLevel previousLevel=level; /* previous level for regular (not CC) characters */
int32_t lastCcPos=0; /* index of last effective LRx,RLx, PDx */
/* The following stack remembers the embedding level and the ISOLATE flag of level runs.
stackLast points to its current entry. */
uint16_t stack[UBIDI_MAX_EXPLICIT_LEVEL+2]; /* we never push anything >=UBIDI_MAX_EXPLICIT_LEVEL
but we need one more entry as base */
uint32_t stackLast=0;
int32_t overflowIsolateCount=0;
int32_t overflowEmbeddingCount=0;
int32_t validIsolateCount=0;
BracketData bracketData;
bracketInit(pBiDi, &bracketData);
stack[0]=level; /* initialize base entry to para level, no override, no isolate */
/* recalculate the flags */
flags=0;
for(i=0; i<length; ++i) {
dirProp=dirProps[i];
switch(dirProp) {
case LRE:
case RLE:
case LRO:
case RLO:
/* (X2, X3, X4, X5) */
flags|=DIRPROP_FLAG(BN);
levels[i]=previousLevel;
if (dirProp==LRE || dirProp==LRO)
/* least greater even level */
newLevel=(UBiDiLevel)((embeddingLevel+2)&~(UBIDI_LEVEL_OVERRIDE|1));
else
/* least greater odd level */
newLevel=(UBiDiLevel)((NO_OVERRIDE(embeddingLevel)+1)|1);
if(newLevel<=UBIDI_MAX_EXPLICIT_LEVEL && overflowIsolateCount==0 &&
overflowEmbeddingCount==0) {
lastCcPos=i;
embeddingLevel=newLevel;
if(dirProp==LRO || dirProp==RLO)
embeddingLevel|=UBIDI_LEVEL_OVERRIDE;
stackLast++;
stack[stackLast]=embeddingLevel;
/* we don't need to set UBIDI_LEVEL_OVERRIDE off for LRE and RLE
since this has already been done for newLevel which is
the source for embeddingLevel.
*/
} else {
if(overflowIsolateCount==0)
overflowEmbeddingCount++;
}
break;
case PDF:
/* (X7) */
flags|=DIRPROP_FLAG(BN);
levels[i]=previousLevel;
/* handle all the overflow cases first */
if(overflowIsolateCount) {
break;
}
if(overflowEmbeddingCount) {
overflowEmbeddingCount--;
break;
}
if(stackLast>0 && stack[stackLast]<ISOLATE) { /* not an isolate entry */
lastCcPos=i;
stackLast--;
embeddingLevel=(UBiDiLevel)stack[stackLast];
}
break;
case LRI:
case RLI:
flags|=(DIRPROP_FLAG(ON)|DIRPROP_FLAG_LR(embeddingLevel));
levels[i]=NO_OVERRIDE(embeddingLevel);
if(NO_OVERRIDE(embeddingLevel)!=NO_OVERRIDE(previousLevel)) {
bracketProcessBoundary(&bracketData, lastCcPos,
previousLevel, embeddingLevel);
flags|=DIRPROP_FLAG_MULTI_RUNS;
}
previousLevel=embeddingLevel;
/* (X5a, X5b) */
if(dirProp==LRI)
/* least greater even level */
newLevel=(UBiDiLevel)((embeddingLevel+2)&~(UBIDI_LEVEL_OVERRIDE|1));
else
/* least greater odd level */
newLevel=(UBiDiLevel)((NO_OVERRIDE(embeddingLevel)+1)|1);
if(newLevel<=UBIDI_MAX_EXPLICIT_LEVEL && overflowIsolateCount==0 &&
overflowEmbeddingCount==0) {
flags|=DIRPROP_FLAG(dirProp);
lastCcPos=i;
validIsolateCount++;
if(validIsolateCount>pBiDi->isolateCount)
pBiDi->isolateCount=validIsolateCount;
embeddingLevel=newLevel;
/* we can increment stackLast without checking because newLevel
will exceed UBIDI_MAX_EXPLICIT_LEVEL before stackLast overflows */
stackLast++;
stack[stackLast]=embeddingLevel+ISOLATE;
bracketProcessLRI_RLI(&bracketData, embeddingLevel);
} else {
/* make it WS so that it is handled by adjustWSLevels() */
dirProps[i]=WS;
overflowIsolateCount++;
}
break;
case PDI:
if(NO_OVERRIDE(embeddingLevel)!=NO_OVERRIDE(previousLevel)) {
bracketProcessBoundary(&bracketData, lastCcPos,
previousLevel, embeddingLevel);
flags|=DIRPROP_FLAG_MULTI_RUNS;
}
/* (X6a) */
if(overflowIsolateCount) {
overflowIsolateCount--;
/* make it WS so that it is handled by adjustWSLevels() */
dirProps[i]=WS;
}
else if(validIsolateCount) {
flags|=DIRPROP_FLAG(PDI);
lastCcPos=i;
overflowEmbeddingCount=0;
while(stack[stackLast]<ISOLATE) /* pop embedding entries */
stackLast--; /* until the last isolate entry */
stackLast--; /* pop also the last isolate entry */
validIsolateCount--;
bracketProcessPDI(&bracketData);
} else
/* make it WS so that it is handled by adjustWSLevels() */
dirProps[i]=WS;
embeddingLevel=(UBiDiLevel)stack[stackLast]&~ISOLATE;
flags|=(DIRPROP_FLAG(ON)|DIRPROP_FLAG_LR(embeddingLevel));
previousLevel=embeddingLevel;
levels[i]=NO_OVERRIDE(embeddingLevel);
break;
case B:
flags|=DIRPROP_FLAG(B);
levels[i]=GET_PARALEVEL(pBiDi, i);
if((i+1)<length) {
if(text[i]==CR && text[i+1]==LF)
break; /* skip CR when followed by LF */
overflowEmbeddingCount=overflowIsolateCount=0;
validIsolateCount=0;
stackLast=0;
previousLevel=embeddingLevel=GET_PARALEVEL(pBiDi, i+1);
stack[0]=embeddingLevel; /* initialize base entry to para level, no override, no isolate */
bracketProcessB(&bracketData, embeddingLevel);
}
break;
case BN:
/* BN, LRE, RLE, and PDF are supposed to be removed (X9) */
/* they will get their levels set correctly in adjustWSLevels() */
levels[i]=previousLevel;
flags|=DIRPROP_FLAG(BN);
break;
default:
/* all other types are normal characters and get the "real" level */
if(NO_OVERRIDE(embeddingLevel)!=NO_OVERRIDE(previousLevel)) {
bracketProcessBoundary(&bracketData, lastCcPos,
previousLevel, embeddingLevel);
flags|=DIRPROP_FLAG_MULTI_RUNS;
if(embeddingLevel&UBIDI_LEVEL_OVERRIDE)
flags|=DIRPROP_FLAG_O(embeddingLevel);
else
flags|=DIRPROP_FLAG_E(embeddingLevel);
}
previousLevel=embeddingLevel;
levels[i]=embeddingLevel;
if(!bracketProcessChar(&bracketData, i))
return (UBiDiDirection)-1;
/* the dirProp may have been changed in bracketProcessChar() */
flags|=DIRPROP_FLAG(dirProps[i]);
break;
}
}
if(flags&MASK_EMBEDDING)
flags|=DIRPROP_FLAG_LR(pBiDi->paraLevel);
if(pBiDi->orderParagraphsLTR && (flags&DIRPROP_FLAG(B)))
flags|=DIRPROP_FLAG(L);
/* again, determine if the text is mixed-directional or single-directional */
pBiDi->flags=flags;
direction=directionFromFlags(pBiDi);
}
return direction;
}
/*
* Use a pre-specified embedding levels array:
*
* Adjust the directional properties for overrides (->LEVEL_OVERRIDE),
* ignore all explicit codes (X9),
* and check all the preset levels.
*
* Recalculate the flags to have them reflect the real properties
* after taking the explicit embeddings into account.
*/
static UBiDiDirection
checkExplicitLevels(UBiDi *pBiDi, UErrorCode *pErrorCode) {
DirProp *dirProps=pBiDi->dirProps;
UBiDiLevel *levels=pBiDi->levels;
int32_t isolateCount=0;
int32_t length=pBiDi->length;
Flags flags=0; /* collect all directionalities in the text */
pBiDi->isolateCount=0;
int32_t currentParaIndex = 0;
int32_t currentParaLimit = pBiDi->paras[0].limit;
int32_t currentParaLevel = pBiDi->paraLevel;
for(int32_t i=0; i<length; ++i) {
UBiDiLevel level=levels[i];
DirProp dirProp=dirProps[i];
if(dirProp==LRI || dirProp==RLI) {
isolateCount++;
if(isolateCount>pBiDi->isolateCount)
pBiDi->isolateCount=isolateCount;
}
else if(dirProp==PDI)
isolateCount--;
else if(dirProp==B)
isolateCount=0;
// optimized version of int32_t currentParaLevel = GET_PARALEVEL(pBiDi, i);
if (pBiDi->defaultParaLevel != 0 &&
i == currentParaLimit && (currentParaIndex + 1) < pBiDi->paraCount) {
currentParaLevel = pBiDi->paras[++currentParaIndex].level;
currentParaLimit = pBiDi->paras[currentParaIndex].limit;
}
UBiDiLevel overrideFlag = level & UBIDI_LEVEL_OVERRIDE;
level &= ~UBIDI_LEVEL_OVERRIDE;
if (level < currentParaLevel || UBIDI_MAX_EXPLICIT_LEVEL < level) {
if (level == 0) {
if (dirProp == B) {
// Paragraph separators are ok with explicit level 0.
// Prevents reordering of paragraphs.
} else {
// Treat explicit level 0 as a wildcard for the paragraph level.
// Avoid making the caller guess what the paragraph level would be.
level = (UBiDiLevel)currentParaLevel;
levels[i] = level | overrideFlag;
}
} else {
// 1 <= level < currentParaLevel or UBIDI_MAX_EXPLICIT_LEVEL < level
/* level out of bounds */
*pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
return UBIDI_LTR;
}
}
if (overrideFlag != 0) {
/* keep the override flag in levels[i] but adjust the flags */
flags|=DIRPROP_FLAG_O(level);
} else {
/* set the flags */
flags|=DIRPROP_FLAG_E(level)|DIRPROP_FLAG(dirProp);
}
}
if(flags&MASK_EMBEDDING)
flags|=DIRPROP_FLAG_LR(pBiDi->paraLevel);
/* determine if the text is mixed-directional or single-directional */
pBiDi->flags=flags;
return directionFromFlags(pBiDi);
}
/******************************************************************
The Properties state machine table
*******************************************************************
All table cells are 8 bits:
bits 0..4: next state
bits 5..7: action to perform (if > 0)
Cells may be of format "n" where n represents the next state
(except for the rightmost column).
Cells may also be of format "s(x,y)" where x represents an action
to perform and y represents the next state.
*******************************************************************
Definitions and type for properties state table
*******************************************************************
*/
#define IMPTABPROPS_COLUMNS 16
#define IMPTABPROPS_RES (IMPTABPROPS_COLUMNS - 1)
#define GET_STATEPROPS(cell) ((cell)&0x1f)
#define GET_ACTIONPROPS(cell) ((cell)>>5)
#define s(action, newState) ((uint8_t)(newState+(action<<5)))
static const uint8_t groupProp[] = /* dirProp regrouped */
{
/* L R EN ES ET AN CS B S WS ON LRE LRO AL RLE RLO PDF NSM BN FSI LRI RLI PDI ENL ENR */
0, 1, 2, 7, 8, 3, 9, 6, 5, 4, 4, 10, 10, 12, 10, 10, 10, 11, 10, 4, 4, 4, 4, 13, 14
};
enum { DirProp_L=0, DirProp_R=1, DirProp_EN=2, DirProp_AN=3, DirProp_ON=4, DirProp_S=5, DirProp_B=6 }; /* reduced dirProp */
/******************************************************************
PROPERTIES STATE TABLE
In table impTabProps,
- the ON column regroups ON and WS, FSI, RLI, LRI and PDI
- the BN column regroups BN, LRE, RLE, LRO, RLO, PDF
- the Res column is the reduced property assigned to a run
Action 1: process current run1, init new run1
2: init new run2
3: process run1, process run2, init new run1
4: process run1, set run1=run2, init new run2
Notes:
1) This table is used in resolveImplicitLevels().
2) This table triggers actions when there is a change in the Bidi
property of incoming characters (action 1).
3) Most such property sequences are processed immediately (in
fact, passed to processPropertySeq().
4) However, numbers are assembled as one sequence. This means
that undefined situations (like CS following digits, until
it is known if the next char will be a digit) are held until
following chars define them.
Example: digits followed by CS, then comes another CS or ON;
the digits will be processed, then the CS assigned
as the start of an ON sequence (action 3).
5) There are cases where more than one sequence must be
processed, for instance digits followed by CS followed by L:
the digits must be processed as one sequence, and the CS
must be processed as an ON sequence, all this before starting
assembling chars for the opening L sequence.
*/
static const uint8_t impTabProps[][IMPTABPROPS_COLUMNS] =
{
/* L , R , EN , AN , ON , S , B , ES , ET , CS , BN , NSM , AL , ENL , ENR , Res */
/* 0 Init */ { 1 , 2 , 4 , 5 , 7 , 15 , 17 , 7 , 9 , 7 , 0 , 7 , 3 , 18 , 21 , DirProp_ON },
/* 1 L */ { 1 , s(1,2), s(1,4), s(1,5), s(1,7),s(1,15),s(1,17), s(1,7), s(1,9), s(1,7), 1 , 1 , s(1,3),s(1,18),s(1,21), DirProp_L },
/* 2 R */ { s(1,1), 2 , s(1,4), s(1,5), s(1,7),s(1,15),s(1,17), s(1,7), s(1,9), s(1,7), 2 , 2 , s(1,3),s(1,18),s(1,21), DirProp_R },
/* 3 AL */ { s(1,1), s(1,2), s(1,6), s(1,6), s(1,8),s(1,16),s(1,17), s(1,8), s(1,8), s(1,8), 3 , 3 , 3 ,s(1,18),s(1,21), DirProp_R },
/* 4 EN */ { s(1,1), s(1,2), 4 , s(1,5), s(1,7),s(1,15),s(1,17),s(2,10), 11 ,s(2,10), 4 , 4 , s(1,3), 18 , 21 , DirProp_EN },
/* 5 AN */ { s(1,1), s(1,2), s(1,4), 5 , s(1,7),s(1,15),s(1,17), s(1,7), s(1,9),s(2,12), 5 , 5 , s(1,3),s(1,18),s(1,21), DirProp_AN },
/* 6 AL:EN/AN */ { s(1,1), s(1,2), 6 , 6 , s(1,8),s(1,16),s(1,17), s(1,8), s(1,8),s(2,13), 6 , 6 , s(1,3), 18 , 21 , DirProp_AN },
/* 7 ON */ { s(1,1), s(1,2), s(1,4), s(1,5), 7 ,s(1,15),s(1,17), 7 ,s(2,14), 7 , 7 , 7 , s(1,3),s(1,18),s(1,21), DirProp_ON },
/* 8 AL:ON */ { s(1,1), s(1,2), s(1,6), s(1,6), 8 ,s(1,16),s(1,17), 8 , 8 , 8 , 8 , 8 , s(1,3),s(1,18),s(1,21), DirProp_ON },
/* 9 ET */ { s(1,1), s(1,2), 4 , s(1,5), 7 ,s(1,15),s(1,17), 7 , 9 , 7 , 9 , 9 , s(1,3), 18 , 21 , DirProp_ON },
/*10 EN+ES/CS */ { s(3,1), s(3,2), 4 , s(3,5), s(4,7),s(3,15),s(3,17), s(4,7),s(4,14), s(4,7), 10 , s(4,7), s(3,3), 18 , 21 , DirProp_EN },
/*11 EN+ET */ { s(1,1), s(1,2), 4 , s(1,5), s(1,7),s(1,15),s(1,17), s(1,7), 11 , s(1,7), 11 , 11 , s(1,3), 18 , 21 , DirProp_EN },
/*12 AN+CS */ { s(3,1), s(3,2), s(3,4), 5 , s(4,7),s(3,15),s(3,17), s(4,7),s(4,14), s(4,7), 12 , s(4,7), s(3,3),s(3,18),s(3,21), DirProp_AN },
/*13 AL:EN/AN+CS */ { s(3,1), s(3,2), 6 , 6 , s(4,8),s(3,16),s(3,17), s(4,8), s(4,8), s(4,8), 13 , s(4,8), s(3,3), 18 , 21 , DirProp_AN },
/*14 ON+ET */ { s(1,1), s(1,2), s(4,4), s(1,5), 7 ,s(1,15),s(1,17), 7 , 14 , 7 , 14 , 14 , s(1,3),s(4,18),s(4,21), DirProp_ON },
/*15 S */ { s(1,1), s(1,2), s(1,4), s(1,5), s(1,7), 15 ,s(1,17), s(1,7), s(1,9), s(1,7), 15 , s(1,7), s(1,3),s(1,18),s(1,21), DirProp_S },
/*16 AL:S */ { s(1,1), s(1,2), s(1,6), s(1,6), s(1,8), 16 ,s(1,17), s(1,8), s(1,8), s(1,8), 16 , s(1,8), s(1,3),s(1,18),s(1,21), DirProp_S },
/*17 B */ { s(1,1), s(1,2), s(1,4), s(1,5), s(1,7),s(1,15), 17 , s(1,7), s(1,9), s(1,7), 17 , s(1,7), s(1,3),s(1,18),s(1,21), DirProp_B },
/*18 ENL */ { s(1,1), s(1,2), 18 , s(1,5), s(1,7),s(1,15),s(1,17),s(2,19), 20 ,s(2,19), 18 , 18 , s(1,3), 18 , 21 , DirProp_L },
/*19 ENL+ES/CS */ { s(3,1), s(3,2), 18 , s(3,5), s(4,7),s(3,15),s(3,17), s(4,7),s(4,14), s(4,7), 19 , s(4,7), s(3,3), 18 , 21 , DirProp_L },
/*20 ENL+ET */ { s(1,1), s(1,2), 18 , s(1,5), s(1,7),s(1,15),s(1,17), s(1,7), 20 , s(1,7), 20 , 20 , s(1,3), 18 , 21 , DirProp_L },
/*21 ENR */ { s(1,1), s(1,2), 21 , s(1,5), s(1,7),s(1,15),s(1,17),s(2,22), 23 ,s(2,22), 21 , 21 , s(1,3), 18 , 21 , DirProp_AN },
/*22 ENR+ES/CS */ { s(3,1), s(3,2), 21 , s(3,5), s(4,7),s(3,15),s(3,17), s(4,7),s(4,14), s(4,7), 22 , s(4,7), s(3,3), 18 , 21 , DirProp_AN },
/*23 ENR+ET */ { s(1,1), s(1,2), 21 , s(1,5), s(1,7),s(1,15),s(1,17), s(1,7), 23 , s(1,7), 23 , 23 , s(1,3), 18 , 21 , DirProp_AN }
};
/* we must undef macro s because the levels tables have a different
* structure (4 bits for action and 4 bits for next state.
*/
#undef s
/******************************************************************
The levels state machine tables
*******************************************************************
All table cells are 8 bits:
bits 0..3: next state
bits 4..7: action to perform (if > 0)
Cells may be of format "n" where n represents the next state
(except for the rightmost column).
Cells may also be of format "s(x,y)" where x represents an action
to perform and y represents the next state.
This format limits each table to 16 states each and to 15 actions.
*******************************************************************
Definitions and type for levels state tables
*******************************************************************
*/
#define IMPTABLEVELS_COLUMNS (DirProp_B + 2)
#define IMPTABLEVELS_RES (IMPTABLEVELS_COLUMNS - 1)
#define GET_STATE(cell) ((cell)&0x0f)
#define GET_ACTION(cell) ((cell)>>4)
#define s(action, newState) ((uint8_t)(newState+(action<<4)))
typedef uint8_t ImpTab[][IMPTABLEVELS_COLUMNS];
typedef uint8_t ImpAct[];
/* FOOD FOR THOUGHT: each ImpTab should have its associated ImpAct,
* instead of having a pair of ImpTab and a pair of ImpAct.
*/
typedef struct ImpTabPair {
const void * pImpTab[2];
const void * pImpAct[2];
} ImpTabPair;
/******************************************************************
LEVELS STATE TABLES
In all levels state tables,
- state 0 is the initial state
- the Res column is the increment to add to the text level
for this property sequence.
The impAct arrays for each table of a pair map the local action
numbers of the table to the total list of actions. For instance,
action 2 in a given table corresponds to the action number which
appears in entry [2] of the impAct array for that table.
The first entry of all impAct arrays must be 0.
Action 1: init conditional sequence
2: prepend conditional sequence to current sequence
3: set ON sequence to new level - 1
4: init EN/AN/ON sequence
5: fix EN/AN/ON sequence followed by R
6: set previous level sequence to level 2
Notes:
1) These tables are used in processPropertySeq(). The input
is property sequences as determined by resolveImplicitLevels.
2) Most such property sequences are processed immediately
(levels are assigned).
3) However, some sequences cannot be assigned a final level till
one or more following sequences are received. For instance,
ON following an R sequence within an even-level paragraph.
If the following sequence is R, the ON sequence will be
assigned basic run level+1, and so will the R sequence.
4) S is generally handled like ON, since its level will be fixed
to paragraph level in adjustWSLevels().
*/
static const ImpTab impTabL_DEFAULT = /* Even paragraph level */
/* In this table, conditional sequences receive the lower possible level
until proven otherwise.
*/
{
/* L , R , EN , AN , ON , S , B , Res */
/* 0 : init */ { 0 , 1 , 0 , 2 , 0 , 0 , 0 , 0 },
/* 1 : R */ { 0 , 1 , 3 , 3 , s(1,4), s(1,4), 0 , 1 },
/* 2 : AN */ { 0 , 1 , 0 , 2 , s(1,5), s(1,5), 0 , 2 },
/* 3 : R+EN/AN */ { 0 , 1 , 3 , 3 , s(1,4), s(1,4), 0 , 2 },
/* 4 : R+ON */ { 0 , s(2,1), s(3,3), s(3,3), 4 , 4 , 0 , 0 },
/* 5 : AN+ON */ { 0 , s(2,1), 0 , s(3,2), 5 , 5 , 0 , 0 }
};
static const ImpTab impTabR_DEFAULT = /* Odd paragraph level */
/* In this table, conditional sequences receive the lower possible level
until proven otherwise.
*/
{
/* L , R , EN , AN , ON , S , B , Res */
/* 0 : init */ { 1 , 0 , 2 , 2 , 0 , 0 , 0 , 0 },
/* 1 : L */ { 1 , 0 , 1 , 3 , s(1,4), s(1,4), 0 , 1 },
/* 2 : EN/AN */ { 1 , 0 , 2 , 2 , 0 , 0 , 0 , 1 },
/* 3 : L+AN */ { 1 , 0 , 1 , 3 , 5 , 5 , 0 , 1 },
/* 4 : L+ON */ { s(2,1), 0 , s(2,1), 3 , 4 , 4 , 0 , 0 },
/* 5 : L+AN+ON */ { 1 , 0 , 1 , 3 , 5 , 5 , 0 , 0 }
};
static const ImpAct impAct0 = {0,1,2,3,4};
static const ImpTabPair impTab_DEFAULT = {{&impTabL_DEFAULT,
&impTabR_DEFAULT},
{&impAct0, &impAct0}};
static const ImpTab impTabL_NUMBERS_SPECIAL = /* Even paragraph level */
/* In this table, conditional sequences receive the lower possible level
until proven otherwise.
*/
{
/* L , R , EN , AN , ON , S , B , Res */
/* 0 : init */ { 0 , 2 , s(1,1), s(1,1), 0 , 0 , 0 , 0 },
/* 1 : L+EN/AN */ { 0 , s(4,2), 1 , 1 , 0 , 0 , 0 , 0 },
/* 2 : R */ { 0 , 2 , 4 , 4 , s(1,3), s(1,3), 0 , 1 },
/* 3 : R+ON */ { 0 , s(2,2), s(3,4), s(3,4), 3 , 3 , 0 , 0 },
/* 4 : R+EN/AN */ { 0 , 2 , 4 , 4 , s(1,3), s(1,3), 0 , 2 }
};
static const ImpTabPair impTab_NUMBERS_SPECIAL = {{&impTabL_NUMBERS_SPECIAL,
&impTabR_DEFAULT},
{&impAct0, &impAct0}};
static const ImpTab impTabL_GROUP_NUMBERS_WITH_R =
/* In this table, EN/AN+ON sequences receive levels as if associated with R
until proven that there is L or sor/eor on both sides. AN is handled like EN.
*/
{
/* L , R , EN , AN , ON , S , B , Res */
/* 0 init */ { 0 , 3 , s(1,1), s(1,1), 0 , 0 , 0 , 0 },
/* 1 EN/AN */ { s(2,0), 3 , 1 , 1 , 2 , s(2,0), s(2,0), 2 },
/* 2 EN/AN+ON */ { s(2,0), 3 , 1 , 1 , 2 , s(2,0), s(2,0), 1 },
/* 3 R */ { 0 , 3 , 5 , 5 , s(1,4), 0 , 0 , 1 },
/* 4 R+ON */ { s(2,0), 3 , 5 , 5 , 4 , s(2,0), s(2,0), 1 },
/* 5 R+EN/AN */ { 0 , 3 , 5 , 5 , s(1,4), 0 , 0 , 2 }
};
static const ImpTab impTabR_GROUP_NUMBERS_WITH_R =
/* In this table, EN/AN+ON sequences receive levels as if associated with R
until proven that there is L on both sides. AN is handled like EN.
*/
{
/* L , R , EN , AN , ON , S , B , Res */
/* 0 init */ { 2 , 0 , 1 , 1 , 0 , 0 , 0 , 0 },
/* 1 EN/AN */ { 2 , 0 , 1 , 1 , 0 , 0 , 0 , 1 },
/* 2 L */ { 2 , 0 , s(1,4), s(1,4), s(1,3), 0 , 0 , 1 },
/* 3 L+ON */ { s(2,2), 0 , 4 , 4 , 3 , 0 , 0 , 0 },
/* 4 L+EN/AN */ { s(2,2), 0 , 4 , 4 , 3 , 0 , 0 , 1 }
};
static const ImpTabPair impTab_GROUP_NUMBERS_WITH_R = {
{&impTabL_GROUP_NUMBERS_WITH_R,
&impTabR_GROUP_NUMBERS_WITH_R},
{&impAct0, &impAct0}};
static const ImpTab impTabL_INVERSE_NUMBERS_AS_L =
/* This table is identical to the Default LTR table except that EN and AN are
handled like L.
*/
{
/* L , R , EN , AN , ON , S , B , Res */
/* 0 : init */ { 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 },
/* 1 : R */ { 0 , 1 , 0 , 0 , s(1,4), s(1,4), 0 , 1 },
/* 2 : AN */ { 0 , 1 , 0 , 0 , s(1,5), s(1,5), 0 , 2 },
/* 3 : R+EN/AN */ { 0 , 1 , 0 , 0 , s(1,4), s(1,4), 0 , 2 },
/* 4 : R+ON */ { s(2,0), 1 , s(2,0), s(2,0), 4 , 4 , s(2,0), 1 },
/* 5 : AN+ON */ { s(2,0), 1 , s(2,0), s(2,0), 5 , 5 , s(2,0), 1 }
};
static const ImpTab impTabR_INVERSE_NUMBERS_AS_L =
/* This table is identical to the Default RTL table except that EN and AN are
handled like L.
*/
{
/* L , R , EN , AN , ON , S , B , Res */
/* 0 : init */ { 1 , 0 , 1 , 1 , 0 , 0 , 0 , 0 },
/* 1 : L */ { 1 , 0 , 1 , 1 , s(1,4), s(1,4), 0 , 1 },
/* 2 : EN/AN */ { 1 , 0 , 1 , 1 , 0 , 0 , 0 , 1 },
/* 3 : L+AN */ { 1 , 0 , 1 , 1 , 5 , 5 , 0 , 1 },
/* 4 : L+ON */ { s(2,1), 0 , s(2,1), s(2,1), 4 , 4 , 0 , 0 },
/* 5 : L+AN+ON */ { 1 , 0 , 1 , 1 , 5 , 5 , 0 , 0 }
};
static const ImpTabPair impTab_INVERSE_NUMBERS_AS_L = {
{&impTabL_INVERSE_NUMBERS_AS_L,
&impTabR_INVERSE_NUMBERS_AS_L},
{&impAct0, &impAct0}};
static const ImpTab impTabR_INVERSE_LIKE_DIRECT = /* Odd paragraph level */
/* In this table, conditional sequences receive the lower possible level
until proven otherwise.
*/
{
/* L , R , EN , AN , ON , S , B , Res */
/* 0 : init */ { 1 , 0 , 2 , 2 , 0 , 0 , 0 , 0 },
/* 1 : L */ { 1 , 0 , 1 , 2 , s(1,3), s(1,3), 0 , 1 },
/* 2 : EN/AN */ { 1 , 0 , 2 , 2 , 0 , 0 , 0 , 1 },
/* 3 : L+ON */ { s(2,1), s(3,0), 6 , 4 , 3 , 3 , s(3,0), 0 },
/* 4 : L+ON+AN */ { s(2,1), s(3,0), 6 , 4 , 5 , 5 , s(3,0), 3 },
/* 5 : L+AN+ON */ { s(2,1), s(3,0), 6 , 4 , 5 , 5 , s(3,0), 2 },
/* 6 : L+ON+EN */ { s(2,1), s(3,0), 6 , 4 , 3 , 3 , s(3,0), 1 }
};
static const ImpAct impAct1 = {0,1,13,14};
/* FOOD FOR THOUGHT: in LTR table below, check case "JKL 123abc"
*/
static const ImpTabPair impTab_INVERSE_LIKE_DIRECT = {
{&impTabL_DEFAULT,
&impTabR_INVERSE_LIKE_DIRECT},
{&impAct0, &impAct1}};
static const ImpTab impTabL_INVERSE_LIKE_DIRECT_WITH_MARKS =
/* The case handled in this table is (visually): R EN L
*/
{
/* L , R , EN , AN , ON , S , B , Res */
/* 0 : init */ { 0 , s(6,3), 0 , 1 , 0 , 0 , 0 , 0 },
/* 1 : L+AN */ { 0 , s(6,3), 0 , 1 , s(1,2), s(3,0), 0 , 4 },
/* 2 : L+AN+ON */ { s(2,0), s(6,3), s(2,0), 1 , 2 , s(3,0), s(2,0), 3 },
/* 3 : R */ { 0 , s(6,3), s(5,5), s(5,6), s(1,4), s(3,0), 0 , 3 },
/* 4 : R+ON */ { s(3,0), s(4,3), s(5,5), s(5,6), 4 , s(3,0), s(3,0), 3 },
/* 5 : R+EN */ { s(3,0), s(4,3), 5 , s(5,6), s(1,4), s(3,0), s(3,0), 4 },
/* 6 : R+AN */ { s(3,0), s(4,3), s(5,5), 6 , s(1,4), s(3,0), s(3,0), 4 }
};
static const ImpTab impTabR_INVERSE_LIKE_DIRECT_WITH_MARKS =
/* The cases handled in this table are (visually): R EN L
R L AN L
*/
{
/* L , R , EN , AN , ON , S , B , Res */
/* 0 : init */ { s(1,3), 0 , 1 , 1 , 0 , 0 , 0 , 0 },
/* 1 : R+EN/AN */ { s(2,3), 0 , 1 , 1 , 2 , s(4,0), 0 , 1 },
/* 2 : R+EN/AN+ON */ { s(2,3), 0 , 1 , 1 , 2 , s(4,0), 0 , 0 },
/* 3 : L */ { 3 , 0 , 3 , s(3,6), s(1,4), s(4,0), 0 , 1 },
/* 4 : L+ON */ { s(5,3), s(4,0), 5 , s(3,6), 4 , s(4,0), s(4,0), 0 },
/* 5 : L+ON+EN */ { s(5,3), s(4,0), 5 , s(3,6), 4 , s(4,0), s(4,0), 1 },
/* 6 : L+AN */ { s(5,3), s(4,0), 6 , 6 , 4 , s(4,0), s(4,0), 3 }
};
static const ImpAct impAct2 = {0,1,2,5,6,7,8};
static const ImpAct impAct3 = {0,1,9,10,11,12};
static const ImpTabPair impTab_INVERSE_LIKE_DIRECT_WITH_MARKS = {
{&impTabL_INVERSE_LIKE_DIRECT_WITH_MARKS,
&impTabR_INVERSE_LIKE_DIRECT_WITH_MARKS},
{&impAct2, &impAct3}};
static const ImpTabPair impTab_INVERSE_FOR_NUMBERS_SPECIAL = {
{&impTabL_NUMBERS_SPECIAL,
&impTabR_INVERSE_LIKE_DIRECT},
{&impAct0, &impAct1}};
static const ImpTab impTabL_INVERSE_FOR_NUMBERS_SPECIAL_WITH_MARKS =
/* The case handled in this table is (visually): R EN L
*/
{
/* L , R , EN , AN , ON , S , B , Res */
/* 0 : init */ { 0 , s(6,2), 1 , 1 , 0 , 0 , 0 , 0 },
/* 1 : L+EN/AN */ { 0 , s(6,2), 1 , 1 , 0 , s(3,0), 0 , 4 },
/* 2 : R */ { 0 , s(6,2), s(5,4), s(5,4), s(1,3), s(3,0), 0 , 3 },
/* 3 : R+ON */ { s(3,0), s(4,2), s(5,4), s(5,4), 3 , s(3,0), s(3,0), 3 },
/* 4 : R+EN/AN */ { s(3,0), s(4,2), 4 , 4 , s(1,3), s(3,0), s(3,0), 4 }
};
static const ImpTabPair impTab_INVERSE_FOR_NUMBERS_SPECIAL_WITH_MARKS = {
{&impTabL_INVERSE_FOR_NUMBERS_SPECIAL_WITH_MARKS,
&impTabR_INVERSE_LIKE_DIRECT_WITH_MARKS},
{&impAct2, &impAct3}};
#undef s
typedef struct {
const ImpTab * pImpTab; /* level table pointer */
const ImpAct * pImpAct; /* action map array */
int32_t startON; /* start of ON sequence */
int32_t startL2EN; /* start of level 2 sequence */
int32_t lastStrongRTL; /* index of last found R or AL */
int32_t state; /* current state */
int32_t runStart; /* start position of the run */
UBiDiLevel runLevel; /* run level before implicit solving */
} LevState;
/*------------------------------------------------------------------------*/
static void
addPoint(UBiDi *pBiDi, int32_t pos, int32_t flag)
/* param pos: position where to insert
param flag: one of LRM_BEFORE, LRM_AFTER, RLM_BEFORE, RLM_AFTER
*/
{
#define FIRSTALLOC 10
Point point;
InsertPoints * pInsertPoints=&(pBiDi->insertPoints);
if (pInsertPoints->capacity == 0)
{
pInsertPoints->points=static_cast<Point *>(uprv_malloc(sizeof(Point)*FIRSTALLOC));
if (pInsertPoints->points == NULL)
{
pInsertPoints->errorCode=U_MEMORY_ALLOCATION_ERROR;
return;
}
pInsertPoints->capacity=FIRSTALLOC;
}
if (pInsertPoints->size >= pInsertPoints->capacity) /* no room for new point */
{
Point * savePoints=pInsertPoints->points;
pInsertPoints->points=static_cast<Point *>(uprv_realloc(pInsertPoints->points,
pInsertPoints->capacity*2*sizeof(Point)));
if (pInsertPoints->points == NULL)
{
pInsertPoints->points=savePoints;
pInsertPoints->errorCode=U_MEMORY_ALLOCATION_ERROR;
return;
}
else pInsertPoints->capacity*=2;
}
point.pos=pos;
point.flag=flag;
pInsertPoints->points[pInsertPoints->size]=point;
pInsertPoints->size++;
#undef FIRSTALLOC
}
static void
setLevelsOutsideIsolates(UBiDi *pBiDi, int32_t start, int32_t limit, UBiDiLevel level)
{
DirProp *dirProps=pBiDi->dirProps, dirProp;
UBiDiLevel *levels=pBiDi->levels;
int32_t isolateCount=0, k;
for(k=start; k<limit; k++) {
dirProp=dirProps[k];
if(dirProp==PDI)
isolateCount--;
if(isolateCount==0)
levels[k]=level;
if(dirProp==LRI || dirProp==RLI)
isolateCount++;
}
}
/* perform rules (Wn), (Nn), and (In) on a run of the text ------------------ */
/*
* This implementation of the (Wn) rules applies all rules in one pass.
* In order to do so, it needs a look-ahead of typically 1 character
* (except for W5: sequences of ET) and keeps track of changes
* in a rule Wp that affect a later Wq (p<q).
*
* The (Nn) and (In) rules are also performed in that same single loop,
* but effectively one iteration behind for white space.
*
* Since all implicit rules are performed in one step, it is not necessary
* to actually store the intermediate directional properties in dirProps[].
*/
static void
processPropertySeq(UBiDi *pBiDi, LevState *pLevState, uint8_t _prop,
int32_t start, int32_t limit) {
uint8_t cell, oldStateSeq, actionSeq;
const ImpTab * pImpTab=pLevState->pImpTab;
const ImpAct * pImpAct=pLevState->pImpAct;
UBiDiLevel * levels=pBiDi->levels;
UBiDiLevel level, addLevel;
InsertPoints * pInsertPoints;
int32_t start0, k;
start0=start; /* save original start position */
oldStateSeq=(uint8_t)pLevState->state;
cell=(*pImpTab)[oldStateSeq][_prop];
pLevState->state=GET_STATE(cell); /* isolate the new state */
actionSeq=(*pImpAct)[GET_ACTION(cell)]; /* isolate the action */
addLevel=(*pImpTab)[pLevState->state][IMPTABLEVELS_RES];
if(actionSeq) {
switch(actionSeq) {
case 1: /* init ON seq */
pLevState->startON=start0;
break;
case 2: /* prepend ON seq to current seq */
start=pLevState->startON;
break;
case 3: /* EN/AN after R+ON */
level=pLevState->runLevel+1;
setLevelsOutsideIsolates(pBiDi, pLevState->startON, start0, level);
break;
case 4: /* EN/AN before R for NUMBERS_SPECIAL */
level=pLevState->runLevel+2;
setLevelsOutsideIsolates(pBiDi, pLevState->startON, start0, level);
break;
case 5: /* L or S after possible relevant EN/AN */
/* check if we had EN after R/AL */
if (pLevState->startL2EN >= 0) {
addPoint(pBiDi, pLevState->startL2EN, LRM_BEFORE);
}
pLevState->startL2EN=-1; /* not within previous if since could also be -2 */
/* check if we had any relevant EN/AN after R/AL */
pInsertPoints=&(pBiDi->insertPoints);
if ((pInsertPoints->capacity == 0) ||
(pInsertPoints->size <= pInsertPoints->confirmed))
{
/* nothing, just clean up */
pLevState->lastStrongRTL=-1;
/* check if we have a pending conditional segment */
level=(*pImpTab)[oldStateSeq][IMPTABLEVELS_RES];
if ((level & 1) && (pLevState->startON > 0)) { /* after ON */
start=pLevState->startON; /* reset to basic run level */
}
if (_prop == DirProp_S) /* add LRM before S */
{
addPoint(pBiDi, start0, LRM_BEFORE);
pInsertPoints->confirmed=pInsertPoints->size;
}
break;
}
/* reset previous RTL cont to level for LTR text */
for (k=pLevState->lastStrongRTL+1; k<start0; k++)
{
/* reset odd level, leave runLevel+2 as is */
levels[k]=(levels[k] - 2) & ~1;
}
/* mark insert points as confirmed */
pInsertPoints->confirmed=pInsertPoints->size;
pLevState->lastStrongRTL=-1;
if (_prop == DirProp_S) /* add LRM before S */
{
addPoint(pBiDi, start0, LRM_BEFORE);
pInsertPoints->confirmed=pInsertPoints->size;
}
break;
case 6: /* R/AL after possible relevant EN/AN */
/* just clean up */
pInsertPoints=&(pBiDi->insertPoints);
if (pInsertPoints->capacity > 0)
/* remove all non confirmed insert points */
pInsertPoints->size=pInsertPoints->confirmed;
pLevState->startON=-1;
pLevState->startL2EN=-1;
pLevState->lastStrongRTL=limit - 1;
break;
case 7: /* EN/AN after R/AL + possible cont */
/* check for real AN */
if ((_prop == DirProp_AN) && (pBiDi->dirProps[start0] == AN) &&
(pBiDi->reorderingMode!=UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL))
{
/* real AN */
if (pLevState->startL2EN == -1) /* if no relevant EN already found */
{
/* just note the righmost digit as a strong RTL */
pLevState->lastStrongRTL=limit - 1;
break;
}
if (pLevState->startL2EN >= 0) /* after EN, no AN */
{
addPoint(pBiDi, pLevState->startL2EN, LRM_BEFORE);
pLevState->startL2EN=-2;
}
/* note AN */
addPoint(pBiDi, start0, LRM_BEFORE);
break;
}
/* if first EN/AN after R/AL */
if (pLevState->startL2EN == -1) {
pLevState->startL2EN=start0;
}
break;
case 8: /* note location of latest R/AL */
pLevState->lastStrongRTL=limit - 1;
pLevState->startON=-1;
break;
case 9: /* L after R+ON/EN/AN */
/* include possible adjacent number on the left */
for (k=start0-1; k>=0 && !(levels[k]&1); k--);
if(k>=0) {
addPoint(pBiDi, k, RLM_BEFORE); /* add RLM before */
pInsertPoints=&(pBiDi->insertPoints);
pInsertPoints->confirmed=pInsertPoints->size; /* confirm it */
}
pLevState->startON=start0;
break;
case 10: /* AN after L */
/* AN numbers between L text on both sides may be trouble. */
/* tentatively bracket with LRMs; will be confirmed if followed by L */
addPoint(pBiDi, start0, LRM_BEFORE); /* add LRM before */
addPoint(pBiDi, start0, LRM_AFTER); /* add LRM after */
break;
case 11: /* R after L+ON/EN/AN */
/* false alert, infirm LRMs around previous AN */
pInsertPoints=&(pBiDi->insertPoints);
pInsertPoints->size=pInsertPoints->confirmed;
if (_prop == DirProp_S) /* add RLM before S */
{
addPoint(pBiDi, start0, RLM_BEFORE);
pInsertPoints->confirmed=pInsertPoints->size;
}
break;
case 12: /* L after L+ON/AN */
level=pLevState->runLevel + addLevel;
for(k=pLevState->startON; k<start0; k++) {
if (levels[k]<level)
levels[k]=level;
}
pInsertPoints=&(pBiDi->insertPoints);
pInsertPoints->confirmed=pInsertPoints->size; /* confirm inserts */
pLevState->startON=start0;
break;
case 13: /* L after L+ON+EN/AN/ON */
level=pLevState->runLevel;
for(k=start0-1; k>=pLevState->startON; k--) {
if(levels[k]==level+3) {
while(levels[k]==level+3) {
levels[k--]-=2;
}
while(levels[k]==level) {
k--;
}
}
if(levels[k]==level+2) {
levels[k]=level;
continue;
}
levels[k]=level+1;
}
break;
case 14: /* R after L+ON+EN/AN/ON */
level=pLevState->runLevel+1;
for(k=start0-1; k>=pLevState->startON; k--) {
if(levels[k]>level) {
levels[k]-=2;
}
}
break;
default: /* we should never get here */
UPRV_UNREACHABLE_EXIT;
}
}
if((addLevel) || (start < start0)) {
level=pLevState->runLevel + addLevel;
if(start>=pLevState->runStart) {
for(k=start; k<limit; k++) {
levels[k]=level;
}
} else {
setLevelsOutsideIsolates(pBiDi, start, limit, level);
}
}
}
/**
* Returns the directionality of the last strong character at the end of the prologue, if any.
* Requires prologue!=null.
*/
static DirProp
lastL_R_AL(UBiDi *pBiDi) {
const UChar *text=pBiDi->prologue;
int32_t length=pBiDi->proLength;
int32_t i;
UChar32 uchar;
DirProp dirProp;
for(i=length; i>0; ) {
/* i is decremented by U16_PREV */
U16_PREV(text, 0, i, uchar);
dirProp=(DirProp)ubidi_getCustomizedClass(pBiDi, uchar);
if(dirProp==L) {
return DirProp_L;
}
if(dirProp==R || dirProp==AL) {
return DirProp_R;
}
if(dirProp==B) {
return DirProp_ON;
}
}
return DirProp_ON;
}
/**
* Returns the directionality of the first strong character, or digit, in the epilogue, if any.
* Requires epilogue!=null.
*/
static DirProp
firstL_R_AL_EN_AN(UBiDi *pBiDi) {
const UChar *text=pBiDi->epilogue;
int32_t length=pBiDi->epiLength;
int32_t i;
UChar32 uchar;
DirProp dirProp;
for(i=0; i<length; ) {
/* i is incremented by U16_NEXT */
U16_NEXT(text, i, length, uchar);
dirProp=(DirProp)ubidi_getCustomizedClass(pBiDi, uchar);
if(dirProp==L) {
return DirProp_L;
}
if(dirProp==R || dirProp==AL) {
return DirProp_R;
}
if(dirProp==EN) {
return DirProp_EN;
}
if(dirProp==AN) {
return DirProp_AN;
}
}
return DirProp_ON;
}
static void
resolveImplicitLevels(UBiDi *pBiDi,
int32_t start, int32_t limit,
DirProp sor, DirProp eor) {
const DirProp *dirProps=pBiDi->dirProps;
DirProp dirProp;
LevState levState;
int32_t i, start1, start2;
uint16_t oldStateImp, stateImp, actionImp;
uint8_t gprop, resProp, cell;
UBool inverseRTL;
DirProp nextStrongProp=R;
int32_t nextStrongPos=-1;
/* check for RTL inverse BiDi mode */
/* FOOD FOR THOUGHT: in case of RTL inverse BiDi, it would make sense to
* loop on the text characters from end to start.
* This would need a different properties state table (at least different
* actions) and different levels state tables (maybe very similar to the
* LTR corresponding ones.
*/
inverseRTL=(UBool)
((start<pBiDi->lastArabicPos) && (GET_PARALEVEL(pBiDi, start) & 1) &&
(pBiDi->reorderingMode==UBIDI_REORDER_INVERSE_LIKE_DIRECT ||
pBiDi->reorderingMode==UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL));
/* initialize for property and levels state tables */
levState.startL2EN=-1; /* used for INVERSE_LIKE_DIRECT_WITH_MARKS */
levState.lastStrongRTL=-1; /* used for INVERSE_LIKE_DIRECT_WITH_MARKS */
levState.runStart=start;
levState.runLevel=pBiDi->levels[start];
levState.pImpTab=(const ImpTab*)((pBiDi->pImpTabPair)->pImpTab)[levState.runLevel&1];
levState.pImpAct=(const ImpAct*)((pBiDi->pImpTabPair)->pImpAct)[levState.runLevel&1];
if(start==0 && pBiDi->proLength>0) {
DirProp lastStrong=lastL_R_AL(pBiDi);
if(lastStrong!=DirProp_ON) {
sor=lastStrong;
}
}
/* The isolates[] entries contain enough information to
resume the bidi algorithm in the same state as it was
when it was interrupted by an isolate sequence. */
if(dirProps[start]==PDI && pBiDi->isolateCount >= 0) {
levState.startON=pBiDi->isolates[pBiDi->isolateCount].startON;
start1=pBiDi->isolates[pBiDi->isolateCount].start1;
stateImp=pBiDi->isolates[pBiDi->isolateCount].stateImp;
levState.state=pBiDi->isolates[pBiDi->isolateCount].state;
pBiDi->isolateCount--;
} else {
levState.startON=-1;
start1=start;
if(dirProps[start]==NSM)
stateImp = 1 + sor;
else
stateImp=0;
levState.state=0;
processPropertySeq(pBiDi, &levState, sor, start, start);
}
start2=start; /* to make Java compiler happy */
for(i=start; i<=limit; i++) {
if(i>=limit) {
int32_t k;
for(k=limit-1; k>start&&(DIRPROP_FLAG(dirProps[k])&MASK_BN_EXPLICIT); k--);
dirProp=dirProps[k];
if(dirProp==LRI || dirProp==RLI)
break; /* no forced closing for sequence ending with LRI/RLI */
gprop=eor;
} else {
DirProp prop, prop1;
prop=dirProps[i];
if(prop==B) {
pBiDi->isolateCount=-1; /* current isolates stack entry == none */
}
if(inverseRTL) {
if(prop==AL) {
/* AL before EN does not make it AN */
prop=R;
} else if(prop==EN) {
if(nextStrongPos<=i) {
/* look for next strong char (L/R/AL) */
int32_t j;
nextStrongProp=R; /* set default */
nextStrongPos=limit;
for(j=i+1; j<limit; j++) {
prop1=dirProps[j];
if(prop1==L || prop1==R || prop1==AL) {
nextStrongProp=prop1;
nextStrongPos=j;
break;
}
}
}
if(nextStrongProp==AL) {
prop=AN;
}
}
}
gprop=groupProp[prop];
}
oldStateImp=stateImp;
cell=impTabProps[oldStateImp][gprop];
stateImp=GET_STATEPROPS(cell); /* isolate the new state */
actionImp=GET_ACTIONPROPS(cell); /* isolate the action */
if((i==limit) && (actionImp==0)) {
/* there is an unprocessed sequence if its property == eor */
actionImp=1; /* process the last sequence */
}
if(actionImp) {
resProp=impTabProps[oldStateImp][IMPTABPROPS_RES];
switch(actionImp) {
case 1: /* process current seq1, init new seq1 */
processPropertySeq(pBiDi, &levState, resProp, start1, i);
start1=i;
break;
case 2: /* init new seq2 */
start2=i;
break;
case 3: /* process seq1, process seq2, init new seq1 */
processPropertySeq(pBiDi, &levState, resProp, start1, start2);
processPropertySeq(pBiDi, &levState, DirProp_ON, start2, i);
start1=i;
break;
case 4: /* process seq1, set seq1=seq2, init new seq2 */
processPropertySeq(pBiDi, &levState, resProp, start1, start2);
start1=start2;
start2=i;
break;
default: /* we should never get here */
UPRV_UNREACHABLE_EXIT;
}
}
}
/* flush possible pending sequence, e.g. ON */
if(limit==pBiDi->length && pBiDi->epiLength>0) {
DirProp firstStrong=firstL_R_AL_EN_AN(pBiDi);
if(firstStrong!=DirProp_ON) {
eor=firstStrong;
}
}
/* look for the last char not a BN or LRE/RLE/LRO/RLO/PDF */
for(i=limit-1; i>start&&(DIRPROP_FLAG(dirProps[i])&MASK_BN_EXPLICIT); i--);
dirProp=dirProps[i];
if((dirProp==LRI || dirProp==RLI) && limit<pBiDi->length) {
pBiDi->isolateCount++;
pBiDi->isolates[pBiDi->isolateCount].stateImp=stateImp;
pBiDi->isolates[pBiDi->isolateCount].state=levState.state;
pBiDi->isolates[pBiDi->isolateCount].start1=start1;
pBiDi->isolates[pBiDi->isolateCount].startON=levState.startON;
}
else
processPropertySeq(pBiDi, &levState, eor, limit, limit);
}
/* perform (L1) and (X9) ---------------------------------------------------- */
/*
* Reset the embedding levels for some non-graphic characters (L1).
* This function also sets appropriate levels for BN, and
* explicit embedding types that are supposed to have been removed
* from the paragraph in (X9).
*/
static void
adjustWSLevels(UBiDi *pBiDi) {
const DirProp *dirProps=pBiDi->dirProps;
UBiDiLevel *levels=pBiDi->levels;
int32_t i;
if(pBiDi->flags&MASK_WS) {
UBool orderParagraphsLTR=pBiDi->orderParagraphsLTR;
Flags flag;
i=pBiDi->trailingWSStart;
while(i>0) {
/* reset a sequence of WS/BN before eop and B/S to the paragraph paraLevel */
while(i>0 && (flag=DIRPROP_FLAG(dirProps[--i]))&MASK_WS) {
if(orderParagraphsLTR&&(flag&DIRPROP_FLAG(B))) {
levels[i]=0;
} else {
levels[i]=GET_PARALEVEL(pBiDi, i);
}
}
/* reset BN to the next character's paraLevel until B/S, which restarts above loop */
/* here, i+1 is guaranteed to be <length */
while(i>0) {
flag=DIRPROP_FLAG(dirProps[--i]);
if(flag&MASK_BN_EXPLICIT) {
levels[i]=levels[i+1];
} else if(orderParagraphsLTR&&(flag&DIRPROP_FLAG(B))) {
levels[i]=0;
break;
} else if(flag&MASK_B_S) {
levels[i]=GET_PARALEVEL(pBiDi, i);
break;
}
}
}
}
}
U_CAPI void U_EXPORT2
ubidi_setContext(UBiDi *pBiDi,
const UChar *prologue, int32_t proLength,
const UChar *epilogue, int32_t epiLength,
UErrorCode *pErrorCode) {
/* check the argument values */
RETURN_VOID_IF_NULL_OR_FAILING_ERRCODE(pErrorCode);
if(pBiDi==NULL || proLength<-1 || epiLength<-1 ||
(prologue==NULL && proLength!=0) || (epilogue==NULL && epiLength!=0)) {
*pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
return;
}
if(proLength==-1) {
pBiDi->proLength=u_strlen(prologue);
} else {
pBiDi->proLength=proLength;
}
if(epiLength==-1) {
pBiDi->epiLength=u_strlen(epilogue);
} else {
pBiDi->epiLength=epiLength;
}
pBiDi->prologue=prologue;
pBiDi->epilogue=epilogue;
}
static void
setParaSuccess(UBiDi *pBiDi) {
pBiDi->proLength=0; /* forget the last context */
pBiDi->epiLength=0;
pBiDi->pParaBiDi=pBiDi; /* mark successful setPara */
}
#define BIDI_MIN(x, y) ((x)<(y) ? (x) : (y))
#define BIDI_ABS(x) ((x)>=0 ? (x) : (-(x)))
static void
setParaRunsOnly(UBiDi *pBiDi, const UChar *text, int32_t length,
UBiDiLevel paraLevel, UErrorCode *pErrorCode) {
int32_t *runsOnlyMemory = NULL;
int32_t *visualMap;
UChar *visualText;
int32_t saveLength, saveTrailingWSStart;
const UBiDiLevel *levels;
UBiDiLevel *saveLevels;
UBiDiDirection saveDirection;
UBool saveMayAllocateText;
Run *runs;
int32_t visualLength, i, j, visualStart, logicalStart,
runCount, runLength, addedRuns, insertRemove,
start, limit, step, indexOddBit, logicalPos,
index0, index1;
uint32_t saveOptions;
pBiDi->reorderingMode=UBIDI_REORDER_DEFAULT;
if(length==0) {
ubidi_setPara(pBiDi, text, length, paraLevel, NULL, pErrorCode);
goto cleanup3;
}
/* obtain memory for mapping table and visual text */
runsOnlyMemory=static_cast<int32_t *>(uprv_malloc(length*(sizeof(int32_t)+sizeof(UChar)+sizeof(UBiDiLevel))));
if(runsOnlyMemory==NULL) {
*pErrorCode=U_MEMORY_ALLOCATION_ERROR;
goto cleanup3;
}
visualMap=runsOnlyMemory;
visualText=(UChar *)&visualMap[length];
saveLevels=(UBiDiLevel *)&visualText[length];
saveOptions=pBiDi->reorderingOptions;
if(saveOptions & UBIDI_OPTION_INSERT_MARKS) {
pBiDi->reorderingOptions&=~UBIDI_OPTION_INSERT_MARKS;
pBiDi->reorderingOptions|=UBIDI_OPTION_REMOVE_CONTROLS;
}
paraLevel&=1; /* accept only 0 or 1 */
ubidi_setPara(pBiDi, text, length, paraLevel, NULL, pErrorCode);
if(U_FAILURE(*pErrorCode)) {
goto cleanup3;
}
/* we cannot access directly pBiDi->levels since it is not yet set if
* direction is not MIXED
*/
levels=ubidi_getLevels(pBiDi, pErrorCode);
uprv_memcpy(saveLevels, levels, (size_t)pBiDi->length*sizeof(UBiDiLevel));
saveTrailingWSStart=pBiDi->trailingWSStart;
saveLength=pBiDi->length;
saveDirection=pBiDi->direction;
/* FOOD FOR THOUGHT: instead of writing the visual text, we could use
* the visual map and the dirProps array to drive the second call
* to ubidi_setPara (but must make provision for possible removal of
* BiDi controls. Alternatively, only use the dirProps array via
* customized classifier callback.
*/
visualLength=ubidi_writeReordered(pBiDi, visualText, length,
UBIDI_DO_MIRRORING, pErrorCode);
ubidi_getVisualMap(pBiDi, visualMap, pErrorCode);
if(U_FAILURE(*pErrorCode)) {
goto cleanup2;
}
pBiDi->reorderingOptions=saveOptions;
pBiDi->reorderingMode=UBIDI_REORDER_INVERSE_LIKE_DIRECT;
paraLevel^=1;
/* Because what we did with reorderingOptions, visualText may be shorter
* than the original text. But we don't want the levels memory to be
* reallocated shorter than the original length, since we need to restore
* the levels as after the first call to ubidi_setpara() before returning.
* We will force mayAllocateText to false before the second call to
* ubidi_setpara(), and will restore it afterwards.
*/
saveMayAllocateText=pBiDi->mayAllocateText;
pBiDi->mayAllocateText=false;
ubidi_setPara(pBiDi, visualText, visualLength, paraLevel, NULL, pErrorCode);
pBiDi->mayAllocateText=saveMayAllocateText;
ubidi_getRuns(pBiDi, pErrorCode);
if(U_FAILURE(*pErrorCode)) {
goto cleanup1;
}
/* check if some runs must be split, count how many splits */
addedRuns=0;
runCount=pBiDi->runCount;
runs=pBiDi->runs;
visualStart=0;
for(i=0; i<runCount; i++, visualStart+=runLength) {
runLength=runs[i].visualLimit-visualStart;
if(runLength<2) {
continue;
}
logicalStart=GET_INDEX(runs[i].logicalStart);
for(j=logicalStart+1; j<logicalStart+runLength; j++) {
index0=visualMap[j];
index1=visualMap[j-1];
if((BIDI_ABS(index0-index1)!=1) || (saveLevels[index0]!=saveLevels[index1])) {
addedRuns++;
}
}
}
if(addedRuns) {
if(getRunsMemory(pBiDi, runCount+addedRuns)) {
if(runCount==1) {
/* because we switch from UBiDi.simpleRuns to UBiDi.runs */
pBiDi->runsMemory[0]=runs[0];
}
runs=pBiDi->runs=pBiDi->runsMemory;
pBiDi->runCount+=addedRuns;
} else {
goto cleanup1;
}
}
/* split runs which are not consecutive in source text */
for(i=runCount-1; i>=0; i--) {
runLength= i==0 ? runs[0].visualLimit :
runs[i].visualLimit-runs[i-1].visualLimit;
logicalStart=runs[i].logicalStart;
indexOddBit=GET_ODD_BIT(logicalStart);
logicalStart=GET_INDEX(logicalStart);
if(runLength<2) {
if(addedRuns) {
runs[i+addedRuns]=runs[i];
}
logicalPos=visualMap[logicalStart];
runs[i+addedRuns].logicalStart=MAKE_INDEX_ODD_PAIR(logicalPos,
saveLevels[logicalPos]^indexOddBit);
continue;
}
if(indexOddBit) {
start=logicalStart;
limit=logicalStart+runLength-1;
step=1;
} else {
start=logicalStart+runLength-1;
limit=logicalStart;
step=-1;
}
for(j=start; j!=limit; j+=step) {
index0=visualMap[j];
index1=visualMap[j+step];
if((BIDI_ABS(index0-index1)!=1) || (saveLevels[index0]!=saveLevels[index1])) {
logicalPos=BIDI_MIN(visualMap[start], index0);
runs[i+addedRuns].logicalStart=MAKE_INDEX_ODD_PAIR(logicalPos,
saveLevels[logicalPos]^indexOddBit);
runs[i+addedRuns].visualLimit=runs[i].visualLimit;
runs[i].visualLimit-=BIDI_ABS(j-start)+1;
insertRemove=runs[i].insertRemove&(LRM_AFTER|RLM_AFTER);
runs[i+addedRuns].insertRemove=insertRemove;
runs[i].insertRemove&=~insertRemove;
start=j+step;
addedRuns--;
}
}
if(addedRuns) {
runs[i+addedRuns]=runs[i];
}
logicalPos=BIDI_MIN(visualMap[start], visualMap[limit]);
runs[i+addedRuns].logicalStart=MAKE_INDEX_ODD_PAIR(logicalPos,
saveLevels[logicalPos]^indexOddBit);
}
cleanup1:
/* restore initial paraLevel */
pBiDi->paraLevel^=1;
cleanup2:
/* restore real text */
pBiDi->text=text;
pBiDi->length=saveLength;
pBiDi->originalLength=length;
pBiDi->direction=saveDirection;
/* the saved levels should never excess levelsSize, but we check anyway */
if(saveLength>pBiDi->levelsSize) {
saveLength=pBiDi->levelsSize;
}
uprv_memcpy(pBiDi->levels, saveLevels, (size_t)saveLength*sizeof(UBiDiLevel));
pBiDi->trailingWSStart=saveTrailingWSStart;
if(pBiDi->runCount>1) {
pBiDi->direction=UBIDI_MIXED;
}
cleanup3:
/* free memory for mapping table and visual text */
uprv_free(runsOnlyMemory);
pBiDi->reorderingMode=UBIDI_REORDER_RUNS_ONLY;
}
/* ubidi_setPara ------------------------------------------------------------ */
U_CAPI void U_EXPORT2
ubidi_setPara(UBiDi *pBiDi, const UChar *text, int32_t length,
UBiDiLevel paraLevel, UBiDiLevel *embeddingLevels,
UErrorCode *pErrorCode) {
UBiDiDirection direction;
DirProp *dirProps;
/* check the argument values */
RETURN_VOID_IF_NULL_OR_FAILING_ERRCODE(pErrorCode);
if(pBiDi==NULL || text==NULL || length<-1 ||
(paraLevel>UBIDI_MAX_EXPLICIT_LEVEL && paraLevel<UBIDI_DEFAULT_LTR)) {
*pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
return;
}
if(length==-1) {
length=u_strlen(text);
}
/* special treatment for RUNS_ONLY mode */
if(pBiDi->reorderingMode==UBIDI_REORDER_RUNS_ONLY) {
setParaRunsOnly(pBiDi, text, length, paraLevel, pErrorCode);
return;
}
/* initialize the UBiDi structure */
pBiDi->pParaBiDi=NULL; /* mark unfinished setPara */
pBiDi->text=text;
pBiDi->length=pBiDi->originalLength=pBiDi->resultLength=length;
pBiDi->paraLevel=paraLevel;
pBiDi->direction=(UBiDiDirection)(paraLevel&1);
pBiDi->paraCount=1;
pBiDi->dirProps=NULL;
pBiDi->levels=NULL;
pBiDi->runs=NULL;
pBiDi->insertPoints.size=0; /* clean up from last call */
pBiDi->insertPoints.confirmed=0; /* clean up from last call */
/*
* Save the original paraLevel if contextual; otherwise, set to 0.
*/
pBiDi->defaultParaLevel=IS_DEFAULT_LEVEL(paraLevel);
if(length==0) {
/*
* For an empty paragraph, create a UBiDi object with the paraLevel and
* the flags and the direction set but without allocating zero-length arrays.
* There is nothing more to do.
*/
if(IS_DEFAULT_LEVEL(paraLevel)) {
pBiDi->paraLevel&=1;
pBiDi->defaultParaLevel=0;
}
pBiDi->flags=DIRPROP_FLAG_LR(paraLevel);
pBiDi->runCount=0;
pBiDi->paraCount=0;
setParaSuccess(pBiDi); /* mark successful setPara */
return;
}
pBiDi->runCount=-1;
/* allocate paras memory */
if(pBiDi->parasMemory)
pBiDi->paras=pBiDi->parasMemory;
else
pBiDi->paras=pBiDi->simpleParas;
/*
* Get the directional properties,
* the flags bit-set, and
* determine the paragraph level if necessary.
*/
if(getDirPropsMemory(pBiDi, length)) {
pBiDi->dirProps=pBiDi->dirPropsMemory;
if(!getDirProps(pBiDi)) {
*pErrorCode=U_MEMORY_ALLOCATION_ERROR;
return;
}
} else {
*pErrorCode=U_MEMORY_ALLOCATION_ERROR;
return;
}
dirProps=pBiDi->dirProps;
/* the processed length may have changed if UBIDI_OPTION_STREAMING */
length= pBiDi->length;
pBiDi->trailingWSStart=length; /* the levels[] will reflect the WS run */
/* are explicit levels specified? */
if(embeddingLevels==NULL) {
/* no: determine explicit levels according to the (Xn) rules */\
if(getLevelsMemory(pBiDi, length)) {
pBiDi->levels=pBiDi->levelsMemory;
direction=resolveExplicitLevels(pBiDi, pErrorCode);
if(U_FAILURE(*pErrorCode)) {
return;
}
} else {
*pErrorCode=U_MEMORY_ALLOCATION_ERROR;
return;
}
} else {
/* set BN for all explicit codes, check that all levels are 0 or paraLevel..UBIDI_MAX_EXPLICIT_LEVEL */
pBiDi->levels=embeddingLevels;
direction=checkExplicitLevels(pBiDi, pErrorCode);
if(U_FAILURE(*pErrorCode)) {
return;
}
}
/* allocate isolate memory */
if(pBiDi->isolateCount<=SIMPLE_ISOLATES_COUNT)
pBiDi->isolates=pBiDi->simpleIsolates;
else
if((int32_t)(pBiDi->isolateCount*sizeof(Isolate))<=pBiDi->isolatesSize)
pBiDi->isolates=pBiDi->isolatesMemory;
else {
if(getInitialIsolatesMemory(pBiDi, pBiDi->isolateCount)) {
pBiDi->isolates=pBiDi->isolatesMemory;
} else {
*pErrorCode=U_MEMORY_ALLOCATION_ERROR;
return;
}
}
pBiDi->isolateCount=-1; /* current isolates stack entry == none */
/*
* The steps after (X9) in the UBiDi algorithm are performed only if
* the paragraph text has mixed directionality!
*/
pBiDi->direction=direction;
switch(direction) {
case UBIDI_LTR:
/* all levels are implicitly at paraLevel (important for ubidi_getLevels()) */
pBiDi->trailingWSStart=0;
break;
case UBIDI_RTL:
/* all levels are implicitly at paraLevel (important for ubidi_getLevels()) */
pBiDi->trailingWSStart=0;
break;
default:
/*
* Choose the right implicit state table
*/
switch(pBiDi->reorderingMode) {
case UBIDI_REORDER_DEFAULT:
pBiDi->pImpTabPair=&impTab_DEFAULT;
break;
case UBIDI_REORDER_NUMBERS_SPECIAL:
pBiDi->pImpTabPair=&impTab_NUMBERS_SPECIAL;
break;
case UBIDI_REORDER_GROUP_NUMBERS_WITH_R:
pBiDi->pImpTabPair=&impTab_GROUP_NUMBERS_WITH_R;
break;
case UBIDI_REORDER_INVERSE_NUMBERS_AS_L:
pBiDi->pImpTabPair=&impTab_INVERSE_NUMBERS_AS_L;
break;
case UBIDI_REORDER_INVERSE_LIKE_DIRECT:
if (pBiDi->reorderingOptions & UBIDI_OPTION_INSERT_MARKS) {
pBiDi->pImpTabPair=&impTab_INVERSE_LIKE_DIRECT_WITH_MARKS;
} else {
pBiDi->pImpTabPair=&impTab_INVERSE_LIKE_DIRECT;
}
break;
case UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL:
if (pBiDi->reorderingOptions & UBIDI_OPTION_INSERT_MARKS) {
pBiDi->pImpTabPair=&impTab_INVERSE_FOR_NUMBERS_SPECIAL_WITH_MARKS;
} else {
pBiDi->pImpTabPair=&impTab_INVERSE_FOR_NUMBERS_SPECIAL;
}
break;
default:
/* we should never get here */
UPRV_UNREACHABLE_EXIT;
}
/*
* If there are no external levels specified and there
* are no significant explicit level codes in the text,
* then we can treat the entire paragraph as one run.
* Otherwise, we need to perform the following rules on runs of
* the text with the same embedding levels. (X10)
* "Significant" explicit level codes are ones that actually
* affect non-BN characters.
* Examples for "insignificant" ones are empty embeddings
* LRE-PDF, LRE-RLE-PDF-PDF, etc.
*/
if(embeddingLevels==NULL && pBiDi->paraCount<=1 &&
!(pBiDi->flags&DIRPROP_FLAG_MULTI_RUNS)) {
resolveImplicitLevels(pBiDi, 0, length,
GET_LR_FROM_LEVEL(GET_PARALEVEL(pBiDi, 0)),
GET_LR_FROM_LEVEL(GET_PARALEVEL(pBiDi, length-1)));
} else {
/* sor, eor: start and end types of same-level-run */
UBiDiLevel *levels=pBiDi->levels;
int32_t start, limit=0;
UBiDiLevel level, nextLevel;
DirProp sor, eor;
/* determine the first sor and set eor to it because of the loop body (sor=eor there) */
level=GET_PARALEVEL(pBiDi, 0);
nextLevel=levels[0];
if(level<nextLevel) {
eor=GET_LR_FROM_LEVEL(nextLevel);
} else {
eor=GET_LR_FROM_LEVEL(level);
}
do {
/* determine start and limit of the run (end points just behind the run) */
/* the values for this run's start are the same as for the previous run's end */
start=limit;
level=nextLevel;
if((start>0) && (dirProps[start-1]==B)) {
/* except if this is a new paragraph, then set sor = para level */
sor=GET_LR_FROM_LEVEL(GET_PARALEVEL(pBiDi, start));
} else {
sor=eor;
}
/* search for the limit of this run */
while((++limit<length) &&
((levels[limit]==level) ||
(DIRPROP_FLAG(dirProps[limit])&MASK_BN_EXPLICIT))) {}
/* get the correct level of the next run */
if(limit<length) {
nextLevel=levels[limit];
} else {
nextLevel=GET_PARALEVEL(pBiDi, length-1);
}
/* determine eor from max(level, nextLevel); sor is last run's eor */
if(NO_OVERRIDE(level)<NO_OVERRIDE(nextLevel)) {
eor=GET_LR_FROM_LEVEL(nextLevel);
} else {
eor=GET_LR_FROM_LEVEL(level);
}
/* if the run consists of overridden directional types, then there
are no implicit types to be resolved */
if(!(level&UBIDI_LEVEL_OVERRIDE)) {
resolveImplicitLevels(pBiDi, start, limit, sor, eor);
} else {
/* remove the UBIDI_LEVEL_OVERRIDE flags */
do {
levels[start++]&=~UBIDI_LEVEL_OVERRIDE;
} while(start<limit);
}
} while(limit<length);
}
/* check if we got any memory shortage while adding insert points */
if (U_FAILURE(pBiDi->insertPoints.errorCode))
{
*pErrorCode=pBiDi->insertPoints.errorCode;
return;
}
/* reset the embedding levels for some non-graphic characters (L1), (X9) */
adjustWSLevels(pBiDi);
break;
}
/* add RLM for inverse Bidi with contextual orientation resolving
* to RTL which would not round-trip otherwise
*/
if((pBiDi->defaultParaLevel>0) &&
(pBiDi->reorderingOptions & UBIDI_OPTION_INSERT_MARKS) &&
((pBiDi->reorderingMode==UBIDI_REORDER_INVERSE_LIKE_DIRECT) ||
(pBiDi->reorderingMode==UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL))) {
int32_t i, j, start, last;
UBiDiLevel level;
DirProp dirProp;
for(i=0; i<pBiDi->paraCount; i++) {
last=(pBiDi->paras[i].limit)-1;
level= static_cast<UBiDiLevel>(pBiDi->paras[i].level);
if(level==0)
continue; /* LTR paragraph */
start= i==0 ? 0 : pBiDi->paras[i-1].limit;
for(j=last; j>=start; j--) {
dirProp=dirProps[j];
if(dirProp==L) {
if(j<last) {
while(dirProps[last]==B) {
last--;
}
}
addPoint(pBiDi, last, RLM_BEFORE);
break;
}
if(DIRPROP_FLAG(dirProp) & MASK_R_AL) {
break;
}
}
}
}
if(pBiDi->reorderingOptions & UBIDI_OPTION_REMOVE_CONTROLS) {
pBiDi->resultLength -= pBiDi->controlCount;
} else {
pBiDi->resultLength += pBiDi->insertPoints.size;
}
setParaSuccess(pBiDi); /* mark successful setPara */
}
U_CAPI void U_EXPORT2
ubidi_orderParagraphsLTR(UBiDi *pBiDi, UBool orderParagraphsLTR) {
if(pBiDi!=NULL) {
pBiDi->orderParagraphsLTR=orderParagraphsLTR;
}
}
U_CAPI UBool U_EXPORT2
ubidi_isOrderParagraphsLTR(UBiDi *pBiDi) {
if(pBiDi!=NULL) {
return pBiDi->orderParagraphsLTR;
} else {
return false;
}
}
U_CAPI UBiDiDirection U_EXPORT2
ubidi_getDirection(const UBiDi *pBiDi) {
if(IS_VALID_PARA_OR_LINE(pBiDi)) {
return pBiDi->direction;
} else {
return UBIDI_LTR;
}
}
U_CAPI const UChar * U_EXPORT2
ubidi_getText(const UBiDi *pBiDi) {
if(IS_VALID_PARA_OR_LINE(pBiDi)) {
return pBiDi->text;
} else {
return NULL;
}
}
U_CAPI int32_t U_EXPORT2
ubidi_getLength(const UBiDi *pBiDi) {
if(IS_VALID_PARA_OR_LINE(pBiDi)) {
return pBiDi->originalLength;
} else {
return 0;
}
}
U_CAPI int32_t U_EXPORT2
ubidi_getProcessedLength(const UBiDi *pBiDi) {
if(IS_VALID_PARA_OR_LINE(pBiDi)) {
return pBiDi->length;
} else {
return 0;
}
}
U_CAPI int32_t U_EXPORT2
ubidi_getResultLength(const UBiDi *pBiDi) {
if(IS_VALID_PARA_OR_LINE(pBiDi)) {
return pBiDi->resultLength;
} else {
return 0;
}
}
/* paragraphs API functions ------------------------------------------------- */
U_CAPI UBiDiLevel U_EXPORT2
ubidi_getParaLevel(const UBiDi *pBiDi) {
if(IS_VALID_PARA_OR_LINE(pBiDi)) {
return pBiDi->paraLevel;
} else {
return 0;
}
}
U_CAPI int32_t U_EXPORT2
ubidi_countParagraphs(UBiDi *pBiDi) {
if(!IS_VALID_PARA_OR_LINE(pBiDi)) {
return 0;
} else {
return pBiDi->paraCount;
}
}
U_CAPI void U_EXPORT2
ubidi_getParagraphByIndex(const UBiDi *pBiDi, int32_t paraIndex,
int32_t *pParaStart, int32_t *pParaLimit,
UBiDiLevel *pParaLevel, UErrorCode *pErrorCode) {
int32_t paraStart;
/* check the argument values */
RETURN_VOID_IF_NULL_OR_FAILING_ERRCODE(pErrorCode);
RETURN_VOID_IF_NOT_VALID_PARA_OR_LINE(pBiDi, *pErrorCode);
RETURN_VOID_IF_BAD_RANGE(paraIndex, 0, pBiDi->paraCount, *pErrorCode);
pBiDi=pBiDi->pParaBiDi; /* get Para object if Line object */
if(paraIndex) {
paraStart=pBiDi->paras[paraIndex-1].limit;
} else {
paraStart=0;
}
if(pParaStart!=NULL) {
*pParaStart=paraStart;
}
if(pParaLimit!=NULL) {
*pParaLimit=pBiDi->paras[paraIndex].limit;
}
if(pParaLevel!=NULL) {
*pParaLevel=GET_PARALEVEL(pBiDi, paraStart);
}
}
U_CAPI int32_t U_EXPORT2
ubidi_getParagraph(const UBiDi *pBiDi, int32_t charIndex,
int32_t *pParaStart, int32_t *pParaLimit,
UBiDiLevel *pParaLevel, UErrorCode *pErrorCode) {
int32_t paraIndex;
/* check the argument values */
/* pErrorCode will be checked by the call to ubidi_getParagraphByIndex */
RETURN_IF_NULL_OR_FAILING_ERRCODE(pErrorCode, -1);
RETURN_IF_NOT_VALID_PARA_OR_LINE(pBiDi, *pErrorCode, -1);
pBiDi=pBiDi->pParaBiDi; /* get Para object if Line object */
RETURN_IF_BAD_RANGE(charIndex, 0, pBiDi->length, *pErrorCode, -1);
for(paraIndex=0; charIndex>=pBiDi->paras[paraIndex].limit; paraIndex++);
ubidi_getParagraphByIndex(pBiDi, paraIndex, pParaStart, pParaLimit, pParaLevel, pErrorCode);
return paraIndex;
}
U_CAPI void U_EXPORT2
ubidi_setClassCallback(UBiDi *pBiDi, UBiDiClassCallback *newFn,
const void *newContext, UBiDiClassCallback **oldFn,
const void **oldContext, UErrorCode *pErrorCode)
{
RETURN_VOID_IF_NULL_OR_FAILING_ERRCODE(pErrorCode);
if(pBiDi==NULL) {
*pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
return;
}
if( oldFn )
{
*oldFn = pBiDi->fnClassCallback;
}
if( oldContext )
{
*oldContext = pBiDi->coClassCallback;
}
pBiDi->fnClassCallback = newFn;
pBiDi->coClassCallback = newContext;
}
U_CAPI void U_EXPORT2
ubidi_getClassCallback(UBiDi *pBiDi, UBiDiClassCallback **fn, const void **context)
{
if(pBiDi==NULL) {
return;
}
if( fn )
{
*fn = pBiDi->fnClassCallback;
}
if( context )
{
*context = pBiDi->coClassCallback;
}
}
U_CAPI UCharDirection U_EXPORT2
ubidi_getCustomizedClass(UBiDi *pBiDi, UChar32 c)
{
UCharDirection dir;
if( pBiDi->fnClassCallback == NULL ||
(dir = (*pBiDi->fnClassCallback)(pBiDi->coClassCallback, c)) == U_BIDI_CLASS_DEFAULT )
{
dir = ubidi_getClass(c);
}
if(dir >= U_CHAR_DIRECTION_COUNT) {
dir = (UCharDirection)ON;
}
return dir;
}
| [
"jengelh@inai.de"
] | jengelh@inai.de |
a6bec2512113c8fb1389d50f81b91f9f45565b0d | 40a00025fdb79a9c4c0f608cdf385dcef7ed1445 | /arduino-prototype/libraries/ArduCAM/ArduCAM.h | 5d697cf4a2a0c8c13f5c15430491c27c490ed946 | [] | no_license | ideapod/nanosat-revolution | a85267d4829202dca86fc349ef6db935c032bffd | d94c0b994a573e65b4d4d1ad665973f88a1245be | refs/heads/master | 2021-01-10T09:42:01.690560 | 2017-05-13T22:09:06 | 2017-05-13T22:09:21 | 45,902,103 | 4 | 1 | null | 2017-02-16T12:26:26 | 2015-11-10T09:38:54 | C++ | UTF-8 | C++ | false | false | 12,960 | h | /*
ArduCAM.h - Arduino library support for CMOS Image Sensor
Copyright (C)2011-2015 ArduCAM.com. All right reserved
Basic functionality of this library are based on the demo-code provided by
ArduCAM.com. You can find the latest version of the library at
http://www.ArduCAM.com
Now supported controllers:
- OV7670
- MT9D111
- OV7675
- OV2640
- OV3640
- OV5642
- OV7660
- OV7725
- MT9M112
- MT9V111
- OV5640
- MT9M001
- MT9T112
- MT9D112
We will add support for many other sensors in next release.
Supported MCU platform
- Theoretically support all Arduino families
- Arduino UNO R3 (Tested)
- Arduino MEGA2560 R3 (Tested)
- Arduino Leonardo R3 (Tested)
- Arduino Nano (Tested)
- Arduino DUE (Tested)
- Arduino Yun (Tested)
- Raspberry Pi (Tested)
- ESP8266-12 (Tested)
If you make any modifications or improvements to the code, I would appreciate
that you share the code with me so that I might include it in the next release.
I can be contacted through http://www.ArduCAM.com
This library 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.
This library 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 this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*------------------------------------
Revision History:
2012/09/20 V1.0.0 by Lee first release
2012/10/23 V1.0.1 by Lee Resolved some timing issue for the Read/Write Register
2012/11/29 V1.1.0 by Lee Add support for MT9D111 sensor
2012/12/13 V1.2.0 by Lee Add support for OV7675 sensor
2012/12/28 V1.3.0 by Lee Add support for OV2640,OV3640,OV5642 sensors
2013/02/26 V2.0.0 by Lee New Rev.B shield hardware, add support for FIFO control
and support Mega1280/2560 boards
2013/05/28 V2.1.0 by Lee Add support all drawing functions derived from UTFT library
2013/08/24 V3.0.0 by Lee Support ArudCAM shield Rev.C hardware, features SPI interface and low power mode.
Support almost all series of Arduino boards including DUE.
2014/03/09 V3.1.0 by Lee Add the more impressive example sketches.
Optimise the OV5642 settings, improve image quality.
Add live preview before JPEG capture.
Add play back photos one by one after BMP capture.
2014/05/01 V3.1.1 by Lee Minor changes to add support Arduino IDE for linux distributions.
2014/09/30 V3.2.0 by Lee Improvement on OV5642 camera dirver.
2014/10/06 V3.3.0 by Lee Add OV7660,OV7725 camera support.
2015/02/27 V3.4.0 by Lee Add the support for Arduino Yun board, update the latest UTFT library for ArduCAM.
2015/06/09 V3.4.1 by Lee Minor changes and add some comments
2015/06/19 V3.4.2 by Lee Add support for MT9M112 camera.
2015/06/20 V3.4.3 by Lee Add support for MT9V111 camera.
2015/06/22 V3.4.4 by Lee Add support for OV5640 camera.
2015/06/22 V3.4.5 by Lee Add support for MT9M001 camera.
2015/08/05 V3.4.6 by Lee Add support for MT9T112 camera.
2015/08/08 V3.4.7 by Lee Add support for MT9D112 camera.
2015/09/20 V3.4.8 by Lee Add support for ESP8266 processor.
2016/02/03 V3.4.9 by Lee Add support for Arduino ZERO board.
2016/06/07 V3.5.0 by Lee Add support for OV5642_CAM_BIT_ROTATION_FIXED.
2016/06/14 V3.5.1 by Lee Add support for ArduCAM-Mini-5MP-Plus OV5640_CAM.
--------------------------------------*/
#ifndef ArduCAM_H
#define ArduCAM_H
#include "Arduino.h"
#include <pins_arduino.h>
#if defined (__AVR__)
#define cbi(reg, bitmask) *reg &= ~bitmask
#define sbi(reg, bitmask) *reg |= bitmask
#define pulse_high(reg, bitmask) sbi(reg, bitmask); cbi(reg, bitmask);
#define pulse_low(reg, bitmask) cbi(reg, bitmask); sbi(reg, bitmask);
#define cport(port, data) port &= data
#define sport(port, data) port |= data
#define swap(type, i, j) {type t = i; i = j; j = t;}
#define fontbyte(x) pgm_read_byte(&cfont.font[x])
#define regtype volatile uint8_t
#define regsize uint8_t
#endif
#if defined(__arm__)
#define cbi(reg, bitmask) *reg &= ~bitmask
#define sbi(reg, bitmask) *reg |= bitmask
#define pulse_high(reg, bitmask) sbi(reg, bitmask); cbi(reg, bitmask);
#define pulse_low(reg, bitmask) cbi(reg, bitmask); sbi(reg, bitmask);
#define cport(port, data) port &= data
#define sport(port, data) port |= data
#define swap(type, i, j) {type t = i; i = j; j = t;}
#define fontbyte(x) cfont.font[x]
#define regtype volatile uint32_t
#define regsize uint32_t
#define PROGMEM
#define pgm_read_byte(x) (*((char *)x))
// #define pgm_read_word(x) (*((short *)(x & 0xfffffffe)))
#define pgm_read_word(x) ( ((*((unsigned char *)x + 1)) << 8) + (*((unsigned char *)x)))
#define pgm_read_byte_near(x) (*((char *)x))
#define pgm_read_byte_far(x) (*((char *)x))
// #define pgm_read_word_near(x) (*((short *)(x & 0xfffffffe))
// #define pgm_read_word_far(x) (*((short *)(x & 0xfffffffe)))
#define pgm_read_word_near(x) ( ((*((unsigned char *)x + 1)) << 8) + (*((unsigned char *)x)))
#define pgm_read_word_far(x) ( ((*((unsigned char *)x + 1)) << 8) + (*((unsigned char *)x))))
#define PSTR(x) x
#if defined F
#undef F
#endif
#define F(X) (X)
#endif
#if defined(ESP8266)
#define cbi(reg, bitmask) digitalWrite(bitmask, LOW)
#define sbi(reg, bitmask) digitalWrite(bitmask, HIGH)
#define pulse_high(reg, bitmask) sbi(reg, bitmask); cbi(reg, bitmask);
#define pulse_low(reg, bitmask) cbi(reg, bitmask); sbi(reg, bitmask);
#define cport(port, data) port &= data
#define sport(port, data) port |= data
#define swap(type, i, j) {type t = i; i = j; j = t;}
#define fontbyte(x) cfont.font[x]
#define regtype volatile uint32_t
#define regsize uint32_t
#endif
/****************************************************/
/* Sensor related definition */
/****************************************************/
#define BMP 0
#define JPEG 1
#define OV7670 0
#define MT9D111_A 1
#define OV7675 2
#define OV5642 3
#define OV3640 4
#define OV2640 5
#define OV9655 6
#define MT9M112 7
#define OV7725 8
#define OV7660 9
#define MT9M001 10
#define OV5640 11
#define MT9D111_B 12
#define OV9650 13
#define MT9V111 14
#define MT9T112 15
#define MT9D112 16
#define OV2640_160x120 0 //160x120
#define OV2640_176x144 1 //176x144
#define OV2640_320x240 2 //320x240
#define OV2640_352x288 3 //352x288
#define OV2640_640x480 4 //640x480
#define OV2640_800x600 5 //800x600
#define OV2640_1024x768 6 //1024x768
#define OV2640_1280x1024 7 //1280x1024
#define OV2640_1600x1200 8 //1600x1200
#define OV5642_320x240 0 //320x240
#define OV5642_640x480 1 //640x480
#define OV5642_1280x720 2 //1280x720
#define OV5642_1920x1080 3 //1920x1080
#define OV5642_2048x1563 4 //2048x1563
#define OV5642_2592x1944 5 //2592x1944
#define OV5640_320x240 0 //320x240
#define OV5640_352x288 1 //352x288
#define OV5640_640x480 2 //640x480
#define OV5640_800x480 3 //800x480
#define OV5640_1024x768 4 //1024x768
#define OV5640_1280x960 5 //1280x960
#define OV5640_1600x1200 6 //1600x1200
#define OV5640_2048x1536 7 //2048x1536
#define OV5640_2592x1944 8 //2592x1944
/****************************************************/
/* I2C Control Definition */
/****************************************************/
#define I2C_ADDR_8BIT 0
#define I2C_ADDR_16BIT 1
#define I2C_REG_8BIT 0
#define I2C_REG_16BIT 1
#define I2C_DAT_8BIT 0
#define I2C_DAT_16BIT 1
/* Register initialization tables for SENSORs */
/* Terminating list entry for reg */
#define SENSOR_REG_TERM_8BIT 0xFF
#define SENSOR_REG_TERM_16BIT 0xFFFF
/* Terminating list entry for val */
#define SENSOR_VAL_TERM_8BIT 0xFF
#define SENSOR_VAL_TERM_16BIT 0xFFFF
/****************************************************/
/* ArduChip related definition */
/****************************************************/
#define RWBIT 0x80 //READ AND WRITE BIT IS BIT[7]
#define ARDUCHIP_TEST1 0x00 //TEST register
#define ARDUCHIP_TEST2 0x01 //TEST register
#define ARDUCHIP_FRAMES 0x01 //Bit[2:0]Number of frames to be captured
#define ARDUCHIP_MODE 0x02 //Mode register
#define MCU2LCD_MODE 0x00
#define CAM2LCD_MODE 0x01
#define LCD2MCU_MODE 0x02
#define ARDUCHIP_TIM 0x03 //Timming control
#define HREF_LEVEL_MASK 0x01 //0 = High active , 1 = Low active
#define VSYNC_LEVEL_MASK 0x02 //0 = High active , 1 = Low active
#define LCD_BKEN_MASK 0x04 //0 = Enable, 1 = Disable
#define DELAY_MASK 0x08 //0 = no delay, 1 = delay one clock
#define MODE_MASK 0x10 //0 = LCD mode, 1 = FIFO mode
#define FIFO_PWRDN_MASK 0x20 //0 = Normal operation, 1 = FIFO power down
#define LOW_POWER_MODE 0x40 //0 = Normal mode, 1 = Low power mode
#define ARDUCHIP_FIFO 0x04 //FIFO and I2C control
#define FIFO_CLEAR_MASK 0x01
#define FIFO_START_MASK 0x02
#define FIFO_RDPTR_RST_MASK 0x10
#define FIFO_WRPTR_RST_MASK 0x20
#define ARDUCHIP_GPIO 0x06 //GPIO Write Register
#define GPIO_RESET_MASK 0x01 //0 = default state, 1 = Sensor reset IO value
#define GPIO_PWDN_MASK 0x02 //0 = Sensor power down IO value, 1 = Sensor power enable IO value
#define BURST_FIFO_READ 0x3C //Burst FIFO read operation
#define SINGLE_FIFO_READ 0x3D //Single FIFO read operation
#define ARDUCHIP_REV 0x40 //ArduCHIP revision
#define VER_LOW_MASK 0x3F
#define VER_HIGH_MASK 0xC0
#define ARDUCHIP_TRIG 0x41 //Trigger source
#define VSYNC_MASK 0x01
#define SHUTTER_MASK 0x02
#define CAP_DONE_MASK 0x08
#define FIFO_SIZE1 0x42 //Camera write FIFO size[7:0] for burst to read
#define FIFO_SIZE2 0x43 //Camera write FIFO size[15:8]
#define FIFO_SIZE3 0x44 //Camera write FIFO size[18:16]
/****************************************************/
/****************************************************************/
/* define a structure for sensor register initialization values */
/****************************************************************/
struct sensor_reg {
uint16_t reg;
uint16_t val;
};
class ArduCAM
{
public:
ArduCAM();
ArduCAM(byte model,int CS);
void InitCAM();
void CS_HIGH(void);
void CS_LOW(void);
void flush_fifo(void);
void start_capture(void);
void clear_fifo_flag(void);
uint8_t read_fifo(void);
uint8_t read_reg(uint8_t addr);
void write_reg(uint8_t addr, uint8_t data);
uint32_t read_fifo_length(void);
void set_fifo_burst(void);
void set_bit(uint8_t addr, uint8_t bit);
void clear_bit(uint8_t addr, uint8_t bit);
uint8_t get_bit(uint8_t addr, uint8_t bit);
void set_mode(uint8_t mode);
int wrSensorRegs(const struct sensor_reg*);
int wrSensorRegs8_8(const struct sensor_reg*);
int wrSensorRegs8_16(const struct sensor_reg*);
int wrSensorRegs16_8(const struct sensor_reg*);
int wrSensorRegs16_16(const struct sensor_reg*);
byte wrSensorReg(int regID, int regDat);
byte wrSensorReg8_8(int regID, int regDat);
byte wrSensorReg8_16(int regID, int regDat);
byte wrSensorReg16_8(int regID, int regDat);
byte wrSensorReg16_16(int regID, int regDat);
byte rdSensorReg8_8(uint8_t regID, uint8_t* regDat);
byte rdSensorReg16_8(uint16_t regID, uint8_t* regDat);
byte rdSensorReg8_16(uint8_t regID, uint16_t* regDat);
byte rdSensorReg16_16(uint16_t regID, uint16_t* regDat);
void OV2640_set_JPEG_size(uint8_t size);
void OV5642_set_JPEG_size(uint8_t size);
void OV5640_set_JPEG_size(uint8_t size);
void set_format(byte fmt);
void transferBytes_(uint8_t * out, uint8_t * in, uint8_t size);
void transferBytes(uint8_t * out, uint8_t * in, uint32_t size);
inline void setDataBits(uint16_t bits);
int bus_write(int address, int value);
uint8_t bus_read(int address);
void diagnosticsOn();
void diagnosticsOff();
void diagmsg(char *msg);
void diagBusMsg(char *msg, int address, int value);
void diagReadBusMsg(int address, int value);
void diagWriteBusMsg(int address, int value);
boolean isCaptureComplete();
boolean isCapturing();
void complete_capture();
protected:
regtype *P_CS;
regsize B_CS;
byte m_fmt;
byte sensor_model;
byte sensor_addr;
boolean diagFlag;
boolean capturing;
};
#endif
| [
"ligalog@icloud.com"
] | ligalog@icloud.com |
576982cb97353117710fc063ae29b1afce8fdc5f | ce279d5aba441318246d13e66f26075541f5bf73 | /serial/include/interface/IfceSerialController.h | 6cf3369e89362f857de89babd589083db1063a8b | [] | no_license | krkruk/Qt-OrionPi | 25b2758cb2989d8450861c31ed110e004944d77f | 276b145c32ddbdaf1b847486cfec3bfdce393de2 | refs/heads/master | 2021-09-10T19:22:49.329929 | 2018-03-31T17:08:12 | 2018-03-31T17:08:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,318 | h | #ifndef IFCESERIALCONTROLLER_H
#define IFCESERIALCONTROLLER_H
#include <QSharedPointer>
class IfceSerialModel;
class QByteArray;
/**
* @brief The IfceSerialController interface allows communication between view and models.
*
* Any class derived from the interface should implement single way data exchange between
* a view (a serial device server) and a model (a data representation).
*/
class IfceSerialController
{
public:
virtual ~IfceSerialController() {}
/**
* @brief addModel Adds model that should be informed about incoming data from the serial server.
* @param model {@link IfceSerialModel}
*/
virtual void addModel(QSharedPointer<IfceSerialModel> model) = 0;
/**
* @brief onLineReceived Strategy method that allows forwarding data to the particular model object
* described by id.
* @param id ID of the model the data is addressed to
* @param line Data to be parsed by the model.
*/
virtual void onLineReceived(int id, const QByteArray &line) = 0;
/**
* @brief getLastReceived Returns the data that was recently received from the view
* @param id ID of serial device that recently has sent data.
* @return Raw data.
*/
virtual QByteArray getLastReceived(int id) const = 0;
};
#endif // IFCESERIALCONTROLLER_H
| [
"krzysztof.pawel.kruk@gmail.com"
] | krzysztof.pawel.kruk@gmail.com |
b1e5c03d4474abcd04ac8ba9c3eaa0ba30839cf3 | 9edbec38bbf4f6788764d77835b915de00e05c34 | /P2/include/Hannah.h | 83cca146930916c58a29d91c131f1cf575cb9709 | [] | no_license | saketb-2703/trial1 | 900dd48912360526c3b7b53310bfc5b8bc083cee | 7bedc82d51e7c48c4d4f83a78f70f16722557143 | refs/heads/master | 2023-05-09T15:55:22.886579 | 2021-05-08T19:12:12 | 2021-05-08T19:12:12 | 365,592,500 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 167 | h | #ifndef HANNAH_H
#define HANNAH_H
class Hannah
{
public:
Hannah(int num);
void printCrap();
private:
int h;
};
#endif // HANNAH_H
| [
"f20200983@goa.bits-pilani.ac.in"
] | f20200983@goa.bits-pilani.ac.in |
48ed70cfa4d0e61ad34dfb552e3c1712221dfb70 | cf9c3aa192d9ae2e8535f9f78d1a305c9d992d77 | /caffe/src/caffe/layers/myeuclidean_loss_layer.cpp | 05b9fee413076e31fc888a9671f169e9ea4b6239 | [
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause",
"LicenseRef-scancode-public-domain"
] | permissive | rumsyx/RPCF | 520dffdc90e1b5848f698bacb8c5ba29737685f7 | 0b6fab52f3d85eaab5d89139469a618ed07a9728 | refs/heads/master | 2020-03-27T08:45:33.621225 | 2019-11-14T04:20:10 | 2019-11-14T04:20:10 | 146,284,948 | 12 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,776 | cpp | #include <vector>
#include "caffe/layer.hpp"
#include "caffe/util/io.hpp"
#include "caffe/util/math_functions.hpp"
#include "caffe/vision_layers.hpp"
namespace caffe {
template <typename Dtype>
void myEuclideanLossLayer<Dtype>::Reshape(
const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {
LossLayer<Dtype>::Reshape(bottom, top);
CHECK_EQ(bottom[0]->count(1), bottom[1]->count(1))
<< "Inputs must have the same dimension.";
diff_.ReshapeLike(*bottom[0]);
}
template <typename Dtype>
void myEuclideanLossLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
int count = bottom[0]->count();
caffe_sub(
count,
bottom[0]->cpu_data(),
bottom[1]->cpu_data(),
diff_.mutable_cpu_data());
Dtype dot = caffe_cpu_dot(count, diff_.cpu_data(), diff_.cpu_data());
Dtype loss = dot / bottom[0]->num() / Dtype(2);
top[0]->mutable_cpu_data()[0] = loss;
}
template <typename Dtype>
void myEuclideanLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {
for (int i = 0; i < 2; ++i) {
if (propagate_down[i]) {
const Dtype sign = (i == 0) ? 1 : -1;
const Dtype alpha = sign * top[0]->cpu_diff()[0] / bottom[i]->num();
caffe_cpu_axpby(
bottom[i]->count(), // count
alpha, // alpha
diff_.cpu_data(), // a
Dtype(0), // beta
bottom[i]->mutable_cpu_diff()); // b
}
}
}
#ifdef CPU_ONLY
STUB_GPU(myEuclideanLossLayer);
#endif
INSTANTIATE_CLASS(myEuclideanLossLayer);
REGISTER_LAYER_CLASS(myEuclideanLoss);
} // namespace caffe
| [
"aprilsun@hotmail.com"
] | aprilsun@hotmail.com |
88f24f7977fdc2f843f1dc6980872531b5ff1627 | d34960c2d9a84ad0639005b86d79b3a0553292ab | /boost/boost/numeric/ublas/detail/raw.hpp | 63e69a1e8c6b2292670b0ed95170080e910e8bfc | [
"BSL-1.0",
"Apache-2.0"
] | permissive | tonystone/geofeatures | 413c13ebd47ee6676196399d47f5e23ba5345287 | 25aca530a9140b3f259e9ee0833c93522e83a697 | refs/heads/master | 2020-04-09T12:44:36.472701 | 2019-03-17T01:37:55 | 2019-03-17T01:37:55 | 41,232,751 | 28 | 9 | NOASSERTION | 2019-03-17T01:37:56 | 2015-08-23T02:35:40 | C++ | UTF-8 | C++ | false | false | 30,379 | hpp | //
// Copyright (c) 2002-2003
// Toon Knapen, Kresimir Fresl, Joerg Walter
//
// 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)
//
//
#ifndef _BOOST_UBLAS_RAW_
#define _BOOST_UBLAS_RAW_
namespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace numeric { namespace ublas { namespace raw {
// We need data_const() mostly due to MSVC 6.0.
// But how shall we write portable code otherwise?
template < typename V >
BOOST_UBLAS_INLINE
int size( const V &v ) ;
template < typename V >
BOOST_UBLAS_INLINE
int size( const vector_reference<V> &v ) ;
template < typename M >
BOOST_UBLAS_INLINE
int size1( const M &m ) ;
template < typename M >
BOOST_UBLAS_INLINE
int size2( const M &m ) ;
template < typename M >
BOOST_UBLAS_INLINE
int size1( const matrix_reference<M> &m ) ;
template < typename M >
BOOST_UBLAS_INLINE
int size2( const matrix_reference<M> &m ) ;
template < typename M >
BOOST_UBLAS_INLINE
int leading_dimension( const M &m, row_major_tag ) ;
template < typename M >
BOOST_UBLAS_INLINE
int leading_dimension( const M &m, column_major_tag ) ;
template < typename M >
BOOST_UBLAS_INLINE
int leading_dimension( const M &m ) ;
template < typename M >
BOOST_UBLAS_INLINE
int leading_dimension( const matrix_reference<M> &m ) ;
template < typename V >
BOOST_UBLAS_INLINE
int stride( const V &v ) ;
template < typename V >
BOOST_UBLAS_INLINE
int stride( const vector_range<V> &v ) ;
template < typename V >
BOOST_UBLAS_INLINE
int stride( const vector_slice<V> &v ) ;
template < typename M >
BOOST_UBLAS_INLINE
int stride( const matrix_row<M> &v ) ;
template < typename M >
BOOST_UBLAS_INLINE
int stride( const matrix_column<M> &v ) ;
template < typename M >
BOOST_UBLAS_INLINE
int stride1( const M &m ) ;
template < typename M >
BOOST_UBLAS_INLINE
int stride2( const M &m ) ;
template < typename M >
BOOST_UBLAS_INLINE
int stride1( const matrix_reference<M> &m ) ;
template < typename M >
BOOST_UBLAS_INLINE
int stride2( const matrix_reference<M> &m ) ;
template < typename T, std::size_t M, std::size_t N >
BOOST_UBLAS_INLINE
int stride1( const c_matrix<T, M, N> &m ) ;
template < typename T, std::size_t M, std::size_t N >
BOOST_UBLAS_INLINE
int stride2( const c_matrix<T, M, N> &m ) ;
template < typename M >
BOOST_UBLAS_INLINE
int stride1( const matrix_range<M> &m ) ;
template < typename M >
BOOST_UBLAS_INLINE
int stride1( const matrix_slice<M> &m ) ;
template < typename M >
BOOST_UBLAS_INLINE
int stride2( const matrix_range<M> &m ) ;
template < typename M >
BOOST_UBLAS_INLINE
int stride2( const matrix_slice<M> &m ) ;
template < typename MV >
BOOST_UBLAS_INLINE
typename MV::array_type::array_type::const_pointer data( const MV &mv ) ;
template < typename MV >
BOOST_UBLAS_INLINE
typename MV::array_type::array_type::const_pointer data_const( const MV &mv ) ;
template < typename MV >
BOOST_UBLAS_INLINE
typename MV::array_type::pointer data( MV &mv ) ;
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::array_type::const_pointer data( const vector_reference<V> &v ) ;
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::array_type::const_pointer data_const( const vector_reference<V> &v ) ;
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::pointer data( vector_reference<V> &v ) ;
template < typename T, std::size_t N >
BOOST_UBLAS_INLINE
typename c_vector<T, N>::array_type::array_type::const_pointer data( const c_vector<T, N> &v ) ;
template < typename T, std::size_t N >
BOOST_UBLAS_INLINE
typename c_vector<T, N>::array_type::array_type::const_pointer data_const( const c_vector<T, N> &v ) ;
template < typename T, std::size_t N >
BOOST_UBLAS_INLINE
typename c_vector<T, N>::pointer data( c_vector<T, N> &v ) ;
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::array_type::const_pointer data( const vector_range<V> &v ) ;
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::array_type::const_pointer data( const vector_slice<V> &v ) ;
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::array_type::const_pointer data_const( const vector_range<V> &v ) ;
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::array_type::const_pointer data_const( const vector_slice<V> &v ) ;
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::pointer data( vector_range<V> &v ) ;
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::pointer data( vector_slice<V> &v ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::array_type::const_pointer data( const matrix_reference<M> &m ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::array_type::const_pointer data_const( const matrix_reference<M> &m ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::pointer data( matrix_reference<M> &m ) ;
template < typename T, std::size_t M, std::size_t N >
BOOST_UBLAS_INLINE
typename c_matrix<T, M, N>::array_type::array_type::const_pointer data( const c_matrix<T, M, N> &m ) ;
template < typename T, std::size_t M, std::size_t N >
BOOST_UBLAS_INLINE
typename c_matrix<T, M, N>::array_type::array_type::const_pointer data_const( const c_matrix<T, M, N> &m ) ;
template < typename T, std::size_t M, std::size_t N >
BOOST_UBLAS_INLINE
typename c_matrix<T, M, N>::pointer data( c_matrix<T, M, N> &m ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::array_type::const_pointer data( const matrix_row<M> &v ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::array_type::const_pointer data( const matrix_column<M> &v ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::array_type::const_pointer data_const( const matrix_row<M> &v ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::array_type::const_pointer data_const( const matrix_column<M> &v ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::pointer data( matrix_row<M> &v ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::pointer data( matrix_column<M> &v ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::array_type::const_pointer data( const matrix_range<M> &m ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::array_type::const_pointer data( const matrix_slice<M> &m ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::array_type::const_pointer data_const( const matrix_range<M> &m ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::array_type::const_pointer data_const( const matrix_slice<M> &m ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::pointer data( matrix_range<M> &m ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::pointer data( matrix_slice<M> &m ) ;
template < typename MV >
BOOST_UBLAS_INLINE
typename MV::array_type::array_type::const_pointer base( const MV &mv ) ;
template < typename MV >
BOOST_UBLAS_INLINE
typename MV::array_type::array_type::const_pointer base_const( const MV &mv ) ;
template < typename MV >
BOOST_UBLAS_INLINE
typename MV::array_type::pointer base( MV &mv ) ;
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::array_type::const_pointer base( const vector_reference<V> &v ) ;
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::array_type::const_pointer base_const( const vector_reference<V> &v ) ;
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::pointer base( vector_reference<V> &v ) ;
template < typename T, std::size_t N >
BOOST_UBLAS_INLINE
typename c_vector<T, N>::array_type::array_type::const_pointer base( const c_vector<T, N> &v ) ;
template < typename T, std::size_t N >
BOOST_UBLAS_INLINE
typename c_vector<T, N>::array_type::array_type::const_pointer base_const( const c_vector<T, N> &v ) ;
template < typename T, std::size_t N >
BOOST_UBLAS_INLINE
typename c_vector<T, N>::pointer base( c_vector<T, N> &v ) ;
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::array_type::const_pointer base( const vector_range<V> &v ) ;
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::array_type::const_pointer base( const vector_slice<V> &v ) ;
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::array_type::const_pointer base_const( const vector_range<V> &v ) ;
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::array_type::const_pointer base_const( const vector_slice<V> &v ) ;
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::pointer base( vector_range<V> &v ) ;
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::pointer base( vector_slice<V> &v ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::array_type::const_pointer base( const matrix_reference<M> &m ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::array_type::const_pointer base_const( const matrix_reference<M> &m ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::pointer base( matrix_reference<M> &m ) ;
template < typename T, std::size_t M, std::size_t N >
BOOST_UBLAS_INLINE
typename c_matrix<T, M, N>::array_type::array_type::const_pointer base( const c_matrix<T, M, N> &m ) ;
template < typename T, std::size_t M, std::size_t N >
BOOST_UBLAS_INLINE
typename c_matrix<T, M, N>::array_type::array_type::const_pointer base_const( const c_matrix<T, M, N> &m ) ;
template < typename T, std::size_t M, std::size_t N >
BOOST_UBLAS_INLINE
typename c_matrix<T, M, N>::pointer base( c_matrix<T, M, N> &m ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::array_type::const_pointer base( const matrix_row<M> &v ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::array_type::const_pointer base( const matrix_column<M> &v ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::array_type::const_pointer base_const( const matrix_row<M> &v ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::array_type::const_pointer base_const( const matrix_column<M> &v ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::pointer base( matrix_row<M> &v ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::pointer base( matrix_column<M> &v ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::array_type::const_pointer base( const matrix_range<M> &m ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::array_type::const_pointer base( const matrix_slice<M> &m ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::array_type::const_pointer base_const( const matrix_range<M> &m ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::array_type::const_pointer base_const( const matrix_slice<M> &m ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::pointer base( matrix_range<M> &m ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::pointer base( matrix_slice<M> &m ) ;
template < typename MV >
BOOST_UBLAS_INLINE
typename MV::size_type start( const MV &mv ) ;
template < typename V >
BOOST_UBLAS_INLINE
typename V::size_type start( const vector_range<V> &v ) ;
template < typename V >
BOOST_UBLAS_INLINE
typename V::size_type start( const vector_slice<V> &v ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::size_type start( const matrix_row<M> &v ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::size_type start( const matrix_column<M> &v ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::size_type start( const matrix_range<M> &m ) ;
template < typename M >
BOOST_UBLAS_INLINE
typename M::size_type start( const matrix_slice<M> &m ) ;
template < typename V >
BOOST_UBLAS_INLINE
int size( const V &v ) {
return v.size() ;
}
template < typename V >
BOOST_UBLAS_INLINE
int size( const vector_reference<V> &v ) {
return size( v ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
int size1( const M &m ) {
return m.size1() ;
}
template < typename M >
BOOST_UBLAS_INLINE
int size2( const M &m ) {
return m.size2() ;
}
template < typename M >
BOOST_UBLAS_INLINE
int size1( const matrix_reference<M> &m ) {
return size1( m.expression() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
int size2( const matrix_reference<M> &m ) {
return size2( m.expression() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
int leading_dimension( const M &m, row_major_tag ) {
return m.size2() ;
}
template < typename M >
BOOST_UBLAS_INLINE
int leading_dimension( const M &m, column_major_tag ) {
return m.size1() ;
}
template < typename M >
BOOST_UBLAS_INLINE
int leading_dimension( const M &m ) {
return leading_dimension( m, typename M::orientation_category() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
int leading_dimension( const matrix_reference<M> &m ) {
return leading_dimension( m.expression() ) ;
}
template < typename V >
BOOST_UBLAS_INLINE
int stride( const V &v ) {
return 1 ;
}
template < typename V >
BOOST_UBLAS_INLINE
int stride( const vector_range<V> &v ) {
return stride( v.data() ) ;
}
template < typename V >
BOOST_UBLAS_INLINE
int stride( const vector_slice<V> &v ) {
return v.stride() * stride( v.data() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
int stride( const matrix_row<M> &v ) {
return stride2( v.data() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
int stride( const matrix_column<M> &v ) {
return stride1( v.data() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
int stride1( const M &m ) {
typedef typename M::functor_type functor_type;
return functor_type::one1( m.size1(), m.size2() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
int stride2( const M &m ) {
typedef typename M::functor_type functor_type;
return functor_type::one2( m.size1(), m.size2() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
int stride1( const matrix_reference<M> &m ) {
return stride1( m.expression() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
int stride2( const matrix_reference<M> &m ) {
return stride2( m.expression() ) ;
}
template < typename T, std::size_t M, std::size_t N >
BOOST_UBLAS_INLINE
int stride1( const c_matrix<T, M, N> &m ) {
return N ;
}
template < typename T, std::size_t M, std::size_t N >
BOOST_UBLAS_INLINE
int stride2( const c_matrix<T, M, N> &m ) {
return 1 ;
}
template < typename M >
BOOST_UBLAS_INLINE
int stride1( const matrix_range<M> &m ) {
return stride1( m.data() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
int stride1( const matrix_slice<M> &m ) {
return m.stride1() * stride1( m.data() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
int stride2( const matrix_range<M> &m ) {
return stride2( m.data() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
int stride2( const matrix_slice<M> &m ) {
return m.stride2() * stride2( m.data() ) ;
}
template < typename MV >
BOOST_UBLAS_INLINE
typename MV::array_type::array_type::array_type::const_pointer data( const MV &mv ) {
return &mv.data().begin()[0] ;
}
template < typename MV >
BOOST_UBLAS_INLINE
typename MV::array_type::array_type::const_pointer data_const( const MV &mv ) {
return &mv.data().begin()[0] ;
}
template < typename MV >
BOOST_UBLAS_INLINE
typename MV::array_type::pointer data( MV &mv ) {
return &mv.data().begin()[0] ;
}
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::array_type::const_pointer data( const vector_reference<V> &v ) {
return data( v.expression () ) ;
}
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::array_type::const_pointer data_const( const vector_reference<V> &v ) {
return data_const( v.expression () ) ;
}
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::pointer data( vector_reference<V> &v ) {
return data( v.expression () ) ;
}
template < typename T, std::size_t N >
BOOST_UBLAS_INLINE
typename c_vector<T, N>::array_type::array_type::const_pointer data( const c_vector<T, N> &v ) {
return v.data() ;
}
template < typename T, std::size_t N >
BOOST_UBLAS_INLINE
typename c_vector<T, N>::array_type::array_type::const_pointer data_const( const c_vector<T, N> &v ) {
return v.data() ;
}
template < typename T, std::size_t N >
BOOST_UBLAS_INLINE
typename c_vector<T, N>::pointer data( c_vector<T, N> &v ) {
return v.data() ;
}
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::array_type::const_pointer data( const vector_range<V> &v ) {
return data( v.data() ) + v.start() * stride (v.data() ) ;
}
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::array_type::const_pointer data( const vector_slice<V> &v ) {
return data( v.data() ) + v.start() * stride (v.data() ) ;
}
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::array_type::const_pointer data_const( const vector_range<V> &v ) {
return data_const( v.data() ) + v.start() * stride (v.data() ) ;
}
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::const_pointer data_const( const vector_slice<V> &v ) {
return data_const( v.data() ) + v.start() * stride (v.data() ) ;
}
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::pointer data( vector_range<V> &v ) {
return data( v.data() ) + v.start() * stride (v.data() ) ;
}
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::pointer data( vector_slice<V> &v ) {
return data( v.data() ) + v.start() * stride (v.data() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::const_pointer data( const matrix_reference<M> &m ) {
return data( m.expression () ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::const_pointer data_const( const matrix_reference<M> &m ) {
return data_const( m.expression () ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::pointer data( matrix_reference<M> &m ) {
return data( m.expression () ) ;
}
template < typename T, std::size_t M, std::size_t N >
BOOST_UBLAS_INLINE
typename c_matrix<T, M, N>::array_type::const_pointer data( const c_matrix<T, M, N> &m ) {
return m.data() ;
}
template < typename T, std::size_t M, std::size_t N >
BOOST_UBLAS_INLINE
typename c_matrix<T, M, N>::array_type::const_pointer data_const( const c_matrix<T, M, N> &m ) {
return m.data() ;
}
template < typename T, std::size_t M, std::size_t N >
BOOST_UBLAS_INLINE
typename c_matrix<T, M, N>::pointer data( c_matrix<T, M, N> &m ) {
return m.data() ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::const_pointer data( const matrix_row<M> &v ) {
return data( v.data() ) + v.index() * stride1( v.data() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::const_pointer data( const matrix_column<M> &v ) {
return data( v.data() ) + v.index() * stride2( v.data() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::const_pointer data_const( const matrix_row<M> &v ) {
return data_const( v.data() ) + v.index() * stride1( v.data() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::const_pointer data_const( const matrix_column<M> &v ) {
return data_const( v.data() ) + v.index() * stride2( v.data() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::pointer data( matrix_row<M> &v ) {
return data( v.data() ) + v.index() * stride1( v.data() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::pointer data( matrix_column<M> &v ) {
return data( v.data() ) + v.index() * stride2( v.data() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::const_pointer data( const matrix_range<M> &m ) {
return data( m.data() ) + m.start1() * stride1( m.data () ) + m.start2() * stride2( m.data () ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::const_pointer data( const matrix_slice<M> &m ) {
return data( m.data() ) + m.start1() * stride1( m.data () ) + m.start2() * stride2( m.data () ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::const_pointer data_const( const matrix_range<M> &m ) {
return data_const( m.data() ) + m.start1() * stride1( m.data () ) + m.start2() * stride2( m.data () ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::const_pointer data_const( const matrix_slice<M> &m ) {
return data_const( m.data() ) + m.start1() * stride1( m.data () ) + m.start2() * stride2( m.data () ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::pointer data( matrix_range<M> &m ) {
return data( m.data() ) + m.start1() * stride1( m.data () ) + m.start2() * stride2( m.data () ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::pointer data( matrix_slice<M> &m ) {
return data( m.data() ) + m.start1() * stride1( m.data () ) + m.start2() * stride2( m.data () ) ;
}
template < typename MV >
BOOST_UBLAS_INLINE
typename MV::array_type::const_pointer base( const MV &mv ) {
return &mv.data().begin()[0] ;
}
template < typename MV >
BOOST_UBLAS_INLINE
typename MV::array_type::const_pointer base_const( const MV &mv ) {
return &mv.data().begin()[0] ;
}
template < typename MV >
BOOST_UBLAS_INLINE
typename MV::array_type::pointer base( MV &mv ) {
return &mv.data().begin()[0] ;
}
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::const_pointer base( const vector_reference<V> &v ) {
return base( v.expression () ) ;
}
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::const_pointer base_const( const vector_reference<V> &v ) {
return base_const( v.expression () ) ;
}
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::pointer base( vector_reference<V> &v ) {
return base( v.expression () ) ;
}
template < typename T, std::size_t N >
BOOST_UBLAS_INLINE
typename c_vector<T, N>::array_type::const_pointer base( const c_vector<T, N> &v ) {
return v.data() ;
}
template < typename T, std::size_t N >
BOOST_UBLAS_INLINE
typename c_vector<T, N>::array_type::const_pointer base_const( const c_vector<T, N> &v ) {
return v.data() ;
}
template < typename T, std::size_t N >
BOOST_UBLAS_INLINE
typename c_vector<T, N>::pointer base( c_vector<T, N> &v ) {
return v.data() ;
}
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::const_pointer base( const vector_range<V> &v ) {
return base( v.data() ) ;
}
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::const_pointer base( const vector_slice<V> &v ) {
return base( v.data() ) ;
}
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::const_pointer base_const( const vector_range<V> &v ) {
return base_const( v.data() ) ;
}
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::const_pointer base_const( const vector_slice<V> &v ) {
return base_const( v.data() ) ;
}
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::pointer base( vector_range<V> &v ) {
return base( v.data() ) ;
}
template < typename V >
BOOST_UBLAS_INLINE
typename V::array_type::pointer base( vector_slice<V> &v ) {
return base( v.data() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::const_pointer base( const matrix_reference<M> &m ) {
return base( m.expression () ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::const_pointer base_const( const matrix_reference<M> &m ) {
return base_const( m.expression () ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::pointer base( matrix_reference<M> &m ) {
return base( m.expression () ) ;
}
template < typename T, std::size_t M, std::size_t N >
BOOST_UBLAS_INLINE
typename c_matrix<T, M, N>::array_type::const_pointer base( const c_matrix<T, M, N> &m ) {
return m.data() ;
}
template < typename T, std::size_t M, std::size_t N >
BOOST_UBLAS_INLINE
typename c_matrix<T, M, N>::array_type::const_pointer base_const( const c_matrix<T, M, N> &m ) {
return m.data() ;
}
template < typename T, std::size_t M, std::size_t N >
BOOST_UBLAS_INLINE
typename c_matrix<T, M, N>::pointer base( c_matrix<T, M, N> &m ) {
return m.data() ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::const_pointer base( const matrix_row<M> &v ) {
return base( v.data() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::const_pointer base( const matrix_column<M> &v ) {
return base( v.data() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::const_pointer base_const( const matrix_row<M> &v ) {
return base_const( v.data() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::const_pointer base_const( const matrix_column<M> &v ) {
return base_const( v.data() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::pointer base( matrix_row<M> &v ) {
return base( v.data() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::pointer base( matrix_column<M> &v ) {
return base( v.data() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::const_pointer base( const matrix_range<M> &m ) {
return base( m.data() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::const_pointer base( const matrix_slice<M> &m ) {
return base( m.data() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::const_pointer base_const( const matrix_range<M> &m ) {
return base_const( m.data() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::const_pointer base_const( const matrix_slice<M> &m ) {
return base_const( m.data() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::pointer base( matrix_range<M> &m ) {
return base( m.data() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::array_type::pointer base( matrix_slice<M> &m ) {
return base( m.data() ) ;
}
template < typename MV >
BOOST_UBLAS_INLINE
typename MV::size_type start( const MV &mv ) {
return 0 ;
}
template < typename V >
BOOST_UBLAS_INLINE
typename V::size_type start( const vector_range<V> &v ) {
return v.start() * stride (v.data() ) ;
}
template < typename V >
BOOST_UBLAS_INLINE
typename V::size_type start( const vector_slice<V> &v ) {
return v.start() * stride (v.data() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::size_type start( const matrix_row<M> &v ) {
return v.index() * stride1( v.data() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::size_type start( const matrix_column<M> &v ) {
return v.index() * stride2( v.data() ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::size_type start( const matrix_range<M> &m ) {
return m.start1() * stride1( m.data () ) + m.start2() * stride2( m.data () ) ;
}
template < typename M >
BOOST_UBLAS_INLINE
typename M::size_type start( const matrix_slice<M> &m ) {
return m.start1() * stride1( m.data () ) + m.start2() * stride2( m.data () ) ;
}
}}}}
#endif
| [
"tony@mobilegridinc.com"
] | tony@mobilegridinc.com |
452a84f18d66c3ac1bd8f919ae28b012abe0a24a | e727cc3c1e9a3542b9114b77b15b6f77450ca4a5 | /src/app/necat2sv/sv_reads.cpp | 6ffc9bbec2535e5e4de3ca15b971f9c74847eaec | [] | no_license | xiaochuanle/lesv | 3624b4a5ae35e6ccf3e826b0a6791d469f366d87 | b3c41997c5c2da2f355cff5bdcae25ce061eed99 | refs/heads/master | 2022-12-12T02:22:54.304662 | 2020-09-07T02:40:29 | 2020-09-07T02:40:29 | 293,403,776 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,768 | cpp | #include "sv_reads.h"
#include "../../ncbi_blast/str_util/ncbistr.hpp"
#include <fstream>
using namespace std;
extern "C"
void
sread_sv_read(const char* in, SvRead* rp)
{
ncbi::CTempString ins(in);
ncbi::CTempString delim("\t");
vector<ncbi::CTempString> components;
NStr::Split(ins, delim, components);
int np = components.size();
hbn_assert(np == 9 || np == 10 || np == 15 || np == 16, "n = %d, %s", np, in);
rp->query_id = NStr::StringToInt(components[0]);
rp->qdir = NStr::StringToInt(components[1]);
rp->qoff = NStr::StringToInt(components[2]);
rp->qend = NStr::StringToInt(components[3]);
rp->qsize = NStr::StringToInt(components[4]);
rp->subject_id = NStr::StringToInt(components[5]);
rp->soff = NStr::StringToInt(components[6]);
rp->send = NStr::StringToInt(components[7]);
rp->dist = NStr::StringToInt(components[8]);
rp->dual_qdir = -1;
if (np > 11) {
rp->dual_qdir = NStr::StringToInt(components[9]);
rp->dual_qoff = NStr::StringToInt(components[10]);
rp->dual_qend = NStr::StringToInt(components[11]);
rp->dual_soff = NStr::StringToInt(components[12]);
rp->dual_send = NStr::StringToInt(components[13]);
rp->dual_dist = NStr::StringToInt(components[14]);
}
}
extern "C"
SvRead*
load_sv_read_array(const char* path, int* sv_read_count)
{
ifstream in(path);
if (!in) HBN_ERR("Fail to open file %s for reading", path);
string line;
kv_dinit(vec_sv_read, sv_read_list);
SvRead sv_read;
while (getline(in, line)) {
sread_sv_read(line.c_str(), &sv_read);
kv_push(SvRead, sv_read_list, sv_read);
}
in.close();
*sv_read_count = kv_size(sv_read_list);
return kv_data(sv_read_list);
} | [
"sysu@sysudeMacBook-Pro.local"
] | sysu@sysudeMacBook-Pro.local |
8a808f13c92e9a84fa6185235b34d9274478fbdb | 805109c841a3431bc6f543ee9b3ab3da07b5460d | /rotateList/rotateList/main.cpp | 50e4120aacb581adc7820c47c661ba3aada7c735 | [] | no_license | jingninc/algorithm | bc4f8e3ecd845596e418c297bf11da917e868241 | 481406c8d5763585ff645a85db26f9deb5376cab | refs/heads/master | 2016-09-05T16:12:32.324491 | 2015-02-02T19:00:23 | 2015-02-02T19:00:23 | 30,202,500 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 992 | cpp | //
// main.cpp
// rotateList
//
// Created by JINGNING CAO on 1/25/15.
// Copyright (c) 2015 JINGNING CAO. All rights reserved.
//
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
int getLen(ListNode* head){
int len = 0;
while(head){
len++;
head=head->next;
}
return len;
}
ListNode *rotateRight(ListNode *head, int k) {
if (!head) return head;
k = k % getLen(head);
ListNode* dummy = new ListNode(-1);
dummy->next = head;
ListNode* advance = dummy;
for(int i = 0; i < k; i++, advance =advance->next){}
ListNode* pre = dummy;
for(; advance->next; advance=advance->next, pre=pre->next){}
advance->next = dummy->next;
ListNode* newHead = pre->next;
pre->next = NULL;
return newHead;
}
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
return 0;
}
| [
"caojn909224@gmail.com"
] | caojn909224@gmail.com |
da7dfdc64834631d73b9ac94d5ff5e6acfb1b1fd | 885dfd7cbf285f88808b957475092217c5b09c68 | /2020-hpc-ii/hw4/p1_p2/main_ssa_test.cpp | 24010d41420b03b5c71194551f067bf74296c06a | [] | no_license | florian-world/high-performance-computing | d89c0c70ff7fb034611a7f42683aa2b0770770fb | 86c22cd31eb327d5281fb65ca24227dfd0d6cbd0 | refs/heads/master | 2022-11-18T13:51:49.443508 | 2020-07-04T09:41:38 | 2020-07-04T09:41:38 | 277,081,315 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,014 | cpp | #include <cstdio>
#include <cstdlib>
#include <vector>
#include <string>
#include <chrono>
#include "ArgumentParser.hpp"
#include "SSA_CPU.hpp"
typedef std::chrono::system_clock Clock;
using namespace std;
int main(int argc, const char ** argv)
{
if (argc != 6) {
fprintf(stderr, "Usage: %s k1 k2 k3 k4 n\n", argv[0]);
exit(1);
}
auto k1 = (double) atof(argv[1]);
auto k2 = (double) atof(argv[2]);
auto k3 = (double) atof(argv[3]);
auto k4 = (double) atof(argv[4]);
int n = atoi(argv[5]);
printf("Running with k1 = %f, k2 = %f, k3 = %f k4 = %f\n\n", k1, k2, k3, k4);
double sum1 = 0.0;
double sum2 = 0.0;
for (int i = 0; i < n; ++i) {
SSA_CPU ssa(10, 2000, 5.0, 0.1, // omega, numSamples, T, dt
k1, k2, k3, k4);
ssa();
auto S1 = ssa.getS1();
auto S2 = ssa.getS2();
sum1 += S1;
sum2 += S2;
printf("Output %2d: S1 = %f, S2 = %f\n", (i+1), S1, S2);
}
printf("\n Average: S1 = %f, S2 = %f\n\n", sum1/n, sum2/n);
return 0;
}
| [
"m@florian.world"
] | m@florian.world |
bdc203aa30b520f4923417a88964901db325be45 | 2aa898dbe14af58220cd90d58ee42a60373d4983 | /Card Game.cpp | 52aae1e90e0addfa7d38ab543ef9972f909c4d31 | [] | no_license | saidul-islam98/Codeforces-Codes | f87a93d10a29aceea1cda4b4ff6b7470ddadc604 | 69db958e0b1918524336139dfeec39696a00d847 | refs/heads/main | 2023-07-12T03:27:31.196702 | 2021-08-09T11:09:30 | 2021-08-09T11:09:30 | 320,839,008 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 501 | cpp | #include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int n,f,s;
cin>>n>>f>>s;
int a[f],b[s];
for(int i=0;i<f;i++){
cin>>a[i];
}
for(int i=0;i<s;i++){
cin>>b[i];
}
int max1=*max_element(a,a+f);
int max2=*max_element(b,b+s);
if(max1>max2){
cout<<"YES\n";
}
else{
cout<<"NO\n";
}
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
2af8f14ec8f19c88a0c5842441437c8b045bb1aa | fb5b25b4fbe66c532672c14dacc520b96ff90a04 | /export/release/windows/obj/src/__resources__.cpp | 0d6df011e3aba6aeada7d0d4fe01d647099e9c9b | [
"Apache-2.0"
] | permissive | Tyrcnex/tai-mod | c3849f817fe871004ed171245d63c5e447c4a9c3 | b83152693bb3139ee2ae73002623934f07d35baf | refs/heads/main | 2023-08-15T07:15:43.884068 | 2021-09-29T23:39:23 | 2021-09-29T23:39:23 | 383,313,424 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,631 | cpp | #include <hxcpp.h>
namespace hx {
extern unsigned char __res_0[];
extern unsigned char __res_1[];
extern unsigned char __res_2[];
extern unsigned char __res_3[];
extern unsigned char __res_4[];
extern unsigned char __res_5[];
extern unsigned char __res_6[];
extern unsigned char __res_7[];
extern unsigned char __res_8[];
extern unsigned char __res_9[];
extern unsigned char __res_10[];
extern unsigned char __res_11[];
extern unsigned char __res_12[];
extern unsigned char __res_13[];
extern unsigned char __res_14[];
extern unsigned char __res_15[];
extern unsigned char __res_16[];
extern unsigned char __res_17[];
extern unsigned char __res_18[];
extern unsigned char __res_19[];
extern unsigned char __res_20[];
extern unsigned char __res_21[];
extern unsigned char __res_22[];
extern unsigned char __res_23[];
extern unsigned char __res_24[];
extern unsigned char __res_25[];
extern unsigned char __res_26[];
extern unsigned char __res_27[];
extern unsigned char __res_28[];
extern unsigned char __res_29[];
extern unsigned char __res_30[];
extern unsigned char __res_31[];
extern unsigned char __res_32[];
extern unsigned char __res_33[];
extern unsigned char __res_34[];
extern unsigned char __res_35[];
extern unsigned char __res_36[];
extern unsigned char __res_37[];
extern unsigned char __res_38[];
extern unsigned char __res_39[];
extern unsigned char __res_40[];
extern unsigned char __res_41[];
extern unsigned char __res_42[];
extern unsigned char __res_43[];
extern unsigned char __res_44[];
extern unsigned char __res_45[];
extern unsigned char __res_46[];
extern unsigned char __res_47[];
extern unsigned char __res_48[];
extern unsigned char __res_49[];
extern unsigned char __res_50[];
extern unsigned char __res_51[];
extern unsigned char __res_52[];
extern unsigned char __res_53[];
extern unsigned char __res_54[];
extern unsigned char __res_55[];
extern unsigned char __res_56[];
extern unsigned char __res_57[];
extern unsigned char __res_58[];
extern unsigned char __res_59[];
extern unsigned char __res_60[];
extern unsigned char __res_61[];
extern unsigned char __res_62[];
extern unsigned char __res_63[];
extern unsigned char __res_64[];
extern unsigned char __res_65[];
extern unsigned char __res_66[];
extern unsigned char __res_67[];
extern unsigned char __res_68[];
extern unsigned char __res_69[];
extern unsigned char __res_70[];
extern unsigned char __res_71[];
extern unsigned char __res_72[];
}
::hx::Resource __Resources[] = {
{ HX_("__ASSET__:image___ASSET__flixel_images_ui_button_png",a1,20,a7,8f),519,::hx::__res_0 + 4 },
{ HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_chrome_flat_png",43,9f,23,04),212,::hx::__res_1 + 4 },
{ HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_box_png",f0,30,d2,d5),912,::hx::__res_2 + 4 },
{ HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_radio_png",a0,60,63,c4),191,::hx::__res_3 + 4 },
{ HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_swatch_png",cb,3b,87,68),185,::hx::__res_4 + 4 },
{ HX_("__ASSET__:bitmap_flixel_system_debug__FlxDebugger_GraphicFlixel",d8,af,bc,0c),3105,::hx::__res_5 + 4 },
{ HX_("__ASSET__:bitmap_flixel_addons_transition_GraphicTransTileCircle",79,9b,85,6a),16201,::hx::__res_6 + 4 },
{ HX_("__ASSET__:bitmap_flixel_system__FlxPreloader_GraphicLogoCorners",da,69,74,ee),1515,::hx::__res_7 + 4 },
{ HX_("LIME_font___ASSET__flixel_fonts_nokiafc22_ttf",32,8e,cf,38),15744,::hx::__res_8 + 4 },
{ HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_check_mark_png",73,3f,b4,e4),946,::hx::__res_9 + 4 },
{ HX_("__ASSET__:image___ASSET__flixel_images_logo_default_png",5d,c4,77,3f),3280,::hx::__res_10 + 4 },
{ HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_button_arrow_up_png",63,22,63,a8),493,::hx::__res_11 + 4 },
{ HX_("__ASSET__:bitmap_flixel_system_debug__Window_GraphicWindowHandle",b1,52,a1,65),174,::hx::__res_12 + 4 },
{ HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_button_arrow_down_png",6a,37,2c,53),446,::hx::__res_13 + 4 },
{ HX_("__ASSET__:bitmap_flixel_system_GraphicVirtualInput",34,a9,10,f7),36963,::hx::__res_14 + 4 },
{ HX_("__ASSET__:bitmap_flixel_system_debug_GraphicInteractive",39,22,20,19),246,::hx::__res_15 + 4 },
{ HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_minus_mark_png",cb,22,ec,26),136,::hx::__res_16 + 4 },
{ HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_tab_back_png",20,f0,05,f9),210,::hx::__res_17 + 4 },
{ HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_tooltip_arrow_png",f2,65,b0,31),18509,::hx::__res_18 + 4 },
{ HX_("__ASSET__:bitmap_flixel_system_debug_GraphicArrowRight",dc,1c,ad,91),156,::hx::__res_19 + 4 },
{ HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_tab_png",3a,ba,84,7e),201,::hx::__res_20 + 4 },
{ HX_("__ASSET__:file___ASSET__flixel_flixel_ui_xml_default_loading_screen_xml",61,22,d8,fd),1953,::hx::__res_21 + 4 },
{ HX_("__ASSET__:bitmap_flixel_system_debug__FlxDebugger_GraphicDrawDebug",b3,af,96,c5),173,::hx::__res_22 + 4 },
{ HX_("__ASSET__:bitmap_flixel_system_debug_GraphicConsole",2e,18,f0,f3),206,::hx::__res_23 + 4 },
{ HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_chrome_inset_png",a7,e3,97,7f),192,::hx::__res_24 + 4 },
{ HX_("__ASSET__:bitmap_flixel_system_debug_interaction_tools__Transform_GraphicTransformCursorRotate",77,c1,65,97),202,::hx::__res_25 + 4 },
{ HX_("__ASSET__:bitmap_flixel_input_mouse__FlxMouse_GraphicCursor",c5,22,e3,93),706,::hx::__res_26 + 4 },
{ HX_("__ASSET__:file___ASSET__flixel_flixel_ui_xml_defaults_xml",66,61,52,48),1263,::hx::__res_27 + 4 },
{ HX_("__ASSET__:bitmap_flixel_system_debug_GraphicBitmapLog",6c,ac,7b,3e),180,::hx::__res_28 + 4 },
{ HX_("__ASSET__:bitmap_flixel_system_debug_GraphicCloseButton",21,6c,f7,70),258,::hx::__res_29 + 4 },
{ HX_("__ASSET__:file___ASSET__flixel_sounds_beep_ogg",6d,0a,6e,70),5794,::hx::__res_30 + 4 },
{ HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_button_arrow_left_png",8f,7d,3f,25),459,::hx::__res_31 + 4 },
{ HX_("__ASSET__:file_flixel_system_VirtualInputData",cf,a9,c1,46),206,::hx::__res_32 + 4 },
{ HX_("__ASSET__:bitmap_flixel_system_GraphicLogo",a0,bd,f5,14),4002,::hx::__res_33 + 4 },
{ HX_("__ASSET__:bitmap_flixel_system_debug_interaction_tools__Transform_GraphicTransformCursorScaleX",aa,65,6b,08),213,::hx::__res_34 + 4 },
{ HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_chrome_light_png",20,68,80,1a),214,::hx::__res_35 + 4 },
{ HX_("__ASSET__:bitmap_flixel_system_debug_interaction_tools__Transform_GraphicTransformCursorDefault",25,16,4a,8c),214,::hx::__res_36 + 4 },
{ HX_("LIME_font___ASSET__flixel_fonts_monsterrat_ttf",c6,95,44,8e),29724,::hx::__res_37 + 4 },
{ HX_("__ASSET__:file___ASSET__assets_fonts_fonts_go_here_txt",1d,b3,63,d8),0,::hx::__res_38 + 4 },
{ HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_button_arrow_right_png",68,d9,3c,b2),511,::hx::__res_39 + 4 },
{ HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_finger_small_png",80,fb,be,f7),294,::hx::__res_40 + 4 },
{ HX_("__ASSET__:sound_flixel_addons_text_TypeSound",86,8d,a7,7b),4197,::hx::__res_41 + 4 },
{ HX_("__ASSET__:bitmap_flixel_addons_transition__TransitionFade_GraphicDiagonalGradient",43,3b,8c,88),18812,::hx::__res_42 + 4 },
{ HX_("__ASSET__:bitmap_flixel_system_debug_interaction_tools__Transform_GraphicTransformTool",fe,f8,0a,56),194,::hx::__res_43 + 4 },
{ HX_("__ASSET__:bitmap_flixel_system_debug_interaction_tools__Mover_GraphicMoverTool",5e,5f,d5,0e),47775,::hx::__res_44 + 4 },
{ HX_("LIME_font___ASSET__assets_fonts_pixel_otf",7b,14,69,8d),14656,::hx::__res_45 + 4 },
{ HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_button_toggle_png",26,ef,a6,83),534,::hx::__res_46 + 4 },
{ HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_invis_png",c0,26,93,7b),128,::hx::__res_47 + 4 },
{ HX_("__ASSET__:bitmap_flixel_system_debug_GraphicLog",db,89,51,9b),158,::hx::__res_48 + 4 },
{ HX_("__ASSET__:file___ASSET__flixel_flixel_ui_xml_default_popup_xml",4a,b4,43,80),1848,::hx::__res_49 + 4 },
{ HX_("__ASSET__:bitmap_flixel_system_debug_GraphicArrowLeft",07,17,f4,7a),179,::hx::__res_50 + 4 },
{ HX_("__ASSET__:bitmap_flixel_system_debug_interaction_tools__Transform_GraphicTransformCursorScaleY",ab,65,6b,08),204,::hx::__res_51 + 4 },
{ HX_("__ASSET__:bitmap_flixel_system_debug_interaction_tools_GraphicCursorCross",12,f7,e2,fa),214,::hx::__res_52 + 4 },
{ HX_("__ASSET__:bitmap_flixel_system_debug_GraphicWatch",66,8f,5d,86),342,::hx::__res_53 + 4 },
{ HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_button_thin_png",6b,32,6e,23),247,::hx::__res_54 + 4 },
{ HX_("__ASSET__:bitmap_flixel_system_debug_interaction_tools__Transform_GraphicTransformCursorScaleXY",6f,8f,8d,55),213,::hx::__res_55 + 4 },
{ HX_("__ASSET__:file___ASSET__flixel_sounds_flixel_ogg",9b,a0,bd,8d),33629,::hx::__res_56 + 4 },
{ HX_("__ASSET__:bitmap_flixel_system_debug_interaction_tools__Eraser_GraphicEraserTool",08,fb,52,67),48233,::hx::__res_57 + 4 },
{ HX_("__ASSET__:bitmap_flixel_system__FlxPreloader_GraphicLogoLight",b2,b0,e9,d2),1804,::hx::__res_58 + 4 },
{ HX_("__ASSET__:bitmap_flixel_system_debug_stats__Stats_GraphicMinimizeButton",38,20,46,56),178,::hx::__res_59 + 4 },
{ HX_("__ASSET__:bitmap_flixel_addons_transition_GraphicTransTileSquare",06,2a,6a,6d),15583,::hx::__res_60 + 4 },
{ HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_finger_big_png",39,e2,df,0d),1724,::hx::__res_61 + 4 },
{ HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_hilight_png",9a,7b,e5,4d),129,::hx::__res_62 + 4 },
{ HX_("LIME_font___ASSET__assets_fonts_vcr_ttf",9f,aa,95,e0),75864,::hx::__res_63 + 4 },
{ HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_radio_dot_png",2a,28,60,f8),153,::hx::__res_64 + 4 },
{ HX_("__ASSET__:bitmap_flixel_system_debug_GraphicStats",36,ef,43,45),171,::hx::__res_65 + 4 },
{ HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_chrome_png",49,b7,86,49),253,::hx::__res_66 + 4 },
{ HX_("__ASSET__:bitmap_flixel_addons_transition_GraphicTransTileDiamond",cb,79,c6,30),1657,::hx::__res_67 + 4 },
{ HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_dropdown_mark_png",e0,ec,16,1f),156,::hx::__res_68 + 4 },
{ HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_button_png",c1,bb,20,7d),433,::hx::__res_69 + 4 },
{ HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_check_box_png",79,29,1e,5c),922,::hx::__res_70 + 4 },
{ HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_plus_mark_png",f7,d6,28,cb),147,::hx::__res_71 + 4 },
{ HX_("__ASSET__:bitmap_flixel_system_debug_stats__Stats_GraphicMaximizeButton",66,7c,bc,b9),194,::hx::__res_72 + 4 },
{ ::String(null()),0,0 }
};
namespace hx { Resource *GetResources() { return __Resources; } }
| [
"72734817+khiodev@users.noreply.github.com"
] | 72734817+khiodev@users.noreply.github.com |
47494578e2e10d4041715616642590fef9abfee9 | cba69333cf60daaa172987fa023948adfba60679 | /RingBuffer/main.cpp | 48c363194b97146ce4af8996baf3b045ecf5cc5b | [] | no_license | thomasalvatran/Oct2015 | ba08b8fd4e5cecae98356ec772f04f2dd3097321 | 4bfe7e66532cc02fd64e4ff5ecf33f94a74e8f50 | refs/heads/master | 2021-01-10T02:33:23.593018 | 2015-10-27T13:31:56 | 2015-10-27T13:31:56 | 44,273,249 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,501 | cpp |
#include "ds/ringbuffer.h"
#include "fxttypes.h"
#include "fxtio.h"
#include "jjassert.h"
#include "nextarg.h"
//% Demo of the ring buffer data structure.
typedef signed char RBt;
static void print_ringbuffer(ringbuffer<RBt> &R) {
cout << " ";
for (ulong j = 0; j < R.n_; ++j)
cout << setw(3) << R.x_[j];
for (ulong j = R.n_; j < R.s_; ++j)
cout << " ";
cout << " ";
ulong k = 0;
RBt z;
while ((k = R.read(k, z))) {
cout << setw(3) << z;
}
for (ulong j = R.n_; j < R.s_; ++j)
cout << " ";
cout << " ";
cout << " #=" << setw(1) << R.num();
cout << " r=" << setw(1) << R.wpos_;
cout << " w=" << setw(1) << R.fpos_;
cout << endl;
}
// -------------------------
static void vinsert(ringbuffer<RBt> &R, RBt k) {
R.insert(k);
cout << "insert(" << k << ") ";
print_ringbuffer(R);
}
// -------------------------
int main(int argc, char **argv) {
ulong n = 4;
NXARG(n, "Size of the ringbuffer");
ringbuffer<RBt> R(n);
const char A[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// for (ulong k=1; k<5*n/2; ++k) vinsert(R, k); // for RBt == ulong
//for (ulong k = 0; k < 26 / 2; ++k)
for (ulong k = 0; k < 5 * n / 2; ++k)
vinsert(R, A[(k % 26)]);
return 0;
}
// -------------------------
/// Emacs:
/// Local Variables:
/// MyRelDir: "demo/ds"
/// makefile-dir: "../../"
/// make-target: "1demo DSRC=demo/ds/ringbuffer-demo.cc"
/// make-target2: "1demo DSRC=demo/ds/ringbuffer-demo.cc DEMOFLAGS=-DTIMING"
/// End:
| [
"thomasalvatran@gmail.com"
] | thomasalvatran@gmail.com |
e62651abe0fee7d15bc813d3c67944f58772a45a | 565c581fd92809e1e44b4a04d5b7fbbfbcaf30b9 | /module05/ex02/Form.hpp | f3910bc1a2d8cad1c763dbac15588e5a84297af4 | [] | no_license | brojoon/cpp_module | 1e1a44d59fccdb6145529cf0e6eb81578ee12e30 | c627e5623ea9fca547a905c40da9a3ecc9506653 | refs/heads/main | 2023-06-07T05:58:35.642321 | 2021-07-02T22:16:14 | 2021-07-02T22:16:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,176 | hpp | #ifndef Form_hpp
#define Form_hpp
#include <iostream>
#include <exception>
#include "Bureaucrat.hpp"
class Form
{
private:
const std::string name;
std::string target;
bool isSigned;
const int gradeToSign;
const int gradeToExecute;
public:
Form();
Form(std::string name, std::string target, int gradeToSign, int gradeToExecute);
virtual ~Form();
Form(const Form&);
Form &operator=(const Form&);
std::string const &getName() const;
std::string const &getTarget() const;
bool getIsSigned() const;
int getGradeToSign() const;
int getGradeToExecute() const;
void beSigned(Bureaucrat&);
virtual void execute(Bureaucrat const & executor) const;
class GradeTooHighException : public std::exception
{
public:
virtual const char* what() const throw();
};
class GradeTooLowException : public std::exception
{
public:
virtual const char* what() const throw();
};
class AlreadySignedException : public std::exception
{
public:
virtual const char* what() const throw();
};
class NotSignedException : public std::exception
{
public:
virtual const char* what() const throw();
};
};
std::ostream &operator<<(std::ostream&, Form&);
#endif | [
"ydngjink1234@gmail.com"
] | ydngjink1234@gmail.com |
7190987d6962462271471d2bf34173b30ab05653 | f56f7dfe684e448f72c32dd4d56dc81dd494dd35 | /thrift/lib/cpp2/transport/http2/client/H2ClientConnection.cpp | f23f7f25a428050fc2ad4d4a141b93ff1f54480f | [
"Apache-2.0"
] | permissive | CHJoanna/fbthrift | 088145e079078ab09d321d101c6cc50c128838b7 | bb1dd6ba08f2fadacb801f968eee50493ab4e801 | refs/heads/master | 2023-03-23T13:20:38.916692 | 2021-03-26T18:45:03 | 2021-03-26T18:46:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,514 | cpp | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thrift/lib/cpp2/transport/http2/client/H2ClientConnection.h>
#include <glog/logging.h>
#include <folly/portability/GFlags.h>
#include <folly/Likely.h>
#include <proxygen/lib/http/codec/HTTP1xCodec.h>
#include <proxygen/lib/http/codec/HTTP2Codec.h>
#include <proxygen/lib/http/codec/TransportDirection.h>
#include <proxygen/lib/http/session/HTTPTransaction.h>
#include <proxygen/lib/utils/WheelTimerInstance.h>
#include <thrift/lib/cpp/transport/TTransportException.h>
#include <thrift/lib/cpp2/transport/core/ThriftClient.h>
#include <thrift/lib/cpp2/transport/http2/client/ThriftTransactionHandler.h>
#include <thrift/lib/cpp2/transport/http2/common/SingleRpcChannel.h>
#include <wangle/acceptor/TransportInfo.h>
#include <algorithm>
namespace apache {
namespace thrift {
using apache::thrift::transport::TTransportException;
using folly::EventBase;
using proxygen::HTTPSessionBase;
using proxygen::HTTPTransaction;
using proxygen::HTTPUpstreamSession;
using proxygen::SettingsList;
using proxygen::WheelTimerInstance;
using std::string;
std::unique_ptr<ClientConnectionIf> H2ClientConnection::newHTTP2Connection(
folly::AsyncTransport::UniquePtr transport,
FlowControlSettings flowControlSettings) {
std::unique_ptr<H2ClientConnection> connection(new H2ClientConnection(
std::move(transport),
std::make_unique<proxygen::HTTP2Codec>(
proxygen::TransportDirection::UPSTREAM),
flowControlSettings));
return std::move(connection);
}
H2ClientConnection::H2ClientConnection(
folly::AsyncTransport::UniquePtr transport,
std::unique_ptr<proxygen::HTTPCodec> codec,
FlowControlSettings flowControlSettings)
: evb_(transport->getEventBase()) {
DCHECK(evb_ && evb_->isInEventBaseThread());
auto localAddress = transport->getLocalAddress();
auto peerAddress = transport->getPeerAddress();
httpSession_ = new HTTPUpstreamSession(
WheelTimerInstance(timeout_, evb_),
std::move(transport),
localAddress,
peerAddress,
std::move(codec),
wangle::TransportInfo(),
this);
httpSession_->setFlowControl(
flowControlSettings.initialReceiveWindow,
flowControlSettings.receiveStreamWindowSize,
flowControlSettings.receiveSessionWindowSize);
// TODO: Improve the way max outging streams is set
setMaxPendingRequests(100000);
httpSession_->startNow();
}
H2ClientConnection::~H2ClientConnection() {
closeNow();
}
std::shared_ptr<ThriftChannelIf> H2ClientConnection::getChannel() {
DCHECK(evb_ && evb_->isInEventBaseThread());
return std::make_shared<SingleRpcChannel>(
*evb_, [this](auto* self) { return this->newTransaction(self); });
}
void H2ClientConnection::setMaxPendingRequests(uint32_t num) {
DCHECK(evb_ && evb_->isInEventBaseThread());
if (httpSession_) {
httpSession_->setMaxConcurrentOutgoingStreams(num);
}
}
void H2ClientConnection::setCloseCallback(
ThriftClient* client, CloseCallback* cb) {
if (cb == nullptr) {
closeCallbacks_.erase(client);
} else {
closeCallbacks_[client] = cb;
}
}
EventBase* H2ClientConnection::getEventBase() const {
return evb_;
}
HTTPTransaction* H2ClientConnection::newTransaction(H2Channel* channel) {
DCHECK(evb_ && evb_->isInEventBaseThread());
if (!httpSession_) {
throw TTransportException(
TTransportException::NOT_OPEN, "HTTPSession is not open");
}
// These objects destroy themselves when done.
auto handler = new ThriftTransactionHandler();
auto txn = httpSession_->newTransactionWithError(handler);
if (txn.hasError()) {
delete handler;
TTransportException ex(TTransportException::NETWORK_ERROR, txn.error());
// Might be able to create another transaction soon
ex.setOptions(TTransportException::CHANNEL_IS_VALID);
throw ex;
}
handler->setChannel(
std::dynamic_pointer_cast<H2Channel>(channel->shared_from_this()));
return txn.value();
}
folly::AsyncTransport* H2ClientConnection::getTransport() {
DCHECK(!evb_ || evb_->isInEventBaseThread());
if (httpSession_) {
return httpSession_->getTransport();
} else {
return nullptr;
}
}
bool H2ClientConnection::good() {
DCHECK(evb_ && evb_->isInEventBaseThread());
auto transport = httpSession_ ? httpSession_->getTransport() : nullptr;
return transport && transport->good();
}
ClientChannel::SaturationStatus H2ClientConnection::getSaturationStatus() {
DCHECK(evb_ && evb_->isInEventBaseThread());
if (httpSession_) {
return ClientChannel::SaturationStatus(
httpSession_->getNumOutgoingStreams(),
httpSession_->getMaxConcurrentOutgoingStreams());
} else {
return ClientChannel::SaturationStatus();
}
}
void H2ClientConnection::attachEventBase(EventBase* evb) {
DCHECK(evb && evb->isInEventBaseThread());
if (httpSession_) {
httpSession_->attachThreadLocals(
evb,
nullptr,
WheelTimerInstance(timeout_, evb),
nullptr,
[](proxygen::HTTPCodecFilter*) {},
nullptr,
nullptr);
}
evb_ = evb;
}
void H2ClientConnection::detachEventBase() {
DCHECK(evb_->isInEventBaseThread());
if (httpSession_) {
httpSession_->detachTransactions();
httpSession_->detachThreadLocals();
}
evb_ = nullptr;
}
bool H2ClientConnection::isDetachable() {
// MultiRpcChannel will always have at least one open stream.
// This is used to leverage multiple rpcs in one stream. We should
// still enable detaching if MultiRpc doesn't have any outstanding
// rpcs and the number of streams is <= 1.
// SingleRpcChannel should only detach if the number of outgoing
// streams == 0. That's how we know there are no pending rpcs to
// be fulfilled.
auto session_isDetachable =
!httpSession_ || httpSession_->getNumOutgoingStreams() == 0;
auto transport = getTransport();
auto transport_isDetachable = !transport || transport->isDetachable();
return transport_isDetachable && session_isDetachable;
}
uint32_t H2ClientConnection::getTimeout() {
return timeout_.count();
}
void H2ClientConnection::setTimeout(uint32_t ms) {
timeout_ = std::chrono::milliseconds(ms);
// TODO: need to change timeout in httpSession_. This functionality
// is also missing in JiaJie's HTTPClientChannel.
}
void H2ClientConnection::closeNow() {
DCHECK(!evb_ || evb_->isInEventBaseThread());
if (httpSession_) {
if (!evb_) {
attachEventBase(folly::EventBaseManager::get()->getEventBase());
}
httpSession_->dropConnection();
httpSession_ = nullptr;
}
}
CLIENT_TYPE H2ClientConnection::getClientType() {
return THRIFT_HTTP_CLIENT_TYPE;
}
void H2ClientConnection::onDestroy(const HTTPSessionBase&) {
DCHECK(evb_ && evb_->isInEventBaseThread());
for (auto& cb : closeCallbacks_) {
cb.second->channelClosed();
}
closeCallbacks_.clear();
httpSession_ = nullptr;
}
} // namespace thrift
} // namespace apache
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
12ca42b2973b3f47f070e1aab04f8911a8593fcc | 1f15c52f532cbbe7b759979640c2361bed3ccfb2 | /library/ProvizWiFi/ProvizData.cpp | a1de4dcc547f5bf8142de9d0b150de2494e1537a | [
"MIT"
] | permissive | cslfiu/SOTA-Skeleton-Code-for-Client | 4888ba0c2506e52617248d31035c3d5e8020d52a | 7eaf7003dfecbbe9f65ca18e2c72c7a083671b12 | refs/heads/master | 2021-09-09T00:37:51.119631 | 2018-03-13T01:10:49 | 2018-03-13T01:10:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 85 | cpp | #include "ProvizData.h"
ProvizData::ProvizData()
{
}
ProvizData::~ProvizData()
{
}
| [
"h.burakyesilyurt@gmail.com"
] | h.burakyesilyurt@gmail.com |
822eebb57ea74e2292be747ffbc060bddc1238a4 | d6c69bd9c770fe1916f6d91f542e6217224102c0 | /nodemcu/Pruebas/s_infrarojo_v01/s_infrarojo_v01.ino | 650b029044c882fafe02eef1046ea9cdee9e46f3 | [] | no_license | novagenio/arduinos | 4cb4521aa68a7a9b57dc7dfbd426081147fc4f7f | bd425ff076d7771871909d25964d26b2f46597b2 | refs/heads/master | 2020-04-13T01:44:28.685163 | 2019-09-29T17:12:32 | 2019-09-29T17:12:32 | 162,882,114 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,527 | ino | // Cantidad de pulsos
#define TRAIN_LENGTH 32
// En microsegundos
#define LOW_LIMIT 600
#define HIGH_LIMIT 1800
#define INIT_LIMIT 4000
#define IN 2
#define LED 13
long start, delta = 0;
uint32_t value;
int pos = 0;
boolean has_value = false;
unsigned int key[10];
void inputPin() {
noInterrupts();
if (has_value) return;
if (digitalRead(IN) == HIGH) {
start = micros();
}
else {
delta = micros() - start;
if (delta < LOW_LIMIT) {
value <<= 1;
value |= 1;
++pos;
}
else if (delta < HIGH_LIMIT) {
value <<= 1;
value |= 0;
++pos;
}
else if (delta > INIT_LIMIT) {
value = 0;
pos = 0;
}
if (pos == TRAIN_LENGTH) {
has_value = true;
}
}
interrupts();
}
void setup()
{
key[0] = 0x9768;
key[1] = 0xCF30;
key[2] = 0xE718;
key[3] = 0x857A;
key[4] = 0xEF10;
key[5] = 0xC738;
key[6] = 0xA55A;
key[7] = 0xBD42;
key[8] = 0xB54A;
key[9] = 0xAD52;
Serial.begin(9600);
pinMode(IN, INPUT);
pinMode(LED, OUTPUT);
digitalWrite(LED, LOW);
attachInterrupt(0, inputPin, CHANGE);
}
void loop()
{
int i;
if (has_value) {
Serial.print("V: ");
Serial.println(value);
Serial.println(value & 0x0000FFFF, HEX);
i = 0;
while(i<10 && (key[i] != (value & 0x0000FFFF))) ++i;
//Serial.println(i);
//while(i--) {
// digitalWrite(LED, HIGH);
// delay(400);
// digitalWrite(LED, LOW);
// delay(200);
//}
Serial.println(i);
has_value = false;
pos = 0;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
374267ef6be99a029b01d9661f12ed44f24cd752 | 9d48ec858357416d2910a5924c7add1f962bad44 | /chatClient/chatWorks.cpp | db1a60d6ca3a77ef192e92ccfca540ba4106c37e | [] | no_license | andrewly/3574_HW7 | 90a7ed118384988c2ddf8898724acc78b8838e79 | cf8a58d0ca8f48769aaf200b47489a1a93d21a2e | refs/heads/master | 2020-05-05T04:11:22.004404 | 2015-05-04T21:23:43 | 2015-05-04T21:23:43 | 34,747,081 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 709 | cpp | #include "chatWorks.h"
ChatWork::ChatWork(QString name)
{
userName = name;
//connect(Server,SIGNAL(messages(QString, QString)),this,SLOT(receving(QString, QString)));
//connect(Server,SIGNAL(messages(QString, QString)),this,SLOT(newMembers(QString)));
}
WorkObject::~WorkObject()
{
}
void WorkObject::sendMessage(QString chat, QString person)
{
//sends a signal for the message
qDebug() << "Doing Work in thread: " << QObject::thread();
emit sending(chat, person);
}
void WorkObject::newMemebers(QString member)
{
//adds the new member to the list of targets.
userChat.addItem(member);
}
void WorkObject::exitChat();
{
//sends the exit signal to remove from list.
emit exit();
}
| [
"akbor492@vt.edu"
] | akbor492@vt.edu |
459c62c1e9a0a48868e8c5d3dd3db11574730d01 | b39b17291b7976722ccb325ad569ba5d8e6be76e | /Grafy/include/graphs/adjacency_matrix_graph.hpp | 14bb52f14b06f7df72d5b8d0aaf1d160a37ca897 | [] | no_license | Adrian-Graczyk/PAMSI | fe86d702612daa036dd5b1c458f0628735608163 | 466f8895026778d520bbb8962fbf9007ecda24d3 | refs/heads/main | 2023-05-20T22:25:34.995557 | 2021-06-06T21:03:40 | 2021-06-06T21:03:40 | 344,514,717 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 656 | hpp | #ifndef ADJACENCY_MATRIX_GRAPH_HPP_
#define ADJACENCY_MATRIX_GRAPH_HPP_
#include <memory>
#include <vector>
#include "graphs/graph.hpp"
class AdjacencyMatrixGraph : public Graph
{
public:
std::vector<std::vector<int>> Matrix;
static std::unique_ptr<Graph> createGraph(std::istream& is);
//metody przesłaniające odpowiednie metody wirtualne z klasy bazowej Graph
virtual int get_Weight(int i, int j) override;
std::vector<int> neighbours(int i) override;
virtual bool check_zero(int i, int j) override;
};
std::ostream& operator<<(std::ostream& os, const AdjacencyMatrixGraph& Matrix);
#endif /* ADJACENCY_MATRIX_GRAPH_HPP_ */
| [
"adrian@DESKTOP-BS4R2K2.localdomain"
] | adrian@DESKTOP-BS4R2K2.localdomain |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.