blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
438941a1ca9e473b072930f19efcfdd0f7b64f88
c1985888352044a0645210fe4ab5bb18870f673a
/20170712_strTest/20170712_strTest.cpp
aa4a63b3b8c20011aeb149a79c50a1ca320d6da3
[]
no_license
xzth/devTest
574b5bebcf719bf8f9e2d2aeca02dbc14614607e
2b72b4e1d5dd98a64440a41a4ccbdf90ececb664
refs/heads/master
2020-03-18T18:52:30.218747
2018-06-08T13:59:06
2018-06-08T13:59:06
135,120,073
0
0
null
null
null
null
UTF-8
C++
false
false
416
cpp
#include <iostream> #include <string.h> #include <memory.h> using namespace std; void print_str(char *str){ cout<<str<<endl; int N = strlen(str); for(int i=0;i<N;++i){ cout<<*(str+i)<<endl; cout<<char((*(str+i))|'0')<<endl; } } void flip(char &c, char act){ c = 48+((c-48)^(act-48)); } int main(){ char s[30]; cin>>s; print_str(s); char c = '1'; flip(c,'1'); cout<<c; }
[ "1419393745@qq.com" ]
1419393745@qq.com
83dc06e9219062070fb7bbdb700fa064be0ec738
cbf02ac524cb043b1a5ca40d1991a6cf9255d0e9
/VirtualCamera/jrtplibutil_jni.cpp
5d282d8a1bf9cc406d82c499a5a79f78c6d6da5f
[]
no_license
diaxia/android-virtualcamera
9564966e926d885e84bb00ee2982b1cca5380a9c
516020991b932b8a13a7c0f5b791e7eceda2b180
refs/heads/main
2023-07-14T06:59:04.170170
2021-08-23T07:57:26
2021-08-23T07:57:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,219
cpp
#include <jni.h> #include <android/native_window_jni.h> #include <stdlib.h> #include <stdio.h> #include <iostream> #include <string> #include <JRTPLIB/src/rtpipv4address.h> #include <JRTPLIB/src/rtptimeutilities.h> #include <JRTPLIB/src/rtpudpv4transmitter.h> #include <JRTPLIB/src/rtpsessionparams.h> #include <JRTPLIB/src/rtpsession.h> #include <JRTPLIB/src/rtppacket.h> #include <Common/thread/thread.h> #include <AnsyncDecoder/AnsyncDecoder.h> #include <display/display.h> #include "rtpsession.h" #include "rtpudpv4transmitter.h" #include "rtpipv4address.h" #include "rtpsessionparams.h" #include "rtperrors.h" #include "rtplibraryversion.h" #include "fflog.h" using namespace jrtplib; typedef struct stJrtplibClassInfo { JavaVM *jvm; jfieldID context; jmethodID postEventId; } JrtplibClassInfo; // This function checks if there was a RTP error. If so, it displays an error message and exists. #define CHECK_ERROR_JRTPLIB(status) \ if (status < 0) { \ LOGFE("ERROR: %s", jrtplib::RTPGetErrorString(status).c_str()); \ exit(-1);\ } int test1() { RTPSession sess; uint16_t portbase, destport; uint32_t destip; std::string ipstr; int status, i, num; LOGFD("Using version %s", RTPLibraryVersion::GetVersion().GetVersionString().c_str()); // First, we'll ask for the necessary information portbase = 6000; ipstr = "127.0.0.1"; destip = inet_addr(ipstr.c_str()); if (destip == INADDR_NONE) { LOGFE("Bad IP address specified"); return -1; } // The inet_addr function returns a value in network byte order, but // we need the IP address in host byte order, so we use a call to // ntohl destip = ntohl(destip); destport = 6000; num = 3; // Now, we'll create a RTP session, set the destination, send some packets and poll for incoming data. RTPUDPv4TransmissionParams transparams; RTPSessionParams sessparams; // IMPORTANT: The local timestamp unit MUST be set, otherwise RTCP Sender Report info will be calculated wrong // In this case, we'll be sending 10 samples each second, so we'll put the timestamp unit to (1.0/10.0) sessparams.SetOwnTimestampUnit(1.0 / 10.0); sessparams.SetAcceptOwnPackets(true); transparams.SetPortbase(portbase); status = sess.Create(sessparams, &transparams); CHECK_ERROR_JRTPLIB(status); RTPIPv4Address addr(destip, destport); status = sess.AddDestination(addr); CHECK_ERROR_JRTPLIB(status); status = sess.SendPacket((void *) "1234567890", 10, 0, false, 10); CHECK_ERROR_JRTPLIB(status); status = sess.SendPacket((void *) "1234567890", 10, 0, false, 10); CHECK_ERROR_JRTPLIB(status); for (i = 1; i <= num; i++) { // printf("Sending packet %d/%d\n", i, num); // send the packet // status = sess.SendPacket((void *) "1234567890", 10, 0, false, 10); // checkerror(status); // status = sess.SendPacket((void *) "1234567890", 10, 0, false, 10); // checkerror(status); sess.BeginDataAccess(); // check incoming packets if (sess.GotoFirstSourceWithData()) { do { RTPPacket *pack; while ((pack = sess.GetNextPacket()) != NULL) { // You can examine the data here printf("Got packet !\n"); // we don't longer need the packet, so we'll delete it sess.DeletePacket(pack); } } while (sess.GotoNextSourceWithData()); } sess.EndDataAccess(); #ifndef RTP_SUPPORT_THREAD status = sess.Poll(); checkerror(status); #endif // RTP_SUPPORT_THREAD RTPTime::Wait(RTPTime(1, 0)); } sess.BYEDestroy(RTPTime(10, 0), 0, 0); return 1; } int test2() { RTPSession session; RTPSessionParams sessionparams; sessionparams.SetOwnTimestampUnit(1.0 / 9000.0); sessionparams.SetAcceptOwnPackets(true); RTPUDPv4TransmissionParams transparams; transparams.SetPortbase(8000); int status = session.Create(sessionparams, &transparams); CHECK_ERROR_JRTPLIB(status); uint8_t localip[] = {127, 0, 0, 1}; RTPIPv4Address addr(localip, 8000); status = session.AddDestination(addr); CHECK_ERROR_JRTPLIB(status); session.SetDefaultPayloadType(96); session.SetDefaultMark(false); session.SetDefaultTimestampIncrement(160); uint8_t silencebuffer[16000]; for (int i = 0; i < 160; i++) { silencebuffer[i] = 128; } RTPTime delay(0.020); RTPTime starttime = RTPTime::CurrentTime(); status = session.SendPacketAfterSlice(silencebuffer, 2000, 96, true, 300); CHECK_ERROR_JRTPLIB(status); status = session.SendPacketAfterSlice(silencebuffer, 1000, 96, true, 300); CHECK_ERROR_JRTPLIB(status); bool done = false; while (!done) { session.BeginDataAccess(); if (session.GotoFirstSource()) { do { RTPPacket *packet; while ((packet = session.GetNextPacket()) != 0) { LOGFD("Got packet with extended sequence number %u from SSRC %u", packet->GetExtendedSequenceNumber(), packet->GetSSRC()); LOGFD("Got packet len = %zd playload len = %zd timestamp = %u", packet->GetPacketLength(), packet->GetPayloadLength(), packet->GetTimestamp()); session.DeletePacket(packet); } } while (session.GotoNextSource()); } session.EndDataAccess(); RTPTime::Wait(delay); RTPTime t = RTPTime::CurrentTime(); t -= starttime; if (t > RTPTime(10.0)) done = true; } delay = RTPTime(10.0); session.BYEDestroy(delay, "Time's up", 9); return 0; } int receiveVideoPacket(void *data, size_t *dataLen); int receiveAudioPacket(void *data, size_t *dataLen); RTPSession videoSession; RTPSession audioSession; uint8_t recvData[1024*1024]; size_t recvLen; uint8_t mediaType; Thread *recvThread; int recvQuit; AnsyncDecoder *decoder; GLDisplay *glDisplay; GLFrameData glFrameData; ANativeWindow *window = NULL; #define CLASS_NAME "com/forrest/jrtplib/JrtplibUtil" jobject gObj; JavaVM *jvm; jmethodID postEventId; static void java_callback_init(JNIEnv *env) { env->GetJavaVM(&jvm); jclass jcls = env->FindClass(CLASS_NAME); CHECK_NULL_ASSERT(jcls) // gClassInfo.context = (*env)->GetFieldID(env, jcls, "mNativeContext", "J"); // CHECK_NULL_ASSERT(gClassInfo.context) postEventId = env->GetMethodID(jcls, "postEventFromNative", "(I[BI)V"); CHECK_NULL_ASSERT(postEventId) } static void copyFrame(const uint8_t *src, uint8_t *dest, const int width, const int height, const int stride_src, const int stride_dest) { const int h8 = height % 8; for (int i = 0; i < h8; i++) { memcpy(dest, src, width); dest += stride_dest; src += stride_src; } for (int i = 0; i < height; i += 8) { memcpy(dest, src, width); dest += stride_dest; src += stride_src; memcpy(dest, src, width); dest += stride_dest; src += stride_src; memcpy(dest, src, width); dest += stride_dest; src += stride_src; memcpy(dest, src, width); dest += stride_dest; src += stride_src; memcpy(dest, src, width); dest += stride_dest; src += stride_src; memcpy(dest, src, width); dest += stride_dest; src += stride_src; memcpy(dest, src, width); dest += stride_dest; src += stride_src; memcpy(dest, src, width); dest += stride_dest; src += stride_src; } } // 直接将解码之后的RGB拷贝进surface, Android会自动调用SurfaceTexture.OnFrameAvailableListener static int directCopyToSurface(uint8_t *rgb, int w, int h, ANativeWindow *window) { int result = 0; if (window != NULL) { ANativeWindow_Buffer buffer; if (ANativeWindow_lock(window, &buffer, NULL) == 0) { if (buffer.stride == buffer.width) { //步长与宽度相等时,直接拷贝 memcpy(buffer.bits, rgb, (size_t) (w * h * 3)); } else { const uint8_t *src = rgb; const int src_w = w * 3; const int src_step = w * 3; uint8_t *dest = (uint8_t *)buffer.bits; const int dest_w = buffer.width * 3; const int dest_step = buffer.stride * 3; const int width = src_w < dest_w ? src_w : dest_w; const int height = h < buffer.height ? h : buffer.height; copyFrame(src, dest, width, height, src_step, dest_step); } ANativeWindow_unlockAndPost(window); } else { result = -1; } } else { result = -1; } return result; } static void decoder_cb(void *userdata, void *data, int dataLen, int w, int h, u32 timestamp, int mediaType) { if (mediaType == 1) { directCopyToSurface((uint8_t *)data, w, h, window); // memcpy(glFrameData.data, data, (size_t)w*h*3); // glFrameData.width = w; // glFrameData.height = h; // JNIEnv *env; // jvm->AttachCurrentThread(&env, NULL); // env->CallVoidMethod(gObj, postEventId, 1, NULL, 0); // jvm->DetachCurrentThread(); } else if (mediaType == 2) { JNIEnv *env; jvm->AttachCurrentThread(&env, NULL); jbyteArray audioArray = env->NewByteArray(dataLen); env->SetByteArrayRegion(audioArray, 0, dataLen, (jbyte *)data); env->CallVoidMethod(gObj, postEventId, 2, audioArray, dataLen); env->DeleteLocalRef(audioArray); jvm->DetachCurrentThread(); } } static void thread_recv_data(void *d) { recvQuit = 0; decoder = AnsyncDecoder_Create(NULL, 0, NULL, 0, NULL, decoder_cb); while (!recvQuit) { receiveAudioPacket(recvData, &recvLen); receiveVideoPacket(recvData, &recvLen); } AnsyncDecoder_Destroy(decoder); decoder = NULL; } int createMediaSession(const uint8_t *ip) { // 视频发送接收端口 RTPSessionParams sessionparams; sessionparams.SetOwnTimestampUnit(1.0 / 9000.0); sessionparams.SetAcceptOwnPackets(true); RTPUDPv4TransmissionParams transparams; transparams.SetPortbase(5000); int status = videoSession.Create(sessionparams, &transparams); CHECK_ERROR_JRTPLIB(status); // uint8_t localip[] = {ip[0], ip[1], ip[2], ip[3]}; RTPIPv4Address addr(localip, 5000); status = videoSession.AddDestination(addr); CHECK_ERROR_JRTPLIB(status); videoSession.SetDefaultPayloadType(96); videoSession.SetDefaultMark(false); videoSession.SetDefaultTimestampIncrement(0); // 音频发送接收端口 RTPSessionParams sessionparams2; sessionparams2.SetOwnTimestampUnit(1.0 / 9000.0); sessionparams2.SetAcceptOwnPackets(true); RTPUDPv4TransmissionParams transparams2; transparams2.SetPortbase(5100); status = audioSession.Create(sessionparams2, &transparams2); CHECK_ERROR_JRTPLIB(status); RTPIPv4Address addr2(localip, 5100); status = audioSession.AddDestination(addr2); CHECK_ERROR_JRTPLIB(status); audioSession.SetDefaultPayloadType(96); audioSession.SetDefaultMark(false); audioSession.SetDefaultTimestampIncrement(0); recvThread = Thread_Create(thread_recv_data, NULL); Thread_Run(recvThread); return 0; } int destroyMediaSession() { RTPTime delay = RTPTime(2.0); videoSession.BYEDestroy(delay, "stop rtp videoSession", strlen("stop rtp videoSession")); audioSession.BYEDestroy(delay, "stop rtp audioSession", strlen("stop rtp audioSession")); recvQuit = 1; Thread_Destroy(recvThread); if (glFrameData.data != NULL) { free(glFrameData.data); glFrameData.data = NULL; } return 0; } // type = 1 video; type = 2 audio int sendMediaPacket(const void *data, size_t len, int type) { if (type == 1) { videoSession.SendPacketAfterSlice(data, len, 96, true, 10); } else if (type == 2) { audioSession.SendPacket(data, len, 96, true, 10); } return 0; } int receiveVideoPacket(void *data, size_t *dataLen) { RTPTime delay(0.020); videoSession.BeginDataAccess(); if (videoSession.GotoFirstSource()) { do { RTPPacket *packet; while ((packet = videoSession.GetNextPacket()) != 0) { // LOGFD("Got packet with extended sequence number %u from SSRC %u", packet->GetExtendedSequenceNumber(), packet->GetSSRC()); // LOGFD("Got packet len = %zd playload len = %zd type(%u) timestamp = %u", // packet->GetPacketLength(), packet->GetPayloadLength(), packet->GetPayloadType(), packet->GetTimestamp()); uint8_t fu_indicator_type = packet->GetPayloadData()[0] & (uint8_t)0x1f; if (fu_indicator_type == 28) { // 分片包 FU_A uint8_t flag = packet->GetPayloadData()[1] & (uint8_t)0xC0; if (flag == 0x80) { memcpy((uint8_t *)data, packet->GetPayloadData() + 2, packet->GetPayloadLength() - 2 ); *dataLen = packet->GetPayloadLength() - 2; // LOGFD("切片RTP包开始 timestamp(%u)", packet->GetTimestamp()); } else if (flag == 0x40) { memcpy((uint8_t *)data + *dataLen, packet->GetPayloadData() + 2, packet->GetPayloadLength() - 2 ); *dataLen += packet->GetPayloadLength() - 2; // LOGFD("切片RTP包结束 dataLen(%d) timestamp(%u)", *dataLen, packet->GetTimestamp()); AnsyncDecoder_ReceiveData(decoder, data, (int)*dataLen, 0, 1); } else { memcpy((uint8_t *)data + *dataLen, packet->GetPayloadData() + 2, packet->GetPayloadLength() - 2 ); *dataLen += packet->GetPayloadLength() - 2; } } else { // 单个包 SPS:7 PPS:8 I:5 P:1 memcpy(data, packet->GetPayloadData(), packet->GetPayloadLength()); *dataLen = packet->GetPayloadLength(); AnsyncDecoder_ReceiveData(decoder, data, (int)*dataLen, 0, 1); // LOGFD("单个RTP包 dataLen(%d) timestamp = %u", *dataLen, packet->GetTimestamp()); } videoSession.DeletePacket(packet); } } while (videoSession.GotoNextSource()); } videoSession.EndDataAccess(); RTPTime::Wait(delay); return 0; } int receiveAudioPacket(void *data, size_t *dataLen) { RTPTime delay(0.020); audioSession.BeginDataAccess(); if (audioSession.GotoFirstSource()) { do { RTPPacket *packet; while ((packet = audioSession.GetNextPacket()) != 0) { // LOGFD("Got packet with extended sequence number %u from SSRC %u", packet->GetExtendedSequenceNumber(), packet->GetSSRC()); // LOGFD("Got packet len = %zd playload len = %zd type(%u) timestamp = %u", // packet->GetPacketLength(), packet->GetPayloadLength(), packet->GetPayloadType(), packet->GetTimestamp()); memcpy(data, packet->GetPayloadData(), packet->GetPayloadLength()); *dataLen = packet->GetPayloadLength(); AnsyncDecoder_ReceiveData(decoder, data, (int)*dataLen, 0, 2); // LOGFD("单个 Audio RTP包 dataLen(%d) timestamp = %u", *dataLen, packet->GetTimestamp()); audioSession.DeletePacket(packet); } } while (audioSession.GotoNextSource()); } audioSession.EndDataAccess(); RTPTime::Wait(delay); return 0; } extern "C" JNIEXPORT void JNICALL Java_com_forrest_jrtplib_JrtplibUtil_createSendSession(JNIEnv *env, jobject instance, jbyteArray ip_) { BEGIN gObj = env->NewGlobalRef(instance); java_callback_init(env); jbyte *ip = env->GetByteArrayElements(ip_, NULL); createMediaSession((const uint8_t *) ip); env->ReleaseByteArrayElements(ip_, ip, 0); END } extern "C" JNIEXPORT void JNICALL Java_com_forrest_jrtplib_JrtplibUtil_destroySendSession(JNIEnv *env, jobject instance) { BEGIN destroyMediaSession(); END } extern "C" JNIEXPORT void JNICALL Java_com_forrest_jrtplib_JrtplibUtil_sendData(JNIEnv *env, jobject instance, jbyteArray data_, jint dataLen, jint dataType) { jbyte *data = env->GetByteArrayElements(data_, NULL); sendMediaPacket(data, (size_t) dataLen, dataType); env->ReleaseByteArrayElements(data_, data, 0); } extern "C" JNIEXPORT void JNICALL Java_com_forrest_jrtplib_JrtplibUtil_receiveData(JNIEnv *env, jobject instance) { receiveVideoPacket(recvData, &recvLen); } extern "C" JNIEXPORT void JNICALL Java_com_forrest_jrtplib_JrtplibUtil_displayInit(JNIEnv *env, jobject instance) { glDisplay = display_init(); glFrameData.data = (unsigned char *)malloc(1280 * 720 * 3); memset(glFrameData.data, 0, 1280 * 720 * 3); glFrameData.width = 0; glFrameData.height = 0; } extern "C" JNIEXPORT void JNICALL Java_com_forrest_jrtplib_JrtplibUtil_displayDestroy(JNIEnv *env, jobject instance) { display_shutdown(glDisplay); glDisplay = NULL; free(glFrameData.data); glFrameData.data = NULL; } extern "C" JNIEXPORT void JNICALL Java_com_forrest_jrtplib_JrtplibUtil_displayDraw(JNIEnv *env, jobject instance, jint x, jint y, jint w, jint h) { display_draw(glDisplay, &glFrameData, x, y, w, h); } extern "C" JNIEXPORT void JNICALL Java_com_forrest_jrtplib_JrtplibUtil_setSurface(JNIEnv *env, jobject instance, jobject surface) { ANativeWindow *preview_window = surface ? ANativeWindow_fromSurface(env, surface) : NULL; window = preview_window; ANativeWindow_setBuffersGeometry(window, 1280, 720, AHARDWAREBUFFER_FORMAT_R8G8B8_UNORM); //WINDOW_FORMAT_RGBX_8888 } extern "C" JNIEXPORT void JNICALL Java_com_forrest_jrtplib_JrtplibUtil_releaseSurface(JNIEnv *env, jobject instance) { if (window) { ANativeWindow_release(window); window = NULL; } }
[ "pppaass@163.com" ]
pppaass@163.com
cca1c78a2d694cea397460cc873b12b794b21a56
3fc9e78daecdb2f2b4e2389f65ee469acda14bba
/src/utiltime.h
5220e704c28270e6d20273cf729388f779a8abdd
[ "MIT" ]
permissive
Test-Coin/bederlcore
1edf0c0610b5798799bfa4cec22412d71eff99e5
79c29c1c968593f71468fda267df9d9f44c6fb2d
refs/heads/master
2020-03-27T01:41:01.989484
2018-06-26T14:54:01
2018-06-26T14:54:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
706
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2016-2017 The PIVX developers // Copyright (c) 2017 The Bederl developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_UTILTIME_H #define BITCOIN_UTILTIME_H #include <stdint.h> #include <string> int64_t GetTime(); int64_t GetTimeMillis(); int64_t GetTimeMicros(); void SetMockTime(int64_t nMockTimeIn); void MilliSleep(int64_t n); std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime); std::string DurationToDHMS(int64_t nDurationTime); #endif // BITCOIN_UTILTIME_H
[ "root@localhost.localdomain" ]
root@localhost.localdomain
86a3b1d92534f94ce831a34aafa4782cb247611c
cfb726c545143b004b8263e61011c976b1da89a6
/include/RPCDetector.h
c17191a0f5143d01b295b20fc842143908f2e491
[ "CC0-1.0" ]
permissive
rehamMaly/GIF_OfflineAnalysis
faddb139f1da7be2cc349125fc419953f1cbce56
07c93bc75242829a9c51cf002f1c4e0d769da199
refs/heads/master
2022-04-05T16:19:58.034924
2020-02-03T15:39:07
2020-02-03T15:39:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,651
h
#ifndef __RPCDETECTOR_H_ #define __RPCDETECTOR_H_ //*************************************************************** // * GIF OFFLINE TOOL v7 // * // * Program developped to extract from the raw data files // * the rates, currents and DIP parameters. // * // * RPCDetector.h // * // * Class the defines RPC objects. RPCs are objects // * containing all the useful information about the // * detectors being tested inside of GIF++ needed to // * make the rate and current calculations. // * // * Developped by : Alexis Fagot & Salvador Carillo // * 22/06/2017 //*************************************************************** #include <string> #include <vector> #include "types.h" #include "IniFile.h" using namespace std; class RPC{ private: string name; //RPC name as in webDCS database Uint nGaps; //Number of gaps in the RPC Uint nPartitions; //Number of partitions in the RPC Uint nStrips; //Number of strips per partition vector<string> gaps; //List of gap labels (BOT, TOP, etc...) vector<float> gapGeo; //List of gap active areas vector<float> stripGeo; //List of strip active areas public: RPC(); RPC(string ID, IniFile* geofile); RPC(const RPC& other); ~RPC(); RPC& operator=(const RPC& other); string GetName(); Uint GetNGaps(); Uint GetNPartitions(); Uint GetNStrips(); string GetGap(Uint g); float GetGapGeo(Uint g); float GetStripGeo(Uint p); }; #endif
[ "alexis.fagot@ugent.be" ]
alexis.fagot@ugent.be
00f60153c616c255658c5f2e48da242d7b7a1d23
d4b733f2e00b5d0ab103ea0df6341648d95c993b
/src/c-cpp/lib/sst/catalog/bignum/numeric_limits.cpp
799f52fb438957cc836739b15150cc0641b06905
[ "MIT" ]
permissive
stealthsoftwareinc/sst
ad6117a3d5daf97d947862674336e6938c0bc699
f828f77db0ab27048b3204e10153ee8cfc1b2081
refs/heads/master
2023-04-06T15:21:14.371804
2023-03-24T08:30:48
2023-03-24T08:30:48
302,539,309
1
0
null
null
null
null
UTF-8
C++
false
false
2,913
cpp
// // Copyright (C) 2012-2023 Stealth Software Technologies, Inc. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice (including // the next paragraph) shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // // SPDX-License-Identifier: MIT // // Include first to test independence. #include <sst/catalog/bignum.hpp> // Include twice to test idempotence. #include <sst/catalog/bignum.hpp> // #include <sst/catalog/SST_WITH_OPENSSL_CRYPTO.h> #if SST_WITH_OPENSSL_CRYPTO #include <limits> namespace std { constexpr bool numeric_limits<sst::bignum>::is_specialized; constexpr int numeric_limits<sst::bignum>::digits; constexpr int numeric_limits<sst::bignum>::digits10; constexpr int numeric_limits<sst::bignum>::max_digits10; constexpr bool numeric_limits<sst::bignum>::is_signed; constexpr bool numeric_limits<sst::bignum>::is_integer; constexpr bool numeric_limits<sst::bignum>::is_exact; constexpr int numeric_limits<sst::bignum>::radix; constexpr int numeric_limits<sst::bignum>::min_exponent; constexpr int numeric_limits<sst::bignum>::min_exponent10; constexpr int numeric_limits<sst::bignum>::max_exponent; constexpr int numeric_limits<sst::bignum>::max_exponent10; constexpr bool numeric_limits<sst::bignum>::has_infinity; constexpr bool numeric_limits<sst::bignum>::has_quiet_NaN; constexpr bool numeric_limits<sst::bignum>::has_signaling_NaN; constexpr std::float_denorm_style numeric_limits<sst::bignum>::has_denorm; constexpr bool numeric_limits<sst::bignum>::has_denorm_loss; constexpr bool numeric_limits<sst::bignum>::is_iec559; constexpr bool numeric_limits<sst::bignum>::is_bounded; constexpr bool numeric_limits<sst::bignum>::is_modulo; constexpr bool numeric_limits<sst::bignum>::traps; constexpr bool numeric_limits<sst::bignum>::tinyness_before; constexpr std::float_round_style numeric_limits<sst::bignum>::round_style; } // namespace std #endif // #if SST_WITH_OPENSSL_CRYPTO
[ "sst@stealthsoftwareinc.com" ]
sst@stealthsoftwareinc.com
fb4d06856a78b416c943318e76fefcde3f4d1cb3
59fa0c736fddcb83fe9044447c01a02a32b181cf
/Buildings/Assets/StreetBloc/StreetCorner.hpp
2639937f3765e139baf705cfb2e2d6a38c273c47
[]
no_license
rodc87/CityBuilder
1b6fbdd4d453408a59160fb5047bb6e59c014492
68628cba594d272507793ffb0e1860825d588b6a
refs/heads/master
2021-05-13T13:28:40.546902
2018-01-08T19:33:29
2018-01-08T19:33:29
116,708,020
0
1
null
null
null
null
UTF-8
C++
false
false
441
hpp
#ifndef _STREETCORNER_ #define _STREETCORNER_ #include <AABB.hpp> #include <Plane.hpp> #include <Building.hpp> #include <Pavement.hpp> #include <Streetlight.hpp> #include <TrafficLight.hpp> #include "StreetBloc.hpp" /** @brief A Corner of a street. */ class StreetCorner : public StreetBloc { public : /** @brief Default contructor */ StreetCorner(); ~StreetCorner(); protected : void setBuiltIn(); }; #endif
[ "rodc87@gmail.com" ]
rodc87@gmail.com
682f10d25c5a470bb0f53a1452a00cf3b2642a49
f6e9d13b062fc56fc666e3d623c2930a31f6fc4a
/ArmV4l2Opencv/moc_administratorw.cpp
4a7891c60ce56a85c776a859bb0743c9bb28b9f7
[]
no_license
George-sudo/attendance-system
a2c31d80afa088d6e213e188cb6023a9ab22463c
81c0e407f5d6ae45c51e9a4f30e995ede5e54d54
refs/heads/master
2022-04-16T07:37:50.099073
2019-12-03T14:00:43
2019-12-03T14:00:43
225,753,854
3
0
null
null
null
null
UTF-8
C++
false
false
4,013
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'administratorw.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.7.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "administratorw.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'administratorw.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.7.0. 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 struct qt_meta_stringdata_AdministratorW_t { QByteArrayData data[6]; char stringdata0[94]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_AdministratorW_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_AdministratorW_t qt_meta_stringdata_AdministratorW = { { QT_MOC_LITERAL(0, 0, 14), // "AdministratorW" QT_MOC_LITERAL(1, 15, 16), // "on_retBt_clicked" QT_MOC_LITERAL(2, 32, 0), // "" QT_MOC_LITERAL(3, 33, 22), // "on_TakePhotoBt_clicked" QT_MOC_LITERAL(4, 56, 19), // "on_InIofoBt_clicked" QT_MOC_LITERAL(5, 76, 17) // "on_SureBt_clicked" }, "AdministratorW\0on_retBt_clicked\0\0" "on_TakePhotoBt_clicked\0on_InIofoBt_clicked\0" "on_SureBt_clicked" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_AdministratorW[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 4, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 34, 2, 0x08 /* Private */, 3, 0, 35, 2, 0x08 /* Private */, 4, 0, 36, 2, 0x08 /* Private */, 5, 0, 37, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, 0 // eod }; void AdministratorW::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { AdministratorW *_t = static_cast<AdministratorW *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->on_retBt_clicked(); break; case 1: _t->on_TakePhotoBt_clicked(); break; case 2: _t->on_InIofoBt_clicked(); break; case 3: _t->on_SureBt_clicked(); break; default: ; } } Q_UNUSED(_a); } const QMetaObject AdministratorW::staticMetaObject = { { &QMainWindow::staticMetaObject, qt_meta_stringdata_AdministratorW.data, qt_meta_data_AdministratorW, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *AdministratorW::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *AdministratorW::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_AdministratorW.stringdata0)) return static_cast<void*>(const_cast< AdministratorW*>(this)); return QMainWindow::qt_metacast(_clname); } int AdministratorW::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QMainWindow::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 4) qt_static_metacall(this, _c, _id, _a); _id -= 4; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 4) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 4; } return _id; } QT_END_MOC_NAMESPACE
[ "15915251934@163.com" ]
15915251934@163.com
d4507dcfbf7a9d9ae9aa961cb4bd0c4ad87238ed
d624540cecedf09ae2e3dcdf897840c457bd2393
/QMXMFunModule/Classes/XMFun/SDKBaseFile/JsonHeader/Common/SystemInfo.h
a097657902d4c182598205e5b45a2ff25097282f
[ "MIT" ]
permissive
joedrm/QMXMFunModule
06faa586bd7600140843f1323ceb10c10bb7e9c7
9dd9537051f2235884e988bdec023ee130475f34
refs/heads/master
2023-08-30T14:36:42.770860
2021-11-18T09:21:31
2021-11-18T09:21:31
346,965,940
1
0
null
null
null
null
UTF-8
C++
false
false
1,508
h
#pragma once #include "FunSDK/JObject.h" #define JK_SystemInfo "SystemInfo" class SystemInfo : public JObject //关于设备硬件软件版本信息等等设备信息头文件 { public: JIntObj AlarmInChannel; JIntObj AlarmOutChannel; JIntObj AudioInChannel; JStrObj BuildTime; JIntObj CombineSwitch; JIntHex DeviceRunTime; JIntObj DigChannel; JStrObj EncryptVersion; JIntObj ExtraChannel; JStrObj HardWare; JStrObj HardWareVersion; JStrObj SerialNo; JStrObj SoftWareVersion; JIntObj TalkInChannel; JIntObj TalkOutChannel; JStrObj UpdataTime; JIntHex UpdataType; JIntObj VideoInChannel; JIntObj VideoOutChannel; public: SystemInfo(JObject *pParent = NULL, const char *szName = JK_SystemInfo): JObject(pParent,szName), AlarmInChannel(this, "AlarmInChannel"), AlarmOutChannel(this, "AlarmOutChannel"), AudioInChannel(this, "AudioInChannel"), BuildTime(this, "BuildTime"), CombineSwitch(this, "CombineSwitch"), DeviceRunTime(this, "DeviceRunTime"), DigChannel(this, "DigChannel"), EncryptVersion(this, "EncryptVersion"), ExtraChannel(this, "ExtraChannel"), HardWare(this, "HardWare"), HardWareVersion(this, "HardWareVersion"), SerialNo(this, "SerialNo"), SoftWareVersion(this, "SoftWareVersion"), TalkInChannel(this, "TalkInChannel"), TalkOutChannel(this, "TalkOutChannel"), UpdataTime(this, "UpdataTime"), UpdataType(this, "UpdataType"), VideoInChannel(this, "VideoInChannel"), VideoOutChannel(this, "VideoOutChannel"){ }; ~SystemInfo(void){}; };
[ "wangfang@sengled.com" ]
wangfang@sengled.com
62a0cb6c08b7658cef9316b40f087ab3793e6e5e
a349dbf18493cd9bbb2bc9288671f2c981aa8233
/DP/Longest Palindrome in a String.cpp
3165a7b09771e15deb85cc0a2f90be12a8e4eaf7
[]
no_license
Ashish-kumar7/geeks-for-geeks-solutions
dd67fb596162d866a8043460f07e2052dc38446d
045dc4041323b4f912fcb50ae087eb5865fbacb3
refs/heads/master
2022-10-27T14:43:09.588551
2022-10-02T10:41:56
2022-10-02T10:41:56
228,147,267
38
50
null
2022-10-19T05:32:24
2019-12-15T07:40:36
C++
UTF-8
C++
false
false
1,200
cpp
#include<bits/stdc++.h> using namespace std; int main(){ int t; cin>>t; while(t--){ char str[101]; cin>>str; int n=strlen(str); int dp[n][n]={0}; for(int i=0;i<n;i++){ dp[i][i]=1; } int start=0,flag=0,maxLen=1; for(int i=0;i<n-1;i++){ if(str[i]==str[i+1]){ dp[i][i+1]=1; if(start==0 && flag==0){ start=i; flag=1; maxLen=2; } } } int len; for(len=3;len<=n;len++){ for(int i=0;i<n-len+1;i++){ int j=i+len-1; if(str[i]==str[j] && dp[i+1][j-1]){ if(maxLen<len){ start=i; maxLen=len; } dp[i][j]=1; } } } for(int i=0;i<maxLen;i++) cout<<str[i+start]; cout<<endl; } return 0; }
[ "ashishkumar357ak@gmail.com" ]
ashishkumar357ak@gmail.com
eb6d5ef838bc93302a7b77310b5722708a286e8a
b4bff7f61d078e3dddeb760e21174a781ed7f985
/Source/Contrib/UserInterface/src/UndoableEdit/OSGCommand.h
2b560f044e41711cf6ad9a9f33893c40bb3e328b
[]
no_license
Langkamp/OpenSGToolbox
8283edb6074dffba477c2c4d632e954c3c73f4e3
5a4230441e68f001cdf3e08e9f97f9c0f3c71015
refs/heads/master
2021-01-16T18:15:50.951223
2010-05-19T20:24:52
2010-05-19T20:24:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,098
h
/*---------------------------------------------------------------------------*\ * OpenSG ToolBox UserInterface * * * * * * * * * * Authors: David Kabala, Alden Peterson, Lee Zaniewski, Jonathan Flory * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * License * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Library General Public License as published * * by the Free Software Foundation, version 2. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * * \*---------------------------------------------------------------------------*/ #ifndef _OSGCOMMAND_H_ #define _OSGCOMMAND_H_ #ifdef __sgi #pragma once #endif #include "OSGConfig.h" #include "OSGContribUserInterfaceDef.h" #include <boost/shared_ptr.hpp> #include "OSGCommandType.h" #include "OSGCommandManagerFields.h" #include <string> OSG_BEGIN_NAMESPACE class Command; typedef boost::shared_ptr<Command> CommandPtr; class OSG_CONTRIBUSERINTERFACE_DLLMAPPING Command { /*========================= PUBLIC ===============================*/ protected: friend class CommandManager; typedef CommandPtr Ptr; typedef Command Self; Command(void); Command(const Command& source); void operator =(const Command& source); //This command should be overriden by sub-classes virtual void execute(void) = 0; public: //A human readable string that describes the command virtual std::string getCommandDescription(void) const = 0; virtual const CommandType &getType(void) const = 0; virtual ~Command(void); }; OSG_END_NAMESPACE #include "OSGCommand.inl" #endif /* _OSGCOMMAND_H_ */
[ "djkabala@gmail.com" ]
djkabala@gmail.com
f418f2a8e3b86372b430ccfc9e10b1a923b770d5
ea92a36b8e9b608f0fcbdc292f502e142818097d
/hitable.h
de0358beecacfc4dc01d94da83d63539f9acb5ba
[ "MIT" ]
permissive
Qinja/Raytracing
e1dcd0875369c052e41a74622d4904849ebc4e90
e46493e3d532ab42765b7d33611eb90e5182a3a7
refs/heads/master
2020-07-09T13:08:45.715358
2019-08-23T10:21:23
2019-08-23T10:21:23
203,976,272
0
0
null
null
null
null
UTF-8
C++
false
false
124
h
#pragma once #include "ray.h" class material; struct hit_record { float t; vec3 p; vec3 normal; material *mat_ptr; };
[ "wangqinjia19960407@qq.com" ]
wangqinjia19960407@qq.com
049e55d0d8ff4c6a81f9d2ded8ad2599e73dbeed
c258ecfc7fd11507da15e25bfcf5c6548c6f5874
/rishikD.cpp
27441afaca14265fc548ff0f09f5f5bea2a6be0a
[]
no_license
sagarsingla14/Codechef
724ae9b8563deed5cb6c8648cbc39603f0283c57
74384679a2eec984b2fbb762e0a8a8e8f60cc103
refs/heads/master
2021-07-13T17:17:34.026783
2020-09-27T14:07:27
2020-09-27T14:07:27
208,868,122
0
0
null
null
null
null
UTF-8
C++
false
false
1,869
cpp
#include <bits/stdc++.h> using namespace std; #define ll long long #define int long long #define ff first #define ss second #define pb push_back #define mp make_pair #define pii pair<int, int> #define vi vector<int> #define pqb priority_queue<int> #define pqs priority_queue<int, vi, greater<int>> #define setbits(x) __builtin_popcountll(x) #define zrobits(x) __builtin_ctzll(x) #define mod 1000000007 #define inf (int)(1e18) #define ps(x, y) fixed << setprecision(y) << x #define w(x) \ int x; \ cin >> x; \ while (x--) #define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end))) #define all(p) p.begin(), p.end() #define ub(a, b) upper_bound(all(a), b) #define lb(a, b) lower_bound(all(a), b) #define PI 3.14159265 mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); void run() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); } void solution() { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; i++) { cin >> a[i]; } int ans = 0; vector<int> c(23, 0); for (int i = 0; i < n; i++) { for (int j = 0; j < 23; j++) { if (a[i] & (1 << j)) { c[j]++; } } } for(ll i = 0 ; i < 23 ; i++) { cout << c[i] << " "; } cout << endl; while (1) { bool flag = false; int temp = 0; for (int i = 0; i < 23; i++) { if (c[i]) { c[i]--; flag = true; temp += (1 << i); } } ans += (temp * temp); if (flag == false) { break; } } cout << ans << endl; } int32_t main() { run(); solution(); return 0; }
[ "sagarrock1499@gmail.com" ]
sagarrock1499@gmail.com
9d4d42ce4451459f3f6f65a0f968427765189561
d4ec335ea5673eeac037d2306c9ff39efceeb237
/Source/MyGameEditor/Public/MyAnimGraphNode.h
c98d085d69de650557b7f352d4c3380f02fbd62e
[]
no_license
lazilywalk/UE4_AnimGraphNode_Project
dff0a64f098b97c46c1ecd3a95d67b5395cfdb4f
1d51893460ed0ac8d6c07a27f2af7b76194fa3f2
refs/heads/master
2020-04-28T08:20:47.556352
2019-03-12T03:03:10
2019-03-12T03:03:10
175,122,910
1
0
null
null
null
null
UTF-8
C++
false
false
815
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "AnimGraphNode_Base.h" #include "MyAnimNode.h" #include "MyAnimGraphNode.generated.h" /** * */ UCLASS() class MYGAMEEDITOR_API UMyAnimGraphNode : public UAnimGraphNode_Base { GENERATED_BODY() UPROPERTY(EditAnywhere, Category = Settings) FMyAnimNode Node; //~ Begin UEdGraphNode Interface. virtual FLinearColor GetNodeTitleColor() const override; virtual FText GetTooltipText() const override; virtual FText GetNodeTitle(ENodeTitleType::Type TitleType) const override; //~ End UEdGraphNode Interface. //~ Begin UAnimGraphNode_Base Interface virtual FString GetNodeCategory() const override; //~ End UAnimGraphNode_Base Interface UMyAnimGraphNode(const FObjectInitializer& ObjectInitializer); };
[ "lazilywalk@gmail.com" ]
lazilywalk@gmail.com
c791e753547d07c466644a8117739174b5958382
c51febc209233a9160f41913d895415704d2391f
/library/ATF/NPEXTLOGPEN.hpp
09d5743f71540ef52a538efc547ffc6c87a1c98e
[ "MIT" ]
permissive
roussukke/Yorozuya
81f81e5e759ecae02c793e65d6c3acc504091bc3
d9a44592b0714da1aebf492b64fdcb3fa072afe5
refs/heads/master
2023-07-08T03:23:00.584855
2023-06-29T08:20:25
2023-06-29T08:20:25
463,330,454
0
0
MIT
2022-02-24T23:15:01
2022-02-24T23:15:00
null
UTF-8
C++
false
false
257
hpp
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <tagEXTLOGPEN.hpp> START_ATF_NAMESPACE typedef tagEXTLOGPEN *NPEXTLOGPEN; END_ATF_NAMESPACE
[ "b1ll.cipher@yandex.ru" ]
b1ll.cipher@yandex.ru
58ef1d747eaee281749d6c8977ec4faf73347284
b7d40014fee00de6e51e49ede9edd438bbd78394
/Sequence Analysis/cpp/viterbikd.cpp
2ef6aebfab515a074ced7a319c9863c5ac82ac2e
[]
no_license
smeanapole/NanoporeCode
71fbb9bd0571130b12688a5af581187f44b82072
88c5c5d22e91843a066c5a8186de95537d4a0e60
refs/heads/master
2023-04-10T09:23:56.155434
2018-04-06T02:22:54
2018-04-06T02:22:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,553
cpp
/*========================================================== * * viterbikd.cpp * * Runs Viterbi algorithm on aligned sequences * * Arguments: levels array * *========================================================*/ #include "matrix.h" #include "mex.h" #include <stdint.h> #include <memory> #include <vector> #include <algorithm> #include <cmath> #include <iostream> #include <cstring> #include "viterbi.h" #include "EventData.h" using namespace std; /* The gateway function */ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { int nkeep = 0; double skip_prob = 0.05; double stay_prob = 0.01; double mut_min = 0.33; double mut_max = 0.75; // parse params if (nrhs > 1) { mxArray* arr; arr = mxGetField(prhs[1],0,"mutations"); if (arr) nkeep = mxGetScalar(arr); arr = mxGetField(prhs[1],0,"skip_prob"); if (arr) skip_prob = mxGetScalar(arr); arr = mxGetField(prhs[1],0,"stay_prob"); if (arr) stay_prob = mxGetScalar(arr); arr = mxGetField(prhs[1],0,"mut_min"); if (arr) mut_min = mxGetScalar(arr); arr = mxGetField(prhs[1],0,"mut_max"); if (arr) mut_max = mxGetScalar(arr); } // how many sequences? int n_seq = mxGetNumberOfElements(prhs[0]); vector<EventData> events; // contain the dynamically growing array of scores vector<VK_PTR> scores; // initialize all the events and models for (int i=0; i<n_seq; i++) events.push_back(EventData(prhs[0],i)); // so now all seqinds are at their first nonzero location // and refind is set to the first aligned reference state // let's make a blank, dummy initial likelihood scores.push_back(VK_PTR(new VK_LIK())); VK_PTR& lik0 = scores.back(); for (int i=0; i<N_STATES; i++) { lik0->liks[i] = 0; lik0->backptrs[i] = -1; lik0->fwdprobs[i] = 1.0/N_STATES; } cout << "Viterbi"; double* obs = new double[N_STATES*n_seq]; int refind = events[0].refstart; for (int i=0; i<n_seq; i++) refind = min(refind,events[i].refstart); // now loop through each level while (1) { // calculate log-normalized observations //double obs[N_STATES*n_seq]; memset(obs,0,N_STATES*sizeof(double)); int nlik = 0; for (int k=0; k<n_seq; k++) { vector<int> inds = events[k].getrefstates(refind); // does this strand have any states that line up with this ref state? if (inds.size() == 0) continue; nlik++; // now, average all these thingies, and stuff double lvl = 0; double sd = 0; for (int j=0; j<inds.size(); j++) { lvl += events[k].mean[inds[j]]; sd += events[k].stdv[inds[j]]; } lvl = lvl/inds.size(); sd = sd/inds.size(); for (int j=0; j<N_STATES; j++) obs[j*n_seq + nlik-1] = log(1/inf + events[k].model.getProb(lvl,sd,j)); } // how many align here? int nalhere = 0; for (int k=0; k<n_seq; k++) if (refind >= events[k].refstart && refind <= events[k].refend) nalhere++; // if too few aligned strands, skip over this state (or end, if done) if (nlik <= nalhere*0.2) { // stop, if no more strands if (nalhere == 0) break; // or just skip this one refind++; continue; } if (nlik > 1) { // sort obs likelihoods, ascendingally for (int j=0; j<N_STATES; j++) sort(obs+j*n_seq,obs+j*n_seq+nlik); // and then calculate means likelihood of the last few elements only int nskip = floor(nlik*0.25); if (nskip > nlik-2) nskip = 0; for (int j=0; j<N_STATES; j++) { double lik = 0.0; for (int k=nskip; k<nlik; k++) lik += obs[j*n_seq + k]; // now put it in the first column, this is shitty code // but again, suck it obs[j] = lik / (nlik - nskip); } } else { // nothing really to do for (int j=0; j<N_STATES; j++) obs[j] = obs[j*n_seq]; } // save a new likelihood double curskipprob = skip_prob;// + 0.3*(nalhere-nlik)/(double)n_seq; double curstayprob = stay_prob;// + 0.1*(nalhere-nlik)/(double)n_seq; scores.push_back(VK_PTR(new VK_LIK(scores.back(),obs,curskipprob,curstayprob))); // and advance refind++; if (refind%100 == 0) { mexPrintf("."); cout.flush(); } } delete[] obs; mexPrintf("\n"); cout.flush(); // now output the resulty thingy int n = scores.size() - 1; plhs[0] = mxCreateDoubleMatrix(n,1 + nkeep,mxREAL); double *pr = mxGetPr(plhs[0]); // run backtrace on main path // find largest final likelihood double* mlik = max_element(scores.back()->liks,scores.back()->liks+N_STATES); int curst = mlik - scores.back()->liks; for (int i=n-1; i>=0; i--) { // 1-based states pr[i] = curst + 1; curst = scores[i+1]->backptrs[curst]; } // and now for mutations (if needed) if (nkeep == 0) return; // create a transition matrix double* T = new double[N_STATES*N_STATES]; buildT(T, skip_prob, stay_prob); // now make sure transition matrix knows about stays properly for (int i=0; i<N_STATES; i++) T[i*(1+N_STATES)] = stay_prob; for (int k=0; k<nkeep; k++) { for (int i=n-1; i>=0; i--) { // 1-based states pr[i + (k+1)*n] = curst + 1; curst = scores[i+1]->randbp(curst,mut_min+(mut_max-mut_min)*k/(double)nkeep,T); } } delete[] T; }
[ "sjf11@case.edu" ]
sjf11@case.edu
d7df55fc1de5f04e3abd993a6ef737ba0b90358b
74252343a789ddf1b03eabcd5689979762d9a417
/ocelot-tracker-master/events.h
aa3feed74c829588bce16a695686cf7ed1000655
[ "WTFPL", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
3evils/u232.dev.site
6677c9c2f05472b4f36d9ec56a4b249a0c912733
a0457f5b5a3bc6b265ae0ff44f4034140c2bca3f
refs/heads/master
2022-04-11T14:19:38.146057
2020-02-09T20:46:43
2020-02-09T20:46:43
231,963,407
1
1
null
null
null
null
UTF-8
C++
false
false
2,484
h
#pragma once #include <iostream> #include <string> #include <cstring> // libev #include <ev++.h> // Sockets #include <sys/socket.h> #include <arpa/inet.h> #include <fcntl.h> #include <unistd.h> #include <netinet/in.h> #include <netdb.h> #include <sys/types.h> /* We have three classes - the mother, the middlemen, and the worker THE MOTHER The mother is called when a client opens a connection to the server. It creates a middleman for every new connection, which will be called when its socket is ready for reading. THE MIDDLEMEN Each middleman hang around until data is written to its socket. It then reads the data and sends it to the worker. When it gets the response, it gets called to write its data back to the client. THE WORKER The worker gets data from the middleman, and returns the response. It doesn't concern itself with silly things like sockets. see worker.h for the worker. */ // THE MOTHER - Spawns connection middlemen class connection_mother { private: int sock; worker * work; config * conf; mysql * db; ev::timer schedule_event; unsigned long opened_connections; unsigned int open_connections; public: connection_mother(worker * worker_obj, config * config_obj, mysql * db_obj); void increment_open_connections() { open_connections++; } void decrement_open_connections() { open_connections--; } int get_open_connections() { return open_connections; } int get_opened_connections() { return opened_connections; } void handle_connect(ev::io &watcher, int events_flags); ~connection_mother(); }; // THE MIDDLEMAN // Created by connection_mother // Add their own watchers to see when sockets become readable class connection_middleman { private: int connect_sock; ev::io read_event; ev::io write_event; ev::timer timeout_event; std::string response; config * conf; connection_mother * mother; worker * work; struct sockaddr_storage client_addr; public: connection_middleman(int &listen_socket, worker* work, connection_mother * mother_arg, config * config_obj); ~connection_middleman(); void handle_read(ev::io &watcher, int events_flags); void handle_write(ev::io &watcher, int events_flags); void handle_timeout(ev::timer &watcher, int events_flags); }; /* Get information about a host. */ struct addrinfo* getnetinfo(const char* host, int port, int proto); /* Get human-readable information out of a sockaddr. */ char *get_ip_str(struct sockaddr *sa, char *s, size_t maxlen);
[ "root@u-232.dev" ]
root@u-232.dev
8d6ed78b30a7390a9027d96720956252405428ec
a1fbf16243026331187b6df903ed4f69e5e8c110
/cs/sdk/3d_sdk/3dsmax/ver-6.0/samples/objects/cone.cpp
6e7e419095ede14e4e5c45f558b0bc7e7544163b
[ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ]
permissive
OpenXRay/xray-15
ca0031cf1893616e0c9795c670d5d9f57ca9beff
1390dfb08ed20997d7e8c95147ea8e8cb71f5e86
refs/heads/xd_dev
2023-07-17T23:42:14.693841
2021-09-01T23:25:34
2021-09-01T23:25:34
23,224,089
64
23
NOASSERTION
2019-04-03T17:50:18
2014-08-22T12:09:41
C++
UTF-8
C++
false
false
34,591
cpp
/********************************************************************** *< FILE: cone.cpp DESCRIPTION: Cone object CREATED BY: Rolf Berteig HISTORY: created November 11 1994 *> Copyright (c) 1994, All Rights Reserved. **********************************************************************/ #include "prim.h" #ifndef NO_OBJECT_STANDARD_PRIMITIVES #include "polyobj.h" #include "iparamm.h" #include "Simpobj.h" #include "surf_api.h" class ConeObject : public SimpleObject, public IParamArray { public: // Class vars static IParamMap *pmapCreate; static IParamMap *pmapTypeIn; static IParamMap *pmapParam; static IObjParam *ip; static int dlgSegments, dlgSides, dlgCapSegments; static int dlgCreateMeth; static int dlgSmooth; static Point3 crtPos; static float crtRadius1; static float crtRadius2; static float crtHeight; ConeObject(); // From Object int CanConvertToType(Class_ID obtype); Object* ConvertToType(TimeValue t, Class_ID obtype); Object* BuildPoly (TimeValue t); void GetCollapseTypes(Tab<Class_ID> &clist,Tab<TSTR*> &nlist); BOOL HasUVW(); void SetGenUVW(BOOL sw); BOOL IsParamSurface() {return TRUE;} Point3 GetSurfacePoint(TimeValue t, float u, float v,Interval &iv); // From BaseObject CreateMouseCallBack* GetCreateMouseCallBack(); void BeginEditParams( IObjParam *ip, ULONG flags,Animatable *prev); void EndEditParams( IObjParam *ip, ULONG flags,Animatable *next); TCHAR *GetObjectName() { return GetString(IDS_RB_CONE); } // Animatable methods void DeleteThis() { delete this; } Class_ID ClassID() { return Class_ID(CONE_CLASS_ID,0); } // From ref RefTargetHandle Clone(RemapDir& remap = NoRemap()); IOResult Load(ILoad *iload); // From IParamArray BOOL SetValue(int i, TimeValue t, int v); BOOL SetValue(int i, TimeValue t, float v); BOOL SetValue(int i, TimeValue t, Point3 &v); BOOL GetValue(int i, TimeValue t, int &v, Interval &ivalid); BOOL GetValue(int i, TimeValue t, float &v, Interval &ivalid); BOOL GetValue(int i, TimeValue t, Point3 &v, Interval &ivalid); // From SimpleObject void BuildMesh(TimeValue t); BOOL OKtoDisplay(TimeValue t); void InvalidateUI(); ParamDimension *GetParameterDim(int pbIndex); TSTR GetParameterName(int pbIndex); }; #define MIN_SEGMENTS 1 #define MAX_SEGMENTS 200 #define MIN_SIDES 3 #define MAX_SIDES 200 #define MIN_RADIUS float(0) #define MAX_RADIUS float( 1.0E30) #define MIN_HEIGHT float(-1.0E30) #define MAX_HEIGHT float( 1.0E30) #define MIN_PIESLICE float(-1.0E30) #define MAX_PIESLICE float( 1.0E30) #define DEF_SEGMENTS 5 #define DEF_SIDES 24 #define DEF_RADIUS float(0.0) #define DEF_HEIGHT float(0.01) #define SMOOTH_ON 1 #define SMOOTH_OFF 0 //--- ClassDescriptor and class vars --------------------------------- class ConeClassDesc:public ClassDesc { public: int IsPublic() { return 1; } void * Create(BOOL loading = FALSE) { return new ConeObject; } const TCHAR * ClassName() { return GetString(IDS_RB_CONE_CLASS); } SClass_ID SuperClassID() { return GEOMOBJECT_CLASS_ID; } Class_ID ClassID() { return Class_ID(CONE_CLASS_ID,0); } const TCHAR* Category() { return GetString(IDS_RB_PRIMITIVES); } void ResetClassParams(BOOL fileReset); }; static ConeClassDesc coneDesc; ClassDesc* GetConeDesc() { return &coneDesc; } // in prim.cpp - The dll instance handle extern HINSTANCE hInstance; // class variables for Cone class. IObjParam *ConeObject::ip = NULL; int ConeObject::dlgSegments = DEF_SEGMENTS; int ConeObject::dlgCapSegments = 1; int ConeObject::dlgSides = DEF_SIDES; int ConeObject::dlgCreateMeth = 1; // create_radius int ConeObject::dlgSmooth = SMOOTH_ON; IParamMap *ConeObject::pmapCreate = NULL; IParamMap *ConeObject::pmapTypeIn = NULL; IParamMap *ConeObject::pmapParam = NULL; Point3 ConeObject::crtPos = Point3(0,0,0); float ConeObject::crtRadius1 = 0.0f; float ConeObject::crtRadius2 = 0.0f; float ConeObject::crtHeight = 0.0f; void ConeClassDesc::ResetClassParams(BOOL fileReset) { ConeObject::dlgSegments = DEF_SEGMENTS; ConeObject::dlgCapSegments = 1; ConeObject::dlgSides = DEF_SIDES; ConeObject::dlgCreateMeth = 1; // create_radius ConeObject::dlgSmooth = SMOOTH_ON; ConeObject::crtRadius1 = 0.0f; ConeObject::crtRadius2 = 0.0f; ConeObject::crtHeight = 0.0f; ConeObject::crtPos = Point3(0,0,0); } //--- Parameter map/block descriptors ------------------------------- // Parameter map indices #define PB_RADIUS1 0 #define PB_RADIUS2 1 #define PB_HEIGHT 2 #define PB_SEGMENTS 3 #define PB_CAPSEGMENTS 4 #define PB_SIDES 5 #define PB_SMOOTH 6 #define PB_SLICEON 7 #define PB_PIESLICE1 8 #define PB_PIESLICE2 9 #define PB_GENUVS 10 // Non-parameter block indices #define PB_CREATEMETHOD 0 #define PB_TI_POS 1 #define PB_TI_RADIUS1 2 #define PB_TI_RADIUS2 3 #define PB_TI_HEIGHT 4 // // // Creation method static int createMethIDs[] = {IDC_CREATEDIAMETER,IDC_CREATERADIUS}; static ParamUIDesc descCreate[] = { // Diameter/radius ParamUIDesc(PB_CREATEMETHOD,TYPE_RADIO,createMethIDs,2) }; #define CREATEDESC_LENGH 1 // // // Type in static ParamUIDesc descTypeIn[] = { // Position ParamUIDesc( PB_TI_POS, EDITTYPE_UNIVERSE, IDC_TI_POSX,IDC_TI_POSXSPIN, IDC_TI_POSY,IDC_TI_POSYSPIN, IDC_TI_POSZ,IDC_TI_POSZSPIN, -99999999.0f,99999999.0f, SPIN_AUTOSCALE), // Radius 1 ParamUIDesc( PB_TI_RADIUS1, EDITTYPE_UNIVERSE, IDC_RADIUS1,IDC_RADSPINNER1, MIN_RADIUS,MAX_RADIUS, SPIN_AUTOSCALE), // Radius 2 ParamUIDesc( PB_TI_RADIUS2, EDITTYPE_UNIVERSE, IDC_RADIUS2,IDC_RADSPINNER2, MIN_RADIUS,MAX_RADIUS, SPIN_AUTOSCALE), // Height ParamUIDesc( PB_TI_HEIGHT, EDITTYPE_UNIVERSE, IDC_LENGTH,IDC_LENSPINNER, MIN_HEIGHT,MAX_HEIGHT, SPIN_AUTOSCALE) }; #define TYPEINDESC_LENGH 4 // // // Parameters static ParamUIDesc descParam[] = { // Radius 1 ParamUIDesc( PB_RADIUS1, EDITTYPE_UNIVERSE, IDC_RADIUS1,IDC_RADSPINNER1, MIN_RADIUS,MAX_RADIUS, SPIN_AUTOSCALE), // Radius 2 ParamUIDesc( PB_RADIUS2, EDITTYPE_UNIVERSE, IDC_RADIUS2,IDC_RADSPINNER2, MIN_RADIUS,MAX_RADIUS, SPIN_AUTOSCALE), // Height ParamUIDesc( PB_HEIGHT, EDITTYPE_UNIVERSE, IDC_LENGTH,IDC_LENSPINNER, MIN_HEIGHT,MAX_HEIGHT, SPIN_AUTOSCALE), // Circle Segments ParamUIDesc( PB_SEGMENTS, EDITTYPE_INT, IDC_SEGMENTS,IDC_SEGSPINNER, (float)MIN_SEGMENTS,(float)MAX_SEGMENTS, 0.1f), // Cap Segments ParamUIDesc( PB_CAPSEGMENTS, EDITTYPE_INT, IDC_CAPSEGMENTS,IDC_CAPSEGSPINNER, (float)MIN_SEGMENTS,(float)MAX_SEGMENTS, 0.1f), // Sides ParamUIDesc( PB_SIDES, EDITTYPE_INT, IDC_SIDES,IDC_SIDESPINNER, (float)MIN_SIDES,(float)MAX_SIDES, 0.1f), // Smooth ParamUIDesc(PB_SMOOTH,TYPE_SINGLECHEKBOX,IDC_OBSMOOTH), // Slice on ParamUIDesc(PB_SLICEON,TYPE_SINGLECHEKBOX,IDC_SLICEON), // Pie slice from ParamUIDesc( PB_PIESLICE1, EDITTYPE_FLOAT, IDC_PIESLICE1,IDC_PIESLICESPIN1, MIN_PIESLICE,MAX_PIESLICE, 0.5f, stdAngleDim), // Pie slice to ParamUIDesc( PB_PIESLICE2, EDITTYPE_FLOAT, IDC_PIESLICE2,IDC_PIESLICESPIN2, MIN_PIESLICE,MAX_PIESLICE, 0.5f, stdAngleDim), // Gen UVs ParamUIDesc(PB_GENUVS,TYPE_SINGLECHEKBOX,IDC_GENTEXTURE), }; #define PARAMDESC_LENGH 11 static ParamBlockDescID descVer0[] = { { TYPE_FLOAT, NULL, TRUE, 0 }, { TYPE_FLOAT, NULL, TRUE, 1 }, { TYPE_FLOAT, NULL, TRUE, 2 }, { TYPE_INT, NULL, TRUE, 3 }, { TYPE_INT, NULL, TRUE, 4 }, { TYPE_INT, NULL, TRUE, 5 }, { TYPE_INT, NULL, TRUE, 6 }, { TYPE_FLOAT, NULL, TRUE, 7 }, { TYPE_FLOAT, NULL, TRUE, 8 } }; static ParamBlockDescID descVer1[] = { { TYPE_FLOAT, NULL, TRUE, 0 }, { TYPE_FLOAT, NULL, TRUE, 1 }, { TYPE_FLOAT, NULL, TRUE, 2 }, { TYPE_INT, NULL, TRUE, 3 }, { TYPE_INT, NULL, TRUE, 9 }, { TYPE_INT, NULL, TRUE, 4 }, { TYPE_INT, NULL, TRUE, 5 }, { TYPE_INT, NULL, TRUE, 6 }, { TYPE_FLOAT, NULL, TRUE, 7 }, { TYPE_FLOAT, NULL, TRUE, 8 } }; static ParamBlockDescID descVer2[] = { { TYPE_FLOAT, NULL, TRUE, 0 }, { TYPE_FLOAT, NULL, TRUE, 1 }, { TYPE_FLOAT, NULL, TRUE, 2 }, { TYPE_INT, NULL, TRUE, 3 }, { TYPE_INT, NULL, TRUE, 9 }, { TYPE_INT, NULL, TRUE, 4 }, { TYPE_BOOL, NULL, TRUE, 5 }, { TYPE_INT, NULL, TRUE, 6 }, { TYPE_FLOAT, NULL, TRUE, 7 }, { TYPE_FLOAT, NULL, TRUE, 8 }, { TYPE_INT, NULL, FALSE, 10 } }; #define PBLOCK_LENGTH 11 // Array of old versions static ParamVersionDesc versions[] = { ParamVersionDesc(descVer0,9,0), ParamVersionDesc(descVer1,10,0), }; #define NUM_OLDVERSIONS 2 // Current version #define CURRENT_VERSION 2 static ParamVersionDesc curVersion(descVer2,PBLOCK_LENGTH,CURRENT_VERSION); //--- TypeInDlgProc -------------------------------- class ConeTypeInDlgProc : public ParamMapUserDlgProc { public: ConeObject *ob; ConeTypeInDlgProc(ConeObject *o) {ob=o;} BOOL DlgProc(TimeValue t,IParamMap *map,HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam); void DeleteThis() {delete this;} }; BOOL ConeTypeInDlgProc::DlgProc( TimeValue t,IParamMap *map,HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam) { switch (msg) { case WM_COMMAND: switch (LOWORD(wParam)) { case IDC_TI_CREATE: { if (ob->crtRadius1==0.0) return TRUE; // We only want to set the value if the object is // not in the scene. if (ob->TestAFlag(A_OBJ_CREATING)) { ob->pblock->SetValue(PB_RADIUS1,0,ob->crtRadius1); ob->pblock->SetValue(PB_RADIUS2,0,ob->crtRadius2); ob->pblock->SetValue(PB_HEIGHT,0,ob->crtHeight); } Matrix3 tm(1); tm.SetTrans(ob->crtPos); ob->suspendSnap = FALSE; ob->ip->NonMouseCreate(tm); // NOTE that calling NonMouseCreate will cause this // object to be deleted. DO NOT DO ANYTHING BUT RETURN. return TRUE; } } break; } return FALSE; } //--- ParamDlgProc -------------------------------- class ConeParamDlgProc : public ParamMapUserDlgProc { public: ConeObject *so; HWND thishWnd; ConeParamDlgProc(ConeObject *s) {so=s;thishWnd=NULL;} BOOL DlgProc(TimeValue t,IParamMap *map,HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam); void Update(TimeValue t); void DeleteThis() {delete this;} void TurnSpinner(HWND hWnd,int SpinNum,BOOL ison) { ISpinnerControl *spin2 = GetISpinner(GetDlgItem(hWnd,SpinNum)); if (ison) spin2->Enable();else spin2->Disable(); ReleaseISpinner(spin2); }; }; void ConeParamDlgProc::Update(TimeValue t) { if (!thishWnd) return; int ison; so->pblock->GetValue(PB_SLICEON,t,ison,FOREVER); TurnSpinner(thishWnd,IDC_PIESLICESPIN1,ison); TurnSpinner(thishWnd,IDC_PIESLICESPIN2,ison); EnableWindow(GetDlgItem(thishWnd,IDC_STATICFROM),ison); EnableWindow(GetDlgItem(thishWnd,IDC_STATICTO),ison); } BOOL ConeParamDlgProc::DlgProc( TimeValue t,IParamMap *map,HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam) { thishWnd=hWnd; switch (msg) { case WM_INITDIALOG: Update(t); break; case WM_COMMAND: switch (LOWORD(wParam)) { case IDC_SC_SLICEON: { int ison; so->pblock->GetValue(PB_SLICEON,t,ison,FOREVER); TurnSpinner(hWnd,IDC_PIESLICESPIN1,ison); TurnSpinner(hWnd,IDC_PIESLICESPIN2,ison); EnableWindow(GetDlgItem(hWnd,IDC_STATICFROM),ison); EnableWindow(GetDlgItem(hWnd,IDC_STATICTO),ison); return TRUE; } } break; } return FALSE; } //--- Cone methods ------------------------------- ConeObject::ConeObject() { MakeRefByID(FOREVER, 0, CreateParameterBlock(descVer2, PBLOCK_LENGTH, CURRENT_VERSION)); assert(pblock); pblock->SetValue(PB_SMOOTH,0,dlgSmooth); pblock->SetValue(PB_SEGMENTS,0,dlgSegments); pblock->SetValue(PB_CAPSEGMENTS,0,dlgCapSegments); pblock->SetValue(PB_SIDES,0,dlgSides); pblock->SetValue(PB_HEIGHT,0,crtHeight); pblock->SetValue(PB_RADIUS1,0,crtRadius1); pblock->SetValue(PB_RADIUS2,0,crtRadius2); pblock->SetValue(PB_GENUVS,0,TRUE); } IOResult ConeObject::Load(ILoad *iload) { iload->RegisterPostLoadCallback( new ParamBlockPLCB(versions,NUM_OLDVERSIONS,&curVersion,this,0)); return IO_OK; } void ConeObject::BeginEditParams(IObjParam *ip,ULONG flags,Animatable *prev) { SimpleObject::BeginEditParams(ip,flags,prev); this->ip = ip; if (pmapCreate && pmapParam) { // Left over from last Cone ceated pmapCreate->SetParamBlock(this); pmapTypeIn->SetParamBlock(this); pmapParam->SetParamBlock(pblock); } else { // Gotta make a new one. if (flags&BEGIN_EDIT_CREATE) { pmapCreate = CreateCPParamMap( descCreate,CREATEDESC_LENGH, this, ip, hInstance, MAKEINTRESOURCE(IDD_CONEPARAM1), GetString(IDS_RB_CREATIONMETHOD), 0); pmapTypeIn = CreateCPParamMap( descTypeIn,TYPEINDESC_LENGH, this, ip, hInstance, MAKEINTRESOURCE(IDD_CONEPARAM3), GetString(IDS_RB_KEYBOARDENTRY), APPENDROLL_CLOSED); } pmapParam = CreateCPParamMap( descParam,PARAMDESC_LENGH, pblock, ip, hInstance, MAKEINTRESOURCE(IDD_CONEPARAM2), GetString(IDS_RB_PARAMETERS), 0); } if(pmapTypeIn) { // A callback for the type in. pmapTypeIn->SetUserDlgProc(new ConeTypeInDlgProc(this)); } if(pmapParam) { // A callback for the type in. pmapParam->SetUserDlgProc(new ConeParamDlgProc(this)); } } void ConeObject::EndEditParams( IObjParam *ip, ULONG flags,Animatable *next ) { SimpleObject::EndEditParams(ip,flags,next); this->ip = NULL; if (flags&END_EDIT_REMOVEUI ) { if (pmapCreate) DestroyCPParamMap(pmapCreate); if (pmapTypeIn) DestroyCPParamMap(pmapTypeIn); DestroyCPParamMap(pmapParam); pmapParam = NULL; pmapTypeIn = NULL; pmapCreate = NULL; } // Save these values in class variables so the next object created will inherit them. pblock->GetValue(PB_SIDES,ip->GetTime(),dlgSides,FOREVER); pblock->GetValue(PB_SEGMENTS,ip->GetTime(),dlgSegments,FOREVER); pblock->GetValue(PB_CAPSEGMENTS,ip->GetTime(),dlgCapSegments,FOREVER); pblock->GetValue(PB_SMOOTH,ip->GetTime(),dlgSmooth,FOREVER); } // In cyl.cpp extern void BuildCylinderMesh(Mesh &mesh, int segs, int smooth, int llsegs, int capsegs, int doPie, float radius1, float radius2, float height, float pie1, float pie2, int genUVs); extern void BuildCylinderPoly (MNMesh & mesh, int segs, int smooth, int lsegs, int capsegs, int doPie, float radius1, float radius2, float height, float pie1, float pie2, int genUVs); BOOL ConeObject::HasUVW() { BOOL genUVs; Interval v; pblock->GetValue(PB_GENUVS, 0, genUVs, v); return genUVs; } void ConeObject::SetGenUVW(BOOL sw) { if (sw==HasUVW()) return; pblock->SetValue(PB_GENUVS,0, sw); } Point3 ConeObject::GetSurfacePoint( TimeValue t, float u, float v,Interval &iv) { float radius1, radius2, height; pblock->GetValue(PB_RADIUS1,t,radius1,iv); pblock->GetValue(PB_RADIUS2,t,radius2,iv); pblock->GetValue(PB_HEIGHT,t,height,iv); Point3 p; float sn = -(float)cos(u*TWOPI); float cs = (float)sin(u*TWOPI); p.x = (1.0f-v)*radius1*cs + v*radius2*cs; p.y = (1.0f-v)*radius1*sn + v*radius2*sn; p.z = height * v; return p; } Object *ConeObject::BuildPoly (TimeValue t) { int segs, smooth, llsegs, capsegs; float radius1, radius2, height, pie1, pie2; int doPie, genUVs; // Start the validity interval at forever and widdle it down. Interval tvalid = FOREVER; pblock->GetValue(PB_SIDES,t,segs,tvalid); pblock->GetValue(PB_SEGMENTS,t,llsegs,tvalid); pblock->GetValue(PB_CAPSEGMENTS,t,capsegs,tvalid); pblock->GetValue(PB_SMOOTH,t,smooth,tvalid); pblock->GetValue(PB_SLICEON,t,doPie,tvalid); pblock->GetValue(PB_GENUVS,t,genUVs,tvalid); Interval gvalid = tvalid; pblock->GetValue(PB_RADIUS1,t,radius1,gvalid); pblock->GetValue(PB_RADIUS2,t,radius2,gvalid); pblock->GetValue(PB_HEIGHT,t,height,gvalid); pblock->GetValue(PB_PIESLICE1,t,pie1,gvalid); pblock->GetValue(PB_PIESLICE2,t,pie2,gvalid); LimitValue(radius1, MIN_RADIUS, MAX_RADIUS); LimitValue(radius2, MIN_RADIUS, MAX_RADIUS); LimitValue(height, MIN_HEIGHT, MAX_HEIGHT); LimitValue(llsegs, MIN_SEGMENTS, MAX_SEGMENTS); LimitValue(segs, MIN_SIDES, MAX_SIDES); LimitValue(capsegs, MIN_SEGMENTS, MAX_SEGMENTS); LimitValue(smooth, 0, 1); PolyObject *pobj = new PolyObject(); MNMesh & mesh = pobj->GetMesh(); BuildCylinderPoly (mesh, segs, smooth, llsegs, capsegs, doPie, radius1, radius2, height, pie1, pie2, genUVs); pobj->SetChannelValidity(TOPO_CHAN_NUM,tvalid); pobj->SetChannelValidity(GEOM_CHAN_NUM,gvalid); return pobj; } void ConeObject::BuildMesh(TimeValue t) { int segs,llsegs,smooth,capsegs; float radius1,radius2,height,pie1, pie2; int doPie, genUVs; // Start the validity interval at forever and widdle it down. ivalid = FOREVER; pblock->GetValue(PB_SIDES,t,segs,ivalid); pblock->GetValue(PB_SEGMENTS,t,llsegs,ivalid); pblock->GetValue(PB_CAPSEGMENTS,t,capsegs,ivalid); pblock->GetValue(PB_RADIUS1,t,radius1,ivalid); pblock->GetValue(PB_RADIUS2,t,radius2,ivalid); pblock->GetValue(PB_HEIGHT,t,height,ivalid); pblock->GetValue(PB_SMOOTH,t,smooth,ivalid); pblock->GetValue(PB_PIESLICE1,t,pie1,ivalid); pblock->GetValue(PB_PIESLICE2,t,pie2,ivalid); pblock->GetValue(PB_SLICEON,t,doPie,ivalid); pblock->GetValue(PB_GENUVS,t,genUVs,ivalid); LimitValue(radius1, MIN_RADIUS, MAX_RADIUS); LimitValue(radius2, MIN_RADIUS, MAX_RADIUS); LimitValue(height, MIN_HEIGHT, MAX_HEIGHT); LimitValue(llsegs, MIN_SEGMENTS, MAX_SEGMENTS); LimitValue(segs, MIN_SIDES, MAX_SIDES); LimitValue(capsegs, MIN_SEGMENTS, MAX_SEGMENTS); LimitValue(smooth, 0, 1); BuildCylinderMesh(mesh, segs, smooth, llsegs, capsegs, doPie, radius1, radius2, height, pie1, pie2, genUVs); } // In cyl,cpp extern void BuildCylinderPatch( TimeValue t, PatchMesh &patch, float radius1, float radius2, float height, int genUVs); #ifndef NO_NURBS Object * BuildNURBSCone(float radius1, float radius2, float height, BOOL sliceon, float pie1, float pie2, BOOL genUVs) { BOOL flip = FALSE; if (radius1 == 0.0f) radius1 = 0.001f; if (radius2 == 0.0f) radius2 = 0.001f; if (height < 0.0f) flip = !flip; NURBSSet nset; Point3 origin(0,0,0); Point3 symAxis(0,0,1); Point3 refAxis(0,1,0); float startAngle = 0.0f; float endAngle = TWOPI; if (sliceon && pie1 != pie2) { float sweep = TWOPI - (pie2-pie1); if (sweep > TWOPI) sweep -= TWOPI; refAxis = Point3(Point3(1,0,0) * RotateZMatrix(pie2)); endAngle = sweep; } // first the main surface NURBSCVSurface *surf = new NURBSCVSurface(); nset.AppendObject(surf); surf->SetGenerateUVs(genUVs); surf->SetTextureUVs(0, 0, Point2(0.0f, 0.0f)); surf->SetTextureUVs(0, 1, Point2(0.0f, 1.0f)); surf->SetTextureUVs(0, 2, Point2(1.0f, 0.0f)); surf->SetTextureUVs(0, 3, Point2(1.0f, 1.0f)); surf->FlipNormals(!flip); surf->Renderable(TRUE); char bname[80]; char sname[80]; strcpy(bname, GetString(IDS_RB_CONE)); sprintf(sname, "%s%s", bname, GetString(IDS_CT_SURF)); if (sliceon && pie1 != pie2) { surf->SetName(sname); GenNURBSConeSurface(radius1, radius2, height, origin, symAxis, refAxis, startAngle, endAngle, TRUE, *surf); #define F(s1, s2, s1r, s1c, s2r, s2c) \ fuse.mSurf1 = (s1); \ fuse.mSurf2 = (s2); \ fuse.mRow1 = (s1r); \ fuse.mCol1 = (s1c); \ fuse.mRow2 = (s2r); \ fuse.mCol2 = (s2c); \ nset.mSurfFuse.Append(1, &fuse); NURBSFuseSurfaceCV fuse; NURBSCVSurface *s0 = (NURBSCVSurface*)nset.GetNURBSObject(0); Point3 cen; // next the two caps for (int c = 0; c < 2; c++) { if (c == 0) { cen = Point3(0,0,0); } else { cen = Point3(0.0f, 0.0f, height); } NURBSCVSurface *s = new NURBSCVSurface(); nset.AppendObject(s); // we'll be cubic in on direction and match the sphere in the other s->SetUOrder(4); s->SetNumUKnots(8); for (int i = 0; i < 4; i++) { s->SetUKnot(i, 0.0); s->SetUKnot(i+4, 1.0); } s->SetVOrder(s0->GetVOrder()); s->SetNumVKnots(s0->GetNumVKnots()); for (i = 0; i < s->GetNumVKnots(); i++) s->SetVKnot(i, s0->GetVKnot(i)); int numU, numV; s0->GetNumCVs(numU, numV); s->SetNumCVs(4, numV); for (int v = 0; v < numV; v++) { Point3 edge; if (c == 0) edge = s0->GetCV(0, v)->GetPosition(0); else edge = s0->GetCV(numU-1, v)->GetPosition(0); double w = s0->GetCV(0, v)->GetWeight(0); for (int u = 0; u < 4; u++) { NURBSControlVertex ncv; ncv.SetPosition(0, cen + ((edge - cen)*((float)u/3.0f))); ncv.SetWeight(0, w); s->SetCV(u, v, ncv); } } s->SetGenerateUVs(genUVs); s->SetTextureUVs(0, 0, Point2(1.0f, 1.0f)); s->SetTextureUVs(0, 1, Point2(0.0f, 1.0f)); s->SetTextureUVs(0, 2, Point2(1.0f, 0.0f)); s->SetTextureUVs(0, 3, Point2(0.0f, 0.0f)); if (c == 0) s->FlipNormals(!flip); else s->FlipNormals(flip); s->Renderable(TRUE); sprintf(sname, "%s%s%02d", bname, GetString(IDS_CT_CAP), c+1); s->SetName(sname); } NURBSCVSurface *s1 = (NURBSCVSurface *)nset.GetNURBSObject(1); NURBSCVSurface *s2 = (NURBSCVSurface *)nset.GetNURBSObject(2); // next the two pie slices for (c = 0; c < 2; c++) { if (c == 0) cen = Point3(0,0,0); else cen = Point3(0.0f, 0.0f, height); NURBSCVSurface *s = new NURBSCVSurface(); nset.AppendObject(s); // we'll match the cylinder in on dimention and the caps in the other. s->SetUOrder(s0->GetUOrder()); int numKnots = s0->GetNumUKnots(); s->SetNumUKnots(numKnots); for (int i = 0; i < numKnots; i++) s->SetUKnot(i, s0->GetUKnot(i)); s->SetVOrder(s1->GetUOrder()); numKnots = s1->GetNumUKnots(); s->SetNumVKnots(numKnots); for (i = 0; i < numKnots; i++) s->SetVKnot(i, s1->GetUKnot(i)); int s0u, s0v, s1u, s1v, s2u, s2v; s0->GetNumCVs(s0u, s0v); s1->GetNumCVs(s1u, s1v); s2->GetNumCVs(s2u, s2v); int uNum = s0u, vNum = s1u; s->SetNumCVs(uNum, vNum); for (int v = 0; v < vNum; v++) { for (int u = 0; u < uNum; u++) { // we get get the ends from the caps and the edge from the main sheet if (u == 0) { // bottom if (c == 0) { s->SetCV(u, v, *s1->GetCV(v, 0)); F(1, 3, v, 0, u, v); } else { s->SetCV(u, v, *s1->GetCV(v, s1v-1)); F(1, 4, v, s1v-1, u, v); } } else if (u == uNum-1) { // top if (c == 0) { s->SetCV(u, v, *s2->GetCV(v, 0)); F(2, 3, v, 0, u, v); } else { s->SetCV(u, v, *s2->GetCV(v, s2v-1)); F(2, 4, v, s2v-1, u, v); } } else { // middle if (v == vNum-1) { // outer edge if (c == 0) { s->SetCV(u, v, *s0->GetCV(u, 0)); F(0, 3, u, 0, u, v); } else { s->SetCV(u, v, *s0->GetCV(u, s0v-1)); F(0, 4, u, s0v-1, u, v); } } else { // inside float angle; if (c == 0) angle = pie2; else angle = pie1; float hrad1 = radius1 * (float)v / (float)(vNum-1); float hrad2 = radius2 * (float)v / (float)(vNum-1); float rad = hrad1 + ((hrad2 - hrad1) * (float)u / (float)(uNum-1)); NURBSControlVertex ncv; ncv.SetPosition(0, Point3(rad, 0.0f, height * (float)u / (float)(uNum-1)) * RotateZMatrix(angle)); ncv.SetWeight(0, 1.0f); s->SetCV(u, v, ncv); } } } } s->SetGenerateUVs(genUVs); s->SetTextureUVs(0, 0, Point2(0.0f, 0.0f)); s->SetTextureUVs(0, 1, Point2(0.0f, 1.0f)); s->SetTextureUVs(0, 2, Point2(1.0f, 0.0f)); s->SetTextureUVs(0, 3, Point2(1.0f, 1.0f)); if (c == 0) s->FlipNormals(!flip); else s->FlipNormals(flip); s->Renderable(TRUE); sprintf(sname, "%s%s%02d", bname, GetString(IDS_CT_SLICE), c+1); s->SetName(sname); } NURBSCVSurface *s3 = (NURBSCVSurface *)nset.GetNURBSObject(3); NURBSCVSurface *s4 = (NURBSCVSurface *)nset.GetNURBSObject(4); // now fuse up the rest // Fuse the edges for (int v = 0; v < s0->GetNumVCVs(); v++) { F(0, 1, 0, v, s1->GetNumUCVs()-1, v); F(0, 2, s0->GetNumUCVs()-1, v, s2->GetNumUCVs()-1, v); } // Fuse the cap centers for (v = 1; v < s1->GetNumVCVs(); v++) { F(1, 1, 0, 0, 0, v); F(2, 2, 0, 0, 0, v); } // Fuse the core for (int u = 0; u < s3->GetNumUCVs(); u++) { F(3, 4, u, 0, u, 0); } } else { GenNURBSConeSurface(radius1, radius2, height, origin, symAxis, refAxis, startAngle, endAngle, FALSE, *surf); // now create caps on the ends if (radius1 != 0.0) { NURBSCapSurface *cap0 = new NURBSCapSurface(); nset.AppendObject(cap0); cap0->SetGenerateUVs(genUVs); cap0->SetParent(0); cap0->SetEdge(0); cap0->FlipNormals(!flip); cap0->Renderable(TRUE); char sname[80]; sprintf(sname, "%s%s%02d", bname, GetString(IDS_CT_CAP), 0); cap0->SetName(sname); } if (radius2 != 0.0) { NURBSCapSurface *cap1 = new NURBSCapSurface(); nset.AppendObject(cap1); cap1->SetGenerateUVs(genUVs); cap1->SetParent(0); cap1->SetEdge(1); cap1->FlipNormals(flip); cap1->Renderable(TRUE); sprintf(sname, "%s%s%02d", bname, GetString(IDS_CT_CAP), 1); cap1->SetName(sname); } } Matrix3 mat; mat.IdentityMatrix(); Object *ob = CreateNURBSObject(NULL, &nset, mat); return ob; } #endif Object* ConeObject::ConvertToType(TimeValue t, Class_ID obtype) { #ifndef NO_PATCHES if (obtype == patchObjectClassID) { Interval valid = FOREVER; float radius1, radius2, height; int genUVs; pblock->GetValue(PB_RADIUS1,t,radius1,valid); pblock->GetValue(PB_RADIUS2,t,radius2,valid); pblock->GetValue(PB_HEIGHT,t,height,valid); pblock->GetValue(PB_GENUVS,t,genUVs,valid); if (radius1 < 0.0f) radius1 = 0.0f; if (radius2 < 0.0f) radius2 = 0.0f; PatchObject *ob = new PatchObject(); BuildCylinderPatch(t,ob->patch,radius1,radius2,height,genUVs); ob->SetChannelValidity(TOPO_CHAN_NUM,valid); ob->SetChannelValidity(GEOM_CHAN_NUM,valid); ob->UnlockObject(); return ob; } #endif if (obtype == polyObjectClassID) { Object *ob = BuildPoly (t); ob->UnlockObject (); return ob; } #ifndef NO_NURBS if (obtype == EDITABLE_SURF_CLASS_ID) { Interval valid = FOREVER; float radius1, radius2, height, pie1, pie2; int sliceon, genUVs; pblock->GetValue(PB_RADIUS1,t,radius1,valid); pblock->GetValue(PB_RADIUS2,t,radius2,valid); pblock->GetValue(PB_HEIGHT,t,height,valid); pblock->GetValue(PB_PIESLICE1,t,pie1,valid); pblock->GetValue(PB_PIESLICE2,t,pie2,valid); pblock->GetValue(PB_SLICEON,t,sliceon,valid); pblock->GetValue(PB_GENUVS,t,genUVs,valid); if (radius1 < 0.0f) radius1 = 0.0f; if (radius2 < 0.0f) radius2 = 0.0f; Object *ob = BuildNURBSCone(radius1, radius2, height, sliceon, pie1, pie2, genUVs); ob->SetChannelValidity(TOPO_CHAN_NUM,valid); ob->SetChannelValidity(GEOM_CHAN_NUM,valid); ob->UnlockObject(); return ob; } #endif #ifdef DESIGN_VER if (obtype == GENERIC_AMSOLID_CLASS_ID) { Interval valid = FOREVER; float radius1, radius2, height, pie1, pie2; int sliceon, genUVs, sides; pblock->GetValue(PB_RADIUS1,t,radius1,valid); pblock->GetValue(PB_RADIUS2,t,radius2,valid); pblock->GetValue(PB_HEIGHT,t,height,valid); pblock->GetValue(PB_PIESLICE1,t,pie1,valid); pblock->GetValue(PB_PIESLICE2,t,pie2,valid); pblock->GetValue(PB_SLICEON,t,sliceon,valid); pblock->GetValue(PB_GENUVS,t,genUVs,valid); pblock->GetValue(PB_SIDES,t,sides,valid); int smooth; pblock->GetValue(PB_SMOOTH,t,smooth,valid); if (radius1 < 0.0f) radius1 = 0.0f; if (radius2 < 0.0f) radius2 = 0.0f; Object* solid = (Object*)CreateInstance(GEOMOBJECT_CLASS_ID, GENERIC_AMSOLID_CLASS_ID); assert(solid); if(solid) { IGeomImp* cacheptr = (IGeomImp*)(solid->GetInterface(I_GEOMIMP)); assert(cacheptr); if(cacheptr) { bool res = cacheptr->createCone(height, radius1, radius2, sides, smooth); solid->ReleaseInterface(I_GEOMIMP, cacheptr); if(res) return solid; else { solid->DeleteMe(); } } } return NULL; } #endif return SimpleObject::ConvertToType(t,obtype); } int ConeObject::CanConvertToType(Class_ID obtype) { if(obtype==defObjectClassID || obtype==mapObjectClassID || obtype==triObjectClassID) return 1; #ifndef NO_PATCHES if(obtype == patchObjectClassID) return 1; #endif #ifndef NO_NURBS if(obtype == EDITABLE_SURF_CLASS_ID) return 1; #endif #ifdef DESIGN_VER if(obtype == GENERIC_AMSOLID_CLASS_ID) return 1; #endif if (obtype == polyObjectClassID) return 1; return SimpleObject::CanConvertToType(obtype); } void ConeObject::GetCollapseTypes(Tab<Class_ID> &clist,Tab<TSTR*> &nlist) { Object::GetCollapseTypes(clist, nlist); #ifndef NO_NURBS Class_ID id = EDITABLE_SURF_CLASS_ID; TSTR *name = new TSTR(GetString(IDS_SM_NURBS_SURFACE)); clist.Append(1,&id); nlist.Append(1,&name); #endif } class ConeObjCreateCallBack: public CreateMouseCallBack { ConeObject *ob; Point3 p[4]; IPoint2 sp0,sp1,sp2,sp3; float r1; public: int proc( ViewExp *vpt,int msg, int point, int flags, IPoint2 m, Matrix3& mat ); void SetObj(ConeObject *obj) { ob = obj; } }; int ConeObjCreateCallBack::proc(ViewExp *vpt,int msg, int point, int flags, IPoint2 m, Matrix3& mat ) { float r; #ifdef _OSNAP if (msg == MOUSE_FREEMOVE) { #ifdef _3D_CREATE vpt->SnapPreview(m,m,NULL, SNAP_IN_3D); #else vpt->SnapPreview(m,m,NULL, SNAP_IN_PLANE); #endif } #endif if (msg==MOUSE_POINT||msg==MOUSE_MOVE) { switch(point) { case 0: ob->suspendSnap = TRUE; sp0 = m; #ifdef _3D_CREATE p[0] = vpt->SnapPoint(m,m,NULL,SNAP_IN_3D); #else p[0] = vpt->SnapPoint(m,m,NULL,SNAP_IN_PLANE); #endif mat.SetTrans(p[0]); // Set Node's transform ob->pblock->SetValue(PB_RADIUS1,0,0.01f); ob->pblock->SetValue(PB_RADIUS2,0,0.01f); ob->pblock->SetValue(PB_HEIGHT,0,0.01f); break; case 1: mat.IdentityMatrix(); //mat.PreRotateZ(HALFPI); sp1 = m; #ifdef _3D_CREATE p[1] = vpt->SnapPoint(m,m,NULL,SNAP_IN_3D); #else p[1] = vpt->SnapPoint(m,m,NULL,SNAP_IN_PLANE); #endif if (ob->dlgCreateMeth) { // radius r = Length(p[1]-p[0]); mat.SetTrans(p[0]); } else { // diameter Point3 center = (p[0]+p[1])/float(2); r = Length(center-p[0]); mat.SetTrans(center); // Modify Node's transform } ob->pblock->SetValue(PB_RADIUS1,0,r); ob->pblock->SetValue(PB_RADIUS2,0,r+1.0f); ob->pmapParam->Invalidate(); r1 = r; if (flags&MOUSE_CTRL) { float ang = (float)atan2(p[1].y-p[0].y,p[1].x-p[0].x); mat.PreRotateZ(ob->ip->SnapAngle(ang)); } if (msg==MOUSE_POINT) { if (Length(m-sp0)<3 || Length(p[1]-p[0]) < 0.1f) { return CREATE_ABORT; } } break; case 2: { sp2 = m; #ifdef _OSNAP float h = vpt->SnapLength(vpt->GetCPDisp(p[1],Point3(0,0,1),sp1,m,TRUE)); #else float h = vpt->SnapLength(vpt->GetCPDisp(p[1],Point3(0,0,1),sp1,m)); #endif ob->pblock->SetValue(PB_HEIGHT,0,h); ob->pmapParam->Invalidate(); } break; case 3: r = vpt->SnapLength(vpt->GetCPDisp(p[1],Point3(0,0,1),sp2,m)) + r1; ob->pblock->SetValue(PB_RADIUS2,0,r); ob->pmapParam->Invalidate(); if (msg==MOUSE_POINT) { ob->suspendSnap = FALSE; return CREATE_STOP; } break; } } else if (msg == MOUSE_ABORT) { return CREATE_ABORT; } return TRUE; } static ConeObjCreateCallBack coneCreateCB; CreateMouseCallBack* ConeObject::GetCreateMouseCallBack() { coneCreateCB.SetObj(this); return(&coneCreateCB); } BOOL ConeObject::OKtoDisplay(TimeValue t) { float radius1, radius2; pblock->GetValue(PB_RADIUS1,t,radius1,FOREVER); pblock->GetValue(PB_RADIUS2,t,radius2,FOREVER); if (radius1==0.0f && radius2==0.0f) return FALSE; else return TRUE; } // From ParamArray BOOL ConeObject::SetValue(int i, TimeValue t, int v) { switch (i) { case PB_CREATEMETHOD: dlgCreateMeth = v; break; } return TRUE; } BOOL ConeObject::SetValue(int i, TimeValue t, float v) { switch (i) { case PB_TI_RADIUS1: crtRadius1 = v; break; case PB_TI_RADIUS2: crtRadius2 = v; break; case PB_TI_HEIGHT: crtHeight = v; break; } return TRUE; } BOOL ConeObject::SetValue(int i, TimeValue t, Point3 &v) { switch (i) { case PB_TI_POS: crtPos = v; break; } return TRUE; } BOOL ConeObject::GetValue(int i, TimeValue t, int &v, Interval &ivalid) { switch (i) { case PB_CREATEMETHOD: v = dlgCreateMeth; break; } return TRUE; } BOOL ConeObject::GetValue(int i, TimeValue t, float &v, Interval &ivalid) { switch (i) { case PB_TI_RADIUS1: v = crtRadius1; break; case PB_TI_RADIUS2: v = crtRadius2; break; case PB_TI_HEIGHT: v = crtHeight; break; } return TRUE; } BOOL ConeObject::GetValue(int i, TimeValue t, Point3 &v, Interval &ivalid) { switch (i) { case PB_TI_POS: v = crtPos; break; } return TRUE; } void ConeObject::InvalidateUI() { if (pmapParam) pmapParam->Invalidate(); } ParamDimension *ConeObject::GetParameterDim(int pbIndex) { switch (pbIndex) { case PB_RADIUS1: case PB_RADIUS2: return stdWorldDim; case PB_HEIGHT: return stdWorldDim; case PB_SEGMENTS: return stdSegmentsDim; case PB_CAPSEGMENTS: return stdSegmentsDim; case PB_SIDES: return stdSegmentsDim; case PB_SMOOTH: return stdNormalizedDim; case PB_SLICEON: return stdNormalizedDim; case PB_PIESLICE1: return stdAngleDim; case PB_PIESLICE2: return stdAngleDim; default: return defaultDim; } } TSTR ConeObject::GetParameterName(int pbIndex) { switch (pbIndex) { case PB_RADIUS1: return GetString(IDS_RB_RADIUS1); case PB_RADIUS2: return GetString(IDS_RB_RADIUS2); case PB_HEIGHT: return GetString(IDS_RB_HEIGHT); case PB_SEGMENTS: return GetString(IDS_RB_CIRCLESEGMENTS); case PB_CAPSEGMENTS: return GetString(IDS_RB_CAPSEGMENTS); case PB_SIDES: return GetString(IDS_RB_SIDES); case PB_SMOOTH: return GetString(IDS_RB_SMOOTH); case PB_SLICEON: return GetString(IDS_RB_SLICEON); case PB_PIESLICE1: return GetString(IDS_RB_SLICEFROM); case PB_PIESLICE2: return GetString(IDS_RB_SLICETO); //case PB_GENUVS: return GetString(IDS_RB_GENTEXCOORDS); default: return TSTR(_T("")); } } RefTargetHandle ConeObject::Clone(RemapDir& remap) { ConeObject* newob = new ConeObject(); newob->ReplaceReference(0,pblock->Clone(remap)); newob->ivalid.SetEmpty(); BaseClone(this, newob, remap); return(newob); } #endif // NO_OBJECT_STANDARD_PRIMITIVES
[ "paul-kv@yandex.ru" ]
paul-kv@yandex.ru
0b67e61e120b333989a5b390bd868343a08f13b4
25880501eb7abc150d1f1bd709f9499615b0c295
/ogl-samples-4.5.0.0/tests/gl-330-sampler-wrap.cpp
4285c7eb6a88a2533aef700e02afa7d4ae51c941
[ "MIT" ]
permissive
hikboy/SDL-test
895e59848914f20ada2ad6dec3f451e292f2d0e2
94cd4cf2097f39afa2f54b3567f255b4aecc9387
refs/heads/main
2023-04-06T17:19:23.252578
2021-04-03T11:44:19
2021-04-03T11:44:19
354,226,507
0
0
null
null
null
null
UTF-8
C++
false
false
8,633
cpp
/////////////////////////////////////////////////////////////////////////////////// /// OpenGL Samples Pack (ogl-samples.g-truc.net) /// /// Copyright (c) 2004 - 2014 G-Truc Creation (www.g-truc.net) /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. /////////////////////////////////////////////////////////////////////////////////// #include "test.hpp" namespace { char const * VERT_SHADER_SOURCE("gl-330/texture-2d.vert"); char const * FRAG_SHADER_SOURCE("gl-330/texture-2d.frag"); char const * TEXTURE_DIFFUSE("kueken1-dxt5.dds"); struct vertex { vertex ( glm::vec2 const & Position, glm::vec2 const & Texcoord ) : Position(Position), Texcoord(Texcoord) {} glm::vec2 Position; glm::vec2 Texcoord; }; // With DDS textures, v texture coordinate are reversed, from top to bottom GLsizei const VertexCount = 6; GLsizeiptr const VertexSize = VertexCount * sizeof(vertex); vertex const VertexData[VertexCount] = { vertex(glm::vec2(-1.0f,-1.0f) * 1.5f, glm::vec2(-2.0f, 2.0f)), vertex(glm::vec2( 1.0f,-1.0f) * 1.5f, glm::vec2( 2.0f, 2.0f)), vertex(glm::vec2( 1.0f, 1.0f) * 1.5f, glm::vec2( 2.0f,-2.0f)), vertex(glm::vec2( 1.0f, 1.0f) * 1.5f, glm::vec2( 2.0f,-2.0f)), vertex(glm::vec2(-1.0f, 1.0f) * 1.5f, glm::vec2(-2.0f,-2.0f)), vertex(glm::vec2(-1.0f,-1.0f) * 1.5f, glm::vec2(-2.0f, 2.0f)) }; namespace viewport { enum type { V00, V10, V11, V01, MAX }; }//namespace viewport GLuint VertexArrayName; GLuint ProgramName; GLuint BufferName; GLuint Texture2DName; GLint UniformMVP; GLint UniformDiffuse; GLuint SamplerName[viewport::MAX]; glm::ivec4 Viewport[viewport::MAX]; }//namespace class gl_330_sampler_wrap : public test { public: gl_330_sampler_wrap(int argc, char* argv[]) : test(argc, argv, "gl-330-sampler-wrap", test::CORE, 3, 3) {} private: bool initProgram() { bool Validated = true; if(Validated) { compiler Compiler; GLuint VertShaderName = Compiler.create(GL_VERTEX_SHADER, getDataDirectory() + VERT_SHADER_SOURCE, "--version 330 --profile core"); GLuint FragShaderName = Compiler.create(GL_FRAGMENT_SHADER, getDataDirectory() + FRAG_SHADER_SOURCE, "--version 330 --profile core"); Validated = Validated && Compiler.check(); ProgramName = glCreateProgram(); glAttachShader(ProgramName, VertShaderName); glAttachShader(ProgramName, FragShaderName); glLinkProgram(ProgramName); Validated = Validated && Compiler.checkProgram(ProgramName); } if(Validated) { UniformMVP = glGetUniformLocation(ProgramName, "MVP"); UniformDiffuse = glGetUniformLocation(ProgramName, "Diffuse"); } return Validated && this->checkError("initProgram"); } bool initBuffer() { glGenBuffers(1, &BufferName); glBindBuffer(GL_ARRAY_BUFFER, BufferName); glBufferData(GL_ARRAY_BUFFER, VertexSize, VertexData, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); return this->checkError("initBuffer"); } #define GL_MIRROR_CLAMP_TO_EDGE 0x8743 #define GL_MIRROR_CLAMP_TO_BORDER_EXT 0x8912 bool initSampler() { glGenSamplers(viewport::MAX, SamplerName); for(std::size_t i = 0; i < viewport::MAX; ++i) { glSamplerParameteri(SamplerName[i], GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glSamplerParameteri(SamplerName[i], GL_TEXTURE_MAG_FILTER, GL_LINEAR); glm::vec4 BorderColor(0.0f, 0.5f, 1.0f, 1.0f); glSamplerParameterfv(SamplerName[i], GL_TEXTURE_BORDER_COLOR, &BorderColor[0]); } glSamplerParameteri(SamplerName[viewport::V00], GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT); glSamplerParameteri(SamplerName[viewport::V10], GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glSamplerParameteri(SamplerName[viewport::V11], GL_TEXTURE_WRAP_S, GL_REPEAT); glSamplerParameteri(SamplerName[viewport::V01], GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glSamplerParameteri(SamplerName[viewport::V00], GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT); glSamplerParameteri(SamplerName[viewport::V10], GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glSamplerParameteri(SamplerName[viewport::V11], GL_TEXTURE_WRAP_T, GL_REPEAT); glSamplerParameteri(SamplerName[viewport::V01], GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); return this->checkError("initSampler"); } bool initTexture() { glGenTextures(1, &Texture2DName); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, Texture2DName); gli::texture2D Texture(gli::load_dds((getDataDirectory() + TEXTURE_DIFFUSE).c_str())); for(std::size_t Level = 0; Level < Texture.levels(); ++Level) { glCompressedTexImage2D( GL_TEXTURE_2D, GLint(Level), GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GLsizei(Texture[Level].dimensions().x), GLsizei(Texture[Level].dimensions().y), 0, GLsizei(Texture[Level].size()), Texture[Level].data()); } return this->checkError("initTexture"); } bool initVertexArray() { glGenVertexArrays(1, &VertexArrayName); glBindVertexArray(VertexArrayName); glBindBuffer(GL_ARRAY_BUFFER, BufferName); glVertexAttribPointer(semantic::attr::POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(vertex), BUFFER_OFFSET(0)); glVertexAttribPointer(semantic::attr::TEXCOORD, 2, GL_FLOAT, GL_FALSE, sizeof(vertex), BUFFER_OFFSET(sizeof(glm::vec2))); glBindBuffer(GL_ARRAY_BUFFER, 0); glEnableVertexAttribArray(semantic::attr::POSITION); glEnableVertexAttribArray(semantic::attr::TEXCOORD); glBindVertexArray(0); return this->checkError("initVertexArray"); } bool begin() { glm::ivec2 WindowSize(this->getWindowSize()); Viewport[viewport::V00] = glm::ivec4(0, 0, WindowSize >> 1); Viewport[viewport::V10] = glm::ivec4(WindowSize.x >> 1, 0, WindowSize >> 1); Viewport[viewport::V11] = glm::ivec4(WindowSize.x >> 1, WindowSize.y >> 1, WindowSize >> 1); Viewport[viewport::V01] = glm::ivec4(0, WindowSize.y >> 1, WindowSize >> 1); bool Validated = true; if(Validated) Validated = initProgram(); if(Validated) Validated = initBuffer(); if(Validated) Validated = initTexture(); if(Validated) Validated = initSampler(); if(Validated) Validated = initVertexArray(); return Validated && this->checkError("begin"); } bool end() { glDeleteBuffers(1, &BufferName); glDeleteProgram(ProgramName); glDeleteTextures(1, &Texture2DName); glDeleteVertexArrays(1, &VertexArrayName); return this->checkError("end"); } bool render() { glm::vec2 WindowSize(this->getWindowSize()); glm::mat4 Projection = glm::perspective(glm::pi<float>() * 0.25f, WindowSize.x / WindowSize.y, 0.1f, 1000.0f); glm::mat4 Model = glm::mat4(1.0f); glm::mat4 MVP = Projection * this->view() * Model; glClearBufferfv(GL_COLOR, 0, &glm::vec4(1.0f, 0.5f, 0.0f, 1.0f)[0]); glUseProgram(ProgramName); glUniformMatrix4fv(UniformMVP, 1, GL_FALSE, &MVP[0][0]); glUniform1i(UniformDiffuse, 0); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, Texture2DName); glBindVertexArray(VertexArrayName); for(std::size_t Index = 0; Index < viewport::MAX; ++Index) { glViewport(Viewport[Index].x, Viewport[Index].y, Viewport[Index].z, Viewport[Index].w); glBindSampler(0, SamplerName[Index]); glDrawArraysInstanced(GL_TRIANGLES, 0, VertexCount, 1); } return true; } }; int main(int argc, char* argv[]) { int Error(0); gl_330_sampler_wrap Test(argc, argv); Error += Test(); return Error; }
[ "hikboy@outlook.com" ]
hikboy@outlook.com
05ba5b97536016d0976e047dc2f1b0dee31d9a20
e5a40e4ac8b6785c947c7f7b7a3953abd2387bd7
/iiiteru.cpp
ca0294f7dba1101ffa79d9f8047453c5cec07cfd
[]
no_license
fengtuo58/SPW
e0cb37c1bb00161a087d5ba68507653ce2fd60a1
166bec52bb6216cc0fd1ca3aadf8c180ea8fea18
refs/heads/master
2021-01-10T12:12:11.533241
2016-03-28T11:48:27
2016-03-28T11:48:27
50,399,852
0
0
null
null
null
null
UTF-8
C++
false
false
1,108
cpp
//#include"DataLogger.h" //#include <iomanip> //#include<sstream> //#include <string> //using namespace std; //ostream&operator <<(ostream &os,const Coord &c){ // return os<<c.deg<<"*"<<c.min<<"\'"<<c.sec<<"\""; // //} //std:: string IntToString(int a){ // std::ostringstream s; // s<<a; // return s.str(); // //} //string Coord ::toString()const { // ostringstream os; // os<<*this; // return os.str(); //} //ostream & operator<<(ostream &os,const DataPoint& d){ // os.setf(ios::fixed,ios::floatfield); // char fillc=os.fill('0'); // tm*tdata=localtime(&d.timestamp); // os<<setw(2)<<tdata->tm_mon+1<<'\\' // <<setw(2)<<tdata->tm_mday<<'\\' // <<setw(2)<<tdata->tm_year+1900<<' ' // <<setw(2)<<tdata->tm_hour<<' :' // <<setw(2)<<tdata->tm_min<<':' // <<setw(2)<<tdata->tm_sec; // os.fill(' '); // streamsize prec=os.precision(4); // os<<"Lat:"<<setw(9)<<d.latitude.toString() // <<",long"<<setw(9)<<d.longitude.toString() // <<",depth"<<setw(9)<<d.depth // <<",temp: "<<setw(9)<<d.temprature; //os.fill(fillc); //os.precision(prec); //return os; // //} //
[ "2693263558@qq.com" ]
2693263558@qq.com
e6fcc96b145239b136ed5d978cfd4380c2a7a30d
1fcf32178d813855d804293a961c61dd51fb6b14
/src/hiir/StageProc16Avx512.h
4f349d1d61bf518a71bfe933e548f9707a9964dd
[ "WTFPL" ]
permissive
kurtjcu/pedalevite
d33248538a62d7e0dee3c66122abb9aad075634e
61ec6f9b5dd7667c620ebc8d3b4ca7944ed8760d
refs/heads/master
2023-07-26T03:49:10.209241
2021-09-04T08:34:32
2021-09-04T08:34:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,797
h
/***************************************************************************** StageProc16Avx512.h Author: Laurent de Soras, 2020 Template parameters: - REMAINING: Number of remaining coefficients to process, >= 0 --- 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***********************************************************************/ #if ! defined (hiir_StageProc16Avx512_HEADER_INCLUDED) #define hiir_StageProc16Avx512_HEADER_INCLUDED #if defined (_MSC_VER) #pragma once #pragma warning (4 : 4250) // "Inherits via dominance." #endif /*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ #include "hiir/def.h" //#include <xmmintrin.h> #include <immintrin.h> namespace hiir { class StageDataAvx512; template <int REMAINING> class StageProc16Avx512 { static_assert ((REMAINING >= 0), "REMAINING must be >= 0"); /*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ public: static hiir_FORCEINLINE void process_sample_pos (const int nbr_coefs, __m512 &spl_0, __m512 &spl_1, StageDataAvx512 *stage_arr) noexcept; static hiir_FORCEINLINE void process_sample_neg (const int nbr_coefs, __m512 &spl_0, __m512 &spl_1, StageDataAvx512 *stage_arr) noexcept; /*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ protected: /*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ private: /*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ private: StageProc16Avx512 () = delete; StageProc16Avx512 (const StageProc16Avx512 <REMAINING> &other) = delete; StageProc16Avx512 (StageProc16Avx512 <REMAINING> &&other) = delete; ~StageProc16Avx512 () = delete; StageProc16Avx512 <REMAINING> & operator = (const StageProc16Avx512 <REMAINING> &other) = delete; StageProc16Avx512 <REMAINING> & operator = (StageProc16Avx512 <REMAINING> &&other) = delete; bool operator == (const StageProc16Avx512 <REMAINING> &other) = delete; bool operator != (const StageProc16Avx512 <REMAINING> &other) = delete; }; // class StageProc16Avx512 } // namespace hiir #include "hiir/StageProc16Avx512.hpp" #endif // hiir_StageProc16Avx512_HEADER_INCLUDED /*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
[ "fuck@fuck.fuck" ]
fuck@fuck.fuck
bb0883491f90151ed0f02bfab66aa712584d046d
869cefe6ea1acb40e347f5430278b1204984b565
/extras/include/boost/boost/test/utils/runtime/cla/typed_parameter.hpp
264604de797aa184b6426a365a30f1bfa27fb816
[ "BSL-1.0" ]
permissive
muschellij2/FSL6.0.0
c68ed91e8c2777fcf07d994d7ab288a75e448fd1
3c3dd651066ee189bc8c290f744ca48cb3d1f156
refs/heads/master
2020-04-27T01:04:04.915711
2019-03-05T14:57:48
2019-03-05T14:57:48
173,954,388
9
4
null
null
null
null
UTF-8
C++
false
false
2,174
hpp
// (C) Copyright Gennadiy Rozental 2005-2008. // Use, modification, and distribution are 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) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile: typed_parameter.hpp,v $ // // Version : $Revision: 1.1.1.2 $ // // Description : generic typed parameter model // *************************************************************************** #ifndef BOOST_RT_CLA_TYPED_PARAMETER_HPP_062604GER #define BOOST_RT_CLA_TYPED_PARAMETER_HPP_062604GER // Boost.Runtime.Parameter #include <boost/test/utils/runtime/config.hpp> #include <boost/test/utils/runtime/fwd.hpp> #include <boost/test/utils/runtime/validation.hpp> #include <boost/test/utils/runtime/cla/parameter.hpp> #include <boost/test/utils/runtime/cla/argument_factory.hpp> // Boost.Test #include <boost/test/utils/rtti.hpp> namespace boost { namespace BOOST_RT_PARAM_NAMESPACE { namespace cla { // ************************************************************************** // // ************** runtime::cla::typed_parameter ************** // // ************************************************************************** // template<typename T> class typed_parameter : public cla::parameter { public: explicit typed_parameter( identification_policy& ID ) : cla::parameter( ID, m_arg_factory, rtti::type_id<T>() == rtti::type_id<bool>() ) {} // parameter properties modification template<typename Modifier> void accept_modifier( Modifier const& m ) { cla::parameter::accept_modifier( m ); m_arg_factory.accept_modifier( m ); BOOST_RT_PARAM_VALIDATE_LOGIC( !p_optional || !m_arg_factory.m_value_generator, BOOST_RT_PARAM_LITERAL( "can't define a value generator for optional parameter " ) << id_2_report() ); } private: // Data members typed_argument_factory<T> m_arg_factory; }; } // namespace cla } // namespace BOOST_RT_PARAM_NAMESPACE } // namespace boost #endif // BOOST_RT_CLA_TYPED_PARAMETER_HPP_062604GER
[ "muschellij2@gmail.com" ]
muschellij2@gmail.com
eb58e256ebd300b83e14102208fbfef87c3c34ff
6c37664722b69ae85262b6dbe135aad1c127d2ea
/C++/TheSolution/TheSolution/TheSolution/Test_project/Person.h
ab34a2663488ac3d656635bbcb0a81504bb9feb3
[]
no_license
TonyBoy22/gittest
317941ae437ab0134bd98d447c8e18d9ee5475d4
ff90a6b922d2b8fcace19acc2a81df2a199013ae
refs/heads/master
2022-12-12T11:09:59.487845
2022-11-27T16:21:34
2022-11-27T16:21:34
102,378,996
0
0
null
null
null
null
UTF-8
C++
false
false
519
h
#pragma once #include <string> #include <map> // Will define the person class and maybe other parameters using namespace std; class Person { public: // Needs std::string name; unsigned int type; // The type of perso. Will be a dict float riskValue; float profit; // Couple of flags bool Resident; bool Maintainer; // Wil be responsible for maintenance float PossessionFactor; }; map <string, unsigned int> personType; /* * Will be let's say 0 for investors, * 1 for roomates, 2 for associates workers */
[ "antoine.marion@usherbrooke.ca" ]
antoine.marion@usherbrooke.ca
2281ee3f2627c2284bbb3fe4e686e53db09ef9f5
8dd64ef7cfafa452eb307123bf0ca75ae11e8bb5
/Algorithms/easy/422_valid_word_square.cpp
99f75cbabc807dcf07d7d03448b6117e15cdbdbe
[]
no_license
gwqw/LeetCodeCpp
1a9dd673ab0dd50a5f033f3d3e373b84477369be
64a7abad03a3783e6129ee942e842aaed91f75a5
refs/heads/master
2021-12-23T10:56:38.466793
2021-08-13T07:36:25
2021-08-13T07:36:25
204,003,689
0
0
null
null
null
null
UTF-8
C++
false
false
1,765
cpp
/** 422. Valid Word Square Given an array of strings words, return true if it forms a valid word square. A sequence of strings forms a valid word square if the kth row and column read the same string, where 0 <= k < max(numRows, numColumns). Example 1: Input: words = ["abcd","bnrt","crmy","dtye"] Output: true Explanation: The 1st row and 1st column both read "abcd". The 2nd row and 2nd column both read "bnrt". The 3rd row and 3rd column both read "crmy". The 4th row and 4th column both read "dtye". Therefore, it is a valid word square. Example 2: Input: words = ["abcd","bnrt","crm","dt"] Output: true Explanation: The 1st row and 1st column both read "abcd". The 2nd row and 2nd column both read "bnrt". The 3rd row and 3rd column both read "crm". The 4th row and 4th column both read "dt". Therefore, it is a valid word square. Example 3: Input: words = ["ball","area","read","lady"] Output: false Explanation: The 3rd row reads "read" while the 3rd column reads "lead". Therefore, it is NOT a valid word square. Constraints: 1 <= words.length <= 500 1 <= words[i].length <= 500 words[i] consists of only lowercase English letters. Algo: compare row with col for i in range(n): if not compare(row[i], col[i]): return false return true */ class Solution { public: bool validWordSquare(const vector<string>& words) { if (words.size() != words[0].size()) return false; for (size_t i = 0; i < words.size(); ++i) { if (!compare(words, i)) return false; } return true; } private: static bool compare(const vector<string>& words, size_t i) { if (words[i].size() > words.size()) return false; for (size_t j = 0; j < words[i].size(); ++j) { if (words[i][j] != words[j][i]) return false; } return true; } };
[ "i.kuvykin@cognitive.com" ]
i.kuvykin@cognitive.com
8b34bba14620ee0c39adc6b74878e4edbccf1bfd
2e62eded4a05a565aa67c2557fed94d2dd2965cf
/TagsInventory/TagsInventory/MyDatabase.cpp
32226e351e8c89e33fb5d5582638f9602a0184b6
[]
no_license
jielmn/MyProjects
f34b308a1495f02e1cdbd887ee0faf3f103a8df8
0f0519991d0fdbb98ad0ef86e8bd472c2176a2aa
refs/heads/master
2021-06-03T11:56:40.884186
2020-05-29T09:47:55
2020-05-29T09:47:55
110,639,886
0
0
null
null
null
null
GB18030
C++
false
false
11,284
cpp
#include "stdafx.h" #include "MyDatabase.h" #include "MyEncrypt.h" #define FLOW_NUM_LEN 3 #define DB_TYPE_ORACLE 0 #define DB_TYPE_MYSQL 1 static int CountChar(const CString & str, char ch) { int iStart = -1; int cnt = 0; iStart = str.Find(ch, iStart + 1); while (iStart != -1) { cnt++; iStart = str.Find(ch, iStart + 1); } return cnt; } CMyDatabase::CMyDatabase() { m_nStatus = -1; m_bUtf8 = FALSE; m_nDbType = -1; } CMyDatabase::~CMyDatabase() { } int CMyDatabase::GetStatus() const { return m_nStatus; } void CMyDatabase::ReconnectDb() { char buf[8192]; char tmp[8192]; static BOOL bFist = TRUE; CString strSql; if (m_nStatus == STATUS_OPEN) { return; } try { m_database.Close(); m_nStatus = STATUS_CLOSE; g_cfg->GetConfig("odbc string", tmp, sizeof(tmp)); DWORD dwLen = sizeof(buf); MyDecrypt(tmp, buf, dwLen); m_database.OpenEx(buf, CDatabase::noOdbcDialog); if (bFist) { m_recordset.m_pDatabase = &m_database; bFist = FALSE; } g_cfg->GetConfig("odbc type", buf, sizeof(buf)); if (0 == _stricmp(buf, "oracle")) { m_nDbType = DB_TYPE_ORACLE; strSql = "SELECT sid, serial#, username, osuser FROM v$session where sid in(select session_id from v$locked_object);"; m_recordset.Open(CRecordset::forwardOnly, strSql, CRecordset::readOnly); while (!m_recordset.IsEOF()) { CString strValue[2]; m_recordset.GetFieldValue((short)0, strValue[0]); m_recordset.GetFieldValue((short)1, strValue[1]); CString strTemp; strTemp.Format("ALTER SYSTEM KILL SESSION '%s,%s';", strValue[0], strValue[1]); m_database.ExecuteSQL(strTemp); m_recordset.MoveNext(); } m_recordset.Close();//关闭记录集 } else { m_nDbType = DB_TYPE_MYSQL; m_bUtf8 = TRUE; } m_nStatus = STATUS_OPEN; } catch (CException* e) { e->GetErrorMessage(buf, sizeof(buf)); g_log->Output(ILog::LOG_SEVERITY_ERROR, buf); m_nStatus = STATUS_CLOSE; g_thrd_db->PostDelayMessage(RECONNECT_DB_TIME, g_handler_db, MSG_RECONNECT_DB); } ::PostMessage(g_hDlg, UM_SHOW_STATUS, STATUS_TYPE_DATABASE, m_nStatus); } void CMyDatabase::VerifyUser(const TagItem * pItem) { CString strSql; char buf[8192]; int static cnt = 0; cnt++; if ( m_nStatus == STATUS_CLOSE ) { return; } try { GetUid(buf, sizeof(buf), pItem->abyUid, pItem->dwUidLen); if (g_bLogVerifyID) { g_log->Output(ILog::LOG_SEVERITY_INFO, "verify id is %s\n", buf); } strSql.Format("select * from staff where ext1='%s'", buf); m_recordset.Open(CRecordset::forwardOnly, strSql, CRecordset::readOnly); // 存在记录,验证OK if (!m_recordset.IsEOF()) { CString v; m_recordset.GetFieldValue( (short)1, v ); strncpy(g_login_user.user_id, v, sizeof(g_login_user.user_id) - 1); m_recordset.GetFieldValue( (short)2, v ); if ( m_bUtf8) { Utf8ToAnsi(g_login_user.user_name, sizeof(g_login_user.user_name), v); } else { strncpy(g_login_user.user_name, v, sizeof(g_login_user.user_name) - 1); } memcpy(&g_login_user.user_tag_id, pItem, sizeof(TagItem)); // 验证成功 ::PostMessage(g_hDlg, UM_VERIFY_USER_RESULT, TRUE, 0); } //验证失败 else { ::PostMessage(g_hDlg, UM_VERIFY_USER_RESULT, FALSE, 0); } m_recordset.Close();//关闭记录集 } catch (CException* e) { e->GetErrorMessage(buf, sizeof(buf)); g_log->Output(ILog::LOG_SEVERITY_ERROR, buf); } } void CMyDatabase::SaveInventory(CSaveInvParam * pParam) { if (m_nStatus == STATUS_CLOSE) { NotifyUiError(g_hDlg, 1, "数据库没有连接上", TRUE, ""); return; } CTime now = CTime::GetCurrentTime(); CString strTime = now.Format("%Y-%m-%d %H:%M:%S"); char szFactoryId[64]; char szProductId[64]; g_cfg->GetConfig("factory code", szFactoryId, sizeof(szFactoryId)); g_cfg->GetConfig("product code", szProductId, sizeof(szProductId)); char buf[8192]; CString strTags; vector<TagItem *>::iterator it; for ( it = pParam->m_items.begin(); it != pParam->m_items.end(); ++it) { TagItem * pItem = *it; GetUid( buf, sizeof(buf), pItem->abyUid, pItem->dwUidLen ); if (strTags.GetLength() > 0) { strTags += ","; } strTags += buf; } CString strSql; strSql.Format("select max(id) from proceinfo;"); DWORD dwProceId = 0; try { m_recordset.Open(CRecordset::forwardOnly, strSql, CRecordset::readOnly); if (!m_recordset.IsEOF()) { CString strValue; m_recordset.GetFieldValue((short)0, strValue); sscanf(strValue, "%u", &dwProceId); } m_recordset.Close();//关闭记录集 } catch (CException* e) { OnDatabaseException(g_hDlg, e); return; } CString strTmp; // 开始事务 try { #ifdef _DEBUG if (m_database.m_bTransactionPending) { m_database.Rollback(); } #else m_database.Rollback(); #endif m_database.BeginTrans(); // 插入tag数据 for (it = pParam->m_items.begin(); it != pParam->m_items.end(); it++) { TagItem * pIem = *it; GetUid(buf, sizeof(buf), pIem->abyUid, pIem->dwUidLen); strSql.Format("insert into tagsinfo values('%s',%u);", buf, dwProceId + 1); m_database.ExecuteSQL(strSql); } CString strMaxBatchId; now = CTime::GetCurrentTime(); strTmp.Format("%s%s%s%%", szFactoryId, szProductId, pParam->m_strBatchId); strSql.Format("select proce_batch_id from proceinfo where proce_batch_id like '%s' order by proce_batch_id desc;", strTmp); m_recordset.Open(CRecordset::forwardOnly, strSql, CRecordset::readOnly); if (!m_recordset.IsEOF()) { m_recordset.GetFieldValue((short)0, strMaxBatchId); } m_recordset.Close();//关闭记录集 int nFlowId = 0; if (strMaxBatchId.GetLength() > 0) { DWORD dwFactoryLen = strlen(szFactoryId); DWORD dwProcCodeLen = strlen(szProductId); sscanf(strMaxBatchId.Mid(dwFactoryLen + dwProcCodeLen + pParam->m_strBatchId.GetLength(), FLOW_NUM_LEN), "%d", &nFlowId); } nFlowId++; strTmp.Format("%s%s%s%03d", szFactoryId, szProductId, pParam->m_strBatchId, nFlowId); CString strBatchId = strTmp; if (m_nDbType == DB_TYPE_ORACLE) { // 插入批量数据 strSql.Format("insert into proceinfo values ( %u, 100, '%s', to_date('%s','yyyy-mm-dd hh24:mi:ss'),'%s','%s')", dwProceId + 1, g_login_user.user_id, strTime, strTags, strBatchId); } else { // 插入批量数据 strSql.Format("insert into proceinfo values ( %u, 100, '%s', '%s','%s','%s')", dwProceId + 1, g_login_user.user_id, strTime, strTags, strBatchId); } m_database.ExecuteSQL(strSql); m_database.CommitTrans(); NotifyUiError( g_hDlg, 0, 0, FALSE, strBatchId); } catch (CException* e) { OnDatabaseException(g_hDlg, e); if (m_nStatus == STATUS_OPEN) { m_database.Rollback(); } return; } } void CMyDatabase::OnDatabaseException( HWND hWnd, CException* e, BOOL bNotifyUi /*= TRUE*/, void * pParam /*= 0*/) { char buf[8192]; e->GetErrorMessage(buf, sizeof(buf)); g_log->Output(ILog::LOG_SEVERITY_ERROR, buf); if (!bNotifyUi) { return; } BOOL bNeedReconnect = FALSE; if (m_nDbType == DB_TYPE_MYSQL) { if ( 0 != strstr(buf, "connection") || 0 != strstr(buf, "没有连接") || 0 != strstr(buf, "gone awaw") ) { bNeedReconnect = TRUE; m_nStatus = STATUS_CLOSE; } } else { // 看是ORACLE否断开连接 if (strstr(buf, "ORA-12152") != 0) { bNeedReconnect = TRUE; m_nStatus = STATUS_CLOSE; } } NotifyUiError( hWnd, 1, buf, bNeedReconnect, 0, pParam ); } void CMyDatabase::NotifyUiError(HWND hWnd, DWORD dwErrorID, const char * szErrDescription /*= 0*/, BOOL bNeedReconnect /*= FALSE*/, const char * szBatchId /*= 0*/, void * pParam /*= 0*/) { DbErrMsg * pDbErrMsg = new DbErrMsg; memset(pDbErrMsg, 0, sizeof(DbErrMsg)); pDbErrMsg->bDisconnected = bNeedReconnect; pDbErrMsg->dwErrId = dwErrorID; if (szErrDescription) { strncpy(pDbErrMsg->szErrDescription, szErrDescription, sizeof(pDbErrMsg->szErrDescription) - 1); } if (szBatchId) { strncpy(pDbErrMsg->szBatchId, szBatchId, sizeof(pDbErrMsg->szBatchId) - 1); } pDbErrMsg->pParam = pParam; ::PostMessage(hWnd, UM_DB_ERR_MSG, (WPARAM)pDbErrMsg, 0); } void CMyDatabase::Query(const LmnToolkits::MessageData * pParam) { char buf[8192]; CQueryParam * pQueryParam = (CQueryParam *)pParam; if (m_nStatus == STATUS_CLOSE) { NotifyUiError(g_hQueryDlg, 1, "数据库没有连接上", TRUE, ""); return; } DWORD dwOperatorLen = strlen(pQueryParam->m_szOperator); CString strSql; if (m_nDbType == DB_TYPE_ORACLE) { if (dwOperatorLen == 0) { strSql.Format("select a.id, a.procetype,b.stfname,a.procetime,a.tagbaseid,a.proce_batch_id from proceinfo a inner join staff b on a.proceman = b.stfid where a.procetime >= to_date('%s','yyyy-mm-dd hh24:mi:ss') " "AND a.procetime <= to_date('%s','yyyy-mm-dd hh24:mi:ss')", pQueryParam->m_szStartTime, pQueryParam->m_szEndTime); } else { strSql.Format("select a.id, a.procetype,b.stfname,a.procetime,a.tagbaseid,a.proce_batch_id from proceinfo a inner join staff b on a.proceman = b.stfid where a.procetime >= to_date('%s','yyyy-mm-dd hh24:mi:ss') " "AND a.procetime <= to_date('%s','yyyy-mm-dd hh24:mi:ss') " "AND a.procetime like '%%%s%%'", pQueryParam->m_szStartTime, pQueryParam->m_szEndTime, pQueryParam->m_szOperator); } } else { if (dwOperatorLen == 0) { strSql.Format("select a.id, a.procetype,b.stfname,a.procetime,a.tagbaseid,a.proce_batch_id from proceinfo a inner join staff b on a.proceman = b.stfid WHERE a.procetime >= '%s' " "AND a.procetime <= '%s' ", pQueryParam->m_szStartTime, pQueryParam->m_szEndTime ); } else { strSql.Format("select a.id, a.procetype,b.stfname,a.procetime,a.tagbaseid,a.proce_batch_id from proceinfo a inner join staff b on a.proceman = b.stfid WHERE a.procetime >= '%s' " "AND a.procetime <= '%s' " "AND b.stfname like '%%%s%%'", pQueryParam->m_szStartTime, pQueryParam->m_szEndTime, AnsiToUtf8( buf, sizeof(buf), pQueryParam->m_szOperator) ); } } try { m_recordset.Open(CRecordset::forwardOnly, strSql, CRecordset::readOnly); std::vector<QueryResult *> * pvRet = new std::vector<QueryResult *>; while (!m_recordset.IsEOF()) { QueryResult * pResult = new QueryResult; memset(pResult, 0, sizeof(QueryResult)); CString strRet; m_recordset.GetFieldValue((short)0, strRet); sscanf(strRet, " %lu", &pResult->dwId); m_recordset.GetFieldValue((short)1, strRet); sscanf(strRet, " %d", &pResult->nProcType); m_recordset.GetFieldValue((short)2, strRet); if (m_bUtf8) { Utf8ToAnsi(buf, sizeof(buf), strRet); strncpy(pResult->szOperator, buf, sizeof(pResult->szOperator) - 1); } else { strncpy(pResult->szOperator, strRet, sizeof(pResult->szOperator) - 1); } m_recordset.GetFieldValue((short)3, strRet); strncpy(pResult->szProcTime, strRet, sizeof(pResult->szProcTime) - 1); m_recordset.GetFieldValue((short)4, strRet); pResult->dwTagsCnt = CountChar(strRet, ',') + 1; m_recordset.GetFieldValue((short)5, strRet); strncpy(pResult->szBatchId, strRet, sizeof(pResult->szBatchId) - 1); pvRet->push_back(pResult); m_recordset.MoveNext(); } m_recordset.Close();//关闭记录集 NotifyUiError(g_hQueryDlg, 0, 0, FALSE, 0, pvRet ); } catch (CException* e) { OnDatabaseException(g_hQueryDlg, e); } }
[ "jielmn@aliyun.com" ]
jielmn@aliyun.com
c7bbbd86e56faa5cb42b2d1aed47120f5d77017d
7163f2414baab4f4179b519f0d72bea3493a2531
/strategy_pattern策略模式/strategy.cpp
1a389c37f421a5ddc6a8f7285cd1af03e10fa8ed
[]
no_license
lishujun5/design_Mode
91a9646d7aede08f16718169ad8f19f92adf2a98
2986ad4475c44c9e275fb038c54310f38b6234f3
refs/heads/master
2020-09-11T00:51:38.578242
2020-03-22T09:32:15
2020-03-22T09:32:15
221,885,473
0
0
null
null
null
null
UTF-8
C++
false
false
352
cpp
#include "strategy.h" double ReturnCash::AlgorithmInterrace(double amount) { if(amount>=condition && condition != 0 ) { return amount - amount/condition*PreReturnCash; } } double Discount::AlgorithmInterrace(double amount) { return amount*discount; } double NomalCash::AlgorithmInterrace(double amount) { return amount; }
[ "624297561@qq.com" ]
624297561@qq.com
4d86940dc8df70a14e0b2c4a45903e3b07aee6ed
6365c830bf8590819e876edc2c75eb29a8620c17
/exercise13/sorting.cpp
02909ca87b2f705d8bef19a5938f74b346f0e62f
[]
no_license
sulovm/SDP2018
0aec940dc6ea32e5372179caf6ff7b5289c6b0c8
9256cf7603d4712cb653e24de72092f038a08691
refs/heads/master
2020-03-31T06:36:47.807483
2019-01-16T23:32:30
2019-01-16T23:32:30
151,988,548
0
0
null
null
null
null
UTF-8
C++
false
false
4,251
cpp
#include <iostream> #include <vector> #include <queue> template <typename T> std::ostream& operator <<(std::ostream& out, const std::vector<T>& v) { if (v.empty() == true) { out << "[]"; return out; } out << "["; auto iter = v.begin(); auto iterAtLast = v.end() - 1; for (; iter != iterAtLast; iter++) //to exclude the last element { out << *iter << ";"; } out << *iterAtLast << "]"; return out; } template <typename T> void quickSort(std::vector<T>& v) { if (v.empty() == true) { //if empty - nothing to do return; } if (v.size() == 1) { //if only 1 element, it is sorted //nothing to do return; } if (v.size() == 2) { //if only 2 elements - put them into order if (v[0] > v[1]) { std::swap(v[0], v[1]); } return; } T pivot = v[0]; //split the vector into 2 vectors - one with the elements lesser than the pivot //and one with the elements greater than the pivot std::vector<T> lesserThanPivot; std::vector<T> greaterThanPivot; for (auto iter = v.begin(); iter != v.end(); iter++) { if (*iter < pivot) { lesserThanPivot.push_back(*iter); } else if (*iter > pivot) { greaterThanPivot.push_back(*iter); } } //now sort the two vectors quickSort(lesserThanPivot); quickSort(greaterThanPivot); //clear and fill the original vector with the two already sorted vectors v.clear(); v.insert(v.end(), lesserThanPivot.begin(), lesserThanPivot.end()); v.push_back(pivot); v.insert(v.end(), greaterThanPivot.begin(), greaterThanPivot.end()); } template <typename T> std::queue<T> makeQueueFromVector(const std::vector<T>& v) { std::queue<T> result; for (auto iter = v.begin(); iter != v.end(); iter++) { result.push(*iter); } return result; } template <typename T> std::vector<T> mergeSorted(const std::vector<T>& v1, const std::vector<T>& v2) { std::queue<T> q1 = makeQueueFromVector(v1); std::queue<T> q2 = makeQueueFromVector(v2); std::vector<T> result; while (q1.empty() == false && q2.empty() == false) { if (q1.front() < q2.front()) { result.push_back(q1.front()); q1.pop(); } else //successfully handles the case when the two fronts are equals { result.push_back(q2.front()); q2.pop(); } } //we will enter in only one of the two whiles below (because of the while above) while (q1.empty() == false) { result.push_back(q1.front()); q1.pop(); } while (q2.empty() == false) { result.push_back(q2.front()); q2.pop(); } return result; } template <typename T> void mergeSort(std::vector<T>& v) { if (v.empty() == true) { //if empty - nothing to do return; } if (v.size() == 1) { //if only 1 element, it is sorted //nothing to do return; } if (v.size() == 2) { //if only 2 elements - put them into order if (v[0] > v[1]) { std::swap(v[0], v[1]); } return; } //split the vector into two halfs auto iterMiddle = v.begin() + v.size() / 2; //iterator pointing at the middle element std::vector<T> firstHalf(v.begin(), iterMiddle); std::vector<T> secondHalf(iterMiddle, v.end()); //sort each half (recursively) mergeSort(firstHalf); mergeSort(secondHalf); //clear the original vector and merge the two sorted vectors into it keeping it sorted v.clear(); v = mergeSorted(firstHalf, secondHalf); } int main() { std::vector<int> v = {7, 3, 5, 1, 14, 6, 23, 22, 2, 17}; std::vector<int> v1 = v; std::cout << "Original vector: " << v << std::endl; quickSort(v); std::cout << "Sorted by Quicksort: " << v << std::endl; std::cout << std::endl; std::cout << "Original vector: " << v1 << std::endl; mergeSort(v1); std::cout << "Sorted by Mergesort: " << v1 << std::endl; return 0; }
[ "sulovmomchil@gmail.com" ]
sulovmomchil@gmail.com
aa5c69df5f178a07aca67cfc05174165ca73f9ce
40612d6221dfb6713965f3cc46b70d6ef444e31a
/src/rpcwallet.cpp
268320bb4dde34fbb036f15963324186fe8c1734
[ "MIT" ]
permissive
acornproject/acorn
d6c77b57705dbd6836d0bb02211d2eb4d0de92db
973252b12883af07d9aa99e723de3b4018ce0f06
refs/heads/master
2016-09-05T20:52:05.850626
2014-05-21T19:57:10
2014-05-21T19:57:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
61,694
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "wallet.h" #include "walletdb.h" #include "bitcoinrpc.h" #include "init.h" #include "base58.h" using namespace json_spirit; using namespace std; int64_t nWalletUnlockTime; static CCriticalSection cs_nWalletUnlockTime; extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry); static void accountingDeprecationCheck() { if (!GetBoolArg("-enableaccounts", false)) throw runtime_error( "Accounting API is deprecated and will be removed in future.\n" "It can easily result in negative or odd balances if misused or misunderstood, which has happened in the field.\n" "If you still want to enable it, add to your config file enableaccounts=1\n"); if (GetBoolArg("-staking", true)) throw runtime_error("If you want to use accounting API, staking must be disabled, add to your config file staking=0\n"); } std::string HelpRequiringPassphrase() { return pwalletMain->IsCrypted() ? "\nrequires wallet passphrase to be set with walletpassphrase first" : ""; } void EnsureWalletIsUnlocked() { if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); if (fWalletUnlockStakingOnly) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Wallet is unlocked for staking only."); } void WalletTxToJSON(const CWalletTx& wtx, Object& entry) { int confirms = wtx.GetDepthInMainChain(); entry.push_back(Pair("confirmations", confirms)); if (wtx.IsCoinBase() || wtx.IsCoinStake()) entry.push_back(Pair("generated", true)); if (confirms > 0) { entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex())); entry.push_back(Pair("blockindex", wtx.nIndex)); entry.push_back(Pair("blocktime", (boost::int64_t)(mapBlockIndex[wtx.hashBlock]->nTime))); } entry.push_back(Pair("txid", wtx.GetHash().GetHex())); entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime())); entry.push_back(Pair("timereceived", (boost::int64_t)wtx.nTimeReceived)); BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue) entry.push_back(Pair(item.first, item.second)); } string AccountFromValue(const Value& value) { string strAccount = value.get_str(); if (strAccount == "*") throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name"); return strAccount; } Value getinfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getinfo\n" "Returns an object containing various state info."); proxyType proxy; GetProxy(NET_IPV4, proxy); Object obj, diff; obj.push_back(Pair("version", FormatFullVersion())); obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION)); obj.push_back(Pair("walletversion", pwalletMain->GetVersion())); obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance()))); obj.push_back(Pair("newmint", ValueFromAmount(pwalletMain->GetNewMint()))); obj.push_back(Pair("stake", ValueFromAmount(pwalletMain->GetStake()))); obj.push_back(Pair("blocks", (int)nBestHeight)); obj.push_back(Pair("timeoffset", (boost::int64_t)GetTimeOffset())); obj.push_back(Pair("moneysupply", ValueFromAmount(pindexBest->nMoneySupply))); obj.push_back(Pair("connections", (int)vNodes.size())); obj.push_back(Pair("proxy", (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string()))); obj.push_back(Pair("ip", addrSeenByPeer.ToStringIP())); diff.push_back(Pair("proof-of-work", GetDifficulty())); diff.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true)))); obj.push_back(Pair("difficulty", diff)); obj.push_back(Pair("testnet", fTestNet)); obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime())); obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize())); obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee))); obj.push_back(Pair("mininput", ValueFromAmount(nMinimumInputValue))); if (pwalletMain->IsCrypted()) obj.push_back(Pair("unlocked_until", (boost::int64_t)nWalletUnlockTime / 1000)); obj.push_back(Pair("errors", GetWarnings("statusbar"))); return obj; } Value getnewpubkey(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getnewpubkey [account]\n" "Returns new public key for coinbase generation."); // Parse the account first so we don't generate a key if there's an error string strAccount; if (params.size() > 0) strAccount = AccountFromValue(params[0]); if (!pwalletMain->IsLocked()) pwalletMain->TopUpKeyPool(); // Generate a new key that is added to wallet CPubKey newKey; if (!pwalletMain->GetKeyFromPool(newKey, false)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); CKeyID keyID = newKey.GetID(); pwalletMain->SetAddressBookName(keyID, strAccount); vector<unsigned char> vchPubKey = newKey.Raw(); return HexStr(vchPubKey.begin(), vchPubKey.end()); } Value getnewaddress(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getnewaddress [account]\n" "Returns a new Acorn address for receiving payments. " "If [account] is specified (recommended), it is added to the address book " "so payments received with the address will be credited to [account]."); // Parse the account first so we don't generate a key if there's an error string strAccount; if (params.size() > 0) strAccount = AccountFromValue(params[0]); if (!pwalletMain->IsLocked()) pwalletMain->TopUpKeyPool(); // Generate a new key that is added to wallet CPubKey newKey; if (!pwalletMain->GetKeyFromPool(newKey, false)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); CKeyID keyID = newKey.GetID(); pwalletMain->SetAddressBookName(keyID, strAccount); return CBitcoinAddress(keyID).ToString(); } CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false) { CWalletDB walletdb(pwalletMain->strWalletFile); CAccount account; walletdb.ReadAccount(strAccount, account); bool bKeyUsed = false; // Check if the current key has been used if (account.vchPubKey.IsValid()) { CScript scriptPubKey; scriptPubKey.SetDestination(account.vchPubKey.GetID()); for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid(); ++it) { const CWalletTx& wtx = (*it).second; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) bKeyUsed = true; } } // Generate a new key if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed) { if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), strAccount); walletdb.WriteAccount(strAccount, account); } return CBitcoinAddress(account.vchPubKey.GetID()); } Value getaccountaddress(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaccountaddress <account>\n" "Returns the current Acorn address for receiving payments to this account."); // Parse the account first so we don't generate a key if there's an error string strAccount = AccountFromValue(params[0]); Value ret; ret = GetAccountAddress(strAccount).ToString(); return ret; } Value setaccount(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "setaccount <address> <account>\n" "Sets the account associated with the given address."); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Acorn address"); string strAccount; if (params.size() > 1) strAccount = AccountFromValue(params[1]); // Detect when changing the account of an address that is the 'unused current key' of another account: if (pwalletMain->mapAddressBook.count(address.Get())) { string strOldAccount = pwalletMain->mapAddressBook[address.Get()]; if (address == GetAccountAddress(strOldAccount)) GetAccountAddress(strOldAccount, true); } pwalletMain->SetAddressBookName(address.Get(), strAccount); return Value::null; } Value getaccount(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaccount <address>\n" "Returns the account associated with the given address."); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Acorn address"); string strAccount; map<CTxDestination, string>::iterator mi = pwalletMain->mapAddressBook.find(address.Get()); if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty()) strAccount = (*mi).second; return strAccount; } Value getaddressesbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaddressesbyaccount <account>\n" "Returns the list of addresses for the given account."); string strAccount = AccountFromValue(params[0]); // Find all addresses that have the given account Array ret; BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strName = item.second; if (strName == strAccount) ret.push_back(address.ToString()); } return ret; } Value sendtoaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 4) throw runtime_error( "sendtoaddress <address> <amount> [comment] [comment-to]\n" "<amount> is a real and is rounded to the nearest 0.000001" + HelpRequiringPassphrase()); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Acorn address"); // Amount int64_t nAmount = AmountFromValue(params[1]); // Wallet comments CWalletTx wtx; if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty()) wtx.mapValue["comment"] = params[2].get_str(); if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty()) wtx.mapValue["to"] = params[3].get_str(); if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx); if (strError != "") throw JSONRPCError(RPC_WALLET_ERROR, strError); return wtx.GetHash().GetHex(); } Value listaddressgroupings(const Array& params, bool fHelp) { if (fHelp) throw runtime_error( "listaddressgroupings\n" "Lists groups of addresses which have had their common ownership\n" "made public by common use as inputs or as the resulting change\n" "in past transactions"); Array jsonGroupings; map<CTxDestination, int64_t> balances = pwalletMain->GetAddressBalances(); BOOST_FOREACH(set<CTxDestination> grouping, pwalletMain->GetAddressGroupings()) { Array jsonGrouping; BOOST_FOREACH(CTxDestination address, grouping) { Array addressInfo; addressInfo.push_back(CBitcoinAddress(address).ToString()); addressInfo.push_back(ValueFromAmount(balances[address])); { LOCK(pwalletMain->cs_wallet); if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end()) addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second); } jsonGrouping.push_back(addressInfo); } jsonGroupings.push_back(jsonGrouping); } return jsonGroupings; } Value signmessage(const Array& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "signmessage <address> <message>\n" "Sign a message with the private key of an address"); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); string strMessage = params[1].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); CKey key; if (!pwalletMain->GetKey(keyID, key)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available"); CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; vector<unsigned char> vchSig; if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed"); return EncodeBase64(&vchSig[0], vchSig.size()); } Value verifymessage(const Array& params, bool fHelp) { if (fHelp || params.size() != 3) throw runtime_error( "verifymessage <address> <signature> <message>\n" "Verify a signed message"); string strAddress = params[0].get_str(); string strSign = params[1].get_str(); string strMessage = params[2].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); bool fInvalid = false; vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid); if (fInvalid) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding"); CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; CKey key; if (!key.SetCompactSignature(Hash(ss.begin(), ss.end()), vchSig)) return false; return (key.GetPubKey().GetID() == keyID); } Value getreceivedbyaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getreceivedbyaddress <address> [minconf=1]\n" "Returns the total amount received by <address> in transactions with at least [minconf] confirmations."); // Bitcoin address CBitcoinAddress address = CBitcoinAddress(params[0].get_str()); CScript scriptPubKey; if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Acorn address"); scriptPubKey.SetDestination(address.Get()); if (!IsMine(*pwalletMain,scriptPubKey)) return (double)0.0; // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); // Tally int64_t nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || wtx.IsCoinStake() || !wtx.IsFinal()) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; } return ValueFromAmount(nAmount); } void GetAccountAddresses(string strAccount, set<CTxDestination>& setAddress) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& item, pwalletMain->mapAddressBook) { const CTxDestination& address = item.first; const string& strName = item.second; if (strName == strAccount) setAddress.insert(address); } } Value getreceivedbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getreceivedbyaccount <account> [minconf=1]\n" "Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations."); accountingDeprecationCheck(); // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); // Get the set of pub keys assigned to account string strAccount = AccountFromValue(params[0]); set<CTxDestination> setAddress; GetAccountAddresses(strAccount, setAddress); // Tally int64_t nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || wtx.IsCoinStake() || !wtx.IsFinal()) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address)) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; } } return (double)nAmount / (double)COIN; } int64_t GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth) { int64_t nBalance = 0; // Tally wallet transactions for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!wtx.IsFinal() || wtx.GetDepthInMainChain() < 0) continue; int64_t nReceived, nSent, nFee; wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee); if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth && wtx.GetBlocksToMaturity() == 0) nBalance += nReceived; nBalance -= nSent + nFee; } // Tally internal accounting entries nBalance += walletdb.GetAccountCreditDebit(strAccount); return nBalance; } int64_t GetAccountBalance(const string& strAccount, int nMinDepth) { CWalletDB walletdb(pwalletMain->strWalletFile); return GetAccountBalance(walletdb, strAccount, nMinDepth); } Value getbalance(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getbalance [account] [minconf=1]\n" "If [account] is not specified, returns the server's total available balance.\n" "If [account] is specified, returns the balance in the account."); if (params.size() == 0) return ValueFromAmount(pwalletMain->GetBalance()); int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); if (params[0].get_str() == "*") { // Calculate total balance a different way from GetBalance() // (GetBalance() sums up all unspent TxOuts) // getbalance and getbalance '*' 0 should return the same number. int64_t nBalance = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!wtx.IsTrusted()) continue; int64_t allFee; string strSentAccount; list<pair<CTxDestination, int64_t> > listReceived; list<pair<CTxDestination, int64_t> > listSent; wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount); if (wtx.GetDepthInMainChain() >= nMinDepth && wtx.GetBlocksToMaturity() == 0) { BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listReceived) nBalance += r.second; } BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listSent) nBalance -= r.second; nBalance -= allFee; } return ValueFromAmount(nBalance); } accountingDeprecationCheck(); string strAccount = AccountFromValue(params[0]); int64_t nBalance = GetAccountBalance(strAccount, nMinDepth); return ValueFromAmount(nBalance); } Value movecmd(const Array& params, bool fHelp) { if (fHelp || params.size() < 3 || params.size() > 5) throw runtime_error( "move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n" "Move from one account in your wallet to another."); accountingDeprecationCheck(); string strFrom = AccountFromValue(params[0]); string strTo = AccountFromValue(params[1]); int64_t nAmount = AmountFromValue(params[2]); if (params.size() > 3) // unused parameter, used to be nMinDepth, keep type-checking it though (void)params[3].get_int(); string strComment; if (params.size() > 4) strComment = params[4].get_str(); CWalletDB walletdb(pwalletMain->strWalletFile); if (!walletdb.TxnBegin()) throw JSONRPCError(RPC_DATABASE_ERROR, "database error"); int64_t nNow = GetAdjustedTime(); // Debit CAccountingEntry debit; debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb); debit.strAccount = strFrom; debit.nCreditDebit = -nAmount; debit.nTime = nNow; debit.strOtherAccount = strTo; debit.strComment = strComment; walletdb.WriteAccountingEntry(debit); // Credit CAccountingEntry credit; credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb); credit.strAccount = strTo; credit.nCreditDebit = nAmount; credit.nTime = nNow; credit.strOtherAccount = strFrom; credit.strComment = strComment; walletdb.WriteAccountingEntry(credit); if (!walletdb.TxnCommit()) throw JSONRPCError(RPC_DATABASE_ERROR, "database error"); return true; } Value sendfrom(const Array& params, bool fHelp) { if (fHelp || params.size() < 3 || params.size() > 6) throw runtime_error( "sendfrom <fromaccount> <toaddress> <amount> [minconf=1] [comment] [comment-to]\n" "<amount> is a real and is rounded to the nearest 0.000001" + HelpRequiringPassphrase()); string strAccount = AccountFromValue(params[0]); CBitcoinAddress address(params[1].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Acorn address"); int64_t nAmount = AmountFromValue(params[2]); int nMinDepth = 1; if (params.size() > 3) nMinDepth = params[3].get_int(); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty()) wtx.mapValue["comment"] = params[4].get_str(); if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty()) wtx.mapValue["to"] = params[5].get_str(); EnsureWalletIsUnlocked(); // Check funds int64_t nBalance = GetAccountBalance(strAccount, nMinDepth); if (nAmount > nBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); // Send string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx); if (strError != "") throw JSONRPCError(RPC_WALLET_ERROR, strError); return wtx.GetHash().GetHex(); } Value sendmany(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 4) throw runtime_error( "sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n" "amounts are double-precision floating point numbers" + HelpRequiringPassphrase()); string strAccount = AccountFromValue(params[0]); Object sendTo = params[1].get_obj(); int nMinDepth = 1; if (params.size() > 2) nMinDepth = params[2].get_int(); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty()) wtx.mapValue["comment"] = params[3].get_str(); set<CBitcoinAddress> setAddress; vector<pair<CScript, int64_t> > vecSend; int64_t totalAmount = 0; BOOST_FOREACH(const Pair& s, sendTo) { CBitcoinAddress address(s.name_); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Acorn address: ")+s.name_); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_); setAddress.insert(address); CScript scriptPubKey; scriptPubKey.SetDestination(address.Get()); int64_t nAmount = AmountFromValue(s.value_); totalAmount += nAmount; vecSend.push_back(make_pair(scriptPubKey, nAmount)); } EnsureWalletIsUnlocked(); // Check funds int64_t nBalance = GetAccountBalance(strAccount, nMinDepth); if (totalAmount > nBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); // Send CReserveKey keyChange(pwalletMain); int64_t nFeeRequired = 0; bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired); if (!fCreated) { if (totalAmount + nFeeRequired > pwalletMain->GetBalance()) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds"); throw JSONRPCError(RPC_WALLET_ERROR, "Transaction creation failed"); } if (!pwalletMain->CommitTransaction(wtx, keyChange)) throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed"); return wtx.GetHash().GetHex(); } Value addmultisigaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 3) { string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n" "Add a nrequired-to-sign multisignature address to the wallet\"\n" "each key is a Acorn address or hex-encoded public key\n" "If [account] is specified, assign address to [account]."; throw runtime_error(msg); } int nRequired = params[0].get_int(); const Array& keys = params[1].get_array(); string strAccount; if (params.size() > 2) strAccount = AccountFromValue(params[2]); // Gather public keys if (nRequired < 1) throw runtime_error("a multisignature address must require at least one key to redeem"); if ((int)keys.size() < nRequired) throw runtime_error( strprintf("not enough keys supplied " "(got %"PRIszu" keys, but need at least %d to redeem)", keys.size(), nRequired)); std::vector<CKey> pubkeys; pubkeys.resize(keys.size()); for (unsigned int i = 0; i < keys.size(); i++) { const std::string& ks = keys[i].get_str(); // Case 1: Bitcoin address and we have full public key: CBitcoinAddress address(ks); if (address.IsValid()) { CKeyID keyID; if (!address.GetKeyID(keyID)) throw runtime_error( strprintf("%s does not refer to a key",ks.c_str())); CPubKey vchPubKey; if (!pwalletMain->GetPubKey(keyID, vchPubKey)) throw runtime_error( strprintf("no full public key for address %s",ks.c_str())); if (!vchPubKey.IsValid() || !pubkeys[i].SetPubKey(vchPubKey)) throw runtime_error(" Invalid public key: "+ks); } // Case 2: hex public key else if (IsHex(ks)) { CPubKey vchPubKey(ParseHex(ks)); if (!vchPubKey.IsValid() || !pubkeys[i].SetPubKey(vchPubKey)) throw runtime_error(" Invalid public key: "+ks); } else { throw runtime_error(" Invalid public key: "+ks); } } // Construct using pay-to-script-hash: CScript inner; inner.SetMultisig(nRequired, pubkeys); CScriptID innerID = inner.GetID(); pwalletMain->AddCScript(inner); pwalletMain->SetAddressBookName(innerID, strAccount); return CBitcoinAddress(innerID).ToString(); } Value addredeemscript(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) { string msg = "addredeemscript <redeemScript> [account]\n" "Add a P2SH address with a specified redeemScript to the wallet.\n" "If [account] is specified, assign address to [account]."; throw runtime_error(msg); } string strAccount; if (params.size() > 1) strAccount = AccountFromValue(params[1]); // Construct using pay-to-script-hash: vector<unsigned char> innerData = ParseHexV(params[0], "redeemScript"); CScript inner(innerData.begin(), innerData.end()); CScriptID innerID = inner.GetID(); pwalletMain->AddCScript(inner); pwalletMain->SetAddressBookName(innerID, strAccount); return CBitcoinAddress(innerID).ToString(); } struct tallyitem { int64_t nAmount; int nConf; tallyitem() { nAmount = 0; nConf = std::numeric_limits<int>::max(); } }; Value ListReceived(const Array& params, bool fByAccounts) { // Minimum confirmations int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); // Whether to include empty accounts bool fIncludeEmpty = false; if (params.size() > 1) fIncludeEmpty = params[1].get_bool(); // Tally map<CBitcoinAddress, tallyitem> mapTally; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || wtx.IsCoinStake() || !wtx.IsFinal()) continue; int nDepth = wtx.GetDepthInMainChain(); if (nDepth < nMinDepth) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address) || !IsMine(*pwalletMain, address)) continue; tallyitem& item = mapTally[address]; item.nAmount += txout.nValue; item.nConf = min(item.nConf, nDepth); } } // Reply Array ret; map<string, tallyitem> mapAccountTally; BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strAccount = item.second; map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address); if (it == mapTally.end() && !fIncludeEmpty) continue; int64_t nAmount = 0; int nConf = std::numeric_limits<int>::max(); if (it != mapTally.end()) { nAmount = (*it).second.nAmount; nConf = (*it).second.nConf; } if (fByAccounts) { tallyitem& item = mapAccountTally[strAccount]; item.nAmount += nAmount; item.nConf = min(item.nConf, nConf); } else { Object obj; obj.push_back(Pair("address", address.ToString())); obj.push_back(Pair("account", strAccount)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); ret.push_back(obj); } } if (fByAccounts) { for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it) { int64_t nAmount = (*it).second.nAmount; int nConf = (*it).second.nConf; Object obj; obj.push_back(Pair("account", (*it).first)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); ret.push_back(obj); } } return ret; } Value listreceivedbyaddress(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "listreceivedbyaddress [minconf=1] [includeempty=false]\n" "[minconf] is the minimum number of confirmations before payments are included.\n" "[includeempty] whether to include addresses that haven't received any payments.\n" "Returns an array of objects containing:\n" " \"address\" : receiving address\n" " \"account\" : the account of the receiving address\n" " \"amount\" : total amount received by the address\n" " \"confirmations\" : number of confirmations of the most recent transaction included"); return ListReceived(params, false); } Value listreceivedbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "listreceivedbyaccount [minconf=1] [includeempty=false]\n" "[minconf] is the minimum number of confirmations before payments are included.\n" "[includeempty] whether to include accounts that haven't received any payments.\n" "Returns an array of objects containing:\n" " \"account\" : the account of the receiving addresses\n" " \"amount\" : total amount received by addresses with this account\n" " \"confirmations\" : number of confirmations of the most recent transaction included"); accountingDeprecationCheck(); return ListReceived(params, true); } static void MaybePushAddress(Object & entry, const CTxDestination &dest) { CBitcoinAddress addr; if (addr.Set(dest)) entry.push_back(Pair("address", addr.ToString())); } void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret) { int64_t nFee; string strSentAccount; list<pair<CTxDestination, int64_t> > listReceived; list<pair<CTxDestination, int64_t> > listSent; wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount); bool fAllAccounts = (strAccount == string("*")); // Sent if ((!wtx.IsCoinStake()) && (!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount)) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& s, listSent) { Object entry; entry.push_back(Pair("account", strSentAccount)); MaybePushAddress(entry, s.first); entry.push_back(Pair("category", "send")); entry.push_back(Pair("amount", ValueFromAmount(-s.second))); entry.push_back(Pair("fee", ValueFromAmount(-nFee))); if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } } // Received if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth) { bool stop = false; BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& r, listReceived) { string account; if (pwalletMain->mapAddressBook.count(r.first)) account = pwalletMain->mapAddressBook[r.first]; if (fAllAccounts || (account == strAccount)) { Object entry; entry.push_back(Pair("account", account)); MaybePushAddress(entry, r.first); if (wtx.IsCoinBase() || wtx.IsCoinStake()) { if (wtx.GetDepthInMainChain() < 1) entry.push_back(Pair("category", "orphan")); else if (wtx.GetBlocksToMaturity() > 0) entry.push_back(Pair("category", "immature")); else entry.push_back(Pair("category", "generate")); } else { entry.push_back(Pair("category", "receive")); } if (!wtx.IsCoinStake()) entry.push_back(Pair("amount", ValueFromAmount(r.second))); else { entry.push_back(Pair("amount", ValueFromAmount(-nFee))); stop = true; // only one coinstake output } if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } if (stop) break; } } } void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret) { bool fAllAccounts = (strAccount == string("*")); if (fAllAccounts || acentry.strAccount == strAccount) { Object entry; entry.push_back(Pair("account", acentry.strAccount)); entry.push_back(Pair("category", "move")); entry.push_back(Pair("time", (boost::int64_t)acentry.nTime)); entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit))); entry.push_back(Pair("otheraccount", acentry.strOtherAccount)); entry.push_back(Pair("comment", acentry.strComment)); ret.push_back(entry); } } Value listtransactions(const Array& params, bool fHelp) { if (fHelp || params.size() > 3) throw runtime_error( "listtransactions [account] [count=10] [from=0]\n" "Returns up to [count] most recent transactions skipping the first [from] transactions for account [account]."); string strAccount = "*"; if (params.size() > 0) strAccount = params[0].get_str(); int nCount = 10; if (params.size() > 1) nCount = params[1].get_int(); int nFrom = 0; if (params.size() > 2) nFrom = params[2].get_int(); if (nCount < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count"); if (nFrom < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from"); Array ret; std::list<CAccountingEntry> acentries; CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, strAccount); // iterate backwards until we have nCount items to return: for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) { CWalletTx *const pwtx = (*it).second.first; if (pwtx != 0) ListTransactions(*pwtx, strAccount, 0, true, ret); CAccountingEntry *const pacentry = (*it).second.second; if (pacentry != 0) AcentryToJSON(*pacentry, strAccount, ret); if ((int)ret.size() >= (nCount+nFrom)) break; } // ret is newest to oldest if (nFrom > (int)ret.size()) nFrom = ret.size(); if ((nFrom + nCount) > (int)ret.size()) nCount = ret.size() - nFrom; Array::iterator first = ret.begin(); std::advance(first, nFrom); Array::iterator last = ret.begin(); std::advance(last, nFrom+nCount); if (last != ret.end()) ret.erase(last, ret.end()); if (first != ret.begin()) ret.erase(ret.begin(), first); std::reverse(ret.begin(), ret.end()); // Return oldest to newest return ret; } Value listaccounts(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "listaccounts [minconf=1]\n" "Returns Object that has account names as keys, account balances as values."); accountingDeprecationCheck(); int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); map<string, int64_t> mapAccountBalances; BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& entry, pwalletMain->mapAddressBook) { if (IsMine(*pwalletMain, entry.first)) // This address belongs to me mapAccountBalances[entry.second] = 0; } for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; int64_t nFee; string strSentAccount; list<pair<CTxDestination, int64_t> > listReceived; list<pair<CTxDestination, int64_t> > listSent; int nDepth = wtx.GetDepthInMainChain(); if (nDepth < 0) continue; wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount); mapAccountBalances[strSentAccount] -= nFee; BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& s, listSent) mapAccountBalances[strSentAccount] -= s.second; if (nDepth >= nMinDepth && wtx.GetBlocksToMaturity() == 0) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& r, listReceived) if (pwalletMain->mapAddressBook.count(r.first)) mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second; else mapAccountBalances[""] += r.second; } } list<CAccountingEntry> acentries; CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries); BOOST_FOREACH(const CAccountingEntry& entry, acentries) mapAccountBalances[entry.strAccount] += entry.nCreditDebit; Object ret; BOOST_FOREACH(const PAIRTYPE(string, int64_t)& accountBalance, mapAccountBalances) { ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second))); } return ret; } Value listsinceblock(const Array& params, bool fHelp) { if (fHelp) throw runtime_error( "listsinceblock [blockhash] [target-confirmations]\n" "Get all transactions in blocks since block [blockhash], or all transactions if omitted"); CBlockIndex *pindex = NULL; int target_confirms = 1; if (params.size() > 0) { uint256 blockId = 0; blockId.SetHex(params[0].get_str()); pindex = CBlockLocator(blockId).GetBlockIndex(); } if (params.size() > 1) { target_confirms = params[1].get_int(); if (target_confirms < 1) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); } int depth = pindex ? (1 + nBestHeight - pindex->nHeight) : -1; Array transactions; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++) { CWalletTx tx = (*it).second; if (depth == -1 || tx.GetDepthInMainChain() < depth) ListTransactions(tx, "*", 0, true, transactions); } uint256 lastblock; if (target_confirms == 1) { lastblock = hashBestChain; } else { int target_height = pindexBest->nHeight + 1 - target_confirms; CBlockIndex *block; for (block = pindexBest; block && block->nHeight > target_height; block = block->pprev) { } lastblock = block ? block->GetBlockHash() : 0; } Object ret; ret.push_back(Pair("transactions", transactions)); ret.push_back(Pair("lastblock", lastblock.GetHex())); return ret; } Value gettransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "gettransaction <txid>\n" "Get detailed information about <txid>"); uint256 hash; hash.SetHex(params[0].get_str()); Object entry; if (pwalletMain->mapWallet.count(hash)) { const CWalletTx& wtx = pwalletMain->mapWallet[hash]; TxToJSON(wtx, 0, entry); int64_t nCredit = wtx.GetCredit(); int64_t nDebit = wtx.GetDebit(); int64_t nNet = nCredit - nDebit; int64_t nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0); entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee))); if (wtx.IsFromMe()) entry.push_back(Pair("fee", ValueFromAmount(nFee))); WalletTxToJSON(wtx, entry); Array details; ListTransactions(pwalletMain->mapWallet[hash], "*", 0, false, details); entry.push_back(Pair("details", details)); } else { CTransaction tx; uint256 hashBlock = 0; if (GetTransaction(hash, tx, hashBlock)) { TxToJSON(tx, 0, entry); if (hashBlock == 0) entry.push_back(Pair("confirmations", 0)); else { entry.push_back(Pair("blockhash", hashBlock.GetHex())); map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight)); else entry.push_back(Pair("confirmations", 0)); } } } else throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction"); } return entry; } Value backupwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "backupwallet <destination>\n" "Safely copies wallet.dat to destination, which can be a directory or a path with filename."); string strDest = params[0].get_str(); if (!BackupWallet(*pwalletMain, strDest)) throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!"); return Value::null; } Value keypoolrefill(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "keypoolrefill [new-size]\n" "Fills the keypool." + HelpRequiringPassphrase()); unsigned int nSize = max(GetArg("-keypool", 100), (int64_t)0); if (params.size() > 0) { if (params[0].get_int() < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid size"); nSize = (unsigned int) params[0].get_int(); } EnsureWalletIsUnlocked(); pwalletMain->TopUpKeyPool(nSize); if (pwalletMain->GetKeyPoolSize() < nSize) throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool."); return Value::null; } void ThreadTopUpKeyPool(void* parg) { // Make this thread recognisable as the key-topping-up thread RenameThread("Acorn-key-top"); pwalletMain->TopUpKeyPool(); } void ThreadCleanWalletPassphrase(void* parg) { // Make this thread recognisable as the wallet relocking thread RenameThread("Acorn-lock-wa"); int64_t nMyWakeTime = GetTimeMillis() + *((int64_t*)parg) * 1000; ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime); if (nWalletUnlockTime == 0) { nWalletUnlockTime = nMyWakeTime; do { if (nWalletUnlockTime==0) break; int64_t nToSleep = nWalletUnlockTime - GetTimeMillis(); if (nToSleep <= 0) break; LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime); MilliSleep(nToSleep); ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime); } while(1); if (nWalletUnlockTime) { nWalletUnlockTime = 0; pwalletMain->Lock(); } } else { if (nWalletUnlockTime < nMyWakeTime) nWalletUnlockTime = nMyWakeTime; } LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime); delete (int64_t*)parg; } Value walletpassphrase(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 3)) throw runtime_error( "walletpassphrase <passphrase> <timeout> [stakingonly]\n" "Stores the wallet decryption key in memory for <timeout> seconds.\n" "if [stakingonly] is true sending functions are disabled."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called."); if (!pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already unlocked, use walletlock first if need to change unlock settings."); // Note that the walletpassphrase is stored in params[0] which is not mlock()ed SecureString strWalletPass; strWalletPass.reserve(100); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. strWalletPass = params[0].get_str().c_str(); if (strWalletPass.length() > 0) { if (!pwalletMain->Unlock(strWalletPass)) throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect."); } else throw runtime_error( "walletpassphrase <passphrase> <timeout>\n" "Stores the wallet decryption key in memory for <timeout> seconds."); NewThread(ThreadTopUpKeyPool, NULL); int64_t* pnSleepTime = new int64_t(params[1].get_int64()); NewThread(ThreadCleanWalletPassphrase, pnSleepTime); // ppcoin: if user OS account compromised prevent trivial sendmoney commands if (params.size() > 2) fWalletUnlockStakingOnly = params[2].get_bool(); else fWalletUnlockStakingOnly = false; return Value::null; } Value walletpassphrasechange(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2)) throw runtime_error( "walletpassphrasechange <oldpassphrase> <newpassphrase>\n" "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called."); // TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strOldWalletPass; strOldWalletPass.reserve(100); strOldWalletPass = params[0].get_str().c_str(); SecureString strNewWalletPass; strNewWalletPass.reserve(100); strNewWalletPass = params[1].get_str().c_str(); if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1) throw runtime_error( "walletpassphrasechange <oldpassphrase> <newpassphrase>\n" "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>."); if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass)) throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect."); return Value::null; } Value walletlock(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0)) throw runtime_error( "walletlock\n" "Removes the wallet encryption key from memory, locking the wallet.\n" "After calling this method, you will need to call walletpassphrase again\n" "before being able to call any methods which require the wallet to be unlocked."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called."); { LOCK(cs_nWalletUnlockTime); pwalletMain->Lock(); nWalletUnlockTime = 0; } return Value::null; } Value encryptwallet(const Array& params, bool fHelp) { if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1)) throw runtime_error( "encryptwallet <passphrase>\n" "Encrypts the wallet with <passphrase>."); if (fHelp) return true; if (pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called."); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strWalletPass; strWalletPass.reserve(100); strWalletPass = params[0].get_str().c_str(); if (strWalletPass.length() < 1) throw runtime_error( "encryptwallet <passphrase>\n" "Encrypts the wallet with <passphrase>."); if (!pwalletMain->EncryptWallet(strWalletPass)) throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet."); // BDB seems to have a bad habit of writing old data into // slack space in .dat files; that is bad if the old data is // unencrypted private keys. So: StartShutdown(); return "wallet encrypted; Acorn server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup."; } class DescribeAddressVisitor : public boost::static_visitor<Object> { public: Object operator()(const CNoDestination &dest) const { return Object(); } Object operator()(const CKeyID &keyID) const { Object obj; CPubKey vchPubKey; pwalletMain->GetPubKey(keyID, vchPubKey); obj.push_back(Pair("isscript", false)); obj.push_back(Pair("pubkey", HexStr(vchPubKey.Raw()))); obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed())); return obj; } Object operator()(const CScriptID &scriptID) const { Object obj; obj.push_back(Pair("isscript", true)); CScript subscript; pwalletMain->GetCScript(scriptID, subscript); std::vector<CTxDestination> addresses; txnouttype whichType; int nRequired; ExtractDestinations(subscript, whichType, addresses, nRequired); obj.push_back(Pair("script", GetTxnOutputType(whichType))); obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end()))); Array a; BOOST_FOREACH(const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); obj.push_back(Pair("addresses", a)); if (whichType == TX_MULTISIG) obj.push_back(Pair("sigsrequired", nRequired)); return obj; } }; Value validateaddress(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "validateaddress <address>\n" "Return information about <address>."); CBitcoinAddress address(params[0].get_str()); bool isValid = address.IsValid(); Object ret; ret.push_back(Pair("isvalid", isValid)); if (isValid) { CTxDestination dest = address.Get(); string currentAddress = address.ToString(); ret.push_back(Pair("address", currentAddress)); bool fMine = IsMine(*pwalletMain, dest); ret.push_back(Pair("ismine", fMine)); if (fMine) { Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest); ret.insert(ret.end(), detail.begin(), detail.end()); } if (pwalletMain->mapAddressBook.count(dest)) ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest])); } return ret; } Value validatepubkey(const Array& params, bool fHelp) { if (fHelp || !params.size() || params.size() > 2) throw runtime_error( "validatepubkey <pubkey>\n" "Return information about <pubkey>."); std::vector<unsigned char> vchPubKey = ParseHex(params[0].get_str()); CPubKey pubKey(vchPubKey); bool isValid = pubKey.IsValid(); bool isCompressed = pubKey.IsCompressed(); CKeyID keyID = pubKey.GetID(); CBitcoinAddress address; address.Set(keyID); Object ret; ret.push_back(Pair("isvalid", isValid)); if (isValid) { CTxDestination dest = address.Get(); string currentAddress = address.ToString(); ret.push_back(Pair("address", currentAddress)); bool fMine = IsMine(*pwalletMain, dest); ret.push_back(Pair("ismine", fMine)); ret.push_back(Pair("iscompressed", isCompressed)); if (fMine) { Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest); ret.insert(ret.end(), detail.begin(), detail.end()); } if (pwalletMain->mapAddressBook.count(dest)) ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest])); } return ret; } // ppcoin: reserve balance from being staked for network protection Value reservebalance(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "reservebalance [<reserve> [amount]]\n" "<reserve> is true or false to turn balance reserve on or off.\n" "<amount> is a real and rounded to cent.\n" "Set reserve amount not participating in network protection.\n" "If no parameters provided current setting is printed.\n"); if (params.size() > 0) { bool fReserve = params[0].get_bool(); if (fReserve) { if (params.size() == 1) throw runtime_error("must provide amount to reserve balance.\n"); int64_t nAmount = AmountFromValue(params[1]); nAmount = (nAmount / CENT) * CENT; // round to cent if (nAmount < 0) throw runtime_error("amount cannot be negative.\n"); nReserveBalance = nAmount; } else { if (params.size() > 1) throw runtime_error("cannot specify amount to turn off reserve.\n"); nReserveBalance = 0; } } Object result; result.push_back(Pair("reserve", (nReserveBalance > 0))); result.push_back(Pair("amount", ValueFromAmount(nReserveBalance))); return result; } // ppcoin: check wallet integrity Value checkwallet(const Array& params, bool fHelp) { if (fHelp || params.size() > 0) throw runtime_error( "checkwallet\n" "Check wallet for integrity.\n"); int nMismatchSpent; int64_t nBalanceInQuestion; pwalletMain->FixSpentCoins(nMismatchSpent, nBalanceInQuestion, true); Object result; if (nMismatchSpent == 0) result.push_back(Pair("wallet check passed", true)); else { result.push_back(Pair("mismatched spent coins", nMismatchSpent)); result.push_back(Pair("amount in question", ValueFromAmount(nBalanceInQuestion))); } return result; } // ppcoin: repair wallet Value repairwallet(const Array& params, bool fHelp) { if (fHelp || params.size() > 0) throw runtime_error( "repairwallet\n" "Repair wallet if checkwallet reports any problem.\n"); int nMismatchSpent; int64_t nBalanceInQuestion; pwalletMain->FixSpentCoins(nMismatchSpent, nBalanceInQuestion); Object result; if (nMismatchSpent == 0) result.push_back(Pair("wallet check passed", true)); else { result.push_back(Pair("mismatched spent coins", nMismatchSpent)); result.push_back(Pair("amount affected by repair", ValueFromAmount(nBalanceInQuestion))); } return result; } // NovaCoin: resend unconfirmed wallet transactions Value resendtx(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "resendtx\n" "Re-send unconfirmed transactions.\n" ); ResendWalletTransactions(true); return Value::null; } // ppcoin: make a public-private key pair Value makekeypair(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "makekeypair [prefix]\n" "Make a public/private key pair.\n" "[prefix] is optional preferred prefix for the public key.\n"); string strPrefix = ""; if (params.size() > 0) strPrefix = params[0].get_str(); CKey key; key.MakeNewKey(false); CPrivKey vchPrivKey = key.GetPrivKey(); Object result; result.push_back(Pair("PrivateKey", HexStr<CPrivKey::iterator>(vchPrivKey.begin(), vchPrivKey.end()))); result.push_back(Pair("PublicKey", HexStr(key.GetPubKey().Raw()))); return result; }
[ "prjacorn@gmail.com" ]
prjacorn@gmail.com
da2cc7a18f0f9112fee0d634ea5c3b439afc7fdf
37c1a88c539c00421c1faaca7d61656de6d4dc26
/nodegtk.cpp
ba7fb28307b8085873950998777be89c6bde4cfa
[]
no_license
Strawhatspirates/node-gtk
bbf51a755e5124d0320ebb699d136bfa97d47d4e
7f49a62ee2db3e40e233a7382b18281ac52a9fa7
refs/heads/master
2021-01-25T04:58:00.932933
2015-02-05T08:11:20
2015-02-05T08:11:20
29,980,196
3
0
null
null
null
null
UTF-8
C++
false
false
407
cpp
#include <node.h> #include <nan.h> #include <v8.h> #include "Gwindow.h" using namespace v8; NAN_METHOD(checkFrame) { NanScope(); int argc; char **argv; createTestwindow(argc,argv); NanReturnValue(NanNew("1")); } void init(Handle<Object> target) { target->Set(NanNew<String>("checkFrame"), NanNew<FunctionTemplate>(checkFrame)->GetFunction()); } NODE_MODULE(nodegtk, init)
[ "plasmashadowx@gmail.com" ]
plasmashadowx@gmail.com
83e72e3991916659e221b50611482f7fe58dd2e3
d035380bb2675bd306537fdf9ecf82c7d4607f7b
/src/telox-tx.cpp
e86519d4fedbc0919b4512a7006897fed1b797cd
[]
no_license
teloxproject/telox
5212123c72990aa07a0076e29d6c90da2302ee71
233df4b1da591c4f9c23ab38f14fecfc524d84aa
refs/heads/master
2020-04-08T12:57:54.656317
2018-11-28T18:08:51
2018-11-28T18:08:51
159,192,945
0
0
null
null
null
null
UTF-8
C++
false
false
20,280
cpp
// Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "base58.h" #include "clientversion.h" #include "coins.h" #include "core_io.h" #include "keystore.h" #include "primitives/block.h" // for MAX_BLOCK_SIZE #include "primitives/transaction.h" #include "script/script.h" #include "script/sign.h" #include "ui_interface.h" // for _(...) #include "univalue/univalue.h" #include "util.h" #include "utilmoneystr.h" #include "utilstrencodings.h" #include <stdio.h> #include <boost/algorithm/string.hpp> #include <boost/assign/list_of.hpp> using namespace boost::assign; using namespace std; static bool fCreateBlank; static map<string, UniValue> registers; CClientUIInterface uiInterface; static bool AppInitRawTx(int argc, char* argv[]) { // // Parameters // ParseParameters(argc, argv); // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) if (!SelectParamsFromCommandLine()) { fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n"); return false; } fCreateBlank = GetBoolArg("-create", false); if (argc < 2 || mapArgs.count("-?") || mapArgs.count("-help")) { // First part of help message is specific to this utility std::string strUsage = _("Telox Core telox-tx utility version") + " " + FormatFullVersion() + "\n\n" + _("Usage:") + "\n" + " telox-tx [options] <hex-tx> [commands] " + _("Update hex-encoded telox transaction") + "\n" + " telox-tx [options] -create [commands] " + _("Create hex-encoded telox transaction") + "\n" + "\n"; fprintf(stdout, "%s", strUsage.c_str()); strUsage = HelpMessageGroup(_("Options:")); strUsage += HelpMessageOpt("-?", _("This help message")); strUsage += HelpMessageOpt("-create", _("Create new, empty TX.")); strUsage += HelpMessageOpt("-json", _("Select JSON output")); strUsage += HelpMessageOpt("-txid", _("Output only the hex-encoded transaction id of the resultant transaction.")); strUsage += HelpMessageOpt("-regtest", _("Enter regression test mode, which uses a special chain in which blocks can be solved instantly.")); strUsage += HelpMessageOpt("-testnet", _("Use the test network")); fprintf(stdout, "%s", strUsage.c_str()); strUsage = HelpMessageGroup(_("Commands:")); strUsage += HelpMessageOpt("delin=N", _("Delete input N from TX")); strUsage += HelpMessageOpt("delout=N", _("Delete output N from TX")); strUsage += HelpMessageOpt("in=TXID:VOUT", _("Add input to TX")); strUsage += HelpMessageOpt("locktime=N", _("Set TX lock time to N")); strUsage += HelpMessageOpt("nversion=N", _("Set TX version to N")); strUsage += HelpMessageOpt("outaddr=VALUE:ADDRESS", _("Add address-based output to TX")); strUsage += HelpMessageOpt("outscript=VALUE:SCRIPT", _("Add raw script output to TX")); strUsage += HelpMessageOpt("sign=SIGHASH-FLAGS", _("Add zero or more signatures to transaction") + ". " + _("This command requires JSON registers:") + _("prevtxs=JSON object") + ", " + _("privatekeys=JSON object") + ". " + _("See signrawtransaction docs for format of sighash flags, JSON objects.")); fprintf(stdout, "%s", strUsage.c_str()); strUsage = HelpMessageGroup(_("Register Commands:")); strUsage += HelpMessageOpt("load=NAME:FILENAME", _("Load JSON file FILENAME into register NAME")); strUsage += HelpMessageOpt("set=NAME:JSON-STRING", _("Set register NAME to given JSON-STRING")); fprintf(stdout, "%s", strUsage.c_str()); return false; } return true; } static void RegisterSetJson(const string& key, const string& rawJson) { UniValue val; if (!val.read(rawJson)) { string strErr = "Cannot parse JSON for key " + key; throw runtime_error(strErr); } registers[key] = val; } static void RegisterSet(const string& strInput) { // separate NAME:VALUE in string size_t pos = strInput.find(':'); if ((pos == string::npos) || (pos == 0) || (pos == (strInput.size() - 1))) throw runtime_error("Register input requires NAME:VALUE"); string key = strInput.substr(0, pos); string valStr = strInput.substr(pos + 1, string::npos); RegisterSetJson(key, valStr); } static void RegisterLoad(const string& strInput) { // separate NAME:FILENAME in string size_t pos = strInput.find(':'); if ((pos == string::npos) || (pos == 0) || (pos == (strInput.size() - 1))) throw runtime_error("Register load requires NAME:FILENAME"); string key = strInput.substr(0, pos); string filename = strInput.substr(pos + 1, string::npos); FILE* f = fopen(filename.c_str(), "r"); if (!f) { string strErr = "Cannot open file " + filename; throw runtime_error(strErr); } // load file chunks into one big buffer string valStr; while ((!feof(f)) && (!ferror(f))) { char buf[4096]; int bread = fread(buf, 1, sizeof(buf), f); if (bread <= 0) break; valStr.insert(valStr.size(), buf, bread); } if (ferror(f)) { string strErr = "Error reading file " + filename; throw runtime_error(strErr); } fclose(f); // evaluate as JSON buffer register RegisterSetJson(key, valStr); } static void MutateTxVersion(CMutableTransaction& tx, const string& cmdVal) { int64_t newVersion = atoi64(cmdVal); if (newVersion < 1 || newVersion > CTransaction::CURRENT_VERSION) throw runtime_error("Invalid TX version requested"); tx.nVersion = (int)newVersion; } static void MutateTxLocktime(CMutableTransaction& tx, const string& cmdVal) { int64_t newLocktime = atoi64(cmdVal); if (newLocktime < 0LL || newLocktime > 0xffffffffLL) throw runtime_error("Invalid TX locktime requested"); tx.nLockTime = (unsigned int)newLocktime; } static void MutateTxAddInput(CMutableTransaction& tx, const string& strInput) { // separate TXID:VOUT in string size_t pos = strInput.find(':'); if ((pos == string::npos) || (pos == 0) || (pos == (strInput.size() - 1))) throw runtime_error("TX input missing separator"); // extract and validate TXID string strTxid = strInput.substr(0, pos); if ((strTxid.size() != 64) || !IsHex(strTxid)) throw runtime_error("invalid TX input txid"); uint256 txid(strTxid); static const unsigned int minTxOutSz = 9; static const unsigned int maxVout = MAX_BLOCK_SIZE / minTxOutSz; // extract and validate vout string strVout = strInput.substr(pos + 1, string::npos); int vout = atoi(strVout); if ((vout < 0) || (vout > (int)maxVout)) throw runtime_error("invalid TX input vout"); // append to transaction input list CTxIn txin(txid, vout); tx.vin.push_back(txin); } static void MutateTxAddOutAddr(CMutableTransaction& tx, const string& strInput) { // separate VALUE:ADDRESS in string size_t pos = strInput.find(':'); if ((pos == string::npos) || (pos == 0) || (pos == (strInput.size() - 1))) throw runtime_error("TX output missing separator"); // extract and validate VALUE string strValue = strInput.substr(0, pos); CAmount value; if (!ParseMoney(strValue, value)) throw runtime_error("invalid TX output value"); // extract and validate ADDRESS string strAddr = strInput.substr(pos + 1, string::npos); CBitcoinAddress addr(strAddr); if (!addr.IsValid()) throw runtime_error("invalid TX output address"); // build standard output script via GetScriptForDestination() CScript scriptPubKey = GetScriptForDestination(addr.Get()); // construct TxOut, append to transaction output list CTxOut txout(value, scriptPubKey); tx.vout.push_back(txout); } static void MutateTxAddOutScript(CMutableTransaction& tx, const string& strInput) { // separate VALUE:SCRIPT in string size_t pos = strInput.find(':'); if ((pos == string::npos) || (pos == 0)) throw runtime_error("TX output missing separator"); // extract and validate VALUE string strValue = strInput.substr(0, pos); CAmount value; if (!ParseMoney(strValue, value)) throw runtime_error("invalid TX output value"); // extract and validate script string strScript = strInput.substr(pos + 1, string::npos); CScript scriptPubKey = ParseScript(strScript); // throws on err // construct TxOut, append to transaction output list CTxOut txout(value, scriptPubKey); tx.vout.push_back(txout); } static void MutateTxDelInput(CMutableTransaction& tx, const string& strInIdx) { // parse requested deletion index int inIdx = atoi(strInIdx); if (inIdx < 0 || inIdx >= (int)tx.vin.size()) { string strErr = "Invalid TX input index '" + strInIdx + "'"; throw runtime_error(strErr.c_str()); } // delete input from transaction tx.vin.erase(tx.vin.begin() + inIdx); } static void MutateTxDelOutput(CMutableTransaction& tx, const string& strOutIdx) { // parse requested deletion index int outIdx = atoi(strOutIdx); if (outIdx < 0 || outIdx >= (int)tx.vout.size()) { string strErr = "Invalid TX output index '" + strOutIdx + "'"; throw runtime_error(strErr.c_str()); } // delete output from transaction tx.vout.erase(tx.vout.begin() + outIdx); } static const unsigned int N_SIGHASH_OPTS = 6; static const struct { const char* flagStr; int flags; } sighashOptions[N_SIGHASH_OPTS] = { {"ALL", SIGHASH_ALL}, {"NONE", SIGHASH_NONE}, {"SINGLE", SIGHASH_SINGLE}, {"ALL|ANYONECANPAY", SIGHASH_ALL | SIGHASH_ANYONECANPAY}, {"NONE|ANYONECANPAY", SIGHASH_NONE | SIGHASH_ANYONECANPAY}, {"SINGLE|ANYONECANPAY", SIGHASH_SINGLE | SIGHASH_ANYONECANPAY}, }; static bool findSighashFlags(int& flags, const string& flagStr) { flags = 0; for (unsigned int i = 0; i < N_SIGHASH_OPTS; i++) { if (flagStr == sighashOptions[i].flagStr) { flags = sighashOptions[i].flags; return true; } } return false; } uint256 ParseHashUO(map<string, UniValue>& o, string strKey) { if (!o.count(strKey)) return 0; return ParseHashUV(o[strKey], strKey); } vector<unsigned char> ParseHexUO(map<string, UniValue>& o, string strKey) { if (!o.count(strKey)) { vector<unsigned char> emptyVec; return emptyVec; } return ParseHexUV(o[strKey], strKey); } static void MutateTxSign(CMutableTransaction& tx, const string& flagStr) { int nHashType = SIGHASH_ALL; if (flagStr.size() > 0) if (!findSighashFlags(nHashType, flagStr)) throw runtime_error("unknown sighash flag/sign option"); vector<CTransaction> txVariants; txVariants.push_back(tx); // mergedTx will end up with all the signatures; it // starts as a clone of the raw tx: CMutableTransaction mergedTx(txVariants[0]); bool fComplete = true; CCoinsView viewDummy; CCoinsViewCache view(&viewDummy); if (!registers.count("privatekeys")) throw runtime_error("privatekeys register variable must be set."); bool fGivenKeys = false; CBasicKeyStore tempKeystore; UniValue keysObj = registers["privatekeys"]; fGivenKeys = true; for (unsigned int kidx = 0; kidx < keysObj.count(); kidx++) { if (!keysObj[kidx].isStr()) throw runtime_error("privatekey not a string"); CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(keysObj[kidx].getValStr()); if (!fGood) throw runtime_error("privatekey not valid"); CKey key = vchSecret.GetKey(); tempKeystore.AddKey(key); } // Add previous txouts given in the RPC call: if (!registers.count("prevtxs")) throw runtime_error("prevtxs register variable must be set."); UniValue prevtxsObj = registers["prevtxs"]; { for (unsigned int previdx = 0; previdx < prevtxsObj.count(); previdx++) { UniValue prevOut = prevtxsObj[previdx]; if (!prevOut.isObject()) throw runtime_error("expected prevtxs internal object"); map<string, UniValue::VType> types = map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM)("scriptPubKey", UniValue::VSTR); if (!prevOut.checkObject(types)) throw runtime_error("prevtxs internal object typecheck fail"); uint256 txid = ParseHashUV(prevOut["txid"], "txid"); int nOut = atoi(prevOut["vout"].getValStr()); if (nOut < 0) throw runtime_error("vout must be positive"); vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey")); CScript scriptPubKey(pkData.begin(), pkData.end()); { CCoinsModifier coins = view.ModifyCoins(txid); if (coins->IsAvailable(nOut) && coins->vout[nOut].scriptPubKey != scriptPubKey) { string err("Previous output scriptPubKey mismatch:\n"); err = err + coins->vout[nOut].scriptPubKey.ToString() + "\nvs:\n" + scriptPubKey.ToString(); throw runtime_error(err); } if ((unsigned int)nOut >= coins->vout.size()) coins->vout.resize(nOut + 1); coins->vout[nOut].scriptPubKey = scriptPubKey; coins->vout[nOut].nValue = 0; // we don't know the actual output value } // if redeemScript given and private keys given, // add redeemScript to the tempKeystore so it can be signed: if (fGivenKeys && scriptPubKey.IsPayToScriptHash() && prevOut.exists("redeemScript")) { UniValue v = prevOut["redeemScript"]; vector<unsigned char> rsData(ParseHexUV(v, "redeemScript")); CScript redeemScript(rsData.begin(), rsData.end()); tempKeystore.AddCScript(redeemScript); } } } const CKeyStore& keystore = tempKeystore; bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE); // Sign what we can: for (unsigned int i = 0; i < mergedTx.vin.size(); i++) { CTxIn& txin = mergedTx.vin[i]; const CCoins* coins = view.AccessCoins(txin.prevout.hash); if (!coins || !coins->IsAvailable(txin.prevout.n)) { fComplete = false; continue; } const CScript& prevPubKey = coins->vout[txin.prevout.n].scriptPubKey; txin.scriptSig.clear(); // Only sign SIGHASH_SINGLE if there's a corresponding output: if (!fHashSingle || (i < mergedTx.vout.size())) SignSignature(keystore, prevPubKey, mergedTx, i, nHashType); // ... and merge in other signatures: BOOST_FOREACH (const CTransaction& txv, txVariants) { txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig); } if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i))) fComplete = false; } if (fComplete) { // do nothing... for now // perhaps store this for later optional JSON output } tx = mergedTx; } static void MutateTx(CMutableTransaction& tx, const string& command, const string& commandVal) { if (command == "nversion") MutateTxVersion(tx, commandVal); else if (command == "locktime") MutateTxLocktime(tx, commandVal); else if (command == "delin") MutateTxDelInput(tx, commandVal); else if (command == "in") MutateTxAddInput(tx, commandVal); else if (command == "delout") MutateTxDelOutput(tx, commandVal); else if (command == "outaddr") MutateTxAddOutAddr(tx, commandVal); else if (command == "outscript") MutateTxAddOutScript(tx, commandVal); else if (command == "sign") MutateTxSign(tx, commandVal); else if (command == "load") RegisterLoad(commandVal); else if (command == "set") RegisterSet(commandVal); else throw runtime_error("unknown command"); } static void OutputTxJSON(const CTransaction& tx) { UniValue entry(UniValue::VOBJ); TxToUniv(tx, 0, entry); string jsonOutput = entry.write(4); fprintf(stdout, "%s\n", jsonOutput.c_str()); } static void OutputTxHash(const CTransaction& tx) { string strHexHash = tx.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id) fprintf(stdout, "%s\n", strHexHash.c_str()); } static void OutputTxHex(const CTransaction& tx) { string strHex = EncodeHexTx(tx); fprintf(stdout, "%s\n", strHex.c_str()); } static void OutputTx(const CTransaction& tx) { if (GetBoolArg("-json", false)) OutputTxJSON(tx); else if (GetBoolArg("-txid", false)) OutputTxHash(tx); else OutputTxHex(tx); } static string readStdin() { char buf[4096]; string ret; while (!feof(stdin)) { size_t bread = fread(buf, 1, sizeof(buf), stdin); ret.append(buf, bread); if (bread < sizeof(buf)) break; } if (ferror(stdin)) throw runtime_error("error reading stdin"); boost::algorithm::trim_right(ret); return ret; } static int CommandLineRawTx(int argc, char* argv[]) { string strPrint; int nRet = 0; try { // Skip switches; Permit common stdin convention "-" while (argc > 1 && IsSwitchChar(argv[1][0]) && (argv[1][1] != 0)) { argc--; argv++; } CTransaction txDecodeTmp; int startArg; if (!fCreateBlank) { // require at least one param if (argc < 2) throw runtime_error("too few parameters"); // param: hex-encoded telox transaction string strHexTx(argv[1]); if (strHexTx == "-") // "-" implies standard input strHexTx = readStdin(); if (!DecodeHexTx(txDecodeTmp, strHexTx)) throw runtime_error("invalid transaction encoding"); startArg = 2; } else startArg = 1; CMutableTransaction tx(txDecodeTmp); for (int i = startArg; i < argc; i++) { string arg = argv[i]; string key, value; size_t eqpos = arg.find('='); if (eqpos == string::npos) key = arg; else { key = arg.substr(0, eqpos); value = arg.substr(eqpos + 1); } MutateTx(tx, key, value); } OutputTx(tx); } catch (boost::thread_interrupted) { throw; } catch (std::exception& e) { strPrint = string("error: ") + e.what(); nRet = EXIT_FAILURE; } catch (...) { PrintExceptionContinue(NULL, "CommandLineRawTx()"); throw; } if (strPrint != "") { fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str()); } return nRet; } int main(int argc, char* argv[]) { SetupEnvironment(); try { if (!AppInitRawTx(argc, argv)) return EXIT_FAILURE; } catch (std::exception& e) { PrintExceptionContinue(&e, "AppInitRawTx()"); return EXIT_FAILURE; } catch (...) { PrintExceptionContinue(NULL, "AppInitRawTx()"); return EXIT_FAILURE; } int ret = EXIT_FAILURE; try { ret = CommandLineRawTx(argc, argv); } catch (std::exception& e) { PrintExceptionContinue(&e, "CommandLineRawTx()"); } catch (...) { PrintExceptionContinue(NULL, "CommandLineRawTx()"); } return ret; }
[ "telox@i.ua" ]
telox@i.ua
407cba51698fbe2945f1b96b879268036ed22ff9
55bb84592fbbb48f321a56a118d507dc2241fea2
/Starting_Out_Games_Graphics/Source_Code/Chapter 02/TypeCast/TypeCast/TypeCast.cpp
8ab19ff4cd985320f582c77d607d54f82197efeb
[]
no_license
tdiliberto19/cpp-practice
8f801fedf5bf6fba56dc8120c6c2b36d2bc0ce0b
f5068e4fb7abb70219564024cb36041fc45370e1
refs/heads/master
2020-11-24T04:36:07.731061
2020-05-27T22:11:57
2020-05-27T22:11:57
227,964,906
0
0
null
null
null
null
UTF-8
C++
false
false
708
cpp
// This program uses a type cast to avoid integer division. #include <iostream> using namespace std; int main() { int books; // Number of books to read int months; // Number of months spent reading double perMonth;// Average number of books per month // Get the number of books the user plans to read. cout << "How many books do you plan to read? "; cin >> books; // Get the number of months it will take. cout << "How many months will it take you to read them? "; cin >> months; // Calculate and display the average number of // books per month. perMonth = static_cast<double>(books) / months; cout << "That is " << perMonth << " books per month.\n"; return 0; }
[ "tdiliberto19@berkeley.edu" ]
tdiliberto19@berkeley.edu
dfb94cacabd4a68e69cf2d9b48b628e56a72f439
ff41519dbbcf5e36c67e2ff85319fa3c36b69291
/lab4/paxos_exec.cpp
edd998e18b6c33fd2f4988e523a8c2f0e250f192
[]
no_license
banaka/AOS
fd9893d6fb31330c2f5a6432871b19daea937567
dc48934d0d3440f8c3cb0f71267edb0809a700b5
refs/heads/master
2021-01-01T19:06:09.276825
2014-11-06T17:25:50
2014-11-06T17:25:50
24,524,091
1
1
null
null
null
null
UTF-8
C++
false
false
6,457
cpp
// Basic routines for Paxos implementation #include "make_unique.h" #include "paxmsg.h" #include "paxserver.h" #include "log.h" bool my_trim_func(const std::unique_ptr<Paxlog::tup>& myTup){ return (*myTup).executed; } void paxserver::execute_arg(const struct execute_arg& ex_arg) { LOG(l::DEBUG, id_str() << " execute_arg:" << ex_arg << " state:"<< paxlog.latest_exec() <<"\n" ); //Way to check Check if the request is already been taken care of for (auto it = exec_rid_cache.begin(); it != exec_rid_cache.end(); ++it ){ //std::cout << (*it).first << (*it).second<<std::endl; if(((*it).first == ex_arg.nid) && ((*it).second == ex_arg.rid)){ LOG(l::DEBUG, id_str() << "The request has already been processed\n"); net->drop(this, ex_arg, " The request has already been processsed."); return; } } if(primary()){ if(paxlog.find_rid(ex_arg.nid, ex_arg.rid)){ LOG(l::DEBUG, id_str() << " find_rid Pass, The request is being processsed." <<"\n" ); net->drop(this, ex_arg, " The request is being processsed."); return; } std::set<node_id_t> servers = get_other_servers(vc_state.view); //Generate a new View timestamp for the request //viewstamp_t new_vs= paxlog.latest_accept(); //Not using this because this seems to be made for use with view change viewstamp_t new_vs; new_vs.vid = vc_state.view.vid; new_vs.ts = ts; ts += 1 ; paxlog.set_latest_accept(new_vs); //LOG the request //Adding one server to count of other servers so as to get the count of total servers paxlog.log(ex_arg.nid, ex_arg.rid, new_vs, ex_arg.request, servers.size() + 1 , net->now()); //Send for Voting to every replica for(const auto& serv : servers){ auto new_rep_arg = std::make_unique<struct replicate_arg>(new_vs, ex_arg, paxlog.latest_exec()); net->send(this, serv, std::move(new_rep_arg)); } LOG(l::DEBUG, id_str() << " Logged and sent for Vote for Request:" << ex_arg.request <<"\n" ); }else { //Send execute_fail to the client so that it can send request to the correct Primary auto new_execute_fail = std::make_unique<struct execute_fail>(vc_state.view.vid, vc_state.view.primary, ex_arg.rid); net->send(this, ex_arg.nid, std::move(new_execute_fail)); } //MASSERT(0, "execute_arg not implemented\n"); } void paxserver::replicate_arg(const struct replicate_arg& repl_arg) { //1. Try and execute the operations untill the committed in the message and update lastest_seen //2. Reply with the Viewstamp LOG(l::DEBUG, id_str() << " replicate_arg:" << repl_arg << " latest_exec:"<< paxlog.latest_exec() <<"\n" ); if(!primary()) { //Execute all the Operatins the Replica Can for(auto it = paxlog.begin(); it != paxlog.end(); ++it) { //We need to make sure that the View Id is same therefore the comparison has been performed between the //ViewStamps and not just the timestamps if((paxlog.latest_exec() <= repl_arg.committed) && paxlog.next_to_exec(it)){ paxlog.execute(*it); std::string result = paxop_on_paxobj(*it); vc_state.latest_seen.ts += 1; //So that every request which can be executed is executed.. it = paxlog.begin(); if(paxlog.latest_accept() <= repl_arg.committed) paxlog.set_latest_accept(repl_arg.committed); LOG(l::DEBUG, id_str() << " Executed:" << paxlog.latest_exec() << " result:" << result <<"\n"); } } paxlog.trim_front(my_trim_func); //Not needed because the inc_resp at the primary is going to take care of incrementing it only for the valid vs. //if(vc_state.latest_seen < repl_arg.vs) { int total_server_count = get_serv_cnt(vc_state.view);//(get_other_servers(vc_state.view)).size() + 1; paxlog.log(repl_arg.arg.nid, repl_arg.arg.rid, repl_arg.vs, repl_arg.arg.request, total_server_count, net->now()); //First log then send ACK auto new_rep_res = std::make_unique<struct replicate_res>(repl_arg.vs); net->send(this, vc_state.view.primary, std::move(new_rep_res)); LOG(l::DEBUG, id_str() << " Logged and Ack the Request from Primary" <<"\n"); } } void paxserver::replicate_res(const struct replicate_res& repl_res) { //1. Log the respone only primary should be getting these messages. //2. When the count of the response is more than half the server count Send Accept_arg message to all LOG(l::DEBUG, id_str() << " replicate_res:" << repl_res << " latest_exec:" << paxlog.latest_exec() <<"\n"); if(primary()) { if(!paxlog.incr_resp(repl_res.vs)){ LOG(l::DEBUG, id_str() << " Got request for already executed request and then truncated from log" <<"\n" ); return; } for(auto it = paxlog.begin(); it != paxlog.end(); ++it) { //This if condition will only pass for the message which has been passed to the function. if(((*it)->resp_cnt > (*it)->serv_cnt/2 ) && paxlog.next_to_exec(it) ) { paxlog.execute(*it); std::string result = paxop_on_paxobj(*it); vc_state.latest_seen.ts += 1; LOG(l::DEBUG, id_str() << " Executed:" << paxlog.latest_exec() << " result:" << result <<"\n"); //Respond to the client auto new_exe_succ = std::make_unique<struct execute_success>(result, (*it)->rid); net->send(this, (*it)->src, std::move(new_exe_succ)); } } paxlog.trim_front(my_trim_func); if(paxlog.empty()){//(paxlog.begin() == paxlog.end()){ //send Accept messages to rest of the servers std::set<node_id_t> servers = get_other_servers(vc_state.view); for(const auto& serv:servers) { auto new_acc_arg = std::make_unique<struct accept_arg>(repl_res.vs); net->send(this, serv, std::move(new_acc_arg)); } } } //MASSERT(0, "replicate_res not implemented\n"); } void paxserver::accept_arg(const struct accept_arg& acc_arg) { LOG(l::DEBUG, id_str() <<" accept_arg:" << acc_arg << " latest_exec:"<< paxlog.latest_exec() <<"\n" ); for(auto it = paxlog.begin(); it != paxlog.end(); ++it) { //if((paxlog.latest_exec() <= acc_arg.committed) && paxlog.next_to_exec(it)){ if(paxlog.next_to_exec(it)){ paxlog.execute(*it); std::string result = paxop_on_paxobj(*it); vc_state.latest_seen.ts += 1; LOG(l::DEBUG, id_str() << " Executed:" << paxlog.latest_exec() << " result:" << result <<"\n"); it = paxlog.begin(); } } paxlog.trim_front(my_trim_func); // MASSERT(0, "accept_arg not implemented\n"); }
[ "banaka@github.com" ]
banaka@github.com
63122fb9bc42f8c07eb7ce5b02c826eb4a85a111
dc0b1da910fca8446652aabf53397531cc94c5f4
/aws-cpp-sdk-dynamodb/source/model/DescribeTableResult.cpp
7f62518061fa27dd62ca8ec98161e31641556922
[ "JSON", "MIT", "Apache-2.0" ]
permissive
capeanalytics/aws-sdk-cpp
19db86298a6daaee59c4b9fba82acedacd658bdf
e88f75add5a9433601b6d46fe738e493da56ac3b
refs/heads/master
2020-04-06T04:03:12.337555
2017-05-11T13:31:39
2017-05-11T13:31:39
57,893,688
0
0
Apache-2.0
2018-07-30T16:46:55
2016-05-02T13:51:23
C++
UTF-8
C++
false
false
1,338
cpp
/* * 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. */ #include <aws/dynamodb/model/DescribeTableResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::DynamoDB::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; DescribeTableResult::DescribeTableResult() { } DescribeTableResult::DescribeTableResult(const AmazonWebServiceResult<JsonValue>& result) { *this = result; } DescribeTableResult& DescribeTableResult::operator =(const AmazonWebServiceResult<JsonValue>& result) { const JsonValue& jsonValue = result.GetPayload(); if(jsonValue.ValueExists("Table")) { m_table = jsonValue.GetObject("Table"); } return *this; }
[ "henso@amazon.com" ]
henso@amazon.com
8d2801bd9f8f12d980cd7cb8e60a57a3ab6792cf
d128c6f3a6316b03b74845979a74488baa087534
/srcmisc/slowpipe.cpp
e2aaae917e3716fef57d2050bb8f27acf7f77091
[]
no_license
wikimedia/analytics-udplog
733b7a08cc7378ecd62adbf831bdb2a94d5dbbb8
8964b83c15a9949522bbb1d994120e8898cf6a38
refs/heads/master
2023-06-30T06:59:21.712337
2023-05-23T16:29:42
2023-05-24T13:37:19
8,012,771
0
0
null
null
null
null
UTF-8
C++
false
false
739
cpp
#include "../srclib/PosixClock.h" #include <stdlib.h> #include <unistd.h> int main(int argc, char** argv) { long long rate = 1e6; // bytes per second if (argc > 1) { rate = atoll(argv[1]); } const int bufSize = 32768; char buffer[bufSize]; ssize_t bytesRead; PosixClock clock(CLOCK_REALTIME); PosixClock::Time t = clock.Get(); PosixClock::Time currentTime; PosixClock::Time maxDrift(0.001); for (;;) { bytesRead = read(STDIN_FILENO, buffer, bufSize); if (bytesRead <= 0) { return 0; } write(STDOUT_FILENO, buffer, bytesRead); currentTime = clock.Get(); if (currentTime - t > maxDrift) { t = currentTime; } t += PosixClock::Time((double)bytesRead / rate); clock.NanoSleep(TIMER_ABSTIME, t); } }
[ "tstarling@wikimedia.org" ]
tstarling@wikimedia.org
88a2e36964cb8e509bdf42116ce7fe78f650c1af
c3f4f6adb53381483658fde5671c84cd4a15975c
/Ex3.1/Ex3.1/MainFrm.cpp
03a9d90b9b9e07d1d6cb6257d6937ec273ce9517
[]
no_license
LTS123456/LTS01
40fadc08ceb392b34b3f039943f684783f17f796
2b6129d9a5751736a84ff9b8042b874bcf035631
refs/heads/master
2021-03-26T02:21:16.817381
2020-05-25T15:31:48
2020-05-25T15:31:48
247,664,137
0
0
null
null
null
null
GB18030
C++
false
false
1,766
cpp
// MainFrm.cpp : CMainFrame 类的实现 // #include "stdafx.h" #include "Ex3.1.h" #include "MainFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CMainFrame IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd) BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) ON_WM_CREATE() END_MESSAGE_MAP() static UINT indicators[] = { ID_SEPARATOR, // 状态行指示器 ID_INDICATOR_CAPS, ID_INDICATOR_NUM, ID_INDICATOR_SCRL, }; // CMainFrame 构造/析构 CMainFrame::CMainFrame() { // TODO: 在此添加成员初始化代码 } CMainFrame::~CMainFrame() { } int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CFrameWnd::OnCreate(lpCreateStruct) == -1) return -1; if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) || !m_wndToolBar.LoadToolBar(IDR_MAINFRAME)) { TRACE0("未能创建工具栏\n"); return -1; // 未能创建 } if (!m_wndStatusBar.Create(this)) { TRACE0("未能创建状态栏\n"); return -1; // 未能创建 } m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT)); // TODO: 如果不需要可停靠工具栏,则删除这三行 m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY); EnableDocking(CBRS_ALIGN_ANY); DockControlBar(&m_wndToolBar); return 0; } BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) { if( !CFrameWnd::PreCreateWindow(cs) ) return FALSE; // TODO: 在此处通过修改 // CREATESTRUCT cs 来修改窗口类或样式 return TRUE; } // CMainFrame 诊断 #ifdef _DEBUG void CMainFrame::AssertValid() const { CFrameWnd::AssertValid(); } void CMainFrame::Dump(CDumpContext& dc) const { CFrameWnd::Dump(dc); } #endif //_DEBUG // CMainFrame 消息处理程序
[ "1216859581@qq.com" ]
1216859581@qq.com
0dc914a9c1136939baa0a0e83197a3d2408f3dbb
ffeb539d40243ce50bb0d83a57abec2624c26e57
/src/net/service_error.h
d6306dd0733d9f6aa5f43b2707564a6041a824cc
[]
no_license
Michael-Z/dooqu_server
f9b016dbc1fd5c573744244e86701304b80f4d37
55f86d8785ad02644a1ebe1b5b800db5ae491110
refs/heads/master
2021-01-15T12:36:26.230163
2015-07-23T05:33:21
2015-07-23T05:33:21
null
0
0
null
null
null
null
GB18030
C++
false
false
412
h
#ifndef __NET_SERVICE_ERROR_H__ #define __NET_SERVICE_ERROR_H__ namespace dooqu_server { namespace net { class service_error { public: //NET ERROR是指客户端的网络层断开 static const int CLIENT_NET_ERROR = 0; /// static const int CLIENT_EXIT = 1; static const int DATA_OUT_OF_BUFFER = 2; static const int SERVER_CLOSEING = 3; static const int OK = 99; }; } } #endif
[ "51045352@qq.com" ]
51045352@qq.com
16f7ea1413c27d06efaaf16e8d04f1b1cc1f4265
c258c99fa1af1d76f5c44c644aa2ca68975914bd
/plugins/http_plugin/http_plugin.cpp
854dc060b4e147bf58ad269342c507103a955ce3
[ "MIT" ]
permissive
hot-chain/hotchain
fdfaf7681c082c3e584bce1f6c73f62f63159562
4e147b63675a5a09d5f3b87b54b909164ee64ea9
refs/heads/master
2020-03-13T10:24:19.631089
2019-04-02T09:27:55
2019-04-02T09:27:55
131,082,835
2
2
null
null
null
null
UTF-8
C++
false
false
8,009
cpp
#include <hotc/http_plugin/http_plugin.hpp> #include <fc/network/ip.hpp> #include <fc/log/logger_config.hpp> #include <boost/asio.hpp> #include <boost/optional.hpp> #include <websocketpp/config/asio_client.hpp> #include <websocketpp/config/asio.hpp> #include <websocketpp/server.hpp> #include <websocketpp/config/asio_client.hpp> #include <websocketpp/client.hpp> #include <websocketpp/logger/stub.hpp> #include <thread> #include <memory> namespace hotc { namespace asio = boost::asio; using std::map; using std::string; using boost::optional; using boost::asio::ip::tcp; using std::shared_ptr; using websocketpp::connection_hdl; namespace detail { struct asio_with_stub_log : public websocketpp::config::asio { typedef asio_with_stub_log type; typedef asio base; typedef base::concurrency_type concurrency_type; typedef base::request_type request_type; typedef base::response_type response_type; typedef base::message_type message_type; typedef base::con_msg_manager_type con_msg_manager_type; typedef base::endpoint_msg_manager_type endpoint_msg_manager_type; /// Custom Logging policies /*typedef websocketpp::log::syslog<concurrency_type, websocketpp::log::elevel> elog_type; typedef websocketpp::log::syslog<concurrency_type, websocketpp::log::alevel> alog_type; */ //typedef base::alog_type alog_type; //typedef base::elog_type elog_type; typedef websocketpp::log::stub elog_type; typedef websocketpp::log::stub alog_type; typedef base::rng_type rng_type; struct transport_config : public base::transport_config { typedef type::concurrency_type concurrency_type; typedef type::alog_type alog_type; typedef type::elog_type elog_type; typedef type::request_type request_type; typedef type::response_type response_type; typedef websocketpp::transport::asio::basic_socket::endpoint socket_type; }; typedef websocketpp::transport::asio::endpoint<transport_config> transport_type; static const long timeout_open_handshake = 0; }; } using websocket_server_type = websocketpp::server<detail::asio_with_stub_log>; class http_plugin_impl { public: //shared_ptr<std::thread> http_thread; //asio::io_service http_ios; map<string,url_handler> url_handlers; optional<tcp::endpoint> listen_endpoint; websocket_server_type server; }; http_plugin::http_plugin():my(new http_plugin_impl()){} http_plugin::~http_plugin(){} void http_plugin::set_program_options(options_description&, options_description& cfg) { cfg.add_options() ("http-server-endpoint", bpo::value<string>()->default_value("127.0.0.1:8888"), "The local IP and port to listen for incoming http connections.") ; } void http_plugin::plugin_initialize(const variables_map& options) { if(options.count("http-server-endpoint")) { #if 0 auto lipstr = options.at("http-server-endpoint").as< string >(); auto fcep = fc::ip::endpoint::from_string(lipstr); my->listen_endpoint = tcp::endpoint(boost::asio::ip::address_v4::from_string((string)fcep.get_address()), fcep.port()); #endif auto resolver = std::make_shared<tcp::resolver>( std::ref( app().get_io_service() ) ); if( options.count( "http-server-endpoint" ) ) { auto lipstr = options.at("http-server-endpoint").as< string >(); auto host = lipstr.substr( 0, lipstr.find(':') ); auto port = lipstr.substr( host.size()+1, lipstr.size() ); idump((host)(port)); tcp::resolver::query query( tcp::v4(), host.c_str(), port.c_str() ); my->listen_endpoint = *resolver->resolve( query); ilog("configured http to listen on ${h}:${p}", ("h",host)("p",port)); } // uint32_t addr = my->listen_endpoint->address().to_v4().to_ulong(); // auto fcep = fc::ip::endpoint (addr,my->listen_endpoint->port()); } } void http_plugin::plugin_startup() { if(my->listen_endpoint) { //my->http_thread = std::make_shared<std::thread>([&](){ ilog("start processing http thread"); try { my->server.clear_access_channels(websocketpp::log::alevel::all); my->server.init_asio(&app().get_io_service()); //&my->http_ios); my->server.set_reuse_addr(true); my->server.set_http_handler([&](connection_hdl hdl) { auto con = my->server.get_con_from_hdl(hdl); try { //ilog("handle http request: ${url}", ("url",con->get_uri()->str())); //ilog("${body}", ("body", con->get_request_body())); auto body = con->get_request_body(); auto resource = con->get_uri()->get_resource(); auto handler_itr = my->url_handlers.find(resource); if(handler_itr != my->url_handlers.end()) { handler_itr->second(resource, body, [con,this](int code, string body) { con->set_body(body); con->set_status(websocketpp::http::status_code::value(code)); con->append_header("Access-Control-Allow-Origin", "*"); }); } else { wlog("404 - not found: ${ep}", ("ep",resource)); con->set_body("Unknown Endpoint"); con->set_status(websocketpp::http::status_code::not_found); } } catch( const fc::exception& e ) { elog( "http: ${e}", ("e",e.to_detail_string())); con->set_body(e.to_detail_string()); con->set_status(websocketpp::http::status_code::internal_server_error); } catch( const std::exception& e ) { elog( "http: ${e}", ("e",e.what())); con->set_body(e.what()); con->set_status(websocketpp::http::status_code::internal_server_error); } catch( ... ) { con->set_body("unknown exception"); con->set_status(websocketpp::http::status_code::internal_server_error); } }); ilog("start listening for http requests"); my->server.listen(*my->listen_endpoint); my->server.start_accept(); // my->http_ios.run(); ilog("http io service exit"); } catch ( const fc::exception& e ){ elog( "http: ${e}", ("e",e.to_detail_string())); } catch ( const std::exception& e ){ elog( "http: ${e}", ("e",e.what())); } catch (...) { elog("error thrown from http io service"); } //}); } } void http_plugin::plugin_shutdown() { // if(my->http_thread) { if(my->server.is_listening()) my->server.stop_listening(); // my->http_ios.stop(); // my->http_thread->join(); // my->http_thread.reset(); // } } void http_plugin::add_handler(const string& url, const url_handler& handler) { ilog( "add api url: ${c}", ("c",url) ); app().get_io_service().post([=](){ my->url_handlers.insert(std::make_pair(url,handler)); }); } }
[ "hotc001@163.com" ]
hotc001@163.com
f1dbd356c4ad0584f99ba6f22af832ecc641b3d3
67a48a7a2db56247fdd84474efa35124565fd8b9
/Codeforces/1452/1542d.cpp
950f49b7863dde03a45fc83530e5896f6a69b945
[]
no_license
qazz625/Competitive-Programming-Codes
e3de31f9276f84e919a6017b2cf781c946809862
e5df9cdc4714d78b7b6a7535ed7a45e07d3781c3
refs/heads/master
2022-08-30T07:57:55.172867
2022-08-10T08:02:07
2022-08-10T08:02:07
242,182,922
0
0
null
null
null
null
UTF-8
C++
false
false
2,067
cpp
#include <bits/stdc++.h> using namespace std; #define int long long int mod = 998244353; #ifndef ONLINE_JUDGE #define _GLIBCXX_DEBUG #include "../../../debug.cpp" #endif //USING 1 BASED INDEXING int dp[600][600]; int32_t main(){ int n; cin >> n; vector<pair<char, int>> arr(n+1); for(int i=1; i<=n; i++){ cin >> arr[i].first; if(arr[i].first == '+') cin >> arr[i].second; } int ans = 0; for(int i=1; i<=n; i++){ if(arr[i].first == '-') continue; //calculate number of ways to select x numbers less or equal to than a[j] from 1 to i-1 for(int j=0; j<=n; j++) for(int k=0; k<=n; k++) dp[j][k] = 0; dp[0][0] = 1; for(int j=1; j<i; j++){ //dont choose current element for(int k=0; k<=n; k++){ dp[j][k] += dp[j-1][k]; dp[j][k] %= mod; } //choose current if(arr[j].first == '-'){ for(int k=0; k<=n-1; k++){ dp[j][k] += dp[j-1][k+1]; dp[j][k] %= mod; } dp[j][0] += dp[j-1][0]; dp[j][0] %= mod; } else if(arr[j].second < arr[i].second){ for(int k=1; k<=n; k++){ dp[j][k] += dp[j-1][k-1]; dp[j][k] %= mod; } } else{ for(int k=0; k<=n; k++){ dp[j][k] += dp[j-1][k]; dp[j][k] %= mod; } } } for(int k=1; k<=n; k++){ dp[i][k] += dp[i-1][k-1]; dp[i][k] %= mod; } for(int j=i+1; j<=n; j++){ //dont choose current element for(int k=0; k<=n; k++){ dp[j][k] += dp[j-1][k]; dp[j][k] %= mod; } //choose current if(arr[j].first == '-'){ for(int k=0; k<=n-1; k++){ dp[j][k] += dp[j-1][k+1]; dp[j][k] %= mod; } dp[j][0] += dp[j-1][0]; dp[j][0] %= mod; } else if(arr[j].second <= arr[i].second){ for(int k=2; k<=n; k++){ dp[j][k] += dp[j-1][k-1]; dp[j][k] %= mod; } } else{ for(int k=0; k<=n; k++){ dp[j][k] += dp[j-1][k]; dp[j][k] %= mod; } } } int tot = 0; for(int j=1; j<=n; j++){ tot += dp[n][j]; tot %= mod; } tot %= mod; ans += tot*arr[i].second; ans %= mod; } cout << ans << "\n"; }
[ "arun49804@gmail.com" ]
arun49804@gmail.com
f8c08c53b3b582775002c60579461ee2f92d420a
02508aa773dcbd9939eb879952ee2cb3dd90bcad
/c10/core/impl/FakeGuardImpl.h
2d47db0fdb18471a282351324d98f24cbc984330
[ "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "BSL-1.0", "Apache-2.0" ]
permissive
dhivyadharshin/pytorch
d8a3b7f3c03e21e776ea34788d13743467b738c8
6a170011876bb8bd1909e8f60fba1270ac7a5577
refs/heads/master
2023-07-18T07:31:52.918955
2021-08-17T18:12:01
2021-08-17T18:12:01
397,330,616
5
0
NOASSERTION
2021-08-17T18:12:02
2021-08-17T16:57:16
null
UTF-8
C++
false
false
3,224
h
#pragma once #include <c10/core/impl/DeviceGuardImplInterface.h> #include <array> namespace c10 { namespace impl { // FakeGuardImpl is hardcoded to have eight devices. Not for // any good reason, just to simplify code. constexpr size_t kFakeGuardImplMaxDevices = 8; /** * A fake implementation of DeviceGuardImplInterface suitable for testing. * The current device is modeled as a mutable field in the guard implementation * class. See DeviceGuard_test.cpp for an example use. */ template <DeviceType T> struct FakeGuardImpl final : public DeviceGuardImplInterface { static constexpr DeviceType static_type = T; // Runtime device type is not used FakeGuardImpl(DeviceType) {} FakeGuardImpl() {} DeviceType type() const override { return T; } Device exchangeDevice(Device d) const override { AT_ASSERT(d.type() == type()); AT_ASSERT(d.index() < kFakeGuardImplMaxDevices); Device old_device = getDevice(); if (old_device.index() != d.index()) { current_device_ = d.index(); } return old_device; } Device getDevice() const override { return Device(type(), current_device_); } void setDevice(Device d) const override { AT_ASSERT(d.type() == type()); AT_ASSERT(d.index() >= 0); AT_ASSERT(d.index() < kFakeGuardImplMaxDevices); current_device_ = d.index(); } void uncheckedSetDevice(Device d) const noexcept override { current_device_ = d.index(); } Stream getStream(Device d) const noexcept override { return Stream(Stream::UNSAFE, d, current_streams_[d.index()]); } Stream exchangeStream(Stream s) const noexcept override { auto old_id = current_streams_[s.device_index()]; current_streams_[s.device_index()] = s.id(); return Stream(Stream::UNSAFE, s.device(), old_id); } DeviceIndex deviceCount() const noexcept override { return kFakeGuardImplMaxDevices; } // Event-related functions void record( void** event, const Stream& stream, const DeviceIndex device_index, const EventFlag flag) const override {} void block(void* event, const Stream& stream) const override {} bool queryEvent(void* event) const override { return true; } void destroyEvent(void* event, const DeviceIndex device_index) const noexcept override {} // Convenience methods for testing static DeviceIndex getDeviceIndex() { return current_device_; } static void setDeviceIndex(DeviceIndex i) { AT_ASSERT(i >= 0); AT_ASSERT(i < kFakeGuardImplMaxDevices); current_device_ = i; } static StreamId getCurrentStreamIdFor(DeviceIndex i) { return current_streams_.at(i); } static void resetStreams() { current_streams_.fill(0); } private: thread_local static DeviceIndex current_device_; thread_local static std::array<StreamId, kFakeGuardImplMaxDevices> current_streams_; }; template <DeviceType T> thread_local DeviceIndex FakeGuardImpl<T>::current_device_ = 0; template <DeviceType T> constexpr DeviceType FakeGuardImpl<T>::static_type; template <DeviceType T> thread_local std::array<StreamId, kFakeGuardImplMaxDevices> FakeGuardImpl<T>::current_streams_ = {0, 0, 0, 0, 0, 0, 0, 0}; } // namespace impl } // namespace c10
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
de57f51dc136e157687bd400a7d87da4cd3135f2
391b79380d7cad63498ea9acf38668f6fc40eb3f
/scene/MechLauncher.h
2e2101d05952c81667ed0e8565ecddd74cf97b26
[ "MIT" ]
permissive
pstiasny/derpengine
14b70f70a57ad2150fb3db5ab4b9e4f239577beb
854f6896a6888724cb273c126bf92cc110f3da72
refs/heads/master
2021-01-13T07:33:02.620881
2020-04-29T18:25:27
2020-04-29T18:25:27
9,779,731
0
1
null
null
null
null
UTF-8
C++
false
false
215
h
#include "../core/GraphNode.h" #include "GeometryNode.h" #include "Tile.h" #include "../common.h" class MechLauncher : public GraphNode { public: MechLauncher(); private: void doRender(RenderingContext *rc); };
[ "pawelstiasny@gmail.com" ]
pawelstiasny@gmail.com
059e8c89de75e8305977408ef1d5f384db5f5dea
e07fbaa5207d27f0a793c6e5cf187690722df32a
/src/util/shared.cpp
f1889e944400a88566ee80ad9efe0ca7a53062b4
[ "Apache-2.0" ]
permissive
maspadaru/ares
154942e4f14ee0d6d07e79f204925a27783e2eae
f92ee0cc8fcec6581916e765fabe70856c3aaaa3
refs/heads/master
2021-03-26T09:42:42.236782
2020-06-25T10:15:03
2020-06-25T10:15:03
247,693,418
0
0
null
null
null
null
UTF-8
C++
false
false
369
cpp
#include "util/shared.h" namespace ares::util::special_predicate { const std::string MATH = "laser_math"; } // namespace ares::util::special_predicate namespace ares::util::special_value { // const std::string CHASE_LABELED_NULL = // "laser_special_value_chase_labeled_null"; const std::string CHASE_LABELED_NULL = "nul"; } // namespace ares::util::special_value
[ "maspadaru@tutanota.com" ]
maspadaru@tutanota.com
85b9f3d479a35bb864b937b02bbc77fa24902c17
7e9a90f8cd512d376d6e8b5c6648c1c98d811be5
/examples/T4_i2c_tb_v5/T4_i2c_tb_v5.ino
5c1fd8200dab493a575b64ba13e30421307f23b8
[ "MIT" ]
permissive
Defragster/tti2c
513cd03f2ef0a9dcc8d3dcc9d2b534b4bf17d2ae
840778a4dceb6e1142cdf8ea0f3e8c9c32ccaffd
refs/heads/master
2020-12-15T05:20:21.906940
2020-02-20T13:45:21
2020-02-20T13:45:21
235,005,066
0
0
null
null
null
null
UTF-8
C++
false
false
8,286
ino
#include <Wire.h> #if defined(__IMXRT1062__) #include "Watchdog_t4.h" WDT_T4<WDT2> wdt; #endif #include "Wire_Scanner_all.ino.h" #define _use_9250 #define _use_BNO055 #define _use_BNO080 #define _use_lidar #define _use_MB85 //#define _write_init_MB85 uint16_t writeaddress = 0x025; #define _use_ssd1306 TwoWire *DisplayWire = &Wire1; #define _MPU9250_port Wire #define _BNO055_port Wire #define _BNO080_port Wire #define _LIDAR_port Wire #define _MB85_port Wire int idisp9250 = 0; int idisp055 = 1; int idisp080 = 0; void myCallback() { Serial.println("FEED THE DOG SOON, OR RESET!"); idisp9250 = 1; idisp055 = 0; idisp080 = 0; } #include "configDevices.h" void ToggleClock0( int iCmd ) { Serial.print("TC #"); Serial.print(iCmd); if ( !iCmd ) return; // Pass in ZERO to have exit with no action pinMode( 18, INPUT ); pinMode( 19, OUTPUT ); #define ICNT 32 Serial.print("\tTC SDA read: "); for ( int ii = 0; ii < ICNT; ii++ ) { digitalWriteFast(19, ii % 2 ); Serial.print( digitalReadFast(18) ); Serial.print( " " ); delayMicroseconds(3); } Serial.print("\n"); } void printSSD( int xx, int yy, const char * szOut, int tSize ) { #if defined ( _use_ssd1306 ) if ( xx == 0 && yy == 0 ) { display.clearDisplay(); Serial.println(); } Serial.print(szOut); display.setTextSize(tSize); display.setTextColor(SSD1306_WHITE); // Draw white text if ( xx >= 0 && yy >= 0 ) display.setCursor(xx, yy); display.print(szOut); display.display(); #endif } /* ========================================= Setup Devices now ======================================== */ void setup() { // serial to display data Serial.begin(115200); while (!Serial) {} Serial.println("\n" __FILE__ " " __DATE__ " " __TIME__); Scansetup(); // setup() :: Wire_Scanner_all.ino.h Scanloop(); // one loop() :: Wire_Scanner_all.ino.h #if defined(__IMXRT1062__) WDT_timings_t config; config.trigger = 10; /* in seconds, 0->128 */ config.timeout = 20; /* in seconds, 0->128 */ config.callback = myCallback; wdt.begin(config); #endif ToggleClock0( 1 ); #if defined( _use_MB85) Serial.println("Starting MB85..."); mymemory.begin(); //_MB85_port.setClock(1000000); //mymemory.eraseDevice(); #if defined( _write_init_MB85) //---------init data - load array byte arraySize = sizeof(MYDATA_t); mydata.datastruct.data_0 = true; Serial.print("Data_0: "); if (mydata.datastruct.data_0) Serial.println("true"); if (!mydata.datastruct.data_0) Serial.println("false"); mydata.datastruct.data_1 = 1.3575; Serial.print("Data_1: "); Serial.println(mydata.datastruct.data_1, DEC); mydata.datastruct.data_2 = 314159L; Serial.print("Data_2: "); Serial.println(mydata.datastruct.data_2, DEC); mydata.datastruct.data_3 = 142; Serial.print("Data_3: "); Serial.println(mydata.datastruct.data_3, DEC); mydata.datastruct.data_4 = 0x50; Serial.print("Data_4: 0x"); Serial.println(mydata.datastruct.data_4, HEX); //string test String string_test = "The Quick Brown Fox Jumped"; char cbuff[string_test.length() + 1]; string_test.toCharArray(cbuff, string_test.length() + 1); for (uint8_t j = 0; j < string_test.length() + 1; j++) { mydata.datastruct.data_5[j] = cbuff[j]; } Serial.println(string_test); Serial.println("...... ...... ......"); Serial.println("Init Done - array loaded"); Serial.println("...... ...... ......"); //----------write to FRAM chip byte result = mymemory.writeArray(writeaddress, arraySize, mydata.I2CPacket); if (result == 0) Serial.println("Write Done - array loaded in FRAM chip"); if (result != 0) Serial.println("Write failed"); Serial.println("...... ...... ......"); #endif //write_init_data #endif #if defined ( _use_ssd1306 ) //DisplayWire->begin(); // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3D for 128x64 Serial.println(F("SSD1306 allocation failed")); } delay(500); printSSD( 0, 0, ("Hello\n"), 2 ); #endif #if defined(_use_9250) // start communication with IMU printSSD( 0, 0, ("9250 Init"), 1 ); status = IMU.begin(); if (status < 0) { Serial.println("IMU 9250 initialization unsuccessful"); Serial.println("Check IMU wiring or try cycling power"); Serial.print("Status: "); Serial.println(status); while (1) {} } // setting the accelerometer full scale range to +/-8G IMU.setAccelRange(MPU9250::ACCEL_RANGE_8G); // setting the gyroscope full scale range to +/-500 deg/s IMU.setGyroRange(MPU9250::GYRO_RANGE_500DPS); // setting DLPF bandwidth to 20 Hz IMU.setDlpfBandwidth(MPU9250::DLPF_BANDWIDTH_20HZ); // setting SRD to 19 for a 50 Hz update rate IMU.setSrd(19); printSSD( -1, -1, ("ialized\n"), 1 ); #endif #if defined(_use_BNO055) /* Initialise the sensor */ printSSD( -1, -1, ("055 Init"), 1 ); if (!bno.begin()) { /* There was a problem detecting the BNO055 ... check your connections */ Serial.print("Ooops, no BNO055 detected ... Check your wiring or I2C ADDR!"); while (1); } printSSD( -1, -1, ("ialized\n"), 1 ); /* Display the current temperature */ int8_t temp = bno.getTemp(); Serial.print("Current Temperature: "); Serial.print(temp); Serial.println(" C"); Serial.println(""); bno.setExtCrystalUse(true); Serial.println("Calibration status values: 0=uncalibrated, 3=fully calibrated"); #endif #if defined(_use_BNO080) printSSD( -1, -1, ("080 Init"), 1 ); delay(200); _BNO080_port.begin(); if (myIMU.begin(0x4B, _BNO080_port) == false) { Serial.println("\tBNO080 not detected at default I2C address. Check your jumpers and the hookup guide. TOGGLE..."); if ( 1 ) { printSSD( -1, -1, ("... TOGGLE\n"), 1 ); ToggleClock0( 1 ); if (!bno.begin()) { /* There was a problem detecting the BNO055 ... check your connections */ Serial.print("\tOoops, no BNO080 detected ... Check your wiring or I2C ADDR!"); while (1); } printSSD( -1, -1, ("080 Init"), 1 ); _BNO080_port.begin(); if (myIMU.begin(0x4B, _BNO080_port) == false) { Serial.println("\tBNO080 not detected at default I2C address. Check your jumpers and the hookup guide. Freezing..."); printSSD( -1, -1, ("... FAIL"), 1 ); Scanloop(); Serial.print("\nFAIL - STOP << ============================================================= \n"); while (1); } else { printSSD( -1, -1, ("\nRecovered\n"), 1 ); Serial.print("\nRecovered << ============================================================= \n"); Serial.print("\nRecovered << ============================================================= \n"); delay(5000); } } else while (1); } _BNO080_port.setClock(400000); //Increase I2C data rate to 400kHz //max myIMU.enableRotationVector(50); //Send data update every 50ms Serial.println(F("Rotation vector enabled")); Serial.println(F("Output in form i, j, k, real, accuracy")); printSSD( -1, -1, ("ialized\n"), 1 ); #endif #if defined( _use_lidar) printSSD( -1, -1, ("LL3 Init"), 1 ); //myLidarLite.begin(0, true); // Set configuration to default and I2C to 400 kHz _LIDAR_port.begin(); Wire.setClock(400000UL); //max myLidarLite.configure(0); // Change this number to try out alternate configurations printSSD( -1, -1, ("ialized C+\n"), 1 ); delay(1000); #endif } void loop() { static uint32_t feed = millis(); if ( millis() - feed > 21000 ) { feed = millis(); #if defined(__IMXRT1062__) wdt.feed(); /* feed the dog every 11 seconds, to exceed 10second timeout period to refresh callback and gpio state for repeat */ #endif idisp055 = 1; idisp9250 = 0; idisp080 = 0; } else if (millis() - feed > 16000) { idisp055 = 0; idisp9250 = 0; idisp080 = 1; } #if defined( _use_9250) loop9250(); Serial.println(); #endif #if defined(_use_BNO055) loop055(); Serial.println(); #endif #if defined(_use_BNO080) loop080(); Serial.println(); #endif #if defined(_use_lidar) looplidar(); Serial.println(); #endif #if defined( _use_MB85) loopMB85(); Serial.println(); #endif }
[ "Defragster@users.noreply.github.com" ]
Defragster@users.noreply.github.com
7d03ce528668193d64c648cdfb785e412b4e7716
271ee7f9b31c4053442d1e488bcf7113b984e9a3
/Covid Challenge/Round-3/judge/submissions/97105771/main.cpp
7bc86436f40c52c6babec0124fa187dea86b3a77
[]
no_license
amirghx/Algorithms_Jupyter
3f3e196a43023c3f231adaddb57c1b55e1202d1c
adceb29cc6a7618e9040eae809f8e027dfe90593
refs/heads/master
2023-01-22T19:27:51.767018
2020-12-07T16:46:53
2020-12-07T16:46:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,746
cpp
#include <iostream> #include <bits/stdc++.h> using namespace std; const int MAXN = 505; int n, m; class edge { public: int id; int city1; int city2; int passPrice; }; class city { public: vector<edge> edges; int id{}; int stayPrice{}; bool operator<(const city &str) const { return (stayPrice > str.stayPrice); } }; class act { public: int type; int day; int familyNum; int destCity; int destFamily; bool operator<(const act &str) const { if (day == str.day) return type > str.type; return (day > str.day); } }; city cities[MAXN]; edge edges[MAXN * MAXN]; vector<act> acts; bool moved[MAXN]; bool seen[MAXN][MAXN]; int currentCity[MAXN]; bool bstEdges[MAXN][MAXN]; bool bstFound[MAXN]; int everyDayPath[MAXN * 3]; int pattern[MAXN]; int nextOneIndex[MAXN]; void input(); void moveAndMeet(int i, int j, int day); void move(int i, int j, int day); void meet(int i, int j, int day); void createBST(); void output(); void createTree(); void createEveryDayPath(); void dfs(city city); void calc(); void add(const city &city); int main() { input(); createBST(); createEveryDayPath(); calc(); output(); } int counter = 0; int totalCounter = 0; int indexInt = 0; void calc() { int counter2 = 0; int i = 0; while (totalCounter != n * (n - 1)) { if (!bstFound[everyDayPath[i]]) { bstFound[everyDayPath[i]] = true; for (int j = i + 1; j < i + counter; ++j) { if(totalCounter == n * (n-1)) break; if (pattern[nextOneIndex[everyDayPath[i]]] == everyDayPath[j]) { moveAndMeet(everyDayPath[i], everyDayPath[j], j + counter2); nextOneIndex[everyDayPath[i]]++; } else move(everyDayPath[i], everyDayPath[j], j + counter2); } counter2++; } i++; } } void createEveryDayPath() { dfs(cities[1]); for (int i = 0; i < counter; ++i) { everyDayPath[counter + i] = everyDayPath[i + 1]; } for (int i = 0; i < n; ++i) { pattern[n + i] = pattern[i]; } // for (int j = 0; j < 2*counter; ++j) { // cout<< everyDayPath[j] << " "; // } // cout << "||" << counter << " " << lastStop << endl; // for (int i = 0; i < 2 * n ; ++i) { // cout << pattern[i] << " "; // } // cout << endl; // for (int i = 0; i < n + 1; ++i) { // cout << nextOneIndex[i] << " "; // } // cout << endl; } void dfs(city city) { bstFound[city.id] = false; everyDayPath[counter] = city.id; counter++; pattern[indexInt] = city.id; nextOneIndex[city.id] = indexInt + 1; indexInt++; for (auto edge:city.edges) { if (edge.city2 == city.id) { if (bstFound[edge.city1]) { dfs(cities[edge.city1]); add(city); } } else { if (bstFound[edge.city2]) { dfs(cities[edge.city2]); add(city); } } } } void add(const city &city) { everyDayPath[counter] = city.id; counter++; } void createBST() { priority_queue<pair<int, int>> pq; for (auto edge: cities[1].edges) { pq.push({-edge.passPrice, edge.id}); } bstFound[1] = true; for (int i = 0; i < n - 1; ++i) { edge edge = edges[pq.top().second]; pq.pop(); if (bstFound[edge.city2] && bstFound[edge.city1]) { i--; continue; } int cityIndex = bstFound[edge.city1] ? edge.city2 : edge.city1; bstFound[cityIndex] = true; bstEdges[edge.city1][edge.city2] = true; bstEdges[edge.city2][edge.city1] = true; for (auto edge2:cities[cityIndex].edges) { pq.push({-edge2.passPrice, edge2.id}); } } createTree(); } void createTree() { for (int i = 1; i < n + 1; ++i) { vector<edge> newEdges; while (!cities[i].edges.empty()) { edge temp = cities[i].edges.back(); if (bstEdges[temp.city1][temp.city2]) { newEdges.push_back(temp); } cities[i].edges.pop_back(); } for (auto edge : newEdges) { cities[i].edges.push_back(edge); } } } void move(int i, int j, int day) { if (currentCity[i] == j) return; currentCity[i] = j; act act{1, day, i, j, 0}; acts.push_back(act); } void meet(int i, int j, int day) { if (seen[i][j]) return; totalCounter++; moved[i] = true; seen[i][j] = true; act act{2, day, i, 0, j}; acts.push_back(act); } void moveAndMeet(int i, int j, int day) { move(i, j, day); meet(i, j, day); } void input() { cin >> n >> m; for (int i = 1; i <= n; ++i) { int a; cin >> a; currentCity[i] = i; seen[i][i] = true; city city{{}, i, a}; cities[i] = city; } for (int j = 0; j < m; ++j) { int u, v, c; cin >> u >> v >> c; edge edge{j, u, v, c}; cities[u].edges.push_back(edge); cities[v].edges.push_back(edge); edges[j] = edge; } } void output() { sort(acts.begin(), acts.end()); int size = acts.size(); cout << acts.size() << endl; for (int i = 0; i < size; ++i) { act act = acts.back(); acts.pop_back(); if (act.type == 1) cout << act.type << " " << act.day << " " << act.familyNum << " " << act.destCity << endl; else cout << act.type << " " << act.day << " " << act.familyNum << " " << act.destFamily << endl; } }
[ "kianoosh.abbasi76@gmail.com" ]
kianoosh.abbasi76@gmail.com
10c085ecc9145bba21457c8e4962b28912cd6d46
27a54d590a2997eee972309dc25a8cffd320b4f0
/include/cg_mesh.hpp
139c98b6ef19aedca3413eb403c7567276ddde95
[]
no_license
JamShan/opengl-samples
8ca3c6955ad4dcccd6ce5e31deb421474648373c
3128e217797a6d459d5f287a919f7e93e476823b
refs/heads/master
2020-03-16T08:37:16.964756
2018-05-03T06:56:56
2018-05-03T06:56:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,638
hpp
#ifndef _CG_MESH_HPP_ #define _CG_MESH_HPP_ #include <string> #include <sstream> #include <vector> #include <cgm/cg_math.h> #include "cg_texture.hpp" #include "cg_shader.hpp" namespace cg { // 顶点 struct Vertex { Vertex(const Vec3f& pos); Vertex(const Vec3f& pos, const Vec3f& norm); Vertex(const Vec3f& pos, const Vec3f& norm, const Vec2f& txCrds); Vertex(const Vec3f& pos, const Vec3f& norm, const Vec2f& txCrds, const Vec3f& tan, const Vec3f& bitan); Vec3f position; // 位置 Vec3f normal; // 法向量 Vec2f texCoords; // 纹理坐标 Vec3f tangent; // 切向量 Vec3f bitangent; // 二重切向量 }; // 3D网格模型类 class Mesh { public: /*** 成员函数 ***/ // 构造函数 Mesh(const vector<Vertex>& vertices, const vector<unsigned int>& indices, const vector<Texture>& textures); Mesh(const vector<Vertex>& vertices, const vector<Texture>& textures); Mesh(const vector<Vertex>& vertices); // 使用指定的着色器进行渲染(绘制) void render(const Shader& shader) const; void render(const Shader* pShader) const; private: /*** 网格数据 ***/ vector<Vertex> _vertices; // 网格顶点集合 vector<unsigned int> _indices; // 三角形索引集合 vector<Texture> _textures; // 纹理集合 /*** 渲染数据 ***/ unsigned int _VAO, _VBO, _EBO; /*** 初始化 ***/ void init(); }; // 计算顶点法线 void calcNormals(const GLuint indices[], GLuint indexCount, Vertex vertices[], GLuint vertexCount); } // namespace #endif
[ "baiwen1979@qq.com" ]
baiwen1979@qq.com
cdecc7115ad13a05c0948ac8d0af574db9403874
49e9081cc9e9967c12e9ca203aa756491fe5bfaa
/src/Robot.cpp
8cadbe016c715938ae4498a30471d5e026cdb2f5
[]
no_license
FRO5401/FroshBot
9d00480e404fe59322d6fb2ad3d9456241ffeec3
7a76a6c2d8075be44e849f4532f4b37e27a3f054
refs/heads/master
2021-01-25T10:16:36.753140
2016-01-11T22:19:39
2016-01-11T22:19:39
39,141,806
0
0
null
null
null
null
UTF-8
C++
false
false
1,090
cpp
#include "WPILib.h" #include "Commands/Command.h" #include "Commands/PSControllerMove.h" #include "CommandBase.h" //Include includes for each and every command //OMFG Please work!! Pretty please!!! class Robot: public IterativeRobot { private: Command *autonomousCommand; LiveWindow *lw; void RobotInit() { CommandBase::init(); //autonomousCommand = new ExampleCommand(); lw = LiveWindow::GetInstance(); } void DisabledPeriodic() { Scheduler::GetInstance()->Run(); } void AutonomousInit() { if (autonomousCommand != NULL) autonomousCommand->Start(); } void AutonomousPeriodic() { Scheduler::GetInstance()->Run(); } void TeleopInit() { // This makes sure that the autonomous stops running when // teleop starts running. If you want the autonomous to // continue until interrupted by another command, remove // this line or comment it out. if (autonomousCommand != NULL) autonomousCommand->Cancel(); } void TeleopPeriodic() { Scheduler::GetInstance()->Run(); } void TestPeriodic() { lw->Run(); } }; START_ROBOT_CLASS(Robot);
[ "kmckay@bensalemsd.org" ]
kmckay@bensalemsd.org
346ef13b74feee12f23c3c68b4477945d859eee0
a8f2302f3c64ccd0054a8039a0581b7be4fe79c1
/c10/cuda/CUDACachingAllocator.h
df564b8ea474d391cd2a65058234c0f90fb9efa3
[ "BSD-3-Clause", "BSD-2-Clause", "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
mrshenli/pytorch
e3c603973d49ce156389e732d3084871394152ca
31732347e35747d1968a321e167f3cdf92751a15
refs/heads/master
2023-05-14T09:45:49.861988
2019-01-29T23:05:54
2019-01-30T19:50:23
160,590,620
2
0
NOASSERTION
2023-04-08T01:25:21
2018-12-05T23:17:26
C++
UTF-8
C++
false
false
1,860
h
#ifndef THC_DEVICE_ALLOCATOR_INC #define THC_DEVICE_ALLOCATOR_INC #include <c10/cuda/CUDAStream.h> #include <c10/core/Allocator.h> #include <c10/cuda/CUDAMacros.h> #include <mutex> namespace c10 { namespace cuda { // TODO: Turn this into an honest to goodness class. I briefly attempted to do // this, but it was a bit irritating to figure out how to also correctly // apply pimpl pattern so I didn't have to leak any internal implementation // details in the header (CUDACachingAllocator could be made a pimpl, but // you also need to appropriately define a class which is a subclass // of Allocator. Not impossible, but required a bit more surgery than // I wanted to do at the time.) // // Why is this using a namespace rather than old-style THCCachingAllocator_ // prefix? Mostly because it made the HIPify rules easier to write; _ is // not counted as a word boundary, so you would otherwise have to list each // of these functions. namespace CUDACachingAllocator { C10_CUDA_API Allocator* get(); // Invariant: &raw_delete == get()->raw_deleter() C10_CUDA_API void raw_delete(void* ptr); C10_CUDA_API void emptyCache(); C10_CUDA_API void cacheInfo(int dev_id, size_t* cachedAndFree, size_t* largestBlock); C10_CUDA_API void* getBaseAllocation(void *ptr, size_t *size); C10_CUDA_API void recordStream(void *ptr, CUDAStream stream); C10_CUDA_API uint64_t currentMemoryAllocated(int device); C10_CUDA_API uint64_t maxMemoryAllocated(int device); C10_CUDA_API void resetMaxMemoryAllocated(int device); C10_CUDA_API uint64_t currentMemoryCached(int device); C10_CUDA_API uint64_t maxMemoryCached(int device); C10_CUDA_API void resetMaxMemoryCached(int device); C10_CUDA_API std::mutex* getFreeMutex(); C10_CUDA_API std::shared_ptr<void> getIpcDevPtr(std::string handle); } // namespace CUDACachingAllocator }} // namespace c10::cuda #endif
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
fd475a3c39d637c3a8f011c6e8ef44a272e05d27
492976adfdf031252c85de91a185bfd625738a0c
/lib/hkStubs/Havok/Physics2012/Dynamics/World/Listener/hkpWorldPostIntegrateListener.h
30fafae25e7a6614b44694925ca6ac863db47c7a
[]
no_license
zeldaret/botw
50ccb72c6d3969c0b067168f6f9124665a7f7590
fd527f92164b8efdb746cffcf23c4f033fbffa76
refs/heads/master
2023-07-21T13:12:24.107437
2023-07-01T20:29:40
2023-07-01T20:29:40
288,736,599
1,350
117
null
2023-09-03T14:45:38
2020-08-19T13:16:30
C++
UTF-8
C++
false
false
261
h
#pragma once class hkpWorld; class hkpEntity; class hkStepInfo; class hkpWorldPostIntegrateListener { public: virtual ~hkpWorldPostIntegrateListener() = default; virtual void postIntegrateCallback(hkpWorld* world, const hkStepInfo& stepInfo) = 0; };
[ "leo@leolam.fr" ]
leo@leolam.fr
60a9267838250588b31887bab49cfb29e78aefe7
e077f637281ec77d5437ba8fb59f4656b14902b2
/dynamic_link/hello.cpp
485d78d486aebff5eec125656da01eb27b8fad66
[]
no_license
ahcorde/mini_test
6a296fa4f3b8e643d67dab7d6d54d74ddf84a3ac
c708791eda7b120348617245fa0de3c1b9830dc9
refs/heads/master
2022-12-14T16:25:42.292395
2020-08-20T21:38:31
2020-08-20T21:38:31
289,115,052
0
0
null
null
null
null
UTF-8
C++
false
false
543
cpp
#include "hello.hpp" #include <cstdio> #include <iostream> namespace ignition { namespace plugin { namespace { struct ExecuteWhenLoadingLibrary { ExecuteWhenLoadingLibrary() { std::cerr << "ExecuteWhenLoadingLibrary:" << std::endl; } }; } /* namespace */ static ignition::plugin::ExecuteWhenLoadingLibrary execute; } } #ifdef __cplusplus extern "C" { #endif void hello( const char* text ) { printf("Hello, %s\n", text); } #ifdef __cplusplus } // extern "C" #endif
[ "ahcorde@gmail.com" ]
ahcorde@gmail.com
050b9eac37ffed00a089213d8916a39472578fb8
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/chromium_org/ui/gfx/icon_util.h
0cb35088147a9344279d528f12ddb7e0096209e1
[ "MIT", "BSD-3-Clause" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
11,223
h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_GFX_ICON_UTIL_H_ #define UI_GFX_ICON_UTIL_H_ #include <windows.h> #include <string> #include <vector> #include "base/basictypes.h" #include "base/gtest_prod_util.h" #include "base/memory/scoped_ptr.h" #include "ui/gfx/gfx_export.h" #include "ui/gfx/point.h" #include "ui/gfx/size.h" namespace base { class FilePath; } namespace gfx { class ImageFamily; class Size; } class SkBitmap; /////////////////////////////////////////////////////////////////////////////// // // The IconUtil class contains helper functions for manipulating Windows icons. // The class interface contains methods for converting an HICON handle into an // SkBitmap object and vice versa. The class can also create a .ico file given // a PNG image contained in an SkBitmap object. The following code snippet // shows an example usage of IconUtil::CreateHICONFromSkBitmap(): // // SkBitmap bitmap; // // // Fill |bitmap| with valid data // bitmap.setConfig(...); // bitmap.allocPixels(); // // ... // // // Convert the bitmap into a Windows HICON // HICON icon = IconUtil::CreateHICONFromSkBitmap(bitmap); // if (icon == NULL) { // // Handle error // ... // } // // // Use the icon with a WM_SETICON message // ::SendMessage(hwnd, WM_SETICON, static_cast<WPARAM>(ICON_BIG), // reinterpret_cast<LPARAM>(icon)); // // // Destroy the icon when we are done // ::DestroyIcon(icon); // /////////////////////////////////////////////////////////////////////////////// class GFX_EXPORT IconUtil { public: // The size of the large icon entries in .ico files on Windows Vista+. static const int kLargeIconSize = 256; // The size of icons in the medium icons view on Windows Vista+. This is the // maximum size Windows will display an icon that does not have a 256x256 // image, even at the large or extra large icons views. static const int kMediumIconSize = 48; // The dimensions for icon images in Windows icon files. All sizes are square; // that is, the value 48 means a 48x48 pixel image. Sizes are listed in // ascending order. static const int kIconDimensions[]; // The number of elements in kIconDimensions. static const size_t kNumIconDimensions; // The number of elements in kIconDimensions <= kMediumIconSize. static const size_t kNumIconDimensionsUpToMediumSize; // Given an SkBitmap object, the function converts the bitmap to a Windows // icon and returns the corresponding HICON handle. If the function cannot // convert the bitmap, NULL is returned. // // The client is responsible for destroying the icon when it is no longer // needed by calling ::DestroyIcon(). static HICON CreateHICONFromSkBitmap(const SkBitmap& bitmap); // Given a valid HICON handle representing an icon, this function converts // the icon into an SkBitmap object containing an ARGB bitmap using the // dimensions specified in |s|. |s| must specify valid dimensions (both // width() an height() must be greater than zero). If the function cannot // convert the icon to a bitmap (most probably due to an invalid parameter), // the return value is NULL. // // The client owns the returned bitmap object and is responsible for deleting // it when it is no longer needed. static SkBitmap* CreateSkBitmapFromHICON(HICON icon, const gfx::Size& s); // Loads an icon resource as a SkBitmap for the specified |size| from a // loaded .dll or .exe |module|. Supports loading smaller icon sizes as well // as the Vista+ 256x256 PNG icon size. If the icon could not be loaded or // found, returns a NULL scoped_ptr. static scoped_ptr<SkBitmap> CreateSkBitmapFromIconResource(HMODULE module, int resource_id, int size); // Given a valid HICON handle representing an icon, this function converts // the icon into an SkBitmap object containing an ARGB bitmap using the // dimensions of HICON. If the function cannot convert the icon to a bitmap // (most probably due to an invalid parameter), the return value is NULL. // // The client owns the returned bitmap object and is responsible for deleting // it when it is no longer needed. static SkBitmap* CreateSkBitmapFromHICON(HICON icon); // Creates Windows .ico file at |icon_path|. The icon file is created with // multiple BMP representations at varying predefined dimensions (by resizing // an appropriately sized image from |image_family|) because Windows uses // different image sizes when loading icons, depending on where the icon is // drawn (ALT+TAB window, desktop shortcut, Quick Launch, etc.). // // If |image_family| contains an image larger than 48x48, the resulting icon // will contain all sizes up to 256x256. The 256x256 image will be stored in // PNG format inside the .ico file. If not, the resulting icon will contain // all sizes up to 48x48. // // The function returns true on success and false otherwise. Returns false if // |image_family| is empty. static bool CreateIconFileFromImageFamily( const gfx::ImageFamily& image_family, const base::FilePath& icon_path); // Creates a cursor of the specified size from the DIB passed in. // Returns the cursor on success or NULL on failure. static HICON CreateCursorFromDIB(const gfx::Size& icon_size, const gfx::Point& hotspot, const void* dib_bits, size_t dib_size); private: // The icon format is published in the MSDN but there is no definition of // the icon file structures in any of the Windows header files so we need to // define these structure within the class. We must make sure we use 2 byte // packing so that the structures are layed out properly within the file. // See: http://msdn.microsoft.com/en-us/library/ms997538.aspx #pragma pack(push) #pragma pack(2) // ICONDIRENTRY contains meta data for an individual icon image within a // .ico file. struct ICONDIRENTRY { BYTE bWidth; BYTE bHeight; BYTE bColorCount; BYTE bReserved; WORD wPlanes; WORD wBitCount; DWORD dwBytesInRes; DWORD dwImageOffset; }; // ICONDIR Contains information about all the icon images contained within a // single .ico file. struct ICONDIR { WORD idReserved; WORD idType; WORD idCount; ICONDIRENTRY idEntries[1]; }; // GRPICONDIRENTRY contains meta data for an individual icon image within a // RT_GROUP_ICON resource in an .exe or .dll. struct GRPICONDIRENTRY { BYTE bWidth; BYTE bHeight; BYTE bColorCount; BYTE bReserved; WORD wPlanes; WORD wBitCount; DWORD dwBytesInRes; WORD nID; }; // GRPICONDIR Contains information about all the icon images contained within // a RT_GROUP_ICON resource in an .exe or .dll. struct GRPICONDIR { WORD idReserved; WORD idType; WORD idCount; GRPICONDIRENTRY idEntries[1]; }; // Contains the actual icon image. struct ICONIMAGE { BITMAPINFOHEADER icHeader; RGBQUAD icColors[1]; BYTE icXOR[1]; BYTE icAND[1]; }; #pragma pack(pop) friend class IconUtilTest; // Used for indicating that the .ico contains an icon (rather than a cursor) // image. This value is set in the |idType| field of the ICONDIR structure. static const int kResourceTypeIcon = 1; // Returns true if any pixel in the given pixels buffer has an non-zero alpha. static bool PixelsHaveAlpha(const uint32* pixels, size_t num_pixels); // A helper function that initializes a BITMAPV5HEADER structure with a set // of values. static void InitializeBitmapHeader(BITMAPV5HEADER* header, int width, int height); // Given a single SkBitmap object and pointers to the corresponding icon // structures within the icon data buffer, this function sets the image // information (dimensions, color depth, etc.) in the icon structures and // also copies the underlying icon image into the appropriate location. // The width and height of |bitmap| must be < 256. // (Note that the 256x256 icon is treated specially, as a PNG, and should not // use this method.) // // The function will set the data pointed to by |image_byte_count| with the // number of image bytes written to the buffer. Note that the number of bytes // includes only the image data written into the memory pointed to by // |icon_image|. static void SetSingleIconImageInformation(const SkBitmap& bitmap, size_t index, ICONDIR* icon_dir, ICONIMAGE* icon_image, size_t image_offset, size_t* image_byte_count); // Copies the bits of an SkBitmap object into a buffer holding the bits of // the corresponding image for an icon within the .ico file. static void CopySkBitmapBitsIntoIconBuffer(const SkBitmap& bitmap, unsigned char* buffer, size_t buffer_size); // Given a set of bitmaps with varying dimensions, this function computes // the amount of memory needed in order to store the bitmaps as image icons // in a .ico file. static size_t ComputeIconFileBufferSize(const std::vector<SkBitmap>& set); // A helper function for computing various size components of a given bitmap. // The different sizes can be used within the various .ico file structures. // // |xor_mask_size| - the size, in bytes, of the XOR mask in the ICONIMAGE // structure. // |and_mask_size| - the size, in bytes, of the AND mask in the ICONIMAGE // structure. // |bytes_in_resource| - the total number of bytes set in the ICONIMAGE // structure. This value is equal to the sum of the // bytes in the AND mask and the XOR mask plus the size // of the BITMAPINFOHEADER structure. Note that since // only 32bpp are handled by the IconUtil class, the // icColors field in the ICONIMAGE structure is ignored // and is not accounted for when computing the // different size components. static void ComputeBitmapSizeComponents(const SkBitmap& bitmap, size_t* xor_mask_size, size_t* bytes_in_resource); // A helper function of CreateSkBitmapFromHICON. static SkBitmap CreateSkBitmapFromHICONHelper(HICON icon, const gfx::Size& s); // Prevent clients from instantiating objects of that class by declaring the // ctor/dtor as private. DISALLOW_IMPLICIT_CONSTRUCTORS(IconUtil); }; #endif // UI_GFX_ICON_UTIL_H_
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
1c61674a5701f1b326b51a4fe02388198799881b
c6aafdbcad02ce86c643d647d8ffac0d0a96f1f1
/ComputerDesignTechnology/CacheDesign/cache.h
0b1c4a4f2909632599ab07dc2a3d8a2ceed3da62
[]
no_license
Pratheekbm/MS_PROJECTS
e3adac53809a881ebe7073ecb0437fb5054f23e4
896a49d8233ac130ca5ccd4c7bf5bbb61e3c7fd0
refs/heads/master
2021-01-20T20:48:32.404772
2016-11-27T18:24:38
2016-11-27T18:24:38
62,931,943
0
0
null
null
null
null
UTF-8
C++
false
false
2,032
h
/* * cache.h * * Created on: Feb 27, 2015 * Author: pratheek */ #ifndef INC_CACHE_H_ #define INC_CACHE_H_ typedef enum _STATUS { FAIL = -1, SUCCESS = 0 } STATUS; typedef enum _TYPE { RESET = 0, SET = 1 } TYPE; typedef enum _CACHEID { CACHE_L1 = 1, CACHE_L2 = 2, CACHE_L3 = 3, MEM = 100, BAD = 101 } CACHEID; typedef enum _replacementPolicy { LRU = 0, FIFO = 1, PLRU = 2, INV = 3 } LRUPOLICY; typedef enum _INC { NONINCLUSION = 0, INCLUSION = 1, EXCLUSION = 2, NONE = 3 } IP; typedef enum _VALIDITY { INVALID = -1, VALID = 0, DIRTY = 1 } VALIDITY; class Cache { public: CACHEID id; int assosivity; int size; int blockSize; LRUPOLICY lruPolicy; IP incPolicy; int noOfSets; int bitsForBlockOffset; int bitsForIndex; int bitsForTag; long int indexMask; long int **fifoLruTs; int ***lruMatrix; int **pLruMatrix; long int **tag; VALIDITY **validity; Cache *next; Cache *previous; int totalRead; int totalWrite; int readMiss; int writeMiss; int readHit; int writeHit; int writeBack; int memTraffic; Cache(CACHEID id, int associvity, int size, int blockSize, LRUPOLICY lru, IP incPolicy); ~Cache(); void calculateTagFromAddress(long int address, long int &tag, long int &index); int log_2(long int var); STATUS searchForTagInASet(long int localtag, long int index, int &slot); STATUS checkSpaceInASet(long int index, int &slot); void updateLru(long int index, int slot); void getLru(long int index, long int &tag, int &slot); void updateValidity(long int address, VALIDITY val); void updateValidity(long int index, int slot, VALIDITY val); STATUS evictBlockWithAddress(long int address); void evictBlockFromASet(long int index); void checkValidity(long int address, VALIDITY &validity); void read(long int address); void write(long int write); }; #endif /* INC_CACHE_H_ */
[ "pbm@Pratheeks-MacBook-Pro.local" ]
pbm@Pratheeks-MacBook-Pro.local
e1c8429b40adb231df08a1147c6373cd2e85241d
681f456bc4c20a7dbad4f1ccf27abb374fdcca0b
/SensorDataFactory.cpp
95cfa770ad620b9feeb6c75fad0986afa0e4b33c
[]
no_license
ternence-li/MoCap
c86daa3de0e27dbea9fc16508a065839eb48bc45
347032977081a56118e220bdd39e4709462b4006
refs/heads/master
2021-12-23T05:32:29.937185
2017-10-26T17:23:37
2017-10-26T17:23:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,980
cpp
/* Copyright (c) 2016, Jochen Kempfle 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "SensorDataFactory.h" #include "SensorData.h" #include "SensorBuffer.h" SensorDataFactory* SensorDataFactory::_instance = nullptr; // std::vector<std::pair<std::string, CreateRecvFunc> > SensorDataFactory::_receiverList; SensorDataFactory::SensorDataFactory() { } size_t SensorDataFactory::getNumSensorDataTypes() { return getInstance()->_sensorDataTypeList.size(); } std::string SensorDataFactory::getSensorDataTypeName(unsigned int type) { return getInstance()->_sensorDataTypeList[type].first; } SensorData* SensorDataFactory::createSensorDataType(unsigned int type) { return getInstance()->_sensorDataTypeList[type].second(); } SensorBuffer* SensorDataFactory::createSensorBuffer(unsigned int type) { auto it = getInstance()->_sensorBufferMap.find(type); if (it == getInstance()->_sensorBufferMap.end()) { return nullptr; } return it->second(); } const int SensorDataFactory::registerSensorDataType(std::string name, CreateSensorDataTypeFunc dataFunc, CreateSensorBufferFunc bufFunc) { int typeId = getInstance()->_sensorDataTypeList.size(); getInstance()->_sensorDataTypeList.push_back(std::make_pair(name, dataFunc)); getInstance()->_sensorBufferMap[SensorDataType(typeId)] = bufFunc; return typeId; } const int SensorDataFactory::registerSensorDataCompositionType(SensorDataType type, CreateSensorBufferFunc bufFunc) { getInstance()->_sensorBufferMap[type] = bufFunc; return getInstance()->_sensorDataTypeList.size(); } SensorDataFactory* SensorDataFactory::getInstance() { if (_instance == nullptr) { _instance = new SensorDataFactory(); } return _instance; }
[ "J-Kempfle@t-online.de" ]
J-Kempfle@t-online.de
c30647016e5b257b7f314e5ad08db68ff1c745f8
b59210673a57e18f499563af9e6c5d0905dea2e5
/lib/libyasa/linearssf.h
5934f93d92788023597f50c74daa6a91d4d53652
[ "Apache-2.0" ]
permissive
ugermann/yasa
73465779ab0e2e972d2093b533ae3602b45ed1b6
2b67b3610a68287a29999499dee0ca8f8b8b0f62
refs/heads/master
2021-05-31T15:02:53.011106
2016-04-21T17:18:05
2016-04-21T17:18:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,229
h
/* Copyright 2013 RALI Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef JAPA_LINEAR_SSF_H #define JAPA_LINEAR_SSF_H #include <set> #include "point2d.h" #include "searchspacefiller.h" #include "solutionmarker.h" #include "text.h" namespace japa { /** * \french * <em>( Linear search space filler )</em> Rempli un espace de recherche * par intrapollation lin�aire. * * Le remplissage est g�r� par un foncteur, ce qui rend la classe plus flexible * et permet de lancer des faisceau dont le rayon n'est pas constant. Donc * cette classe ne fait qu'extrapoller des points. * \endfrench * * \english * <em>( Linear search space filler )</em> Fills a search space by linear * intrapolation. * * A fonctor must be specified to fill each point found. Thus, flexibility is * enhanced and a beam of constant or variable radius can be used. * \endenglish * * * @version 1.1 */ class LinearSSF : public SearchSpaceFiller { public : /** * \french * Constructeur. * * @param marker Une r�f�rence vers le marqueur de solution � utiliser. * \endfrench * * \english * Constructor. * * @param marker A reference to the solution marker. * \endenglish */ LinearSSF( SolutionMarker& marker ); /** * \french * Destructeur. * \endfrench * * \english * Destructor. * \endenglish */ virtual ~LinearSSF(); /** * \french * Ajoute un point de passage qui sera utilis� lors de l'interpollation. * * Les points peuvent �tre ajout� dans n'importe quel ordre, mais seront * interpoll�s selon l'ordre des x, et ensuite des y. Ex : * * <p> * <code>( 2, 3 ) ( 1, 8 ) ( 2, 1 ) ( 7, 0 )</code> * </p> * * seront interpoll�s dans l'ordre : * * <p> * <code>( 1, 8 ) ( 2, 1 ) ( 2, 3 ) ( 7, 0 )</code> * </p> * * @param x La coordonn�e en x du point de passage. * @param y La coordonn�e en y du point de passage. * \endfrench * * \english * Add a passage point that will be considered during the interpolation. * * The order of insertion of the points has no importance, because the * points will be interpolated from left to right. * * Example : * * <p> * <code>( 2, 3 ) ( 1, 8 ) ( 2, 1 ) ( 7, 0 )</code> * </p> * * will be interpolated in the following order : * * <p> * <code>( 1, 8 ) ( 2, 1 ) ( 2, 3 ) ( 7, 0 )</code> * </p> * * \endenglish */ void addPassagePoint( const int x, const int y ); SearchSpace& operator()( SearchSpace& s ); private : /** * \french * Le type d'un point de passage * \endfrench * * \english * Passage point's data type. * \endenglish */ typedef Point2D< int > PassagePoint; /** * \french * Compare deux point de passage pour savoir laquelle est le plus petit en * terme de rang de visite. * \endfrench * * \english * Compare two passage point in order to compute their precedence. * \endenglish * * * @version 1.1 */ class PassagePointComparator : public std::binary_function< PassagePoint, PassagePoint, bool > { public : /** * \french * Permet de comparer deux point de passage selon leurs rang. * * @param p1 La premi�re solution. * @param p2 La deuxi�me solution. * * @return <code>true</code> si p1 < p2. * \endfrench * * \english * Compare two passage points. * * @param p1 The first passage point. * @param p2 The second passage point. * * @return <code>true</code> if p1 < p2. * \endenglish */ bool operator()( const PassagePoint& p1, const PassagePoint& p2 ) const; }; /** * \french * Le type de la structure contenant les points de passage. * \endfrench * * \english * Passage points holder's data type. * \endenglish */ typedef std::set< PassagePoint, PassagePointComparator > PointsContainer; /** * \french * Une r�f�rence vers le marqueur de solutions. * \endfrench * * \english * A reference to the solution marker. * \endenglish */ SolutionMarker& m_marker; /** * \french * Contient les points de passage. * \endfrench * * \english * Passage points holder. * \endenglish */ PointsContainer m_passagePoints; }; }// namespace japa #endif
[ "critter@iro.umontreal.ca" ]
critter@iro.umontreal.ca
0bec0277351e4fb79119125d4d1108684ef43191
0de652685d9926570b59a74b5bf403a0795644b5
/h/Orient.h
ccbd8443950d173fcbbb0bab6006a3d378ea0e16
[]
no_license
zayac/runningram
b49215378f3ecfee3d24cb64ab2bb56f0c6bfc24
01ffeca795602b97583a4a6e089b8830e702e5f0
refs/heads/master
2020-03-30T21:59:14.160199
2011-09-30T19:15:41
2011-09-30T19:15:41
32,114,091
0
0
null
2020-02-28T21:18:31
2015-03-13T01:16:28
C++
UTF-8
C++
false
false
1,547
h
/* * File: Orient.h * Author: necto * * Created on January 10, 2010, 4:18 PM */ #ifndef _ORIENT_H #define _ORIENT_H #include "Vec.h" const float PI = 3.1415926; inline float inRange (float what) {while (what > PI) what -= 2*PI; while (what < -PI) what += 2*PI; return what;} class Orient { bool updated; float ang; Vector2f dir; // friend class Orient; public: Orient (); Orient (float angle, bool update = false); Orient (Vector2f direction, bool normed = false); Orient (const Orient& orig); virtual ~Orient(); void setAngle (float a); void update(); float getAngle() const; Vector2f getDir() const; Vector2f getDir(); Orient operator -() const; Orient operator - (const Orient& that) const; Orient operator + (const Orient& that) const; inline float operator - (float that) const {return ang - that;} inline float operator + (float that) const {return ang + that;} Orient& operator -= (const Orient& that); Orient& operator += (const Orient& that); inline bool operator < (float that) const {return ang < that;} inline bool operator < (const Orient& that) const {return ang < that.ang;} inline bool operator > (float that) const {return ang > that;} inline bool operator > (const Orient& that) const {return ang > that.ang;} Vector2f rotate (Vector2f what); bool ok() const; }; inline float operator - (float one, const Orient& two) {return inRange (one - two.getAngle());} inline float operator + (float one, const Orient& two) {return inRange (one + two.getAngle());} #endif /* _ORIENT_H */
[ "necto.ne@0b8b07ca-f9fe-11de-aabd-2bfef65f77b5" ]
necto.ne@0b8b07ca-f9fe-11de-aabd-2bfef65f77b5
38bbb59f105b9897d9cbbeedbcd529b3a92c5665
77fb5ef05ae70e0020aa57f995d489e82e08c061
/src/graphic/GRBembel.cpp
590fec63b2019af027c2b409d62270ef37f4a0b4
[]
no_license
Kanma/guido-engine
19c9e20db94e7924f208b2b34ab0dc7fa8a84819
be0c3a890e67e09e0bf983d38350610fcbf167dd
refs/heads/master
2021-01-24T23:35:50.857020
2015-01-05T23:22:58
2015-01-05T23:22:58
28,835,145
0
0
null
2015-01-05T22:33:51
2015-01-05T22:33:50
null
UTF-8
C++
false
false
1,686
cpp
/* GUIDO Library Copyright (C) 2002 Holger Hoos, Juergen Kilian, Kai Renz This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "ARBembel.h" #include "GRBembel.h" #include "GRDefine.h" unsigned int GRBembel::sBembelSymbol = kBembelSymbol; // SCR_BEMBEL was 164 NVPoint GRBembel::refpos; GRBembel::GRBembel(ARBembel * par) : GRTagARNotationElement(/*dynamic cast<ARMusicalObject *>*/(par), LSPACE) { // No! mNeedsSpring = 1; // obsolete // spacing = 0; mSymbol = sBembelSymbol; const float extent = (float)GetSymbolExtent( mSymbol ); // obsolete .. mBoundingBox.left = 0; mBoundingBox.top = 0; mBoundingBox.right = (GCoord)extent; mBoundingBox.bottom = (GCoord)(3 * LSPACE); mLeftSpace = (GCoord)(extent * 0.5f); mRightSpace = (GCoord)(extent * 0.5f); // extent; // no referencePosition? refpos = NVPoint( (GCoord)(-extent * 0.5f) ,0); } GRBembel::~GRBembel() { } void GRBembel::print() const { } void GRBembel::OnDraw(VGDevice & hdc) const { GRTagARNotationElement::OnDraw(hdc); }
[ "fober@grame.fr" ]
fober@grame.fr
c3c956062b5e21cfc91c06c7fe0b46da1b62a2f8
8fcdc4aa429ee8862b3dc1b3d53f950f007b737b
/src/envoy/test/mocks/network/mocks.h
9024a1550583d0d68e6893f03d42fc13fa807364
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
bdecoste/istio_proxy_build_image
60d6c1ddcd54e2fc2d0f9bf3d37d3dd2b3345d7e
6070903cf7a83781028a58cea855d12811505ab3
refs/heads/master
2022-11-01T14:58:00.092844
2018-01-27T00:19:10
2018-01-27T00:19:10
117,725,464
0
1
null
2022-10-05T18:50:06
2018-01-16T18:42:27
C++
UTF-8
C++
false
false
8,900
h
#pragma once #include <cstdint> #include <list> #include <string> #include "envoy/network/connection.h" #include "envoy/network/drain_decision.h" #include "envoy/network/filter.h" #include "test/mocks/event/mocks.h" #include "test/test_common/printers.h" #include "gmock/gmock.h" namespace Envoy { namespace Network { class MockConnectionCallbacks : public ConnectionCallbacks { public: MockConnectionCallbacks(); ~MockConnectionCallbacks(); // Network::ConnectionCallbacks MOCK_METHOD1(onEvent, void(Network::ConnectionEvent event)); MOCK_METHOD0(onAboveWriteBufferHighWatermark, void()); MOCK_METHOD0(onBelowWriteBufferLowWatermark, void()); }; class MockConnectionBase { public: void raiseEvent(Network::ConnectionEvent event); void runHighWatermarkCallbacks(); void runLowWatermarkCallbacks(); static uint64_t next_id_; testing::NiceMock<Event::MockDispatcher> dispatcher_; std::list<Network::ConnectionCallbacks*> callbacks_; uint64_t id_{next_id_++}; Address::InstanceConstSharedPtr remote_address_; bool read_enabled_{true}; Connection::State state_{Connection::State::Open}; }; class MockConnection : public Connection, public MockConnectionBase { public: MockConnection(); ~MockConnection(); // Network::Connection MOCK_METHOD1(addConnectionCallbacks, void(ConnectionCallbacks& cb)); MOCK_METHOD1(addWriteFilter, void(WriteFilterSharedPtr filter)); MOCK_METHOD1(addFilter, void(FilterSharedPtr filter)); MOCK_METHOD1(addReadFilter, void(ReadFilterSharedPtr filter)); MOCK_METHOD1(close, void(ConnectionCloseType type)); MOCK_METHOD0(dispatcher, Event::Dispatcher&()); MOCK_CONST_METHOD0(id, uint64_t()); MOCK_METHOD0(initializeReadFilters, bool()); MOCK_CONST_METHOD0(nextProtocol, std::string()); MOCK_METHOD1(noDelay, void(bool enable)); MOCK_METHOD1(readDisable, void(bool disable)); MOCK_METHOD1(detectEarlyCloseWhenReadDisabled, void(bool)); MOCK_CONST_METHOD0(readEnabled, bool()); MOCK_CONST_METHOD0(remoteAddress, const Address::Instance&()); MOCK_CONST_METHOD0(localAddress, const Address::Instance&()); MOCK_METHOD1(setConnectionStats, void(const ConnectionStats& stats)); MOCK_METHOD0(ssl, Ssl::Connection*()); MOCK_CONST_METHOD0(ssl, const Ssl::Connection*()); MOCK_CONST_METHOD0(state, State()); MOCK_METHOD1(write, void(Buffer::Instance& data)); MOCK_METHOD1(setBufferLimits, void(uint32_t limit)); MOCK_CONST_METHOD0(bufferLimit, uint32_t()); MOCK_CONST_METHOD0(usingOriginalDst, bool()); MOCK_CONST_METHOD0(aboveHighWatermark, bool()); }; /** * NOTE: MockClientConnection duplicated most of MockConnection due to the fact that NiceMock * cannot be reliably used on base class methods. */ class MockClientConnection : public ClientConnection, public MockConnectionBase { public: MockClientConnection(); ~MockClientConnection(); // Network::Connection MOCK_METHOD1(addConnectionCallbacks, void(ConnectionCallbacks& cb)); MOCK_METHOD1(addWriteFilter, void(WriteFilterSharedPtr filter)); MOCK_METHOD1(addFilter, void(FilterSharedPtr filter)); MOCK_METHOD1(addReadFilter, void(ReadFilterSharedPtr filter)); MOCK_METHOD1(close, void(ConnectionCloseType type)); MOCK_METHOD0(dispatcher, Event::Dispatcher&()); MOCK_CONST_METHOD0(id, uint64_t()); MOCK_METHOD0(initializeReadFilters, bool()); MOCK_CONST_METHOD0(nextProtocol, std::string()); MOCK_METHOD1(noDelay, void(bool enable)); MOCK_METHOD1(readDisable, void(bool disable)); MOCK_METHOD1(detectEarlyCloseWhenReadDisabled, void(bool)); MOCK_CONST_METHOD0(readEnabled, bool()); MOCK_CONST_METHOD0(remoteAddress, const Address::Instance&()); MOCK_CONST_METHOD0(localAddress, const Address::Instance&()); MOCK_METHOD1(setConnectionStats, void(const ConnectionStats& stats)); MOCK_METHOD0(ssl, Ssl::Connection*()); MOCK_CONST_METHOD0(ssl, const Ssl::Connection*()); MOCK_CONST_METHOD0(state, State()); MOCK_METHOD1(write, void(Buffer::Instance& data)); MOCK_METHOD1(setBufferLimits, void(uint32_t limit)); MOCK_CONST_METHOD0(bufferLimit, uint32_t()); MOCK_CONST_METHOD0(usingOriginalDst, bool()); MOCK_CONST_METHOD0(aboveHighWatermark, bool()); // Network::ClientConnection MOCK_METHOD0(connect, void()); }; class MockActiveDnsQuery : public ActiveDnsQuery { public: MockActiveDnsQuery(); ~MockActiveDnsQuery(); // Network::ActiveDnsQuery MOCK_METHOD0(cancel, void()); }; class MockDnsResolver : public DnsResolver { public: MockDnsResolver(); ~MockDnsResolver(); // Network::DnsResolver MOCK_METHOD3(resolve, ActiveDnsQuery*(const std::string& dns_name, DnsLookupFamily dns_lookup_family, ResolveCb callback)); testing::NiceMock<MockActiveDnsQuery> active_query_; }; class MockReadFilterCallbacks : public ReadFilterCallbacks { public: MockReadFilterCallbacks(); ~MockReadFilterCallbacks(); MOCK_METHOD0(connection, Connection&()); MOCK_METHOD0(continueReading, void()); MOCK_METHOD0(upstreamHost, Upstream::HostDescriptionConstSharedPtr()); MOCK_METHOD1(upstreamHost, void(Upstream::HostDescriptionConstSharedPtr host)); testing::NiceMock<MockConnection> connection_; Upstream::HostDescriptionConstSharedPtr host_; }; class MockReadFilter : public ReadFilter { public: MockReadFilter(); ~MockReadFilter(); MOCK_METHOD1(onData, FilterStatus(Buffer::Instance& data)); MOCK_METHOD0(onNewConnection, FilterStatus()); MOCK_METHOD1(initializeReadFilterCallbacks, void(ReadFilterCallbacks& callbacks)); ReadFilterCallbacks* callbacks_{}; }; class MockWriteFilter : public WriteFilter { public: MockWriteFilter(); ~MockWriteFilter(); MOCK_METHOD1(onWrite, FilterStatus(Buffer::Instance& data)); }; class MockFilter : public Filter { public: MockFilter(); ~MockFilter(); MOCK_METHOD1(onData, FilterStatus(Buffer::Instance& data)); MOCK_METHOD0(onNewConnection, FilterStatus()); MOCK_METHOD1(onWrite, FilterStatus(Buffer::Instance& data)); MOCK_METHOD1(initializeReadFilterCallbacks, void(ReadFilterCallbacks& callbacks)); ReadFilterCallbacks* callbacks_{}; }; class MockListenerCallbacks : public ListenerCallbacks { public: MockListenerCallbacks(); ~MockListenerCallbacks(); void onNewConnection(ConnectionPtr&& conn) override { onNewConnection_(conn); } MOCK_METHOD1(onNewConnection_, void(ConnectionPtr& conn)); }; class MockDrainDecision : public DrainDecision { public: MockDrainDecision(); ~MockDrainDecision(); MOCK_CONST_METHOD0(drainClose, bool()); }; class MockFilterChainFactory : public FilterChainFactory { public: MockFilterChainFactory(); ~MockFilterChainFactory(); MOCK_METHOD1(createFilterChain, bool(Connection& connection)); }; class MockListenSocket : public ListenSocket { public: MockListenSocket(); ~MockListenSocket(); MOCK_CONST_METHOD0(localAddress, Address::InstanceConstSharedPtr()); MOCK_METHOD0(fd, int()); MOCK_METHOD0(close, void()); Address::InstanceConstSharedPtr local_address_; }; class MockListener : public Listener { public: MockListener(); ~MockListener(); MOCK_METHOD0(onDestroy, void()); }; class MockConnectionHandler : public ConnectionHandler { public: MockConnectionHandler(); ~MockConnectionHandler(); MOCK_METHOD0(numConnections, uint64_t()); MOCK_METHOD5(addListener, void(Network::FilterChainFactory& factory, Network::ListenSocket& socket, Stats::Scope& scope, uint64_t listener_tag, const Network::ListenerOptions& listener_options)); MOCK_METHOD6(addSslListener, void(Network::FilterChainFactory& factory, Ssl::ServerContext& ssl_ctx, Network::ListenSocket& socket, Stats::Scope& scope, uint64_t listener_tag, const Network::ListenerOptions& listener_options)); MOCK_METHOD1(findListenerByAddress, Network::Listener*(const Network::Address::Instance& address)); MOCK_METHOD1(removeListeners, void(uint64_t listener_tag)); MOCK_METHOD1(stopListeners, void(uint64_t listener_tag)); MOCK_METHOD0(stopListeners, void()); }; class MockResolvedAddress : public Address::Instance { public: MockResolvedAddress(const std::string& logical, const std::string& physical) : logical_(logical), physical_(physical) {} bool operator==(const Address::Instance& other) const override { return asString() == other.asString(); } MOCK_CONST_METHOD1(bind, int(int)); MOCK_CONST_METHOD1(connect, int(int)); MOCK_CONST_METHOD0(ip, Address::Ip*()); MOCK_CONST_METHOD1(socket, int(Address::SocketType)); MOCK_CONST_METHOD0(type, Address::Type()); const std::string& asString() const override { return physical_; } const std::string& logicalName() const override { return logical_; } const std::string logical_; const std::string physical_; }; } // namespace Network } // namespace Envoy
[ "root@ose3x-master.example.com" ]
root@ose3x-master.example.com
2fb49fc258152639ebbb6ddda66e089d1c6866c3
ad484ea400e585816facd20744aa873ae88c870f
/eagleeye/basic/count_down_latch.h
c64d1247300bd22f485e9378459fc37b64373457
[ "Apache-2.0" ]
permissive
maxenergy/eagleeye
f80c78583f0fdd4d3816a3fc23baa0bd0a8ccb1f
37ada5e71bebb8c51f29219fd32c485a0721ccbe
refs/heads/master
2023-05-31T14:39:51.246087
2021-06-23T04:08:19
2021-06-23T04:08:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,909
h
// Copyright 2019 The MACE Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef _EAGLEEYE_COUNT_DOWN_LATCH_H_ #define _EAGLEEYE_COUNT_DOWN_LATCH_H_ #include <atomic> // NOLINT(build/c++11) #include <condition_variable> // NOLINT(build/c++11) #include <mutex> // NOLINT(build/c++11) #include "eagleeye/basic/spinlock.hpp" namespace eagleeye { class CountDownLatch { public: explicit CountDownLatch(int64_t spin_timeout) : spin_timeout_(spin_timeout), count_(0) {} CountDownLatch(int64_t spin_timeout, int count) : spin_timeout_(spin_timeout), count_(count) {} void Wait() { if (spin_timeout_ > 0) { SpinWaitUntil(count_, 0, spin_timeout_); } if (count_.load(std::memory_order_acquire) != 0) { std::unique_lock<std::mutex> m(mutex_); while (count_.load(std::memory_order_acquire) != 0) { cond_.wait(m); } } } void CountDown() { if (count_.fetch_sub(1, std::memory_order_release) == 1) { std::unique_lock<std::mutex> m(mutex_); cond_.notify_all(); } } void Reset(int count) { count_.store(count, std::memory_order_release); } int count() const { return count_; } private: int64_t spin_timeout_; std::atomic<int> count_; std::mutex mutex_; std::condition_variable cond_; }; } // namespace mace #endif // MACE_UTILS_COUNT_DOWN_LATCH_H_
[ "jian.fbehind@gmail.com" ]
jian.fbehind@gmail.com
ae222057e8da01f46e8845e39866f5ced07bbc4b
8d82f844648ad98d554b3b82cdbff954e14bae3a
/Common/Device/Dll/ComCtrl/ComCtrl.cpp
8b9f2bd9faad37f44d2eb7608390b09161f58c61
[]
no_license
angelinana0408/financial-transaction
519151f05bb6c92b9b35bcf4eb1ac68ee0edc522
e8f4696d7108dc7ff25719269f7106b8430708aa
refs/heads/master
2021-04-27T16:43:52.282331
2018-02-21T08:14:21
2018-02-21T08:14:21
122,308,506
0
0
null
null
null
null
UTF-8
C++
false
false
761
cpp
// ComCtrl.cpp : Defines the initialization routines for the DLL. // #include "stdafx.h" #include <afxdllx.h> #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif static AFX_EXTENSION_MODULE ComCtrlDLL = { NULL, NULL }; extern "C" int APIENTRY DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) { UNREFERENCED_PARAMETER(lpReserved); if (dwReason == DLL_PROCESS_ATTACH) { TRACE0("COMCTRL.DLL Initializing!\n"); if (!AfxInitExtensionModule(ComCtrlDLL, hInstance)) return 0; new CDynLinkLibrary(ComCtrlDLL); } else if (dwReason == DLL_PROCESS_DETACH) { TRACE0("COMCTRL.DLL Terminating!\n"); AfxTermExtensionModule(ComCtrlDLL); } return 1; }
[ "qiaoyang@qiaoyangdeMacBook-Pro.local" ]
qiaoyang@qiaoyangdeMacBook-Pro.local
ee1170250e373cb6ffba8a30889ef1fe73edfd90
e217eaf05d0dab8dd339032b6c58636841aa8815
/Ifc2x3/src/OpenInfraPlatform/Ifc2x3/entity/IfcSurfaceTexture.cpp
2a3352a40fdb6749b0b38f7a0198c74096f08d75
[]
no_license
bigdoods/OpenInfraPlatform
f7785ebe4cb46e24d7f636e1b4110679d78a4303
0266e86a9f25f2ea9ec837d8d340d31a58a83c8e
refs/heads/master
2021-01-21T03:41:20.124443
2016-01-26T23:20:21
2016-01-26T23:20:21
57,377,206
0
1
null
2016-04-29T10:38:19
2016-04-29T10:38:19
null
UTF-8
C++
false
false
3,283
cpp
/*! \verbatim * \copyright Copyright (c) 2014 Julian Amann. All rights reserved. * \date 2014-04-26 17:30 * \author Julian Amann <julian.amann@tum.de> (https://www.cms.bgu.tum.de/en/team/amann) * \brief This file is part of the BlueFramework. * \endverbatim */ #include <sstream> #include <limits> #include "model/Ifc2x3Exception.h" #include "reader/ReaderUtil.h" #include "writer/WriterUtil.h" #include "Ifc2x3EntityEnums.h" #include "include/IfcCartesianTransformationOperator2D.h" #include "include/IfcSurfaceTexture.h" #include "include/IfcSurfaceTextureEnum.h" namespace OpenInfraPlatform { namespace Ifc2x3 { // ENTITY IfcSurfaceTexture IfcSurfaceTexture::IfcSurfaceTexture() { m_entity_enum = IFCSURFACETEXTURE; } IfcSurfaceTexture::IfcSurfaceTexture( int id ) { m_id = id; m_entity_enum = IFCSURFACETEXTURE; } IfcSurfaceTexture::~IfcSurfaceTexture() {} // method setEntity takes over all attributes from another instance of the class void IfcSurfaceTexture::setEntity( shared_ptr<Ifc2x3Entity> other_entity ) { shared_ptr<IfcSurfaceTexture> other = dynamic_pointer_cast<IfcSurfaceTexture>(other_entity); if( !other) { return; } m_RepeatS = other->m_RepeatS; m_RepeatT = other->m_RepeatT; m_TextureType = other->m_TextureType; m_TextureTransform = other->m_TextureTransform; } void IfcSurfaceTexture::getStepLine( std::stringstream& stream ) const { stream << "#" << m_id << "=IFCSURFACETEXTURE" << "("; if( m_RepeatS == false ) { stream << ".F."; } else if( m_RepeatS == true ) { stream << ".T."; } stream << ","; if( m_RepeatT == false ) { stream << ".F."; } else if( m_RepeatT == true ) { stream << ".T."; } stream << ","; if( m_TextureType ) { m_TextureType->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_TextureTransform ) { stream << "#" << m_TextureTransform->getId(); } else { stream << "$"; } stream << ");"; } void IfcSurfaceTexture::getStepParameter( std::stringstream& stream, bool ) const { stream << "#" << m_id; } void IfcSurfaceTexture::readStepData( std::vector<std::string>& args, const std::map<int,shared_ptr<Ifc2x3Entity> >& map ) { const int num_args = (int)args.size(); if( num_args<4 ){ std::stringstream strserr; strserr << "Wrong parameter count for entity IfcSurfaceTexture, expecting 4, having " << num_args << ". Object id: " << getId() << std::endl; throw Ifc2x3Exception( strserr.str().c_str() ); } #ifdef _DEBUG if( num_args>4 ){ std::cout << "Wrong parameter count for entity IfcSurfaceTexture, expecting 4, having " << num_args << ". Object id: " << getId() << std::endl; } #endif if( _stricmp( args[0].c_str(), ".F." ) == 0 ) { m_RepeatS = false; } else if( _stricmp( args[0].c_str(), ".T." ) == 0 ) { m_RepeatS = true; } if( _stricmp( args[1].c_str(), ".F." ) == 0 ) { m_RepeatT = false; } else if( _stricmp( args[1].c_str(), ".T." ) == 0 ) { m_RepeatT = true; } m_TextureType = IfcSurfaceTextureEnum::readStepData( args[2] ); readEntityReference( args[3], m_TextureTransform, map ); } void IfcSurfaceTexture::setInverseCounterparts( shared_ptr<Ifc2x3Entity> ) { } void IfcSurfaceTexture::unlinkSelf() { } } // end namespace Ifc2x3 } // end namespace OpenInfraPlatform
[ "planung.cms.bv@tum.de" ]
planung.cms.bv@tum.de
aa62e74f4a81ce81c46fca1afb55c39640b83d28
7bcc51362468098bbb9ddd241230e02cdbeea6e4
/standard/src/StdBuf.cpp
7619779dbb0c11347ac4ce0cc9381563593ea35c
[ "ISC" ]
permissive
Marko10-000/clonk-rage
af4ac62b7227c00874ecd49431a29a984a417fbb
230e715f2abe65966d5e5467cb18382062d1dec6
refs/heads/master
2021-01-18T07:29:38.108084
2015-09-07T01:34:56
2015-09-07T01:34:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,851
cpp
#include <Standard.h> #include <StdBuf.h> #include <StdCompiler.h> #include <StdAdaptors.h> #include <StdFile.h> #include <stdarg.h> #include <stdio.h> #ifdef _WIN32 #include <io.h> #define vsnprintf _vsnprintf #else #define O_BINARY 0 #define O_SEQUENTIAL 0 #include <unistd.h> #include <stdlib.h> #endif #include <ctype.h> #include <fcntl.h> #include <sys/stat.h> // *** StdBuf bool StdBuf::LoadFromFile(const char *szFile) { // Open file int fh = open(szFile, O_BINARY | O_RDONLY | O_SEQUENTIAL, S_IREAD | S_IWRITE); if(fh < 0) return false; // Create buf New(FileSize(fh)); // Read if(read(fh, getMData(), getSize()) != (signed int) getSize()) { close(fh); return false; } close(fh); // Ok return true; } bool StdBuf::SaveToFile(const char *szFile) const { // Open file int fh = open(szFile, O_BINARY | O_CREAT | O_WRONLY | O_SEQUENTIAL | O_TRUNC, S_IREAD | S_IWRITE); if(fh < 0) return false; // Write data if(write(fh, getData(), getSize()) != (signed int) getSize()) { close(fh); return false; } close(fh); // Ok return true; } bool StdStrBuf::LoadFromFile(const char *szFile) { // Open file int fh = open(szFile, O_BINARY | O_RDONLY | O_SEQUENTIAL, S_IREAD | S_IWRITE); if(fh < 0) return false; // Create buf SetLength(FileSize(fh)); // Read if(read(fh, getMData(), getLength()) != (size_t) getLength()) { close(fh); return false; } close(fh); // Ok return true; } bool StdStrBuf::SaveToFile(const char *szFile) const { // Open file int fh = open(szFile, O_BINARY | O_CREAT | O_WRONLY | O_SEQUENTIAL | O_TRUNC, S_IREAD | S_IWRITE); if(fh < 0) return false; // Write data if(write(fh, getData(), getLength()) != (size_t) getLength()) { close(fh); return false; } close(fh); // Ok return true; } void StdBuf::CompileFunc(StdCompiler *pComp, int iType) { // Size (guess it is a small value most of the time - if it's big, an extra byte won't hurt anyway) uint32_t tmp = iSize; pComp->Value(mkIntPackAdapt(tmp)); iSize = tmp; pComp->Seperator(StdCompiler::SEP_PART2); // Read/write data if(pComp->isCompiler()) { New(iSize); pComp->Raw(getMData(), iSize, StdCompiler::RawCompileType(iType)); } else { pComp->Raw(const_cast<void *>(getData()), iSize, StdCompiler::RawCompileType(iType)); } } // *** StdStringBuf void StdStrBuf::Format(const char *szFmt, ...) { // Create argument list va_list args; va_start(args, szFmt); // Format FormatV(szFmt, args); } void StdStrBuf::FormatV(const char *szFmt, va_list args) { // Clear previous contents Clear(); // Format AppendFormatV(szFmt, args); } void StdStrBuf::AppendFormat(const char *szFmt, ...) { // Create argument list va_list args; va_start(args, szFmt); // Format AppendFormatV(szFmt, args); } void StdStrBuf::AppendFormatV(const char *szFmt, va_list args) { if(!IsSafeFormatString(szFmt)) { BREAKPOINT_HERE szFmt = "<UNSAFE FORMAT STRING>"; } #ifdef HAVE_VASPRINTF // Format char *pStr; int iBytes = vasprintf(&pStr, szFmt, args); if(iBytes < 0 || !pStr) return; // Append if(isNull()) Take(pStr, iBytes); else { Append(pStr, iBytes); free(pStr); } #elif defined(HAVE_VSCPRINTF) // Save append start int iStart = getLength(); // Calculate size, allocate int iLength = vscprintf(szFmt, args); Grow(iLength); // Format char *pPos = getMElem<char>(*this, iSize - iLength - 1); vsprintf(getMPtr(iStart), szFmt, args); #else // Save append start int iStart = getLength(), iBytes; do { // Grow Grow(512); // Try output iBytes = vsnprintf(getMPtr(iStart), getLength() - iStart, szFmt, args); } while(iBytes < 0 || (unsigned int)(iBytes) >= getLength() - iStart); // Calculate real length, if vsnprintf didn't return anything of value iBytes = strlen(getMPtr(iStart)); // Shrink to fit SetSize(iStart + iBytes + 1); #endif } void StdStrBuf::CompileFunc(StdCompiler *pComp, int iRawType) { if(pComp->isCompiler()) { char *pnData; pComp->String(&pnData, StdCompiler::RawCompileType(iRawType)); Take(pnData); } else { char *pData = const_cast<char *>(getData()); if (!pData) pData = ""; pComp->String(&pData, StdCompiler::RawCompileType(iRawType)); } } StdStrBuf FormatString(const char *szFmt, ...) { va_list args; va_start(args, szFmt); return FormatStringV(szFmt, args); } StdStrBuf FormatStringV(const char *szFmt, va_list args) { StdStrBuf Buf; Buf.FormatV(szFmt, args); return Buf; } // replace all occurences of one string with another. Return number of replacements. int StdStrBuf::Replace(const char *szOld, const char *szNew, size_t iStartSearch) { if (!getPtr(0) || !szOld) return 0; if (!szNew) szNew = ""; int cnt=0; size_t iOldLen = strlen(szOld), iNewLen = strlen(szNew); if (iOldLen != iNewLen) { // count number of occurences to calculate new string length size_t iResultLen = getLength(); const char *szPos = getPtr(iStartSearch); while (szPos = SSearch(szPos, szOld)) { iResultLen += iNewLen - iOldLen; ++cnt; } if (!cnt) return 0; // now construct new string by replacement StdStrBuf sResult; sResult.New(iResultLen+1); const char *szRPos = getPtr(0), *szRNextPos; char *szWrite = sResult.getMPtr(0); if (iStartSearch) { memcpy(szWrite, szRPos, iStartSearch * sizeof(char)); szRPos += iStartSearch; szWrite += iStartSearch; } while (szRNextPos = SSearch(szRPos, szOld)) { memcpy(szWrite, szRPos, (szRNextPos - szRPos - iOldLen) * sizeof(char)); szWrite += (szRNextPos - szRPos - iOldLen); memcpy(szWrite, szNew, iNewLen * sizeof(char)); szWrite += iNewLen; szRPos = szRNextPos; } strcpy(szWrite, szRPos); Take(std::move(sResult)); } else { // replace directly in this string char *szRPos = getMPtr(iStartSearch); while (szRPos = const_cast<char *>(SSearch(szRPos, szOld))) { memcpy(szRPos - iOldLen, szNew, iOldLen * sizeof(char)); ++cnt; } } return cnt; } int StdStrBuf::ReplaceChar(char cOld, char cNew, size_t iStartSearch) { if (isNull()) return 0; char *szPos = getMPtr(0); if (!cOld) return 0; if (!cNew) cNew = '_'; int cnt=0; while (szPos = strchr(szPos, cOld)) { *szPos++ = cNew; ++cnt; } return cnt; } void StdStrBuf::ReplaceEnd(size_t iPos, const char *szNewEnd) { size_t iLen = getLength(); assert(iPos <= iLen); if (iPos > iLen) return; size_t iEndLen = strlen(szNewEnd); if (iLen - iPos != iEndLen) SetLength(iPos + iEndLen); memcpy(getMPtr(iPos), szNewEnd, iEndLen * sizeof(char)); } bool StdStrBuf::ValidateChars(const char *szInitialChars, const char *szMidChars) { // only given chars may be in string for (size_t i=0; i<getLength(); ++i) if (!strchr(i ? szMidChars : szInitialChars, getData()[i])) return false; return true; } bool StdStrBuf::GetSection(size_t idx, StdStrBuf *psOutSection, char cSeparator) const { assert(psOutSection); psOutSection->Clear(); const char *szStr = getData(), *szSepPos; if (!szStr) return false; // invaid argument while ((szSepPos = strchr(szStr, cSeparator)) && idx) { szStr = szSepPos+1; --idx; } if (idx) return false; // indexed section not found // fill output buffer with section, if not empty if (!szSepPos) szSepPos = getData() + getLength(); if (szSepPos != szStr) psOutSection->Copy(szStr, szSepPos - szStr); // return true even if section is empty, because the section obviously exists // (to enable loops like while (buf.GetSection(i++, &sect)) if (sect) ...) return true; } void StdStrBuf::ToLowerCase() { if (!isNull()) for (char *szPos = getMPtr(0); *szPos; ++szPos) *szPos = tolower(*szPos); } void StdStrBuf::EnsureUnicode() { bool valid = true; int need_continuation_bytes = 0; // Check wether valid UTF-8 for (size_t i = 0; i < getSize(); ++i) { unsigned char c = *getPtr(i); // remaining of a code point started before if (need_continuation_bytes) { --need_continuation_bytes; // (10000000-10111111) if (0x80 <= c && c <= 0xBF) continue; else { valid = false; break; } } // ASCII if (c < 0x80) continue; // Two byte sequence (11000010-11011111) // Note: 1100000x is an invalid overlong sequence if (0xC2 <= c && c <= 0xDF) { need_continuation_bytes = 1; continue; } // Three byte sequence (11100000-11101111) if (0xE0 <= c && c <= 0xEF) { need_continuation_bytes = 2; continue; // FIXME: could check for UTF-16 surrogates from a broken utf-16->utf-8 converter here } // Four byte sequence (11110000-11110100) if (0xF0 <= c && c <= 0xF4) { need_continuation_bytes = 3; continue; } valid = false; break; } if (need_continuation_bytes) valid = false; // assume that it's windows-1252 and convert to utf-8 if (!valid) { size_t j = 0; StdStrBuf buf; buf.Grow(getLength()); // totally unfounded statistic: most texts have less than 20 umlauts. enum { GROWSIZE = 20 }; for (size_t i = 0; i < getSize(); ++i) { unsigned char c = *getPtr(i); if (c < 0x80) { if (j >= buf.getLength()) buf.Grow(GROWSIZE); *buf.getMPtr(j++) = c; continue; } if (0xA0 <= c) { if (j + 1 >= buf.getLength()) buf.Grow(GROWSIZE); *buf.getMPtr(j++) = (0xC0 | c>>6); *buf.getMPtr(j++) = (0x80 | c & 0x3F); continue; } // Extra windows-1252-characters buf.SetLength(j); // Let's hope that no editor mangles these UTF-8 strings... static const char * extra_chars [] = { "€", "?", "‚", "ƒ", "„", "…", "†", "‡", "ˆ", "‰", "Š", "‹", "Œ", "?", "Ž", "?", "?", "‘", "’", "“", "”", "•", "–", "—", "˜", "™", "š", "›", "œ", "?", "ž", "Ÿ" }; buf.Append(extra_chars[c - 0x80]); j += strlen(extra_chars[c - 0x80]); } buf.SetLength(j); Take(std::move(buf)); } } bool StdStrBuf::TrimSpaces() { // get left trim int32_t iSpaceLeftCount = 0, iLength = getLength(); if (!iLength) return false; const char *szStr = getData(); while (iSpaceLeftCount < iLength) if (isspace((unsigned char)(unsigned char) szStr[iSpaceLeftCount])) ++iSpaceLeftCount; else break; // only spaces? Clear! if (iSpaceLeftCount == iLength) { Clear(); return true; } // get right trim int32_t iSpaceRightCount = 0; while (isspace((unsigned char)szStr[iLength - 1 - iSpaceRightCount])) ++iSpaceRightCount; // anything to trim? if (!iSpaceLeftCount && !iSpaceRightCount) return false; // only right trim? Can do this by shortening if (!iSpaceLeftCount) { SetLength(iLength - iSpaceRightCount); return true; } // left trim involved - move text and shorten memmove(getMPtr(0), szStr+iSpaceLeftCount, iLength - iSpaceLeftCount - iSpaceRightCount); SetLength(iLength - iSpaceLeftCount - iSpaceRightCount); return true; }
[ "kanibalclonk@freenet.de" ]
kanibalclonk@freenet.de
d9eeeb31199393dc58d4163312d62f58c7a3bbb3
c00982f3a7d96a729177af91ab5a71682f99527f
/module04/ex03/Cure.hpp
96f6faefb9d8042247bc8ccc7c376d5ef841de7c
[]
no_license
roknyazev/cpp
a1b9126be32a0514d8dafb1e509755b4d52a70d9
8cf3a70b809e9099fdd933e19d70ecfc2dd78f3e
refs/heads/master
2023-04-22T00:27:30.858110
2021-05-05T00:11:18
2021-05-05T00:11:18
352,736,046
0
0
null
null
null
null
UTF-8
C++
false
false
350
hpp
// // Created by Wolmer Rudy on 4/21/21. // #ifndef EX03_CURE_HPP #define EX03_CURE_HPP #include "AMateria.hpp" class Cure : public AMateria { public: virtual ~Cure(); Cure(); Cure(const Cure &original); Cure &operator=(const Cure &operand); virtual AMateria* clone() const; virtual void use(ICharacter& target); }; #endif //EX03_CURE_HPP
[ "wrudy@student.21-school.ru" ]
wrudy@student.21-school.ru
f34f24ece5a787af4d732796a887f402b36e1e99
9c16d6b984c9a22c219bd2a20a02db21a51ba8d7
/content/browser/accessibility/accessibility_ipc_error_browsertest.cc
6c47f9470c03fa94bd1a68c062798425b6bbfb50
[ "BSD-3-Clause" ]
permissive
nv-chromium/chromium-crosswalk
fc6cc201cb1d6a23d5f52ffd3a553c39acd59fa7
b21ec2ffe3a13b6a8283a002079ee63b60e1dbc5
refs/heads/nv-crosswalk-17
2022-08-25T01:23:53.343546
2019-01-16T21:35:23
2019-01-16T21:35:23
63,197,891
0
0
NOASSERTION
2019-01-16T21:38:06
2016-07-12T22:58:43
null
UTF-8
C++
false
false
7,522
cc
// Copyright (c) 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/frame_host/render_frame_host_impl.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/public/browser/ax_event_notification_details.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/content_browser_test.h" #include "content/public/test/content_browser_test_utils.h" #include "content/shell/browser/shell.h" #include "content/test/accessibility_browser_test_utils.h" #include "ui/accessibility/ax_node.h" #include "ui/accessibility/ax_tree.h" namespace content { class AccessibilityIpcErrorBrowserTest : public ContentBrowserTest { public: AccessibilityIpcErrorBrowserTest() {} protected: // Convenience method to get the value of a particular AXNode // attribute as a UTF-8 string. std::string GetAttr(const ui::AXNode* node, const ui::AXStringAttribute attr) { const ui::AXNodeData& data = node->data(); for (size_t i = 0; i < data.string_attributes.size(); ++i) { if (data.string_attributes[i].first == attr) return data.string_attributes[i].second; } return std::string(); } DISALLOW_COPY_AND_ASSIGN(AccessibilityIpcErrorBrowserTest); }; IN_PROC_BROWSER_TEST_F(AccessibilityIpcErrorBrowserTest, ResetBrowserAccessibilityManager) { // Create a data url and load it. const char url_str[] = "data:text/html," "<div aria-live='polite'>" " <p id='p1'>Paragraph One</p>" " <p id='p2'>Paragraph Two</p>" "</div>" "<button id='button'>Button</button>"; GURL url(url_str); NavigateToURL(shell(), url); // Simulate a condition where the RFH can't create a // BrowserAccessibilityManager - like if there's no view. RenderFrameHostImpl* frame = static_cast<RenderFrameHostImpl*>( shell()->web_contents()->GetMainFrame()); frame->set_no_create_browser_accessibility_manager_for_testing(true); ASSERT_EQ(nullptr, frame->GetOrCreateBrowserAccessibilityManager()); { // Enable accessibility (passing AccessibilityModeComplete to // AccessibilityNotificationWaiter does this automatically) and wait for // the first event. AccessibilityNotificationWaiter waiter( shell(), AccessibilityModeComplete, ui::AX_EVENT_LAYOUT_COMPLETE); waiter.WaitForNotification(); } // Make sure we still didn't create a BrowserAccessibilityManager. // This means that at least one accessibility IPC was lost. ASSERT_EQ(nullptr, frame->GetOrCreateBrowserAccessibilityManager()); // Now create a BrowserAccessibilityManager, simulating what would happen // if the RFH's view is created now - but then disallow recreating the // BrowserAccessibilityManager so that we can test that this one gets // destroyed. frame->set_no_create_browser_accessibility_manager_for_testing(false); ASSERT_TRUE(frame->GetOrCreateBrowserAccessibilityManager() != nullptr); frame->set_no_create_browser_accessibility_manager_for_testing(true); { // Hide one of the elements on the page, and wait for an accessibility // notification triggered by the hide. AccessibilityNotificationWaiter waiter( shell(), AccessibilityModeComplete, ui::AX_EVENT_LIVE_REGION_CHANGED); ASSERT_TRUE(ExecuteScript( shell()->web_contents(), "document.getElementById('p1').style.display = 'none';")); waiter.WaitForNotification(); } // Show that accessibility was reset because the frame doesn't have a // BrowserAccessibilityManager anymore. ASSERT_EQ(nullptr, frame->browser_accessibility_manager()); // Finally, allow creating a new accessibility manager and // ensure that we didn't kill the renderer; we can still send it messages. frame->set_no_create_browser_accessibility_manager_for_testing(false); const ui::AXTree* tree = nullptr; { AccessibilityNotificationWaiter waiter( shell(), AccessibilityModeComplete, ui::AX_EVENT_FOCUS); ASSERT_TRUE(ExecuteScript( shell()->web_contents(), "document.getElementById('button').focus();")); waiter.WaitForNotification(); tree = &waiter.GetAXTree(); } // Get the accessibility tree, ensure it reflects the final state of the // document. const ui::AXNode* root = tree->root(); // Use this for debugging if the test fails. VLOG(1) << tree->ToString(); EXPECT_EQ(ui::AX_ROLE_ROOT_WEB_AREA, root->data().role); ASSERT_EQ(2, root->child_count()); const ui::AXNode* live_region = root->ChildAtIndex(0); ASSERT_EQ(1, live_region->child_count()); EXPECT_EQ(ui::AX_ROLE_DIV, live_region->data().role); const ui::AXNode* para = live_region->ChildAtIndex(0); EXPECT_EQ(ui::AX_ROLE_PARAGRAPH, para->data().role); const ui::AXNode* button_container = root->ChildAtIndex(1); EXPECT_EQ(ui::AX_ROLE_GROUP, button_container->data().role); ASSERT_EQ(1, button_container->child_count()); const ui::AXNode* button = button_container->ChildAtIndex(0); EXPECT_EQ(ui::AX_ROLE_BUTTON, button->data().role); EXPECT_TRUE(button->data().state >> ui::AX_STATE_FOCUSED & 1); } IN_PROC_BROWSER_TEST_F(AccessibilityIpcErrorBrowserTest, MultipleBadAccessibilityIPCsKillsRenderer) { // Create a data url and load it. const char url_str[] = "data:text/html," "<button id='button'>Button</button>"; GURL url(url_str); NavigateToURL(shell(), url); RenderFrameHostImpl* frame = static_cast<RenderFrameHostImpl*>( shell()->web_contents()->GetMainFrame()); { // Enable accessibility (passing AccessibilityModeComplete to // AccessibilityNotificationWaiter does this automatically) and wait for // the first event. AccessibilityNotificationWaiter waiter( shell(), AccessibilityModeComplete, ui::AX_EVENT_LAYOUT_COMPLETE); waiter.WaitForNotification(); } // Construct a bad accessibility message that BrowserAccessibilityManager // will reject. std::vector<AXEventNotificationDetails> bad_accessibility_event_list; bad_accessibility_event_list.push_back(AXEventNotificationDetails()); bad_accessibility_event_list[0].update.node_id_to_clear = -2; // We should be able to reset accessibility |max_iterations-1| times // (see render_frame_host_impl.cc - kMaxAccessibilityResets), // but the subsequent time the renderer should be killed. int max_iterations = RenderFrameHostImpl::kMaxAccessibilityResets; for (int iteration = 0; iteration < max_iterations; iteration++) { // Send the browser accessibility the bad message. BrowserAccessibilityManager* manager = frame->GetOrCreateBrowserAccessibilityManager(); manager->OnAccessibilityEvents(bad_accessibility_event_list); // Now the frame should have deleted the BrowserAccessibilityManager. ASSERT_EQ(nullptr, frame->browser_accessibility_manager()); if (iteration == max_iterations - 1) break; AccessibilityNotificationWaiter waiter( shell(), AccessibilityModeComplete, ui::AX_EVENT_LOAD_COMPLETE); waiter.WaitForNotification(); } // Wait for the renderer to be killed. if (frame->IsRenderFrameLive()) { RenderProcessHostWatcher render_process_watcher( frame->GetProcess(), RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); render_process_watcher.Wait(); } ASSERT_FALSE(frame->IsRenderFrameLive()); } } // namespace content
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
a74e7926a71291987533b3b1155fcb96271b347b
295c9499ff320a230847ba347ce3602d78269747
/ECS/Components.hpp
23242f0929593399f52c95c2235c7c160fe327b9
[]
no_license
CristianBrazales/GameProject
dcf17512d7bc5d324d4035da0165d25e9548fe93
f7cc8a2b31215d41d84629ff080d41758e5b6ec2
refs/heads/master
2022-11-25T12:41:10.414867
2020-07-28T04:08:37
2020-07-28T04:08:37
281,443,272
0
0
null
null
null
null
UTF-8
C++
false
false
354
hpp
// // Components.hpp // New project // // Created by Cristian Brazales on 2020-07-19. // Copyright © 2020 Cristian Brazales. All rights reserved. // #ifndef Components_hpp #define Components_hpp #include "ECS.hpp" #include "TransformComponent.hpp" #include "SpriteComponent.hpp" #include "KeyboardController.hpp" #endif /* Components_hpp */
[ "cristianbrazalesmolina@gmail.com" ]
cristianbrazalesmolina@gmail.com
098bf3b9d6e93c97e7dcbe60dbfc904f34d694cc
1f542e79a6a84c7119f08ad812e48e0978ee6dc1
/C++/making_of_class1.cpp
65bb8e0a6142c463c4644e606b08855a095dca50
[]
no_license
murad034/All-Code-Semister
218dc4bc1cb6ece4b734664607bef7e80310498a
181b5d6e78bd724bfab0f72057b485e7538325e7
refs/heads/master
2022-04-03T01:06:36.983377
2020-02-04T10:55:33
2020-02-04T10:55:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
370
cpp
#include<iostream> using namespace std; class rectangle { private: int height; int width; public: void set(int ,int ); int area(); }; int rectangle::area() { return height*width; } void rectangle::set(int h,int w) { height=h; width=w; } int main() { rectangle obj; obj.set(5,6); cout<<"AREA : "<<obj.area()<<endl; return 0; }
[ "muradmd312@gmail.com" ]
muradmd312@gmail.com
bef393dc0053af976c97d857d05be84c966007a7
6ec718a05a221b3d8fe78dca9b57cde5a0f10250
/lab9/lab9.1/lab9.1/Source.cpp
0e8ed1647b7197fc0a17c24659a741a946a8440d
[]
no_license
VRytikova/OAiP_labs
0dd59b7a0bd5260d93b534c6067c6de8da1c12e4
ffb125eeeae72f8391f6c9c1e7617645fe934365
refs/heads/master
2020-09-06T19:29:40.838002
2020-02-01T10:04:21
2020-02-01T10:04:21
220,524,478
0
0
null
null
null
null
UTF-8
C++
false
false
1,511
cpp
//#define _CRT_SECURE_NO_WARNINGS //#include<stdio.h> //#include<string.h> // // //FILE* fp; //FILE* fp1; //FILE* fp2; //FILE* fp3; //int array[4] = { 12, 3, 67, 8 }; // //void main() { // errno_t err; // err = fopen_s(&fp, "C:\\Users\\User\\Documents\\Projects\\OAiP\\lab9\\lab9.1\\NameA.txt", "r+b"); // if (err == 0) printf("The file was opened\n"); // else printf("The file was not opened\n"); // //int t ; // if (fp != 0) { // fwrite(&array, sizeof(short), 4, fp); // while (!(fread(&array, sizeof(short), 4, fp)) == 0) break; // { // for (int i = 0; i < 4; i++) { // printf("%d", array[i]); // } // } // } // else printf("mistake\n"); /*if (fp != 0) { while ((t = getc(fp)) != EOF) { putchar(fp); } err = fclose(fp); } else printf("MISTAKE\n");*/ //} #define _CRT_SECURE_NO_WARNINGS #include "stdio.h" int max(int a, int b) { return a > b ? a : b; } int main() { int a, b, c; FILE* inA = fopen("C:\\Users\\User\\Documents\\Projects\\OAiP\\lab9\\lab9.1\\NameA.txt", "r"); FILE* inB = fopen("C:\\Users\\User\\Documents\\Projects\\OAiP\\lab9\\lab9.1\\NameB.txt", "r"); FILE* inC = fopen("C:\\Users\\User\\Documents\\Projects\\OAiP\\lab9\\lab9.1\\NameC.txt", "r"); FILE* outD = fopen("C:\\Users\\User\\Documents\\Projects\\OAiP\\lab9\\lab9.1\\NameD.txt", "w"); while (fscanf_s(inA, "%d", &a) > 0) { fscanf_s(inB, "%d", &b); fscanf_s(inC, "%d", &c); fprintf(outD, "%d ", max(max(a, b), c)); } fclose(inA); fclose(inB); fclose(inC); fclose(outD); return 0; }
[ "akinrv16@gmail.com" ]
akinrv16@gmail.com
cd34c1a64c8de5a23d511afb5a6bfa58aefe05a2
f0c872eb0b60bef25a7534078bb98fe402b541da
/chrome/browser/instant/instant_loader.cc
abb1a23d5a66f2cb81c9f49b9bb26535bca07c40
[ "BSD-3-Clause" ]
permissive
aYukiSekiguchi/ACCESS-Chromium
f31c3795889c5ace66eb750a235105fe2466c116
bec8149e84800b81aa0c98b5556ec8f46cb9db47
refs/heads/master
2020-06-01T19:31:30.180217
2012-07-26T08:54:49
2012-07-26T08:55:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
42,513
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/instant/instant_loader.h" #include <algorithm> #include <string> #include <utility> #include <vector> #include "base/command_line.h" #include "base/i18n/case_conversion.h" #include "base/metrics/histogram.h" #include "base/string_number_conversions.h" #include "base/timer.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/favicon/favicon_service.h" #include "chrome/browser/history/history_marshaling.h" #include "chrome/browser/history/history_tab_helper.h" #include "chrome/browser/instant/instant_loader_delegate.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/search_engines/template_url.h" #include "chrome/browser/ui/blocked_content/blocked_content_tab_helper.h" #include "chrome/browser/ui/constrained_window_tab_helper.h" #include "chrome/browser/ui/constrained_window_tab_helper_delegate.h" #include "chrome/browser/ui/tab_contents/core_tab_helper.h" #include "chrome/browser/ui/tab_contents/core_tab_helper_delegate.h" #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/render_messages.h" #include "content/browser/in_process_webkit/session_storage_namespace.h" #include "content/browser/renderer_host/render_view_host.h" #include "content/browser/renderer_host/render_widget_host.h" #include "content/browser/renderer_host/render_widget_host_view.h" #include "content/browser/tab_contents/provisional_load_details.h" #include "content/public/browser/favicon_status.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/browser/web_contents_view.h" #include "net/http/http_util.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/codec/png_codec.h" using content::NavigationController; using content::NavigationEntry; using content::WebContents; namespace { // Number of ms to delay before updating the omnibox bounds. This is only used // when the bounds of the omnibox shrinks. If the bounds grows, we update // immediately. const int kUpdateBoundsDelayMS = 1000; // If this status code is seen instant is disabled for the specified host. const int kHostBlacklistStatusCode = 403; enum PreviewUsageType { PREVIEW_CREATED, PREVIEW_DELETED, PREVIEW_LOADED, PREVIEW_SHOWN, PREVIEW_COMMITTED, PREVIEW_NUM_TYPES, }; void AddPreviewUsageForHistogram(TemplateURLID template_url_id, PreviewUsageType usage, const std::string& group) { DCHECK(0 <= usage && usage < PREVIEW_NUM_TYPES); // Only track the histogram for the instant loaders, for now. if (template_url_id) { UMA_HISTOGRAM_ENUMERATION("Instant.Previews" + group, usage, PREVIEW_NUM_TYPES); } } SessionStorageNamespace* GetSessionStorageNamespace(TabContentsWrapper* tab) { return tab->web_contents()->GetController().GetSessionStorageNamespace(); } } // namespace // static const char* const InstantLoader::kInstantHeader = "X-Purpose"; // static const char* const InstantLoader::kInstantHeaderValue = "instant"; // FrameLoadObserver is responsible for determining if the page supports // instant after it has loaded. class InstantLoader::FrameLoadObserver : public content::NotificationObserver { public: FrameLoadObserver(InstantLoader* loader, WebContents* web_contents, const string16& text, bool verbatim) : loader_(loader), web_contents_(web_contents), text_(text), verbatim_(verbatim), unique_id_( web_contents_->GetController().GetPendingEntry()->GetUniqueID()) { registrar_.Add(this, content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, content::Source<WebContents>(web_contents_)); } // Sets the text to send to the page. void set_text(const string16& text) { text_ = text; } // Sets whether verbatim results are obtained rather than predictive. void set_verbatim(bool verbatim) { verbatim_ = verbatim; } // content::NotificationObserver: virtual void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) OVERRIDE; private: InstantLoader* loader_; // The WebContents we're listening for changes on. WebContents* web_contents_; // Text to send down to the page. string16 text_; // Whether verbatim results are obtained. bool verbatim_; // unique_id of the NavigationEntry we're waiting on. const int unique_id_; // Registers and unregisters us for notifications. content::NotificationRegistrar registrar_; DISALLOW_COPY_AND_ASSIGN(FrameLoadObserver); }; void InstantLoader::FrameLoadObserver::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME: { int page_id = *(content::Details<int>(details).ptr()); NavigationEntry* active_entry = web_contents_->GetController().GetActiveEntry(); if (!active_entry || active_entry->GetPageID() != page_id || active_entry->GetUniqueID() != unique_id_) { return; } loader_->SendBoundsToPage(true); // TODO: support real cursor position. int text_length = static_cast<int>(text_.size()); RenderViewHost* host = web_contents_->GetRenderViewHost(); host->Send(new ChromeViewMsg_DetermineIfPageSupportsInstant( host->routing_id(), text_, verbatim_, text_length, text_length)); break; } default: NOTREACHED(); break; } } // TabContentsDelegateImpl ----------------------------------------------------- class InstantLoader::TabContentsDelegateImpl : public content::WebContentsDelegate, public CoreTabHelperDelegate, public ConstrainedWindowTabHelperDelegate, public content::NotificationObserver, public content::WebContentsObserver { public: explicit TabContentsDelegateImpl(InstantLoader* loader); // Invoked prior to loading a new URL. void PrepareForNewLoad(); // Invoked when the preview paints. Invokes PreviewPainted on the loader. void PreviewPainted(); bool is_mouse_down_from_activate() const { return is_mouse_down_from_activate_; } void set_user_typed_before_load() { user_typed_before_load_ = true; } // Sets the last URL that will be added to history when CommitHistory is // invoked and removes all but the first navigation. void SetLastHistoryURLAndPrune(const GURL& url); // Commits the currently buffered history. void CommitHistory(bool supports_instant); void RegisterForPaintNotifications(RenderWidgetHost* render_widget_host); void UnregisterForPaintNotifications(); // NotificationObserver: virtual void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) OVERRIDE; // content::WebContentsDelegate: virtual void NavigationStateChanged(const WebContents* source, unsigned changed_flags) OVERRIDE; virtual void AddNavigationHeaders(const GURL& url, std::string* headers) OVERRIDE; virtual bool ShouldSuppressDialogs() OVERRIDE; virtual void BeforeUnloadFired(content::WebContents* tab, bool proceed, bool* proceed_to_fire_unload) OVERRIDE; virtual void SetFocusToLocationBar(bool select_all) OVERRIDE; virtual bool ShouldFocusPageAfterCrash() OVERRIDE; virtual void LostCapture() OVERRIDE; // If the user drags, we won't get a mouse up (at least on Linux). Commit the // instant result when the drag ends, so that during the drag the page won't // move around. virtual void DragEnded() OVERRIDE; virtual bool CanDownload(content::WebContents* source, int request_id) OVERRIDE; virtual void HandleMouseUp() OVERRIDE; virtual void HandleMouseActivate() OVERRIDE; virtual bool OnGoToEntryOffset(int offset) OVERRIDE; virtual bool ShouldAddNavigationToHistory( const history::HistoryAddPageArgs& add_page_args, content::NavigationType navigation_type) OVERRIDE; // CoreTabHelperDelegate: virtual void SwapTabContents(TabContentsWrapper* old_tc, TabContentsWrapper* new_tc) OVERRIDE; // ConstrainedWindowTabHelperDelegate: virtual void WillShowConstrainedWindow(TabContentsWrapper* source) OVERRIDE; virtual bool ShouldFocusConstrainedWindow() OVERRIDE; // content::WebContentsObserver: virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE; private: typedef std::vector<scoped_refptr<history::HistoryAddPageArgs> > AddPageVector; // Message from renderer indicating the page has suggestions. void OnSetSuggestions( int32 page_id, const std::vector<std::string>& suggestions, InstantCompleteBehavior behavior); // Messages from the renderer when we've determined whether the page supports // instant. void OnInstantSupportDetermined(int32 page_id, bool result); void CommitFromMouseReleaseIfNecessary(); InstantLoader* loader_; content::NotificationRegistrar registrar_; // If we are registered for paint notifications on a RenderWidgetHost this // will contain a pointer to it. RenderWidgetHost* registered_render_widget_host_; // Used to cache data that needs to be added to history. Normally entries are // added to history as the user types, but for instant we only want to add the // items to history if the user commits instant. So, we cache them here and if // committed then add the items to history. AddPageVector add_page_vector_; // Are we we waiting for a NavigationType of NEW_PAGE? If we're waiting for // NEW_PAGE navigation we don't add history items to add_page_vector_. bool waiting_for_new_page_; // True if the mouse is down from an activate. bool is_mouse_down_from_activate_; // True if the user typed in the search box before the page loaded. bool user_typed_before_load_; DISALLOW_COPY_AND_ASSIGN(TabContentsDelegateImpl); }; InstantLoader::TabContentsDelegateImpl::TabContentsDelegateImpl( InstantLoader* loader) : content::WebContentsObserver(loader->preview_contents()->web_contents()), loader_(loader), registered_render_widget_host_(NULL), waiting_for_new_page_(true), is_mouse_down_from_activate_(false), user_typed_before_load_(false) { DCHECK(loader->preview_contents()); registrar_.Add(this, content::NOTIFICATION_INTERSTITIAL_ATTACHED, content::Source<WebContents>(loader->preview_contents()->web_contents())); registrar_.Add(this, content::NOTIFICATION_FAIL_PROVISIONAL_LOAD_WITH_ERROR, content::Source<NavigationController>( &loader->preview_contents()->web_contents()->GetController())); } void InstantLoader::TabContentsDelegateImpl::PrepareForNewLoad() { user_typed_before_load_ = false; waiting_for_new_page_ = true; add_page_vector_.clear(); UnregisterForPaintNotifications(); } void InstantLoader::TabContentsDelegateImpl::PreviewPainted() { loader_->PreviewPainted(); } void InstantLoader::TabContentsDelegateImpl::SetLastHistoryURLAndPrune( const GURL& url) { if (add_page_vector_.empty()) return; history::HistoryAddPageArgs* args = add_page_vector_.front().get(); args->url = url; args->redirects.clear(); args->redirects.push_back(url); // Prune all but the first entry. add_page_vector_.erase(add_page_vector_.begin() + 1, add_page_vector_.end()); } void InstantLoader::TabContentsDelegateImpl::CommitHistory( bool supports_instant) { TabContentsWrapper* tab = loader_->preview_contents(); if (tab->profile()->IsOffTheRecord()) return; for (size_t i = 0; i < add_page_vector_.size(); ++i) { tab->history_tab_helper()->UpdateHistoryForNavigation( add_page_vector_[i].get()); } NavigationEntry* active_entry = tab->web_contents()->GetController().GetActiveEntry(); if (!active_entry) { // It appears to be possible to get here with no active entry. This seems // to be possible with an auth dialog, but I can't narrow down the // circumstances. If you hit this, file a bug with the steps you did and // assign it to me (sky). NOTREACHED(); return; } tab->history_tab_helper()->UpdateHistoryPageTitle(*active_entry); FaviconService* favicon_service = tab->profile()->GetFaviconService(Profile::EXPLICIT_ACCESS); if (favicon_service && active_entry->GetFavicon().valid && !active_entry->GetFavicon().bitmap.empty()) { std::vector<unsigned char> image_data; gfx::PNGCodec::EncodeBGRASkBitmap(active_entry->GetFavicon().bitmap, false, &image_data); favicon_service->SetFavicon(active_entry->GetURL(), active_entry->GetFavicon().url, image_data, history::FAVICON); if (supports_instant && !add_page_vector_.empty()) { // If we're using the instant API, then we've tweaked the url that is // going to be added to history. We need to also set the favicon for the // url we're adding to history (see comment in ReleasePreviewContents // for details). favicon_service->SetFavicon(add_page_vector_.back()->url, active_entry->GetFavicon().url, image_data, history::FAVICON); } } } void InstantLoader::TabContentsDelegateImpl::RegisterForPaintNotifications( RenderWidgetHost* render_widget_host) { DCHECK(registered_render_widget_host_ == NULL); registered_render_widget_host_ = render_widget_host; content::Source<RenderWidgetHost> source = content::Source<RenderWidgetHost>(registered_render_widget_host_); registrar_.Add(this, content::NOTIFICATION_RENDER_WIDGET_HOST_DID_PAINT, source); registrar_.Add(this, content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED, source); } void InstantLoader::TabContentsDelegateImpl::UnregisterForPaintNotifications() { if (registered_render_widget_host_) { content::Source<RenderWidgetHost> source = content::Source<RenderWidgetHost>(registered_render_widget_host_); registrar_.Remove(this, content::NOTIFICATION_RENDER_WIDGET_HOST_DID_PAINT, source); registrar_.Remove(this, content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED, source); registered_render_widget_host_ = NULL; } } void InstantLoader::TabContentsDelegateImpl::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case content::NOTIFICATION_FAIL_PROVISIONAL_LOAD_WITH_ERROR: if (content::Details<ProvisionalLoadDetails>(details)->url() == loader_->url_) { // This typically happens with downloads (which are disabled with // instant active). To ensure the download happens when the user presses // enter we set needs_reload_ to true, which triggers a reload. loader_->needs_reload_ = true; } break; case content::NOTIFICATION_RENDER_WIDGET_HOST_DID_PAINT: UnregisterForPaintNotifications(); PreviewPainted(); break; case content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED: UnregisterForPaintNotifications(); break; case content::NOTIFICATION_INTERSTITIAL_ATTACHED: PreviewPainted(); break; default: NOTREACHED() << "Got a notification we didn't register for."; } } void InstantLoader::TabContentsDelegateImpl::NavigationStateChanged( const WebContents* source, unsigned changed_flags) { if (!loader_->ready() && !registered_render_widget_host_ && source->GetController().GetEntryCount()) { // The load has been committed. Install an observer that waits for the // first paint then makes the preview active. We wait for the load to be // committed before waiting on paint as there is always an initial paint // when a new renderer is created from the resize so that if we showed the // preview after the first paint we would end up with a white rect. RenderWidgetHostView *rwhv = source->GetRenderWidgetHostView(); if (rwhv) RegisterForPaintNotifications(rwhv->GetRenderWidgetHost()); } else if (source->IsCrashed()) { PreviewPainted(); } } void InstantLoader::TabContentsDelegateImpl::AddNavigationHeaders( const GURL& url, std::string* headers) { net::HttpUtil::AppendHeaderIfMissing(kInstantHeader, kInstantHeaderValue, headers); } bool InstantLoader::TabContentsDelegateImpl::ShouldSuppressDialogs() { // Any message shown during instant cancels instant, so we suppress them. return true; } void InstantLoader::TabContentsDelegateImpl::BeforeUnloadFired( WebContents* tab, bool proceed, bool* proceed_to_fire_unload) { } void InstantLoader::TabContentsDelegateImpl::SetFocusToLocationBar( bool select_all) { } bool InstantLoader::TabContentsDelegateImpl::ShouldFocusPageAfterCrash() { return false; } void InstantLoader::TabContentsDelegateImpl::LostCapture() { CommitFromMouseReleaseIfNecessary(); } void InstantLoader::TabContentsDelegateImpl::DragEnded() { CommitFromMouseReleaseIfNecessary(); } bool InstantLoader::TabContentsDelegateImpl::CanDownload(WebContents* source, int request_id) { // Downloads are disabled. return false; } void InstantLoader::TabContentsDelegateImpl::HandleMouseUp() { CommitFromMouseReleaseIfNecessary(); } void InstantLoader::TabContentsDelegateImpl::HandleMouseActivate() { is_mouse_down_from_activate_ = true; } bool InstantLoader::TabContentsDelegateImpl::OnGoToEntryOffset(int offset) { return false; } bool InstantLoader::TabContentsDelegateImpl::ShouldAddNavigationToHistory( const history::HistoryAddPageArgs& add_page_args, content::NavigationType navigation_type) { if (waiting_for_new_page_ && navigation_type == content::NAVIGATION_TYPE_NEW_PAGE) { waiting_for_new_page_ = false; } if (!waiting_for_new_page_) { add_page_vector_.push_back( scoped_refptr<history::HistoryAddPageArgs>(add_page_args.Clone())); } return false; } // If this is being called, something is swapping in to our preview_contents_ // before we've added it to the tab strip. void InstantLoader::TabContentsDelegateImpl::SwapTabContents( TabContentsWrapper* old_tc, TabContentsWrapper* new_tc) { loader_->ReplacePreviewContents(old_tc, new_tc); } bool InstantLoader::TabContentsDelegateImpl::ShouldFocusConstrainedWindow() { // Return false so that constrained windows are not initially focused. If // we did otherwise the preview would prematurely get committed when focus // goes to the constrained window. return false; } void InstantLoader::TabContentsDelegateImpl::WillShowConstrainedWindow( TabContentsWrapper* source) { if (!loader_->ready()) { // A constrained window shown for an auth may not paint. Show the preview // contents. UnregisterForPaintNotifications(); loader_->ShowPreview(); } } bool InstantLoader::TabContentsDelegateImpl::OnMessageReceived( const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(TabContentsDelegateImpl, message) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_SetSuggestions, OnSetSuggestions) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_InstantSupportDetermined, OnInstantSupportDetermined) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void InstantLoader::TabContentsDelegateImpl::OnSetSuggestions( int32 page_id, const std::vector<std::string>& suggestions, InstantCompleteBehavior behavior) { TabContentsWrapper* source = loader_->preview_contents(); NavigationEntry* entry = source->web_contents()->GetController().GetActiveEntry(); if (!entry || page_id != entry->GetPageID()) return; if (suggestions.empty()) loader_->SetCompleteSuggestedText(string16(), behavior); else loader_->SetCompleteSuggestedText(UTF8ToUTF16(suggestions[0]), behavior); } void InstantLoader::TabContentsDelegateImpl::OnInstantSupportDetermined( int32 page_id, bool result) { WebContents* source = loader_->preview_contents()->web_contents(); if (!source->GetController().GetActiveEntry() || page_id != source->GetController().GetActiveEntry()->GetPageID()) return; content::Details<const bool> details(&result); content::NotificationService::current()->Notify( chrome::NOTIFICATION_INSTANT_SUPPORT_DETERMINED, content::NotificationService::AllSources(), details); if (result) loader_->PageFinishedLoading(); else loader_->PageDoesntSupportInstant(user_typed_before_load_); } void InstantLoader::TabContentsDelegateImpl ::CommitFromMouseReleaseIfNecessary() { bool was_down = is_mouse_down_from_activate_; is_mouse_down_from_activate_ = false; if (was_down && loader_->ShouldCommitInstantOnMouseUp()) loader_->CommitInstantLoader(); } // InstantLoader --------------------------------------------------------------- InstantLoader::InstantLoader(InstantLoaderDelegate* delegate, TemplateURLID id, const std::string& group) : delegate_(delegate), template_url_id_(id), ready_(false), http_status_ok_(true), last_transition_type_(content::PAGE_TRANSITION_LINK), verbatim_(false), needs_reload_(false), group_(group) { } InstantLoader::~InstantLoader() { registrar_.RemoveAll(); // Delete the TabContents before the delegate as the TabContents holds a // reference to the delegate. if (preview_contents()) AddPreviewUsageForHistogram(template_url_id_, PREVIEW_DELETED, group_); preview_contents_.reset(); } bool InstantLoader::Update(TabContentsWrapper* tab_contents, const TemplateURL* template_url, const GURL& url, content::PageTransition transition_type, const string16& user_text, bool verbatim, string16* suggested_text) { DCHECK(!url.is_empty() && url.is_valid()); // Strip leading ?. string16 new_user_text = !user_text.empty() && (UTF16ToWide(user_text)[0] == L'?') ? user_text.substr(1) : user_text; // We should preserve the transition type regardless of whether we're already // showing the url. last_transition_type_ = transition_type; // If state hasn't changed, reuse the last suggestion. There are two cases: // 1. If no template url (not using instant API), then we only care if the url // changes. // 2. Template url (using instant API) then the important part is if the // user_text changes. // We have to be careful in checking user_text as in some situations // InstantController passes in an empty string (when it knows the user_text // won't matter). if ((!template_url_id_ && url_ == url) || (template_url_id_ && (new_user_text.empty() || user_text_ == new_user_text))) { suggested_text->assign(last_suggestion_); // Track the url even if we're not going to update. This is important as // when we get the suggest text we set user_text_ to the new suggest text, // but yet the url is much different. url_ = url; return false; } url_ = url; user_text_ = new_user_text; verbatim_ = verbatim; last_suggestion_.clear(); needs_reload_ = false; bool created_preview_contents = preview_contents_.get() == NULL; if (created_preview_contents) CreatePreviewContents(tab_contents); if (template_url) { DCHECK(template_url_id_ == template_url->id()); if (!created_preview_contents) { if (is_determining_if_page_supports_instant()) { // The page hasn't loaded yet. We'll send the script down when it does. frame_load_observer_->set_text(user_text_); frame_load_observer_->set_verbatim(verbatim); preview_tab_contents_delegate_->set_user_typed_before_load(); return true; } // TODO: support real cursor position. int text_length = static_cast<int>(user_text_.size()); RenderViewHost* host = preview_contents_->web_contents()->GetRenderViewHost(); host->Send(new ChromeViewMsg_SearchBoxChange( host->routing_id(), user_text_, verbatim, text_length, text_length)); string16 complete_suggested_text_lower = base::i18n::ToLower( complete_suggested_text_); string16 user_text_lower = base::i18n::ToLower(user_text_); if (!verbatim && complete_suggested_text_lower.size() > user_text_lower.size() && !complete_suggested_text_lower.compare(0, user_text_lower.size(), user_text_lower)) { *suggested_text = last_suggestion_ = complete_suggested_text_.substr(user_text_.size()); } } else { LoadInstantURL(tab_contents, template_url, transition_type, user_text_, verbatim); } } else { DCHECK(template_url_id_ == 0); preview_tab_contents_delegate_->PrepareForNewLoad(); frame_load_observer_.reset(NULL); preview_contents_->web_contents()->GetController().LoadURL( url_, content::Referrer(), transition_type, std::string()); } return true; } void InstantLoader::SetOmniboxBounds(const gfx::Rect& bounds) { if (omnibox_bounds_ == bounds) return; // Don't update the page while the mouse is down. http://crbug.com/71952 if (IsMouseDownFromActivate()) return; omnibox_bounds_ = bounds; if (preview_contents_.get() && is_showing_instant() && !is_determining_if_page_supports_instant()) { // Updating the bounds is rather expensive, and because of the async nature // of the omnibox the bounds can dance around a bit. Delay the update in // hopes of things settling down. To avoid hiding results we grow // immediately, but delay shrinking. update_bounds_timer_.Stop(); if (omnibox_bounds_.height() > last_omnibox_bounds_.height()) { SendBoundsToPage(false); } else { update_bounds_timer_.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(kUpdateBoundsDelayMS), this, &InstantLoader::ProcessBoundsChange); } } } bool InstantLoader::IsMouseDownFromActivate() { return preview_tab_contents_delegate_.get() && preview_tab_contents_delegate_->is_mouse_down_from_activate(); } TabContentsWrapper* InstantLoader::ReleasePreviewContents( InstantCommitType type, TabContentsWrapper* tab_contents) { if (!preview_contents_.get()) return NULL; // FrameLoadObserver is only used for instant results, and instant results are // only committed if active (when the FrameLoadObserver isn't installed). DCHECK(type == INSTANT_COMMIT_DESTROY || !frame_load_observer_.get()); if (type != INSTANT_COMMIT_DESTROY && is_showing_instant()) { RenderViewHost* host = preview_contents_->web_contents()->GetRenderViewHost(); if (type == INSTANT_COMMIT_FOCUS_LOST) { host->Send(new ChromeViewMsg_SearchBoxCancel(host->routing_id())); } else { host->Send(new ChromeViewMsg_SearchBoxSubmit( host->routing_id(), user_text_, type == INSTANT_COMMIT_PRESSED_ENTER)); } } omnibox_bounds_ = gfx::Rect(); last_omnibox_bounds_ = gfx::Rect(); GURL url; url.Swap(&url_); user_text_.clear(); complete_suggested_text_.clear(); if (preview_contents_.get()) { if (type != INSTANT_COMMIT_DESTROY) { if (template_url_id_) { // The URL used during instant is mostly gibberish, and not something // we'll parse and match as a past search. Set it to something we can // parse. preview_tab_contents_delegate_->SetLastHistoryURLAndPrune(url); } preview_tab_contents_delegate_->CommitHistory(template_url_id_ != 0); } if (preview_contents_->web_contents()->GetRenderWidgetHostView()) { #if defined(OS_MACOSX) preview_contents_->web_contents()->GetRenderWidgetHostView()-> SetTakesFocusOnlyOnMouseDown(false); registrar_.Remove( this, content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED, content::Source<NavigationController>( &preview_contents_->web_contents()->GetController())); #endif } preview_contents_->web_contents()->SetDelegate(NULL); ready_ = false; } update_bounds_timer_.Stop(); AddPreviewUsageForHistogram(template_url_id_, type == INSTANT_COMMIT_DESTROY ? PREVIEW_DELETED : PREVIEW_COMMITTED, group_); if (type != INSTANT_COMMIT_DESTROY) { UMA_HISTOGRAM_ENUMERATION( "Instant.SessionStorageNamespace" + group_, tab_contents == NULL || session_storage_namespace_ == GetSessionStorageNamespace(tab_contents), 2); } session_storage_namespace_ = NULL; return preview_contents_.release(); } bool InstantLoader::ShouldCommitInstantOnMouseUp() { return delegate_->ShouldCommitInstantOnMouseUp(); } void InstantLoader::CommitInstantLoader() { delegate_->CommitInstantLoader(this); } void InstantLoader::MaybeLoadInstantURL(TabContentsWrapper* tab_contents, const TemplateURL* template_url) { DCHECK(template_url_id_ == template_url->id()); // If we already have a |preview_contents_|, future search queries will be // issued into it (see the "if (!created_preview_contents)" block in |Update| // above), so there is no need to load the |template_url|'s instant URL. if (preview_contents_.get()) return; CreatePreviewContents(tab_contents); LoadInstantURL(tab_contents, template_url, content::PAGE_TRANSITION_GENERATED, string16(), true); } bool InstantLoader::IsNavigationPending() const { return preview_contents_.get() && preview_contents_->web_contents()->GetController().GetPendingEntry(); } void InstantLoader::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { #if defined(OS_MACOSX) if (type == content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED) { if (preview_contents_->web_contents()->GetRenderWidgetHostView()) { preview_contents_->web_contents()->GetRenderWidgetHostView()-> SetTakesFocusOnlyOnMouseDown(true); } return; } #endif if (type == content::NOTIFICATION_NAV_ENTRY_COMMITTED) { content::LoadCommittedDetails* load_details = content::Details<content::LoadCommittedDetails>(details).ptr(); if (load_details->is_main_frame) { if (load_details->http_status_code == kHostBlacklistStatusCode) { delegate_->AddToBlacklist(this, load_details->entry->GetURL()); } else { SetHTTPStatusOK(load_details->http_status_code == 200); } } return; } NOTREACHED() << "Got a notification we didn't register for."; } void InstantLoader::SetCompleteSuggestedText( const string16& complete_suggested_text, InstantCompleteBehavior behavior) { if (!is_showing_instant()) { // We're not trying to use the instant API with this page. Ignore it. return; } ShowPreview(); if (complete_suggested_text == complete_suggested_text_) return; if (verbatim_) { // Don't show suggest results for verbatim queries. return; } string16 user_text_lower = base::i18n::ToLower(user_text_); string16 complete_suggested_text_lower = base::i18n::ToLower( complete_suggested_text); last_suggestion_.clear(); if (user_text_lower.compare(0, user_text_lower.size(), complete_suggested_text_lower, 0, user_text_lower.size())) { // The user text no longer contains the suggested text, ignore it. complete_suggested_text_.clear(); delegate_->SetSuggestedTextFor(this, string16(), behavior); return; } complete_suggested_text_ = complete_suggested_text; if (behavior == INSTANT_COMPLETE_NOW) { // We are effectively showing complete_suggested_text_ now. Update // user_text_ so we don't notify the page again if Update happens to be // invoked (which is more than likely if this callback completes before the // omnibox is done). string16 suggestion = complete_suggested_text_.substr(user_text_.size()); user_text_ = complete_suggested_text_; delegate_->SetSuggestedTextFor(this, suggestion, behavior); } else { DCHECK((behavior == INSTANT_COMPLETE_DELAYED) || (behavior == INSTANT_COMPLETE_NEVER)); last_suggestion_ = complete_suggested_text_.substr(user_text_.size()); delegate_->SetSuggestedTextFor(this, last_suggestion_, behavior); } } void InstantLoader::PreviewPainted() { // If instant is supported then we wait for the first suggest result before // showing the page. if (!template_url_id_) ShowPreview(); } void InstantLoader::SetHTTPStatusOK(bool is_ok) { if (is_ok == http_status_ok_) return; http_status_ok_ = is_ok; if (ready_) delegate_->InstantStatusChanged(this); } void InstantLoader::ShowPreview() { if (!ready_) { ready_ = true; delegate_->InstantStatusChanged(this); AddPreviewUsageForHistogram(template_url_id_, PREVIEW_SHOWN, group_); } } void InstantLoader::PageFinishedLoading() { frame_load_observer_.reset(); // Send the bounds of the omnibox down now. SendBoundsToPage(false); // Wait for the user input before showing, this way the page should be up to // date by the time we show it. AddPreviewUsageForHistogram(template_url_id_, PREVIEW_LOADED, group_); } // TODO(tonyg): This method only fires when the omnibox bounds change. It also // needs to fire when the preview bounds change (e.g. open/close info bar). gfx::Rect InstantLoader::GetOmniboxBoundsInTermsOfPreview() { gfx::Rect preview_bounds(delegate_->GetInstantBounds()); gfx::Rect intersection(omnibox_bounds_.Intersect(preview_bounds)); // Translate into window's coordinates. if (!intersection.IsEmpty()) { intersection.Offset(-preview_bounds.origin().x(), -preview_bounds.origin().y()); } // In the current Chrome UI, these must always be true so they sanity check // the above operations. In a future UI, these may be removed or adjusted. // There is no point in sanity-checking |intersection.y()| because the omnibox // can be placed anywhere vertically relative to the preview (for example, in // Mac fullscreen mode, the omnibox is entirely enclosed by the preview // bounds). DCHECK_LE(0, intersection.x()); DCHECK_LE(0, intersection.width()); DCHECK_LE(0, intersection.height()); return intersection; } void InstantLoader::PageDoesntSupportInstant(bool needs_reload) { frame_load_observer_.reset(NULL); delegate_->InstantLoaderDoesntSupportInstant(this); AddPreviewUsageForHistogram(template_url_id_, PREVIEW_LOADED, group_); } void InstantLoader::ProcessBoundsChange() { SendBoundsToPage(false); } void InstantLoader::SendBoundsToPage(bool force_if_waiting) { if (last_omnibox_bounds_ == omnibox_bounds_) return; if (preview_contents_.get() && is_showing_instant() && (force_if_waiting || !is_determining_if_page_supports_instant())) { last_omnibox_bounds_ = omnibox_bounds_; RenderViewHost* host = preview_contents_->web_contents()->GetRenderViewHost(); host->Send(new ChromeViewMsg_SearchBoxResize( host->routing_id(), GetOmniboxBoundsInTermsOfPreview())); } } void InstantLoader::ReplacePreviewContents(TabContentsWrapper* old_tc, TabContentsWrapper* new_tc) { DCHECK(old_tc == preview_contents_); // We release here without deleting so that the caller still has reponsibility // for deleting the TabContentsWrapper. ignore_result(preview_contents_.release()); preview_contents_.reset(new_tc); session_storage_namespace_ = GetSessionStorageNamespace(new_tc); // Make sure the new preview contents acts like the old one. SetupPreviewContents(old_tc); // Cleanup the old preview contents. old_tc->constrained_window_tab_helper()->set_delegate(NULL); old_tc->core_tab_helper()->set_delegate(NULL); old_tc->web_contents()->SetDelegate(NULL); #if defined(OS_MACOSX) registrar_.Remove( this, content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED, content::Source<NavigationController>( &old_tc->web_contents()->GetController())); #endif registrar_.Remove( this, content::NOTIFICATION_NAV_ENTRY_COMMITTED, content::Source<NavigationController>( &old_tc->web_contents()->GetController())); // We prerendered so we should be ready to show. If we're ready, swap in // immediately, otherwise show the preview as normal. if (ready_) delegate_->SwappedTabContents(this); else ShowPreview(); } void InstantLoader::SetupPreviewContents(TabContentsWrapper* tab_contents) { preview_contents_->web_contents()->SetDelegate( preview_tab_contents_delegate_.get()); preview_contents_->blocked_content_tab_helper()->SetAllContentsBlocked(true); preview_contents_->constrained_window_tab_helper()->set_delegate( preview_tab_contents_delegate_.get()); preview_contents_->core_tab_helper()->set_delegate( preview_tab_contents_delegate_.get()); #if defined(OS_MACOSX) // If |preview_contents_| does not currently have a RWHV, we will call // SetTakesFocusOnlyOnMouseDown() as a result of the // RENDER_VIEW_HOST_CHANGED notification. if (preview_contents_->web_contents()->GetRenderWidgetHostView()) { preview_contents_->web_contents()->GetRenderWidgetHostView()-> SetTakesFocusOnlyOnMouseDown(true); } registrar_.Add( this, content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED, content::Source<NavigationController>( &preview_contents_->web_contents()->GetController())); #endif registrar_.Add( this, content::NOTIFICATION_NAV_ENTRY_COMMITTED, content::Source<NavigationController>( &preview_contents_->web_contents()->GetController())); gfx::Rect tab_bounds; tab_contents->web_contents()->GetView()->GetContainerBounds(&tab_bounds); preview_contents_->web_contents()->GetView()->SizeContents(tab_bounds.size()); } void InstantLoader::CreatePreviewContents(TabContentsWrapper* tab_contents) { WebContents* new_contents = WebContents::Create( tab_contents->profile(), NULL, MSG_ROUTING_NONE, NULL, NULL); preview_contents_.reset(new TabContentsWrapper(new_contents)); AddPreviewUsageForHistogram(template_url_id_, PREVIEW_CREATED, group_); session_storage_namespace_ = GetSessionStorageNamespace(tab_contents); preview_tab_contents_delegate_.reset(new TabContentsDelegateImpl(this)); SetupPreviewContents(tab_contents); preview_contents_->web_contents()->ShowContents(); } void InstantLoader::LoadInstantURL(TabContentsWrapper* tab_contents, const TemplateURL* template_url, content::PageTransition transition_type, const string16& user_text, bool verbatim) { preview_tab_contents_delegate_->PrepareForNewLoad(); // Load the instant URL. We don't reflect the url we load in url() as // callers expect that we're loading the URL they tell us to. // // This uses an empty string for the replacement text as the url doesn't // really have the search params, but we need to use the replace // functionality so that embeded tags (like {google:baseURL}) are escaped // correctly. // TODO(sky): having to use a replaceable url is a bit of a hack here. GURL instant_url(template_url->instant_url()->ReplaceSearchTermsUsingProfile( tab_contents->profile(), *template_url, string16(), -1, string16())); CommandLine* cl = CommandLine::ForCurrentProcess(); if (cl->HasSwitch(switches::kInstantURL)) instant_url = GURL(cl->GetSwitchValueASCII(switches::kInstantURL)); preview_contents_->web_contents()->GetController().LoadURL( instant_url, content::Referrer(), transition_type, std::string()); RenderViewHost* host = preview_contents_->web_contents()->GetRenderViewHost(); preview_contents_->web_contents()->HideContents(); // If user_text is empty, this must be a preload of the search homepage. In // that case, send down a SearchBoxResize message, which will switch the page // to "search results" UI. This avoids flicker when the page is shown with // results. In addition, we don't want the page accidentally causing the // preloaded page to be displayed yet (by calling setSuggestions), so don't // send a SearchBoxChange message. if (user_text.empty()) { host->Send(new ChromeViewMsg_SearchBoxResize( host->routing_id(), GetOmniboxBoundsInTermsOfPreview())); } else { host->Send(new ChromeViewMsg_SearchBoxChange( host->routing_id(), user_text, verbatim, 0, 0)); } frame_load_observer_.reset(new FrameLoadObserver( this, preview_contents()->web_contents(), user_text, verbatim)); }
[ "yuki.sekiguchi@access-company.com" ]
yuki.sekiguchi@access-company.com
fde615913bd36df49fa0dc57de9534e29aef1e23
95efaa256914926ac30acbb1a8c89c320c19bf40
/HeCore/IInitializeable.h
ea8c4663dcc890fadbd6193676652a8d77f21d11
[]
no_license
mabo0001/QtCode
bc2d80446a160d97b4034fa1c068324ba939cb20
9038f05da33c870c1e9808791f03467dcc19a4ab
refs/heads/master
2022-08-26T13:36:14.021944
2019-07-15T01:12:51
2019-07-15T01:12:51
266,298,758
1
0
null
2020-05-23T08:54:08
2020-05-23T08:54:07
null
UTF-8
C++
false
false
604
h
/*************************************************************************************************** ** 2018-06-19 IInitializeable 可初始化接口。 ***************************************************************************************************/ #ifndef IINITIALIZEABLE_H #define IINITIALIZEABLE_H #include "HCoreGlobal.h" #include <QtCore/QVariant> HE_CORE_BEGIN_NAMESPACE class IInitializeable { public: // 初始化 virtual void initialize(QVariantMap param) = 0; // 类型名称 virtual QString typeName() = 0; }; HE_CORE_END_NAMESPACE #endif // IINITIALIZEABLE_H
[ "hexianqi@msn.com" ]
hexianqi@msn.com
2a8cb51532856358610bef518ed37bc9a36b78f9
7d0f76a3b69b1841d74dda54cd34e459c7da5aaf
/src/utils/BamTools/src/utils/bamtools_filter_properties.h
a69f31d643f558ec58208d7054585005374a1eaf
[ "MIT", "LicenseRef-scancode-public-domain" ]
permissive
arq5x/lumpy-sv
aa313dd1dc24c5966a4347445180c9bb0fafc24a
f24085f5d7865579e390add664ebbd9383fa0536
refs/heads/master
2022-06-23T14:04:51.403033
2022-06-07T21:10:43
2022-06-07T21:10:43
6,121,988
285
127
MIT
2022-06-07T21:10:44
2012-10-08T09:09:26
C
UTF-8
C++
false
false
7,917
h
// *************************************************************************** // bamtools_filter_properties.h (c) 2010 Derek Barnett, Erik Garrison // Marth Lab, Department of Biology, Boston College // --------------------------------------------------------------------------- // Last modified: 10 October 2011 // --------------------------------------------------------------------------- // Provides support data structures & methods for FilterEngine // // The FilterEngine consists, most importantly, of : // // a list of possible properties (each tagged whether it has been 'enabled' as a filter) // a map of filterName => propertySet // queue for compound rule expression (i.e. "(filter1 AND filter2) OR !filter3" ) // // Each propertySet is a list of properties enabled for this particular filter object // // Implemented as a map of propertyNames to propertyFilterValue // ( "property1" => pfv1 // "property2" => pfv2 // "property4" => pfv4 // etc. ) // // Any properties that are 'possible', via FilterEngine::addProperty(), but not enabled // via FilterEngine::setProperty() (in our example, say "property3"), evaluate to true // for any query. Meaning that if a property is not set on this filter, we don't care // about it here, so it passes though OK. // // A propertyFilterValue contains a value and comparison type // // ( pfv1: Value = 50, Type = GREATER_THAN_EQUAL // pfv2: Value = "foo", Type = STARTS_WITH // pfv4: Value = "bar", Type = CONTAINS // etc. ) // // This allows for more complex queries (than simple isEqual?) against a variety of data types. // // *************************************************************************** #ifndef BAMTOOLS_FILTER_PROPERTIES_H #define BAMTOOLS_FILTER_PROPERTIES_H #include "utils/utils_global.h" #include "utils/bamtools_utilities.h" #include "utils/bamtools_variant.h" #include <iostream> #include <map> #include <string> namespace BamTools { // ---------------------------------------------------------- // PropertyFilterValue struct UTILS_EXPORT PropertyFilterValue { // define valid ValueCompareTypes enum ValueCompareType { CONTAINS = 0 , ENDS_WITH , EXACT , GREATER_THAN , GREATER_THAN_EQUAL , LESS_THAN , LESS_THAN_EQUAL , NOT , STARTS_WITH }; // ctor PropertyFilterValue(const Variant& value = Variant(), const ValueCompareType& type = PropertyFilterValue::EXACT) : Value(value) , Type(type) { } // filter check methods template<typename T> bool check(const T& query) const; bool check(const std::string& query) const; // data members Variant Value; ValueCompareType Type; }; // checks a query against a filter (value, compare type) template<typename T> bool PropertyFilterValue::check(const T& query) const { // ensure filter value & query are same type if ( !Value.is_type<T>() ) { std::cerr << "Cannot compare different types!" << std::endl; return false; } // string matching if ( Value.is_type<std::string>() ) { std::cerr << "Cannot compare different types - query is a string!" << std::endl; return false; } // numeric matching based on our filter type switch ( Type ) { case ( PropertyFilterValue::EXACT) : return ( query == Value.get<T>() ); case ( PropertyFilterValue::GREATER_THAN) : return ( query > Value.get<T>() ); case ( PropertyFilterValue::GREATER_THAN_EQUAL) : return ( query >= Value.get<T>() ); case ( PropertyFilterValue::LESS_THAN) : return ( query < Value.get<T>() ); case ( PropertyFilterValue::LESS_THAN_EQUAL) : return ( query <= Value.get<T>() ); case ( PropertyFilterValue::NOT) : return ( query != Value.get<T>() ); default : BAMTOOLS_ASSERT_UNREACHABLE; } return false; } // checks a string query against filter (value, compare type) inline bool PropertyFilterValue::check(const std::string& query) const { // ensure filter value & query are same type if ( !Value.is_type<std::string>() ) { std::cerr << "Cannot compare different types!" << std::endl; return false; } // localize string version of our filter value const std::string& valueString = Value.get<std::string>(); // string matching based on our filter type switch ( Type ) { case ( PropertyFilterValue::CONTAINS) : return ( query.find(valueString) != std::string::npos ); case ( PropertyFilterValue::ENDS_WITH) : return ( query.find(valueString) == (query.length() - valueString.length()) ); case ( PropertyFilterValue::EXACT) : return ( query == valueString ); case ( PropertyFilterValue::GREATER_THAN) : return ( query > valueString ); case ( PropertyFilterValue::GREATER_THAN_EQUAL) : return ( query >= valueString ); case ( PropertyFilterValue::LESS_THAN) : return ( query < valueString ); case ( PropertyFilterValue::LESS_THAN_EQUAL) : return ( query <= valueString ); case ( PropertyFilterValue::NOT) : return ( query != valueString ); case ( PropertyFilterValue::STARTS_WITH) : return ( query.find(valueString) == 0 ); default : BAMTOOLS_ASSERT_UNREACHABLE; } return false; } inline const std::string toString(const PropertyFilterValue::ValueCompareType& type) { switch ( type ) { case ( PropertyFilterValue::CONTAINS ) : return std::string( "CONTAINS"); case ( PropertyFilterValue::ENDS_WITH ) : return std::string( "ENDS_WITH"); case ( PropertyFilterValue::EXACT ) : return std::string( "EXACT"); case ( PropertyFilterValue::GREATER_THAN ) : return std::string( "GREATER_THAN"); case ( PropertyFilterValue::GREATER_THAN_EQUAL ) : return std::string( "GREATER_THAN_EQUAL"); case ( PropertyFilterValue::LESS_THAN ) : return std::string( "LESS_THAN"); case ( PropertyFilterValue::LESS_THAN_EQUAL ) : return std::string( "LESS_THAN_EQUAL"); case ( PropertyFilterValue::NOT ) : return std::string( "NOT"); case ( PropertyFilterValue::STARTS_WITH ) : return std::string( "STARTS_WITH"); default : BAMTOOLS_ASSERT_UNREACHABLE; } return std::string(); } // property name => property filter value // ('name' => ('SSR', STARTS_WITH), 'mapQuality' => (50, GREATER_THAN_EQUAL), etc...) typedef std::map<std::string, PropertyFilterValue> PropertyMap; // ---------------------------------------------------------- // PropertyFilter struct UTILS_EXPORT PropertyFilter { // data members PropertyMap Properties; }; // filter name => properties // ('filter1' => properties1, 'filter2' => properties2, etc...) typedef std::map<std::string, PropertyFilter> FilterMap; // ---------------------------------------------------------- // Property // used to store properties known to engine & keep track of enabled state struct UTILS_EXPORT Property { std::string Name; bool IsEnabled; Property(const std::string& name, bool isEnabled = false) : Name(name) , IsEnabled(isEnabled) { } }; inline bool operator< (const Property& lhs, const Property& rhs) { return lhs.Name < rhs.Name; } inline bool operator== (const Property& lhs, const Property& rhs) { return lhs.Name == rhs.Name; } } // namespace BamTools #endif // BAMTOOLS_FILTER_PROPERTIES_H
[ "ryan.layer@gmail.com" ]
ryan.layer@gmail.com
a0c8f5692b11708d19d936c13d10adede3901101
da5bb5e44b56f9c22e3bedb145aaff6a62cfa7b1
/Sphere/Sphere4/src/ofApp.cpp
4a55c3d3a7600e686360f6ad61f74c9faa731241
[]
no_license
r21nomi/of-artwork
0abc1e18aa3c9aafa368d0180e21917c431fbd2d
6aef14cd40cc9e6a171caea3aec4296a3d0f4e49
refs/heads/master
2021-01-24T08:17:41.132581
2017-03-02T00:39:59
2017-03-02T00:39:59
68,909,172
9
0
null
null
null
null
UTF-8
C++
false
false
2,383
cpp
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ ofBackground(0); float lineStep = 3; float radius = (ofGetHeight() / 2) * 0.8; for(int s = 0; s <= 180; s += lineStep){ ofColor color = ofColor(0, ofRandom(255), ofRandom(255)); float radianS = s == 0 ? ofDegToRad(3) : ofDegToRad(s); float z = radius * cos(radianS); float r = radius * sin(radianS); ofVec3f position = ofVec3f(ofGetWidth() / 2, ofGetHeight() / 2, z); float radius = 360; float bold = ofRandom(1, 10); float angle = ofRandom(0, 240); float speedOffSet = ofRandom(3, 6); float rotateOffSet = 0.05; curveItems.push_back(new CurveItem(position, color, r, bold, angle, speedOffSet, rotateOffSet)); } } //-------------------------------------------------------------- void ofApp::update(){ for (CurveItem* item : curveItems) { item->update(); } } //-------------------------------------------------------------- void ofApp::draw(){ for (CurveItem* item : curveItems) { item->draw(); } } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
[ "ryotakosu@gmail.com" ]
ryotakosu@gmail.com
e2e6d2bf28035d14df0c1cbd4138238b107f64e2
9a3b9d80afd88e1fa9a24303877d6e130ce22702
/src/Providers/UNIXProviders/UserContact/UNIX_UserContact.cpp
c45057ecf6ffb104626795b347bd3f81f65f6c81
[ "MIT" ]
permissive
brunolauze/openpegasus-providers
3244b76d075bc66a77e4ed135893437a66dd769f
f24c56acab2c4c210a8d165bb499cd1b3a12f222
refs/heads/master
2020-04-17T04:27:14.970917
2015-01-04T22:08:09
2015-01-04T22:08:09
19,707,296
0
0
null
null
null
null
UTF-8
C++
false
false
3,226
cpp
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // License. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // ////////////////////////////////////////////////////////////////////////// // //%///////////////////////////////////////////////////////////////////////// #include "UNIX_UserContact.h" #if defined(PEGASUS_OS_HPUX) # include "UNIX_UserContact_HPUX.hxx" # include "UNIX_UserContact_HPUX.hpp" #elif defined(PEGASUS_OS_LINUX) # include "UNIX_UserContact_LINUX.hxx" # include "UNIX_UserContact_LINUX.hpp" #elif defined(PEGASUS_OS_DARWIN) # include "UNIX_UserContact_DARWIN.hxx" # include "UNIX_UserContact_DARWIN.hpp" #elif defined(PEGASUS_OS_AIX) # include "UNIX_UserContact_AIX.hxx" # include "UNIX_UserContact_AIX.hpp" #elif defined(PEGASUS_OS_FREEBSD) # include "UNIX_UserContact_FREEBSD.hxx" # include "UNIX_UserContact_FREEBSD.hpp" #elif defined(PEGASUS_OS_SOLARIS) # include "UNIX_UserContact_SOLARIS.hxx" # include "UNIX_UserContact_SOLARIS.hpp" #elif defined(PEGASUS_OS_ZOS) # include "UNIX_UserContact_ZOS.hxx" # include "UNIX_UserContact_ZOS.hpp" #elif defined(PEGASUS_OS_VMS) # include "UNIX_UserContact_VMS.hxx" # include "UNIX_UserContact_VMS.hpp" #elif defined(PEGASUS_OS_TRU64) # include "UNIX_UserContact_TRU64.hxx" # include "UNIX_UserContact_TRU64.hpp" #else # include "UNIX_UserContact_STUB.hxx" # include "UNIX_UserContact_STUB.hpp" #endif Boolean UNIX_UserContact::validateKey(CIMKeyBinding &kb) const { /* Keys */ //CreationClassName //Name CIMName name = kb.getName(); if (name.equal(PROPERTY_CREATION_CLASS_NAME) || name.equal(PROPERTY_NAME) ) return true; return false; } void UNIX_UserContact::setScope(CIMName scope) { currentScope = CIMName(scope.getString()); } void UNIX_UserContact::setCIMOMHandle(CIMOMHandle &ch) { _cimomHandle = ch; }
[ "brunolauze@msn.com" ]
brunolauze@msn.com
173d9798f8878435753ab1bdd0eb1b24baf97193
77eabcca6f181af0a28a631216463b113bf1ba43
/src/dep/lua/lua_tinker.cpp
ba405d3709d7d09a549d9b2a78b04b2606ced332
[ "MIT" ]
permissive
DexianZhao/PhantomEngineV2
6d636cee432ca021c01ee4a549e1e3857f2ca3d9
cc3bf02ca1d442713d471ca8835ca026bb32e841
refs/heads/main
2023-08-22T17:09:57.261023
2021-10-30T07:49:09
2021-10-30T07:49:09
422,811,761
1
0
null
null
null
null
UTF-8
C++
false
false
18,210
cpp
// lua_tinker.cpp // // LuaTinker - Simple and light C++ wrapper for Lua. // // Copyright (c) 2005-2007 Kwon-il Lee (zupet@hitel.net) // // please check Licence.txt file for licence and legal issues. #include <iostream> #include "../include/PhantomBase.h" extern const char* GetCurrentLuaFile(); extern "C" { #include "lua.h" #include "lualib.h" #include "lauxlib.h" }; #include "lua_tinker.h" //class temp //{ //public: // int get(){return 0;} // void set(int& n){} //}; // template<typename T, typename V> // struct p_var : lua_tinker::var_base // { // typedef V (T::*gfunc)(); // typedef void (T::*sfunc)(V& v); // gfunc _gfunc; // sfunc _sfunc; // p_var(gfunc gf, sfunc sf) : _gfunc(gf),_sfunc(sf) {} // void get(lua_State *L) { lua_tinker::push<V>(L, (lua_tinker::read<T*>(L,1)->*_gfunc)()); }//push<typename if_<is_obj<V>::value,V,V>::type>(L, (read<T*>(L,1)->*_gfunc)()); } // void set(lua_State *L) { (lua_tinker::read<T*>(L,1)->*_sfunc)(lua_tinker::read<V&>(L, 3)); } // }; // template<typename T, typename BASE, typename VAR> // void class_p(lua_State* L, const char* name, VAR (BASE::*gfunc)(), void (BASE::*sfunc)(VAR& v)) // { // lua_tinker::push_meta(L, lua_tinker::class_name<T>::name()); // if(lua_istable(L, -1)) // { // lua_pushstring(L, name); // new(lua_newuserdata(L,sizeof(p_var<BASE,VAR>))) p_var<BASE,VAR>(gfunc, sfunc); // lua_rawset(L, -3); // } // lua_pop(L, 1); // } // //void a(){ // class_p<temp>(0, "rgba", &temp::get, &temp::set); //} /*---------------------------------------------------------------------------*/ /* init */ /*---------------------------------------------------------------------------*/ void lua_tinker::init(lua_State *L) { init_s64(L); init_u64(L); } /*---------------------------------------------------------------------------*/ /* __s64 */ /*---------------------------------------------------------------------------*/ static int tostring_s64(lua_State *L) { char temp[64]; sprintf(temp, "%I64d", *(long long*)lua_topointer(L, 1)); lua_pushstring(L, temp); return 1; } /*---------------------------------------------------------------------------*/ static int eq_s64(lua_State *L) { lua_pushboolean(L, memcmp(lua_topointer(L, 1), lua_topointer(L, 2), sizeof(long long)) == 0); return 1; } /*---------------------------------------------------------------------------*/ static int lt_s64(lua_State *L) { lua_pushboolean(L, memcmp(lua_topointer(L, 1), lua_topointer(L, 2), sizeof(long long)) < 0); return 1; } /*---------------------------------------------------------------------------*/ static int le_s64(lua_State *L) { lua_pushboolean(L, memcmp(lua_topointer(L, 1), lua_topointer(L, 2), sizeof(long long)) <= 0); return 1; } /*---------------------------------------------------------------------------*/ void lua_tinker::init_s64(lua_State *L) { const char* name = "__s64"; lua_pushstring(L, name); lua_newtable(L); lua_pushstring(L, "__name"); lua_pushstring(L, name); lua_rawset(L, -3); lua_pushstring(L, "__tostring"); lua_pushcclosure(L, tostring_s64, 0); lua_rawset(L, -3); lua_pushstring(L, "__eq"); lua_pushcclosure(L, eq_s64, 0); lua_rawset(L, -3); lua_pushstring(L, "__lt"); lua_pushcclosure(L, lt_s64, 0); lua_rawset(L, -3); lua_pushstring(L, "__le"); lua_pushcclosure(L, le_s64, 0); lua_rawset(L, -3); lua_settable(L, LUA_GLOBALSINDEX); } /*---------------------------------------------------------------------------*/ /* __u64 */ /*---------------------------------------------------------------------------*/ static int tostring_u64(lua_State *L) { char temp[64]; sprintf(temp, "%I64u", *(unsigned long long*)lua_topointer(L, 1)); lua_pushstring(L, temp); return 1; } /*---------------------------------------------------------------------------*/ static int eq_u64(lua_State *L) { lua_pushboolean(L, memcmp(lua_topointer(L, 1), lua_topointer(L, 2), sizeof(unsigned long long)) == 0); return 1; } /*---------------------------------------------------------------------------*/ static int lt_u64(lua_State *L) { lua_pushboolean(L, memcmp(lua_topointer(L, 1), lua_topointer(L, 2), sizeof(unsigned long long)) < 0); return 1; } /*---------------------------------------------------------------------------*/ static int le_u64(lua_State *L) { lua_pushboolean(L, memcmp(lua_topointer(L, 1), lua_topointer(L, 2), sizeof(unsigned long long)) <= 0); return 1; } /*---------------------------------------------------------------------------*/ void lua_tinker::init_u64(lua_State *L) { const char* name = "__u64"; lua_pushstring(L, name); lua_newtable(L); lua_pushstring(L, "__name"); lua_pushstring(L, name); lua_rawset(L, -3); lua_pushstring(L, "__tostring"); lua_pushcclosure(L, tostring_u64, 0); lua_rawset(L, -3); lua_pushstring(L, "__eq"); lua_pushcclosure(L, eq_u64, 0); lua_rawset(L, -3); lua_pushstring(L, "__lt"); lua_pushcclosure(L, lt_u64, 0); lua_rawset(L, -3); lua_pushstring(L, "__le"); lua_pushcclosure(L, le_u64, 0); lua_rawset(L, -3); lua_settable(L, LUA_GLOBALSINDEX); } /*---------------------------------------------------------------------------*/ /* excution */ /*---------------------------------------------------------------------------*/ void lua_tinker::dofile(lua_State *L, const char *filename) { lua_pushcclosure(L, on_error, 0); int errfunc = lua_gettop(L); if(luaL_loadfile(L, filename) == 0) { lua_pcall(L, 0, 1, errfunc); } else { print_error(L, "%s", lua_tostring(L, -1)); } lua_remove(L, errfunc); lua_pop(L, 1); } /*---------------------------------------------------------------------------*/ void lua_tinker::dostring(lua_State *L, const char* buff) { lua_tinker::dobuffer(L, buff, strlen(buff)); } /*---------------------------------------------------------------------------*/ void lua_tinker::dobuffer(lua_State *L, const char* buff, size_t len) { lua_pushcclosure(L, on_error, 0); int errfunc = lua_gettop(L); if(luaL_loadbuffer(L, buff, len, "lua_tinker::dobuffer()") == 0) { lua_pcall(L, 0, 1, errfunc); } else { print_error(L, "%s", lua_tostring(L, -1)); } lua_remove(L, errfunc); lua_pop(L, 1); } /*---------------------------------------------------------------------------*/ /* debug helpers */ /*---------------------------------------------------------------------------*/ static void call_stack(lua_State* L, int n) { lua_Debug ar; if(lua_getstack(L, n, &ar) == 1) { lua_getinfo(L, "nSlu", &ar); const char* indent; if(n == 0) { indent = "->\t"; lua_tinker::print_error(L, "\t<call stack>"); } else { indent = "\t"; } if(ar.name) lua_tinker::print_error(L, "%s%s() : line %d [%s : line %d]", indent, ar.name, ar.currentline, ar.source, ar.linedefined); else lua_tinker::print_error(L, "%sunknown : line %d [%s : line %d]", indent, ar.currentline, ar.source, ar.linedefined); call_stack(L, n+1); } } /*---------------------------------------------------------------------------*/ int lua_tinker::on_error(lua_State *L) { print_error(L, "%s", lua_tostring(L, -1)); call_stack(L, 0); return 0; } /*---------------------------------------------------------------------------*/ void lua_tinker::print_error(lua_State *L, const char* fmt, ...) { char text[10240]; va_list args; va_start(args, fmt); vsnprintf(text, 10230, fmt, args); va_end(args); LogInfo("error->[%s] in file(%s)", text, GetCurrentLuaFile()); // // lua_pushstring(L, "_ALERT"); // lua_gettable(L, LUA_GLOBALSINDEX); // if(lua_isfunction(L, -1)) // { // lua_pushstring(L, text); // lua_call(L, 1, 0); // } // else // { // printf("%s\n", text); // lua_pop(L, 1); // } } /*---------------------------------------------------------------------------*/ void lua_tinker::enum_stack(lua_State *L) { int top = lua_gettop(L); print_error(L, "Type:%d", top); for(int i=1; i<=lua_gettop(L); ++i) { switch(lua_type(L, i)) { case LUA_TNIL: print_error(L, "\t%s", lua_typename(L, lua_type(L, i))); break; case LUA_TBOOLEAN: print_error(L, "\t%s %s", lua_typename(L, lua_type(L, i)), lua_toboolean(L, i)?"true":"false"); break; case LUA_TLIGHTUSERDATA: print_error(L, "\t%s 0x%08p", lua_typename(L, lua_type(L, i)), lua_topointer(L, i)); break; case LUA_TNUMBER: print_error(L, "\t%s %f", lua_typename(L, lua_type(L, i)), lua_tonumber(L, i)); break; case LUA_TSTRING: print_error(L, "\t%s %s", lua_typename(L, lua_type(L, i)), lua_tostring(L, i)); break; case LUA_TTABLE: print_error(L, "\t%s 0x%08p", lua_typename(L, lua_type(L, i)), lua_topointer(L, i)); break; case LUA_TFUNCTION: print_error(L, "\t%s() 0x%08p", lua_typename(L, lua_type(L, i)), lua_topointer(L, i)); break; case LUA_TUSERDATA: print_error(L, "\t%s 0x%08p", lua_typename(L, lua_type(L, i)), lua_topointer(L, i)); break; case LUA_TTHREAD: print_error(L, "\t%s", lua_typename(L, lua_type(L, i))); break; } } } /*---------------------------------------------------------------------------*/ /* read */ /*---------------------------------------------------------------------------*/ template<> char* lua_tinker::read(lua_State *L, int index) { return (char*)lua_tostring(L, index); } template<> const char* lua_tinker::read(lua_State *L, int index) { return (const char*)lua_tostring(L, index); } template<> char lua_tinker::read(lua_State *L, int index) { return (char)lua_tonumber(L, index); } template<> unsigned char lua_tinker::read(lua_State *L, int index) { return (unsigned char)lua_tonumber(L, index); } template<> short lua_tinker::read(lua_State *L, int index) { return (short)lua_tonumber(L, index); } template<> unsigned short lua_tinker::read(lua_State *L, int index) { return (unsigned short)lua_tonumber(L, index); } template<> long lua_tinker::read(lua_State *L, int index) { return (long)lua_tonumber(L, index); } template<> unsigned long lua_tinker::read(lua_State *L, int index) { return (unsigned long)lua_tonumber(L, index); } template<> int lua_tinker::read(lua_State *L, int index) { return (int)lua_tonumber(L, index); } template<> unsigned int lua_tinker::read(lua_State *L, int index) { return (unsigned int)lua_tonumber(L, index); } template<> float lua_tinker::read(lua_State *L, int index) { return (float)lua_tonumber(L, index); } template<> double lua_tinker::read(lua_State *L, int index) { return (double)lua_tonumber(L, index); } template<> bool lua_tinker::read(lua_State *L, int index) { if(lua_isboolean(L, index)) return lua_toboolean(L, index) != 0; else return lua_tonumber(L, index) != 0; } template<> void lua_tinker::read(lua_State *L, int index) { return; } template<> long long lua_tinker::read(lua_State *L, int index) { if(lua_isnumber(L,index)) return (long long)lua_tonumber(L, index); else return *(long long*)lua_touserdata(L, index); } template<> unsigned long long lua_tinker::read(lua_State *L, int index) { if(lua_isnumber(L,index)) return (unsigned long long)lua_tonumber(L, index); else return *(unsigned long long*)lua_touserdata(L, index); } template<> lua_tinker::table lua_tinker::read(lua_State *L, int index) { return table(L, index); } /*---------------------------------------------------------------------------*/ /* push */ /*---------------------------------------------------------------------------*/ template<> void lua_tinker::push(lua_State *L, char ret) { lua_pushnumber(L, ret); } template<> void lua_tinker::push(lua_State *L, unsigned char ret) { lua_pushnumber(L, ret); } template<> void lua_tinker::push(lua_State *L, short ret) { lua_pushnumber(L, ret); } template<> void lua_tinker::push(lua_State *L, unsigned short ret) { lua_pushnumber(L, ret); } template<> void lua_tinker::push(lua_State *L, long ret) { lua_pushnumber(L, ret); } template<> void lua_tinker::push(lua_State *L, unsigned long ret) { lua_pushnumber(L, ret); } template<> void lua_tinker::push(lua_State *L, int ret) { lua_pushnumber(L, ret); } template<> void lua_tinker::push(lua_State *L, unsigned int ret) { lua_pushnumber(L, ret); } template<> void lua_tinker::push(lua_State *L, float ret) { lua_pushnumber(L, ret); } template<> void lua_tinker::push(lua_State *L, double ret) { lua_pushnumber(L, ret); } template<> void lua_tinker::push(lua_State *L, char* ret) { lua_pushstring(L, ret); } template<> void lua_tinker::push(lua_State *L, const char* ret) { lua_pushstring(L, ret); } template<> void lua_tinker::push(lua_State *L, bool ret) { lua_pushboolean(L, ret); } template<> void lua_tinker::push(lua_State *L, lua_value* ret) { if(ret) ret->to_lua(L); else lua_pushnil(L); } template<> void lua_tinker::push(lua_State *L, long long ret) { *(long long*)lua_newuserdata(L, sizeof(long long)) = ret; lua_pushstring(L, "__s64"); lua_gettable(L, LUA_GLOBALSINDEX); lua_setmetatable(L, -2); } template<> void lua_tinker::push(lua_State *L, unsigned long long ret) { *(unsigned long long*)lua_newuserdata(L, sizeof(unsigned long long)) = ret; lua_pushstring(L, "__u64"); lua_gettable(L, LUA_GLOBALSINDEX); lua_setmetatable(L, -2); } template<> void lua_tinker::push(lua_State *L, lua_tinker::table ret) { lua_pushvalue(L, ret.m_obj->m_index); } /*---------------------------------------------------------------------------*/ /* pop */ /*---------------------------------------------------------------------------*/ template<> void lua_tinker::pop(lua_State *L) { lua_pop(L, 1); } template<> lua_tinker::table lua_tinker::pop(lua_State *L) { return table(L, lua_gettop(L)); } /*---------------------------------------------------------------------------*/ /* Tinker Class Helper */ /*---------------------------------------------------------------------------*/ static void invoke_parent(lua_State *L) { lua_pushstring(L, "__parent"); lua_rawget(L, -2); if(lua_istable(L,-1)) { lua_pushvalue(L,2); lua_rawget(L, -2); if(!lua_isnil(L,-1)) { lua_remove(L,-2); } else { lua_remove(L, -1); invoke_parent(L); lua_remove(L,-2); } } } /*---------------------------------------------------------------------------*/ int lua_tinker::meta_get(lua_State *L) { lua_getmetatable(L,1); lua_pushvalue(L,2); lua_rawget(L,-2); if(lua_isuserdata(L,-1)) { user2type<var_base*>::invoke(L,-1)->get(L); lua_remove(L, -2); } else if(lua_isnil(L,-1)) { lua_remove(L,-1); invoke_parent(L); if(lua_isnil(L,-1)) { lua_pushfstring(L, "can't find '%s' class variable. (forgot registering class variable ?)", lua_tostring(L, 2)); lua_error(L); } } lua_remove(L,-2); return 1; } /*---------------------------------------------------------------------------*/ int lua_tinker::meta_set(lua_State *L) { lua_getmetatable(L,1); lua_pushvalue(L,2); lua_rawget(L,-2); if(lua_isuserdata(L,-1)) { user2type<var_base*>::invoke(L,-1)->set(L); } else if(lua_isnil(L, -1)) { lua_pushvalue(L,2); lua_pushvalue(L,3); lua_rawset(L, -4); } lua_settop(L, 3); return 0; } /*---------------------------------------------------------------------------*/ void lua_tinker::push_meta(lua_State *L, const char* name) { lua_pushstring(L, name); lua_gettable(L, LUA_GLOBALSINDEX); } /*---------------------------------------------------------------------------*/ /* table object on stack */ /*---------------------------------------------------------------------------*/ lua_tinker::table_obj::table_obj(lua_State* L, int index) :m_L(L) ,m_index(index) ,m_ref(0) { if(lua_isnil(m_L, m_index)) { m_pointer = NULL; lua_remove(m_L, m_index); } else { m_pointer = lua_topointer(m_L, m_index); } } lua_tinker::table_obj::~table_obj() { if(validate()) { lua_remove(m_L, m_index); } } void lua_tinker::table_obj::inc_ref() { ++m_ref; } void lua_tinker::table_obj::dec_ref() { if(--m_ref == 0) delete this; } bool lua_tinker::table_obj::validate() { if(m_pointer != NULL) { if(m_pointer == lua_topointer(m_L, m_index)) { return true; } else { int top = lua_gettop(m_L); for(int i=1; i<=top; ++i) { if(m_pointer == lua_topointer(m_L, i)) { m_index = i; return true; } } m_pointer = NULL; return false; } } else { return false; } } /*---------------------------------------------------------------------------*/ /* Table Object Holder */ /*---------------------------------------------------------------------------*/ lua_tinker::table::table(lua_State* L) { lua_newtable(L); m_obj = new table_obj(L, lua_gettop(L)); m_obj->inc_ref(); } lua_tinker::table::table(lua_State* L, const char* name) { lua_pushstring(L, name); lua_gettable(L, LUA_GLOBALSINDEX); if(lua_istable(L, -1) == 0) { lua_pop(L, 1); lua_newtable(L); lua_pushstring(L, name); lua_pushvalue(L, -2); lua_settable(L, LUA_GLOBALSINDEX); } m_obj = new table_obj(L, lua_gettop(L)); } lua_tinker::table::table(lua_State* L, int index) { if(index < 0) { index = lua_gettop(L) + index + 1; } m_obj = new table_obj(L, index); m_obj->inc_ref(); } lua_tinker::table::table(const table& input) { m_obj = input.m_obj; m_obj->inc_ref(); } lua_tinker::table::~table() { m_obj->dec_ref(); } BOOL lua_tinker::g_luaTnikerCallError = false; /*---------------------------------------------------------------------------*/
[ "yuzhou_995@hotmail.com" ]
yuzhou_995@hotmail.com
d0e56d0c846e356d8538539712b42cdb2e2a220f
40fcdd9f7a84ae90559769395553b03b902d18f5
/Conjure/src/InputCore.cpp
3e7a6adeaedfdb1be140b6cc5e040dd78510206d
[]
no_license
BrandonLing/Legacy-C-Projects
b78196d54ea37447c4c7ce533e262cb3bc6319ea
b646bd7f34ba7668dd9c7c73f34b749617893cce
refs/heads/master
2021-04-30T18:08:35.303278
2017-01-29T02:51:49
2017-01-29T02:51:49
80,325,502
0
0
null
null
null
null
UTF-8
C++
false
false
1,366
cpp
#include "InputCore.h" void InputCore::init() { bool success = SDL_Init(SDL_INIT_EVENTS); if (success) printf("Error in Input Core: Cannot initialize events\n"); } void InputCore::quit() { SDL_Quit(); } void InputCore::recv_inputs() { SDL_Event event; while (SDL_PollEvent(&event)) { int keyCode = event.key.keysym.sym; int type = event.type; switch (type) { case SDL_KEYDOWN: //fallthrough case SDL_KEYUP: EventQueue.postInputEvent(keyCode, type); break; case SDL_MOUSEMOTION: EventQueue.postMouseEvent(1, event.motion.xrel, event.motion.yrel); //std::cout << event.motion.xrel << "," << event.motion.yrel << "\n"; break; case SDL_MOUSEBUTTONDOWN: if (event.button.button == SDL_BUTTON_LEFT) EventQueue.postMouseEvent(2, event.button.x, event.button.y); else if (event.button.button == SDL_BUTTON_RIGHT) EventQueue.postMouseEvent(3, event.button.x, event.button.y); //std::cout << "Mouse at " << event.button.x << "," << event.button.y << "\n"; break; case SDL_QUIT: EventQueue.postQuitEvent(); break; } } }
[ "meta.pfs@gmail.com" ]
meta.pfs@gmail.com
d60965c318f8751bbab88061d805c7bd2da3e5f9
ef17b8a68d3d85e9b3f12ca7795a80d28ede75e3
/The Witcher/Alien Engine/ModuleWindow.h
28581feb06cc032fde67c3b2f71a2eb73a12540d
[ "MIT" ]
permissive
OverPowered-Team/TheWitcher
de3e3d891a5d0f27c1d914e47510fbefaa41fc73
09888ccde82c9dee41043bac225a4dad44aa37d0
refs/heads/dev
2023-05-04T16:03:41.857115
2020-06-15T08:49:56
2020-06-15T08:49:56
240,340,565
13
4
MIT
2020-06-15T08:51:11
2020-02-13T19:11:57
C++
UTF-8
C++
false
false
1,307
h
#ifndef __ModuleWindow_H__ #define __ModuleWindow_H__ #include "Module.h" #include "SDL/include/SDL.h" #include "Color.h" class Application; class ModuleWindow : public Module { public: ModuleWindow(bool start_enabled = true); // Destructor virtual ~ModuleWindow(); bool Init(); bool CleanUp(); void LoadConfig(JSONfilepack*& config); void SaveConfig(JSONfilepack*& config); void SetTitle(const char* title); void SetWindowName(const char* name); void SetOrganitzationName(const char* name); void SetBorderless(bool borderless); void SetFullScreen(bool fullscreen); void SetFullDesktop(bool fulldesktop); void SetResizable(bool resizable); void IncreaseBar(); bool CreateCoreWindow(); public: //The window we'll be rendering to SDL_Window* window = nullptr; //The surface contained by the window SDL_Surface* screen_surface = nullptr; int width = 0; int height = 0; float brightness = 0.0f; bool fullscreen = false; bool full_desktop = false; bool borderless = false; bool resizable = false; bool start_maximized = false; int style = 0; char* window_name = nullptr; char* organitzation_name = nullptr; int segment_width = 0; private: SDL_Renderer* renderer = nullptr; SDL_Texture* texture = nullptr; int current_division = 0; }; #endif // __ModuleWindow_H__
[ "36154523+OriolCS2@users.noreply.github.com" ]
36154523+OriolCS2@users.noreply.github.com
bc0d4c481dbb4ac7a47f68d3ad230c3508571622
a117f6d09df0d16f8bc230ecf9678e84484506c8
/code/cpp_console_debug/src/cpu_test.cpp
93d6e517d5e5c2aa4351b727a811654dc0f6eed3
[]
no_license
JimmyFromSYSU/NES
556d76f1722d1d547234db47be62a6d4fef2512c
dcf318e1b5837d52fb63e622d22d57d14ce88560
refs/heads/main
2023-01-12T11:41:48.167165
2020-11-20T16:46:03
2020-11-20T16:46:03
314,155,901
1
0
null
null
null
null
UTF-8
C++
false
false
3,503
cpp
#include "tool.h" #include "cpu.h" #include "joystick.h" joystick j; ppu p; cpu c(&p,&j); int run_cnt=0; int cnt = 0; //int pos = 0xC070; int pos = -1; bool one(bool f = true){ cnt++; if(f)printf("\n || step %d ||\n",cnt); if(c.oneStep(f)==false){ printf(YELLOW"Step %d error"NONE"\n",cnt); c.printM(); c.printI(); c.printR(); return false; } return true; } void print_memory(){ char buffer[64]; char cmd; printf("1 cpu memory\n"); printf("2 ppu OAM\n"); printf("3 ppu Palette\n"); printf("4 ppu VRAM\n"); printf("5 ppu VROM\n"); printf("6 ppu screen\n"); printf("7 save screen(coe)\n"); printf("What you want to print? "); cmd = getch(); puts(""); if(cmd=='1'){ printf("show memory at (pos offset): "); scanf("%s",buffer); int n = hex2int(buffer); scanf("%s",buffer); int a = hex2int(buffer); if(a<=16){ for(int i = n;i< n+a;i++){ c.printM(i); } } else{ printf(" 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n"); for(int i = n - n%16;i < n+a;i+=16){ c.printM16(i); } } } //printf("2 ppu VROM\n"); //printf("3 ppu Palette\n"); //printf("4 ppu VRAM\n"); //printf("5 ppu OAM\n"); else if(cmd=='2'){p.printOAM();} else if(cmd=='3'){p.printPalette();} else if(cmd=='4'){p.printVRAM();} else if(cmd=='5'){p.printVROM();} else if(cmd=='6'){ printf("Which name table: "); cmd = getch(); puts(""); if(cmd<'0' || cmd > '3') return; int t = cmd - '0'; p.showNameTable(t); printf("ok\n"); p.printBuffer(); } else if(cmd =='7') { p.saveImgCoe(); c.saveMem(); } } void set_memory(){ char buffer[64]; int a,d; printf("set memory (pos value(hex)): "); scanf("%s",buffer); if(buffer[0]=='-') return; a = hex2int(buffer); scanf("%s",buffer); d = hex2int(buffer); c.set_mem(a,d); } void set_joystick(){ printf("0 NO, 1 A, 2 B, 3 SELECT, 4 START, 5 UP, 6 DOWN, 7 LEFT, 8 RIGHT\n"); printf("Choice: "); char c = getch();puts(""); if(c>='0' && c<='8'){ int b = c-'0'; j.setButton((JOYSTICK_BUTTON)b,0); } } void run_silent(int t){ while(t>1){ assert(one(false)); t--; } if(t==1) assert(one()); } void run(){ printf("run: "); int t; scanf("%d",&t); run_silent(t); } void solve( ){ if(pos>=0x8000 && pos<=0xFFFF){ c.setPC(pos); printf("start from %X ... ",pos); } run_silent(run_cnt); while(1){ char t = getch(); int cmd; if(t=='\n')continue; if(t=='q')break; else if(t=='s'){c.printST();} // else if(t=='f'){} else if(t>='0' && t<='8'){ printf("joystick %c\n",t); j.setButton((JOYSTICK_BUTTON)(t-'0'),0); } else if(t=='m'){set_memory();} else if(t=='p'){print_memory();} else if(t=='i'){c.nmi();puts("Interruption occur!");} else if(t=='j'){set_joystick();} else if(t=='r'){run();} else if(t=='a'){ c.nmi();puts("Interruption occur!"); run_silent(100000); } else if(t=='t'){printf("run to: ");scanf("%d",&cmd);run_silent(cmd-cnt);} else if(t=='h'){ printf("q: quit\n"); printf("s: show statck\n"); printf("m: set mem\n"); printf("p: print mem\n"); printf("i: interrupt nmi\n"); } else{printf("\n");assert(one());} } } int dealOpts(int argc,char ** argv){ int c; while((c = getopt(argc, argv,"r:s:")) != -1) { switch(c) { case 'r': run_cnt = atoi(optarg); break; case 's': pos = hex2int(optarg); break; default: return false; break; } } return true; } int main(int argc, char ** argv) { if(! dealOpts(argc, argv)) return 0; solve(); return 0; }
[ "nanfangxiaozhi@gmail.com" ]
nanfangxiaozhi@gmail.com
1fe7e2bbe4997cfdaad6795549ef3eae0b57dc1c
1459d6b60e93b5176c854b5e0df38788983ea7af
/source/ClientApplication/ClientApplication/CpuUsageCalculator.h
11586f07aee7b43d4d454d01b88439ec1c67f8c9
[]
no_license
naseefcse/SystemMonitor
4f7d6b8d1579fde14a3d040a7ccbcda772738da5
b71640985700fae577017979e3ec84a46f2cb4b4
refs/heads/master
2021-01-10T07:00:25.600240
2015-12-24T10:35:42
2015-12-24T10:35:42
48,533,969
1
0
null
null
null
null
UTF-8
C++
false
false
919
h
#ifndef CPU_USAGE_CALCULATOR #define CPU_USAGE_CALCULATOR #pragma once #include "windows.h" #include <stdio.h> #include "tchar.h" #define WIDTH 7 typedef BOOL(__stdcall * pfnGetSystemTimes)(LPFILETIME lpIdleTime, LPFILETIME lpKernelTime, LPFILETIME lpUserTime); static pfnGetSystemTimes s_pfnGetSystemTimes = NULL; static HMODULE s_hKernel = NULL; //----------------------------------------------------- class CCpuUsageCalculator { public: CCpuUsageCalculator(); virtual ~CCpuUsageCalculator(); char getCPUUsage(); char calculateCPUUsage(); char m_fCPUUsage; void GetSystemTimesAddress() { if (s_hKernel == NULL) { s_hKernel = LoadLibrary(L"Kernel32.dll"); if (s_hKernel != NULL) { s_pfnGetSystemTimes = (pfnGetSystemTimes)GetProcAddress(s_hKernel, "GetSystemTimes"); if (s_pfnGetSystemTimes == NULL) { FreeLibrary(s_hKernel); s_hKernel = NULL; } } } } }; #endif
[ "naseef@ipvisionsoft.com" ]
naseef@ipvisionsoft.com
75ab5aca825939f438c442e9584011840e9c0ed6
03b5b626962b6c62fc3215154b44bbc663a44cf6
/src/instruction/LEAVE.cpp
27971d04db36a52bca5f6efaa4c1a9f7526bb5fe
[]
no_license
haochenprophet/iwant
8b1f9df8ee428148549253ce1c5d821ece0a4b4c
1c9bd95280216ee8cd7892a10a7355f03d77d340
refs/heads/master
2023-06-09T11:10:27.232304
2023-05-31T02:41:18
2023-05-31T02:41:18
67,756,957
17
5
null
2018-08-11T16:37:37
2016-09-09T02:08:46
C++
UTF-8
C++
false
false
175
cpp
#include "LEAVE.h" int CLEAVE::my_init(void *p) { this->name = "CLEAVE"; this->alias = "LEAVE"; return 0; } CLEAVE::CLEAVE() { this->my_init(); } CLEAVE::~CLEAVE() { }
[ "hao__chen@sina.com" ]
hao__chen@sina.com
ba6dbb59c07caecae2a58da2e3f29d0784aca725
3ccf610a536b70aea11a7ba44890028ed809e07e
/Blaze/taco-master/src/lower/mode_access.cpp
7aa533e40f9298eebfa948c501b9b7790c71d39e
[ "MIT" ]
permissive
kengwit/MachineLearning
843aa5a0de3bef75c20f60f409d0c2e8b85c33d0
5c16f71a41145aed87d4a642205fe7a8ee26b20e
refs/heads/master
2021-04-06T19:19:44.874109
2019-01-14T23:27:50
2019-01-14T23:27:50
125,287,985
1
1
null
2019-01-14T10:05:12
2018-03-14T23:47:54
Jupyter Notebook
UTF-8
C++
false
false
758
cpp
#include "lower/mode_access.h" namespace taco { ModeAccess::ModeAccess(Access access, int mode) : access(access), mode(mode){ } Access ModeAccess::getAccess() const { return access; } size_t ModeAccess::getMode() const { return mode; } bool operator==(const ModeAccess& a, const ModeAccess& b) { return a.getAccess() == b.getAccess() && a.getMode() == b.getMode(); } bool operator<(const ModeAccess& a, const ModeAccess& b) { if (a.getAccess() == b.getAccess()) { return a.getMode() < b.getMode(); } return a.getAccess() < b.getAccess(); } std::ostream &operator<<(std::ostream &os, const ModeAccess & modeAccess) { return os << modeAccess.getAccess().getTensorVar().getName() << "(" << modeAccess.getMode() << ")"; } }
[ "kengwit@gmail.com" ]
kengwit@gmail.com
b05e8de85d87bd6367a04bf4d1c55422848891ed
e9774bd2d0cd9aaad49eacd092ba97e95dbf9a5f
/problems/C - Nastya and Strange Generator.cpp
364adafb7720aff6ad3ffdc58af1213c67c5d5ff
[]
no_license
My-Competitive-Programming-Legacy/CodeForces
fb589c187706060d8a33eccf75597dad4dab904d
f9df0ffe76b1d37215f063e87920c0044fe226a4
refs/heads/master
2023-06-23T06:04:30.369027
2021-07-19T12:20:19
2021-07-19T12:20:19
387,414,460
0
0
null
null
null
null
UTF-8
C++
false
false
1,307
cpp
#include <iostream> #include <vector> #include <algorithm> #include <set> #include <map> #include <stack> #include <queue> #include <cmath> #include <time.h> typedef long long int ll; using namespace std; #define vi vector<int> const int Mod = 1000000007; void solve() { int n; cin >> n; vi p(n); vi idx(n); for (int i = 0; i < n; i++) { cin >> p[i]; p[i]--; idx[p[i]] = i; } int nxt = 0; int end = n; int nxtend = n; bool ok = true; int cnt = 1; while (ok && cnt < n) { nxtend = idx[nxt]; for (int i = idx[nxt]; i < end; i++) { nxt++; cnt++; if ((i < end - 1) && p[i + 1] - p[i] != 1) { ok = false; } if (i == end - 1) end = nxtend; } end = nxtend; } if (ok) cout << "Yes" << endl; else cout << "No" << endl; } int main() { #ifdef _DEBUG // place in cmake-build-debug folder freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); #endif ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int q; cin >> q; for (int i = 1; i <= q; i++) { // cout << "Case #" << i << ": "; solve(); } // solve(); return 0; }
[ "hamzahasssan835@gmail.com" ]
hamzahasssan835@gmail.com
0cb32a9622e66c66a7da564b3d101f6c6bd677f9
9d3e98383082c15778d1e80c6ea286aac3187d15
/BLE_Sensor/BLE_Password/BLE_Password.ino
3404a38761e5b97de6924685ac991bab1a1cf780
[]
no_license
Huzar01/BLESensor
34cea05cd68c1d6901c8c2175ebb3d1b75292301
6f972b70327fbf76a435b21f12f2149b2ab299ce
refs/heads/master
2020-04-25T21:31:24.006386
2019-02-28T19:16:21
2019-02-28T19:16:21
173,082,476
0
0
null
null
null
null
UTF-8
C++
false
false
6,165
ino
#include <SPI.h> #include <BLEPeripheral.h> #include <Servo.h> // defining the pins #define MOTOR_PIN 12 #define BUTTON_PIN 7 #define BLE_REQ 11 #define BLE_RDY 2 #define BLE_RST 10 // Defines Tirg and Echo pins of the Ultrasonic Sensor const int trigPin = 8; const int echoPin = 9; int currentState; int debounceState; // intial state of the button should be OFF int switchState = 0; int motorState = 0; long duration; int distance; int val; // Secert code variables char secret[] = "butters"; char infinite[] = "infinite"; long openTime = 0; Servo myServo; // Creates a servo object for controlling the servo motor // Lets the arduino know where the chip is BLEPeripheral blePeripheral = BLEPeripheral( BLE_REQ, BLE_RDY, BLE_RST); BLEService motorswitch = BLEService( "FF45" ); // BLE Written BLEService motorWrite = BLEService ("D270"); BLECharacteristic writeCharacteristic = BLECharacteristic("D271",BLEWrite, 20); // Adding BLE Characteristics BLECharCharacteristic switchCharacteristic = BLECharCharacteristic("FF69", BLERead | BLEWrite); BLECharCharacteristic stateCharacteristic = BLECharCharacteristic("D271", BLENotify); // Adding BLE Descriptors BLEDescriptor switchDescriptor = BLEDescriptor("2901", "Motor Switch"); BLEDescriptor stateDescriptor = BLEDescriptor("2901", "Motor State"); BLEDescriptor writeDescriptor = BLEDescriptor("2901", "Activate Sensor"); void setup() { Serial.begin(9600); pinMode(MOTOR_PIN, OUTPUT); pinMode(BUTTON_PIN, INPUT); pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output pinMode(echoPin, INPUT); // Sets the echoPin as an Input // Wise to set both names incase a device uses one or the other blePeripheral.setLocalName("Dope Sensor"); blePeripheral.setDeviceName("BLE Dope Sensor"); blePeripheral.setAdvertisedServiceUuid(motorWrite.uuid()); blePeripheral.addAttribute(motorWrite); blePeripheral.addAttribute(writeCharacteristic); blePeripheral.addAttribute(writeDescriptor); blePeripheral.addAttribute(motorswitch); blePeripheral.addAttribute(switchCharacteristic); blePeripheral.addAttribute(switchDescriptor); blePeripheral.addAttribute(stateCharacteristic); blePeripheral.addAttribute(stateDescriptor); // Adding event handler, will get called when BLE is written too. switchCharacteristic.setEventHandler(BLEWritten, switchCharacteristicWritten); writeCharacteristic.setEventHandler(BLEWritten, switchMotorWritten); //Begins BLE service blePeripheral.begin(); Serial.println("BLE Dope Sensor"); } void loop() { blePeripheral.poll(); currentState = digitalRead(BUTTON_PIN); delay(10); debounceState = digitalRead(BUTTON_PIN); if( currentState != switchState ) { if( currentState == debounceState ) { if (currentState == LOW) { // do nothing, button has just been released } else { Serial.println("Button event: PRESSED ON"); if ( motorState == 0 ) { switchCharacteristic.setValue(1); stateCharacteristic.setValue(1); digitalWrite(MOTOR_PIN, HIGH); // rotates the servo motor from 15 to 165 degrees myServo.attach(12); sensorRotate(); myServo.detach(); motorState = 1; } else { switchCharacteristic.setValue(0); stateCharacteristic.setValue(0); digitalWrite(MOTOR_PIN, LOW); motorState = 0; } } // Notifys the program the BUTTON STATE has been changed switchState = currentState; }}} void switchMotorWritten(BLECentral& central, BLECharacteristic& characteristic) { //BLE Function Serial.print(F("Motor Written Characteristic Event: ")); startMotor(characteristic.value(), characteristic.valueLength()); } void startMotor(const unsigned char* code, int codeLength) { boolean match = false; // Does the code match secret if (strlen(secret) == codeLength) { for (int i = 0; i < codeLength; i++) { if (secret[i] != code[i]) { match = false; break; } else { // Serial.println(code); match = true; } } } if (match) { // turn on motor Serial.println("Code matches, sensor is now active"); digitalWrite(MOTOR_PIN, HIGH); stateCharacteristic.setValue("Valid Code"); myServo.attach(12); sensorRotate(); Serial.println("\nRotation has been complete"); myServo.detach(); motorState = 1; } else { Serial.println("INCORRECT YOU WILL NOW BE ELIMANTED"); stateCharacteristic.setValue("Invalid Code"); } } void switchCharacteristicWritten(BLECentral& central, BLECharacteristic& characteristic) { //BLE Function Serial.print(F("Characteristic Sensor event: ")); if ( switchCharacteristic.value() ) { digitalWrite( MOTOR_PIN, HIGH); stateCharacteristic.setValue(1); myServo.attach(12); sensorRotate(); Serial.println("\nRotation has been complete"); myServo.detach(); motorState = 1; } else { digitalWrite( MOTOR_PIN, LOW); motorState = 0; stateCharacteristic.setValue(0); } } void sensorRotate() { // Rotates the Sensor 150 degrees for(int i=15;i<=165;i++){ myServo.write(i); delay(30); distance = calculateDistance(); Serial.print(i); Serial.print(","); Serial.print(distance); Serial.print("."); } for(int i=165;i>15;i--){ myServo.write(i); delay(30); distance = calculateDistance(); Serial.print(i); Serial.print(","); Serial.print(distance); Serial.print("."); } //motorState = 0; //currentState = LOW; } int calculateDistance(){ // Calculats the sound when it echos forward and hits an object. (Need to half the results) digitalWrite(trigPin, LOW); delayMicroseconds(2); // Sets the trigPin on HIGH state for 10 micro seconds digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); // Reads the echoPin, returns the sound wave travel time in microseconds distance= duration*0.034/2; return distance; }
[ "44473085+Huzar01@users.noreply.github.com" ]
44473085+Huzar01@users.noreply.github.com
31114b02c944129f4ec307324d608994791564c3
8143f7063f49a6971ce1a382f8240557ae4ed45b
/Mechanic.cc
ab84e001975056fc82f306f4a3b396c135f10f4f
[]
no_license
naolwakoya/MechanicShop
baadfa3d9326fdb4bc096294389a66a2168a8e59
b68ef826564caf86edd324dc99a523fbd8f27bda
refs/heads/main
2023-03-05T07:12:17.203304
2021-02-20T01:42:03
2021-02-20T01:42:03
340,527,966
0
0
null
null
null
null
UTF-8
C++
false
false
896
cc
#include <iostream> using namespace std; #include "Mechanic.h" int Mechanic::nextId = 5000; Mechanic::Mechanic(string fname, string lname, string add, string pnum, int sal) : Person(fname,lname,add,pnum), id(Mechanic::nextId++), salary(sal) { } int Mechanic::getId() const { return id; } ostream& operator<<(ostream& output, Mechanic& m) { ostringstream name; name << m.firstName << " " << m.lastName; output << "Employee ID " << m.id << endl << endl << " Name: " << setw(40) << name.str() << endl << " Address: " << setw(37) << m.address << endl << " Phone Number: " << setw(32) << m.phoneNumber << endl << " Salary: " << setw(38) << m.salary << endl; return output; } bool Mechanic::operator<(Mechanic& c) { return salary < c.salary; } bool Mechanic::operator>(Mechanic& c) { return salary > c.salary; }
[ "naolwakoya@cmail.carleton.ca" ]
naolwakoya@cmail.carleton.ca
6a87c23300e8c197825559487ad1eb56096d579f
3c9dcf4f6f2725982684b629a747f6063cf74866
/show_stulist.cpp
fe23053879d9b4d1297866b3ef30a85b1328cd4b
[]
no_license
Tina-Yin-2001/Library
efece7d41650d799010d933d1df7a81a735984a5
6b0b0ef9bc66421d2d73a6ff9ee4b00e83b74dfe
refs/heads/master
2023-08-19T22:19:40.068337
2021-10-14T08:18:01
2021-10-14T08:18:01
417,020,727
0
0
null
null
null
null
UTF-8
C++
false
false
2,715
cpp
#include "show_stulist.h" #include "init.h" #include "student.h" #include "ui_show_stulist.h" #include "studentstore.h" #include <iostream> #include <stdio.h> #include <stdlib.h> #include <fstream> #include <sstream> #include "utils.h" using namespace utils; show_stulist::show_stulist(QWidget *parent) : QDialog(parent), ui(new Ui::show_stulist) { ui->setupUi(this); loadStuList(); } show_stulist::~show_stulist() { delete ui; } void show_stulist::on_pushButton_clicked() { loadStuList(); } void show_stulist::loadStuList() { auto size = sizeof (Student);//学生类的大小 FILE *file = openfile(studentDatPath, size); //打开文件 fseek(file, 0, SEEK_END);//fseek将文件指针指到文件末尾 auto offset = ftell(file);//ftell得到文件从指针到文件头的大小(offset是文件总大小) int row = offset / size; //采取和增加用户时算ID大小一样的方法算数据行数 ui->tableWidget->setColumnCount(3); //设置列数 QStringList header; header << "学工号" << "姓名" << "专业"; ui->tableWidget->setHorizontalHeaderLabels(header); ui->tableWidget->setRowCount(row); //设置行数 for(int i = 0; i < row; i++) { Student* tempStu = studentstore::creatStudent(); fseek(file, size * i, SEEK_SET); //将指针移到该放的地方 fread(tempStu, size, 1, file); //读出需要查询的同学数据 QString id = QString(QString::fromLocal8Bit(tempStu->stu_id, MAX_ID)); QString name = QString(QString::fromLocal8Bit(tempStu->name, MAX_NAME)); QString major = QString(QString::fromLocal8Bit(tempStu->major, MAX_MAJOR)); ui->tableWidget->setItem(i, 0, new QTableWidgetItem(id)); ui->tableWidget->setItem(i, 1, new QTableWidgetItem(name)); ui->tableWidget->setItem(i, 2, new QTableWidgetItem(major)); delete(tempStu); } fclose(file);//关闭文件 } //导出成csv void show_stulist::on_pushButton_2_clicked() { ofstream outFile; outFile.open("C:\\Users\\dell\\Documents\\2021_news\\soft\\Library1.4\\stuList_output.csv", ios::out); //打开模式可省略 for (int i = 0; i < ui->tableWidget->rowCount(); i++) { QString str = ui->tableWidget->item(i, 0)->text(); string name = string((const char *)str.toLocal8Bit()); QString str_2 = ui->tableWidget->item(i, 1)->text(); string stu_id = string((const char *)str_2.toLocal8Bit()); QString str_3 = ui->tableWidget->item(i, 2)->text(); string major = string((const char *)str_3.toLocal8Bit()); outFile << name << "," << stu_id << "," << major << endl; } outFile.close(); }
[ "825111205@qq.com" ]
825111205@qq.com
9e9858688e1ddc85e286dbb7cd76c0c2084e9f0e
67b645a97d18d12841a1ac70aaf3f4c87b5d96d6
/framework/code/graphic/drawer/DrawerLightEffect.h
41bad94a3f38e4785e242e77ce1e0f8dfaed6954
[]
no_license
H405/MSProject
051d8ac7dbc8e6e0a39d9b6abdcceece102267d0
07cb61afc4ed5caa2c6ee2a928a3f5c6d34ccdc3
refs/heads/master
2021-01-10T17:44:19.281382
2016-01-19T23:54:43
2016-01-19T23:54:43
44,644,877
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
9,518
h
//============================================================================== // // File : DrawerLightEffect.h // Brief : ライト描画クラス // Author : Taiga Shirakawa // Date : 2015/10/31 sat : Taiga Shirakawa : create // //============================================================================== //****************************************************************************** // インクルードガード //****************************************************************************** #ifndef MY_DRAWER_LIGHT_EFFECT_H #define MY_DRAWER_LIGHT_EFFECT_H //****************************************************************************** // インクルード //****************************************************************************** #include "../../framework/graphic/drawer.h" //****************************************************************************** // ライブラリ //****************************************************************************** //****************************************************************************** // マクロ //****************************************************************************** //****************************************************************************** // クラス前方宣言 //****************************************************************************** class Effect; class EffectParameter; class Polygon2D; //****************************************************************************** // クラス定義 //****************************************************************************** class DrawerLightEffect : public Drawer { public: // パラメータ enum { PARAMETER_OFFET_TEXEL = 0, // テクセルオフセット PARAMETER_TEXTURE_DIFFUSE, // ディフューズテクスチャ PARAMETER_TEXTURE_SPECULAR, // スペキュラテクスチャ PARAMETER_TEXTURE_NORMAL, // 法線テクスチャ PARAMETER_TEXTURE_DEPTH, // 深度テクスチャ PARAMETER_TEXTURE_DIFFUSE_RIVER, // 川のディフューズテクスチャ PARAMETER_TEXTURE_SPECULAR_RIVER, // 川のスペキュラテクスチャ PARAMETER_TEXTURE_NORMAL_RIVER, // 川の法線テクスチャ PARAMETER_TEXTURE_DEPTH_RIVER, // 川の深度テクスチャ PARAMETER_TEXTURE_SHADOW, // 影テクスチャ PARAMETER_MATRIX_PROJECTION_INVERSE, // プロジェクション変換逆行列 PARAMETER_MATRIX_VIEW_INVERSE, // ビュー変換逆行列 PARAMETER_POSITION_EYE, // 視点座標 PARAMETER_CLIP_CAMERA, // カメラのクリップ値 PARAMETER_COLOR_AMBIENT, // 環境光色 PARAMETER_VECTOR_LIGHT_DIRECTION, // ディレクショナルライトのベクトル PARAMETER_COLOR_LIGHT_DIRECTION, // ディレクショナルライトの色 PARAMETER_POSITION_LIGHT_POINT, // ポイントライトの座標 PARAMETER_COLOR_LIGHT_POINT, // ポイントライトの色 PARAMETER_ATTENUATION_LIGHT_POINT, // ポイントライトの減衰率 PARAMETER_MAX // 最大値 }; //============================================================================== // Brief : コンストラクタ // Return : : // Arg : void : なし //============================================================================== DrawerLightEffect( void ); //============================================================================== // Brief : デストラクタ // Return : : // Arg : void : なし //============================================================================== ~DrawerLightEffect( void ); //============================================================================== // Brief : 初期化処理 // Return : int : 実行結果 // Arg : const EffectParameter* pParameter : エフェクトパラメータ // Arg : Effect* pEffect : 描画エフェクト // Arg : Polygon2D* pPolygon : 2Dポリゴン // Arg : IDirect3DTexture9* pTextureDiffuse : ディフューズ情報テクスチャ // Arg : IDirect3DTexture9* pTextureSpecular : スペキュラ情報テクスチャ // Arg : IDirect3DTexture9* pTextureNormal : 法線情報テクスチャ // Arg : IDirect3DTexture9* pTextureDepth : 深度情報テクスチャ // Arg : IDirect3DTexture9* pTextureDiffuseRiver : ディフューズ情報テクスチャ // Arg : IDirect3DTexture9* pTextureSpecularRiver : スペキュラ情報テクスチャ // Arg : IDirect3DTexture9* pTextureNormalRiver : 法線情報テクスチャ // Arg : IDirect3DTexture9* pTextureDepthRiver : 深度情報テクスチャ // Arg : IDirect3DTexture9* pTextureShadow : 影テクスチャ //============================================================================== int Initialize( const EffectParameter* pParameter, Effect* pEffect, Polygon2D* pPolygon, IDirect3DTexture9* pTextureDiffuse, IDirect3DTexture9* pTextureSpecular, IDirect3DTexture9* pTextureNormal, IDirect3DTexture9* pTextureDepth, IDirect3DTexture9* pTextureDiffuseRiver, IDirect3DTexture9* pTextureSpecularRiver, IDirect3DTexture9* pTextureNormalRiver, IDirect3DTexture9* pTextureDepthRiver, IDirect3DTexture9* pTextureShadow ); //============================================================================== // Brief : 終了処理 // Return : int : 実行結果 // Arg : void : なし //============================================================================== int Finalize( void ); //============================================================================== // Brief : 再初期化処理 // Return : int : 実行結果 // Arg : const EffectParameter* pParameter : エフェクトパラメータ // Arg : Effect* pEffect : 描画エフェクト // Arg : Polygon2D* pPolygon : 2Dポリゴン // Arg : IDirect3DTexture9* pTextureDiffuse : ディフューズ情報テクスチャ // Arg : IDirect3DTexture9* pTextureSpecular : スペキュラ情報テクスチャ // Arg : IDirect3DTexture9* pTextureNormal : 法線情報テクスチャ // Arg : IDirect3DTexture9* pTextureDepth : 深度情報テクスチャ // Arg : IDirect3DTexture9* pTextureDiffuseRiver : ディフューズ情報テクスチャ // Arg : IDirect3DTexture9* pTextureSpecularRiver : スペキュラ情報テクスチャ // Arg : IDirect3DTexture9* pTextureNormalRiver : 法線情報テクスチャ // Arg : IDirect3DTexture9* pTextureDepthRiver : 深度情報テクスチャ // Arg : IDirect3DTexture9* pTextureShadow : 影テクスチャ //============================================================================== int Reinitialize( const EffectParameter* pParameter, Effect* pEffect, Polygon2D* pPolygon, IDirect3DTexture9* pTextureDiffuse, IDirect3DTexture9* pTextureSpecular, IDirect3DTexture9* pTextureNormal, IDirect3DTexture9* pTextureDepth, IDirect3DTexture9* pTextureDiffuseRiver, IDirect3DTexture9* pTextureSpecularRiver, IDirect3DTexture9* pTextureNormalRiver, IDirect3DTexture9* pTextureDepthRiver, IDirect3DTexture9* pTextureShadow ); //============================================================================== // Brief : クラスのコピー // Return : int : 実行結果 // Arg : DrawerLightEffect* pOut : コピー先アドレス //============================================================================== int Copy( DrawerLightEffect* pOut ) const; //============================================================================== // Brief : 描画処理 // Return : void : なし // Arg : const D3DXMATRIX& matrixWorld : ワールドマトリクス //============================================================================== void Draw( const D3DXMATRIX& matrixWorld ); //============================================================================== // アクセサ //============================================================================== void SetTextureDiffuse( IDirect3DTexture9* pValue ); IDirect3DTexture9* GetTextureDiffuse( void ) const; void SetTextureSpecular( IDirect3DTexture9* pValue ); IDirect3DTexture9* GetTextureSpecular( void ) const; void SetTextureNormal( IDirect3DTexture9* pValue ); IDirect3DTexture9* GetTextureNormal( void ) const; void SetTextureDepth( IDirect3DTexture9* pValue ); IDirect3DTexture9* GetTextureDepth( void ) const; protected: const EffectParameter* pEffectParameter_; // エフェクトパラメータ Effect* pEffect_; // エフェクト IDirect3DTexture9* pTextureDiffuse_; // ディフューズ情報テクスチャ IDirect3DTexture9* pTextureSpecular_; // スペキュラ情報テクスチャ IDirect3DTexture9* pTextureNormal_; // 法線情報テクスチャ IDirect3DTexture9* pTextureDepth_; // 深度情報テクスチャ IDirect3DTexture9* pTextureDiffuseRiver_; // ディフューズ情報テクスチャ IDirect3DTexture9* pTextureSpecularRiver_; // スペキュラ情報テクスチャ IDirect3DTexture9* pTextureNormalRiver_; // 法線情報テクスチャ IDirect3DTexture9* pTextureDepthRiver_; // 深度情報テクスチャ IDirect3DTexture9* pTextureShadow_; // 影テクスチャ Polygon2D* pPolygon_; // ポリゴン private: void InitializeSelf( void ); DrawerLightEffect( const DrawerLightEffect& ); DrawerLightEffect operator=( const DrawerLightEffect& ); }; #endif // MY_DRAWER_LIGHT_EFFECT_H
[ "taiga11235@gmail.com" ]
taiga11235@gmail.com
7a2934a7827cf7174755f49efd802179aeda520a
7e6f19290c2a4bbe03cf5ac6ab302ff45be2cee3
/Source/PortalGame/HexEditorActor.cpp
c078f8ecad46713618a72c24bd1edee92fd6a1d2
[]
no_license
jijik/portal_game
fa512eb054164b0a53701667c17ba76ab1dcb45d
a7614e331f2d511e71fd30fcb400825f5efe203a
refs/heads/master
2020-04-06T07:04:01.781521
2016-08-16T19:56:42
2016-08-16T19:56:42
53,754,208
1
0
null
null
null
null
UTF-8
C++
false
false
31,964
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "PortalGame.h" #include "HexEditorActor.h" #include "CompanionActor.h" #include "BlockerActor.h" #include "BarrierActor.h" #include "BridgeActor.h" #include "TurretActor.h" #include "PlatformActor.h" #include "FinishActor.h" #include "TeleportActor.h" #include "Dude.h" #include "HexGame.h" #include "PortalAI.h" #include "ExpandArrowComponent.h" #include "Engine/StaticMeshActor.h" #include <istream> #include <ostream> #include <fstream> #include <sstream> #include <ctime> //======================================================================== AHexEditorActor::AHexEditorActor() :m_RootTileCoordinates(0,0,0) { m_PortalAI = new C_PortalAI; gHexEditor = this; m_Grid.SetTileRadius(100.0); m_SelectedHexTile = nullptr; PrimaryActorTick.bCanEverTick = true; static ConstructorHelpers::FObjectFinder<UMaterial> DefaultMat(TEXT("Material'/Game/Materials/Default.Default'")); static ConstructorHelpers::FObjectFinder<UMaterial> Selected(TEXT("Material'/Game/Materials/Default2.Default2'")); m_DefaultMaterial = DefaultMat.Object; m_SelectedMaterial = Selected.Object; } //======================================================================== AHexEditorActor::~AHexEditorActor() { delete m_PortalAI; } //======================================================================== void AHexEditorActor::BeginPlay() { Super::BeginPlay(); AHexTileActor::Init(m_RootTileCoordinates); m_Grid.InsertElement({ 0, 0 }, this); EnableInput(GetWorld()->GetFirstPlayerController()); SwitchBindings(InputMode::Expanding); FVector locator(0, 0, 0); m_ArrowsParent = GetWorld()->SpawnActor(AActor::StaticClass()); m_ArrowsParent->SetRootComponent(NewObject<USceneComponent>(m_ArrowsParent,TEXT("ArrowsParent"))); for (int i = 0; i < 6; ++i) { FVector locator(0, 0, 0); FRotator rot(0, 60 * -i, 0); auto* actor = GetWorld()->SpawnActor(ExpansionArrowActor, &locator, &rot); m_Arrows[i] = CastChecked<AStaticMeshActor>(actor); m_Arrows[i]->GetStaticMeshComponent()->SetVisibility(false); m_Arrows[i]->GetStaticMeshComponent()->SetCollisionEnabled(ECollisionEnabled::NoCollision); m_Arrows[i]->GetStaticMeshComponent()->SetMobility(EComponentMobility::Movable); auto* arrowComp = m_Arrows[i]->FindComponentByClass<UExpandArrowComponent>(); check(arrowComp); arrowComp->SetRelativeDirection(i); m_Arrows[i]->GetStaticMeshComponent()->OnClicked.AddDynamic(arrowComp, &UExpandArrowComponent::OnClick); m_Arrows[i]->AttachRootComponentToActor(m_ArrowsParent); } } //======================================================================== void AHexEditorActor::SwitchBindings(InputMode to) { UnregisterAllBindings(); switch (to) { case AHexEditorActor::None: RegisterNoneBinding(); break; case AHexEditorActor::Expanding: RegisterExpandingBinding(); break; case AHexEditorActor::Barriers: RegisterBarriersBinding(); break; case AHexEditorActor::Platforms: RegisterPlatformsBinding(); break; case AHexEditorActor::Companions: RegisterCompanionsBinding();break; case AHexEditorActor::Blockers: RegisterBlockersBinding(); break; case AHexEditorActor::Bridges: RegisterBridgesBinding(); break; case AHexEditorActor::Turrets: RegisterTurretsBinding(); break; case AHexEditorActor::Teleports: RegisterTeleportsBinding(); break; case AHexEditorActor::Finish: RegisterFinishBinding(); break; case AHexEditorActor::Game: RegisterGameBinding(); break; default: check(false); break; } } //======================================================================== void AHexEditorActor::RegisterNoneBinding() { InputComponent->BindAction("InputMode", IE_Pressed, this, &AHexEditorActor::CycleInputMode); } //======================================================================== void AHexEditorActor::RegisterExpandingBinding() { InputComponent->BindAction("Deselect", IE_Released, this, &AHexEditorActor::Deselect); InputComponent->BindAction("DEL", IE_Released, this, &AHexEditorActor::DeleteTile); InputComponent->BindAction("CycleModel", IE_Pressed, this, &AHexEditorActor::CycleModel); InputComponent->BindAction("RotateModel", IE_Pressed, this, &AHexEditorActor::RotateModel); InputComponent->BindAction("ExpandUp", IE_Pressed, this, &AHexEditorActor::ExpandUp); InputComponent->BindAction("InputMode", IE_Pressed, this, &AHexEditorActor::CycleInputMode); } //======================================================================== void AHexEditorActor::RegisterBarriersBinding() { InputComponent->BindAction("Deselect", IE_Released, this, &AHexEditorActor::Deselect); InputComponent->BindAction("CycleModel", IE_Pressed, this, &AHexEditorActor::CycleModel); InputComponent->BindAction("InputMode", IE_Pressed, this, &AHexEditorActor::CycleInputMode); } //======================================================================== void AHexEditorActor::RegisterPlatformsBinding() { InputComponent->BindAction("Deselect", IE_Released, this, &AHexEditorActor::Deselect); InputComponent->BindAction("CycleModel", IE_Pressed, this, &AHexEditorActor::CycleModel); InputComponent->BindAction("InputMode", IE_Pressed, this, &AHexEditorActor::CycleInputMode); } //======================================================================== void AHexEditorActor::RegisterCompanionsBinding() { InputComponent->BindAction("DEL", IE_Released, this, &AHexEditorActor::DeleteAllCompanions); InputComponent->BindAction("InputMode", IE_Pressed, this, &AHexEditorActor::CycleInputMode); } //======================================================================== void AHexEditorActor::RegisterBlockersBinding() { InputComponent->BindAction("DEL", IE_Released, this, &AHexEditorActor::DeleteAllBlockers); InputComponent->BindAction("InputMode", IE_Pressed, this, &AHexEditorActor::CycleInputMode); } //======================================================================== void AHexEditorActor::RegisterBridgesBinding() { InputComponent->BindAction("DEL", IE_Released, this, &AHexEditorActor::DeleteAllBridges); InputComponent->BindAction("InputMode", IE_Pressed, this, &AHexEditorActor::CycleInputMode); } //======================================================================== void AHexEditorActor::RegisterTurretsBinding() { InputComponent->BindAction("DEL", IE_Released, this, &AHexEditorActor::DeleteAllTurrets); InputComponent->BindAction("InputMode", IE_Pressed, this, &AHexEditorActor::CycleInputMode); } //======================================================================== void AHexEditorActor::RegisterFinishBinding() { InputComponent->BindAction("InputMode", IE_Pressed, this, &AHexEditorActor::CycleInputMode); } //======================================================================== void AHexEditorActor::RegisterTeleportsBinding() { InputComponent->BindAction("DEL", IE_Released, this, &AHexEditorActor::DeleteAllTeleports); InputComponent->BindAction("InputMode", IE_Pressed, this, &AHexEditorActor::CycleInputMode); } //======================================================================== void AHexEditorActor::RegisterGameBinding() { InputComponent->BindAction("Action1", IE_Pressed, this, &AHexEditorActor::Action1Click); InputComponent->BindAction("Action2", IE_Pressed, this, &AHexEditorActor::Action2Click); InputComponent->BindAction("InputMode", IE_Pressed, this, &AHexEditorActor::CycleInputMode); InputComponent->BindAction("CycleModel", IE_Pressed, this, &AHexEditorActor::GameCycleModel); } //======================================================================== void AHexEditorActor::UnregisterAllBindings() { while (InputComponent->GetNumActionBindings() > 0) { InputComponent->RemoveActionBinding(0); } } //======================================================================== void AHexEditorActor::Tick(float DeltaTime) { print_frame(InputModeStr[m_InputType].c_str(), DeltaTime); UpdateBarrierPlacing(); UpdatePlatformPlacing(); m_PortalAI->Update(DeltaTime); if (m_AttachingPlatform) { print_frame("Click on the platform target", DeltaTime); } // Raycast<AActor>(this, [&](auto& resultActor, auto& traceResult) // { // print_frame((*resultActor->GetHumanReadableName()), DeltaTime); // // auto tileCenter = m_Grid.GetPosition(m_Grid.GetCoordinates(traceResult.Location)); // DrawDebugCircle(GetWorld(), tileCenter, 50, 32, FColor::Red, false, -1.f, 0, 3); // }); // for (auto& c : m_Grid.GetStorage()) // { // std::stringstream ss; // ss << c.first.s << "," << c.first.t << "\n"; // DrawDebugString(GetWorld(), pos, ss.str().c_str()); // } } //======================================================================== void AHexEditorActor::ClickOnTile(AHexTileActor& hexTile) { if (m_InputType == InputMode::Expanding) { SelectTile(&hexTile); } else if (m_InputType == InputMode::Barriers) { PlaceBarrier(); } else if (m_InputType == InputMode::Platforms) { PlacePlatform(); } else if (m_InputType == InputMode::Companions) { PlaceCompanion(); } else if (m_InputType == InputMode::Blockers) { PlaceBlocker(hexTile); } else if (m_InputType == InputMode::Bridges) { PlaceBridge(hexTile); } else if (m_InputType == InputMode::Turrets) { PlaceTurret(hexTile); } else if (m_InputType == InputMode::Teleports) { PlaceTeleport(hexTile); } else if (m_InputType == InputMode::Finish) { PlaceFinish(hexTile); } } //======================================================================== void AHexEditorActor::SelectTile(AHexTileActor* hexTile) { HandleSelectionMaterial(hexTile); m_SelectedHexTile = hexTile; ShowExpansionArrows(); if (hexTile) { SelectBarrier(nullptr); } SelectPlatform(nullptr); } //======================================================================== void AHexEditorActor::DeselectTile() { SelectTile(nullptr); m_AttachingPlatform = false; } //======================================================================== void AHexEditorActor::Deselect() { DeselectTile(); SelectBarrier(nullptr); SelectPlatform(nullptr); if (m_InputType != InputMode::Expanding) { ChangeInputMode(InputMode::None); } } //======================================================================== void AHexEditorActor::HandleSelectionMaterial(AHexTileActor* hexTile) { if (m_SelectedHexTile) { m_SelectedHexTile->SetSelectedMaterial(false); } if (hexTile) { hexTile->SetSelectedMaterial(true); } } //======================================================================== void AHexEditorActor::ShowExpansionArrows() { for (auto* arrow : m_Arrows) { arrow->GetStaticMeshComponent()->SetVisibility(false); arrow->GetStaticMeshComponent()->SetCollisionEnabled(ECollisionEnabled::NoCollision); } if (m_SelectedHexTile == nullptr) { return; } auto& currentTile = m_SelectedHexTile->GetCoordinates(); for (int i = 0; i < 6; ++i) { auto potentialTile = T_HexGrid::HorizontalNeighborIndexes[i] + currentTile; if (m_Grid.GetElement(potentialTile) == nullptr) { auto p = m_Grid.GetPosition(currentTile); m_Arrows[i]->SetActorLocation(p); m_Arrows[i]->GetStaticMeshComponent()->SetVisibility(true); m_Arrows[i]->GetStaticMeshComponent()->SetCollisionEnabled(ECollisionEnabled::QueryAndPhysics); } } } //======================================================================== void AHexEditorActor::Expand(const S_HexCoordinates& dir) { check(m_SelectedHexTile); S_HexCoordinates expandedCoordinated = m_SelectedHexTile->GetCoordinates() + dir; check(m_Grid.GetElement(expandedCoordinated) == nullptr); auto* tile = GetWorld()->SpawnActor<AHexTileActor>(); tile->Init(expandedCoordinated); m_Grid.InsertElement(expandedCoordinated, tile); if (dir.IsHorizontalDir()) { auto hexDir = dir.ToHexDir(); auto* barrier = m_SelectedHexTile->GetBarrierAt(hexDir); if (barrier) { auto complementDir = T_HexGrid::GetComplementaryNeighborIndex(hexDir); tile->PlaceBarrierAt(*barrier, complementDir); barrier->Place(*m_SelectedHexTile, hexDir, tile, complementDir); } } DeselectTile(); SelectTile(tile); } //======================================================================== void AHexEditorActor::ExpandUp() { if (m_SelectedHexTile == nullptr) { return; } S_HexCoordinates up(0, 0, 1); S_HexCoordinates expandedCoordinated = m_SelectedHexTile->GetCoordinates() + up; if (m_Grid.GetElement(expandedCoordinated) != nullptr) { return; //full } Expand(up); } //======================================================================== void AHexEditorActor::DeleteTile() { DeleteBarrier(); DeletePlatform(); if (m_SelectedHexTile == nullptr) { return; } DeleteTileImpl(*m_SelectedHexTile, true); } //======================================================================== void AHexEditorActor::DeleteTileImpl(AHexTileActor& hexTile, bool deselectOld) { auto coords = hexTile.GetCoordinates(); if (coords == m_RootTileCoordinates) { FMessageDialog::Debugf(FText::FromString("Cannot delete the root tile!")); return; } UnlinkAllFromTile(hexTile); if (deselectOld) { DeselectTile(); } GetWorld()->DestroyActor(&hexTile); m_Grid.RemoveElement(coords); } //======================================================================== void AHexEditorActor::UnlinkAllFromTile(AHexTileActor& hexTile) { for (HexDir i = 0; i < 6; ++i) { auto* barrier = hexTile.GetBarrierAt(i); if (barrier) { auto orphan = barrier->UnlinkTileFomBarrier(hexTile); if (orphan) { GetWorld()->DestroyActor(barrier); m_AllBarriers.erase(barrier); } hexTile.RemoveBarrierAt(i); } } auto* platform = hexTile.GetPlatform(); if (platform) { hexTile.RemovePlatform(); GetWorld()->DestroyActor(platform); m_AllPlatforms.erase(platform); } } //======================================================================== void AHexEditorActor::DeleteBarrier() { if (m_SelectedBarrier == nullptr) { return; } check(m_SelectedHexTile == nullptr); m_SelectedBarrier->UnlinkBarrierFromNeighborTiles(); GetWorld()->DestroyActor(m_SelectedBarrier); m_AllBarriers.erase(m_SelectedBarrier); for (auto* platform : m_AllPlatforms) { if (platform->GetTarget() == m_SelectedBarrier) { platform->SetTarget(nullptr); } } m_SelectedBarrier = nullptr; } //======================================================================== void AHexEditorActor::CreatePlatformForPlacing() { check(m_CurrentPlatform == nullptr); m_CurrentPlatform = GetWorld()->SpawnActor<APlatformActor>(); m_CurrentPlatform->Init(); } //======================================================================== void AHexEditorActor::UpdatePlatformPlacing() { if (m_CurrentPlatform) { check(m_InputType == InputMode::Platforms); Raycast<AHexTileActor>(this, [&](auto& resultActor, auto& traceResult) { auto& coords = resultActor->GetCoordinates(); auto tilePos = m_Grid.GetPosition(coords); m_CurrentPlatform->SetActorLocation(tilePos); m_CurrentPlatform->SetOwningTileBeforePlace(resultActor); }, [&]() { m_CurrentPlatform->SetOwningTileBeforePlace(nullptr); }); } } //======================================================================== void AHexEditorActor::PlacePlatform(bool inGame) { if(m_AttachingPlatform || !m_CurrentPlatform->IsReadyToPlace()) { return; } auto* owner = m_CurrentPlatform->GetOwningTileBeforePlace(); check(owner); if (owner->HasPlatform()) { return; } owner->PlacePlatform(*m_CurrentPlatform); m_CurrentPlatform->Place(*owner); m_AllPlatforms.insert(m_CurrentPlatform); auto* placed = m_CurrentPlatform; m_CurrentPlatform = nullptr; //leave it to live it's life if (inGame) { m_AttachingPlatform = true; SelectPlatform(placed); } print("Platform placed..."); } //======================================================================== void AHexEditorActor::DeletePlatform() { if (m_SelectedPlatform == nullptr) { return; } check(m_SelectedHexTile == nullptr); m_SelectedPlatform->UnlinkPlatformFromOwningTile(); GetWorld()->DestroyActor(m_SelectedPlatform); m_AllPlatforms.erase(m_SelectedPlatform); m_SelectedPlatform = nullptr; } //======================================================================== AHexEditorActor::T_HexGrid& AHexEditorActor::GetHexGrid() { return m_Grid; } //======================================================================== void AHexEditorActor::CycleModel() { if (m_InputType == InputMode::Expanding) { if (m_SelectedHexTile) { m_SelectedHexTile->CycleModel(); } } else if (m_InputType == InputMode::Barriers) { check(m_CurrentBarrier); m_CurrentBarrier->CycleModel(); } else if (m_InputType == InputMode::Platforms) { check(m_CurrentPlatform); m_CurrentPlatform->CycleModel(); } } //======================================================================== void AHexEditorActor::RotateModel() { if (m_InputType == InputMode::Expanding && m_SelectedHexTile) { m_SelectedHexTile->RotateModel(); } } //======================================================================== void AHexEditorActor::CycleInputMode() { unsigned tmp = (unsigned)m_InputType; tmp += 1; tmp %= InputMode::TOTAL; ChangeInputMode((InputMode)tmp); } //======================================================================== void AHexEditorActor::ChangeInputMode(InputMode to, bool deselect) { if (m_InputType == InputMode::Barriers) { check(m_CurrentBarrier); GetWorld()->DestroyActor(m_CurrentBarrier); m_CurrentBarrier = nullptr; } else if (m_InputType == InputMode::Platforms) { if (m_CurrentPlatform) { GetWorld()->DestroyActor(m_CurrentPlatform); m_CurrentPlatform = nullptr; } } else if (m_InputType == InputMode::Teleports) { if (m_CurrentTeleport) { m_AllTeleports.erase(m_CurrentTeleport); GetWorld()->DestroyActor(m_CurrentTeleport); m_CurrentTeleport = nullptr; } } if (to == InputMode::Barriers) { CreateBarrierForPlacing(); } else if (to == InputMode::Platforms) { if (!m_AttachingPlatform) { CreatePlatformForPlacing(); } } m_InputType = to; if (deselect) { DeselectTile(); } SwitchBindings(to); } //======================================================================== void AHexEditorActor::Action1Click() { Raycast<AActor>(this, [&](auto& resultActor, auto& traceResult) { auto* companion = Cast<ACompanionActor>(resultActor); auto* teleport = Cast<ATeleportActor>(resultActor); if (companion) { companion->OnClick(); } else if (teleport) { teleport->Use(*gHexGame->Dude); } else { gHexGame->Dude->Move(traceResult.Location); } }); } //======================================================================== void AHexEditorActor::Action2Click() { if (m_CurrentBlocker) { FinishBlockerPlacing(); } if (m_CurrentBridge) { FinishBridgePlacing(); } gHexGame->Dude->Drop(); } //======================================================================== void AHexEditorActor::CreateBarrierForPlacing() { check(m_CurrentBarrier == nullptr); m_CurrentBarrier = GetWorld()->SpawnActor<ABarrierActor>(); m_CurrentBarrier->Init(); } //======================================================================== void AHexEditorActor::UpdateBarrierPlacing() { if (m_CurrentBarrier) { check(m_InputType == InputMode::Barriers); Raycast<AHexTileActor>(this, [&](auto& resultActor, auto& traceResult) { auto& coords = resultActor->GetCoordinates(); auto tilePos = m_Grid.GetPosition(coords); auto toHit = traceResult.ImpactPoint - tilePos; auto nId = GetNeighborId(toHit); auto neighborRelativeCoordinates = T_HexGrid::HorizontalNeighborIndexes[nId]; auto pos = m_Grid.GetPositionBetweenTiles(coords, coords + neighborRelativeCoordinates); m_CurrentBarrier->SetActorLocation(pos); m_CurrentBarrier->SetActorRotation(FRotator(0, 60 * -(int)nId, 0)); m_CurrentBarrier->SetOwningTileBeforePlace(resultActor, nId); }, [&]() { m_CurrentBarrier->SetOwningTileBeforePlace(nullptr); }); } } //======================================================================== unsigned AHexEditorActor::GetNeighborId(const FVector& fromCenter) { // compensate axis switch etc, nasty piece of code... redo auto rad = atan2(fromCenter.Y, fromCenter.X); auto deg = FMath::RadiansToDegrees(rad); unsigned segment; if (deg < 0) deg = 360.0 + deg; deg = 360 - deg; segment = (unsigned)deg / 60; segment += 2; segment %= 6; return segment; } //======================================================================== void AHexEditorActor::PlaceBarrier(bool createAnother) { if (!m_CurrentBarrier->IsReadyToPlace()) { return; } auto* owningTile = m_CurrentBarrier->GetOwningTileBeforePlace(); auto sectorDir = m_CurrentBarrier->GetOwningSectorBeforePlace(); check(owningTile); if (owningTile->HasBarrierAt(sectorDir)) { return; } auto neighborCoordinates = owningTile->GetCoordinates() + T_HexGrid::HorizontalNeighborIndexes[sectorDir]; auto neighborTile = m_Grid.GetElement(neighborCoordinates); owningTile->PlaceBarrierAt(*m_CurrentBarrier, sectorDir); auto complementarySector = T_HexGrid::GetComplementaryNeighborIndex(sectorDir); if (neighborTile) { check(!neighborTile->HasBarrierAt(complementarySector)); neighborTile->PlaceBarrierAt(*m_CurrentBarrier, complementarySector); } m_CurrentBarrier->Place(*owningTile, sectorDir, neighborTile, complementarySector); m_AllBarriers.insert(m_CurrentBarrier); m_CurrentBarrier = nullptr; //leave it to live it's life if (createAnother) { CreateBarrierForPlacing(); } print("Barrier placed..."); } //======================================================================== void AHexEditorActor::PlaceCompanion() { Raycast<AHexTileActor>(this, [&](auto& resultActor, auto& traceResult) { auto* companion = GetWorld()->SpawnActor<ACompanionActor>(); m_AllCompanions.insert(companion); companion->Init(traceResult.Location); }); } //======================================================================== void AHexEditorActor::DeleteAllCompanions() { for (auto* c : m_AllCompanions) { GetWorld()->DestroyActor(c); } m_AllCompanions.clear(); } //======================================================================== void AHexEditorActor::PlaceBlocker(AHexTileActor& hexTile) { Raycast<AHexTileActor>(this, [&](auto& resultActor, auto& traceResult) { auto* blocker = GetWorld()->SpawnActor<ABlockerActor>(); m_AllBlockers.insert(blocker); blocker->Init(traceResult.Location); }); } //======================================================================== void AHexEditorActor::DeleteAllBlockers() { for (auto* c : m_AllBlockers) { GetWorld()->DestroyActor(c); } m_AllBlockers.clear(); } //======================================================================== void AHexEditorActor::FinishBlockerPlacing() { m_CurrentBlocker->m_Placing = false; m_CurrentBlocker = nullptr; } //======================================================================== void AHexEditorActor::PlaceBridge(AHexTileActor& hexTile) { Raycast<AHexTileActor>(this, [&](auto& resultActor, auto& traceResult) { auto* bridge = GetWorld()->SpawnActor<ABridgeActor>(); m_AllBridges.insert(bridge); bridge->Init(traceResult.Location); }); } //======================================================================== void AHexEditorActor::DeleteAllBridges() { for (auto* c : m_AllBridges) { GetWorld()->DestroyActor(c); } m_AllBridges.clear(); } //======================================================================== void AHexEditorActor::FinishBridgePlacing() { m_CurrentBridge->m_Placing = false; m_CurrentBridge = nullptr; } //======================================================================== void AHexEditorActor::PlaceTurret(AHexTileActor& hexTile) { Raycast<AHexTileActor>(this, [&](auto& resultActor, auto& traceResult) { auto* turret = GetWorld()->SpawnActor<ATurretActor>(); m_AllTurrets.insert(turret); turret->SetActorLocation(m_Grid.GetPosition(hexTile.GetCoordinates())); }); } //======================================================================== void AHexEditorActor::DeleteAllTurrets() { for (auto* c : m_AllTurrets) { GetWorld()->DestroyActor(c); } m_AllTurrets.clear(); } //======================================================================== void AHexEditorActor::PlaceTeleport(AHexTileActor& hexTile) { auto createTeleport = [&]() { auto* teleport = GetWorld()->SpawnActor<ATeleportActor>(); m_AllTeleports.insert(teleport); teleport->SetActorLocation(m_Grid.GetPosition(hexTile.GetCoordinates())); return teleport; }; if (!m_CurrentTeleport) { m_CurrentTeleport = createTeleport(); } else { auto* teleport = createTeleport(); teleport->Link(*m_CurrentTeleport); m_CurrentTeleport->Link(*teleport); m_CurrentTeleport = nullptr; } } //======================================================================== void AHexEditorActor::DeleteAllTeleports() { for (auto* c : m_AllTeleports) { GetWorld()->DestroyActor(c); } m_AllTeleports.clear(); } //======================================================================== void AHexEditorActor::PlaceFinish(AHexTileActor& hexTile) { if (!m_Finish) { m_Finish = GetWorld()->SpawnActor<AFinishActor>(); } m_Finish->SetActorLocation(m_Grid.GetPosition(hexTile.GetCoordinates())); } //======================================================================== void AHexEditorActor::DeleteFinish() { if (m_Finish) { GetWorld()->DestroyActor(m_Finish); } m_Finish = nullptr; } //======================================================================== void AHexEditorActor::GameCycleModel() { if (m_CurrentBridge) { m_CurrentBridge->Cycle(); } } //======================================================================== void AHexEditorActor::SelectBarrier(class ABarrierActor* ba) { if (m_InputType == InputMode::Platforms && m_AttachingPlatform) { check(m_SelectedPlatform && ba); m_SelectedPlatform->SetTarget(ba); DeselectTile(); m_AttachingPlatform = false; CreatePlatformForPlacing(); } if (m_InputType != InputMode::Expanding) { return; } if (ba) { DeselectTile(); } check(m_CurrentBarrier == nullptr); if (m_SelectedBarrier) { m_SelectedBarrier->SetSelectedMaterial(false); } m_SelectedBarrier = ba; if (m_SelectedBarrier) { m_SelectedBarrier->SetSelectedMaterial(true); } } //======================================================================== void AHexEditorActor::SelectPlatform(class APlatformActor* pa) { if (!(m_InputType == InputMode::Expanding || m_InputType == InputMode::Platforms && m_AttachingPlatform)) { return; } if (pa && !pa->GetTarget()) { m_AttachingPlatform = true; ChangeInputMode(InputMode::Platforms, false); } if (pa) { DeselectTile(); } check(m_CurrentPlatform == nullptr); if (m_SelectedPlatform) { m_SelectedPlatform->SetSelectedMaterial(false); } m_SelectedPlatform = pa; if (m_SelectedPlatform) { m_SelectedPlatform->SetSelectedMaterial(true); } if (m_SelectedPlatform && !m_SelectedPlatform->GetTarget()) { m_AttachingPlatform = true; } } //======================================================================== void AHexEditorActor::ClearAll() { std::vector<AHexTileActor*> toDelete; for (auto& pair: m_Grid.GetStorage()) { if (!pair.first.IsZero()) //delete all but main tile { toDelete.push_back(pair.second); } } while (!toDelete.empty()) { SelectTile(toDelete.back()); DeleteTile(); toDelete.pop_back(); } DeleteAllCompanions(); DeleteAllBlockers(); DeleteAllTurrets(); DeleteAllTeleports(); DeleteFinish(); auto* element = m_Grid.GetElement({ 0,0,0 }); check(element); UnlinkAllFromTile(*element); } //======================================================================== void AHexEditorActor::SaveMap(const FString& name) { if (FPaths::FileExists(name)) { //if file exists copy it to backup file to prevent overriding some maps auto newName = name; std::stringstream ss; auto t = std::time(nullptr); ss << t; newName.Append(ss.str().c_str()); std::ifstream src(*name, std::ios::binary); std::ofstream dst(*newName, std::ios::binary); dst << src.rdbuf(); src.close(); dst.close(); } std::ofstream file; file.open(*name, std::ofstream::binary); auto& gridStorage = m_Grid.GetStorage(); binary_write(file, (unsigned)gridStorage.size()); this->Save(file); //editor tile first for (auto& pair : gridStorage) { if (pair.second != this) { pair.second->Save(file); } } binary_write(file, (unsigned)m_AllBarriers.size()); for (auto* barrier : m_AllBarriers) { barrier->Save(file); } binary_write(file, (unsigned)m_AllPlatforms.size()); for (auto* platform : m_AllPlatforms) { platform->Save(file); } binary_write(file, (unsigned)m_AllCompanions.size()); for (auto* companion : m_AllCompanions) { companion->Save(file); } binary_write(file, (unsigned)m_AllBlockers.size()); for (auto* blocker : m_AllBlockers) { blocker->Save(file); } binary_write(file, (unsigned)m_AllBridges.size()); for (auto* bridges : m_AllBridges) { bridges->Save(file); } binary_write(file, (unsigned)m_AllTurrets.size()); for (auto* turret : m_AllTurrets) { turret->Save(file); } binary_write(file, (unsigned)m_AllTeleports.size()); for (auto* t : m_AllTeleports) { t->Save(file); } binary_write(file, m_Finish); m_Finish->Save(file); file.close(); } //======================================================================== void AHexEditorActor::LoadMap(const FString& name) { ClearAll(); std::ifstream file(*name, std::ifstream::binary); if (!file.good()) { print(TEXT("no such map file!")); return; } unsigned count = 0; binary_read(file, count); //tiles for (unsigned i = 0; i < count; ++i) { AHexTileActor* tile; if (i == 0) { tile = this; } else { tile = GetWorld()->SpawnActor<AHexTileActor>(); tile->Init({ 0,0,0 }); //tmp coords; } tile->Load(file); m_Grid.InsertElement(tile->GetCoordinates(), tile); } binary_read(file, count); //barriers for (unsigned i = 0; i < count; ++i) { CreateBarrierForPlacing(); m_CurrentBarrier->Load(file); PlaceBarrier(false); } binary_read(file, count); //platforms for (unsigned i = 0; i < count; ++i) { CreatePlatformForPlacing(); m_CurrentPlatform->Load(file); PlacePlatform(false); } binary_read(file, count); //companions for (unsigned i = 0; i < count; ++i) { auto* companion = GetWorld()->SpawnActor<ACompanionActor>(); m_AllCompanions.insert(companion); companion->Load(file); } binary_read(file, count); //blocker for (unsigned i = 0; i < count; ++i) { auto* blocker = GetWorld()->SpawnActor<ABlockerActor>(); m_AllBlockers.insert(blocker); blocker->Load(file); } binary_read(file, count); //bridges for (unsigned i = 0; i < count; ++i) { auto* bridge = GetWorld()->SpawnActor<ABridgeActor>(); m_AllBridges.insert(bridge); bridge->Load(file); } binary_read(file, count); //turret for (unsigned i = 0; i < count; ++i) { auto* turret = GetWorld()->SpawnActor<ATurretActor>(); m_AllTurrets.insert(turret); turret->Load(file); } binary_read(file, count); //teleport for (unsigned i = 0; i < count; ++i) { auto* teleport = GetWorld()->SpawnActor<ATeleportActor>(); m_AllTeleports.insert(teleport); teleport->Load(file); } for (auto* t : m_AllTeleports) { t->PostLoad(); } AFinishActor* finish; binary_read(file, finish); //finish if (finish) { m_Finish = GetWorld()->SpawnActor<AFinishActor>(); m_Finish->Load(file); } file.close(); m_PortalAI->Generate(); UNavigationSystem* NavSys = UNavigationSystem::GetCurrent(GetWorld()); if (NavSys) { NavSys->Build(); } } //========================================================================
[ "=" ]
=
aa7474f5e6680a04b158c0c86558b4c2f735cb99
3fc3367fb56b21f34d2b6c36e0da93266cd7c15b
/src/rpcrawtransaction.cpp
1d1aa31d73b817c6d16a37100b4d6b408e69b919
[ "MIT" ]
permissive
oldtvcf/picoin_v1.1
344965b850d24fdeab55070000394d2890763c0c
bd22257838d0dbc66c3fe5ad7a2c26254a97d10b
refs/heads/master
2021-06-14T15:20:36.052423
2017-04-21T20:08:57
2017-04-21T20:08:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,282
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> #include "base58.h" #include "bitcoinrpc.h" #include "txdb.h" #include "init.h" #include "main.h" #include "net.h" #include "wallet.h" using namespace std; using namespace boost; using namespace boost::assign; using namespace json_spirit; void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out, bool fIncludeHex) { txnouttype type; vector<CTxDestination> addresses; int nRequired; out.push_back(Pair("asm", scriptPubKey.ToString())); if (fIncludeHex) out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end()))); if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) { out.push_back(Pair("type", GetTxnOutputType(TX_NONSTANDARD))); return; } out.push_back(Pair("reqSigs", nRequired)); out.push_back(Pair("type", GetTxnOutputType(type))); Array a; BOOST_FOREACH(const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); out.push_back(Pair("addresses", a)); } void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry) { entry.push_back(Pair("txid", tx.GetHash().GetHex())); entry.push_back(Pair("version", tx.nVersion)); entry.push_back(Pair("time", (boost::int64_t)tx.nTime)); entry.push_back(Pair("locktime", (boost::int64_t)tx.nLockTime)); Array vin; BOOST_FOREACH(const CTxIn& txin, tx.vin) { Object in; if (tx.IsCoinBase()) in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); else { in.push_back(Pair("txid", txin.prevout.hash.GetHex())); in.push_back(Pair("vout", (boost::int64_t)txin.prevout.n)); Object o; o.push_back(Pair("asm", txin.scriptSig.ToString())); o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); in.push_back(Pair("scriptSig", o)); } in.push_back(Pair("sequence", (boost::int64_t)txin.nSequence)); vin.push_back(in); } entry.push_back(Pair("vin", vin)); Array vout; for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; Object out; out.push_back(Pair("value", ValueFromAmount(txout.nValue))); out.push_back(Pair("n", (boost::int64_t)i)); Object o; ScriptPubKeyToJSON(txout.scriptPubKey, o, false); out.push_back(Pair("scriptPubKey", o)); vout.push_back(out); } entry.push_back(Pair("vout", vout)); if (hashBlock != 0) { entry.push_back(Pair("blockhash", hashBlock.GetHex())); map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) { entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight)); entry.push_back(Pair("time", (boost::int64_t)pindex->nTime)); entry.push_back(Pair("blocktime", (boost::int64_t)pindex->nTime)); } else entry.push_back(Pair("confirmations", 0)); } } } Value getrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getrawtransaction <txid> [verbose=0]\n" "If verbose=0, returns a string that is\n" "serialized, hex-encoded data for <txid>.\n" "If verbose is non-zero, returns an Object\n" "with information about <txid>."); uint256 hash; hash.SetHex(params[0].get_str()); bool fVerbose = false; if (params.size() > 1) fVerbose = (params[1].get_int() != 0); CTransaction tx; uint256 hashBlock = 0; if (!GetTransaction(hash, tx, hashBlock)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction"); CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; string strHex = HexStr(ssTx.begin(), ssTx.end()); if (!fVerbose) return strHex; Object result; result.push_back(Pair("hex", strHex)); TxToJSON(tx, hashBlock, result); return result; } Value listunspent(const Array& params, bool fHelp) { if (fHelp || params.size() > 3) throw runtime_error( "listunspent [minconf=1] [maxconf=9999999] [\"address\",...]\n" "Returns array of unspent transaction outputs\n" "with between minconf and maxconf (inclusive) confirmations.\n" "Optionally filtered to only include txouts paid to specified addresses.\n" "Results are an array of Objects, each of which has:\n" "{txid, vout, scriptPubKey, amount, confirmations}"); RPCTypeCheck(params, list_of(int_type)(int_type)(array_type)); int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); int nMaxDepth = 9999999; if (params.size() > 1) nMaxDepth = params[1].get_int(); set<CBitcoinAddress> setAddress; if (params.size() > 2) { Array inputs = params[2].get_array(); BOOST_FOREACH(Value& input, inputs) { CBitcoinAddress address(input.get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid picoin address: ")+input.get_str()); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+input.get_str()); setAddress.insert(address); } } Array results; vector<COutput> vecOutputs; pwalletMain->AvailableCoins(vecOutputs, false); BOOST_FOREACH(const COutput& out, vecOutputs) { if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth) continue; if(setAddress.size()) { CTxDestination address; if(!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) continue; if (!setAddress.count(address)) continue; } int64_t nValue = out.tx->vout[out.i].nValue; const CScript& pk = out.tx->vout[out.i].scriptPubKey; Object entry; entry.push_back(Pair("txid", out.tx->GetHash().GetHex())); entry.push_back(Pair("vout", out.i)); CTxDestination address; if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) { entry.push_back(Pair("address", CBitcoinAddress(address).ToString())); if (pwalletMain->mapAddressBook.count(address)) entry.push_back(Pair("account", pwalletMain->mapAddressBook[address])); } entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end()))); entry.push_back(Pair("amount",ValueFromAmount(nValue))); entry.push_back(Pair("confirmations",out.nDepth)); results.push_back(entry); } return results; } Value createrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "createrawtransaction [{\"txid\":txid,\"vout\":n},...] {address:amount,...}\n" "Create a transaction spending given inputs\n" "(array of objects containing transaction id and output number),\n" "sending to given address(es).\n" "Returns hex-encoded raw transaction.\n" "Note that the transaction's inputs are not signed, and\n" "it is not stored in the wallet or transmitted to the network."); RPCTypeCheck(params, list_of(array_type)(obj_type)); Array inputs = params[0].get_array(); Object sendTo = params[1].get_obj(); CTransaction rawTx; BOOST_FOREACH(Value& input, inputs) { const Object& o = input.get_obj(); const Value& txid_v = find_value(o, "txid"); if (txid_v.type() != str_type) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing txid key"); string txid = txid_v.get_str(); if (!IsHex(txid)) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid"); const Value& vout_v = find_value(o, "vout"); if (vout_v.type() != int_type) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key"); int nOutput = vout_v.get_int(); if (nOutput < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive"); CTxIn in(COutPoint(uint256(txid), nOutput)); rawTx.vin.push_back(in); } set<CBitcoinAddress> setAddress; BOOST_FOREACH(const Pair& s, sendTo) { CBitcoinAddress address(s.name_); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid picoin address: ")+s.name_); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_); setAddress.insert(address); CScript scriptPubKey; scriptPubKey.SetDestination(address.Get()); int64_t nAmount = AmountFromValue(s.value_); CTxOut out(nAmount, scriptPubKey); rawTx.vout.push_back(out); } CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << rawTx; return HexStr(ss.begin(), ss.end()); } Value decoderawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "decoderawtransaction <hex string>\n" "Return a JSON object representing the serialized, hex-encoded transaction."); RPCTypeCheck(params, list_of(str_type)); vector<unsigned char> txData(ParseHex(params[0].get_str())); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); CTransaction tx; try { ssData >> tx; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } Object result; TxToJSON(tx, 0, result); return result; } Value decodescript(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "decodescript <hex string>\n" "Decode a hex-encoded script."); RPCTypeCheck(params, list_of(str_type)); Object r; CScript script; if (params[0].get_str().size() > 0){ vector<unsigned char> scriptData(ParseHexV(params[0], "argument")); script = CScript(scriptData.begin(), scriptData.end()); } else { // Empty scripts are valid } ScriptPubKeyToJSON(script, r, false); r.push_back(Pair("p2sh", CBitcoinAddress(script.GetID()).ToString())); return r; } Value signrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 4) throw runtime_error( "signrawtransaction <hex string> [{\"txid\":txid,\"vout\":n,\"scriptPubKey\":hex},...] [<privatekey1>,...] [sighashtype=\"ALL\"]\n" "Sign inputs for raw transaction (serialized, hex-encoded).\n" "Second optional argument (may be null) is an array of previous transaction outputs that\n" "this transaction depends on but may not yet be in the blockchain.\n" "Third optional argument (may be null) is an array of base58-encoded private\n" "keys that, if given, will be the only keys used to sign the transaction.\n" "Fourth optional argument is a string that is one of six values; ALL, NONE, SINGLE or\n" "ALL|ANYONECANPAY, NONE|ANYONECANPAY, SINGLE|ANYONECANPAY.\n" "Returns json object with keys:\n" " hex : raw transaction with signature(s) (hex-encoded string)\n" " complete : 1 if transaction has a complete set of signature (0 if not)" + HelpRequiringPassphrase()); RPCTypeCheck(params, list_of(str_type)(array_type)(array_type)(str_type), true); vector<unsigned char> txData(ParseHex(params[0].get_str())); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); vector<CTransaction> txVariants; while (!ssData.empty()) { try { CTransaction tx; ssData >> tx; txVariants.push_back(tx); } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } } if (txVariants.empty()) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction"); // mergedTx will end up with all the signatures; it // starts as a clone of the rawtx: CTransaction mergedTx(txVariants[0]); bool fComplete = true; // Fetch previous transactions (inputs): map<COutPoint, CScript> mapPrevOut; for (unsigned int i = 0; i < mergedTx.vin.size(); i++) { CTransaction tempTx; MapPrevTx mapPrevTx; CTxDB txdb("r"); map<uint256, CTxIndex> unused; bool fInvalid; // FetchInputs aborts on failure, so we go one at a time. tempTx.vin.push_back(mergedTx.vin[i]); tempTx.FetchInputs(txdb, unused, false, false, mapPrevTx, fInvalid); // Copy results into mapPrevOut: BOOST_FOREACH(const CTxIn& txin, tempTx.vin) { const uint256& prevHash = txin.prevout.hash; if (mapPrevTx.count(prevHash) && mapPrevTx[prevHash].second.vout.size()>txin.prevout.n) mapPrevOut[txin.prevout] = mapPrevTx[prevHash].second.vout[txin.prevout.n].scriptPubKey; } } // Add previous txouts given in the RPC call: if (params.size() > 1 && params[1].type() != null_type) { Array prevTxs = params[1].get_array(); BOOST_FOREACH(Value& p, prevTxs) { if (p.type() != obj_type) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}"); Object prevOut = p.get_obj(); RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type)); string txidHex = find_value(prevOut, "txid").get_str(); if (!IsHex(txidHex)) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "txid must be hexadecimal"); uint256 txid; txid.SetHex(txidHex); int nOut = find_value(prevOut, "vout").get_int(); if (nOut < 0) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive"); string pkHex = find_value(prevOut, "scriptPubKey").get_str(); if (!IsHex(pkHex)) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "scriptPubKey must be hexadecimal"); vector<unsigned char> pkData(ParseHex(pkHex)); CScript scriptPubKey(pkData.begin(), pkData.end()); COutPoint outpoint(txid, nOut); if (mapPrevOut.count(outpoint)) { // Complain if scriptPubKey doesn't match if (mapPrevOut[outpoint] != scriptPubKey) { string err("Previous output scriptPubKey mismatch:\n"); err = err + mapPrevOut[outpoint].ToString() + "\nvs:\n"+ scriptPubKey.ToString(); throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err); } } else mapPrevOut[outpoint] = scriptPubKey; } } bool fGivenKeys = false; CBasicKeyStore tempKeystore; if (params.size() > 2 && params[2].type() != null_type) { fGivenKeys = true; Array keys = params[2].get_array(); BOOST_FOREACH(Value k, keys) { CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(k.get_str()); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY,"Invalid private key"); CKey key; bool fCompressed; CSecret secret = vchSecret.GetSecret(fCompressed); key.SetSecret(secret, fCompressed); tempKeystore.AddKey(key); } } else EnsureWalletIsUnlocked(); const CKeyStore& keystore = (fGivenKeys ? tempKeystore : *pwalletMain); int nHashType = SIGHASH_ALL; if (params.size() > 3 && params[3].type() != null_type) { static map<string, int> mapSigHashValues = boost::assign::map_list_of (string("ALL"), int(SIGHASH_ALL)) (string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)) (string("NONE"), int(SIGHASH_NONE)) (string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)) (string("SINGLE"), int(SIGHASH_SINGLE)) (string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)) ; string strHashType = params[3].get_str(); if (mapSigHashValues.count(strHashType)) nHashType = mapSigHashValues[strHashType]; else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param"); } bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE); // Sign what we can: for (unsigned int i = 0; i < mergedTx.vin.size(); i++) { CTxIn& txin = mergedTx.vin[i]; if (mapPrevOut.count(txin.prevout) == 0) { fComplete = false; continue; } const CScript& prevPubKey = mapPrevOut[txin.prevout]; txin.scriptSig.clear(); // Only sign SIGHASH_SINGLE if there's a corresponding output: if (!fHashSingle || (i < mergedTx.vout.size())) SignSignature(keystore, prevPubKey, mergedTx, i, nHashType); // ... and merge in other signatures: BOOST_FOREACH(const CTransaction& txv, txVariants) { txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig); } if (!VerifyScript(txin.scriptSig, prevPubKey, mergedTx, i, 0)) fComplete = false; } Object result; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << mergedTx; result.push_back(Pair("hex", HexStr(ssTx.begin(), ssTx.end()))); result.push_back(Pair("complete", fComplete)); return result; } Value sendrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1) throw runtime_error( "sendrawtransaction <hex string>\n" "Submits raw transaction (serialized, hex-encoded) to local node and network."); RPCTypeCheck(params, list_of(str_type)); // parse hex string from parameter vector<unsigned char> txData(ParseHex(params[0].get_str())); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); CTransaction tx; // deserialize binary data stream try { ssData >> tx; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } uint256 hashTx = tx.GetHash(); // See if the transaction is already in a block // or in the memory pool: CTransaction existingTx; uint256 hashBlock = 0; if (GetTransaction(hashTx, existingTx, hashBlock)) { if (hashBlock != 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("transaction already in block ")+hashBlock.GetHex()); // Not in block, but already in the memory pool; will drop // through to re-relay it. } else { // push to local node CTxDB txdb("r"); if (!tx.AcceptToMemoryPool(txdb)) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX rejected"); SyncWithWallets(tx, NULL, true); } RelayTransaction(tx, hashTx); return hashTx.GetHex(); }
[ "dev@picoin.club" ]
dev@picoin.club
b416477a6c2c8d6ca89418b764df0f3203f4da25
ef4d8379631df7ecd9c277ac5c1b329493c0632e
/docs/prototype/Arduino code/Adafruit_AM2315.cpp
183088ff062cf55c9d489e5139da55a079d14651
[]
no_license
CollinHeist/CropTop
c1f2139acc0f57d4235fdc1c198561b2778027da
cf3ad0784ff3e101281359385d09521089f6c9e9
refs/heads/master
2020-12-14T04:03:10.557049
2020-06-23T02:33:41
2020-06-23T02:33:41
234,627,746
1
1
null
2020-01-17T20:08:58
2020-01-17T20:08:58
null
UTF-8
C++
false
false
66,598
cpp
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <link rel="dns-prefetch" href="https://assets-cdn.github.com"> <link rel="dns-prefetch" href="https://avatars0.githubusercontent.com"> <link rel="dns-prefetch" href="https://avatars1.githubusercontent.com"> <link rel="dns-prefetch" href="https://avatars2.githubusercontent.com"> <link rel="dns-prefetch" href="https://avatars3.githubusercontent.com"> <link rel="dns-prefetch" href="https://github-cloud.s3.amazonaws.com"> <link rel="dns-prefetch" href="https://user-images.githubusercontent.com/"> <link crossorigin="anonymous" media="all" integrity="sha512-qQ+v+W1uJYfDMrQ/cwCVI+AGTsn1yi4rCU6KX45obe52BoF+WiHNeQ11u63iJA05vyivY57xNbhAsyK4/j1ZIQ==" rel="stylesheet" href="https://assets-cdn.github.com/assets/frameworks-01356238c65ce56a395237b592b58668.css" /> <link crossorigin="anonymous" media="all" integrity="sha512-mTmc5Z+PoIyUZZ2BXwFjpO02bzaP6OezYkRcnMIepBh5TIXbLOk1bc/ArdTJoVRKlzDQnR6xuiy2UcTm0Qhvqg==" rel="stylesheet" href="https://assets-cdn.github.com/assets/github-a88c4d0252c1695d3c969e68dd61d1f9.css" /> <link crossorigin="anonymous" media="all" integrity="sha512-2jE+5s+6LV2ckEshC+YTwb0A/IhES9iLMcwfkkybRMMGemXcEjAx8wdd2ZbbVr1dYBJt+fkCaR+UvXiybFr/sA==" rel="stylesheet" href="https://assets-cdn.github.com/assets/site-99075769314a73391cea9aa2907a29f9.css" /> <meta name="viewport" content="width=device-width"> <title>stalk-pusher/Adafruit_AM2315.cpp at master · tcl326/stalk-pusher · GitHub</title> <meta name="description" content="A device that aids crop plant breeders to more accurately predict plant strength"> <link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="GitHub"> <link rel="fluid-icon" href="https://github.com/fluidicon.png" title="GitHub"> <meta property="fb:app_id" content="1401488693436528"> <meta property="og:image" content="https://avatars1.githubusercontent.com/u/11898872?s=400&amp;v=4" /><meta property="og:site_name" content="GitHub" /><meta property="og:type" content="object" /><meta property="og:title" content="tcl326/stalk-pusher" /><meta property="og:url" content="https://github.com/tcl326/stalk-pusher" /><meta property="og:description" content="stalk-pusher - A device that aids crop plant breeders to more accurately predict plant strength" /> <link rel="assets" href="https://assets-cdn.github.com/"> <meta name="pjax-timeout" content="1000"> <meta name="request-id" content="EC12:1E4F:9EF72A:EDCA4B:5B6B21A2" data-pjax-transient> <meta name="selected-link" value="repo_source" data-pjax-transient> <meta name="google-site-verification" content="KT5gs8h0wvaagLKAVWq8bbeNwnZZK1r1XQysX3xurLU"> <meta name="google-site-verification" content="ZzhVyEFwb7w3e0-uOTltm8Jsck2F5StVihD0exw2fsA"> <meta name="google-site-verification" content="GXs5KoUUkNCoaAZn7wPN-t01Pywp9M3sEjnt_3_ZWPc"> <meta name="google-analytics" content="UA-3769691-2"> <meta name="octolytics-host" content="collector.githubapp.com" /><meta name="octolytics-app-id" content="github" /><meta name="octolytics-event-url" content="https://collector.githubapp.com/github-external/browser_event" /><meta name="octolytics-dimension-request_id" content="EC12:1E4F:9EF72A:EDCA4B:5B6B21A2" /><meta name="octolytics-dimension-region_edge" content="sea" /><meta name="octolytics-dimension-region_render" content="iad" /> <meta name="analytics-location" content="/&lt;user-name&gt;/&lt;repo-name&gt;/blob/show" data-pjax-transient="true" /> <meta class="js-ga-set" name="dimension1" content="Logged Out"> <meta name="hostname" content="github.com"> <meta name="user-login" content=""> <meta name="expected-hostname" content="github.com"> <meta name="js-proxy-site-detection-payload" content="N2JlMmE3Njk3MjhlZTgyOGVjM2FmNzU4NjFlODgzNjU4ODlhYTA4OGU3ZTU4Nzc2ZmE4ZTY0NGEzNmFhNWFmZnx7InJlbW90ZV9hZGRyZXNzIjoiMTI5LjEwMS4yMjEuMTA1IiwicmVxdWVzdF9pZCI6IkVDMTI6MUU0Rjo5RUY3MkE6RURDQTRCOjVCNkIyMUEyIiwidGltZXN0YW1wIjoxNTMzNzQ3NjIyLCJob3N0IjoiZ2l0aHViLmNvbSJ9"> <meta name="enabled-features" content="DASHBOARD_V2_LAYOUT_OPT_IN,EXPLORE_DISCOVER_REPOSITORIES,UNIVERSE_BANNER,FREE_TRIALS,MARKETPLACE_INSIGHTS,MARKETPLACE_PLAN_RESTRICTION_EDITOR,MARKETPLACE_SEARCH,MARKETPLACE_INSIGHTS_CONVERSION_PERCENTAGES"> <meta name="html-safe-nonce" content="713af97731f39cbe5d9479bec9f5917859444f1b"> <meta http-equiv="x-pjax-version" content="b5bc1916b3fe252021d07080b7d65a0b"> <link href="https://github.com/tcl326/stalk-pusher/commits/master.atom" rel="alternate" title="Recent Commits to stalk-pusher:master" type="application/atom+xml"> <meta name="go-import" content="github.com/tcl326/stalk-pusher git https://github.com/tcl326/stalk-pusher.git"> <meta name="octolytics-dimension-user_id" content="11898872" /><meta name="octolytics-dimension-user_login" content="tcl326" /><meta name="octolytics-dimension-repository_id" content="93379374" /><meta name="octolytics-dimension-repository_nwo" content="tcl326/stalk-pusher" /><meta name="octolytics-dimension-repository_public" content="true" /><meta name="octolytics-dimension-repository_is_fork" content="false" /><meta name="octolytics-dimension-repository_network_root_id" content="93379374" /><meta name="octolytics-dimension-repository_network_root_nwo" content="tcl326/stalk-pusher" /><meta name="octolytics-dimension-repository_explore_github_marketplace_ci_cta_shown" content="false" /> <link rel="canonical" href="https://github.com/tcl326/stalk-pusher/blob/master/hardware/stalkPusher/Adafruit_AM2315.cpp" data-pjax-transient> <meta name="browser-stats-url" content="https://api.github.com/_private/browser/stats"> <meta name="browser-errors-url" content="https://api.github.com/_private/browser/errors"> <link rel="mask-icon" href="https://assets-cdn.github.com/pinned-octocat.svg" color="#000000"> <link rel="icon" type="image/x-icon" class="js-site-favicon" href="https://assets-cdn.github.com/favicon.ico"> <meta name="theme-color" content="#1e2327"> <meta name="u2f-support" content="true"> <link rel="manifest" href="/manifest.json" crossOrigin="use-credentials"> </head> <body class="logged-out env-production page-blob"> <div class="position-relative js-header-wrapper "> <a href="#start-of-content" tabindex="1" class="px-2 py-4 bg-blue text-white show-on-focus js-skip-to-content">Skip to content</a> <div id="js-pjax-loader-bar" class="pjax-loader-bar"><div class="progress"></div></div> <header class="Header header-logged-out position-relative f4 py-3" role="banner" > <div class="container-lg d-flex px-3"> <div class="d-flex flex-justify-between flex-items-center"> <a class="header-logo-invertocat my-0" href="https://github.com/" aria-label="Homepage" data-ga-click="(Logged out) Header, go to homepage, icon:logo-wordmark; experiment:site_header_dropdowns; group:control"> <svg height="32" class="octicon octicon-mark-github" viewBox="0 0 16 16" version="1.1" width="32" aria-hidden="true"><path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"/></svg> </a> </div> <div class="HeaderMenu d-flex flex-justify-between flex-auto"> <nav class="mt-0"> <ul class="d-flex list-style-none"> <li class="ml-2"> <a class="js-selected-navigation-item HeaderNavlink px-0 py-2 m-0" data-ga-click="Header, click, Nav menu - item:features; experiment:site_header_dropdowns; group:control" data-selected-links="/features /features/project-management /features/code-review /features/project-management /features/integrations /features" href="/features"> Features </a> </li> <li class="ml-4"> <a class="js-selected-navigation-item HeaderNavlink px-0 py-2 m-0" data-ga-click="Header, click, Nav menu - item:business; experiment:site_header_dropdowns; group:control" data-selected-links="/business /business/security /business/customers /business" href="/business"> Business </a> </li> <li class="ml-4"> <a class="js-selected-navigation-item HeaderNavlink px-0 py-2 m-0" data-ga-click="Header, click, Nav menu - item:explore; experiment:site_header_dropdowns; group:control" data-selected-links="/explore /trending /trending/developers /integrations /integrations/feature/code /integrations/feature/collaborate /integrations/feature/ship showcases showcases_search showcases_landing /explore" href="/explore"> Explore </a> </li> <li class="ml-4"> <a class="js-selected-navigation-item HeaderNavlink px-0 py-2 m-0" data-ga-click="Header, click, Nav menu - item:marketplace; experiment:site_header_dropdowns; group:control" data-selected-links=" /marketplace" href="/marketplace"> Marketplace </a> </li> <li class="ml-4"> <a class="js-selected-navigation-item HeaderNavlink px-0 py-2 m-0" data-ga-click="Header, click, Nav menu - item:pricing; experiment:site_header_dropdowns; group:control" data-selected-links="/pricing /pricing/developer /pricing/team /pricing/business-hosted /pricing/business-enterprise /pricing" href="/pricing"> Pricing </a> </li> </ul> </nav> <div class="d-flex"> <div class="d-lg-flex flex-items-center mr-3"> <div class="header-search scoped-search site-scoped-search js-site-search position-relative js-jump-to" role="search combobox" aria-owns="jump-to-results" aria-label="Search or jump to" aria-haspopup="listbox" aria-expanded="true" > <div class="position-relative"> <!-- '"` --><!-- </textarea></xmp> --></option></form><form class="js-site-search-form" data-scope-type="Repository" data-scope-id="93379374" data-scoped-search-url="/tcl326/stalk-pusher/search" data-unscoped-search-url="/search" action="/tcl326/stalk-pusher/search" accept-charset="UTF-8" method="get"><input name="utf8" type="hidden" value="&#x2713;" /> <label class="form-control header-search-wrapper header-search-wrapper-jump-to position-relative d-flex flex-justify-between flex-items-center js-chromeless-input-container"> <input type="text" class="form-control header-search-input jump-to-field js-jump-to-field js-site-search-focus js-site-search-field is-clearable" data-hotkey="s,/" name="q" value="" placeholder="Search" data-unscoped-placeholder="Search GitHub" data-scoped-placeholder="Search" autocapitalize="off" aria-autocomplete="list" aria-controls="jump-to-results" data-jump-to-suggestions-path="/_graphql/GetSuggestedNavigationDestinations#csrf-token=FWtFDmON+EfuHoKJhm9LezznSKG9vpVPP83xnwBbby71kK8QdHuXIhS6748CDKQzlqNuSQQ5asC0zm1y+62KJA==" spellcheck="false" autocomplete="off" > <input type="hidden" class="js-site-search-type-field" name="type" > <img src="https://assets-cdn.github.com/images/search-shortcut-hint.svg" alt="" class="mr-2 header-search-key-slash"> <div class="Box position-absolute overflow-hidden d-none jump-to-suggestions js-jump-to-suggestions-container"> <ul class="d-none js-jump-to-suggestions-template-container"> <li class="d-flex flex-justify-start flex-items-center p-0 f5 navigation-item js-navigation-item"> <a tabindex="-1" class="no-underline d-flex flex-auto flex-items-center p-2 jump-to-suggestions-path js-jump-to-suggestion-path js-navigation-open" href=""> <div class="jump-to-octicon js-jump-to-octicon mr-2 text-center d-none"></div> <img class="avatar mr-2 flex-shrink-0 js-jump-to-suggestion-avatar" alt="" aria-label="Team" src="" width="28" height="28"> <div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div> <div class="border rounded-1 flex-shrink-0 bg-gray px-1 text-gray-light ml-1 f6 d-none js-jump-to-badge-search"> <span class="js-jump-to-badge-search-text-default d-none" aria-label="in this repository"> In this repository </span> <span class="js-jump-to-badge-search-text-global d-none" aria-label="in all of GitHub"> All GitHub </span> <span aria-hidden="true" class="d-inline-block ml-1 v-align-middle">↵</span> </div> <div aria-hidden="true" class="border rounded-1 flex-shrink-0 bg-gray px-1 text-gray-light ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span class="d-inline-block ml-1 v-align-middle">↵</span> </div> </a> </li> <svg height="16" width="16" class="octicon octicon-repo flex-shrink-0 js-jump-to-repo-octicon-template" title="Repository" aria-label="Repository" viewBox="0 0 12 16" version="1.1" role="img"><path fill-rule="evenodd" d="M4 9H3V8h1v1zm0-3H3v1h1V6zm0-2H3v1h1V4zm0-2H3v1h1V2zm8-1v12c0 .55-.45 1-1 1H6v2l-1.5-1.5L3 16v-2H1c-.55 0-1-.45-1-1V1c0-.55.45-1 1-1h10c.55 0 1 .45 1 1zm-1 10H1v2h2v-1h3v1h5v-2zm0-10H2v9h9V1z"/></svg> <svg height="16" width="16" class="octicon octicon-project flex-shrink-0 js-jump-to-project-octicon-template" title="Project" aria-label="Project" viewBox="0 0 15 16" version="1.1" role="img"><path fill-rule="evenodd" d="M10 12h3V2h-3v10zm-4-2h3V2H6v8zm-4 4h3V2H2v12zm-1 1h13V1H1v14zM14 0H1a1 1 0 0 0-1 1v14a1 1 0 0 0 1 1h13a1 1 0 0 0 1-1V1a1 1 0 0 0-1-1z"/></svg> <svg height="16" width="16" class="octicon octicon-search flex-shrink-0 js-jump-to-search-octicon-template" title="Search" aria-label="Search" viewBox="0 0 16 16" version="1.1" role="img"><path fill-rule="evenodd" d="M15.7 13.3l-3.81-3.83A5.93 5.93 0 0 0 13 6c0-3.31-2.69-6-6-6S1 2.69 1 6s2.69 6 6 6c1.3 0 2.48-.41 3.47-1.11l3.83 3.81c.19.2.45.3.7.3.25 0 .52-.09.7-.3a.996.996 0 0 0 0-1.41v.01zM7 10.7c-2.59 0-4.7-2.11-4.7-4.7 0-2.59 2.11-4.7 4.7-4.7 2.59 0 4.7 2.11 4.7 4.7 0 2.59-2.11 4.7-4.7 4.7z"/></svg> </ul> <ul class="d-none js-jump-to-no-results-template-container"> <li class="d-flex flex-justify-center flex-items-center p-3 f5 d-none"> <span class="text-gray">No suggested jump to results</span> </li> </ul> <ul id="jump-to-results" class="js-navigation-container jump-to-suggestions-results-container js-jump-to-suggestions-results-container" > <li class="d-flex flex-justify-center flex-items-center p-0 f5"> <img src="https://assets-cdn.github.com/images/spinners/octocat-spinner-128.gif" alt="Octocat Spinner Icon" class="m-2" width="28"> </li> </ul> </div> </label> </form> </div> </div> </div> <span class="d-inline-block"> <div class="HeaderNavlink px-0 py-2 m-0"> <a class="text-bold text-white no-underline" href="/login?return_to=%2Ftcl326%2Fstalk-pusher%2Fblob%2Fmaster%2Fhardware%2FstalkPusher%2FAdafruit_AM2315.cpp" data-ga-click="(Logged out) Header, clicked Sign in, text:sign-in; experiment:site_header_dropdowns; group:control">Sign in</a> <span class="text-gray">or</span> <a class="text-bold text-white no-underline" href="/join?source=header-repo" data-ga-click="(Logged out) Header, clicked Sign up, text:sign-up; experiment:site_header_dropdowns; group:control">Sign up</a> </div> </span> </div> </div> </div> </header> </div> <div id="start-of-content" class="show-on-focus"></div> <div id="js-flash-container"> </div> <div role="main" class="application-main "> <div itemscope itemtype="http://schema.org/SoftwareSourceCode" class=""> <div id="js-repo-pjax-container" data-pjax-container > <div class="pagehead repohead instapaper_ignore readability-menu experiment-repo-nav "> <div class="repohead-details-container clearfix container"> <ul class="pagehead-actions"> <li> <a href="/login?return_to=%2Ftcl326%2Fstalk-pusher" class="btn btn-sm btn-with-count tooltipped tooltipped-n" aria-label="You must be signed in to watch a repository" rel="nofollow"> <svg class="octicon octicon-eye v-align-text-bottom" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8.06 2C3 2 0 8 0 8s3 6 8.06 6C13 14 16 8 16 8s-3-6-7.94-6zM8 12c-2.2 0-4-1.78-4-4 0-2.2 1.8-4 4-4 2.22 0 4 1.8 4 4 0 2.22-1.78 4-4 4zm2-4c0 1.11-.89 2-2 2-1.11 0-2-.89-2-2 0-1.11.89-2 2-2 1.11 0 2 .89 2 2z"/></svg> Watch </a> <a class="social-count" href="/tcl326/stalk-pusher/watchers" aria-label="2 users are watching this repository"> 2 </a> </li> <li> <a href="/login?return_to=%2Ftcl326%2Fstalk-pusher" class="btn btn-sm btn-with-count tooltipped tooltipped-n" aria-label="You must be signed in to star a repository" rel="nofollow"> <svg class="octicon octicon-star v-align-text-bottom" viewBox="0 0 14 16" version="1.1" width="14" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M14 6l-4.9-.64L7 1 4.9 5.36 0 6l3.6 3.26L2.67 14 7 11.67 11.33 14l-.93-4.74L14 6z"/></svg> Star </a> <a class="social-count js-social-count" href="/tcl326/stalk-pusher/stargazers" aria-label="0 users starred this repository"> 0 </a> </li> <li> <a href="/login?return_to=%2Ftcl326%2Fstalk-pusher" class="btn btn-sm btn-with-count tooltipped tooltipped-n" aria-label="You must be signed in to fork a repository" rel="nofollow"> <svg class="octicon octicon-repo-forked v-align-text-bottom" viewBox="0 0 10 16" version="1.1" width="10" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8 1a1.993 1.993 0 0 0-1 3.72V6L5 8 3 6V4.72A1.993 1.993 0 0 0 2 1a1.993 1.993 0 0 0-1 3.72V6.5l3 3v1.78A1.993 1.993 0 0 0 5 15a1.993 1.993 0 0 0 1-3.72V9.5l3-3V4.72A1.993 1.993 0 0 0 8 1zM2 4.2C1.34 4.2.8 3.65.8 3c0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm3 10c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm3-10c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2z"/></svg> Fork </a> <a href="/tcl326/stalk-pusher/network/members" class="social-count" aria-label="0 users forked this repository"> 0 </a> </li> </ul> <h1 class="public "> <svg class="octicon octicon-repo" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M4 9H3V8h1v1zm0-3H3v1h1V6zm0-2H3v1h1V4zm0-2H3v1h1V2zm8-1v12c0 .55-.45 1-1 1H6v2l-1.5-1.5L3 16v-2H1c-.55 0-1-.45-1-1V1c0-.55.45-1 1-1h10c.55 0 1 .45 1 1zm-1 10H1v2h2v-1h3v1h5v-2zm0-10H2v9h9V1z"/></svg> <span class="author" itemprop="author"><a class="url fn" rel="author" href="/tcl326">tcl326</a></span><!-- --><span class="path-divider">/</span><!-- --><strong itemprop="name"><a data-pjax="#js-repo-pjax-container" href="/tcl326/stalk-pusher">stalk-pusher</a></strong> </h1> </div> <nav class="reponav js-repo-nav js-sidenav-container-pjax container" itemscope itemtype="http://schema.org/BreadcrumbList" role="navigation" data-pjax="#js-repo-pjax-container"> <span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement"> <a class="js-selected-navigation-item selected reponav-item" itemprop="url" data-hotkey="g c" data-selected-links="repo_source repo_downloads repo_commits repo_releases repo_tags repo_branches repo_packages /tcl326/stalk-pusher" href="/tcl326/stalk-pusher"> <svg class="octicon octicon-code" viewBox="0 0 14 16" version="1.1" width="14" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M9.5 3L8 4.5 11.5 8 8 11.5 9.5 13 14 8 9.5 3zm-5 0L0 8l4.5 5L6 11.5 2.5 8 6 4.5 4.5 3z"/></svg> <span itemprop="name">Code</span> <meta itemprop="position" content="1"> </a> </span> <span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement"> <a itemprop="url" data-hotkey="g i" class="js-selected-navigation-item reponav-item" data-selected-links="repo_issues repo_labels repo_milestones /tcl326/stalk-pusher/issues" href="/tcl326/stalk-pusher/issues"> <svg class="octicon octicon-issue-opened" viewBox="0 0 14 16" version="1.1" width="14" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7 2.3c3.14 0 5.7 2.56 5.7 5.7s-2.56 5.7-5.7 5.7A5.71 5.71 0 0 1 1.3 8c0-3.14 2.56-5.7 5.7-5.7zM7 1C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7-3.14-7-7-7zm1 3H6v5h2V4zm0 6H6v2h2v-2z"/></svg> <span itemprop="name">Issues</span> <span class="Counter">0</span> <meta itemprop="position" content="2"> </a> </span> <span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement"> <a data-hotkey="g p" itemprop="url" class="js-selected-navigation-item reponav-item" data-selected-links="repo_pulls checks /tcl326/stalk-pusher/pulls" href="/tcl326/stalk-pusher/pulls"> <svg class="octicon octicon-git-pull-request" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M11 11.28V5c-.03-.78-.34-1.47-.94-2.06C9.46 2.35 8.78 2.03 8 2H7V0L4 3l3 3V4h1c.27.02.48.11.69.31.21.2.3.42.31.69v6.28A1.993 1.993 0 0 0 10 15a1.993 1.993 0 0 0 1-3.72zm-1 2.92c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zM4 3c0-1.11-.89-2-2-2a1.993 1.993 0 0 0-1 3.72v6.56A1.993 1.993 0 0 0 2 15a1.993 1.993 0 0 0 1-3.72V4.72c.59-.34 1-.98 1-1.72zm-.8 10c0 .66-.55 1.2-1.2 1.2-.65 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2zM2 4.2C1.34 4.2.8 3.65.8 3c0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2z"/></svg> <span itemprop="name">Pull requests</span> <span class="Counter">0</span> <meta itemprop="position" content="3"> </a> </span> <a data-hotkey="g b" class="js-selected-navigation-item reponav-item" data-selected-links="repo_projects new_repo_project repo_project /tcl326/stalk-pusher/projects" href="/tcl326/stalk-pusher/projects"> <svg class="octicon octicon-project" viewBox="0 0 15 16" version="1.1" width="15" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M10 12h3V2h-3v10zm-4-2h3V2H6v8zm-4 4h3V2H2v12zm-1 1h13V1H1v14zM14 0H1a1 1 0 0 0-1 1v14a1 1 0 0 0 1 1h13a1 1 0 0 0 1-1V1a1 1 0 0 0-1-1z"/></svg> Projects <span class="Counter" >0</span> </a> <a class="js-selected-navigation-item reponav-item" data-selected-links="repo_graphs repo_contributors dependency_graph pulse /tcl326/stalk-pusher/pulse" href="/tcl326/stalk-pusher/pulse"> <svg class="octicon octicon-graph" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M16 14v1H0V0h1v14h15zM5 13H3V8h2v5zm4 0H7V3h2v10zm4 0h-2V6h2v7z"/></svg> Insights </a> </nav> </div> <div class="container new-discussion-timeline experiment-repo-nav "> <div class="repository-content "> <a class="d-none js-permalink-shortcut" data-hotkey="y" href="/tcl326/stalk-pusher/blob/acc2b66b58dd11be35feca50ba6d6500d1c510dd/hardware/stalkPusher/Adafruit_AM2315.cpp">Permalink</a> <!-- blob contrib key: blob_contributors:v21:10c378d3e82708ac943eeabc4eb2aef9 --> <div class="signup-prompt-bg rounded-1"> <div class="signup-prompt p-4 text-center mb-4 rounded-1"> <div class="position-relative"> <!-- '"` --><!-- </textarea></xmp> --></option></form><form action="/site/dismiss_signup_prompt" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="&#x2713;" /><input type="hidden" name="authenticity_token" value="ysRC0bLcDXgeUi0Tcl3DMSyheMHUsYdTUjc9E7Fns/rAxymXoezDeHYjPi1/tsCiEBCot03ytIYuPx0SLOBKxQ==" /> <button type="submit" class="position-absolute top-0 right-0 btn-link link-gray" data-ga-click="(Logged out) Sign up prompt, clicked Dismiss, text:dismiss"> Dismiss </button> </form> <h3 class="pt-2">Join GitHub today</h3> <p class="col-6 mx-auto">GitHub is home to over 28 million developers working together to host and review code, manage projects, and build software together.</p> <a class="btn btn-primary" href="/join?source=prompt-blob-show" data-ga-click="(Logged out) Sign up prompt, clicked Sign up, text:sign-up">Sign up</a> </div> </div> </div> <div class="file-navigation"> <div class="select-menu branch-select-menu js-menu-container js-select-menu float-left"> <button class=" btn btn-sm select-menu-button js-menu-target css-truncate" data-hotkey="w" type="button" aria-label="Switch branches or tags" aria-expanded="false" aria-haspopup="true"> <i>Branch:</i> <span class="js-select-button css-truncate-target">master</span> </button> <div class="select-menu-modal-holder js-menu-content js-navigation-container" data-pjax> <div class="select-menu-modal"> <div class="select-menu-header"> <svg class="octicon octicon-x js-menu-close" role="img" aria-label="Close" viewBox="0 0 12 16" version="1.1" width="12" height="16"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48L7.48 8z"/></svg> <span class="select-menu-title">Switch branches/tags</span> </div> <div class="select-menu-filters"> <div class="select-menu-text-filter"> <input type="text" aria-label="Filter branches/tags" id="context-commitish-filter-field" class="form-control js-filterable-field js-navigation-enable" placeholder="Filter branches/tags"> </div> <div class="select-menu-tabs"> <ul> <li class="select-menu-tab"> <a href="#" data-tab-filter="branches" data-filter-placeholder="Filter branches/tags" class="js-select-menu-tab" role="tab">Branches</a> </li> <li class="select-menu-tab"> <a href="#" data-tab-filter="tags" data-filter-placeholder="Find a tag…" class="js-select-menu-tab" role="tab">Tags</a> </li> </ul> </div> </div> <div class="select-menu-list select-menu-tab-bucket js-select-menu-tab-bucket" data-tab-filter="branches" role="menu"> <div data-filterable-for="context-commitish-filter-field" data-filterable-type="substring"> <a class="select-menu-item js-navigation-item js-navigation-open selected" href="/tcl326/stalk-pusher/blob/master/hardware/stalkPusher/Adafruit_AM2315.cpp" data-name="master" data-skip-pjax="true" rel="nofollow"> <svg class="octicon octicon-check select-menu-item-icon" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5L12 5z"/></svg> <span class="select-menu-item-text css-truncate-target js-select-menu-filter-text"> master </span> </a> </div> <div class="select-menu-no-results">Nothing to show</div> </div> <div class="select-menu-list select-menu-tab-bucket js-select-menu-tab-bucket" data-tab-filter="tags"> <div data-filterable-for="context-commitish-filter-field" data-filterable-type="substring"> </div> <div class="select-menu-no-results">Nothing to show</div> </div> </div> </div> </div> <div class="BtnGroup float-right"> <a href="/tcl326/stalk-pusher/find/master" class="js-pjax-capture-input btn btn-sm BtnGroup-item" data-pjax data-hotkey="t"> Find file </a> <clipboard-copy for="blob-path" class="btn btn-sm BtnGroup-item"> Copy path </clipboard-copy> </div> <div id="blob-path" class="breadcrumb"> <span class="repo-root js-repo-root"><span class="js-path-segment"><a data-pjax="true" href="/tcl326/stalk-pusher"><span>stalk-pusher</span></a></span></span><span class="separator">/</span><span class="js-path-segment"><a data-pjax="true" href="/tcl326/stalk-pusher/tree/master/hardware"><span>hardware</span></a></span><span class="separator">/</span><span class="js-path-segment"><a data-pjax="true" href="/tcl326/stalk-pusher/tree/master/hardware/stalkPusher"><span>stalkPusher</span></a></span><span class="separator">/</span><strong class="final-path">Adafruit_AM2315.cpp</strong> </div> </div> <include-fragment src="/tcl326/stalk-pusher/contributors/master/hardware/stalkPusher/Adafruit_AM2315.cpp" class="commit-tease commit-loader"> <div> Fetching contributors&hellip; </div> <div class="commit-tease-contributors"> <img alt="" class="loader-loading float-left" src="https://assets-cdn.github.com/images/spinners/octocat-spinner-32-EAF2F5.gif" width="16" height="16" /> <span class="loader-error">Cannot retrieve contributors at this time</span> </div> </include-fragment> <div class="file"> <div class="file-header"> <div class="file-actions"> <div class="BtnGroup"> <a id="raw-url" class="btn btn-sm BtnGroup-item" href="/tcl326/stalk-pusher/raw/master/hardware/stalkPusher/Adafruit_AM2315.cpp">Raw</a> <a class="btn btn-sm js-update-url-with-hash BtnGroup-item" data-hotkey="b" href="/tcl326/stalk-pusher/blame/master/hardware/stalkPusher/Adafruit_AM2315.cpp">Blame</a> <a rel="nofollow" class="btn btn-sm BtnGroup-item" href="/tcl326/stalk-pusher/commits/master/hardware/stalkPusher/Adafruit_AM2315.cpp">History</a> </div> <a class="btn-octicon tooltipped tooltipped-nw" href="https://desktop.github.com" aria-label="Open this file in GitHub Desktop" data-ga-click="Repository, open with desktop, type:windows"> <svg class="octicon octicon-device-desktop" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M15 2H1c-.55 0-1 .45-1 1v9c0 .55.45 1 1 1h5.34c-.25.61-.86 1.39-2.34 2h8c-1.48-.61-2.09-1.39-2.34-2H15c.55 0 1-.45 1-1V3c0-.55-.45-1-1-1zm0 9H1V3h14v8z"/></svg> </a> <button type="button" class="btn-octicon disabled tooltipped tooltipped-nw" aria-label="You must be signed in to make or propose changes"> <svg class="octicon octicon-pencil" viewBox="0 0 14 16" version="1.1" width="14" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M0 12v3h3l8-8-3-3-8 8zm3 2H1v-2h1v1h1v1zm10.3-9.3L12 6 9 3l1.3-1.3a.996.996 0 0 1 1.41 0l1.59 1.59c.39.39.39 1.02 0 1.41z"/></svg> </button> <button type="button" class="btn-octicon btn-octicon-danger disabled tooltipped tooltipped-nw" aria-label="You must be signed in to make or propose changes"> <svg class="octicon octicon-trashcan" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M11 2H9c0-.55-.45-1-1-1H5c-.55 0-1 .45-1 1H2c-.55 0-1 .45-1 1v1c0 .55.45 1 1 1v9c0 .55.45 1 1 1h7c.55 0 1-.45 1-1V5c.55 0 1-.45 1-1V3c0-.55-.45-1-1-1zm-1 12H3V5h1v8h1V5h1v8h1V5h1v8h1V5h1v9zm1-10H2V3h9v1z"/></svg> </button> </div> <div class="file-info"> 107 lines (80 sloc) <span class="file-info-divider"></span> 2.76 KB </div> </div> <div itemprop="text" class="blob-wrapper data type-c"> <table class="highlight tab-size js-file-line-container" data-tab-size="8"> <tr> <td id="L1" class="blob-num js-line-number" data-line-number="1"></td> <td id="LC1" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">/*</span>************************************************** </span></td> </tr> <tr> <td id="L2" class="blob-num js-line-number" data-line-number="2"></td> <td id="LC2" class="blob-code blob-code-inner js-file-line"><span class="pl-c"> This is a library for the AM2315 Humidity &amp; Temp Sensor</span></td> </tr> <tr> <td id="L3" class="blob-num js-line-number" data-line-number="3"></td> <td id="LC3" class="blob-code blob-code-inner js-file-line"><span class="pl-c"></span></td> </tr> <tr> <td id="L4" class="blob-num js-line-number" data-line-number="4"></td> <td id="LC4" class="blob-code blob-code-inner js-file-line"><span class="pl-c"> Designed specifically to work with the AM2315 sensor from Adafruit</span></td> </tr> <tr> <td id="L5" class="blob-num js-line-number" data-line-number="5"></td> <td id="LC5" class="blob-code blob-code-inner js-file-line"><span class="pl-c"> ----&gt; https://www.adafruit.com/products/1293</span></td> </tr> <tr> <td id="L6" class="blob-num js-line-number" data-line-number="6"></td> <td id="LC6" class="blob-code blob-code-inner js-file-line"><span class="pl-c"></span></td> </tr> <tr> <td id="L7" class="blob-num js-line-number" data-line-number="7"></td> <td id="LC7" class="blob-code blob-code-inner js-file-line"><span class="pl-c"> These displays use I2C to communicate, 2 pins are required to </span></td> </tr> <tr> <td id="L8" class="blob-num js-line-number" data-line-number="8"></td> <td id="LC8" class="blob-code blob-code-inner js-file-line"><span class="pl-c"> interface</span></td> </tr> <tr> <td id="L9" class="blob-num js-line-number" data-line-number="9"></td> <td id="LC9" class="blob-code blob-code-inner js-file-line"><span class="pl-c"> Adafruit invests time and resources providing this open source code, </span></td> </tr> <tr> <td id="L10" class="blob-num js-line-number" data-line-number="10"></td> <td id="LC10" class="blob-code blob-code-inner js-file-line"><span class="pl-c"> please support Adafruit and open-source hardware by purchasing </span></td> </tr> <tr> <td id="L11" class="blob-num js-line-number" data-line-number="11"></td> <td id="LC11" class="blob-code blob-code-inner js-file-line"><span class="pl-c"> products from Adafruit!</span></td> </tr> <tr> <td id="L12" class="blob-num js-line-number" data-line-number="12"></td> <td id="LC12" class="blob-code blob-code-inner js-file-line"><span class="pl-c"></span></td> </tr> <tr> <td id="L13" class="blob-num js-line-number" data-line-number="13"></td> <td id="LC13" class="blob-code blob-code-inner js-file-line"><span class="pl-c"> Written by Limor Fried/Ladyada for Adafruit Industries. </span></td> </tr> <tr> <td id="L14" class="blob-num js-line-number" data-line-number="14"></td> <td id="LC14" class="blob-code blob-code-inner js-file-line"><span class="pl-c"> BSD license, all text above must be included in any redistribution</span></td> </tr> <tr> <td id="L15" class="blob-num js-line-number" data-line-number="15"></td> <td id="LC15" class="blob-code blob-code-inner js-file-line"><span class="pl-c"> ***************************************************<span class="pl-c">*/</span></span></td> </tr> <tr> <td id="L16" class="blob-num js-line-number" data-line-number="16"></td> <td id="LC16" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L17" class="blob-num js-line-number" data-line-number="17"></td> <td id="LC17" class="blob-code blob-code-inner js-file-line">#<span class="pl-k">include</span> <span class="pl-s"><span class="pl-pds">&quot;</span>Adafruit_AM2315.h<span class="pl-pds">&quot;</span></span></td> </tr> <tr> <td id="L18" class="blob-num js-line-number" data-line-number="18"></td> <td id="LC18" class="blob-code blob-code-inner js-file-line">#<span class="pl-k">if</span> defined(__AVR__)</td> </tr> <tr> <td id="L19" class="blob-num js-line-number" data-line-number="19"></td> <td id="LC19" class="blob-code blob-code-inner js-file-line"> #<span class="pl-k">include</span> <span class="pl-s"><span class="pl-pds">&lt;</span>util/delay.h<span class="pl-pds">&gt;</span></span></td> </tr> <tr> <td id="L20" class="blob-num js-line-number" data-line-number="20"></td> <td id="LC20" class="blob-code blob-code-inner js-file-line">#<span class="pl-k">endif</span></td> </tr> <tr> <td id="L21" class="blob-num js-line-number" data-line-number="21"></td> <td id="LC21" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L22" class="blob-num js-line-number" data-line-number="22"></td> <td id="LC22" class="blob-code blob-code-inner js-file-line"><span class="pl-en">Adafruit_AM2315::Adafruit_AM2315</span>() {</td> </tr> <tr> <td id="L23" class="blob-num js-line-number" data-line-number="23"></td> <td id="LC23" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L24" class="blob-num js-line-number" data-line-number="24"></td> <td id="LC24" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L25" class="blob-num js-line-number" data-line-number="25"></td> <td id="LC25" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L26" class="blob-num js-line-number" data-line-number="26"></td> <td id="LC26" class="blob-code blob-code-inner js-file-line">boolean <span class="pl-en">Adafruit_AM2315::begin</span>(<span class="pl-k">void</span>) {</td> </tr> <tr> <td id="L27" class="blob-num js-line-number" data-line-number="27"></td> <td id="LC27" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">begin</span>();</td> </tr> <tr> <td id="L28" class="blob-num js-line-number" data-line-number="28"></td> <td id="LC28" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L29" class="blob-num js-line-number" data-line-number="29"></td> <td id="LC29" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">//</span> try to read data, as a test</span></td> </tr> <tr> <td id="L30" class="blob-num js-line-number" data-line-number="30"></td> <td id="LC30" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-c1">readData</span>();</td> </tr> <tr> <td id="L31" class="blob-num js-line-number" data-line-number="31"></td> <td id="LC31" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L32" class="blob-num js-line-number" data-line-number="32"></td> <td id="LC32" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L33" class="blob-num js-line-number" data-line-number="33"></td> <td id="LC33" class="blob-code blob-code-inner js-file-line">boolean <span class="pl-en">Adafruit_AM2315::readData</span>(<span class="pl-k">void</span>) {</td> </tr> <tr> <td id="L34" class="blob-num js-line-number" data-line-number="34"></td> <td id="LC34" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">uint8_t</span> reply[<span class="pl-c1">10</span>];</td> </tr> <tr> <td id="L35" class="blob-num js-line-number" data-line-number="35"></td> <td id="LC35" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L36" class="blob-num js-line-number" data-line-number="36"></td> <td id="LC36" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">//</span> Wake up the sensor</span></td> </tr> <tr> <td id="L37" class="blob-num js-line-number" data-line-number="37"></td> <td id="LC37" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">beginTransmission</span>(AM2315_I2CADDR);</td> </tr> <tr> <td id="L38" class="blob-num js-line-number" data-line-number="38"></td> <td id="LC38" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">delay</span>(<span class="pl-c1">2</span>);</td> </tr> <tr> <td id="L39" class="blob-num js-line-number" data-line-number="39"></td> <td id="LC39" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">endTransmission</span>();</td> </tr> <tr> <td id="L40" class="blob-num js-line-number" data-line-number="40"></td> <td id="LC40" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L41" class="blob-num js-line-number" data-line-number="41"></td> <td id="LC41" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">//</span> OK lets ready!</span></td> </tr> <tr> <td id="L42" class="blob-num js-line-number" data-line-number="42"></td> <td id="LC42" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">beginTransmission</span>(AM2315_I2CADDR);</td> </tr> <tr> <td id="L43" class="blob-num js-line-number" data-line-number="43"></td> <td id="LC43" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">write</span>(AM2315_READREG);</td> </tr> <tr> <td id="L44" class="blob-num js-line-number" data-line-number="44"></td> <td id="LC44" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">write</span>(<span class="pl-c1">0x00</span>); <span class="pl-c"><span class="pl-c">//</span> start at address 0x0</span></td> </tr> <tr> <td id="L45" class="blob-num js-line-number" data-line-number="45"></td> <td id="LC45" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">write</span>(<span class="pl-c1">4</span>); <span class="pl-c"><span class="pl-c">//</span> request 4 bytes data</span></td> </tr> <tr> <td id="L46" class="blob-num js-line-number" data-line-number="46"></td> <td id="LC46" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">endTransmission</span>();</td> </tr> <tr> <td id="L47" class="blob-num js-line-number" data-line-number="47"></td> <td id="LC47" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L48" class="blob-num js-line-number" data-line-number="48"></td> <td id="LC48" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">delay</span>(<span class="pl-c1">10</span>); <span class="pl-c"><span class="pl-c">//</span> add delay between request and actual read!</span></td> </tr> <tr> <td id="L49" class="blob-num js-line-number" data-line-number="49"></td> <td id="LC49" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L50" class="blob-num js-line-number" data-line-number="50"></td> <td id="LC50" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">requestFrom</span>(AM2315_I2CADDR, <span class="pl-c1">8</span>);</td> </tr> <tr> <td id="L51" class="blob-num js-line-number" data-line-number="51"></td> <td id="LC51" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">for</span> (<span class="pl-c1">uint8_t</span> i=<span class="pl-c1">0</span>; i&lt;<span class="pl-c1">8</span>; i++) {</td> </tr> <tr> <td id="L52" class="blob-num js-line-number" data-line-number="52"></td> <td id="LC52" class="blob-code blob-code-inner js-file-line"> reply[i] = Wire.<span class="pl-c1">read</span>();</td> </tr> <tr> <td id="L53" class="blob-num js-line-number" data-line-number="53"></td> <td id="LC53" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">//</span>Serial.println(reply[i], HEX);</span></td> </tr> <tr> <td id="L54" class="blob-num js-line-number" data-line-number="54"></td> <td id="LC54" class="blob-code blob-code-inner js-file-line"> }</td> </tr> <tr> <td id="L55" class="blob-num js-line-number" data-line-number="55"></td> <td id="LC55" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L56" class="blob-num js-line-number" data-line-number="56"></td> <td id="LC56" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> (reply[<span class="pl-c1">0</span>] != AM2315_READREG) <span class="pl-k">return</span> <span class="pl-c1">false</span>;</td> </tr> <tr> <td id="L57" class="blob-num js-line-number" data-line-number="57"></td> <td id="LC57" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> (reply[<span class="pl-c1">1</span>] != <span class="pl-c1">4</span>) <span class="pl-k">return</span> <span class="pl-c1">false</span>; <span class="pl-c"><span class="pl-c">//</span> bytes req&#39;d</span></td> </tr> <tr> <td id="L58" class="blob-num js-line-number" data-line-number="58"></td> <td id="LC58" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L59" class="blob-num js-line-number" data-line-number="59"></td> <td id="LC59" class="blob-code blob-code-inner js-file-line"> humidity = reply[<span class="pl-c1">2</span>];</td> </tr> <tr> <td id="L60" class="blob-num js-line-number" data-line-number="60"></td> <td id="LC60" class="blob-code blob-code-inner js-file-line"> humidity *= <span class="pl-c1">256</span>;</td> </tr> <tr> <td id="L61" class="blob-num js-line-number" data-line-number="61"></td> <td id="LC61" class="blob-code blob-code-inner js-file-line"> humidity += reply[<span class="pl-c1">3</span>];</td> </tr> <tr> <td id="L62" class="blob-num js-line-number" data-line-number="62"></td> <td id="LC62" class="blob-code blob-code-inner js-file-line"> humidity /= <span class="pl-c1">10</span>;</td> </tr> <tr> <td id="L63" class="blob-num js-line-number" data-line-number="63"></td> <td id="LC63" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">//</span>Serial.print(&quot;H&quot;); Serial.println(humidity);</span></td> </tr> <tr> <td id="L64" class="blob-num js-line-number" data-line-number="64"></td> <td id="LC64" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L65" class="blob-num js-line-number" data-line-number="65"></td> <td id="LC65" class="blob-code blob-code-inner js-file-line"> temp = reply[<span class="pl-c1">4</span>] &amp; <span class="pl-c1">0x7F</span>;</td> </tr> <tr> <td id="L66" class="blob-num js-line-number" data-line-number="66"></td> <td id="LC66" class="blob-code blob-code-inner js-file-line"> temp *= <span class="pl-c1">256</span>;</td> </tr> <tr> <td id="L67" class="blob-num js-line-number" data-line-number="67"></td> <td id="LC67" class="blob-code blob-code-inner js-file-line"> temp += reply[<span class="pl-c1">5</span>];</td> </tr> <tr> <td id="L68" class="blob-num js-line-number" data-line-number="68"></td> <td id="LC68" class="blob-code blob-code-inner js-file-line"> temp /= <span class="pl-c1">10</span>;</td> </tr> <tr> <td id="L69" class="blob-num js-line-number" data-line-number="69"></td> <td id="LC69" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">//</span>Serial.print(&quot;T&quot;); Serial.println(temp);</span></td> </tr> <tr> <td id="L70" class="blob-num js-line-number" data-line-number="70"></td> <td id="LC70" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L71" class="blob-num js-line-number" data-line-number="71"></td> <td id="LC71" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">//</span> change sign</span></td> </tr> <tr> <td id="L72" class="blob-num js-line-number" data-line-number="72"></td> <td id="LC72" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> (reply[<span class="pl-c1">4</span>] &gt;&gt; <span class="pl-c1">7</span>) temp = -temp;</td> </tr> <tr> <td id="L73" class="blob-num js-line-number" data-line-number="73"></td> <td id="LC73" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L74" class="blob-num js-line-number" data-line-number="74"></td> <td id="LC74" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-c1">true</span>;</td> </tr> <tr> <td id="L75" class="blob-num js-line-number" data-line-number="75"></td> <td id="LC75" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L76" class="blob-num js-line-number" data-line-number="76"></td> <td id="LC76" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L77" class="blob-num js-line-number" data-line-number="77"></td> <td id="LC77" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L78" class="blob-num js-line-number" data-line-number="78"></td> <td id="LC78" class="blob-code blob-code-inner js-file-line"><span class="pl-k">float</span> <span class="pl-en">Adafruit_AM2315::readTemperature</span>(<span class="pl-k">void</span>) {</td> </tr> <tr> <td id="L79" class="blob-num js-line-number" data-line-number="79"></td> <td id="LC79" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> (! <span class="pl-c1">readData</span>()) <span class="pl-k">return</span> NAN;</td> </tr> <tr> <td id="L80" class="blob-num js-line-number" data-line-number="80"></td> <td id="LC80" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> temp;</td> </tr> <tr> <td id="L81" class="blob-num js-line-number" data-line-number="81"></td> <td id="LC81" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L82" class="blob-num js-line-number" data-line-number="82"></td> <td id="LC82" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L83" class="blob-num js-line-number" data-line-number="83"></td> <td id="LC83" class="blob-code blob-code-inner js-file-line"><span class="pl-k">float</span> <span class="pl-en">Adafruit_AM2315::readHumidity</span>(<span class="pl-k">void</span>) {</td> </tr> <tr> <td id="L84" class="blob-num js-line-number" data-line-number="84"></td> <td id="LC84" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> (! <span class="pl-c1">readData</span>()) <span class="pl-k">return</span> NAN;</td> </tr> <tr> <td id="L85" class="blob-num js-line-number" data-line-number="85"></td> <td id="LC85" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> humidity;</td> </tr> <tr> <td id="L86" class="blob-num js-line-number" data-line-number="86"></td> <td id="LC86" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L87" class="blob-num js-line-number" data-line-number="87"></td> <td id="LC87" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L88" class="blob-num js-line-number" data-line-number="88"></td> <td id="LC88" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L89" class="blob-num js-line-number" data-line-number="89"></td> <td id="LC89" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">/*</span></span></td> </tr> <tr> <td id="L90" class="blob-num js-line-number" data-line-number="90"></td> <td id="LC90" class="blob-code blob-code-inner js-file-line"><span class="pl-c"> * This method returns both temperature and humidity in a single call and using a single I2C request. </span></td> </tr> <tr> <td id="L91" class="blob-num js-line-number" data-line-number="91"></td> <td id="LC91" class="blob-code blob-code-inner js-file-line"><span class="pl-c"> *</span></td> </tr> <tr> <td id="L92" class="blob-num js-line-number" data-line-number="92"></td> <td id="LC92" class="blob-code blob-code-inner js-file-line"><span class="pl-c"> * If you want to obtain both temperature and humidity when you sample the sensor, be aware that calling </span></td> </tr> <tr> <td id="L93" class="blob-num js-line-number" data-line-number="93"></td> <td id="LC93" class="blob-code blob-code-inner js-file-line"><span class="pl-c"> * readTemperature() and readHumidity() in rapid succession may swamp the sensor and result in invalid </span></td> </tr> <tr> <td id="L94" class="blob-num js-line-number" data-line-number="94"></td> <td id="LC94" class="blob-code blob-code-inner js-file-line"><span class="pl-c"> * readingings (the AM2315 manual advisess that continuous samples must be at least 2 seconds apart).</span></td> </tr> <tr> <td id="L95" class="blob-num js-line-number" data-line-number="95"></td> <td id="LC95" class="blob-code blob-code-inner js-file-line"><span class="pl-c"> * Calling this method avoids the double I2C request.</span></td> </tr> <tr> <td id="L96" class="blob-num js-line-number" data-line-number="96"></td> <td id="LC96" class="blob-code blob-code-inner js-file-line"><span class="pl-c"> <span class="pl-c">*/</span></span></td> </tr> <tr> <td id="L97" class="blob-num js-line-number" data-line-number="97"></td> <td id="LC97" class="blob-code blob-code-inner js-file-line"><span class="pl-k">bool</span> <span class="pl-en">Adafruit_AM2315::readTemperatureAndHumidity</span>(<span class="pl-k">float</span> &amp;t, <span class="pl-k">float</span> &amp;h) {</td> </tr> <tr> <td id="L98" class="blob-num js-line-number" data-line-number="98"></td> <td id="LC98" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> (!<span class="pl-c1">readData</span>()) <span class="pl-k">return</span> <span class="pl-c1">false</span>;</td> </tr> <tr> <td id="L99" class="blob-num js-line-number" data-line-number="99"></td> <td id="LC99" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L100" class="blob-num js-line-number" data-line-number="100"></td> <td id="LC100" class="blob-code blob-code-inner js-file-line"> t = temp;</td> </tr> <tr> <td id="L101" class="blob-num js-line-number" data-line-number="101"></td> <td id="LC101" class="blob-code blob-code-inner js-file-line"> h = humidity;</td> </tr> <tr> <td id="L102" class="blob-num js-line-number" data-line-number="102"></td> <td id="LC102" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L103" class="blob-num js-line-number" data-line-number="103"></td> <td id="LC103" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-c1">true</span>;</td> </tr> <tr> <td id="L104" class="blob-num js-line-number" data-line-number="104"></td> <td id="LC104" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L105" class="blob-num js-line-number" data-line-number="105"></td> <td id="LC105" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L106" class="blob-num js-line-number" data-line-number="106"></td> <td id="LC106" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">/*</span>*******************************************************************<span class="pl-c">*/</span></span></td> </tr> </table> <details class="details-reset details-overlay BlobToolbar position-absolute js-file-line-actions dropdown d-none" aria-hidden="true"> <summary class="btn-octicon ml-0 px-2 p-0 bg-white border border-gray-dark rounded-1" aria-label="Inline file action toolbar"> <svg class="octicon octicon-kebab-horizontal" viewBox="0 0 13 16" version="1.1" width="13" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M1.5 9a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3zm5 0a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3zM13 7.5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0z"/></svg> </summary> <details-menu> <ul class="BlobToolbar-dropdown dropdown-menu dropdown-menu-se mt-2"> <li><clipboard-copy role="menuitem" class="dropdown-item" id="js-copy-lines" style="cursor:pointer;" data-original-text="Copy lines">Copy lines</clipboard-copy></li> <li><clipboard-copy role="menuitem" class="dropdown-item" id="js-copy-permalink" style="cursor:pointer;" data-original-text="Copy permalink">Copy permalink</clipboard-copy></li> <li><a class="dropdown-item js-update-url-with-hash" id="js-view-git-blame" role="menuitem" href="/tcl326/stalk-pusher/blame/acc2b66b58dd11be35feca50ba6d6500d1c510dd/hardware/stalkPusher/Adafruit_AM2315.cpp">View git blame</a></li> <li><a class="dropdown-item" id="js-new-issue" role="menuitem" href="/tcl326/stalk-pusher/issues/new">Open new issue</a></li> </ul> </details-menu> </details> </div> </div> <details class="details-reset details-overlay details-overlay-dark"> <summary data-hotkey="l" aria-label="Jump to line"></summary> <details-dialog class="Box Box--overlay d-flex flex-column anim-fade-in fast linejump" aria-label="Jump to line"> <!-- '"` --><!-- </textarea></xmp> --></option></form><form class="js-jump-to-line-form Box-body d-flex" action="" accept-charset="UTF-8" method="get"><input name="utf8" type="hidden" value="&#x2713;" /> <input class="form-control flex-auto mr-3 linejump-input js-jump-to-line-field" type="text" placeholder="Jump to line&hellip;" aria-label="Jump to line" autofocus> <button type="submit" class="btn" data-close-dialog>Go</button> </form> </details-dialog> </details> </div> <div class="modal-backdrop js-touch-events"></div> </div> </div> </div> </div> <div class="footer container-lg px-3" role="contentinfo"> <div class="position-relative d-flex flex-justify-between pt-6 pb-2 mt-6 f6 text-gray border-top border-gray-light "> <ul class="list-style-none d-flex flex-wrap "> <li class="mr-3">&copy; 2018 <span title="0.22074s from unicorn-79748d6cc4-5kwcf">GitHub</span>, Inc.</li> <li class="mr-3"><a data-ga-click="Footer, go to terms, text:terms" href="https://github.com/site/terms">Terms</a></li> <li class="mr-3"><a data-ga-click="Footer, go to privacy, text:privacy" href="https://github.com/site/privacy">Privacy</a></li> <li class="mr-3"><a href="https://help.github.com/articles/github-security/" data-ga-click="Footer, go to security, text:security">Security</a></li> <li class="mr-3"><a href="https://status.github.com/" data-ga-click="Footer, go to status, text:status">Status</a></li> <li><a data-ga-click="Footer, go to help, text:help" href="https://help.github.com">Help</a></li> </ul> <a aria-label="Homepage" title="GitHub" class="footer-octicon" href="https://github.com"> <svg height="24" class="octicon octicon-mark-github" viewBox="0 0 16 16" version="1.1" width="24" aria-hidden="true"><path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"/></svg> </a> <ul class="list-style-none d-flex flex-wrap "> <li class="mr-3"><a data-ga-click="Footer, go to contact, text:contact" href="https://github.com/contact">Contact GitHub</a></li> <li class="mr-3"><a href="https://developer.github.com" data-ga-click="Footer, go to api, text:api">API</a></li> <li class="mr-3"><a href="https://training.github.com" data-ga-click="Footer, go to training, text:training">Training</a></li> <li class="mr-3"><a href="https://shop.github.com" data-ga-click="Footer, go to shop, text:shop">Shop</a></li> <li class="mr-3"><a href="https://blog.github.com" data-ga-click="Footer, go to blog, text:blog">Blog</a></li> <li><a data-ga-click="Footer, go to about, text:about" href="https://github.com/about">About</a></li> </ul> </div> <div class="d-flex flex-justify-center pb-6"> <span class="f6 text-gray-light"></span> </div> </div> <div id="ajax-error-message" class="ajax-error-message flash flash-error"> <svg class="octicon octicon-alert" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8.893 1.5c-.183-.31-.52-.5-.887-.5s-.703.19-.886.5L.138 13.499a.98.98 0 0 0 0 1.001c.193.31.53.501.886.501h13.964c.367 0 .704-.19.877-.5a1.03 1.03 0 0 0 .01-1.002L8.893 1.5zm.133 11.497H6.987v-2.003h2.039v2.003zm0-3.004H6.987V5.987h2.039v4.006z"/></svg> <button type="button" class="flash-close js-ajax-error-dismiss" aria-label="Dismiss error"> <svg class="octicon octicon-x" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48L7.48 8z"/></svg> </button> You can’t perform that action at this time. </div> <script crossorigin="anonymous" integrity="sha512-KzMN78fl7zl9khU8sHnDTAaEOs8IyidbN0kN5dcsEMnFAhDD3SueLZN/Cgd4v2+BUolauU3VbjbBe5d0eA9DfQ==" type="application/javascript" src="https://assets-cdn.github.com/assets/frameworks-edf16da922b28a7eed43ab4f51c61f11.js"></script> <script crossorigin="anonymous" async="async" integrity="sha512-RInxhX584u4h3Dt9yc9CZF2DTmqhWY5J/W9cDLaIsKwYM1wkPNeWdlEriEvxIG6byZsg6aKEnsd5c5yvviLdaw==" type="application/javascript" src="https://assets-cdn.github.com/assets/github-943a97ac42ce3e5820d811264c16454e.js"></script> <div class="js-stale-session-flash stale-session-flash flash flash-warn flash-banner d-none"> <svg class="octicon octicon-alert" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8.893 1.5c-.183-.31-.52-.5-.887-.5s-.703.19-.886.5L.138 13.499a.98.98 0 0 0 0 1.001c.193.31.53.501.886.501h13.964c.367 0 .704-.19.877-.5a1.03 1.03 0 0 0 .01-1.002L8.893 1.5zm.133 11.497H6.987v-2.003h2.039v2.003zm0-3.004H6.987V5.987h2.039v4.006z"/></svg> <span class="signed-in-tab-flash">You signed in with another tab or window. <a href="">Reload</a> to refresh your session.</span> <span class="signed-out-tab-flash">You signed out in another tab or window. <a href="">Reload</a> to refresh your session.</span> </div> <div class="facebox" id="facebox" style="display:none;"> <div class="facebox-popup"> <div class="facebox-content" role="dialog" aria-labelledby="facebox-header" aria-describedby="facebox-description"> </div> <button type="button" class="facebox-close js-facebox-close" aria-label="Close modal"> <svg class="octicon octicon-x" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48L7.48 8z"/></svg> </button> </div> </div> <div class="Popover js-hovercard-content position-absolute" style="display: none; outline: none;" tabindex="0"> <div class="Popover-message Popover-message--bottom-left Popover-message--large Box box-shadow-large" style="width:360px;"> </div> </div> <div id="hovercard-aria-description" class="sr-only"> Press h to open a hovercard with more details. </div> </body> </html>
[ "kennedyc@uidaho.edu" ]
kennedyc@uidaho.edu
2f873103409295d39e9015b309d704ecb6d84cea
0926ce7b4ab7b18968e5d3ec2dce2afa14e286e2
/Libraries/open-powerplant/PowerPlantX/ViewSystem/SystemViews/PPxPopupButton.h
dc5d151cc7ac5f7767e0c6bd5f2077dd66f3f74c
[ "Apache-2.0" ]
permissive
quanah/mulberry-main
dd4557a8c1fe3bc79bb76a2720278b2332c7d0ae
02581ac16f849c8d89e6a22cb97b07b7b5e7185a
refs/heads/master
2020-06-18T08:48:01.653513
2019-07-11T01:59:15
2019-07-11T01:59:15
196,239,708
1
0
null
2019-07-10T16:26:52
2019-07-10T16:26:51
null
WINDOWS-1252
C++
false
false
2,168
h
// Copyright ©2005, 2006 Freescale Semiconductor, Inc. // Please see the License for the specific language governing rights and // limitations under the License. // =========================================================================== // PPxPopupButton.h // // Copyright © 2003-2005 Metrowerks Corporation. All rights reserved. // // $Date: 2006/01/18 01:37:43 $ // $Revision: 1.1.1.1 $ // =========================================================================== /** @file PPxPopupButton.h @brief A system popup button control */ #ifndef H_PPxPopupButton #define H_PPxPopupButton #pragma once #include <PPxView.h> namespace PPx { // =========================================================================== // PopupButton /** A system popup button control */ class PopupButton : public View { public: PopupButton(); virtual ~PopupButton(); void Initialize( View* inSuperView, const HIRect& inFrame, bool inVisible, bool inEnabled, CFStringRef inTitle, SInt32 inMenuID, bool inHasVariableWidth, SInt16 inTitleWidth, SInt16 inTitleJustification, Style inTitleStyle); void SetMenuRef( MenuRef inMenu ); MenuRef GetMenuRef() const; void SetOwnedMenuRef( MenuRef inMenu ); MenuRef GetOwnedMenuRef() const; void SetMenuID( SInt16 inMenuID ); SInt16 GetMenuID() const; void SetExtraHeight( SInt16 inExtraHeight ); SInt16 GetExtraHeight() const; void SetCheckCurrentItemFlag( bool inCheckIt ); bool GetCheckCurrentItemFlag() const; protected: virtual void InitState( const DataReader& inReader); virtual void WriteState( DataWriter& ioWriter ) const; private: virtual CFStringRef ClassName() const; private: SInt16 mMenuID; /**< MENU resource ID */ SInt16 mTitleWidth; /**< Width of title area in pixels */ SInt16 mTitleJustification; /**< Justification of title */ bool mHasVariableWidth; /**< Adjust title area to width of text? */ Style mTitleStyle; /**< Text style of title */ }; } // namespace PPx #endif // H_PPxPopupButton
[ "mdietze@gmail.com" ]
mdietze@gmail.com
5f330fdbeea2b05618ef5d3ffdcef48f274c956c
752ec26fddc2ee76a9b6e6d884c5ba5967fda110
/labs/11/task2.cpp
d2682dfa8206a59dd75c55762da8b639f43ffbc1
[]
no_license
bsu-docs/computer-networks
0b9a220eb7c70fe8a7c018f1e89d2f2190ffa803
3c9a660e68f522510b496d8746e0a10c22d207e0
refs/heads/master
2021-01-19T23:41:17.431453
2017-04-21T19:50:25
2017-04-21T19:50:25
89,018,175
1
0
null
null
null
null
UTF-8
C++
false
false
5,287
cpp
#include <sys/socket.h> #include <sys/ioctl.h> #include <sys/time.h> #include <asm/types.h> #include <math.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <linux/if_packet.h> #include <linux/if_ether.h> #include <linux/if_arp.h> #include <arpa/inet.h> #define PROTO_ARP 0x0806 #define ETH2_HEADER_LEN 14 #define HW_TYPE 1 #define PROTOCOL_TYPE 0x800 #define MAC_LENGTH 6 #define IPV4_LENGTH 4 #define ARP_REQUEST 0x01 #define ARP_REPLY 0x02 #define BUF_SIZE 60 struct arp_header { unsigned short hardware_type; unsigned short protocol_type; unsigned char hardware_len; unsigned char protocol_len; unsigned short opcode; unsigned char sender_mac[MAC_LENGTH]; unsigned char sender_ip[IPV4_LENGTH]; unsigned char target_mac[MAC_LENGTH]; unsigned char target_ip[IPV4_LENGTH]; }; int main() { int sd; unsigned char buffer[BUF_SIZE]; unsigned char source_ip[4] = {10,150,5,146}; unsigned char target_ip[4] = {10,150,5,80}; struct ifreq ifr; struct ethhdr *send_req = (struct ethhdr *)buffer; struct ethhdr *rcv_resp= (struct ethhdr *)buffer; struct arp_header *arp_req = (struct arp_header *)(buffer+ETH2_HEADER_LEN); struct arp_header *arp_resp = (struct arp_header *)(buffer+ETH2_HEADER_LEN); struct sockaddr_ll socket_address; int index,ret,length=0,ifindex; memset(buffer,0x00,60); sd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL)); if (sd == -1) { perror("socket():"); exit(1); } strcpy(ifr.ifr_name,"enp0s25"); if (ioctl(sd, SIOCGIFINDEX, &ifr) == -1) { perror("SIOCGIFINDEX"); exit(1); } ifindex = ifr.ifr_ifindex; printf("interface index is %d\n",ifindex); if (ioctl(sd, SIOCGIFHWADDR, &ifr) == -1) { perror("SIOCGIFINDEX"); exit(1); } close (sd); for (index = 0; index < 6; index++) { send_req->h_dest[index] = (unsigned char)0xff; arp_req->target_mac[index] = (unsigned char)0x00; /* Filling the source mac address in the header*/ send_req->h_source[index] = (unsigned char)ifr.ifr_hwaddr.sa_data[index]; arp_req->sender_mac[index] = (unsigned char)ifr.ifr_hwaddr.sa_data[index]; socket_address.sll_addr[index] = (unsigned char)ifr.ifr_hwaddr.sa_data[index]; } printf("Successfully got eth1 MAC address: %02X:%02X:%02X:%02X:%02X:%02X\n", send_req->h_source[0],send_req->h_source[1],send_req->h_source[2], send_req->h_source[3],send_req->h_source[4],send_req->h_source[5]); printf(" arp_reqMAC address: %02X:%02X:%02X:%02X:%02X:%02X\n", arp_req->sender_mac[0],arp_req->sender_mac[1],arp_req->sender_mac[2], arp_req->sender_mac[3],arp_req->sender_mac[4],arp_req->sender_mac[5]); printf("socket_address MAC address: %02X:%02X:%02X:%02X:%02X:%02X\n", socket_address.sll_addr[0],socket_address.sll_addr[1],socket_address.sll_addr[2], socket_address.sll_addr[3],socket_address.sll_addr[4],socket_address.sll_addr[5]); /*prepare sockaddr_ll*/ socket_address.sll_family = AF_PACKET; socket_address.sll_protocol = htons(ETH_P_ARP); socket_address.sll_ifindex = ifindex; socket_address.sll_hatype = htons(ARPHRD_ETHER); socket_address.sll_pkttype = (PACKET_BROADCAST); socket_address.sll_halen = MAC_LENGTH; socket_address.sll_addr[6] = 0x00; socket_address.sll_addr[7] = 0x00; /* Setting protocol of the packet */ send_req->h_proto = htons(ETH_P_ARP); /* Creating ARP request */ arp_req->hardware_type = htons(HW_TYPE); arp_req->protocol_type = htons(ETH_P_IP); arp_req->hardware_len = MAC_LENGTH; arp_req->protocol_len = IPV4_LENGTH; arp_req->opcode = htons(ARP_REQUEST); for(index = 0; index < 5; ++index) { arp_req->sender_ip[index]=(unsigned char)source_ip[index]; arp_req->target_ip[index]=(unsigned char)target_ip[index]; } // Submit request for a raw socket descriptor. if ((sd = socket (PF_PACKET, SOCK_RAW, htons (ETH_P_ALL))) < 0) { perror ("socket() failed "); exit (EXIT_FAILURE); } buffer[32] = 0x00; ret = sendto(sd, buffer, 42, 0, (struct sockaddr*)&socket_address, sizeof(socket_address)); if (ret == -1) { perror("sendto():"); exit(1); } else { printf(" Sent the ARP REQ \n\t"); for(index = 0; index < 42; index++) { printf("%02X ",buffer[index]); if(index % 16 ==0 && index !=0) { printf("\n\t"); } } } printf("\n\t"); memset(buffer,0x00,60); while(1) { length = recvfrom(sd, buffer, BUF_SIZE, 0, NULL, NULL); if (length == -1) { perror("recvfrom():"); exit(1); } if(htons(rcv_resp->h_proto) == PROTO_ARP) { printf(" RECEIVED ARP RESP len=%d \n",length); printf(" Sender IP :"); for(index=0;index<4;index++) printf("%u.",(unsigned int)arp_resp->sender_ip[index]); printf("\n Sender MAC: "); for(index=0;index<6;index++) printf("%02X:",arp_resp->sender_mac[index]); printf("\nReceiver IP: "); for(index=0;index<4;index++) printf("%u.",arp_resp->target_ip[index]); printf("\n Self MAC: "); for(index=0;index<6;index++) printf("%02X:",arp_resp->target_mac[index]); printf("\n :"); break; } } return 0; }
[ "selatnick@gmail.com" ]
selatnick@gmail.com
b91fc132996cd8f1cc632acd00576356af10fc5e
bdb86d72be26f0d2d4d72d692f0875887fd11402
/BCC102/include/windows/sdk/wsdhost.h
0cdc1dc16e626cdb25b5aba9d3e2a06dee888f16
[]
no_license
KaarthicPulogarajah/Battleship
28168359e4209a36b12e855668105ab31f7121f3
a216169e28c7b54c730df23d61ab07d25d487c05
refs/heads/master
2021-01-12T04:23:33.630829
2019-08-21T01:37:39
2019-08-21T01:37:39
77,579,201
0
0
null
null
null
null
UTF-8
C++
false
false
18,185
h
#pragma option push -b -a8 -pc -A- -w-pun /*P_O_Push*/ /* this ALWAYS GENERATED file contains the definitions for the interfaces */ /* File created by MIDL compiler version 8.00.0611 */ /* @@MIDL_FILE_HEADING( ) */ /* verify that the <rpcndr.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCNDR_H_VERSION__ #define __REQUIRED_RPCNDR_H_VERSION__ 500 #endif /* verify that the <rpcsal.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCSAL_H_VERSION__ #define __REQUIRED_RPCSAL_H_VERSION__ 100 #endif #include "rpc.h" #include "rpcndr.h" #ifndef __RPCNDR_H_VERSION__ #error this stub requires an updated version of <rpcndr.h> #endif /* __RPCNDR_H_VERSION__ */ #ifndef COM_NO_WINDOWS_H #include "windows.h" #include "ole2.h" #endif /*COM_NO_WINDOWS_H*/ #ifndef __wsdhost_h__ #define __wsdhost_h__ #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif /* Forward Declarations */ #ifndef __IWSDDeviceHost_FWD_DEFINED__ #define __IWSDDeviceHost_FWD_DEFINED__ typedef interface IWSDDeviceHost IWSDDeviceHost; #endif /* __IWSDDeviceHost_FWD_DEFINED__ */ #ifndef __IWSDDeviceHostNotify_FWD_DEFINED__ #define __IWSDDeviceHostNotify_FWD_DEFINED__ typedef interface IWSDDeviceHostNotify IWSDDeviceHostNotify; #endif /* __IWSDDeviceHostNotify_FWD_DEFINED__ */ #ifndef __IWSDServiceMessaging_FWD_DEFINED__ #define __IWSDServiceMessaging_FWD_DEFINED__ typedef interface IWSDServiceMessaging IWSDServiceMessaging; #endif /* __IWSDServiceMessaging_FWD_DEFINED__ */ /* header files for imported files */ #include "oaidl.h" #include "ocidl.h" #include "wsdxmldom.h" #include "wsdtypes.h" #ifdef __cplusplus extern "C"{ #endif /* interface __MIDL_itf_wsdhost_0000_0000 */ /* [local] */ #include <winapifamily.h> #pragma region Desktop Family #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) HRESULT WINAPI WSDCreateDeviceHost( _In_ LPCWSTR pszLocalId, IWSDXMLContext* pContext, _Outptr_ IWSDDeviceHost** ppDeviceHost); HRESULT WINAPI WSDCreateDeviceHostAdvanced( _In_ LPCWSTR pszLocalId, IWSDXMLContext* pContext, _In_reads_opt_(dwHostAddressCount) IWSDAddress** ppHostAddresses, DWORD dwHostAddressCount, _Outptr_ IWSDDeviceHost** ppDeviceHost); #if (WINVER >= _WIN32_WINNT_WIN7) HRESULT WINAPI WSDCreateDeviceHost2( _In_ LPCWSTR pszLocalId, IWSDXMLContext* pContext, _In_reads_opt_(dwConfigParamCount) WSD_CONFIG_PARAM* pConfigParams, DWORD dwConfigParamCount, _Outptr_ IWSDDeviceHost** ppDeviceHost); #endif extern RPC_IF_HANDLE __MIDL_itf_wsdhost_0000_0000_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_wsdhost_0000_0000_v0_0_s_ifspec; #ifndef __IWSDDeviceHost_INTERFACE_DEFINED__ #define __IWSDDeviceHost_INTERFACE_DEFINED__ /* interface IWSDDeviceHost */ /* [local][restricted][unique][helpstring][uuid][object] */ EXTERN_C const IID IID_IWSDDeviceHost; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("917fe891-3d13-4138-9809-934c8abeb12c") IWSDDeviceHost : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE Init( /* [annotation][in] */ _In_ LPCWSTR pszLocalId, /* [annotation][optional][in] */ _In_opt_ IWSDXMLContext *pContext, /* [annotation][optional][in] */ _In_reads_opt_(dwHostAddressCount) IWSDAddress **ppHostAddresses, /* [annotation][optional][in] */ _In_opt_ DWORD dwHostAddressCount) = 0; virtual HRESULT STDMETHODCALLTYPE Start( /* [in] */ ULONGLONG ullInstanceId, /* [in] */ const WSD_URI_LIST *pScopeList, /* [annotation][optional][in] */ _In_opt_ IWSDDeviceHostNotify *pNotificationSink) = 0; virtual HRESULT STDMETHODCALLTYPE Stop( void) = 0; virtual HRESULT STDMETHODCALLTYPE Terminate( void) = 0; virtual HRESULT STDMETHODCALLTYPE RegisterPortType( /* [in] */ const WSD_PORT_TYPE *pPortType) = 0; virtual HRESULT STDMETHODCALLTYPE SetMetadata( /* [in] */ const WSD_THIS_MODEL_METADATA *pThisModelMetadata, /* [in] */ const WSD_THIS_DEVICE_METADATA *pThisDeviceMetadata, /* [annotation][optional][in] */ _In_opt_ const WSD_HOST_METADATA *pHostMetadata, /* [annotation][optional][in] */ _In_opt_ const WSD_METADATA_SECTION_LIST *pCustomMetadata) = 0; virtual HRESULT STDMETHODCALLTYPE RegisterService( /* [annotation][in] */ _In_ LPCWSTR pszServiceId, /* [in] */ IUnknown *pService) = 0; virtual HRESULT STDMETHODCALLTYPE RetireService( /* [annotation][in] */ _In_ LPCWSTR pszServiceId) = 0; virtual HRESULT STDMETHODCALLTYPE AddDynamicService( /* [annotation][in] */ _In_ LPCWSTR pszServiceId, /* [annotation][optional][in] */ _In_opt_ LPCWSTR pszEndpointAddress, /* [annotation][optional][in] */ _In_opt_ const WSD_PORT_TYPE *pPortType, /* [annotation][optional][in] */ _In_opt_ const WSDXML_NAME *pPortName, /* [annotation][optional][in] */ _In_opt_ const WSDXML_ELEMENT *pAny, /* [annotation][optional][in] */ _In_opt_ IUnknown *pService) = 0; virtual HRESULT STDMETHODCALLTYPE RemoveDynamicService( /* [annotation][in] */ _In_ LPCWSTR pszServiceId) = 0; virtual HRESULT STDMETHODCALLTYPE SetServiceDiscoverable( /* [annotation][in] */ _In_ LPCWSTR pszServiceId, /* [in] */ BOOL fDiscoverable) = 0; virtual HRESULT STDMETHODCALLTYPE SignalEvent( /* [annotation][in] */ _In_ LPCWSTR pszServiceId, /* [annotation][in] */ _In_opt_ const void *pBody, /* [in] */ const WSD_OPERATION *pOperation) = 0; }; #else /* C style interface */ typedef struct IWSDDeviceHostVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IWSDDeviceHost * This, /* [in] */ REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IWSDDeviceHost * This); ULONG ( STDMETHODCALLTYPE *Release )( IWSDDeviceHost * This); HRESULT ( STDMETHODCALLTYPE *Init )( IWSDDeviceHost * This, /* [annotation][in] */ _In_ LPCWSTR pszLocalId, /* [annotation][optional][in] */ _In_opt_ IWSDXMLContext *pContext, /* [annotation][optional][in] */ _In_reads_opt_(dwHostAddressCount) IWSDAddress **ppHostAddresses, /* [annotation][optional][in] */ _In_opt_ DWORD dwHostAddressCount); HRESULT ( STDMETHODCALLTYPE *Start )( IWSDDeviceHost * This, /* [in] */ ULONGLONG ullInstanceId, /* [in] */ const WSD_URI_LIST *pScopeList, /* [annotation][optional][in] */ _In_opt_ IWSDDeviceHostNotify *pNotificationSink); HRESULT ( STDMETHODCALLTYPE *Stop )( IWSDDeviceHost * This); HRESULT ( STDMETHODCALLTYPE *Terminate )( IWSDDeviceHost * This); HRESULT ( STDMETHODCALLTYPE *RegisterPortType )( IWSDDeviceHost * This, /* [in] */ const WSD_PORT_TYPE *pPortType); HRESULT ( STDMETHODCALLTYPE *SetMetadata )( IWSDDeviceHost * This, /* [in] */ const WSD_THIS_MODEL_METADATA *pThisModelMetadata, /* [in] */ const WSD_THIS_DEVICE_METADATA *pThisDeviceMetadata, /* [annotation][optional][in] */ _In_opt_ const WSD_HOST_METADATA *pHostMetadata, /* [annotation][optional][in] */ _In_opt_ const WSD_METADATA_SECTION_LIST *pCustomMetadata); HRESULT ( STDMETHODCALLTYPE *RegisterService )( IWSDDeviceHost * This, /* [annotation][in] */ _In_ LPCWSTR pszServiceId, /* [in] */ IUnknown *pService); HRESULT ( STDMETHODCALLTYPE *RetireService )( IWSDDeviceHost * This, /* [annotation][in] */ _In_ LPCWSTR pszServiceId); HRESULT ( STDMETHODCALLTYPE *AddDynamicService )( IWSDDeviceHost * This, /* [annotation][in] */ _In_ LPCWSTR pszServiceId, /* [annotation][optional][in] */ _In_opt_ LPCWSTR pszEndpointAddress, /* [annotation][optional][in] */ _In_opt_ const WSD_PORT_TYPE *pPortType, /* [annotation][optional][in] */ _In_opt_ const WSDXML_NAME *pPortName, /* [annotation][optional][in] */ _In_opt_ const WSDXML_ELEMENT *pAny, /* [annotation][optional][in] */ _In_opt_ IUnknown *pService); HRESULT ( STDMETHODCALLTYPE *RemoveDynamicService )( IWSDDeviceHost * This, /* [annotation][in] */ _In_ LPCWSTR pszServiceId); HRESULT ( STDMETHODCALLTYPE *SetServiceDiscoverable )( IWSDDeviceHost * This, /* [annotation][in] */ _In_ LPCWSTR pszServiceId, /* [in] */ BOOL fDiscoverable); HRESULT ( STDMETHODCALLTYPE *SignalEvent )( IWSDDeviceHost * This, /* [annotation][in] */ _In_ LPCWSTR pszServiceId, /* [annotation][in] */ _In_opt_ const void *pBody, /* [in] */ const WSD_OPERATION *pOperation); END_INTERFACE } IWSDDeviceHostVtbl; interface IWSDDeviceHost { CONST_VTBL struct IWSDDeviceHostVtbl *lpVtbl; }; #ifdef COBJMACROS #define IWSDDeviceHost_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IWSDDeviceHost_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IWSDDeviceHost_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IWSDDeviceHost_Init(This,pszLocalId,pContext,ppHostAddresses,dwHostAddressCount) \ ( (This)->lpVtbl -> Init(This,pszLocalId,pContext,ppHostAddresses,dwHostAddressCount) ) #define IWSDDeviceHost_Start(This,ullInstanceId,pScopeList,pNotificationSink) \ ( (This)->lpVtbl -> Start(This,ullInstanceId,pScopeList,pNotificationSink) ) #define IWSDDeviceHost_Stop(This) \ ( (This)->lpVtbl -> Stop(This) ) #define IWSDDeviceHost_Terminate(This) \ ( (This)->lpVtbl -> Terminate(This) ) #define IWSDDeviceHost_RegisterPortType(This,pPortType) \ ( (This)->lpVtbl -> RegisterPortType(This,pPortType) ) #define IWSDDeviceHost_SetMetadata(This,pThisModelMetadata,pThisDeviceMetadata,pHostMetadata,pCustomMetadata) \ ( (This)->lpVtbl -> SetMetadata(This,pThisModelMetadata,pThisDeviceMetadata,pHostMetadata,pCustomMetadata) ) #define IWSDDeviceHost_RegisterService(This,pszServiceId,pService) \ ( (This)->lpVtbl -> RegisterService(This,pszServiceId,pService) ) #define IWSDDeviceHost_RetireService(This,pszServiceId) \ ( (This)->lpVtbl -> RetireService(This,pszServiceId) ) #define IWSDDeviceHost_AddDynamicService(This,pszServiceId,pszEndpointAddress,pPortType,pPortName,pAny,pService) \ ( (This)->lpVtbl -> AddDynamicService(This,pszServiceId,pszEndpointAddress,pPortType,pPortName,pAny,pService) ) #define IWSDDeviceHost_RemoveDynamicService(This,pszServiceId) \ ( (This)->lpVtbl -> RemoveDynamicService(This,pszServiceId) ) #define IWSDDeviceHost_SetServiceDiscoverable(This,pszServiceId,fDiscoverable) \ ( (This)->lpVtbl -> SetServiceDiscoverable(This,pszServiceId,fDiscoverable) ) #define IWSDDeviceHost_SignalEvent(This,pszServiceId,pBody,pOperation) \ ( (This)->lpVtbl -> SignalEvent(This,pszServiceId,pBody,pOperation) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IWSDDeviceHost_INTERFACE_DEFINED__ */ #ifndef __IWSDDeviceHostNotify_INTERFACE_DEFINED__ #define __IWSDDeviceHostNotify_INTERFACE_DEFINED__ /* interface IWSDDeviceHostNotify */ /* [restricted][unique][helpstring][uuid][object] */ EXTERN_C const IID IID_IWSDDeviceHostNotify; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("b5bee9f9-eeda-41fe-96f7-f45e14990fb0") IWSDDeviceHostNotify : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetService( /* [annotation][in] */ _In_ LPCWSTR pszServiceId, /* [annotation][out] */ _Outptr_ IUnknown **ppService) = 0; }; #else /* C style interface */ typedef struct IWSDDeviceHostNotifyVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IWSDDeviceHostNotify * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IWSDDeviceHostNotify * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IWSDDeviceHostNotify * This); HRESULT ( STDMETHODCALLTYPE *GetService )( __RPC__in IWSDDeviceHostNotify * This, /* [annotation][in] */ _In_ LPCWSTR pszServiceId, /* [annotation][out] */ _Outptr_ IUnknown **ppService); END_INTERFACE } IWSDDeviceHostNotifyVtbl; interface IWSDDeviceHostNotify { CONST_VTBL struct IWSDDeviceHostNotifyVtbl *lpVtbl; }; #ifdef COBJMACROS #define IWSDDeviceHostNotify_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IWSDDeviceHostNotify_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IWSDDeviceHostNotify_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IWSDDeviceHostNotify_GetService(This,pszServiceId,ppService) \ ( (This)->lpVtbl -> GetService(This,pszServiceId,ppService) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IWSDDeviceHostNotify_INTERFACE_DEFINED__ */ #ifndef __IWSDServiceMessaging_INTERFACE_DEFINED__ #define __IWSDServiceMessaging_INTERFACE_DEFINED__ /* interface IWSDServiceMessaging */ /* [local][restricted][unique][helpstring][uuid][object] */ EXTERN_C const IID IID_IWSDServiceMessaging; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("94974cf4-0cab-460d-a3f6-7a0ad623c0e6") IWSDServiceMessaging : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE SendResponse( /* [annotation][in] */ _In_opt_ void *pBody, /* [in] */ WSD_OPERATION *pOperation, /* [in] */ IWSDMessageParameters *pMessageParameters) = 0; virtual HRESULT STDMETHODCALLTYPE FaultRequest( /* [in] */ WSD_SOAP_HEADER *pRequestHeader, /* [in] */ IWSDMessageParameters *pMessageParameters, /* [annotation][optional][in] */ _In_opt_ WSD_SOAP_FAULT *pFault) = 0; }; #else /* C style interface */ typedef struct IWSDServiceMessagingVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IWSDServiceMessaging * This, /* [in] */ REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IWSDServiceMessaging * This); ULONG ( STDMETHODCALLTYPE *Release )( IWSDServiceMessaging * This); HRESULT ( STDMETHODCALLTYPE *SendResponse )( IWSDServiceMessaging * This, /* [annotation][in] */ _In_opt_ void *pBody, /* [in] */ WSD_OPERATION *pOperation, /* [in] */ IWSDMessageParameters *pMessageParameters); HRESULT ( STDMETHODCALLTYPE *FaultRequest )( IWSDServiceMessaging * This, /* [in] */ WSD_SOAP_HEADER *pRequestHeader, /* [in] */ IWSDMessageParameters *pMessageParameters, /* [annotation][optional][in] */ _In_opt_ WSD_SOAP_FAULT *pFault); END_INTERFACE } IWSDServiceMessagingVtbl; interface IWSDServiceMessaging { CONST_VTBL struct IWSDServiceMessagingVtbl *lpVtbl; }; #ifdef COBJMACROS #define IWSDServiceMessaging_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IWSDServiceMessaging_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IWSDServiceMessaging_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IWSDServiceMessaging_SendResponse(This,pBody,pOperation,pMessageParameters) \ ( (This)->lpVtbl -> SendResponse(This,pBody,pOperation,pMessageParameters) ) #define IWSDServiceMessaging_FaultRequest(This,pRequestHeader,pMessageParameters,pFault) \ ( (This)->lpVtbl -> FaultRequest(This,pRequestHeader,pMessageParameters,pFault) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IWSDServiceMessaging_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_wsdhost_0000_0003 */ /* [local] */ #endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) */ #pragma endregion extern RPC_IF_HANDLE __MIDL_itf_wsdhost_0000_0003_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_wsdhost_0000_0003_v0_0_s_ifspec; /* Additional Prototypes for ALL interfaces */ /* end of Additional Prototypes */ #ifdef __cplusplus } #endif #endif #pragma option pop /*P_O_Pop*/
[ "kaarthicp@hotmail.com" ]
kaarthicp@hotmail.com
263a48a94ca37335ab39c496c85ec9e72b99c29f
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/icu/source/test/intltest/numrgts.h
0c5b574d052f290d9a48626ec34bb3be57afeb1a
[ "Apache-2.0", "LGPL-2.0-or-later", "MIT", "GPL-1.0-or-later", "BSD-3-Clause", "LicenseRef-scancode-unicode", "ICU", "LicenseRef-scancode-unknown-license-reference", "GPL-3.0-or-later", "NTP", "GPL-2.0-or-later", "LicenseRef-scancode-autoconf-simple-exception", "Autoconf-exception-generic", ...
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
3,256
h
// © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /*********************************************************************** * COPYRIGHT: * Copyright (c) 1997-2013, International Business Machines Corporation * and others. All Rights Reserved. ***********************************************************************/ #ifndef _NUMBERFORMATREGRESSIONTEST_ #define _NUMBERFORMATREGRESSIONTEST_ #include "unicode/utypes.h" #if !UCONFIG_NO_FORMATTING #include "unicode/unistr.h" #include "unicode/numfmt.h" #include "unicode/decimfmt.h" #include "intltest.h" /** * Performs regression test for MessageFormat **/ class NumberFormatRegressionTest: public IntlTest { // IntlTest override void runIndexedTest( int32_t index, UBool exec, const char* &name, char* par ) override; public: void Test4075713(void); void Test4074620(void) ; void Test4088161 (void); void Test4087245 (void); void Test4087535 (void); void Test4088503 (void); void Test4066646 (void); float assignFloatValue(float returnfloat); void Test4059870(void); void Test4083018 (void); void Test4071492 (void); void Test4086575(void); void Test4068693(void); void Test4069754(void); void Test4087251 (void); void Test4090489 (void); void Test4090504 (void); void Test4095713 (void); void Test4092561 (void); void Test4092480 (void); void Test4087244 (void); void Test4070798 (void); void Test4071005 (void); void Test4071014 (void); void Test4071859 (void); void Test4093610(void); void roundingTest(DecimalFormat *df, double x, UnicodeString& expected); void Test4098741(void); void Test4074454(void); void Test4099404(void); void Test4101481(void); void Test4052223(void); void Test4061302(void); void Test4062486(void); void Test4108738(void); void Test4106658(void); void Test4106662(void); void Test4114639(void); void Test4106664(void); void Test4106667(void); void Test4110936(void); void Test4122840(void); void Test4125885(void); void Test4134034(void); void Test4134300(void); void Test4140009(void); void Test4141750(void); void Test4145457(void); void Test4147295(void); void Test4147706(void); void Test4162198(void); void Test4162852(void); void Test4167494(void); void Test4170798(void); void Test4176114(void); void Test4179818(void); void Test4212072(void); void Test4216742(void); void Test4217661(void); void Test4161100(void); void Test4243011(void); void Test4243108(void); void TestJ691(void); void Test8199(void); void Test9109(void); void Test9780(void); void Test9677(void); void Test10361(void); protected: UBool failure(UErrorCode status, const UnicodeString& msg, UBool possibleDataError=false); UBool failure(UErrorCode status, const UnicodeString& msg, const char *l, UBool possibleDataError=false); UBool failure(UErrorCode status, const UnicodeString& msg, const Locale& l, UBool possibleDataError=false); }; #endif /* #if !UCONFIG_NO_FORMATTING */ #endif // _NUMBERFORMATREGRESSIONTEST_ //eof
[ "jengelh@inai.de" ]
jengelh@inai.de
28416b9e7194bf0cea35649ed9c1bc725db3243b
91bfb0e3afd74888c3e005c61c6f354b630f96c7
/src/delphi/solver/solver_fastSOR_run.cpp
2779ce58571ad371ee77535213f8d34340317199
[]
no_license
delphi001/DelphiPkaSalt
fd5792e11b5742410e855db7fe510495df44beed
242fa266ab5498f7906fc9473f2ff3f055e863e6
refs/heads/master
2023-01-10T07:52:17.936560
2020-11-16T17:32:18
2020-11-16T17:32:18
313,376,012
1
0
null
null
null
null
UTF-8
C++
false
false
6,277
cpp
/* * solver_fastSOR_run.cpp * * Created on: Feb 10, 2014 * Author: chuan */ #include "solver_fastSOR.h" void CDelphiFastSOR::run() { debug_solver=false; const char * infoString = " Info> "; const char * timeString = " Time> "; const char * bndcString = " Bndc> "; size_t MAXWIDTH = 45; if(debug_solver) cout << "###### start run of solver ### " << endl; if (debug_solver) cout << "###: fsrfdens: " << fsrfdens << endl; if (debug_solver) cout << "###: inhomo: " << inhomo << endl; //ARGO modification made to accommodate iConvlute module if (inhomo == 1) fIonStrength=0; if( (iGaussian==1 && inhomo==0 ) || (iConvolute != 0 && inhomo==0) ) //reset some vectors for 2nd run of Gaussian or convolution { if (prgfGridCrg.size()>0 ) { if(debug_solver)cout << "prgfGridCrg.size(): " << prgfGridCrg.size() << endl; vector<delphi_real>().swap(prgfGridCrg) ;//gchrg } if (prgigGridCrgPose.size()>0 ){ if(debug_solver)cout << "prgigGridCrgPose.size(): " << prgigGridCrgPose.size() << endl; vector< SGrid<delphi_integer> >().swap(prgigGridCrgPose) ; //gchrgp } //vector<delphi_integer> ibndx,ibndy,ibndz; if (ibndx.size()>0 ){ if(debug_solver)cout << "ibndx.size(): " << ibndx.size() << endl; vector<delphi_integer>().swap(ibndx) ; //ibndx } if (ibndy.size()>0 ){ if(debug_solver)cout << "ibndy.size(): " << ibndy.size() << endl; vector<delphi_integer>().swap(ibndy) ; //ibndy } if (ibndz.size()>0 ){ if(debug_solver)cout << "ibndz.size(): " << ibndz.size() << endl; vector<delphi_integer>().swap(ibndz) ; //ibndz } if (phimap1.size()>0 ){ if(debug_solver)cout << "phimap1.size(): " << phimap1.size() << endl; vector<delphi_real>().swap(phimap1) ; //phimap1 } if (phimap2.size()>0 ){ if(debug_solver)cout << "phimap2.size(): " << phimap2.size() << endl; vector<delphi_real>().swap(phimap2) ; //phimap2 } if (prgiBndyDielecIndex.size()>0 ){ if(debug_solver)cout << "prgiBndyDielecIndex.size(): " << prgiBndyDielecIndex.size() << endl; vector<delphi_integer>().swap(prgiBndyDielecIndex) ; //prgiBndyDielecIndex } if (prgfBndyDielec.size()>0 ){ if(debug_solver)cout << "prgfBndyDielec.size(): " << prgfBndyDielec.size() << endl; vector< vector<delphi_real> >().swap(prgfBndyDielec) ; //prgfBndyDielec } //vector< SDoubleGridValue >& prgdgvCrgBndyGrid; // cgbp(ibc) if (prgdgvCrgBndyGrid.size()>0 ){ if(debug_solver)cout << "prgdgvCrgBndyGrid.size(): " << prgdgvCrgBndyGrid.size() << endl; vector< SDoubleGridValue >().swap(prgdgvCrgBndyGrid) ; //prgdgvCrgBndyGrid } if(debug_solver)cout << "prgfPhiMap.size(): " << prgfPhiMap.size() << endl; if (gaussianBoundaryDensity.size()>0) { if (debug_solver)cout << "gaussianBoundaryDensity.size(): " << gaussianBoundaryDensity.size() << endl; vector< delphi_real >().swap(gaussianBoundaryDensity); //prgdgvCrgBndyGrid } iDielecBndyOdd=0; } if(debug_solver)cout << "iDielecBndyOdd: " << iDielecBndyOdd << endl; validateInput(); setDielecBndySaltMap(); setCrg(); #ifdef VERBOSE cout << timeString << "iepsmp to db, and charging done at "; pTimer->showElapse(); cout << endl; cout << infoString << left << setw(MAXWIDTH) << "Number of grid points assigned charge" << " : " << iCrgedGridSum << endl; #endif if (bEpsOut && iGaussian==0 && iConvolute==0) //----- write dielectric map { unique_ptr<CIO> pio(new CIO()); // smart unique_ptr // pio->writeEpsMap(iAtomNum,iObjectNum,iGrid,fScale,fgBoxCenter,prgigEpsMap,prgbDielecMap,strEpsFile); pio->writeHomoEpsMap(iGrid,repsout, repsin,fScale,fgBoxCenter,prgbDielecMap,strEpsFile); pio.reset(); } if (bEpsOut && iGaussian==1 && iConvolute==0) //----- write dielectric map { unique_ptr<CIO> pio(new CIO()); // smart unique_ptr // pio->writeEpsMap(iAtomNum,iObjectNum,iGrid,fScale,fgBoxCenter,prgigEpsMap,prgbDielecMap,strEpsFile); pio->writeGaussEpsMap(iGrid,repsout, fScale,fgBoxCenter,gepsmp2,strEpsFile); pio.reset(); } //----- the order of calculateRelaxFactor and setBndy cannnot be reverted! prgfPhiMap is used // as temporary array in calculateRelaxFactor... if (bSpectralRadius) { fSpec = fSpectralRadius; cout << infoString << left << setw(MAXWIDTH) << "Using entered value for relaxation of" << " : " << fSpec << endl; } else { fSpec = calculateRelaxFactor(); } int noit = (int)(7.8/log(1.0+sqrt(1-fSpec))); cout << left << setw(MAXWIDTH) << " Estimated iterations to convergence" << " : " << noit << endl; if (bAutoConverge) iLinIterateNum = noit; setBndy(); #ifdef VERBOSE cout << endl; cout << timeString << "Setup time was "; pTimer->showElapse(); cout << endl; #endif if (0.3 < (delphi_real)iCrgBndyGridNum/iBndyGridNum && bAutoConverge) { iLinIterateNum = iLinIterateNum*iCrgBndyGridNum/(0.3*iBndyGridNum); cout << left << setw(MAXWIDTH) << " Re-estimated iterations now " << " : " << iLinIterateNum << endl; } #ifdef VERBOSE cout << timeString << "Now iterating on "; pTimer->showTime(); cout << endl; #endif if (0 == iNonIterateNum || fZero > fIonStrength || inhomo == 1) { if (0 >= iLinIterateNum) throw CZeorLinIterateNum(bAutoConverge,iLinIterateNum); itit(); } else { if (50 < noit || 0 >= iLinIterateNum) { iLinIterateNum = noit/2; cout << left << setw(MAXWIDTH) << " Re-estimated iterations now " << " : " << iLinIterateNum << endl; } delphi_real qfact = abs(fNetCrg)*(delphi_real)iCrgBndyGridNum/iBndyGridNum; nitit(qfact); } }
[ "delphi001@clemson.edu" ]
delphi001@clemson.edu
222335756919257c659e37bea075cd6c7c9c0ad0
2cf838b54b556987cfc49f42935f8aa7563ea1f4
/aws-cpp-sdk-comprehend/source/model/DocumentClassifierOutputDataConfig.cpp
ed74aa094ca3efb0988db19b34f914d4056bed3a
[ "MIT", "Apache-2.0", "JSON" ]
permissive
QPC-database/aws-sdk-cpp
d11e9f0ff6958c64e793c87a49f1e034813dac32
9f83105f7e07fe04380232981ab073c247d6fc85
refs/heads/main
2023-06-14T17:41:04.817304
2021-07-09T20:28:20
2021-07-09T20:28:20
384,714,703
1
0
Apache-2.0
2021-07-10T14:16:41
2021-07-10T14:16:41
null
UTF-8
C++
false
false
1,416
cpp
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/comprehend/model/DocumentClassifierOutputDataConfig.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace Comprehend { namespace Model { DocumentClassifierOutputDataConfig::DocumentClassifierOutputDataConfig() : m_s3UriHasBeenSet(false), m_kmsKeyIdHasBeenSet(false) { } DocumentClassifierOutputDataConfig::DocumentClassifierOutputDataConfig(JsonView jsonValue) : m_s3UriHasBeenSet(false), m_kmsKeyIdHasBeenSet(false) { *this = jsonValue; } DocumentClassifierOutputDataConfig& DocumentClassifierOutputDataConfig::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("S3Uri")) { m_s3Uri = jsonValue.GetString("S3Uri"); m_s3UriHasBeenSet = true; } if(jsonValue.ValueExists("KmsKeyId")) { m_kmsKeyId = jsonValue.GetString("KmsKeyId"); m_kmsKeyIdHasBeenSet = true; } return *this; } JsonValue DocumentClassifierOutputDataConfig::Jsonize() const { JsonValue payload; if(m_s3UriHasBeenSet) { payload.WithString("S3Uri", m_s3Uri); } if(m_kmsKeyIdHasBeenSet) { payload.WithString("KmsKeyId", m_kmsKeyId); } return payload; } } // namespace Model } // namespace Comprehend } // namespace Aws
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
d3a4e3d25ef8b02ca685f2c962914e9ff424f291
9eb566566bf1f4ef10b56cf1165dff12e0549d19
/Unit1.cpp
49b6bbaea9b403fbaa6b61be55e71454c19a7998
[]
no_license
swnuwangyun/InnerClassAndOuterPrivateMembers
0e9671b03acb74698873316d763ee0f6374d0ffc
6ba33dbd9a9941799c13d28667e2943beb4321ba
refs/heads/master
2021-01-17T05:27:01.712364
2016-09-09T01:42:37
2016-09-09T01:42:37
29,811,780
0
0
null
null
null
null
UTF-8
C++
false
false
842
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "Unit1.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm1 *Form1; //--------------------------------------------------------------------------- __fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) { this->privateVar = L"privateVar"; this->publicVar = L"publicVar"; } //--------------------------------------------------------------------------- void __fastcall TForm1::Button1Click(TObject *Sender) { struct task{ String run(TForm1 *thiz){ return thiz->privateVar + L" " + thiz->publicVar; } }t; this->Edit1->Text = t.run(this); } //---------------------------------------------------------------------------
[ "swnuwangyun@gmail.com" ]
swnuwangyun@gmail.com
d3a31c84a07bff3d94e6dcf11c0c37f41901a5ea
6716b6292797c29d68ab17b8567a9322109fdf6b
/Liang_etal/oscillatingLinearMotion/0.2_NACA0012_1e-3/system/controlDict
941203ae2771a8aa4b651b39e61d4137a4e41b4f
[]
no_license
pruthvi1991/solver_validation
1af12e1c19c0dc6dfae85419c3994b39ee338125
468e58d57d32e2766e43e888defb19dd127e200d
refs/heads/master
2021-01-25T07:34:39.287505
2015-06-20T01:38:25
2015-06-20T01:38:25
37,448,204
0
1
null
null
null
null
UTF-8
C++
false
false
1,339
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 2.3.0 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "system"; object controlDict; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // libs ( "libOpenFOAM.so" ); application pimpleDyMFoam; startFrom startTime; startTime 0; stopAt endTime; endTime 16; deltaT 1e-3; writeControl adjustableRunTime; writeInterval 0.5; purgeWrite 0; writeFormat binary; writePrecision 10; writeCompression on; timeFormat general; timePrecision 6; runTimeModifiable true; adjustTimeStep no; maxCo 0.9; functions { #include "forceCoeffs" } // ************************************************************************* //
[ "pruthvi.krishnaaa@gmail.com" ]
pruthvi.krishnaaa@gmail.com
d9f3a7899d7a8ffbd1215c200646cd695cfe03f3
fac52aacf1a7145d46f420bb2991528676e3be3f
/SDK/Zombie_Shemagh_Scarf_01_classes.h
a2b3260382813b0e0ead2b31a9cd06845233790d
[]
no_license
zH4x-SDK/zSCUM-SDK
2342afd6ee54f4f0b14b0a0e9e3920d75bdb4fed
711376eb272b220521fec36d84ca78fc11d4802a
refs/heads/main
2023-07-15T16:02:22.649492
2021-08-27T13:44:21
2021-08-27T13:44:21
400,522,163
2
0
null
null
null
null
UTF-8
C++
false
false
668
h
#pragma once // Name: SCUM, Version: 4.20.3 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Zombie_Shemagh_Scarf_01.Zombie_Shemagh_Scarf_01_C // 0x0000 (0x0928 - 0x0928) class AZombie_Shemagh_Scarf_01_C : public AClothesItem { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass Zombie_Shemagh_Scarf_01.Zombie_Shemagh_Scarf_01_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
ee04c0ee2f08046bd05a815b52fbe5912c22c625
b111b77f2729c030ce78096ea2273691b9b63749
/perf-native-large/project550/src/testComponent502/cpp/lib6.cpp
949eadbba99d988fd9d782f4838e0510ce816163
[]
no_license
WeilerWebServices/Gradle
a1a55bdb0dd39240787adf9241289e52f593ccc1
6ab6192439f891256a10d9b60f3073cab110b2be
refs/heads/master
2023-01-19T16:48:09.415529
2020-11-28T13:28:40
2020-11-28T13:28:40
256,249,773
1
0
null
null
null
null
UTF-8
C++
false
false
126
cpp
#include <stdio.h> #include <testComponent502/lib1.h> int testComponent502_6 () { printf("Hello world!\n"); return 0; }
[ "nateweiler84@gmail.com" ]
nateweiler84@gmail.com
89b5dd01afb82e127944716a999579ad18b32a7d
a04e0c3fcba8b85befa414d726ef2863b98cb013
/esercizi/3/esercizio7.1/main.cpp
6cbe69a42bb516b521d55efff6b0c167e02e875f
[]
no_license
gfugante/Numerical-Treatment-of-Experimental-Data-TNDS-2018
df6e85c9d88ec804ee3af4f4dbc463becd193588
e11a488b53990ae5c14e110fecdefef3de186cf3
refs/heads/master
2023-07-13T16:02:16.433019
2021-08-25T14:21:01
2021-08-25T14:21:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
585
cpp
#include <iostream> #include <math.h> #include "integrale.hpp" #include "funzionebase.h" #include "trigonometric.hpp" #include <cmath> #include <fstream> using namespace std; ofstream out; int main() { double a=0; double b=M_PI; FunzioneBase *seno=new Seno(); Integral *integrale=new Integral(a,b,seno); double risultato=2; out.open ("errore.txt"); out<<"N:"<<" "<<"Errore:"<<endl; for(int n=10; n<100001; n=n+10){ double simpson=integrale->Simpson(n); out<<n<<" "<<simpson-risultato<<endl; } out.close(); return 0; }
[ "gianlucafugante@MBP-di-Gianluca.fritz.box" ]
gianlucafugante@MBP-di-Gianluca.fritz.box
e20e5a3e226bb5f024c8969c0eaafcff24810b7f
d3affeadad9619cda35d5cd8674e503be203ac29
/finalproject/src/hw_soln/fire_module/solution1/syn/systemc/FIFO_fire2_matrix_e3x3_stream_o_33_V.h
6a7ec268bd427e25f970688cb6c2430fa739e2c1
[]
no_license
chl218/FPGA-for-Computer-Vision
800c98ebf6df4d8ec1818698d401f88dd448fe79
9ccad894bf7ac59d9f4c33afcd385ea3f47bf938
refs/heads/master
2021-01-20T02:42:47.126346
2017-05-02T05:07:10
2017-05-02T05:07:10
89,445,626
0
0
null
null
null
null
UTF-8
C++
false
false
5,829
h
// ============================================================== // File generated by Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC // Version: 2015.4 // Copyright (C) 2015 Xilinx Inc. All rights reserved. // // ============================================================== #ifndef FIFO_fire2_matrix_e3x3_stream_o_33_V_HH_ #define FIFO_fire2_matrix_e3x3_stream_o_33_V_HH_ #include <systemc> using namespace std; SC_MODULE(FIFO_fire2_matrix_e3x3_stream_o_33_V) { static const unsigned int DATA_WIDTH = 32; static const unsigned int ADDR_WIDTH = 1; static const unsigned int FIFO_fire2_matrix_e3x3_stream_o_33_V_depth = 2; sc_core::sc_in_clk clk; sc_core::sc_in< sc_dt::sc_logic > reset; sc_core::sc_out< sc_dt::sc_logic > if_empty_n; sc_core::sc_in< sc_dt::sc_logic > if_read_ce; sc_core::sc_in< sc_dt::sc_logic > if_read; sc_core::sc_out< sc_dt::sc_lv<DATA_WIDTH> > if_dout; sc_core::sc_out< sc_dt::sc_logic > if_full_n; sc_core::sc_in< sc_dt::sc_logic > if_write_ce; sc_core::sc_in< sc_dt::sc_logic > if_write; sc_core::sc_in< sc_dt::sc_lv<DATA_WIDTH> > if_din; sc_core::sc_signal< sc_dt::sc_logic > internal_empty_n; sc_core::sc_signal< sc_dt::sc_logic > internal_full_n; sc_core::sc_signal< sc_dt::sc_lv<DATA_WIDTH> > mStorage[FIFO_fire2_matrix_e3x3_stream_o_33_V_depth]; sc_core::sc_signal< sc_dt::sc_uint<ADDR_WIDTH> > mInPtr; sc_core::sc_signal< sc_dt::sc_uint<ADDR_WIDTH> > mOutPtr; sc_core::sc_signal< sc_dt::sc_uint<1> > mFlag_nEF_hint; sc_core::sc_trace_file* mTrace; SC_CTOR(FIFO_fire2_matrix_e3x3_stream_o_33_V) : mTrace(0) { const char* dump_vcd = std::getenv("AP_WRITE_VCD"); if (dump_vcd && string(dump_vcd) == "1") { std::string tracefn = "sc_trace_" + std::string(name()); mTrace = sc_core::sc_create_vcd_trace_file( tracefn.c_str()); sc_trace(mTrace, clk, "(port)clk"); sc_trace(mTrace, reset, "(port)reset"); sc_trace(mTrace, if_full_n, "(port)if_full_n"); sc_trace(mTrace, if_write_ce, "(port)if_write_ce"); sc_trace(mTrace, if_write, "(port)if_write"); sc_trace(mTrace, if_din, "(port)if_din"); sc_trace(mTrace, if_empty_n, "(port)if_empty_n"); sc_trace(mTrace, if_read_ce, "(port)if_read_ce"); sc_trace(mTrace, if_read, "(port)if_read"); sc_trace(mTrace, if_dout, "(port)if_dout"); sc_trace(mTrace, mInPtr, "mInPtr"); sc_trace(mTrace, mOutPtr, "mOutPtr"); sc_trace(mTrace, mFlag_nEF_hint, "mFlag_nEF_hint"); } mInPtr = 0; mOutPtr = 0; mFlag_nEF_hint = 0; SC_METHOD(proc_read_write); sensitive << clk.pos(); SC_METHOD(proc_dout); sensitive << mOutPtr; for (unsigned i = 0; i < FIFO_fire2_matrix_e3x3_stream_o_33_V_depth; i++) { sensitive << mStorage[i]; } SC_METHOD(proc_ptr); sensitive << mInPtr << mOutPtr<< mFlag_nEF_hint; SC_METHOD(proc_status); sensitive << internal_empty_n << internal_full_n; } ~FIFO_fire2_matrix_e3x3_stream_o_33_V() { if (mTrace) sc_core::sc_close_vcd_trace_file(mTrace); } void proc_status() { if_empty_n.write(internal_empty_n.read()); if_full_n.write(internal_full_n.read()); } void proc_read_write() { if (reset.read() == sc_dt::SC_LOGIC_1) { mInPtr.write(0); mOutPtr.write(0); mFlag_nEF_hint.write(0); } else { if (if_read_ce.read() == sc_dt::SC_LOGIC_1 && if_read.read() == sc_dt::SC_LOGIC_1 && internal_empty_n.read() == sc_dt::SC_LOGIC_1) { sc_dt::sc_uint<ADDR_WIDTH> ptr; if (mOutPtr.read().to_uint() == (FIFO_fire2_matrix_e3x3_stream_o_33_V_depth-1)) { ptr = 0; mFlag_nEF_hint.write(~mFlag_nEF_hint.read()); } else { ptr = mOutPtr.read(); ptr++; } assert(ptr.to_uint() < FIFO_fire2_matrix_e3x3_stream_o_33_V_depth); mOutPtr.write(ptr); } if (if_write_ce.read() == sc_dt::SC_LOGIC_1 && if_write.read() == sc_dt::SC_LOGIC_1 && internal_full_n.read() == sc_dt::SC_LOGIC_1) { sc_dt::sc_uint<ADDR_WIDTH> ptr; ptr = mInPtr.read(); mStorage[ptr.to_uint()].write(if_din.read()); if (ptr.to_uint() == (FIFO_fire2_matrix_e3x3_stream_o_33_V_depth-1)) { ptr = 0; mFlag_nEF_hint.write(~mFlag_nEF_hint.read()); } else { ptr++; assert(ptr.to_uint() < FIFO_fire2_matrix_e3x3_stream_o_33_V_depth); } mInPtr.write(ptr); } } } void proc_dout() { sc_dt::sc_uint<ADDR_WIDTH> ptr = mOutPtr.read(); if (ptr.to_uint() > FIFO_fire2_matrix_e3x3_stream_o_33_V_depth) { if_dout.write(sc_dt::sc_lv<DATA_WIDTH>()); } else { if_dout.write(mStorage[ptr.to_uint()]); } } void proc_ptr() { if (mInPtr.read() == mOutPtr.read() && mFlag_nEF_hint.read().to_uint()==0) { internal_empty_n.write(sc_dt::SC_LOGIC_0); } else { internal_empty_n.write(sc_dt::SC_LOGIC_1); } if (mInPtr.read() == mOutPtr.read() && mFlag_nEF_hint.read().to_uint()==1) { internal_full_n.write(sc_dt::SC_LOGIC_0); } else { internal_full_n.write(sc_dt::SC_LOGIC_1); } } }; #endif //FIFO_fire2_matrix_e3x3_stream_o_33_V_HH_
[ "chl218@eng.ucsd.edu" ]
chl218@eng.ucsd.edu
dcbce2d6e74c0db8655bf9ba5b76016d690908f6
6ed471f36e5188f77dc61cca24daa41496a6d4a0
/SDK/MovieSceneCore_parameters.h
72fc693b067e81a6b24da0daf5c597c0b5d7ec70
[]
no_license
zH4x-SDK/zARKSotF-SDK
77bfaf9b4b9b6a41951ee18db88f826dd720c367
714730f4bb79c07d065181caf360d168761223f6
refs/heads/main
2023-07-16T22:33:15.140456
2021-08-27T13:40:06
2021-08-27T13:40:06
400,521,086
0
0
null
null
null
null
UTF-8
C++
false
false
1,202
h
#pragma once #include "../SDK.h" // Name: ARKSotF, Version: 178.8.0 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Parameters //--------------------------------------------------------------------------- // Function MovieSceneCore.RuntimeMovieScenePlayer.Play struct URuntimeMovieScenePlayer_Play_Params { }; // Function MovieSceneCore.RuntimeMovieScenePlayer.Pause struct URuntimeMovieScenePlayer_Pause_Params { }; // Function MovieSceneCore.RuntimeMovieScenePlayer.CreateRuntimeMovieScenePlayer struct URuntimeMovieScenePlayer_CreateRuntimeMovieScenePlayer_Params { class ULevel* Level; // (Parm, ZeroConstructor, IsPlainOldData) class UMovieSceneBindings* InMovieSceneBindings; // (Parm, ZeroConstructor, IsPlainOldData) class URuntimeMovieScenePlayer* ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
3c9c31485b98f807ae81ccb36bbcf2db83f22902
7a1d0d9115761d97bfb1428b8baa015417dd567c
/src/main.cpp
7ba894e9d44b735098489e33b80f5e57a39acbe3
[]
no_license
TomoyukiOhe/OFWebCamera
da1aa6e13571f6a74321c6d0dcff888da2a12445
d70e6ada7f7f00419fb34f2f35a106ae764a854b
refs/heads/master
2021-01-20T11:59:38.623131
2015-05-13T04:36:52
2015-05-13T04:36:52
35,525,210
0
0
null
null
null
null
UTF-8
C++
false
false
408
cpp
#include "ofMain.h" #include "ofApp.h" //======================================================================== int main( ){ // ofSetupOpenGL(1024,768, OF_WINDOW); // <-------- setup the GL context ofSetupOpenGL(640,480, OF_WINDOW); // this kicks off the running of my app // can be OF_WINDOW or OF_FULLSCREEN // pass in width and height too: ofRunApp( new ofApp()); }
[ "morujomamu@yahoo.co.jp" ]
morujomamu@yahoo.co.jp
c21a3d0fbbf731f1d7b899e0839070ba092980c4
c2b706e60cf60e2303af59a6c4c1729683bd1861
/C++11/RAII.cpp
a2457a4767a40e727df372a3f414b603536272e7
[]
no_license
MeowDada/Cpp-Playground
00e8b5d804cbd2c6ceec9cbcd9b2220cd2ac0895
00902d40f02599b12640cab68310b8636b048817
refs/heads/master
2020-07-29T08:51:54.544214
2019-10-01T10:47:13
2019-10-01T10:47:13
209,736,258
0
0
null
null
null
null
UTF-8
C++
false
false
631
cpp
#include <map> #include <memory> #include <string> #include <vector> int main() { /* RAII = Resouce Acquisition Is Initialization */ /* The code below will internally manage some dynamically allocated memory. They are all, however, implemented such that they deallocate the memory when they are destroyed. This practice is know as RAII */ std::vector<int> vec = { 1, 2, 3, 4, 5 }; std::map<std::string, int> map = {{"Foo",10}, {"Bar",20}}; std::string str = "some text"; std::unique_ptr<int> ptr1 = std::make_unique<int>(8); std::shared_ptr<int> ptr2 = std::make_shared<int>(16); }
[ "chang.hungjui1251@gmail.com" ]
chang.hungjui1251@gmail.com
3b3354c811557776a6ec1dbff5acce261e50a2d5
5509788aa5c5bacc053ea21796d3ef5ba878d744
/Practice/2017/2017.5.2/CJOJ 1098-1.cpp
dab37236ad59b51dc2a82d65e108ae6ad785084a
[ "MIT" ]
permissive
SYCstudio/OI
3c5a6a9c5c9cd93ef653ad77477ad1cd849b8930
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
refs/heads/master
2021-06-25T22:29:50.276429
2020-10-26T11:57:06
2020-10-26T11:57:06
108,716,217
3
0
null
null
null
null
UTF-8
C++
false
false
2,602
cpp
#include<iostream> #include<cstdio> #include<cstdlib> #include<queue> #include<cstring> using namespace std; const int maxN=1001; const int maxM=10001; const int inf=2147483647; int n,m=0; bool flag; int V[maxM]; int W[maxM]; int First[maxN]; int Last[maxN]; int Next[maxM]; int In[maxN]; int Dist[maxN]; bool vis[maxN]; void init(); void Add_Edge(int u,int v,int w); void OK(); void dfs(int u); int main() { init(); int ml,md; int a,b,d; cin>>n>>ml>>md; for (int i=1;i<=ml;i++) { cin>>a>>b>>d; Add_Edge(b,a,d); In[a]++; } for (int i=1;i<=md;i++) { cin>>a>>b>>d; Add_Edge(a,b,-d); In[b]++; } OK(); queue<int> Q; for (int i=1;i<=n;i++) if (In[i]==0) { //cout<<"push"<<endl; Q.push(i); Dist[i]=0; vis[i]=1; } else Dist[i]=inf; do { int u=Q.front(); vis[u]=0; Q.pop(); for (int i=First[u];i!=-1;i=Next[i]) { int v=V[i]; int w=W[i]; if (Dist[v]>Dist[u]+w) { Dist[v]=Dist[u]+w; if (vis[v]==0) { vis[v]=1; Q.push(v); } } } } while (Q.empty()!=1); //for (int i=1;i<=n;i++) // cout<<Dist[i]<<' '; //cout<<endl; if (Dist[1]==inf) cout<<-2<<endl; else cout<<Dist[1]<<endl; return 0; } void init() { memset(First,-1,sizeof(First)); memset(Next,-1,sizeof(Next)); memset(In,0,sizeof(In)); memset(vis,0,sizeof(vis)); } void Add_Edge(int u,int v,int w) { m++; V[m]=v; W[m]=w; if(First[u]==-1) { First[u]=m; Last[u]=m; } else { Next[Last[u]]=m; Last[u]=m; } return; } void OK() { flag=0; for (int i=1;i<=n;i++) if (In[i]==0) { flag=1; dfs(i); } if (flag==0) { cout<<-1<<endl; exit(0); } memset(vis,0,sizeof(vis)); return; } void dfs(int u) { vis[u]=1; for (int i=First[u];i!=-1;i=Next[i]) { int v=V[i]; if (vis[v]==0) { dfs(v); } else { flag=0; cout<<-1<<endl; exit(0); } } vis[u]=0; }
[ "1726016246@qq.com" ]
1726016246@qq.com
e834211eae235bda8d5374028037790e769071f9
72db6cd99efbce079979de388b4b4fcb1795a312
/Tank_Game/Source/Tank_Game/Public/TankBarrel.h
1d3b0b0f13ecd9c2a4b2e7c61e94ad98cef4662a
[]
no_license
Shawn-Gallea123/Tank_Game
b40a43ab90fcc56867ac6f76e95e6138d5000ca8
df6ae9286cb0afae6b173d4cdcd159e9b3ebc012
refs/heads/master
2021-03-24T13:51:31.326129
2018-05-15T00:30:09
2018-05-15T00:30:09
96,841,690
0
0
null
null
null
null
UTF-8
C++
false
false
704
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Components/StaticMeshComponent.h" #include "TankBarrel.generated.h" /** * */ UCLASS(meta = (BlueprintSpawnableComponent)) class TANK_GAME_API UTankBarrel : public UStaticMeshComponent { GENERATED_BODY() public: // -1 is max downward movement, +1 is max upward movement void Elevate(float RelativeSpeed); private: UPROPERTY(EditDefaultsOnly, Category = Setup) float MaxDegreesPerSecond = 5.0; UPROPERTY(EditDefaultsOnly, Category = Setup) float MaxElevationDegrees = 40.0; UPROPERTY(EditDefaultsOnly, Category = Setup) float MinElevationDegrees = 0.0; };
[ "shawngallea@gmail.com" ]
shawngallea@gmail.com