blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2 values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260 values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80 values | src_encoding stringclasses 28 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 8 9.86M | extension stringclasses 52 values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5ee1065ace67716a2eebcfc862753ade23459812 | b2adab7ad93d1afc5be1654f3ed2f0bdd3fbbacf | /Ivaldi/Source/GPUClient/VertexBuffer.h | d463a8bb2378a6e1a3c6b8b5df94033e8c3d7d5e | [] | no_license | vyeresko/ivaldi | 3004ed49249c99a51061142088d98aa1edc5ddd5 | fb717f0aa4bc63915b6ecfdf6a00085969c93eab | refs/heads/master | 2020-05-14T20:55:28.702774 | 2019-04-17T19:12:36 | 2019-04-17T19:12:36 | 181,952,426 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 375 | h | #pragma once
#include "Core.h"
#include "GPUClient/ShaderInputLayout.h"
namespace ivaldi {
namespace gpu {
class VertexBuffer {
public:
friend class GPUClient;
VertexBuffer() = default;
virtual ~VertexBuffer() = default;
virtual void copyData(const std::vector<float> &data) = 0;
virtual void bind() = 0;
virtual void unbind() = 0;
};
}
} | [
"vyeresko@gmail.com"
] | vyeresko@gmail.com |
05996d0d6c8ca87172fdb24b4a0f304c7deefa88 | c773732bc141c8ad6861127ae5024f4b71b901b2 | /Arithmetic/cpp/qsort.cpp | 094b04758d308319c56fe7d95c0375f6b945ccd9 | [] | no_license | agmi/code | ac938b85a1fcd1e070c0f1a863b176a3ddd9eb88 | aa2af3bef2ffb3209c6ac11b7cf3435edf683c8e | refs/heads/master | 2021-01-17T17:06:54.607710 | 2014-04-20T17:26:52 | 2014-04-20T17:26:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 905 | cpp | #include <iostream>
using namespace std;
int parition(int list[], int low, int high){
int pivot = low;
int middle = list[low];
while(low<high){
if(list[low] < middle){
int tmp = list[low];
list[low] = list[pivot];
list[pivot] = tmp;
pivot = low;
low++;
}
else if(list[low] > middle){
int i =0;
for(i=high;i>low;i--){
if(list[i]<middle){
int tmp = list[i];
list[i] = list[low];
list[low] = tmp;
break;
}
}
if(i==low){
break;
}
}
else{
low++;
}
}
return pivot;
}
void qsort(int list[], int low, int high){
if(low < high){
int pivot = parition(list,low,high);
qsort(list,0,pivot-1);
qsort(list,pivot+1, high);
}
}
int main(void){
int list[] = {0,-2,11,-4,13,-5,14,-43};
qsort(list,0,7);
std::cout << std::endl;
for(int i=0;i<8;i++){
std::cout << list[i] << " ";
}
std::cout << std::endl;
return 0;
}
| [
"agilemichael@gmail.com"
] | agilemichael@gmail.com |
3c92a16a3f94e52aa4468dc25b0a23ab5afe940c | 3e79ef0c47b8cb95f847dc090d1a46cda2489d60 | /src/media/PacketQueue.cpp | 34944b6429f491f376ab293f2b090da85e7d3951 | [] | no_license | mehome/ffmpeg_media | b4315a418bb509135b3849ced92efd2f331cf7f7 | 8b28de8e56b58ca4308fea18f4d65e58ee198f5a | refs/heads/master | 2022-12-17T09:22:12.170830 | 2020-09-11T09:17:11 | 2020-09-11T09:17:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 809 | cpp | #include "PacketQueue.h"
#ifdef __cplusplus
extern "C" {
#endif
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libswscale/swscale.h>
#include <libavutil/imgutils.h>
#include <libswresample/swresample.h>
#ifdef __cplusplus
};
#endif
PacketQueue::PacketQueue()
{
}
bool PacketQueue::push(const AVPacketPtr& packet)
{
m_queue.push(packet);
++m_nb_packets;
m_packetSize += packet->size;
return true;
}
bool PacketQueue::pop(AVPacketPtr& packet)
{
if (m_queue.size())
{
packet = m_queue.front();
m_packetSize -= packet->size;
--m_nb_packets;
m_queue.pop();
return true;
}
return false;
}
void PacketQueue::clear()
{
m_queue.swap(std::queue<AVPacketPtr>());
m_nb_packets = 0;
m_packetSize = 0;
}
| [
"qiudaowen@yy.com"
] | qiudaowen@yy.com |
564266920f094946f5455e27f5d6dcecf494e09b | b12585f232e90a61715b6258e063c616d9dd7719 | /source/lib/dng_sdk/dng_shared.cpp | 8c96c8115f9a58c66f126b47a874744c4f0bc335 | [
"BSD-3-Clause",
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | supertobi/gpr | e55d68e23952f942370d7677b460dd25bc970537 | db9cacfd1f9234ffe2501870989d5872c50876f9 | refs/heads/master | 2023-08-13T10:23:47.332996 | 2021-09-28T08:06:12 | 2021-09-28T08:06:12 | 410,865,814 | 0 | 0 | NOASSERTION | 2021-09-27T11:58:26 | 2021-09-27T11:58:26 | null | UTF-8 | C++ | false | false | 60,322 | cpp | /*****************************************************************************/
// Copyright 2006-2008 Adobe Systems Incorporated
// All Rights Reserved.
//
// NOTICE: Adobe permits you to use, modify, and distribute this file in
// accordance with the terms of the Adobe license agreement accompanying it.
/*****************************************************************************/
/* $Id: //mondo/dng_sdk_1_4/dng_sdk/source/dng_shared.cpp#2 $ */
/* $DateTime: 2012/06/14 20:24:41 $ */
/* $Change: 835078 $ */
/* $Author: tknoll $ */
/*****************************************************************************/
#include "dng_shared.h"
#include "dng_camera_profile.h"
#include "dng_exceptions.h"
#include "dng_globals.h"
#include "dng_parse_utils.h"
#include "dng_tag_codes.h"
#include "dng_tag_types.h"
#include "dng_tag_values.h"
#include "dng_utils.h"
/*****************************************************************************/
dng_camera_profile_info::dng_camera_profile_info ()
: fBigEndian (false)
, fColorPlanes (0)
, fCalibrationIlluminant1 (lsUnknown)
, fCalibrationIlluminant2 (lsUnknown)
, fColorMatrix1 ()
, fColorMatrix2 ()
, fForwardMatrix1 ()
, fForwardMatrix2 ()
, fReductionMatrix1 ()
, fReductionMatrix2 ()
, fProfileCalibrationSignature ()
, fProfileName ()
, fProfileCopyright ()
, fEmbedPolicy (pepAllowCopying)
, fProfileHues (0)
, fProfileSats (0)
, fProfileVals (0)
, fHueSatDeltas1Offset (0)
, fHueSatDeltas1Count (0)
, fHueSatDeltas2Offset (0)
, fHueSatDeltas2Count (0)
, fHueSatMapEncoding (encoding_Linear)
, fLookTableHues (0)
, fLookTableSats (0)
, fLookTableVals (0)
, fLookTableOffset (0)
, fLookTableCount (0)
, fLookTableEncoding (encoding_Linear)
, fBaselineExposureOffset (0, 100)
, fDefaultBlackRender (defaultBlackRender_Auto)
, fToneCurveOffset (0)
, fToneCurveCount (0)
, fUniqueCameraModel ()
{
}
/*****************************************************************************/
dng_camera_profile_info::~dng_camera_profile_info ()
{
}
/*****************************************************************************/
bool dng_camera_profile_info::ParseTag (dng_stream &stream,
uint32 parentCode,
uint32 tagCode,
uint32 tagType,
uint32 tagCount,
uint64 tagOffset)
{
switch (tagCode)
{
case tcCalibrationIlluminant1:
{
CheckTagType (parentCode, tagCode, tagType, ttShort);
CheckTagCount (parentCode, tagCode, tagCount, 1);
fCalibrationIlluminant1 = stream.TagValue_uint32 (tagType);
#if qDNGValidate
if (gVerbose)
{
printf ("CalibrationIlluminant1: %s\n",
LookupLightSource (fCalibrationIlluminant1));
}
#endif
break;
}
case tcCalibrationIlluminant2:
{
CheckTagType (parentCode, tagCode, tagType, ttShort);
CheckTagCount (parentCode, tagCode, tagCount, 1);
fCalibrationIlluminant2 = stream.TagValue_uint32 (tagType);
#if qDNGValidate
if (gVerbose)
{
printf ("CalibrationIlluminant2: %s\n",
LookupLightSource (fCalibrationIlluminant2));
}
#endif
break;
}
case tcColorMatrix1:
{
CheckTagType (parentCode, tagCode, tagType, ttSRational);
if (fColorPlanes == 0)
{
fColorPlanes = Pin_uint32 (0, tagCount / 3, kMaxColorPlanes);
}
if (!CheckColorImage (parentCode, tagCode, fColorPlanes))
return false;
if (!ParseMatrixTag (stream,
parentCode,
tagCode,
tagType,
tagCount,
fColorPlanes,
3,
fColorMatrix1))
return false;
#if qDNGValidate
if (gVerbose)
{
printf ("ColorMatrix1:\n");
DumpMatrix (fColorMatrix1);
}
#endif
break;
}
case tcColorMatrix2:
{
CheckTagType (parentCode, tagCode, tagType, ttSRational);
// Kludge - Hasselblad FFF files are very DNG-like, but sometimes
// only have a ColorMatrix2 tag and no ColorMatrix1 tag.
bool hasselbladHack = (fColorPlanes == 0);
if (hasselbladHack)
{
fColorPlanes = Pin_uint32 (0, tagCount / 3, kMaxColorPlanes);
#if qDNGValidate
ReportWarning ("ColorMatrix2 without ColorMatrix1");
#endif
}
if (!CheckColorImage (parentCode, tagCode, fColorPlanes))
return false;
if (!ParseMatrixTag (stream,
parentCode,
tagCode,
tagType,
tagCount,
fColorPlanes,
3,
fColorMatrix2))
return false;
#if qDNGValidate
if (gVerbose)
{
printf ("ColorMatrix2:\n");
DumpMatrix (fColorMatrix2);
}
#endif
if (hasselbladHack)
{
fColorMatrix1 = fColorMatrix2;
fColorMatrix2 = dng_matrix ();
}
break;
}
case tcForwardMatrix1:
{
CheckTagType (parentCode, tagCode, tagType, ttSRational);
if (!CheckColorImage (parentCode, tagCode, fColorPlanes))
return false;
if (!ParseMatrixTag (stream,
parentCode,
tagCode,
tagType,
tagCount,
3,
fColorPlanes,
fForwardMatrix1))
return false;
#if qDNGValidate
if (gVerbose)
{
printf ("ForwardMatrix1:\n");
DumpMatrix (fForwardMatrix1);
}
#endif
break;
}
case tcForwardMatrix2:
{
CheckTagType (parentCode, tagCode, tagType, ttSRational);
if (!CheckColorImage (parentCode, tagCode, fColorPlanes))
return false;
if (!ParseMatrixTag (stream,
parentCode,
tagCode,
tagType,
tagCount,
3,
fColorPlanes,
fForwardMatrix2))
return false;
#if qDNGValidate
if (gVerbose)
{
printf ("ForwardMatrix2:\n");
DumpMatrix (fForwardMatrix2);
}
#endif
break;
}
case tcReductionMatrix1:
{
CheckTagType (parentCode, tagCode, tagType, ttSRational);
if (!CheckColorImage (parentCode, tagCode, fColorPlanes))
return false;
if (!ParseMatrixTag (stream,
parentCode,
tagCode,
tagType,
tagCount,
3,
fColorPlanes,
fReductionMatrix1))
return false;
#if qDNGValidate
if (gVerbose)
{
printf ("ReductionMatrix1:\n");
DumpMatrix (fReductionMatrix1);
}
#endif
break;
}
case tcReductionMatrix2:
{
CheckTagType (parentCode, tagCode, tagType, ttSRational);
if (!CheckColorImage (parentCode, tagCode, fColorPlanes))
return false;
if (!ParseMatrixTag (stream,
parentCode,
tagCode,
tagType,
tagCount,
3,
fColorPlanes,
fReductionMatrix2))
return false;
#if qDNGValidate
if (gVerbose)
{
printf ("ReductionMatrix2:\n");
DumpMatrix (fReductionMatrix2);
}
#endif
break;
}
case tcProfileCalibrationSignature:
{
CheckTagType (parentCode, tagCode, tagType, ttAscii, ttByte);
ParseStringTag (stream,
parentCode,
tagCode,
tagCount,
fProfileCalibrationSignature,
false);
#if qDNGValidate
if (gVerbose)
{
printf ("ProfileCalibrationSignature: ");
DumpString (fProfileCalibrationSignature);
printf ("\n");
}
#endif
break;
}
case tcProfileName:
{
CheckTagType (parentCode, tagCode, tagType, ttAscii, ttByte);
ParseStringTag (stream,
parentCode,
tagCode,
tagCount,
fProfileName,
false);
#if qDNGValidate
if (gVerbose)
{
printf ("ProfileName: ");
DumpString (fProfileName);
printf ("\n");
}
#endif
break;
}
case tcProfileCopyright:
{
CheckTagType (parentCode, tagCode, tagType, ttAscii, ttByte);
ParseStringTag (stream,
parentCode,
tagCode,
tagCount,
fProfileCopyright,
false);
#if qDNGValidate
if (gVerbose)
{
printf ("ProfileCopyright: ");
DumpString (fProfileCopyright);
printf ("\n");
}
#endif
break;
}
case tcProfileEmbedPolicy:
{
CheckTagType (parentCode, tagCode, tagType, ttLong);
CheckTagCount (parentCode, tagCode, tagCount, 1);
fEmbedPolicy = stream.TagValue_uint32 (tagType);
#if qDNGValidate
if (gVerbose)
{
const char *policy;
switch (fEmbedPolicy)
{
case pepAllowCopying:
policy = "Allow copying";
break;
case pepEmbedIfUsed:
policy = "Embed if used";
break;
case pepEmbedNever:
policy = "Embed never";
break;
case pepNoRestrictions:
policy = "No restrictions";
break;
default:
policy = "INVALID VALUE";
}
printf ("ProfileEmbedPolicy: %s\n", policy);
}
#endif
break;
}
case tcProfileHueSatMapDims:
{
CheckTagType (parentCode, tagCode, tagType, ttLong);
CheckTagCount (parentCode, tagCode, tagCount, 2, 3);
fProfileHues = stream.TagValue_uint32 (tagType);
fProfileSats = stream.TagValue_uint32 (tagType);
if (tagCount > 2)
fProfileVals = stream.TagValue_uint32 (tagType);
else
fProfileVals = 1;
#if qDNGValidate
if (gVerbose)
{
printf ("ProfileHueSatMapDims: Hues = %u, Sats = %u, Vals = %u\n",
(unsigned) fProfileHues,
(unsigned) fProfileSats,
(unsigned) fProfileVals);
}
#endif
break;
}
case tcProfileHueSatMapData1:
{
if (!CheckTagType (parentCode, tagCode, tagType, ttFloat))
return false;
bool skipSat0 = (tagCount == fProfileHues *
(fProfileSats - 1) *
fProfileVals * 3);
if (!skipSat0)
{
if (!CheckTagCount (parentCode, tagCode, tagCount, fProfileHues *
fProfileSats *
fProfileVals * 3))
return false;
}
fBigEndian = stream.BigEndian ();
fHueSatDeltas1Offset = tagOffset;
fHueSatDeltas1Count = tagCount;
#if qDNGValidate
if (gVerbose)
{
printf ("ProfileHueSatMapData1:\n");
DumpHueSatMap (stream,
fProfileHues,
fProfileSats,
fProfileVals,
skipSat0);
}
#endif
break;
}
case tcProfileHueSatMapData2:
{
if (!CheckTagType (parentCode, tagCode, tagType, ttFloat))
return false;
bool skipSat0 = (tagCount == fProfileHues *
(fProfileSats - 1) *
fProfileVals * 3);
if (!skipSat0)
{
if (!CheckTagCount (parentCode, tagCode, tagCount, fProfileHues *
fProfileSats *
fProfileVals * 3))
return false;
}
fBigEndian = stream.BigEndian ();
fHueSatDeltas2Offset = tagOffset;
fHueSatDeltas2Count = tagCount;
#if qDNGValidate
if (gVerbose)
{
printf ("ProfileHueSatMapData2:\n");
DumpHueSatMap (stream,
fProfileHues,
fProfileSats,
fProfileVals,
skipSat0);
}
#endif
break;
}
case tcProfileHueSatMapEncoding:
{
CheckTagType (parentCode, tagCode, tagType, ttLong);
CheckTagCount (parentCode, tagCode, tagCount, 1);
fHueSatMapEncoding = stream.TagValue_uint32 (tagType);
#if qDNGValidate
if (gVerbose)
{
const char *encoding = NULL;
switch (fHueSatMapEncoding)
{
case encoding_Linear:
encoding = "Linear";
break;
case encoding_sRGB:
encoding = "sRGB";
break;
default:
encoding = "INVALID VALUE";
}
printf ("ProfileHueSatMapEncoding: %s\n", encoding);
}
#endif
break;
}
case tcProfileLookTableDims:
{
CheckTagType (parentCode, tagCode, tagType, ttLong);
CheckTagCount (parentCode, tagCode, tagCount, 2, 3);
fLookTableHues = stream.TagValue_uint32 (tagType);
fLookTableSats = stream.TagValue_uint32 (tagType);
if (tagCount > 2)
fLookTableVals = stream.TagValue_uint32 (tagType);
else
fLookTableVals = 1;
#if qDNGValidate
if (gVerbose)
{
printf ("ProfileLookTableDims: Hues = %u, Sats = %u, Vals = %u\n",
(unsigned) fLookTableHues,
(unsigned) fLookTableSats,
(unsigned) fLookTableVals);
}
#endif
break;
}
case tcProfileLookTableData:
{
if (!CheckTagType (parentCode, tagCode, tagType, ttFloat))
return false;
bool skipSat0 = (tagCount == fLookTableHues *
(fLookTableSats - 1) *
fLookTableVals * 3);
if (!skipSat0)
{
if (!CheckTagCount (parentCode, tagCode, tagCount, fLookTableHues *
fLookTableSats *
fLookTableVals * 3))
return false;
}
fBigEndian = stream.BigEndian ();
fLookTableOffset = tagOffset;
fLookTableCount = tagCount;
#if qDNGValidate
if (gVerbose)
{
printf ("ProfileLookTableData:\n");
DumpHueSatMap (stream,
fLookTableHues,
fLookTableSats,
fLookTableVals,
skipSat0);
}
#endif
break;
}
case tcProfileLookTableEncoding:
{
CheckTagType (parentCode, tagCode, tagType, ttLong);
CheckTagCount (parentCode, tagCode, tagCount, 1);
fLookTableEncoding = stream.TagValue_uint32 (tagType);
#if qDNGValidate
if (gVerbose)
{
const char *encoding = NULL;
switch (fLookTableEncoding)
{
case encoding_Linear:
encoding = "Linear";
break;
case encoding_sRGB:
encoding = "sRGB";
break;
default:
encoding = "INVALID VALUE";
}
printf ("ProfileLookTableEncoding: %s\n", encoding);
}
#endif
break;
}
case tcBaselineExposureOffset:
{
CheckTagType (parentCode, tagCode, tagType, ttSRational);
CheckTagCount (parentCode, tagCode, tagCount, 1);
fBaselineExposureOffset = stream.TagValue_srational (tagType);
#if qDNGValidate
if (gVerbose)
{
printf ("BaselineExposureOffset: %+0.2f\n",
fBaselineExposureOffset.As_real64 ());
}
#endif
break;
}
case tcDefaultBlackRender:
{
CheckTagType (parentCode, tagCode, tagType, ttLong);
CheckTagCount (parentCode, tagCode, tagCount, 1);
fDefaultBlackRender = stream.TagValue_uint32 (tagType);
#if qDNGValidate
if (gVerbose)
{
const char *setting = NULL;
switch (fDefaultBlackRender)
{
case defaultBlackRender_Auto:
setting = "Auto";
break;
case defaultBlackRender_None:
setting = "None";
break;
default:
setting = "INVALID VALUE";
}
printf ("DefaultBlackRender: %s\n",
setting);
}
#endif
break;
}
case tcProfileToneCurve:
{
if (!CheckTagType (parentCode, tagCode, tagType, ttFloat))
return false;
if (!CheckTagCount (parentCode, tagCode, tagCount, 4, tagCount))
return false;
if ((tagCount & 1) != 0)
{
#if qDNGValidate
{
char message [256];
sprintf (message,
"%s %s has odd count (%u)",
LookupParentCode (parentCode),
LookupTagCode (parentCode, tagCode),
(unsigned) tagCount);
ReportWarning (message);
}
#endif
return false;
}
fBigEndian = stream.BigEndian ();
fToneCurveOffset = tagOffset;
fToneCurveCount = tagCount;
#if qDNGValidate
if (gVerbose)
{
DumpTagValues (stream,
"Coord",
parentCode,
tagCode,
tagType,
tagCount);
}
#endif
break;
}
case tcUniqueCameraModel:
{
// Note: This code is only used when parsing stand-alone
// profiles. The embedded profiles are assumed to be restricted
// to the model they are embedded in.
CheckTagType (parentCode, tagCode, tagType, ttAscii);
ParseStringTag (stream,
parentCode,
tagCode,
tagCount,
fUniqueCameraModel,
false);
bool didTrim = fUniqueCameraModel.TrimTrailingBlanks ();
#if qDNGValidate
if (didTrim)
{
ReportWarning ("UniqueCameraModel string has trailing blanks");
}
if (gVerbose)
{
printf ("UniqueCameraModel: ");
DumpString (fUniqueCameraModel);
printf ("\n");
}
#else
(void) didTrim; // Unused
#endif
break;
}
default:
{
return false;
}
}
return true;
}
/*****************************************************************************/
bool dng_camera_profile_info::ParseExtended (dng_stream &stream)
{
try
{
// Offsets are relative to the start of this structure, not the entire file.
uint64 startPosition = stream.Position ();
// Read header. Like a TIFF header, but with different magic number
// Plus all offsets are relative to the start of the IFD, not to the
// stream or file.
uint16 byteOrder = stream.Get_uint16 ();
if (byteOrder == byteOrderMM)
fBigEndian = true;
else if (byteOrder == byteOrderII)
fBigEndian = false;
else
return false;
TempBigEndian setEndianness (stream, fBigEndian);
uint16 magicNumber = stream.Get_uint16 ();
if (magicNumber != magicExtendedProfile)
{
return false;
}
uint32 offset = stream.Get_uint32 ();
stream.Skip (offset - 8);
// Start on IFD entries.
uint32 ifdEntries = stream.Get_uint16 ();
if (ifdEntries < 1)
{
return false;
}
for (uint32 tag_index = 0; tag_index < ifdEntries; tag_index++)
{
stream.SetReadPosition (startPosition + 8 + 2 + tag_index * 12);
uint16 tagCode = stream.Get_uint16 ();
uint32 tagType = stream.Get_uint16 ();
uint32 tagCount = stream.Get_uint32 ();
uint64 tagOffset = stream.Position ();
if (TagTypeSize (tagType) * tagCount > 4)
{
tagOffset = startPosition + stream.Get_uint32 ();
stream.SetReadPosition (tagOffset);
}
if (!ParseTag (stream,
0,
tagCode,
tagType,
tagCount,
tagOffset))
{
#if qDNGValidate
if (gVerbose)
{
stream.SetReadPosition (tagOffset);
printf ("*");
DumpTagValues (stream,
LookupTagType (tagType),
0,
tagCode,
tagType,
tagCount);
}
#endif
}
}
return true;
}
catch (...)
{
// Eat parsing errors.
}
return false;
}
/*****************************************************************************/
dng_shared::dng_shared ()
: fExifIFD (0)
, fGPSInfo (0)
, fInteroperabilityIFD (0)
, fKodakDCRPrivateIFD (0)
, fKodakKDCPrivateIFD (0)
, fXMPCount (0)
, fXMPOffset (0)
, fIPTC_NAA_Count (0)
, fIPTC_NAA_Offset (0)
, fMakerNoteCount (0)
, fMakerNoteOffset (0)
, fMakerNoteSafety (0)
, fDNGVersion (0)
, fDNGBackwardVersion (0)
, fUniqueCameraModel ()
, fLocalizedCameraModel ()
, fCameraProfile ()
, fExtraCameraProfiles ()
, fCameraCalibration1 ()
, fCameraCalibration2 ()
, fCameraCalibrationSignature ()
, fAnalogBalance ()
, fAsShotNeutral ()
, fAsShotWhiteXY ()
, fBaselineExposure (0, 1)
, fBaselineNoise (1, 1)
, fNoiseReductionApplied (0, 0)
, fBaselineSharpness (1, 1)
, fLinearResponseLimit (1, 1)
, fShadowScale (1, 1)
, fHasBaselineExposure (false)
, fHasShadowScale (false)
, fDNGPrivateDataCount (0)
, fDNGPrivateDataOffset (0)
, fRawImageDigest ()
, fNewRawImageDigest ()
, fRawDataUniqueID ()
, fOriginalRawFileName ()
, fOriginalRawFileDataCount (0)
, fOriginalRawFileDataOffset (0)
, fOriginalRawFileDigest ()
, fAsShotICCProfileCount (0)
, fAsShotICCProfileOffset (0)
, fAsShotPreProfileMatrix ()
, fCurrentICCProfileCount (0)
, fCurrentICCProfileOffset (0)
, fCurrentPreProfileMatrix ()
, fColorimetricReference (crSceneReferred)
, fAsShotProfileName ()
, fNoiseProfile ()
, fOriginalDefaultFinalSize ()
, fOriginalBestQualityFinalSize ()
, fOriginalDefaultCropSizeH ()
, fOriginalDefaultCropSizeV ()
{
}
/*****************************************************************************/
dng_shared::~dng_shared ()
{
}
/*****************************************************************************/
bool dng_shared::ParseTag (dng_stream &stream,
dng_exif &exif,
uint32 parentCode,
bool /* isMainIFD */,
uint32 tagCode,
uint32 tagType,
uint32 tagCount,
uint64 tagOffset,
int64 /* offsetDelta */)
{
if (parentCode == 0)
{
if (Parse_ifd0 (stream,
exif,
parentCode,
tagCode,
tagType,
tagCount,
tagOffset))
{
return true;
}
}
if (parentCode == 0 ||
parentCode == tcExifIFD)
{
if (Parse_ifd0_exif (stream,
exif,
parentCode,
tagCode,
tagType,
tagCount,
tagOffset))
{
return true;
}
}
return false;
}
/*****************************************************************************/
// Parses tags that should only appear in IFD 0.
bool dng_shared::Parse_ifd0 (dng_stream &stream,
dng_exif & /* exif */,
uint32 parentCode,
uint32 tagCode,
uint32 tagType,
uint32 tagCount,
uint64 tagOffset)
{
switch (tagCode)
{
case tcXMP:
{
CheckTagType (parentCode, tagCode, tagType, ttByte, ttUndefined);
fXMPCount = tagCount;
fXMPOffset = fXMPCount ? tagOffset : 0;
#if qDNGValidate
if (gVerbose)
{
printf ("XMP: Count = %u, Offset = %u\n",
(unsigned) fXMPCount,
(unsigned) fXMPOffset);
if (fXMPCount)
{
DumpXMP (stream, fXMPCount);
}
}
#endif
break;
}
case tcIPTC_NAA:
{
CheckTagType (parentCode, tagCode, tagType, ttLong, ttAscii, ttUndefined);
fIPTC_NAA_Count = tagCount * TagTypeSize (tagType);
fIPTC_NAA_Offset = fIPTC_NAA_Count ? tagOffset : 0;
#if qDNGValidate
if (gVerbose)
{
printf ("IPTC/NAA: Count = %u, Offset = %u\n",
(unsigned) fIPTC_NAA_Count,
(unsigned) fIPTC_NAA_Offset);
if (fIPTC_NAA_Count)
{
DumpHexAscii (stream, fIPTC_NAA_Count);
}
// Compute and output the digest.
dng_memory_data buffer (fIPTC_NAA_Count);
stream.SetReadPosition (fIPTC_NAA_Offset);
stream.Get (buffer.Buffer (), fIPTC_NAA_Count);
const uint8 *data = buffer.Buffer_uint8 ();
uint32 count = fIPTC_NAA_Count;
// Method 1: Counting all bytes (this is correct).
{
dng_md5_printer printer;
printer.Process (data, count);
printf ("IPTCDigest: ");
DumpFingerprint (printer.Result ());
printf ("\n");
}
// Method 2: Ignoring zero padding.
{
uint32 removed = 0;
while ((removed < 3) && (count > 0) && (data [count - 1] == 0))
{
removed++;
count--;
}
if (removed != 0)
{
dng_md5_printer printer;
printer.Process (data, count);
printf ("IPTCDigest (ignoring zero padding): ");
DumpFingerprint (printer.Result ());
printf ("\n");
}
}
}
#endif
break;
}
case tcExifIFD:
{
CheckTagType (parentCode, tagCode, tagType, ttLong, ttIFD);
CheckTagCount (parentCode, tagCode, tagCount, 1);
fExifIFD = stream.TagValue_uint32 (tagType);
#if qDNGValidate
if (gVerbose)
{
printf ("ExifIFD: %u\n", (unsigned) fExifIFD);
}
#endif
break;
}
case tcGPSInfo:
{
CheckTagType (parentCode, tagCode, tagType, ttLong, ttIFD);
CheckTagCount (parentCode, tagCode, tagCount, 1);
fGPSInfo = stream.TagValue_uint32 (tagType);
#if qDNGValidate
if (gVerbose)
{
printf ("GPSInfo: %u\n", (unsigned) fGPSInfo);
}
#endif
break;
}
case tcKodakDCRPrivateIFD:
{
CheckTagType (parentCode, tagCode, tagType, ttLong, ttIFD);
CheckTagCount (parentCode, tagCode, tagCount, 1);
fKodakDCRPrivateIFD = stream.TagValue_uint32 (tagType);
#if qDNGValidate
if (gVerbose)
{
printf ("KodakDCRPrivateIFD: %u\n", (unsigned) fKodakDCRPrivateIFD);
}
#endif
break;
}
case tcKodakKDCPrivateIFD:
{
CheckTagType (parentCode, tagCode, tagType, ttLong, ttIFD);
CheckTagCount (parentCode, tagCode, tagCount, 1);
fKodakKDCPrivateIFD = stream.TagValue_uint32 (tagType);
#if qDNGValidate
if (gVerbose)
{
printf ("KodakKDCPrivateIFD: %u\n", (unsigned) fKodakKDCPrivateIFD);
}
#endif
break;
}
case tcDNGVersion:
{
CheckTagType (parentCode, tagCode, tagType, ttByte);
CheckTagCount (parentCode, tagCode, tagCount, 4);
uint32 b0 = stream.Get_uint8 ();
uint32 b1 = stream.Get_uint8 ();
uint32 b2 = stream.Get_uint8 ();
uint32 b3 = stream.Get_uint8 ();
fDNGVersion = (b0 << 24) | (b1 << 16) | (b2 << 8) | b3;
#if qDNGValidate
if (gVerbose)
{
printf ("DNGVersion: %u.%u.%u.%u\n",
(unsigned) b0,
(unsigned) b1,
(unsigned) b2,
(unsigned) b3);
}
#endif
break;
}
case tcDNGBackwardVersion:
{
CheckTagType (parentCode, tagCode, tagType, ttByte);
CheckTagCount (parentCode, tagCode, tagCount, 4);
uint32 b0 = stream.Get_uint8 ();
uint32 b1 = stream.Get_uint8 ();
uint32 b2 = stream.Get_uint8 ();
uint32 b3 = stream.Get_uint8 ();
fDNGBackwardVersion = (b0 << 24) | (b1 << 16) | (b2 << 8) | b3;
#if qDNGValidate
if (gVerbose)
{
printf ("DNGBackwardVersion: %u.%u.%u.%u\n",
(unsigned) b0,
(unsigned) b1,
(unsigned) b2,
(unsigned) b3);
}
#endif
break;
}
case tcUniqueCameraModel:
{
CheckTagType (parentCode, tagCode, tagType, ttAscii);
ParseStringTag (stream,
parentCode,
tagCode,
tagCount,
fUniqueCameraModel,
false);
bool didTrim = fUniqueCameraModel.TrimTrailingBlanks ();
#if qDNGValidate
if (didTrim)
{
ReportWarning ("UniqueCameraModel string has trailing blanks");
}
if (gVerbose)
{
printf ("UniqueCameraModel: ");
DumpString (fUniqueCameraModel);
printf ("\n");
}
#else
(void) didTrim; // Unused
#endif
break;
}
case tcLocalizedCameraModel:
{
CheckTagType (parentCode, tagCode, tagType, ttAscii, ttByte);
ParseStringTag (stream,
parentCode,
tagCode,
tagCount,
fLocalizedCameraModel,
false);
bool didTrim = fLocalizedCameraModel.TrimTrailingBlanks ();
#if qDNGValidate
if (didTrim)
{
ReportWarning ("LocalizedCameraModel string has trailing blanks");
}
if (gVerbose)
{
printf ("LocalizedCameraModel: ");
DumpString (fLocalizedCameraModel);
printf ("\n");
}
#else
(void) didTrim; // Unused
#endif
break;
}
case tcCameraCalibration1:
{
CheckTagType (parentCode, tagCode, tagType, ttSRational);
if (!CheckColorImage (parentCode, tagCode, fCameraProfile.fColorPlanes))
return false;
if (!ParseMatrixTag (stream,
parentCode,
tagCode,
tagType,
tagCount,
fCameraProfile.fColorPlanes,
fCameraProfile.fColorPlanes,
fCameraCalibration1))
return false;
#if qDNGValidate
if (gVerbose)
{
printf ("CameraCalibration1:\n");
DumpMatrix (fCameraCalibration1);
}
#endif
break;
}
case tcCameraCalibration2:
{
CheckTagType (parentCode, tagCode, tagType, ttSRational);
if (!CheckColorImage (parentCode, tagCode, fCameraProfile.fColorPlanes))
return false;
if (!ParseMatrixTag (stream,
parentCode,
tagCode,
tagType,
tagCount,
fCameraProfile.fColorPlanes,
fCameraProfile.fColorPlanes,
fCameraCalibration2))
return false;
#if qDNGValidate
if (gVerbose)
{
printf ("CameraCalibration2:\n");
DumpMatrix (fCameraCalibration2);
}
#endif
break;
}
case tcCameraCalibrationSignature:
{
CheckTagType (parentCode, tagCode, tagType, ttAscii, ttByte);
ParseStringTag (stream,
parentCode,
tagCode,
tagCount,
fCameraCalibrationSignature,
false);
#if qDNGValidate
if (gVerbose)
{
printf ("CameraCalibrationSignature: ");
DumpString (fCameraCalibrationSignature);
printf ("\n");
}
#endif
break;
}
case tcAnalogBalance:
{
CheckTagType (parentCode, tagCode, tagType, ttRational);
// Kludge - Hasselblad FFF files are very DNG-like, but sometimes
// they don't have any ColorMatrix tags.
bool hasselbladHack = (fDNGVersion == 0 &&
fCameraProfile.fColorPlanes == 0);
if (hasselbladHack)
{
fCameraProfile.fColorPlanes = Pin_uint32 (0, tagCount, kMaxColorPlanes);
#if qDNGValidate
ReportWarning ("AnalogBalance without ColorMatrix1");
#endif
}
if (!CheckColorImage (parentCode, tagCode, fCameraProfile.fColorPlanes))
return false;
if (!ParseVectorTag (stream,
parentCode,
tagCode,
tagType,
tagCount,
fCameraProfile.fColorPlanes,
fAnalogBalance))
return false;
#if qDNGValidate
if (gVerbose)
{
printf ("AnalogBalance:");
DumpVector (fAnalogBalance);
}
#endif
break;
}
case tcAsShotNeutral:
{
CheckTagType (parentCode, tagCode, tagType, ttRational);
// Kludge - Hasselblad FFF files are very DNG-like, but sometimes
// they don't have any ColorMatrix tags.
bool hasselbladHack = (fDNGVersion == 0 &&
fCameraProfile.fColorPlanes == 0);
if (hasselbladHack)
{
fCameraProfile.fColorPlanes = Pin_uint32 (0, tagCount, kMaxColorPlanes);
#if qDNGValidate
ReportWarning ("AsShotNeutral without ColorMatrix1");
#endif
}
if (!CheckColorImage (parentCode, tagCode, fCameraProfile.fColorPlanes))
return false;
if (!ParseVectorTag (stream,
parentCode,
tagCode,
tagType,
tagCount,
fCameraProfile.fColorPlanes,
fAsShotNeutral))
return false;
#if qDNGValidate
if (gVerbose)
{
printf ("AsShotNeutral:");
DumpVector (fAsShotNeutral);
}
#endif
break;
}
case tcAsShotWhiteXY:
{
CheckTagType (parentCode, tagCode, tagType, ttRational);
if (!CheckColorImage (parentCode, tagCode, fCameraProfile.fColorPlanes))
return false;
if (!CheckTagCount (parentCode, tagCode, tagCount, 2))
return false;
fAsShotWhiteXY.x = stream.TagValue_real64 (tagType);
fAsShotWhiteXY.y = stream.TagValue_real64 (tagType);
#if qDNGValidate
if (gVerbose)
{
printf ("AsShotWhiteXY: %0.4f %0.4f\n",
fAsShotWhiteXY.x,
fAsShotWhiteXY.y);
}
#endif
break;
}
case tcBaselineExposure:
{
CheckTagType (parentCode, tagCode, tagType, ttSRational);
CheckTagCount (parentCode, tagCode, tagCount, 1);
fBaselineExposure = stream.TagValue_srational (tagType);
fHasBaselineExposure = true;
#if qDNGValidate
if (gVerbose)
{
printf ("BaselineExposure: %+0.2f\n",
fBaselineExposure.As_real64 ());
}
#endif
break;
}
case tcBaselineNoise:
{
CheckTagType (parentCode, tagCode, tagType, ttRational);
CheckTagCount (parentCode, tagCode, tagCount, 1);
fBaselineNoise = stream.TagValue_urational (tagType);
#if qDNGValidate
if (gVerbose)
{
printf ("BaselineNoise: %0.2f\n",
fBaselineNoise.As_real64 ());
}
#endif
break;
}
case tcNoiseReductionApplied:
{
if (!CheckTagType (parentCode, tagCode, tagType, ttRational))
return false;
if (!CheckTagCount (parentCode, tagCode, tagCount, 1))
return false;
fNoiseReductionApplied = stream.TagValue_urational (tagType);
#if qDNGValidate
if (gVerbose)
{
printf ("NoiseReductionApplied: %u/%u\n",
(unsigned) fNoiseReductionApplied.n,
(unsigned) fNoiseReductionApplied.d);
}
#endif
break;
}
case tcNoiseProfile:
{
if (!CheckTagType (parentCode, tagCode, tagType, ttDouble))
return false;
// Must be an even, positive number of doubles in a noise profile.
if (!tagCount || (tagCount & 1))
return false;
// Determine number of planes (i.e., half the number of doubles).
const uint32 numPlanes = Pin_uint32 (0,
tagCount >> 1,
kMaxColorPlanes);
// Parse the noise function parameters.
std::vector<dng_noise_function> noiseFunctions;
for (uint32 i = 0; i < numPlanes; i++)
{
const real64 scale = stream.TagValue_real64 (tagType);
const real64 offset = stream.TagValue_real64 (tagType);
noiseFunctions.push_back (dng_noise_function (scale, offset));
}
// Store the noise profile.
fNoiseProfile = dng_noise_profile (noiseFunctions);
// Debug.
#if qDNGValidate
if (gVerbose)
{
printf ("NoiseProfile:\n");
printf (" Planes: %u\n", (unsigned) numPlanes);
for (uint32 plane = 0; plane < numPlanes; plane++)
{
printf (" Noise function for plane %u: scale = %.8lf, offset = %.8lf\n",
(unsigned) plane,
noiseFunctions [plane].Scale (),
noiseFunctions [plane].Offset ());
}
}
#endif
break;
}
case tcBaselineSharpness:
{
CheckTagType (parentCode, tagCode, tagType, ttRational);
CheckTagCount (parentCode, tagCode, tagCount, 1);
fBaselineSharpness = stream.TagValue_urational (tagType);
#if qDNGValidate
if (gVerbose)
{
printf ("BaselineSharpness: %0.2f\n",
fBaselineSharpness.As_real64 ());
}
#endif
break;
}
case tcLinearResponseLimit:
{
CheckTagType (parentCode, tagCode, tagType, ttRational);
CheckTagCount (parentCode, tagCode, tagCount, 1);
fLinearResponseLimit = stream.TagValue_urational (tagType);
#if qDNGValidate
if (gVerbose)
{
printf ("LinearResponseLimit: %0.2f\n",
fLinearResponseLimit.As_real64 ());
}
#endif
break;
}
case tcShadowScale:
{
CheckTagType (parentCode, tagCode, tagType, ttRational);
CheckTagCount (parentCode, tagCode, tagCount, 1);
fShadowScale = stream.TagValue_urational (tagType);
fHasShadowScale = true;
#if qDNGValidate
if (gVerbose)
{
printf ("ShadowScale: %0.4f\n",
fShadowScale.As_real64 ());
}
#endif
break;
}
case tcDNGPrivateData:
{
CheckTagType (parentCode, tagCode, tagType, ttByte);
fDNGPrivateDataCount = tagCount;
fDNGPrivateDataOffset = tagOffset;
#if qDNGValidate
if (gVerbose)
{
printf ("DNGPrivateData: Count = %u, Offset = %u\n",
(unsigned) fDNGPrivateDataCount,
(unsigned) fDNGPrivateDataOffset);
DumpHexAscii (stream, tagCount);
}
#endif
break;
}
case tcMakerNoteSafety:
{
CheckTagType (parentCode, tagCode, tagType, ttShort);
CheckTagCount (parentCode, tagCode, tagCount, 1);
fMakerNoteSafety = stream.TagValue_uint32 (tagType);
#if qDNGValidate
if (gVerbose)
{
printf ("MakerNoteSafety: %s\n",
LookupMakerNoteSafety (fMakerNoteSafety));
}
#endif
break;
}
case tcRawImageDigest:
{
if (!CheckTagType (parentCode, tagCode, tagType, ttByte))
return false;
if (!CheckTagCount (parentCode, tagCode, tagCount, 16))
return false;
stream.Get (fRawImageDigest.data, 16);
#if qDNGValidate
if (gVerbose)
{
printf ("RawImageDigest: ");
DumpFingerprint (fRawImageDigest);
printf ("\n");
}
#endif
break;
}
case tcNewRawImageDigest:
{
if (!CheckTagType (parentCode, tagCode, tagType, ttByte))
return false;
if (!CheckTagCount (parentCode, tagCode, tagCount, 16))
return false;
stream.Get (fNewRawImageDigest.data, 16);
#if qDNGValidate
if (gVerbose)
{
printf ("NewRawImageDigest: ");
DumpFingerprint (fNewRawImageDigest);
printf ("\n");
}
#endif
break;
}
case tcRawDataUniqueID:
{
if (!CheckTagType (parentCode, tagCode, tagType, ttByte))
return false;
if (!CheckTagCount (parentCode, tagCode, tagCount, 16))
return false;
stream.Get (fRawDataUniqueID.data, 16);
#if qDNGValidate
if (gVerbose)
{
printf ("RawDataUniqueID: ");
DumpFingerprint (fRawDataUniqueID);
printf ("\n");
}
#endif
break;
}
case tcOriginalRawFileName:
{
CheckTagType (parentCode, tagCode, tagType, ttAscii, ttByte);
ParseStringTag (stream,
parentCode,
tagCode,
tagCount,
fOriginalRawFileName,
false);
#if qDNGValidate
if (gVerbose)
{
printf ("OriginalRawFileName: ");
DumpString (fOriginalRawFileName);
printf ("\n");
}
#endif
break;
}
case tcOriginalRawFileData:
{
CheckTagType (parentCode, tagCode, tagType, ttUndefined);
fOriginalRawFileDataCount = tagCount;
fOriginalRawFileDataOffset = tagOffset;
#if qDNGValidate
if (gVerbose)
{
printf ("OriginalRawFileData: Count = %u, Offset = %u\n",
(unsigned) fOriginalRawFileDataCount,
(unsigned) fOriginalRawFileDataOffset);
DumpHexAscii (stream, tagCount);
}
#endif
break;
}
case tcOriginalRawFileDigest:
{
if (!CheckTagType (parentCode, tagCode, tagType, ttByte))
return false;
if (!CheckTagCount (parentCode, tagCode, tagCount, 16))
return false;
stream.Get (fOriginalRawFileDigest.data, 16);
#if qDNGValidate
if (gVerbose)
{
printf ("OriginalRawFileDigest: ");
DumpFingerprint (fOriginalRawFileDigest);
printf ("\n");
}
#endif
break;
}
case tcAsShotICCProfile:
{
CheckTagType (parentCode, tagCode, tagType, ttUndefined);
fAsShotICCProfileCount = tagCount;
fAsShotICCProfileOffset = tagOffset;
#if qDNGValidate
if (gVerbose)
{
printf ("AsShotICCProfile: Count = %u, Offset = %u\n",
(unsigned) fAsShotICCProfileCount,
(unsigned) fAsShotICCProfileOffset);
DumpHexAscii (stream, tagCount);
}
#endif
break;
}
case tcAsShotPreProfileMatrix:
{
CheckTagType (parentCode, tagCode, tagType, ttSRational);
if (!CheckColorImage (parentCode, tagCode, fCameraProfile.fColorPlanes))
return false;
uint32 rows = fCameraProfile.fColorPlanes;
if (tagCount == fCameraProfile.fColorPlanes * 3)
{
rows = 3;
}
if (!ParseMatrixTag (stream,
parentCode,
tagCode,
tagType,
tagCount,
rows,
fCameraProfile.fColorPlanes,
fAsShotPreProfileMatrix))
return false;
#if qDNGValidate
if (gVerbose)
{
printf ("AsShotPreProfileMatrix:\n");
DumpMatrix (fAsShotPreProfileMatrix);
}
#endif
break;
}
case tcCurrentICCProfile:
{
CheckTagType (parentCode, tagCode, tagType, ttUndefined);
fCurrentICCProfileCount = tagCount;
fCurrentICCProfileOffset = tagOffset;
#if qDNGValidate
if (gVerbose)
{
printf ("CurrentICCProfile: Count = %u, Offset = %u\n",
(unsigned) fCurrentICCProfileCount,
(unsigned) fCurrentICCProfileOffset);
DumpHexAscii (stream, tagCount);
}
#endif
break;
}
case tcCurrentPreProfileMatrix:
{
CheckTagType (parentCode, tagCode, tagType, ttSRational);
if (!CheckColorImage (parentCode, tagCode, fCameraProfile.fColorPlanes))
return false;
uint32 rows = fCameraProfile.fColorPlanes;
if (tagCount == fCameraProfile.fColorPlanes * 3)
{
rows = 3;
}
if (!ParseMatrixTag (stream,
parentCode,
tagCode,
tagType,
tagCount,
rows,
fCameraProfile.fColorPlanes,
fCurrentPreProfileMatrix))
return false;
#if qDNGValidate
if (gVerbose)
{
printf ("CurrentPreProfileMatrix:\n");
DumpMatrix (fCurrentPreProfileMatrix);
}
#endif
break;
}
case tcColorimetricReference:
{
CheckTagType (parentCode, tagCode, tagType, ttShort);
CheckTagCount (parentCode, tagCode, tagCount, 1);
fColorimetricReference = stream.TagValue_uint32 (tagType);
#if qDNGValidate
if (gVerbose)
{
printf ("ColorimetricReference: %s\n",
LookupColorimetricReference (fColorimetricReference));
}
#endif
break;
}
case tcExtraCameraProfiles:
{
CheckTagType (parentCode, tagCode, tagType, ttLong);
CheckTagCount (parentCode, tagCode, tagCount, 1, tagCount);
#if qDNGValidate
if (gVerbose)
{
printf ("ExtraCameraProfiles: %u\n", (unsigned) tagCount);
}
#endif
fExtraCameraProfiles.reserve (tagCount);
for (uint32 index = 0; index < tagCount; index++)
{
#if qDNGValidate
if (gVerbose)
{
printf ("\nExtraCameraProfile [%u]:\n\n", (unsigned) index);
}
#endif
stream.SetReadPosition (tagOffset + index * 4);
uint32 profileOffset = stream.TagValue_uint32 (tagType);
dng_camera_profile_info profileInfo;
stream.SetReadPosition (profileOffset);
if (profileInfo.ParseExtended (stream))
{
fExtraCameraProfiles.push_back (profileInfo);
}
else
{
#if qDNGValidate
ReportWarning ("Unable to parse extra camera profile");
#endif
}
}
#if qDNGValidate
if (gVerbose)
{
printf ("\nDone with ExtraCameraProfiles\n\n");
}
#endif
break;
}
case tcAsShotProfileName:
{
CheckTagType (parentCode, tagCode, tagType, ttAscii, ttByte);
ParseStringTag (stream,
parentCode,
tagCode,
tagCount,
fAsShotProfileName,
false);
#if qDNGValidate
if (gVerbose)
{
printf ("AsShotProfileName: ");
DumpString (fAsShotProfileName);
printf ("\n");
}
#endif
break;
}
case tcOriginalDefaultFinalSize:
{
CheckTagType (parentCode, tagCode, tagType, ttShort, ttLong);
if (!CheckTagCount (parentCode, tagCode, tagCount, 2))
return false;
fOriginalDefaultFinalSize.h = stream.TagValue_int32 (tagType);
fOriginalDefaultFinalSize.v = stream.TagValue_int32 (tagType);
#if qDNGValidate
if (gVerbose)
{
printf ("OriginalDefaultFinalSize: H = %d V = %d\n",
(int) fOriginalDefaultFinalSize.h,
(int) fOriginalDefaultFinalSize.v);
}
#endif
break;
}
case tcOriginalBestQualityFinalSize:
{
CheckTagType (parentCode, tagCode, tagType, ttShort, ttLong);
if (!CheckTagCount (parentCode, tagCode, tagCount, 2))
return false;
fOriginalBestQualityFinalSize.h = stream.TagValue_int32 (tagType);
fOriginalBestQualityFinalSize.v = stream.TagValue_int32 (tagType);
#if qDNGValidate
if (gVerbose)
{
printf ("OriginalBestQualityFinalSize: H = %d V = %d\n",
(int) fOriginalBestQualityFinalSize.h,
(int) fOriginalBestQualityFinalSize.v);
}
#endif
break;
}
case tcOriginalDefaultCropSize:
{
CheckTagType (parentCode, tagCode, tagType, ttShort, ttLong, ttRational);
if (!CheckTagCount (parentCode, tagCode, tagCount, 2))
return false;
fOriginalDefaultCropSizeH = stream.TagValue_urational (tagType);
fOriginalDefaultCropSizeV = stream.TagValue_urational (tagType);
#if qDNGValidate
if (gVerbose)
{
printf ("OriginalDefaultCropSize: H = %0.2f V = %0.2f\n",
fOriginalDefaultCropSizeH.As_real64 (),
fOriginalDefaultCropSizeV.As_real64 ());
}
#endif
break;
}
default:
{
// The main camera profile tags also appear in IFD 0
return fCameraProfile.ParseTag (stream,
parentCode,
tagCode,
tagType,
tagCount,
tagOffset);
}
}
return true;
}
/*****************************************************************************/
// Parses tags that should only appear in IFD 0 or EXIF IFD.
bool dng_shared::Parse_ifd0_exif (dng_stream &stream,
dng_exif & /* exif */,
uint32 parentCode,
uint32 tagCode,
uint32 tagType,
uint32 tagCount,
uint64 tagOffset)
{
switch (tagCode)
{
case tcMakerNote:
{
CheckTagType (parentCode, tagCode, tagType, ttUndefined);
fMakerNoteCount = tagCount;
fMakerNoteOffset = tagOffset;
#if qDNGValidate
if (gVerbose)
{
printf ("MakerNote: Count = %u, Offset = %u\n",
(unsigned) fMakerNoteCount,
(unsigned) fMakerNoteOffset);
DumpHexAscii (stream, tagCount);
}
#endif
break;
}
case tcInteroperabilityIFD:
{
CheckTagType (parentCode, tagCode, tagType, ttLong, ttIFD);
CheckTagCount (parentCode, tagCode, tagCount, 1);
fInteroperabilityIFD = stream.TagValue_uint32 (tagType);
#if qDNGValidate
if (gVerbose)
{
printf ("InteroperabilityIFD: %u\n", (unsigned) fInteroperabilityIFD);
}
#endif
break;
}
default:
{
return false;
}
}
return true;
}
/*****************************************************************************/
void dng_shared::PostParse (dng_host & /* host */,
dng_exif & /* exif */)
{
// Fill in default values for DNG images.
if (fDNGVersion != 0)
{
// Support for DNG versions before 1.0.0.0.
if (fDNGVersion < dngVersion_1_0_0_0)
{
#if qDNGValidate
ReportWarning ("DNGVersion less than 1.0.0.0");
#endif
// The CalibrationIlluminant tags were added just before
// DNG version 1.0.0.0, and were hardcoded before that.
fCameraProfile.fCalibrationIlluminant1 = lsStandardLightA;
fCameraProfile.fCalibrationIlluminant2 = lsD65;
fDNGVersion = dngVersion_1_0_0_0;
}
// Default value for DNGBackwardVersion tag.
if (fDNGBackwardVersion == 0)
{
fDNGBackwardVersion = fDNGVersion & 0xFFFF0000;
}
// Check DNGBackwardVersion value.
if (fDNGBackwardVersion < dngVersion_1_0_0_0)
{
#if qDNGValidate
ReportWarning ("DNGBackwardVersion less than 1.0.0.0");
#endif
fDNGBackwardVersion = dngVersion_1_0_0_0;
}
if (fDNGBackwardVersion > fDNGVersion)
{
#if qDNGValidate
ReportWarning ("DNGBackwardVersion > DNGVersion");
#endif
fDNGBackwardVersion = fDNGVersion;
}
// Check UniqueCameraModel.
if (fUniqueCameraModel.IsEmpty ())
{
#if qDNGValidate
ReportWarning ("Missing or invalid UniqueCameraModel");
#endif
fUniqueCameraModel.Set ("Digital Negative");
}
// If we don't know the color depth yet, it must be a monochrome DNG.
if (fCameraProfile.fColorPlanes == 0)
{
fCameraProfile.fColorPlanes = 1;
}
// Check color info.
if (fCameraProfile.fColorPlanes > 1)
{
// Check illuminant pair.
if (fCameraProfile.fColorMatrix2.NotEmpty ())
{
if (fCameraProfile.fCalibrationIlluminant1 == lsUnknown ||
(fCameraProfile.fCalibrationIlluminant2 == lsUnknown ||
(fCameraProfile.fCalibrationIlluminant1 == fCameraProfile.fCalibrationIlluminant2)))
{
#if qDNGValidate
ReportWarning ("Invalid CalibrationIlluminant pair");
#endif
fCameraProfile.fColorMatrix2 = dng_matrix ();
}
}
// If the colorimetric reference is the ICC profile PCS, then the
// data must already be white balanced. The "AsShotWhiteXY" is required
// to be the ICC Profile PCS white point.
if (fColorimetricReference == crICCProfilePCS)
{
if (fAsShotNeutral.NotEmpty ())
{
#if qDNGValidate
ReportWarning ("AsShotNeutral not allowed for this "
"ColorimetricReference value");
#endif
fAsShotNeutral.Clear ();
}
dng_xy_coord pcs = PCStoXY ();
#if qDNGValidate
if (fAsShotWhiteXY.IsValid ())
{
if (Abs_real64 (fAsShotWhiteXY.x - pcs.x) > 0.01 ||
Abs_real64 (fAsShotWhiteXY.y - pcs.y) > 0.01)
{
ReportWarning ("AsShotWhiteXY does not match the ICC Profile PCS");
}
}
#endif
fAsShotWhiteXY = pcs;
}
else
{
// Warn if both AsShotNeutral and AsShotWhiteXY are specified.
if (fAsShotNeutral.NotEmpty () && fAsShotWhiteXY.IsValid ())
{
#if qDNGValidate
ReportWarning ("Both AsShotNeutral and AsShotWhiteXY included");
#endif
fAsShotWhiteXY = dng_xy_coord ();
}
// Warn if neither AsShotNeutral nor AsShotWhiteXY are specified.
#if qDNGValidate
if (fAsShotNeutral.IsEmpty () && !fAsShotWhiteXY.IsValid ())
{
ReportWarning ("Neither AsShotNeutral nor AsShotWhiteXY included",
"legal but not recommended");
}
#endif
}
// Default values of calibration signatures are required for legacy
// compatiblity.
if (fCameraProfile.fCalibrationIlluminant1 == lsStandardLightA &&
fCameraProfile.fCalibrationIlluminant2 == lsD65 &&
fCameraCalibration1.Rows () == fCameraProfile.fColorPlanes &&
fCameraCalibration1.Cols () == fCameraProfile.fColorPlanes &&
fCameraCalibration2.Rows () == fCameraProfile.fColorPlanes &&
fCameraCalibration2.Cols () == fCameraProfile.fColorPlanes &&
fCameraCalibrationSignature.IsEmpty () &&
fCameraProfile.fProfileCalibrationSignature.IsEmpty () )
{
fCameraCalibrationSignature.Set (kAdobeCalibrationSignature);
fCameraProfile.fProfileCalibrationSignature.Set (kAdobeCalibrationSignature);
}
}
// Check BaselineNoise.
if (fBaselineNoise.As_real64 () <= 0.0)
{
#if qDNGValidate
ReportWarning ("Invalid BaselineNoise");
#endif
fBaselineNoise = dng_urational (1, 1);
}
// Check BaselineSharpness.
if (fBaselineSharpness.As_real64 () <= 0.0)
{
#if qDNGValidate
ReportWarning ("Invalid BaselineSharpness");
#endif
fBaselineSharpness = dng_urational (1, 1);
}
// Check NoiseProfile.
if (!fNoiseProfile.IsValid () && fNoiseProfile.NumFunctions () != 0)
{
#if qDNGValidate
ReportWarning ("Invalid NoiseProfile");
#endif
fNoiseProfile = dng_noise_profile ();
}
// Check LinearResponseLimit.
if (fLinearResponseLimit.As_real64 () < 0.5 ||
fLinearResponseLimit.As_real64 () > 1.0)
{
#if qDNGValidate
ReportWarning ("Invalid LinearResponseLimit");
#endif
fLinearResponseLimit = dng_urational (1, 1);
}
// Check ShadowScale.
if (fShadowScale.As_real64 () <= 0.0)
{
#if qDNGValidate
ReportWarning ("Invalid ShadowScale");
#endif
fShadowScale = dng_urational (1, 1);
}
}
}
/*****************************************************************************/
bool dng_shared::IsValidDNG ()
{
// Check DNGVersion value.
if (fDNGVersion < dngVersion_1_0_0_0)
{
#if qDNGValidate
if (fDNGVersion != dngVersion_None)
{
ReportError ("Invalid DNGVersion");
}
#if qDNGValidateTarget
else
{
ReportError ("Missing DNGVersion");
}
#endif
#endif
return false;
}
// Check DNGBackwardVersion value.
if (fDNGBackwardVersion > dngVersion_Current)
{
#if qDNGValidate
ReportError ("DNGBackwardVersion (or DNGVersion) is too high");
#endif
ThrowUnsupportedDNG ();
}
// Check color transform info.
if (fCameraProfile.fColorPlanes > 1)
{
// CameraCalibration1 is optional, but it must be valid if present.
if (fCameraCalibration1.Cols () != 0 ||
fCameraCalibration1.Rows () != 0)
{
if (fCameraCalibration1.Cols () != fCameraProfile.fColorPlanes ||
fCameraCalibration1.Rows () != fCameraProfile.fColorPlanes)
{
#if qDNGValidate
ReportError ("CameraCalibration1 is wrong size");
#endif
return false;
}
// Make sure it is invertable.
try
{
(void) Invert (fCameraCalibration1);
}
catch (...)
{
#if qDNGValidate
ReportError ("CameraCalibration1 is not invertable");
#endif
return false;
}
}
// CameraCalibration2 is optional, but it must be valid if present.
if (fCameraCalibration2.Cols () != 0 ||
fCameraCalibration2.Rows () != 0)
{
if (fCameraCalibration2.Cols () != fCameraProfile.fColorPlanes ||
fCameraCalibration2.Rows () != fCameraProfile.fColorPlanes)
{
#if qDNGValidate
ReportError ("CameraCalibration2 is wrong size");
#endif
return false;
}
// Make sure it is invertable.
try
{
(void) Invert (fCameraCalibration2);
}
catch (...)
{
#if qDNGValidate
ReportError ("CameraCalibration2 is not invertable");
#endif
return false;
}
}
// Check analog balance
dng_matrix analogBalance;
if (fAnalogBalance.NotEmpty ())
{
analogBalance = fAnalogBalance.AsDiagonal ();
try
{
(void) Invert (analogBalance);
}
catch (...)
{
#if qDNGValidate
ReportError ("AnalogBalance is not invertable");
#endif
return false;
}
}
}
return true;
}
/*****************************************************************************/
| [
"aabbas@gopro.com"
] | aabbas@gopro.com |
6d478815c7e57d198e1d60e56376da50fcb41be3 | 5df36d6a2a73d3aa24bd7b1d3fe35a4731706c34 | /ABC158/b.cpp | 65e66b0ecc6080774db281f251df59d5b410c098 | [] | no_license | shunya-s15/Atcoder | 7a5ce84eef673fc0b1dc4fd1100d44ebe1ba9dcc | 7c670109bcc19a25efa4ec48c95615d0ebaafab0 | refs/heads/master | 2023-06-20T04:12:44.711496 | 2021-07-20T03:47:16 | 2021-07-20T03:47:16 | 282,530,952 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 366 | cpp | #include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main(){
int64_t n,a,b;
cin >> n >> a >> b;
int64_t sum = a+b;
int64_t ans = a*(n/sum);
if(n%sum != 0){
if(n%sum > a){
ans += a;
}else{
ans += n%sum;
}
}
cout << ans << endl;
return 0;
} | [
"shunya.suraimu@gmail.com"
] | shunya.suraimu@gmail.com |
ffe873fe6f6f7357b9e08c4004aa13efce33625e | 6e20207f8aff0f0ad94f05bd025810c6b10a1d5f | /SDK/ArthurStoryShelter_classes.h | 47f579f23fac2b34d4c3e7db651620aad7dcd6f6 | [] | no_license | zH4x-SDK/zWeHappyFew-SDK | 2a4e246d8ee4b58e45feaa4335f1feb8ea618a4a | 5906adc3edfe1b5de86b7ef0a0eff38073e12214 | refs/heads/main | 2023-08-17T06:05:18.561339 | 2021-08-27T13:36:09 | 2021-08-27T13:36:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 789 | h | #pragma once
// Name: WeHappyFew, Version: 1.8.8
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass ArthurStoryShelter.ArthurStoryShelter_C
// 0x00A8 (0x0598 - 0x04F0)
class UArthurStoryShelter_C : public UStateQuest
{
public:
unsigned char UnknownData00[0xA8]; // 0x04F0(0x00A8) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass ArthurStoryShelter.ArthurStoryShelter_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
28521891d627d58b0b5cc5d84a5f2b43a8ed8bda | 1aa38513e62d081e7c3733aad9fe1487f22d7a73 | /compat/check-visible.cpp | 84ddd6d90f8b7ccdbf4c82f61f70a595f4166840 | [
"ISC",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | cpuwolf/opentrack | c3eae3700a585193b67187c6619bf32e1dedd1aa | 5541cfc68d87c2fc254eb2f2a5aad79831871a88 | refs/heads/unstable | 2021-06-05T14:18:24.851128 | 2017-11-02T13:10:54 | 2017-11-02T13:10:54 | 83,854,103 | 1 | 0 | null | 2017-03-04T00:44:16 | 2017-03-04T00:44:15 | null | UTF-8 | C++ | false | false | 1,247 | cpp | #include "check-visible.hpp"
#if defined _WIN32
#include "timer.hpp"
#include <QMutexLocker>
#include <windows.h>
constexpr int visible_timeout = 5000;
constexpr int invisible_timeout = 250;
static Timer timer;
static QMutex mtx;
static bool visible = true;
never_inline OTR_COMPAT_EXPORT
void set_is_visible(const QWidget& w, bool force)
{
QMutexLocker l(&mtx);
if (!force && timer.elapsed_ms() < (visible ? visible_timeout : invisible_timeout))
return;
timer.start();
const HWND id = (HWND) w.winId();
const QPoint pt = w.mapToGlobal({ 0, 0 });
const int W = w.width(), H = w.height();
const QPoint points[] =
{
pt,
pt + QPoint(W - 1, 0),
pt + QPoint(0, H - 1),
pt + QPoint(W - 1, H - 1),
pt + QPoint(W / 2, H / 2),
};
for (const QPoint& pt : points)
{
visible = WindowFromPoint({ pt.x(), pt.y() }) == id;
if (visible)
break;
}
}
never_inline OTR_COMPAT_EXPORT
bool check_is_visible()
{
QMutexLocker l(&mtx);
return visible;
}
#else
never_inline OTR_COMPAT_EXPORT
void set_is_visible(const QWidget&, bool)
{
}
never_inline OTR_COMPAT_EXPORT
bool check_is_visible()
{
return true;
}
#endif
| [
"sthalik@misaki.pl"
] | sthalik@misaki.pl |
073475aa1124a2f6a6722e505e2d2ed06e8de8b3 | ecc970107f26e382b2e170c7201f7fa8b7d47050 | /2120/Lab7/lab07.cpp | 1e266ec53dd8ee94e0413f2ff43e51ffdd72b66d | [] | no_license | OnyxKnight/Labs | 53315f93910072004561f1cf63eeeb6ce8d0cda5 | 5593e79f2da56de275858d0cae7d9e95bf6baebd | refs/heads/master | 2021-01-20T08:00:23.314252 | 2017-05-06T17:55:10 | 2017-05-06T17:55:10 | 90,075,679 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,240 | cpp | #include <iostream>
#include <string>
#include "Queue.h"
using namespace std;
//Print a Queue
template<class T>
void printQueue(Queue<T> & q, string name){
cout << name << ": ";
cout << "size = " << q.size();
cout << ", queue = (front) ";
while( !q.empty() ){
cout << q.front() << " ";
//Uncomment the line below to view memory addresses
//cout << (unsigned long) &q.front() << " ";
q.dequeue();
}
cout << "(back)" << endl;
}
//Test the Queue class in Queue.h
int main( ){
Queue<int> q1;
for(int i = 1; i < 30; i++){
q1.push(i);
if(i % 3 == 0){
q1.pop();
q1.pop();
}
}
printQueue<int>(q1, "q1");
printQueue<int>(q1, "q1");
Queue<char> q2;
int i = 1;
for(char c = 'a'; c <= 'z'; c++, i++){
if(i % 3 == 0){
char d = (char) (c - 32);
q2.enqueue(d);
}
else{
q2.enqueue(c);
}
if(i % 6 == 0){
q2.dequeue();
q2.dequeue();
}
}
printQueue<char>(q2, "q2");
printQueue<char>(q2, "q2");
Queue<double> q3;
for(double k = 1; k <= 1000000; k++){
q3.push(k);
}
for(double k = 1; k <= 1000000 - 6; k++){
q3.pop();
}
printQueue<double>(q3, "q3");
printQueue<double>(q3, "q3");
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
1719c9b73e455719947198cf66ab745591bd7b5c | aa138fc4785411c9d88b827eaaf3644579a37c67 | /test/unit/DslPrimaryTisUnitTest.cpp | 7625b596661b7c226c6b05c50718418313745ed5 | [
"MIT"
] | permissive | tuniarhq/deepstream-services-library | e9bf5abc7960849dbc284277497e22c59572e36b | 9b238004a42c6e0c891d538e698ad38ce678422f | refs/heads/master | 2023-08-20T01:38:54.888679 | 2021-09-17T19:39:50 | 2021-09-17T19:39:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,633 | cpp | /*
The MIT License
Copyright (c) 2019-2021, Prominence AI, 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 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 "catch.hpp"
#include "DslInferBintr.h"
using namespace DSL;
static const std::string primaryTisName("primary-tis");
static const std::string inferConfigFile(
"/opt/nvidia/deepstream/deepstream-5.1/samples/configs/deepstream-app-trtis/config_infer_plan_engine_primary.txt");
SCENARIO( "A new PrimaryTisBintr is created correctly", "[PrimaryTisBintr]" )
{
GIVEN( "Attributes for a new PrimaryTisBintr" )
{
uint interval(1);
WHEN( "A new PrimaryTisBintr is created" )
{
DSL_PRIMARY_TIS_PTR pPrimaryTisBintr =
DSL_PRIMARY_TIS_NEW(primaryTisName.c_str(), inferConfigFile.c_str(), interval);
THEN( "The PrimaryTisBintr's memebers are setup and returned correctly" )
{
std::string returnedInferConfigFile = pPrimaryTisBintr->GetInferConfigFile();
REQUIRE( pPrimaryTisBintr->GetInferType() == DSL_INFER_TYPE_TIS);
REQUIRE( returnedInferConfigFile == inferConfigFile );
REQUIRE( interval == pPrimaryTisBintr->GetInterval() );
REQUIRE( pPrimaryTisBintr->IsLinked() == false );
}
}
}
}
SCENARIO( "A new PrimaryTisBintr with its Batch Size set can LinkAll Child Elementrs", "[PrimaryTisBintr]" )
{
GIVEN( "A new PrimaryTisBintr in an Unlinked state" )
{
std::string primaryTisName("primary-tis");
std::string inferConfigFile(
"/opt/nvidia/deepstream/deepstream-5.1/samples/configs/deepstream-app-trtis/config_infer_plan_engine_primary.txt");
uint interval(1);
DSL_PRIMARY_TIS_PTR pPrimaryTisBintr =
DSL_PRIMARY_TIS_NEW(primaryTisName.c_str(), inferConfigFile.c_str(), interval);
WHEN( "The Batch Size is set and the PrimaryTisBintr is asked to LinkAll" )
{
pPrimaryTisBintr->SetBatchSize(1);
REQUIRE( pPrimaryTisBintr->LinkAll() == true );
THEN( "The PrimaryTisBintr IsLinked state is updated correctly" )
{
REQUIRE( pPrimaryTisBintr->IsLinked() == true );
}
}
}
}
SCENARIO( "A Linked PrimaryTisBintr can UnlinkAll Child Elementrs", "[PrimaryTisBintr]" )
{
GIVEN( "A Linked PrimaryTisBintr" )
{
uint interval(1);
DSL_PRIMARY_TIS_PTR pPrimaryTisBintr =
DSL_PRIMARY_TIS_NEW(primaryTisName.c_str(), inferConfigFile.c_str(), interval);
pPrimaryTisBintr->SetBatchSize(1);
REQUIRE( pPrimaryTisBintr->LinkAll() == true );
WHEN( "A new PrimaryTisBintr is created" )
{
pPrimaryTisBintr->UnlinkAll();
THEN( "The PrimaryTisBintr can LinkAll Child Elementrs" )
{
REQUIRE( pPrimaryTisBintr->IsLinked() == false );
}
}
}
}
SCENARIO( "A Linked PrimaryTisBintr can not be linked again", "[PrimaryTisBintr]" )
{
GIVEN( "A new PrimaryTisBintr in an Unlinked state" )
{
uint interval(1);
DSL_PRIMARY_TIS_PTR pPrimaryTisBintr =
DSL_PRIMARY_TIS_NEW(primaryTisName.c_str(), inferConfigFile.c_str(), interval);
WHEN( "A new PrimaryTisBintr is Linked" )
{
pPrimaryTisBintr->SetBatchSize(1);
REQUIRE( pPrimaryTisBintr->LinkAll() == true );
THEN( "The PrimaryTisBintr can not be linked again" )
{
REQUIRE( pPrimaryTisBintr->LinkAll() == false );
}
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
4a1a58a467ed9e75ab259e1f7dcd5dde9b7720f3 | 66a0e5c3959683c12a61c2e97b0f361dc042a3e4 | /CodeForces/713B.cpp | b2ebc44d050e425424507a1d5c9599251219fe76 | [] | no_license | theteleton/ACM | 3f5fb98a20599443b5ead010e477c3338fbb07e0 | 161b6daea32a6b0fd122c6858749f54269089b45 | refs/heads/master | 2023-07-14T15:09:38.779805 | 2021-08-26T18:00:55 | 2021-08-26T18:00:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,552 | cpp | #include <iostream>
#include <vector>
#include <map>
#include <cmath>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
char mat[401][401];
int x1 = -1;
int y1 = -1;
int x2 = -1;
int y2 = -1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> mat[i][j];
if (mat[i][j] == '*') {
if (x1 == -1) {
x1 = i;
y1 = j;
} else {
x2 = i;
y2 = j;
}
}
}
}
if (x1 == x2) {
if (x1 + 1 < n) {
mat[x1 + 1][y1] = '*';
mat[x2 + 1][y2] = '*';
} else if (x1 - 1 < n) {
mat[x1 - 1][y1] = '*';
mat[x2 - 1][y2] = '*';
}
}
else if (y1 == y2) {
if (y1 + 1 < n) {
mat[x1][y1 + 1] = '*';
mat[x2][y2 + 1] = '*';
} else if (x1 - 1 < n) {
mat[x1][y1 - 1] = '*';
mat[x2][y2 - 1] = '*';
}
} else {
mat[x2][y1] = '*';
mat[x1][y2] = '*';
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << mat[i][j];
}
cout << endl;
}
}
return 0;
} | [
"it8816@student.uni-lj.si"
] | it8816@student.uni-lj.si |
817ee6dd412157a800636a8408c2963e5dff7cf7 | e1f49710ce394d6817b77c6589259263d574df20 | /TinySTL/alloc.h | 482936dc4b5bd05661b1e3385d9e0f2282e2f072 | [] | no_license | LinNego/TinySTL | f3d24a80fdc79055692c9661cba711ff3e9e52c6 | 79bf69e2a10bd551f60849c9658ed87c409c7a1f | refs/heads/master | 2022-12-06T01:49:15.592200 | 2020-07-31T10:44:13 | 2020-07-31T10:44:13 | 272,491,698 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,358 | h | /*LinNego*/
#ifndef MYSTL_ALLOC_H
#define MYSTL_ALLOC_H
#include <cstddef>
#include <cstring>
#include <cstdlib>
#include <exception>
#include <new>
namespace mystl {
template <int inst>
class alloc_prime {
typedef void (*hander)(); //为了简化声明
alloc_prime(const alloc_prime&) = delete;
alloc_prime& operator=(const alloc_prime&) = delete;
private:
/*都为static的原因*/
/*我认为有一个就是可以不用构造用户不需要构造一个对象可以直接使用.2020.6.19*/
static void* oom_malloc(size_t);
static void* oom_realloc(void *, size_t);
/*这个设为静态成员的目的?*/
static hander oom_hander;
void* realloc(void *p, size_t new_sz);
public:
static void* allocate(size_t n) {
void *result = malloc(n);
if(result == nullptr) result = oom_malloc(n);
return result;
}
static void deallocate(void *p, size_t) {
free(static_cast<char*>(p));
}
static void* reallocate(void *p, size_t, size_t new_size) {
void *result = realloc(p, new_size);
if(result == nullptr) result = oom_realloc(p, new_size);
return result;
}
hander set_myalloc_hander(hander new_hander) {
hander old_hander = oom_hander;
oom_hander = new_hander;
return old_hander;
}
};
template <int inst>
typename alloc_prime<inst>::hander alloc_prime<inst>::oom_hander = nullptr;
template <int inst>
void* alloc_prime<inst>::oom_malloc(size_t sz) {
void * result;
hander cur_hander;
for(; ;) {
cur_hander = oom_hander;
if(cur_hander == nullptr) {
throw std::bad_alloc();
}
(*cur_hander)();
result = malloc(sz);
if(result) return result;
}
}
template <int inst>
void* alloc_prime<inst>::oom_realloc(void *p, size_t n) {
void *result;
hander cur_hander;
for(; ;) {
cur_hander = oom_hander;
if(cur_hander == nullptr) {
throw std::bad_alloc();
}
(*cur_hander)();
result = realloc(p, n);
if(result) return result;
(*cur_hander)();
}
}
/*realloc where ?*/
using malloc_alloc = alloc_prime<0>;
}
namespace mystl {
enum {ALIGN = 8};
enum {MAX_BYTES = 128};
enum {NFREELISTS = MAX_BYTES / ALIGN};
template <bool threads, int inst>
class alloc_optimize {
/*私以为改成static成员并且放进类里面可以隐藏数据*/
alloc_optimize(const alloc_optimize&) = delete;
alloc_optimize& operator=(const alloc_optimize&) = delete;
public:
static void* allocate(size_t n);
static void deallocate(void *p, size_t);
static void* reallocate(void *p, size_t old_sz, size_t new_sz);
private:
static size_t round_up(size_t bytes) {
return (bytes + ALIGN - 1) & ~(ALIGN - 1);
}
union obj {
union obj *free_list_link;
char client_data[1];
};
static obj* volatile free_list[NFREELISTS];
static size_t freelist_index(size_t bytes) {
return (bytes - 1) / ALIGN + 1;
}
static void *refill(size_t n);
static char *chunk_alloc(size_t size, int &nobjs);
static char *start_free;
static char *end_free;
static size_t heap_size;
};
template <bool threads, int inst>
char* alloc_optimize<threads, inst>::start_free = nullptr;
template <bool threads, int inst>
char* alloc_optimize<threads, inst>::end_free = nullptr;
template <bool threads, int inst>
size_t alloc_optimize<threads, inst>::heap_size = 0;
template <bool threads, int inst>
typename alloc_optimize<threads, inst>::obj* volatile
alloc_optimize<threads, inst>::free_list[NFREELISTS] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
template <bool threads, int inst>
void* alloc_optimize<threads, inst>::allocate(size_t n) {
if(n > MAX_BYTES) {
return malloc_alloc::allocate(n);
}
obj* volatile *my_free_list;
obj *result;
my_free_list = free_list + freelist_index(n);
result = *my_free_list;
if(result == nullptr) {
void *r = refill(round_up(n));
return r;
}
*my_free_list = result->free_list_link;
return result;
}
template <bool threads, int inst>
void alloc_optimize<threads, inst>::deallocate(void *p, size_t n) {
obj *q = static_cast<obj*>(p);
obj *volatile *my_free_list;
if(n > static_cast<size_t>(MAX_BYTES)) {
malloc_alloc::deallocate(p, n);
return ;
}
my_free_list = free_list + freelist_index(n);
q->free_list_link = *my_free_list;
*my_free_list = q;
}
template <bool threads, int inst>
void* alloc_optimize<threads, inst>::refill(size_t n) {
int nobjs = 20;
char *chunk = chunk_alloc(n, nobjs);
obj *volatile *my_free_list;
obj *result;
if(nobjs == 1) {
return chunk;
}
obj *cur_obj;
my_free_list = free_list + freelist_index(n);
result = *my_free_list = cur_obj = static_cast<obj*>(chunk);
for(int i = 1; i != nobjs; ++i) {
cur_obj->free_list_link = static_cast<obj*>(static_cast<char*>(cur_obj) + n);
cur_obj = cur_obj->free_list_link;
}
cur_obj->free_list_link = nullptr;
return result;
}
template <bool threads, int inst>
char* alloc_optimize<threads, inst>::chunk_alloc(size_t size, int &nobjs) {
char *result;
size_t total_bytes = size * nobjs;
size_t bytes_left = end_free - start_free;
if(bytes_left >= total_bytes) {
result = start_free;
start_free += total_bytes;
return result;
} else if(bytes_left >= size) {
nobjs = bytes_left / size;
total_bytes = size * nobjs;
result = start_free;
start_free += total_bytes;
return result;
} else {
size_t bytes_to_get = 2 * total_bytes + round_up(heap_size >> 4);
if(bytes_left >= 0) {
obj* volatile *my_free_list = free_list + freelist_index(bytes_left);
static_cast<obj*>(start_free) -> free_list_link = *my_free_list;
*my_free_list = static_cast<obj*>(start_free);
}
start_free = (char*)malloc(bytes_to_get);
if(start_free == nullptr) {
int i;
obj* volatile *my_free_list, *p;
for(i = size; i <= MAX_BYTES; i += ALIGN) {
my_free_list = free_list + freelist_index(i);
p = *my_free_list;
if(p != nullptr) {
*my_free_list = p->free_list_link;
start_free = (char*)p;
end_free = start_free + i;
return chunk_alloc(size, nobjs);
}
}
end_free = nullptr;
start_free = (char*)malloc_alloc::allocate(bytes_to_get);
}
heap_size += bytes_to_get;
end_free = start_free + bytes_to_get;
return chunk_alloc(size, nobjs);
}
}
typedef alloc_optimize<0, 0> alloc;
}
#endif
| [
"LinNego@example.com"
] | LinNego@example.com |
e791833770276f6261e50f204029fd22c29e7c57 | 30114f6730aac693971d826f58e46f6d158e6957 | /ATL/Advanced/CThreadPool/tasks.h | 54516d642ce8052fa80c8708ad9ff5c1d1b61cdb | [] | no_license | oudream/vc_example_official | 67111751a416df93cdc4b9f1048d93f482819992 | 8075deebd4755b2a7531a8f918c19ad2e82e2b23 | refs/heads/master | 2020-06-14T08:00:01.267447 | 2019-07-03T01:03:59 | 2019-07-03T01:03:59 | 194,953,887 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,799 | h | // File: tasks.h
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Classes Reference and related electronic
// documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft C++ Libraries products.
#pragma once
///////////////////////////////////////////////////////////////////////////////
class CTaskBase
{
public:
virtual void DoTask(void *pvParam, OVERLAPPED *pOverlapped)=0;
};
///////////////////////////////////////////////////////////////////////////////
class CTask1 : public CTaskBase
{
public:
virtual void DoTask(void *pvParam, OVERLAPPED *pOverlapped)
{
printf("[%d]: CTask1::DoTask(pvParam=%d, pOverlapped=%d)\n",
::GetCurrentThreadId(), (DWORD_PTR)pvParam, (DWORD_PTR)pOverlapped);
}
};
///////////////////////////////////////////////////////////////////////////////
class CTask2 : public CTaskBase
{
public:
virtual void DoTask(void *pvParam, OVERLAPPED *pOverlapped)
{
printf("[%d]: CTask2::DoTask(pvParam=%d, pOverlapped=%d)\n",
::GetCurrentThreadId(), (DWORD_PTR)pvParam, (DWORD_PTR)pOverlapped);
}
};
///////////////////////////////////////////////////////////////////////////////
typedef CSimpleArray<CTaskBase*> CTaskArray;
///////////////////////////////////////////////////////////////////////////////
bool CreateTasks(CTaskArray& tasks, DWORD dwCount)
{
bool bOk = false;
if ( 0 == tasks.GetSize() && dwCount > 0 ) {
CTaskBase* pTask = NULL;
for ( DWORD i = 0; i < dwCount; i++ ) {
if ( i % 2 )
pTask = new CTask1;
else
pTask = new CTask2;
if ( !tasks.Add( pTask ))
ATLASSERT( false );
}
bOk = true;
}
return bOk;
}
| [
"oudream@126.com"
] | oudream@126.com |
ceed7f3afa30c58910a7683eb6004335afa131a6 | 028411051fe54000e882aef22878061cd7eb28bf | /Priority Queue/Pqueue.h | a877dde5b8b4e7c4479c90965a1b680c218f7e1f | [] | no_license | Kacper20/Priority-Queue | 8335ed28916e3b6d5312d36bd7af19c8646e9679 | e7c61ac85f4491fa8e67ada2fa1516a54ae917af | refs/heads/master | 2021-03-12T20:28:40.926005 | 2014-04-01T18:24:33 | 2014-04-01T18:24:33 | null | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 1,865 | h | /*
***Kacper Harasim
*** Projekt 1
*** Deklaracja klasy PQueue
*** INFO:
/ Implementacja oparta jest na kopcu binarnym. Wszystkie operacje poza łączeniem kolejek odbywają się w czasie O(lgN) gdzie N jest wielkością kopca.
/ Operacja połączenia(zdefiniowana w funkcji operatorowej +) jest zrealizowana w czasie O(N).
*** Data oddania: 13.03.2014r.
*/
class Pqueue
{
private:
struct item{
int key;
int value;
int eld; // starszość elementu przechowywana dla każdego elementu z kolejki.
};
int max_eld; //
int max_size; // Maksymalny rozmiar dla ktorego tworzona jest kolejka
int N; // Aktualny rozmiar kolejki
int low_bound = 85;
int upp_bound = 95;
item *pq; // wskaznik na struktury
void fixUp(int k); // Kopcuje w dół
void fixDown(int k); // Naprawia kopcowanie w górę
void swap(int a, int b); // Pomocnicza do zmieniania wartości
bool less(int a, int b);
void build_max_heap(); // Tworzy maksymalny kopiec.
void swap_with_min(int key, int value); // funkcja zamienia element wkladany z elementem o najmniejszym priorytecie(wyrzuca go z kolejki)
public:
Pqueue(int size = 40);
Pqueue(const int tab[], int rozmiar);
~Pqueue();
bool ifEmpty(); // Sprawdza czy kolejka jest pusta
bool ifFull(); // Sprawdza czy jest pełna.
void insert(int key, int value);
int deleteMax(); // Usuwa element o maksymalnym priorytecie i zwraca jego wartosc.
int max(); // Zwraca wartosc elementu o maksymalnym priorytecie.
int size(); // Zwraca rozmiar kolejki.
int msize(); // Zwraca pojemnosc kolejki.
void change_up(int val); // Zmienia upp bound kolejki
void change_low(int val); // Zmienia low bound kolejki
int check_up(); // Zwraca stosunek akt rozmiar/upp bound w procentach
int check_low(); // Zwraca stosunek akt rozmiar/low bound w procentach
Pqueue operator +(Pqueue &cq); // Przeciążony operator dodawania.
};
| [
"kacper.harasim@gmail.com"
] | kacper.harasim@gmail.com |
95f5f4199b99fa34f20910cb095c190fa095960e | 934bece520adff2a6cf481d5314319b030d69728 | /Conference Track Management/Conference Track Management/Tactics/CTimeLimit.h | b83cab216e94807e09d0295892f1a215074a860b | [] | no_license | skyformat99/Conference-Track-Management | aae996618543a2fd8c92d12083f583004e6fc76a | f4e71aa6bb9b08becfdb5fb53a2440f15fe0e7b7 | refs/heads/master | 2021-01-24T08:54:18.193299 | 2016-03-26T06:08:16 | 2016-03-26T06:08:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 261 | h | #pragma once
#include "CTactics.h"
class CTimeLimit : public CTactics
{
public:
CTimeLimit();
~CTimeLimit();
bool IsSatisfy(vector<CCourse>* listPool, vector<CCourse>* list, int count);
private:
bool HasCourseWithID(vector<CCourse>* list, int id);
};
| [
"shiple@qq.com"
] | shiple@qq.com |
c3f7d42621992bb97fda4b725c2771e2962be490 | 37a63e7798a3cb5cf8e9524d4bfed69948986319 | /firmware/teensy/ad7616.cpp | 1993654b6b4c95b1a7b97fe651b387c5dfdbb407 | [] | no_license | arne48/control_board_set | 62121b2a0c9b739a61d270e792eea082fbfd2ee9 | f849a5185bce2521ae91ab5597a3d996371ca963 | refs/heads/master | 2023-04-21T19:24:08.543040 | 2021-05-03T09:45:47 | 2021-05-03T09:45:47 | 283,436,400 | 0 | 1 | null | 2020-12-23T12:06:20 | 2020-07-29T08:00:10 | C++ | UTF-8 | C++ | false | false | 1,203 | cpp | #include "ad7616.h"
AD7616::AD7616(Embedded_SPI *dev, Embedded_GPIO *gpio, int trigger_measurement_gpio) {
_dev = dev;
_gpio = gpio;
_trigger_measurement_gpio = trigger_measurement_gpio;
}
void AD7616::prepareChannel(uint8_t channel, int cs){
_channel_select_command[1] = channel | channel << 4;
_channel_select_command[3] = channel | channel << 4;
_dev->transferSPI(cs, 4, _channel_select_command, _rx_buffer);
//Dummy read to get rid of values of the last measurement
_gpio->set_output(_trigger_measurement_gpio, Embedded_GPIO::gpio_state::EMB_ON);
_gpio->set_output(_trigger_measurement_gpio, Embedded_GPIO::gpio_state::EMB_OFF);
_dev->transferSPI(cs, 4, _channel_select_command, _rx_buffer);
}
uint32_t AD7616::getMeasurementPair(int cs, uint8_t channel){
prepareChannel(channel, cs);
_gpio->set_output(_trigger_measurement_gpio, Embedded_GPIO::gpio_state::EMB_ON);
_gpio->set_output(_trigger_measurement_gpio, Embedded_GPIO::gpio_state::EMB_OFF);
_dev->transferSPI(cs, 4, _tx_buffer, _rx_buffer);
uint32_t ret = 0;
ret = (uint8_t)_rx_buffer[0] << 24 | (uint8_t)_rx_buffer[1] << 16 | (uint8_t)_rx_buffer[2] << 8 | (uint8_t)_rx_buffer[3];
return ret;
}
| [
"arne.hitzmann@gmail.com"
] | arne.hitzmann@gmail.com |
116599c82954fb1564a605a261345e8c6b27e0cd | 1cf0d109e5f5c29d938158829cb96a5a5c0fdfee | /StringTransformationThroughDictionaryWords.cpp | 9bdc42037b3a40a4a49e7d7ae675d1439b6c7846 | [] | no_license | gauraviitp/cpp | ca4a189e4cf83555370986df20e8b076ca5546db | 394b5d00886ec7aadc4f81b804e3ee79d8cf6358 | refs/heads/master | 2020-03-28T22:38:15.215529 | 2019-09-12T21:54:13 | 2019-09-12T21:54:13 | 94,628,550 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,594 | cpp | // ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <algorithm>
#include <climits>
#include <iostream>
#include <map>
#include <string>
#include <unordered_set>
#include <vector>
using namespace std;
typedef vector<string> VS;
typedef map<string, VS> MSVS;
typedef unordered_set<string> US;
bool compare(const string& a, const string& b) {
if (a.length() != b.length()) return false;
int diffs = 0;
for (int i = 0; i < a.length(); ++i) {
if (a[i] != b[i]) {
diffs++;
if (diffs > 1) {
return false;
}
}
}
if (diffs == 1) return true;
else return false;
}
int dfs(MSVS& g, string& node, string& target, int level, US& us) {
if (node == target) return level;
int minLevel = INT_MAX;
us.insert(node);
VS& v = g[node];
for (auto& e : v) {
if (us.find(e) == us.end()) {
minLevel = min(minLevel, dfs(g, e, target, level + 1, us));
}
}
us.erase(node);
return minLevel;
}
int main() {
// Read the input
freopen("input.txt", "r", stdin);
freopen("output.txt", "w+", stdout);
string start;
string target;
cin >> start >> target;
int n;
cin >> n;
string word;
VS dict;
while (getline(cin, word)) {
if (word.empty()) continue;
dict.push_back(word);
}
// push target when target not in dict
//dict.push_back(target);
// Create the graph
MSVS g;
for (auto& ea : dict) {
VS v;
for (auto& eb : dict) {
if (compare(ea, eb)) {
v.push_back(eb);
}
}
g[ea] = v;
}
US us;
int minTransforms = dfs(g, start, target, 1, us);
cout << minTransforms << "\n";
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
e2e8089da58b0783b348430c36d88f25fc60b567 | 163dc8d3c9be4e2c3cf713b1ca6e1bd3993bcac6 | /include/mixr/map/rpf/CadrgTocEntry.hpp | 2fe105e4a40bfebc4477112128f136affb6d7445 | [] | no_license | azcbuell/mixr | 3091c75d0d4f489ee8385ea38612d7b4bfe5550c | b1ccf3166f1feb0c4c8822a18adb83e8d2ceee8a | refs/heads/master | 2021-01-20T05:34:39.662113 | 2017-09-08T23:03:00 | 2017-09-08T23:03:00 | 101,452,440 | 0 | 0 | null | 2017-08-26T00:44:34 | 2017-08-26T00:44:34 | null | UTF-8 | C++ | false | false | 5,598 | hpp |
#ifndef __mixr_map_rpf_CadrgTocEntry_H__
#define __mixr_map_rpf_CadrgTocEntry_H__
#include "mixr/map/rpf/CadrgFrameEntry.hpp"
#include "mixr/base/Object.hpp"
namespace mixr {
namespace rpf {
//------------------------------------------------------------------------------
// Class: CadrgTocEntry
//
// This is a Table of Contents Boundary Rectangle Entry, which describes the
// boundary of a given set of frames, including the scale and size of the
// rectangle.
//
// Subroutines:
// getFrameEntry() - Return the frame at the given row, column.
// CadrgFrameEntry* CadrgTocEntry::getFrameEntry(const int v, const int h)
//
// generateItems() - Simply generate the name of the file we are using for our image.
// void CadrgTocEntry::generateItems()
//
// setType() - Sets our entry type (ie... "CADRG")
// void CadrgTocEntry::setType(const char* x, const int size)
//
// setZone() - Sets the zone this entry lies in
// void CadrgTocEntry::setZone(const char* x, const int size)
//
// setScale() - Sets the scale of this entry (ie... "1:500K")
// void CadrgTocEntry::setScale(const char* x, const int size)
//
// isInZone() - Takes in a lat lon and returns true if that point falls in our entry
// bool CadrgTocEntry::isInZone(double lat, double lon)
//------------------------------------------------------------------------------
class CadrgTocEntry : public base::Object
{
DECLARE_SUBCLASS(CadrgTocEntry, base::Object)
public:
CadrgTocEntry();
// Get functions
double getNWLat() { return nwLat; }
double getNWLon() { return nwLon; }
double getSWLat() { return swLat; }
double getSWLon() { return swLon; }
double getNELat() { return neLat; }
double getNELon() { return neLon; }
double getSELat() { return seLat; }
double getSELon() { return seLon; }
double getHorizInterval() { return horizInterval; }
double getVertInterval() { return vertInterval; }
int getHorizFrames() { return horizFrames; }
int getVertFrames() { return vertFrames; }
int isMapImage() { return mapImage; }
int getMapIndex() { return mapIndex; }
bool isInZone(double lat, double lon);
double getVertResolution() { return vertResolution; }
double getHorizResolution() { return horizResolution; }
const char* getType() { return type; }
const char* getZone() { return zone; }
const char* getScale () { return scale; }
const char* getTitle() { return title; }
CadrgFrameEntry* getFrameEntry(const int v, const int h);
CadrgFrameEntry** getFrames() { return frames; }
// Set functions
virtual void setNWLat(const double x) { nwLat = x; }
virtual void setNWLon(const double x) { nwLon = x; }
virtual void setSWLat(const double x) { swLat = x; }
virtual void setSWLon(const double x) { swLon = x; }
virtual void setNELat(const double x) { neLat = x; }
virtual void setNELon(const double x) { neLon = x; }
virtual void setSELat(const double x) { seLat = x; }
virtual void setSELon(const double x) { seLon = x; }
virtual void setHorizInterval(const double x) { horizInterval = x; }
virtual void setVertInterval(const double x) { vertInterval = x; }
virtual void setVertFrames(const int x) { vertFrames = x; }
virtual void setHorizFrames(const int x) { horizFrames = x; }
virtual void setVertResolution(const double x) { vertResolution = x; }
virtual void setHorizResolution(const double x) { horizResolution = x; }
virtual void setType(const char* x, const int size);
virtual void setZone(const char* x, const int size);
virtual void setScale(const char* x, const int size);
virtual void setEntries(CadrgFrameEntry** x) { frames = x; }
virtual void setMapIndex(const int x) { mapIndex = x; }
// Generate our frames
virtual void generateItems();
private:
char type[5] {}; // Type of map entry we are (ie.. CADRG)
char scale[12] {}; // Scale of this entry (1:500K, etc.)
char zone[1] {}; // Zone this entry falls in
double nwLat {}; // Northwest latitude of entry
double nwLon {}; // Northwest longitude of entry
double seLat {}; // Southeast latitude of entry
double seLon {}; // Southeast longitude of entry
double swLat {}; // Southwest latitude of entry
double swLon {}; // Southwest longitude of entry
double neLat {}; // Northeast latitude of entry
double neLon {}; // Northeast longitude of entry
double vertInterval {}; // Distance (deg) between each pixel in this entry NS
double horizInterval {}; // Distance (deg) between each pixel in the entry EW
double vertResolution {}; // Resolution (pixels) NS
double horizResolution {}; // Resolution (pixels) EW
int horizFrames {}; // Number of horizontal frames (rows)
int vertFrames {}; // Number of vertical frames (cols)
char title[100]; // Full name of file we represent
int mapImage {}; // are we a map image?
int mapIndex {-1}; // index to keep track of which map file we belong to
CadrgFrameEntry** frames {}; // Our array of frames that make up this entry.
};
}
}
#endif
| [
"doug@openeaagles.org"
] | doug@openeaagles.org |
dcd992e8aa00bde0af3113fc790417c71aa18356 | 8b393f1b7b02443d4365d1d99c468dcd2f810b10 | /wled00/wled17_mqtt.ino | 5e6e418627a92bfe75ffe82395715d5251da731d | [
"MIT"
] | permissive | TheAeroPath/m5stickCLED | 5796ba16d21d6bd523d90d8a21dfa777de160eec | 931d14d9ce47f78d863b09af10e3f6e51b7d0ced | refs/heads/master | 2023-03-19T15:00:49.180859 | 2019-06-23T09:55:00 | 2019-06-23T09:55:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,941 | ino | /*
* MQTT communication protocol for home automation
*/
#define WLED_MQTT_PORT 1883
void parseMQTTBriPayload(char* payload)
{
if (strstr(payload, "ON") || strstr(payload, "on") || strstr(payload, "true")) {bri = briLast; colorUpdated(1);}
else if (strstr(payload, "T" ) || strstr(payload, "t" )) {toggleOnOff(); colorUpdated(1);}
else {
uint8_t in = strtoul(payload, NULL, 10);
if (in == 0 && bri > 0) briLast = bri;
bri = in;
colorUpdated(1);
}
}
void onMqttConnect(bool sessionPresent)
{
//(re)subscribe to required topics
char subuf[38];
strcpy(subuf, mqttDeviceTopic);
if (mqttDeviceTopic[0] != 0)
{
strcpy(subuf, mqttDeviceTopic);
mqtt->subscribe(subuf, 0);
strcat(subuf, "/col");
mqtt->subscribe(subuf, 0);
strcpy(subuf, mqttDeviceTopic);
strcat(subuf, "/api");
mqtt->subscribe(subuf, 0);
}
if (mqttGroupTopic[0] != 0)
{
strcpy(subuf, mqttGroupTopic);
mqtt->subscribe(subuf, 0);
strcat(subuf, "/col");
mqtt->subscribe(subuf, 0);
strcpy(subuf, mqttGroupTopic);
strcat(subuf, "/api");
mqtt->subscribe(subuf, 0);
}
sendHADiscoveryMQTT();
publishMqtt();
DEBUG_PRINTLN("MQTT ready");
}
void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
DEBUG_PRINT("MQTT callb rec: ");
DEBUG_PRINTLN(topic);
DEBUG_PRINTLN(payload);
//no need to check the topic because we only get topics we are subscribed to
if (strstr(topic, "/col"))
{
colorFromDecOrHexString(col, (char*)payload);
colorUpdated(1);
} else if (strstr(topic, "/api"))
{
String apireq = "win&";
apireq += (char*)payload;
handleSet(nullptr, apireq);
} else parseMQTTBriPayload(payload);
}
void publishMqtt()
{
if (mqtt == NULL) return;
if (!mqtt->connected()) return;
DEBUG_PRINTLN("Publish MQTT");
char s[10];
char subuf[38];
sprintf(s, "%ld", bri);
strcpy(subuf, mqttDeviceTopic);
strcat(subuf, "/g");
mqtt->publish(subuf, 0, true, s);
sprintf(s, "#%06X", col[3]*16777216 + col[0]*65536 + col[1]*256 + col[2]);
strcpy(subuf, mqttDeviceTopic);
strcat(subuf, "/c");
mqtt->publish(subuf, 0, true, s);
char apires[1024];
XML_response(nullptr, false, apires);
strcpy(subuf, mqttDeviceTopic);
strcat(subuf, "/v");
mqtt->publish(subuf, 0, true, apires);
}
const char HA_static_JSON[] PROGMEM = R"=====(,"bri_val_tpl":"{{value}}","rgb_cmd_tpl":"{{'#%02x%02x%02x' | format(red, green, blue)}}","rgb_val_tpl":"{{value[1:3]|int(base=16)}},{{value[3:5]|int(base=16)}},{{value[5:7]|int(base=16)}}","qos":0,"opt":true,"pl_on":"ON","pl_off":"OFF","fx_val_tpl":"{{value}}","fx_list":[)=====";
void sendHADiscoveryMQTT(){
#if ARDUINO_ARCH_ESP32 || LEDPIN != 3
/*
YYYY is discovery tipic
XXXX is device name
Send out HA MQTT Discovery message on MQTT connect (~2.4kB):
{
"name": "XXXX",
"stat_t":"YYYY/c",
"cmd_t":"YYYY",
"rgb_stat_t":"YYYY/c",
"rgb_cmd_t":"YYYY/col",
"bri_cmd_t":"YYYY",
"bri_stat_t":"YYYY/g",
"bri_val_tpl":"{{value}}",
"rgb_cmd_tpl":"{{'#%02x%02x%02x' | format(red, green, blue)}}",
"rgb_val_tpl":"{{value[1:3]|int(base=16)}},{{value[3:5]|int(base=16)}},{{value[5:7]|int(base=16)}}",
"qos": 0,
"opt":true,
"pl_on": "ON",
"pl_off": "OFF",
"fx_cmd_t":"YYYY/api",
"fx_stat_t":"YYYY/api",
"fx_val_tpl":"{{value}}",
"fx_list":[
"[FX=00] Solid",
"[FX=01] Blink",
"[FX=02] ...",
"[FX=79] Ripple"
]
}
*/
char bufc[36], bufcol[38], bufg[36], bufapi[38], buffer[2500];
strcpy(bufc, mqttDeviceTopic);
strcpy(bufcol, mqttDeviceTopic);
strcpy(bufg, mqttDeviceTopic);
strcpy(bufapi, mqttDeviceTopic);
strcat(bufc, "/c");
strcat(bufcol, "/col");
strcat(bufg, "/g");
strcat(bufapi, "/api");
StaticJsonBuffer<JSON_OBJECT_SIZE(9) +512> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
root["name"] = serverDescription;
root["stat_t"] = bufc;
root["cmd_t"] = mqttDeviceTopic;
root["rgb_stat_t"] = bufc;
root["rgb_cmd_t"] = bufcol;
root["bri_cmd_t"] = mqttDeviceTopic;
root["bri_stat_t"] = bufg;
root["fx_cmd_t"] = bufapi;
root["fx_stat_t"] = bufapi;
size_t jlen = root.measureLength();
char pubt[21 + sizeof(serverDescription) + 8];
DEBUG_PRINTLN(jlen);
root.printTo(buffer, jlen);
//add values which don't change
strcpy_P(buffer + jlen -1, HA_static_JSON);
olen = 0;
obuf = buffer + jlen -1 + strlen_P(HA_static_JSON);
//add fx_list
uint16_t jmnlen = strlen_P(JSON_mode_names);
uint16_t nameStart = 0, nameEnd = 0;
int i = 0;
bool isNameStart = true;
for (uint16_t j = 0; j < jmnlen; j++)
{
if (pgm_read_byte(JSON_mode_names + j) == '\"' || j == jmnlen -1)
{
if (isNameStart)
{
nameStart = j +1;
}
else
{
nameEnd = j;
char mdnfx[64], mdn[56];
uint16_t namelen = nameEnd - nameStart;
strncpy_P(mdn, JSON_mode_names + nameStart, namelen);
mdn[namelen] = 0;
snprintf(mdnfx, 64, "\"[FX=%02d] %s\",", i, mdn);
oappend(mdnfx);
DEBUG_PRINTLN(mdnfx);
i++;
}
isNameStart = !isNameStart;
}
}
olen--;
oappend("]}");
DEBUG_PRINT("HA Discovery Sending >>");
DEBUG_PRINTLN(buffer);
strcpy(pubt, "homeassistant/light/WLED_");
strcat(pubt, escapedMac.c_str());
strcat(pubt, "/config");
mqtt->publish(pubt, 0, true, buffer);
#endif
}
bool initMqtt()
{
if (mqttServer[0] == 0) return false;
if (WiFi.status() != WL_CONNECTED) return false;
if (!mqtt) mqtt = new AsyncMqttClient();
if (mqtt->connected()) return true;
IPAddress mqttIP;
if (mqttIP.fromString(mqttServer)) //see if server is IP or domain
{
mqtt->setServer(mqttIP, WLED_MQTT_PORT);
} else {
mqtt->setServer(mqttServer, WLED_MQTT_PORT);
}
mqtt->setClientId(escapedMac.c_str());
mqtt->onMessage(onMqttMessage);
mqtt->onConnect(onMqttConnect);
mqtt->connect();
return true;
}
| [
"aenertia@aenertia.net"
] | aenertia@aenertia.net |
f353a5cb63c43c139c5cf4ff9b5b0a565a7db407 | a7764174fb0351ea666faa9f3b5dfe304390a011 | /inc/V3d_TypeOfView.hxx | 0e2d26a3cdddf8995824d3abc418b33a2e2e9909 | [] | no_license | uel-dataexchange/Opencascade_uel | f7123943e9d8124f4fa67579e3cd3f85cfe52d91 | 06ec93d238d3e3ea2881ff44ba8c21cf870435cd | refs/heads/master | 2022-11-16T07:40:30.837854 | 2020-07-08T01:56:37 | 2020-07-08T01:56:37 | 276,290,778 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 518 | hxx | // This file is generated by WOK (CPPExt).
// Please do not edit this file; modify original file instead.
// The copyright and license terms as defined for the original file apply to
// this header file considered to be the "object code" form of the original source.
#ifndef _V3d_TypeOfView_HeaderFile
#define _V3d_TypeOfView_HeaderFile
enum V3d_TypeOfView {
V3d_ORTHOGRAPHIC,
V3d_PERSPECTIVE
};
#ifndef _Standard_PrimitiveTypes_HeaderFile
#include <Standard_PrimitiveTypes.hxx>
#endif
#endif
| [
"shoka.sho2@excel.co.jp"
] | shoka.sho2@excel.co.jp |
c8633c90cc57e5dba870ba3ddf2c27591ec54e32 | 1ceed49a59cc104695732b404ce3f195ae3d4954 | /sem 1/6.16/main.cpp | e56be619f80eff1a09f7deceaee812c84f2b6f4c | [] | no_license | pawellazicki/C_Homework | 60804b4627082c9ff4edb1d8b5b38af37825ecf2 | 725e59ce635fa8c908d2d4d74610ac7cda5ba73a | refs/heads/master | 2020-05-29T16:57:05.415139 | 2019-05-29T16:01:21 | 2019-05-29T16:01:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 713 | cpp | // program wczytuje macierz 5 na 5 i pokazuje kolumny ktorych suma jest najwieksza
#include <stdio.h>
#include <stdlib.h>
#define N 5
int main()
{
int tab[N][N],i,a,s[N],maxi;
printf("wpisz liczby:\n");
for(i=0;i<N;i++)
{
for(a=0;a<N;a++)
{
scanf("%d", &tab[i][a]);
}
}
for(i=0;i<N;i++)
{
s[i]=0;
for(a=0;a<N;a++)
{
s[i]+=tab[a][i];
}
}
maxi=s[0];
for(i=0;i<N;i++)
{
if(s[i]>maxi)
maxi=s[i];
}
for(i=0;i<N;i++)
{
if(maxi==s[i])
printf("%d %d %d %d %d\n", tab[0][i],tab[1][i],tab[2][i],tab[3][i],tab[4][i]);
}
return 0;
}
| [
"pawelllaz@gmail.com"
] | pawelllaz@gmail.com |
b534ad7c7610883747062435c3433eb2a59fbe69 | 600df3590cce1fe49b9a96e9ca5b5242884a2a70 | /buildtools/third_party/libc++/trunk/test/std/containers/associative/set/set.special/swap_noexcept.pass.cpp | 3ec6976127545e35927f32818e4880ec5ee5642a | [
"MIT",
"NCSA",
"BSD-3-Clause"
] | permissive | metux/chromium-suckless | efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a | 72a05af97787001756bae2511b7985e61498c965 | refs/heads/orig | 2022-12-04T23:53:58.681218 | 2017-04-30T10:59:06 | 2017-04-30T23:35:58 | 89,884,931 | 5 | 3 | BSD-3-Clause | 2022-11-23T20:52:53 | 2017-05-01T00:09:08 | null | UTF-8 | C++ | false | false | 3,885 | cpp | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <set>
// void swap(set& c)
// noexcept(!allocator_type::propagate_on_container_swap::value ||
// __is_nothrow_swappable<allocator_type>::value);
//
// In C++17, the standard says that swap shall have:
// noexcept(allocator_traits<Allocator>::is_always_equal::value &&
// noexcept(swap(declval<Compare&>(), declval<Compare&>())));
// This tests a conforming extension
#include <set>
#include <cassert>
#include "MoveOnly.h"
#include "test_allocator.h"
template <class T>
struct some_comp
{
typedef T value_type;
some_comp() {}
some_comp(const some_comp&) {}
void deallocate(void*, unsigned) {}
typedef std::true_type propagate_on_container_swap;
};
template <class T>
struct some_comp2
{
typedef T value_type;
some_comp2() {}
some_comp2(const some_comp2&) {}
void deallocate(void*, unsigned) {}
typedef std::true_type propagate_on_container_swap;
};
#if TEST_STD_VER >= 14
template <typename T>
void swap(some_comp2<T>&, some_comp2<T>&) noexcept {}
#endif
template <class T>
struct some_alloc
{
typedef T value_type;
some_alloc() {}
some_alloc(const some_alloc&);
void deallocate(void*, unsigned) {}
typedef std::true_type propagate_on_container_swap;
};
template <class T>
struct some_alloc2
{
typedef T value_type;
some_alloc2() {}
some_alloc2(const some_alloc2&);
void deallocate(void*, unsigned) {}
typedef std::false_type propagate_on_container_swap;
typedef std::true_type is_always_equal;
};
template <class T>
struct some_alloc3
{
typedef T value_type;
some_alloc3() {}
some_alloc3(const some_alloc3&);
void deallocate(void*, unsigned) {}
typedef std::false_type propagate_on_container_swap;
typedef std::false_type is_always_equal;
};
int main()
{
#if __has_feature(cxx_noexcept)
{
typedef std::set<MoveOnly> C;
C c1, c2;
static_assert(noexcept(swap(c1, c2)), "");
}
{
typedef std::set<MoveOnly, std::less<MoveOnly>, test_allocator<MoveOnly>> C;
C c1, c2;
static_assert(noexcept(swap(c1, c2)), "");
}
{
typedef std::set<MoveOnly, std::less<MoveOnly>, other_allocator<MoveOnly>> C;
C c1, c2;
static_assert(noexcept(swap(c1, c2)), "");
}
{
typedef std::set<MoveOnly, some_comp<MoveOnly>> C;
C c1, c2;
static_assert(!noexcept(swap(c1, c2)), "");
}
#if TEST_STD_VER >= 14
{ // POCS allocator, throwable swap for comp
typedef std::set<MoveOnly, some_comp <MoveOnly>, some_alloc <MoveOnly>> C;
C c1, c2;
static_assert(!noexcept(swap(c1, c2)), "");
}
{ // always equal allocator, throwable swap for comp
typedef std::set<MoveOnly, some_comp <MoveOnly>, some_alloc2<MoveOnly>> C;
C c1, c2;
static_assert(!noexcept(swap(c1, c2)), "");
}
{ // POCS allocator, nothrow swap for comp
typedef std::set<MoveOnly, some_comp2<MoveOnly>, some_alloc <MoveOnly>> C;
C c1, c2;
static_assert( noexcept(swap(c1, c2)), "");
}
{ // always equal allocator, nothrow swap for comp
typedef std::set<MoveOnly, some_comp2<MoveOnly>, some_alloc2<MoveOnly>> C;
C c1, c2;
static_assert( noexcept(swap(c1, c2)), "");
}
{ // NOT always equal allocator, nothrow swap for comp
typedef std::set<MoveOnly, some_comp2<MoveOnly>, some_alloc3<MoveOnly>> C;
C c1, c2;
static_assert( noexcept(swap(c1, c2)), "");
}
#endif
#endif
}
| [
"enrico.weigelt@gr13.net"
] | enrico.weigelt@gr13.net |
ce0816a0eae011e1ba35071229d4ca7f60a6d46b | 351916691d65c96c6d9330fe735daaab4bfddfdf | /LibraryManager/BookEdit.cpp | 49dc04d7d06268458ef8cc723d9d5d50bfca7c4d | [] | no_license | TianbaoLi/LibraryManager | c268377081e76c7cd7192f7dcb112230562bc3f0 | e7ef97c3c8f2cc089fceed686076008305c4edc9 | refs/heads/master | 2021-09-09T00:53:37.561523 | 2015-01-05T05:18:56 | 2015-01-05T05:18:56 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,325 | cpp | // BookEdit.cpp : 实现文件
//
#include "stdafx.h"
#include "LibraryManager.h"
#include "BookEdit.h"
#include "afxdialogex.h"
#include "BookManager.h"
// BookEdit 对话框
IMPLEMENT_DYNAMIC(BookEdit, CDialogEx)
BookEdit::BookEdit(CWnd* pParent /*=NULL*/)
: CDialogEx(BookEdit::IDD, pParent)
{
}
BookEdit::~BookEdit()
{
}
void BookEdit::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_EDIT2, Edit_BookEditName);
DDX_Control(pDX, IDC_EDIT3, Edit_BookEditNumber);
DDX_Control(pDX, IDC_EDIT4, Edit_BookEditAmount);
DDX_Control(pDX, IDC_EDIT7, Edit_BookEditYear);
DDX_Control(pDX, IDC_EDIT9, Edit_BookEditDay);
DDX_Control(pDX, IDC_EDIT8, Edit_BookEditMonth);
}
BEGIN_MESSAGE_MAP(BookEdit, CDialogEx)
ON_BN_CLICKED(IDBookEdit, &BookEdit::OnBnClickedBookedit)
END_MESSAGE_MAP()
// BookEdit 消息处理程序
void BookEdit::OnBnClickedBookedit()
{
// TODO: 在此添加控件通知处理程序代码
CString bookname,temp;
int number,amount,year,month,day;
Edit_BookEditName.GetWindowTextW(bookname);
if(bookname==TEXT(""))
MessageBox(TEXT("请输入书名"),TEXT("错误"));
else
{
Edit_BookEditNumber.GetWindowTextW(temp);
if(temp==TEXT(""))
MessageBox(TEXT("请输入书号"),TEXT("错误"));
else
{
number=StrToInt(temp);
Edit_BookEditAmount.GetWindowTextW(temp);
if(temp==TEXT(""))
MessageBox(TEXT("请输入数量"),TEXT("错误"));
else
{
amount=StrToInt(temp);
Edit_BookEditYear.GetWindowTextW(temp);
if(temp==TEXT(""))
MessageBox(TEXT("请输入年"),TEXT("错误"));
else
{
year=StrToInt(temp);
Edit_BookEditMonth.GetWindowTextW(temp);
if(temp==TEXT(""))
MessageBox(TEXT("请输入月"),TEXT("错误"));
else
{
month=StrToInt(temp);
Edit_BookEditDay.GetWindowTextW(temp);
if(temp==TEXT(""))
MessageBox(TEXT("请输入日"),TEXT("错误"));
else
{
day=StrToInt(temp);
BookManager bookmanager;
Book book=Book(bookname,number,amount,year,month,day,0);
if(bookmanager.EditBook(book)==1)
MessageBox(TEXT("成功修改"),TEXT("成功"));
else
MessageBox(TEXT("修改失败,未找到图书"),TEXT("失败"));
BookEdit::OnCancel();
}
}
}
}
}
}
}
| [
"turingmac@hotmail.com"
] | turingmac@hotmail.com |
3b5fa77371a8b36db8ff7d0352527cfc6360b779 | 4c23be1a0ca76f68e7146f7d098e26c2bbfb2650 | /ic8h18/0.007/NC7H14OOH-P | 04cbe11a91aca863565d47ec80c0b087faa61703 | [] | no_license | labsandy/OpenFOAM_workspace | a74b473903ddbd34b31dc93917e3719bc051e379 | 6e0193ad9dabd613acf40d6b3ec4c0536c90aed4 | refs/heads/master | 2022-02-25T02:36:04.164324 | 2019-08-23T02:27:16 | 2019-08-23T02:27:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 843 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 6
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0.007";
object NC7H14OOH-P;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 0 0 0 0];
internalField uniform 3.30505e-46;
boundaryField
{
boundary
{
type empty;
}
}
// ************************************************************************* //
| [
"jfeatherstone123@gmail.com"
] | jfeatherstone123@gmail.com | |
b6f2185189637c304bf5734cf92ce751efcc7c01 | cf2939e41477981c3dab7918afa699baf81e5aad | /src/boost/polygon/polygon_90_data.hpp | f44023c350b5d4549c06ffed3e231d0a1668dec3 | [
"BSL-1.0"
] | permissive | ivankravets/arduino-boost | 250187c853a15de3da086fe12baab1a6a3c72ec6 | 10696aee3f6150f26734c43f9da2070e9fca9582 | refs/heads/master | 2020-03-28T06:54:13.522677 | 2018-09-06T01:08:21 | 2018-09-06T01:08:21 | 147,868,298 | 1 | 0 | BSL-1.0 | 2018-09-07T19:50:04 | 2018-09-07T19:50:04 | null | UTF-8 | C++ | false | false | 2,977 | hpp | /*
Copyright 2008 Intel Corporation
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).
*/
#ifndef BOOST_POLYGON_POLYGON_90_DATA_HPP
#define BOOST_POLYGON_POLYGON_90_DATA_HPP
namespace boost { namespace polygon{
struct polygon_90_concept;
template <typename T>
class polygon_90_data {
public:
typedef polygon_90_concept geometry_type;
typedef T coordinate_type;
typedef typename std::vector<coordinate_type>::const_iterator compact_iterator_type;
typedef iterator_compact_to_points<compact_iterator_type, point_data<coordinate_type> > iterator_type;
typedef typename coordinate_traits<T>::area_type area_type;
inline polygon_90_data() : coords_() {} //do nothing default constructor
// initialize a polygon from x,y values, it is assumed that the first is an x
// and that the input is a well behaved polygon
template<class iT>
inline polygon_90_data& set(iT begin_point, iT end_point) {
return set_compact(iterator_points_to_compact<iT, typename std::iterator_traits<iT>::value_type>(begin_point, end_point),
iterator_points_to_compact<iT, typename std::iterator_traits<iT>::value_type>(end_point, end_point));
}
template<class iT>
inline polygon_90_data& set_compact(iT input_begin, iT input_end) {
coords_.clear(); //just in case there was some old data there
while(input_begin != input_end) {
coords_.insert(coords_.end(), *input_begin);
++input_begin;
}
return *this;
}
// copy constructor (since we have dynamic memory)
inline polygon_90_data(const polygon_90_data& that) : coords_(that.coords_) {}
// assignment operator (since we have dynamic memory do a deep copy)
inline polygon_90_data& operator=(const polygon_90_data& that) {
coords_ = that.coords_;
return *this;
}
template <typename T2>
inline polygon_90_data& operator=(const T2& rvalue);
// assignment operator (since we have dynamic memory do a deep copy)
inline bool operator==(const polygon_90_data& that) const {
return coords_ == that.coords_;
}
// get begin iterator, returns a pointer to a const Unit
inline iterator_type begin() const { return iterator_type(coords_.begin(), coords_.end()); }
// get end iterator, returns a pointer to a const Unit
inline iterator_type end() const { return iterator_type(coords_.end(), coords_.end()); }
// get begin iterator, returns a pointer to a const Unit
inline compact_iterator_type begin_compact() const { return coords_.begin(); }
// get end iterator, returns a pointer to a const Unit
inline compact_iterator_type end_compact() const { return coords_.end(); }
inline std::size_t size() const { return coords_.size(); }
private:
std::vector<coordinate_type> coords_;
};
}
}
#endif
| [
"rpavlik@iastate.edu"
] | rpavlik@iastate.edu |
43633aa34c91c18c530baa0bfd0364119a4c77e6 | 80e7858df30191bf233302a3730c31b9397ad37e | /Personal_Practice/constructor.cpp | 5c019f758dd4b59dc1918c13243f07c07890a306 | [] | no_license | junyoung5/ev3Project | 6ae63880e1d80a2ed66a0ea6ee49d37de1e744b1 | 950367825d14e22552e82504a59e136ccf3547d9 | refs/heads/master | 2021-08-31T14:31:03.983991 | 2017-12-21T17:42:40 | 2017-12-21T17:42:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 576 | cpp | #include <iostream>
//formal parameter의 이름을 달리한 경우
class Student
{
private:
int age;
char* name;
public:
Student();
Student(int Age, char * Name) //formal parameter의 이름을 달리한 경우
{
age = Age;
name = Name;
}
}
//formal parameter의 이름과 Attribute이름 같게 하나 This 함수 사용.
class Student
{
private:
int age;
char* name;
public:
Student();
Student(int age, char * name)
{
this -> age = age;
this -> name = name;
}
}
| [
"21300455@handong.edu"
] | 21300455@handong.edu |
842a37e8672be2cb0e0d9867084d5bd1980fc17e | 9538a4d0b744965d84bb97447002b585513cee8f | /greedy.cpp | c24be56e6e613d7bdca330ac4745367947e2f45d | [] | no_license | bamboo-hust/google-hashcode | 5a88bf90f3908f6739ee42f2f42c8a31807aeab9 | 72074ae48efc06d15ddc0451a97cf792c60a095a | refs/heads/master | 2021-01-04T20:05:22.644501 | 2020-02-17T05:42:30 | 2020-02-17T05:42:30 | 240,741,788 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 463 | cpp | #include <bits/stdc++.h>
using namespace std;
int m, n;
vector<int> a;
int main() {
cin >> m >> n;
a.resize(n);
for (int i = 0; i < n; ++i) cin >> a[i];
vector<int> res;
for (int i = n - 1; i >= 0; --i) {
if (m >= a[i]) {
m -= a[i];
res.push_back(i);
}
}
reverse(begin(res), end(res));
cout << res.size() << endl;
for (int i : res) cout << i << ' ';
cout << endl;
return 0;
} | [
"anhducle@coccoc.com"
] | anhducle@coccoc.com |
f7fb38b79aa4bf18554488d8753332fb97fa92be | 39b853ddd115dea90f667829c75e1110a3ffa6a5 | /Others/Odev2.cpp | 82ca0bac12425d9fee20a0d1927888727e0a86d8 | [] | no_license | muhammet-mucahit/My-C-Studies | c238d4e51674f856d08447ad02debf7a06ca3787 | 458de617df8096b5e50bd1be6940e0bd32484b10 | refs/heads/master | 2020-06-28T14:30:55.203428 | 2019-08-02T15:19:00 | 2019-08-02T15:19:00 | 200,255,747 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 399 | cpp | #include<stdio.h>
#include<math.h>
int main()
{
int a,b,c;
printf("1.sayiyi giriniz :");scanf("%d",&a);
printf("2.sayiyi giriniz :");scanf("%d",&b);
printf("3.sayiyi giriniz :");scanf("%d",&c);
if(a>b)
{
if(a>c)
{
printf("En buyuk a.");
}
else
{
printf("En buyuk c.");
}
}
else
{
if(b>c)
{
printf("En buyuk b.");
}
else
{
printf("En buyuk c.");
}
}
}
| [
"mucahit@zeo.org"
] | mucahit@zeo.org |
7e9fd726729c19137471fe024a6e6c90eaddd4a6 | fb8b507984a7b61999a49175b9c82d79ab4d517a | /src/display/screenshot.hpp | 0b0ae7791eb08e19f3f86609661a2d8b850701fb | [] | no_license | henrypc6/clothSim | 1e110508c39a27d84d216bfb97357a33f1db1499 | 7d2c4f7d5b8ef15f42c088db9da284c78e65f23a | refs/heads/master | 2020-03-16T03:10:02.615744 | 2018-05-09T04:14:06 | 2018-05-09T04:14:06 | 132,481,841 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 227 | hpp | #ifndef DISPLAY_SCREENSHOT_HPP
#define DISPLAY_SCREENSHOT_HPP
class Screenshot
{
public:
Screenshot() {}
~Screenshot() {}
void saveScreenshot(const int window, const unsigned int frame, const char* imagesDir);
};
#endif | [
"peng0175@umn.edu"
] | peng0175@umn.edu |
4ca7b5fc80f3a980d033f7c5fa4e591e1617838b | 616e90f1892c8958039059cd00eeb10ddd5e1e92 | /tree/617-merge-two-binary-trees.cpp | 00f16f53a9087f063720e24869feb4c6c862960b | [] | no_license | zuselegacy/leetcode | 3bbd6c5c025b46d40383a46112941b2d7f4503ff | 9d444019211bfa484d99b47a5703cc19763c780b | refs/heads/master | 2022-10-20T19:40:42.087679 | 2022-09-22T13:37:50 | 2022-09-22T13:37:50 | 230,397,626 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,065 | cpp | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* merge(TreeNode* t1, TreeNode* t2) {
if(t1==NULL && t2==NULL)
return NULL;
else if(t2 == NULL)
;
else if(t1 == NULL) {
t1 = new TreeNode(t2->val);
} else {
t1->val += t2->val;
}
TreeNode* node = merge(t1->left, t2==NULL?NULL:t2->left);
t1->left = node;
TreeNode* node2 = merge(t1->right,t2==NULL?NULL:t2->right);
t1->right = node2;
return t1;
}
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
TreeNode* node = merge(t1,t2) ;
return node;
}
};
| [
"zuselegacy@gmail.com"
] | zuselegacy@gmail.com |
70dbbfaca11f2ef4fbf2f2baa49ddc21a53e15e0 | 9869acb3d91e06529f0a017954cae10d796f6fc6 | /keylogger-fud/TimeLog.cpp | dcd14ffbb7f84d0e6d1f230a512785048b897770 | [] | no_license | Patrickjusz/CPP | 2cf39368cf05a0e98058a1346966cfba8a2235d8 | 559bbf1ac33d43ef5796175bc08bfbce9ff0e624 | refs/heads/master | 2021-08-07T09:31:14.192964 | 2017-11-08T00:26:50 | 2017-11-08T00:26:50 | 109,883,260 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,407 | cpp | #include "TimeLog.h"
TimeLog::TimeLog() {
this->config = new Config();
}
int TimeLog::getTimeMs() {
return time(NULL);
}
string TimeLog::loadFileTime() {
FILE *file = fopen(this->config->GetTimeFileName().c_str(), "r");
if (file) {
char tmpBuffor[16]; //UNIX TIME (s) BUFFOR (10 digit [1/1/1970 - 22/04/2015])
fgets(tmpBuffor, 16, file);
fclose(file);
return tmpBuffor;
} else {
return "0";
}
}
bool TimeLog::saveFileTime() {
FILE *file = fopen(this->config->GetTimeFileName().c_str(), "w");
if (file) {
fprintf(file, "%d", this->getTimeMs());
fclose(file);
return true;
} else {
return false;
}
}
bool TimeLog::compareTime() {
int minutyPlik = 0;
string wPlikuTxt = this->loadFileTime();
minutyPlik = atoi(wPlikuTxt.c_str());
int roznica = this->getTimeMs();
roznica = roznica - minutyPlik;
if (roznica >= this->config->GetSendMailTime()) {
roznica = 0;
this->saveFileTime();
return true;
}
return false;
}
string TimeLog::getNowTime() {
time_t rawtime;
struct tm * timeinfo;
char str[158];
time(&rawtime);
timeinfo = localtime(&rawtime);
sprintf(str, "%02d-%02d-%d | %02d:%02d", timeinfo->tm_mday, (timeinfo->tm_mon + 1), (1900 + timeinfo->tm_year), timeinfo->tm_hour, timeinfo->tm_min);
return str;
}
| [
"patryk.jastrzebski91@gmail.com"
] | patryk.jastrzebski91@gmail.com |
e6053de34c6bbf4b0b17234b112130873c208e5f | 4e74645771b2b3457906a52958fd0a2f5931b72c | /Chapter-12/ex1221.cc | 9aacbc856a4dff7c2f26cb9041efb81744f3a7ee | [] | no_license | chushu10/cpp-primer | 750b09a058ab45a8b629312a55f2ac43acd981f7 | 1bd1c90ab46bc02cf0bd039672e489c5cd91bef8 | refs/heads/master | 2022-02-23T00:59:03.861091 | 2019-09-10T13:49:33 | 2019-09-10T13:49:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 438 | cc | #include <string>
#include <fstream>
class NoName {
public:
NoName(const std::string &name, int ival, double *pd, std::ifstream &ifs):
name_(name), ival_(ival), pd_(pd), ifs_(ifs) {}
private:
const std::string name_;
int ival_;
double *pd_;
std::ifstream &ifs_;
};
int main(int argc, char const *argv[])
{
double dval = 0.0;
std::ifstream ifs;
NoName noname("NoName", 0, &dval, ifs);
return 0;
}
| [
"liuchushu10@gmail.com"
] | liuchushu10@gmail.com |
0b806d34763853a120df65c661335e6ff4f6e13c | bb2abaf75ffcafb5cab0bcde2825a5f699c32114 | /cpp_rtype/server/include/Component/Position.hpp | 9efa50e9d1838ae68537f6f306f3384357ad04ae | [] | no_license | leroy-0/CPP_2017 | 72afa80106fb437bb75a3545244098115308cb67 | f8de1b38dec8802ebf74e116470dbd465723bbc7 | refs/heads/master | 2022-06-08T07:59:26.647201 | 2020-05-05T14:34:07 | 2020-05-05T14:34:07 | 261,495,573 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 451 | hpp | //
// Created by Sebastien on 12/01/2018.
//
#ifndef R_TYPE_UI_HPP
#define R_TYPE_UI_HPP
#include <vector>
namespace Component {
struct Position {
enum Geolocalisation
{
LEFT_UP,
RIGHT_UP,
LEFT_DOWN,
RIGHT_DOWN
};
int x;
int y;
std::vector<Component::Position::Geolocalisation> posInMap;
};
}
#endif //R_TYPE_UI_HPP
| [
"maxime.leroy@corp.ovh.com"
] | maxime.leroy@corp.ovh.com |
f6a87bb1134ef8d84a5205e999c9bd9fd274f55d | 3bacd8f24d38a5072fdaa2ae1bb3a1b10c8ef064 | /robot_control/Robotics/Heatmap/Heatmap/Lidar.h | 7b9d1d31b586ae2bc66841e6de6b1a85f3b6f4f1 | [] | no_license | JakobYde/Robotics_Vision_AI_Group_Project | e253fdf753a66486def5ef66c757360857df2f4e | 857e351f07029cda2150ef6263f4bdf61d0e8e29 | refs/heads/master | 2020-11-24T06:09:24.582400 | 2018-12-16T12:38:06 | 2018-12-16T12:38:06 | 228,000,890 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 378 | h | #pragma once
#include "Point.h"
#include "Edge.h"
class Lidar
{
public:
Lidar();
~Lidar();
void newMeasurement();
void addMeasurement(PolarPoint p);
void addMeasurements(std::vector<PolarPoint> points);
Line leastSquareFit(std::vector<PolarPoint> points);
std::vector<Line> getLines();
std::vector<Point> getCorners();
private:
std::vector<PolarPoint> points;
};
| [
"olvea16@student.sdu.dk"
] | olvea16@student.sdu.dk |
d72ec7c465349d200982880c20ec50cf62173814 | bed3ac926beac0f4e0293303d7b2a6031ee476c9 | /Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vnl_sparse_matrix+complex+double--.cxx | c22e8f2a7a3394091d4094da435646f1cae6036a | [
"IJG",
"Zlib",
"LicenseRef-scancode-proprietary-license",
"SMLNJ",
"BSD-3-Clause",
"BSD-4.3TAHOE",
"LicenseRef-scancode-free-unknown",
"Spencer-86",
"LicenseRef-scancode-llnl",
"FSFUL",
"Libpng",
"libtiff",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-permissive",
... | permissive | InsightSoftwareConsortium/ITK | ed9dbbc5b8b3f7511f007c0fc0eebb3ad37b88eb | 3eb8fd7cdfbc5ac2d0c2e5e776848a4cbab3d7e1 | refs/heads/master | 2023-08-31T17:21:47.754304 | 2023-08-31T00:58:51 | 2023-08-31T14:12:21 | 800,928 | 1,229 | 656 | Apache-2.0 | 2023-09-14T17:54:00 | 2010-07-27T15:48:04 | C++ | UTF-8 | C++ | false | false | 120 | cxx | #include "vnl/vnl_complex.h"
#include "vnl/vnl_sparse_matrix.hxx"
VNL_SPARSE_MATRIX_INSTANTIATE(std::complex<double>);
| [
"hans-johnson@uiowa.edu"
] | hans-johnson@uiowa.edu |
045a687a3acb4090f27fc426c945e10d61a4521b | 32987a0e09e0be0f7aa462c4085fae378d0e6759 | /D03/ex04/SuperTrap.hpp | 7843fb7a309536c35098926086c08877c59b9050 | [] | no_license | yslati/CPP | c4994f70e2e7ada110d6de94b3d53f3205bf661f | 328b7d46b4101da79d14f8b884c05dd960088b1e | refs/heads/master | 2023-04-15T15:10:04.073423 | 2021-04-12T16:17:16 | 2021-04-12T16:17:16 | 331,574,864 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,454 | hpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* SuperTrap.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: yslati <yslati@student.1337.ma> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/02/11 15:11:07 by yslati #+# #+# */
/* Updated: 2021/02/14 15:58:23 by yslati ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef SUPER_TRAP_HPP
# define SUPER_TRAP_HPP
# include "FragTrap.hpp"
# include "ClapTrap.hpp"
# include "ScavTrap.hpp"
# include "NinjaTrap.hpp"
class SuperTrap : public FragTrap, public NinjaTrap {
public:
SuperTrap( void );
SuperTrap( std::string const & name );
SuperTrap( SuperTrap const & src );
SuperTrap & operator=( SuperTrap const & src );
~SuperTrap( void );
std::string getname() const {
return _name;
}
void meleeAttack(std::string const & traget);
void rangedAttack(std::string const & target);
private:
};
#endif
| [
"yslati@e2r4p6.1337.ma"
] | yslati@e2r4p6.1337.ma |
9d4ff38791673ffe72f17a50f932ccdba516c4ec | 9c75528c3a4a31a23e3c8f035d19c30ed6a58244 | /SafeArray.cpp | 9343cc934f803c52d555203c7ea467d38867df53 | [] | no_license | LeventJ/SafeArray | bd0f59cf11bfb14ade806a84e1ac7c384409490b | 2c237dd72a508eb390e7a58d639c131bb9668481 | refs/heads/master | 2021-01-01T17:28:29.838011 | 2015-04-24T04:30:15 | 2015-04-24T04:30:15 | 34,491,322 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 681 | cpp | #include "SafeArray.h"
SafeArray::SafeArray(int size)
{
this ->size = size;
number = new int[size];
}
SafeArray::~SafeArray()
{
}
void SafeArray::check(int index)
{
if(index<0||index>size)
{
cout<<"Warning!"<<endl;
// exit(0);
}
}
int& SafeArray::operator[](int index)
{
check(index);
return number[index];
}
istream& operator>>(istream &in,SafeArray &a)
{
int value;
for(int i=0;i<a.size;i++){
in>>value;
a.number[i] = value;
}
return in;
}
ostream& operator<<(ostream &out,const SafeArray &b)
{
for(int i=0;i<b.size;i++){
out<<"["<<i<<"]="<<b.number[i]<<" "<<endl;
}
return out;
}
| [
"Levent_J@163.com"
] | Levent_J@163.com |
7c16f4142aa715e558b4827367290f5b8cdb2dd1 | 2557b930a316247a60108bd7c62b7506f01f8777 | /examples/steady_inlet_outlet_bifurcation/system/controlDict | 3d62fb186555fe416684269b27f29b025e254c30 | [
"MIT"
] | permissive | Chr1sC0de/ArteryScalingLawsBC | 1b49c68d6734698067eef815cb992a4089e1e420 | 254498e26107e3542fedeb456873b5a02c4bd2ad | refs/heads/main | 2023-02-21T06:40:23.114436 | 2021-01-28T01:49:53 | 2021-01-28T01:49:53 | 318,335,876 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,300 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.1.1 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class dictionary;
location "system";
object controlDict;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
application implicitFoam;
startFrom latestTime;
stopAt endTime;
endTime 0.4;
deltaT 1e-03;
writeControl runTime;
writeInterval 0.01;
purgeWrite 0;
writeFormat ascii;
writePrecision 6;
writeCompression off;
timeFormat general;
timePrecision 6;
runTimeModifiable true;
// libraries
libs
(
"libarteryScalingLawOutlet.so"
"libarterySteadyScalingLawInlet.so"
);
// ************************************************************************* //
| [
"63153273+Chr1sC0de@users.noreply.github.com"
] | 63153273+Chr1sC0de@users.noreply.github.com | |
b00b0372a2bb84323134e0e5b358653cb7465ef7 | 2a7889e17a4c8c5c751052661ed0f8498205e960 | /sum of array number.cpp | a22210d741dc235ee638ee9054d081099f4c06ee | [] | no_license | alaminsheikh01/CPP_important-topics | d6e5496374883ec8f58c5f4b18b655368ecfd4b3 | 708f7308debcb3d5042bded785aeebf7fee32dd9 | refs/heads/master | 2022-03-08T19:29:30.700573 | 2019-11-07T05:18:02 | 2019-11-07T05:18:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 184 | cpp | #include<iostream>
using namespace std;
int main()
{
int num[5]={10,20,30,40,50};
int sum=0;
for(int i=0;i<5;i++)
{
sum +=num[i];
cout<<sum<<endl;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
36556279d5274237776cca665599099d61f71108 | c47b80e996fa5469fae837bdba6f213f2460e95c | /buffer.h | 71e4bde2c6167e435fcb19f1a2c6a1023f49c21a | [] | no_license | Felipeasg/LFTracking | c8e2670194205636fee18d1f355992728a51ead0 | d1de1b26a11303923b170b65e3af0584ef869bb7 | refs/heads/master | 2021-01-10T17:19:37.678323 | 2020-07-12T01:02:19 | 2020-07-12T01:02:19 | 36,243,414 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 401 | h | #ifndef BUFFER_H
#define BUFFER_H
class Buffer
{
public:
Buffer(char* array, int size);
~Buffer();
int putByte(char* ch);
int getByte(char* ch);
int putN(char* data, int offset, int n);
int getN(char* data, int offset, int n);
int getLength();
private:
char* data_array;
int array_size;
int get_idx;
int put_idx;
int length;
};
#endif // BUFFER_H
| [
"felipeadrianosg@gmail.com"
] | felipeadrianosg@gmail.com |
4be50e29bb9a36aaec3bed81a32f37be40792540 | bd3bbe85e6652f13090ffd729a6bd8a50e0015a7 | /BinomialTree.hpp | 3618ee80806ec23dd5358f42c477ff74c2d5e368 | [] | no_license | PPPW/Financial-Simulations | c299784e6eae92af6e601e0775209e586933352f | cf4839974a7f6b360df275e8833b7ccd70d16764 | refs/heads/master | 2021-01-10T15:59:16.488523 | 2016-01-02T22:34:23 | 2016-01-02T22:34:23 | 43,526,114 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 884 | hpp | /**
The BinomialTree class generates the binomial tree and uses the tree to
price different instruments.
The default model is Cox-Ross-Rubinstein.
@author Pei Wang
*/
#ifndef BINOMIAL_TREE
#define BINOMIAL_TREE
#include "Trees.hpp"
#include "VanillaOption.hpp"
#include <vector>
class BinomialTree : public Trees
{
public:
BinomialTree(double spot_,
double r_,
double dvdnt_,
double vol_,
double expiry_,
unsigned long NumOfPeriods_);
std::vector<std::vector<double> > TheTree;
void printTree() const;
virtual double priceEuropeanOption(const VanillaOption& option) const;
private:
double spot;
double r;
double dvdnt;
double vol;
double expiry;
double NumOfPeriods;
void buildTree();
double q; // q is model dependent
};
#endif
| [
"pei.wang.fudan@gmail.com"
] | pei.wang.fudan@gmail.com |
32d3bb8b5b62e3ed63a5468db5bb42e114f15be2 | 175cb710901f613caf919bc34fd1d3699aa2458e | /CppPractice/CSES/Dynamic Programming/dp4.cpp | e54ccc9720f8dc5793479960d98e38727de5d026 | [] | no_license | harshit977/CP_Solutions | 0df1cd3ddbebdf0fd840c3a35f876c5ce7d3e3a1 | b83e70f10229da6c2005f12b653ed6aa5eb74a07 | refs/heads/main | 2023-08-12T06:48:50.721317 | 2021-10-01T11:43:18 | 2021-10-01T11:43:18 | 412,458,588 | 1 | 0 | null | 2021-10-01T12:29:36 | 2021-10-01T12:29:35 | null | UTF-8 | C++ | false | false | 1,012 | cpp | #include<bits/stdc++.h>
#define boost ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define ll long long
#define fi for(ll i=0;i<n;i++)
#define pb push_back
ll solve(ll *v,ll n,ll w)
{
int dp[n+1][w+1];
ll mod=1e9+7;
for(int i=1;i<=n;i++)
dp[i][0]=1;
for(int i=0;i<=w;i++)
dp[0][i]=0;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=w;j++)
{
if(v[i-1]<=j)
{
dp[i][j]=(dp[i][j-v[i-1]]%mod+dp[i-1][j]%mod)%mod;
}
else
dp[i][j]=dp[i-1][j]%mod;
}
}
return dp[n][w]%mod;
}
using namespace std;
int main()
{
boost;
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
ll n,x;
cin>>n>>x;
ll v[n];
ll a;
for(int i=0;i<n;i++)
cin>>v[i];
cout<<solve(v,n,x);
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
930d4815bc359d41a95f1c2f1dcb0a525705f60e | 2a99d31e41e265efd0c215ad455e8b8a05d6d84a | /palette.h | eef2a2a0935847dfcabc2cb30f03698c7a3b54b8 | [] | no_license | oragelac/brams-waterfall | e6f8bbeaf37037105417c89d148439d1f236a3a7 | 174a8223c81ed1dabdf9b5c054a3e4c2dcfd28d3 | refs/heads/main | 2023-03-06T04:38:44.614627 | 2021-02-23T09:14:49 | 2021-02-23T09:14:49 | 341,494,421 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 335 | h | #ifndef PALETTE_H
#define PALETTE_H
#include <QColor>
#include <iostream>
class Palette {
public:
Palette();
void setBrightness(int);
void setContrast(int contrast);
QColor *colors;
QColor operator[](unsigned int i);
private:
int brightness;
int contrast;
double _f;
};
#endif // PALETTE_H
| [
"calegaroantoine@gmail.com"
] | calegaroantoine@gmail.com |
b979b9aa993fe18ca5db3e1018d82f16cb771f2c | 4aa72084aa12cb676d51807243e8a70b02ba4ff9 | /Plamadeala_Raytracing_1/Code/objloader.cpp | 28895cf8eea2b750501dc6e3b118ec49ec7b2617 | [
"MIT"
] | permissive | Cornul11/CG_2021 | 90c2b79f48881ab86e6a9a55ab722b9371f4d173 | 286ebb03bade9fa1e1609a603731e9ada994204d | refs/heads/main | 2023-03-26T09:59:17.770765 | 2021-03-22T01:27:28 | 2021-03-22T01:27:28 | 338,468,537 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,620 | cpp | #include "objloader.h"
// Pro C++ Tip: here you can specify other includes you may need
// such as <iostream>
#include <fstream>
#include <iostream>
#include <sstream>
using namespace std;
// ===================================================================
// -- Constructors and destructor ------------------------------------
// ===================================================================
// --- Public --------------------------------------------------------
OBJLoader::OBJLoader(string const &filename)
:
d_hasTexCoords(false) {
parseFile(filename);
}
// ===================================================================
// -- Member functions -----------------------------------------------
// ===================================================================
// --- Public --------------------------------------------------------
vector<Vertex> OBJLoader::vertex_data() const {
vector<Vertex> data;
// For all vertices in the model, interleave the data
for (Vertex_idx const &vertex : d_vertices) {
// Add coordinate data
Vertex vert;
vec3 const coord = d_coordinates.at(vertex.d_coord);
vert.x = coord.x;
vert.y = coord.y;
vert.z = coord.z;
// Add normal data
vec3 const norm = d_normals.at(vertex.d_norm);
vert.nx = norm.x;
vert.ny = norm.y;
vert.nz = norm.z;
// Add texture data (if available)
if (d_hasTexCoords) {
vec2 const tex = d_texCoords.at(vertex.d_tex);
vert.u = tex.u; // u coordinate
vert.v = tex.v; // v coordinate
} else {
vert.u = 0;
vert.v = 0;
}
data.push_back(vert);
}
return data; // copy elision
}
unsigned OBJLoader::numTriangles() const {
return d_vertices.size() / 3U;
}
bool OBJLoader::hasTexCoords() const {
return d_hasTexCoords;
}
void OBJLoader::unitize() {
// This is a very handy function for importing models
// which you may reuse in other projects.
// You may have noticed you can use arbitrary sizes for your
// models. You may find that modelers do not always use the
// same size for models. Therefore it might be preferable to
// scale the object to fit inside a [-1, 1]^3 cube so you can easily
// set the right scale of your model. Aditionally,
// the model does not have to be centered around the origin
// (0, 0, 0) which may cause troubles when translating
// This function should fix that!
// A common approach looks like this:
// Determine min / max and offset in each dimension
// Determine by which factor to scale (largest difference
// in min / max in a dimension (Important! Scale uniformaly in
// all dimensions!)
// Loop over all coordinate data and scale the coordinates
// and apply the translate/scaling
cerr << "unitize() is not implemented!\n";
}
// --- Private -------------------------------------------------------
void OBJLoader::parseFile(string const &filename) {
ifstream file(filename);
if (file) {
string line;
while (getline(file, line))
parseLine(line);
} else {
cerr << "Could not open: " << filename << " for reading!\n";
}
}
void OBJLoader::parseLine(string const &line) {
if (line[0] == '#')
return; // ignore comments
StringList tokens = split(line, ' ', false);
if (tokens[0] == "v")
parseVertex(tokens);
else if (tokens[0] == "vn")
parseNormal(tokens);
else if (tokens[0] == "vt")
parseTexCoord(tokens);
else if (tokens[0] == "f")
parseFace(tokens);
// Other data is also ignored
}
void OBJLoader::parseVertex(StringList const &tokens) {
float x, y, z;
x = stof(tokens.at(1)); // 0 is the "v" token
y = stof(tokens.at(2));
z = stof(tokens.at(3));
d_coordinates.push_back(vec3{x, y, z});
}
void OBJLoader::parseNormal(StringList const &tokens) {
float x, y, z;
x = stof(tokens.at(1)); // 0 is the "vn" token
y = stof(tokens.at(2));
z = stof(tokens.at(3));
d_normals.push_back(vec3{x, y, z});
}
void OBJLoader::parseTexCoord(StringList const &tokens) {
d_hasTexCoords = true; // Texture data will be read
float u, v;
u = stof(tokens.at(1)); // 0 is the "vt" token
v = stof(tokens.at(2));
d_texCoords.push_back(vec2{u, v});
}
void OBJLoader::parseFace(StringList const &tokens) {
// skip the first token ("f")
for (size_t idx = 1; idx < tokens.size(); ++idx) {
// format is:
// <vertex idx + 1>/<texture idx +1>/<normal idx + 1>
// Wavefront .obj files start counting from 1 (yuck)
StringList elements = split(tokens.at(idx), '/');
Vertex_idx vertex{}; // initialize to zeros on all fields
vertex.d_coord = stoul(elements.at(0)) - 1U;
if (d_hasTexCoords)
vertex.d_tex = stoul(elements.at(1)) - 1U;
else
vertex.d_tex = 0U; // ignored
vertex.d_norm = stoul(elements.at(2)) - 1U;
d_vertices.push_back(vertex);
}
}
OBJLoader::StringList OBJLoader::split(string const &line,
char splitChar,
bool keepEmpty) {
StringList tokens;
istringstream iss(line);
string token;
while (getline(iss, token, splitChar))
if (token.size() > 0 || (token.size() == 0 && keepEmpty))
tokens.push_back(token);
return tokens;
}
| [
"cornul11@gmail.com"
] | cornul11@gmail.com |
343881634a69ce69397dfbc14fa9abdd647cd498 | f84f0c113acded328c44aa15b3dbc9856a4c0e1e | /Second Semester/Alexander_D_SolveForPI/Alexander_D_SolveForPI/Alexander_D_SolveForPI.cpp | 89b5b5116c3f9ac901a9f663047af0cc2d2e8f10 | [
"MIT"
] | permissive | FullscreenSauna/School-12th-grade | f16a7ee4319fa3aedf7bbf4ce1513f5adb4fb837 | bba0ed1daccd24130515716cc3be178e3401394b | refs/heads/main | 2023-06-16T04:29:17.735444 | 2021-07-09T09:06:40 | 2021-07-09T09:06:40 | 384,380,216 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 454 | cpp | #include <iostream>
using namespace std;
int main()
{
cout << "How many terms do you want to calculate?" << endl;
int n;
cin >> n;
int denominator = 3;
double sum = 1;
for (int i = 2; i <= n; i++)
{
if (i % 2 == 0)
{
sum -= 1.0 / denominator;
}
else
{
sum += 1.0 / denominator;
}
denominator += 2;
}
cout << "PI = " << sum * 4;
}
| [
"alexanderdz@abv.bg"
] | alexanderdz@abv.bg |
d2b90f776fda424b9f729728c3116965cc83ff9e | 38370ec6d3ba86570dd0efd1de8841f6ff5bad59 | /CrossApp/view/CACollectionView.h | 7fb59499d69606a81cefb37c7a33b14e02b4d2e1 | [] | no_license | RainbowMin/CrossApp | f3588907811cc5f3b9936439b95aade65eb29e5a | 45b5d4893fab0bb955089e1655694b189760608d | refs/heads/master | 2021-01-18T10:07:52.377093 | 2014-07-22T05:44:16 | 2014-07-22T05:44:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,128 | h | //
// CAAlertView.h
// CrossApp
//
// Created by Zhujian on 14-6-27.
// Copyright (c) 2014 http://www.9miao.com All rights reserved.
//
#ifndef __cocos2dx__CACollectionView__
#define __cocos2dx__CACollectionView__
#include "view/CAView.h"
#include "view/CAScale9ImageView.h"
#include "controller/CABarItem.h"
#include "view/CATableView.h"
#include "view/CALabel.h"
NS_CC_BEGIN
class CACollectionViewCell;
class CACollectionView;
class CACollectionViewDelegate
{
public:
virtual ~CACollectionViewDelegate(){};
virtual void collectionViewDidSelectCellAtIndexPath(CACollectionView *collectionView, unsigned int section, unsigned int row, unsigned int item) {};
virtual void collectionViewDidDeselectCellAtIndexPath(CACollectionView *collectionView, unsigned int section, unsigned int row, unsigned int item) {};
};
class CACollectionViewDataSource
{
public:
virtual ~CACollectionViewDataSource(){};
virtual CACollectionViewCell* collectionCellAtIndex(CACollectionView *collectionView, const CCSize& cellSize, unsigned int section, unsigned int row, unsigned int item) = 0;
virtual unsigned int numberOfSectionsInCollectioView() { return 1; }
virtual unsigned int numberOfRowsInSectionCollectionView(CACollectionView *collectionView, unsigned int section) = 0;
virtual unsigned int collectionViewHeightForHeaderInSection(CACollectionView *collectionView, unsigned int section) { return 0; }
virtual unsigned int collectionViewHeightForFooterInSection(CACollectionView *collectionView, unsigned int section) { return 0; }
virtual CAView* collectionViewSectionViewForHeaderInSection(CACollectionView *collectionView, const CCSize& viewSize, unsigned int section){ return NULL; }
virtual CAView* collectionViewSectionViewForFooterInSection(CACollectionView *collectionView, const CCSize& viewSize, unsigned int section){ return NULL; }
virtual unsigned int numberOfItemsInRowsInSection(CACollectionView *collectionView, unsigned int section, unsigned int row) = 0;
virtual unsigned int collectionViewHeightForRowAtIndexPath(CACollectionView* collectionView, unsigned int section, unsigned int row) { return 0; }
};
class CC_DLL CACollectionView : public CAScrollView
{
public:
CACollectionView();
virtual ~CACollectionView();
virtual void onEnterTransitionDidFinish();
virtual void onExitTransitionDidStart();
static CACollectionView* createWithFrame(const CCRect& rect);
static CACollectionView* createWithCenter(const CCRect& rect);
virtual bool init();
void reloadData();
virtual void setAllowsSelection(bool var);
virtual void setAllowsMultipleSelection(bool var);
void setSelectRowAtIndexPath(unsigned int section, unsigned int row, unsigned int item);
protected:
inline virtual float maxSpeed(float dt);
inline virtual float maxSpeedCache(float dt);
inline virtual float decelerationRatio(float dt);
inline virtual CCPoint maxBouncesLenght();
virtual void update(float dt);
protected:
virtual bool ccTouchBegan(CATouch *pTouch, CAEvent *pEvent);
virtual void ccTouchMoved(CATouch *pTouch, CAEvent *pEvent);
virtual void ccTouchEnded(CATouch *pTouch, CAEvent *pEvent);
virtual void ccTouchCancelled(CATouch *pTouch, CAEvent *pEvent);
protected:
CC_SYNTHESIZE(CACollectionViewDataSource*, m_pCollectionViewDataSource, CollectionViewDataSource);
CC_SYNTHESIZE(CACollectionViewDelegate*, m_pCollectionViewDelegate, CollectionViewDelegate);
CC_SYNTHESIZE_RETAIN(CAView*, m_pCollectionHeaderView, CollectionHeaderView);
CC_SYNTHESIZE_RETAIN(CAView*, m_pCollectionFooterView, CollectionFooterView);
CC_SYNTHESIZE(unsigned int, m_nCollectionHeaderHeight, CollectionHeaderHeight);
CC_SYNTHESIZE(unsigned int, m_nCollectionFooterHeight, CollectionFooterHeight);
CC_SYNTHESIZE_IS_READONLY(bool, m_bAllowsSelection, AllowsSelection);
CC_SYNTHESIZE_IS_READONLY(bool, m_bAllowsMultipleSelection, AllowsMultipleSelection);
private:
std::set<CACollectionViewCell*> m_pSelectedCollectionCells;
CACollectionViewCell* m_pHighlightedCollectionCells;
std::vector<CACollectionViewCell*> m_pCollectionCells;
};
class CC_DLL CACollectionViewCell : public CAControl
{
public:
CACollectionViewCell();
virtual ~CACollectionViewCell();
static CACollectionViewCell* create(const char* reuseIdentifier);
bool initWithReuseIdentifier(const char* reuseIdentifier);
using CAControl::setBackGroundViewForState;
protected:
virtual void normalTableViewCell(){};
virtual void highlightedTableViewCell(){};
virtual void selectedTableViewCell(){};
virtual void disabledTableViewCell(){};
void setControlState(CAControlState var);
using CAControl::setTouchEnabled;
protected:
CC_SYNTHESIZE(std::string, m_sReuseIdentifier, ReuseIdentifier);
CC_SYNTHESIZE_READONLY(unsigned int, m_nSection, Section);
CC_SYNTHESIZE_READONLY(unsigned int, m_nRow, Row);
CC_SYNTHESIZE_READONLY(unsigned int, m_nItem, Item);
friend class CACollectionView;
};
NS_CC_END
#endif /* defined(__cocos2dx__CACollectionView__) */ | [
"278688386@qq.com"
] | 278688386@qq.com |
4045d80c31ed93d31fa6d57bbaccf6d137bd9afc | 48717e6e780ed9e135c465284c5587fa537385a2 | /src/qt/coincontroldialog.h | 419fe32febd04a2f87a495d0fca655304cc4cb23 | [
"MIT"
] | permissive | champmine/privcy | 7f239621cb4aef2c1e204e3a6b69dd73ced116bf | bed16b116211351080db1759ae4fd332af2175e6 | refs/heads/master | 2023-06-22T21:24:09.715310 | 2021-07-08T17:30:45 | 2021-07-08T17:30:45 | 384,041,920 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,038 | h | // Copyright (c) 2011-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_COINCONTROLDIALOG_H
#define BITCOIN_QT_COINCONTROLDIALOG_H
#include <amount.h>
#include <QAbstractButton>
#include <QAction>
#include <QDialog>
#include <QList>
#include <QMenu>
#include <QPoint>
#include <QString>
#include <QTreeWidgetItem>
class WalletModel;
class CCoinControl;
namespace Ui {
class CoinControlDialog;
}
#define ASYMP_UTF8 "\xE2\x89\x88"
class CCoinControlWidgetItem : public QTreeWidgetItem
{
public:
explicit CCoinControlWidgetItem(QTreeWidget *parent, int type = Type) : QTreeWidgetItem(parent, type) {}
explicit CCoinControlWidgetItem(int type = Type) : QTreeWidgetItem(type) {}
explicit CCoinControlWidgetItem(QTreeWidgetItem *parent, int type = Type) : QTreeWidgetItem(parent, type) {}
bool operator<(const QTreeWidgetItem &other) const;
};
class CoinControlDialog : public QDialog
{
Q_OBJECT
public:
explicit CoinControlDialog(QWidget* parent = 0);
~CoinControlDialog();
void setModel(WalletModel *model);
// static because also called from sendcoinsdialog
static void updateLabels(WalletModel*, QDialog*);
static QList<CAmount> payAmounts;
static CCoinControl *coinControl();
static bool fSubtractFeeFromAmount;
static void usePRiVCYSend(bool fUsePRiVCYSend);
private:
Ui::CoinControlDialog *ui;
WalletModel *model;
int sortColumn;
Qt::SortOrder sortOrder;
QMenu *contextMenu;
QTreeWidgetItem *contextMenuItem;
QAction *copyTransactionHashAction;
QAction *lockAction;
QAction *unlockAction;
bool fHideAdditional{true};
void sortView(int, Qt::SortOrder);
void updateView();
enum
{
COLUMN_CHECKBOX = 0,
COLUMN_AMOUNT,
COLUMN_LABEL,
COLUMN_ADDRESS,
COLUMN_PRIVCYSEND_ROUNDS,
COLUMN_DATE,
COLUMN_CONFIRMATIONS,
};
enum
{
TxHashRole = Qt::UserRole,
VOutRole
};
friend class CCoinControlWidgetItem;
enum class Mode {
NORMAL,
PRIVCYSEND,
};
static CoinControlDialog::Mode mode;
private Q_SLOTS:
void showMenu(const QPoint &);
void copyAmount();
void copyLabel();
void copyAddress();
void copyTransactionHash();
void lockCoin();
void unlockCoin();
void clipboardQuantity();
void clipboardAmount();
void clipboardFee();
void clipboardAfterFee();
void clipboardBytes();
void clipboardLowOutput();
void clipboardChange();
void radioTreeMode(bool);
void radioListMode(bool);
void viewItemChanged(QTreeWidgetItem*, int);
void headerSectionClicked(int);
void buttonBoxClicked(QAbstractButton*);
void buttonSelectAllClicked();
void buttonToggleLockClicked();
void updateLabelLocked();
void on_hideButton_clicked();
};
#endif // BITCOIN_QT_COINCONTROLDIALOG_H
| [
"sarris88p@gmail.com"
] | sarris88p@gmail.com |
f576b790de5a2b5258db16d173b1fa57b264f79f | 4c23be1a0ca76f68e7146f7d098e26c2bbfb2650 | /3WeekTutorial/day2/forwardStep/0.5/Ma | 5b3a931566aa55e31c33f655c4f42865c46a7853 | [] | no_license | labsandy/OpenFOAM_workspace | a74b473903ddbd34b31dc93917e3719bc051e379 | 6e0193ad9dabd613acf40d6b3ec4c0536c90aed4 | refs/heads/master | 2022-02-25T02:36:04.164324 | 2019-08-23T02:27:16 | 2019-08-23T02:27:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 42,627 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 6
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0.5";
object Ma;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 0 0 0 0];
internalField nonuniform List<scalar>
5250
(
3
2.99999
2.99996
2.99991
2.99973
2.99944
2.99831
2.99664
2.98991
2.97967
2.94202
2.87336
2.67702
2.25423
1.39537
0.335387
0.118686
0.059019
0.160779
0.187354
0.179646
0.130256
0.0844351
0.0342137
0.070779
3
2.99999
2.99996
2.99991
2.99973
2.99945
2.99833
2.99669
2.99004
2.97992
2.94262
2.87454
2.67958
2.25833
1.40186
0.341906
0.121369
0.0783969
0.168366
0.195089
0.186853
0.139678
0.0997366
0.0628058
0.0813175
3
2.99999
2.99996
2.99992
2.99974
2.99947
2.99838
2.99679
2.99031
2.98046
2.94392
2.8772
2.68528
2.26859
1.41825
0.360797
0.127207
0.110414
0.181365
0.207381
0.200525
0.158933
0.127692
0.103008
0.111227
3
2.99999
2.99997
2.99992
2.99975
2.99949
2.99847
2.99695
2.99075
2.98134
2.94605
2.88169
2.69494
2.28659
1.44819
0.39508
0.142061
0.145758
0.19567
0.22348
0.221341
0.187646
0.165163
0.14917
0.153385
3
2.99999
2.99997
2.99993
2.99977
2.99953
2.99858
2.99716
2.99138
2.98259
2.94913
2.88822
2.709
2.31373
1.49388
0.446542
0.171666
0.1809
0.208542
0.243393
0.24874
0.223893
0.208942
0.198937
0.202331
3
3
2.99997
2.99993
2.99979
2.99957
2.99871
2.99743
2.99219
2.98418
2.95334
2.8969
2.72855
2.35174
1.56032
0.520415
0.219043
0.213482
0.219129
0.269012
0.283713
0.267093
0.258614
0.253136
0.257369
3
3
2.99997
2.99994
2.99981
2.99962
2.99886
2.99772
2.99313
2.98601
2.95881
2.90773
2.75576
2.40268
1.66048
0.621714
0.285311
0.237272
0.232068
0.304438
0.32798
0.318519
0.315379
0.315502
0.322227
3
3
2.99998
2.99995
2.99983
2.99966
2.99899
2.998
2.99406
2.98789
2.96493
2.9204
2.78887
2.47201
1.80703
0.762564
0.366576
0.254539
0.2584
0.352188
0.381951
0.378263
0.382694
0.389224
0.403335
3
3
2.99998
2.99995
2.99985
2.99969
2.99911
2.99824
2.99486
2.98965
2.97067
2.93355
2.82443
2.5547
1.9824
0.969001
0.454573
0.274264
0.300813
0.410723
0.444445
0.447854
0.461188
0.482543
0.51964
3
3
2.99998
2.99996
2.99987
2.99973
2.9992
2.99844
2.99544
2.99104
2.97462
2.94535
2.85579
2.63957
2.17457
1.25704
0.527559
0.290881
0.355182
0.475859
0.51199
0.52471
0.555671
0.604901
0.707507
3
3
2.99999
2.99996
2.99988
2.99976
2.99928
2.9986
2.9959
2.99205
2.97706
2.95298
2.87448
2.70127
2.31348
1.52218
0.595977
0.315025
0.423799
0.540415
0.579811
0.606307
0.660146
0.755512
0.912662
3.00001
3
2.99999
2.99997
2.9999
2.99979
2.99937
2.99878
2.99638
2.99305
2.97965
2.95913
2.88982
2.74284
2.40375
1.66963
0.722025
0.379661
0.501429
0.592689
0.639713
0.684136
0.756007
0.873973
1.03521
3.00001
3
2.99999
2.99998
2.99992
2.99983
2.99948
2.99899
2.99698
2.99418
2.98271
2.96584
2.9041
2.78172
2.47993
1.80548
0.900748
0.485398
0.564512
0.62809
0.687568
0.747214
0.82706
0.939234
1.07767
3.00001
3
3
2.99998
2.99994
2.99987
2.9996
2.99921
2.99762
2.99538
2.98653
2.97211
2.92389
2.81513
2.56644
1.94678
1.09264
0.61746
0.60526
0.660639
0.723902
0.791759
0.873888
0.974143
1.08921
3.00001
3
3
2.99999
2.99995
2.9999
2.9997
2.9994
2.9982
2.99646
2.98977
2.97837
2.94123
2.85458
2.65538
2.12156
1.3433
0.77857
0.65587
0.698128
0.756976
0.826354
0.906665
0.994972
1.09471
3.00001
3.00001
3
2.99999
2.99997
2.99993
2.99977
2.99954
2.99858
2.99728
2.99155
2.98372
2.9519
2.89855
2.73672
2.38956
1.67516
0.960426
0.726576
0.754543
0.803024
0.867779
0.940345
1.0191
1.10198
3.00001
3.00001
3
3
2.99998
2.99995
2.99984
2.99968
2.999
2.99807
2.994
2.98842
2.96551
2.92719
2.80833
2.54454
1.97789
1.14245
0.819704
0.821389
0.861048
0.913432
0.975463
1.0406
1.11205
3.00001
3.00001
3
3
2.99999
2.99997
2.9999
2.9998
2.99935
2.99876
2.99603
2.99239
2.97678
2.95075
2.87005
2.67967
2.27974
1.45607
1.0078
0.903899
0.920751
0.956104
1.01062
1.06746
1.12814
3.00001
3.00001
3.00001
3
3
2.99999
2.99995
2.99989
2.99965
2.9993
2.99788
2.99575
2.987
2.97266
2.91755
2.81183
2.53067
1.94499
1.24576
1.00808
0.989052
1.0101
1.04779
1.09785
1.14935
3.00001
3.00001
3.00001
3.00001
3
3
2.99997
2.99993
2.99978
2.99957
2.99861
2.99739
2.99191
2.98345
2.95414
2.88368
2.7176
2.2714
1.6004
1.1417
1.05506
1.06155
1.08679
1.12946
1.17469
3.00001
3.00001
3.00001
3.00001
3
3
2.99999
2.99997
2.99988
2.99976
2.9992
2.9985
2.99506
2.99064
2.97016
2.93807
2.82543
2.59953
2.05209
1.40421
1.1672
1.12881
1.13713
1.16445
1.2063
3.00001
3.00001
3.00001
3.00001
3.00001
3
3
2.99999
2.99995
2.9999
2.99971
2.99933
2.9981
2.99563
2.98547
2.97093
2.90574
2.79531
2.45879
1.8817
1.3452
1.21454
1.19926
1.21189
1.23798
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3
3
2.99998
2.99995
2.9998
2.99964
2.99875
2.99774
2.99282
2.98519
2.95964
2.89099
2.73872
2.30797
1.7153
1.33252
1.26127
1.26232
1.28105
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3
3
2.99998
2.99993
2.99985
2.99945
2.99901
2.99628
2.99334
2.97677
2.9537
2.8578
2.68766
2.19596
1.64914
1.37908
1.32981
1.33009
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3
3
2.99997
2.99994
2.99978
2.99961
2.99885
2.99754
2.9942
2.9818
2.95061
2.8622
2.64179
2.17714
1.63973
1.42993
1.3986
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3
3
2.99998
2.99995
2.99984
2.99971
2.99922
2.99801
2.99623
2.98274
2.95187
2.86241
2.62833
2.18087
1.68056
1.48371
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3
3
2.99999
2.99996
2.99988
2.99969
2.99908
2.99658
2.99357
2.97532
2.95065
2.84648
2.66881
2.18054
1.76923
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3
3
2.99999
2.99996
2.99985
2.99973
2.99892
2.99812
2.99475
2.98415
2.96034
2.88618
2.68487
2.30272
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3
2.99999
2.99996
2.99992
2.99975
2.99944
2.99846
2.9953
2.98352
2.96616
2.88523
2.75942
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3
2.99999
2.99995
2.99986
2.99948
2.99915
2.9955
2.99603
2.9729
2.91351
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3
3
2.99996
2.9999
2.99971
2.99872
2.99815
2.99345
2.98072
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3
3
2.99996
2.99993
2.99971
2.99951
2.99827
2.99533
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3
3
2.99999
2.99993
2.99987
2.9995
2.99904
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3
3
2.99999
2.99997
2.99988
2.99981
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3
3
2.99998
2.99996
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3
3
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
1.134
1.36056
1.5148
1.60863
1.64183
1.6223
1.56268
1.51041
1.43035
1.35598
1.29539
1.27101
1.26889
1.27849
1.28624
1.29787
1.31148
1.32148
1.32929
1.33711
1.34558
1.35474
1.36448
1.37497
1.38655
1.39962
1.41434
1.43052
1.44756
1.46471
1.48136
1.49722
1.51233
1.52704
1.54185
1.55723
1.57331
1.58971
1.60573
1.62051
1.63297
1.64257
1.65039
1.65563
1.6561
1.65204
1.64658
1.6415
1.63879
1.63921
1.64168
1.64753
1.66358
1.69191
1.72911
1.7758
1.83182
1.89652
1.96861
2.04642
2.12774
2.21028
2.29169
2.37005
2.44358
2.51121
2.57215
2.62636
2.67392
2.71538
2.75115
2.78188
2.80826
2.83105
2.85113
2.86929
2.88632
2.90277
2.91888
2.93456
2.94929
2.96237
2.97321
2.9818
2.98862
2.99436
2.99927
3.00362
3.00771
3.0089
3.00823
3.00676
3.00525
3.00377
3.00243
3.00151
3.00092
3.00054
3.00031
3.00018
1.19382
1.33919
1.44092
1.50006
1.52546
1.52881
1.53057
1.54689
1.58233
1.6265
1.65489
1.66333
1.66614
1.6617
1.65203
1.64377
1.63833
1.64003
1.64361
1.65026
1.65992
1.6702
1.68069
1.69097
1.7008
1.7104
1.72029
1.73102
1.74284
1.75563
1.76895
1.78216
1.79471
1.80632
1.81719
1.8279
1.83912
1.85121
1.86421
1.87762
1.89043
1.9012
1.90907
1.91483
1.91876
1.91895
1.91367
1.90463
1.89518
1.88821
1.88502
1.88503
1.88697
1.89407
1.91186
1.94295
1.98293
2.03115
2.08663
2.14802
2.21379
2.28223
2.3516
2.42018
2.48652
2.54944
2.608
2.66163
2.70997
2.75295
2.79066
2.8232
2.85087
2.87405
2.89347
2.90993
2.92444
2.93778
2.95046
2.96252
2.97351
2.98291
2.99027
2.99568
2.99976
3.00289
3.00538
3.00942
3.01193
3.01178
3.0102
3.00822
3.0063
3.00434
3.00282
3.00178
3.00109
3.00065
3.00038
3.00022
1.1924
1.29577
1.38346
1.45873
1.52686
1.59536
1.66414
1.72729
1.78317
1.83132
1.86757
1.88348
1.88532
1.88387
1.87519
1.86091
1.84883
1.84262
1.84027
1.84266
1.8468
1.8529
1.86099
1.86934
1.87776
1.88628
1.89493
1.90393
1.91354
1.92376
1.93439
1.94507
1.9553
1.96462
1.97293
1.9806
1.98832
1.99677
2.00637
2.01701
2.02812
2.03837
2.04619
2.05131
2.05493
2.05625
2.05368
2.04573
2.03644
2.02887
2.02469
2.02381
2.02486
2.03047
2.04559
2.07298
2.10868
2.15189
2.20174
2.25712
2.3167
2.37893
2.44222
2.50497
2.56582
2.62357
2.67733
2.72636
2.77024
2.80864
2.84155
2.86919
2.89193
2.91034
2.92512
2.9372
2.9475
2.95694
2.9661
2.97506
2.98342
2.99054
2.99596
2.99983
3.00264
3.00473
3.00677
3.01058
3.0126
3.01211
3.01036
3.00829
3.00629
3.00427
3.00277
3.00174
3.00107
3.00063
3.00037
3.00022
1.19496
1.28532
1.36835
1.44764
1.52356
1.59681
1.66745
1.73181
1.79089
1.8384
1.87724
1.90804
1.93117
1.94779
1.95731
1.96086
1.96207
1.96037
1.95805
1.95574
1.9531
1.95487
1.95732
1.96126
1.96727
1.97569
1.98596
1.99739
2.00918
2.02064
2.03145
2.04136
2.0501
2.05753
2.06388
2.06974
2.07576
2.08273
2.0913
2.10119
2.1117
2.12157
2.12918
2.13407
2.13746
2.13893
2.13766
2.1342
2.13122
2.13025
2.13106
2.13379
2.14319
2.16246
2.1878
2.21918
2.25619
2.29825
2.3445
2.39402
2.44576
2.49859
2.55134
2.60285
2.65217
2.69849
2.74135
2.78045
2.8157
2.8469
2.87402
2.89704
2.91618
2.93174
2.94435
2.95464
2.96342
2.9714
2.97909
2.98664
2.99367
2.99954
3.00374
3.00642
3.008
3.00903
3.01107
3.01405
3.01486
3.01361
3.01138
3.00905
3.00668
3.00449
3.00292
3.00185
3.00114
3.00068
3.0004
3.00024
1.19436
1.28489
1.36621
1.4422
1.51517
1.58324
1.64739
1.70799
1.76471
1.81736
1.8657
1.91013
1.94964
1.9828
2.00989
2.02832
2.04107
2.04538
2.04543
2.04463
2.04288
2.03965
2.03858
2.04055
2.04376
2.0483
2.05534
2.0659
2.07729
2.08813
2.09802
2.1068
2.11445
2.12102
2.12676
2.1322
2.13789
2.14435
2.15221
2.1614
2.17129
2.18081
2.18866
2.19425
2.19819
2.20141
2.204
2.20584
2.20764
2.21019
2.21616
2.22967
2.24927
2.27309
2.30116
2.33331
2.36914
2.40809
2.44948
2.49265
2.53696
2.58172
2.62619
2.66968
2.71144
2.75087
2.78753
2.82121
2.85174
2.87901
2.90282
2.92294
2.93935
2.95229
2.96237
2.97037
2.97719
2.98343
2.98945
2.99526
3.00055
3.00481
3.0077
3.00928
3.0099
3.01084
3.01264
3.01511
3.01538
3.0138
3.01141
3.009
3.00652
3.00436
3.00283
3.00178
3.00109
3.00065
3.00038
3.00022
1.18955
1.27417
1.35298
1.42632
1.49515
1.55991
1.62175
1.68094
1.73756
1.79138
1.84212
1.88961
1.9335
1.97304
2.00797
2.037
2.06016
2.07718
2.08861
2.09546
2.09862
2.10004
2.10136
2.10324
2.10571
2.10958
2.1152
2.12187
2.12964
2.13776
2.1461
2.15407
2.16151
2.16842
2.17495
2.18149
2.18855
2.1965
2.20521
2.21454
2.22449
2.23443
2.24307
2.24958
2.2547
2.25964
2.26476
2.27027
2.27788
2.2893
2.30524
2.32517
2.34813
2.37399
2.40265
2.43389
2.46747
2.50304
2.54022
2.57852
2.61742
2.65638
2.69474
2.73196
2.76742
2.80063
2.83121
2.85913
2.88433
2.90687
2.92662
2.94338
2.9571
2.96781
2.97599
2.98235
2.98781
2.99302
2.99814
3.00327
3.00778
3.0111
3.01285
3.01325
3.0136
3.01409
3.01529
3.01713
3.01671
3.01464
3.01197
3.00934
3.00661
3.00442
3.00287
3.00181
3.00111
3.00066
3.00039
3.00023
1.18839
1.26504
1.33868
1.40847
1.47471
1.53791
1.59845
1.65631
1.71255
1.76692
1.81884
1.86766
1.91248
1.95391
1.99138
2.0251
2.05455
2.07973
2.10075
2.118
2.13163
2.1429
2.15162
2.15848
2.16438
2.17024
2.17623
2.18154
2.18625
2.19069
2.19518
2.20013
2.20576
2.21158
2.21781
2.22491
2.23329
2.24277
2.25293
2.26337
2.27383
2.28406
2.29344
2.3013
2.30844
2.31672
2.32625
2.3365
2.34852
2.36379
2.38303
2.40559
2.43044
2.4573
2.48592
2.51621
2.54796
2.58095
2.6149
2.64945
2.68407
2.71821
2.75133
2.78298
2.81289
2.8408
2.86642
2.8897
2.91072
2.92962
2.94631
2.96059
2.97229
2.98137
2.98811
2.99319
2.99754
3.00171
3.00572
3.00979
3.01339
3.01566
3.01624
3.01629
3.01591
3.01576
3.01628
3.01794
3.01713
3.01476
3.01194
3.00919
3.00637
3.00425
3.00275
3.00173
3.00106
3.00063
3.00037
3.00022
1.19309
1.26047
1.32797
1.39401
1.45815
1.52006
1.57978
1.63708
1.692
1.74423
1.79376
1.84079
1.8852
1.92661
1.96453
1.99904
2.03028
2.05913
2.08591
2.11107
2.1342
2.15531
2.17355
2.18948
2.20269
2.213
2.2211
2.22732
2.23152
2.23489
2.23779
2.24036
2.24418
2.24875
2.2543
2.26134
2.27049
2.28116
2.2925
2.30399
2.31556
2.32715
2.33891
2.35028
2.36111
2.37303
2.38682
2.40169
2.41777
2.43594
2.45718
2.48117
2.50673
2.5334
2.56099
2.58956
2.61913
2.64954
2.68054
2.71174
2.7427
2.77281
2.80154
2.82846
2.85352
2.87674
2.89808
2.91737
2.93467
2.95004
2.96365
2.97532
2.98492
2.9924
2.99789
3.00195
3.00548
3.00884
3.01213
3.01566
3.01852
3.01951
3.01964
3.01924
3.01844
3.01804
3.0187
3.01947
3.01789
3.01509
3.01212
3.00912
3.00627
3.00418
3.00271
3.00171
3.00105
3.00062
3.00037
3.00022
1.2055
1.26269
1.32199
1.38224
1.44226
1.50137
1.55906
1.61462
1.66785
1.71881
1.76728
1.81311
1.85568
1.89508
1.93176
1.96645
1.99981
2.03196
2.06321
2.09364
2.12289
2.1506
2.17637
2.19953
2.21972
2.23622
2.24956
2.25958
2.26699
2.27252
2.27721
2.28178
2.28621
2.29134
2.29744
2.30442
2.3128
2.32296
2.33407
2.34576
2.35818
2.37131
2.38551
2.40024
2.41522
2.43092
2.44777
2.4658
2.48465
2.50486
2.52715
2.5517
2.57727
2.60299
2.6291
2.6559
2.68338
2.71131
2.73944
2.76735
2.79458
2.82062
2.84512
2.86776
2.88835
2.90748
2.92527
2.94121
2.95526
2.96773
2.97855
2.98782
2.99545
3.00157
3.00622
3.00968
3.01259
3.01534
3.01802
3.02078
3.02234
3.02262
3.02254
3.02151
3.02027
3.01957
3.02043
3.02028
3.01809
3.01502
3.01194
3.00877
3.00599
3.00398
3.00257
3.00162
3.00099
3.00059
3.00035
3.0002
1.22163
1.27103
1.32199
1.3757
1.43128
1.48703
1.54197
1.59529
1.64646
1.6951
1.74097
1.78427
1.82523
1.86432
1.90177
1.9379
1.97322
2.00782
2.04184
2.07477
2.10668
2.1371
2.16578
2.19217
2.21625
2.23744
2.25611
2.27189
2.28562
2.29724
2.30699
2.31608
2.3238
2.33155
2.33943
2.34752
2.35571
2.36497
2.37542
2.38746
2.40032
2.41462
2.43085
2.44854
2.4669
2.4856
2.50502
2.52539
2.54644
2.56844
2.59181
2.61644
2.64163
2.66638
2.69126
2.71629
2.74164
2.76711
2.79232
2.81686
2.84026
2.8624
2.88295
2.90247
2.92009
2.93578
2.94973
2.9621
2.9735
2.98413
2.99274
2.99976
3.00537
3.00991
3.01359
3.01663
3.01921
3.02157
3.02371
3.02516
3.02547
3.02595
3.02517
3.02363
3.02211
3.02131
3.02216
3.02109
3.01835
3.01504
3.0118
3.00847
3.00577
3.00383
3.00247
3.00155
3.00095
3.00056
3.00033
3.0002
1.24665
1.28761
1.33242
1.37917
1.42832
1.47901
1.52976
1.5797
1.62816
1.67479
1.71926
1.76159
1.802
1.84086
1.87863
1.91563
1.95209
1.98786
2.02311
2.05724
2.09022
2.12123
2.15057
2.17791
2.20349
2.22759
2.24986
2.27116
2.29054
2.30915
2.32563
2.34108
2.35523
2.36752
2.37895
2.38936
2.39962
2.41016
2.42129
2.43407
2.44831
2.46359
2.48037
2.49981
2.52035
2.54136
2.56209
2.58331
2.60539
2.62841
2.65214
2.67608
2.69978
2.72306
2.74642
2.7698
2.79309
2.81586
2.83779
2.85893
2.87877
2.897
2.91483
2.9313
2.94608
2.95904
2.97037
2.98036
2.98912
2.99681
3.00395
3.00992
3.01398
3.01714
3.01998
3.02268
3.02518
3.02732
3.0288
3.02895
3.02917
3.02893
3.02742
3.02539
3.0235
3.02265
3.02319
3.02146
3.01829
3.01481
3.0114
3.00801
3.00545
3.0036
3.00232
3.00145
3.00089
3.00053
3.00031
3.00018
1.27496
1.31387
1.35266
1.39372
1.4368
1.48083
1.52646
1.57215
1.61707
1.6609
1.70359
1.74506
1.78536
1.82483
1.86354
1.90123
1.93808
1.97408
2.00908
2.04269
2.07469
2.10508
2.1339
2.1615
2.18789
2.2137
2.23849
2.26315
2.28686
2.31023
2.3331
2.35416
2.37466
2.39266
2.40903
2.42396
2.43738
2.45083
2.46457
2.47901
2.4959
2.51406
2.53255
2.55274
2.5749
2.59738
2.61913
2.64087
2.6633
2.68627
2.70856
2.73075
2.7526
2.77475
2.79643
2.818
2.83912
2.8592
2.87822
2.89547
2.91105
2.92697
2.94203
2.95529
2.96696
2.97718
2.98617
2.99409
3.00103
3.00699
3.01224
3.01711
3.02072
3.02289
3.02503
3.02749
3.03008
3.03209
3.03272
3.03298
3.03304
3.03159
3.02929
3.02676
3.02465
3.02409
3.02408
3.02163
3.01806
3.01446
3.01085
3.00756
3.00513
3.00338
3.00218
3.00136
3.00083
3.00049
3.00029
3.00017
1.31012
1.346
1.38219
1.41819
1.4554
1.49512
1.5346
1.57503
1.61596
1.65665
1.69691
1.73686
1.77673
1.81627
1.8552
1.89324
1.93011
1.96542
1.9991
2.03105
2.06148
2.09065
2.11884
2.1464
2.17351
2.2003
2.22714
2.25383
2.28056
2.30694
2.33304
2.35862
2.38262
2.40586
2.42697
2.44657
2.46568
2.48348
2.50224
2.52118
2.54078
2.56219
2.58389
2.60577
2.62904
2.65308
2.67637
2.69912
2.72145
2.74364
2.76521
2.78582
2.80617
2.82613
2.84565
2.86483
2.88375
2.9012
2.91601
2.92867
2.94166
2.95455
2.96614
2.9766
2.98566
2.99323
2.99979
3.00563
3.01075
3.01506
3.01866
3.02221
3.02539
3.02708
3.0287
3.03094
3.03352
3.0353
3.0363
3.03707
3.03594
3.03348
3.03054
3.02765
3.02566
3.02584
3.02462
3.02141
3.01756
3.01388
3.01016
3.00704
3.00476
3.00313
3.00201
3.00125
3.00076
3.00045
3.00026
3.00016
1.34875
1.37617
1.40979
1.44507
1.48054
1.51585
1.55201
1.5883
1.62409
1.66064
1.6982
1.73652
1.77525
1.81383
1.85192
1.88908
1.92482
1.95861
1.9905
2.02095
2.05036
2.07887
2.10689
2.13462
2.16227
2.18996
2.21766
2.24556
2.27356
2.30186
2.32998
2.35784
2.38509
2.41093
2.43644
2.46027
2.48406
2.50745
2.53086
2.55497
2.57913
2.60388
2.62924
2.65398
2.6785
2.70344
2.7277
2.75126
2.77453
2.79707
2.81909
2.83965
2.85909
2.87803
2.89574
2.91332
2.93099
2.94599
2.95649
2.96626
2.97617
2.98527
2.99349
3.0004
3.00614
3.0105
3.01427
3.01736
3.02028
3.02319
3.02552
3.02723
3.02931
3.03074
3.03181
3.03343
3.03558
3.03755
3.03983
3.04005
3.03796
3.03478
3.03128
3.02835
3.02732
3.02723
3.0247
3.02091
3.01693
3.01316
3.00942
3.00651
3.00439
3.00288
3.00184
3.00114
3.00069
3.00041
3.00024
3.00014
1.39725
1.41314
1.43707
1.46824
1.50074
1.53431
1.56871
1.60352
1.63885
1.67373
1.70801
1.74294
1.77851
1.81447
1.85048
1.88588
1.9201
1.95287
1.98406
2.01384
2.04276
2.07117
2.09928
2.12725
2.15521
2.1833
2.21158
2.24025
2.26929
2.29876
2.32829
2.35785
2.38673
2.41527
2.44256
2.47025
2.49683
2.52424
2.55182
2.57937
2.60798
2.6359
2.66423
2.6927
2.71942
2.74632
2.77269
2.79673
2.81979
2.84358
2.86514
2.88587
2.90575
2.92444
2.94203
2.95899
2.97661
2.99062
2.99856
3.00627
3.01332
3.01949
3.02464
3.02843
3.03075
3.0319
3.03238
3.03259
3.03274
3.033
3.03338
3.03402
3.03446
3.03505
3.03559
3.03636
3.03751
3.04002
3.04265
3.04225
3.03947
3.03574
3.03193
3.0292
3.02902
3.02766
3.02433
3.02019
3.01616
3.01225
3.00866
3.00596
3.00399
3.00261
3.00166
3.00103
3.00062
3.00037
3.00022
3.00013
1.45514
1.45907
1.4749
1.49855
1.52793
1.55873
1.5909
1.62343
1.65588
1.68839
1.72124
1.75387
1.78647
1.81929
1.85222
1.88513
1.91776
1.94953
1.98027
2.01005
2.03917
2.06813
2.09712
2.12626
2.15541
2.18465
2.21392
2.24333
2.27293
2.30264
2.33237
2.36172
2.39098
2.41976
2.44874
2.4773
2.50676
2.53593
2.56601
2.59658
2.62697
2.65828
2.68871
2.71905
2.74921
2.77717
2.80486
2.83217
2.85602
2.87959
2.90314
2.92423
2.94417
2.96369
2.98017
2.99552
3.01257
3.02663
3.03368
3.03999
3.04552
3.05009
3.05354
3.05537
3.0554
3.05409
3.05204
3.04972
3.04739
3.04526
3.04345
3.04201
3.04119
3.04075
3.04041
3.0402
3.04072
3.04307
3.04506
3.04411
3.04084
3.03667
3.03261
3.03019
3.02992
3.02755
3.02364
3.01927
3.01519
3.01122
3.00787
3.00539
3.0036
3.00234
3.00148
3.00092
3.00056
3.00033
3.00019
3.00011
1.55629
1.52371
1.52095
1.5348
1.55488
1.58117
1.61055
1.64276
1.67528
1.70674
1.73728
1.76753
1.79786
1.82841
1.85911
1.8897
1.9201
1.95062
1.9809
2.01083
2.04061
2.07059
2.10073
2.13094
2.16104
2.19095
2.22058
2.25005
2.27932
2.30855
2.33765
2.36674
2.39584
2.42503
2.45453
2.48432
2.51463
2.54542
2.5768
2.60829
2.64081
2.67245
2.70508
2.73646
2.76736
2.7979
2.82586
2.85386
2.88081
2.90446
2.92823
2.95171
2.97091
2.99016
3.00845
3.02355
3.03906
3.05469
3.062
3.06655
3.07065
3.07386
3.07609
3.07661
3.07517
3.07233
3.06887
3.06528
3.06146
3.05738
3.05386
3.05102
3.04888
3.04737
3.04625
3.04526
3.04508
3.04665
3.04752
3.04577
3.04204
3.03755
3.03327
3.03102
3.03016
3.02699
3.0226
3.01811
3.01402
3.01011
3.00705
3.0048
3.00319
3.00207
3.00131
3.00081
3.00049
3.00029
3.00017
3.0001
1.85032
1.61812
1.58251
1.57782
1.59008
1.6083
1.63284
1.66089
1.69263
1.72483
1.75521
1.78393
1.81222
1.84073
1.86953
1.89872
1.9282
1.95802
1.9882
2.01858
2.04898
2.07902
2.10868
2.13815
2.16763
2.19718
2.22683
2.25647
2.28596
2.31528
2.34435
2.37339
2.40239
2.43173
2.46135
2.4916
2.52232
2.55369
2.58551
2.61786
2.6502
2.68308
2.7151
2.7473
2.77843
2.80867
2.83841
2.86602
2.89347
2.91977
2.94249
2.96601
2.98793
3.00542
3.02307
3.03892
3.05255
3.06846
3.0797
3.08311
3.08668
3.08955
3.09156
3.09178
3.08975
3.0863
3.08247
3.07809
3.07283
3.06775
3.06322
3.0594
3.05631
3.05393
3.05205
3.0504
3.04974
3.05051
3.04993
3.04713
3.04274
3.03796
3.03366
3.03168
3.02992
3.02592
3.02115
3.01669
3.01259
3.00896
3.00622
3.00422
3.00279
3.0018
3.00114
3.0007
3.00042
3.00025
3.00014
3.00009
2.35626
1.99219
1.70411
1.64211
1.63193
1.64443
1.66086
1.68283
1.70971
1.74023
1.77178
1.80119
1.82802
1.85424
1.88162
1.91041
1.94051
1.97098
2.00151
2.03163
2.06102
2.08985
2.11867
2.14755
2.17664
2.20592
2.23536
2.26482
2.29422
2.32342
2.35246
2.38137
2.41033
2.43953
2.4691
2.49927
2.52996
2.56136
2.59316
2.62546
2.65784
2.69015
2.72219
2.75354
2.78425
2.81444
2.84343
2.87219
2.89886
2.92524
2.94985
2.97118
2.99335
3.013
3.02816
3.04441
3.05814
3.07018
3.08389
3.09041
3.09265
3.09542
3.09752
3.09791
3.09598
3.09273
3.08907
3.08446
3.07904
3.07386
3.06916
3.06506
3.06168
3.05897
3.05657
3.05468
3.05403
3.05346
3.05145
3.04759
3.04266
3.03774
3.03365
3.0322
3.02903
3.02422
3.0193
3.01498
3.01104
3.00781
3.0054
3.00364
3.0024
3.00154
3.00097
3.0006
3.00036
3.00021
3.00012
3.00008
2.8098
2.48325
2.11681
1.78678
1.69707
1.68377
1.69848
1.71315
1.73153
1.75589
1.78513
1.81583
1.84656
1.87518
1.90198
1.92846
1.95557
1.98363
2.01243
2.04166
2.0711
2.10047
2.12967
2.15873
2.18779
2.21688
2.24604
2.2751
2.30405
2.33282
2.36148
2.39009
2.41881
2.44777
2.47715
2.50704
2.53752
2.56856
2.60004
2.63183
2.66364
2.69525
2.72645
2.75706
2.78719
2.81654
2.8454
2.87306
2.89989
2.92488
2.94897
2.97105
2.99063
3.01066
3.02757
3.04074
3.05536
3.06707
3.07713
3.08724
3.09046
3.09261
3.09506
3.09595
3.09459
3.09187
3.0887
3.08453
3.07967
3.07502
3.07077
3.06707
3.06393
3.06119
3.05873
3.0573
3.05638
3.05453
3.05128
3.04662
3.0414
3.03685
3.0342
3.03192
3.02714
3.02187
3.01711
3.01307
3.00949
3.00668
3.00459
3.00308
3.00202
3.0013
3.00081
3.0005
3.0003
3.00018
3.0001
3.00007
2.93862
2.86342
2.60196
2.25193
1.88614
1.75246
1.73778
1.75064
1.76602
1.78384
1.80499
1.83221
1.86148
1.89109
1.91947
1.9463
1.97237
1.99863
2.0257
2.05368
2.08238
2.11152
2.14077
2.16999
2.19909
2.22798
2.2567
2.28526
2.31376
2.34217
2.37058
2.39898
2.42753
2.4563
2.48545
2.51502
2.54506
2.57551
2.6063
2.63722
2.66809
2.69871
2.72894
2.75876
2.78807
2.81681
2.84474
2.87153
2.89703
2.92103
2.94363
2.96495
2.98457
3.00213
3.01967
3.03358
3.04509
3.05799
3.06719
3.07495
3.08185
3.08367
3.08601
3.08778
3.08714
3.08504
3.08249
3.07909
3.07523
3.07152
3.06813
3.06519
3.06252
3.06014
3.05866
3.05744
3.0557
3.05288
3.04872
3.04378
3.03932
3.03698
3.03471
3.02979
3.02431
3.01915
3.01477
3.01113
3.00799
3.00559
3.00382
3.00255
3.00167
3.00106
3.00067
3.00041
3.00025
3.00015
3.00009
3.00005
2.9832
2.96171
2.88546
2.73116
2.36976
2.03239
1.83245
1.81199
1.80718
1.82149
1.83618
1.85618
1.88067
1.90706
1.93373
1.96
1.98602
2.01237
2.03952
2.06748
2.09603
2.12479
2.15354
2.18206
2.21038
2.23848
2.26647
2.29445
2.32249
2.35059
2.37878
2.40709
2.43556
2.46425
2.49321
2.52245
2.55198
2.58173
2.61163
2.64152
2.67128
2.70081
2.73008
2.75907
2.78755
2.81525
2.84184
2.86729
2.89147
2.91435
2.93593
2.95601
2.97483
2.99187
3.00725
3.02182
3.03313
3.04324
3.05384
3.06043
3.06613
3.071
3.0725
3.07466
3.07511
3.07367
3.07181
3.06937
3.06663
3.06406
3.06175
3.05954
3.05776
3.05674
3.05562
3.05417
3.05192
3.04834
3.04419
3.04066
3.04038
3.03682
3.03179
3.02637
3.02109
3.01633
3.0124
3.00921
3.00655
3.00455
3.00309
3.00206
3.00134
3.00085
3.00053
3.00033
3.0002
3.00012
3.00007
3.00005
2.99546
2.9922
2.97351
2.92826
2.8135
2.5618
2.19789
1.94654
1.88117
1.86586
1.8767
1.8881
1.90386
1.92509
1.94908
1.97469
2.00076
2.02717
2.05416
2.08181
2.1099
2.13809
2.16617
2.19404
2.22171
2.24923
2.2767
2.30417
2.33179
2.35956
2.38751
2.41566
2.44398
2.47243
2.50099
2.52962
2.55829
2.58702
2.61576
2.64447
2.67309
2.70169
2.7301
2.75801
2.78512
2.81139
2.83669
2.86091
2.8839
2.90563
2.92601
2.94512
2.96281
2.97901
2.99377
3.00682
3.01867
3.02813
3.03664
3.04464
3.04902
3.05354
3.05733
3.05848
3.05978
3.05927
3.05806
3.05662
3.05511
3.05364
3.05239
3.05165
3.05115
3.05058
3.04953
3.0476
3.04496
3.04259
3.0431
3.04133
3.03756
3.03277
3.0276
3.02247
3.01769
3.01347
3.01003
3.00735
3.0052
3.00358
3.00242
3.0016
3.00104
3.00066
3.00041
3.00025
3.00015
3.00009
3.00006
3.00004
2.99906
2.99843
2.99441
2.98441
2.94977
2.89191
2.69421
2.43562
2.11312
1.94639
1.93129
1.92519
1.94021
1.95439
1.97281
1.99246
2.01647
2.04205
2.06822
2.09488
2.1221
2.14963
2.17723
2.20473
2.23214
2.25946
2.28673
2.31401
2.34139
2.36898
2.39669
2.42447
2.45234
2.48025
2.50813
2.53594
2.56362
2.5912
2.61874
2.64638
2.6741
2.7016
2.72859
2.75494
2.78068
2.80567
2.82974
2.85271
2.87446
2.89498
2.91426
2.93231
2.94904
2.96448
2.9784
2.99096
3.00196
3.0115
3.01959
3.02637
3.03194
3.03528
3.03919
3.04196
3.04267
3.04317
3.04278
3.0423
3.04198
3.0417
3.04174
3.04189
3.04189
3.04148
3.04052
3.03994
3.04178
3.0417
3.03988
3.0367
3.03254
3.0278
3.02292
3.01827
3.01415
3.01064
3.00777
3.0056
3.00395
3.00271
3.00182
3.0012
3.00077
3.00049
3.00031
3.00019
3.00012
3.00007
3.00004
3.00003
2.99981
2.99969
2.99887
2.99686
2.98928
2.97621
2.92689
2.84121
2.6011
2.3294
2.07822
1.99567
1.98364
1.99134
2.00384
2.0199
2.04015
2.06111
2.08409
2.10829
2.13354
2.15976
2.18659
2.21377
2.24104
2.26837
2.2957
2.323
2.35028
2.37755
2.40488
2.43213
2.45935
2.48656
2.51365
2.54058
2.56732
2.59399
2.6207
2.64742
2.67385
2.69972
2.72518
2.75017
2.77461
2.79831
2.82106
2.84272
2.8632
2.88254
2.90075
2.91786
2.93378
2.94845
2.96174
2.97368
2.98419
2.99342
3.0012
3.0079
3.01318
3.01722
3.02039
3.0236
3.02528
3.02601
3.0266
3.02712
3.02788
3.02864
3.02952
3.03023
3.03077
3.03243
3.03499
3.03645
3.03701
3.03621
3.03402
3.03072
3.02667
3.02228
3.01796
3.01404
3.01067
3.00791
3.00574
3.00406
3.00284
3.00194
3.0013
3.00086
3.00055
3.00035
3.00022
3.00014
3.00008
3.00005
3.00003
3.00002
2.99998
2.99996
2.9998
2.99965
2.99862
2.99515
2.98789
2.9642
2.91194
2.76355
2.55035
2.25995
2.08022
2.04974
2.04402
2.05602
2.07097
2.0881
2.10761
2.12599
2.14738
2.17099
2.19608
2.22221
2.24885
2.27583
2.30288
2.32995
2.35698
2.38396
2.41089
2.43773
2.46439
2.49097
2.51743
2.54371
2.56976
2.5956
2.62124
2.64651
2.67137
2.69584
2.71996
2.74367
2.76679
2.78912
2.81051
2.83085
2.85014
2.86837
2.88567
2.90195
2.91714
2.93114
2.94385
2.95528
2.96543
2.97432
2.98198
2.9885
2.99385
2.99813
3.00165
3.00504
3.00724
3.00836
3.00973
3.0114
3.0131
3.01485
3.01713
3.0198
3.02266
3.02567
3.02835
3.03006
3.03043
3.0294
3.02719
3.02408
3.0204
3.01663
3.01312
3.01006
3.00753
3.00551
3.00396
3.00279
3.00194
3.00131
3.00088
3.00058
3.00038
3.00024
3.00015
3.0001
3.00006
3.00004
3.00002
3.00002
3.00001
3
2.99999
2.9999
2.99985
2.9993
2.99872
2.99418
2.9825
2.95616
2.88886
2.7443
2.49868
2.2613
2.12801
2.10804
2.10804
2.12053
2.13466
2.15231
2.17054
2.18825
2.20905
2.23231
2.25715
2.28271
2.30878
2.33522
2.36182
2.38839
2.41492
2.44127
2.46744
2.49333
2.51904
2.54449
2.56958
2.59435
2.61872
2.64276
2.66649
2.68981
2.71263
2.73501
2.75682
2.77782
2.7979
2.81703
2.83524
2.85258
2.86905
2.88469
2.89928
2.91271
2.92492
2.93591
2.94573
2.95439
2.96196
2.96848
2.97399
2.9786
2.98263
2.98632
2.98908
2.9909
2.99326
2.99617
2.99919
3.00246
3.00617
3.01027
3.01451
3.01832
3.02118
3.02278
3.02306
3.02216
3.02013
3.01733
3.01428
3.01136
3.00879
3.00663
3.00491
3.00356
3.00254
3.00178
3.00123
3.00084
3.00056
3.00037
3.00024
3.00016
3.0001
3.00006
3.00004
3.00003
3.00002
3.00002
3.00001
3.00001
3
3
2.99997
2.9999
2.99964
2.9991
2.99683
2.99299
2.97901
2.95235
2.87909
2.74032
2.51254
2.29361
2.18174
2.16665
2.17053
2.18296
2.19746
2.21454
2.23249
2.25035
2.26982
2.29187
2.31554
2.3398
2.36454
2.38972
2.41518
2.44071
2.46609
2.49126
2.51618
2.5409
2.56528
2.58924
2.61294
2.6362
2.65891
2.68107
2.70268
2.72381
2.74438
2.76426
2.78318
2.80128
2.81864
2.83523
2.85116
2.86622
2.88028
2.89318
2.90492
2.91561
2.92522
2.93384
2.94145
2.94812
2.95393
2.95905
2.96367
2.96782
2.97099
2.97407
2.97792
2.9821
2.98657
2.99147
2.99669
3.00194
3.00677
3.01074
3.01369
3.01556
3.01608
3.01515
3.01328
3.01107
3.00889
3.00694
3.00529
3.00396
3.00291
3.0021
3.0015
3.00106
3.00073
3.0005
3.00034
3.00022
3.00015
3.0001
3.00006
3.00004
3.00003
3.00002
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3
3
2.99996
2.99995
2.99967
2.99923
2.99712
2.99199
2.97969
2.9486
2.87918
2.736
2.56466
2.34679
2.24507
2.22492
2.2324
2.24249
2.25684
2.27409
2.29225
2.31001
2.32797
2.34814
2.37018
2.39294
2.41617
2.4398
2.46371
2.48774
2.5117
2.53552
2.55902
2.58204
2.60458
2.62685
2.64852
2.66958
2.69016
2.71023
2.72978
2.74864
2.76667
2.78391
2.80062
2.81672
2.83212
2.84666
2.86023
2.87275
2.88427
2.89476
2.90432
2.91297
2.92076
2.92779
2.93409
2.93989
2.94519
2.9498
2.95406
2.95919
2.96467
2.97033
2.97625
2.98236
2.98842
2.99413
2.99932
3.00403
3.00768
3.00943
3.00946
3.00856
3.00729
3.00596
3.00472
3.00366
3.00278
3.00208
3.00154
3.00112
3.00081
3.00057
3.0004
3.00028
3.00019
3.00013
3.00009
3.00006
3.00004
3.00003
3.00002
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3
2.99999
2.99999
2.9999
2.99976
2.99899
2.99732
2.99252
2.97998
2.95537
2.89304
2.78258
2.62178
2.42557
2.31731
2.28242
2.29341
2.29994
2.31444
2.32979
2.34833
2.36602
2.38339
2.40193
2.42184
2.44313
2.46501
2.48715
2.50922
2.53113
2.55282
2.57428
2.59551
2.61634
2.63692
2.6569
2.67644
2.69556
2.71414
2.73204
2.74926
2.76583
2.78194
2.79758
2.81249
2.82661
2.83988
2.8522
2.86361
2.87416
2.88387
2.89281
2.90111
2.90876
2.91589
2.92252
2.92851
2.93433
2.94088
2.94746
2.95409
2.9608
2.96756
2.97427
2.98104
2.98814
2.99506
3.00009
3.00262
3.00354
3.00365
3.00335
3.0029
3.00241
3.00195
3.00154
3.0012
3.00092
3.0007
3.00052
3.00039
3.00028
3.0002
3.00014
3.0001
3.00007
3.00005
3.00003
3.00002
3.00002
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3
3
2.99997
2.99993
2.99968
2.99919
2.99753
2.99363
2.98453
2.963
2.91605
2.82715
2.70582
2.53211
2.40697
2.34696
2.34922
2.35711
2.36837
2.38282
2.39949
2.41784
2.43675
2.45471
2.47292
2.49188
2.51138
2.53108
2.55063
2.56996
2.58914
2.60821
2.62704
2.64564
2.66384
2.68194
2.6995
2.71634
2.73262
2.7485
2.76405
2.77932
2.794
2.80787
2.82088
2.83323
2.84481
2.8556
2.86575
2.87538
2.88454
2.89316
2.90118
2.90835
2.9158
2.92347
2.93085
2.93809
2.94524
2.95246
2.96019
2.96916
2.97913
2.9877
2.99312
2.99618
2.99799
2.99909
2.99974
3.00012
3.00032
3.0004
3.00042
3.0004
3.00036
3.00031
3.00025
3.0002
3.00016
3.00012
3.00009
3.00007
3.00005
3.00004
3.00003
3.00002
3.00002
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3
2.99998
2.99991
2.99976
2.99925
2.99813
2.99525
2.98888
2.97446
2.94471
2.88545
2.78828
2.66802
2.52286
2.43724
2.40187
2.41269
2.42284
2.4347
2.44922
2.4657
2.48328
2.50214
2.51993
2.53656
2.55328
2.57028
2.58745
2.60465
2.62187
2.63883
2.65575
2.67249
2.68897
2.70478
2.72012
2.73548
2.75069
2.76559
2.77992
2.79353
2.80639
2.81882
2.83077
2.84199
2.85267
2.86315
2.87311
2.8821
2.89017
2.89857
2.90674
2.9145
2.92208
2.92969
2.93814
2.94873
2.96157
2.97362
2.98195
2.98719
2.99083
2.99351
2.99549
2.99694
2.99799
2.99872
2.99923
2.99956
2.99978
2.99992
2.99999
3.00003
3.00005
3.00005
3.00005
3.00005
3.00004
3.00003
3.00002
3.00002
3.00002
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3
3
2.99998
2.99993
2.99979
2.99947
2.99873
2.99685
2.99327
2.98466
2.96688
2.93143
2.86829
2.78608
2.67799
2.56719
2.49708
2.46592
2.47293
2.485
2.49778
2.51125
2.52584
2.54158
2.55849
2.5754
2.59169
2.6079
2.62386
2.63951
2.65504
2.67063
2.68587
2.7007
2.7151
2.72964
2.74431
2.7585
2.77223
2.7854
2.79797
2.81025
2.82219
2.83342
2.84412
2.85485
2.86457
2.87297
2.88169
2.89015
2.89823
2.90647
2.91617
2.92907
2.94506
2.96009
2.97075
2.97785
2.98321
2.98745
2.99079
2.99337
2.99532
2.99676
2.9978
2.99854
2.99906
2.99941
2.99964
2.99979
2.99989
2.99995
2.99998
3
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3
2.99999
2.99995
2.99987
2.99968
2.99921
2.9983
2.99603
2.99172
2.98209
2.96375
2.93111
2.88
2.81723
2.73819
2.64747
2.57998
2.53927
2.533
2.541
2.55482
2.56956
2.58363
2.59754
2.61183
2.6264
2.64135
2.65596
2.67064
2.68523
2.69914
2.71268
2.72647
2.74035
2.75387
2.76674
2.77924
2.79134
2.80333
2.815
2.82605
2.83656
2.84697
2.85606
2.86461
2.87376
2.88403
2.8972
2.91436
2.93355
2.95005
2.96165
2.96999
2.97671
2.98224
2.98671
2.99023
2.99293
2.99497
2.99647
2.99756
2.99834
2.99889
2.99927
2.99953
2.9997
2.99982
2.99989
2.99994
2.99997
2.99999
3
3
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3
3
2.99999
2.99998
2.99992
2.99984
2.99959
2.99915
2.99805
2.99596
2.99149
2.98309
2.9681
2.94499
2.91019
2.86875
2.81973
2.75916
2.69733
2.64728
2.62092
2.60901
2.61038
2.61976
2.63231
2.64615
2.65975
2.6735
2.68706
2.70024
2.71274
2.72558
2.73853
2.75094
2.76322
2.77471
2.78633
2.79793
2.80884
2.8195
2.83032
2.84164
2.85517
2.87189
2.89177
2.91285
2.93189
2.94663
2.95729
2.96604
2.97342
2.97955
2.98454
2.9885
2.99156
2.99389
2.99563
2.99691
2.99784
2.99851
2.99898
2.99931
2.99954
2.9997
2.99981
2.99988
2.99993
2.99996
2.99998
2.99999
3
3
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3
3
2.99999
2.99996
2.99992
2.99981
2.9996
2.99912
2.9982
2.99634
2.99293
2.98712
2.97792
2.96438
2.94588
2.92206
2.89596
2.86675
2.83627
2.8012
2.76929
2.74531
2.72897
2.7202
2.71692
2.71907
2.72461
2.73233
2.74065
2.75001
2.76188
2.77493
2.78892
2.8034
2.82075
2.83792
2.85584
2.87535
2.8945
2.91274
2.92856
2.94113
2.95152
2.96061
2.96847
2.97516
2.98075
2.98529
2.9889
2.99173
2.99391
2.99556
2.9968
2.99771
2.99838
2.99886
2.99921
2.99946
2.99963
2.99975
2.99984
2.9999
2.99994
2.99996
2.99998
2.99999
3
3
3
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3
3
2.99999
2.99997
2.99992
2.99983
2.99963
2.99926
2.99855
2.99733
2.99533
2.99222
2.98768
2.98141
2.97331
2.9635
2.95217
2.94033
2.92818
2.91619
2.90625
2.89713
2.89091
2.88619
2.8846
2.88472
2.8872
2.89046
2.89537
2.90231
2.91055
2.91925
2.92795
2.93614
2.94414
2.95191
2.95917
2.96583
2.97182
2.97712
2.98169
2.98555
2.98873
2.99132
2.99339
2.99502
2.99628
2.99725
2.99799
2.99854
2.99895
2.99925
2.99947
2.99963
2.99974
2.99983
2.99988
2.99992
2.99995
2.99997
2.99998
2.99999
3
3
3
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3
3
2.99999
2.99997
2.99993
2.99986
2.99972
2.99947
2.99907
2.99845
2.99751
2.99619
2.99441
2.99212
2.98937
2.98618
2.98273
2.97916
2.97571
2.97254
2.96988
2.96777
2.96641
2.96575
2.96608
2.96674
2.96771
2.96932
2.97174
2.9744
2.97717
2.97993
2.98268
2.98519
2.98756
2.9897
2.99158
2.99321
2.99459
2.99574
2.99668
2.99744
2.99805
2.99853
2.9989
2.99918
2.9994
2.99956
2.99969
2.99978
2.99984
2.99989
2.99993
2.99995
2.99997
2.99998
2.99999
3
3
3
3
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3
3
2.99999
2.99998
2.99995
2.9999
2.99982
2.9997
2.99952
2.99926
2.99891
2.99845
2.99789
2.99722
2.99648
2.99567
2.99487
2.99406
2.99339
2.99281
2.99235
2.99211
2.99199
2.99212
2.99228
2.99255
2.99302
2.99362
2.99427
2.99492
2.99557
2.9962
2.99678
2.99731
2.99778
2.99819
2.99855
2.99885
2.99909
2.9993
2.99946
2.99959
2.99969
2.99977
2.99983
2.99988
2.99991
2.99994
2.99996
2.99997
2.99998
2.99999
3
3
3
3
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3
3
3
2.99998
2.99997
2.99994
2.9999
2.99985
2.99977
2.99967
2.99954
2.99939
2.99922
2.99903
2.99883
2.99864
2.99845
2.99829
2.99816
2.99806
2.998
2.99799
2.99802
2.99806
2.99814
2.99826
2.99841
2.99857
2.99873
2.9989
2.99905
2.9992
2.99933
2.99945
2.99955
2.99964
2.99971
2.99978
2.99983
2.99987
2.9999
2.99993
2.99995
2.99996
2.99997
2.99998
2.99999
3
3
3
3
3
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
)
;
boundaryField
{
inlet
{
type calculated;
value uniform 3.00001;
}
outlet
{
type calculated;
value nonuniform List<scalar>
40
(
3.00018
3.00022
3.00022
3.00024
3.00022
3.00023
3.00022
3.00022
3.0002
3.0002
3.00018
3.00017
3.00016
3.00014
3.00013
3.00011
3.0001
3.00009
3.00008
3.00007
3.00005
3.00005
3.00004
3.00003
3.00002
3.00002
3.00002
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
3.00001
)
;
}
bottom
{
type symmetryPlane;
}
top
{
type symmetryPlane;
}
obstacle
{
type calculated;
value uniform 0;
}
defaultFaces
{
type empty;
}
}
// ************************************************************************* //
| [
"jfeatherstone123@gmail.com"
] | jfeatherstone123@gmail.com | |
91670aa1925e522cf6e6709ef97e6492a30f0a2b | 95326a775c0b4980561ab7b1a7f43058c9ef9b7c | /Exercices/src/Labels.h | 1a5a235b06def6100f8e9ec54187b207bf8cfb26 | [
"MIT"
] | permissive | polferrando98/ParticleSystem | ef2526dba76f9484a02dfeb55fcf65c32f3915b1 | ad112cb0bcf581bdb696febe7c80f32960ed546f | refs/heads/master | 2020-03-10T03:06:36.161625 | 2018-06-01T09:14:07 | 2018-06-01T09:14:07 | 129,154,997 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 513 | h | #ifndef _LABELS_
#define _LABELS_
#include "Widgets.h"
#include "mdFonts.h"
#include "SDL/include/SDL.h"
class Labels : public Widgets {
public:
Labels(const char* content, const SDL_Color& color, _TTF_Font* font_size, std::pair<int, int> pos, Module* callback);
~Labels();
void draw();
void setText(const char* content, const SDL_Color &color, _TTF_Font* font_size);
void setArea(std::pair<int, int> area);
void changeContent(const char* new_content);
public:
SDL_Texture* text_texture;
};
#endif
| [
"pol.ferrando.98@gmail.com"
] | pol.ferrando.98@gmail.com |
87a01ff60f0557b6cb1b021255f7d3fb52849d3e | c0338811bab1c94204c12bf2c33324ac0d33f36b | /ModelPusty.cpp | ec1328536f0cc9dd81a1ab0b9269386ad9a0f550 | [] | no_license | MateuszBielski/odZera | 7933a28937987a454a5a526590ab4b0b527cff9c | 5c0575021801119c765eeea887a29d17c4286b2b | refs/heads/master | 2020-03-21T18:50:00.921940 | 2018-12-24T11:41:14 | 2018-12-24T11:41:14 | 138,915,765 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 173 | cpp | #include "ModelPusty.h"
ModelPusty::~ModelPusty()
{
// g_print("\ndestruktor ModelPusty");
}
itLspModel ModelPusty::AdresPelnegoObiektu()
{
return tuJestemPelny;
}
| [
"mateo_bass@bialan.pl"
] | mateo_bass@bialan.pl |
7f56b59b48dd6c72a616a243b390b56d82766e8f | f5d27caff31fa8a7924738256086f506d0ff260b | /Pixy_get_video/get_video_from_pixy.cpp | 26301e9a91eb269877569f68ea5ac8bf5af393f8 | [] | no_license | edwardlo12/Pixy_get_video | d37a391458814e7545fac6bba6deac60452383ee | 4c910a52b0b87ade9b4252fa87a63d7272019cd6 | refs/heads/master | 2021-01-19T18:38:47.272039 | 2017-04-16T08:33:41 | 2017-04-16T08:33:41 | 88,369,908 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,531 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <math.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <ctime>
#include "pixy.h"
using namespace cv;
using namespace std;
void interpolateBayer(unsigned int width, unsigned int x, unsigned int y, unsigned char *pixel, unsigned int &r, unsigned int &g, unsigned int &b);
Mat renderBA81(uint8_t renderFlags, uint16_t width, uint16_t height, uint32_t frameLen, uint8_t *frame);
Mat getImage();
int main(int argc, char * argv[])
{
int pixy_init_status;
int return_value;
int32_t response;
pixy_init_status = pixy_init();
if (!pixy_init_status == 0)
{
printf("pixy_init(): ");
pixy_error(pixy_init_status);
return pixy_init_status;
}
return_value = pixy_command("stop", END_OUT_ARGS, &response, END_IN_ARGS);
return_value = pixy_rcs_set_position(1, 900);
return_value = pixy_rcs_set_position(0, 500);
Mat pixy_image = getImage();
namedWindow("Image", CV_WINDOW_NORMAL);
imshow("Image", pixy_image);
return 0;
}
Mat getImage()
{
unsigned char *pixels;
int32_t response, fourcc;
int8_t renderflags;
int return_value, res;
uint16_t rwidth, rheight;
uint32_t numPixels;
uint16_t height, width;
uint16_t mode;
return_value = pixy_command("run", END_OUT_ARGS, &response, END_IN_ARGS);
return_value = pixy_command("stop", END_OUT_ARGS, &response, END_IN_ARGS);
return_value = pixy_command("cam_getFrame", // String id for remote procedure
0x01, 0x21, // mode
0x02, 0, // xoffset
0x02, 0, // yoffset
0x02, 320, // width
0x02, 200, // height
0, // separator
&response, &fourcc, &renderflags, &rwidth, &rheight, &numPixels, &pixels, 0);
return renderBA81(renderflags, rwidth, rheight, numPixels, pixels);
}
inline void interpolateBayer(uint16_t width, uint16_t x, uint16_t y, uint8_t *pixel, uint8_t* r, uint8_t* g, uint8_t* b)
{
if (y & 1)
{
if (x & 1)
{
*r = *pixel;
*g = (*(pixel - 1) + *(pixel + 1) + *(pixel + width) + *(pixel - width)) >> 2;
*b = (*(pixel - width - 1) + *(pixel - width + 1) + *(pixel + width - 1) + *(pixel + width + 1)) >> 2;
}
else
{
*r = (*(pixel - 1) + *(pixel + 1)) >> 1;
*g = *pixel;
*b = (*(pixel - width) + *(pixel + width)) >> 1;
}
}
else
{
if (x & 1)
{
*r = (*(pixel - width) + *(pixel + width)) >> 1;
*g = *pixel;
*b = (*(pixel - 1) + *(pixel + 1)) >> 1;
}
else
{
*r = (*(pixel - width - 1) + *(pixel - width + 1) + *(pixel + width - 1) + *(pixel + width + 1)) >> 2;
*g = (*(pixel - 1) + *(pixel + 1) + *(pixel + width) + *(pixel - width)) >> 2;
*b = *pixel;
}
}
}
void interpolateBayer(unsigned int width, unsigned int x, unsigned int y, unsigned char * pixel, unsigned int & r, unsigned int & g, unsigned int & b)
{
}
Mat renderBA81(uint8_t renderFlags, uint16_t width, uint16_t height, uint32_t frameLen, uint8_t *frame)
{
uint16_t x, y;
uint8_t r, g, b;
Mat imageRGB;
Mat imageHSV;
frame += width;
uchar data[3 * ((height - 2)*(width - 2))];
uint m = 0;
for (y = 1; y<height - 1; y++)
{
frame++;
for (x = 1; x<width - 1; x++, frame++)
{
interpolateBayer(width, x, y, frame, &r, &g, &b);
data[m++] = b;
data[m++] = g;
data[m++] = r;
}
frame++;
}
imageRGB = Mat(height - 2, width - 2, CV_8UC3, data);
cvtColor(imageRGB, imageHSV, CV_BGR2HSV);
return imageHSV;
}
//test05 | [
"edwardssd@EDWARDSSD-PC"
] | edwardssd@EDWARDSSD-PC |
1498b904268dd16aa3bfd7594ece60e3613b148e | 73ee941896043f9b3e2ab40028d24ddd202f695f | /external/chromium_org/chrome/browser/ui/webui/ntp/android/navigation_handler.cc | d5c9a2e1693f74bc8e2aeb594833d0b1d453f18e | [
"BSD-3-Clause"
] | permissive | CyFI-Lab-Public/RetroScope | d441ea28b33aceeb9888c330a54b033cd7d48b05 | 276b5b03d63f49235db74f2c501057abb9e79d89 | refs/heads/master | 2022-04-08T23:11:44.482107 | 2016-09-22T20:15:43 | 2016-09-22T20:15:43 | 58,890,600 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 3,011 | cc | // Copyright 2013 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/ui/webui/ntp/android/navigation_handler.h"
#include "base/bind.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/values.h"
#include "chrome/browser/google/google_util.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/common/page_transition_types.h"
NavigationHandler::NavigationHandler() {}
NavigationHandler::~NavigationHandler() {
// Record an omnibox-based navigation, if there is one.
content::NavigationEntry* entry =
web_ui()->GetWebContents()->GetController().GetActiveEntry();
if (!entry)
return;
if (!(entry->GetTransitionType() &
content::PAGE_TRANSITION_FROM_ADDRESS_BAR) ||
entry->GetTransitionType() & content::PAGE_TRANSITION_FORWARD_BACK) {
return;
}
if (entry->GetURL().SchemeIs(chrome::kChromeUIScheme) &&
entry->GetURL().host() == chrome::kChromeUINewTabHost) {
return;
}
Action action;
if ((entry->GetTransitionType() & content::PAGE_TRANSITION_CORE_MASK) ==
content::PAGE_TRANSITION_GENERATED) {
action = ACTION_SEARCHED_USING_OMNIBOX;
} else if (google_util::IsGoogleHomePageUrl(entry->GetURL())) {
action = ACTION_NAVIGATED_TO_GOOGLE_HOMEPAGE;
} else {
action = ACTION_NAVIGATED_USING_OMNIBOX;
}
RecordAction(action);
}
void NavigationHandler::RegisterMessages() {
web_ui()->RegisterMessageCallback(
"openedMostVisited",
base::Bind(&NavigationHandler::HandleOpenedMostVisited,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
"openedRecentlyClosed",
base::Bind(&NavigationHandler::HandleOpenedRecentlyClosed,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
"openedBookmark",
base::Bind(&NavigationHandler::HandleOpenedBookmark,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
"openedForeignSession",
base::Bind(&NavigationHandler::HandleOpenedForeignSession,
base::Unretained(this)));
}
void NavigationHandler::HandleOpenedMostVisited(const base::ListValue* args) {
RecordAction(ACTION_OPENED_MOST_VISITED_ENTRY);
}
void NavigationHandler::HandleOpenedRecentlyClosed(
const base::ListValue* args) {
RecordAction(ACTION_OPENED_RECENTLY_CLOSED_ENTRY);
}
void NavigationHandler::HandleOpenedBookmark(const base::ListValue* args) {
RecordAction(ACTION_OPENED_BOOKMARK);
}
void NavigationHandler::HandleOpenedForeignSession(
const base::ListValue* args) {
RecordAction(ACTION_OPENED_FOREIGN_SESSION);
}
void NavigationHandler::RecordAction(Action action) {
UMA_HISTOGRAM_ENUMERATION("NewTabPage.ActionAndroid", action, NUM_ACTIONS);
}
| [
"ProjectRetroScope@gmail.com"
] | ProjectRetroScope@gmail.com |
82dc161e29657204d72925bc2fa0b5d405cd7d79 | a30a69ada79fd9799f27e45c7234fbca23ffd4e9 | /MRF_JW/GraphCuts.cpp | bd21474ea6455f5ef4f08f1bc9434109e22482a9 | [] | no_license | leejang/stereo_matching | b4be4a8547fec0442c19e66fb4ba521a65dace5c | 5127472db7d4cf00492b44be28d31efb0b760efa | refs/heads/master | 2020-04-20T21:06:01.654909 | 2019-02-04T15:17:02 | 2019-02-04T15:17:02 | 169,097,748 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,766 | cpp | /*
* File: GraphCuts.cpp
*
* This file originzted from the MRF 2.2 Library
* slightly modfied by Jangwon Lee, 11/2016
* Email: leejang@indiana.edu
*/
#include "energy.h"
#include "graph.h"
#include "GraphCuts.h"
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include "string.h"
#define MAX_INTT 1000000000
/**************************************************************************************/
void GraphCuts::initialize_memory()
{
m_lookupPixVar = (PixelType *) new PixelType[m_nPixels];
m_labelTable = (LabelType *) new LabelType[m_nLabels];
terminateOnError( !m_lookupPixVar || !m_labelTable ,"Not enough memory");
for ( int i = 0; i < m_nLabels; i++ )
m_labelTable[i] = i;
}
/**************************************************************************************/
void GraphCuts::commonGridInitialization(PixelType width, PixelType height, int nLabels)
{
terminateOnError( (width < 0) || (height <0) || (nLabels <0 ),"Illegal negative parameters");
m_width = width;
m_height = height;
m_nPixels = width*height;
m_nLabels = nLabels;
m_grid_graph = 1;
}
/**************************************************************************************/
void GraphCuts::setParameters(int numParam, void *param)
{
if (numParam != 1 )
printf("\nInvalid number of parameters, can only set one parameter\\that is boolean label order\n");
else
{
m_random_label_order = *((bool *) param);
}
}
/**************************************************************************************/
void GraphCuts::commonNonGridInitialization(PixelType nupixels, int num_labels)
{
terminateOnError( (nupixels <0) || (num_labels <0 ),"Illegal negative parameters");
m_nLabels = num_labels;
m_nPixels = nupixels;
m_grid_graph = 0;
m_neighbors = (LinkedBlockList *) new LinkedBlockList[nupixels];
terminateOnError(!m_neighbors,"Not enough memory");
}
/**************************************************************************************/
void GraphCuts::commonInitialization()
{
m_needToFreeV = 0;
m_random_label_order = 1;
initialize_memory();
}
/**************************************************************************************/
/* Use this constructor only for grid graphs */
GraphCuts::GraphCuts(PixelType width,PixelType height,LabelType nLabels,EnergyFunction *eng):MRF(width,height,nLabels,eng)
{
commonGridInitialization(width,height,nLabels);
m_labeling = (LabelType *) new LabelType[m_nPixels];
terminateOnError(!m_labeling,"out of memory");
for ( int i = 0; i < m_nPixels; i++ ) m_labeling[i] = (LabelType) 0;
commonInitialization();
}
/**************************************************************************************/
/* Use this constructor for general graphs */
GraphCuts::GraphCuts(PixelType nPixels,int nLabels,EnergyFunction *eng):MRF(nPixels,nLabels,eng)
{
commonNonGridInitialization(nPixels, nLabels);
m_labeling = (LabelType *) new LabelType[m_nPixels];
terminateOnError(!m_labeling,"out of memory");
for ( int i = 0; i < nPixels; i++ ) m_labeling[i] = (LabelType) 0;
commonInitialization();
}
/**************************************************************************************/
void GraphCuts::setData(EnergyTermType* dataArray)
{
m_datacost = dataArray;
}
/**************************************************************************************/
// Truncated L1
void GraphCuts::setSmoothness(int smoothExp,CostVal smoothMax, CostVal lambda)
{
int i, j;
CostVal cost;
m_needToFreeV = 1;
m_smoothcost = (CostVal *) new CostVal[m_nLabels*m_nLabels];
if (!m_smoothcost) { fprintf(stderr, "Not enough memory!\n"); exit(1); }
for (i=0; i<m_nLabels; i++)
for (j=i; j<m_nLabels; j++)
{
cost = (CostVal)(j - i);
if (cost > smoothMax) cost = smoothMax;
m_smoothcost[i*m_nLabels + j] = m_smoothcost[j*m_nLabels + i] = cost*lambda;
}
}
#if 0
// Pott Model
void GraphCuts::setSmoothness(int smoothExp,CostVal smoothMax, CostVal lambda)
{
int i, j;
CostVal cost;
m_needToFreeV = 1;
m_smoothcost = (CostVal *) new CostVal[m_nLabels*m_nLabels];
if (!m_smoothcost) { fprintf(stderr, "Not enough memory!\n"); exit(1); }
for (i=0; i<m_nLabels; i++)
for (j=i; j<m_nLabels; j++) {
if (j == i)
cost = (CostVal) 0;
else
cost = (CostVal) 10;
m_smoothcost[i*m_nLabels + j] = m_smoothcost[j*m_nLabels + i] = cost;
}
}
#endif
/**************************************************************************************/
void GraphCuts::setSmoothness(SmoothCostGeneralFn cost)
{
m_smoothFnPix = cost;
}
/**************************************************************************************/
GraphCuts::EnergyType GraphCuts::dataEnergy()
{
if (m_dataType == ARRAY)
return(giveDataEnergyArray());
else
fprintf(stderr, "Did not support Function Type Data Energy!\n");
return(0);
}
/**************************************************************************************/
GraphCuts::EnergyType GraphCuts::giveDataEnergyArray()
{
EnergyType eng = (EnergyType) 0;
for ( int i = 0; i < m_nPixels; i++ )
eng = eng + m_datacost(i,m_labeling[i]);
return(eng);
}
/**************************************************************************************/
GraphCuts::EnergyType GraphCuts::smoothnessEnergy()
{
if (m_grid_graph)
{
if ( m_smoothType != FUNCTION )
{
if (m_varWeights) return(fprintf(stderr, "Did not support weighted array for data cost!\n"));
else return(giveSmoothEnergy_G_ARRAY());
}
else return(fprintf(stderr, "Did not support Function Type Data Energy!\n"));
}
else
{
fprintf(stderr, "Did not support Non Grid Type!\n");
}
return(0);
}
/**************************************************************************************/
GraphCuts::EnergyType GraphCuts::giveSmoothEnergy_G_ARRAY()
{
EnergyType eng = (EnergyType) 0;
int x,y,pix;
for ( y = 0; y < m_height; y++ )
for ( x = 1; x < m_width; x++ )
{
pix = x+y*m_width;
eng = eng + m_smoothcost(m_labeling[pix],m_labeling[pix-1]);
}
for ( y = 1; y < m_height; y++ )
for ( x = 0; x < m_width; x++ )
{
pix = x+y*m_width;
eng = eng + m_smoothcost(m_labeling[pix],m_labeling[pix-m_width]);
}
return(eng);
}
/**************************************************************************************/
void GraphCuts::setLabelOrder(bool RANDOM_LABEL_ORDER)
{
m_random_label_order = RANDOM_LABEL_ORDER;
}
/****************************************************************************/
/* This procedure checks if an error has occured, terminates program if yes */
void GraphCuts::terminateOnError(bool error_condition,const char *message)
{
if (error_condition)
{
fprintf(stderr, "\n %s \n", message);
exit(1);
}
}
/****************************************************************************/
void GraphCuts::clearAnswer()
{
if (!m_labeling ) {printf("First initialize algorithm" );exit(0);}
memset(m_labeling, 0, m_nPixels*sizeof(Label));
}
/****************************************************************************/
void GraphCuts::scramble_label_table()
{
LabelType r1,r2,temp;
int num_times,cnt;
num_times = m_nLabels*2;
srand(clock());
for ( cnt = 0; cnt < num_times; cnt++ )
{
r1 = rand()%m_nLabels;
r2 = rand()%m_nLabels;
temp = m_labelTable[r1];
m_labelTable[r1] = m_labelTable[r2];
m_labelTable[r2] = temp;
}
}
/**************************************************************************************/
void GraphCuts::add_t_links_ARRAY(Energy *e,Energy::Var *variables,int size,LabelType alpha_label)
{
for ( int i = 0; i < size; i++ )
e -> add_term1(variables[i], m_datacost(m_lookupPixVar[i],alpha_label),
m_datacost(m_lookupPixVar[i],m_labeling[m_lookupPixVar[i]]));
}
/**************************************************************************************/
void GraphCuts::add_t_links_FnPix(Energy *e,Energy::Var *variables,int size,LabelType alpha_label)
{
for ( int i = 0; i < size; i++ )
e -> add_term1(variables[i], m_dataFnPix(m_lookupPixVar[i],alpha_label),
m_dataFnPix(m_lookupPixVar[i],m_labeling[m_lookupPixVar[i]]));
}
/**************************************************************************************/
void GraphCuts::setNeighbors(PixelType pixel1, int pixel2, EnergyTermType weight)
{
assert(pixel1 < m_nPixels && pixel1 >= 0 && pixel2 < m_nPixels && pixel2 >= 0);
assert(m_grid_graph == 0);
Neighbor *temp1 = (Neighbor *) new Neighbor;
Neighbor *temp2 = (Neighbor *) new Neighbor;
temp1->weight = weight;
temp1->to_node = pixel2;
temp2->weight = weight;
temp2->to_node = pixel1;
m_neighbors[pixel1].addFront(temp1);
m_neighbors[pixel2].addFront(temp2);
}
/**************************************************************************************/
GraphCuts::~GraphCuts()
{
delete [] m_labeling;
if ( ! m_grid_graph ) delete [] m_neighbors;
delete [] m_labelTable;
delete [] m_lookupPixVar;
if (m_needToFreeV) delete [] m_smoothcost;
}
/**************************************************************************************/
Swap::Swap(PixelType width,PixelType height,int num_labels, EnergyFunction *eng):GraphCuts(width,height,num_labels,eng)
{
m_pixels = new PixelType[m_nPixels];
terminateOnError( !m_pixels ,"Not enough memory");
}
/**************************************************************************************/
Swap::~Swap()
{
delete [] m_pixels;
}
/**************************************************************************************/
GraphCuts::EnergyType Swap::swap(int max_num_iterations)
{
return(start_swap(max_num_iterations));
}
/**************************************************************************************/
GraphCuts::EnergyType Swap::start_swap(int max_num_iterations )
{
int curr_cycle = 1;
EnergyType new_energy,old_energy;
new_energy = dataEnergy()+smoothnessEnergy();
//old_energy = new_energy+1; // this doesn't work for large float energies
old_energy = -1;
while (old_energy < 0 || (old_energy > new_energy && curr_cycle <= max_num_iterations))
{
old_energy = new_energy;
new_energy = oneSwapIteration();
curr_cycle++;
}
//printf(" swap energy %d",new_energy);
return(new_energy);
}
/**************************************************************************************/
GraphCuts::EnergyType Swap::oneSwapIteration()
{
int next,next1;
if (m_random_label_order) scramble_label_table();
for (next = 0; next < m_nLabels; next++ )
for (next1 = m_nLabels - 1; next1 >= 0; next1-- )
if ( m_labelTable[next] < m_labelTable[next1] )
{
perform_alpha_beta_swap(m_labelTable[next],m_labelTable[next1]);
}
return(dataEnergy()+smoothnessEnergy());
}
/**************************************************************************************/
GraphCuts::EnergyType Swap::alpha_beta_swap(LabelType alpha_label, LabelType beta_label)
{
terminateOnError( alpha_label < 0 || alpha_label >= m_nLabels || beta_label < 0 || beta_label >= m_nLabels,
"Illegal Label to Expand On");
perform_alpha_beta_swap(alpha_label,beta_label);
return(dataEnergy()+smoothnessEnergy());
}
/**************************************************************************************/
void Swap::add_t_links_ARRAY_swap(Energy *e,Energy::Var *variables,int size,
LabelType alpha_label, LabelType beta_label,
PixelType *pixels)
{
for ( int i = 0; i < size; i++ )
e -> add_term1(variables[i], m_datacost(pixels[i],alpha_label),
m_datacost(pixels[i],beta_label));
}
/**************************************************************************************/
void Swap::add_t_links_FnPix_swap(Energy *e,Energy::Var *variables,int size,
LabelType alpha_label, LabelType beta_label,
PixelType *pixels)
{
for ( int i = 0; i < size; i++ )
e -> add_term1(variables[i], m_dataFnPix(pixels[i],alpha_label),
m_dataFnPix(pixels[i],beta_label));
}
/**************************************************************************************/
void Swap::perform_alpha_beta_swap(LabelType alpha_label, LabelType beta_label)
{
PixelType i,size = 0;
Energy *e = new Energy();
for ( i = 0; i < m_nPixels; i++ )
{
if ( m_labeling[i] == alpha_label || m_labeling[i] == beta_label)
{
m_pixels[size] = i;
m_lookupPixVar[i] = size;
size++;
}
}
if ( size == 0 ) return;
Energy::Var *variables = (Energy::Var *) new Energy::Var[size];
if (!variables) { fprintf(stderr, "Not enough memory!\n"); exit(1); }
for ( i = 0; i < size; i++ )
variables[i] = e ->add_variable();
if (m_dataType == ARRAY)
add_t_links_ARRAY_swap(e,variables,size,alpha_label,beta_label,m_pixels);
else
fprintf(stderr, "Did not support Function Type Data Energy!\n");
if (m_grid_graph) {
if ( m_smoothType != FUNCTION ) {
if (m_varWeights)
fprintf(stderr, "Did not support weighted array for data cost!\n");
else
set_up_swap_energy_G_ARRAY(size,alpha_label,beta_label,m_pixels,e,variables);
} else {
fprintf(stderr, "Did not support Function Type Data Energy!\n");
}
}
else
{
fprintf(stderr, "Did not support Non Grid Type!\n");
}
e -> minimize();
for ( i = 0; i < size; i++ )
if ( e->get_var(variables[i]) == 0 )
m_labeling[m_pixels[i]] = alpha_label;
else m_labeling[m_pixels[i]] = beta_label;
delete [] variables;
delete e;
}
/**************************************************************************************/
void Swap::set_up_swap_energy_G_ARRAY(int size,LabelType alpha_label,LabelType beta_label,
PixelType *pixels,Energy* e, Energy::Var *variables)
{
PixelType nPix,pix,i,x,y;
for ( i = 0; i < size; i++ )
{
pix = pixels[i];
y = pix/m_width;
x = pix - y*m_width;
if ( x > 0 )
{
nPix = pix - 1;
if ( m_labeling[nPix] == alpha_label || m_labeling[nPix] == beta_label)
e ->add_term2(variables[i],variables[m_lookupPixVar[nPix]],
m_smoothcost(alpha_label,alpha_label),
m_smoothcost(alpha_label,beta_label),
m_smoothcost(beta_label,alpha_label),
m_smoothcost(beta_label,beta_label) );
else
e ->add_term1(variables[i],m_smoothcost(alpha_label,m_labeling[nPix]),
m_smoothcost(beta_label,m_labeling[nPix]));
}
if ( y > 0 )
{
nPix = pix - m_width;
if ( m_labeling[nPix] == alpha_label || m_labeling[nPix] == beta_label)
e ->add_term2(variables[i],variables[m_lookupPixVar[nPix]],
m_smoothcost(alpha_label,alpha_label),
m_smoothcost(alpha_label,beta_label),
m_smoothcost(beta_label,alpha_label),
m_smoothcost(beta_label,beta_label) );
else
e ->add_term1(variables[i],m_smoothcost(alpha_label,m_labeling[nPix]),
m_smoothcost(beta_label,m_labeling[nPix]));
}
if ( x < m_width - 1 )
{
nPix = pix + 1;
if ( !(m_labeling[nPix] == alpha_label || m_labeling[nPix] == beta_label) )
e ->add_term1(variables[i],m_smoothcost(alpha_label,m_labeling[nPix]),
m_smoothcost(beta_label,m_labeling[nPix]));
}
if ( y < m_height - 1 )
{
nPix = pix + m_width;
if ( !(m_labeling[nPix] == alpha_label || m_labeling[nPix] == beta_label))
e ->add_term1(variables[i],m_smoothcost(alpha_label,m_labeling[nPix]),
m_smoothcost(beta_label,m_labeling[nPix]));
}
}
}
/**************************************************************************************/
void Swap::optimizeAlg(int nIterations)
{
swap(nIterations);
}
/**************************************************************************************/
GraphCuts::EnergyType Expansion::expansion(int max_num_iterations)
{
return(start_expansion(max_num_iterations));
}
/**************************************************************************************/
GraphCuts::EnergyType Expansion::start_expansion(int max_num_iterations )
{
int curr_cycle = 1;
EnergyType new_energy,old_energy;
new_energy = dataEnergy()+smoothnessEnergy();
//old_energy = new_energy+1; // this doesn't work for large float energies
old_energy = -1;
while (old_energy < 0 || (old_energy > new_energy && curr_cycle <= max_num_iterations))
{
old_energy = new_energy;
new_energy = oneExpansionIteration();
curr_cycle++;
}
//printf(" Exp energy %d",new_energy);
return(new_energy);
}
/**************************************************************************************/
GraphCuts::EnergyType Expansion::alpha_expansion(LabelType label)
{
terminateOnError( label < 0 || label >= m_nLabels,"Illegal Label to Expand On");
perform_alpha_expansion(label);
return(dataEnergy()+smoothnessEnergy());
}
/**************************************************************************************/
void Expansion::perform_alpha_expansion(LabelType alpha_label)
{
PixelType i,size = 0;
Energy *e = new Energy();
for ( i = 0; i < m_nPixels; i++ )
{
if ( m_labeling[i] != alpha_label )
{
m_lookupPixVar[size] = i;
size++;
}
}
if ( size > 0 )
{
Energy::Var *variables = (Energy::Var *) new Energy::Var[size];
if ( !variables) {printf("\nOut of memory, exiting");exit(1);}
for ( i = 0; i < size; i++ )
variables[i] = e ->add_variable();
if ( m_dataType == ARRAY ) add_t_links_ARRAY(e,variables,size,alpha_label);
else add_t_links_FnPix(e,variables,size,alpha_label);
if (m_grid_graph) {
if ( m_smoothType != FUNCTION ) {
if (m_varWeights)
fprintf(stderr, "Did not support weighted array for data cost!\n");
else
set_up_expansion_energy_G_ARRAY(size,alpha_label,e,variables);
} else {
fprintf(stderr, "Did not support Function Type Data Energy!\n");
}
} else {
fprintf(stderr, "Did not support Non Grid Type!\n");
}
e -> minimize();
for ( i = 0,size = 0; i < m_nPixels; i++ )
{
if ( m_labeling[i] != alpha_label )
{
if ( e->get_var(variables[size]) == 0 )
m_labeling[i] = alpha_label;
size++;
}
}
delete [] variables;
}
delete e;
}
/**********************************************************************************************/
/* Performs alpha-expansion for regular grid graph for case when energy terms are NOT */
/* specified by a function */
void Expansion::set_up_expansion_energy_G_ARRAY(int size, LabelType alpha_label,Energy *e,
Energy::Var *variables )
{
int i,nPix,pix,x,y;
for ( i = size - 1; i >= 0; i-- )
{
pix = m_lookupPixVar[i];
y = pix/m_width;
x = pix - y*m_width;
m_lookupPixVar[pix] = i;
if ( x < m_width - 1 )
{
nPix = pix + 1;
if ( m_labeling[nPix] != alpha_label )
e ->add_term2(variables[i],variables[m_lookupPixVar[nPix]],
m_smoothcost(alpha_label,alpha_label),
m_smoothcost(alpha_label,m_labeling[nPix]),
m_smoothcost(m_labeling[pix],alpha_label),
m_smoothcost(m_labeling[pix],m_labeling[nPix]));
else e ->add_term1(variables[i],m_smoothcost(alpha_label,m_labeling[nPix]),
m_smoothcost(m_labeling[pix],alpha_label));
}
if ( y < m_height - 1 )
{
nPix = pix + m_width;
if ( m_labeling[nPix] != alpha_label )
e ->add_term2(variables[i],variables[m_lookupPixVar[nPix]],
m_smoothcost(alpha_label,alpha_label) ,
m_smoothcost(alpha_label,m_labeling[nPix]),
m_smoothcost(m_labeling[pix],alpha_label) ,
m_smoothcost(m_labeling[pix],m_labeling[nPix]) );
else e ->add_term1(variables[i],m_smoothcost(alpha_label,m_labeling[nPix]),
m_smoothcost(m_labeling[pix],alpha_label));
}
if ( x > 0 )
{
nPix = pix - 1;
if ( m_labeling[nPix] == alpha_label )
e ->add_term1(variables[i],m_smoothcost(alpha_label,m_labeling[nPix]),
m_smoothcost(m_labeling[pix],alpha_label) );
}
if ( y > 0 )
{
nPix = pix - m_width;
if ( m_labeling[nPix] == alpha_label )
e ->add_term1(variables[i],m_smoothcost(alpha_label,alpha_label),
m_smoothcost(m_labeling[pix],alpha_label));
}
}
}
/**************************************************************************************/
GraphCuts::EnergyType Expansion::oneExpansionIteration()
{
int next;
terminateOnError( m_dataType == NONE,"You have to set up the data cost before running optimization");
terminateOnError( m_smoothType == NONE,"You have to set up the smoothness cost before running optimization");
if (m_random_label_order) scramble_label_table();
for (next = 0; next < m_nLabels; next++ )
perform_alpha_expansion(m_labelTable[next]);
return(dataEnergy()+smoothnessEnergy());
}
/**************************************************************************************/
void Expansion::optimizeAlg(int nIterations)
{
expansion(nIterations);
}
| [
"leejang@madthunder.soic.indiana.edu"
] | leejang@madthunder.soic.indiana.edu |
1fa79d33b2249d1f38c84f839ac045bb69213d9c | b367fe5f0c2c50846b002b59472c50453e1629bc | /xbox_leak_may_2020/xbox trunk/xbox/private/test/crttests/test/clib/time/drv.cpp | 1b91b4add90396d347c45b3007efbbe889628dbb | [] | no_license | sgzwiz/xbox_leak_may_2020 | 11b441502a659c8da8a1aa199f89f6236dd59325 | fd00b4b3b2abb1ea6ef9ac64b755419741a3af00 | refs/heads/master | 2022-12-23T16:14:54.706755 | 2020-09-27T18:24:48 | 2020-09-27T18:24:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 652 | cpp | #include <xtl.h>
int gmtime1Entry();
int localtime1Entry();
int mktime1Entry();
int mktime2Entry();
//int mktime3Entry();
int futime1Entry();
int futime2Entry();
int utime1Entry();
int utime2Entry();
int ftime1Entry();
int time1Entry();
int ctime1Entry();
//int strftime1Entry();
int testcrtEntry();
#ifdef __cplusplus
extern "C"
#endif
void __cdecl timeStartTest()
{
gmtime1Entry();
localtime1Entry();
mktime1Entry();
mktime2Entry();
//mktime3Entry();
futime1Entry();
futime2Entry();
utime1Entry();
utime2Entry();
ftime1Entry();
time1Entry();
ctime1Entry();
//strftime1Entry();
testcrtEntry();
}
| [
"benjamin.barratt@icloud.com"
] | benjamin.barratt@icloud.com |
73053cac6bd7e0a348fe06b9f023ee07feda9469 | 792f2ee67210556f224daf88ef0b9785becadc9b | /AOJ/contest/PakenCamp19Day1-C.cpp | 6954546ee9033caf6a98333ca2992ed16167aa65 | [] | no_license | firiexp/contest_log | e5b345286e7d69ebf2a599d4a81bdb19243ca18d | 6474a7127d3a2fed768ebb62031d5ff30eeeef86 | refs/heads/master | 2021-07-20T01:16:47.869936 | 2020-04-30T03:27:51 | 2020-04-30T03:27:51 | 150,196,219 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 546 | cpp | #include <iostream>
#include <algorithm>
#include <iomanip>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <numeric>
#include <bitset>
#include <cmath>
static const int MOD = 1000000007;
using ll = long long;
using u32 = unsigned;
using u64 = unsigned long long;
using namespace std;
template<class T> constexpr T INF = ::numeric_limits<T>::max()/32*15+208;
int main() {
double a, b, p, q, r;
cin >> a >> b >> p >> q >> r;
printf("%.10lf\n", b+(p*b-q*b+q*a)/(q+r));
return 0;
} | [
"firiexp@PC.localdomain"
] | firiexp@PC.localdomain |
7064dd812f29dd37166a56fe39df3f4913a5f12d | a4dfd629736c667a2204b489b24021a88e5bfc46 | /LeetCode/ReverseInteger.h | 6ba5e83997141c2320f22cc4d32337fa29e77dcf | [] | no_license | djhanove/MechE-to-SWE | 1474444838bf81e688c7e8080df8593d6b09e197 | c91ab9df339b0335d09945895ba0128f8025c3cb | refs/heads/master | 2021-03-26T21:55:43.440428 | 2020-06-28T15:10:10 | 2020-06-28T15:10:10 | 247,753,643 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 319 | h | class Solution {
public:
int reverse(int x) {
int reversed = 0;
while(x)
{
if(INT_MAX/10 < reversed) return 0;
if(INT_MIN/10 > reversed) return 0;
reversed = reversed * 10 + x % 10;
x/=10;
}
return reversed;
}
};
| [
"djhanove@mtu.edu"
] | djhanove@mtu.edu |
5e7a6879351bc6782a48eac58862d6ac763143a0 | 8c2b209d83d457eb0b55822d440007387f2d2a75 | /util/src/Subsystem.cpp | 377fff85d85a3152761c9473325a4b9a7f9f384c | [] | no_license | MayaPosch/Lucid | 491277fdd2edacb8469171292330853d51b35bc6 | 48e7563f59ba125e3d694976fc4d7a8fd47e66bc | refs/heads/master | 2022-09-07T08:03:40.387631 | 2020-06-01T15:33:42 | 2020-06-01T15:33:42 | 266,867,257 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 534 | cpp | //
// Subsystem.cpp
//
// Library: Util
// Package: Application
// Module: Subsystem
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "lucid/Util/Subsystem.h"
namespace Lucid {
namespace Util {
Subsystem::Subsystem()
{
}
Subsystem::~Subsystem()
{
}
void Subsystem::reinitialize(Application& app)
{
uninitialize();
initialize(app);
}
void Subsystem::defineOptions(OptionSet& options)
{
}
} } // namespace Lucid::Util
| [
"maya@nyanko.ws"
] | maya@nyanko.ws |
f78ef41d66b6a9525f32dcbb2699522f643ee64d | b44e47d7941c0299312c20ad2e6cad141aff62f2 | /main.cpp | dd7c5f2645b4c8d6ba7be32ff9979b0a2b27287a | [] | no_license | Ons-zerai/Sending-SCD30-sensor-data-to-a-network-server-via-LoRaWAN-protocol- | 40b65ab0bdefda46ba3b7daebf4364e791a43ffa | b0c72739794b1c7a87a4fdea6558a498b7a91143 | refs/heads/main | 2023-08-16T07:33:47.819271 | 2021-10-22T21:40:12 | 2021-10-22T21:40:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,199 | cpp | /* USER CODE BEGIN Header */
/**
******************************************************************************
* @file lora_app.c
* @author MCD Application Team
* @brief Application of the LRWAN Middleware
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2020 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "platform.h"
#include "Region.h" /* Needed for LORAWAN_DEFAULT_DATA_RATE */
#include "sys_app.h"
#include "lora_app.h"
#include "stm32_seq.h"
#include "stm32_timer.h"
#include "utilities_def.h"
#include "lora_app_version.h"
#include "lorawan_version.h"
#include "subghz_phy_version.h"
#include "lora_info.h"
#include "LmHandler.h"
#include "stm32_lpm.h"
#include "adc_if.h"
#include "sys_conf.h"
#include "CayenneLpp.h"
#include "sys_sensors.h"
/* USER CODE BEGIN Includes */
#include "i2c.h"
#include "co2_sensor.h"
#include <string.h>
#include <stdio.h>
#include "usart_if.h" // to use the VCP TRACE function
/* USER CODE END Includes */
/* External variables ---------------------------------------------------------*/
/* USER CODE BEGIN EV */
uint8_t SCD30_cnt_measurement[8]; // buffer where to stock data to be sent
uint8_t SCD30_mess_data[18]; // buffer where to stock data to be received
uint8_t SCD30_receive[1];
extern I2C_HandleTypeDef hi2c1;
unsigned char SCD30_ready;
float SCD30_co2concentration;
float SCD30_temperature;
float SCD30_humidity ;
unsigned int SCD30_co2_value;
unsigned int SCD30_temperature_temp;
unsigned int SCD30_humidity_temp ;
/* USER CODE END EV */
/* Private typedef -----------------------------------------------------------*/
/**
* @brief LoRa State Machine states
*/
typedef enum TxEventType_e
{
/**
* @brief Appdata Transmission issue based on timer every TxDutyCycleTime
*/
TX_ON_TIMER,
/**
* @brief Appdata Transmission external event plugged on OnSendEvent( )
*/
TX_ON_EVENT
/* USER CODE BEGIN TxEventType_t */
/* USER CODE END TxEventType_t */
} TxEventType_t;
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private function prototypes -----------------------------------------------*/
/**
* @brief LoRa End Node send request
*/
static void SendTxData(void);
/**
* @brief TX timer callback function
* @param context ptr of timer context
*/
static void OnTxTimerEvent(void *context);
/**
* @brief join event callback function
* @param joinParams status of join
*/
static void OnJoinRequest(LmHandlerJoinParams_t *joinParams);
/**
* @brief tx event callback function
* @param params status of last Tx
*/
static void OnTxData(LmHandlerTxParams_t *params);
/**
* @brief callback when LoRa application has received a frame
* @param appData data received in the last Rx
* @param params status of last Rx
*/
static void OnRxData(LmHandlerAppData_t *appData, LmHandlerRxParams_t *params);
/*!
* Will be called each time a Radio IRQ is handled by the MAC layer
*
*/
static void OnMacProcessNotify(void);
/* USER CODE BEGIN PFP */
/**
* @brief LED Tx timer callback function
* @param context ptr of LED context
*/
static void OnTxTimerLedEvent(void *context);
/**
* @brief LED Rx timer callback function
* @param context ptr of LED context
*/
static void OnRxTimerLedEvent(void *context);
/**
* @brief LED Join timer callback function
* @param context ptr of LED context
*/
static void OnJoinTimerLedEvent(void *context);
/* USER CODE END PFP */
/* Private variables ---------------------------------------------------------*/
static ActivationType_t ActivationType = LORAWAN_DEFAULT_ACTIVATION_TYPE;
/**
* @brief LoRaWAN handler Callbacks
*/
static LmHandlerCallbacks_t LmHandlerCallbacks =
{
.GetBatteryLevel = GetBatteryLevel,
.GetTemperature = GetTemperatureLevel,
.GetUniqueId = GetUniqueId,
.GetDevAddr = GetDevAddr,
.OnMacProcess = OnMacProcessNotify,
.OnJoinRequest = OnJoinRequest,
.OnTxData = OnTxData,
.OnRxData = OnRxData
};
/**
* @brief LoRaWAN handler parameters
*/
static LmHandlerParams_t LmHandlerParams =
{
.ActiveRegion = ACTIVE_REGION,
.DefaultClass = LORAWAN_DEFAULT_CLASS,
.AdrEnable = LORAWAN_ADR_STATE,
.TxDatarate = LORAWAN_DEFAULT_DATA_RATE,
.PingPeriodicity = LORAWAN_DEFAULT_PING_SLOT_PERIODICITY
};
/**
* @brief Type of Event to generate application Tx
*/
static TxEventType_t EventType = TX_ON_TIMER;
/**
* @brief Timer to handle the application Tx
*/
static UTIL_TIMER_Object_t TxTimer;
/* USER CODE BEGIN PV */
/**
* @brief User application buffer
*/
static uint8_t AppDataBuffer[LORAWAN_APP_DATA_BUFFER_MAX_SIZE];
/**
* @brief User application data structure
*/
static LmHandlerAppData_t AppData = { 0, 0, AppDataBuffer };
/**
* @brief Specifies the state of the application LED
*/
static uint8_t AppLedStateOn = RESET;
/**
* @brief Timer to handle the application Tx Led to toggle
*/
static UTIL_TIMER_Object_t TxLedTimer;
/**
* @brief Timer to handle the application Rx Led to toggle
*/
static UTIL_TIMER_Object_t RxLedTimer;
/**
* @brief Timer to handle the application Join Led to toggle
*/
static UTIL_TIMER_Object_t JoinLedTimer;
/* USER CODE END PV */
/* Exported functions ---------------------------------------------------------*/
/* USER CODE BEGIN EF */
/* USER CODE END EF */
void LoRaWAN_Init(void)
{
/* USER CODE BEGIN LoRaWAN_Init_1 */
BSP_LED_Init(LED_BLUE);
BSP_LED_Init(LED_GREEN);
BSP_LED_Init(LED_RED);
BSP_PB_Init(BUTTON_SW2, BUTTON_MODE_EXTI);
/* Get LoRa APP version*/
APP_LOG(TS_OFF, VLEVEL_M, "APP_VERSION: V%X.%X.%X\r\n",
(uint8_t)(__LORA_APP_VERSION >> __APP_VERSION_MAIN_SHIFT),
(uint8_t)(__LORA_APP_VERSION >> __APP_VERSION_SUB1_SHIFT),
(uint8_t)(__LORA_APP_VERSION >> __APP_VERSION_SUB2_SHIFT));
/* Get MW LoraWAN info */
APP_LOG(TS_OFF, VLEVEL_M, "MW_LORAWAN_VERSION: V%X.%X.%X\r\n",
(uint8_t)(__LORAWAN_VERSION >> __APP_VERSION_MAIN_SHIFT),
(uint8_t)(__LORAWAN_VERSION >> __APP_VERSION_SUB1_SHIFT),
(uint8_t)(__LORAWAN_VERSION >> __APP_VERSION_SUB2_SHIFT));
/* Get MW SubGhz_Phy info */
APP_LOG(TS_OFF, VLEVEL_M, "MW_RADIO_VERSION: V%X.%X.%X\r\n",
(uint8_t)(__SUBGHZ_PHY_VERSION >> __APP_VERSION_MAIN_SHIFT),
(uint8_t)(__SUBGHZ_PHY_VERSION >> __APP_VERSION_SUB1_SHIFT),
(uint8_t)(__SUBGHZ_PHY_VERSION >> __APP_VERSION_SUB2_SHIFT));
UTIL_TIMER_Create(&TxLedTimer, 0xFFFFFFFFU, UTIL_TIMER_ONESHOT, OnTxTimerLedEvent, NULL);
UTIL_TIMER_Create(&RxLedTimer, 0xFFFFFFFFU, UTIL_TIMER_ONESHOT, OnRxTimerLedEvent, NULL);
UTIL_TIMER_Create(&JoinLedTimer, 0xFFFFFFFFU, UTIL_TIMER_PERIODIC, OnJoinTimerLedEvent, NULL);
UTIL_TIMER_SetPeriod(&TxLedTimer, 500);
UTIL_TIMER_SetPeriod(&RxLedTimer, 500);
UTIL_TIMER_SetPeriod(&JoinLedTimer, 500);
/* USER CODE END LoRaWAN_Init_1 */
UTIL_SEQ_RegTask((1 << CFG_SEQ_Task_LmHandlerProcess), UTIL_SEQ_RFU, LmHandlerProcess);
UTIL_SEQ_RegTask((1 << CFG_SEQ_Task_LoRaSendOnTxTimerOrButtonEvent), UTIL_SEQ_RFU, SendTxData);
/* Init Info table used by LmHandler*/
LoraInfo_Init();
/* Init the Lora Stack*/
LmHandlerInit(&LmHandlerCallbacks);
LmHandlerConfigure(&LmHandlerParams);
/* USER CODE BEGIN LoRaWAN_Init_2 */
UTIL_TIMER_Start(&JoinLedTimer);
/* USER CODE END LoRaWAN_Init_2 */
LmHandlerJoin(ActivationType);
if (EventType == TX_ON_TIMER)
{
/* send every time timer elapses */
UTIL_TIMER_Create(&TxTimer, 0xFFFFFFFFU, UTIL_TIMER_ONESHOT, OnTxTimerEvent, NULL);
UTIL_TIMER_SetPeriod(&TxTimer, APP_TX_DUTYCYCLE);
UTIL_TIMER_Start(&TxTimer);
}
else
{
/* USER CODE BEGIN LoRaWAN_Init_3 */
/* send every time button is pushed */
BSP_PB_Init(BUTTON_SW1, BUTTON_MODE_EXTI);
/* USER CODE END LoRaWAN_Init_3 */
}
/* USER CODE BEGIN LoRaWAN_Init_Last */
/* USER CODE END LoRaWAN_Init_Last */
}
/* USER CODE BEGIN PB_Callbacks */
/* Note: Current the stm32wlxx_it.c generated by STM32CubeMX does not support BSP for PB in EXTI mode. */
/* In order to get a push button IRS by code automatically generated */
/* HAL_GPIO_EXTI_Callback is today the only available possibility. */
/* Using HAL_GPIO_EXTI_Callback() shortcuts the BSP. */
/* If users wants to go through the BSP, stm32wlxx_it.c should be updated */
/* in the USER CODE SESSION of the correspondent EXTIn_IRQHandler() */
/* to call the BSP_PB_IRQHandler() or the HAL_EXTI_IRQHandler(&H_EXTI_n);. */
/* Then the below HAL_GPIO_EXTI_Callback() can be replaced by BSP callback */
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
switch (GPIO_Pin)
{
case BUTTON_SW1_PIN:
/* Note: when "EventType == TX_ON_TIMER" this GPIO is not initialized */
UTIL_SEQ_SetTask((1 << CFG_SEQ_Task_LoRaSendOnTxTimerOrButtonEvent), CFG_SEQ_Prio_0);
break;
case BUTTON_SW2_PIN:
break;
case BUTTON_SW3_PIN:
break;
default:
break;
}
}
/* USER CODE END PB_Callbacks */
/* Private functions ---------------------------------------------------------*/
/* USER CODE BEGIN PrFD */
/* USER CODE END PrFD */
static void OnRxData(LmHandlerAppData_t *appData, LmHandlerRxParams_t *params)
{
/* USER CODE BEGIN OnRxData_1 */
if ((appData != NULL) || (params != NULL))
{
BSP_LED_On(LED_BLUE) ;
UTIL_TIMER_Start(&RxLedTimer);
static const char *slotStrings[] = { "1", "2", "C", "C Multicast", "B Ping-Slot", "B Multicast Ping-Slot" };
APP_LOG(TS_OFF, VLEVEL_M, "\r\n###### ========== MCPS-Indication ==========\r\n");
APP_LOG(TS_OFF, VLEVEL_H, "###### D/L FRAME:%04d | SLOT:%s | PORT:%d | DR:%d | RSSI:%d | SNR:%d\r\n",
params->DownlinkCounter, slotStrings[params->RxSlot], appData->Port, params->Datarate, params->Rssi, params->Snr);
switch (appData->Port)
{
case LORAWAN_SWITCH_CLASS_PORT:
/*this port switches the class*/
if (appData->BufferSize == 1)
{
switch (appData->Buffer[0])
{
case 0:
{
LmHandlerRequestClass(CLASS_A);
break;
}
case 1:
{
LmHandlerRequestClass(CLASS_B);
break;
}
case 2:
{
LmHandlerRequestClass(CLASS_C);
break;
}
default:
break;
}
}
break;
case LORAWAN_USER_APP_PORT:
if (appData->BufferSize == 1)
{
AppLedStateOn = appData->Buffer[0] & 0x01;
if (AppLedStateOn == RESET)
{
APP_LOG(TS_OFF, VLEVEL_H, "LED OFF\r\n");
BSP_LED_Off(LED_RED) ;
}
else
{
APP_LOG(TS_OFF, VLEVEL_H, "LED ON\r\n");
BSP_LED_On(LED_RED) ;
}
}
break;
default:
break;
}
}
/* USER CODE END OnRxData_1 */
}
static void SendTxData(void)
{
/*USER CODE BEGIN SendTxData_1 */
UTIL_TIMER_Time_t nextTxIn = 0;
// uint16_t humidity = 0; //added by ons
#ifdef CAYENNE_LPP
uint8_t channel = 0;
#else
uint16_t humidity = 0;
uint32_t i = 0;
int32_t latitude = 0;
int32_t longitude = 0;
uint16_t altitudeGps = 0;
#endif /* CAYENNE_LPP */
/**** Start measurement ****/
SCD30_cnt_measurement[0]=0x00;
SCD30_cnt_measurement[1]=0x10;
SCD30_cnt_measurement[2]=0x00;
SCD30_cnt_measurement[3]=0x00;
SCD30_cnt_measurement[4]=0x81;
HAL_I2C_Master_Transmit(&hi2c1,sensor_address, SCD30_cnt_measurement,5,1000);
/***************************** Get ready Status***********************/
/***** It is essential to know when we can have data to read **********/
SCD30_cnt_measurement[0]=0x02;
SCD30_cnt_measurement[1]=0x02;
if (HAL_I2C_Master_Transmit(&hi2c1,sensor_address, SCD30_cnt_measurement,2,HAL_MAX_DELAY)== HAL_OK)
{
HAL_I2C_Master_Receive(&hi2c1
,sensor_address_read, SCD30_receive,3,100);
SCD30_ready = SCD30_receive[1];
}
/*************** Read and display measured data ( CO2 values in PPM, Temperature in degree C and Humidity ) ******************/
SCD30_cnt_measurement[0]=0x03;
SCD30_cnt_measurement[1]=0x00;
if ( SCD30_ready == 0x01 )
{ //always check if measurement is ready
HAL_I2C_Master_Transmit(&hi2c1,sensor_address, SCD30_cnt_measurement,2,1000);
HAL_I2C_Master_Receive(&hi2c1,sensor_address_read, SCD30_mess_data,18,100);
// cast 4 bytes to one unsigned 32 bit integer
SCD30_co2_value = (unsigned int)((((unsigned int) SCD30_mess_data[0]) << 24)|
(((unsigned int) SCD30_mess_data[1]) << 16) |
(((unsigned int) SCD30_mess_data[3]) << 8) |
((unsigned int) SCD30_mess_data[4]));
// cast unsigned 32 bit integer to 32 bit float
SCD30_co2concentration= *(float*)& SCD30_co2_value;
// cast 4 bytes to one unsigned 32 bit integer
SCD30_temperature_temp = (unsigned int)((((unsigned int) SCD30_mess_data[6]) << 24)|
(((unsigned int) SCD30_mess_data[7]) << 16) |
(((unsigned int) SCD30_mess_data[9]) << 8) |
((unsigned int) SCD30_mess_data[10]));
SCD30_temperature = *(float*)& SCD30_temperature_temp;
// cast 4 bytes to one unsigned 32 bit integer
SCD30_humidity_temp = (unsigned int)((((unsigned int) SCD30_mess_data[12]) << 24)|
(((unsigned int) SCD30_mess_data[13]) << 16) |
(((unsigned int) SCD30_mess_data[15]) << 8) |
((unsigned int) SCD30_mess_data[16]));
// cast unsigned 32 bit integer to 32 bit float
SCD30_humidity = *(float*)& SCD30_humidity_temp;
// convert the content of SCD30_co2concentration/SCD30_temperature/ SCD30_humidity to string and put it in the buffer SCD30_mess_data, this conversion is needed for Vcom trace function
sprintf((char*) SCD30_mess_data,"%u PPM\r\n",
((unsigned int) SCD30_co2concentration));
// Display the current Co2 measurement in PPM ( Part per Million)
vcom_Trace(SCD30_mess_data,strlen((char*) SCD30_mess_data));
// convert the content of SCSCD30_temperature to string and put it in the buffer SCD30_mess_data, this conversion is needed for Vcom trace function
sprintf((char*) SCD30_mess_data,"%u C\r\n",
((unsigned int)SCD30_temperature));
// Display the current Temperature measurement
vcom_Trace(SCD30_mess_data,strlen((char*) SCD30_mess_data));
// convert the content of SCD30_humidity to string and put it in the buffer SCD30_mess_data, this conversion is needed for Vcom trace function
sprintf((char*) SCD30_mess_data,"%u H\r\n",
((unsigned int) SCD30_humidity));
// Display the current Humidity measurement
vcom_Trace( SCD30_mess_data,strlen((char*) SCD30_mess_data));
}
AppData.Port = LORAWAN_USER_APP_PORT;
#ifdef CAYENNE_LPP
CayenneLppReset();
CayenneLppAddBarometricPressure(channel++, pressure);
CayenneLppAddTemperature(channel++, temperature);
CayenneLppAddRelativeHumidity(channel++, (uint16_t)(sensor_data.humidity));
if ((LmHandlerParams.ActiveRegion != LORAMAC_REGION_US915) && (LmHandlerParams.ActiveRegion != LORAMAC_REGION_AU915)
&& (LmHandlerParams.ActiveRegion != LORAMAC_REGION_AS923))
{
CayenneLppAddDigitalInput(channel++, GetBatteryLevel());
CayenneLppAddDigitalOutput(channel++, AppLedStateOn);
}
CayenneLppCopy(AppData.Buffer);
AppData.BufferSize = CayenneLppGetSize();
#else /* not CAYENNE_LPP */
// humidity = (uint16_t)(sensor_data.humidity * 10); /* in %*10 */
AppData.Buffer[i++] = AppLedStateOn;
AppData.Buffer[i++] = (uint8_t)((SCD30_co2_value>> 8) & 0xFF);
AppData.Buffer[i++] = (uint8_t)(SCD30_co2_value & 0xFF);
AppData.Buffer[i++] = (uint8_t)(SCD30_temperature_temp & 0xFF);
AppData.Buffer[i++] = (uint8_t)((SCD30_humidity_temp >> 8) & 0xFF);
AppData.Buffer[i++] = (uint8_t)(SCD30_humidity_temp & 0xFF);
if ((LmHandlerParams.ActiveRegion == LORAMAC_REGION_US915) || (LmHandlerParams.ActiveRegion == LORAMAC_REGION_AU915)
|| (LmHandlerParams.ActiveRegion == LORAMAC_REGION_AS923))
{
AppData.Buffer[i++] = 0;
AppData.Buffer[i++] = 0;
AppData.Buffer[i++] = 0;
AppData.Buffer[i++] = 0;
}
else
{
//latitude = sensor_data.latitude;
//longitude = sensor_data.longitude;
AppData.Buffer[i++] = GetBatteryLevel(); /* 1 (very low) to 254 (fully charged) */
AppData.Buffer[i++] = (uint8_t)((latitude >> 16) & 0xFF);
AppData.Buffer[i++] = (uint8_t)((latitude >> 8) & 0xFF);
AppData.Buffer[i++] = (uint8_t)(latitude & 0xFF);
AppData.Buffer[i++] = (uint8_t)((longitude >> 16) & 0xFF);
AppData.Buffer[i++] = (uint8_t)((longitude >> 8) & 0xFF);
AppData.Buffer[i++] = (uint8_t)(longitude & 0xFF);
AppData.Buffer[i++] = (uint8_t)((altitudeGps >> 8) & 0xFF);
AppData.Buffer[i++] = (uint8_t)(altitudeGps & 0xFF);
}
AppData.BufferSize = i;
#endif /* CAYENNE_LPP */
if (LORAMAC_HANDLER_SUCCESS == LmHandlerSend(&AppData, LORAWAN_DEFAULT_CONFIRMED_MSG_STATE, &nextTxIn, false))
{
APP_LOG(TS_ON, VLEVEL_L, "SEND REQUEST\r\n");
}
else if (nextTxIn > 0)
{
APP_LOG(TS_ON, VLEVEL_L, "Next Tx in : ~%d second(s)\r\n", (nextTxIn / 1000));
}
/* USER CODE END SendTxData_1 */
}
static void OnTxTimerEvent(void *context)
{
/* USER CODE BEGIN OnTxTimerEvent_1 */
/* USER CODE END OnTxTimerEvent_1 */
UTIL_SEQ_SetTask((1 << CFG_SEQ_Task_LoRaSendOnTxTimerOrButtonEvent), CFG_SEQ_Prio_0);
/*Wait for next tx slot*/
UTIL_TIMER_Start(&TxTimer);
/* USER CODE BEGIN OnTxTimerEvent_2 */
/* USER CODE END OnTxTimerEvent_2 */
}
/* USER CODE BEGIN PrFD_LedEvents */
static void OnTxTimerLedEvent(void *context)
{
BSP_LED_Off(LED_GREEN) ;
}
static void OnRxTimerLedEvent(void *context)
{
BSP_LED_Off(LED_BLUE) ;
}
static void OnJoinTimerLedEvent(void *context)
{
BSP_LED_Toggle(LED_RED) ;
}
/* USER CODE END PrFD_LedEvents */
static void OnTxData(LmHandlerTxParams_t *params)
{
/* USER CODE BEGIN OnTxData_1 */
if ((params != NULL))
{
/* Process Tx event only if its a mcps response to prevent some internal events (mlme) */
if (params->IsMcpsConfirm != 0)
{
BSP_LED_On(LED_GREEN) ;
UTIL_TIMER_Start(&TxLedTimer);
APP_LOG(TS_OFF, VLEVEL_M, "\r\n###### ========== MCPS-Confirm =============\r\n");
APP_LOG(TS_OFF, VLEVEL_H, "###### U/L FRAME:%04d | PORT:%d | DR:%d | PWR:%d", params->UplinkCounter,
params->AppData.Port, params->Datarate, params->TxPower);
APP_LOG(TS_OFF, VLEVEL_H, " | MSG TYPE:");
if (params->MsgType == LORAMAC_HANDLER_CONFIRMED_MSG)
{
APP_LOG(TS_OFF, VLEVEL_H, "CONFIRMED [%s]\r\n", (params->AckReceived != 0) ? "ACK" : "NACK");
}
else
{
APP_LOG(TS_OFF, VLEVEL_H, "UNCONFIRMED\r\n");
}
}
}
/* USER CODE END OnTxData_1 */
}
static void OnJoinRequest(LmHandlerJoinParams_t *joinParams)
{
/* USER CODE BEGIN OnJoinRequest_1 */
if (joinParams != NULL)
{
if (joinParams->Status == LORAMAC_HANDLER_SUCCESS)
{
UTIL_TIMER_Stop(&JoinLedTimer);
BSP_LED_Off(LED_RED) ;
APP_LOG(TS_OFF, VLEVEL_M, "\r\n###### = JOINED = ");
if (joinParams->Mode == ACTIVATION_TYPE_ABP)
{
APP_LOG(TS_OFF, VLEVEL_M, "ABP ======================\r\n");
}
else
{
APP_LOG(TS_OFF, VLEVEL_M, "OTAA =====================\r\n");
}
}
else
{
APP_LOG(TS_OFF, VLEVEL_M, "\r\n###### = JOIN FAILED\r\n");
}
}
/* USER CODE END OnJoinRequest_1 */
}
static void OnMacProcessNotify(void)
{
/* USER CODE BEGIN OnMacProcessNotify_1 */
/* USER CODE END OnMacProcessNotify_1 */
UTIL_SEQ_SetTask((1 << CFG_SEQ_Task_LmHandlerProcess), CFG_SEQ_Prio_0);
/* USER CODE BEGIN OnMacProcessNotify_2 */
/* USER CODE END OnMacProcessNotify_2 */
}
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| [
"noreply@github.com"
] | noreply@github.com |
61bd8d37bc2f2d8289013bbba58a0aab56b01b16 | fc51d373fb5f6bf772023b8e1959bcd0818b928d | /juce_libsamplerate/src_wrappers/libsamplerate_SRC.h | e0b607e8f7e92483d3753ed402a28dd9c8ee3c50 | [
"BSD-2-Clause"
] | permissive | talaviram/juce_libsamplerate | a572724a61012e7f91c8c9dfb3b87b042b22183b | 5d6c8a48636e84f38333e341d315551342a90f76 | refs/heads/master | 2020-06-26T07:50:43.548721 | 2019-08-17T13:07:43 | 2019-08-17T13:07:43 | 199,576,434 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,512 | h | /*
==============================================================================
Copyright (c) 2019, Tal Aviram
All rights reserved.
This code is released under 2-clause BSD license. Please see the
file at : https://github.com/talaviram/juce_libsamplerate/blob/master/COPYING
==============================================================================
*/
/**
Frontend for libsamplerate needed API to be used with JUCE
@see ResamplingAudioSource
@tags{Audio}
*/
#pragma once
namespace libsamplerate
{
#include "samplerate.h"
class SRC
{
public:
enum ResamplerQuality
{
SRC_SINC_BEST_QUALITY = libsamplerate::SRC_SINC_BEST_QUALITY,
SRC_SINC_MEDIUM_QUALITY = libsamplerate::SRC_SINC_MEDIUM_QUALITY,
SRC_SINC_FASTEST = libsamplerate::SRC_SINC_FASTEST,
SRC_ZERO_ORDER_HOLD = libsamplerate::SRC_ZERO_ORDER_HOLD,
SRC_LINEAR = libsamplerate::SRC_LINEAR
};
//==============================================================================
/** Resamples an audio buffer.
Important Note: This callback is not designed to work on small chunks of a larger piece of audio. If you attempt to use it this way you are doing it wrong and will not get the results you want.
@see SRCAudioSource
*/
static int resample (const juce::AudioBuffer<float>& bufferToResample, juce::AudioBuffer<float>& outputBuffer, double samplesInPerOutputSample, ResamplerQuality converter_type);
};
}
| [
"me@talaviram.com"
] | me@talaviram.com |
1aa1ef581ca946cb1ab9d5814b1d2efedcd20a9b | 948f4e13af6b3014582909cc6d762606f2a43365 | /testcases/juliet_test_suite/testcases/CWE124_Buffer_Underwrite/s03/CWE124_Buffer_Underwrite__new_wchar_t_loop_82.h | 17e9f0b3b9469b344068b2fc9fe49cdadbfb76f7 | [] | no_license | junxzm1990/ASAN-- | 0056a341b8537142e10373c8417f27d7825ad89b | ca96e46422407a55bed4aa551a6ad28ec1eeef4e | refs/heads/master | 2022-08-02T15:38:56.286555 | 2022-06-16T22:19:54 | 2022-06-16T22:19:54 | 408,238,453 | 74 | 13 | null | 2022-06-16T22:19:55 | 2021-09-19T21:14:59 | null | UTF-8 | C++ | false | false | 1,270 | h | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE124_Buffer_Underwrite__new_wchar_t_loop_82.h
Label Definition File: CWE124_Buffer_Underwrite__new.label.xml
Template File: sources-sink-82.tmpl.h
*/
/*
* @description
* CWE: 124 Buffer Underwrite
* BadSource: Set data pointer to before the allocated memory buffer
* GoodSource: Set data pointer to the allocated memory buffer
* Sinks: loop
* BadSink : Copy string to data using a loop
* Flow Variant: 82 Data flow: data passed in a parameter to a virtual method called via a pointer
*
* */
#include "std_testcase.h"
#include <wchar.h>
namespace CWE124_Buffer_Underwrite__new_wchar_t_loop_82
{
class CWE124_Buffer_Underwrite__new_wchar_t_loop_82_base
{
public:
/* pure virtual function */
virtual void action(wchar_t * data) = 0;
};
#ifndef OMITBAD
class CWE124_Buffer_Underwrite__new_wchar_t_loop_82_bad : public CWE124_Buffer_Underwrite__new_wchar_t_loop_82_base
{
public:
void action(wchar_t * data);
};
#endif /* OMITBAD */
#ifndef OMITGOOD
class CWE124_Buffer_Underwrite__new_wchar_t_loop_82_goodG2B : public CWE124_Buffer_Underwrite__new_wchar_t_loop_82_base
{
public:
void action(wchar_t * data);
};
#endif /* OMITGOOD */
}
| [
"yzhang0701@gmail.com"
] | yzhang0701@gmail.com |
777c96b5ad109d1f27e2db7b2acafa8ef8c60289 | 9a1a0b47b59e55e3f2043ad32d5d58455e69425d | /0607/ficheros/numeros.cpp | 44a0cb7338f30f93cac0a6cd3e83fb6c845e2bfa | [] | no_license | piranna/asi-iesenlaces | dcabc0213791c04a8b6b4ccb850d5bda78292ae1 | cf35cbea732065e09a58604a93538a9b9dca875f | refs/heads/master | 2016-08-06T05:09:44.270637 | 2008-06-15T09:00:27 | 2008-06-15T09:00:27 | 32,416,588 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,096 | cpp | // $Id$
// ficheros de enteros
#include <stdio.h>
#include <stdlib.h>
void creaFichero(char *nombre)
{
int i;
FILE * f;
f = fopen(nombre, "w");
if ( f == NULL)
{
perror("fopen");
exit(1);
system("pause"); // Detiene la consola
}
for (i=1; i<1001; i++)
fprintf(f, "%d ", i);
fclose(f);
}
void leeFichero(char *nombre)
{
int i;
FILE * f;
f = fopen(nombre, "r");
if ( f == NULL)
{
perror("fopen");
exit(1);
system("pause"); // Detiene la consola
}
fscanf(f, "%d", &i);
while (! feof(f) )
{
printf("%d\n", i);
fscanf(f, "%d", &i);
}
}
void escribeBinario(char *origen, char *destino)
// escribe en binario el contenido de origen (texto)
{
int i; // para almacenar los enteros que leemos del fichero
FILE * fin, *fout;
fin = fopen(origen, "r");
if ( fin == NULL)
{
perror("fopen");
exit(1);
system("pause"); // Detiene la consola
}
fout = fopen(destino, "wb");
if ( fout == NULL)
{
perror("fopen");
exit(1);
system("pause"); // Detiene la consola
}
fscanf(fin, "%d", &i);
while (! feof(fin) )
{
fwrite(&i, sizeof(i), 1, fout);
fscanf(fin, "%d", &i);
}
fclose(fin);
fclose(fout);
}
void leeBinario(char *nombre)
{
int i; // para almacenar los enteros que leemos del fichero
FILE * fin;
fin = fopen(nombre, "rb");
if ( fin == NULL)
{
perror("fopen");
exit(1);
system("pause"); // Detiene la consola
}
while (fread(&i, sizeof(int), 1, fin))
printf("%d ", i);
fclose(fin);
}
int main(void)
{
creaFichero("numeros.txt");
leeFichero("numeros.txt");
escribeBinario("numeros.txt", "numeros.dat");
leeBinario("numeros.dat");
system("pause"); // Detiene la consola
}
| [
"morillas@f86dea77-7e2e-0410-97ea-a74e350978e6"
] | morillas@f86dea77-7e2e-0410-97ea-a74e350978e6 |
59fc25a3a5bd3de49f1cabea18a47a9e71c8314d | dfb4cb8d916b62d7272ca353302d1ad95e4d7244 | /src/test/univalue_tests.cpp | af903cc2a0bc2d14c3c30889bf3fd09427974245 | [
"MIT"
] | permissive | mirzaei-ce/core-shahbit | d166ab47067bf66c3015c3da49ff31cd29f843db | 57ad738667b3d458c92d94aee713c184d911c537 | refs/heads/master | 2021-07-21T11:09:22.493418 | 2017-10-25T13:50:55 | 2017-10-25T13:50:55 | 108,276,937 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,501 | cpp | // Copyright 2014 BitPay, Inc.
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <stdint.h>
#include <vector>
#include <string>
#include <map>
#include <univalue.h>
#include "test/test_shahbit.h"
#include <boost/test/unit_test.hpp>
using namespace std;
BOOST_FIXTURE_TEST_SUITE(univalue_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(univalue_constructor)
{
UniValue v1;
BOOST_CHECK(v1.isNull());
UniValue v2(UniValue::VSTR);
BOOST_CHECK(v2.isStr());
UniValue v3(UniValue::VSTR, "foo");
BOOST_CHECK(v3.isStr());
BOOST_CHECK_EQUAL(v3.getValStr(), "foo");
UniValue numTest;
BOOST_CHECK(numTest.setNumStr("82"));
BOOST_CHECK(numTest.isNum());
BOOST_CHECK_EQUAL(numTest.getValStr(), "82");
uint64_t vu64 = 82;
UniValue v4(vu64);
BOOST_CHECK(v4.isNum());
BOOST_CHECK_EQUAL(v4.getValStr(), "82");
int64_t vi64 = -82;
UniValue v5(vi64);
BOOST_CHECK(v5.isNum());
BOOST_CHECK_EQUAL(v5.getValStr(), "-82");
int vi = -688;
UniValue v6(vi);
BOOST_CHECK(v6.isNum());
BOOST_CHECK_EQUAL(v6.getValStr(), "-688");
double vd = -7.21;
UniValue v7(vd);
BOOST_CHECK(v7.isNum());
BOOST_CHECK_EQUAL(v7.getValStr(), "-7.21");
string vs("yawn");
UniValue v8(vs);
BOOST_CHECK(v8.isStr());
BOOST_CHECK_EQUAL(v8.getValStr(), "yawn");
const char *vcs = "zappa";
UniValue v9(vcs);
BOOST_CHECK(v9.isStr());
BOOST_CHECK_EQUAL(v9.getValStr(), "zappa");
}
BOOST_AUTO_TEST_CASE(univalue_typecheck)
{
UniValue v1;
BOOST_CHECK(v1.setNumStr("1"));
BOOST_CHECK(v1.isNum());
BOOST_CHECK_THROW(v1.get_bool(), runtime_error);
UniValue v2;
BOOST_CHECK(v2.setBool(true));
BOOST_CHECK_EQUAL(v2.get_bool(), true);
BOOST_CHECK_THROW(v2.get_int(), runtime_error);
UniValue v3;
BOOST_CHECK(v3.setNumStr("32482348723847471234"));
BOOST_CHECK_THROW(v3.get_int64(), runtime_error);
BOOST_CHECK(v3.setNumStr("1000"));
BOOST_CHECK_EQUAL(v3.get_int64(), 1000);
UniValue v4;
BOOST_CHECK(v4.setNumStr("2147483648"));
BOOST_CHECK_EQUAL(v4.get_int64(), 2147483648);
BOOST_CHECK_THROW(v4.get_int(), runtime_error);
BOOST_CHECK(v4.setNumStr("1000"));
BOOST_CHECK_EQUAL(v4.get_int(), 1000);
BOOST_CHECK_THROW(v4.get_str(), runtime_error);
BOOST_CHECK_EQUAL(v4.get_real(), 1000);
BOOST_CHECK_THROW(v4.get_array(), runtime_error);
BOOST_CHECK_THROW(v4.getKeys(), runtime_error);
BOOST_CHECK_THROW(v4.getValues(), runtime_error);
BOOST_CHECK_THROW(v4.get_obj(), runtime_error);
UniValue v5;
BOOST_CHECK(v5.read("[true, 10]"));
BOOST_CHECK_NO_THROW(v5.get_array());
std::vector<UniValue> vals = v5.getValues();
BOOST_CHECK_THROW(vals[0].get_int(), runtime_error);
BOOST_CHECK_EQUAL(vals[0].get_bool(), true);
BOOST_CHECK_EQUAL(vals[1].get_int(), 10);
BOOST_CHECK_THROW(vals[1].get_bool(), runtime_error);
}
BOOST_AUTO_TEST_CASE(univalue_set)
{
UniValue v(UniValue::VSTR, "foo");
v.clear();
BOOST_CHECK(v.isNull());
BOOST_CHECK_EQUAL(v.getValStr(), "");
BOOST_CHECK(v.setObject());
BOOST_CHECK(v.isObject());
BOOST_CHECK_EQUAL(v.size(), 0);
BOOST_CHECK_EQUAL(v.getType(), UniValue::VOBJ);
BOOST_CHECK(v.empty());
BOOST_CHECK(v.setArray());
BOOST_CHECK(v.isArray());
BOOST_CHECK_EQUAL(v.size(), 0);
BOOST_CHECK(v.setStr("zum"));
BOOST_CHECK(v.isStr());
BOOST_CHECK_EQUAL(v.getValStr(), "zum");
BOOST_CHECK(v.setFloat(-1.01));
BOOST_CHECK(v.isNum());
BOOST_CHECK_EQUAL(v.getValStr(), "-1.01");
BOOST_CHECK(v.setInt((int)1023));
BOOST_CHECK(v.isNum());
BOOST_CHECK_EQUAL(v.getValStr(), "1023");
BOOST_CHECK(v.setInt((int64_t)-1023LL));
BOOST_CHECK(v.isNum());
BOOST_CHECK_EQUAL(v.getValStr(), "-1023");
BOOST_CHECK(v.setInt((uint64_t)1023ULL));
BOOST_CHECK(v.isNum());
BOOST_CHECK_EQUAL(v.getValStr(), "1023");
BOOST_CHECK(v.setNumStr("-688"));
BOOST_CHECK(v.isNum());
BOOST_CHECK_EQUAL(v.getValStr(), "-688");
BOOST_CHECK(v.setBool(false));
BOOST_CHECK_EQUAL(v.isBool(), true);
BOOST_CHECK_EQUAL(v.isTrue(), false);
BOOST_CHECK_EQUAL(v.isFalse(), true);
BOOST_CHECK_EQUAL(v.getBool(), false);
BOOST_CHECK(v.setBool(true));
BOOST_CHECK_EQUAL(v.isBool(), true);
BOOST_CHECK_EQUAL(v.isTrue(), true);
BOOST_CHECK_EQUAL(v.isFalse(), false);
BOOST_CHECK_EQUAL(v.getBool(), true);
BOOST_CHECK(!v.setNumStr("zombocom"));
BOOST_CHECK(v.setNull());
BOOST_CHECK(v.isNull());
}
BOOST_AUTO_TEST_CASE(univalue_array)
{
UniValue arr(UniValue::VARR);
UniValue v((int64_t)1023LL);
BOOST_CHECK(arr.push_back(v));
string vStr("zippy");
BOOST_CHECK(arr.push_back(vStr));
const char *s = "pippy";
BOOST_CHECK(arr.push_back(s));
vector<UniValue> vec;
v.setStr("boing");
vec.push_back(v);
v.setStr("going");
vec.push_back(v);
BOOST_CHECK(arr.push_backV(vec));
BOOST_CHECK_EQUAL(arr.empty(), false);
BOOST_CHECK_EQUAL(arr.size(), 5);
BOOST_CHECK_EQUAL(arr[0].getValStr(), "1023");
BOOST_CHECK_EQUAL(arr[1].getValStr(), "zippy");
BOOST_CHECK_EQUAL(arr[2].getValStr(), "pippy");
BOOST_CHECK_EQUAL(arr[3].getValStr(), "boing");
BOOST_CHECK_EQUAL(arr[4].getValStr(), "going");
BOOST_CHECK_EQUAL(arr[999].getValStr(), "");
arr.clear();
BOOST_CHECK(arr.empty());
BOOST_CHECK_EQUAL(arr.size(), 0);
}
BOOST_AUTO_TEST_CASE(univalue_object)
{
UniValue obj(UniValue::VOBJ);
string strKey, strVal;
UniValue v;
strKey = "age";
v.setInt(100);
BOOST_CHECK(obj.pushKV(strKey, v));
strKey = "first";
strVal = "John";
BOOST_CHECK(obj.pushKV(strKey, strVal));
strKey = "last";
const char *cVal = "Smith";
BOOST_CHECK(obj.pushKV(strKey, cVal));
strKey = "distance";
BOOST_CHECK(obj.pushKV(strKey, (int64_t) 25));
strKey = "time";
BOOST_CHECK(obj.pushKV(strKey, (uint64_t) 3600));
strKey = "calories";
BOOST_CHECK(obj.pushKV(strKey, (int) 12));
strKey = "temperature";
BOOST_CHECK(obj.pushKV(strKey, (double) 90.012));
UniValue obj2(UniValue::VOBJ);
BOOST_CHECK(obj2.pushKV("cat1", 9000));
BOOST_CHECK(obj2.pushKV("cat2", 12345));
BOOST_CHECK(obj.pushKVs(obj2));
BOOST_CHECK_EQUAL(obj.empty(), false);
BOOST_CHECK_EQUAL(obj.size(), 9);
BOOST_CHECK_EQUAL(obj["age"].getValStr(), "100");
BOOST_CHECK_EQUAL(obj["first"].getValStr(), "John");
BOOST_CHECK_EQUAL(obj["last"].getValStr(), "Smith");
BOOST_CHECK_EQUAL(obj["distance"].getValStr(), "25");
BOOST_CHECK_EQUAL(obj["time"].getValStr(), "3600");
BOOST_CHECK_EQUAL(obj["calories"].getValStr(), "12");
BOOST_CHECK_EQUAL(obj["temperature"].getValStr(), "90.012");
BOOST_CHECK_EQUAL(obj["cat1"].getValStr(), "9000");
BOOST_CHECK_EQUAL(obj["cat2"].getValStr(), "12345");
BOOST_CHECK_EQUAL(obj["nyuknyuknyuk"].getValStr(), "");
BOOST_CHECK(obj.exists("age"));
BOOST_CHECK(obj.exists("first"));
BOOST_CHECK(obj.exists("last"));
BOOST_CHECK(obj.exists("distance"));
BOOST_CHECK(obj.exists("time"));
BOOST_CHECK(obj.exists("calories"));
BOOST_CHECK(obj.exists("temperature"));
BOOST_CHECK(obj.exists("cat1"));
BOOST_CHECK(obj.exists("cat2"));
BOOST_CHECK(!obj.exists("nyuknyuknyuk"));
map<string, UniValue::VType> objTypes;
objTypes["age"] = UniValue::VNUM;
objTypes["first"] = UniValue::VSTR;
objTypes["last"] = UniValue::VSTR;
objTypes["distance"] = UniValue::VNUM;
objTypes["time"] = UniValue::VNUM;
objTypes["calories"] = UniValue::VNUM;
objTypes["temperature"] = UniValue::VNUM;
objTypes["cat1"] = UniValue::VNUM;
objTypes["cat2"] = UniValue::VNUM;
BOOST_CHECK(obj.checkObject(objTypes));
objTypes["cat2"] = UniValue::VSTR;
BOOST_CHECK(!obj.checkObject(objTypes));
obj.clear();
BOOST_CHECK(obj.empty());
BOOST_CHECK_EQUAL(obj.size(), 0);
}
static const char *json1 =
"[1.10000000,{\"key1\":\"str\\u0000\",\"key2\":800,\"key3\":{\"name\":\"martian http://test.com\"}}]";
BOOST_AUTO_TEST_CASE(univalue_readwrite)
{
UniValue v;
BOOST_CHECK(v.read(json1));
string strJson1(json1);
BOOST_CHECK(v.read(strJson1));
BOOST_CHECK(v.isArray());
BOOST_CHECK_EQUAL(v.size(), 2);
BOOST_CHECK_EQUAL(v[0].getValStr(), "1.10000000");
UniValue obj = v[1];
BOOST_CHECK(obj.isObject());
BOOST_CHECK_EQUAL(obj.size(), 3);
BOOST_CHECK(obj["key1"].isStr());
std::string correctValue("str");
correctValue.push_back('\0');
BOOST_CHECK_EQUAL(obj["key1"].getValStr(), correctValue);
BOOST_CHECK(obj["key2"].isNum());
BOOST_CHECK_EQUAL(obj["key2"].getValStr(), "800");
BOOST_CHECK(obj["key3"].isObject());
BOOST_CHECK_EQUAL(strJson1, v.write());
/* Check for (correctly reporting) a parsing error if the initial
JSON construct is followed by more stuff. Note that whitespace
is, of course, exempt. */
BOOST_CHECK(v.read(" {}\n "));
BOOST_CHECK(v.isObject());
BOOST_CHECK(v.read(" []\n "));
BOOST_CHECK(v.isArray());
BOOST_CHECK(!v.read("@{}"));
BOOST_CHECK(!v.read("{} garbage"));
BOOST_CHECK(!v.read("[]{}"));
BOOST_CHECK(!v.read("{}[]"));
BOOST_CHECK(!v.read("{} 42"));
}
BOOST_AUTO_TEST_SUITE_END()
| [
"mirzaei@ce.sharif.edu"
] | mirzaei@ce.sharif.edu |
44324e3056ef8f13282dd8602dd07825ccfb6882 | b87556def7b2308ecee1f2f6837aafdea995b681 | /source/cGameStatePlay.cpp | 89ac413cbe281039a20b6dfc66e66a5680f33943 | [] | no_license | ChuckBolin/SideScroller | b418e52dee41d0b162fa18c6ef37c5de2dd1a6ad | 9993eb68dda5d4c7e47d66ff14af6d483441fac3 | refs/heads/master | 2016-09-11T11:05:46.763091 | 2014-04-12T01:30:17 | 2014-04-12T01:30:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,842 | cpp | //cGameStatePlay.cpp
#include "..\includes\cgamestateplay.h"
#include "..\includes\keystatus.h"
#include "..\includes\log_templates.h"
//defined in main.cpp WndProc
extern HWND g_hMainWnd;
extern UINT g_Msg;
extern WPARAM g_wParam;
extern LPARAM g_lParam;
extern HINSTANCE g_hAppInst;
extern KEY_SELECTION g_KeySelection;
cGameStatePlay::cGameStatePlay(void)
{
}
cGameStatePlay::~cGameStatePlay(void)
{
::SelectObject(m_hdcBB, m_hOldSurface);
::DeleteObject(m_hSurface);
::DeleteObject(m_hOldSurface);
::DeleteDC(m_hdcBB);
::DeleteObject(m_hBitmap);
//::DeleteObject(m_hHill);
//::DeleteObject(m_hHillMask);
//::DeleteObject(m_hBitmapMask);
//::DeleteObject(m_hBitmapMask2);
//::DeleteObject(m_hTileset);
::DeleteObject(m_hOldBrush);
::DeleteObject(m_hBrush);
::DeleteObject(m_hRedBrush);
::DeleteObject(m_hBlueBrush);
::DeleteObject(m_hBlackBrush);
::DeleteObject(m_hYellowBrush);
}
void cGameStatePlay::initialize(){
::GetWindowRect(g_hMainWnd,&m_RC);
m_width = m_RC.right - m_RC.left;
m_height = m_RC.bottom - m_RC.top;
HDC hdc = ::GetDC(g_hMainWnd);
m_hdcBB = ::CreateCompatibleDC(hdc);//backbuffer DC
m_hSurface = ::CreateCompatibleBitmap(hdc, m_width, m_height);//drawing surface
::ReleaseDC(g_hMainWnd,hdc);
m_hOldSurface = (HBITMAP)::SelectObject(m_hdcBB, m_hSurface);
HBRUSH black = (HBRUSH)::GetStockObject(BLACK_BRUSH);
HBRUSH oldBrush = (HBRUSH)::SelectObject(m_hdcBB, m_hSurface);//select white brush
::Rectangle(m_hdcBB, 0, 0, m_width, m_height);//clears with white
::SelectObject(m_hdcBB, oldBrush);
m_hBitmap = ::LoadBitmap(g_hAppInst,MAKEINTRESOURCE(IDB_BITMAP2));
m_hBling=::LoadBitmap(g_hAppInst,MAKEINTRESOURCE(IDB_BITMAP7));
m_timer.initialize();
//brushes for filling rectangles
m_lb.lbStyle=BS_SOLID;
m_lb.lbColor=RGB(0,210,210);//cyan
m_hBrush = ::CreateBrushIndirect(&m_lb);
m_lb.lbColor=RGB(255, 255,0); //yellow
m_hYellowBrush = ::CreateBrushIndirect(&m_lb);
m_lb.lbColor=RGB(0,0,0);//black
m_hBlackBrush = ::CreateBrushIndirect(&m_lb);
m_lb.lbColor=RGB(0, 80, 0);//dark green
m_hBlueBrush = ::CreateBrushIndirect(&m_lb);
m_lb.lbColor=RGB(155,0,0); //redish
m_hRedBrush = ::CreateBrushIndirect(&m_lb);
loadSprites();//this loads mapping data for IDB_BITMAP2
m_file.loadLevel("levels\\level1.dat");
addLevel(1);
m_bPlaybackMode = false;
Log("cGameStatePlay initialized...");
m_score = 0;
m_bGameActivated = false;
m_bPaused = false;
m_Sound.play(SOUND_PENGO);
}
void cGameStatePlay::activate(){}
cGameStateObject* cGameStatePlay::update(){
m_Sound.update();
if(m_bPaused == true)
return 0;
POINT player;
POINT object;
int type;
int up;
int floor;
if(m_game.isPlayback() == false)
m_bPlaybackMode = false;
if(m_bGameActivated == false){
m_game.newGame();
m_Sound.stopAll();
m_Sound.play(SOUND_SEGWAY);
m_file.loadLevel("levels\\level1.dat");
addLevel(1);
m_bGameActivated = true;
}
if(m_game.gameOver()){
//m_game.newGame();
m_event = GO_MAIN;
m_bGameActivated = true;
}
if(m_game.levelComplete()){
m_Sound.play(SOUND_LEVEL);
switch(m_game.getLevel()){
case 1:
m_file.loadLevel("levels\\level1.dat");
addLevel(1);
break;
case 2:
m_file.loadLevel("levels\\level2.dat");
addLevel(2);
break;
case 3:
m_file.loadLevel("levels\\level3.dat");
addLevel(3);
break;
}
m_game.newLevel();
}
else if(m_game.lifeOver()){
m_game.newLife();
}
if(m_bPlaybackMode == false){
//process all objects and determine if there is a new bottom
player = m_game.getPlayerPosition();
player.x += 16;
floor = 1600;
up = m_game.getVertVel();
POINT pt;
//let's update position of moving platforms
for(int i = 0; i < m_objects.size(); i++){
if(m_objects.getType(i) > 2000)
m_objects.update(i);
}
if(up >= 0){//segway is dropping
for(int i = 0; i < m_objects.size(); i++){
type = m_objects.getType(i);
object.x = m_objects.getPosX(i); //segway is in same hor pos as object
object.y = m_objects.getPosY(i) - 32;
//determine new floor value
if(type < 2000){//stationary platforms
if( player.x >= object.x && player.x <= object.x + 32){
if(type == 109 || type == 1009 || type == 603){//hard surfaces
if(player.y <= object.y && object.y <= floor){
floor = object.y;
}//if
}//if
}//if
}
else{//moving platforms...this works if platform moves down
//but if platform moves up then player.y needs to be changed
if( player.x >= object.x && player.x <= object.x + 32){
if(type > 2000 && type < 2010){//vertical
if(player.y <= object.y + 3){
player.y = object.y - 3;
floor = object.y;
}//if
}//if
else if(type > 2100 && type < 2125){//horizontal movement
if(player.y <= object.y && object.y <= floor){
floor = object.y;
if(m_objects.getDir(i) == 1){ //moving right
pt = m_game.getPlayerPosition();
pt.x += 3;
m_game.setPlayerPosition(pt);
}
else{//moving left
pt = m_game.getPlayerPosition();
pt.x -= 3;
m_game.setPlayerPosition(pt);
}
}
}//if
}//if
}
}//for
}//if(up
m_game.setBottom(floor);
if(player.y > floor + 2){
m_game.setVertVel(0);
player = m_game.getPlayerPosition();
player.y = floor;
m_game.setPlayerPosition(player);
}//if
}//if(m_playbackMode
//collect tokens and battery
player = m_game.getPlayerPosition();
player.x += 16;
player.y += 16;
if(player.y > 768){
m_Sound.stopAll();
m_Sound.resetCountDown();
m_Sound.play(SOUND_SPLASH);
}
for(int i = 0; i < m_objects.size(); i++){
type = m_objects.getType(i);
object.x = m_objects.getPosX(i); //segway is in same hor pos as object
object.y = m_objects.getPosY(i);
if((type == 402 || type == 701 || type == 703 || type == 1205) && m_objects.isActive(i) == 1){
if(player.x > m_objects.getPosX(i)){
if(player.x < m_objects.getPosX(i) + 32){
if(player.y > m_objects.getPosY(i)){
if(player.y < m_objects.getPosY(i) + 32){
m_objects.disable(i);
if(type == 1205)
m_game.incLevel();
else if(type == 402){
m_Sound.stop(SOUND_GOLD);
m_Sound.play(SOUND_GOLD);
m_game.addToken();
}
else if(type == 701){
m_Sound.stop(SOUND_SILVER);
m_Sound.play(SOUND_SILVER);
m_game.addSilverToken();
}
else if(type == 703){
m_Sound.stop(SOUND_BATTERY);
m_Sound.play(SOUND_BATTERY);
m_game.resetEnergy();
}
}//if
}//if
}//if
}//if
}//if(type
}//for
//look for contact with skunks
player = m_game.getPlayerPosition();
player.x += 16;//center of segway wheel
player.y += 32;//wheel point of contact
//skunk sprite is 3 sections: top (12 pix), middle row(10 pix),bottom row(10 pix)
//segway bottom of wheel kills skunk if it is in middle row
//if segway bottom of wheel is in bottom row then segway is killed
for(int i = 0; i < m_objects.size(); i++){
type = m_objects.getType(i);
object.x = m_objects.getPosX(i); //segway is in same hor pos as object
object.y = m_objects.getPosY(i);
//play skunk sound if close to active skunk
if(type > 3000 && m_objects.isActive(i) == 1){
if(player.x > m_objects.getPosX(i) - 64 ){
if(player.x < m_objects.getPosX(i) + 64){
if(player.y > m_objects.getPosY(i) - 64){
if(player.y < m_objects.getPosY(i) + 64){
m_Sound.stop(SOUND_SKUNK);
m_Sound.play(SOUND_SKUNK);
}
}
}
}
}
if(type > 3000 && m_objects.isActive(i) == 1){
if(player.x > m_objects.getPosX(i)){
if(player.x < m_objects.getPosX(i) + 32){
if(player.y > m_objects.getPosY(i)+ 2){
if(player.y < m_objects.getPosY(i) + 22){
m_objects.disable(i); //skunk killed
if(type < 3125){//black skunk
m_Sound.stop(SOUND_SQUISH);
m_Sound.play(SOUND_SQUISH);
m_game.addBlackSkunkScore();
}
else{
m_Sound.stop(SOUND_CRUNCH);
m_Sound.play(SOUND_CRUNCH);
m_game.addRedSkunkScore();
}
}//if
else if(player.y >= m_objects.getPosY(i) + 22 && player.y < m_objects.getPosY(i) + 54){
m_Sound.stop(SOUND_SCREAM);
m_Sound.play(SOUND_SCREAM);
m_game.killSegway(); //segway killed
}//if
}//if
}//if
}//if
}//if(type
}//for
m_game.update();
for(int i=0; i< m_TE.size(); i++){
if (m_TE[i].event == m_event){
if(m_event == GO_MAIN)
m_bGameActivated = false;//this allows reentry with new game
return m_TE[i].p_gso;
}//if
}//for
return 0;
}
void cGameStatePlay::render(){
HDC hdcBitmap = ::CreateCompatibleDC(NULL);
PAINTSTRUCT ps;
HDC hdc = ::BeginPaint(g_hMainWnd, &ps);
//clear backbuffer with black
::BitBlt(m_hdcBB, 0, 0, m_width, m_height, 0, 0, 0, BLACKNESS);
::SelectObject(m_hdcBB,m_hBlackBrush);
::Rectangle(m_hdcBB,0,0, m_width, m_height);//top border
//copies stored bitmap to backbuffer
RECT vrc = m_game.getView();
POINT p = m_game.getPlayerPosition();
int type;
m_hOldBrush=(HBRUSH)::SelectObject(m_hdcBB, m_hBrush);//cyan
::Rectangle(m_hdcBB,400 - p.x, 300 - p.y, 400 + (2400 - p.x), 300 + (800 - p.y));
//draws entities
::SelectObject(hdcBitmap, m_hBitmap);
for(int i = 0; i < m_objects.size(); i++){
//if(m_objects.isActive(i) == true){
if(m_objects.getPosX(i) > p.x - 440 && m_objects.getPosX(i) < p.x + 440 &&
m_objects.getPosY(i) > p.y - 340 && m_objects.getPosY(i) < p.y + 340){
type = m_objects.getType(i);
if(type > 2000 && type < 3000) //this is a moving platform brick 1009
type = 1009;
//32x32 objects
if(type == 106 || type == 109 || type == 201){
::BitBlt(m_hdcBB, (m_objects.getPosX(i) - p.x) + 400, (m_objects.getPosY(i) - p.y) + 300, m_graphics.getSpriteWidth(type), m_graphics.getSpriteHeight(type), hdcBitmap,m_graphics.getSpriteX(type),m_graphics.getSpriteY(type),SRCCOPY);
}
//sprites that have masks
else if (type == 100 || type == 102 || type == 104 || type == 608||
type == 305 || type == 601 || type == 603 || type == 1205 ||
type == 1100 || type == 1109 ||type == 1009){
::BitBlt(m_hdcBB, (m_objects.getPosX(i) - p.x) + 400, (m_objects.getPosY(i) - p.y) + 300, m_graphics.getSpriteWidth(type), m_graphics.getSpriteHeight(type), hdcBitmap,m_graphics.getSpriteMaskX(type),m_graphics.getSpriteMaskY(type),SRCAND);
::BitBlt(m_hdcBB, (m_objects.getPosX(i) - p.x) + 400, (m_objects.getPosY(i) - p.y) + 300, m_graphics.getSpriteWidth(type), m_graphics.getSpriteHeight(type), hdcBitmap,m_graphics.getSpriteX(type),m_graphics.getSpriteY(type),SRCPAINT);
}
else if (type == 402 || type == 701 || type == 703){//gold token,silver token, battery
if(m_objects.isActive(i) == 1){
::BitBlt(m_hdcBB, (m_objects.getPosX(i) - p.x) + 400, (m_objects.getPosY(i) - p.y) + 300, m_graphics.getSpriteWidth(type), m_graphics.getSpriteHeight(type), hdcBitmap,m_graphics.getSpriteMaskX(type),m_graphics.getSpriteMaskY(type),SRCAND);
::BitBlt(m_hdcBB, (m_objects.getPosX(i) - p.x) + 400, (m_objects.getPosY(i) - p.y) + 300, m_graphics.getSpriteWidth(type), m_graphics.getSpriteHeight(type), hdcBitmap,m_graphics.getSpriteX(type),m_graphics.getSpriteY(type),SRCPAINT);
}
}
else if (type > 3000 && type < 3125){//marching of the black skunks
if(m_objects.isActive(i) == 1){
if(m_objects.getDir(i) == 1){
::BitBlt(m_hdcBB, (m_objects.getPosX(i) - p.x) + 400, (m_objects.getPosY(i) - p.y) + 300, 32, 32,hdcBitmap, 160 + (32 * m_objects.getFrame(i)), 288 ,SRCAND);//mask
::BitBlt(m_hdcBB, (m_objects.getPosX(i) - p.x) + 400, (m_objects.getPosY(i) - p.y) + 300, 32, 32,hdcBitmap, 32 + (32 * m_objects.getFrame(i)), 288,SRCPAINT);
}
else if(m_objects.getDir(i) == 0){
if(m_objects.getFrame(i) < 3)
::BitBlt(m_hdcBB, (m_objects.getPosX(i) - p.x) + 400, (m_objects.getPosY(i) - p.y) + 300, 32, 32,hdcBitmap, 224 + (32 * m_objects.getFrame(i)), 256 ,SRCAND);//mask
else
::BitBlt(m_hdcBB, (m_objects.getPosX(i) - p.x) + 400, (m_objects.getPosY(i) - p.y) + 300, 32, 32,hdcBitmap, 0, 288 ,SRCAND);//mask
::BitBlt(m_hdcBB, (m_objects.getPosX(i) - p.x) + 400, (m_objects.getPosY(i) - p.y) + 300, 32, 32,hdcBitmap, 96 + (32 * m_objects.getFrame(i)), 256,SRCPAINT);
}
}
}
else if (type > 3200 && type < 3325){//marching of the red skunks
if(m_objects.isActive(i) == 1){
if(m_objects.getDir(i) == 1){
::BitBlt(m_hdcBB, (m_objects.getPosX(i) - p.x) + 400, (m_objects.getPosY(i) - p.y) + 300, 32, 32,hdcBitmap, 160 + (32 * m_objects.getFrame(i)), 288 ,SRCAND);//mask
::BitBlt(m_hdcBB, (m_objects.getPosX(i) - p.x) + 400, (m_objects.getPosY(i) - p.y) + 300, 32, 32,hdcBitmap, 160 + (32 * m_objects.getFrame(i)), 320,SRCPAINT);
}
else if(m_objects.getDir(i) == 0){
if(m_objects.getFrame(i) < 3)
::BitBlt(m_hdcBB, (m_objects.getPosX(i) - p.x) + 400, (m_objects.getPosY(i) - p.y) + 300, 32, 32,hdcBitmap, 224 + (32 * m_objects.getFrame(i)), 256 ,SRCAND);//mask
else
::BitBlt(m_hdcBB, (m_objects.getPosX(i) - p.x) + 400, (m_objects.getPosY(i) - p.y) + 300, 32, 32,hdcBitmap, 0, 288 ,SRCAND);//mask
::BitBlt(m_hdcBB, (m_objects.getPosX(i) - p.x) + 400, (m_objects.getPosY(i) - p.y) + 300, 32, 32,hdcBitmap, 32 + (32 * m_objects.getFrame(i)), 320,SRCPAINT);
}
}
}
}//if(m_objects
//}//if(m_objects
}//for
//draws segway
int anim = m_game.getFrameNum();
if(p.y < 768){
switch(anim){
case 0:
if(m_game.getDirection() == 0){
::BitBlt(m_hdcBB, 400, 300, 32, 32, hdcBitmap, 0, 64, SRCAND);
::BitBlt(m_hdcBB, 400, 300, 32, 32, hdcBitmap, 64, 32, SRCPAINT);
}
else{
::BitBlt(m_hdcBB, 400, 300, 32, 32, hdcBitmap, 32, 64, SRCAND);
::BitBlt(m_hdcBB, 400, 300, 32, 32, hdcBitmap, 288, 32, SRCPAINT);
}
break;
case 1:
if(m_game.getDirection() == 0){
::BitBlt(m_hdcBB, 400, 300, 32, 32, hdcBitmap, 0, 64, SRCAND);
::BitBlt(m_hdcBB, 400, 300, 32, 32, hdcBitmap, 96, 32, SRCPAINT);
}
else{
::BitBlt(m_hdcBB, 400, 300, 32, 32, hdcBitmap, 32, 64, SRCAND);
::BitBlt(m_hdcBB, 400, 300, 32, 32, hdcBitmap, 256, 32, SRCPAINT);
}
break;
case 2:
if(m_game.getDirection() == 0){
::BitBlt(m_hdcBB, 400, 300, 32, 32, hdcBitmap, 0, 64, SRCAND);
::BitBlt(m_hdcBB, 400, 300, 32, 32, hdcBitmap, 128, 32, SRCPAINT);
}
else{
::BitBlt(m_hdcBB, 400, 300, 32, 32, hdcBitmap, 32, 64, SRCAND);
::BitBlt(m_hdcBB, 400, 300, 32, 32, hdcBitmap, 224, 32, SRCPAINT);
}
break;
case 3:
if(m_game.getDirection() == 0){
::BitBlt(m_hdcBB, 400, 300, 32, 32, hdcBitmap, 0, 64, SRCAND);
::BitBlt(m_hdcBB, 400, 300, 32, 32, hdcBitmap, 160, 32, SRCPAINT);
}
else{
::BitBlt(m_hdcBB, 400, 300, 32, 32, hdcBitmap, 32, 64, SRCAND);
::BitBlt(m_hdcBB, 400, 300, 32, 32, hdcBitmap, 192, 32, SRCPAINT);
}
break;
}
}
//draws overlay
::SelectObject(m_hdcBB,m_hBlueBrush);
::Rectangle(m_hdcBB,0,0, m_width, 100);//top border
::Rectangle(m_hdcBB,0, m_height - 120, m_width,m_height);//bottom border
::SelectObject(m_hdcBB,m_hOldBrush);
//draws map
int mapX = 40;
int mapY = m_height - 110;
POINT player = m_game.getPlayerPosition();
POINT exitLevel = m_game.getExit();
player.x /= 20;
player.y /= 20;
exitLevel.x /= 20;
exitLevel.y /= 20;
::SelectObject(m_hdcBB,m_hBlackBrush); //black 160x70 = 3200x1400
::Rectangle(m_hdcBB, mapX, mapY, mapX + 160, mapY + 70);
::SelectObject(m_hdcBB, m_hBrush); //blue 120x40 = 2400x800
::Rectangle(m_hdcBB, mapX + 20, mapY + 15, mapX + 140, mapY + 55);
::SelectObject(m_hdcBB,m_hYellowBrush);//player position
::Rectangle(m_hdcBB,20 + mapX + player.x - 3 , 15 + mapY + player.y - 3, 20 + mapX + player.x + 3 , 15 + mapY + player.y + 3);
::SelectObject(m_hdcBB,m_hOldBrush);
::SelectObject(m_hdcBB,m_hRedBrush);//exit position
::Rectangle(m_hdcBB,20 + mapX + exitLevel.x - 3 , 15 + mapY + exitLevel.y - 3, 20 + mapX + exitLevel.x + 3 , 15 + mapY + exitLevel.y + 3);
::SelectObject(m_hdcBB,m_hOldBrush);
::SelectObject(m_hdcBB,m_hYellowBrush);//viewport
RECT view;
view.left = 20 + mapX + player.x - 20;
view.top = 15 + mapY + player.y - 15;
view.right = view.left + 40;
view.bottom = view.top + 30;
::FrameRect(m_hdcBB,&view, m_hYellowBrush);
//draws power grid
::SelectObject(hdcBitmap, m_hBling);
::BitBlt(m_hdcBB, 10, 10, m_game.getEnergy() , 77, hdcBitmap, 156, 289, SRCAND);
::BitBlt(m_hdcBB, 10, 10, m_game.getEnergy() , 77, hdcBitmap, 1, 289, SRCPAINT);
//power label
::BitBlt(m_hdcBB, 30, 60, 108, 47, hdcBitmap, 1, 93, SRCAND);
::BitBlt(m_hdcBB, 30, 60, 108, 47, hdcBitmap, 1, 1, SRCPAINT);
//level
GRAPHIC_DIGIT glevel = getFontData(m_game.getLevel());
//digit
::BitBlt(m_hdcBB, 475, 10, 35, 50, hdcBitmap, glevel.digit[0], 237, SRCAND);//mask
::BitBlt(m_hdcBB, 475, 10, 35, 50, hdcBitmap, glevel.digit[0], 185, SRCPAINT);//font
//word level
::BitBlt(m_hdcBB, 450, 60, 94, 39, hdcBitmap, 118, 141, SRCAND);
::BitBlt(m_hdcBB, 450, 60, 94, 39, hdcBitmap, 118, 49, SRCPAINT);
//displays lives
int lives = m_game.getLives();
if(lives > 0){
::BitBlt(m_hdcBB, 240, 10, 35, 54, hdcBitmap, 452, 57, SRCAND);
::BitBlt(m_hdcBB, 240, 10, 35, 54, hdcBitmap, 415, 1, SRCPAINT);
}
if(lives > 1){
::BitBlt(m_hdcBB, 280, 10, 35, 54, hdcBitmap, 452, 57, SRCAND);
::BitBlt(m_hdcBB, 280, 10, 35, 54, hdcBitmap, 415, 57, SRCPAINT);
}
if(lives > 2){
::BitBlt(m_hdcBB, 320, 10, 35, 54, hdcBitmap, 452, 57, SRCAND);
::BitBlt(m_hdcBB, 320, 10, 35, 54, hdcBitmap, 415, 113, SRCPAINT);
}
::BitBlt(m_hdcBB, 250, 60, 96, 46, hdcBitmap, 117, 93, SRCAND);
::BitBlt(m_hdcBB, 250, 60, 96, 46, hdcBitmap, 117, 1, SRCPAINT);
//my name
::BitBlt(m_hdcBB, 303, 545, 194, 34, hdcBitmap, 1, 483, SRCAND);
::BitBlt(m_hdcBB, 303, 545, 194, 34, hdcBitmap, 1, 447, SRCPAINT);
//prints numbers
::SelectObject(hdcBitmap, m_hBling);
//display score
GRAPHIC_DIGIT g = getFontData(m_game.getScore());
int maxDigit = 5;
if(m_game.getScore() < 10)
maxDigit = 1;
else if(m_game.getScore() < 100)
maxDigit = 2;
else if(m_game.getScore() < 1000)
maxDigit = 3;
else if(m_game.getScore() < 10000)
maxDigit = 4;
for(int i=0; i<maxDigit;i++){
::BitBlt(m_hdcBB, 600 + ((5 - maxDigit)*32) + (i * 35), 525, 35, 50, hdcBitmap,g.digit[i], 237, SRCAND);//mask
::BitBlt(m_hdcBB, 600 + ((5 - maxDigit)*32) + (i * 35), 525, 35, 50, hdcBitmap,g.digit[i], 185, SRCPAINT);//font
}
::BitBlt(m_hdcBB, 650, 485, 99, 45, hdcBitmap,1, 138, SRCAND);//mask
::BitBlt(m_hdcBB, 650, 485, 99, 45, hdcBitmap,1, 46, SRCPAINT);//font
//display remaining time
GRAPHIC_DIGIT gs = getFontData(m_game.getTime());
maxDigit = 3;
if(m_game.getTime() < 10)
maxDigit = 1;
else if(m_game.getTime() < 100)
maxDigit = 2;
for(int i=0; i<maxDigit;i++){
::BitBlt(m_hdcBB, 625 + ((3 - maxDigit)*32) + (i * 35), 10, 35, 50, hdcBitmap,gs.digit[i], 237, SRCAND);//mask
::BitBlt(m_hdcBB, 625 + ((3 - maxDigit)*32) + (i * 35), 10, 35, 50, hdcBitmap,gs.digit[i], 185, SRCPAINT);//font
}
::BitBlt(m_hdcBB, 635, 60, 89, 44, hdcBitmap, 238, 93, SRCAND);//mask
::BitBlt(m_hdcBB, 635, 60, 89, 44, hdcBitmap, 238, 1, SRCPAINT);//font
//display player coordinates
POINT pt = m_game.getPlayerPosition();
::SetTextColor(m_hdcBB,RGB(255,255,255));
::SetBkColor(m_hdcBB,RGB(0,80,0));
PrintText(m_hdcBB,"X: ", pt.x,210,505);
PrintText(m_hdcBB,"Y: ", pt.y,210,535);
//display GI challenge
//::SetTextColor(m_hdcBB,RGB(255,255,0));
//PrintText(m_hdcBB,"GI Game Challenge 2",330,505);
//PrintText(m_hdcBB,"<July 13 - August 12, 2007>",310,530);
::BitBlt(m_hdcBB, 272, 505, 252, 45, hdcBitmap, 198, 448, SRCAND);//mask
::BitBlt(m_hdcBB, 272, 505, 252, 45, hdcBitmap, 198, 449, SRCPAINT);//font
//display pause image if paused
if(m_bPaused == true){
::BitBlt(m_hdcBB, 332, 230, 164, 78, hdcBitmap, 311, 368, SRCAND);//mask
::BitBlt(m_hdcBB, 332, 230, 164, 78, hdcBitmap,311, 289, SRCPAINT);//font
}
//copies backbuffer to front buffer
::BitBlt(hdc, 0, 0, m_width, m_height, m_hdcBB, 0, 0, SRCCOPY);
::ReleaseDC(g_hMainWnd, hdc);
::DeleteObject(hdcBitmap);
::EndPaint(g_hMainWnd,&ps);
}
void cGameStatePlay::processEvent(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam){
m_event = GO_NO_WHERE;
if(m_bPlaybackMode == false){
if(keyDown(g_KeySelection.moveLeft))
m_game.movePlayerLeft(2);
if(keyDown(g_KeySelection.moveRight))
m_game.movePlayerRight(2);
if(keyDown(g_KeySelection.moveJump)){
m_Sound.stop(SOUND_BOUNCE2);
m_Sound.play(SOUND_BOUNCE2);
m_game.movePlayerUp(22);
}
if(keyDown(g_KeySelection.moveBrake))
m_game.movePlayerStop();
if(keyDown(0x50)){ //P{
if(m_bPaused == false)
m_bPaused = true;
else
m_bPaused = false;
}
}
if(keyDown(VK_ESCAPE)){ //M{
m_Sound.stopAll();
m_event = GO_MAIN;
}
/*if(keyDown(0x52)){//Q
if(m_game.isPlayback() == false){
m_game.playBack();
}
} */
}
GRAPHIC_DIGIT cGameStatePlay::getFontData(int value){
std::ostringstream oss;
std::string sNum;
GRAPHIC_DIGIT gd;
gd.digit[0]=1;
gd.digit[1]=1;
gd.digit[2]=1;
gd.digit[3]=1;
gd.digit[4]=1;
oss << value;
sNum = oss.str();
int digit[]= {1,36,70,106,139,172,208,240,275,310};
int number = 0;
//Log("sNum",sNum);
for(int i=0; i < sNum.size(); i++){
number = 0;
if (sNum.at(i) == '0')
number = 0;
else if(sNum.at(i) == '1')
number = 1;
else if(sNum.at(i) == '2')
number = 2;
else if(sNum.at(i) == '3')
number = 3;
else if(sNum.at(i) == '4')
number = 4;
else if(sNum.at(i) == '5')
number = 5;
else if(sNum.at(i) == '6')
number = 6;
else if(sNum.at(i) == '7')
number = 7;
else if(sNum.at(i) == '8')
number = 8;
else if(sNum.at(i) == '9')
number = 9;
switch(i){
case 0:
gd.digit[i] = digit[number];
break;
case 1:
gd.digit[i] = digit[number];
break;
case 2:
gd.digit[i] = digit[number];
break;
case 3:
gd.digit[i] = digit[number];
break;
case 4:
gd.digit[i] = digit[number];
break;
case 5:
gd.digit[i] = digit[number];
break;
case 6:
gd.digit[i] = digit[number];
break;
case 7:
gd.digit[i] = digit[number];
break;
case 8:
gd.digit[i] = digit[number];
break;
case 9:
gd.digit[i] = digit[number];
break;
}
}
return gd;
}
void cGameStatePlay::deactivate(){
}
void cGameStatePlay::resume(){
}
void cGameStatePlay::pause(){
}
void cGameStatePlay::save(){
}
void cGameStatePlay::addTransitionEvent(int event, cGameStateObject* p_Next){
TRANSITION_EVENT te;
te.event=event;
te.p_gso = p_Next;
m_TE.push_back(te);
}
//loads entities to be displayed on the level
void cGameStatePlay::addLevel(int level){
POINT levelExit;
if(level < 1 || level > 3)
return; //legal levels are 1, 2 and 3
m_game.setLevel(level);
m_objects.clearAll();//clears entity data used by game play
for(int i = 0; i < m_file.size(); i++){
m_objects.addEntity( m_file.getType(i),
m_file.getPosX(i),
m_file.getPosY(i));
if(m_file.getType(i) == 1205){ //location of level exit
levelExit.x = m_file.getPosX(i);
levelExit.y = m_file.getPosY(i);
m_game.setExit(levelExit);
}
}
m_file.clearData(); //clears previously stored file data
//load player starting data
POINT player;
if(m_objects.getType(0) == 1){
player.x = m_objects.getPosX(0);
player.y = m_objects.getPosY(0);
m_game.setPlayerInitialPosition(player);
}
else{
player.x = 108;
player.y = 660;
m_game.setPlayerInitialPosition(player);
}
}
//loads sprites
void cGameStatePlay::loadSprites(){
m_graphics.addSprite(100,0,0,32,32,32,0,3);//center dirt w/ grass lower
m_graphics.addSprite(102,64,0,32,32,96,0,3);//right dirt w/grass lower
m_graphics.addSprite(104,128,0,32,32,160,0,3);//left dirt w/grass lower
m_graphics.addSprite(106,192,0,32,32,288,128,1);//32x32 dirt
m_graphics.addSprite(109,288,0,32,32,288,128,1);//32x32 brick
m_graphics.addSprite(201,32,32,32,32,288,128,1);//32x32 brick - alternative
m_graphics.addSprite(305,160,64,32,32,32,0,3);//lower metal
m_graphics.addSprite(402,64,96,32,32,96,96,5);//token gold
m_graphics.addSprite(601,32,160,32,32,32,0,2);//color panel upper
m_graphics.addSprite(603,96,160,32,32,128, 160,2);//color panel upper
m_graphics.addSprite(608,256,160,32,32,288,160,6);//32x32 lava
m_graphics.addSprite(701,32,192,32,32,64,192,5);//token silver
m_graphics.addSprite(703,96,192,32,32,224,192,9); //battery
m_graphics.addSprite(1009,288,288,32,32,128,160,2);//upper half brick
m_graphics.addSprite(1100,0,320,32,32,32,0,3); //lower half brick
m_graphics.addSprite(1109,288,320,32,32,0,352,6);//water full
m_graphics.addSprite(1205,160,352,32,32,192,352,5);//exit
} | [
"cbolin@sc.rr.com"
] | cbolin@sc.rr.com |
58b7976462527618928344afd5177c392e91c02a | 575c78d3b7a2fe90f4f0624d963bd6111dfca309 | /deps/polyscope/src/render/opengl/shaders/ribbon_shaders.cpp | 303a1e4d2e809b5def4a3d7a0c133d39073d79da | [
"MIT"
] | permissive | g-gisbert/Inpainting-Holes-In-Folded-Fabric-Meshes | 1898a35a848f9f16a99653c7c1e95ab0941755cd | ccce75215b742a1c971008c4f1a889bd85b6c74d | refs/heads/main | 2023-08-19T08:49:47.829392 | 2023-08-18T13:55:11 | 2023-08-18T13:55:11 | 648,992,474 | 5 | 2 | MIT | 2023-07-21T15:34:49 | 2023-06-03T12:45:00 | C++ | UTF-8 | C++ | false | false | 5,861 | cpp | // Copyright 2017-2019, Nicholas Sharp and the Polyscope contributors. http://polyscope.run.
#include "polyscope/render/opengl/shaders/ribbon_shaders.h"
namespace polyscope {
namespace render {
namespace backend_openGL3_glfw {
// clang-format off
const ShaderStageSpecification RIBBON_VERT_SHADER = {
ShaderStageType::Vertex,
{ }, // uniforms
// attributes
{
{"a_position", DataType::Vector3Float},
{"a_color", DataType::Vector3Float},
{"a_normal", DataType::Vector3Float},
},
{}, // textures
// source
R"(
${ GLSL_VERSION }$
in vec3 a_position;
in vec3 a_color;
in vec3 a_normal;
out vec3 Color;
out vec3 Normal;
void main()
{
Color = a_color;
Normal = a_normal;
gl_Position = vec4(a_position,1.0);
}
)"
};
const ShaderStageSpecification RIBBON_GEOM_SHADER = {
ShaderStageType::Geometry,
// uniforms
{
{"u_modelView", DataType::Matrix44Float},
{"u_projMatrix", DataType::Matrix44Float},
{"u_ribbonWidth", DataType::Float},
{"u_depthOffset", DataType::Float},
},
// attributes
{
},
{}, // textures
// source
R"(
${ GLSL_VERSION }$
layout(lines_adjacency) in;
layout(triangle_strip, max_vertices=20) out;
in vec3 Color[];
in vec3 Normal[];
uniform mat4 u_modelView;
uniform mat4 u_projMatrix;
uniform float u_ribbonWidth;
uniform float u_depthOffset;
out vec3 colorToFrag;
out vec3 cameraNormalToFrag;
out float intensityToFrag;
void main() {
mat4 PV = u_projMatrix * u_modelView;
const float PI = 3.14159265358;
vec3 pos0 = gl_in[0].gl_Position.xyz;
vec3 pos1 = gl_in[1].gl_Position.xyz;
vec3 pos2 = gl_in[2].gl_Position.xyz;
vec3 pos3 = gl_in[3].gl_Position.xyz;
vec3 dir = normalize(pos2 - pos1);
vec3 prevDir = normalize(pos1 - pos0);
vec3 nextDir = normalize(pos3 - pos2);
vec3 sideVec0 = normalize(cross(normalize(dir + prevDir), Normal[1]));
vec3 sideVec1 = normalize(cross(normalize(dir + nextDir), Normal[2]));
// The points on the front and back sides of the ribbon
vec4 pStartLeft = vec4(pos1 + sideVec0 * u_ribbonWidth, 1);
vec4 pStartMid = vec4(pos1, 1);
vec4 pStartRight = vec4(pos1 - sideVec0 * u_ribbonWidth, 1);
vec4 pEndLeft = vec4(pos2 + sideVec1 * u_ribbonWidth, 1);
vec4 pEndMid = vec4(pos2, 1);
vec4 pEndRight = vec4(pos2 - sideVec1 * u_ribbonWidth, 1);
// First triangle
gl_Position = PV * pStartRight;
gl_Position.z -= u_depthOffset;
cameraNormalToFrag = mat3(u_modelView) * Normal[1];
colorToFrag = Color[1];
intensityToFrag = 0.0;
EmitVertex();
gl_Position = PV * pEndRight;
gl_Position.z -= u_depthOffset;
cameraNormalToFrag = mat3(u_modelView) * Normal[2];
colorToFrag = Color[2];
intensityToFrag = 0.0;
EmitVertex();
gl_Position = PV * pStartMid;
gl_Position.z -= u_depthOffset;
cameraNormalToFrag = mat3(u_modelView) * Normal[1];
colorToFrag = Color[1];
intensityToFrag = 1.0;
EmitVertex();
// Second triangle
gl_Position = PV * pEndMid;
gl_Position.z -= u_depthOffset;
cameraNormalToFrag = mat3(u_modelView) * Normal[2];
colorToFrag = Color[2];
intensityToFrag = 1.0;
EmitVertex();
// Third triangle
gl_Position = PV * pStartLeft;
gl_Position.z -= u_depthOffset;
cameraNormalToFrag = mat3(u_modelView) * Normal[1];
colorToFrag = Color[1];
intensityToFrag = 0.0;
EmitVertex();
// Fourth triangle
gl_Position = PV * pEndLeft;
gl_Position.z -= u_depthOffset;
cameraNormalToFrag = mat3(u_modelView) * Normal[2];
colorToFrag = Color[2];
intensityToFrag = 0.0;
EmitVertex();
EndPrimitive();
}
)"
};
const ShaderStageSpecification RIBBON_FRAG_SHADER = {
ShaderStageType::Fragment,
{}, // uniforms
{}, // attributes
{}, // textures
// source
R"(
${ GLSL_VERSION }$
in vec3 colorToFrag;
in vec3 cameraNormalToFrag;
in float intensityToFrag;
layout(location = 0) out vec4 outputF;
${ FRAG_DECLARATIONS }$
void main()
{
float depth = gl_FragCoord.z;
${ GLOBAL_FRAGMENT_FILTER }$
// Compute a fade factor to set the transparency
// Basically amounts to antialiasing in screen space when lines are relatively large on screen
float screenFadeLen = 2.5;
float dF = length(vec2(dFdx(intensityToFrag),dFdy(intensityToFrag)));
float thresh = min(dF * screenFadeLen, 0.2);
float fadeFactor = smoothstep(0, thresh, intensityToFrag);
vec3 albedoColor = colorToFrag;
vec3 shadeNormal = cameraNormalToFrag;
// Lighting
${ GENERATE_LIT_COLOR }$
// Set alpha
float alphaOut = 1.0;
${ GENERATE_ALPHA }$
alphaOut *= fadeFactor;
// Write output
outputF = vec4(litColor, alphaOut);
}
)"
};
// clang-format on
} // namespace backend_openGL3_glfw
} // namespace render
} // namespace polyscope
| [
"gisbert.guillaume1997@gmail.com"
] | gisbert.guillaume1997@gmail.com |
9fcac7f98d060629dcac11e70d8466f2aeb6f5f4 | a1dec9b8941cdefce699d2b0c5c907b7f9f5cce1 | /Project_CPP/detcted_windows_architecture.cpp | 3fbf9d2ace951b01fc1aa809ebd18dc2fbaeaeec | [] | no_license | ddarkclay/programming-cookbook | 876763762e5922f267259233ddbca71b0d833ddb | 1ebe5ab0a1798cef25aeababfa3deb0e6a4b0d10 | refs/heads/master | 2020-11-24T09:14:08.502636 | 2019-12-14T18:34:52 | 2019-12-14T18:34:52 | 228,066,456 | 0 | 3 | null | 2019-12-15T02:34:29 | 2019-12-14T18:02:29 | Python | UTF-8 | C++ | false | false | 290 | cpp | #include<iostream>
#include<conio.h>
using namespace std;
int main()
{
#if (defined (_WIN32))
std::cout<<"Windows 32 Bit Architecture !"<<std::endl;
#elif(defined (_WIN64))
std::cout<<"Windows 64 Bit Architecture !"<<std::endl;
#endif
getch();
}
| [
"vaibhavchaudhari8625@gmail.com"
] | vaibhavchaudhari8625@gmail.com |
fd40c3a1dfe5f708b8b54081af0ce481c6a29c8b | 62b0d19327705b09c47764f588327f5f91c2576f | /Hashing/common-elements.cpp | 5d60a85c6a162582b01b9f9e4660950ab8a78be6 | [] | no_license | SparshJain2000/GFG_Solutions | 637600a12010c26f6fd28644c9aca8c8ae9020ad | d570c35683969cf7f343d3da4827359cf87269c6 | refs/heads/main | 2023-08-28T03:22:23.989906 | 2021-10-05T08:07:59 | 2021-10-05T08:07:59 | 320,352,756 | 4 | 5 | null | 2021-10-05T08:08:00 | 2020-12-10T18:09:58 | C++ | UTF-8 | C++ | false | false | 1,061 | cpp | #include <bits/stdc++.h>
using namespace std;
/*
Given two lists V1 and V2 of sizes n and m respectively.
Return the list of elements common to both the lists and return the list in sorted order. Duplicates may be there in the output list.
*/
vector<int> common_element(vector<int> v1, vector<int> v2) {
sort(v1.begin(), v1.end());
sort(v2.begin(), v2.end());
auto lit = set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), v1.begin());
return vector<int>(v1.begin(), lit);
}
// { Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> v1(n, 0);
for (int i = 0; i < n; i++) {
cin >> v1[i];
}
int m;
cin >> m;
vector<int> v2(m, 0);
for (int i = 0; i < m; i++) {
cin >> v2[i];
}
vector<int> result;
result = common_element(v1, v2);
for (auto i : result) {
cout << i << " ";
}
cout << endl;
}
} // } Driver Code Ends | [
"jainsparsh0801@gmail.com"
] | jainsparsh0801@gmail.com |
ac0c74f8d6006fd12a2679ab796f77a724dc63aa | 13771efbe4bd2803f21b75c0edb621a0d68d0f6c | /그래프/단어변환_그래프BFS_프로그래머스.cpp | a88fb0c9b536320cea318910a5f53c4e875fab9d | [] | no_license | Flare-k/Algorithm | f6e597bcb376d8c0f50e91556cadf2cceadd786c | 64ab13c5304712292c41a26a4347f010d70daf98 | refs/heads/master | 2023-04-08T21:05:08.130284 | 2023-04-03T13:57:01 | 2023-04-03T13:57:01 | 236,532,243 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,167 | cpp | #include <iostream>
#include <algorithm>
#include <string>
#include <queue>
#include <vector>
using namespace std;
int result = 21e8;
bool used[51];
struct Node {
string word;
int level;
};
int checkStr(string a, string b) {
int cnt = 0;
int len = a.length();
for (int i = 0; i < len; i++) {
if (a[i] != b[i]) cnt++;
}
return cnt;
}
int solution(string begin, string target, vector<string> words) {
int answer = 0;
queue<Node> q;
q.push({begin, 0});
int idx = 0;
while (!q.empty()) {
Node now = q.front();
q.pop();
if (now.word == target) {
answer = now.level;
break;
}
for (int i = 0; i < words.size(); i++) {
if (used[i]) continue;
if (checkStr(now.word, words[i]) == 1) {
used[i] = true;
q.push({words[i], now.level + 1});
}
}
}
return answer;
}
int main() {
cout << solution("hit", "cog", {"hot", "dot", "dog", "lot", "log", "cog"}) << '\n';
// cout << solution("hit", "cog", {"hot", "dot", "dog", "lot", "log"}) << '\n';
return 0;
} | [
"rokkyw@naver.com"
] | rokkyw@naver.com |
41f20d9ff21cd4f0f16faed88c619dd585abfc9f | 084c16828bf29c1534976b81394b75bfd02fedc4 | /E-olimp/Geometri/what_type_of_triangle.cpp | 55b4b2f56e33ebb435ac61f5c705c2c9baa3150c | [] | no_license | timminn/Competitive-Programming-Solutions | 278f3b9e1ae06173cfd7c6af851bbcda09c85301 | 21c8070a807dff1d6170acf5cb102ac5e1d4b4b5 | refs/heads/master | 2021-05-30T10:05:45.225954 | 2016-01-26T01:05:57 | 2016-01-26T01:05:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 348 | cpp | #include <iostream>
#define FOR(i,a,b) for(i=a; i<=b; i++)
#define FOR2(i,n) FOR(i,0,n-1)
#define all(x) x.begin(),x.end()
using namespace std;
int solve()
{
int a,b,c;
cin >> a >> b >> c;
if(a == b && b == c) return 1;
if(a == b || b == c || a == c) return 2;
return 3;
}
int main()
{
cout << solve() << endl;
return 0;
}
| [
"harungunaydin@Harun-2.local"
] | harungunaydin@Harun-2.local |
d039f6cedea8f914363d5492dbe54e9e780ea949 | 9f2ea2feeed695d5d4870ff7074d5c96999d7146 | /components/password_manager/core/browser/form_parsing/form_parser.cc | dba8aa4d2e20796bbfce5602e74e4b4c9228be86 | [
"BSD-3-Clause"
] | permissive | vitalybuka/chromium | 289ebbafe4db85fe9ee794e2e93ac5525db96fd0 | c43e2076a35b740204deac7d213edb93d03bc68b | refs/heads/master | 2023-02-24T14:49:53.938847 | 2019-12-14T01:19:24 | 2019-12-14T01:35:10 | 103,636,540 | 0 | 0 | null | 2017-09-15T09:12:32 | 2017-09-15T08:59:45 | null | UTF-8 | C++ | false | false | 45,181 | cc | // Copyright 2018 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 "components/password_manager/core/browser/form_parsing/form_parser.h"
#include <stdint.h>
#include <algorithm>
#include <iterator>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base/metrics/histogram_macros.h"
#include "base/no_destructor.h"
#include "base/stl_util.h"
#include "base/strings/string16.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_split.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "components/autofill/core/browser/field_types.h"
#include "components/autofill/core/common/autofill_regex_constants.h"
#include "components/autofill/core/common/autofill_regexes.h"
#include "components/autofill/core/common/form_data.h"
#include "components/autofill/core/common/password_form.h"
#include "components/password_manager/core/common/password_manager_features.h"
using autofill::FieldPropertiesFlags;
using autofill::FormData;
using autofill::FormFieldData;
using autofill::PasswordForm;
using base::string16;
namespace password_manager {
namespace {
constexpr char kAutocompleteUsername[] = "username";
constexpr char kAutocompleteCurrentPassword[] = "current-password";
constexpr char kAutocompleteNewPassword[] = "new-password";
constexpr char kAutocompleteCreditCardPrefix[] = "cc-";
// The susbset of autocomplete flags related to passwords.
enum class AutocompleteFlag {
kNone,
kUsername,
kCurrentPassword,
kNewPassword,
// Represents the whole family of cc-* flags.
kCreditCard
};
// The autocomplete attribute has one of the following structures:
// [section-*] [shipping|billing] [type_hint] field_type
// on | off | false
// (see
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls%3A-the-autocomplete-attribute).
// For password forms, only the field_type is relevant. So parsing the attribute
// amounts to just taking the last token. If that token is one of "username",
// "current-password" or "new-password", this returns an appropriate enum value.
// If the token starts with a "cc-" prefix, this returns kCreditCard.
// Otherwise, returns kNone.
AutocompleteFlag ExtractAutocompleteFlag(const std::string& attribute) {
std::vector<base::StringPiece> tokens =
base::SplitStringPiece(attribute, base::kWhitespaceASCII,
base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
if (tokens.empty())
return AutocompleteFlag::kNone;
const base::StringPiece& field_type = tokens.back();
if (base::LowerCaseEqualsASCII(field_type, kAutocompleteUsername))
return AutocompleteFlag::kUsername;
if (base::LowerCaseEqualsASCII(field_type, kAutocompleteCurrentPassword))
return AutocompleteFlag::kCurrentPassword;
if (base::LowerCaseEqualsASCII(field_type, kAutocompleteNewPassword))
return AutocompleteFlag::kNewPassword;
if (base::StartsWith(field_type, kAutocompleteCreditCardPrefix,
base::CompareCase::SENSITIVE))
return AutocompleteFlag::kCreditCard;
return AutocompleteFlag::kNone;
}
// How likely is user interaction for a given field?
// Note: higher numeric values should match higher likeliness to allow using the
// standard operator< for comparison of likeliness.
enum class Interactability {
// When the field is invisible.
kUnlikely = 0,
// When the field is visible/focusable.
kPossible = 1,
// When the user actually typed into the field before.
kCertain = 2,
};
// A wrapper around FormFieldData, carrying some additional data used during
// parsing.
struct ProcessedField {
// This points to the wrapped FormFieldData.
const FormFieldData* field;
// The flag derived from field->autocomplete_attribute.
AutocompleteFlag autocomplete_flag = AutocompleteFlag::kNone;
// True if field->form_control_type == "password".
bool is_password = false;
// True if field is predicted to be a password.
bool is_predicted_as_password = false;
// True if the server predicts that this field is not a password field.
bool server_hints_not_password = false;
// True if the server predicts that this field is not a username field.
bool server_hints_not_username = false;
Interactability interactability = Interactability::kUnlikely;
};
// Returns true if the |str| contains words related to CVC fields.
bool StringMatchesCVC(const base::string16& str) {
static const base::NoDestructor<base::string16> kCardCvcReCached(
base::UTF8ToUTF16(autofill::kCardCvcRe));
return autofill::MatchesPattern(str, *kCardCvcReCached);
}
// TODO(crbug.com/860700): Remove name and attribute checking once server-side
// provides hints for CVC.
// Returns true if the |field| is suspected to be not the password field.
// The suspicion is based on server-side provided hints and on checking the
// field's id and name for hinting towards a CVC code.
bool IsNotPasswordField(const ProcessedField& field) {
return field.server_hints_not_password ||
StringMatchesCVC(field.field->name_attribute) ||
StringMatchesCVC(field.field->id_attribute) ||
field.autocomplete_flag == AutocompleteFlag::kCreditCard;
}
// Returns true if the |field| is suspected to be not the username field.
bool IsNotUsernameField(const ProcessedField& field) {
return field.server_hints_not_username;
}
// Checks if the Finch experiment for offering password generation for
// server-predicted clear-text fields is enabled.
bool IsPasswordGenerationForClearTextFieldsEnabled() {
return base::FeatureList::IsEnabled(
password_manager::features::KEnablePasswordGenerationForClearTextFields);
}
// Returns true iff |field_type| is one of password types.
bool IsPasswordPrediction(const CredentialFieldType field_type) {
switch (field_type) {
case CredentialFieldType::kUsername:
case CredentialFieldType::kSingleUsername:
case CredentialFieldType::kNone:
return false;
case CredentialFieldType::kCurrentPassword:
case CredentialFieldType::kNewPassword:
case CredentialFieldType::kConfirmationPassword:
return true;
}
NOTREACHED();
return false;
}
// Returns true iff |processed_field| matches the |interactability_bar|. That is
// when either:
// (1) |processed_field.interactability| is not less than |interactability_bar|,
// or
// (2) |interactability_bar| is |kCertain|, and |processed_field| was
// autofilled. The second clause helps to handle the case when both Chrome and
// the user contribute to filling a form:
//
// <form>
// <input type="password" autocomplete="current-password" id="Chrome">
// <input type="password" autocomplete="new-password" id="user">
// </form>
//
// In the example above, imagine that Chrome filled the field with id=Chrome,
// and the user typed the new password in field with id=user. Then the parser
// should identify that id=Chrome is the current password and id=user is the new
// password. Without clause (2), Chrome would ignore id=Chrome.
bool MatchesInteractability(const ProcessedField& processed_field,
Interactability interactability_bar) {
return (processed_field.interactability >= interactability_bar) ||
(interactability_bar == Interactability::kCertain &&
(processed_field.field->properties_mask &
FieldPropertiesFlags::AUTOFILLED));
}
bool DoesStringContainOnlyDigits(const base::string16& s) {
return std::all_of(s.begin(), s.end(), &base::IsAsciiDigit<base::char16>);
}
// Heuristics to determine that a string is very unlikely to be a username.
bool IsProbablyNotUsername(const base::string16& s) {
return s.empty() || (s.size() < 3 && DoesStringContainOnlyDigits(s));
}
// Returns |typed_value| if it is not empty, |value| otherwise.
base::string16 GetFieldValue(const FormFieldData& field) {
return field.typed_value.empty() ? field.value : field.typed_value;
}
// A helper struct that is used to capture significant fields to be used for
// the construction of a PasswordForm.
struct SignificantFields {
const FormFieldData* username = nullptr;
const FormFieldData* password = nullptr;
const FormFieldData* new_password = nullptr;
const FormFieldData* confirmation_password = nullptr;
// True if the information about fields could only be derived after relaxing
// some constraints. The resulting PasswordForm should only be used for
// fallback UI.
bool is_fallback = false;
// True iff the new password field was found with server hints or autocomplete
// attributes.
bool is_new_password_reliable = false;
// True if the current form has only username, but no passwords.
bool is_single_username = false;
// Returns true if some password field is present. This is the minimal
// requirement for a successful creation of a PasswordForm is present.
bool HasPasswords() const {
DCHECK(!confirmation_password || new_password)
<< "There is no password to confirm if there is no new password field.";
return password || new_password;
}
void ClearAllPasswordFields() {
password = nullptr;
new_password = nullptr;
confirmation_password = nullptr;
}
};
// Returns true if |field| is in |significant_fields|.
bool IsFieldInSignificantFields(const SignificantFields& significant_fields,
const FormFieldData* field) {
return significant_fields.username == field ||
significant_fields.password == field ||
significant_fields.new_password == field ||
significant_fields.confirmation_password == field;
}
bool DoesPredictionCorrespondToField(
const FormFieldData& field,
const PasswordFieldPrediction& prediction) {
#if defined(OS_IOS)
return field.unique_id == prediction.unique_id;
#else
return field.unique_renderer_id == prediction.renderer_id;
#endif
}
// Returns the first element of |fields| which corresponds to |prediction|, or
// null if there is no such element.
ProcessedField* FindField(std::vector<ProcessedField>* processed_fields,
const PasswordFieldPrediction& prediction) {
for (ProcessedField& processed_field : *processed_fields) {
if (DoesPredictionCorrespondToField(*processed_field.field, prediction))
return &processed_field;
}
return nullptr;
}
// Tries to parse |processed_fields| based on server |predictions|. Uses |mode|
// to decide which of two username hints are relevant, if present.
void ParseUsingPredictions(std::vector<ProcessedField>* processed_fields,
const FormPredictions& predictions,
FormDataParser::Mode mode,
SignificantFields* result) {
// Following the design from https://goo.gl/Mc2KRe, this code will attempt to
// understand the special case when there are two usernames hinted by the
// server. In that case, they are considered the sign-in and sign-up
// usernames, in the order in which the (only) current password and the first
// new-password come. If there is another amount of usernames, 0 or 2+ current
// password fields or no new password field, then the abort switch below is
// set and simply the first field of each kind is used.
bool prevent_handling_two_usernames = false; // the abort switch
// Whether the first username is for sign-in.
bool sign_in_username_first = true;
// First username is stored in |result->username|.
const FormFieldData* second_username = nullptr;
for (const PasswordFieldPrediction& prediction : predictions.fields) {
ProcessedField* processed_field = nullptr;
CredentialFieldType field_type = DeriveFromServerFieldType(prediction.type);
bool is_password_prediction = IsPasswordPrediction(field_type);
if (mode == FormDataParser::Mode::kSaving && is_password_prediction) {
// TODO(crbug.com/913965): Consider server predictions for password fields
// in SAVING mode when the server predictions become complete.
continue;
}
switch (field_type) {
case CredentialFieldType::kUsername:
if (!result->username) {
processed_field = FindField(processed_fields, prediction);
if (processed_field)
result->username = processed_field->field;
} else if (!second_username) {
processed_field = FindField(processed_fields, prediction);
if (processed_field)
second_username = processed_field->field;
} else {
prevent_handling_two_usernames = true;
}
break;
case CredentialFieldType::kSingleUsername:
processed_field = FindField(processed_fields, prediction);
if (processed_field) {
result->username = processed_field->field;
result->is_single_username = true;
result->ClearAllPasswordFields();
return;
}
break;
case CredentialFieldType::kCurrentPassword:
if (result->password) {
prevent_handling_two_usernames = true;
} else {
processed_field = FindField(processed_fields, prediction);
if (processed_field) {
if (!processed_field->is_password)
continue;
result->password = processed_field->field;
}
}
break;
case CredentialFieldType::kNewPassword:
// If any (and thus the first) new password comes before the current
// password, the first username is understood as sign-up, not sign-in.
if (!result->password)
sign_in_username_first = false;
// If multiple hints for new-password fields are given (e.g., because
// of more fields having the same signature), the first one should be
// marked as new-password. That way the generation can be offered
// before the user has thought of and typed their new password
// elsewhere. See https://crbug.com/902700 for more details.
if (!result->new_password) {
processed_field = FindField(processed_fields, prediction);
if (processed_field) {
if (!IsPasswordGenerationForClearTextFieldsEnabled() &&
!processed_field->is_password) {
continue;
}
result->new_password = processed_field->field;
processed_field->is_predicted_as_password = true;
}
}
break;
case CredentialFieldType::kConfirmationPassword:
processed_field = FindField(processed_fields, prediction);
if (processed_field) {
if (!IsPasswordGenerationForClearTextFieldsEnabled() &&
!processed_field->is_password) {
continue;
}
result->confirmation_password = processed_field->field;
processed_field->is_predicted_as_password = true;
}
break;
case CredentialFieldType::kNone:
break;
}
}
if (!result->new_password || !result->password)
prevent_handling_two_usernames = true;
if (!prevent_handling_two_usernames && second_username) {
// Now that there are two usernames, |sign_in_username_first| determines
// which is sign-in and which sign-up.
const FormFieldData* sign_in = result->username;
const FormFieldData* sign_up = second_username;
if (!sign_in_username_first)
std::swap(sign_in, sign_up);
// For filling, the sign-in username is relevant, because Chrome should not
// fill where the credentials first need to be created. For saving, the
// sign-up username is relevant: if both have values, then the sign-up one
// was not filled and hence was typed by the user.
result->username =
mode == FormDataParser::Mode::kSaving ? sign_up : sign_in;
}
// If the server suggests there is a confirmation field but no new password,
// something went wrong. Sanitize the result.
if (result->confirmation_password && !result->new_password)
result->confirmation_password = nullptr;
// For the use of basic heuristics, also mark CVC fields and NOT_PASSWORD
// fields as such.
for (const PasswordFieldPrediction& prediction : predictions.fields) {
ProcessedField* current_field = FindField(processed_fields, prediction);
if (!current_field)
continue;
if (prediction.type == autofill::CREDIT_CARD_VERIFICATION_CODE ||
prediction.type == autofill::NOT_PASSWORD) {
current_field->server_hints_not_password = true;
} else if (prediction.type == autofill::NOT_USERNAME) {
current_field->server_hints_not_username = true;
}
}
}
// Looks for autocomplete attributes in |processed_fields| and saves predictions
// to |result|. Assumption on the usage autocomplete attributes:
// 1. Not more than 1 field with autocomplete=username.
// 2. Not more than 1 field with autocomplete=current-password.
// 3. Not more than 2 fields with autocomplete=new-password.
// 4. Only password fields have "*-password" attribute and only non-password
// fields have the "username" attribute.
// If any assumption is violated, the autocomplete attribute is ignored.
void ParseUsingAutocomplete(const std::vector<ProcessedField>& processed_fields,
SignificantFields* result) {
bool new_password_found_by_server = result->new_password;
const FormFieldData* field_marked_as_username = nullptr;
int username_fields_found = 0;
for (const ProcessedField& processed_field : processed_fields) {
if (IsFieldInSignificantFields(*result, processed_field.field)) {
// Skip this field because it was already chosen in previous steps.
continue;
}
switch (processed_field.autocomplete_flag) {
case AutocompleteFlag::kUsername:
if (processed_field.is_password || result->username ||
processed_field.server_hints_not_username)
continue;
username_fields_found++;
field_marked_as_username = processed_field.field;
break;
case AutocompleteFlag::kCurrentPassword:
if (!processed_field.is_password || result->password ||
processed_field.server_hints_not_password)
continue;
result->password = processed_field.field;
break;
case AutocompleteFlag::kNewPassword:
if (!processed_field.is_password || new_password_found_by_server ||
processed_field.server_hints_not_password)
continue;
// The first field with autocomplete=new-password is considered to be
// new_password and the second is confirmation_password.
if (!result->new_password)
result->new_password = processed_field.field;
else if (!result->confirmation_password)
result->confirmation_password = processed_field.field;
break;
case AutocompleteFlag::kCreditCard:
case AutocompleteFlag::kNone:
break;
}
}
if (!result->username && username_fields_found == 1)
result->username = field_marked_as_username;
}
// This computes the "likely" condition from the design https://goo.gl/ERvoEN .
// The |field| is likely to be a password if it is not a CVC field, not
// readonly, etc. |*ignored_readonly| is incremented specifically if this
// function returns false because of the |field| being readonly.
bool IsLikelyPassword(const ProcessedField& field, size_t* ignored_readonly) {
// Readonly fields can be an indication that filling is useless (e.g., the
// page might use a virtual keyboard). However, if the field was readonly
// only temporarily, that makes it still interesting for saving. The fact
// that a user typed or Chrome filled into that field in the past is an
// indicator that the readonly was only temporary.
if (field.field->is_readonly &&
!(field.field->properties_mask & (FieldPropertiesFlags::USER_TYPED |
FieldPropertiesFlags::AUTOFILLED))) {
++*ignored_readonly;
return false;
}
return !IsNotPasswordField(field);
}
// Filters the available passwords from |processed_fields| using these rules:
// (1) Passwords with Interactability below |best_interactability| are removed.
// (2) If |mode| == |kSaving|, passwords with empty values are removed.
// (3) Passwords for which IsLikelyPassword returns false are removed.
// If applying rules (1)-(3) results in a non-empty vector of password fields,
// that vector is returned. Otherwise, only rules (1) and (2) are applied and
// the result returned (even if it is empty).
// Neither of the following output parameters may be null:
// |readonly_status| will be updated according to the processing of the parsed
// fields.
// |is_fallback| is set to true if the filtering rule (3) was not used to
// obtain the result.
std::vector<const FormFieldData*> GetRelevantPasswords(
const std::vector<ProcessedField>& processed_fields,
FormDataParser::Mode mode,
Interactability best_interactability,
FormDataParser::ReadonlyPasswordFields* readonly_status,
bool* is_fallback) {
DCHECK(readonly_status);
DCHECK(is_fallback);
// Step 0: filter out all non-password fields.
std::vector<const ProcessedField*> passwords;
passwords.reserve(processed_fields.size());
for (const ProcessedField& processed_field : processed_fields) {
if (processed_field.is_password)
passwords.push_back(&processed_field);
}
if (passwords.empty())
return std::vector<const FormFieldData*>();
// These two counters are used to determine the ReadonlyPasswordFields value
// corresponding to this form.
const size_t all_passwords_seen = passwords.size();
size_t ignored_readonly = 0;
// Step 1: apply filter criterion (1).
base::EraseIf(
passwords, [best_interactability](const ProcessedField* processed_field) {
return !MatchesInteractability(*processed_field, best_interactability);
});
if (mode == FormDataParser::Mode::kSaving) {
// Step 2: apply filter criterion (2).
base::EraseIf(passwords, [](const ProcessedField* processed_field) {
return processed_field->field->value.empty();
});
}
// Step 3: apply filter criterion (3). Keep the current content of
// |passwords| though, in case it is needed for fallback.
std::vector<const ProcessedField*> filtered;
filtered.reserve(passwords.size());
std::copy_if(passwords.begin(), passwords.end(), std::back_inserter(filtered),
[&ignored_readonly](const ProcessedField* processed_field) {
return IsLikelyPassword(*processed_field, &ignored_readonly);
});
// Compute the readonly statistic for metrics.
DCHECK_LE(ignored_readonly, all_passwords_seen);
if (ignored_readonly == 0)
*readonly_status = FormDataParser::ReadonlyPasswordFields::kNoneIgnored;
else if (ignored_readonly < all_passwords_seen)
*readonly_status = FormDataParser::ReadonlyPasswordFields::kSomeIgnored;
else
*readonly_status = FormDataParser::ReadonlyPasswordFields::kAllIgnored;
// Ensure that |filtered| contains what needs to be returned...
if (filtered.empty()) {
filtered = std::move(passwords);
*is_fallback = true;
}
// ...and strip ProcessedFields down to FormFieldData.
std::vector<const FormFieldData*> result;
result.reserve(filtered.size());
for (const ProcessedField* processed_field : filtered)
result.push_back(processed_field->field);
return result;
}
// Detects different password fields from |passwords|.
void LocateSpecificPasswords(const std::vector<const FormFieldData*>& passwords,
const FormFieldData** current_password,
const FormFieldData** new_password,
const FormFieldData** confirmation_password) {
DCHECK(current_password);
DCHECK(!*current_password);
DCHECK(new_password);
DCHECK(!*new_password);
DCHECK(confirmation_password);
DCHECK(!*confirmation_password);
switch (passwords.size()) {
case 1:
*current_password = passwords[0];
break;
case 2:
if (!passwords[0]->value.empty() &&
passwords[0]->value == passwords[1]->value) {
// Two identical non-empty passwords: assume we are seeing a new
// password with a confirmation. This can be either a sign-up form or a
// password change form that does not ask for the old password.
*new_password = passwords[0];
*confirmation_password = passwords[1];
} else {
// Assume first is old password, second is new (no choice but to guess).
// If the passwords are both empty, it is impossible to tell if they
// are the old and the new one, or the new one and its confirmation. In
// that case Chrome errs on the side of filling and classifies them as
// old & new to allow filling of change password forms.
*current_password = passwords[0];
*new_password = passwords[1];
}
break;
default:
// If there are more than 3 passwords it is not very clear what this form
// it is. Consider only the first 3 passwords in such case as a
// best-effort solution.
if (!passwords[0]->value.empty() &&
passwords[0]->value == passwords[1]->value &&
passwords[0]->value == passwords[2]->value) {
// All passwords are the same. Assume that the first field is the
// current password.
*current_password = passwords[0];
} else if (passwords[1]->value == passwords[2]->value) {
// New password is the duplicated one, and comes second; or empty form
// with at least 3 password fields.
*current_password = passwords[0];
*new_password = passwords[1];
*confirmation_password = passwords[2];
} else if (passwords[0]->value == passwords[1]->value) {
// It is strange that the new password comes first, but trust more which
// fields are duplicated than the ordering of fields. Assume that
// any password fields after the new password contain sensitive
// information that isn't actually a password (security hint, SSN, etc.)
*new_password = passwords[0];
*confirmation_password = passwords[1];
} else {
// Three different passwords, or first and last match with middle
// different. No idea which is which. Let's save the first password.
// Password selection in a prompt will allow to correct the choice.
*current_password = passwords[0];
}
}
}
// Tries to find username field among text fields from |processed_fields|
// occurring before |first_relevant_password|. Returns nullptr if the username
// is not found. If |mode| is SAVING, ignores all fields with empty values.
// Ignores all fields with interactability less than |best_interactability|.
const FormFieldData* FindUsernameFieldBaseHeuristics(
const std::vector<ProcessedField>& processed_fields,
const std::vector<ProcessedField>::const_iterator& first_relevant_password,
FormDataParser::Mode mode,
Interactability best_interactability,
bool is_fallback) {
DCHECK(first_relevant_password != processed_fields.end());
// For saving filter out empty fields and fields with values which are not
// username.
const bool is_saving = mode == FormDataParser::Mode::kSaving;
// Search through the text input fields preceding |first_relevant_password|
// and find the closest one focusable and the closest one in general.
const FormFieldData* focusable_username = nullptr;
const FormFieldData* username = nullptr;
// Do reverse search to find the closest candidates preceding the password.
for (auto it = std::make_reverse_iterator(first_relevant_password);
it != processed_fields.rend(); ++it) {
if (it->is_password || it->is_predicted_as_password)
continue;
if (!MatchesInteractability(*it, best_interactability))
continue;
if (is_saving && IsProbablyNotUsername(it->field->value))
continue;
if (!is_fallback && IsNotPasswordField(*it))
continue;
if (!is_fallback && IsNotUsernameField(*it)) {
continue;
}
if (!username)
username = it->field;
if (it->field->is_focusable) {
focusable_username = it->field;
break;
}
}
return focusable_username ? focusable_username : username;
}
// A helper to return a |field|'s unique_renderer_id or
// kNotSetRendererId if |field| is null.
uint32_t ExtractUniqueId(const FormFieldData* field) {
return field ? field->unique_renderer_id : FormData::kNotSetRendererId;
}
// Tries to find the username and password fields in |processed_fields| based
// on the structure (how the fields are ordered). If |mode| is SAVING, only
// considers non-empty fields. The |found_fields| is both an input and output
// argument: if some password field and the username are already present, the
// the function exits early. If something is missing, the function tries to
// complete it. The result is stored back in |found_fields|. The best
// interactability for usernames, which depends on position of the found
// passwords as well, is returned through |username_max| to be used in other
// kinds of analysis. If password fields end up being parsed, |readonly_status|
// will be updated according to that processing.
void ParseUsingBaseHeuristics(
const std::vector<ProcessedField>& processed_fields,
FormDataParser::Mode mode,
SignificantFields* found_fields,
Interactability* username_max,
FormDataParser::ReadonlyPasswordFields* readonly_status) {
// If there is both the username and the minimal set of fields to build a
// PasswordForm, return early -- no more work to do.
if (found_fields->HasPasswords() && found_fields->username)
return;
// Will point to the password included in |found_field| which is first in the
// order of fields in |processed_fields|.
auto first_relevant_password = processed_fields.end();
if (!found_fields->HasPasswords()) {
// What is the best interactability among passwords?
Interactability password_max = Interactability::kUnlikely;
for (const ProcessedField& processed_field : processed_fields) {
if (processed_field.is_password && !IsNotPasswordField(processed_field))
password_max = std::max(password_max, processed_field.interactability);
}
// Try to find password elements (current, new, confirmation) among those
// with best interactability.
std::vector<const FormFieldData*> passwords =
GetRelevantPasswords(processed_fields, mode, password_max,
readonly_status, &found_fields->is_fallback);
if (passwords.empty())
return;
LocateSpecificPasswords(passwords, &found_fields->password,
&found_fields->new_password,
&found_fields->confirmation_password);
if (!found_fields->HasPasswords())
return;
for (auto it = processed_fields.begin(); it != processed_fields.end();
++it) {
if (it->field == passwords[0]) {
first_relevant_password = it;
break;
}
}
} else {
const uint32_t password_ids[] = {
ExtractUniqueId(found_fields->password),
ExtractUniqueId(found_fields->new_password),
ExtractUniqueId(found_fields->confirmation_password)};
for (auto it = processed_fields.begin(); it != processed_fields.end();
++it) {
if ((it->is_password || it->is_predicted_as_password) &&
base::Contains(password_ids, it->field->unique_renderer_id)) {
first_relevant_password = it;
break;
}
}
}
DCHECK(first_relevant_password != processed_fields.end());
if (found_fields->username)
return;
// What is the best interactability among text fields preceding the passwords?
*username_max = Interactability::kUnlikely;
for (auto it = processed_fields.begin(); it != first_relevant_password;
++it) {
if (!it->is_password && !IsNotPasswordField(*it))
*username_max = std::max(*username_max, it->interactability);
}
found_fields->username = FindUsernameFieldBaseHeuristics(
processed_fields, first_relevant_password, mode, *username_max,
found_fields->is_fallback);
return;
}
// Helper to get the platform specific identifier by which autofill and password
// manager refer to a field. The fuzzing infrastructure doed not run on iOS, so
// the iOS specific parts of PasswordForm are also built on fuzzer enabled
// platforms. See http://crbug.com/896594
string16 GetPlatformSpecificIdentifier(const FormFieldData& field) {
#if defined(OS_IOS)
return field.unique_id;
#else
return field.name;
#endif
}
// Set username and password fields in |password_form| based on
// |significant_fields| .
void SetFields(const SignificantFields& significant_fields,
PasswordForm* password_form) {
#if !defined(OS_IOS)
password_form->has_renderer_ids = true;
#endif
if (significant_fields.username) {
password_form->username_element =
GetPlatformSpecificIdentifier(*significant_fields.username);
password_form->username_value = GetFieldValue(*significant_fields.username);
password_form->username_element_renderer_id =
significant_fields.username->unique_renderer_id;
}
if (significant_fields.password) {
password_form->password_element =
GetPlatformSpecificIdentifier(*significant_fields.password);
password_form->password_value = GetFieldValue(*significant_fields.password);
password_form->password_element_renderer_id =
significant_fields.password->unique_renderer_id;
}
if (significant_fields.new_password) {
password_form->new_password_element =
GetPlatformSpecificIdentifier(*significant_fields.new_password);
password_form->new_password_value =
GetFieldValue(*significant_fields.new_password);
password_form->new_password_element_renderer_id =
significant_fields.new_password->unique_renderer_id;
}
if (significant_fields.confirmation_password) {
password_form->confirmation_password_element =
GetPlatformSpecificIdentifier(
*significant_fields.confirmation_password);
password_form->confirmation_password_element_renderer_id =
significant_fields.confirmation_password->unique_renderer_id;
}
}
// For each relevant field of |fields| computes additional data useful for
// parsing and wraps that in a ProcessedField. Returns the vector of all those
// ProcessedField instances, or an empty vector if there was not a single
// password field. Also, computes the vector of all password values and
// associated element names in |all_possible_passwords|, and similarly for
// usernames and |all_possible_usernames|. If |mode| is |kSaving|, fields with
// empty values are ignored.
std::vector<ProcessedField> ProcessFields(
const std::vector<FormFieldData>& fields,
autofill::ValueElementVector* all_possible_passwords,
autofill::ValueElementVector* all_possible_usernames,
FormDataParser::Mode mode) {
DCHECK(all_possible_passwords);
DCHECK(all_possible_passwords->empty());
std::vector<ProcessedField> result;
result.reserve(fields.size());
// |all_possible_passwords| should only contain each value once.
// |seen_password_values| ensures that duplicates are ignored.
std::set<base::StringPiece16> seen_password_values;
// Similarly for usernames.
std::set<base::StringPiece16> seen_username_values;
const bool consider_only_non_empty = mode == FormDataParser::Mode::kSaving;
for (const FormFieldData& field : fields) {
if (!field.IsTextInputElement())
continue;
if (consider_only_non_empty && field.value.empty())
continue;
const bool is_password = field.form_control_type == "password";
if (!field.value.empty()) {
std::set<base::StringPiece16>& seen_values =
is_password ? seen_password_values : seen_username_values;
autofill::ValueElementVector* all_possible_fields =
is_password ? all_possible_passwords : all_possible_usernames;
// Only the field name of the first occurrence is added.
auto insertion = seen_values.insert(base::StringPiece16(field.value));
if (insertion.second) {
// There was no such element in |seen_values|.
all_possible_fields->push_back({field.value, field.name});
}
}
const AutocompleteFlag flag =
ExtractAutocompleteFlag(field.autocomplete_attribute);
ProcessedField processed_field = {
.field = &field, .autocomplete_flag = flag, .is_password = is_password};
if (field.properties_mask & FieldPropertiesFlags::USER_TYPED)
processed_field.interactability = Interactability::kCertain;
else if (field.is_focusable)
processed_field.interactability = Interactability::kPossible;
result.push_back(processed_field);
}
return result;
}
// Find the first element in |username_predictions| (i.e. the most reliable
// prediction) that occurs in |processed_fields| and has interactability level
// at least |username_max|.
const FormFieldData* FindUsernameInPredictions(
const std::vector<uint32_t>& username_predictions,
const std::vector<ProcessedField>& processed_fields,
Interactability username_max) {
for (uint32_t predicted_id : username_predictions) {
auto iter = std::find_if(
processed_fields.begin(), processed_fields.end(),
[predicted_id, username_max](const ProcessedField& processed_field) {
return processed_field.field->unique_renderer_id == predicted_id &&
MatchesInteractability(processed_field, username_max);
});
if (iter != processed_fields.end()) {
return iter->field;
}
}
return nullptr;
}
// Return true if |significant_fields| has an username field and
// |form_predictions| has |may_use_prefilled_placeholder| == true for the
// username field.
bool GetMayUsePrefilledPlaceholder(
const base::Optional<FormPredictions>& form_predictions,
const SignificantFields& significant_fields) {
if (!base::FeatureList::IsEnabled(
password_manager::features::kEnableOverwritingPlaceholderUsernames))
return false;
if (!form_predictions || !significant_fields.username)
return false;
uint32_t username_id = significant_fields.username->unique_renderer_id;
for (const PasswordFieldPrediction& prediction : form_predictions->fields) {
if (prediction.renderer_id == username_id)
return prediction.may_use_prefilled_placeholder;
}
return false;
}
// Puts together a PasswordForm, the result of the parsing, based on the
// |form_data| description of the form metadata (e.g., action), the already
// parsed information about what are the |significant_fields|, the list
// |all_possible_passwords| of all non-empty password values which occurred in
// the form and their associated element names, and the list
// |all_possible_usernames| of all non-empty username values which
// occurred in the form and their associated elements. |form_predictions| is
// used to find fields that may have preffilled placeholders.
std::unique_ptr<PasswordForm> AssemblePasswordForm(
const FormData& form_data,
const SignificantFields& significant_fields,
autofill::ValueElementVector all_possible_passwords,
autofill::ValueElementVector all_possible_usernames,
const base::Optional<FormPredictions>& form_predictions) {
if (!significant_fields.HasPasswords() &&
!significant_fields.is_single_username) {
return nullptr;
}
// Create the PasswordForm and set data not related to specific fields.
auto result = std::make_unique<PasswordForm>();
result->origin = form_data.url;
result->signon_realm = GetSignonRealm(form_data.url);
result->action = form_data.action;
result->form_data = form_data;
result->all_possible_passwords = std::move(all_possible_passwords);
result->all_possible_usernames = std::move(all_possible_usernames);
result->scheme = PasswordForm::Scheme::kHtml;
result->blacklisted_by_user = false;
result->type = PasswordForm::Type::kManual;
result->username_may_use_prefilled_placeholder =
GetMayUsePrefilledPlaceholder(form_predictions, significant_fields);
result->is_new_password_reliable =
significant_fields.is_new_password_reliable;
result->only_for_fallback = significant_fields.is_fallback;
result->submission_event = form_data.submission_event;
for (const FormFieldData& field : form_data.fields) {
if (field.form_control_type == "password" &&
(field.properties_mask & FieldPropertiesFlags::AUTOFILLED)) {
result->form_has_autofilled_value = true;
}
}
// Set data related to specific fields.
SetFields(significant_fields, result.get());
return result;
}
} // namespace
FormDataParser::FormDataParser() = default;
FormDataParser::~FormDataParser() = default;
std::unique_ptr<PasswordForm> FormDataParser::Parse(const FormData& form_data,
Mode mode) {
if (form_data.fields.size() > kMaxParseableFields)
return nullptr;
readonly_status_ = ReadonlyPasswordFields::kNoHeuristics;
autofill::ValueElementVector all_possible_passwords;
autofill::ValueElementVector all_possible_usernames;
std::vector<ProcessedField> processed_fields = ProcessFields(
form_data.fields, &all_possible_passwords, &all_possible_usernames, mode);
if (processed_fields.empty())
return nullptr;
SignificantFields significant_fields;
UsernameDetectionMethod username_detection_method =
UsernameDetectionMethod::kNoUsernameDetected;
// (1) First, try to parse with server predictions.
if (predictions_) {
ParseUsingPredictions(&processed_fields, *predictions_, mode,
&significant_fields);
if (significant_fields.username) {
username_detection_method =
UsernameDetectionMethod::kServerSidePrediction;
}
}
// (2) If that failed, try to parse with autocomplete attributes.
if (!significant_fields.is_single_username) {
ParseUsingAutocomplete(processed_fields, &significant_fields);
if (username_detection_method ==
UsernameDetectionMethod::kNoUsernameDetected &&
significant_fields.username) {
username_detection_method =
UsernameDetectionMethod::kAutocompleteAttribute;
}
}
// Pass the "reliability" information to mark the new-password fields as
// eligible for automatic password generation. This only makes sense when
// forms are analysed for filling, because no passwords are generated when the
// user saves the already entered one.
if (mode == Mode::kFilling && significant_fields.new_password) {
significant_fields.is_new_password_reliable = true;
}
// (3) Now try to fill the gaps.
const bool username_found_before_heuristic = significant_fields.username;
// Try to parse with base heuristic.
if (!significant_fields.is_single_username) {
Interactability username_max = Interactability::kUnlikely;
ParseUsingBaseHeuristics(processed_fields, mode, &significant_fields,
&username_max, &readonly_status_);
if (username_detection_method ==
UsernameDetectionMethod::kNoUsernameDetected &&
significant_fields.username) {
username_detection_method = UsernameDetectionMethod::kBaseHeuristic;
}
// Additionally, and based on the best interactability computed by base
// heuristics, try to improve the username based on the context of the
// fields, unless the username already came from more reliable types of
// analysis.
if (!username_found_before_heuristic) {
const FormFieldData* username_field_by_context =
FindUsernameInPredictions(form_data.username_predictions,
processed_fields, username_max);
if (username_field_by_context &&
!(mode == FormDataParser::Mode::kSaving &&
username_field_by_context->value.empty())) {
significant_fields.username = username_field_by_context;
if (username_detection_method ==
UsernameDetectionMethod::kNoUsernameDetected ||
username_detection_method ==
UsernameDetectionMethod::kBaseHeuristic) {
username_detection_method =
UsernameDetectionMethod::kHtmlBasedClassifier;
}
}
}
}
UMA_HISTOGRAM_ENUMERATION("PasswordManager.UsernameDetectionMethod",
username_detection_method,
UsernameDetectionMethod::kCount);
return AssemblePasswordForm(form_data, significant_fields,
std::move(all_possible_passwords),
std::move(all_possible_usernames), predictions_);
}
std::string GetSignonRealm(const GURL& url) {
GURL::Replacements rep;
rep.ClearUsername();
rep.ClearPassword();
rep.ClearQuery();
rep.ClearRef();
rep.SetPathStr(std::string());
return url.ReplaceComponents(rep).spec();
}
} // namespace password_manager
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
3c27d977fdf5c373f267ae76d2d49754772be786 | ef68b62f4a1dd2e26e26ef2fc67e18f8fbe96418 | /libs/cgv_gl/gl/gl_transparent_renderer.h | 88251550bc6004034536970a1d4bc36c17e55f70 | [] | no_license | lintianfang/cleaning_cobotics | 68d9a4b418cdadab9dde1c24f529f45e7fc3bd4f | 26ccba618aec0b1176fcfc889e95ed5320ccbe75 | refs/heads/master | 2023-02-25T21:36:10.777059 | 2021-01-29T09:49:16 | 2021-01-29T09:49:16 | 281,898,712 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,781 | h | #pragma once
#include <cgv/render/texture.h>
#include <cgv/render/frame_buffer.h>
#include "gl_depth_peeler.h"
#include "lib_begin.h"
namespace cgv {
namespace render {
namespace gl {
/** OpenGL helper class to simplify transparent rendering. It is derived from a depth peeler whose functionality
is used for the visibility sorting according to the approach described in the "order independent transparency"
paper of Cass Everit. Call the init method after your OpenGL
context has been created. Transparent rendering is done such that the rendered objects are blended
over the rendered scene in the current color and depth buffer. Rendering of transparent objects
should be done in the finish_frame method of a drawable. A sample implementation looks like this:
\code
// in init
\endcode
*/
class CGV_API gl_transparent_renderer : public gl_depth_peeler
{
protected:
/// depth peeler used for visibility sorting
gl_depth_peeler peeler;
// depth texture used as depth buffer used in offline rendering
texture depth_buffer;
// texture to store the peeled layers, which is used as color buffer in offline rendering and as texture during blending
texture layer_tex;
/// texture used as color buffer in front to back mode to blend together all transparent layers before blending the result over the current color buffer
texture color_tex;
// frame buffer object used for offline rendering of the layers
frame_buffer fb;
/// ensure that texture has the correct dimensions and is created
void create_and_attach_texture(context& ctx, texture& tex, int w, int h, int i = -1);
/// renders the given texture over the current viewport
void blend_texture_over_viewport(context& ctx, texture& tex);
public:
/// a string that contains the last error, which is only set by the init method
mutable std::string last_error;
/// signal called to render the transparent content for first layer without additional depth test
cgv::signal::signal<context&> render_callback;
/// signal called to render the transparent content for second and further layers with additional depth test against texture given in second argument
cgv::signal::signal<context&,texture&> render_callback_2;
/// construct uninitialized depth peeler
gl_transparent_renderer(bool front_to_back = true, float _depth_bias = 0.001);
/// checks for extensions and init depth peeler, return success
bool init(context& ctx);
/// configure frame buffer and textures
void init_frame(context& ctx);
/// perform transparent rendering by considering a maximum of the specified number of depth layers
int render_transparent(context& ctx, int max_nr_layers, int tex_unit = -1);
/// destruct the transparent renderer
void destruct(context& ctx);
};
}
}
}
#include <cgv/config/lib_end.h>
| [
"tianfang.lin@tu-dresden.de"
] | tianfang.lin@tu-dresden.de |
139a046a79ed335d7327c15ddc4821868c285582 | 1eee1c3d2d376b39884012ca99e8c002a410fa92 | /Code/3100-3199/3164.cpp | 35de052c327ed6f12d204554d094ecb677c7d4d3 | [] | no_license | Ienu/ExerciseEveryday | 7ceb85d69f6ce4518ea7da75868585acab755650 | 458a39561594a4504a806199ff5c43adcbcdb7ee | refs/heads/master | 2020-03-15T18:50:48.158822 | 2018-09-30T08:14:21 | 2018-09-30T08:14:21 | 132,293,599 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 346 | cpp | #include <iostream>
#include <algorithm>
using namespace std;
int main() {
int a[10], i;
for (i = 0; i < 10; ++i) {
cin >> a[i];
}
sort(a, a + 10);
for (i = 0; i < 10; ++i) {
if (a[i] % 2 == 1) {
cout << a[i] << " ";
}
}
for (i = 0; i < 10; ++i) {
if (a[i] % 2 == 0) {
cout << a[i] << " ";
}
}
cout << endl;
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
5effa2fca03c20f2f277f501f47f289fb905345b | 792e697ba0f9c11ef10b7de81edb1161a5580cfb | /lib/IR/Instructions.cpp | 7798af3b19b99a75dd817fa6fc307db788e27e1f | [
"NCSA",
"LLVM-exception",
"Apache-2.0"
] | permissive | opencor/llvmclang | 9eb76cb6529b6a3aab2e6cd266ef9751b644f753 | 63b45a7928f2a8ff823db51648102ea4822b74a6 | refs/heads/master | 2023-08-26T04:52:56.472505 | 2022-11-02T04:35:46 | 2022-11-03T03:55:06 | 115,094,625 | 0 | 1 | Apache-2.0 | 2021-08-12T22:29:21 | 2017-12-22T08:29:14 | LLVM | UTF-8 | C++ | false | false | 180,683 | cpp | //===- Instructions.cpp - Implement the LLVM instructions -----------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements all of the non-inline methods for the LLVM instruction
// classes.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/Instructions.h"
#include "LLVMContextImpl.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Twine.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Value.h"
#include "llvm/Support/AtomicOrdering.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/TypeSize.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <vector>
using namespace llvm;
static cl::opt<bool> DisableI2pP2iOpt(
"disable-i2p-p2i-opt", cl::init(false),
cl::desc("Disables inttoptr/ptrtoint roundtrip optimization"));
//===----------------------------------------------------------------------===//
// AllocaInst Class
//===----------------------------------------------------------------------===//
Optional<TypeSize>
AllocaInst::getAllocationSizeInBits(const DataLayout &DL) const {
TypeSize Size = DL.getTypeAllocSizeInBits(getAllocatedType());
if (isArrayAllocation()) {
auto *C = dyn_cast<ConstantInt>(getArraySize());
if (!C)
return None;
assert(!Size.isScalable() && "Array elements cannot have a scalable size");
Size *= C->getZExtValue();
}
return Size;
}
//===----------------------------------------------------------------------===//
// SelectInst Class
//===----------------------------------------------------------------------===//
/// areInvalidOperands - Return a string if the specified operands are invalid
/// for a select operation, otherwise return null.
const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
if (Op1->getType() != Op2->getType())
return "both values to select must have same type";
if (Op1->getType()->isTokenTy())
return "select values cannot have token type";
if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
// Vector select.
if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
return "vector select condition element type must be i1";
VectorType *ET = dyn_cast<VectorType>(Op1->getType());
if (!ET)
return "selected values for vector select must be vectors";
if (ET->getElementCount() != VT->getElementCount())
return "vector select requires selected vectors to have "
"the same vector length as select condition";
} else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
return "select condition must be i1 or <n x i1>";
}
return nullptr;
}
//===----------------------------------------------------------------------===//
// PHINode Class
//===----------------------------------------------------------------------===//
PHINode::PHINode(const PHINode &PN)
: Instruction(PN.getType(), Instruction::PHI, nullptr, PN.getNumOperands()),
ReservedSpace(PN.getNumOperands()) {
allocHungoffUses(PN.getNumOperands());
std::copy(PN.op_begin(), PN.op_end(), op_begin());
std::copy(PN.block_begin(), PN.block_end(), block_begin());
SubclassOptionalData = PN.SubclassOptionalData;
}
// removeIncomingValue - Remove an incoming value. This is useful if a
// predecessor basic block is deleted.
Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
Value *Removed = getIncomingValue(Idx);
// Move everything after this operand down.
//
// FIXME: we could just swap with the end of the list, then erase. However,
// clients might not expect this to happen. The code as it is thrashes the
// use/def lists, which is kinda lame.
std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx);
std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx);
// Nuke the last value.
Op<-1>().set(nullptr);
setNumHungOffUseOperands(getNumOperands() - 1);
// If the PHI node is dead, because it has zero entries, nuke it now.
if (getNumOperands() == 0 && DeletePHIIfEmpty) {
// If anyone is using this PHI, make them use a dummy value instead...
replaceAllUsesWith(UndefValue::get(getType()));
eraseFromParent();
}
return Removed;
}
/// growOperands - grow operands - This grows the operand list in response
/// to a push_back style of operation. This grows the number of ops by 1.5
/// times.
///
void PHINode::growOperands() {
unsigned e = getNumOperands();
unsigned NumOps = e + e / 2;
if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common.
ReservedSpace = NumOps;
growHungoffUses(ReservedSpace, /* IsPhi */ true);
}
/// hasConstantValue - If the specified PHI node always merges together the same
/// value, return the value, otherwise return null.
Value *PHINode::hasConstantValue() const {
// Exploit the fact that phi nodes always have at least one entry.
Value *ConstantValue = getIncomingValue(0);
for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) {
if (ConstantValue != this)
return nullptr; // Incoming values not all the same.
// The case where the first value is this PHI.
ConstantValue = getIncomingValue(i);
}
if (ConstantValue == this)
return UndefValue::get(getType());
return ConstantValue;
}
/// hasConstantOrUndefValue - Whether the specified PHI node always merges
/// together the same value, assuming that undefs result in the same value as
/// non-undefs.
/// Unlike \ref hasConstantValue, this does not return a value because the
/// unique non-undef incoming value need not dominate the PHI node.
bool PHINode::hasConstantOrUndefValue() const {
Value *ConstantValue = nullptr;
for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i) {
Value *Incoming = getIncomingValue(i);
if (Incoming != this && !isa<UndefValue>(Incoming)) {
if (ConstantValue && ConstantValue != Incoming)
return false;
ConstantValue = Incoming;
}
}
return true;
}
//===----------------------------------------------------------------------===//
// LandingPadInst Implementation
//===----------------------------------------------------------------------===//
LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
const Twine &NameStr, Instruction *InsertBefore)
: Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertBefore) {
init(NumReservedValues, NameStr);
}
LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
const Twine &NameStr, BasicBlock *InsertAtEnd)
: Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertAtEnd) {
init(NumReservedValues, NameStr);
}
LandingPadInst::LandingPadInst(const LandingPadInst &LP)
: Instruction(LP.getType(), Instruction::LandingPad, nullptr,
LP.getNumOperands()),
ReservedSpace(LP.getNumOperands()) {
allocHungoffUses(LP.getNumOperands());
Use *OL = getOperandList();
const Use *InOL = LP.getOperandList();
for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
OL[I] = InOL[I];
setCleanup(LP.isCleanup());
}
LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
const Twine &NameStr,
Instruction *InsertBefore) {
return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertBefore);
}
LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
const Twine &NameStr,
BasicBlock *InsertAtEnd) {
return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertAtEnd);
}
void LandingPadInst::init(unsigned NumReservedValues, const Twine &NameStr) {
ReservedSpace = NumReservedValues;
setNumHungOffUseOperands(0);
allocHungoffUses(ReservedSpace);
setName(NameStr);
setCleanup(false);
}
/// growOperands - grow operands - This grows the operand list in response to a
/// push_back style of operation. This grows the number of ops by 2 times.
void LandingPadInst::growOperands(unsigned Size) {
unsigned e = getNumOperands();
if (ReservedSpace >= e + Size) return;
ReservedSpace = (std::max(e, 1U) + Size / 2) * 2;
growHungoffUses(ReservedSpace);
}
void LandingPadInst::addClause(Constant *Val) {
unsigned OpNo = getNumOperands();
growOperands(1);
assert(OpNo < ReservedSpace && "Growing didn't work!");
setNumHungOffUseOperands(getNumOperands() + 1);
getOperandList()[OpNo] = Val;
}
//===----------------------------------------------------------------------===//
// CallBase Implementation
//===----------------------------------------------------------------------===//
CallBase *CallBase::Create(CallBase *CB, ArrayRef<OperandBundleDef> Bundles,
Instruction *InsertPt) {
switch (CB->getOpcode()) {
case Instruction::Call:
return CallInst::Create(cast<CallInst>(CB), Bundles, InsertPt);
case Instruction::Invoke:
return InvokeInst::Create(cast<InvokeInst>(CB), Bundles, InsertPt);
case Instruction::CallBr:
return CallBrInst::Create(cast<CallBrInst>(CB), Bundles, InsertPt);
default:
llvm_unreachable("Unknown CallBase sub-class!");
}
}
CallBase *CallBase::Create(CallBase *CI, OperandBundleDef OpB,
Instruction *InsertPt) {
SmallVector<OperandBundleDef, 2> OpDefs;
for (unsigned i = 0, e = CI->getNumOperandBundles(); i < e; ++i) {
auto ChildOB = CI->getOperandBundleAt(i);
if (ChildOB.getTagName() != OpB.getTag())
OpDefs.emplace_back(ChildOB);
}
OpDefs.emplace_back(OpB);
return CallBase::Create(CI, OpDefs, InsertPt);
}
Function *CallBase::getCaller() { return getParent()->getParent(); }
unsigned CallBase::getNumSubclassExtraOperandsDynamic() const {
assert(getOpcode() == Instruction::CallBr && "Unexpected opcode!");
return cast<CallBrInst>(this)->getNumIndirectDests() + 1;
}
bool CallBase::isIndirectCall() const {
const Value *V = getCalledOperand();
if (isa<Function>(V) || isa<Constant>(V))
return false;
return !isInlineAsm();
}
/// Tests if this call site must be tail call optimized. Only a CallInst can
/// be tail call optimized.
bool CallBase::isMustTailCall() const {
if (auto *CI = dyn_cast<CallInst>(this))
return CI->isMustTailCall();
return false;
}
/// Tests if this call site is marked as a tail call.
bool CallBase::isTailCall() const {
if (auto *CI = dyn_cast<CallInst>(this))
return CI->isTailCall();
return false;
}
Intrinsic::ID CallBase::getIntrinsicID() const {
if (auto *F = getCalledFunction())
return F->getIntrinsicID();
return Intrinsic::not_intrinsic;
}
bool CallBase::isReturnNonNull() const {
if (hasRetAttr(Attribute::NonNull))
return true;
if (getRetDereferenceableBytes() > 0 &&
!NullPointerIsDefined(getCaller(), getType()->getPointerAddressSpace()))
return true;
return false;
}
Value *CallBase::getReturnedArgOperand() const {
unsigned Index;
if (Attrs.hasAttrSomewhere(Attribute::Returned, &Index))
return getArgOperand(Index - AttributeList::FirstArgIndex);
if (const Function *F = getCalledFunction())
if (F->getAttributes().hasAttrSomewhere(Attribute::Returned, &Index))
return getArgOperand(Index - AttributeList::FirstArgIndex);
return nullptr;
}
/// Determine whether the argument or parameter has the given attribute.
bool CallBase::paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const {
assert(ArgNo < arg_size() && "Param index out of bounds!");
if (Attrs.hasParamAttr(ArgNo, Kind))
return true;
if (const Function *F = getCalledFunction())
return F->getAttributes().hasParamAttr(ArgNo, Kind);
return false;
}
bool CallBase::hasFnAttrOnCalledFunction(Attribute::AttrKind Kind) const {
Value *V = getCalledOperand();
if (auto *CE = dyn_cast<ConstantExpr>(V))
if (CE->getOpcode() == BitCast)
V = CE->getOperand(0);
if (auto *F = dyn_cast<Function>(V))
return F->getAttributes().hasFnAttr(Kind);
return false;
}
bool CallBase::hasFnAttrOnCalledFunction(StringRef Kind) const {
Value *V = getCalledOperand();
if (auto *CE = dyn_cast<ConstantExpr>(V))
if (CE->getOpcode() == BitCast)
V = CE->getOperand(0);
if (auto *F = dyn_cast<Function>(V))
return F->getAttributes().hasFnAttr(Kind);
return false;
}
void CallBase::getOperandBundlesAsDefs(
SmallVectorImpl<OperandBundleDef> &Defs) const {
for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
Defs.emplace_back(getOperandBundleAt(i));
}
CallBase::op_iterator
CallBase::populateBundleOperandInfos(ArrayRef<OperandBundleDef> Bundles,
const unsigned BeginIndex) {
auto It = op_begin() + BeginIndex;
for (auto &B : Bundles)
It = std::copy(B.input_begin(), B.input_end(), It);
auto *ContextImpl = getContext().pImpl;
auto BI = Bundles.begin();
unsigned CurrentIndex = BeginIndex;
for (auto &BOI : bundle_op_infos()) {
assert(BI != Bundles.end() && "Incorrect allocation?");
BOI.Tag = ContextImpl->getOrInsertBundleTag(BI->getTag());
BOI.Begin = CurrentIndex;
BOI.End = CurrentIndex + BI->input_size();
CurrentIndex = BOI.End;
BI++;
}
assert(BI == Bundles.end() && "Incorrect allocation?");
return It;
}
CallBase::BundleOpInfo &CallBase::getBundleOpInfoForOperand(unsigned OpIdx) {
/// When there isn't many bundles, we do a simple linear search.
/// Else fallback to a binary-search that use the fact that bundles usually
/// have similar number of argument to get faster convergence.
if (bundle_op_info_end() - bundle_op_info_begin() < 8) {
for (auto &BOI : bundle_op_infos())
if (BOI.Begin <= OpIdx && OpIdx < BOI.End)
return BOI;
llvm_unreachable("Did not find operand bundle for operand!");
}
assert(OpIdx >= arg_size() && "the Idx is not in the operand bundles");
assert(bundle_op_info_end() - bundle_op_info_begin() > 0 &&
OpIdx < std::prev(bundle_op_info_end())->End &&
"The Idx isn't in the operand bundle");
/// We need a decimal number below and to prevent using floating point numbers
/// we use an intergal value multiplied by this constant.
constexpr unsigned NumberScaling = 1024;
bundle_op_iterator Begin = bundle_op_info_begin();
bundle_op_iterator End = bundle_op_info_end();
bundle_op_iterator Current = Begin;
while (Begin != End) {
unsigned ScaledOperandPerBundle =
NumberScaling * (std::prev(End)->End - Begin->Begin) / (End - Begin);
Current = Begin + (((OpIdx - Begin->Begin) * NumberScaling) /
ScaledOperandPerBundle);
if (Current >= End)
Current = std::prev(End);
assert(Current < End && Current >= Begin &&
"the operand bundle doesn't cover every value in the range");
if (OpIdx >= Current->Begin && OpIdx < Current->End)
break;
if (OpIdx >= Current->End)
Begin = Current + 1;
else
End = Current;
}
assert(OpIdx >= Current->Begin && OpIdx < Current->End &&
"the operand bundle doesn't cover every value in the range");
return *Current;
}
CallBase *CallBase::addOperandBundle(CallBase *CB, uint32_t ID,
OperandBundleDef OB,
Instruction *InsertPt) {
if (CB->getOperandBundle(ID))
return CB;
SmallVector<OperandBundleDef, 1> Bundles;
CB->getOperandBundlesAsDefs(Bundles);
Bundles.push_back(OB);
return Create(CB, Bundles, InsertPt);
}
CallBase *CallBase::removeOperandBundle(CallBase *CB, uint32_t ID,
Instruction *InsertPt) {
SmallVector<OperandBundleDef, 1> Bundles;
bool CreateNew = false;
for (unsigned I = 0, E = CB->getNumOperandBundles(); I != E; ++I) {
auto Bundle = CB->getOperandBundleAt(I);
if (Bundle.getTagID() == ID) {
CreateNew = true;
continue;
}
Bundles.emplace_back(Bundle);
}
return CreateNew ? Create(CB, Bundles, InsertPt) : CB;
}
bool CallBase::hasReadingOperandBundles() const {
// Implementation note: this is a conservative implementation of operand
// bundle semantics, where *any* non-assume operand bundle forces a callsite
// to be at least readonly.
return hasOperandBundles() && getIntrinsicID() != Intrinsic::assume;
}
//===----------------------------------------------------------------------===//
// CallInst Implementation
//===----------------------------------------------------------------------===//
void CallInst::init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) {
this->FTy = FTy;
assert(getNumOperands() == Args.size() + CountBundleInputs(Bundles) + 1 &&
"NumOperands not set up?");
#ifndef NDEBUG
assert((Args.size() == FTy->getNumParams() ||
(FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
"Calling a function with bad signature!");
for (unsigned i = 0; i != Args.size(); ++i)
assert((i >= FTy->getNumParams() ||
FTy->getParamType(i) == Args[i]->getType()) &&
"Calling a function with a bad signature!");
#endif
// Set operands in order of their index to match use-list-order
// prediction.
llvm::copy(Args, op_begin());
setCalledOperand(Func);
auto It = populateBundleOperandInfos(Bundles, Args.size());
(void)It;
assert(It + 1 == op_end() && "Should add up!");
setName(NameStr);
}
void CallInst::init(FunctionType *FTy, Value *Func, const Twine &NameStr) {
this->FTy = FTy;
assert(getNumOperands() == 1 && "NumOperands not set up?");
setCalledOperand(Func);
assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
setName(NameStr);
}
CallInst::CallInst(FunctionType *Ty, Value *Func, const Twine &Name,
Instruction *InsertBefore)
: CallBase(Ty->getReturnType(), Instruction::Call,
OperandTraits<CallBase>::op_end(this) - 1, 1, InsertBefore) {
init(Ty, Func, Name);
}
CallInst::CallInst(FunctionType *Ty, Value *Func, const Twine &Name,
BasicBlock *InsertAtEnd)
: CallBase(Ty->getReturnType(), Instruction::Call,
OperandTraits<CallBase>::op_end(this) - 1, 1, InsertAtEnd) {
init(Ty, Func, Name);
}
CallInst::CallInst(const CallInst &CI)
: CallBase(CI.Attrs, CI.FTy, CI.getType(), Instruction::Call,
OperandTraits<CallBase>::op_end(this) - CI.getNumOperands(),
CI.getNumOperands()) {
setTailCallKind(CI.getTailCallKind());
setCallingConv(CI.getCallingConv());
std::copy(CI.op_begin(), CI.op_end(), op_begin());
std::copy(CI.bundle_op_info_begin(), CI.bundle_op_info_end(),
bundle_op_info_begin());
SubclassOptionalData = CI.SubclassOptionalData;
}
CallInst *CallInst::Create(CallInst *CI, ArrayRef<OperandBundleDef> OpB,
Instruction *InsertPt) {
std::vector<Value *> Args(CI->arg_begin(), CI->arg_end());
auto *NewCI = CallInst::Create(CI->getFunctionType(), CI->getCalledOperand(),
Args, OpB, CI->getName(), InsertPt);
NewCI->setTailCallKind(CI->getTailCallKind());
NewCI->setCallingConv(CI->getCallingConv());
NewCI->SubclassOptionalData = CI->SubclassOptionalData;
NewCI->setAttributes(CI->getAttributes());
NewCI->setDebugLoc(CI->getDebugLoc());
return NewCI;
}
// Update profile weight for call instruction by scaling it using the ratio
// of S/T. The meaning of "branch_weights" meta data for call instruction is
// transfered to represent call count.
void CallInst::updateProfWeight(uint64_t S, uint64_t T) {
auto *ProfileData = getMetadata(LLVMContext::MD_prof);
if (ProfileData == nullptr)
return;
auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
if (!ProfDataName || (!ProfDataName->getString().equals("branch_weights") &&
!ProfDataName->getString().equals("VP")))
return;
if (T == 0) {
LLVM_DEBUG(dbgs() << "Attempting to update profile weights will result in "
"div by 0. Ignoring. Likely the function "
<< getParent()->getParent()->getName()
<< " has 0 entry count, and contains call instructions "
"with non-zero prof info.");
return;
}
MDBuilder MDB(getContext());
SmallVector<Metadata *, 3> Vals;
Vals.push_back(ProfileData->getOperand(0));
APInt APS(128, S), APT(128, T);
if (ProfDataName->getString().equals("branch_weights") &&
ProfileData->getNumOperands() > 0) {
// Using APInt::div may be expensive, but most cases should fit 64 bits.
APInt Val(128, mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1))
->getValue()
.getZExtValue());
Val *= APS;
Vals.push_back(MDB.createConstant(
ConstantInt::get(Type::getInt32Ty(getContext()),
Val.udiv(APT).getLimitedValue(UINT32_MAX))));
} else if (ProfDataName->getString().equals("VP"))
for (unsigned i = 1; i < ProfileData->getNumOperands(); i += 2) {
// The first value is the key of the value profile, which will not change.
Vals.push_back(ProfileData->getOperand(i));
uint64_t Count =
mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(i + 1))
->getValue()
.getZExtValue();
// Don't scale the magic number.
if (Count == NOMORE_ICP_MAGICNUM) {
Vals.push_back(ProfileData->getOperand(i + 1));
continue;
}
// Using APInt::div may be expensive, but most cases should fit 64 bits.
APInt Val(128, Count);
Val *= APS;
Vals.push_back(MDB.createConstant(
ConstantInt::get(Type::getInt64Ty(getContext()),
Val.udiv(APT).getLimitedValue())));
}
setMetadata(LLVMContext::MD_prof, MDNode::get(getContext(), Vals));
}
/// IsConstantOne - Return true only if val is constant int 1
static bool IsConstantOne(Value *val) {
assert(val && "IsConstantOne does not work with nullptr val");
const ConstantInt *CVal = dyn_cast<ConstantInt>(val);
return CVal && CVal->isOne();
}
static Instruction *createMalloc(Instruction *InsertBefore,
BasicBlock *InsertAtEnd, Type *IntPtrTy,
Type *AllocTy, Value *AllocSize,
Value *ArraySize,
ArrayRef<OperandBundleDef> OpB,
Function *MallocF, const Twine &Name) {
assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
"createMalloc needs either InsertBefore or InsertAtEnd");
// malloc(type) becomes:
// bitcast (i8* malloc(typeSize)) to type*
// malloc(type, arraySize) becomes:
// bitcast (i8* malloc(typeSize*arraySize)) to type*
if (!ArraySize)
ArraySize = ConstantInt::get(IntPtrTy, 1);
else if (ArraySize->getType() != IntPtrTy) {
if (InsertBefore)
ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
"", InsertBefore);
else
ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
"", InsertAtEnd);
}
if (!IsConstantOne(ArraySize)) {
if (IsConstantOne(AllocSize)) {
AllocSize = ArraySize; // Operand * 1 = Operand
} else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
false /*ZExt*/);
// Malloc arg is constant product of type size and array size
AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
} else {
// Multiply type size by the array size...
if (InsertBefore)
AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
"mallocsize", InsertBefore);
else
AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
"mallocsize", InsertAtEnd);
}
}
assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
// Create the call to Malloc.
BasicBlock *BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
Module *M = BB->getParent()->getParent();
Type *BPTy = Type::getInt8PtrTy(BB->getContext());
FunctionCallee MallocFunc = MallocF;
if (!MallocFunc)
// prototype malloc as "void *malloc(size_t)"
MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy);
PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
CallInst *MCall = nullptr;
Instruction *Result = nullptr;
if (InsertBefore) {
MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall",
InsertBefore);
Result = MCall;
if (Result->getType() != AllocPtrType)
// Create a cast instruction to convert to the right type...
Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
} else {
MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall");
Result = MCall;
if (Result->getType() != AllocPtrType) {
InsertAtEnd->getInstList().push_back(MCall);
// Create a cast instruction to convert to the right type...
Result = new BitCastInst(MCall, AllocPtrType, Name);
}
}
MCall->setTailCall();
if (Function *F = dyn_cast<Function>(MallocFunc.getCallee())) {
MCall->setCallingConv(F->getCallingConv());
if (!F->returnDoesNotAlias())
F->setReturnDoesNotAlias();
}
assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
return Result;
}
/// CreateMalloc - Generate the IR for a call to malloc:
/// 1. Compute the malloc call's argument as the specified type's size,
/// possibly multiplied by the array size if the array size is not
/// constant 1.
/// 2. Call malloc with that argument.
/// 3. Bitcast the result of the malloc call to the specified type.
Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
Type *IntPtrTy, Type *AllocTy,
Value *AllocSize, Value *ArraySize,
Function *MallocF,
const Twine &Name) {
return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize,
ArraySize, None, MallocF, Name);
}
Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
Type *IntPtrTy, Type *AllocTy,
Value *AllocSize, Value *ArraySize,
ArrayRef<OperandBundleDef> OpB,
Function *MallocF,
const Twine &Name) {
return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize,
ArraySize, OpB, MallocF, Name);
}
/// CreateMalloc - Generate the IR for a call to malloc:
/// 1. Compute the malloc call's argument as the specified type's size,
/// possibly multiplied by the array size if the array size is not
/// constant 1.
/// 2. Call malloc with that argument.
/// 3. Bitcast the result of the malloc call to the specified type.
/// Note: This function does not add the bitcast to the basic block, that is the
/// responsibility of the caller.
Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
Type *IntPtrTy, Type *AllocTy,
Value *AllocSize, Value *ArraySize,
Function *MallocF, const Twine &Name) {
return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
ArraySize, None, MallocF, Name);
}
Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
Type *IntPtrTy, Type *AllocTy,
Value *AllocSize, Value *ArraySize,
ArrayRef<OperandBundleDef> OpB,
Function *MallocF, const Twine &Name) {
return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
ArraySize, OpB, MallocF, Name);
}
static Instruction *createFree(Value *Source,
ArrayRef<OperandBundleDef> Bundles,
Instruction *InsertBefore,
BasicBlock *InsertAtEnd) {
assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
"createFree needs either InsertBefore or InsertAtEnd");
assert(Source->getType()->isPointerTy() &&
"Can not free something of nonpointer type!");
BasicBlock *BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
Module *M = BB->getParent()->getParent();
Type *VoidTy = Type::getVoidTy(M->getContext());
Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
// prototype free as "void free(void*)"
FunctionCallee FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy);
CallInst *Result = nullptr;
Value *PtrCast = Source;
if (InsertBefore) {
if (Source->getType() != IntPtrTy)
PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
Result = CallInst::Create(FreeFunc, PtrCast, Bundles, "", InsertBefore);
} else {
if (Source->getType() != IntPtrTy)
PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
Result = CallInst::Create(FreeFunc, PtrCast, Bundles, "");
}
Result->setTailCall();
if (Function *F = dyn_cast<Function>(FreeFunc.getCallee()))
Result->setCallingConv(F->getCallingConv());
return Result;
}
/// CreateFree - Generate the IR for a call to the builtin free function.
Instruction *CallInst::CreateFree(Value *Source, Instruction *InsertBefore) {
return createFree(Source, None, InsertBefore, nullptr);
}
Instruction *CallInst::CreateFree(Value *Source,
ArrayRef<OperandBundleDef> Bundles,
Instruction *InsertBefore) {
return createFree(Source, Bundles, InsertBefore, nullptr);
}
/// CreateFree - Generate the IR for a call to the builtin free function.
/// Note: This function does not add the call to the basic block, that is the
/// responsibility of the caller.
Instruction *CallInst::CreateFree(Value *Source, BasicBlock *InsertAtEnd) {
Instruction *FreeCall = createFree(Source, None, nullptr, InsertAtEnd);
assert(FreeCall && "CreateFree did not create a CallInst");
return FreeCall;
}
Instruction *CallInst::CreateFree(Value *Source,
ArrayRef<OperandBundleDef> Bundles,
BasicBlock *InsertAtEnd) {
Instruction *FreeCall = createFree(Source, Bundles, nullptr, InsertAtEnd);
assert(FreeCall && "CreateFree did not create a CallInst");
return FreeCall;
}
//===----------------------------------------------------------------------===//
// InvokeInst Implementation
//===----------------------------------------------------------------------===//
void InvokeInst::init(FunctionType *FTy, Value *Fn, BasicBlock *IfNormal,
BasicBlock *IfException, ArrayRef<Value *> Args,
ArrayRef<OperandBundleDef> Bundles,
const Twine &NameStr) {
this->FTy = FTy;
assert((int)getNumOperands() ==
ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)) &&
"NumOperands not set up?");
#ifndef NDEBUG
assert(((Args.size() == FTy->getNumParams()) ||
(FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
"Invoking a function with bad signature");
for (unsigned i = 0, e = Args.size(); i != e; i++)
assert((i >= FTy->getNumParams() ||
FTy->getParamType(i) == Args[i]->getType()) &&
"Invoking a function with a bad signature!");
#endif
// Set operands in order of their index to match use-list-order
// prediction.
llvm::copy(Args, op_begin());
setNormalDest(IfNormal);
setUnwindDest(IfException);
setCalledOperand(Fn);
auto It = populateBundleOperandInfos(Bundles, Args.size());
(void)It;
assert(It + 3 == op_end() && "Should add up!");
setName(NameStr);
}
InvokeInst::InvokeInst(const InvokeInst &II)
: CallBase(II.Attrs, II.FTy, II.getType(), Instruction::Invoke,
OperandTraits<CallBase>::op_end(this) - II.getNumOperands(),
II.getNumOperands()) {
setCallingConv(II.getCallingConv());
std::copy(II.op_begin(), II.op_end(), op_begin());
std::copy(II.bundle_op_info_begin(), II.bundle_op_info_end(),
bundle_op_info_begin());
SubclassOptionalData = II.SubclassOptionalData;
}
InvokeInst *InvokeInst::Create(InvokeInst *II, ArrayRef<OperandBundleDef> OpB,
Instruction *InsertPt) {
std::vector<Value *> Args(II->arg_begin(), II->arg_end());
auto *NewII = InvokeInst::Create(
II->getFunctionType(), II->getCalledOperand(), II->getNormalDest(),
II->getUnwindDest(), Args, OpB, II->getName(), InsertPt);
NewII->setCallingConv(II->getCallingConv());
NewII->SubclassOptionalData = II->SubclassOptionalData;
NewII->setAttributes(II->getAttributes());
NewII->setDebugLoc(II->getDebugLoc());
return NewII;
}
LandingPadInst *InvokeInst::getLandingPadInst() const {
return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
}
//===----------------------------------------------------------------------===//
// CallBrInst Implementation
//===----------------------------------------------------------------------===//
void CallBrInst::init(FunctionType *FTy, Value *Fn, BasicBlock *Fallthrough,
ArrayRef<BasicBlock *> IndirectDests,
ArrayRef<Value *> Args,
ArrayRef<OperandBundleDef> Bundles,
const Twine &NameStr) {
this->FTy = FTy;
assert((int)getNumOperands() ==
ComputeNumOperands(Args.size(), IndirectDests.size(),
CountBundleInputs(Bundles)) &&
"NumOperands not set up?");
#ifndef NDEBUG
assert(((Args.size() == FTy->getNumParams()) ||
(FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
"Calling a function with bad signature");
for (unsigned i = 0, e = Args.size(); i != e; i++)
assert((i >= FTy->getNumParams() ||
FTy->getParamType(i) == Args[i]->getType()) &&
"Calling a function with a bad signature!");
#endif
// Set operands in order of their index to match use-list-order
// prediction.
std::copy(Args.begin(), Args.end(), op_begin());
NumIndirectDests = IndirectDests.size();
setDefaultDest(Fallthrough);
for (unsigned i = 0; i != NumIndirectDests; ++i)
setIndirectDest(i, IndirectDests[i]);
setCalledOperand(Fn);
auto It = populateBundleOperandInfos(Bundles, Args.size());
(void)It;
assert(It + 2 + IndirectDests.size() == op_end() && "Should add up!");
setName(NameStr);
}
void CallBrInst::updateArgBlockAddresses(unsigned i, BasicBlock *B) {
assert(getNumIndirectDests() > i && "IndirectDest # out of range for callbr");
if (BasicBlock *OldBB = getIndirectDest(i)) {
BlockAddress *Old = BlockAddress::get(OldBB);
BlockAddress *New = BlockAddress::get(B);
for (unsigned ArgNo = 0, e = arg_size(); ArgNo != e; ++ArgNo)
if (dyn_cast<BlockAddress>(getArgOperand(ArgNo)) == Old)
setArgOperand(ArgNo, New);
}
}
CallBrInst::CallBrInst(const CallBrInst &CBI)
: CallBase(CBI.Attrs, CBI.FTy, CBI.getType(), Instruction::CallBr,
OperandTraits<CallBase>::op_end(this) - CBI.getNumOperands(),
CBI.getNumOperands()) {
setCallingConv(CBI.getCallingConv());
std::copy(CBI.op_begin(), CBI.op_end(), op_begin());
std::copy(CBI.bundle_op_info_begin(), CBI.bundle_op_info_end(),
bundle_op_info_begin());
SubclassOptionalData = CBI.SubclassOptionalData;
NumIndirectDests = CBI.NumIndirectDests;
}
CallBrInst *CallBrInst::Create(CallBrInst *CBI, ArrayRef<OperandBundleDef> OpB,
Instruction *InsertPt) {
std::vector<Value *> Args(CBI->arg_begin(), CBI->arg_end());
auto *NewCBI = CallBrInst::Create(
CBI->getFunctionType(), CBI->getCalledOperand(), CBI->getDefaultDest(),
CBI->getIndirectDests(), Args, OpB, CBI->getName(), InsertPt);
NewCBI->setCallingConv(CBI->getCallingConv());
NewCBI->SubclassOptionalData = CBI->SubclassOptionalData;
NewCBI->setAttributes(CBI->getAttributes());
NewCBI->setDebugLoc(CBI->getDebugLoc());
NewCBI->NumIndirectDests = CBI->NumIndirectDests;
return NewCBI;
}
//===----------------------------------------------------------------------===//
// ReturnInst Implementation
//===----------------------------------------------------------------------===//
ReturnInst::ReturnInst(const ReturnInst &RI)
: Instruction(Type::getVoidTy(RI.getContext()), Instruction::Ret,
OperandTraits<ReturnInst>::op_end(this) - RI.getNumOperands(),
RI.getNumOperands()) {
if (RI.getNumOperands())
Op<0>() = RI.Op<0>();
SubclassOptionalData = RI.SubclassOptionalData;
}
ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
: Instruction(Type::getVoidTy(C), Instruction::Ret,
OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
InsertBefore) {
if (retVal)
Op<0>() = retVal;
}
ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
: Instruction(Type::getVoidTy(C), Instruction::Ret,
OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
InsertAtEnd) {
if (retVal)
Op<0>() = retVal;
}
ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
: Instruction(Type::getVoidTy(Context), Instruction::Ret,
OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {}
//===----------------------------------------------------------------------===//
// ResumeInst Implementation
//===----------------------------------------------------------------------===//
ResumeInst::ResumeInst(const ResumeInst &RI)
: Instruction(Type::getVoidTy(RI.getContext()), Instruction::Resume,
OperandTraits<ResumeInst>::op_begin(this), 1) {
Op<0>() = RI.Op<0>();
}
ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
: Instruction(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
Op<0>() = Exn;
}
ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
: Instruction(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
Op<0>() = Exn;
}
//===----------------------------------------------------------------------===//
// CleanupReturnInst Implementation
//===----------------------------------------------------------------------===//
CleanupReturnInst::CleanupReturnInst(const CleanupReturnInst &CRI)
: Instruction(CRI.getType(), Instruction::CleanupRet,
OperandTraits<CleanupReturnInst>::op_end(this) -
CRI.getNumOperands(),
CRI.getNumOperands()) {
setSubclassData<Instruction::OpaqueField>(
CRI.getSubclassData<Instruction::OpaqueField>());
Op<0>() = CRI.Op<0>();
if (CRI.hasUnwindDest())
Op<1>() = CRI.Op<1>();
}
void CleanupReturnInst::init(Value *CleanupPad, BasicBlock *UnwindBB) {
if (UnwindBB)
setSubclassData<UnwindDestField>(true);
Op<0>() = CleanupPad;
if (UnwindBB)
Op<1>() = UnwindBB;
}
CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB,
unsigned Values, Instruction *InsertBefore)
: Instruction(Type::getVoidTy(CleanupPad->getContext()),
Instruction::CleanupRet,
OperandTraits<CleanupReturnInst>::op_end(this) - Values,
Values, InsertBefore) {
init(CleanupPad, UnwindBB);
}
CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB,
unsigned Values, BasicBlock *InsertAtEnd)
: Instruction(Type::getVoidTy(CleanupPad->getContext()),
Instruction::CleanupRet,
OperandTraits<CleanupReturnInst>::op_end(this) - Values,
Values, InsertAtEnd) {
init(CleanupPad, UnwindBB);
}
//===----------------------------------------------------------------------===//
// CatchReturnInst Implementation
//===----------------------------------------------------------------------===//
void CatchReturnInst::init(Value *CatchPad, BasicBlock *BB) {
Op<0>() = CatchPad;
Op<1>() = BB;
}
CatchReturnInst::CatchReturnInst(const CatchReturnInst &CRI)
: Instruction(Type::getVoidTy(CRI.getContext()), Instruction::CatchRet,
OperandTraits<CatchReturnInst>::op_begin(this), 2) {
Op<0>() = CRI.Op<0>();
Op<1>() = CRI.Op<1>();
}
CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB,
Instruction *InsertBefore)
: Instruction(Type::getVoidTy(BB->getContext()), Instruction::CatchRet,
OperandTraits<CatchReturnInst>::op_begin(this), 2,
InsertBefore) {
init(CatchPad, BB);
}
CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB,
BasicBlock *InsertAtEnd)
: Instruction(Type::getVoidTy(BB->getContext()), Instruction::CatchRet,
OperandTraits<CatchReturnInst>::op_begin(this), 2,
InsertAtEnd) {
init(CatchPad, BB);
}
//===----------------------------------------------------------------------===//
// CatchSwitchInst Implementation
//===----------------------------------------------------------------------===//
CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
unsigned NumReservedValues,
const Twine &NameStr,
Instruction *InsertBefore)
: Instruction(ParentPad->getType(), Instruction::CatchSwitch, nullptr, 0,
InsertBefore) {
if (UnwindDest)
++NumReservedValues;
init(ParentPad, UnwindDest, NumReservedValues + 1);
setName(NameStr);
}
CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
unsigned NumReservedValues,
const Twine &NameStr, BasicBlock *InsertAtEnd)
: Instruction(ParentPad->getType(), Instruction::CatchSwitch, nullptr, 0,
InsertAtEnd) {
if (UnwindDest)
++NumReservedValues;
init(ParentPad, UnwindDest, NumReservedValues + 1);
setName(NameStr);
}
CatchSwitchInst::CatchSwitchInst(const CatchSwitchInst &CSI)
: Instruction(CSI.getType(), Instruction::CatchSwitch, nullptr,
CSI.getNumOperands()) {
init(CSI.getParentPad(), CSI.getUnwindDest(), CSI.getNumOperands());
setNumHungOffUseOperands(ReservedSpace);
Use *OL = getOperandList();
const Use *InOL = CSI.getOperandList();
for (unsigned I = 1, E = ReservedSpace; I != E; ++I)
OL[I] = InOL[I];
}
void CatchSwitchInst::init(Value *ParentPad, BasicBlock *UnwindDest,
unsigned NumReservedValues) {
assert(ParentPad && NumReservedValues);
ReservedSpace = NumReservedValues;
setNumHungOffUseOperands(UnwindDest ? 2 : 1);
allocHungoffUses(ReservedSpace);
Op<0>() = ParentPad;
if (UnwindDest) {
setSubclassData<UnwindDestField>(true);
setUnwindDest(UnwindDest);
}
}
/// growOperands - grow operands - This grows the operand list in response to a
/// push_back style of operation. This grows the number of ops by 2 times.
void CatchSwitchInst::growOperands(unsigned Size) {
unsigned NumOperands = getNumOperands();
assert(NumOperands >= 1);
if (ReservedSpace >= NumOperands + Size)
return;
ReservedSpace = (NumOperands + Size / 2) * 2;
growHungoffUses(ReservedSpace);
}
void CatchSwitchInst::addHandler(BasicBlock *Handler) {
unsigned OpNo = getNumOperands();
growOperands(1);
assert(OpNo < ReservedSpace && "Growing didn't work!");
setNumHungOffUseOperands(getNumOperands() + 1);
getOperandList()[OpNo] = Handler;
}
void CatchSwitchInst::removeHandler(handler_iterator HI) {
// Move all subsequent handlers up one.
Use *EndDst = op_end() - 1;
for (Use *CurDst = HI.getCurrent(); CurDst != EndDst; ++CurDst)
*CurDst = *(CurDst + 1);
// Null out the last handler use.
*EndDst = nullptr;
setNumHungOffUseOperands(getNumOperands() - 1);
}
//===----------------------------------------------------------------------===//
// FuncletPadInst Implementation
//===----------------------------------------------------------------------===//
void FuncletPadInst::init(Value *ParentPad, ArrayRef<Value *> Args,
const Twine &NameStr) {
assert(getNumOperands() == 1 + Args.size() && "NumOperands not set up?");
llvm::copy(Args, op_begin());
setParentPad(ParentPad);
setName(NameStr);
}
FuncletPadInst::FuncletPadInst(const FuncletPadInst &FPI)
: Instruction(FPI.getType(), FPI.getOpcode(),
OperandTraits<FuncletPadInst>::op_end(this) -
FPI.getNumOperands(),
FPI.getNumOperands()) {
std::copy(FPI.op_begin(), FPI.op_end(), op_begin());
setParentPad(FPI.getParentPad());
}
FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
ArrayRef<Value *> Args, unsigned Values,
const Twine &NameStr, Instruction *InsertBefore)
: Instruction(ParentPad->getType(), Op,
OperandTraits<FuncletPadInst>::op_end(this) - Values, Values,
InsertBefore) {
init(ParentPad, Args, NameStr);
}
FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
ArrayRef<Value *> Args, unsigned Values,
const Twine &NameStr, BasicBlock *InsertAtEnd)
: Instruction(ParentPad->getType(), Op,
OperandTraits<FuncletPadInst>::op_end(this) - Values, Values,
InsertAtEnd) {
init(ParentPad, Args, NameStr);
}
//===----------------------------------------------------------------------===//
// UnreachableInst Implementation
//===----------------------------------------------------------------------===//
UnreachableInst::UnreachableInst(LLVMContext &Context,
Instruction *InsertBefore)
: Instruction(Type::getVoidTy(Context), Instruction::Unreachable, nullptr,
0, InsertBefore) {}
UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
: Instruction(Type::getVoidTy(Context), Instruction::Unreachable, nullptr,
0, InsertAtEnd) {}
//===----------------------------------------------------------------------===//
// BranchInst Implementation
//===----------------------------------------------------------------------===//
void BranchInst::AssertOK() {
if (isConditional())
assert(getCondition()->getType()->isIntegerTy(1) &&
"May only branch on boolean predicates!");
}
BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
: Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
OperandTraits<BranchInst>::op_end(this) - 1, 1,
InsertBefore) {
assert(IfTrue && "Branch destination may not be null!");
Op<-1>() = IfTrue;
}
BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
Instruction *InsertBefore)
: Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
OperandTraits<BranchInst>::op_end(this) - 3, 3,
InsertBefore) {
// Assign in order of operand index to make use-list order predictable.
Op<-3>() = Cond;
Op<-2>() = IfFalse;
Op<-1>() = IfTrue;
#ifndef NDEBUG
AssertOK();
#endif
}
BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
: Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
OperandTraits<BranchInst>::op_end(this) - 1, 1, InsertAtEnd) {
assert(IfTrue && "Branch destination may not be null!");
Op<-1>() = IfTrue;
}
BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
BasicBlock *InsertAtEnd)
: Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
OperandTraits<BranchInst>::op_end(this) - 3, 3, InsertAtEnd) {
// Assign in order of operand index to make use-list order predictable.
Op<-3>() = Cond;
Op<-2>() = IfFalse;
Op<-1>() = IfTrue;
#ifndef NDEBUG
AssertOK();
#endif
}
BranchInst::BranchInst(const BranchInst &BI)
: Instruction(Type::getVoidTy(BI.getContext()), Instruction::Br,
OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
BI.getNumOperands()) {
// Assign in order of operand index to make use-list order predictable.
if (BI.getNumOperands() != 1) {
assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
Op<-3>() = BI.Op<-3>();
Op<-2>() = BI.Op<-2>();
}
Op<-1>() = BI.Op<-1>();
SubclassOptionalData = BI.SubclassOptionalData;
}
void BranchInst::swapSuccessors() {
assert(isConditional() &&
"Cannot swap successors of an unconditional branch");
Op<-1>().swap(Op<-2>());
// Update profile metadata if present and it matches our structural
// expectations.
swapProfMetadata();
}
//===----------------------------------------------------------------------===//
// AllocaInst Implementation
//===----------------------------------------------------------------------===//
static Value *getAISize(LLVMContext &Context, Value *Amt) {
if (!Amt)
Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
else {
assert(!isa<BasicBlock>(Amt) &&
"Passed basic block into allocation size parameter! Use other ctor");
assert(Amt->getType()->isIntegerTy() &&
"Allocation array size is not an integer!");
}
return Amt;
}
static Align computeAllocaDefaultAlign(Type *Ty, BasicBlock *BB) {
assert(BB && "Insertion BB cannot be null when alignment not provided!");
assert(BB->getParent() &&
"BB must be in a Function when alignment not provided!");
const DataLayout &DL = BB->getModule()->getDataLayout();
return DL.getPrefTypeAlign(Ty);
}
static Align computeAllocaDefaultAlign(Type *Ty, Instruction *I) {
assert(I && "Insertion position cannot be null when alignment not provided!");
return computeAllocaDefaultAlign(Ty, I->getParent());
}
AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name,
Instruction *InsertBefore)
: AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertBefore) {}
AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name,
BasicBlock *InsertAtEnd)
: AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertAtEnd) {}
AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
const Twine &Name, Instruction *InsertBefore)
: AllocaInst(Ty, AddrSpace, ArraySize,
computeAllocaDefaultAlign(Ty, InsertBefore), Name,
InsertBefore) {}
AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
const Twine &Name, BasicBlock *InsertAtEnd)
: AllocaInst(Ty, AddrSpace, ArraySize,
computeAllocaDefaultAlign(Ty, InsertAtEnd), Name,
InsertAtEnd) {}
AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
Align Align, const Twine &Name,
Instruction *InsertBefore)
: UnaryInstruction(PointerType::get(Ty, AddrSpace), Alloca,
getAISize(Ty->getContext(), ArraySize), InsertBefore),
AllocatedType(Ty) {
setAlignment(Align);
assert(!Ty->isVoidTy() && "Cannot allocate void!");
setName(Name);
}
AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
Align Align, const Twine &Name, BasicBlock *InsertAtEnd)
: UnaryInstruction(PointerType::get(Ty, AddrSpace), Alloca,
getAISize(Ty->getContext(), ArraySize), InsertAtEnd),
AllocatedType(Ty) {
setAlignment(Align);
assert(!Ty->isVoidTy() && "Cannot allocate void!");
setName(Name);
}
bool AllocaInst::isArrayAllocation() const {
if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
return !CI->isOne();
return true;
}
/// isStaticAlloca - Return true if this alloca is in the entry block of the
/// function and is a constant size. If so, the code generator will fold it
/// into the prolog/epilog code, so it is basically free.
bool AllocaInst::isStaticAlloca() const {
// Must be constant size.
if (!isa<ConstantInt>(getArraySize())) return false;
// Must be in the entry block.
const BasicBlock *Parent = getParent();
return Parent == &Parent->getParent()->front() && !isUsedWithInAlloca();
}
//===----------------------------------------------------------------------===//
// LoadInst Implementation
//===----------------------------------------------------------------------===//
void LoadInst::AssertOK() {
assert(getOperand(0)->getType()->isPointerTy() &&
"Ptr must have pointer type.");
}
static Align computeLoadStoreDefaultAlign(Type *Ty, BasicBlock *BB) {
assert(BB && "Insertion BB cannot be null when alignment not provided!");
assert(BB->getParent() &&
"BB must be in a Function when alignment not provided!");
const DataLayout &DL = BB->getModule()->getDataLayout();
return DL.getABITypeAlign(Ty);
}
static Align computeLoadStoreDefaultAlign(Type *Ty, Instruction *I) {
assert(I && "Insertion position cannot be null when alignment not provided!");
return computeLoadStoreDefaultAlign(Ty, I->getParent());
}
LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name,
Instruction *InsertBef)
: LoadInst(Ty, Ptr, Name, /*isVolatile=*/false, InsertBef) {}
LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name,
BasicBlock *InsertAE)
: LoadInst(Ty, Ptr, Name, /*isVolatile=*/false, InsertAE) {}
LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
Instruction *InsertBef)
: LoadInst(Ty, Ptr, Name, isVolatile,
computeLoadStoreDefaultAlign(Ty, InsertBef), InsertBef) {}
LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
BasicBlock *InsertAE)
: LoadInst(Ty, Ptr, Name, isVolatile,
computeLoadStoreDefaultAlign(Ty, InsertAE), InsertAE) {}
LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
Align Align, Instruction *InsertBef)
: LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic,
SyncScope::System, InsertBef) {}
LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
Align Align, BasicBlock *InsertAE)
: LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic,
SyncScope::System, InsertAE) {}
LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
Align Align, AtomicOrdering Order, SyncScope::ID SSID,
Instruction *InsertBef)
: UnaryInstruction(Ty, Load, Ptr, InsertBef) {
assert(cast<PointerType>(Ptr->getType())->isOpaqueOrPointeeTypeMatches(Ty));
setVolatile(isVolatile);
setAlignment(Align);
setAtomic(Order, SSID);
AssertOK();
setName(Name);
}
LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
Align Align, AtomicOrdering Order, SyncScope::ID SSID,
BasicBlock *InsertAE)
: UnaryInstruction(Ty, Load, Ptr, InsertAE) {
assert(cast<PointerType>(Ptr->getType())->isOpaqueOrPointeeTypeMatches(Ty));
setVolatile(isVolatile);
setAlignment(Align);
setAtomic(Order, SSID);
AssertOK();
setName(Name);
}
//===----------------------------------------------------------------------===//
// StoreInst Implementation
//===----------------------------------------------------------------------===//
void StoreInst::AssertOK() {
assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
assert(getOperand(1)->getType()->isPointerTy() &&
"Ptr must have pointer type!");
assert(cast<PointerType>(getOperand(1)->getType())
->isOpaqueOrPointeeTypeMatches(getOperand(0)->getType()) &&
"Ptr must be a pointer to Val type!");
}
StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
: StoreInst(val, addr, /*isVolatile=*/false, InsertBefore) {}
StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
: StoreInst(val, addr, /*isVolatile=*/false, InsertAtEnd) {}
StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
Instruction *InsertBefore)
: StoreInst(val, addr, isVolatile,
computeLoadStoreDefaultAlign(val->getType(), InsertBefore),
InsertBefore) {}
StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
BasicBlock *InsertAtEnd)
: StoreInst(val, addr, isVolatile,
computeLoadStoreDefaultAlign(val->getType(), InsertAtEnd),
InsertAtEnd) {}
StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align,
Instruction *InsertBefore)
: StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic,
SyncScope::System, InsertBefore) {}
StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align,
BasicBlock *InsertAtEnd)
: StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic,
SyncScope::System, InsertAtEnd) {}
StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align,
AtomicOrdering Order, SyncScope::ID SSID,
Instruction *InsertBefore)
: Instruction(Type::getVoidTy(val->getContext()), Store,
OperandTraits<StoreInst>::op_begin(this),
OperandTraits<StoreInst>::operands(this), InsertBefore) {
Op<0>() = val;
Op<1>() = addr;
setVolatile(isVolatile);
setAlignment(Align);
setAtomic(Order, SSID);
AssertOK();
}
StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align,
AtomicOrdering Order, SyncScope::ID SSID,
BasicBlock *InsertAtEnd)
: Instruction(Type::getVoidTy(val->getContext()), Store,
OperandTraits<StoreInst>::op_begin(this),
OperandTraits<StoreInst>::operands(this), InsertAtEnd) {
Op<0>() = val;
Op<1>() = addr;
setVolatile(isVolatile);
setAlignment(Align);
setAtomic(Order, SSID);
AssertOK();
}
//===----------------------------------------------------------------------===//
// AtomicCmpXchgInst Implementation
//===----------------------------------------------------------------------===//
void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
Align Alignment, AtomicOrdering SuccessOrdering,
AtomicOrdering FailureOrdering,
SyncScope::ID SSID) {
Op<0>() = Ptr;
Op<1>() = Cmp;
Op<2>() = NewVal;
setSuccessOrdering(SuccessOrdering);
setFailureOrdering(FailureOrdering);
setSyncScopeID(SSID);
setAlignment(Alignment);
assert(getOperand(0) && getOperand(1) && getOperand(2) &&
"All operands must be non-null!");
assert(getOperand(0)->getType()->isPointerTy() &&
"Ptr must have pointer type!");
assert(cast<PointerType>(getOperand(0)->getType())
->isOpaqueOrPointeeTypeMatches(getOperand(1)->getType()) &&
"Ptr must be a pointer to Cmp type!");
assert(cast<PointerType>(getOperand(0)->getType())
->isOpaqueOrPointeeTypeMatches(getOperand(2)->getType()) &&
"Ptr must be a pointer to NewVal type!");
assert(getOperand(1)->getType() == getOperand(2)->getType() &&
"Cmp type and NewVal type must be same!");
}
AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
Align Alignment,
AtomicOrdering SuccessOrdering,
AtomicOrdering FailureOrdering,
SyncScope::ID SSID,
Instruction *InsertBefore)
: Instruction(
StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())),
AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
OperandTraits<AtomicCmpXchgInst>::operands(this), InsertBefore) {
Init(Ptr, Cmp, NewVal, Alignment, SuccessOrdering, FailureOrdering, SSID);
}
AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
Align Alignment,
AtomicOrdering SuccessOrdering,
AtomicOrdering FailureOrdering,
SyncScope::ID SSID,
BasicBlock *InsertAtEnd)
: Instruction(
StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())),
AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
OperandTraits<AtomicCmpXchgInst>::operands(this), InsertAtEnd) {
Init(Ptr, Cmp, NewVal, Alignment, SuccessOrdering, FailureOrdering, SSID);
}
//===----------------------------------------------------------------------===//
// AtomicRMWInst Implementation
//===----------------------------------------------------------------------===//
void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
Align Alignment, AtomicOrdering Ordering,
SyncScope::ID SSID) {
Op<0>() = Ptr;
Op<1>() = Val;
setOperation(Operation);
setOrdering(Ordering);
setSyncScopeID(SSID);
setAlignment(Alignment);
assert(getOperand(0) && getOperand(1) &&
"All operands must be non-null!");
assert(getOperand(0)->getType()->isPointerTy() &&
"Ptr must have pointer type!");
assert(cast<PointerType>(getOperand(0)->getType())
->isOpaqueOrPointeeTypeMatches(getOperand(1)->getType()) &&
"Ptr must be a pointer to Val type!");
assert(Ordering != AtomicOrdering::NotAtomic &&
"AtomicRMW instructions must be atomic!");
}
AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
Align Alignment, AtomicOrdering Ordering,
SyncScope::ID SSID, Instruction *InsertBefore)
: Instruction(Val->getType(), AtomicRMW,
OperandTraits<AtomicRMWInst>::op_begin(this),
OperandTraits<AtomicRMWInst>::operands(this), InsertBefore) {
Init(Operation, Ptr, Val, Alignment, Ordering, SSID);
}
AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
Align Alignment, AtomicOrdering Ordering,
SyncScope::ID SSID, BasicBlock *InsertAtEnd)
: Instruction(Val->getType(), AtomicRMW,
OperandTraits<AtomicRMWInst>::op_begin(this),
OperandTraits<AtomicRMWInst>::operands(this), InsertAtEnd) {
Init(Operation, Ptr, Val, Alignment, Ordering, SSID);
}
StringRef AtomicRMWInst::getOperationName(BinOp Op) {
switch (Op) {
case AtomicRMWInst::Xchg:
return "xchg";
case AtomicRMWInst::Add:
return "add";
case AtomicRMWInst::Sub:
return "sub";
case AtomicRMWInst::And:
return "and";
case AtomicRMWInst::Nand:
return "nand";
case AtomicRMWInst::Or:
return "or";
case AtomicRMWInst::Xor:
return "xor";
case AtomicRMWInst::Max:
return "max";
case AtomicRMWInst::Min:
return "min";
case AtomicRMWInst::UMax:
return "umax";
case AtomicRMWInst::UMin:
return "umin";
case AtomicRMWInst::FAdd:
return "fadd";
case AtomicRMWInst::FSub:
return "fsub";
case AtomicRMWInst::BAD_BINOP:
return "<invalid operation>";
}
llvm_unreachable("invalid atomicrmw operation");
}
//===----------------------------------------------------------------------===//
// FenceInst Implementation
//===----------------------------------------------------------------------===//
FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
SyncScope::ID SSID,
Instruction *InsertBefore)
: Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertBefore) {
setOrdering(Ordering);
setSyncScopeID(SSID);
}
FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
SyncScope::ID SSID,
BasicBlock *InsertAtEnd)
: Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertAtEnd) {
setOrdering(Ordering);
setSyncScopeID(SSID);
}
//===----------------------------------------------------------------------===//
// GetElementPtrInst Implementation
//===----------------------------------------------------------------------===//
void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
const Twine &Name) {
assert(getNumOperands() == 1 + IdxList.size() &&
"NumOperands not initialized?");
Op<0>() = Ptr;
llvm::copy(IdxList, op_begin() + 1);
setName(Name);
}
GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
: Instruction(GEPI.getType(), GetElementPtr,
OperandTraits<GetElementPtrInst>::op_end(this) -
GEPI.getNumOperands(),
GEPI.getNumOperands()),
SourceElementType(GEPI.SourceElementType),
ResultElementType(GEPI.ResultElementType) {
std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
SubclassOptionalData = GEPI.SubclassOptionalData;
}
Type *GetElementPtrInst::getTypeAtIndex(Type *Ty, Value *Idx) {
if (auto *Struct = dyn_cast<StructType>(Ty)) {
if (!Struct->indexValid(Idx))
return nullptr;
return Struct->getTypeAtIndex(Idx);
}
if (!Idx->getType()->isIntOrIntVectorTy())
return nullptr;
if (auto *Array = dyn_cast<ArrayType>(Ty))
return Array->getElementType();
if (auto *Vector = dyn_cast<VectorType>(Ty))
return Vector->getElementType();
return nullptr;
}
Type *GetElementPtrInst::getTypeAtIndex(Type *Ty, uint64_t Idx) {
if (auto *Struct = dyn_cast<StructType>(Ty)) {
if (Idx >= Struct->getNumElements())
return nullptr;
return Struct->getElementType(Idx);
}
if (auto *Array = dyn_cast<ArrayType>(Ty))
return Array->getElementType();
if (auto *Vector = dyn_cast<VectorType>(Ty))
return Vector->getElementType();
return nullptr;
}
template <typename IndexTy>
static Type *getIndexedTypeInternal(Type *Ty, ArrayRef<IndexTy> IdxList) {
if (IdxList.empty())
return Ty;
for (IndexTy V : IdxList.slice(1)) {
Ty = GetElementPtrInst::getTypeAtIndex(Ty, V);
if (!Ty)
return Ty;
}
return Ty;
}
Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<Value *> IdxList) {
return getIndexedTypeInternal(Ty, IdxList);
}
Type *GetElementPtrInst::getIndexedType(Type *Ty,
ArrayRef<Constant *> IdxList) {
return getIndexedTypeInternal(Ty, IdxList);
}
Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList) {
return getIndexedTypeInternal(Ty, IdxList);
}
/// hasAllZeroIndices - Return true if all of the indices of this GEP are
/// zeros. If so, the result pointer and the first operand have the same
/// value, just potentially different types.
bool GetElementPtrInst::hasAllZeroIndices() const {
for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
if (!CI->isZero()) return false;
} else {
return false;
}
}
return true;
}
/// hasAllConstantIndices - Return true if all of the indices of this GEP are
/// constant integers. If so, the result pointer and the first operand have
/// a constant offset between them.
bool GetElementPtrInst::hasAllConstantIndices() const {
for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
if (!isa<ConstantInt>(getOperand(i)))
return false;
}
return true;
}
void GetElementPtrInst::setIsInBounds(bool B) {
cast<GEPOperator>(this)->setIsInBounds(B);
}
bool GetElementPtrInst::isInBounds() const {
return cast<GEPOperator>(this)->isInBounds();
}
bool GetElementPtrInst::accumulateConstantOffset(const DataLayout &DL,
APInt &Offset) const {
// Delegate to the generic GEPOperator implementation.
return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset);
}
bool GetElementPtrInst::collectOffset(
const DataLayout &DL, unsigned BitWidth,
MapVector<Value *, APInt> &VariableOffsets,
APInt &ConstantOffset) const {
// Delegate to the generic GEPOperator implementation.
return cast<GEPOperator>(this)->collectOffset(DL, BitWidth, VariableOffsets,
ConstantOffset);
}
//===----------------------------------------------------------------------===//
// ExtractElementInst Implementation
//===----------------------------------------------------------------------===//
ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
const Twine &Name,
Instruction *InsertBef)
: Instruction(cast<VectorType>(Val->getType())->getElementType(),
ExtractElement,
OperandTraits<ExtractElementInst>::op_begin(this),
2, InsertBef) {
assert(isValidOperands(Val, Index) &&
"Invalid extractelement instruction operands!");
Op<0>() = Val;
Op<1>() = Index;
setName(Name);
}
ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
const Twine &Name,
BasicBlock *InsertAE)
: Instruction(cast<VectorType>(Val->getType())->getElementType(),
ExtractElement,
OperandTraits<ExtractElementInst>::op_begin(this),
2, InsertAE) {
assert(isValidOperands(Val, Index) &&
"Invalid extractelement instruction operands!");
Op<0>() = Val;
Op<1>() = Index;
setName(Name);
}
bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy())
return false;
return true;
}
//===----------------------------------------------------------------------===//
// InsertElementInst Implementation
//===----------------------------------------------------------------------===//
InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
const Twine &Name,
Instruction *InsertBef)
: Instruction(Vec->getType(), InsertElement,
OperandTraits<InsertElementInst>::op_begin(this),
3, InsertBef) {
assert(isValidOperands(Vec, Elt, Index) &&
"Invalid insertelement instruction operands!");
Op<0>() = Vec;
Op<1>() = Elt;
Op<2>() = Index;
setName(Name);
}
InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
const Twine &Name,
BasicBlock *InsertAE)
: Instruction(Vec->getType(), InsertElement,
OperandTraits<InsertElementInst>::op_begin(this),
3, InsertAE) {
assert(isValidOperands(Vec, Elt, Index) &&
"Invalid insertelement instruction operands!");
Op<0>() = Vec;
Op<1>() = Elt;
Op<2>() = Index;
setName(Name);
}
bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
const Value *Index) {
if (!Vec->getType()->isVectorTy())
return false; // First operand of insertelement must be vector type.
if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
return false;// Second operand of insertelement must be vector element type.
if (!Index->getType()->isIntegerTy())
return false; // Third operand of insertelement must be i32.
return true;
}
//===----------------------------------------------------------------------===//
// ShuffleVectorInst Implementation
//===----------------------------------------------------------------------===//
static Value *createPlaceholderForShuffleVector(Value *V) {
assert(V && "Cannot create placeholder of nullptr V");
return PoisonValue::get(V->getType());
}
ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *Mask, const Twine &Name,
Instruction *InsertBefore)
: ShuffleVectorInst(V1, createPlaceholderForShuffleVector(V1), Mask, Name,
InsertBefore) {}
ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *Mask, const Twine &Name,
BasicBlock *InsertAtEnd)
: ShuffleVectorInst(V1, createPlaceholderForShuffleVector(V1), Mask, Name,
InsertAtEnd) {}
ShuffleVectorInst::ShuffleVectorInst(Value *V1, ArrayRef<int> Mask,
const Twine &Name,
Instruction *InsertBefore)
: ShuffleVectorInst(V1, createPlaceholderForShuffleVector(V1), Mask, Name,
InsertBefore) {}
ShuffleVectorInst::ShuffleVectorInst(Value *V1, ArrayRef<int> Mask,
const Twine &Name, BasicBlock *InsertAtEnd)
: ShuffleVectorInst(V1, createPlaceholderForShuffleVector(V1), Mask, Name,
InsertAtEnd) {}
ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
const Twine &Name,
Instruction *InsertBefore)
: Instruction(
VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
cast<VectorType>(Mask->getType())->getElementCount()),
ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this),
OperandTraits<ShuffleVectorInst>::operands(this), InsertBefore) {
assert(isValidOperands(V1, V2, Mask) &&
"Invalid shuffle vector instruction operands!");
Op<0>() = V1;
Op<1>() = V2;
SmallVector<int, 16> MaskArr;
getShuffleMask(cast<Constant>(Mask), MaskArr);
setShuffleMask(MaskArr);
setName(Name);
}
ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
const Twine &Name, BasicBlock *InsertAtEnd)
: Instruction(
VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
cast<VectorType>(Mask->getType())->getElementCount()),
ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this),
OperandTraits<ShuffleVectorInst>::operands(this), InsertAtEnd) {
assert(isValidOperands(V1, V2, Mask) &&
"Invalid shuffle vector instruction operands!");
Op<0>() = V1;
Op<1>() = V2;
SmallVector<int, 16> MaskArr;
getShuffleMask(cast<Constant>(Mask), MaskArr);
setShuffleMask(MaskArr);
setName(Name);
}
ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask,
const Twine &Name,
Instruction *InsertBefore)
: Instruction(
VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
Mask.size(), isa<ScalableVectorType>(V1->getType())),
ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this),
OperandTraits<ShuffleVectorInst>::operands(this), InsertBefore) {
assert(isValidOperands(V1, V2, Mask) &&
"Invalid shuffle vector instruction operands!");
Op<0>() = V1;
Op<1>() = V2;
setShuffleMask(Mask);
setName(Name);
}
ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask,
const Twine &Name, BasicBlock *InsertAtEnd)
: Instruction(
VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
Mask.size(), isa<ScalableVectorType>(V1->getType())),
ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this),
OperandTraits<ShuffleVectorInst>::operands(this), InsertAtEnd) {
assert(isValidOperands(V1, V2, Mask) &&
"Invalid shuffle vector instruction operands!");
Op<0>() = V1;
Op<1>() = V2;
setShuffleMask(Mask);
setName(Name);
}
void ShuffleVectorInst::commute() {
int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
int NumMaskElts = ShuffleMask.size();
SmallVector<int, 16> NewMask(NumMaskElts);
for (int i = 0; i != NumMaskElts; ++i) {
int MaskElt = getMaskValue(i);
if (MaskElt == UndefMaskElem) {
NewMask[i] = UndefMaskElem;
continue;
}
assert(MaskElt >= 0 && MaskElt < 2 * NumOpElts && "Out-of-range mask");
MaskElt = (MaskElt < NumOpElts) ? MaskElt + NumOpElts : MaskElt - NumOpElts;
NewMask[i] = MaskElt;
}
setShuffleMask(NewMask);
Op<0>().swap(Op<1>());
}
bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
ArrayRef<int> Mask) {
// V1 and V2 must be vectors of the same type.
if (!isa<VectorType>(V1->getType()) || V1->getType() != V2->getType())
return false;
// Make sure the mask elements make sense.
int V1Size =
cast<VectorType>(V1->getType())->getElementCount().getKnownMinValue();
for (int Elem : Mask)
if (Elem != UndefMaskElem && Elem >= V1Size * 2)
return false;
if (isa<ScalableVectorType>(V1->getType()))
if ((Mask[0] != 0 && Mask[0] != UndefMaskElem) || !is_splat(Mask))
return false;
return true;
}
bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
const Value *Mask) {
// V1 and V2 must be vectors of the same type.
if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
return false;
// Mask must be vector of i32, and must be the same kind of vector as the
// input vectors
auto *MaskTy = dyn_cast<VectorType>(Mask->getType());
if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32) ||
isa<ScalableVectorType>(MaskTy) != isa<ScalableVectorType>(V1->getType()))
return false;
// Check to see if Mask is valid.
if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
return true;
if (const auto *MV = dyn_cast<ConstantVector>(Mask)) {
unsigned V1Size = cast<FixedVectorType>(V1->getType())->getNumElements();
for (Value *Op : MV->operands()) {
if (auto *CI = dyn_cast<ConstantInt>(Op)) {
if (CI->uge(V1Size*2))
return false;
} else if (!isa<UndefValue>(Op)) {
return false;
}
}
return true;
}
if (const auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) {
unsigned V1Size = cast<FixedVectorType>(V1->getType())->getNumElements();
for (unsigned i = 0, e = cast<FixedVectorType>(MaskTy)->getNumElements();
i != e; ++i)
if (CDS->getElementAsInteger(i) >= V1Size*2)
return false;
return true;
}
return false;
}
void ShuffleVectorInst::getShuffleMask(const Constant *Mask,
SmallVectorImpl<int> &Result) {
ElementCount EC = cast<VectorType>(Mask->getType())->getElementCount();
if (isa<ConstantAggregateZero>(Mask)) {
Result.resize(EC.getKnownMinValue(), 0);
return;
}
Result.reserve(EC.getKnownMinValue());
if (EC.isScalable()) {
assert((isa<ConstantAggregateZero>(Mask) || isa<UndefValue>(Mask)) &&
"Scalable vector shuffle mask must be undef or zeroinitializer");
int MaskVal = isa<UndefValue>(Mask) ? -1 : 0;
for (unsigned I = 0; I < EC.getKnownMinValue(); ++I)
Result.emplace_back(MaskVal);
return;
}
unsigned NumElts = EC.getKnownMinValue();
if (auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) {
for (unsigned i = 0; i != NumElts; ++i)
Result.push_back(CDS->getElementAsInteger(i));
return;
}
for (unsigned i = 0; i != NumElts; ++i) {
Constant *C = Mask->getAggregateElement(i);
Result.push_back(isa<UndefValue>(C) ? -1 :
cast<ConstantInt>(C)->getZExtValue());
}
}
void ShuffleVectorInst::setShuffleMask(ArrayRef<int> Mask) {
ShuffleMask.assign(Mask.begin(), Mask.end());
ShuffleMaskForBitcode = convertShuffleMaskForBitcode(Mask, getType());
}
Constant *ShuffleVectorInst::convertShuffleMaskForBitcode(ArrayRef<int> Mask,
Type *ResultTy) {
Type *Int32Ty = Type::getInt32Ty(ResultTy->getContext());
if (isa<ScalableVectorType>(ResultTy)) {
assert(is_splat(Mask) && "Unexpected shuffle");
Type *VecTy = VectorType::get(Int32Ty, Mask.size(), true);
if (Mask[0] == 0)
return Constant::getNullValue(VecTy);
return UndefValue::get(VecTy);
}
SmallVector<Constant *, 16> MaskConst;
for (int Elem : Mask) {
if (Elem == UndefMaskElem)
MaskConst.push_back(UndefValue::get(Int32Ty));
else
MaskConst.push_back(ConstantInt::get(Int32Ty, Elem));
}
return ConstantVector::get(MaskConst);
}
static bool isSingleSourceMaskImpl(ArrayRef<int> Mask, int NumOpElts) {
assert(!Mask.empty() && "Shuffle mask must contain elements");
bool UsesLHS = false;
bool UsesRHS = false;
for (int I : Mask) {
if (I == -1)
continue;
assert(I >= 0 && I < (NumOpElts * 2) &&
"Out-of-bounds shuffle mask element");
UsesLHS |= (I < NumOpElts);
UsesRHS |= (I >= NumOpElts);
if (UsesLHS && UsesRHS)
return false;
}
// Allow for degenerate case: completely undef mask means neither source is used.
return UsesLHS || UsesRHS;
}
bool ShuffleVectorInst::isSingleSourceMask(ArrayRef<int> Mask) {
// We don't have vector operand size information, so assume operands are the
// same size as the mask.
return isSingleSourceMaskImpl(Mask, Mask.size());
}
static bool isIdentityMaskImpl(ArrayRef<int> Mask, int NumOpElts) {
if (!isSingleSourceMaskImpl(Mask, NumOpElts))
return false;
for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) {
if (Mask[i] == -1)
continue;
if (Mask[i] != i && Mask[i] != (NumOpElts + i))
return false;
}
return true;
}
bool ShuffleVectorInst::isIdentityMask(ArrayRef<int> Mask) {
// We don't have vector operand size information, so assume operands are the
// same size as the mask.
return isIdentityMaskImpl(Mask, Mask.size());
}
bool ShuffleVectorInst::isReverseMask(ArrayRef<int> Mask) {
if (!isSingleSourceMask(Mask))
return false;
for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) {
if (Mask[i] == -1)
continue;
if (Mask[i] != (NumElts - 1 - i) && Mask[i] != (NumElts + NumElts - 1 - i))
return false;
}
return true;
}
bool ShuffleVectorInst::isZeroEltSplatMask(ArrayRef<int> Mask) {
if (!isSingleSourceMask(Mask))
return false;
for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) {
if (Mask[i] == -1)
continue;
if (Mask[i] != 0 && Mask[i] != NumElts)
return false;
}
return true;
}
bool ShuffleVectorInst::isSelectMask(ArrayRef<int> Mask) {
// Select is differentiated from identity. It requires using both sources.
if (isSingleSourceMask(Mask))
return false;
for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) {
if (Mask[i] == -1)
continue;
if (Mask[i] != i && Mask[i] != (NumElts + i))
return false;
}
return true;
}
bool ShuffleVectorInst::isTransposeMask(ArrayRef<int> Mask) {
// Example masks that will return true:
// v1 = <a, b, c, d>
// v2 = <e, f, g, h>
// trn1 = shufflevector v1, v2 <0, 4, 2, 6> = <a, e, c, g>
// trn2 = shufflevector v1, v2 <1, 5, 3, 7> = <b, f, d, h>
// 1. The number of elements in the mask must be a power-of-2 and at least 2.
int NumElts = Mask.size();
if (NumElts < 2 || !isPowerOf2_32(NumElts))
return false;
// 2. The first element of the mask must be either a 0 or a 1.
if (Mask[0] != 0 && Mask[0] != 1)
return false;
// 3. The difference between the first 2 elements must be equal to the
// number of elements in the mask.
if ((Mask[1] - Mask[0]) != NumElts)
return false;
// 4. The difference between consecutive even-numbered and odd-numbered
// elements must be equal to 2.
for (int i = 2; i < NumElts; ++i) {
int MaskEltVal = Mask[i];
if (MaskEltVal == -1)
return false;
int MaskEltPrevVal = Mask[i - 2];
if (MaskEltVal - MaskEltPrevVal != 2)
return false;
}
return true;
}
bool ShuffleVectorInst::isExtractSubvectorMask(ArrayRef<int> Mask,
int NumSrcElts, int &Index) {
// Must extract from a single source.
if (!isSingleSourceMaskImpl(Mask, NumSrcElts))
return false;
// Must be smaller (else this is an Identity shuffle).
if (NumSrcElts <= (int)Mask.size())
return false;
// Find start of extraction, accounting that we may start with an UNDEF.
int SubIndex = -1;
for (int i = 0, e = Mask.size(); i != e; ++i) {
int M = Mask[i];
if (M < 0)
continue;
int Offset = (M % NumSrcElts) - i;
if (0 <= SubIndex && SubIndex != Offset)
return false;
SubIndex = Offset;
}
if (0 <= SubIndex && SubIndex + (int)Mask.size() <= NumSrcElts) {
Index = SubIndex;
return true;
}
return false;
}
bool ShuffleVectorInst::isInsertSubvectorMask(ArrayRef<int> Mask,
int NumSrcElts, int &NumSubElts,
int &Index) {
int NumMaskElts = Mask.size();
// Don't try to match if we're shuffling to a smaller size.
if (NumMaskElts < NumSrcElts)
return false;
// TODO: We don't recognize self-insertion/widening.
if (isSingleSourceMaskImpl(Mask, NumSrcElts))
return false;
// Determine which mask elements are attributed to which source.
APInt UndefElts = APInt::getZero(NumMaskElts);
APInt Src0Elts = APInt::getZero(NumMaskElts);
APInt Src1Elts = APInt::getZero(NumMaskElts);
bool Src0Identity = true;
bool Src1Identity = true;
for (int i = 0; i != NumMaskElts; ++i) {
int M = Mask[i];
if (M < 0) {
UndefElts.setBit(i);
continue;
}
if (M < NumSrcElts) {
Src0Elts.setBit(i);
Src0Identity &= (M == i);
continue;
}
Src1Elts.setBit(i);
Src1Identity &= (M == (i + NumSrcElts));
}
assert((Src0Elts | Src1Elts | UndefElts).isAllOnes() &&
"unknown shuffle elements");
assert(!Src0Elts.isZero() && !Src1Elts.isZero() &&
"2-source shuffle not found");
// Determine lo/hi span ranges.
// TODO: How should we handle undefs at the start of subvector insertions?
int Src0Lo = Src0Elts.countTrailingZeros();
int Src1Lo = Src1Elts.countTrailingZeros();
int Src0Hi = NumMaskElts - Src0Elts.countLeadingZeros();
int Src1Hi = NumMaskElts - Src1Elts.countLeadingZeros();
// If src0 is in place, see if the src1 elements is inplace within its own
// span.
if (Src0Identity) {
int NumSub1Elts = Src1Hi - Src1Lo;
ArrayRef<int> Sub1Mask = Mask.slice(Src1Lo, NumSub1Elts);
if (isIdentityMaskImpl(Sub1Mask, NumSrcElts)) {
NumSubElts = NumSub1Elts;
Index = Src1Lo;
return true;
}
}
// If src1 is in place, see if the src0 elements is inplace within its own
// span.
if (Src1Identity) {
int NumSub0Elts = Src0Hi - Src0Lo;
ArrayRef<int> Sub0Mask = Mask.slice(Src0Lo, NumSub0Elts);
if (isIdentityMaskImpl(Sub0Mask, NumSrcElts)) {
NumSubElts = NumSub0Elts;
Index = Src0Lo;
return true;
}
}
return false;
}
bool ShuffleVectorInst::isIdentityWithPadding() const {
if (isa<UndefValue>(Op<2>()))
return false;
// FIXME: Not currently possible to express a shuffle mask for a scalable
// vector for this case.
if (isa<ScalableVectorType>(getType()))
return false;
int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements();
if (NumMaskElts <= NumOpElts)
return false;
// The first part of the mask must choose elements from exactly 1 source op.
ArrayRef<int> Mask = getShuffleMask();
if (!isIdentityMaskImpl(Mask, NumOpElts))
return false;
// All extending must be with undef elements.
for (int i = NumOpElts; i < NumMaskElts; ++i)
if (Mask[i] != -1)
return false;
return true;
}
bool ShuffleVectorInst::isIdentityWithExtract() const {
if (isa<UndefValue>(Op<2>()))
return false;
// FIXME: Not currently possible to express a shuffle mask for a scalable
// vector for this case.
if (isa<ScalableVectorType>(getType()))
return false;
int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements();
if (NumMaskElts >= NumOpElts)
return false;
return isIdentityMaskImpl(getShuffleMask(), NumOpElts);
}
bool ShuffleVectorInst::isConcat() const {
// Vector concatenation is differentiated from identity with padding.
if (isa<UndefValue>(Op<0>()) || isa<UndefValue>(Op<1>()) ||
isa<UndefValue>(Op<2>()))
return false;
// FIXME: Not currently possible to express a shuffle mask for a scalable
// vector for this case.
if (isa<ScalableVectorType>(getType()))
return false;
int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements();
if (NumMaskElts != NumOpElts * 2)
return false;
// Use the mask length rather than the operands' vector lengths here. We
// already know that the shuffle returns a vector twice as long as the inputs,
// and neither of the inputs are undef vectors. If the mask picks consecutive
// elements from both inputs, then this is a concatenation of the inputs.
return isIdentityMaskImpl(getShuffleMask(), NumMaskElts);
}
static bool isReplicationMaskWithParams(ArrayRef<int> Mask,
int ReplicationFactor, int VF) {
assert(Mask.size() == (unsigned)ReplicationFactor * VF &&
"Unexpected mask size.");
for (int CurrElt : seq(0, VF)) {
ArrayRef<int> CurrSubMask = Mask.take_front(ReplicationFactor);
assert(CurrSubMask.size() == (unsigned)ReplicationFactor &&
"Run out of mask?");
Mask = Mask.drop_front(ReplicationFactor);
if (!all_of(CurrSubMask, [CurrElt](int MaskElt) {
return MaskElt == UndefMaskElem || MaskElt == CurrElt;
}))
return false;
}
assert(Mask.empty() && "Did not consume the whole mask?");
return true;
}
bool ShuffleVectorInst::isReplicationMask(ArrayRef<int> Mask,
int &ReplicationFactor, int &VF) {
// undef-less case is trivial.
if (none_of(Mask, [](int MaskElt) { return MaskElt == UndefMaskElem; })) {
ReplicationFactor =
Mask.take_while([](int MaskElt) { return MaskElt == 0; }).size();
if (ReplicationFactor == 0 || Mask.size() % ReplicationFactor != 0)
return false;
VF = Mask.size() / ReplicationFactor;
return isReplicationMaskWithParams(Mask, ReplicationFactor, VF);
}
// However, if the mask contains undef's, we have to enumerate possible tuples
// and pick one. There are bounds on replication factor: [1, mask size]
// (where RF=1 is an identity shuffle, RF=mask size is a broadcast shuffle)
// Additionally, mask size is a replication factor multiplied by vector size,
// which further significantly reduces the search space.
// Before doing that, let's perform basic correctness checking first.
int Largest = -1;
for (int MaskElt : Mask) {
if (MaskElt == UndefMaskElem)
continue;
// Elements must be in non-decreasing order.
if (MaskElt < Largest)
return false;
Largest = std::max(Largest, MaskElt);
}
// Prefer larger replication factor if all else equal.
for (int PossibleReplicationFactor :
reverse(seq_inclusive<unsigned>(1, Mask.size()))) {
if (Mask.size() % PossibleReplicationFactor != 0)
continue;
int PossibleVF = Mask.size() / PossibleReplicationFactor;
if (!isReplicationMaskWithParams(Mask, PossibleReplicationFactor,
PossibleVF))
continue;
ReplicationFactor = PossibleReplicationFactor;
VF = PossibleVF;
return true;
}
return false;
}
bool ShuffleVectorInst::isReplicationMask(int &ReplicationFactor,
int &VF) const {
// Not possible to express a shuffle mask for a scalable vector for this
// case.
if (isa<ScalableVectorType>(getType()))
return false;
VF = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
if (ShuffleMask.size() % VF != 0)
return false;
ReplicationFactor = ShuffleMask.size() / VF;
return isReplicationMaskWithParams(ShuffleMask, ReplicationFactor, VF);
}
//===----------------------------------------------------------------------===//
// InsertValueInst Class
//===----------------------------------------------------------------------===//
void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
const Twine &Name) {
assert(getNumOperands() == 2 && "NumOperands not initialized?");
// There's no fundamental reason why we require at least one index
// (other than weirdness with &*IdxBegin being invalid; see
// getelementptr's init routine for example). But there's no
// present need to support it.
assert(!Idxs.empty() && "InsertValueInst must have at least one index");
assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
Val->getType() && "Inserted value must match indexed type!");
Op<0>() = Agg;
Op<1>() = Val;
Indices.append(Idxs.begin(), Idxs.end());
setName(Name);
}
InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
: Instruction(IVI.getType(), InsertValue,
OperandTraits<InsertValueInst>::op_begin(this), 2),
Indices(IVI.Indices) {
Op<0>() = IVI.getOperand(0);
Op<1>() = IVI.getOperand(1);
SubclassOptionalData = IVI.SubclassOptionalData;
}
//===----------------------------------------------------------------------===//
// ExtractValueInst Class
//===----------------------------------------------------------------------===//
void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
assert(getNumOperands() == 1 && "NumOperands not initialized?");
// There's no fundamental reason why we require at least one index.
// But there's no present need to support it.
assert(!Idxs.empty() && "ExtractValueInst must have at least one index");
Indices.append(Idxs.begin(), Idxs.end());
setName(Name);
}
ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
: UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
Indices(EVI.Indices) {
SubclassOptionalData = EVI.SubclassOptionalData;
}
// getIndexedType - Returns the type of the element that would be extracted
// with an extractvalue instruction with the specified parameters.
//
// A null type is returned if the indices are invalid for the specified
// pointer type.
//
Type *ExtractValueInst::getIndexedType(Type *Agg,
ArrayRef<unsigned> Idxs) {
for (unsigned Index : Idxs) {
// We can't use CompositeType::indexValid(Index) here.
// indexValid() always returns true for arrays because getelementptr allows
// out-of-bounds indices. Since we don't allow those for extractvalue and
// insertvalue we need to check array indexing manually.
// Since the only other types we can index into are struct types it's just
// as easy to check those manually as well.
if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
if (Index >= AT->getNumElements())
return nullptr;
Agg = AT->getElementType();
} else if (StructType *ST = dyn_cast<StructType>(Agg)) {
if (Index >= ST->getNumElements())
return nullptr;
Agg = ST->getElementType(Index);
} else {
// Not a valid type to index into.
return nullptr;
}
}
return const_cast<Type*>(Agg);
}
//===----------------------------------------------------------------------===//
// UnaryOperator Class
//===----------------------------------------------------------------------===//
UnaryOperator::UnaryOperator(UnaryOps iType, Value *S,
Type *Ty, const Twine &Name,
Instruction *InsertBefore)
: UnaryInstruction(Ty, iType, S, InsertBefore) {
Op<0>() = S;
setName(Name);
AssertOK();
}
UnaryOperator::UnaryOperator(UnaryOps iType, Value *S,
Type *Ty, const Twine &Name,
BasicBlock *InsertAtEnd)
: UnaryInstruction(Ty, iType, S, InsertAtEnd) {
Op<0>() = S;
setName(Name);
AssertOK();
}
UnaryOperator *UnaryOperator::Create(UnaryOps Op, Value *S,
const Twine &Name,
Instruction *InsertBefore) {
return new UnaryOperator(Op, S, S->getType(), Name, InsertBefore);
}
UnaryOperator *UnaryOperator::Create(UnaryOps Op, Value *S,
const Twine &Name,
BasicBlock *InsertAtEnd) {
UnaryOperator *Res = Create(Op, S, Name);
InsertAtEnd->getInstList().push_back(Res);
return Res;
}
void UnaryOperator::AssertOK() {
Value *LHS = getOperand(0);
(void)LHS; // Silence warnings.
#ifndef NDEBUG
switch (getOpcode()) {
case FNeg:
assert(getType() == LHS->getType() &&
"Unary operation should return same type as operand!");
assert(getType()->isFPOrFPVectorTy() &&
"Tried to create a floating-point operation on a "
"non-floating-point type!");
break;
default: llvm_unreachable("Invalid opcode provided");
}
#endif
}
//===----------------------------------------------------------------------===//
// BinaryOperator Class
//===----------------------------------------------------------------------===//
BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
Type *Ty, const Twine &Name,
Instruction *InsertBefore)
: Instruction(Ty, iType,
OperandTraits<BinaryOperator>::op_begin(this),
OperandTraits<BinaryOperator>::operands(this),
InsertBefore) {
Op<0>() = S1;
Op<1>() = S2;
setName(Name);
AssertOK();
}
BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
Type *Ty, const Twine &Name,
BasicBlock *InsertAtEnd)
: Instruction(Ty, iType,
OperandTraits<BinaryOperator>::op_begin(this),
OperandTraits<BinaryOperator>::operands(this),
InsertAtEnd) {
Op<0>() = S1;
Op<1>() = S2;
setName(Name);
AssertOK();
}
void BinaryOperator::AssertOK() {
Value *LHS = getOperand(0), *RHS = getOperand(1);
(void)LHS; (void)RHS; // Silence warnings.
assert(LHS->getType() == RHS->getType() &&
"Binary operator operand types must match!");
#ifndef NDEBUG
switch (getOpcode()) {
case Add: case Sub:
case Mul:
assert(getType() == LHS->getType() &&
"Arithmetic operation should return same type as operands!");
assert(getType()->isIntOrIntVectorTy() &&
"Tried to create an integer operation on a non-integer type!");
break;
case FAdd: case FSub:
case FMul:
assert(getType() == LHS->getType() &&
"Arithmetic operation should return same type as operands!");
assert(getType()->isFPOrFPVectorTy() &&
"Tried to create a floating-point operation on a "
"non-floating-point type!");
break;
case UDiv:
case SDiv:
assert(getType() == LHS->getType() &&
"Arithmetic operation should return same type as operands!");
assert(getType()->isIntOrIntVectorTy() &&
"Incorrect operand type (not integer) for S/UDIV");
break;
case FDiv:
assert(getType() == LHS->getType() &&
"Arithmetic operation should return same type as operands!");
assert(getType()->isFPOrFPVectorTy() &&
"Incorrect operand type (not floating point) for FDIV");
break;
case URem:
case SRem:
assert(getType() == LHS->getType() &&
"Arithmetic operation should return same type as operands!");
assert(getType()->isIntOrIntVectorTy() &&
"Incorrect operand type (not integer) for S/UREM");
break;
case FRem:
assert(getType() == LHS->getType() &&
"Arithmetic operation should return same type as operands!");
assert(getType()->isFPOrFPVectorTy() &&
"Incorrect operand type (not floating point) for FREM");
break;
case Shl:
case LShr:
case AShr:
assert(getType() == LHS->getType() &&
"Shift operation should return same type as operands!");
assert(getType()->isIntOrIntVectorTy() &&
"Tried to create a shift operation on a non-integral type!");
break;
case And: case Or:
case Xor:
assert(getType() == LHS->getType() &&
"Logical operation should return same type as operands!");
assert(getType()->isIntOrIntVectorTy() &&
"Tried to create a logical operation on a non-integral type!");
break;
default: llvm_unreachable("Invalid opcode provided");
}
#endif
}
BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
const Twine &Name,
Instruction *InsertBefore) {
assert(S1->getType() == S2->getType() &&
"Cannot create binary operator with two operands of differing type!");
return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
}
BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
const Twine &Name,
BasicBlock *InsertAtEnd) {
BinaryOperator *Res = Create(Op, S1, S2, Name);
InsertAtEnd->getInstList().push_back(Res);
return Res;
}
BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
Instruction *InsertBefore) {
Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
return new BinaryOperator(Instruction::Sub,
zero, Op,
Op->getType(), Name, InsertBefore);
}
BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
BasicBlock *InsertAtEnd) {
Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
return new BinaryOperator(Instruction::Sub,
zero, Op,
Op->getType(), Name, InsertAtEnd);
}
BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
Instruction *InsertBefore) {
Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
}
BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
BasicBlock *InsertAtEnd) {
Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
}
BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
Instruction *InsertBefore) {
Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
}
BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
BasicBlock *InsertAtEnd) {
Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
}
BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
Instruction *InsertBefore) {
Constant *C = Constant::getAllOnesValue(Op->getType());
return new BinaryOperator(Instruction::Xor, Op, C,
Op->getType(), Name, InsertBefore);
}
BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
BasicBlock *InsertAtEnd) {
Constant *AllOnes = Constant::getAllOnesValue(Op->getType());
return new BinaryOperator(Instruction::Xor, Op, AllOnes,
Op->getType(), Name, InsertAtEnd);
}
// Exchange the two operands to this instruction. This instruction is safe to
// use on any binary instruction and does not modify the semantics of the
// instruction. If the instruction is order-dependent (SetLT f.e.), the opcode
// is changed.
bool BinaryOperator::swapOperands() {
if (!isCommutative())
return true; // Can't commute operands
Op<0>().swap(Op<1>());
return false;
}
//===----------------------------------------------------------------------===//
// FPMathOperator Class
//===----------------------------------------------------------------------===//
float FPMathOperator::getFPAccuracy() const {
const MDNode *MD =
cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
if (!MD)
return 0.0;
ConstantFP *Accuracy = mdconst::extract<ConstantFP>(MD->getOperand(0));
return Accuracy->getValueAPF().convertToFloat();
}
//===----------------------------------------------------------------------===//
// CastInst Class
//===----------------------------------------------------------------------===//
// Just determine if this cast only deals with integral->integral conversion.
bool CastInst::isIntegerCast() const {
switch (getOpcode()) {
default: return false;
case Instruction::ZExt:
case Instruction::SExt:
case Instruction::Trunc:
return true;
case Instruction::BitCast:
return getOperand(0)->getType()->isIntegerTy() &&
getType()->isIntegerTy();
}
}
bool CastInst::isLosslessCast() const {
// Only BitCast can be lossless, exit fast if we're not BitCast
if (getOpcode() != Instruction::BitCast)
return false;
// Identity cast is always lossless
Type *SrcTy = getOperand(0)->getType();
Type *DstTy = getType();
if (SrcTy == DstTy)
return true;
// Pointer to pointer is always lossless.
if (SrcTy->isPointerTy())
return DstTy->isPointerTy();
return false; // Other types have no identity values
}
/// This function determines if the CastInst does not require any bits to be
/// changed in order to effect the cast. Essentially, it identifies cases where
/// no code gen is necessary for the cast, hence the name no-op cast. For
/// example, the following are all no-op casts:
/// # bitcast i32* %x to i8*
/// # bitcast <2 x i32> %x to <4 x i16>
/// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
/// Determine if the described cast is a no-op.
bool CastInst::isNoopCast(Instruction::CastOps Opcode,
Type *SrcTy,
Type *DestTy,
const DataLayout &DL) {
assert(castIsValid(Opcode, SrcTy, DestTy) && "method precondition");
switch (Opcode) {
default: llvm_unreachable("Invalid CastOp");
case Instruction::Trunc:
case Instruction::ZExt:
case Instruction::SExt:
case Instruction::FPTrunc:
case Instruction::FPExt:
case Instruction::UIToFP:
case Instruction::SIToFP:
case Instruction::FPToUI:
case Instruction::FPToSI:
case Instruction::AddrSpaceCast:
// TODO: Target informations may give a more accurate answer here.
return false;
case Instruction::BitCast:
return true; // BitCast never modifies bits.
case Instruction::PtrToInt:
return DL.getIntPtrType(SrcTy)->getScalarSizeInBits() ==
DestTy->getScalarSizeInBits();
case Instruction::IntToPtr:
return DL.getIntPtrType(DestTy)->getScalarSizeInBits() ==
SrcTy->getScalarSizeInBits();
}
}
bool CastInst::isNoopCast(const DataLayout &DL) const {
return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), DL);
}
/// This function determines if a pair of casts can be eliminated and what
/// opcode should be used in the elimination. This assumes that there are two
/// instructions like this:
/// * %F = firstOpcode SrcTy %x to MidTy
/// * %S = secondOpcode MidTy %F to DstTy
/// The function returns a resultOpcode so these two casts can be replaced with:
/// * %Replacement = resultOpcode %SrcTy %x to DstTy
/// If no such cast is permitted, the function returns 0.
unsigned CastInst::isEliminableCastPair(
Instruction::CastOps firstOp, Instruction::CastOps secondOp,
Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy,
Type *DstIntPtrTy) {
// Define the 144 possibilities for these two cast instructions. The values
// in this matrix determine what to do in a given situation and select the
// case in the switch below. The rows correspond to firstOp, the columns
// correspond to secondOp. In looking at the table below, keep in mind
// the following cast properties:
//
// Size Compare Source Destination
// Operator Src ? Size Type Sign Type Sign
// -------- ------------ ------------------- ---------------------
// TRUNC > Integer Any Integral Any
// ZEXT < Integral Unsigned Integer Any
// SEXT < Integral Signed Integer Any
// FPTOUI n/a FloatPt n/a Integral Unsigned
// FPTOSI n/a FloatPt n/a Integral Signed
// UITOFP n/a Integral Unsigned FloatPt n/a
// SITOFP n/a Integral Signed FloatPt n/a
// FPTRUNC > FloatPt n/a FloatPt n/a
// FPEXT < FloatPt n/a FloatPt n/a
// PTRTOINT n/a Pointer n/a Integral Unsigned
// INTTOPTR n/a Integral Unsigned Pointer n/a
// BITCAST = FirstClass n/a FirstClass n/a
// ADDRSPCST n/a Pointer n/a Pointer n/a
//
// NOTE: some transforms are safe, but we consider them to be non-profitable.
// For example, we could merge "fptoui double to i32" + "zext i32 to i64",
// into "fptoui double to i64", but this loses information about the range
// of the produced value (we no longer know the top-part is all zeros).
// Further this conversion is often much more expensive for typical hardware,
// and causes issues when building libgcc. We disallow fptosi+sext for the
// same reason.
const unsigned numCastOps =
Instruction::CastOpsEnd - Instruction::CastOpsBegin;
static const uint8_t CastResults[numCastOps][numCastOps] = {
// T F F U S F F P I B A -+
// R Z S P P I I T P 2 N T S |
// U E E 2 2 2 2 R E I T C C +- secondOp
// N X X U S F F N X N 2 V V |
// C T T I I P P C T T P T T -+
{ 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc -+
{ 8, 1, 9,99,99, 2,17,99,99,99, 2, 3, 0}, // ZExt |
{ 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt |
{ 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI |
{ 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI |
{ 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP +- firstOp
{ 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP |
{ 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // FPTrunc |
{ 99,99,99, 2, 2,99,99, 8, 2,99,99, 4, 0}, // FPExt |
{ 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt |
{ 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr |
{ 5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast |
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+
};
// TODO: This logic could be encoded into the table above and handled in the
// switch below.
// If either of the casts are a bitcast from scalar to vector, disallow the
// merging. However, any pair of bitcasts are allowed.
bool IsFirstBitcast = (firstOp == Instruction::BitCast);
bool IsSecondBitcast = (secondOp == Instruction::BitCast);
bool AreBothBitcasts = IsFirstBitcast && IsSecondBitcast;
// Check if any of the casts convert scalars <-> vectors.
if ((IsFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
(IsSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
if (!AreBothBitcasts)
return 0;
int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
[secondOp-Instruction::CastOpsBegin];
switch (ElimCase) {
case 0:
// Categorically disallowed.
return 0;
case 1:
// Allowed, use first cast's opcode.
return firstOp;
case 2:
// Allowed, use second cast's opcode.
return secondOp;
case 3:
// No-op cast in second op implies firstOp as long as the DestTy
// is integer and we are not converting between a vector and a
// non-vector type.
if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
return firstOp;
return 0;
case 4:
// No-op cast in second op implies firstOp as long as the DestTy
// is floating point.
if (DstTy->isFloatingPointTy())
return firstOp;
return 0;
case 5:
// No-op cast in first op implies secondOp as long as the SrcTy
// is an integer.
if (SrcTy->isIntegerTy())
return secondOp;
return 0;
case 6:
// No-op cast in first op implies secondOp as long as the SrcTy
// is a floating point.
if (SrcTy->isFloatingPointTy())
return secondOp;
return 0;
case 7: {
// Disable inttoptr/ptrtoint optimization if enabled.
if (DisableI2pP2iOpt)
return 0;
// Cannot simplify if address spaces are different!
if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
return 0;
unsigned MidSize = MidTy->getScalarSizeInBits();
// We can still fold this without knowing the actual sizes as long we
// know that the intermediate pointer is the largest possible
// pointer size.
// FIXME: Is this always true?
if (MidSize == 64)
return Instruction::BitCast;
// ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size.
if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy)
return 0;
unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits();
if (MidSize >= PtrSize)
return Instruction::BitCast;
return 0;
}
case 8: {
// ext, trunc -> bitcast, if the SrcTy and DstTy are same size
// ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
// ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
unsigned SrcSize = SrcTy->getScalarSizeInBits();
unsigned DstSize = DstTy->getScalarSizeInBits();
if (SrcSize == DstSize)
return Instruction::BitCast;
else if (SrcSize < DstSize)
return firstOp;
return secondOp;
}
case 9:
// zext, sext -> zext, because sext can't sign extend after zext
return Instruction::ZExt;
case 11: {
// inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
if (!MidIntPtrTy)
return 0;
unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits();
unsigned SrcSize = SrcTy->getScalarSizeInBits();
unsigned DstSize = DstTy->getScalarSizeInBits();
if (SrcSize <= PtrSize && SrcSize == DstSize)
return Instruction::BitCast;
return 0;
}
case 12:
// addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS
// addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS
if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
return Instruction::AddrSpaceCast;
return Instruction::BitCast;
case 13:
// FIXME: this state can be merged with (1), but the following assert
// is useful to check the correcteness of the sequence due to semantic
// change of bitcast.
assert(
SrcTy->isPtrOrPtrVectorTy() &&
MidTy->isPtrOrPtrVectorTy() &&
DstTy->isPtrOrPtrVectorTy() &&
SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() &&
MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
"Illegal addrspacecast, bitcast sequence!");
// Allowed, use first cast's opcode
return firstOp;
case 14: {
// bitcast, addrspacecast -> addrspacecast if the element type of
// bitcast's source is the same as that of addrspacecast's destination.
PointerType *SrcPtrTy = cast<PointerType>(SrcTy->getScalarType());
PointerType *DstPtrTy = cast<PointerType>(DstTy->getScalarType());
if (SrcPtrTy->hasSameElementTypeAs(DstPtrTy))
return Instruction::AddrSpaceCast;
return 0;
}
case 15:
// FIXME: this state can be merged with (1), but the following assert
// is useful to check the correcteness of the sequence due to semantic
// change of bitcast.
assert(
SrcTy->isIntOrIntVectorTy() &&
MidTy->isPtrOrPtrVectorTy() &&
DstTy->isPtrOrPtrVectorTy() &&
MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
"Illegal inttoptr, bitcast sequence!");
// Allowed, use first cast's opcode
return firstOp;
case 16:
// FIXME: this state can be merged with (2), but the following assert
// is useful to check the correcteness of the sequence due to semantic
// change of bitcast.
assert(
SrcTy->isPtrOrPtrVectorTy() &&
MidTy->isPtrOrPtrVectorTy() &&
DstTy->isIntOrIntVectorTy() &&
SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() &&
"Illegal bitcast, ptrtoint sequence!");
// Allowed, use second cast's opcode
return secondOp;
case 17:
// (sitofp (zext x)) -> (uitofp x)
return Instruction::UIToFP;
case 99:
// Cast combination can't happen (error in input). This is for all cases
// where the MidTy is not the same for the two cast instructions.
llvm_unreachable("Invalid Cast Combination");
default:
llvm_unreachable("Error in CastResults table!!!");
}
}
CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
const Twine &Name, Instruction *InsertBefore) {
assert(castIsValid(op, S, Ty) && "Invalid cast!");
// Construct and return the appropriate CastInst subclass
switch (op) {
case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertBefore);
default: llvm_unreachable("Invalid opcode provided");
}
}
CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
const Twine &Name, BasicBlock *InsertAtEnd) {
assert(castIsValid(op, S, Ty) && "Invalid cast!");
// Construct and return the appropriate CastInst subclass
switch (op) {
case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertAtEnd);
default: llvm_unreachable("Invalid opcode provided");
}
}
CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
const Twine &Name,
Instruction *InsertBefore) {
if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
}
CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
const Twine &Name,
BasicBlock *InsertAtEnd) {
if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
}
CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
const Twine &Name,
Instruction *InsertBefore) {
if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
}
CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
const Twine &Name,
BasicBlock *InsertAtEnd) {
if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
}
CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
const Twine &Name,
Instruction *InsertBefore) {
if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
}
CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
const Twine &Name,
BasicBlock *InsertAtEnd) {
if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
}
CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
const Twine &Name,
BasicBlock *InsertAtEnd) {
assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
"Invalid cast");
assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
assert((!Ty->isVectorTy() ||
cast<VectorType>(Ty)->getElementCount() ==
cast<VectorType>(S->getType())->getElementCount()) &&
"Invalid cast");
if (Ty->isIntOrIntVectorTy())
return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertAtEnd);
}
/// Create a BitCast or a PtrToInt cast instruction
CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
const Twine &Name,
Instruction *InsertBefore) {
assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
"Invalid cast");
assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
assert((!Ty->isVectorTy() ||
cast<VectorType>(Ty)->getElementCount() ==
cast<VectorType>(S->getType())->getElementCount()) &&
"Invalid cast");
if (Ty->isIntOrIntVectorTy())
return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore);
}
CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
Value *S, Type *Ty,
const Twine &Name,
BasicBlock *InsertAtEnd) {
assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertAtEnd);
return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
}
CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
Value *S, Type *Ty,
const Twine &Name,
Instruction *InsertBefore) {
assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore);
return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
}
CastInst *CastInst::CreateBitOrPointerCast(Value *S, Type *Ty,
const Twine &Name,
Instruction *InsertBefore) {
if (S->getType()->isPointerTy() && Ty->isIntegerTy())
return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
if (S->getType()->isIntegerTy() && Ty->isPointerTy())
return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore);
return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
}
CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
bool isSigned, const Twine &Name,
Instruction *InsertBefore) {
assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
"Invalid integer cast");
unsigned SrcBits = C->getType()->getScalarSizeInBits();
unsigned DstBits = Ty->getScalarSizeInBits();
Instruction::CastOps opcode =
(SrcBits == DstBits ? Instruction::BitCast :
(SrcBits > DstBits ? Instruction::Trunc :
(isSigned ? Instruction::SExt : Instruction::ZExt)));
return Create(opcode, C, Ty, Name, InsertBefore);
}
CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
bool isSigned, const Twine &Name,
BasicBlock *InsertAtEnd) {
assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
"Invalid cast");
unsigned SrcBits = C->getType()->getScalarSizeInBits();
unsigned DstBits = Ty->getScalarSizeInBits();
Instruction::CastOps opcode =
(SrcBits == DstBits ? Instruction::BitCast :
(SrcBits > DstBits ? Instruction::Trunc :
(isSigned ? Instruction::SExt : Instruction::ZExt)));
return Create(opcode, C, Ty, Name, InsertAtEnd);
}
CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
const Twine &Name,
Instruction *InsertBefore) {
assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
"Invalid cast");
unsigned SrcBits = C->getType()->getScalarSizeInBits();
unsigned DstBits = Ty->getScalarSizeInBits();
Instruction::CastOps opcode =
(SrcBits == DstBits ? Instruction::BitCast :
(SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
return Create(opcode, C, Ty, Name, InsertBefore);
}
CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
const Twine &Name,
BasicBlock *InsertAtEnd) {
assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
"Invalid cast");
unsigned SrcBits = C->getType()->getScalarSizeInBits();
unsigned DstBits = Ty->getScalarSizeInBits();
Instruction::CastOps opcode =
(SrcBits == DstBits ? Instruction::BitCast :
(SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
return Create(opcode, C, Ty, Name, InsertAtEnd);
}
bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) {
if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
return false;
if (SrcTy == DestTy)
return true;
if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) {
if (SrcVecTy->getElementCount() == DestVecTy->getElementCount()) {
// An element by element cast. Valid if casting the elements is valid.
SrcTy = SrcVecTy->getElementType();
DestTy = DestVecTy->getElementType();
}
}
}
if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) {
if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) {
return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace();
}
}
TypeSize SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
TypeSize DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
// Could still have vectors of pointers if the number of elements doesn't
// match
if (SrcBits.getKnownMinSize() == 0 || DestBits.getKnownMinSize() == 0)
return false;
if (SrcBits != DestBits)
return false;
if (DestTy->isX86_MMXTy() || SrcTy->isX86_MMXTy())
return false;
return true;
}
bool CastInst::isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy,
const DataLayout &DL) {
// ptrtoint and inttoptr are not allowed on non-integral pointers
if (auto *PtrTy = dyn_cast<PointerType>(SrcTy))
if (auto *IntTy = dyn_cast<IntegerType>(DestTy))
return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) &&
!DL.isNonIntegralPointerType(PtrTy));
if (auto *PtrTy = dyn_cast<PointerType>(DestTy))
if (auto *IntTy = dyn_cast<IntegerType>(SrcTy))
return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) &&
!DL.isNonIntegralPointerType(PtrTy));
return isBitCastable(SrcTy, DestTy);
}
// Provide a way to get a "cast" where the cast opcode is inferred from the
// types and size of the operand. This, basically, is a parallel of the
// logic in the castIsValid function below. This axiom should hold:
// castIsValid( getCastOpcode(Val, Ty), Val, Ty)
// should not assert in castIsValid. In other words, this produces a "correct"
// casting opcode for the arguments passed to it.
Instruction::CastOps
CastInst::getCastOpcode(
const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
Type *SrcTy = Src->getType();
assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
"Only first class types are castable!");
if (SrcTy == DestTy)
return BitCast;
// FIXME: Check address space sizes here
if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
if (SrcVecTy->getElementCount() == DestVecTy->getElementCount()) {
// An element by element cast. Find the appropriate opcode based on the
// element types.
SrcTy = SrcVecTy->getElementType();
DestTy = DestVecTy->getElementType();
}
// Get the bit sizes, we'll need these
unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
// Run through the possibilities ...
if (DestTy->isIntegerTy()) { // Casting to integral
if (SrcTy->isIntegerTy()) { // Casting from integral
if (DestBits < SrcBits)
return Trunc; // int -> smaller int
else if (DestBits > SrcBits) { // its an extension
if (SrcIsSigned)
return SExt; // signed -> SEXT
else
return ZExt; // unsigned -> ZEXT
} else {
return BitCast; // Same size, No-op cast
}
} else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
if (DestIsSigned)
return FPToSI; // FP -> sint
else
return FPToUI; // FP -> uint
} else if (SrcTy->isVectorTy()) {
assert(DestBits == SrcBits &&
"Casting vector to integer of different width");
return BitCast; // Same size, no-op cast
} else {
assert(SrcTy->isPointerTy() &&
"Casting from a value that is not first-class type");
return PtrToInt; // ptr -> int
}
} else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
if (SrcTy->isIntegerTy()) { // Casting from integral
if (SrcIsSigned)
return SIToFP; // sint -> FP
else
return UIToFP; // uint -> FP
} else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
if (DestBits < SrcBits) {
return FPTrunc; // FP -> smaller FP
} else if (DestBits > SrcBits) {
return FPExt; // FP -> larger FP
} else {
return BitCast; // same size, no-op cast
}
} else if (SrcTy->isVectorTy()) {
assert(DestBits == SrcBits &&
"Casting vector to floating point of different width");
return BitCast; // same size, no-op cast
}
llvm_unreachable("Casting pointer or non-first class to float");
} else if (DestTy->isVectorTy()) {
assert(DestBits == SrcBits &&
"Illegal cast to vector (wrong type or size)");
return BitCast;
} else if (DestTy->isPointerTy()) {
if (SrcTy->isPointerTy()) {
if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace())
return AddrSpaceCast;
return BitCast; // ptr -> ptr
} else if (SrcTy->isIntegerTy()) {
return IntToPtr; // int -> ptr
}
llvm_unreachable("Casting pointer to other than pointer or int");
} else if (DestTy->isX86_MMXTy()) {
if (SrcTy->isVectorTy()) {
assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
return BitCast; // 64-bit vector to MMX
}
llvm_unreachable("Illegal cast to X86_MMX");
}
llvm_unreachable("Casting to type that is not first-class");
}
//===----------------------------------------------------------------------===//
// CastInst SubClass Constructors
//===----------------------------------------------------------------------===//
/// Check that the construction parameters for a CastInst are correct. This
/// could be broken out into the separate constructors but it is useful to have
/// it in one place and to eliminate the redundant code for getting the sizes
/// of the types involved.
bool
CastInst::castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy) {
if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
SrcTy->isAggregateType() || DstTy->isAggregateType())
return false;
// Get the size of the types in bits, and whether we are dealing
// with vector types, we'll need this later.
bool SrcIsVec = isa<VectorType>(SrcTy);
bool DstIsVec = isa<VectorType>(DstTy);
unsigned SrcScalarBitSize = SrcTy->getScalarSizeInBits();
unsigned DstScalarBitSize = DstTy->getScalarSizeInBits();
// If these are vector types, get the lengths of the vectors (using zero for
// scalar types means that checking that vector lengths match also checks that
// scalars are not being converted to vectors or vectors to scalars).
ElementCount SrcEC = SrcIsVec ? cast<VectorType>(SrcTy)->getElementCount()
: ElementCount::getFixed(0);
ElementCount DstEC = DstIsVec ? cast<VectorType>(DstTy)->getElementCount()
: ElementCount::getFixed(0);
// Switch on the opcode provided
switch (op) {
default: return false; // This is an input error
case Instruction::Trunc:
return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
SrcEC == DstEC && SrcScalarBitSize > DstScalarBitSize;
case Instruction::ZExt:
return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize;
case Instruction::SExt:
return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize;
case Instruction::FPTrunc:
return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
SrcEC == DstEC && SrcScalarBitSize > DstScalarBitSize;
case Instruction::FPExt:
return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize;
case Instruction::UIToFP:
case Instruction::SIToFP:
return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
SrcEC == DstEC;
case Instruction::FPToUI:
case Instruction::FPToSI:
return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
SrcEC == DstEC;
case Instruction::PtrToInt:
if (SrcEC != DstEC)
return false;
return SrcTy->isPtrOrPtrVectorTy() && DstTy->isIntOrIntVectorTy();
case Instruction::IntToPtr:
if (SrcEC != DstEC)
return false;
return SrcTy->isIntOrIntVectorTy() && DstTy->isPtrOrPtrVectorTy();
case Instruction::BitCast: {
PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
// BitCast implies a no-op cast of type only. No bits change.
// However, you can't cast pointers to anything but pointers.
if (!SrcPtrTy != !DstPtrTy)
return false;
// For non-pointer cases, the cast is okay if the source and destination bit
// widths are identical.
if (!SrcPtrTy)
return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
// If both are pointers then the address spaces must match.
if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace())
return false;
// A vector of pointers must have the same number of elements.
if (SrcIsVec && DstIsVec)
return SrcEC == DstEC;
if (SrcIsVec)
return SrcEC == ElementCount::getFixed(1);
if (DstIsVec)
return DstEC == ElementCount::getFixed(1);
return true;
}
case Instruction::AddrSpaceCast: {
PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
if (!SrcPtrTy)
return false;
PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
if (!DstPtrTy)
return false;
if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
return false;
return SrcEC == DstEC;
}
}
}
TruncInst::TruncInst(
Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
}
TruncInst::TruncInst(
Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
}
ZExtInst::ZExtInst(
Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
}
ZExtInst::ZExtInst(
Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
}
SExtInst::SExtInst(
Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
) : CastInst(Ty, SExt, S, Name, InsertBefore) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
}
SExtInst::SExtInst(
Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
}
FPTruncInst::FPTruncInst(
Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
}
FPTruncInst::FPTruncInst(
Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
}
FPExtInst::FPExtInst(
Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
}
FPExtInst::FPExtInst(
Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
}
UIToFPInst::UIToFPInst(
Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
}
UIToFPInst::UIToFPInst(
Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
}
SIToFPInst::SIToFPInst(
Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
}
SIToFPInst::SIToFPInst(
Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
}
FPToUIInst::FPToUIInst(
Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
}
FPToUIInst::FPToUIInst(
Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
}
FPToSIInst::FPToSIInst(
Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
}
FPToSIInst::FPToSIInst(
Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
}
PtrToIntInst::PtrToIntInst(
Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
}
PtrToIntInst::PtrToIntInst(
Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
}
IntToPtrInst::IntToPtrInst(
Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
}
IntToPtrInst::IntToPtrInst(
Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
}
BitCastInst::BitCastInst(
Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
}
BitCastInst::BitCastInst(
Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
}
AddrSpaceCastInst::AddrSpaceCastInst(
Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
) : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
}
AddrSpaceCastInst::AddrSpaceCastInst(
Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
) : CastInst(Ty, AddrSpaceCast, S, Name, InsertAtEnd) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
}
//===----------------------------------------------------------------------===//
// CmpInst Classes
//===----------------------------------------------------------------------===//
CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS,
Value *RHS, const Twine &Name, Instruction *InsertBefore,
Instruction *FlagsSource)
: Instruction(ty, op,
OperandTraits<CmpInst>::op_begin(this),
OperandTraits<CmpInst>::operands(this),
InsertBefore) {
Op<0>() = LHS;
Op<1>() = RHS;
setPredicate((Predicate)predicate);
setName(Name);
if (FlagsSource)
copyIRFlags(FlagsSource);
}
CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS,
Value *RHS, const Twine &Name, BasicBlock *InsertAtEnd)
: Instruction(ty, op,
OperandTraits<CmpInst>::op_begin(this),
OperandTraits<CmpInst>::operands(this),
InsertAtEnd) {
Op<0>() = LHS;
Op<1>() = RHS;
setPredicate((Predicate)predicate);
setName(Name);
}
CmpInst *
CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2,
const Twine &Name, Instruction *InsertBefore) {
if (Op == Instruction::ICmp) {
if (InsertBefore)
return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
S1, S2, Name);
else
return new ICmpInst(CmpInst::Predicate(predicate),
S1, S2, Name);
}
if (InsertBefore)
return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
S1, S2, Name);
else
return new FCmpInst(CmpInst::Predicate(predicate),
S1, S2, Name);
}
CmpInst *
CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2,
const Twine &Name, BasicBlock *InsertAtEnd) {
if (Op == Instruction::ICmp) {
return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
S1, S2, Name);
}
return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
S1, S2, Name);
}
void CmpInst::swapOperands() {
if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
IC->swapOperands();
else
cast<FCmpInst>(this)->swapOperands();
}
bool CmpInst::isCommutative() const {
if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
return IC->isCommutative();
return cast<FCmpInst>(this)->isCommutative();
}
bool CmpInst::isEquality(Predicate P) {
if (ICmpInst::isIntPredicate(P))
return ICmpInst::isEquality(P);
if (FCmpInst::isFPPredicate(P))
return FCmpInst::isEquality(P);
llvm_unreachable("Unsupported predicate kind");
}
CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
switch (pred) {
default: llvm_unreachable("Unknown cmp predicate!");
case ICMP_EQ: return ICMP_NE;
case ICMP_NE: return ICMP_EQ;
case ICMP_UGT: return ICMP_ULE;
case ICMP_ULT: return ICMP_UGE;
case ICMP_UGE: return ICMP_ULT;
case ICMP_ULE: return ICMP_UGT;
case ICMP_SGT: return ICMP_SLE;
case ICMP_SLT: return ICMP_SGE;
case ICMP_SGE: return ICMP_SLT;
case ICMP_SLE: return ICMP_SGT;
case FCMP_OEQ: return FCMP_UNE;
case FCMP_ONE: return FCMP_UEQ;
case FCMP_OGT: return FCMP_ULE;
case FCMP_OLT: return FCMP_UGE;
case FCMP_OGE: return FCMP_ULT;
case FCMP_OLE: return FCMP_UGT;
case FCMP_UEQ: return FCMP_ONE;
case FCMP_UNE: return FCMP_OEQ;
case FCMP_UGT: return FCMP_OLE;
case FCMP_ULT: return FCMP_OGE;
case FCMP_UGE: return FCMP_OLT;
case FCMP_ULE: return FCMP_OGT;
case FCMP_ORD: return FCMP_UNO;
case FCMP_UNO: return FCMP_ORD;
case FCMP_TRUE: return FCMP_FALSE;
case FCMP_FALSE: return FCMP_TRUE;
}
}
StringRef CmpInst::getPredicateName(Predicate Pred) {
switch (Pred) {
default: return "unknown";
case FCmpInst::FCMP_FALSE: return "false";
case FCmpInst::FCMP_OEQ: return "oeq";
case FCmpInst::FCMP_OGT: return "ogt";
case FCmpInst::FCMP_OGE: return "oge";
case FCmpInst::FCMP_OLT: return "olt";
case FCmpInst::FCMP_OLE: return "ole";
case FCmpInst::FCMP_ONE: return "one";
case FCmpInst::FCMP_ORD: return "ord";
case FCmpInst::FCMP_UNO: return "uno";
case FCmpInst::FCMP_UEQ: return "ueq";
case FCmpInst::FCMP_UGT: return "ugt";
case FCmpInst::FCMP_UGE: return "uge";
case FCmpInst::FCMP_ULT: return "ult";
case FCmpInst::FCMP_ULE: return "ule";
case FCmpInst::FCMP_UNE: return "une";
case FCmpInst::FCMP_TRUE: return "true";
case ICmpInst::ICMP_EQ: return "eq";
case ICmpInst::ICMP_NE: return "ne";
case ICmpInst::ICMP_SGT: return "sgt";
case ICmpInst::ICMP_SGE: return "sge";
case ICmpInst::ICMP_SLT: return "slt";
case ICmpInst::ICMP_SLE: return "sle";
case ICmpInst::ICMP_UGT: return "ugt";
case ICmpInst::ICMP_UGE: return "uge";
case ICmpInst::ICMP_ULT: return "ult";
case ICmpInst::ICMP_ULE: return "ule";
}
}
ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
switch (pred) {
default: llvm_unreachable("Unknown icmp predicate!");
case ICMP_EQ: case ICMP_NE:
case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
return pred;
case ICMP_UGT: return ICMP_SGT;
case ICMP_ULT: return ICMP_SLT;
case ICMP_UGE: return ICMP_SGE;
case ICMP_ULE: return ICMP_SLE;
}
}
ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
switch (pred) {
default: llvm_unreachable("Unknown icmp predicate!");
case ICMP_EQ: case ICMP_NE:
case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
return pred;
case ICMP_SGT: return ICMP_UGT;
case ICMP_SLT: return ICMP_ULT;
case ICMP_SGE: return ICMP_UGE;
case ICMP_SLE: return ICMP_ULE;
}
}
CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
switch (pred) {
default: llvm_unreachable("Unknown cmp predicate!");
case ICMP_EQ: case ICMP_NE:
return pred;
case ICMP_SGT: return ICMP_SLT;
case ICMP_SLT: return ICMP_SGT;
case ICMP_SGE: return ICMP_SLE;
case ICMP_SLE: return ICMP_SGE;
case ICMP_UGT: return ICMP_ULT;
case ICMP_ULT: return ICMP_UGT;
case ICMP_UGE: return ICMP_ULE;
case ICMP_ULE: return ICMP_UGE;
case FCMP_FALSE: case FCMP_TRUE:
case FCMP_OEQ: case FCMP_ONE:
case FCMP_UEQ: case FCMP_UNE:
case FCMP_ORD: case FCMP_UNO:
return pred;
case FCMP_OGT: return FCMP_OLT;
case FCMP_OLT: return FCMP_OGT;
case FCMP_OGE: return FCMP_OLE;
case FCMP_OLE: return FCMP_OGE;
case FCMP_UGT: return FCMP_ULT;
case FCMP_ULT: return FCMP_UGT;
case FCMP_UGE: return FCMP_ULE;
case FCMP_ULE: return FCMP_UGE;
}
}
bool CmpInst::isNonStrictPredicate(Predicate pred) {
switch (pred) {
case ICMP_SGE:
case ICMP_SLE:
case ICMP_UGE:
case ICMP_ULE:
case FCMP_OGE:
case FCMP_OLE:
case FCMP_UGE:
case FCMP_ULE:
return true;
default:
return false;
}
}
bool CmpInst::isStrictPredicate(Predicate pred) {
switch (pred) {
case ICMP_SGT:
case ICMP_SLT:
case ICMP_UGT:
case ICMP_ULT:
case FCMP_OGT:
case FCMP_OLT:
case FCMP_UGT:
case FCMP_ULT:
return true;
default:
return false;
}
}
CmpInst::Predicate CmpInst::getStrictPredicate(Predicate pred) {
switch (pred) {
case ICMP_SGE:
return ICMP_SGT;
case ICMP_SLE:
return ICMP_SLT;
case ICMP_UGE:
return ICMP_UGT;
case ICMP_ULE:
return ICMP_ULT;
case FCMP_OGE:
return FCMP_OGT;
case FCMP_OLE:
return FCMP_OLT;
case FCMP_UGE:
return FCMP_UGT;
case FCMP_ULE:
return FCMP_ULT;
default:
return pred;
}
}
CmpInst::Predicate CmpInst::getNonStrictPredicate(Predicate pred) {
switch (pred) {
case ICMP_SGT:
return ICMP_SGE;
case ICMP_SLT:
return ICMP_SLE;
case ICMP_UGT:
return ICMP_UGE;
case ICMP_ULT:
return ICMP_ULE;
case FCMP_OGT:
return FCMP_OGE;
case FCMP_OLT:
return FCMP_OLE;
case FCMP_UGT:
return FCMP_UGE;
case FCMP_ULT:
return FCMP_ULE;
default:
return pred;
}
}
CmpInst::Predicate CmpInst::getFlippedStrictnessPredicate(Predicate pred) {
assert(CmpInst::isRelational(pred) && "Call only with relational predicate!");
if (isStrictPredicate(pred))
return getNonStrictPredicate(pred);
if (isNonStrictPredicate(pred))
return getStrictPredicate(pred);
llvm_unreachable("Unknown predicate!");
}
CmpInst::Predicate CmpInst::getSignedPredicate(Predicate pred) {
assert(CmpInst::isUnsigned(pred) && "Call only with unsigned predicates!");
switch (pred) {
default:
llvm_unreachable("Unknown predicate!");
case CmpInst::ICMP_ULT:
return CmpInst::ICMP_SLT;
case CmpInst::ICMP_ULE:
return CmpInst::ICMP_SLE;
case CmpInst::ICMP_UGT:
return CmpInst::ICMP_SGT;
case CmpInst::ICMP_UGE:
return CmpInst::ICMP_SGE;
}
}
CmpInst::Predicate CmpInst::getUnsignedPredicate(Predicate pred) {
assert(CmpInst::isSigned(pred) && "Call only with signed predicates!");
switch (pred) {
default:
llvm_unreachable("Unknown predicate!");
case CmpInst::ICMP_SLT:
return CmpInst::ICMP_ULT;
case CmpInst::ICMP_SLE:
return CmpInst::ICMP_ULE;
case CmpInst::ICMP_SGT:
return CmpInst::ICMP_UGT;
case CmpInst::ICMP_SGE:
return CmpInst::ICMP_UGE;
}
}
bool CmpInst::isUnsigned(Predicate predicate) {
switch (predicate) {
default: return false;
case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
case ICmpInst::ICMP_UGE: return true;
}
}
bool CmpInst::isSigned(Predicate predicate) {
switch (predicate) {
default: return false;
case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
case ICmpInst::ICMP_SGE: return true;
}
}
bool ICmpInst::compare(const APInt &LHS, const APInt &RHS,
ICmpInst::Predicate Pred) {
assert(ICmpInst::isIntPredicate(Pred) && "Only for integer predicates!");
switch (Pred) {
case ICmpInst::Predicate::ICMP_EQ:
return LHS.eq(RHS);
case ICmpInst::Predicate::ICMP_NE:
return LHS.ne(RHS);
case ICmpInst::Predicate::ICMP_UGT:
return LHS.ugt(RHS);
case ICmpInst::Predicate::ICMP_UGE:
return LHS.uge(RHS);
case ICmpInst::Predicate::ICMP_ULT:
return LHS.ult(RHS);
case ICmpInst::Predicate::ICMP_ULE:
return LHS.ule(RHS);
case ICmpInst::Predicate::ICMP_SGT:
return LHS.sgt(RHS);
case ICmpInst::Predicate::ICMP_SGE:
return LHS.sge(RHS);
case ICmpInst::Predicate::ICMP_SLT:
return LHS.slt(RHS);
case ICmpInst::Predicate::ICMP_SLE:
return LHS.sle(RHS);
default:
llvm_unreachable("Unexpected non-integer predicate.");
};
}
bool FCmpInst::compare(const APFloat &LHS, const APFloat &RHS,
FCmpInst::Predicate Pred) {
APFloat::cmpResult R = LHS.compare(RHS);
switch (Pred) {
default:
llvm_unreachable("Invalid FCmp Predicate");
case FCmpInst::FCMP_FALSE:
return false;
case FCmpInst::FCMP_TRUE:
return true;
case FCmpInst::FCMP_UNO:
return R == APFloat::cmpUnordered;
case FCmpInst::FCMP_ORD:
return R != APFloat::cmpUnordered;
case FCmpInst::FCMP_UEQ:
return R == APFloat::cmpUnordered || R == APFloat::cmpEqual;
case FCmpInst::FCMP_OEQ:
return R == APFloat::cmpEqual;
case FCmpInst::FCMP_UNE:
return R != APFloat::cmpEqual;
case FCmpInst::FCMP_ONE:
return R == APFloat::cmpLessThan || R == APFloat::cmpGreaterThan;
case FCmpInst::FCMP_ULT:
return R == APFloat::cmpUnordered || R == APFloat::cmpLessThan;
case FCmpInst::FCMP_OLT:
return R == APFloat::cmpLessThan;
case FCmpInst::FCMP_UGT:
return R == APFloat::cmpUnordered || R == APFloat::cmpGreaterThan;
case FCmpInst::FCMP_OGT:
return R == APFloat::cmpGreaterThan;
case FCmpInst::FCMP_ULE:
return R != APFloat::cmpGreaterThan;
case FCmpInst::FCMP_OLE:
return R == APFloat::cmpLessThan || R == APFloat::cmpEqual;
case FCmpInst::FCMP_UGE:
return R != APFloat::cmpLessThan;
case FCmpInst::FCMP_OGE:
return R == APFloat::cmpGreaterThan || R == APFloat::cmpEqual;
}
}
CmpInst::Predicate CmpInst::getFlippedSignednessPredicate(Predicate pred) {
assert(CmpInst::isRelational(pred) &&
"Call only with non-equality predicates!");
if (isSigned(pred))
return getUnsignedPredicate(pred);
if (isUnsigned(pred))
return getSignedPredicate(pred);
llvm_unreachable("Unknown predicate!");
}
bool CmpInst::isOrdered(Predicate predicate) {
switch (predicate) {
default: return false;
case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
case FCmpInst::FCMP_ORD: return true;
}
}
bool CmpInst::isUnordered(Predicate predicate) {
switch (predicate) {
default: return false;
case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
case FCmpInst::FCMP_UNO: return true;
}
}
bool CmpInst::isTrueWhenEqual(Predicate predicate) {
switch(predicate) {
default: return false;
case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
}
}
bool CmpInst::isFalseWhenEqual(Predicate predicate) {
switch(predicate) {
case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
default: return false;
}
}
bool CmpInst::isImpliedTrueByMatchingCmp(Predicate Pred1, Predicate Pred2) {
// If the predicates match, then we know the first condition implies the
// second is true.
if (Pred1 == Pred2)
return true;
switch (Pred1) {
default:
break;
case ICMP_EQ:
// A == B implies A >=u B, A <=u B, A >=s B, and A <=s B are true.
return Pred2 == ICMP_UGE || Pred2 == ICMP_ULE || Pred2 == ICMP_SGE ||
Pred2 == ICMP_SLE;
case ICMP_UGT: // A >u B implies A != B and A >=u B are true.
return Pred2 == ICMP_NE || Pred2 == ICMP_UGE;
case ICMP_ULT: // A <u B implies A != B and A <=u B are true.
return Pred2 == ICMP_NE || Pred2 == ICMP_ULE;
case ICMP_SGT: // A >s B implies A != B and A >=s B are true.
return Pred2 == ICMP_NE || Pred2 == ICMP_SGE;
case ICMP_SLT: // A <s B implies A != B and A <=s B are true.
return Pred2 == ICMP_NE || Pred2 == ICMP_SLE;
}
return false;
}
bool CmpInst::isImpliedFalseByMatchingCmp(Predicate Pred1, Predicate Pred2) {
return isImpliedTrueByMatchingCmp(Pred1, getInversePredicate(Pred2));
}
//===----------------------------------------------------------------------===//
// SwitchInst Implementation
//===----------------------------------------------------------------------===//
void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
assert(Value && Default && NumReserved);
ReservedSpace = NumReserved;
setNumHungOffUseOperands(2);
allocHungoffUses(ReservedSpace);
Op<0>() = Value;
Op<1>() = Default;
}
/// SwitchInst ctor - Create a new switch instruction, specifying a value to
/// switch on and a default destination. The number of additional cases can
/// be specified here to make memory allocation more efficient. This
/// constructor can also autoinsert before another instruction.
SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
Instruction *InsertBefore)
: Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch,
nullptr, 0, InsertBefore) {
init(Value, Default, 2+NumCases*2);
}
/// SwitchInst ctor - Create a new switch instruction, specifying a value to
/// switch on and a default destination. The number of additional cases can
/// be specified here to make memory allocation more efficient. This
/// constructor also autoinserts at the end of the specified BasicBlock.
SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
BasicBlock *InsertAtEnd)
: Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch,
nullptr, 0, InsertAtEnd) {
init(Value, Default, 2+NumCases*2);
}
SwitchInst::SwitchInst(const SwitchInst &SI)
: Instruction(SI.getType(), Instruction::Switch, nullptr, 0) {
init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
setNumHungOffUseOperands(SI.getNumOperands());
Use *OL = getOperandList();
const Use *InOL = SI.getOperandList();
for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
OL[i] = InOL[i];
OL[i+1] = InOL[i+1];
}
SubclassOptionalData = SI.SubclassOptionalData;
}
/// addCase - Add an entry to the switch instruction...
///
void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
unsigned NewCaseIdx = getNumCases();
unsigned OpNo = getNumOperands();
if (OpNo+2 > ReservedSpace)
growOperands(); // Get more space!
// Initialize some new operands.
assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
setNumHungOffUseOperands(OpNo+2);
CaseHandle Case(this, NewCaseIdx);
Case.setValue(OnVal);
Case.setSuccessor(Dest);
}
/// removeCase - This method removes the specified case and its successor
/// from the switch instruction.
SwitchInst::CaseIt SwitchInst::removeCase(CaseIt I) {
unsigned idx = I->getCaseIndex();
assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
unsigned NumOps = getNumOperands();
Use *OL = getOperandList();
// Overwrite this case with the end of the list.
if (2 + (idx + 1) * 2 != NumOps) {
OL[2 + idx * 2] = OL[NumOps - 2];
OL[2 + idx * 2 + 1] = OL[NumOps - 1];
}
// Nuke the last value.
OL[NumOps-2].set(nullptr);
OL[NumOps-2+1].set(nullptr);
setNumHungOffUseOperands(NumOps-2);
return CaseIt(this, idx);
}
/// growOperands - grow operands - This grows the operand list in response
/// to a push_back style of operation. This grows the number of ops by 3 times.
///
void SwitchInst::growOperands() {
unsigned e = getNumOperands();
unsigned NumOps = e*3;
ReservedSpace = NumOps;
growHungoffUses(ReservedSpace);
}
MDNode *
SwitchInstProfUpdateWrapper::getProfBranchWeightsMD(const SwitchInst &SI) {
if (MDNode *ProfileData = SI.getMetadata(LLVMContext::MD_prof))
if (auto *MDName = dyn_cast<MDString>(ProfileData->getOperand(0)))
if (MDName->getString() == "branch_weights")
return ProfileData;
return nullptr;
}
MDNode *SwitchInstProfUpdateWrapper::buildProfBranchWeightsMD() {
assert(Changed && "called only if metadata has changed");
if (!Weights)
return nullptr;
assert(SI.getNumSuccessors() == Weights->size() &&
"num of prof branch_weights must accord with num of successors");
bool AllZeroes =
all_of(Weights.getValue(), [](uint32_t W) { return W == 0; });
if (AllZeroes || Weights.getValue().size() < 2)
return nullptr;
return MDBuilder(SI.getParent()->getContext()).createBranchWeights(*Weights);
}
void SwitchInstProfUpdateWrapper::init() {
MDNode *ProfileData = getProfBranchWeightsMD(SI);
if (!ProfileData)
return;
if (ProfileData->getNumOperands() != SI.getNumSuccessors() + 1) {
llvm_unreachable("number of prof branch_weights metadata operands does "
"not correspond to number of succesors");
}
SmallVector<uint32_t, 8> Weights;
for (unsigned CI = 1, CE = SI.getNumSuccessors(); CI <= CE; ++CI) {
ConstantInt *C = mdconst::extract<ConstantInt>(ProfileData->getOperand(CI));
uint32_t CW = C->getValue().getZExtValue();
Weights.push_back(CW);
}
this->Weights = std::move(Weights);
}
SwitchInst::CaseIt
SwitchInstProfUpdateWrapper::removeCase(SwitchInst::CaseIt I) {
if (Weights) {
assert(SI.getNumSuccessors() == Weights->size() &&
"num of prof branch_weights must accord with num of successors");
Changed = true;
// Copy the last case to the place of the removed one and shrink.
// This is tightly coupled with the way SwitchInst::removeCase() removes
// the cases in SwitchInst::removeCase(CaseIt).
Weights.getValue()[I->getCaseIndex() + 1] = Weights.getValue().back();
Weights.getValue().pop_back();
}
return SI.removeCase(I);
}
void SwitchInstProfUpdateWrapper::addCase(
ConstantInt *OnVal, BasicBlock *Dest,
SwitchInstProfUpdateWrapper::CaseWeightOpt W) {
SI.addCase(OnVal, Dest);
if (!Weights && W && *W) {
Changed = true;
Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0);
Weights.getValue()[SI.getNumSuccessors() - 1] = *W;
} else if (Weights) {
Changed = true;
Weights.getValue().push_back(W.getValueOr(0));
}
if (Weights)
assert(SI.getNumSuccessors() == Weights->size() &&
"num of prof branch_weights must accord with num of successors");
}
SymbolTableList<Instruction>::iterator
SwitchInstProfUpdateWrapper::eraseFromParent() {
// Instruction is erased. Mark as unchanged to not touch it in the destructor.
Changed = false;
if (Weights)
Weights->resize(0);
return SI.eraseFromParent();
}
SwitchInstProfUpdateWrapper::CaseWeightOpt
SwitchInstProfUpdateWrapper::getSuccessorWeight(unsigned idx) {
if (!Weights)
return None;
return Weights.getValue()[idx];
}
void SwitchInstProfUpdateWrapper::setSuccessorWeight(
unsigned idx, SwitchInstProfUpdateWrapper::CaseWeightOpt W) {
if (!W)
return;
if (!Weights && *W)
Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0);
if (Weights) {
auto &OldW = Weights.getValue()[idx];
if (*W != OldW) {
Changed = true;
OldW = *W;
}
}
}
SwitchInstProfUpdateWrapper::CaseWeightOpt
SwitchInstProfUpdateWrapper::getSuccessorWeight(const SwitchInst &SI,
unsigned idx) {
if (MDNode *ProfileData = getProfBranchWeightsMD(SI))
if (ProfileData->getNumOperands() == SI.getNumSuccessors() + 1)
return mdconst::extract<ConstantInt>(ProfileData->getOperand(idx + 1))
->getValue()
.getZExtValue();
return None;
}
//===----------------------------------------------------------------------===//
// IndirectBrInst Implementation
//===----------------------------------------------------------------------===//
void IndirectBrInst::init(Value *Address, unsigned NumDests) {
assert(Address && Address->getType()->isPointerTy() &&
"Address of indirectbr must be a pointer");
ReservedSpace = 1+NumDests;
setNumHungOffUseOperands(1);
allocHungoffUses(ReservedSpace);
Op<0>() = Address;
}
/// growOperands - grow operands - This grows the operand list in response
/// to a push_back style of operation. This grows the number of ops by 2 times.
///
void IndirectBrInst::growOperands() {
unsigned e = getNumOperands();
unsigned NumOps = e*2;
ReservedSpace = NumOps;
growHungoffUses(ReservedSpace);
}
IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
Instruction *InsertBefore)
: Instruction(Type::getVoidTy(Address->getContext()),
Instruction::IndirectBr, nullptr, 0, InsertBefore) {
init(Address, NumCases);
}
IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
BasicBlock *InsertAtEnd)
: Instruction(Type::getVoidTy(Address->getContext()),
Instruction::IndirectBr, nullptr, 0, InsertAtEnd) {
init(Address, NumCases);
}
IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
: Instruction(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
nullptr, IBI.getNumOperands()) {
allocHungoffUses(IBI.getNumOperands());
Use *OL = getOperandList();
const Use *InOL = IBI.getOperandList();
for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
OL[i] = InOL[i];
SubclassOptionalData = IBI.SubclassOptionalData;
}
/// addDestination - Add a destination.
///
void IndirectBrInst::addDestination(BasicBlock *DestBB) {
unsigned OpNo = getNumOperands();
if (OpNo+1 > ReservedSpace)
growOperands(); // Get more space!
// Initialize some new operands.
assert(OpNo < ReservedSpace && "Growing didn't work!");
setNumHungOffUseOperands(OpNo+1);
getOperandList()[OpNo] = DestBB;
}
/// removeDestination - This method removes the specified successor from the
/// indirectbr instruction.
void IndirectBrInst::removeDestination(unsigned idx) {
assert(idx < getNumOperands()-1 && "Successor index out of range!");
unsigned NumOps = getNumOperands();
Use *OL = getOperandList();
// Replace this value with the last one.
OL[idx+1] = OL[NumOps-1];
// Nuke the last value.
OL[NumOps-1].set(nullptr);
setNumHungOffUseOperands(NumOps-1);
}
//===----------------------------------------------------------------------===//
// FreezeInst Implementation
//===----------------------------------------------------------------------===//
FreezeInst::FreezeInst(Value *S,
const Twine &Name, Instruction *InsertBefore)
: UnaryInstruction(S->getType(), Freeze, S, InsertBefore) {
setName(Name);
}
FreezeInst::FreezeInst(Value *S,
const Twine &Name, BasicBlock *InsertAtEnd)
: UnaryInstruction(S->getType(), Freeze, S, InsertAtEnd) {
setName(Name);
}
//===----------------------------------------------------------------------===//
// cloneImpl() implementations
//===----------------------------------------------------------------------===//
// Define these methods here so vtables don't get emitted into every translation
// unit that uses these classes.
GetElementPtrInst *GetElementPtrInst::cloneImpl() const {
return new (getNumOperands()) GetElementPtrInst(*this);
}
UnaryOperator *UnaryOperator::cloneImpl() const {
return Create(getOpcode(), Op<0>());
}
BinaryOperator *BinaryOperator::cloneImpl() const {
return Create(getOpcode(), Op<0>(), Op<1>());
}
FCmpInst *FCmpInst::cloneImpl() const {
return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
}
ICmpInst *ICmpInst::cloneImpl() const {
return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
}
ExtractValueInst *ExtractValueInst::cloneImpl() const {
return new ExtractValueInst(*this);
}
InsertValueInst *InsertValueInst::cloneImpl() const {
return new InsertValueInst(*this);
}
AllocaInst *AllocaInst::cloneImpl() const {
AllocaInst *Result =
new AllocaInst(getAllocatedType(), getType()->getAddressSpace(),
getOperand(0), getAlign());
Result->setUsedWithInAlloca(isUsedWithInAlloca());
Result->setSwiftError(isSwiftError());
return Result;
}
LoadInst *LoadInst::cloneImpl() const {
return new LoadInst(getType(), getOperand(0), Twine(), isVolatile(),
getAlign(), getOrdering(), getSyncScopeID());
}
StoreInst *StoreInst::cloneImpl() const {
return new StoreInst(getOperand(0), getOperand(1), isVolatile(), getAlign(),
getOrdering(), getSyncScopeID());
}
AtomicCmpXchgInst *AtomicCmpXchgInst::cloneImpl() const {
AtomicCmpXchgInst *Result = new AtomicCmpXchgInst(
getOperand(0), getOperand(1), getOperand(2), getAlign(),
getSuccessOrdering(), getFailureOrdering(), getSyncScopeID());
Result->setVolatile(isVolatile());
Result->setWeak(isWeak());
return Result;
}
AtomicRMWInst *AtomicRMWInst::cloneImpl() const {
AtomicRMWInst *Result =
new AtomicRMWInst(getOperation(), getOperand(0), getOperand(1),
getAlign(), getOrdering(), getSyncScopeID());
Result->setVolatile(isVolatile());
return Result;
}
FenceInst *FenceInst::cloneImpl() const {
return new FenceInst(getContext(), getOrdering(), getSyncScopeID());
}
TruncInst *TruncInst::cloneImpl() const {
return new TruncInst(getOperand(0), getType());
}
ZExtInst *ZExtInst::cloneImpl() const {
return new ZExtInst(getOperand(0), getType());
}
SExtInst *SExtInst::cloneImpl() const {
return new SExtInst(getOperand(0), getType());
}
FPTruncInst *FPTruncInst::cloneImpl() const {
return new FPTruncInst(getOperand(0), getType());
}
FPExtInst *FPExtInst::cloneImpl() const {
return new FPExtInst(getOperand(0), getType());
}
UIToFPInst *UIToFPInst::cloneImpl() const {
return new UIToFPInst(getOperand(0), getType());
}
SIToFPInst *SIToFPInst::cloneImpl() const {
return new SIToFPInst(getOperand(0), getType());
}
FPToUIInst *FPToUIInst::cloneImpl() const {
return new FPToUIInst(getOperand(0), getType());
}
FPToSIInst *FPToSIInst::cloneImpl() const {
return new FPToSIInst(getOperand(0), getType());
}
PtrToIntInst *PtrToIntInst::cloneImpl() const {
return new PtrToIntInst(getOperand(0), getType());
}
IntToPtrInst *IntToPtrInst::cloneImpl() const {
return new IntToPtrInst(getOperand(0), getType());
}
BitCastInst *BitCastInst::cloneImpl() const {
return new BitCastInst(getOperand(0), getType());
}
AddrSpaceCastInst *AddrSpaceCastInst::cloneImpl() const {
return new AddrSpaceCastInst(getOperand(0), getType());
}
CallInst *CallInst::cloneImpl() const {
if (hasOperandBundles()) {
unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo);
return new(getNumOperands(), DescriptorBytes) CallInst(*this);
}
return new(getNumOperands()) CallInst(*this);
}
SelectInst *SelectInst::cloneImpl() const {
return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
}
VAArgInst *VAArgInst::cloneImpl() const {
return new VAArgInst(getOperand(0), getType());
}
ExtractElementInst *ExtractElementInst::cloneImpl() const {
return ExtractElementInst::Create(getOperand(0), getOperand(1));
}
InsertElementInst *InsertElementInst::cloneImpl() const {
return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
}
ShuffleVectorInst *ShuffleVectorInst::cloneImpl() const {
return new ShuffleVectorInst(getOperand(0), getOperand(1), getShuffleMask());
}
PHINode *PHINode::cloneImpl() const { return new PHINode(*this); }
LandingPadInst *LandingPadInst::cloneImpl() const {
return new LandingPadInst(*this);
}
ReturnInst *ReturnInst::cloneImpl() const {
return new(getNumOperands()) ReturnInst(*this);
}
BranchInst *BranchInst::cloneImpl() const {
return new(getNumOperands()) BranchInst(*this);
}
SwitchInst *SwitchInst::cloneImpl() const { return new SwitchInst(*this); }
IndirectBrInst *IndirectBrInst::cloneImpl() const {
return new IndirectBrInst(*this);
}
InvokeInst *InvokeInst::cloneImpl() const {
if (hasOperandBundles()) {
unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo);
return new(getNumOperands(), DescriptorBytes) InvokeInst(*this);
}
return new(getNumOperands()) InvokeInst(*this);
}
CallBrInst *CallBrInst::cloneImpl() const {
if (hasOperandBundles()) {
unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo);
return new (getNumOperands(), DescriptorBytes) CallBrInst(*this);
}
return new (getNumOperands()) CallBrInst(*this);
}
ResumeInst *ResumeInst::cloneImpl() const { return new (1) ResumeInst(*this); }
CleanupReturnInst *CleanupReturnInst::cloneImpl() const {
return new (getNumOperands()) CleanupReturnInst(*this);
}
CatchReturnInst *CatchReturnInst::cloneImpl() const {
return new (getNumOperands()) CatchReturnInst(*this);
}
CatchSwitchInst *CatchSwitchInst::cloneImpl() const {
return new CatchSwitchInst(*this);
}
FuncletPadInst *FuncletPadInst::cloneImpl() const {
return new (getNumOperands()) FuncletPadInst(*this);
}
UnreachableInst *UnreachableInst::cloneImpl() const {
LLVMContext &Context = getContext();
return new UnreachableInst(Context);
}
FreezeInst *FreezeInst::cloneImpl() const {
return new FreezeInst(getOperand(0));
}
| [
"agarny@hellix.com"
] | agarny@hellix.com |
dc2d189beacc592aadc739f5399fdfe1cba5c665 | 3d6e3bed8ffc6c31cedbfce5fb7b18906a11e556 | /src/RcppExports.cpp | 9198483b4c6fd665b3f6de1f88779d291defc46e | [] | no_license | AnestisTouloumis/ShrinkCovMat | df2b2164554d8ab5b8dcc106c8ba8c36defd7b86 | 7941b4c65493ea01fdf6f355a231bbdb64a88943 | refs/heads/master | 2023-07-25T09:31:08.904217 | 2023-07-21T09:02:13 | 2023-07-21T09:02:13 | 94,104,864 | 11 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,952 | cpp | // Generated by using Rcpp::compileAttributes() -> do not edit by hand
// Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
#include <RcppArmadillo.h>
#include <Rcpp.h>
using namespace Rcpp;
#ifdef RCPP_USE_GLOBAL_ROSTREAM
Rcpp::Rostream<true>& Rcpp::Rcout = Rcpp::Rcpp_cout_get();
Rcpp::Rostream<false>& Rcpp::Rcerr = Rcpp::Rcpp_cerr_get();
#endif
// centerdata
arma::mat centerdata(arma::mat X);
RcppExport SEXP _ShrinkCovMat_centerdata(SEXP XSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< arma::mat >::type X(XSEXP);
rcpp_result_gen = Rcpp::wrap(centerdata(X));
return rcpp_result_gen;
END_RCPP
}
// trace_stats_uncentered
arma::vec trace_stats_uncentered(arma::mat X);
RcppExport SEXP _ShrinkCovMat_trace_stats_uncentered(SEXP XSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< arma::mat >::type X(XSEXP);
rcpp_result_gen = Rcpp::wrap(trace_stats_uncentered(X));
return rcpp_result_gen;
END_RCPP
}
// trace_stats_centered
arma::vec trace_stats_centered(arma::mat X);
RcppExport SEXP _ShrinkCovMat_trace_stats_centered(SEXP XSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< arma::mat >::type X(XSEXP);
rcpp_result_gen = Rcpp::wrap(trace_stats_centered(X));
return rcpp_result_gen;
END_RCPP
}
static const R_CallMethodDef CallEntries[] = {
{"_ShrinkCovMat_centerdata", (DL_FUNC) &_ShrinkCovMat_centerdata, 1},
{"_ShrinkCovMat_trace_stats_uncentered", (DL_FUNC) &_ShrinkCovMat_trace_stats_uncentered, 1},
{"_ShrinkCovMat_trace_stats_centered", (DL_FUNC) &_ShrinkCovMat_trace_stats_centered, 1},
{NULL, NULL, 0}
};
RcppExport void R_init_ShrinkCovMat(DllInfo *dll) {
R_registerRoutines(dll, NULL, CallEntries, NULL, NULL);
R_useDynamicSymbols(dll, FALSE);
}
| [
"A.Touloumis@brighton.ac.uk"
] | A.Touloumis@brighton.ac.uk |
ba4844c4854efe929277c52769a9f9509e6d07fa | 974749492500560d2d29fb89b305a7c2966011a5 | /NFC_monitoring/NFCwidget.cpp | 1253dabf3b0e395618bea10bef367104d1fe8bfa | [] | no_license | holmes-asava/NFC | 78d226603ed900301c7df62706ffcdc89d191dc0 | 54f12107dbef29ec1f18932c8891e28367bfa3d4 | refs/heads/master | 2021-09-16T13:50:59.706405 | 2018-06-21T09:57:49 | 2018-06-21T09:57:49 | 135,673,516 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 438 | cpp | #include "nfcwidget.h"
#include <QItemSelection>
#include <QtWidgets>
NFCWidget::NFCWidget()
{
descriptionLabel = new QLabel(tr("There are currently no contacts in your address book. "
"\nClick Add to add new contacts."));
mainLayout = new QVBoxLayout;
mainLayout->addWidget(descriptionLabel);
mainLayout->addWidget(addButton, 0, Qt::AlignCenter);
setLayout(mainLayout);
}
| [
"homer.asava@gmail.com"
] | homer.asava@gmail.com |
88833cb468518864ef1a23a6ddf9e8899ad54f2e | 6250f3343eff1638912510b66ed936c59796635a | /src_vc141/base/win/scoped_winrt_initializer.cc | 64379193c5120c278387e00e3b2647407fc1041c | [
"Apache-2.0"
] | permissive | nneesshh/mytoolkit | b4b242307a6603bc5785bc130de8f4d3b5ea9265 | 336ae9c7077c8687a8cf8a2ce4aec804c28ab90c | refs/heads/master | 2020-04-05T15:18:07.985547 | 2018-12-17T11:36:07 | 2018-12-17T11:36:07 | 156,961,652 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,087 | cc | // Copyright 2017 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 "base/win/scoped_winrt_initializer.h"
#include "base/logging.h"
#include "base/win/com_init_util.h"
#include "base/win/core_winrt_util.h"
#include "base/win/windows_version.h"
namespace base {
namespace win {
ScopedWinrtInitializer::ScopedWinrtInitializer()
: hr_(base::win::RoInitialize(RO_INIT_MULTITHREADED)) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK_GE(GetVersion(), VERSION_WIN8);
#if DCHECK_IS_ON()
if (SUCCEEDED(hr_))
AssertComApartmentType(ComApartmentType::MTA);
else
DCHECK_NE(RPC_E_CHANGED_MODE, hr_) << "Invalid COM thread model change";
#endif
}
ScopedWinrtInitializer::~ScopedWinrtInitializer() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (SUCCEEDED(hr_))
base::win::RoUninitialize();
}
bool ScopedWinrtInitializer::Succeeded() const {
return SUCCEEDED(hr_);
}
} // namespace win
} // namespace base | [
"nneesshh@163.com"
] | nneesshh@163.com |
84facb2ed00f4e8bac805ea89774cbb1fdc5e45b | 8dc84558f0058d90dfc4955e905dab1b22d12c08 | /net/third_party/quiche/src/quic/core/quic_control_frame_manager.cc | 511ef2be82b1f86b584af5dc80899c0c0b76859d | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | meniossin/src | 42a95cc6c4a9c71d43d62bc4311224ca1fd61e03 | 44f73f7e76119e5ab415d4593ac66485e65d700a | refs/heads/master | 2022-12-16T20:17:03.747113 | 2020-09-03T10:43:12 | 2020-09-03T10:43:12 | 263,710,168 | 1 | 0 | BSD-3-Clause | 2020-05-13T18:20:09 | 2020-05-13T18:20:08 | null | UTF-8 | C++ | false | false | 11,066 | cc | // Copyright (c) 2017 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 "net/third_party/quiche/src/quic/core/quic_control_frame_manager.h"
#include <string>
#include "net/third_party/quiche/src/quic/core/quic_constants.h"
#include "net/third_party/quiche/src/quic/core/quic_session.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_bug_tracker.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_flag_utils.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_map_util.h"
namespace quic {
QuicControlFrameManager::QuicControlFrameManager(QuicSession* session)
: last_control_frame_id_(kInvalidControlFrameId),
least_unacked_(1),
least_unsent_(1),
session_(session) {}
QuicControlFrameManager::~QuicControlFrameManager() {
while (!control_frames_.empty()) {
DeleteFrame(&control_frames_.front());
control_frames_.pop_front();
}
}
void QuicControlFrameManager::WriteOrBufferQuicFrame(QuicFrame frame) {
const bool had_buffered_frames = HasBufferedFrames();
control_frames_.emplace_back(frame);
if (had_buffered_frames) {
return;
}
WriteBufferedFrames();
}
void QuicControlFrameManager::WriteOrBufferRstStream(
QuicStreamId id,
QuicRstStreamErrorCode error,
QuicStreamOffset bytes_written) {
QUIC_DVLOG(1) << "Writing RST_STREAM_FRAME";
WriteOrBufferQuicFrame((QuicFrame(new QuicRstStreamFrame(
++last_control_frame_id_, id, error, bytes_written))));
}
void QuicControlFrameManager::WriteOrBufferGoAway(
QuicErrorCode error,
QuicStreamId last_good_stream_id,
const std::string& reason) {
QUIC_DVLOG(1) << "Writing GOAWAY_FRAME";
WriteOrBufferQuicFrame(QuicFrame(new QuicGoAwayFrame(
++last_control_frame_id_, error, last_good_stream_id, reason)));
}
void QuicControlFrameManager::WriteOrBufferWindowUpdate(
QuicStreamId id,
QuicStreamOffset byte_offset) {
QUIC_DVLOG(1) << "Writing WINDOW_UPDATE_FRAME";
WriteOrBufferQuicFrame(QuicFrame(
new QuicWindowUpdateFrame(++last_control_frame_id_, id, byte_offset)));
}
void QuicControlFrameManager::WriteOrBufferBlocked(QuicStreamId id) {
QUIC_DVLOG(1) << "Writing BLOCKED_FRAME";
WriteOrBufferQuicFrame(
QuicFrame(new QuicBlockedFrame(++last_control_frame_id_, id)));
}
void QuicControlFrameManager::WriteOrBufferStreamsBlocked(QuicStreamCount count,
bool unidirectional) {
QUIC_DVLOG(1) << "Writing STREAMS_BLOCKED Frame";
QUIC_CODE_COUNT(quic_streams_blocked_transmits);
WriteOrBufferQuicFrame(QuicFrame(QuicStreamsBlockedFrame(
++last_control_frame_id_, count, unidirectional)));
}
void QuicControlFrameManager::WriteOrBufferMaxStreams(QuicStreamCount count,
bool unidirectional) {
QUIC_DVLOG(1) << "Writing MAX_STREAMS Frame";
QUIC_CODE_COUNT(quic_max_streams_transmits);
WriteOrBufferQuicFrame(QuicFrame(
QuicMaxStreamsFrame(++last_control_frame_id_, count, unidirectional)));
}
void QuicControlFrameManager::WriteOrBufferStopSending(uint16_t code,
QuicStreamId stream_id) {
QUIC_DVLOG(1) << "Writing STOP_SENDING_FRAME";
WriteOrBufferQuicFrame(QuicFrame(
new QuicStopSendingFrame(++last_control_frame_id_, stream_id, code)));
}
void QuicControlFrameManager::WritePing() {
QUIC_DVLOG(1) << "Writing PING_FRAME";
if (HasBufferedFrames()) {
// Do not send ping if there is buffered frames.
QUIC_LOG(WARNING)
<< "Try to send PING when there is buffered control frames.";
return;
}
control_frames_.emplace_back(
QuicFrame(QuicPingFrame(++last_control_frame_id_)));
WriteBufferedFrames();
}
void QuicControlFrameManager::OnControlFrameSent(const QuicFrame& frame) {
QuicControlFrameId id = GetControlFrameId(frame);
if (id == kInvalidControlFrameId) {
QUIC_BUG
<< "Send or retransmit a control frame with invalid control frame id";
return;
}
if (frame.type == WINDOW_UPDATE_FRAME) {
QuicStreamId stream_id = frame.window_update_frame->stream_id;
if (QuicContainsKey(window_update_frames_, stream_id) &&
id > window_update_frames_[stream_id]) {
// Consider the older window update of the same stream as acked.
OnControlFrameIdAcked(window_update_frames_[stream_id]);
}
window_update_frames_[stream_id] = id;
}
if (QuicContainsKey(pending_retransmissions_, id)) {
// This is retransmitted control frame.
pending_retransmissions_.erase(id);
return;
}
if (id > least_unsent_) {
QUIC_BUG << "Try to send control frames out of order, id: " << id
<< " least_unsent: " << least_unsent_;
session_->connection()->CloseConnection(
QUIC_INTERNAL_ERROR, "Try to send control frames out of order",
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
return;
}
++least_unsent_;
}
bool QuicControlFrameManager::OnControlFrameAcked(const QuicFrame& frame) {
QuicControlFrameId id = GetControlFrameId(frame);
if (!OnControlFrameIdAcked(id)) {
return false;
}
if (frame.type == WINDOW_UPDATE_FRAME) {
QuicStreamId stream_id = frame.window_update_frame->stream_id;
if (QuicContainsKey(window_update_frames_, stream_id) &&
window_update_frames_[stream_id] == id) {
window_update_frames_.erase(stream_id);
}
}
return true;
}
void QuicControlFrameManager::OnControlFrameLost(const QuicFrame& frame) {
QuicControlFrameId id = GetControlFrameId(frame);
if (id == kInvalidControlFrameId) {
// Frame does not have a valid control frame ID, ignore it.
return;
}
if (id >= least_unsent_) {
QUIC_BUG << "Try to mark unsent control frame as lost";
session_->connection()->CloseConnection(
QUIC_INTERNAL_ERROR, "Try to mark unsent control frame as lost",
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
return;
}
if (id < least_unacked_ ||
GetControlFrameId(control_frames_.at(id - least_unacked_)) ==
kInvalidControlFrameId) {
// This frame has already been acked.
return;
}
if (!QuicContainsKey(pending_retransmissions_, id)) {
pending_retransmissions_[id] = true;
}
}
bool QuicControlFrameManager::IsControlFrameOutstanding(
const QuicFrame& frame) const {
QuicControlFrameId id = GetControlFrameId(frame);
if (id == kInvalidControlFrameId) {
// Frame without a control frame ID should not be retransmitted.
return false;
}
// Consider this frame is outstanding if it does not get acked.
return id < least_unacked_ + control_frames_.size() && id >= least_unacked_ &&
GetControlFrameId(control_frames_.at(id - least_unacked_)) !=
kInvalidControlFrameId;
}
bool QuicControlFrameManager::HasPendingRetransmission() const {
return !pending_retransmissions_.empty();
}
bool QuicControlFrameManager::WillingToWrite() const {
return HasPendingRetransmission() || HasBufferedFrames();
}
QuicFrame QuicControlFrameManager::NextPendingRetransmission() const {
QUIC_BUG_IF(pending_retransmissions_.empty())
<< "Unexpected call to NextPendingRetransmission() with empty pending "
<< "retransmission list.";
QuicControlFrameId id = pending_retransmissions_.begin()->first;
return control_frames_.at(id - least_unacked_);
}
void QuicControlFrameManager::OnCanWrite() {
if (HasPendingRetransmission()) {
// Exit early to allow streams to write pending retransmissions if any.
WritePendingRetransmission();
return;
}
WriteBufferedFrames();
}
bool QuicControlFrameManager::RetransmitControlFrame(const QuicFrame& frame) {
QuicControlFrameId id = GetControlFrameId(frame);
if (id == kInvalidControlFrameId) {
// Frame does not have a valid control frame ID, ignore it. Returns true
// to allow writing following frames.
return true;
}
if (id >= least_unsent_) {
QUIC_BUG << "Try to retransmit unsent control frame";
session_->connection()->CloseConnection(
QUIC_INTERNAL_ERROR, "Try to retransmit unsent control frame",
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
return false;
}
if (id < least_unacked_ ||
GetControlFrameId(control_frames_.at(id - least_unacked_)) ==
kInvalidControlFrameId) {
// This frame has already been acked.
return true;
}
QuicFrame copy = CopyRetransmittableControlFrame(frame);
QUIC_DVLOG(1) << "control frame manager is forced to retransmit frame: "
<< frame;
if (session_->WriteControlFrame(copy)) {
return true;
}
DeleteFrame(©);
return false;
}
void QuicControlFrameManager::WriteBufferedFrames() {
while (HasBufferedFrames()) {
if (session_->session_decides_what_to_write()) {
session_->SetTransmissionType(NOT_RETRANSMISSION);
}
QuicFrame frame_to_send =
control_frames_.at(least_unsent_ - least_unacked_);
QuicFrame copy = CopyRetransmittableControlFrame(frame_to_send);
if (!session_->WriteControlFrame(copy)) {
// Connection is write blocked.
DeleteFrame(©);
break;
}
OnControlFrameSent(frame_to_send);
}
}
void QuicControlFrameManager::WritePendingRetransmission() {
while (HasPendingRetransmission()) {
QuicFrame pending = NextPendingRetransmission();
QuicFrame copy = CopyRetransmittableControlFrame(pending);
if (!session_->WriteControlFrame(copy)) {
// Connection is write blocked.
DeleteFrame(©);
break;
}
OnControlFrameSent(pending);
}
}
bool QuicControlFrameManager::OnControlFrameIdAcked(QuicControlFrameId id) {
if (id == kInvalidControlFrameId) {
// Frame does not have a valid control frame ID, ignore it.
return false;
}
if (id >= least_unsent_) {
QUIC_BUG << "Try to ack unsent control frame";
session_->connection()->CloseConnection(
QUIC_INTERNAL_ERROR, "Try to ack unsent control frame",
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
return false;
}
if (id < least_unacked_ ||
GetControlFrameId(control_frames_.at(id - least_unacked_)) ==
kInvalidControlFrameId) {
// This frame has already been acked.
return false;
}
// Set control frame ID of acked frames to 0.
SetControlFrameId(kInvalidControlFrameId,
&control_frames_.at(id - least_unacked_));
// Remove acked control frames from pending retransmissions.
pending_retransmissions_.erase(id);
// Clean up control frames queue and increment least_unacked_.
while (!control_frames_.empty() &&
GetControlFrameId(control_frames_.front()) == kInvalidControlFrameId) {
DeleteFrame(&control_frames_.front());
control_frames_.pop_front();
++least_unacked_;
}
return true;
}
bool QuicControlFrameManager::HasBufferedFrames() const {
return least_unsent_ < least_unacked_ + control_frames_.size();
}
} // namespace quic
| [
"arnaud@geometry.ee"
] | arnaud@geometry.ee |
59f7a3977dce4579d09ff7ea08fb8673e58c5fcd | a474bca61f76af8ea7e089f2f5307f12bc6c6756 | /Atividade04/01.cpp | b952282d703d072d9c75420ba96e286d05aefd7a | [] | no_license | davigomesflorencio/programming_challenges | 82fda9748765d24ade535217a6e6ea657f5bbdc1 | 5f75a2ceabf5c03097b6381fd501fa7736854268 | refs/heads/main | 2023-07-23T10:16:41.749537 | 2021-09-02T00:47:24 | 2021-09-02T00:47:24 | 367,394,171 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,244 | cpp | #include <bits/stdc++.h>
#include <iostream>
#include <stack>
using namespace std;
/**
*
* 1405. Longest Happy String
*
**/
typedef pair<int, int> pi;
class Solution {
public:
string longestDiverseString(int a, int b, int c) {
string s = "";
int last = -1, letter_index, tam;
int count[] = {a, b, c};
while (true) {
letter_index = -1;
last = -1;
tam = s.size();
if (tam > 1 && s.at(tam - 2) == s.at(tam - 1)) {
last = s.at(tam - 1) - 'a';
}
if (last != 0 and count[0] > 0) {
letter_index = 0;
// cout << "recebeu 0 ";
}
if (last != 1 and count[1] > 0 and
(letter_index == -1 || count[1] > count[0])) {
letter_index = 1;
// cout << " recebeu 1 ";
}
if (last != 2 and count[2] > 0 and
(letter_index == -1 || count[2] > max(count[0], count[1]))) {
letter_index = 2;
// cout << " recebeu 2 ";
}
// cout << "letter_index " << letter_index << endl;
if (letter_index == 0) {
s += "a";
count[0] -= 1;
// cout << "a inserido -> " << s << endl;
} else if (letter_index == 1) {
s += "b";
count[1] -= 1;
// cout << "b inserido -> " << s << endl;
} else if (letter_index == 2) {
s += "c";
count[2] -= 1;
// cout << "c inserido -> " << s << endl;
}
if ((count[0] == 0 and count[1] == 0) ||
(count[0] == 0 and count[2] == 0) ||
(count[1] == 0 and count[2] == 0)) {
char last_char = s.at(s.size() - 1);
if (count[0] >= 2 and last != 'a') {
s += "aa";
} else if (count[0] == 1 and last != 'a') {
s += "a";
}
if (count[1] >= 2 and last != 'b') {
s += "bb";
} else if (count[1] == 1 and last != 'b') {
s += "b";
}
if (count[2] >= 2 and last != 'c') {
s += "cc";
} else if (count[2] == 1 and last != 'c') {
s += "c";
}
break;
}
}
// cout << s.at(s.size() - 1) << endl;
return s;
}
};
int main() {
Solution so;
string a = so.longestDiverseString(2, 2, 1);
cout << a << endl;
return 0;
} | [
"davigomesflorencio@gmail.com"
] | davigomesflorencio@gmail.com |
c5a4f4843d013e68ff4fd7598752277b0e4aecca | 0e1b1f5e2893070ebdcb5eb15b07b89b0f31f471 | /submodules/seqan/tests/translation/test_translation.h | f1d3dd3fa44edc5fb5bf2778fec12deec3d620ab | [
"MIT",
"BSD-3-Clause"
] | permissive | sheffield-bioinformatics-core/STRique | 1a4a3e59e0ac66174ed5c9a4498d6d8bed40b54d | fd2df916847727b3484b2bbad839814043d7dbea | refs/heads/master | 2022-12-27T22:28:31.893074 | 2020-09-29T14:31:45 | 2020-09-29T14:31:45 | 296,618,760 | 0 | 0 | MIT | 2020-09-18T12:45:30 | 2020-09-18T12:45:29 | null | UTF-8 | C++ | false | false | 21,968 | h | // ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2018, Knut Reinert, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Knut Reinert or the FU Berlin nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN 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.
//
// ==========================================================================
// Author: Hannes Hauswedell <hauswedell@mi.fu-berlin.de>
// ==========================================================================
// Tests for basic/translation.h
// ==========================================================================
#ifndef SEQAN_TESTS_BASIC_TEST_TRANSLATION_H_
#define SEQAN_TESTS_BASIC_TEST_TRANSLATION_H_
#include <seqan/basic.h>
#include <seqan/sequence.h>
#include <seqan/stream.h>
// #include <seqan/parallel.h>
#include <seqan/translation.h>
using namespace seqan;
template <typename TString>
inline void
test_translation_onestring_singleframe_impl(TString const & str)
{
{
String<AminoAcid> outStr;
translate(outStr, str);
SEQAN_ASSERT_EQ(outStr,
"KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSS*CWCLFLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, GeneticCode<VERT_MITOCHONDRIAL>());
SEQAN_ASSERT_EQ(outStr,
"KNKNTTTT*S*SMIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, GeneticCode<YEAST_MITOCHONDRIAL>());
SEQAN_ASSERT_EQ(outStr,
"KNKNTTTTRSRSMIMIQHQHPPPPRRRRTTTTEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, GeneticCode<INVERT_MITOCHONDRIAL>());
SEQAN_ASSERT_EQ(outStr,
"KNKNTTTTSSSSMIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, GeneticCode<CILIATE>());
SEQAN_ASSERT_EQ(outStr,
"KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVVQYQYSSSS*CWCLFLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, GeneticCode<FLATWORM_MITOCHONDRIAL>());
SEQAN_ASSERT_EQ(outStr,
"NNKNTTTTSSSSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, GeneticCode<EUPLOTID>());
SEQAN_ASSERT_EQ(outStr,
"KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSCCWCLFLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, GeneticCode<PROKARYOTE>());
SEQAN_ASSERT_EQ(outStr,
"KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSS*CWCLFLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, GeneticCode<ALT_YEAST>());
SEQAN_ASSERT_EQ(outStr,
"KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLSLEDEDAAAAGGGGVVVV*Y*YSSSS*CWCLFLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, GeneticCode<ASCIDIAN_MITOCHONDRIAL>());
SEQAN_ASSERT_EQ(outStr,
"KNKNTTTTGSGSMIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, GeneticCode<BLEPHARISMA>());
SEQAN_ASSERT_EQ(outStr,
"KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*YQYSSSS*CWCLFLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, GeneticCode<CHLOROPHYCEAN_MITOCHONDRIAL>());
SEQAN_ASSERT_EQ(outStr,
"KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*YLYSSSS*CWCLFLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, GeneticCode<TREMATODE_MITOCHONDRIAL>());
SEQAN_ASSERT_EQ(outStr,
"NNKNTTTTSSSSMIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, GeneticCode<SCENEDESMUS_MITOCHONDRIAL>());
SEQAN_ASSERT_EQ(outStr,
"KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*YLY*SSS*CWCLFLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, GeneticCode<THRAUSTOCHYTRIUM_MITOCHONDRIAL>());
SEQAN_ASSERT_EQ(outStr,
"KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSS*CWC*FLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, GeneticCode<PTEROBRANCHIA_MITOCHONDRIAL>());
SEQAN_ASSERT_EQ(outStr,
"KNKNTTTTSSKSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, GeneticCode<GRACILIBACTERIA>());
SEQAN_ASSERT_EQ(outStr,
"KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSGCWCLFLF");
}
}
template <typename TString>
inline void
test_translation_onestring_singleframe_impl_runtime(TString const & str)
{
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, CANONICAL);
SEQAN_ASSERT_EQ(outStr,
"KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSS*CWCLFLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, VERT_MITOCHONDRIAL);
SEQAN_ASSERT_EQ(outStr,
"KNKNTTTT*S*SMIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, YEAST_MITOCHONDRIAL);
SEQAN_ASSERT_EQ(outStr,
"KNKNTTTTRSRSMIMIQHQHPPPPRRRRTTTTEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, INVERT_MITOCHONDRIAL);
SEQAN_ASSERT_EQ(outStr,
"KNKNTTTTSSSSMIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, CILIATE);
SEQAN_ASSERT_EQ(outStr,
"KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVVQYQYSSSS*CWCLFLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, FLATWORM_MITOCHONDRIAL);
SEQAN_ASSERT_EQ(outStr,
"NNKNTTTTSSSSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, EUPLOTID);
SEQAN_ASSERT_EQ(outStr,
"KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSCCWCLFLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, PROKARYOTE);
SEQAN_ASSERT_EQ(outStr,
"KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSS*CWCLFLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, ALT_YEAST);
SEQAN_ASSERT_EQ(outStr,
"KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLSLEDEDAAAAGGGGVVVV*Y*YSSSS*CWCLFLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, ASCIDIAN_MITOCHONDRIAL);
SEQAN_ASSERT_EQ(outStr,
"KNKNTTTTGSGSMIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, BLEPHARISMA);
SEQAN_ASSERT_EQ(outStr,
"KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*YQYSSSS*CWCLFLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, CHLOROPHYCEAN_MITOCHONDRIAL);
SEQAN_ASSERT_EQ(outStr,
"KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*YLYSSSS*CWCLFLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, TREMATODE_MITOCHONDRIAL);
SEQAN_ASSERT_EQ(outStr,
"NNKNTTTTSSSSMIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, SCENEDESMUS_MITOCHONDRIAL);
SEQAN_ASSERT_EQ(outStr,
"KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*YLY*SSS*CWCLFLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, THRAUSTOCHYTRIUM_MITOCHONDRIAL);
SEQAN_ASSERT_EQ(outStr,
"KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSS*CWC*FLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, PTEROBRANCHIA_MITOCHONDRIAL);
SEQAN_ASSERT_EQ(outStr,
"KNKNTTTTSSKSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF");
}
{
String<AminoAcid> outStr;
translate(outStr, str, SINGLE_FRAME, GRACILIBACTERIA);
SEQAN_ASSERT_EQ(outStr,
"KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSGCWCLFLF");
}
}
SEQAN_DEFINE_TEST(test_translation_onestring_singleframe_allcodes)
{
const char * dna = "aaaaacaagaatacaaccacgactagaagcaggagtataatcatgattcaacacc"
"agcatccacccccgcctcgacgccggcgtctactcctgcttgaagacgaggatgcagccgcggctggaggcggg"
"ggtgtagtcgtggtttaatactagtattcatcctcgtcttgatgctggtgtttattcttgttt";
const char * rna = "aaaaacaagaauacaaccacgacuagaagcaggaguauaaucaugauucaacacc"
"agcauccacccccgccucgacgccggcgucuacuccugcuugaagacgaggaugcagccgcggcuggaggcggg"
"gguguagucgugguuuaauacuaguauucauccucgucuugaugcugguguuuauucuuguuu";
// dna
{
DnaString str(dna);
test_translation_onestring_singleframe_impl(str);
}
// dna5
{
Dna5String str(dna);
test_translation_onestring_singleframe_impl(str);
}
// rna
{
RnaString str(rna);
test_translation_onestring_singleframe_impl(str);
}
// rna5
{
Rna5String str(rna);
test_translation_onestring_singleframe_impl(str);
}
// CharString
{
CharString str(dna);
test_translation_onestring_singleframe_impl(str);
}
// 0-terminated
{
test_translation_onestring_singleframe_impl(dna);
}
// std::string
{
std::string str(dna);
test_translation_onestring_singleframe_impl(str);
}
}
SEQAN_DEFINE_TEST(test_translation_onestring_singleframe_allcodes_runtime)
{
const char * dna = "aaaaacaagaatacaaccacgactagaagcaggagtataatcatgattcaacacc"
"agcatccacccccgcctcgacgccggcgtctactcctgcttgaagacgaggatgcagccgcggctggaggcggg"
"ggtgtagtcgtggtttaatactagtattcatcctcgtcttgatgctggtgtttattcttgttt";
const char * rna = "aaaaacaagaauacaaccacgacuagaagcaggaguauaaucaugauucaacacc"
"agcauccacccccgccucgacgccggcgucuacuccugcuugaagacgaggaugcagccgcggcuggaggcggg"
"gguguagucgugguuuaauacuaguauucauccucgucuugaugcugguguuuauucuuguuu";
// dna
{
DnaString str(dna);
test_translation_onestring_singleframe_impl_runtime(str);
}
// dna5
{
Dna5String str(dna);
test_translation_onestring_singleframe_impl_runtime(str);
}
// rna
{
RnaString str(rna);
test_translation_onestring_singleframe_impl_runtime(str);
}
// rna5
{
Rna5String str(rna);
test_translation_onestring_singleframe_impl_runtime(str);
}
// CharString
{
CharString str(dna);
test_translation_onestring_singleframe_impl_runtime(str);
}
// 0-terminated
{
test_translation_onestring_singleframe_impl_runtime(dna);
}
// std::string
{
std::string str(dna);
test_translation_onestring_singleframe_impl_runtime(str);
}
}
template <typename TTargetSet, typename TParallelism>
inline void
test_translation_onestring_multiframe_impl()
{
Dna5String str("acgtnncgtaaaccgttaaaccgnntaagtnnaccccggtaccgataan");
// __|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|
// __|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|
// __|__|__|__|__|__|__|__|__|__|__|__|__|__|__|
StringSet<String<AminoAcid> > trans;
appendValue(trans, "TXRKPLNXXSXPRYR*");
appendValue(trans, "RXVNR*TX*XXPGTDX");
appendValue(trans, "XX*TVKPXKXTPVPI" );
appendValue(trans, "XIGTGXXLXGLTVYXT");
appendValue(trans, "LSVPGXTXXV*RFTXR");
appendValue(trans, "YRYRGXLXRFNGLXX" );
TTargetSet res;
{
translate(res, str, SINGLE_FRAME, TParallelism());
SEQAN_ASSERT_EQ(length(res), 1u);
SEQAN_ASSERT_EQ(res[0], trans[0]);
}
{
translate(res, str, WITH_REVERSE_COMPLEMENT, TParallelism());
SEQAN_ASSERT_EQ(length(res), 2u);
SEQAN_ASSERT_EQ(res[0], trans[0]);
SEQAN_ASSERT_EQ(res[1], trans[3]);
}
{
translate(res, str, WITH_FRAME_SHIFTS, TParallelism());
SEQAN_ASSERT_EQ(length(res), 3u);
SEQAN_ASSERT_EQ(res[0], trans[0]);
SEQAN_ASSERT_EQ(res[1], trans[1]);
SEQAN_ASSERT_EQ(res[2], trans[2]);
}
{
translate(res, str, SIX_FRAME, TParallelism());
SEQAN_ASSERT_EQ(length(res), 6u);
SEQAN_ASSERT_EQ(res[0], trans[0]);
SEQAN_ASSERT_EQ(res[1], trans[1]);
SEQAN_ASSERT_EQ(res[2], trans[2]);
SEQAN_ASSERT_EQ(res[3], trans[3]);
SEQAN_ASSERT_EQ(res[4], trans[4]);
SEQAN_ASSERT_EQ(res[5], trans[5]);
}
}
SEQAN_DEFINE_TEST(test_translation_onestring_multiframe_serial)
{
typedef StringSet<String<AminoAcid> > TRegSet;
test_translation_onestring_multiframe_impl<TRegSet, Serial>();
}
SEQAN_DEFINE_TEST(test_translation_onestring_multiframe_concatdirect_serial)
{
typedef StringSet<String<AminoAcid>, Owner<ConcatDirect<> > > TConcatSet;
test_translation_onestring_multiframe_impl<TConcatSet, Serial>();
}
SEQAN_DEFINE_TEST(test_translation_onestring_multiframe_parallel)
{
typedef StringSet<String<AminoAcid> > TRegSet;
test_translation_onestring_multiframe_impl<TRegSet, Parallel>();
}
SEQAN_DEFINE_TEST(test_translation_onestring_multiframe_concatdirect_parallel)
{
#ifndef __alpha__ // NOTE(h-2): fails on alpha for unknown reasons
typedef StringSet<String<AminoAcid>, Owner<ConcatDirect<> > > TConcatSet;
test_translation_onestring_multiframe_impl<TConcatSet, Parallel>();
#endif
}
template <typename TSourceSet, typename TResultSet, typename TParallelism>
inline void
test_translation_stringset_multiframe_impl(TResultSet const & comp,
TSourceSet const & source,
TParallelism const & /**/)
{
TResultSet res;
unsigned l = length(source);
{
translate(res, source, SINGLE_FRAME, TParallelism());
unsigned r = length(res) / l;
SEQAN_ASSERT_EQ(r, 1u);
for (unsigned i = 0; i < l; ++i)
{
SEQAN_ASSERT_EQ(res[0+i*r], comp[0+i*6]);
}
}
{
translate(res, source, WITH_REVERSE_COMPLEMENT,
TParallelism());
unsigned r = length(res) / l;
SEQAN_ASSERT_EQ(r, 2u);
for (unsigned i = 0; i < l; ++i)
{
SEQAN_ASSERT_EQ(res[0+i*r], comp[0+i*6]);
SEQAN_ASSERT_EQ(res[1+i*r], comp[3+i*6]);
}
}
{
translate(res, source, WITH_FRAME_SHIFTS,
TParallelism());
unsigned r = length(res) / l;
SEQAN_ASSERT_EQ(r, 3u);
for (unsigned i = 0; i < l; ++i)
{
SEQAN_ASSERT_EQ(length(res), 3*length(source));
SEQAN_ASSERT_EQ(res[0+i*r], comp[0+i*6]);
SEQAN_ASSERT_EQ(res[1+i*r], comp[1+i*6]);
SEQAN_ASSERT_EQ(res[2+i*r], comp[2+i*6]);
}
}
{
translate(res, source, SIX_FRAME, TParallelism());
unsigned r = length(res) / l;
SEQAN_ASSERT_EQ(r, 6u);
for (unsigned i = 0; i < l; ++i)
{
SEQAN_ASSERT_EQ(res[0+i*r], comp[0+i*6]);
SEQAN_ASSERT_EQ(res[1+i*r], comp[1+i*6]);
SEQAN_ASSERT_EQ(res[2+i*r], comp[2+i*6]);
SEQAN_ASSERT_EQ(res[3+i*r], comp[3+i*6]);
SEQAN_ASSERT_EQ(res[4+i*r], comp[4+i*6]);
SEQAN_ASSERT_EQ(res[5+i*r], comp[5+i*6]);
}
}
}
template <typename TSetSpec, typename TParallelism>
inline void
test_translation_stringset_multiframe_impl0()
{
StringSet<String<AminoAcid>, TSetSpec> comp;
appendValue(comp, "TXRKPLNXXSXPRYR*");
appendValue(comp, "RXVNR*TX*XXPGTDX");
appendValue(comp, "XX*TVKPXKXTPVPI" );
appendValue(comp, "XIGTGXXLXGLTVYXT");
appendValue(comp, "LSVPGXTXXV*RFTXR");
appendValue(comp, "YRYRGXLXRFNGLXX" );
appendValue(comp, "GYVXYRLVLGASRX");
appendValue(comp, "VTYXTG*YLGRVXX" );
appendValue(comp, "LRXXPVSTWGE*XV" );
appendValue(comp, "NXLLAPSTNRXXT*" );
appendValue(comp, "XXYSPQVLTGXIRN" );
appendValue(comp, "XSTRPKY*PVXYVT" );
//DNA
{
StringSet<Dna5String, TSetSpec> source;
Dna5String str("acgtnncgtaaaccgttaaaccgnntaagtnnaccccggtaccgataan");
// __|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|
// __|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|
// __|__|__|__|__|__|__|__|__|__|__|__|__|__|__|
appendValue(source, str);
str = "ggttacgtatnntaccggttagtacttggggcgagtaganngtt";
// __|__|__|__|__|__|__|__|__|__|__|__|__|__|__
// __|__|__|__|__|__|__|__|__|__|__|__|__|__|
// __|__|__|__|__|__|__|__|__|__|__|__|__|__|
appendValue(source, str);
test_translation_stringset_multiframe_impl(comp, source, TParallelism());
}
//RNA
{
StringSet<Rna5String, TSetSpec> source;
Rna5String str("acgunncguaaaccguuaaaccgnnuaagunnaccccgguaccgauaan");
// __|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|
// __|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|
// __|__|__|__|__|__|__|__|__|__|__|__|__|__|__|
appendValue(source, str);
str = "gguuacguaunnuaccgguuaguacuuggggcgaguagannguu";
// __|__|__|__|__|__|__|__|__|__|__|__|__|__|__
// __|__|__|__|__|__|__|__|__|__|__|__|__|__|
// __|__|__|__|__|__|__|__|__|__|__|__|__|__|
appendValue(source, str);
test_translation_stringset_multiframe_impl(comp, source, TParallelism());
}
// handle empty input sequences correctly, see #2228
{
// one empty input results in 6 empty output frames for consistency
insertValue(comp, 0, "");
insertValue(comp, 1, "");
insertValue(comp, 2, "");
insertValue(comp, 3, "");
insertValue(comp, 4, "");
insertValue(comp, 5, "");
// too short for anything also results in six empty
insertValue(comp, 6, "");
insertValue(comp, 7, "");
insertValue(comp, 8, "");
insertValue(comp, 9, "");
insertValue(comp, 10, "");
insertValue(comp, 11, "");
// too short for shift results in some empty frames
insertValue(comp, 12, "T");
insertValue(comp, 13, "");
insertValue(comp, 14, "");
insertValue(comp, 15, "R");
insertValue(comp, 16, "");
insertValue(comp, 17, "");
StringSet<Dna5String, TSetSpec> source;
appendValue(source, ""); // empty
appendValue(source, "a"); // empty
appendValue(source, "acg"); // some empty frames
appendValue(source, "acgtnncgtaaaccgttaaaccgnntaagtnnaccccggtaccgataan");
appendValue(source, "ggttacgtatnntaccggttagtacttggggcgagtaganngtt");
test_translation_stringset_multiframe_impl(comp, source, TParallelism());
}
}
SEQAN_DEFINE_TEST(test_translation_stringset_multiframe_serial)
{
test_translation_stringset_multiframe_impl0<Owner<>, Serial >();
}
SEQAN_DEFINE_TEST(test_translation_stringset_multiframe_concatdirect_serial)
{
test_translation_stringset_multiframe_impl0<Owner<ConcatDirect<> >,Serial>();
}
SEQAN_DEFINE_TEST(test_translation_stringset_multiframe_parallel)
{
test_translation_stringset_multiframe_impl0<Owner<>, Parallel>();
}
SEQAN_DEFINE_TEST(test_translation_stringset_multiframe_concatdirect_parallel)
{
#ifndef __alpha__ // NOTE(h-2): fails on alpha for unknown reasons
test_translation_stringset_multiframe_impl0<Owner<ConcatDirect<> >,
Parallel>();
#endif
}
#endif // SEQAN_TESTS_BASIC_TEST_TRANSLATION_H_
| [
"matthew.parker@sheffield.ac.uk"
] | matthew.parker@sheffield.ac.uk |
78d9ee63a31c7fedcd509374042c90702e1f86f9 | 95ae7dfa9ee578f1b24a65986ff78bf77ceca0c5 | /Engine/source/math/mRotation.h | 0ec23f2e169b431569ae45ae9c74080f073b0649 | [
"MIT",
"LicenseRef-scancode-unknown"
] | permissive | TorqueGameEngines/Torque3D | 4e1f6a05cc0928980c8c7c20bcdd680eaa6dcee8 | a445a4364664e299196bd551d213844486080145 | refs/heads/development | 2023-09-03T12:40:40.658487 | 2023-08-24T14:44:43 | 2023-08-24T14:44:43 | 267,440,108 | 1,192 | 178 | MIT | 2023-09-13T14:28:16 | 2020-05-27T22:35:54 | C++ | UTF-8 | C++ | false | false | 11,908 | h | //-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef MROTATION_H
#define MROTATION_H
#ifndef _MMATHFN_H_
#include "math/mMathFn.h"
#endif
#ifndef _MPOINT3_H_
#include "math/mPoint3.h"
#endif
#ifndef _MQUAT_H_
#include "math/mQuat.h"
#endif
#ifndef _MMATRIX_H_
#include "math/mMatrix.h"
#endif
#ifndef _MANGAXIS_H_
#include "math/mAngAxis.h"
#endif
//------------------------------------------------------------------------------
/// Rotation Interop Utility class
///
/// Useful for easily handling rotations/orientations in transforms while manipulating or converting between formats.
class RotationF
{
//-------------------------------------- Public data
public:
F32 x; ///< X co-ordinate.
F32 y; ///< Y co-ordinate.
F32 z; ///< Z co-ordinate.
F32 w; ///< W co-ordinate.
enum RotationTypes
{
Euler = 0,
AxisAngle
};
RotationTypes mRotationType;
enum UnitFormat
{
Radians = 0,
Degrees
};
RotationF(); ///< Create an uninitialized point.
RotationF(const RotationF&); ///< Copy constructor.
//
//Eulers
RotationF(EulerF euler, UnitFormat format = Radians);
RotationF(F32 _x, F32 _y, F32 _z, UnitFormat format = Radians);
void set(EulerF euler, UnitFormat format = Radians);
void set(F32 _x, F32 _y, F32 _z, UnitFormat format = Radians);
//As with AxisAngles, we make the assumption here that if not told otherwise, inbound rotations are in Degrees.
RotationF operator=(const EulerF&);
RotationF operator-(const EulerF&) const;
RotationF operator+(const EulerF&) const;
RotationF& operator-=(const EulerF&);
RotationF& operator+=(const EulerF&);
S32 operator==(const EulerF&) const;
S32 operator!=(const EulerF&) const;
//
//AxisAngle
RotationF(AngAxisF aa, UnitFormat format = Radians);
void set(AngAxisF aa, UnitFormat format = Radians);
//As with Eulers, we make the assumption here that if not told otherwise, inbound rotations are in Degrees.
RotationF operator=(const AngAxisF&);
RotationF operator-(const AngAxisF&) const;
RotationF operator+(const AngAxisF&) const;
RotationF& operator-=(const AngAxisF&);
RotationF& operator+=(const AngAxisF&);
S32 operator==(const AngAxisF&) const;
S32 operator!=(const AngAxisF&) const;
//
//Quat
RotationF(QuatF quat);
void set(QuatF _quat);
RotationF operator=(const QuatF&);
RotationF operator-(const QuatF&) const;
RotationF operator+(const QuatF&) const;
RotationF& operator-=(const QuatF&);
RotationF& operator+=(const QuatF&);
S32 operator==(const QuatF&) const;
S32 operator!=(const QuatF&) const;
//
//Matrix
RotationF(MatrixF mat);
void set(MatrixF _mat);
RotationF operator=(const MatrixF&);
RotationF operator-(const MatrixF&) const;
RotationF operator+(const MatrixF&) const;
RotationF& operator-=(const MatrixF&);
RotationF& operator+=(const MatrixF&);
S32 operator==(const MatrixF&) const;
S32 operator!=(const MatrixF&) const;
//
void interpolate(const RotationF& _pt1, const RotationF& _pt2, F32 _factor);
void lookAt(const Point3F& _origin, const Point3F& _target, const Point3F& _up = Point3F(0, 0, 1));
VectorF getDirection();
F32 len() const;
void normalize();
//Non-converting operators
S32 operator ==(const RotationF &) const;
S32 operator !=(const RotationF &) const;
RotationF operator+(const RotationF&) const;
RotationF& operator+=(const RotationF&);
RotationF operator-(const RotationF&) const;
RotationF& operator-=(const RotationF&);
RotationF& operator=(const RotationF&);
//Conversion stuffs
EulerF asEulerF(UnitFormat format = Radians) const;
AngAxisF asAxisAngle(UnitFormat format = Radians) const;
MatrixF asMatrixF() const;
QuatF asQuatF() const;
};
inline RotationF::RotationF()
{
x = 0;
y = 0;
z = 0;
w = 0;
mRotationType = AxisAngle;
}
inline RotationF::RotationF(const RotationF& _copy)
: x(_copy.x), y(_copy.y), z(_copy.z), w(_copy.w), mRotationType(_copy.mRotationType)
{}
inline int RotationF::operator ==(const RotationF& _rotation) const
{
return (x == _rotation.x && y == _rotation.y && z == _rotation.z && w == _rotation.w);
}
inline int RotationF::operator !=(const RotationF& _rotation) const
{
return (x != _rotation.x || y != _rotation.y || z != _rotation.z || w != _rotation.w);
}
//When it comes to actually trying to add rotations, we, in fact, actually multiply their data together.
//Since we're specifically operating on usability for RotationF, we'll operate on this, rather than the literal addition of the values
inline RotationF& RotationF::operator +=(const RotationF& _rotation)
{
if (mRotationType == Euler)
{
x += _rotation.x;
y += _rotation.y;
z += _rotation.z;
}
else
{
MatrixF tempMat = asMatrixF();
MatrixF tempMatAdd = _rotation.asMatrixF();
tempMat.mul(tempMatAdd);
this->set(tempMat);
}
return *this;
}
inline RotationF RotationF::operator +(const RotationF& _rotation) const
{
RotationF result = *this;
if (mRotationType == Euler)
{
result.x += _rotation.x;
result.y += _rotation.y;
result.z += _rotation.z;
}
else
{
MatrixF tempMat = asMatrixF();
MatrixF tempMatAdd = _rotation.asMatrixF();
tempMat.mul(tempMatAdd);
result.set(tempMat);
}
return result;
}
//Much like addition, when subtracting, we're not literally subtracting the values, but infact multiplying the inverse.
//This subtracts the rotation angles to get the difference
inline RotationF& RotationF::operator -=(const RotationF& _rotation)
{
if (mRotationType == Euler)
{
x -= _rotation.x;
y -= _rotation.y;
z -= _rotation.z;
}
else
{
MatrixF tempMat = asMatrixF();
MatrixF tempMatAdd = _rotation.asMatrixF();
tempMatAdd.inverse();
tempMat.mul(tempMatAdd);
this->set(tempMat);
}
return *this;
}
inline RotationF RotationF::operator -(const RotationF& _rotation) const
{
RotationF result = *this;
if (mRotationType == Euler)
{
result.x += _rotation.x;
result.y += _rotation.y;
result.z += _rotation.z;
}
else
{
MatrixF tempMat = asMatrixF();
MatrixF tempMatAdd = _rotation.asMatrixF();
tempMatAdd.inverse();
tempMat.mul(tempMatAdd);
result.set(tempMat);
}
return result;
}
inline RotationF& RotationF::operator =(const RotationF& _rotation)
{
x = _rotation.x;
y = _rotation.y;
z = _rotation.z;
w = _rotation.w;
mRotationType = _rotation.mRotationType;
return *this;
}
//====================================================================
// Euler operators
//====================================================================
inline RotationF RotationF::operator=(const EulerF& _euler)
{
return RotationF(_euler, Radians);
}
inline RotationF RotationF::operator-(const EulerF& _euler) const
{
RotationF temp = *this;
temp -= RotationF(_euler, Radians);
return temp;
}
inline RotationF RotationF::operator+(const EulerF& _euler) const
{
RotationF temp = *this;
temp += RotationF(_euler, Radians);
return temp;
}
inline RotationF& RotationF::operator-=(const EulerF& _euler)
{
*this -= RotationF(_euler, Radians);
return *this;
}
inline RotationF& RotationF::operator+=(const EulerF& _euler)
{
*this += RotationF(_euler, Radians);
return *this;
}
inline S32 RotationF::operator==(const EulerF& _euler) const
{
return *this == RotationF(_euler);
}
inline S32 RotationF::operator!=(const EulerF& _euler) const
{
return *this != RotationF(_euler);
}
//====================================================================
// AxisAngle operators
//====================================================================
inline RotationF RotationF::operator=(const AngAxisF& _aa)
{
return RotationF(_aa, Radians);
}
inline RotationF RotationF::operator-(const AngAxisF& _aa) const
{
RotationF temp = *this;
temp -= RotationF(_aa, Radians);
return temp;
}
inline RotationF RotationF::operator+(const AngAxisF& _aa) const
{
RotationF temp = *this;
temp += RotationF(_aa, Radians);
return temp;
}
inline RotationF& RotationF::operator-=(const AngAxisF& _aa)
{
*this -= RotationF(_aa, Radians);
return *this;
}
inline RotationF& RotationF::operator+=(const AngAxisF& _aa)
{
*this += RotationF(_aa, Radians);
return *this;
}
inline S32 RotationF::operator==(const AngAxisF& _aa) const
{
return *this == RotationF(_aa);
}
inline S32 RotationF::operator!=(const AngAxisF& _aa) const
{
return *this != RotationF(_aa);
}
//====================================================================
// QuatF operators
//====================================================================
inline RotationF RotationF::operator=(const QuatF& _quat)
{
return RotationF(_quat);
}
inline RotationF RotationF::operator-(const QuatF& _quat) const
{
RotationF temp = *this;
temp -= RotationF(_quat);
return temp;
}
inline RotationF RotationF::operator+(const QuatF& _quat) const
{
RotationF temp = *this;
temp += RotationF(_quat);
return temp;
}
inline RotationF& RotationF::operator-=(const QuatF& _quat)
{
*this -= RotationF(_quat);
return *this;
}
inline RotationF& RotationF::operator+=(const QuatF& _quat)
{
*this += RotationF(_quat);
return *this;
}
inline S32 RotationF::operator==(const QuatF& _quat) const
{
return *this == RotationF(_quat);
}
inline S32 RotationF::operator!=(const QuatF& _quat) const
{
return *this != RotationF(_quat);
}
//====================================================================
// MatrixF operators
//====================================================================
inline RotationF RotationF::operator=(const MatrixF& _mat)
{
return RotationF(_mat);
}
inline RotationF RotationF::operator-(const MatrixF& _mat) const
{
RotationF temp = *this;
temp -= RotationF(_mat);
return temp;
}
inline RotationF RotationF::operator+(const MatrixF& _mat) const
{
RotationF temp = *this;
temp += RotationF(_mat);
return temp;
}
inline RotationF& RotationF::operator-=(const MatrixF& _mat)
{
*this -= RotationF(_mat);
return *this;
}
inline RotationF& RotationF::operator+=(const MatrixF& _mat)
{
*this += RotationF(_mat);
return *this;
}
inline S32 RotationF::operator==(const MatrixF& _mat) const
{
return *this == RotationF(_mat);
}
inline S32 RotationF::operator!=(const MatrixF& _mat) const
{
return *this != RotationF(_mat);
}
#endif // MROTATION_H
| [
"Areloch@gmail.com"
] | Areloch@gmail.com |
85e30f6cfd0f56132eae9f3a40d392ee958f1ff8 | 7f5b3d155887bd28176e81f060fcb8f16b762d94 | /abc/123/123a.cpp | 7b213c05046a44c9bab59da99a7af4a58879b484 | [] | no_license | 3to5thpower/kyopro | 3aadae55f5953e26a8f2a5d410b86b56c3ffa5da | b3f4612c9dbccb42559b59d40cc5e6241fbb63b9 | refs/heads/master | 2020-04-23T11:02:28.927160 | 2019-12-08T14:08:05 | 2019-12-08T14:08:05 | 171,122,530 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 757 | cpp | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define INF 99999999
#define rep(i,n) for(int i=0,temp=(int)(n);i<temp;++i) //vec.size()がnの時等の高速化
#define all(x) (x).begin(),(x).end()
#define SORT(v, n) sort(v, v+n);
#define VSORT(v) sort(v.begin(), v.end());
#define vint vector<int>
#define vvint vector<vector<int>>
template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; }
int gcd(int a,int b){return b?gcd(b,a%b):a;}
int ctoi(char c) {return c-'0';}
int main(){
int k,a,b,c,d,e;
cin >> a >> b >> c >> d >> e >> k;
if(e-a<=k) cout << "Yay!" << endl;
else cout << ":(" << endl;
return 0;
}
| [
"gen194265@gmail.com"
] | gen194265@gmail.com |
5a3cdb1b319756c8aeb769e5f57c7a4d4d5a795a | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/httpd/gumtree/httpd_repos_function_1843_last_repos.cpp | 56efb4f3213e31ff2dceb3df94eed0ba99179885 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 382 | cpp | static apr_array_header_t *get_sorted_modules(apr_pool_t *p)
{
apr_array_header_t *arr = apr_array_make(p, 64, sizeof(module *));
module *modp, **entry;
for (modp = ap_top_module; modp; modp = modp->next) {
entry = &APR_ARRAY_PUSH(arr, module *);
*entry = modp;
}
qsort(arr->elts, arr->nelts, sizeof(module *), cmp_module_name);
return arr;
} | [
"993273596@qq.com"
] | 993273596@qq.com |
d978435cab0614fa2ccec3edd1e065ba3dcfa40f | 330d1e60e0402cfc685d469b44f4a6674614f681 | /Src/iberbar/Utility/StdHelper_Vector.h | 5f33a202b49fcadcdeed15e7148ab308131182d2 | [] | no_license | berbar/iberbarEngine | abeeb7e714f44867c2cf8bc55a2f699a5462e294 | 87b4d45eca444c34ad6f71326f8fa2063a62ca5d | refs/heads/master | 2023-01-23T08:28:12.872280 | 2022-05-01T16:52:47 | 2022-05-01T16:52:47 | 299,245,571 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 809 | h | #pragma once
#include <iberbar/Utility/Unknown.h>
#include <vector>
namespace iberbar
{
namespace StdHelper
{
template < typename T >
void VectorSafeClearRef( std::vector<T*>& data, bool release )
{
if ( release == true )
{
auto iter = data.begin();
auto end = data.end();
for ( ; iter != end; iter++ )
{
UNKNOWN_SAFE_RELEASE_NULL( *iter );
}
}
data.clear();
}
template < typename T >
bool VectorSafeEraseRef( std::vector<T*>& data, T* ref, bool release )
{
auto iter = data.begin();
auto end = data.end();
for ( ; iter != end; iter++ )
{
if ( ref == (*iter) )
{
if ( release == true )
{
UNKNOWN_SAFE_RELEASE_NULL( *iter );
}
data.erase( iter );
return true;
}
}
return false;
}
}
}
| [
"bigbigbir@hotmail.com"
] | bigbigbir@hotmail.com |
ea54d749e54b94c15074939604224f9a874fafac | 5606abcea74fb003332a6876e799de3c4ce01039 | /Lab 9/190041208_Task_4.cpp | f9c4ca16c98774f21d90c39b8d9730dade7ee2bf | [] | no_license | lamiya-tahsin/190041208-CSE-4302 | d43b345e42aa6365039949a20d9b0a0dc7b6a370 | 6c826d03ba9efb300dd6bc0ef3f14c4661a5873a | refs/heads/master | 2023-08-29T05:19:36.671587 | 2021-10-05T14:48:25 | 2021-10-05T14:48:25 | 380,792,763 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,080 | cpp | #include <bits/stdc++.h>
#include <string>
using namespace std;
//git commit
enum class Material {Wood,Board,Steel,foam};
class Furniture
{
protected:
string pname;
double price;
double discount;
Material madeof;
public:
Furniture(string pn,double p,double d,Material m):pname("Bed"),price(0),discount(0),madeof(Material::Wood)
{
setName(pn);
setPrice(p);
setDiscount(d);
setMadeof(m);
}
void setName(string val)
{
pname=val;
}
void setPrice(double val)
{
if(val>0)
price=val;
}
void setDiscount(double val)
{
if(val<=price)
discount=val;
}
void setMadeof(Material val)
{
madeof=val;
}
string getMadeof()
{
if(madeof==Material::Wood)
return string("Wood");
else if(madeof==Material::Board)
return string("Board");
else if(madeof==Material::Steel)
return string("Steel");
else
return string("");
}
virtual void productDetails()
{
cout<<"--------------------------------------------"<<endl;
cout<<"Product Name: "<<pname<<endl;
cout<<"Regular price:"<<price<<endl;
cout<<"Discounted price:"<<price-discount<<endl;
cout<<"Material:"<<getMadeof()<<endl;
}
double getDiscountedPrice()
{
return price-discount;
}
};
enum class Bedsize{Single,SemiDouble,Double};
class Bed:public Furniture
{
protected:
Bedsize beds;
public:
Bed(string pn,double p,double d,Material m,Bedsize b):Furniture(pn,p,d,m),beds(Bedsize::Single)
{
setBedsize(beds);
}
void setBedsize(Bedsize val)
{
beds=val;
}
string getbedsize()
{
if(beds==Bedsize::Single)
return string("Single");
else if(beds==Bedsize::SemiDouble)
return string("SemiDouble");
else if(beds==Bedsize::Double)
return string("Double");
else
return string("");
}
void productDetails()
{
Furniture::productDetails();
cout<<"Bed Size: "<<getbedsize()<<endl;
cout<<"#############################################"<<endl;
}
};
enum class SeatNumber{One,Two,Three,Four,Five};
class Sofa:public Furniture
{
protected:
SeatNumber seat;
public:
Sofa(string pn,double p,double d,Material m,SeatNumber s):Furniture(pn,p,d,m),seat(SeatNumber::Two)
{
setSeat(s);
}
void setSeat(SeatNumber val)
{
seat=val;
}
string getSeat()
{
if(seat==SeatNumber::One)
return string("One");
else if(seat==SeatNumber::Two)
return string("Two");
else if(seat==SeatNumber::Three)
return string("Three");
else if(seat==SeatNumber::Four)
return string("Four");
else if(seat==SeatNumber::Five)
return string("Five");
}
void productDetails()
{
Furniture::productDetails();
cout<<"Seat Number: "<<getSeat()<<endl;
cout<<"#############################################"<<endl;
}
};
enum class ChairCount{Two,Four,Six};
class DiningTable:public Furniture
{
protected:
ChairCount chairs;
public:
DiningTable(string pn,double p,double d,Material m,ChairCount s):Furniture(pn,p,d,m),chairs(ChairCount::Two)
{
setchair(s);
}
void setchair(ChairCount val)
{
chairs=val;
}
string getchairs()
{
if(chairs==ChairCount::Two)
return string("Two");
else if(chairs==ChairCount::Four)
return string("Four");
else if(chairs==ChairCount::Six)
return string("Six");
}
void productDetails()
{
Furniture::productDetails();
cout<<"Number of chairs: "<<getchairs()<<endl;
cout<<"#############################################"<<endl;
}
};
void order(Furniture** f1,Furniture** f2)
{
if ((*f1)->getDiscountedPrice()<(*f2)->getDiscountedPrice()) {
Furniture* temp = *f1;
*f1 = *f2;
*f2 = temp;
}
}
void sort_furniture_discount(Furniture *f[],int no_of_furnitures)
{
for (int i=0;i<no_of_furnitures;i++) {
for (int j=i+1;j<no_of_furnitures;j++) {
order( f+i,f+ j);
}
}
}
int main()
{
Furniture* f_list[100];
f_list[0] = new Bed("Bed",10000,123,Material::Wood,Bedsize::Single);
f_list[1] = new Sofa("Sofa",11000,234,Material::Steel,SeatNumber::Five);
f_list[2] = new DiningTable("Dining Table",13000,345,Material::Wood,ChairCount::Six);
f_list[3] = new Bed("Bed",10090,134,Material::Wood,Bedsize::Single);
for(int i=0; i<4; i++)
{
f_list[i]->productDetails();
}
sort_furniture_discount(f_list,4);
cout<<endl<<endl<<"*************************"<<endl;
cout<<"The sorted list: "<<endl;
for(int i=0; i<4; i++)
{
f_list[i]->productDetails();
}
f_list[1]->setSeat(4)
for(int i=0; i<4; i++)
{
delete f_list[i];
}
}
| [
"lamiya.tahsin17@gmail.com"
] | lamiya.tahsin17@gmail.com |
193d559477a4de8ac0c445fbfae9e58bdac22fb3 | 3c85cc067bc9bb9db9015c207b58081ca10fe520 | /BlockFactory.cpp | 77864b6efff40aae7231c683e828a90f45ba2245 | [] | no_license | 253627764/jowu | 37ec3fb35aa87d99256657db0fb6b0dc8d61d33f | 95b7d549bf02449a30efdafcfe650042f79b7f68 | refs/heads/master | 2021-01-21T16:44:14.491477 | 2015-05-17T16:50:23 | 2015-05-17T16:50:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 629 | cpp | #include "BlockFactory.h"
#include "TetrisBlock.h"
Block* BlockFactory::create(Block_Type type)
{
switch (type) {
case Block_Stick:
{
return new BlockStick;
}
break;
case Block_S:
{
return new BlockS;
}
break;
case Block_Z:
{
return new BlockZ;
}
break;
case Block_L:
{
return new BlockL;
}
break;
case Block_MirrorL:
{
return new BlockMirrorL;
}
break;
case Block_Hill:
{
return new BlockHill;
}
break;
case Block_Square:
{
return new BlockSquare;
}
break;
default:
{
return nullptr;
}
break;
}
} | [
"jowu598@gmail.com"
] | jowu598@gmail.com |
318db3cddd2c879079b221f82a99b49e2188b03b | ba12045eb9c0230e61bf4b0f13bd43f721678e61 | /Print_balanced_paranthesis_by_recursion.cpp | b805f52a88904be38a089890dd2b701334908b10 | [] | no_license | Kriti7744/pol | 8c346172766df8dac44dfd8b5e2d6de01d2ef1c6 | 42a7b29af74bff4e85fc5da380300870b8afa527 | refs/heads/main | 2023-08-12T11:09:02.550248 | 2021-10-19T06:26:41 | 2021-10-19T06:26:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 733 | cpp | //proposed by dark_coder
#include <bits/stdc++.h>
using namespace std;
void generateParenthesis(int n, int open, int close, string s, vector<string> &ans)
{
if (open == n && close == n)
{
ans.push_back(s);
return;
}
if (open < n)
{
generateParenthesis(n, open + 1, close, s + "{", ans);
}
if (close < open)
{
generateParenthesis(n, open, close + 1, s + "}", ans);
}
}
int main()
{
int n;
cout<<"Enter number of paranthesis you want to print combination of (eg '1' if '()')"<<endl;
cin>>n;
vector<string> ans;
generateParenthesis(n, 0, 0, "", ans);
cout<<endl;
for (auto s : ans)
{
cout << s << endl;
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
12d7beabf127181b726b24a38db56d21840f688c | c9ea781a99dfbb0d580cf35f346189077617a1f0 | /plugins/samplesource/limesdrinput/limesdrinputgui.cpp | 60859e53c316e96915eaa1396248126f80e141e2 | [] | no_license | LiShuai1225/sdrangel | 9ca7c58eb2e3e8b69fc063de6f80897d21075c07 | 10065d7243828c1d6754c7be86b1a4fb99552d07 | refs/heads/master | 2021-01-25T08:13:26.411043 | 2017-05-16T20:46:29 | 2017-05-16T20:46:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,261 | cpp | ///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2017 Edouard Griffiths, F4EXB //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation as version 3 of the License, or //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include "limesdrinputgui.h"
#include <QDebug>
#include <QMessageBox>
#include "ui_limesdrinputgui.h"
#include "gui/colormapper.h"
#include "gui/glspectrum.h"
#include "dsp/dspengine.h"
#include "dsp/dspcommands.h"
#include "device/devicesourceapi.h"
#include "dsp/filerecord.h"
LimeSDRInputGUI::LimeSDRInputGUI(DeviceSourceAPI *deviceAPI, QWidget* parent) :
QWidget(parent),
ui(new Ui::LimeSDRInputGUI),
m_deviceAPI(deviceAPI),
m_settings(),
m_sampleSource(0),
m_sampleRate(0),
m_lastEngineState((DSPDeviceSourceEngine::State)-1),
m_doApplySettings(true),
m_statusCounter(0)
{
m_limeSDRInput = new LimeSDRInput(m_deviceAPI);
m_sampleSource = (DeviceSampleSource *) m_limeSDRInput;
m_deviceAPI->setSource(m_sampleSource);
ui->setupUi(this);
float minF, maxF, stepF;
m_limeSDRInput->getLORange(minF, maxF, stepF);
ui->centerFrequency->setColorMapper(ColorMapper(ColorMapper::ReverseGold));
ui->centerFrequency->setValueRange(7, ((uint32_t) minF)/1000, ((uint32_t) maxF)/1000); // frequency dial is in kHz
m_limeSDRInput->getSRRange(minF, maxF, stepF);
ui->sampleRate->setColorMapper(ColorMapper(ColorMapper::ReverseGreenYellow));
ui->sampleRate->setValueRange(8, (uint32_t) minF, (uint32_t) maxF);
m_limeSDRInput->getLPRange(minF, maxF, stepF);
ui->lpf->setColorMapper(ColorMapper(ColorMapper::ReverseGold));
ui->lpf->setValueRange(6, (minF/1000)+1, maxF/1000);
ui->lpFIR->setColorMapper(ColorMapper(ColorMapper::ReverseGold));
ui->lpFIR->setValueRange(5, 1U, 56000U);
ui->ncoFrequency->setColorMapper(ColorMapper(ColorMapper::ReverseGold));
ui->channelNumberText->setText(tr("#%1").arg(m_limeSDRInput->getChannelIndex()));
ui->hwDecimLabel->setText(QString::fromUtf8("H\u2193"));
ui->swDecimLabel->setText(QString::fromUtf8("S\u2193"));
connect(&m_updateTimer, SIGNAL(timeout()), this, SLOT(updateHardware()));
connect(&m_statusTimer, SIGNAL(timeout()), this, SLOT(updateStatus()));
m_statusTimer.start(500);
displaySettings();
char recFileNameCStr[30];
sprintf(recFileNameCStr, "test_%d.sdriq", m_deviceAPI->getDeviceUID());
m_fileSink = new FileRecord(std::string(recFileNameCStr));
m_deviceAPI->addSink(m_fileSink);
connect(m_deviceAPI->getDeviceOutputMessageQueue(), SIGNAL(messageEnqueued()), this, SLOT(handleMessagesToGUI()), Qt::QueuedConnection);
}
LimeSDRInputGUI::~LimeSDRInputGUI()
{
m_deviceAPI->removeSink(m_fileSink);
delete m_fileSink;
delete m_sampleSource; // Valgrind memcheck
delete ui;
}
void LimeSDRInputGUI::destroy()
{
delete this;
}
void LimeSDRInputGUI::setName(const QString& name)
{
setObjectName(name);
}
QString LimeSDRInputGUI::getName() const
{
return objectName();
}
void LimeSDRInputGUI::resetToDefaults()
{
m_settings.resetToDefaults();
displaySettings();
sendSettings();
}
qint64 LimeSDRInputGUI::getCenterFrequency() const
{
return m_settings.m_centerFrequency;
}
void LimeSDRInputGUI::setCenterFrequency(qint64 centerFrequency)
{
m_settings.m_centerFrequency = centerFrequency;
displaySettings();
sendSettings();
}
QByteArray LimeSDRInputGUI::serialize() const
{
return m_settings.serialize();
}
bool LimeSDRInputGUI::deserialize(const QByteArray& data)
{
if (m_settings.deserialize(data))
{
displaySettings();
sendSettings();
return true;
}
else
{
resetToDefaults();
return false;
}
}
bool LimeSDRInputGUI::handleMessage(const Message& message) // TODO: does not seem to be really useful in any of the source (+sink?) plugins
{
return false;
}
void LimeSDRInputGUI::handleMessagesToGUI()
{
Message* message;
while ((message = m_deviceAPI->getDeviceOutputMessageQueue()->pop()) != 0)
{
if (DSPSignalNotification::match(*message))
{
qDebug("LimeSDRInputGUI::handleMessagesToGUI: message: %s", message->getIdentifier());
DSPSignalNotification* notif = (DSPSignalNotification*) message;
m_sampleRate = notif->getSampleRate();
m_deviceCenterFrequency = notif->getCenterFrequency();
qDebug("LimeSDRInputGUI::handleMessagesToGUI: SampleRate: %d, CenterFrequency: %llu", notif->getSampleRate(), notif->getCenterFrequency());
updateSampleRateAndFrequency();
m_fileSink->handleMessage(*notif); // forward to file sink
delete message;
}
else if (LimeSDRInput::MsgReportLimeSDRToGUI::match(*message))
{
qDebug("LimeSDRInputGUI::handleMessagesToGUI: message: %s", message->getIdentifier());
LimeSDRInput::MsgReportLimeSDRToGUI *report = (LimeSDRInput::MsgReportLimeSDRToGUI *) message;
m_settings.m_centerFrequency = report->getCenterFrequency();
m_settings.m_devSampleRate = report->getSampleRate();
m_settings.m_log2HardDecim = report->getLog2HardDecim();
blockApplySettings(true);
displaySettings();
blockApplySettings(false);
LimeSDRInput::MsgSetReferenceConfig* conf = LimeSDRInput::MsgSetReferenceConfig::create(m_settings);
m_sampleSource->getInputMessageQueue()->push(conf);
delete message;
}
else if (DeviceLimeSDRShared::MsgCrossReportToGUI::match(*message))
{
DeviceLimeSDRShared::MsgCrossReportToGUI *report = (DeviceLimeSDRShared::MsgCrossReportToGUI *) message;
m_settings.m_devSampleRate = report->getSampleRate();
blockApplySettings(true);
displaySettings();
blockApplySettings(false);
LimeSDRInput::MsgSetReferenceConfig* conf = LimeSDRInput::MsgSetReferenceConfig::create(m_settings);
m_sampleSource->getInputMessageQueue()->push(conf);
delete message;
}
else if (LimeSDRInput::MsgReportStreamInfo::match(*message))
{
LimeSDRInput::MsgReportStreamInfo *report = (LimeSDRInput::MsgReportStreamInfo *) message;
if (report->getSuccess())
{
ui->streamStatusLabel->setStyleSheet("QLabel { background-color : green; }");
ui->streamLinkRateText->setText(tr("%1 MB/s").arg(QString::number(report->getLinkRate() / 1000000.0f, 'f', 3)));
if (report->getUnderrun() > 0) {
ui->underrunLabel->setStyleSheet("QLabel { background-color : red; }");
} else {
ui->underrunLabel->setStyleSheet("QLabel { background:rgb(79,79,79); }");
}
if (report->getOverrun() > 0) {
ui->overrunLabel->setStyleSheet("QLabel { background-color : red; }");
} else {
ui->overrunLabel->setStyleSheet("QLabel { background:rgb(79,79,79); }");
}
if (report->getDroppedPackets() > 0) {
ui->droppedLabel->setStyleSheet("QLabel { background-color : red; }");
} else {
ui->droppedLabel->setStyleSheet("QLabel { background:rgb(79,79,79); }");
}
ui->fifoBar->setMaximum(report->getFifoSize());
ui->fifoBar->setValue(report->getFifoFilledCount());
ui->fifoBar->setToolTip(tr("FIFO fill %1/%2 samples").arg(QString::number(report->getFifoFilledCount())).arg(QString::number(report->getFifoSize())));
}
else
{
ui->streamStatusLabel->setStyleSheet("QLabel { background:rgb(79,79,79); }");
}
}
}
}
void LimeSDRInputGUI::updateSampleRateAndFrequency()
{
m_deviceAPI->getSpectrum()->setSampleRate(m_sampleRate);
m_deviceAPI->getSpectrum()->setCenterFrequency(m_deviceCenterFrequency);
ui->deviceRateLabel->setText(tr("%1k").arg(QString::number(m_sampleRate / 1000.0f, 'g', 5)));
}
void LimeSDRInputGUI::displaySettings()
{
ui->centerFrequency->setValue(m_settings.m_centerFrequency / 1000);
ui->sampleRate->setValue(m_settings.m_devSampleRate);
ui->dcOffset->setChecked(m_settings.m_dcBlock);
ui->iqImbalance->setChecked(m_settings.m_iqCorrection);
ui->hwDecim->setCurrentIndex(m_settings.m_log2HardDecim);
ui->swDecim->setCurrentIndex(m_settings.m_log2SoftDecim);
ui->lpf->setValue(m_settings.m_lpfBW / 1000);
ui->lpFIREnable->setChecked(m_settings.m_lpfFIREnable);
ui->lpFIR->setValue(m_settings.m_lpfFIRBW / 1000);
ui->gain->setValue(m_settings.m_gain);
ui->gainText->setText(tr("%1dB").arg(m_settings.m_gain));
ui->antenna->setCurrentIndex((int) m_settings.m_antennaPath);
setNCODisplay();
ui->ncoEnable->setChecked(m_settings.m_ncoEnable);
}
void LimeSDRInputGUI::setNCODisplay()
{
int ncoHalfRange = (m_settings.m_devSampleRate * (1<<(m_settings.m_log2HardDecim)))/2;
ui->ncoFrequency->setValueRange(7,
(m_settings.m_centerFrequency - ncoHalfRange)/1000,
(m_settings.m_centerFrequency + ncoHalfRange)/1000); // frequency dial is in kHz
ui->ncoFrequency->setValue((m_settings.m_centerFrequency + m_settings.m_ncoFrequency)/1000);
}
void LimeSDRInputGUI::sendSettings()
{
if(!m_updateTimer.isActive())
m_updateTimer.start(100);
}
void LimeSDRInputGUI::updateHardware()
{
if (m_doApplySettings)
{
qDebug() << "LimeSDRInputGUI::updateHardware";
LimeSDRInput::MsgConfigureLimeSDR* message = LimeSDRInput::MsgConfigureLimeSDR::create(m_settings);
m_sampleSource->getInputMessageQueue()->push(message);
m_updateTimer.stop();
}
}
void LimeSDRInputGUI::updateStatus()
{
int state = m_deviceAPI->state();
if(m_lastEngineState != state)
{
switch(state)
{
case DSPDeviceSourceEngine::StNotStarted:
ui->startStop->setStyleSheet("QToolButton { background:rgb(79,79,79); }");
break;
case DSPDeviceSourceEngine::StIdle:
ui->startStop->setStyleSheet("QToolButton { background-color : blue; }");
break;
case DSPDeviceSourceEngine::StRunning:
ui->startStop->setStyleSheet("QToolButton { background-color : green; }");
break;
case DSPDeviceSourceEngine::StError:
ui->startStop->setStyleSheet("QToolButton { background-color : red; }");
QMessageBox::information(this, tr("Message"), m_deviceAPI->errorMessage());
break;
default:
break;
}
m_lastEngineState = state;
}
if (m_statusCounter < 1)
{
m_statusCounter++;
}
else
{
LimeSDRInput::MsgGetStreamInfo* message = LimeSDRInput::MsgGetStreamInfo::create();
m_sampleSource->getInputMessageQueue()->push(message);
m_statusCounter = 0;
}
}
void LimeSDRInputGUI::blockApplySettings(bool block)
{
m_doApplySettings = !block;
}
void LimeSDRInputGUI::on_startStop_toggled(bool checked)
{
if (checked)
{
if (m_deviceAPI->initAcquisition())
{
m_deviceAPI->startAcquisition();
DSPEngine::instance()->startAudioOutput();
}
}
else
{
m_deviceAPI->stopAcquisition();
DSPEngine::instance()->stopAudioOutput();
}
}
void LimeSDRInputGUI::on_record_toggled(bool checked)
{
if (checked)
{
ui->record->setStyleSheet("QToolButton { background-color : red; }");
m_fileSink->startRecording();
}
else
{
ui->record->setStyleSheet("QToolButton { background:rgb(79,79,79); }");
m_fileSink->stopRecording();
}
}
void LimeSDRInputGUI::on_centerFrequency_changed(quint64 value)
{
m_settings.m_centerFrequency = value * 1000;
setNCODisplay();
sendSettings();
}
void LimeSDRInputGUI::on_ncoFrequency_changed(quint64 value)
{
m_settings.m_ncoFrequency = (int64_t) value - (int64_t) m_settings.m_centerFrequency/1000;
m_settings.m_ncoFrequency *= 1000;
sendSettings();
}
void LimeSDRInputGUI::on_ncoEnable_toggled(bool checked)
{
m_settings.m_ncoEnable = checked;
sendSettings();
}
void LimeSDRInputGUI::on_ncoReset_clicked(bool checked)
{
m_settings.m_ncoFrequency = 0;
ui->ncoFrequency->setValue(m_settings.m_centerFrequency/1000);
sendSettings();
}
void LimeSDRInputGUI::on_dcOffset_toggled(bool checked)
{
m_settings.m_dcBlock = checked;
sendSettings();
}
void LimeSDRInputGUI::on_iqImbalance_toggled(bool checked)
{
m_settings.m_iqCorrection = checked;
sendSettings();
}
void LimeSDRInputGUI::on_sampleRate_changed(quint64 value)
{
m_settings.m_devSampleRate = value;
setNCODisplay();
sendSettings();}
void LimeSDRInputGUI::on_hwDecim_currentIndexChanged(int index)
{
if ((index <0) || (index > 5))
return;
m_settings.m_log2HardDecim = index;
setNCODisplay();
sendSettings();
}
void LimeSDRInputGUI::on_swDecim_currentIndexChanged(int index)
{
if ((index <0) || (index > 6))
return;
m_settings.m_log2SoftDecim = index;
sendSettings();
}
void LimeSDRInputGUI::on_lpf_changed(quint64 value)
{
m_settings.m_lpfBW = value * 1000;
sendSettings();
}
void LimeSDRInputGUI::on_lpFIREnable_toggled(bool checked)
{
m_settings.m_lpfFIREnable = checked;
sendSettings();
}
void LimeSDRInputGUI::on_lpFIR_changed(quint64 value)
{
m_settings.m_lpfFIRBW = value * 1000;
if (m_settings.m_lpfFIREnable) { // do not send the update if the FIR is disabled
sendSettings();
}
}
void LimeSDRInputGUI::on_gain_valueChanged(int value)
{
m_settings.m_gain = value;
ui->gainText->setText(tr("%1dB").arg(m_settings.m_gain));
sendSettings();
}
void LimeSDRInputGUI::on_antenna_currentIndexChanged(int index)
{
m_settings.m_antennaPath = (LimeSDRInputSettings::PathRFE) index;
sendSettings();
}
| [
"f4exb06@gmail.com"
] | f4exb06@gmail.com |
01bcabdbd8d64c391fdf4038f2ca31c0dc75b7c5 | d8ea1ed34f0261f9164b597799111ece08c208e4 | /TopCoder/RandomPancakeStackDiv2.cpp | 15f13a121d668ca2f0ad39637f1633814628010f | [] | no_license | OmarAbdelrahman/solved-problems | 8a6695280072588332e0e0c5606d699b7489b898 | 62b734644bce6c997bd08aa651b968a9fdff205c | refs/heads/master | 2021-09-05T07:58:58.631821 | 2018-01-25T12:45:07 | 2018-01-25T12:45:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 696 | cpp | #include <bits/stdc++.h>
using namespace std;
class RandomPancakeStackDiv2 {
public:
double f(const int mask, const int width, const int sum, const int size, const vector<int>& d) {
if (size == 0) {
return sum;
}
double result = 0.0;
for (int i = 0; i < d.size(); ++i) {
if (mask & (1 << i)) {
continue;
}
if (i < width) {
result += f(mask | (1 << i), i, sum + d[i], size - 1, d) / size;
} else {
result += (sum * 1.0 / size);
}
}
return result;
}
double expectedDeliciousness(vector<int> d) {
const int n = d.size();
double result = 0.0;
for (int i = 0; i < n; ++i) {
result += f(1 << i, i, d[i], n - 1, d) / n;
}
return result;
}
}; | [
"omar.sebres@gmail.com"
] | omar.sebres@gmail.com |
b2d79e74c25aaf77d284fdcafb5d6f95885e286d | 9ee5bb630c292084d4d875e89215a8989e8422dc | /Conway_GoL/Game.cpp | e614458a1c10d2d6b4b823cdcfb620662fd12f1f | [] | no_license | joonhan/Conway-GoL | fa73e4fc7c7d328216962e784cdfd53c53464d2e | d6076fbf4f1981cc10afc05dac8b2496a493b190 | refs/heads/master | 2021-01-22T08:10:14.239921 | 2017-02-14T05:50:30 | 2017-02-14T05:50:30 | 81,877,547 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,914 | cpp | // Game.cpp
// Conway_GoL
#include "Game.hpp"
using namespace Constants_GoL;
//Game class default constructor
Game::Game() {
//assign window settings
window.create(sf::VideoMode(kWindowWidth, kWindowHeight), "Game of Life");
//initialize game status flag
isGameRunning = false;
}
//simplify button draw methods
void Game::drawButton(Button &btn) {
window.draw(btn.getShape());
window.draw(btn.getText());
}
//draw the blinker shape
void Game::drawBlinker() {
//scale the drawing of shape according to the cellSize and draw at center of window
grid.setCellIsAlive(true, kCellsPerCol/2 * kCellSize, kCellsPerRow/2 * kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/2 * kCellSize, kCellsPerRow/2 * kCellSize + kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/2 * kCellSize, kCellsPerRow/2 * kCellSize + 2*kCellSize);
}
//draw the glider shape
void Game::drawGlider() {
grid.setCellIsAlive(true, kCellsPerCol/2 * kCellSize, kCellsPerRow/2 * kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/2 * kCellSize + kCellSize, kCellsPerRow/2*kCellSize + kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/2 * kCellSize-kCellSize, kCellsPerRow/2 *kCellSize + 2*kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/2 * kCellSize, kCellsPerRow/2 * kCellSize + 2*kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/2 * kCellSize + kCellSize, kCellsPerRow/2 * kCellSize + 2*kCellSize);
}
//draw the gun shape from left to right
void Game::drawGoblinGun() {
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize, kCellsPerRow/2 * kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + kCellSize, kCellsPerRow/2 * kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize, kCellsPerRow/2*kCellSize + kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + kCellSize, kCellsPerRow/2*kCellSize + kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 10*kCellSize, kCellsPerRow/2 * kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 10*kCellSize, kCellsPerRow/2 * kCellSize + kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 10*kCellSize, kCellsPerRow/2 * kCellSize + 2*kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 11*kCellSize, kCellsPerRow/2 * kCellSize - kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 11*kCellSize, kCellsPerRow/2 * kCellSize + 3*kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 12*kCellSize, kCellsPerRow/2 * kCellSize - 2*kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 12*kCellSize, kCellsPerRow/2 * kCellSize + 4*kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 13*kCellSize, kCellsPerRow/2 * kCellSize - 2*kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 13*kCellSize, kCellsPerRow/2 * kCellSize + 4*kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 14*kCellSize, kCellsPerRow/2 * kCellSize + kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 15*kCellSize, kCellsPerRow/2 * kCellSize - kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 15*kCellSize, kCellsPerRow/2 * kCellSize + 3*kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 16*kCellSize, kCellsPerRow/2 * kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 16*kCellSize, kCellsPerRow/2 * kCellSize + kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 16*kCellSize, kCellsPerRow/2 * kCellSize + 2*kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 17*kCellSize, kCellsPerRow/2 * kCellSize + kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 20*kCellSize, kCellsPerRow/2 * kCellSize - 2*kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 20*kCellSize, kCellsPerRow/2 * kCellSize - kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 20*kCellSize, kCellsPerRow/2 * kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 21*kCellSize, kCellsPerRow/2 * kCellSize - 2*kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 21*kCellSize, kCellsPerRow/2 * kCellSize - kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 21*kCellSize, kCellsPerRow/2 * kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 22*kCellSize, kCellsPerRow/2 * kCellSize - 3*kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 22*kCellSize, kCellsPerRow/2 * kCellSize + kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 24*kCellSize, kCellsPerRow/2 * kCellSize - 4*kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 24*kCellSize, kCellsPerRow/2 * kCellSize - 3*kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 24*kCellSize, kCellsPerRow/2 * kCellSize + 1*kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 24*kCellSize, kCellsPerRow/2 * kCellSize + 2*kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 34*kCellSize, kCellsPerRow/2*kCellSize - 2*kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 35*kCellSize, kCellsPerRow/2*kCellSize - 2*kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 34*kCellSize, kCellsPerRow/2*kCellSize - kCellSize);
grid.setCellIsAlive(true, kCellsPerCol/4 * kCellSize + 35*kCellSize, kCellsPerRow/2*kCellSize - kCellSize);
}
//runs the main game loop
void Game::run() {
//set background texture
sf::Texture background;
if (!(background.loadFromFile(resourcePath() + "white_1600x1200.jpg"))) {
std::cout << "Error: could not load image" << std::endl;
return EXIT_FAILURE;
}
//set font
sf::Font font;
if (!(font.loadFromFile(resourcePath() + "Arial.ttf"))) {
std::cout << "Error: could not load text file" << std::endl;
return EXIT_FAILURE;
}
//assign texture to sprite, which will be drawn
sf::Sprite gameBackground(background);
//limit fps
window.setFramerateLimit(30);
//create gray color
sf::Color gray(210, 210, 210);
//create buttons with text, color, and x and y positions
Button blinkerButton ("Blinker", gray, 160, 1060);
Button gliderButton ("Glider", gray, 330, 1060);
Button goblinGunButton ("GoblinGun", gray, 480, 1060);
Button clearButton("CLEAR", gray, 1100, 1060);
Button startButton("START", gray, 1260, 1060);
Button stopButton("STOP", gray, 1260, 1060);
Button speedUpButton("SPEED +", gray, 700, 1060);
Button speedDownButton("SPEED -", gray, 850, 1060);
//set cell generation counter
int genNum = 0;
//set text that shows the cell generation counter
sf::Text genCounter("generation: " + std::to_string(genNum), font, 40);
genCounter.setFillColor(sf::Color::Black);
genCounter.setPosition(5, 0);
//start the clock
sf::Clock clock;
//set delay between frames
sf::Time frameDelay = sf::milliseconds(500);
//set text that shows the frame delay
sf::Text delayCounter("delay: " + std::to_string(frameDelay.asMilliseconds()) + "ms", font, 40);
delayCounter.setFillColor(sf::Color::Black);
delayCounter.setPosition(5, 40);
//main game loop
while (window.isOpen()) {
//event handler
while (window.pollEvent(event)) {
//when window close button is pressed, close it
if (event.type == sf::Event::Closed) {
window.close();
}
//check when left mouse button is released (instead of 'pressed' which will sometimes detect
//multiple clicks in each loop iteration)
if (event.type == sf::Event::MouseButtonReleased) {
//get the position of the mouse within the window
sf::Vector2i position = sf::Mouse::getPosition(window);
//if mouse position is hovering over startButton
if (position.x > startButton.getBound(Button::left) && position.x < startButton.getBound(Button::right) && position.y > startButton.getBound(Button::top) && position.y < startButton.getBound(Button::bottom)) {
//if game is running, mouse click pauses it; else restarts it
if (isGameRunning == true) {
isGameRunning = false;
} else {
isGameRunning = true;
}
}
if (!isGameRunning) {
//if left mouse is pressed, set switch cell status
if (grid.getCellIsAlive(position.x, position.y) == false) {
grid.setCellIsAlive(true, position.x, position.y);
}
else {
grid.setCellIsAlive(false, position.x, position.y);
}
//if mouse is over clearButton
if (position.x > clearButton.getBound(Button::left) && position.x < clearButton.getBound(Button::right) && position.y > clearButton.getBound(Button::top) && position.y < clearButton.getBound(Button::bottom)) {
//clear grid and reset generation counter
grid.clearGrid();
genNum = 0;
genCounter.setString("generation: " + std::to_string(genNum));
}
}
//if mouse is over blinkerButton
if (position.x > blinkerButton.getBound(Button::left) && position.x < blinkerButton.getBound(Button::right) && position.y > blinkerButton.getBound(Button::top) && position.y < blinkerButton.getBound(Button::bottom)) {
grid.clearGrid();
genNum = 0;
drawBlinker();
}
//if mouse is over gliderButton
if (position.x > gliderButton.getBound(Button::left) && position.x < gliderButton.getBound(Button::right) && position.y > gliderButton.getBound(Button::top) && position.y < gliderButton.getBound(Button::bottom)) {
grid.clearGrid();
genNum = 0;
drawGlider();
}
//if mouse is over goblinGunButton
if (position.x > goblinGunButton.getBound(Button::left) && position.x < goblinGunButton.getBound(Button::right) && position.y > goblinGunButton.getBound(Button::top) && position.y < goblinGunButton.getBound(Button::bottom)) {
grid.clearGrid();
genNum = 0;
drawGoblinGun();
}
//if mouse is over speedUpButton
if (position.x > speedUpButton.getBound(Button::left) && position.x < speedUpButton.getBound(Button::right) && position.y > speedUpButton.getBound(Button::top) && position.y < speedUpButton.getBound(Button::bottom)) {
//with every press of speedUpButton, decrement delay by 50ms but keep delay >= 0
if (frameDelay.asMilliseconds() > 0) {
frameDelay -= sf::milliseconds(50);
}
delayCounter.setString("delay: " + std::to_string(frameDelay.asMilliseconds())+"ms");
}
//if mouse is over speedDownButton
if (position.x > speedDownButton.getBound(Button::left) && position.x < speedDownButton.getBound(Button::right) && position.y > speedDownButton.getBound(Button::top) && position.y < speedDownButton.getBound(Button::bottom)) {
//increment delay with each press but keep frameDelay <= 1000
if (frameDelay.asMilliseconds() < 1000) {
frameDelay += sf::milliseconds(50);
}
delayCounter.setString("delay: " + std::to_string(frameDelay.asMilliseconds())+"ms");
}
} //end mouse pressed
//if spacebar is pressed, pause the game
if (event.type == sf::Event::KeyPressed){
if (event.key.code == sf::Keyboard::Space) {
isGameRunning = !isGameRunning;
}
}
}
//begin drawing in the loop
window.clear();
window.draw(gameBackground);
grid.drawCells(window);
grid.drawGridLines(window);
//get elapsed time with each loop
sf::Time elapsed = clock.getElapsedTime();
if (isGameRunning == true) {
//only update cells if the time elapsed goes over frameDelay
if (elapsed.asMilliseconds() > frameDelay.asMilliseconds()) {
grid.update(window);
clock.restart();
genNum++;
genCounter.setString("generation: " + std::to_string(genNum));
}
drawButton(stopButton);
drawButton(speedUpButton);
drawButton(speedDownButton);
} else {
drawButton(startButton);
drawButton(clearButton);
}
grid.drawCells(window);
grid.drawGridLines(window);
drawButton(blinkerButton);
drawButton(gliderButton);
drawButton(goblinGunButton);
window.draw(genCounter);
window.draw(delayCounter);
window.display();
}
} //end run()
| [
"hanjs@Joonsoos-MacBook-Pro.local"
] | hanjs@Joonsoos-MacBook-Pro.local |
b00f292f9b383fed8ed6b26dd35b643c62c73be9 | f5f67756f203c35eed8edd3330a2c60d927cee52 | /hrdesktop/common/src/Modules/ScreenCapture/ScreenCaptureModule_Impl.cpp | e22d212dcb33ca14e9cf3e86e2ee7e53ea25dd6c | [
"BSD-2-Clause"
] | permissive | wang5858/highwayns | 86c87ca139f0c0bdd7930b649ef3236e4b116aba | 73b1cf13b5a9a36f485d7b82600654095a271cd9 | refs/heads/master | 2021-01-19T14:24:01.144989 | 2017-04-22T01:56:18 | 2017-04-22T01:56:18 | 88,157,128 | 1 | 0 | null | 2017-04-13T11:18:11 | 2017-04-13T11:18:11 | null | UTF-8 | C++ | false | false | 2,560 | cpp |
/*******************************************************************************
* @file ScreenCaptureModule_Impl.cpp 2015\5\5 15:51:49 $
* @author 南松<nansong@mogujie.com>
* @brief
******************************************************************************/
#include "stdafx.h"
#include "ScreenCaptureModule_Impl.h"
#include "ScreenCapture/ScreenCapture.h"
#include "utility/utilCommonAPI.h"
#include "utility/utilStrCodingAPI.h"
#include "../../3rdParty/src/cxImage/cxImage/ximage.h"
/******************************************************************************/
namespace module
{
IScreenCaptureModule* getScreenCaptureModule()
{
static ScreenCaptureModule_Impl module;
return &module;
}
}
BOOL ScreenCaptureModule_Impl::initCapture(__in HWND hWnd)
{
return ScreenCapture::getInstance()->initCapture(hWnd);
}
void ScreenCaptureModule_Impl::onScreenCaptureFinish(__in std::wstring resultPicPath)
{
//1. 加载到剪切板
/*CxImage img;
img.Load(resultPicPath.c_str(), CXIMAGE_SUPPORT_PNG);
HBITMAP hBitmap = img.MakeBitmap();
if (!hBitmap)
{
return;
}
OpenClipboard(AfxGetMainWnd()->GetSafeHwnd());
EmptyClipboard();
SetClipboardData(CF_BITMAP, hBitmap);
CloseClipboard();
std::string strCapturePath = util::ws2s(resultPicPath);
asynNotifyObserver(module::MODULE_SCREEN_CAPTURE_PREFIX + "id", strCapturePath);*/
HBITMAP hBitmap = (HBITMAP)LoadImage(NULL, resultPicPath.c_str(), IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
if (!hBitmap)
{
return;
}
if (!OpenClipboard(NULL))
{
return;
}
do
{
if (!EmptyClipboard())
{
break;
}
SetClipboardData(CF_BITMAP, hBitmap);
std::string strCapturePath = util::ws2s(resultPicPath);
asynNotifyObserver(module::MODULE_SCREEN_CAPTURE_PREFIX + "id", strCapturePath);
} while (FALSE);
CloseClipboard();
DeleteObject(hBitmap);
}
BOOL ScreenCaptureModule_Impl::startCapture(__in std::wstring strSavePath, __in BOOL bMinimizeWindow)
{
return ScreenCapture::getInstance()->startCapture(strSavePath, (ScreenCaptureCallback *)this, bMinimizeWindow);
}
module::ScreenCaptureHotkeyId ScreenCaptureModule_Impl::shouldHandle(__in LPARAM lParam)
{
return (module::ScreenCaptureHotkeyId)ScreenCapture::getInstance()->shouldHandle(lParam);
}
void ScreenCaptureModule_Impl::cancelCapture()
{
ScreenCapture::getInstance()->cancelCapture();
}
/**************************************************************/
| [
"tei952@hotmail.com"
] | tei952@hotmail.com |
b006b27d6f069b8ed7ddef18b04407df8dac9920 | fe50b4afc85d88027c6f63ec9da85787946507db | /Libs/PluginFramework/Testing/FrameworkTestPlugins/auth_plugin/auth_plugin.cpp | afa81b9a9c90dc065be57403c38ab1cc2f9bfe32 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | yuzhongbin/CTK | a33e14bcb99ddbf11040f7d8202d6b79b2925b72 | c7c851074079d3e61eb20d89f0c8b129dbd64fa9 | refs/heads/master | 2020-12-21T01:10:39.283543 | 2020-02-28T13:24:33 | 2020-02-28T13:24:33 | 236,262,193 | 0 | 0 | Apache-2.0 | 2020-01-26T03:29:36 | 2020-01-26T03:29:35 | null | UTF-8 | C++ | false | false | 465 | cpp | #include <QtDebug>
#include "auth_plugin.h"
#include <ctkPluginContext.h>
AuthPlugin::AuthPlugin()
{
// context->registerService<AuthenticationService>(this);
}
bool AuthPlugin::login(const QString& username, const QString& password)
{
qDebug() << __FILE__ << __FUNCTION__;
if (QString::compare(username, "root") == 0
&& QString::compare(password, "123456") == 0) {
return true;
} else {
return false;
}
} | [
"yuzhongbin@gmail.com"
] | yuzhongbin@gmail.com |
94d85d7968974b379a2719fea54919a3625beee5 | 188fb8ded33ad7a2f52f69975006bb38917437ef | /Fluid/processor5/0.16/Force | a89f78bb57d7d6a39a8f11d75af0accb63d09419 | [] | no_license | abarcaortega/Tuto_2 | 34a4721f14725c20471ff2dc8d22b52638b8a2b3 | 4a84c22efbb9cd2eaeda92883343b6910e0941e2 | refs/heads/master | 2020-08-05T16:11:57.674940 | 2019-10-04T09:56:09 | 2019-10-04T09:56:09 | 212,573,883 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,724 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: dev |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volVectorField;
location "0.16";
object Force;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [1 1 -2 0 0 0 0];
internalField uniform (0 0 0);
boundaryField
{
inlet
{
type calculated;
value nonuniform 0();
}
outlet
{
type calculated;
value uniform (0 0 0);
}
flap
{
type calculated;
value nonuniform 0();
}
upperWall
{
type calculated;
value nonuniform 0();
}
lowerWall
{
type calculated;
value uniform (0 0 0);
}
frontAndBack
{
type empty;
}
procBoundary5to2
{
type processor;
value uniform (0 0 0);
}
procBoundary5to4
{
type processor;
value uniform (0 0 0);
}
}
// ************************************************************************* //
| [
"aldo.abarca.ortega@gmail.com"
] | aldo.abarca.ortega@gmail.com | |
a18b70f1c0b854b82c37421855437280ad0b1aa4 | de9645f0e53f9a1b130ed3a1fb6888ed0433cd7c | /asgmt03.cpp | 74403026bfb2c74842c33e00185a6908293fb268 | [] | no_license | JMWhitney/hashmap | 0a32bb50f9255453550aa0eefe3bf6732a0e10f8 | e4263ee571525fb69579fd00a6b35210223f4fe8 | refs/heads/master | 2020-04-07T10:52:49.765797 | 2018-11-19T23:36:39 | 2018-11-19T23:36:39 | 158,303,828 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,368 | cpp | // do not change this file
#include <cstring>
#include <iostream>
#include <iomanip>
#include "hashmap.h"
using namespace std;
static HashMap *hm;
static void printStocks(void)
{
cout << endl
<< "----------------------------------------------------------------------------"
<< endl << endl
<< *hm // print the contents of the HashMap
<< endl
<< "----------------------------------------------------------------------------"
<< endl << endl;
}
// The following 4 functions are used by main() to exercise your code.
// You can look at the details of them if you need to understand exactly
// how your code is being called.
// prints information about how an item was stored by your code
static void printAdditional(unsigned int symbolHash, unsigned int hashIndex,
unsigned int usedIndex, unsigned int sequenceLgth)
{
cout << "(hc 0x"
<< right
<< hex << setfill('0')
<< uppercase << setw(8) << symbolHash
<< dec << setfill(' ')
<< ", hi " << setw(2) << hashIndex
<< ", ui " << setw(2) << static_cast<signed int>(usedIndex)
<< ", sl " << setw(2) << sequenceLgth
<< ")"
<< left << endl;
}
// exercises your HashMap::get() function
static void searchStock(char const * const symbol)
{
unsigned int usedIndex, hashIndex, symbolHash, sequenceLgth;
Stock s;
if (hm->get(symbol, s, symbolHash, hashIndex, usedIndex, sequenceLgth))
cout << "found " << left << setw(8) << symbol;
else
cout << symbol << " not found ";
printAdditional(symbolHash, hashIndex, usedIndex, sequenceLgth);
}
// exercises your HashMap::put() function. Creates an instance of Stock, hands that
// to your code, and then totally destroys it. This makes sure that your code will
// fail unless you do a "deep copy" of the Stock instance.
static void addStock(char *symbol, char *name, int sharePrice, Date priceDate)
{
unsigned int usedIndex, hashIndex, symbolHash, sequenceLgth;
char *sym {new char[strlen(symbol) + 1]};
char *nm {new char[strlen(name) + 1]};
Stock *s;
strcpy(sym, symbol);
strcpy(nm, name);
s = new Stock(sym, nm, sharePrice, priceDate);
if (hm->put(*s, symbolHash, hashIndex, usedIndex, sequenceLgth)) {
cout << "added " << left << setw(8) << s->getSymbol();
printAdditional(symbolHash, hashIndex, usedIndex, sequenceLgth);
}
else
cout << s->getSymbol() << " not added" << endl;
delete[] sym;
delete[] nm;
delete s;
}
// exercises your HashMap::remove() function
static void removeStock(char *symbol)
{
unsigned int usedIndex, hashIndex, symbolHash, sequenceLgth;
Stock s;
if (hm->remove(symbol, s, symbolHash, hashIndex, usedIndex, sequenceLgth)) {
cout << "removed " << left << setw(6) << symbol;
printAdditional(symbolHash, hashIndex, usedIndex, sequenceLgth);
}
else
cout << symbol << " not removed" << endl;
}
int main(int argc, char **argv)
{
if (argc > 1) // turn off cout
std::cout.setstate(std::ios_base::badbit);
cout << "CS260 - Assignment 3 - " << HashMap::YOUR_NAME << endl;
hm = new HashMap(13);
printStocks();
searchStock("IBM");
addStock("IBM", "International Business Machines", 2573, Date(Date::MAY, 23, 1967));
printStocks();
searchStock("IBM");
removeStock("IBM");
searchStock("IBM");
removeStock("IBM");
addStock("MLT", "MLT Software, Inc.", 800, Date(Date::APRIL, 18, 1988));
addStock("IBM", "International Business Machines", 2573, Date(Date::MAY, 23, 1967));
addStock("XRX", "Xerox", 1892, Date(Date::JUNE, 1, 1980));
addStock("US:BA", "Boeing", 6407, Date(Date::DECEMBER, 14, 1993));
addStock("GD", "General Dynamics", 7281, Date(Date::OCTOBER, 24, 2006));
addStock("AAPL", "Apple Computer, Inc.", 2308, Date(Date::MAY, 1, 1980));
addStock("AAPL", "Apple Computer, Inc.", 2308, Date(Date::MAY, 1, 1980));
addStock("GE", "General Electric", 1948, Date(Date::MARCH, 22, 1987));
addStock("ATT", "American Telephone & Telegraph", 20, Date(Date::MAY, 10, 1998));
printStocks();
searchStock("ATT");
removeStock("AAPL");
removeStock("AAPL");
searchStock("ATT");
removeStock("US:BA");
searchStock("GE");
removeStock("GE");
searchStock("ATT");
addStock("AAPL", "Apple Computer, Inc.", 2308, Date(Date::MAY, 1, 1980));
addStock("GE", "General Electric", 1948, Date(Date::MARCH, 22, 1987));
addStock("US:BA", "Boeing", 6407, Date(Date::DECEMBER, 14, 1993));
printStocks();
delete hm;
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
50957fcf36409706b3751ee8bb1f6e6a98c6f3e6 | 9dae91b21614b0cbfb7d7e89b7b3eb642fcc9a20 | /build-highlight-Desktop-Debug/moc_mainwindow.cpp | 918c8e54c79c4a0a2983b2e6299241eb56b6f0ee | [] | no_license | EdwardOwusuAdjei/QT-CPP-Texteditor | 34da13ef0c02629d7268dae922abe78a4a0bbb26 | a9dc9890324d8796ddb05edea9049484300aff8c | refs/heads/master | 2021-01-10T17:11:36.267587 | 2016-02-17T20:04:13 | 2016-02-17T20:04:13 | 51,951,161 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,636 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'mainwindow.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.5.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../highlight/mainwindow.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'mainwindow.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.5.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_MainWindow_t {
QByteArrayData data[10];
char stringdata0[77];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_MainWindow_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_MainWindow_t qt_meta_stringdata_MainWindow = {
{
QT_MOC_LITERAL(0, 0, 10), // "MainWindow"
QT_MOC_LITERAL(1, 11, 5), // "about"
QT_MOC_LITERAL(2, 17, 0), // ""
QT_MOC_LITERAL(3, 18, 7), // "newFile"
QT_MOC_LITERAL(4, 26, 8), // "openFile"
QT_MOC_LITERAL(5, 35, 4), // "path"
QT_MOC_LITERAL(6, 40, 4), // "open"
QT_MOC_LITERAL(7, 45, 4), // "save"
QT_MOC_LITERAL(8, 50, 6), // "saveAs"
QT_MOC_LITERAL(9, 57, 19) // "documentWasModified"
},
"MainWindow\0about\0\0newFile\0openFile\0"
"path\0open\0save\0saveAs\0documentWasModified"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_MainWindow[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
8, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 54, 2, 0x0a /* Public */,
3, 0, 55, 2, 0x0a /* Public */,
4, 1, 56, 2, 0x0a /* Public */,
4, 0, 59, 2, 0x2a /* Public | MethodCloned */,
6, 0, 60, 2, 0x0a /* Public */,
7, 0, 61, 2, 0x0a /* Public */,
8, 0, 62, 2, 0x0a /* Public */,
9, 0, 63, 2, 0x0a /* Public */,
// slots: parameters
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, QMetaType::QString, 5,
QMetaType::Void,
QMetaType::Void,
QMetaType::Bool,
QMetaType::Bool,
QMetaType::Void,
0 // eod
};
void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
MainWindow *_t = static_cast<MainWindow *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->about(); break;
case 1: _t->newFile(); break;
case 2: _t->openFile((*reinterpret_cast< const QString(*)>(_a[1]))); break;
case 3: _t->openFile(); break;
case 4: _t->open(); break;
case 5: { bool _r = _t->save();
if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; } break;
case 6: { bool _r = _t->saveAs();
if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; } break;
case 7: _t->documentWasModified(); break;
default: ;
}
}
}
const QMetaObject MainWindow::staticMetaObject = {
{ &QMainWindow::staticMetaObject, qt_meta_stringdata_MainWindow.data,
qt_meta_data_MainWindow, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *MainWindow::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *MainWindow::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_MainWindow.stringdata0))
return static_cast<void*>(const_cast< MainWindow*>(this));
return QMainWindow::qt_metacast(_clname);
}
int MainWindow::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 < 8)
qt_static_metacall(this, _c, _id, _a);
_id -= 8;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 8)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 8;
}
return _id;
}
QT_END_MOC_NAMESPACE
| [
"adjei.edward@yahoo.com"
] | adjei.edward@yahoo.com |
a35453bfa563d0e5c7e1e4e6dda44ba9503cd297 | 9620c8e0ca242f056af639a6501a3729e03fc13d | /VaporPlus/Postprocess.cpp | 2c34db8ce6d84f5d895a866889698bb1cda5e98b | [
"MIT"
] | permissive | clandrew/vapor | 2c405bf063e24bb6346b6b6eed94020ff9cbc680 | 500ef1ac43f7b72499914ccad2306037fc7d96b9 | refs/heads/master | 2021-06-20T23:54:32.338340 | 2021-02-02T06:14:41 | 2021-02-02T06:14:41 | 179,010,582 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,910 | cpp | #include "stdafx.h"
#include "Postprocess.h"
#include "CompiledShaders\PostprocessVS.hlsl.h"
#include "CompiledShaders\PostprocessPS.hlsl.h"
using namespace DirectX;
void Postprocess::CreatePostprocessPipelineState(ID3D12Device5* device)
{
ComPtr<ID3DBlob> vertexShader;
ComPtr<ID3DBlob> pixelShader;
UINT compileFlags = 0;
// Define the vertex input layout.
D3D12_INPUT_ELEMENT_DESC inputElementDescs[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }
};
// Describe and create the graphics pipeline state object (PSO).
D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {};
psoDesc.InputLayout = { inputElementDescs, _countof(inputElementDescs) };
psoDesc.pRootSignature = m_postprocessRootSignature.Get();
psoDesc.VS = CD3DX12_SHADER_BYTECODE((void*)g_pPostprocessVS, ARRAYSIZE(g_pPostprocessVS));
psoDesc.PS = CD3DX12_SHADER_BYTECODE((void*)g_pPostprocessPS, ARRAYSIZE(g_pPostprocessPS));
psoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);
psoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);
psoDesc.DepthStencilState.DepthEnable = FALSE;
psoDesc.DepthStencilState.StencilEnable = FALSE;
psoDesc.SampleMask = UINT_MAX;
psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
psoDesc.NumRenderTargets = 1;
psoDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
psoDesc.SampleDesc.Count = 1;
ThrowIfFailed(device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&m_postprocessPipelineState)));
}
void Postprocess::CreatePostprocessResources(ID3D12Device5* device)
{
{
struct PostprocessVertex
{
XMFLOAT3 position;
XMFLOAT2 uv;
};
// Define the geometry for a triangle.
PostprocessVertex triangleVertices[] =
{
{ { -1, 1, 0.0f },{ 0.0f, 0.0f } }, // Top left
{ { 1, 1, 0.0f },{ 1.0f, 0.0f } }, // Top right
{ { -1, -1, 0.0f },{ 0.0f, 1.0f } }, // Bottom left
{ { -1, -1, 0.0f },{ 0.0f, 1.0f } }, // Bottom left
{ { 1, 1, 0.0f },{ 1.0f, 0.0f } }, // Top right
{ { 1, -1, 0.0f },{ 1.0f, 1.0f } } // Bottom right
};
const UINT vertexBufferSize = sizeof(triangleVertices);
ThrowIfFailed(device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer(vertexBufferSize),
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(&m_postprocessVertexBuffer)));
// Copy the triangle data to the vertex buffer.
UINT8* pVertexDataBegin;
CD3DX12_RANGE readRange(0, 0); // We do not intend to read from this resource on the CPU.
ThrowIfFailed(m_postprocessVertexBuffer->Map(0, &readRange, reinterpret_cast<void**>(&pVertexDataBegin)));
memcpy(pVertexDataBegin, triangleVertices, sizeof(triangleVertices));
m_postprocessVertexBuffer->Unmap(0, nullptr);
// Initialize the vertex buffer view.
m_postprocessVertexBufferView.BufferLocation = m_postprocessVertexBuffer->GetGPUVirtualAddress();
m_postprocessVertexBufferView.StrideInBytes = sizeof(PostprocessVertex);
m_postprocessVertexBufferView.SizeInBytes = vertexBufferSize;
}
// Descriptors:
// - Raytracing output
// - TV noise
m_postprocessSRVHeap.Initialize(device, 2);
}
void Postprocess::CreateRootSignature(ID3D12Device5* device)
{
CD3DX12_DESCRIPTOR_RANGE srvTableRange[1]{};
srvTableRange[0].Init(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 2, 0, 0);
CD3DX12_DESCRIPTOR_RANGE samplerTableRange[1]{};
samplerTableRange[0].Init(D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 1, 0);
CD3DX12_ROOT_PARAMETER rootParameters[3];
rootParameters[0].InitAsDescriptorTable(ARRAYSIZE(srvTableRange), srvTableRange, D3D12_SHADER_VISIBILITY_PIXEL);
rootParameters[1].InitAsConstants(2, 0);
rootParameters[2].InitAsDescriptorTable(ARRAYSIZE(samplerTableRange), samplerTableRange, D3D12_SHADER_VISIBILITY_PIXEL);
CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc(ARRAYSIZE(rootParameters), rootParameters);
rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
SerializeAndCreateRootSignature(device, rootSignatureDesc, &m_postprocessRootSignature);
}
void Postprocess::CreateRaytracedInputUAV(ID3D12Resource* resource)
{
m_raytracingOutputResourceUAVDescriptorHeapIndexDuringPostprocess = m_postprocessSRVHeap.CreateTextureUAV(resource);
}
ID3D12PipelineState* Postprocess::GetPipelineState() const
{
return m_postprocessPipelineState.Get();
}
ID3D12RootSignature* Postprocess::GetRootSignature() const
{
return m_postprocessRootSignature.Get();
}
DescriptorHeapWrapper* Postprocess::GetSRVHeap()
{
return &m_postprocessSRVHeap;
}
ID3D12DescriptorHeap* Postprocess::GetSRVHeapResource() const
{
return m_postprocessSRVHeap.GetResource();
}
D3D12_VERTEX_BUFFER_VIEW const* Postprocess::GetVertexBufferView() const
{
return &m_postprocessVertexBufferView;
} | [
"cmlandrews@gmail.com"
] | cmlandrews@gmail.com |
7c36be4bcce060d8be11af1bcc78fcda0214bc82 | 8eae6774231f4a313e7aa8ac30d5c678dc1c2a42 | /SWUST OJ/0290.cpp | 04a53fc5935e060d653cd39d27bfa0f54b076aff | [
"MIT"
] | permissive | windcry1/My-ACM-ICPC | c97b203e5e54d355168ed14db888f4a1b3e6c363 | b85b1c83b72c6b51731dae946a0df57c31d3e7a1 | refs/heads/master | 2021-09-06T20:47:56.525749 | 2021-08-22T14:06:10 | 2021-08-22T14:06:10 | 231,622,263 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 954 | cpp | //Author:LanceYu
#include<iostream>
#include<string>
#include<cstring>
#include<cstdio>
#include<fstream>
#include<iosfwd>
#include<sstream>
#include<fstream>
#include<cwchar>
#include<iomanip>
#include<ostream>
#include<vector>
#include<cstdlib>
#include<queue>
#include<set>
#include<ctime>
#include<algorithm>
#include<complex>
#include<cmath>
#include<valarray>
#include<bitset>
#include<iterator>
#define ll long long
using namespace std;
const double clf=1e-8;
//const double e=2.718281828;
const double PI=3.141592653589793;
const int MMAX=2147483647;
const int mod=1e9+7;
//priority_queue<int>p;
//priority_queue<int,vector<int>,greater<int> >pq;
int a[11],m,k;
int f(int x)
{
int num=0;
if(x<10)
return x;
if(x>=10)
{
for(int i=0;i<10;i++)
{
num+=a[i]*f(x-i-1);
num%=m;
}
}
return num;
}
int main()
{
while(scanf("%d%d",&k,&m)!=EOF)
{
for(int i=0;i<10;i++)
scanf("%d",&a[i]);
printf("%d\n",f(k)%m);
}
return 0;
}
| [
"lanceyu120@gmail.com"
] | lanceyu120@gmail.com |
ec8a4915df69c921e2b1162ee4430ffaf040bf5b | ba9322f7db02d797f6984298d892f74768193dcf | /cloudwf/src/model/ShopDeleteRequest.cc | 34d953123f9587b4a894922bf819049e38aee872 | [
"Apache-2.0"
] | permissive | sdk-team/aliyun-openapi-cpp-sdk | e27f91996b3bad9226c86f74475b5a1a91806861 | a27fc0000a2b061cd10df09cbe4fff9db4a7c707 | refs/heads/master | 2022-08-21T18:25:53.080066 | 2022-07-25T10:01:05 | 2022-07-25T10:01:05 | 183,356,893 | 3 | 0 | null | 2019-04-25T04:34:29 | 2019-04-25T04:34:28 | null | UTF-8 | C++ | false | false | 1,299 | cc | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/cloudwf/model/ShopDeleteRequest.h>
using AlibabaCloud::Cloudwf::Model::ShopDeleteRequest;
ShopDeleteRequest::ShopDeleteRequest() :
RpcServiceRequest("cloudwf", "2017-03-28", "ShopDelete")
{}
ShopDeleteRequest::~ShopDeleteRequest()
{}
std::string ShopDeleteRequest::getAccessKeyId()const
{
return accessKeyId_;
}
void ShopDeleteRequest::setAccessKeyId(const std::string& accessKeyId)
{
accessKeyId_ = accessKeyId;
setParameter("AccessKeyId", accessKeyId);
}
long ShopDeleteRequest::getSid()const
{
return sid_;
}
void ShopDeleteRequest::setSid(long sid)
{
sid_ = sid;
setParameter("Sid", std::to_string(sid));
}
| [
"haowei.yao@alibaba-inc.com"
] | haowei.yao@alibaba-inc.com |
860ceca0d80e823d3b1780d4b556b710dd47f961 | aad6b08ee56c2760b207d562f16be0a5bb8e3e2a | /tags/Galekid1.0/WebKit/OrigynWebBrowser/WebCoreSupport/WebInspectorClient.cpp | 5a1bf13f495d0c7a351c7b9a43a9268eff7bb9e3 | [
"BSD-3-Clause"
] | permissive | Chengjian-Tang/owb-mirror | 5ffd127685d06f2c8e00832c63cd235bec63f753 | b48392a07a2f760bfc273d8d8b80e8d3f43b6b55 | refs/heads/master | 2021-05-27T02:09:03.654458 | 2010-06-23T11:10:12 | 2010-06-23T11:10:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,022 | cpp | /*
* Copyright (C) 2008 Pleyo. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Pleyo nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY PLEYO AND ITS 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 PLEYO OR ITS 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 "config.h"
#include "WebInspectorClient.h"
#include "NotImplemented.h"
#include "PlatformString.h"
#include "WebView.h"
using namespace WebCore;
WebInspectorClient::WebInspectorClient(WebView *view)
:m_webView(view)
{
}
WebInspectorClient::~WebInspectorClient()
{
}
void WebInspectorClient::inspectorDestroyed()
{
delete this;
}
Page* WebInspectorClient::createPage()
{
notImplemented();
return 0;
}
String WebInspectorClient::localizedStringsURL()
{
notImplemented();
return String();
}
void WebInspectorClient::showWindow()
{
notImplemented();
}
void WebInspectorClient::closeWindow()
{
notImplemented();
}
void WebInspectorClient::attachWindow()
{
notImplemented();
}
void WebInspectorClient::detachWindow()
{
notImplemented();
}
void WebInspectorClient::setAttachedWindowHeight(unsigned height)
{
notImplemented();
}
void WebInspectorClient::highlight(Node* node)
{
notImplemented();
}
void WebInspectorClient::hideHighlight()
{
notImplemented();
}
void WebInspectorClient::inspectedURLChanged(const String&)
{
notImplemented();
}
void WebInspectorClient::populateSetting(const WebCore::String& key, WebCore::InspectorController::Setting&)
{
notImplemented();
}
void WebInspectorClient::storeSetting(const WebCore::String& key, const WebCore::InspectorController::Setting&)
{
notImplemented();
}
void WebInspectorClient::removeSetting(const WebCore::String& key)
{
notImplemented();
}
| [
"mbensi@a3cd4a6d-042f-0410-9b26-d8d12826d3fb"
] | mbensi@a3cd4a6d-042f-0410-9b26-d8d12826d3fb |
914efa233915317d27cbc7660e612f50202aeabc | df295d7ec2064c527d7c47f7dfd3a6364c7a9cbf | /spoj/SUBXOR.cpp | 79547a043faf02bbe2dc27ab8ac037a73985e093 | [] | no_license | Shahraaz/CP_S4 | 7df25e4b764f0067ce51600e76923a7ed1b6fb82 | b1ae31fa40028ab878f27b4435bfe0d356b70df0 | refs/heads/master | 2020-05-24T22:08:55.990592 | 2019-07-15T23:42:49 | 2019-07-15T23:42:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,052 | cpp | //Optimise
#include <bits/stdc++.h>
using namespace std;
#define multitest 1
// #define Debug 1
#ifdef Debug
#define db(...) ZZ(#__VA_ARGS__, __VA_ARGS__);
template <typename Arg1>
void ZZ(const char *name, Arg1 &&arg1)
{
std::cerr << name << " = " << arg1 << endl;
}
template <typename Arg1, typename... Args>
void ZZ(const char *names, Arg1 &&arg1, Args &&... args)
{
const char *comma = strchr(names + 1, ',');
std::cerr.write(names, comma - names) << " = " << arg1;
ZZ(comma, args...);
}
#else
#define db(...)
#endif
typedef long long ll;
typedef long double ld;
#define f first
#define s second
#define pb push_back
const long long mod = 1000000007;
struct Trie
{
int lc, rc;
Trie *left, *right;
Trie()
{
lc = rc = 0;
left = right = NULL;
}
};
int maxBits = 20;
Trie *insert(Trie *curr, int level, int N)
{
if (level == -1)
return curr;
int b = N & (1 << level);
if (b)
{
curr->rc++;
if (curr->right == NULL)
curr->right = new Trie;
curr->right = insert(curr->right, level - 1, N);
}
else
{
curr->lc++;
if (curr->left == NULL)
curr->left = new Trie;
curr->left = insert(curr->left, level - 1, N);
}
return curr;
}
int query(Trie *curr, int level, int N, int K)
{
if (level == -1 || curr == NULL)
return 0;
bool bitN = N & (1 << level);
bool bitK = K & (1 << level);
if (bitK)
{
if (bitN)
return curr->rc + query(curr->left, level - 1, N, K);
else
return curr->lc + query(curr->right, level - 1, N, K);
}
else
{
if (bitN)
return query(curr->right, level - 1, N, K);
else
return query(curr->left, level - 1, N, K);
}
}
void solve()
{
int x, n, k;
cin >> n >> k;
int p;
p = 0;
ll ans = 0;
Trie *root = new Trie;
root = insert(root, maxBits, 0);
for (int i = 0; i < n; ++i)
{
cin >> x;
p = p ^ x;
ans += query(root, maxBits, p, k);
root = insert(root, maxBits, p);
}
cout << ans << '\n';
}
int main()
{
#ifndef Debug
ios_base::sync_with_stdio(0);
cin.tie(0);
#endif
int t = 1;
#ifdef multitest
cin >> t;
#endif
while (t--)
solve();
return 0;
} | [
"shahraazhussain@gmail.com"
] | shahraazhussain@gmail.com |
54807fb81fc61e7ae37fa6d16e94bfc161436349 | d426bcbf5211e6d499d8bc874f88be43d9c4570a | /SoftwareController/Log.h | 3676173e8a5b9b1cdbf2f09bb2c8aecf292ecf1a | [] | no_license | i-Seiza/SoftwareController | a3f69c927552e10b0118367f481dcc1839827dcd | 6bf147b54b1c47c02e95587d8422b17aa26de532 | refs/heads/master | 2021-01-21T05:09:38.845719 | 2015-08-12T07:25:05 | 2015-08-12T07:25:05 | 40,586,234 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 246 | h | #pragma once
class CLog
{
public:
CLog(void);
~CLog(void);
private:
bool IsWrite();
public:
void Write( const std::string sLog );
void Write( const std::string sClass, const int eType, const std::string sContents );
};
| [
"ikuko.masuda@optim.co.jp"
] | ikuko.masuda@optim.co.jp |
c848312d03a5798637fe80c09e1c61c919f5de31 | b3eb8ce1ba90537837af172fd1d96a3f560769e1 | /Sources/Helpers.h | 92ed67c6deae0974b41a7d4b174638a7e3601d44 | [] | no_license | patternspandemic/KoreC | cc0a129bc7043d9d9f4144420bb1fb78e6538701 | 331a0793b0a881f6d26d7945a608e03730c2b292 | refs/heads/master | 2021-06-30T00:07:29.062810 | 2021-05-18T00:18:20 | 2021-05-18T00:18:20 | 96,575,220 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 406 | h | #include <Kore/pch.h>
#include <Kore/Graphics4/Shader.h>
#include <Kore/Graphics4/Texture.h>
/*
namespace KoreC {
class WTextureUnit4 {
public:
WTextureUnit4(Kore::Graphics4::TextureUnit unit);
Kore::Graphics4::TextureUnit unit;
};
class WConstantLocation4 {
public:
WConstantLocation4(Kore::Graphics4::ConstantLocation location);
Kore::Graphics4::ConstantLocation location;
};
}
*/ | [
"patternspandemic@live.com"
] | patternspandemic@live.com |
c904c294c25b136ae4cca67bfa7d611138ea963d | 7785cc65f7adbb079fc31458a7ddd9a7a7a55104 | /tic_tac_toe_qt/general_handler.cpp | 69655ad107fea6b75d17548f62960d860a3b4a53 | [] | no_license | rodrigovb96/tic_tac_toe | 7c916e2fce3e318ebcbf71bfe09b250a032a99f0 | e370c09909c72575f495f71dffeb852ddd096086 | refs/heads/master | 2021-01-22T16:04:39.611793 | 2018-05-10T19:37:06 | 2018-05-10T19:37:06 | 102,387,396 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,197 | cpp | #include "general_handler.h"
General_Handler::General_Handler()
{
// Window setup
window.create(VideoMode(600,600),"Tic-Tac-Toe AI",Style::Close);
window.setFramerateLimit(30);
// loading text font
if(!font.loadFromFile("../files/font.TTF"))
std::cerr << "ERROR LOADING TEXT FONT!" << '\n';
else
init_txt.setFont(font);
if(!bg_texture.loadFromFile("../files/images/background.png"))
std::cerr << "ERROR LOADING BACKGROUND IMAGE!" << '\n';
else
background.setTexture(bg_texture);
// Initial Text
// =====
init_txt.setString("\t\tTIC-TAC-TOE AI!!\nChoose your mark('X'or'O'):");
init_txt.setCharacterSize(18);
init_txt.setColor(Color::Red); // SFML < 2.3 (DEPRECATED)
//init_txt.setFillColor(Color::Red); <- SFML 2.4.2
init_txt.setOrigin(-100,-100);
init_txt.setPosition(50,10);
// =====
// Loading all the necessary textures
textures['x'].loadFromFile("../files/images/x_mark.png");
textures['o'].loadFromFile("../files/images/o_mark.png");
textures[' '].loadFromFile("../files/images/clear_img.png");
// Loading input keys
input_key[0] = Keyboard::Q;
input_key[1] = Keyboard::W;
input_key[2] = Keyboard::E;
input_key[3] = Keyboard::A;
input_key[4] = Keyboard::S;
input_key[5] = Keyboard::D;
input_key[6] = Keyboard::Z;
input_key[7] = Keyboard::X;
input_key[8] = Keyboard::C;
// Positions of the sprites(s) in the table
/*
s|s|s
s|s|s
s|s|s
*/
sprite_board[0].setOrigin(10,10);
sprite_board[0].setPosition(20,10);
sprite_board[1].setOrigin(-100,10);
sprite_board[1].setPosition(115,10);
sprite_board[2].setOrigin(-200,10);
sprite_board[2].setPosition(215,10);
sprite_board[3].setOrigin(10,-100);
sprite_board[3].setPosition(10,110);
sprite_board[4].setOrigin(-100,-100);
sprite_board[4].setPosition(115,110);
sprite_board[5].setOrigin(-200,-100);
sprite_board[5].setPosition(215,110);
sprite_board[6].setOrigin(10,-200);
sprite_board[6].setPosition(10,210);
sprite_board[7].setOrigin(-100,-200);
sprite_board[7].setPosition(115,210);
sprite_board[8].setOrigin(-200,-200);
sprite_board[8].setPosition(215,210);
}
// while the window is open all the process is made
// input and output
void General_Handler::main_loop(GameState::Mode game_mode,char mark)
{
board.set_game_mode(game_mode);
board.set_player_mark(mark);
while(window.isOpen())
{
Event evt;
while(window.pollEvent(evt))
{
//close the window if escape key is pressed
if(evt.type == Event::Closed || (evt.type == Event::KeyPressed && (evt.key.code == Keyboard::Escape)))
window.close();
// if the game is not over(has no winner and its not a draw)
if((!board.game_over() && !board.p2_turn() ) || (!board.game_over() && board.game_mode() == GameState::Mode::PVP_GAME ))
input_handler(evt);
else if( !board.game_over() && board.p2_turn())
ai_input_handler(computer(board));
else if(evt.type == Event::KeyPressed && evt.key.code == Keyboard::Num2)
{// reset the game
board.clear_board();
clear_graphics();
game_over = false;
}
else
game_over = true;
}
window.clear();
window.draw(background);
for(auto& sprite : sprite_board)
window.draw(sprite);
window.display();
}
}
// handles all the user inputs
void General_Handler::input_handler(Event input_evt)
{
if(input_evt.type == Event::KeyPressed)
{
for(unsigned int i = 0; i < input_key.size(); i++)
if(input_evt.key.code == input_key[i] && !board.is_pos_used(i))
{
mark_in_board = board.put_in_pos(i);
sprite_board[i].setTexture(textures[mark_in_board]);
}
}
}
// handle all the AI inputs
void General_Handler::ai_input_handler(int pos)
{
mark_in_board = ' ';
mark_in_board = board.put_in_pos(pos);
sprite_board[pos].setTexture(textures[mark_in_board]);
}
// clear all the graphics in the sprite_board
void General_Handler::clear_graphics()
{
for(int i = 0; i < 9; i++)
sprite_board[i].setTexture(textures[' ']);
}
| [
"rodrigovalente1996@gmail.com"
] | rodrigovalente1996@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.