blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2 values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905 values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 10.4M | extension stringclasses 115 values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0abbedd51fa5c47045289baf464ba3ec2e02177d | f72ca04c390b6ea4d49a8e53262288738ad02ef0 | /xr3core/h/xr/debug.hpp | f69dbfc0ae5124c6332d17432ed958c6a3ea14f7 | [
"BSD-2-Clause"
] | permissive | zyndor/xrhodes | cae4c0b12995cb206bfb46b755241d57b40489af | 995618bc82dc8e562c9ae1e6afc2ac795aeb517b | refs/heads/master | 2022-07-28T04:22:15.117802 | 2022-07-10T16:57:09 | 2022-07-10T16:57:09 | 153,730,253 | 9 | 0 | BSD-2-Clause | 2021-02-19T15:39:29 | 2018-10-19T05:20:10 | C++ | UTF-8 | C++ | false | false | 5,379 | hpp | #ifndef XR_DEBUG_HPP
#define XR_DEBUG_HPP
//==============================================================================
//
// XRhodes
//
// copyright (c) Gyorgy Straub. All rights reserved.
//
// License: https://github.com/zyndor/xrhodes#License-bsd-2-clause
//
//==============================================================================
#include "platform.hpp"
#include <cstdio>
//==============================================================================
///@brief Printing to stdout followed by explicit flush.
#define XR_RAWTRACE(format) do { printf format; fflush(stdout); } while(0)
//==============================================================================
///@brief Binary debugging aid - wrap call to help determine whether it causes a
/// crash / exception.
#define XR_SURVIVE(call) do { XR_RAWTRACE(("SURVIVE: %s (%s:%d)\n", #call, __FILE__, __LINE__)); call; printf("OK.\n"); } while(0)
//==============================================================================
#if !defined(XR_DEBUG) && defined(XR_DEBUG_PERFORMANCE)
#define XR_DEBUG
#endif
//==============================================================================
#if defined(XR_DEBUG)
#define XR_DEBUG_ONLY(op) op
#else
#define XR_DEBUG_ONLY(op)
#endif
//==============================================================================
///@brief If the given channel is enabled, it passes the given @a channel and
/// formattable message to the trace handler.
///@note msg must be a parenthesised, C-style message format + parameters.
#define XR_TRACE(channel, msg) XR_DEBUG_ONLY(if(xr::detail::DebugChannel::IsEnabled(#channel)){ xr::detail::DebugChannel(#channel).Trace msg; })
//==============================================================================
///@brief If @a cond evaluates to true and the given channel is enabled, it
/// passes the given @a channel and formattable message to the trace handler.
///@note msg must be a parenthesised, C-style message format + parameters.
#define XR_TRACEIF(channel, cond, msg) XR_DEBUG_ONLY(if((cond) && xr::detail::DebugChannel::IsEnabled(#channel)){ xr::detail::DebugChannel(#channel).Trace msg; })
//==============================================================================
#define XR_DETAIL_ASSERT_STATE_INIT static char xrDebugIsAssertActive = 1;
#define XR_DETAIL_ASSERT_STATE_CHECK(c) (xrDebugIsAssertActive == 1 && xr::detail::DebugChannel::IsEnabled(c))
#define XR_DETAIL_ASSERT_STATE_DISABLE xrDebugIsAssertActive = 0
//==============================================================================
#if defined(XR_DEBUG)
#if defined(XR_COMPILER_MSVC)
#define XR_TRAP __debugbreak();
#elif defined(XR_CPU_ARM)
#define XR_TRAP __builtin_trap();
#else
#define XR_TRAP __asm__ ("int $3");
#endif
#else
#define XR_TRAP
#endif
///@brief If the condition evaluates to false and the channel is enabled, it
/// passes the given channel and formattable message to the assert handler.
///@note msg must be a parenthesised, C-style message format + parameters.
#define XR_ASSERTMSG(channel, cond, msg)\
XR_DEBUG_ONLY({ XR_DETAIL_ASSERT_STATE_INIT if (!(cond) && XR_DETAIL_ASSERT_STATE_CHECK(#channel)){\
switch(xr::detail::DebugChannel(#channel).Assert msg) {\
case xr::AssertAction::Break: XR_TRAP break;\
case xr::AssertAction::Continue: break;\
case xr::AssertAction::Ignore: XR_DETAIL_ASSERT_STATE_DISABLE; break;\
case xr::AssertAction::IgnoreChannel: xr::detail::DebugChannel::SetEnabled(#channel, false); break;\
}}})
//==============================================================================
///@brief If the condition evaluates to false and the channel is enabled, it
/// passes the given channel and default message specifying the location of the
/// assert, to the assert handler.
#define XR_ASSERT(channel, cond) XR_ASSERTMSG(channel, cond, ("Assertion failed: %s (%s:%d)", #cond, __FILE__, __LINE__))
//==============================================================================
#define XR_ERROR(msg)\
{\
XR_RAWTRACE(msg);\
XR_TRAP\
}\
namespace xr
{
//==============================================================================
enum class AssertAction
{
Break,
Continue,
Ignore,
IgnoreChannel,
};
using TraceHandler = void(*)(char const* channel, char const* message);
using AssertHandler = AssertAction(*)(char const* channel, char const* message);
///@brief Sets the function that a trace channel and formatted message are passed
/// to, once the channel is checked and found active. Passing nullptr as @a handler
/// will set the default handler, which writes to stdout.
void SetTraceHandler(TraceHandler handler);
///@brief Sets the function which an assert channel and formatted message are
/// passed to, once the channel is checked and found active. Passing nullptr as
/// @a handler will set the default handler.
void SetAssertHandler(AssertHandler handler);
namespace detail
{
//==============================================================================
struct DebugChannel
{
static void SetEnabled(char const* name, bool state);
static bool IsEnabled(char const* name);
DebugChannel(char const* name);
void Trace(char const* format, ...);
AssertAction Assert(char const* format, ...);
private:
#if defined(XR_DEBUG)
char const* m_name;
#endif
};
} // detail
} // xr
#endif //XR_DEBUG_HPP
| [
"gyorgy@nuclearheart.com"
] | gyorgy@nuclearheart.com |
7357d5d6b1a26c8e34981ae641148198e4e0f388 | 8fea82d0c844357b63bfe6950fa03474cd8f10d5 | /Tutorial/GacUI_Controls/TextEditor/UI/Source/AboutWindow.cpp | 9f0f9b30c0a434cf9296a2196f9dfa68005e8352 | [] | no_license | wuzeen/Release | 2a869d60b2452009b3267894a9ec35890adb8ddb | 85478ae79719d4716e22041016ddd1c90d977ad4 | refs/heads/master | 2021-07-06T06:09:21.255447 | 2017-09-28T15:33:10 | 2017-09-28T15:33:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,511 | cpp | /***********************************************************************
!!!!!! DO NOT MODIFY !!!!!!
GacGen.exe Resource.xml
This file is generated by Workflow compiler
https://github.com/vczh-libraries
***********************************************************************/
#include "Demo.h"
/* CodePack:BeginIgnore() */
#ifndef VCZH_DEBUG_NO_REFLECTION
/* CodePack:ConditionOff(VCZH_DEBUG_NO_REFLECTION, DemoReflection.h) */
#include "DemoReflection.h"
#endif
/* CodePack:EndIgnore() */
#if defined( _MSC_VER)
#pragma warning(push)
#pragma warning(disable:4250)
#elif defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wparentheses-equality"
#elif defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wparentheses-equality"
#endif
#define GLOBAL_SYMBOL ::vl_workflow_global::Demo::
#define GLOBAL_NAME ::vl_workflow_global::Demo::Instance().
#define GLOBAL_OBJ &::vl_workflow_global::Demo::Instance()
#define USERIMPL(...)
/***********************************************************************
Class (::demo::AboutWindow)
***********************************************************************/
namespace demo
{
USERIMPL(/* ::demo::AboutWindow */)
void AboutWindow::documentLabel_ActiveHyperlinkExecuted(::vl::presentation::compositions::GuiGraphicsComposition* sender, ::vl::presentation::compositions::GuiEventArgs* arguments)
{
OpenUrl(documentLabel->GetActiveHyperlinkReference());
}
AboutWindow::AboutWindow()
: ::vl::presentation::controls::GuiWindow(::vl::__vwsn::This(::vl::presentation::theme::GetCurrentTheme())->CreateWindowStyle())
{
auto __vwsn_resource_ = ::vl::__vwsn::This(::vl::presentation::GetResourceManager())->GetResourceFromClassName(::vl::WString(L"demo::AboutWindow", false));
auto __vwsn_resolver_ = ::vl::Ptr<::vl::presentation::GuiResourcePathResolver>(new ::vl::presentation::GuiResourcePathResolver(__vwsn_resource_, ::vl::__vwsn::This(__vwsn_resource_.Obj())->GetWorkingDirectory()));
::vl::__vwsn::This(this)->SetResourceResolver(__vwsn_resolver_);
::vl::__vwsn::This(this)->__vwsn_initialize_instance_(this);
}
AboutWindow::~AboutWindow()
{
this->FinalizeInstanceRecursively(static_cast<::vl::presentation::controls::GuiControlHost*>(this));
}
}
#undef GLOBAL_SYMBOL
#undef GLOBAL_NAME
#undef GLOBAL_OBJ
#undef USERIMPL
#if defined( _MSC_VER)
#pragma warning(pop)
#elif defined(__GNUC__)
#pragma GCC diagnostic pop
#elif defined(__clang__)
#pragma clang diagnostic pop
#endif
| [
"vczh@163.com"
] | vczh@163.com |
a3753bc5bca7feac377556b35c046cd0c69a5f4f | 429113ad9528c7e5391fb0e9dfaaa6180db086d1 | /C++/PR5/Vector.cpp | a3dd8cd118e05612b554fb6faf52fe15dfb53a22 | [] | no_license | dbarashev/SPbAU | b868d601ba2ff64a9e2a4bbb1b39128eef5932a9 | f524896afe779f3e2d40aa58b9175dd7f54bd2bd | refs/heads/master | 2020-05-25T14:17:50.724756 | 2013-11-22T21:41:33 | 2013-11-22T21:41:33 | 14,721,313 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,412 | cpp | #include "Vector.hpp"
#include <cstdio>
#include <cassert>
#include <algorithm>
Vector::Vector(size_t initialSize, int value) :
increase_factor(2.0),
size(initialSize),
capacity(std::max(initialSize, 16ul)),
data(new int[capacity])
{
std::fill(data, data + size, value);
}
Vector::Vector(Vector const &other) :
increase_factor(2.0),
size(other.size),
capacity(other.capacity),
data(new int[capacity])
{
std::copy(other.data, other.data + size, data);
}
Vector::~Vector()
{
delete[] data;
}
Vector& Vector::operator=(Vector const& other)
{
if (this != &other)
Vector(other).swap(*this);
return *this;
}
void Vector::add(int value)
{
reserve(size + 1);
data[size++] = value;
}
void Vector::reserve(size_t newCapacity)
{
if (newCapacity > capacity)
{
newCapacity = std::max(newCapacity, (size_t)(capacity * increase_factor));
int *temp = new int[newCapacity];
std::copy(data, data + size, temp);
delete[] data;
data = temp;
capacity = newCapacity;
}
}
void Vector::resize(size_t newSize)
{
reserve(newSize);
std::fill(data + size, data + newSize, 0u);
size = newSize;
}
int& Vector::get(size_t i)
{
return data[i];
}
int Vector::get(size_t i) const
{
return data[i];
}
size_t Vector::get_size() const
{
return size;
}
void Vector::swap(Vector &other)
{
std::swap(size, other.size);
std::swap(capacity, other.capacity);
std::swap(data, other.data);
}
| [
"doxxerACM@gmail.com"
] | doxxerACM@gmail.com |
7e99a1f7a2b526cb065290b231a222b37fd5e3df | b1ecf5efbcacbb274898e29e7ee542e59ef93916 | /Graph prblm/Graph Merathon/Longest path in a tree .cpp | a1fbc23d8adb1355fe48ef2671427ed7dcf4dc03 | [] | no_license | abufarhad/Programming | 92160c224578be116b2bb1e957ea105640a83ee6 | 282bf4df6c47817cb5d96ccee7dc2953438e8e11 | refs/heads/master | 2021-06-16T17:07:14.095691 | 2021-03-23T17:22:13 | 2021-03-23T17:22:13 | 180,426,830 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 971 | cpp | #include<bits/stdc++.h>
#include<stdio.h>
using namespace std;
#define ll long long
#define scl(n) scanf("%lld", &n)
#define fr(i,n) for (ll i=0;i<n;i++)
#define fr1(i,n) for(ll i=1;i<=n;i++)
#define pfl(x) printf("%lld\n",x)
#define pb push_back
bool vis[10005 ];
vector<ll>g[10005];
ll dist[10005];
ll dfs( ll n, ll d )
{
vis[n]=1, dist[n]=d;
fr(i, g[n].size())if(!vis[ g[n][i] ] )dfs(g[n][i], d+1 );
}
int main()
{
ll m,n,i,k,l,t,r,cnt=0,a,b;
ll node, edge;
cin>>node;
fr(i,node-1)
{
cin>>a>>b;
g[a].pb(b);
g[b].pb(a);
}
dfs(1,0);
ll start_node=0, max_dist=0;
fr1(i,node)if(dist[i]>dist[start_node ] )start_node=i;
memset(vis, 0, sizeof(vis) );
dfs(start_node, 0);
fr1(i, node)max_dist=max( max_dist, dist[i] );
pfl(max_dist);
}
| [
"abufarhad15@gmail.com"
] | abufarhad15@gmail.com |
eee0a6a3bd59eecb91307b35e2d93433f723ebf1 | 31f75edeef8c2f825f02c608bd63d427dfa1e147 | /Homework4/ofxRollercoaster/src/ofApp.h | 5e9e98d1eb1d946dfea3f2c2deb333687df9b10f | [] | no_license | jeffsetter/Music256a | 23c2b2945fe50e5d9fef2d196741fe56f5f3a2f0 | 12c135fa87744794a82648d22418449a4617b8ad | refs/heads/master | 2020-12-02T10:14:05.839668 | 2016-12-10T03:34:57 | 2016-12-10T03:34:57 | 70,084,295 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,237 | h | #pragma once
#include "ofMain.h"
#include "sizeDefs.h"
#include "objects.h"
enum Direction {
Straight, Up, Down, Right, Left
};
typedef struct {
ofBoxPrimitive hBar;
ofBoxPrimitive vBar;
void setup() {
hBar.setHeight(20);
hBar.setWidth(RAIL_OFFSET * 2);
hBar.setDepth(70);
vBar.setHeight(50);
vBar.setWidth(20);
vBar.setDepth(20);
}
} Strut;
class ofApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
void keyPressed(int key);
void keyReleased(int key);
void mouseMoved(int x, int y );
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void mouseEntered(int x, int y);
void mouseExited(int x, int y);
void windowResized(int w, int h);
void dragEvent(ofDragInfo dragInfo);
void gotMessage(ofMessage msg);
ofPlanePrimitive groundPlane;
ofEasyCam cam;
ofLight light;
ofSoundPlayer sp[5];
string audioFiles[5] = { "rollercoaster.mp3", "tree.mp3", "cloud.mp3", "seagull.mp3", "lake.mp3" };
ofSoundPlayer* audioPlayers[5] = { &sp[0], &sp[1], &sp[2], &sp[3], &sp[4] };
float globalGain = 1;
float userTilt[3];
float userRot[3];
float userPos[3];
Direction userDir;
float userSpeed;
// objects for the rollercoaster
ofCylinderPrimitive railRight, railLeft, railFutureRight, railFutureLeft;
ofCylinderPrimitive *rails[4] = { &railRight, &railLeft, &railFutureRight, &railFutureLeft };
ofMesh railFutureMeshRight;
ofMesh railFutureMeshLeft;
ofBoxPrimitive middleRail;
// methods for rollercoaster struts
Strut strut;
void drawStrut();
float strutStart;
// create objects
Cloud cloud;
Tree tree;
Grass grass;
Pond pond;
Bird bird;
void audioOut(float * input, int bufferSize, int nChannels);
ofSoundStream soundStream;
float pan = 0;
int sampleRate, nInputChans;
bool bNoise = true;
float volume;
vector <float> lAudio;
vector <float> rAudio;
//------------------- for the simple sine wave synthesis
float targetFrequency;
float phase;
float phaseAdder;
float phaseAdderTarget;
void audioSetup();
float **audioBuffer; // The 2d audio buffer that Faust wants to work with
ofMutex myMutex;
};
| [
"setter@stanford.edu"
] | setter@stanford.edu |
46cc23906a0eb4de54b60207c6ae9018ef4cb275 | 18bb98bfd36f63fd3b6f3443fc3f04b0a9228a59 | /UserListCtrl.h | e563eeed70a545252ae26cb794dd465ef4ab121e | [] | no_license | anzhsoft/Readings | c0909b540957aab9a8172a300d31e4c8c445dd56 | 72795df2556273ac168e8729ecae87b25e46d6c1 | refs/heads/master | 2020-04-06T05:21:43.719490 | 2014-01-04T11:18:39 | 2014-01-04T11:18:39 | 15,630,264 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,453 | h | #if !defined(AFX_USERLISTCTRL_H__9B235BBA_42CB_4BC3_A0A8_411BB5852096__INCLUDED_)
#define AFX_USERLISTCTRL_H__9B235BBA_42CB_4BC3_A0A8_411BB5852096__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// UserListCtrl.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CUserListCtrl window
class CUserListCtrl : public CListCtrl
{
// Construction
public:
CUserListCtrl();
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CUserListCtrl)
virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);
//}}AFX_VIRTUAL
// Implementation
public:
void RemoveImage(int nItem);
void DeleteImageList();
BOOL CreateImageList();
BOOL SetImage(UINT icon, int nItem);
void Draw(CDC* pDC, int nItem, CRect rect, COLORREF txtColor, COLORREF bgColor);
virtual ~CUserListCtrl();
// Generated message map functions
protected:
//{{AFX_MSG(CUserListCtrl)
afx_msg void MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct);
afx_msg void OnDeleteitem(NMHDR* pNMHDR, LRESULT* pResult);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_USERLISTCTRL_H__9B235BBA_42CB_4BC3_A0A8_411BB5852096__INCLUDED_)
| [
"anzhsoft@gmail.com"
] | anzhsoft@gmail.com |
42b7a7be074ed55f923b8bf50cdad74e31275729 | 26d5c0a2cc368c48e3ae82ddbe47969154066556 | /c++/practise/3_practise/2_29_for.cpp | ac75dd0c72f5f3d8f8df886395b8a142d53d480a | [] | no_license | liujuan525/fudan | b793a51ce31d59822062c3597717dead91ef134c | 6e7487a7dea2a32c345990fadbd4c010cfb0ee40 | refs/heads/master | 2023-06-05T17:49:18.676965 | 2021-06-23T08:14:19 | 2021-06-23T08:14:19 | 254,825,874 | 1 | 0 | null | 2020-05-31T12:50:05 | 2020-04-11T08:37:37 | C++ | UTF-8 | C++ | false | false | 682 | cpp | // 用穷举法找出 1-100 间的质数并显示出来。分别使用 while,do...while,for循环语句实现
#include <iostream>
using namespace std;
// 质数:一个大于 1 的自然数,除了 1 和 它自身之外不能被其它自然数整除的数
int main()
{
int N = 0;
for (int i = 2; i < 100; i++)
{
bool flag = true;
for (int j = 2; j < i; j++)
{
if (i % j == 0)
{
flag = false;
break;
}
}
if (flag == true)
{
cout<<i<<"\n";
N += 1;
}
}
cout<<"共有: "<<N<<" 个质数。"<<endl;
return 0;
} | [
"liujuan@liujuandeMacBook-Pro.local"
] | liujuan@liujuandeMacBook-Pro.local |
0157e3c27b66e796348a45ea59660c487161ba73 | 8ad1e3fc2e58089cb68a4da0fcbe3f4d4ec2871c | /qualification-round/include/Book.hpp | 1ce0821145ec3db1e12718242c3a0dbd82b4228d | [] | no_license | whichxjy/Hash-Code-2020 | 5748becc98f2c74862dc47369fc9d2794634a2ac | 636f3ceb364128e4a24eaf3430acc15226cb2182 | refs/heads/master | 2021-01-08T12:41:06.768923 | 2020-02-21T02:22:57 | 2020-02-21T02:22:57 | 242,029,955 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 157 | hpp | #ifndef _BOOK_HPP_
#define _BOOK_HPP_
struct Book {
int index;
int score;
Book(int index, int score) : index(index), score(score) {}
};
#endif | [
"whichxjy@gmail.com"
] | whichxjy@gmail.com |
9635701bd746574c8a79ed135aadfe445515d329 | a52ca01fcd1250ce5dbbdd969f85cbd72255d69f | /EngineUAB/Code/GUI/Controls/GUIImage.h | fa09adb55a619852deddcfdb7c1e4c25941eddbd | [] | no_license | kusku/red-forest | b089c8a76ed211ec126e07a32cd5c2cee90f6c12 | 24a104f06cce6031a66a6a920c0c170d059f38fb | refs/heads/master | 2021-01-10T08:00:46.367896 | 2012-10-26T02:35:34 | 2012-10-26T02:35:34 | 53,213,277 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,830 | h | //----------------------------------------------------------------------------------
// CSlider class
// Author: Enric Vergara
//
// Description:
// A Image..
//----------------------------------------------------------------------------------
#pragma once
#ifndef INC_IMAGE_H
#define INC_IMAGE_H
#include "RenderManager.h"
#include "GuiElement.h"
#include "Math/Color.h"
#include <map>
#include "Math/MathUtils.h"
//---Forward Declarations---
class CTexture;
//--------------------------
enum
{
GUI_I_NO_EFFECT = 0,
GUI_I_FADE_IN,
GUI_I_FADE_OUT
};
class CGUIImage: public CGuiElement
{
private:
typedef std::map<std::string, CTexture*> tTexturesMap;
typedef std::vector<CTexture*>::iterator tItTexturesVec;
typedef std::vector<CTexture*> tTexturesVec;
public:
CGUIImage( uint32 windowsHeight, uint32 windowsWidth, float height_precent, float witdh_percent,
const Vect2f position_percent, std::string lit="", uint32 textHeightOffset=0, uint32 textWidthOffset=0,
bool isVisible = true, bool isActive = true);
virtual ~CGUIImage() {/*NOTHING*/;}
//---------------CGuiElement Interface----------------------
virtual void Render (CRenderManager *renderManager, CFontManager* fm);
virtual void Update (CInputManager* intputManager, float elapsedTime);
virtual void OnClickedChild (const std::string& name) {/*NOTHING*/;}
//---------------CImage Interface---------------------------
void SetTexture (CTexture* texture, std::string name );
void SetActiveTexture (const std::string& inName) {m_sActiveTexture = inName;}
std::string& GetActiveTexture () {return m_sActiveTexture;}
void PlayAnimation (float timePerImage, bool loop);
void SetFlip (ETypeFlip flip) {m_eFlip = flip;}
ETypeFlip GetFlip () const {return m_eFlip;}
bool IsQuadrant () const {return m_bIsQuadrant;}
void SetQuadrant (bool flag) {m_bIsQuadrant = flag;}
void SetBackGround (bool flag) {m_bIsBackGround=flag;}
void FadeOut (float startTime, float fadePerSecond);
void SetAlpha (float _Alpha) { m_fAlpha = _Alpha; }
CTexture* GetTexture ( const std::string &name) { return m_Textures[name]; }
private:
tTexturesMap m_Textures;
tItTexturesVec m_itVecTextures;
tTexturesVec m_VecTextures;
CColor m_Color;
std::string m_sActiveTexture;
bool m_bAnimated;
bool m_bLoop;
float m_fTimePerImage;
float m_fCounter;
ETypeFlip m_eFlip;
bool m_bIsQuadrant;
bool m_bIsBackGround;
int m_iEffect;
float m_fAlpha;
float m_fFadeCounter;
float m_fFadeStartAfter;
float m_fFadePerSecond;
};
#endif //INC_IMAGE_H | [
"mcuscullola@gmail.com"
] | mcuscullola@gmail.com |
2d8f095b15748cb6dc28e7a23932117d60b32293 | 858f566155244ae25f49b0cc8ad054a5664d2c25 | /src/graphics/g3d/model/MeshPart.cpp | 355a0ddb9260539626231761f1e7650a6783b43c | [] | no_license | ccour004/libgdxpp | ba0f910c175bb37f35b50ce70a9858d26f164a4c | 53dcf598978836ec5993ad21c0808058f97a5801 | refs/heads/master | 2021-01-23T05:46:04.621145 | 2017-09-11T14:01:43 | 2017-09-11T14:01:43 | 92,987,795 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 68 | cpp | #include "MeshPart.h"
BoundingBox MeshPart::bounds = BoundingBox(); | [
"ccour004@gmail.com"
] | ccour004@gmail.com |
7e85a0cd7cd7859c4ba655c0a675bc207039ed76 | ee36265f8b51b9fd2abe219b293ead7bfc3e306c | /BinarySearch/SearchInRotatedSortedArray.cpp | 49aef99a91ba57145c61393ca3117c626045b60b | [] | no_license | shakti-rajput/Coding | 7d0ce524415413adf800c6b67070344cb8ddc018 | 3e7b145ff60dc705e2d50498a764cf6e6a0a09a3 | refs/heads/master | 2022-04-28T08:33:16.257092 | 2022-04-07T12:57:11 | 2022-04-07T12:57:11 | 122,243,215 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,280 | cpp | class Solution {
public:
int binSearch(vector<int>& arr,int lo,int hi,int target)
{
while(lo<=hi)
{
int mid =lo+(hi-lo)/2;
if(arr[mid]==target)
return mid;
else if(arr[mid]<target)
lo=mid+1;
else
hi=mid-1;
}
return -1;
}
int search(vector<int>& arr, int target) {
int lo=0,hi=arr.size()-1;
int pivot=-1;
while(lo<hi)
{
int mid=lo+(hi-lo)/2;
// cout<<"lo "<<lo<<endl;
// cout<<"hi "<<hi<<endl;
// cout<<"mid "<<mid<<endl;
// cout<<"arr[mid] "<<arr[mid]<<endl;
// cout<<"arr[hi] "<<arr[hi]<<endl;
if(arr[mid]>arr[hi])
lo=mid+1;
else
hi=mid;
// cout<<"lo "<<lo<<endl;
// cout<<"hi "<<hi<<endl;
}
pivot=lo;
// cout<<lo;
if(target>=arr[pivot] && target<=arr[arr.size()-1])
{
return binSearch(arr,pivot,arr.size()-1,target);
}
else if(target>=arr[0] && pivot-1 >= 0 && target<=arr[pivot-1])
{
return binSearch(arr,0,pivot-1,target);
}
return -1;
}
};
| [
"shakti@availfinance.in"
] | shakti@availfinance.in |
8eacf656bad57731d5cbc025c201b6e4fe1b9ce0 | 9fcf6505213b669b291ceda13392a01c53c858b4 | /autonomous_car/esp.hh | ea1eb1dceef9635b0859e3bcd18dab8566a2f8d9 | [] | no_license | Watscob/arduino_car | 1e6a99ea23a88e3f01d93d7da0aef227cba7b74f | d48420db061e2d5c1c212687e9343877d7e712f6 | refs/heads/master | 2023-08-11T15:51:01.443099 | 2021-09-26T14:53:46 | 2021-09-26T14:53:46 | 314,654,074 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 818 | hh | #pragma once
#include <Arduino.h>
enum Request
{
REQUEST_UNDEFINED, // 0
REQUEST_SPEED_PLUS, // 1
REQUEST_SPEED_MINUS, // 2
REQUEST_MIN_SPEED, // 3
REQUEST_MAX_SPEED, // 4
REQUEST_GO_FORWARD, // 5
REQUEST_GO_BACKWARD, // 6
REQUEST_ROTATE_LEFT, // 7
REQUEST_ROTATE_RIGHT, // 8
REQUEST_STOP, // 9
REQUEST_LIGHT_ALL, //10
REQUEST_LIGHT_FRONT, //11
REQUEST_LIGHT_BACK, //12
REQUEST_LIGHT_OFF, //13
REQUEST_LIGHT_BLINK, //14
REQUEST_CONNECTED, //15
REQUEST_GET_SSID, //16
REQUEST_GET_IP //17
};
class ESPAdaptator
{
public:
ESPAdaptator(long update_speed);
~ESPAdaptator();
Request read_wifi(String *arg);
};
| [
"etienne.chanudet@epita.fr"
] | etienne.chanudet@epita.fr |
cdbd36d1d442bd71b2fbb4fa44bf11e2ba230e9e | ef8914233abc7f1508e182c5ffbef0ec2d25c271 | /raaGraphToolQt/raaGraphHud.h | 718ef879710d03b8ceb901c9c88d9741b48376ac | [] | no_license | trebornipsa/raaGraphTool | 656a49ebb236f3d19b8b8287878416a1e5ce9239 | 79f51fee80a5b853086ccd68f114ad1de470f768 | refs/heads/master | 2021-01-12T14:06:52.790313 | 2016-10-06T15:11:17 | 2016-10-06T15:11:17 | 70,153,927 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,022 | h | #pragma once
#include <map>
#include <string>
#include <osg/Drawable>
class raaGraphPlot;
typedef std::map<std::string, raaGraphPlot*> raaPlots;
class raaGraphHud : public osg::Drawable::DrawCallback
{
public:
raaGraphHud();
virtual ~raaGraphHud();
virtual void drawImplementation(osg::RenderInfo &, const osg::Drawable *) const;
osg::Group* root();
void resize(int iX, int iY, int iWidth, int iHeight);
unsigned int toPanelX(float fX) const;
unsigned int toGraphX(float fX) const;
unsigned int toPanelY(float fY) const;
unsigned int toGraphY(float fY) const;
float fromPanelX(unsigned int uiX);
float fromPanelY(unsigned int uiY);
float fromGraphX(unsigned int uiX);
float fromGraphY(unsigned int uiY);
bool addPlot(std::string sName, raaGraphPlot *pPlot);
void removePlot(std::string sName);
protected:
int m_iWidth;
int m_iPanelHeight;
int m_iHeight;
osg::Group *m_pGroup;
osg::Geode *m_pGeode;
osg::MatrixTransform *m_pTransform;
osg::Projection *m_pProjection;
raaPlots m_mPlots;
};
| [
"R.Aspin@salford.ac.uk"
] | R.Aspin@salford.ac.uk |
0f842b767ba64cb46cd0391095be943dad9b8cf1 | 36b5eabb25b2b2d9bf01e26b4ba6728e234c4c96 | /codeforces/Edu96G.cpp | 839d7e22bf4c1e1e113edcf72b9a979174a48013 | [] | no_license | king7282/algorithm | e5d5dbf6ba9e723ffadeca7a1a08e7e6bf362065 | 871507ca7647e95bcd7d86988147559252755670 | refs/heads/master | 2023-06-29T04:14:10.056548 | 2021-07-28T00:29:50 | 2021-07-28T00:29:50 | 293,427,801 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,151 | cpp | #include <stdio.h>
#include <algorithm>
#include <vector>
#include <cstring>
#include <climits>
#include <queue>
struct info {
int val, num, bitmask;
};
int need_mask[20];
long long weights[19], dp[19][19][1 << 18], degree[19], result[19];
std::vector<int> graph[19], order, reverse[19];
bool check[19][19][1 << 18];
long long func(int val, int num, int bitmask) {
if (bitmask == ((1 << order.size()) - 1)) {
return 0;
}
if (val < 0) {
return LLONG_MAX / 2;
}
if (check[val][num][bitmask] == true)
return dp[val][num][bitmask];
check[val][num][bitmask] = true;
dp[val][num][bitmask] = LLONG_MAX / 2;
dp[val][num][bitmask] = std::min(dp[val][num][bitmask], func(val - 1, order.size() - 1, bitmask));
if ((bitmask & (1 << (order[num] - 1))) == 0 && (need_mask[order[num]] | bitmask) == bitmask)
dp[val][num][bitmask] = std::min(dp[val][num][bitmask], func(val - 1, order.size() - 1, bitmask | (1 << (order[num] - 1))) + weights[order[num]] * val);
if (num != 0) {
int next = num - 1;
if ((bitmask & (1 << (order[num] - 1))) == 0 && (need_mask[order[num]] | bitmask) == bitmask)
dp[val][num][bitmask] = std::min(dp[val][num][bitmask], func(val, next, bitmask | (1 << (order[num] - 1))) + weights[order[num]] * val);
dp[val][num][bitmask] = std::min(dp[val][num][bitmask], func(val, next, bitmask));
}
return dp[val][num][bitmask];
}
int main(void) {
int n, m;
scanf("%d %d", &n, &m);
for (int i = 1; i <= m; i++) {
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
reverse[b].push_back(a);
graph[a].push_back(b);
weights[a] += c;
weights[b] -= c;
degree[b]++;
}
if (m == 0) {
for (int i = 1; i <= n; i++)
printf("1 ");
printf("\n");
return 0;
}
std::queue<int> qu;
for (int i = 1; i <= n; i++) {
if (degree[i] == 0) {
qu.push(i);
}
}
while (!qu.empty()) {
int front = qu.front();
qu.pop();
order.push_back(front);
for (int i = 0; i < graph[front].size(); i++) {
degree[graph[front][i]]--;
if (degree[graph[front][i]] == 0) {
qu.push(graph[front][i]);
}
}
}
for (int i = 0; i < order.size(); i++) {
for (int j = 0; j < reverse[order[i]].size(); j++) {
need_mask[order[i]] |= (need_mask[reverse[order[i]][j]] | (1 << (reverse[order[i]][j] - 1)));
}
}
func(n, order.size() - 1, 0);
info cur;
cur.val = n; cur.num = order.size() - 1; cur.bitmask = 0;
while (cur.bitmask != (1 << n) - 1) {
info next;
int nnext = cur.num - 1;
if (cur.val == 0) {
if((cur.bitmask | (1 << (order[cur.num] - 1))) == (1 << (n - 1))) {
next.val = cur.val - 1;
next.num = order.size() - 1;
next.bitmask = (cur.bitmask | (1 << (order[cur.num] - 1)));
}
}
else {
if (dp[cur.val][cur.num][cur.bitmask] == dp[cur.val - 1][order.size() - 1][cur.bitmask]) {
next.val = cur.val - 1;
next.num = order.size() - 1;
next.bitmask = cur.bitmask;
}
if ((cur.bitmask & (1 << (order[cur.num] - 1))) == 0 && (need_mask[order[cur.num]] | cur.bitmask) == cur.bitmask) {
if (dp[cur.val][cur.num][cur.bitmask] == dp[cur.val - 1][order.size() - 1][cur.bitmask | (1 << (order[cur.num] - 1))] + weights[order[cur.num]] * cur.val) {
next.val = cur.val - 1;
next.num = order.size() - 1;
next.bitmask = (cur.bitmask | (1 << (order[cur.num] - 1)));
}
}
}
if (nnext != -1) {
if ((cur.bitmask & (1 << (order[cur.num] - 1))) == 0 && (need_mask[order[cur.num]] | cur.bitmask) == cur.bitmask) {
if (dp[cur.val][cur.num][cur.bitmask] == dp[cur.val][nnext][cur.bitmask | (1 << (order[cur.num] - 1))] + weights[order[cur.num]] * cur.val) {
next.val = cur.val;
next.num = nnext;
next.bitmask = (cur.bitmask | (1 << (order[cur.num] - 1)));
}
}
if (dp[cur.val][cur.num][cur.bitmask] == dp[cur.val][nnext][cur.bitmask]) {
next.val = cur.val;
next.num = nnext;
next.bitmask = cur.bitmask;
}
}
if (cur.bitmask != next.bitmask) {
for (int i = 1; i <= n; i++) {
if ((cur.bitmask & (1 << (i - 1))) == 0 && (next.bitmask & (1 << (i - 1))) != 0) {
result[i] = cur.val;
}
}
}
cur = next;
}
for (int i = 1; i <= n; i++)
printf("%d ", result[i]);
} | [
"juyj7282@gmail.com"
] | juyj7282@gmail.com |
f05bb717e89a74704a0c4a5f1768c90c9a9851fe | 00da795e529b9c8acd4e20dcedaa68db9015f449 | /Geeks4Geeks/Trees/printroottoleaf.cpp | ef6b84a9ff823ae342a1ddc762580c74a6d0829a | [] | no_license | nitish11/coding-practices | f557c24babc9ac210da429dfc184d9294feeeb27 | 85a38d71165b71c535f020fe2e7edd095588b854 | refs/heads/master | 2021-01-01T05:31:53.599731 | 2014-07-09T12:56:29 | 2014-07-09T12:56:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,694 | cpp | using namespace std;
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<string>
#include<vector>
#include<map>
#include<queue>
#include<algorithm>
typedef long long int int64;
struct node
{
int data;
struct node* left;
struct node* right;
};
struct node* newNode(int );
/* Helper function that allocates a new node with the given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Function to print roottoleave */
void print(int a[],int n)
{
for(int i=0; i<n; i++) cout<<a[i]<<" ";
cout<<endl;
}
void roottoleave(struct node* root, int a[],int plen)
{
int64 t,i,j,k,mx;
if(root==NULL) {return; }
a[plen] = root->data; plen++;
if(root->left ==NULL && root->right ==NULL)print(a,plen);
if(root->left !=NULL) roottoleave(root->left,a,plen);
if(root->right !=NULL) roottoleave(root->right,a,plen);
}
void printroottoleave(struct node* root)
{
int a[1000],plen=0;
roottoleave(root,a,plen);
}
/* Driver program to test mirror() */
int main()
{
int a[100][100],m,n,i,j,k;
struct node *root = newNode(10);
root->left = newNode(11);
root->right = newNode(4);
root->right->left = newNode(3);
root->right->right = newNode(5);
/* Constructed tree is
10
/ \
11 4
/ \
3 5
*/
printroottoleave(root);
cin>>i;
return 0;
}
| [
"nitish.bhardwaj11@gmail.com"
] | nitish.bhardwaj11@gmail.com |
b57417425b3a20f85541a87e01d9c16bc69a32a1 | 51bbfe4653e7ba7c95e7822151b2f8b59ca8083c | /microsoft/LightGBM-1/src/io/sparse_bin.hpp | 5e458a2a696b283e41711f82bf6fa45a9ea38a94 | [
"MIT"
] | permissive | Ankitvaibs/Virus | 8a744ba01ba2b1e09fea95aeacd37518261cd187 | debf3a893ee3cf328e155b1eb760ce2b7290043a | refs/heads/master | 2020-04-29T03:07:12.010478 | 2019-03-18T03:22:49 | 2019-03-18T03:22:49 | 175,797,516 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,440 | hpp | #ifndef LIGHTGBM_IO_SPARSE_BIN_HPP_
#define LIGHTGBM_IO_SPARSE_BIN_HPP_
#include <LightGBM/utils/log.h>
#include <LightGBM/bin.h>
#include <LightGBM/utils/openmp_wrapper.h>
#include <cstring>
#include <cstdint>
#include <limits>
#include <vector>
namespace LightGBM {
template <typename VAL_T>
class SparseBin;
const size_t kNumFastIndex = 64;
const uint8_t kMaxDelta = 255;
template <typename VAL_T>
class SparseBinIterator: public BinIterator {
public:
SparseBinIterator(const SparseBin<VAL_T>* bin_data, data_size_t start_idx)
: bin_data_(bin_data) {
Reset(start_idx);
}
inline VAL_T InnerGet(data_size_t idx);
inline uint32_t Get(data_size_t idx) override {
return InnerGet(idx);
}
inline void Reset(data_size_t idx);
private:
const SparseBin<VAL_T>* bin_data_;
data_size_t cur_pos_;
data_size_t i_delta_;
};
template <typename VAL_T>
class OrderedSparseBin;
template <typename VAL_T>
class SparseBin: public Bin {
public:
friend class SparseBinIterator<VAL_T>;
friend class OrderedSparseBin<VAL_T>;
SparseBin(data_size_t num_data, uint32_t default_bin)
: num_data_(num_data) {
default_bin_ = static_cast<VAL_T>(default_bin);
#pragma omp parallel
#pragma omp master
{
num_threads_ = omp_get_num_threads();
}
for (int i = 0; i < num_threads_; ++i) {
push_buffers_.emplace_back();
}
}
~SparseBin() {
}
void ReSize(data_size_t num_data) override {
num_data_ = num_data;
}
void Push(int tid, data_size_t idx, uint32_t value) override {
auto cur_bin = static_cast<VAL_T>(value);
if (cur_bin != default_bin_) {
push_buffers_[tid].emplace_back(idx, cur_bin);
}
}
BinIterator* GetIterator(data_size_t start_idx) const override;
void ConstructHistogram(const data_size_t*, data_size_t, const score_t*,
const score_t*, HistogramBinEntry*) const override {
// Will use OrderedSparseBin->ConstructHistogram() instead
Log::Fatal("Using OrderedSparseBin->ConstructHistogram() instead");
}
inline bool NextNonzero(data_size_t* i_delta,
data_size_t* cur_pos) const {
const VAL_T non_data_flag = std::numeric_limits<VAL_T>::max();
++(*i_delta);
*cur_pos += deltas_[*i_delta];
data_size_t factor = 1;
while (*i_delta < num_vals_ && vals_[*i_delta] == non_data_flag) {
++(*i_delta);
factor *= kMaxDelta;
*cur_pos += deltas_[*i_delta] * factor;
}
if (*i_delta >= 0 && *i_delta < num_vals_) {
return true;
} else {
return false;
}
}
virtual data_size_t Split(unsigned int threshold, data_size_t* data_indices, data_size_t num_data,
data_size_t* lte_indices, data_size_t* gt_indices) const override {
// not need to split
if (num_data <= 0) { return 0; }
SparseBinIterator<VAL_T> iterator(this, data_indices[0]);
data_size_t lte_count = 0;
data_size_t gt_count = 0;
for (data_size_t i = 0; i < num_data; ++i) {
const data_size_t idx = data_indices[i];
VAL_T bin = iterator.InnerGet(idx);
if (bin > threshold) {
gt_indices[gt_count++] = idx;
} else {
lte_indices[lte_count++] = idx;
}
}
return lte_count;
}
data_size_t num_data() const override { return num_data_; }
OrderedBin* CreateOrderedBin() const override;
void FinishLoad() override {
// get total non zero size
size_t pair_cnt = 0;
for (size_t i = 0; i < push_buffers_.size(); ++i) {
pair_cnt += push_buffers_[i].size();
}
std::vector<std::pair<data_size_t, VAL_T>> idx_val_pairs;
// merge
idx_val_pairs.reserve(pair_cnt);
for (size_t i = 0; i < push_buffers_.size(); ++i) {
idx_val_pairs.insert(idx_val_pairs.end(), push_buffers_[i].begin(), push_buffers_[i].end());
push_buffers_[i].clear();
push_buffers_[i].shrink_to_fit();
}
push_buffers_.clear();
push_buffers_.shrink_to_fit();
// sort by data index
std::sort(idx_val_pairs.begin(), idx_val_pairs.end(),
[](const std::pair<data_size_t, VAL_T>& a, const std::pair<data_size_t, VAL_T>& b) {
return a.first < b.first;
});
// load detla array
LoadFromPair(idx_val_pairs);
}
void LoadFromPair(const std::vector<std::pair<data_size_t, VAL_T>>& idx_val_pairs) {
deltas_.clear();
vals_.clear();
const VAL_T non_data_flag = std::numeric_limits<VAL_T>::max();
// transform to delta array
data_size_t last_idx = 0;
for (size_t i = 0; i < idx_val_pairs.size(); ++i) {
const data_size_t cur_idx = idx_val_pairs[i].first;
const VAL_T bin = idx_val_pairs[i].second;
data_size_t cur_delta = cur_idx - last_idx;
while (cur_delta > kMaxDelta) {
deltas_.push_back(cur_delta % kMaxDelta);
vals_.push_back(non_data_flag);
cur_delta /= kMaxDelta;
}
deltas_.push_back(static_cast<uint8_t>(cur_delta));
vals_.push_back(bin);
last_idx = cur_idx;
}
// avoid out of range
deltas_.push_back(0);
num_vals_ = static_cast<data_size_t>(vals_.size());
// reduce memory cost
deltas_.shrink_to_fit();
vals_.shrink_to_fit();
// generate fast index
GetFastIndex();
}
void GetFastIndex() {
fast_index_.clear();
// get shift cnt
data_size_t mod_size = (num_data_ + kNumFastIndex - 1) / kNumFastIndex;
data_size_t pow2_mod_size = 1;
fast_index_shift_ = 0;
while (pow2_mod_size < mod_size) {
pow2_mod_size <<= 1;
++fast_index_shift_;
}
// build fast index
data_size_t i_delta = -1;
data_size_t cur_pos = 0;
data_size_t next_threshold = 0;
while (NextNonzero(&i_delta, &cur_pos)) {
while (next_threshold <= cur_pos) {
fast_index_.emplace_back(i_delta, cur_pos);
next_threshold += pow2_mod_size;
}
}
// avoid out of range
while (next_threshold < num_data_) {
fast_index_.emplace_back(num_vals_ - 1, cur_pos);
next_threshold += pow2_mod_size;
}
fast_index_.shrink_to_fit();
}
void SaveBinaryToFile(FILE* file) const override {
fwrite(&num_vals_, sizeof(num_vals_), 1, file);
fwrite(deltas_.data(), sizeof(uint8_t), num_vals_ + 1, file);
fwrite(vals_.data(), sizeof(VAL_T), num_vals_, file);
}
size_t SizesInByte() const override {
return sizeof(num_vals_) + sizeof(uint8_t) * (num_vals_ + 1)
+ sizeof(VAL_T) * num_vals_;
}
void LoadFromMemory(const void* memory, const std::vector<data_size_t>& local_used_indices) override {
const char* mem_ptr = reinterpret_cast<const char*>(memory);
data_size_t tmp_num_vals = *(reinterpret_cast<const data_size_t*>(mem_ptr));
mem_ptr += sizeof(tmp_num_vals);
const uint8_t* tmp_delta = reinterpret_cast<const uint8_t*>(mem_ptr);
mem_ptr += sizeof(uint8_t) * (tmp_num_vals + 1);
const VAL_T* tmp_vals = reinterpret_cast<const VAL_T*>(mem_ptr);
deltas_.clear();
vals_.clear();
num_vals_ = tmp_num_vals;
for (data_size_t i = 0; i < num_vals_; ++i) {
deltas_.push_back(tmp_delta[i]);
vals_.push_back(tmp_vals[i]);
}
deltas_.push_back(0);
// reduce memory cost
deltas_.shrink_to_fit();
vals_.shrink_to_fit();
if (local_used_indices.empty()) {
// generate fast index
GetFastIndex();
} else {
std::vector<std::pair<data_size_t, VAL_T>> tmp_pair;
data_size_t cur_pos = 0;
data_size_t j = -1;
for (data_size_t i = 0; i < static_cast<data_size_t>(local_used_indices.size()); ++i) {
const data_size_t idx = local_used_indices[i];
while (cur_pos < idx && j < num_vals_) {
NextNonzero(&j, &cur_pos);
}
if (cur_pos == idx && j < num_vals_) {
// new row index is i
tmp_pair.emplace_back(i, vals_[j]);
}
}
LoadFromPair(tmp_pair);
}
}
void CopySubset(const Bin* full_bin, const data_size_t* used_indices, data_size_t num_used_indices) override {
auto other_bin = reinterpret_cast<const SparseBin<VAL_T>*>(full_bin);
SparseBinIterator<VAL_T> iterator(other_bin, used_indices[0]);
std::vector<std::pair<data_size_t, VAL_T>> tmp_pair;
for (data_size_t i = 0; i < num_used_indices; ++i) {
VAL_T bin = iterator.InnerGet(used_indices[i]);
if (bin != default_bin_) {
tmp_pair.emplace_back(i, bin);
}
}
LoadFromPair(tmp_pair);
}
protected:
data_size_t num_data_;
std::vector<uint8_t> deltas_;
std::vector<VAL_T> vals_;
data_size_t num_vals_;
int num_threads_;
std::vector<std::vector<std::pair<data_size_t, VAL_T>>> push_buffers_;
std::vector<std::pair<data_size_t, data_size_t>> fast_index_;
data_size_t fast_index_shift_;
VAL_T default_bin_;
};
template <typename VAL_T>
inline VAL_T SparseBinIterator<VAL_T>::InnerGet(data_size_t idx) {
while (cur_pos_ < idx && i_delta_ < bin_data_->num_vals_) {
bin_data_->NextNonzero(&i_delta_, &cur_pos_);
}
if (cur_pos_ == idx && i_delta_ < bin_data_->num_vals_ && i_delta_ >= 0) {
return bin_data_->vals_[i_delta_];
} else {
return bin_data_->default_bin_;
}
}
template <typename VAL_T>
inline void SparseBinIterator<VAL_T>::Reset(data_size_t start_idx) {
const auto fast_pair = bin_data_->fast_index_[start_idx >> bin_data_->fast_index_shift_];
i_delta_ = fast_pair.first;
cur_pos_ = fast_pair.second;
}
template <typename VAL_T>
BinIterator* SparseBin<VAL_T>::GetIterator(data_size_t start_idx) const {
return new SparseBinIterator<VAL_T>(this, start_idx);
}
template <typename VAL_T>
class SparseCategoricalBin: public SparseBin<VAL_T> {
public:
SparseCategoricalBin(data_size_t num_data, uint32_t default_bin)
: SparseBin<VAL_T>(num_data, default_bin) {
}
virtual data_size_t Split(unsigned int threshold, data_size_t* data_indices, data_size_t num_data,
data_size_t* lte_indices, data_size_t* gt_indices) const override {
// not need to split
if (num_data <= 0) { return 0; }
SparseBinIterator<VAL_T> iterator(this, data_indices[0]);
data_size_t lte_count = 0;
data_size_t gt_count = 0;
for (data_size_t i = 0; i < num_data; ++i) {
const data_size_t idx = data_indices[i];
VAL_T bin = iterator.InnerGet(idx);
if (bin != threshold) {
gt_indices[gt_count++] = idx;
} else {
lte_indices[lte_count++] = idx;
}
}
return lte_count;
}
};
} // namespace LightGBM
#endif // LightGBM_IO_SPARSE_BIN_HPP_
| [
"42571581+Ankitvaibs@users.noreply.github.com"
] | 42571581+Ankitvaibs@users.noreply.github.com |
529f9dfcfe77a4f642fe75eda2402f8c0977a49f | 1fcdb2bc2c7f75f6aed466119a4b1c53777f0b7a | /holly_inlet_LRR_RSM_noturbulence/5/phi | 24e0d48773563c14fbec5eda2217b0763680b93b | [] | no_license | bshambaugh/openfoam-experiments3 | b32549e80836eee9fc6062873fc737155168f919 | 4bd90a951845a4bc5dda7063e91f6cc0ba730e48 | refs/heads/master | 2020-04-15T08:17:15.156512 | 2019-01-15T04:31:23 | 2019-01-15T04:31:23 | 164,518,405 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,616 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 4.1 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class surfaceScalarField;
location "5";
object phi;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 3 -1 0 0 0 0];
internalField nonuniform List<scalar>
420
(
-949.88
2249.78
-1573.95
1924.27
-2054
1779.94
-2424.23
1670.13
-2699.86
1575.83
-2888.38
1488.42
-2993.06
1404.58
-3013.86
1321
-2949.62
1235.66
-2797.24
1147.52
-2551.17
1054.13
-2193
941.733
-1687.17
794.064
-1012.67
625.704
287.231
373.345
1876.43
442.736
1854.88
437.271
1785.41
406.652
1700.75
380.536
1601.95
359.864
1509.09
345.263
1419.18
337.508
1328.76
333.461
1239.71
326.938
1154.04
309.604
1071.47
267.471
983.872
191.433
870.106
111.448
705.694
398.679
33.6571
1842.8
-97.3336
1985.88
-253.552
1941.64
-371.032
1818.24
-473.06
1703.98
-567.383
1603.43
-651.586
1503.39
-725.609
1402.79
-787.872
1301.98
-837.088
1203.28
-867.964
1102.39
-855.863
971.756
-740.181
754.449
-434.279
399.817
-35.5992
28.7022
1814.09
-100.645
2115.27
-225.508
2066.49
-304.333
1897.12
-367.995
1767.63
-416.756
1652.24
-446.047
1532.68
-456.798
1413.6
-451.643
1296.84
-429.943
1181.62
-387.113
1059.52
-311.699
896.471
-192.698
635.544
-48.2579
255.475
-83.8567
169.498
1644.55
146.098
2138.68
123.692
2088.86
122.839
1897.99
126.841
1763.62
135.676
1643.43
148.937
1519.42
166.402
1396.14
186.718
1276.52
207.891
1160.46
228.797
1038.55
243.567
881.795
232.85
646.307
155.267
333.104
71.4092
223.351
1421.22
244.439
2117.55
234.927
2098.41
235.988
1896.87
240.256
1759.38
244.077
1639.54
246.318
1517.2
244.932
1397.46
240.863
1280.61
233.685
1167.58
221.254
1051.06
198.937
903.929
155.945
689.177
78.1354
410.799
149.544
203.544
1217.76
238.453
2082.64
213.574
2123.35
191.223
1919.19
177.07
1773.57
163.677
1652.89
150.044
1530.86
135.933
1411.54
121.202
1295.37
107.117
1181.65
93.1237
1065.09
76.049
920.959
52.2226
712.971
19.0789
443.911
168.624
171.268
1046.48
221.226
2032.76
198.692
2145.85
170.002
1947.97
151.839
1791.68
137.74
1667.09
122.909
1545.64
108.898
1425.65
95.9268
1308.3
83.5244
1194.13
71.7814
1076.77
58.9414
933.91
40.5709
731.403
15.9282
468.609
184.555
145.247
901.111
209.182
1968.87
196.155
2158.74
169.773
1974.46
152.202
1809.16
139.478
1679.96
126.846
1558.17
113.692
1438.94
100.906
1320.96
88.9677
1206.19
76.1327
1089.38
62.556
947.956
44.0517
750.257
19.2459
493.736
203.798
116.862
784.107
185.114
1900.55
179.95
2163.84
154.54
1999.81
137.237
1826.43
123.703
1693.43
110.877
1571.01
98.2549
1451.49
85.351
1333.91
72.9421
1218.49
61.4683
1101.13
48
960.886
31.7798
766.105
12.2915
512.887
216.086
84.0651
700.025
144.098
1840.36
145.486
2162.47
123.038
2022.07
106.142
1843.34
94.0579
1705.3
82.154
1582.93
70.587
1462.85
59.9394
1344.59
48.9957
1229.25
39.3207
1110.91
29.5396
970.269
17.8435
777.459
4.97808
525.442
221.067
51.5941
648.439
98.0486
1793.84
102.484
2158
86.8289
2037.64
72.4885
1857.65
62.4851
1715.23
53.7322
1591.66
44.484
1472.06
35.8651
1353.15
28.0443
1237.09
20.3071
1118.55
13.8817
976.96
7.13285
784.476
-0.0407066
532.854
221.024
24.7212
623.803
56.919
1761.7
62.598
2152.36
52.7112
2047.56
43.4152
1866.96
36.0484
1722.62
29.7182
1598
23.912
1477.9
17.6602
1359.44
12.0247
1242.72
7.53655
1123.19
3.13108
981.072
-0.670054
788.031
-3.52275
535.488
217.504
0.453926
623.357
22.6933
1739.54
32.0513
2142.97
26.9412
2052.76
19.9668
1873.91
15.0844
1727.63
9.69623
1603.38
4.91349
1482.8
0.330408
1364
-4.45408
1247.63
-8.20779
1126.8
-9.27439
982.554
-9.21916
788.319
-6.61725
533.198
210.888
-12.4305
-3.99222
0.717856
-0.770517
-5.18483
-8.65499
-11.4761
-14.8053
-17.6578
-19.7866
-21.3686
-20.712
-17.7122
-12.0768
)
;
boundaryField
{
inletFace
{
type calculated;
value nonuniform List<scalar>
450
(
-2.96439e-13
3.81612e-13
-2.77427e-13
-1.94783e-13
2.05867e-13
-1.78977e-13
-5.50478e-14
8.49066e-14
-8.40886e-14
-4.77321e-14
4.62913e-14
-2.03957e-14
-9.82249e-15
4.57052e-15
1.89319e-15
-2.06963e-12
-2.33705e-12
-5.26391e-14
-7.48823e-13
-3.16264e-13
2.30204e-14
-3.30512e-13
-1.71764e-13
4.77262e-14
-6.16775e-14
-5.23918e-14
4.76455e-14
-1.24691e-14
-6.46437e-15
-8.44803e-16
-2.1943e-12
-1.97624e-12
-2.40713e-13
-5.75306e-13
-2.51839e-13
-1.33414e-13
-3.4098e-13
-1.03068e-13
-7.60696e-14
-7.83985e-14
-1.04069e-16
-1.58069e-14
-1.07699e-14
8.57866e-15
1.43715e-15
-2.56092e-12
-1.9658e-12
-3.02686e-13
-8.33376e-13
-1.65156e-13
-2.74473e-13
-4.17448e-13
-7.07314e-14
-1.87703e-13
-2.16858e-13
5.91721e-15
-7.54356e-14
-7.46166e-14
3.62025e-14
6.4706e-14
-2.25663e-12
-2.01287e-12
-3.73119e-13
-7.39712e-13
-2.04661e-13
-2.66914e-13
-4.00958e-13
-1.97631e-13
-2.2736e-13
-2.0921e-13
-5.83313e-14
-1.74623e-14
-5.051e-14
1.42989e-14
8.268e-14
-2.00727e-12
-2.05179e-12
-5.17063e-13
-5.77024e-13
-2.25403e-13
-2.25056e-13
-3.75196e-13
-2.22259e-13
-2.09175e-13
-1.66044e-13
-5.5866e-14
4.45417e-15
7.05741e-15
3.61661e-14
3.80164e-14
-1.79207e-12
-2.13588e-12
-7.23801e-13
-5.41993e-13
-2.57664e-13
-2.4183e-13
-3.43361e-13
-1.66823e-13
-2.27398e-13
-1.58526e-13
-7.37527e-14
-8.67359e-14
2.20491e-14
-5.20965e-14
-1.44768e-13
-1.5851e-12
-2.17804e-12
-9.22302e-13
-5.18602e-13
-2.80639e-13
-2.54609e-13
-3.47229e-13
-1.90873e-13
-2.2083e-13
-2.26959e-13
-1.30779e-13
-1.23808e-13
-7.68185e-14
-1.68554e-14
-2.35009e-13
-1.32728e-12
-2.16998e-12
-1.0739e-12
-4.96252e-13
-2.84965e-13
-2.50449e-13
-3.61484e-13
-2.32428e-13
-2.34676e-13
-2.53473e-13
-1.4151e-13
-9.80799e-14
-9.64235e-14
-1.31071e-14
-5.6861e-14
-1.13921e-12
-2.12829e-12
-1.19286e-12
-5.57619e-13
-2.97883e-13
-2.12754e-13
-2.94369e-13
-2.42015e-13
-2.3507e-13
-2.24233e-13
-1.45992e-13
-8.78851e-14
-6.55854e-14
-5.53908e-14
6.69342e-14
-9.59283e-13
-2.07267e-12
-1.29527e-12
-5.94164e-13
-2.90207e-13
-1.92376e-13
-2.43176e-13
-2.39902e-13
-2.00049e-13
-1.85748e-13
-1.50948e-13
-6.31361e-14
-3.20543e-14
-2.81833e-14
1.17893e-13
-8.08401e-13
-2.03074e-12
-1.33429e-12
-5.94342e-13
-2.92553e-13
-1.89158e-13
-2.60337e-13
-2.47578e-13
-1.33277e-13
-1.61357e-13
-1.57424e-13
1.47154e-14
-1.43591e-14
1.39125e-13
1.67341e-13
-7.41528e-13
-1.98034e-12
-1.35942e-12
-6.18442e-13
-3.12784e-13
-1.91068e-13
-2.53636e-13
-2.71019e-13
-1.13762e-13
-1.60564e-13
-1.53728e-13
1.6299e-14
-3.34481e-15
1.39323e-13
1.42883e-13
-6.98963e-13
-1.93903e-12
-1.38433e-12
-6.30676e-13
-3.17577e-13
-1.78748e-13
-2.43449e-13
-2.84455e-13
-1.24478e-13
-1.6715e-13
-1.57566e-13
1.71469e-14
-2.03434e-15
1.05061e-13
1.2312e-13
-6.9218e-13
-1.87209e-12
-1.37781e-12
-6.4104e-13
-3.16866e-13
-1.84543e-13
-2.44077e-13
-2.67549e-13
-1.32161e-13
-1.64201e-13
-1.38638e-13
8.77679e-15
9.54578e-16
1.05989e-13
6.62064e-14
2.96439e-13
-3.81612e-13
2.77427e-13
1.94783e-13
-2.05867e-13
1.78977e-13
5.50478e-14
-8.49066e-14
8.40886e-14
4.77321e-14
-4.62913e-14
2.03957e-14
9.82249e-15
-4.57052e-15
-1.89319e-15
2.06963e-12
2.33705e-12
5.26391e-14
7.48823e-13
3.16264e-13
-2.30204e-14
3.30512e-13
1.71764e-13
-4.77262e-14
6.16775e-14
5.23918e-14
-4.76455e-14
1.24691e-14
6.46437e-15
8.44803e-16
2.1943e-12
1.97624e-12
2.40713e-13
5.75306e-13
2.51839e-13
1.33414e-13
3.4098e-13
1.03068e-13
7.60696e-14
7.83985e-14
1.04069e-16
1.58069e-14
1.07699e-14
-8.57866e-15
-1.43715e-15
2.56092e-12
1.9658e-12
3.02686e-13
8.33376e-13
1.65156e-13
2.74473e-13
4.17448e-13
7.07314e-14
1.87703e-13
2.16858e-13
-5.91721e-15
7.54356e-14
7.46166e-14
-3.62025e-14
-6.4706e-14
2.25663e-12
2.01287e-12
3.73119e-13
7.39712e-13
2.04661e-13
2.66914e-13
4.00958e-13
1.97631e-13
2.2736e-13
2.0921e-13
5.83313e-14
1.74623e-14
5.051e-14
-1.42989e-14
-8.268e-14
2.00727e-12
2.05179e-12
5.17063e-13
5.77024e-13
2.25403e-13
2.25056e-13
3.75196e-13
2.22259e-13
2.09175e-13
1.66044e-13
5.5866e-14
-4.45417e-15
-7.05741e-15
-3.61661e-14
-3.80164e-14
1.79207e-12
2.13588e-12
7.23801e-13
5.41993e-13
2.57664e-13
2.4183e-13
3.43361e-13
1.66823e-13
2.27398e-13
1.58526e-13
7.37527e-14
8.67359e-14
-2.20491e-14
5.20965e-14
1.44768e-13
1.5851e-12
2.17804e-12
9.22302e-13
5.18602e-13
2.80639e-13
2.54609e-13
3.47229e-13
1.90873e-13
2.2083e-13
2.26959e-13
1.30779e-13
1.23808e-13
7.68185e-14
1.68554e-14
2.35009e-13
1.32728e-12
2.16998e-12
1.0739e-12
4.96252e-13
2.84965e-13
2.50449e-13
3.61484e-13
2.32428e-13
2.34676e-13
2.53473e-13
1.4151e-13
9.80799e-14
9.64235e-14
1.31071e-14
5.6861e-14
1.13921e-12
2.12829e-12
1.19286e-12
5.57619e-13
2.97883e-13
2.12754e-13
2.94369e-13
2.42015e-13
2.3507e-13
2.24233e-13
1.45992e-13
8.78851e-14
6.55854e-14
5.53908e-14
-6.69342e-14
9.59283e-13
2.07267e-12
1.29527e-12
5.94164e-13
2.90207e-13
1.92376e-13
2.43176e-13
2.39902e-13
2.00049e-13
1.85748e-13
1.50948e-13
6.31361e-14
3.20543e-14
2.81833e-14
-1.17893e-13
8.08401e-13
2.03074e-12
1.33429e-12
5.94342e-13
2.92553e-13
1.89158e-13
2.60337e-13
2.47578e-13
1.33277e-13
1.61357e-13
1.57424e-13
-1.47154e-14
1.43591e-14
-1.39125e-13
-1.67341e-13
7.41528e-13
1.98034e-12
1.35942e-12
6.18442e-13
3.12784e-13
1.91068e-13
2.53636e-13
2.71019e-13
1.13762e-13
1.60564e-13
1.53728e-13
-1.6299e-14
3.34481e-15
-1.39323e-13
-1.42883e-13
6.98963e-13
1.93903e-12
1.38433e-12
6.30676e-13
3.17577e-13
1.78748e-13
2.43449e-13
2.84455e-13
1.24478e-13
1.6715e-13
1.57566e-13
-1.71469e-14
2.03434e-15
-1.05061e-13
-1.2312e-13
6.9218e-13
1.87209e-12
1.37781e-12
6.4104e-13
3.16866e-13
1.84543e-13
2.44077e-13
2.67549e-13
1.32161e-13
1.64201e-13
1.38638e-13
-8.77679e-15
-9.54578e-16
-1.05989e-13
-6.62064e-14
)
;
}
inlet
{
type calculated;
value nonuniform List<scalar>
15
(
-1299.9
-1300.2
-1299.9
-1299.9
-1300.2
-1299.9
-1299.9
-1300.2
-1299.9
-1299.9
-1300.2
-1299.9
-1299.9
-1300.2
-1299.9
)
;
}
inletWalls
{
type calculated;
value uniform 0;
}
outletInlet
{
type calculated;
value nonuniform List<scalar>
15
(
198.811
527.701
785.469
981.987
1128.46
1249.85
1366.91
1486.23
1606.24
1731.2
1878.37
2054.34
2138.31
1731.17
635.85
)
;
}
}
// ************************************************************************* //
| [
"brent.shambaugh@gmail.com"
] | brent.shambaugh@gmail.com | |
f5bd60b527ef48a625886f49e1e9686c1d946f75 | 95091219c4006af6622053e99425daf8d84c39e5 | /main.cpp | af6f9bed1b9a07eb6d9f955ef813a7e2250f9ee6 | [] | no_license | anuraags/vulkan-tutorial | 14bb8653d501ce22bc4f5dba5a0f8a7d99dfebd8 | 0d234987581f8d31bb34f912b2816e51bd19d405 | refs/heads/master | 2023-08-07T08:22:51.090697 | 2021-10-03T02:54:16 | 2021-10-03T02:54:16 | 411,900,128 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 445 | cpp | #define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/vec4.hpp>
#include <glm/mat4x4.hpp>
#include <iostream>
#include "VulkanApplication.h"
int main() {
VulkanApplication app("Vulkan Application", 800, 600);
try {
app.init();
while (app.step()) {};
app.cleanup();
}
catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
} | [
"anuraag.sridhar@gmail.com"
] | anuraag.sridhar@gmail.com |
820febb6955e2d22645372e9ca3696b56885ca16 | c8fc2703cce588d28dd9583e523f7f78378e3fd3 | /bit_manipulation/count_number_of_ones_in_1_to_n.cpp | 422f2f93b750324b2bcef82d6ce5e238478b6103 | [] | no_license | ngangwar962/C_and_Cpp_Programs | e4da2951b1a8c0091df26e363227488e279a9caa | 396d4313d2451e073811c0657f068829db10bcd5 | refs/heads/master | 2020-06-19T14:20:19.749116 | 2019-08-10T16:54:09 | 2019-08-10T16:54:09 | 196,741,346 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 268 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int i,j,k;
int n;
cin>>n;
long int count=0;
int NO_OF_BITS=sizeof(int)*8;
for(i=1;i<=n;i++)
{
for(j=0;j<NO_OF_BITS;j++)
{
if(i&1<<j)
{
count++;
}
}
}
cout<<count<<"\n";
return 0;
}
| [
"ngangwar962@gmail.com"
] | ngangwar962@gmail.com |
2b4830e1b2aa6cbba355e061747c4262afd32120 | 2d5db0df3c23f9251d7a71d4f42341078b31d6a8 | /t4.cpp | 4d561073e4eee455ba62958ef1870200d723d6f1 | [] | no_license | justfornamesake/coding | 381e7e0e6b1f25d325d8a8bd83321c5e5c43338d | 6fe2ecb61e0a28bc50573d0dfba106ab8bbe7ce0 | refs/heads/master | 2020-06-04T20:23:45.881340 | 2019-06-16T10:40:51 | 2019-06-16T10:40:51 | 192,178,973 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 926 | cpp | #include <bits/stdc++.h>
using namespace std;
struct node{
int data;
node *left;
node *right;
};
node *insert(node *root,int data){
if(root==NULL){
root=new node();
root->data=data;
root->left=root->right=NULL;
}
else if(root->data>=data){
root->left=insert(root->left,data);
}
else{
root->right=insert(root->right,data);
}
return root;
}
bool identical(node *a,node *b){
cout<<a->data<<" "<<b->data<<endl;
if(a==NULL && b==NULL)
return true;
if(a!=NULL && b!=NULL){
return
(
a->data ==b->data && identical(a->left,b->left) && identical(a->right,b->right)
);
}
return false;
}
int main(){
node *root=NULL;
root=insert(root,10);
root=insert(root,200);
root=insert(root,2992);
node *root1=NULL;
root1=insert(root1,10);
root1=insert(root1,200);
root1=insert(root1,2992);
bool ans=identical(root,root1);
cout<<ans<<endl;
} | [
"satyajeetjha06@gmail.com"
] | satyajeetjha06@gmail.com |
6e3ffb825ef2036af381a47e722ddddc0be639ac | c2d270aff0a4d939f43b6359ac2c564b2565be76 | /src/chrome/browser/ui/views/location_bar/location_bar_bubble_delegate_view.h | 32cb9e84ef28ee8107f6e297b7df2da1741d33a0 | [
"BSD-3-Clause"
] | permissive | bopopescu/QuicDep | dfa5c2b6aa29eb6f52b12486ff7f3757c808808d | bc86b705a6cf02d2eade4f3ea8cf5fe73ef52aa0 | refs/heads/master | 2022-04-26T04:36:55.675836 | 2020-04-29T21:29:26 | 2020-04-29T21:29:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,832 | h | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_VIEWS_LOCATION_BAR_LOCATION_BAR_BUBBLE_DELEGATE_VIEW_H_
#define CHROME_BROWSER_UI_VIEWS_LOCATION_BAR_LOCATION_BAR_BUBBLE_DELEGATE_VIEW_H_
#include "base/macros.h"
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_registrar.h"
#include "ui/views/bubble/bubble_dialog_delegate.h"
#include "ui/views/event_monitor.h"
namespace content {
class NotificationDetails;
class NotificationSource;
class WebContents;
};
// Base class for bubbles that are shown from location bar icons. The bubble
// will automatically close when the browser transitions in or out of fullscreen
// mode.
class LocationBarBubbleDelegateView : public views::BubbleDialogDelegateView,
public content::NotificationObserver {
public:
enum DisplayReason {
// The bubble appears as a direct result of a user action (clicking on the
// location bar icon).
USER_GESTURE,
// The bubble appears spontaneously over the course of the user's
// interaction with Chrome (e.g. due to some change in the feature's
// status).
AUTOMATIC,
};
// Constructs LocationBarBubbleDelegateView. Anchors the bubble to
// |anchor_view| when it is not nullptr or alternatively, to |anchor_point|.
// Registers with a fullscreen controller identified by |web_contents| to
// close the bubble if the fullscreen state changes.
LocationBarBubbleDelegateView(views::View* anchor_view,
const gfx::Point& anchor_point,
content::WebContents* web_contents);
// TODO(varkha): Delete this override and use the constructor above.
LocationBarBubbleDelegateView(views::View* anchor_view,
content::WebContents* web_contents);
~LocationBarBubbleDelegateView() override;
// Displays the bubble with appearance and behavior tailored for |reason|.
void ShowForReason(DisplayReason reason);
// content::NotificationObserver:
void Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) override;
// If the bubble is not anchored to a view, places the bubble in the top right
// (left in RTL) of the |screen_bounds| that contain web contents's browser
// window. Because the positioning is based on the size of the bubble, this
// must be called after the bubble is created.
void AdjustForFullscreen(const gfx::Rect& screen_bounds);
protected:
// The class listens for WebContentsView events and closes the bubble. Useful
// for bubbles that do not start out focused but need to close when the user
// interacts with the web view.
class WebContentMouseHandler : public ui::EventHandler {
public:
WebContentMouseHandler(LocationBarBubbleDelegateView* bubble,
content::WebContents* web_contents);
~WebContentMouseHandler() override;
void OnKeyEvent(ui::KeyEvent* event) override;
void OnMouseEvent(ui::MouseEvent* event) override;
void OnTouchEvent(ui::TouchEvent* event) override;
private:
LocationBarBubbleDelegateView* bubble_;
content::WebContents* web_contents_;
std::unique_ptr<views::EventMonitor> event_monitor_;
DISALLOW_COPY_AND_ASSIGN(WebContentMouseHandler);
};
// Closes the bubble.
virtual void CloseBubble();
private:
// Used to register for fullscreen change notifications.
content::NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(LocationBarBubbleDelegateView);
};
#endif // CHROME_BROWSER_UI_VIEWS_LOCATION_BAR_LOCATION_BAR_BUBBLE_DELEGATE_VIEW_H_
| [
"rdeshm0@aptvm070-6.apt.emulab.net"
] | rdeshm0@aptvm070-6.apt.emulab.net |
622b2caf41c8946d7dfb6b3e45ea115c59522d9b | badddc303f57c1f2bc62842efdfc7afbbc10e7f5 | /include/dynd/callables/unique_callable.hpp | 91f7edd7b68ef286d9c92a217b7b0a9dbb244e5a | [
"BSL-1.0",
"BSD-2-Clause"
] | permissive | corsy/libdynd | 9a144b277adca2c9d5412c8a62503cc0a595684e | 8d9c2aa8fc15017940602739f9a06eb7b9eed5ca | refs/heads/master | 2021-01-22T07:35:35.365650 | 2016-03-24T05:01:03 | 2016-03-24T05:01:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,602 | hpp | //
// Copyright (C) 2011-15 DyND Developers
// BSD 2-Clause License, see LICENSE.txt
//
#pragma once
#include <dynd/callables/base_callable.hpp>
#include <dynd/kernels/unique_kernel.hpp>
namespace dynd {
namespace nd {
class unique_callable : public base_callable {
public:
unique_callable() : base_callable(ndt::callable_type::make(ndt::make_type<void>(), {ndt::type("Fixed * Scalar")}))
{
}
void instantiate(char *DYND_UNUSED(static_data), char *data, kernel_builder *ckb,
const ndt::type &DYND_UNUSED(dst_tp), const char *DYND_UNUSED(dst_arrmeta),
intptr_t DYND_UNUSED(nsrc), const ndt::type *src_tp, const char *const *src_arrmeta,
kernel_request_t kernreq, intptr_t nkwd, const nd::array *kwds,
const std::map<std::string, ndt::type> &tp_vars)
{
const ndt::type &src0_element_tp = src_tp[0].extended<ndt::fixed_dim_type>()->get_element_type();
ckb->emplace_back<unique_kernel>(
kernreq, reinterpret_cast<const fixed_dim_type_arrmeta *>(src_arrmeta[0])->dim_size,
reinterpret_cast<const fixed_dim_type_arrmeta *>(src_arrmeta[0])->stride, src0_element_tp.get_data_size());
const callable &equal = nd::equal::get();
const ndt::type equal_src_tp[2] = {src0_element_tp, src0_element_tp};
equal.get()->instantiate(equal.get()->static_data(), data, ckb, ndt::make_type<bool1>(), NULL, 2, equal_src_tp,
NULL, kernel_request_single, nkwd, kwds, tp_vars);
}
};
} // namespace dynd::nd
} // namespace dynd
| [
"hi@irwinzaid.com"
] | hi@irwinzaid.com |
1cab063add36ecde484230c531735520bcb91cf3 | 30dd9ff200f97b525b069577471d23387b23970b | /src/sensing/driver/ublox/ublox_gps/include/ublox_gps/callback.h | 9db1834885c5cd3017d60335371387bbdcbb35fc | [] | permissive | ColleyLi/AutowareArchitectureProposal | cd544ef913e3c49852d385883c3e3ee5b518b1b8 | 80ac2a8823d342e5a1e34703dbde27e8e9b5cd98 | refs/heads/master | 2022-04-18T01:41:53.649137 | 2020-04-21T12:18:58 | 2020-04-21T12:18:58 | 257,659,506 | 2 | 0 | Apache-2.0 | 2020-04-21T17:03:50 | 2020-04-21T17:03:49 | null | UTF-8 | C++ | false | false | 8,438 | h | //==============================================================================
// Copyright (c) 2012, Johannes Meyer, TU Darmstadt
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the Flight Systems and Automatic Control group,
// TU Darmstadt, nor the names of its contributors may be used to
// endorse or promote products derived from this software without
// specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.
//==============================================================================
#ifndef UBLOX_GPS_CALLBACK_H
#define UBLOX_GPS_CALLBACK_H
#include <ros/console.h>
#include <ublox/serialization/ublox_msgs.h>
#include <boost/format.hpp>
#include <boost/function.hpp>
#include <boost/thread.hpp>
namespace ublox_gps {
/**
* @brief A callback handler for a u-blox message.
*/
class CallbackHandler {
public:
/**
* @brief Decode the u-blox message.
*/
virtual void handle(ublox::Reader& reader) = 0;
/**
* @brief Wait for on the condition.
*/
bool wait(const boost::posix_time::time_duration& timeout) {
boost::mutex::scoped_lock lock(mutex_);
return condition_.timed_wait(lock, timeout);
}
protected:
boost::mutex mutex_; //!< Lock for the handler
boost::condition_variable condition_; //!< Condition for the handler lock
};
/**
* @brief A callback handler for a u-blox message.
* @typedef T the message type
*/
template <typename T>
class CallbackHandler_ : public CallbackHandler {
public:
typedef boost::function<void(const T&)> Callback; //!< A callback function
/**
* @brief Initialize the Callback Handler with a callback function
* @param func a callback function for the message, defaults to none
*/
CallbackHandler_(const Callback& func = Callback()) : func_(func) {}
/**
* @brief Get the last received message.
*/
virtual const T& get() { return message_; }
/**
* @brief Decode the U-Blox message & call the callback function if it exists.
* @param reader a reader to decode the message buffer
*/
void handle(ublox::Reader& reader) {
boost::mutex::scoped_lock lock(mutex_);
try {
if (!reader.read<T>(message_)) {
ROS_DEBUG_COND(debug >= 2, "U-Blox Decoder error for 0x%02x / 0x%02x (%d bytes)",
static_cast<unsigned int>(reader.classId()), static_cast<unsigned int>(reader.messageId()),
reader.length());
condition_.notify_all();
return;
}
} catch (std::runtime_error& e) {
ROS_DEBUG_COND(debug >= 2, "U-Blox Decoder error for 0x%02x / 0x%02x (%d bytes)",
static_cast<unsigned int>(reader.classId()), static_cast<unsigned int>(reader.messageId()),
reader.length());
condition_.notify_all();
return;
}
if (func_) func_(message_);
condition_.notify_all();
}
private:
Callback func_; //!< the callback function to handle the message
T message_; //!< The last received message
};
/**
* @brief Callback handlers for incoming u-blox messages.
*/
class CallbackHandlers {
public:
/**
* @brief Add a callback handler for the given message type.
* @param callback the callback handler for the message
* @typedef.a ublox_msgs message with CLASS_ID and MESSAGE_ID constants
*/
template <typename T>
void insert(typename CallbackHandler_<T>::Callback callback) {
boost::mutex::scoped_lock lock(callback_mutex_);
CallbackHandler_<T>* handler = new CallbackHandler_<T>(callback);
callbacks_.insert(
std::make_pair(std::make_pair(T::CLASS_ID, T::MESSAGE_ID), boost::shared_ptr<CallbackHandler>(handler)));
}
/**
* @brief Add a callback handler for the given message type and ID. This is
* used for messages in which have the same structure (and therefore msg file)
* and same class ID but different message IDs. (e.g. INF, ACK)
* @param callback the callback handler for the message
* @param message_id the ID of the message
* @typedef.a ublox_msgs message with a CLASS_ID constant
*/
template <typename T>
void insert(typename CallbackHandler_<T>::Callback callback, unsigned int message_id) {
boost::mutex::scoped_lock lock(callback_mutex_);
CallbackHandler_<T>* handler = new CallbackHandler_<T>(callback);
callbacks_.insert(
std::make_pair(std::make_pair(T::CLASS_ID, message_id), boost::shared_ptr<CallbackHandler>(handler)));
}
/**
* @brief Calls the callback handler for the message in the reader.
* @param reader a reader containing a u-blox message
*/
void handle(ublox::Reader& reader) {
// Find the callback handlers for the message & decode it
boost::mutex::scoped_lock lock(callback_mutex_);
Callbacks::key_type key = std::make_pair(reader.classId(), reader.messageId());
for (Callbacks::iterator callback = callbacks_.lower_bound(key); callback != callbacks_.upper_bound(key);
++callback)
callback->second->handle(reader);
}
/**
* @brief Read a u-blox message of the given type.
* @param message the received u-blox message
* @param timeout the amount of time to wait for the desired message
*/
template <typename T>
bool read(T& message, const boost::posix_time::time_duration& timeout) {
bool result = false;
// Create a callback handler for this message
callback_mutex_.lock();
CallbackHandler_<T>* handler = new CallbackHandler_<T>();
Callbacks::iterator callback = callbacks_.insert(
(std::make_pair(std::make_pair(T::CLASS_ID, T::MESSAGE_ID), boost::shared_ptr<CallbackHandler>(handler))));
callback_mutex_.unlock();
// Wait for the message
if (handler->wait(timeout)) {
message = handler->get();
result = true;
}
// Remove the callback handler
callback_mutex_.lock();
callbacks_.erase(callback);
callback_mutex_.unlock();
return result;
}
/**
* @brief Processes u-blox messages in the given buffer & clears the read
* messages from the buffer.
* @param data the buffer of u-blox messages to process
* @param size the size of the buffer
*/
void readCallback(unsigned char* data, std::size_t& size) {
ublox::Reader reader(data, size);
// Read all U-Blox messages in buffer
while (reader.search() != reader.end() && reader.found()) {
if (debug >= 3) {
// Print the received bytes
std::ostringstream oss;
for (ublox::Reader::iterator it = reader.pos(); it != reader.pos() + reader.length() + 8; ++it)
oss << boost::format("%02x") % static_cast<unsigned int>(*it) << " ";
ROS_DEBUG("U-blox: reading %d bytes\n%s", reader.length() + 8, oss.str().c_str());
}
handle(reader);
}
// delete read bytes from ASIO input buffer
std::copy(reader.pos(), reader.end(), data);
size -= reader.pos() - data;
}
private:
typedef std::multimap<std::pair<uint8_t, uint8_t>, boost::shared_ptr<CallbackHandler> > Callbacks;
// Call back handlers for u-blox messages
Callbacks callbacks_;
boost::mutex callback_mutex_;
};
} // namespace ublox_gps
#endif // UBLOX_GPS_CALLBACK_H
| [
"yukky.saito@gmail.com"
] | yukky.saito@gmail.com |
c4642e5b1f9a79206c5a974caac0faefac399319 | dd6de2549e1ba47627b82cf408fd46072b7856f6 | /MXCommon/include/MxSoundManager.h | 878b2b1b0882aa92ce3234c9c6ffec717e32466b | [] | no_license | mylifecode/SYprojectcode | 36e5459a2527b9d45f2413c9b78f0f9fb9f6d4e2 | 7328a9b7667bc2d1d03204e84f41f8873b5c3680 | refs/heads/master | 2022-04-14T08:10:25.417006 | 2020-04-11T01:33:08 | 2020-04-11T01:33:08 | 195,399,969 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,283 | h | #pragma once
#include "MXCommon.h"
#include<string>
#include<map>
#include "bass.h"
/**
该类主要用于播放音频文件,可支持同时播放多个不同的音频文件,但不支持同时播放相同的音频文件
*/
class MXCOMMON_API MxSoundManager
{
private:
MxSoundManager(void);
~MxSoundManager(void);
public:
enum PlayState
{
PS_Playing,
PS_Stopped,
PS_NotReady,
PS_Paused,
PS_Error
};
static MxSoundManager* GetInstance();
/**
播放一个音频文件
fileName:音频文件的名字
stopOldSound:决定是否停止先前播放的音频。如果为false,如果再次播放先前已经打开的,并且当前正在播放的音频,那么不错任何事情
*/
bool Play(const std::string& fileName,bool stopOldSound = false);
void StopSound(const std::string& fileName);
void StopAllSound();
/** 清空所有导入的音频资源 */
void Clear();
void MuteDevice(bool mute);
private:
/** 如果发生错误,则返回true */
//bool CheckCmdError(MCIERROR error);
//int ExtractFileNameStartIndex(const std::string& fullFileName);
//PlayState _GetSoundState(const std::string& hashValue);
private:
std::map<std::string , HSTREAM> m_StreamInPlay;
//audiere::AudioDevicePtr m_pDevice;
float m_DeviceVolume;
};
| [
"332437798@qq.com"
] | 332437798@qq.com |
503fce962d04f92dc7fbf236171037ef175d27ba | e3dcfd12bd1c565283c1ee2c1cb06a003f01577d | /Scene_graph/Scene_graph/supervoxel_clustering.cpp | 3b0996dd0320eaa9c7279256330f7680c1afdd82 | [] | no_license | yifeishi/proactive-learning-on-scenes | a0957579f4e445fe74d50045d2dc5a4b6af563db | becda902f47a6c610a29e728d0dd159c4322e9ca | refs/heads/master | 2021-05-28T08:22:29.433283 | 2014-12-19T13:31:59 | 2014-12-19T13:31:59 | 28,232,013 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,114 | cpp | #include <pcl/point_types.h>
#include <pcl/impl/instantiate.hpp>
#include "supervoxel_clustering.hpp"
#include <pcl/octree/impl/octree_pointcloud_adjacency.hpp>
#include <pcl/octree/impl/octree_pointcloud.hpp>
#include <pcl/octree/impl/octree_base.hpp>
#include <pcl/octree/impl/octree_iterator.hpp>
template class pcl::SupervoxelClustering<pcl::PointXYZRGBA>;
template class pcl::SupervoxelClustering<pcl::PointXYZRGB>;
template class pcl::SupervoxelClustering<pcl::PointXYZ>;
typedef pcl::SupervoxelClustering<pcl::PointXYZ>::VoxelData VoxelDataT;
typedef pcl::SupervoxelClustering<pcl::PointXYZRGB>::VoxelData VoxelDataRGBT;
typedef pcl::SupervoxelClustering<pcl::PointXYZRGBA>::VoxelData VoxelDataRGBAT;
typedef pcl::octree::OctreePointCloudAdjacencyContainer<pcl::PointXYZ, VoxelDataT> AdjacencyContainerT;
typedef pcl::octree::OctreePointCloudAdjacencyContainer<pcl::PointXYZRGB, VoxelDataRGBT> AdjacencyContainerRGBT;
typedef pcl::octree::OctreePointCloudAdjacencyContainer<pcl::PointXYZRGBA, VoxelDataRGBAT> AdjacencyContainerRGBAT;
template class pcl::octree::OctreePointCloudAdjacencyContainer<pcl::PointXYZ, VoxelDataT>;
template class pcl::octree::OctreePointCloudAdjacencyContainer<pcl::PointXYZRGB, VoxelDataRGBT>;
template class pcl::octree::OctreePointCloudAdjacencyContainer<pcl::PointXYZRGBA, VoxelDataRGBAT>;
template class pcl::octree::OctreePointCloudAdjacency<pcl::PointXYZ, AdjacencyContainerT>;
template class pcl::octree::OctreePointCloudAdjacency<pcl::PointXYZRGB, AdjacencyContainerRGBT>;
template class pcl::octree::OctreePointCloudAdjacency<pcl::PointXYZRGBA, AdjacencyContainerRGBAT>;
//template class pcl::octree::OctreeBase<AdjacencyContainerRGBT, pcl::octree::OctreeContainerEmpty>;
//template class pcl::octree::OctreeBase<AdjacencyContainerRGBAT, pcl::octree::OctreeContainerEmpty>;
//template class pcl::octree::OctreeBreadthFirstIterator<pcl::octree::OctreeBase<AdjacencyContainerRGBT, pcl::octree::OctreeContainerEmpty> >;
//template class pcl::octree::OctreeBreadthFirstIterator<pcl::octree::OctreeBase<AdjacencyContainerRGBAT, pcl::octree::OctreeContainerEmpty> >;
| [
"hao.li@siat.ac.cn"
] | hao.li@siat.ac.cn |
b6e23df37484fbf584a1d0d925bdf422c641caa2 | 3b107aa31c9b8905410e72a5783f314d2bffa9cd | /range_tone/range_tone.ino | 689fb8444180a5e49949ff844293b539851f8a4a | [] | no_license | dcbriccetti/arduino-lessons | d530bd53ee4ea29989181075852be116523ac25a | 1b7b44a2893d51bdeadb8c35899359baca1ce9fa | refs/heads/master | 2020-04-20T02:07:20.609987 | 2019-09-13T00:51:58 | 2019-09-13T00:51:58 | 25,756,681 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,041 | ino | #include "SRF05.h"
#define TRIGGER 4
#define ECHO 5
#define LED 6
#define SPEAKER 12
#define MAX_CM 200
#define PLAYMODE_CONTINUOUS 1
#define PLAYMODE_ARPEGGIO 2
SRF05 Sensor(TRIGGER, ECHO, MAX_CM, 0);
void setup() {
pinMode(LED, OUTPUT);
Sensor.Unlock = true;
}
void loop() {
Sensor.Read();
float cm = Sensor.Distance;
int potValue = 500; // analogRead(A0);
if (cm > 0 && cm < MAX_CM) {
play(PLAYMODE_ARPEGGIO, cm, potValue);
digitalWrite(LED, HIGH);
} else {
digitalWrite(LED, LOW);
noTone(SPEAKER);
}
delay(10);
}
void play(int mode, float cm, int potValue) {
int noteLength;
const int maxNoteLength = 200;
switch (mode) {
case PLAYMODE_CONTINUOUS:
tone(SPEAKER, (MAX_CM - cm) * potValue / 50);
break;
case PLAYMODE_ARPEGGIO:
noteLength = map(cm, 0, MAX_CM, 20, maxNoteLength);
tone(SPEAKER, 262); // C 4
delay(noteLength);
tone(SPEAKER, 311); // E-flat 4
delay(noteLength);
noTone(SPEAKER);
delay(2 * noteLength);
}
}
| [
"daveb@davebsoft.com"
] | daveb@davebsoft.com |
77f2d99e66da0b272d3154088613f81db1f08618 | 8af1c8d72e6b7e9471987f945ebff059278da526 | /CMSIS/DSP/Testing/Include/Tests/DistanceTestsF32.h | fdddaed78998c16f60315872b8d35b5203bedb4d | [
"Apache-2.0"
] | permissive | WMXZ-EU/CMSIS_5 | 8899559de35d76516982536cd810f8af839e0c77 | 572825384134b9c7dcda421e357e9bcc433fb5fb | refs/heads/develop | 2021-01-12T14:54:15.304086 | 2020-06-09T17:18:14 | 2020-06-09T17:18:14 | 72,098,551 | 0 | 0 | Apache-2.0 | 2020-06-09T17:18:15 | 2016-10-27T10:42:38 | C | UTF-8 | C++ | false | false | 903 | h | #include "Test.h"
#include "Pattern.h"
class DistanceTestsF32:public Client::Suite
{
public:
DistanceTestsF32(Testing::testID_t id);
virtual void setUp(Testing::testID_t,std::vector<Testing::param_t>& paramsArgs,Client::PatternMgr *mgr);
virtual void tearDown(Testing::testID_t,Client::PatternMgr *mgr);
private:
#include "DistanceTestsF32_decl.h"
Client::Pattern<float32_t> inputA;
Client::Pattern<float32_t> inputB;
Client::Pattern<int16_t> dims;
Client::LocalPattern<float32_t> output;
Client::LocalPattern<float32_t> tmpA;
Client::LocalPattern<float32_t> tmpB;
// Reference patterns are not loaded when we are in dump mode
Client::RefPattern<float32_t> ref;
int vecDim;
int nbPatterns;
};
| [
"Christophe.Favergeon@arm.com"
] | Christophe.Favergeon@arm.com |
22133cd639ad554f28972202c16a8ae0442cd38c | f07ba658d2ab736bea063c89dfaa876d5ddaa483 | /factoria/TrianguloIsosceles.h | d3c11fca7fcc480c0c1b55dd5f64f176ff982db5 | [] | no_license | jmunozpoveda/patrones | b17d8915d6c2cfcb0efc504dcf603558f5c10a47 | b9bbb551f392e94ea21315f2e0396263eeb6518c | refs/heads/master | 2021-12-24T21:39:10.013210 | 2016-04-15T15:29:52 | 2016-04-15T15:29:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 228 | h | #ifndef __TRIANGULO_ISOSCELES__
#define __TRIANGULO_ISOSCELES__
#include "Triangulo.h"
class TrianguloIsosceles: public Triangulo
{
public:
TrianguloIsosceles(int l1, int l2, int l3);
char* getDescription();
};
#endif | [
"jmp4281@hotmail.com"
] | jmp4281@hotmail.com |
b510c78c5cef1a653341699ce09bf987aee537de | 6a165bd09d8303ba99ed25cee93af985fb361f41 | /main.cpp | e869f72ebf46f64999162aca796f88cdb3dcd294 | [] | no_license | Pashamks/Book-List | 80b257c1c7b9d8518d195df98e8de065d4fe5d4a | fad7d015cce0b445a8ce33eefea0008cf31a229e | refs/heads/main | 2023-06-20T10:10:53.492059 | 2021-07-10T13:08:00 | 2021-07-10T13:08:00 | 384,697,444 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 691 | cpp | #include "listwindow.h"
#include <QApplication>
#include<QLabel>
#include<QMovie>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
ListWindow w;
QFile stuleShitFile("C:/Users/38095/Desktop/Qt/lab_6/Obit.txt");
stuleShitFile.open(QFile::ReadOnly);
QString stuleShit1 = QLatin1String(stuleShitFile.readAll());
a.setStyleSheet(stuleShit1);
w.show();
QLabel *lbl = new QLabel;
QMovie *movie = new QMovie("C:/Users/38095/Desktop/loading.gif");
lbl->setMovie(movie);
lbl->setMinimumHeight(300);
lbl->setMinimumWidth(800);
lbl->show();
movie->start();
QTimer::singleShot(5450, lbl, SLOT(close()));
return a.exec();
}
| [
"74491257+Pashamks@users.noreply.github.com"
] | 74491257+Pashamks@users.noreply.github.com |
e422f12f8e6f132772baccebf1744af88fb03ba7 | 41f52b15ab4c256ed5579f65520d1dee949613b8 | /tensorflow/compiler/xla/service/hlo_graph_dumper_test.cc | 7b0f937f383a416f805a799bd6787afe15b324b0 | [
"Apache-2.0"
] | permissive | ychen404/TensorFlowPlus | c029ad2a77850cc6f141c13a4c10925e0a92d771 | d4fcbe7278b983b6f736acf2d948e1f7954ca7e6 | refs/heads/master | 2022-10-15T16:59:37.683864 | 2017-10-04T23:28:02 | 2017-10-04T23:28:02 | 210,258,338 | 1 | 0 | Apache-2.0 | 2022-10-04T23:54:20 | 2019-09-23T03:37:58 | C++ | UTF-8 | C++ | false | false | 4,635 | cc | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/hlo_graph_dumper.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/hlo_module.h"
#include "tensorflow/compiler/xla/service/hlo_opcode.h"
#include "tensorflow/compiler/xla/test.h"
#include "tensorflow/compiler/xla/tests/test_utils.h"
#include "tensorflow/compiler/xla/xla.pb.h"
#include "tensorflow/core/lib/strings/strcat.h"
namespace xla {
namespace {
using ::tensorflow::strings::StrCat;
using ::testing::HasSubstr;
string TestName() {
return ::testing::UnitTest::GetInstance()->current_test_info()->name();
}
class DotRenderer : public hlo_graph_dumper::GraphRendererInterface {
public:
string RenderGraph(const string& graph, GraphKind graph_kind,
const DebugOptions& debug_options) override {
return graph;
}
private:
string last_graph_;
};
XLA_REGISTER_GRAPH_RENDERER(DotRenderer, std::numeric_limits<int>::max());
TEST(HloGraphDumperTest, NestedFusion) {
HloComputation::Builder b("b");
// Build param0 + param1 + param2 + param3 + param4.
auto shape = ShapeUtil::MakeShape(F32, {10, 100});
std::vector<HloInstruction*> params;
for (int i = 0; i <= 4; ++i) {
params.push_back(b.AddInstruction(
HloInstruction::CreateParameter(i, shape, StrCat("param", i))));
}
std::vector<HloInstruction*> sums;
sums.push_back(b.AddInstruction(HloInstruction::CreateBinary(
shape, HloOpcode::kAdd, params[0], params[1])));
for (int i = 0; i <= 2; ++i) {
sums.push_back(b.AddInstruction(HloInstruction::CreateBinary(
shape, HloOpcode::kAdd, sums[i], params[i + 2])));
}
HloModule m(TestName());
m.AddEntryComputation(b.Build());
HloComputation* root_computation = m.entry_computation();
// Fuse into fusion(param0 + param1 + param2 + param3 + param4).
auto* outer_fusion = root_computation->CreateFusionInstruction(
{sums[3], sums[2], sums[1], sums[0]}, HloInstruction::FusionKind::kLoop);
// Fusing invalidates the pointers in sums -- the instructions are cloned when
// they're moved to the new computation. Get the updated pointers to sums.
std::vector<HloInstruction*> fused_sums;
for (auto* instr : outer_fusion->fused_instructions_computation()
->MakeInstructionPostOrder()) {
if (instr->opcode() == HloOpcode::kAdd) {
fused_sums.push_back(instr);
}
}
// Fuse into fusion(fusion(param0 + param1 + param2) + param3 + param4).
auto* inner_fusion =
outer_fusion->fused_instructions_computation()->CreateFusionInstruction(
{fused_sums[1], fused_sums[0]}, HloInstruction::FusionKind::kLoop);
// Generate the graph; all nodes should be present.
string graph = hlo_graph_dumper::DumpGraph(*root_computation, /*label=*/"",
DebugOptions());
for (const HloComputation* computation :
{root_computation, //
inner_fusion->fused_instructions_computation(),
outer_fusion->fused_instructions_computation()}) {
for (const HloInstruction* instruction : computation->instructions()) {
EXPECT_THAT(graph, HasSubstr(instruction->name()));
}
}
// Dump a neighborhood around one of the inner sum nodes. We don't really
// care that the outer nodes are omitted -- whether they are or not is based
// fiddly heuristics -- but we do care that the node we asked for is printed.
const HloInstruction* inner_sum = nullptr;
for (const HloInstruction* instruction :
inner_fusion->fused_instructions_computation()->instructions()) {
if (instruction->opcode() == HloOpcode::kAdd) {
inner_sum = instruction;
break;
}
}
ASSERT_NE(inner_sum, nullptr);
EXPECT_THAT(
hlo_graph_dumper::DumpNeighborhoodAround(*inner_sum, /*radius=*/1),
HasSubstr(inner_sum->name()));
}
} // anonymous namespace
} // namespace xla
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
3628ae5537a30b1dc5f6c40e21cc4750c1f11b8c | 01837a379a09f74f7ef43807533093fa716e71ac | /src/utils/xulrunner-sdk/nsIRedirectChannelRegistrar.h | 43b0eb5792f356f396f46d21f96ecfea195ad002 | [] | no_license | lasuax/jorhy-prj | ba2061d3faf4768cf2e12ee2484f8db51003bd3e | d22ded7ece50fb36aa032dad2cc01deac457b37f | refs/heads/master | 2021-05-05T08:06:01.954941 | 2014-01-13T14:03:30 | 2014-01-13T14:03:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,663 | h | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-m-rel-xr_w32_bld-000000000/build/netwerk/base/public/nsIRedirectChannelRegistrar.idl
*/
#ifndef __gen_nsIRedirectChannelRegistrar_h__
#define __gen_nsIRedirectChannelRegistrar_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class nsIChannel; /* forward declaration */
class nsIParentChannel; /* forward declaration */
/* starting interface: nsIRedirectChannelRegistrar */
#define NS_IREDIRECTCHANNELREGISTRAR_IID_STR "efa36ea2-5b07-46fc-9534-a5acb8b77b72"
#define NS_IREDIRECTCHANNELREGISTRAR_IID \
{0xefa36ea2, 0x5b07, 0x46fc, \
{ 0x95, 0x34, 0xa5, 0xac, 0xb8, 0xb7, 0x7b, 0x72 }}
class NS_NO_VTABLE nsIRedirectChannelRegistrar : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IREDIRECTCHANNELREGISTRAR_IID)
/* uint32_t registerChannel (in nsIChannel channel); */
NS_IMETHOD RegisterChannel(nsIChannel *channel, uint32_t *_retval) = 0;
/* nsIChannel linkChannels (in uint32_t id, in nsIParentChannel channel); */
NS_IMETHOD LinkChannels(uint32_t id, nsIParentChannel *channel, nsIChannel * *_retval) = 0;
/* nsIChannel getRegisteredChannel (in uint32_t id); */
NS_IMETHOD GetRegisteredChannel(uint32_t id, nsIChannel * *_retval) = 0;
/* nsIParentChannel getParentChannel (in uint32_t id); */
NS_IMETHOD GetParentChannel(uint32_t id, nsIParentChannel * *_retval) = 0;
/* void deregisterChannels (in uint32_t id); */
NS_IMETHOD DeregisterChannels(uint32_t id) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIRedirectChannelRegistrar, NS_IREDIRECTCHANNELREGISTRAR_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIREDIRECTCHANNELREGISTRAR \
NS_IMETHOD RegisterChannel(nsIChannel *channel, uint32_t *_retval); \
NS_IMETHOD LinkChannels(uint32_t id, nsIParentChannel *channel, nsIChannel * *_retval); \
NS_IMETHOD GetRegisteredChannel(uint32_t id, nsIChannel * *_retval); \
NS_IMETHOD GetParentChannel(uint32_t id, nsIParentChannel * *_retval); \
NS_IMETHOD DeregisterChannels(uint32_t id);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIREDIRECTCHANNELREGISTRAR(_to) \
NS_IMETHOD RegisterChannel(nsIChannel *channel, uint32_t *_retval) { return _to RegisterChannel(channel, _retval); } \
NS_IMETHOD LinkChannels(uint32_t id, nsIParentChannel *channel, nsIChannel * *_retval) { return _to LinkChannels(id, channel, _retval); } \
NS_IMETHOD GetRegisteredChannel(uint32_t id, nsIChannel * *_retval) { return _to GetRegisteredChannel(id, _retval); } \
NS_IMETHOD GetParentChannel(uint32_t id, nsIParentChannel * *_retval) { return _to GetParentChannel(id, _retval); } \
NS_IMETHOD DeregisterChannels(uint32_t id) { return _to DeregisterChannels(id); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIREDIRECTCHANNELREGISTRAR(_to) \
NS_IMETHOD RegisterChannel(nsIChannel *channel, uint32_t *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->RegisterChannel(channel, _retval); } \
NS_IMETHOD LinkChannels(uint32_t id, nsIParentChannel *channel, nsIChannel * *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->LinkChannels(id, channel, _retval); } \
NS_IMETHOD GetRegisteredChannel(uint32_t id, nsIChannel * *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetRegisteredChannel(id, _retval); } \
NS_IMETHOD GetParentChannel(uint32_t id, nsIParentChannel * *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetParentChannel(id, _retval); } \
NS_IMETHOD DeregisterChannels(uint32_t id) { return !_to ? NS_ERROR_NULL_POINTER : _to->DeregisterChannels(id); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsRedirectChannelRegistrar : public nsIRedirectChannelRegistrar
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIREDIRECTCHANNELREGISTRAR
nsRedirectChannelRegistrar();
private:
~nsRedirectChannelRegistrar();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsRedirectChannelRegistrar, nsIRedirectChannelRegistrar)
nsRedirectChannelRegistrar::nsRedirectChannelRegistrar()
{
/* member initializers and constructor code */
}
nsRedirectChannelRegistrar::~nsRedirectChannelRegistrar()
{
/* destructor code */
}
/* uint32_t registerChannel (in nsIChannel channel); */
NS_IMETHODIMP nsRedirectChannelRegistrar::RegisterChannel(nsIChannel *channel, uint32_t *_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* nsIChannel linkChannels (in uint32_t id, in nsIParentChannel channel); */
NS_IMETHODIMP nsRedirectChannelRegistrar::LinkChannels(uint32_t id, nsIParentChannel *channel, nsIChannel * *_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* nsIChannel getRegisteredChannel (in uint32_t id); */
NS_IMETHODIMP nsRedirectChannelRegistrar::GetRegisteredChannel(uint32_t id, nsIChannel * *_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* nsIParentChannel getParentChannel (in uint32_t id); */
NS_IMETHODIMP nsRedirectChannelRegistrar::GetParentChannel(uint32_t id, nsIParentChannel * *_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void deregisterChannels (in uint32_t id); */
NS_IMETHODIMP nsRedirectChannelRegistrar::DeregisterChannels(uint32_t id)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIRedirectChannelRegistrar_h__ */
| [
"joorhy@gmail.com"
] | joorhy@gmail.com |
455c10564e2438a8de1ac843ec885d09c385ea4b | 79d07f18c18e058efbf3a230f4e43bec3c2428c3 | /Modules/Source/Basic_MNIST_Test/Source/Basic_MNIST_Test.cpp | bc750d05bb1f5f94cec8a9685c375630e6813b50 | [
"MIT"
] | permissive | Robot-Fromage/ANN_MNIST_NumberGenerator | a2dc544b05fe5aae6b55f256e44b80030fcf5a76 | d448ae0523144c33b21f2df744587d2a5c09b7c0 | refs/heads/master | 2020-06-30T02:32:37.882794 | 2019-08-06T13:34:23 | 2019-08-06T13:34:23 | 200,694,025 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,812 | cpp | /*************************************************************************
*
* ANN_MNIST_NumberGenerator
*__________________
*
* Basic_MNIST_Test/main.cpp
* Layl
* Please refer to LICENSE.md
*/
#include <iostream>
#define DNN_USE_IMAGE_API
#include "tiny_dnn/tiny_dnn.h"
// rescale output to 0-100
template <typename Activation>
double rescale(double x) {
Activation a(1);
return 100.0 * (x - a.scale().first) / (a.scale().second - a.scale().first);
}
void convert_image(const std::string &imagefilename,
double minv,
double maxv,
int w,
int h,
tiny_dnn::vec_t &data) {
tiny_dnn::image<> img(imagefilename, tiny_dnn::image_type::grayscale);
tiny_dnn::image<> resized = resize_image(img, w, h);
// mnist dataset is "white on black", so negate required
std::transform(
resized.begin(), resized.end(), std::back_inserter(data),
[=](uint8_t c) { return (255 - c) * (maxv - minv) / 255.0 + minv; });
}
int main()
{
tiny_dnn::network<tiny_dnn::sequential> nn;
std::string model_dir_path = "Resources/TrainedModels";
nn.load( model_dir_path + "/BasicModel" );
// convert imagefile to vec_t
tiny_dnn::vec_t data;
std::string test_dir_path = "Resources/TestData";
convert_image( test_dir_path + "/test28.png", 0.0, 1.0, 28, 28, data);
// recognize
auto res = nn.predict(data);
std::vector<std::pair<double, int>> scores;
// sort & print top-3
for (int i = 0; i < 10; i++)
scores.emplace_back(rescale<tiny_dnn::tanh_layer>(res[i]), i);
sort(scores.begin(), scores.end(), std::greater<std::pair<double, int>>());
for (int i = 0; i < 3; i++)
std::cout << scores[i].second << "," << scores[i].first << std::endl;
return 0;
} | [
"code@clementberthaud.com"
] | code@clementberthaud.com |
5f2dfc1e2eacc1b3f5b10a1e3625696a9b2bb5af | 08d3e4ceb86c17559bcaf8e2b6f649eec7d295e4 | /dialog.h | b24dda153011510dbda1c18af81b7bf336d57ae5 | [] | no_license | logan011/Terminal_watch_client | 7bded30cfe98d1693e184c9bcb1bfb66380ead1e | d904ff6d3740837152cec248eb4f3867921ee48c | refs/heads/master | 2020-04-10T15:35:49.351826 | 2013-10-23T13:32:20 | 2013-10-23T13:32:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 429 | h | #ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include <QTime>
#include<QDate>
#include "widget.h"
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = 0);
~Dialog();
public slots:
void slotShowDialog();
void slotSaveData();
signals:
void sendtomain(date *op);
private:
Ui::Dialog *ui;
date *optiondata;
};
#endif // DIALOG_H
| [
"roman-ostash@yahoo.com"
] | roman-ostash@yahoo.com |
25d61aa27514968c502e7230d3bb62bd2a6f1a5c | 233a9c9d99557ce9e54da126c8c7cb813bb051d2 | /common/src/observer.h | 534fba4417ce7138d253fd2937f4323b6d9d7aa9 | [] | no_license | maattam/engine | 1c512b9bd43257c659489d3ab7b02575689b3ca5 | 562de4bf2ade38c6bc3ecd7050763f49f7fa7fbb | refs/heads/master | 2022-09-29T02:47:08.499123 | 2014-10-26T08:36:14 | 2014-10-26T08:36:14 | 269,517,821 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 408 | h | //
// Author : Matti Määttä
// Summary :
//
#ifndef OBSERVER_H
#define OBSERVER_H
#include "observable.h"
template<typename ObserverType>
class Observer
{
public:
Observer();
virtual ~Observer();
typedef Observable<ObserverType> ObservableType;
void _setObservable(ObservableType* obs);
private:
ObservableType* observable_;
};
#include "observer.inl"
#endif // OBSERVER_H | [
"lesetus@gmail.com"
] | lesetus@gmail.com |
c36d34ee93c58ad4514e12e645467d23537dce23 | 559207eb5beae4ba9fd638d19bd3009cbe3a6d11 | /src/third_party/chromium/src/base/id_map_unittest.cc | feb150b1dab2677ccb3e959735ac0542d8bf7ab3 | [
"Apache-2.0"
] | permissive | voku/mod-spdy | 2a8989668fe0c0f0de48c0b7ecd85b5b5b554ed1 | bcfb388cbc5415ee660c2b5dbcf61f6f43c2a5ca | refs/heads/master | 2023-04-05T09:50:46.847114 | 2015-03-19T17:58:09 | 2015-03-19T17:58:09 | 32,537,692 | 0 | 0 | NOASSERTION | 2023-04-04T01:40:41 | 2015-03-19T17:56:26 | C++ | UTF-8 | C++ | false | false | 4,603 | cc | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/id_map.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
class IDMapTest : public testing::Test {
};
class TestObject {
};
class DestructorCounter {
public:
explicit DestructorCounter(int* counter) : counter_(counter) {}
~DestructorCounter() { ++(*counter_); }
private:
int* counter_;
};
TEST_F(IDMapTest, Basic) {
IDMap<TestObject> map;
EXPECT_TRUE(map.IsEmpty());
EXPECT_EQ(0U, map.size());
TestObject obj1;
TestObject obj2;
int32 id1 = map.Add(&obj1);
EXPECT_FALSE(map.IsEmpty());
EXPECT_EQ(1U, map.size());
EXPECT_EQ(&obj1, map.Lookup(id1));
int32 id2 = map.Add(&obj2);
EXPECT_FALSE(map.IsEmpty());
EXPECT_EQ(2U, map.size());
EXPECT_EQ(&obj1, map.Lookup(id1));
EXPECT_EQ(&obj2, map.Lookup(id2));
map.Remove(id1);
EXPECT_FALSE(map.IsEmpty());
EXPECT_EQ(1U, map.size());
map.Remove(id2);
EXPECT_TRUE(map.IsEmpty());
EXPECT_EQ(0U, map.size());
map.AddWithID(&obj1, 1);
map.AddWithID(&obj2, 2);
EXPECT_EQ(&obj1, map.Lookup(1));
EXPECT_EQ(&obj2, map.Lookup(2));
}
TEST_F(IDMapTest, IteratorRemainsValidWhenRemovingCurrentElement) {
IDMap<TestObject> map;
TestObject obj1;
TestObject obj2;
TestObject obj3;
map.Add(&obj1);
map.Add(&obj2);
map.Add(&obj3);
{
IDMap<TestObject>::const_iterator iter(&map);
while (!iter.IsAtEnd()) {
map.Remove(iter.GetCurrentKey());
iter.Advance();
}
// Test that while an iterator is still in scope, we get the map emptiness
// right (http://crbug.com/35571).
EXPECT_TRUE(map.IsEmpty());
EXPECT_EQ(0U, map.size());
}
EXPECT_TRUE(map.IsEmpty());
EXPECT_EQ(0U, map.size());
}
TEST_F(IDMapTest, IteratorRemainsValidWhenRemovingOtherElements) {
IDMap<TestObject> map;
const int kCount = 5;
TestObject obj[kCount];
int32 ids[kCount];
for (int i = 0; i < kCount; i++)
ids[i] = map.Add(&obj[i]);
int counter = 0;
for (IDMap<TestObject>::const_iterator iter(&map);
!iter.IsAtEnd(); iter.Advance()) {
switch (counter) {
case 0:
EXPECT_EQ(ids[0], iter.GetCurrentKey());
EXPECT_EQ(&obj[0], iter.GetCurrentValue());
map.Remove(ids[1]);
break;
case 1:
EXPECT_EQ(ids[2], iter.GetCurrentKey());
EXPECT_EQ(&obj[2], iter.GetCurrentValue());
map.Remove(ids[3]);
break;
case 2:
EXPECT_EQ(ids[4], iter.GetCurrentKey());
EXPECT_EQ(&obj[4], iter.GetCurrentValue());
map.Remove(ids[0]);
break;
default:
FAIL() << "should not have that many elements";
break;
}
counter++;
}
}
TEST_F(IDMapTest, OwningPointersDeletesThemOnRemove) {
const int kCount = 3;
int external_del_count = 0;
DestructorCounter* external_obj[kCount];
int map_external_ids[kCount];
int owned_del_count = 0;
DestructorCounter* owned_obj[kCount];
int map_owned_ids[kCount];
IDMap<DestructorCounter> map_external;
IDMap<DestructorCounter, IDMapOwnPointer> map_owned;
for (int i = 0; i < kCount; ++i) {
external_obj[i] = new DestructorCounter(&external_del_count);
map_external_ids[i] = map_external.Add(external_obj[i]);
owned_obj[i] = new DestructorCounter(&owned_del_count);
map_owned_ids[i] = map_owned.Add(owned_obj[i]);
}
for (int i = 0; i < kCount; ++i) {
EXPECT_EQ(external_del_count, 0);
EXPECT_EQ(owned_del_count, i);
map_external.Remove(map_external_ids[i]);
map_owned.Remove(map_owned_ids[i]);
}
for (int i = 0; i < kCount; ++i) {
delete external_obj[i];
}
EXPECT_EQ(external_del_count, kCount);
EXPECT_EQ(owned_del_count, kCount);
}
TEST_F(IDMapTest, OwningPointersDeletesThemOnDestruct) {
const int kCount = 3;
int external_del_count = 0;
DestructorCounter* external_obj[kCount];
int owned_del_count = 0;
DestructorCounter* owned_obj[kCount];
{
IDMap<DestructorCounter> map_external;
IDMap<DestructorCounter, IDMapOwnPointer> map_owned;
for (int i = 0; i < kCount; ++i) {
external_obj[i] = new DestructorCounter(&external_del_count);
map_external.Add(external_obj[i]);
owned_obj[i] = new DestructorCounter(&owned_del_count);
map_owned.Add(owned_obj[i]);
}
}
EXPECT_EQ(external_del_count, 0);
for (int i = 0; i < kCount; ++i) {
delete external_obj[i];
}
EXPECT_EQ(external_del_count, kCount);
EXPECT_EQ(owned_del_count, kCount);
}
} // namespace
| [
"ptrck@blck.io"
] | ptrck@blck.io |
03b49aecc6c054e81c545e78a9f408b36c7e8f98 | d9cfe5dd9bcbd5e168c780c0f4ede892b9e9df63 | /pfs-debby/include/pfs/debby.hpp | 5cc07aa7e0e2cfd67405b0b8abd1efb516b5f809 | [] | no_license | semenovf/archive | c196d326d85524f86ee734adee74b2f090eac6ee | 5bc6d21d072292dedc9aa4d7a281bc75a1663441 | refs/heads/master | 2022-05-30T11:04:17.315475 | 2022-04-27T03:33:56 | 2022-04-27T03:33:56 | 130,155,339 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 252 | hpp | /**
* @file debby.hpp
* @author wladt
* @date Jan 14, 2014
*/
#ifndef __PFS_DEBBY_HPP__
#define __PFS_DEBBY_HPP__
#include <pfs/debby/debby.hpp>
#include <pfs/debby/database.hpp>
#include <pfs/debby/statement.hpp>
#endif /* __PFS_DEBBY_HPP__ */
| [
"fedor.v.semenov@gmail.com"
] | fedor.v.semenov@gmail.com |
a7f8dd8dfd8e404dc5756a57f963fa3efe5c2d4e | ad687256cd7763ffbb9f211129af69bc952ccc40 | /mainwindow.h | e497686922edb87fe29d6bc22cfe52d0f518f576 | [] | no_license | bkubicek/illuminat | 66c3376eda1f5cf73fe9c60dca1af6e109e99e9a | 50f8934e0cd931d03c1ef049aacd3fe21fd1f3b2 | refs/heads/master | 2021-01-25T03:27:20.389679 | 2014-09-18T07:02:38 | 2014-09-18T07:02:38 | 24,025,312 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 469 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "stlfile.h"
class QSlider;
class QPushButton;
class Motion;
class Illuminator;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
Illuminator *il;
QSlider *sl;
QPushButton *pbLoad;
QPushButton *pbRun;
public slots:
void slChanged(int);
void pbLoadClicked();
};
#endif // MAINWINDOW_H
| [
"kubicekätgmx.at"
] | kubicekätgmx.at |
e36b158d1d484da0b0e12e8fa8af410b1e9da5df | df986f7ce0b65230695b647d37ba5b3cae1fc524 | /ScrollableText/Font.cpp | 06cb25cc4941cb8b18432274d21b7e6c4673ec38 | [] | no_license | zsloss/scrollable-text | e3746c8003e7977d3d6d188a638704da5a0cc339 | a4a337e106e7c6b7f7b5113647cd5c34903988be | refs/heads/master | 2021-01-20T18:58:31.026378 | 2016-07-10T15:12:53 | 2016-07-10T15:12:53 | 60,432,575 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,714 | cpp | #include "Font.h"
#include <SDL_image.h>
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
Font::Font(const std::string name, SDL_Renderer *renderer)
{
_renderer = renderer;
load_info(name + ".fnt");
load_texture();
}
Font::~Font()
{
SDL_DestroyTexture(_texture);
_texture = nullptr;
_renderer = nullptr;
}
std::shared_ptr<Font> Font::get_font(const std::string name, SDL_Renderer *renderer) {
if (Font::_cache.find(name) != _cache.end()) {
return _cache[name];
}
auto font = std::make_shared<Font>(name, renderer);
_cache[name] = font;
return font;
}
bool Font::load_texture()
{
SDL_Surface *surface = IMG_Load(_image_filename.c_str());
if (surface == nullptr) {
printf("Load image error: %s\n", IMG_GetError());
}
else {
_texture = SDL_CreateTextureFromSurface(_renderer, surface);
SDL_FreeSurface(surface);
if (_texture == nullptr) {
printf("Create texture from surface error: %s\n", SDL_GetError());
}
else {
return true;
}
}
return false;
}
bool Font::load_info(const std::string filename) {
std::string line;
std::ifstream file(filename.c_str());
if (file.is_open()) {
while (std::getline(file, line)) {
if (line.substr(0, 2) == "co") { // "common"
auto it = line.cbegin();
_line_height = get_next_value(line, it);
}
else if (line.substr(0, 4) == "page") {
auto it = line.cbegin();
auto page_id = get_next_value(line, it);
_image_filename = get_next_string(line, it);
}
else if (line.substr(0, 5) == "char ") {
auto it = line.cbegin();
char glyph = static_cast<char>(get_next_value(line, it));
_glyph_info[glyph].sourceRect = { get_next_value(line, it), get_next_value(line, it), get_next_value(line, it), get_next_value(line, it) };
_glyph_info[glyph].xoffset = get_next_value(line, it);
_glyph_info[glyph].yoffset = get_next_value(line, it);
_glyph_info[glyph].xadvance = get_next_value(line, it);
}
}
}
return true;
}
int Font::get_next_value(std::string &line, std::string::const_iterator &it) {
// Move to the next '='
while (it != line.cend() && *it != '=') {
++it;
}
if (it == line.cend()) {
throw "Iterator past end of line";
}
// Move to the integer value
++it;
std::ostringstream ss;
while (it != line.cend() && *it != ' ') {
ss << *(it++);
}
return stoi(ss.str());
}
std::string Font::get_next_string(std::string &line, std::string::const_iterator &it) {
// Move to the next '='
while (it != line.cend() && *it != '=') {
++it;
}
if (it == line.cend()) {
throw "Iterator past end of line";
}
// Move to the integer value
it += 2;
std::ostringstream ss;
while (it != line.cend() && *it != '"') {
ss << *(it++);
}
return ss.str();
}
std::vector<std::string> Font::get_wrapped_lines(std::string &input, int width) {
std::vector<std::string> lines;
int x = 0;
std::string::const_iterator end_of_word, start_of_line, undefined = input.cend();
for (auto it = start_of_line = input.cbegin(); it != input.cend(); ++it) {
if (*it == '\n') {
lines.push_back(std::string(start_of_line, it));
start_of_line = it + 1;
end_of_word = undefined;
x = _glyph_info[*it].xadvance;
}
else if (*it == ' ') {
end_of_word = it;
x += _glyph_info[*it].xadvance;
}
else if (*it == '<' || *it == '>') {
}
else {
x += _glyph_info[*it].xadvance;
if (x >= width) {
if (end_of_word != undefined) {
lines.push_back(std::string(start_of_line, end_of_word));
it = start_of_line = end_of_word + 1;
x = _glyph_info[*it].xadvance;
}
else {
lines.push_back(std::string(start_of_line, it));
start_of_line = it;
x = _glyph_info[*it].xadvance;
}
end_of_word = undefined;
}
}
}
lines.push_back(std::string(start_of_line, input.cend()));
return lines;
}
int Font::get_line_height()
{
return _line_height;
}
int Font::get_xoffset(const char c)
{
return _glyph_info[c].xoffset;
}
int Font::get_yoffset(const char c)
{
return _glyph_info[c].yoffset;
}
int Font::get_xadvance(const char c)
{
return _glyph_info[c].xadvance;
}
void Font::set_colour(Uint8 r, Uint8 g, Uint8 b)
{
SDL_SetTextureColorMod(_texture, r, g, b);
}
void Font::render_char(const char c, int x, int y)
{
auto source = &_glyph_info[c].sourceRect;
auto dest = SDL_Rect{ x + get_xoffset(c), y + get_yoffset(c), source->w, source->h };
SDL_RenderCopy(_renderer, _texture, source, &dest);
}
std::unordered_map<std::string, std::shared_ptr<Font>> Font::_cache;
| [
"zachary.sloss@gmail.com"
] | zachary.sloss@gmail.com |
c31312d8a2bbe394e9b6142b76623379627d6f95 | 3ae912cbb3dcc1d0472f7ed0931f9718ba6b3da6 | /Console Library/Inventory.h | 1f91c61ec1493c71842f9ddae611c58bceb74579 | [] | no_license | black-licorice/Library | 4b98d10cf444a3338f395c2cb3495f941b7cb53e | 5914a03221a94e622f1fe4d3c8d607543f888997 | refs/heads/master | 2023-03-05T17:08:10.104488 | 2021-02-20T11:10:32 | 2021-02-20T11:10:32 | 336,062,095 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 415 | h | #pragma once
#include "Book.h"
#include <vector>
class Inventory
{
private:
std::vector<Book> m_Books;
Book* m_getBookById(int index, std::string title);
public:
int getVBooksSize();
Book getCopyAtIndex(int index);
void addBook(Book book);
void removeBookByTitle(std::string title);
Book* findBookByTitle(std::string title);
int checkInOutByTitle(std::string title, std::string inOut);
void saveBooks();
}; | [
"judahtrembe@gmail.com"
] | judahtrembe@gmail.com |
2622e8d2ec78494866b39a51e322ae414a50e775 | f37473ebcd9f96dc5e7c53baf19646d453a77c6e | /nmcs-iter-level-2.cpp | fc7690e1fd17fcd17add2d8dbfa3353c77bf08ff | [] | no_license | jamek1990/MCTS | 4139440c244ea97562c147375038c9d3964ec41c | 4787cc3db983c47f84e3cc20ecb315ef7856216e | refs/heads/master | 2023-06-09T14:29:45.742766 | 2023-05-31T11:06:43 | 2023-05-31T11:06:43 | 7,212,891 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,718 | cpp | #include<iostream>
#include<vector>
#include<algorithm>
#include <cstdio>
#include <sstream>
#include <iostream>
#include <fstream>
#include <math.h>
#include <time.h>
//#include <gsl/gsl_math.h>
//#include <gsl/gsl_rng.h>
//#include <gsl/gsl_randist.h>
//#include "generator.h"
using namespace std;
//generator g;
//
using namespace std;
const int SIZE = 40;
int rekord[]={-4, 3, -4, 3, -4, -1, 0, -1, -4, -1, 0, -1, -2, -2, -4, 0, 0, -4, 3, -4, -1, -4, 3, -4, 2, 6, 2, 6, 2, 2, -2, 5, -2, 5, 2, 5, -1, 6, -1, 6, -1, 2, 0, 2, -4, 2, 0, 2, -2, 3, 0, 5, -4, 1, 1, -1, 0, -1, 4, -1, 0, 4, 2, 6, -2, 2, 1, 4, -1, 6, 3, 2, 1, 2, 0, 2, 4, 2, -2, 4, -2, 4, 2, 4, -2, 1, -2, 5, -2, 1, -1, 0, -4, 3, 0, -1, -1, 1, -1, 2, -1, -2, 0, 0, -2, 2, 2, -2, 1, 1, 2, 2, -2, -2, 2, 0, -2, 4, 2, 0, 2, 1, 2, 2, 2, -2, 0, 3, -2, 5, 2, 1, -3, 3, -4, 3, 0, 3, 0, 1, 0, 3, 0, -1, 3, 6, 3, 6, -1, 2, 0, 6, 0, 6, -4, 2, -3, 1, -4, 1, 0, 1, 1, 6, -1, 6, 3, 6, 0, 7, 0, 7, 0, 3, 3, 3, 0, 6, 4, 2, 1, 3, 1, 6, 1, 2, -3, 4, 0, 7, -4, 3, 4, 3, 0, 3, 4, 3, 3, 1, -1, 5, 3, 1, -3, 0, -3, 4, -3, 0, 1, 0, -3, 4, 1, 0, 3, 4, 0, 7, 4, 3, 4, 1, 0, 1, 4, 1, 0, -3, -4, 1, 0, -3, -5, -2, -1, 2, -5, -2, 1, -2, 1, 2, 1, -2, 5, 4, 5, 4, 1, 0, 3, 5, 3, 6, 3, 2, 4, 5, 4, 5, 0, 1, 4, -5, 0, -1, 4, -5, 3, 0, 3, 0, -1, -4, 4, 6, 4, 6, 0, 2, 4, 0, 0, 0, 4, 0, 3, -2, 3, 2, 3, -2, 4, 4, 4, 6, 4, 2, 4, -2, 4, 2, 4, -2, 0, -2, -1, -2, 3, -2, 0, -5, 4, -1, 0, -5, 6, 4, 2, 4, 6, 4, -2, 0, -4, 2, 0, -2, -2, -4, 2, 0, -2, -4, 0, -6, 0, -2, 0, -6, 5, 3, 6, 4, 2, 0, -5, 0, -5, 0, -1, 0, -2, -3, -2, 1, -2, -3, 5, 5, 5, 5, 5, 1, 6, 2, 2, 6, 6, 2, -3, -2, -5, 0, -1, -4, -3, -4, 1, 0, -3, -4, 6, 5, 2, 5, 6, 5, 6, 6, 6, 6, 2, 2, 7, 3, 7, 3, 3, -1, -4, -2, -5, -2, -1, -2, -3, -3, -3, 0, -3, -4, 6, 3, 6, 6, 6, 2, 8, 2, 4, 6, 8, 2, -5, -3, -1, 1, -5, -3, 8, 3, 4, 3, 8, 3, 7, 4, 7, 4, 3, 0, 7, 2, 4, 2, 8, 2, -4, -3, -5, -3, -1, -3, 8, 1, 4, 5, 8, 1, 6, 1, 8, 3, 4, -1, -5, -4, -1, 0, -5, -4, 7, 1, 4, 1, 8, 1, -4, -4, -5, -4, -1, -4, 7, 0, 7, 4, 7, 0, 6, 0, 8, 2, 4, -2, -4, -5, -4, -1, -4, -5, 8, -1, 4, 3, 8, -1, 8, 0, 4, 0, 8, 0, 8, -2, 8, 2, 8, -2, 7, -1, 4, 2, 8, -2, 6, -1, 4, -1, 8, -1, 6, -2, 6, 2, 6, -2, 7, -2, 3, 2, 7, -2, 7, -3, 3, 1, 7, -3, 5, -2, 3, -2, 7, -2, 7, -4, 7, 0, 7, -4, 5, -3, 5, 1, 5, -3, 6, -3, 2, 1, 6, -3, 4, -3, 8, 1, 4, -3, 6, -4, 2, 0, 6, -4, 4, -4, 8, 0, 4, -4, 3, -3, 3, -3, 7, -3, 5, -4, 3, -4, 7, -4, 1, -3, -1, -3, 3, -3, 1, -5, 4, -2, 0, -6, 6, -5, 2, -1, 6, -5, -1, -5, 3, -1, -1, -5, 1, -6, 1, -2, 1, -6, 6, -6, 6, -2, 6, -6, -1, -6, -1, -2, -1, -6, -5, -1, -5, -1, -1, -5, 5, -5, 2, -2, 6, -6, -2, -5, -5, -2, -1, -6, -6, -2, -2, 2, -6, -2, 4, -6, 8, -2, 4, -6, 3, -5, 0, -2, 4, -6, 2, -5, -1, -5, 3, -5, 7, -5, 3, -5, 7, -5, 3, -6, 3, -2, 3, -6, 2, -6, 2, -2, 2, -6, 0, -7, 4, -3, 0, -7, 4, -7, 0, -3, 4, -7, 2, -7, 6, -3, 2, -7, -2, -6, -2, -6, 2, -6, 5, -6, 2, -6, 6, -6, 4, -8, 4, -4, 4, -8, 3, -8, -1, -4, 3, -8, -2, -7, -2, -3, -2, -7, -3, -5, -6, -2, -2, -6, 5, -7, 5, -3, 5, -7, 3, -7, 0, -4, 4, -8, -5, -5, -5, -5, -1, -5, 3, -9, 7, -5, 3, -9, 1, -7, 1, -7, 5, -7, -5, -6, -5, -2, -5, -6, -6, -6, -2, -2, -6, -6, 3, -10, 3, -6, 3, -10, 2, -8, -1, -5, 3, -9, 0, -8, 4, -4, 0, -8, 1, -8, 0, -8, 4, -8, 2, -9, -1, -6, 3, -10, 2, -10, 2, -6, 2, -10, 1, -10, 5, -6, 1, -10, 1, -9, 1, -6, 1, -10, -1, -7, -2, -6, 2, -10, 0, -10, 4, -6, 0, -10, -3, -7, -3, -7, 1, -7, -1, -10, -1, -10, 3, -10, 0, -9, 0, -6, 0, -10, -1, -9, -1, -9, 3, -9, -2, -11, 2, -7, -2, -11, -1, -8, -1, -6, -1, -10, -3, -6, -5, -4, -1, -8, -4, -6, -6, -6, -2, -6, -3, -8, -3, -4, -3, -8, -2, -8, -5, -5, -1, -9, -4, -9, 0, -5, -4, -9, -4, -8, -4, -8, 0, -8, -4, -7, -4, -5, -4, -9, -5, -9, -1, -5, -5, -9, -2, -9, -5, -6, -1, -10, -5, -8, -1, -4, -5, -8, -3, -9, -5, -9, -1, -9, -2, -10, -2, -7, -2, -11, -4, -10, 0, -6, -4, -10, -5, -7, -6, -6, -2, -10, -5, -10, -5, -6, -5, -10, -6, -8, -2, -4, -6, -8, -3, -10, -5, -10, -1, -10, -6, -7, -6, -7, -2, -11, -4, -11, 0, -7, -4, -11, -7, -7, -7, -7, -3, -7, -3, -11, -7, -7, -3, -11, -3, -12, -3, -8, -3, -12, -4, -12, 0, -8, -4, -12, -4, -13, -4, -9, -4, -13, -7, -8, -3, -4, -7, -8, -6, -9, -7, -8, -3, -12, -6, -5, -6, -5, -6, -9, -8, -8, -8, -8, -4, -8};
struct point{
int x;
int y;
};
inline int hash_point(point p){
return SIZE*p.y+p.x;
}
struct move{
point bgn;
short int dir; //0-SW 1-S 2-SE 3-E
point pnt;
};
bool operator==(const move& m1, const move& m2){
if(m1.bgn.x!=m2.bgn.x)return false;
if(m1.bgn.y!=m2.bgn.y)return false;
if(m1.pnt.x!=m2.pnt.x)return false;
if(m1.pnt.y!=m2.pnt.y)return false;
if(m1.dir!=m2.dir)return false;
return true;
}
inline int hash_move(move m){
return hash_point(m.bgn)*4+m.dir;
}
move available_moves[100000];
int available_moves_size = 0;
bool points[SIZE][SIZE];
point points_clear[1000];
short int points_clear_size=0;
bool connections[SIZE*SIZE][SIZE*SIZE];
point connections_clear[1000];
short int connections_clear_size = 0;
move save_moves[1000];
short int save_moves_size=0;
int dir_x[4]={-1,0,1,1};
int dir_y[4]={1,1,1,0};
move pop[1000];
short int pop_size =0;
point p[36];
void cross(){
p[0].x=0; p[0].y=0;p[1].x=0; p[1].y=1;
p[2].x=0; p[2].y=2;p[3].x=0; p[3].y=3;
p[4].x=1; p[4].y=3;p[5].x=2; p[5].y=3;
p[6].x=3; p[6].y=3;p[7].x=3; p[7].y=4;
p[8].x=3; p[8].y=5;p[9].x=3; p[9].y=6;
p[10].x=4; p[10].y=6;p[11].x=5; p[11].y=6;
p[12].x=6; p[12].y=6;p[13].x=6; p[13].y=5;
p[14].x=6; p[14].y=4;p[15].x=6; p[15].y=3;
p[16].x=7; p[16].y=3;p[17].x=8; p[17].y=3;
p[18].x=9; p[18].y=3;p[19].x=9; p[19].y=2;
p[20].x=9; p[20].y=1;p[21].x=9; p[21].y=0;
p[22].x=8; p[22].y=0;p[23].x=7; p[23].y=0;
p[24].x=6; p[24].y=0;p[25].x=6; p[25].y=-1;
p[26].x=6; p[26].y=-2;p[27].x=6; p[27].y=-3;
p[28].x=5; p[28].y=-3;p[29].x=4; p[29].y=-3;
p[30].x=3; p[30].y=-3;p[31].x=3; p[31].y=-2;
p[32].x=3; p[32].y=-1;p[33].x=3; p[33].y=0;
p[34].x=2; p[34].y=0;p[35].x=1; p[35].y=0;
}
/*#######################################################################
Funkcja: EXTEND
Argumenty: move m
Zwraca: bool czy ruch jest polaczony
#######################################################################*/
inline bool extend(move m){
if(connections[SIZE*m.bgn.y+m.bgn.x][SIZE*(m.bgn.y-dir_y[m.dir])+m.bgn.x-dir_x[m.dir]])
return true;
if(connections[SIZE*(m.bgn.y+4*dir_y[m.dir])+m.bgn.x+4*dir_x[m.dir]][SIZE*(m.bgn.y+5*dir_y[m.dir])+m.bgn.x+5*dir_x[m.dir]])
return true;
return false;
}
/*#######################################################################
Funkcja: ADD_NEW_MOVE
Argumenty: point pt
Zwraca: int liczba ruchĂłw dodanych
Cel: dodaje nowe moves po dodaniu punktu, aktualizuje wektor moves i moves2.
jest odporna na bezsensowne moves bez polaczen.
#######################################################################*/
int add_new_move(point pt){
int wynik =0;
int ill =0;
int pon =0;
int ok =0;
move rucht;
point ptg;
//poziomo
for(int i=0;i<9;i++){
if(points[pt.x-4+i][pt.y]){
if(ok > 0){
if(!connections[SIZE*pt.y+pt.x-4+i-1][SIZE*pt.y+pt.x-4+i])
ok += 1;
else{
pon = 0;
ok = 1;
}
}else{
ok = 1;
}
}else{
if(pon == 1){
ok = pt.x-4+i-ptg.x;
ptg.x = pt.x-4+i;
ptg.y = pt.y;
}
else{
pon = 1;
ptg.x = pt.x-4+i;
ptg.y = pt.y;
ok += 1;
}
}
if(ok > 4 && (pon == 1 && (pt.x-4+i-ptg.x)<5)){
rucht.pnt=ptg;
rucht.bgn.x=pt.x-4+i-4;
rucht.bgn.y=pt.y;
rucht.dir=3;
if(extend(rucht)){
while(ill--){
available_moves_size--;
wynik--;
}
available_moves[available_moves_size]=rucht;
available_moves_size++;
wynik++;
break;
}
available_moves[available_moves_size]=rucht;
available_moves_size++;
ill++;
wynik++;
}
}
//pionowo
ok = 0;
pon = 0;
ill=0;
for(int i = 0;i<9;i++){
if(points[pt.x][pt.y-4+i]){
if(ok > 0){
if(!connections[SIZE*(pt.y-4+i-1) + pt.x][SIZE*(pt.y-4+i) + pt.x]){
ok += 1;
}
else{
pon =0;
ok =1;
}
}
else{
ok = 1;
}
}else{
if(pon == 1){
ok = pt.y-4+i-ptg.y;
ptg.x = pt.x;
ptg.y = pt.y-4+i;
}
else{
pon = 1;
ptg.x = pt.x;
ptg.y = pt.y-4+i;
ok += 1;
}
}
if(ok > 4 && (pon == 1 && (pt.y-4+i-ptg.y)<5)){
rucht.pnt=ptg;
rucht.bgn.x=pt.x;
rucht.bgn.y=pt.y-4+i-4;
rucht.dir=1;
if(extend(rucht)){
while(ill--){
available_moves_size--;
wynik--;
}
available_moves[available_moves_size]=rucht;
available_moves_size++;
wynik++;
break;
}
available_moves[available_moves_size]=rucht;
available_moves_size++;
ill++;
wynik++;
}
}
//ukosL
ok = 0;
pon = 0;
ill=0;
for(int i=0;i<9;i++){
if(points[pt.x-4+i][pt.y-4+i]){
if(ok > 0){
if(!connections[SIZE*(pt.y-4+i-1)+pt.x-4+i-1][SIZE*(pt.y-4+i)+pt.x-4+i]){
ok +=1;
}else{
pon = 0;
ok = 1;
}
}
else{
ok = 1;
}
}else{
if(pon == 1){
ok = pt.x-4+i-ptg.x;
ptg.x = pt.x-4+i;
ptg.y = pt.y-4+i;
}else{
pon = 1;
ptg.x = pt.x-4+i;
ptg.y = pt.y-4+i;
ok += 1;
}
}
if(ok > 4 && (pon == 1 && (pt.x-4+i-ptg.x)<5)){
rucht.pnt=ptg;
rucht.bgn.x=pt.x-4+i-4;
rucht.bgn.y=pt.y-4+i-4;
rucht.dir=2;
if(extend(rucht)){
while(ill--){
available_moves_size--;
wynik--;
}
available_moves[available_moves_size]=rucht;
available_moves_size++;
wynik++;
break;
}
available_moves[available_moves_size]=rucht;
available_moves_size++;
ill++;
wynik++;
}
}
//ukos_P
ok = 0;
pon = 0;
ill=0;
for(int i=0;i<9;i++){
if(points[pt.x+4-i][pt.y-4+i]){
if(ok > 0){
if(!connections[SIZE*(pt.y-4+i-1)+pt.x+4-i+1][SIZE*(pt.y-4+i)+pt.x+4-i]){
ok += 1;
}else{
ok = 1;
pon = 0;
}
}
else{
ok = 1;
}
}
else{
if(pon == 1){
ok = pt.y-4+i-ptg.y;
ptg.x = pt.x+4-i;
ptg.y = pt.y-4+i;
}
else{
pon = 1;
ptg.x = pt.x+4-i;
ptg.y = pt.y-4+i;
ok += 1;
}
}
if(ok > 4 && (pon == 1 && (pt.y-4+i-ptg.y)<5)){
rucht.pnt=ptg;
rucht.bgn.x=pt.x+4-i+4;
rucht.bgn.y=pt.y-4+i-4;
rucht.dir=0;
if(extend(rucht)){
while(ill--){
available_moves_size--;
wynik--;
}
available_moves[available_moves_size]=rucht;
available_moves_size++;
wynik++;
break;
}
available_moves[available_moves_size]=rucht;
available_moves_size++;
ill++;
wynik++;
}
}
return wynik;
}
/*#######################################################################
Funckja: ADD_POINT
Argumenty: point pt
Zwraca: void
Cel: aktualizuje tablice table po dodaniu nowego punktu, wywoluje funkcej
ADD_NEW_MOVE.
#######################################################################*/
void add_point(point pnt){
points[pnt.x][pnt.y] = true;
add_new_move(pnt);
}
/*#######################################################################
Funckja: add_connection
Argumenty: move m
Zwraca: void
Cel: dodaje polaczenie, uaktualnie tablice connections[][] oraz wektor
do czyszczenia connections_clear
#######################################################################*/
point con;
void add_connection(move m){
for(int i=0;i<4;i++){
con.x=SIZE*(m.bgn.y+i*dir_y[m.dir])+m.bgn.x+i*dir_x[m.dir];
con.y=SIZE*(m.bgn.y+(i+1)*dir_y[m.dir])+m.bgn.x+(i+1)*dir_x[m.dir];
connections[con.x][con.y]=true;
connections[con.y][con.x]=true;
connections_clear_size++;
connections_clear[connections_clear_size]=con;
}
}
/*#######################################################################
Funckja: clear_all
Argumenty: void
Zwraca: void
Cel: usuwa wszytskie punkty z planszy i polaczenia
#######################################################################*/
void clear_all(){
while(connections_clear_size!=0){
connections[connections_clear[connections_clear_size].x][connections_clear[connections_clear_size].y]=false;
connections[connections_clear[connections_clear_size].y][connections_clear[connections_clear_size].x]=false;
connections_clear_size--;
}
while(points_clear_size!=0){
points[points_clear[points_clear_size].x][points_clear[points_clear_size].y]=false;
points_clear_size--;
}
}
/*#######################################################################
Funckja: clear_ile
Argumenty: ile
Zwraca: void
Cel: usuwa punkty z planszy i polaczenia do pozycji z ile
#######################################################################*/
void clear_ile(int ile){
while(connections_clear_size!=4*ile){
connections[connections_clear[connections_clear_size].x][connections_clear[connections_clear_size].y]=false;
connections[connections_clear[connections_clear_size].y][connections_clear[connections_clear_size].x]=false;
connections_clear_size--;
}
while(points_clear_size!=ile){
points[points_clear[points_clear_size].x][points_clear[points_clear_size].y]=false;
points_clear_size--;
}
}
void set_cross(){
cross();
point temp;
for(int i=0;i<36;i++){
temp.x = p[i].x+16;
temp.y = p[i].y+18;
add_point(temp);
}
}
void show_points(){
for(int i=0;i<SIZE;i++){
for(int j=0;j<SIZE;j++){
if(points[i][j])
cout<<"x";
else
cout<<" ";
}
cout<<"\n";
}
cout<<"\n";
}
/*#######################################################################
Funkcja: remove
Argumenty: brak
Zwraca: void
Cel: usuwa bledne ruchy z wektora avaliable_moves
#######################################################################*/
void remove(){
pop_size=0;
move m;
int ok;
for(int ii=0;ii<available_moves_size;ii++){
m=available_moves[ii];
if(points[m.pnt.x][m.pnt.y])
continue;
ok=1;
for(int i=0;i<4;i++)
if(connections[SIZE*(m.bgn.y+i*dir_y[m.dir])+m.bgn.x+i*dir_x[m.dir]][SIZE*(m.bgn.y+(i+1)*dir_y[m.dir])+m.bgn.x+(i+1)*dir_x[m.dir]]){
ok=0;
break;
}
if(ok){
pop[pop_size]=available_moves[ii];
pop_size++;
}
}
for(int i =0;i<pop_size;i++)
available_moves[i]=pop[i];
available_moves_size=pop_size;
}
char name[10];
void save(int score){
move m;
cout<<"\a";
ostringstream os;
os << score;
string str = os.str();
str = str+".txt";
for(int i=0; i<str.size(); i++)
name[i]=str[i];
std::ofstream o(name);
for(int i=0;i<score;i++){
m=save_moves[i];
o<<m.pnt.x-20<<" "<<m.pnt.y-19<<" "<<m.bgn.x-20<<" "<<m.bgn.y-19<<" "<<m.bgn.x+4*dir_x[m.dir]-20<<" "<<m.bgn.y+4*dir_y[m.dir]-19<<"\n";
}
}
inline bool check_move(move m){
if(points[m.pnt.x][m.pnt.y])
return false;
if(connections[SIZE*m.bgn.y+m.bgn.x][SIZE*(m.bgn.y+dir_y[m.dir])+m.bgn.x+dir_x[m.dir]])
return false;
if(connections[SIZE*(m.bgn.y+3*dir_y[m.dir])+m.bgn.x+3*dir_x[m.dir]][SIZE*(m.bgn.y+4*dir_y[m.dir])+m.bgn.x+4*dir_x[m.dir]])
return false;
return true;
}
void check_con(){
for(int i=0;i<SIZE*SIZE;i++)
for(int j=0;j<SIZE*SIZE;j++)
if(connections[i][j])
cout<<"dupa";
}
void dodaj(move move_exe){
add_connection(move_exe);
add_point(move_exe.pnt);
points_clear_size++;
points_clear[points_clear_size]=move_exe.pnt;
save_moves[save_moves_size]=move_exe;
save_moves_size++;
}
move Level[6][200];
move bestSeqLevel[6][200];
int bestSeqLevelS[6];
int LevelS[6];
move seq[1000];
int global_maks=0;
void NMCS(int level){
int ile=0;
for(int i=0;i<available_moves_size;i++)
Level[0][i]=available_moves[i];
LevelS[0]=available_moves_size;
while(LevelS[0]!=0){
int temp_ile=ile;
for(int i=0;i<LevelS[0];i++){
dodaj(Level[0][i]);ile++;
remove();
for(int m=0;m<available_moves_size;m++)
Level[1][m]=available_moves[m];
LevelS[1]=available_moves_size;
bestSeqLevelS[1]=-1;
while(LevelS[1]!=0){
int temp_ile_1=ile;
for(int j=0;j<LevelS[1];j++){
dodaj(Level[1][j]);ile++;
remove();
while(available_moves_size!=0){
int w = rand()%available_moves_size;
dodaj(available_moves[w]);ile++;
remove();
}
if(bestSeqLevelS[1]<ile){
bestSeqLevelS[1]=ile;
for(int k=0;k<ile;k++)
bestSeqLevel[1][k]=save_moves[k];
}
if(ile>global_maks){
global_maks=ile;
cout<<ile<<" ";
save(ile);
}
clear_ile(temp_ile_1);
ile =save_moves_size=temp_ile_1;
for(int m=0;m<LevelS[1];m++)
available_moves[m]=Level[1][m];
available_moves_size=LevelS[1];
}
dodaj(bestSeqLevel[1][temp_ile_1]);ile++;
remove();
for(int m=0;m<available_moves_size;m++)
Level[1][m]=available_moves[m];
LevelS[1]=available_moves_size;
}
if(bestSeqLevelS[0]<bestSeqLevelS[1]){
bestSeqLevelS[0]=bestSeqLevelS[1];
for(int k=0;k<bestSeqLevelS[1];k++)
bestSeqLevel[0][k]=bestSeqLevel[1][k];
}
clear_ile(temp_ile);
ile =save_moves_size=temp_ile;
for(int m=0;m<LevelS[0];m++)
available_moves[m]=Level[0][m];
available_moves_size=LevelS[0];
}
dodaj(bestSeqLevel[0][temp_ile]);ile++;
remove();
for(int m=0;m<available_moves_size;m++)
Level[0][m]=available_moves[m];
LevelS[0]=available_moves_size;
}
}
void read_word_rekord(int ile){
move m;
int ilee=0;
for(int i=0;i<ile;i++){
int dx=(rekord[i*6+4]-rekord[i*6+2])/4;
int dy=(rekord[i*6+3]-rekord[i*6+5])/4;
if(dx==0 && dy==1)
swap(rekord[i*6+3],rekord[i*6+5]);
if(dx==1 && dy==1){
swap(rekord[i*6+3],rekord[i*6+5]);
swap(rekord[i*6+2],rekord[i*6+4]);
}
if(dx==-1 && dy==1){
swap(rekord[i*6+3],rekord[i*6+5]);
swap(rekord[i*6+2],rekord[i*6+4]);
}
m.pnt.x=rekord[i*6]+20;
m.pnt.y=rekord[i*6+1]+19;
m.bgn.x=rekord[i*6+2]+20;
m.bgn.y=rekord[i*6+3]+19;
if(rekord[i*6+2]==rekord[i*6+4])
m.dir=1;
else if(rekord[i*6+3]==rekord[i*6+5])
m.dir=3;
else if(rekord[i*6+2]>rekord[i*6+4])
m.dir=0;
else
m.dir=2;
//znajdz i wstaw:)
for(int j=0;j<available_moves_size;j++){
if(m==available_moves[j]){
add_connection(m);
add_point(m.pnt);
points_clear_size++;
points_clear[points_clear_size]=m.pnt;
save_moves[save_moves_size]=m;
save_moves_size++;
ilee++;
break;
}
}
}
cout<<ilee<<"\n";
}
void read(int yr){
for(int i=0;i<yr*6;i++){
cin>>rekord[i];
}
}
int main(){
srand ( unsigned ( time (NULL) ) );
set_cross();
//read(0);
//read_word_rekord(50);
move start[1000];
int start_size=0;
for(int i=0;i<available_moves_size;i++)
start[i]=available_moves[i];
start_size=available_moves_size;
while(1){
cout<<"|";
clear_ile(0);
save_moves_size=0;
for(int i=0;i<start_size;i++)
available_moves[i]=start[i];
available_moves_size=start_size;
NMCS(2);
}
remove();
NMCS(2);
//random_layer_price_game2(50);
//random_layer_game();
//random_layer_price_game(93);
//random_price_game();
//random_price_time_game(0);
//random_game();
//MCTS();
//MCTS_P();
return 0;
}
| [
"kjamroz@o2.pl"
] | kjamroz@o2.pl |
957cf4fa08391eb33ecc57ef63b0dd8f11637a8b | 2c4c827f38412e6d01f0b2c7ead80371e793ac2c | /agui/root.cc | 879c74b6e1fb7b3a5f4ab381aece79482c4d904a | [
"BSD-3-Clause"
] | permissive | chuxuewen/Avocado | 1df0fb4af165638fae3113026bc5fa94dfc4cefd | 8ab3614f690c4ca62d360bdbd32fcf65af204327 | refs/heads/master | 2020-12-02T10:08:34.379994 | 2017-07-09T15:01:54 | 2017-07-09T15:01:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,063 | cc | /* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2015, louis.chu
* 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 louis.chu 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 louis.chu 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.
*
* ***** END LICENSE BLOCK ***** */
#include "app-1.h"
#include "display-port.h"
#include "root.h"
#include "draw.h"
av_gui_begin
/**
* @constructor
*/
Root::Root() av_def_err {
auto app = gui::app();
av_assert_err(app, "Before you create a root, you need to create a GUIApplication");
Inl_GUIApplication(app)->set_root(this);
m_background_color = Color(255, 255, 255); // 默认白色背景
m_level = 1; // 根视图为1
m_final_visible = true;
m_explicit_width = true;
m_explicit_height = true;
Vec2 size = display_port()->size();
set_width(size.width());
set_height(size.height());
mark(M_MATRIX);
}
/**
* @overwrite
*/
void Root::draw() {
if ( m_visible ) {
if ( mark_value ) {
if ( mark_value & M_BASIC_MATRIX ) { // 变换
Vec2 offset = layout_offset(); // xy 位移
offset.x( offset.x() + origin().x() + translate().x() );
offset.y( offset.y() + origin().y() + translate().y() );
// 更新基础矩阵
m_matrix = Mat(offset, scale(), -rotate_z(), skew());
}
if ( mark_value & M_OPACITY ) {
m_final_opacity = opacity();
}
if ( mark_value & M_TRANSFORM ) {
m_final_matrix = m_matrix;
}
if ( mark_value & (M_TRANSFORM | M_SHAPE) ) {
set_visible_draw();
}
}
m_ctx->draw(this);
mark_value = M_NONE;
} else {
m_ctx->clear_screen(Color(0, 0, 0));
}
}
/**
* @overwrite
*/
void Root::prepend(View* child) av_def_err {
if ( ! m_ctr ) { // set default controller
(new ViewController())->view(this);
}
Box::prepend(child);
}
/**
* @overwrite
*/
void Root::append(View* child) av_def_err {
if ( ! m_ctr) { // set default controller
(new ViewController())->view(this);
}
Box::append(child);
}
/**
* @overwrite
*/
View* Root::append_text(cUcs2String& str) av_def_err {
if ( ! m_ctr) { // set default controller
(new ViewController())->view(this);
}
return Box::append_text(str);
}
/**
* @overwrite
*/
void Root::set_parent(View* parent) av_def_err {
av_unreachable();
}
/**
* @overwrite
*/
void Root::set_layout_explicit_size() {
float final_width = m_final_width;
float final_height = m_final_height;
Vec2 port_size = display_port()->size();
if ( m_width.type == ValueType::PIXEL ) {
m_final_width = m_width.value;
} else {
m_final_width = port_size.width();
}
if ( m_height.type == ValueType::PIXEL ) {
m_final_height = m_height.value;
} else {
m_final_height = port_size.height();
}
m_raw_client_width = m_final_width;
m_raw_client_height = m_final_height;
Box::set_default_offset_value();
bool h = m_final_width != final_width;
bool v = m_final_height != final_height;
uint child_mark = M_NONE;
if ( h ) {
if ( m_content_align == ContentAlign::RIGHT ) {
child_mark = M_MATRIX;
}
}
if ( v ) {
if ( m_content_align == ContentAlign::BOTTOM ) {
child_mark = M_MATRIX;
}
}
relevance_child_box_change(h, v, child_mark);
}
/**
* @overwrite
*/
void Root::set_layout_content_offset() {
Vec2 squeeze;
Div::set_div_content_offset(squeeze, Vec2());
}
/**
* @overwrite
*/
Vec2 Root::layout_offset() {
return Vec2(m_offset_start.x() + m_final_margin_left + m_border_left.width,
m_offset_start.y() + m_final_margin_top + m_border_top.width);
}
av_gui_end
| [
"chuxuewen@gochinatv.com"
] | chuxuewen@gochinatv.com |
8d445b165f960ce8ea81440b7e5c24a0c81c1403 | 104f4cef1fc9ee73e04e7c1100897f720fb57011 | /graphs/wfs.tpp | 957b00322da7637a2a6693ffaa354f3ee5e880ed | [] | no_license | Demiurg-in-real/algorithms | a2c9aaa90e717d6a03a222d2be96d65489e6fa27 | 9ca1f8f9c623a541d2d9834734c03b163e11ca86 | refs/heads/master | 2021-02-10T08:02:11.616838 | 2020-10-02T13:09:55 | 2020-10-02T13:09:55 | 244,363,834 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 422 | tpp | void WFS::wfs(size_t start){
std::stack<std::pair<bool,std::vector<int>>> que;
que.push(gr[start]);
std::pair<bool, std::vector<int>> x;
while(!que.empty()){
x = que.top();
que.pop();
for(size_t i = 0; i<gr.size();i++) {
if(x == gr[i]){
visited.push_back(i);
gr[i].first = true;
break;
}
}
for(size_t i = 0; i<x.second.size();i++) if(!gr[x.second[i]].first) que.push(gr[x.second[i]]);
}
}
| [
"bezginandrew@gmail.com"
] | bezginandrew@gmail.com |
2185b6f86b88809282b9a98d672a36e0ae02de4d | 92365dad5ab950192e086d2dec3da4f9123a2a90 | /leetcode/213. House Robber II/solution.cpp | adee57c808bc7e10435b9e4378db27f93367ddc0 | [] | no_license | roachsinai/Coding_Interviews | e2fec89c57e53fdccb55d103486685cc0d5a4a21 | bf39ee91f6b7b241067a7be79bf0023000d8c7a7 | refs/heads/master | 2020-12-26T16:48:24.749461 | 2019-01-12T09:07:39 | 2019-01-12T09:18:59 | 63,310,037 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,288 | cpp | // 暴力法,就是循环所有可能得到最大的解
// 实际上在环中的房子,两个相邻的房子在最优解中最后有三种状态:前一个被偷,后一个被偷,两个都没有被偷。
// 这样的话,假如第i个房子不偷,那么i+1个房子可偷可不偷,这就和第一道题一样了。同样,在另第i+1个房子不偷,最优解肯定在这两个结果中。
#include <algorithm>
class Solution {
public:
int rob(vector<int>& nums) {
if (nums.size() == 0)
return 0;
else if (nums.size() == 1)
return nums[0];
return max( rob(nums, 0, nums.size()-2), rob(nums, 1, nums.size()-1) );
}
int rob(vector<int>& nums, int begin, int end)
{
if (begin == end)
return nums[begin];
if (begin == end-1)
return ((nums[begin] > nums[end]) ? nums[begin] : nums[end]);
int pp_pre = nums[begin], p_pre = max(pp_pre, nums[begin + 1]);
int result = p_pre;
for (int i = begin + 2; i <= end; ++ i)
{
result = ((pp_pre + nums[i] > p_pre) ? (pp_pre+nums[i]) : p_pre);
pp_pre = p_pre;
p_pre = result;
}
return result;
}
}; | [
"roachsinai@qq.com"
] | roachsinai@qq.com |
16ae9ad54657fd63f0c2b76f4195d06195aaee0b | d80450ee8f8a90000947ed84c079988b47b1d2d6 | /src/ZkGame/Entities/PlayerEntity.cpp | 44014171a8c1e92d8a5480bb6908e2dc4acf5c4d | [] | no_license | Tommalla/zoldak | bc7b839cda2be829ad64e9258c10ff00576534cc | 0db9b54232b60a0adea13659813d9050ff8dd11d | refs/heads/master | 2021-01-18T12:33:13.786972 | 2015-03-12T13:43:05 | 2015-03-12T13:43:05 | 27,772,651 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,796 | cpp | #include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <Box2D/Box2D.h>
#include <cmath>
#include <algorithm>
#include <memory>
#include <utility>
#include <QtCore>
#include <QDebug>
#include "../../ZkCommon/Constants.hpp"
#include "../../ZkCommon/LibraryCast.hpp"
#include "PlayerEntity.hpp"
#include "MedKitEntity.hpp"
#include "GrenadePackEntity.hpp"
#include "CrosshairEntity.hpp"
#include "../Config/InputConfig.hpp"
#include "../Config/PlayerAction.hpp"
#include "../Config/InputAction.hpp"
#include "../Renderables/BoxRenderable.hpp"
#include "../Weapons/WeaponDef.hpp"
#include "../Weapons/Weapon.hpp"
#include "../Game.hpp"
#include "../GameSystem.hpp"
#include "../InputSystem.hpp"
using namespace Zk::Common;
using namespace Zk::Game;
static const WeaponDef mainWeaponDef {
7.5, //obrażenia od jednego strzału
100.0, //prędkość wylotowa
0.05, //czas do następnego wystrzału
3.0, //czas przzeładowania
30, //rozmiar magazynka
WeaponDef::ParticleType::BULLET
};
static const WeaponDef grenadeDef {
100.0, //obrażenia od jednego strzału
10.0, //prędkość wylotowa
0.5, //czas do następnego strzału
0.0, //czas przeładowania (tutaj nieistotny)
5, //rozmiar magazynka
WeaponDef::ParticleType::GRENADE
};
PlayerEntity::ContactInfo::ContactInfo(b2Body * myBody, b2Contact * original)
{
this->original = original;
b2WorldManifold worldManifold;
original->GetWorldManifold(&worldManifold);
if (original->GetFixtureA()->GetBody() == myBody)
{
normal = worldManifold.normal;
toucher = original->GetFixtureB()->GetBody();
}
else
{
normal = -worldManifold.normal;
toucher = original->GetFixtureA()->GetBody();
}
}
PlayerEntity::PlayerEntity(
Player & player,
sf::Vector2f pos,
const InputConfig & inputConfig
) :
Entity(nullptr, nullptr),
BodyCollisionListener(nullptr),
std::enable_shared_from_this<PlayerEntity>(),
weapon(mainWeaponDef, player),
grenadeWeapon(grenadeDef, player),
inputConfig(inputConfig),
player(player)
{
b2World & world = Game::getInstance()->getPhysicsSystem().getWorld();
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position = lib_cast<b2Vec2>(pos);
bodyDef.userData = (void*)this;
b2Body * body = world.CreateBody(&bodyDef);
float bodyWidth = 24.f / 64.f;
float bodyHeight = 40.f / 64.f;
b2PolygonShape polyShape;
polyShape.SetAsBox(bodyWidth, bodyHeight);
b2FixtureDef fixtureDef;
fixtureDef.shape = &polyShape;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.6f;
body->CreateFixture(&fixtureDef);
body->SetFixedRotation(true);
setBody(body);
setFilteringBody(body);
std::string characterPath;
if (player.getID())
characterPath = "soldier-A.png";
else
characterPath = "soldier-B.png";
BoxRenderable * br = new BoxRenderable(
"OBJECTS",
body, GameSystem::resourcePath(characterPath).c_str()
);
setRenderable(br);
jumpCooldown = 0.0;
health = MAX_HP;
}
PlayerEntity::~PlayerEntity()
{
}
void PlayerEntity::registerMe()
{
Game::getInstance()->getPhysicsSystem().registerListener(
shared_from_this()
);
auto crosshair = std::make_shared<CrosshairEntity>(
shared_from_this(), inputConfig.mouseDevice
);
crosshair->registerMe();
Game::getInstance()->addEntity(crosshair);
this->crosshair = crosshair;
}
void PlayerEntity::onBeginContactEvent(b2Contact * contact)
{
ContactInfo ci(getBody(), contact);
contacts.push_back(ci);
}
void PlayerEntity::onEndContactEvent(b2Contact * contact)
{
ContactInfo ci(getBody(), contact);
contacts.erase(std::find(contacts.begin(), contacts.end(), ci));
}
void PlayerEntity::onPreSolveEvent(b2Contact * contact, const b2Manifold * oldManifold)
{
ContactInfo ci(getBody(), contact);
Entity * ent = (Entity*)ci.toucher->GetUserData();
if (ent->getType() == EntityType::MedKitEntity)
{
MedKitEntity * ceEnt = (MedKitEntity*)ent;
ceEnt->pickUp();
contact->SetEnabled(false);
pickUpMedKit();
}
else if (ent->getType() == EntityType::GrenadePackEntity)
{
GrenadePackEntity * ceEnt = (GrenadePackEntity*)ent;
ceEnt->pickUp();
contact->SetEnabled(false);
pickUpGrenadePack();
}
}
void PlayerEntity::onPostSolveEvent(b2Contact * contact, const b2ContactImpulse * impulse)
{
}
void PlayerEntity::update(double step)
{
const b2Vec2 runAcceleration(25.f, 0.f);
const b2Vec2 strafeAcceleration(10.f, 0.f);
bool isStanding = false;
bool isRunning = false;
b2Vec2 groundNormal(0.f, 0.f);
//Sprawdźmy, czy stoimy na twardym gruncie
{
for (const ContactInfo & ci : contacts)
{
Entity * ent = (Entity*)ci.toucher->GetUserData();
if (ent->getType() == EntityType::LevelMeshEntity && ci.normal.y > 0.05f)
groundNormal += ci.normal;
}
if (groundNormal.LengthSquared() > 0.f)
isStanding = true;
}
jumpCooldown = std::max(0.0, jumpCooldown - step);
if (inputConfig.isActionTriggered(PlayerAction::GoLeft))
{
if (getBody()->GetLinearVelocity().x > -HORIZONTAL_VELOCITY_CAP)
getBody()->ApplyForceToCenter(
isStanding ? -runAcceleration : -strafeAcceleration,
true
);
if (isStanding)
isRunning = !isRunning;
}
if (inputConfig.isActionTriggered(PlayerAction::GoRight))
{
if (getBody()->GetLinearVelocity().x < HORIZONTAL_VELOCITY_CAP)
getBody()->ApplyForceToCenter(
isStanding ? runAcceleration : strafeAcceleration,
true
);
if (isStanding)
isRunning = !isRunning;
}
if (inputConfig.isActionTriggered(PlayerAction::Jump)
&& jumpCooldown == 0.f)
{
if (isStanding)
{
float scale = -7.5f / groundNormal.Length();
groundNormal.x *= scale;
groundNormal.y *= scale;
getBody()->ApplyLinearImpulse(
groundNormal, b2Vec2(0.f, 0.f), true
);
jumpCooldown = 0.25;
isStanding = false;
}
}
//Jeśli nie biegniemy i jesteśmy na ziemi, powinniśmy szybko spowolnić nasz bieg
if (isStanding && !isRunning && jumpCooldown == 0.f)
getBody()->SetLinearVelocity(b2Vec2(0.f, 0.f));
//Aktualizacja broni
sf::Vector2f direction =
crosshair.lock()->getCenterPosition() - getCenterPosition();
weapon.update(
step, direction, inputConfig.isActionTriggered(PlayerAction::Shoot)
);
//Aktualizacja granatów
grenadeWeapon.update(
step, direction, inputConfig.isActionTriggered(PlayerAction::ThrowGrenade)
);
}
EntityType PlayerEntity::getType() const
{
return EntityType::PlayerEntity;
}
void PlayerEntity::takeDamage(double damage)
{
if (health == 0.0)
return;
health = std::max(0.0, health - damage);
if (health == 0.0)
{
player.reportDeath();
markForDeletion();
}
}
int PlayerEntity::getGrenadeCount() const
{
return grenadeWeapon.getAmmoCount();
}
void PlayerEntity::pickUpMedKit()
{
health += MedKitEntity::HP_PER_MEDKIT;
if (health > MAX_HP)
health = MAX_HP;
}
void PlayerEntity::pickUpGrenadePack()
{
grenadeWeapon.loadAmmo(1);
}
| [
"piodul@op.pl"
] | piodul@op.pl |
916451cbe925c9908991bcc76789f01a1ed3fab0 | d396697011aa127c517372383bb56675ef6b4318 | /practiceCode/practiceCode/B746.cpp | bffe08869d687432b10756b6c25e879b6b9c274e | [] | no_license | Quach2502/hello-world | f7afa3edff1bfb5db5eb5dd66474f4ad5000f22b | 9932368ac24e907b138d3f5e744a28dfc5874bd3 | refs/heads/master | 2021-01-09T20:47:02.399667 | 2017-08-30T07:42:26 | 2017-08-30T07:42:26 | 63,652,315 | 0 | 0 | null | 2016-07-19T02:21:41 | 2016-07-19T02:17:30 | null | UTF-8 | C++ | false | false | 671 | cpp | //#include <iostream>
//#include <set>
//#include <vector>
//#include <algorithm>
//#include <string>
//#include <unordered_map>
//#include <unordered_set>
//typedef long long ll;
//void main()
//{
// std::ios::sync_with_stdio(false);
// std::unordered_map<std::string, std::string> dict;
// int n(0);std::cin>>n;
// std::string input; std::cin>>input;
// char output[2001];
// std::reverse(input.begin(),input.end());
// int temp = n-1;
// for(int i =0;i<n;i+=2)
// {
// output[temp] = input[i];
// temp--;
// }
// temp = 0;
// for(int i = 1;i<n;i+=2)
// {
// output[temp] = input[i];
// temp++;
// }
// for(int i = 0;i<n;i++)
// {
// std::cout<<output[i];
// }
//} | [
"quachdung2502@gmail.com"
] | quachdung2502@gmail.com |
68bdea7beea268d39ebd073b7615ab17ddf1992c | 20a277e4e8a4ad949c97e3e4cc6b7ef11cf5ae0b | /Recursion/Backtracking/nqueen.cpp | 38c16c363b0998b818e76c498e4a2940b6148128 | [] | no_license | Neilketchum/Compedetive-Programing | da265ffc218f63b87bd67160512c8f342f506702 | bd007eed7c1ae9e5b2dfe809ce9349b9d04ae7f5 | refs/heads/master | 2022-11-24T19:03:51.548401 | 2020-07-31T11:28:54 | 2020-07-31T11:28:54 | 269,554,949 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,731 | cpp | #include <bits/stdc++.h>
using namespace std;
bool isSafe(int board[10][10],int i,int j,int n){
//Checking for Col
for(int row = 0;row < i;row++){
if(board[row][j] == 1){
return false;
}
}
// Checking for Left Diagonal
int x = i;
int y = j;
while(x>=0 && y>= 0){
if(board[x][y] == 1 ){
return false;
}
x--;
y--;
}
// CHecking for right diagonal
x = i;
y = j;
while(x>=0 && y< n){
if(board[x][y] == 1 ){
return false;
}
x--;
y++;
}
return true;
}
bool solveNqueen(int board[][10], int i, int n)
{
// Base Case
if (i == n )
{
// board[i][j] = 1;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << board[i][j] << " ";
}
cout << endl;
}
cout << endl;
return false;
}
// traversing collumn for a given row to find a place for the queen
for (int j = 0; j < n; j++)
{
if (isSafe(board, i, j, n))
{
// Place the queen and assumeing its right pos
board[i][j] = 1;
bool aglaQueenRakhPau = solveNqueen(board, i + 1, n);
if (aglaQueenRakhPau)
{
return true;
}
// Asumed Positon of the queen is wrong hence Backtrack
board[i][j] = 0;
}
}
return false;
}
int main(int argc, char const *argv[])
{
int board[10][10] = {0};
int n;
cin >> n;
solveNqueen(board, 0, n );
return 0;
}
| [
"daipayanh@gmail.com"
] | daipayanh@gmail.com |
8866173af449f9fe4f901e3c80b70492be8f6524 | 8ceb5757987e2e19ef9d6fae54a8f2babebe1976 | /05/A.cpp | 82af870f48a2b79406b21456fd8ac34d72befd88 | [] | no_license | salavay/algorithms_labs | 2dd361811212fb729c4aa9cd8dd6ca91d14eeaf1 | 5a39da854ef0c5942be35d92d1dfa15ab229a3c9 | refs/heads/master | 2023-03-30T19:03:33.489973 | 2021-03-30T14:13:39 | 2021-03-30T14:13:39 | 353,020,901 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,098 | cpp | #include <bits/stdc++.h>
using namespace std;
struct vertex {
int value;
int height = 1;
vertex *left = nullptr;
vertex *right = nullptr;
vertex(int value) {
this->value = value;
}
};
class AVL_tree {
private:
vertex *root;
int getHeight(vertex *a) {
if (a != nullptr) {
return a->height;
} else {
return 0;
}
}
int getBalance(vertex *a) {
return getHeight(a->right) - getHeight(a->left);
}
void updateHeight(vertex *a) {
int leftHeight = getHeight(a->left);
int rightHeight = getHeight(a->right);
a->height = max(leftHeight, rightHeight) + 1;
}
vertex *rightRotate(vertex *a) {
if (a == root) {
root = a->left;
}
vertex *tmp = a->left;
a->left = tmp->right;
tmp->right = a;
updateHeight(a);
updateHeight(tmp);
return tmp;
}
vertex *leftRotate(vertex *a) {
if (a == root) {
root = a->right;
}
vertex *tmp = a->right;
a->right = tmp->left;
tmp->left = a;
updateHeight(a);
updateHeight(tmp);
return tmp;
}
vertex *balancing(vertex *a) {
updateHeight(a);
if (getBalance(a) == 2) {
if (getBalance(a->right) < 0) {
a->right = rightRotate(a->right);
}
return leftRotate(a);
}
if (getBalance(a) == -2) {
if (getBalance(a->left) > 0) {
a->left = leftRotate(a->left);
}
return rightRotate(a);
}
return a;
}
vertex *leftestFind(vertex *a) {
if (a->left == nullptr) {
return a;
} else {
return leftestFind(a->left);
}
}
vertex *rightestFind(vertex *a) {
if (a->right == nullptr) {
return a;
} else {
return rightestFind(a->right);
}
}
vertex *deleteTheLeftest(vertex *a) {
if (a->left == nullptr) {
return a->right;
}
a->left = deleteTheLeftest(a->left);
return balancing(a);
}
vertex *deleteTheRightest(vertex *now) {
if (now->right == nullptr) {
return now->left;
}
now->right = deleteTheRightest(now->right);
return balancing(now);
}
public:
AVL_tree() {
root = nullptr;
}
vertex *getRoot() {
return root;
}
vertex *insert(vertex *now, int x) {
if (exist(now, x)) {
return nullptr;
}
if (now == nullptr) {
if (now == root) {
root = new vertex(x);
}
return new vertex(x);
}
if (x < now->value) {
now->left = insert(now->left, x);
} else {
now->right = insert(now->right, x);
}
return balancing(now);
}
static bool exist(vertex *now, int x) {
if (!now) {
return false;
}
if (x < now->value) {
return exist(now->left, x);
} else {
if (x == now->value) {
return true;
} else {
return exist(now->right, x);
}
}
}
vertex *deleteValue(vertex *a, int x) {
if (!exist(root, x)) {
return nullptr;
}
if (a == nullptr) {
return a;
}
if (x < a->value) {
a->left = deleteValue(a->left, x);
} else if (x > a->value) {
a->right = deleteValue(a->right, x);
} else {
bool flagChangeRoot = (a == root);
vertex *tmpL = a->left;
vertex *tmpR = a->right;
delete a;
if (tmpL == nullptr) {
if (tmpR == nullptr && flagChangeRoot) root = nullptr;
if (flagChangeRoot && tmpR != nullptr) root = tmpR;
return tmpR;
}
vertex *theRightest = rightestFind(tmpL);
theRightest->left = deleteTheRightest(tmpL);
theRightest->right = tmpR;
if (flagChangeRoot) {
root = balancing(theRightest);
}
return balancing(theRightest);
}
if (a == root) {
root = balancing(a);
}
return balancing(a);
}
vertex *next(int x) {
vertex *now = root;
vertex *lastGood = nullptr;
while (now) {
if (now->value > x) {
lastGood = now;
now = now->left;
} else {
now = now->right;
}
}
return lastGood;
}
vertex *prev(int x) {
vertex *now = root;
vertex *lastGood = nullptr;
while (now) {
if (now->value >= x) {
now = now->left;
} else {
lastGood = now;
now = now->right;
}
}
return lastGood;
}
};
signed main() {
#ifdef salavay
freopen("test", "r", stdin);
#endif
AVL_tree tree;
string command;
while (cin >> command) {
int x;
cin >> x;
if (command == "insert") {
tree.insert(tree.getRoot(), x);
} else if (command == "delete") {
tree.deleteValue(tree.getRoot(), x);
} else if (command == "exists") {
cout << (AVL_tree::exist(tree.getRoot(), x) ? "true" : "false");
cout << '\n';
} else if (command == "next") {
vertex *next = tree.next(x);
if (next != nullptr) {
cout << next->value;
} else {
cout << "none";
}
cout << '\n';
} else {
vertex *prev = tree.prev(x);
if (prev != nullptr) {
cout << prev->value;
} else {
cout << "none";
}
cout << '\n';
}
}
return 0;
}
| [
"salavat2002@gmail.com"
] | salavat2002@gmail.com |
85940cd4bcd3dfe2e94cface5de77fea8b09e0b6 | 3e578d170d93f7492e9c6659c5066542addc1113 | /TestNetworks/TimingTest2/TimingTest2.cpp | d5abdc35e3cf9b0262eee82f1fb03458848b6b9c | [
"Artistic-2.0"
] | permissive | caomw/cppfbp | ffb20f0e6c5171e91341e3250273636f31929f82 | f1a20ea29b7d00f0e74d36c86234f8ea2d4efbea | refs/heads/master | 2021-01-18T01:05:24.085942 | 2014-09-29T15:30:56 | 2014-09-29T15:30:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,977 | cpp | // TimingTest2.cpp : Defines the entry point for the console application.
#include "thxdef.h"
#include <stdio.h>
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
/* This is not the THREADS internal structure - this
is a structured representation of the free-form connection list
Using fibres...
This test case took 11 secs with 2,000,000 IPs, and connection capacity of 50;
assuming create/destroy trivial, send/receive pair takes 110 nanoseconds
Only uses one processor
Using Boost...
25 secs - this suggests that send/receive is quite a bit slower!
Uses all 4 processors
However, there may be too few processes, so we will add 5 more, giving 11 processes, and see what happens...
We still have 2,000,000 IPs, so 2,000,000 creates and destroys each, 10 sends and receives for each IP
Took 18 secs - maybe 25 secs was bug! That seems much better - twice as many processes and not a lot more time...!
*/
void CppFBP(label_ent * label_blk, bool dynam, FILE * fp, bool timereq);
THRCOMP ThGenIps(_anchor anch);
THRCOMP ThDrop(_anchor anch);
THRCOMP ThPsThru(_anchor anch);
bool TRACE = false;
proc_ent P00 = {0, "Gen", "ThGenIps", ThGenIps, 0, 0, TRACE, 0};
proc_ent P01 = {&P00, "Copy0", "ThPsThru", ThPsThru, 0, 0, TRACE, 0};
proc_ent P02 = {&P01, "Copy1", "ThPsThru", ThPsThru, 0, 0, TRACE, 0};
proc_ent P03 = {&P02, "Copy2", "ThPsThru", ThPsThru, 0, 0, TRACE, 0};
proc_ent P04 = {&P03, "Copy3", "ThPsThru", ThPsThru, 0, 0, TRACE, 0};
proc_ent P05 = {&P04, "Copy4", "ThPsThru", ThPsThru, 0, 0, TRACE, 0}; // added
proc_ent P06 = {&P05, "Copy5", "ThPsThru", ThPsThru, 0, 0, TRACE, 0}; // added
proc_ent P07 = {&P06, "Copy6", "ThPsThru", ThPsThru, 0, 0, TRACE, 0}; // added
proc_ent P08 = {&P07, "Copy7", "ThPsThru", ThPsThru, 0, 0, TRACE, 0}; // added
proc_ent P09 = {&P08, "Copy8", "ThPsThru", ThPsThru, 0, 0, TRACE, 0}; // added
proc_ent P10 = {&P09, "Drop", "ThDrop", ThDrop, 0, 0, TRACE, 0};
IIP I00 = {"2000000"}; // was 2000000
cnxt_ent C00 = {0, "!", "", 0, "Gen", "COUNT", 0, &I00, 0};
cnxt_ent C01 = {&C00, "Gen", "OUT", 0, "Copy0", "IN", 0, 0, 50};
cnxt_ent C02 = {&C01, "Copy0", "OUT", 0, "Copy1", "IN", 0, 0, 50};
cnxt_ent C03 = {&C02, "Copy1", "OUT", 0, "Copy2", "IN", 0, 0, 50};
cnxt_ent C04 = {&C03, "Copy2", "OUT", 0, "Copy3", "IN", 0, 0, 50};
cnxt_ent C05 = {&C04, "Copy3", "OUT", 0, "Copy4", "IN", 0, 0, 50};
cnxt_ent C06 = {&C05, "Copy4", "OUT", 0, "Copy5", "IN", 0, 0, 50};
cnxt_ent C07 = {&C06, "Copy5", "OUT", 0, "Copy6", "IN", 0, 0, 50};
cnxt_ent C08 = {&C07, "Copy6", "OUT", 0, "Copy7", "IN", 0, 0, 50};
cnxt_ent C09 = {&C08, "Copy7", "OUT", 0, "Copy8", "IN", 0, 0, 50};
cnxt_ent C10 = {&C09, "Copy8", "OUT", 0, "Drop", "IN", 0, 0, 50};
label_ent LABELTAB = {0, " ", "", &C10, &P10, 'L'};
void main() {
//_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG)|_CRTDBG_LEAK_CHECK_DF);
//_CrtSetBreakAlloc(838); // 3132 989 714
CppFBP(&LABELTAB, 0, 0, 1); // time required
}
| [
"jpaulmorr@gmail.com"
] | jpaulmorr@gmail.com |
d4fa5ad4824f12739b8fcd5192179e4034b5bce2 | ae526c5669bda2992fb550e8b655203f2911f3af | /examples/example-cpp-app/cocos2d/extensions/Particle3D/PU/CCPUOnVelocityObserver.cpp | 92d370028c2e38d2e12b79a1b93874adeee961d0 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | bugsnag/bugsnag-cocos2dx | 681e5237031c49acc7f0261ab012a718cccb5ea4 | 2bf8fb015a939aba5cfde6851e94bdd844e3f8a0 | refs/heads/next | 2022-09-14T16:59:57.085853 | 2022-09-14T12:22:28 | 2022-09-14T12:22:28 | 223,420,560 | 1 | 2 | MIT | 2022-09-14T12:22:30 | 2019-11-22T14:28:55 | C++ | UTF-8 | C++ | false | false | 3,253 | cpp | /****************************************************************************
Copyright (C) 2013 Henry van Merode. All rights reserved.
Copyright (c) 2015-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "extensions/Particle3D/PU/CCPUOnVelocityObserver.h"
#include "extensions/Particle3D/PU/CCPUParticleSystem3D.h"
NS_CC_BEGIN
static bool almostEquals(float a, float b, float epsilon = std::numeric_limits<float>::epsilon())
{
return fabs(a - b) <= ( (fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon);
};
// Constants
const float PUOnVelocityObserver::DEFAULT_VELOCITY_THRESHOLD = 0.0f;
//-----------------------------------------------------------------------
PUOnVelocityObserver::PUOnVelocityObserver(void) :
PUObserver(),
_threshold(DEFAULT_VELOCITY_THRESHOLD),
_compare(CO_LESS_THAN)
{
};
//-----------------------------------------------------------------------
bool PUOnVelocityObserver::observe (PUParticle3D* particle, float /*timeElapsed*/)
{
if (!particle)
return false;
// Compensate for the scaled velocity
float scaleVelocity = _particleSystem->getParticleSystemScaleVelocity();
if (_compare == CO_GREATER_THAN)
{
// Changed in V 1.3.1
return (particle->calculateVelocity()) > (scaleVelocity * _threshold);
}
else if (_compare == CO_LESS_THAN)
{
return (particle->calculateVelocity()) < (scaleVelocity * _threshold);
}
else
{
// Equals
return almostEquals(particle->calculateVelocity(), (scaleVelocity * _threshold), 0.01f);
}
return false;
}
PUOnVelocityObserver* PUOnVelocityObserver::create()
{
auto pvo = new (std::nothrow) PUOnVelocityObserver();
pvo->autorelease();
return pvo;
}
void PUOnVelocityObserver::copyAttributesTo( PUObserver* observer )
{
PUObserver::copyAttributesTo(observer);
PUOnVelocityObserver* onVelocityObserver = static_cast<PUOnVelocityObserver*>(observer);
onVelocityObserver->_threshold = _threshold;
onVelocityObserver->_compare = _compare;
}
NS_CC_END
| [
"iskanamagus@gmail.com"
] | iskanamagus@gmail.com |
0f00d1481a413a9acab77ff6ca5a4b7b3dc09452 | 8b8bcfc5f7e1d82f80349972e1948358f54fd3a0 | /SampleCode/misc.h | 2dff758c231299fecfbeaf356b19e898a724fc60 | [] | no_license | sharperM/mspCode | 0387138d20b4a94e50c1cb672fc857938f4d7d29 | 186d7d0e41b357214adcbfcd4cba3c857ffcf40a | refs/heads/master | 2021-01-17T13:13:49.244420 | 2016-06-07T09:58:43 | 2016-06-07T09:58:43 | 16,302,156 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 345 | h | #pragma once
#include <windows.h>
#include <objidl.h>
#include <gdiplus.h>
#include <atldef.h>
#include <atlconv.h>
#include <atlalloc.h>
using namespace Gdiplus;
class GDIplusLib
{
private:
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
GDIplusLib();
public:
~GDIplusLib();
static GDIplusLib& instance();
};
| [
"mshaopei@gmail.com"
] | mshaopei@gmail.com |
890cf631806581b1b2b8ef49a83c09a46d6aaca1 | 00add89b1c9712db1a29a73f34864854a7738686 | /packages/utility/archive/src/Utility_HDF5OArchive.cpp | ff23deecfe1277daca3b4932adf6f3b115652536 | [
"BSD-3-Clause"
] | permissive | FRENSIE/FRENSIE | a4f533faa02e456ec641815886bc530a53f525f9 | 1735b1c8841f23d415a4998743515c56f980f654 | refs/heads/master | 2021-11-19T02:37:26.311426 | 2021-09-08T11:51:24 | 2021-09-08T11:51:24 | 7,826,404 | 11 | 6 | NOASSERTION | 2021-09-08T11:51:25 | 2013-01-25T19:03:09 | C++ | UTF-8 | C++ | false | false | 4,180 | cpp | //---------------------------------------------------------------------------//
//!
//! \file Utility_HDF5OArchive.cpp
//! \author Alex Robinson
//! \brief HDF5 output archive class definition
//!
//---------------------------------------------------------------------------//
// Boost Includes
#include <boost/archive/detail/archive_serializer_map.hpp>
#include <boost/archive/impl/archive_serializer_map.ipp>
// FRENSIE Includes
#include "Utility_HDF5OArchive.hpp"
namespace Utility{
template void HDF5OArchiveImpl<HDF5OArchive>::save( const bool& );
template void HDF5OArchiveImpl<HDF5OArchive>::save( const char& );
template void HDF5OArchiveImpl<HDF5OArchive>::save( const unsigned char& );
template void HDF5OArchiveImpl<HDF5OArchive>::save( const signed char& );
template void HDF5OArchiveImpl<HDF5OArchive>::save( const short& );
template void HDF5OArchiveImpl<HDF5OArchive>::save( const unsigned short& );
template void HDF5OArchiveImpl<HDF5OArchive>::save( const int& );
template void HDF5OArchiveImpl<HDF5OArchive>::save( const unsigned& );
template void HDF5OArchiveImpl<HDF5OArchive>::save( const long& );
template void HDF5OArchiveImpl<HDF5OArchive>::save( const unsigned long& );
template void HDF5OArchiveImpl<HDF5OArchive>::save( const long long& );
template void HDF5OArchiveImpl<HDF5OArchive>::save( const unsigned long long& );
template void HDF5OArchiveImpl<HDF5OArchive>::save( const float& );
template void HDF5OArchiveImpl<HDF5OArchive>::save( const double& );
template void HDF5OArchiveImpl<HDF5OArchive>::save( const long double& );
template void HDF5OArchiveImpl<HDF5OArchive>::save( const std::string& );
#ifdef BOOST_SERIALIZATION_ARRAY_WRAPPER_AVAILABLE
template void HDF5OArchiveImpl<HDF5OArchive>::save_array( const boost::serialization::array_wrapper<bool>&, unsigned int );
template void HDF5OArchiveImpl<HDF5OArchive>::save_array( const boost::serialization::array_wrapper<char>&, unsigned int );
template void HDF5OArchiveImpl<HDF5OArchive>::save_array( const boost::serialization::array_wrapper<unsigned char>&, unsigned int );
template void HDF5OArchiveImpl<HDF5OArchive>::save_array( const boost::serialization::array_wrapper<signed char>&, unsigned int );
template void HDF5OArchiveImpl<HDF5OArchive>::save_array( const boost::serialization::array_wrapper<short>&, unsigned int );
template void HDF5OArchiveImpl<HDF5OArchive>::save_array( const boost::serialization::array_wrapper<unsigned short>&, unsigned int );
template void HDF5OArchiveImpl<HDF5OArchive>::save_array( const boost::serialization::array_wrapper<int>&, unsigned int );
template void HDF5OArchiveImpl<HDF5OArchive>::save_array( const boost::serialization::array_wrapper<unsigned>&, unsigned int );
template void HDF5OArchiveImpl<HDF5OArchive>::save_array( const boost::serialization::array_wrapper<long>&, unsigned int );
template void HDF5OArchiveImpl<HDF5OArchive>::save_array( const boost::serialization::array_wrapper<unsigned long>&, unsigned int );
template void HDF5OArchiveImpl<HDF5OArchive>::save_array( const boost::serialization::array_wrapper<long long>&, unsigned int );
template void HDF5OArchiveImpl<HDF5OArchive>::save_array( const boost::serialization::array_wrapper<unsigned long long>&, unsigned int );
template void HDF5OArchiveImpl<HDF5OArchive>::save_array( const boost::serialization::array_wrapper<float>&, unsigned int );
template void HDF5OArchiveImpl<HDF5OArchive>::save_array( const boost::serialization::array_wrapper<double>&, unsigned int );
template void HDF5OArchiveImpl<HDF5OArchive>::save_array( const boost::serialization::array_wrapper<long double>&, unsigned int );
template void HDF5OArchiveImpl<HDF5OArchive>::save_array( const boost::serialization::array_wrapper<std::string>&, unsigned int );
#endif
} // end Utility namespace
namespace boost{
namespace archive{
namespace detail{
template class archive_serializer_map<Utility::HDF5OArchive>;
} // end detail namespace
} // end archive namespace
} // end boost namespace
//---------------------------------------------------------------------------//
// end Utility_HDF5OArchive.cpp
//---------------------------------------------------------------------------//
| [
"aprobinson@wisc.edu"
] | aprobinson@wisc.edu |
0c66448894b5c2fae517e82758c138c9e50a57dc | 2837839d3149152a8b7c2ee8d189473dbb9754f1 | /SceneDebug/SystemMain.h | 7ca12e396a1546d73bf925b21199a54d2f487311 | [] | no_license | takowasaby/SceneDebug | 50e586cfcc1f46eeff41206b051938917d5f687d | 43d85f17d0e15ee4be50e1ce21f919b88d4ecde9 | refs/heads/master | 2020-03-26T17:54:37.901997 | 2018-08-19T10:52:07 | 2018-08-19T10:52:07 | 145,186,753 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 346 | h | #pragma once
#include "SceneChanger.h"
class SystemMain : public SceneChanger
{
public:
SystemMain() = default;
~SystemMain() = default;
bool initialize() const;
void finalize() const;
void main();
void onSceneChanged(const eScene scene, const Parameter& parameter, const bool stackClear) override {};
void onScenePoped() override {};
};
| [
"31348840+takowasaby@users.noreply.github.com"
] | 31348840+takowasaby@users.noreply.github.com |
7059da8a751ad84728d92b5d96f0667534c502d1 | 724c0ee36c0e6262f143d965f2e5f894a31cbb16 | /c,c++/bitwise/2013/41.cpp | 0486051363f6d1108715f4b80317cdf0cf358546 | [] | no_license | amit-mittal/Programming-Questions-Practice | bf5fe47ba1b074960ad33eb2e525baaf99a85336 | 899995ff49cdf1ef77cc9327feb2fbed7b5c94fe | refs/heads/master | 2021-09-04T15:27:52.569111 | 2018-01-19T21:03:31 | 2018-01-19T21:03:31 | 117,618,138 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,596 | cpp | #include<iostream>
#include<stdio.h>
#include<vector>
using namespace std;
vector<long long int[4][4]> pre;
#define MOD 1000000007
void multiply(long long int a[][4],long long int b[][4]){
long long int c[4][4]={0},i,j,k;
for(i=0;i<4;++i){
for(j=0;j<4;++j){
for(k=0;k<4;++k){
a[i][k]%=MOD;
b[k][j]%=MOD;
c[i][j]+=((a[i][k]*b[k][j])%MOD);
c[i][j]%=MOD;
}
}
}
for(i=0;i<4;++i)
for(j=0;j<4;++j)
a[i][j]=c[i][j];
}
void matr(long long int c[][4], long long int n){
int counter=1;
while(n>0){
if(n%2==1)
multiply(c,pre[counter]);
n = n/2;
counter++;
}
}
int main(){
long long int test,i,j,k;
long long int n,val1,val2,ans;
long long int b[62][4][4];
long long int a[4][4]={{1,2,3,1},{1,0,0,0},{0,1,0,0},{0,0,1,0}};
scanf("%lld",&test);
pre.push_back(a);
for(i=1;i<62;++i){
long long int c[4][4];
for(k=0;k<4;++k)
for(j=0;j<4;++j)
c[k][j]=pre[i-1][k][j];
multiply(c,c);
pre.push_back(c);
}
while(test--){
long long int c[4][4]={0};
for(i=0;i<4;++i)
c[i][i]=1;
scanf("%lld",&n);
if(n<=4){
if(n==1)
printf("1\n");
else if(n==2)
printf("2\n");
else if(n==3)
printf("5\n");
else if(n==4)
printf("12\n");
continue;
}
for(n=2;n<20;++n){
matr(c,n-1);
for(i=0;i<4;++i){
for(j=0;j<4;++j){
printf("%lld ", a[i][j]);
}
printf("\n");
}
}
/*
val1=(c[3][0]*12)%MOD;
val1+=((c[3][1]*5)%MOD);
val1%=MOD;
val1+=(c[3][2]*2)%MOD;
val1%=MOD;
val1+=(c[3][3]*1)%MOD;
val1%=MOD;
printf("%lld\n",val1);
// printf("%lld\n",ans);
*/ }
return 0;
} | [
"Administrator@Amit-Laptop.fareast.corp.microsoft.com"
] | Administrator@Amit-Laptop.fareast.corp.microsoft.com |
fc11a9809d44370be0e4892ea065ca97e9159ba2 | 73a8f3c9c640af08acbefe657bff62e3d1751fc2 | /Dependencies/Qt-5.4.1/include/QtXmlPatterns/5.4.1/QtXmlPatterns/private/qbuiltinnodetype_tpl_p.h | 008b32588ef6b06be47251579a6e855c363d216f | [] | no_license | knight666/pitstop | 8d5ad076a71055803df1601e1df1640430ad56ca | 4e541d90507f38f36274e50b0d702a284d648e27 | refs/heads/master | 2020-07-10T00:51:28.141786 | 2019-08-24T20:08:02 | 2019-08-24T20:08:02 | 204,123,196 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,805 | h | /****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtXmlPatterns module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists purely as an
// implementation detail. This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//
/**
* @file
* @short This file is included by BuiltintNodeType.h.
* If you need includes in this file, put them in BuiltintNodeType.h, outside of the namespace.
*/
template <const QXmlNodeModelIndex::NodeKind kind>
BuiltinNodeType<kind>::BuiltinNodeType()
{
}
template <const QXmlNodeModelIndex::NodeKind kind>
bool BuiltinNodeType<kind>::xdtTypeMatches(const ItemType::Ptr &other) const
{
if(!other->isNodeType())
return false;
return *static_cast<const BuiltinNodeType *>(other.data()) == *this
? true
: xdtTypeMatches(other->xdtSuperType());
}
template <const QXmlNodeModelIndex::NodeKind kind>
bool BuiltinNodeType<kind>::itemMatches(const Item &item) const
{
Q_ASSERT(item);
return item.isNode() &&
item.asNode().kind() == kind;
}
template <const QXmlNodeModelIndex::NodeKind kind>
ItemType::Ptr BuiltinNodeType<kind>::atomizedType() const
{
switch(kind)
{
/* Fallthrough all these. */
case QXmlNodeModelIndex::Attribute:
case QXmlNodeModelIndex::Document:
case QXmlNodeModelIndex::Element:
case QXmlNodeModelIndex::Text:
return BuiltinTypes::xsUntypedAtomic;
case QXmlNodeModelIndex::ProcessingInstruction:
/* Fallthrough. */
case QXmlNodeModelIndex::Comment:
return BuiltinTypes::xsString;
default:
{
Q_ASSERT_X(false, Q_FUNC_INFO,
"Encountered invalid XPath Data Model node type.");
return BuiltinTypes::xsUntypedAtomic;
}
}
}
template <const QXmlNodeModelIndex::NodeKind kind>
QString BuiltinNodeType<kind>::displayName(const NamePool::Ptr &) const
{
switch(kind)
{
case QXmlNodeModelIndex::Element:
return QLatin1String("element()");
case QXmlNodeModelIndex::Document:
return QLatin1String("document()");
case QXmlNodeModelIndex::Attribute:
return QLatin1String("attribute()");
case QXmlNodeModelIndex::Text:
return QLatin1String("text()");
case QXmlNodeModelIndex::ProcessingInstruction:
return QLatin1String("processing-instruction()");
case QXmlNodeModelIndex::Comment:
return QLatin1String("comment()");
default:
{
Q_ASSERT_X(false, Q_FUNC_INFO,
"Encountered invalid XPath Data Model node type.");
return QString();
}
}
}
template <const QXmlNodeModelIndex::NodeKind kind>
ItemType::Ptr BuiltinNodeType<kind>::xdtSuperType() const
{
return BuiltinTypes::node;
}
template <const QXmlNodeModelIndex::NodeKind kind>
QXmlNodeModelIndex::NodeKind BuiltinNodeType<kind>::nodeKind() const
{
return kind;
}
template <const QXmlNodeModelIndex::NodeKind kind>
PatternPriority BuiltinNodeType<kind>::patternPriority() const
{
/* See XSL Transformations (XSLT) Version 2.0, 6.4 Conflict Resolution for
* Template Rules */
switch(kind)
{
case QXmlNodeModelIndex::Text:
/* Fallthrough. */
case QXmlNodeModelIndex::ProcessingInstruction:
/* Fallthrough. */
case QXmlNodeModelIndex::Comment:
/* "If the pattern is any other NodeTest, optionally preceded by a
* PatternAxis, then the priority is 0.5."
* Fallthrough. */
case QXmlNodeModelIndex::Attribute:
/* Fallthrough. */
case QXmlNodeModelIndex::Element:
/* Fallthrough. */
case QXmlNodeModelIndex::Document:
/* "If the pattern has the form /, then the priority is -0.5.". */
return -0.5;
default:
{
Q_ASSERT_X(false, Q_FUNC_INFO, "Unknown node type");
return 0;
}
}
}
| [
"knight666+github@gmail.com"
] | knight666+github@gmail.com |
7926a4a9e268a766b05cbf1a991e01355a5fd4f9 | cb1909b06c3dac07d2ab9569f47dd287364a67d0 | /src/core/ffStream.hpp | ea947ab87fe36189ec844f0cd02f67be99a69e49 | [] | no_license | zhangguof/mkrkr | 34c3215ac05fcfbdf823b48df4d5dd8c814f5e54 | b99bb4b757309f64dbbcbcc9bd04c9c7939dfa6c | refs/heads/master | 2021-06-22T18:27:54.900399 | 2020-12-21T14:42:57 | 2020-12-21T14:42:57 | 175,441,180 | 6 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 13,032 | hpp | #ifndef _FF_STREAM_H_
#define _FF_STREAM_H_
#include <string>
#include "SDL.h"
#include <string>
#include "safeQueue.hpp"
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libswresample/swresample.h"
#include "libavutil/opt.h"
#include "libswscale/swscale.h"
#include "libavutil/imgutils.h"
#include "libavformat/avio.h"
#include "libavutil/timestamp.h"
#include "libavutil/mathematics.h"
#define LOGE printf
#define LOGI printf
const int DEFAUTL_CHANNELS = 2;
const int DEFAUTL_FREQ = 44100;
#define MAX_AUDIO_FRAME_SIZE (192000)
// extern int audio_swr_resampling_audio(SwrContext *swr_ctx,
// TargetAudioParams *targetAudioParams,
// AVFrame *audioFrame,
// uint8_t **targetData);
// extern void audio_swr_resampling_audio_init(SwrContext **swr_ctx,
// TargetAudioParams *targetAudioParams,
// AVCodecContext *codec);
// extern void
// audio_swr_resampling_audio_destory(SwrContext **swr_ctx);
#ifdef __cplusplus
}
#endif
extern uint32_t time_now();
class FrameBuffer
{
public:
int frame_size;
int cur_pos;
int len;
struct Frame
{
uint8_t* data;
Frame(uint8_t* _data,int _size)
{
data = new uint8_t[_size];
memcpy(data,_data,_size);
}
~Frame()
{
delete[] data;
// SDL_Log("delete Frame data!");
}
};
std::vector<std::shared_ptr<Frame> > v;
FrameBuffer(int f_size)
{
frame_size = f_size;
cur_pos = 0;
len = 0;
}
FrameBuffer()
{
frame_size = -1;
cur_pos = 0;
len = 0;
}
~FrameBuffer()
{
v.clear();
SDL_Log("clear FrameBuffer!");
}
void push_frame(uint8_t* _data, int size)
{
if(frame_size == -1)
frame_size = size;
assert(size == frame_size);
auto pf = std::make_shared<Frame>(_data,size);
v.push_back(pf);
++len;
}
int read(uint8_t** data, int size)
{
// if(frame_size!=size)
// printf("frame_size:%d,size:%d\n", frame_size,size);
assert(frame_size == size);
if(cur_pos >= len)
return 0;
*data = v[cur_pos++]->data;
return size;
}
int seek(uint32_t pos)
{
if(pos > len)
pos = len;
cur_pos = pos;
return pos;
}
int readable_frame()
{
return len - cur_pos;
}
int get_pos()
{
return cur_pos;
}
};
class DataBuffer
{
public:
std::vector<uint8_t> v;
int len;
int rpos;
bool locked;
DataBuffer(){
v.resize(4096);
len = 0;
rpos = 0;
locked = false;
}
uint8_t* get_data()
{
return v.data();
// return &(*(v.begin()));
}
uint8_t* get_tail()
{
return v.data()+len;
// return &(*(v.begin()+len));
}
void ensure_size(int size)
{
if(len + size > v.size())
{
v.resize(len + size);
}
}
void push(uint8_t* data,int size)
{
//fix using size() better than capacity()!!!
ensure_size(size);
memcpy(get_tail(),data,size);
len += size;
}
//24bits
//1024*768, linesize = 1024*3
// void push_pic_buf(uint8_t* data,int linesize,int w,int h)
// {
// int size = linesize * h;
// uint32_t cur_t = time_now();
// uint32_t start_tick = cur_t;
// ensure_size(size);
// cur_t = time_now();
// // for(int i=0;i<h;++i)
// // {
// // push(data + i*linesize, linesize);
// // }
// memcpy(get_tail(),data,size);
// len+=size;
// }
int readable_size()
{
return len - rpos;
}
int read(uint8_t** data,int n)
{
if(rpos == len)
{
return 0;
}
int read_len = n;
if( n > len - rpos)
{
read_len = len - rpos;
}
*data = get_data() + rpos;
rpos += read_len;
return read_len;
}
//read all;
int read(uint8_t** data)
{
*data = get_data() + rpos;
rpos = len;
return len;
}
int fill(uint8_t* data,int n)
{
if(rpos == len)
return 0;
int read_len = n;
if(n > len -rpos)
read_len = len - rpos;
memcpy(data,get_data()+rpos, read_len);
rpos += read_len;
return read_len;
}
void seek(int pos)
{
if(pos>=len)
rpos = len;
else
rpos = pos;
}
void* new_buffer(int bytes)
{
ensure_size(bytes);
return get_tail();
}
void reset()
{
rpos = 0;
len = 0;
}
void* lock(int bytes)
{
if(locked) return nullptr;
locked = true;
ensure_size(bytes);
return get_tail();
}
void unlock()
{
if(!locked) return;
locked = false;
}
};
typedef std::shared_ptr<DataBuffer> tPtrDB;
struct TargetAudioParams
{
int sample_rate;
int channels;
uint64_t channel_layout;
AVSampleFormat sample_fmt;
};
typedef SafeQueue<AVPacket> tPacketQueue;
typedef int(*tReadPacketCB)(void *opaque, uint8_t *buf, int buf_size);
// struct Frame
// {
// int f_idx;
// int nSamples;
// Frame(int _idx,int n)
// {
// f_idx = _idx;
// nSamples = n;
// }
// ~Frame()
// {
// }
// };
// struct FrameQueue
// {
// int nSample;
// int SampleSize;
// std::vector<Frame> v;
// std::shared_ptr<DataBuffer> pdb;
// FrameQueue(int size,std::shared_ptr<DataBuffer>& pdb)
// {
// SampleSize = size;
// }
// void push_frame(int _idx,int n_sample,uint8_t* buf,int size)
// {
// Frame f(_idx,n_sample);
// pdb.push(buf,size);
// }
// };
class FFDecoder
{
public:
AVCodecContext *aCodecCtx;
SwrContext *swr;
AVPacket pkt;
uint8_t* audio_pkt_data;
int audio_pkt_size;
uint8_t** frame_buf;
int max_samples;
TargetAudioParams* target_params;
tPtrDB pdb;
int allocat_buffer(int n_sample)
{
int ret = 0,dst_linesize;
if(!frame_buf)
{
ret = av_samples_alloc_array_and_samples(
&frame_buf, &dst_linesize,
aCodecCtx->channels,max_samples,
target_params->sample_fmt, 0);
// printf("====allocat_buffer:%d\n", ret);
}
else if(n_sample > max_samples)
{
av_freep(&frame_buf[0]);
max_samples = n_sample;
ret = av_samples_alloc(frame_buf, &dst_linesize, aCodecCtx->channels,
max_samples, target_params->sample_fmt, 1);
// printf("=====re allocat_buffer:%d\n", ret);
}
if(ret<0)
{
printf("swr_alloc fail!!!:max_samples:%d\n",max_samples);
}
return ret;
}
FFDecoder(tPtrDB& _p,TargetAudioParams* pfmt,AVCodecContext* ctx, SwrContext* _swr=NULL)
{
aCodecCtx = ctx;
swr = _swr;
audio_pkt_data = nullptr;
audio_pkt_size = 0;
frame_buf = NULL;
pdb = _p;
max_samples = 8192;
target_params = pfmt;
}
~FFDecoder()
{
if (frame_buf)
av_freep(&frame_buf[0]);
av_freep(&frame_buf);
}
int decode_one_pkt(AVPacket& _pkt);
int decode(uint8_t* audio_buf, int buf_size);
};
class FFVDecoder
{
public:
AVCodecContext *pCodecCtx;
SwsContext *sws_ctx;
AVPacket pkt;
uint8_t* video_pkt_data;
int video_pkt_size;
uint8_t** frame_buf;
// tPtrDB pdb;
std::shared_ptr<FrameBuffer> pfb;
//copy buffer
uint8_t *decoded_data[4];
int decoded_linesize[4];
//using for flip img.
uint8_t *flip_buf[4];
int flip_linesize[4];
//vidoe scaling
AVPixelFormat src_pix_fmt;
int src_w, src_h;
const AVPixelFormat dst_pix_fmt = AV_PIX_FMT_BGRA;
int dst_w, dst_h;
FFVDecoder(std::shared_ptr<FrameBuffer>& _p,AVCodecContext* ctx, SwsContext* _sws=NULL)
{
pCodecCtx = ctx;
sws_ctx = _sws;
video_pkt_data = nullptr;
video_pkt_size = 0;
frame_buf = NULL;
pfb = _p;
//
printf("video timebase:%d/%d,tick:%d\n", pCodecCtx->time_base.num,
pCodecCtx->time_base.den,pCodecCtx->ticks_per_frame
);
src_w = dst_w = pCodecCtx->width;
src_h = dst_h = pCodecCtx->height;
src_pix_fmt = pCodecCtx->pix_fmt;
decoded_linesize[0] = flip_linesize[0] = 0;
decoded_data[0] = flip_buf[0] = nullptr;
init_sws_ctx();
}
~FFVDecoder()
{
if (frame_buf)
av_freep(&frame_buf[0]);
av_freep(&frame_buf);
free_buffer();
SDL_Log("release FFVDecoder!");
}
void init_sws_ctx()
{
// initialize SWS context for software scaling
if(sws_ctx==NULL)
{
sws_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height,pCodecCtx->pix_fmt,
dst_w,dst_h,dst_pix_fmt,
SWS_BILINEAR,NULL,NULL,NULL);
if(!sws_ctx){
fprintf(stderr,
"Impossible to create scale context for the conversion "
"fmt:%s s:%dx%d -> fmt:%s s:%dx%d\n",
av_get_pix_fmt_name(pCodecCtx->pix_fmt), pCodecCtx->width, pCodecCtx->height,
av_get_pix_fmt_name(dst_pix_fmt), dst_w, dst_h);
return;
}
}
alloc_buffer();
}
void alloc_buffer()
{
if(sws_ctx)
{
int ret1 = av_image_alloc(decoded_data,decoded_linesize,
dst_w,dst_h,dst_pix_fmt,1);
int ret2 = av_image_alloc(flip_buf, flip_linesize,
src_w,src_h,src_pix_fmt,1);
if(ret1<0 || ret2<0)
{
fprintf(stderr, "Could not allocate destination image\n");
}
SDL_Log("flip_buf:%d,%d",ret2,flip_linesize[0]);
}
}
void free_buffer()
{
if(decoded_data[0])
{
av_freep(&decoded_data[0]);
}
if(flip_buf[0])
{
av_freep(&flip_buf[0]);
}
}
int decode_one_pkt(AVPacket& _pkt, bool turn_img=true);
int decode(uint8_t* video_buf, int buf_size);
};
class ffStream
{
private:
std::string fname;
AVFormatContext *pFormatCtx;
AVCodecContext *aCodecCtx;
// AVCodecContext *aCodecCtxOrig;
AVCodec* aCodec;
SwrContext *swr;
int audioStream;
// TargetAudioParams target_params;
SafeQueue<AVPacket> packet_q;
bool has_open;
// uint8_t* decode_data;
// int decode_data_size;
// DataBuffer db;
std::shared_ptr<DataBuffer> pdb;
//stream api
uint8_t* avio_ctx_buffer;
AVIOContext* p_avio_ctx;
const uint32_t avio_ctx_buffer_size = 4096;
bool is_decode_all;
//decode
std::shared_ptr<FFDecoder> pdecoder;
private:
//video
int videoStream;
AVCodecContext* vCodecCtx;
AVCodec* vCodec;
std::shared_ptr<FrameBuffer> pvbuf;
std::shared_ptr<FFVDecoder> pvdecoder;
SafeQueue<AVPacket> video_packet_q;
public:
int freq;
int channels;
TargetAudioParams target_params;
const int BitsPerSample = 16;
const int BytesPerSample = 2;
uint64_t total_time; //ms
uint64_t n_src_samples;
bool decoded_end;
bool video_decoded_end;
uint64_t total_frame;
bool turn_img;
// uint32_t read_pos;
// uint32_t decoded_len;
public:
//video
int video_decode_nframe(int nframe = 1);
double get_fps()
{
if(vCodecCtx)
{
return 1.0 / av_q2d(vCodecCtx->time_base) / FFMAX(vCodecCtx->ticks_per_frame, 1);
}
return 0.0;
}
int get_width()
{
if(vCodecCtx)
{
return vCodecCtx->width;
}
return 0;
}
int get_height()
{
if(vCodecCtx)
return vCodecCtx->height;
return 0;
}
public:
ffStream(std::string name
, bool _is_decode_all=false
):is_decode_all(_is_decode_all)
{
init();
fname = name;
open_audio_file();
}
ffStream(bool _is_decode_all = false):
is_decode_all(_is_decode_all)
{
init();
}
void init()
{
fname = "";
pFormatCtx = NULL;
aCodecCtx = NULL;
// aCodecCtxOrig = NULL;
aCodec = NULL;
swr = NULL;
audioStream = -1;
memset(&target_params,0,sizeof(target_params));
freq = -1;
channels = 0;
avio_ctx_buffer = NULL;
p_avio_ctx = NULL;
pdb = nullptr;
pdecoder = nullptr;
decoded_end = false;
total_time = 0;
n_src_samples = 0;
has_open = false;
//video
videoStream = -1;
vCodecCtx = nullptr;
vCodec = nullptr;
pvbuf = nullptr;
pvdecoder = nullptr;
video_decoded_end = false;
total_frame = 0;
turn_img = true;
}
std::shared_ptr<DataBuffer> get_decode_buffer()
{
return pdb;
}
std::shared_ptr<FrameBuffer>get_video_buffer()
{
return pvbuf;
}
int open_audio_stream();
int open_audio_stream_cb(void* stream,tReadPacketCB read_packet_cb);
int open_audio_file();
void read_all_packet();
int audio_decode_frame(uint8_t* audio_buf, int buf_size);
void decode_all();
int decode_one();
void on_packet(AVPacket& pkt);
//audio
int Read(void* buf, uint32_t readsize)
{
int has_read = 0;
while(!decoded_end && readsize > pdb->readable_size())
{
decode_one();
}
has_read = pdb->fill((uint8_t*)buf,readsize);
return has_read;
}
void SetPos(uint32_t pos)
{
// read_pos = pos;
while(!decoded_end && pos > pdb->readable_size())
decode_one();
pdb->seek(pos);
}
//video
int ReadFrame(uint8_t** data, int size)
{
// int next_pos = cur_pos + 1;
while(!video_decoded_end && pvbuf->readable_frame()<1)
{
video_decode_nframe(5);
}
int r = pvbuf->read(data,size);
if(r > 0)
{
// cur_pos = next_pos;
return r;
}
return 0;
}
void SetFrame(uint32_t pos)
{
while(!video_decoded_end && pos > pvbuf->len)
{
video_decode_nframe(5);
}
pvbuf->seek(pos);
}
int GetFrame()
{
return pvbuf->get_pos();
}
uint64_t GetFrameNums()
{
return total_frame;
}
uint64_t GetVideoTotalTime() //ms
{
return (uint64_t)(1000 * total_frame / get_fps());
}
public:
int open_audio();
int open_video();
~ffStream();
};
#endif
| [
"zhangguof@gmail.com"
] | zhangguof@gmail.com |
c1b053fe91f13b414f8434b784a059c8b29f4a94 | 3b1489bdd63cd53770a066e6f90a13ef3286bfe7 | /include/cinder/vr/openvr/Controller.h | fbff03a9b24621ad12d2a3c96bcb5e3dbced02cc | [] | no_license | seph14/Cinder-VR | cc996f6b470e851d2c80370d0acefc9ecafbaa1a | 511d3c9422ff8012d3ee4d0dccb3ecbdfab07464 | refs/heads/master | 2021-01-12T19:44:17.842838 | 2017-02-16T20:02:59 | 2017-02-16T20:02:59 | 64,486,455 | 1 | 0 | null | 2016-07-29T14:22:05 | 2016-07-29T14:22:03 | null | UTF-8 | C++ | false | false | 4,516 | h | /*
Copyright 2016 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Copyright (c) 2016, The Cinder Project, All rights reserved.
This code is intended for use with the Cinder C++ library: http://libcinder.org
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "cinder/vr/Controller.h"
#if defined( CINDER_VR_ENABLE_OPENVR )
#include <openvr.h>
namespace cinder { namespace vr { namespace openvr {
class Context;
class Controller;
using ControllerRef = std::shared_ptr<Controller>;
//! \class Controller
//!
//!
class Controller : public vr::Controller {
public:
enum AxisIndex{
AXIS_INDEX_TOUCHPAD = 0,
AXIS_INDEX_TRIGGER = 1
};
~Controller();
static ci::vr::openvr::ControllerRef create( ::vr::TrackedDeviceIndex_t trackedDeviceIndex, ci::vr::Controller::Type type, ci::vr::Context *context );
virtual std::string getName() const override;
virtual std::string getButtonName( ci::vr::Controller::ButtonId ) const override;
virtual std::string getTriggerName( ci::vr::Controller::TriggerId ) const override;
virtual std::string getAxisName( ci::vr::Controller::AxisId ) const override;
virtual bool hasInputRay() const override { return mEventsEnabled ? true : false; }
::vr::TrackedDeviceIndex_t getTrackedDeviceIndex() const { return mTrackedDeviceIndex; }
virtual ::vr::EVRButtonId toOpenVr( ci::vr::Controller::ButtonId value ) const;
virtual ci::vr::Controller::ButtonId fromOpenVr( ::vr::EVRButtonId value ) const;
protected:
Controller( ::vr::TrackedDeviceIndex_t trackedDeviceIndex, ci::vr::Controller::Type type, ci::vr::Context *context );
friend class ci::vr::openvr::Context;
virtual void processControllerState( const ::vr::VRControllerState_t& state);
virtual void processButtons( const ::vr::VRControllerState_t& state );
virtual void processTriggers( const ::vr::VRControllerState_t& state );
virtual void processAxes( const ::vr::VRControllerState_t& state );
virtual void processControllerPose( const ci::mat4& inverseLookMatrix, const ci::mat4& inverseOriginMatrix, const ci::mat4& deviceToTrackingMatrix, const ci::mat4& trackingToDeviceMatrix );
bool mEventsEnabled = false;
bool isEventsEnabled() const { return mEventsEnabled; }
void setEventsEnabled( bool value = true ) { mEventsEnabled = value; }
void clearInputRay() { mInputRay = ci::Ray( ci::vec3( 0 ), ci::vec3(0 ) ); }
::vr::TrackedDeviceIndex_t mTrackedDeviceIndex = UINT32_MAX;
//ci::vr::Controller::HandId mHandId = ci::vr::Controller::HAND_UNKNOWN;
uint32_t mPacketNum = UINT32_MAX;
bool mTrackPadTouched = false;
bool mTriggerTouched = false;
};
}}} // namespace cinder::vr::vive
#endif // defined( CINDER_VR_ENABLE_OPENVR ) | [
"s@solid-jellyfish.com"
] | s@solid-jellyfish.com |
d0ef658dc125df1f5e74716b1e6edfa6628ac39e | b1b734ab75a6fe114733d3c0b8ca5046d54b407d | /third_party/ComputeLibrary/src/runtime/CL/functions/CLFullyConnectedLayer.cpp | 68c6576a7951b853c8714cc6f0140a73d455c226 | [
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause",
"Apache-2.0",
"MIT"
] | permissive | waybarrios/video_nonlocal_net_caffe2 | 754fea2b96318d677144f16faadf59cb6b00189b | b19c2ac3ddc1836d90d7d0fccb60d710c017253e | refs/heads/master | 2020-04-20T03:15:12.286080 | 2019-01-31T20:44:01 | 2019-01-31T20:44:01 | 168,593,110 | 0 | 0 | Apache-2.0 | 2019-01-31T20:40:40 | 2019-01-31T20:40:39 | null | UTF-8 | C++ | false | false | 15,575 | cpp | /*
* Copyright (c) 2017 ARM Limited.
*
* SPDX-License-Identifier: MIT
*
* 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 "arm_compute/runtime/CL/functions/CLFullyConnectedLayer.h"
#include "arm_compute/core/Size2D.h"
#include "arm_compute/core/Validate.h"
#include "arm_compute/core/utils/misc/ShapeCalculator.h"
#include "arm_compute/core/utils/quantization/AsymmHelpers.h"
#include "arm_compute/runtime/CL/CLScheduler.h"
#include "support/ToolchainSupport.h"
#include <algorithm>
using namespace arm_compute;
using namespace arm_compute::misc::shape_calculator;
namespace
{
Status validate_mm(const ITensorInfo &input, const ITensorInfo &weights, const ITensorInfo &output, bool is_interleaved_transposed)
{
const GPUTarget gpu_target = CLScheduler::get().target();
if(is_data_type_quantized_asymmetric(input.data_type()))
{
// Since we need negative offsets for computing convolution, we need to change QuantizationInfo()
// Extract and negate input and weights offset
const QuantizationInfo input_quantization_info(input.quantization_info().scale, -input.quantization_info().offset);
const QuantizationInfo weights_quantization_info(weights.quantization_info().scale, -weights.quantization_info().offset);
// Validate gemmlowp function
ARM_COMPUTE_RETURN_ON_ERROR(CLGEMMLowpMatrixMultiplyCore::validate(&input.clone()->set_quantization_info(input_quantization_info),
&weights.clone()->set_quantization_info(weights_quantization_info),
&output));
}
else
{
ARM_COMPUTE_RETURN_ON_ERROR(CLGEMMMatrixMultiplyKernel::validate(&input, &weights, &output, 1.f, is_interleaved_transposed, gpu_target));
}
return Status{};
}
} // namespace
void CLFullyConnectedLayerReshapeWeights::configure(const ICLTensor *input, ICLTensor *output)
{
auto k = arm_compute::support::cpp14::make_unique<CLTransposeKernel>();
k->configure(input, output);
_kernel = std::move(k);
}
Status CLFullyConnectedLayerReshapeWeights::validate(const ITensorInfo *input, const ITensorInfo *output)
{
return CLTransposeKernel::validate(input, output);
}
CLFullyConnectedLayer::CLFullyConnectedLayer(std::shared_ptr<IMemoryManager> memory_manager)
: _memory_group(memory_manager), _im2col_kernel(), _reshape_weights_kernel(), _mm_kernel(), _mm_gemmlowp(memory_manager), _gemmlowp_output_stage(), _accumulate_biases_kernel(), _im2col_output(),
_gemmlowp_output(), _reshape_weights_output(), _are_weights_reshaped(true), _is_fc_after_conv(true), _accumulate_biases(false), _is_quantized(false)
{
}
void CLFullyConnectedLayer::configure_mm(const ICLTensor *input, const ICLTensor *weights, ICLTensor *output, bool is_interleaved_transposed)
{
if(_is_quantized)
{
// Since we need negative offsets for computing convolution, we need to change QuantizationInfo()
// Extract and negate input and weights offset
const QuantizationInfo input_quantization_info = input->info()->quantization_info();
const QuantizationInfo weights_quantization_info = weights->info()->quantization_info();
input->info()->set_quantization_info(QuantizationInfo(input_quantization_info.scale, -input_quantization_info.offset));
weights->info()->set_quantization_info(QuantizationInfo(weights_quantization_info.scale, -weights_quantization_info.offset));
// Configure gemmlowp function
_mm_gemmlowp.configure(input, weights, output);
// Revert back QuantizatioInfo as input and weights could be used in other fully connected layers
input->info()->set_quantization_info(input_quantization_info);
weights->info()->set_quantization_info(weights_quantization_info);
}
else
{
// Configure matrix multiply kernel
_mm_kernel.set_target(CLScheduler::get().target());
_mm_kernel.configure(input, weights, output, 1.f, is_interleaved_transposed);
}
}
void CLFullyConnectedLayer::configure_conv_fc(const ICLTensor *input, const ICLTensor *weights, ICLTensor *output)
{
ARM_COMPUTE_ERROR_ON((weights->info()->dimension(1) != (input->info()->dimension(0) * input->info()->dimension(1) * input->info()->dimension(2))));
// If the fully connected layer is called after a convolution layer, the input tensor must be linearized
// Initialize output tensor for im2col
TensorShape shape_im2col = compute_im2col_shape(*input->info());
_im2col_output.allocator()->init(input->info()->clone()->set_is_resizable(true).reset_padding().set_tensor_shape(shape_im2col));
// Configure im2col kernel
_memory_group.manage(&_im2col_output);
_im2col_kernel.configure(input, &_im2col_output, Size2D(1, 1), PadStrideInfo(1, 1, 0, 0), false);
// Configure matrix multiply kernel
configure_mm(&_im2col_output, weights, output, false);
// Allocate the output tensor for im2col once all the configure methods have been called
_im2col_output.allocator()->allocate();
}
void CLFullyConnectedLayer::configure_fc_fc(const ICLTensor *input, const ICLTensor *weights, ICLTensor *output)
{
ARM_COMPUTE_ERROR_ON(input->info()->dimension(0) != weights->info()->dimension(1));
// Configure matrix multiply kernel
configure_mm(input, weights, output, false);
}
void CLFullyConnectedLayer::configure(const ICLTensor *input, const ICLTensor *weights, const ICLTensor *biases, ICLTensor *output, bool transpose_weights, bool are_weights_reshaped)
{
ARM_COMPUTE_ERROR_ON_NULLPTR(input, weights, output);
// Perform validate step
ARM_COMPUTE_ERROR_THROW_ON(CLFullyConnectedLayer::validate(input->info(),
weights->info(),
biases != nullptr ? biases->info() : nullptr,
output->info(),
transpose_weights,
are_weights_reshaped));
_are_weights_reshaped = transpose_weights ? are_weights_reshaped : true;
_is_fc_after_conv = true;
_accumulate_biases = false;
_is_quantized = is_data_type_quantized_asymmetric(input->info()->data_type());
// Configure gemmlowp output
if(_is_quantized)
{
_gemmlowp_output.allocator()->init(output->info()->clone()->set_is_resizable(true).reset_padding().set_data_type(DataType::S32));
}
// Configure accumulate biases kernel for non quantized asymmetric types
if(biases != nullptr && !_is_quantized)
{
ARM_COMPUTE_ERROR_ON_MISMATCHING_DATA_TYPES(input, biases);
_accumulate_biases = true;
// Configure accumulate biases kernel
_accumulate_biases_kernel.set_target(CLScheduler::get().target());
_accumulate_biases_kernel.configure(output, biases);
}
// With the Fully Connected layer we can have 4 different cases:
// 1) Convolution layer -> Fully Connected layer without batches
// 2) Fully Connected layer -> Fully Connected layer without batches
// 3) Convolution layer -> Fully Connected layer with batches
// 4) Fully Connected layer -> Fully Connected layer with batches
const ICLTensor *weights_to_use = weights;
if(!_are_weights_reshaped)
{
weights_to_use = &_reshape_weights_output;
// Reshape the weights
_reshape_weights_kernel.configure(weights, &_reshape_weights_output);
}
// Check if we have a fully connected layer with batches
const bool is_batched_fc_layer = output->info()->dimension(1) > 1;
if(is_batched_fc_layer)
{
_is_fc_after_conv = (TensorShape::num_max_dimensions >= 4) && (std::equal(input->info()->tensor_shape().cbegin() + 3,
input->info()->tensor_shape().cend(),
output->info()->tensor_shape().cbegin() + 1));
}
else
{
_is_fc_after_conv = input->info()->num_dimensions() > 1;
}
ICLTensor *tmp_output = (_is_quantized) ? &_gemmlowp_output : output;
if(_is_fc_after_conv)
{
// Fully Connected layer after a Convolution Layer without batches
configure_conv_fc(input, weights_to_use, tmp_output);
}
else
{
// Fully Connected layer after a Fully Connected Layer without batches
configure_fc_fc(input, weights_to_use, tmp_output);
}
// Configure output stage for asymmetric quantized types
if(_is_quantized)
{
float multiplier = input->info()->quantization_info().scale * weights->info()->quantization_info().scale / output->info()->quantization_info().scale;
int output_multiplier, output_shift;
quantization::calculate_quantized_multiplier_less_than_one(multiplier, &output_multiplier, &output_shift);
_gemmlowp_output_stage.configure(&_gemmlowp_output, biases, output, output_multiplier, output_shift, output->info()->quantization_info().offset);
_gemmlowp_output.allocator()->allocate();
}
// Allocate the transpose tensor if the are_weights_reshaped flag is false and once all the configure methods have been called
if(!_are_weights_reshaped)
{
// Allocate the tensor for the weights reshaped
_reshape_weights_output.allocator()->allocate();
}
}
Status CLFullyConnectedLayer::validate(const ITensorInfo *input, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *output, bool transpose_weights, bool are_weights_reshaped)
{
ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(input, weights, output);
ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(input, 1, DataType::QS8, DataType::QASYMM8, DataType::QS16, DataType::F16, DataType::F32);
ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input, weights, output);
ARM_COMPUTE_RETURN_ERROR_ON(weights->num_dimensions() > 2);
bool weights_reshaped = transpose_weights ? are_weights_reshaped : true;
bool is_fc_after_conv = true;
bool is_quantized = is_data_type_quantized_asymmetric(input->data_type());
const GPUTarget gpu_target = CLScheduler::get().target();
const ITensorInfo &im2col_input = TensorInfo(input->clone()->set_is_resizable(true).reset_padding().set_tensor_shape(compute_im2col_shape(*input)));
const ITensorInfo &reshaped_weights = TensorInfo(weights->clone()->set_is_resizable(true).reset_padding().set_tensor_shape(compute_transposed_shape(*weights)));
const ITensorInfo &gemmlowp_output = TensorInfo(output->clone()->set_is_resizable(true).reset_padding().set_data_type(DataType::S32));
// Configure accumulate biases kernel for non quantized asymmetric types
if(biases != nullptr && !is_quantized)
{
ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input, biases);
ARM_COMPUTE_RETURN_ON_ERROR(CLGEMMMatrixAccumulateBiasesKernel::validate(output, biases, gpu_target));
}
// With the Fully Connected layer we can have 4 different cases:
// 1) Convolution layer -> Fully Connected layer without batches
// 2) Fully Connected layer -> Fully Connected layer without batches
// 3) Convolution layer -> Fully Connected layer with batches
// 4) Fully Connected layer -> Fully Connected layer with batches
const ITensorInfo *input_to_use = input;
const ITensorInfo *weights_to_use = weights;
const ITensorInfo *tmp_output = (is_quantized) ? &gemmlowp_output : output;
if(!weights_reshaped)
{
// Validate reshape weights kernel
ARM_COMPUTE_RETURN_ON_ERROR(CLFullyConnectedLayerReshapeWeights::validate(weights, &reshaped_weights));
weights_to_use = &reshaped_weights;
}
// Check if we have a fully connected layer with batches
const bool is_batched_fc_layer = output->dimension(1) > 1;
if(is_batched_fc_layer)
{
is_fc_after_conv = (TensorShape::num_max_dimensions >= 4) && (std::equal(input->tensor_shape().cbegin() + 3,
input->tensor_shape().cend(),
output->tensor_shape().cbegin() + 1));
}
else
{
is_fc_after_conv = input->num_dimensions() > 1;
}
if(is_fc_after_conv)
{
// Fully Connected layer after a Convolution Layer without batches
ARM_COMPUTE_RETURN_ERROR_ON((weights_to_use->dimension(1) != (input->dimension(0) * input->dimension(1) * input->dimension(2))));
// Validate im2col kernel
ARM_COMPUTE_RETURN_ON_ERROR(CLIm2ColKernel::validate(input, &im2col_input, Size2D(1, 1), PadStrideInfo(1, 1, 0, 0), false));
input_to_use = &im2col_input;
}
else
{
// Fully Connected layer after a Fully Connected Layer without batches
ARM_COMPUTE_RETURN_ERROR_ON(input->dimension(0) != weights_to_use->dimension(1));
}
// Validate matrix multiply kernel
ARM_COMPUTE_RETURN_ON_ERROR(validate_mm(*input_to_use, *weights_to_use, *tmp_output, false));
// Validate output stage for asymmetric quantized types
if(is_quantized)
{
ARM_COMPUTE_RETURN_ON_ERROR(CLGEMMLowpQuantizeDownInt32ToUint8ScaleByFixedPoint::validate(&gemmlowp_output, biases, output));
}
return Status{};
}
void CLFullyConnectedLayer::run()
{
// Reshape of the weights (happens only once)
if(!_are_weights_reshaped)
{
_are_weights_reshaped = true;
_reshape_weights_kernel.run();
}
_memory_group.acquire();
// Linearize input if it comes from a convolutional layer
if(_is_fc_after_conv)
{
CLScheduler::get().enqueue(_im2col_kernel, false);
}
// Run matrix multiply
if(_is_quantized)
{
_mm_gemmlowp.run();
}
else
{
CLScheduler::get().enqueue(_mm_kernel, !_accumulate_biases);
}
// Accumulate biases if provided
if(_is_quantized)
{
_gemmlowp_output_stage.run();
}
else
{
if(_accumulate_biases)
{
CLScheduler::get().enqueue(_accumulate_biases_kernel);
}
}
_memory_group.release();
}
| [
"gemfield@civilnet.cn"
] | gemfield@civilnet.cn |
8f3713fd690223c15a71a5fb8c4c2590998d7e66 | d3483de380893ec9982df64cb70e4c0b2096591b | /PerformDecomp/src/RootInterface/ScanGrabber.cpp | d6e0d2ca88a41aab190754c87b82221a07131400 | [] | no_license | jmatta1/SourceDecomposition | 9bd4830ab6c270ddf272ff7fb19b48ff060b0f45 | 76108385084fad4dccdbefa24e444552d044f22c | refs/heads/master | 2021-01-01T18:25:16.086506 | 2017-09-08T15:05:57 | 2017-09-08T15:05:57 | 98,332,218 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,391 | cpp | #include"ScanGrabber.h"
#include<sstream>
#include<TFile.h>
#include<TH1.h>
namespace ScanInternal
{
static const int DetNums[105] =
{
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15
};
static const int RunNums[105] =
{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14
};
}
ScanGrabber::ScanGrabber(const std::string& inFileName,
int numPos, int numEnBins) :
scanData(nullptr), scanDataTr(nullptr), numPositions(numPos),
numEnergyBins(numEnBins)
{
//first allocate and initialize the data arrays
allocAndInit();
//now go through and load the scan data corresponding to each position index
loadData(inFileName);
}
void ScanGrabber::allocAndInit()
{
int numBins = numPositions*numEnergyBins;
scanData = new double[numBins];
scanDataTr = new double[numBins];
for(int i=0; i<numBins; ++i)
{
scanData[i] = 0.0;
scanDataTr[i] = 0.0;
}
}
void ScanGrabber::loadData(const std::string& inFileName)
{
TFile* file = new TFile(inFileName.c_str());
for(int i=0; i<numPositions; ++i)
{
std::ostringstream namer;
namer<<"Decomp_"<<ScanInternal::DetNums[i]<<"_"<<ScanInternal::RunNums[i];
TH1D* hist = (TH1D*)file->Get(namer.str().c_str());
if(i==0)
{
minEdge = hist->GetBinLowEdge(1);
maxEdge = hist->GetBinLowEdge(numEnergyBins+1);
}
for(int j=0; j<numEnergyBins; ++j)
{
double temp = hist->GetBinContent(j+1);
scanData[j*numPositions + i] = temp;
scanDataTr[i*numEnergyBins + j] = temp;
}
delete hist;
}
delete file;
}
| [
"jamesmatta@gmail.com"
] | jamesmatta@gmail.com |
b2c12a0123501a0bee669035581f2aa68f26dc09 | 82a3e40b75d0cc4250998702c2bff873590d92db | /src/data/criterion.h | caec74b8e2752a608994916d2ae8abaa901c7828 | [] | no_license | PavelAmialiushka/Aera.demo | 12c7981d0883e8b832c2f3e72fee14234cdeb3b0 | 4beeb315a99da6f90a87ba0bb5b3dffa6c52bd2d | refs/heads/master | 2021-10-11T14:41:00.180456 | 2019-01-27T13:38:21 | 2019-01-27T13:38:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,927 | h | //////////////////////////////////////////////////////////////////////////
//
// data library
//
// Written by Pavel Amialiushka
// No commercial use permited.
//
//////////////////////////////////////////////////////////////////////////
#pragma once
#include "data_fwrd.h"
#include "stage.h"
#include "utilites/serl/Archive.h"
namespace monpac
{
//////////////////////////////////////////////////////////////////////////
enum zip_t
{
zip_0,
zip_a,
zip_b,
zip_c,
zip_d,
zip_e,
zip_na,
};
//////////////////////////////////////////////////////////////////////////
struct hit
{
hit(double t, double c, double a, double e, double d)
: amplitude(a), channel(c), time(t), energy(e), duration(d)
{
}
double time;
double channel;
double amplitude;
double duration;
double energy;
};
//////////////////////////////////////////////////////////////////////////
typedef stage hold;
//////////////////////////////////////////////////////////////////////////
class criterion : public serl::serializable
{
public:
criterion();
void set_stage(const stage &stg);
stage get_stage() const;
void set_vessel(int);
void set_test_threshold(bool);
zip_t get_zip(unsigned cnt, double h, double s);
int get_vessel() const;
int get_max_hit65() const;
double get_max_duration() const;
int get_max_total_hits() const;
unsigned get_max_hold_hits() const;
int get_hold_pause() const;
bool get_test_threshold() const;
double get_threashold() const;
int get_hold(double) const;
const std::vector<hold> &get_holds() const;
void serialization(serl::archiver &ar);
private:
bool test_threshold_;
int vessel_;
std::string text_;
stage stage_;
std::vector< stage > holds_;
};
//////////////////////////////////////////////////////////////////////////
} | [
"Amialiushka@gmail.com"
] | Amialiushka@gmail.com |
2bd4af011a091e2c6be03fab426f655bbdd9574c | 7f69fb7f33bd449cb305305a898e2827b3f8d6ba | /MoviesProject/movie.cpp | 76e451aa11f07a3ad39071d01e19db0afd2cc2e3 | [] | no_license | simonpals/Hash_table_movies | dc9be9f6d9bb4ee48a75989ae52bb1fe9bae4565 | 8d0dc187cc7e1391b3955967b59ab0d7f1f69510 | refs/heads/master | 2022-11-29T00:44:29.902997 | 2020-08-11T20:37:08 | 2020-08-11T20:37:08 | 286,842,874 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,456 | cpp | #include "movie.h"
Movie::Movie()
: Movie("","","",0)
{
}
Movie::Movie(std::string title, std::string leadActorActress, std::string description, int yearReleased)
{
next = nullptr;
prev = nullptr;
this->title = title;
this->leadActorActress = leadActorActress;
this->description = description;
this->yearReleased = yearReleased;
}
bool Movie::operator<=(const Movie &movie)
{
return this->yearReleased <= movie.yearReleased;
}
void Movie::Print()
{
std::cout << GetTitle() << "," << GetLeadActorActress() << "," << GetDescription() << "," << GetYearReleased() << '\n';
}
Movie * Movie::GetNext()
{
return next;
}
void Movie::SetNext(Movie * next)
{
this->next = next;
}
Movie * Movie::GetPrev()
{
return prev;
}
void Movie::SetPrev(Movie * prev)
{
this->prev = prev;
}
std::string Movie::GetTitle()
{
return this->title;
}
void Movie::SetTitle(std::string title)
{
this->title = title;
}
std::string Movie::GetLeadActorActress()
{
return leadActorActress;
}
void Movie::SetLeadActorActress(std::string leadActorActress)
{
this->leadActorActress = leadActorActress;
}
std::string Movie::GetDescription()
{
return description;
}
void Movie::SetDescription(std::string description)
{
this->description = description;
}
int Movie::GetYearReleased()
{
return yearReleased;
}
void Movie::SetYearReleased(int yearReleased)
{
this->yearReleased = yearReleased;
}
| [
"semenyshyn@nltu.edu.ua"
] | semenyshyn@nltu.edu.ua |
fb049d120d89e9208602f24ab2fac009496161c4 | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14468/function14468_schedule_18/function14468_schedule_18.cpp | 171426636ae3fcf4fd513811e824a20a3b2a4c88 | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,493 | cpp | #include <tiramisu/tiramisu.h>
using namespace tiramisu;
int main(int argc, char **argv){
tiramisu::init("function14468_schedule_18");
constant c0("c0", 8192), c1("c1", 128), c2("c2", 64);
var i0("i0", 0, c0), i1("i1", 0, c1), i2("i2", 0, c2), i01("i01"), i02("i02"), i03("i03"), i04("i04"), i05("i05"), i06("i06");
input input00("input00", {i0, i2}, p_int32);
input input01("input01", {i0}, p_int32);
input input02("input02", {i1, i2}, p_int32);
input input03("input03", {i1}, p_int32);
input input04("input04", {i0}, p_int32);
computation comp0("comp0", {i0, i1, i2}, input00(i0, i2) + input01(i0) * input02(i1, i2) - input03(i1) * input04(i0));
comp0.tile(i0, i1, i2, 32, 64, 64, i01, i02, i03, i04, i05, i06);
comp0.parallelize(i01);
buffer buf00("buf00", {8192, 64}, p_int32, a_input);
buffer buf01("buf01", {8192}, p_int32, a_input);
buffer buf02("buf02", {128, 64}, p_int32, a_input);
buffer buf03("buf03", {128}, p_int32, a_input);
buffer buf04("buf04", {8192}, p_int32, a_input);
buffer buf0("buf0", {8192, 128, 64}, p_int32, a_output);
input00.store_in(&buf00);
input01.store_in(&buf01);
input02.store_in(&buf02);
input03.store_in(&buf03);
input04.store_in(&buf04);
comp0.store_in(&buf0);
tiramisu::codegen({&buf00, &buf01, &buf02, &buf03, &buf04, &buf0}, "../data/programs/function14468/function14468_schedule_18/function14468_schedule_18.o");
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
58f9ad1ab90143f8c10f1cbb480c509e239dc390 | a6d6768f0cb3cf60ead4861f3d0956542647e2be | /src/include/ontologyRecord.h | 1e294ab5a5c03b54d21571510dd1ed4c57af283b | [] | no_license | mclumd/MCL | d8707e7b85476a6f926757980b1f7313915cbe60 | 90c6a70187ab13e8ba664038eb2205f9667f8607 | refs/heads/master | 2020-04-12T05:46:15.173170 | 2014-02-06T23:35:57 | 2014-02-06T23:35:57 | 16,597,476 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,052 | h | #include "mclEntity.h"
#include <map>
using namespace std;
namespace metacog {
class mclFrame;
class ontologyRecord : public frameComponent {
public:
ontologyRecord(mclFrame* the_frame);
virtual ~ontologyRecord() {};
virtual string toString();
virtual vector<string> nodeNames()=0;
virtual double p_for(string node)=0;
static const double P_NONE = -1.0;
protected:
mclFrame* my_frame;
private:
int when;
};
class ontologyRecord_map : public ontologyRecord {
public:
ontologyRecord_map(mclFrame* the_frame);
virtual ~ontologyRecord_map() {};
static const double P_NONE = -1.0;
virtual vector<string> nodeNames();
virtual double p_for(string node);
virtual string baseClassName() { return "or_map"; };
protected:
private:
map<string,double> p_map;
};
class or_comparison {
public:
or_comparison() {};
virtual ~or_comparison() {};
virtual double similarity(const ontologyRecord& or1,
const ontologyRecord& or2)=0;
};
};
| [
"e.hand@live.com"
] | e.hand@live.com |
e3fcdf1679734d54a728a0c5b6496f687836474d | 2147d0d957b3189d0a87fd31d84812556bb379f5 | /vlib/ssci/bio/bioseqalignQrySub.cpp | 14de9f9d9487604774a443a30f864423689b7cac | [] | no_license | kkaragiannis/DVG-profiler | 74d894f44c4f6e752e943ff2b0f4e2aaa473300c | a35e65ef255ab3dc90da1e1087d5c4a7a9b41e0a | refs/heads/master | 2020-04-11T08:53:07.643424 | 2018-12-14T01:26:04 | 2018-12-14T01:26:04 | 161,658,993 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,608 | cpp | /*
* ::718604!
*
* Copyright(C) November 20, 2014 U.S. Food and Drug Administration
* Authors: Dr. Vahan Simonyan (1), Dr. Raja Mazumder (2), et al
* Affiliation: Food and Drug Administration (1), George Washington University (2)
*
* All rights Reserved.
*
* The MIT License (MIT)
*
* 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 <slib/core.hpp>
#include <slib/std/file.hpp>
#include <ssci/bio/bioseq.hpp>
#include <ctype.h>
using namespace slib;
#define _costMatch(_v_sbits, _v_qbits) (((_v_sbits) != (_v_qbits)) ? costMismatch : costMatch)
#define QIDX(_v_iq, _v_len) ((flags&fAlignBackward) ? ((_v_len)-1-(_v_iq)) : (_v_iq))
#define SIDX(_v_is, _v_len) ( ( (!(flags&fAlignCircular)) || (_v_is)<(_v_len) ) ? (_v_is) : ( (_v_is) -(_v_len) ) )
//sPerf bioPerf;
idx cntHashLookup=0,cntBloomLookup=0,cntHSPHit=0,cntAlignmentSW=0,cntTotLetters=0;
// _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
// _/
// _/ Major Alignment Procedures
// _/
// _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
idx sBioseqAlignment::findHSPs(sIndex <HSP > & hspTbl, const char * qry, idx qrylen, idx id, idx flagset, idx * subfos, idx * qryfos)
{
idx flags=flagset;
idx hspPara=(bioHash.hdr.lenUnit);
idx oldHashList[32];
//
// now build HSPs
//
for ( idx idir=0; idir < 2; ++idir) {
idx mask = (idir==0) ? fAlignForward : fAlignBackward; // direction considering now
if( !(flagset&mask) ) continue; // this does not seem to be required to compute now
flags=( flagset&(~(fAlignForward|fAlignBackward)) ) | mask;
udx chash=0,chash2=0; // this is unsigned due to rotations sign digit overload
for( idx iq=0; iq<qrylen; ++iq ) {
++cntTotLetters;
// prepare the hash for this position
chash <<= 2;
idx iqx=QIDX(iq,qrylen);
chash|=_seqBits(qry, iqx , flags);
if(iq<bioHash.hdr.lenUnit-1)continue; // we still didn't accumulate enough letters
chash&=bioHash.hdr.hashMask;
if( flags&fAlignOptimizeDoubleHash ){
chash2=oldHashList[iq%bioHash.hdr.lenUnit];
oldHashList[iq%bioHash.hdr.lenUnit]=chash;
if(iq<2*bioHash.hdr.lenUnit-1)continue; // we still didn't accumulate enough letters
}
//retrieve the list of hits from subject
++cntBloomLookup;
if( (bioHash.hb [chash/8] & (((udx)1)<<(chash%8))) ==0 )
continue;
++cntHashLookup;
idx lstdim=bioHash.cnt(chash) ,lstdim2=0;
//if(lstdim==0)continue; filtered by bloom;
sBioseqHash::RefPos * lst=bioHash.lst(chash), * list2=0;
if( flags&fAlignOptimizeDoubleHash ){ // bloom
if( (bioHash.hb [chash2/8] & (((udx)1)<<(chash2%8))) !=0 ){ // bloom
lstdim2=bioHash.cnt(chash2);
list2=bioHash.lst(chash2);
}
else continue;
//if(!lstdim2) continue;// filtered by bloom
}
idx qpos=iq-bioHash.hdr.lenUnit+1;
// for all of the hits at this position
for ( idx il=0; il<lstdim ; ++il ) {
// get the match position
sBioseqHash::RefPos & ref=lst[il];
idx refid=ref.id();
idx refpos=ref.pos();
if(id!=sNotIdx && refid!=id) continue; // this reference is to a different sequence
idx matchShape=0;
if(subfos ){
idx * thissubfos=sBioseqHash::fos(subfos, refid );
//idx cntfos=*subfos; ++subfos;
idx pos=(refpos-1)/500+1;//, ps=pos-1, pe=pos+1;
//if(ps<0)ps=0;if(pe>=cntfos)pe=cntfos;
//for ( idx ip=ps ; ip<pe; ++ip ){ // check three fossils
idx sfos=thissubfos[pos];
idx qfos=qryfos[1];
if(idir)qfos>>=24;
//if(qryfos[1]&sfos)
matchShape=sfos;
//}
}
if( flags&fAlignOptimizeDoubleHash ) {
idx i2;
for( i2=0; i2<lstdim2 ; ++i2){
if( list2[i2]._pos == ref._pos-(bioHash.hdr.lenUnit) )break;
}
if(i2==lstdim2) continue; /// didn't find the second piece of a hash
}
++cntHSPHit;
HSP hsp;
hsp.subPosExact=refpos;//ref.pos(); // the position where the first unit would have been aligned (not necessarily through an exact match)
hsp.qryPosExact=qpos;
hsp.refid=refid;//ref.id();
hsp.flags=flags;
hsp.defint=ref._pos-qpos;
if(hsp.defint<0)hsp.defint=0;
hsp.refcnt=0;
hsp.defint=(hsp.defint/hspPara)*hspPara;
if((flags&fAlignBackward))hsp.defint=-1-hsp.defint;
hsp.matchShape=matchShape;
idx r=hspTbl.add(hsp.defint,hsp);
++hspTbl[r].refcnt;
}
}
}
return hspTbl.dim();
}
idx sBioseqAlignment::alignfromHSPs(HSP * pr, sVec < sVec < idx > > * hits , const char * sub, idx sublen , const char * qry, idx qrylen, idx id, idx flagset)
{
idx pos=pr->subPosExact-pr->qryPosExact;
idx revshift=0;
if(pos<0) {revshift=-pos; pos=0;}
// run Smith Waterman
sVec <idx > * al=hits->add();
idx flags=( flagset&(~(fAlignForward|fAlignBackward)) ) | (pr->defint<0 ? fAlignBackward : fAlignForward );
if(!computeDiagonalWidth)computeDiagonalWidth=bioHash.hdr.lenUnit/2;
idx slen=sublen-pos;
if(slen>qrylen+computeDiagonalWidth)slen=qrylen+computeDiagonalWidth;
++cntAlignmentSW;
alignSmithWaterman(al,sub, pos, slen, qry, revshift, qrylen-revshift, flags , sublen, qrylen);
Al * hdr=(Al *)al->ptr();
hdr->idSub=id;
return hits->dim();
}
idx sBioseqAlignment::alignSmithWaterman( sVec < idx > * al, const char * sub, idx substart, idx sublen, const char * qry, idx qrystart, idx qrylen, idx flags , idx subbuflen, idx qrybuflen)
{
//vioPerf.start("alignSW1");
// #ifndef sBIO_ATGC_SEQ_2BIT
// idx isComp=( (flags&fAlignForwardComplement) && (flags&fAlignForward) ) || ( (flags&fAlignBackwardComplement) &&(flags&fAlignBackward) ) ? true : false;
// #endif
if(!qrybuflen)qrybuflen=qrylen;
idx reserve=1024*1024;
idx maxSeq=qrylen*2+computeDiagonalWidth; /// the maximum number of sequence letters to be considered cannot be bigger than this.
idx sz=(maxSeq+2)*(qrylen+1);if(sz<reserve)sz=reserve;
MatSW.resizeM(sz*2); // make sure there is enough space to hold the matrix
short int * matP=(short int *)MatSW.ptr();
//memset(matP,0,sz*sizeof(short int));
sz=(maxSeq+1)*qrylen;if(sz<reserve)sz=reserve;
MatBR.resizeM(sz); // this matrix doesn't have the zeroth elements , so it is one less
char * matB=MatBR.ptr();
//memset(matB,0,sz*sizeof(char));
// we keep a matrix of for smith waterman algorithm
#define mat(_v_i, _v_j) matP[(qrylen+1)*(_v_i)+(_v_j)]
#define bak(_v_i, _v_j) matB[(qrylen)*(_v_i)+(_v_j)]
idx fv,cv=0;//,bestCasePotential;
idx maxAll=0, maxAllLastLetter=0; // the maximal score
idx maxS=0, maxQ=0, maxRowLastLetter=0, maxColLastLetter=0; // maxS,maxQ: the position of the maxAll
// cellsComputed=0;
idx qStart=0, qEnd=(flags&fAlignOptimizeDiagonal ) ? computeDiagonalWidth : qrylen; // definition of the diagonal width where we compute
//DEBUG_OUT_SMITHWATERMANN_TABLE_HEADER
idx is, iq;
idx nonCompFlags=(flags&(~(fAlignBackwardComplement|fAlignForwardComplement)));
//vioPerf.end();
//vioPerf.start("alignSW2");
for( is=0; is<sublen; ++is ) {
//vioPerf.start("alignSW2 - 1 ");
idx isx=SIDX( (substart+is) , subbuflen);
#ifdef sBIO_ATGC_SEQ_2BIT
idx sBits=_seqBits(sub, isx, nonCompFlags ); // this is the current sequence letter (bits) on the subject
#else
idx sBits=sub[isx];
#endif
idx maxRow=0;
idx maxRowPos=0;
//vioPerf.end();
//vioPerf.start("alignSW2 - 2 ");
for( iq=qStart; iq<qEnd; ++iq ) {
idx iqx=QIDX((qrystart+iq),qrybuflen);
//#ifdef sBIO_ATGC_SEQ_2BIT
idx qBits=_seqBits(qry, iqx, flags) ; // this is the current sequence letter (bits) on the query
//#else
// idx qBits= ( isComp ) ? sBioseq::mapComplementATGC[(idx)qry[iqx]] : qry[iqx];
//#endif
cv=mat(is+1,iq+1);
// consider a match
fv=mat(is,iq)+_costMatch( sBits , qBits );
if( cv<=fv ) {cv=fv; bak(is,iq)=3; };// if(is && iq)back(is-1,iq-1)|=0x30; }
// consider insertion
fv=mat(is,iq+1)+ ( (is==0 || bak(is-1,iq)==3) ? costGapOpen : costGapNext);//_costMatch(-1, sBits);
if( cv<fv ) {cv=fv; bak(is,iq)=1; }// if(is)back(is-1,iq)|=0x30; }
// consider deletion
fv=mat(is+1,iq)+( (iq==0 || bak(is,iq-1)==3) ? costGapOpen : costGapNext);//_costMatch(sBits,-1);
if( cv<fv ) {cv=fv; bak(is,iq)=2;};// if(iq)back(is,iq-1)|=0x20; }
// is still better to be aligned or start a new one ?
if(cv>0){
mat(is+1,iq+1)=(short int)cv;
if(cv>=maxRow){ // we remember the Rows maximum value and its position for local alignment
maxRow=cv; // it will be useful for exit criteria
maxRowPos=iq;
}
}
}
//vioPerf.end();
//vioPerf.start("alignSW2 - 3 ");
// for global alignments we remember the max score and row for the last letter (all sequence is aligned)
if( flags&fAlignGlobal) {
if( maxAllLastLetter< cv ) {
maxAllLastLetter=cv;
maxRowLastLetter=is; // qEnd-1; //is
maxColLastLetter=qEnd-1; // qEnd-1; //is
}
}
// we remember where the maximum score alignment starts
if(maxAll<maxRow || ( (flags&fAlignMaxExtendTail) && maxAll==maxRow) ) { // for local alignment
maxAll=maxRow;
maxS=is;
maxQ=maxRowPos;
}
if(flags&fAlignOptimizeDiagonal) {
qStart=is-computeDiagonalWidth;
if(qStart<0)qStart=0;
qEnd=is+computeDiagonalWidth;
if(qEnd>qrylen)qEnd=qrylen;
}
//DEBUG_OUT_SMITHWATERMANN_TABLE_ROW
if(qStart>=qrylen-1)break;
}
//vioPerf.end();
//vioPerf.start("alignSW3");
//
// traceback mechanism
//
al->resizeM(sizeof(Al)/sizeof(idx)); // initialize the header
Al * hdr=(Al*)al->ptr();
sSet(hdr);
//hdr->scoreLocal=maxAll;
//hdr->scoreGlobal=maxAllLastLetter;
hdr->flags=flags;
if(flags&fAlignGlobal) {
maxAll=maxAllLastLetter;
maxS=maxRowLastLetter;
maxQ=maxColLastLetter; // qrylen-1
hdr->score=maxAllLastLetter;//hdr->scoreGlobal;
}else
hdr->score=maxAll;//hdr->scoreLocal;
hdr->dimAlign=0; // to be counted a little later
hdr->subStart=substart;
hdr->qryStart=qrystart;
hdr->subEnd=maxS+hdr->subStart; // the maximum subject window used for alignment : +1 is because maxS was an index
hdr->qryEnd=maxQ+hdr->qryStart; // qryLen // the maximum query window used for alignment
//
// first we determine the length
//
idx dlen;
for(dlen=0, is=maxS, iq=maxQ, cv=maxAll; ; cv=mat(is+1,iq+1) , dlen+=2) { // start walking back on backtrace pointers
if(flags&fAlignGlobal){ if(iq<0 || is<0) break;} // break when we reach the first letter in global alignment
else if(cv<=0) break;// break if we reach the 0 score in local alignment
//else if(cv<=0 || is<0 || iq<0) break;// break if we reach the 0 score in local alignment
char bw=bak(is,iq);
if( (!(flags&fAlignMaxExtendTail)) && cv<costMatch ){ break;} // if we want compact alignment ... no reason to walk left without gaining anything
if(!bw) break;
if(bw & 0x1)--is; // backstep
if(bw & 0x2)--iq;
}
idx * m=al->addM(dlen);//+(sizeof(Alignment::Hdr)/sizeof(idx)) ); // this is the real number of elements needed
hdr=(Al*)al->ptr(); // because it may have been reallocated
bak(0,0)=3;
hdr->dimAlign=dlen;
for(dlen-=2, is=maxS, iq=maxQ, cv=maxAll; dlen>=0 ; cv=mat(is+1,iq+1) , dlen-=2) { // start walking back on backtrace pointers
char bw=bak(is,iq);
m[dlen]= bw==0x02 ? -1 : is; // here we remember the matching pairs: the fact that subject position goes after
m[dlen+1]= bw==0x01 ? -1 : iq; // query position is reverted in the next loop during reversal of the array to forward order
if(bw & 0x1)--is; // backstep
if(bw & 0x2)--iq;
}
hdr->lenAlign=hdr->dimAlign;
//vioPerf.end();
//vioPerf.start("alignSW4");
//set back things to zero
qStart=0;
qEnd=(flags&fAlignOptimizeDiagonal ) ? computeDiagonalWidth : qrylen; // definition of the diagonal width where we compute
for( is=0; is<sublen; ++is ) {
for( iq=qStart; iq<qEnd; ++iq ) {
mat(is+1,iq+1)=0;
bak(is,iq)=0;
if(flags&fAlignOptimizeDiagonal) {
qStart=is-computeDiagonalWidth;
if(qStart<0)qStart=0;
qEnd=is+computeDiagonalWidth;
if(qEnd>qrylen)qEnd=qrylen;
}
}
}
//vioPerf.end();
return 1;
#undef mat
}
// _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
// _/
// _/ Manipulating Alignments
// _/
// _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
/*
idx sBioseqAlignment::alignmentSplit(const char * prefix, sVec < FILE* > * fps , Al * hdr, Al * hdre, idx cntBestHit, idx subNum, idx start, idx cnt)
{
sVec < sStr > * strL = prefix ? 0 : (sVec < sStr > * ) fps ;// the pointer is FILE pointer and we work in file mode
idx MM[2]={0,0};
idx cntCurHit=0,idLastHit=-1,i;
sStr t1;
for ( i=0; hdr<hdre && i<cnt+start ; ++i) {
if(i<start)continue;
if(subNum!=sNotIdx && hdr->idSub!=subNum) continue; // particular subid is required
if(hdr->idQry!=idLastHit) {idLastHit=hdr->idQry;cntCurHit=1;} // a new query sequence hits are here
else ++cntCurHit;
if(cntBestHit && cntCurHit>cntBestHit )
continue;
idx * m =hdr->lenAlign ? hdr->match() : MM;
// open file or stream
if(prefix){
fps->resize(hdr->idSub+1);
if( (*fps)[hdr->idSub]==0 ) {
sFilePath mk("queryMap.vioal","%s%%pathx.%"_d_".%%ext",prefix,hdr->idSub);
(*fps)[hdr->idSub]=fopen(mk.ptr(),"wrt");
if(!(*fps)[hdr->idSub])(*fps)[hdr->idSub]=(FILE *)sNotPtr;
}
if((*fps)[hdr->idSub]==0 && (*fps)[hdr->idSub]==(FILE *)sNotPtr)continue;
t1.cut(0);sBioseqAlignment::printf(&t1, hdr, m);
if(t1.length())fprintf((*fps)[hdr->idSub],"%s", t1.ptr(0));
}
else {
strL->resize(hdr->idSub+1);
sBioseqAlignment::printf(strL->ptr(hdr->idSub), hdr, m);
}
hdr=sShift(hdr,hdr->sizeofFlat());
}
return i;
}
*/
idx sBioseqAlignment::alignPostCompute(Al * hdr, const char * sub, const char * qry, idx subbuflen, idx qrybuflen)
{
idx i, is , iq ;
idx * m =hdr->match();
hdr->matches=0;
hdr->mismatches=0;
hdr->inserts=0;
hdr->deletions=0;
idx flags=hdr->flags;
idx nonCompFlags=((hdr->flags)&(~(fAlignBackwardComplement|fAlignForwardComplement)));
idx isInsDel=0; // we keep track of the previous state so we count gap of multiple as one
for( i=0 ; i<hdr->lenAlign; i+=2) {
is=m[i];
iq=m[i+1];
if(is<0) {
if(!isInsDel)
++hdr->inserts;
++isInsDel;
}
else if(iq<0){
if(!isInsDel){
++hdr->deletions;
}
++isInsDel;
}
else {
isInsDel=0;
idx iqx=QIDX( hdr->qryStart+iq, qrybuflen );
idx isx=SIDX( (hdr->subStart+is) , subbuflen);
char chS=sBioseq::mapRevATGC[(idx)_seqBits(sub, isx, nonCompFlags)];
char chQ=sBioseq::mapRevATGC[(idx)_seqBits(qry, iqx , hdr->flags)];
if( chS != chQ )
++hdr->mismatches;
else
++hdr->matches;
}
}
return hdr->lenAlign/2;
}
idx sBioseqAlignment::viewAlignment(sStr * dst, Al * hdr, idx * m, const char * sub, const char * qry, idx subbuflen, idx qrybuflen, const char * prefix, const char * id, const char * qua)
{
idx i, is , iq ;
//idx * m =Alignment::match(hdr);
idx flags=hdr->flags;
idx nonCompFlags=((hdr->flags)&(~(fAlignBackwardComplement|fAlignForwardComplement)));
sStr l1, l2, l3;
sStr l4; // for qualities
if(id){
dst->printf("%s[%"_d_"]<->Query[%"_d_"] %s: score=%"_d_" matches=%"_d_" miss=%"_d_" ins=%"_d_" del=%"_d_"\n",
hdr->idSub>0 ? "Amplicon" :"Master", hdr->idSub,hdr->idQry, id,
hdr->score,hdr->matches, hdr->mismatches, hdr->inserts, hdr->deletions );
}
if(prefix) {
l1.printf("%s",prefix);
l2.printf("%s",prefix);
l3.printf("%s",prefix);
if(qua) {
l4.printf("%s",prefix);
}
}
l1.printf("subject[%7"_d_"] %7"_d_"-%7"_d_": ",hdr->idSub,hdr->subStart+m[0]+1,hdr->subEnd+1);
l2.printf(" : ");
if( hdr->flags&fAlignBackward ) l3.printf("query[%7"_d_"](-)%7"_d_"-%7"_d_": ", hdr->idQry,hdr->qryEnd+1,hdr->qryStart+m[1]+1);
else l3.printf("query[%7"_d_"](+)%7"_d_"-%7"_d_": ", hdr->idQry,hdr->qryStart+m[1]+1,hdr->qryEnd+1);
if(qua){
l4.printf(" : ");
}
for( i=0 ; i<hdr->lenAlign; i+=2) {
is=m[i];
iq=m[i+1];
idx isx=SIDX( (hdr->subStart+is) , subbuflen);
char chS=sBioseq::mapRevATGC[(idx)_seqBits(sub, isx,nonCompFlags)];
idx iqx=QIDX( hdr->qryStart+iq, qrybuflen );
char chQ=sBioseq::mapRevATGC[(idx)_seqBits(qry, iqx, hdr->flags)];
l1.printf("%c", is>=0 ? ( (iq<0 || chQ!=chS) ? tolower(chS) : chS ) :'-' );
if(is<0)
l2.printf("-");
else if(iq<0)
l2.printf(".");
else if(chS==chQ)
l2.printf("|");
else
l2.printf(" ");
l3.printf("%c",iq>=0 ? ( (is<0 || chQ!=chS) ? tolower(chQ) : chQ) : '.' );
if(qua) {
if(qua[iqx/8]&(((idx)1)<<(iqx%8)))l4.printf("+");
else l4.printf("-");
}
}
dst->printf("%s\n%s\n%s\n",l1.ptr(),l2.ptr(),l3.ptr());
if(qua)dst->printf("%s\n",l4.ptr());
return hdr->lenAlign/2;
}
idx sBioseqAlignment::remapAlignment(Al * from, Al * to )
{
idx * mfrom0=from->match();
idx * mto0=to->match();
idx cntfrom=from->lenAlign, cntto=to->lenAlign;
idx ofsfrom=from->subStart, ofsto=to->qryStart;
idx * mfrom, * mto, *mfromEnd=mfrom0+cntfrom, * mtoEnd=mto0+cntto;
for( mfrom=mfrom0, mto=mto0+1; mfrom < mfromEnd && mto<mtoEnd; mfrom+=2 ) { // mto0+1 because in master alignment to amplicon , amplicon is the query
// find the position where we have and overlap of the two mappings on amplicon
while ( mfrom<mfromEnd && (*mfrom)+ofsfrom < (*mto)+ofsto) // TODO : sortsearch instead of scanning
mfrom+=2;
if(mfrom>=mfromEnd)break;
while ( mto<mtoEnd && (*mfrom)+ofsfrom > (*mto)+ofsto)
mto+=2;
if(mto>=mtoEnd)break;
if ( (*mfrom)+ofsfrom!=(*mto)+ofsto) // this position is not aligned
*(mfrom+1)=-1; // query points to -1
else {
*mfrom=*(mto-1);
if(*mfrom!=-1) {
*mfrom+=-from->subStart;
from->subEnd=*mfrom;
from->lenAlign=mfrom-mfrom0;
}
}
if( *(mfrom+1)!=-1){
from->qryEnd=*(mfrom+1);
from->lenAlign=mfrom-mfrom0+2;
}
}
from->idSub=to->idSub;// now we are aligned with master
from->subStart=to->subStart+from->subStart;
from->subEnd+=from->subStart;
from->qryEnd+=from->qryStart;
return from->lenAlign; // how many elements in a new array
}
idx sBioseqAlignment::truncateAlignment(Al * hdr, idx maskBefore, idx maskAfter, idx issuborqry)
{
idx * m=hdr->match();
if ( issuborqry==0) {
if(maskAfter<0)maskAfter=hdr->subEnd+maskAfter;
if( hdr->subEnd<=maskBefore ) return 0;
if( hdr->subStart>maskAfter )return 0; // this is before the requested region
}
idx len=hdr->lenAlign, idst, isrc;
idx newsubstart=-1, newqrystart=-1;
for ( isrc=0, idst=0; isrc<len; isrc+=2 ) {
if ( issuborqry==0) {
if( m[isrc]+hdr->subStart<maskBefore ) continue; // this is before the requested region
if( m[isrc]+hdr->subStart>=maskAfter ) break; // this is before the requested region
} else if ( issuborqry==1) {
if( m[isrc+1]+hdr->qryStart<maskBefore ) continue; // this is before the requested region
if( m[isrc+1]+hdr->qryStart>=maskAfter ) break; // this is before the requested region
}
if(newsubstart==-1)
newsubstart=hdr->subStart+m[isrc]; // we remember the new start position
if(newqrystart==-1)
newqrystart=hdr->qryStart+m[isrc+1];
if(m[isrc]!=-1)
hdr->subEnd=m[idst]=hdr->subStart+m[isrc]-newsubstart;
if(m[idst+1]!=-1)
hdr->qryEnd=m[idst+1]=hdr->qryStart+m[isrc+1]-newqrystart;
idst+=2;
}
hdr->lenAlign=idst;
hdr->subStart=newsubstart;
hdr->subEnd+=newsubstart;
hdr->qryStart=newqrystart;
hdr->qryEnd+=newqrystart;
return hdr->lenAlign; // how many elements in a new array
}
// _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
// _/
// _/ SNP counting
// _/
// _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
idx sBioseqAlignment::countSNPSingleSeq(idx * freq, idx substart, idx sublen, const char * qrybits, idx qrybuflen,const char * qua, Al * hdr, idx * m, idx maxRptIns)
{
if( hdr->subEnd < substart || hdr->subStart+m[0] > substart+sublen) // if the range requestes is beyond mapping of this query
return 0;
idx i, is, iq;
idx ddd=SNPtableColSize;
// retrieve the query sequence
idx lastSubOK=0, ch, flags=hdr->flags;
char let=0;
for( i=0 ; i<hdr->lenAlign; i+=2) {
is=m[i];
iq=m[i+1];
if(qua) {
if( (qua[i/8]&(((idx)1)<<(i%8))) ==0 ) // quality bit is not set
continue; // ignore the bases with low Phred score
}
if(is<0){ ch=4; is=lastSubOK;} // we remember inserts on the last mapped position
else if(iq<0)ch=5; // deletions
else {
idx iqx=QIDX( hdr->qryStart+iq, qrybuflen );
ch=let=_seqBits(qrybits, iqx , hdr->flags) ; // mapped ok
}
if( is +hdr->subStart < substart)continue; // before the range requested
else if( is+hdr->subStart >= sublen+substart)break; // after the range requested
if(maxRptIns && ch==4 && hdr->qryStart+iq>maxRptIns) { // check if this is a valid insert
idx irp, iqx;
char qlet, prvlet=-1;
for ( irp=0 ; irp<=maxRptIns; ++irp ){
iqx=QIDX( hdr->qryStart+iq-irp, qrybuflen );
qlet=_seqBits(qrybits, iqx , hdr->flags);
if( irp>0 && prvlet!=qlet)break ; // scan back untill the letters are the same
prvlet=qlet;
}
if(irp>maxRptIns)
continue; // this is a device error repeat insert
}
if( (hdr->flags&fAlignCircular) && is>=sublen)is-=sublen;
idx line=ddd*(hdr->subStart+is-substart);
if(hdr->flags&fAlignBackward) ch+=ddd/2;
++(freq)[line+ch];
if(qua && freq){
idx iQua=6; if (hdr->flags&fAlignBackward) iQua=13 ;
(freq)[line+iQua]+=( (qua[i/8]&(((idx)1)<<(i%8))) ==0 ) ? 40 : 10 ; // qua[i];
}
lastSubOK=is;
}
return i;
}
/*
idx sBioseqAlignment::countSNP(sVec < idx > * freq, idx substart, idx sublen, sBioseq * qry, sBioseqAlignment * qryMap, idx id, idx maxRptIns)
{
idx iQry;
idx ddd=SNPtableColSize;
freq->resizeM(ddd*sublen);freq->set(0); // memory for frequencies
// walk on queries one by one
for ( iQry=0; qryMap->next(); ++iQry ) {
//idx * m=sSeqAlign::Alignment::match(hdr);
Al * hdr=qryMap->hdr();
idx * m=qryMap->match();
if(hdr->idSub!=id) // hitting not this id
continue;
if( (hdr->subEnd)<substart || hdr->subStart+m[0]>substart+sublen) // if the range requestes is beyond mapping of this query
continue;
// retrieve the query sequence
const char * qrybits=qry->seq(hdr->idQry);
const char * qua=qry->qua(hdr->idQry);
idx qrybuflen=qry->len(hdr->idQry);
countSNPSingleSeq(freq->ptr(), substart, sublen, qrybits, qrybuflen,qua, hdr, m, maxRptIns);
}
return 0;
}
*/
| [
"anton.golikow@gmail.com"
] | anton.golikow@gmail.com |
4aa941cb152ebe759e21c7352cfb713bf135d6d1 | 565c1b6ca0c24ef10397b8d8a96ecac378e58a9c | /ftag/semaphore.hpp | e38b7d1dc1906d4a49c9192fae17184d8eaa4181 | [
"BSD-2-Clause"
] | permissive | faljse/ftag | 419cc588e3bd17f9b06295b1cb8d46d619256202 | 499bb92acaa55aa0409b3a10d7d8be0ce9e845a1 | refs/heads/master | 2020-04-22T04:59:40.765894 | 2019-02-19T13:31:47 | 2019-02-19T13:31:47 | 170,143,552 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 755 | hpp |
class Semaphore
{
private:
std::mutex mutex_;
std::condition_variable condition_;
unsigned long count_ = 0; // Initialized as locked.
public:
Semaphore() {
}
Semaphore(int count) {
count_ = count;
}
void notify() {
std::unique_lock<decltype(mutex_)> lock(mutex_);
++count_;
condition_.notify_one();
}
void wait() {
std::unique_lock<decltype(mutex_)> lock(mutex_);
while(!count_) // Handle spurious wake-ups.
condition_.wait(lock);
--count_;
}
bool try_wait() {
std::unique_lock<decltype(mutex_)> lock(mutex_);
if(count_) {
--count_;
return true;
}
return false;
}
}; | [
"user@localhost.localdomain"
] | user@localhost.localdomain |
629d8fda0c842731724fc0ef9a5f7d9f08a515d4 | 7b5d5a9c61a74a35af817c8a513062bd56987235 | /Placement Preparation-II/DP/permutation_coefficient.cpp | 60c7d22035ed16355378ad86e50abc4ed2c18f93 | [] | no_license | amanr11314/PLACEMENT-PREPARATION | f3d5b9b1daa6a56e58f3dffb8d1d0f45c4be258b | f854dda0718dc5dd56328412226f112df92fd514 | refs/heads/master | 2023-06-24T16:23:16.021832 | 2021-07-30T05:07:44 | 2021-07-30T05:07:44 | 271,448,245 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 921 | cpp | //To efficiently compute nPr:-
/**
* nPr is calculated by using relation :--
* nPr = (n-1)P(r) + r * (n-1)P(r-1)
* _______________________________________
* Another best approach is to notice that:--
* P(10,2) = 10 * 9
* P(10,3) = 10 * 9 * 8
* i..e P(n,r) = n * (n-1) ..*(n-r+1)
* */
#include<bits/stdc++.h>
using namespace std;
// O(n*k) time and space complecity
int solve(int n, int k) {
int P[n + 1][k + 1];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= std::min(i, k); j++) {
if (j == 0)
P[i][j] = 1;
else
P[i][j] = P[i - 1][j] + (j * P[i - 1][j - 1]);
//for j>i
P[i][j + 1] = 0;
}
}
return P[n][k];
}
//O(n) apporach
int solve(int n,int k) {
if(k==0 || k==n) return 1;
int npk = 1;
for(int i=n;i>=n-k+1;--i) {
npk*=i;
}
return npk;
} | [
"amanr11314@gmail.com"
] | amanr11314@gmail.com |
d03ab7e2f4eb45e5f0668bace12410dbefd9d04c | 28ebd798251e6bc38d04706d702f803ebe1c61bd | /classical/GRIDSUM1.cpp | ce4084f0c9a789322e8d328f3913976018441388 | [] | no_license | Sidhbtu/spoj-solution | 484bae87e7f6c20275795deb66c5b35dc8c301e4 | 6461a47357ad014f12abcf229e9e31f0334afca8 | refs/heads/master | 2022-02-08T21:54:57.478153 | 2019-08-13T22:22:35 | 2019-08-13T22:22:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,552 | cpp | // GRIDSUM1 - 2x2 Subgrid Sum Problem (medium)
// http://www.spoj.com/problems/GRIDSUM1/
#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
#include <functional>
#include <iomanip>
#include <cstdio>
#include <queue>
#include <cstring>
#include <cstdlib>
#include <cassert>
#include <stdio.h>
#include <set>
using namespace std;
inline void inp( int &n )
{
n=0;
int ch=getchar_unlocked();int sign=1;
while(ch < '0' || ch > '9' ){if(ch=='-')sign=-1; ch=getchar_unlocked();}
while(ch >= '0' && ch <= '9' )
n = (n<<3)+(n<<1) + ch-'0', ch=getchar_unlocked();
n=n*sign;
}
int a, b, n;
int cells[3][3];
long long int finalRs;
void getSol () {
int rangeMin, rangeMax, tmpSum;
long long int anotherTemp;
for (int m1 = a; m1 <= b; m1++)
for (int m2 = a; m2 <= b; m2++)
for (int m3 = m1; m3 <= b; m3++) {
cells[1][0] = m1; cells[1][1] = m2; cells[1][2] = m3;
rangeMin = a; rangeMax = b;
tmpSum = n - (cells[1][0] + cells[1][1]);
rangeMax = min(rangeMax, tmpSum - a);
rangeMin = max(rangeMin, tmpSum - b);
tmpSum = n - (cells[1][1] + cells[1][2]);
rangeMax = min(rangeMax, tmpSum - a);
rangeMin = max(rangeMin, tmpSum - b);
if (rangeMin <= rangeMax) {
anotherTemp = (rangeMax - rangeMin + 1);
anotherTemp = anotherTemp * anotherTemp;
finalRs += anotherTemp;
if (m1 != m3)
finalRs += anotherTemp;
}
}
}
int main () {
int t;
inp(t);
for (int z = 0; z < t; z++) {
inp(a); inp(b); inp(n);
finalRs = 0;
getSol();
cout << finalRs << "\n";
}
}
| [
"boy19ykienandon@yahoo.com.vn"
] | boy19ykienandon@yahoo.com.vn |
72b7dcce4dcf37542a206bcc849c9ff35689d016 | 26458cd5a4aa8db6bfb42de54f5027e5a5e2d214 | /Script/JavaScript/SpiderMonkey/src/Array.cpp | 78fa71455fc344eaa3f54a040ae0f8ab17a21ae8 | [] | no_license | oscommonjs/sandbox | 184be2c648cb077e8cad2556ed615db7ae50d643 | 798c5f5258cb0e8cae02386e050b289a74acd272 | refs/heads/master | 2021-01-25T11:44:10.403338 | 2013-03-24T15:21:21 | 2013-03-24T15:21:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,480 | cpp | //
// Array.cpp
//
// $Id$
//
// Library: JavaScript
// Package: SpiderMonkey
// Module: Array
//
// Implementation of Array
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// 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. Redistributions in any form must be accompanied by information on
// how to obtain complete source code for this software and any
// accompanying software that uses this software. The source code
// must either be included in the distribution or be available for no
// more than the cost of distribution plus a nominal fee, and must be
// freely redistributable under reasonable conditions. For an
// executable file, complete source code means the source code for all
// modules it contains. It does not include source code for modules or
// files that typically accompany the major components of the operating
// system on which the executable file runs.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
#include "Poco/Script/ScriptException.h"
#include "Poco/Script/JavaScript/SpiderMonkey/Object.h"
#include "Poco/Script/JavaScript/SpiderMonkey/Context.h"
#include "Poco/Script/JavaScript/SpiderMonkey/Array.h"
namespace Poco {
namespace Script {
namespace JavaScript {
namespace SpiderMonkey {
Array::Array(const Object& obj) : Object(obj)
{
}
Array::Array(const Context& cx, JSObject* obj) : Object(cx, obj)
{
}
Array::Array(const Poco::DynamicAny& any)
{
if ( any.type() == typeid(Array) )
{
*this = any.extract<Array>();
}
}
Array::Array(const Array& copy) : Object(copy)
{
}
Array::~Array()
{
}
Array& Array::operator = (const Array& other)
{
Object::operator =(other);
return *this;
}
void Array::set(int index, const DynamicAny& value)
{
setProperty(index, value);
}
DynamicAny Array::operator[](int index) const
{
return get(index);
}
DynamicAny Array::get(int index) const
{
return getProperty(index);
}
bool Array::isValid() const
{
if ( Object::isValid() )
{
return JS_IsArrayObject(*_context, _obj) == JS_TRUE;
}
return false;
}
Array Array::newArray(const Context& context, int elementCount)
{
return Array(context, JS_NewArrayObject(*context, elementCount, NULL));
}
} } } }
| [
"fbraem@users.sourceforge.net"
] | fbraem@users.sourceforge.net |
b9293397b900f53142b5e3e2fe3eb7aa7b1fda5e | 753244933fc4465b0047821aea81c311738e1732 | /core/target/cpp-Os/ts26/include/TS26.h | 4dfe6356884397822f8b3ba4fd09ab1be6a2b06c | [
"MIT"
] | permissive | mboussaa/HXvariability | abfaba5452fecb1b83bc595dc3ed942a126510b8 | ea32b15347766b6e414569b19cbc113d344a56d9 | refs/heads/master | 2021-01-01T17:45:54.656971 | 2017-07-26T01:27:49 | 2017-07-26T01:27:49 | 98,127,672 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 1,183 | h | // Generated by Haxe 3.3.0
#ifndef INCLUDED_TS26
#define INCLUDED_TS26
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
HX_DECLARE_CLASS0(TS26)
HX_DECLARE_CLASS1(utest,Runner)
class HXCPP_CLASS_ATTRIBUTES TS26_obj : public hx::Object
{
public:
typedef hx::Object super;
typedef TS26_obj OBJ_;
TS26_obj();
public:
void __construct();
inline void *operator new(size_t inSize, bool inContainer=false,const char *inName="TS26")
{ return hx::Object::operator new(inSize,inContainer,inName); }
inline void *operator new(size_t inSize, int extra)
{ return hx::Object::operator new(inSize+extra,false,"TS26"); }
static hx::ObjectPtr< TS26_obj > __new();
static Dynamic __CreateEmpty();
static Dynamic __Create(hx::DynamicArray inArgs);
//~TS26_obj();
HX_DO_RTTI_ALL;
static bool __GetStatic(const ::String &inString, Dynamic &outValue, hx::PropertyAccess inCallProp);
static void __register();
::String __ToString() const { return HX_HCSTRING("TS26","\x03","\x13","\xc5","\x37"); }
static void addTests( ::utest::Runner runner);
static ::Dynamic addTests_dyn();
static void main();
static ::Dynamic main_dyn();
};
#endif /* INCLUDED_TS26 */
| [
"mohamed.boussaa@inria.fr"
] | mohamed.boussaa@inria.fr |
7e346d733a4aaaae643f75dfc1c15203813a85aa | 993cb140cd01fd70ae7338b9f16d59f1b1362bea | /1146.cpp | c990fb75dba0a20c06bab963ca13023b7bc62c7a | [] | no_license | blowing-wind/pat_advanced | 6d52638641c87cefc42936e59af603ec953554fc | 1f920e5ccfab7c8bbbe3803be43413cf1c302892 | refs/heads/master | 2021-06-23T04:23:22.816100 | 2019-07-04T08:12:43 | 2019-07-04T08:12:43 | 143,998,786 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 739 | cpp | #include <iostream>
#include <vector>
using namespace std;
vector<vector<int>> G;
bool judge(vector<int> inDegree);
int main()
{
int N, M, K;
cin >> N >> M;
G.resize(N + 1);
vector<int> inDegree(N + 1, 0);
int i, v, w;
for (i = 0; i < M; i++)
{
cin >> v >> w;
G[v].push_back(w);
inDegree[w]++;
}
cin >> K;
bool first = true;
for (i = 0; i < K; i++)
{
if (!judge(inDegree))
{
if (!first) cout << " ";
else first = false;
cout << i;
}
}
return 0;
}
bool judge(vector<int> inDegree)
{
bool ans = true;
int i, v, N = G.size() - 1;
for (i = 0; i < N; i++)
{
cin >> v;
if (!ans) continue;
if (inDegree[v] > 0) ans = false;
else
{
for (int w : G[v])
inDegree[w]--;
}
}
return ans;
}
| [
"lxc1019no1207@gmail.com"
] | lxc1019no1207@gmail.com |
93fbca78db7c28e2e6cf23c71a412fd6360aaafa | b3bdb9503391e82b95c120d841e7aeba4b162206 | /ch4/4.10.cpp | eac3bb763ff9fbd72d5225df09d846c332a311ca | [] | no_license | winterfell30/Cpp-Concurrency-in-Action | 33814fb627903cd19d4b4f1b47061b308895f764 | 192d734bf0ce6510c532906eecff6f3833b7a513 | refs/heads/master | 2021-01-18T17:55:18.474163 | 2018-11-17T05:12:36 | 2018-11-17T05:12:36 | 86,824,537 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 790 | cpp | #include <future>
void process_connection(connection_set& connections)
{
while (!done(connections))
{
for (connection_iterator connection = connections.begin(), end = connections.end();
connection != end; ++connection)
{
if (connection->has_incoming_data())
{
data_package data = connection->incoming();
std::promise<payload_type>& p = connection->get_promise(data.id);
p.set_value(data.payload);
}
if (connection->has_outgoing_data())
{
outgoing_package data = connection->top_of_outgoing_queue();
connection->send(data.payload);
data.promise.set_value(true);
}
}
}
}
| [
"m17862917336@163.com"
] | m17862917336@163.com |
22de9885946c52c508cc4dca09499e69fb3350a4 | da94b9bd63a9eb355e41385521c7ba43b3c43cf9 | /src/Mesh/CNodeElementConnectivity.hpp | fb3109cc091bf13fec10415a900133ac8f7493e8 | [] | no_license | zhanggjun/coolfluid3 | 9630cc4c4e6176d818ad20c9835ba053ce7c7175 | 04a180e1f8fdc20018dd297c00a273462e686d03 | refs/heads/master | 2023-03-26T02:54:11.595910 | 2011-08-09T07:52:37 | 2011-08-09T07:52:37 | 526,964,683 | 1 | 0 | null | 2022-08-20T15:25:58 | 2022-08-20T15:25:57 | null | UTF-8 | C++ | false | false | 2,847 | hpp | // Copyright (C) 2010 von Karman Institute for Fluid Dynamics, Belgium
//
// This software is distributed under the terms of the
// GNU Lesser General Public License version 3 (LGPLv3).
// See doc/lgpl.txt and doc/gpl.txt for the license text.
#ifndef CF_Mesh_CNodeElementConnectivity_hpp
#define CF_Mesh_CNodeElementConnectivity_hpp
#include "Mesh/CElements.hpp"
#include "Mesh/CUnifiedData.hpp"
#include "Mesh/CDynTable.hpp"
////////////////////////////////////////////////////////////////////////////////
namespace CF {
namespace Common {
class CLink;
}
namespace Mesh {
class CRegion;
class CNodes;
////////////////////////////////////////////////////////////////////////////////
/// Stores connectivity data between nodes and their adjacent elements
/// and provides a convenient API to access the data
class Mesh_API CNodeElementConnectivity : public Common::Component
{
public:
typedef boost::shared_ptr<CNodeElementConnectivity> Ptr;
typedef boost::shared_ptr<CNodeElementConnectivity const> ConstPtr;
/// Contructor
/// @param name of the component
CNodeElementConnectivity ( const std::string& name );
/// Virtual destructor
virtual ~CNodeElementConnectivity() {}
/// Get the class name
static std::string type_name () { return "CNodeElementConnectivity"; }
/// setup the node to element connectivity
/// This function calls
/// - set_elements(elements_range)
/// - build_connectivity
/// They could be called seperately if wanted
/// @post all access functions can be used after setup
/// @param [in] region in which the elements are connected to the nodes.
void setup(CRegion& region);
/// Build the connectivity table
/// Build the connectivity table as a CDynTable<Uint>
/// @pre set_nodes() and set_elements() must have been called
void build_connectivity();
CUnifiedData& elements() { return *m_elements; }
const CUnifiedData& elements() const { return *m_elements; }
/// const access to the node to element connectivity table in unified indices
CDynTable<Uint>& connectivity() { return *m_connectivity; }
const CDynTable<Uint>& connectivity() const { return *m_connectivity; }
private: //functions
/// set the nodes for the node to element connectivity
/// @param [in] nodes the nodes component to find connected elements of
void set_nodes(CNodes& nodes);
private: // data
/// link to the nodes component
boost::shared_ptr<Common::CLink> m_nodes;
/// unified view of the elements
CUnifiedData::Ptr m_elements;
/// Actual connectivity table
CDynTable<Uint>::Ptr m_connectivity;
}; // CNodeElementConnectivity
////////////////////////////////////////////////////////////////////////////////
} // Mesh
} // CF
////////////////////////////////////////////////////////////////////////////////
#endif // CF_Mesh_ConnectivityData_hpp
| [
"ir.willem.deconinck@gmail.com"
] | ir.willem.deconinck@gmail.com |
3b25797829b4aec345c9abac309bba34916042a9 | fa63c487c5b5682b2e085fb720a8cb62192079a1 | /Source/Urho3D/UI/Window.cpp | 8006849441f058d4bed1f5b7df712d9bd4e648a2 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | Geniok/Dviglo | cdc9d497b75ab7595b1224efc8526367ae8565ea | e2ddbf90377e6734570ea83b24385fd535cfa126 | refs/heads/master | 2023-05-06T20:22:52.971847 | 2021-05-29T10:33:24 | 2021-05-29T10:33:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,041 | cpp | // Copyright (c) 2008-2021 the Urho3D project
// Copyright (c) 2021 проект Dviglo
// Лицензия: MIT
#include "../Precompiled.h"
#include "../Core/Context.h"
#include "../Input/InputEvents.h"
#include "../UI/Cursor.h"
#include "../UI/UI.h"
#include "../UI/UIEvents.h"
#include "../UI/Window.h"
#include "../DebugNew.h"
namespace Dviglo
{
static const int DEFAULT_RESIZE_BORDER = 4;
extern const char* UI_CATEGORY;
Window::Window(Context* context) :
BorderImage(context),
movable_(false),
resizable_(false),
fixedWidthResizing_(false),
fixedHeightResizing_(false),
resizeBorder_(DEFAULT_RESIZE_BORDER, DEFAULT_RESIZE_BORDER, DEFAULT_RESIZE_BORDER, DEFAULT_RESIZE_BORDER),
dragMode_(DRAG_NONE),
modal_(false),
modalAutoDismiss_(true),
modalShadeColor_(Color::TRANSPARENT_BLACK),
modalFrameColor_(Color::TRANSPARENT_BLACK),
modalFrameSize_(IntVector2::ZERO)
{
bringToFront_ = true;
clipChildren_ = true;
SetEnabled(true);
}
Window::~Window() = default;
void Window::RegisterObject(Context* context)
{
context->RegisterFactory<Window>(UI_CATEGORY);
URHO3D_COPY_BASE_ATTRIBUTES(BorderImage);
URHO3D_UPDATE_ATTRIBUTE_DEFAULT_VALUE("Bring To Front", true);
URHO3D_UPDATE_ATTRIBUTE_DEFAULT_VALUE("Clip Children", true);
URHO3D_UPDATE_ATTRIBUTE_DEFAULT_VALUE("Is Enabled", true);
URHO3D_ACCESSOR_ATTRIBUTE("Resize Border", GetResizeBorder, SetResizeBorder, IntRect, IntRect(DEFAULT_RESIZE_BORDER, \
DEFAULT_RESIZE_BORDER, DEFAULT_RESIZE_BORDER, DEFAULT_RESIZE_BORDER), AM_FILE);
URHO3D_ACCESSOR_ATTRIBUTE("Is Movable", IsMovable, SetMovable, bool, false, AM_FILE);
URHO3D_ACCESSOR_ATTRIBUTE("Is Resizable", IsResizable, SetResizable, bool, false, AM_FILE);
URHO3D_ACCESSOR_ATTRIBUTE("Fixed Width Resizing", GetFixedWidthResizing, SetFixedWidthResizing, bool, false, AM_FILE);
URHO3D_ACCESSOR_ATTRIBUTE("Fixed Height Resizing", GetFixedHeightResizing, SetFixedHeightResizing, bool, false, AM_FILE);
URHO3D_ACCESSOR_ATTRIBUTE("Is Modal", IsModal, SetModal, bool, false, AM_FILE | AM_NOEDIT);
URHO3D_ACCESSOR_ATTRIBUTE("Modal Shade Color", GetModalShadeColor, SetModalShadeColor, Color, Color::TRANSPARENT_BLACK, AM_FILE);
URHO3D_ACCESSOR_ATTRIBUTE("Modal Frame Color", GetModalFrameColor, SetModalFrameColor, Color, Color::TRANSPARENT_BLACK, AM_FILE);
URHO3D_ACCESSOR_ATTRIBUTE("Modal Frame Size", GetModalFrameSize, SetModalFrameSize, IntVector2, IntVector2::ZERO, AM_FILE);
// Modal auto dismiss is purposefully not an attribute, as using it can make the editor lock up.
// Instead it should be set false in code when needed
}
void Window::GetBatches(PODVector<UIBatch>& batches, PODVector<float>& vertexData, const IntRect& currentScissor)
{
if (modal_)
{
// Modal shade
if (modalShadeColor_ != Color::TRANSPARENT_BLACK)
{
UIElement* rootElement = GetRoot();
const IntVector2& rootSize = rootElement->GetSize();
UIBatch batch(rootElement, BLEND_ALPHA, IntRect(0, 0, rootSize.x_, rootSize.y_), nullptr, &vertexData);
batch.SetColor(modalShadeColor_);
batch.AddQuad(0, 0, rootSize.x_, rootSize.y_, 0, 0);
UIBatch::AddOrMerge(batch, batches);
}
// Modal frame
if (modalFrameColor_ != Color::TRANSPARENT_BLACK && modalFrameSize_ != IntVector2::ZERO)
{
UIBatch batch(this, BLEND_ALPHA, currentScissor, nullptr, &vertexData);
int x = GetIndentWidth();
IntVector2 size = GetSize();
size.x_ -= x;
batch.SetColor(modalFrameColor_);
batch.AddQuad(x - modalFrameSize_.x_, -modalFrameSize_.y_, size.x_ + 2 * modalFrameSize_.x_,
size.y_ + 2 * modalFrameSize_.y_, 0, 0);
UIBatch::AddOrMerge(batch, batches);
}
}
BorderImage::GetBatches(batches, vertexData, currentScissor);
}
void Window::OnHover(const IntVector2& position, const IntVector2& screenPosition, MouseButtonFlags buttons, QualifierFlags qualifiers, Cursor* cursor)
{
UIElement::OnHover(position, screenPosition, buttons, qualifiers, cursor);
if (dragMode_ == DRAG_NONE)
{
WindowDragMode mode = GetDragMode(position);
SetCursorShape(mode, cursor);
}
else
SetCursorShape(dragMode_, cursor);
}
void Window::OnDragBegin(const IntVector2& position, const IntVector2& screenPosition, MouseButtonFlags buttons, QualifierFlags qualifiers, Cursor* cursor)
{
UIElement::OnDragBegin(position, screenPosition, buttons, qualifiers, cursor);
if (buttons != MOUSEB_LEFT || !CheckAlignment())
{
dragMode_ = DRAG_NONE;
return;
}
dragBeginCursor_ = screenPosition;
dragBeginPosition_ = GetPosition();
dragBeginSize_ = GetSize();
dragMode_ = GetDragMode(position);
SetCursorShape(dragMode_, cursor);
}
void Window::OnDragMove(const IntVector2& /*position*/, const IntVector2& screenPosition, const IntVector2& /*deltaPos*/,
MouseButtonFlags /*buttons*/, QualifierFlags /*qualifiers*/, Cursor* cursor)
{
if (dragMode_ == DRAG_NONE)
return;
IntVector2 delta = screenPosition - dragBeginCursor_;
IntVector2 dragSize;
IntVector2 resizeBorderSize(resizeBorder_.left_ + resizeBorder_.right_, resizeBorder_.top_ + resizeBorder_.bottom_);
const IntVector2& position = GetPosition();
const IntVector2& size = GetSize();
// Use GetEffectiveMinSize() instead of GetMinSize() to prevent windows moving once the effective minimum size is reached
const IntVector2 effectiveMinSize = GetEffectiveMinSize();
const IntVector2& maxSize = GetMaxSize();
switch (dragMode_)
{
case DRAG_MOVE:
SetPosition(dragBeginPosition_ + delta);
break;
case DRAG_RESIZE_TOPLEFT:
SetPosition(Clamp(dragBeginPosition_.x_ + delta.x_, position.x_ - (maxSize.x_ - size.x_),
position.x_ + (size.x_ - effectiveMinSize.x_)),
Clamp(dragBeginPosition_.y_ + delta.y_, position.y_ - (maxSize.y_ - size.y_),
position.y_ + (size.y_ - effectiveMinSize.y_)));
dragSize = dragBeginSize_ - delta;
fixedWidthResizing_ ? SetFixedWidth(Max(dragSize.x_, resizeBorderSize.x_)) : SetWidth(dragSize.x_);
fixedHeightResizing_ ? SetFixedHeight(Max(dragSize.y_, resizeBorderSize.y_)) : SetHeight(dragSize.y_);
break;
case DRAG_RESIZE_TOP:
SetPosition(dragBeginPosition_.x_, Clamp(dragBeginPosition_.y_ + delta.y_, position.y_ - (maxSize.y_ - size.y_),
position.y_ + (size.y_ - effectiveMinSize.y_)));
dragSize = IntVector2(dragBeginSize_.x_, dragBeginSize_.y_ - delta.y_);
fixedHeightResizing_ ? SetFixedHeight(Max(dragSize.y_, resizeBorderSize.y_)) : SetHeight(dragSize.y_);
break;
case DRAG_RESIZE_TOPRIGHT:
SetPosition(dragBeginPosition_.x_, Clamp(dragBeginPosition_.y_ + delta.y_, position.y_ - (maxSize.y_ - size.y_),
position.y_ + (size.y_ - effectiveMinSize.y_)));
dragSize = IntVector2(dragBeginSize_.x_ + delta.x_, dragBeginSize_.y_ - delta.y_);
fixedWidthResizing_ ? SetFixedWidth(Max(dragSize.x_, resizeBorderSize.x_)) : SetWidth(dragSize.x_);
fixedHeightResizing_ ? SetFixedHeight(Max(dragSize.y_, resizeBorderSize.y_)) : SetHeight(dragSize.y_);
break;
case DRAG_RESIZE_RIGHT:
dragSize = IntVector2(dragBeginSize_.x_ + delta.x_, dragBeginSize_.y_);
fixedWidthResizing_ ? SetFixedWidth(Max(dragSize.x_, resizeBorderSize.x_)) : SetWidth(dragSize.x_);
break;
case DRAG_RESIZE_BOTTOMRIGHT:
dragSize = dragBeginSize_ + delta;
fixedWidthResizing_ ? SetFixedWidth(Max(dragSize.x_, resizeBorderSize.x_)) : SetWidth(dragSize.x_);
fixedHeightResizing_ ? SetFixedHeight(Max(dragSize.y_, resizeBorderSize.y_)) : SetHeight(dragSize.y_);
break;
case DRAG_RESIZE_BOTTOM:
dragSize = IntVector2(dragBeginSize_.x_, dragBeginSize_.y_ + delta.y_);
fixedHeightResizing_ ? SetFixedHeight(Max(dragSize.y_, resizeBorderSize.y_)) : SetHeight(dragSize.y_);
break;
case DRAG_RESIZE_BOTTOMLEFT:
SetPosition(Clamp(dragBeginPosition_.x_ + delta.x_, position.x_ - (maxSize.x_ - size.x_),
position.x_ + (size.x_ - effectiveMinSize.x_)), dragBeginPosition_.y_);
dragSize = IntVector2(dragBeginSize_.x_ - delta.x_, dragBeginSize_.y_ + delta.y_);
fixedWidthResizing_ ? SetFixedWidth(Max(dragSize.x_, resizeBorderSize.x_)) : SetWidth(dragSize.x_);
fixedHeightResizing_ ? SetFixedHeight(Max(dragSize.y_, resizeBorderSize.y_)) : SetHeight(dragSize.y_);
break;
case DRAG_RESIZE_LEFT:
SetPosition(Clamp(dragBeginPosition_.x_ + delta.x_, position.x_ - (maxSize.x_ - size.x_),
position.x_ + (size.x_ - effectiveMinSize.x_)), dragBeginPosition_.y_);
dragSize = IntVector2(dragBeginSize_.x_ - delta.x_, dragBeginSize_.y_);
fixedWidthResizing_ ? SetFixedWidth(Max(dragSize.x_, resizeBorderSize.x_)) : SetWidth(dragSize.x_);
break;
default:
break;
}
ValidatePosition();
SetCursorShape(dragMode_, cursor);
}
void Window::OnDragEnd(const IntVector2& position, const IntVector2& screenPosition, MouseButtonFlags dragButtons, MouseButtonFlags releaseButtons, Cursor* cursor)
{
UIElement::OnDragEnd(position, screenPosition, dragButtons, releaseButtons, cursor);
dragMode_ = DRAG_NONE;
}
void Window::OnDragCancel(const IntVector2& position, const IntVector2& screenPosition, MouseButtonFlags dragButtons, MouseButtonFlags cancelButtons,
Cursor* cursor)
{
UIElement::OnDragCancel(position, screenPosition, dragButtons, cancelButtons, cursor);
if (dragButtons == MOUSEB_LEFT && dragMode_ != DRAG_NONE)
{
dragMode_ = DRAG_NONE;
SetPosition(dragBeginPosition_);
SetSize(dragBeginSize_);
}
}
void Window::SetMovable(bool enable)
{
movable_ = enable;
}
void Window::SetResizable(bool enable)
{
resizable_ = enable;
}
void Window::SetFixedWidthResizing(bool enable)
{
fixedWidthResizing_ = enable;
}
void Window::SetFixedHeightResizing(bool enable)
{
fixedHeightResizing_ = enable;
}
void Window::SetResizeBorder(const IntRect& rect)
{
resizeBorder_.left_ = Max(rect.left_, 0);
resizeBorder_.top_ = Max(rect.top_, 0);
resizeBorder_.right_ = Max(rect.right_, 0);
resizeBorder_.bottom_ = Max(rect.bottom_, 0);
}
void Window::SetModal(bool modal)
{
auto* ui = GetSubsystem<UI>();
// Can be null at exit time; no-op in that case
if (!ui)
return;
if (ui->SetModalElement(this, modal))
{
modal_ = modal;
using namespace ModalChanged;
VariantMap& eventData = GetEventDataMap();
eventData[P_ELEMENT] = this;
eventData[P_MODAL] = modal;
SendEvent(E_MODALCHANGED, eventData);
}
}
void Window::SetModalShadeColor(const Color& color)
{
modalShadeColor_ = color;
}
void Window::SetModalFrameColor(const Color& color)
{
modalFrameColor_ = color;
}
void Window::SetModalFrameSize(const IntVector2& size)
{
modalFrameSize_ = size;
}
void Window::SetModalAutoDismiss(bool enable)
{
modalAutoDismiss_ = enable;
}
WindowDragMode Window::GetDragMode(const IntVector2& position) const
{
WindowDragMode mode = DRAG_NONE;
// Top row
if (position.y_ < resizeBorder_.top_)
{
if (movable_)
mode = DRAG_MOVE;
if (resizable_)
{
mode = DRAG_RESIZE_TOP;
if (position.x_ < resizeBorder_.left_)
mode = DRAG_RESIZE_TOPLEFT;
if (position.x_ >= GetWidth() - resizeBorder_.right_)
mode = DRAG_RESIZE_TOPRIGHT;
}
}
// Bottom row
else if (position.y_ >= GetHeight() - resizeBorder_.bottom_)
{
if (movable_)
mode = DRAG_MOVE;
if (resizable_)
{
mode = DRAG_RESIZE_BOTTOM;
if (position.x_ < resizeBorder_.left_)
mode = DRAG_RESIZE_BOTTOMLEFT;
if (position.x_ >= GetWidth() - resizeBorder_.right_)
mode = DRAG_RESIZE_BOTTOMRIGHT;
}
}
// Middle
else
{
if (movable_)
mode = DRAG_MOVE;
if (resizable_)
{
if (position.x_ < resizeBorder_.left_)
mode = DRAG_RESIZE_LEFT;
if (position.x_ >= GetWidth() - resizeBorder_.right_)
mode = DRAG_RESIZE_RIGHT;
}
}
return mode;
}
void Window::SetCursorShape(WindowDragMode mode, Cursor* cursor) const
{
CursorShape shape = CS_NORMAL;
switch (mode)
{
case DRAG_RESIZE_TOP:
case DRAG_RESIZE_BOTTOM:
shape = CS_RESIZEVERTICAL;
break;
case DRAG_RESIZE_LEFT:
case DRAG_RESIZE_RIGHT:
shape = CS_RESIZEHORIZONTAL;
break;
case DRAG_RESIZE_TOPRIGHT:
case DRAG_RESIZE_BOTTOMLEFT:
shape = CS_RESIZEDIAGONAL_TOPRIGHT;
break;
case DRAG_RESIZE_TOPLEFT:
case DRAG_RESIZE_BOTTOMRIGHT:
shape = CS_RESIZEDIAGONAL_TOPLEFT;
break;
default:
break;
}
if (cursor)
cursor->SetShape(shape);
}
void Window::ValidatePosition()
{
// Check that window does not go more than halfway outside its parent in either dimension
if (!parent_)
return;
const IntVector2& parentSize = parent_->GetSize();
IntVector2 position = GetPosition();
IntVector2 halfSize = GetSize() / 2;
position.x_ = Clamp(position.x_, -halfSize.x_, parentSize.x_ - halfSize.x_);
position.y_ = Clamp(position.y_, -halfSize.y_, parentSize.y_ - halfSize.y_);
SetPosition(position);
}
bool Window::CheckAlignment() const
{
// Only top left-alignment is supported for move and resize
if (GetHorizontalAlignment() == HA_LEFT && GetVerticalAlignment() == VA_TOP)
return true;
else
return false;
}
}
| [
"1vanK@users.noreply.github.com"
] | 1vanK@users.noreply.github.com |
e013905a3372ca035293fa461842151c96bc8cda | a503c2c354569db02294f936f799b727326ad9ed | /src/dialect/krnl/krnl_types.cpp | 48ac166e33be80e8456171b7ad2ba9b47310d60d | [
"Apache-2.0"
] | permissive | tungld/ONNF | dd0be81887f1d3ead437267a32c9d8fe00fac8ae | 937bbec2655fcc6fae69bb6e07ff8f5843b9d219 | refs/heads/master | 2020-12-01T11:31:17.607259 | 2020-02-13T05:50:05 | 2020-02-13T05:50:05 | 230,617,547 | 0 | 0 | Apache-2.0 | 2019-12-28T14:02:51 | 2019-12-28T14:02:50 | null | UTF-8 | C++ | false | false | 323 | cpp | //===--------------------- krnl_types.cpp - MLIR Operations ---------------===//
//
// Copyright 2019 The IBM Research Authors.
//
// =============================================================================
//
//===----------------------------------------------------------------------===//
#include "krnl_types.hpp"
| [
"gheorghe-teod.bercea@ibm.com"
] | gheorghe-teod.bercea@ibm.com |
4bde56e2311e5b38db62066d951ed3d65c6bb8d4 | 7b9b73f430e422e6420fba5534afcee7b1eb044c | /leetcode/260.single-number-iii.cpp | 967d19e56564444c936f03b42ecc265f0c95c8f2 | [] | no_license | imsong52/Q.solution | 5a5b26f0be8a0b49acd9932378b228792a775e4a | 47b732e28c61ba242c96db245f49eb0c8498ebf6 | refs/heads/master | 2020-04-30T14:18:57.482616 | 2018-10-28T02:14:09 | 2018-10-28T02:14:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,174 | cpp | /*
* [260] Single Number III
*
* https://leetcode.com/problems/single-number-iii
*
* Medium (49.93%)
* Total Accepted: 60357
* Total Submissions: 120846
* Testcase Example: '[1,2,1,3,2,5]'
*
*
* Given an array of numbers nums, in which exactly two elements appear only
* once and all the other elements appear exactly twice. Find the two elements
* that appear only once.
*
*
* For example:
*
*
* Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].
*
*
* Note:
*
* The order of the result is not important. So in the above example, [5, 3] is
* also correct.
* Your algorithm should run in linear runtime complexity. Could you implement
* it using only constant space complexity?
*
*
*
* Credits:Special thanks to @jianchao.li.fighter for adding this problem and
* creating all test cases.
*/
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
int s = 0;
for (auto num : nums) s ^= num;
while (s & (s - 1)) s &= (s-1);
int x = 0, y = 0;
for (auto num : nums) {
if (num & s) x ^= num;
else y ^= num;
}
return {x, y};
}
};
| [
"skygragon@gmail.com"
] | skygragon@gmail.com |
dee987f4bae19b9dc592e45c081565659e68d8f5 | dca7c72b1e992a7ac8a9f2123185c3da1147a270 | /atcoder.jp/abc099/abc099_c/Main.cpp | 7bc069b955cf1286804fca9b25847b8592574cfc | [] | no_license | eTakazawa/procon-archive | 4182d3d65016414c124bd03d352c1363b3fe7e70 | 15ef2e892ed3bdbd86641ad88a9ccf64156b9cdb | refs/heads/master | 2021-04-21T04:36:13.418633 | 2020-08-31T14:18:28 | 2020-08-31T14:18:28 | 249,749,882 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 930 | cpp | #include <bits/stdc++.h>
using namespace std;
int main(void) {
int N;
cin >> N;
int a = 9;
vector<int> dr;
dr.push_back(1);
for (int i = 1;; i++) {
dr.push_back(a);
a *= 9;
if (a > N) break;
}
a = 6;
for (int i = 1;; i++) {
dr.push_back(a);
a *= 6;
if (a > N) break;
}
sort(dr.begin(), dr.end());
int dp[100001];
for (int i = 0; i < 100001; i++) dp[i] = 1e9;
dp[0] = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < dr.size(); j++) {
if (i + dr[j] > N) continue;
dp[i + dr[j]] = min(dp[i + dr[j]], dp[i] + 1);
}
}
// reverse(dr.begin(), dr.end());
// int cnt = 0;
// while (N > 6) {
// cerr << N << endl;
// for (int i = 0; i < dr.size(); i++) {
// if (N >= dr[i]) {
// N -= dr[i];
// cerr << dr[i] << endl;
// cnt++;
// break;
// }
// }
// }
cout << dp[N] << endl;
return 0;
} | [
"takazawa621@gmail.com"
] | takazawa621@gmail.com |
87e885f35208455813b5038eb7f0dd70f98dd392 | 304ce70f24d1f5a2809d0313506595353be31f1b | /test/source/contadapt/bitset1.cpp | 297d11ee347333507fecd52572d287e760b312a1 | [
"Unlicense"
] | permissive | kensou24/CppStandardV2 | a401837c6d81277a0da149b22ba30adc7cd19952 | 3d801e93e76f765ba3ae579af8e4c8beb87fab94 | refs/heads/master | 2023-03-11T03:20:41.629340 | 2021-02-22T00:49:38 | 2021-02-22T00:49:38 | 325,675,752 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,439 | cpp | /* The following code example is taken from the book
* "The C++ Standard Library - A Tutorial and Reference, 2nd Edition"
* by Nicolai M. Josuttis, Addison-Wesley, 2012
*
* (C) Copyright Nicolai M. Josuttis 2012.
* Permission to copy, use, modify, sell and distribute this software
* is granted provided this copyright notice appears in all copies.
* This software is provided "as is" without express or implied
* warranty, and with no claim as to its suitability for any purpose.
*/
#include <bitset>
#include <iostream>
#include <doctest/doctest.h>
using namespace std;
TEST_CASE("bitset1")
{
// enumeration type for the bits
// - each bit represents a color
enum Color { red, yellow, green, blue, white, black, //...,
numColors };
// create bitset for all bits/colors
bitset<numColors> usedColors;
// set bits for two colors
usedColors.set(red);
usedColors.set(blue);
// print some bitset data
cout << "bitfield of used colors: " << usedColors << endl;
cout << "number of used colors: " << usedColors.count() << endl;
cout << "bitfield of unused colors: " << ~usedColors << endl;
// if any color is used
if (usedColors.any()) {
// loop over all colors
for (int c = 0; c < numColors; ++c) {
// if the actual color is used
if (usedColors[(Color)c]) {
//...
}
}
}
}
| [
"kensou.24@hotmail.com"
] | kensou.24@hotmail.com |
5c93e612a695914c5977ba91b3f43a4a5dbf799d | ae749189ba676971203c9f1dfbbb5cc0f9415b18 | /Algorithm/e-olymp/0482_plutka_100.cpp | 9f4075719d2e5e6c01c51e00ed69a053b396e9e9 | [] | no_license | sergiiGitHub/Demo | 55c7db8d949170b30fad0a1e159ff4304f2a0f9d | 52f2df67c1f3a1fedd009c216de9d461cb5d086c | refs/heads/master | 2021-11-26T14:57:30.384503 | 2021-11-24T11:10:59 | 2021-11-24T11:10:59 | 36,115,459 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,307 | cpp | #include <stdio.h>
#include <iostream>
using namespace std;
#define M 3
#define N 31
#define SIZE_TABLE 1 << M
int calcTabel[SIZE_TABLE][SIZE_TABLE];
void makeCanTable(){
int size = SIZE_TABLE;
for ( int y = 0, x = size-1; y < size; ++y ){
calcTabel[ y ][ x - y ] = true;
}
calcTabel[ 1 ][ 0 ] = true;
calcTabel[ 4 ][ 0 ] = true;
calcTabel[ 0 ][ 4 ] = true;
calcTabel[ 0 ][ 1 ] = true;
//for ( int y = 0; y < size; ++y ){
// for ( int x = 0; x < size; ++x ){
// cout << calcTabel[ y ][ x ] << " ";
// }
// cout << endl;
//}
}
void solve(int n){
int dp[N][SIZE_TABLE] = {0};
dp[0][0] = 1;
for ( int next_mask = 0; next_mask < SIZE_TABLE; ++next_mask ){
dp[1][next_mask] = calcTabel[0][next_mask];
}
for ( int pos = 2; pos <= n; ++pos ){
for ( int mask = 0; mask < SIZE_TABLE; ++mask ){
for ( int next_mask = 0; next_mask < SIZE_TABLE; ++next_mask ){
dp[pos][mask] += dp[pos - 1][next_mask] * calcTabel[mask][next_mask];
}
}
}
cout << dp[ n ][0] << endl;
}
int main()
{
freopen("input.txt", "r", stdin);
int T = 3;
makeCanTable();
int n;
while ( cin >> n && n != -1 ){
solve(n);
}
return 0;
} | [
"m.sergiigithub@gmail.com"
] | m.sergiigithub@gmail.com |
093ee489fd00369e65bd01307f325ab14061c8ee | 3f41a239bb54723cd446a1ade0bf618bf56fc57a | /src/qt/splashscreen.cpp | 210532e39ede5da869add3bfc5317d6800ec3bed | [
"MIT"
] | permissive | pixicoin/pixicoin | d022026d55fc0b17510e241c3221ab1d7a8bdaa9 | e6255872395a351cce7c412297dc732d47e69597 | refs/heads/master | 2021-01-16T20:34:09.666825 | 2014-01-10T09:06:15 | 2014-01-10T09:06:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,853 | cpp | #include "splashscreen.h"
#include "clientversion.h"
#include "util.h"
#include <QPainter>
#undef loop /* ugh, remove this when the #define loop is gone from util.h */
#include <QApplication>
SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f) :
QSplashScreen(pixmap, f)
{
// set reference point, paddings
int paddingLeftCol2 = 230;
int paddingTopCol2 = 376;
int line1 = 0;
int line2 = 13;
int line3 = 26;
float fontFactor = 1.0;
// define text to place
QString titleText = QString(QApplication::applicationName()).replace(QString("-testnet"), QString(""), Qt::CaseSensitive); // cut of testnet, place it as single object further down
QString versionText = QString("Version %1 ").arg(QString::fromStdString(FormatFullVersion()));
QString copyrightText1 = QChar(0xA9)+QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin developers"));
QString copyrightText2 = QChar(0xA9)+QString(" 2011-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Pixicoin developers"));
QString font = "Arial";
// load the bitmap for writing some text over it
QPixmap newPixmap;
if(GetBoolArg("-testnet")) {
newPixmap = QPixmap(":/images/splash_testnet");
}
else {
newPixmap = QPixmap(":/images/splash");
}
QPainter pixPaint(&newPixmap);
pixPaint.setPen(QColor(70,70,70));
pixPaint.setFont(QFont(font, 9*fontFactor));
pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line3,versionText);
// draw copyright stuff
pixPaint.setFont(QFont(font, 9*fontFactor));
pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line1,copyrightText1);
pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line2,copyrightText2);
pixPaint.end();
this->setPixmap(newPixmap);
}
| [
"pixicoin@gmail.com"
] | pixicoin@gmail.com |
5c5a1b710f96a28a03de4917ec9272746dc825d3 | 27767fec931b598954cc354dd4a4bf604c50eab1 | /Inference/shuffleUnit.h | 1e1737cd6d8f8bebb8827d6d4088470de1b02c11 | [] | no_license | sysu-eda/Distributed-CNN-Inference | 092701b73c9e3602be768b02736df8bb13c61a22 | a717274a8f0a1426949676dd5741d649b4ab81e7 | refs/heads/main | 2023-03-13T07:38:16.757646 | 2021-02-26T04:11:01 | 2021-02-26T04:11:01 | 314,996,278 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,167 | h | #ifndef _EASY_UNIT_
#define _EASY_UNIT_
#include "opWrapper.h"
namespace opWrapper{
class shuffleUnit
{
public:
shuffleUnit(Tensor * input, Tensor * output, int bn, int in_d, int out_d) //const std::string &base_filename, const std::string &conv_number
{
std::string dp;
branch_number = bn;
if(branch_number == 1)
{
//Tensor for intermediate output
/*
Tensor * ts_out_1 = new Tensor();
Tensor * ts_out_2 = new Tensor();
Tensor * ts_out_3 = new Tensor();
Tensor * ts_out_4 = new Tensor();
Tensor * ts_out_5 = new Tensor();
Tensor * ts_out_6 = new Tensor(); */
//std::cout<<"Only 1 Branch"<<std::endl;
layer_group_before_1 = opWrapper::ConvolutionLayer(input,ts_out_1, 1, 0, 1, 1, in_d, out_d);
//std::cout<<dp+"groupconv_before_"+conv_number+"_weights_0.npy"<<std::endl;
layer_group_before_1_bn = opWrapper::BNLayer(ts_out_1,ts_out_2, out_d);
//std::cout<<dp+"groupconv_before_"+conv_number+"_batch_norm"<<std::endl;
layer_dw_1 = opWrapper::DWConvolutionLayer(ts_out_2, ts_out_3, 1, 1, 3, 3, out_d);
//std::cout<<dp+"depthwise_"+conv_number+"_weights_0.npy"<<std::endl;
layer_dw_1_bn = opWrapper::BNLayer(ts_out_3,ts_out_4, out_d);
//std::cout<<dp+"depthwise_"+conv_number+"_batch_norm"<<std::endl;
layer_group_after_1 = opWrapper::ConvolutionLayer(ts_out_4, ts_out_5, 1, 0, 1, 1, out_d, out_d);
//std::cout<<dp+"groupconv_after_"+conv_number+"_weights_0.npy"<<std::endl;
layer_group_after_1_bn = opWrapper::BNLayer(ts_out_5,ts_out_6, out_d);
//std::cout<<dp+"groupconv_after_"+conv_number+"_batch_norm"<<std::endl;
/* std::cout<<input->info()->tensor_shape()[0]<<std::endl;
std::cout<<input->info()->tensor_shape()[1]<<std::endl;
std::cout<<input->info()->tensor_shape()[2]<<std::endl;
std::cout<<ts_out_6->info()->tensor_shape()[0]<<std::endl;
std::cout<<ts_out_6->info()->tensor_shape()[1]<<std::endl;
std::cout<<ts_out_6->info()->tensor_shape()[2]<<std::endl; */
layer_branchAdd = opWrapper::ElementAddOp(input, ts_out_5, output);
}
else
{
//First Branch
//std::cout<<"Two Branch"<<std::endl;
layer_group_before_1 = opWrapper::ConvolutionLayer(input,ts_out_1, 1, 0, 1, 1, in_d, out_d);
//std::cout<<dp+"groupconv_before_"+conv_number+"_weights_0.npy"<<std::endl;
layer_group_before_1_bn = opWrapper::BNLayer(ts_out_1,ts_out_2, out_d);
//std::cout<<dp+"groupconv_before_"+conv_number+"_batch_norm"<<std::endl;
layer_dw_1 = opWrapper::DWConvolutionLayer(ts_out_2, ts_out_3, 2, 1, 3, 3, out_d);
//std::cout<<dp+"depthwise_"+conv_number+"_weights_0.npy"<<std::endl;
layer_dw_1_bn = opWrapper::BNLayer(ts_out_3,ts_out_4, out_d);
//std::cout<<dp+"depthwise_"+conv_number+"_batch_norm"<<std::endl;
layer_group_after_1 = opWrapper::ConvolutionLayer(ts_out_4, ts_out_5, 1, 0, 1, 1 , out_d, out_d);
//std::cout<<dp+"groupconv_after_"+conv_number+"_weights_0.npy"<<std::endl;
layer_group_after_1_bn = opWrapper::BNLayer(ts_out_5,ts_out_6, out_d);
//std::cout<<dp+"groupconv_after_"+conv_number+"_batch_norm"<<std::endl;
//Second Branch
layer_dw_2 = opWrapper::DWConvolutionLayer(input, ts_out_7, 2, 1, 3, 3, in_d);
//std::cout<<dp+"depthwise_"+conv_number+"_weights_0.npy"<<std::endl;
layer_dw_2_bn = opWrapper::BNLayer(ts_out_7,ts_out_8, in_d);
//std::cout<<dp+"depthwise_"+conv_number+"_batch_norm"<<std::endl;
layer_group_after_2 = opWrapper::ConvolutionLayer(ts_out_8, ts_out_9, 1, 0, 1, 1, in_d, out_d);
//std::cout<<dp+"groupconv_after_"+conv_number+"_weights_0.npy"<<std::endl;
layer_group_after_2_bn = opWrapper::BNLayer(ts_out_9,ts_out_10, out_d);
//std::cout<<dp+"groupconv_after_"+conv_number+"_batch_norm"<<std::endl;
layer_branchAdd = opWrapper::ElementAddOp(ts_out_6, ts_out_10, output);
}
}
~shuffleUnit() = default;
//void configure(Tensor * input, Tensor * output, int branch_number, const std::string &base_filename, const std::string &conv_number);
void run()
{
if(branch_number == 1)
{
layer_group_before_1->run();
//std::cout<<*reinterpret_cast<float *>(ts_out_1->allocator()->data())<<std::endl;
layer_group_before_1_bn->run();
//std::cout<<*reinterpret_cast<float *>(ts_out_2->allocator()->data())<<std::endl;
layer_dw_1->run();
//std::cout<<*reinterpret_cast<float *>(ts_out_3->allocator()->data())<<std::endl;
layer_dw_1_bn->run();
//std::cout<<*reinterpret_cast<float *>(ts_out_4->allocator()->data())<<std::endl;
layer_group_after_1->run();
//std::cout<<*reinterpret_cast<float *>(ts_out_5->allocator()->data())<<std::endl;
layer_group_after_1_bn->run();
//std::cout<<*reinterpret_cast<float *>(ts_out_6->allocator()->data())<<std::endl;
layer_branchAdd->run();
/* std::cout<<*reinterpret_cast<float *>(ts_out_1->allocator()->data())<<std::endl;
std::cout<<*reinterpret_cast<float *>(ts_out_2->allocator()->data())<<std::endl;
std::cout<<*reinterpret_cast<float *>(ts_out_3->allocator()->data())<<std::endl;
std::cout<<*reinterpret_cast<float *>(ts_out_4->allocator()->data())<<std::endl;
std::cout<<*reinterpret_cast<float *>(ts_out_5->allocator()->data())<<std::endl;
std::cout<<*reinterpret_cast<float *>(ts_out_6->allocator()->data())<<std::endl; */
}
else
{
layer_group_before_1->run();
layer_group_before_1_bn->run();
layer_dw_1->run();
layer_dw_1_bn->run();
layer_group_after_1->run();
layer_group_after_1_bn->run();
layer_dw_2->run();
layer_dw_2_bn->run();
layer_group_after_2->run();
layer_group_after_2_bn->run();
layer_branchAdd->run();
}
}
private:
int branch_number = 0;
Tensor * ts_out_1 = new Tensor();
Tensor * ts_out_2 = new Tensor();
Tensor * ts_out_3 = new Tensor();
Tensor * ts_out_4 = new Tensor();
Tensor * ts_out_5 = new Tensor();
Tensor * ts_out_6 = new Tensor();
Tensor * ts_out_7 = new Tensor();
Tensor * ts_out_8 = new Tensor();
Tensor * ts_out_9 = new Tensor();
Tensor * ts_out_10 = new Tensor();
//First Branch
NEConvolutionLayer * layer_group_before_1 = new NEConvolutionLayer();
NEBatchNormalizationLayer * layer_group_before_1_bn = new NEBatchNormalizationLayer();
NEDepthwiseConvolutionLayer * layer_dw_1 = new NEDepthwiseConvolutionLayer();
NEBatchNormalizationLayer * layer_dw_1_bn = new NEBatchNormalizationLayer();
NEConvolutionLayer * layer_group_after_1 = new NEConvolutionLayer();
NEBatchNormalizationLayer * layer_group_after_1_bn = new NEBatchNormalizationLayer();
//Second Branch
NEDepthwiseConvolutionLayer * layer_dw_2 = new NEDepthwiseConvolutionLayer();
NEBatchNormalizationLayer * layer_dw_2_bn = new NEBatchNormalizationLayer();
NEConvolutionLayer * layer_group_after_2 = new NEConvolutionLayer();
NEBatchNormalizationLayer * layer_group_after_2_bn = new NEBatchNormalizationLayer();
//Concat
NEArithmeticAddition * layer_branchAdd = new NEArithmeticAddition();
};
}
#endif | [
"dujingsu@163.com"
] | dujingsu@163.com |
4087be0d1d2765dabc3b5c63f420a0843227057a | 38c10c01007624cd2056884f25e0d6ab85442194 | /third_party/pdfium/fpdfsdk/src/fpdfdoc.cpp | 8a4d619292aeb322dea564cca36ddc2c36660e2d | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | permissive | zenoalbisser/chromium | 6ecf37b6c030c84f1b26282bc4ef95769c62a9b2 | e71f21b9b4b9b839f5093301974a45545dad2691 | refs/heads/master | 2022-12-25T14:23:18.568575 | 2016-07-14T21:49:52 | 2016-07-23T08:02:51 | 63,980,627 | 0 | 2 | BSD-3-Clause | 2022-12-12T12:43:41 | 2016-07-22T20:14:04 | null | UTF-8 | C++ | false | false | 11,672 | cpp | // Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "../../public/fpdf_doc.h"
#include "../include/fsdk_define.h"
namespace {
int THISMODULE = 0;
CPDF_Bookmark FindBookmark(const CPDF_BookmarkTree& tree,
CPDF_Bookmark bookmark,
const CFX_WideString& title) {
if (bookmark && bookmark.GetTitle().CompareNoCase(title.c_str()) == 0) {
// First check this item
return bookmark;
}
// go into children items
CPDF_Bookmark child = tree.GetFirstChild(bookmark);
while (child) {
// check if this item
CPDF_Bookmark found = FindBookmark(tree, child, title);
if (found)
return found;
child = tree.GetNextSibling(child);
}
return CPDF_Bookmark();
}
void ReleaseLinkList(void* data) {
delete (CPDF_LinkList*)data;
}
CPDF_LinkList* GetLinkList(CPDF_Page* page) {
if (!page)
return nullptr;
// Link list is stored with the document
CPDF_Document* pDoc = page->m_pDocument;
CPDF_LinkList* pLinkList = (CPDF_LinkList*)pDoc->GetPrivateData(&THISMODULE);
if (!pLinkList) {
pLinkList = new CPDF_LinkList;
pDoc->SetPrivateData(&THISMODULE, pLinkList, ReleaseLinkList);
}
return pLinkList;
}
} // namespace
DLLEXPORT FPDF_BOOKMARK STDCALL
FPDFBookmark_GetFirstChild(FPDF_DOCUMENT document, FPDF_BOOKMARK pDict) {
CPDF_Document* pDoc = CPDFDocumentFromFPDFDocument(document);
if (!pDoc)
return nullptr;
CPDF_BookmarkTree tree(pDoc);
CPDF_Bookmark bookmark =
CPDF_Bookmark(ToDictionary(static_cast<CPDF_Object*>(pDict)));
return tree.GetFirstChild(bookmark).GetDict();
}
DLLEXPORT FPDF_BOOKMARK STDCALL
FPDFBookmark_GetNextSibling(FPDF_DOCUMENT document, FPDF_BOOKMARK pDict) {
if (!pDict)
return nullptr;
CPDF_Document* pDoc = CPDFDocumentFromFPDFDocument(document);
if (!pDoc)
return nullptr;
CPDF_BookmarkTree tree(pDoc);
CPDF_Bookmark bookmark =
CPDF_Bookmark(ToDictionary(static_cast<CPDF_Object*>(pDict)));
return tree.GetNextSibling(bookmark).GetDict();
}
DLLEXPORT unsigned long STDCALL FPDFBookmark_GetTitle(FPDF_BOOKMARK pDict,
void* buffer,
unsigned long buflen) {
if (!pDict)
return 0;
CPDF_Bookmark bookmark(ToDictionary(static_cast<CPDF_Object*>(pDict)));
CFX_WideString title = bookmark.GetTitle();
CFX_ByteString encodedTitle = title.UTF16LE_Encode();
unsigned long len = encodedTitle.GetLength();
if (buffer && buflen >= len) {
FXSYS_memcpy(buffer, encodedTitle.c_str(), len);
}
return len;
}
DLLEXPORT FPDF_BOOKMARK STDCALL FPDFBookmark_Find(FPDF_DOCUMENT document,
FPDF_WIDESTRING title) {
if (!title || title[0] == 0)
return nullptr;
CPDF_Document* pDoc = CPDFDocumentFromFPDFDocument(document);
if (!pDoc)
return nullptr;
CPDF_BookmarkTree tree(pDoc);
FX_STRSIZE len = CFX_WideString::WStringLength(title);
CFX_WideString encodedTitle = CFX_WideString::FromUTF16LE(title, len);
return FindBookmark(tree, CPDF_Bookmark(), encodedTitle).GetDict();
}
DLLEXPORT FPDF_DEST STDCALL FPDFBookmark_GetDest(FPDF_DOCUMENT document,
FPDF_BOOKMARK pDict) {
if (!pDict)
return nullptr;
CPDF_Document* pDoc = CPDFDocumentFromFPDFDocument(document);
if (!pDoc)
return nullptr;
CPDF_Bookmark bookmark(ToDictionary(static_cast<CPDF_Object*>(pDict)));
CPDF_Dest dest = bookmark.GetDest(pDoc);
if (dest)
return dest.GetObject();
// If this bookmark is not directly associated with a dest, we try to get
// action
CPDF_Action action = bookmark.GetAction();
if (!action)
return nullptr;
return action.GetDest(pDoc).GetObject();
}
DLLEXPORT FPDF_ACTION STDCALL FPDFBookmark_GetAction(FPDF_BOOKMARK pDict) {
if (!pDict)
return NULL;
CPDF_Bookmark bookmark(ToDictionary(static_cast<CPDF_Object*>(pDict)));
return bookmark.GetAction().GetDict();
}
DLLEXPORT unsigned long STDCALL FPDFAction_GetType(FPDF_ACTION pDict) {
if (!pDict)
return PDFACTION_UNSUPPORTED;
CPDF_Action action(ToDictionary(static_cast<CPDF_Object*>(pDict)));
CPDF_Action::ActionType type = action.GetType();
switch (type) {
case CPDF_Action::GoTo:
return PDFACTION_GOTO;
case CPDF_Action::GoToR:
return PDFACTION_REMOTEGOTO;
case CPDF_Action::URI:
return PDFACTION_URI;
case CPDF_Action::Launch:
return PDFACTION_LAUNCH;
default:
return PDFACTION_UNSUPPORTED;
}
}
DLLEXPORT FPDF_DEST STDCALL FPDFAction_GetDest(FPDF_DOCUMENT document,
FPDF_ACTION pDict) {
if (!pDict)
return nullptr;
CPDF_Document* pDoc = CPDFDocumentFromFPDFDocument(document);
if (!pDoc)
return nullptr;
CPDF_Action action(ToDictionary(static_cast<CPDF_Object*>(pDict)));
return action.GetDest(pDoc).GetObject();
}
DLLEXPORT unsigned long STDCALL
FPDFAction_GetFilePath(FPDF_ACTION pDict, void* buffer, unsigned long buflen) {
unsigned long type = FPDFAction_GetType(pDict);
if (type != PDFACTION_REMOTEGOTO && type != PDFACTION_LAUNCH)
return 0;
CPDF_Action action(ToDictionary(static_cast<CPDF_Object*>(pDict)));
CFX_ByteString path = action.GetFilePath().UTF8Encode();
unsigned long len = path.GetLength() + 1;
if (buffer && buflen >= len)
FXSYS_memcpy(buffer, path.c_str(), len);
return len;
}
DLLEXPORT unsigned long STDCALL FPDFAction_GetURIPath(FPDF_DOCUMENT document,
FPDF_ACTION pDict,
void* buffer,
unsigned long buflen) {
if (!pDict)
return 0;
CPDF_Document* pDoc = CPDFDocumentFromFPDFDocument(document);
if (!pDoc)
return 0;
CPDF_Action action(ToDictionary(static_cast<CPDF_Object*>(pDict)));
CFX_ByteString path = action.GetURI(pDoc);
unsigned long len = path.GetLength() + 1;
if (buffer && buflen >= len)
FXSYS_memcpy(buffer, path.c_str(), len);
return len;
}
DLLEXPORT unsigned long STDCALL FPDFDest_GetPageIndex(FPDF_DOCUMENT document,
FPDF_DEST pDict) {
if (!pDict)
return 0;
CPDF_Document* pDoc = CPDFDocumentFromFPDFDocument(document);
if (!pDoc)
return 0;
CPDF_Dest dest(static_cast<CPDF_Array*>(pDict));
return dest.GetPageIndex(pDoc);
}
DLLEXPORT FPDF_LINK STDCALL
FPDFLink_GetLinkAtPoint(FPDF_PAGE page, double x, double y) {
CPDF_Page* pPage = CPDFPageFromFPDFPage(page);
if (!pPage)
return nullptr;
CPDF_LinkList* pLinkList = GetLinkList(pPage);
if (!pLinkList)
return nullptr;
return pLinkList->GetLinkAtPoint(pPage, (FX_FLOAT)x, (FX_FLOAT)y, nullptr)
.GetDict();
}
DLLEXPORT int STDCALL
FPDFLink_GetLinkZOrderAtPoint(FPDF_PAGE page, double x, double y) {
CPDF_Page* pPage = CPDFPageFromFPDFPage(page);
if (!pPage)
return -1;
CPDF_LinkList* pLinkList = GetLinkList(pPage);
if (!pLinkList)
return -1;
int z_order = -1;
pLinkList->GetLinkAtPoint(pPage, (FX_FLOAT)x, (FX_FLOAT)y, &z_order);
return z_order;
}
DLLEXPORT FPDF_DEST STDCALL FPDFLink_GetDest(FPDF_DOCUMENT document,
FPDF_LINK pDict) {
if (!pDict)
return nullptr;
CPDF_Document* pDoc = CPDFDocumentFromFPDFDocument(document);
if (!pDoc)
return nullptr;
CPDF_Link link(ToDictionary(static_cast<CPDF_Object*>(pDict)));
FPDF_DEST dest = link.GetDest(pDoc).GetObject();
if (dest)
return dest;
// If this link is not directly associated with a dest, we try to get action
CPDF_Action action = link.GetAction();
if (!action)
return nullptr;
return action.GetDest(pDoc).GetObject();
}
DLLEXPORT FPDF_ACTION STDCALL FPDFLink_GetAction(FPDF_LINK pDict) {
if (!pDict)
return nullptr;
CPDF_Link link(ToDictionary(static_cast<CPDF_Object*>(pDict)));
return link.GetAction().GetDict();
}
DLLEXPORT FPDF_BOOL STDCALL FPDFLink_Enumerate(FPDF_PAGE page,
int* startPos,
FPDF_LINK* linkAnnot) {
if (!startPos || !linkAnnot)
return FALSE;
CPDF_Page* pPage = CPDFPageFromFPDFPage(page);
if (!pPage || !pPage->m_pFormDict)
return FALSE;
CPDF_Array* pAnnots = pPage->m_pFormDict->GetArray("Annots");
if (!pAnnots)
return FALSE;
for (int i = *startPos; i < (int)pAnnots->GetCount(); i++) {
CPDF_Dictionary* pDict =
ToDictionary(static_cast<CPDF_Object*>(pAnnots->GetElementValue(i)));
if (!pDict)
continue;
if (pDict->GetString(FX_BSTRC("Subtype")).Equal(FX_BSTRC("Link"))) {
*startPos = i + 1;
*linkAnnot = (FPDF_LINK)pDict;
return TRUE;
}
}
return FALSE;
}
DLLEXPORT FPDF_BOOL STDCALL FPDFLink_GetAnnotRect(FPDF_LINK linkAnnot,
FS_RECTF* rect) {
if (!linkAnnot || !rect)
return FALSE;
CPDF_Dictionary* pAnnotDict =
ToDictionary(static_cast<CPDF_Object*>(linkAnnot));
CPDF_Rect rt = pAnnotDict->GetRect(FX_BSTRC("Rect"));
rect->left = rt.left;
rect->bottom = rt.bottom;
rect->right = rt.right;
rect->top = rt.top;
return TRUE;
}
DLLEXPORT int STDCALL FPDFLink_CountQuadPoints(FPDF_LINK linkAnnot) {
if (!linkAnnot)
return 0;
CPDF_Dictionary* pAnnotDict =
ToDictionary(static_cast<CPDF_Object*>(linkAnnot));
CPDF_Array* pArray = pAnnotDict->GetArray(FX_BSTRC("QuadPoints"));
if (!pArray)
return 0;
return pArray->GetCount() / 8;
}
DLLEXPORT FPDF_BOOL STDCALL FPDFLink_GetQuadPoints(FPDF_LINK linkAnnot,
int quadIndex,
FS_QUADPOINTSF* quadPoints) {
if (!linkAnnot || !quadPoints)
return FALSE;
CPDF_Dictionary* pAnnotDict =
ToDictionary(static_cast<CPDF_Object*>(linkAnnot));
CPDF_Array* pArray = pAnnotDict->GetArray(FX_BSTRC("QuadPoints"));
if (pArray) {
if (quadIndex < 0 || quadIndex >= (int)pArray->GetCount() / 8 ||
((quadIndex * 8 + 7) >= (int)pArray->GetCount()))
return FALSE;
quadPoints->x1 = pArray->GetNumber(quadIndex * 8);
quadPoints->y1 = pArray->GetNumber(quadIndex * 8 + 1);
quadPoints->x2 = pArray->GetNumber(quadIndex * 8 + 2);
quadPoints->y2 = pArray->GetNumber(quadIndex * 8 + 3);
quadPoints->x3 = pArray->GetNumber(quadIndex * 8 + 4);
quadPoints->y3 = pArray->GetNumber(quadIndex * 8 + 5);
quadPoints->x4 = pArray->GetNumber(quadIndex * 8 + 6);
quadPoints->y4 = pArray->GetNumber(quadIndex * 8 + 7);
return TRUE;
}
return FALSE;
}
DLLEXPORT unsigned long STDCALL FPDF_GetMetaText(FPDF_DOCUMENT doc,
FPDF_BYTESTRING tag,
void* buffer,
unsigned long buflen) {
if (!tag)
return 0;
CPDF_Document* pDoc = CPDFDocumentFromFPDFDocument(doc);
if (!pDoc)
return 0;
CPDF_Dictionary* pInfo = pDoc->GetInfo();
if (!pInfo)
return 0;
CFX_WideString text = pInfo->GetUnicodeText(tag);
// Use UTF-16LE encoding
CFX_ByteString encodedText = text.UTF16LE_Encode();
unsigned long len = encodedText.GetLength();
if (buffer && buflen >= len) {
FXSYS_memcpy(buffer, encodedText.c_str(), len);
}
return len;
}
| [
"zeno.albisser@hemispherian.com"
] | zeno.albisser@hemispherian.com |
15cface1b2b803556e97ba451787481105d3c3c2 | e52327e0c890b24349222a5e0e0a5e1ca247c02f | /src/qt/masternodelist.h | 4ed441932c1e44648fd06f943b466a9af4b0277a | [
"MIT"
] | permissive | oryxian/oryxcoin | 33910e64cf188f2005ef2be28785935eee202c3c | bcd9f790f468f87714afe38c0936c176f4d302c3 | refs/heads/master | 2020-04-23T07:12:23.028248 | 2019-02-16T12:22:45 | 2019-02-16T12:22:45 | 140,945,061 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,865 | h | // Copyright (c) 2014-2016 The Dash Developers
// Copyright (c) 2016-2017 The PIVX developers
// Copyright (c) 2017-2018 The Oryxcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef MASTERNODELIST_H
#define MASTERNODELIST_H
#include "masternode.h"
#include "platformstyle.h"
#include "sync.h"
#include "util.h"
#include <QMenu>
#include <QTimer>
#include <QWidget>
#define MY_MASTERNODELIST_UPDATE_SECONDS 60
#define MASTERNODELIST_UPDATE_SECONDS 15
#define MASTERNODELIST_FILTER_COOLDOWN_SECONDS 3
namespace Ui
{
class MasternodeList;
}
class ClientModel;
class WalletModel;
QT_BEGIN_NAMESPACE
class QModelIndex;
QT_END_NAMESPACE
/** Masternode Manager page widget */
class MasternodeList : public QWidget
{
Q_OBJECT
public:
explicit MasternodeList(QWidget* parent = 0);
~MasternodeList();
void setClientModel(ClientModel* clientModel);
void setWalletModel(WalletModel* walletModel);
void StartAlias(std::string strAlias);
void StartAll(std::string strCommand = "start-all");
private:
QMenu* contextMenu;
int64_t nTimeFilterUpdated;
bool fFilterUpdated;
public Q_SLOTS:
void updateMyMasternodeInfo(QString strAlias, QString strAddr, CMasternode* pmn);
void updateMyNodeList(bool fForce = false);
Q_SIGNALS:
private:
QTimer* timer;
Ui::MasternodeList* ui;
ClientModel* clientModel;
WalletModel* walletModel;
CCriticalSection cs_mnlistupdate;
QString strCurrentFilter;
private Q_SLOTS:
void showContextMenu(const QPoint&);
void on_startButton_clicked();
void on_startAllButton_clicked();
void on_startMissingButton_clicked();
void on_tableWidgetMyMasternodes_itemSelectionChanged();
void on_UpdateButton_clicked();
};
#endif // MASTERNODELIST_H
| [
"39878257+oryxian@users.noreply.github.com"
] | 39878257+oryxian@users.noreply.github.com |
d7782efb6a280ab3fcea553a3e1079fbbc74c244 | 5cf5223da2bf49af7f5a8ecde4d1cb31536f5ce7 | /extras/apps/ngs_roi/roi_feature_projection.cpp | c18e857a192fa11eaf8e506e7c43edeb5781441c | [
"BSD-3-Clause"
] | permissive | jwillis0720/seqan | e579f8419cec7f330eb1fe29838c5c098ee57240 | 36b300b8c4c42bbfc03edd3220fa299961d517be | refs/heads/master | 2020-12-02T15:06:46.899846 | 2015-01-10T08:59:05 | 2015-01-10T08:59:05 | 27,658,559 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 40,577 | cpp | // ==========================================================================
// NGS: Regions of Interest Analysis
// ==========================================================================
// Copyright (c) 2012-2013, Bernd Jagla, Institut Pasteur
// 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: Manuel Holtgrewe <manuel.holtgrewe@fu-berlin.de>
// ==========================================================================
// Intersection of ROI file with BED and/or GFF files.
// ==========================================================================
// TODO(holtgrew): Actually, union is projection with extension and could be renamed.
// TODO(holtgrew): More stringent checking, i.e. make sure that input is GFF/GTF if grouping/filtering is active.
// TODO(holtgrew): Rename to roi_overlapper?
#include <sstream>
#include <seqan/basic.h>
#include <seqan/sequence.h>
#include <seqan/arg_parse.h>
#include "project_interval.h"
#include "project_spliced.h"
#include "version.h"
// ==========================================================================
// Classes
// ==========================================================================
// --------------------------------------------------------------------------
// Class RoiIntersectOptions
// --------------------------------------------------------------------------
// This struct stores the options from the command line.
//
// You might want to rename this to reflect the name of your app.
struct RoiIntersectOptions
{
// The combination mode.
enum CombinationMode
{
PROJECTION,
INTERSECTION,
UNION,
DIFF
};
// Verbosity level. 0 -- quiet, 1 -- normal, 2 -- verbose, 3 -- very verbose.
int verbosity;
// Path to ROI file to read.
seqan::CharString inputRoiFile;
// Path to intervals file to read.
seqan::CharString inputIntervalsFile;
seqan::CharString inputIntervalsFileExt; // extension for type
// Output ROI file.
seqan::CharString outputRoiFile;
// The GFF/GTF record type to filter for. Empty for no filter.
seqan::CharString gffType;
// The GFF/GTF key/tag name to use for grouping. Empty for no grouping.
seqan::CharString gffGroupBy;
// The mode to use for the combination.
CombinationMode mode;
// Whether or not to run in strand-specific mode.
bool strandSpecific;
RoiIntersectOptions() : verbosity(1), mode(PROJECTION), strandSpecific(false)
{}
};
// --------------------------------------------------------------------------
// Class RoiIntersectApp
// --------------------------------------------------------------------------
// Class RoiIntersectApp
class RoiIntersectApp
{
public:
typedef seqan::RecordReader<std::ifstream, seqan::SinglePass<> > TRecordReader;
// The configuration for the application.
RoiIntersectOptions const & options;
// Input file streams.
std::ifstream inIntervals, inRoi;
std::ofstream outRoi;
RoiIntersectApp(RoiIntersectOptions const & options) : options(options)
{}
// App object's main routine. Contains mostly console I/O.
int run();
// Called by run() for the actual work step.
int doStreaming();
};
// --------------------------------------------------------------------------
// Class IntersectDriver
// --------------------------------------------------------------------------
// Helper function: Make the given record (must have int rId and int beginPos members) a sentinel (> all others).
template <typename TRecord>
void makeSentinel(TRecord & record)
{
clear(record.ref);
record.rID = seqan::maxValue<int>();
record.beginPos = seqan::maxValue<int>();
}
void makeSentinel(seqan::GffRecord & record)
{
clear(record.ref);
record.rID = seqan::maxValue<int>();
record.beginPos = seqan::maxValue<int>();
}
// Configuration object for directly reading BED records with IntersectDriver.
struct IntersectWithBedConfig
{
typedef seqan::StringSet<seqan::CharString> TNameStore;
typedef seqan::BedIOContext<TNameStore> TBedIOContext;
IntersectWithBedConfig(RoiIntersectOptions const & /*options*/)
{}
template <typename TStream, typename TReaderSpec>
int readRecord(seqan::BedRecord<seqan::Bed6> & record,
seqan::RecordReader<TStream, TReaderSpec> & reader,
TBedIOContext & bedIOContext)
{
return seqan::readRecord(record, reader, bedIOContext, seqan::Bed());
}
};
// Configuration object for directly reading GFF records with IntersectDriver with implicit conversion to BED.
struct IntersectWithGffConfig
{
typedef seqan::StringSet<seqan::CharString> TNameStore;
typedef seqan::GffIOContext<TNameStore> TBedIOContext;
// running number of read GFF records.
int gffID;
// The GFF record type to filter to.
seqan::CharString gffType;
// Used for building BED record names.
std::stringstream ss;
// Buffer for the current GFF record.
seqan::GffRecord gffRecord;
IntersectWithGffConfig(RoiIntersectOptions const & options) : gffID(0), gffType(options.gffType)
{}
template <typename TStream, typename TReaderSpec>
int readRecord(seqan::BedRecord<seqan::Bed6> & bedRecord,
seqan::RecordReader<TStream, TReaderSpec> & reader,
TBedIOContext & gffIOContext)
{
// Read GFF record. When GFF record type filtering is active then we skip over records with the incorrect type.
// We make bedRecord a sentinel if there is no GFF record with a valid type left.
while (!atEnd(reader))
{
int res = 0;
if ((res = seqan::readRecord(gffRecord, reader, gffIOContext, seqan::Gff())) != 0)
return res;
if (!empty(gffType) && gffRecord.type != gffType)
continue; // Read next.
// Convert GFF to BED.
clear(bedRecord);
bedRecord.ref = gffRecord.ref;
bedRecord.rID = gffRecord.rID;
bedRecord.beginPos = gffRecord.beginPos;
bedRecord.endPos = gffRecord.endPos;
bedRecord.score = 0;
bedRecord.strand = (gffRecord.strand == '-') ? '-' : '+'; // '.' becomes '+'
// Build BED record name. We cannot rely on the GFF/GTF record having an ID so we simply construct one.
ss.str("");
ss.clear();
ss << "ggf_" << (gffID++) << "_" << bedRecord.ref << ":" << bedRecord.beginPos << "-" << bedRecord.endPos;
bedRecord.name = ss.str();
return 0;
}
makeSentinel(bedRecord);
return 0;
}
};
// This class template is used for the generic streaming of ROIs against BED records or GFF records being converted into
// BED records. The names for the I/O contexts and record readers are prefixed for BED even if we actually read from
// GFF and convert to BED afterwards.
template <typename TConfig>
class IntersectDriver
{
public:
// Names store for the reference names.
typedef seqan::StringSet<seqan::CharString> TNameStore;
// TConfig defines some types and we have an instance for reading BED records and converting GFF records to BED
// records when reading.
TConfig config;
// The reference name store and a cache for this store.
TNameStore refNames;
seqan::NameStoreCache<TNameStore> refNamesCache;
// File stream for writing ROI to.
std::ofstream & outRoi;
// I/O contexts for translating reference names to ids.
typename TConfig::TBedIOContext bedIOContext;
seqan::RoiIOContext<TNameStore> roiIOContext;
// Record readers for reading the files.
seqan::RecordReader<std::ifstream, seqan::SinglePass<> > bedReader;
seqan::RecordReader<std::ifstream, seqan::SinglePass<> > roiReader;
// BED and ROI records.
seqan::BedRecord<seqan::Bed6> bedRecord;
seqan::RoiRecord roiRecord;
// Options for intersecting.
RoiIntersectOptions const & options;
IntersectDriver(std::ofstream & outRoi, std::ifstream & bedStream, std::ifstream & roiStream,
RoiIntersectOptions const & options) :
config(options), refNamesCache(refNames), outRoi(outRoi), bedIOContext(refNames, refNamesCache),
roiIOContext(refNames, refNamesCache), bedReader(bedStream), roiReader(roiStream),
options(options)
{}
int run()
{
// TODO(holtgrew): What happens if there are no records for one contig?
// Write header.
outRoi << "##ref\t"
<< "begin_pos\t"
<< "end_pos\t"
<< "region_name\t"
<< "length\t"
<< "strand\t"
<< "max_count\t"
<< "counts\n";
// Read first records.
while (!atEnd(bedReader) && value(bedReader) == '#')
if (skipLine(bedReader) != 0)
{
std::cerr << "ERROR: Could not skip header/comment line in BED.\n";
return 1;
}
if (atEnd(bedReader))
{
makeSentinel(bedRecord);
}
else if (config.readRecord(bedRecord, bedReader, bedIOContext) != 0)
{
std::cerr << "ERROR: Problem reading from BED file!\n";
return 1;
}
while (!atEnd(roiReader) && value(roiReader) == '#')
if (skipLine(roiReader) != 0)
{
std::cerr << "ERROR: Could not skip header/comment line in ROI.\n";
return 1;
}
if (atEnd(roiReader))
{
makeSentinel(roiRecord);
}
else if (readRecord(roiRecord, roiReader, roiIOContext, seqan::Roi()) != 0)
{
std::cerr << "ERROR: Problem reading from ROI file!\n";
return 1;
}
// The algorithm objects.
IntersectBedOptions intersectOptions;
switch (options.mode)
{
case RoiIntersectOptions::PROJECTION:
intersectOptions.mode = IntersectBedOptions::PROJECTION;
break;
case RoiIntersectOptions::INTERSECTION:
intersectOptions.mode = IntersectBedOptions::INTERSECTION;
break;
case RoiIntersectOptions::UNION:
intersectOptions.mode = IntersectBedOptions::UNION;
break;
case RoiIntersectOptions::DIFF:
intersectOptions.mode = IntersectBedOptions::DIFF;
break;
default:
SEQAN_FAIL("Cannot reach here!");
}
intersectOptions.verbosity = options.verbosity;
// We create two IntersectBed objects, one for each forward and reverse strand. The forward IntersectBed object is
// also used in non-strand-specific mode.
IntersectBed intersectBedF(outRoi, intersectOptions);
IntersectBed intersectBedR(outRoi, intersectOptions);
// Stream over all BED and ROI records.
while (bedRecord.rID != seqan::maxValue<int>() || roiRecord.rID != seqan::maxValue<int>())
{
if (options.verbosity >= 3)
{
std::cerr << ",--\n"
<< "| ROI:\t";
writeRecord(std::cerr, roiRecord, seqan::Roi());
std::cerr << "| BED:\t";
writeRecord(std::cerr, bedRecord, seqan::Bed());
std::cerr << "`--\n";
}
// Push smaller, prefering ROI over BED on ties.
if (bedRecord.rID < roiRecord.rID || (bedRecord.rID == roiRecord.rID && bedRecord.beginPos < roiRecord.beginPos))
{
if (!options.strandSpecific || bedRecord.strand == '+')
intersectBedF.pushBed(bedRecord);
else
intersectBedR.pushBed(bedRecord);
clear(bedRecord);
// Read next records
if (atEnd(bedReader))
{
makeSentinel(bedRecord);
if (options.verbosity >= 2)
std::cerr << "BED record is a sentinel now!\n";
}
else if (config.readRecord(bedRecord, bedReader, bedIOContext) != 0)
{
std::cerr << "ERROR: Problem reading from BED file!\n";
return 1;
}
}
else
{
if (!options.strandSpecific || roiRecord.strand == '+')
intersectBedF.pushRoi(roiRecord);
else
intersectBedR.pushRoi(roiRecord);
clear(roiRecord);
// Read next record.
if (atEnd(roiReader))
{
makeSentinel(roiRecord);
if (options.verbosity >= 2)
std::cerr << "ROI record is a sentinel now!\n";
}
else if (readRecord(roiRecord, roiReader, roiIOContext, seqan::Roi()) != 0)
{
std::cerr << "ERROR: Problem reading from ROI file!\n";
return 1;
}
}
}
return 0;
}
};
// --------------------------------------------------------------------------
// Class GroupByDriver
// --------------------------------------------------------------------------
// Helper function.
seqan::Pair<int, int> position(seqan::GffRecord const & record)
{
return seqan::Pair<int, int>(record.rID, record.beginPos);
}
seqan::Pair<int, int> position(seqan::RoiRecord const & record)
{
return seqan::Pair<int, int>(record.rID, record.beginPos);
}
// Code for the intersection with grouping of GFF records.
class GroupByDriver
{
public:
// Names store for the reference names.
typedef seqan::StringSet<seqan::CharString> TNameStore;
// The reference name store and a cache for this store.
TNameStore refNames;
seqan::NameStoreCache<TNameStore> refNamesCache;
// File stream for writing ROI to.
std::ofstream & outRoi;
// I/O contexts for translating reference names to ids.
seqan::GffIOContext<TNameStore> gffIOContext;
seqan::RoiIOContext<TNameStore> roiIOContext;
// Record readers for reading the files.
seqan::RecordReader<std::ifstream, seqan::SinglePass<> > gffReader;
seqan::RecordReader<std::ifstream, seqan::SinglePass<> > roiReader;
// BED and ROI records.
seqan::GffRecord gffRecord;
seqan::RoiRecord roiRecord;
// Options for intersecting.
RoiIntersectOptions const & options;
GroupByDriver(std::ofstream & outRoi, std::ifstream & bedStream, std::ifstream & roiStream,
RoiIntersectOptions const & options) :
refNamesCache(refNames), outRoi(outRoi), gffIOContext(refNames, refNamesCache),
roiIOContext(refNames, refNamesCache), gffReader(bedStream), roiReader(roiStream),
options(options)
{}
// Actually running the intersection with grouping.
int run()
{
// The current reference name.
seqan::CharString ref;
// Write header.
outRoi << "##ref\t"
<< "begin_pos\t"
<< "end_pos\t"
<< "region_name\t"
<< "length\t"
<< "strand\t"
<< "max_count\t"
<< "counts\n";
// TODO(holtgrew): What happens if there are no records for one contig?
// Initialize objects that we will use for the overlapping and output generation.
ProjectSplicedRoi workerF(outRoi, options.gffGroupBy, options.verbosity);
ProjectSplicedRoi workerR(outRoi, options.gffGroupBy, options.verbosity);
// Read first records.
if (initializeRecords() != 0)
return 1;
if (options.verbosity >= 2)
{
std::cerr << "FIRST GFF RECORD REF = " << ref << "\n ";
writeRecord(std::cerr, gffRecord, seqan::Gff());
}
typedef seqan::RecordReader<std::ifstream, seqan::SinglePass<> > TGffReader;
typedef seqan::Position<TGffReader>::Type TGffReaderPos;
TGffReaderPos chromBegin = position(gffReader);
while (gffRecord.rID != seqan::maxValue<int>())
{
// First pass: Register all GFF records with worker and reset position to chromosome begin afterwards.
if (roiRecord.rID != seqan::maxValue<int>())
ref = std::min(gffRecord.ref, roiRecord.ref);
else
ref = gffRecord.ref; // case where ROI is already at end
if (options.verbosity >= 2)
std::cerr << "FIRST PASS REF=" << ref << "\n";
workerF.beginContig();
workerR.beginContig();
chromBegin = position(gffReader);
seqan::GffRecord firstGffRecord = gffRecord;
while (gffRecord.ref == ref)
{
if (!empty(options.gffType) && gffRecord.type == options.gffType)
{
if (!options.strandSpecific || gffRecord.strand == '+')
workerF.updateRanges(gffRecord);
else
workerR.updateRanges(gffRecord);
}
if (atEnd(gffReader))
{
makeSentinel(gffRecord);
if (options.verbosity >= 2)
std::cerr << "GFF record is a sentinel now.\n";
}
else if (readRecord(gffRecord, gffReader, gffIOContext, seqan::Gff()) != 0)
{
std::cerr << "ERROR: Problem reading GFF.\n";
return 1;
}
}
if (!atEnd(gffReader))
SEQAN_ASSERT_GT(gffRecord.ref, ref);
if (setPosition(gffReader, chromBegin) != 0)
{
std::cerr << "ERROR: Could not reset file pointer for second pass!\n";
return 1;
}
gffRecord = firstGffRecord;
if (options.verbosity >= 2)
std::cerr << "SECOND PASS REF=" << ref << "\n";
workerF.beginSecondPass();
workerR.beginSecondPass();
while (gffRecord.ref == ref || roiRecord.ref == ref)
{
if (options.verbosity >= 3)
{
std::cerr << ",--\n"
<< "| ROI:\t";
// NOTE that the sentinel is given as a negative value because of an overflow.
writeRecord(std::cerr, roiRecord, seqan::Roi());
std::cerr << "| GFF:\t";
writeRecord(std::cerr, gffRecord, seqan::Gff());
std::cerr << "`--\n";
}
// Push smaller, prefering ROI over GFF on ties.
if (roiRecord.rID == seqan::maxValue<int>() ||
std::make_pair(gffRecord.ref, (int)gffRecord.beginPos) <
std::make_pair(roiRecord.ref, roiRecord.beginPos))
{
if (gffRecord.rID == seqan::maxValue<int>())
break; // Break out of outer loop, termination criterion.
if (!empty(options.gffType) && gffRecord.type == options.gffType)
{
if (!options.strandSpecific || gffRecord.strand == '+')
workerF.pushGff(gffRecord);
else
workerR.pushGff(gffRecord);
}
clear(gffRecord);
// Get current position to check for sortedness of GFF.
std::pair<seqan::CharString, __uint32> oldPos(gffRecord.ref, gffRecord.beginPos);
// Read next records
if (atEnd(gffReader))
{
makeSentinel(gffRecord);
if (options.verbosity >= 3)
std::cerr << "GFF record is a sentinel now!\n";
}
else if (readRecord(gffRecord, gffReader, gffIOContext, seqan::Gff()) != 0)
{
std::cerr << "ERROR: Problem reading from GFF file!\n";
return 1;
}
if (std::make_pair(gffRecord.ref, gffRecord.beginPos) < oldPos)
{
std::cerr << "ERROR: GFF file is not sorted properly!\n";
return 1;
}
}
else
{
if (!options.strandSpecific || roiRecord.strand == '+')
workerF.pushRoi(roiRecord);
else
workerR.pushRoi(roiRecord);
clear(roiRecord);
// Get current position to check for sortedness of GFF.
std::pair<seqan::CharString, int> oldPos(roiRecord.ref, roiRecord.beginPos);
// Read next record.
if (atEnd(roiReader))
{
makeSentinel(roiRecord);
if (options.verbosity >= 2)
std::cerr << "ROI record is a sentinel now!\n";
}
else if (readRecord(roiRecord, roiReader, roiIOContext, seqan::Roi()) != 0)
{
std::cerr << "ERROR: Problem reading from ROI file!\n";
return 1;
}
if (std::make_pair(roiRecord.ref, roiRecord.beginPos) < oldPos)
{
std::cerr << "ERROR: ROI file is not sorted properly!\n";
return 1;
}
}
}
}
// Finish reading ROI file to check for sortedness.
while (!atEnd(roiReader))
{
std::pair<seqan::CharString, int> oldPos(roiRecord.ref, roiRecord.beginPos);
if (readRecord(roiRecord, roiReader, roiIOContext, seqan::Roi()) != 0)
{
std::cerr << "ERROR: Problem reading from ROI file!\n";
return 1;
}
if (std::make_pair(roiRecord.ref, roiRecord.beginPos) < oldPos)
{
std::cerr << "ERROR: ROI file is not sorted properly!\n";
return 1;
}
}
return 0;
}
int initializeRecords()
{
// TODO(holtgrew): Check for sortedness here as well.
// Read first records.
while (!atEnd(gffReader) && value(gffReader) == '#')
if (skipLine(gffReader) != 0)
{
std::cerr << "ERROR: Could not skip header/comment line in GFF.\n";
return 1;
}
if (atEnd(gffReader))
{
makeSentinel(gffRecord);
}
else
{
bool found = false;
while (!atEnd(gffReader))
{
if (readRecord(gffRecord, gffReader, gffIOContext, seqan::Gff()) != 0)
{
std::cerr << "ERROR: Problem reading from GFF file!\n";
return 1;
}
if (empty(options.gffType) || (options.gffType == gffRecord.type))
{
found = true;
break;
}
}
if (!found)
makeSentinel(gffRecord);
}
while (!atEnd(roiReader) && value(roiReader) == '#')
if (skipLine(roiReader) != 0)
{
std::cerr << "ERROR: Could not skip header/comment line in ROI.\n";
return 1;
}
if (atEnd(roiReader))
{
makeSentinel(roiRecord);
}
else if (readRecord(roiRecord, roiReader, roiIOContext, seqan::Roi()) != 0)
{
std::cerr << "ERROR: Problem reading from ROI file!\n";
return 1;
}
return 0;
}
};
// ==========================================================================
// Functions
// ==========================================================================
// --------------------------------------------------------------------------
// Function combinationModeStr()
// --------------------------------------------------------------------------
char const * combinationModeStr(RoiIntersectOptions::CombinationMode m)
{
switch (m)
{
case RoiIntersectOptions::PROJECTION:
return "projection";
case RoiIntersectOptions::INTERSECTION:
return "intersection";
case RoiIntersectOptions::UNION:
return "union";
case RoiIntersectOptions::DIFF:
return "difference";
default:
return "INVALID";
}
}
// --------------------------------------------------------------------------
// Function print()
// --------------------------------------------------------------------------
void print(std::ostream & out, RoiIntersectOptions const & options)
{
// Print the command line arguments back to the user.
out << "__OPTIONS____________________________________________________________________\n"
<< '\n'
<< "VERBOSITY \t" << options.verbosity << '\n'
<< "\n"
<< "INPUT ROI \t" << options.inputRoiFile << "\n"
<< "INPUT BED \t" << options.inputIntervalsFile << "\n"
<< "OUTPUT ROI \t" << options.outputRoiFile << "\n"
<< "\n"
<< "COMBINATION MODE\t" << combinationModeStr(options.mode) << "\n"
<< "\n"
<< "GFF TYPE \t" << options.gffType << "\n"
<< "GFF GROUP BY \t" << options.gffGroupBy << "\n"
<< "\n";
}
// --------------------------------------------------------------------------
// Function parseCommandLine()
// --------------------------------------------------------------------------
seqan::ArgumentParser::ParseResult
parseCommandLine(RoiIntersectOptions & options, int argc, char const ** argv)
{
// Setup ArgumentParser.
seqan::ArgumentParser parser("roi_feature_projection");
setCategory(parser, "NGS ROI Analysis");
// Set short description, version, and date.
setShortDescription(parser, "Region Of Interest Projection.");
setVersion(parser, VERSION);
setDate(parser, DATE);
// Define usage line and long description.
addUsageLine(parser, "[\\fIOPTIONS\\fP] \\fB-ir\\fP \\fIIN.roi\\fP \\fB-if\\fP \\fIIN.{bed,gff,gtf}\\fP \\fB-or\\fP \\fIOUT.roi\\fP");
addDescription(parser,
"Compute the projection of a ROI file to regions from a BED or GFF file. The result is "
"a ROI file where each interval from the BED/GFF/GTF file that overlapped with one input ROI file "
"is a region of interest, with the coverage counts projected to the new region of interest.");
// -----------------------------------------------------------------------
// General Options
// -----------------------------------------------------------------------
addOption(parser, seqan::ArgParseOption("q", "quiet", "Set verbosity to a minimum."));
addOption(parser, seqan::ArgParseOption("v", "verbose", "Enable verbose output."));
addOption(parser, seqan::ArgParseOption("vv", "very-verbose", "Enable very verbose output."));
// -----------------------------------------------------------------------
// Input / Output Options
// -----------------------------------------------------------------------
addSection(parser, "Input / Output");
addOption(parser, seqan::ArgParseOption("ir", "in-roi", "ROI file to read.", seqan::ArgParseOption::INPUTFILE, "ROI"));
setRequired(parser, "in-roi");
setValidValues(parser, "in-roi", "roi");
addOption(parser, seqan::ArgParseOption("if", "in-features", "BED, GFF, or GTF file to read.", seqan::ArgParseOption::INPUTFILE, "FILE"));
setRequired(parser, "in-features");
setValidValues(parser, "in-features", "bed gff gtf");
addOption(parser, seqan::ArgParseOption("or", "out-roi", "ROI file to write.", seqan::ArgParseOption::OUTPUTFILE, "ROI"));
setRequired(parser, "out-roi");
setValidValues(parser, "out-roi", "roi");
addOption(parser, seqan::ArgParseOption("g", "genome",
"Path to FASTA file with genome; optional. When given, this is used for "
"computing the overall region's C+G content.",
seqan::ArgParseOption::INPUTFILE, "FASTA"));
setValidValues(parser, "genome", "fasta fa");
// -----------------------------------------------------------------------
// Combination Options
// -----------------------------------------------------------------------
addSection(parser, "Combination Options");
addOption(parser, seqan::ArgParseOption("m", "mode",
"The mode in which to combine the ROI and BED/GFF file. See section "
"Combination Modes below for details.", seqan::ArgParseOption::STRING,
"MODE"));
setDefaultValue(parser, "mode", "projection");
setValidValues(parser, "mode", "intersection projection union difference");
addOption(parser, seqan::ArgParseOption("ss", "strand-specific", "Enable strand-specific mode if set."));
// -----------------------------------------------------------------------
// GFF Filter Options
// -----------------------------------------------------------------------
addSection(parser, "GFF Filters");
addOption(parser, seqan::ArgParseOption("", "gff-type",
"The GFF/GTF record type (value of third column) to keep. Keep all if "
"not set or input file type is not GFF/GTF.",
seqan::ArgParseOption::STRING, "STR"));
addOption(parser, seqan::ArgParseOption("", "gff-group-by",
"The GFF/GTF tag to use for grouping, e.g. \"Parent\", \"transcript_id\". No "
"grouping if empty. When using the grouping feature, the \\fB--mode\\fP is "
"automatically set to \\fIprojection\\fP.", seqan::ArgParseOption::STRING, "STR"));
// -----------------------------------------------------------------------
// Examples
// -----------------------------------------------------------------------
addTextSection(parser, "Examples");
addListItem(parser, "\\fBroi_intersect\\fP \\fB--in-features\\fP \\fIIN.bed\\fP \\fB--in-roi\\fP \\fIIN.roi\\fP \\fB--out-roi\\fP \\fIOUT.roi\\fP",
"Project the data from IN.roi to the intervals from IN.bed and write out the result to OUT.roi.");
addListItem(parser, "\\fBroi_intersect\\fP \\fB--mode\\fP \\fIdifference\\fP \\fB--in-features\\fP \\fIIN.bed\\fP \\fB--in-roi\\fP \\fIIN.roi\\fP \\fB--out-roi\\fP \\fIOUT.roi\\fP",
"Compute symmetric difference of IN.bed and IN.roi and write to OUT.roi.");
addListItem(parser, "\\fBroi_intersect\\fP \\fB--in-features\\fP \\fIIN.gff\\fP \\fB--gff-type\\fP \\fIexon\\fP \\fB--gff-group-by\\fP \\fIParent\\fP \\fB--in-roi\\fP \\fIIN.roi\\fP \\fB--out-roi\\fP \\fIOUT.roi\\fP",
"Project the data from IN.ROI to the intervals of type exon in IN.gff. The resulting projections to the"
"exons with the same Parent are then joined. Note that the exons have to be non-overlapping.");
// -----------------------------------------------------------------------
// Combination Modes Details
// -----------------------------------------------------------------------
addTextSection(parser, "Combination Modes");
addText(parser,
"The following combination modes are available.");
addListItem(parser, "\\fBintersection\\fP",
"Intersect the intervals BED/GFF file with the ones from the ROI file. Only the intersections are "
"kept and the coverage for each position is taken from the ROI records' coverages.");
addListItem(parser, "\\fBunion\\fP",
"Compute union of BED and BED/GFF file intervals, take coverages from ROI records. This leads "
"to the joining of ROIs into larger ones.");
addListItem(parser, "\\fBprojection\\fP",
"Compute intersection of BED/GFF file intervals with the ROI intervals. All BED/GFF intervals are "
"kept and the coverages are taken from the ROI records.");
addListItem(parser, "\\fBdifference\\fP",
"Compute symmetric difference of intervals in BED/GFF and ROI file. BED/GFF intervals without any "
"overlap in the ROI file are written out as ROI records with max_count=0. ROI intervals without "
"overlap in BED/GFF file are written out as they are in the input.");
// -----------------------------------------------------------------------
// Parse and Extract Options
// -----------------------------------------------------------------------
// Parse command line.
seqan::ArgumentParser::ParseResult res = seqan::parse(parser, argc, argv);
// Only extract options if the program will continue after parseCommandLine()
if (res != seqan::ArgumentParser::PARSE_OK)
return res;
// Extract option values.
if (isSet(parser, "quiet"))
options.verbosity = 0;
if (isSet(parser, "verbose"))
options.verbosity = 2;
if (isSet(parser, "very-verbose"))
options.verbosity = 3;
getOptionValue(options.inputRoiFile, parser, "in-roi");
getOptionValue(options.inputIntervalsFile, parser, "in-features");
options.inputIntervalsFileExt = getOptionFileExtension(parser, "in-features");
getOptionValue(options.outputRoiFile, parser, "out-roi");
seqan::CharString tmp;
getOptionValue(tmp, parser, "mode");
if (tmp == "projection")
options.mode = RoiIntersectOptions::PROJECTION;
else if (tmp == "intersection")
options.mode = RoiIntersectOptions::INTERSECTION;
else if (tmp == "union")
options.mode = RoiIntersectOptions::UNION;
else if (tmp == "difference")
options.mode = RoiIntersectOptions::DIFF;
options.strandSpecific = isSet(parser, "strand-specific");
getOptionValue(options.gffType, parser, "gff-type");
getOptionValue(options.gffGroupBy, parser, "gff-group-by");
if (!empty(options.gffGroupBy))
options.mode = RoiIntersectOptions::PROJECTION;
return seqan::ArgumentParser::PARSE_OK;
}
// --------------------------------------------------------------------------
// Member Function RoiIntersectApp::doStreaming()
// --------------------------------------------------------------------------
int RoiIntersectApp::doStreaming()
{
if (empty(options.gffGroupBy))
{
// Grouping is not ative, project against BED (or GFF/GTF reduced to BED information).
if (options.inputIntervalsFileExt == "bed" || options.inputIntervalsFileExt == ".bed")
{
IntersectDriver<IntersectWithBedConfig> driver(outRoi, inIntervals, inRoi, options);
return driver.run();
}
else
{
IntersectDriver<IntersectWithGffConfig> driver(outRoi, inIntervals, inRoi, options);
return driver.run();
}
}
else
{
// Group By is active, project with grouping.
GroupByDriver driver(outRoi, inIntervals, inRoi, options);
return driver.run();
}
}
// --------------------------------------------------------------------------
// Member Function RoiIntersectApp::run()
// --------------------------------------------------------------------------
int RoiIntersectApp::run()
{
if (options.verbosity >= 1)
{
std::cerr << "ROI INTERSECT\n"
<< "=============\n\n";
print(std::cerr, options);
}
if (options.verbosity >= 1)
std::cerr << "__OPENING FILES______________________________________________________________\n"
<< "\n";
if (options.verbosity >= 1)
std::cerr << "INPUT INTERVALS \t" << options.inputIntervalsFile << " ...";
inIntervals.open(toCString(options.inputIntervalsFile), std::ios::binary | std::ios::in);
if (!inIntervals.good())
{
std::cerr << "\nERROR: Could not open file!\n";
return 1;
}
if (options.verbosity >= 1)
std::cerr << " OK\n";
if (options.verbosity >= 1)
std::cerr << "INPUT ROI \t" << options.inputRoiFile << " ...";
inRoi.open(toCString(options.inputRoiFile), std::ios::binary | std::ios::in);
if (!inRoi.good())
{
std::cerr << "\nERROR: Could not open file!\n";
return 1;
}
if (options.verbosity >= 1)
std::cerr << " OK\n";
if (options.verbosity >= 1)
std::cerr << "OUTPUT ROI\t" << options.outputRoiFile << " ...";
outRoi.open(toCString(options.outputRoiFile), std::ios::binary | std::ios::out);
if (!inRoi.good())
{
std::cerr << "\nERROR: Could not open file!\n";
return 1;
}
if (options.verbosity >= 1)
std::cerr << " OK\n\n";
if (options.verbosity >= 1)
std::cerr << "__PROCESSING FILES___________________________________________________________\n"
<< "\n"
<< "STREAMING ...";
if (doStreaming() != 0)
return 1;
if (options.verbosity >= 1)
std::cerr << " OK\n\n";
if (options.verbosity >= 1)
std::cerr << "DONE.\n";
return 0;
}
// --------------------------------------------------------------------------
// Function main()
// --------------------------------------------------------------------------
// Program entry point.
int main(int argc, char const ** argv)
{
// Parse the command line.
seqan::ArgumentParser parser;
RoiIntersectOptions options;
seqan::ArgumentParser::ParseResult res = parseCommandLine(options, argc, argv);
// If there was an error parsing or built-in argument parser functionality
// was triggered then we exit the program. The return code is 1 if there
// were errors and 0 if there were none.
if (res != seqan::ArgumentParser::PARSE_OK)
return res == seqan::ArgumentParser::PARSE_ERROR;
RoiIntersectApp app(options);
return app.run();
}
| [
"holtgrew@e6417c60-b987-48fd-844e-b20f0fcc1017"
] | holtgrew@e6417c60-b987-48fd-844e-b20f0fcc1017 |
a1bb65dbbb43c640ddea4080c937b14871145b2a | 56b87dd6e4e2f9142a55c637cda8eb5ea357805f | /src/triggers/SingleTkTauEta.cpp | 553781542e992743dfb11176e1107b56507019c8 | [] | no_license | nsahoo/MenuGeneration | acdaafaa6caf2cdfea85e22f98ac549bffeac5ff | 8859b21722196b8415421f7fcb0ce042379493b2 | refs/heads/master | 2020-06-10T18:10:51.968536 | 2014-08-11T16:21:13 | 2014-08-11T16:21:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,007 | cpp | #include "SingleTkTauEta.h"
#include <stdexcept>
#include "../implementation/RegisterTriggerMacro.h"
#include "l1menu/L1TriggerDPGEvent.h"
#include "UserCode/L1TriggerUpgrade/interface/L1AnalysisDataFormat.h"
namespace l1menu
{
namespace triggers
{
/* The REGISTER_TRIGGER macro will make sure that the given trigger is registered in the
* l1menu::TriggerTable when the program starts. I also want to provide some suggested binning
* however. The REGISTER_TRIGGER_AND_CUSTOMISE macro does exactly the same but lets me pass
* a pointer to a function that will be called directly after the trigger has been registered
* at program startup. The function takes no parameters and returns void. In this case I'm
* giving it a lambda function.
*/
REGISTER_TRIGGER_AND_CUSTOMISE( SingleTkTauEta_v0,
[]() // Use a lambda function to customise rather than creating a named function that never gets used again.
{
l1menu::TriggerTable& triggerTable=l1menu::TriggerTable::instance();
SingleTkTauEta_v0 tempTriggerInstance;
triggerTable.registerSuggestedBinning( tempTriggerInstance.name(), "threshold1", 200, 0, 200 );
} // End of customisation lambda function
) // End of REGISTER_TRIGGER_AND_CUSTOMISE macro call
} // end of namespace triggers
} // end of namespace l1menu
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
//--------------- Definitions below ---------------------------------------------
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
bool l1menu::triggers::SingleTkTauEta_v0::apply( const l1menu::L1TriggerDPGEvent& event ) const
{
const L1Analysis::L1AnalysisDataFormat& analysisDataFormat=event.rawEvent();
const bool* PhysicsBits=event.physicsBits();
bool raw = PhysicsBits[0]; // ZeroBias
if (! raw) return false;
int n1=0;
int Nt = analysisDataFormat.NTktau ;
for (int ue=0; ue < Nt; ue++) {
int bx = analysisDataFormat.BxTktau[ue];
if (bx != 0) continue;
float rank = analysisDataFormat.EtTktau[ue]; // the rank of the electron
float pt = rank; //CorrectedL1JetPtByGCTregions(analysisDataFormat.Etajet[ue],rank*4.,theL1JetCorrection);
float eta = analysisDataFormat.EtaTktau[ue];
if (eta < regionCut_ || eta > 21.-regionCut_) continue; // eta = 5 - 16 // eta = 5 - 16
if (pt >= threshold1_) n1++;
} // end loop over jets
bool ok = ( n1 >=1 );
return ok;
}
bool l1menu::triggers::SingleTkTauEta_v0::thresholdsAreCorrelated() const
{
return false;
}
unsigned int l1menu::triggers::SingleTkTauEta_v0::version() const
{
return 0;
}
l1menu::triggers::SingleTkTauEta::SingleTkTauEta()
: threshold1_(20), regionCut_(4.5)
{
// No operation other than the initialiser list
}
const std::string l1menu::triggers::SingleTkTauEta::name() const
{
return "L1_SingleTkTau";
}
const std::vector<std::string> l1menu::triggers::SingleTkTauEta::parameterNames() const
{
std::vector<std::string> returnValue;
returnValue.push_back("threshold1");
returnValue.push_back("regionCut");
return returnValue;
}
float& l1menu::triggers::SingleTkTauEta::parameter( const std::string& parameterName )
{
if( parameterName=="threshold1" ) return threshold1_;
else if( parameterName=="regionCut" ) return regionCut_;
else throw std::logic_error( "Not a valid parameter name" );
}
const float& l1menu::triggers::SingleTkTauEta::parameter( const std::string& parameterName ) const
{
if( parameterName=="threshold1" ) return threshold1_;
else if( parameterName=="regionCut" ) return regionCut_;
else throw std::logic_error( "Not a valid parameter name" );
}
| [
"brianwiner@gmail.com"
] | brianwiner@gmail.com |
4c2f78f8922507ee6940ced6ae6fde88013b607a | 39e38c0be28ce52f8e42d8329efcfcbbe5b24e84 | /ETMX05/2.cpp | b41c8a2cc5554f01cf48093ffdb99a28c8bc0994 | [] | no_license | shailesh1001/CODECHEF | bba2460f3a8ee2f61537fd67c1ed6add22a8e135 | 450a54d3513987691f96c2935b74362a119ab1f9 | refs/heads/master | 2021-01-17T20:51:28.200912 | 2014-11-18T16:04:04 | 2014-11-18T16:04:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 399 | cpp | //Author : pakhandi
//
using namespace std;
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<cstring>
#define wl while
#define fl(i,a,b) for(i=a; i<b; i++)
int main()
{
char str[10000];
scanf("%s", str);
int len=strlen(str);
if(len<3)
printf("0");
else
{
printf("%c%c%c",str[(len/2)-1], str[len/2], str[(len/2)+1]);
}
return 0;
} | [
"asimkprasad@gmail.com"
] | asimkprasad@gmail.com |
46cfbf1f85d0b8daed4b478d478e1f109896538a | 30799ddd251fb15c347c0441aa881dadaa1d4918 | /Hackerrank/NewYearChaos.cpp | bcfc62b20b686312166dbe2491a14ad7fb55e8a7 | [] | no_license | AsutoshPadhi/Competitve-Programming | e7d696653b2df52f2cd91c3d3acb5d3047d42f1e | b77d07b8cb7b4c3d59e76e50912da48c086ec324 | refs/heads/master | 2020-06-11T22:56:52.672432 | 2020-04-22T03:21:50 | 2020-04-22T03:21:50 | 194,113,986 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 822 | cpp | #include <iostream>
using namespace std;
int main()
{
int t;
cin>>t;
while(t-->0)
{
int n;
cin>>n;
int arr[n];
for(int i=0; i<n; i++)
{
cin>>arr[i];
}
int cnt=0, flag=1;
for(int i=0; i<n; i++)
{
if(arr[i]-(i+1)>2)
{
cout<<"Too chaotic\n";
flag=0;
break;
}
int diff;
if(arr[i]>(i+1))
{
diff = arr[i]-(i+1);
cnt += diff;
// i += diff;
}
else if(arr[i]<(i+1) && (i+1)-arr[i]>2)
{
cnt++;
}
}
if(flag==1)
{
cout<<cnt<<"\n";
}
}
return 0;
} | [
"2015asutosh.padhi@ves.ac.in"
] | 2015asutosh.padhi@ves.ac.in |
5eb8ed1f2258aa3d703110197fc2857b613c1e6f | 6a6193dc6dc8a49cf92846d8011c1f37c7c1fb48 | /tools/halide_malloc_trace.h | 0018e555656cf3d7af9bab7ef3d3950659d8cb32 | [
"MIT"
] | permissive | StanfordAHA/Halide-to-Hardware | ac10c68fea5a295a8556284bec67dbd1ab8feffc | 135c5da2587e6f6b17b2e9352a456a645367ad4e | refs/heads/master | 2023-08-31T07:00:40.869746 | 2021-10-20T19:16:51 | 2021-10-20T19:17:08 | 167,240,813 | 76 | 14 | NOASSERTION | 2023-09-06T00:09:25 | 2019-01-23T19:25:20 | C++ | UTF-8 | C++ | false | false | 3,358 | h | #ifndef HALIDE_MALLOC_TRACE_H
#define HALIDE_MALLOC_TRACE_H
//---------------------------------------------------------------------------
// The custom trace allocator can be used in an application by calling:
//
// halide_enable_malloc_trace();
//
// When the app is run, calls to halide_malloc/free will produce output like:
//
// halide_malloc => [0x9e400, 0xa27ff], # size:17408, align:1K
// halide-header => [0x9e390, 0x9e3ff], # size:112, align:16
// halide_malloc => [0xa2880, 0xa6e9f], # size:17952, align:128
// halide-header => [0xa2820, 0xa287f], # size:96, align:32
// halide_free => [0x9e390, 0x9e3ff], # size:112, align:16
// halide_free => [0xa2820, 0xa287f], # size:96, align:32
//
//---------------------------------------------------------------------------
#include <cstdlib>
#include <memory>
#include <iostream>
namespace Halide {
namespace Tools {
static inline void print_meminfoalign(intptr_t val) {
intptr_t align_chk = 1024*1024;
while (align_chk > 0) {
if ((val & (align_chk-1)) == 0) {
char aunit = ' ';
if (align_chk >= 1024) {
align_chk >>= 10;
aunit = 'K';
}
if (align_chk >= 1024) {
align_chk >>= 10;
aunit = 'M';
}
std::cout << "align:" << align_chk;
if (aunit != ' ') {
std::cout << aunit;
}
break;
}
align_chk >>= 1;
}
}
void *halide_malloc_trace(void *user_context, size_t x) {
// Halide requires halide_malloc to allocate memory that can be
// read 8 bytes before the start to store the original pointer.
// Additionally, we also need to align it to the natural vector
// width.
void *orig = malloc(x+128);
if (orig == NULL) {
// Will result in a failed assertion and a call to halide_error
return NULL;
}
// Round up to next multiple of 128.
void *ptr = (void *)((((size_t)orig + 128) >> 7) << 7);
((void **)ptr)[-1] = orig;
void *headend = (orig == ptr) ? orig : (char *)ptr - 1;
std::cout << "halide_malloc => [0x" << std::hex
<< (intptr_t)ptr << ", 0x"
<< (intptr_t)ptr + x-1 << std::dec
<< "], # size:"
<< (intptr_t)x << ", ";
print_meminfoalign((intptr_t)ptr);
std::cout << std::endl;
std::cout << "halide-header => [0x" << std::hex
<< (intptr_t)orig << ", 0x"
<< (intptr_t)headend << std::dec
<< "], # size:"
<< (intptr_t)ptr - (intptr_t)orig << ", ";
print_meminfoalign((intptr_t)orig);
std::cout << std::endl;
return ptr;
}
void halide_free_trace(void *user_context, void *ptr) {
std::cout << "halide_free => [0x" << std::hex
<< (intptr_t)((void**)ptr)[-1] << ", 0x"
<< (intptr_t)ptr - 1 << std::dec
<< "], # size:"
<< (intptr_t)ptr - (intptr_t)((void**)ptr)[-1] << ", ";
print_meminfoalign((intptr_t)((void**)ptr)[-1]);
std::cout << std::endl;
free(((void**)ptr)[-1]);
}
void halide_enable_malloc_trace(void) {
halide_set_custom_malloc(halide_malloc_trace);
halide_set_custom_free(halide_free_trace);
}
} // namespace Tools
} // namespace Halide
#endif // HALIDE_MALLOC_TRACE_H
| [
"dpalermo@codeaurora.org"
] | dpalermo@codeaurora.org |
b2cbbdf0506e4e0f2d6e6a3349ebf196f32a69d3 | bd7493522a7f2283408774c55107a04c5906252d | /Menu.cpp | 0b5af08022c777230f3d24bc765a79782bb06493 | [
"MIT"
] | permissive | a-recknagel/dodgson | ea5f43cc66a05d334fe80b1ae2238ddd3ba84ea0 | 81027ec83e0b2b0cf2f001d0980db2a57fca7220 | refs/heads/main | 2023-02-26T11:36:36.762838 | 2021-02-07T21:22:36 | 2021-02-07T21:22:36 | 336,889,033 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,518 | cpp | #include "Menu.h"
#include <iostream>
#include <fstream>
#include <ctime>
#include <cmath>
#include <future>
#include <algorithm>
#include "Baseline.h"
#include "DepthFirstSearch.h"
#include "UniformCostSearch.h"
#include "SmartCache.h"
#include "IterativeDFS.h"
#include "Logger.h"
using namespace std;
long g_countBefore;
long g_countAfter;
Menu::Menu(Util::preferenceProfile &prefProf) {
m_continue = true;
m_heuristic = BASELINE;
m_pp = &prefProf;
m_verbose = true;
m_threaded = false;
m_scorers = vector<DodgsonScorer*>();
m_scorers.push_back(new Baseline(*m_pp));
m_scorers.push_back(new DepthFirstSearch(*m_pp));
m_scorers.push_back(new UniformCostSearch(*m_pp));
m_scorers.push_back(new SmartCache(*m_pp));
m_scorers.push_back(new IterativeDFS(*m_pp));
/* Add a new scorer here */
//m_scorers.push_back(new SCORER(*m_pp));
}
Menu::Menu() {
m_continue = false;
m_heuristic = BASELINE;
m_pp = nullptr;
m_verbose = true;
m_threaded = false;
m_scorers = vector<DodgsonScorer*>();
cout << "Menu needs a preference profile!" << endl;
}
Menu::Menu(string fileName) {
m_continue = false;
m_heuristic = BASELINE;
m_scorers = vector<DodgsonScorer*>();
load(fileName);
m_pp = &(m_scorers[0]->getPP());
m_verbose = true;
m_threaded = false;
m_continue = true;
}
void Menu::mainMenu() {
while(m_continue) {
cout << "Main Menu" << endl;
cout << "Choose options:" << endl
<< "[1]: Save profile" << endl
<< "[2]: Load profile" << endl
<< "[3]: Scramble profile" << endl
<< "[4]: Create new profile" << endl
<< "[5]: Peek at profile" << endl
<< "[6]: Toggle verbose mode" << endl
<< "[7]: Benchmark with max duration" << endl
<< "[8]: Run evaluation menu" << endl
<< "[9]: Close program" << endl << endl;
string input;
getline(cin, input);
switch(input[0]) {
case '1': save(); mainMenu(); break;
case '2': load(); mainMenu(); break;
case '3': scramble(); mainMenu(); break;
case '4': newPrefProf(); mainMenu(); break;
case '5': peek(); mainMenu(); break;
case '6': toggleVerbose(); mainMenu(); break;
case '7': testAll(); mainMenu(); break;
case '8': evalMenu(); break;
case '9': m_continue = false; break;
default:
cout << "Character not recognized." << endl;
mainMenu();
}
cin.clear();
}
}
void Menu::toggleVerbose() {
m_verbose = !m_verbose;
cout << "Verbose is now turned " << (m_verbose ? "on" : "off") << endl;
}
void Menu::save() {
int nextIdx;
ifstream iFile;
for(nextIdx=0; nextIdx<100; nextIdx++) {
iFile.open("Data/prefProf_"+to_string(static_cast<long long>(nextIdx))+".txt");
if(!iFile) break;
}
if(nextIdx < 100) {
for(unsigned int i=0; i<m_scorers.size(); i++) {
string fileName = "Data/prefProf_"+to_string(static_cast<long long>(nextIdx+i))+".txt";
m_scorers[i]->writePP(fileName);
cout << "Successfully saved file as " << fileName << endl;
}
}else{
cout << "Error: Total number of saved profiles is greater than 100."
<< " You might want to consider deleting some." << endl;
}
}
void Menu::load(string fileName) {
ifstream iFile(fileName);
if(iFile) {
cleanUp();
m_scorers[0] = new Baseline(fileName);
m_scorers[1] = new DepthFirstSearch(fileName);
m_scorers[2] = new UniformCostSearch(fileName);
m_scorers[3] = new SmartCache(fileName);
m_scorers[4] = new IterativeDFS(fileName);
/* Insert option to load new scorer here */
//m_scorers[5] = new NewScorer(fileName);
m_pp = &(m_scorers[0]->getPP());
cout << "Successfully loaded profile from " << fileName << endl;
}else{
cout << "Error: There is no file called: " << fileName << endl;
}
}
void Menu::load() {
cout << "Please enter the number of the file you wish to load: ";
string fileName;
getline(cin, fileName);
cout << endl;
fileName = "Data/prefProf_" + fileName + ".txt";
load(fileName);
}
void Menu::newPrefProf() {
cleanUp();
int n, m;
cout << "Specify the amount of agents in the new preference profile: ";
string input;
getline(cin, input);
n = stoi(input);
cout << "\nSpecify the amount of alternatives in the new preference profile: ";
getline(cin, input);
m = stoi(input);
m_pp = new Util::preferenceProfile(n, m);
cout << "\nSuccessfully build a new preference profile with with dimensions " << n << "x" << m << endl;
Util::scramble(*m_pp);
m_continue = true;
m_heuristic = BASELINE;
m_scorers = vector<DodgsonScorer*>();
m_scorers.push_back(new Baseline(*m_pp));
m_scorers.push_back(new DepthFirstSearch(*m_pp));
m_scorers.push_back(new UniformCostSearch(*m_pp));
m_scorers.push_back(new SmartCache(*m_pp));
m_scorers.push_back(new IterativeDFS(*m_pp));
/* Insert new scorer for flexible generation here */
//m_scorers.push_back(new NewScorer(*m_pp));
}
void Menu::scramble() {
Util::scramble(*m_pp);
cout << "Succsefully scrambled!" << endl;
}
void Menu::peek() {
Util::printPP(*m_pp);
}
void Menu::evalMenu() {
cout << "Entering evaluation mode." << endl;
cout << "Choose options:" << endl
<< "[1]: Chose heuristic" << endl
<< "[2]: Enter menu for normal solving algorithms" << endl
<< "[3]: Enter menu for threaded solving algorithms" << endl
<< "[4]: Test all solvers" << endl
<< "[5]: Examine distribution" << endl
<< "[6]: Return to main menu" << endl << endl;
string input;
getline(cin, input);
switch(input[0]) {
case '1': chooseHeuristics(); evalMenu(); break;
case '2': normalSolve(); break;
case '3': threadedSolve(); break;
case '4': test(); evalMenu(); break;
case '5': analyzeDistribution(); evalMenu(); break;
case '6': mainMenu(); break;
default:
cout << "Character not recognized." << endl;
evalMenu();
}
}
void Menu::normalSolve(){
m_threaded = false;
cout << "Entering normal solve mode." << endl;
cout << "Choose options:" << endl
<< "[1]: Show condorcet winner" << endl
<< "[2]: Run eval for current profile" << endl
<< "[3]: Randomized benchmarking" << endl
<< "[4]: Randomized benchmarking for all scorers" << endl
<< "[5]: Return to eval menu" << endl << endl;
string input;
getline(cin, input);
switch(input[0]) {
case '1': getCW(); normalSolve(); break;
case '2': runEval(); normalSolve(); break;
case '3': repeatRandEval(); normalSolve(); break;
case '4': allRepeatRandEval(); normalSolve(); break;
case '5': evalMenu(); break;
default:
cout << "Character not recognized." << endl;
normalSolve();
}
}
void Menu::threadedSolve(){
m_threaded = true;
cout << "Entering threaded solve mode." << endl;
cout << "Choose options:" << endl
<< "[1]: Run eval for current profile" << endl
<< "[2]: Randomized benchmarking" << endl
<< "[3]: Randomized benchmarking for all scorers" << endl
<< "[4]: Return to eval menu" << endl << endl;
string input;
getline(cin, input);
switch(input[0]) {
case '1': runEval(); threadedSolve(); break;
case '2': repeatRandEval(); threadedSolve(); break;
case '3': allRepeatRandEval(); threadedSolve(); break;
case '4': evalMenu(); break;
default:
cout << "Character not recognized." << endl;
threadedSolve();
}
}
void Menu::runEval() {
cout << "Computing scores for scorer number " << m_heuristic+1 << " ..." << endl;
clock_t t = clock();
vector<pair<int, int> > solution;
if(m_threaded)
solution = m_scorers[m_heuristic]->getFastSCD(NUM_THREADS);
else
m_scorers[m_heuristic]->getSCD();
t = clock() - t;
cout << "\nTotal duration: " << t << " clock-ticks, or " << ((float)t)/CLOCKS_PER_SEC << " seconds" << endl;
cout << "Results:" << endl;
if(m_threaded) {
cout << "Winner(s):\n";
for(pair<int, int> p : solution) {
cout << "Alternative " << p.first << " with a dodgson score of " << p.second << ".\n";
}
} else
m_scorers[m_heuristic]->print();
cout << endl << "------------------------------------------------" << endl << endl;
}
void Menu::repeatRandEval() {
string input;
cout << "Amount of runs: ";
getline(cin, input);
cout << "Agents: " << m_pp->n << ", Alternatives: " << m_pp->m << endl;
int numRuns = stoi(input);
int seed = (int)time(0);
randEval(numRuns, seed);
}
void Menu::allRepeatRandEval() {
Heuristic initialState = m_heuristic;
string input;
cout << "Amount of runs: ";
getline(cin, input);
cout << "Agents: " << m_pp->n << ", Alternatives: " << m_pp->m << endl;
int numRuns = stoi(input);
int seed = (int)time(0);
for(unsigned int i=0; i<m_scorers.size(); i++) {
m_heuristic = Heuristic(i);
randEval(numRuns, seed);
}
m_heuristic = initialState;
}
void Menu::randEval(int num, int seed) {
int numRuns = num;
vector<clock_t> benchmark;
int min, max, median;
float mean = 0, var = 0, count = 0, sDeviat;
if (m_verbose) cout << "\nResult in clock-ticks:\n+---------------" << endl;
for(int i=0; i<numRuns; i++) {
clock_t t = clock();
if(m_threaded)
m_scorers[m_heuristic]->getFastSCD(NUM_THREADS);
else
m_scorers[m_heuristic]->getSCD();
benchmark.push_back(clock() - t);
Util::scramble(*m_pp, seed++);
mean += benchmark[i];
count += m_scorers[m_heuristic]->getCount();
if(m_verbose) cout << "| " << benchmark[i] << endl;
}
sort(benchmark.begin(), benchmark.end());
min = benchmark.front();
max = benchmark.back();
median = benchmark[benchmark.size()/2];
mean /= numRuns;
count /= numRuns;
for(unsigned int i=0; i<benchmark.size(); i++) {
var += ((((float)benchmark[i]) - mean) * (((float)benchmark[i]) - mean));
}
var /= numRuns;
sDeviat = sqrt(var);
cout << "+---------------\nMean: " << mean << ", Variance: " << (int)var << ", Standard deviation: " << (int)sDeviat << endl;
cout << "Median: " << median << ", Min: " << min << ", Max: " << max << endl;
cout << "Average number of instances checked: " << count << endl;
cout << "Clocks per second on this system: " << CLOCKS_PER_SEC << endl << endl;
}
void Menu::test() {
string input;
cout << "Amount of runs: ";
getline(cin, input);
int numRuns = stoi(input);
int seed = (int)time(0), errors = 0;
vector<Util::preferenceProfile> profiles;
m_threaded = true;
cout << "Now running threaded algorithms . . .\n";
for(int i=0; i<numRuns; i++) {
if(m_verbose) cout << "\nRun number " << i+1 << "/" << numRuns << "\n****************************************\n";
vector<pair<int, int> > currentScores, lastScores;
int lastSeed = 0;
Util::scramble(*m_pp, seed++);
for(unsigned int j=0; j<m_scorers.size(); j++) {
if(m_verbose) cout << "Running scorer " << j+1 << endl;
currentScores = m_scorers[j]->getFastSCD(NUM_THREADS);
for(unsigned int k=0; k<lastScores.size(); k++) {
if((lastScores[k].first != currentScores[k].first) || (lastScores[k].second != currentScores[k].second)) {
errors++;
if(m_verbose) cout << "\nDiscrepancy for scorers " << j << " and " << j+1 << endl;
if(seed != lastSeed && (seed+1) != lastSeed) {
lastSeed = seed;
Util::preferenceProfile clone;
Util::clonePP(*m_pp, clone);
profiles.push_back(clone);
}
}
}
if(m_verbose) {
cout << "Finished with winner(s):" << endl;
for(pair<int, int> p : currentScores) {
cout << "Alternative " << p.first << " with a dodgson score of " << p.second << ".\n";
}
}
lastScores = vector<pair<int, int> >(currentScores);
}
}
m_threaded = false;
cout << "Now running normal algorithms . . .\n";
for(int i=0; i<numRuns; i++) {
if(m_verbose) cout << "\nRun number " << i+1 << "/" << numRuns << "\n****************************************\n";
vector<int> currentScores, lastScores;
int lastSeed = 0;
Util::scramble(*m_pp, seed++);
for(unsigned int j=0; j<m_scorers.size(); j++) {
if(m_verbose) cout << "Running scorer " << j+1 << endl;
m_scorers[j]->getSCD();
currentScores = vector<int>(m_scorers[j]->getScores());
for(unsigned int k=0; k<lastScores.size(); k++) {
if(currentScores[k] != lastScores[k]) {
errors++;
if(m_verbose) cout << "\nDiscrepancy for scorers " << j << " and " << j+1 << endl;
if(seed != lastSeed && (seed+1) != lastSeed) {
lastSeed = seed;
Util::preferenceProfile clone;
Util::clonePP(*m_pp, clone);
profiles.push_back(clone);
}
}
}
lastScores = vector<int>(currentScores);
if(m_verbose) cout << "Finished" << endl;
}
}
cout << "A total of " << errors << " discrepancies occured in ";
cout << (errors == 0 ? 0 : profiles.size()+1 ) << " of the " << numRuns << " runs\n";
if(m_verbose) for(Util::preferenceProfile profile : profiles) Util::printPP(profile);
}
void Menu::getCW() {
cout << "Condorcet winner: " << m_scorers[m_heuristic]->getCW() << endl;
}
void Menu::chooseHeuristics() {
/* Insert option to choose the new scorer here */
cout << "Choose heuristic (only first character is read):" << endl
<< "[1]: Baseline" << endl
<< "[2]: DFS" << endl
<< "[3]: UCS" << endl
<< "[4]: Smart Cache" << endl
<< "[5]: Iterative DFS" << endl << endl;
//<< "[6]: New Scorer?" << endl << endl;
string input;
getline(cin, input);
switch(input[0]) {
case '1': m_heuristic = BASELINE; break;
case '2': m_heuristic = DFS; break;
case '3': m_heuristic = UCS; break;
case '4': m_heuristic = SMARTCACHE; break;
case '5': m_heuristic = ICRDFS; break;
//case '6': m_heuristic = NEWSCORER; break;
default:
cout << "Character not recognized." << endl;
}
}
void Menu::fillBuckets(vector<int> &curve, int sum, int current, int n, int scD) {
if(current != n) {
for(int i=0; i<=current; i++) {
fillBuckets(curve, sum+i, current+1, n, scD);
}
} else {
// when current == n is reached, one permutation is finished,
// and its repective bucket can be incremented
curve[sum]++;
if(sum <= scD) g_countBefore++;
else g_countAfter++;
}
}
void Menu::analyzeDistribution() {
string input;
cout << "Profile dimension: ";
getline(cin, input);
int n = stoi(input);
// the maximum number of possible swaps is pre-determinable as follows:
// if the dimension of profile is n x n, then the maximum number of possible
// swaps is = sum (1 .. n) + 1 (+1 for the 'no swap at all' container)
int vecSize = 1, scD = 0;
for(int i=0; i<n; i++) vecSize += i;
for(int i=1; i<=n/2; i++) scD += i;
vector<int> curve(vecSize, 0);
g_countAfter = 0;
g_countBefore = 0;
fillBuckets(curve, 0, 0, n, scD);
// curve filled with values, now print
int biggest = 0;
for(unsigned int i=0; i<curve.size(); i++) {
if(curve[i] > biggest) biggest = curve[i];
}
cout << "\nDistribution for n=m=" << n << endl;
cout << "Number of profiles before minimal scd: " << g_countBefore << endl;
cout << "Number of profiles after minimal scd: " << g_countAfter << endl;
cout << "Total count: " << g_countBefore+g_countAfter << endl;
cout << "Percentage saved: " << ((double)g_countAfter)/(((double)g_countBefore)+((double)g_countAfter))*100 << "%" << endl;
cout << "\nMinimal scD indicated by arrow" << endl;
for(unsigned int i=0; i<curve.size(); i++) {
cout << "[" << i << "]: ";
int max = ((int)(65 * (((float)curve[i]) / ((float)biggest))));
for(int j=0; j<max; j++) {
cout << "|";
}
if(i == scD) cout << " <-- ";
cout << endl;
}
cout << endl;
}
void Menu::testAll() {
string input;
cout << "Maximum wait-time in seconds: ";
getline(cin, input);
int waitTime = stoi(input);
chrono::milliseconds checkIntervall = chrono::milliseconds(100); // something small. Must be less than waittime
cout << endl;
ofstream out("log.txt", ofstream::app);
time_t t = time(0);
struct tm * now = localtime( & t );
out << "\n\n\n******Starting benchmark at "
<< (now->tm_year + 1900) << '-'
<< (now->tm_mon + 1) << '-'
<< now->tm_mday
<< " with threshold " << input << " seconds******" << endl;
for(int counter = 0; counter < 100; counter++) {
out << endl << endl << "Run number " << counter << ", starting with normal runs" << endl;
// for normal solving:
for(unsigned int i=0; i<m_scorers.size(); i++) {
out << "scorer: " << i << endl << endl;
float sumAvg = 0;
int j;
for(j=3; j<100; j++) {
int k;
vector<float> times;
for(k=3; k<1000; k++) {
// create new profile
m_pp->alter(j, k);
Util::scramble(*m_pp);
m_scorers[i]->update();
// start test
clock_t t = clock();
if(m_verbose) cout << "starting thread\n";
bool timeUp = false;
m_scorers[i]->setAbortState(false);
auto future = async(launch::async, static_cast<void (DodgsonScorer::*)(void)>(&DodgsonScorer::getSCD), m_scorers[i]);
// check if finished or time up
while(future.wait_for(checkIntervall) != std::future_status::ready && !timeUp) {
timeUp = (((float)(clock() - t))/CLOCKS_PER_SEC) > waitTime;
if(timeUp){
if(m_verbose) cout << "Time is up, aborting .. " << endl;
m_scorers[i]->setAbortState(true);
}
if(m_verbose) cout << "current: " << (((float)(clock() - t))/CLOCKS_PER_SEC) << ", max: " << waitTime << endl;
}
future.get();
if(m_verbose) cout << "thread ended\n";
// success:
if(!timeUp) {
times.push_back(((float)(clock() - t))/CLOCKS_PER_SEC);
if(m_verbose) cout << "Scorer " << i << " solved a " << m_pp->n << "x" << m_pp->m << " profile in " << times.back() << " seconds.\n\n";
}
// fail:
else {
if(times.size() != 0) {
cout << "Scorer " << i << " failed at a " << m_pp->n << "x" << m_pp->m << " profile after " << times.back() << " seconds.\n\n";
// the wonders of lambda
sort(times.begin(), times.end(), [](float a, float b) { return a < b; });
float sum = 0;
for(float f : times) {sum += f; cout << f << endl;}
out << m_pp->n << "/" << m_pp->m
<< " min: " << times.front()
<< " median: " << times[times.size()/2]
<< " max: " << times.back()
<< " avg: " << sum/times.size() << endl;
sumAvg += sum/times.size();
} else cout << "Scorer " << i << "immediate fail at " << m_pp->n << "x" << m_pp->m << endl;
break;
}
}
// stop condition, maybe just restrict max value if too slow
if(k<=4) {
cout << "Stop testing for n = " << j << endl << endl;
break;
}
}
out << "Total average: " << sumAvg/j << endl << endl;
}
cout << "finished normal runs, now testing for threaded variants\n\n\n";
// for threaded solving:
for(unsigned int i=0; i<m_scorers.size(); i++) {
if(m_scorers[i]->threadable()) {
out << "scorer: " << i << endl << endl;
float sumAvg = 0;
int j;
for(j=3; j<100; j++) {
int k;
vector<float> times;
for(k=3; k<1000; k++) {
// create new profile
m_pp->alter(j, k);
Util::scramble(*m_pp);
m_scorers[i]->update();
// start test
clock_t t = clock();
if(m_verbose) cout << "starting thread\n";
bool timeUp = false;
m_scorers[i]->setAbortState(false);
auto future = async(launch::async, &DodgsonScorer::getFastSCD, m_scorers[i], NUM_THREADS);
// check if finished or time up
while(future.wait_for(checkIntervall) != std::future_status::ready && !timeUp) {
timeUp = (((float)(clock() - t))/CLOCKS_PER_SEC) > waitTime;
if(timeUp){
if(m_verbose) cout << "Time is up, aborting .. " << endl;
m_scorers[i]->setAbortState(true);
}
if(m_verbose) cout << "current: " << (((float)(clock() - t))/CLOCKS_PER_SEC) << ", max: " << waitTime << endl;
}
future.get();
if(m_verbose) cout << "thread ended\n";
// success:
if(!timeUp) {
times.push_back(((float)(clock() - t))/CLOCKS_PER_SEC);
if(m_verbose) cout << "Scorer " << i << " solved a " << m_pp->n << "x" << m_pp->m << " profile in " << times.back() << " seconds.\n\n";
}
// fail:
else {
if(times.size() != 0) {
cout << "Scorer " << i << " failed at a " << m_pp->n << "x" << m_pp->m << " profile after " << times.back() << " seconds.\n\n";
// the wonders of lambda
sort(times.begin(), times.end(), [](float a, float b) { return a < b; });
float sum = 0;
for(float f : times) {sum += f; cout << f << endl;}
out << m_pp->n << "/" << m_pp->m
<< " min: " << times.front()
<< " median: " << times[times.size()/2]
<< " max: " << times.back()
<< " avg: " << sum/times.size() << endl;
sumAvg += sum/times.size();
} else cout << "Scorer " << i << "immediate fail at " << m_pp->n << "x" << m_pp->m << endl;
break;
}
}
// stop condition, maybe just restrict max value if too slow
if(k<=4) {
cout << "Stop testing for n = " << j << endl << endl;
break;
}
}
out << "Total average: " << sumAvg/j << endl << endl;
}
}
cout << "finished threaded runs, starting next run\n\n\n";
}
out.close();
}
//void Menu::threadEval() {
// cout << "Computing scores for scorer number " << m_heuristic << " ..." << endl;
//
// clock_t t = clock();
// pair<int, int> solution = m_scorers[m_heuristic]->getFastSCD(NUM_THREADS);
// t = clock() - t;
//
// cout << "\nTotal duration: " << t << " clock-ticks, or " << ((float)t)/CLOCKS_PER_SEC << " seconds" << endl;
// cout << "Results: " << endl;
// cout << "Alternative " << solution.second << " wins with a dodgson score of " << solution.first << ".\n";
// cout << endl << "------------------------------------------------" << endl << endl;
//}
//void Menu::repeatEval() {
// string input;
// cout << "Amount of runs: ";
// getline(cin, input);
// int numRuns = stoi(input), sum = 0, min = INT_MAX, max = 0;
// vector<clock_t> benchmark;
//
// cout << "\nResult in clock-ticks:\n+---------------" << endl;
// for(int i=0; i<numRuns; i++) {
// clock_t t = clock();
// m_scorers[m_heuristic]->getSCD();
// min = min > (clock() - t) ? (clock() - t) : min;
// max = max < (clock() - t) ? (clock() - t) : max;
// benchmark.push_back(clock() - t);
// sum += benchmark[i];
// cout << "| " << benchmark[i] << endl;
// }
// cout << "+---------------\nAverage number of ticks: " << ((float)sum)/((float)numRuns) << endl << endl;
// cout << "min: " << min << ", max:" << max << endl;
// cout << "Clocks per second on this system: " << CLOCKS_PER_SEC << endl;
//}
void Menu::cleanUp() {
// TODO: clean up scorers and anything
// else that comes to mind. Not really
// that much though, as the only object
// on the heap is the profile, which
// gets recycled for every scramble,
// alteration or new loading.
} | [
"arecknag@gmail.com"
] | arecknag@gmail.com |
be2aa86975fac67b39b8b4db21747864a4295fb4 | 15e95a7a599753c152de95c45531daba882e6fe2 | /src/core/script/script_num.h | 5ccbae9671c7477b5b843578baa6578765472106 | [
"MIT"
] | permissive | herculas/StdChain | 13d7cff418545612d1ed85d3dc345ced019d23c3 | 4001f9c62bf9e70ea23a84e54bef4a01ab10f913 | refs/heads/main | 2023-09-01T05:25:09.073922 | 2021-03-31T07:40:52 | 2021-03-31T07:40:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,744 | h | #ifndef STDCHAIN_CORE_SCRIPT_NUM_H
#define STDCHAIN_CORE_SCRIPT_NUM_H
#include <cstdint>
#include <cstdlib>
#include <vector>
class ScriptNum {
private:
static const size_t DEFAULT_MAX_NUM_SIZE = 4;
int64_t value;
public:
explicit ScriptNum(const int64_t &n);
ScriptNum(const std::vector<unsigned char> &vch, bool requiredMinimal, size_t maxNumSize = DEFAULT_MAX_NUM_SIZE);
[[nodiscard]] int32_t getInt() const;
[[nodiscard]] std::vector<unsigned char> getVch() const;
static std::vector<unsigned char> serialize(const int64_t &value);
private:
static int64_t setVch(const std::vector<unsigned char> &vch);
public:
inline bool operator==(const int64_t &rhs) const { return this->value == rhs; }
inline bool operator!=(const int64_t &rhs) const { return this->value != rhs; }
inline bool operator<=(const int64_t &rhs) const { return this->value <= rhs; }
inline bool operator>=(const int64_t &rhs) const { return this->value >= rhs; }
inline bool operator<(const int64_t &rhs) const { return this->value < rhs; }
inline bool operator>(const int64_t &rhs) const { return this->value > rhs; }
inline bool operator==(const ScriptNum &rhs) const { return operator==(rhs.value); }
inline bool operator!=(const ScriptNum &rhs) const { return operator!=(rhs.value); }
inline bool operator<=(const ScriptNum &rhs) const { return operator<=(rhs.value); }
inline bool operator>=(const ScriptNum &rhs) const { return operator>=(rhs.value); }
inline bool operator<(const ScriptNum &rhs) const { return operator<(rhs.value); }
inline bool operator>(const ScriptNum &rhs) const { return operator>(rhs.value); }
inline ScriptNum operator+(const int64_t &rhs) const { return ScriptNum(this->value + rhs); }
inline ScriptNum operator-(const int64_t &rhs) const { return ScriptNum(this->value - rhs); }
inline ScriptNum operator&(const int64_t &rhs) const { return ScriptNum(this->value & rhs); }
inline ScriptNum operator+(const ScriptNum &rhs) const { return operator+(rhs.value); }
inline ScriptNum operator-(const ScriptNum &rhs) const { return operator-(rhs.value); }
inline ScriptNum operator&(const ScriptNum &rhs) const { return operator&(rhs.value); }
inline ScriptNum &operator+=(const ScriptNum &rhs) { return operator+=(rhs.value); }
inline ScriptNum &operator-=(const ScriptNum &rhs) { return operator-=(rhs.value); }
inline ScriptNum &operator&=(const ScriptNum &rhs) { return operator&=(rhs.value); }
inline ScriptNum operator-() const;
inline ScriptNum &operator=(const int64_t &rhs);
inline ScriptNum &operator+=(const int64_t &rhs);
inline ScriptNum &operator-=(const int64_t &rhs);
inline ScriptNum &operator&=(const int64_t &rhs);
};
ScriptNum ScriptNum::operator-() const {
assert(this->value != std::numeric_limits<int64_t>::min());
return ScriptNum(-this->value);
}
ScriptNum &ScriptNum::operator=(const int64_t &rhs) {
this->value = rhs;
return *this;
}
ScriptNum &ScriptNum::operator+=(const int64_t &rhs) {
assert(rhs == 0 ||
(rhs > 0 && this->value <= std::numeric_limits<int64_t>::max() - rhs) ||
(rhs < 0 && this->value >= std::numeric_limits<int64_t>::min() - rhs));
this->value += rhs;
return *this;
}
ScriptNum &ScriptNum::operator-=(const int64_t &rhs) {
assert(rhs == 0 ||
(rhs > 0 && this->value >= std::numeric_limits<int64_t>::min() + rhs) ||
(rhs < 0 && this->value <= std::numeric_limits<int64_t>::max() + rhs));
this->value -= rhs;
return *this;
}
ScriptNum &ScriptNum::operator&=(const int64_t &rhs) {
this->value &= rhs;
return *this;
}
#endif //STDCHAIN_CORE_SCRIPT_NUM_H
| [
"wurahara@163.com"
] | wurahara@163.com |
0038058b7252b1694ee3fe894be81a66d997189c | e055c4e76ab1da03db14c0fdf9908e9d63115ca0 | /zco/2014/smart_phone.cpp | 1681e6d3eff1eda9dedf3c0506f9c71b345c6b92 | [] | no_license | pmdev15/competitiveprogramming | 2514fca2015de83256d65d4ed1224dd823d3ea61 | 2cbe16934df7bd74b413fcf1208c0b250e30af16 | refs/heads/main | 2023-03-15T00:26:09.870133 | 2021-03-16T14:35:22 | 2021-03-16T14:35:22 | 316,480,373 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 397 | cpp | #include <bits/stdc++.h>
using namespace std;
int main(int argc, char const *argv[])
{
long long int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
sort(arr, arr + n);
long long int maxr = 0;
for (int j = 0; j < n; j++)
{
maxr = max(maxr, arr[j] * (n - j));
}
cout << maxr << endl;
return 0;
}
| [
"pmdev1566@gmail.com"
] | pmdev1566@gmail.com |
b094a001cfe1167debe4683843785f1978c67b9d | 1e8b0df7c04daf0143eaea1793288d654d5eca16 | /AStar_Simulation/EnemyManager.cpp | 7a7041755ac5f4dcd78086e55473a40af42c204f | [] | no_license | dlwlxns4/AStar_Algorithm_Simulation | 3ef9d39a63fa91ec05fd0d9676be765a55eb5a2b | f11698c9d9aa5c47297050400b52f01f3a8c8e00 | refs/heads/main | 2023-08-13T04:46:24.764312 | 2021-10-08T15:59:23 | 2021-10-08T15:59:23 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,746 | cpp | #include "EnemyManager.h"
#include "Enemy.h"
HRESULT EnemyManager::Init()
{
enemyMaxCount = 10;
// 데이터타입 : Enemy* 데이터를 10개를 생성, 삽입
vecEnemys.resize(enemyMaxCount);
for (int i = 0; i < enemyMaxCount; i++)
{
vecEnemys[i] = new Enemy;
vecEnemys[i]->Init();
POINTFLOAT pos{ 100.0f + (i % 5) * 100.0f, 100.0f + (i / 5) * 80.0f };
vecEnemys[i]->SetPos(pos);
}
// 데이터타입 : Enemy* 데이터 10개를 삽입할 수 있는 메모리만 확보
//vecEnemys.reserve(10);
//int count = vecEnemys.size();
//cout << "reserve count : " << count << endl;
//for (int i = 0; i < 10; i++)
//{
// vecEnemys.push_back(new Enemy);
// vecEnemys[i]->Init();
//}
//// 포인터 10개짜리 배열
//for (int i = 0; i < 10; i++)
//{
// enemy[i] = new Enemy;
// enemy[i]->Init();
// POINTFLOAT pos { 100.0f + (i % 5) * 100.0f, 100.0f + (i / 5) * 80.0f };
// enemy[i]->SetPos(pos);
//}
return S_OK;
}
void EnemyManager::Update()
{
for (itEnemys = vecEnemys.begin();
itEnemys != vecEnemys.end(); itEnemys++)
{
(*itEnemys)->Update();
}
//for (int i = 0; i < enemyMaxCount; i++)
//{
// vecEnemys[i]->Update();
//}
}
void EnemyManager::Render(HDC hdc)
{
for (itEnemys = vecEnemys.begin();
itEnemys != vecEnemys.end(); itEnemys++)
{
(*itEnemys)->Render(hdc);
}
//for (int i = 0; i < enemyMaxCount; i++)
//{
// vecEnemys[i]->Render(hdc);
//}
}
void EnemyManager::Release()
{
for (itEnemys = vecEnemys.begin();
itEnemys != vecEnemys.end(); itEnemys++)
{
SAFE_RELEASE((*itEnemys));
}
vecEnemys.clear();
//for (int i = 0; i < enemyMaxCount; i++)
//{
// SAFE_RELEASE(vecEnemys[i]);
//}
//vecEnemys.clear();
}
void EnemyManager::AddEnemy(float posX, float posY)
{
}
| [
"dlwlxns4@gmail.com"
] | dlwlxns4@gmail.com |
4a6aab114ff83ee8f7e6b2757794402cb95714fc | c57209b5e792ec10f39367a76f279e9b572d62fc | /src/lib/cg/tests/TestCgConst.cpp | b61caa66fea69a33f2e26c7511bb4323d8a2122f | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | jrk/PostHaste | 87302cb9a240a40fc378df01f26d567b30f1d86c | 279f32daa751fbb364426b7cfce9a32bbe070214 | refs/heads/master | 2021-01-25T02:28:54.875393 | 2010-01-24T23:52:31 | 2010-01-24T23:52:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,879 | cpp | #include "cg/CgConst.h"
#include "cg/CgTypes.h"
#include "ir/IRValues.h"
#include "ir/IRTypes.h"
#include "util/UtLog.h"
#include <gtest/gtest.h>
#include <iostream>
#include <llvm/Constants.h>
#include <llvm/LLVMContext.h>
#include <llvm/Module.h>
class TestCgConst : public testing::Test {
public:
UtLog mLog;
CgConst mCodegen;
IRTypes mTypes;
TestCgConst() :
mLog(stderr),
mCodegen(CgComponent::Create(&mLog))
{
mCodegen.InitForTest();
}
~TestCgConst() {
mCodegen.Destroy();
}
};
TEST_F(TestCgConst, TestFloatConst)
{
IRNumConst v(1.0f);
llvm::Constant* c = mCodegen.Convert(&v);
std::cout << *c << std::endl;
const llvm::ConstantFP* f = llvm::dyn_cast<llvm::ConstantFP>(c);
ASSERT_TRUE(f != NULL);
EXPECT_TRUE(f->isExactlyValue(1.0f));
}
TEST_F(TestCgConst, TestTripleConst)
{
const float data[] = { 1.0f, 2.0f, 3.0f };
IRNumConst v(data, mTypes.GetPointTy());
llvm::Constant* c = mCodegen.Convert(&v);
std::cout << *c << std::endl;
EXPECT_TRUE(llvm::isa<llvm::ConstantStruct>(c));
}
TEST_F(TestCgConst, TestArrayConst)
{
const IRArrayType* ty = mTypes.GetArrayType(mTypes.GetFloatTy(), 3);
const float elements[] = { 1.0f, 2.0f, 3.0f };
IRNumArrayConst v(elements, ty);
llvm::Constant* c = mCodegen.Convert(&v);
std::cout << *c << std::endl;
EXPECT_TRUE(llvm::isa<llvm::ConstantArray>(c));
}
TEST_F(TestCgConst, TestTripleArrayConst)
{
const IRArrayType* ty = mTypes.GetArrayType(mTypes.GetPointTy(), 2);
const float elements[] = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f };
IRNumArrayConst v(elements, ty);
llvm::Constant* c = mCodegen.Convert(&v);
std::cout << *c << std::endl;
EXPECT_TRUE(llvm::isa<llvm::ConstantArray>(c));
}
TEST_F(TestCgConst, TestStringConst)
{
IRStringConst v("hello");
llvm::Constant* c = mCodegen.Convert(&v);
std::cout << *c << std::endl;
EXPECT_TRUE(llvm::isa<llvm::ConstantExpr>(c));
}
TEST_F(TestCgConst, TestStringArrayConst)
{
const IRArrayType* ty = mTypes.GetArrayType(mTypes.GetStringTy(), 3);
std::vector<std::string> elements;
elements.push_back("one");
elements.push_back("two");
elements.push_back("three");
IRStringArrayConst v(&elements[0], ty);
llvm::Constant* c = mCodegen.Convert(&v);
std::cout << *c << std::endl;
EXPECT_TRUE(llvm::isa<llvm::ConstantArray>(c));
}
TEST_F(TestCgConst, TestMatrixConst)
{
const float data[] = { 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16 };
IRNumConst v(data, mTypes.GetMatrixTy());
llvm::Constant* c = mCodegen.Convert(&v);
// std::cout << *c << std::endl;
std::cout << *c->getType() << std::endl;
EXPECT_TRUE(llvm::isa<llvm::ConstantStruct>(c));
}
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| [
"markleone@gmail.com"
] | markleone@gmail.com |
fca3da7ca3fa4c0da6255f570a09df3e3dde03cc | 948f4e13af6b3014582909cc6d762606f2a43365 | /testcases/juliet_test_suite/testcases/CWE78_OS_Command_Injection/s06/CWE78_OS_Command_Injection__wchar_t_console_w32_spawnv_83_bad.cpp | 6d811f59c8ba2761d1ee47805f62d5a5cb7e58df | [] | 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 | 2,366 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__wchar_t_console_w32_spawnv_83_bad.cpp
Label Definition File: CWE78_OS_Command_Injection.strings.label.xml
Template File: sources-sink-83_bad.tmpl.cpp
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: console Read input from the console
* GoodSource: Fixed string
* Sinks: w32_spawnv
* BadSink : execute command with wspawnv
* Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack
*
* */
#ifndef OMITBAD
#include "std_testcase.h"
#include "CWE78_OS_Command_Injection__wchar_t_console_w32_spawnv_83.h"
#include <process.h>
namespace CWE78_OS_Command_Injection__wchar_t_console_w32_spawnv_83
{
CWE78_OS_Command_Injection__wchar_t_console_w32_spawnv_83_bad::CWE78_OS_Command_Injection__wchar_t_console_w32_spawnv_83_bad(wchar_t * dataCopy)
{
data = dataCopy;
{
/* Read input from the console */
size_t dataLen = wcslen(data);
/* if there is room in data, read into it from the console */
if (100-dataLen > 1)
{
/* POTENTIAL FLAW: Read data from the console */
if (fgetws(data+dataLen, (int)(100-dataLen), stdin) != NULL)
{
/* The next few lines remove the carriage return from the string that is
* inserted by fgetws() */
dataLen = wcslen(data);
if (dataLen > 0 && data[dataLen-1] == L'\n')
{
data[dataLen-1] = L'\0';
}
}
else
{
printLine("fgetws() failed");
/* Restore NUL terminator if fgetws fails */
data[dataLen] = L'\0';
}
}
}
}
CWE78_OS_Command_Injection__wchar_t_console_w32_spawnv_83_bad::~CWE78_OS_Command_Injection__wchar_t_console_w32_spawnv_83_bad()
{
{
wchar_t *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL};
/* wspawnv - specify the path where the command is located */
/* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
_wspawnv(_P_WAIT, COMMAND_INT_PATH, args);
}
}
}
#endif /* OMITBAD */
| [
"yzhang0701@gmail.com"
] | yzhang0701@gmail.com |
598a8488ceebba8231081f0fea6bf1653c1c3e4b | 6f9ca9684edca7c507062744c9cbcbf91d8a9f02 | /src/AdjustPrice/AdjustPriceGoodsSelectListView.h | 22fa87bb41154b53acd120673a48f1c1c885bb6b | [] | no_license | yangchenglin815/kmis | e039a32c42965ccfc8a6b4396f6264eec24a2e76 | d06bafa60c9a87b5ed5617adc0a39a82ec0c89d7 | refs/heads/master | 2020-05-04T06:39:25.653287 | 2019-07-25T03:14:03 | 2019-07-25T03:14:03 | 179,011,069 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,865 | h | #ifndef ADJUSTPRICEGOODSSELECTLISTVIEW_H
#define ADJUSTPRICEGOODSSELECTLISTVIEW_H
#include <QListView>
#include <QStyledItemDelegate>
#include <QStandardItemModel>
#include "adjustpricedata.h"
class AdjustPriceGoodsSelectDelegate : public QStyledItemDelegate
{
public:
AdjustPriceGoodsSelectDelegate(QObject* parent = NULL);
void paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const;
private:
void paintContent(QPainter *painter, const QStyleOptionViewItem &option, const AdjustPriceSelectGoodsInfo& rInfo, bool bSelected) const;
void paintSeqCol(QPainter *painter, const QStyleOptionViewItem &option, const AdjustPriceSelectGoodsInfo& rInfo, bool bSelected) const;
void paintGoodsNameCol(QPainter *painter, const QStyleOptionViewItem &option, const AdjustPriceSelectGoodsInfo& rInfo, bool bSelected) const;
void paintOtherCol(QPainter *painter, const QStyleOptionViewItem &option, const AdjustPriceSelectGoodsInfo& rInfo, bool bSelected) const;
void paintLine(QPainter *painter, const QStyleOptionViewItem &option) const;
};
class AdjustPriceGoodsSelectListView : public QListView
{
Q_OBJECT
public:
explicit AdjustPriceGoodsSelectListView(QWidget *parent = 0);
void appendItem(const AdjustPriceSelectGoodsInfo& selectGoodsInfo);
void clearItems();
bool isExistItem(int nKeyId);
int getSelectKeyId();
void setSelectKeyId(int nKeyId);
bool getSelectItem(AdjustPriceSelectGoodsInfo& selectGoodsInfo);
protected:
void mousePressEvent(QMouseEvent *event);
private:
void init();
signals:
void sigClickItem(AdjustPriceSelectGoodsInfo selectGoodsInfo);
private:
QStandardItemModel* m_pStandardItemModel;
QMap<int, QStandardItem*> m_ItemKeyIdMap;
int m_nItemHeight;
int m_nSelectKeyId;
};
#endif // ADJUSTPRICEGOODSSELECTLISTVIEW_H
| [
"ycldream815@gmail.com"
] | ycldream815@gmail.com |
2ca293153a9608bf77bd596ea6235b65ccf7a01f | 26b37be005cc4661b4d28b8ced3410c1208597e2 | /tests/base/include/chrono.hpp | d2718e9e91411abd23bc361370d6c09f7ccef1a1 | [] | no_license | kleopatra999/yas | 9d8864fb8704b0293a35fea9e1f241c8e2f29ad4 | 965ea5c2ac2fc32c148a38ebf58bdb32aca4b820 | refs/heads/master | 2021-01-19T09:58:35.664509 | 2017-04-09T09:32:38 | 2017-04-09T09:32:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,896 | hpp |
// Copyright (c) 2010-2017 niXman (i dot nixman dog gmail dot com). All
// rights reserved.
//
// This file is part of YAS(https://github.com/niXman/yas) project.
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
//
//
// Boost Software License - Version 1.0 - August 17th, 2003
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#ifndef _yas_test__chrono_hpp
#define _yas_test__chrono_hpp
/***************************************************************************/
template<typename archive_traits>
bool chrono_test(const char* archive_type) {
{
std::chrono::duration<int, std::ratio<1>> w0{32}, r0;
std::chrono::duration<double, std::ratio<1>> w1{23}, r1;
typename archive_traits::oarchive oa;
archive_traits::ocreate(oa, archive_type);
oa & w0
& w1
;
typename archive_traits::iarchive ia;
archive_traits::icreate(ia, oa, archive_type);
ia & r0
& r1
;
if ( r0 != w0 || r1 != w1 ) {
std::cout << "CHRONO serialization error! [1]" << std::endl;
return false;
}
}
{
auto w0 = std::chrono::system_clock::now();
auto r0 = std::chrono::system_clock::now();
typename archive_traits::oarchive oa;
archive_traits::ocreate(oa, archive_type);
oa & w0;
typename archive_traits::iarchive ia;
archive_traits::icreate(ia, oa, archive_type);
ia & r0;
if ( r0 != w0 ) {
std::cout << "CHRONO serialization error! [2]" << std::endl;
return false;
}
}
#if defined(YAS_SERIALIZE_BOOST_TYPES)
{
boost::chrono::duration<int, boost::ratio<1>> w0{32}, r0;
boost::chrono::duration<double, boost::ratio<1>> w1{23}, r1;
typename archive_traits::oarchive oa;
archive_traits::ocreate(oa, archive_type);
oa & w0
& w1
;
typename archive_traits::iarchive ia;
archive_traits::icreate(ia, oa, archive_type);
ia & r0
& r1
;
if ( r0 != w0 || r1 != w1 ) {
std::cout << "CHRONO serialization error! [3]" << std::endl;
return false;
}
}
{
decltype(boost::chrono::system_clock::now()) w0 = boost::chrono::system_clock::now(), r0;
typename archive_traits::oarchive oa;
archive_traits::ocreate(oa, archive_type);
oa & w0;
typename archive_traits::iarchive ia;
archive_traits::icreate(ia, oa, archive_type);
ia & r0;
if ( r0 != w0 ) {
std::cout << "CHRONO serialization error! [4]" << std::endl;
return false;
}
}
#endif // defined(YAS_SERIALIZE_BOOST_TYPES)
return true;
}
/***************************************************************************/
#endif // _yas_test__chrono_hpp
| [
"i.nixman@autistici.org"
] | i.nixman@autistici.org |
d15a15e212151dc69968f6a270fb44b2b0a8c33e | e9025d80026f7d00e0fd69e0ee7e0f97533bd630 | /Global round/round1/D.cpp | b393e68d68958fd90aad2c56ec558b55e104c0a8 | [] | no_license | rishup132/Codeforces-Solutions | 66170b368d851b7076c03f42c9463a2342bac5df | 671d16b0beec519b99fc79058ab9035c6f956670 | refs/heads/master | 2020-04-12T04:32:10.451666 | 2019-03-22T14:04:31 | 2019-03-22T14:04:31 | 162,298,347 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 766 | cpp | #include <bits/stdc++.h>
// #define int long long
// #define mod 1000000007
using namespace std;
int a[1000010];
int32_t main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n,m;
cin >> n >> m;
for(int i=0;i<n;i++)
{
int x;
cin >> x;
a[x]++;
}
int dp[2][3][3] = {0};
for(int i=1;i<=m;i++)
{
memset(dp[i&1^1],0,36);
for(int x=0;x<3;x++)
{
for(int y=0;y<3;y++)
{
for(int z=0;z<3;z++)
{
if(a[i] >= x+y+z)
dp[i&1^1][y][z] = max(dp[i&1^1][y][z],dp[i&1][x][y]+z+(a[i]-x-y-z)/3);
}
}
}
}
cout << dp[m&1^1][0][0] << endl;
} | [
"rishupgupta132@gmail.com"
] | rishupgupta132@gmail.com |
0618dc18f2c648d5bc46d3a7006c78e008c0d8b3 | 1e0ffb3ac40fbb4ef9816eec5e8a05e68e827c61 | /bindings/node/binding.cc | ebee2c5093050eb5939a41d78036497a72920b8b | [] | no_license | richardjdare/tree-sitter-common-lisp | 5ee8a0fe38a2e7d125d5cbf05d5476e2951c64f6 | 6c1944963dc662fb0be386a9a72cccde10927bdf | refs/heads/master | 2023-07-25T22:04:27.275888 | 2021-09-09T15:23:24 | 2021-09-09T15:23:24 | 404,748,952 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 861 | cc | #include "tree_sitter/parser.h"
#include <node.h>
#include "nan.h"
using namespace v8;
extern "C" TSLanguage * tree_sitter_sexp();
namespace {
NAN_METHOD(New) {}
void Init(Local<Object> exports, Local<Object> module) {
Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);
tpl->SetClassName(Nan::New("Language").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Local<Function> constructor = Nan::GetFunction(tpl).ToLocalChecked();
Local<Object> instance = constructor->NewInstance(Nan::GetCurrentContext()).ToLocalChecked();
Nan::SetInternalFieldPointer(instance, 0, tree_sitter_sexp());
Nan::Set(instance, Nan::New("name").ToLocalChecked(), Nan::New("sexp").ToLocalChecked());
Nan::Set(module, Nan::New("exports").ToLocalChecked(), instance);
}
NODE_MODULE(tree_sitter_sexp_binding, Init)
} // namespace
| [
"richardjdare@googlemail.com"
] | richardjdare@googlemail.com |
5e9f16fab559e71c5c49c2335c829293e03d5fba | 99e63f2bba8b91300601577be8af451603efc3dd | /LCD1602.cpp | d50be91f49620aa8cb1fc28653f5dc3df308ac19 | [] | no_license | caoyuan96421/PushToGo_L476 | 704f8900522c149fc44a299c4689dad07faaf1e5 | e5a6b1fdccc207b3e2aca8a0332786db289bf030 | refs/heads/master | 2022-01-26T18:54:45.686038 | 2021-12-26T09:10:15 | 2021-12-26T09:10:15 | 200,592,221 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,779 | cpp | /*
* LCD1602.cpp
*
* Created on: Jul 18, 2019
* Author: caoyu
*/
#include "LCD1602.h"
#include "rtos/ThisThread.h"
#include "mbed_wait_api.h"
#include <stdarg.h>
#include <chrono>
#include "printf.h"
using namespace std::chrono_literals;
LCD1602::LCD1602(PinName rs, PinName rw, PinName en, PinName d[],
PinName brightness, bool fourwire) :
rs(rs), rw(rw), en(en), br(NULL), fw(fourwire), d
{ fourwire ? NC : d[0], fourwire ? NC : d[1],
fourwire ? NC : d[2], fourwire ? NC : d[3], d[4], d[5],
d[6], d[7] } {
this->en = 0;
for (int i = fourwire ? 4 : 0; i < 8; i++) {
this->d[i].output();
}
if (brightness != NC) {
br = new PwmOut(brightness);
br->period_us(64);
*br = 1.0;
}
init();
}
LCD1602::~LCD1602() {
if (br) {
delete br;
}
}
void LCD1602::clear() {
command(0x01);
}
void LCD1602::write(const char *buf, int len) {
for (int i = 0; i < len; i++) {
rw = 0;
rs = 1;
send_byte(buf[i]);
busy_wait();
}
}
void LCD1602::print(const char *fmt, ...) {
char buf[128];
va_list args;
va_start(args, fmt);
int len = vsnprintf(buf, sizeof(buf), fmt, args);
va_end(args);
for (int i = 0; i < len; i++) {
rw = 0;
rs = 1;
send_byte(buf[i]);
busy_wait();
}
}
void LCD1602::setCursor(bool on) {
if (on) {
command(0x0F);
} else {
command(0x0C);
}
}
void LCD1602::setDisplay(bool on) {
if (on) {
command(0x08);
} else {
command(0x0C);
}
}
void LCD1602::setPosition(uint8_t row, uint8_t column) {
uint8_t addr = row * 0x40 + column;
command(0x80 | (addr & 0x7F));
}
void LCD1602::addGlyph(char code, uint8_t glyph[]) {
}
void LCD1602::send_high_nibble(uint8_t nibble) {
d[7] = nibble & 0x80;
d[6] = nibble & 0x40;
d[5] = nibble & 0x20;
d[4] = nibble & 0x10;
en = 1;
wait_ns(50);
en = 0;
}
void LCD1602::send_byte(uint8_t byte) {
d[7] = byte & 0x80;
d[6] = byte & 0x40;
d[5] = byte & 0x20;
d[4] = byte & 0x10;
if (fw) {
// Send high byte
en = 1;
wait_ns(500);
en = 0;
d[7] = byte & 0x08;
d[6] = byte & 0x04;
d[5] = byte & 0x02;
d[4] = byte & 0x01;
// Send low byte
en = 1;
wait_ns(500);
en = 0;
} else {
d[3] = byte & 0x08;
d[2] = byte & 0x04;
d[1] = byte & 0x02;
d[0] = byte & 0x01;
// Send whole byte
en = 1;
wait_ns(500);
en = 0;
}
}
uint8_t LCD1602::read_byte() {
uint8_t data = 0;
uint8_t ep = fw ? 4 : 0;
for (int i = ep; i < 8; i++)
d[i].input();
en = 1;
wait_ns(500);
for (int i = 7; i >= ep; i--) {
data |= d[i] ? 1 : 0;
data <<= 1;
}
en = 0;
wait_ns(500);
if (fw) {
// Do again for lower nibble
en = 1;
wait_ns(500);
for (int i = 7; i >= ep; i--) {
data |= d[i] ? 1 : 0;
data <<= 1;
}
en = 0;
wait_ns(500);
}
for (int i = ep; i < 8; i++)
d[i].output();
return data;
}
void LCD1602::busy_wait() {
// wait_ms(5);
bool busy = true;
rs = 0;
rw = 1;
for (int i = fw ? 4 : 0; i < 8; i++)
d[i].input();
while (busy) {
en = 1;
wait_ns(500);
busy = d[7];
en = 0;
wait_ns(500);
if (fw) {
// Have to do twice to complete one read
en = 1;
wait_ns(500);
en = 0;
wait_ns(500);
}
}
for (int i = fw ? 4 : 0; i < 8; i++)
d[i].output();
}
void LCD1602::init() {
rs = 0;
rw = 0;
// Powerup delay
rtos::ThisThread::sleep_for(100ms);
// Init four wire
if (fw) {
send_high_nibble(0x30);
rtos::ThisThread::sleep_for(5ms);
send_high_nibble(0x30);
rtos::ThisThread::sleep_for(5ms);
send_high_nibble(0x20);
rtos::ThisThread::sleep_for(5ms);
send_byte(0x28);
rtos::ThisThread::sleep_for(5ms);
} else {
send_byte(0x38);
rtos::ThisThread::sleep_for(5ms);
}
command(0x0C); // No cursor
command(0x06); // Increment addr after read/write, no shifting
command(0x02); // Home
command(0x01); // Clear display
}
void LCD1602::command(uint8_t cmd) {
rs = 0;
rw = 0;
send_byte(cmd);
busy_wait();
}
void LCD1602::setBrightness(float level) {
if (br) {
br->write(level);
}
}
void LCD1602::write_ram(uint8_t addr, uint8_t data, RAM ram) {
// Set address
if (ram == CGRAM) {
command(0x40 | (addr & 0x3F));
} else {
command(0x80 | (addr & 0x7F));
}
rw = 0;
rs = 1;
send_byte(data);
busy_wait();
}
uint8_t LCD1602::read_ram(uint8_t addr, RAM ram) {
// Set address
if (ram == CGRAM) {
command(0x40 | (addr & 0x3F));
} else {
command(0x80 | (addr & 0x7F));
}
rw = 1;
rs = 1;
uint8_t data = read_byte();
busy_wait();
return data;
}
void LCD1602::fillWith(char ch, int cnt) {
for (int i = 0; i < cnt; i++) {
rw = 0;
rs = 1;
send_byte(ch);
busy_wait();
}
}
| [
"caoyuan96421@gmail.com"
] | caoyuan96421@gmail.com |
c1a43ffa98c17b2cea0381b2f40fa245271f5b4d | 4042764ea638e7011afe3880b5c5f3fbcecdbc3d | /src/qt/darksendconfig.cpp | 4f9d05ec0cd4f823550e87f3f51939f219fbfda1 | [
"MIT"
] | permissive | deduwka/RLN.V.1.0 | e5f8545d276563dd04bbd592f0f3a74e6c00c3ad | 6e2e30775e8ba8617ba9e5723fb8f1727cb311c1 | refs/heads/master | 2020-04-01T17:21:30.587568 | 2018-10-12T16:26:45 | 2018-10-12T16:26:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,431 | cpp | #include "darksendconfig.h"
#include "ui_darksendconfig.h"
#include "bitcoinunits.h"
#include "darksend.h"
#include "guiconstants.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include <QMessageBox>
#include <QPushButton>
#include <QKeyEvent>
#include <QSettings>
DarksendConfig::DarksendConfig(QWidget *parent) :
QDialog(parent),
ui(new Ui::DarksendConfig),
model(0)
{
ui->setupUi(this);
connect(ui->buttonBasic, SIGNAL(clicked()), this, SLOT(clickBasic()));
connect(ui->buttonHigh, SIGNAL(clicked()), this, SLOT(clickHigh()));
connect(ui->buttonMax, SIGNAL(clicked()), this, SLOT(clickMax()));
}
DarksendConfig::~DarksendConfig()
{
delete ui;
}
void DarksendConfig::setModel(WalletModel *model)
{
this->model = model;
}
void DarksendConfig::clickBasic()
{
configure(true, 1000, 2);
QString strAmount(BitcoinUnits::formatWithUnit(
model->getOptionsModel()->getDisplayUnit(), 1000 * COIN));
QMessageBox::information(this, tr("PrivateSend Configuration"),
tr(
"PrivateSend was successfully set to basic (%1 and 2 rounds). You can change this at any time by opening Lotus's configuration screen."
).arg(strAmount)
);
close();
}
void DarksendConfig::clickHigh()
{
configure(true, 1000, 8);
QString strAmount(BitcoinUnits::formatWithUnit(
model->getOptionsModel()->getDisplayUnit(), 1000 * COIN));
QMessageBox::information(this, tr("PrivateSend Configuration"),
tr(
"PrivateSend was successfully set to high (%1 and 8 rounds). You can change this at any time by opening Lotus's configuration screen."
).arg(strAmount)
);
close();
}
void DarksendConfig::clickMax()
{
configure(true, 1000, 16);
QString strAmount(BitcoinUnits::formatWithUnit(
model->getOptionsModel()->getDisplayUnit(), 1000 * COIN));
QMessageBox::information(this, tr("PrivateSend Configuration"),
tr(
"PrivateSend was successfully set to maximum (%1 and 16 rounds). You can change this at any time by opening Lotus's configuration screen."
).arg(strAmount)
);
close();
}
void DarksendConfig::configure(bool enabled, int coins, int rounds) {
QSettings settings;
settings.setValue("nPrivateSendRounds", rounds);
settings.setValue("nPrivateSendAmount", coins);
nPrivateSendRounds = rounds;
nPrivateSendAmount = coins;
}
| [
"redlotusnetwork@gmail.com"
] | redlotusnetwork@gmail.com |
dd98b3108548d16112c26ad3fa9781bc8616adeb | 598737b786a20889dc6acd468478baf4972535b3 | /src/dist/atf/atf/tests.cpp | 161c64de8e34397cfdb545ed42ef44dd6d899e15 | [
"FSFUL",
"LicenseRef-scancode-unknown-license-reference",
"BSD-4-Clause"
] | permissive | shisa/shisa-netbsd | 5c8e289de2a48b6d8f39bd3add9ca4ea48fec1da | 28d999d1c25107c126e0a458a97b9397aae592ef | refs/heads/master | 2021-01-01T05:33:32.619808 | 2008-05-26T04:27:54 | 2008-05-26T04:27:54 | 32,793,680 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 27,373 | cpp | //
// Automated Testing Framework (atf)
//
// Copyright (c) 2007 The NetBSD Foundation, Inc.
// 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. All advertising materials mentioning features or use of this
// software must display the following acknowledgement:
// This product includes software developed by the NetBSD
// Foundation, Inc. and its contributors.
// 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. AND
// CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
// IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
// IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
extern "C" {
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <signal.h>
#include <unistd.h>
}
#include <algorithm>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <map>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <vector>
#include "atf/application.hpp"
#include "atf/config.hpp"
#include "atf/env.hpp"
#include "atf/exceptions.hpp"
#include "atf/expand.hpp"
#include "atf/formats.hpp"
#include "atf/fs.hpp"
#include "atf/io.hpp"
#include "atf/sanity.hpp"
#include "atf/tests.hpp"
#include "atf/text.hpp"
#include "atf/ui.hpp"
#include "atf/user.hpp"
namespace impl = atf::tests;
#define IMPL_NAME "atf::tests"
//
// Define LAST_SIGNAL to the last signal number valid for the system.
// This is tricky. For example, NetBSD defines SIGPWR as the last valid
// number, whereas Mac OS X defines it as SIGTHR. Both share the same
// signal number (32). If none of these are available, we assume that
// the highest signal is SIGUSR2.
//
#if defined(SIGTHR) && defined(SIGPWR)
# if SIGTHR > SIGPWR
# define LAST_SIGNAL SIGTHR
# elif SIGPWR < SIGTHR
# define LAST_SIGNAL SIGPWR
# else
# define LAST_SIGNAL SIGPWR
# endif
#elif defined(SIGTHR)
# define LAST_SIGNAL SIGTHR
#elif defined(SIGPWR)
# define LAST_SIGNAL SIGPWR
#else
# define LAST_SIGNAL SIGUSR2
#endif
// ------------------------------------------------------------------------
// The auxiliary "signal_holder" class.
// ------------------------------------------------------------------------
//
// A RAII model to hold a signal while the object is alive.
//
class signal_holder {
int m_signal;
bool m_happened;
struct sigaction m_sanew, m_saold;
static std::map< int, signal_holder* > m_holders;
static void handler(int s)
{
m_holders[s]->m_happened = true;
}
void program(void)
{
if (::sigaction(m_signal, &m_sanew, &m_saold) == -1)
throw atf::system_error("signal_holder::signal_holder",
"sigaction(2) failed", errno);
}
public:
signal_holder(int s) :
m_signal(s),
m_happened(false)
{
m_sanew.sa_handler = handler;
sigemptyset(&m_sanew.sa_mask);
m_sanew.sa_flags = 0;
program();
PRE(m_holders.find(m_signal) == m_holders.end());
m_holders[m_signal] = this;
}
~signal_holder(void)
{
int res = ::sigaction(m_signal, &m_saold, NULL);
try {
process();
if (res == -1)
throw atf::system_error("signal_holder::signal_holder",
"sigaction(2) failed", errno);
} catch (...) {
if (res == -1)
throw atf::system_error("signal_holder::signal_holder",
"sigaction(2) failed", errno);
}
}
void process(void)
{
if (m_happened) {
int res = ::sigaction(m_signal, &m_saold, NULL);
::kill(0, m_signal);
if (res == -1)
throw atf::system_error("signal_holder::signal_holder",
"sigaction(2) failed", errno);
program();
}
}
};
std::map< int, signal_holder* > signal_holder::m_holders;
// ------------------------------------------------------------------------
// The "vars_map" class.
// ------------------------------------------------------------------------
impl::vars_map::vars_map(void)
{
}
const std::string&
impl::vars_map::get(const std::string& key)
const
{
const_iterator iter = find(key);
if (iter == end())
throw std::runtime_error("Could not find variable `" + key +
"' in map");
return (*iter).second;
}
const std::string&
impl::vars_map::get(const std::string& key, const std::string& def)
const
{
const_iterator iter = find(key);
return (iter == end()) ? def : (*iter).second;
}
bool
impl::vars_map::get_bool(const std::string& key)
const
{
bool val;
std::string str = text::to_lower(get(key));
if (str == "yes" || str == "true")
val = true;
else if (str == "no" || str == "false")
val = false;
else
throw std::runtime_error("Invalid value for boolean variable `" +
key + "'");
return val;
}
bool
impl::vars_map::get_bool(const std::string& key, bool def)
const
{
bool val;
const_iterator iter = find(key);
if (iter == end())
val = def;
else {
std::string str = text::to_lower((*iter).second);
if (str == "yes" || str == "true")
val = true;
else if (str == "no" || str == "false")
val = false;
else
throw std::runtime_error("Invalid value for boolean "
"variable `" + key + "'");
}
return val;
}
bool
impl::vars_map::has(const std::string& key)
const
{
return find(key) != end();
}
impl::vars_map::value_type
impl::vars_map::parse(const std::string& str)
{
if (str.empty())
throw std::runtime_error("-v requires a non-empty argument");
std::vector< std::string > ws = atf::text::split(str, "=");
if (ws.size() == 1 && str[str.length() - 1] == '=') {
return impl::vars_map::value_type(ws[0], "");
} else {
if (ws.size() != 2)
throw std::runtime_error("-v requires an argument of the form "
"var=value");
return impl::vars_map::value_type(ws[0], ws[1]);
}
}
// ------------------------------------------------------------------------
// The "tcr" class.
// ------------------------------------------------------------------------
impl::tcr::tcr(void) :
m_status(status_failed),
m_reason("Uninitialized test case result")
{
}
impl::tcr::tcr(impl::tcr::status s, const std::string& r) :
m_status(s)
{
if (r.find('\n') == std::string::npos)
m_reason = r;
else {
m_reason = "BOGUS REASON (THE ORIGINAL HAD NEWLINES): ";
for (std::string::size_type i = 0; i < r.length(); i++) {
if (r[i] == '\n')
m_reason += "<<NEWLINE>>";
else if (r[i] != '\r')
m_reason += r[i];
}
}
}
impl::tcr
impl::tcr::passed(void)
{
return tcr(status_passed, "");
}
impl::tcr
impl::tcr::skipped(const std::string& reason)
{
return tcr(status_skipped, reason);
}
impl::tcr
impl::tcr::failed(const std::string& reason)
{
return tcr(status_failed, reason);
}
impl::tcr::status
impl::tcr::get_status(void)
const
{
return m_status;
}
const std::string&
impl::tcr::get_reason(void)
const
{
return m_reason;
}
// ------------------------------------------------------------------------
// The "tc" class.
// ------------------------------------------------------------------------
impl::tc::tc(const std::string& ident) :
m_ident(ident)
{
}
impl::tc::~tc(void)
{
}
void
impl::tc::ensure_boolean(const std::string& name)
{
ensure_not_empty(name);
std::string val = text::to_lower(get(name));
if (val == "yes" || val == "true")
set(name, "true");
else if (val == "no" || val == "false")
set(name, "false");
else
throw std::runtime_error("Invalid value for boolean variable `" +
name + "'");
}
void
impl::tc::ensure_not_empty(const std::string& name)
{
if (m_meta_data.find(name) == m_meta_data.end())
throw atf::not_found_error< std::string >
("Undefined or empty variable", name);
vars_map::const_iterator iter = m_meta_data.find(name);
INV(iter != m_meta_data.end());
const std::string& val = (*iter).second;
if (val.empty())
throw atf::not_found_error< std::string > // XXX Incorrect error
("Undefined or empty variable", name);
}
void
impl::tc::set(const std::string& var, const std::string& val)
{
m_meta_data[var] = val;
}
const std::string&
impl::tc::get(const std::string& var)
const
{
vars_map::const_iterator iter = m_meta_data.find(var);
PRE(iter != m_meta_data.end());
return (*iter).second;
}
bool
impl::tc::get_bool(const std::string& var)
const
{
std::string val = get(var);
if (val == "true")
return true;
else if (val == "false")
return false;
else
UNREACHABLE;
}
bool
impl::tc::has(const std::string& var)
const
{
vars_map::const_iterator iter = m_meta_data.find(var);
return (iter != m_meta_data.end());
}
const impl::vars_map&
impl::tc::config(void)
const
{
return m_config;
}
const std::string&
impl::tc::get_srcdir(void)
const
{
return m_srcdir;
}
void
impl::tc::init(const vars_map& c, const std::string& srcdir)
{
PRE(m_meta_data.empty());
m_config = c; // XXX Uh, deep copy. Should be a reference...
m_srcdir = srcdir;
m_meta_data["ident"] = m_ident;
head();
ensure_not_empty("descr");
ensure_not_empty("ident");
INV(m_meta_data["ident"] == m_ident);
}
impl::tcr
impl::tc::safe_run(void)
const
{
atf::fs::temp_dir workdir
(atf::fs::path(m_config.get("workdir")) / "atf.XXXXXX");
impl::tcr tcr = fork_body(workdir.get_path().str());
fork_cleanup(workdir.get_path().str());
return tcr;
}
static void
sanitize_process(const atf::fs::path& workdir)
{
// Reset all signal handlers to their default behavior.
struct sigaction sadfl;
sadfl.sa_handler = SIG_DFL;
sigemptyset(&sadfl.sa_mask);
sadfl.sa_flags = 0;
for (int i = 0; i < LAST_SIGNAL; i++)
::sigaction(i, &sadfl, NULL);
// Reset critical environment variables to known values.
atf::env::set("HOME", workdir.str());
atf::env::unset("LANG");
atf::env::unset("LC_ALL");
atf::env::unset("LC_COLLATE");
atf::env::unset("LC_CTYPE");
atf::env::unset("LC_MESSAGES");
atf::env::unset("LC_MONETARY");
atf::env::unset("LC_NUMERIC");
atf::env::unset("LC_TIME");
atf::env::unset("TZ");
// Reset the umask.
::umask(S_IWGRP | S_IWOTH);
// Set the work directory.
atf::fs::change_directory(workdir);
}
void
impl::tc::check_requirements(void)
const
{
if (has("require.config")) {
const std::string& c = get("require.config");
std::vector< std::string > vars = text::split(c, " ");
for (std::vector< std::string >::const_iterator iter = vars.begin();
iter != vars.end(); iter++) {
if (!m_config.has(*iter))
throw tcr::skipped("Required configuration variable " +
*iter + " not defined");
}
}
if (has("require.user")) {
const std::string& u = get("require.user");
if (u == "root") {
if (!user::is_root())
throw tcr::skipped("Requires root privileges");
} else if (u == "unprivileged") {
if (!user::is_unprivileged())
throw tcr::skipped("Requires an unprivileged user");
} else
throw tcr::skipped("Invalid value in the require.user "
"property");
}
if (has("require.progs")) {
std::vector< std::string > progs =
text::split(get("require.progs"), " ");
for (std::vector< std::string >::const_iterator iter =
progs.begin(); iter != progs.end(); iter++)
require_prog(*iter);
}
}
impl::tcr
impl::tc::fork_body(const std::string& workdir)
const
{
tcr tcr;
fs::path result(fs::path(workdir) / "tc-result");
pid_t pid = ::fork();
if (pid == -1) {
tcr = tcr::failed("Coult not fork to run test case");
} else if (pid == 0) {
int errcode;
// Unexpected errors detected in the child process are mentioned
// in stderr to give the user a chance to see what happened.
// This is specially useful in those cases where these errors
// cannot be directed to the parent process.
try {
sanitize_process(atf::fs::path(workdir));
check_requirements();
body();
throw impl::tcr::passed();
} catch (const impl::tcr& tcre) {
std::ofstream os(result.c_str());
if (!os) {
std::cerr << "Could not open the temporary file " +
result.str() + " to leave the results in it"
<< std::endl;
errcode = EXIT_FAILURE;
} else {
if (tcre.get_status() == impl::tcr::status_passed)
os << "passed\n";
else if (tcre.get_status() == impl::tcr::status_failed)
os << "failed\n" << tcre.get_reason() << '\n';
else if (tcre.get_status() == impl::tcr::status_skipped)
os << "skipped\n" << tcre.get_reason() << '\n';
os.close();
errcode = EXIT_SUCCESS;
}
} catch (const std::runtime_error& e) {
std::cerr << "Caught unexpected error: " << e.what() << std::endl;
errcode = EXIT_FAILURE;
} catch (...) {
std::cerr << "Caught unexpected error" << std::endl;
errcode = EXIT_FAILURE;
}
std::exit(errcode);
} else {
int status;
if (::waitpid(pid, &status, 0) == -1) {
tcr = tcr::failed("Error while waiting for process " +
atf::text::to_string(pid) + ": " +
::strerror(errno));
} else {
if (WIFEXITED(status)) {
if (WEXITSTATUS(status) == EXIT_SUCCESS) {
std::ifstream is(result.c_str());
if (!is) {
tcr = tcr::failed("Could not open results file for "
"reading");
} else {
std::string line;
std::getline(is, line);
if (line == "passed") {
tcr = tcr::passed();
} else if (line == "failed") {
std::getline(is, line);
tcr = tcr::failed(line);
} else if (line == "skipped") {
std::getline(is, line);
tcr = tcr::skipped(line);
} else {
tcr = tcr::failed("Test case failed to report its "
"status");
}
is.close();
}
} else
tcr = tcr::failed("Test case returned non-OK status; "
"see its stderr output for more "
"details");
} else if (WIFSIGNALED(status)) {
tcr = tcr::failed("Test case received signal " +
atf::text::to_string(WTERMSIG(status)));
} else if (WIFSTOPPED(status)) {
tcr = tcr::failed("Test case received stop signal " +
atf::text::to_string(WSTOPSIG(status)));
} else
UNREACHABLE;
}
}
return tcr;
}
void
impl::tc::fork_cleanup(const std::string& workdir)
const
{
pid_t pid = ::fork();
if (pid == -1) {
std::cerr << "WARNING: Could not fork to run test case's cleanup "
"routine for " << workdir << std::endl;
} else if (pid == 0) {
int errcode = EXIT_FAILURE;
try {
sanitize_process(atf::fs::path(workdir));
cleanup();
errcode = EXIT_SUCCESS;
} catch (const std::exception& e) {
std::cerr << "WARNING: Caught unexpected exception while "
"running the test case's cleanup routine: "
<< e.what() << std::endl;
} catch (...) {
std::cerr << "WARNING: Caught unknown exception while "
"running the test case's cleanup routine"
<< std::endl;
}
std::exit(errcode);
} else {
int status;
if (::waitpid(pid, &status, 0) == -1)
std::cerr << "WARNING: Error while waiting for cleanup process "
<< atf::text::to_string(pid) << ": "
<< ::strerror(errno) << std::endl;
if (!WIFEXITED(status) || WEXITSTATUS(status) != EXIT_SUCCESS)
std::cerr << "WARNING: Cleanup process ended unexpectedly"
<< std::endl;
}
}
impl::tcr
impl::tc::run(void)
const
{
PRE(!m_meta_data.empty());
tcr tcr;
try {
tcr = safe_run();
} catch (const std::exception& e) {
tcr = tcr::failed(std::string("Unhandled exception: ") +
e.what());
} catch (...) {
tcr = tcr::failed("Unknown unhandled exception");
}
return tcr;
}
void
impl::tc::cleanup(void)
const
{
}
void
impl::tc::require_prog(const std::string& prog)
const
{
PRE(!prog.empty());
fs::path p(prog);
if (p.is_absolute()) {
if (!fs::is_executable(p))
throw impl::tcr::skipped("The required program " + prog +
" could not be found");
} else {
INV(p.branch_path() == fs::path("."));
if (fs::find_prog_in_path(prog).empty())
throw impl::tcr::skipped("The required program " + prog +
" could not be found in the PATH");
}
}
// ------------------------------------------------------------------------
// The "tp" class.
// ------------------------------------------------------------------------
class tp : public atf::application {
public:
typedef std::vector< impl::tc * > tc_vector;
private:
static const char* m_description;
bool m_lflag;
int m_results_fd;
std::auto_ptr< std::ostream > m_results_os;
atf::fs::path m_srcdir;
std::set< std::string > m_tcnames;
atf::tests::vars_map m_vars;
std::string specific_args(void) const;
options_set specific_options(void) const;
void process_option(int, const char*);
tc_vector m_tcs;
tc_vector init_tcs(void);
static tc_vector filter_tcs(tc_vector, const std::set< std::string >&);
std::ostream& results_stream(void);
int list_tcs(void);
int run_tcs(void);
public:
tp(const tc_vector&);
int main(void);
};
const char* tp::m_description =
"This is an independent atf test program.";
tp::tp(const tc_vector& tcs) :
application(m_description, "atf-test-program(1)"),
m_lflag(false),
m_results_fd(STDOUT_FILENO),
m_srcdir(atf::fs::get_current_dir()),
m_tcs(tcs)
{
m_vars["workdir"] = atf::config::get("atf_workdir");
}
std::string
tp::specific_args(void)
const
{
return "[test_case1 [.. test_caseN]]";
}
tp::options_set
tp::specific_options(void)
const
{
options_set opts;
opts.insert(option('l', "", "List test cases and their purpose"));
opts.insert(option('r', "fd", "The file descriptor to which the test "
"program will send the results of the "
"test cases"));
opts.insert(option('s', "srcdir", "Directory where the test's data "
"files are located"));
opts.insert(option('v', "var=value", "Sets the configuration variable "
"`var' to `value'"));
return opts;
}
void
tp::process_option(int ch, const char* arg)
{
switch (ch) {
case 'l':
m_lflag = true;
break;
case 'r':
{
std::istringstream ss(arg);
ss >> m_results_fd;
}
break;
case 's':
m_srcdir = atf::fs::path(arg);
break;
case 'v':
{
atf::tests::vars_map::value_type v =
atf::tests::vars_map::parse(arg);
m_vars[v.first] = v.second;
}
break;
default:
UNREACHABLE;
}
}
tp::tc_vector
tp::init_tcs(void)
{
tc_vector tcs = m_tcs;
for (tc_vector::iterator iter = tcs.begin();
iter != tcs.end(); iter++) {
impl::tc* tc = *iter;
tc->init(m_vars, m_srcdir.str());
}
return tcs;
}
//
// An auxiliary unary predicate that compares the given test case's
// identifier to the identifier stored in it.
//
class tc_equal_to_ident {
const std::string& m_ident;
public:
tc_equal_to_ident(const std::string& i) :
m_ident(i)
{
}
bool operator()(const impl::tc* tc)
{
return tc->get("ident") == m_ident;
}
};
tp::tc_vector
tp::filter_tcs(tc_vector tcs, const std::set< std::string >& tcnames)
{
tc_vector tcso;
if (tcnames.empty()) {
// Special case: added for efficiency because this is the most
// typical situation.
tcso = tcs;
} else {
// Collect all the test cases' identifiers.
std::set< std::string > ids;
for (tc_vector::iterator iter = tcs.begin();
iter != tcs.end(); iter++) {
impl::tc* tc = *iter;
ids.insert(tc->get("ident"));
}
// Iterate over all names provided by the user and, for each one,
// expand it as if it were a glob pattern. Collect all expansions.
std::set< std::string > exps;
for (std::set< std::string >::const_iterator iter = tcnames.begin();
iter != tcnames.end(); iter++) {
const std::string& glob = *iter;
std::set< std::string > ms = atf::expand::expand_glob(glob, ids);
if (ms.empty())
throw std::runtime_error("Unknown test case `" + glob + "'");
exps.insert(ms.begin(), ms.end());
}
// For each expansion, locate its corresponding test case and add
// it to the output set.
for (std::set< std::string >::const_iterator iter = exps.begin();
iter != exps.end(); iter++) {
const std::string& name = *iter;
tc_vector::iterator tciter =
std::find_if(tcs.begin(), tcs.end(), tc_equal_to_ident(name));
INV(tciter != tcs.end());
tcso.push_back(*tciter);
}
}
return tcso;
}
int
tp::list_tcs(void)
{
tc_vector tcs = filter_tcs(init_tcs(), m_tcnames);
std::string::size_type maxlen = 0;
for (tc_vector::const_iterator iter = tcs.begin();
iter != tcs.end(); iter++) {
const impl::tc* tc = *iter;
if (maxlen < tc->get("ident").length())
maxlen = tc->get("ident").length();
}
for (tc_vector::const_iterator iter = tcs.begin();
iter != tcs.end(); iter++) {
const impl::tc* tc = *iter;
std::cout << atf::ui::format_text_with_tag(tc->get("descr"),
tc->get("ident"),
false, maxlen + 4)
<< std::endl;
}
return EXIT_SUCCESS;
}
std::ostream&
tp::results_stream(void)
{
if (m_results_fd == STDOUT_FILENO)
return std::cout;
else if (m_results_fd == STDERR_FILENO)
return std::cerr;
else
return *m_results_os;
}
int
tp::run_tcs(void)
{
tc_vector tcs = filter_tcs(init_tcs(), m_tcnames);
if (!atf::fs::exists(atf::fs::path(m_vars.get("workdir"))))
throw std::runtime_error("Cannot find the work directory `" +
m_vars.get("workdir") + "'");
int errcode = EXIT_SUCCESS;
signal_holder sighup(SIGHUP);
signal_holder sigint(SIGINT);
signal_holder sigterm(SIGTERM);
atf::formats::atf_tcs_writer w(results_stream(), std::cout, std::cerr,
tcs.size());
for (tc_vector::iterator iter = tcs.begin();
iter != tcs.end(); iter++) {
impl::tc* tc = *iter;
w.start_tc(tc->get("ident"));
impl::tcr tcr = tc->run();
w.end_tc(tcr);
sighup.process();
sigint.process();
sigterm.process();
if (tcr.get_status() == impl::tcr::status_failed)
errcode = EXIT_FAILURE;
}
return errcode;
}
int
tp::main(void)
{
int errcode;
if (!atf::fs::exists(m_srcdir / m_prog_name))
throw std::runtime_error("Cannot find the test program in the "
"source directory `" + m_srcdir.str() + "'");
for (int i = 0; i < m_argc; i++)
m_tcnames.insert(m_argv[i]);
if (m_lflag)
errcode = list_tcs();
else {
if (m_results_fd != STDOUT_FILENO && m_results_fd != STDERR_FILENO) {
atf::io::file_handle fh(m_results_fd);
m_results_os =
std::auto_ptr< std::ostream >(new atf::io::postream(fh));
}
errcode = run_tcs();
}
return errcode;
}
namespace atf {
namespace tests {
int run_tp(int, char* const*, const tp::tc_vector&);
}
}
int
impl::run_tp(int argc, char* const* argv, const tp::tc_vector& tcs)
{
return tp(tcs).run(argc, argv);
}
| [
"keiichi@mobilegravity.sfc.wide.ad.jp"
] | keiichi@mobilegravity.sfc.wide.ad.jp |
e80262832e66267bfc6363cef7593577fb943247 | 4f07dffbbc1dcf3c06c33219296eb72d99b08ab0 | /ui/keyboard/container_fullscreen_behavior.h | 66a6ad555c349fc1590930da2efde1d6e191d91d | [
"BSD-3-Clause"
] | permissive | zeyiwu/chromium | 4815e89f8a9acd0e9e6957dc2be6e6d6f4995a52 | 2969192f368b295477a3348584160a854fd3316b | refs/heads/master | 2023-02-21T20:39:29.821478 | 2018-05-22T02:04:26 | 2018-05-22T02:04:26 | 134,348,434 | 1 | 0 | null | 2018-05-22T02:16:57 | 2018-05-22T02:16:57 | null | UTF-8 | C++ | false | false | 1,106 | h | // 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.
#ifndef UI_KEYBOARD_CONTAINER_FULLSCREEN_BEHAVIOR_H_
#define UI_KEYBOARD_CONTAINER_FULLSCREEN_BEHAVIOR_H_
#include "ui/aura/window.h"
#include "ui/keyboard/container_full_width_behavior.h"
#include "ui/keyboard/keyboard_controller.h"
#include "ui/keyboard/keyboard_export.h"
namespace keyboard {
class KEYBOARD_EXPORT ContainerFullscreenBehavior
: public ContainerFullWidthBehavior {
public:
ContainerFullscreenBehavior(KeyboardController* controller);
~ContainerFullscreenBehavior() override;
// ContainerFullWidthBehavior overrides
gfx::Rect AdjustSetBoundsRequest(
const gfx::Rect& display_bounds,
const gfx::Rect& requested_bounds_in_screen_coords) override;
void SetCanonicalBounds(aura::Window* container,
const gfx::Rect& display_bounds) override;
ContainerType GetType() const override;
};
} // namespace keyboard
#endif // UI_KEYBOARD_CONTAINER_FULLSCREEN_BEHAVIOR_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.