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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a93fcf8e1d70ce0f7c31f057a90c0ca9debadd8f | 24bc4990e9d0bef6a42a6f86dc783785b10dbd42 | /third_party/blink/renderer/modules/webcodecs/background_readback.cc | 77d22d9c0bd9c2fa882c53c158395dda284142e3 | [
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"Apache-2.0",
"MIT",
"BSD-3-Clause"
] | permissive | nwjs/chromium.src | 7736ce86a9a0b810449a3b80a4af15de9ef9115d | 454f26d09b2f6204c096b47f778705eab1e3ba46 | refs/heads/nw75 | 2023-08-31T08:01:39.796085 | 2023-04-19T17:25:53 | 2023-04-19T17:25:53 | 50,512,158 | 161 | 201 | BSD-3-Clause | 2023-05-08T03:19:09 | 2016-01-27T14:17:03 | null | UTF-8 | C++ | false | false | 15,686 | cc | // Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/modules/webcodecs/background_readback.h"
#include "base/feature_list.h"
#include "base/numerics/safe_conversions.h"
#include "base/task/task_traits.h"
#include "base/threading/thread_checker.h"
#include "base/trace_event/common/trace_event_common.h"
#include "base/trace_event/trace_event.h"
#include "components/viz/common/gpu/raster_context_provider.h"
#include "gpu/command_buffer/client/raster_interface.h"
#include "media/base/bind_to_current_loop.h"
#include "media/base/video_frame_pool.h"
#include "media/base/video_util.h"
#include "media/base/wait_and_replace_sync_token_client.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_audio_data_init.h"
#include "third_party/blink/renderer/modules/webaudio/audio_buffer.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/graphics/gpu/shared_gpu_context.h"
#include "third_party/blink/renderer/platform/graphics/web_graphics_context_3d_provider_util.h"
#include "third_party/blink/renderer/platform/heap/cross_thread_handle.h"
#include "third_party/blink/renderer/platform/wtf/cross_thread_copier_base.h"
#include "third_party/blink/renderer/platform/wtf/cross_thread_copier_gfx.h"
#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/thread_safe_ref_counted.h"
namespace {
bool CanUseRgbReadback(media::VideoFrame& frame) {
return media::IsRGB(frame.format()) && (frame.NumTextures() == 1);
}
SkImageInfo GetImageInfoForFrame(const media::VideoFrame& frame,
const gfx::Size& size) {
SkColorType color_type =
SkColorTypeForPlane(frame.format(), media::VideoFrame::kARGBPlane);
SkAlphaType alpha_type = kUnpremul_SkAlphaType;
return SkImageInfo::Make(size.width(), size.height(), color_type, alpha_type);
}
gpu::raster::RasterInterface* GetSharedGpuRasterInterface() {
auto wrapper = blink::SharedGpuContext::ContextProviderWrapper();
if (wrapper && wrapper->ContextProvider()) {
auto* raster_provider = wrapper->ContextProvider()->RasterContextProvider();
if (raster_provider)
return raster_provider->RasterInterface();
}
return nullptr;
}
// Controls how asyc VideoFrame.copyTo() works
// Enabled - RI::ReadbackARGBPixelsAsync()
// Disabled - simply call sync readback on a separate thread.
BASE_FEATURE(kTrullyAsyncRgbVideoFrameCopyTo,
"TrullyAsyncRgbVideoFrameCopyTo",
base::FEATURE_ENABLED_BY_DEFAULT);
} // namespace
namespace WTF {
template <>
struct CrossThreadCopier<blink::VideoFrameLayout>
: public CrossThreadCopierPassThrough<blink::VideoFrameLayout> {
STATIC_ONLY(CrossThreadCopier);
};
template <>
struct CrossThreadCopier<base::span<uint8_t>>
: public CrossThreadCopierPassThrough<base::span<uint8_t>> {
STATIC_ONLY(CrossThreadCopier);
};
} // namespace WTF
namespace blink {
// This is a part of BackgroundReadback that lives and dies on the worker's
// thread and does all the actual work of creating GPU context and calling
// sync readback functions.
class SyncReadbackThread
: public WTF::ThreadSafeRefCounted<SyncReadbackThread> {
public:
SyncReadbackThread();
scoped_refptr<media::VideoFrame> ReadbackToFrame(
scoped_refptr<media::VideoFrame> frame);
bool ReadbackToBuffer(scoped_refptr<media::VideoFrame> frame,
const gfx::Rect src_rect,
const VideoFrameLayout dest_layout,
base::span<uint8_t> dest_buffer);
private:
bool LazyInitialize();
media::VideoFramePool result_frame_pool_;
std::unique_ptr<WebGraphicsContext3DProvider> context_provider_;
THREAD_CHECKER(thread_checker_);
};
BackgroundReadback::BackgroundReadback(base::PassKey<BackgroundReadback> key,
ExecutionContext& context)
: Supplement<ExecutionContext>(context),
sync_readback_impl_(base::MakeRefCounted<SyncReadbackThread>()),
worker_task_runner_(base::ThreadPool::CreateSingleThreadTaskRunner(
{base::WithBaseSyncPrimitives()},
base::SingleThreadTaskRunnerThreadMode::DEDICATED)) {}
BackgroundReadback::~BackgroundReadback() {
worker_task_runner_->ReleaseSoon(FROM_HERE, std::move(sync_readback_impl_));
}
const char BackgroundReadback::kSupplementName[] = "BackgroundReadback";
// static
BackgroundReadback* BackgroundReadback::From(ExecutionContext& context) {
BackgroundReadback* supplement =
Supplement<ExecutionContext>::From<BackgroundReadback>(context);
if (!supplement) {
supplement = MakeGarbageCollected<BackgroundReadback>(
base::PassKey<BackgroundReadback>(), context);
Supplement<ExecutionContext>::ProvideTo(context, supplement);
}
return supplement;
}
void BackgroundReadback::ReadbackTextureBackedFrameToMemoryFrame(
scoped_refptr<media::VideoFrame> txt_frame,
ReadbackToFrameDoneCallback result_cb) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(txt_frame);
if (CanUseRgbReadback(*txt_frame)) {
ReadbackRGBTextureBackedFrameToMemory(std::move(txt_frame),
std::move(result_cb));
return;
}
ReadbackOnThread(std::move(txt_frame), std::move(result_cb));
}
void BackgroundReadback::ReadbackTextureBackedFrameToBuffer(
scoped_refptr<media::VideoFrame> txt_frame,
const gfx::Rect& src_rect,
const VideoFrameLayout& dest_layout,
base::span<uint8_t> dest_buffer,
ReadbackDoneCallback done_cb) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(txt_frame);
if (base::FeatureList::IsEnabled(kTrullyAsyncRgbVideoFrameCopyTo) &&
CanUseRgbReadback(*txt_frame)) {
ReadbackRGBTextureBackedFrameToBuffer(txt_frame, src_rect, dest_layout,
dest_buffer, std::move(done_cb));
return;
}
ReadbackOnThread(std::move(txt_frame), src_rect, dest_layout, dest_buffer,
std::move(done_cb));
}
void BackgroundReadback::ReadbackOnThread(
scoped_refptr<media::VideoFrame> txt_frame,
ReadbackToFrameDoneCallback result_cb) {
worker_task_runner_->PostTaskAndReplyWithResult(
FROM_HERE,
ConvertToBaseOnceCallback(
CrossThreadBindOnce(&SyncReadbackThread::ReadbackToFrame,
sync_readback_impl_, std::move(txt_frame))),
std::move(result_cb));
}
void BackgroundReadback::ReadbackOnThread(
scoped_refptr<media::VideoFrame> txt_frame,
const gfx::Rect& src_rect,
const VideoFrameLayout& dest_layout,
base::span<uint8_t> dest_buffer,
ReadbackDoneCallback done_cb) {
worker_task_runner_->PostTaskAndReplyWithResult(
FROM_HERE,
ConvertToBaseOnceCallback(CrossThreadBindOnce(
&SyncReadbackThread::ReadbackToBuffer, sync_readback_impl_,
std::move(txt_frame), src_rect, dest_layout, dest_buffer)),
std::move(done_cb));
}
void BackgroundReadback::ReadbackRGBTextureBackedFrameToMemory(
scoped_refptr<media::VideoFrame> txt_frame,
ReadbackToFrameDoneCallback result_cb) {
DCHECK(CanUseRgbReadback(*txt_frame));
SkImageInfo info = GetImageInfoForFrame(*txt_frame, txt_frame->coded_size());
const auto format = media::VideoPixelFormatFromSkColorType(
info.colorType(), media::IsOpaque(txt_frame->format()));
auto result = result_frame_pool_.CreateFrame(
format, txt_frame->coded_size(), txt_frame->visible_rect(),
txt_frame->natural_size(), txt_frame->timestamp());
auto* ri = GetSharedGpuRasterInterface();
if (!ri || !result) {
media::BindToCurrentLoop(std::move(std::move(result_cb))).Run(nullptr);
return;
}
TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(
"media", "ReadbackRGBTextureBackedFrameToMemory", txt_frame.get(),
"timestamp", txt_frame->timestamp());
uint8_t* dst_pixels =
result->GetWritableVisibleData(media::VideoFrame::kARGBPlane);
int rgba_stide = result->stride(media::VideoFrame::kARGBPlane);
DCHECK_GT(rgba_stide, 0);
auto origin = txt_frame->metadata().texture_origin_is_top_left
? kTopLeft_GrSurfaceOrigin
: kBottomLeft_GrSurfaceOrigin;
gfx::Point src_point;
gpu::MailboxHolder mailbox_holder = txt_frame->mailbox_holder(0);
ri->WaitSyncTokenCHROMIUM(mailbox_holder.sync_token.GetConstData());
gfx::Size texture_size = txt_frame->coded_size();
ri->ReadbackARGBPixelsAsync(
mailbox_holder.mailbox, mailbox_holder.texture_target, origin,
texture_size, src_point, info, base::saturated_cast<GLuint>(rgba_stide),
dst_pixels,
WTF::BindOnce(&BackgroundReadback::OnARGBPixelsFrameReadCompleted,
MakeUnwrappingCrossThreadHandle(this), std::move(result_cb),
std::move(txt_frame), std::move(result)));
}
void BackgroundReadback::OnARGBPixelsFrameReadCompleted(
ReadbackToFrameDoneCallback result_cb,
scoped_refptr<media::VideoFrame> txt_frame,
scoped_refptr<media::VideoFrame> result_frame,
bool success) {
TRACE_EVENT_NESTABLE_ASYNC_END1("media",
"ReadbackRGBTextureBackedFrameToMemory",
txt_frame.get(), "success", success);
if (!success) {
ReadbackOnThread(std::move(txt_frame), std::move(result_cb));
return;
}
if (auto* ri = GetSharedGpuRasterInterface()) {
media::WaitAndReplaceSyncTokenClient client(ri);
txt_frame->UpdateReleaseSyncToken(&client);
} else {
success = false;
}
result_frame->set_color_space(txt_frame->ColorSpace());
result_frame->metadata().MergeMetadataFrom(txt_frame->metadata());
result_frame->metadata().ClearTextureFrameMedatada();
std::move(result_cb).Run(success ? std::move(result_frame) : nullptr);
}
void BackgroundReadback::ReadbackRGBTextureBackedFrameToBuffer(
scoped_refptr<media::VideoFrame> txt_frame,
const gfx::Rect& src_rect,
const VideoFrameLayout& dest_layout,
base::span<uint8_t> dest_buffer,
ReadbackDoneCallback done_cb) {
if (dest_layout.NumPlanes() != 1) {
NOTREACHED()
<< "This method shouldn't be called on anything but RGB frames";
media::BindToCurrentLoop(std::move(std::move(done_cb))).Run(false);
return;
}
auto* ri = GetSharedGpuRasterInterface();
if (!ri) {
media::BindToCurrentLoop(std::move(std::move(done_cb))).Run(false);
return;
}
uint32_t offset = dest_layout.Offset(0);
uint32_t stride = dest_layout.Stride(0);
uint8_t* dst_pixels = dest_buffer.data() + offset;
size_t max_bytes_written = stride * src_rect.height();
if (stride <= 0 || max_bytes_written > dest_buffer.size()) {
DLOG(ERROR) << "Buffer is not sufficiently large for readback";
media::BindToCurrentLoop(std::move(std::move(done_cb))).Run(false);
return;
}
TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(
"media", "ReadbackRGBTextureBackedFrameToBuffer", txt_frame.get(),
"timestamp", txt_frame->timestamp());
SkImageInfo info = GetImageInfoForFrame(*txt_frame, src_rect.size());
gfx::Point src_point = src_rect.origin();
auto origin = txt_frame->metadata().texture_origin_is_top_left
? kTopLeft_GrSurfaceOrigin
: kBottomLeft_GrSurfaceOrigin;
gpu::MailboxHolder mailbox_holder = txt_frame->mailbox_holder(0);
ri->WaitSyncTokenCHROMIUM(mailbox_holder.sync_token.GetConstData());
gfx::Size texture_size = txt_frame->coded_size();
ri->ReadbackARGBPixelsAsync(
mailbox_holder.mailbox, mailbox_holder.texture_target, origin,
texture_size, src_point, info, base::saturated_cast<GLuint>(stride),
dst_pixels,
WTF::BindOnce(&BackgroundReadback::OnARGBPixelsBufferReadCompleted,
MakeUnwrappingCrossThreadHandle(this), std::move(txt_frame),
src_rect, dest_layout, dest_buffer, std::move(done_cb)));
}
void BackgroundReadback::OnARGBPixelsBufferReadCompleted(
scoped_refptr<media::VideoFrame> txt_frame,
const gfx::Rect& src_rect,
const VideoFrameLayout& dest_layout,
base::span<uint8_t> dest_buffer,
ReadbackDoneCallback done_cb,
bool success) {
TRACE_EVENT_NESTABLE_ASYNC_END1("media",
"ReadbackRGBTextureBackedFrameToBuffer",
txt_frame.get(), "success", success);
if (!success) {
ReadbackOnThread(std::move(txt_frame), src_rect, dest_layout, dest_buffer,
std::move(done_cb));
return;
}
if (auto* ri = GetSharedGpuRasterInterface()) {
media::WaitAndReplaceSyncTokenClient client(ri);
txt_frame->UpdateReleaseSyncToken(&client);
} else {
success = false;
}
std::move(done_cb).Run(success);
}
SyncReadbackThread::SyncReadbackThread() {
DETACH_FROM_THREAD(thread_checker_);
}
bool SyncReadbackThread::LazyInitialize() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (context_provider_)
return true;
Platform::ContextAttributes attributes;
attributes.enable_raster_interface = true;
attributes.support_grcontext = true;
attributes.prefer_low_power_gpu = true;
Platform::GraphicsInfo info;
context_provider_ = CreateOffscreenGraphicsContext3DProvider(
attributes, &info, KURL("chrome://BackgroundReadback"));
if (!context_provider_) {
DLOG(ERROR) << "Can't create context provider.";
return false;
}
if (!context_provider_->BindToCurrentSequence()) {
DLOG(ERROR) << "Can't bind context provider.";
context_provider_ = nullptr;
return false;
}
return true;
}
scoped_refptr<media::VideoFrame> SyncReadbackThread::ReadbackToFrame(
scoped_refptr<media::VideoFrame> frame) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (!LazyInitialize())
return nullptr;
auto* ri = context_provider_->RasterInterface();
auto* gr_context = context_provider_->GetGrContext();
return media::ReadbackTextureBackedFrameToMemorySync(*frame, ri, gr_context,
&result_frame_pool_);
}
bool SyncReadbackThread::ReadbackToBuffer(
scoped_refptr<media::VideoFrame> frame,
const gfx::Rect src_rect,
const VideoFrameLayout dest_layout,
base::span<uint8_t> dest_buffer) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
TRACE_EVENT1("media", "SyncReadbackThread::ReadbackToBuffer", "timestamp",
frame->timestamp());
if (!LazyInitialize() || !frame)
return false;
auto* ri = context_provider_->RasterInterface();
auto* gr_context = context_provider_->GetGrContext();
if (!ri)
return false;
for (wtf_size_t i = 0; i < dest_layout.NumPlanes(); i++) {
const gfx::Size sample_size =
media::VideoFrame::SampleSize(dest_layout.Format(), i);
gfx::Rect plane_src_rect(src_rect.x() / sample_size.width(),
src_rect.y() / sample_size.height(),
src_rect.width() / sample_size.width(),
src_rect.height() / sample_size.height());
uint8_t* dest_pixels = dest_buffer.data() + dest_layout.Offset(i);
if (!media::ReadbackTexturePlaneToMemorySync(
*frame, i, plane_src_rect, dest_pixels, dest_layout.Stride(i), ri,
gr_context)) {
// It's possible to fail after copying some but not all planes, leaving
// the output buffer in a corrupt state D:
return false;
}
}
return true;
}
} // namespace blink
| [
"roger@nwjs.io"
] | roger@nwjs.io |
42fd2295bf43a0cf85b3a9a0f21ef184acd3d99c | 21840aca65db3330b732de6902974e95c5dce1a8 | /CPPGenerated/tensorflow/compiler/xla/xla_data.grpc.pb.cc | f4db233058c1211acd5c92b3ace7ca02e1e669c4 | [
"MIT"
] | permissive | nubbel/swift-tensorflow | 818a53a1f16fed71066018801fa5071b4397ff06 | 3385401ed76ae8a0eca10f2757bb43b8a46f3d46 | refs/heads/master | 2021-01-17T15:46:58.033441 | 2017-10-31T15:01:51 | 2017-10-31T15:01:51 | 69,651,119 | 20 | 3 | null | 2017-04-25T15:28:40 | 2016-09-30T08:58:24 | Swift | UTF-8 | C++ | false | true | 676 | cc | // Generated by the gRPC C++ plugin.
// If you make any local change, they will be lost.
// source: tensorflow/compiler/xla/xla_data.proto
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/compiler/xla/xla_data.grpc.pb.h"
#include <grpc++/impl/codegen/async_stream.h>
#include <grpc++/impl/codegen/async_unary_call.h>
#include <grpc++/impl/codegen/channel_interface.h>
#include <grpc++/impl/codegen/client_unary_call.h>
#include <grpc++/impl/codegen/method_handler_impl.h>
#include <grpc++/impl/codegen/rpc_service_method.h>
#include <grpc++/impl/codegen/service_type.h>
#include <grpc++/impl/codegen/sync_stream.h>
namespace xla {
} // namespace xla
| [
"jp@fieldstormapp.com"
] | jp@fieldstormapp.com |
914ba8528d6a772e072025cbbc714ccc15453b5b | 6a151d774c8230cf2a6a04cd6566c5aa813f9a3a | /Codeforces/City Day cf 1199A.cpp | a3a9c3edf31dfcdf1d056d334e827c562741f597 | [] | no_license | RakibulRanak/Solved-ACM-problems | fdc5b39bdbe1bcc06f95c2a77478534362dca257 | 7d28d4da7bb01989f741228c4039a96ab307a8a6 | refs/heads/master | 2021-07-01T09:50:02.039776 | 2020-10-11T20:46:28 | 2020-10-11T20:46:28 | 168,976,930 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,054 | cpp | #include<bits/stdc++.h>
using namespace std;
int ara[100005];
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n,x,y;
cin>>n>>x>>y;
int ara[n];
for(int i=0;i<n;i++)
cin>>ara[i];
for(int i=0;i<n;i++)
{
int left=0;
int right=0;
int day=ara[i];
bool l=false,r=false;
while(left<x)
{
left++;
if(i-left<0)
{
l=true;
break;
}
if(ara[i-left]<=day)
{
left=-1;
break;
}
//cout<<i<<" "<<left<<endl;
}
if(left==x){
l=true;
//cout<<"left true"<<endl;
}
while(right<y)
{
right++;
if(i+right>=n)
{
r=true;
break;
}
if(ara[i+right]<=day)
{
right=-1;
break;
}
}
if(right==y ){
r=true;
}
if(r&&l)
{
cout<<i+1<<endl;
return 0;
}
}
return 0;
} | [
"rakibulhasanranak1@gmail.com"
] | rakibulhasanranak1@gmail.com |
bfa1a0bb42b8ee3efc62f35081dc08e7782203e5 | 19cae379f38528b27fb1321c127302ca245ec536 | /Sources/CeleXDemo/videostream.cpp | 8cdc3e6703af666cdb673b99815fd31f233f269e | [
"Apache-2.0"
] | permissive | shawnzhangpersonal/CeleX5-MIPI | fb6134e534bea33b11a2d3a1669d39a550fbe2cb | 8029430968f0f952a6fec5f918007d0fdba30518 | refs/heads/master | 2020-05-04T04:59:48.912556 | 2019-03-22T10:21:18 | 2019-03-22T10:21:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,913 | cpp | #include "videostream.h"
VideoStream::VideoStream()
{
frameCount=0;
mydata = new unsigned char[DATASIZE];
}
VideoStream::~VideoStream()
{
}
AVStream* VideoStream::addVideoStream(AVFormatContext *oc, enum AVCodecID codec_id)//init AVFormatContext struct for output
{
AVStream *st;
AVCodec *codec;
st = avformat_new_stream(oc, NULL);
if (!st)
{
qDebug("Could not alloc stream\n");
exit(1);
}
codec = avcodec_find_encoder(codec_id);//find mjpeg decoders
if (!codec)
{
qDebug("codec not found\n");
exit(1);
}
avcodec_get_context_defaults3(st->codec, codec);
st->codec->bit_rate = 64000;//bit
st->codec->width = 1280;
st->codec->height = 800;
st->codec->time_base.den = 25;//fps
st->codec->time_base.num = 1;
st->codec->pix_fmt = AV_PIX_FMT_YUV420P;//format
st->codec->codec_tag = 0;
if (oc->oformat->flags & AVFMT_GLOBALHEADER)
st->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
return st;
}
bool VideoStream::avWriterInit(const char* out_filename)
{
int ret;
av_register_all();//init decode
avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, out_filename);//init AVFormatContext struct for output
if (!ofmt_ctx)
{
qDebug("Could not create output context\n");
return false;
}
AVStream *outStream = addVideoStream(ofmt_ctx, AV_CODEC_ID_MJPEG);//create output video stream
// av_dump_format(ofmt_ctx, 0, out_filename, 1); //display the video info
if (!(ofmt_ctx->oformat->flags & AVFMT_NOFILE))//open the output file
{
ret = avio_open(&ofmt_ctx->pb, out_filename, AVIO_FLAG_WRITE);
if (ret < 0) {
qDebug("Could not open output file '%s'", out_filename);
return false;
}
}
AVDictionary *opt = 0;
av_dict_set_int(&opt, "video_track_timescale", 25, 0); //set the fps!!!
if (avformat_write_header(ofmt_ctx, &opt) < 0)//Write file header
{
printf("Error occurred when opening output file\n");
return false;
}
av_init_packet(&pkt);
pkt.flags |= AV_PKT_FLAG_KEY;
pkt.stream_index = outStream->index;
return true;
}
void VideoStream::avWtiter(char* buffer)
{
FILE *file;
file = fopen(buffer, "rb");
pkt.size = fread(mydata, 1, DATASIZE, file);
pkt.data = mydata;
if (av_interleaved_write_frame(ofmt_ctx, &pkt) < 0) //write to video file
{
qDebug("Error muxing packet\n");
}
// qDebug("Write %8d frames to output file\n", frameCount);
frameCount++;
fclose(file);
}
bool VideoStream::avWriterRelease()
{
av_free_packet(&pkt);
av_write_trailer(ofmt_ctx);//Write file trailer
if (ofmt_ctx && !(ofmt_ctx->oformat->flags & AVFMT_NOFILE))
avio_close(ofmt_ctx->pb);//close video file
avformat_free_context(ofmt_ctx);//release struct
return true;
}
| [
"xiaozheng.mou@celepixel.com"
] | xiaozheng.mou@celepixel.com |
a002ac54cbe3e040bef81cd7f48957c288562da0 | 45ed582646b1cb3b36e56a4c523afb62d3da43b2 | /trunk/refactory/decorator/single_decorator/bigger_decorator.cpp | 2d1652ad1df165eb41beb49e258468a2fa6a7e73 | [] | no_license | zhengxiexie/chess | 3056486f90412a228b99a64b7a44b17697e49611 | 69b035469259d4103ae79785263daf3fa508f173 | refs/heads/master | 2018-12-28T18:16:40.864327 | 2014-01-18T14:02:59 | 2014-01-18T14:02:59 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,752 | cpp | /*
* bigger_decorator.cpp
*
* Created on: 2013-5-31
* Author: guoweijiang
*/
#include "bigger_decorator.h"
BiggerThanDecorator::BiggerThanDecorator():AbstractSingleDecorator()
{
this->is_bigger_and_equal = false;
this->is_special = false;
}
BiggerThanDecorator::~BiggerThanDecorator()
{
}
/*
* 实现抽象接口:
*/
int BiggerThanDecorator::custom_result_set_query(bson* query)
{
int size = this->fitler_conditions.size();
LOGD("[GWJ] %s: filter_size[%d]", __FUNCTION__, size);
if(size > 0)
{
const char* column_name = this->fitler_conditions[0].table_column;
if(column_name == NULL)
{
LOGD("[GWJ] %s: end. Error filter column name!!", __FUNCTION__);
return -1;
}
LOGD("[GWJ] %s: start. column[%s], size[%d]", __FUNCTION__, column_name, size);
bson_append_start_object(query, column_name);
if(this->is_bigger_and_equal)
{
bson_append_string(query, "$gte", this->fitler_conditions[0].value);
LOGD("[GWJ] %s: [%s] bigger and equal[%s]",
__FUNCTION__, column_name, this->fitler_conditions[0].value);
}
else
{
bson_append_string(query, "$gt", this->fitler_conditions[0].value);
LOGD("[GWJ] %s: [%s] bigger than[%s]",
__FUNCTION__, column_name, this->fitler_conditions[0].value);
}
bson_append_finish_object(query);
}
else if(size == 0)
{
LOGD("[GWJ] %s: BiggerThanDecorator no filter Error!", __FUNCTION__);
return -1;
}
LOGD("[GWJ] %s: BiggerThanDecorator end", __FUNCTION__);
return 0;
}
| [
"zhengxiexie@126.com"
] | zhengxiexie@126.com |
02cc555ba0303bbec02b2b2770b65f014d26ebe1 | aa41acccf53d4a11fd408d82061a4da76c9657e2 | /src/EssosIntegration.cpp | ac9e43c2bd4d838b326b8747343814e423311dbc | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | rdkcentral/Flutter-ESSOS | 1d0806f7cbd671ad5b1f61766319c0194ffd5e5e | 26cf005864fc831bf3a1404431a2cf1b6a4585e8 | refs/heads/master | 2023-04-09T13:18:09.087787 | 2021-04-01T12:43:05 | 2021-04-01T12:43:05 | 294,380,303 | 0 | 2 | NOASSERTION | 2021-04-01T12:43:06 | 2020-09-10T10:41:11 | C++ | UTF-8 | C++ | false | false | 2,312 | cpp | /*
* If not stated otherwise in this file or this component's LICENSE file the
* following copyright and licenses apply:
*
* Copyright 2020 RDK Management
*
* 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 "EssosIntegration.h"
#include <stdlib.h>
#include <cstdlib>
#include <stdio.h>
static EssTerminateListener terminateListener =
{
//terminated
[](void* /*data*/) {
//_exit(-1);
exit(-1);
}
};
//this callback is invoked with the new width and height values
void displaySize( void *userData, int width, int height )
{
EssCtx *ctx = (EssCtx*)userData;
fprintf(stderr,"essos: display size changed: %dx%d\n", width, height);
EssContextResizeWindow( ctx, width, height );
}
static EssSettingsListener settingsListener=
{
displaySize
};
EssCtxHolder* EssCtxHolder::mInstance;
EssCtxHolder::EssCtxHolder()
: mEssCtx(EssContextCreate())
{
bool error = false;
if( !EssContextSetSettingsListener(mEssCtx, mEssCtx, &settingsListener) )
{
error = true;
}
else if ( !EssContextInit(mEssCtx) )
{
error = true;
}
else if ( !EssContextSetTerminateListener(mEssCtx, 0, &terminateListener) )
{
error = true;
}
if ( error )
{
const char *detail = EssContextGetLastErrorDetail(mEssCtx);
fprintf(stderr, "Essos error: '%s'\n", detail);
}
}
EssCtxHolder::~EssCtxHolder()
{
stopDispatching();
EssContextDestroy(mEssCtx);
}
EssCtxHolder* EssCtxHolder::instance()
{
if( !mInstance )
{
mInstance = new EssCtxHolder;
}
return mInstance;
}
bool EssCtxHolder::startDispatching()
{
if ( !EssContextStart(mEssCtx) )
return false;
return true;
}
void EssCtxHolder::stopDispatching()
{
EssContextStop(mEssCtx);
}
| [
"Lekshmi_Renuka@comcast.com"
] | Lekshmi_Renuka@comcast.com |
0392f3890f70bf446cdd090072602aba3b7eb3b7 | 797f2f44800628e6a3b623e85ce46b18e6f9fe1d | /devel/include/velodyne_pointcloud/CloudNodeConfig.h | 9f67f7e25f9189984f72f0b340403e7ec17a3eb9 | [] | no_license | enginBozkurt/these | e6d6bb35e7b2272e07eefbaca9faeb8e39c7c8da | ab6e7ded7a5e646a8eaf34fd4211f61d15f7ba78 | refs/heads/master | 2022-06-16T20:05:12.038172 | 2020-05-12T13:07:40 | 2020-05-12T13:07:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,408 | h | //#line 2 "/opt/ros/melodic/share/dynamic_reconfigure/cmake/../templates/ConfigType.h.template"
// *********************************************************
//
// File autogenerated for the velodyne_pointcloud package
// by the dynamic_reconfigure package.
// Please do not edit.
//
// ********************************************************/
#ifndef __velodyne_pointcloud__CLOUDNODECONFIG_H__
#define __velodyne_pointcloud__CLOUDNODECONFIG_H__
#if __cplusplus >= 201103L
#define DYNAMIC_RECONFIGURE_FINAL final
#else
#define DYNAMIC_RECONFIGURE_FINAL
#endif
#include <dynamic_reconfigure/config_tools.h>
#include <limits>
#include <ros/node_handle.h>
#include <dynamic_reconfigure/ConfigDescription.h>
#include <dynamic_reconfigure/ParamDescription.h>
#include <dynamic_reconfigure/Group.h>
#include <dynamic_reconfigure/config_init_mutex.h>
#include <boost/any.hpp>
namespace velodyne_pointcloud
{
class CloudNodeConfigStatics;
class CloudNodeConfig
{
public:
class AbstractParamDescription : public dynamic_reconfigure::ParamDescription
{
public:
AbstractParamDescription(std::string n, std::string t, uint32_t l,
std::string d, std::string e)
{
name = n;
type = t;
level = l;
description = d;
edit_method = e;
}
virtual void clamp(CloudNodeConfig &config, const CloudNodeConfig &max, const CloudNodeConfig &min) const = 0;
virtual void calcLevel(uint32_t &level, const CloudNodeConfig &config1, const CloudNodeConfig &config2) const = 0;
virtual void fromServer(const ros::NodeHandle &nh, CloudNodeConfig &config) const = 0;
virtual void toServer(const ros::NodeHandle &nh, const CloudNodeConfig &config) const = 0;
virtual bool fromMessage(const dynamic_reconfigure::Config &msg, CloudNodeConfig &config) const = 0;
virtual void toMessage(dynamic_reconfigure::Config &msg, const CloudNodeConfig &config) const = 0;
virtual void getValue(const CloudNodeConfig &config, boost::any &val) const = 0;
};
typedef boost::shared_ptr<AbstractParamDescription> AbstractParamDescriptionPtr;
typedef boost::shared_ptr<const AbstractParamDescription> AbstractParamDescriptionConstPtr;
// Final keyword added to class because it has virtual methods and inherits
// from a class with a non-virtual destructor.
template <class T>
class ParamDescription DYNAMIC_RECONFIGURE_FINAL : public AbstractParamDescription
{
public:
ParamDescription(std::string a_name, std::string a_type, uint32_t a_level,
std::string a_description, std::string a_edit_method, T CloudNodeConfig::* a_f) :
AbstractParamDescription(a_name, a_type, a_level, a_description, a_edit_method),
field(a_f)
{}
T (CloudNodeConfig::* field);
virtual void clamp(CloudNodeConfig &config, const CloudNodeConfig &max, const CloudNodeConfig &min) const
{
if (config.*field > max.*field)
config.*field = max.*field;
if (config.*field < min.*field)
config.*field = min.*field;
}
virtual void calcLevel(uint32_t &comb_level, const CloudNodeConfig &config1, const CloudNodeConfig &config2) const
{
if (config1.*field != config2.*field)
comb_level |= level;
}
virtual void fromServer(const ros::NodeHandle &nh, CloudNodeConfig &config) const
{
nh.getParam(name, config.*field);
}
virtual void toServer(const ros::NodeHandle &nh, const CloudNodeConfig &config) const
{
nh.setParam(name, config.*field);
}
virtual bool fromMessage(const dynamic_reconfigure::Config &msg, CloudNodeConfig &config) const
{
return dynamic_reconfigure::ConfigTools::getParameter(msg, name, config.*field);
}
virtual void toMessage(dynamic_reconfigure::Config &msg, const CloudNodeConfig &config) const
{
dynamic_reconfigure::ConfigTools::appendParameter(msg, name, config.*field);
}
virtual void getValue(const CloudNodeConfig &config, boost::any &val) const
{
val = config.*field;
}
};
class AbstractGroupDescription : public dynamic_reconfigure::Group
{
public:
AbstractGroupDescription(std::string n, std::string t, int p, int i, bool s)
{
name = n;
type = t;
parent = p;
state = s;
id = i;
}
std::vector<AbstractParamDescriptionConstPtr> abstract_parameters;
bool state;
virtual void toMessage(dynamic_reconfigure::Config &msg, const boost::any &config) const = 0;
virtual bool fromMessage(const dynamic_reconfigure::Config &msg, boost::any &config) const =0;
virtual void updateParams(boost::any &cfg, CloudNodeConfig &top) const= 0;
virtual void setInitialState(boost::any &cfg) const = 0;
void convertParams()
{
for(std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = abstract_parameters.begin(); i != abstract_parameters.end(); ++i)
{
parameters.push_back(dynamic_reconfigure::ParamDescription(**i));
}
}
};
typedef boost::shared_ptr<AbstractGroupDescription> AbstractGroupDescriptionPtr;
typedef boost::shared_ptr<const AbstractGroupDescription> AbstractGroupDescriptionConstPtr;
// Final keyword added to class because it has virtual methods and inherits
// from a class with a non-virtual destructor.
template<class T, class PT>
class GroupDescription DYNAMIC_RECONFIGURE_FINAL : public AbstractGroupDescription
{
public:
GroupDescription(std::string a_name, std::string a_type, int a_parent, int a_id, bool a_s, T PT::* a_f) : AbstractGroupDescription(a_name, a_type, a_parent, a_id, a_s), field(a_f)
{
}
GroupDescription(const GroupDescription<T, PT>& g): AbstractGroupDescription(g.name, g.type, g.parent, g.id, g.state), field(g.field), groups(g.groups)
{
parameters = g.parameters;
abstract_parameters = g.abstract_parameters;
}
virtual bool fromMessage(const dynamic_reconfigure::Config &msg, boost::any &cfg) const
{
PT* config = boost::any_cast<PT*>(cfg);
if(!dynamic_reconfigure::ConfigTools::getGroupState(msg, name, (*config).*field))
return false;
for(std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = groups.begin(); i != groups.end(); ++i)
{
boost::any n = &((*config).*field);
if(!(*i)->fromMessage(msg, n))
return false;
}
return true;
}
virtual void setInitialState(boost::any &cfg) const
{
PT* config = boost::any_cast<PT*>(cfg);
T* group = &((*config).*field);
group->state = state;
for(std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = groups.begin(); i != groups.end(); ++i)
{
boost::any n = boost::any(&((*config).*field));
(*i)->setInitialState(n);
}
}
virtual void updateParams(boost::any &cfg, CloudNodeConfig &top) const
{
PT* config = boost::any_cast<PT*>(cfg);
T* f = &((*config).*field);
f->setParams(top, abstract_parameters);
for(std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = groups.begin(); i != groups.end(); ++i)
{
boost::any n = &((*config).*field);
(*i)->updateParams(n, top);
}
}
virtual void toMessage(dynamic_reconfigure::Config &msg, const boost::any &cfg) const
{
const PT config = boost::any_cast<PT>(cfg);
dynamic_reconfigure::ConfigTools::appendGroup<T>(msg, name, id, parent, config.*field);
for(std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = groups.begin(); i != groups.end(); ++i)
{
(*i)->toMessage(msg, config.*field);
}
}
T (PT::* field);
std::vector<CloudNodeConfig::AbstractGroupDescriptionConstPtr> groups;
};
class DEFAULT
{
public:
DEFAULT()
{
state = true;
name = "Default";
}
void setParams(CloudNodeConfig &config, const std::vector<AbstractParamDescriptionConstPtr> params)
{
for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator _i = params.begin(); _i != params.end(); ++_i)
{
boost::any val;
(*_i)->getValue(config, val);
if("fixed_frame"==(*_i)->name){fixed_frame = boost::any_cast<std::string>(val);}
if("target_frame"==(*_i)->name){target_frame = boost::any_cast<std::string>(val);}
if("min_range"==(*_i)->name){min_range = boost::any_cast<double>(val);}
if("max_range"==(*_i)->name){max_range = boost::any_cast<double>(val);}
if("view_direction"==(*_i)->name){view_direction = boost::any_cast<double>(val);}
if("view_width"==(*_i)->name){view_width = boost::any_cast<double>(val);}
if("organize_cloud"==(*_i)->name){organize_cloud = boost::any_cast<bool>(val);}
}
}
std::string fixed_frame;
std::string target_frame;
double min_range;
double max_range;
double view_direction;
double view_width;
bool organize_cloud;
bool state;
std::string name;
}groups;
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
std::string fixed_frame;
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
std::string target_frame;
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double min_range;
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double max_range;
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double view_direction;
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double view_width;
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
bool organize_cloud;
//#line 228 "/opt/ros/melodic/share/dynamic_reconfigure/cmake/../templates/ConfigType.h.template"
bool __fromMessage__(dynamic_reconfigure::Config &msg)
{
const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__();
const std::vector<AbstractGroupDescriptionConstPtr> &__group_descriptions__ = __getGroupDescriptions__();
int count = 0;
for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i)
if ((*i)->fromMessage(msg, *this))
count++;
for (std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = __group_descriptions__.begin(); i != __group_descriptions__.end(); i ++)
{
if ((*i)->id == 0)
{
boost::any n = boost::any(this);
(*i)->updateParams(n, *this);
(*i)->fromMessage(msg, n);
}
}
if (count != dynamic_reconfigure::ConfigTools::size(msg))
{
ROS_ERROR("CloudNodeConfig::__fromMessage__ called with an unexpected parameter.");
ROS_ERROR("Booleans:");
for (unsigned int i = 0; i < msg.bools.size(); i++)
ROS_ERROR(" %s", msg.bools[i].name.c_str());
ROS_ERROR("Integers:");
for (unsigned int i = 0; i < msg.ints.size(); i++)
ROS_ERROR(" %s", msg.ints[i].name.c_str());
ROS_ERROR("Doubles:");
for (unsigned int i = 0; i < msg.doubles.size(); i++)
ROS_ERROR(" %s", msg.doubles[i].name.c_str());
ROS_ERROR("Strings:");
for (unsigned int i = 0; i < msg.strs.size(); i++)
ROS_ERROR(" %s", msg.strs[i].name.c_str());
// @todo Check that there are no duplicates. Make this error more
// explicit.
return false;
}
return true;
}
// This version of __toMessage__ is used during initialization of
// statics when __getParamDescriptions__ can't be called yet.
void __toMessage__(dynamic_reconfigure::Config &msg, const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__, const std::vector<AbstractGroupDescriptionConstPtr> &__group_descriptions__) const
{
dynamic_reconfigure::ConfigTools::clear(msg);
for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i)
(*i)->toMessage(msg, *this);
for (std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = __group_descriptions__.begin(); i != __group_descriptions__.end(); ++i)
{
if((*i)->id == 0)
{
(*i)->toMessage(msg, *this);
}
}
}
void __toMessage__(dynamic_reconfigure::Config &msg) const
{
const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__();
const std::vector<AbstractGroupDescriptionConstPtr> &__group_descriptions__ = __getGroupDescriptions__();
__toMessage__(msg, __param_descriptions__, __group_descriptions__);
}
void __toServer__(const ros::NodeHandle &nh) const
{
const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__();
for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i)
(*i)->toServer(nh, *this);
}
void __fromServer__(const ros::NodeHandle &nh)
{
static bool setup=false;
const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__();
for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i)
(*i)->fromServer(nh, *this);
const std::vector<AbstractGroupDescriptionConstPtr> &__group_descriptions__ = __getGroupDescriptions__();
for (std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = __group_descriptions__.begin(); i != __group_descriptions__.end(); i++){
if (!setup && (*i)->id == 0) {
setup = true;
boost::any n = boost::any(this);
(*i)->setInitialState(n);
}
}
}
void __clamp__()
{
const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__();
const CloudNodeConfig &__max__ = __getMax__();
const CloudNodeConfig &__min__ = __getMin__();
for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i)
(*i)->clamp(*this, __max__, __min__);
}
uint32_t __level__(const CloudNodeConfig &config) const
{
const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__();
uint32_t level = 0;
for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i)
(*i)->calcLevel(level, config, *this);
return level;
}
static const dynamic_reconfigure::ConfigDescription &__getDescriptionMessage__();
static const CloudNodeConfig &__getDefault__();
static const CloudNodeConfig &__getMax__();
static const CloudNodeConfig &__getMin__();
static const std::vector<AbstractParamDescriptionConstPtr> &__getParamDescriptions__();
static const std::vector<AbstractGroupDescriptionConstPtr> &__getGroupDescriptions__();
private:
static const CloudNodeConfigStatics *__get_statics__();
};
template <> // Max and min are ignored for strings.
inline void CloudNodeConfig::ParamDescription<std::string>::clamp(CloudNodeConfig &config, const CloudNodeConfig &max, const CloudNodeConfig &min) const
{
(void) config;
(void) min;
(void) max;
return;
}
class CloudNodeConfigStatics
{
friend class CloudNodeConfig;
CloudNodeConfigStatics()
{
CloudNodeConfig::GroupDescription<CloudNodeConfig::DEFAULT, CloudNodeConfig> Default("Default", "", 0, 0, true, &CloudNodeConfig::groups);
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.fixed_frame = "";
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.fixed_frame = "";
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.fixed_frame = "velodyne";
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(CloudNodeConfig::AbstractParamDescriptionConstPtr(new CloudNodeConfig::ParamDescription<std::string>("fixed_frame", "str", 0, "The desired input frame", "", &CloudNodeConfig::fixed_frame)));
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(CloudNodeConfig::AbstractParamDescriptionConstPtr(new CloudNodeConfig::ParamDescription<std::string>("fixed_frame", "str", 0, "The desired input frame", "", &CloudNodeConfig::fixed_frame)));
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.target_frame = "";
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.target_frame = "";
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.target_frame = "velodyne";
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(CloudNodeConfig::AbstractParamDescriptionConstPtr(new CloudNodeConfig::ParamDescription<std::string>("target_frame", "str", 0, "The desired output frame", "", &CloudNodeConfig::target_frame)));
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(CloudNodeConfig::AbstractParamDescriptionConstPtr(new CloudNodeConfig::ParamDescription<std::string>("target_frame", "str", 0, "The desired output frame", "", &CloudNodeConfig::target_frame)));
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.min_range = 0.1;
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.min_range = 10.0;
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.min_range = 0.9;
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(CloudNodeConfig::AbstractParamDescriptionConstPtr(new CloudNodeConfig::ParamDescription<double>("min_range", "double", 0, "min range to publish", "", &CloudNodeConfig::min_range)));
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(CloudNodeConfig::AbstractParamDescriptionConstPtr(new CloudNodeConfig::ParamDescription<double>("min_range", "double", 0, "min range to publish", "", &CloudNodeConfig::min_range)));
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.max_range = 0.1;
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.max_range = 200.0;
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.max_range = 130.0;
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(CloudNodeConfig::AbstractParamDescriptionConstPtr(new CloudNodeConfig::ParamDescription<double>("max_range", "double", 0, "max range to publish", "", &CloudNodeConfig::max_range)));
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(CloudNodeConfig::AbstractParamDescriptionConstPtr(new CloudNodeConfig::ParamDescription<double>("max_range", "double", 0, "max range to publish", "", &CloudNodeConfig::max_range)));
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.view_direction = -3.14159265359;
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.view_direction = 3.14159265359;
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.view_direction = 0.0;
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(CloudNodeConfig::AbstractParamDescriptionConstPtr(new CloudNodeConfig::ParamDescription<double>("view_direction", "double", 0, "angle defining the center of view", "", &CloudNodeConfig::view_direction)));
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(CloudNodeConfig::AbstractParamDescriptionConstPtr(new CloudNodeConfig::ParamDescription<double>("view_direction", "double", 0, "angle defining the center of view", "", &CloudNodeConfig::view_direction)));
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.view_width = 0.0;
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.view_width = 6.28318530718;
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.view_width = 6.28318530718;
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(CloudNodeConfig::AbstractParamDescriptionConstPtr(new CloudNodeConfig::ParamDescription<double>("view_width", "double", 0, "angle defining the view width", "", &CloudNodeConfig::view_width)));
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(CloudNodeConfig::AbstractParamDescriptionConstPtr(new CloudNodeConfig::ParamDescription<double>("view_width", "double", 0, "angle defining the view width", "", &CloudNodeConfig::view_width)));
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.organize_cloud = 0;
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.organize_cloud = 1;
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.organize_cloud = 0;
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(CloudNodeConfig::AbstractParamDescriptionConstPtr(new CloudNodeConfig::ParamDescription<bool>("organize_cloud", "bool", 0, "organized cloud", "", &CloudNodeConfig::organize_cloud)));
//#line 291 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(CloudNodeConfig::AbstractParamDescriptionConstPtr(new CloudNodeConfig::ParamDescription<bool>("organize_cloud", "bool", 0, "organized cloud", "", &CloudNodeConfig::organize_cloud)));
//#line 246 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.convertParams();
//#line 246 "/opt/ros/melodic/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__group_descriptions__.push_back(CloudNodeConfig::AbstractGroupDescriptionConstPtr(new CloudNodeConfig::GroupDescription<CloudNodeConfig::DEFAULT, CloudNodeConfig>(Default)));
//#line 366 "/opt/ros/melodic/share/dynamic_reconfigure/cmake/../templates/ConfigType.h.template"
for (std::vector<CloudNodeConfig::AbstractGroupDescriptionConstPtr>::const_iterator i = __group_descriptions__.begin(); i != __group_descriptions__.end(); ++i)
{
__description_message__.groups.push_back(**i);
}
__max__.__toMessage__(__description_message__.max, __param_descriptions__, __group_descriptions__);
__min__.__toMessage__(__description_message__.min, __param_descriptions__, __group_descriptions__);
__default__.__toMessage__(__description_message__.dflt, __param_descriptions__, __group_descriptions__);
}
std::vector<CloudNodeConfig::AbstractParamDescriptionConstPtr> __param_descriptions__;
std::vector<CloudNodeConfig::AbstractGroupDescriptionConstPtr> __group_descriptions__;
CloudNodeConfig __max__;
CloudNodeConfig __min__;
CloudNodeConfig __default__;
dynamic_reconfigure::ConfigDescription __description_message__;
static const CloudNodeConfigStatics *get_instance()
{
// Split this off in a separate function because I know that
// instance will get initialized the first time get_instance is
// called, and I am guaranteeing that get_instance gets called at
// most once.
static CloudNodeConfigStatics instance;
return &instance;
}
};
inline const dynamic_reconfigure::ConfigDescription &CloudNodeConfig::__getDescriptionMessage__()
{
return __get_statics__()->__description_message__;
}
inline const CloudNodeConfig &CloudNodeConfig::__getDefault__()
{
return __get_statics__()->__default__;
}
inline const CloudNodeConfig &CloudNodeConfig::__getMax__()
{
return __get_statics__()->__max__;
}
inline const CloudNodeConfig &CloudNodeConfig::__getMin__()
{
return __get_statics__()->__min__;
}
inline const std::vector<CloudNodeConfig::AbstractParamDescriptionConstPtr> &CloudNodeConfig::__getParamDescriptions__()
{
return __get_statics__()->__param_descriptions__;
}
inline const std::vector<CloudNodeConfig::AbstractGroupDescriptionConstPtr> &CloudNodeConfig::__getGroupDescriptions__()
{
return __get_statics__()->__group_descriptions__;
}
inline const CloudNodeConfigStatics *CloudNodeConfig::__get_statics__()
{
const static CloudNodeConfigStatics *statics;
if (statics) // Common case
return statics;
boost::mutex::scoped_lock lock(dynamic_reconfigure::__init_mutex__);
if (statics) // In case we lost a race.
return statics;
statics = CloudNodeConfigStatics::get_instance();
return statics;
}
}
#undef DYNAMIC_RECONFIGURE_FINAL
#endif // __CLOUDNODERECONFIGURATOR_H__
| [
"hanayoritevez@gmail.com"
] | hanayoritevez@gmail.com |
f149a8f4bd982f5f1354e944d32c40367bc1889a | 0fd5d9cb9fc505ae4f4a7737da76c8df06f99d26 | /CommandExpression.cpp | b418d1a09742dbabd2c92be8f2997bb5a633745a | [] | no_license | ImryUzan/FlightSimulator | 4ee522d5c6a2ff4cd35f21461a264321b73d64d8 | 8966085f717b06fbd2a6c9912688dad67f054321 | refs/heads/master | 2020-04-11T04:44:35.643379 | 2018-12-20T13:41:55 | 2018-12-20T13:41:55 | 161,524,131 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 167 | cpp |
#include "CommandExpression.h"
/*
double CommandExpression:: calculate(){
this->command->doCommand(listExpCommand,beginIndex,paramsToUpdate);
return 0;
}*/
| [
"ImryUzan@github.com"
] | ImryUzan@github.com |
7cfe1c3ce6972acba995a05e810985f7be37b83c | e05ee73f59fa33c462743b30cbc5d35263383e89 | /testing/testing_zlacpy_batched.cpp | 57d91b7044a6a8e507c90b9aa1d03f0ea09e30b9 | [] | no_license | bhrnjica/magma | 33c9e8a89f9bc2352f70867a48ec2dab7f94a984 | 88c8ca1a668055859a1cb9a31a204b702b688df5 | refs/heads/master | 2021-10-09T18:49:50.396412 | 2019-01-02T13:51:33 | 2019-01-02T13:51:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,134 | cpp | /*
-- MAGMA (version 2.4.0) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date June 2018
@precisions normal z -> c d s
@author Mark Gates
*/
// includes, system
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
// includes, project
#include "magma_v2.h"
#include "magma_lapack.h"
#include "testings.h"
/* ////////////////////////////////////////////////////////////////////////////
-- Testing zlacpy_batched
Code is very similar to testing_zgeadd_batched.cpp
*/
int main( int argc, char** argv)
{
TESTING_CHECK( magma_init() );
magma_print_environment();
real_Double_t gbytes, gpu_perf, gpu_time, cpu_perf, cpu_time;
double error, work[1];
magmaDoubleComplex c_neg_one = MAGMA_Z_NEG_ONE;
magmaDoubleComplex *h_A, *h_B;
magmaDoubleComplex_ptr d_A, d_B;
magmaDoubleComplex **hAarray, **hBarray, **dAarray, **dBarray;
magma_int_t M, N, mb, nb, size, lda, ldda, mstride, nstride, ntile;
magma_int_t ione = 1;
magma_int_t ISEED[4] = {0,0,0,1};
int status = 0;
magma_opts opts( MagmaOptsBatched );
opts.parse_opts( argc, argv );
mb = (opts.nb == 0 ? 32 : opts.nb);
nb = (opts.nb == 0 ? 64 : opts.nb);
mstride = 2*mb;
nstride = 3*nb;
printf("%% mb=%lld, nb=%lld, mstride=%lld, nstride=%lld\n", (long long) mb, (long long) nb, (long long) mstride, (long long) nstride );
printf("%% M N ntile CPU Gflop/s (ms) GPU Gflop/s (ms) check\n");
printf("%%================================================================\n");
for( int itest = 0; itest < opts.ntest; ++itest ) {
for( int iter = 0; iter < opts.niter; ++iter ) {
M = opts.msize[itest];
N = opts.nsize[itest];
lda = M;
ldda = magma_roundup( M, opts.align ); // multiple of 32 by default
size = lda*N;
if ( N < nb || M < nb ) {
ntile = 0;
} else {
ntile = min( (M - nb)/mstride + 1,
(N - nb)/nstride + 1 );
}
gbytes = 2.*mb*nb*ntile / 1e9;
TESTING_CHECK( magma_zmalloc_cpu( &h_A, lda *N ));
TESTING_CHECK( magma_zmalloc_cpu( &h_B, lda *N ));
TESTING_CHECK( magma_zmalloc( &d_A, ldda*N ));
TESTING_CHECK( magma_zmalloc( &d_B, ldda*N ));
TESTING_CHECK( magma_malloc_cpu( (void**) &hAarray, ntile * sizeof(magmaDoubleComplex*) ));
TESTING_CHECK( magma_malloc_cpu( (void**) &hBarray, ntile * sizeof(magmaDoubleComplex*) ));
TESTING_CHECK( magma_malloc( (void**) &dAarray, ntile * sizeof(magmaDoubleComplex*) ));
TESTING_CHECK( magma_malloc( (void**) &dBarray, ntile * sizeof(magmaDoubleComplex*) ));
lapackf77_zlarnv( &ione, ISEED, &size, h_A );
lapackf77_zlarnv( &ione, ISEED, &size, h_B );
/* ====================================================================
Performs operation using MAGMA
=================================================================== */
magma_zsetmatrix( M, N, h_A, lda, d_A, ldda, opts.queue );
magma_zsetmatrix( M, N, h_B, lda, d_B, ldda, opts.queue );
// setup pointers
for( magma_int_t tile = 0; tile < ntile; ++tile ) {
magma_int_t offset = tile*mstride + tile*nstride*ldda;
hAarray[tile] = &d_A[offset];
hBarray[tile] = &d_B[offset];
}
magma_setvector( ntile, sizeof(magmaDoubleComplex*), hAarray, 1, dAarray, 1, opts.queue );
magma_setvector( ntile, sizeof(magmaDoubleComplex*), hBarray, 1, dBarray, 1, opts.queue );
gpu_time = magma_sync_wtime( opts.queue );
magmablas_zlacpy_batched( MagmaFull, mb, nb, dAarray, ldda, dBarray, ldda, ntile, opts.queue );
gpu_time = magma_sync_wtime( opts.queue ) - gpu_time;
gpu_perf = gbytes / gpu_time;
/* =====================================================================
Performs operation using LAPACK
=================================================================== */
cpu_time = magma_wtime();
for( magma_int_t tile = 0; tile < ntile; ++tile ) {
magma_int_t offset = tile*mstride + tile*nstride*lda;
lapackf77_zlacpy( MagmaFullStr, &mb, &nb,
&h_A[offset], &lda,
&h_B[offset], &lda );
}
cpu_time = magma_wtime() - cpu_time;
cpu_perf = gbytes / cpu_time;
/* =====================================================================
Check the result
=================================================================== */
magma_zgetmatrix( M, N, d_B, ldda, h_A, lda, opts.queue );
blasf77_zaxpy(&size, &c_neg_one, h_A, &ione, h_B, &ione);
error = lapackf77_zlange("f", &M, &N, h_B, &lda, work);
bool okay = (error == 0);
status += ! okay;
printf("%5lld %5lld %5lld %7.2f (%7.2f) %7.2f (%7.2f) %s\n",
(long long) M, (long long) N, (long long) ntile,
cpu_perf, cpu_time*1000., gpu_perf, gpu_time*1000.,
(okay ? "ok" : "failed") );
magma_free_cpu( h_A );
magma_free_cpu( h_B );
magma_free( d_A );
magma_free( d_B );
magma_free_cpu( hAarray );
magma_free_cpu( hBarray );
magma_free( dAarray );
magma_free( dBarray );
fflush( stdout );
}
if ( opts.niter > 1 ) {
printf( "\n" );
}
}
opts.cleanup();
TESTING_CHECK( magma_finalize() );
return status;
}
| [
"sinkingsugar@gmail.com"
] | sinkingsugar@gmail.com |
3ab43f8fcc11495fe0c416e64f34cdbf2d161aa1 | 9f817a1d7818ee5f2974270896ae44810db52bbc | /Final_project/SamplePluginPA10/build/src/moc_SamplePlugin.cxx | b2b49f346dd7ec96f16723c56ca0dd6b99794143 | [] | no_license | StefanRvO/ROVI | 978670451297d9de9df5b897756b5fc38c5a08f6 | 38d3b309b6d04b417aa79e36ce2d768ec1913dd0 | refs/heads/master | 2021-01-12T12:43:33.037539 | 2017-03-16T15:50:30 | 2017-03-16T15:50:30 | 69,665,284 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 3,368 | cxx | /****************************************************************************
** Meta object code from reading C++ file 'SamplePlugin.hpp'
**
** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.6)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../src/SamplePlugin.hpp"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'SamplePlugin.hpp' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.6. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_SamplePlugin[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
3, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: signature, parameters, type, tag, flags
14, 13, 13, 13, 0x08,
27, 13, 13, 13, 0x08,
41, 35, 13, 13, 0x08,
0 // eod
};
static const char qt_meta_stringdata_SamplePlugin[] = {
"SamplePlugin\0\0btnPressed()\0timer()\0"
"state\0stateChangedListener(rw::kinematics::State)\0"
};
void SamplePlugin::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
Q_ASSERT(staticMetaObject.cast(_o));
SamplePlugin *_t = static_cast<SamplePlugin *>(_o);
switch (_id) {
case 0: _t->btnPressed(); break;
case 1: _t->timer(); break;
case 2: _t->stateChangedListener((*reinterpret_cast< const rw::kinematics::State(*)>(_a[1]))); break;
default: ;
}
}
}
const QMetaObjectExtraData SamplePlugin::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject SamplePlugin::staticMetaObject = {
{ &rws::RobWorkStudioPlugin::staticMetaObject, qt_meta_stringdata_SamplePlugin,
qt_meta_data_SamplePlugin, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &SamplePlugin::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *SamplePlugin::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *SamplePlugin::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_SamplePlugin))
return static_cast<void*>(const_cast< SamplePlugin*>(this));
if (!strcmp(_clname, "dk.sdu.mip.Robwork.RobWorkStudioPlugin/0.1"))
return static_cast< rws::RobWorkStudioPlugin*>(const_cast< SamplePlugin*>(this));
typedef rws::RobWorkStudioPlugin QMocSuperClass;
return QMocSuperClass::qt_metacast(_clname);
}
int SamplePlugin::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
typedef rws::RobWorkStudioPlugin QMocSuperClass;
_id = QMocSuperClass::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 3)
qt_static_metacall(this, _c, _id, _a);
_id -= 3;
}
return _id;
}
QT_END_MOC_NAMESPACE
| [
"stefan@stefanrvo.dk"
] | stefan@stefanrvo.dk |
fe28755af33ec721f13e5215f657f0a270c37cea | cc15d0b5aa908651e80a1e08eb7696e305b8811a | /Src/Kernel/Modules/Source/source.cpp | b984652ad3b8adf848f6242df1924b6e3ac3f147 | [] | no_license | Ivehui/RobotSDK | c75f22c9be646212b7c4852821026aae27c030b4 | 3c0da3a3ea149542244cec9ef60598b390602803 | refs/heads/master | 2020-12-25T22:57:15.709863 | 2015-03-25T06:12:04 | 2015-03-25T06:12:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,626 | cpp | #include "source.h"
Source::Source(QString qstrSharedLibrary, QString qstrNodeType, QString qstrNodeClass, QString qstrNodeName, QString qstrConfigName, QString qstrFuncEx)
: Node(qstrSharedLibrary,qstrNodeType,qstrNodeClass,qstrNodeName,qstrConfigName)
{
LoadCheckFptr(sharedlibrary,initializeOutputDataFptr,initializeOutputData,nodetype,nodeclass);
LoadCheckExFptr(sharedlibrary,generateSourceDataFptr,generateSourceData,qstrFuncEx,nodetype,nodeclass);
if(inputports.size()>0)
{
QMessageBox::information(NULL,QString("Source Node Error"),QString("Source %1_%2_%3: Number of input ports >0").arg(nodetype).arg(nodeclass).arg(nodename));
exit(0);
}
if(outputports.size()<1)
{
QMessageBox::information(NULL,QString("Source Node Error"),QString("Source %1_%2_%3: Number of output ports <1").arg(nodetype).arg(nodeclass).arg(nodename));
exit(0);
}
}
Source::Source(QString qstrSharedLibrary, QString qstrNodeClass, QString qstrNodeName, QString qstrConfigName, QString qstrFuncEx)
: Node(qstrSharedLibrary,QString("Source"),qstrNodeClass,qstrNodeName,qstrConfigName)
{
LoadCheckFptr(sharedlibrary,initializeOutputDataFptr,initializeOutputData,nodetype,nodeclass);
LoadCheckExFptr(sharedlibrary,generateSourceDataFptr,generateSourceData,qstrFuncEx,nodetype,nodeclass);
if(inputports.size()>0)
{
QMessageBox::information(NULL,QString("Source Node Error"),QString("Source %1_%2_%3: Number of input ports >0").arg(nodetype).arg(nodeclass).arg(nodename));
exit(0);
}
if(outputports.size()<1)
{
QMessageBox::information(NULL,QString("Source Node Error"),QString("Source %1_%2_%3: Number of output ports <1").arg(nodetype).arg(nodeclass).arg(nodename));
exit(0);
}
}
void Source::generateSourceDataSlot()
{
if(openflag)
{
nodeTriggerTime(NodeTriggerStart);
boost::shared_ptr<void> outputdata;
initializeOutputData(paramsptr.get(),varsptr.get(),outputdata);
QList<int> outputportindex;
QTime timestamp;
if(generateSourceData(paramsptr.get(),varsptr.get(),outputdata.get(),outputportindex,timestamp))
{
if(outputportindex.size()==0)
{
int i,n=outputports.size();
for(i=0;i<n;i++)
{
outputports[i]->outputData(paramsptr,outputdata);
}
}
else
{
int i,n=outputportindex.size();
for(i=0;i<n;i++)
{
if(outputportindex[i]>=0&&outputportindex[i]<outputports.size())
{
outputports[outputportindex[i]]->outputData(paramsptr,outputdata);
}
}
}
emit generateSourceDataSignal();
nodeTriggerTime(NodeTriggerEnd);
}
else
{
emit generateSourceDataErrorSignal();
nodeTriggerTime(NodeTriggerError);
}
}
}
| [
"alexanderhmw@gmail.com"
] | alexanderhmw@gmail.com |
011a6a2d68e306a55f7acf8259bf7c61d2fc9a63 | e5f21b933297a05f101af5ee27423c630013552d | /mem/ruby/protocol/L1Cache_Event.cc | 924bd1417970edf2971fb909fc68e3ffc01ad8f7 | [] | no_license | zhouzhiyong18/gem5 | 467bf5a3dc64a2a548d6534fae0196054fc5a9c1 | 1eeffe8030e45db6b4cd725ffb3dc73d5d04617d | refs/heads/master | 2020-11-24T14:24:02.868358 | 2020-02-25T09:23:21 | 2020-02-25T09:23:21 | 228,190,356 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,540 | cc | /** \file L1Cache_Event.hh
*
* Auto generated C++ code started by /home/zhouzhiyong/gem5/src/mem/slicc/symbols/Type.py:566
*/
#include <cassert>
#include <iostream>
#include <string>
#include "base/logging.hh"
#include "mem/ruby/protocol/L1Cache_Event.hh"
using namespace std;
// Code for output operator
ostream&
operator<<(ostream& out, const L1Cache_Event& obj)
{
out << L1Cache_Event_to_string(obj);
out << flush;
return out;
}
// Code to convert state to a string
string
L1Cache_Event_to_string(const L1Cache_Event& obj)
{
switch(obj) {
case L1Cache_Event_Load:
return "Load";
case L1Cache_Event_Store:
return "Store";
case L1Cache_Event_WriteBack:
return "WriteBack";
case L1Cache_Event_L0_DataAck:
return "L0_DataAck";
case L1Cache_Event_Inv:
return "Inv";
case L1Cache_Event_L0_Invalidate_Own:
return "L0_Invalidate_Own";
case L1Cache_Event_L0_Invalidate_Else:
return "L0_Invalidate_Else";
case L1Cache_Event_L1_Replacement:
return "L1_Replacement";
case L1Cache_Event_Fwd_GETX:
return "Fwd_GETX";
case L1Cache_Event_Fwd_GETS:
return "Fwd_GETS";
case L1Cache_Event_Data:
return "Data";
case L1Cache_Event_Data_Exclusive:
return "Data_Exclusive";
case L1Cache_Event_DataS_fromL1:
return "DataS_fromL1";
case L1Cache_Event_Data_all_Acks:
return "Data_all_Acks";
case L1Cache_Event_L0_Ack:
return "L0_Ack";
case L1Cache_Event_Ack:
return "Ack";
case L1Cache_Event_Ack_all:
return "Ack_all";
case L1Cache_Event_WB_Ack:
return "WB_Ack";
default:
panic("Invalid range for type L1Cache_Event");
}
}
// Code to convert from a string to the enumeration
L1Cache_Event
string_to_L1Cache_Event(const string& str)
{
if (str == "Load") {
return L1Cache_Event_Load;
} else if (str == "Store") {
return L1Cache_Event_Store;
} else if (str == "WriteBack") {
return L1Cache_Event_WriteBack;
} else if (str == "L0_DataAck") {
return L1Cache_Event_L0_DataAck;
} else if (str == "Inv") {
return L1Cache_Event_Inv;
} else if (str == "L0_Invalidate_Own") {
return L1Cache_Event_L0_Invalidate_Own;
} else if (str == "L0_Invalidate_Else") {
return L1Cache_Event_L0_Invalidate_Else;
} else if (str == "L1_Replacement") {
return L1Cache_Event_L1_Replacement;
} else if (str == "Fwd_GETX") {
return L1Cache_Event_Fwd_GETX;
} else if (str == "Fwd_GETS") {
return L1Cache_Event_Fwd_GETS;
} else if (str == "Data") {
return L1Cache_Event_Data;
} else if (str == "Data_Exclusive") {
return L1Cache_Event_Data_Exclusive;
} else if (str == "DataS_fromL1") {
return L1Cache_Event_DataS_fromL1;
} else if (str == "Data_all_Acks") {
return L1Cache_Event_Data_all_Acks;
} else if (str == "L0_Ack") {
return L1Cache_Event_L0_Ack;
} else if (str == "Ack") {
return L1Cache_Event_Ack;
} else if (str == "Ack_all") {
return L1Cache_Event_Ack_all;
} else if (str == "WB_Ack") {
return L1Cache_Event_WB_Ack;
} else {
panic("Invalid string conversion for %s, type L1Cache_Event", str);
}
}
// Code to increment an enumeration type
L1Cache_Event&
operator++(L1Cache_Event& e)
{
assert(e < L1Cache_Event_NUM);
return e = L1Cache_Event(e+1);
}
| [
"438504124@qq.com"
] | 438504124@qq.com |
502db7ae58b667afcd973739a363dfff575ec35a | 89da47fbe3683f721f0e9a164a71013641318cd9 | /src/IA-32/DataUnpacker.h | 85597c46b34199babe27ce21bd04d3b5f0d5eab4 | [] | no_license | gofrito/swspec | e5d7875b8b581a42d7c5138fec83478b9b803130 | 4c7c5d7317c4919b1452a64d20c8eff2cd8c0947 | refs/heads/master | 2022-01-20T16:50:08.743711 | 2022-01-03T10:28:42 | 2022-01-03T10:28:42 | 12,752,779 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,476 | h | #ifndef DATAUNPACKER_H
#define DATAUNPACKER_H
/************************************************************************
* IBM Cell / Intel Software Spectrometer
* Copyright (C) 2008 Jan Wagner
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA
**************************************************************************/
#include "Settings.h"
#include <cstring>
#include <ippcore.h>
#include <string>
/**
* DataUnpacker base class
*/
class DataUnpacker {
public:
DataUnpacker() { return; }
DataUnpacker(swspect_settings_t const* settings) { return; }
virtual size_t extract_samples(char const* const src, Ipp32f* dst, const size_t count, const int channel) const = 0;
static bool canHandleConfig(swspect_settings_t const* settings) { return false; }
};
#endif // DATAUNPACKER_H
| [
"gofrito@marcopolo.(none)"
] | gofrito@marcopolo.(none) |
8bf29b82f7ad891265c94fb7029caa7a47dcf055 | 4424eb0c6d2666a37bbe5b9d6b3550ca11d51729 | /SerialPrograms/Source/PokemonSwSh/PokemonSwSh_SettingsPanel.h | e3ed5c91c91ad505f5c263fc13e9df676feef560 | [
"LicenseRef-scancode-proprietary-license",
"MIT"
] | permissive | ercdndrs/Arduino-Source | cd87e4036f0e36c3dd0180448293721be95cc654 | c0490f0f06aaa38759aa8f11def9e1349e551679 | refs/heads/main | 2023-05-05T07:43:52.845481 | 2021-05-24T02:27:25 | 2021-05-24T02:27:25 | 369,910,477 | 0 | 0 | MIT | 2021-05-22T21:39:34 | 2021-05-22T21:39:33 | null | UTF-8 | C++ | false | false | 497 | h | /* Pokemon Settings Panel
*
* From: https://github.com/PokemonAutomation/Arduino-Source
*
*/
#ifndef PokemonAutomation_PokemonSettingsPanel_H
#define PokemonAutomation_PokemonSettingsPanel_H
#include "CommonFramework/Panels/SettingsPanel.h"
namespace PokemonAutomation{
namespace NintendoSwitch{
namespace PokemonSwSh{
class PokemonSettings : public SettingsPanel{
public:
PokemonSettings();
PokemonSettings(const QJsonValue& json);
};
}
}
}
#endif
| [
"a-yee@u.northwestern.edu"
] | a-yee@u.northwestern.edu |
cb9b5acf1a752aaf69692882d8b8dc153fea5730 | ad273708d98b1f73b3855cc4317bca2e56456d15 | /aws-cpp-sdk-macie2/include/aws/macie2/model/GetMacieSessionRequest.h | fb89846f6f26c85e5cb24d256d0cbcef55558b4b | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | novaquark/aws-sdk-cpp | b390f2e29f86f629f9efcf41c4990169b91f4f47 | a0969508545bec9ae2864c9e1e2bb9aff109f90c | refs/heads/master | 2022-08-28T18:28:12.742810 | 2020-05-27T15:46:18 | 2020-05-27T15:46:18 | 267,351,721 | 1 | 0 | Apache-2.0 | 2020-05-27T15:08:16 | 2020-05-27T15:08:15 | null | UTF-8 | C++ | false | false | 1,415 | h | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/macie2/Macie2_EXPORTS.h>
#include <aws/macie2/Macie2Request.h>
namespace Aws
{
namespace Macie2
{
namespace Model
{
/**
*/
class AWS_MACIE2_API GetMacieSessionRequest : public Macie2Request
{
public:
GetMacieSessionRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "GetMacieSession"; }
Aws::String SerializePayload() const override;
};
} // namespace Model
} // namespace Macie2
} // namespace Aws
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
a8d26380189914748a96a6bece39838e7d49e878 | cd790fb7e8ef78b1989531f5864f67649dcb1557 | /uva11371(NumberTheoryforNewbies).cpp | 4e77a77255d3a0c57daa44e0b5fd39b84fbc7513 | [] | no_license | FatimaTasnim/uva-solution | 59387c26816c271b17e9604255934b7c8c7faf11 | c7d75f0a5384229b243504dfbef4686052b9dea8 | refs/heads/master | 2020-03-27T22:23:18.611201 | 2018-10-23T05:53:46 | 2018-10-23T05:53:46 | 147,226,519 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,451 | cpp | #include<bits/stdc++.h>
#define pi 2*acos(0.0)
#define PS system("pause")
#define S1for(n) for(int i=1;i<=n;i++)
#define Sfor(n) for(int i=0;i<n;i++)
#define inf (1<<30)
#define pb push_back
#define ppb pop_back
#define F first
#define S second
#define sz(x) ((int)x.size())
#define eps 1e-9
#define gcd(x,y) __gcd(x,y)
#define lcm(a,b) (a*(b/gcd(a,b)))
#define on(x,w) x=x|(1<<w)
#define check(x,w) (x&(1<<w))==(1<<w)?true:false
#define all(x) (x).begin(),(x).end()
#define s(n) scanf("%c",&n)
#define ss(n) scanf("%s",n)
#define pf printf
#define ll long long int
#define MOD 1000000007
#define sqr(x) (( (x)* (x))%MOD)
#define cube(x) ( (sqr(x)*(x))%MOD)
#define bit_cnt(x) __builtin_popcount(x)
#define INT(c) ((int)((c) - '0'))
#define maxall(v) *max_element(all(v))
#define minall(v) *min_element(all(v))
#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))
#define btz(a) __builtin_ctz(a)
#define Mems(p,n) memset(p, n, sizeof(p))
#define what_is(x) cerr<<#x<<" is "<<x<<"\n";
#define M 1000000
#define makeint(n,s) istringstream(s)>>n
#define BOUNDARY(i,j,Row,Col) ((i >= 0 && i < Row) && (j >= 0 && j < Col))
using namespace std;
template<class T>
inline bool fs(T &x)
{
int c=getchar();
int sgn=1;
while(~c&&c<'0'||c>'9')
{
if(c=='-')sgn=-1;
c=getchar();
}
for(x=0; ~c&&'0'<=c&&c<='9'; c=getchar())
x=x*10+c-'0';
x*=sgn;
return ~c;
}
long long ans(char *a)
{
long long r=0;
int i;
for(i=0; a[i]; i++)
{
r=r*10+(a[i]-48);
}
return r;
}
int factor(int n)
{
if(n==1)
return n;
else return n*factor(n-1);
}
int main()
{
char str[100];
long long r1,r2,f,c,n;
while(scanf("%s",str)==1)
{
n=0;f=0;
int len= strlen(str);
for(int i=0;str[i];i++)
{
if(str[i]=='0')
n++;
}
if(n>0)
c=factor(len)/factor(n);
else
c=factor(len);
while(prev_permutation(str,str+len));
r1=ans(str);
//while(next_permutation(str,str+len));
//c;
Sfor(c){
next_permutation(str,str+len);}
r2=ans(str);
printf("\n%lld - %lld = %lld = 9 * %lld\n",r1,r2,r1-r2,(r1-r2)/9);
}
}
| [
"tasnim.roujat@gmail.com"
] | tasnim.roujat@gmail.com |
5a0aa914f78c81cedb2d903d14780d2b5d18b81a | 0823ee424bda39cbfb86c8feceef12b0e9261d1d | /main.cc | 633764938448a2c335e5ffeb8a128cfa606f2c0b | [] | no_license | dishather/steganodisk | 53642408561483a43f18350b164b5f5288066082 | b88079c0d7639fb5e9392a88167443ddbe1cd437 | refs/heads/master | 2020-05-05T07:49:33.898121 | 2019-04-06T14:00:27 | 2019-04-06T14:00:27 | 179,839,351 | 7 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 6,608 | cc | #include <QByteArray>
#include <QCoreApplication>
#include <QFile>
#include <QFileInfo>
#include <QStringList>
#include "cipher.h"
#include "secretfile.h"
#include <iostream>
#include <stdexcept>
#ifdef Q_OS_LINUX
# include <fcntl.h>
# include <linux/fs.h>
# include <sys/ioctl.h>
# include <sys/stat.h>
# include <sys/types.h>
# include <unistd.h>
//
static
qint64 GetDeviceSize( QString const &path )
{
char const *p = path.toLocal8Bit().constData();
int fd = open( p, O_RDONLY );
qint64 file_size_in_bytes = 0;
ioctl( fd, BLKGETSIZE64, &file_size_in_bytes );
close( fd );
return file_size_in_bytes;
}
#endif /* Q_OS_LINUX */
//
static
void EncryptToDevice( QString const &device, SecretFile const &sf,
QString const &password )
{
QFileInfo fi( device );
if( !fi.exists() )
{
throw std::runtime_error( "output device or file does not exist" );
}
qint64 devSize = fi.size();
#ifdef Q_OS_LINUX
if( devSize < qint64( ClusterSize ) )
{
devSize = GetDeviceSize( device );
}
#endif
if( devSize < qint64( ClusterSize ) )
{
throw std::runtime_error( "output device or file is too small" );
}
QFile file( device );
if( !file.open( QIODevice::WriteOnly ) )
{
throw std::runtime_error( "error opening output device or file "
"for writing" );
}
const quint64 numClusters = quint64( devSize / ClusterSize );
std::cout << "About to write " << numClusters << " clusters to device " <<
qPrintable( device ) << std::endl;
const int secFileClusters = sf.numChunks();
std::cout << "SecretFile is " << secFileClusters << " cluster(s) long, "
"writing about " << ( numClusters / secFileClusters ) << " copies." <<
std::endl;
for( quint64 cluster = 0; cluster < numClusters; ++cluster )
{
QByteArray chunk = sf.getChunkForCluster( cluster );
EncryptData( chunk, password );
if( file.write( chunk ) != chunk.size() )
{
throw std::runtime_error( "write error" );
}
if( ( cluster % 100 ) == 0 )
{
int percent = int( ( cluster * 100 ) / numClusters );
std::cout << "\r" << cluster << ' ' << percent << '%';
std::cout.flush();
}
}
std::cout << "\r" << numClusters << " 100%" << std::endl;
}
//
static
void DecryptFromDevice( QString const &device, SecretFile &sf,
QString const &password )
{
QFileInfo fi( device );
if( !fi.exists() )
{
throw std::runtime_error( "input device or file does not exist" );
}
qint64 devSize = fi.size();
#ifdef Q_OS_LINUX
if( devSize < qint64( ClusterSize ) )
{
devSize = GetDeviceSize( device );
}
#endif
if( devSize < qint64( ClusterSize ) )
{
throw std::runtime_error( "input device or file is too small" );
}
QFile file( device );
if( !file.open( QIODevice::ReadOnly ) )
{
throw std::runtime_error( "error opening output device or file "
"for reading" );
}
const quint32 numClusters = quint32( devSize / ClusterSize );
std::cout << "Device size: " << numClusters << " clusters" << std::endl;
quint32 totalChunks = 0, goodChunks = 0;
QByteArray chunk = file.read( qint64( ClusterSize ) );
while( chunk.size() == ClusterSize )
{
DecryptData( chunk, password );
if( sf.addDataChunk( chunk ) )
{
std::cout << ' ' << totalChunks << " - decrypted\n";
++goodChunks;
if( sf.isFileComplete() )
{
break;
}
}
else
{
if( ( totalChunks % 100 ) == 0 )
{
int percent = int( ( totalChunks * 100 ) / numClusters );
std::cout << "\r" << totalChunks << ' ' << percent << '%';
std::cout.flush();
}
}
++totalChunks;
std::cout.flush();
chunk = file.read( qint64( ClusterSize ) );
}
std::cout << "\nTotal clusters read: " << totalChunks << ", decrypted: " <<
goodChunks << std::endl;
}
//
static
bool ParseCommandLine( QStringList const &args, bool &encrypt, QString &device,
QString &password, QString &secretFile )
{
for( int i = 1; i < args.size(); ++i )
{
if( args[i] == "-h" )
{
return false;
}
if( args[i] == "-s" )
{
++i;
secretFile = args[i];
continue;
}
if( args[i] == "-p" )
{
++i;
password = args[i];
continue;
}
if( args[i] == "-e" )
{
encrypt = true;
continue;
}
if( device.isEmpty() )
{
device = args[i];
}
else
{
return false;
}
}
return !password.isEmpty() && !device.isEmpty() &&
( !secretFile.isEmpty() == encrypt );
}
//
int main( int argc, char *argv[] )
{
QCoreApplication app( argc, argv );
QString device, password, secretFile;
bool encrypt = false;
if( !ParseCommandLine( app.arguments(), encrypt, device, password,
secretFile ) )
{
std::cout << "Usage:\n" << qPrintable( app.arguments()[0] ) <<
" [-h] [-e] -p password [-s secretFile] deviceOrImageFile" <<
std::endl;
std::cout <<
" -h: this help\n"
" -e: encrypt secretFile into device using password (default is "
"to extract an encrypted file from the device)\n"
" -p password: the encryption/decryption password\n"
" -s secretFile: the file to encrypt onto the device\n"
" deviceOrImageFile: where to write the encrypted data (warning: "
"will overwrite any existing data!)" << std::endl;
return 1;
}
try {
SecretFile sf;
if( encrypt )
{
sf.loadFrom( secretFile );
EncryptToDevice( device, sf, password );
}
else
{
DecryptFromDevice( device, sf, password );
sf.saveToSecretFile(); // obtained from the data
std::cout << "Wrote " << sf.filesize() << " bytes to file " <<
qPrintable( sf.filename() ) << std::endl;
}
}
catch( std::runtime_error const &e )
{
std::cout << "ERROR: " << e.what() << std::endl;
return 1;
}
std::cout << "Done." << std::endl;
return 0;
}
| [
"zmey@nas.home"
] | zmey@nas.home |
b075c54bb963ebacd43a7d250078e5186284a822 | 5555bc68f5b54d9cb9a9ab0558b0b1e80fb5421a | /src/serialization/variant.h | e8c56ecbaaa3ec1ce3bc432d8202a3908bc8cd08 | [
"MIT"
] | permissive | monero-classic-project/monero-classic | f039006b8e79299417e25d04fddcd24d366c67dc | a88ce4e38055aa43749f1f2ab066a8ce99c75534 | refs/heads/master | 2021-05-01T12:05:35.046668 | 2018-02-10T22:12:51 | 2018-02-10T22:12:51 | 121,058,016 | 5 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 4,713 | h | // Copyright (c) 2018, The Monero Classic Developers.
// Portions Copyright (c) 2012-2013, The CryptoNote Developers.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#pragma once
#include <boost/variant/variant.hpp>
#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/static_visitor.hpp>
#include <boost/mpl/empty.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/front.hpp>
#include <boost/mpl/pop_front.hpp>
#include "serialization.h"
template <class Archive, class T>
struct variant_serialization_traits
{
};
template <class Archive, class Variant, class TBegin, class TEnd>
struct variant_reader
{
typedef typename Archive::variant_tag_type variant_tag_type;
typedef typename boost::mpl::next<TBegin>::type TNext;
typedef typename boost::mpl::deref<TBegin>::type current_type;
static inline bool read(Archive &ar, Variant &v, variant_tag_type t)
{
if (variant_serialization_traits<Archive, current_type>::get_tag() == t) {
current_type x;
if(!::do_serialize(ar, x))
{
ar.stream().setstate(std::ios::failbit);
return false;
}
v = x;
} else {
return variant_reader<Archive, Variant, TNext, TEnd>::read(ar, v, t);
}
return true;
}
};
template <class Archive, class Variant, class TBegin>
struct variant_reader<Archive, Variant, TBegin, TBegin>
{
typedef typename Archive::variant_tag_type variant_tag_type;
static inline bool read(Archive &ar, Variant &v, variant_tag_type t)
{
ar.stream().setstate(std::ios::failbit);
return false;
}
};
template <template <bool> class Archive, BOOST_VARIANT_ENUM_PARAMS(typename T)>
struct serializer<Archive<false>, boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)>>
{
typedef boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> variant_type;
typedef typename Archive<false>::variant_tag_type variant_tag_type;
typedef typename variant_type::types types;
static bool serialize(Archive<false> &ar, variant_type &v) {
variant_tag_type t;
ar.begin_variant();
ar.read_variant_tag(t);
if(!variant_reader<Archive<false>, variant_type, typename boost::mpl::begin<types>::type, typename boost::mpl::end<types>::type>::read(ar, v, t))
{
ar.stream().setstate(std::ios::failbit);
return false;
}
ar.end_variant();
return true;
}
};
template <template <bool> class Archive, BOOST_VARIANT_ENUM_PARAMS(typename T)>
struct serializer<Archive<true>, boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)>>
{
typedef boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> variant_type;
//typedef typename Archive<true>::variant_tag_type variant_tag_type;
struct visitor : public boost::static_visitor<bool>
{
Archive<true> &ar;
visitor(Archive<true> &a) : ar(a) { }
template <class T>
bool operator ()(T &rv) const
{
ar.begin_variant();
ar.write_variant_tag(variant_serialization_traits<Archive<true>, T>::get_tag());
if(!::do_serialize(ar, rv))
{
ar.stream().setstate(std::ios::failbit);
return false;
}
ar.end_variant();
return true;
}
};
static bool serialize(Archive<true> &ar, variant_type &v) {
return boost::apply_visitor(visitor(ar), v);
}
};
| [
"xmrc-dev@protonmail.com"
] | xmrc-dev@protonmail.com |
95107bb88c48eaeeb6b068b39034ed2a3b6e72f5 | d9b6cd7472b5e12d64074c0d4a80f3f1633567b3 | /src/lcals/FIRST_SUM.cpp | 0f7d38aa5216d61ee02eff972067e8377e87e66d | [
"BSD-3-Clause"
] | permissive | Zhaojp-Frank/RAJAPerf | 642aeab7ebfe8d51c56da119b28f79ad75088b82 | a6ef0279d9d240199947d872d8f28bf121f2192c | refs/heads/master | 2021-04-19T04:42:17.561043 | 2020-02-10T16:18:29 | 2020-02-10T16:18:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,086 | cpp | //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Copyright (c) 2017-20, Lawrence Livermore National Security, LLC
// and RAJA Performance Suite project contributors.
// See the RAJAPerf/COPYRIGHT file for details.
//
// SPDX-License-Identifier: (BSD-3-Clause)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
#include "FIRST_SUM.hpp"
#include "RAJA/RAJA.hpp"
#include "common/DataUtils.hpp"
namespace rajaperf
{
namespace lcals
{
FIRST_SUM::FIRST_SUM(const RunParams& params)
: KernelBase(rajaperf::Lcals_FIRST_SUM, params)
{
setDefaultSize(100000);
setDefaultReps(16000);
}
FIRST_SUM::~FIRST_SUM()
{
}
void FIRST_SUM::setUp(VariantID vid)
{
m_N = getRunSize();
allocAndInitDataConst(m_x, m_N, 0.0, vid);
allocAndInitData(m_y, m_N, vid);
}
void FIRST_SUM::updateChecksum(VariantID vid)
{
checksum[vid] += calcChecksum(m_x, getRunSize());
}
void FIRST_SUM::tearDown(VariantID vid)
{
(void) vid;
deallocData(m_x);
deallocData(m_y);
}
} // end namespace lcals
} // end namespace rajaperf
| [
"hornung1@llnl.gov"
] | hornung1@llnl.gov |
e94f6797328f2ca1b9e6a0c3edf6ed5095fb0dcb | d5a632c3abf23785f8d7de0b88abaac16d9b6861 | /unit-test/util/test_tc_timer.cpp | 0aac37d423868171e839811e21bc53ab4315bc9e | [
"BSD-3-Clause"
] | permissive | TarsCloud/TarsCpp | 423c317307c8839ab5bc3903702733e7de58c91c | 3ff6359173c087473032bff35ced648fbfaa0520 | refs/heads/master | 2023-09-04T11:34:16.804590 | 2023-09-02T14:24:32 | 2023-09-02T14:24:32 | 147,453,621 | 507 | 300 | BSD-3-Clause | 2023-08-25T02:35:58 | 2018-09-05T03:20:39 | C++ | UTF-8 | C++ | false | false | 4,842 | cpp | #include "util/tc_timer.h"
#include "util/tc_common.h"
#include "util/tc_cron.h"
#include "util/tc_epoller.h"
#include <cmath>
#include "gtest/gtest.h"
#include <iostream>
#include <vector>
using namespace std;
using namespace tars;
class UtilTimerTest : public testing::Test
{
public:
//添加日志
static void SetUpTestCase()
{
}
static void TearDownTestCase()
{
}
virtual void SetUp() //TEST跑之前会执行SetUp
{
}
virtual void TearDown() //TEST跑完之后会执行TearDown
{
}
};
class TestClass
{
public:
void test1()
{
_data.push_back(std::make_pair(TNOWMS, 0));
}
void test2(int64_t i)
{
_data.push_back(std::make_pair(TNOWMS, i));
}
void test3(int i)
{
_data.push_back(std::make_pair(TNOWMS, i));
}
void testCron()
{
_data.push_back(std::make_pair(TNOWMS, 0));
}
void testCron2()
{
_data.push_back(std::make_pair(TNOWMS, 0));
}
vector<pair<int64_t, int64_t>> _data;
};
TEST_F(UtilTimerTest, testDelayTask1)
{
TC_Timer timer;
timer.startTimer(1);
shared_ptr<TestClass> tPtr = std::make_shared<TestClass>();
timer.postDelayed(100, std::bind(&TestClass::test2, tPtr.get(), std::placeholders::_1), 111);
TC_Common::msleep(106);
ASSERT_TRUE(tPtr->_data.size() == 1);
timer.stopTimer();
}
TEST_F(UtilTimerTest, testDelayTask2)
{
TC_Timer timer;
timer.startTimer(1);
shared_ptr<TestClass> tPtr = std::make_shared<TestClass>();
uint64_t id2 = timer.postDelayed(100, std::bind(&TestClass::test2, tPtr.get(), std::placeholders::_1), 111);
TC_Common::msleep(5);
ASSERT_TRUE(tPtr->_data.size() == 0);
timer.erase(id2);
timer.stopTimer();
}
TEST_F(UtilTimerTest, testRepeatTask)
{
TC_Timer timer;
shared_ptr<TestClass> tPtr = std::make_shared<TestClass>();
timer.startTimer(1);
uint64_t id2 = timer.postRepeated(50, false, std::bind(&TestClass::test1, tPtr.get()));
TC_Common::msleep(1080);
//由于精度原因, 有一定误差
cout << tPtr->_data.size() << endl;
ASSERT_TRUE(tPtr->_data.size() >= 20);
ASSERT_TRUE(tPtr->_data.size() <= 21);
for (int i = 0; i < 9; i++)
{
int diff = fabs(tPtr->_data[i + 1].first - tPtr->_data[i].first);
ASSERT_TRUE(diff <= 56);
}
timer.erase(id2);
TC_Common::msleep(100);
ASSERT_TRUE(tPtr->_data.size() >= 20);
ASSERT_TRUE(tPtr->_data.size() <= 21);
timer.stopTimer();
}
struct AAA
{
AAA() { };
~AAA() { };
void test() {}
int xxx = 100;
};
void fff(const std::shared_ptr<AAA>& ppp)
{
ppp->xxx++;
// cout << TC_Common::now2ms() << ", " << ppp->xxx << endl;
}
TEST_F(UtilTimerTest, testTimerMem)
{
TC_Timer timer;
timer.startTimer(1);
std::shared_ptr<AAA> pa = std::make_shared<AAA>();
//right
{
auto func = [pa]
{
fff(pa);
};
int xxx = pa->xxx;
timer.postDelayed(100, func);
TC_Common::msleep(120);
ASSERT_TRUE(pa->xxx - xxx == 1);
}
//right
{
auto funcb = std::bind(fff, pa);
int xxx = pa->xxx;
timer.postDelayed(100, funcb);
TC_Common::msleep(120);
ASSERT_TRUE(pa->xxx - xxx == 1);
}
//right
{
int xxx = pa->xxx;
timer.postDelayed(100, fff, pa);
TC_Common::msleep(120);
ASSERT_TRUE(pa->xxx - xxx == 1);
}
//right
{
int xxx = pa->xxx;
timer.postDelayed(100, std::bind(fff, std::ref(pa)));
TC_Common::msleep(120);
ASSERT_TRUE(pa->xxx - xxx == 1);
}
//wrong, unkown reason
// if (1)
{
int xxx = pa->xxx;
timer.postDelayed(100, std::bind(fff, pa));
TC_Common::msleep(120);
ASSERT_TRUE(pa->xxx - xxx == 1);
}
timer.stopTimer();
}
TEST_F(UtilTimerTest, testTimerRepeatMem)
{
TC_Timer timer;
timer.startTimer(1);
std::shared_ptr<AAA> pa = std::make_shared<AAA>();
int xxx = pa->xxx;
auto func = [pa] {
fff(pa);
};
int64_t taskId = timer.postRepeated(50, false, func);
TC_Common::msleep(1020);
//注意timer有精度的问题, 精度只能到5ms, 所以这里有一定的误差!
int diff = pa->xxx - xxx;
cout << diff << endl;
ASSERT_TRUE(diff >= 19);
ASSERT_TRUE(diff <= 20);
timer.erase(taskId);
TC_Common::msleep(1000);
diff = pa->xxx - xxx;
ASSERT_TRUE(diff >= 19);
ASSERT_TRUE(diff <= 20);
timer.stopTimer();
}
TEST_F(UtilTimerTest, testRepeatUseCount)
{
TC_Timer timer;
timer.startTimer(1);
std::shared_ptr<AAA> pa = std::make_shared<AAA>();
ASSERT_TRUE(pa.use_count() == 1);
int64_t taskId = timer.postRepeated(50, false, std::bind(&AAA::test, pa));
ASSERT_TRUE(pa.use_count() == 2);
timer.erase(taskId);
ASSERT_TRUE(pa.use_count() == 1);
timer.postRepeated(50, false, std::bind(&AAA::test, pa));
ASSERT_TRUE(pa.use_count() == 2);
timer.clear();
ASSERT_TRUE(pa.use_count() == 1);
timer.stopTimer();
}
| [
"ruanshudong@qq.com"
] | ruanshudong@qq.com |
9cc984023463d736d83ef1dc4d2b0a14a773dd8c | 5838cf8f133a62df151ed12a5f928a43c11772ed | /NT/printscan/print/spooler/monitors/tcpmon/tcpmib/snmpmgr.cpp | 4c7c2b1aeaa9b7bb8326c930c19f576c4b4a2483 | [] | no_license | proaholic/Win2K3 | e5e17b2262f8a2e9590d3fd7a201da19771eb132 | 572f0250d5825e7b80920b6610c22c5b9baaa3aa | refs/heads/master | 2023-07-09T06:15:54.474432 | 2021-08-11T09:09:14 | 2021-08-11T09:09:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,637 | cpp | /*****************************************************************************
*
* $Workfile: SnmpMgr.cpp $
*
* Copyright (C) 1997 Hewlett-Packard Company.
* Copyright (C) 1997 Microsoft Corporation.
* All rights reserved.
*
* 11311 Chinden Blvd.
* Boise, Idaho 83714
*
*****************************************************************************/
#include "precomp.h"
#include "stdoids.h"
#include "snmpmgr.h"
///////////////////////////////////////////////////////////////////////////////
// CSnmpMgr::CSnmpMgr()
CSnmpMgr::CSnmpMgr() :
m_pAgent(NULL), m_pCommunity(NULL),m_pSession(NULL),
m_iLastError(NO_ERROR), m_iRetries(DEFAULT_RETRIES),
m_iTimeout(DEFAULT_TIMEOUT),
m_bRequestType(DEFAULT_SNMP_REQUEST)
{
} // ::CSnmpMgr()
///////////////////////////////////////////////////////////////////////////////
// CSnmpMgr::CSnmpMgr() -- establishes a session w/ a given agent
// uses the default request type (get) & community name (public)
CSnmpMgr::CSnmpMgr( const char in *pHost,
const char in *pCommunity,
DWORD dwDevIndex ) :
m_pAgent(NULL), m_pCommunity(NULL),m_pSession(NULL),
m_iLastError(NO_ERROR), m_iRetries(DEFAULT_RETRIES),
m_iTimeout(DEFAULT_TIMEOUT),
m_bRequestType(DEFAULT_SNMP_REQUEST)
{
size_t cchAgent = strlen(pHost) + 1;
m_pAgent = (LPSTR)SNMP_malloc(cchAgent * sizeof m_pAgent [0]); // copy the agent
if( m_pAgent != NULL )
{
StringCchCopyA (m_pAgent, cchAgent, pHost);
}
size_t cchCommunity = strlen(pCommunity) + 1;
m_pCommunity = (LPSTR)SNMP_malloc(cchCommunity * sizeof m_pCommunity [0]); // copy the community name
if( m_pCommunity != NULL )
{
StringCchCopyA (m_pCommunity, cchCommunity, pCommunity);
}
m_bRequestType = DEFAULT_SNMP_REQUEST; // set the default request type == GET request
m_pSession = NULL;
if ( !Open() ) // establish a session w/ the agent
{
m_iLastError = GetLastError();
}
} // ::CSnmpMgr()
///////////////////////////////////////////////////////////////////////////////
// CSnmpMgr::CSnmpMgr() -- establishes a session w/ a given agent
// uses the default request type (get) & community name (public)
CSnmpMgr::CSnmpMgr( const char in *pHost,
const char in *pCommunity,
DWORD in dwDevIndex,
AsnObjectIdentifier in *pMibObjId,
RFC1157VarBindList out *pVarBindList) :
m_pAgent(NULL), m_pCommunity(NULL),m_pSession(NULL),
m_iLastError(NO_ERROR), m_iRetries(DEFAULT_RETRIES),
m_iTimeout(DEFAULT_TIMEOUT),
m_bRequestType(DEFAULT_SNMP_REQUEST)
{
DWORD dwRetCode = SNMPAPI_NOERROR;
size_t cchAgent = strlen(pHost) + 1;
m_pAgent = (LPSTR)SNMP_malloc(cchAgent * sizeof m_pAgent [0]); // copy the agent
if( m_pAgent != NULL )
{
StringCchCopyA (m_pAgent, cchAgent, pHost);
}
size_t cchCommunity = strlen(pCommunity) + 1;
m_pCommunity = (LPSTR)SNMP_malloc(cchCommunity * sizeof m_pCommunity [0]); // copy the community name
if( m_pCommunity != NULL )
{
StringCchCopyA (m_pCommunity, cchCommunity, pCommunity);
}
m_bRequestType = DEFAULT_SNMP_REQUEST; // set the default request type == GET request
dwRetCode = BldVarBindList(pMibObjId, pVarBindList);
if (dwRetCode == SNMPAPI_NOERROR)
{
m_pSession = NULL;
if ( !Open() ) // establish a session w/ the agent
{
m_iLastError = GetLastError();
}
}
} // ::CSnmpMgr()
///////////////////////////////////////////////////////////////////////////////
// CSnmpMgr::~CSnmpMgr()
CSnmpMgr::~CSnmpMgr()
{
if (m_pSession) Close(); // close the session
// delete the allocated memory from community & agent names
if (m_pAgent) SNMP_free(m_pAgent);
if (m_pCommunity) SNMP_free(m_pCommunity);
} // ::~CSnmpMgr()
///////////////////////////////////////////////////////////////////////////////
// Open() -- establishes a session
// Error Codes:
// SNMPAPI_NOERROR if successful
// SNMPAPI_ERROR if fails
BOOL
CSnmpMgr::Open()
{
m_iLastError = SNMPAPI_NOERROR;
m_pSession = SnmpMgrOpen(m_pAgent, m_pCommunity, m_iTimeout, m_iRetries);
if ( m_pSession == NULL )
{
m_iLastError = SNMPAPI_ERROR;
m_pSession = NULL;
return FALSE;
}
return TRUE;
} // ::Open()
///////////////////////////////////////////////////////////////////////////////
// Close() -- closes the previously established session
void
CSnmpMgr::Close()
{
_ASSERTE( m_pSession != NULL);
if ( !SnmpMgrClose(m_pSession) )
{
m_iLastError = GetLastError();
}
m_pSession = NULL;
} // ::Close()
///////////////////////////////////////////////////////////////////////////////
// Get() -- does an SNMP command (m_bRequestType) given a set of OIDs
// Error Codes:
// SNMP_ERRORSTATUS_NOERROR if no error
// SNMP_ERRORSTATUS_TOOBIG if the packet returned is big
// SNMP_ERRORSTATUS_NOSUCHNAME if the OID isn't supported
// SNMP_ERRORSTATUS_BADVALUE
// SNMP_ERRORSTATUS_READONLY
// SNMP_ERRORSTATUS_GENERR
// SNMP_MGMTAPI_TIMEOUT -- set by GetLastError()
// SNMP_MGMTAPI_SELECT_FDERRORS -- set by GetLastError()
int
CSnmpMgr::Get( RFC1157VarBindList in *pVariableBindings)
{
int iRetCode = SNMP_ERRORSTATUS_NOERROR;
AsnInteger errorStatus;
AsnInteger errorIndex;
if ( !SnmpMgrRequest( m_pSession, m_bRequestType, pVariableBindings, &errorStatus, &errorIndex) )
{
iRetCode = m_iLastError = GetLastError();
}
else
{
if (errorStatus > 0)
{
iRetCode = errorStatus;
}
else // return the result of the variable bindings?
{
// variableBindings->list[x]->value contains the return value
}
}
return iRetCode;
} // ::Get()
///////////////////////////////////////////////////////////////////////////////
// Walk -- given an object, it walks until the tree is done
// Error Codes:
// SNMP_ERRORSTATUS_TOOBIG if the packet returned is big
// SNMP_ERRORSTATUS_NOSUCHNAME if the OID isn't supported
// SNMP_ERRORSTATUS_BADVALUE
// SNMP_ERRORSTATUS_READONLY
// SNMP_ERRORSTATUS_GENERR
// SNMP_MGMTAPI_TIMEOUT -- set by GetLastError()
// SNMP_MGMTAPI_SELECT_FDERRORS -- set by GetLastError()
int
CSnmpMgr::Walk( RFC1157VarBindList inout *pVariableBindings)
{
int iRetCode = SNMP_ERRORSTATUS_NOERROR;
RFC1157VarBindList variableBindings;
UINT numElements=0;
LPVOID pTemp;
variableBindings.len = 0;
variableBindings.list = NULL;
variableBindings.len++;
if ( (variableBindings.list = (RFC1157VarBind *)SNMP_realloc(variableBindings.list,
sizeof(RFC1157VarBind) * variableBindings.len)) == NULL)
{
iRetCode = ERROR_NOT_ENOUGH_MEMORY;
return iRetCode;
}
if ( !SnmpUtilVarBindCpy(&(variableBindings.list[variableBindings.len -1]), &(pVariableBindings->list[0])) )
{
iRetCode = ERROR_NOT_ENOUGH_MEMORY;
return iRetCode;
}
AsnObjectIdentifier root;
AsnObjectIdentifier tempOid;
AsnInteger errorStatus;
AsnInteger errorIndex;
if (!SnmpUtilOidCpy(&root, &variableBindings.list[0].name))
{
iRetCode = ERROR_NOT_ENOUGH_MEMORY;
goto CleanUp;
}
m_bRequestType = ASN_RFC1157_GETNEXTREQUEST;
while(1) // walk the MIB tree (or sub-tree)
{
if (!SnmpMgrRequest(m_pSession, m_bRequestType, &variableBindings,
&errorStatus, &errorIndex))
{
// The API is indicating an error.
iRetCode = m_iLastError = GetLastError();
break;
}
else
{
// The API succeeded, errors may be indicated from the remote agent.
// Test for end of subtree or end of MIB.
if (errorStatus == SNMP_ERRORSTATUS_NOSUCHNAME ||
SnmpUtilOidNCmp(&variableBindings.list[0].name, &root, root.idLength))
{
iRetCode = SNMP_ERRORSTATUS_NOSUCHNAME;
break;
}
// Test for general error conditions or sucesss.
if (errorStatus > 0)
{
iRetCode = errorStatus;
break;
}
numElements++;
} // end if()
// append the variableBindings to the pVariableBindings
_ASSERTE(pVariableBindings->len != 0);
if ( ( pTemp = (RFC1157VarBind *)SNMP_realloc(pVariableBindings->list,
sizeof(RFC1157VarBind) * (pVariableBindings->len + 1))) == NULL)
{
iRetCode = ERROR_NOT_ENOUGH_MEMORY;
break;
}
else
{
pVariableBindings->list = (SnmpVarBind *)pTemp;
pVariableBindings->len++;
}
if ( !SnmpUtilVarBindCpy(&(pVariableBindings->list[pVariableBindings->len -1]), &(variableBindings.list[0])) )
{
iRetCode = ERROR_NOT_ENOUGH_MEMORY;
break;
}
// Prepare for the next iteration. Make sure returned oid is
// preserved and the returned value is freed
if( SnmpUtilOidCpy(&tempOid, &variableBindings.list[0].name) )
{
SnmpUtilVarBindFree(&variableBindings.list[0]);
if ( SnmpUtilOidCpy(&variableBindings.list[0].name, &tempOid))
{
variableBindings.list[0].value.asnType = ASN_NULL;
SnmpUtilOidFree(&tempOid);
}
else
{
iRetCode = SNMP_ERRORSTATUS_GENERR;
goto CleanUp;
}
}
else
{
iRetCode = SNMP_ERRORSTATUS_GENERR;
goto CleanUp;
}
} // end while()
CleanUp:
// Free the variable bindings that have been allocated.
SnmpUtilVarBindListFree(&variableBindings);
SnmpUtilOidFree(&root);
if (iRetCode == SNMP_ERRORSTATUS_NOSUCHNAME)
if (numElements != 0) // list is full; iRetCode indicates the end of the MIB
iRetCode = SNMP_ERRORSTATUS_NOERROR;
return (iRetCode);
} // Walk()
///////////////////////////////////////////////////////////////////////////////
// WalkNext -- given object(s), it walks until the table has no more object
// entries. The end of the table is determined by the first item in the list.
// Error Codes:
// SNMP_ERRORSTATUS_TOOBIG if the packet returned is big
// SNMP_ERRORSTATUS_NOSUCHNAME if the OID isn't supported
// SNMP_ERRORSTATUS_BADVALUE
// SNMP_ERRORSTATUS_READONLY
// SNMP_ERRORSTATUS_GENERR
// SNMP_MGMTAPI_TIMEOUT -- set by GetLastError()
// SNMP_MGMTAPI_SELECT_FDERRORS -- set by GetLastError()
int
CSnmpMgr::WalkNext( RFC1157VarBindList inout *pVariableBindings)
{
int iRetCode = SNMP_ERRORSTATUS_NOERROR;
RFC1157VarBindList variableBindings;
UINT numElements=0;
UINT len=0, i=0;
LPVOID pTemp;
variableBindings.len = 0;
variableBindings.list = NULL;
variableBindings.len = pVariableBindings->len;
if ( (variableBindings.list = (RFC1157VarBind *)SNMP_realloc(variableBindings.list,
sizeof(RFC1157VarBind) * variableBindings.len)) == NULL)
{
iRetCode = ERROR_NOT_ENOUGH_MEMORY;
return iRetCode;
}
for (i=0; i<variableBindings.len; i++)
{
if ( !SnmpUtilVarBindCpy(&(variableBindings.list[i]), &(pVariableBindings->list[i])) )
{
iRetCode = ERROR_NOT_ENOUGH_MEMORY;
return iRetCode;
}
}
AsnObjectIdentifier root;
AsnObjectIdentifier tempOid;
AsnInteger errorStatus;
AsnInteger errorIndex;
if (!SnmpUtilOidCpy(&root, &variableBindings.list[0].name))
{
iRetCode = ERROR_NOT_ENOUGH_MEMORY;
goto CleanUp;
}
m_bRequestType = ASN_RFC1157_GETNEXTREQUEST;
while(1) // get the object(s) in the MIB table
{
if (!SnmpMgrRequest(m_pSession, m_bRequestType, &variableBindings,
&errorStatus, &errorIndex))
{
// The API is indicating an error.
iRetCode = m_iLastError = GetLastError();
break;
}
else
{
// The API succeeded, errors may be indicated from the remote agent.
// Test for end of subtree or end of MIB.
if (errorStatus == SNMP_ERRORSTATUS_NOSUCHNAME ||
SnmpUtilOidNCmp(&variableBindings.list[0].name, &root, root.idLength))
{
iRetCode = SNMP_ERRORSTATUS_NOSUCHNAME;
break;
}
// Test for general error conditions or sucesss.
if (errorStatus > 0)
{
iRetCode = errorStatus;
break;
}
numElements++;
} // end if()
// append the variableBindings to the pVariableBindings
_ASSERTE(pVariableBindings->len != 0);
len = pVariableBindings->len;
if ( (pTemp = (RFC1157VarBind *)SNMP_realloc(pVariableBindings->list,
sizeof(RFC1157VarBind) * (pVariableBindings->len + variableBindings.len))) == NULL)
{
iRetCode = ERROR_NOT_ENOUGH_MEMORY;
break;
}
else
{
pVariableBindings->list = (SnmpVarBind *)pTemp;
pVariableBindings->len += variableBindings.len;
}
int j=0;
for ( i=len; i < pVariableBindings->len; i++, j++)
{
if ( !SnmpUtilVarBindCpy(&(pVariableBindings->list[i]), &(variableBindings.list[j])) )
{
iRetCode = ERROR_NOT_ENOUGH_MEMORY;
break;
}
}
// Prepare for the next iteration. Make sure returned oid is
// preserved and the returned value is freed
for (i=0; i<variableBindings.len; i++)
{
if ( SnmpUtilOidCpy(&tempOid, &variableBindings.list[i].name) )
{
SnmpUtilVarBindFree(&variableBindings.list[i]);
if( SnmpUtilOidCpy(&variableBindings.list[i].name, &tempOid))
{
variableBindings.list[i].value.asnType = ASN_NULL;
SnmpUtilOidFree(&tempOid);
}
else
{
iRetCode = SNMP_ERRORSTATUS_GENERR;
goto CleanUp;
}
}
else
{
iRetCode = SNMP_ERRORSTATUS_GENERR;
goto CleanUp;
}
}
} // end while()
CleanUp:
// Free the variable bindings that have been allocated.
SnmpUtilVarBindListFree(&variableBindings);
SnmpUtilOidFree(&root);
if (iRetCode == SNMP_ERRORSTATUS_NOSUCHNAME)
if (numElements != 0) // list is full; iRetCode indicates the end of the MIB
iRetCode = SNMP_ERRORSTATUS_NOERROR;
return (iRetCode);
} // WalkNext()
///////////////////////////////////////////////////////////////////////////////
// GetNext -- does an SNMP GetNext command on the set of OID(s)
// Error Codes:
// SNMP_ERRORSTATUS_TOOBIG if the packet returned is big
// SNMP_ERRORSTATUS_NOSUCHNAME if the OID isn't supported
// SNMP_ERRORSTATUS_BADVALUE
// SNMP_ERRORSTATUS_READONLY
// SNMP_ERRORSTATUS_GENERR
// SNMP_MGMTAPI_TIMEOUT -- set by GetLastError()
// SNMP_MGMTAPI_SELECT_FDERRORS -- set by GetLastError()
int
CSnmpMgr::GetNext( RFC1157VarBindList inout *pVariableBindings)
{
int iRetCode = SNMP_ERRORSTATUS_NOERROR;
AsnInteger errorStatus;
AsnInteger errorIndex;
m_bRequestType = ASN_RFC1157_GETNEXTREQUEST;
if ( !SnmpMgrRequest( m_pSession, m_bRequestType, pVariableBindings, &errorStatus, &errorIndex) )
{
iRetCode = m_iLastError = GetLastError();
}
else
{
if (errorStatus > 0)
{
iRetCode = errorStatus;
}
else // return the result of the variable bindings?
{
// variableBindings->list[x]->value contains the return value
}
}
return (iRetCode);
} // GetNext()
///////////////////////////////////////////////////////////////////////////////
// BldVarBindList -- given a category, it retuns the RFC1157VarBindList
// Error Codes:
// NO_ERROR if successful
// ERROR_NOT_ENOUGH_MEMORY if memory allocation failes
// ERROR_INVALID_HANDLE if can't build the variable bindings
DWORD
CSnmpMgr::BldVarBindList( AsnObjectIdentifier in *pMibObjId, // group identifier
RFC1157VarBindList inout *pVarBindList)
{
DWORD dwRetCode = SNMPAPI_NOERROR;
LPVOID pTemp;
m_iLastError = SNMPAPI_NOERROR;
while (pMibObjId->idLength != 0)
{
// setup the variable bindings
CONST UINT uNewLen = pVarBindList->len + 1;
if ( (pTemp = (RFC1157VarBind *)SNMP_realloc(pVarBindList->list,
sizeof(RFC1157VarBind) * uNewLen)) == NULL)
{
m_iLastError = ERROR_NOT_ENOUGH_MEMORY;
return ERROR_NOT_ENOUGH_MEMORY;
}
else
{
pVarBindList->list = (SnmpVarBind *)pTemp;
pVarBindList-> len = uNewLen;
}
AsnObjectIdentifier reqObject;
if ( !SnmpUtilOidCpy(&reqObject, pMibObjId) )
{
m_iLastError = ERROR_INVALID_HANDLE;
return ERROR_INVALID_HANDLE;
}
pVarBindList->list[pVarBindList->len -1].name = reqObject;
pVarBindList->list[pVarBindList->len -1].value.asnType = ASN_NULL;
pMibObjId++;
}
return dwRetCode;
} // BldVarBindList
| [
"blindtiger@foxmail.com"
] | blindtiger@foxmail.com |
4b1f83d4fa1bdb82012495ccd3e6f4a92f0854df | 610cebc6ac4d0b934a3ffd3653a59d55deab2b2c | /code/DatabaseExperimentationProject/Main/gpu_queries.h | f3652897ab1919364dc5cdf93b84a02c6479b9e1 | [] | no_license | patrickkostjens/experimentation-project-databases | a5d6310761534ea9788e1e460f2b4880c440c920 | 479ea61751c7785fff790b108538fbd3137baebf | refs/heads/master | 2021-01-16T21:58:09.460153 | 2016-01-17T15:11:40 | 2016-01-17T15:11:40 | 34,780,281 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 180 | h | void RunGPUFilter(std::vector<LineItem>& items);
void RunGPUFilter(std::vector<Order>& orders);
void RunGPUSortMergeJoin(std::vector<LineItem>& items, std::vector<Order>& orders);
| [
"patrickkostjens@gmail.com"
] | patrickkostjens@gmail.com |
38a9697425a97693414bd975632eb0193dd4c2bf | e346ef1260a522d1fbedd63989be0cba7193eff9 | /process_example/forkProcess.cc | d419ad55ef96313b30708d8b215a89969ec532d5 | [] | no_license | hujuncheng132/ServerSide | 1a7882aa9ad863b91989b3564fe2635e5e0d351e | 2468a8e1e00b1308c2ee08032d58521edb820328 | refs/heads/master | 2020-07-05T04:29:05.740755 | 2019-09-03T02:13:56 | 2019-09-03T02:13:56 | 202,521,957 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 690 | cc | /*
创建一个子进程
*/
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
pid_t pid; //进程标识符,本质上就是一个无符号整型的类型别名
pid = fork(); //创建一个子进程,并返回子进程的PID
if(pid < 0)
{
perror("创建子进程错误\n");
exit(-1);
}
else if(pid == 0)
{
// sleep(1);
printf("此时位于子进程内:子进程的pid为%u,父进程的pid为%u\n",getpid(),getppid());
}
else
{
printf("此时位于父进程内:父进程的pid为%u,父进程的pid为%u\n",getpid(),pid);
}
return 0;
} | [
"973839291@qq.com"
] | 973839291@qq.com |
ac25370b2ea572d344f35b9d8f5c5c0e2e3352d7 | 77da2b0bc1ae9265c531f0756c2dc6db83888258 | /Opdracht5/Opdracht5/Main.cpp | 56298d96e51ad1cd474beb9bb8f1406068e4b036 | [] | no_license | MickGerrit/CPPBasic | a27b3d38cd5b0d5895b7a3880269f6655621bda5 | 5444b3f9908ccbed53a1c7d75fd6648747bb5913 | refs/heads/master | 2023-01-01T18:02:12.193416 | 2020-10-23T21:07:30 | 2020-10-23T21:07:30 | 306,746,804 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 446 | cpp | #include <iostream>
#include "Library.h"
int main() {
Library library = Library();
library.createBook("Hamlet");
library.createBook("Romeo & Julia");
Book* hamlet = library.rentBook("Hamlet");
Book* romeoAndJulia = library.rentBook("Romeo & Julia");
std::cout << "Renting this book: " << hamlet->bookTitle << std::endl;
std::cout << "Renting this book: " << romeoAndJulia->bookTitle << std::endl;
delete romeoAndJulia;
delete hamlet;
}
| [
"mick@gerritsen-online.nl"
] | mick@gerritsen-online.nl |
46975cc9ab66645a77ac63eda013b90894d5ee0e | d498af7e8d3ab7a58a60371dda47476e9d6cb3c4 | /src/tests/TestAppSatellite/MainWidget.hpp | 1606c1340562d9c646ab0af4963c37e54935509e | [] | no_license | SvOlli/SLART | 3121e5fa310f7b7f34309a3b15c084ee5e023ad4 | 85b42c9ec874f32afdecedb49c84b0ad7416ec0b | refs/heads/master | 2020-12-24T17:55:05.152518 | 2018-01-26T07:40:11 | 2018-01-26T07:40:11 | 2,235,857 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,077 | hpp | /*
* src/tests/TestAppSatellite/MainWidget.hpp
* written by Sven Oliver Moll
*
* distributed under the terms of the GNU General Public License (GPL)
* available at http://www.gnu.org/licenses/lgpl.html
*/
#ifndef MAINWIDGET_HPP
#define MAINWIDGET_HPP MAINWIDGET_HPP
/* base class */
#include <QWidget>
/* system headers */
/* Qt headers */
/* local library headers */
/* local headers */
/* forward declaration of Qt classes */
class QIcon;
class QString;
class QListWidget;
class QLineEdit;
/* forward declaration of local classes */
class Satellite;
class MainWidget : public QWidget
{
Q_OBJECT
public:
MainWidget( QWidget *parent = 0, Qt::WindowFlags flags = 0 );
public slots:
void handleInput();
void addDebug( const QByteArray &message );
void addMessage( const QByteArray &message, QListWidget *list = 0 );
signals:
void sendText( const QByteArray &text );
private:
Q_DISABLE_COPY( MainWidget )
Satellite *mpSatellite;
QListWidget *mpDebugBuffer;
QListWidget *mpMessageBuffer;
QLineEdit *mpInput;
};
#endif
| [
"svolli@svolli.org"
] | svolli@svolli.org |
a381018e914c5ab786bf788a14aa5443c868c25e | 372bfe808f8350693caa750c98805b3847393f75 | /dfstravers/traverse.h | a850dfea71051e659a81c6dc1f44815c9269a15a | [] | no_license | omidrazzaghi2000/ap1399-1-hw7-master | 69705747a225fc3252e2abc50a23edbac9136a38 | e27e059a9ff8e2c391aaeab66a6e2b75ee17f89b | refs/heads/master | 2023-02-14T14:25:32.289099 | 2021-01-07T20:08:15 | 2021-01-07T20:08:15 | 326,675,673 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 964 | h | #ifndef TRAVERSE_H
#define TRAVERSE_H
#include <iostream>
#include <vector>
#include <queue>
#include <memory>
#include "board.h"
std::vector<Board> BFSTraverse(Board start , Board goal ,int numberOfLevel);
class DFSTraverseClass{
public:
DFSTraverseClass();
~DFSTraverseClass()=default;
std::vector<Board> DFSTraverse(Board start , Board goal ,int numberOflevels, int level = 0 ,Direction formerDirection=Direction::NOTHING );
private:
std::vector<Board> solution;
std::vector<Board> final_solution;
bool finished=false;
};
class Node{
public:
std::shared_ptr<Node> fatherPointer;
std::shared_ptr<Board> UPchildPointer;
std::shared_ptr<Board> DOWNchildPointer;
std::shared_ptr<Board> LEFTchildPointer;
std::shared_ptr<Board> RIGHTchildPointer;
Board table;
Node(Board table , Direction);
Node()=default;
~Node()=default;
void disp();
};
#endif | [
"omidrazzaghi2000@gmail.com"
] | omidrazzaghi2000@gmail.com |
ed66c67100000261671c8c019b2d6a680f77d2ed | 5a87eaac41c3341c52fb01f347eb991b9aaffe95 | /unp/chapter11/11.14.cpp | 0f5159bae09aefbb4096eeff982409be97d26fa4 | [] | no_license | TTLIUJJ/MyLearning | 031cd457379a403a526478048604ccf00308b0fb | 1682796cb9f8da59e6c87e6e015aa4e12bbeab2a | refs/heads/master | 2021-01-17T17:48:21.252858 | 2017-03-25T15:10:48 | 2017-03-25T15:10:48 | 70,613,108 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,336 | cpp | #include <iostream>
#include "unp.h"
using namespace std;
int unp_client(const char *, const char *, SA **, socklen_t*);
int main(int argc, char **argv)
{
int sockfd, n;
char recvline[MAXLINE+1];
socklen_t salen;
struct sockaddr *sa;
if(argc != 3){
cerr << "usage: daytimeudpcli <hostname/IPaddress> <service/port#>" << endl;
return -1;
}
sockfd = unp_client(argv[1], argv[2], (SA **)&sa, &salen);
cout << "sending to ???" << endl;
sendto(sockfd, "", 1, 0, sa, salen);
n = recvfrom(sockfd, recvline, MAXLINE, 0, NULL, NULL);
recvline[n] = 0;
fputs(recvline, stdout);
exit(0);
}
int unp_client(const char *host, const char *serv, SA **saptr, socklen_t *lenp)
{
int sockfd, n;
struct addrinfo hints, *res, *ressave;
bzero(&hints, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
if((n = getaddrinfo(host, serv, &hints, &res)) != 0){
cerr << "unp_client error for " << host << ", " << serv << ": " << gai_strerror(n) << endl;
return -1;
}
ressave = res;
do{
sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if(sockfd >= 0)
break;
}while((res = res->ai_next) != NULL);
*saptr = (SA *)malloc(res->ai_addrlen);
memcpy(*saptr, res->ai_addr, res->ai_addrlen);
*lenp = res->ai_addrlen;
freeaddrinfo(ressave);
return sockfd;
}
| [
"TTLIUJJ@GMAIL.COM"
] | TTLIUJJ@GMAIL.COM |
4ae1f9e309a3eb933e7ddfc37c4feaf06dadca48 | ec681d943400d1ce01c1de6ccdea5245c3a87646 | /corecpp/Chapter02/Listing06.cpp | 467e4fb3f8e0b2bdf1eb5d76beb18ba882faa6a9 | [] | no_license | hechenyu/book_code | 84ca011308c9d4faaff9050a8bdcc4cbbd0ea1cc | 4e1501bb1918f55be60bed1bd03f3441f0bdc66b | refs/heads/master | 2020-05-21T04:34:03.457535 | 2017-07-12T11:37:40 | 2017-07-12T11:37:40 | 65,210,563 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 777 | cpp | // Listing 2-6. Your first C++ program with a nested statement block
#include <iostream> // preprocessor directives
#include <cmath>
using namespace std;
const double PI = 3.1415926; // definition of a constant
int main(void)
{
double x=PI, y=1, z; // definitions of variables
cout << "Welcome to the C++ world!" << endl;
z = y + 1;
y = pow(x,z);
{ // start of statement block
cout << "In that world, pi square is " << y << endl;
cout << "Have a nice day!" << endl;
return 0;
} // end of statement block
} // end of function block
| [
"hexu_bupt@sina.com"
] | hexu_bupt@sina.com |
bbf8cf8813e1ac774085384fbefa54f5588cee3b | 2d34422361367d6fb28167c713f689ee7084d5c0 | /libraries/isotropicHyperelasticFEM/StVKIsotropicMaterial.h | 689fec3f06630e1628e1c72555da190f1cc03a87 | [] | no_license | kengwit/VegaFEM-v3.0 | 5c307de1f2a2f57c2cc7d111c1da989fe07202f4 | 6eb4822f8d301d502d449d28bcfb5b9dbb916f08 | refs/heads/master | 2021-12-10T15:03:14.828219 | 2016-08-24T12:04:03 | 2016-08-24T12:04:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,354 | h | /*************************************************************************
* *
* Vega FEM Simulation Library Version 3.0 *
* *
* "isotropic hyperelastic FEM" library , Copyright (C) 2016 USC *
* All rights reserved. *
* *
* Code authors: Jernej Barbic, Fun Shing Sin *
* http://www.jernejbarbic.com/code *
* *
* Research: Jernej Barbic, Fun Shing Sin, Daniel Schroeder, *
* Doug L. James, Jovan Popovic *
* *
* Funding: National Science Foundation, Link Foundation, *
* Singapore-MIT GAMBIT Game Lab, *
* Zumberge Research and Innovation Fund at USC *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the BSD-style license that is *
* included with this library in the file LICENSE.txt *
* *
* 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 file *
* LICENSE.TXT for more details. *
* *
*************************************************************************/
#ifndef _STVKISOTROPICMATERIAL_H_
#define _STVKISOTROPICMATERIAL_H_
#include "isotropicMaterialWithCompressionResistance.h"
#include "tetMesh.h"
/*
StVK material. Material properties are read from the tet mesh, and can be heterogeneous.
The implemented St.Venant-Kirchhoff material is described in:
BONET J., WOOD R. D.: Nonlinear Continuum Mechanics
for Finite Element Analysis, 2nd Ed. Cambridge University
Press, 2008, page 158
*/
class StVKIsotropicMaterial : public IsotropicMaterialWithCompressionResistance
{
public:
StVKIsotropicMaterial(TetMesh * tetMesh, int enableCompressionResistance=0, double compressionResistance=0.0);
virtual ~StVKIsotropicMaterial();
virtual double ComputeEnergy(int elementIndex, double * invariants);
virtual void ComputeEnergyGradient(int elementIndex, double * invariants, double * gradient); // invariants and gradient are 3-vectors
virtual void ComputeEnergyHessian(int elementIndex, double * invariants, double * hessian); // invariants is a 3-vector, hessian is a 3x3 symmetric matrix, unrolled into a 6-vector, in the following order: (11, 12, 13, 22, 23, 33).
protected:
double * lambdaLame;
double * muLame;
double compressionResistance;
double * EdivNuFactor;
virtual double GetCompressionResistanceFactor(int elementIndex);
};
#endif
| [
"jslee02@gmail.com"
] | jslee02@gmail.com |
40ef2b6638dacc8d860eb186cd15d23f1856770b | 2a105ba28278ac3c3aa959ab5a1b2176f5b703dc | /MTJSocketClient/Src/MTJSocket.cpp | 7c6e9930c19f90b126e4d1f5b959b2d13c58d050 | [] | no_license | mingxinkejian/MTJSocketClient | 5a1a02bc89cb3cb1c19be0b05739b71ee8302acc | 7846eb4b07b4c4ccc656c3b780732f1568cd4b75 | refs/heads/master | 2021-01-10T23:28:22.699930 | 2016-10-13T03:15:53 | 2016-10-13T03:15:53 | 70,582,820 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,537 | cpp | //
// MTJSocket.cpp
// MTJSocketClient
//
// Created by Reddog on 16/10/11.
// Copyright (c) 2016年 mingtingjian. All rights reserved.
//
#include "MTJSocket.h"
#include <errno.h>
MTJSocket::MTJSocket():
m_pIP(NULL),
m_pListener(NULL),
m_pProtocal(NULL)
{
}
MTJSocket::~MTJSocket(){
MTJ_SAFE_DELETE(m_pProtocal);
MTJ_SAFE_DELETE(m_pListener);
}
int MTJSocket::GetSocketId(){
return m_nSsockId;
}
MTJSocketListener* MTJSocket::GetListener(){
return m_pListener;
}
MTJSocketProtocal* MTJSocket::GetProtocal(){
return this->m_pProtocal;
}
void MTJSocket::SetProtocal(MTJSocketProtocal *pProtocal){
m_pProtocal = pProtocal;
}
void MTJSocket::Open(MTJSocketListener *pListener,SocketType eSockType){
m_pListener = pListener;
m_pListener->SetContext(this);
int domain = -1;
int type = -1;
switch (eSockType) {
case SOCK_TCP:
domain = AF_INET;
type = SOCK_STREAM;
break;
case SOCK_TCP6:
domain = AF_INET6;
type = SOCK_STREAM;
break;
case SOCK_UDP:
domain = AF_INET;
type = SOCK_DGRAM;
break;
case SOCK_UDP6:
domain = AF_INET6;
type = SOCK_DGRAM;
break;
#if TARGET_PLATFORM != PLATFORM_WIN32
//windows下不支持此参数,在客户端不建议使用下面两个选项,仅作为支持
case SOCK_UNIX_DGRAM:
domain = AF_UNIX;
type = SOCK_DGRAM;
break;
case SOCK_UNIX_STREAM:
domain = AF_UNIX;
type = SOCK_STREAM;
break;
#endif
default:
domain = AF_INET;
type = SOCK_STREAM;
break;
}
m_nDomain = domain;
m_nType = type;
m_eSockType = eSockType;
m_nSsockId = socket(AF_INET, SOCK_STREAM, 0);
}
void MTJSocket::Connect(const char* ip,unsigned int port,double dTimeout,int nFlag){
m_pIP = ip;
m_nPort = port;
if (m_nSsockId != INVALID_SOCKET) {
if (InitInetAddr() != 1) {
//不等于1表示创建失败
m_pListener->OnClose(this, false);
}else{
//特殊处理,UDP为无连接协议
if (m_eSockType == SOCK_UDP || m_eSockType == SOCK_UDP6) {
// goto UDP;
}
int connError;
extern int errno;
if ((connError = connect(m_nSsockId, (struct sockaddr*)&m_sSockAddr.addr, m_sSockAddr.len)) != SOCKET_ERROR) {
// UDP:
int bufSize = SOCKET_UDP_SIZE; //通常设置为32K
if (m_eSockType == SOCK_UDP || m_eSockType == SOCK_UDP6) {
setsockopt(m_nSsockId, SOL_SOCKET, SO_SNDBUF, &bufSize, sizeof(bufSize));
setsockopt(m_nSsockId, SOL_SOCKET, SO_RCVBUF, &bufSize, sizeof(bufSize));
}
m_pListener->OnOpen(this);
m_pListener->Start();
}else{
printf("connect error code: %d\n",errno);
m_pListener->OnClose(this, false);
}
}
}else{
m_pListener->OnClose(this, false);
}
}
int MTJSocket::InitInetAddr(){
void* s_addr = NULL;
if (m_eSockType == SOCK_TCP || m_eSockType == SOCK_UDP) {
m_sSockAddr.addr.inetv4.sin_family = AF_INET;
m_sSockAddr.addr.inetv4.sin_port = htons(m_nPort);
s_addr = &m_sSockAddr.addr.inetv4.sin_addr.s_addr;
m_sSockAddr.len = sizeof(m_sSockAddr.addr.inetv4);
//inet_pton为新的函数,支持IPV6,inet_addr比较老
if (inet_pton(AF_INET, m_pIP, s_addr)) {
return 1;
}
}else if(m_eSockType == SOCK_TCP6 || m_eSockType == SOCK_UDP6){
m_sSockAddr.addr.inetv6.sin6_family = AF_INET6;
m_sSockAddr.addr.inetv6.sin6_port = htons(m_nPort);
s_addr = &m_sSockAddr.addr.inetv6.sin6_addr.s6_addr;
m_sSockAddr.len = sizeof(m_sSockAddr.addr.inetv6);
if (inet_pton(AF_INET6, m_pIP, s_addr)) {
return 1;
}
}else if(m_eSockType == SOCK_UNIX_STREAM || m_eSockType == SOCK_UNIX_DGRAM){
printf("sorry unsupport SOCK_UNIX_STREAM or SOCK_UNIX_DGRAM\n");
}
return -1;
}
int MTJSocket::Close(){
if (m_nSsockId == -1) {
return -1;
}
int t = m_nSsockId;
m_nSsockId = -1;
#if TARGET_PLATFORM == PLATFORM_WIN32
shutdown(t, SD_SEND);
return (closesocket(t));
#else
shutdown(t, SHUT_RDWR);
return close(t);
#endif
}
int MTJSocket::Send(MTJSocketBuffer *frame){
char* content = frame->GetData();
int bytes = 0;
int count = 0;
int len = frame->ReadableBytes();
if (m_eSockType == SOCK_TCP || m_eSockType == SOCK_TCP6) {
while (count < len) {
bytes = (int)send(m_nSsockId, content + count, len - count, 0);
if (bytes == -1 || bytes == 0) {
return -1;
}
count += bytes;
frame->ReaderIndex(frame->ReaderIndex() + bytes);
}
}else if (m_eSockType == SOCK_UDP || m_eSockType == SOCK_UDP6){
extern int errno;
count = (int)sendto(m_nSsockId, content, len, 0, (struct sockaddr*)&m_sSockAddr.addr, m_sSockAddr.len);
printf("sendto error code: %d\n",errno);
}
return count;
}
int MTJSocket::Send(MTJSocketDataFrame *frame){
if (frame->IsEnd()) {
return Send(frame->GetData());
}
return 0;
} | [
"mingtingjian@sina.com"
] | mingtingjian@sina.com |
711cc48c3e5aa342278b70738903d4801907a830 | 1a8331d4d2220a5c37232f766b726d0429622cfb | /main.edu.pl/POI/18th/met.cpp | de0b9e733f8b4f4ea0e8b6d232e6ea9c4792aed8 | [] | no_license | ngthanhvinh/competitive-programming | 90918dda51b7020348d2c63b68320a52702eba47 | cad90ac623e362d54df9a7d71c317de555d35080 | refs/heads/master | 2022-04-21T07:02:07.239086 | 2020-04-18T08:05:59 | 2020-04-18T08:05:59 | 176,119,804 | 0 | 1 | null | 2020-04-18T08:06:01 | 2019-03-17T15:19:38 | Roff | UTF-8 | C++ | false | false | 1,725 | cpp | #include <bits/stdc++.h>
using namespace std;
const int N = 300010;
const long long INF = 1e18;
typedef pair<int,int> ii;
long long t[N];
int n, m, q;
void upd(int x, int val) { for (; x <= m; x += x & -x) t[x] += val; }
long long get(int x) { long long res = 0; for (; x > 0; x -= x & -x) res += t[x], res = min(res, INF); return res; }
void upd(int l, int r, int val) { upd(l, val); upd(r+1, -val); }
void query(int l, int r, int val) {
if (l <= r) return upd(l, r, val);
else upd(l, m, val), upd(1, r, val);
}
long long getPoint(int x) { return get(x); }
#undef mid
int u[N], v[N], k[N], a[N], lim[N];
int lo[N], hi[N];
vector <int> met[N];
vector <ii> curMid;
void reset() {
curMid.clear();
for (int i = 1; i <= n; i++) if (!((lo[i] == hi[i] && lo[i] != q) || lo[i] > hi[i]))
curMid.push_back(ii((lo[i] + hi[i]) >> 1, i));
sort(curMid.begin(), curMid.end());
memset(t, 0, sizeof t);
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; i++) scanf("%d", &a[i]), met[a[i]].push_back(i);
for (int i = 1; i <= n; i++) scanf("%d", &lim[i]);
cin >> q;
for (int i = 1; i <= n; i++) lo[i] = 0, hi[i] = q;
for (int i = 1; i <= q; i++) scanf("%d%d%d", &u[i], &v[i], &k[i]);
for (int times = 0; times < 19; times++) {
reset();
int ptr = 1;
for (int i = 0; i < curMid.size(); i++) {
int mid = curMid[i].first, p = curMid[i].second;
while(ptr <= mid && ptr <= q) query(u[ptr], v[ptr], k[ptr]), ptr++;
long long sum = 0;
for (int j = 0; j < met[p].size(); j++) sum += getPoint(met[p][j]), sum = min(sum, INF);
if (sum >= lim[p]) hi[p] = mid;
else lo[p] = mid + 1;
}
}
for (int i = 1; i <= n; i++)
if (lo[i] == q+1) printf("NIE\n");
else printf("%d\n", lo[i]);
} | [
"ngthanhvinh2000@gmail.com"
] | ngthanhvinh2000@gmail.com |
13f2db554e5ad742a9967f2d44a346f14e242fac | 5141d53672d52879444bc2ca2c9329a725ded6ef | /sources/week2/7-7.cpp | 8307a7cc0b3f1b669d80febe1cf1bb2781c73050 | [] | no_license | uuwuuwwuu/2021SummerPPS | c31053fc866d7450a49a705622bea146d31e34a6 | 3d709e83cedeaf3f89976d843b959ab7968c24c4 | refs/heads/main | 2023-06-21T00:47:58.914150 | 2021-07-18T14:22:18 | 2021-07-18T14:22:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 269 | cpp | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
int n, k;
cin >> n >> k;
vector<int> nums(n);
for (int i = 0; i < n; i++)
cin >> nums[i];
sort(nums.begin(), nums.end());
cout << nums[k - 1] << endl;
return 0;
} | [
"84551508+Gyuhyun-Kim@users.noreply.github.com"
] | 84551508+Gyuhyun-Kim@users.noreply.github.com |
eb789f0250a7e84236cd4dacaa6904eded223baf | f699576e623d90d2e07d6c43659a805d12b92733 | /WTLOnline-SDK/SDK/WTLOnline_BP_NPC_BlackMarketDealer_functions.cpp | 610f9891e38daf76202e1d71fae7d8240769b1b4 | [] | no_license | ue4sdk/WTLOnline-SDK | 2309620c809efeb45ba9ebd2fc528fa2461b9ca0 | ff244cd4118c54ab2048ba0632b59ced111c405c | refs/heads/master | 2022-07-12T13:02:09.999748 | 2019-04-22T08:22:35 | 2019-04-22T08:22:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,968 | cpp | // Will To Live Online (0.57) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "WTLOnline_BP_NPC_BlackMarketDealer_classes.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function BP_NPC_BlackMarketDealer.BP_NPC_BlackMarketDealer_C.GetReplicaArrayMainDialog
// (FUNC_Public, FUNC_HasOutParms, FUNC_BlueprintCallable, FUNC_BlueprintEvent)
// Parameters:
// class AWTLCharacter* Character (CPF_BlueprintVisible, CPF_BlueprintReadOnly, CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
// TArray<int> IncharacterReplicaArray (CPF_BlueprintVisible, CPF_BlueprintReadOnly, CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_ReferenceParm)
// TArray<int> CharacterReplicaArray (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor)
void ABP_NPC_BlackMarketDealer_C::GetReplicaArrayMainDialog(class AWTLCharacter* Character, TArray<int>* IncharacterReplicaArray, TArray<int>* CharacterReplicaArray)
{
static auto fn = UObject::FindObject<UFunction>(_xor_("Function BP_NPC_BlackMarketDealer.BP_NPC_BlackMarketDealer_C.GetReplicaArrayMainDialog"));
struct
{
class AWTLCharacter* Character;
TArray<int> IncharacterReplicaArray;
TArray<int> CharacterReplicaArray;
} params;
params.Character = Character;
UObject::ProcessEvent(fn, ¶ms);
if (IncharacterReplicaArray != nullptr)
*IncharacterReplicaArray = params.IncharacterReplicaArray;
if (CharacterReplicaArray != nullptr)
*CharacterReplicaArray = params.CharacterReplicaArray;
}
// Function BP_NPC_BlackMarketDealer.BP_NPC_BlackMarketDealer_C.ExecutingAction
// (FUNC_Public, FUNC_HasOutParms, FUNC_BlueprintCallable, FUNC_BlueprintEvent)
// Parameters:
// class AWTLCharacter* Character (CPF_BlueprintVisible, CPF_BlueprintReadOnly, CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
// EWTLNPCReplicaAction Action (CPF_BlueprintVisible, CPF_BlueprintReadOnly, CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
// int QuestID (CPF_BlueprintVisible, CPF_BlueprintReadOnly, CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
// int CurrentReplicaID (CPF_BlueprintVisible, CPF_BlueprintReadOnly, CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
// int InNPCReplicaID (CPF_BlueprintVisible, CPF_BlueprintReadOnly, CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
// TArray<int> IncharacterReplicaArray (CPF_BlueprintVisible, CPF_BlueprintReadOnly, CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_ReferenceParm)
void ABP_NPC_BlackMarketDealer_C::ExecutingAction(class AWTLCharacter* Character, EWTLNPCReplicaAction Action, int QuestID, int CurrentReplicaID, int InNPCReplicaID, TArray<int>* IncharacterReplicaArray)
{
static auto fn = UObject::FindObject<UFunction>(_xor_("Function BP_NPC_BlackMarketDealer.BP_NPC_BlackMarketDealer_C.ExecutingAction"));
struct
{
class AWTLCharacter* Character;
EWTLNPCReplicaAction Action;
int QuestID;
int CurrentReplicaID;
int InNPCReplicaID;
TArray<int> IncharacterReplicaArray;
} params;
params.Character = Character;
params.Action = Action;
params.QuestID = QuestID;
params.CurrentReplicaID = CurrentReplicaID;
params.InNPCReplicaID = InNPCReplicaID;
UObject::ProcessEvent(fn, ¶ms);
if (IncharacterReplicaArray != nullptr)
*IncharacterReplicaArray = params.IncharacterReplicaArray;
}
// Function BP_NPC_BlackMarketDealer.BP_NPC_BlackMarketDealer_C.GetRandomReplicaID
// (FUNC_Public, FUNC_HasOutParms, FUNC_BlueprintCallable, FUNC_BlueprintEvent)
// Parameters:
// TArray<int> ReplicaIDArray (CPF_BlueprintVisible, CPF_BlueprintReadOnly, CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_ReferenceParm)
// int ReplicaID (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_IsPlainOldData)
void ABP_NPC_BlackMarketDealer_C::GetRandomReplicaID(TArray<int>* ReplicaIDArray, int* ReplicaID)
{
static auto fn = UObject::FindObject<UFunction>(_xor_("Function BP_NPC_BlackMarketDealer.BP_NPC_BlackMarketDealer_C.GetRandomReplicaID"));
struct
{
TArray<int> ReplicaIDArray;
int ReplicaID;
} params;
UObject::ProcessEvent(fn, ¶ms);
if (ReplicaIDArray != nullptr)
*ReplicaIDArray = params.ReplicaIDArray;
if (ReplicaID != nullptr)
*ReplicaID = params.ReplicaID;
}
// Function BP_NPC_BlackMarketDealer.BP_NPC_BlackMarketDealer_C.ShowStartDialog
// (FUNC_Public, FUNC_BlueprintCallable, FUNC_BlueprintEvent)
// Parameters:
// class AWTLCharacter* Character (CPF_BlueprintVisible, CPF_BlueprintReadOnly, CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
void ABP_NPC_BlackMarketDealer_C::ShowStartDialog(class AWTLCharacter* Character)
{
static auto fn = UObject::FindObject<UFunction>(_xor_("Function BP_NPC_BlackMarketDealer.BP_NPC_BlackMarketDealer_C.ShowStartDialog"));
struct
{
class AWTLCharacter* Character;
} params;
params.Character = Character;
UObject::ProcessEvent(fn, ¶ms);
}
// Function BP_NPC_BlackMarketDealer.BP_NPC_BlackMarketDealer_C.UserConstructionScript
// (FUNC_Event, FUNC_Public, FUNC_BlueprintCallable, FUNC_BlueprintEvent)
void ABP_NPC_BlackMarketDealer_C::UserConstructionScript()
{
static auto fn = UObject::FindObject<UFunction>(_xor_("Function BP_NPC_BlackMarketDealer.BP_NPC_BlackMarketDealer_C.UserConstructionScript"));
struct
{
} params;
UObject::ProcessEvent(fn, ¶ms);
}
// Function BP_NPC_BlackMarketDealer.BP_NPC_BlackMarketDealer_C.Timeline_0_0__FinishedFunc
// (FUNC_BlueprintEvent)
void ABP_NPC_BlackMarketDealer_C::Timeline_0_0__FinishedFunc()
{
static auto fn = UObject::FindObject<UFunction>(_xor_("Function BP_NPC_BlackMarketDealer.BP_NPC_BlackMarketDealer_C.Timeline_0_0__FinishedFunc"));
struct
{
} params;
UObject::ProcessEvent(fn, ¶ms);
}
// Function BP_NPC_BlackMarketDealer.BP_NPC_BlackMarketDealer_C.Timeline_0_0__UpdateFunc
// (FUNC_BlueprintEvent)
void ABP_NPC_BlackMarketDealer_C::Timeline_0_0__UpdateFunc()
{
static auto fn = UObject::FindObject<UFunction>(_xor_("Function BP_NPC_BlackMarketDealer.BP_NPC_BlackMarketDealer_C.Timeline_0_0__UpdateFunc"));
struct
{
} params;
UObject::ProcessEvent(fn, ¶ms);
}
// Function BP_NPC_BlackMarketDealer.BP_NPC_BlackMarketDealer_C.Timeline_0__FinishedFunc
// (FUNC_BlueprintEvent)
void ABP_NPC_BlackMarketDealer_C::Timeline_0__FinishedFunc()
{
static auto fn = UObject::FindObject<UFunction>(_xor_("Function BP_NPC_BlackMarketDealer.BP_NPC_BlackMarketDealer_C.Timeline_0__FinishedFunc"));
struct
{
} params;
UObject::ProcessEvent(fn, ¶ms);
}
// Function BP_NPC_BlackMarketDealer.BP_NPC_BlackMarketDealer_C.Timeline_0__UpdateFunc
// (FUNC_BlueprintEvent)
void ABP_NPC_BlackMarketDealer_C::Timeline_0__UpdateFunc()
{
static auto fn = UObject::FindObject<UFunction>(_xor_("Function BP_NPC_BlackMarketDealer.BP_NPC_BlackMarketDealer_C.Timeline_0__UpdateFunc"));
struct
{
} params;
UObject::ProcessEvent(fn, ¶ms);
}
// Function BP_NPC_BlackMarketDealer.BP_NPC_BlackMarketDealer_C.ReceiveBeginPlay
// (FUNC_Event, FUNC_Protected, FUNC_BlueprintEvent)
void ABP_NPC_BlackMarketDealer_C::ReceiveBeginPlay()
{
static auto fn = UObject::FindObject<UFunction>(_xor_("Function BP_NPC_BlackMarketDealer.BP_NPC_BlackMarketDealer_C.ReceiveBeginPlay"));
struct
{
} params;
UObject::ProcessEvent(fn, ¶ms);
}
// Function BP_NPC_BlackMarketDealer.BP_NPC_BlackMarketDealer_C.OnNPCDialogActivated
// (FUNC_Event, FUNC_Public, FUNC_BlueprintEvent)
// Parameters:
// class AWTLCharacter* Character (CPF_BlueprintVisible, CPF_BlueprintReadOnly, CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
void ABP_NPC_BlackMarketDealer_C::OnNPCDialogActivated(class AWTLCharacter* Character)
{
static auto fn = UObject::FindObject<UFunction>(_xor_("Function BP_NPC_BlackMarketDealer.BP_NPC_BlackMarketDealer_C.OnNPCDialogActivated"));
struct
{
class AWTLCharacter* Character;
} params;
params.Character = Character;
UObject::ProcessEvent(fn, ¶ms);
}
// Function BP_NPC_BlackMarketDealer.BP_NPC_BlackMarketDealer_C.OnPlayerSelectReplica
// (FUNC_Event, FUNC_Public, FUNC_BlueprintEvent)
// Parameters:
// class AWTLCharacter* Character (CPF_BlueprintVisible, CPF_BlueprintReadOnly, CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
// int ReplicaID (CPF_BlueprintVisible, CPF_BlueprintReadOnly, CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
void ABP_NPC_BlackMarketDealer_C::OnPlayerSelectReplica(class AWTLCharacter* Character, int ReplicaID)
{
static auto fn = UObject::FindObject<UFunction>(_xor_("Function BP_NPC_BlackMarketDealer.BP_NPC_BlackMarketDealer_C.OnPlayerSelectReplica"));
struct
{
class AWTLCharacter* Character;
int ReplicaID;
} params;
params.Character = Character;
params.ReplicaID = ReplicaID;
UObject::ProcessEvent(fn, ¶ms);
}
// Function BP_NPC_BlackMarketDealer.BP_NPC_BlackMarketDealer_C.ReceiveTick
// (FUNC_Event, FUNC_Public, FUNC_BlueprintEvent)
// Parameters:
// float DeltaSeconds (CPF_BlueprintVisible, CPF_BlueprintReadOnly, CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
void ABP_NPC_BlackMarketDealer_C::ReceiveTick(float DeltaSeconds)
{
static auto fn = UObject::FindObject<UFunction>(_xor_("Function BP_NPC_BlackMarketDealer.BP_NPC_BlackMarketDealer_C.ReceiveTick"));
struct
{
float DeltaSeconds;
} params;
params.DeltaSeconds = DeltaSeconds;
UObject::ProcessEvent(fn, ¶ms);
}
// Function BP_NPC_BlackMarketDealer.BP_NPC_BlackMarketDealer_C.ExecuteUbergraph_BP_NPC_BlackMarketDealer
// (FUNC_Final)
// Parameters:
// int EntryPoint (CPF_BlueprintVisible, CPF_BlueprintReadOnly, CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
void ABP_NPC_BlackMarketDealer_C::ExecuteUbergraph_BP_NPC_BlackMarketDealer(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>(_xor_("Function BP_NPC_BlackMarketDealer.BP_NPC_BlackMarketDealer_C.ExecuteUbergraph_BP_NPC_BlackMarketDealer"));
struct
{
int EntryPoint;
} params;
params.EntryPoint = EntryPoint;
UObject::ProcessEvent(fn, ¶ms);
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"igromanru@yahoo.de"
] | igromanru@yahoo.de |
832b8cb3375fabb087c1eaf8ba7ab37c2655a6c4 | 0f08276e557de8437759659970efc829a9cbc669 | /problems/p1617.h | 6286535e773012855047bf583c635de8ceedfc71 | [] | no_license | petru-d/leetcode-solutions-reboot | 4fb35a58435f18934b9fe7931e01dabcc9d05186 | 680dc63d24df4c0cc58fcad429135e90f7dfe8bd | refs/heads/master | 2023-06-14T21:58:53.553870 | 2021-07-11T20:41:57 | 2021-07-11T20:41:57 | 250,795,996 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 66 | h | #pragma once
namespace p1617
{
class Solution
{
};
}
| [
"berserk.ro@gmail.com"
] | berserk.ro@gmail.com |
b51f0c981e66f5b6f494e3b7db5143f730cc0551 | 2b23b92fccd94b957762a7f472228a73a3a4b8d9 | /W.c++ | dee5f77179be26aec0123599e30404b177dbb1b6 | [] | no_license | nAthHaiman/Newcomer_sheet--Codeforces--Sheet--2 | 762dc471767bb47f200fce9a682303c5015ad94e | 7d244319334330a0090f7de544d7b6580e5af28d | refs/heads/main | 2023-07-19T11:55:55.037444 | 2021-08-24T16:23:15 | 2021-08-24T16:23:15 | 391,688,503 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 445 | #include<iostream>
using namespace std;
int main()
{
int n,row,col;
cin>>n;
for(row=1;row<=n;row++)
{
for(col=1;col<=n-row;col++)
cout<<" ";
for(col=1;col<=2*row-1;col++)
cout<<"*";
cout<<endl;
}
for(row=n;row>=1;row--)
{
for(col=1;col<=n-row;col++)
cout<<" ";
for(col=1;col<=2*row-1;col++)
cout<<"*";
cout<<endl;
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com | |
452a0d39c96a78a5c2d53bbc5e3d9512c1b4a9bd | c8b22b02e6a6c88c5b03cd869839f24beda4c2e3 | /dm40_最小的k个数.h | 3d29f03c0d091b278e05fb52c917adf3532ba95a | [] | no_license | czopg/SwordToOffer | 881b5b129652c2840250af1ec97cdbc3f1d30afb | a463b06ebdbc618b411393a943733d8a763c2ea3 | refs/heads/master | 2020-07-31T04:42:50.531126 | 2019-09-24T02:24:07 | 2019-09-24T02:24:07 | 210,487,893 | 2 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,384 | h | #pragma once
#include <vector>
#include <set>
#include <functional>
using namespace std;
/**
* 方法1 参考快速排序算法的partition函数,类似dm39
* 以第k个数作为枢纽,递归求解 O(n)
*/
void getLeastNumbers(int* input, int n, int* output, int k)
{
if (input == nullptr || output == nullptr || n < k || n <= 0 || k <= 0)
return;
int start = 0;
int end = n - 1;
int index = partition(input, n, start, end);
while (index != k-1)
{
if (index > k - 1)
partition(input, n, start, index - 1);
else
partition(input, n, index + 1, end);
}
for (int i = 0; i < k; ++k)
output[i] = input[i];
}
/**
* 方法2 考虑用二叉树来存储最小的数,需要在其中反复查找最大值然后删除替换
* 可用堆、红黑树等特殊的二叉树,即STL的multiset O(nlogk)
*/
typedef multiset<int, greater<int>> setLeast;
typedef multiset<int, greater<int>>::iterator setIter;
void getLeastNumbers2(const vector<int>& numbers, setLeast& leastNums, int k)
{
leastNums.clear();
if (k <= 0 || numbers.size() < k)
return;
vector<int>::const_iterator iter = numbers.begin();
for (; iter != numbers.end(); ++iter)
{
if (leastNums.size() < k)
leastNums.insert(*iter);
else
{
setIter greatNum = leastNums.begin();
if (*iter < *greatNum)
{
leastNums.erase(greatNum);
leastNums.insert(*iter);
}
}
}
}
| [
"zhangsan@gmail.com"
] | zhangsan@gmail.com |
2f7a79f05ae7d131241390f8343a4215f9cc3fa7 | 1ca22c3dead23a2924f5b6aeb7e87abb33235ce4 | /Test/TestWinTools/TestOBMButtonDlg.cpp | 2a9f58e935802c9b985b4049f80908109f12c0ad | [] | no_license | bienhuynh/Big-Numbers | 01379a31f32993e881f92d253a40bef539823cbf | 54470c914bbceca91120a74ca139bca29a9f983e | refs/heads/master | 2021-01-22T19:17:58.077391 | 2017-01-18T19:27:33 | 2017-01-18T19:27:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,100 | cpp | #include "stdafx.h"
#include <MyUtil.h>
#include <MFCUtil/WinTools.h>
#include "testwintools.h"
#include "TestOBMButtonDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
CTestOBMButtonDlg::CTestOBMButtonDlg(CWnd* pParent /*=NULL*/) : CDialog(CTestOBMButtonDlg::IDD, pParent) {
m_buttonsEnabled = TRUE;
}
void CTestOBMButtonDlg::DoDataExchange(CDataExchange* pDX) {
CDialog::DoDataExchange(pDX);
DDX_Check(pDX, IDC_CHECK_ENABLEBUTTONS, m_buttonsEnabled);
}
BEGIN_MESSAGE_MAP(CTestOBMButtonDlg, CDialog)
ON_BN_CLICKED(IDC_CHECK_ENABLEBUTTONS, OnCheckEnableButtons)
ON_BN_CLICKED(IDC_DNARROW_BUTTON , OnButtonDNARROW)
ON_BN_CLICKED(IDC_LFARROW_BUTTON , OnButtonLFARROW)
ON_BN_CLICKED(IDC_RGARROW_BUTTON , OnButtonRGARROW)
ON_BN_CLICKED(IDC_UPARROW_BUTTON , OnButtonUPARROW)
ON_BN_CLICKED(IDC_ZOOM_BUTTON , OnButtonZOOM )
ON_BN_CLICKED(IDC_REDUCE_BUTTON , OnButtonREDUCE )
ON_BN_CLICKED(IDC_RESTORE_BUTTON , OnButtonRESTORE)
END_MESSAGE_MAP()
void CTestOBMButtonDlg::OnOK() {
}
BOOL CTestOBMButtonDlg::OnInitDialog() {
CDialog::OnInitDialog();
CPoint p(20, 20);
m_dnArrayButton.Create(this, OBMIMAGE(DNARROW), p, IDC_DNARROW_BUTTON, true); p.y += 20;
m_lfArrowButton.Create(this, OBMIMAGE(LFARROW), p, IDC_LFARROW_BUTTON, true); p.y += 20;
m_rgArrowbutton.Create(this, OBMIMAGE(RGARROW), p, IDC_RGARROW_BUTTON, true); p.y += 20;
m_upArrowButton.Create(this, OBMIMAGE(UPARROW), p, IDC_UPARROW_BUTTON, true); p.y += 20;
m_zoomButton.Create( this, OBMIMAGE(ZOOM ), p, IDC_ZOOM_BUTTON , true); p.y += 20;
m_reduceButton.Create( this, OBMIMAGE(REDUCE ), p, IDC_REDUCE_BUTTON , true); p.y += 20;
m_restoreButton.Create(this, OBMIMAGE(RESTORE), p, IDC_RESTORE_BUTTON, true); p.y += 20;
return TRUE;
}
void CTestOBMButtonDlg::OnCheckEnableButtons() {
BOOL enabled = IsDlgButtonChecked(IDC_CHECK_ENABLEBUTTONS);
m_dnArrayButton.EnableWindow(enabled);
m_lfArrowButton.EnableWindow(enabled);
m_rgArrowbutton.EnableWindow(enabled);
m_upArrowButton.EnableWindow(enabled);
m_zoomButton.EnableWindow( enabled);
m_reduceButton.EnableWindow( enabled);
m_restoreButton.EnableWindow(enabled);
}
void CTestOBMButtonDlg::OnButtonDNARROW() {
MessageBox(_T("Down-ARROW pushed"), _T("Button pushed"), MB_ICONINFORMATION);
}
void CTestOBMButtonDlg::OnButtonLFARROW() {
MessageBox(_T("Left-ARROW pushed"), _T("Button pushed"), MB_ICONINFORMATION);
}
void CTestOBMButtonDlg::OnButtonRGARROW() {
MessageBox(_T("Right-ARROW pushed"), _T("Button pushed"), MB_ICONINFORMATION);
}
void CTestOBMButtonDlg::OnButtonUPARROW() {
MessageBox(_T("Up-ARROW pushed"), _T("Button pushed"), MB_ICONINFORMATION);
}
void CTestOBMButtonDlg::OnButtonZOOM() {
MessageBox(_T("ZOOM-button pushed"), _T("Button pushed"), MB_ICONINFORMATION);
}
void CTestOBMButtonDlg::OnButtonREDUCE() {
MessageBox(_T("REDUCE-button pushed"), _T("Button pushed"), MB_ICONINFORMATION);
}
void CTestOBMButtonDlg::OnButtonRESTORE() {
MessageBox(_T("RESTORE-button pushed"), _T("Button pushed"), MB_ICONINFORMATION);
}
| [
"jesper.gr.mikkelsen@gmail.com"
] | jesper.gr.mikkelsen@gmail.com |
6e204138b7a13e0434278b2077c298418e0cad1d | 297497957c531d81ba286bc91253fbbb78b4d8be | /third_party/libwebrtc/modules/audio_coding/audio_network_adaptor/controller_manager.h | 7aa137453fec54e3daaffa26f9059dd3d351a3d9 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | marco-c/gecko-dev-comments-removed | 7a9dd34045b07e6b22f0c636c0a836b9e639f9d3 | 61942784fb157763e65608e5a29b3729b0aa66fa | refs/heads/master | 2023-08-09T18:55:25.895853 | 2023-08-01T00:40:39 | 2023-08-01T00:40:39 | 211,297,481 | 0 | 0 | NOASSERTION | 2019-09-29T01:27:49 | 2019-09-27T10:44:24 | C++ | UTF-8 | C++ | false | false | 3,013 | h |
#ifndef MODULES_AUDIO_CODING_AUDIO_NETWORK_ADAPTOR_CONTROLLER_MANAGER_H_
#define MODULES_AUDIO_CODING_AUDIO_NETWORK_ADAPTOR_CONTROLLER_MANAGER_H_
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "absl/strings/string_view.h"
#include "modules/audio_coding/audio_network_adaptor/controller.h"
namespace webrtc {
class DebugDumpWriter;
class ControllerManager {
public:
virtual ~ControllerManager() = default;
virtual std::vector<Controller*> GetSortedControllers(
const Controller::NetworkMetrics& metrics) = 0;
virtual std::vector<Controller*> GetControllers() const = 0;
};
class ControllerManagerImpl final : public ControllerManager {
public:
struct Config {
Config(int min_reordering_time_ms, float min_reordering_squared_distance);
~Config();
int min_reordering_time_ms;
float min_reordering_squared_distance;
};
static std::unique_ptr<ControllerManager> Create(
absl::string_view config_string,
size_t num_encoder_channels,
rtc::ArrayView<const int> encoder_frame_lengths_ms,
int min_encoder_bitrate_bps,
size_t intial_channels_to_encode,
int initial_frame_length_ms,
int initial_bitrate_bps,
bool initial_fec_enabled,
bool initial_dtx_enabled);
static std::unique_ptr<ControllerManager> Create(
absl::string_view config_string,
size_t num_encoder_channels,
rtc::ArrayView<const int> encoder_frame_lengths_ms,
int min_encoder_bitrate_bps,
size_t intial_channels_to_encode,
int initial_frame_length_ms,
int initial_bitrate_bps,
bool initial_fec_enabled,
bool initial_dtx_enabled,
DebugDumpWriter* debug_dump_writer);
explicit ControllerManagerImpl(const Config& config);
ControllerManagerImpl(
const Config& config,
std::vector<std::unique_ptr<Controller>> controllers,
const std::map<const Controller*, std::pair<int, float>>&
chracteristic_points);
~ControllerManagerImpl() override;
ControllerManagerImpl(const ControllerManagerImpl&) = delete;
ControllerManagerImpl& operator=(const ControllerManagerImpl&) = delete;
std::vector<Controller*> GetSortedControllers(
const Controller::NetworkMetrics& metrics) override;
std::vector<Controller*> GetControllers() const override;
private:
struct ScoringPoint {
ScoringPoint(int uplink_bandwidth_bps, float uplink_packet_loss_fraction);
float SquaredDistanceTo(const ScoringPoint& scoring_point) const;
int uplink_bandwidth_bps;
float uplink_packet_loss_fraction;
};
const Config config_;
std::vector<std::unique_ptr<Controller>> controllers_;
absl::optional<int64_t> last_reordering_time_ms_;
ScoringPoint last_scoring_point_;
std::vector<Controller*> default_sorted_controllers_;
std::vector<Controller*> sorted_controllers_;
std::map<const Controller*, ScoringPoint> controller_scoring_points_;
};
}
#endif
| [
"mcastelluccio@mozilla.com"
] | mcastelluccio@mozilla.com |
db73d75f37f3e0cdc4e71f44f7e72c9125fe40cc | 13b14c9c75143bf2eda87cb4a41006a52dd6f02b | /AOJ/0008_ex/bf.cpp | 120cc7ae7c79800a3a1aee958cb5a841de8297dc | [] | no_license | yutaka-watanobe/problem-solving | 2c311ac856c79c20aef631938140118eb3bc3835 | f0b92125494fbd3c8d203989ec9fef53f52ad4b4 | refs/heads/master | 2021-06-03T12:58:39.881107 | 2020-12-16T14:34:16 | 2020-12-16T14:34:16 | 94,963,754 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 284 | cpp | #include<iostream>
using namespace std;
#define rep(i,n) for ( int i = 0; i <= n; i++)
#define L 9
main(){
int n;
while( cin >> n){
int cnt = 0;
rep(a,L) rep(b,L) rep(c,L) rep(d,L){
if ( a + b + c + d == n ) cnt++;
}
cout << cnt << endl;
}
}
| [
"y.watanobe@gmail.com"
] | y.watanobe@gmail.com |
5a840f5d88518412e8e434ba87050026fd0779a6 | c8836eb85cd6f7255a76bc45bb495c88db3fa32f | /huffman_encoding_core_build/alternative/syn/systemc/huffman_encoding_wdI.cpp | cb31be55b222c0567c1c6c48b107be679115a2cd | [] | no_license | CayenneLow/COMP4601_Proj | 442b620cd0115ebb67c707b3428be003b73894f0 | ea690f342df10897f12fcff2167acd607d433804 | refs/heads/master | 2023-07-05T01:40:38.116700 | 2021-08-04T10:56:52 | 2021-08-04T10:56:52 | 389,930,060 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,772 | cpp | // ==============================================================
// Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC v2020.1 (64-bit)
// Copyright 1986-2020 Xilinx, Inc. All Rights Reserved.
// ==============================================================
#include "huffman_encoding_wdI.h"
using namespace std;
using namespace sc_core;
using namespace sc_dt;
huffman_encoding_wdI::~huffman_encoding_wdI() {
if (m_trace_file) sc_close_vcd_trace_file(m_trace_file);
}
void huffman_encoding_wdI::proc_i_full_n() {
i_full_n.write(full_n.read());
}
void huffman_encoding_wdI::proc_t_empty_n() {
t_empty_n.write(empty_n.read());
}
void huffman_encoding_wdI::proc_memcore_addr() {
memcore_iaddr = (i_address0.read(), iptr.read());
memcore_taddr = (t_address0.read(), tptr.read());
}
void huffman_encoding_wdI::proc_push_buf() {
push_buf.write(i_ce.read() & i_write.read() & full_n.read());
}
void huffman_encoding_wdI::proc_pop_buf() {
pop_buf.write(t_ce.read() & t_read.read() & empty_n.read());
}
void huffman_encoding_wdI::proc_iptr() {
if (reset.read() == SC_LOGIC_1) {
iptr.write(0);
} else if (push_buf.read() == SC_LOGIC_1) {
if (iptr.read() == BufferCount -1) {
iptr.write(0);
} else {
iptr.write(iptr.read()+1);
}
}
}
void huffman_encoding_wdI::proc_tptr() {
if (reset.read() == SC_LOGIC_1) {
tptr.write(0);
} else if (pop_buf.read() == SC_LOGIC_1) {
if (tptr.read() == BufferCount -1) {
tptr.write(0);
} else {
tptr.write(tptr.read()+1);
}
}
}
void huffman_encoding_wdI::proc_count() {
if (reset.read() == SC_LOGIC_1) {
count.write(0);
} else if (push_buf.read() == SC_LOGIC_1 && pop_buf.read() == SC_LOGIC_0) {
count.write(count.read()+1);
} else if (push_buf.read() == SC_LOGIC_0 && pop_buf.read() == SC_LOGIC_1) {
count.write(count.read()-1);
}
}
void huffman_encoding_wdI::proc_full_n() {
if (reset.read() == SC_LOGIC_1) {
full_n.write(SC_LOGIC_1);
} else if (push_buf.read() == SC_LOGIC_1 && pop_buf.read() == SC_LOGIC_0
&& count.read() == BufferCount - 2) {
full_n.write(SC_LOGIC_0);
} else if (push_buf.read() == SC_LOGIC_0 && pop_buf.read() == SC_LOGIC_1) {
full_n.write(SC_LOGIC_1);
}
}
void huffman_encoding_wdI::proc_empty_n() {
if (reset.read() == SC_LOGIC_1) {
empty_n.write(SC_LOGIC_0);
} else if (push_buf.read() == SC_LOGIC_1 && pop_buf.read() == SC_LOGIC_0) {
empty_n.write(SC_LOGIC_1);
} else if (push_buf.read() == SC_LOGIC_0 && pop_buf.read() == SC_LOGIC_1
&& count.read() == 1) {
empty_n.write(SC_LOGIC_0);
}
}
| [
"lowkhyeean@gmail.com"
] | lowkhyeean@gmail.com |
0b2156ec72221609ec212326885cc17c27f5a9d5 | f321d2c7456d153dde5e0c0ba46db7f7602ac065 | /sse.hpp | a2a3930dbb1085164a3ca476819d551887cdaabc | [
"BSD-2-Clause"
] | permissive | alanphumphrey/simd-math | 0b8795eae43136b66d919bd0646bd5354f7ed6cf | 01139c7bfe13a910e994a4de8421a0ab1f0c3e80 | refs/heads/master | 2020-12-29T22:40:18.798316 | 2020-02-07T17:10:36 | 2020-02-07T17:10:36 | 238,758,817 | 0 | 0 | NOASSERTION | 2020-02-06T18:42:31 | 2020-02-06T18:42:29 | null | UTF-8 | C++ | false | false | 13,389 | hpp | /*
//@HEADER
// ************************************************************************
//
// Kokkos v. 2.0
// Copyright (2014) Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// 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.
//
// Questions? Contact Christian R. Trott (crtrott@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#pragma once
#include "simd_common.hpp"
#ifdef __SSE__
#include <xmmintrin.h>
#endif
#ifdef __SSE2__
#include <emmintrin.h>
#endif
/* Intel SVML disclaimer: cbrt, exp, etc. are not intrinsics, they are Intel-proprietary library functions
https://stackoverflow.com/questions/36636159/where-is-clangs-mm256-pow-ps-intrinsic
This is why the specializations that call these functions are protected with __INTEL_COMPILER.
*/
/* Intel FMA disclaimer: it is hard to detect FMA across compilers
https://stackoverflow.com/questions/16348909/how-do-i-know-if-i-can-compile-with-fma-instruction-sets
it seems like the best we can do is __FMA__ or __AVX2__, since MSVC doesn't define __FMA__
*/
#ifdef __SSE__
#include "simd_common.hpp"
namespace SIMD_NAMESPACE {
namespace simd_abi {
class sse {};
}
template <>
class simd_mask<float, simd_abi::sse> {
__m128 m_value;
public:
using value_type = bool;
using simd_type = simd<float, simd_abi::sse>;
using abi_type = simd_abi::sse;
SIMD_ALWAYS_INLINE inline simd_mask() = default;
SIMD_ALWAYS_INLINE inline simd_mask(bool value)
:m_value(_mm_castsi128_ps(_mm_set1_epi32(-int(value))))
{}
SIMD_ALWAYS_INLINE inline static constexpr int size() { return 4; }
SIMD_ALWAYS_INLINE inline constexpr simd_mask(__m128 const& value_in)
:m_value(value_in)
{}
SIMD_ALWAYS_INLINE constexpr __m128 get() const { return m_value; }
SIMD_ALWAYS_INLINE simd_mask operator||(simd_mask const& other) const {
return simd_mask(_mm_or_ps(m_value, other.m_value));
}
SIMD_ALWAYS_INLINE simd_mask operator&&(simd_mask const& other) const {
return simd_mask(_mm_and_ps(m_value, other.m_value));
}
SIMD_ALWAYS_INLINE simd_mask operator!() const {
return simd_mask(_mm_andnot_ps(m_value, simd_mask(true).get()));
}
};
SIMD_ALWAYS_INLINE inline bool all_of(simd_mask<float, simd_abi::sse> const& a) {
return _mm_movemask_ps(a.get()) == 0xF;
}
SIMD_ALWAYS_INLINE inline bool any_of(simd_mask<float, simd_abi::sse> const& a) {
return _mm_movemask_ps(a.get()) != 0x0;
}
template <>
class simd<float, simd_abi::sse> {
__m128 m_value;
public:
using value_type = float;
using abi_type = simd_abi::sse;
using mask_type = simd_mask<float, abi_type>;
using storage_type = simd_storage<float, abi_type>;
SIMD_ALWAYS_INLINE inline simd() = default;
SIMD_ALWAYS_INLINE inline static constexpr int size() { return 4; }
SIMD_ALWAYS_INLINE inline simd(float value)
:m_value(_mm_set1_ps(value))
{}
SIMD_ALWAYS_INLINE inline
simd(storage_type const& value) {
copy_from(value.data(), element_aligned_tag());
}
SIMD_ALWAYS_INLINE inline
simd& operator=(storage_type const& value) {
copy_from(value.data(), element_aligned_tag());
return *this;
}
template <class Flags>
SIMD_ALWAYS_INLINE inline simd(float const* ptr, Flags flags) {
copy_from(ptr, flags);
}
SIMD_ALWAYS_INLINE inline constexpr simd(__m128 const& value_in)
:m_value(value_in)
{}
SIMD_ALWAYS_INLINE inline simd operator*(simd const& other) const {
return simd(_mm_mul_ps(m_value, other.m_value));
}
SIMD_ALWAYS_INLINE inline simd operator/(simd const& other) const {
return simd(_mm_div_ps(m_value, other.m_value));
}
SIMD_ALWAYS_INLINE inline simd operator+(simd const& other) const {
return simd(_mm_add_ps(m_value, other.m_value));
}
SIMD_ALWAYS_INLINE inline simd operator-(simd const& other) const {
return simd(_mm_sub_ps(m_value, other.m_value));
}
SIMD_ALWAYS_INLINE inline simd operator-() const {
return simd(_mm_sub_ps(_mm_set1_ps(0.0), m_value));
}
SIMD_ALWAYS_INLINE void copy_from(float const* ptr, element_aligned_tag) {
m_value = _mm_loadu_ps(ptr);
}
SIMD_ALWAYS_INLINE void copy_to(float* ptr, element_aligned_tag) const {
_mm_storeu_ps(ptr, m_value);
}
SIMD_ALWAYS_INLINE constexpr __m128 get() const { return m_value; }
SIMD_ALWAYS_INLINE simd_mask<float, simd_abi::sse> operator<(simd const& other) const {
return simd_mask<float, simd_abi::sse>(_mm_cmplt_ps(m_value, other.m_value));
}
SIMD_ALWAYS_INLINE simd_mask<float, simd_abi::sse> operator==(simd const& other) const {
return simd_mask<float, simd_abi::sse>(_mm_cmpeq_ps(m_value, other.m_value));
}
};
SIMD_ALWAYS_INLINE inline simd<float, simd_abi::sse> abs(simd<float, simd_abi::sse> const& a) {
__m128 const sign_mask = _mm_set1_ps(-0.f); // -0.f = 1 << 31
return simd<float, simd_abi::sse>(_mm_andnot_ps(sign_mask, a.get()));
}
SIMD_ALWAYS_INLINE inline simd<float, simd_abi::sse> sqrt(simd<float, simd_abi::sse> const& a) {
return simd<float, simd_abi::sse>(_mm_sqrt_ps(a.get()));
}
#ifdef __INTEL_COMPILER
SIMD_ALWAYS_INLINE inline simd<float, simd_abi::sse> cbrt(simd<float, simd_abi::sse> const& a) {
return simd<float, simd_abi::sse>(_mm_cbrt_ps(a.get()));
}
SIMD_ALWAYS_INLINE inline simd<float, simd_abi::sse> exp(simd<float, simd_abi::sse> const& a) {
return simd<float, simd_abi::sse>(_mm_exp_ps(a.get()));
}
#endif
#if defined(__FMA__) || defined(__AVX2__)
SIMD_ALWAYS_INLINE inline simd<float, simd_abi::sse> fma(
simd<float, simd_abi::sse> const& a,
simd<float, simd_abi::sse> const& b,
simd<float, simd_abi::sse> const& c) {
return simd<float, simd_abi::sse>(_mm_fmadd_ps(a.get(), b.get(), c.get()));
}
#endif
SIMD_ALWAYS_INLINE inline simd<float, simd_abi::sse> max(
simd<float, simd_abi::sse> const& a, simd<float, simd_abi::sse> const& b) {
return simd<float, simd_abi::sse>(_mm_max_ps(a.get(), b.get()));
}
SIMD_ALWAYS_INLINE inline simd<float, simd_abi::sse> min(
simd<float, simd_abi::sse> const& a, simd<float, simd_abi::sse> const& b) {
return simd<float, simd_abi::sse>(_mm_min_ps(a.get(), b.get()));
}
SIMD_ALWAYS_INLINE inline simd<float, simd_abi::sse> choose(
simd_mask<float, simd_abi::sse> const& a, simd<float, simd_abi::sse> const& b, simd<float, simd_abi::sse> const& c) {
return simd<float, simd_abi::sse>(_mm_add_ps(_mm_and_ps(a.get(), b.get()), _mm_andnot_ps(a.get(), c.get())));
}
#endif
#ifdef __SSE2__
template <>
class simd_mask<double, simd_abi::sse> {
__m128d m_value;
public:
using value_type = bool;
using simd_type = simd<double, simd_abi::sse>;
using abi_type = simd_abi::sse;
SIMD_ALWAYS_INLINE inline simd_mask() = default;
SIMD_ALWAYS_INLINE inline simd_mask(bool value)
:m_value(_mm_castsi128_pd(_mm_set1_epi64x(-std::int64_t(value))))
{}
SIMD_ALWAYS_INLINE inline static constexpr int size() { return 4; }
SIMD_ALWAYS_INLINE inline constexpr simd_mask(__m128d const& value_in)
:m_value(value_in)
{}
SIMD_ALWAYS_INLINE inline constexpr __m128d get() const { return m_value; }
SIMD_ALWAYS_INLINE inline simd_mask operator||(simd_mask const& other) const {
return simd_mask(_mm_or_pd(m_value, other.m_value));
}
SIMD_ALWAYS_INLINE inline simd_mask operator&&(simd_mask const& other) const {
return simd_mask(_mm_and_pd(m_value, other.m_value));
}
SIMD_ALWAYS_INLINE inline simd_mask operator!() const {
return simd_mask(_mm_andnot_pd(m_value, simd_mask(true).get()));
}
};
SIMD_ALWAYS_INLINE inline bool all_of(simd_mask<double, simd_abi::sse> const& a) {
return _mm_movemask_pd(a.get()) == 0x3;
}
SIMD_ALWAYS_INLINE inline bool any_of(simd_mask<double, simd_abi::sse> const& a) {
return _mm_movemask_pd(a.get()) != 0x0;
}
template <>
class simd<double, simd_abi::sse> {
__m128d m_value;
public:
using value_type = double;
using abi_type = simd_abi::sse;
using mask_type = simd_mask<double, abi_type>;
using storage_type = simd_storage<double, abi_type>;
SIMD_ALWAYS_INLINE inline simd() = default;
SIMD_ALWAYS_INLINE inline static constexpr int size() { return 2; }
SIMD_ALWAYS_INLINE inline simd(double value)
:m_value(_mm_set1_pd(value))
{}
SIMD_ALWAYS_INLINE inline
simd(storage_type const& value) {
copy_from(value.data(), element_aligned_tag());
}
SIMD_ALWAYS_INLINE inline
simd& operator=(storage_type const& value) {
copy_from(value.data(), element_aligned_tag());
return *this;
}
template <class Flags>
SIMD_ALWAYS_INLINE inline simd(double const* ptr, Flags flags) {
copy_from(ptr, flags);
}
SIMD_ALWAYS_INLINE inline constexpr simd(__m128d const& value_in)
:m_value(value_in)
{}
SIMD_ALWAYS_INLINE inline simd operator*(simd const& other) const {
return simd(_mm_mul_pd(m_value, other.m_value));
}
SIMD_ALWAYS_INLINE inline simd operator/(simd const& other) const {
return simd(_mm_div_pd(m_value, other.m_value));
}
SIMD_ALWAYS_INLINE inline simd operator+(simd const& other) const {
return simd(_mm_add_pd(m_value, other.m_value));
}
SIMD_ALWAYS_INLINE inline simd operator-(simd const& other) const {
return simd(_mm_sub_pd(m_value, other.m_value));
}
SIMD_ALWAYS_INLINE inline simd operator-() const {
return simd(_mm_sub_pd(_mm_set1_pd(0.0), m_value));
}
SIMD_ALWAYS_INLINE inline void copy_from(double const* ptr, element_aligned_tag) {
m_value = _mm_loadu_pd(ptr);
}
SIMD_ALWAYS_INLINE inline void copy_to(double* ptr, element_aligned_tag) const {
_mm_storeu_pd(ptr, m_value);
}
SIMD_ALWAYS_INLINE inline constexpr __m128d get() const { return m_value; }
SIMD_ALWAYS_INLINE inline simd_mask<double, simd_abi::sse> operator<(simd const& other) const {
return simd_mask<double, simd_abi::sse>(_mm_cmplt_pd(m_value, other.m_value));
}
SIMD_ALWAYS_INLINE inline simd_mask<double, simd_abi::sse> operator==(simd const& other) const {
return simd_mask<double, simd_abi::sse>(_mm_cmpeq_pd(m_value, other.m_value));
}
};
SIMD_ALWAYS_INLINE inline simd<double, simd_abi::sse> abs(simd<double, simd_abi::sse> const& a) {
__m128d const sign_mask = _mm_set1_pd(-0.); // -0. = 1 << 63
return simd<double, simd_abi::sse>(_mm_andnot_pd(sign_mask, a.get()));
}
SIMD_ALWAYS_INLINE inline simd<double, simd_abi::sse> sqrt(simd<double, simd_abi::sse> const& a) {
return simd<double, simd_abi::sse>(_mm_sqrt_pd(a.get()));
}
#ifdef __INTEL_COMPILER
SIMD_ALWAYS_INLINE inline simd<double, simd_abi::sse> cbrt(simd<double, simd_abi::sse> const& a) {
return simd<double, simd_abi::sse>(_mm_cbrt_pd(a.get()));
}
SIMD_ALWAYS_INLINE inline simd<double, simd_abi::sse> exp(simd<double, simd_abi::sse> const& a) {
return simd<double, simd_abi::sse>(_mm_exp_pd(a.get()));
}
#endif
#if defined(__FMA__) || defined(__AVX2__)
SIMD_ALWAYS_INLINE inline simd<double, simd_abi::sse> fma(
simd<double, simd_abi::sse> const& a,
simd<double, simd_abi::sse> const& b,
simd<double, simd_abi::sse> const& c) {
return simd<double, simd_abi::sse>(_mm_fmadd_pd(a.get(), b.get(), c.get()));
}
#endif
SIMD_ALWAYS_INLINE inline simd<double, simd_abi::sse> max(
simd<double, simd_abi::sse> const& a, simd<double, simd_abi::sse> const& b) {
return simd<double, simd_abi::sse>(_mm_max_pd(a.get(), b.get()));
}
SIMD_ALWAYS_INLINE inline simd<double, simd_abi::sse> min(
simd<double, simd_abi::sse> const& a, simd<double, simd_abi::sse> const& b) {
return simd<double, simd_abi::sse>(_mm_min_pd(a.get(), b.get()));
}
SIMD_ALWAYS_INLINE inline simd<double, simd_abi::sse> choose(
simd_mask<double, simd_abi::sse> const& a, simd<double, simd_abi::sse> const& b, simd<double, simd_abi::sse> const& c) {
return simd<double, simd_abi::sse>(
_mm_add_pd(
_mm_and_pd(a.get(), b.get()),
_mm_andnot_pd(a.get(), c.get())));
}
}
#endif
| [
"ahumphrey@sci.utah.edu"
] | ahumphrey@sci.utah.edu |
c53d2b1a52471361132c490c668e4db376655219 | 3b7510e0b11f33d3d311c73cfe7786828c406095 | /04/ex03/Character.cpp | 98ede3963a5f66ca6e0490bfa2e2178f805c70b7 | [] | no_license | Nimon77/Piscine_CPP | 3ae7f747a92018a39d79b91e9f15947e453037e9 | 2a3f745764d4bed60522f0af04aa30cbd24ec7cd | refs/heads/main | 2023-04-14T00:27:58.686490 | 2021-04-17T18:02:22 | 2021-04-17T18:02:22 | 336,347,602 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,741 | cpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Character.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nsimon <nsimon@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/22 19:08:47 by nsimon #+# #+# */
/* Updated: 2021/03/22 20:12:20 by nsimon ### ########.fr */
/* */
/* ************************************************************************** */
#include "Character.hpp"
Character::Character(std::string const & name): _name(name) {}
Character::Character(Character const & copy): _name(copy._name)
{
for (int i = 0; i < 4; i++)
_inv[i] = copy._inv[i];
}
Character::~Character() {}
Character & Character::operator=(Character const & rhs)
{
if (this != &rhs)
return *this;
_name = rhs._name;
for (int i = 0; i < 4; i++)
_inv[i] = rhs._inv[i];
return *this;
}
std::string const & Character::getName() const { return _name; }
void Character::equip(AMateria* m)
{
int i = 0;
while (_inv[i] && i < 4)
i++;
if (i == 4)
return ;
_inv[i] = m;
}
void Character::unequip(int idx)
{
if (idx < 0 || idx >= 4)
return ;
_inv[idx] = NULL;
}
void Character::use(int idx, ICharacter& target)
{
if (idx < 0 || idx >= 4 || !_inv[idx])
return ;
_inv[idx]->use(target);
}
| [
"nsimon@student.42.fr"
] | nsimon@student.42.fr |
cfa11ed13c4c1279617d811f095a92813aa8ffc2 | 07e6fc323f657d1fbfc24f861a278ab57338b80a | /cpp/tests/parsing/test_LispLike.cpp | 4284962bf4827cda5d64b0924bd02805d941f54c | [
"MIT"
] | permissive | ProkopHapala/SimpleSimulationEngine | 99cf2532501698ee8a03b2e40d1e4bedd9a12609 | 47543f24f106419697e82771289172d7773c7810 | refs/heads/master | 2022-09-05T01:02:42.820199 | 2022-08-28T10:22:41 | 2022-08-28T10:22:41 | 40,007,027 | 35 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 605 | cpp | #include "StructParser.h"
//#include "LispParser.h"
#include <cstring>
using namespace parsing;
StructParser parser;
//LispParser parser;
//char * test_str = "Name1{ x1; [10,15,5.5,-18.9]; x3; Name2{ x3; x4; }; Name3{ x5; x6; }; };";
//char * test_str = "Name1{ x1; x2; x3; Name2{ x3; x4; }; Name3{ x5; x6; }; };";
char * test_str = "N1{ x1; x2; x3; N2{ x3; x4; N3{ x7; x8; }; }; N4{ x5; x6; }; };";
int main(){
printf( " %s\n", test_str );
printf( " ==== \n" );
parser.parseString( strlen(test_str), test_str );
//parser.parse( 0, 0, -1 );
parser.printItemStruct();
}
| [
"ProkopHapala@gmail.com"
] | ProkopHapala@gmail.com |
111d7f664d133c0f3b0134255994c2ca6172b842 | d0aa688eeaa9dfae47670fcae6029c049800ba40 | /primer_punto/Geometrica.cpp | abfef9db33d37b216681d4180fbf6815e6ba3eda | [] | no_license | Camilo174/ALSE_VNE | 886701d731643ccaa583b4fadb35d9f22d284e31 | 8db567f96ecbb7b1ff25626bffcc54956aaca23d | refs/heads/master | 2021-04-11T16:55:12.302390 | 2020-03-22T22:46:46 | 2020-03-22T22:46:46 | 249,038,743 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 219 | cpp | #include "Geometrica.h"
#include <iostream>
using namespace std;
float Geometrica::area(){
return 0.0;
}
float Geometrica::perimetro(){
return 0.0;
}
Geometrica::Geometrica(){}
Geometrica::~Geometrica(){}
| [
"andres.nunez@mail.escuelaing.edu.co"
] | andres.nunez@mail.escuelaing.edu.co |
cf60265b3bec04f5bd432f9535754df1155c44e8 | 8163ba77e2e6f1fffd39832001db44147c91dbbd | /card.cpp | d1af956e06d6d8c23562fe74e639e1aaa8955ae8 | [] | no_license | uurlasrl/GameSolitario | 053db2a5c4823fbd5ce8787ba6a0a4db29dd87a1 | 7c2edd3fdde7fbdbe0ed82fd347992a7831b32a7 | refs/heads/master | 2023-09-05T01:25:25.382757 | 2021-11-23T21:34:28 | 2021-11-23T21:34:28 | 426,765,414 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,748 | cpp | #include "card.h"
#include <algorithm>
QImage *Card::backImage = nullptr;
QList<QImage *> Card::voltiImages;
/**
* @brief Card::Card
* inizializza la carta
* @param iid
*/
Card::CardColor Card::getCardColor() {
return cardColor;
}
int Card::getCardId() {
return id;
}
int Card::getCardNumber() {
return value + 1;
}
QImage Card::resizedBackImage(int x, int y) {
return Card::backImage->scaled(x, y);
}
QImage Card::resizedVoltiImages(int x, int y) {
return Card::voltiImages[QRandomGenerator::global()->bounded(7)]->scaled(x - 20, y - 30);
}
Card::Card(int iid) {
//QPixmap pixmap
//QImage image(myw-6-10, myh-10-10,QImage::Format_RGB32);
if (Card::backImage == nullptr) {
Card::backImage = new QImage(":/images/card.png");
Card::voltiImages.append(new QImage(":/images/chiara.jpeg"));
Card::voltiImages.append(new QImage(":/images/domenico.jpeg"));
Card::voltiImages.append(new QImage(":/images/davide.jpeg"));
Card::voltiImages.append(new QImage(":/images/enrico.jpeg"));
Card::voltiImages.append(new QImage(":/images/franco.jpeg"));
Card::voltiImages.append(new QImage(":/images/nadine.jpeg"));
Card::voltiImages.append(new QImage(":/images/sandro.jpeg"));
Card::voltiImages.append(new QImage(":/images/sara.jpeg"));
}
id = iid;
value = iid % 13;
cardColor = static_cast<CardColor>(iid / 13);
}
void Card::paintBackCard(QRectF boundingRect, QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget,
const QImage &img, const QImage &img1) {
QPen pen;
pen.setStyle(Qt::SolidLine);
pen.setWidth(2);
pen.setColor(Qt::black);
painter->setPen(pen);
painter->drawRoundedRect(boundingRect.x() + 3, boundingRect.y() + 5, boundingRect.width() - 6,
boundingRect.height() - 10, 10.0, 10.0);
painter->setBrush(Qt::white);
painter->drawImage(boundingRect.x() + 3 + 5, boundingRect.y() + 5 + 5, img);
painter->drawImage(boundingRect.x() + 3 + 15, boundingRect.y() + 5 + 35, img1);
}
void Card::paint(QRectF boundingRect, QPainter *painter, const QStyleOptionGraphicsItem *option,
QWidget *widget) {//QRectF *position,
painter->setBrush(Qt::white);
QPen pen;
pen.setStyle(Qt::SolidLine);
pen.setWidth(2);
pen.setColor(Qt::black);
painter->setPen(pen);
painter->drawRoundedRect(boundingRect.x() + 3, boundingRect.y() + 5, boundingRect.width() - 6,
boundingRect.height() - 10, 10.0, 10.0);
// painter->setBrush(Qt::white);
// painter->drawImage( 3+5, 5+5, img);
if (this->getCardNumber() > 10) {
paintFigura(&boundingRect, painter, option, widget);
} else {
paintCarta(&boundingRect, painter, option, widget);
}
}
void Card::paintFigura(QRectF *position, QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
QImage imgIcon;
QImage figura;
QString lettera;
QString simbolo = getColorName();
switch (value) {
case 10:
lettera = "J";
break;
case 11:
lettera = "Q";
break;
case 12:
lettera = "K";
}
QFont f;
f.setBold(true);
painter->setFont(f);
painter->drawText(position->x() + 15, position->y() + 24, lettera);
imgIcon.load(":/images/" + simbolo.toLower() + ".png");
imgIcon = imgIcon.scaled(15, 15);
figura.load(":/images/" + lettera + simbolo + ".png");
painter->drawImage(position->x() + 30, position->y() + 15, imgIcon);
}
QString Card::getColorName() {
switch (this->getCardColor()) {
case CardColor::Quadri:
return QString("Quadri");
case CardColor::Fiori:
return QString("Fiori");
case CardColor::Picche:
return QString("Picche");
case CardColor::Cuori:
return QString("Cuori");
}
return QString();
}
void Card::paintCarta(QRectF *position, QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
QImage imgIcon;
QString simbolo = getColorName();
QFont f;
f.setBold(true);
painter->setFont(f);
painter->drawText(position->x() + 12, position->y() + 24, QString::number(this->getCardNumber()));
// if(value<9)
// painter->drawText(15,15,QString(strchr("123456789",this->value)));
// else
// painter->drawText(15,15,QString("10"));
imgIcon.load(":/images/" + simbolo.toLower() + ".png");
imgIcon = imgIcon.scaled(15, 15);
painter->drawImage(position->x() + 30, position->y() + 15, imgIcon);
}
Card::Colored Card::getCardColored() {
return (this->cardColor == Card::Fiori || this->cardColor == Card::Picche) ? Card::Nere : Card::Rosse;
}
CardStackItem::~CardStackItem() {}
CardStackItem::CardStackItem(QColor *c) : color(c) {
rand_generator.seed(QDateTime::currentDateTime().toMSecsSinceEpoch());
}
/**
* controlla se lo stack e' vuoto
* @return
*/
bool CardStackItem::isEmpty() {
return carteScoperte.isEmpty() && carteCoperte.isEmpty();
}
int CardStackItem::sizeCoperte() {
return carteCoperte.size();
}
int CardStackItem::sizeScoperte() {
return carteCoperte.size();
}
/**
* @brief CardStackItem::transferFrom
* trasferisce le carta da un altro stack
* @param otherCardStack
* @return torna vero se il trasferimanto e' andato a buon fine altrimenti falso
*/
bool CardStackItem::transferFrom(CardStackItem *otherCardStack, Card *from, qint32 eventID) {
QRectF rectOther(otherCardStack->boundingRect());
rectOther.moveTo(otherCardStack->pos());
QRectF rectThis(boundingRect());
rectThis.moveTo(pos());
//va a cercare l'indice della card
Card *c;
int idx = otherCardStack->carteScoperte.size() - 1;
while (idx >= 0) {
c = otherCardStack->carteScoperte[idx];
if (c == from) {
break;
}
idx--;
}
if (idx < 0)return false; //non trova la card
if (!this->isValid(c)) return false; //l'elemento da inserire non e' valido
// calcola il numero di card da togliere
int len = idx = otherCardStack->carteScoperte.size() - idx;
// riversa le card da togliere in una lista temporanea
CardList temp;
while (idx > 0) {
temp.append(otherCardStack->carteScoperte.pop());
idx--;
}
idx = len - 1;
while (idx >= 0) {
this->carteScoperte.push(temp[idx--]);
}
// comunica le modifiche per un visitors o per la modifica della visualizzazione
qint32 id = eventID == 0 ? rand_generator.bounded((qint32) 1, (qint32) 32000) : eventID;
//rimuovo la carta dall'altro item
QRectF rectAfterOther(otherCardStack->boundingRect());
rectAfterOther.moveTo(otherCardStack->pos());
emit otherCardStack->changeData(id, Card::CardEventType::toglieCarta, temp,
rectOther.united(rectAfterOther));//rimozione carte
otherCardStack->scopriCartaIfEmpty(id);
//aggiungo la carta in questo item
QRectF rectAfterThis(boundingRect());
rectAfterThis.moveTo(pos());
emit changeData(id, Card::CardEventType::aggiungeCarte, temp, rectThis.united(rectAfterThis));//aggiunta carte
return true;
}
CardList CardStackItem::getCarteScoperte() const {
CardList tmp(carteScoperte);
return tmp;
}
void CardStackItem::resetEvent(GameEvent *event) {
switch (event->eventType) {
case Card::CardEventType::aggiungeCarte: {
//bisogna togliere le carte che sono state aggiunte dalle carte scoperte
for (int i = 0; i < event->data.size(); i++)
carteScoperte.pop();
break;
}
case Card::CardEventType::toglieCarta: {
//bisogna aggiungere le carte alle carte scoperte
for (int i = 0; i < event->data.size(); i++) {
carteScoperte.push(event->data[event->data.size() - i - 1]);
}
break;
}
case Card::CardEventType::scopreCarta: {
//bisogna ricoprire la carta
carteCoperte.push(carteScoperte.pop());
break;
}
case Card::CardEventType::giraCarteDelMazzo: {
//bisogna riposizionare il mazzo come prima
while (!carteCoperte.isEmpty())
carteScoperte.push(carteCoperte.pop());
break;
}
}
}
void CardStackItem::deserializeFrom(QDataStream &dataStream, CardGenerator *cardGenerator) {
carteScoperte.clear();
qsizetype nScoperte;
dataStream >> nScoperte;
for (int i = 0; i < nScoperte; i++) {
unsigned short id;
dataStream >> id;
carteScoperte.append(cardGenerator->getCardById(id));
}
carteCoperte.clear();
qsizetype nCoperte;
dataStream >> nCoperte;
for (int i = 0; i < nCoperte; i++) {
unsigned short id;
dataStream >> id;
carteScoperte.append(cardGenerator->getCardById(id));
}
}
void CardStackItem::serializeTo(QDataStream &dataStream) {
//dataStream << color;
dataStream << carteScoperte.size();
for (int i = 0; i < carteScoperte.size(); i++) {
dataStream << carteScoperte[i]->getCardId();
}
dataStream << carteCoperte.size();
for (int i = 0; i < carteCoperte.size(); i++) {
dataStream << carteCoperte[i]->getCardId();
}
}
void GameEvent::serializeTo(QDataStream &dataStream) {
dataStream << eventID;
dataStream << eventType;
//dataStream << area;
dataStream << data.size();
for (int i = 0; i < data.size(); i++) {
dataStream << data[i]->getCardId();
}
dataStream << this->sender->objectName();
}
| [
"info@uurla.it"
] | info@uurla.it |
3f394e6449d6d4fe651e366f18b3004b5eb153af | f5c847319959a9395f139abb826bfbe280716357 | /Powder/src/Simulation.h | 020101407b11ff6e46f33d308608bc23674c11d4 | [
"MIT"
] | permissive | TelerikArsov/Powder | b83d686caee87ba4a695a498a7c1802b6ef5cf6b | f187f33810325e676d7d671ad8188f8f947a1f35 | refs/heads/master | 2020-04-03T04:29:12.702492 | 2019-06-03T07:49:51 | 2019-06-03T07:49:51 | 155,015,361 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,665 | h | #pragma once
#include <vector>
#include <list>
#include "Element/Element.h"
#include "Element/ElementsIds.h"
#include "SimTool/Tool.h"
#include "SimTool/ToolsIds.h"
#include "UI/BaseUI.h"
#include "Brushes/Brush.h"
#include "Physics/Gravity.h"
#include "Physics/Air.h"
class Vector;
class Simulation
{
public:
int elements_count;
float fps = 0.0f;
bool paused = true;
int cells_x_count = 10, cells_y_count = 10;
int mouse_cell_x, mouse_cell_y;
// how fast heat heats up elements
float heat_coef = 1.f;
// power of 10, not sure how to make it only a power of 10
float scale = 1.f;
Gravity gravity;
Air air;
BaseUI baseUI;
bool neut_grav = false;
// Set in the ui, used to know which grid to draw
// either none = 0, grav = 1, air = 2
int drav_grid = 0;
bool check_if_empty(Vector cordinates) const;
bool check_if_empty(float x, float y) const;
bool check_if_empty(int x, int y) const;
bool check_id(Vector cordinates, int id) const;
bool check_id(float x, float y, int id) const;
bool check_id(int x, int y, int id) const;
std::shared_ptr<Element> get_from_grid(Vector cordinates) const;
std::shared_ptr<Element> get_from_grid(float x, float y) const;
std::shared_ptr<Element> get_from_grid(int x, int y) const;
int get_from_gol(Vector cordinates) const;
int get_from_gol(float x, float y) const;
int get_from_gol(int x, int y) const;
// Gets all the alive neighbours of a cell
// with position x and y
// Uses the gol_grid
int get_gol_neigh_count(int x, int y) const;
void set_gol_at(int x, int y, int val);
std::shared_ptr<Element> find_by_id(int id);
std::shared_ptr<Brush> find_brush_by_id(int id);
std::shared_ptr<Tool> find_tool_by_id(int id);
// Updates the gol grid.
// Loops over all the active elements and calls their update method.
// If the update method returns true, then the elements is deleted.
// Adds any newly created elements to the active list.
void tick(bool bypass_pause = false, float dt = 1);
// Loops over all the active elements and calls their render method.
// Renders the grid(NOT YET IMPLEMENTED) and the outline of the spawn area
void render(sf::RenderWindow* window);
// Creates element inside the grid and returns a pointer towards it
//
// bool from_mouse = whether the creation is called by the mouse
// or from another existing element
// int id = the identifier of the element to be created
// bool add_to_active = whether the elements needs to be added to the active list
// int x, y = the position of the element in the grid
std::shared_ptr<Element> create_element(int id, bool from_mouse, bool add_to_active, int x, int y);
std::shared_ptr<Element> create_element(int id, bool from_mouse, bool add_to_active, int idx);
void transition_element(const std::shared_ptr<Element> el, int id);
void destroy_element(const std::shared_ptr<Element> destroyed, bool destroy_from_active = true);
void destroy_element(int x, int y, bool destroy_from_active = true);
void swap_elements(int x1, int y1, int x2, int y2);
// Checks if the possition at x and y
// is inside the grid
bool bounds_check(int x, int y) const;
// Spawns elements at the mouse position
// Uses the spawn_area to determine the area in which the elements should be spawned
void mouse_left_click();
// Toggles the pause
void toggle_pause();
void set_mouse_coordinates(int x, int y);
// If d > 0 then the spawn area increases
// If d < 0 the spawn area decrease
// Based on the currently used spawn area type the creation method is called
// Spanw area types include circle, square, triangle NOTE: currently only cirlce is implemented
void resize_brush(float d);
bool add_element(std::shared_ptr<Element>);
bool add_brush(std::shared_ptr<Brush>);
bool add_tool(std::shared_ptr<Tool>);
void select_brush(int brushId);
void select_element(int elementId);
void select_tool(int toolId);
void clear_field();
void set_cell_count(int x_count, int y_count);
void set_window_size(int window_width, int window_height);
// int window_width, int window_height = the dimensions of the window
// where the simulation will be rendered
Simulation(int cells_x_count, int cells_y_count, int window_width, int window_height, float base_g);
~Simulation();
//TODO something something encapsulation, most of the public properties should be here anyways
private:
// the dimensions of each cell
float cell_height, cell_width;
float m_cell_height, m_cell_width;
int const window_height, window_width;
int m_window_height, m_window_width;
// The identifier of the current selected element
int selected_element;
std::weak_ptr<Brush> selected_brush;
std::weak_ptr<Tool> selected_tool;
friend class BaseUI;
int mouse_x = 0, mouse_y = 0;
std::vector<std::shared_ptr<Element>> elements_grid;
// Used for GoL simulation
// 1 is alive 0 is dead, anything else varies
// of the specific GoL element
std::vector<int> gol_grid;
// All the available elements that can be spawned
std::vector<std::shared_ptr<SimObject>> available_elements;
std::vector<std::shared_ptr<SimObject>> brushes;
std::vector<std::shared_ptr<SimObject>> tools;
// All currently active elements inside the element grid
std::vector<std::shared_ptr<Element>> active_elements;
// Elements that need to be added to the active list
std::vector<std::shared_ptr<Element>> add_queue;
bool add_simObject(std::shared_ptr<SimObject> object, std::vector<std::shared_ptr<SimObject>>& container);
std::shared_ptr<SimObject> find_simObject_byId(int id, std::vector<std::shared_ptr<SimObject>>& list);
void mouse_calibrate();
sf::VertexArray draw_grid(std::vector<Vector> velocities, int cell_size, int height, int width);
}; | [
"telerik007@gmail.com"
] | telerik007@gmail.com |
c40e66f50ce4211bd0e632b6c2c57794fccd2c3e | 8974b8cf04eea68e0ff96d29044341f1ae499e2c | /11 - LCD1602/11.1 - LCD 1602/LCD1602_Disp/LCD1602_Disp.ino | 0d843958c40b90f134d3bb72649d55daf9b97989 | [] | no_license | Play-Zone/BlueBirdKit | 8c827c8acf8ce596fc496dae554d5cde9ca41542 | 3e7b5b599ddd2b26a7f19febcfd63a17f68a5116 | refs/heads/master | 2021-01-13T02:16:38.096064 | 2015-05-31T13:04:13 | 2015-05-31T13:04:13 | 36,603,069 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 630 | ino | #include <Wire.h> //包含I2C的代码
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,16,2); // PCA8574的A0-A2=1,所以地址为0X27。
// 16表示16列,2表示2行
void setup(){
lcd.init(); //液晶的初使化
lcd.noBacklight(); //关闭背光
lcd.setCursor(0,0); //光标移动到第1行第1列
lcd.print("Hello, world!"); //第一行显示“Hello, world”
lcd.setCursor(0,1); //光标移动到第2行第1列
lcd.print('a',HEX); //显示字符“a”的十六进制数值
}
void loop(){
}
| [
"d@c64.ch"
] | d@c64.ch |
cba394ad07b8347aba5bff15c4db65f84976e693 | b42ba10b9daccae46922bcb69c2b850288235fad | /Raytracing-demo_specular/Scene/Sphere.h | f9abc9d6c617415487ea26657e5de7f31e61a92b | [] | no_license | Phyronnaz/demo | 5cb897bb35f6d17f0a3233ba519f069ac1d77b85 | 07a4642849a37919c684ddd3727ec12954197713 | refs/heads/master | 2021-08-28T06:14:42.067589 | 2017-12-11T11:02:45 | 2017-12-11T11:02:45 | 113,465,104 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 424 | h | #pragma once
#include "Vector.h"
#include "Color.h"
#include "Object.h"
#include "Ray.h"
#include "Hit.h"
class Sphere : public Object
{
public:
const Vector center;
const double radius;
Sphere(const Vector& center, const double& radius, const Color& color,
double diffuse = 0.5, double specular = 0.5, double specular_exponent = 5);
bool intersect(const Ray& ray, Hit& hit) const override;
}; | [
"phyronnaz@gmail.com"
] | phyronnaz@gmail.com |
e7cd66a4f68e8c8a78168355c71d4cb326eb8707 | 3d528e36d85f7fd49da626bcc6bf227aba14fc1c | /IdentifierBinaryTree.cpp | 07b2f6ae6286d919d61f49cf137227a4b705f89f | [] | no_license | srujank1/lab5 | f5a298746343cd75ab56a4b3d6adb5794e1357a0 | e0ea7ca624a02aa964fa406ee64110d3ca14f070 | refs/heads/master | 2020-04-01T19:24:32.949791 | 2014-04-25T21:15:50 | 2014-04-25T21:15:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,119 | cpp | //
// IdentifierBinaryTree.cpp
// Lab4
//
// Created by Bryce Holton on 3/28/14.
// Copyright (c) 2014 Bryce Holton. All rights reserved.
//
#include "IdentifierBinaryTree.h"
#include "LineNumberList.h"
using namespace std;
IdentifierBinaryTree::IdentifierBinaryTree()
{
setTreeRoot(NULL);
}
IdentifierBinaryTree::~IdentifierBinaryTree()
{
Identifier *root = getTreeRoot();
if (root != NULL)
{
depthFirstDeleteTree(root);
}
}
void IdentifierBinaryTree::depthFirstDeleteTree(Identifier *tok)
{
if (tok->getLeftChild() != NULL)
{
depthFirstDeleteTree(tok->getLeftChild());
}
// cout << tok->getTokenString() << "\n";
if (tok->getRightChild() != NULL)
{
depthFirstDeleteTree(tok->getRightChild());
}
delete tok;
}
void IdentifierBinaryTree::setTreeRoot(Identifier *root)
{
this->treeRoot = root;
}
Identifier *IdentifierBinaryTree::getTreeRoot()
{
return this->treeRoot;
}
bool IdentifierBinaryTree::addIdentifier(Identifier *id, int lineNum)
{
bool success = false;
LineNumberList *listItem = new LineNumberList();
listItem->setLineNumber(lineNum);
if (getTreeRoot() == NULL)
{
setTreeRoot(tok);
tok->addToLineNumberList(listItem);
success = true;
}
else
{
string tokenName = tok->getTokenString();
Token *parentNode = getTreeRoot();
string treeNodeName;
int stringComparison;
while (parentNode != NULL)
{
treeNodeName = parentNode->getTokenString();
stringComparison = tokenName.compare(treeNodeName);
if (stringComparison == 0)
{
//They are the same identifier token we just need to add a new line number to the list.
parentNode->addToLineNumberList(listItem);
parentNode = NULL; //Exit the loop
delete tok; //We won't need tok and it won't be deleted in main.
success = true;
}
else if (stringComparison < 0)
{
//Go to the left.
if (parentNode->getLeftChild() == NULL)
{
//Add tok to the left
tok->addToLineNumberList(listItem);
parentNode->setLeftChild(tok);
parentNode = NULL;
success = true;
}
else
{
parentNode = parentNode->getLeftChild();
}
}
else
{
//Go to the right.
if (parentNode->getRightChild() == NULL)
{
//Add tok to the right
tok->addToLineNumberList(listItem);
parentNode->setRightChild(tok);
parentNode = NULL;
success = true;
}
else
{
parentNode = parentNode->getRightChild();
}
}
}
}
return success;
}
| [
"bakolden5@gmail.com"
] | bakolden5@gmail.com |
5b3183220a4923cf6d13e858db5fbd08a9cf92dd | 7e62f0928681aaaecae7daf360bdd9166299b000 | /external/DirectXShaderCompiler/external/SPIRV-Tools/test/opt/loop_optimizations/fusion_compatibility.cpp | 280008c19aa429bc5a9b30265d3ff18936aec157 | [
"NCSA",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | permissive | yuri410/rpg | 949b001bd0aec47e2a046421da0ff2a1db62ce34 | 266282ed8cfc7cd82e8c853f6f01706903c24628 | refs/heads/master | 2020-08-03T09:39:42.253100 | 2020-06-16T15:38:03 | 2020-06-16T15:38:03 | 211,698,323 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 56,581 | cpp | // Copyright (c) 2018 Google LLC.
//
// 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 <algorithm>
#include <iterator>
#include <memory>
#include <string>
#include <vector>
#include "gmock/gmock.h"
#include "source/opt/loop_descriptor.h"
#include "source/opt/loop_fusion.h"
#include "test/opt/pass_fixture.h"
namespace spvtools {
namespace opt {
namespace {
using FusionCompatibilityTest = PassTest<::testing::Test>;
/*
Generated from the following GLSL + --eliminate-local-multi-store
#version 440 core
void main() {
int i = 0; // Can't fuse, i=0 in first & i=10 in second
for (; i < 10; i++) {}
for (; i < 10; i++) {}
}
*/
TEST_F(FusionCompatibilityTest, SameInductionVariableDifferentBounds) {
const std::string text = R"(
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main"
OpExecutionMode %4 OriginUpperLeft
OpSource GLSL 440
OpName %4 "main"
OpName %8 "i"
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 1
%7 = OpTypePointer Function %6
%9 = OpConstant %6 0
%16 = OpConstant %6 10
%17 = OpTypeBool
%20 = OpConstant %6 1
%4 = OpFunction %2 None %3
%5 = OpLabel
%8 = OpVariable %7 Function
OpStore %8 %9
OpBranch %10
%10 = OpLabel
%31 = OpPhi %6 %9 %5 %21 %13
OpLoopMerge %12 %13 None
OpBranch %14
%14 = OpLabel
%18 = OpSLessThan %17 %31 %16
OpBranchConditional %18 %11 %12
%11 = OpLabel
OpBranch %13
%13 = OpLabel
%21 = OpIAdd %6 %31 %20
OpStore %8 %21
OpBranch %10
%12 = OpLabel
OpBranch %22
%22 = OpLabel
%32 = OpPhi %6 %31 %12 %30 %25
OpLoopMerge %24 %25 None
OpBranch %26
%26 = OpLabel
%28 = OpSLessThan %17 %32 %16
OpBranchConditional %28 %23 %24
%23 = OpLabel
OpBranch %25
%25 = OpLabel
%30 = OpIAdd %6 %32 %20
OpStore %8 %30
OpBranch %22
%24 = OpLabel
OpReturn
OpFunctionEnd
)";
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
Module* module = context->module();
EXPECT_NE(nullptr, module) << "Assembling failed for shader:\n"
<< text << std::endl;
Function& f = *module->begin();
LoopDescriptor& ld = *context->GetLoopDescriptor(&f);
EXPECT_EQ(ld.NumLoops(), 2u);
auto loops = ld.GetLoopsInBinaryLayoutOrder();
LoopFusion fusion(context.get(), loops[0], loops[1]);
EXPECT_FALSE(fusion.AreCompatible());
}
/*
Generated from the following GLSL + --eliminate-local-multi-store
// 1
#version 440 core
void main() {
for (int i = 0; i < 10; i++) {}
for (int i = 0; i < 10; i++) {}
}
*/
TEST_F(FusionCompatibilityTest, Compatible) {
const std::string text = R"(
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main"
OpExecutionMode %4 OriginUpperLeft
OpSource GLSL 440
OpName %4 "main"
OpName %8 "i"
OpName %22 "i"
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 1
%7 = OpTypePointer Function %6
%9 = OpConstant %6 0
%16 = OpConstant %6 10
%17 = OpTypeBool
%20 = OpConstant %6 1
%4 = OpFunction %2 None %3
%5 = OpLabel
%8 = OpVariable %7 Function
%22 = OpVariable %7 Function
OpStore %8 %9
OpBranch %10
%10 = OpLabel
%32 = OpPhi %6 %9 %5 %21 %13
OpLoopMerge %12 %13 None
OpBranch %14
%14 = OpLabel
%18 = OpSLessThan %17 %32 %16
OpBranchConditional %18 %11 %12
%11 = OpLabel
OpBranch %13
%13 = OpLabel
%21 = OpIAdd %6 %32 %20
OpStore %8 %21
OpBranch %10
%12 = OpLabel
OpStore %22 %9
OpBranch %23
%23 = OpLabel
%33 = OpPhi %6 %9 %12 %31 %26
OpLoopMerge %25 %26 None
OpBranch %27
%27 = OpLabel
%29 = OpSLessThan %17 %33 %16
OpBranchConditional %29 %24 %25
%24 = OpLabel
OpBranch %26
%26 = OpLabel
%31 = OpIAdd %6 %33 %20
OpStore %22 %31
OpBranch %23
%25 = OpLabel
OpReturn
OpFunctionEnd
)";
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
Module* module = context->module();
EXPECT_NE(nullptr, module) << "Assembling failed for shader:\n"
<< text << std::endl;
Function& f = *module->begin();
LoopDescriptor& ld = *context->GetLoopDescriptor(&f);
EXPECT_EQ(ld.NumLoops(), 2u);
auto loops = ld.GetLoopsInBinaryLayoutOrder();
LoopFusion fusion(context.get(), loops[0], loops[1]);
EXPECT_TRUE(fusion.AreCompatible());
}
/*
Generated from the following GLSL + --eliminate-local-multi-store
// 2
#version 440 core
void main() {
for (int i = 0; i < 10; i++) {}
for (int j = 0; j < 10; j++) {}
}
*/
TEST_F(FusionCompatibilityTest, DifferentName) {
const std::string text = R"(
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main"
OpExecutionMode %4 OriginUpperLeft
OpSource GLSL 440
OpName %4 "main"
OpName %8 "i"
OpName %22 "j"
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 1
%7 = OpTypePointer Function %6
%9 = OpConstant %6 0
%16 = OpConstant %6 10
%17 = OpTypeBool
%20 = OpConstant %6 1
%4 = OpFunction %2 None %3
%5 = OpLabel
%8 = OpVariable %7 Function
%22 = OpVariable %7 Function
OpStore %8 %9
OpBranch %10
%10 = OpLabel
%32 = OpPhi %6 %9 %5 %21 %13
OpLoopMerge %12 %13 None
OpBranch %14
%14 = OpLabel
%18 = OpSLessThan %17 %32 %16
OpBranchConditional %18 %11 %12
%11 = OpLabel
OpBranch %13
%13 = OpLabel
%21 = OpIAdd %6 %32 %20
OpStore %8 %21
OpBranch %10
%12 = OpLabel
OpStore %22 %9
OpBranch %23
%23 = OpLabel
%33 = OpPhi %6 %9 %12 %31 %26
OpLoopMerge %25 %26 None
OpBranch %27
%27 = OpLabel
%29 = OpSLessThan %17 %33 %16
OpBranchConditional %29 %24 %25
%24 = OpLabel
OpBranch %26
%26 = OpLabel
%31 = OpIAdd %6 %33 %20
OpStore %22 %31
OpBranch %23
%25 = OpLabel
OpReturn
OpFunctionEnd
)";
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
Module* module = context->module();
EXPECT_NE(nullptr, module) << "Assembling failed for shader:\n"
<< text << std::endl;
Function& f = *module->begin();
LoopDescriptor& ld = *context->GetLoopDescriptor(&f);
EXPECT_EQ(ld.NumLoops(), 2u);
auto loops = ld.GetLoopsInBinaryLayoutOrder();
LoopFusion fusion(context.get(), loops[0], loops[1]);
EXPECT_TRUE(fusion.AreCompatible());
}
/*
Generated from the following GLSL + --eliminate-local-multi-store
#version 440 core
void main() {
// Can't fuse, different step
for (int i = 0; i < 10; i++) {}
for (int j = 0; j < 10; j=j+2) {}
}
*/
TEST_F(FusionCompatibilityTest, SameBoundsDifferentStep) {
const std::string text = R"(
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main"
OpExecutionMode %4 OriginUpperLeft
OpSource GLSL 440
OpName %4 "main"
OpName %8 "i"
OpName %22 "j"
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 1
%7 = OpTypePointer Function %6
%9 = OpConstant %6 0
%16 = OpConstant %6 10
%17 = OpTypeBool
%20 = OpConstant %6 1
%31 = OpConstant %6 2
%4 = OpFunction %2 None %3
%5 = OpLabel
%8 = OpVariable %7 Function
%22 = OpVariable %7 Function
OpStore %8 %9
OpBranch %10
%10 = OpLabel
%33 = OpPhi %6 %9 %5 %21 %13
OpLoopMerge %12 %13 None
OpBranch %14
%14 = OpLabel
%18 = OpSLessThan %17 %33 %16
OpBranchConditional %18 %11 %12
%11 = OpLabel
OpBranch %13
%13 = OpLabel
%21 = OpIAdd %6 %33 %20
OpStore %8 %21
OpBranch %10
%12 = OpLabel
OpStore %22 %9
OpBranch %23
%23 = OpLabel
%34 = OpPhi %6 %9 %12 %32 %26
OpLoopMerge %25 %26 None
OpBranch %27
%27 = OpLabel
%29 = OpSLessThan %17 %34 %16
OpBranchConditional %29 %24 %25
%24 = OpLabel
OpBranch %26
%26 = OpLabel
%32 = OpIAdd %6 %34 %31
OpStore %22 %32
OpBranch %23
%25 = OpLabel
OpReturn
OpFunctionEnd
)";
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
Module* module = context->module();
EXPECT_NE(nullptr, module) << "Assembling failed for shader:\n"
<< text << std::endl;
Function& f = *module->begin();
LoopDescriptor& ld = *context->GetLoopDescriptor(&f);
EXPECT_EQ(ld.NumLoops(), 2u);
auto loops = ld.GetLoopsInBinaryLayoutOrder();
LoopFusion fusion(context.get(), loops[0], loops[1]);
EXPECT_FALSE(fusion.AreCompatible());
}
/*
Generated from the following GLSL + --eliminate-local-multi-store
// 4
#version 440 core
void main() {
// Can't fuse, different upper bound
for (int i = 0; i < 10; i++) {}
for (int j = 0; j < 20; j++) {}
}
*/
TEST_F(FusionCompatibilityTest, DifferentUpperBound) {
const std::string text = R"(
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main"
OpExecutionMode %4 OriginUpperLeft
OpSource GLSL 440
OpName %4 "main"
OpName %8 "i"
OpName %22 "j"
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 1
%7 = OpTypePointer Function %6
%9 = OpConstant %6 0
%16 = OpConstant %6 10
%17 = OpTypeBool
%20 = OpConstant %6 1
%29 = OpConstant %6 20
%4 = OpFunction %2 None %3
%5 = OpLabel
%8 = OpVariable %7 Function
%22 = OpVariable %7 Function
OpStore %8 %9
OpBranch %10
%10 = OpLabel
%33 = OpPhi %6 %9 %5 %21 %13
OpLoopMerge %12 %13 None
OpBranch %14
%14 = OpLabel
%18 = OpSLessThan %17 %33 %16
OpBranchConditional %18 %11 %12
%11 = OpLabel
OpBranch %13
%13 = OpLabel
%21 = OpIAdd %6 %33 %20
OpStore %8 %21
OpBranch %10
%12 = OpLabel
OpStore %22 %9
OpBranch %23
%23 = OpLabel
%34 = OpPhi %6 %9 %12 %32 %26
OpLoopMerge %25 %26 None
OpBranch %27
%27 = OpLabel
%30 = OpSLessThan %17 %34 %29
OpBranchConditional %30 %24 %25
%24 = OpLabel
OpBranch %26
%26 = OpLabel
%32 = OpIAdd %6 %34 %20
OpStore %22 %32
OpBranch %23
%25 = OpLabel
OpReturn
OpFunctionEnd
)";
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
Module* module = context->module();
EXPECT_NE(nullptr, module) << "Assembling failed for shader:\n"
<< text << std::endl;
Function& f = *module->begin();
LoopDescriptor& ld = *context->GetLoopDescriptor(&f);
EXPECT_EQ(ld.NumLoops(), 2u);
auto loops = ld.GetLoopsInBinaryLayoutOrder();
LoopFusion fusion(context.get(), loops[0], loops[1]);
EXPECT_FALSE(fusion.AreCompatible());
}
/*
Generated from the following GLSL + --eliminate-local-multi-store
// 5
#version 440 core
void main() {
// Can't fuse, different lower bound
for (int i = 5; i < 10; i++) {}
for (int j = 0; j < 10; j++) {}
}
*/
TEST_F(FusionCompatibilityTest, DifferentLowerBound) {
const std::string text = R"(
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main"
OpExecutionMode %4 OriginUpperLeft
OpSource GLSL 440
OpName %4 "main"
OpName %8 "i"
OpName %22 "j"
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 1
%7 = OpTypePointer Function %6
%9 = OpConstant %6 5
%16 = OpConstant %6 10
%17 = OpTypeBool
%20 = OpConstant %6 1
%23 = OpConstant %6 0
%4 = OpFunction %2 None %3
%5 = OpLabel
%8 = OpVariable %7 Function
%22 = OpVariable %7 Function
OpStore %8 %9
OpBranch %10
%10 = OpLabel
%33 = OpPhi %6 %9 %5 %21 %13
OpLoopMerge %12 %13 None
OpBranch %14
%14 = OpLabel
%18 = OpSLessThan %17 %33 %16
OpBranchConditional %18 %11 %12
%11 = OpLabel
OpBranch %13
%13 = OpLabel
%21 = OpIAdd %6 %33 %20
OpStore %8 %21
OpBranch %10
%12 = OpLabel
OpStore %22 %23
OpBranch %24
%24 = OpLabel
%34 = OpPhi %6 %23 %12 %32 %27
OpLoopMerge %26 %27 None
OpBranch %28
%28 = OpLabel
%30 = OpSLessThan %17 %34 %16
OpBranchConditional %30 %25 %26
%25 = OpLabel
OpBranch %27
%27 = OpLabel
%32 = OpIAdd %6 %34 %20
OpStore %22 %32
OpBranch %24
%26 = OpLabel
OpReturn
OpFunctionEnd
)";
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
Module* module = context->module();
EXPECT_NE(nullptr, module) << "Assembling failed for shader:\n"
<< text << std::endl;
Function& f = *module->begin();
LoopDescriptor& ld = *context->GetLoopDescriptor(&f);
EXPECT_EQ(ld.NumLoops(), 2u);
auto loops = ld.GetLoopsInBinaryLayoutOrder();
LoopFusion fusion(context.get(), loops[0], loops[1]);
EXPECT_FALSE(fusion.AreCompatible());
}
/*
Generated from the following GLSL + --eliminate-local-multi-store
// 6
#version 440 core
void main() {
// Can't fuse, break in first loop
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
}
for (int j = 0; j < 10; j++) {}
}
*/
TEST_F(FusionCompatibilityTest, Break) {
const std::string text = R"(
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main"
OpExecutionMode %4 OriginUpperLeft
OpSource GLSL 440
OpName %4 "main"
OpName %8 "i"
OpName %28 "j"
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 1
%7 = OpTypePointer Function %6
%9 = OpConstant %6 0
%16 = OpConstant %6 10
%17 = OpTypeBool
%20 = OpConstant %6 5
%26 = OpConstant %6 1
%4 = OpFunction %2 None %3
%5 = OpLabel
%8 = OpVariable %7 Function
%28 = OpVariable %7 Function
OpStore %8 %9
OpBranch %10
%10 = OpLabel
%38 = OpPhi %6 %9 %5 %27 %13
OpLoopMerge %12 %13 None
OpBranch %14
%14 = OpLabel
%18 = OpSLessThan %17 %38 %16
OpBranchConditional %18 %11 %12
%11 = OpLabel
%21 = OpIEqual %17 %38 %20
OpSelectionMerge %23 None
OpBranchConditional %21 %22 %23
%22 = OpLabel
OpBranch %12
%23 = OpLabel
OpBranch %13
%13 = OpLabel
%27 = OpIAdd %6 %38 %26
OpStore %8 %27
OpBranch %10
%12 = OpLabel
OpStore %28 %9
OpBranch %29
%29 = OpLabel
%39 = OpPhi %6 %9 %12 %37 %32
OpLoopMerge %31 %32 None
OpBranch %33
%33 = OpLabel
%35 = OpSLessThan %17 %39 %16
OpBranchConditional %35 %30 %31
%30 = OpLabel
OpBranch %32
%32 = OpLabel
%37 = OpIAdd %6 %39 %26
OpStore %28 %37
OpBranch %29
%31 = OpLabel
OpReturn
OpFunctionEnd
)";
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
Module* module = context->module();
EXPECT_NE(nullptr, module) << "Assembling failed for shader:\n"
<< text << std::endl;
Function& f = *module->begin();
LoopDescriptor& ld = *context->GetLoopDescriptor(&f);
EXPECT_EQ(ld.NumLoops(), 2u);
auto loops = ld.GetLoopsInBinaryLayoutOrder();
LoopFusion fusion(context.get(), loops[0], loops[1]);
EXPECT_FALSE(fusion.AreCompatible());
}
/*
Generated from the following GLSL + --eliminate-local-multi-store
#version 440 core
layout(location = 0) in vec4 c;
void main() {
int N = int(c.x);
for (int i = 0; i < N; i++) {}
for (int j = 0; j < N; j++) {}
}
*/
TEST_F(FusionCompatibilityTest, UnknownButSameUpperBound) {
const std::string text = R"(
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main" %12
OpExecutionMode %4 OriginUpperLeft
OpSource GLSL 440
OpName %4 "main"
OpName %8 "N"
OpName %12 "c"
OpName %19 "i"
OpName %33 "j"
OpDecorate %12 Location 0
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 1
%7 = OpTypePointer Function %6
%9 = OpTypeFloat 32
%10 = OpTypeVector %9 4
%11 = OpTypePointer Input %10
%12 = OpVariable %11 Input
%13 = OpTypeInt 32 0
%14 = OpConstant %13 0
%15 = OpTypePointer Input %9
%20 = OpConstant %6 0
%28 = OpTypeBool
%31 = OpConstant %6 1
%4 = OpFunction %2 None %3
%5 = OpLabel
%8 = OpVariable %7 Function
%19 = OpVariable %7 Function
%33 = OpVariable %7 Function
%16 = OpAccessChain %15 %12 %14
%17 = OpLoad %9 %16
%18 = OpConvertFToS %6 %17
OpStore %8 %18
OpStore %19 %20
OpBranch %21
%21 = OpLabel
%44 = OpPhi %6 %20 %5 %32 %24
OpLoopMerge %23 %24 None
OpBranch %25
%25 = OpLabel
%29 = OpSLessThan %28 %44 %18
OpBranchConditional %29 %22 %23
%22 = OpLabel
OpBranch %24
%24 = OpLabel
%32 = OpIAdd %6 %44 %31
OpStore %19 %32
OpBranch %21
%23 = OpLabel
OpStore %33 %20
OpBranch %34
%34 = OpLabel
%46 = OpPhi %6 %20 %23 %43 %37
OpLoopMerge %36 %37 None
OpBranch %38
%38 = OpLabel
%41 = OpSLessThan %28 %46 %18
OpBranchConditional %41 %35 %36
%35 = OpLabel
OpBranch %37
%37 = OpLabel
%43 = OpIAdd %6 %46 %31
OpStore %33 %43
OpBranch %34
%36 = OpLabel
OpReturn
OpFunctionEnd
)";
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
Module* module = context->module();
EXPECT_NE(nullptr, module) << "Assembling failed for shader:\n"
<< text << std::endl;
Function& f = *module->begin();
LoopDescriptor& ld = *context->GetLoopDescriptor(&f);
EXPECT_EQ(ld.NumLoops(), 2u);
auto loops = ld.GetLoopsInBinaryLayoutOrder();
LoopFusion fusion(context.get(), loops[0], loops[1]);
EXPECT_TRUE(fusion.AreCompatible());
}
/*
Generated from the following GLSL + --eliminate-local-multi-store
#version 440 core
layout(location = 0) in vec4 c;
void main() {
int N = int(c.x);
for (int i = 0; N > j; i++) {}
for (int j = 0; N > j; j++) {}
}
*/
TEST_F(FusionCompatibilityTest, UnknownButSameUpperBoundReverseCondition) {
const std::string text = R"(
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main" %12
OpExecutionMode %4 OriginUpperLeft
OpSource GLSL 440
OpName %4 "main"
OpName %8 "N"
OpName %12 "c"
OpName %19 "i"
OpName %33 "j"
OpDecorate %12 Location 0
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 1
%7 = OpTypePointer Function %6
%9 = OpTypeFloat 32
%10 = OpTypeVector %9 4
%11 = OpTypePointer Input %10
%12 = OpVariable %11 Input
%13 = OpTypeInt 32 0
%14 = OpConstant %13 0
%15 = OpTypePointer Input %9
%20 = OpConstant %6 0
%28 = OpTypeBool
%31 = OpConstant %6 1
%4 = OpFunction %2 None %3
%5 = OpLabel
%8 = OpVariable %7 Function
%19 = OpVariable %7 Function
%33 = OpVariable %7 Function
%16 = OpAccessChain %15 %12 %14
%17 = OpLoad %9 %16
%18 = OpConvertFToS %6 %17
OpStore %8 %18
OpStore %19 %20
OpBranch %21
%21 = OpLabel
%45 = OpPhi %6 %20 %5 %32 %24
OpLoopMerge %23 %24 None
OpBranch %25
%25 = OpLabel
%29 = OpSGreaterThan %28 %18 %45
OpBranchConditional %29 %22 %23
%22 = OpLabel
OpBranch %24
%24 = OpLabel
%32 = OpIAdd %6 %45 %31
OpStore %19 %32
OpBranch %21
%23 = OpLabel
OpStore %33 %20
OpBranch %34
%34 = OpLabel
%47 = OpPhi %6 %20 %23 %43 %37
OpLoopMerge %36 %37 None
OpBranch %38
%38 = OpLabel
%41 = OpSGreaterThan %28 %18 %47
OpBranchConditional %41 %35 %36
%35 = OpLabel
OpBranch %37
%37 = OpLabel
%43 = OpIAdd %6 %47 %31
OpStore %33 %43
OpBranch %34
%36 = OpLabel
OpReturn
OpFunctionEnd
)";
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
Module* module = context->module();
EXPECT_NE(nullptr, module) << "Assembling failed for shader:\n"
<< text << std::endl;
Function& f = *module->begin();
LoopDescriptor& ld = *context->GetLoopDescriptor(&f);
EXPECT_EQ(ld.NumLoops(), 2u);
auto loops = ld.GetLoopsInBinaryLayoutOrder();
LoopFusion fusion(context.get(), loops[0], loops[1]);
EXPECT_TRUE(fusion.AreCompatible());
}
/*
Generated from the following GLSL + --eliminate-local-multi-store
#version 440 core
layout(location = 0) in vec4 c;
void main() {
// Can't fuse different bound
int N = int(c.x);
for (int i = 0; i < N; i++) {}
for (int j = 0; j < N+1; j++) {}
}
*/
TEST_F(FusionCompatibilityTest, UnknownUpperBoundAddition) {
const std::string text = R"(
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main" %12
OpExecutionMode %4 OriginUpperLeft
OpSource GLSL 440
OpName %4 "main"
OpName %8 "N"
OpName %12 "c"
OpName %19 "i"
OpName %33 "j"
OpDecorate %12 Location 0
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 1
%7 = OpTypePointer Function %6
%9 = OpTypeFloat 32
%10 = OpTypeVector %9 4
%11 = OpTypePointer Input %10
%12 = OpVariable %11 Input
%13 = OpTypeInt 32 0
%14 = OpConstant %13 0
%15 = OpTypePointer Input %9
%20 = OpConstant %6 0
%28 = OpTypeBool
%31 = OpConstant %6 1
%4 = OpFunction %2 None %3
%5 = OpLabel
%8 = OpVariable %7 Function
%19 = OpVariable %7 Function
%33 = OpVariable %7 Function
%16 = OpAccessChain %15 %12 %14
%17 = OpLoad %9 %16
%18 = OpConvertFToS %6 %17
OpStore %8 %18
OpStore %19 %20
OpBranch %21
%21 = OpLabel
%45 = OpPhi %6 %20 %5 %32 %24
OpLoopMerge %23 %24 None
OpBranch %25
%25 = OpLabel
%29 = OpSLessThan %28 %45 %18
OpBranchConditional %29 %22 %23
%22 = OpLabel
OpBranch %24
%24 = OpLabel
%32 = OpIAdd %6 %45 %31
OpStore %19 %32
OpBranch %21
%23 = OpLabel
OpStore %33 %20
OpBranch %34
%34 = OpLabel
%47 = OpPhi %6 %20 %23 %44 %37
OpLoopMerge %36 %37 None
OpBranch %38
%38 = OpLabel
%41 = OpIAdd %6 %18 %31
%42 = OpSLessThan %28 %47 %41
OpBranchConditional %42 %35 %36
%35 = OpLabel
OpBranch %37
%37 = OpLabel
%44 = OpIAdd %6 %47 %31
OpStore %33 %44
OpBranch %34
%36 = OpLabel
OpReturn
OpFunctionEnd
)";
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
Module* module = context->module();
EXPECT_NE(nullptr, module) << "Assembling failed for shader:\n"
<< text << std::endl;
Function& f = *module->begin();
LoopDescriptor& ld = *context->GetLoopDescriptor(&f);
EXPECT_EQ(ld.NumLoops(), 2u);
auto loops = ld.GetLoopsInBinaryLayoutOrder();
LoopFusion fusion(context.get(), loops[0], loops[1]);
EXPECT_FALSE(fusion.AreCompatible());
}
/*
Generated from the following GLSL + --eliminate-local-multi-store
// 10
#version 440 core
void main() {
for (int i = 0; i < 10; i++) {}
for (int j = 0; j < 10; j++) {}
for (int k = 0; k < 10; k++) {}
}
*/
TEST_F(FusionCompatibilityTest, SeveralAdjacentLoops) {
const std::string text = R"(
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main"
OpExecutionMode %4 OriginUpperLeft
OpSource GLSL 440
OpName %4 "main"
OpName %8 "i"
OpName %22 "j"
OpName %32 "k"
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 1
%7 = OpTypePointer Function %6
%9 = OpConstant %6 0
%16 = OpConstant %6 10
%17 = OpTypeBool
%20 = OpConstant %6 1
%4 = OpFunction %2 None %3
%5 = OpLabel
%8 = OpVariable %7 Function
%22 = OpVariable %7 Function
%32 = OpVariable %7 Function
OpStore %8 %9
OpBranch %10
%10 = OpLabel
%42 = OpPhi %6 %9 %5 %21 %13
OpLoopMerge %12 %13 None
OpBranch %14
%14 = OpLabel
%18 = OpSLessThan %17 %42 %16
OpBranchConditional %18 %11 %12
%11 = OpLabel
OpBranch %13
%13 = OpLabel
%21 = OpIAdd %6 %42 %20
OpStore %8 %21
OpBranch %10
%12 = OpLabel
OpStore %22 %9
OpBranch %23
%23 = OpLabel
%43 = OpPhi %6 %9 %12 %31 %26
OpLoopMerge %25 %26 None
OpBranch %27
%27 = OpLabel
%29 = OpSLessThan %17 %43 %16
OpBranchConditional %29 %24 %25
%24 = OpLabel
OpBranch %26
%26 = OpLabel
%31 = OpIAdd %6 %43 %20
OpStore %22 %31
OpBranch %23
%25 = OpLabel
OpStore %32 %9
OpBranch %33
%33 = OpLabel
%44 = OpPhi %6 %9 %25 %41 %36
OpLoopMerge %35 %36 None
OpBranch %37
%37 = OpLabel
%39 = OpSLessThan %17 %44 %16
OpBranchConditional %39 %34 %35
%34 = OpLabel
OpBranch %36
%36 = OpLabel
%41 = OpIAdd %6 %44 %20
OpStore %32 %41
OpBranch %33
%35 = OpLabel
OpReturn
OpFunctionEnd
)";
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
Module* module = context->module();
EXPECT_NE(nullptr, module) << "Assembling failed for shader:\n"
<< text << std::endl;
Function& f = *module->begin();
LoopDescriptor& ld = *context->GetLoopDescriptor(&f);
EXPECT_EQ(ld.NumLoops(), 3u);
auto loops = ld.GetLoopsInBinaryLayoutOrder();
auto loop_0 = loops[0];
auto loop_1 = loops[1];
auto loop_2 = loops[2];
EXPECT_FALSE(LoopFusion(context.get(), loop_0, loop_0).AreCompatible());
EXPECT_FALSE(LoopFusion(context.get(), loop_0, loop_2).AreCompatible());
EXPECT_FALSE(LoopFusion(context.get(), loop_1, loop_0).AreCompatible());
EXPECT_TRUE(LoopFusion(context.get(), loop_0, loop_1).AreCompatible());
EXPECT_TRUE(LoopFusion(context.get(), loop_1, loop_2).AreCompatible());
}
/*
Generated from the following GLSL + --eliminate-local-multi-store
#version 440 core
void main() {
// Can't fuse, not adjacent
int x = 0;
for (int i = 0; i < 10; i++) {
if (i > 10) {
x++;
}
}
x++;
for (int j = 0; j < 10; j++) {}
for (int k = 0; k < 10; k++) {}
}
*/
TEST_F(FusionCompatibilityTest, NonAdjacentLoops) {
const std::string text = R"(
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main"
OpExecutionMode %4 OriginUpperLeft
OpSource GLSL 440
OpName %4 "main"
OpName %8 "x"
OpName %10 "i"
OpName %31 "j"
OpName %41 "k"
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 1
%7 = OpTypePointer Function %6
%9 = OpConstant %6 0
%17 = OpConstant %6 10
%18 = OpTypeBool
%25 = OpConstant %6 1
%4 = OpFunction %2 None %3
%5 = OpLabel
%8 = OpVariable %7 Function
%10 = OpVariable %7 Function
%31 = OpVariable %7 Function
%41 = OpVariable %7 Function
OpStore %8 %9
OpStore %10 %9
OpBranch %11
%11 = OpLabel
%52 = OpPhi %6 %9 %5 %56 %14
%51 = OpPhi %6 %9 %5 %28 %14
OpLoopMerge %13 %14 None
OpBranch %15
%15 = OpLabel
%19 = OpSLessThan %18 %51 %17
OpBranchConditional %19 %12 %13
%12 = OpLabel
%21 = OpSGreaterThan %18 %52 %17
OpSelectionMerge %23 None
OpBranchConditional %21 %22 %23
%22 = OpLabel
%26 = OpIAdd %6 %52 %25
OpStore %8 %26
OpBranch %23
%23 = OpLabel
%56 = OpPhi %6 %52 %12 %26 %22
OpBranch %14
%14 = OpLabel
%28 = OpIAdd %6 %51 %25
OpStore %10 %28
OpBranch %11
%13 = OpLabel
%30 = OpIAdd %6 %52 %25
OpStore %8 %30
OpStore %31 %9
OpBranch %32
%32 = OpLabel
%53 = OpPhi %6 %9 %13 %40 %35
OpLoopMerge %34 %35 None
OpBranch %36
%36 = OpLabel
%38 = OpSLessThan %18 %53 %17
OpBranchConditional %38 %33 %34
%33 = OpLabel
OpBranch %35
%35 = OpLabel
%40 = OpIAdd %6 %53 %25
OpStore %31 %40
OpBranch %32
%34 = OpLabel
OpStore %41 %9
OpBranch %42
%42 = OpLabel
%54 = OpPhi %6 %9 %34 %50 %45
OpLoopMerge %44 %45 None
OpBranch %46
%46 = OpLabel
%48 = OpSLessThan %18 %54 %17
OpBranchConditional %48 %43 %44
%43 = OpLabel
OpBranch %45
%45 = OpLabel
%50 = OpIAdd %6 %54 %25
OpStore %41 %50
OpBranch %42
%44 = OpLabel
OpReturn
OpFunctionEnd
)";
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
Module* module = context->module();
EXPECT_NE(nullptr, module) << "Assembling failed for shader:\n"
<< text << std::endl;
Function& f = *module->begin();
LoopDescriptor& ld = *context->GetLoopDescriptor(&f);
EXPECT_EQ(ld.NumLoops(), 3u);
auto loops = ld.GetLoopsInBinaryLayoutOrder();
auto loop_0 = loops[0];
auto loop_1 = loops[1];
auto loop_2 = loops[2];
EXPECT_FALSE(LoopFusion(context.get(), loop_0, loop_0).AreCompatible());
EXPECT_FALSE(LoopFusion(context.get(), loop_0, loop_2).AreCompatible());
EXPECT_FALSE(LoopFusion(context.get(), loop_0, loop_1).AreCompatible());
EXPECT_TRUE(LoopFusion(context.get(), loop_1, loop_2).AreCompatible());
}
/*
Generated from the following GLSL + --eliminate-local-multi-store
// 12
#version 440 core
void main() {
int j = 0;
int i = 0;
for (; i < 10; i++) {}
for (; j < 10; j++) {}
}
*/
TEST_F(FusionCompatibilityTest, CompatibleInitDeclaredBeforeLoops) {
const std::string text = R"(
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main"
OpExecutionMode %4 OriginUpperLeft
OpSource GLSL 440
OpName %4 "main"
OpName %8 "j"
OpName %10 "i"
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 1
%7 = OpTypePointer Function %6
%9 = OpConstant %6 0
%17 = OpConstant %6 10
%18 = OpTypeBool
%21 = OpConstant %6 1
%4 = OpFunction %2 None %3
%5 = OpLabel
%8 = OpVariable %7 Function
%10 = OpVariable %7 Function
OpStore %8 %9
OpStore %10 %9
OpBranch %11
%11 = OpLabel
%32 = OpPhi %6 %9 %5 %22 %14
OpLoopMerge %13 %14 None
OpBranch %15
%15 = OpLabel
%19 = OpSLessThan %18 %32 %17
OpBranchConditional %19 %12 %13
%12 = OpLabel
OpBranch %14
%14 = OpLabel
%22 = OpIAdd %6 %32 %21
OpStore %10 %22
OpBranch %11
%13 = OpLabel
OpBranch %23
%23 = OpLabel
%33 = OpPhi %6 %9 %13 %31 %26
OpLoopMerge %25 %26 None
OpBranch %27
%27 = OpLabel
%29 = OpSLessThan %18 %33 %17
OpBranchConditional %29 %24 %25
%24 = OpLabel
OpBranch %26
%26 = OpLabel
%31 = OpIAdd %6 %33 %21
OpStore %8 %31
OpBranch %23
%25 = OpLabel
OpReturn
OpFunctionEnd
)";
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
Module* module = context->module();
EXPECT_NE(nullptr, module) << "Assembling failed for shader:\n"
<< text << std::endl;
Function& f = *module->begin();
LoopDescriptor& ld = *context->GetLoopDescriptor(&f);
EXPECT_EQ(ld.NumLoops(), 2u);
auto loops = ld.GetLoopsInBinaryLayoutOrder();
EXPECT_TRUE(LoopFusion(context.get(), loops[0], loops[1]).AreCompatible());
}
/*
Generated from the following GLSL + --eliminate-local-multi-store
// 13 regenerate!
#version 440 core
void main() {
int[10] a;
int[10] b;
// Can't fuse, several induction variables
for (int j = 0; j < 10; j++) {
b[i] = a[i];
}
for (int i = 0, j = 0; i < 10; i++, j = j+2) {
}
}
*/
TEST_F(FusionCompatibilityTest, SeveralInductionVariables) {
const std::string text = R"(
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main"
OpExecutionMode %4 OriginUpperLeft
OpSource GLSL 440
OpName %4 "main"
OpName %8 "j"
OpName %23 "b"
OpName %25 "a"
OpName %33 "i"
OpName %34 "j"
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 1
%7 = OpTypePointer Function %6
%9 = OpConstant %6 0
%16 = OpConstant %6 10
%17 = OpTypeBool
%19 = OpTypeInt 32 0
%20 = OpConstant %19 10
%21 = OpTypeArray %6 %20
%22 = OpTypePointer Function %21
%31 = OpConstant %6 1
%48 = OpConstant %6 2
%4 = OpFunction %2 None %3
%5 = OpLabel
%8 = OpVariable %7 Function
%23 = OpVariable %22 Function
%25 = OpVariable %22 Function
%33 = OpVariable %7 Function
%34 = OpVariable %7 Function
OpStore %8 %9
OpBranch %10
%10 = OpLabel
%50 = OpPhi %6 %9 %5 %32 %13
OpLoopMerge %12 %13 None
OpBranch %14
%14 = OpLabel
%18 = OpSLessThan %17 %50 %16
OpBranchConditional %18 %11 %12
%11 = OpLabel
%27 = OpAccessChain %7 %25 %50
%28 = OpLoad %6 %27
%29 = OpAccessChain %7 %23 %50
OpStore %29 %28
OpBranch %13
%13 = OpLabel
%32 = OpIAdd %6 %50 %31
OpStore %8 %32
OpBranch %10
%12 = OpLabel
OpStore %33 %9
OpStore %34 %9
OpBranch %35
%35 = OpLabel
%52 = OpPhi %6 %9 %12 %49 %38
%51 = OpPhi %6 %9 %12 %46 %38
OpLoopMerge %37 %38 None
OpBranch %39
%39 = OpLabel
%41 = OpSLessThan %17 %51 %16
OpBranchConditional %41 %36 %37
%36 = OpLabel
%44 = OpAccessChain %7 %25 %52
OpStore %44 %51
OpBranch %38
%38 = OpLabel
%46 = OpIAdd %6 %51 %31
OpStore %33 %46
%49 = OpIAdd %6 %52 %48
OpStore %34 %49
OpBranch %35
%37 = OpLabel
OpReturn
OpFunctionEnd
)";
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
Module* module = context->module();
EXPECT_NE(nullptr, module) << "Assembling failed for shader:\n"
<< text << std::endl;
Function& f = *module->begin();
LoopDescriptor& ld = *context->GetLoopDescriptor(&f);
EXPECT_EQ(ld.NumLoops(), 2u);
auto loops = ld.GetLoopsInBinaryLayoutOrder();
EXPECT_FALSE(LoopFusion(context.get(), loops[0], loops[1]).AreCompatible());
}
/*
Generated from the following GLSL + --eliminate-local-multi-store
// 14
#version 440 core
void main() {
// Fine
for (int i = 0; i < 10; i = i + 2) {}
for (int j = 0; j < 10; j = j + 2) {}
}
*/
TEST_F(FusionCompatibilityTest, CompatibleNonIncrementStep) {
const std::string text = R"(
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main"
OpExecutionMode %4 OriginUpperLeft
OpSource GLSL 440
OpName %4 "main"
OpName %8 "j"
OpName %10 "i"
OpName %11 "i"
OpName %24 "j"
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 1
%7 = OpTypePointer Function %6
%9 = OpConstant %6 0
%18 = OpConstant %6 10
%19 = OpTypeBool
%22 = OpConstant %6 2
%4 = OpFunction %2 None %3
%5 = OpLabel
%8 = OpVariable %7 Function
%10 = OpVariable %7 Function
%11 = OpVariable %7 Function
%24 = OpVariable %7 Function
OpStore %8 %9
OpStore %10 %9
OpStore %11 %9
OpBranch %12
%12 = OpLabel
%34 = OpPhi %6 %9 %5 %23 %15
OpLoopMerge %14 %15 None
OpBranch %16
%16 = OpLabel
%20 = OpSLessThan %19 %34 %18
OpBranchConditional %20 %13 %14
%13 = OpLabel
OpBranch %15
%15 = OpLabel
%23 = OpIAdd %6 %34 %22
OpStore %11 %23
OpBranch %12
%14 = OpLabel
OpStore %24 %9
OpBranch %25
%25 = OpLabel
%35 = OpPhi %6 %9 %14 %33 %28
OpLoopMerge %27 %28 None
OpBranch %29
%29 = OpLabel
%31 = OpSLessThan %19 %35 %18
OpBranchConditional %31 %26 %27
%26 = OpLabel
OpBranch %28
%28 = OpLabel
%33 = OpIAdd %6 %35 %22
OpStore %24 %33
OpBranch %25
%27 = OpLabel
OpReturn
OpFunctionEnd
)";
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
Module* module = context->module();
EXPECT_NE(nullptr, module) << "Assembling failed for shader:\n"
<< text << std::endl;
Function& f = *module->begin();
LoopDescriptor& ld = *context->GetLoopDescriptor(&f);
EXPECT_EQ(ld.NumLoops(), 2u);
auto loops = ld.GetLoopsInBinaryLayoutOrder();
EXPECT_TRUE(LoopFusion(context.get(), loops[0], loops[1]).AreCompatible());
}
/*
Generated from the following GLSL + --eliminate-local-multi-store
// 15
#version 440 core
int j = 0;
void main() {
// Not compatible, unknown init for second.
for (int i = 0; i < 10; i = i + 2) {}
for (; j < 10; j = j + 2) {}
}
*/
TEST_F(FusionCompatibilityTest, UnknonInitForSecondLoop) {
const std::string text = R"(
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main"
OpExecutionMode %4 OriginUpperLeft
OpSource GLSL 440
OpName %4 "main"
OpName %8 "j"
OpName %11 "i"
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 1
%7 = OpTypePointer Private %6
%8 = OpVariable %7 Private
%9 = OpConstant %6 0
%10 = OpTypePointer Function %6
%18 = OpConstant %6 10
%19 = OpTypeBool
%22 = OpConstant %6 2
%4 = OpFunction %2 None %3
%5 = OpLabel
%11 = OpVariable %10 Function
OpStore %8 %9
OpStore %11 %9
OpBranch %12
%12 = OpLabel
%33 = OpPhi %6 %9 %5 %23 %15
OpLoopMerge %14 %15 None
OpBranch %16
%16 = OpLabel
%20 = OpSLessThan %19 %33 %18
OpBranchConditional %20 %13 %14
%13 = OpLabel
OpBranch %15
%15 = OpLabel
%23 = OpIAdd %6 %33 %22
OpStore %11 %23
OpBranch %12
%14 = OpLabel
OpBranch %24
%24 = OpLabel
OpLoopMerge %26 %27 None
OpBranch %28
%28 = OpLabel
%29 = OpLoad %6 %8
%30 = OpSLessThan %19 %29 %18
OpBranchConditional %30 %25 %26
%25 = OpLabel
OpBranch %27
%27 = OpLabel
%31 = OpLoad %6 %8
%32 = OpIAdd %6 %31 %22
OpStore %8 %32
OpBranch %24
%26 = OpLabel
OpReturn
OpFunctionEnd
)";
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
Module* module = context->module();
EXPECT_NE(nullptr, module) << "Assembling failed for shader:\n"
<< text << std::endl;
Function& f = *module->begin();
LoopDescriptor& ld = *context->GetLoopDescriptor(&f);
EXPECT_EQ(ld.NumLoops(), 2u);
auto loops = ld.GetLoopsInBinaryLayoutOrder();
EXPECT_FALSE(LoopFusion(context.get(), loops[0], loops[1]).AreCompatible());
}
/*
Generated from the following GLSL + --eliminate-local-multi-store
// 16
#version 440 core
void main() {
// Not compatible, continue in loop 0
for (int i = 0; i < 10; ++i) {
if (i % 2 == 1) {
continue;
}
}
for (int j = 0; j < 10; ++j) {}
}
*/
TEST_F(FusionCompatibilityTest, Continue) {
const std::string text = R"(
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main"
OpExecutionMode %4 OriginUpperLeft
OpSource GLSL 440
OpName %4 "main"
OpName %8 "i"
OpName %29 "j"
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 1
%7 = OpTypePointer Function %6
%9 = OpConstant %6 0
%16 = OpConstant %6 10
%17 = OpTypeBool
%20 = OpConstant %6 2
%22 = OpConstant %6 1
%4 = OpFunction %2 None %3
%5 = OpLabel
%8 = OpVariable %7 Function
%29 = OpVariable %7 Function
OpStore %8 %9
OpBranch %10
%10 = OpLabel
%39 = OpPhi %6 %9 %5 %28 %13
OpLoopMerge %12 %13 None
OpBranch %14
%14 = OpLabel
%18 = OpSLessThan %17 %39 %16
OpBranchConditional %18 %11 %12
%11 = OpLabel
%21 = OpSMod %6 %39 %20
%23 = OpIEqual %17 %21 %22
OpSelectionMerge %25 None
OpBranchConditional %23 %24 %25
%24 = OpLabel
OpBranch %13
%25 = OpLabel
OpBranch %13
%13 = OpLabel
%28 = OpIAdd %6 %39 %22
OpStore %8 %28
OpBranch %10
%12 = OpLabel
OpStore %29 %9
OpBranch %30
%30 = OpLabel
%40 = OpPhi %6 %9 %12 %38 %33
OpLoopMerge %32 %33 None
OpBranch %34
%34 = OpLabel
%36 = OpSLessThan %17 %40 %16
OpBranchConditional %36 %31 %32
%31 = OpLabel
OpBranch %33
%33 = OpLabel
%38 = OpIAdd %6 %40 %22
OpStore %29 %38
OpBranch %30
%32 = OpLabel
OpReturn
OpFunctionEnd
)";
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
Module* module = context->module();
EXPECT_NE(nullptr, module) << "Assembling failed for shader:\n"
<< text << std::endl;
Function& f = *module->begin();
LoopDescriptor& ld = *context->GetLoopDescriptor(&f);
EXPECT_EQ(ld.NumLoops(), 2u);
auto loops = ld.GetLoopsInBinaryLayoutOrder();
EXPECT_FALSE(LoopFusion(context.get(), loops[0], loops[1]).AreCompatible());
}
/*
Generated from the following GLSL + --eliminate-local-multi-store
#version 440 core
void main() {
int[10] a;
// Compatible
for (int i = 0; i < 10; ++i) {
if (i % 2 == 1) {
} else {
a[i] = i;
}
}
for (int j = 0; j < 10; ++j) {}
}
*/
TEST_F(FusionCompatibilityTest, IfElseInLoop) {
const std::string text = R"(
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main"
OpExecutionMode %4 OriginUpperLeft
OpSource GLSL 440
OpName %4 "main"
OpName %8 "i"
OpName %31 "a"
OpName %37 "j"
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 1
%7 = OpTypePointer Function %6
%9 = OpConstant %6 0
%16 = OpConstant %6 10
%17 = OpTypeBool
%20 = OpConstant %6 2
%22 = OpConstant %6 1
%27 = OpTypeInt 32 0
%28 = OpConstant %27 10
%29 = OpTypeArray %6 %28
%30 = OpTypePointer Function %29
%4 = OpFunction %2 None %3
%5 = OpLabel
%8 = OpVariable %7 Function
%31 = OpVariable %30 Function
%37 = OpVariable %7 Function
OpStore %8 %9
OpBranch %10
%10 = OpLabel
%47 = OpPhi %6 %9 %5 %36 %13
OpLoopMerge %12 %13 None
OpBranch %14
%14 = OpLabel
%18 = OpSLessThan %17 %47 %16
OpBranchConditional %18 %11 %12
%11 = OpLabel
%21 = OpSMod %6 %47 %20
%23 = OpIEqual %17 %21 %22
OpSelectionMerge %25 None
OpBranchConditional %23 %24 %26
%24 = OpLabel
OpBranch %25
%26 = OpLabel
%34 = OpAccessChain %7 %31 %47
OpStore %34 %47
OpBranch %25
%25 = OpLabel
OpBranch %13
%13 = OpLabel
%36 = OpIAdd %6 %47 %22
OpStore %8 %36
OpBranch %10
%12 = OpLabel
OpStore %37 %9
OpBranch %38
%38 = OpLabel
%48 = OpPhi %6 %9 %12 %46 %41
OpLoopMerge %40 %41 None
OpBranch %42
%42 = OpLabel
%44 = OpSLessThan %17 %48 %16
OpBranchConditional %44 %39 %40
%39 = OpLabel
OpBranch %41
%41 = OpLabel
%46 = OpIAdd %6 %48 %22
OpStore %37 %46
OpBranch %38
%40 = OpLabel
OpReturn
OpFunctionEnd
)";
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
Module* module = context->module();
EXPECT_NE(nullptr, module) << "Assembling failed for shader:\n"
<< text << std::endl;
Function& f = *module->begin();
LoopDescriptor& ld = *context->GetLoopDescriptor(&f);
EXPECT_EQ(ld.NumLoops(), 2u);
auto loops = ld.GetLoopsInBinaryLayoutOrder();
EXPECT_TRUE(LoopFusion(context.get(), loops[0], loops[1]).AreCompatible());
}
} // namespace
} // namespace opt
} // namespace spvtools
| [
"yuri410@users.noreply.github.com"
] | yuri410@users.noreply.github.com |
9cf5ee1cbe81780f4dad2ce21ecd617bc489bc12 | 10e629b4357be87ee7c49247f280b93a8164ea2f | /main.cpp | 6f3920960d03e25f3e941607567bcbd62712a9de | [] | no_license | MichaelKirsch/ALGO_Ex2_towers_of_hanoi | b96312619286fbf41cad1381d4c1655d4f2006e1 | e0b0c0fd7927a25ff25d95467606c97f438275cc | refs/heads/master | 2022-06-06T13:45:30.873751 | 2020-05-02T16:35:27 | 2020-05-02T16:35:27 | 260,728,123 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 729 | cpp | #include <iostream>
#define DEBUG false
void move(int& count,int n, int src, int work, int dest)
{
count++;
if(n>1)
move(count,n-1,src,dest,work);
if(DEBUG)
std::cout <<"Step:"<<count << " | Move disk " << n << " from " << src << " to " << dest<< std::endl;
if(n>1)
move(count,n-1,work,src,dest);
}
int monks_do_your_damn_job(int amount)
{
int n = amount;
int dest = 3;
int counter = 0;
move(counter,n,1,dest-1,dest);
std::cout << "Took " << counter << " steps for "<< amount << std::endl;
return counter;
}
int main() {
monks_do_your_damn_job(3);
monks_do_your_damn_job(4);
monks_do_your_damn_job(5);
//Formula is (2^n)-1
return 0;
}
| [
"michael_kirsch"
] | michael_kirsch |
4912f4f27f8afbb76a90b43e63e77f9dea192111 | 18f4c05c3407bc5fadd033284cd5afc7e7108310 | /scr/BitmapLoader.cpp | cfd41e8744312054929d4ffa5ca00b58fa54afeb | [] | no_license | AxlWest/Grass | 1e24f949a506abd9cd7872afea707206162394de | df2e2209027f09ff4044f9afa165c6373c11c0c0 | refs/heads/master | 2021-01-10T21:36:30.866703 | 2015-09-29T08:27:30 | 2015-09-29T08:27:30 | 38,953,035 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,912 | cpp | #include <stdio.h>
#include "BitmapLoader.h"
GLuint BitmapLoader::texnum[BitmapLoader::TEXTURE_MAX] ;
BitmapLoader::BitmapLoader(void)
{
this->numberOfStoredTextures = 0 ;
}
BitmapLoader::~BitmapLoader(void)
{
}
void BitmapLoader::openGLBitmapInit(void)
{
glEnable(GL_TEXTURE_2D) ;
glGenTextures(8 , texnum) ;
}
GLuint BitmapLoader::loadBitmapTexture(const char* imagePathway)
{
if(this->numberOfStoredTextures < this->TEXTURE_MAX) //Checks to see if there are not to many textures already
{
this->bitmapData = this->bitmapFileLoader(imagePathway) ;
glBindTexture(GL_TEXTURE_2D , texnum[this->numberOfStoredTextures]) ;
glTexParameteri(GL_TEXTURE_2D , GL_TEXTURE_MAG_FILTER, GL_NEAREST) ;
glTexParameteri(GL_TEXTURE_2D , GL_TEXTURE_MIN_FILTER, GL_NEAREST) ;
glTexImage2D(GL_TEXTURE_2D , 0 , GL_RGB , bitmapInfoHeader.biWidth , bitmapInfoHeader.biHeight , 0 , GL_RGB , GL_UNSIGNED_BYTE , bitmapData) ;
this->numberOfStoredTextures++ ; //Increments the number of textures that are stored
}
return this->texnum[(this->numberOfStoredTextures -1)] ;
}
unsigned char* BitmapLoader::bitmapFileLoader(const char* imagePathway)
{
FILE *filePtr ;
BITMAPFILEHEADER bitmapFileHeader; // bitmap file header
unsigned char *bitmapImage; // bitmap image data
int imageIdx = 0; // image index counter
unsigned char tempRGB; // swap variable
// open filename in "read binary" mode
filePtr = fopen(imagePathway, "rb") ;
if (filePtr == NULL)
{
return NULL ;
}
// read the bitmap file header
fread(&bitmapFileHeader , sizeof(BITMAPFILEHEADER) , 1 , filePtr) ;
// verify that this is a bitmap by checking for the universal bitmap id
if(bitmapFileHeader.bfType != BITMAP_ID)
{
fclose(filePtr) ;
return NULL ;
}
// read the bitmap information header
fread(&bitmapInfoHeader , sizeof(BITMAPINFOHEADER) , 1 , filePtr);
// move file pointer to beginning of bitmap data
fseek(filePtr , bitmapFileHeader.bfOffBits , SEEK_SET);
// allocate enough memory for the bitmap image data
bitmapImage = (unsigned char*)malloc(bitmapInfoHeader.biSizeImage);
// verify memory allocation
if (!bitmapImage)
{
free(bitmapImage);
fclose(filePtr);
return NULL;
}
// read in the bitmap image data
fread(bitmapImage, 1, bitmapInfoHeader.biSizeImage, filePtr);
// make sure bitmap image data was read
if (bitmapImage == NULL)
{
fclose(filePtr) ;
return NULL ;
}
// swap the R and B values to get RGB since the bitmap color format is in BGR
for (imageIdx = 0; imageIdx < bitmapInfoHeader.biSizeImage; imageIdx+=3)
{
tempRGB = bitmapImage[imageIdx] ;
bitmapImage[imageIdx] = bitmapImage[imageIdx + 2] ;
bitmapImage[imageIdx + 2] = tempRGB ;
}
// close the file and return the bitmap image data
fclose(filePtr) ;
return bitmapImage ;
}
GLuint BitmapLoader::getTexnum(int num)
{
if(num < this->TEXTURE_MAX)
{
return this->texnum[num] ;
}
} | [
"axlwest@hotmail.com"
] | axlwest@hotmail.com |
70d4e30d2c199322423db04bd41a09560316d5db | 2adfc7b844d2bfbd43d95530f624fdca6f021510 | /Intro_to_Concurrency/Building_a_Concurrent_Message_Queue/concurrent_message_queue.cpp | 41cb3b0f6f38377065739149342e86c061adcfff | [] | no_license | rahul263-stack/100program-of-cpp | 96381ce5183e0e0ad17bb96db40042f5080b76db | 7cbda3f41c50d9a1d7a8889ec10b33ebd0024f18 | refs/heads/master | 2020-12-09T17:00:34.199728 | 2020-02-24T17:36:27 | 2020-02-24T17:36:27 | 233,365,464 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,986 | cpp | #include <iostream>
#include <thread>
#include <queue>
#include <future>
#include <mutex>
#include <algorithm>
template <class T>
class MessageQueue
{
public:
T receive()
{
// perform queue modification under the lock
std::unique_lock<std::mutex> u_lock(mutex_);
// pass unique lock to condition variable
cond_.wait( u_lock, [this] { return !messages_.empty(); } );
// remove last vector element from queue
T msg = std::move( messages_.back() );
messages_.pop_back();
return msg; // will not be copied due to return value optimization (RVO) in C++
}
void send(T&& msg)
{
// simulate some work
std::this_thread::sleep_for( std::chrono::milliseconds(100) );
// perform vector modification under the lock
std::lock_guard<std::mutex> u_lock(mutex_);
// add vector to queue
std::cout << " Message #" << msg << " has been sent to the queue" << std::endl;
messages_.push_back( std::move(msg) );
}
private:
std::mutex mutex_;
std::condition_variable cond_;
std::deque<T> messages_;
};
int main()
{
// create monitor object as a shared pointer to enable access by multiple threads
std::shared_ptr<MessageQueue<int>> queue( new MessageQueue<int> );
std::cout << "Spawning threads..." << std::endl;
std::vector<std::future<void>> futures;
for (int i = 0; i < 10; i++)
{
int message = i;
futures.emplace_back( std::async( std::launch::async, &MessageQueue<int>::send, queue, std::move(message) ) );
}
std::cout << "Collecting results..." << std::endl;
while (true)
{
int message = queue->receive();
std::cout << " Message #" << message << " has been removed from the queue" << std::endl;
}
std::for_each( futures.begin(), futures.end(), [](std::future<void>& ftr) { ftr.wait(); } );
std::cout << "Finished!" << std::endl;
return 0;
} | [
"53581155+rahul263-stack@users.noreply.github.com"
] | 53581155+rahul263-stack@users.noreply.github.com |
80bb8dde2545a89daca2e70159f1315ce6c54077 | 6754583bfba3b2a3c8d51d8dbfb626eb31d00c1b | /Source/ProjectRPG/Private/Item/ProjectRPGConsumable.cpp | d7f6d430533cccb8e22c8d6cdcec4a83b83b988f | [] | no_license | SmallImpactGames/ProjectRPG | 18462c5a56dcc8db9f594915a31edf5a1bce4488 | 843a7b91ef3532da1f4d60155cc855ec9dcbe55a | refs/heads/master | 2021-05-28T07:37:59.418561 | 2014-12-30T20:50:39 | 2014-12-30T20:50:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 242 | cpp |
#include "ProjectRPG.h"
#include "ProjectRPGConsumable.h"
AProjectRPGConsumable::AProjectRPGConsumable(const class FPostConstructInitializeProperties& PCIP)
: Super(PCIP)
{
// potions are always stackable
isStackable = true;
}
| [
"Russell.J.Baker@gmail.com"
] | Russell.J.Baker@gmail.com |
c93d2b7b998c18b596d20ae30482c866aeda1d4e | e5cd80fd89480cbc27a177b9608ec93359cca5f8 | /396.cpp | 701ab4a147fcc8b3fb3acdb7829cb629a503b15c | [] | no_license | higsyuhing/leetcode_middle | c5db8dd2e64f1b0a879b54dbd140117a8616c973 | 405c4fabd82ed1188d89851b4df35b28c5cb0fa6 | refs/heads/master | 2023-01-28T20:40:52.865658 | 2023-01-12T06:15:28 | 2023-01-12T06:15:28 | 139,873,993 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 465 | cpp | class Solution {
public:
int maxRotateFunction(vector<int>& A) {
int n = A.size();
long sum_t = 0, sum = 0;
for (int i = 0; i < n; i++) {
sum_t += i*A[i];
sum += A[i];
}
long res = sum_t;
for (int i = 1; i < n; i++) {
long p = (long)n*A[n-i];
sum_t = sum_t + sum - p;
res = max(res, sum_t);
}
return res;
}
};
| [
"noreply@github.com"
] | noreply@github.com |
de19f6e460219535aebea1fa9cc242f91ffad1ee | 02cd958f2757a615818312e98ad2a8d7ab5761d0 | /examples/Python-calls-C++/Boost.Python/callback/wrapper.cpp | 34e0a6b5739369d58423beae7d429bb5ea58b273 | [] | no_license | jacquev6/Polyglot | 3326d7194443d34dcc805e2a70eec503b79049c3 | 6f75cc0dd0a90787173a9305b02a77d7fa96973a | refs/heads/master | 2023-04-27T12:36:01.719228 | 2023-04-18T14:46:02 | 2023-04-18T14:46:02 | 46,793,504 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 349 | cpp | #include <boost/python.hpp>
namespace bp = boost::python;
#include "guest.hpp"
std::string wrapper(const std::string& host, bp::object f) {
return guest(
host,
[f](const std::string& s) {
return bp::extract<std::string>(f(s))();
}
);
}
BOOST_PYTHON_MODULE(wrapper)
{
bp::def("wrapper", wrapper);
}
| [
"vincent@vincent-jacques.net"
] | vincent@vincent-jacques.net |
c2eb4acf1a1231201d14fe21f23460de83a3301f | 35338779967e7d6585cc4e985c088b4032430fb2 | /CubeCrash/GameFramework/Engine/Include/Dx11Window.h | f390feb5d5b8f0e3f1482862ea971b6d8d94c682 | [] | no_license | axaxax1122/GraduationProject | 0e5f3c80cf43faa2f64ec9efa82a36ae25d045bd | db5a19bcc4d7db9bb2f64ca8fc2fd8d336d590af | refs/heads/master | 2021-01-12T00:55:03.742519 | 2017-08-07T14:05:54 | 2017-08-07T14:05:54 | 78,314,168 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 721 | h | #pragma once
#include "..\Include\Dx11Object.h"
DX11_BEGIN
class DX11_DLL CDx11Window :
public CDx11Object
{
private:
friend class CDx11Core; //Core Class에서 Window Class 멤버 접근 가능
private:
CDx11Window();
~CDx11Window();
private:
HWND m_hWnd;
HINSTANCE m_hInst;
RESOLUTION_TYPE m_eRSType;
public:
RESOLUTION_TYPE GetResolutionType();
HWND GetWindowHandle();
public:
bool Init(TCHAR* pTitle, TCHAR* pClass, HINSTANCE hInst,
int iIconID, int iSmallIconID, RESOLUTION_TYPE eRT,
WNDPROC pProc);
private:
ATOM MyRegisterClass(HINSTANCE hInst, TCHAR* pClass,
int iIconID, int iSmallIconID, WNDPROC pProc);
BOOL InitInstance(TCHAR* pTitle, TCHAR* pClass, RESOLUTION_TYPE eRT);
};
DX11_END | [
"twiclok@naver.com"
] | twiclok@naver.com |
354f53088cf0260ad5937c1e7caefbc19033748f | c2233581c9fcf627e3958ad351ccee10eb05ea7d | /CommonPCTool/commonWigets/romExportDialog.cpp | 374faf25ad02dbcb416edfc27bac5ce273e4a26a | [] | no_license | caiweijianGZ/Mygit | 3b796067f99e53440c581f7c20add0a659dd73ed | 90652195a04e360ed68c03a3d4b6ca8323b52021 | refs/heads/master | 2020-04-23T06:51:01.784298 | 2019-02-17T15:04:39 | 2019-02-17T15:04:39 | 170,987,737 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,548 | cpp | #include "romExportDialog.h"
#include "ui_romExportDialog.h"
romExportDialog::romExportDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::romExportDialog)
{
ui->setupUi(this);
m_closeEnable = true;
m_devAddr = addrSetDialog::currentDevAddr();
widgetInit();
qRegisterMetaType<uint32_t>("uint32_t");
connect(this, SIGNAL(dataExport(uint32_t,int)), this, SLOT(dataExportSlot(uint32_t,int)));
QString str_fileName = QDate::currentDate().toString("yyyy-MM-dd.log");
str_fileName = ROM_EXPORT_LOG_DIRECTORY + str_fileName;
m_pLogger = Logger::LoggerCreate(str_fileName);
if ( NULL == m_pLogger )
{
qDebug() << "创建日志文件失败:" << str_fileName;
}
}
romExportDialog::~romExportDialog()
{
if ( NULL != m_pLogger )
{
delete m_pLogger;
}
delete ui;
}
int romExportDialog::setInterface(AbsRWInterface *pInterface)
{
m_interface = pInterface;
return 0;
}
void* romExportDialog::threadExport(void *param)
{
pthread_detach(pthread_self());
romExportDialog *dialog = (romExportDialog*)param;
uint32_t romOffset = dialog->m_dataOffset;
uint32_t romDataLen = dialog->m_dataLen;
QByteArray readBytes;
int ret = dialog->infWrite(dialog->pkgExportRomAsk(romOffset, romDataLen));
dialog->m_pLogger->writeWithDate(tr("请求导出ROM数据,起始地址:%1,总长度:%2").arg(romOffset).arg(romDataLen));
if ( -1 == ret )
{
dialog->m_pLogger->writeWithDate("发送数据失败");
dialog->dataExport(0, LOGIC_EXPORT_ERR);
dialog->interfaceError(dialog->m_interface);
pthread_exit(NULL);
}
ret = dialog->infWaitForRead(readBytes, READ_TOTAL_TIMEOUT, ROM_READ_PERIOD);
if ( -1 == ret )
{
dialog->m_pLogger->writeWithDate("接收数据失败");
dialog->dataExport(0, LOGIC_EXPORT_ERR);
dialog->interfaceError(dialog->m_interface);
pthread_exit(NULL);
}
if ( 0 == ret )
{
dialog->m_pLogger->writeWithDate("接收数据超时");
dialog->dataExport(0, LOGIC_EXPORT_ERR);
pthread_exit(NULL);
}
ret = dialog->parseExportRomAck(readBytes);
if ( TP02_RTN_NO_ERR != ret )
{
dialog->m_pLogger->writeWithDate(tr("请求导出ROM数据失败,错误码:%1").arg(ret));
dialog->dataExport(0, LOGIC_EXPORT_ERR_ARG);
pthread_exit(NULL);
}
uint32_t readLenMax = READ_MAX_LEN;
int sendErrorCount = SEND_ERR_COUNT;
uint32_t readDataLen = romDataLen;
uint32_t readOffset = romOffset;
uint32_t readIndex = 0;
while ( sendErrorCount-- && readDataLen)
{
int readLen = (readDataLen>readLenMax)?readLenMax:readDataLen;
ret = dialog->infWrite(dialog->pkgExportRomData(readOffset, readLen));
dialog->m_pLogger->writeWithDate(tr("请求导出数据分片,地址偏移:%1,长度:%2").arg(readOffset).arg(readLen));
if ( -1 == ret )
{
dialog->m_pLogger->writeWithDate("发送数据失败");
dialog->dataExport(readIndex, LOGIC_EXPORT_ERR);
dialog->interfaceError(dialog->m_interface);
pthread_exit(NULL);
}
ret = dialog->infWaitForRead(readBytes, READ_TOTAL_TIMEOUT, ROM_READ_PERIOD);
if ( -1 == ret )
{
dialog->m_pLogger->writeWithDate("接收数据失败");
dialog->dataExport(readIndex, LOGIC_EXPORT_ERR);
dialog->interfaceError(dialog->m_interface);
pthread_exit(NULL);
}
if ( 0 == ret )
{
dialog->m_pLogger->writeWithDate("接收数据超时");
sleep(2);
continue;
}
QByteArray tmpRomData;
ret = dialog->parseExportRomData(readBytes, tmpRomData);
if ( TP02_RTN_NO_ERR != ret )
{
dialog->m_pLogger->writeWithDate(tr("请求导出数据分片失败,错误码:%1").arg(ret));
sleep(2);
continue;
}
dialog->m_romDataCache.append(tmpRomData);
readOffset += readLen;
readIndex += readLen;
readDataLen -= readLen;
sendErrorCount = SEND_ERR_COUNT;
dialog->dataExport(readIndex, LOGIC_EXPORT_DATA);
}
if ( readDataLen )
{
dialog->m_pLogger->writeWithDate(tr("导出ROM数据失败,剩余字节:%1").arg(readDataLen));
dialog->dataExport(readIndex, LOGIC_EXPORT_ERR);
pthread_exit(NULL);
}
dialog->dataExport(readIndex, LOGIC_EXPORT_FINSH);
return (void *)NULL;
}
int romExportDialog::exportStart()
{
int ret = pthread_create(&m_tid, NULL, threadExport, this);
if ( ret )
{
perror("pthread create error!");
return -1;
}
return 0;
}
QByteArray romExportDialog::pkgExportRomAsk(uint32_t offset, uint32_t dataLen)
{
TP02Protocol tp;
char sendBuff[2048] = {0};
uint16_t packLen = 0;
tp.genPkgExportRomAsk(sendBuff, packLen, m_devAddr, offset, dataLen);
QByteArray sendByte(sendBuff, packLen);
return sendByte;
}
QByteArray romExportDialog::pkgExportRomData(uint32_t offset, uint32_t dataLen)
{
TP02Protocol tp;
char sendBuff[2048] = {0};
uint16_t packLen = 0;
tp.genPkgExportRomData(sendBuff, packLen, m_devAddr, offset, dataLen);
QByteArray sendByte(sendBuff, packLen);
return sendByte;
}
int romExportDialog::parseExportRomAck(const QByteArray &ack)
{
TP02Protocol tp;
int ret = tp.fromRawData(ack.constData(), ack.length());
if ( TP02_RTN_NO_ERR != ret )
{
return -1;
}
uint8_t rtn;
ret = tp.getRtn(rtn);
if ( TP02_RTN_NO_ERR != ret )
{
return -1;
}
return rtn;
}
int romExportDialog::parseExportRomData(const QByteArray &ack, QByteArray &data)
{
TP02Protocol tp;
int ret = tp.fromRawData(ack.constData(), ack.length());
if ( TP02_RTN_NO_ERR != ret )
{
return -1;
}
char buff[4096];
uint16_t dataLen = 0;
ret = tp.getExportRomData(buff, dataLen);
if ( TP02_RTN_NO_ERR != ret )
{
return -1;
}
QByteArray readByte(buff, dataLen);
data = readByte;
return 0;
}
int romExportDialog::saveExportData(const QByteArray &data)
{
if ( data.isEmpty() )
{
return -1;
}
return this->saveData2File(m_saveFileName, data);
}
int romExportDialog::saveExportCache(const QByteArray &data)
{
if ( data.isEmpty() )
{
return -1;
}
QString cacheFileName = m_saveFileName + ".cache";
return this->saveData2File(cacheFileName, data);
}
int romExportDialog::saveData2File(const QString &fileName, const QByteArray &data)
{
QFile *pFile = new QFile(fileName);
if ( !pFile->exists() )
{
pFile->open(QIODevice::WriteOnly | QIODevice::Text);
pFile->close();
}
delete pFile;
QFile file(fileName);
if (!file.open(QIODevice::ReadWrite | QIODevice::Truncate) )
{
qDebug() << "文件打开失败!";
return -1;
}
file.write(data);
file.close();
return 0;
}
int romExportDialog::infWrite(QByteArray data)
{
return m_interface->write(data);
}
int romExportDialog::infRead(QByteArray &data)
{
return m_interface->read(data);
}
int romExportDialog::infWaitForRead(QByteArray &data, int msecs)
{
return m_interface->waitForRead(data, msecs);
}
int romExportDialog::infWaitForRead(QByteArray &data, int msecs, int period)
{
QByteArray readCache;
int ret = m_interface->waitForRead(readCache, msecs);
if ( ret <= 0 )
{
return ret;
}
data = readCache;
int readedLen = m_interface->waitForRead(readCache, period);
while ( readedLen > 0 )
{
ret += readedLen;
data += readCache;
readedLen = m_interface->waitForRead(readCache, period);
}
return ret;
}
void romExportDialog::setCloseEnable(bool enable)
{
m_closeEnable = enable;
}
void romExportDialog::widgetInit()
{
this->setWindowFlags(this->windowFlags() & (~Qt::WindowCloseButtonHint));
ui->progressBar->setValue(0);
}
void romExportDialog::setButtonEnable(bool enable)
{
ui->pushButton->setEnabled(enable);
ui->pushButton_2->setEnabled(enable);
ui->pushButton_3->setEnabled(enable);
ui->lineEdit->setEnabled(enable);
ui->lineEdit_2->setEnabled(enable);
}
void romExportDialog::closeEvent(QCloseEvent *event)
{
if ( m_closeEnable )
{
event->accept();
}else{
event->ignore();
}
}
void romExportDialog::dataExportSlot(uint32_t readIndex, int status)
{
switch (status) {
case LOGIC_EXPORT_ERR:
ui->label->setText("导出失败!");
this->setButtonEnable(true);
this->setCloseEnable(true);
this->saveExportCache(m_romDataCache);
m_saveFileName.clear();
break;
case LOGIC_EXPORT_FINSH:
ui->label->setText("导出完成!");
this->setButtonEnable(true);
this->setCloseEnable(true);
this->saveExportData(m_romDataCache);
m_saveFileName.clear();
break;
case LOGIC_EXPORT_DATA:
ui->progressBar->setValue(readIndex);
ui->label->setText("数据导出中,请稍后...");
break;
case LOGIC_EXPORT_START:
ui->progressBar->setMaximum(readIndex);
ui->label->setText(tr("数据导出开始,共%1字节").arg(readIndex));
break;
default:
break;
}
}
void romExportDialog::on_pushButton_3_clicked()
{
this->close();
}
void romExportDialog::on_pushButton_2_clicked()
{
if ( m_saveFileName.isEmpty() )
{
ui->label->setText("请选择导出数据储存文件");
return;
}
bool ok = false;
m_dataOffset = ui->lineEdit->text().toUInt(&ok);
if ( !ok )
{
ui->label->setText("请填写正确的数值");
return;
}
m_dataLen = ui->lineEdit_2->text().toUInt(&ok);
if ( !ok )
{
ui->label->setText("请填写正确的数值");
return;
}
ui->progressBar->setMaximum(m_dataLen);
m_romDataCache.clear();
this->setButtonEnable(false);
this->setCloseEnable(false);
this->exportStart();
}
void romExportDialog::on_pushButton_clicked()
{
QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),
"./untitled.data",
tr("DATA File (*.data)"));
if( fileName.isNull() )
{
return ;
}
m_saveFileName = fileName;
}
| [
"15521502713@163.com"
] | 15521502713@163.com |
8500b46646a8c7dc10bfc03cc33ad935ab95ace1 | 1ab5c4eafb8aaaa52be14eafd9aa80ea0439add2 | /pipesWindows/source/texture.cpp | 972d69cbe68dccd79fec0d2f7aca4a5b105d0200 | [] | no_license | JonahMania/pipes | f8ce0840a730b6f2417abc1ea420c8d43288950c | 9cc99be00c3367c20c9ef616c6960e63dfb36a36 | refs/heads/master | 2020-12-24T16:31:38.496038 | 2015-03-12T01:09:53 | 2015-03-12T01:09:53 | 32,049,677 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,071 | cpp | #include "headers/texture.hpp"
//Initializes variables
Texture::Texture()
{
hardTexture = NULL;
imageWidth = 0;
imageHeight = 0;
}
//Deallocates memory
Texture::~Texture()
{
close();
}
//Loads an image takes sting p as path to image and Render w
bool Texture::loadImage( std::string p, SDL_Renderer* w )
{
close();
//Create texture
SDL_Texture* imageTexture = NULL;
//Load the image at path p
SDL_Surface* loadedSurface = IMG_Load( p.c_str() );
//Check that loadedSurface is not empty
if( loadedSurface == NULL )
{
std::cerr << "ERROR: Image was not loaded " << p.c_str() << IMG_GetError() << std::endl;
}
else
{
//Set the texture to the image
imageTexture = SDL_CreateTextureFromSurface( w, loadedSurface );
//Check if imageTexture is empty
if( imageTexture == NULL )
{
std::cerr << "ERROR: Image texture was not created " << p.c_str() << SDL_GetError() << std::endl;
}
else
{
//Set image dimensions
imageWidth = loadedSurface->w;
imageHeight = loadedSurface->h;
}
//Get rid of loaded surface
SDL_FreeSurface( loadedSurface );
}
hardTexture = imageTexture;
return hardTexture != NULL;
}
//Deallocates texture
void Texture::close()
{
//If the hardware texture exists
if( hardTexture != NULL )
{
//Destroy the hardware texture
SDL_DestroyTexture( hardTexture );
hardTexture = NULL;
imageWidth = 0;
imageHeight = 0;
}
}
//Renders texture at a given point
void Texture::render( int x, int y, SDL_Renderer* w, SDL_Rect* clip, double angle, SDL_Point* center, SDL_RendererFlip flip )
{
//Set rendering clip of the sprite sheet
SDL_Rect renderClip = { x, y, imageWidth, imageHeight };
//Set clip rendering dimensions
if( clip != NULL )
{
renderClip.w = clip->w;
renderClip.h = clip->h;
}
//Render to the clipped portion of the texture to the screen
SDL_RenderCopyEx( w, hardTexture, clip, &renderClip, angle, center, flip );
}
//Get image width
int Texture::getWidth()
{
return imageWidth;
}
//Get image height
int Texture::getHeight()
{
return imageHeight;
}
| [
"jmania999@gmail.com"
] | jmania999@gmail.com |
643f61d48e475b48f4aeca8648012db5a11fdd80 | 6258de2aeb36cc728c998c107013ccd3f4ec29f1 | /DP/DP/LCS2_9252.cpp | 9c4e4950f0b211f0439ad820aec618fa504eed58 | [] | no_license | gihop/AlgorithmStudy | ac1f885ad03ba896d5b88334aaedc8a385d2fb48 | 281d786f4e6fc51bceb69fbc8684ab9485489012 | refs/heads/master | 2021-06-30T11:57:18.768253 | 2021-05-07T15:56:46 | 2021-05-07T15:56:46 | 230,912,854 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,027 | cpp | //
// LCS2_9252.cpp
// DP
//
// Created by jiho park on 2020/07/11.
// Copyright © 2020 jiho park. All rights reserved.
//
#include <iostream>
#include <string>
using namespace std;
//LCS_9251 문제를 참고하자.
//메모리 제한이 256mb 정도면 string 배열 100만개도 가능한 것 같다.
string LCS[1001][1001];
int bigger(int a, int b) { if(a>b) return a; return b; }
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
string a, b;
cin >> a >> b;
for(int i=0; i<a.size(); i++){
for(int j=0; j<b.size(); j++){
if(a[i]==b[j]) {
LCS[i+1][j+1]=LCS[i][j]+a[i];
}
else {
if(LCS[i+1][j].size() > LCS[i][j+1].size())
LCS[i+1][j+1] = LCS[i+1][j];
else
LCS[i+1][j+1] = LCS[i][j+1];
}
}
}
cout << LCS[a.size()][b.size()].size() << endl << LCS[a.size()][b.size()];
return 0;
}
| [
"giho-p@hanmail.net"
] | giho-p@hanmail.net |
19daa373655420f4a73bd38d2cd3d62146a81fbd | 877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a | /app/src/main/cpp/dir521/dir3871/dir5864/dir6285/dir7244/file7274.cpp | 8ebee0b3268410f4efd0da5bb68f5afc84072c43 | [] | no_license | tgeng/HugeProject | 829c3bdfb7cbaf57727c41263212d4a67e3eb93d | 4488d3b765e8827636ce5e878baacdf388710ef2 | refs/heads/master | 2022-08-21T16:58:54.161627 | 2020-05-28T01:54:03 | 2020-05-28T01:54:03 | 267,468,475 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 111 | cpp | #ifndef file7274
#error "macro file7274 must be defined"
#endif
static const char* file7274String = "file7274"; | [
"tgeng@google.com"
] | tgeng@google.com |
77db38629647e3e0dc0743a25825e292ca45fd29 | 84fd54bcf4e0224bb4de125bdc8fee9af9498910 | /cpp/ICPC/gcpc_17_D.cpp | b3abfca0d84b8c82391d1abb4fc122775e018910 | [] | no_license | vrublack/competitive-programming | 85571f1fa84be1363f37af6af655feb718b5f275 | 648edd02f5a3de64f762dc797c7b1d98893c915a | refs/heads/master | 2021-01-01T04:46:58.261957 | 2017-07-14T14:21:35 | 2017-07-14T14:21:35 | 97,242,297 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,448 | cpp | /**
Author: Valentin Rublack
Status: Correct
Last modified: Mon Jul 10 23:48:00 2017 +0200
Competition: ICPC
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#include <map>
#define LOOP(x, n) for (int x = 0; x < n; x++)
using namespace std;
bool dfs(int start, int end, vector<vector<int>> &adj_list, vector<bool> &visited)
{
if (start == end)
return true;
for (int adj : adj_list[start])
{
if (!visited[adj])
{
visited[adj] = true;
if (dfs(adj, end, adj_list, visited))
return true;
}
}
return false;
}
int main()
{
int n, m;
cin >> n >> m;
map<string, int> nations;
vector<vector<int>> NYT(193, vector<int>());
vector<vector<int>> NYT_rev(193, vector<int>());
//vector<vector<int>> Trump;
LOOP(i, n)
{
string nat1, nat2;
cin >> nat1;
string useless;
LOOP(j, 3)cin >> useless;
cin >> nat2;
if (nations.find(nat1) == nations.end())
{
nations[nat1] = nations.size();
}
if (nations.find(nat2) == nations.end())
{
nations[nat2] = nations.size();
}
int node1 = nations.find(nat1)->second;
int node2 = nations.find(nat2)->second;
NYT[node1].push_back(node2);
NYT_rev[node2].push_back(node1);
}
LOOP(i, m)
{
string nat1, nat2;
cin >> nat1;
string useless;
LOOP(j, 3)cin >> useless;
cin >> nat2;
if (nat1 == nat2)
{
cout << "Alternative Fact" << endl;
} else if (nations.find(nat1) == nations.end() || nations.find(nat2) == nations.end())
{
cout << "Pants on Fire" << endl;
} else
{
int node1 = nations.find(nat1)->second;
int node2 = nations.find(nat2)->second;
vector<bool> visited(193, false);
if (dfs(node1, node2, NYT, visited))
{
cout << "Fact" << endl;
} else
{
vector<bool> visited2(193, false);
if (dfs(node1, node2, NYT_rev, visited2))
{
cout << "Alternative Fact" << endl;
} else
{
cout << "Pants on Fire" << endl;
}
}
}
}
}
| [
"valentin.rublack@gmail.com"
] | valentin.rublack@gmail.com |
2a6d043ebe390096a9356ff0bcd5e304efac6d64 | 16ad74d73b9090626c8db72dbd13d841942a64c0 | /cad/piece.h | 910b796880d6059cfb56b119fd3dfacd2187d7fc | [] | no_license | FudanYuan/CADPRO | 65b18cd5f5f1a9237078b994acf35b45ead5be7f | e89678fd19bb146751d555c9ddefb5ab9a8f5452 | refs/heads/master | 2021-09-22T11:14:44.645028 | 2018-09-09T04:23:28 | 2018-09-09T04:23:28 | 119,213,918 | 4 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 4,114 | h | #ifndef PIECE_H
#define PIECE_H
#include <QObject>
#include <polyline.h>
#include <sheet.h>
#include "collisiondectect.h"
#include "quadtreenode.h"
class Piece
{
public:
enum CollisionsMode{
BoundingRectCollisionMode,
ShapeCollisionMode
};
enum PointRealtionToPiece{
Outside,
Inside,
OnBoundary
};
enum PairType{
None,
Left,
Right
};
Piece();
Piece(Polyline *p, int n=1, short i=6);
Piece(Polyline *p, QVector<QLineF> lines, int n=1, short i=6);
Piece(QVector<QPointF> points, int n=1, short i=6);
Piece(QVector<QPointF> points, QVector<QLineF> lines, int n=1, short i=6); // 带有参考线的多边形
Polyline* getPolyline();
Object* toObject();
void setPairType(PairType type); // 设置零件类型
PairType getPairType() const; // 获取零件类型
QVector<QPointF> &getPointsList();
void setReferenceLinesList(QVector<QLineF> lines);
QVector<QLineF> getReferenceLinesList();
qreal getArea() const;
QRectF getMinBoundingRect() const;
QRectF getBoundingRect() const;
QPointF getPosition() const;
void setAngle(const int angle);
qreal getAngle() const;
qreal getSquareness() const;
QPointF getCenterPoint() const;
void setCount(const int c);
int getCount() const;
QVector<QPointF> getOffset(); // 获取偏移量
void setPrecision(const short i);
short getPrecision() const;
bool isHorizontal() const; // 如果包络矩形的宽>高,则认为是横置的,否则,认为是竖置
void setTranspose(const bool transpose); // 设置切割件是否转置
bool isTranspose() const; // 获取切割件是否转置
QPointF refLineCenterToMinBoundRectCenter() const; // 参考线中心与最小矩形的相对关系
void moveTo(const QPointF position); // 移动零件至给定位置
void rotate(const QPointF cPoint, const qreal alpha); // 将零件旋转alpha度
void moveToByReferenceLine(const QPointF position); // 移动零件至给定位置
void rotateByReferenceLine(const QPointF cPoint, bool flag); // 将零件旋转alpha度
QPointF getOffsetForReferenceLine(const QRectF layoutRect, QPointF &gPoint); // 对于参考线,得到排放零件的偏移量
QPointF getOffsetForReferenceLine(const QRectF layoutRect); // 对于参考线,得到排放零件的偏移量
bool hasRelationToPoint(const QPointF &point); // 点与零件有关系
PointRealtionToPiece relationToPoint(const QPointF &point); // 返回点与零件的关系
bool inBoundingRect(const QPointF &point); // 点在零件的包络矩形范围内
bool contains(const QPointF &point); // 判断零件是否包含某点
bool onBoundary(const QPointF &point); // 判断点是否在零件的边上
bool containsInSheet(const Sheet &sheet); // 判断该零件是否在材料内部
bool collidesWithPiece(Piece piece, const CollisionsMode mode = ShapeCollisionMode); // 判断该零件是否与给定零件碰撞
qreal compactToOnHD(Piece p, qreal compactStep, qreal compactAccuracy); // 向零件水平靠接
qreal compactToOnVD(Piece p, qreal compactStep, qreal compactAccuracy); // 向零件垂直靠接
QPointF compactToOnAlpha(Piece p, qreal alpha, qreal compactStep, qreal compactAccuracy); // 向零件alpha方向靠接
private:
PairType pairType; // 零件类型:左支/右支
QVector<QPointF> pointsList; // 多边形点集
QVector<QLineF> referenceLines; // 上插线集合
qreal area; // 零件面积
QRectF minBoundingRect; // 零件对应的最小包络矩形,其中心为参考点
QRectF boundingRect; // 零件对应的包络矩形
qreal angle; // 零件最小包络矩形对应多变形顺时针旋转angle之后的外包矩形
qreal squareness; // 方正度
QPointF centerPoint; // 零件的质心
int count; // 零件个数
short precision; // 小数保留位数
bool transpose; // 是否转置,即一开始就旋转90'
};
#endif // PIECE_H
| [
"1025024131@qq.com"
] | 1025024131@qq.com |
9a5d18c4451583d89b586a40b12e669d313477c9 | 18102da07df4087a6e2e675c8fb93a25e8e6a8c6 | /examples/HelloWorld/HelloWorld.ino | 54d9c85f235317c36798fc914c3dcffcbbb8f291 | [
"LicenseRef-scancode-public-domain",
"CC0-1.0"
] | permissive | loopstick/ESP32_Tutorial | 5e5c29fa5996fdeb6fc03f2764e72085742455ae | 81b525e75c273e289eb9214d26e98161227c3dcf | refs/heads/master | 2021-02-09T02:03:42.045361 | 2020-04-02T19:29:19 | 2020-04-02T19:29:19 | 244,226,329 | 4 | 0 | null | 2020-03-01T21:41:35 | 2020-03-01T21:27:05 | null | UTF-8 | C++ | false | false | 647 | ino | /*
Hello World
A "Hello, World!" program generally is a computer program that
outputs or displays the message "Hello, World!".
Such a program is very simple in most programming languages,
and is often used to illustrate the basic syntax of a programming language.
It is often the first program written by people learning to code
*/
void setup() {
//initialize serial communication at a 9600 baud rate
Serial.begin(9600);
}
void loop(){
//send 'Hello, world!' over the serial port
Serial.println("Hello, world!");
//wait 100 milliseconds
delay(1000);
// before sending the message again
// so we don't drive ourselves crazy
}
| [
"loopstick@hotmail.com"
] | loopstick@hotmail.com |
721b6c6fd1fdcd35952b074a2acd57dbfa8e3942 | 43a54d76227b48d851a11cc30bbe4212f59e1154 | /ecm/src/v20190719/model/ModifyListenerResponse.cpp | 5f9840cc80bbdd161ecfd7639fbcfd47f2491fd5 | [
"Apache-2.0"
] | permissive | make1122/tencentcloud-sdk-cpp | 175ce4d143c90d7ea06f2034dabdb348697a6c1c | 2af6954b2ee6c9c9f61489472b800c8ce00fb949 | refs/heads/master | 2023-06-04T03:18:47.169750 | 2021-06-18T03:00:01 | 2021-06-18T03:00:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,434 | cpp | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/ecm/v20190719/model/ModifyListenerResponse.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Ecm::V20190719::Model;
using namespace std;
ModifyListenerResponse::ModifyListenerResponse()
{
}
CoreInternalOutcome ModifyListenerResponse::Deserialize(const string &payload)
{
rapidjson::Document d;
d.Parse(payload.c_str());
if (d.HasParseError() || !d.IsObject())
{
return CoreInternalOutcome(Error("response not json format"));
}
if (!d.HasMember("Response") || !d["Response"].IsObject())
{
return CoreInternalOutcome(Error("response `Response` is null or not object"));
}
rapidjson::Value &rsp = d["Response"];
if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString())
{
return CoreInternalOutcome(Error("response `Response.RequestId` is null or not string"));
}
string requestId(rsp["RequestId"].GetString());
SetRequestId(requestId);
if (rsp.HasMember("Error"))
{
if (!rsp["Error"].IsObject() ||
!rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() ||
!rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString())
{
return CoreInternalOutcome(Error("response `Response.Error` format error").SetRequestId(requestId));
}
string errorCode(rsp["Error"]["Code"].GetString());
string errorMsg(rsp["Error"]["Message"].GetString());
return CoreInternalOutcome(Error(errorCode, errorMsg).SetRequestId(requestId));
}
return CoreInternalOutcome(true);
}
| [
"tencentcloudapi@tenent.com"
] | tencentcloudapi@tenent.com |
17f1ba1b56407cc0921cabecf8c110652daa1417 | a62342d6359a88b0aee911e549a4973fa38de9ea | /0.6.0.3/Internal/SDK/BP_RemovableFoliage_Grey_Willow_a_classes.h | e25c7e5fe5af360cfbfbf1cd28b3ee33ceaa4e17 | [] | no_license | zanzo420/Medieval-Dynasty-SDK | d020ad634328ee8ee612ba4bd7e36b36dab740ce | d720e49ae1505e087790b2743506921afb28fc18 | refs/heads/main | 2023-06-20T03:00:17.986041 | 2021-07-15T04:51:34 | 2021-07-15T04:51:34 | 386,165,085 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 828 | h | #pragma once
// Name: Medieval Dynasty, Version: 0.6.0.3
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_RemovableFoliage_Grey_Willow_a.BP_RemovableFoliage_Grey_Willow_a_C
// 0x0000 (FullSize[0x0891] - InheritedSize[0x0891])
class UBP_RemovableFoliage_Grey_Willow_a_C : public UBP_RemovableFoliage_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_RemovableFoliage_Grey_Willow_a.BP_RemovableFoliage_Grey_Willow_a_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
92140393efd2c6ecedaa46c6ba2976c432fed314 | 66c82751d1759118a3b98736ccb0e6a2ac2326b6 | /Customer.cpp | 269ae79b96a2a8bd2e9e2cbf149d16d2d02ab2e9 | [] | no_license | jdeoey49/AccountCustomer | 62c844ed4b240b68036fd4123f10974f16609cf1 | 89503a2d4e15c89abebef494cda655431fda0e71 | refs/heads/master | 2022-10-11T07:39:09.611171 | 2020-05-31T20:51:40 | 2020-05-31T20:51:40 | 268,362,052 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 449 | cpp | #include<iostream>
#include"Customer.h"
using namespace std;
Customer::Customer(const string& n_ref, Account& a_ref) :name_(n_ref), account_ref_(a_ref)
{
cout << "class Customer:constructor running" << endl;
}
Customer::~Customer()
{
cout << "class Customer:destructor running" << endl;
}
Account& Customer::accessAccount()
{
return account_ref_;
}
void Customer::addMoney(double amount)
{
account_ref_.addMoney(amount);
}
| [
"noreply@github.com"
] | noreply@github.com |
ab7be50929ff0c2b16d7fec4c434b238e38845c6 | 2f864e40cc1e5ead7b5ab28dc638af1f556cfb2e | /src/HackPro/ConnectionTable.cpp | 48c129b3ffeb21844a113379c8205e0bab155a64 | [] | no_license | markandey/hackpro | f453b475e41526c68e8bcf2c568612a006a525a0 | dc43bd405cddbd24369b1d40b45cedd74c1d5ad1 | refs/heads/master | 2016-09-01T19:04:11.852246 | 2015-03-13T04:57:24 | 2015-03-13T04:57:24 | 32,129,572 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,449 | cpp | // ConnectionTable.cpp : implementation file
//
#include "stdafx.h"
#include "HackPro.h"
#include "ConnectionTable.h"
// CConnectionTable dialog
IMPLEMENT_DYNAMIC(CConnectionTable, CDialog)
CConnectionTable::CConnectionTable(CWnd* pParent /*=NULL*/)
: CDialog(CConnectionTable::IDD, pParent)
{
}
CConnectionTable::~CConnectionTable()
{
}
void CConnectionTable::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_LIST, m_List);
}
BEGIN_MESSAGE_MAP(CConnectionTable, CDialog)
ON_BN_CLICKED(IDC_REFRESHTABLE, OnBnClickedRefreshtable)
END_MESSAGE_MAP()
// CConnectionTable message handlers
BOOL CConnectionTable::OnInitDialog()
{
CDialog::OnInitDialog();
m_List.SetExtendedStyle(LVS_EX_FULLROWSELECT );
this->m_List.InsertColumn(0,"Local IP",LVCFMT_LEFT,100);
this->m_List.InsertColumn(1,"Remote IP",LVCFMT_LEFT,100);
this->m_List.InsertColumn(2,"Local Port",LVCFMT_LEFT,100);
this->m_List.InsertColumn(3,"Remote Port",LVCFMT_LEFT,100);
this->m_List.InsertColumn(4,"Protocol",LVCFMT_LEFT,70);
this->m_List.InsertColumn(5,"State",LVCFMT_LEFT,100);
GetTable();
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CConnectionTable::GetTable()
{
this->m_List.DeleteAllItems();
int Offset=0;
DWORD dwSize=0;
GetTcpTable(NULL,&dwSize,2);
if(dwSize>0)
{
char* Buffer= new char[dwSize];
MIB_TCPTABLE* pTable=(MIB_TCPTABLE*)Buffer;
if(GetTcpTable(pTable,&dwSize,2)==NO_ERROR)
{
DWORD count=pTable->dwNumEntries;
Offset=count;
MIB_TCPROW* pRows=pTable->table;
for(DWORD i=0;i<count;i++)
{
in_addr a;
a.S_un.S_addr=pRows[i].dwLocalAddr;
int index=this->m_List.InsertItem(i,inet_ntoa(a),0);
a.S_un.S_addr=pRows[i].dwRemoteAddr;
this->m_List.SetItemText(index,1,inet_ntoa(a));
CString strCov;
strCov.Format("%u",ntohs(pRows[i].dwLocalPort));
this->m_List.SetItemText(index,2,strCov);
strCov.Format("%u",ntohs(pRows[i].dwRemotePort));
this->m_List.SetItemText(index,3,strCov);
this->m_List.SetItemText(index,4,"TCP");
switch(pRows[i].dwState)
{
case MIB_TCP_STATE_CLOSED:
this->m_List.SetItemText(index,5,"Closed");
break;
case MIB_TCP_STATE_LISTEN:
this->m_List.SetItemText(index,5,"Listening");
break;
case MIB_TCP_STATE_SYN_SENT:
this->m_List.SetItemText(index,5,"SYN Sent");
break;
case MIB_TCP_STATE_SYN_RCVD:
this->m_List.SetItemText(index,5,"SYN Recieved");
break;
case MIB_TCP_STATE_ESTAB:
this->m_List.SetItemText(index,5,"Established");
break;
case MIB_TCP_STATE_FIN_WAIT1:
this->m_List.SetItemText(index,5,"FIN wait1");
break;
case MIB_TCP_STATE_FIN_WAIT2:
this->m_List.SetItemText(index,5,"FIN wait2");
break;
case MIB_TCP_STATE_CLOSE_WAIT:
this->m_List.SetItemText(index,5,"Closed Wait");
break;
case MIB_TCP_STATE_CLOSING:
this->m_List.SetItemText(index,5,"Closing");
break;
case MIB_TCP_STATE_LAST_ACK:
this->m_List.SetItemText(index,5,"Last ACK");
break;
case MIB_TCP_STATE_TIME_WAIT:
this->m_List.SetItemText(index,5,"Time Wait");
break;
case MIB_TCP_STATE_DELETE_TCB:
this->m_List.SetItemText(index,5,"Delete TCB");
break;
}
}
}
delete Buffer;
}
//-------------
dwSize=0;
GetUdpTable(NULL,&dwSize,2);
if(dwSize>0)
{
char* Buffer= new char[dwSize];
MIB_UDPTABLE* pTable=(MIB_UDPTABLE*)Buffer;
if(GetUdpTable(pTable,&dwSize,2)==NO_ERROR)
{
DWORD count=pTable->dwNumEntries;
MIB_UDPROW* pRows=pTable->table;
for(DWORD i=0;i<count;i++)
{
in_addr a;
a.S_un.S_addr=pRows[i].dwLocalAddr;
int index=this->m_List.InsertItem(Offset+i,inet_ntoa(a),0);
this->m_List.SetItemText(index,1,"--");
CString strCov;
strCov.Format("%u",ntohs(pRows[i].dwLocalPort));
this->m_List.SetItemText(index,2,strCov);
this->m_List.SetItemText(index,3,"--");
this->m_List.SetItemText(index,4,"UDP");
this->m_List.SetItemText(index,5,"--");
}
}
delete Buffer;
}
}
void CConnectionTable::OnBnClickedRefreshtable()
{
GetTable();
}
| [
"markande@yahoo-inc.com"
] | markande@yahoo-inc.com |
b6b48aced8034fd9077a78b1ebeb81f8ee5b8f3d | f65dcb78e78e19a8f4124c57f91cc53fd5c7869a | /最优矩阵连乘/2016.11.8.4.cpp | 5f0d4a308c280c42e3d17db31d49b7ba058f7896 | [
"Apache-2.0"
] | permissive | 1980744819/ACM-code | 8a1c46f20a09acc866309176471367d62ca14cef | a697242bc963e682e552e655e3d78527e044e854 | refs/heads/master | 2020-03-29T01:16:41.766331 | 2018-09-19T02:39:26 | 2018-09-19T02:39:26 | 149,380,865 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,231 | cpp | #include<iostream>
#include<algorithm>
#include<cstdio>
#include<vector>
#include<cstdlib>
#include<cstring>
using namespace std;
int dp[205][205];
int s[205][205];
int a[205];
int n;
void print(int i,int j,int t){
if(i==j){
cout<<"A"<<i-1;
}
else{
if(t!=0)
cout<<"(";
print(i,s[i][j],t+1);
print(s[i][j]+1,j,t+1);
if(t!=0)
cout<<")";
}
}
int main(){
int n;
while(~scanf("%d",&n)&&n!=0){
int i,j,k;
int length;
//memset(s,0,zizeof(s));
n++;
for(i=0;i<n;i++){
scanf("%d",&a[i]);
dp[i][i]=0;
}
int t;
for(length=2;length<=n;length++){
for(i=1;i<=n-length+1;i++){
j=i+length-1;
dp[i][j]=0x7fffffff;
for(k=i;k<=j-1;k++){
t=dp[i][k]+dp[k+1][j]+a[i-1]*a[k]*a[j];
if(t<dp[i][j]){
dp[i][j]=t;
//printf("%d\n",dp[i][j]);
s[i][j]=k;
}
}
}
}
//printf("%d\n",dp[1][n-1]);
print(1,n-1,0);
cout<<endl;
}
return 0;
}
| [
"1980744819@qq.com"
] | 1980744819@qq.com |
eed8c004ccfc84aefd9c2ae32c44b801c7cd52b7 | 4ed379a162fc4533eae675be42d061eaec52d7c4 | /Album.cpp | 613edf741b09cf76b7405f4d544007cc36abe6cd | [] | no_license | Sevo98/OOP_Lab3 | edac3263c9dc75a7474034376d8b739bd2224169 | 0b048982be3cbe07e6beb3718ef9550de0f8dae4 | refs/heads/master | 2022-08-30T08:14:02.370499 | 2020-05-26T10:56:15 | 2020-05-26T10:56:15 | 259,979,769 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 2,524 | cpp | #include <iostream>
#include "Album.h"
#include "Song.h"
#include "Genre.h"
#include "CheckInputInt.h"
using namespace std;
void ReadAlbumFromConsole(Album& album)
{
setlocale(LC_ALL, "ru");
cout << "Введите название альбома: ";
getline(cin, album.Name);
bool CheckYear = false;
while (CheckYear == false)
{
try
{
cout << "Введите год выпуска: ";
int year;
CheckInputInt(&year);
if (year < 0 || year > 2020)
{
throw exception("Неправильный год выпуска! Повторите ввод.");
}
album.Year = year;
CheckYear = true;
}
catch (const std::exception&)
{
cout << "Неправильный год выпуска! Повторите ввод." << endl;
}
}
bool CheckCountSongs = false;
while (CheckCountSongs == false)
{
try
{
cout << "Введите количество песен в альбоме: ";
int count;
CheckInputInt(&count);
if (count < 0)
{
throw exception("Количество не может быть меньше 0! Повторите ввод.");
}
album.countSong = count;
CheckCountSongs = true;
}
catch (const std::exception&)
{
cout << "Количество не может быть меньше 0! Повторите ввод." << endl;
}
}
cin.ignore(32767, '\n');
album.Songs = new Song[album.countSong];
for (int i = 0; i < album.countSong; i++)
{
cout << "Введите название песни №" << i + 1 << ":" << endl;
ReadSongFromConsole(album.Songs[i]);
}
for (int i = 0; i < album.countSong; i++)
{
if (album.Songs[i].Genre == Rock)
{
album.RockCount++;
}
if (album.Songs[i].Genre == Metall)
{
album.MetallCount++;
}
if (album.Songs[i].Genre == HipHop)
{
album.HipHopCount++;
}
if (album.Songs[i].Genre == Rap)
{
album.RapCount++;
}
if (album.Songs[i].Genre == Jazz)
{
album.JazzCount++;
}
if (album.Songs[i].Genre == Classic)
{
album.ClassicCount++;
}
}
}
void WriteAlbumFromConsole(Album& album)
{
cout << "Альбом: " << album.Name << endl;
cout << "Год выпуска: " << album.Year << endl;
cout << "В состав альбома входит " << album.countSong << " треков:" << endl;
for (int i = 0; i < album.countSong; i++)
{
cout << i + 1 << "-";
WriteSongFromConsole(album.Songs[i]);
}
}
void DemoAlbum()
{
Album album;
ReadAlbumFromConsole(album);
WriteAlbumFromConsole(album);
delete[] album.Songs;
}
| [
"sevo98.sk@gmail.com"
] | sevo98.sk@gmail.com |
755394a943bd36295e82ef1afaa569f1a6baf9d6 | 0436bf0c8276500a3ff59093bc6d3561268134c6 | /apps/nvlink_shared/src/Parallelogram.cpp | 86eab0edcd959d1d0f56e3c43d5c472903080f65 | [] | no_license | NVIDIA/OptiX_Apps | 7e21234c3e3c0e5237d011fc567da7f3f90e2c51 | 2ff552ce4b2cf0e998531899bb8b39d27e064d06 | refs/heads/master | 2023-08-20T02:47:58.294963 | 2023-08-08T10:29:36 | 2023-08-08T10:29:36 | 239,562,369 | 223 | 42 | null | 2023-09-04T09:31:07 | 2020-02-10T16:47:28 | C++ | UTF-8 | C++ | false | false | 3,036 | cpp | /*
* Copyright (c) 2013-2020, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//#include "inc/Application.h"
//
//#include <cstring>
//#include <iostream>
//#include <sstream>
//
//#include "shaders/shader_common.h"
#include "inc/SceneGraph.h"
#include "shaders/vector_math.h"
namespace sg
{
// Parallelogram from footpoint position, spanned by unnormalized vectors vecU and vecV, normal is normalized and on the CCW frontface.
void Triangles::createParallelogram(const float3& position, const float3& vecU, const float3& vecV, const float3& normal)
{
m_attributes.clear();
m_indices.clear();
TriangleAttributes attrib;
// Same for all four vertices in this parallelogram.
attrib.tangent = normalize(vecU);
attrib.normal = normal;
attrib.vertex = position; // left bottom
attrib.texcoord = make_float3(0.0f, 0.0f, 0.0f);
m_attributes.push_back(attrib);
attrib.vertex = position + vecU; // right bottom
attrib.texcoord = make_float3(1.0f, 0.0f, 0.0f);
m_attributes.push_back(attrib);
attrib.vertex = position + vecU + vecV; // right top
attrib.texcoord = make_float3(1.0f, 1.0f, 0.0f);
m_attributes.push_back(attrib);
attrib.vertex = position + vecV; // left top
attrib.texcoord = make_float3(0.0f, 1.0f, 0.0f);
m_attributes.push_back(attrib);
m_indices.push_back(0);
m_indices.push_back(1);
m_indices.push_back(2);
m_indices.push_back(2);
m_indices.push_back(3);
m_indices.push_back(0);
}
} // namespace sg
| [
"droettger@nvidia.com"
] | droettger@nvidia.com |
23c688bc0a5178ec1d4abe819845374273390b7e | ede6b30b5e1cac8d71503e26f3fe31bb2eff3544 | /EmojicodeReal-TimeEngine/String.cpp | 4d8ae927cb862ed9053b488cf960d0bbded5b5e7 | [
"LicenseRef-scancode-warranty-disclaimer",
"Artistic-2.0"
] | permissive | imraghava/emojicode | 3f7c9ccc98757df89458b4a022871e14ca2cc1b5 | b9df6025a1af449932ec16aa96f0e6bee9ea401b | refs/heads/master | 2021-01-21T21:38:00.589419 | 2017-05-22T16:34:53 | 2017-05-22T16:34:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,492 | cpp | //
// String.c
// Emojicode
//
// Created by Theo Weidmann on 02.02.15.
// Copyright (c) 2015 Theo Weidmann. All rights reserved.
//
#include "String.h"
#include "../utf8.h"
#include "List.h"
#include "Thread.hpp"
#include "standard.h"
#include <ctype.h>
#include <cstring>
#include <cmath>
#include <utility>
#include <algorithm>
namespace Emojicode {
EmojicodeInteger stringCompare(String *a, String *b) {
if (a == b) {
return 0;
}
if (a->length != b->length) {
return a->length - b->length;
}
return std::memcmp(a->characters(), b->characters(), a->length * sizeof(EmojicodeChar));
}
bool stringEqual(String *a, String *b) {
return stringCompare(a, b) == 0;
}
/** @warning GC-invoking */
Object* stringSubstring(EmojicodeInteger from, EmojicodeInteger length, Thread *thread) {
String *string = thread->getThisObject()->val<String>();
if (from >= string->length) {
length = 0;
from = 0;
}
if (length + from >= string->length) {
length = string->length - from;
}
if (length == 0) {
return emptyString;
}
Object *const &co = thread->retain(newArray(length * sizeof(EmojicodeChar)));
Object *ostro = newObject(CL_STRING);
String *ostr = ostro->val<String>();
ostr->length = length;
ostr->charactersObject = co;
std::memcpy(ostr->characters(), thread->getThisObject()->val<String>()->characters() + from,
length * sizeof(EmojicodeChar));
thread->release(1);
return ostro;
}
const char* stringToCString(Object *str) {
auto string = str->val<String>();
size_t ds = u8_codingsize(string->characters(), string->length);
char *utf8str = newArray(ds + 1)->val<char>();
// Convert
size_t written = u8_toutf8(utf8str, ds, string->characters(), string->length);
utf8str[written] = 0;
return utf8str;
}
Object* stringFromChar(const char *cstring) {
EmojicodeInteger len = u8_strlen(cstring);
if (len == 0) {
return emptyString;
}
Object *stro = newObject(CL_STRING);
String *string = stro->val<String>();
string->length = len;
string->charactersObject = newArray(len * sizeof(EmojicodeChar));
u8_toucs(string->characters(), len, cstring, strlen(cstring));
return stro;
}
void stringPrintStdoutBrigde(Thread *thread, Value *destination) {
printf("%s\n", stringToCString(thread->getThisObject()));
}
void stringEqualBridge(Thread *thread, Value *destination) {
String *a = thread->getThisObject()->val<String>();
String *b = thread->getVariable(0).object->val<String>();
destination->raw = stringEqual(a, b);
}
void stringSubstringBridge(Thread *thread, Value *destination) {
EmojicodeInteger from = thread->getVariable(0).raw;
EmojicodeInteger length = thread->getVariable(1).raw;
String *string = thread->getThisObject()->val<String>();
if (from < 0) {
from = (EmojicodeInteger)string->length + from;
}
if (length < 0) {
length = (EmojicodeInteger)string->length + length;
}
destination->object = stringSubstring(from, length, thread);
}
void stringIndexOf(Thread *thread, Value *destination) {
String *string = thread->getThisObject()->val<String>();
String *search = thread->getVariable(0).object->val<String>();
auto last = string->characters() + string->length;
EmojicodeChar *location = std::search(string->characters(), last, search->characters(),
search->characters() + search->length);
if (location == last) {
destination->makeNothingness();
}
else {
destination->optionalSet(static_cast<EmojicodeInteger>(location - string->characters()));
}
}
void stringTrimBridge(Thread *thread, Value *destination) {
String *string = thread->getThisObject()->val<String>();
EmojicodeInteger start = 0;
EmojicodeInteger stop = string->length - 1;
while (start < string->length && isWhitespace(string->characters()[start]))
start++;
while (stop > 0 && isWhitespace(string->characters()[stop]))
stop--;
destination->object = stringSubstring(start, stop - start + 1, thread);
}
void stringGetInput(Thread *thread, Value *destination) {
printf("%s\n", stringToCString(thread->getVariable(0).object));
fflush(stdout);
int bufferSize = 50, oldBufferSize = 0;
Object *buffer = newArray(bufferSize);
size_t bufferUsedSize = 0;
while (true) {
fgets(buffer->val<char>() + oldBufferSize, bufferSize - oldBufferSize, stdin);
bufferUsedSize = strlen(buffer->val<char>());
if (bufferUsedSize < bufferSize - 1) {
if (buffer->val<char>()[bufferUsedSize - 1] == '\n') {
bufferUsedSize -= 1;
}
break;
}
oldBufferSize = bufferSize - 1;
bufferSize *= 2;
buffer = resizeArray(buffer, bufferSize);
}
EmojicodeInteger len = u8_strlen_l(buffer->val<char>(), bufferUsedSize);
String *string = thread->getThisObject()->val<String>();
string->length = len;
Object *chars = newArray(len * sizeof(EmojicodeChar));
string = thread->getThisObject()->val<String>();
string->charactersObject = chars;
u8_toucs(string->characters(), len, buffer->val<char>(), bufferUsedSize);
*destination = thread->getThisContext();
}
void stringSplitByStringBridge(Thread *thread, Value *destination) {
Object *const &listObject = thread->retain(newObject(CL_LIST));
EmojicodeInteger firstOfSeperator = 0, seperatorIndex = 0, firstAfterSeperator = 0;
for (EmojicodeInteger i = 0, l = thread->getThisObject()->val<String>()->length; i < l; i++) {
Object *stringObject = thread->getThisObject();
Object *separator = thread->getVariable(0).object;
if (stringObject->val<String>()->characters()[i] == separator->val<String>()->characters()[seperatorIndex]) {
if (seperatorIndex == 0) {
firstOfSeperator = i;
}
// Full seperator found
if (firstOfSeperator + separator->val<String>()->length == i + 1) {
Object *stro;
if (firstAfterSeperator == firstOfSeperator) {
stro = emptyString;
}
else {
stro = stringSubstring(firstAfterSeperator,
i - firstAfterSeperator - separator->val<String>()->length + 1, thread);
}
listAppendDestination(listObject, thread)->copySingleValue(T_OBJECT, stro);
seperatorIndex = 0;
firstAfterSeperator = i + 1;
}
else {
seperatorIndex++;
}
}
else if (seperatorIndex > 0) { // and not matching
seperatorIndex = 0;
// We search from the begin of the last partial match
i = firstOfSeperator;
}
}
Object *stringObject = thread->getThisObject();
String *string = stringObject->val<String>();
listAppendDestination(listObject, thread)->copySingleValue(T_OBJECT, stringSubstring(firstAfterSeperator, string->length - firstAfterSeperator, thread));
*destination = listObject;
thread->release(1);
}
void stringLengthBridge(Thread *thread, Value *destination) {
destination->raw = thread->getThisObject()->val<String>()->length;
}
void stringUTF8LengthBridge(Thread *thread, Value *destination) {
String *str = thread->getThisObject()->val<String>();
destination->raw = u8_codingsize(str->characters(), str->length);
}
void stringByAppendingSymbolBridge(Thread *thread, Value *destination) {
String *string = thread->getThisObject()->val<String>();
Object *const &co = thread->retain(newArray((string->length + 1) * sizeof(EmojicodeChar)));
Object *ostro = newObject(CL_STRING);
String *ostr = ostro->val<String>();
string = thread->getThisObject()->val<String>();
ostr->length = string->length + 1;
ostr->charactersObject = co;
std::memcpy(ostr->characters(), string->characters(), string->length * sizeof(EmojicodeChar));
ostr->characters()[string->length] = thread->getVariable(0).character;
destination->object = ostro;
thread->release(1);
}
void stringSymbolAtBridge(Thread *thread, Value *destination) {
EmojicodeInteger index = thread->getVariable(0).raw;
String *str = thread->getThisObject()->val<String>();
if (index >= str->length) {
destination->makeNothingness();
return;
}
destination->optionalSet(str->characters()[index]);
}
void stringBeginsWithBridge(Thread *thread, Value *destination) {
String *a = thread->getThisObject()->val<String>();
String *with = thread->getVariable(0).object->val<String>();
if (a->length < with->length) {
destination->raw = 0;
return;
}
destination->raw = std::memcmp(a->characters(), with->characters(), with->length * sizeof(EmojicodeChar)) == 0;
}
void stringEndsWithBridge(Thread *thread, Value *destination) {
String *a = thread->getThisObject()->val<String>();
String *end = thread->getVariable(0).object->val<String>();
if (a->length < end->length) {
destination->raw = 0;
return;
}
destination->raw = std::memcmp(a->characters() + (a->length - end->length),
end->characters(), end->length * sizeof(EmojicodeChar)) == 0;
}
void stringSplitBySymbolBridge(Thread *thread, Value *destination) {
EmojicodeChar separator = thread->getVariable(0).character;
Object *const &list = thread->retain(newObject(CL_LIST));
EmojicodeInteger from = 0;
for (EmojicodeInteger i = 0, l = thread->getThisObject()->val<String>()->length; i < l; i++) {
if (thread->getThisObject()->val<String>()->characters()[i] == separator) {
listAppendDestination(list, thread)->copySingleValue(T_OBJECT, stringSubstring(from, i - from, thread));
from = i + 1;
}
}
Object *stringObject = thread->getThisObject();
listAppendDestination(list, thread)->copySingleValue(T_OBJECT,
stringSubstring(from, stringObject->val<String>()->length - from, thread));
thread->release(1);
destination->object = list;
}
void stringToData(Thread *thread, Value *destination) {
String *str = thread->getThisObject()->val<String>();
size_t ds = u8_codingsize(str->characters(), str->length);
Object *const &bytesObject = thread->retain(newArray(ds));
str = thread->getThisObject()->val<String>();
u8_toutf8(bytesObject->val<char>(), ds, str->characters(), str->length);
Object *o = newObject(CL_DATA);
Data *d = o->val<Data>();
d->length = ds;
d->bytesObject = bytesObject;
d->bytes = d->bytesObject->val<char>();
thread->release(1);
destination->object = o;
}
void stringToCharacterList(Thread *thread, Value *destination) {
String *str = thread->getThisObject()->val<String>();
Object *list = newObject(CL_LIST);
for (size_t i = 0; i < str->length; i++) {
listAppendDestination(list, thread)->copySingleValue(T_SYMBOL, str->characters()[i]);
}
destination->object = list;
}
void stringJSON(Thread *thread, Value *destination) {
parseJSON(thread, reinterpret_cast<Box *>(destination));
}
void initStringFromSymbolList(String *str, List *list) {
size_t count = list->count;
str->length = count;
str->charactersObject = newArray(count * sizeof(EmojicodeChar));
for (size_t i = 0; i < count; i++) {
Box b = list->elements()[i];
if (b.isNothingness()) break;
str->characters()[i] = b.value1.character;
}
}
void stringFromSymbolListBridge(Thread *thread, Value *destination) {
String *str = thread->getThisObject()->val<String>();
initStringFromSymbolList(str, thread->getVariable(0).object->val<List>());
*destination = thread->getThisContext();
}
void stringFromStringList(Thread *thread, Value *destination) {
size_t stringSize = 0;
size_t appendLocation = 0;
{
List *list = thread->getVariable(0).object->val<List>();
String *glue = thread->getVariable(1).object->val<String>();
for (size_t i = 0; i < list->count; i++) {
stringSize += list->elements()[i].value1.object->val<String>()->length;
}
if (list->count > 0) {
stringSize += glue->length * (list->count - 1);
}
}
Object *co = newArray(stringSize * sizeof(EmojicodeChar));
{
List *list = thread->getVariable(0).object->val<List>();
String *glue = thread->getVariable(1).object->val<String>();
String *string = thread->getThisObject()->val<String>();
string->length = stringSize;
string->charactersObject = co;
for (size_t i = 0; i < list->count; i++) {
String *aString = list->elements()[i].value1.object->val<String>();
std::memcpy(string->characters() + appendLocation, aString->characters(),
aString->length * sizeof(EmojicodeChar));
appendLocation += aString->length;
if (i + 1 < list->count) {
std::memcpy(string->characters() + appendLocation, glue->characters(),
glue->length * sizeof(EmojicodeChar));
appendLocation += glue->length;
}
}
}
*destination = thread->getThisContext();
}
std::pair<EmojicodeInteger, bool> charactersToInteger(EmojicodeChar *characters, EmojicodeInteger base,
EmojicodeInteger length) {
if (length == 0) {
return std::make_pair(0, false);
}
EmojicodeInteger x = 0;
for (size_t i = 0; i < length; i++) {
if (i == 0 && (characters[i] == '-' || characters[i] == '+')) {
if (length < 2) {
return std::make_pair(0, false);
}
continue;
}
EmojicodeInteger b = base;
if ('0' <= characters[i] && characters[i] <= '9') {
b = characters[i] - '0';
}
else if ('A' <= characters[i] && characters[i] <= 'Z') {
b = characters[i] - 'A' + 10;
}
else if ('a' <= characters[i] && characters[i] <= 'z') {
b = characters[i] - 'a' + 10;
}
if (b >= base) {
return std::make_pair(0, false);
}
x *= base;
x += b;
}
if (characters[0] == '-') {
x *= -1;
}
return std::make_pair(x, true);
}
void stringToInteger(Thread *thread, Value *destination) {
EmojicodeInteger base = thread->getVariable(0).raw;
String *string = thread->getThisObject()->val<String>();
auto pair = charactersToInteger(string->characters(), base, string->length);
if (pair.second) destination->optionalSet(pair.first);
else destination->makeNothingness();
}
void stringToDouble(Thread *thread, Value *destination) {
String *string = thread->getThisObject()->val<String>();
if (string->length == 0) {
destination->makeNothingness();
return;
}
EmojicodeChar *characters = string->characters();
double d = 0.0;
bool sign = true;
bool foundSeparator = false;
bool foundDigit = false;
size_t i = 0, decimalPlace = 0;
if (characters[0] == '-') {
sign = false;
i++;
} else if (characters[0] == '+') {
i++;
}
for (; i < string->length; i++) {
if (characters[i] == '.') {
if (foundSeparator) {
destination->makeNothingness();
return;
} else {
foundSeparator = true;
continue;
}
}
if (characters[i] == 'e' || characters[i] == 'E') {
auto exponent = charactersToInteger(characters + i + 1, 10, string->length - i - 1);
if (!exponent.second) {
destination->makeNothingness();
return;
} else {
d *= pow(10, exponent.first);
}
break;
}
if ('0' <= characters[i] && characters[i] <= '9') {
d *= 10;
d += characters[i] - '0';
if (foundSeparator) {
decimalPlace++;
}
foundDigit = true;
} else {
destination->makeNothingness();
return;
}
}
if (!foundDigit) {
destination->makeNothingness();
return;
}
d /= pow(10, decimalPlace);
if (!sign) {
d *= -1;
}
destination->optionalSet(d);
}
void stringToUppercase(Thread *thread, Value *destination) {
Object *const &o = thread->retain(newObject(CL_STRING));
size_t length = thread->getThisObject()->val<String>()->length;
Object *characters = newArray(length * sizeof(EmojicodeChar));
String *news = o->val<String>();
news->charactersObject = characters;
news->length = length;
String *os = thread->getThisObject()->val<String>();
for (size_t i = 0; i < length; i++) {
EmojicodeChar c = os->characters()[i];
if (c <= 'z') news->characters()[i] = toupper(c);
else news->characters()[i] = c;
}
thread->release(1);
destination->object = o;
}
void stringToLowercase(Thread *thread, Value *destination) {
Object *const &o = thread->retain(newObject(CL_STRING));
size_t length = thread->getThisObject()->val<String>()->length;
Object *characters = newArray(length * sizeof(EmojicodeChar));
String *news = o->val<String>();
news->charactersObject = characters;
news->length = length;
String *os = thread->getThisObject()->val<String>();
for (size_t i = 0; i < length; i++) {
EmojicodeChar c = os->characters()[i];
if (c <= 'z') news->characters()[i] = tolower(c);
else news->characters()[i] = c;
}
thread->release(1);
destination->object = o;
}
void stringCompareBridge(Thread *thread, Value *destination) {
String *a = thread->getThisObject()->val<String>();
String *b = thread->getVariable(0).object->val<String>();
destination->raw = stringCompare(a, b);
}
void stringMark(Object *self) {
auto string = self->val<String>();
if (string->charactersObject) {
mark(&string->charactersObject);
}
}
}
| [
"hi@idmean.xyz"
] | hi@idmean.xyz |
83ecd7e23b975cef1d18cb3f3a266ed44672a42e | 553f5e872d7a46de6b54b5ae2337669d16135330 | /main.cpp | 689f5850eedaf2f0f003321468776e41b3188635 | [] | no_license | bleotiu/OOP_MAPS | ef76c9d892bd47a44ad76a22c21c4ffa70db0773 | 092c6cad7ab9ddd5196280fd92e950dbc234820b | refs/heads/master | 2020-05-26T07:11:32.802046 | 2019-05-23T02:17:31 | 2019-05-23T02:17:31 | 188,145,450 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,821 | cpp | #include <iostream>
#include <vector>
#include <fstream>
#include <queue>
#include "Graph.h"
#include "GeneralGraph.h"
#include "dag.h"
#include "LineGraph.h"
#include "CompleteGraph.h"
#include "Tree.h"
#include "Factory.h"
using namespace std;
void Interface (){
int task,region_code,X,Y,R;
vector < pair< Graph *,int> > regions;
Graph * curr;
cout << "Bun venit la MisterMaps! \n"
"Pentru a crea o regiune introduceti 1 si apasati Enter.\n"
"Pentru a adauga un drum intre 2 orase introduceti 2 si apasati Enter.\n"
"Pentru a primi drumul minim dintre 2 orase introduceti 3 si apasati Enter.\n"
"Pentru a inchide aplicatia introduceti 0 si apasati Enter.\n";
cin >> task;
while (true){
if (task < 0 || task > 3)
cout << "Ati introdus un cod de operatie invalid!\nVa rugam sa incercati dinnou!\n";
if (task == 0) {
cout << "Va multumim ca ati utilizat MisterMaps!\n";
return ;
}
if (task == 1) {
cout << "Ati ales sa creati o noua regiune! \nAcum va trebui sa precizati formatul regiunii\n"
"Pentru formatul unui graf general introduceti 0 si apasati Enter\n"
"Pentru un graf aciclic orientat introduceti 1 si apasati Enter\n"
"Pentru un graf in linie introduceti 2 si apasati Enter\n"
"Pentru un arbore introduceti 3 si apasati Enter\n"
"Pentru un graf complet introduceti 4 si apasati Enter\n";
cin >> region_code;
curr = Factory :: NewGraph (region_code);
curr->CreateGraph ();
regions.push_back (make_pair(curr,region_code));
cout << "Regiunea " << regions.size() << " a fost adaugata!\n";
}
if (task == 2) {
cout << "Ati ales sa adaugati un drum intre 2 orase!\n"
"Acum introduceti in ordine numarul regiunii si cele 2 orase : \n";
cin >> R >> X >> Y;
while (R < 1 || R > regions.size()){
cout << "Regiunea introdusa nu exista!\nIntroduceti inca odata datele : \n";
cin >> R >> X >> Y;
}
while (X > regions[R - 1].first->size() || X < 1 || Y < 1 || Y > regions[R - 1].first->size()){
cout << "Orasele introduse nu se afla in regiune!\nIntroduceti inca odata datele : \n";
cin >> R >> X >> Y;
while (R < 1 || R > regions.size()){
cout << "Regiunea introdusa nu exista!\nIntroduceti inca odata datele : \n";
cin >> R >> X >> Y;
}
}
if (regions[R - 1].second > 1)
cout << "Regiunea " << R << " nu suporta adaugare de drum!\n";
else{
regions[R - 1].first->AddEdge (X,Y);
cout << "Drumul a fost adaugat cu succes!\n";
}
}
if (task == 3){
cout << "Ati ales sa primiti lungimea drumului minim intre 2 orase!\n"
"Acum introduceti in ordine numarul regiunii si cele 2 orase : \n";
cin >> R >> X >> Y;
while (R < 1 || R > regions.size()){
cout << "Regiunea introdusa nu exista!\nIntroduceti inca odata datele : \n";
cin >> R >> X >> Y;
}
while (X > regions[R - 1].first->size() || X < 1 || Y < 1 || Y > regions[R - 1].first->size()){
cout << "Orasele introduse nu se afla in regiune!\nIntroduceti inca odata datele : \n";
cin >> R >> X >> Y;
while (R < 1 || R > regions.size()){
cout << "Regiunea introdusa nu exista!\nIntroduceti inca odata datele : \n";
cin >> R >> X >> Y;
}
}
regions[R - 1].first->GetDistance (X,Y);
}
cout << "\n\nPentru a crea o regiune introduceti 1 si apasati Enter.\n"
"Pentru a adauga un drum intre 2 orase introduceti 2 si apasati Enter.\n"
"Pentru a primi drumul minim dintre 2 orase introduceti 3 si apasati Enter.\n"
"Pentru a inchide aplicatia introduceti 0 si apasati Enter.\n";
cin >> task;
}
}
int main() {
Interface();
Graph * A, * B, *C, *D, *E;
A = new GeneralGraph();
//A->CreateGraph();
//A->AddEdge(2,5);
//A->GetDistance(2,5);
B = new DirectedAcyclicGraph();
//B->CreateGraph();
//B->AddEdge(2,5);
//B->GetDistance(2,5);
C = new LineGraph();
//C->CreateGraph();
//C->GetDistance(2,5);
D = new CompleteGraph();
//D -> CreateGraph();
//D -> GetDistance(2,5);
E = new Tree();
//E->CreateGraph();
//E->GetDistance(5,3);
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
cf266578a691a9f109f00c5bbab9697517e05280 | 5b41e312db8aeb5532ba59498c93e2ec1dccd4ff | /SMC_DBClasses/CHD_GRADE_ANL.h | 42821aba047a05d0e63a31ee3c08499b9fb11321 | [] | no_license | frankilfrancis/KPO_HMI_vs17 | 10d96c6cb4aebffb83254e6ca38fe6d1033eba79 | de49aa55eccd8a7abc165f6057088a28426a1ceb | refs/heads/master | 2020-04-15T16:40:14.366351 | 2019-11-14T15:33:25 | 2019-11-14T15:33:25 | 164,845,188 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,025 | h | //## Copyright (C) 2009 SMS Siemag AG, Germany
//## Version generated by DBClassCodeUtility BETA 0.6.3
//## ALL METHODS MARKED AS - //##DBClassCodeUtility - WILL BE OVERWRITTEN, IF DB CLASS RE-GENERATED
//## MANUALLY IMPLEMENTED METHODS MUST BE LOCATED BELOW THE MARK - "YOUR-CODE" -
#if defined (_MSC_VER) && (_MSC_VER >= 1000)
#pragma once
#endif
#ifndef _INC_CHD_GRADE_ANL_INCLUDED
#define _INC_CHD_GRADE_ANL_INCLUDED
#include <set>
#include "CSMC_DBData.h"
class CHD_GRADE_ANL
: public CSMC_DBData
{
public:
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string HEATID;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string TREATID;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string PLANT;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string STEELGRADECODE;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string ENAME;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string AIMTYPE;
//##DBClassCodeUtility ! DO NOT EDIT !
static const std::string ANL;
//##DBClassCodeUtility ! DO NOT EDIT !
CHD_GRADE_ANL(cCBS_StdConnection* Connection);
//##DBClassCodeUtility ! DO NOT EDIT !
CHD_GRADE_ANL(cCBS_Connection* Connection);
//##DBClassCodeUtility ! DO NOT EDIT !
CHD_GRADE_ANL();
//##DBClassCodeUtility ! DO NOT EDIT !
~CHD_GRADE_ANL();
//##DBClassCodeUtility ! DO NOT EDIT !
//##Internal heat identifier
std::string getHEATID(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setHEATID(const std::string& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Treatment identifier
std::string getTREATID(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setTREATID(const std::string& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Plant identifier
std::string getPLANT(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setPLANT(const std::string& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Steel grade code
std::string getSTEELGRADECODE(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setSTEELGRADECODE(const std::string& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Element or slag compound name
std::string getENAME(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setENAME(const std::string& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Min, Max, Aim
std::string getAIMTYPE(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setAIMTYPE(const std::string& value);
//##DBClassCodeUtility ! DO NOT EDIT !
//##Analysis value
double getANL(long Row);
//##DBClassCodeUtility ! DO NOT EDIT !
void setANL(double value);
//##DBClassCodeUtility ! DO NOT EDIT !
bool select(const std::string& HEATID, const std::string& TREATID, const std::string& PLANT, const std::string& STEELGRADECODE, const std::string& ENAME, const std::string& AIMTYPE);
//## ----------------------------------END-GENERATED-CODE---------------------
//## ----------------------------------YOUR-CODE------------------------------
bool selectOrdered(const std::string& HEATID, const std::string& TREATID, const std::string& PLANT, const std::string& STEELGRADECODE, const std::string& ENAME, const std::string& AIMTYPE);
bool copy(const std::string &STEELGRADECODE, const std::string& HEATID, const std::string& TREATID, const std::string& PLANT, bool Commit, cCBS_ODBC_DBError &Error);
bool exists(const std::string& HEATID, const std::string& TREATID, const std::string& PLANT);
std::set<std::string> getENAMEList(const std::string& HEATID, const std::string& TREATID, const std::string& PLANT, const std::string& STEELGRADECODE, const std::string& AIMTYPE, long MEASUREMENT_NAME_SCOPE );
bool updateAnl(const std::string& HEATID, const std::string& TREATID, const std::string& PLANT, const std::string& STEELGRADECODE, const std::string& ENAME, const std::string& AIMTYPE, double ANL, bool Commit, cCBS_ODBC_DBError &Error);
};
#endif /* _INC_CHD_GRADE_ANL_INCLUDED */
| [
"52784069+FrankilPacha@users.noreply.github.com"
] | 52784069+FrankilPacha@users.noreply.github.com |
6c7e75ebcb9b8ce9e19a65a92ee97ae638c57383 | 4ac4d0379cbe17886b3ec9c1648805d4d97f07b0 | /Day2/10_trivial3.cpp | a36dc8bb88bc45eb3a49b90d7a3b42f62845365f | [] | no_license | nado6miri/cpp_idioms | 1708c61d944e1908b07bac20da6b64916bc67385 | 400ad8cac1a7a841376cf52b5a792ffa9989df56 | refs/heads/master | 2020-06-13T21:20:10.566602 | 2019-07-26T03:11:29 | 2019-07-26T03:11:29 | 194,790,340 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,674 | cpp | #include <iostream>
#include <type_traits>
struct Point
{
int x, y;
};
/*
template<typename T>copy_type(T* d, T* s, size_t n)
{
if (std::is_trivially_copy_constructible<T>::value)
{
memcpy(d, s, sizeof(T)*n);
}
else
{
// 복사 생성자가 하는 일이 있으면 각 요소에 대해서 복사 생성자 호출
while (n--)
{
//new T; // 메모리 할당 + 생성자 호출
//new T(*s); // 메모리 할당 + 복사 생성자 호출
//new(d) T; // d 메모리에 default생성자 호출
new(d) T(*s); // d 메모리에 복사 생성자 호출
++d, ++s;
}
}
}
*/
// 두개의 동일 템플릿이 존재하니 if_enable이용해서 분기 치면 됨.
template<typename T>
typename std::enable_if<std::is_trivially_copy_constructible<T>::value>::type
copy_type(T* d, T* s, size_t n)
{
memcpy(d, s, sizeof(T)*n);
}
template<typename T>
typename std::enable_if<!std::is_trivially_copy_constructible<T>::value>::type
copy_type(T* d, T* s, size_t n)
{
// 복사 생성자가 하는 일이 있으면 각 요소에 대해서 복사 생성자 호출
while (n--)
{
//new T; // 메모리 할당 + 생성자 호출
//new T(*s); // 메모리 할당 + 복사 생성자 호출
//new(d) T; // d 메모리에 default생성자 호출
new(d) T(*s); // d 메모리에 복사 생성자 호출
++d, ++s;
}
}
int main()
{
char s1[10] = "hello";
char s2[10];
strcpy(s2, s1); // 메모리 할당없고, 기존 메모리 복사
// 위 함수는 char밖에 copy하지 못하니 C++철학에 맞게 모든 type을 복사하는 함수를 만들어 보자
copy_type(s2, s1, 10);
} | [
"noreply@github.com"
] | noreply@github.com |
c4391e751ac6a43ac9c3411782a30bccc5944b92 | a626682683f11f2a4a9145331cf89b87ce0f2529 | /5.SelectionSort.cpp | 1ef35b7d688b3cf553149f4cae1b2e8248f39152 | [] | no_license | abdurrezzak/30-Days-30-Algorithms- | 44391214224da1916de40183d88789693dc989b1 | 72f5124cf4a3da281dedf332d6bca5116f8e6b49 | refs/heads/master | 2021-08-20T09:11:20.159339 | 2017-11-28T18:33:56 | 2017-11-28T18:33:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 999 | cpp | /*
* This program takes an array from the user
* sorts it using selection sort
* Prints the sorted array
* For more information about Insertion Sort Algorithm: https://en.wikipedia.org/wiki/Selection_sort
*
* Coded by: Abdurrezak EFE
*
* */
#include <iostream>
#include <algorithm>
using namespace std;
void selection_sort(int arr[],int k) //insertion sort function
{
for(int i=0;i<k;i++)
{
int smallest=999999999;
int smallestIndex=-1;
for(int j=i;j<k;j++)
{
if(arr[j]<=smallest)
smallest = arr[j],smallestIndex=j;
arr[smallestIndex] = arr[i];
arr[i] = smallest;
}
}
}
int main()
{
int k;
cout << "Enter the number of the integers you want to construct the array from: ";
cin >> k;
int arr[k];
for(int i=0;i<k;i++)
cin >> arr[i];
selection_sort(arr,k); //sorting
for(int i=0;i<k;i++) //printing the array
cout << arr[i] << " ";
}
| [
"noreply@github.com"
] | noreply@github.com |
aaf97614938e25cdbafc6517b26b8d7181bad6f3 | bc39fe77f82affcc39cf2a24ad827c13fd471e5f | /cocos2dx/effects/CCGrid.h | fbb3a5e442ec7ec945df1b6ed91ce21b2bdfddb2 | [] | no_license | pigpigyyy/Dorothy | c3a11323fe5b0f46f40955074cffbe28d824c0e8 | ac9eeaf84a5abb0b23de741b747e0fb970c78aba | refs/heads/master | 2022-04-29T09:02:48.788574 | 2022-03-03T08:29:04 | 2022-03-03T08:29:04 | 24,334,351 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,325 | h | /****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2009 On-Core
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __EFFECTS_CCGRID_H__
#define __EFFECTS_CCGRID_H__
#include "cocoa/CCObject.h"
#include "base_nodes/CCNode.h"
#include "basics/CCCamera.h"
#include "ccTypes.h"
#include "textures/CCTexture2D.h"
#include "basics/CCDirector.h"
#include "kazmath/mat4.h"
NS_CC_BEGIN
class CCTexture2D;
class CCGrabber;
class CCGLProgram;
/**
* @addtogroup effects
* @{
*/
/** Base class for other
*/
class CC_DLL CCGridBase : public CCObject
{
public:
virtual ~CCGridBase();
/** whether or not the grid is active */
inline bool isActive() { return m_bActive; }
void setActive(bool bActive);
/** number of times that the grid will be reused */
inline int getReuseGrid() { return m_nReuseGrid; }
inline void setReuseGrid(int nReuseGrid) { m_nReuseGrid = nReuseGrid; }
/** size of the grid */
inline const CCSize& getGridSize() { return m_sGridSize; }
inline void setGridSize(const CCSize& gridSize) { m_sGridSize = gridSize; }
/** pixels between the grids */
inline const CCPoint& getStep() { return m_obStep; }
inline void setStep(const CCPoint& step) { m_obStep = step; }
/** is texture flipped */
inline bool isTextureFlipped() { return m_bIsTextureFlipped; }
void setTextureFlipped(bool bFlipped);
bool initWithSize(const CCSize& gridSize, CCTexture2D *pTexture, bool bFlipped);
bool initWithSize(const CCSize& gridSize);
void beforeDraw();
void afterDraw(CCNode *pTarget);
virtual void blit();
virtual void reuse();
virtual void calculateVertexPoints();
public:
/** create one Grid */
static CCGridBase* create(const CCSize& gridSize, CCTexture2D *texture, bool flipped);
/** create one Grid */
static CCGridBase* create(const CCSize& gridSize);
void set2DProjection();
protected:
bool m_bActive;
int m_nReuseGrid;
CCSize m_sGridSize;
CCTexture2D *m_pTexture;
CCPoint m_obStep;
CCGrabber *m_pGrabber;
bool m_bIsTextureFlipped;
CCGLProgram* m_pShaderProgram;
ccDirectorProjection m_directorProjection;
};
/**
CCGrid3D is a 3D grid implementation. Each vertex has 3 dimensions: x,y,z
*/
class CC_DLL CCGrid3D : public CCGridBase
{
public:
CCGrid3D();
~CCGrid3D();
/** returns the vertex at a given position */
ccVertex3F vertex(const CCPoint& pos);
/** returns the original (non-transformed) vertex at a given position */
ccVertex3F originalVertex(const CCPoint& pos);
/** sets a new vertex at a given position */
void setVertex(const CCPoint& pos, const ccVertex3F& vertex);
virtual void blit();
virtual void reuse();
virtual void calculateVertexPoints();
public:
/** create one Grid */
static CCGrid3D* create(const CCSize& gridSize, CCTexture2D *pTexture, bool bFlipped);
/** create one Grid */
static CCGrid3D* create(const CCSize& gridSize);
protected:
GLvoid *m_pTexCoordinates;
GLvoid *m_pVertices;
GLvoid *m_pOriginalVertices;
GLushort *m_pIndices;
};
/**
CCTiledGrid3D is a 3D grid implementation. It differs from Grid3D in that
the tiles can be separated from the grid.
*/
class CC_DLL CCTiledGrid3D : public CCGridBase
{
public:
CCTiledGrid3D();
~CCTiledGrid3D();
/** returns the tile at the given position */
ccQuad3 tile(const CCPoint& pos);
/** returns the original tile (untransformed) at the given position */
ccQuad3 originalTile(const CCPoint& pos);
/** sets a new tile */
void setTile(const CCPoint& pos, const ccQuad3& coords);
virtual void blit();
virtual void reuse();
virtual void calculateVertexPoints();
public:
/** create one Grid */
static CCTiledGrid3D* create(const CCSize& gridSize, CCTexture2D *pTexture, bool bFlipped);
/** create one Grid */
static CCTiledGrid3D* create(const CCSize& gridSize);
protected:
GLvoid *m_pTexCoordinates;
GLvoid *m_pVertices;
GLvoid *m_pOriginalVertices;
GLushort *m_pIndices;
};
// end of effects group
/// @}
NS_CC_END
#endif // __EFFECTS_CCGRID_H__
| [
"dragon-fly@qq.com"
] | dragon-fly@qq.com |
6264276701aa0aeb6167e1e6f68e8d30358ba0a9 | a06d2f37314a37b6038d46f8deda98b2af2530a2 | /Codeforces/1409A.cpp | 0a9d3b2d8ada1f3a9ccd2014f12e13528014f3f2 | [] | no_license | CarlosAlberto1x9/code | 40bea88605b543b98c8b58bdaafca008159c9ccd | c5161356d2bc868f0b22f5ba0e7f330fc5a6e2d7 | refs/heads/master | 2023-02-01T05:13:57.878134 | 2020-12-17T03:54:28 | 2020-12-17T03:54:28 | 171,583,412 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 296 | cpp | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
ll a, b;
while(t--) {
cin >> a >> b;
cout << abs(a - b)/10 + ( abs(a - b) % 10 > 0 ) << '\n';
}
return 0;
} | [
"starlightone@outlook.com"
] | starlightone@outlook.com |
5dbe4c6013b681c993750724548a54c5552273b1 | 5c2253988a10859ba7d9a65132408b9ea0e494b8 | /Calc/src/Main.cpp | 2e5deb8efb7b97512559b3281831cc024509808f | [] | no_license | Nika-Keks/Calculator | fdd6163ce9f36f3339cee02783d28734b2d2d5d6 | d8a9d88fbbf3003a0256a0f24a949f31796f2c28 | refs/heads/master | 2023-01-22T11:08:26.861674 | 2020-11-22T23:15:22 | 2020-11-22T23:15:22 | 315,151,621 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 223 | cpp | #include <iostream>
#include "Calc/Calculator.h"
int main()
{
Calculator Calc;
std::string str;
std::cin >> str;
while (str != "#")
{
std::cout << Calc.calc(str) << std::endl;
std::cin >> str;
}
return 0;
}
| [
"as79020947761@gmail.com"
] | as79020947761@gmail.com |
a0843158d77de9c0401ede1da7f7b7ce9a233bec | 452dafe3f2c76d22a33098634016c1e323456a67 | /Problems/146A.cpp | c0054ddc9dc92d2cc168d328d64cbb27b7505d80 | [] | no_license | nikakogho/codeforces | 6c87b4d7b640808813e405d5ce6e129bd527f5df | b6261f5a83e221de190f6daec3ba932e45d1acca | refs/heads/master | 2023-03-21T19:34:58.401874 | 2021-03-06T15:49:16 | 2021-03-06T15:49:16 | 345,130,987 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 444 | cpp | #include <bits/stdc++.h>
using namespace std;
string solve()
{
int n;
string s;
cin >> n >> s;
int sum = 0;
for(int i = 0; i < n / 2; i++)
{
char c = s[i];
if(c == '4') sum += 4;
else if(c == '7') sum += 7;
else return "NO";
}
for(int i = n / 2; i < n; i++)
{
char c = s[i];
if(c == '4') sum -= 4;
else if(c == '7') sum -= 7;
else return "NO";
}
return sum == 0 ? "YES" : "NO";
}
int main()
{
cout << solve();
}
| [
"nikakoghuashvili@gmail.com"
] | nikakoghuashvili@gmail.com |
b95e93277432c47a1cd4c7ded0f5c0a6072593ba | f3511dd804b0d28790f70d7334dc8ae650dff32c | /689-div2/D.cpp | 15c53128e61bee4c558f0f7dd430a04861643866 | [] | no_license | iamdeepti/100DaysOfCode | 91c122f0f7f900c369a0ccbca87d59251b9d6e3a | 19f7ab2d4668308cffa31d43395471574e895f5e | refs/heads/master | 2023-03-06T06:34:39.938794 | 2021-01-31T06:20:53 | 2021-01-31T06:20:53 | 260,234,699 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,559 | cpp | #include <bits/stdc++.h>
using namespace std;
#define int long long int
#define ff first
#define ss second
#define pb push_back
#define vi vector <int>
#define pii pair <int, int>
#define loop(i,s,e) for(int i=s;i<e;i++)
#define rloop(i,e,s) for(int i=e;i>=s;i--)
#define mset(a,f) memset(a,f,sizeof(a))
#define endl "\n"
#define sz(x) ((int) x.size())
#define all(p) p.begin(), p.end()
#define print(a) for(auto x:a) cout<<x<<" "; cout<<endl
#define Print(a,s,e) for(int i=s; i<e; i++) cout<<a[i]<<" "; cout<<endl
#define bug(...) __f (#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1>
void __f (const char* name, Arg1&& arg1) { cout << name << " : " << arg1 << endl; }
template <typename Arg1, typename... Args>
void __f (const char* names, Arg1&& arg1, Args&&... args)
{
const char* comma = strchr (names + 1, ',');
cout.write (names, comma - names) << " : " << arg1 << " | "; __f (comma + 1, args...);
}
int n, q;
vi a, pre, sums;
vector<pii> queries;
void divide(int start,int end)
{
if(end<start) return;
sums.pb(pre[end+1]-pre[start]);
// if(start==end) return;
int val = (a[start]+a[end])/2;
int mid = upper_bound(a.begin()+start,a.begin()+end+1,val)-a.begin();
// bug(start,end,mid);
// bug(pre[end+1]-pre[start]);
if(mid-1==end || mid == start) return;
divide(start,mid-1);
divide(mid,end);
}
void solve()
{
cin>>n>>q;
a.clear(); a.resize(n);
pre.clear(); pre.resize(n+1); sums.clear();
loop(i,0,n)
{
cin>>a[i];
// pre[i+1] = pre[i]+a[i];
}
sort(all(a));
loop(i,0,n)
{
// cin>>a[i];
pre[i+1] = pre[i]+a[i];
}
queries.clear(); queries.resize(q);
loop(i,0,q)
{
cin>>queries[i].ff; queries[i].ss = i;
}
vector<string> res(q);
// print(a);
divide(0,n-1);
sort(all(sums));
loop(i,0,q)
{
if(binary_search(all(sums),queries[i].ff))
res[queries[i].ss]="YES";
else
{
res[queries[i].ss] = "NO";
}
}
// print(sums);
for(auto x:res)
{
cout<<x<<endl;
}
}
int32_t main()
{
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
//#ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
//#endif
int t = 1;
cin >> t;
while (t--) solve();
return 0;
}
| [
"iamdeepti956@gmail.com"
] | iamdeepti956@gmail.com |
2e469ac974cdbf4b09712c4fdc58e72c0e87db29 | 7cbb91cb0c9a2f0e53485a7a8e34775d5b272a98 | /rec01/rec01-start.cpp | 11869e306c652efcd90e67032f92548f4853cf8d | [] | no_license | andrebhu/cs2124 | 56f7423a5e8b54543de02023e4c9d069a2b1a53b | 97588f9450840ff4b87b35c98dee480b419adbc9 | refs/heads/main | 2023-08-30T10:08:33.714958 | 2021-10-21T17:18:27 | 2021-10-21T17:18:27 | 418,165,107 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,230 | cpp | // rec01-start.cpp
// 2124 21S
#include <iostream> // Tasks 3, 4, 5 and 6
#include <fstream> // Task 4, 5 and 6
#include <string> // Task 5
using namespace std;
int main() {
// Task 3
cout << "Task 3\n========\n";
// Put code for Task 3 here
cout << "Yay C++!!!" << endl;
// Task 4
cout << "Task 4\n========\n";
// Put code for Task 4 here
ifstream integers("integers.txt");
if (!integers){
cerr << "Could not open the file integers.txt\n";
exit(1);
}
int sum = 0;
int x;
while (integers >> x){
sum += x;
}
cout << sum << endl;
// Task 5
cout << "Task 5\n========\n";
// Put code for Task 5 here
ifstream text("text.txt");
if (!text){
cerr << "Could not open the file text.txt\n";
exit(1);
}
string word;
while (text >> word){
cout << word << endl;
}
// Task 6
cout << "Task 6\n========\n";
// Put code for Task 6 here
ifstream mixed("mixed.txt");
if (!mixed){
cerr << "Could not open the file mixed.txt\n";
exit(1);
}
sum = 0;
int y;
while (mixed >> y){
sum += y;
}
cout << sum << endl;
}
| [
"andrebhu@gmail.com"
] | andrebhu@gmail.com |
127d40d2d9f6a5a6fa46cffe40e17f7f31b7e841 | 792bf8e3600599453c72be903eeb84f1a532433d | /manager/SpellManager.h | 71e2da4a97f802ff065e9b8215d76f09d5719e73 | [] | no_license | Arktas/Ysthme | c5b11aedcec6d7560c648024f8a31fe13a53a791 | 36ca3dbb80abc5fe19452b8f55ea402b5b55ff98 | refs/heads/master | 2021-01-23T11:48:15.572687 | 2015-10-17T16:33:55 | 2015-10-17T16:33:55 | 26,853,601 | 0 | 1 | null | 2014-12-02T08:40:50 | 2014-11-19T09:16:56 | C++ | UTF-8 | C++ | false | false | 905 | h | #ifndef SPELL_MANAGER
#define SPELL_MANAGER
#include "../misc/util.h"
#include "../resource/Spell.h"
#include "../resource/Player.h"
#include "../resource/Monster.h"
#include "../printer/SpellPrinter.h"
class SpellManager
{
private:
float* ORIGIN_DIFF_X_DYNAMIC;
float* ORIGIN_DIFF_Y_DYNAMIC;
_MANAGER_Flags *flags;
std::list<Spell*> spellList;
Player* player;
std::list<Monster*> *monsterList;
Data *dataContainer;
SpellPrinter* spellPrinter;
Hitbox* _INST_hitbox;
public:
SpellManager(Hitbox* _INST_hitbox, Player* player,std::list<Monster*> *monsterlist,_MANAGER_Flags *flags,Data *dataContainer,float* ORIGIN_DIFF_X_DYNAMIC,float* ORIGIN_DIFF_Y_DYNAMIC);
~SpellManager();
void CheckEvent(sf::Event& event,sf::RenderWindow* window);
int rotation(int mX,int mY,int pX,int pY);
};
#endif
| [
"arktas@live.fr"
] | arktas@live.fr |
c8b0d68faea1fb8a4c637ebc1e1c3c789b7aea1b | 18005e5badf7da00b1fc99efb5287cbc4043d0bd | /src/build-qtenv-Desktop_Qt_5_9_1_MinGW_32bit-Debug/moc_comboselectiondialog.cpp | ec740412d0b05f4aba7c91f7c9227df6198d419b | [] | no_license | robinfoxnan/omnet_zh | 1e5b78d355a92c08f4c6218bb66b4fde6b510001 | 3b2aaccb11cbdc8687bf37ff4a3ee432fd6c3c5f | refs/heads/main | 2023-02-16T17:50:30.512206 | 2021-01-15T02:51:44 | 2021-01-15T02:51:44 | 324,327,531 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,064 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'comboselectiondialog.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.9.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../qtenv/comboselectiondialog.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'comboselectiondialog.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.9.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_omnetpp__qtenv__ComboSelectionDialog_t {
QByteArrayData data[1];
char stringdata0[37];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_omnetpp__qtenv__ComboSelectionDialog_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_omnetpp__qtenv__ComboSelectionDialog_t qt_meta_stringdata_omnetpp__qtenv__ComboSelectionDialog = {
{
QT_MOC_LITERAL(0, 0, 36) // "omnetpp::qtenv::ComboSelectio..."
},
"omnetpp::qtenv::ComboSelectionDialog"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_omnetpp__qtenv__ComboSelectionDialog[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
void omnetpp::qtenv::ComboSelectionDialog::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
const QMetaObject omnetpp::qtenv::ComboSelectionDialog::staticMetaObject = {
{ &QDialog::staticMetaObject, qt_meta_stringdata_omnetpp__qtenv__ComboSelectionDialog.data,
qt_meta_data_omnetpp__qtenv__ComboSelectionDialog, qt_static_metacall, nullptr, nullptr}
};
const QMetaObject *omnetpp::qtenv::ComboSelectionDialog::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *omnetpp::qtenv::ComboSelectionDialog::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_omnetpp__qtenv__ComboSelectionDialog.stringdata0))
return static_cast<void*>(const_cast< ComboSelectionDialog*>(this));
return QDialog::qt_metacast(_clname);
}
int omnetpp::qtenv::ComboSelectionDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QDialog::qt_metacall(_c, _id, _a);
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| [
"robin-fox@sohu.com"
] | robin-fox@sohu.com |
86c7d738b46611781e6aa0359d9293d97fab3ed4 | d53af215b3a729447f6dd5656d5acdbe81828892 | /examples_07.16.13/bright_future/grid.hpp | 909644e7d617b876894b678c6376b8379a72101c | [] | no_license | STEllAR-GROUP/hpx_historic | fac13be21e9ec389c8bec23708e0b020790fcc83 | d1d4f35cc40cab6c74054fbd95ab7c7a92b12032 | refs/heads/master | 2020-05-18T11:27:06.431872 | 2013-07-22T18:21:09 | 2013-07-22T18:21:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,173 | hpp | // Copyright (c) 2011 Thomas Heller
//
// 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 HPX_EXAMPLES_GRID_HPP
#define HPX_EXAMPLES_GRID_HPP
#ifdef OPENMP_GRID
#include <omp.h>
#else
#include <hpx/hpx.hpp>
#include <hpx/include/async.hpp>
#include <hpx/lcos/future_wait.hpp>
#endif
#include <vector>
#include <iostream>
#include <boost/config.hpp>
#include <boost/serialization/access.hpp>
#include <boost/assert.hpp>
#include <boost/move/move.hpp>
#if defined(BOOST_NO_VARIADIC_TEMPLATES)
#include <boost/preprocessor/dec.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/comma_if.hpp>
#include <boost/preprocessor/enum_params.hpp>
#include <boost/preprocessor/repeat.hpp>
#endif
#ifndef OPENMP_GRID
HPX_ALWAYS_EXPORT std::size_t
touch_mem(std::size_t, std::size_t, std::size_t, std::size_t);
HPX_DEFINE_PLAIN_ACTION(touch_mem, touch_mem_action);
#endif
#if !defined(BOOST_NOEXCEPT)
#define BOOST_NOEXCEPT
#endif
namespace bright_future
{
template <typename T>
struct numa_allocator;
template <>
struct numa_allocator<void>
{
typedef void * pointer;
typedef const void * const_pointer;
typedef void value_type;
template <typename U> struct rebind { typedef numa_allocator<U> other; };
};
template <typename T>
struct numa_allocator
{
typedef std::size_t size_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
std::size_t block_size;
template <typename U> struct rebind { typedef numa_allocator<U> other; };
numa_allocator() BOOST_NOEXCEPT {}
explicit numa_allocator(std::size_t b_size) BOOST_NOEXCEPT : block_size(b_size){}
numa_allocator(numa_allocator const & n) BOOST_NOEXCEPT : block_size(n.block_size) {}
template <typename U>
numa_allocator(numa_allocator<U> const & n) BOOST_NOEXCEPT : block_size(n.block_size) {}
~numa_allocator() {}
numa_allocator & operator=(numa_allocator const & n) BOOST_NOEXCEPT
{
block_size = n.block_size;
}
template <typename U>
numa_allocator & operator=(numa_allocator<U> const & n) BOOST_NOEXCEPT
{
block_size = n.block_size;
}
pointer allocate(size_type n, numa_allocator<void>::const_pointer locality_hint = 0)
{
size_type len = n * sizeof(value_type);
char *p = static_cast<char *>(std::malloc(len));
if(p == 0) throw std::bad_alloc();
#ifdef OPENMP_GRID
if(!omp_in_parallel())
{
#pragma omp parallel for schedule(static)
for(size_type i_block = 0; i_block < len; i_block += block_size)
{
size_type i_end = (std::min)(i_block + block_size, len);
for(size_type i = i_block; i < i_end; i += sizeof(value_type))
{
for(size_type j = 0; j < sizeof(value_type); ++j)
{
p[i+j] = 0;
}
}
}
}
#else
std::size_t const os_threads = hpx::get_os_thread_count();
hpx::naming::id_type const prefix = hpx::find_here();
std::size_t num_thread = 0;
std::set<std::size_t> attendance;
if(block_size == 0)
{
block_size = len / os_threads + 1;
}
for(size_type i_block = 0; i_block < len; i_block += block_size)
{
attendance.insert(num_thread);
num_thread = (num_thread+1) % os_threads;
}
while(!attendance.empty())
{
std::vector<hpx::lcos::future<std::size_t> > futures;
futures.reserve(attendance.size());
std::size_t start = 0;
BOOST_FOREACH(std::size_t os_thread, attendance)
{
futures.push_back(
hpx::async<touch_mem_action>(
prefix
, os_thread
, reinterpret_cast<std::size_t>(p)
, start
, (std::min)(start + block_size, len)
)
);
start += block_size;
}
hpx::lcos::wait(
futures
, [&](std::size_t, std::size_t t)
{if(std::size_t(-1) != t) attendance.erase(t); }
);
}
/*
std::size_t const os_threads = hpx::get_os_thread_count();
hpx::naming::id_type const prefix = hpx::find_here();
std::set<std::size_t> attendance;
for(std::size_t os_thread = 0; os_thread < os_threads; ++os_thread)
attendance.insert(os_thread);
std::size_t len_per_thread = len / os_threads + 1;
while(!attendance.empty())
{
std::vector<hpx::lcos::future<std::size_t> > futures;
futures.reserve(attendance.size());
BOOST_FOREACH(std::size_t os_thread, attendance)
{
futures.push_back(
hpx::async<touch_mem_action>(
prefix
, os_thread
, reinterpret_cast<std::size_t>(p)
, len_per_thread
, len
)
);
}
hpx::lcos::wait(
futures
, [&](std::size_t, std::size_t t)
{if(std::size_t(-1) != t) attendance.erase(t); }
);
}
*/
#endif
return reinterpret_cast<pointer>(p);
}
void deallocate(pointer p, size_type)
{
std::free(p);
}
size_type max_size() const BOOST_NOEXCEPT
{
return std::allocator<T>().max_size();
}
void construct(pointer p, const value_type& x)
{
new (p) value_type(x);
}
#if defined(BOOST_NO_VARIADIC_TEMPLATES)
#define HPX_GRID_FWD_ARGS(z, n, _) \
BOOST_PP_COMMA() BOOST_FWD_REF(BOOST_PP_CAT(A, n)) BOOST_PP_CAT(a, n) \
/**/
#define HPX_GRID_FORWARD_ARGS(z, n, _) \
BOOST_PP_COMMA_IF(n) \
boost::forward<BOOST_PP_CAT(A, n)>(BOOST_PP_CAT(a, n)) \
/**/
#define HPX_GRID_CONSTRUCT(z, n, _) \
template <typename U BOOST_PP_COMMA_IF(n) \
BOOST_PP_ENUM_PARAMS(n, typename A) > \
void construct(U* p BOOST_PP_REPEAT(n, HPX_GRID_FWD_ARGS, _)) \
{ \
new (p) U(BOOST_PP_REPEAT(n, HPX_GRID_FORWARD_ARGS, _)); \
} \
/**/
BOOST_PP_REPEAT(HPX_ACTION_ARGUMENT_LIMIT, HPX_GRID_CONSTRUCT, _)
#undef HPX_GRID_CONSTRUCT
#undef HPX_GRID_FORWARD_ARGS
#undef HPX_GRID_FWD_ARGS
#else
template <typename U, typename... Args>
void construct(U* p, BOOST_FWD_REF(Args)... args)
{
new (p) U(boost::forward<Args>(args)...);
}
#endif
template <typename U>
void destroy(U * p)
{
p->~U();
}
};
template <typename T1, typename T2>
bool operator==(const numa_allocator<T1>&, const numa_allocator<T2>&) BOOST_NOEXCEPT
{
return true;
}
template <typename T1, typename T2>
bool operator!=(const numa_allocator<T1>&, const numa_allocator<T2>&) BOOST_NOEXCEPT
{
return false;
}
template <typename T>
struct grid
{
typedef std::vector<T/*, numa_allocator<T>*/ > vector_type;
typedef typename vector_type::size_type size_type;
typedef typename vector_type::value_type value_type;
typedef typename vector_type::reference reference_type;
typedef typename vector_type::const_reference const_reference_type;
typedef typename vector_type::iterator iterator;
typedef typename vector_type::const_iterator const_iterator;
typedef value_type result_type;
grid()
{}
grid(size_type x_size, size_type y_size)
: n_x(x_size)
, n_y(y_size)
, data(x_size * y_size)
{}
grid(size_type x_size, size_type y_size, size_type /*block_size*/, T const & t)
: n_x(x_size)
, n_y(y_size)
, data(x_size * y_size, t/*, numa_allocator<T>(block_size)*/)
{}
grid(grid const & g)
: n_x(g.n_x)
, n_y(g.n_y)
, data(g.data)
{}
grid &operator=(grid const & g)
{
grid tmp(g);
std::swap(*this, tmp);
return *this;
}
template <typename F>
void init(F f)
{
for(size_type y_ = 0; y_ < n_y; ++y_)
{
for(size_type x_ = 0; x_ < n_x; ++x_)
{
(*this)(x_, y_) = f(x_, y_);
}
}
}
reference_type operator()(size_type x_, size_type y_)
{
BOOST_ASSERT(x_ < n_x);
BOOST_ASSERT(y_ < n_y);
return data[x_ + y_ * n_x];
}
const_reference_type operator()(size_type x_, size_type y_) const
{
BOOST_ASSERT(x_ < n_x);
BOOST_ASSERT(y_ < n_y);
return data[x_ + y_ * n_x];
}
reference_type operator[](size_type i)
{
return data[i];
}
const_reference_type operator[](size_type i) const
{
return data[i];
}
iterator begin()
{
return data.begin();
}
const_iterator begin() const
{
return data.begin();
}
iterator end()
{
return data.end();
}
const_iterator end() const
{
return data.end();
}
size_type size() const
{
return data.size();
}
size_type x() const
{
return n_x;
}
size_type y() const
{
return n_y;
}
vector_type const & data_handle() const
{
return data;
}
private:
size_type n_x;
size_type n_y;
vector_type data;
// serialization support
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int /*version*/)
{
ar & n_x & n_y & data;
}
};
template <typename T>
std::ostream & operator<<(std::ostream & os, grid<T> const & g)
{
typedef typename grid<T>::size_type size_type;
for(size_type y = 0; y < g.y(); ++y)
{
for(size_type x = 0; x < g.x(); ++x)
{
os << g(x, y) << " ";
}
os << "\n";
}
return os;
}
typedef std::pair<std::size_t, std::size_t> range_type;
inline void jacobi_kernel_simple(
std::vector<grid<double> > & u
, range_type const & x_range
, range_type const & y_range
, std::size_t old
, std::size_t new_
, std::size_t cache_block
)
{
grid<double> & u_new = u[new_];
grid<double> & u_old = u[old];
for(std::size_t y_block = y_range.first; y_block < y_range.second; y_block += cache_block)
{
std::size_t y_end = (std::min)(y_block + cache_block, y_range.second);
for(std::size_t x_block = x_range.first; x_block < x_range.second; x_block += cache_block)
{
std::size_t x_end = (std::min)(x_block + cache_block, x_range.second);
for(std::size_t y = y_block; y < y_end; ++y)
{
for(std::size_t x = x_block; x < x_end; ++x)
{
u_new(x, y)
=(
u_old(x+1,y) + u_old(x-1,y)
+ u_old(x,y+1) + u_old(x,y-1)
) * 0.25;
}
}
}
}
}
template <typename T>
inline T update(
grid<T> const & u
, grid<T> const & rhs
, typename grid<T>::size_type x
, typename grid<T>::size_type y
, T hx_sq
, T hy_sq
, T div
, T relaxation
)
{
return
u(x, y)
+ (
(
(
(u(x - 1, y) + u(x - 1, y)) / hx_sq
+ (u(x, y - 1) + u(x, y + 1)) / hy_sq
+ rhs(x, y)
)
/ div
)
- u(x, y)
)
* relaxation
;
}
template <typename T>
inline T update_residuum(
grid<T> const & u
, grid<T> const & rhs
, typename grid<T>::size_type x
, typename grid<T>::size_type y
, T hx_sq
, T hy_sq
, T k
)
{
return
rhs(x,y)
+ (u(x-1, y) + u(x+1, y) - 2.0 * u(x,y))/hx_sq
+ (u(x, y-1) + u(x, y+1) - 2.0 * u(x,y))/hy_sq
- (u(x, y) * k * k)
;
}
}
#endif
| [
"aserio@cct.lsu.edu"
] | aserio@cct.lsu.edu |
68e31c2e58f37c7bd151cda30ac8d758ab1e227c | 89df1ea7703a7d64ed2549027353b9f98b800e88 | /Game Engine/GameEngine/src/api/uniform_buffer.h | 9cc3632acb780456e45cc5e97a05a83fbc30ca00 | [
"MIT"
] | permissive | llGuy/gamedev | 31a3e23f921fbe38af48177710eb7bae661f4cfd | 16aa203934fd767926c58558e021630288556399 | refs/heads/master | 2021-05-04T15:09:33.217825 | 2019-01-17T23:15:36 | 2019-01-17T23:15:36 | 120,221,445 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 378 | h | #pragma once
#include "buffer.h"
class uniform_buffer : public buffer
{
public:
uniform_buffer(u32 index);
auto get_index(void) -> u32 &;
auto bind_base(GLenum binding_point) -> void;
private:
u32 index;
};
/* user defined block indices */
#define LIGHT_BLOCK_INDEX 0
#define MATERIAL_PROTOTYPE_BLOCK_INDEX 1
#define ANIMATION_BLOCK_INDEX 2
#define SHADOW_BLOCK_INDEX 3 | [
"luc.rosenzweig@yahoo.com"
] | luc.rosenzweig@yahoo.com |
0963561fcb62d8da1578332179bd8d0d6098f768 | 2192a47fe996c3364266c43ca850763b478b4d5e | /Module_01.7_TechnicalAssessmentPractice/Driver.h | bc5d0fbbe3b62269782420b38af184ce870ffc2e | [] | no_license | lorenarms/SNHU_CS_260_Practice_Projects | 9ab49376dc23cfe568d906bacb7c32f189fd4f28 | d3f8e94afbde25c68876842fcfd21dd296bc2dec | refs/heads/master | 2023-09-05T10:10:30.134210 | 2021-11-06T16:33:56 | 2021-11-06T16:33:56 | 402,142,088 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 34 | h | #pragma once
class Driver
{
};
| [
"lorenzo.joseph.dominguez@gmail.com"
] | lorenzo.joseph.dominguez@gmail.com |
f2056a32730dd8d2b88b973b794c497725eed741 | c79a3c378283f53656e146cbc210eddcbf9fafa6 | /Notes/week9_s2017/cpp-part.cpp | 0082861d85033918c0ac9a0f83b3c808cdb20195 | [] | no_license | xyhStruggler/COMS327 | 282c8e8101e00c802f0aa86dce8d68dd9839174d | e457fed80578283f6d8bd942e99f1093ddca1944 | refs/heads/master | 2021-05-01T14:01:43.714886 | 2017-09-24T23:39:14 | 2017-09-24T23:39:14 | 79,598,693 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 238 | cpp | #include <iostream>
#include "c-cpp-header.h"
void cpp_function(const char *s)
{
cout << s;
}
ostream *return_cout(void)
{
return &cout;
}
void use_cout(ostream *o)
{
*o << "Using the pointer that I got from C code!" << endl;
}
| [
"xyhstruggler@gmail.com"
] | xyhstruggler@gmail.com |
c29cdc1b76605282039de94a5241c9c5d45124cb | 089a0ddd07bd2198498555afd7a1173f7b260fab | /algorithm/997_Find_the_Town_Judge/solution.cpp | 76aa724c662b8990d05e2e916da86d6f2017f83e | [] | no_license | 23ksw10/LeetCode | de1570e044a7fc3e9a8a1709794927bfd10c50c6 | f6c78822cf19179131ac3bb1c6c667990508cbf7 | refs/heads/master | 2023-02-04T14:02:38.382321 | 2023-01-28T09:43:47 | 2023-01-28T09:43:47 | 238,220,666 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 347 | cpp | #include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int findJudge(int N, vector<vector<int>>& trust) {
vector<int>check(N + 1, 0);
for (auto &a : trust) {
check[a[1]]++;
check[a[0]]--;
}
int ans = -1;
for (int i = 0; i < N + 1; i++) {
if (check[i] == N - 1)ans = i;
}
return ans;
}
}; | [
"kimsw9603@gmail.com"
] | kimsw9603@gmail.com |
6b46fe5c1be4b07f361f05188dd535366d972dcc | 043624c5ff26c96a973c8ddc7ed4179f1a288ea1 | /codeforcescontests/stub/avl.cpp | fe683d92a1668cadfb13315fa9d92d8ccdf542e9 | [] | no_license | ThePiyushGupta/mycode | 91f44aed39d1115a41418933df5675d676e7c132 | 92bb21808ebda3adace22c2902ba549d2f7c8b7c | refs/heads/master | 2023-04-08T16:52:25.827836 | 2021-04-14T06:17:30 | 2021-04-14T06:17:30 | 156,000,787 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 431 | cpp | #include <iostream>
// #define nll std::NULL
class node {
public:
node *left, *right;
int data;
node(int n) : left(0), right(0),data(n) {
}
};
class avl{
public:
node * head;
avl(): head(0){
};
void insert(int n){
node* temp = new node(n);
if(!head) head = temp;
else{
node * curr = head;
if(n>curr->data)
while(curr)
}
}
}; | [
"piyushg1411@gmail.com"
] | piyushg1411@gmail.com |
762c4b91d86e36ab7c961d36574a5d653db6657b | 26e774ba4e1cc94fe0fcb9d0bc5e2ff2f7adcd04 | /PWGHF/hfe/AliAnalysisTaskFlowTPCEMCalRun2.h | 7141d63497667c4ca5038397a1599425efd55975 | [] | no_license | chills-ALICE/AliPhysics | 1447380c228276e2018aa305bb07aa5572a9d8a9 | 6368196a0fa0a0657e657d5b24ec308ba5fe0a1a | refs/heads/master | 2021-01-18T03:25:35.605274 | 2019-10-17T15:13:28 | 2019-10-17T16:00:49 | 85,835,517 | 0 | 0 | null | 2017-03-22T14:09:47 | 2017-03-22T14:09:47 | null | UTF-8 | C++ | false | false | 9,281 | h | /* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. */
/* See cxx source for full Copyright notice */
/* $Id$ */
#ifndef AliAnalysisTaskFlowTPCEMCalRun2_H
#define AliAnalysisTaskFlowTPCEMCalRun2_H
//#include "AliAnalysisTaskFlowVectorCorrections.h"
#include "AliAnalysisTaskSE.h"
#include "AliAODMCParticle.h"
#include "AliAODMCHeader.h"
#include "AliQnCorrectionsManager.h"
#include "AliRDHFCuts.h"
#include "AliAODEvent.h"
#include "AliHFQnVectorHandler.h"
#include "AliAnalysisVertexingHF.h"
#include <TString.h>
//class AliAODMCParticle;
//class AliAODMCHeader;
class AliAnalysisTaskFlowTPCEMCalRun2 : public AliAnalysisTaskSE
{
public:
enum EventPlaneMeth{kTPC,kTPCVZERO,kVZERO,kVZEROA,kVZEROC,kPosTPCVZERO,kNegTPCVZERO};//Event Plane to be calculated in the task
enum FlowMethod{kEP,kSP,kEvShapeEP,kEvShapeSP,kEPVsMass,kEvShapeEPVsMass};//Event Plane, Scalar Product or Event Shape Engeneering methods
enum EventPlaneDet{kNone=-1,kFullTPC,kPosTPC,kNegTPC,kFullV0,kV0A,kV0C};
enum q2Method{kq2TPC,kq2PosTPC,kq2NegTPC,kq2VZERO,kq2VZEROA,kq2VZEROC};
AliAnalysisTaskFlowTPCEMCalRun2();
//AliAnalysisTaskFlowTPCEMCalRun2(const char *name, AliRDHFCuts *rdCuts);
AliAnalysisTaskFlowTPCEMCalRun2(const char *name);
virtual ~AliAnalysisTaskFlowTPCEMCalRun2();
virtual void UserCreateOutputObjects();
virtual void UserExec(Option_t* option);
virtual void Terminate(Option_t* option);
void FindMother(AliAODMCParticle* part,int &label, int &pid, double &ptmom);
// void SetAODAnalysis() { SetBit(kAODanalysis, kTRUE); };
// void SetESDAnalysis() { SetBit(kAODanalysis, kFALSE); };
// Bool_t IsAODanalysis() const { return TestBit(kAODanalysis); };
void SetTenderTaskName(TString name) {fTenderTaskName = name;}
void SetHarmonic(int harmonic) {fHarmonic = harmonic;}
void SetCalibraionType(int calibtype) {fCalibType = calibtype;}
void SetNormMethod(int norm) {fNormMethod = norm;}
void SetOADBFileName(TString filename) {fOADBFileName = filename; cout << "++++++++++++ "<< filename << endl;}
void SetFlowMethod(int meth) {fFlowMethod = meth;}
void SetEventPlaneDetector(int det) {fEvPlaneDet = det;}
void SetSubEventDetectors(int detsubA, int detsubB) {fSubEvDetA = detsubA; fSubEvDetB = detsubB;}
void SetqnMethod(int qnmethod) {fqnMeth = qnmethod;}
void SetqnPercentileSelection(TString splinesfilepath) {fPercentileqn = true; fqnSplineFileName = splinesfilepath;}
void SetTPCHalvesEtaGap(double etagap = 0.2) {fEtaGapInTPCHalves=etagap;}
void GetTrkClsEtaPhiDiff(AliVTrack *t,AliVCluster *v,Double_t &phidiff, Double_t &etadiff);
//void SelectPhotonicElectron(Int_t itrack, AliVTrack *track, Bool_t &fFlagPhotonicElec, Double_t TrkPt, Double_t DCAxy, Int_t Bsign);
void SelectPhotonicElectron(Int_t itrack, AliAODTrack *track, Bool_t &fFlagPhotonicElec, Double_t TrkPt, Double_t DCAxy, Int_t Bsign, Double_t TrkPhiPI, Double_t PsinV0A);
void CheckMCgen(AliAODMCHeader* fMCheader,Double_t CutEta);
void SetDCA(Double_t xy, Double_t z){DCAxy = xy, DCAz = z;};
void SetPIDcuts(Double_t tpcnsig, Double_t emceop, Double_t emcss_mim, Double_t emcss_max){ftpcnsig = tpcnsig; femceop = emceop; femcss_mim = emcss_mim; femcss_max = emcss_max;};
void SetMasscuts(Double_t invmass, Double_t invmass_pt){finvmass = invmass; finvmass_pt = invmass_pt;};
void SetMinCentrality(float mincentr=30.) {fMinCentr = mincentr;}
void SetMaxCentrality(float maxcentr=50.) {fMaxCentr = maxcentr;}
//virtual void LocalInit();
Bool_t IsPdecay(int mpid);
Bool_t IsDdecay(int mpid);
Bool_t IsBdecay(int mpid);
private:
AliAODEvent* fAOD; //! input event
TList* fOutputList; //! output list
AliVEvent *fVevent; //!event object
AliPIDResponse *fpidResponse;
//Bool_t fUseTender;
double GetDeltaPsiSubInRange(double psi1, double psi2);
void GetMainQnVectorInfo(double &mainPsin, double &mainMultQn, double mainQn[2], double &SubAPsin, double &SubAMultQn, double SubAQn[2], double &SunBPsin, double &SubBMultQn, double SubBQn[2],AliHFQnVectorHandler* HFQnVectorHandler);
bool LoadSplinesForqnPercentile();
//cut parameter
Double_t DCAxy, DCAz;
Double_t ftpcnsig, femceop, femcss_mim, femcss_max;
Double_t finvmass, finvmass_pt;
Double_t massMin;
Int_t Nch;
// TClonesArray *fTracks_tender;//Tender tracks
TH1F* fHistPt; //! dummy histogram
TH1F* fNevents; //no of events
TH1F* fCent; //centrality
TH1F* fVtxZ; //!Vertex z
TH1F* fVtxX; //!Vertex x
TH1F* fVtxY; //!Vertex y
TH1F* fTrkPt;
TH1F* fTrkPtbef;
TH1F* fTrketa;
TH1F* fTrkphi;
TH1F* fTrketa2;
TH2F* fdEdx;
TH1F* fTrkP;
TH1F* fHistClustE;
TH2F* fEMCClsEtaPhi;
TH2F* fHistNoCells;
TH2F* fHistCalCell;
TH1F* fHistNCls;
TH1F* fHistNClsE1;
TH1F* fHistNClsE2;
TH1F* fHistNClsE3;
TH1F* fEMCTrkPt;
TH1F* fEMCTrketa;
TH1F* fEMCTrkphi;
TH2F* fClsEtaPhiAftMatch;
TH2F* fTPCnsig;
TH2F* fTOFnsig;
TH2F* fITSnsig;
TH2F* fTPCnsig_TOFnsig;
//TH3F* fTrkPt_TPCnsig_TOFnsig;
TH2F* fHistele_TOFcuts;
TH2F* fHisthad_TOFcuts;
TH1F* fHisteop;
TH2F* fM20;
TH2F* fM02;
TH2F* fHistNsigEop;
TH1F* fEMCTrkMatchPhi;
TH1F* fEMCTrkMatchEta;
TH2F* fHistelectron;
TH2F* fHisthadron;
TH1F* fInvmassLS;
TH1F* fInvmassULS;
TH2F* fInvmassLS_2D;
TH2F* fInvmassULS_2D;
TClonesArray *fTracks_tender;//Tender tracks
TClonesArray *fCaloClusters_tender;//Tender cluster
//=====MC output=======
AliAODMCParticle* fMCparticle;
TH1F* fMCcheckMother;
TClonesArray* fMCarray;
AliAODMCParticle* fMCTrackpart;
AliAODMCHeader* fMCheader;
TH1F* fCheckEtaMC;
TH2F* fHistMCorgPi0;
TH2F* fHistMCorgEta;
TH1F* fHistMCorgD;
TH1F* fHistMCorgB;
Int_t NpureMC;
Int_t NpureMCproc;
Int_t NembMCpi0;
Int_t NembMCeta;
TH2F* fPt_Btoe;
TH1F* fNDB;
TH1F* fHist_eff_HFE;
TH1F* fHist_eff_TPC;
TF1* fPi010;
TF1* fEta010;
TF1* fPi3050_0;
TF1* fPi3050_1;
TF1* fEta3050;
TH1F* fHistPhoReco0;
TH1F* fHistPhoReco1;
TH1F* fHistPhoReco2;
TH1F* fHistPhoPi0;
TH1F* fHistPhoPi01;
TH1F* fHistPhoEta;
TH1F* fHistPhoEta1;
TH1F* flPercentile;
//AliAnalysisTaskFlowVectorCorrections *flowQnVectorTask;
//AliQnCorrectionsManager* fFlowQnVectorMgr;
//TH1F* fmyEventPlane;
//TH1F* fmyEventPlane2;
//TH1F* fmyEventPlane3;
TH2F* fEPcorV0AC;
TH2F* fEPcorV0ATPC;
TH2F* fEPcorV0CTPC;
//TH1F* fTrkPhiEPFullTPC;
//TH1F* fTrkPhiEPFullV0;
//TH2F* fTrkPhiEPFullTPC_Pt;
TH2F* fTrkPhiEPV0A_Pt;
TH2F* fTrkPhiEPV0A_Pt_ele;
TH2F* fTrkPhiEPV0A_Pt_ele_lowpt;
//TH1F* fTrkPhiEP2;
//TH2F* fTrkPhiEP_Pt;
//TH2F* fTrkPhiEP2_Pt;
TH2F* fTrkPhicos2;
TH2F* fTrkPhisin2;
TH2F* fTrkPhicos2_elelow;
TH2F* fTrkPhisin2_elelow;
TH2F* fTrkPhicos2_elehigh;
TH2F* fTrkPhisin2_elehigh;
TH2F* fTrkPhicos2_hfehigh;
TH2F* fTrkPhisin2_hfehigh;
TH2F* fTrkPhicos2_hadhigh;
TH2F* fTrkPhisin2_hadhigh;
TH2F* fTrkPhicos2_phoLShigh;
TH2F* fTrkPhisin2_phoLShigh;
TH2F* fTrkPhicos2_phoULShigh;
TH2F* fTrkPhisin2_phoULShigh;
//TH1F* fInplane;
//TH1F* fOutplane;
TH1F* fInplane_ele;
TH1F* fOutplane_ele;
TH1F* fInplane_hfe;
TH1F* fOutplane_hfe;
TH1F* fInplane_LSpho;
TH1F* fOutplane_LSpho;
TH1F* fInplane_ULSpho;
TH1F* fOutplane_ULSpho;
TH2F* fDCAxy_Pt_ele;
TH2F* fDCAxy_Pt_had;
TH2F* fDCAxy_Pt_LS;
TH2F* fDCAxy_Pt_ULS;
TH2F* fsubV0ACcos2;
TH2F* fsubV0ATPCcos2;
TH2F* fsubV0CTPCcos2;
TH2F* fcorTrkPhicent_charge;
TH2F* fcorTrkPhicent_ele;
TH2F* fcorcentcos2_charge;
TH2F* fcorcentInplane;
TH2F* fcorcentOutplane;
//TH2F* fQx1;
//TH2F* fQy1;
//TH2F* fQx2;
//TH2F* fQy2;
//TH2F* fQx3;
//TH2F* fQy3;
TH1F* fHistEvPlane[6];
TH2F* fHistEvPlaneQncorr[6]; //histograms for EP angle vs. centrality
//TH3F* fHistEvPlaneQncorr[6]; //histograms for EP angle vs. centrality vs.qn
TH2F* fHistqnVsCentrPercCalib[6]; //histograms for qn percentile calibration with qn fine binning
TH2F* fHistEPResolVsCentrVsqn[3]; //histos needed to compute EP resolution vs. centrality vs. qn
//TH3F* fHistEPResolVsCentrVsqn[3]; //histos needed to compute EP resolution vs. centrality vs. qn
//AliRDHFCuts* fRDCuts;
TString fTenderTaskName; //name of tender task needed to get the calibrated Qn vectors
Int_t fHarmonic;
Int_t fCalibType;
Int_t fNormMethod;
TString fOADBFileName;
Int_t fFlowMethod;
Int_t fEvPlaneDet;
Int_t fSubEvDetA;
Int_t fSubEvDetB;
Int_t fqnMeth;
bool fPercentileqn;
TString fqnSplineFileName;
bool fLoadedSplines;
double fEtaGapInTPCHalves;
double fScalProdLimit;
float fMinCentr;
float fMaxCentr;
TList* fqnSplinesList[6];
THnSparse *fSparseElectron;//!Electron info
Double_t *fvalueElectron;//!Electron info
AliAnalysisTaskFlowTPCEMCalRun2(const AliAnalysisTaskFlowTPCEMCalRun2&); // not implemented
AliAnalysisTaskFlowTPCEMCalRun2& operator=(const AliAnalysisTaskFlowTPCEMCalRun2&); // not implemented
//ClassDef(AliAnalysisTaskFlowTPCEMCalRun2, 1);
ClassDef(AliAnalysisTaskFlowTPCEMCalRun2, 5);
};
#endif
| [
"shingo.sakai@cern.ch"
] | shingo.sakai@cern.ch |
88ede288f401787d299bc911d9cc539427e397b9 | ab2b10318b6203fa3366732362fc10be9da3e7c8 | /Demo-MNist/WndNeuronViewer.h | ce457cc7f406780a01024482a5bd78bc6e3c4061 | [] | no_license | zane-a-karl/Mila_OCR_Project_Spring_2016 | 37ceb177ec1a30a0d670f9414bb5cb9b56492df3 | ee36ef9b5ac17b39a019bc4370f15e764636cdf3 | refs/heads/master | 2021-06-24T10:00:57.009448 | 2017-08-13T00:26:30 | 2017-08-13T00:26:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,182 | h | #if !defined(AFX_WNDNEURONVIEWER_H__27EBD600_E125_472D_A8C0_0869EE1B3618__INCLUDED_)
#define AFX_WNDNEURONVIEWER_H__27EBD600_E125_472D_A8C0_0869EE1B3618__INCLUDED_
#include <vector>
using namespace std;
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// WndNeuronViewer.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CWndNeuronViewer window
class CWndNeuronViewer : public CWnd
{
// Construction
public:
CWndNeuronViewer();
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CWndNeuronViewer)
//}}AFX_VIRTUAL
// Implementation
public:
CBitmap m_bmDisplayedBitmap;
DWORD* m_pValues; // actually stores a gbr quad
int m_cRows;
int m_cCols;
int m_cPixels;
inline DWORD& At( DWORD* p, int row, int col ) // zero-based indices, starting at bottom-left
{ int location = row * m_cCols + col;
ASSERT( location>=0 && location<m_cPixels && row<m_cRows && row>=0 && col<m_cCols && col>=0 );
return p[ location ];
}
CWnd m_wndMagnifier;
virtual ~CWndNeuronViewer();
void BuildBitmapFromNeuronOutputs( std::vector< std::vector< double > >& neuronOutputs );
void DrawOutputBox( UINT left, UINT top, UINT clientWidth, UINT clientHeight, std::vector< double >::iterator& it );
void DrawOutputBox( UINT left, UINT top, UINT clientWidth, UINT clientHeight, DWORD* pArray, int count );
// Generated message map functions
protected:
//{{AFX_MSG(CWndNeuronViewer)
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnNcDestroy();
afx_msg void OnPaint();
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg LRESULT OnMouseLeave(WPARAM, LPARAM);
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_WNDNEURONVIEWER_H__27EBD600_E125_472D_A8C0_0869EE1B3618__INCLUDED_)
| [
"zanekarl17@g.ucla.edu"
] | zanekarl17@g.ucla.edu |
6b56b09fcf51bd10c714d280dbfb6ecf3c798b8a | 74f067ba1b9d22ca63204f4165b113fb7473c031 | /testing/scalability/test1/test.cpp | d271fa1c1c071d07706d4ee186dadc7c3859988b | [] | no_license | Guanwen-Wang/Stock-Exchange-Matching-System | b3ef8e1b6b0f3493cd881e47f2cae37e76e96a5b | 03437c93b3b3a592e0da251fde80934ac84ea25a | refs/heads/master | 2020-05-04T19:45:19.292362 | 2019-04-04T02:31:54 | 2019-04-04T02:31:54 | 179,406,754 | 1 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 2,787 | cpp | #include <arpa/inet.h>
#include <fcntl.h>
#include <fstream>
#include <iostream>
#include <netdb.h>
#include <netinet/in.h>
#include <pthread.h>
#include <sstream>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <thread>
#include <time.h>
#include <unistd.h>
/* the host name and port number, for debugging only */
/* may change if server executing in another machine */
#define SERVER_ADDR "vcm-9254.vm.duke.edu"
#define SERVER_PORT "12345"
// change MAX_THREAD to increase or decrease the number of queries sent
#define MAX_THREAD 1
#define BUFF_SIZE 10240
// set up the client and start sending message to server
void *handler(void *arg) {
char buffer[BUFF_SIZE];
int server_sfd;
int server_port_num;
int stat;
int len;
struct hostent *server_info;
struct addrinfo host_info;
struct addrinfo *host_info_list;
server_info = gethostbyname(SERVER_ADDR);
if (server_info == NULL) {
std::cerr << "host not found\n";
exit(1);
}
server_port_num = 12345; // atoi(SERVER_PORT);
memset(&host_info, 0, sizeof(host_info));
host_info.ai_family = AF_UNSPEC;
host_info.ai_socktype = SOCK_STREAM;
stat = getaddrinfo(SERVER_ADDR, SERVER_PORT, &host_info, &host_info_list);
// create socket
server_sfd = socket(host_info_list->ai_family, host_info_list->ai_socktype,
host_info_list->ai_protocol);
int yes = 1;
stat = setsockopt(server_sfd, SOL_SOCKET, SO_REUSEADDR, (char *)&yes,
sizeof(yes));
if (server_sfd < 0) {
perror("socket");
exit(server_sfd);
}
// connect to the server
stat =
connect(server_sfd, host_info_list->ai_addr, host_info_list->ai_addrlen);
if (stat < 0) {
perror("server connect");
exit(stat);
}
// XML request to be sent
char *temp = (char *)arg;
std::string file(temp);
std::ifstream fs(file);
std::string fcontent;
std::stringstream ss;
std::string req;
if (!fs.fail()) {
ss << fs.rdbuf();
try {
req = ss.str();
} catch (std::exception &e) {
std::cerr << "here... " << e.what() << std::endl;
}
}
long long xml_len = req.length();
std::string prefix = std::to_string(xml_len);
prefix += "\n";
req = prefix + req;
len = send(server_sfd, req.c_str(), req.length(), 0);
stat = recv(server_sfd, buffer, BUFF_SIZE, 0);
}
int main(int argc, char **argv) {
int threads[MAX_THREAD];
pthread_attr_t thread_attr[MAX_THREAD];
pthread_t thread_ids[MAX_THREAD];
for (int i = 0; i < MAX_THREAD; ++i) {
threads[i] = pthread_create(&thread_ids[i], NULL, handler, argv[1]);
usleep(1000);
}
for (int i = 0; i < MAX_THREAD; ++i) {
pthread_join(thread_ids[i], NULL);
}
return 0;
}
| [
"gary@Gary-Mac.local"
] | gary@Gary-Mac.local |
be2087c8f970f72fff88c07dfeecc4d0df981137 | 3d2ab6843ea534c8db6fe6ac42ef9e4761fdb6bf | /src/boost_deps/tools/quickbook/detail/actions.hpp | a4430c873d6c2d8a6e103fc826cdaac929088873 | [
"BSL-1.0"
] | permissive | ahmohamed/autodockr | f336640d7a2b5d439f6f115b1437c129e0ba44a0 | 6b7cf14add563886066eff2d9ae0e15ba58fdee1 | refs/heads/master | 2020-04-24T12:37:46.270962 | 2019-02-22T07:13:23 | 2019-02-22T07:13:23 | 171,961,418 | 1 | 1 | null | 2019-02-22T07:13:25 | 2019-02-21T23:30:49 | C++ | UTF-8 | C++ | false | false | 20,488 | hpp | /*=============================================================================
Copyright (c) 2002 2004 2006 Joel de Guzman
Copyright (c) 2004 Eric Niebler
http://spirit.sourceforge.net/
Use, modification and distribution is subject to 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)
=============================================================================*/
#if !defined(BOOST_SPIRIT_QUICKBOOK_ACTIONS_HPP)
#define BOOST_SPIRIT_QUICKBOOK_ACTIONS_HPP
#include <time.h>
#include <map>
#include <string>
#include <vector>
#include <stack>
#include <algorithm>
#include <boost/spirit/include/classic_iterator.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/foreach.hpp>
#include <boost/tuple/tuple.hpp>
#include "../syntax_highlight.hpp"
#include "./collector.hpp"
#include "./template_stack.hpp"
#include "./utils.hpp"
#ifdef BOOST_MSVC
// disable copy/assignment could not be generated, unreferenced formal params
#pragma warning (push)
#pragma warning(disable : 4511 4512 4100)
#endif
namespace quickbook
{
namespace fs = boost::filesystem;
typedef position_iterator<std::string::const_iterator> iterator;
typedef symbols<std::string> string_symbols;
typedef std::map<std::string, std::string> attribute_map;
struct actions;
extern tm* current_time; // the current time
extern tm* current_gm_time; // the current UTC time
extern bool debug_mode;
extern std::vector<std::string> include_path;
// forward declarations
struct actions;
int parse(char const* filein_, actions& actor, bool ignore_docinfo = false);
struct error_action
{
// Prints an error message to std::cerr
error_action(
int& error_count)
: error_count(error_count) {}
void operator()(iterator first, iterator /*last*/) const;
int& error_count;
};
struct phrase_action
{
// blurb, blockquote, preformatted, list_item,
// unordered_list, ordered_list
phrase_action(
collector& out,
collector& phrase,
std::string const& pre,
std::string const& post)
: out(out)
, phrase(phrase)
, pre(pre)
, post(post) {}
void operator()(iterator first, iterator last) const;
collector& out;
collector& phrase;
std::string pre;
std::string post;
};
struct header_action
{
// Handles paragraph, h1, h2, h3, h4, h5, h6,
header_action(
collector& out,
collector& phrase,
std::string const& library_id,
std::string const& section_id,
std::string const& qualified_section_id,
std::string const& pre,
std::string const& post)
: out(out)
, phrase(phrase)
, library_id(library_id)
, section_id(section_id)
, qualified_section_id(qualified_section_id)
, pre(pre)
, post(post) {}
void operator()(iterator first, iterator last) const;
collector& out;
collector& phrase;
std::string const& library_id;
std::string const& section_id;
std::string const& qualified_section_id;
std::string pre;
std::string post;
};
struct generic_header_action
{
// Handles h
generic_header_action(
collector& out,
collector& phrase,
std::string const& library_id,
std::string const& section_id,
std::string const& qualified_section_id,
int const& section_level)
: out(out)
, phrase(phrase)
, library_id(library_id)
, section_id(section_id)
, qualified_section_id(qualified_section_id)
, section_level(section_level) {}
void operator()(iterator first, iterator last) const;
collector& out;
collector& phrase;
std::string const& library_id;
std::string const& section_id;
std::string const& qualified_section_id;
int const& section_level;
};
struct simple_phrase_action
{
// Handles simple text formats
simple_phrase_action(
collector& out
, std::string const& pre
, std::string const& post
, string_symbols const& macro)
: out(out)
, pre(pre)
, post(post)
, macro(macro) {}
void operator()(iterator first, iterator last) const;
collector& out;
std::string pre;
std::string post;
string_symbols const& macro;
};
struct cond_phrase_action_pre
{
// Handles conditional phrases
cond_phrase_action_pre(
collector& out
, std::vector<bool>& conditions
, string_symbols const& macro)
: out(out)
, conditions(conditions)
, macro(macro) {}
void operator()(iterator first, iterator last) const;
collector& out;
std::vector<bool>& conditions;
string_symbols const& macro;
};
struct cond_phrase_action_post
{
// Handles conditional phrases
cond_phrase_action_post(
collector& out
, std::vector<bool>& conditions
, string_symbols const& macro)
: out(out)
, conditions(conditions)
, macro(macro) {}
void operator()(iterator first, iterator last) const;
collector& out;
std::vector<bool>& conditions;
string_symbols const& macro;
};
struct list_action
{
// Handles lists
typedef std::pair<char, int> mark_type;
list_action(
collector& out
, collector& list_buffer
, int& list_indent
, std::stack<mark_type>& list_marks)
: out(out)
, list_buffer(list_buffer)
, list_indent(list_indent)
, list_marks(list_marks) {}
void operator()(iterator first, iterator last) const;
collector& out;
collector& list_buffer;
int& list_indent;
std::stack<mark_type>& list_marks;
};
struct list_format_action
{
// Handles list formatting and hierarchy
typedef std::pair<char, int> mark_type;
list_format_action(
collector& out
, int& list_indent
, std::stack<mark_type>& list_marks
, int& error_count)
: out(out)
, list_indent(list_indent)
, list_marks(list_marks)
, error_count(error_count) {}
void operator()(iterator first, iterator last) const;
collector& out;
int& list_indent;
std::stack<mark_type>& list_marks;
int& error_count;
};
struct span
{
// Decorates c++ code fragments
span(char const* name, collector& out)
: name(name), out(out) {}
void operator()(iterator first, iterator last) const;
char const* name;
collector& out;
};
struct unexpected_char
{
// Handles unexpected chars in c++ syntax
unexpected_char(collector& out)
: out(out) {}
void operator()(iterator first, iterator last) const;
collector& out;
};
struct anchor_action
{
// Handles anchors
anchor_action(collector& out)
: out(out) {}
void operator()(iterator first, iterator last) const;
collector& out;
};
namespace
{
char const* quickbook_get_date = "__quickbook_get_date__";
char const* quickbook_get_time = "__quickbook_get_time__";
}
struct do_macro_action
{
// Handles macro substitutions
do_macro_action(collector& phrase)
: phrase(phrase) {}
void operator()(std::string const& str) const;
collector& phrase;
};
struct space
{
// Prints a space
space(collector& out)
: out(out) {}
void operator()(iterator first, iterator last) const;
void operator()(char ch) const;
collector& out;
};
struct pre_escape_back
{
// Escapes back from code to quickbook (Pre)
pre_escape_back(actions& escape_actions, std::string& save)
: escape_actions(escape_actions), save(save) {}
void operator()(iterator first, iterator last) const;
actions& escape_actions;
std::string& save;
};
struct post_escape_back
{
// Escapes back from code to quickbook (Post)
post_escape_back(collector& out, actions& escape_actions, std::string& save)
: out(out), escape_actions(escape_actions), save(save) {}
void operator()(iterator first, iterator last) const;
collector& out;
actions& escape_actions;
std::string& save;
};
struct raw_char_action
{
// Prints a single raw (unprocessed) char.
// Allows '<', '>'... etc.
raw_char_action(collector& phrase)
: phrase(phrase) {}
void operator()(char ch) const;
void operator()(iterator first, iterator /*last*/) const;
collector& phrase;
};
struct plain_char_action
{
// Prints a single plain char.
// Converts '<' to "<"... etc See utils.hpp
plain_char_action(collector& phrase)
: phrase(phrase) {}
void operator()(char ch) const;
void operator()(iterator first, iterator /*last*/) const;
collector& phrase;
};
struct attribute_action
{
// Handle image attributes
attribute_action(
attribute_map& attributes
, std::string& attribute_name)
: attributes(attributes)
, attribute_name(attribute_name) {}
void operator()(iterator first, iterator last) const;
attribute_map& attributes;
std::string& attribute_name;
};
struct image_action
{
// Handles inline images
image_action(
collector& phrase
, attribute_map& attributes
, std::string& image_fileref)
: phrase(phrase)
, attributes(attributes)
, image_fileref(image_fileref) {}
void operator()(iterator first, iterator last) const;
collector& phrase;
attribute_map& attributes;
std::string& image_fileref;
};
struct markup_action
{
// A generic markup action
markup_action(collector& phrase, std::string const& str)
: phrase(phrase), str(str) {}
template <typename T>
void operator()(T const&) const
{
phrase << str;
}
template <typename T>
void operator()(T const&, T const&) const
{
phrase << str;
}
collector& phrase;
std::string str;
};
typedef cpp_highlight<
span
, space
, string_symbols
, do_macro_action
, pre_escape_back
, post_escape_back
, actions
, unexpected_char
, collector>
cpp_p_type;
typedef python_highlight<
span
, space
, string_symbols
, do_macro_action
, pre_escape_back
, post_escape_back
, actions
, unexpected_char
, collector>
python_p_type;
typedef teletype_highlight<
plain_char_action
, string_symbols
, do_macro_action
, pre_escape_back
, post_escape_back
, actions
, collector>
teletype_p_type;
struct syntax_highlight
{
syntax_highlight(
collector& temp
, std::string const& source_mode
, string_symbols const& macro
, actions& escape_actions)
: temp(temp)
, source_mode(source_mode)
, cpp_p(temp, macro, do_macro_action(temp), escape_actions)
, python_p(temp, macro, do_macro_action(temp), escape_actions)
, teletype_p(temp, macro, do_macro_action(temp), escape_actions)
{
}
std::string operator()(iterator first, iterator last) const;
collector& temp;
std::string const& source_mode;
cpp_p_type cpp_p;
python_p_type python_p;
teletype_p_type teletype_p;
};
struct code_action
{
// Does the actual syntax highlighing of code
code_action(
collector& out
, collector& phrase
, syntax_highlight& syntax_p)
: out(out)
, phrase(phrase)
, syntax_p(syntax_p)
{
}
void operator()(iterator first, iterator last) const;
collector& out;
collector& phrase;
syntax_highlight& syntax_p;
};
struct inline_code_action
{
// Does the actual syntax highlighing of code inlined in text
inline_code_action(
collector& out
, syntax_highlight& syntax_p)
: out(out)
, syntax_p(syntax_p)
{}
void operator()(iterator first, iterator last) const;
collector& out;
syntax_highlight& syntax_p;
};
struct start_varlistitem_action
{
start_varlistitem_action(collector& phrase)
: phrase(phrase) {}
void operator()(char) const;
collector& phrase;
};
struct end_varlistitem_action
{
end_varlistitem_action(collector& phrase, collector& temp_para)
: phrase(phrase), temp_para(temp_para) {}
void operator()(char) const;
collector& phrase;
collector& temp_para;
};
struct break_action
{
// Handles line-breaks (DEPRECATED!!!)
break_action(collector& phrase)
: phrase(phrase) {}
void operator()(iterator f, iterator) const;
collector& phrase;
};
struct macro_identifier_action
{
// Handles macro identifiers
macro_identifier_action(quickbook::actions& actions)
: actions(actions) {}
void operator()(iterator first, iterator last) const;
quickbook::actions& actions;
};
struct macro_definition_action
{
// Handles macro definitions
macro_definition_action(quickbook::actions& actions)
: actions(actions) {}
void operator()(iterator first, iterator last) const;
quickbook::actions& actions;
};
struct template_body_action
{
// Handles template definitions
template_body_action(quickbook::actions& actions)
: actions(actions) {}
void operator()(iterator first, iterator last) const;
quickbook::actions& actions;
};
struct do_template_action
{
// Handles template substitutions
do_template_action(quickbook::actions& actions)
: actions(actions) {}
void operator()(iterator first, iterator last) const;
quickbook::actions& actions;
};
struct link_action
{
// Handles links (URL, XML refentry, function, class, member)
link_action(collector& phrase, char const* tag)
: phrase(phrase), tag(tag) {}
void operator()(iterator first, iterator last) const;
collector& phrase;
char const* tag;
};
struct variablelist_action
{
// Handles variable lists
variablelist_action(quickbook::actions& actions)
: actions(actions) {}
void operator()(iterator, iterator) const;
quickbook::actions& actions;
};
struct table_action
{
// Handles tables
table_action(quickbook::actions& actions)
: actions(actions) {}
void operator()(iterator, iterator) const;
quickbook::actions& actions;
};
struct start_row_action
{
// Handles table rows
start_row_action(collector& phrase, unsigned& span, std::string& header)
: phrase(phrase), span(span), header(header) {}
void operator()(char) const;
void operator()(iterator f, iterator) const;
collector& phrase;
unsigned& span;
std::string& header;
};
struct start_col_action
{
// Handles table columns
start_col_action(collector& phrase, unsigned& span)
: phrase(phrase), span(span) {}
void operator()(char) const;
collector& phrase;
unsigned& span;
};
struct end_col_action
{
end_col_action(collector& phrase, collector& temp_para)
: phrase(phrase), temp_para(temp_para) {}
void operator()(char) const;
collector& phrase;
collector& temp_para;
};
struct begin_section_action
{
// Handles begin page
begin_section_action(
collector& out
, collector& phrase
, std::string& library_id
, std::string& section_id
, int& section_level
, std::string& qualified_section_id
, std::string& element_id)
: out(out)
, phrase(phrase)
, library_id(library_id)
, section_id(section_id)
, section_level(section_level)
, qualified_section_id(qualified_section_id)
, element_id(element_id) {}
void operator()(iterator first, iterator last) const;
collector& out;
collector& phrase;
std::string& library_id;
std::string& section_id;
int& section_level;
std::string& qualified_section_id;
std::string& element_id;
};
struct end_section_action
{
end_section_action(
collector& out
, int& section_level
, std::string& qualified_section_id
, int& error_count)
: out(out)
, section_level(section_level)
, qualified_section_id(qualified_section_id)
, error_count(error_count) {}
void operator()(iterator first, iterator last) const;
collector& out;
int& section_level;
std::string& qualified_section_id;
int& error_count;
};
struct element_id_warning_action
{
void operator()(iterator first, iterator last) const;
};
struct xinclude_action
{
// Handles XML includes
xinclude_action(collector& out_, quickbook::actions& actions_)
: out(out_), actions(actions_) {}
void operator()(iterator first, iterator last) const;
collector& out;
quickbook::actions& actions;
};
struct include_action
{
// Handles QBK includes
include_action(quickbook::actions& actions_)
: actions(actions_) {}
void operator()(iterator first, iterator last) const;
quickbook::actions& actions;
};
struct import_action
{
// Handles import of source code files (e.g. *.cpp *.py)
import_action(collector& out_, quickbook::actions& actions_)
: out(out_), actions(actions_) {}
void operator()(iterator first, iterator last) const;
collector& out;
quickbook::actions& actions;
};
struct xml_author
{
// Handles xml author
xml_author(collector& out)
: out(out) {}
void operator()(std::pair<std::string, std::string> const& author) const;
collector& out;
};
struct xml_year
{
// Handles xml year
xml_year(collector& out)
: out(out) {}
void operator()(std::string const &year) const;
collector& out;
};
struct xml_copyright
{
// Handles xml copyright
xml_copyright(collector& out)
: out(out) {}
void operator()(std::pair<std::vector<std::string>, std::string> const ©right) const;
collector& out;
};
void pre(collector& out, quickbook::actions& actions, bool ignore_docinfo = false);
void post(collector& out, quickbook::actions& actions, bool ignore_docinfo = false);
struct phrase_to_string_action
{
phrase_to_string_action(std::string& out, collector& phrase)
: out(out) , phrase(phrase) {}
void operator()(iterator first, iterator last) const;
std::string& out;
collector& phrase;
};
}
#ifdef BOOST_MSVC
#pragma warning (pop)
#endif
#endif // BOOST_SPIRIT_QUICKBOOK_ACTIONS_HPP
| [
"mohamed@kuicr.kyoto-u.ac.jp"
] | mohamed@kuicr.kyoto-u.ac.jp |
5dfa04eafcbb4a8c236191b1502112bdddbcfce6 | 2c1c3ec98b878eb5a75fc15634c983c7c5aff9ac | /11 Char/main.cpp | 2096e80570d37c74552f8a689ee37a79d1ee9a52 | [] | no_license | Solcito25/CCOMP | 5e4a66b08d31eb4e7b7dd553be987a0202cd73d3 | a20061519fad0c095ffaf05e2f86f56aac802c8e | refs/heads/master | 2020-07-08T06:35:37.042322 | 2019-11-15T13:56:30 | 2019-11-15T13:56:30 | 203,594,438 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,221 | cpp | #include <iostream>
using namespace std;
int tam(char *cad){
int t=0;
while(*cad++ != '\0'){
t++;
}
return t;
}
int tam2(char *cad){
if(*cad=='\0')
return 0;
return 1+tam2(++cad);
}
void invertir(char *cad){
char *fin=cad+tam(cad)-1;
while(fin>cad){
swap(*cad,*fin);
cad++;
fin--;
}
}
void invertir2(char*cad,char*fin){
if (fin<cad)
return;
else{
swap(*cad,*fin);
return invertir2(++cad,--fin);
}
}
bool palindromo(char *cad, int i=0){
char *fin=cad+tam(cad)-1;
int ca=tam(cad);
while(fin>cad){
if (*fin == *cad){
i++;
}
cad++;
fin--;
}
if (i==ca/2)
return true;
return false;
}
bool palrecursivo(char*cad,char *fin){
if(fin<=cad)
return true;
if(*fin != *cad)
return false;
else
return true,palrecursivo(++cad,--fin);
}
int main()
{
char cadena[] ="hola";
char *fin=cadena+tam(cadena)-1;
//cout<<tam(cadena)<<endl;
//cout<<tam2(cadena)<<endl;
//cout<<cadena<<endl;
//invertir(cadena);
//cout<<cadena<<endl;
//cout<<" "<<endl;
//invertir2(cadena,fin);
//cout<<cadena<<endl;
cout<<boolalpha<<palrecursivo(cadena,fin)<<endl;
return 0;
}
| [
"ALUMNO-E@UCSP.AULAB"
] | ALUMNO-E@UCSP.AULAB |
34bb70c831e751bdc898ee850fea01748ecabc81 | 9c477cd0cf1a59ef4b374a45b0e08531f95f7e31 | /Solar System Game/QSMLProject/client.cpp | a9a510753641eb54174302125e2c39368c1aed55 | [] | no_license | 519984307/projects | 5f31e2b572b7d2b79a92b63e392cf9b5ee0a5a3b | a2fd17589778eb28c65f5892df479f51b6d3665c | refs/heads/master | 2023-03-17T14:27:58.938665 | 2018-02-24T04:25:57 | 2018-02-24T04:25:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,666 | cpp | #include "client.h"
#include <iostream>
#include <cstring>
#include "loginform.h"
#include <QDebug>
#include <sstream>
#include <QTimer>
#include <string>
Client::Client()
{
correctLogin = false;
correctRegister = false;
}
Client::~Client()
{
}
void Client::ClientConnect(QString typeOfLogin)
{
std::cout << "Starting Client" << std::endl;
status = clientSocket.connect("localhost", 72000);
sf::Packet outPacket;
std::string data;
const char *buffer;
if (typeOfLogin == "Login")
{
data = "Login: " + username.toStdString() + " " + password.toStdString() + "\n";
buffer = data.c_str();
outPacket << buffer;
}
else if (typeOfLogin == "Register")
{
data = "Register: " + username.toStdString() + " " + password.toStdString() + " " + firstName.toStdString() + " " + lastName.toStdString() + "\n";
buffer = data.c_str();
outPacket << buffer;
}
clientSocket.send(outPacket);
//check if it has sent then delete buffer
//recieves login information
ReceiveData();
}
void Client::GetUsername(QString name, QString pass)
{
username = name;
password = pass;
ClientConnect("Login");
}
void Client::RegisterUser(QString name, QString pass, QString first, QString last)
{
username = name;
password = pass;
firstName = first;
lastName = last;
ClientConnect("Register");
}
void Client::SaveLevel(int newLevel)
{
//std::string savedlevel = std::to_string(player.level);
std::string data = "ChangeLevel: " + QString::number(player.level).toStdString();
char *buffer = new char [data.length() + 1];
std::strcpy (buffer, data.c_str());
sf::Packet packet;
packet << buffer;
clientSocket.send(packet);
//if send is successful,
//delete buffer;
}
void Client::SaveQuizScore()
{
// //std::string savedlevel = std::to_string(player.level);
// int score = player.quizScores[player.level];
// std::string data = "QuizScore: " + std::to_string(score);
// char *buffer = new char [data.length() + 1];
// std::strcpy (buffer, data.c_str());
// sf::Packet packet;
// packet << buffer;
// clientSocket.send(packet);
// //if send is successful,
// //delete buffer;
}
void Client::ReceiveData()
{
sf::Packet packet;
clientSocket.receive(packet);
char *charData = new char [packet.getDataSize()];
if (packet >> charData)
{
std::string message (charData);
std::stringstream ss(message);
QList <std::string> messageList;
while (ss.good())
{
std::string msg;
ss >> msg;
messageList.push_back(msg);
}
//prints message just to check if it is right.
for(int i = 0; i < messageList.length(); i++)
{
std::cout << messageList[i] << std::endl;
}
if (messageList[0] == "LoginPlayer:")
{
player.username = messageList[1];
player.level = atoi(messageList[2].c_str());
//emit CorrectLoginSignal
correctLogin = true;
}
if (messageList[0] == "SuccessfulRegister:")
{
player.username = messageList[1];
player.level = 1;
//emit CorrectRegisterSignal
correctRegister = true;
}
if (messageList[0] == "IncorrectLogin:")
{
//emit IncorrectLoginSignal();
correctLogin = false;
}
if (messageList[0] == "UnsuccessfulRegister:")
{
//emit UnsuccessfulRegisterSignal();
correctRegister = false;
}
}
}
| [
"connerschacherer@gmail.com"
] | connerschacherer@gmail.com |
70000c410abeef46668d8d68b0390553eb938db2 | 215750938b1dd4354eab9b8581eec76881502afb | /src/fstb/util/ObservableMultiMixin.h | 79f7373ff566cf4f56ed40c52b2b9ffc20d9c01a | [
"WTFPL"
] | permissive | EleonoreMizo/pedalevite | c28fd19578506bce127b4f451c709914ff374189 | 3e324801e3a1c5f19a4f764176cc89e724055a2b | refs/heads/master | 2023-05-30T12:13:26.159826 | 2023-05-01T06:53:31 | 2023-05-01T06:53:31 | 77,694,808 | 103 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 2,725 | h | /*****************************************************************************
ObservableMultiMixin.h
Author: Laurent de Soras, 2016
--- Legal stuff ---
This program is free software. It comes without any warranty, to
the extent permitted by applicable law. You can redistribute it
and/or modify it under the terms of the Do What The Fuck You Want
To Public License, Version 2, as published by Sam Hocevar. See
http://sam.zoy.org/wtfpl/COPYING for more details.
*Tab=3***********************************************************************/
#pragma once
#if ! defined (fstb_util_ObservableMultiMixin_HEADER_INCLUDED)
#define fstb_util_ObservableMultiMixin_HEADER_INCLUDED
#if defined (_MSC_VER)
#pragma warning (4 : 4250)
#endif
/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
#include "fstb/util/ObservableInterface.h"
#include <vector>
namespace fstb
{
namespace util
{
class ObservableMultiMixin
: public virtual ObservableInterface
{
/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
public:
ObservableMultiMixin () = default;
ObservableMultiMixin (const ObservableMultiMixin &other) = default;
ObservableMultiMixin (ObservableMultiMixin &&other) = default;
~ObservableMultiMixin () = default;
ObservableMultiMixin &
operator = (const ObservableMultiMixin &other) = default;
/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
protected:
// ObservableInterface
void do_add_observer (ObserverInterface &observer) override;
void do_remove_observer (ObserverInterface &observer) override;
void do_notify_observers () override;
/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
private:
typedef std::vector <ObserverInterface *> ObserverList;
class NotificationFtor
{
public:
NotificationFtor (ObservableMultiMixin &subject);
void operator () (ObserverInterface *observer_ptr) const;
private:
ObservableMultiMixin &
_subject;
};
ObserverList _observer_list;
/*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
private:
ObservableMultiMixin &
operator = (ObservableMultiMixin &&other) = delete;
}; // class ObservableMultiMixin
} // namespace util
} // namespace fstb
//#include "fstb/util/ObservableMultiMixin.hpp"
#endif // fstb_util_ObservableMultiMixin_HEADER_INCLUDED
/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
| [
"fuck@fuck.fuck"
] | fuck@fuck.fuck |
07390f18c291cc60b91b84e2d156495c1ed9b48b | c59191babe8b6909eb12ac2bb1e7cfd3cd919e65 | /source/RenderTarget.cpp | 39de8176a6e2da72e8c99f7b27f15bb79f969d41 | [
"MIT"
] | permissive | xzrunner/painting2 | ab5667476ada3d0c9b40a7266ec650d7a8b21bf3 | c16e0133adf27a877b40b8fce642b5a42e043d09 | refs/heads/master | 2021-05-04T02:52:14.167266 | 2020-08-05T23:27:27 | 2020-08-05T23:27:27 | 120,367,182 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,177 | cpp | //#include "painting2/RenderTarget.h"
//
//#include <unirender/RenderContext.h>
//#include <unirender/Blackboard.h>
//#include <unirender/RenderTarget.h>
//#include <unirender/Texture.h>
//#include <stat/StatImages.h>
//
//namespace pt2
//{
//
//static const int IMG_ID = -2;
//
//RenderTarget::RenderTarget(int width, int height, bool has_depth)
//{
// auto& ur_rc = ur::Blackboard::Instance()->GetRenderContext();
// m_impl = new ur::RenderTarget(&ur_rc, width, height, has_depth);
//
// st::StatImages::Instance()->Add(IMG_ID, width, height, ur::TEXTURE_RGBA8);
//}
//
//RenderTarget::~RenderTarget()
//{
// st::StatImages::Instance()->Remove(IMG_ID, m_impl->Width(), m_impl->Height(), ur::TEXTURE_RGBA8);
//
// delete m_impl;
//}
//
//void RenderTarget::Bind()
//{
// m_impl->Bind();
//}
//
//void RenderTarget::Unbind()
//{
// m_impl->Unbind();
//}
//
//int RenderTarget::Width() const
//{
// return m_impl->Width();
//}
//
//int RenderTarget::Height() const
//{
// return m_impl->Height();
//}
//
//int RenderTarget::GetTexID() const
//{
// return m_impl->TexID();
//}
//
//void RenderTarget::Resize(int width, int height)
//{
// m_impl->Resize(width, height);
//}
//
//} | [
"xzrunner@gmail.com"
] | xzrunner@gmail.com |
b6e042f03f5e1dbaff3f7c5d55519e7e22d6394c | 6d7c8a5f8b4ac88cb4dc1b70330dc977d0f56587 | /Arduino Advance/LED_object/LEDBasic.cpp | 6eb30edfde04064f9579b580209000a4acb7faa2 | [
"Apache-2.0"
] | permissive | AlexParkSeoultech/Ardupilot_APM2.8_codes | 486ee3f1389e3a0140b4ea73c161c899860d8ace | 822a2c27e729c2e1f395231d1daac9eb2d949359 | refs/heads/master | 2020-07-28T04:36:00.785684 | 2019-09-20T05:45:40 | 2019-09-20T05:45:40 | 209,311,183 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 703 | cpp | #include "LEDBasic.h" //include the declaration for this class
//const byte LED_PIN = 13; //use the LED @ Arduino pin 13
LEDbasic::LEDbasic(int pin){ //<<constructor>>
LED_pin=pin;
pinMode(LED_pin, OUTPUT);
}
LEDbasic::~LEDbasic(){/*nothing to destruct*/} //<<destructor>>
void LEDbasic::on(){
digitalWrite(LED_pin,HIGH);
}
void LEDbasic::off(){//turn the LED off
digitalWrite(LED_pin,LOW);
}
void LEDbasic::flip(){//turn the LED off
digitalWrite(LED_pin,!digitalRead(LED_pin));
}
void LEDbasic::blink(int time){//blink the LED
on();
delay(time/2); //wait half of period
off();
delay(time/2);
}
| [
"noreply@github.com"
] | noreply@github.com |
8f0362c1a2147b6ad6964032091b81669f330c05 | 436c61a5ef9d35d14920bb7c48fb7aa5ab5a9ab7 | /kdtree.cpp | 2874f4a1f09b8cd1f37dee7baa1b8b7c8ade064e | [] | no_license | dszhengyu/Clever | 79341453fbfa52280aaeedc60528fc94d46b3bfc | 29ab349c7f2b8964f80c5300468ffd76509ecc90 | refs/heads/master | 2016-09-03T07:28:21.218389 | 2015-05-27T13:13:06 | 2015-05-27T13:13:06 | 35,722,687 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,774 | cpp | #include "kdtree.h"
KdTree::KdTree(distanceFuncType distanceFunction)
:tree(), distanceFunction(distanceFunction)
{
}
void KdTree::formTree(const Matrix &X, const Matrix &y)
{
vector<Matrix> trainSet = X.merge(y, 1).splictRow();
k = X.columnSize();
int curDepth = 0;
treePtr parentOfRoot(nullptr);
tree = createNode(trainSet, curDepth, parentOfRoot);
printTree();
}
Matrix KdTree::search(int neighbour, const Matrix &X)
{
Matrix predict(X.rowSize(), 1);
vector<Matrix> xVec(X.splictRow());
for (auto it = xVec.begin(); it != xVec.end(); ++it){
Matrix xSingle(*it);
stack<treePtr> path;
// 1. down to leaf, push node into path
treePtr curNode(tree);
while (curNode != nullptr) {
path.push(curNode);
int curSplit = curNode->split;
if (xSingle(0, curSplit) < curNode->data(0, curSplit)) {
curNode = curNode->left;
}
else {
curNode = curNode->right;
}
}
vector<treePtr> kNearestNeighbour;
//should be Inf
double longestInVec = 655536;
set<treePtr> nodeWalked;
// 2. start search, go back according to path, use set to record walked node,
// put node into vector, sort every time and pop last one, remember the longest
// in the vector
while (!path.empty()) {
curNode = path.top();
#ifdef DEBUG
cout << "debug" << endl;
cout << curNode->data << endl;
#endif
path.pop();
nodeWalked.insert(curNode);
// insert into vec
double curDistance = distanceFunction(curNode->data, xSingle);
if (kNearestNeighbour.size() < neighbour) {
kNearestNeighbour.push_back(curNode);
}
else if (curDistance < longestInVec) {
kNearestNeighbour[neighbour - 1] = curNode;
sort(kNearestNeighbour.begin(), kNearestNeighbour.end(),
[=](const treePtr &lhs, const treePtr &rhs)
{return (distanceFunction(lhs->data, xSingle) < distanceFunction(rhs->data, xSingle));});
longestInVec = distanceFunction(kNearestNeighbour[neighbour - 1]->data, xSingle);
}
int curSplit = curNode->split;
double hyperplaneDistance = abs(curNode->data(0,curSplit) - xSingle(0, curSplit));
if (hyperplaneDistance < longestInVec) {
if (curNode->left != nullptr && nodeWalked.find(curNode->left) == nodeWalked.end()) {
path.push(curNode->left);
}
if (curNode->right != nullptr && nodeWalked.find(curNode->right) == nodeWalked.end()) {
path.push(curNode->right);
}
}
}
// 3. calculate the predict label
vector<double> labelAll;
labelAll.reserve(kNearestNeighbour.size());
for (treePtr &node : kNearestNeighbour)
labelAll.push_back(node->label);
sort(labelAll.begin(), labelAll.end());
int numMax = 0;
double labelMax = labelAll[0];
int curNum = 0;
double curLabel = labelAll[0];
for (auto label : labelAll) {
if (label == curLabel) {
++curNum;
}
else {
if (curNum > numMax) {
numMax = curNum;
labelMax = curLabel;
}
curNum = 1;
curLabel = label;
}
}
if (curNum > numMax) {
labelMax = curLabel;
}
#ifdef DEBUG
for (auto label : labelAll)
cout << label << '\t';
cout << endl;
#endif
auto indexOfMatrix = it - xVec.begin();
predict(indexOfMatrix, 0) = labelMax;
}
return predict;
}
KdTree::treePtr KdTree::createNode(vector<Matrix> &trainSet, int curDepth, treePtr parent)
{
if (trainSet.size() <=0) {
return nullptr;
}
int split = curDepth % k;
treePtr node(new treeNode);
node->parent = parent;
node->split = split;
sort(trainSet.begin(), trainSet.end(), [split](Matrix &lhs, Matrix &rhs) {return lhs(0, split) < rhs(0, split);});
Matrix dataCur = trainSet[trainSet.size() / 2];
trainSet.erase(trainSet.begin() + trainSet.size() / 2);
vector<Matrix> leftSet(trainSet.begin(), trainSet.begin() + trainSet.size() / 2);
vector<Matrix> rightSet(trainSet.begin() + trainSet.size() / 2, trainSet.end());
node->data = dataCur.splice(0, dataCur.columnSize() - 1, 1);
node->label = dataCur(0, dataCur.columnSize() - 1);
int childDepth = curDepth + 1;
node->left = createNode(leftSet, childDepth, node);
node->right = createNode(rightSet, childDepth, node);
return node;
}
void KdTree::printTree(ostream & out) const
{
deque<treePtr> q1;
q1.push_back(tree);
deque<treePtr> q2;
while (!q1.empty() || !q2.empty()) {
if (!q1.empty()) {
for (treePtr node : q1) {
if (node->left != nullptr)
q2.push_back(node->left);
if (node->right != nullptr)
q2.push_back(node->right);
out << node->data;
}
out << endl;
q1.clear();
}
else {
for (treePtr node : q2) {
if (node->left != nullptr)
q1.push_back(node->left);
if (node->right != nullptr)
q1.push_back(node->right);
out << node->data;
}
out << endl;
q2.clear();
}
}
}
| [
"dszhengyu@qq.com"
] | dszhengyu@qq.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.