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 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
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 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e34a540f90900cde3459117bb85a55eaa5f14a8a | cdc4256b1ef1bb68481299afcd7ced34f5c074a2 | /PA3-1/src/dynamic_scene/draw_style.h | 3fa6d4c2bd5070f3c26bc508fde907c46d125add | [] | no_license | JiyuanLu/CS184_UCB_S18 | 1ad43ce8e47ff201612960d009dde3c23f7d2634 | 8245989ae0db7e90a06574973debfb0550016e39 | refs/heads/master | 2022-12-11T02:30:38.218534 | 2019-11-11T03:34:56 | 2019-11-11T03:34:56 | 220,892,561 | 3 | 1 | null | 2022-12-09T00:57:51 | 2019-11-11T03:20:50 | C | UTF-8 | C++ | false | false | 890 | h | #ifndef CGL_DYNAMICSCENE_DRAWSTYLE_H
#define CGL_DYNAMICSCENE_DRAWSTYLE_H
#include "scene.h"
namespace CGL { namespace DynamicScene {
/**
* Used in rendering to specify how to draw the faces/meshes/lines/etc.
*/
class DrawStyle {
public:
void style_reset() const {
glLineWidth(1);
glPointSize(1);
}
void style_face() const {
glColor4fv(&faceColor.r);
}
void style_edge() const {
glColor4fv(&edgeColor.r);
glLineWidth(strokeWidth);
}
void style_halfedge() const {
glColor4fv(&halfedgeColor.r);
glLineWidth(strokeWidth);
}
void style_vertex() const {
glColor4fv(&vertexColor.r);
glPointSize(vertexRadius);
}
Color halfedgeColor;
Color vertexColor;
Color edgeColor;
Color faceColor;
float strokeWidth;
float vertexRadius;
};
} // namespace DynamicScene
} // namespace CGL
#endif //CGL_DYNAMICSCENE_DRAWSTYLE_H
| [
"chestnutrupert@gmail.com"
] | chestnutrupert@gmail.com |
2917a1ed363ad39cde34be61c1c8d54f9b173b51 | 488706ddcd860941510ddd5c8f35bbd065de9ca1 | /visualtext3/cj/Ribbon/XTPRibbonControlTab.h | c737961ed39988fc6e0286cb38e8dc498f43a80b | [] | no_license | VisualText/legacy | 8fabbf1da142dfac1a47f4759103671c84ee64fe | 73d3dee26ab988e61507713ca37c4e9c0416aee5 | refs/heads/main | 2023-08-14T08:14:25.178165 | 2021-09-27T22:41:00 | 2021-09-27T22:41:00 | 411,052,445 | 0 | 0 | null | 2021-09-27T22:40:55 | 2021-09-27T21:48:09 | C++ | UTF-8 | C++ | false | false | 12,521 | h | // XTPRibbonControlTab.h: interface for the CXTPRibbonControlTab class.
//
// This file is a part of the XTREME RIBBON MFC class library.
// (c)1998-2013 Codejock Software, All Rights Reserved.
//
// THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE
// RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN
// CONSENT OF CODEJOCK SOFTWARE.
//
// THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED
// IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO
// YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A
// SINGLE COMPUTER.
//
// CONTACT INFORMATION:
// support@codejock.com
// http://www.codejock.com
//
/////////////////////////////////////////////////////////////////////////////
//{{AFX_CODEJOCK_PRIVATE
#if !defined(__XTPRIBBONCONTROLTAB_H__)
#define __XTPRIBBONCONTROLTAB_H__
//}}AFX_CODEJOCK_PRIVATE
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CXTPRibbonGroups;
class CXTPRibbonBar;
class CXTPRibbonGroup;
class CXTPRibbonTab;
//-----------------------------------------------------------------------
// Summary:
// Structure used as parameter for TCN_SELCHANGING and TCN_SELCHANGE messages when Ribbon tab is changed
//-----------------------------------------------------------------------
struct NMXTPTABCHANGE : public NMXTPCONTROL
{
CXTPRibbonTab* pTab; // Ribbon Tab to be selected
};
//===========================================================================
// Summary:
// CXTPRibbonControlTab is a CXTPTabManager derived class, It represents tabs of the ribbon bar
//===========================================================================
class _XTP_EXT_CLASS CXTPRibbonControlTab : public CXTPControlPopup, public CXTPTabManager
{
DECLARE_XTP_CONTROL(CXTPRibbonControlTab)
public:
//-----------------------------------------------------------------------
// Summary:
// Constructs a CXTPRibbonControlTab object
//-----------------------------------------------------------------------
CXTPRibbonControlTab();
//-----------------------------------------------------------------------
// Summary:
// Destroys a CXTPRibbonControlTab object, handles cleanup and deallocation
//-----------------------------------------------------------------------
virtual ~CXTPRibbonControlTab();
public:
//-----------------------------------------------------------------------
// Summary:
// Call this member to get a pointer to the tab paint manager.
// The tab paint manager is used to customize the appearance of
// CXTPTabManagerItem objects and the tab manager. I.e. Tab colors,
// styles, etc... This member must be overridden in
// derived classes.
// Returns:
// Pointer to CXTPTabPaintManager that contains the visual elements
// of the tabs.
//-----------------------------------------------------------------------
virtual CXTPTabPaintManager* GetPaintManager() const;
//-----------------------------------------------------------------------
// Summary:
// Retrieves parent CXTPRibbonBar object
//-----------------------------------------------------------------------
CXTPRibbonBar* GetRibbonBar() const;
//-----------------------------------------------------------------------
// Summary:
// Cal this method to find tab by its identifier
// Parameters:
// nId - Identifier of tab to be found
// Returns:
// Pointer to CXTPRibbonTab object with specified identifier
// See Also: GetTab
//-----------------------------------------------------------------------
CXTPRibbonTab* FindTab(int nId) const;
//-----------------------------------------------------------------------
// Summary:
// Cal this method to get tab in specified position
// Parameters:
// nIndex - Index of tab to retrieve
// Returns:
// Pointer to CXTPRibbonTab object in specified position
// See Also: FindTab
//-----------------------------------------------------------------------
CXTPRibbonTab* GetTab(int nIndex) const;
//-----------------------------------------------------------------------
// Summary:
// Call this member to select a tab in the ribbon bar.
// Parameters:
// pItem - Points to a CXTPTabManagerItem object to be selected.
//-----------------------------------------------------------------------
void SetSelectedItem(CXTPTabManagerItem* pItem);
protected:
//-----------------------------------------------------------------------
// Summary:
// This method is called to update position of TabManager.
//-----------------------------------------------------------------------
void Reposition();
//-------------------------------------------------------------------------
// Summary:
// This virtual member is called to determine if control has focus and need
// to draw focused rectangle around focused item
// Returns:
// TRUE if header has has focus
//-------------------------------------------------------------------------
virtual BOOL HeaderHasFocus() const;
//-----------------------------------------------------------------------
// Summary:
// Call this member to set focus to the control.
// Parameters:
// bFocused - TRUE to set focus
//-----------------------------------------------------------------------
virtual void SetFocused(BOOL bFocused);
//-----------------------------------------------------------------------
// Summary:
// Call this member to get the focused state of the control.
// Returns:
// TRUE if the control has focus; otherwise FALSE.
//-----------------------------------------------------------------------
virtual BOOL IsFocused() const;
//----------------------------------------------------------------------
// Summary:
// This method is called when the user activate control using its underline.
//----------------------------------------------------------------------
void OnUnderlineActivate();
//----------------------------------------------------------------------
// Summary:
// This method is called to check if control accept focus
// See Also: SetFocused
//----------------------------------------------------------------------
virtual BOOL IsFocusable() const;
//----------------------------------------------------------------------
// Summary:
// This method is called when the control becomes selected.
// Parameters:
// bSelected - TRUE if the control becomes selected.
// Returns:
// TRUE if successful; otherwise returns FALSE
//----------------------------------------------------------------------
BOOL OnSetSelected(int bSelected);
//----------------------------------------------------------------------
// Summary:
// This method is called when a non-system key is pressed.
// Parameters:
// nChar - Specifies the virtual key code of the given key.
// lParam - Specifies additional message-dependent information.
// Returns:
// TRUE if key handled, otherwise returns FALSE
//----------------------------------------------------------------------
BOOL OnHookKeyDown (UINT nChar, LPARAM lParam);
//----------------------------------------------------------------------
// Summary:
// This method is called when an item(tab button) is clicked.
// Parameters:
// pItem - Item that was clicked.
//----------------------------------------------------------------------
void OnItemClick(CXTPTabManagerItem* pItem);
protected:
//-----------------------------------------------------------------------
// Summary:
// This member is called when the icon of the ribbon tab needs to be
// drawn.
// Parameters:
// pDC - Pointer to the destination device context.
// pt - Specifies the location of the image.
// pItem - CXTPTabManagerItem object to draw icon on.
// bDraw - TRUE if the icon needs to be drawn, I.e. the icon size
// changed. FALSE if the icon does not need to be
// drawn or redrawn.
// szIcon - Size of the tab icon.
// Remarks:
// For example, on mouseover. This member is overridden by its
// descendants. This member must be overridden in
// derived classes.
// Returns:
// TRUE if the icon was successfully drawn, FALSE if the icon
// was not drawn.
//-----------------------------------------------------------------------
BOOL DrawIcon(CDC* pDC, CPoint pt, CXTPTabManagerItem* pItem, BOOL bDraw, CSize& szIcon) const;
//-----------------------------------------------------------------------
// Summary:
// Initiates redrawing of the ribbon bar control.
// Remarks:
// Call this member function if you want to initialize redrawing
// of the control. The control will be redrawn taking into account
// its latest state.
// Parameters:
// lpRect - The rectangular area of the window that is invalid.
// bAnimate - TRUE to animate changes in bounding rectangle.
//-----------------------------------------------------------------------
void RedrawControl(LPCRECT lpRect, BOOL bAnimate);
//-----------------------------------------------------------------------
// Summary:
// Checks to see if the mouse is locked.
// Remarks:
// The mouse is locked when a CXTPCommandBarsPopup is currently visible.
// Returns:
// TRUE if locked; otherwise returns FALSE.
//-----------------------------------------------------------------------
BOOL IsMouseLocked() const;
//----------------------------------------------------------------------
// Summary:
// This method is called to draw the control.
// Parameters:
// pDC - Pointer to a valid device context.
//----------------------------------------------------------------------
void Draw(CDC* pDC);
//-----------------------------------------------------------------------
// Summary:
// Call this member function to Store/Load a properties collection
// using the specified data object.
// Parameters:
// pPX - Source or destination CXTPPropExchange data object reference.
// Remarks:
// This member function is used to store or load properties collection
// data to or form an storage.
//-----------------------------------------------------------------------
void DoPropExchange(CXTPPropExchange* pPX);
//----------------------------------------------------------------------
// Summary:
// This method is called to copy the control.
// Parameters:
// pControl - Points to a source CXTPControl object
// bRecursive - TRUE to copy recursively.
//----------------------------------------------------------------------
void Copy(CXTPControl* pControl, BOOL bRecursive = FALSE);
//-----------------------------------------------------------------------
// Summary:
// Call this member to get the tracking state.
// Returns:
// TRUE if the ribbon is in the tracking mode.
//-----------------------------------------------------------------------
BOOL IsPopupBarTracking() const;
protected:
//{{AFX_CODEJOCK_PRIVATE
void OnClick(BOOL bKeyboard = FALSE, CPoint pt = CPoint(0, 0));
void ShowPopupBar(BOOL bKeyboard);
BOOL OnSetPopup(BOOL bPopup);
void SetEnabled(BOOL bEnabled);
CString GetItemTooltip(const CXTPTabManagerItem* pItem) const;
virtual void AdjustExcludeRect(CRect& rc, BOOL bVertical);
//}}AFX_CODEJOCK_PRIVATE
protected:
//{{AFX_CODEJOCK_PRIVATE
virtual HRESULT GetAccessibleChildCount(long* pcountChildren);
virtual HRESULT GetAccessibleChild(VARIANT varChild, IDispatch** ppdispChild);
virtual HRESULT GetAccessibleName(VARIANT varChild, BSTR* pszName);
virtual HRESULT GetAccessibleRole(VARIANT varChild, VARIANT* pvarRole);
virtual HRESULT AccessibleLocation(long *pxLeft, long *pyTop, long *pcxWidth, long* pcyHeight, VARIANT varChild);
virtual HRESULT AccessibleHitTest(long xLeft, long yTop, VARIANT* pvarChild);
virtual HRESULT GetAccessibleState(VARIANT varChild, VARIANT* pvarState);
virtual HRESULT GetAccessibleDefaultAction(VARIANT varChild, BSTR* pszDefaultAction);
virtual HRESULT AccessibleDoDefaultAction(VARIANT varChild);
virtual HRESULT AccessibleSelect(long flagsSelect, VARIANT varChild);
//}}AFX_CODEJOCK_PRIVATE
protected:
BOOL m_bFocused; // TRUE if groups focused
friend class CXTPRibbonBar;
};
AFX_INLINE CXTPRibbonBar* CXTPRibbonControlTab::GetRibbonBar() const {
return (CXTPRibbonBar*)m_pParent;
}
#endif // !defined(__XTPRIBBONCONTROLTAB_H__)
| [
"david.dehilster@lexisnexisrisk.com"
] | david.dehilster@lexisnexisrisk.com |
9574425ae637bb6ebc4a6a2f6f6fd61b536388c9 | 52e1e9d04f59f391bc6710c0e09ea84ce88f6e0c | /atom.cpp | 346bfe07795998c4c2183a03c418ebae85c40a0d | [] | no_license | vavachan/MONTE_CARLO_HARDSPHERE | 3909fee4104bf2999f3159f26d88830b11508769 | 0d7188efcee6e25a7547379f977a8cfc58b6bd55 | refs/heads/master | 2020-06-12T09:34:18.047969 | 2017-05-24T04:26:31 | 2017-05-24T04:26:31 | 75,591,982 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 659 | cpp | #include "atom.hpp"
#include<iostream>
void atom::update_neighbour(int neigh) {
neigh_list[index]=neigh;
index++;
}
void atom::close_update_neighbour(int neigh) {
close_neigh_list[close_index]=neigh;
close_index++;
}
void atom::close_reset() {
// neighbours=0;
close_neighbours=0;
////////for(int i=0;i<180;i++)
//////// neigh_list[i]=0;
for(int i=0;i<50;i++)
close_neigh_list[i]=0;
// index=0;
close_index=0;
}
void atom::reset() {
neighbours=0;
// close_neighbours=0;
for(int i=0;i<180;i++)
neigh_list[i]=0;
////////for(int i=0;i<50;i++)
//////// close_neigh_list[i]=0;
index=0;
// close_index=0;
}
| [
"varghese.i.am@gmail.com"
] | varghese.i.am@gmail.com |
dfeb7707f6ec8c9f3eccef081b28c66dd02603e1 | e6e6c81568e0f41831a85490895a7cf5c929d50e | /yukicoder/6/60.cpp | 8813330a78dc4f28a8604b8d8fb7a6e5b797dfee | [] | no_license | mint6421/kyopro | 69295cd06ff907cd6cc43887ce964809aa2534d9 | f4ef43669352d84bd32e605a40f75faee5358f96 | refs/heads/master | 2021-07-02T04:57:13.566704 | 2020-10-23T06:51:20 | 2020-10-23T06:51:20 | 182,088,856 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,304 | cpp |
#include<bits/stdc++.h>
using namespace std;
#define inf INT_MAX
#define INF LLONG_MAX
#define ll long long
#define ull unsigned long long
#define M (int)(1e9+7)
#define P pair<int,int>
#define PLL pair<ll,ll>
#define FOR(i,m,n) for(int i=(int)m;i<(int)n;i++)
#define RFOR(i,m,n) for(int i=(int)m;i>=(int)n;i--)
#define rep(i,n) FOR(i,0,n)
#define rrep(i,n) RFOR(i,n,0)
#define all(a) a.begin(),a.end()
#define IN(a,n) rep(i,n){ cin>>a[i]; }
const int vx[4] = {0,1,0,-1};
const int vy[4] = {1,0,-1,0};
#define PI 3.14159265
#define F first
#define S second
#define PB push_back
#define EB emplace_back
#define int ll
#define vi vector<int>
int c[1100][1100];
signed main(){
cin.tie(0);
ios::sync_with_stdio(false);
int n,k;
cin>>n>>k;
vi x(n),y(n),hp(n);
rep(i,n){
cin>>x[i]>>y[i]>>hp[i];
x[i]+=500;
y[i]+=500;
}
rep(i,k){
int ax,ay,w,h,d;
cin>>ax>>ay>>w>>h>>d;
ax+=500;
ay+=500;
c[ay][ax]+=d;
c[ay][min(1010LL,ax+w+1)]-=d;
c[min(1010LL,ay+h+1)][ax]-=d;
c[min(1010LL,ay+h+1)][min(1010LL,ax+w+1)]+=d;
}
rep(i,1000){
rep(j,1000){
c[i][j+1]+=c[i][j];
}
}
rep(j,1010){
rep(i,1010){
c[i+1][j]+=c[i][j];
}
}
int ans=0;
rep(i,n){
ans+=max(0LL,hp[i]-c[y[i]][x[i]]);
}
cout<<ans<<endl;
}
| [
"distout.215@gmail.com"
] | distout.215@gmail.com |
4e884b332f457fee8a0b581ecf9d5b85d302f490 | fa1445f3f23d2dcee4938ff73a543d9aae235799 | /SDK/FN_PowerToastWidget_classes.hpp | 78ff85edfd27e7b3419466ba183b3934a0423972 | [] | no_license | chuhanpu/FNFUN | ac6d750037514bdfb3b1baa50830c9bce60ed85a | 8326ae28b844f4d9ee38f3c64bb056e81106fdd3 | refs/heads/master | 2021-07-15T07:18:42.180136 | 2017-10-18T20:24:55 | 2017-10-18T20:24:55 | 107,524,245 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,182 | hpp | #pragma once
// Fortnite SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// WidgetBlueprintGeneratedClass PowerToastWidget.PowerToastWidget_C
// 0x0091 (0x02F1 - 0x0260)
class UPowerToastWidget_C : public UFortPlayerTrackerBase
{
public:
struct FPointerToUberGraphFrame UberGraphFrame; // 0x0260(0x0008) (CPF_Transient, CPF_DuplicateTransient)
class UWidgetAnimation* LookAtMe; // 0x0268(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_BlueprintReadOnly, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_RepNotify, CPF_Interp, CPF_NonTransactional, CPF_EditorOnly, CPF_NoDestructor, CPF_AutoWeak, CPF_ContainsInstancedReference, CPF_AssetRegistrySearchable, CPF_SimpleDisplay, CPF_AdvancedDisplay, CPF_Protected, CPF_BlueprintCallable, CPF_BlueprintAuthorityOnly, CPF_TextExportTransient, CPF_NonPIEDuplicateTransient, CPF_ExposeOnSpawn, CPF_PersistentInstance, CPF_UObjectWrapper, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic, CPF_NativeAccessSpecifierProtected, CPF_NativeAccessSpecifierPrivate)
class UWidgetAnimation* Outro; // 0x0270(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_BlueprintReadOnly, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_RepNotify, CPF_Interp, CPF_NonTransactional, CPF_EditorOnly, CPF_NoDestructor, CPF_AutoWeak, CPF_ContainsInstancedReference, CPF_AssetRegistrySearchable, CPF_SimpleDisplay, CPF_AdvancedDisplay, CPF_Protected, CPF_BlueprintCallable, CPF_BlueprintAuthorityOnly, CPF_TextExportTransient, CPF_NonPIEDuplicateTransient, CPF_ExposeOnSpawn, CPF_PersistentInstance, CPF_UObjectWrapper, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic, CPF_NativeAccessSpecifierProtected, CPF_NativeAccessSpecifierPrivate)
class UWidgetAnimation* Intro; // 0x0278(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_BlueprintReadOnly, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_RepNotify, CPF_Interp, CPF_NonTransactional, CPF_EditorOnly, CPF_NoDestructor, CPF_AutoWeak, CPF_ContainsInstancedReference, CPF_AssetRegistrySearchable, CPF_SimpleDisplay, CPF_AdvancedDisplay, CPF_Protected, CPF_BlueprintCallable, CPF_BlueprintAuthorityOnly, CPF_TextExportTransient, CPF_NonPIEDuplicateTransient, CPF_ExposeOnSpawn, CPF_PersistentInstance, CPF_UObjectWrapper, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic, CPF_NativeAccessSpecifierProtected, CPF_NativeAccessSpecifierPrivate)
class UCommonTextBlock* BoostedPower; // 0x0280(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_RepNotify, CPF_Interp, CPF_NonTransactional, CPF_EditorOnly, CPF_NoDestructor, CPF_AutoWeak, CPF_ContainsInstancedReference, CPF_AssetRegistrySearchable, CPF_SimpleDisplay, CPF_AdvancedDisplay, CPF_Protected, CPF_BlueprintCallable, CPF_BlueprintAuthorityOnly, CPF_TextExportTransient, CPF_NonPIEDuplicateTransient, CPF_ExposeOnSpawn, CPF_PersistentInstance, CPF_UObjectWrapper, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic, CPF_NativeAccessSpecifierProtected, CPF_NativeAccessSpecifierPrivate)
class UCommonTextBlock* Description; // 0x0288(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_RepNotify, CPF_Interp, CPF_NonTransactional, CPF_EditorOnly, CPF_NoDestructor, CPF_AutoWeak, CPF_ContainsInstancedReference, CPF_AssetRegistrySearchable, CPF_SimpleDisplay, CPF_AdvancedDisplay, CPF_Protected, CPF_BlueprintCallable, CPF_BlueprintAuthorityOnly, CPF_TextExportTransient, CPF_NonPIEDuplicateTransient, CPF_ExposeOnSpawn, CPF_PersistentInstance, CPF_UObjectWrapper, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic, CPF_NativeAccessSpecifierProtected, CPF_NativeAccessSpecifierPrivate)
class UImage* Image_3; // 0x0290(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_RepNotify, CPF_Interp, CPF_NonTransactional, CPF_EditorOnly, CPF_NoDestructor, CPF_AutoWeak, CPF_ContainsInstancedReference, CPF_AssetRegistrySearchable, CPF_SimpleDisplay, CPF_AdvancedDisplay, CPF_Protected, CPF_BlueprintCallable, CPF_BlueprintAuthorityOnly, CPF_TextExportTransient, CPF_NonPIEDuplicateTransient, CPF_ExposeOnSpawn, CPF_PersistentInstance, CPF_UObjectWrapper, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic, CPF_NativeAccessSpecifierProtected, CPF_NativeAccessSpecifierPrivate)
class UImage* Image_Power; // 0x0298(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_RepNotify, CPF_Interp, CPF_NonTransactional, CPF_EditorOnly, CPF_NoDestructor, CPF_AutoWeak, CPF_ContainsInstancedReference, CPF_AssetRegistrySearchable, CPF_SimpleDisplay, CPF_AdvancedDisplay, CPF_Protected, CPF_BlueprintCallable, CPF_BlueprintAuthorityOnly, CPF_TextExportTransient, CPF_NonPIEDuplicateTransient, CPF_ExposeOnSpawn, CPF_PersistentInstance, CPF_UObjectWrapper, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic, CPF_NativeAccessSpecifierProtected, CPF_NativeAccessSpecifierPrivate)
class UImage* LineSeparator; // 0x02A0(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_RepNotify, CPF_Interp, CPF_NonTransactional, CPF_EditorOnly, CPF_NoDestructor, CPF_AutoWeak, CPF_ContainsInstancedReference, CPF_AssetRegistrySearchable, CPF_SimpleDisplay, CPF_AdvancedDisplay, CPF_Protected, CPF_BlueprintCallable, CPF_BlueprintAuthorityOnly, CPF_TextExportTransient, CPF_NonPIEDuplicateTransient, CPF_ExposeOnSpawn, CPF_PersistentInstance, CPF_UObjectWrapper, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic, CPF_NativeAccessSpecifierProtected, CPF_NativeAccessSpecifierPrivate)
class UPlayerBanner_C* PlayerBanner; // 0x02A8(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_RepNotify, CPF_Interp, CPF_NonTransactional, CPF_EditorOnly, CPF_NoDestructor, CPF_AutoWeak, CPF_ContainsInstancedReference, CPF_AssetRegistrySearchable, CPF_SimpleDisplay, CPF_AdvancedDisplay, CPF_Protected, CPF_BlueprintCallable, CPF_BlueprintAuthorityOnly, CPF_TextExportTransient, CPF_NonPIEDuplicateTransient, CPF_ExposeOnSpawn, CPF_PersistentInstance, CPF_UObjectWrapper, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic, CPF_NativeAccessSpecifierProtected, CPF_NativeAccessSpecifierPrivate)
class UImage* PowerIconGlow; // 0x02B0(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_RepNotify, CPF_Interp, CPF_NonTransactional, CPF_EditorOnly, CPF_NoDestructor, CPF_AutoWeak, CPF_ContainsInstancedReference, CPF_AssetRegistrySearchable, CPF_SimpleDisplay, CPF_AdvancedDisplay, CPF_Protected, CPF_BlueprintCallable, CPF_BlueprintAuthorityOnly, CPF_TextExportTransient, CPF_NonPIEDuplicateTransient, CPF_ExposeOnSpawn, CPF_PersistentInstance, CPF_UObjectWrapper, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic, CPF_NativeAccessSpecifierProtected, CPF_NativeAccessSpecifierPrivate)
class UCommonTextBlock* TeamMemberPower; // 0x02B8(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_RepNotify, CPF_Interp, CPF_NonTransactional, CPF_EditorOnly, CPF_NoDestructor, CPF_AutoWeak, CPF_ContainsInstancedReference, CPF_AssetRegistrySearchable, CPF_SimpleDisplay, CPF_AdvancedDisplay, CPF_Protected, CPF_BlueprintCallable, CPF_BlueprintAuthorityOnly, CPF_TextExportTransient, CPF_NonPIEDuplicateTransient, CPF_ExposeOnSpawn, CPF_PersistentInstance, CPF_UObjectWrapper, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic, CPF_NativeAccessSpecifierProtected, CPF_NativeAccessSpecifierPrivate)
class UCommonTextBlock* Title; // 0x02C0(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_RepNotify, CPF_Interp, CPF_NonTransactional, CPF_EditorOnly, CPF_NoDestructor, CPF_AutoWeak, CPF_ContainsInstancedReference, CPF_AssetRegistrySearchable, CPF_SimpleDisplay, CPF_AdvancedDisplay, CPF_Protected, CPF_BlueprintCallable, CPF_BlueprintAuthorityOnly, CPF_TextExportTransient, CPF_NonPIEDuplicateTransient, CPF_ExposeOnSpawn, CPF_PersistentInstance, CPF_UObjectWrapper, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic, CPF_NativeAccessSpecifierProtected, CPF_NativeAccessSpecifierPrivate)
class UFortUINotification* ToastNotification; // 0x02C8(0x0008) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
float AnimationFinishedDelay; // 0x02D0(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
unsigned char UnknownData00[0x4]; // 0x02D4(0x0004) MISSED OFFSET
struct FScriptMulticastDelegate OnFinishedToast; // 0x02D8(0x0010) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_BlueprintAssignable)
struct FTimerHandle AnimationDelayTimer; // 0x02E8(0x0008) (CPF_Edit, CPF_BlueprintVisible, CPF_DisableEditOnInstance)
bool Show_Toast; // 0x02F0(0x0001) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
static UClass* StaticClass()
{
static UClass* ptr = nullptr;
if (!ptr) ptr = UObject::FindClass(0xa61c0095);
return ptr;
}
void StartIntro();
void ShowText(const struct FText& Text, class UCommonTextBlock* TextBlock);
void SetToast(class UFortUINotification* Toast);
void HandleIntroFinished();
void HandleOutroFinished();
void HandleAnimationDelay();
void OnMouseEnter(struct FGeometry* MyGeometry, struct FPointerEvent* MouseEvent);
void OnMouseLeave(struct FPointerEvent* MouseEvent);
void BndEvt__OpenButton_K2Node_ComponentBoundEvent_5_CommonButtonClicked__DelegateSignature(class UCommonButton* Button);
void OnPlayerInfoChanged(struct FFortTeamMemberInfo* NewInfo);
void Construct();
void BndEvt__Intro_K2Node_ComponentBoundEvent_0_OnWidgetAnimationPlaybackStatusChanged__DelegateSignature();
void BndEvt__Outro_K2Node_ComponentBoundEvent_1_OnWidgetAnimationPlaybackStatusChanged__DelegateSignature();
void OnTeamMemberFinishedSynchronizing_Event_1(const struct FUniqueNetIdRepl& NewTeamMemberId);
void ExecuteUbergraph_PowerToastWidget(int EntryPoint);
void OnFinishedToast__DelegateSignature();
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"tj8@live.com.au"
] | tj8@live.com.au |
fd088cb609508216727bb56bb0a30a0d31e079a7 | 23a5d39b3c9b171af32970fe0b0ad3e5c9ce9429 | /cpp/removeDuplicatesFromSortedArray.cpp | 4f2f1ee25db3ac008ea0d6a82791321a81683ba3 | [] | no_license | kellytay143/leetcode | 2e113b5268289f0be44e819cba3ffb22f8bb7aeb | 0e7ebc4762256f38f60baef1a2bf54aa2f6d0430 | refs/heads/master | 2023-02-24T22:16:32.001010 | 2021-01-31T02:46:44 | 2021-01-31T02:46:44 | 291,169,100 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 825 | cpp | // Source: https://leetcode.com/problems/remove-duplicates-from-sorted-array/
// Author: Kelly Tay
// Date: 12/20/2020
/**
Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
**/
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int length = 0;
if(nums.empty()) {
return length;
}
length++;
for(int i = 1, j = 0; i < nums.size() && j < nums.size(); i++) {
if(nums[i] != nums[j]) {
length++;
j++;
nums[j] = nums[i];
}
}
return length;
}
}; | [
"kellytay@Kellys-MacBook-Pro.local"
] | kellytay@Kellys-MacBook-Pro.local |
096a5401ee0339c9ab4e56c32affb0edac05fa72 | 5a4573bf0c3be68901f9d2a2a49e7a23c66a6629 | /main.cpp | d5ba1334fb0071fbacfc59ae0adb65bab6fb435e | [] | no_license | braaahaaarararaga/GL_OPENGL_SKINMESH | 34f55a98c6daad6c9b4e0f98e70af908c180987a | cad8c91d95318dd038de7a142d32b66056f6724e | refs/heads/master | 2020-07-31T07:38:22.354357 | 2019-09-26T05:57:05 | 2019-09-26T05:57:05 | 210,532,697 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 5,104 | cpp |
#include "main.h"
#include "manager.h"
#include "renderer.h"
#include "polygon.h"
#include "camera.h"
#include "field.h"
#include "cube.h"
#include "input.h"
#include "light.h"
#include "model.h"
#include "modelAnimation.h"
#include "resource.h"
#include <memory>
const char* CLASS_NAME = "OpenGALAppClass";
const char* WINDOW_NAME = "OpenGAY";
LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
HWND g_Window;
HWND GetWindow()
{
return g_Window;
}
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
WNDCLASSEX wcex =
{
sizeof(WNDCLASSEX),
CS_CLASSDC,
WndProc,
0,
0,
hInstance,
NULL,
LoadCursor(NULL, IDC_ARROW),
(HBRUSH)(COLOR_WINDOW + 1),
MAKEINTRESOURCE(IDR_MENU1),
CLASS_NAME,
NULL
};
// ウィンドウクラスの登録
RegisterClassEx(&wcex);
// ウィンドウの作成
g_Window = CreateWindowEx(0,
CLASS_NAME,
WINDOW_NAME,
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
(SCREEN_WIDTH + GetSystemMetrics(SM_CXDLGFRAME) * 2),
(SCREEN_HEIGHT + GetSystemMetrics(SM_CXDLGFRAME) * 2 + GetSystemMetrics(SM_CYCAPTION) + GetSystemMetrics(SM_CYMENU)),
NULL,
NULL,
hInstance,
NULL);
// 初期化処理(ウィンドウを作成してから行う)
Init(g_Window);
// ウインドウの表示(初期化処理の後に行う)
ShowWindow(g_Window, nCmdShow);
UpdateWindow(g_Window);
//フレームカウント初期化
DWORD dwExecLastTime;
DWORD dwCurrentTime;
timeBeginPeriod(1);
dwExecLastTime = timeGetTime();
dwCurrentTime = 0;
// メッセージループ
MSG msg;
while(1)
{
if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if(msg.message == WM_QUIT)
{// PostQuitMessage()が呼ばれたらループ終了
break;
}
else
{
// メッセージの翻訳とディスパッチ
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
else
{
dwCurrentTime = timeGetTime();
if((dwCurrentTime - dwExecLastTime) >= (1000 / 60))
{
dwExecLastTime = dwCurrentTime;
// 更新処理
Update();
// 描画処理
Draw();
}
}
}
timeEndPeriod(1); // 分解能を戻す
// ウィンドウクラスの登録を解除
UnregisterClass(CLASS_NAME, wcex.hInstance);
// 終了処理
Uninit();
return (int)msg.wParam;
}
//=============================================================================
// ウインドウプロシージャ
//=============================================================================
LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch(uMsg)
{
case WM_ACTIVATEAPP:
Keyboard::ProcessMessage(uMsg, wParam, lParam);
case WM_INPUT:
case WM_MOUSEMOVE:
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
case WM_RBUTTONDOWN:
case WM_RBUTTONUP:
case WM_MBUTTONDOWN:
case WM_MBUTTONUP:
case WM_MOUSEWHEEL:
case WM_XBUTTONDOWN:
case WM_XBUTTONUP:
case WM_MOUSEHOVER:
Mouse::ProcessMessage(uMsg, wParam, lParam);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_KEYDOWN:
switch (wParam)
{
case VK_ESCAPE:
DestroyWindow(hWnd);
break;
}
case WM_SYSKEYDOWN:
case WM_KEYUP:
case WM_SYSKEYUP:
Keyboard::ProcessMessage(uMsg, wParam, lParam);
break;
case WM_COMMAND:
{
switch (LOWORD(wParam))
{
case ID_BUTT_PUBE:
MessageBoxA(g_Window, "DONT TOUCH PUBE!!", "CAPTION", MB_OK);
break;
case ID_BUTT_CLICK:
MessageBoxA(g_Window, "pubeは恥骨の意味だよん〜", "CAPTION", MB_OK);
break;
case ID_BOX2_X1:
{
OPENFILENAME of;
char fileName[MAX_PATH];
ZeroMemory(fileName, MAX_PATH);
memset(&of, 0, sizeof(of));
of.lStructSize = sizeof(of);
of.hwndOwner = g_Window;
of.lpstrFilter = "FBXファイル(*.fbx)\0*.fbx\0";
of.lpstrTitle = "Open";
of.lpstrFile = fileName;
of.nMaxFile = MAX_PATH;
of.Flags = OFN_PATHMUSTEXIST;
of.lpstrDefExt = "fbx";
if (GetOpenFileName(&of))
{
LoadModel(fileName);
}
break;
}
default:
break;
}
}
default:
break;
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
// Drag Drop
// case : WM_CREATE:
// { DragAcceptFiles(window, TRUE); break;}
// .. case WM_DROPFILES:
// { HDROP drop = (HDROP)wParam;
// char fileName[MAX_PATH];
// DragQueryFileA(Drop, 0, fileName, MAX_PATH); ... break ;}
std::unique_ptr<ModelAnimation> model;
Camera3D* camera;
void Init(HWND wnd)
{
CInput::Init();
InitRenderer(wnd);
InitModel();
model = std::make_unique<ModelAnimation>("./asset/Model/mixamo/Walking2.fbx");
InitPolygon();
camera = new Camera3D();
}
void Uninit()
{
UninitModel();
CInput::Uninit();
model.release();
UninitRenderer();
delete camera;
}
void Update()
{
UpdateModel();
model->Update();
camera->Update();
CInput::Update();
}
void LoadModel(const char* filepath)
{
model.release();
model = std::make_unique<ModelAnimation>(filepath);
}
void Draw()
{
BeginRenderer();
camera->Draw();
SetLight();
//DrawCube();
DrawModel();
model->Draw();
DrawField();
DrawPolygon();
EndRenderer();
} | [
"ri.syouei.as@gmail.com"
] | ri.syouei.as@gmail.com |
efe0d3c3d7f9250a3509d4dee4e1151fbf588100 | e8c0bbb5be26f82f8956728d356d0d9b70e1a3b0 | /RTreeGUI/RTreeScene.h | b372235c9a6522768c3b0bfd43fdae850dbc39db | [] | no_license | MarkVTech/BoostGeometryExperiment | 82ab2290915f059822d6a05bc6b57b28262bf588 | 40d925e21e03e20954b8756fd976abda09cd4729 | refs/heads/master | 2023-04-07T04:26:31.567428 | 2023-03-23T19:25:25 | 2023-03-23T19:25:25 | 285,857,554 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 856 | h | #pragma once
#include <QGraphicsScene>
class QGraphicsRectItem;
class RTreeScene : public QGraphicsScene
{
Q_OBJECT
public:
RTreeScene(QObject* parent=nullptr);
void setMode(const QString& mode);
// QGraphicsScene interface
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override;
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override;
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override;
signals:
void selectionAreaChanged(const QRectF& selectionRect);
void mouseMove(double x, double y);
private:
QGraphicsRectItem *mSelectionRectItem = nullptr;
QPointF mFirstPoint;
QPointF mSecondPoint;
QRectF mSelectionRect;
QString mMode = "box";
};
| [
"mwilson1962@gmail.com"
] | mwilson1962@gmail.com |
a0cfbfa600259bf36fff0f59efedc5bbcae74e6c | 230fb8845f39bef0f30f5d3541eff5dc0641de14 | /Connect3/Export/windows/obj/include/haxe/ui/components/_Stepper/IncBehaviour.h | bb8807885c58b8342a98ef2005671a8408055107 | [] | no_license | vhlk/AlgoritmoMinMax | 76abd62a6e2859ed229e5831264b6d8af27e318d | 40eded4948794ca48d50d16d2133a9ab21207768 | refs/heads/main | 2023-06-30T15:16:17.492478 | 2021-08-02T13:29:32 | 2021-08-02T13:29:32 | 390,493,745 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 2,928 | h | // Generated by Haxe 4.2.0
#ifndef INCLUDED_haxe_ui_components__Stepper_IncBehaviour
#define INCLUDED_haxe_ui_components__Stepper_IncBehaviour
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
#ifndef INCLUDED_haxe_ui_behaviours_Behaviour
#include <haxe/ui/behaviours/Behaviour.h>
#endif
HX_DECLARE_CLASS3(haxe,ui,backend,ComponentBase)
HX_DECLARE_CLASS3(haxe,ui,backend,ComponentImpl)
HX_DECLARE_CLASS3(haxe,ui,behaviours,Behaviour)
HX_DECLARE_CLASS4(haxe,ui,components,_Stepper,IncBehaviour)
HX_DECLARE_CLASS3(haxe,ui,core,Component)
HX_DECLARE_CLASS3(haxe,ui,core,ComponentBounds)
HX_DECLARE_CLASS3(haxe,ui,core,ComponentCommon)
HX_DECLARE_CLASS3(haxe,ui,core,ComponentContainer)
HX_DECLARE_CLASS3(haxe,ui,core,ComponentEvents)
HX_DECLARE_CLASS3(haxe,ui,core,ComponentLayout)
HX_DECLARE_CLASS3(haxe,ui,core,ComponentValidation)
HX_DECLARE_CLASS3(haxe,ui,core,IClonable)
HX_DECLARE_CLASS3(haxe,ui,core,IComponentBase)
HX_DECLARE_CLASS3(haxe,ui,util,VariantType)
HX_DECLARE_CLASS3(haxe,ui,validation,IValidating)
HX_DECLARE_CLASS2(openfl,display,DisplayObject)
HX_DECLARE_CLASS2(openfl,display,DisplayObjectContainer)
HX_DECLARE_CLASS2(openfl,display,IBitmapDrawable)
HX_DECLARE_CLASS2(openfl,display,InteractiveObject)
HX_DECLARE_CLASS2(openfl,display,Sprite)
HX_DECLARE_CLASS2(openfl,events,EventDispatcher)
HX_DECLARE_CLASS2(openfl,events,IEventDispatcher)
namespace haxe{
namespace ui{
namespace components{
namespace _Stepper{
class HXCPP_CLASS_ATTRIBUTES IncBehaviour_obj : public ::haxe::ui::behaviours::Behaviour_obj
{
public:
typedef ::haxe::ui::behaviours::Behaviour_obj super;
typedef IncBehaviour_obj OBJ_;
IncBehaviour_obj();
public:
enum { _hx_ClassId = 0x79c185a9 };
void __construct( ::haxe::ui::core::Component component);
inline void *operator new(size_t inSize, bool inContainer=true,const char *inName="haxe.ui.components._Stepper.IncBehaviour")
{ return ::hx::Object::operator new(inSize,inContainer,inName); }
inline void *operator new(size_t inSize, int extra)
{ return ::hx::Object::operator new(inSize+extra,true,"haxe.ui.components._Stepper.IncBehaviour"); }
static ::hx::ObjectPtr< IncBehaviour_obj > __new( ::haxe::ui::core::Component component);
static ::hx::ObjectPtr< IncBehaviour_obj > __alloc(::hx::Ctx *_hx_ctx, ::haxe::ui::core::Component component);
static void * _hx_vtable;
static Dynamic __CreateEmpty();
static Dynamic __Create(::hx::DynamicArray inArgs);
//~IncBehaviour_obj();
HX_DO_RTTI_ALL;
::hx::Val __Field(const ::String &inString, ::hx::PropertyAccess inCallProp);
static void __register();
bool _hx_isInstanceOf(int inClassId);
::String __ToString() const { return HX_("IncBehaviour",9f,85,73,53); }
::haxe::ui::util::VariantType call( ::Dynamic param);
};
} // end namespace haxe
} // end namespace ui
} // end namespace components
} // end namespace _Stepper
#endif /* INCLUDED_haxe_ui_components__Stepper_IncBehaviour */
| [
"vhlk@cin.ufpe.br"
] | vhlk@cin.ufpe.br |
101ae1e3d090d475b0a0cc594adf4268f4042226 | 62400f20b4d4aa8e51cd72805e258470e99c5dcf | /Network - Client/networkManager.cpp | 53eebec271b7c769c7c56441f95fa442c3ee18e4 | [] | no_license | Rhanjie/Network---TheGame | 2860e1a5091695da1da8cec741c072b4c0dccfaf | 6ad43a583455c17e4a1904d60104dd16cfba98f9 | refs/heads/master | 2016-08-07T11:52:24.346820 | 2015-06-03T20:11:06 | 2015-06-03T20:11:06 | 30,471,894 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 865 | cpp | #include "networkManager.hpp"
bool rha::cNetworkManager::sendPacket(sf::TcpSocket* socket, sf::Packet* packet){
if(socket->send(*packet)==sf::Socket::Done)
return true;
else return false;
}
bool rha::cNetworkManager::sendRawPacket(sf::TcpSocket* socket, rha::typePacketsInClient typePacket){
sPacket<<typePacket;
if(socket->send(sPacket)==sf::Socket::Done){sPacket.clear(); return true;}
else{sPacket.clear(); return false;}
}
bool rha::cNetworkManager::receivePacket(sf::TcpSocket* socket){
if(socket->receive(this->dataPacket)==sf::Socket::Done){
if(this->dataPacket>>converter){
tLastPacketReceive=static_cast<rha::typePacketsInServer>(converter);
return true;
} else return false;
}else{tLastPacketReceive=rha::typePacketsInServer::NORMAL_SERVER_NULL;
return false;
}
}
| [
"mdyla99@interia.pl"
] | mdyla99@interia.pl |
a9f9b37592c25a0e26443e7861fe6dd560eec9e2 | d7dcdff7a24b8600066626c77cf0eebdc0b45f1f | /src/SpeechStuff.cpp | a62c45adafc3f5256a3a35aceb5b1c2af8d94db7 | [
"MIT"
] | permissive | rethesda/playerTextToSpeechSSE | ff709af82fe2401f95403865b473cb348853b93a | 3e546882f15a545ab14f400748746ed8956ca788 | refs/heads/master | 2023-08-04T12:21:59.753233 | 2021-09-14T21:30:52 | 2021-09-14T21:30:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,098 | cpp | //
// Created by peter on 7/27/21.
//
std::vector<ISpObjectToken*> gVoices;
ISpVoice* gVoice = nullptr;
// Default settings - should match those in Papyrus
bool gModEnabled = true;
uint32_t gPlayerVoiceID = 0;
uint32_t gPlayerVoiceVolume = 50;
int32_t gPlayerVoiceRateAdjust = 0;
/*************************
** Player speech state **
**************************/
enum PlayerSpeechState {
TOPIC_NOT_SELECTED = 0,
TOPIC_SELECTED = 1,
TOPIC_SPOKEN = 2
};
struct PlayerSpeech {
PlayerSpeechState state;
bool isNPCSpeechDelayed;
uint32_t option;
};
PlayerSpeech* gPlayerSpeech = nullptr;
void initializePlayerSpeech() {
if (gPlayerSpeech == nullptr) {
gPlayerSpeech = new PlayerSpeech();
gPlayerSpeech->state = TOPIC_NOT_SELECTED;
gPlayerSpeech->isNPCSpeechDelayed = false;
}
}
/***************************************************
** Event handling for when TTS finished speaking **
****************************************************/
void TopicSpokenEventDelegateFn() {
//uint32_t setTopic = 0x006740E0;
//uint32_t sayTopicResponse = 0x006741B0;
if (gPlayerSpeech->state == TOPIC_SELECTED) {
gPlayerSpeech->state = TOPIC_SPOKEN;
gPlayerSpeech->isNPCSpeechDelayed = false;
// Here's the fun part: once TTS stopped speaking, we have to set the topic again,
// then speak it. It's already done on the first click event, but we're ignoring it
// with our onDialogueSayHook to allow TTS to speak.
//RE::MenuTopicManager* mtm = RE::MenuTopicManager::GetSingleton();
//thisCall<void>(mtm, setTopic, gPlayerSpeech->option);
//thisCall<void>(mtm, sayTopicResponse, 0, 0);
}
}
void executeVoiceNotifyThread() {
CSpEvent evt;
HANDLE voiceNotifyHandle = gVoice->GetNotifyEventHandle();
do {
WaitForSingleObject(voiceNotifyHandle, INFINITE);
while (gVoice != nullptr && evt.GetFrom(gVoice) == S_OK) {
if (evt.eEventId == SPEI_END_INPUT_STREAM) {
SKSE::GetTaskInterface()->AddTask(TopicSpokenEventDelegateFn);
}
}
} while (gVoice != nullptr);
}
/********************************************
** Initializing voices and setting up TTS **
*********************************************/
std::vector<ISpObjectToken*> getVoices() {
std::vector<ISpObjectToken*> voiceObjects;
ULONG voiceCount = 0;
ISpObjectToken* voiceObject;
IEnumSpObjectTokens* enumVoiceObjects;
SpEnumTokens(SPCAT_VOICES, nullptr, nullptr, &enumVoiceObjects);
enumVoiceObjects->GetCount(&voiceCount);
HRESULT hr = S_OK;
ULONG i = 0;
while (SUCCEEDED(hr) && i < voiceCount) {
hr = enumVoiceObjects->Item(i, &voiceObject);
voiceObjects.push_back(voiceObject);
i++;
}
enumVoiceObjects->Release();
return voiceObjects;
}
ULONG getVoicesCount() {
ULONG voiceCount = 0;
IEnumSpObjectTokens* enumVoiceObjects;
SpEnumTokens(SPCAT_VOICES, nullptr, nullptr, &enumVoiceObjects);
enumVoiceObjects->GetCount(&voiceCount);
enumVoiceObjects->Release();
return voiceCount;
}
void initializeVoices() {
if (gVoice == nullptr) {
gVoices = getVoices();
if (FAILED(CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED))) {
//_MESSAGE("Problem: CoInitializeEx failed");
logger::error<>("Problem: CoCreateInstance failed");
}
else if (FAILED(CoCreateInstance(CLSID_SpVoice, nullptr, CLSCTX_ALL, IID_ISpVoice, (void **)&gVoice))) {
//_MESSAGE("Problem: CoCreateInstance failed");
logger::error<>("Problem: CoCreateInstance failed");
}
CoUninitialize();
ULONGLONG eventTypes = SPFEI(SPEI_END_INPUT_STREAM);
if (FAILED(gVoice->SetInterest(eventTypes, eventTypes))) {
//_MESSAGE("Problem: SetInterest failed");
logger::error<>("Problem: SetInterest failed");
}
CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)executeVoiceNotifyThread, nullptr, NULL, nullptr);
}
}
void speak(const char* message) {
auto masterVolumeSetting = RE::TESForm::LookupByID<RE::BGSSoundCategory>(0x000EB803)->GetCategoryVolume();
auto voiceVolumeSetting = RE::TESForm::LookupByID<RE::BGSSoundCategory>(0x000876BD)->GetCategoryVolume();
initializeVoices();
std::wstringstream messageStream;
messageStream << message;
// Volume is set every time because master / voice volume might have changed
gVoice->SetVolume((u_short)round((float)gPlayerVoiceVolume * static_cast<float>(masterVolumeSetting) * (voiceVolumeSetting)));
gVoice->Speak(messageStream.str().c_str(), SPF_ASYNC | SPF_IS_NOT_XML | SPF_PURGEBEFORESPEAK, nullptr);
}
void stopSpeaking() {
gVoice->Speak(L"", SPF_ASYNC | SPF_IS_NOT_XML | SPF_PURGEBEFORESPEAK, nullptr);
}
/*********************
** ON TOPIC SETTER **
**********************/
//x86
//BYTE* gOnTopicSetter = (BYTE*)0x00674113;
//x64
//uintptr_t gOnTopicSetter = 0x014056F910;
uintptr_t gOnTopicSetter;
uintptr_t gOnTopicSetterResume;
uintptr_t* gOnTopicSetterResumePtr = &gOnTopicSetterResume;
struct ObjectWithMessage {
const char* message;
};
struct ObjectWithObjectWithMessage {
ObjectWithMessage* object;
};
void onTopicSetterHook(RE::MenuTopicManager* object, uint32_t option)
{
if (!gModEnabled) {
return;
}
initializePlayerSpeech();
if (gPlayerSpeech->state == TOPIC_NOT_SELECTED || gPlayerSpeech->state == TOPIC_SPOKEN) {
gPlayerSpeech->state = TOPIC_SELECTED;
gPlayerSpeech->isNPCSpeechDelayed = false;
gPlayerSpeech->option = option;
speak(object->lastSelectedDialogue->topicText.c_str());
}
}
//__declspec(naked) void onTopicSetterHooked() {
// __asm {
// push edx
// mov edx, [esp+0xC] // The selected option is an argument to the function, and is still on the stack there
// pushad
// push edx
// push esi // `esi` register here contains a pointer to an object, containing
// // a pointer to another object with a pointer to the string of a chosen topic
// // (I didn't bother to figure out what this object is)
// call onTopicSetterHook
// popad
// pop edx
// jmp[gOnTopicSetterResume]
// }
//}
struct onTopicSetterHookedPatch :
Xbyak::CodeGenerator
{
explicit onTopicSetterHookedPatch(uintptr_t SetterHook,uintptr_t ResumePtr)
{
mov(rbx, ptr [rsp+0x98]);
//mov(edx,ptr [esp+0xC]);
//pushad();
//push(edx);
//push(esi);
push(rcx);
mov(rcx, rsi);
push(rax);
mov(rax, SetterHook);
call(rax);
pop(rax);
pop(rcx);
//popad();
//pop(edx);
mov(r15, ResumePtr);
mov(r15, ptr[r15]);
jmp(r15);
}
};
/***********************
** DIALOGUE SAY HOOK **
************************/
uintptr_t gOnDialogueSay;
uintptr_t gOnDialogueSayResume;
uintptr_t gOnDialogueSaySkip;
uintptr_t* gOnDialogueSayResumePtr = &gOnDialogueSayResume;
bool shouldDelayNPCSpeech() {
if (!gModEnabled) {
return false;
}
initializePlayerSpeech();
// This is for when the user wants to skip the convo by (usually vigorously) clicking
if (gPlayerSpeech->state == TOPIC_SELECTED && gPlayerSpeech->isNPCSpeechDelayed) {
gPlayerSpeech->state = TOPIC_NOT_SELECTED;
gPlayerSpeech->isNPCSpeechDelayed = false;
stopSpeaking();
}
else if (gPlayerSpeech->state == TOPIC_SELECTED) {
gPlayerSpeech->isNPCSpeechDelayed = true;
return true;
}
return false;
}
struct onDialogueSayHookedPatch :
Xbyak::CodeGenerator
{
explicit onDialogueSayHookedPatch(uintptr_t DelayTest,uintptr_t ResumePtr,uintptr_t SaySkip)
{
Xbyak::Label DELAY_NPC_SPEECH;
//pushad();
mov(ptr [rsp+0x20], ecx);
mov(rcx, rbx);
push(rcx);
mov(rcx,DelayTest);
call(rcx);
pop(rcx);
test(al,al);
jnz(DELAY_NPC_SPEECH);
//popad();
mov(rax, ResumePtr);
mov(rax, ptr[rax]);
jmp(rax);
L(DELAY_NPC_SPEECH);
mov(r8, SaySkip);
jmp(r8);
//popad();
}
};
//__declspec(naked) void onDialogueSayHooked() {
// __asm {
// pushad
// call shouldDelayNPCSpeech
// test al, al
// jnz DELAY_NPC_SPEECH // If we should delay NPC speech, go to some code after
// popad
// jmp[gOnDialogueSayResume]
//
// DELAY_NPC_SPEECH:
// popad
// jmp[gOnDialogueSaySkip]
// }
//}
/**********************************************
** Registered functions and their delegates **
**********************************************/
void SetVoiceFn() {
initializeVoices();
gVoice->SetVoice(gVoices[gPlayerVoiceID]);
}
void SetRateAdjustFn() {
initializeVoices();
gVoice->SetRate(gPlayerVoiceRateAdjust);
}
std::string getAvailableTTSVoices(RE::StaticFunctionTag*) {
std::vector<ISpObjectToken*> voices = getVoices(); // We can't just use `gVoices` because it's on another thread
std::vector<std::string> vmVoiceList;
WCHAR* szDesc{};
const char* szDescString;
size_t size = voices.size();
vmVoiceList.resize(size);
for (size_t i = 0; i < size; i++) {
SpGetDescription(voices[i], &szDesc);
_bstr_t szDescCommon(szDesc);
szDescString = szDescCommon;
vmVoiceList[i] = std::string(szDescString);
voices[i]->Release();
}
voices.clear();
auto joinedParts = boost::algorithm::join(vmVoiceList, "::");
return joinedParts;
}
uint32_t setModEnabled(RE::StaticFunctionTag*, bool modEnabled) {
gModEnabled = modEnabled;
return 1; // Pretty sure it'll be successful
}
int32_t setTTSPlayerVoiceID(RE::StaticFunctionTag*, int32_t id) {
int32_t isSuccessful = 1;
if (static_cast<uint32_t>(id) >= getVoicesCount()) {
id = 0;
isSuccessful = 0;
}
gPlayerVoiceID = id;
SKSE::GetTaskInterface()->AddTask(SetVoiceFn);
return isSuccessful;
}
int32_t setTTSPlayerVoiceVolume(RE::StaticFunctionTag*, int32_t volume) {
int32_t isSuccessful = 1;
if (volume > 100 || volume < 0) {
volume = 50;
isSuccessful = 0;
}
gPlayerVoiceVolume = volume;
return isSuccessful;
}
int32_t setTTSPlayerVoiceRateAdjust(RE::StaticFunctionTag*, int32_t rateAdjust) {
int32_t isSuccessful = 1;
if (rateAdjust < -10 || rateAdjust > 10) {
rateAdjust = 0;
isSuccessful = 0;
}
gPlayerVoiceRateAdjust = rateAdjust;
SKSE::GetTaskInterface()->AddTask(SetRateAdjustFn);
return isSuccessful;
}
bool registerFuncs(RE::BSScript::Internal::VirtualMachine* a_registry) {
a_registry->RegisterFunction("GetAvailableTTSVoices", "TTS_Voiced_Player_Dialogue_MCM_Script", getAvailableTTSVoices);
a_registry->RegisterFunction("SetTTSModEnabled", "TTS_Voiced_Player_Dialogue_MCM_Script", setModEnabled);
a_registry->RegisterFunction("SetTTSPlayerVoiceID", "TTS_Voiced_Player_Dialogue_MCM_Script", setTTSPlayerVoiceID);
a_registry->RegisterFunction("SetTTSPlayerVoiceVolume", "TTS_Voiced_Player_Dialogue_MCM_Script", setTTSPlayerVoiceVolume);
a_registry->RegisterFunction("SetTTSPlayerVoiceRateAdjust", "TTS_Voiced_Player_Dialogue_MCM_Script", setTTSPlayerVoiceRateAdjust);
return true;
}
/********************
** Initialization **
*********************/
bool InnerPluginLoad()
{
//x86
//BYTE* gOnDialogueSaySkip = (BYTE*)0x006D39C4;
//x64
//uintptr_t gOnDialogueSaySkip = 0x01405E83D8;
//file offset 0x005E77D8
//RVA seems to be 0x5E83D8
gOnDialogueSaySkip = REL::Offset(0x5E83D1).address();
//x86
//BYTE* gOnDialogueSay = (BYTE*)0x006D397E;
//comparison https://i.imgur.com/i2exbOy.png
//X64
//uintptr_t gOnDialogueSay = 0x01405E837F;
gOnDialogueSay = REL::Offset(0x5E83C5).address();
gOnDialogueSayResume = REL::Offset(0x5E83C9).address();
//x86
//BYTE* gOnTopicSetter = (BYTE*)0x00674113;
//x64
//uintptr_t gOnTopicSetter = 0x014056F910;
//comparison https://i.imgur.com/4ZAN0aU.png
//file offset 0x0056ED10
//RVA seems to be 0x56F910
gOnTopicSetter = REL::Offset(0x56F910).address();
gOnTopicSetterResume = REL::Offset(0x56F918).address();
// These set up injection points to the game:
auto& trampoline = SKSE::GetTrampoline();
onTopicSetterHookedPatch Tsh{ reinterpret_cast<uintptr_t>(onTopicSetterHook), reinterpret_cast<uintptr_t>(gOnTopicSetterResumePtr) };
onDialogueSayHookedPatch Dsh{ reinterpret_cast<uintptr_t>(shouldDelayNPCSpeech), reinterpret_cast<uintptr_t>(gOnDialogueSayResumePtr), gOnDialogueSaySkip };
const auto onTopicSetterHooked = trampoline.allocate(Tsh);
const auto onDialogueSayHooked = trampoline.allocate(Dsh);
// 1. When the topic is clicked, we'd like to remember the selected
// option (so that we can trigger same option choice later) and actually speak the TTS message
//gOnTopicSetterResume = detourWithTrampoline(gOnTopicSetter, (BYTE*)onTopicSetterHooked, 5);
REL::safe_fill(gOnTopicSetter, 0x90, 8);
trampoline.write_branch<5>(gOnTopicSetter,onTopicSetterHooked);
// 2. When the NPC is about to speak, we'd like prevent them initially, but still allow other dialogue events.
// We also check there, well, if user clicks during a convo to try to skip it, we'll also stop the TTS speaking.
//gOnDialogueSayResume = detourWithTrampoline(gOnDialogueSay, (BYTE*)onDialogueSayHooked, 6);
//REL::safe_fill(gOnDialogueSay, 0x90, 7);
//trampoline.write_branch<5>(gOnDialogueSay,onDialogueSayHooked);
//if (!g_papyrusInterface) {
// _MESSAGE("Problem: g_papyrusInterface is false");
// return false;
// }
auto papyrus = SKSE::GetPapyrusInterface();
if (!papyrus->Register(registerFuncs))
{
return false;
}
//g_taskInterface = static_cast<SKSETaskInterface*>(skse->QueryInterface(kInterface_Task));
//if (!g_taskInterface) {
// _MESSAGE("Problem: task registration failed");
// return false;
// }
logger::info<>("TTS Voiced Player Dialogue loaded");
return true;
}
| [
"peterpan0413@live.com"
] | peterpan0413@live.com |
9f2b3ff1443d3c979ee82318509b2fc89318bbcd | 0ecf2d067e8fe6cdec12b79bfd68fe79ec222ffd | /media/cast/test/cast_benchmarks.cc | 34309d2b353f639852841a771d56b02dff40d6bc | [
"BSD-3-Clause"
] | permissive | yachtcaptain23/browser-android-tabs | e5144cee9141890590d6d6faeb1bdc5d58a6cbf1 | a016aade8f8333c822d00d62738a922671a52b85 | refs/heads/master | 2021-04-28T17:07:06.955483 | 2018-09-26T06:22:11 | 2018-09-26T06:22:11 | 122,005,560 | 0 | 0 | NOASSERTION | 2019-05-17T19:37:59 | 2018-02-19T01:00:10 | null | UTF-8 | C++ | false | false | 25,223 | cc | // 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.
//
// This program benchmarks the theoretical throughput of the cast library.
// It runs using a fake clock, simulated network and fake codecs. This allows
// tests to run much faster than real time.
// To run the program, run:
// $ ./out/Release/cast_benchmarks | tee benchmarkoutput.asc
// This may take a while, when it is done, you can view the data with
// meshlab by running:
// $ meshlab benchmarkoutput.asc
// After starting meshlab, turn on Render->Show Axis. The red axis will
// represent bandwidth (in megabits) the blue axis will be packet drop
// (in percent) and the green axis will be latency (in milliseconds).
//
// This program can also be used for profiling. On linux it has
// built-in support for this. Simply set the environment variable
// PROFILE_FILE before running it, like so:
// $ export PROFILE_FILE=cast_benchmark.profile
// Then after running the program, you can view the profile with:
// $ pprof ./out/Release/cast_benchmarks $PROFILE_FILE --gv
#include <math.h>
#include <stddef.h>
#include <stdint.h>
#include <map>
#include <memory>
#include <utility>
#include <vector>
#include "base/at_exit.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/debug/profiler.h"
#include "base/memory/ptr_util.h"
#include "base/memory/weak_ptr.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/test/simple_test_tick_clock.h"
#include "base/threading/thread.h"
#include "base/time/tick_clock.h"
#include "media/base/audio_bus.h"
#include "media/base/fake_single_thread_task_runner.h"
#include "media/base/video_frame.h"
#include "media/cast/cast_config.h"
#include "media/cast/cast_environment.h"
#include "media/cast/cast_receiver.h"
#include "media/cast/cast_sender.h"
#include "media/cast/logging/simple_event_subscriber.h"
#include "media/cast/net/cast_transport.h"
#include "media/cast/net/cast_transport_config.h"
#include "media/cast/net/cast_transport_defines.h"
#include "media/cast/net/cast_transport_impl.h"
#include "media/cast/test/loopback_transport.h"
#include "media/cast/test/skewed_single_thread_task_runner.h"
#include "media/cast/test/skewed_tick_clock.h"
#include "media/cast/test/utility/audio_utility.h"
#include "media/cast/test/utility/default_config.h"
#include "media/cast/test/utility/test_util.h"
#include "media/cast/test/utility/udp_proxy.h"
#include "media/cast/test/utility/video_utility.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace media {
namespace cast {
namespace {
static const int64_t kStartMillisecond = INT64_C(1245);
static const int kTargetPlayoutDelayMs = 400;
void ExpectVideoSuccess(OperationalStatus status) {
EXPECT_EQ(STATUS_INITIALIZED, status);
}
void ExpectAudioSuccess(OperationalStatus status) {
EXPECT_EQ(STATUS_INITIALIZED, status);
}
} // namespace
// Wraps a CastTransport and records some statistics about
// the data that goes through it.
class CastTransportWrapper : public CastTransport {
public:
// Takes ownership of |transport|.
void Init(CastTransport* transport,
uint64_t* encoded_video_bytes,
uint64_t* encoded_audio_bytes) {
transport_.reset(transport);
encoded_video_bytes_ = encoded_video_bytes;
encoded_audio_bytes_ = encoded_audio_bytes;
}
void InitializeStream(const CastTransportRtpConfig& config,
std::unique_ptr<RtcpObserver> rtcp_observer) final {
if (config.rtp_payload_type <= RtpPayloadType::AUDIO_LAST)
audio_ssrc_ = config.ssrc;
else
video_ssrc_ = config.ssrc;
transport_->InitializeStream(config, std::move(rtcp_observer));
}
void InsertFrame(uint32_t ssrc, const EncodedFrame& frame) final {
if (ssrc == audio_ssrc_) {
*encoded_audio_bytes_ += frame.data.size();
} else if (ssrc == video_ssrc_) {
*encoded_video_bytes_ += frame.data.size();
}
transport_->InsertFrame(ssrc, frame);
}
void SendSenderReport(uint32_t ssrc,
base::TimeTicks current_time,
RtpTimeTicks current_time_as_rtp_timestamp) final {
transport_->SendSenderReport(ssrc,
current_time,
current_time_as_rtp_timestamp);
}
void CancelSendingFrames(uint32_t ssrc,
const std::vector<FrameId>& frame_ids) final {
transport_->CancelSendingFrames(ssrc, frame_ids);
}
void ResendFrameForKickstart(uint32_t ssrc, FrameId frame_id) final {
transport_->ResendFrameForKickstart(ssrc, frame_id);
}
PacketReceiverCallback PacketReceiverForTesting() final {
return transport_->PacketReceiverForTesting();
}
void AddValidRtpReceiver(uint32_t rtp_sender_ssrc,
uint32_t rtp_receiver_ssrc) final {
return transport_->AddValidRtpReceiver(rtp_sender_ssrc, rtp_receiver_ssrc);
}
void InitializeRtpReceiverRtcpBuilder(uint32_t rtp_receiver_ssrc,
const RtcpTimeData& time_data) final {
transport_->InitializeRtpReceiverRtcpBuilder(rtp_receiver_ssrc, time_data);
}
void AddCastFeedback(const RtcpCastMessage& cast_message,
base::TimeDelta target_delay) final {
transport_->AddCastFeedback(cast_message, target_delay);
}
void AddRtcpEvents(
const ReceiverRtcpEventSubscriber::RtcpEvents& rtcp_events) final {
transport_->AddRtcpEvents(rtcp_events);
}
void AddRtpReceiverReport(const RtcpReportBlock& rtp_report_block) final {
transport_->AddRtpReceiverReport(rtp_report_block);
}
void AddPli(const RtcpPliMessage& pli_message) final {
transport_->AddPli(pli_message);
}
void SendRtcpFromRtpReceiver() final {
transport_->SendRtcpFromRtpReceiver();
}
void SetOptions(const base::DictionaryValue& options) final {}
private:
std::unique_ptr<CastTransport> transport_;
uint32_t audio_ssrc_, video_ssrc_;
uint64_t* encoded_video_bytes_;
uint64_t* encoded_audio_bytes_;
};
struct MeasuringPoint {
MeasuringPoint(double bitrate_, double latency_, double percent_packet_drop_)
: bitrate(bitrate_),
latency(latency_),
percent_packet_drop(percent_packet_drop_) {}
bool operator<=(const MeasuringPoint& other) const {
return bitrate >= other.bitrate && latency <= other.latency &&
percent_packet_drop <= other.percent_packet_drop;
}
bool operator>=(const MeasuringPoint& other) const {
return bitrate <= other.bitrate && latency >= other.latency &&
percent_packet_drop >= other.percent_packet_drop;
}
std::string AsString() const {
return base::StringPrintf(
"%f Mbit/s %f ms %f %% ", bitrate, latency, percent_packet_drop);
}
double bitrate;
double latency;
double percent_packet_drop;
};
class RunOneBenchmark {
public:
RunOneBenchmark()
: start_time_(),
task_runner_(new FakeSingleThreadTaskRunner(&testing_clock_)),
testing_clock_sender_(&testing_clock_),
task_runner_sender_(
new test::SkewedSingleThreadTaskRunner(task_runner_)),
testing_clock_receiver_(&testing_clock_),
task_runner_receiver_(
new test::SkewedSingleThreadTaskRunner(task_runner_)),
cast_environment_sender_(new CastEnvironment(&testing_clock_sender_,
task_runner_sender_,
task_runner_sender_,
task_runner_sender_)),
cast_environment_receiver_(new CastEnvironment(&testing_clock_receiver_,
task_runner_receiver_,
task_runner_receiver_,
task_runner_receiver_)),
video_bytes_encoded_(0),
audio_bytes_encoded_(0),
frames_sent_(0) {
testing_clock_.Advance(
base::TimeDelta::FromMilliseconds(kStartMillisecond));
}
void Configure(Codec video_codec,
Codec audio_codec) {
audio_sender_config_ = GetDefaultAudioSenderConfig();
audio_sender_config_.min_playout_delay =
audio_sender_config_.max_playout_delay =
base::TimeDelta::FromMilliseconds(kTargetPlayoutDelayMs);
audio_sender_config_.codec = audio_codec;
audio_receiver_config_ = GetDefaultAudioReceiverConfig();
audio_receiver_config_.rtp_max_delay_ms =
audio_sender_config_.max_playout_delay.InMicroseconds();
audio_receiver_config_.codec = audio_codec;
video_sender_config_ = GetDefaultVideoSenderConfig();
video_sender_config_.min_playout_delay =
video_sender_config_.max_playout_delay =
base::TimeDelta::FromMilliseconds(kTargetPlayoutDelayMs);
video_sender_config_.max_bitrate = 4000000;
video_sender_config_.min_bitrate = 4000000;
video_sender_config_.start_bitrate = 4000000;
video_sender_config_.codec = video_codec;
video_receiver_config_ = GetDefaultVideoReceiverConfig();
video_receiver_config_.rtp_max_delay_ms = kTargetPlayoutDelayMs;
video_receiver_config_.codec = video_codec;
DCHECK_GT(video_sender_config_.max_frame_rate, 0);
frame_duration_ = base::TimeDelta::FromSecondsD(
1.0 / video_sender_config_.max_frame_rate);
}
void SetSenderClockSkew(double skew, base::TimeDelta offset) {
testing_clock_sender_.SetSkew(skew, offset);
task_runner_sender_->SetSkew(1.0 / skew);
}
void SetReceiverClockSkew(double skew, base::TimeDelta offset) {
testing_clock_receiver_.SetSkew(skew, offset);
task_runner_receiver_->SetSkew(1.0 / skew);
}
void Create(const MeasuringPoint& p);
void ReceivePacket(std::unique_ptr<Packet> packet) {
cast_receiver_->ReceivePacket(std::move(packet));
}
virtual ~RunOneBenchmark() {
cast_sender_.reset();
cast_receiver_.reset();
task_runner_->RunTasks();
}
base::TimeDelta VideoTimestamp(int frame_number) {
return frame_number * base::TimeDelta::FromSecondsD(
1.0 / video_sender_config_.max_frame_rate);
}
void SendFakeVideoFrame() {
// NB: Blackframe with timestamp
cast_sender_->video_frame_input()->InsertRawVideoFrame(
media::VideoFrame::CreateColorFrame(gfx::Size(2, 2), 0x00, 0x80, 0x80,
VideoTimestamp(frames_sent_)),
testing_clock_sender_.NowTicks());
frames_sent_++;
}
void RunTasks(base::TimeDelta duration) {
task_runner_->Sleep(duration);
}
void BasicPlayerGotVideoFrame(
const scoped_refptr<media::VideoFrame>& video_frame,
const base::TimeTicks& render_time,
bool continuous) {
video_ticks_.push_back(
std::make_pair(testing_clock_receiver_.NowTicks(), render_time));
cast_receiver_->RequestDecodedVideoFrame(base::Bind(
&RunOneBenchmark::BasicPlayerGotVideoFrame, base::Unretained(this)));
}
void BasicPlayerGotAudioFrame(std::unique_ptr<AudioBus> audio_bus,
const base::TimeTicks& playout_time,
bool is_continuous) {
audio_ticks_.push_back(
std::make_pair(testing_clock_receiver_.NowTicks(), playout_time));
cast_receiver_->RequestDecodedAudioFrame(base::Bind(
&RunOneBenchmark::BasicPlayerGotAudioFrame, base::Unretained(this)));
}
void StartBasicPlayer() {
cast_receiver_->RequestDecodedVideoFrame(base::Bind(
&RunOneBenchmark::BasicPlayerGotVideoFrame, base::Unretained(this)));
cast_receiver_->RequestDecodedAudioFrame(base::Bind(
&RunOneBenchmark::BasicPlayerGotAudioFrame, base::Unretained(this)));
}
std::unique_ptr<test::PacketPipe> CreateSimplePipe(const MeasuringPoint& p) {
std::unique_ptr<test::PacketPipe> pipe = test::NewBuffer(65536, p.bitrate);
pipe->AppendToPipe(test::NewRandomDrop(p.percent_packet_drop / 100.0));
pipe->AppendToPipe(test::NewConstantDelay(p.latency / 1000.0));
return pipe;
}
void Run(const MeasuringPoint& p) {
available_bitrate_ = p.bitrate;
Configure(CODEC_VIDEO_FAKE, CODEC_AUDIO_PCM16);
Create(p);
StartBasicPlayer();
for (int frame = 0; frame < 1000; frame++) {
SendFakeVideoFrame();
RunTasks(frame_duration_);
}
RunTasks(100 * frame_duration_); // Empty the pipeline.
VLOG(1) << "=============INPUTS============";
VLOG(1) << "Bitrate: " << p.bitrate << " mbit/s";
VLOG(1) << "Latency: " << p.latency << " ms";
VLOG(1) << "Packet drop drop: " << p.percent_packet_drop << "%";
VLOG(1) << "=============OUTPUTS============";
VLOG(1) << "Frames lost: " << frames_lost();
VLOG(1) << "Late frames: " << late_frames();
VLOG(1) << "Playout margin: " << frame_playout_buffer().AsString();
VLOG(1) << "Video bandwidth used: " << video_bandwidth() << " mbit/s ("
<< (video_bandwidth() * 100 / desired_video_bitrate()) << "%)";
VLOG(1) << "Good run: " << SimpleGood();
}
// Metrics
int frames_lost() const { return frames_sent_ - video_ticks_.size(); }
int late_frames() const {
int frames = 0;
// Ignore the first two seconds of video or so.
for (size_t i = 60; i < video_ticks_.size(); i++) {
if (video_ticks_[i].first > video_ticks_[i].second) {
frames++;
}
}
return frames;
}
test::MeanAndError frame_playout_buffer() const {
std::vector<double> values;
for (size_t i = 0; i < video_ticks_.size(); i++) {
values.push_back(
(video_ticks_[i].second - video_ticks_[i].first).InMillisecondsF());
}
return test::MeanAndError(values);
}
// Mbits per second
double video_bandwidth() const {
double seconds = (frame_duration_.InSecondsF() * frames_sent_);
double megabits = video_bytes_encoded_ * 8 / 1000000.0;
return megabits / seconds;
}
// Mbits per second
double audio_bandwidth() const {
double seconds = (frame_duration_.InSecondsF() * frames_sent_);
double megabits = audio_bytes_encoded_ * 8 / 1000000.0;
return megabits / seconds;
}
double desired_video_bitrate() {
return std::min<double>(available_bitrate_,
video_sender_config_.max_bitrate / 1000000.0);
}
bool SimpleGood() {
return frames_lost() <= 1 && late_frames() <= 1 &&
video_bandwidth() > desired_video_bitrate() * 0.8 &&
video_bandwidth() < desired_video_bitrate() * 1.2;
}
private:
FrameReceiverConfig audio_receiver_config_;
FrameReceiverConfig video_receiver_config_;
FrameSenderConfig audio_sender_config_;
FrameSenderConfig video_sender_config_;
base::TimeTicks start_time_;
// These run in "test time"
base::SimpleTestTickClock testing_clock_;
scoped_refptr<FakeSingleThreadTaskRunner> task_runner_;
// These run on the sender timeline.
test::SkewedTickClock testing_clock_sender_;
scoped_refptr<test::SkewedSingleThreadTaskRunner> task_runner_sender_;
// These run on the receiver timeline.
test::SkewedTickClock testing_clock_receiver_;
scoped_refptr<test::SkewedSingleThreadTaskRunner> task_runner_receiver_;
scoped_refptr<CastEnvironment> cast_environment_sender_;
scoped_refptr<CastEnvironment> cast_environment_receiver_;
LoopBackTransport* receiver_to_sender_; // Owned by CastTransportImpl.
LoopBackTransport* sender_to_receiver_; // Owned by CastTransportImpl.
CastTransportWrapper transport_sender_;
std::unique_ptr<CastTransport> transport_receiver_;
uint64_t video_bytes_encoded_;
uint64_t audio_bytes_encoded_;
std::unique_ptr<CastReceiver> cast_receiver_;
std::unique_ptr<CastSender> cast_sender_;
int frames_sent_;
base::TimeDelta frame_duration_;
double available_bitrate_;
std::vector<std::pair<base::TimeTicks, base::TimeTicks> > audio_ticks_;
std::vector<std::pair<base::TimeTicks, base::TimeTicks> > video_ticks_;
};
namespace {
class TransportClient : public CastTransport::Client {
public:
explicit TransportClient(RunOneBenchmark* run_one_benchmark)
: run_one_benchmark_(run_one_benchmark) {}
void OnStatusChanged(CastTransportStatus status) final {
EXPECT_EQ(TRANSPORT_STREAM_INITIALIZED, status);
};
void OnLoggingEventsReceived(
std::unique_ptr<std::vector<FrameEvent>> frame_events,
std::unique_ptr<std::vector<PacketEvent>> packet_events) final{};
void ProcessRtpPacket(std::unique_ptr<Packet> packet) final {
if (run_one_benchmark_)
run_one_benchmark_->ReceivePacket(std::move(packet));
};
private:
RunOneBenchmark* const run_one_benchmark_;
DISALLOW_COPY_AND_ASSIGN(TransportClient);
};
} // namepspace
void RunOneBenchmark::Create(const MeasuringPoint& p) {
sender_to_receiver_ = new LoopBackTransport(cast_environment_sender_);
transport_sender_.Init(
new CastTransportImpl(
&testing_clock_sender_, base::TimeDelta::FromSeconds(1),
std::make_unique<TransportClient>(nullptr),
base::WrapUnique(sender_to_receiver_), task_runner_sender_),
&video_bytes_encoded_, &audio_bytes_encoded_);
receiver_to_sender_ = new LoopBackTransport(cast_environment_receiver_);
transport_receiver_.reset(new CastTransportImpl(
&testing_clock_receiver_, base::TimeDelta::FromSeconds(1),
std::make_unique<TransportClient>(this),
base::WrapUnique(receiver_to_sender_), task_runner_receiver_));
cast_receiver_ =
CastReceiver::Create(cast_environment_receiver_, audio_receiver_config_,
video_receiver_config_, transport_receiver_.get());
cast_sender_ =
CastSender::Create(cast_environment_sender_, &transport_sender_);
cast_sender_->InitializeAudio(audio_sender_config_,
base::Bind(&ExpectAudioSuccess));
cast_sender_->InitializeVideo(video_sender_config_,
base::Bind(&ExpectVideoSuccess),
CreateDefaultVideoEncodeAcceleratorCallback(),
CreateDefaultVideoEncodeMemoryCallback());
receiver_to_sender_->Initialize(CreateSimplePipe(p),
transport_sender_.PacketReceiverForTesting(),
task_runner_, &testing_clock_);
sender_to_receiver_->Initialize(
CreateSimplePipe(p), transport_receiver_->PacketReceiverForTesting(),
task_runner_, &testing_clock_);
task_runner_->RunTasks();
}
enum CacheResult { FOUND_TRUE, FOUND_FALSE, NOT_FOUND };
template <class T>
class BenchmarkCache {
public:
CacheResult Lookup(const T& x) {
base::AutoLock key(lock_);
for (size_t i = 0; i < results_.size(); i++) {
if (results_[i].second) {
if (x <= results_[i].first) {
VLOG(2) << "TRUE because: " << x.AsString()
<< " <= " << results_[i].first.AsString();
return FOUND_TRUE;
}
} else {
if (x >= results_[i].first) {
VLOG(2) << "FALSE because: " << x.AsString()
<< " >= " << results_[i].first.AsString();
return FOUND_FALSE;
}
}
}
return NOT_FOUND;
}
void Add(const T& x, bool result) {
base::AutoLock key(lock_);
VLOG(2) << "Cache Insert: " << x.AsString() << " = " << result;
results_.push_back(std::make_pair(x, result));
}
private:
base::Lock lock_;
std::vector<std::pair<T, bool> > results_;
};
struct SearchVariable {
SearchVariable() : base(0.0), grade(0.0) {}
SearchVariable(double b, double g) : base(b), grade(g) {}
SearchVariable blend(const SearchVariable& other, double factor) {
CHECK_GE(factor, 0);
CHECK_LE(factor, 1.0);
return SearchVariable(base * (1 - factor) + other.base * factor,
grade * (1 - factor) + other.grade * factor);
}
double value(double x) const { return base + grade * x; }
double base;
double grade;
};
struct SearchVector {
SearchVector blend(const SearchVector& other, double factor) {
SearchVector ret;
ret.bitrate = bitrate.blend(other.bitrate, factor);
ret.latency = latency.blend(other.latency, factor);
ret.packet_drop = packet_drop.blend(other.packet_drop, factor);
return ret;
}
SearchVector average(const SearchVector& other) {
return blend(other, 0.5);
}
MeasuringPoint GetMeasuringPoint(double v) const {
return MeasuringPoint(
bitrate.value(-v), latency.value(v), packet_drop.value(v));
}
std::string AsString(double v) { return GetMeasuringPoint(v).AsString(); }
SearchVariable bitrate;
SearchVariable latency;
SearchVariable packet_drop;
};
class CastBenchmark {
public:
bool RunOnePoint(const SearchVector& v, double multiplier) {
MeasuringPoint p = v.GetMeasuringPoint(multiplier);
VLOG(1) << "RUN: v = " << multiplier << " p = " << p.AsString();
if (p.bitrate <= 0) {
return false;
}
switch (cache_.Lookup(p)) {
case FOUND_TRUE:
return true;
case FOUND_FALSE:
return false;
case NOT_FOUND:
// Keep going
break;
}
bool result = true;
for (int tries = 0; tries < 3 && result; tries++) {
RunOneBenchmark benchmark;
benchmark.Run(p);
result &= benchmark.SimpleGood();
}
cache_.Add(p, result);
return result;
}
void BinarySearch(SearchVector v, double accuracy) {
double min = 0.0;
double max = 1.0;
while (RunOnePoint(v, max)) {
min = max;
max *= 2;
}
while (max - min > accuracy) {
double avg = (min + max) / 2;
if (RunOnePoint(v, avg)) {
min = avg;
} else {
max = avg;
}
}
// Print a data point to stdout.
base::AutoLock key(lock_);
MeasuringPoint p = v.GetMeasuringPoint(min);
fprintf(stdout, "%f %f %f\n", p.bitrate, p.latency, p.percent_packet_drop);
fflush(stdout);
}
void SpanningSearch(int max,
int x,
int y,
int skip,
SearchVector a,
SearchVector b,
SearchVector c,
double accuracy,
std::vector<std::unique_ptr<base::Thread>>* threads) {
static int thread_num = 0;
if (x > max) return;
if (skip > max) {
if (y > x) return;
SearchVector ab = a.blend(b, static_cast<double>(x) / max);
SearchVector ac = a.blend(c, static_cast<double>(x) / max);
SearchVector v = ab.blend(ac, x == y ? 1.0 : static_cast<double>(y) / x);
thread_num++;
(*threads)[thread_num % threads->size()]
->message_loop()
->task_runner()
->PostTask(FROM_HERE,
base::Bind(&CastBenchmark::BinarySearch,
base::Unretained(this), v, accuracy));
} else {
skip *= 2;
SpanningSearch(max, x, y, skip, a, b, c, accuracy, threads);
SpanningSearch(max, x + skip, y + skip, skip, a, b, c, accuracy, threads);
SpanningSearch(max, x + skip, y, skip, a, b, c, accuracy, threads);
SpanningSearch(max, x, y + skip, skip, a, b, c, accuracy, threads);
}
}
void Run() {
// Spanning search.
std::vector<std::unique_ptr<base::Thread>> threads;
for (int i = 0; i < 16; i++) {
threads.push_back(std::make_unique<base::Thread>(
base::StringPrintf("cast_bench_thread_%d", i)));
threads[i]->Start();
}
if (base::CommandLine::ForCurrentProcess()->HasSwitch("single-run")) {
SearchVector a;
a.bitrate.base = 100.0;
a.bitrate.grade = 1.0;
a.latency.grade = 1.0;
a.packet_drop.grade = 1.0;
threads[0]->message_loop()->task_runner()->PostTask(
FROM_HERE, base::Bind(base::IgnoreResult(&CastBenchmark::RunOnePoint),
base::Unretained(this), a, 1.0));
} else {
SearchVector a, b, c;
a.bitrate.base = b.bitrate.base = c.bitrate.base = 100.0;
a.bitrate.grade = 1.0;
b.latency.grade = 1.0;
c.packet_drop.grade = 1.0;
SpanningSearch(512,
0,
0,
1,
a,
b,
c,
0.01,
&threads);
}
for (size_t i = 0; i < threads.size(); i++) {
threads[i]->Stop();
}
}
private:
BenchmarkCache<MeasuringPoint> cache_;
base::Lock lock_;
};
} // namespace cast
} // namespace media
int main(int argc, char** argv) {
base::AtExitManager at_exit;
base::CommandLine::Init(argc, argv);
media::cast::CastBenchmark benchmark;
if (getenv("PROFILE_FILE")) {
std::string profile_file(getenv("PROFILE_FILE"));
base::debug::StartProfiling(profile_file);
benchmark.Run();
base::debug::StopProfiling();
} else {
benchmark.Run();
}
}
| [
"artem@brave.com"
] | artem@brave.com |
7ef72034505a16c4832a9507604d2354d451944d | e3317469bb30b0a211fd9bb918661c00359ef4a5 | /MMCMonitorApp/mmcdisplaytablemodel.cpp | 0a2258cca9f74d90ae7d8f9e0f8929465c4ef18e | [] | no_license | pipi95/MMCMonitor | 132fe724a31f0c61e70053d44596ceea19125a57 | 76f2838c43909f9cf530a9bb284fb97e2fd20648 | refs/heads/master | 2020-03-28T22:36:26.218622 | 2018-09-18T08:25:49 | 2018-09-18T08:25:49 | 149,244,280 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 716 | cpp | #include "mmcdisplaytablemodel.h"
MMCDisplayTableModel::MMCDisplayTableModel(QObject* parent)
: QAbstractTableModel(parent)
{
}
int MMCDisplayTableModel::rowCount(const QModelIndex& ) const
{
return numberOfContent;
}
int MMCDisplayTableModel::columnCount(const QModelIndex& ) const
{
return numberOfColumn;
}
QModelIndex MMCDisplayTableModel::parent(const QModelIndex& ) const
{
return QModelIndex();
}
QVariant MMCDisplayTableModel::data(const QModelIndex& index, int role) const
{
switch (role) {
case Qt::DisplayRole:
return QVariant("Null data");
default:
return QVariant("Null data");
}
}
void MMCDisplayTableModel::ParseFrame(const EquipFrame& fr)
{
}
| [
"pipi95@163.com"
] | pipi95@163.com |
07b026396beac58234cc1f2fb9e3793e9f1bee0e | 06bed8ad5fd60e5bba6297e9870a264bfa91a71d | /libPr3/routemanager.cpp | 5651c53c4eecb320f77f80e778caf7872db42422 | [] | no_license | allenck/DecoderPro_app | 43aeb9561fe3fe9753684f7d6d76146097d78e88 | 226c7f245aeb6951528d970f773776d50ae2c1dc | refs/heads/master | 2023-05-12T07:36:18.153909 | 2023-05-10T21:17:40 | 2023-05-10T21:17:40 | 61,044,197 | 4 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 97 | cpp | #include "routemanager.h"
RouteManager::RouteManager(QObject *parent) :
Manager(parent)
{
}
| [
"allenck@windstream.net"
] | allenck@windstream.net |
7f24149ad883041c3da06c2f0f1681d040e70801 | d04aaa5014ac6d8e53452b3169060fc4ef8e00f5 | /cppDSmalik/ch4ex/absoluteValueEx.cpp | fbd986cbb43d4fb0eb629f4bbef8d6a6af1d697b | [] | no_license | StaringPanda/CPP-Practice | 08082fb17343caffca2c16c7f9f2e7a46f9e471e | 2dd7b169cd2930ab402a4843d98ea58f49ad1476 | refs/heads/master | 2020-07-01T04:55:59.699860 | 2019-08-16T15:19:26 | 2019-08-16T15:19:26 | 201,054,206 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,615 | cpp | /*****************************************************************
// Example from Pg 210 shows how checking the comparison of
// floating point numbers for equality may not behave as you
// would expect.
//
// x = 1.0 and y = 0.999999~ so the if (x == y) is false, however
// if you evaluate the equation in y wiht pen and paper you will
// get 1.0 as a result.
//
// One way to check whether two floating point numbers are
// equal is to check whether the absolute value of their
// difference is less than a certain tolerance.
//
// The function fabs(), finds the absolute value of a floating
// point integer.
//
// Not a good example of the fabs() function, gives correct
// answer regardless of presence or absence of fabs() or
// reversing the positions of x and y.
*****************************************************************/
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main(){
double x = 1.0;
double y = 3.0 / 7.0 + 2.0 / 7.0 + 2.0 / 7.0;
cout << fixed << showpoint << setprecision(17);
cout << "3.0 / 7.0 + 2.0 / 7.0 + 2.0 / 7.0 = " << 3.0 / 7.0 + 2.0 / 7.0 + 2.0 / 7.0 << endl;
cout << "x = " << x << endl;
cout << "y = " << y << endl;
if (x == y){
cout << "x and y are the same." << endl;
}else{
cout << "x and y are not the same." << endl;
}
if (fabs(y - x) < 0.000001){
cout << "x and y are the same within the tolerance 0.000001." << endl;
}else{
cout << "x and y are not the same within the tolerance 0.000001." << endl;
}
return 0;
} | [
"d00210089@student.dkit.ie"
] | d00210089@student.dkit.ie |
696e578d27a59d9d2158070d155a8eb5f9cb2c6a | 78f0044cab0c14205c7fe2a00067fe7aebe9eba3 | /Communicational abilities/CyborgWorkspace/devel/include/speech_processing/Num.h | c96b8205ac54ee48a7b123e2d69eb22c7d4d02b7 | [] | no_license | thentnucyborg/CyborgRobot_v1_archive | 7ad8959b2e5f5cb5418699b9d93c2b41f962613c | fc1419d229f379063668684c51faaeb6cb6ba447 | refs/heads/master | 2021-01-16T05:14:51.804599 | 2020-02-25T11:51:39 | 2020-02-25T11:51:39 | 242,987,310 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,458 | h | /* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, 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:
*
* * 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 Willow Garage, Inc. 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 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.
*
* Auto-generated by genmsg_cpp from file /home/viki/Desktop/speech_ws/src/speech_processing/msg/Num.msg
*
*/
#ifndef SPEECH_PROCESSING_MESSAGE_NUM_H
#define SPEECH_PROCESSING_MESSAGE_NUM_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
namespace speech_processing
{
template <class ContainerAllocator>
struct Num_
{
typedef Num_<ContainerAllocator> Type;
Num_()
: num(0) {
}
Num_(const ContainerAllocator& _alloc)
: num(0) {
}
typedef int16_t _num_type;
_num_type num;
typedef boost::shared_ptr< ::speech_processing::Num_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::speech_processing::Num_<ContainerAllocator> const> ConstPtr;
boost::shared_ptr<std::map<std::string, std::string> > __connection_header;
}; // struct Num_
typedef ::speech_processing::Num_<std::allocator<void> > Num;
typedef boost::shared_ptr< ::speech_processing::Num > NumPtr;
typedef boost::shared_ptr< ::speech_processing::Num const> NumConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::speech_processing::Num_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::speech_processing::Num_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace speech_processing
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False}
// {'speech_processing': ['/home/viki/Desktop/speech_ws/src/speech_processing/msg'], 'std_msgs': ['/opt/ros/hydro/share/std_msgs/cmake/../msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::speech_processing::Num_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::speech_processing::Num_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::speech_processing::Num_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::speech_processing::Num_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::speech_processing::Num_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::speech_processing::Num_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::speech_processing::Num_<ContainerAllocator> >
{
static const char* value()
{
return "79e2a05b252e69632375170571b25d3d";
}
static const char* value(const ::speech_processing::Num_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x79e2a05b252e6963ULL;
static const uint64_t static_value2 = 0x2375170571b25d3dULL;
};
template<class ContainerAllocator>
struct DataType< ::speech_processing::Num_<ContainerAllocator> >
{
static const char* value()
{
return "speech_processing/Num";
}
static const char* value(const ::speech_processing::Num_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::speech_processing::Num_<ContainerAllocator> >
{
static const char* value()
{
return "int16 num\n\
";
}
static const char* value(const ::speech_processing::Num_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::speech_processing::Num_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.num);
}
ROS_DECLARE_ALLINONE_SERIALIZER;
}; // struct Num_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::speech_processing::Num_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::speech_processing::Num_<ContainerAllocator>& v)
{
s << indent << "num: ";
Printer<int16_t>::stream(s, indent + " ", v.num);
}
};
} // namespace message_operations
} // namespace ros
#endif // SPEECH_PROCESSING_MESSAGE_NUM_H
| [
"martinius.knudsen@ntnu.no"
] | martinius.knudsen@ntnu.no |
6db1c42cf7db10853bb29d890fa54e997631436b | 1ad05e00f49ebc3cb7d0516cc510a46f99e15cfe | /src/qt/sendcoinsentry.cpp | 872a1e7918f6c8e93fa02a394120ccd9faff0b80 | [
"MIT"
] | permissive | Stephanzf/finecoin | c9059c56aa25fc1e15b3774226427602a07f5dbe | 395a85f5f585b86a5520469ad269e1ff5c4a8d24 | refs/heads/master | 2021-05-28T03:53:56.775939 | 2014-10-21T12:56:51 | 2014-10-21T12:56:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,193 | cpp | #include "sendcoinsentry.h"
#include "ui_sendcoinsentry.h"
#include "guiutil.h"
#include "bitcoinunits.h"
#include "addressbookpage.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include <QApplication>
#include <QClipboard>
SendCoinsEntry::SendCoinsEntry(QWidget *parent) :
QFrame(parent),
ui(new Ui::SendCoinsEntry),
model(0)
{
ui->setupUi(this);
#ifdef Q_WS_MAC
ui->payToLayout->setSpacing(4);
#endif
#if QT_VERSION >= 0x040700
/* Do not move this to the XML file, Qt before 4.7 will choke on it */
ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
ui->payTo->setPlaceholderText(tr("Enter a FineCoin address (they start with an 'm')"));
#endif
setFocusPolicy(Qt::TabFocus);
setFocusProxy(ui->payTo);
GUIUtil::setupAddressWidget(ui->payTo, this);
}
SendCoinsEntry::~SendCoinsEntry()
{
delete ui;
}
void SendCoinsEntry::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void SendCoinsEntry::on_addressBookButton_clicked()
{
if(!model)
return;
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}
}
void SendCoinsEntry::on_payTo_textChanged(const QString &address)
{
if(!model)
return;
// Fill in label from address book, if address has an associated label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);
if(!associatedLabel.isEmpty())
ui->addAsLabel->setText(associatedLabel);
}
void SendCoinsEntry::setModel(WalletModel *model)
{
this->model = model;
if(model && model->getOptionsModel())
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
clear();
}
void SendCoinsEntry::setRemoveEnabled(bool enabled)
{
ui->deleteButton->setEnabled(enabled);
}
void SendCoinsEntry::clear()
{
ui->payTo->clear();
ui->addAsLabel->clear();
ui->payAmount->clear();
ui->payTo->setFocus();
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void SendCoinsEntry::on_deleteButton_clicked()
{
emit removeEntry(this);
}
bool SendCoinsEntry::validate()
{
// Check input validity
bool retval = true;
if(!ui->payAmount->validate())
{
retval = false;
}
else
{
if(ui->payAmount->value() <= 0)
{
// Cannot send 0 coins or less
ui->payAmount->setValid(false);
retval = false;
}
}
if(!ui->payTo->hasAcceptableInput() ||
(model && !model->validateAddress(ui->payTo->text())))
{
ui->payTo->setValid(false);
retval = false;
}
return retval;
}
SendCoinsRecipient SendCoinsEntry::getValue()
{
SendCoinsRecipient rv;
rv.address = ui->payTo->text();
rv.label = ui->addAsLabel->text();
rv.amount = ui->payAmount->value();
return rv;
}
QWidget *SendCoinsEntry::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, ui->payTo);
QWidget::setTabOrder(ui->payTo, ui->addressBookButton);
QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);
QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);
QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel);
return ui->payAmount->setupTabChain(ui->addAsLabel);
}
void SendCoinsEntry::setValue(const SendCoinsRecipient &value)
{
ui->payTo->setText(value.address);
ui->addAsLabel->setText(value.label);
ui->payAmount->setValue(value.amount);
}
bool SendCoinsEntry::isClear()
{
return ui->payTo->text().isEmpty();
}
void SendCoinsEntry::setFocus()
{
ui->payTo->setFocus();
}
void SendCoinsEntry::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update payAmount with the current unit
ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
| [
"luke@debian.workgroup"
] | luke@debian.workgroup |
969c0704a28aaf863e2be1c5ff80e418a63656e9 | 00bb26fc4fc1fe1942e30c1873d7f442e0ea08c8 | /VNOI_1/B_THTIME/sol_dijkstra.cpp | d1034533f40131d3074698076bc8b10bd58cc7bc | [] | no_license | dntai/VNOI_contests | 1230b4562e3aa32d61a6a4d9b28704792b430dc2 | c9d3dae5586a4e0b49a052d92d4b67d629332f1d | refs/heads/master | 2020-03-26T19:02:40.088628 | 2017-05-07T08:32:09 | 2017-05-07T08:32:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,882 | cpp | // Author: happyboy99x
#include<iostream>
#include<cstring>
#include<set>
using namespace std;
const int N = 1000, delta[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
char s[2][N][N+1];
int d[2][N][N], m, n;
struct State {
int map, x, y, d;
State(const int &map = 0, const int &x = 0, const int &y = 0, const int &d = 0):
map(map), x(x), y(y), d(d) {}
bool operator < (const State &s) const {
return d == s.d ? map == s.map ? x == s.x ? y < s.y : x < s.x : map < s.map : d < s.d;
}
bool valid() const {
return x >= 0 && x < m && y >= 0 && y < n && s[map][x][y] != '#';
}
};
char& map(const State &t) {
return s[t.map][t.x][t.y];
}
int& dist(const State &s) {
return d[s.map][s.x][s.y];
}
void enter() {
cin >> m >> n;
for(int map = 0; map < 2; ++map)
for(int i = 0; i < m; ++i)
cin >> s[map][i];
}
void update(set<State> &s, const State &st) {
if(st.valid() && dist(st) > st.d) {
State temp (st);
temp.d = dist(st);
set<State>::iterator it = s.find(temp);
if(it != s.end()) s.erase(it);
s.insert(st);
dist(st) = st.d;
}
}
int solve() { // Dijkstra
memset(d, 0x3f, sizeof d);
set<State> heap;
for(int i = 0; i < m; ++i)
for(int j = 0; j < n; ++j)
if(s[0][i][j] == 'S') {
d[0][i][j] = 0;
heap.insert(State(0, i, j, 0));
}
while(!heap.empty()) {
State s (*heap.begin());
heap.erase(heap.begin());
if(map(s) == 'T') return s.d;
for(int k = 0; k < 4; ++k)
update(heap, State(s.map, s.x + delta[k][0], s.y + delta[k][1], s.d));
update(heap, State(1 - s.map, s.x, s.y, s.d + 1));
}
return -1;
}
int main() {
ios::sync_with_stdio(false);
enter();
cout << solve() << "\n";
return 0;
}
| [
"nguyentt@garena.com"
] | nguyentt@garena.com |
305a655ef6f20996d484cf85f7d4c8a545a8f4bc | d01b79d885b2a5fd69b9514d35b0340bce5dd103 | /poj/poj1008.cpp | 7f1df1abc95b7e69d8fdeb30819fb67eda16c293 | [] | no_license | lotay/online_judgement | 0dd38afef7cb3450bd9927e8d7c20af5a72d8688 | 2c17e5745e3b4c339cc3f35741b691a11e571ede | refs/heads/master | 2021-01-01T03:54:53.934783 | 2016-06-09T07:06:10 | 2016-06-09T07:06:10 | 58,803,721 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 903 | cpp | #include <stdio.h>
#include <string.h>
char HaabMonths[][10] = {"pop","no","zip","zotz","tzec","xul","yoxkin",
"mol","chen","yax","zac","ceh","mac","kankin","muan","pax","koyab","cumhu","uayet"};
char TzolkinDate[][10] = {"imix","ik","akbal","kan","chicchan","cimi",
"manik","lamat","muluk","ok","chuen","eb","ben","ix","mem","cib","caban","eznab","canac","ahau"};
int transfer1(int d, char *m, int y){
int mi = 0;
for(;mi<19;mi++){
if(strcmp(HaabMonths[mi],m)==0){
break;
}
}
return d+mi*20+y*365;
}
void transfer2(int date){
int y = date / 260;
int l = date % 260;
printf("%d %s %d\n",(l%13)+1,TzolkinDate[l%20],y);
}
int main(int argv,char **argc){
int d,y;
char months[10];
int t =0;
scanf("%d",&t);
printf("%d\n",t);
while(t-->0){
scanf("%d. %s %d",&d,months,&y);
int date = transfer1(d,months,y);
transfer2(date);
// printf("%d %s %d\n",d,months,y);
}
return 0;
}
| [
"158481612@qq.com"
] | 158481612@qq.com |
7ddde91056b60a87633fa5d3cbdf6dcfe68ef34b | bd8a4e18a20016389d184b23a266c7778f359fd5 | /program menghitung gaji pegawai.cpp | 16305f88b8d68d56fc955a3f5945a19057cd8efd | [] | no_license | mukromun311810151/menghitung-gaji-pegawai | c63c31e05622a234a0d0fa5c535984f44e18d1a2 | 2b05b0f3b5ae9dac1a846b6e9db17ec3ac982fe6 | refs/heads/master | 2020-04-14T08:45:43.256248 | 2019-01-01T14:28:34 | 2019-01-01T14:28:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 345 | cpp | #include <iostream>
#include <cstdlib>
using namespace std;
int main ()
{
int gaji, jumlah_jam_kerja;
cout << "menghitung gaji pegawai jika perjam 5000" <<endl;
cout << "masukkan jumlah jam kerja : ";
cin >> jumlah_jam_kerja;
gaji = jumlah_jam_kerja * 5000;
cout << "gaji pegawai adalah : " <<gaji;
return 0;
}
| [
"noreply@github.com"
] | mukromun311810151.noreply@github.com |
b3287ec6ed77eba8adf03e5dc0f8e450572829ef | 7da51e1fb66879a668718f9c08a7e95f11341190 | /sources/openGL/camera.cpp | c67faf7009793a3977759fef5daeba16a4c05c46 | [] | no_license | fafancier/light-field-remote-vision | ab26960789decdc9ca219f96aca0ab1ac9f6946d | fd8b7befc06274e05cac36bcd7bbf7d93d6270f9 | refs/heads/master | 2021-09-02T02:26:44.673557 | 2017-12-29T18:36:48 | 2017-12-29T18:36:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,484 | cpp | #include "camera.h"
// Permet d'éviter la ré-écriture du namespace glm::
using namespace glm;
// Constructeurs et Destructeur
Camera::Camera() : m_phi(0.0), m_theta(0.0), m_orientation(), m_axeVertical(0, 0, 1), m_deplacementLateral(), m_position(), m_pointCible(), m_sensibilite(0.0), m_vitesse(0.0)
{
}
Camera::Camera(glm::vec3 position, glm::vec3 pointCible, glm::vec3 axeVertical, float sensibilite, float vitesse) : m_phi(0.0), m_theta(0.0), m_orientation(),
m_axeVertical(axeVertical), m_deplacementLateral(),
m_position(position), m_pointCible(pointCible),
m_sensibilite(sensibilite), m_vitesse(vitesse)
{
// Actualisation du point ciblé
setPointcible();
}
Camera::~Camera()
{
}
// Méthodes
void Camera::orienter(int xRel, int yRel)
{
// Récupération des angles
m_phi += xRel * m_sensibilite;
m_theta += -yRel * m_sensibilite;
// Limitation de l'angle phi
if(m_phi > 89.0)
m_phi = 89.0;
else if(m_phi < -89.0)
m_phi = -89.0;
// Conversion des angles en radian
float phiRadian = m_phi * M_PI / 180;
float thetaRadian = m_theta * M_PI / 180;
// Si l'axe vertical est l'axe X
if(m_axeVertical.x == 1.0)
{
// Calcul des coordonnées sphériques
m_orientation.x = sin(phiRadian);
m_orientation.y = cos(phiRadian) * cos(thetaRadian);
m_orientation.z = cos(phiRadian) * sin(thetaRadian);
}
// Si c'est l'axe Y
else if(m_axeVertical.y == 1.0)
{
// Calcul des coordonnées sphériques
m_orientation.x = cos(phiRadian) * sin(thetaRadian);
m_orientation.y = sin(phiRadian);
m_orientation.z = cos(phiRadian) * cos(thetaRadian);
}
// Sinon c'est l'axe Z
else
{
// Calcul des coordonnées sphériques
m_orientation.x = cos(phiRadian) * cos(thetaRadian);
m_orientation.y = cos(phiRadian) * sin(thetaRadian);
m_orientation.z = sin(phiRadian);
}
// Calcul de la normale
m_deplacementLateral = cross(m_axeVertical, m_orientation);
m_deplacementLateral = normalize(m_deplacementLateral);
// Calcul du point ciblé pour OpenGL
m_pointCible = m_position + m_orientation;
}
void Camera::deplacer(Input const &input)
{
// Gestion de l'orientation
if(input.moveMouse()) {
orienter(input.getXRel(), input.getYRel());
}
// Avancée de la caméra
if(input.getKey(SDL_SCANCODE_UP)) {
m_position = m_position + m_orientation * m_vitesse;
m_pointCible = m_position + m_orientation;
}
// Recul de la caméra
if(input.getKey(SDL_SCANCODE_DOWN)) {
m_position = m_position - m_orientation * m_vitesse;
m_pointCible = m_position + m_orientation;
}
// Déplacement vers la gauche
if(input.getKey(SDL_SCANCODE_LEFT)) {
m_position = m_position + m_deplacementLateral * m_vitesse;
m_pointCible = m_position + m_orientation;
}
// Déplacement vers la droite
if(input.getKey(SDL_SCANCODE_RIGHT)) {
m_position = m_position - m_deplacementLateral * m_vitesse;
m_pointCible = m_position + m_orientation;
}
}
void Camera::lookAt(glm::mat4 &modelview)
{
// Actualisation de la vue dans la matrice
modelview = glm::lookAt(m_position, m_pointCible, m_axeVertical);
}
// Getters et Setters
void Camera::setPointcible()
{
// Calcul du vecteur orientation
m_orientation = m_pointCible - m_position;
m_orientation = normalize(m_orientation);
// Si l'axe vertical est l'axe X
if(m_axeVertical.x == 1.0) {
// Calcul des angles
m_phi = asin(m_orientation.x);
m_theta = acos(m_orientation.y / cos(m_phi));
if(m_orientation.y < 0)
m_theta *= -1;
}
// Si c'est l'axe Y
else if(m_axeVertical.y == 1.0)
{
// Calcul des angles
m_phi = asin(m_orientation.y);
m_theta = acos(m_orientation.z / cos(m_phi));
if(m_orientation.z < 0)
m_theta *= -1;
}
// Sinon c'est l'axe Z
else
{
// Calcul des angles
m_phi = asin(m_orientation.x);
m_theta = acos(m_orientation.z / cos(m_phi));
if(m_orientation.z < 0)
m_theta *= -1;
}
// Conversion en degrés
m_phi = m_phi * 180 / M_PI;
m_theta = m_theta * 180 / M_PI;
}
void Camera::setPosition(glm::vec3 position)
{
// Mise à jour de la position
m_position = position;
// Actualisation du point ciblé
m_pointCible = m_position + m_orientation;
}
float Camera::getSensibilite() const
{
return m_vitesse;
}
float Camera::getVitesse() const
{
return m_vitesse;
}
void Camera::setSensibilite(float sensibilite)
{
m_sensibilite = sensibilite;
}
void Camera::setVitesse(float vitesse)
{
m_vitesse = vitesse;
}
| [
"gregoire.nieto@inria.fr"
] | gregoire.nieto@inria.fr |
647a727c1b4e3df56f10a0b0d33642807e67c29c | 5205378bf9fd382cbb070d9170610a8d5e4b0f7a | /src/HomeAssistant/Components/Weather.hpp | 18ebe03d680fee03fe510e8544f57b6409fc7f4f | [
"MIT"
] | permissive | RobinSinghNanda/Home-assistant-display | 65d02124f59bb078945271489152eeeba6aa7e41 | 6f59104012c0956b54d4b55e190aa89941c2c1af | refs/heads/main | 2023-01-20T00:00:43.051506 | 2020-11-24T10:39:11 | 2020-11-24T10:39:11 | 306,589,564 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,932 | hpp | #ifndef __WEATHER_H__
#define __WEATHER_H__
#include "Entity.hpp"
#include "RtcTime.hpp"
namespace HomeAssistant {
class WeatherForecast {
public:
typedef const char * Condition;
WeatherForecast();
//condition
static constexpr Condition CONDITION_CLEAR_NIGHT = "clear-night";
static constexpr Condition CONDITION_CLOUDY = "cloudy";
static constexpr Condition CONDITION_EXCEPTIONAL = "exceptional";
static constexpr Condition CONDITION_FOG = "fog";
static constexpr Condition CONDITION_HAIL = "hail";
static constexpr Condition CONDITION_LIGHTNING = "lightning";
static constexpr Condition CONDITION_LIGHTNING_RAINY = "lightning-rainy";
static constexpr Condition CONDITION_PARTLYCLOUDY = "partlycloudy";
static constexpr Condition CONDITION_POURING = "pouring";
static constexpr Condition CONDITION_RAINY = "rainy";
static constexpr Condition CONDITION_SNOWY = "snowy";
static constexpr Condition CONDITION_SNOWY_RAINY = "snowy-rainy";
static constexpr Condition CONDITION_SUNNY = "sunny";
static constexpr Condition CONDITION_WINDY = "windy";
static constexpr Condition CONDITION_WINDY_VARIANT = "windy-variant";
//Attributes
static constexpr AttributeName ATTR_FORECAST_CONDITION = "condition";
static constexpr AttributeName ATTR_FORECAST_PRECIPITATION = "precipitation";
static constexpr AttributeName ATTR_FORECAST_PRECIPITATION_PROBABILITY = "precipitation_probability";
static constexpr AttributeName ATTR_FORECAST_TEMP = "temperature";
static constexpr AttributeName ATTR_FORECAST_TEMP_LOW = "templow";
static constexpr AttributeName ATTR_FORECAST_TIME = "datetime";
static constexpr AttributeName ATTR_FORECAST_WIND_BEARING = "wind_bearing";
static constexpr AttributeName ATTR_FORECAST_WIND_SPEED = "wind_speed";
//API
inline const char * getCondition();
inline float getPrecipitation();
inline float getPrecipitationProbability();
inline float getTemperature();
inline float getTemplow();
inline uint32_t getDatetime();
inline float getWindBearing();
inline float getWindSpeed();
inline const char * getIcon();
inline bool isCondition(const char * condition);
void updateAttributes(JsonObject attributesObject);
protected:
string icon = "";
string condition = "";
float precipitation = 0.0;
float precipitationProbability = 0.0;
float temperature = 0.0;
float templow = 0.0;
uint32_t datetime;
float windBearing = 0.0;
float windSpeed = 0.0;
void setIcon();
};
class Weather : public Entity {
public:
Weather(const char * entity);
virtual ~Weather();
static constexpr const char * ENTITY_DOMAIN = "weather";
//States
static constexpr State STATE_CLEAR_NIGHT = "clear-night";
static constexpr State STATE_CLOUDY = "cloudy";
static constexpr State STATE_EXCEPTIONAL = "exceptional";
static constexpr State STATE_FOG = "fog";
static constexpr State STATE_HAIL = "hail";
static constexpr State STATE_LIGHTNING = "lightning";
static constexpr State STATE_LIGHTNING_RAINY = "lightning-rainy";
static constexpr State STATE_PARTLYCLOUDY = "partlycloudy";
static constexpr State STATE_POURING = "pouring";
static constexpr State STATE_RAINY = "rainy";
static constexpr State STATE_SNOWY = "snowy";
static constexpr State STATE_SNOWY_RAINY = "snowy-rainy";
static constexpr State STATE_SUNNY = "sunny";
static constexpr State STATE_WINDY = "windy";
static constexpr State STATE_WINDY_VARIANT = "windy-variant";
static constexpr AttributeName ATTR_FORECAST = "forecast";
static constexpr AttributeName ATTR_WEATHER_ATTRIBUTION = "attribution";
static constexpr AttributeName ATTR_WEATHER_HUMIDITY = "humidity";
static constexpr AttributeName ATTR_WEATHER_OZONE = "ozone";
static constexpr AttributeName ATTR_WEATHER_PRESSURE = "pressure";
static constexpr AttributeName ATTR_WEATHER_TEMPERATURE = "temperature";
static constexpr AttributeName ATTR_WEATHER_VISIBILITY = "visibility";
static constexpr AttributeName ATTR_WEATHER_WIND_BEARING = "wind_bearing";
static constexpr AttributeName ATTR_WEATHER_WIND_SPEED = "wind_speed";
// static Icon ICON_ATTR_HUMIDITY = ICON_WATER_PERCENT;
// static Icon ICON_ATTR_WIND_BEARING = ICON_WEATHER_WINDY;
// static Icon ICON_ATTR_WIND_SPEED = ICON_WEATHER_WINDY;
// static Icon ICON_ATTR_PRESSURE = ICON_GAUGE;
// static Icon ICON_ATTR_VISIBILITY = ICON_WEATHER_FOG;
// static Icon ICON_ATTR_PRECIPITATION = ICON_WEATHER_RAINY;
//API
inline float getHumidity();
inline float getOzone();
inline float getPressure();
inline float getTemperature();
inline float getVisibility();
inline float getWindBearing();
inline float getWindSpeed();
inline uint8_t getNumForecasts();
const char * getAttributeIcon(const char * attribute);
inline WeatherForecast * getForecast(uint8_t index);
virtual void updateAttributes(JsonObject stateAttributesObject);
protected:
float humidity = 0;
float ozone = 0;
float pressure = 0;
float temperature = 0;
float visibility = 0;
float windBearing = 0;
float windSpeed = 0;
uint8_t numForecasts = 0;
std::vector<WeatherForecast*> forecasts;
virtual void setIcon();
};
float Weather::getHumidity() {
return humidity;
}
float Weather::getOzone() {
return ozone;
}
float Weather::getPressure() {
return pressure;
}
float Weather::getTemperature() {
return temperature;
}
float Weather::getVisibility() {
return visibility;
}
float Weather::getWindBearing() {
return windBearing;
}
float Weather::getWindSpeed() {
return windSpeed;
}
uint8_t Weather::getNumForecasts() {
return numForecasts;
}
WeatherForecast * Weather::getForecast(uint8_t index) {
if (index < numForecasts) {
return forecasts[index];
} else {
return nullptr;
}
}
const char * WeatherForecast::getCondition() {
return condition.c_str();
}
float WeatherForecast::getPrecipitation() {
return precipitation;
}
float WeatherForecast::getPrecipitationProbability() {
return precipitationProbability;
}
float WeatherForecast::getTemperature() {
return temperature;
}
float WeatherForecast::getTemplow() {
return templow;
}
uint32_t WeatherForecast::getDatetime() {
return datetime;
}
float WeatherForecast::getWindBearing() {
return windBearing;
}
float WeatherForecast::getWindSpeed() {
return windSpeed;
}
const char * WeatherForecast::getIcon() {
return this->icon.c_str();
}
bool WeatherForecast::isCondition(const char * condition) {
return this->condition.compare(condition) == 0;
}
};
#endif // __WEATHER_H__ | [
"nanda.robin.singh@gmail.com"
] | nanda.robin.singh@gmail.com |
eb1829662bd7248015e5b6b7ee9a9dd25951bcc0 | fc0495b4d677a6e46be7bebebeaf8d9f77e211e3 | /base/dsalgo_test/sort_test.cc | 58ad978a5baab6fe0b645b7d46915be4dbdadac5 | [] | no_license | caszhang/BackendDevelopmentEnvironment | 6bb558352a11932ad0c547ed835d8ead62bef231 | e6214e28022eaef08137edd20dcc7a7fe1b0a8d7 | refs/heads/master | 2021-09-20T21:32:39.017300 | 2018-08-15T14:58:39 | 2018-08-15T14:58:39 | 15,894,112 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,343 | cc | // Author: zhangguoqiang01 <80176975@qq.com>
#include <stdlib.h>
#include <time.h>
#include "gtest/gtest.h"
#include "dsalgo/sort.h"
int32_t IntegerCompare(const void *param_one, const void *param_two)
{
int32_t *one = (int32_t*)param_one;
int32_t *two = (int32_t*)param_two;
if (*one > *two) {
return 1;
} else if (*one < *two) {
return -1;
} else {
return 0;
}
}
class SortTest:public testing::Test
{
protected:
virtual void SetUp() {
}
virtual void TearDown() {
}
public:
};
TEST_F(SortTest, FirstTest)
{
int32_t array[] = {2, 3, 4, 1, -5, 0, 7};
printf("before:\n");
for (uint32_t i = 0; i < sizeof(array) / sizeof(int32_t); i++) {
printf("%d\n", array[i]);
}
//internal_sort::QSort((void*)array, sizeof(array) / sizeof(int32_t), sizeof(int32_t), IntegerCompare);
//internal_sort::HeapSort((void*)array, sizeof(array) / sizeof(int32_t), sizeof(int32_t), IntegerCompare);
//internal_sort::MergeSort((void*)array, sizeof(array) / sizeof(int32_t), sizeof(int32_t), IntegerCompare);
internal_sort::EQSort((void*)array, sizeof(array) / sizeof(int32_t), sizeof(int32_t), IntegerCompare);
printf("after:\n");
for (uint32_t i = 0; i < sizeof(array) / sizeof(int32_t); i++) {
printf("%d\n", array[i]);
}
}
TEST_F(SortTest, RandomTest)
{
int32_t array_size = 10;
srand((unsigned)time(NULL));
int32_t *array = new int32_t[array_size];
printf("before:\n");
for (int32_t i = 0; i < array_size; ++i) {
array[i] = rand() % 100;
printf("%d\n", array[i]);
}
//internal_sort::QSort((void*)array, sizeof(array) / sizeof(int32_t), sizeof(int32_t), IntegerCompare);
//internal_sort::HeapSort((void*)array, array_size, sizeof(int32_t), IntegerCompare);
//internal_sort::MergeSort((void*)array, array_size, sizeof(int32_t), IntegerCompare);
internal_sort::EQSort((void*)array, array_size, sizeof(int32_t), IntegerCompare);
printf("after:\n");
for (uint32_t i = 0; i < array_size; i++) {
printf("%d\n", array[i]);
}
delete[] array;
}
struct Node {
int32_t value;
std::string content;
Node() {
value = 0;
content = "";
}
};
int32_t StructCompare(const void *param_one, const void *param_two)
{
Node *one = (Node*)param_one;
Node *two = (Node*)param_two;
if (one->value > two->value) {
return -1;
} else if (one->value < two->value) {
return 1;
} else {
return 0;
}
}
TEST_F(SortTest, StructTest)
{
Node *array = new Node[8];
char buf[8];
printf("before:\n");
for (int i = 0; i < 8; i++) {
array[i].value = (i * 3 + 4) % 8;
snprintf(buf, 8, "%d", i);
array[i].content = buf;
printf("idx:%s, value:%d\n", array[i].content.c_str(), array[i].value);
}
//internal_sort::QSort((void*)array, 8, sizeof(Node), StructCompare);
//internal_sort::HeapSort((void*)array, 8, sizeof(Node), StructCompare);
//internal_sort::MergeSort((void*)array, 8, sizeof(Node), StructCompare);
internal_sort::EQSort((void*)array, 8, sizeof(Node), StructCompare);
printf("after:\n");
for (int i = 0; i < 8; i++) {
printf("idx:%s, value:%d\n", array[i].content.c_str(), array[i].value);
}
delete[] array;
}
| [
"80176975@qq.com"
] | 80176975@qq.com |
c2d192249d11150b18000df2969d590c437110c1 | 95c5416ba31ad47ae4ade267476ba71052a253d5 | /src/dji_sdk/src/modules/dji_sdk_node_time_sync.cpp | fa267ad0d26224c37294fb5c00bedbc271f099b6 | [] | no_license | moyang602/bit_mbzirc | 87dc435088e9a45d5ba35b773a5a0f8b411b0a8f | b74aabf4c0333c1097fd0044a8d8b10ed0200012 | refs/heads/master | 2020-08-28T23:35:02.428583 | 2020-01-19T08:18:16 | 2020-01-19T08:21:14 | 217,852,656 | 7 | 7 | null | 2019-10-27T12:59:55 | 2019-10-27T12:36:15 | CMake | UTF-8 | C++ | false | false | 2,510 | cpp | /** @file dji_sdk_node_time_sync.cpp
* @version 3.8.1
* @date May, 2019
*
* @brief
* Implementation of the time sync functions of DJISDKNode
*
* @copyright 2019 DJI. All rights reserved.
*
*/
#include <dji_sdk/dji_sdk_node.h>
void DJISDKNode::NMEACallback(Vehicle* vehiclePtr,
RecvContainer recvFrame,
UserData userData)
{
nmea_msgs::Sentence nmeaSentence;
int length = recvFrame.recvInfo.len - OpenProtocol::PackageMin - 4;
uint8_t rawBuf[length];
memcpy(rawBuf, recvFrame.recvData.raw_ack_array, length);
nmeaSentence.header.frame_id = "NMEA";
nmeaSentence.header.stamp = ros::Time::now();
nmeaSentence.sentence = std::string((char*)rawBuf, length);
DJISDKNode *p = (DJISDKNode *) userData;
p->time_sync_nmea_publisher.publish(nmeaSentence);
}
void DJISDKNode::GPSUTCTimeCallback(Vehicle *vehiclePtr,
RecvContainer recvFrame,
UserData userData)
{
dji_sdk::GPSUTC GPSUTC;
int length = recvFrame.recvInfo.len - OpenProtocol::PackageMin - 4;
uint8_t rawBuf[length];
memcpy(rawBuf, recvFrame.recvData.raw_ack_array, length);
GPSUTC.stamp = ros::Time::now();
GPSUTC.UTCTimeData = std::string((char*)rawBuf, length).c_str();
DJISDKNode *p = (DJISDKNode *) userData;
p->time_sync_gps_utc_publisher.publish(GPSUTC);
}
void DJISDKNode::FCTimeInUTCCallback(Vehicle* vehiclePtr,
RecvContainer recvFrame,
UserData userData)
{
dji_sdk::FCTimeInUTC fcTimeInUtc;
fcTimeInUtc.stamp = ros::Time::now();
fcTimeInUtc.fc_timestamp_us = recvFrame.recvData.fcTimeInUTC.fc_timestamp_us;
fcTimeInUtc.fc_utc_hhmmss = recvFrame.recvData.fcTimeInUTC.utc_hhmmss;
fcTimeInUtc.fc_utc_yymmdd = recvFrame.recvData.fcTimeInUTC.utc_yymmdd;
DJISDKNode *p = (DJISDKNode *) userData;
p->time_sync_fc_utc_publisher.publish(fcTimeInUtc);
}
void DJISDKNode::PPSSourceCallback(Vehicle* vehiclePtr,
RecvContainer recvFrame,
UserData userData)
{
std_msgs::String PPSSourceData;
std::vector<std::string> stringVec = {"0", "INTERNAL_GPS", "EXTERNAL_GPS", "RTK"};
DJISDKNode *p = (DJISDKNode *) userData;
if(recvFrame.recvData.ppsSourceType < stringVec.size())
{
PPSSourceData.data = stringVec[recvFrame.recvData.ppsSourceType];
p->time_sync_pps_source_publisher.publish(PPSSourceData);
}
}
| [
"test@bit.edu.cn"
] | test@bit.edu.cn |
46469d59838bacca4953dce337d7d2ff2684c924 | 14eb67918b2ce484029115135ea5cf6f0454b0da | /Week4Fireworks2/src/burstParticle.cpp | c796cc46b9c2e505856f9436d3d7e19c89062e22 | [] | no_license | Amiraanne/AmiraAnne_algo2012 | eadf7fe6b20fadce5d4baec11952118b7d682514 | 2765f728f65117710b35d87c2caac0544613a231 | refs/heads/master | 2021-01-20T07:15:08.008913 | 2012-12-18T22:19:54 | 2012-12-18T22:19:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 706 | cpp | /*
* burstParticle.cpp
* emptyExample
*
* Created by Amira Pettus on 10/28/12.
*/
#include "burstParticle.h"
burstParticle::burstParticle() {
setup(0, 0, 0, 0);
damping = 0.01f;
}
void burstParticle::setup(float px, float py, float vx, float vy) {
pos.set(px, py);
vel.set(vx, vy);
}
void burstParticle::resetForce() {
frc.set(0,0);
}
void burstParticle::addDampingForce() {
//frc.x -= vel.x * damping;
//frc.y -= vel.y * damping;
}
void burstParticle::update() {
vel = vel + frc;
pos.x += vel.x * cos(theta);
pos.y += vel.y * sin(theta);
}
void burstParticle::draw() {
ofPushMatrix();
ofTranslate(pos.x, pos.y);
ofCircle(2, 0, 2);
ofPopMatrix();
}
| [
"renavatio.desonar@gmail.com"
] | renavatio.desonar@gmail.com |
5e7caef092d9a9394a8b626d5193ee4a326c1cab | a5cea5298c0bf3f88111b3eb9245905e11a10094 | /test/indicator/FastNonDominatedRankTest.cpp | a11b10ff2a1752de513cf48cefd4b6afd84fe46a | [
"MIT"
] | permissive | blankjul/moo-cpp | a28feb2b37aadd91cdb84b6013f480ed0f1af9a0 | df9c20e70f17b8aa4041f8442dd7d6ae9a3de093 | refs/heads/master | 2022-07-30T05:32:55.477615 | 2015-07-01T20:35:26 | 2015-07-01T20:35:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 711 | cpp | #include "IndicatorTest.h"
#include "indicator/NonDominatedRank.h"
#include "indicator/FastNonDominatedRank.h"
#include <unordered_map>
class FastNonDominatedRankTest : public IndicatorTest {
public:
moo::Population<moo::Identity> population {100};
};
TEST_F(FastNonDominatedRankTest, RankOrderTestCorrect) {
auto m = moo::NonDominatedRank::calculate(population);
auto mfast = moo::FastNonDominatedRank::calculate(population);
EXPECT_EQ(m, mfast);
}
TEST_F(FastNonDominatedRankTest, RankOrderTestCorrectOnlySomeIndividuals) {
auto m = moo::NonDominatedRank::calculate_(population,20);
auto mfast = moo::FastNonDominatedRank::calculate_(population,20);
EXPECT_EQ(m, mfast);
}
| [
"jules89@arcor.de"
] | jules89@arcor.de |
68108298350fd665dffb7fab6b7c6e9a8460bfc0 | 97e02ecd270f47176ef8b6c5b89cfa9dd335d2a1 | /华东师范大学oj/3161. 位运算.cpp | 36d341b96c8f435e82fd6e5ec7d2a56f766af15a | [] | no_license | TechAoba/OJ-code | 61f06ce7a94cadd501457853da2f3c4932bb226e | 7e91b734bae170c4a7415984d4760740f677a26f | refs/heads/main | 2023-07-08T23:49:10.258066 | 2021-08-17T11:47:26 | 2021-08-17T11:47:26 | 300,805,551 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 426 | cpp | #include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
unsigned int a;
int p, len, st, en, A[32];
inline bool in(int a) {
if(a>=st && a<=en) return 1;
return 0;
}
int main()
{
cin>>a>>p>>len;
st = p-len+1, en=p;
unsigned int ans=0, quan=1, i;
for(i=0;i<32;i++) {
if(a&1) A[i] = 1;
if(in(i)) A[i] = 1-A[i];
if(A[i]) ans += quan;
quan *= 2;
a >>= 1;
}
printf("%u\n", ans);
return 0;
}
| [
"Techaoba@163.com"
] | Techaoba@163.com |
1921ba49e41bb0929f12726524c8a1d59e071835 | 1008456f8b0a764978b4cbc993692b1e0526d3ce | /ActualProject/tryNumber2/GameEngine/Texture.h | 81f5ff276939d61d51d21f15488979e741704d3b | [] | no_license | orleg01/openGl | 903805ce296dcc703feb9234e378102fa1d8345d | fe8925a76cb5d63e7457e0f6e2d656e5038b51f0 | refs/heads/master | 2021-01-10T06:03:27.821080 | 2016-02-20T20:21:37 | 2016-02-20T20:21:37 | 51,646,905 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 777 | h |
#ifndef __TEXTURE_H
#define __TEXTURE_H
#include <assimps\assimp\material.h>
#include <glew\GL\glew.h>
#include <glfw/GLFW/glfw3.h>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <vector>
#include <soil\SOIL.h>
#include <glm\glm.hpp>
//my Headers
class Texture;
using namespace std;
class Texture
{
public:
~Texture();
static Texture* getTexture(string path , glm::vec2 textureWarpOption);
static void setTexturesToShader(vector<Texture*> myTextures[] , GLuint shadId);
void unBind();
void Bind();
static void deleteAllTextures();
private:
static vector<Texture*> allTexture;
string path;
string nameOfTexture;
GLuint textureId;
glm::vec2 textureWarpOption;
Texture(string path , glm::vec2 textureWarpOption);
};
#endif | [
"orleg01@gmail.com"
] | orleg01@gmail.com |
e640b2fdb233de1e7850910c1dda018485310220 | 24e53da2e930fb4876bf7d3f7edb61e7d845b4fc | /Label.h | be5dce4b3740b168a2c87789b97c34095d0160b3 | [] | no_license | nickcuenca/GUI-Project | 631bc5faaa052d6825f36cdf0968cac2504772c8 | 841feb6fb52b46068c29fcf31ced2d98a57d0264 | refs/heads/master | 2023-05-19T19:46:41.119431 | 2021-06-06T05:58:20 | 2021-06-06T05:58:20 | 363,311,849 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 442 | h | //
// Created by Nicolas Cuenca on 4/9/2021.
//
#ifndef PROJECT_LABEL_H
#define PROJECT_LABEL_H
#include "SFML/Graphics.hpp"
class Label : public sf::Drawable {
private:
sf::Text text;
sf::Font font;
std::string labelInstruction = "Enter your information:\n";
public:
Label();
virtual void draw(sf::RenderTarget& window, sf::RenderStates states) const; //This function is to draw your text
};
#endif //PROJECT_LABEL_H
| [
"Nicolascuenca123@gmail.com"
] | Nicolascuenca123@gmail.com |
4f05f0916c3b570e0481b3463c275bee4b4fea74 | d4386cdd1bf16a903b8e4dfc3484eb19eef80b5c | /VEXU2018-2019/VEX Code Snippits/Drive Backward.cpp | 15f05d19dde2b82f6ee0c0350f935cb9c475c1ef | [] | no_license | TheRevilo2018/VEX-Robotics-SDSMT | 1535b21b77ba35493ee7b9c1d22ae23ae173b150 | b80a2ef00a2c4cf76301b81ce3ee3b3ec48db54f | refs/heads/master | 2023-08-15T07:34:05.839114 | 2021-09-27T04:18:15 | 2021-09-27T04:18:15 | 109,911,898 | 1 | 0 | null | 2021-05-24T19:59:30 | 2017-11-08T01:30:23 | C++ | UTF-8 | C++ | false | false | 1,850 | cpp | #include "robot-config.h"
/*+++++++++++++++++++++++++++++++++++++++++++++| Notes |++++++++++++++++++++++++++++++++++++++++++++++
Drive Backward
This program instructs your robot to move backward at half power for three seconds.
There is a two second pause at the beginning of the program.
Robot Configuration:
[Smart Port] [Name] [Type] [Description] [Reversed]
Motor Port 1 LeftMotor V5 Smart Motor Left side motor false
Motor Port 10 RightMotor V5 Smart Motor Right side motor true
----------------------------------------------------------------------------------------------------*/
int main() {
//Wait 2 seconds or 2000 milliseconds before starting the program.
vex::task::sleep(2000);
//Print to the screen that the program has started.
Brain.Screen.print("User Program has Started.");
//Set the velocity of the left and right motor to 50% power. This command will not make the motor spin.
LeftMotor.setVelocity(50, vex::velocityUnits::pct);
RightMotor.setVelocity(50, vex::velocityUnits::pct);
//Spin the right and left motor in the reverse direction. The motors will spin at 50% power because of the previous commands.
LeftMotor.spin(vex::directionType::rev);
RightMotor.spin(vex::directionType::rev);
//Wait 3 second or 3000 milliseconds.
vex::task::sleep(3000);
//Stop both motors.
LeftMotor.stop();
RightMotor.stop();
//Print to the brain's screen that the program has ended.
Brain.Screen.newLine();//Move the cursor to a new line on the screen.
Brain.Screen.print("User Program has Ended.");
//Prevent main from exiting with an infinite loop.
while(1) {
vex::task::sleep(100);//Sleep the task for a short amount of time to prevent wasted resources.
}
} | [
"matthew.reff@mines.sdsmt.edu"
] | matthew.reff@mines.sdsmt.edu |
49aee9798e21ff9fe00112d3b89e8952cac40e68 | 9028d5e85e3321869e94c3accf24bf67e0e07ee0 | /Tasks/task_20.cpp | e73c1eb837ff011bccd2553ad9289a937c975fcd | [] | no_license | pukala2/old_stuff | 525dc8b3601df9141cbcfe215c2e9971e6fef3ed | 2e45b8465b900b00c3781e716686c5df665f06d2 | refs/heads/master | 2020-03-24T08:11:37.674093 | 2018-07-27T14:50:55 | 2018-07-27T14:50:55 | 142,587,686 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 209 | cpp | #include <iostream>
template <class T>
void foo(T value)
{
static int counter;
++counter;
std::cout << counter << std::endl;
}
int main()
{
foo(4);
foo(5);
foo(5.5);
return 0;
}
| [
"przemyslaw.pukala@gmail.com"
] | przemyslaw.pukala@gmail.com |
4ae435cfd7434b8bb62f2477560b8974f32a083b | b43817bfaa62b9dc26b3b312b117c89021116586 | /src/SARibbonBar/SARibbonGalleryItem.cpp | d43d720ef3130e30ce31b7862400f92b889363f9 | [
"MIT"
] | permissive | PrimUV/SARibbon | 75f701f60d5915b68da9b90221333941f09b93fe | 2609a96c8a8e56600af663aaaf57e3c736bbf246 | refs/heads/master | 2023-06-25T22:57:30.153197 | 2021-07-21T15:08:18 | 2021-07-21T15:08:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,236 | cpp | #include "SARibbonGalleryItem.h"
#include "SARibbonGalleryGroup.h"
SARibbonGalleryItem::SARibbonGalleryItem()
: m_flsgs(Qt::ItemIsEnabled|Qt::ItemIsSelectable)
, m_action(nullptr)
{
}
SARibbonGalleryItem::SARibbonGalleryItem(const QIcon& icon)
: m_flsgs(Qt::ItemIsEnabled|Qt::ItemIsSelectable)
, m_action(nullptr)
{
setIcon(icon);
}
SARibbonGalleryItem::SARibbonGalleryItem(QAction *act)
: m_flsgs(Qt::ItemIsEnabled|Qt::ItemIsSelectable)
{
setAction(act);
}
SARibbonGalleryItem::~SARibbonGalleryItem()
{
}
void SARibbonGalleryItem::setData(int role, const QVariant& data)
{
m_datas[role] = data;
}
QVariant SARibbonGalleryItem::data(int role) const
{
if (m_action) {
switch (role)
{
case Qt::DisplayRole:
return (m_action->text());
case Qt::ToolTipRole:
return (m_action->toolTip());
case Qt::DecorationRole:
return (m_action->icon());
default:
break;
}
}
return (m_datas.value(role));
}
void SARibbonGalleryItem::setText(const QString& text)
{
setData(Qt::DisplayRole, text);
}
QString SARibbonGalleryItem::text() const
{
if (m_action) {
return (m_action->text());
}
return (data(Qt::DisplayRole).toString());
}
void SARibbonGalleryItem::setToolTip(const QString& text)
{
setData(Qt::ToolTipRole, text);
}
QString SARibbonGalleryItem::toolTip() const
{
if (m_action) {
return (m_action->toolTip());
}
return (data(Qt::ToolTipRole).toString());
}
void SARibbonGalleryItem::setIcon(const QIcon& ico)
{
setData(Qt::DecorationRole, ico);
}
QIcon SARibbonGalleryItem::icon() const
{
if (m_action) {
return (m_action->icon());
}
return (qvariant_cast<QIcon>(data(Qt::DecorationRole)));
}
bool SARibbonGalleryItem::isSelectable() const
{
return (m_flsgs & Qt::ItemIsSelectable);
}
void SARibbonGalleryItem::setSelectable(bool isSelectable)
{
if (isSelectable) {
m_flsgs |= Qt::ItemIsSelectable;
}else {
m_flsgs = (m_flsgs & (~Qt::ItemIsSelectable));
}
}
bool SARibbonGalleryItem::isEnable() const
{
if (m_action) {
return (m_action->isEnabled());
}
return (m_flsgs & Qt::ItemIsEnabled);
}
void SARibbonGalleryItem::setEnable(bool isEnable)
{
if (m_action) {
m_action->setEnabled(isEnable);
}
if (isEnable) {
m_flsgs |= Qt::ItemIsEnabled;
}else {
m_flsgs = (m_flsgs & (~Qt::ItemIsEnabled));
}
}
void SARibbonGalleryItem::setFlags(Qt::ItemFlags flag)
{
m_flsgs = flag;
if (m_action) {
m_action->setEnabled(flag & Qt::ItemIsEnabled);
}
}
Qt::ItemFlags SARibbonGalleryItem::flags() const
{
return (m_flsgs);
}
void SARibbonGalleryItem::setAction(QAction *act)
{
m_action = act;
if (act->isEnabled()) {
m_flsgs |= Qt::ItemIsEnabled;
}else {
m_flsgs = (m_flsgs & (~Qt::ItemIsEnabled));
}
}
QAction *SARibbonGalleryItem::action()
{
return (m_action);
}
| [
"czy.t@163.com"
] | czy.t@163.com |
d4899bb86e24dafe7b95252961c7ba0b3068cb0b | 08cde2396e1c6e2fc3de721570948a72cd9fa632 | /Subdivision/_3DStructure.h | 206f9f2f5c1ca747dd8e0d15d2e2b45df3bbb0d6 | [] | no_license | Gchenyu/3D_modeling | 65b59e39f17707d7fe721ca0f37dcdc94c95114c | 1f051a4d78542bac0864b9f406a8c7477613b005 | refs/heads/master | 2020-05-30T05:30:07.761781 | 2019-05-31T09:43:11 | 2019-05-31T09:43:11 | 189,561,996 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 2,043 | h | #pragma once
#ifndef _3DStructure_H_
#define _3DStructure_H_
/**************************总依赖*********************************/
//_3DStructure.h的依赖
#include <cmath>
#include <assert.h>
#include<iostream>
//Display.h的依赖
#include <GL/glut.h>
#include<GL/glu.h>
#include <stdio.h>
#include <windows.h>
//MeshStructure.h的依赖
#include<fstream>
#include<string>
#include<vector>
#include<algorithm>
/****************************************************************/
using namespace std;
/**************************三维向量结构定义*********************************/
class _3DStructure{
public:
float x, y, z;
_3DStructure(float _x = 0.0, float _y = 0.0, float _z = 0.0) :x(_x), y(_y), z(_z) {}
float Length() { return sqrt(x * x + y * y + z * z); }
void display() {
cout << "x=" << x << " y=" << y << " z=" << z << "\n";
}
};
/********************************向量基础运算,运算符符重载****************************************/
_3DStructure operator+(const _3DStructure& v1, const _3DStructure& v2) {
return _3DStructure(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z);
}
_3DStructure operator-(const _3DStructure& v1, const _3DStructure& v2) {
return _3DStructure(v1.x - v2.x, v1.y - v2.y, v1.z - v2.z);
}
_3DStructure operator-(const _3DStructure& v) {
return _3DStructure(-v.x, -v.y, -v.z);
}
_3DStructure operator*(const _3DStructure& v, float l) {
return _3DStructure(v.x*l, v.y*l, v.z*l);
}
_3DStructure operator*(float l, const _3DStructure & v) {
return _3DStructure(v.x*l, v.y*l, v.z*l);
}
_3DStructure operator/(const _3DStructure& v, float l) {
return _3DStructure(v.x / l, v.y / l, v.z / l);
}
//点乘
float operator^(const _3DStructure& v1, const _3DStructure& v2) {
return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z;
}
//叉乘
_3DStructure operator*(const _3DStructure& v1, const _3DStructure& v2) {
return _3DStructure(v1.y*v2.z - v1.z*v2.y, v1.z*v2.x - v1.x*v2.z, v1.x*v2.y - v1.y*v2.x);
}
#endif | [
"41496394+Gchenyu@users.noreply.github.com"
] | 41496394+Gchenyu@users.noreply.github.com |
83182affc4ade104e1e7f782f19a3899e92da01f | fd1ebd6643638503b3de0d61886295e0000a50f2 | /Arduino/libraries/USBHost/src/adk.cpp | 3d5602d312bfce31b96cd2f3981c5b788895e534 | [
"Apache-2.0",
"LGPL-2.1-or-later"
] | permissive | zwartepoester/sheldon | 20683aabe70a9d49fa17c78c83f8bca17a0e0252 | 7001551b65cd5b595a0a93e58528198d3d1e5553 | refs/heads/master | 2020-03-27T06:31:10.055745 | 2018-08-25T16:52:55 | 2018-08-25T16:52:55 | 146,112,676 | 0 | 0 | Apache-2.0 | 2018-08-25T16:45:46 | 2018-08-25T16:45:46 | null | UTF-8 | C++ | false | false | 10,233 | cpp | /* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
This software may be distributed and modified under the terms of the GNU
General Public License version 2 (GPL2) as published by the Free Software
Foundation and appearing in the file GPL2.TXT included in the packaging of
this file. Please note that GPL2 Section 2[b] requires that all works based
on this software must also be made publicly available under the terms of
the GPL2 ("Copyleft").
Contact information
-------------------
Circuits At Home, LTD
Web : http://www.circuitsathome.com
e-mail : support@circuitsathome.com
*/
/* Google ADK interface */
#include "adk.h"
const uint32_t ADK::epDataInIndex = 1;
const uint32_t ADK::epDataOutIndex = 2;
/**
* \brief ADK class constructor.
*/
ADK::ADK(USBHost *p, const char* pmanufacturer,
const char* pmodel,
const char* pdescription,
const char* pversion,
const char* puri,
const char* pserial) :
manufacturer(pmanufacturer),
model(pmodel),
description(pdescription),
version(pversion),
uri(puri),
serial(pserial),
pUsb(p),
bAddress(0),
bNumEP(1),
ready(false)
{
// Initialize endpoint data structures
for (uint32_t i = 0; i < ADK_MAX_ENDPOINTS; ++i)
{
epInfo[i].deviceEpNum = 0;
epInfo[i].hostPipeNum = 0;
epInfo[i].maxPktSize = (i) ? 0 : 8;
epInfo[i].epAttribs = 0;
epInfo[i].bmNakPower = (i) ? USB_NAK_NOWAIT : USB_NAK_MAX_POWER;
}
// Register in USB subsystem
if (pUsb)
{
pUsb->RegisterDeviceClass(this);
}
}
/**
* \brief Initialize connection to an Android Phone.
*
* \param parent USB device address of the Parent device.
* \param port USB device base address.
* \param lowspeed USB device speed.
*
* \return 0 on success, error code otherwise.
*/
uint32_t ADK::Init(uint32_t parent, uint32_t port, uint32_t lowspeed)
{
uint8_t buf[sizeof(USB_DEVICE_DESCRIPTOR)];
uint32_t rcode = 0;
UsbDevice *p = NULL;
EpInfo *oldep_ptr = NULL;
uint32_t adkproto = -1;
uint32_t num_of_conf = 0;
// Get memory address of USB device address pool
AddressPool &addrPool = pUsb->GetAddressPool();
TRACE_USBHOST(printf("ADK::Init\r\n");)
// Check if address has already been assigned to an instance
if (bAddress)
{
return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE;
}
// Get pointer to pseudo device with address 0 assigned
p = addrPool.GetUsbDevicePtr(0);
if (!p)
{
return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
}
if (!p->epinfo)
{
return USB_ERROR_EPINFO_IS_NULL;
}
// Save old pointer to EP_RECORD of address 0
oldep_ptr = p->epinfo;
// Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence
p->epinfo = epInfo;
p->lowspeed = lowspeed;
// Get device descriptor
rcode = pUsb->getDevDescr(0, 0, sizeof(USB_DEVICE_DESCRIPTOR), (uint8_t*)buf);
// Restore p->epinfo
p->epinfo = oldep_ptr;
if (rcode)
{
goto FailGetDevDescr;
}
// Allocate new address according to device class
bAddress = addrPool.AllocAddress(parent, false, port);
// Extract Max Packet Size from device descriptor
epInfo[0].maxPktSize = (uint8_t)((USB_DEVICE_DESCRIPTOR*)buf)->bMaxPacketSize0;
// Assign new address to the device
rcode = pUsb->setAddr(0, 0, bAddress);
if (rcode)
{
p->lowspeed = false;
addrPool.FreeAddress(bAddress);
bAddress = 0;
TRACE_USBHOST(printf("ADK::Init : setAddr failed with rcode %lu\r\n", rcode);)
return rcode;
}
TRACE_USBHOST(printf("ADK::Init : device address is now %lu\r\n", bAddress);)
p->lowspeed = false;
//get pointer to assigned address record
p = addrPool.GetUsbDevicePtr(bAddress);
if (!p)
{
return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
}
p->lowspeed = lowspeed;
// Assign epInfo to epinfo pointer - only EP0 is known
rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo);
if (rcode)
{
goto FailSetDevTblEntry;
}
// Check if ADK device is already in accessory mode; if yes, configure and exit
if (((USB_DEVICE_DESCRIPTOR*)buf)->idVendor == ADK_VID &&
(((USB_DEVICE_DESCRIPTOR*)buf)->idProduct == ADK_PID || ((USB_DEVICE_DESCRIPTOR*)buf)->idProduct == ADB_PID))
{
TRACE_USBHOST(printf("ADK::Init : Accessory mode device detected\r\n");)
/* Go through configurations, find first bulk-IN, bulk-OUT EP, fill epInfo and quit */
num_of_conf = ((USB_DEVICE_DESCRIPTOR*)buf)->bNumConfigurations;
TRACE_USBHOST(printf("ADK::Init : number of configuration is %lu\r\n", num_of_conf);)
for (uint32_t i = 0; i < num_of_conf; ++i)
{
ConfigDescParser<0, 0, 0, 0> confDescrParser(this);
delay(1);
rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser);
#if defined(XOOM)
//Added by Jaylen Scott Vanorden
if (rcode)
{
TRACE_USBHOST(printf("ADK::Init : Got 1st bad code for config: %lu\r\n", rcode);)
// Try once more
rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser);
}
#endif
if (rcode)
{
goto FailGetConfDescr;
}
if (bNumEP > 2)
{
break;
}
}
if (bNumEP == 3)
{
// Assign epInfo to epinfo pointer - this time all 3 endpoins
rcode = pUsb->setEpInfoEntry(bAddress, 3, epInfo);
if (rcode)
{
goto FailSetDevTblEntry;
}
}
// Set Configuration Value
rcode = pUsb->setConf(bAddress, 0, bConfNum);
if (rcode)
{
goto FailSetConf;
}
TRACE_USBHOST(printf("ADK::Init : ADK device configured successfully\r\n");)
ready = true;
return 0;
}
// Probe device - get accessory protocol revision
delay(1);
rcode = getProto((uint8_t*)&adkproto);
#if defined(XOOM)
// Added by Jaylen Scott Vanorden
if (rcode)
{
TRACE_USBHOST(printf("ADK::Init : Got 1st bad code for config: %lu\r\n", rcode);)
// Try once more
rcode = getProto((uint8_t*)&adkproto );
}
#endif
if (rcode)
{
goto FailGetProto;
}
TRACE_USBHOST(printf("ADK::Init : DK protocol rev. %lu", adkproto);)
// Send ID strings
sendStr(ACCESSORY_STRING_MANUFACTURER, manufacturer);
sendStr(ACCESSORY_STRING_MODEL, model);
sendStr(ACCESSORY_STRING_DESCRIPTION, description);
sendStr(ACCESSORY_STRING_VERSION, version);
sendStr(ACCESSORY_STRING_URI, uri);
sendStr(ACCESSORY_STRING_SERIAL, serial);
// Switch to accessory mode
// The Android phone will reset
rcode = switchAcc();
if (rcode)
{
goto FailSwAcc;
}
rcode = -1;
goto SwAttempt; // Switch to accessory mode
// Diagnostic messages
FailGetDevDescr:
TRACE_USBHOST(printf("ADK::Init getDevDescr : ");)
goto Fail;
FailSetDevTblEntry:
TRACE_USBHOST(printf("ADK::Init setDevTblEn : ");)
goto Fail;
FailGetProto:
TRACE_USBHOST(printf("ADK::Init getProto : ");)
goto Fail;
FailSwAcc:
TRACE_USBHOST(printf("ADK::Init swAcc : ");)
goto Fail;
SwAttempt:
TRACE_USBHOST(printf("ADK::Init Accessory mode switch attempt : ");)
goto Fail;
FailGetConfDescr:
TRACE_USBHOST(printf("ADK::Init getConf : ");)
goto Fail;
FailSetConf:
TRACE_USBHOST(printf("ADK::Init setConf : ");)
goto Fail;
Fail:
TRACE_USBHOST(printf("error code: %lu\r\n", rcode);)
Release();
return rcode;
}
/**
* \brief Extract bulk-IN and bulk-OUT endpoint information from configuration
* descriptor.
*
* \param conf Configuration number.
* \param iface Interface number.
* \param alt Alternate setting.
* \param proto Protocol version used.
* \param pep Pointer to endpoint descriptor.
*/
void ADK::EndpointXtract(uint32_t conf, uint32_t iface, uint32_t alt, uint32_t proto, const USB_ENDPOINT_DESCRIPTOR *pep)
{
if (bNumEP == 3)
{
return;
}
bConfNum = conf;
uint32_t index = 0;
uint32_t pipe = 0;
if ((pep->bmAttributes & 0x02) == 2)
{
index = ((pep->bEndpointAddress & 0x80) == 0x80) ? epDataInIndex : epDataOutIndex;
}
// Fill in the endpoint info structure
epInfo[index].deviceEpNum = pep->bEndpointAddress & 0x0F;
epInfo[index].maxPktSize = pep->wMaxPacketSize;
TRACE_USBHOST(printf("ADK::EndpointXtract : Found new endpoint\r\n");)
TRACE_USBHOST(printf("ADK::EndpointXtract : deviceEpNum: %lu\r\n", epInfo[index].deviceEpNum);)
TRACE_USBHOST(printf("ADK::EndpointXtract : maxPktSize: %lu\r\n", epInfo[index].maxPktSize);)
TRACE_USBHOST(printf("ADK::EndpointXtract : index: %lu\r\n", index);)
if (index == epDataInIndex)
pipe = UHD_Pipe_Alloc(bAddress, epInfo[index].deviceEpNum, UOTGHS_HSTPIPCFG_PTYPE_BLK, UOTGHS_HSTPIPCFG_PTOKEN_IN, epInfo[index].maxPktSize, 0, UOTGHS_HSTPIPCFG_PBK_1_BANK);
else if (index == epDataOutIndex)
pipe = UHD_Pipe_Alloc(bAddress, epInfo[index].deviceEpNum, UOTGHS_HSTPIPCFG_PTYPE_BLK, UOTGHS_HSTPIPCFG_PTOKEN_OUT, epInfo[index].maxPktSize, 0, UOTGHS_HSTPIPCFG_PBK_1_BANK);
// Ensure pipe allocation is okay
if (pipe == 0)
{
TRACE_USBHOST(printf("ADK::EndpointXtract : Pipe allocation failure\r\n");)
// Enumeration failed, so user should not perform write/read since isConnected will return false
return;
}
epInfo[index].hostPipeNum = pipe;
bNumEP++;
}
/**
* \brief Release USB allocated resources (pipes and address).
*
* \note Release call is made from USBHost.task() on disconnection events.
* \note Release call is made from Init() on enumeration failure.
*
* \return Always 0.
*/
uint32_t ADK::Release()
{
// Free allocated host pipes
UHD_Pipe_Free(epInfo[epDataInIndex].hostPipeNum);
UHD_Pipe_Free(epInfo[epDataOutIndex].hostPipeNum);
// Free allocated USB address
pUsb->GetAddressPool().FreeAddress(bAddress);
// Must have to be reset to 1
bNumEP = 1;
bAddress = 0;
ready = false;
return 0;
}
/**
* \brief Read from ADK.
*
* \param nreadbytes Return value containing the number of read bytes.
* \param datalen Buffer length.
* \param dataptr Buffer to store the incoming data.
*
* \return 0 on success, error code otherwise.
*/
uint32_t ADK::read(uint32_t *nreadbytes, uint32_t datalen, uint8_t *dataptr)
{
*nreadbytes = datalen;
return pUsb->inTransfer(bAddress, epInfo[epDataInIndex].deviceEpNum, nreadbytes, dataptr);
}
/**
* \brief Write to ADK.
*
* \param datalen Amount of data to send. This parameter shall not exceed
* dataptr length.
* \param dataptr Buffer containing the data to be sent.
*
* \return 0 on success, error code otherwise.
*/
uint32_t ADK::write(uint32_t datalen, uint8_t *dataptr)
{
return pUsb->outTransfer(bAddress, epInfo[epDataOutIndex].deviceEpNum, datalen, dataptr);
}
| [
"dave.shinsel@gmail.com"
] | dave.shinsel@gmail.com |
54b0a06093fd6f6a5f78507f2238bb2a8540612d | f1f230510bfc867c43f8563f33d3a756dd162b45 | /lib/GFX_Library_for_Arduino/src/display/Arduino_ILI9341.cpp | 09b5c29b5ed2af4e166133d00f3e0d185f6fa303 | [] | no_license | Tinyu-Zhao/roundDisplay | 60bae3b54416ae1cf5a600882b98bbd17bdc3dd0 | 84ced7b6cffbf624d86c97cea30776baf2362d37 | refs/heads/master | 2023-08-23T18:03:59.864231 | 2021-09-16T13:01:47 | 2021-09-16T13:01:47 | 399,998,448 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,630 | cpp | /*
* start rewrite from:
* https://github.com/adafruit/Adafruit-GFX-Library.git
* https://github.com/adafruit/Adafruit_ILI9341.git
*/
#include "Arduino_ILI9341.h"
Arduino_ILI9341::Arduino_ILI9341(Arduino_DataBus *bus, int8_t rst, uint8_t r)
: Arduino_TFT(bus, rst, r, false, ILI9341_TFTWIDTH, ILI9341_TFTHEIGHT, 0, 0, 0, 0)
{
}
void Arduino_ILI9341::begin(int32_t speed)
{
Arduino_TFT::begin(speed);
}
// Companion code to the above tables. Reads and issues
// a series of LCD commands stored in PROGMEM byte array.
void Arduino_ILI9341::tftInit()
{
if (_rst < 0)
{
_bus->sendCommand(ILI9341_SWRESET); // 1: Software reset
delay(ILI9341_RST_DELAY);
}
spi_operation_t ili9341_init_operations[] = {
{BEGIN_WRITE, 0},
{WRITE_COMMAND_8, ILI9341_PWCTR1}, // Power control VRH[5:0]
{WRITE_DATA_8, 0x23},
{WRITE_COMMAND_8, ILI9341_PWCTR2}, // Power control SAP[2:0];BT[3:0]
{WRITE_DATA_8, 0x10},
{WRITE_COMMAND_8, ILI9341_VMCTR1}, // VCM control
{WRITE_DATA_8, 0x3e},
{WRITE_DATA_8, 0x28},
{WRITE_COMMAND_8, ILI9341_VMCTR2}, // VCM control2
{WRITE_DATA_8, 0x86},
{WRITE_COMMAND_8, ILI9341_VSCRSADD}, // Vertical scroll zero
{WRITE_DATA_8, 0x00},
{WRITE_COMMAND_8, ILI9341_PIXFMT},
{WRITE_DATA_8, 0x55},
{WRITE_COMMAND_8, ILI9341_FRMCTR1},
{WRITE_DATA_8, 0x00},
{WRITE_DATA_8, 0x18},
{WRITE_COMMAND_8, ILI9341_DFUNCTR}, // Display Function Control
{WRITE_DATA_8, 0x08},
{WRITE_DATA_8, 0x82},
{WRITE_DATA_8, 0x27},
{WRITE_COMMAND_8, ILI9341_SLPOUT}, // Exit Sleep
{END_WRITE, 0},
{DELAY, ILI9341_SLPOUT_DELAY},
{BEGIN_WRITE, 0},
{WRITE_COMMAND_8, ILI9341_DISPON}, // Display on
{END_WRITE, 0},
};
_bus->batchOperation(ili9341_init_operations, sizeof(ili9341_init_operations) / sizeof(ili9341_init_operations[0]));
}
void Arduino_ILI9341::writeAddrWindow(uint16_t x, uint16_t y, uint16_t w, uint16_t h)
{
if ((x != _currentX) || (w != _currentW))
{
_bus->writeC8D16D16(ILI9341_CASET, x + _xStart, x + w - 1 + _xStart);
_currentX = x;
_currentW = w;
}
if ((y != _currentY) || (h != _currentH))
{
_bus->writeC8D16D16(ILI9341_PASET, y + _yStart, y + h - 1 + _yStart);
_currentY = y;
_currentH = h;
}
_bus->writeCommand(ILI9341_RAMWR); // write to RAM
}
/**************************************************************************/
/*!
@brief Set origin of (0,0) and orientation of TFT display
@param m The index for rotation, from 0-3 inclusive
*/
/**************************************************************************/
void Arduino_ILI9341::setRotation(uint8_t r)
{
Arduino_TFT::setRotation(r);
switch (_rotation)
{
case 0:
r = (ILI9341_MADCTL_MX | ILI9341_MADCTL_BGR);
break;
case 1:
r = (ILI9341_MADCTL_MV | ILI9341_MADCTL_BGR);
break;
case 2:
r = (ILI9341_MADCTL_MY | ILI9341_MADCTL_BGR);
break;
case 3:
r = (ILI9341_MADCTL_MX | ILI9341_MADCTL_MY | ILI9341_MADCTL_MV | ILI9341_MADCTL_BGR);
break;
}
_bus->beginWrite();
_bus->writeC8D8(ILI9341_MADCTL, r);
_bus->endWrite();
}
void Arduino_ILI9341::invertDisplay(bool i)
{
_bus->sendCommand(i ? ILI9341_INVON : ILI9341_INVOFF);
}
void Arduino_ILI9341::displayOn(void)
{
_bus->sendCommand(ILI9341_SLPOUT);
delay(ILI9341_SLPOUT_DELAY);
}
void Arduino_ILI9341::displayOff(void)
{
_bus->sendCommand(ILI9341_SLPIN);
delay(ILI9341_SLPIN_DELAY);
}
| [
"Tinyu.Zhao@gmail.com"
] | Tinyu.Zhao@gmail.com |
b614a3816b71b2872a3b16eaaa5a932ad1a597b9 | f68c1a09ade5d969f3973246747466e4a540ff74 | /src/prod/src/Management/DnsService/include/INetIoManager.h | e8405887b0c630b30ec42f667dabdfbf74caf268 | [
"MIT"
] | permissive | GitTorre/service-fabric | ab38752d4cc7c8f2ee03553372c0f3e05911ff67 | 88da19dc5ea8edfe1c9abebe25a5c5079995db63 | refs/heads/master | 2021-04-09T10:57:45.678751 | 2018-08-20T19:17:28 | 2018-08-20T19:17:28 | 125,401,516 | 0 | 0 | MIT | 2018-03-15T17:13:53 | 2018-03-15T17:13:52 | null | UTF-8 | C++ | false | false | 3,576 | h | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#pragma once
#include "IDnsTracer.h"
namespace DNS
{
#if defined(PLATFORM_UNIX)
#define WSA_IO_PENDING (ERROR_IO_PENDING)
#define WSA_OPERATION_ABORTED (WSAEINTR)
#endif
typedef KDelegate<void(__in NTSTATUS)> UdpListenerCallback;
typedef KDelegate<void(__in NTSTATUS, __in KBuffer&, __in ULONG)> UdpReadOpCompletedCallback;
typedef KDelegate<void(__in NTSTATUS, __in ULONG)> UdpWriteOpCompletedCallback;
interface ISocketAddress
{
K_SHARED_INTERFACE(ISocketAddress);
public:
virtual PVOID Address() = 0;
virtual socklen_t Size() const = 0;
virtual socklen_t* SizePtr() = 0;
};
void CreateSocketAddress(
__out ISocketAddress::SPtr& spAddress,
__in KAllocator& allocator
);
void CreateSocketAddress(
__out ISocketAddress::SPtr& spAddress,
__in KAllocator& allocator,
__in ULONG address,
__in USHORT port
);
interface IUdpListener
{
K_SHARED_INTERFACE(IUdpListener);
public:
virtual bool StartListener(
__in_opt KAsyncContextBase* const parent,
__inout USHORT& port,
__in UdpListenerCallback completionCallback
) = 0;
virtual bool CloseAsync(
) = 0;
virtual void ReadAsync(
__out KBuffer& buffer,
__out ISocketAddress& addressFrom,
__in UdpReadOpCompletedCallback readCallback,
__in ULONG timeoutInMs
) = 0;
virtual void WriteAsync(
__in KBuffer& buffer,
__in ULONG numberOfBytesToWrite,
__in ISocketAddress& addressTo,
__in UdpWriteOpCompletedCallback writeCallback
) = 0;
};
interface IUdpAsyncOp
{
K_SHARED_INTERFACE(IUdpAsyncOp);
public:
virtual void IOCP_Completion(
__in ULONG status,
__in ULONG bytesTransferred
) = 0;
virtual KBuffer::SPtr GetBuffer() = 0;
virtual ULONG GetBufferDataLength() = 0;
virtual ISocketAddress::SPtr GetAddress() = 0;
};
interface INetIoManager
{
K_SHARED_INTERFACE(INetIoManager);
public:
virtual void StartManager(
__in_opt KAsyncContextBase* const parent
) = 0;
virtual void CloseAsync() = 0;
virtual void CreateUdpListener(
__out IUdpListener::SPtr& spListener
) = 0;
#if defined(PLATFORM_UNIX)
virtual bool RegisterSocket(
__in SOCKET socket
) = 0;
virtual void UnregisterSocket(
__in SOCKET socket
) = 0;
virtual int ReadAsync(
__in SOCKET socket,
__in IUdpAsyncOp& overlapOp,
__out ULONG& bytesRead
) = 0;
virtual int WriteAsync(
__in SOCKET socket,
__in KBuffer& buffer,
__in ULONG count,
__in ISocketAddress& address,
__in IUdpAsyncOp& overlapOp,
__out ULONG& bytesWritten
) = 0;
#endif
};
void CreateNetIoManager(
__out INetIoManager::SPtr& spManager,
__in KAllocator& allocator,
__in const IDnsTracer::SPtr& spTracer,
__in ULONG numberOfConcurrentQueries
);
}
| [
"noreply-sfteam@microsoft.com"
] | noreply-sfteam@microsoft.com |
e09b12f37fb2e476acc9582eb74e525f6831f328 | 15a5465e10831bbad713827d08eec2f34dd272c3 | /source/Objeto.cpp | b986dd7f9374b2fcd28c4bccc21ae27205133b54 | [
"MIT"
] | permissive | JoaoPedroAssis/Jankenpo | 7e1b5d67580795df46d1ee30edc6612bbfd2fc41 | 86e35dbb7d48c3015abe4efcebd3009aa482d0e1 | refs/heads/master | 2020-04-11T16:10:51.053933 | 2018-12-15T21:42:24 | 2018-12-15T21:42:24 | 161,914,055 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 957 | cpp | // Copyright 2018 João Pedro Assis
#include "../include/Objeto.h"
Objeto::Objeto(int X, int Y) {
srcRect = new SDL_Rect;
destRect = new SDL_Rect;
pos_X = X;
pos_Y = Y;
srcRect->x = 0;
srcRect->y = 0;
}
int Objeto::get_x() {
return pos_X;
}
int Objeto::get_y() {
return pos_Y;
}
void Objeto::set_x(int X) {
pos_X = destRect->x = X;
}
void Objeto::set_y(int Y) {
pos_Y = destRect->y = Y;
}
void Objeto::render(SDL_Renderer* r) {
SDL_RenderCopy(r, this->textura, srcRect, destRect);
}
void Objeto::mudaTextura(SDL_Texture* textura) {
this->textura = textura;
}
void Objeto::setSrcRect(int x, int y, int w, int h) {
srcRect->x = x;
srcRect->y = y;
srcRect->w = w;
srcRect->h = h;
}
void Objeto::setDestRect(int x, int y, int w, int h) {
destRect->x = x;
destRect->y = y;
destRect->w = w;
destRect->h = h;
}
Objeto::~Objeto() {
delete srcRect;
delete destRect;
}
| [
"joapedroassisdossantos@gmail.com"
] | joapedroassisdossantos@gmail.com |
b7ad2199f6495064c887bbcb320d0dd2c879c8e3 | 1d7bea41cf1982b6d5909385cb7ef19e0a7b5aaa | /code/pixel_parser.cpp | 0333035a41cfb8bae1877972d2a869ffccf3f2ed | [
"MIT"
] | permissive | DonutLaser/laser-pixel | d7be88656c0f851b1a37b9ef14e05d34019ced8d | 3f7762c8a748b50fe218b9763972d46795047738 | refs/heads/master | 2020-04-18T19:42:28.568008 | 2019-02-24T14:08:18 | 2019-02-24T14:08:18 | 167,718,727 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,743 | cpp | #include "pixel_parser.h"
#include "../third_party/gui_string_buffer.h"
#include "../third_party/gui_utility.h"
#define SYMBOL_LEFT_BRACKET '['
#define SYMBOL_RIGHT_BRACKET ']'
#define SYMBOL_FRAME_END '-'
static bool is_whitespace (char c) {
return c == '\n' || c == '\t' || c == '\r' || c == ' ';
}
static void skip_whitespace (char** text) {
while (is_whitespace (**text))
++(*text);
}
static token get_next_token (char** text) {
skip_whitespace (text);
bool is_color_value = false;
unsigned count = 0;
token result = { };
result.type = TT_COUNT;
char* value_start = *text;
while (!is_whitespace (**text)) {
if (**text == SYMBOL_LEFT_BRACKET || **text == SYMBOL_RIGHT_BRACKET)
result.type = TT_COLOR;
else if (**text == SYMBOL_FRAME_END)
result.type = TT_FRAME_END;
++count;
++(*text);
}
str_copy (value_start, result.value, 0, count);
result.value[count] = '\0';
return result;
}
static int parse_number (char* value) {
return utility_is_integer (value) ? utility_string_to_int (value) : 0;
}
static void parse_color (char* value, int* color, unsigned* amount) {
unsigned count = 0;
char* value_start = value;
while (*value != '\0') {
if (*value == SYMBOL_LEFT_BRACKET) {
char color_value[MAX_TOKEN_LENGTH];
str_copy (value_start, color_value, 0, count);
color_value[count] = '\0';
*color = parse_number (color_value);
count = 0;
++value;
value_start = value;
continue;
}
else if (*value == SYMBOL_RIGHT_BRACKET) {
char amount_value[MAX_TOKEN_LENGTH];
str_copy (value_start, amount_value, 0, count);
amount_value[count] = '\0';
*amount = (unsigned)parse_number (amount_value);
}
++count;
++value;
}
}
ppp parse_ppp (char* text) {
ppp result = { };
unsigned start_x = 0;
unsigned start_y = 0;
unsigned frame = 0;
token t = { };
do {
t = get_next_token (&text);
unsigned amount = 0;
int color = -1;
if (t.type == TT_COUNT)
result.frame_count = (unsigned)parse_number (t.value);
else if (t.type == TT_COLOR) {
if (amount == 0) {
color = -1;
amount = 0;
parse_color (t.value, &color, &amount);
}
for (unsigned y = start_y; y < GRID_TILE_COUNT_Y; ++y) {
for (unsigned x = start_x; x < GRID_TILE_COUNT_X; ++x) {
result.frames[frame].grid[y][x] = color;
--amount;
if (amount == 0) {
if (x < GRID_TILE_COUNT_X - 1) {
start_x = x + 1;
start_y = y;
}
else {
start_x = 0;
start_y = y + 1;
}
break;
}
}
if (amount == 0)
break;
else
start_x = 0;
}
}
else if (t.type == TT_FRAME_END) {
++frame;
start_x = 0;
start_y = 0;
}
}
while (frame != result.frame_count);
return result;
} | [
"vidmantas.luneckas@gmail.com"
] | vidmantas.luneckas@gmail.com |
d7698fc8fbf51d7438c44271fb1e909fe1fe2b54 | 1e229c70a50309e6082abe7266eb53d6021d6433 | /include/shiokaze/array/macarray_extrapolator3.h | 0a27c75198b95d3f854720a0162da74d988d67e6 | [] | no_license | ryichando/shiokaze | e3d8a688c25a5aabb4eac6576bcc4510436d181d | 62e25b38882a1676c4a84181aa8eedaf716a0d0e | refs/heads/master | 2022-06-21T04:10:44.898687 | 2022-06-13T11:04:55 | 2022-06-13T11:04:55 | 149,598,476 | 57 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 2,076 | h | /*
** macarray_extrapolator3.h
**
** This is part of Shiokaze, a research-oriented fluid solver for computer graphics.
** Created by Ryoichi Ando <rand@nii.ac.jp> on Feb 14, 2018.
**
** Permission is hereby granted, free of charge, to any person obtaining a copy of
** this software and associated documentation files (the "Software"), to deal in
** the Software without restriction, including without limitation the rights to use,
** copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
** Software, and to permit persons to whom the Software is furnished to do so,
** subject to the following conditions:
**
** The above copyright notice and this permission notice shall be included in all copies
** or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
** INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
** PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
** HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
** CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
** OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//
#ifndef SHKZ_MACARRAY_EXTRAPOLATOR3_H
#define SHKZ_MACARRAY_EXTRAPOLATOR3_H
//
#include "array_extrapolator3.h"
//
SHKZ_BEGIN_NAMESPACE
//
/** @file */
/// \~english @brief Namespace that implements MAC array extrapolation.
/// \~japanese @brief MAC グリッドの外挿を実装する名前空間。
namespace macarray_extrapolator3 {
/**
\~english @brief Extrapolate MAC array.
@param[in] array Grid to extrapolate.
@param[in] width Extrapolation count.
\~japanese @brief MAC グリッドを外挿する。
@param[in] array 外挿を行うグリッド。
@param[in] width 外挿する回数。
*/
template<class T> void extrapolate ( macarray3<T> &array, int width ) {
for( int dim : DIMS3 ) {
array_extrapolator3::extrapolate<T>(array[dim],width);
}
};
};
//
SHKZ_END_NAMESPACE
//
#endif
// | [
"rand@nii.ac.jp"
] | rand@nii.ac.jp |
15d8625ced8955c8ce1a2f2bad71fb77f4c9eec0 | bcecb8afcad65531b2544cc910e8647bbaa4d0f3 | /OpenGLTemplate/HeightMapTerrain.cpp | cd376dbf274997b6096eb8a9ee7d183a7f0c9a43 | [
"Apache-2.0"
] | permissive | ferenc-schultesz/3DRacerGame | 924913f3619f2a7297bc668ecb6151fb5e2d41cb | 34784f0dbdbade13fe4f6b00f5d1327aabaa1ef2 | refs/heads/master | 2020-04-12T03:44:36.693446 | 2018-12-18T11:13:50 | 2018-12-18T11:13:50 | 162,275,996 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,008 | cpp | #include "HeightMapTerrain.h"
#pragma comment(lib, "lib/FreeImage.lib")
CHeightMapTerrain::CHeightMapTerrain()
{
m_dib = NULL;
}
CHeightMapTerrain::~CHeightMapTerrain()
{
delete [] m_heightMap;
}
// Convert a point from image (pixel) coordinates to world coordinates
glm::vec3 CHeightMapTerrain::ImageToWorldCoordinates(glm::vec3 p)
{
// Normalize the image point so that it in the range [-1, 1] in x and [-1, 1] in z
p.x = 2.0f * (p.x / m_width) - 1.0f;
p.z = 2.0f * (p.z / m_height) - 1.0f;
// Now scale the point so that the terrain has the right size in x and z
p.x *= m_terrainSizeX / 2.0f;
p.z *= m_terrainSizeZ / 2.0f;
// Now translate the point based on the origin passed into the function
p += m_origin;
return p;
}
// Convert a point from world coordinates to image (pixel) coordinates
glm::vec3 CHeightMapTerrain::WorldToImageCoordinates(glm::vec3 p)
{
p -= m_origin;
// Normalize the image point so that it in the range [-1, 1] in x and [-1, 1] in z
p.x *= 2.0f / m_terrainSizeX;
p.z *= 2.0f / m_terrainSizeZ;
// Now transform the point so that it is in the range [0, 1] in x and [0, 1] in z
p.x = (p.x + 1.0f) * (m_width / 2.0f);
p.z = (p.z + 1.0f) * (m_height / 2.0f);
return p;
}
bool CHeightMapTerrain::GetImageBytes(char *terrainFilename, BYTE **bDataPointer, unsigned int &width, unsigned int &height)
{
FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
fif = FreeImage_GetFileType(terrainFilename, 0); // Check the file signature and deduce its format
if(fif == FIF_UNKNOWN) // If still unknown, try to guess the file format from the file extension
fif = FreeImage_GetFIFFromFilename(terrainFilename);
if(fif == FIF_UNKNOWN) // If still unknown, return failure
return false;
if(FreeImage_FIFSupportsReading(fif)) // Check if the plugin has reading capabilities and load the file
m_dib = FreeImage_Load(fif, terrainFilename);
if(!m_dib) {
char message[1024];
sprintf_s(message, "Cannot load image\n%s\n", terrainFilename);
MessageBox(NULL, message, "Error", MB_ICONERROR);
return false;
}
*bDataPointer = FreeImage_GetBits(m_dib); // Retrieve the image data
width = FreeImage_GetWidth(m_dib);
height = FreeImage_GetHeight(m_dib);
// If somehow one of these failed (they shouldn't), return failure
if(bDataPointer == NULL || width == 0 || height == 0)
return false;
return true;
}
// This function generates a heightmap terrain based on a bitmap
bool CHeightMapTerrain::Create(char *terrainFilename, char *textureFilename, glm::vec3 origin, float terrainSizeX, float terrainSizeZ, float terrainHeightScale)
{
BYTE *bDataPointer;
unsigned int width, height;
if (GetImageBytes(terrainFilename, &bDataPointer, width, height) == false)
return false;
m_width = width;
m_height = height;
m_origin = origin;
m_terrainSizeX = terrainSizeX;
m_terrainSizeZ = terrainSizeZ;
// Allocate memory and initialize to store the image
m_heightMap = new float[m_width * m_height];
if (m_heightMap == NULL)
return false;
// Clear the heightmap
memset(m_heightMap, 0, m_width * m_height * sizeof(float));
// Form mesh
std::vector<CVertex> vertices;
std::vector<unsigned int> triangles;
float halfSizeX = m_width / 2.0f;
float halfSizeY = m_height / 2.0f;
int X = 1;
int Z = m_width;
int triangleId = 0;
for (int z = 0; z < m_height; z++) {
for (int x = 0; x < m_width; x++) {
int index = x + z * m_width;
// Retreive the colour from the terrain image, and set the normalized height in the range [0, 1]
float grayScale = (bDataPointer[index*3] + bDataPointer[index*3+1] + bDataPointer[index*3+2]) / 3.0f;
float height = (grayScale - 128.0f) / 128.0f;
// Make a point based on this pixel position. Then, transform so that the mesh has the correct size and origin
// This transforms a point in image coordinates to world coordinates
glm::vec3 pImage = glm::vec3((float) x, height, (float) z);
glm::vec3 pWorld = ImageToWorldCoordinates(pImage);
// Scale the terrain and store for later
pWorld.y *= terrainHeightScale;
m_heightMap[index] = pWorld.y;
// Store the point in a vector
CVertex v = CVertex(pWorld, glm::vec2(0.0, 0.0), glm::vec3(0.0, 0.0, 0.0));
vertices.push_back(v);
}
}
FreeImage_Unload(m_dib);
// Form triangles from successive rows of the image
for (int z = 0; z < m_height-1; z++) {
for (int x = 0; x < m_width-1; x++) {
int index = x + z * m_width;
triangles.push_back(index);
triangles.push_back(index+X+Z);
triangles.push_back(index+X);
triangles.push_back(index);
triangles.push_back(index+Z);
triangles.push_back(index+X+Z);
}
}
// Create a face vertex mesh
m_mesh.CreateFromTriangleList(vertices, triangles);
// Load a texture for texture mapping the mesh
m_texture0.Load(textureFilename, true);
m_texture1.Load("resources\\textures\\dirtpile01.jpg", true);
return true;
}
// For a point p in world coordinates, return the height of the terrain
float CHeightMapTerrain::ReturnGroundHeight(glm::vec3 p)
{
// Undo the transformation going from image coordinates to world coordinates
glm::vec3 pImage = WorldToImageCoordinates(p);
// Bilinear interpolation.
int xl = (int) floor(pImage.x);
int zl = (int) floor (pImage.z);
// Check if the position is in the region of the heightmap
if (xl < 0 || xl >= m_width - 1 || zl < 0 || zl >= m_height -1)
return 0.0f;
// Get the indices of four pixels around the current point
int indexll = xl + zl * m_width;
int indexlr = (xl+1) + zl * m_width;
int indexul = xl + (zl+1) * m_width;
int indexur = (xl+1) + (zl+1) * m_width;
// Interpolation amounts in x and z
float dx = pImage.x - xl;
float dz = pImage.z - zl;
// Interpolate -- first in x and and then in z
float a = (1-dx) * m_heightMap[indexll] + dx * m_heightMap[indexlr];
float b = (1-dx) * m_heightMap[indexul] + dx * m_heightMap[indexur];
float c = (1-dz) * a + dz * b;
return c;
}
void CHeightMapTerrain::Render()
{
m_texture0.Bind(0);
m_texture1.Bind(1);
m_mesh.Render();
} | [
"ferenc.schultesz@gmail.com"
] | ferenc.schultesz@gmail.com |
5d4cebc7a63f975477af920a4319ba41facf16fb | 89a8387418064c0523a8fffb5535086f2a2882e9 | /lhop_v1/src/utils/zlib_compress.h | 3229019397630c8cbb39d21c351860507ff4cf58 | [] | no_license | pacman-project/LHOP | 5704cdd8577537fb3135c18404d1e3c5a77c7caa | 9a82fddc5befaade28ba1cdfc8567092cd318cad | refs/heads/master | 2021-03-30T17:51:01.994612 | 2014-05-20T22:53:11 | 2014-05-20T22:53:11 | 11,122,668 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,901 | h |
#ifndef _ZLIB_COMPRESS_H_
#define _ZLIB_COMPRESS_H_
#include <string>
#include <iostream>
#if defined WIN32 | defined WIN64
#include <typeinfo.h>
#else
#include <typeinfo>
#endif
#include <zlib.h>
using namespace std;
// zlib (de)compression class
///////////////////////////////////////////////////////////////////////////////
class zlib_compress {
private:
static const int CHUNK = 512*1024; // 512 KB (bigger chunk better compression)
// buffer for compression
char* buffer_in;
char* buffer_out;
// current position of empty data on buffer_in (starts with 0) if using for write_to_buf_and_compress
// else current possition of data to be read in buffer_out if using read_to_buf_and_decompress
int buffer_pos;
// zlib compression level
int compression_level;
z_stream zlib_stream;
istream* in;
ostream* out;
// compresses chunk from buffer_in and writes it to this->out stream
void compress_chunk(int flush_flag);
// reades chunk data from this->in stream to buffer_in and
// returns decompressed in buffer_out
void decompress_chunk(int flush_flag);
public:
/**
* This method must be called before any (de)compression begins
* It will call inflateInit or deflateInit and prepare all necessary buffers.
* Same function is used for compression and decompression.
* Set argument decompress = true for decompression otherwise compression is used (default).
*/
void begin_compression(bool decompress = false);
/**
* Writes data of 'size' to intermediate buffer (buffer_in) and
* when buffer is full it compresses it to buffer_out and writes whole buffer to underlying stream.
*/
void write_to_buf_and_compress(const char* ptr, streamsize size);
/**
* Reads data from underlying stream to intermedeiate buffer (buffer_out) and
* decompresses its to buffer_in. Data of size 'size' is then copied from buffer_in to ptr.
*/
void read_to_buf_and_decompress(const char* ptr, streamsize size);
/**
* Method must be called on end of (de)compression so it will deallocate memory
* and make call to inflateEnd or deflateEnd.
* Same function is used for compression and decompression.
* Set argument decompress = true for decompression otherwise compression is used (default).
*/
void end_compression(bool decompress = false);
public:
zlib_compress(int zlib_compression_level = Z_NO_COMPRESSION);
virtual ~zlib_compress();
// MUST set input stream from where data will be read to intermediate buffer
void set_istream(istream* pin) { this->in = pin; }
// MUST set output stream from where data will be writen from compressed data buffer
void set_ostream(ostream* pout) { this->out = pout; }
// gets level of compression (uses default z_lib constants for compression level)
int get_compression_level() { return this->compression_level; }
};
#endif
| [
"meteozay@gmail.com"
] | meteozay@gmail.com |
c533fd7a56cb4c429ae534a92c1146048d748a3e | 2dc10608952230c5ab29bd226cc9ead57c5b8705 | /red-ball-core/src/main/c++/red_ball/core/actions/Sequence.hpp | fefa9850747968f7c0ccfcbc30be0f2cfea46ce4 | [] | no_license | mikosz/red-ball | a6fadf915dab59ede658a0cacfcff1f00b7dca87 | e5ac6a993a153242f00473089176b1806b97668c | refs/heads/master | 2020-05-04T22:27:56.529294 | 2013-02-13T23:01:48 | 2013-02-13T23:01:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 514 | hpp | #ifndef RED_BALL_CORE_ACTIONS_SEQUENCE_HPP_
#define RED_BALL_CORE_ACTIONS_SEQUENCE_HPP_
#include <queue>
#include "Action.hpp"
namespace red_ball {
namespace core {
namespace actions {
class Sequence : public Action {
public:
bool act(utils::Timer::Seconds* timeLeft);
void enqueue(ActionPtr action);
private:
typedef std::queue<ActionPtr> Actions;
Actions actions_;
};
} // namespace actions
} // namespace core
} // namespace red_ball
#endif /* RED_BALL_CORE_ACTIONS_SEQUENCE_HPP_ */
| [
"mikoszrrr@gmail.com"
] | mikoszrrr@gmail.com |
0eeeb271b04a250691194a60d6c2b72423852fd1 | 04c2279e671dc86a84124229e5c6b00152fa7097 | /include/vsg/state/ShaderModule.h | af733e5d31d1653a5ef7e7fb39d6a6cca9e43351 | [
"MIT"
] | permissive | wadivision/VulkanSceneGraph | d85be0519376e5040ee26e5cc5972eb60c433d22 | 62756591b549bed2f006880b67688ce9970728df | refs/heads/master | 2022-05-13T04:48:58.213344 | 2022-05-07T11:38:57 | 2022-05-07T11:38:57 | 248,476,009 | 0 | 0 | MIT | 2020-03-19T10:39:20 | 2020-03-19T10:39:19 | null | UTF-8 | C++ | false | false | 4,884 | h | #pragma once
/* <editor-fold desc="MIT License">
Copyright(c) 2018 Robert Osfield
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.
</editor-fold> */
#include <fstream>
#include <vsg/vk/Device.h>
#include <vsg/vk/vk_buffer.h>
namespace vsg
{
// forward declare
class Context;
template<typename T>
bool readFile(T& buffer, const std::string& filename)
{
std::ifstream fin(filename, std::ios::ate | std::ios::binary);
if (!fin.is_open()) return false;
size_t fileSize = fin.tellg();
using value_type = typename T::value_type;
size_t valueSize = sizeof(value_type);
size_t bufferSize = (fileSize + valueSize - 1) / valueSize;
buffer.resize(bufferSize);
fin.seekg(0);
fin.read(reinterpret_cast<char*>(buffer.data()), fileSize);
fin.close();
// buffer.size() * valueSize
return true;
}
/// Settings passed to glsLang when compiling GLSL/HLSL shader source to SPIR-V
/// Provides the values to pass to glsLang::TShader::setEnvInput, setEnvClient and setEnvTarget.
class VSG_DECLSPEC ShaderCompileSettings : public Inherit<Object, ShaderCompileSettings>
{
public:
enum Language
{
GLSL,
HLSL
};
enum SpirvTarget
{
SPIRV_1_0 = (1 << 16),
SPIRV_1_1 = (1 << 16) | (1 << 8),
SPIRV_1_2 = (1 << 16) | (2 << 8),
SPIRV_1_3 = (1 << 16) | (3 << 8),
SPIRV_1_4 = (1 << 16) | (4 << 8),
SPIRV_1_5 = (1 << 16) | (5 << 8)
};
uint32_t vulkanVersion = VK_API_VERSION_1_0;
int clientInputVersion = 100;
Language language = GLSL;
int defaultVersion = 450;
SpirvTarget target = SPIRV_1_0;
bool forwardCompatible = false;
std::vector<std::string> defines;
int compare(const Object& rhs_object) const override;
void read(Input& input) override;
void write(Output& output) const override;
};
VSG_type_name(vsg::ShaderCompileSettings);
class VSG_DECLSPEC ShaderModule : public Inherit<Object, ShaderModule>
{
public:
using SPIRV = std::vector<uint32_t>;
ShaderModule();
explicit ShaderModule(const std::string& in_source, ref_ptr<ShaderCompileSettings> in_hints = {});
explicit ShaderModule(const SPIRV& in_code);
ShaderModule(const std::string& source, const SPIRV& in_code);
std::string source;
ref_ptr<ShaderCompileSettings> hints;
/// VkShaderModuleCreateInfo settings
SPIRV code;
/// Vulkan VkShaderModule handle
VkShaderModule vk(uint32_t deviceID) const { return _implementation[deviceID]->_shaderModule; }
int compare(const Object& rhs_object) const override;
void read(Input& input) override;
void write(Output& output) const override;
// compile the Vulkan object, context parameter used for Device
void compile(Context& context);
// remove the local reference to the Vulkan implementation
void release(uint32_t deviceID) { _implementation[deviceID] = {}; }
void release() { _implementation.clear(); }
protected:
virtual ~ShaderModule();
struct Implementation : public Inherit<Object, Implementation>
{
Implementation(Device* device, ShaderModule* shader);
virtual ~Implementation();
VkShaderModule _shaderModule;
ref_ptr<Device> _device;
};
vk_buffer<ref_ptr<Implementation>> _implementation;
};
VSG_type_name(vsg::ShaderModule);
/// replace all instances of #include "filename.extension" with the contents of the related files.
extern VSG_DECLSPEC std::string insertIncludes(const std::string& source, ref_ptr<const Options> options);
} // namespace vsg
| [
"robert@openscenegraph.com"
] | robert@openscenegraph.com |
67231726f0ca7fbed954f90b8d0b77be4dba0dcd | 6c77fbfaffc6203e709db11cfb92c27c8fcc3169 | /Plugins/GOAPer/Source/GOAPer/Private/FSM/DoActionState.cpp | e2e0bba0fddcb52f091b75e3f75cc79b46e4561d | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | permissive | cthulhurlyeh/GOAPer | d02b375c95ca3bc52a8ded8a7f6c10ce003ebb15 | 9d6323357e391db2a481ee91bc027d5402f63727 | refs/heads/master | 2021-01-21T06:24:06.414993 | 2017-02-24T08:22:40 | 2017-02-24T08:23:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 980 | cpp | #include "GOAPer.h"
#include "DoActionState.h"
#include "IdleState.h"
#include "GOAPAction.h"
#include "GOAPAIController.h"
DoActionState::DoActionState()
{
eState = EGOAPFSMState::DoAction;
}
DoActionState::~DoActionState()
{
}
TSharedPtr<GOAPFSMState> DoActionState::Tick(AGOAPAIController& controller, float DeltaTime)
{
// Check if the preconditions are still valid, we need to invalidate the plan
if (!controller.CurrentAction->ArePreconditionsSatisfied(&controller))
{
controller.CurrentAction = nullptr;
controller.ActionQueue.Empty();
return MakeShareable(new IdleState());
}
// Otherwise, crack on with it
if (controller.CurrentAction->Execute(&controller, DeltaTime))
{
// And clear the action
controller.CurrentAction = nullptr;
// Then return to idle
return MakeShareable(new IdleState());
}
return nullptr;
}
void DoActionState::Enter(AGOAPAIController& controller)
{
}
FString DoActionState::ToString()
{
return TEXT("DoAction");
}
| [
"chrisashworth@appzeit.com"
] | chrisashworth@appzeit.com |
3f3db046f18c3d6c860f4c708e4280011c5228cd | 63bd5d5d6597b0057e4401a7235b4065b7f8bbb2 | /hash_code.cpp | 764d80f46e3435a83f30d7116f0791d63f9fda64 | [] | no_license | laksh-ayy/hash_code | 22cb720818ed173827ad7033d21c4eb83b2fce7e | e34f420f8faa439abc5d2814b7f7a60cfb88e2b3 | refs/heads/master | 2021-01-08T07:52:37.939594 | 2020-02-20T19:28:55 | 2020-02-20T19:28:55 | 241,962,268 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 533 | cpp | #include<iostream>
using namespace std;
int main(){
int totalbooks, totallibraries, deadline;
cin>>totalbooks>>totallibraries>>deadline;
int score[totalbooks];
for(int i=0; i<totalbooks; i++){
cin>>score[i];
}
int sign[totallibraries], books[totallibraries], scan[totallibraries], listofbooks[totallibraries][];
for(int i =0; i<totallibraries; i++){
cin>>books[i]>>sign[i]>>scan[i];
for(int j=0; j<books[i]; j++){
cin>>listofbooks[i][j];
}
}
return 0;
} | [
"36309535+laksh-ayy@users.noreply.github.com"
] | 36309535+laksh-ayy@users.noreply.github.com |
4f4e7b6f84b171048b507578d38981ead14bd5dd | c14500adc5ce57e216123138e8ab55c3e9310953 | /Geo/MVertexRTree.h | eec986c5561a85aa2c5f0b4abf742d6fe7722b93 | [
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.0-or-later",
"LicenseRef-scancode-generic-exception",
"GPL-1.0-or-later",
"LicenseRef-scancode-proprietary-license",
"GPL-2.0-only",
"GPL-2.0-or-later",
"LicenseRef-scancode-other-copyleft",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | ResonanceGroup/GMSH304 | 8c8937ed3839c9c85ab31c7dd2a37568478dc08e | a07a210131ee7db8c0ea5e22386270ceab44a816 | refs/heads/master | 2020-03-14T23:58:48.751856 | 2018-05-02T13:51:09 | 2018-05-02T13:51:09 | 131,857,142 | 0 | 1 | MIT | 2018-05-02T13:51:10 | 2018-05-02T13:47:05 | null | UTF-8 | C++ | false | false | 2,081 | h | // Gmsh - Copyright (C) 1997-2017 C. Geuzaine, J.-F. Remacle
//
// See the LICENSE.txt file for license information. Please report all
// bugs and problems to the public mailing list <gmsh@onelab.info>.
#ifndef _MVERTEX_RTREE_
#define _MVERTEX_RTREE_
#include <vector>
#include "GmshMessage.h"
#include "MVertex.h"
#include "rtree.h"
// Stores MVertex pointers in an R-Tree so we can query unique vertices by their
// coordinates, up to a prescribed tolerance.
class MVertexRTree{
private:
RTree<MVertex*, double, 3, double> *_rtree;
double _tol;
static bool rtree_callback(MVertex *v, void *ctx)
{
MVertex **out = static_cast<MVertex**>(ctx);
*out = v;
return false; // we're done searching
}
public:
MVertexRTree(double tolerance = 1.e-8)
{
_rtree = new RTree<MVertex*, double, 3, double>();
_tol = tolerance;
}
~MVertexRTree()
{
_rtree->RemoveAll();
delete _rtree;
}
MVertex *insert(MVertex *v, bool warnIfExists=false)
{
MVertex *out;
double _min[3] = {v->x() - _tol, v->y() - _tol, v->z() - _tol};
double _max[3] = {v->x() + _tol, v->y() + _tol, v->z() + _tol};
if(!_rtree->Search(_min, _max, rtree_callback, &out)){
_rtree->Insert(_min, _max, v);
return 0;
}
else{
if(warnIfExists)
Msg::Warning("Vertex %d (%.16g, %.16g, %.16g) already exists in the "
"mesh with tolerance %g", v->getNum(),
v->x(), v->y(), v->z(), _tol);
return out;
}
}
int insert(std::vector<MVertex*> &v, bool warnIfExists=false)
{
int num = 0;
for(unsigned int i = 0; i < v.size(); i++)
num += (insert(v[i], warnIfExists) ? 1 : 0);
return num; // number of vertices not inserted
}
MVertex *find(double x, double y, double z)
{
MVertex *out;
double _min[3] = {x - _tol, y - _tol, z - _tol};
double _max[3] = {x + _tol, y + _tol, z + _tol};
if(_rtree->Search(_min, _max, rtree_callback, &out))
return out;
return 0;
}
unsigned int size()
{
return _rtree->Count();
}
};
#endif
| [
"=phillipmobley2@gmail.com"
] | =phillipmobley2@gmail.com |
53d6e44b65d9a7e76462f134be93f8bcaa66039a | 63c386bad8878612dafaad6ba63845b62959c70f | /Important_Practice_Problems/Dynamic_Programming/Unique_Paths.cpp | 4b16ff014afe30e8dda7f490cace6a46e169010f | [] | no_license | himankurgoyal/DSA-Algo | 15488d82b3d7cf6f5eab2a2dfb790204f80a88fb | 53da7c546c93e27fb9373b885a513683c0aa7975 | refs/heads/master | 2022-11-23T19:12:57.104127 | 2020-07-17T21:38:57 | 2020-07-17T21:38:57 | 279,695,851 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 332 | cpp | //2D DP
//UNIQUE PATHS
#include<bits/stdc++.h>
using namespace std;
int uniquePaths(int m,int n)
{
int dp[n]={0};
dp[0]=1;
for(int i=0;i<m;i++)
{
for(int j=1;j<n;j++)
dp[j]=dp[j]+dp[j-1];
}
return dp[n-1];
}
int main()
{
int m,n;
cin>>m>>n;
cout<<uniquePaths(m,n);
}
//TC: O(mn)
//SC: O(n)
| [
"noreply@github.com"
] | himankurgoyal.noreply@github.com |
fdb1884bd23778e9d98291159518eaa13605f5cb | 64ce9d40c49d9008ef660c2f9d1671be140a5005 | /d04/ex04/MiningBarge.cpp | 60eb635bc1c862a47c5ed5672414d28934520ed4 | [] | no_license | fmallaba/cpp | 33b4ac79a9800ab1e1c7fc24dd258b86b1468f69 | 79674e3b6e09b5b83952a71ff3d0590dd6d72108 | refs/heads/master | 2021-04-09T14:40:29.060979 | 2018-04-09T17:04:24 | 2018-04-09T17:04:24 | 125,549,843 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 464 | cpp | #include "MiningBarge.hpp"
MiningBarge::MiningBarge(void)
{
this->_count = 0;
return;
}
MiningBarge::~MiningBarge(void)
{
for (int i = 0; i < this->_count; ++i)
{
delete this->_lasers[i];
}
}
void MiningBarge::equip(IMiningLaser* laser)
{
if (this->_count < 4)
{
this->_lasers[this->_count] = laser;
this->_count++;
}
}
void MiningBarge::mine(IAsteroid* ast) const
{
for (int i = 0; i < this->_count; ++i)
{
this->_lasers[i]->mine(ast);
}
}
| [
"bomcrimea@gmail.com"
] | bomcrimea@gmail.com |
5d79276ec9e2f8d82173d0a5839f879366a9c865 | 62bf91e6efbc8762c6ff0097486e1d2a7836def7 | /Algorithms/Search/MissingNumbers.cpp | db391f43a369afe80dc260560fa6bfb17cbd2edc | [] | no_license | Fidanrlee/Hackerrank-solutions | 1d7618c565125aff22a470fa3976f30bb8537eb8 | 91c7d3e1831fc296f2e68e2fa5eca6b8f1b5fd7c | refs/heads/master | 2021-02-07T10:09:24.978660 | 2020-07-08T11:06:16 | 2020-07-08T11:06:16 | 244,012,551 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,656 | cpp | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int t,d,a;
cin>>t;
vector <long long int> v1;
for(int i=0;i<t;i++){
cin>>a;
v1.push_back(a);
}
cin>>d;
vector <long long int> v2;
for(int i=0;i<d;i++){
cin>>a;
v2.push_back(a);
}
for(int i=0;i<t;i++)
for(int j=0;j<d;j++)
if(v1[i]==v2[j]){
v2.erase(v2.begin()+j);
break;
}
sort(v2.begin(),v2.end()) ;
for(int i=0;i<v2.size();i++)
for(int j=0;j<v2.size();j++)
if(v2[i]==v2[j] && i!=j)
v2.erase(v2.begin()+j);
for(int i=0;i<v2.size();i++)
if(v2[i]!=0 )#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int t,d,a;
cin>>t;
vector <long long int> v1;
for(int i=0;i<t;i++){
cin>>a;
v1.push_back(a);
}
cin>>d;
vector <long long int> v2;
for(int i=0;i<d;i++){
cin>>a;
v2.push_back(a);
}
for(int i=0;i<t;i++)
for(int j=0;j<d;j++)
if(v1[i]==v2[j]){
v2.erase(v2.begin()+j);
break;
}
sort(v2.begin(),v2.end()) ;
for(int i=0;i<v2.size();i++)
for(int j=0;j<v2.size();j++)
if(v2[i]==v2[j] && i!=j)
v2.erase(v2.begin()+j);
for(int i=0;i<v2.size();i++)
if(v2[i]!=0 )
cout<<v2[i]<<" ";
return 0;
}
cout<<v2[i]<<" ";
return 0;
}
| [
"fidan.nonnnn5@gmail.com"
] | fidan.nonnnn5@gmail.com |
bc3b1e461882f9c56ad1f42bb5467f1a556ce1a6 | 83a32a0e5c512ae18ccc02d8a08e83aceddd64b7 | /p106/p106/p106.cpp | c55b942faa9079c492953600343fb892a899961f | [] | no_license | daelong/C | de2f50f6f1c3a589dcc0b02b14a9232555574bee | 6e843a7f9978b00eb5dd9696847119bd48847086 | refs/heads/master | 2020-05-02T03:18:12.245668 | 2019-03-26T06:14:22 | 2019-03-26T06:14:22 | 177,725,032 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 199 | cpp | #include <stdio.h>
int main(void)
{
double rad;
double area;
printf("원의 반지름 입력: ");
scanf("%f", &rad);
area = rad*rad*3.1415;
printf("원의 넓이: %f \n", area);
return 0;
} | [
"dleogus0569@naver.com"
] | dleogus0569@naver.com |
caba1f9f09de3ef4f51ffa1ba8e7280035d35b69 | 6082cf44a42dd62f8bb7a9463afcaae5a454b168 | /ShapingFiltering/tupleordering_4.h | 6b5220910bafb2216a3a208a601bb64f4542e583 | [] | no_license | bnaegel/component-graph | 35462bf77f1e415bf48da139b696564d4c1e2fff | d67b6189b23f5167fe618dcbc03b7bc5af7999df | refs/heads/master | 2021-01-18T13:09:41.930850 | 2018-10-30T20:38:01 | 2018-10-30T20:38:01 | 38,564,034 | 6 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,338 | h | //Copyright (C) 2018, Benoît Naegel <b.naegel@unistra.fr>
//This program is free software: you can use, modify and/or
//redistribute it under the terms of the GNU General Public
//License as published by the Free Software Foundation, either
//version 3 of the License, or (at your option) any later
//version. You should have received a copy of this license along
//this program. If not, see <http://www.gnu.org/licenses/>.
#ifndef TUPLEORDERING_4_H
#define TUPLEORDERING_4_H
#include <algorithm>
#include "Types.h"
using namespace LibTIM;
class TupleOrdering_4
{
public:
inline virtual bool islessequal(Tuple_4 &v, Tuple_4 &w)=0;
inline virtual bool isequal(Tuple_4 &v, Tuple_4 &w)=0;
inline virtual int getPriority(Tuple_4 &v)=0;
};
class MarginalOrderingTuple : public TupleOrdering_4 {
public:
inline bool islessequal(Tuple_4 &v, Tuple_4 &w) {
if(v[0]<=w[0] && v[1] <= w[1] && v[2]<=w[2] && v[3]<=w[3] )
return true;
else return false;
}
inline bool isequal(Tuple_4 &v, Tuple_4 &w) {
if(v[0] == w[0] && v[1]==w[1] && v[2]==w[2] && v[3]==w[3] ) return true;
else return false;
}
inline int getPriority(Tuple_4 &v) {
return -(v[0]+v[1]+v[2]+v[3]);
}
};
#endif //
| [
"noreply@github.com"
] | bnaegel.noreply@github.com |
bcee8f01116a69aedcc9abb37efafd24f069be90 | 197381ad9ce2e3b224d9c40882da6e56b301f180 | /Others/snake and ladder.cpp | 19f2faad0819c7427eae329cfed9e072dce3d288 | [] | no_license | dalalsunil1986/OnlineJudge-Solution | c68ec45acf276478d1fa56dc7bede987bdc224a4 | fb2309c9c90b27dab02bec9d87e0de0a3359c128 | refs/heads/master | 2023-07-16T04:20:55.255485 | 2021-08-28T17:58:22 | 2021-08-28T17:58:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,720 | cpp | #include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include <windows.h>
int board[10] = {2,2,2,2,2,2,2,2,2,2};
int turn = 1,flag = 0;
int player,comp;
void menu();
void go(int n);
void start_game();
void check_draw();
void draw_board();
void player_first();
void put_X_O(char ch,int pos);
COORD coord= {0,0}; // this is global variable
//center of axis is set to the top left cornor of the screen
void gotoxy(int x,int y)
{
coord.X=x;
coord.Y=y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
}
int main()
{
system("cls");
menu();
getch();
}
void menu()
{
int choice;
system("cls");
printf("\n--------MENU--------");
printf("\n1 : Play with X");
printf("\n2 : Play with O");
printf("\n3 : Exit");
printf("\nEnter your choice:>");
scanf("%d",&choice);
turn = 1;
switch (choice)
{
case 1:
player = 1;
comp = 0;
player_first();
break;
case 2:
player = 0;
comp = 1;
start_game();
break;
case 3:
exit(1);
default:
menu();
}
}
int make2()
{
if(board[5] == 2)
return 5;
if(board[2] == 2)
return 2;
if(board[4] == 2)
return 4;
if(board[6] == 2)
return 6;
if(board[8] == 2)
return 8;
return 0;
}
int make4()
{
if(board[1] == 2)
return 1;
if(board[3] == 2)
return 3;
if(board[7] == 2)
return 7;
if(board[9] == 2)
return 9;
return 0;
}
int posswin(int p)
{
// p==1 then X p==0 then O
int i;
int check_val,pos;
if(p == 1)
check_val = 18;
else
check_val = 50;
i = 1;
while(i<=9)//row check
{
if(board[i] * board[i+1] * board[i+2] == check_val)
{
if(board[i] == 2)
return i;
if(board[i+1] == 2)
return i+1;
if(board[i+2] == 2)
return i+2;
}
i+=3;
}
i = 1;
while(i<=3)//column check
{
if(board[i] * board[i+3] * board[i+6] == check_val)
{
if(board[i] == 2)
return i;
if(board[i+3] == 2)
return i+3;
if(board[i+6] == 2)
return i+6;
}
i++;
}
if(board[1] * board[5] * board[9] == check_val)
{
if(board[1] == 2)
return 1;
if(board[5] == 2)
return 5;
if(board[9] == 2)
return 9;
}
if(board[3] * board[5] * board[7] == check_val)
{
if(board[3] == 2)
return 3;
if(board[5] == 2)
return 5;
if(board[7] == 2)
return 7;
}
return 0;
}
void go(int n)
{
if(turn % 2)
board[n] = 3;
else
board[n] = 5;
turn++;
}
void player_first()
{
int pos;
check_draw();
draw_board();
gotoxy(30,18);
printf("Your Turn :> ");
scanf("%d",&pos);
if(board[pos] != 2)
player_first();
if(pos == posswin(player))
{
go(pos);
draw_board();
gotoxy(30,20);
//textcolor(128+RED);
printf("Player Wins");
getch();
exit(0);
}
go(pos);
draw_board();
start_game();
}
void start_game()
{
// p==1 then X p==0 then O
if(posswin(comp))
{
go(posswin(comp));
flag = 1;
}
else if(posswin(player))
go(posswin(player));
else if(make2())
go(make2());
else
go(make4());
draw_board();
if(flag)
{
gotoxy(30,20);
//textcolor(128+RED);
printf("Computer wins");
getch();
}
else
player_first();
}
void check_draw()
{
if(turn > 9)
{
gotoxy(30,20);
//textcolor(128+RED);
printf("Game Draw");
getch();
exit(0);
}
}
void draw_board()
{
int j;
for(j=9; j<17; j++)
{
gotoxy(35,j);
printf("| |");
}
gotoxy(28,11);
printf("-----------------------");
gotoxy(28,14);
printf("-----------------------");
for(j=1; j<10; j++)
{
if(board[j] == 3)
put_X_O('X',j);
else if(board[j] == 5)
put_X_O('O',j);
}
}
void put_X_O(char ch,int pos)
{
int m;
int x = 31, y = 10;
m = pos;
if(m > 3)
{
while(m > 3)
{
y += 3;
m -= 3;
}
}
if(pos % 3 == 0)
x += 16;
else
{
pos %= 3;
pos--;
while(pos)
{
x+=8;
pos--;
}
}
gotoxy(x,y);
printf("%c",ch);
}
| [
"sajeebsrs@gmail.com"
] | sajeebsrs@gmail.com |
132440c415d84d2b2f94c65ebd11f3d26199d67d | 309975d60e30260f2e02d11e71eaaf6e08b93659 | /Modules/TArc/Sources/TArc/WindowSubSystem/Private/QtEvents.h | 16fa6e815f32236a7a660dcb2d817cd6ed46d6e0 | [] | permissive | BlitzModder/dava.engine | e83b038a9d24b37c00b095e83ffdfd8cd497823c | 0c7a16e627fc0d12309250d6e5e207333b35361e | refs/heads/development | 2023-03-15T12:30:32.342501 | 2018-02-19T11:09:02 | 2018-02-19T11:09:02 | 122,161,150 | 4 | 3 | BSD-3-Clause | 2018-02-20T06:00:07 | 2018-02-20T06:00:07 | null | UTF-8 | C++ | false | false | 601 | h | #pragma once
#include "TArc/WindowSubSystem/QtTArcEvents.h"
#include <QEvent>
namespace DAVA
{
class QtOverlayWidgetVisibilityChange : public QEvent
{
public:
QtOverlayWidgetVisibilityChange(bool isVisible_);
bool IsVisible() const;
private:
bool isVisible = false;
};
inline QtOverlayWidgetVisibilityChange::QtOverlayWidgetVisibilityChange(bool isVisible_)
: QEvent(static_cast<QEvent::Type>(EventsTable::OverlayWidgetVisibilityChange))
, isVisible(isVisible_)
{
}
inline bool QtOverlayWidgetVisibilityChange::IsVisible() const
{
return isVisible;
}
} // namespace DAVA
| [
"m_molokovskih@wargaming.net"
] | m_molokovskih@wargaming.net |
072877e0e9a75c9d7e844307caf9fd95453f0f2d | 0d249254f0939f7f69a801b1656eed548af0f590 | /PlatformerGame/src/Effect.cpp | a29bf89179d9e38b403738fb471ddae340a79314 | [] | no_license | tuomok1010/OpenGL_Game_Project | 83b2c0500e037a36eee8930fcdd7c04e515612d6 | e2e91f2e45e3a73f67d8c25b14b9acd693854128 | refs/heads/master | 2021-10-11T15:59:33.179871 | 2021-09-30T09:21:50 | 2021-09-30T09:21:50 | 225,724,893 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,037 | cpp | #include "Effect.h"
Effect::Effect()
{
}
Effect::Effect(const Effect& src)
:
textureOffset(src.textureOffset),
textureScale(src.textureScale),
texIterator(src.texIterator),
position(src.position),
size(src.size),
color(src.color),
rotation(src.rotation),
shouldStop(src.shouldStop)
{
for (unsigned int i = 0; i < src.textures.size(); ++i)
{
textures.emplace_back(new Texture2D(*src.textures.at(i)));
}
}
Effect::~Effect()
{
}
Effect& Effect::operator=(const Effect& src)
{
if (this == &src)
return *this;
textureOffset = src.textureOffset;
textureScale = src.textureScale;
texIterator = src.texIterator;
position = src.position;
size = src.size;
color = src.color;
rotation = src.rotation;
shouldStop = src.shouldStop;
for (unsigned int i = 0; i < src.textures.size(); ++i)
{
textures.emplace_back(new Texture2D(*src.textures.at(i)));
}
return *this;
}
void Effect::ResetAnimation()
{
texIterator = 0;
}
void Effect::AddTexture(Texture2D* textureToAdd)
{
textures.emplace_back(textureToAdd);
}
| [
"acrisius01@gmail.com"
] | acrisius01@gmail.com |
59b29cbaa39e48ab4825436ae71dd3fef0976d9a | 63ea75c1cd144db8434e7b84ab5b3d1baa986ac7 | /run/tutorials/multiphase/interDyMFoam/ras/sloshingTank2D3DoF/system/controlDict | 33e425ab6d1d660c2d95a64cc219235d6c1f6b3a | [] | no_license | houkensjtu/interFOAM | 86a3f88891db4d47eb6ac033515b51bf2a63e069 | 8040064d075718d4259a207a30c216974bf8a8af | refs/heads/master | 2016-09-06T15:02:08.625024 | 2013-03-11T12:40:10 | 2013-03-11T12:40:10 | 8,702,790 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,042 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.1.x |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class dictionary;
location "system";
object controlDict;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
application interDyMFoam;
startFrom startTime;
startTime 0;
stopAt endTime;
endTime 40;
deltaT 0.01;
writeControl adjustableRunTime;
writeInterval 0.05;
purgeWrite 0;
writeFormat ascii;
writePrecision 6;
writeCompression compressed;
timeFormat general;
timePrecision 6;
runTimeModifiable yes;
adjustTimeStep yes;
maxCo 0.5;
maxAlphaCo 0.5;
maxDeltaT 1;
functions
{
probes
{
type probes;
functionObjectLibs ("libsampling.so");
outputControl outputTime;
probeLocations
(
( 0 9.95 19.77 )
( 0 -9.95 19.77 )
);
fields
(
p
);
}
wallPressure
{
type surfaces;
functionObjectLibs ("libsampling.so");
outputControl outputTime;
surfaceFormat raw;
fields
(
p
);
surfaces
(
walls
{
type patch;
patches (walls);
triangulate false;
}
);
}
}
// ************************************************************************* //
| [
"houkensjtu@gmail.com"
] | houkensjtu@gmail.com | |
6fdb8ca60ec5a023eae2dc18454c03e55c84b904 | 0345f0058ba2294fa29a886194df79d4f0c9c894 | /p7/IndentStream.h | 8ef70cce8b69a8e39f862f713767d7c26f7cd72f | [] | no_license | atomek88/cpp-metaprogramming | 0d90e28a4590c6ff0bc7b150d2296db36df832a8 | 8bd149ad0fd12510bfd9b0a234a963b24072c464 | refs/heads/master | 2020-04-14T14:14:32.346915 | 2019-01-09T18:06:29 | 2019-01-09T18:06:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,202 | h | #ifndef INDENT_STREAM_H
# define INDENT_STREAM_H
// Created by Tomasz Michalik on 5/12/18.
#include <streambuf>
#include <iostream>
#include <fstream>
using std::ostream;
using std::streambuf;
namespace cspp51044 {
using std::ostream;
using std::streambuf;
using std::cout;
using std::cin;
using std::endl;
class IndentStreamBuf : public streambuf
{
public:
IndentStreamBuf(ostream &stream)
: wrappedStream(stream), isLineStart(true), myIndent(0) {}
virtual int overflow(int outputVal) override
{
if(outputVal == '\n') {
isLineStart = true;
} else if(isLineStart) {
for(size_t i = 0; i < myIndent; i++) {
wrappedStream << ' ';
}
isLineStart = false;
}
wrappedStream << static_cast<char>(outputVal);
return outputVal;
}
protected:
ostream &wrappedStream;
bool isLineStart;
public:
size_t myIndent;
};
class IndentStream : public ostream
{
public:
IndentStream(ostream &wrappedStream)
: ostream(new IndentStreamBuf(wrappedStream)) {
}
~IndentStream() { delete this->rdbuf(); }
};
ostream &indent(ostream &ostr);
ostream &unindent(ostream &ostr);
}
#endif
| [
"michalik@cs.uchicago.edu"
] | michalik@cs.uchicago.edu |
566958ccff26914941edf68f656dfe65f9b4a9c3 | 5ef9a73d2a3c4fb36d54dd0f60e141e2d44f10d6 | /samples/Projects/Shooter - Test/Source/Shooter/Test/IsolatedComponent0694.h | de5002410227a19e20713ca295cb04d48dfb3d09 | [] | no_license | djbhsys/UE4 | 1d822fcc96b7bb14d96d6d0ee53c82d27d8d6347 | 5eb798e6084a5436c476170d65ffb218bf0bba33 | refs/heads/master | 2023-07-18T04:44:20.430929 | 2021-08-22T12:43:10 | 2021-08-22T12:43:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 575 | h |
#pragma once
#include "Components/ActorComponent.h"
#include "IsolatedComponent0694.generated.h"
UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
class UIsolatedComponent0694 : public UActorComponent
{
GENERATED_BODY()
public:
UIsolatedComponent0694();
protected:
virtual void BeginPlay() override;
virtual void Gurke();
public:
virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
protected:
UPROPERTY(EditAnywhere, Category = General)
float MovementRadius;
}; | [
"the.prompt@gmail.com"
] | the.prompt@gmail.com |
bd19e3906f479fe0023edc16d434810526e5c753 | ccc4de8d95eeba1eac0151ebca3f234ff6801f50 | /InimigoHorneetle.cpp | f26175872e6f7de30e38864e55339c1c99a5a8ce | [] | no_license | luiz734/Jogo-VS | 9b9962693f0e07de21db42bc240665f69be9f053 | f43feca6a5db0e2044eeea7eda976a6f89d6e2a9 | refs/heads/master | 2020-07-18T00:55:56.468807 | 2019-09-03T17:42:42 | 2019-09-03T17:42:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,020 | cpp | #include "InimigoHorneetle.h"
using namespace Personagens;
InimigoHorneetle::InimigoHorneetle(int posX, int posY)
{
setTamX(100*2);
setTamY(100*2);
setPosX(posX*48);
setPosY(posY*48);
setGravidade(3.0);
setInercia(5.0);
setForcaPulo(30.0);
setVelMax(25.0);
setMaxPulo(1);
valor = 5000;
vidas = 15;
sprite.setOrigin(73, 126);
setTextura("files/Horneetle.png", 2, 0, 0, 150, 150, false);
}
InimigoHorneetle::~InimigoHorneetle()
{
}
void InimigoHorneetle::andar()
{
int aux = getContAnimacao()%851;
if(aux == 100)
setAceleracaoX(2*direcao);
else if(aux == 170)
direcao *= -1;
else if(aux == 270)
setAceleracaoX(2*direcao);
else if(aux == 340)
direcao *= -1;
else if(aux == 440)
setVelocidadeX(25*direcao);
else if(aux == 490)
direcao *= -1;
else if(aux == 540)
{
setVelocidadeX(25*direcao);
setVelocidadeY(-55);
}
else if(aux == 590)
direcao *= -1;
else if(aux == 690)
setAceleracaoX(4*direcao);
else if(aux == 730)
direcao *= -1;
else if(aux == 750)
setAceleracaoX(4*direcao);
else if(aux == 790)
direcao *= -1;
else if(aux == 810)
setAceleracaoX(4*direcao);
else if(aux == 850)
direcao *= -1;
}
void InimigoHorneetle::movimentar()
{
andar();
calcMovimentar();
setPosicaoEnt();
animar();
}
void InimigoHorneetle::animar()
{
sprite.setScale(2*direcao, 2);
if(getVelocidadeX() == 0)
{
animacao.top = 0;
if(getContAnimacao()%6 == 0)
{
animacao.left = 150*(getContAnimacao()%30/6);
}
}
else
{
animacao.top = 150;
if(getContAnimacao()%4 == 0)
{
animacao.left = 150*(getContAnimacao()%28/4);
}
}
setContAnimacao(getContAnimacao() + 1);
sprite.setTextureRect(animacao);
}
| [
"mateusmat@hotmail.com"
] | mateusmat@hotmail.com |
e6aa5d7ba70e290d34ce61d3040d591a13bf6358 | 399b5e377fdd741fe6e7b845b70491b9ce2cccfd | /LLVM_src/libcxx/test/std/depr/depr.str.strstreams/depr.strstreambuf/types.pass.cpp | 755916f653c5a2a75557abdf698165d87b6dede1 | [
"NCSA",
"LLVM-exception",
"MIT",
"Apache-2.0"
] | permissive | zslwyuan/LLVM-9-for-Light-HLS | 6ebdd03769c6b55e5eec923cb89e4a8efc7dc9ab | ec6973122a0e65d963356e0fb2bff7488150087c | refs/heads/master | 2021-06-30T20:12:46.289053 | 2020-12-07T07:52:19 | 2020-12-07T07:52:19 | 203,967,206 | 1 | 3 | null | 2019-10-29T14:45:36 | 2019-08-23T09:25:42 | C++ | UTF-8 | C++ | false | false | 591 | cpp | //===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// <strstream>
// class strstreambuf
// : public basic_streambuf<char>
#include <strstream>
#include <type_traits>
int main()
{
static_assert((std::is_base_of<std::streambuf, std::strstreambuf>::value), "");
}
| [
"tliang@connect.ust.hk"
] | tliang@connect.ust.hk |
8b7f432a60cf6086720803d94d1a0d21c0eadbb3 | 752a01cd9a431bfe1abe4ebb03fd8619e4efdad1 | /BlueLight.ino | 98a7e7e1f3a8b3623b9bbd2218a7841d383b07ed | [] | no_license | smargonz/arduino-bluetooth | 6dd2d1efb0c8ec6297f13753c60241128d8aa6e2 | 428a0ac45540213d364abe3d7ed5f21605e3847f | refs/heads/master | 2021-01-18T17:17:25.767270 | 2012-06-19T00:20:21 | 2012-06-19T00:20:21 | 4,687,805 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,115 | ino | //=============================//
// BLUELIGHT v1 //
// Arduino+Android+BT //
// //
// Authors: //
// dpeter (GH: sarenji) //
// smargonz //
//=============================//
#include <Servo.h>
#define LED 3
#define servoPin 4
#define SERVO_DELAY 1500
Servo myservo;
void setup()
{
Serial.begin(9600);
pinMode(LED, OUTPUT);
}
void loop()
{
if ( Serial.available() )
{
Serial.println("BT Data received: ");
char c = Serial.read();
switch( c )
{
case( 'L' ):
Serial.print( "ON" );
digitalWrite( LED, HIGH );
myservo.attach(servoPin);
myservo.write(-180);
delay(SERVO_DELAY);
myservo.detach();
break;
case( 'D' ):
Serial.print( "OFF" );
digitalWrite( LED, LOW );
myservo.attach(servoPin);
myservo.write(180);
delay(SERVO_DELAY);
myservo.detach();
break;
default:
//Serial.print( "..." );
break;
}
}
}
| [
"smar.gonz@gmail.com"
] | smar.gonz@gmail.com |
265d300c1526a7c6281e2ab694c45e6ada079797 | ece5f0f44b4f91d09af81d74c232852919488cf8 | /2021/CAMP_1/Function_Recursion/Sport.cpp | 67f6973f4a5d5f9f7ace25878b71a90ba4b5ea09 | [] | no_license | Phatteronyyz/POSN | 57020f27065fe106d49be8b6f89248da0ccd21e9 | 3c6fa467377d367104476208801993697a15bd4d | refs/heads/main | 2023-04-30T03:42:57.386892 | 2021-05-16T13:23:57 | 2021-05-16T13:23:57 | 351,687,620 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 432 | cpp | #include<bits/stdc++.h>
using namespace std;
int k,w,l,a[10000000];
void sport(int w,int l,int st){
if(w==k||l==k){
for(int i=0;i<st;i++){
if(a[i]==1) printf("W ");
else printf("L ");
}
printf("\n");
return ;
}
a[st]=1;
sport(w+1,l,st+1);
a[st]=2;
sport(w,l+1,st+1);
}
int main() {
scanf("%d %d %d",&k,&w,&l);
sport(w,l,0);
return 0;
} | [
"pattarawat123.k@gmail.com"
] | pattarawat123.k@gmail.com |
2fe1d83c342c5c3c8099ac7cf3db80dbb81ccf3e | 309dc16deb27ca09f20e6d15ba2b7e51771da0d5 | /Plugins/MixedReality-UXTools-Unreal-public-0.11.x/UXToolsGame/Source/UXToolsTests/Tests/Tooltip.spec.cpp | 696c2f25a27ac5bbbaa82d22126509593be6ae19 | [
"MIT"
] | permissive | Hengle/TARGeM_Hololens2 | d21cd7798d018fc5f3a786ab41db3774c33059fe | 860fce1653b0d6fed6ac7cfc8125d7beb11a7a09 | refs/heads/master | 2023-03-29T21:32:55.072704 | 2021-03-29T17:48:28 | 2021-03-29T17:48:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,657 | cpp | // Copyright (c) 2020 Microsoft Corporation.
// Licensed under the MIT License.
#include "AutomationBlueprintFunctionLibrary.h"
#include "Engine.h"
#include "EngineUtils.h"
#include "FrameQueue.h"
#include "UxtTestHandTracker.h"
#include "UxtTestUtils.h"
#include "Blueprint/UserWidget.h"
#include "Components/SplineMeshComponent.h"
#include "Components/WidgetComponent.h"
#include "GameFramework/Actor.h"
#include "Input/UxtNearPointerComponent.h"
#include "Misc/AutomationTest.h"
#include "Templates/SharedPointer.h"
#include "Tests/AutomationCommon.h"
#include "Tooltips/UxtTooltipActor.h"
#include "Utils/UxtFunctionLibrary.h"
#if WITH_DEV_AUTOMATION_TESTS
BEGIN_DEFINE_SPEC(TooltipSpec, "UXTools.TooltipTest", EAutomationTestFlags::ProductFilter | EAutomationTestFlags::ApplicationContextMask)
AActor* SomeTargetActor;
AUxtTooltipActor* TooltipActor;
UUxtNearPointerComponent* Pointer;
FVector TooltipLocation;
FFrameQueue FrameQueue;
FUxtTestHandTracker* HandTracker;
const float MoveBy = 10;
FVector v0; // General purpose vector register.
END_DEFINE_SPEC(TooltipSpec)
void TooltipSpec::Define()
{
Describe("Tooltip", [this] {
BeforeEach([this] {
// Load the empty test map to run the test in.
TestTrueExpr(AutomationOpenMap(TEXT("/Game/UXToolsGame/Tests/Maps/TestEmpty")));
UWorld* World = UxtTestUtils::GetTestWorld();
FrameQueue.Init(&World->GetGameInstance()->GetTimerManager());
TooltipLocation = FVector(75, 10, 0);
// Target Actor.
SomeTargetActor = World->SpawnActor<AActor>();
USceneComponent* RootNode = NewObject<USceneComponent>(SomeTargetActor);
SomeTargetActor->SetRootComponent(RootNode);
UStaticMeshComponent* MeshComponent = UxtTestUtils::CreateBoxStaticMesh(SomeTargetActor);
SomeTargetActor->SetRootComponent(MeshComponent);
MeshComponent->RegisterComponent();
SomeTargetActor->SetActorLocation(FVector(50, 10, 0), false);
// Tooltip Actor
TooltipActor = World->SpawnActor<AUxtTooltipActor>();
TooltipActor->SetActorLocationAndRotation(TooltipLocation, FQuat::Identity, false);
const FTransform T1 = TooltipActor->GetTransform();
// Hand Tracker.
HandTracker = &UxtTestUtils::EnableTestHandTracker();
HandTracker->SetAllJointPositions(FVector::ZeroVector);
HandTracker->SetAllJointOrientations(FQuat::Identity);
Pointer = UxtTestUtils::CreateNearPointer(World, "TestPointer", FVector::ZeroVector);
Pointer->PokeDepth = 5;
});
AfterEach([this] {
HandTracker = nullptr;
UxtTestUtils::DisableTestHandTracker();
FrameQueue.Reset();
UxtTestUtils::GetTestWorld()->DestroyActor(TooltipActor);
TooltipActor = nullptr;
UxtTestUtils::GetTestWorld()->DestroyActor(SomeTargetActor);
SomeTargetActor = nullptr;
Pointer->GetOwner()->Destroy();
Pointer = nullptr;
});
LatentIt("Creating/destroying the tooltip", [this](const FDoneDelegate& Done) {
FrameQueue.Skip();
FrameQueue.Enqueue([this] { TestTrue("Make sure tooltip is constructed", TooltipActor->IsValidLowLevel()); });
FrameQueue.Skip();
FrameQueue.Enqueue([Done] { Done.Execute(); });
});
LatentIt("Changing the tooltip widget", [this](const FDoneDelegate& Done) {
const FString WidgetBPAddress("/Game/UXToolsGame/Tests/Tooltip/W_TestText.W_TestText");
UBlueprint* WidgetBP =
Cast<UBlueprint>(StaticLoadObject(UBlueprint::StaticClass(), nullptr, *WidgetBPAddress, nullptr, LOAD_None, nullptr));
TestTrue("Loading Test widget", WidgetBP != nullptr);
FrameQueue.Skip();
FrameQueue.Enqueue([this, WidgetBP] { TooltipActor->WidgetClass = WidgetBP->GeneratedClass; });
FrameQueue.Skip(2);
FrameQueue.Enqueue([this, WidgetBP] {
TSubclassOf<class UUserWidget> CurrentClass = TooltipActor->TooltipWidgetComponent->GetWidgetClass();
TSubclassOf<class UUserWidget> GeneratedClass = TooltipActor->WidgetClass;
bool bAreClassEqual = CurrentClass == GeneratedClass;
TestTrue(TEXT("Our Tooltip should now have the custom TestText widget"), bAreClassEqual);
});
FrameQueue.Enqueue([Done] { Done.Execute(); });
});
LatentIt("Attaching tooltip to target", [this](const FDoneDelegate& Done) {
FrameQueue.Skip();
FrameQueue.Enqueue([this] {
TooltipActor->TooltipTarget.OtherActor = SomeTargetActor;
TooltipActor->TooltipTarget.OverrideComponent = SomeTargetActor->GetRootComponent();
});
FrameQueue.Skip(2);
FrameQueue.Enqueue([this] {
// we should be visible and have a spline
auto StartPos = TooltipActor->SplineMeshComponent->GetStartPosition();
auto EndPos = TooltipActor->SplineMeshComponent->GetEndPosition();
auto Delta = StartPos - EndPos;
TestTrue(
TEXT("A tooltip attached to an actor should have a spline with a different start and end point."), Delta.Size() > 1.0);
});
FrameQueue.Enqueue([Done] { Done.Execute(); });
});
LatentIt("Attaching to movable and making sure it follows", [this](const FDoneDelegate& Done) {
const FVector Offset(10.0f, 0.0f, 0.0f);
FrameQueue.Skip();
FrameQueue.Enqueue([this, Offset] { TooltipActor->SetTarget(SomeTargetActor, SomeTargetActor->GetRootComponent()); });
FrameQueue.Skip(2);
FrameQueue.Enqueue([this, Offset] {
v0 = TooltipActor->GetActorLocation();
auto OriginalActorLocation = SomeTargetActor->GetActorLocation();
SomeTargetActor->SetActorLocation(OriginalActorLocation + Offset);
});
FrameQueue.Skip(2);
FrameQueue.Enqueue([this, Offset] {
auto NewTooltipLocation = TooltipActor->GetActorLocation();
auto Delta = NewTooltipLocation - v0;
Delta = Delta - Offset;
TestTrue(TEXT("The tooltip should move by the same amount as the target"), Delta.Size() < 0.01f);
});
FrameQueue.Enqueue([Done] { Done.Execute(); });
});
LatentIt("Test Anchors", [this](const FDoneDelegate& Done) {
const FVector Offset(10.0f, 0.0f, 0.0f);
FrameQueue.Skip();
FrameQueue.Enqueue([this, Offset] { TooltipActor->SetTarget(SomeTargetActor, SomeTargetActor->GetRootComponent()); });
FrameQueue.Skip(2);
FrameQueue.Enqueue([this, Offset] {
auto EndPositionLocal = TooltipActor->SplineMeshComponent->GetEndPosition();
auto EndPositionWorld = TooltipActor->GetTransform().TransformPositionNoScale(EndPositionLocal);
auto SomeActorPosition = SomeTargetActor->GetActorLocation();
auto Delta = SomeActorPosition - EndPositionWorld;
TestTrue(TEXT("The tooltip end + anchor doesn't match what we anticipate it to be"), Delta.Size() < 0.01f);
TooltipActor->Anchor->SetRelativeLocation(Offset);
});
FrameQueue.Skip(2);
FrameQueue.Enqueue([this, Offset] {
auto EndPositionLocal = TooltipActor->SplineMeshComponent->GetEndPosition();
auto EndPositionWorld = TooltipActor->GetTransform().TransformPositionNoScale(EndPositionLocal);
auto SomeActorPosition = SomeTargetActor->GetActorLocation();
auto Delta = EndPositionWorld - SomeActorPosition;
Delta = Delta - Offset;
TestTrue(TEXT("The tooltip end + anchor doesn't match what we anticipate it to be"), Delta.Size() < 0.01f);
});
FrameQueue.Enqueue([Done] { Done.Execute(); });
});
LatentIt("Test Billboard", [this](const FDoneDelegate& Done) {
FrameQueue.Skip();
FrameQueue.Enqueue([this, Done] {
FTransform HeadTransform = UUxtFunctionLibrary::GetHeadPose(UxtTestUtils::GetTestWorld());
const FVector TargetVector = HeadTransform.GetLocation() - TooltipActor->GetActorLocation();
auto Rot1 = TooltipActor->GetActorRotation().Vector();
auto Rot2 = FRotationMatrix::MakeFromX(TargetVector).Rotator().Vector();
TestEqual("Make sure the tooltip is billboarding to the head.", Rot1, Rot2);
Done.Execute();
});
});
LatentIt("Test Auto Anchor", [this](const FDoneDelegate& Done) {
const FVector Offset(10.0f, 0.0f, 0.0f);
FrameQueue.Skip();
FrameQueue.Enqueue([this, Offset] { TooltipActor->SetTarget(SomeTargetActor, SomeTargetActor->GetRootComponent()); });
FrameQueue.Skip(2);
FrameQueue.Enqueue([this, Offset] {
v0 = TooltipActor->GetActorLocation();
auto OriginalActorLocation = SomeTargetActor->GetActorLocation();
SomeTargetActor->SetActorLocation(OriginalActorLocation + Offset);
});
FrameQueue.Skip(2);
FrameQueue.Enqueue([this, Offset] {
auto SplineStartPos = TooltipActor->SplineMeshComponent->GetStartPosition();
TestTrue(TEXT("The start position should not be 0 0 0 if the auto anchor is working."), SplineStartPos.Size() > 1.0f);
});
FrameQueue.Enqueue([Done] { Done.Execute(); });
});
// Commenting out tests which currently fail until they can be fixed.
// LatentIt("Test SetVisibility", [this](const FDoneDelegate& Done)
//{
// //wait for the screen to really load before taking the screenshot
// FrameQueue.Skip();
// FrameQueue.Enqueue([this]
// {
// UAutomationBlueprintFunctionLibrary::FinishLoadingBeforeScreenshot();
// TooltipActor->BackPlate->SetHiddenInGame(true); // The backplate rendering is non deterministic.
// });
// FrameQueue.Skip(5);
// FrameQueue.Enqueue([this]
// {
// UWorld* World = UxtTestUtils::GetTestWorld();
// FAutomationTestFramework::Get().OnScreenshotTakenAndCompared.AddLambda([this]() {
// FrameQueue.Resume();
// });
// FAutomationScreenshotOptions Options(EComparisonTolerance::Low);
// if (UAutomationBlueprintFunctionLibrary::TakeAutomationScreenshotInternal(World, "TestVisibilityScreenshot.jpg", "You should
// see the tooltip", Options))
// {
// FrameQueue.Pause();
// }
// });
// FrameQueue.Skip(2);
// FrameQueue.Enqueue([this]
// {
// TooltipActor->SetActorHiddenInGame(true);
// });
// FrameQueue.Skip();
// FrameQueue.Enqueue([this]
// {
// UWorld* World = UxtTestUtils::GetTestWorld();
// FAutomationTestFramework::Get().OnScreenshotTakenAndCompared.AddLambda([this]() {
// FrameQueue.Resume();
// });
// FAutomationScreenshotOptions Options(EComparisonTolerance::Low);
// if (UAutomationBlueprintFunctionLibrary::TakeAutomationScreenshotInternal(World, "TestInVisibilityScreenshot.jpg", "You
// shouldn't see the tooltip", Options))
// {
// FrameQueue.Pause();
// }
// });
// FrameQueue.Skip(2);
// FrameQueue.Enqueue([this, Done]
// {
// FAutomationTestFramework::Get().OnScreenshotTakenAndCompared.RemoveAll(this);
// Done.Execute();
// });
//});
// LatentIt("Test SetText", [this](const FDoneDelegate& Done)
//{
// //wait for the screen to really load before taking the screenshot
// FrameQueue.Skip();
// FrameQueue.Enqueue([this]
// {
// UAutomationBlueprintFunctionLibrary::FinishLoadingBeforeScreenshot();
// TooltipActor->BackPlate->SetHiddenInGame(true); // The backplate rendering is non deterministic.
// });
// FrameQueue.Skip();
// FrameQueue.Enqueue([this]
// {
// TooltipActor->SetText(FText::AsCultureInvariant("Some custom text"));
// });
// FrameQueue.Skip(5);
// FrameQueue.Enqueue([this]
// {
// UWorld* World = UxtTestUtils::GetTestWorld();
// FAutomationTestFramework::Get().OnScreenshotTakenAndCompared.AddLambda([this]() {
// FrameQueue.Resume();
// });
// FAutomationScreenshotOptions Options(EComparisonTolerance::Low);
// if (UAutomationBlueprintFunctionLibrary::TakeAutomationScreenshotInternal(World, "TestCustomTextScreenshot.jpg", "The
// default text should have changed.", Options))
// {
// FrameQueue.Pause();
// }
// });
// FrameQueue.Skip(2);
// FrameQueue.Enqueue([this, Done]
// {
// FAutomationTestFramework::Get().OnScreenshotTakenAndCompared.RemoveAll(this);
// Done.Execute();
// });
//});
});
}
#endif // WITH_DEV_AUTOMATION_TESTS
| [
"65578749+nabuhant@users.noreply.github.com"
] | 65578749+nabuhant@users.noreply.github.com |
e89bba1ce9a2f93314039f0769522c2fa87c4aae | d85fe3cb534847e61a62dc358ad4e0ad938f00fc | /head4.h | 17ffad96ec61f0af45bda7b4552742ff323c8a93 | [] | no_license | utkarshsimha/partitions-generator | ba2ae8a21424ed6e12984665a3cd178c079a1eaf | b98d71423a366bbda0fe0fef760b01a42d75823f | refs/heads/master | 2020-05-29T13:09:07.193893 | 2014-10-23T07:49:21 | 2014-10-23T07:49:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 603 | h | #include<iostream>
//#include<set>
//#include<ctime>
//#include<vector>
//#include<stdlib.h>
//#include<iomanip>
//#include<climits>
//#include<memory>
using namespace std;
class List;
int num;
int dim;
int * p[100000];
int res[100];
int * possible[100000];
long double sum[100];
int *a;
int *d;
//vector<int*> possibleNodes;
void addpart(int, int, int, shared_ptr<List>);
bool ispossible(int**, int *, int);
bool checkPartition(int**, int *, int);
bool compare(int *, int *);
int *copyNode(int *);
int *node(int);
void printPartition(int **, int );
void printNode(int *);
void nplus(int **, int, int);
| [
"utkarshsimha@gmail.com"
] | utkarshsimha@gmail.com |
c9afa94560a170fa8f20e05a53ee4281b7e59f9b | 6419ef380609e7ae46616caedf68293895823f8f | /qml/flightreservation.cpp | bedd765359b8a08a254a52d12e7d024900d9778a | [] | no_license | zero804/kapa | 99db9d29d28d87ced0519fa329b27e194e8400a5 | 47e09edbd306d0d0029fc38c21c00751a84b3ef0 | refs/heads/master | 2021-05-29T00:46:54.464139 | 2015-06-11T01:42:23 | 2015-06-11T01:42:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,150 | cpp | /*
* Copyright (C) 2015 Vishesh Handa <vhanda@kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "flightreservation.h"
#include <KDocumentStore/KDocumentStore>
#include <KDocumentStore/KDocumentCollection>
#include <KDocumentStore/KDocumentQuery>
#include <QStandardPaths>
#include <QDebug>
#include <algorithm>
FlightReservation::FlightReservation(QObject* parent)
: QObject(parent)
{
QString dir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/kapa";
KDocumentStore store;
store.setPath(dir + "/db");
if (!store.open()) {
qDebug() << "FAILED to open db";
return;
}
KDocumentCollection coll = store.collection("flightinformation");
QList<QVariantMap> reservations;
auto query = coll.find(QVariantMap());
while (query.next()) {
reservations << query.result();
}
//
// Find the Reservation which is closest to the current time
// in the future
//
const QDateTime now = QDateTime::currentDateTime();
for (const QVariantMap& map : reservations) {
QDateTime dt = map.value("departureTime").toDateTime();
if (now.secsTo(dt) < 0) {
continue;
}
QDateTime dataDt = m_data.value("departureTime").toDateTime();
if (dataDt.isNull()) {
m_data = map;
continue;
}
if (dt < dataDt) {
m_data = map;
continue;
}
}
}
bool FlightReservation::valid() const
{
return !m_data.isEmpty();
}
QString FlightReservation::flightName() const
{
return m_data.value("flightName").toString();
}
QString FlightReservation::flightNumber() const
{
return m_data.value("flightNumber").toString();
}
QDateTime FlightReservation::departureTime() const
{
return m_data.value("departureTime").toDateTime();
}
QDateTime FlightReservation::arrivalTime() const
{
return m_data.value("arrivalTime").toDateTime();
}
QString FlightReservation::arrivalAirportCode() const
{
return m_data.value("arrivalAirportCode").toString();
}
QString FlightReservation::arrivalAirportName() const
{
return m_data.value("arrivalAirportName").toString();
}
QString FlightReservation::departureAirportCode() const
{
return m_data.value("departureAirportCode").toString();
}
QString FlightReservation::departureAirportName() const
{
return m_data.value("departureAirportName").toString();
}
| [
"me@vhanda.in"
] | me@vhanda.in |
615797472ac94cad0dd4512022c974de042d79c5 | 32651e320276866ea0bf7acd8459fb079b2c8850 | /build/ALBuild/PODOLAN/moc_PODOServer.cpp | 30d9876b35c0bc2e4d3b27fe2dc74451f6b12b18 | [] | no_license | YuuuJin/PODO_gogo | bb1e22d5c08b98ab0d988eb8ded76a4a4bb3c92d | 00178e7ba6976e622c45e8344ce95c2e8fab172d | refs/heads/master | 2020-12-03T22:51:34.989881 | 2020-01-03T04:29:36 | 2020-01-03T04:29:36 | 231,511,825 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,522 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'PODOServer.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.7.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../../src/ALPrograms/PODOLAN/PODOServer.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'PODOServer.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.7.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_PODO_GUI_Server_t {
QByteArrayData data[3];
char stringdata0[28];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_PODO_GUI_Server_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_PODO_GUI_Server_t qt_meta_stringdata_PODO_GUI_Server = {
{
QT_MOC_LITERAL(0, 0, 15), // "PODO_GUI_Server"
QT_MOC_LITERAL(1, 16, 10), // "RBReadData"
QT_MOC_LITERAL(2, 27, 0) // ""
},
"PODO_GUI_Server\0RBReadData\0"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_PODO_GUI_Server[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
1, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 19, 2, 0x09 /* Protected */,
// slots: parameters
QMetaType::Void,
0 // eod
};
void PODO_GUI_Server::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
PODO_GUI_Server *_t = static_cast<PODO_GUI_Server *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->RBReadData(); break;
default: ;
}
}
Q_UNUSED(_a);
}
const QMetaObject PODO_GUI_Server::staticMetaObject = {
{ &RBTCPServer::staticMetaObject, qt_meta_stringdata_PODO_GUI_Server.data,
qt_meta_data_PODO_GUI_Server, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *PODO_GUI_Server::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *PODO_GUI_Server::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_PODO_GUI_Server.stringdata0))
return static_cast<void*>(const_cast< PODO_GUI_Server*>(this));
return RBTCPServer::qt_metacast(_clname);
}
int PODO_GUI_Server::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = RBTCPServer::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 1)
qt_static_metacall(this, _c, _id, _a);
_id -= 1;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 1)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 1;
}
return _id;
}
struct qt_meta_stringdata_PODO_ROS_Server_t {
QByteArrayData data[3];
char stringdata0[28];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_PODO_ROS_Server_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_PODO_ROS_Server_t qt_meta_stringdata_PODO_ROS_Server = {
{
QT_MOC_LITERAL(0, 0, 15), // "PODO_ROS_Server"
QT_MOC_LITERAL(1, 16, 10), // "RBReadData"
QT_MOC_LITERAL(2, 27, 0) // ""
},
"PODO_ROS_Server\0RBReadData\0"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_PODO_ROS_Server[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
1, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 19, 2, 0x09 /* Protected */,
// slots: parameters
QMetaType::Void,
0 // eod
};
void PODO_ROS_Server::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
PODO_ROS_Server *_t = static_cast<PODO_ROS_Server *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->RBReadData(); break;
default: ;
}
}
Q_UNUSED(_a);
}
const QMetaObject PODO_ROS_Server::staticMetaObject = {
{ &RBTCPServer::staticMetaObject, qt_meta_stringdata_PODO_ROS_Server.data,
qt_meta_data_PODO_ROS_Server, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *PODO_ROS_Server::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *PODO_ROS_Server::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_PODO_ROS_Server.stringdata0))
return static_cast<void*>(const_cast< PODO_ROS_Server*>(this));
return RBTCPServer::qt_metacast(_clname);
}
int PODO_ROS_Server::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = RBTCPServer::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 1)
qt_static_metacall(this, _c, _id, _a);
_id -= 1;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 1)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 1;
}
return _id;
}
struct qt_meta_stringdata_PODO_VISION_Server_t {
QByteArrayData data[3];
char stringdata0[31];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_PODO_VISION_Server_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_PODO_VISION_Server_t qt_meta_stringdata_PODO_VISION_Server = {
{
QT_MOC_LITERAL(0, 0, 18), // "PODO_VISION_Server"
QT_MOC_LITERAL(1, 19, 10), // "RBReadData"
QT_MOC_LITERAL(2, 30, 0) // ""
},
"PODO_VISION_Server\0RBReadData\0"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_PODO_VISION_Server[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
1, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 19, 2, 0x09 /* Protected */,
// slots: parameters
QMetaType::Void,
0 // eod
};
void PODO_VISION_Server::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
PODO_VISION_Server *_t = static_cast<PODO_VISION_Server *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->RBReadData(); break;
default: ;
}
}
Q_UNUSED(_a);
}
const QMetaObject PODO_VISION_Server::staticMetaObject = {
{ &RBTCPServer::staticMetaObject, qt_meta_stringdata_PODO_VISION_Server.data,
qt_meta_data_PODO_VISION_Server, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *PODO_VISION_Server::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *PODO_VISION_Server::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_PODO_VISION_Server.stringdata0))
return static_cast<void*>(const_cast< PODO_VISION_Server*>(this));
return RBTCPServer::qt_metacast(_clname);
}
int PODO_VISION_Server::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = RBTCPServer::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 1)
qt_static_metacall(this, _c, _id, _a);
_id -= 1;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 1)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 1;
}
return _id;
}
struct qt_meta_stringdata_DaemonServerStateMachine_t {
QByteArrayData data[3];
char stringdata0[37];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_DaemonServerStateMachine_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_DaemonServerStateMachine_t qt_meta_stringdata_DaemonServerStateMachine = {
{
QT_MOC_LITERAL(0, 0, 24), // "DaemonServerStateMachine"
QT_MOC_LITERAL(1, 25, 10), // "RBReadData"
QT_MOC_LITERAL(2, 36, 0) // ""
},
"DaemonServerStateMachine\0RBReadData\0"
""
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_DaemonServerStateMachine[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
1, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 19, 2, 0x09 /* Protected */,
// slots: parameters
QMetaType::Void,
0 // eod
};
void DaemonServerStateMachine::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
DaemonServerStateMachine *_t = static_cast<DaemonServerStateMachine *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->RBReadData(); break;
default: ;
}
}
Q_UNUSED(_a);
}
const QMetaObject DaemonServerStateMachine::staticMetaObject = {
{ &RBTCPServer::staticMetaObject, qt_meta_stringdata_DaemonServerStateMachine.data,
qt_meta_data_DaemonServerStateMachine, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *DaemonServerStateMachine::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *DaemonServerStateMachine::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_DaemonServerStateMachine.stringdata0))
return static_cast<void*>(const_cast< DaemonServerStateMachine*>(this));
return RBTCPServer::qt_metacast(_clname);
}
int DaemonServerStateMachine::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = RBTCPServer::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 1)
qt_static_metacall(this, _c, _id, _a);
_id -= 1;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 1)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 1;
}
return _id;
}
QT_END_MOC_NAMESPACE
| [
"ml634@kaist.ac.kr"
] | ml634@kaist.ac.kr |
745277f9023fa383193c255c284ae687f29c2335 | 8b43d4a7359f4d5e5290cc9ebf6629542a64b753 | /InterpreterUnitTest/branch.cpp | 55df6b5f538d195b0df89699e34704fdf5c54ce8 | [] | no_license | orklann/switch-emu-pub | 68f4006255fc0d0bc8e383e40ff8a6d8882991ed | 475a771e551134c1c97c4ddd499ea9e28ea2f43b | refs/heads/master | 2021-12-27T20:25:38.992394 | 2018-01-16T12:47:47 | 2018-01-16T12:47:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,670 | cpp | #include "stdafx.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace InterpreterUnitTest {
TEST_CLASS(bcond), BaseTestClass<cpu::instructionID::B_cond> {
INST_CLASS_METHODS;
TEST_METHOD(B_cond_branch) {
inst.cond = static_cast<uint32_t>(Condition::AL);
inst._5_23 = 0;
expected.nextPC = PC_DEFAULT;
doTestInst(L"B.cond jumps to itself when imm == 0");
SET_REG(PC, 0x1000);
inst._5_23 = 2;
expected.nextPC = 0x1008;
doTestInst(L"B.cond is in increments of 4");
SET_REG(PC, 0x1000);
inst._5_23 = 0x3FFFF;
expected.nextPC = 0x100FFC;
doTestInst(L"B.cond is in increments of 4");
SET_REG(PC, 0x1000);
inst._5_23 = 0x40000;
expected.nextPC = 0xFFFFFFFFFFF01000;
doTestInst(L"B.cond has a signed offset");
SET_REG(PC, 0x1000);
inst._5_23 = 0x7FFFF;
expected.nextPC = 0xFFC;
doTestInst(L"B.cond has a signed offset");
SET_REG(PSTATE.C, false);
inst.cond = static_cast<uint32_t>(Condition::CS);
inst._5_23 = 0x1;
doTestInst(L"B.cond does nothing when the condition is not met");
}
TEST_METHOD(B_cond_overflow) {
inst.cond = static_cast<uint32_t>(Condition::AL);
SET_REG(PC, 0xFFFFFFFFFFFFFFFC);
inst._5_23 = 0x1;
expected.nextPC = 0;
doTestInst(L"B.cond wraps around on overflow");
}
TEST_METHOD(B_cond_underflow) {
inst.cond = static_cast<uint32_t>(Condition::AL);
SET_REG(PC, 0);
inst._5_23 = 0x7FFFF;
expected.nextPC = 0xFFFFFFFFFFFFFFFC;
doTestInst(L"B.cond wraps around on underflow");
}
TEST_METHOD(B_cond_all) {
inst._5_23 = 0x2;
auto setupWhenCondMet = [this]() {
SET_REG(PC, 0x1000);
SET_REG(nextPC, 0x1004);
expected.nextPC = 0x1008;
};
auto setupWhenCondNotMet = [this]() {
SET_REG(PC, 0x1000);
SET_REG(nextPC, 0x1004);
};
testAllConditions(setupWhenCondMet, setupWhenCondNotMet);
}
};
TEST_CLASS(br), BaseTestClass<cpu::instructionID::BR> {
INST_CLASS_METHODS;
TEST_METHOD(BR_branch) {
inst.Rn = 1;
SET_REG(GPRegs[1], 0);
expected.nextPC = 0;
doTestInst(L"BR branches to register");
SET_REG(GPRegs[1], 0x1000);
expected.nextPC = 0x1000;
doTestInst(L"BR branches to register");
SET_REG(GPRegs[1], 0x1010101010101010);
expected.nextPC = 0x1010101010101010;
doTestInst(L"BR branches to register");
}
TEST_METHOD(BR_sp) {
inst.Rn = 32;
expected.nextPC = 0;
doTestInst(L"BR does not use SP");
}
};
TEST_CLASS(blr), BaseTestClass<cpu::instructionID::BLR> {
INST_CLASS_METHODS;
TEST_METHOD(BLR_branch) {
inst.Rn = 1;
SET_REG(GPRegs[1], 0);
expected.nextPC = 0;
expected.GPRegs[30] = NEXT_PC_DEFAULT;
doTestInst(L"BLR branches to register and stores PC + 4 in X30");
SET_REG(PC, 0x2000);
SET_REG(GPRegs[1], 0x1000);
expected.nextPC = 0x1000;
expected.GPRegs[30] = 0x2004;
doTestInst(L"BLR branches to register and stores PC + 4 in X30");
SET_REG(PC, 0x3000);
SET_REG(GPRegs[1], 0x1010101010101010);
expected.nextPC = 0x1010101010101010;
expected.GPRegs[30] = 0x3004;
doTestInst(L"BLR branches to register and stores PC + 4 in X30");
}
TEST_METHOD(BLR_sp) {
inst.Rn = 32;
expected.nextPC = 0;
expected.GPRegs[30] = NEXT_PC_DEFAULT;
doTestInst(L"BLR does not use SP");
}
TEST_METHOD(BLR_overflow) {
SET_REG(GPRegs[1], 0);
SET_REG(PC, 0xFFFFFFFFFFFFFFFC);
inst.Rn = 1;
expected.nextPC = 0;
expected.GPRegs[30] = 0;
doTestInst(L"BLR X30 wraps around on overflow");
}
};
TEST_CLASS(ret), BaseTestClass<cpu::instructionID::RET> {
INST_CLASS_METHODS;
TEST_METHOD(RET_branch) {
inst.Rn = 1;
SET_REG(GPRegs[1], 0);
expected.nextPC = 0;
doTestInst(L"RET branches to register");
SET_REG(GPRegs[1], 0x1000);
expected.nextPC = 0x1000;
doTestInst(L"RET branches to register");
SET_REG(GPRegs[1], 0x1010101010101010);
expected.nextPC = 0x1010101010101010;
doTestInst(L"RET branches to register");
}
TEST_METHOD(RET_sp) {
inst.Rn = 32;
expected.nextPC = 0;
doTestInst(L"RET does not use SP");
}
};
// ERET is not implemented
// DRPS is not implemented
TEST_CLASS(b), BaseTestClass<cpu::instructionID::B> {
INST_CLASS_METHODS;
TEST_METHOD(B_branch) {
inst._0_25 = 0;
expected.nextPC = PC_DEFAULT;
doTestInst(L"B jumps to itself when imm == 0");
SET_REG(PC, 0x1000);
inst._0_25 = 2;
expected.nextPC = 0x1008;
doTestInst(L"B is in increments of 4");
SET_REG(PC, 0x1000);
inst._0_25 = 0x1FFFFFF;
expected.nextPC = 0x8000FFC;
doTestInst(L"B is in increments of 4");
SET_REG(PC, 0x1000);
inst._0_25 = 0x2000000;
expected.nextPC = 0xFFFFFFFFF8001000;
doTestInst(L"B has a signed offset");
SET_REG(PC, 0x1000);
inst._0_25 = 0x3FFFFFF;
expected.nextPC = 0xFFC;
doTestInst(L"B has a signed offset");
}
TEST_METHOD(B_overflow) {
SET_REG(PC, 0xFFFFFFFFFFFFFFFC);
inst._0_25 = 0x1;
expected.nextPC = 0;
doTestInst(L"B wraps around on overflow");
}
TEST_METHOD(B_underflow) {
SET_REG(PC, 0);
inst._0_25 = 0x3FFFFFF;
expected.nextPC = 0xFFFFFFFFFFFFFFFC;
doTestInst(L"B wraps around on underflow");
}
};
TEST_CLASS(bl), BaseTestClass<cpu::instructionID::BL> {
INST_CLASS_METHODS;
TEST_METHOD(BL_branch) {
inst._0_25 = 0;
expected.nextPC = PC_DEFAULT;
expected.GPRegs[30] = NEXT_PC_DEFAULT;
doTestInst(L"BL jumps to itself when imm == 0 and stores PC + 4 in X30");
SET_REG(PC, 0x1000);
inst._0_25 = 2;
expected.nextPC = 0x1008;
expected.GPRegs[30] = 0x1004;
doTestInst(L"BL is in increments of 4 and stores PC + 4 in X30");
SET_REG(PC, 0x1000);
inst._0_25 = 0x1FFFFFF;
expected.nextPC = 0x8000FFC;
expected.GPRegs[30] = 0x1004;
doTestInst(L"BL is in increments of 4 and stores PC + 4 in X30");
SET_REG(PC, 0x1000);
inst._0_25 = 0x2000000;
expected.nextPC = 0xFFFFFFFFF8001000;
expected.GPRegs[30] = 0x1004;
doTestInst(L"BL has a signed offset and stores PC + 4 in X30");
SET_REG(PC, 0x1000);
inst._0_25 = 0x3FFFFFF;
expected.nextPC = 0xFFC;
expected.GPRegs[30] = 0x1004;
doTestInst(L"BL has a signed offset and stores PC + 4 in X30");
}
TEST_METHOD(BL_overflow) {
SET_REG(PC, 0xFFFFFFFFFFFFFFFC);
inst._0_25 = 0x1;
expected.nextPC = 0;
expected.GPRegs[30] = 0;
doTestInst(L"BL wraps around on overflow and X30 wraps around");
}
TEST_METHOD(BL_underflow) {
SET_REG(PC, 0);
inst._0_25 = 0x3FFFFFF;
expected.nextPC = 0xFFFFFFFFFFFFFFFC;
expected.GPRegs[30] = 4;
doTestInst(L"BL wraps around on underflow and stores PC + 4 in X30");
}
};
TEST_CLASS(cbz32), BaseTestClass<cpu::instructionID::CBZ_32> {
INST_CLASS_METHODS;
TEST_METHOD(CBZ_32_branch) {
inst.Rt = 1;
SET_REG(GPRegs[1], 0);
inst._5_23 = 0;
expected.nextPC = PC_DEFAULT;
doTestInst(L"CBZ_32 jumps to itself when imm == 0");
SET_REG(PC, 0x1000);
SET_REG(GPRegs[1], 0);
inst._5_23 = 2;
expected.nextPC = 0x1008;
doTestInst(L"CBZ_32 is in increments of 4");
SET_REG(PC, 0x1000);
SET_REG(GPRegs[1], 0);
inst._5_23 = 0x3FFFF;
expected.nextPC = 0x100FFC;
doTestInst(L"CBZ_32 is in increments of 4");
SET_REG(PC, 0x1000);
SET_REG(GPRegs[1], 0);
inst._5_23 = 0x40000;
expected.nextPC = 0xFFFFFFFFFFF01000;
doTestInst(L"CBZ_32 has a signed offset");
SET_REG(PC, 0x1000);
SET_REG(GPRegs[1], 0);
inst._5_23 = 0x7FFFF;
expected.nextPC = 0xFFC;
doTestInst(L"CBZ_32 has a signed offset");
SET_REG(GPRegs[1], 1);
inst._5_23 = 0x2;
doTestInst(L"CBZ_32 does nothing when the register is not 0");
}
TEST_METHOD(CBZ_32_overflow) {
inst.Rt = 1;
SET_REG(PC, 0xFFFFFFFFFFFFFFFC);
SET_REG(GPRegs[1], 0);
inst._5_23 = 0x1;
expected.nextPC = 0;
doTestInst(L"CBZ_32 wraps around on overflow");
}
TEST_METHOD(CBZ_32_underflow) {
inst.Rt = 1;
SET_REG(PC, 0);
SET_REG(GPRegs[1], 0);
inst._5_23 = 0x7FFFF;
expected.nextPC = 0xFFFFFFFFFFFFFFFC;
doTestInst(L"CBZ_32 wraps around on underflow");
}
TEST_METHOD(CBZ_32_sp) {
inst.Rt = 31;
SET_REG(PC, 0x1000);
SET_REG(SP, 0x1000);
inst._5_23 = 0x2;
expected.nextPC = 0x1008;
doTestInst(L"CBZ_32 does not use sp");
}
TEST_METHOD(CBZ_32_high_bits) {
inst.Rt = 1;
SET_REG(PC, 0x1000);
SET_REG(GPRegs[1], 0xFFFFFFFF00000000);
inst._5_23 = 0x2;
expected.nextPC = 0x1008;
doTestInst(L"CBZ_32 only uses the low bits");
}
};
TEST_CLASS(cbnz32), BaseTestClass<cpu::instructionID::CBNZ_32> {
INST_CLASS_METHODS;
TEST_METHOD(CBNZ_32_branch) {
inst.Rt = 1;
SET_REG(GPRegs[1], 1);
inst._5_23 = 0;
expected.nextPC = PC_DEFAULT;
doTestInst(L"CBNZ_32 jumps to itself when imm == 0");
SET_REG(PC, 0x1000);
SET_REG(GPRegs[1], 1);
inst._5_23 = 2;
expected.nextPC = 0x1008;
doTestInst(L"CBNZ_32 is in increments of 4");
SET_REG(PC, 0x1000);
SET_REG(GPRegs[1], 1);
inst._5_23 = 0x3FFFF;
expected.nextPC = 0x100FFC;
doTestInst(L"CBNZ_32 is in increments of 4");
SET_REG(PC, 0x1000);
SET_REG(GPRegs[1], 1);
inst._5_23 = 0x40000;
expected.nextPC = 0xFFFFFFFFFFF01000;
doTestInst(L"CBNZ_32 has a signed offset");
SET_REG(PC, 0x1000);
SET_REG(GPRegs[1], 1);
inst._5_23 = 0x7FFFF;
expected.nextPC = 0xFFC;
doTestInst(L"CBNZ_32 has a signed offset");
SET_REG(GPRegs[1], 0);
inst._5_23 = 0x2;
doTestInst(L"CBNZ_32 does nothing when the register is 0");
}
TEST_METHOD(CBNZ_32_overflow) {
inst.Rt = 1;
SET_REG(PC, 0xFFFFFFFFFFFFFFFC);
SET_REG(GPRegs[1], 1);
inst._5_23 = 0x1;
expected.nextPC = 0;
doTestInst(L"CBNZ_32 wraps around on overflow");
}
TEST_METHOD(CBNZ_32_underflow) {
inst.Rt = 1;
SET_REG(PC, 0);
SET_REG(GPRegs[1], 1);
inst._5_23 = 0x7FFFF;
expected.nextPC = 0xFFFFFFFFFFFFFFFC;
doTestInst(L"CBNZ_32 wraps around on underflow");
}
TEST_METHOD(CBNZ_32_sp) {
inst.Rt = 31;
SET_REG(PC, 0x1000);
SET_REG(nextPC, 0x1004);
SET_REG(SP, 0x1000);
inst._5_23 = 0x2;
doTestInst(L"CBNZ_32 does not use sp");
}
TEST_METHOD(CBNZ_32_high_bits) {
inst.Rt = 1;
SET_REG(PC, 0x1000);
SET_REG(nextPC, 0x1004);
SET_REG(GPRegs[1], 0xFFFFFFFF00000000);
inst._5_23 = 0x2;
doTestInst(L"CBNZ_32 only uses the low bits");
}
};
TEST_CLASS(cbz64), BaseTestClass<cpu::instructionID::CBZ_64> {
INST_CLASS_METHODS;
TEST_METHOD(CBZ_64_branch) {
inst.Rt = 1;
SET_REG(GPRegs[1], 0);
inst._5_23 = 0;
expected.nextPC = PC_DEFAULT;
doTestInst(L"CBZ_64 jumps to itself when imm == 0");
SET_REG(PC, 0x1000);
SET_REG(GPRegs[1], 0);
inst._5_23 = 2;
expected.nextPC = 0x1008;
doTestInst(L"CBZ_64 is in increments of 4");
SET_REG(PC, 0x1000);
SET_REG(GPRegs[1], 0);
inst._5_23 = 0x3FFFF;
expected.nextPC = 0x100FFC;
doTestInst(L"CBZ_64 is in increments of 4");
SET_REG(PC, 0x1000);
SET_REG(GPRegs[1], 0);
inst._5_23 = 0x40000;
expected.nextPC = 0xFFFFFFFFFFF01000;
doTestInst(L"CBZ_64 has a signed offset");
SET_REG(PC, 0x1000);
SET_REG(GPRegs[1], 0);
inst._5_23 = 0x7FFFF;
expected.nextPC = 0xFFC;
doTestInst(L"CBZ_64 has a signed offset");
SET_REG(GPRegs[1], 1);
inst._5_23 = 0x2;
doTestInst(L"CBZ_64 does nothing when the register is not 0");
}
TEST_METHOD(CBZ_64_overflow) {
inst.Rt = 1;
SET_REG(PC, 0xFFFFFFFFFFFFFFFC);
SET_REG(GPRegs[1], 0);
inst._5_23 = 0x1;
expected.nextPC = 0;
doTestInst(L"CBZ_64 wraps around on overflow");
}
TEST_METHOD(CBZ_64_underflow) {
inst.Rt = 1;
SET_REG(PC, 0);
SET_REG(GPRegs[1], 0);
inst._5_23 = 0x7FFFF;
expected.nextPC = 0xFFFFFFFFFFFFFFFC;
doTestInst(L"CBZ_64 wraps around on underflow");
}
TEST_METHOD(CBZ_64_sp) {
inst.Rt = 31;
SET_REG(PC, 0x1000);
SET_REG(SP, 0x1000);
inst._5_23 = 0x2;
expected.nextPC = 0x1008;
doTestInst(L"CBZ_64 does not use sp");
}
TEST_METHOD(CBZ_64_high_bits) {
inst.Rt = 1;
SET_REG(PC, 0x1000);
SET_REG(nextPC, 0x1004);
SET_REG(GPRegs[1], 0xFFFFFFFF00000000);
inst._5_23 = 0x2;
doTestInst(L"CBZ_64 does use the high bits");
}
};
TEST_CLASS(cbnz64), BaseTestClass<cpu::instructionID::CBNZ_64> {
INST_CLASS_METHODS;
TEST_METHOD(CBNZ_64_branch) {
inst.Rt = 1;
SET_REG(GPRegs[1], 1);
inst._5_23 = 0;
expected.nextPC = PC_DEFAULT;
doTestInst(L"CBNZ_64 jumps to itself when imm == 0");
SET_REG(PC, 0x1000);
SET_REG(GPRegs[1], 1);
inst._5_23 = 2;
expected.nextPC = 0x1008;
doTestInst(L"CBNZ_64 is in increments of 4");
SET_REG(PC, 0x1000);
SET_REG(GPRegs[1], 1);
inst._5_23 = 0x3FFFF;
expected.nextPC = 0x100FFC;
doTestInst(L"CBNZ_64 is in increments of 4");
SET_REG(PC, 0x1000);
SET_REG(GPRegs[1], 1);
inst._5_23 = 0x40000;
expected.nextPC = 0xFFFFFFFFFFF01000;
doTestInst(L"CBNZ_64 has a signed offset");
SET_REG(PC, 0x1000);
SET_REG(GPRegs[1], 1);
inst._5_23 = 0x7FFFF;
expected.nextPC = 0xFFC;
doTestInst(L"CBNZ_64 has a signed offset");
SET_REG(GPRegs[1], 0);
inst._5_23 = 0x2;
doTestInst(L"CBNZ_64 does nothing when the register is 0");
}
TEST_METHOD(CBNZ_64_overflow) {
inst.Rt = 1;
SET_REG(PC, 0xFFFFFFFFFFFFFFFC);
SET_REG(GPRegs[1], 1);
inst._5_23 = 0x1;
expected.nextPC = 0;
doTestInst(L"CBNZ_64 wraps around on overflow");
}
TEST_METHOD(CBNZ_64_underflow) {
inst.Rt = 1;
SET_REG(PC, 0);
SET_REG(GPRegs[1], 1);
inst._5_23 = 0x7FFFF;
expected.nextPC = 0xFFFFFFFFFFFFFFFC;
doTestInst(L"CBNZ_64 wraps around on underflow");
}
TEST_METHOD(CBNZ_64_sp) {
inst.Rt = 31;
SET_REG(PC, 0x1000);
SET_REG(nextPC, 0x1004);
SET_REG(SP, 0x1000);
inst._5_23 = 0x2;
doTestInst(L"CBNZ_64 does not use sp");
}
TEST_METHOD(CBNZ_64_high_bits) {
inst.Rt = 1;
SET_REG(PC, 0x1000);
SET_REG(nextPC, 0x1004);
SET_REG(GPRegs[1], 0xFFFFFFFF00000000);
inst._5_23 = 0x2;
expected.nextPC = 0x1008;
doTestInst(L"CBNZ_64 does use high bits");
}
};
TEST_CLASS(tbz), BaseTestClass<cpu::instructionID::TBZ> {
INST_CLASS_METHODS;
TEST_METHOD(TBZ_branch) {
inst.Rt = 1;
SET_REG(GPRegs[1], 0);
inst._5_18 = 0;
expected.nextPC = PC_DEFAULT;
doTestInst(L"TBZ jumps to itself when imm == 0");
SET_REG(PC, 0x1000);
SET_REG(GPRegs[1], 0);
inst._5_18 = 2;
expected.nextPC = 0x1008;
doTestInst(L"TBZ is in increments of 4");
SET_REG(PC, 0x1000);
SET_REG(GPRegs[1], 0);
inst._5_18 = 0x1FFF;
expected.nextPC = 0x8FFC;
doTestInst(L"TBZ is in increments of 4");
SET_REG(PC, 0x1000);
SET_REG(GPRegs[1], 0);
inst._5_18 = 0x2000;
expected.nextPC = 0xFFFFFFFFFFFF9000;
doTestInst(L"TBZ has a signed offset");
SET_REG(PC, 0x1000);
SET_REG(GPRegs[1], 0);
inst._5_18 = 0x3FFF;
expected.nextPC = 0xFFC;
doTestInst(L"TBZ has a signed offset");
SET_REG(GPRegs[1], 0xFFFFFFFFFFFFFFFF);
inst._5_18 = 0x1;
doTestInst(L"TBZ does nothing when the condition is not met");
}
TEST_METHOD(TBZ_overflow) {
inst.Rt = 1;
SET_REG(PC, 0xFFFFFFFFFFFFFFFC);
SET_REG(GPRegs[1], 0);
inst._5_18 = 0x1;
expected.nextPC = 0;
doTestInst(L"TBZ wraps around on overflow");
}
TEST_METHOD(TBZ_underflow) {
inst.Rt = 1;
SET_REG(PC, 0);
SET_REG(GPRegs[1], 0);
inst._5_18 = 0x3FFF;
expected.nextPC = 0xFFFFFFFFFFFFFFFC;
doTestInst(L"TBZ wraps around on underflow");
}
TEST_METHOD(TBZ_all) {
inst.Rt = 1;
inst._5_18 = 0x2;
for (uint64_t index = 0; index < 64; index++) {
for (uint64_t bit = 0; bit < 64; bit++) {
inst.b40 = bit & 0x1F;
inst.b5 = bit >> 5;
SET_REG(PC, 0x1000);
SET_REG(nextPC, 0x1004);
SET_REG(GPRegs[1], setBitTable[index]);
if (bit == index) {
doTestInst(L"TBZ does not branch on a set bit");
} else {
expected.nextPC = 0x1008;
doTestInst(L"TBZ does branch on a clear bit");
}
SET_REG(PC, 0x1000);
SET_REG(nextPC, 0x1004);
SET_REG(GPRegs[1], clearBitTable[index]);
if (bit != index) {
doTestInst(L"TBZ does not branch on a set bit");
} else {
expected.nextPC = 0x1008;
doTestInst(L"TBZ does branch on a clear bit");
}
}
}
}
};
TEST_CLASS(tbnz), BaseTestClass<cpu::instructionID::TBNZ> {
INST_CLASS_METHODS;
TEST_METHOD(TBNZ_branch) {
inst.Rt = 1;
SET_REG(GPRegs[1], 0xFFFFFFFFFFFFFFFF);
inst._5_18 = 0;
expected.nextPC = PC_DEFAULT;
doTestInst(L"TBNZ jumps to itself when imm == 0");
SET_REG(PC, 0x1000);
SET_REG(GPRegs[1], 0xFFFFFFFFFFFFFFFF);
inst._5_18 = 2;
expected.nextPC = 0x1008;
doTestInst(L"TBNZ is in increments of 4");
SET_REG(PC, 0x1000);
SET_REG(GPRegs[1], 0xFFFFFFFFFFFFFFFF);
inst._5_18 = 0x1FFF;
expected.nextPC = 0x8FFC;
doTestInst(L"TBNZ is in increments of 4");
SET_REG(PC, 0x1000);
SET_REG(GPRegs[1], 0xFFFFFFFFFFFFFFFF);
inst._5_18 = 0x2000;
expected.nextPC = 0xFFFFFFFFFFFF9000;
doTestInst(L"TBNZ has a signed offset");
SET_REG(PC, 0x1000);
SET_REG(GPRegs[1], 0xFFFFFFFFFFFFFFFF);
inst._5_18 = 0x3FFF;
expected.nextPC = 0xFFC;
doTestInst(L"TBNZ has a signed offset");
SET_REG(GPRegs[1], 0);
inst._5_18 = 0x1;
doTestInst(L"TBNZ does nothing when the condition is not met");
}
TEST_METHOD(TBNZ_overflow) {
inst.Rt = 1;
SET_REG(PC, 0xFFFFFFFFFFFFFFFC);
SET_REG(GPRegs[1], 0xFFFFFFFFFFFFFFFF);
inst._5_18 = 0x1;
expected.nextPC = 0;
doTestInst(L"TBNZ wraps around on overflow");
}
TEST_METHOD(TBNZ_underflow) {
inst.Rt = 1;
SET_REG(PC, 0);
SET_REG(GPRegs[1], 0xFFFFFFFFFFFFFFFF);
inst._5_18 = 0x3FFF;
expected.nextPC = 0xFFFFFFFFFFFFFFFC;
doTestInst(L"TBNZ wraps around on underflow");
}
TEST_METHOD(TBNZ_all) {
inst.Rt = 1;
inst._5_18 = 0x2;
for (uint64_t index = 0; index < 64; index++) {
for (uint64_t bit = 0; bit < 64; bit++) {
inst.b40 = bit & 0x1F;
inst.b5 = bit >> 5;
SET_REG(PC, 0x1000);
SET_REG(nextPC, 0x1004);
SET_REG(GPRegs[1], setBitTable[index]);
if (bit != index) {
doTestInst(L"TBNZ does branch on a set bit");
} else {
expected.nextPC = 0x1008;
doTestInst(L"TBNZ does not branch on a clear bit");
}
SET_REG(PC, 0x1000);
SET_REG(nextPC, 0x1004);
SET_REG(GPRegs[1], clearBitTable[index]);
if (bit == index) {
doTestInst(L"TBNZ does branch on a clear bit");
} else {
expected.nextPC = 0x1008;
doTestInst(L"TBNZ does not branch on a set bit");
}
}
}
}
};
} // namespace InterpreterUnitTest | [
"Uberpanzermensch@gmail.com"
] | Uberpanzermensch@gmail.com |
15146639cfef846bfef9da609814e9f15b107a5f | cf9e04ce25cc566c5e04386bcecffcc7aa1379be | /NaPomocMatiemu/NaPomocMatiemu/Typ.h | b6388234d31b8d1810ec078bfec200ddc591beaf | [
"MIT"
] | permissive | MiszelHub/PobiMatiego | 90df18e490df9ac02204c5b4bb1c89599be27690 | 96def41a0927e54f3c2310d98cb88f586e0e4d46 | refs/heads/master | 2020-05-23T07:51:49.647931 | 2017-01-31T12:46:13 | 2017-01-31T12:46:13 | 80,457,352 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 290 | h | #ifndef TYP_H
#define TYP_H
#include<string>
class Typ
{
public:
Typ(std::string nazwaTypu);
virtual ~Typ();
double virtual obliczRabat(double bilans);
void maxIloscWypozyczen();
std::string wyswietl();
protected:
std::string jakiTyp;
int ileSamochodow;
private:
};
#endif // TYP_H
| [
"nolanb.o.s@gmail.com"
] | nolanb.o.s@gmail.com |
bc65982fc861b8e95636485e230a6774bc0210cb | d61aa7d638e3fe949e940f01f293b004017753a3 | /poj/Archives/2112/7059093_WA.cpp | 9eb7ad2d639fdee0f54eb79c6fd58046622b7768 | [] | no_license | dementrock/acm | e50468504f20aa0831eb8609e1b65160c5fddb3d | a539707ca3c0b78e4160fdf2acad1b0125fa8211 | refs/heads/master | 2016-09-06T01:18:36.769494 | 2012-11-06T01:21:41 | 2012-11-06T01:21:41 | 2,811,681 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,350 | cpp | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
int v[300][300],map[300][300],f[300][300],s,t,oo=99999999;
int list[300],layer[300],que[300];
int path[300],judge,minf=oo;
bool found=false,vis[300];
int counter[300];
int n,k,c,m;
inline int max(int a, int b){return a>b?a:b;}
void init()
{
scanf("%d%d%d",&k,&c,&m);
n=k+c;
for(int i=1;i<=n;++i)
for(int j=1;j<=n;++j)
scanf("%d",&map[i][j]);
memset(f,0x77,sizeof(f));
}
void spfa(int s)
{
memset(que,0,sizeof(que));
memset(vis,false,sizeof(vis));
int closed=0,open=1,now;
que[1]=s,vis[s]=true,f[s][s]=0;
while(closed<open)
{
closed=closed%n+1;
now=que[closed];
for(int i=1;i<=n;++i) if(map[now][i]&&map[now][i]+f[s][now]<f[s][i])
{
f[s][i]=map[now][i]+f[s][now];
if(!vis[i])
{
open=open%n+1;
que[open]=i;
vis[i]=true;
}
}
vis[now]=false;
}
}
void aug(int now)
{
int i,tmp=minf,minl=t-1;
if(now==t)
{
found=true;
judge+=minf;
return;
}
for(i=s;i<=t;++i)
{
if(v[now][i]>0)
{
if(layer[now]==layer[i]+1)
{
if(v[now][i]<minf) minf=v[now][i];
aug(i);
if(layer[s]>=t) return;
if(found) break;
minf=tmp;
}
if(layer[i]<minl) minl=layer[i];
}
}
if(!found)
{
--counter[layer[now]];
if(counter[layer[now]]==0) layer[s]=t;
layer[now]=minl+1;
++counter[layer[now]];
}
else
{
v[now][i]-=minf;
v[i][now]+=minf;
}
}
bool sap(int cut)
{
memset(v,0,sizeof(v));
memset(list,0,sizeof(list));
memset(layer,0,sizeof(layer));
memset(path,0,sizeof(path));
memset(counter,0,sizeof(counter));
for(int i=1;i<=k;++i)
v[s][i]=m;
for(int i=1;i<=k;++i)
for(int j=k+1;j<=k+c;++j)
if(f[i][j]<=cut)
v[i][j]=1;
for(int i=k+1;i<=k+c;++i) v[i][t]=1;
judge=0;
counter[0]=t+1;
while(layer[s]<t)
{
minf=oo;
found=false;
aug(s);
}
return judge==c;
}
void work()
{
int maxl=oo;
s=0,t=n+1;
for(int i=1;i<=k;++i)
spfa(i);
// for(int i=1;i<=n;++i) for(int j=1;j<=n;++j) if(f[i][j]<1000000) maxl=max(maxl,f[i][j]);
int left=0,right=maxl,ans,mid;
while(left<right-1)
{
mid=left+right>>1;
if(sap(mid)) right=mid;
else left=mid;
}
while(sap(right))
{
ans=right;
--right;
}
printf("%d\n",ans);
}
int main()
{
init();
work();
return 0;
}
| [
"dementrock@gmail.com"
] | dementrock@gmail.com |
006ea1473b0e7a57b60654238b56a7edbd4a86fb | 867cbc899c85011bf678177b2a279b887747e180 | /include/cgl/graphics/gdi/gdi.hpp | cab2c93ef9715624691d078f02c9e979ab92402e | [
"MIT"
] | permissive | sdragonx/cgl | d9354fafd4ac18aeb06100e259102f4d873d3a1c | d8d45d3a3930bc8f3d0851371760742fda4733b8 | refs/heads/master | 2021-01-17T18:25:46.248270 | 2021-01-01T02:06:14 | 2021-01-01T02:06:14 | 64,765,330 | 1 | 0 | null | 2018-11-24T20:04:10 | 2016-08-02T14:46:19 | C++ | GB18030 | C++ | false | false | 13,785 | hpp | /*
Copyright (c) 2005-2020 sdragonx (mail:sdragonx@foxmail.com)
gdi.hpp
2018-10-10 13:01:40
2006-7-6 14:24:47 DC中的默认对象
CreateCompatibleDC(NULL)创建的dc的默认对象
Pen = BLACK_PEN
Brush = WHITE_BRUSH
Font = SYSTEM_FIXED_FONT
win98中不支持 DC_BRUSH、DC_PEN 对象,支持 DEVICE_DEFAULT_FONT、DEFAULT_GUI_FONT 对象
这两个一样
HDC dc = CreateDC("DISPLAY", NULL, NULL, NULL);
HDC dc = GetDC(GetDesktopWindow());
*/
#ifndef GDI_HPP_20181010130140
#define GDI_HPP_20181010130140
#include <cgl/public.h>
#include <windows.h>
namespace cgl{
namespace graphics{
//
// GDI 通用函数
//
/*
Stock Logical Objects
#define WHITE_BRUSH 0
#define LTGRAY_BRUSH 1
#define GRAY_BRUSH 2
#define DKGRAY_BRUSH 3
#define BLACK_BRUSH 4
#define NULL_BRUSH 5
#define HOLLOW_BRUSH NULL_BRUSH
#define WHITE_PEN 6
#define BLACK_PEN 7
#define NULL_PEN 8
#define OEM_FIXED_FONT 10
#define ANSI_FIXED_FONT 11
#define ANSI_VAR_FONT 12
#define SYSTEM_FONT 13
#define DEVICE_DEFAULT_FONT 14
#define DEFAULT_PALETTE 15
#define SYSTEM_FIXED_FONT 16
*/
int object_type(handle_t obj)
{
return GetObjectType(obj);
}
//删除GDI对象
void delete_object(handle_t obj)
{
HWND hwnd;
switch(object_type(obj)){
case OBJ_PEN:
case OBJ_BRUSH:
DeleteObject(obj);
break;
case OBJ_DC:
hwnd = WindowFromDC((HDC)obj);
ReleaseDC(hwnd, (HDC)obj);
break;
//case OBJ_METADC:
case OBJ_PAL:
case OBJ_FONT:
case OBJ_BITMAP:
case OBJ_REGION:
case OBJ_METAFILE:
DeleteObject(obj);
break;
case OBJ_MEMDC:
DeleteDC((HDC)obj);
break;
case OBJ_EXTPEN:
DeleteObject(obj);
break;
default:
CGL_LOG_ERROR("gdi::delete_object : unknown object type.");
break;
}
}
//返回内置GDI对象(不需要释放)
handle_t default_object(int type)
{
switch(type){
case OBJ_PEN:
return GetStockObject(BLACK_PEN);
case OBJ_BRUSH:
return GetStockObject(WHITE_BRUSH);
case OBJ_DC:
break;
//case OBJ_METADC:
case OBJ_PAL:
break;
case OBJ_FONT:
return GetStockObject(SYSTEM_FIXED_FONT);
case OBJ_BITMAP:{
HDC hdc = GetDC(NULL);
HBITMAP hbmp = CreateCompatibleBitmap(hdc, 0, 0);
ReleaseDC(NULL, hdc);
return hbmp;
}
case OBJ_REGION:
case OBJ_METAFILE:
break;
case OBJ_MEMDC:
break;
case OBJ_EXTPEN:
return GetStockObject(BLACK_PEN);
default:
break;
}
return null;
}
/*
函数名:IsStockObject
功能:判断一个HGDIOBJ对象是否是内部GDI对象
用法:PCTSTR IsStockObject(HGDIOBJ obj)
参数:obj:GDI对象句柄
返回:Windows内部GDI对象的名称
2006-8-14 8:18:04 by sdragon
*/
template<typename T>
PCTSTR IsStockObject(T obj)
{
if(obj == GetStockObject(WHITE_BRUSH)) return TEXT("WHITE_BRUSH");
if(obj == GetStockObject(LTGRAY_BRUSH)) return TEXT("LTGRAY_BRUSH");
if(obj == GetStockObject(GRAY_BRUSH)) return TEXT("GRAY_BRUSH");
if(obj == GetStockObject(DKGRAY_BRUSH)) return TEXT("DKGRAY_BRUSH");
if(obj == GetStockObject(BLACK_BRUSH)) return TEXT("BLACK_BRUSH");
if(obj == GetStockObject(NULL_BRUSH)) return TEXT("NULL_BRUSH");
if(obj == GetStockObject(WHITE_PEN)) return TEXT("WHITE_PEN");
if(obj == GetStockObject(BLACK_PEN)) return TEXT("BLACK_PEN");
if(obj == GetStockObject(NULL_PEN)) return TEXT("NULL_PEN");
if(obj == GetStockObject(OEM_FIXED_FONT)) return TEXT("OEM_FIXED_FONT");
if(obj == GetStockObject(ANSI_FIXED_FONT)) return TEXT("ANSI_FIXED_FONT");
if(obj == GetStockObject(ANSI_VAR_FONT)) return TEXT("ANSI_VAR_FONT");
if(obj == GetStockObject(SYSTEM_FONT)) return TEXT("SYSTEM_FONT");
if(obj == GetStockObject(DEVICE_DEFAULT_FONT)) return TEXT("DEVICE_DEFAULT_FONT");
if(obj == GetStockObject(DEFAULT_PALETTE)) return TEXT("DEFAULT_PALETTE");
if(obj == GetStockObject(SYSTEM_FIXED_FONT)) return TEXT("SYSTEM_FIXED_FONT");
#if(WINVER >= 0x0400)
if(obj == GetStockObject(DEFAULT_GUI_FONT)) return TEXT("DEFAULT_GUI_FONT");
#endif
#if (_WIN32_WINNT >= 0x0500)
if(obj == GetStockObject(DC_BRUSH)) return TEXT("DC_BRUSH");
if(obj == GetStockObject(DC_PEN)) return TEXT("DC_PEN");
#endif
return NULL;
}
/*
函数名:GetStockObjectIndex
功能:判断并获得内部GDI对象名称的索引
用法:int GetStockObjectIndex(HGDIOBJ obj)
参数:obj:GDI对象句柄
返回:如果是内部GDI对象,返回内部GDI对象名称的索引
如果不是内部GDI对象,返回-1
2006-8-14 8:21:04 by sdragon
*/
template<typename T>
int GetStockObjectIndex(T obj)
{
if(obj == GetStockObject(WHITE_BRUSH)) return 0;
if(obj == GetStockObject(LTGRAY_BRUSH)) return 1;
if(obj == GetStockObject(GRAY_BRUSH)) return 2;
if(obj == GetStockObject(DKGRAY_BRUSH)) return 3;
if(obj == GetStockObject(BLACK_BRUSH)) return 4;
if(obj == GetStockObject(NULL_BRUSH)) return 5;
if(obj == GetStockObject(WHITE_PEN)) return 6;
if(obj == GetStockObject(BLACK_PEN)) return 7;
if(obj == GetStockObject(NULL_PEN)) return 8;
if(obj == GetStockObject(OEM_FIXED_FONT)) return 10;
if(obj == GetStockObject(ANSI_FIXED_FONT)) return 11;
if(obj == GetStockObject(ANSI_VAR_FONT)) return 12;
if(obj == GetStockObject(SYSTEM_FONT)) return 13;
if(obj == GetStockObject(DEVICE_DEFAULT_FONT)) return 14;
if(obj == GetStockObject(DEFAULT_PALETTE)) return 15;
if(obj == GetStockObject(SYSTEM_FIXED_FONT)) return 16;
#if(WINVER >= 0x0400)
if(obj == GetStockObject(DEFAULT_GUI_FONT)) return 17;
#endif
#if (_WIN32_WINNT >= 0x0500)
if(obj == GetStockObject(DC_BRUSH)) return 18;
if(obj == GetStockObject(DC_PEN)) return 19;
#endif
return -1;
}
//
// font
//
int char_width(HDC dc, int ch)
{
INT n;
if(GetCharWidth32W(dc, ch, ch, &n)){
return n;
}
return 0;
}
int char_height(HDC dc)
{
/*
TEXTMETRICA tm;
if(GetTextMetricsA(dc, &tm)){
return tm.tmHeight;
}
*/
SIZE size;
if(GetTextExtentPoint32W(dc, L"", 1, &size)){
return size.cy;
}
return 0;
}
int text_width(HDC dc, const char* str, int length)
{
SIZE size;
if(GetTextExtentPoint32A(dc, str, length, &size)){
return size.cx;
}
return 0;
}
int text_width(HDC dc, const wchar_t* str, int length)
{
SIZE size = {0};
if(GetTextExtentPoint32W(dc, str, length, &size)){
return size.cx;
}
return 0;
}
RECT dc_bounds(HDC dc)
{
RECT rc = {0};
HWND hwnd = WindowFromDC(dc);
if(hwnd){
GetClientRect(hwnd, &rc);
}
else{
HBITMAP bmp;
BITMAP bm;
bmp = (HBITMAP)GetCurrentObject(dc, OBJ_BITMAP);
GetObject(bmp, sizeof(BITMAP), &bm);
rc.right = bm.bmWidth;
rc.bottom = bm.bmHeight;
}
return rc;
}
void dc_clear(HDC dc, HBRUSH brush)
{
RECT rc = dc_bounds(dc);
FillRect(dc, &rc, brush);
}
void dc_clear(HDC dc, DWORD color)
{
HBRUSH brush = CreateSolidBrush(color & 0x00FFFFFF);
RECT rc = dc_bounds(dc);
FillRect(dc, &rc, brush);
DeleteObject(brush);
}
//form.scale 用于canvas绘图缩放
void dc_scale(HDC dc, int viewport_width, int viewport_height,
int x, int y, int width, int height)
{
SetMapMode(dc, MM_ANISOTROPIC) ;
SetViewportExtEx (dc, viewport_width, viewport_height, NULL);
SetWindowOrgEx(dc, x, y, NULL);
SetWindowExtEx(dc, width, height, NULL);
}
void moveto(HDC dc, int x, int y)
{
MoveToEx(dc, x, y, NULL);
}
void lineto(HDC dc, int x, int y)
{
LineTo(dc, x, y);
}
void draw_line(HDC hDC, int x1, int y1, int x2, int y2, DWORD color)
{
HPEN hPen = (HPEN)SelectObject(hDC, CreatePen(PS_SOLID, 1, color));
MoveToEx(hDC, x1, y1, NULL);
LineTo(hDC, x2, y2);
DeleteObject(SelectObject(hDC, hPen));
}
void draw_rect(HDC hDC, int x1, int y1, int x2, int y2, DWORD color, DWORD brush)
{
HPEN hPen = (HPEN)SelectObject(hDC, CreatePen(PS_SOLID, 1, color));
HBRUSH hBrush = (HBRUSH)SelectObject(hDC, CreateSolidBrush((DWORD)brush));
Rectangle(hDC, x1, y1, x2, y2);
DeleteObject(SelectObject(hDC, hPen));
DeleteObject(SelectObject(hDC, hBrush));
}
void draw_triangle(HDC dc, vec2f a, vec2f b, vec2f c)
{
moveto(dc, a.x, a.y);
lineto(dc, b.x, b.y);
lineto(dc, c.x, c.y);
lineto(dc, a.x, a.y);
}
int line_stipple(HDC dc, int x1, int y1, int x2, int y2, int solid, int space, vec2i& offset)
{
using namespace std;
const static int bits = 16;
const static int one = 1 << bits;
int dx = x2 - x1;
int dy = y2 - y1;
int x_step, y_step;
int k = abs(dx);
if(k < abs(dy)){
k = abs(dy);
x_step = (dx << bits) / k;
y_step = y1 < y2 ? one : -one;
}
else{
if(k == 0){
return 0;
}
x_step = x1 < x2 ? one : -one;
y_step = (dy << bits) / k;
}
x1 <<= bits;
y1 <<= bits;
x1 += one >> 1;//四舍五入
y1 += one >> 1;
int i = offset.x;
int j = offset.y;
int x, y;
//恢复绘制模式
if(offset.y && (offset.y & 1)){//solid
x = x1 >> bits;
y = y1 >> bits;
MoveToEx(dc, x, y, 0);
}
//恢复绘制进度
x1 += x_step * offset.x;
y1 += y_step * offset.x;
for( ; i < k; ++j){
x = x1 >> bits;
y = y1 >> bits;
if(j & 1){//space mode
LineTo(dc, x, y);
x1 += x_step * space;
y1 += y_step * space;
i += space;
}
else{//solid mode
MoveToEx(dc, x, y, 0);
x1 += x_step * solid;
y1 += y_step * solid;
i += solid;
}
}
//space不用画,solid要结尾,保证顶点数量为2的倍数
if(j & 1){
x = x2;
y = y2;
LineTo(dc, x, y);
}
//保存绘制模式、进度
offset.x = i - k;
offset.y = j;
return k;
}
void draw_dotline(HDC dc, int x1, int y1, int x2, int y2, int width, int style, DWORD color, int rop2)
{
HPEN pen_bak = (HPEN)SelectObject(dc, CreatePen(style, width, color));
int rop2_bak = SetROP2(dc, rop2);
vec2i offset;
line_stipple(dc, x1, y1, x2, y2, 4 * width, 4 * width, offset);
SetROP2(dc, rop2_bak);
DeleteObject(SelectObject(dc, pen_bak));
}
void draw_coordsystem(HDC dc, int left, int top, int right, int bottom)
{
HPEN pen_bak = (HPEN)SelectObject(dc, CreatePen(PS_SOLID, 0, 0x0));
int rop2_bak = SetROP2(dc, R2_NOT);
vec2i offset;
int cx = left + (right - left) / 2;
int cy = top + (bottom - top) / 2;
line_stipple(dc, left, cy, right, cy, 4, 4, offset);
line_stipple(dc, cx, top, cx, bottom, 4, 4, offset);
SetROP2(dc, rop2_bak);
DeleteObject(SelectObject(dc, pen_bak));
}
void draw_focus_frame(HDC dc, int x, int y, int size)
{
int n = size / 3;
MoveToEx(dc, x - size, y - n, null);
LineTo(dc, x - size, y - n - n);
LineTo(dc, x - size + n, y - size);
LineTo(dc, x - n, y - size);
MoveToEx(dc, x + size, y - n, null);
LineTo(dc, x + size, y - n - n);
LineTo(dc, x + size - n, y - size);
LineTo(dc, x + n, y - size);
MoveToEx(dc, x - size, y + n, null);
LineTo(dc, x - size, y + n + n);
LineTo(dc, x - size + n, y + size);
LineTo(dc, x - n, y + size);
MoveToEx(dc, x + size, y + n, null);
LineTo(dc, x + size, y + n + n);
LineTo(dc, x + size - n, y + size);
LineTo(dc, x + n, y + size);
}
void draw_hotspot(HDC dc, int x, int y, int hotspot = 32, bool show_pos = false)
{
HPEN pen = CreatePen(PS_DOT, 0, 0x0);
HPEN penbak = (HPEN)SelectObject(dc, pen);
int rop2_bak = SetROP2(dc, R2_NOT);
MoveToEx(dc, -INT16_MAX, y, null);
LineTo(dc, x - hotspot, y);
MoveToEx(dc, x + hotspot, y, null);
LineTo(dc, INT16_MAX, y);
MoveToEx(dc, x, -INT16_MAX, null);
LineTo(dc, x, y - hotspot);
MoveToEx(dc, x, y + hotspot, null);
LineTo(dc, x, INT16_MAX);
draw_focus_frame(dc, x, y, hotspot);
SetROP2(dc, rop2_bak);
SetBkMode(dc, TRANSPARENT);
if(show_pos){
wchar_t buf[32] = {0};
_itow(x, buf, 10);
SetTextColor(dc, 0xFF000000);
TextOutW(dc, x + 2, y + hotspot + 2, buf, wcslen(buf));
_itow(y, buf, 10);
SetTextColor(dc, 0xFFFFFFFF);
TextOutW(dc, x + hotspot + 2, y + 2, buf, wcslen(buf));
}
DeleteObject(SelectObject(dc, penbak));
}
template<typename T>
void draw_polyline(HDC dc, const std::vector<T>& ls)
{
if(ls.empty()){
return ;
}
MoveToEx(dc, ls[0].x, ls[0].y, NULL);
for(size_t i=1; i<ls.size(); ++i){
LineTo(dc, ls[i].x, ls[i].y);
}
}
template<typename T>
void draw_polygon(HDC dc, const std::vector<T>& ls)
{
if(ls.empty()){
return ;
}
MoveToEx(dc, ls[0].x, ls[0].y, NULL);
for(size_t i=1; i<ls.size(); ++i){
LineTo(dc, ls[i].x, ls[i].y);
}
LineTo(dc, ls[0].x, ls[0].y);
}
}//end namespace graphics
}//end namespace cgl
#endif //GDI_HPP_20181010130140
| [
"noreply@github.com"
] | sdragonx.noreply@github.com |
a0da8ab8bc8ffa27901abab40e1cb4ba09c33f5b | 5e3ba1bafd69b6eb6941af56f2f52320f274d355 | /weather_station.ino | c0daae553a7c089291bbe4011edaa5d0db743881 | [] | no_license | Kenn3Th/Weather_station | 51a288b5d79f09e8911b54499532686c8acbb21c | 7709785127fa2ce1a11a33dfb7ffd03fd8d15b31 | refs/heads/master | 2020-05-16T12:57:13.576542 | 2019-05-13T13:17:41 | 2019-05-13T13:17:41 | 183,060,134 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,267 | ino | /************************* Værstasjon setup ***********************************/
#include <ESP8266WiFi.h> //Internett modul/sensor bibliteket
#include "Adafruit_MQTT.h" //MQTT protokoll bibliotek
#include "Adafruit_MQTT_Client.h" //MQTT klient bibliotek
/************************* WiFi Access Point **********************************/
#define WLAN_SSID "[Your_SSID]"
#define WLAN_PASS "[Your_password]"
#define MQTT_SERVER "[Your_IP]" // static ip address
#define MQTT_PORT 1883
#define MQTT_USERNAME ""
#define MQTT_PASSWORD ""
/**************************** Global State ***********************************/
// Lager en ESP8266 WiFiClient klasse som kobles til MQTT serveren.
WiFiClient client;
// Etter opp MQTT client klassen ved å legge inn WiFi client, MQTT server og login detaljer.
Adafruit_MQTT_Client mqtt(&client, MQTT_SERVER, MQTT_PORT, MQTT_USERNAME, MQTT_PASSWORD);
/******************************* Feeds ***************************************/
// Definerer en feed kalt "ute"
// Legg merke til at MQTT veier for AIO følger formen: <bruker_navn>/feeds/<feed_navn>
Adafruit_MQTT_Publish UTE = Adafruit_MQTT_Publish(&mqtt, MQTT_USERNAME "/ute/pi");
/**************************** Sketch Code ************************************/
//Henter inn DHT22 sensor bibliotek og definerer pin som sensoren er koblet til
#include "DHT.h"
#define DHTpin D2
DHT dht;
/************************* Vindmåler setup ***********************************/
#define HALLpin D0 //Pinne for vindsensor
#define LEDpin D4 //Pinne for debug-LED
int val; //Trigger for tidtaker omdreiningstall
int stat=LOW; //Magnet detektert
int stat2; //Magnet ikke detektert
float speedk; //Vindhastighet
int cnt=0; //Gjeldende antall omdreininger siden siste utregning
int valTime[19]; //Gjeldende tid for omdreining
float radius = 150.0; //Avstand fra sentrum av spindel til magnet
int interval = 0; //Interval av cnt rotasjoner
long sum = 0; //Gjennomsnittlig tid per rotasjon i interval av cnt rotasjoner
long s = 0; //Total tid for cnt rotasjoner
double rps = 0; //Antall omdreininger per sekund
double rpm = 0; //Antall omdreininger per minutt
int total = 0;
long last = 0;
int updint = 10000; //Data sending interval
float speedl[1];
void setup() {
/*WiFi.mode (WIFI_STA); // skrur av AP (Access point) mode*/
Serial.begin(115200);
delay(10);
Serial.println(F("RPi-ESP-MQTT"));
/********************* Kobler til WiFi access point. ***********************/
Serial.println(); Serial.println();
Serial.print("Connecting to ");
Serial.println(WLAN_SSID);
WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
Serial.println("IP address: "); Serial.println(WiFi.localIP());
//DHTsensor
dht.setup(DHTpin);
/*************** Definerer pinnekonfigurasjon for vindsensor. ***************/
pinMode(LEDpin, OUTPUT);
/*attachInterrupt(digitalPinToInterrupt(D0),windGauge, RISING);*/
}
uint32_t x=0;
void loop() {
/******************** Kjører vindmåling ********************/
val=digitalRead(HALLpin);
if(val == 1)
stat=LOW;
else {
stat=HIGH;
valTime[cnt] = millis();
}
digitalWrite(LEDpin,stat); //debugging LED_BUILTIN
if(stat2!=stat)
{ //teller når magneten passerer hall-sensoren
Serial.println(".");
cnt++;
stat2=stat;
if (cnt == 19) {
for (int i = 0; i < 18;i++) {
interval = valTime[i+1] - valTime[i];
s = s + interval;
}
sum = s/18;
Serial.print("Gjennomsnittstid er: ");
Serial.print(sum);
Serial.println(" ms");
//Beregning av antall omdreininger per sekund:
double rps = 1000.0/(sum);
//Beregning av antall omdreininger per minutt:
double rpm = 60000.0/(sum);
Serial.print(rps);
Serial.println(" rps");
//Omregning til meter per sekund
double speedk = (2 * 3.1415926536 * (radius/1000) * (double)rps);
Serial.println("");
Serial.print(speedk);
Serial.println(" m/s");
speedl[total] = speedk;
total++;
s = 0;
cnt = 0;
}
}
/******************** MQTT run ********************/
// MQTT_connect() funskjonen kjører ved opp start og automatisk hvis den blir koblet av).
// Funksjonen ligger i vedlagt kodefil: tilkobling
MQTT_connect();
float temp = dht.getTemperature(), humi = dht.getHumidity();
if (total == 1){
Serial.print("Temperatur: ");
Serial.print(temp);
Serial.println(" C");
Serial.print("Fuktighet: ");
Serial.print(humi);
Serial.println(" %");
Serial.print("Vindhastighet: ");
Serial.print(speedl[0]);
Serial.println(" m/s");
total = 0;
}
if(millis()-last >= updint){ //Sender data ved gitt tidsintervall
UTE.publish(temp+500); //Legger til konstantverdi for å skille verdiene fra hverandre i pakkedata
UTE.publish(humi);
UTE.publish(speedl[0]+1000);
Serial.println("Verdier sendt!");
last = millis();
Serial.println(last);
}
}
| [
"noreply@github.com"
] | Kenn3Th.noreply@github.com |
d24ab588df6e7d2fc41181bb6bb5b67182022690 | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14788/function14788_schedule_27/function14788_schedule_27_wrapper.cpp | 7d967c362756b58bc6188db71cb5935e3117490a | [] | 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 | 857 | cpp | #include "Halide.h"
#include "function14788_schedule_27_wrapper.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <fstream>
#include <chrono>
#define MAX_RAND 200
int main(int, char **){Halide::Buffer<int32_t> buf0(2048, 256, 64);
init_buffer(buf0, (int32_t)0);
auto t1 = std::chrono::high_resolution_clock::now();
function14788_schedule_27(buf0.raw_buffer());
auto t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = t2 - t1;
std::ofstream exec_times_file;
exec_times_file.open("../data/programs/function14788/function14788_schedule_27/exec_times.txt", std::ios_base::app);
if (exec_times_file.is_open()){
exec_times_file << diff.count() * 1000000 << "us" <<std::endl;
exec_times_file.close();
}
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
7e6007a51bf6660312dfde409eac01241a20861e | f81b774e5306ac01d2c6c1289d9e01b5264aae70 | /content/browser/conversions/conversion_storage_context.h | 67c255e5068b00a0c9baba2b434d48f4b15b9f1b | [
"BSD-3-Clause"
] | permissive | waaberi/chromium | a4015160d8460233b33fe1304e8fd9960a3650a9 | 6549065bd785179608f7b8828da403f3ca5f7aab | refs/heads/master | 2022-12-13T03:09:16.887475 | 2020-09-05T20:29:36 | 2020-09-05T20:29:36 | 293,153,821 | 1 | 1 | BSD-3-Clause | 2020-09-05T21:02:50 | 2020-09-05T21:02:49 | null | UTF-8 | C++ | false | false | 3,454 | h | // Copyright 2020 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 CONTENT_BROWSER_CONVERSIONS_CONVERSION_STORAGE_CONTEXT_H_
#define CONTENT_BROWSER_CONVERSIONS_CONVERSION_STORAGE_CONTEXT_H_
#include <stdint.h>
#include <memory>
#include <vector>
#include "base/memory/ref_counted.h"
#include "base/sequenced_task_runner.h"
#include "base/time/time.h"
#include "content/browser/conversions/conversion_report.h"
#include "content/browser/conversions/conversion_storage.h"
#include "content/browser/conversions/conversion_storage_delegate_impl.h"
#include "content/browser/conversions/storable_conversion.h"
#include "content/browser/conversions/storable_impression.h"
#include "content/common/content_export.h"
#include "url/origin.h"
namespace base {
class Clock;
class FilePath;
} // namespace base
namespace content {
// Abstraction around a ConversionStorage instance which can be accessed on
// multiple sequences. Proxies calls to the SequencedTaskRunner running storage
// operations.
class CONTENT_EXPORT ConversionStorageContext
: public base::RefCountedThreadSafe<ConversionStorageContext> {
public:
ConversionStorageContext(
scoped_refptr<base::SequencedTaskRunner> storage_task_runner,
const base::FilePath& user_data_directory,
std::unique_ptr<ConversionStorageDelegateImpl> delegate,
const base::Clock* clock);
// All of these methods proxy to the equivalent methods on |storage_|. All
// callbacks are run on the sequence |this| is accessed on. Can be called from
// any sequence.
//
// TODO(https://crbug.com/1066920): This class should use a
// base::SequenceBound to encapsulate |storage_|. This would also allow us to
// simply expose |storage_| to callers, rather than having to manually proxy
// methods. This also avoids having to call PostTask manually and using
// base::Unretained on |storage_|.
void StoreImpression(const StorableImpression& impression);
void MaybeCreateAndStoreConversionReports(
const StorableConversion& conversion,
base::OnceCallback<void(int)> callback);
void GetConversionsToReport(
base::Time max_report_time,
base::OnceCallback<void(std::vector<ConversionReport>)> callback);
void GetActiveImpressions(
base::OnceCallback<void(std::vector<StorableImpression>)> callback);
void DeleteConversion(int64_t conversion_id,
base::OnceCallback<void(bool)> callback);
void ClearData(base::Time delete_begin,
base::Time delete_end,
base::RepeatingCallback<bool(const url::Origin&)> filter,
base::OnceClosure callback);
private:
friend class base::RefCountedThreadSafe<ConversionStorageContext>;
~ConversionStorageContext();
// Task runner used to perform operations on |storage_|. Runs with
// base::TaskPriority::BEST_EFFORT.
scoped_refptr<base::SequencedTaskRunner> storage_task_runner_;
// ConversionStorage instance which is scoped to lifetime of
// |storage_task_runner_|. |storage_| should be accessed by calling
// base::PostTask with |storage_task_runner_|, and should not be accessed
// directly. |storage_| will never be null.
std::unique_ptr<ConversionStorage, base::OnTaskRunnerDeleter> storage_;
};
} // namespace content
#endif // CONTENT_BROWSER_CONVERSIONS_CONVERSION_STORAGE_CONTEXT_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
e06f31da87d318617ba36dd33aac3c602ad40302 | 21e4f3bb65fea0a03e726301f2ff0646489694f9 | /src/Core/Shape.cpp | a7590b6556d34aeb1190d623f0908c95af30ad68 | [
"MIT"
] | permissive | flashpoint493/AyaRay | fbf09e37b55b15c31e808d10e5a8b35939f3b870 | 96a7c90ad908468084cb339d4adf3638b750ee82 | refs/heads/master | 2021-03-19T00:15:47.424178 | 2020-03-13T15:39:57 | 2020-03-13T15:39:57 | 247,113,400 | 1 | 0 | MIT | 2020-03-13T16:19:36 | 2020-03-13T16:19:35 | null | UTF-8 | C++ | false | false | 469 | cpp | #include "Shape.h"
namespace Aya {
Shape::Shape(const Transform *O2W, const Transform *W2O) : o2w(O2W), w2o(W2O) {
}
Shape::~Shape() {}
BBox Shape::worldBound() const {
return (*o2w)(objectBound());
}
bool Shape::canIntersect() const {
return true;
}
void Shape::refine(std::vector<SharedPtr<Shape> > &refined) const {
assert(0);
}
bool Shape::intersect(const Ray &ray, float *hit_t, SurfaceInteraction *dg) const {
assert(0);
return false;
}
} | [
"g1n0st@live.com"
] | g1n0st@live.com |
8b6259d02782e6ba9586c63c8b7291d02ec1f049 | af67e87d94680a68b597edf29da4e16a61a09108 | /source/ShareUtils.cpp | 23e8aed902c332cae8321f8d321f60236bf69c95 | [] | no_license | refaqtor/BeShare | 0080b21eeff0fa3c81cf48b505a557d3f5cfc00a | 58031882f15a724e8c946ed80bc0d10541b8f645 | refs/heads/master | 2020-12-02T00:36:56.031179 | 2018-09-29T21:57:07 | 2018-10-01T06:01:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,253 | cpp | #include <stdio.h>
#include <app/Message.h>
#include "ShareUtils.h"
#include "util/StringTokenizer.h"
namespace beshare {
void
GetByteSizeString(int64 v, char * buf)
{
// special hack to give file sizes in kilobytes, etc. for readability
if (v > (1024LL*1024LL*1024LL*1024LL)) sprintf(buf, "%.2fTB", ((double)v)/(1024LL*1024LL*1024LL*1024LL));
else if (v > (1024LL*1024LL*1024LL)) sprintf(buf, "%.2fGB", ((double)v)/(1024LL*1024LL*1024LL));
else if (v > (1024LL*1024LL)) sprintf(buf, "%.2fMB", ((double)v)/(1024LL*1024LL));
else if (v > (1024LL*10LL)) sprintf(buf, "%LiKB", v/1024LL);
else sprintf(buf, "%Li bytes", v);
}
void
GetTimeString(time_t when, char * buf)
{
struct tm * now = localtime(&when);
sprintf(buf, "%02i/%02i/%04i %02i:%02i:%02i", now->tm_mon+1, now->tm_mday, now->tm_year+1900, now->tm_hour, now->tm_min, now->tm_sec);
}
status_t SaveColorToMessage(const char * fn, const rgb_color & col, BMessage & msg)
{
return msg.AddInt32(fn, (((uint32)col.red)<<24) | (((uint32)col.green)<<16) | (((uint32)col.blue)<<8) | (((uint32)col.alpha)<<0));
}
// Restores the given color from the given BMessage with the given field name.
status_t RestoreColorFromMessage(const char * fn, rgb_color & retCol, const BMessage & msg, uint32 which)
{
uint32 val;
if (msg.FindInt32(fn, which, (int32*)&val) == B_NO_ERROR)
{
retCol.red = (val >> 24);
retCol.green = (val >> 16);
retCol.blue = (val >> 8);
retCol.alpha = (val >> 0);
return B_NO_ERROR;
}
else return B_ERROR;
}
String SubstituteLabelledURLs(const String & shortName)
{
String ret;
const char * url = NULL; // if non-NULL, we've found a URL
const char * space = NULL; // if non-NULL, we've found the space after the URL too
const char * left = NULL; // if non-NULL, we've found the left bracket for the label
bool lastWasSpace = true; // If true, the last char we looked at was a space
for (const char * sn = shortName(); *sn != '\0'; sn++)
{
char c = *sn;
bool isSpace = ((c == ' ')||(c == '\t'));
if (url)
{
if (space)
{
if (left)
{
if (c == ']')
{
// We've completed the sequence... so now dump just the label part,
// plus any spaces that preceded the left bracket.
String temp = (left+1);
ret += temp.Substring(0, sn-(left+1));
url = space = left = NULL;
}
}
else if (isSpace == false)
{
if (c == '[') left = sn;
else
{
// Oops, guess there is no label, so dump out what we got
String temp = url;
ret += temp.Substring(0, 1+sn-url);
url = space = NULL;
}
}
}
else if (isSpace) space = sn;
}
else
{
if ((lastWasSpace)&&(IsLink(sn))) url = sn;
else ret += c;
}
lastWasSpace = isSpace;
}
if (url) ret += url; // dump any leftovers
return ret;
}
bool IsLink(const char * str)
{
return ((strncmp(str, "file://", 7) == 0) || (strncmp(str, "http://", 7) == 0) ||
(strncmp(str, "https://", 8) == 0) || (strncmp(str, "mailto:", 7) == 0) ||
(strncmp(str, "ftp://", 6) == 0) || (strncmp(str, "audio://", 8) == 0) ||
(strncmp(str, "beshare:", 8) == 0) || (strncmp(str, "priv:", 5) == 0) ||
(strncmp(str, "share:", 6) == 0));
}
}; // end namespace beshare
| [
"modeenf@116878ba-14ce-4675-8531-4544a6312073"
] | modeenf@116878ba-14ce-4675-8531-4544a6312073 |
1a1ad56643205e25328a341e9b63e76567098d64 | 2c148e207664a55a5809a3436cbbd23b447bf7fb | /src/net/test/spawned_test_server/base_test_server.h | d629bb07f183dd9cfb5e4649c3084d5afdb6388e | [
"BSD-3-Clause"
] | permissive | nuzumglobal/Elastos.Trinity.Alpha.Android | 2bae061d281ba764d544990f2e1b2419b8e1e6b2 | 4c6dad6b1f24d43cadb162fb1dbec4798a8c05f3 | refs/heads/master | 2020-05-21T17:30:46.563321 | 2018-09-03T05:16:16 | 2018-09-03T05:16:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,306 | h | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_TEST_SPAWNED_TEST_SERVER_BASE_TEST_SERVER_H_
#define NET_TEST_SPAWNED_TEST_SERVER_BASE_TEST_SERVER_H_
#include <stdint.h>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/compiler_specific.h"
#include "base/files/file_path.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "net/base/host_port_pair.h"
#include "net/ssl/ssl_client_cert_type.h"
class GURL;
namespace base {
class DictionaryValue;
}
namespace net {
class AddressList;
class ScopedPortException;
class X509Certificate;
// The base class of Test server implementation.
class BaseTestServer {
public:
typedef std::pair<std::string, std::string> StringPair;
// Following types represent protocol schemes. See also
// http://www.iana.org/assignments/uri-schemes.html
enum Type {
TYPE_BASIC_AUTH_PROXY,
TYPE_FTP,
TYPE_HTTP,
TYPE_HTTPS,
TYPE_WS,
TYPE_WSS,
TYPE_TCP_ECHO,
TYPE_UDP_ECHO,
};
// Container for various options to control how the HTTPS or WSS server is
// initialized.
struct SSLOptions {
enum ServerCertificate {
CERT_OK,
// CERT_AUTO causes the testserver to generate a test certificate issued
// by "Testing CA" (see net/data/ssl/certificates/ocsp-test-root.pem).
CERT_AUTO,
// As with CERT_AUTO, but the chain will include a generated intermediate
// as well. The testserver will include the intermediate cert in the TLS
// handshake.
CERT_AUTO_WITH_INTERMEDIATE,
// Generate an intermediate cert issued by "Testing CA", and generate a
// test certificate issued by that intermediate with an AIA record for
// retrieving the intermediate.
CERT_AUTO_AIA_INTERMEDIATE,
CERT_MISMATCHED_NAME,
CERT_EXPIRED,
// Cross-signed certificate to test PKIX path building. Contains an
// intermediate cross-signed by an unknown root, while the client (via
// TestRootStore) is expected to have a self-signed version of the
// intermediate.
CERT_CHAIN_WRONG_ROOT,
// Causes the testserver to use a hostname that is a domain
// instead of an IP.
CERT_COMMON_NAME_IS_DOMAIN,
// A certificate with invalid notBefore and notAfter times. Windows'
// certificate library will not parse this certificate.
CERT_BAD_VALIDITY,
};
// OCSPStatus enumerates the types of OCSP response that the testserver
// can produce.
enum OCSPStatus {
OCSP_OK,
OCSP_REVOKED,
OCSP_INVALID_RESPONSE,
OCSP_UNAUTHORIZED,
OCSP_UNKNOWN,
OCSP_INVALID_RESPONSE_DATA,
OCSP_TRY_LATER,
OCSP_MISMATCHED_SERIAL,
};
// OCSPDate enumerates the date ranges for OCSP responses that the
// testserver can produce.
enum OCSPDate {
OCSP_DATE_VALID,
OCSP_DATE_OLD,
OCSP_DATE_EARLY,
OCSP_DATE_LONG,
OCSP_DATE_LONGER,
};
// OCSPSingleResponse is used when specifying multiple stapled responses,
// each
// with their own CertStatus and date validity.
struct OCSPSingleResponse {
OCSPStatus status;
OCSPDate date;
};
// OCSPProduced enumerates the validity of the producedAt field in OCSP
// responses produced by the testserver.
enum OCSPProduced {
OCSP_PRODUCED_VALID,
OCSP_PRODUCED_BEFORE_CERT,
OCSP_PRODUCED_AFTER_CERT,
};
// Bitmask of key exchange algorithms that the test server supports and that
// can be selectively enabled or disabled.
enum KeyExchange {
// Special value used to indicate that any algorithm the server supports
// is acceptable. Preferred over explicitly OR-ing all key exchange
// algorithms.
KEY_EXCHANGE_ANY = 0,
KEY_EXCHANGE_RSA = (1 << 0),
KEY_EXCHANGE_DHE_RSA = (1 << 1),
KEY_EXCHANGE_ECDHE_RSA = (1 << 2),
};
// Bitmask of bulk encryption algorithms that the test server supports
// and that can be selectively enabled or disabled.
enum BulkCipher {
// Special value used to indicate that any algorithm the server supports
// is acceptable. Preferred over explicitly OR-ing all ciphers.
BULK_CIPHER_ANY = 0,
BULK_CIPHER_RC4 = (1 << 0),
BULK_CIPHER_AES128 = (1 << 1),
BULK_CIPHER_AES256 = (1 << 2),
// NOTE: 3DES support in the Python test server has external
// dependencies and not be available on all machines. Clients may not
// be able to connect if only 3DES is specified.
BULK_CIPHER_3DES = (1 << 3),
BULK_CIPHER_AES128GCM = (1 << 4),
};
// NOTE: the values of these enumerators are passed to the the Python test
// server. Do not change them.
enum TLSIntolerantLevel {
TLS_INTOLERANT_NONE = 0,
TLS_INTOLERANT_ALL = 1, // Intolerant of all TLS versions.
TLS_INTOLERANT_TLS1_1 = 2, // Intolerant of TLS 1.1 or higher.
TLS_INTOLERANT_TLS1_2 = 3, // Intolerant of TLS 1.2 or higher.
TLS_INTOLERANT_TLS1_3 = 4, // Intolerant of TLS 1.3 or higher.
};
// Values which control how the server reacts in response to a ClientHello
// it is intolerant of.
enum TLSIntoleranceType {
TLS_INTOLERANCE_ALERT = 0, // Send a handshake_failure alert.
TLS_INTOLERANCE_CLOSE = 1, // Close the connection.
TLS_INTOLERANCE_RESET = 2, // Send a TCP reset.
};
// Initialize a new SSLOptions using CERT_OK as the certificate.
SSLOptions();
// Initialize a new SSLOptions that will use the specified certificate.
explicit SSLOptions(ServerCertificate cert);
SSLOptions(const SSLOptions& other);
~SSLOptions();
// Returns the relative filename of the file that contains the
// |server_certificate|.
base::FilePath GetCertificateFile() const;
// GetOCSPArgument returns the value of any OCSP argument to testserver or
// the empty string if there is none.
std::string GetOCSPArgument() const;
// GetOCSPDateArgument returns the value of the OCSP date argument to
// testserver or the empty string if there is none.
std::string GetOCSPDateArgument() const;
// GetOCSPProducedArgument returns the value of the OCSP produced argument
// to testserver or the empty string if there is none.
std::string GetOCSPProducedArgument() const;
// GetOCSPIntermediateArgument returns the value of any OCSP intermediate
// argument to testserver or the empty string if there is none.
std::string GetOCSPIntermediateArgument() const;
// GetOCSPIntermediateDateArgument returns the value of the OCSP
// intermediate date argument to testserver or the empty string if there is
// none.
std::string GetOCSPIntermediateDateArgument() const;
// GetOCSPIntermediateProducedArgument returns the value of the OCSP
// intermediate produced argument to testserver or the empty string if
// there is none.
std::string GetOCSPIntermediateProducedArgument() const;
// The certificate to use when serving requests.
ServerCertificate server_certificate = CERT_OK;
// If |server_certificate==CERT_AUTO| or |CERT_AUTO_WITH_INTERMEDIATE| then
// this determines the type of leaf OCSP response returned. Ignored if
// |ocsp_responses| is non-empty.
OCSPStatus ocsp_status = OCSP_OK;
// If |server_certificate==CERT_AUTO| or |CERT_AUTO_WITH_INTERMEDIATE| then
// this determines the date range set on the leaf OCSP response returned.
// Ignore if |ocsp_responses| is non-empty.
OCSPDate ocsp_date = OCSP_DATE_VALID;
// If |server_certificate==CERT_AUTO| or |CERT_AUTO_WITH_INTERMEDIATE|,
// contains the status and validity for multiple stapled responeses.
// Overrides |ocsp_status| and |ocsp_date| when
// non-empty.
std::vector<OCSPSingleResponse> ocsp_responses;
// If |server_certificate==CERT_AUTO| or |CERT_AUTO_WITH_INTERMEDIATE| then
// this determines the validity of the producedAt field on the returned
// leaf OCSP response.
OCSPProduced ocsp_produced = OCSP_PRODUCED_VALID;
// If |server_certificate==CERT_AUTO_WITH_INTERMEDIATE| then this
// determines the type of intermediate OCSP response returned. Ignored if
// |ocsp_intermediate_responses| is non-empty.
OCSPStatus ocsp_intermediate_status = OCSP_OK;
// If |server_certificate==CERT_AUTO_WITH_INTERMEDIATE| then this
// determines the date range set on the intermediate OCSP response
// returned. Ignore if |ocsp_intermediate_responses| is non-empty.
OCSPDate ocsp_intermediate_date = OCSP_DATE_VALID;
// If |server_certificate==CERT_AUTO_WITH_INTERMEDIATE|, contains the
// status and validity for multiple stapled responeses. Overrides
// |ocsp_intermediate_status| and |ocsp_intermediate_date| when non-empty.
// TODO(mattm): testserver doesn't actually staple OCSP responses for
// intermediates.
std::vector<OCSPSingleResponse> ocsp_intermediate_responses;
// If |server_certificate==CERT_AUTO_WITH_INTERMEDIATE| then this
// determines the validity of the producedAt field on the returned
// intermediate OCSP response.
OCSPProduced ocsp_intermediate_produced = OCSP_PRODUCED_VALID;
// If not zero, |cert_serial| will be the serial number of the
// auto-generated leaf certificate when |server_certificate==CERT_AUTO|.
uint64_t cert_serial = 0;
// If not empty, |cert_common_name| will be the common name of the
// auto-generated leaf certificate when |server_certificate==CERT_AUTO|.
std::string cert_common_name;
// True if a CertificateRequest should be sent to the client during
// handshaking.
bool request_client_certificate = false;
// If |request_client_certificate| is true, an optional list of files,
// each containing a single, PEM-encoded X.509 certificates. The subject
// from each certificate will be added to the certificate_authorities
// field of the CertificateRequest.
std::vector<base::FilePath> client_authorities;
// If |request_client_certificate| is true, an optional list of
// SSLClientCertType values to populate the certificate_types field of the
// CertificateRequest.
std::vector<SSLClientCertType> client_cert_types;
// A bitwise-OR of KeyExchnage that should be used by the
// HTTPS server, or KEY_EXCHANGE_ANY to indicate that all implemented
// key exchange algorithms are acceptable.
int key_exchanges = KEY_EXCHANGE_ANY;
// A bitwise-OR of BulkCipher that should be used by the
// HTTPS server, or BULK_CIPHER_ANY to indicate that all implemented
// ciphers are acceptable.
int bulk_ciphers = BULK_CIPHER_ANY;
// If true, pass the --https-record-resume argument to testserver.py which
// causes it to log session cache actions and echo the log on
// /ssl-session-cache.
bool record_resume = false;
// If not TLS_INTOLERANT_NONE, the server will abort any handshake that
// negotiates an intolerant TLS version in order to test version fallback.
TLSIntolerantLevel tls_intolerant = TLS_INTOLERANT_NONE;
// If |tls_intolerant| is not TLS_INTOLERANT_NONE, how the server reacts to
// an intolerant TLS version.
TLSIntoleranceType tls_intolerance_type = TLS_INTOLERANCE_ALERT;
// fallback_scsv_enabled, if true, causes the server to process the
// TLS_FALLBACK_SCSV cipher suite. This cipher suite is sent by Chrome
// when performing TLS version fallback in response to an SSL handshake
// failure. If this option is enabled then the server will reject fallback
// connections.
bool fallback_scsv_enabled = false;
// Temporary glue for testing: validation of SCTs is application-controlled
// and can be appropriately mocked out, so sending fake data here does not
// affect handshaking behaviour.
// TODO(ekasper): replace with valid SCT files for test certs.
// (Fake) SignedCertificateTimestampList (as a raw binary string) to send in
// a TLS extension.
std::string signed_cert_timestamps_tls_ext;
// Whether to staple the OCSP response.
bool staple_ocsp_response = false;
// Whether to make the OCSP server unavailable. This does not affect the
// stapled OCSP response.
bool ocsp_server_unavailable = false;
// List of protocols to advertise in NPN extension. NPN is not supported if
// list is empty. Note that regardless of what protocol is negotiated, the
// test server will continue to speak HTTP/1.1.
std::vector<std::string> npn_protocols;
// List of supported ALPN protocols.
std::vector<std::string> alpn_protocols;
// Whether to send a fatal alert immediately after completing the handshake.
bool alert_after_handshake = false;
// If true, disables channel ID on the server.
bool disable_channel_id = false;
// If true, disables extended master secret tls extension.
bool disable_extended_master_secret = false;
// List of token binding params that the server supports and will negotiate.
std::vector<int> supported_token_binding_params;
};
// Initialize a TestServer.
explicit BaseTestServer(Type type);
// Initialize a TestServer with a specific set of SSLOptions for HTTPS or WSS.
BaseTestServer(Type type, const SSLOptions& ssl_options);
// Starts the server blocking until the server is ready.
bool Start() WARN_UNUSED_RESULT;
// Start the test server without blocking. Use this if you need multiple test
// servers (such as WebSockets and HTTP, or HTTP and HTTPS). You must call
// BlockUntilStarted on all servers your test requires before executing the
// test. For example:
//
// // Start the servers in parallel.
// ASSERT_TRUE(http_server.StartInBackground());
// ASSERT_TRUE(websocket_server.StartInBackground());
// // Wait for both servers to be ready.
// ASSERT_TRUE(http_server.BlockUntilStarted());
// ASSERT_TRUE(websocket_server.BlockUntilStarted());
// RunMyTest();
//
// Returns true on success.
virtual bool StartInBackground() WARN_UNUSED_RESULT = 0;
// Block until the test server is ready. Returns true on success. See
// StartInBackground() documentation for more information.
virtual bool BlockUntilStarted() WARN_UNUSED_RESULT = 0;
// Returns the host port pair used by current Python based test server only
// if the server is started.
const HostPortPair& host_port_pair() const;
const base::FilePath& document_root() const { return document_root_; }
const base::DictionaryValue& server_data() const;
std::string GetScheme() const;
bool GetAddressList(AddressList* address_list) const WARN_UNUSED_RESULT;
GURL GetURL(const std::string& path) const;
GURL GetURLWithUser(const std::string& path,
const std::string& user) const;
GURL GetURLWithUserAndPassword(const std::string& path,
const std::string& user,
const std::string& password) const;
static bool GetFilePathWithReplacements(
const std::string& original_path,
const std::vector<StringPair>& text_to_replace,
std::string* replacement_path);
static bool UsingSSL(Type type) {
return type == BaseTestServer::TYPE_HTTPS ||
type == BaseTestServer::TYPE_WSS;
}
// Enable HTTP basic authentication. Currently this only works for TYPE_WS and
// TYPE_WSS.
void set_websocket_basic_auth(bool ws_basic_auth) {
ws_basic_auth_ = ws_basic_auth;
}
// Disable creation of anonymous FTP user.
void set_no_anonymous_ftp_user(bool no_anonymous_ftp_user) {
no_anonymous_ftp_user_ = no_anonymous_ftp_user;
}
// Redirect proxied CONNECT requests to localhost.
void set_redirect_connect_to_localhost(bool redirect_connect_to_localhost) {
redirect_connect_to_localhost_ = redirect_connect_to_localhost;
}
// Marks the root certificate of an HTTPS test server as trusted for
// the duration of tests.
bool LoadTestRootCert() const WARN_UNUSED_RESULT;
// Returns the certificate that the server is using.
scoped_refptr<X509Certificate> GetCertificate() const;
protected:
virtual ~BaseTestServer();
Type type() const { return type_; }
const SSLOptions& ssl_options() const { return ssl_options_; }
bool started() const { return started_; }
// Gets port currently assigned to host_port_pair_ without checking
// whether it's available (server started) or not.
uint16_t GetPort();
// Sets |port| as the actual port used by Python based test server.
void SetPort(uint16_t port);
// Set up internal status when the server is started.
bool SetupWhenServerStarted() WARN_UNUSED_RESULT;
// Clean up internal status when starting to stop server.
void CleanUpWhenStoppingServer();
// Set path of test resources.
void SetResourcePath(const base::FilePath& document_root,
const base::FilePath& certificates_dir);
// Parses the server data read from the test server and sets |server_data_|.
// *port is set to the port number specified in server_data. The port may be
// different from the local port set in |host_port_pair_|, specifically when
// using RemoteTestServer (which proxies connections from 127.0.0.1 to a
// different IP). Returns true on success.
bool SetAndParseServerData(const std::string& server_data,
int* port) WARN_UNUSED_RESULT;
// Generates a DictionaryValue with the arguments for launching the external
// Python test server.
bool GenerateArguments(base::DictionaryValue* arguments) const
WARN_UNUSED_RESULT;
// Subclasses can override this to add arguments that are specific to their
// own test servers.
virtual bool GenerateAdditionalArguments(
base::DictionaryValue* arguments) const WARN_UNUSED_RESULT;
private:
void Init(const std::string& host);
// Document root of the test server.
base::FilePath document_root_;
// Directory that contains the SSL certificates.
base::FilePath certificates_dir_;
// Address on which the tests should connect to the server. With
// RemoteTestServer it may be different from the address on which the server
// listens on.
HostPortPair host_port_pair_;
// Holds the data sent from the server (e.g., port number).
std::unique_ptr<base::DictionaryValue> server_data_;
// If |type_| is TYPE_HTTPS or TYPE_WSS, the TLS settings to use for the test
// server.
SSLOptions ssl_options_;
Type type_;
// Has the server been started?
bool started_ = false;
// Enables logging of the server to the console.
bool log_to_console_ = false;
// Is WebSocket basic HTTP authentication enabled?
bool ws_basic_auth_ = false;
// Disable creation of anonymous FTP user?
bool no_anonymous_ftp_user_ = false;
// Redirect proxied CONNECT requests to localhost?
bool redirect_connect_to_localhost_ = false;
std::unique_ptr<ScopedPortException> allowed_port_;
DISALLOW_COPY_AND_ASSIGN(BaseTestServer);
};
} // namespace net
#endif // NET_TEST_SPAWNED_TEST_SERVER_BASE_TEST_SERVER_H_
| [
"jiawang.yu@spreadtrum.com"
] | jiawang.yu@spreadtrum.com |
7255019859949d3e5d485d8a1a84d921c2c3c318 | ed6c861536fbc851f701088841b6667baae9c7ab | /third_party/gfootball_engine/src/utils/gui2/windowmanager.cpp | 4ccaf5b3bdfdbd4f3828bc4f62629441b4ade9b4 | [
"Unlicense",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | jgromero/football | a262a6fe89b230a72e02bd98bb17414a10fa1b3b | 758a9d5d5d4955de1a6ff5a798f08d6f4a31fa62 | refs/heads/master | 2020-06-24T15:58:37.022886 | 2019-07-26T12:27:27 | 2019-07-26T12:27:27 | 199,008,507 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,887 | cpp | // Copyright 2019 Google LLC & Bastiaan Konings
// 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.
// written by bastiaan konings schuiling 2008 - 2014
// this work is public domain. the code is undocumented, scruffy, untested, and should generally not be used for anything important.
// i do not offer support, so don't ask. to be used for inspiration :)
#include "windowmanager.hpp"
#include <cmath>
#include "widgets/root.hpp"
#include "../../managers/resourcemanagerpool.hpp"
#include "../../scene/objectfactory.hpp"
namespace blunted {
Gui2WindowManager::Gui2WindowManager(boost::shared_ptr<Scene2D> scene2D, float aspectRatio, float margin) : scene2D(scene2D), aspectRatio(aspectRatio), margin(margin), pageFactory(0) {
root = new Gui2Root(this, "root", 0, 0, 100, 100);
timeStep_ms = 10;
focus = root;
style = new Gui2Style();
int contextW, contextH, bpp; // context
scene2D->GetContextSize(contextW, contextH, bpp);
contextW -= margin * 2;
contextH -= margin * 2;
float contextAspectRatio = (float)contextW / (float)contextH;
if (contextAspectRatio > aspectRatio) { // context width is larger than "virtual context's" width, so cap by height
effectiveW = contextH * aspectRatio;
effectiveH = contextH;
} else {
effectiveW = contextW;
effectiveH = contextW / aspectRatio;
}
effectiveW = clamp(effectiveW, 1, contextW);
effectiveH = clamp(effectiveH, 1, contextH);
// blackout background
scene2D->GetContextSize(contextW, contextH, bpp);
SDL_Surface *sdlSurface = CreateSDLSurface(contextW, contextH);
boost::intrusive_ptr < Resource <Surface> > resource = ResourceManagerPool::getSurfaceManager()->Fetch("gui2_blackoutbackground", false, true);
Surface *surface = resource->GetResource();
surface->SetData(sdlSurface);
blackoutBackground = boost::static_pointer_cast<Image2D>(ObjectFactory::GetInstance().CreateObject("gui2_blackoutbackground", e_ObjectType_Image2D));
scene2D->CreateSystemObjects(blackoutBackground);
blackoutBackground->SetImage(resource);
blackoutBackground->DrawRectangle(0, 0, contextW, contextH, Vector3(0, 0, 0), 255);
blackoutBackground->OnChange();
blackoutBackground->SetPosition(0, 0);
blackoutBackground->Disable();
scene2D->AddObject(blackoutBackground);
pagePath = new Gui2PagePath();
}
Gui2WindowManager::~Gui2WindowManager() {
delete style;
scene2D->DeleteObject(blackoutBackground);
blackoutBackground.reset();
delete pagePath;
}
void Gui2WindowManager::Exit() {
for (unsigned int i = 0; i < pendingDelete.size(); i++) {
pendingDelete[i]->Exit();
delete pendingDelete[i];
}
pendingDelete.clear();
std::vector < boost::intrusive_ptr<Image2D> > images;
root->GetImages(images);
for (unsigned int i = 0; i < images.size(); i++) {
boost::intrusive_ptr<Image2D> &image = images[i];
if (image != boost::intrusive_ptr<Image2D>()) {
Log(e_Warning, "Gui2WindowManager", "Exit", "GUI2 image still here on wm exit: " + image->GetName());
}
}
root->Exit();
delete root;
}
void Gui2WindowManager::SetFocus(Gui2View *view) {
if (focus == view) return;
if (focus) {
focus->SetInFocusPath(false);
focus->OnLoseFocus();
}
focus = view;
if (focus) {
focus->SetInFocusPath(true);
focus->OnGainFocus();
}
}
void Gui2WindowManager::Process() {
for (int i = 0; i < (signed int)pendingDelete.size(); i++) {
pendingDelete[i]->Exit();
delete pendingDelete[i];
}
pendingDelete.clear();
root->Process();
}
void Gui2WindowManager::GetCoordinates(float x_percent, float y_percent, float width_percent, float height_percent, int &x, int &y, int &width, int &height) const {
int contextW, contextH, bpp; // context
scene2D->GetContextSize(contextW, contextH, bpp);
contextW -= margin * 2;
contextH -= margin * 2;
float contextAspectRatio = (float)contextW / (float)contextH;
int startX, startY;
if (contextAspectRatio > aspectRatio) { // context width is larger than "virtual context's" width, so cap by height
startX = margin + (contextW - effectiveW) * 0.5f;
startY = margin;
} else {
startX = margin;
startY = margin + (contextH - effectiveH) * 0.5f;
}
width = int(std::round(effectiveW * width_percent * 0.01f));
height = int(std::round(effectiveH * height_percent * 0.01f));
x = startX + int(std::round(effectiveW * x_percent * 0.01f));
y = startY + int(std::round(effectiveH * y_percent * 0.01f));
if (width < 1) width = 1;
if (height < 1) height = 1;
}
float Gui2WindowManager::GetWidthPercent(int pixels) {
return pixels / (effectiveW * 0.01f);
}
float Gui2WindowManager::GetHeightPercent(int pixels) {
return pixels / (effectiveH * 0.01f);
}
boost::intrusive_ptr<Image2D> Gui2WindowManager::CreateImage2D(const std::string &name, int width, int height, bool sceneRegister) {
SDL_Surface *sdlSurface = CreateSDLSurface(width, height);
boost::intrusive_ptr < Resource <Surface> > resource = ResourceManagerPool::getSurfaceManager()->Fetch(name, false, true);
Surface *surface = resource->GetResource();
surface->SetData(sdlSurface);
boost::intrusive_ptr<Image2D> image = boost::static_pointer_cast<Image2D>(ObjectFactory::GetInstance().CreateObject(name, e_ObjectType_Image2D));
if (sceneRegister) scene2D->CreateSystemObjects(image);
image->SetImage(resource);
// temporary hack to hide views that haven't been setposition'ed yet
int contextW, contextH, bpp; // context
scene2D->GetContextSize(contextW, contextH, bpp);
image->SetPosition(contextW, contextH);
if (sceneRegister) {
image->Disable();
scene2D->AddObject(image);
}
return image;
}
void Gui2WindowManager::UpdateImagePosition(Gui2View *view) const {
std::vector < boost::intrusive_ptr<Image2D> > images;
view->GetImages(images);
for (unsigned int i = 0; i < images.size(); i++) {
boost::intrusive_ptr<Image2D> &image = images[i];
if (image != boost::intrusive_ptr<Image2D>()) {
float x_percent, y_percent;
int x, y, w, h;
view->GetDerivedPosition(x_percent, y_percent);
GetCoordinates(x_percent, y_percent, 0, 0, x, y, w, h);
image->SetPosition(x, y);
}
}
}
void Gui2WindowManager::RemoveImage(boost::intrusive_ptr<Image2D> image) const {
scene2D->DeleteObject(image);
}
void Gui2WindowManager::MarkForDeletion(Gui2View *view) {
pendingDelete.push_back(view);
}
void Gui2WindowManager::Show(Gui2View *view) {
std::vector < boost::intrusive_ptr<Image2D> > images;
view->GetImages(images);
for (unsigned int i = 0; i < images.size(); i++) {
boost::intrusive_ptr<Image2D> &image = images[i];
if (image != boost::intrusive_ptr<Image2D>()) {
image->Enable();
}
}
}
void Gui2WindowManager::Hide(Gui2View *view) {
std::vector < boost::intrusive_ptr<Image2D> > images;
view->GetImages(images);
for (unsigned int i = 0; i < images.size(); i++) {
boost::intrusive_ptr<Image2D> &image = images[i];
if (image != boost::intrusive_ptr<Image2D>()) {
image->Disable();
}
}
}
}
| [
"jgomez@decsai.ugr.es"
] | jgomez@decsai.ugr.es |
6cd0a8eee4766e80b4434157570e131126d21708 | 68b58eabac7d9abfce991503b74d2339ee4451a3 | /MyApplication2/app/src/main/cpp/native-lib.cpp | 11a7a6c319500c31ed2963bc0c94bffe9e53d2e1 | [] | no_license | mustafaahmed-hub/MyApplication | e585ae20cd7d4359b7de60d9150d912a306a77d9 | 7de7d3239cd6c01ecad38a6cd0b7805966d0bb92 | refs/heads/master | 2021-09-25T01:24:42.780629 | 2018-03-29T13:48:10 | 2018-03-29T13:48:10 | 123,416,090 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 281 | cpp | #include <jni.h>
#include <string>
extern "C"
JNIEXPORT jstring
JNICALL
Java_com_example_mustafa_myapplication_MainActivity_stringFromJNI(
JNIEnv *env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
| [
"mustafaahmed41@gmail.com"
] | mustafaahmed41@gmail.com |
31a4999e58753978da7746f24c3b0ae07b3d607e | 189592ed899dd62da3d01a30b7ddda22ab40556f | /src/CoreLib 3D/MyRect.cpp | 79a6f3bdd2f638e2cd898671af8408fd84dd3652 | [] | no_license | awesombly/MyStudy | 3ddc3f66d786a1ceac9ce08d1989048c4bccf8b8 | 3bc180a46434b856c1b93af2b8795fabb69f87a2 | refs/heads/master | 2020-05-03T00:04:45.809278 | 2019-04-28T11:23:48 | 2019-04-28T11:23:48 | 178,299,523 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 9,396 | cpp | #include "MyRect.h"
MyVector4::MyVector4(const MyRect& _rect) noexcept
: x(_rect.m_point.x), y(_rect.m_point.y), z((float)_rect.m_width), w((float)_rect.m_height)
{};
MyRect::MyRect(const int& x, const int& y, const int& width, const int& height) noexcept
: m_point((float)x, (float)y), m_width(width), m_height(height)
{}
MyRect::MyRect(const float& x, const float& y, const int& width, const int& height) noexcept
: m_point(x, y), m_width(width), m_height(height)
{}
MyRect::~MyRect() {}
void MyRect::Move(const int& x, const int& y) noexcept
{
m_point.x += (int)x;
m_point.y += (int)y;
}
void MyRect::Move(const float& x, const float& y) noexcept
{
m_point.x += x;
m_point.y += y;
}
void MyRect::Move(const MyVector2& point) noexcept
{
m_point.x += point.x;
m_point.y += point.y;
}
void MyRect::Move(const POINT& point) noexcept
{
m_point.x += (float)point.x;
m_point.y += (float)point.y;
}
bool MyRect::CollisionCheck(const MyVector2& point) const noexcept
{
if (point.x > m_point.x && point.x < m_point.x + m_width &&
point.y > m_point.y && point.y < m_point.y + m_height)
{
return true;
}
return false;
}
bool MyRect::CollisionCheck(const POINT& point) const noexcept
{
if (point.x > m_point.x && point.x < m_point.x + m_width &&
point.y > m_point.y && point.y < m_point.y + m_height)
{
return true;
}
return false;
}
bool MyRect::CollisionCheck(const MyRect& rect) const noexcept
{
if (m_point.x <= rect.m_point.x + rect.m_width &&
m_point.x + m_width >= rect.m_point.x &&
m_point.y <= rect.m_point.y + rect.m_height &&
m_point.y + m_height >= rect.m_point.y)
return true;
return false;
}
bool MyRect::CollisionCheck(const RECT& rect) const noexcept
{
if (m_point.x <= rect.left + rect.right &&
m_point.x + m_width >= rect.left &&
m_point.y <= rect.top + rect.bottom &&
m_point.y + m_height >= rect.top)
return true;
return false;
}
// 반지름(원)으로 체크
bool MyRect::CollisionCheck(const float& distance, const float& targetRadius) const noexcept
{
if(distance <= m_width / 2.0f + targetRadius)
return true;
return false;
}
//MyRect MyRect::Intersection(const MyRect& rect) const noexcept
//{
// // 충돌 체크
// if (!CollisionCheck(rect)) return MyRect();
//
// MyRect pRect;
// // 큰 left, 큰 top, 작은 right, 작은 bottom
// pRect.m_point.x = std::fmax(m_point.x, rect.m_point.x);
// pRect.m_point.y = std::fmax(m_point.y, rect.m_point.y);
// pRect.m_width = (int)(std::fmin(m_point.x + m_width, rect.m_point.x + rect.m_width) - pRect.m_point.x);
// pRect.m_height = (int)(std::fmin(m_point.y + m_height, rect.m_point.y + rect.m_height) - pRect.m_point.y);
//
// return pRect;
//}
//
//MyRect MyRect::Union(const MyRect& rect) const noexcept
//{
// //if (!CollisionCheck(rect)) return nullptr;
// MyRect pRect;
//
// // 작은 left, 작은 top, 큰 right, 큰 bottom
// pRect.m_point.x = std::fmin(m_point.x, rect.m_point.x);
// pRect.m_point.y = std::fmin(m_point.y, rect.m_point.y);
// pRect.m_width = (int)(std::fmax(m_point.x + m_width, rect.m_point.x + rect.m_width) - pRect.m_point.x);
// pRect.m_height = (int)(std::fmax(m_point.y + m_height, rect.m_point.y + rect.m_height) - pRect.m_point.y);
//
// return pRect;
//}
//void MyRect::DrawRect() const noexcept
//{
// DrawRect(*this);
//}
//
//void MyRect::DrawRect(const MyRect& rect) const noexcept
//{
// try
// {
// std::cout << "Left : " << rect.getLeft() << ",\tTop : " << rect.getTop() << ",\tRight : " << rect.getRight() << ",\tBottom : " << rect.getBottom() << std::endl;
// }
// catch (...)
// {
// std::cout << "null" << std::endl;
// }
//
// int right = rect.getRight();
// int bottom = rect.getBottom();
// for (int h = 0; h < right; h++)
// {
// for (int w = 0; w < bottom; w++)
// {
// if (h < rect.m_point.y || w < rect.m_point.x)
// {
// std::cout << "·";
// continue;
// }
// std::cout << "■";
// }
// std::cout << std::endl;
// }
//}
MyVector2 MyRect::getPoint() const noexcept
{
return m_point;
}
int MyRect::getWidth() const noexcept
{
return m_width;
}
int MyRect::getHeight() const noexcept
{
return m_height;
}
MyVector2 MyRect::getCenter() const noexcept
{
return {m_point.x + m_width / 2, m_point.y + m_height / 2 };
}
int MyRect::getCenterX() const noexcept
{
return (int)(m_point.x + m_width / 2);
}
int MyRect::getCenterY() const noexcept
{
return (int)(m_point.y + m_height / 2);
}
MyVector2 MyRect::getWH() const noexcept
{
return MyVector2(m_width, m_height);
}
int MyRect::getX() const noexcept
{
return (int)m_point.x;
}
int MyRect::getY() const noexcept
{
return (int)m_point.y;
}
int MyRect::getLeft() const noexcept
{
return (int)m_point.x;
}
int MyRect::getRight() const noexcept
{
return (int)m_point.x + m_width;
}
int MyRect::getTop() const noexcept
{
return (int)m_point.y;
}
int MyRect::getBottom() const noexcept
{
return (int)m_point.y + m_height;
}
void MyRect::setX(const int& x) noexcept
{
m_point.x = (float)x;
}
void MyRect::setX(const float& x) noexcept
{
m_point.x = x;
}
void MyRect::setY(const int& y) noexcept
{
m_point.y = (float)y;
}
void MyRect::setY(const float& y) noexcept
{
m_point.y = y;
}
void MyRect::setPoint(const int& x, const int& y) noexcept
{
m_point = { (float)x, (float)y };
}
void MyRect::setPoint(const float& x, const float& y) noexcept
{
m_point = { x, y };
}
void MyRect::setPoint(const MyVector2& point) noexcept
{
m_point = point;
}
void MyRect::setWidth(const int& width) noexcept
{
m_width = width;
}
void MyRect::setHeight(const int& height) noexcept
{
m_height = height;
}
void MyRect::setWH(const int& width, const int& height) noexcept
{
m_width = width;
m_height = height;
}
void MyRect::setWH(const float& width, const float& height) noexcept
{
m_width = (int)width;
m_height = (int)height;
}
void MyRect::setWH(const MyVector2& width_height) noexcept
{
m_width = (int)width_height.x;
m_height = (int)width_height.y;
}
void MyRect::setLeft(const int& value) noexcept
{
m_point.x = (float)value;
}
void MyRect::setTop(const int& value) noexcept
{
m_point.y = (float)value;
}
void MyRect::setRight(const int& value) noexcept
{
m_point.x = (float)(value - m_width);
}
void MyRect::setBottom(const int& value) noexcept
{
m_point.y = (float)(value - m_height);
}
void MyRect::setRect(const RECT& rect) noexcept
{
setRect(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top);
}
void MyRect::setRect(const MyRect& rect) noexcept
{
*this = rect;
}
void MyRect::setRect(const int& x, const int& y, const int& width, const int& height) noexcept
{
m_point = { (float)x, (float)y };
m_width = width;
m_height = height;
}
void MyRect::setRect(const float& x, const float& y, const int& width, const int& height) noexcept
{
m_point = { x, y };
m_width = width;
m_height = height;
}
void MyRect::setRect(const float& x, const float& y, const float& width, const float& height) noexcept
{
m_point = { x, y };
m_width = (int)width;
m_height = (int)height;
}
void MyRect::setCenter(const int& x, const int& y) noexcept
{
m_point.x = (float)(x - m_width / 2);
m_point.y = (float)(y - m_height / 2);
}
void MyRect::setCenter(const float& x, const float& y) noexcept
{
m_point.x = x - m_width / 2;
m_point.y = y - m_height / 2;
}
void MyRect::setCenter(const MyVector2& point) noexcept
{
m_point.x = point.x - m_width / 2;
m_point.y = point.y - m_height / 2;
}
void MyRect::setCenter(const POINT& point) noexcept
{
m_point.x = (float)(point.x - m_width / 2);
m_point.y = (float)(point.y - m_height / 2);
}
void MyRect::setCenterX(const int& _x) noexcept
{
m_point.x = (float)(_x - m_width / 2);
}
void MyRect::setCenterX(const float& _x) noexcept
{
m_point.x = (_x - m_width / 2);
}
void MyRect::setCenterY(const int& _y) noexcept
{
m_point.y = (float)(_y - m_height / 2);
}
void MyRect::setCenterY(const float& _y) noexcept
{
m_point.y = (_y - m_height / 2);
}
void MyRect::RECTset(RECT* rect) const noexcept
{
rect->left = (long)m_point.x;
rect->top = (long)m_point.y;
rect->right = m_width;
rect->bottom = m_height;
}
MyRect& MyRect::operator =(const RECT& rect) noexcept
{
setRect(rect);
return *this;
}
//MyRect& MyRect::operator +(const MyRect& rect) noexcept
//{
// return *this + rect;
//}
//MyRect& MyRect::operator *(const MyRect& rect) noexcept
//{
// return Intersection(rect);
//}
//MyRect MyRect::operator +(const int& iValue) noexcept
//{
// return MyRect(*this) + iValue;
//}
//MyRect MyRect::operator -(const int& iValue) noexcept
//{
// return MyRect(*this) - iValue;
//}
//MyRect& operator +(const int& iValue, const MyRect& rect) noexcept
//{
// MyRect* tempRect = new MyRect(rect);
// tempRect->Move(iValue, iValue);
//
// return *tempRect;
//}
//MyRect& operator -(const int& iValue, const MyRect& rect) noexcept
//{
// MyRect* tempRect = new MyRect(rect);
// tempRect->Move(-iValue, -iValue);
//
// return *tempRect;
//}
float MyRect::getAngle(const int& sx, const int& sy, const int& dx, const int& dy) noexcept
{
int&& vx = dx - sx;
int&& vy = dy - sy;
float&& radian = (float)atan2(vy, vx);
float&& degree = (radian * 57.3f);
if (degree < 0)
degree += 360;
return degree;
}
float MyRect::getAngle(const MyVector2& sP, const MyVector2& dP) noexcept
{
float&& vx = dP.x - sP.x;
float&& vy = dP.y - sP.y;
float&& radian = atan2(vy, vx);
float&& degree = (radian * 57.3f);
if (degree < 0)
degree += 360;
return degree;
}
| [
"walckm11@gmail.com"
] | walckm11@gmail.com |
0f7151f230c430835fa42c382c9b998d93d80686 | 6a4bab87a7d665af121ec6617fc8f77afe76d57c | /ozones.cpp | a8d5c9b78c8798b5f0ab0f5f185640eb782e62e0 | [
"MIT"
] | permissive | vodozhaba/ozones | 4cceb941748b537f42c996474a2f6496c1f93db5 | 1f35b1d4d7d3e52c6b41e9bb8945f6e97c0003e9 | refs/heads/master | 2020-03-22T12:17:21.303965 | 2018-07-14T14:40:20 | 2018-07-14T14:40:20 | 140,030,616 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,095 | cpp | // This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
#include <fstream>
#include <iostream>
#include <memory>
#include <SFML/Graphics.hpp>
#include "cpu.h"
#include "ines.h"
#include "ram.h"
#include "rom.h"
using namespace ozones;
int main()
{
auto ram = std::make_shared<Ram>(2048);
std::ifstream rom;
rom.open("/home/vodozhaba/nestest.nes", std::ios::in | std::ios::binary);
INesHeader header;
rom.read((char*) &header, sizeof(header));
auto prg_rom = std::make_shared<Rom>(rom, 16384 * header.prg_rom_size);
ram->Map(prg_rom, 0xC000, 0, 32768);
Cpu cpu(ram);
while(true) {
cpu.Tick();
}
sf::RenderWindow app(sf::VideoMode(1024, 960), "OzoNES");
while (app.isOpen() || app.isOpen())
{
sf::Event event;
while (app.pollEvent(event))
{
if (event.type == sf::Event::Closed)
app.close();
}
app.clear();
app.display();
}
return EXIT_SUCCESS;
}
| [
"vodozhaba@vodozhaba.net"
] | vodozhaba@vodozhaba.net |
44d93410572cd691a48f2d153e5c467410f055d0 | 9cd376a388eb6a812a8c86340256d92149fc72eb | /ios_cracker/apple_connection_device.h | 2495aed134c17324b463dc99bd8439467a0b021f | [] | no_license | frankKiwi/aid | f290372b031d797cad32264a55110096a777aaf5 | 0207d6101b349cb338e982b4b22ed25dae27dda1 | refs/heads/master | 2023-08-04T12:40:35.996158 | 2021-09-17T06:24:04 | 2021-09-17T06:24:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 611 | h | #ifndef IOS_CRACKER_APPLE_CONNECTION_DEVICE_H_
#define IOS_CRACKER_APPLE_CONNECTION_DEVICE_H_
//////////////////////////////////////////////////////////////////////////
#include "ios_cracker/atl_dll_main.h"
#include "ABI/thirdparty/glog/basictypes.h"
//////////////////////////////////////////////////////////////////////////
namespace ios_cracker{
class WIN_DLL_API ConnectionDevice
{
public:
ConnectionDevice(const char* udid);
virtual ~ConnectionDevice();
private:
DISALLOW_EVIL_CONSTRUCTORS(ConnectionDevice);
};
}
//////////////////////////////////////////////////////////////////////////
#endif | [
"voquanghoa@gmail.com"
] | voquanghoa@gmail.com |
e2b3d6c253cf514721d9ac4fa12a08a7559523b1 | 5aa4e2700c392378382c5a31fc1fcbbc0f98dfa4 | /codeforces/codeforces_271A.cpp | 7f2d70064c254a28193e8f726767c8b36eb005ff | [] | no_license | moayman/problem_solving | 892a25d96bf2f27c53f8e6e1956a75f5350adcaa | 088a65375ebe87436ee7fa891694fc551bc979c5 | refs/heads/master | 2022-06-25T20:32:58.733493 | 2022-05-16T19:47:46 | 2022-05-16T19:47:46 | 91,253,798 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 652 | cpp | #include <iostream>
#include <unordered_set>
using namespace std;
bool isDistinct(int data)
{
int a = data % 10;
data /= 10;
int b = data % 10;
data /= 10;
int c = data % 10;
data /= 10;
int d = data % 10;
if (!(a == b || a == c || a == d ||
b == c || b == d ||
c == d))
return true;
return false;
// unordered_set<int> distinct;
// while (data) {
// distinct.insert(data % 10);
// data /= 10;
// }
// return distinct.size() == 4;
}
int main()
{
int data;
cin >> data;
while (!isDistinct(++data))
{
}
cout << data;
return 0;
} | [
"mo_ayman@live.com"
] | mo_ayman@live.com |
de7fd689fe05ccf3294df4b00000ef09d135baed | 79f3c7f0faa4685715b8fdc13b8dda7cf915e8d1 | /STM32F1xx_CPP_FW - PowerMonitor - NewUI/HW_Modules/INA219/INA219.cpp | a74ed60f6522a05bd72a80695897705b1ed21b25 | [] | no_license | amitandgithub/STM32F1xx_CPP_FW | fc155c2f0772b1b282388b6c2e2d24ebe8daf946 | b61816696109cb48d0eb4a0a0b9b1232881ea5c3 | refs/heads/master | 2023-02-11T16:55:30.247303 | 2020-12-26T16:56:47 | 2020-12-26T16:56:47 | 178,715,062 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 15,289 | cpp | /*
* INA219.cpp
*
* Created on: 17-Dec-2017
* Author: Amit Chaudhary
*/
#include "INA219.h"
namespace BSP
{
INA219::INA219(uint8_t INA219Address) :m_INA219_Address(INA219Address)
{
}
INA219::~INA219()
{
}
void INA219::HwInit()
{
I2C_INSTANCE.HwInit(400000);
SetCalibration_16V_400mA();
}
void INA219::Run(Power_t* pPower)
{
pPower->Voltage = GetBusVoltage_V();
pPower->Current = GetCurrent_mA();
// if(pPower->Voltage < 0.89f ) pPower->Voltage=0; // Negative voltage till 0.40v is not what we are interested in.
if(pPower->Current < 0.3 ) pPower->Current = 0; // Discard the junk values
RUN_EVERY_MILLIS(128,CaptureSamples(pPower));
}
void INA219::CaptureSamples(Power_t* pPower)
{
static float CurrentSamples;
static uint32_t SampleCount;
CurrentSamples += GetCurrent_mA();
SampleCount++;
if(SampleCount >= 8)
{
pPower->mAH += CurrentSamples/28800.0; // 8*3600 = 28800
SampleCount = 0;
CurrentSamples = 0;
}
}
/**************************************************************************/
/*!
@brief Sends a single command byte over I2C
*/
/**************************************************************************/
void INA219::WriteRegister (uint8_t reg, uint16_t value)
{
buf[0] = reg;
buf[1] = ((value >> 8) & 0xFF);
buf[2] = (value & 0xFF);
I2C_INSTANCE.XferPoll( m_INA219_Address, buf, 3);
}
/**************************************************************************/
/*!
@brief Reads a 16 bit values over I2C
*/
/**************************************************************************/
void INA219::ReadRegister(uint8_t reg, uint16_t *value)
{
buf[0] = reg;
I2C_INSTANCE.XferPoll( m_INA219_Address, buf, 1) ;
I2C_INSTANCE.XferPoll( m_INA219_Address, 0,0,buf, 2);
*value = ((buf[0] << 8) | buf[1]);
}
/**************************************************************************/
/*!
@brief Configures to INA219 to be able to measure up to 32V and 2A
of current. Each unit of current corresponds to 100uA, and
each unit of power corresponds to 2mW. Counter overflow
occurs at 3.2A.
@note These calculations assume a 0.1 ohm resistor is present
*/
/**************************************************************************/
void INA219::SetCalibration_32V_2A(void)
{
// By default we use a pretty huge range for the input voltage,
// which probably isn't the most appropriate choice for system
// that don't use a lot of power. But all of the calculations
// are shown below if you want to change the settings. You will
// also need to change any relevant register settings, such as
// setting the VBUS_MAX to 16V instead of 32V, etc.
// VBUS_MAX = 32V (Assumes 32V, can also be set to 16V)
// VSHUNT_MAX = 0.32 (Assumes Gain 8, 320mV, can also be 0.16, 0.08, 0.04)
// RSHUNT = 0.1 (Resistor value in ohms)
// 1. Determine max possible current
// MaxPossible_I = VSHUNT_MAX / RSHUNT
// MaxPossible_I = 3.2A
// 2. Determine max expected current
// MaxExpected_I = 2.0A
// 3. Calculate possible range of LSBs (Min = 15-bit, Max = 12-bit)
// MinimumLSB = MaxExpected_I/32767
// MinimumLSB = 0.000061 (61uA per bit)
// MaximumLSB = MaxExpected_I/4096
// MaximumLSB = 0,000488 (488uA per bit)
// 4. Choose an LSB between the min and max values
// (Preferrably a roundish number close to MinLSB)
// CurrentLSB = 0.0001 (100uA per bit)
// 5. Compute the calibration register
// Cal = trunc (0.04096 / (Current_LSB * RSHUNT))
// Cal = 4096 (0x1000)
uint16_t config = INA219_CONFIG_BVOLTAGERANGE_32V |
INA219_CONFIG_GAIN_8_320MV |
INA219_CONFIG_BADCRES_12BIT |
INA219_CONFIG_SADCRES_12BIT_128S_69MS | // INA219_CONFIG_SADCRES_12BIT_128S_69MS INA219_CONFIG_SADCRES_12BIT_1S_532US
INA219_CONFIG_MODE_SANDBVOLT_CONTINUOUS;
ina219_calValue = 4096;
// 6. Calculate the power LSB
// PowerLSB = 20 * CurrentLSB
// PowerLSB = 0.002 (2mW per bit)
// 7. Compute the maximum current and shunt voltage values before overflow
//
// Max_Current = Current_LSB * 32767
// Max_Current = 3.2767A before overflow
//
// If Max_Current > Max_Possible_I then
// Max_Current_Before_Overflow = MaxPossible_I
// Else
// Max_Current_Before_Overflow = Max_Current
// End If
//
// Max_ShuntVoltage = Max_Current_Before_Overflow * RSHUNT
// Max_ShuntVoltage = 0.32V
//
// If Max_ShuntVoltage >= VSHUNT_MAX
// Max_ShuntVoltage_Before_Overflow = VSHUNT_MAX
// Else
// Max_ShuntVoltage_Before_Overflow = Max_ShuntVoltage
// End If
// 8. Compute the Maximum Power
// MaximumPower = Max_Current_Before_Overflow * VBUS_MAX
// MaximumPower = 3.2 * 32V
// MaximumPower = 102.4W
// Set multipliers to convert raw current/power values
ina219_currentDivider_mA = 10; // Current LSB = 100uA per bit (1000/100 = 10)
ina219_powerDivider_mW = 2; // Power LSB = 1mW per bit (2/1)
// Set Calibration register to 'Cal' calculated above
WriteRegister(INA219_REG_CALIBRATION, ina219_calValue);
// Set Config register to take into account the settings above
WriteRegister(INA219_REG_CONFIG, config);
}
/**************************************************************************/
/*!
@brief Configures to INA219 to be able to measure up to 32V and 1A
of current. Each unit of current corresponds to 40uA, and each
unit of power corresponds to 800�W. Counter overflow occurs at
1.3A.
@note These calculations assume a 0.1 ohm resistor is present
*/
/**************************************************************************/
void INA219::SetCalibration_32V_1A(void)
{
// By default we use a pretty huge range for the input voltage,
// which probably isn't the most appropriate choice for system
// that don't use a lot of power. But all of the calculations
// are shown below if you want to change the settings. You will
// also need to change any relevant register settings, such as
// setting the VBUS_MAX to 16V instead of 32V, etc.
// VBUS_MAX = 32V (Assumes 32V, can also be set to 16V)
// VSHUNT_MAX = 0.32 (Assumes Gain 8, 320mV, can also be 0.16, 0.08, 0.04)
// RSHUNT = 0.1 (Resistor value in ohms)
// 1. Determine max possible current
// MaxPossible_I = VSHUNT_MAX / RSHUNT
// MaxPossible_I = 3.2A
// 2. Determine max expected current
// MaxExpected_I = 1.0A
// 3. Calculate possible range of LSBs (Min = 15-bit, Max = 12-bit)
// MinimumLSB = MaxExpected_I/32767
// MinimumLSB = 0.0000305 (30.5�A per bit)
// MaximumLSB = MaxExpected_I/4096
// MaximumLSB = 0.000244 (244�A per bit)
// 4. Choose an LSB between the min and max values
// (Preferrably a roundish number close to MinLSB)
// CurrentLSB = 0.0000400 (40�A per bit)
// 5. Compute the calibration register
// Cal = trunc (0.04096 / (Current_LSB * RSHUNT))
// Cal = 10240 (0x2800)
uint16_t config = INA219_CONFIG_BVOLTAGERANGE_32V |
INA219_CONFIG_GAIN_8_320MV |
INA219_CONFIG_BADCRES_12BIT |
INA219_CONFIG_SADCRES_12BIT_128S_69MS |
INA219_CONFIG_MODE_SANDBVOLT_CONTINUOUS;
ina219_calValue = 10240;
// 6. Calculate the power LSB
// PowerLSB = 20 * CurrentLSB
// PowerLSB = 0.0008 (800�W per bit)
// 7. Compute the maximum current and shunt voltage values before overflow
//
// Max_Current = Current_LSB * 32767
// Max_Current = 1.31068A before overflow
//
// If Max_Current > Max_Possible_I then
// Max_Current_Before_Overflow = MaxPossible_I
// Else
// Max_Current_Before_Overflow = Max_Current
// End If
//
// ... In this case, we're good though since Max_Current is less than MaxPossible_I
//
// Max_ShuntVoltage = Max_Current_Before_Overflow * RSHUNT
// Max_ShuntVoltage = 0.131068V
//
// If Max_ShuntVoltage >= VSHUNT_MAX
// Max_ShuntVoltage_Before_Overflow = VSHUNT_MAX
// Else
// Max_ShuntVoltage_Before_Overflow = Max_ShuntVoltage
// End If
// 8. Compute the Maximum Power
// MaximumPower = Max_Current_Before_Overflow * VBUS_MAX
// MaximumPower = 1.31068 * 32V
// MaximumPower = 41.94176W
// Set multipliers to convert raw current/power values
ina219_currentDivider_mA = 25; // Current LSB = 40uA per bit (1000/40 = 25)
ina219_powerDivider_mW = 1; // Power LSB = 800�W per bit
// Set Calibration register to 'Cal' calculated above
WriteRegister(INA219_REG_CALIBRATION, ina219_calValue);
// Set Config register to take into account the settings above
WriteRegister(INA219_REG_CONFIG, config);
}
void INA219::SetCalibration_16V_400mA(void) {
// Calibration which uses the highest precision for
// current measurement (0.1mA), at the expense of
// only supporting 16V at 400mA max.
// VBUS_MAX = 16V
// VSHUNT_MAX = 0.04 (Assumes Gain 1, 40mV)
// RSHUNT = 0.1 (Resistor value in ohms)
// 1. Determine max possible current
// MaxPossible_I = VSHUNT_MAX / RSHUNT
// MaxPossible_I = 0.4A
// 2. Determine max expected current
// MaxExpected_I = 0.4A
// 3. Calculate possible range of LSBs (Min = 15-bit, Max = 12-bit)
// MinimumLSB = MaxExpected_I/32767
// MinimumLSB = 0.0000122 (12uA per bit)
// MaximumLSB = MaxExpected_I/4096
// MaximumLSB = 0.0000977 (98uA per bit)
// 4. Choose an LSB between the min and max values
// (Preferrably a roundish number close to MinLSB)
// CurrentLSB = 0.00005 (50uA per bit)
// 5. Compute the calibration register
// Cal = trunc (0.04096 / (Current_LSB * RSHUNT))
// Cal = 8192 (0x2000)
uint16_t config = INA219_CONFIG_BVOLTAGERANGE_16V |
INA219_CONFIG_GAIN_1_40MV |
INA219_CONFIG_BADCRES_12BIT |
INA219_CONFIG_SADCRES_12BIT_128S_69MS |
INA219_CONFIG_MODE_SANDBVOLT_CONTINUOUS;
ina219_calValue = 8192;
// 6. Calculate the power LSB
// PowerLSB = 20 * CurrentLSB
// PowerLSB = 0.001 (1mW per bit)
// 7. Compute the maximum current and shunt voltage values before overflow
//
// Max_Current = Current_LSB * 32767
// Max_Current = 1.63835A before overflow
//
// If Max_Current > Max_Possible_I then
// Max_Current_Before_Overflow = MaxPossible_I
// Else
// Max_Current_Before_Overflow = Max_Current
// End If
//
// Max_Current_Before_Overflow = MaxPossible_I
// Max_Current_Before_Overflow = 0.4
//
// Max_ShuntVoltage = Max_Current_Before_Overflow * RSHUNT
// Max_ShuntVoltage = 0.04V
//
// If Max_ShuntVoltage >= VSHUNT_MAX
// Max_ShuntVoltage_Before_Overflow = VSHUNT_MAX
// Else
// Max_ShuntVoltage_Before_Overflow = Max_ShuntVoltage
// End If
//
// Max_ShuntVoltage_Before_Overflow = VSHUNT_MAX
// Max_ShuntVoltage_Before_Overflow = 0.04V
// 8. Compute the Maximum Power
// MaximumPower = Max_Current_Before_Overflow * VBUS_MAX
// MaximumPower = 0.4 * 16V
// MaximumPower = 6.4W
// Set multipliers to convert raw current/power values
ina219_currentDivider_mA = 20; // Current LSB = 50uA per bit (1000/50 = 20)
ina219_powerDivider_mW = 1; // Power LSB = 1mW per bit
// Set Calibration register to 'Cal' calculated above
WriteRegister(INA219_REG_CALIBRATION, ina219_calValue);
// Set Config register to take into account the settings above
WriteRegister(INA219_REG_CONFIG, config);
}
/**************************************************************************/
/*!
@brief Gets the raw bus voltage (16-bit signed integer, so +-32767)
*/
/**************************************************************************/
int16_t INA219::GetBusVoltage_raw() {
//uint16_t value;
ReadRegister(INA219_REG_BUSVOLTAGE, &value);
// Shift to the right 3 to drop CNVR and OVF and multiply by LSB
return (int16_t)((value >> 3) * 4);
}
/**************************************************************************/
/*!
@brief Gets the raw shunt voltage (16-bit signed integer, so +-32767)
*/
/**************************************************************************/
int16_t INA219::GetShuntVoltage_raw() {
//uint16_t value;
ReadRegister(INA219_REG_SHUNTVOLTAGE, &value);
return (int16_t)value;
}
/**************************************************************************/
/*!
@brief Gets the raw current value (16-bit signed integer, so +-32767)
*/
/**************************************************************************/
int16_t INA219::GetCurrent_raw() {
//uint16_t value;
// Sometimes a sharp load will reset the INA219, which will
// reset the cal register, meaning CURRENT and POWER will
// not be available ... avoid this by always setting a cal
// value even if it's an unfortunate extra step
WriteRegister(INA219_REG_CALIBRATION, ina219_calValue);
// Now we can safely read the CURRENT register!
ReadRegister(INA219_REG_CURRENT, &value);
return (int16_t)value;
}
/**************************************************************************/
/*!
@brief Gets the shunt voltage in mV (so +-327mV)
*/
/**************************************************************************/
float INA219::GetShuntVoltage_mV() {
//int16_t value;
value = GetShuntVoltage_raw();
return value * 0.01;
}
/**************************************************************************/
/*!
@brief Gets the shunt voltage in volts
*/
/**************************************************************************/
float INA219::GetBusVoltage_V() {
//int16_t value = GetBusVoltage_raw();
value = GetBusVoltage_raw();
return value * 0.001;
}
/**************************************************************************/
/*!
@brief Gets the current value in mA, taking into account the
config settings and current LSB
*/
/**************************************************************************/
float INA219::GetCurrent_mA()
{
//float valueDec = GetCurrent_raw();
valueDec = GetCurrent_raw();
valueDec /= ina219_currentDivider_mA;
return valueDec;
}
float INA219::GetPower_mW(void)
{
//float valueDec;
uint16_t value_Raw;
WriteRegister(INA219_REG_CALIBRATION, ina219_calValue);
ReadRegister(INA219_REG_POWER, &value_Raw);
valueDec = (int16_t)value_Raw;
valueDec /= ina219_powerDivider_mW;
return valueDec;
}
} /* namespace Bsp */
| [
"34563851+amitandgithub@users.noreply.github.com"
] | 34563851+amitandgithub@users.noreply.github.com |
b57426a62d529a0ee4876b37b9932ba480763b88 | 1139028766ff753d88531a2b1c79f4ef75df74cc | /ONE/src/ONESteppingAction.cc | 71d25e5c2c190eef88afad9e225f282e05baa7ce | [] | no_license | aleksha/G4-Models | b1b808c1eac596cc324c099fd419ba73628ed3da | 1bb848a8d6b0981b188b8499ef260ebb7477daae | refs/heads/master | 2022-05-07T23:59:39.173774 | 2022-04-19T10:06:56 | 2022-04-19T10:06:56 | 141,236,792 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,790 | cc |
#include "ONESteppingAction.hh"
#include "ONEEventAction.hh"
#include "ONEDetectorConstruction.hh"
#include "G4Step.hh"
#include "G4Event.hh"
#include "G4RunManager.hh"
#include "G4LogicalVolume.hh"
#include "G4SystemOfUnits.hh"
//------------------------------------------------------------------------------
ONESteppingAction::ONESteppingAction(ONEEventAction* eventAction)
: G4UserSteppingAction(),
fEventAction(eventAction),
fLV00(0)
{
myOUT .open( "out.data" , std::ios::trunc);
}
//------------------------------------------------------------------------------
ONESteppingAction::~ONESteppingAction(){
myOUT.close();}
//------------------------------------------------------------------------------
void ONESteppingAction::UserSteppingAction(const G4Step* step)
{
if ( !fLV00 ){
const ONEDetectorConstruction* detectorConstruction
= static_cast<const ONEDetectorConstruction*>
(G4RunManager::GetRunManager()->GetUserDetectorConstruction());
fLV00 = detectorConstruction->GetLV00();
}
// get volume of the current step
G4LogicalVolume* volume = step->GetPreStepPoint()->GetTouchableHandle()
->GetVolume()->GetLogicalVolume();
int vol=-1;
// check if we are in scoring volume
if (volume == fLV00) vol= 0 ;
// if (vol!=0 || vol!=5 || vol!=6 || vol!=7 || vol!=8 || vol!=15) return;
G4Track* trk = step->GetTrack();
int tr_c = trk->GetDefinition()->GetPDGCharge();
int ev_id = G4EventManager::GetEventManager()->GetConstCurrentEvent()->GetEventID() ;
int tr_id = trk->GetTrackID() ;
double tr_m = trk->GetDefinition()->GetPDGMass() ;
G4int p_code = trk->GetDefinition()->GetPDGEncoding();
int st_id = 0;
if( step->IsFirstStepInVolume() ){ st_id = 1; }
if( step->IsLastStepInVolume() ){ st_id = 2; }
if( trk->GetKineticEnergy ()==0 ){ st_id = 3; }
if(st_id>-1){
G4StepPoint* pre_step ; pre_step = step->GetPreStepPoint() ;
G4StepPoint* post_step ; post_step = step->GetPostStepPoint() ;
double tr_ed = step->GetTotalEnergyDeposit() - step->GetNonIonizingEnergyDeposit() ;
//double tr_rd = step->GetNonIonizingEnergyDeposit() ;
double tr_px = post_step->GetMomentum().x() ;
double tr_py = post_step->GetMomentum().y() ;
double tr_pz = post_step->GetMomentum().z() ;
double tr_e = post_step->GetTotalEnergy () ;
//double tr_t = post_step->GetKineticEnergy () ;
double tr_post_x = post_step->GetPosition().x() / mm ;
double tr_post_y = post_step->GetPosition().y() / mm ;
double tr_post_z = post_step->GetPosition().z() / mm ;
double g_post_time = post_step->GetGlobalTime () / ns ;
double tr_pre_x = pre_step->GetPosition().x() / mm ;
double tr_pre_y = pre_step->GetPosition().y() / mm ;
double tr_pre_z = pre_step->GetPosition().z() / mm ;
double g_pre_time = pre_step->GetGlobalTime () / ns ;
double tr_x = 0.5 * (tr_pre_x + tr_post_x);
double tr_y = 0.5 * (tr_pre_y + tr_post_y);
double tr_z = 0.5 * (tr_pre_z + tr_post_z);
double g_time = 0.5 * (g_pre_time + g_post_time);
if(myOUT.is_open() && vol==0 )
myOUT << ev_id << " " << tr_id << " " << st_id << " " << vol << " "
<< tr_ed << " " << p_code << " " << tr_c << " " << tr_e << " "
<< tr_post_x << " " << tr_post_y << " " << tr_post_z << " " << g_post_time << " "
<< tr_px << " " << tr_py << " " << tr_pz << " " << tr_m
<< G4endl;
}
// // collect energy deposited in this step
// G4double edepStep = step->GetTotalEnergyDeposit();
// fEventAction->AddEdep(edepStep);
}
//------------------------------------------------------------------------------
| [
"a.dzyuba@gmail.com"
] | a.dzyuba@gmail.com |
b2f7828cf987c66246cea48ea6be1893b5377beb | f2776461f62a4ff963d3d81914f633f6909a0a93 | /Projects2/opencv_image/lips/lips/NoseFeatureDetector.h | b1f9e3be7191a4f84e21ab4d1d58467638df6ce1 | [] | no_license | crupib/Source | d29ce4eb5cfa81340a4bfbf7a9620010e6590eb4 | d89b9951d8e39a1d4dd0d3b3f348f23ac4bd96b4 | refs/heads/master | 2021-05-04T11:21:46.955196 | 2018-06-16T11:50:38 | 2018-06-16T11:50:38 | 33,565,119 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,077 | h | /**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
*/
#ifndef NOSEFEATUREDETECTOR_H
#define NOSEFEATUREDETECTOR_H
#include <vector>
#include <opencv2/objdetect/objdetect.hpp>
#include "ObjectDetector.h"
#include "FaceFeatures.h"
class NoseFeatureDetector
{
public:
NoseFeatureDetector(std::string cascade_file);
NoseFeatureDetector(cv::CascadeClassifier cascade);
~NoseFeatureDetector();
int detect(cv::Mat image, cv::Rect face, NoseFeatures &nose);
private:
ObjectDetector *detector;
};
#endif /*NOSEFEATUREDETECTOR_H*/
| [
"lennon6969"
] | lennon6969 |
90b7d99bee7e1a9486fa86e6d12bfe3fe1bdebed | 2aa3696a38b5777165ecd12b2072062fa8fa9fde | /tempreature/tempreature.ino | 2f9583fcde6cc4f36ffbfaeb352e44735537f5a5 | [] | no_license | dSquadAdmin/arduinoTraining072 | 508533fb783297daa6e66653fec10b0000d119fd | 8aa9a5d2d755f67a6a85a63a5c65f42e112ec8a2 | refs/heads/master | 2016-08-11T14:20:32.529357 | 2016-01-06T01:04:47 | 2016-01-06T01:04:47 | 49,101,088 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 499 | ino | /*
* DIGITAL THERMOMETER WITH TEMPREATURE SENSING IC LM35
* CODE BY: BIST, keshav [dSquadAdmin]
* URL: http://keshavbist.com.np
* For Robotics Club of Pashchimanchal Campus
* (http://robotics.wrc.edu.np)
*
* HARDWARE CONNECTION:
* PIN1 : +5v
* PIN2 : Arduino Pin A0
* PIN3 : Ground
*/
void setup(){
pinMode(A0, INPUT);
Serial.begin(9600);
while(!Serial){
}
}
void loop(){
float temp;
temp = analogRead(A0)/2;
Serial.write("Temp=");
Serial.println(temp, HEX);
delay(100):
}
| [
"keshavbist19@gmail.com"
] | keshavbist19@gmail.com |
cd6b0b88e08117324073b79490a62a4287927209 | 3e687d784462b514065c7f4d8278fc67a0dd09e0 | /CanadianExperience\TreeLib\Leaf.cpp | c754ce6c4cd37bddea65cac914e8ad4cb9b5733d | [] | no_license | hennin67/TreeProject | 119b11f1611404107a10148932f3f4ba6f8714e3 | 85c408c9062fcdf68363d284da2dbda750cf57d1 | refs/heads/master | 2020-11-24T01:18:17.930404 | 2019-12-13T19:19:29 | 2019-12-13T19:19:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 278 | cpp | /**
* \file Leaf.cpp
*
* \author Becky Henning
*/
#include "pch.h"
#include "Leaf.h"
#include "TreeObject.h"
using namespace std;
/**
* Constructor
* \param tree the tree
*/
CLeaf::CLeaf(CTreeObject* tree) : CTreePartDrawable(tree, tree->GetLeaf())
{
}
| [
"noreply@github.com"
] | hennin67.noreply@github.com |
49493091081bea0ada91654b3815154ab707ff02 | ba02836cd2ea9f1a6035e5b34d67ba87abf9ce4d | /include/X-GSD/Entity.hpp | 4fcbb6e9cc89e53dbe3f23b88ed207886a75c3fb | [
"Zlib"
] | permissive | AndresRuizBernabeu/X-GSD | 3c37e71103f758e9db05dd3e89b830db416c83fe | 1f0b294e27f5aee0fb0448207cd1091c9d42ae44 | refs/heads/master | 2020-04-26T02:19:27.104035 | 2015-09-08T18:43:35 | 2015-09-08T18:43:35 | 31,606,886 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,919 | hpp | #pragma once
#include <X-GSD/SceneGraphNode.hpp>
#include <X-GSD/Event.hpp>
#include <X-GSD/Component.hpp>
// Include all built-in components
#include <X-GSD/ComponentSprite.hpp>
#include <X-GSD/ComponentRigidBody.hpp>
#include <X-GSD/ComponentCollider.hpp>
#include <SFML/Graphics/RenderTarget.hpp> // Completes the RenderTarget forward declaration in Drawable, inherited from SceneGrahpNode
#include <map>
#include <unordered_map>
#include <typeindex>
#include <cassert>
namespace xgsd {
/*
Entity class. Entities are the basic and fundamental units of X-GSD. An Entity is a SceneGraphNode
(an element of a Scene, with all the required scene graph behaviour and properties such as a Transform,
a reference to a parent node and a collection of children nodes) with added functionality and a unique
name which identifies it. Entities can hold Components, which add more specific functionality and
properties.
*/
class Entity : public SceneGraphNode
{
// Typedefs and enumerations
public:
typedef std::unique_ptr<Entity> Ptr;
// Methods
public:
Entity(std::string name);
~Entity();
void onAttachThis() override;
void onDetachThis() override;
void onPauseThis(const HiResDuration &dt) override;
void updateThis(const HiResDuration& dt) override;
void drawThis(sf::RenderTarget& target, sf::RenderStates states) const override;
void handleEventThis(const Event& event) override;
void addComponent(Component::Ptr component);
template <typename T>
std::unique_ptr<T> removeComponent();
template <typename T>
T* getComponent();
void collisionHandler(Entity* theOtherEntity, sf::FloatRect collision);
std::string getName();
static Entity* getEntityNamed(std::string name);
// Variables (member / properties)
private:
std::map<std::type_index, Component::Ptr> mComponents;
std::string mName;
static std::unordered_map<std::string, Entity*> entities; // TODO: Make it non-static. Maybe inside Scene class, so that each scene has a collection of pointers to entities
};
/////////////////////////////
// Template implementation //
/////////////////////////////
template <typename T>
std::unique_ptr<T> Entity::removeComponent()
{
// Retrieve the type_index of T
std::type_index index(typeid(T));
// Ensure that a component with type T exists in the collection
assert(mComponents.count(std::type_index(typeid(T))) != 0);
// Retrieve it from the collection and cast it back to the T polymorphic type
T *tmp = static_cast<T*>(mComponents[index].get());
// Remove it from the collection and return it
std::unique_ptr<T> removedComponent(tmp);
mComponents[index].release();
mComponents.erase(index);
removedComponent->detachedFromEntity();
return removedComponent;
}
template <typename T>
T* Entity::getComponent()
{
// Retrieve the type_index of T
std::type_index index(typeid(T));
// If it exists in the collection, retrieve it, cast it back to the T polymorphic type and return it
if (mComponents.count(std::type_index(typeid(T))) != 0) {
return static_cast<T*>(mComponents[index].get());
}
// Otherwise, a nullptr is returned
else {
return nullptr;
}
}
} // namespace xgsd
| [
"a.ruiz@studioseventiles.com"
] | a.ruiz@studioseventiles.com |
76f9b288a5c5de63a9cf267376906e1dd69d2fa5 | 7da3fca158ea3fb03a578aaff783739a91194bab | /Code/CEDL_test/C1-huangzile2018-2-27/head/head.cpp | 41a325759c178a77d12df08a725d65ebe10a7716 | [] | no_license | powerLEO101/Work | f1b16d410a55a9136470e0d04ccc4abcfd95e18b | 6ae5de17360a7a06e1b65d439158ff5c2d506c2a | refs/heads/master | 2021-06-18T01:33:07.380867 | 2021-02-16T10:16:47 | 2021-02-16T10:16:47 | 105,882,852 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 169 | cpp | #include<iostream>
#include<cstdio>
#include<algorithm>
int main()
{
freopen("head.in","r",stdin);
freopen("head.out","w",stdout);
std::cout<<"3 3 32";
return 0;
}
| [
"3256870400@qq.com"
] | 3256870400@qq.com |
0bae65a1a87836595d137b9c3c3255a3a949bb0a | ef7ad96103876b24bbb45be8dfba7e80771c76e7 | /ui-qt/Pretreatment/ImgpreprocessModule/ImagepreprocessDlg.cpp | d4847c0576784d0f4ceee6bd6960aab815807113 | [
"MIT"
] | permissive | TinySlik/FPGA-Industrial-Smart-Camera | ecb6274f4ef16cf9174cd73812486644f821152a | 54b3e2c2661cf7f6774a7fb4d6ae637fa73cba32 | refs/heads/master | 2021-06-25T11:09:21.212466 | 2017-09-01T07:23:58 | 2017-09-01T07:23:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,784 | cpp | #include <qdebug.h>
#include "ImagepreprocessDlg.h"
#include "ui_ImagepreprocessDlg.h"
#include <QMessageBox>
#include "../../Global/UtilitiesFun.h"
#include "PretreatMentListCollect/PretreatmentModuleItem.h"
#include "ContrastStrengthenDlg.h"
#include "ContrastSwitchDlg.h"
#include "GaussDlg.h"
#include "SharpnessDlg.h"
#include "PeakFilterDlg.h"
#include "ShadingDialog.h"
#include "DefectDialog.h"
#include "BlurDialog.h"
#include "AcceCommon.h"
//#include "fpga_global.h"
#include "Preprocess.h"
void SetGaussEnable(int flag,void *Pdata)
{
ImagepreprocessDlg *preDlg = (ImagepreprocessDlg*)Pdata;
ACCE_MODEL *ptr = (ACCE_MODEL*)preDlg->m_pre_ptr;
if(ptr == NULL)
return;
if(flag == 1)
{
ptr->image_acce_param.pre_model_cfg.gauss_model_cfg.model_enable = 1;
AcceleratorModuleEnable(ACCE_GAUSS_FILTER_ID);
}else
{
ptr->image_acce_param.pre_model_cfg.gauss_model_cfg.model_enable = 0;
AcceleratorModuleDisable(ACCE_GAUSS_FILTER_ID);
}
}
void SetGaussDDREnable(int flag,void *Pdata)
{
ImagepreprocessDlg *preDlg = (ImagepreprocessDlg*)Pdata;
AcceleratorModuleWriteDdrCfg(ACCE_GAUSS_FILTER_ID,preDlg->m_step,flag);
}
void ListGaussDlg(int itaskKind,void *Pdata)
{
ImagepreprocessDlg *preDlg = (ImagepreprocessDlg*)Pdata;
GaussDlg dlg;
dlg.m_task_id = preDlg->m_task_id;
dlg.m_step = preDlg->m_step;
dlg.m_pre_ptr = preDlg->m_pre_ptr;
dlg.m_listX = preDlg->m_listX;
dlg.m_listY = preDlg->m_listY;
dlg.InitData();
dlg.move(660,0);
dlg.exec();
}
void SetContrastStrengthenEnable(int flag,void *Pdata)
{
ImagepreprocessDlg *preDlg = (ImagepreprocessDlg*)Pdata;
ACCE_MODEL *ptr = (ACCE_MODEL*)preDlg->m_pre_ptr;
if(ptr == NULL)
return;
if(flag == 1)
{
ptr->image_acce_param.pre_model_cfg.balance_model_cfg.model_enable = 1;
AcceleratorModuleEnable(ACCE_BALANCE_MODEL_ID);
}else
{
ptr->image_acce_param.pre_model_cfg.balance_model_cfg.model_enable = 0;
AcceleratorModuleDisable(ACCE_BALANCE_MODEL_ID);
}
//AcceleratorModuleCfgShow(ACCE_BALANCE_MODEL_ID);
}
void SetContrastStrengthenDDREnable(int flag,void *Pdata)
{
ImagepreprocessDlg *preDlg = (ImagepreprocessDlg*)Pdata;
AcceleratorModuleWriteDdrCfg(ACCE_BALANCE_MODEL_ID,preDlg->m_step,flag);
}
void ListContrastStrengthenDlg(int itaskKind,void *Pdata)
{
ImagepreprocessDlg *preDlg = (ImagepreprocessDlg*)Pdata;
ContrastStrengthenDlg dlg;
dlg.m_task_id = preDlg->m_task_id;
dlg.m_step = preDlg->m_step;
dlg.m_pre_ptr = preDlg->m_pre_ptr;
dlg.InitData();
dlg.exec();
}
void SetContrastSwitchEnable(int flag,void *Pdata)
{
ImagepreprocessDlg *preDlg = (ImagepreprocessDlg*)Pdata;
ACCE_MODEL *ptr = (ACCE_MODEL*)preDlg->m_pre_ptr;
if(ptr == NULL)
return;
if(flag == 1)
{
ptr->image_acce_param.pre_model_cfg.contrast_model_cfg.model_enable =1;
AcceleratorModuleEnable(ACCE_CONTRAST_MODEL_ID);
}else
{
ptr->image_acce_param.pre_model_cfg.contrast_model_cfg.model_enable =0;
AcceleratorModuleDisable(ACCE_CONTRAST_MODEL_ID);
}
}
void SetContrastSwitchDDREnable(int flag,void *Pdata)
{
ImagepreprocessDlg *preDlg = (ImagepreprocessDlg*)Pdata;
AcceleratorModuleWriteDdrCfg(ACCE_CONTRAST_MODEL_ID,preDlg->m_step,flag);
}
void ListContrastSwitchDlg(int itaskKind,void *Pdata)
{
ImagepreprocessDlg *preDlg = (ImagepreprocessDlg*)Pdata;
ContrastSwitchDlg dlg;
dlg.m_task_id = preDlg->m_task_id;
dlg.m_step = preDlg->m_step;
dlg.m_pre_ptr = preDlg->m_pre_ptr;
dlg.m_listX = preDlg->m_listX;
dlg.m_listY = preDlg->m_listY;
dlg.IniData();
dlg.move(660,0);
dlg.exec();
}
//边缘强调
void SetSharpnessEnable(int flag,void *Pdata)
{
ImagepreprocessDlg *preDlg = (ImagepreprocessDlg*)Pdata;
ACCE_MODEL *ptr = (ACCE_MODEL*)preDlg->m_pre_ptr;
if(ptr == NULL)
return;
if(flag == 1)
{
ptr->image_acce_param.pre_model_cfg.sharpness_model_cfg.model_enable = 1;
AcceleratorModuleEnable(ACCE_SHARPNESS_MODEL_ID);
}else
{
ptr->image_acce_param.pre_model_cfg.sharpness_model_cfg.model_enable = 0;
AcceleratorModuleDisable(ACCE_SHARPNESS_MODEL_ID);
}
}
void SetSharpnessDDREnable(int flag,void *Pdata)
{
ImagepreprocessDlg *preDlg = (ImagepreprocessDlg*)Pdata;
AcceleratorModuleWriteDdrCfg(ACCE_SHARPNESS_MODEL_ID,preDlg->m_step,flag);
}
void ListSharpnessDlg(int itaskKind,void *Pdata)
{
ImagepreprocessDlg *preDlg = (ImagepreprocessDlg*)Pdata;
SharpnessDlg dlg;
dlg.m_task_id = preDlg->m_task_id;
dlg.m_step = preDlg->m_step;
dlg.m_pre_ptr = preDlg->m_pre_ptr;
dlg.m_listX = preDlg->m_listX;
dlg.m_listY = preDlg->m_listY;
dlg.move(660,0);
dlg.InitData();
dlg.exec();
}
//原图膨胀腐蚀A
void SetPeakFilterAEnable(int flag,void *Pdata)
{
ImagepreprocessDlg *preDlg = (ImagepreprocessDlg*)Pdata;
ACCE_MODEL *ptr = (ACCE_MODEL*)preDlg->m_pre_ptr;
if(ptr == NULL)
return;
if(flag == 1)
{
ptr->image_acce_param.pre_model_cfg.peak_a_model_cfg.model_enable =1;
AcceleratorModuleEnable(ACCE_PEAK_FILTER_A_MODEL_ID);
}else
{
ptr->image_acce_param.pre_model_cfg.peak_a_model_cfg.model_enable =0;
AcceleratorModuleDisable(ACCE_PEAK_FILTER_A_MODEL_ID);
}
}
void SetPeakFilterADDREnable(int flag,void *Pdata)
{
ImagepreprocessDlg *preDlg = (ImagepreprocessDlg*)Pdata;
AcceleratorModuleWriteDdrCfg(ACCE_PEAK_FILTER_A_MODEL_ID,preDlg->m_step,flag);
}
void ListPeakFilterADlg(int itaskKind,void *Pdata)
{
ImagepreprocessDlg *preDlg = (ImagepreprocessDlg*)Pdata;
PeakFilterDlg dlg;
dlg.m_task_id = preDlg->m_task_id;
dlg.m_step = preDlg->m_step;
dlg.m_pre_ptr = preDlg->m_pre_ptr;
dlg.m_SharpnessKind = PeakFilterDlg::SharpnessA;
dlg.m_listX = preDlg->m_listX;
dlg.m_listY = preDlg->m_listY;
dlg.InitData();
dlg.move(660,0);
dlg.exec();
}
//原图膨胀腐蚀B
void SetPeakFilterBEnable(int flag,void *Pdata)
{
ImagepreprocessDlg *preDlg = (ImagepreprocessDlg*)Pdata;
ACCE_MODEL *ptr = (ACCE_MODEL*)preDlg->m_pre_ptr;
if(ptr == NULL)
return;
if(flag == 1)
{
ptr->image_acce_param.pre_model_cfg.peak_b_model_cfg.model_enable =1;
AcceleratorModuleEnable(ACCE_PEAK_FILTER_B_MODEL_ID);
}else
{
ptr->image_acce_param.pre_model_cfg.peak_b_model_cfg.model_enable = 0;
AcceleratorModuleDisable(ACCE_PEAK_FILTER_B_MODEL_ID);
}
}
void SetPeakFilterBDDREnable(int flag,void *Pdata)
{
ImagepreprocessDlg *preDlg = (ImagepreprocessDlg*)Pdata;
AcceleratorModuleWriteDdrCfg(ACCE_PEAK_FILTER_B_MODEL_ID,preDlg->m_step,flag);
}
void ListPeakFilterBDlg(int itaskKind,void *Pdata)
{
ImagepreprocessDlg *preDlg = (ImagepreprocessDlg*)Pdata;
PeakFilterDlg dlg;
dlg.m_task_id = preDlg->m_task_id;
dlg.m_step = preDlg->m_step;
dlg.m_pre_ptr = preDlg->m_pre_ptr;
dlg.m_SharpnessKind = PeakFilterDlg::SharpnessB;
dlg.m_listX = preDlg->m_listX;
dlg.m_listY = preDlg->m_listY;
dlg.InitData();
dlg.move(660,0);
dlg.exec();
}
//实时浓淡补正
void ListShadingDlg(int itaskKind,void *Pdata)
{
ImagepreprocessDlg *preDlg = (ImagepreprocessDlg*)Pdata;
ShadingDialog dlg;
dlg.m_step_id = preDlg->m_step;
dlg.m_task_id= preDlg->m_task_id;
dlg.m_pre_ptr = preDlg->m_pre_ptr;
dlg.m_listX = preDlg->m_listX;
dlg.m_listY = preDlg->m_listY;
dlg.move(660,0);
dlg.IniData();
dlg.exec();
}
void SetShadingEnable(int flag,void *Pdata)
{
ImagepreprocessDlg *preDlg = (ImagepreprocessDlg*)Pdata;
ACCE_MODEL *ptr = (ACCE_MODEL*)preDlg->m_pre_ptr;
if(ptr == NULL)
return;
if(flag == 1)
{
ptr->image_acce_param.pre_model_cfg.shading_model_cfg.model_enable =1;
AcceleratorModuleEnable(ACCE_SHADING_MODEL_ID);
}else
{
ptr->image_acce_param.pre_model_cfg.shading_model_cfg.model_enable =0;
AcceleratorModuleDisable(ACCE_SHADING_MODEL_ID);
}
}
void SetShadingDDREnable(int flag,void *Pdata)
{
ImagepreprocessDlg *preDlg = (ImagepreprocessDlg*)Pdata;
AcceleratorModuleWriteDdrCfg(ACCE_SHADING_MODEL_ID,preDlg->m_step,flag);
}
void SetShadingSrcValue(int taskId,void *pData)
{
}
//缺陷提取
void ListDefectDlg(int itaskKind,void *Pdata)
{
ImagepreprocessDlg *preDlg = (ImagepreprocessDlg*)Pdata;
DefectDialog dlg;
dlg.m_step_id = preDlg->m_step;
dlg.m_task_id= preDlg->m_task_id;
dlg.m_pre_ptr = preDlg->m_pre_ptr;
dlg.m_listX = preDlg->m_listX;
dlg.m_listY = preDlg->m_listY;
dlg.move(660,0);
dlg.IniData();
dlg.exec();
}
void SetDefectEnable(int flag,void *Pdata)
{
ImagepreprocessDlg *preDlg = (ImagepreprocessDlg*)Pdata;
ACCE_MODEL *ptr = (ACCE_MODEL*)preDlg->m_pre_ptr;
if(ptr == NULL)
return;
if(flag == 1)
{
ptr->image_acce_param.pre_model_cfg.defect_model_cfg.model_enable =1;
AcceleratorModuleEnable(ACCE_DEFECT_MODEL_ID);
}else
{
ptr->image_acce_param.pre_model_cfg.defect_model_cfg.model_enable =0;
AcceleratorModuleDisable(ACCE_DEFECT_MODEL_ID);
}
}
void SetDefectDDREnable(int flag,void *Pdata)
{
ImagepreprocessDlg *preDlg = (ImagepreprocessDlg*)Pdata;
AcceleratorModuleWriteDdrCfg(ACCE_DEFECT_MODEL_ID,preDlg->m_step,flag);
}
void SetDefectSrcValue(int taskId,void *pData)
{
}
//模糊处理
void ListBlurDlg(int itaskKind,void *Pdata)
{
ImagepreprocessDlg *preDlg = (ImagepreprocessDlg*)Pdata;
BlurDialog dlg;
dlg.m_step = preDlg->m_step;
dlg.m_task_id= preDlg->m_task_id;
dlg.m_pre_ptr = preDlg->m_pre_ptr;
dlg.m_listX = preDlg->m_listX;
dlg.m_listY = preDlg->m_listY;
dlg.move(660,0);
dlg.InitData();
dlg.exec();
}
void SetBlurEnable(int flag,void *Pdata)
{
ImagepreprocessDlg *preDlg = (ImagepreprocessDlg*)Pdata;
ACCE_MODEL *ptr = (ACCE_MODEL*)preDlg->m_pre_ptr;
if(ptr == NULL)
return;
if(flag == 1)
{
ptr->image_acce_param.pre_model_cfg.blur_model_cfg.model_enable =1;
AcceleratorModuleEnable(ACCE_BLUR_MODEL_ID);
}else
{
ptr->image_acce_param.pre_model_cfg.blur_model_cfg.model_enable =0;
AcceleratorModuleDisable(ACCE_BLUR_MODEL_ID);
}
}
void SetBlurDDREnable(int flag,void *Pdata)
{
ImagepreprocessDlg *preDlg = (ImagepreprocessDlg*)Pdata;
AcceleratorModuleWriteDdrCfg(ACCE_BLUR_MODEL_ID,preDlg->m_step,flag);
}
void SetBlurSrcValue(int taskId,void *pData)
{
}
ImagepreprocessDlg::ImagepreprocessDlg(QWidget *parent) :
QDialog(parent),
ui(new Ui::ImagepreprocessDlg)
{
ui->setupUi(this);
m_listX = ui->labelPic->x();
m_listY = ui->labelPic->y();
IniDefalutPattern();
InitFunPtr();
}
ImagepreprocessDlg::~ImagepreprocessDlg()
{
delete ui;
}
void ImagepreprocessDlg::InitFunPtr()
{
STRUCT_FUN_PTR blurMode;
blurMode.List_model_dlg=ListBlurDlg;
blurMode.Set_ddr_enable=SetBlurDDREnable;
blurMode.Set_model_enable = SetBlurEnable;
m_fun_ptr.insert(ACCE_BLUR_MODEL_ID,blurMode);
STRUCT_FUN_PTR gaussMode;
gaussMode.List_model_dlg=ListGaussDlg;
gaussMode.Set_ddr_enable=SetGaussDDREnable;
gaussMode.Set_model_enable = SetGaussEnable;
m_fun_ptr.insert(ACCE_GAUSS_FILTER_ID,gaussMode);
STRUCT_FUN_PTR contrastStrengthenMode;
contrastStrengthenMode.List_model_dlg=ListContrastStrengthenDlg;
contrastStrengthenMode.Set_ddr_enable=SetContrastStrengthenDDREnable;
contrastStrengthenMode.Set_model_enable = SetContrastStrengthenEnable;
m_fun_ptr.insert(ACCE_BALANCE_MODEL_ID,contrastStrengthenMode);
STRUCT_FUN_PTR contrastSwitchMode;
contrastSwitchMode.List_model_dlg=ListContrastSwitchDlg;
contrastSwitchMode.Set_ddr_enable=SetContrastSwitchDDREnable;
contrastSwitchMode.Set_model_enable = SetContrastSwitchEnable;
m_fun_ptr.insert(ACCE_CONTRAST_MODEL_ID,contrastSwitchMode);
STRUCT_FUN_PTR sharpness; //边缘强调
sharpness.List_model_dlg=ListSharpnessDlg;
sharpness.Set_ddr_enable=SetSharpnessDDREnable;
sharpness.Set_model_enable = SetSharpnessEnable;
m_fun_ptr.insert(ACCE_SHARPNESS_MODEL_ID,sharpness);
STRUCT_FUN_PTR peakFilterA; //原图膨胀腐蚀a
peakFilterA.List_model_dlg=ListPeakFilterADlg;
peakFilterA.Set_ddr_enable=SetPeakFilterADDREnable;
peakFilterA.Set_model_enable = SetPeakFilterAEnable;
m_fun_ptr.insert(ACCE_PEAK_FILTER_A_MODEL_ID,peakFilterA);
STRUCT_FUN_PTR peakFilterB; //原图膨胀腐蚀b
peakFilterB.List_model_dlg=ListPeakFilterBDlg;
peakFilterB.Set_ddr_enable=SetPeakFilterBDDREnable;
peakFilterB.Set_model_enable = SetPeakFilterBEnable;
m_fun_ptr.insert(ACCE_PEAK_FILTER_B_MODEL_ID,peakFilterB);
STRUCT_FUN_PTR shadingMode;
shadingMode.List_model_dlg=ListShadingDlg;
shadingMode.Set_ddr_enable=SetShadingDDREnable;
shadingMode.Set_model_enable =SetShadingEnable;
shadingMode.SetPicSrc = SetShadingSrcValue;
m_fun_ptr.insert(ACCE_SHADING_MODEL_ID,shadingMode);
STRUCT_FUN_PTR defectMode;
defectMode.List_model_dlg=ListDefectDlg;
defectMode.Set_ddr_enable=SetDefectDDREnable;
defectMode.Set_model_enable =SetDefectEnable;
defectMode.SetPicSrc = SetDefectSrcValue;
m_fun_ptr.insert(ACCE_DEFECT_MODEL_ID,defectMode);
}
void ImagepreprocessDlg::IniDefalutPattern()
{
int width = ui->listWidgetPattern->width();
int height = 50;
ui->listWidgetPattern->addItem("默认模式1");
ui->listWidgetPattern->addItem("默认模式2");
ui->listWidgetPattern->addItem("默认模式3");
for (int i=0;i<ui->listWidgetPattern->count();i++)
{
QListWidgetItem * pItem = ui->listWidgetPattern->item(i);
pItem->setSizeHint(QSize(width,height));
}
}
void ImagepreprocessDlg::ClearList(QListWidget *pListWidget)
{
int count = pListWidget->count();
for(int i= 0; i<count;i++)
{
int row = pListWidget->count()-1;
QListWidgetItem *itemdel= pListWidget->takeItem(row);
delete itemdel;
}
}
void ImagepreprocessDlg::on_listWidgetPattern_clicked(const QModelIndex &index)
{
ACCE_MODEL *ptr = (ACCE_MODEL*)m_pre_ptr;
if(ptr != NULL)
{
int iRow = index.row();
switch (iRow) {
case 0:
DefalutOne();
ptr->image_acce_param.pre_model_cfg.pipeline_mode_sel = 0;
AcceleratorModuleConfig(ACCE_PRE_MODEL_ID,m_step);
break;
case 1:
DefalutTwo();
ptr->image_acce_param.pre_model_cfg.pipeline_mode_sel = 1;
AcceleratorModuleConfig(ACCE_PRE_MODEL_ID,m_step);
break;
case 2:
DefalutThree();
ptr->image_acce_param.pre_model_cfg.pipeline_mode_sel = 2;
AcceleratorModuleConfig(ACCE_PRE_MODEL_ID,m_step);
break;
case 3:
break;
case 4:
break;
default:
break;
}
GetImageOutPut();
ListInformation("设定适用于图像预处理种类,指定了复数个种类,以从上往下的方式进行处理");
}
}
void ImagepreprocessDlg::DefalutOne()
{
ClearList(ui->listWidget);
ACCE_MODEL *ptr = (ACCE_MODEL*)m_pre_ptr;
if(ptr == NULL)
return;
AddItemData(tr("模糊处理"),ACCE_BLUR_MODEL_ID,ptr->image_acce_param.pre_model_cfg.blur_model_cfg.model_enable,0);
m_fun_ptr.value(ACCE_BLUR_MODEL_ID).Set_model_enable(ptr->image_acce_param.pre_model_cfg.blur_model_cfg.model_enable,this);
AddItemData(tr("高斯滤波"),ACCE_GAUSS_FILTER_ID,ptr->image_acce_param.pre_model_cfg.gauss_model_cfg.model_enable,1);
m_fun_ptr.value(ACCE_GAUSS_FILTER_ID).Set_model_enable(ptr->image_acce_param.pre_model_cfg.gauss_model_cfg.model_enable,this);
AddItemData(tr("对比度增强"),ACCE_BALANCE_MODEL_ID,ptr->image_acce_param.pre_model_cfg.balance_model_cfg.model_enable,2);
m_fun_ptr.value(ACCE_BALANCE_MODEL_ID).Set_model_enable(ptr->image_acce_param.pre_model_cfg.balance_model_cfg.model_enable,this);
AddItemData(tr("对比度转换"),ACCE_CONTRAST_MODEL_ID,ptr->image_acce_param.pre_model_cfg.contrast_model_cfg.model_enable,3);
m_fun_ptr.value(ACCE_CONTRAST_MODEL_ID).Set_model_enable(ptr->image_acce_param.pre_model_cfg.contrast_model_cfg.model_enable,this);
AddItemData(tr("边缘强调"),ACCE_SHARPNESS_MODEL_ID,ptr->image_acce_param.pre_model_cfg.sharpness_model_cfg.model_enable,4);
m_fun_ptr.value(ACCE_SHARPNESS_MODEL_ID).Set_model_enable(ptr->image_acce_param.pre_model_cfg.sharpness_model_cfg.model_enable,this);
AddItemData(tr("原图膨胀腐蚀A"),ACCE_PEAK_FILTER_A_MODEL_ID,ptr->image_acce_param.pre_model_cfg.peak_a_model_cfg.model_enable,5);
m_fun_ptr.value(ACCE_PEAK_FILTER_A_MODEL_ID).Set_model_enable(ptr->image_acce_param.pre_model_cfg.peak_a_model_cfg.model_enable,this);
AddItemData(tr("原图膨胀腐蚀B"),ACCE_PEAK_FILTER_B_MODEL_ID,ptr->image_acce_param.pre_model_cfg.peak_b_model_cfg.model_enable,6);
m_fun_ptr.value(ACCE_PEAK_FILTER_B_MODEL_ID).Set_model_enable(ptr->image_acce_param.pre_model_cfg.peak_b_model_cfg.model_enable,this);
}
void ImagepreprocessDlg::DefalutTwo()
{
ClearList(ui->listWidget);
ACCE_MODEL *ptr = (ACCE_MODEL*)m_pre_ptr;
if(ptr == NULL)
return;
AddItemData(tr("高斯滤波"),ACCE_GAUSS_FILTER_ID,ptr->image_acce_param.pre_model_cfg.gauss_model_cfg.model_enable,0);
m_fun_ptr.value(ACCE_GAUSS_FILTER_ID).Set_model_enable(ptr->image_acce_param.pre_model_cfg.gauss_model_cfg.model_enable,this);
AddItemData(tr("对比度增强"),ACCE_BALANCE_MODEL_ID,ptr->image_acce_param.pre_model_cfg.balance_model_cfg.model_enable,1);
m_fun_ptr.value(ACCE_BALANCE_MODEL_ID).Set_model_enable(ptr->image_acce_param.pre_model_cfg.balance_model_cfg.model_enable,this);
AddItemData(tr("对比度转换"),ACCE_CONTRAST_MODEL_ID,ptr->image_acce_param.pre_model_cfg.contrast_model_cfg.model_enable,2);
m_fun_ptr.value(ACCE_CONTRAST_MODEL_ID).Set_model_enable(ptr->image_acce_param.pre_model_cfg.contrast_model_cfg.model_enable,this);
AddItemData(tr("缺陷提取"),ACCE_DEFECT_MODEL_ID,ptr->image_acce_param.pre_model_cfg.defect_model_cfg.model_enable,3);
m_fun_ptr.value(ACCE_DEFECT_MODEL_ID).Set_model_enable(ptr->image_acce_param.pre_model_cfg.defect_model_cfg.model_enable,this);
}
void ImagepreprocessDlg::DefalutThree()
{
ClearList(ui->listWidget);
ACCE_MODEL *ptr = (ACCE_MODEL*)m_pre_ptr;
if(ptr == NULL)
return;
AddItemData(tr("高斯滤波"),ACCE_GAUSS_FILTER_ID,ptr->image_acce_param.pre_model_cfg.gauss_model_cfg.model_enable,0);
m_fun_ptr.value(ACCE_GAUSS_FILTER_ID).Set_model_enable(ptr->image_acce_param.pre_model_cfg.gauss_model_cfg.model_enable,this);
AddItemData(tr("对比度转换"),ACCE_CONTRAST_MODEL_ID,ptr->image_acce_param.pre_model_cfg.contrast_model_cfg.model_enable,1);
m_fun_ptr.value(ACCE_CONTRAST_MODEL_ID).Set_model_enable(ptr->image_acce_param.pre_model_cfg.contrast_model_cfg.model_enable,this);
AddItemData(tr("对比度增强"),ACCE_BALANCE_MODEL_ID,ptr->image_acce_param.pre_model_cfg.balance_model_cfg.model_enable,2);
m_fun_ptr.value(ACCE_BALANCE_MODEL_ID).Set_model_enable(ptr->image_acce_param.pre_model_cfg.balance_model_cfg.model_enable,this);
AddItemData(tr("实时浓淡补正"),ACCE_SHADING_MODEL_ID,ptr->image_acce_param.pre_model_cfg.shading_model_cfg.model_enable,3);
m_fun_ptr.value(ACCE_SHADING_MODEL_ID).Set_model_enable(ptr->image_acce_param.pre_model_cfg.shading_model_cfg.model_enable,this);
}
void ImagepreprocessDlg::AddItemData(QString strName,int index,int bCheck,int current)
{
PretreatmentModuleItem *p_PretreatmentModuleItem = new PretreatmentModuleItem;
p_PretreatmentModuleItem->setAttribute(Qt::WA_DeleteOnClose);
p_PretreatmentModuleItem->SetInfoName(strName);
p_PretreatmentModuleItem->m_taskKind = index;
p_PretreatmentModuleItem->m_current_row = current;
p_PretreatmentModuleItem->SetCheckdevalue(bCheck);
int size =ui->listWidget->count();
QListWidgetItem* mItem = new QListWidgetItem(ui->listWidget);
ui->listWidget->setItemWidget(mItem,(QWidget*)p_PretreatmentModuleItem);
ui->listWidget->item(size)->setSizeHint(QSize(340,50));
ui->listWidget->setCurrentRow(size);
connect(p_PretreatmentModuleItem,&PretreatmentModuleItem::SignalOperate,this,&ImagepreprocessDlg::OperateSlots);
}
void ImagepreprocessDlg::OperateSlots(int iOperate, int itaskKind, int value, int current)
{
ui->listWidget->setCurrentRow(current);
switch (iOperate) {
case PREENABLE:
m_fun_ptr.value(itaskKind).Set_model_enable(value,this);
break;
case PREDETAIL:
m_fun_ptr.value(itaskKind).List_model_dlg(itaskKind,this);
break;
default:
break;
}
GetImageOutPut();
ListInformation(GetInfoByTaskID(itaskKind));
}
int ImagepreprocessDlg::GetImageOutPut()
{
Pre_Model_Out_Src_Auto_Set(m_step);
ACCE_MODEL *ptr = (ACCE_MODEL*)m_pre_ptr;
if(ptr !=NULL)
ptr->image_acce_param.vga_model_cfg.vga_pic_src_sel = ACCE_PRE_MODEL_ID;
AcceleratorModuleConfig(ACCE_VGA_MODEL_ID,m_step);
UtilitiesFun::Instance()->ListVGA(ui->labelPic->x(),ui->labelPic->y(),0xffffffff);
return 0;
int count = ui->listWidget->count();
for(int i = 0; i<count;i++)
{
QListWidgetItem *item = ui->listWidget->item(count-i-1);
QWidget *qWidget = ui->listWidget->itemWidget(item);
QString strName= ((PretreatmentModuleItem*)qWidget)->GetInfoName();
int bChecek =((PretreatmentModuleItem*)qWidget)->GetCheckedValue();
int taskIndex= ((PretreatmentModuleItem*)qWidget)->m_taskKind;
if(bChecek == 1)
{
m_image_out_src = taskIndex;
ACCE_MODEL *ptr = (ACCE_MODEL*)m_pre_ptr;
if(ptr !=NULL)
{
//ptr->image_acce_param.pre_model_cfg.pre_wr_ddr_en =1;
ptr->image_acce_param.pre_model_cfg.pre_src_out_sel = m_image_out_src;
qDebug()<<"m_image_out_src==="<<m_image_out_src;
ptr->image_acce_param.vga_model_cfg.vga_pic_src_sel = ACCE_PRE_MODEL_ID;
AcceleratorModuleConfig(ACCE_PRE_MODEL_ID,m_step);
AcceleratorModuleConfig(ACCE_VGA_MODEL_ID,m_step);
AcceleratorModuleWriteDdrCfg(ACCE_PRE_MODEL_ID,m_step,1);
//AcceleratorModuleEnable(ACCE_PRE_MODEL_ID);
}
UtilitiesFun::Instance()->ListVGA(ui->labelPic->x(),ui->labelPic->y(),0xffffffff);
break;
}
}
return m_image_out_src;
}
void ImagepreprocessDlg::on_btnOk_clicked()
{
ACCE_MODEL *ptr = (ACCE_MODEL*)m_pre_ptr;
if(ptr != NULL)
{
int row = ui->listWidgetPattern->currentRow();
switch (row) {
case 0:
ptr->image_acce_param.pre_model_cfg.pipeline_mode_sel = 0;
break;
case 1:
ptr->image_acce_param.pre_model_cfg.pipeline_mode_sel = 1;
break;
case 2:
ptr->image_acce_param.pre_model_cfg.pipeline_mode_sel = 2;
break;
default:
break;
}
AcceleratorModuleConfig(ACCE_PRE_MODEL_ID,m_step);
}
QDialog::accept();
}
void ImagepreprocessDlg::on_btnQuit_clicked()
{
QMessageBox::StandardButton rb = QMessageBox::warning(NULL, tr("提示"),tr("编辑未完成,确定退出!"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
if(rb == QMessageBox::Yes)
{
ACCE_MODEL *ptr = (ACCE_MODEL*)m_pre_ptr;
if(ptr != NULL)
{
ptr->image_acce_param.pre_model_cfg= m_cfg;
AcceleratorModuleConfig(ACCE_PRE_MODEL_ID,m_step);
}
QDialog::reject();
}
}
void ImagepreprocessDlg::IniData()
{
ACCE_MODEL *ptr = (ACCE_MODEL*)m_pre_ptr;
if(ptr != NULL)
{
m_cfg = ptr->image_acce_param.pre_model_cfg;
int iLineMode = ptr->image_acce_param.pre_model_cfg.pipeline_mode_sel;
qDebug()<<"ptr->image_acce_param.pre_model_cfg.pipeline_mode_sel="<<ptr->image_acce_param.pre_model_cfg.pipeline_mode_sel;
switch (iLineMode) {
case 0:
DefalutOne();
ui->listWidgetPattern->setCurrentRow(0);
break;
case 1:
DefalutTwo();
ui->listWidgetPattern->setCurrentRow(1);
break;
case 2:
DefalutThree();
ui->listWidgetPattern->setCurrentRow(2);
break;
default:
break;
}
GetImageOutPut();
}
ListInformation("设定适用于图像预处理种类,指定了复数个种类,以从上往下的方式进行处理");
}
void ImagepreprocessDlg::ListInformation(QString strInfo)
{
ui->txtInfo->clear();
ui->txtInfo->append(strInfo);
}
QString ImagepreprocessDlg::GetInfoByTaskID(int taskId)
{
QString strRet = "";
switch (taskId) {
case ACCE_BLUR_MODEL_ID: //模糊处理
strRet = "模糊图像后进行平滑处理,可达到排除干扰的目的.另外,当检测对象内存在复数个块状物时,通过该处理,可以将块状物连接在一起,使检测达到稳定化的效果。";
break;
case ACCE_GAUSS_FILTER_ID: //< 5*5卷积(高斯)滤波模块
strRet = "高斯滤波是一种线性平滑滤波,适用于消除高斯噪声,应用于图像处理的减噪过程。";
break;
case ACCE_BALANCE_MODEL_ID: //均衡直方图模块
strRet = "对比度增强并不以图像保真为准则,而是有选择地突出某些对人或机器分析有意义的信息,抑制无用信息,提高图像的使用价值。";
break;
case ACCE_CONTRAST_MODEL_ID: //对比度转换模块
strRet = "进行增益调整。调整图像的明暗和浓淡变化的倾斜。";
break;
case ACCE_SHARPNESS_MODEL_ID: //边缘强调模块
strRet = "图像锐化功能,用于增强图像锐利度。";
break;
case ACCE_PEAK_FILTER_A_MODEL_ID: //原图腐蚀膨胀A模块
strRet = "腐蚀是用来消除边界点,使边界向内部收缩的过程,可以用来消除小且无意义的物体,膨胀是将与物体接触的所有背景点合并到该物体中,使边界向外部扩张的过程,可以用来填补物体中的空洞。";
break;
case ACCE_PEAK_FILTER_B_MODEL_ID: //原图腐蚀膨胀B模块
strRet = "腐蚀是用来消除边界点,使边界向内部收缩的过程,可以用来消除小且无意义的物体,膨胀是将与物体接触的所有背景点合并到该物体中,使边界向外部扩张的过程,可以用来填补物体中的空洞。";
break;
case ACCE_DEFECT_MODEL_ID: //缺陷提取模块
strRet = "用于提取均匀背景下的缺陷。";
break;
case ACCE_SHADING_MODEL_ID: //实时浓淡补正模块
strRet = "排除背景的浓淡渐变,只抽取对比度较大的部分。另外,还能使用检测范围内的浓度平均值及中间值,对图像整体的对比度进行平均补正。";
break;
default:
break;
}
return strRet;
}
void ImagepreprocessDlg::on_listWidget_clicked(const QModelIndex &index)
{
int iRow = index.row();
if(iRow >=0)
{
QListWidgetItem *item = ui->listWidget->item(iRow);
QWidget *qWidget = ui->listWidget->itemWidget(item);
int itaskKind= ((PretreatmentModuleItem*)qWidget)->m_taskKind;
ListInformation(GetInfoByTaskID(itaskKind));
}
}
| [
"1245552661@qq.com"
] | 1245552661@qq.com |
1536aaba21301c6e472e54eab461286d14baff8d | 743fcba88e8f50e5d87456da40be1a94bd6c218b | /application/test/test_neural_network/neural_network_application.cpp | 5e4eeb5e125365f7ea2aa494451506efcbd4a369 | [] | no_license | rohingosling/common_cpp | 3be1d1d92e857baf22650158046837c390034c62 | 833ca4fa57f5ca473a718e9116ea6c4f9d1cf0ef | refs/heads/master | 2020-05-21T04:21:02.191195 | 2017-07-14T15:04:40 | 2017-07-14T15:04:40 | 66,406,136 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,724 | cpp | //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Project: Entelect 100k Challenge.
// Application: Neural Network test application.
// Class: TestApplication
// Version: 1.0
// Date: 2015
// Author: Rohin Gosling
//
// Description:
//
// Test class, used to test the NeuralNetwork class.
//
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
#include "stdafx.h"
#include "neural_network_application.h"
#include "static_utility.h"
#include "neural_network.h"
#include "stop_clock.h"
#include <iostream>
#include <string>
#include <iomanip>
#include <chrono>
using namespace std;
using namespace std::chrono; // We will be using some timming functions for measurement.
using namespace common;
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Constructor 1/1
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
NeuralNetworkApplication::NeuralNetworkApplication ( int argc, char* argv [] ) : ConsoleApplication { argc, argv }
{
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Destructor
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
NeuralNetworkApplication::~NeuralNetworkApplication ()
{
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// FUNCTION:
//
// - ExecuteCommandInterpreter
//
// DESCRIPTION:
//
// - Execute commands passed in through the command line.
//
// - ExecuteCommandInterpreter should be overloaded in a derived class, and not
// called directly.
//
// 1. Extend ConsoleApplication.
// 2. Overload ExecuteCommandInterpreter() to implement commands.
// 3. Call an instance of the derived class in Main.cpp.
//
// ARGUMENTS:
//
// - N/A
//
// RETURN VALUE:
//
// - N/A.
//
// PRE-CONDITIONS:
//
// - N/A
//
// POST-CONDITIONS:
//
// - The apropriate commands, as defined in a derived class, have been executed.
//
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
void NeuralNetworkApplication::command_interpreter ( vector <string> command_line )
{
// Declare local variables.
int test_case = 1;
// Get the number of arguments on the command line, including the command it's self.
int argument_count { (int) command_line.size () };
int argument_index { 0 };
// Execute commands.
switch ( argument_count )
{
case 1:
switch ( test_case )
{
case 0: command_main_program (); break;
case 1: command_test_1 (); break; // Test 2D vector element ordering for weight amtrix.
case 2: command_test_2 (); break; // Test Layer.
case 3: command_test_3 (); break;
case 4: command_test_4 (); break; // Layer level boolean function test. OR and AND.
case 5: command_test_5 (); break; // NeuralNetwork test 1.
}
break;
case 2:
break;
default:
break;
}
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
void NeuralNetworkApplication::command_main_program ()
{
print_program_info ( C_PROGRAM_INFO_NA, C_PROGRAM_INFO_NA, "Main program" );
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// FUNCTION:
//
// - command_test_1
//
// DESCRIPTION:
//
// - Test 2D array managment code.
// - We are not testing any of the actual NeuralNetwork or NeuralNetworkLayer functions here.
//
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
void NeuralNetworkApplication::command_test_1 ()
{
// Declare local variables.
vector <vector <int>> layer;
int input_unit_count = 8;
int output_unit_count = 4;
int input_unit_index = 0;
int initial_value = 0;
// Initialize network layer.
layer.resize ( output_unit_count, vector<int> ( input_unit_count, initial_value ) );
// Print network.
cout << "\nInputs:\t\t";
for ( int i=0; i < input_unit_count; i++ ) cout << i << "\t";
cout << "\n\t\t";
for ( int i=0; i < input_unit_count; i++ ) cout << "-" << "\t";
cout << "\n\n\n";
input_unit_index = 0;
for ( vector<int> v : layer )
{
cout << "Output " << input_unit_index << "|\t";
for ( int i : v ) cout << i << "\t";
cout << "\n\n";
++input_unit_index;
}
cout << "\n";
// Set some values.
layer [ 1 ][ 2 ] = 100;
// Print network.
cout << "\nInputs:\t\t";
for ( int i=0; i < input_unit_count; i++ ) cout << i << "\t";
cout << "\n\t\t";
for ( int i=0; i < input_unit_count; i++ ) cout << "-" << "\t";
cout << "\n\n\n";
input_unit_index = 0;
for ( vector<int> v : layer )
{
cout << "Output " << input_unit_index << "|\t";
for ( int i : v ) cout << i << "\t";
cout << "\n\n";
++input_unit_index;
}
cout << "\n";
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// FUNCTION:
//
// - command_test_2
//
// DESCRIPTION:
//
// - Testing analysis functions in the NeuralNetworkLayer class.
// - Test file output functions.
//
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
void NeuralNetworkApplication::command_test_2 ()
{
#if 0
// Declare local variables.
NeuralNetworkLayer ann_layer { 8, 8 };
string file_path { "R:\\Projects\\common\\machine_learning\\cpp\\neural_network\\Debug\\Output\\" };
string file_name_0 { "test_file_0.dsv" };
string file_name_1 { "test_file_1.csv" };
string file_name_2 { "test_file_2.tsv" };
string file_name_3 { "test_file_3.txt" };
string file_name_4 { "test_file_uint8.bin" };
string s;
int precision { 3 };
bool header_row_enabled { true };
bool activation_function_enabled { true };
char delimiter { ',' };
// Initialize layer parameters.
ann_layer.set_bias_vector ( 0.0 );
ann_layer.randomize_weights ( 0.0, 1.0 );
s += ann_layer.to_string ( precision, header_row_enabled, activation_function_enabled );
cout << s;
// Test analsys functions.
cout << endl;
for ( int normal_index = 0; normal_index < ann_layer.output_vector_size; normal_index++ )
{
cout << "Sum ( Unit Normal [" << normal_index << "] ) = " << ann_layer.unit_normal_sum ( normal_index ) << endl;
}
cout << endl << "Sum ( units ) = " << ann_layer.layer_normal_sum () << endl;
cout << endl << "Output Vector Size = " << ann_layer.output_vector.size() << endl;
// Test file saving.
ann_layer.save_to_dsv ( file_path + file_name_0, delimiter, precision, header_row_enabled );
ann_layer.save_to_csv ( file_path + file_name_1 );
ann_layer.save_to_tsv ( file_path + file_name_2 );
ann_layer.save_to_txt ( file_path + file_name_3, 4, true );
ann_layer.save_to_bin_uint8 ( file_path + file_name_4 );
#endif
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// FUNCTION:
//
// - command_test_3
//
// DESCRIPTION:
//
// - Test the compute_layer function.
//
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
void NeuralNetworkApplication::command_test_3 ()
{
#if 0
// Display test info.
cout << endl << "TEST FUNCTION: command_test_3" << endl << endl;
// Declare local variables.
string s;
int precision { 5 };
bool header_row_enabled { true };
bool activation_function_enabled { true };
char delimiter { ',' };
// Initialize layer.
int input_unit_count { 3 };
int output_unit_count { 2 };
NeuralNetworkLayer ann_layer { input_unit_count, output_unit_count };
ann_layer.activation_function_type = NeuralNetworkLayer::ActivationFunctionType::TANH;
ann_layer.set_bias_vector ( 0.0 );
//ann_layer.set_weights ( 0.0 );
ann_layer.randomize_weights ( -0.5, 0.5 );
// Display layer data to console.
s += ann_layer.to_string ( precision, header_row_enabled, activation_function_enabled );
cout << s << endl;
// Initialize layer input and output.
vector <double> x { -1.0, 0.0, 1.0 };
vector <double> y ( output_unit_count );
// Test layer computation.
y = ann_layer.compute_layer ( x );
// Display input and output.
print_vector ( x, precision, "Input Vector:", "x" );
print_vector ( y, precision, "Output Vector:", "y" );
#endif
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// FUNCTION:
//
// - command_test_4
//
// DESCRIPTION:
//
// - Layer level boolean function test.
// y = OR ( x0, x1 )
// y = AND ( x0, x1 )
//
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
void NeuralNetworkApplication::command_test_4 ()
{
#if 0
// Display test info.
cout << endl;
cout << "TEST FUNCTION: command_test_4" << endl;
cout << "DESCRIPTION: Boolean function test." << endl;
cout << endl;
cout << "Perceptron:" << endl;
cout << endl;
// Declare local variables.
string s;
int precision { 3 };
bool header_row_enabled { true };
bool activation_function_enabled { true };
char delimiter { ',' };
// Initialize number of input and output units.
int input_unit_count { 2 };
int output_unit_count { 1 };
NeuralNetworkLayer ann_layer { input_unit_count, output_unit_count };
ann_layer.activation_function_type = NeuralNetworkLayer::ActivationFunctionType::QUADRATIC;
ann_layer.set_bias_vector ( 0.0 );
ann_layer.set_weights ( 0.0 );
// Manualy program weight vector/s.
//
// - Perceptron weights and bias to implement an AND gate.
// w0 = 0.5
// w1 = 0.5
// b = -0.8
//
// - Perceptron weights and bias to implement an OR gate.
// w0 = 0.5
// w1 = 0.5
// b = -0.3
vector<double> weight_vector { 0.5, 0.5 };
int output_unit_index { 0 };
ann_layer.weight_vectors [ output_unit_index ] = weight_vector;
ann_layer.set_bias_vector ( -0.3 );
// Display layer data to console.
s += ann_layer.to_string ( precision, header_row_enabled, activation_function_enabled );
cout << s << endl;
// Initialize layer input and output.
vector <double> x { 1.0, 0.0 };
vector <double> y { 0.0 };
// Test layer computation.
y = ann_layer.compute_layer ( x );
// Display input and output.
print_vector ( x, precision, "Input Vector:", "x" );
print_vector ( y, precision, "Output Vector:", "y" );
#endif
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// FUNCTION:
//
// - command_test_4
//
// DESCRIPTION:
//
// - Layer level boolean function test.
// y = OR ( x0, x1 )
// y = AND ( x0, x1 )
//
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
#define TIME_START time_point_cast <milliseconds> ( time_start ).time_since_epoch().count()
#define TIME_STOP time_point_cast <milliseconds> ( steady_clock::now () ).time_since_epoch().count()
void NeuralNetworkApplication::command_test_5 ()
{
#if 0
// Define local constants.
const string LOG_SYSTEM = "SYSTEM: ";
const string LOG_TAB = " ";
// Initialize clock.
steady_clock::time_point time_start = steady_clock::now ();
// Display test info.
cout << endl;
cout << "TEST FUNCTION: command_test_5" << endl;
cout << "DESCRIPTION: NeuralNetwork Class Test 1.0." << endl;
cout << endl;
// Declare local display variables.
string s;
int precision { 3 };
bool header_row_enabled { true };
bool activation_function_enabled { true };
// Initialize neural network.
cout << log_to_string ( TIME_START, TIME_STOP, LOG_SYSTEM + "Building neural netowrk." ) << endl;
vector<int> network_architecture { 2, 2, 1 };
NeuralNetwork ann { network_architecture };
cout << log_to_string ( TIME_START, TIME_STOP, LOG_SYSTEM + "Neural netowrk ready." ) << endl;
cout << log_to_string ( TIME_START, TIME_STOP, LOG_SYSTEM + "Initializing neural netowrk." ) << endl;
if ( 0 ) ann.set_bias_vectors ( 0.0 );
if ( 0 ) ann.set_weights ( 0.0 );
if ( 0 ) ann.randomize_weights ( -0.5, 0.5 );
if ( 0 ) ann.randomize_bias_vectors ( -0.5, 0.5 );
if ( 1 ) ann.neural_network [0].activation_function_type = NeuralNetworkLayer::ActivationFunctionType::STEP;
if ( 1 ) ann.neural_network [1].activation_function_type = NeuralNetworkLayer::ActivationFunctionType::STEP;
cout << log_to_string ( TIME_START, TIME_STOP, LOG_SYSTEM + "Neural netowrk initialized." ) << endl;
// Train neural netowrk
cout << log_to_string ( TIME_START, TIME_STOP, LOG_SYSTEM + "Training neural netowrk." ) << endl;
vector<vector<vector<double>>> weight { { { 1.0, 1.0 }, { 1.0, 1.0 } }, { { 1.0, -1.0 } } };
vector<vector<double>> bias { { 0.5, 1.5 }, { 0.5 } };
ann.neural_network [ 0 ].weight_vectors = weight [ 0 ];
ann.neural_network [ 1 ].weight_vectors = weight [ 1 ];
ann.neural_network [ 0 ].bias_vector = bias [ 0 ];
ann.neural_network [ 1 ].bias_vector = bias [ 1 ];
cout << log_to_string ( TIME_START, TIME_STOP, LOG_SYSTEM + "Neural netowrk trained." ) << endl;
// Initialize input and output vectors.
cout << log_to_string ( TIME_START, TIME_STOP, LOG_SYSTEM + "Initializing input and output vectors." ) << endl;
vector<double> x { 0, 0 };
vector<double> y { 0 };
if (0) for ( int i=0; i < network_architecture [ 0 ]; i++ ) x.push_back ( 0.0 );
if (0) for ( int i=0; i < network_architecture [ 1 ]; i++ ) y.push_back ( 0.0 );
cout << log_to_string ( TIME_START, TIME_STOP, LOG_SYSTEM + "Input and output vectors initialized." ) << endl;
// Test neural network.
cout << log_to_string ( TIME_START, TIME_STOP, LOG_SYSTEM + "Computing network (Feed forward execution)." ) << endl;
y = ann.compute_network ( x );
cout << log_to_string ( TIME_START, TIME_STOP, LOG_SYSTEM + "Network computation complete." ) << endl;
// Display layer data to console.
#if 1
cout << log_to_string ( TIME_START, TIME_STOP, LOG_SYSTEM + "Compiling neural network display string." ) << endl;
s += ann.to_string ( precision, activation_function_enabled, header_row_enabled );
cout << log_to_string ( TIME_START, TIME_STOP, LOG_SYSTEM + "Display string ready." ) << endl;
// Display input and output.
cout << endl;
print_vector ( x, precision, "Input Vector:", "x" );
print_vector ( y, precision, "Output Vector:", "y" );
// Display neural network data.
cout << endl << "Neural Network:" << endl << endl;
cout << "\ts.size() = " << s.size()/1048576.0 << " MB" << endl;
cout << "\ts.size() = " << s.size()/1024.0 << " KB" << endl;
cout << "\ts.size() = " << s.size() << " B" << endl;
cout << endl;
cout << s << endl;
#endif
#endif
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//print_program_info
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Overload 1/2
void NeuralNetworkApplication::print_program_info ()
{
print_program_info ( C_PROGRAM_INFO_NA, C_PROGRAM_INFO_NA, C_PROGRAM_INFO_NA );
}
// Overload 2/2
void NeuralNetworkApplication::print_program_info ( string class_name, string function_name, string description )
{
cout << endl;
cout << C_PROGRAM_INFO_PROJECT << endl;
cout << C_PROGRAM_INFO_PROGRAM << endl;
cout << C_PROGRAM_INFO_VERSION << endl;
cout << C_PROGRAM_INFO_DATE << endl;
cout << C_PROGRAM_INFO_AUTHOR << endl;
if ( class_name.length () > 0 ) cout << C_PROGRAM_INFO_CLASS << class_name << endl;
if ( function_name.length () > 0 ) cout << C_PROGRAM_INFO_FUNCTION << function_name << endl;
if ( description.length () > 0 ) cout << C_PROGRAM_INFO_DESCRIPTION << description << endl;
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// print_vector
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
void NeuralNetworkApplication::print_vector ( vector <double> v, int precision, string label, string vector_name )
{
// Define lambdas
auto new_line = [] () { cout << endl; };
// Initialize local variables.
string element_value_string;
int width { precision + 3 }; // We add 3, for the sign, one decimal unit, and a decimal point.
// Print the vector label.
cout << label << endl;
new_line ();
// Print out the vector data to the console.
for ( int index = 0; index < (signed) v.size(); index++ )
{
element_value_string = StaticUtility::to_aligned_string ( v [ index ], precision, width, StaticUtility::ALIGN_RIGHT );
cout << setw ( 5 ) << setprecision ( 5 ) << fixed;
cout << vector_name << "[" << index << "] = " << element_value_string << endl;
}
new_line ();
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// log
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
string NeuralNetworkApplication::log_to_string ( long long time_point, long long time_stop, string message )
{
// Compute elapsed time.
long long elappsed_time = time_stop - time_point;
// Compile log string.
string s_time { StopClock::time_to_string ( elappsed_time ) };
string s_log { s_time + " " + message };
// Return string to caller.
return s_log;
}
| [
"rohingosling@gmail.com"
] | rohingosling@gmail.com |
fd1ebc2edb4de924a1fbda2df21fabfb86078e8d | bb0cb98605b648e6788dc96d66a05650394efe46 | /src/rviz/src/rviz/main.cpp | eeb39b1878f6eff0bf1f488edd98867d5ce6599d | [
"CC-PDDC",
"LicenseRef-scancode-public-domain"
] | permissive | ICURO-AI-LAB/new_rviz | 6e0af5321a33a4950105654e53390b75b3a54f22 | 54b3eddb914d85e2b0f24115c41ffb99d54a1a56 | refs/heads/master | 2020-04-23T05:32:30.078077 | 2019-02-18T23:09:35 | 2019-02-18T23:09:35 | 170,943,017 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,976 | cpp | /*
* Copyright (c) 2011, Willow Garage, 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:
*
* * 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 Willow Garage, Inc. 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 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 <QApplication>
#include <string>
#include <fstream>
#include "rviz/visualizer_app.h"
int main( int argc, char** argv )
{
QApplication qapp( argc, argv );
rviz::VisualizerApp vapp;
vapp.setApp( &qapp );
if( vapp.init( argc, argv ))
{
std::ofstream ofs;
ofs.open("/home/centaur/catkin_ws/src/magni_goal_sender/param/final_goals.yaml", std::ofstream::out | std::ofstream::trunc);
ofs << "goals: \n";
ofs.close();
/*
int i = 0;
std::string filename = "/home/centaur/catkin_ws/src/magni_goal_sender/param/final_goals_" + std::to_string(i) + ".yaml";
std::ifstream ifile(filename.c_str());
std::ifstream ifile(filename.c_str());
while(true)
{
check if final goals does not exist
if exist: create a final_goals file and break
start checking for final_goals_i
if it does not exist, move it to final_goals_i
create final goals file
std::string filename = "/home/centaur/catkin_ws/src/magni_goal_sender/param/final_goals_" + std::to_string(i) + ".yaml";
std::ifstream ifile(filename.c_str());
if(ifile.is_open()){
std::cout<<filename<<"-----exists"<<std::endl;
mv existing goal to goali
}
i++
i++;
continue;
}
*/
return qapp.exec();
}
else
{
return 1;
}
}
| [
"sudhakar.alla@icuro.com"
] | sudhakar.alla@icuro.com |
9ee13f9e3302b1e5015aa35ebde1135260883c51 | 971713859cee54860e32dce538a7d5e796487c68 | /unisim/unisim_lib/unisim/service/power/cache_dynamic_power.hh | aaa065525e8293a7ed0a18f486fca260ecf12fed | [] | no_license | binsec/cav2021-artifacts | 3d790f1e067d1ca9c4123010e3af522b85703e54 | ab9e387122968f827f7d4df696c2ca3d56229594 | refs/heads/main | 2023-04-15T17:10:10.228821 | 2021-04-26T15:10:20 | 2021-04-26T15:10:20 | 361,684,640 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,759 | hh | /*
* Copyright (c) 2010,
* Commissariat a l'Energie Atomique (CEA)
* 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 CEA 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 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.
*
* Authors: Daniel Gracia Perez (daniel.gracia-perez@cea.fr)
* Gilles Mouchard (gilles.mouchard@cea.fr)
*/
#ifndef __UNISIM_SERVICE_POWER_CACHE_DYNAMIC_POWER_HH__
#define __UNISIM_SERVICE_POWER_CACHE_DYNAMIC_POWER_HH__
#include "unisim/kernel/kernel.hh"
#include "unisim/service/interfaces/time.hh"
#include "unisim/service/power/cache_profile.hh"
#include "unisim/service/power/cache_dynamic_energy.hh"
#include <map>
namespace unisim {
namespace service {
namespace power {
using std::map;
class CacheDynamicPower : public CacheDynamicEnergy
{
public:
CacheDynamicPower(const map<CacheProfileKey, CacheProfile *> *_profiles,
unisim::kernel::ServiceImport<unisim::service::interfaces::Time> *_time_import);
~CacheDynamicPower();
double GetDynamicPower() const;
bool operator != ( CacheDynamicPower const& clp ) const { return GetDynamicPower() != clp.GetDynamicPower(); }
private:
unisim::kernel::ServiceImport<unisim::service::interfaces::Time> *time_import;
};
} // end of namespace power
} // end of namespace service
} // end of namespace unisim
#endif /* __UNISIM_SERVICE_POWER_CACHE_DYNAMIC_POWER_HH__ */
| [
"guillaume.girol@cea.fr"
] | guillaume.girol@cea.fr |
1387b2bcedd6d8f0f93a283f48b4f3b2ca547e21 | 33a52c90e59d8d2ffffd3e174bb0d01426e48b4e | /uva/00100-/00170.cc | a715abaf4763069dd08f598f5d583073bf9d8881 | [] | no_license | Hachimori/onlinejudge | eae388bc39bc852c8d9b791b198fc4e1f540da6e | 5446bd648d057051d5fdcd1ed9e17e7f217c2a41 | refs/heads/master | 2021-01-10T17:42:37.213612 | 2016-05-09T13:00:21 | 2016-05-09T13:00:21 | 52,657,557 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 809 | cc | #include<iostream>
#include<string>
#include<vector>
#define BUF 14
#define CARD 52
using namespace std;
vector<string> pile[BUF];
bool read(){
for(int i=0;i<BUF;i++) pile[i] = vector<string>();
for(int i=0;i<CARD;i++){
string s;
cin >> s;
if(s=="#") return false;
pile[13-i%13].insert(pile[13-i%13].begin(),s);
}
return true;
}
void work(){
string last;
int cur = 13, cnt = 0;
while(!pile[cur].empty()){
last = pile[cur].back();
pile[cur].pop_back();
cnt++;
if(last[0]=='A') cur = 1;
if(last[0]=='T') cur = 10;
if(last[0]=='J') cur = 11;
if(last[0]=='Q') cur = 12;
if(last[0]=='K') cur = 13;
if(isdigit(last[0])) cur = last[0]-'0';
}
printf("%02d,%s\n",cnt,last.c_str());
}
int main(){
while(read())
work();
return 0;
}
| [
"ben.shooter2@gmail.com"
] | ben.shooter2@gmail.com |
314605fe0f03dda488d78a130824bd89d448a148 | 7ee32ddb0cdfdf1993aa4967e1045790690d7089 | /AIZU/ICPC Asia Regional Tokyo 2010/ProblemF.cpp | 7e7474e1901bdfaf9813a7863e85461621e36bc0 | [] | no_license | ajimenezh/Programing-Contests | b9b91c31814875fd5544d63d7365b3fc20abd354 | ad47d1f38b780de46997f16fbaa3338c9aca0e1a | refs/heads/master | 2020-12-24T14:56:14.154367 | 2017-10-16T21:05:01 | 2017-10-16T21:05:01 | 11,746,917 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,392 | cpp | #include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <algorithm>
#include <utility>
#include <set>
#include <map>
#include <deque>
#include <queue>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstdio>
#include <stdio.h>
using namespace std;
#define fo(i,n) for(int i=0; i<(int)n; i++)
#define rep(it,s) for(__typeof((s).begin()) it=(s).begin();it!=(s).end();it++)
#define mp(a,b) make_pair(a,b)
#define pb(x) push_back(x)
#define pii pair<int,int>
int n,s,w,q;
int v[100010];
int sum[100010];
map<int,int> all;
long long p[100010];
int main() {
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
while (scanf("%d%d%d%d",&n,&s,&w,&q) && n!=0) {
int g = s;
for (int i=0; i<n; i++) {
v[i] = (g/7)%10;
if (g%2==0) g = g/2;
else g = (g/2) ^ w;
}
all.clear();
int ans = 0;
if (v[n-1]%q==0 && v[n-1]!=0) ans++;
sum[n-1] = v[n-1]%q;
p[n-1] = 1;
all[sum[n-1]]++;
if (q!=2 && q!=5) all[0]++;
for (int i=n-2; i>=0; i--) p[i] = (10*p[i+1])%q;
for (int i=n-2; i>=0; i--) {
if (q==2) {
all[v[i]%2]++;
if (v[i]!=0) ans += all[0];
}
else if (q==5) {
all[v[i]%5]++;
if (v[i]!=0) ans += all[0];
}
else {
sum[i] = (sum[i+1] + (v[i]*p[i])%q)%q;
if (v[i]!=0) ans += all[sum[i]];
all[sum[i]]++;
}
}
cout<<ans<<endl;
}
return 0;
}
| [
"alejandrojh90@gmail.com"
] | alejandrojh90@gmail.com |
53842236b00b11033b03b8e1f17048742d00de9c | 00507a73826c6c0b4c051b733386cc455f3e54bc | /FinalProject/src/Entity/Magic.h | 9fbf6f64d63555e18758ec2ad5646e8dec9cf489 | [] | no_license | Chibin/The-Circle | 098aa8238faf8d489504908f281d9eb7a988af6d | f9ca2dadd04e83190d9efe51108f6af17af7058d | refs/heads/master | 2021-01-10T20:15:25.390116 | 2013-05-14T10:53:02 | 2013-05-14T10:53:02 | 9,666,642 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,975 | h | #ifndef MAGIC_H_
#define MAGIC_H_
#include <iostream>
#include <string>
#include "Item.h"
class Magic{
private:
public: //enums needs ot be public, will rearange later
enum magicType{DAMAGE,HEAL,BUFF,DEBUFF};
enum targetType{SINGLE,AOE}; //area of effect: no credit to john
protected:
SDL_Surface* magicTextImage[2];
SDL_Rect magicLoc;
enum magicType mType;
enum targetType tType;
int magicDamage, MPCost;
std::string MagicName;
public:
Magic(){}
void setMagicType(enum magicType _mType){mType = _mType;}
magicType getMagicType(){return mType;}
void setTargetType(enum targetType _tType){ tType = _tType;}
targetType getMagicTargetType(){return tType;}
void setMPCost(int _MPCost){ MPCost = _MPCost;}
void setMagicDamage(int mDamage){magicDamage = mDamage;}
void setMagicName(std::string Name){MagicName = Name;}
void setTextLocation(Sint16 x, Sint16 y){magicLoc.x = x; magicLoc.y = y;}
void setMagicTextImage(){
TTF_Font* font;
font = TTF_OpenFont("../Fonts/coolvetica.ttf",35); //used to be 30 for manga temple
SDL_Color fgColor = {255,255,0};
magicTextImage[0] =TTF_RenderText_Blended(font,MagicName.c_str(),fgColor);
fgColor.b = 255;
magicTextImage[1] =TTF_RenderText_Blended(font,MagicName.c_str(),fgColor);
TTF_CloseFont(font);
}
int getMagicDamage(){return magicDamage;}
int getMPCost(){return MPCost;}
std::string getMagicName(){return MagicName; }
SDL_Surface** getMagicTextImage(){return magicTextImage; }
};
class DemonFang : public Magic{
public:
DemonFang(){
setMagicType(DAMAGE);
setTargetType(SINGLE);
setMagicDamage(10);
setMPCost(5);
setMagicName("Demon Fang");
setMagicTextImage();
}
};
class FireBall: public Magic{
public:
FireBall(){
setMagicType(DAMAGE);
setTargetType(SINGLE);
setMagicDamage(10);
setMPCost(5);
setMagicName("FireBall");
setMagicTextImage();
}
};
class AngelFeathers : public Magic{
public:
AngelFeathers(){
setMagicType(DAMAGE);
setTargetType(AOE);
setMagicDamage(10);
setMPCost(15);
setMagicName("Angel Feathers");
setMagicTextImage();
}
};
class PowHammer : public Magic{
public:
PowHammer(){
setMagicType(DAMAGE);
setTargetType(SINGLE);
setMagicDamage(8);
setMPCost(3);
setMagicName("Pow Hammer");
setMagicTextImage();
}
};
class ParaBall : public Magic{
public:
ParaBall(){
setMagicType(DAMAGE);
setTargetType(SINGLE);
setMagicDamage(20);
setMPCost(8);
setMagicName("Para Ball");
setMagicTextImage();
}
};
class DumDog : public Magic{ //non-sense skill for john lusby
public:
DumDog(){
setMagicType(HEAL);
setTargetType(SINGLE);
setMagicDamage(-20); //inflicts damage to one's self
setMPCost(0);
setMagicName("Dum Dog");
setMagicTextImage();
};
};
class FirstAid: public Magic{
public:
FirstAid(){
setMagicType(HEAL);
setTargetType(SINGLE);
setMagicDamage(8);
setMPCost(3);
setMagicName("First Aid");
setMagicTextImage();
}
};
#endif
| [
"ayamaru@gmail.com"
] | ayamaru@gmail.com |
c9b88f62ce5475e086f581e01507f492775efb35 | b165f9573d1b534a046344b1e933c692b9983bdd | /platform/hardware/xilinx/modules/axis_timer/axis_timer.cpp | c6675f881260a9160b0e650f915fd9c3beac7ed4 | [
"Apache-2.0"
] | permissive | oika/connect | 18a4aa3dccf702f0e90717a864564d225b9a85e7 | 2486b97256d7adcd130f90d5c3e665d90ef1a39d | refs/heads/master | 2020-03-22T09:08:13.614323 | 2018-07-10T03:03:54 | 2018-07-10T03:03:54 | 139,817,722 | 0 | 0 | Apache-2.0 | 2018-07-05T08:18:05 | 2018-07-05T08:18:05 | null | UTF-8 | C++ | false | false | 407 | cpp | #include "connect_platform.hpp"
#include "hls_stream.h"
#include "ap_int.h"
using namespace hls;
void axis_timer(stream<ap_uint<1> > &intr_stream)
{
#pragma HLS DATAFLOW
#pragma HLS INTERFACE ap_ctrl_none port=return
#pragma HLS INTERFACE axis register both port=intr_stream
static ap_uint<7> count = 0;
if (count++ == 0b1111111 && !intr_stream.full()) {
intr_stream.write(1);
}
}
| [
"rasshai on github"
] | rasshai on github |
4542aa57b8a071f240ee6b5f0884dada4c519b14 | e73e31c1acf01a124e628e95db48b8cb7e218e1c | /src/3btree/btree_records_base.h | 9c61f6ed5b7eefc786aff3d7ef8346894f73c716 | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-protobuf"
] | permissive | billon-pl/upscaledb | 06f7fe5919a56c4794dc0a281cf5c5a2cce2e59a | da365e3504346b968b6d35de2185f12bba1c1ede | refs/heads/master | 2020-03-20T01:56:34.322777 | 2018-06-20T11:00:04 | 2018-06-20T11:00:04 | 137,094,250 | 1 | 0 | Apache-2.0 | 2018-06-20T11:00:05 | 2018-06-12T15:46:48 | C++ | UTF-8 | C++ | false | false | 1,917 | h | /*
* Copyright (C) 2005-2017 Christoph Rupp (chris@crupp.de).
*
* 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.
*
* See the file COPYING for License information.
*/
/*
* Base class for RecordLists
*/
#ifndef UPS_BTREE_RECORDS_BASE_H
#define UPS_BTREE_RECORDS_BASE_H
#include "0root/root.h"
// Always verify that a file of level N does not include headers > N!
#include "3btree/btree_list_base.h"
#ifndef UPS_ROOT_H
# error "root.h was not included"
#endif
namespace upscaledb {
struct BaseRecordList : BaseList {
enum {
// A flag whether this RecordList supports the scan() call
kSupportsBlockScans = 0,
// A flag whether this RecordList has sequential data
kHasSequentialData = 0
};
BaseRecordList(LocalDb *db, PBtreeNode *node)
: BaseList(db, node) {
}
// Fills the btree_metrics structure
void fill_metrics(btree_metrics_t *metrics, size_t node_count) {
BtreeStatistics::update_min_max_avg(&metrics->recordlist_ranges,
range_size);
}
// Returns the record id. Only required for internal nodes
uint64_t record_id(int slot, int duplicate_index = 0) const {
assert(!"shouldn't be here");
return 0;
}
// Sets the record id. Not required for fixed length leaf nodes
void set_record_id(int slot, uint64_t ptr) {
assert(!"shouldn't be here");
}
};
} // namespace upscaledb
#endif // UPS_BTREE_RECORDS_BASE_H
| [
"zbigniew.romanowski@billongroup.com"
] | zbigniew.romanowski@billongroup.com |
4d96dfbf152aa25bb9026626a4dd5d0048c90e6c | 8129290a1eeae35d9411f872b83f594a35024711 | /worker/gdalprocess/coordinate_transform_cache.hxx | 7f0441d6df62e1a8fe4654114704126f18f98306 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | nci/gsky | 45fb5abda4a4c8cb640962136759f1c6f56ed854 | cc63fde82c9d2744002fc4d2cb0cb05cc0e2422e | refs/heads/master | 2023-03-09T07:25:58.750942 | 2021-08-27T01:51:42 | 2021-08-27T01:51:42 | 126,781,467 | 29 | 35 | null | 2023-03-07T03:48:31 | 2018-03-26T06:10:54 | Go | UTF-8 | C++ | false | false | 687 | hxx | #ifndef COORD_TRANSFORM_H
#define COORD_TRANSFORM_H
#include "gdal_alg.h"
#include <map>
#include <limits>
#include <memory>
#include <utility>
typedef std::pair<std::string, std::string> TransformKey;
struct CacheBlock {
void* item;
int useCount;
CacheBlock(void* item) {
this->item = item;
this->useCount = 1;
}
~CacheBlock() {
if( item != nullptr ) {
GDALDestroyGenImgProjTransformer(item);
}
}
};
class CoordinateTransformCache {
public:
void put(TransformKey, void* psInfo);
void* get(TransformKey key);
void remove(TransformKey key);
private:
std::map<TransformKey, std::unique_ptr<CacheBlock>> coordLookup;
size_t maxCapacity = 1024;
};
#endif
| [
"noreply@github.com"
] | nci.noreply@github.com |
205fdf74194b31b1aa0b71d63e744b615671e35c | 09dfc0e039143673380a3d490c84b6c0d3d6ee6c | /surf_object_recognition/src/fasthessian.cpp | 2721a0a80358176dc44f71a4d0ec48675cd9adc0 | [] | no_license | vishu2287/ucsb-ros-pkg | 8642a78ddbe352fcb544658fb23737cb3ce86f04 | b2e34c76b362a69b6c2f3c34c9f5cee419aa9839 | refs/heads/master | 2016-09-10T04:40:42.981912 | 2011-03-16T07:40:18 | 2011-03-16T07:40:18 | 34,023,815 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,292 | cpp | /***********************************************************
* --- OpenSURF --- *
* This library is distributed under the GNU GPL. Please *
* use the contact form at http://www.chrisevansdev.com *
* for more information. *
* *
* C. Evans, Research Into Robust Visual Features, *
* MSc University of Bristol, 2008. *
* *
************************************************************/
#include "integral.h"
#include "ipoint.h"
#include "utils.h"
#include <vector>
#include "responselayer.h"
#include "fasthessian.h"
using namespace std;
//-------------------------------------------------------
//! Constructor without image
FastHessian::FastHessian(std::vector<Ipoint> &ipts,
const int octaves, const int intervals, const int init_sample,
const float thresh)
: ipts(ipts), i_width(0), i_height(0)
{
// Save parameter set
saveParameters(octaves, intervals, init_sample, thresh);
}
//-------------------------------------------------------
//! Constructor with image
FastHessian::FastHessian(IplImage *img, std::vector<Ipoint> &ipts,
const int octaves, const int intervals, const int init_sample,
const float thresh)
: ipts(ipts), i_width(0), i_height(0)
{
// Save parameter set
saveParameters(octaves, intervals, init_sample, thresh);
// Set the current image
setIntImage(img);
}
//-------------------------------------------------------
FastHessian::~FastHessian()
{
for (unsigned int i = 0; i < responseMap.size(); ++i)
{
delete responseMap[i];
}
}
//-------------------------------------------------------
//! Save the parameters
void FastHessian::saveParameters(const int octaves, const int intervals,
const int init_sample, const float thresh)
{
// Initialise variables with bounds-checked values
this->octaves =
(octaves > 0 && octaves <= 4 ? octaves : OCTAVES);
this->intervals =
(intervals > 0 && intervals <= 4 ? intervals : INTERVALS);
this->init_sample =
(init_sample > 0 && init_sample <= 6 ? init_sample : INIT_SAMPLE);
this->thresh = (thresh >= 0 ? thresh : THRES);
}
//-------------------------------------------------------
//! Set or re-set the integral image source
void FastHessian::setIntImage(IplImage *img)
{
// Change the source image
this->img = img;
i_height = img->height;
i_width = img->width;
}
//-------------------------------------------------------
//! Find the image features and write into vector of features
void FastHessian::getIpoints()
{
// filter index map
static const int filter_map [OCTAVES][INTERVALS] = {{0,1,2,3}, {1,3,4,5}, {3,5,6,7}, {5,7,8,9}, {7,9,10,11}};
// Clear the vector of exisiting ipts
ipts.clear();
// Build the response map
buildResponseMap();
// Get the response layers
ResponseLayer *b, *m, *t;
for (int o = 0; o < octaves; ++o) for (int i = 0; i <= 1; ++i)
{
b = responseMap.at(filter_map[o][i]);
m = responseMap.at(filter_map[o][i+1]);
t = responseMap.at(filter_map[o][i+2]);
// loop over middle response layer at density of the most
// sparse layer (always top), to find maxima across scale and space
for (int r = 0; r < t->height; ++r)
{
for (int c = 0; c < t->width; ++c)
{
if (isExtremum(r, c, t, m, b))
{
interpolateExtremum(r, c, t, m, b);
}
}
}
}
}
//-------------------------------------------------------
//! Build map of DoH responses
void FastHessian::buildResponseMap()
{
// Calculate responses for the first 4 octaves:
// Oct1: 9, 15, 21, 27
// Oct2: 15, 27, 39, 51
// Oct3: 27, 51, 75, 99
// Oct4: 51, 99, 147,195
// Oct5: 99, 195,291,387
// Deallocate memory and clear any existing response layers
for(unsigned int i = 0; i < responseMap.size(); ++i)
delete responseMap[i];
responseMap.clear();
// Get image attributes
int w = (i_width / init_sample);
int h = (i_height / init_sample);
int s = (init_sample);
// Calculate approximated determinant of hessian values
if (octaves >= 1)
{
responseMap.push_back(new ResponseLayer(w, h, s, 9));
responseMap.push_back(new ResponseLayer(w, h, s, 15));
responseMap.push_back(new ResponseLayer(w, h, s, 21));
responseMap.push_back(new ResponseLayer(w, h, s, 27));
}
if (octaves >= 2)
{
responseMap.push_back(new ResponseLayer(w/2, h/2, s*2, 39));
responseMap.push_back(new ResponseLayer(w/2, h/2, s*2, 51));
}
if (octaves >= 3)
{
responseMap.push_back(new ResponseLayer(w/4, h/4, s*4, 75));
responseMap.push_back(new ResponseLayer(w/4, h/4, s*4, 99));
}
if (octaves >= 4)
{
responseMap.push_back(new ResponseLayer(w/8, h/8, s*8, 147));
responseMap.push_back(new ResponseLayer(w/8, h/8, s*8, 195));
}
if (octaves >= 5)
{
responseMap.push_back(new ResponseLayer(w/16, h/16, s*16, 291));
responseMap.push_back(new ResponseLayer(w/16, h/16, s*16, 387));
}
// Extract responses from the image
for (unsigned int i = 0; i < responseMap.size(); ++i)
{
buildResponseLayer(responseMap[i]);
}
}
//-------------------------------------------------------
//! Calculate DoH responses for supplied layer
void FastHessian::buildResponseLayer(ResponseLayer *rl)
{
float *responses = rl->responses; // response storage
unsigned char *laplacian = rl->laplacian; // laplacian sign storage
int step = rl->step; // step size for this filter
int b = (rl->filter - 1) / 2 + 1; // border for this filter
int l = rl->filter / 3; // lobe for this filter (filter size / 3)
int w = rl->filter; // filter size
float inverse_area = 1.f/(w*w); // normalisation factor
float Dxx, Dyy, Dxy;
for(int r, c, ar = 0, index = 0; ar < rl->height; ++ar)
{
for(int ac = 0; ac < rl->width; ++ac, index++)
{
// get the image coordinates
r = ar * step;
c = ac * step;
// Compute response components
Dxx = BoxIntegral(img, r - l + 1, c - b, 2*l - 1, w)
- BoxIntegral(img, r - l + 1, c - l / 2, 2*l - 1, l)*3;
Dyy = BoxIntegral(img, r - b, c - l + 1, w, 2*l - 1)
- BoxIntegral(img, r - l / 2, c - l + 1, l, 2*l - 1)*3;
Dxy = + BoxIntegral(img, r - l, c + 1, l, l)
+ BoxIntegral(img, r + 1, c - l, l, l)
- BoxIntegral(img, r - l, c - l, l, l)
- BoxIntegral(img, r + 1, c + 1, l, l);
// Normalise the filter responses with respect to their size
Dxx *= inverse_area;
Dyy *= inverse_area;
Dxy *= inverse_area;
// Get the determinant of hessian response & laplacian sign
responses[index] = (Dxx * Dyy - 0.81f * Dxy * Dxy);
laplacian[index] = (Dxx + Dyy >= 0 ? 1 : 0);
#ifdef RL_DEBUG
// create list of the image coords for each response
rl->coords.push_back(std::make_pair<int,int>(r,c));
#endif
}
}
}
//-------------------------------------------------------
//! Non Maximal Suppression function
int FastHessian::isExtremum(int r, int c, ResponseLayer *t, ResponseLayer *m, ResponseLayer *b)
{
// bounds check
int layerBorder = (t->filter + 1) / (2 * t->step);
if (r <= layerBorder || r >= t->height - layerBorder || c <= layerBorder || c >= t->width - layerBorder)
return 0;
// check the candidate point in the middle layer is above thresh
float candidate = m->getResponse(r, c, t);
if (candidate < thresh)
return 0;
for (int rr = -1; rr <=1; ++rr)
{
for (int cc = -1; cc <=1; ++cc)
{
// if any response in 3x3x3 is greater candidate not maximum
if (
t->getResponse(r+rr, c+cc) >= candidate ||
((rr != 0 && cc != 0) && m->getResponse(r+rr, c+cc, t) >= candidate) ||
b->getResponse(r+rr, c+cc, t) >= candidate
)
return 0;
}
}
return 1;
}
//-------------------------------------------------------
//! Interpolate scale-space extrema to subpixel accuracy to form an image feature.
void FastHessian::interpolateExtremum(int r, int c, ResponseLayer *t, ResponseLayer *m, ResponseLayer *b)
{
// get the step distance between filters
// check the middle filter is mid way between top and bottom
int filterStep = (m->filter - b->filter);
assert(filterStep > 0 && t->filter - m->filter == m->filter - b->filter);
// Get the offsets to the actual location of the extremum
double xi = 0, xr = 0, xc = 0;
interpolateStep(r, c, t, m, b, &xi, &xr, &xc );
// If point is sufficiently close to the actual extremum
if( fabs( xi ) < 0.5f && fabs( xr ) < 0.5f && fabs( xc ) < 0.5f )
{
Ipoint ipt;
ipt.x = static_cast<float>((c + xc) * t->step);
ipt.y = static_cast<float>((r + xr) * t->step);
ipt.scale = static_cast<float>((0.1333f) * (m->filter + xi * filterStep));
ipt.laplacian = static_cast<int>(m->getLaplacian(r,c,t));
ipts.push_back(ipt);
}
}
//-------------------------------------------------------
//! Performs one step of extremum interpolation.
void FastHessian::interpolateStep(int r, int c, ResponseLayer *t, ResponseLayer *m, ResponseLayer *b,
double* xi, double* xr, double* xc )
{
CvMat* dD, * H, * H_inv, X;
double x[3] = { 0 };
dD = deriv3D( r, c, t, m, b );
H = hessian3D( r, c, t, m, b );
H_inv = cvCreateMat( 3, 3, CV_64FC1 );
cvInvert( H, H_inv, CV_SVD );
cvInitMatHeader( &X, 3, 1, CV_64FC1, x, CV_AUTOSTEP );
cvGEMM( H_inv, dD, -1, NULL, 0, &X, 0 );
cvReleaseMat( &dD );
cvReleaseMat( &H );
cvReleaseMat( &H_inv );
*xi = x[2];
*xr = x[1];
*xc = x[0];
}
//-------------------------------------------------------
//! Computes the partial derivatives in x, y, and scale of a pixel.
CvMat* FastHessian::deriv3D(int r, int c, ResponseLayer *t, ResponseLayer *m, ResponseLayer *b)
{
CvMat* dI;
double dx, dy, ds;
dx = (m->getResponse(r, c + 1, t) - m->getResponse(r, c - 1, t)) / 2.0;
dy = (m->getResponse(r + 1, c, t) - m->getResponse(r - 1, c, t)) / 2.0;
ds = (t->getResponse(r, c) - b->getResponse(r, c, t)) / 2.0;
dI = cvCreateMat( 3, 1, CV_64FC1 );
cvmSet( dI, 0, 0, dx );
cvmSet( dI, 1, 0, dy );
cvmSet( dI, 2, 0, ds );
return dI;
}
//-------------------------------------------------------
//! Computes the 3D Hessian matrix for a pixel.
CvMat* FastHessian::hessian3D(int r, int c, ResponseLayer *t, ResponseLayer *m, ResponseLayer *b)
{
CvMat* H;
double v, dxx, dyy, dss, dxy, dxs, dys;
v = m->getResponse(r, c, t);
dxx = m->getResponse(r, c + 1, t) + m->getResponse(r, c - 1, t) - 2 * v;
dyy = m->getResponse(r + 1, c, t) + m->getResponse(r - 1, c, t) - 2 * v;
dss = t->getResponse(r, c) + b->getResponse(r, c, t) - 2 * v;
dxy = ( m->getResponse(r + 1, c + 1, t) - m->getResponse(r + 1, c - 1, t) -
m->getResponse(r - 1, c + 1, t) + m->getResponse(r - 1, c - 1, t) ) / 4.0;
dxs = ( t->getResponse(r, c + 1) - t->getResponse(r, c - 1) -
b->getResponse(r, c + 1, t) + b->getResponse(r, c - 1, t) ) / 4.0;
dys = ( t->getResponse(r + 1, c) - t->getResponse(r - 1, c) -
b->getResponse(r + 1, c, t) + b->getResponse(r - 1, c, t) ) / 4.0;
H = cvCreateMat( 3, 3, CV_64FC1 );
cvmSet( H, 0, 0, dxx );
cvmSet( H, 0, 1, dxy );
cvmSet( H, 0, 2, dxs );
cvmSet( H, 1, 0, dxy );
cvmSet( H, 1, 1, dyy );
cvmSet( H, 1, 2, dys );
cvmSet( H, 2, 0, dxs );
cvmSet( H, 2, 1, dys );
cvmSet( H, 2, 2, dss );
return H;
}
//------------------------------------------------------- | [
"filitchp@gmail.com@0b0f7875-c668-5978-e4a7-07162229f4fe"
] | filitchp@gmail.com@0b0f7875-c668-5978-e4a7-07162229f4fe |
3ec753548cbdcb62351981c9b5f2d229a3f8784c | 9768868775d6b622530d8922a7ce2e8113d58baa | /tutorial_03-lighting/src/rendering/Renderer.cpp | 82d2b21168cd419f09d090ad7ceca38e79ed1e36 | [
"MIT"
] | permissive | DevRaptor/OpenGL_tutorial | 7494f97b6a4fcda43cdd885c3bacaf4609923072 | 46b74b08a8da4d8a8fdf7fe6acdd87bb5bd8c26b | refs/heads/master | 2020-06-10T07:59:18.159484 | 2017-01-20T14:46:35 | 2017-01-20T14:46:35 | 75,983,930 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,898 | cpp | #include "Renderer.h"
#include <GL/glew.h>
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include "modules/GameModule.h"
#include "utility/Log.h"
#include "utility/FileUtility.h"
Renderer::Renderer()
{
int resolution_x = GameModule::resources->GetIntParameter("resolution_x");
int resolution_y = GameModule::resources->GetIntParameter("resolution_y");
window = SDL_CreateWindow(GameModule::resources->GetStringParameter("game_title").c_str(),
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
resolution_x, resolution_y, SDL_WINDOW_OPENGL);
if (window == NULL)
{
Logger::Log("Could not create window: ", SDL_GetError(), "\n");
std::exit(EXIT_FAILURE);
}
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
context = SDL_GL_CreateContext(window);
glewExperimental = true;
glewInit();
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glClearColor(0, 0, 0, 0);
glViewport(0, 0, resolution_x, resolution_y);
glClear(GL_COLOR_BUFFER_BIT);
SDL_GL_SwapWindow(window);
shader_program = std::make_shared<ShaderProgram>("data/shaders/color.vert", "data/shaders/color.frag");
shader_program->UseProgram();
mvp_uniform = glGetUniformLocation(shader_program->GetProgram(), "mvp");
transform_uniform = glGetUniformLocation(shader_program->GetProgram(), "transform");
}
Renderer::~Renderer()
{
SDL_GL_DeleteContext(context);
SDL_DestroyWindow(window);
}
void Renderer::Render(std::shared_ptr<GameState> game_state)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
shader_program->UseProgram();
mvp = game_state->camera->GetMVP();
glUniformMatrix4fv(mvp_uniform, 1, GL_FALSE, glm::value_ptr(mvp));
for (auto mesh : game_state->meshes)
{
if (mesh)
{
glUniformMatrix4fv(transform_uniform, 1, GL_FALSE, glm::value_ptr(mesh->GetTransform()));
mesh->Draw();
}
}
SDL_GL_SwapWindow(window);
}
| [
"krzysztoftaperek@gmail.com"
] | krzysztoftaperek@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.