blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
37dd17a8d24fc40b34f11dd0cc55dec9d7701966
dc933e6c4af6db8e5938612935bb51ead04da9b3
/android-x86/external/opencore/oscl/oscl/osclproc/src/oscl_thread.h
2b173c493650abb2de89d50adfd4beb350f66e3f
[]
no_license
leotfrancisco/patch-hosting-for-android-x86-support
213f0b28a7171570a77a3cec48a747087f700928
e932645af3ff9515bd152b124bb55479758c2344
refs/heads/master
2021-01-10T08:40:36.731838
2009-05-28T04:29:43
2009-05-28T04:29:43
51,474,005
1
0
null
null
null
null
UTF-8
C++
false
false
7,904
h
/* ------------------------------------------------------------------ * Copyright (C) 2008 PacketVideo * * 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. * ------------------------------------------------------------------- */ // -*- c++ -*- // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // OSCL_T H R E A D (T H R E A D I M P L E M E N T A T I O N) // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = /*! \file oscl_thread.h .This file provides THREAD implementation that can be ported to three OS LINUX, SYMBIAN, WIN32 */ // Definition file for OSCL Threads #ifndef OSCL_THREAD_H_INCLUDED #define OSCL_THREAD_H_INCLUDED #ifndef OSCLCONFIG_PROC_H_INCLUDED #include "osclconfig_proc.h" #endif #ifndef OSCL_PROCSTATUS_H_INCLUDED #include "oscl_procstatus.h" #endif #ifndef OSCL_BASE_H_INCLUDED #include "oscl_base.h" #endif // Thread state on creation enum OsclThread_State { Start_on_creation , Suspend_on_creation }; // Enumerated Priority Values enum OsclThreadPriority { ThreadPriorityLowest , ThreadPriorityLow , ThreadPriorityBelowNormal , ThreadPriorityNormal , ThreadPriorityAboveNormal , ThreadPriorityHighest , ThreadPriorityTimeCritical }; //thread function pointer type. typedef TOsclThreadFuncRet(OSCL_THREAD_DECL *TOsclThreadFuncPtr)(TOsclThreadFuncArg); /** * Thread Class. A subset of Thread APIs. * It implements platform independendent APIs for thread creation, exiting, suspend, resume, priority * and termination. With the use of proper defines it implements the basic thread festures. * It provides an opaque layer through which user doesn't need to worry about OS specific data. */ class OsclThread { public: /** * Class constructor */ OSCL_IMPORT_REF OsclThread(); /** * Class destructor */ OSCL_IMPORT_REF ~OsclThread(); /** * This routine will create a thread. The thread may be * launched immediately or may be created in a suspended * state and launched with a Resume call. * * @param * func = Name of the thread Function * stack_size = Size of the thread stack. If zero, then the * platform-specific default stack size will be used. * argument = Argument to be passed to thread function * state = Enumeration which specifies the state of the thread on creation * with values Running and Suspend. Note: the Suspend option * may not be available on all platforms. If it is not supported, * the Create call will return INVALID_PARAM_ERROR. * @return eOsclProcError */ OSCL_IMPORT_REF OsclProcStatus::eOsclProcError Create(TOsclThreadFuncPtr func, int32 stack_size, TOsclThreadFuncArg argument, OsclThread_State state = Start_on_creation); /** * Exit is a static function which is used to end the current thread. When called it * just ends the execution of the current thread. * @param * exitcode = Exitcode of the thread. This can be used by other threads to know the * exit status of this thread. * @return None */ OSCL_IMPORT_REF static void Exit(OsclAny* exitcode); /** * EnableKill is a static function which can * be called by the thread routine in order to enable * thread termination without waiting for cancellation * points. * EnableKill only applies to pthread implementations. * For other implementations this function will do nothing. * * @return None */ OSCL_IMPORT_REF static void EnableKill(); /** * GetThreadPriority gets the priority of the thread. It takes reference of the input argument * and assigns priority to it from one of the already defined priorities. * @param * int16& refThreadPriority : Output Priority value * @return Error code */ OSCL_IMPORT_REF OsclProcStatus::eOsclProcError GetPriority(OsclThreadPriority& refThreadPriority); /** * SetThreadPriority sets the priority of the thread. It takes priority as the input argument * and assigns it to the thread referred. * @param * ePriorityLevel : Input Priority value * @return Error code * Note: this function may not be supported on all platforms, and * may return NOT_IMPLEMENTED. */ OSCL_IMPORT_REF OsclProcStatus::eOsclProcError SetPriority(OsclThreadPriority ePriority); /** * This API suspends the thread being referred. The thread can later be brought into execution * by calling OSCL_ResumeThread() on it. * @param None * @return Error code * Note: this function may not be supported on all platforms, and * may return NOT_IMPLEMENTED. */ OSCL_IMPORT_REF OsclProcStatus::eOsclProcError Suspend(); /** * ResumeThread resumes the suspended thread and brings it into execution. * @param None * @return Error code * Note: this function may not be supported on all platforms, and * may return NOT_IMPLEMENTED. */ OSCL_IMPORT_REF OsclProcStatus::eOsclProcError Resume(); /** * Terminate a thread other than the calling thread. * * Note: for pthread implementations, the Terminate call will * block until the thread has terminated. By default, * threads will not terminate until a cancellation point * is reached. The EnableKill method may be used to override * this default behavior and allow immediate termination. * * @param * exitcode = Exitcode of the thread. * @return Error code */ OSCL_IMPORT_REF OsclProcStatus::eOsclProcError Terminate(OsclAny* exitcode); /** * Static routine to retrieve ID of calling thread. * @param Thread ID passed by the application * @return Error code */ OSCL_IMPORT_REF static OsclProcStatus::eOsclProcError GetId(TOsclThreadId& refThreadId); /** * Static routine to compare whether two thread ID's are equal. * @param t1, t2: thread ID passed by the application * @return true if equal. */ OSCL_IMPORT_REF static bool CompareId(TOsclThreadId &t1, TOsclThreadId &t2); /** * Suspend current thread execution for specified time. * @param msec, t2: sleep time in milliseconds. */ OSCL_IMPORT_REF static void SleepMillisec(const int32 msec); private: /** * Helper Function * Map the Operating system errors to OSCL defined erros * @param * error : Input error as one of the OS errors * @return Error code ( User defined ) */ OsclProcStatus::eOsclProcError MapOsclError(int16 error); TOsclMutexObject mutex; TOsclConditionObject condition; uint8 suspend; TOsclThreadObject ObjThread; bool bCreated; }; #endif
[ "beyounn@8848914e-2522-11de-9896-099eabac0e35" ]
beyounn@8848914e-2522-11de-9896-099eabac0e35
9ca003d9e7d4568fb8fd4bc8897a5682aff96ab1
0a06806d5880c05cce436ba765302b72f179d342
/C_C++/Tree00 Code/CNode.cpp
2d98a7a3d2feb6ef4743e96704ef0599785f4831
[]
no_license
nanarochi/My-Structure-Algorithm-Project-1
9f160330c281f5c8c46c3cf94192eaa8c688d910
a320ff9fc82660446c43f48bf6b77485a3960ee3
refs/heads/master
2020-07-28T22:03:24.144163
2019-09-19T13:26:01
2019-09-19T13:26:01
209,553,872
0
0
null
null
null
null
UTF-8
C++
false
false
566
cpp
#include "stdafx.h" C_NODE::C_NODE() : m_nData(0), m_pLeft(nullptr), m_pRight(nullptr) { } int C_NODE::I_getData() { return m_nData; } void C_NODE::I_setData(const int nData) { m_nData = nData; } C_NODE * C_NODE::I_getLeftChild() { return m_pLeft; } void C_NODE::I_setLeftChild(C_NODE * pNode) { m_pLeft = pNode; } C_NODE * C_NODE::I_getRightChild() { return m_pRight; } void C_NODE::I_setRightChild(C_NODE * pNode) { m_pRight = pNode; } C_NODE ** C_NODE::I_getpLeft() { return &m_pLeft; } C_NODE ** C_NODE::I_getpRight() { return &m_pRight; }
[ "nanarochi4457@gmail.com" ]
nanarochi4457@gmail.com
034c0c1032ab379adba57f9784adc81d3c9ece15
6440c8be44307ee74da76c2454d774f6ef81b37d
/src/Callback.hpp
5242edbd873bfd7ec6c8babd4832fe3c06d3eea5
[]
no_license
nmanjofo/DualGPU
d3733d602df670309f3ea375ccb5fb7e9ee50ab9
47b9b53023968d24c0c8012c02ebd12508d626b8
refs/heads/master
2020-05-31T11:22:36.846680
2015-02-19T15:27:53
2015-02-19T15:27:53
27,722,996
0
0
null
null
null
null
UTF-8
C++
false
false
645
hpp
#pragma once #include <functional> class Callback { public: virtual void call(void* arg) = 0; }; template <class T> class CallbackFromInstance : public Callback { public: void bind(void(T::*function)(void*), T* instance) { func = std::bind(function, instance, std::placeholders::_1); } void call(void* arg) override { func(arg); } protected: std::function<void(void*)> func; }; class CallbackFromFunction : public Callback { public: void bind(std::function<void(void*)> &f) { func = std::bind(f, std::placeholders::_1); } void call(void* arg) override { func(arg); } protected: std::function<void(void*)> func; };
[ "nmanjofo@pretaktovanie.sk" ]
nmanjofo@pretaktovanie.sk
4c28fa8bb71b7284f5cae47d9a32a34d900a6193
5d72a0b367d11c8dc4f8d9c5118e3be09bd48b83
/HeaderStone_Deck_Maker/ChartViewer.h
7b9cc5404d6e3084bf3d45d8ab9e1fb56f42762e
[]
no_license
Yeoto/Hearthstone_Deck_Maker
8835154681bf34d901cee0216db07650dc04b3ca
5e69bc787ee5481b92b1dd1a18d00f05a2bb109f
refs/heads/master
2020-05-18T01:20:00.155101
2019-05-30T14:42:02
2019-05-30T14:42:02
184,087,503
4
0
null
null
null
null
UTF-8
C++
false
false
14,157
h
/////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright 2016 Advanced Software Engineering Limited // // You may use and modify the code in this file in your application, provided the code and // its modifications are used only in conjunction with ChartDirector. Usage of this software // is subjected to the terms and condition of the ChartDirector license. /////////////////////////////////////////////////////////////////////////////////////////////////// #pragma once #include "CharDirector/chartdir.h" #include <afxmt.h> // // Constants // #ifdef CD_NAMESPACE namespace CD_NAMESPACE { #endif namespace Chart { // // Mouse usage mode constants // enum { MouseUsageDefault = 0, MouseUsageScroll = 1, MouseUsageZoomIn = 3, MouseUsageZoomOut = 4, }; } #ifdef CD_NAMESPACE } #endif // // Forward declarations // class CViewPortControl; // // Utility to convert from UTF8 string to MFC TCHAR string. // class UTF8toTCHAR { public : UTF8toTCHAR(const char *utf8_string) : t_string(0), needFree(false) { if (0 == utf8_string) t_string = 0; else if (0 == *utf8_string) t_string = _T(""); else if ((sizeof(TCHAR) == sizeof(char)) && isPureAscii(utf8_string)) // No conversion needed for pure ASCII text t_string = (TCHAR *)utf8_string; else { // Either TCHAR = Unicode (2 bytes), or utf8_string contains non-ASCII characters. // Needs conversion needFree = true; // Convert to Unicode (2 bytes) int string_len = (int)strlen(utf8_string); wchar_t *buffer = new wchar_t[string_len + 1]; MultiByteToWideChar(CP_UTF8, 0, utf8_string, -1, buffer, string_len + 1); buffer[string_len] = 0; #ifdef _UNICODE t_string = buffer; #else // TCHAR is MBCS - need to convert back to MBCS t_string = new char[string_len * 2 + 2]; WideCharToMultiByte(CP_ACP, 0, buffer, -1, t_string, string_len * 2 + 1, 0, 0); t_string[string_len * 2 + 1] = 0; delete[] buffer; #endif } } operator const TCHAR*() { return t_string; } ~UTF8toTCHAR() { if (needFree) delete[] t_string; } private : TCHAR *t_string; bool needFree; // // helper utility to test if a string contains only ASCII characters // bool isPureAscii(const char *s) { while (*s != 0) { if (*(s++) & 0x80) return false; } return true; } //disable assignment UTF8toTCHAR(const UTF8toTCHAR &rhs); UTF8toTCHAR &operator=(const UTF8toTCHAR &rhs); }; // // Utility to convert from MFC TCHAR string to UTF8 string // class TCHARtoUTF8 { public : TCHARtoUTF8(const TCHAR *t_string) : utf8_string(0), needFree(false) { if (0 == t_string) utf8_string = 0; else if (0 == *t_string) utf8_string = ""; else if ((sizeof(TCHAR) == sizeof(char)) && isPureAscii((char *)t_string)) // No conversion needed for pure ASCII text utf8_string = (char *)t_string; else { // TCHAR is non-ASCII. Needs conversion. needFree = true; int string_len = (int)_tcslen(t_string); #ifndef _UNICODE // Convert to Unicode if not already in unicode. wchar_t *w_string = new wchar_t[string_len + 1]; MultiByteToWideChar(CP_ACP, 0, t_string, -1, w_string, string_len + 1); w_string[string_len] = 0; #else wchar_t *w_string = (wchar_t*)t_string; #endif // Convert from Unicode (2 bytes) to UTF8 utf8_string = new char[string_len * 3 + 1]; WideCharToMultiByte(CP_UTF8, 0, w_string, -1, utf8_string, string_len * 3 + 1, 0, 0); utf8_string[string_len * 3] = 0; if (w_string != (wchar_t *)t_string) delete[] w_string; } } operator const char*() { return utf8_string; } ~TCHARtoUTF8() { if (needFree) delete[] utf8_string; } private : char *utf8_string; bool needFree; // // helper utility to test if a string contains only ASCII characters // bool isPureAscii(const char *s) { while (*s != 0) { if (*(s++) & 0x80) return false; } return true; } //disable assignment TCHARtoUTF8(const TCHARtoUTF8 &rhs); TCHARtoUTF8 &operator=(const TCHARtoUTF8 &rhs); }; ///////////////////////////////////////////////////////////////////////////// // CRectCtrl window // // A rectangle with a background color. Use as thick edges for the selection // rectangle. // class CRectCtrl : public CStatic { public: // Public interface BOOL Create(CWnd* pParentWnd, COLORREF c); void SetColor(COLORREF c); // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CRectCtrl) //}}AFX_VIRTUAL protected: // Generated message map functions //{{AFX_MSG(CRectCtrl) afx_msg HBRUSH CtlColor(CDC* pDC, UINT nCtlColor); //}}AFX_MSG DECLARE_MESSAGE_MAP() private : CBrush m_Color; }; ///////////////////////////////////////////////////////////////////////////// // CStaticHelper utiltiies class CStaticHelper { private: HBITMAP m_currentHBITMAP; int m_WCCisV6; bool m_testMode; void setHBITMAP(CStatic *self, HBITMAP newBitMap); HBITMAP bmpToHBITMAP(CStatic *self, const char *data); public: CStaticHelper(); void onPaint(CStatic *self); void displayChart(CStatic *self, BaseChart *c); }; ///////////////////////////////////////////////////////////////////////////// // CChartViewer window // // Event message ID // #define CVN_ViewPortChanged 1000 // View port has changed #define CVN_MouseMoveChart 1001 // Mouse moves over the chart #define CVN_MouseLeaveChart 1002 // Mouse leaves the chart #define CVN_MouseMovePlotArea 1003 // Mouse moves over the extended plot area #define CVN_MouseLeavePlotArea 1004 // Mouse leaves the extended plot area class CChartViewer : public CStatic, public ViewPortManager, private CStaticHelper { public: CChartViewer(); // // CChartViewer properties // virtual void setChart(BaseChart *c); virtual BaseChart *getChart(); virtual void setViewPortControl(CViewPortControl *vpc); virtual CViewPortControl *getViewPortControl(); virtual void setImageMap(const char *imageMap); virtual ImageMapHandler *getImageMapHandler(); virtual void setDefaultToolTip(LPCTSTR text); virtual CToolTipCtrl *getToolTipCtrl(); virtual void setSelectionBorderWidth(int width); virtual int getSelectionBorderWidth(); virtual void setSelectionBorderColor(COLORREF c); virtual COLORREF getSelectionBorderColor(); virtual void setMouseUsage(int mouseUsage); virtual int getMouseUsage(); virtual void setZoomDirection(int direction); virtual int getZoomDirection(); virtual void setScrollDirection(int direction); virtual int getScrollDirection(); virtual void setZoomInRatio(double ratio); virtual double getZoomInRatio(); virtual void setZoomOutRatio(double ratio); virtual double getZoomOutRatio(); virtual void setMouseWheelZoomRatio(double ratio); virtual double getMouseWheelZoomRatio(); virtual void setMinimumDrag(int offset); virtual int getMinimumDrag(); virtual void setUpdateInterval(int interval); virtual int getUpdateInterval(); virtual bool needUpdateChart(); virtual bool needUpdateImageMap(); virtual bool isMouseOnPlotArea(); virtual bool isInMouseMoveEvent(); virtual bool isMouseDragging(); // // CChartViewer methods // // Trigger the ViewPortChanged event virtual void updateViewPort(bool needUpdateChart, bool needUpdateImageMap); // Request CChartViewer to redisplay the chart virtual void updateDisplay(); // Handles mouse wheel zooming virtual BOOL onMouseWheelZoom(int x, int y, short zDelta); // Set the message used to remove the dynamic layer virtual void removeDynamicLayer(int msg); // Get the mouse coordinates virtual int getChartMouseX(); virtual int getChartMouseY(); // Get the mouse coordinates bounded to the plot area virtual int getPlotAreaMouseX(); virtual int getPlotAreaMouseY(); // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CChartViewer) public: virtual BOOL PreTranslateMessage(MSG* pMsg); //}}AFX_VIRTUAL protected: // Generated message map functions afx_msg void OnPaint(); afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnDelayedMouseMove(); afx_msg LRESULT OnMouseLeave(WPARAM wParam, LPARAM lParam); afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message); afx_msg void OnDestroy(); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); afx_msg BOOL OnMouseWheel(UINT nFlags, short zDelta, CPoint pt); afx_msg void OnTimer(UINT_PTR nIDEvent); DECLARE_MESSAGE_MAP() private: // // CChartViewer configurable properties // BaseChart *m_currentChart; // Current BaseChart object ImageMapHandler *m_hotSpotTester; // ImageMapHander representing the image map CString m_defaultToolTip; // Default tool tip text CToolTipCtrl m_ToolTip; // CToolTipCtrl for managing tool tips bool m_toolTipHasAttached; // CToolTipCtrl has attached to CChartViewer COLORREF m_selectBoxLineColor; // Selectiom box border color int m_selectBoxLineWidth; // Selectiom box border width int m_mouseUsage; // Mouse usage mode int m_zoomDirection; // Zoom direction int m_scrollDirection; // Scroll direction double m_zoomInRatio; // Click zoom in ratio double m_zoomOutRatio; // Click zoom out ratio double m_mouseWheelZoomRatio; // Mouse wheel zoom ratio int m_minDragAmount; // Minimum drag amount int m_updateInterval; // Minimum interval between chart updates bool m_needUpdateChart; // Has pending chart update request bool m_needUpdateImageMap; // Has pending image map udpate request // // Keep track of mouse states // int m_currentHotSpot; // The hot spot under the mouse cursor. bool m_isClickable; // Mouse is over a clickable hot spot. bool m_isOnPlotArea; // Mouse is over the plot area. bool m_isPlotAreaMouseDown; // Mouse left button is down in the plot area. bool m_isDragScrolling; // Is drag scrolling the chart. bool m_isMouseTracking; // Is tracking mouse leave event. bool m_isInMouseMove; // Is in mouse moeve event handler // // Dragging support // int m_plotAreaMouseDownXPos; // The starting x coordinate of the mouse drag. int m_plotAreaMouseDownYPos; // The starting y coordinate of the mouse drag. bool isDrag(int direction, CPoint point); // Check if mouse is dragging void OnPlotAreaMouseDrag(UINT nFlags, CPoint point); // Process mouse dragging // // Selection rectangle // CRectCtrl m_LeftLine; // Left edge of selection rectangle CRectCtrl m_RightLine; // Right edge of selection rectangle CRectCtrl m_TopLine; // Top edge of selection rectangle CRectCtrl m_BottomLine; // Bottom edge of selection rectangle void initRect(); // Initialize selection rectangle edges void drawRect(int x, int y, int width, int height); // Draw selection rectangle void setRectVisible(bool b); // Show/hide selection rectangle // // Chart update rate control // bool m_holdTimerActive; // Delay chart update to limit update frequency int m_delayUpdateChart; // Delay chart update until the mouse event is completed BaseChart *m_delayedChart; // The chart to be used for delayed update. void commitUpdateChart(); // Commit updating the chart. unsigned int m_lastMouseMove; // The timestamp of the last mouse move event. bool m_hasDelayedMouseMove; // Delay the mouse move event to allow other updates UINT m_delayedMouseMoveFlag; // The mouse key flags of the delayed mouse move event. CPoint m_delayedMouseMovePoint; // The mouse coordinates of the delayed mouse move event. void commitMouseMove(UINT nFlags, CPoint point); // Raise the delayed mouse move event. bool m_delayImageMapUpdate; // Delay image map update until mouse moves on plot area // // Track Cursor support // int m_currentMouseX; // Get the mouse x-pixel coordinate int m_currentMouseY; // Get the mouse y-pixel coordinate int m_isInMouseMovePlotArea; // flag to indicate if is in a mouse move plot area event. // // Dynamic Layer support // int m_autoHideMsg; // The message that will trigger removing the dynamic layer. void applyAutoHide(int msg); // Attempt to remove the dynamic layer with the given message. // // CViewPortControl support // CViewPortControl *m_vpControl; // Associated CViewPortControl bool m_ReentrantGuard; // Prevents infinite calling loops }; ///////////////////////////////////////////////////////////////////////////// // CViewPortControl window class CViewPortControl : public CStatic, public ViewPortControlBase, private CStaticHelper { public: CViewPortControl(); // Set the chart to be displayed in the control virtual void setChart(BaseChart *c); virtual BaseChart *getChart(); // Associated CChartViewer virtual void setViewer(CChartViewer *viewer); virtual CChartViewer *getViewer(); // Request the CViewPortControl to update its contents virtual void updateDisplay(); protected: // Generated message map functions afx_msg void OnDestroy(); afx_msg void OnPaint(); afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg BOOL OnMouseWheel(UINT nFlags, short zDelta, CPoint pt); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message); DECLARE_MESSAGE_MAP() private: CChartViewer *m_ChartViewer; // Associated CChartViewer BaseChart *m_Chart; // BaseChart object displayed in the control bool m_ReentrantGuard; // Prevents infinite calling loops int m_mouseDownX; // Current mouse x coordinates int m_mouseDownY; // Current mouse y coordinates bool isDrag(CPoint point); // Check if mouse is dragging HCURSOR getHCursor(int position); // Get the mouse cursor void paintDisplay(); // Paint the display void syncState(); // Synchronize the CViewPortControl with CChartViewer void updateChartViewerIfNecessary(); // Update CChartViewer if viewport has changed double toImageX(int x); // Convert from mouse to image x-coordinate double toImageY(int y); // Convert from mouse to image y-coordinate };
[ "yeoto867@naver.com" ]
yeoto867@naver.com
7db359d067b30c286cbc1aa6096025abc493b74c
71a08e13da1980d28f8328456d7ab210e76d67fc
/thirdparty/z3/src/api/api_parsers.cpp
b3252281b28d791090a92bccf9f6e14ec2c0f6a9
[ "BSD-2-Clause", "MIT" ]
permissive
wslee/euphony
ef4cffd52fb1bacbe33ea8127a4f66ab843934ec
0b9a62a294897b707c86ba3c0f63561ff503cb3b
refs/heads/master
2022-12-01T15:19:13.720166
2022-11-21T05:57:09
2022-11-21T05:57:09
122,758,209
26
12
NOASSERTION
2022-03-18T17:15:27
2018-02-24T16:34:54
Slash
UTF-8
C++
false
false
11,532
cpp
/*++ Copyright (c) 2012 Microsoft Corporation Module Name: api_parsers.cpp Abstract: API for parsing different formats Author: Leonardo de Moura (leonardo) 2012-02-29. Revision History: --*/ #include<iostream> #include "api/z3.h" #include "api/api_log_macros.h" #include "api/api_context.h" #include "api/api_util.h" #include "cmd_context/cmd_context.h" #include "parsers/smt2/smt2parser.h" #include "parsers/smt/smtparser.h" #include "solver/solver_na2as.h" extern "C" { void init_smtlib_parser(Z3_context c, unsigned num_sorts, Z3_symbol const sort_names[], Z3_sort const types[], unsigned num_decls, Z3_symbol const decl_names[], Z3_func_decl const decls[]) { mk_c(c)->reset_parser(); mk_c(c)->m_smtlib_parser = smtlib::parser::create(mk_c(c)->m()); mk_c(c)->m_smtlib_parser->initialize_smtlib(); smtlib::symtable * table = mk_c(c)->m_smtlib_parser->get_benchmark()->get_symtable(); for (unsigned i = 0; i < num_sorts; i++) { table->insert(to_symbol(sort_names[i]), to_sort(types[i])); } for (unsigned i = 0; i < num_decls; i++) { table->insert(to_symbol(decl_names[i]), to_func_decl(decls[i])); } } void Z3_API Z3_parse_smtlib_string(Z3_context c, const char * str, unsigned num_sorts, Z3_symbol const sort_names[], Z3_sort const sorts[], unsigned num_decls, Z3_symbol const decl_names[], Z3_func_decl const decls[]) { Z3_TRY; LOG_Z3_parse_smtlib_string(c, str, num_sorts, sort_names, sorts, num_decls, decl_names, decls); scoped_ptr<std::ostringstream> outs = alloc(std::ostringstream); bool ok = false; RESET_ERROR_CODE(); init_smtlib_parser(c, num_sorts, sort_names, sorts, num_decls, decl_names, decls); mk_c(c)->m_smtlib_parser->set_error_stream(*outs); try { ok = mk_c(c)->m_smtlib_parser->parse_string(str); } catch (...) { ok = false; } mk_c(c)->m_smtlib_error_buffer = outs->str(); outs = nullptr; if (!ok) { mk_c(c)->reset_parser(); SET_ERROR_CODE(Z3_PARSER_ERROR); } Z3_CATCH; } void Z3_API Z3_parse_smtlib_file(Z3_context c, const char * file_name, unsigned num_sorts, Z3_symbol const sort_names[], Z3_sort const types[], unsigned num_decls, Z3_symbol const decl_names[], Z3_func_decl const decls[]) { Z3_TRY; LOG_Z3_parse_smtlib_file(c, file_name, num_sorts, sort_names, types, num_decls, decl_names, decls); bool ok = false; RESET_ERROR_CODE(); scoped_ptr<std::ostringstream> outs = alloc(std::ostringstream); init_smtlib_parser(c, num_sorts, sort_names, types, num_decls, decl_names, decls); mk_c(c)->m_smtlib_parser->set_error_stream(*outs); try { ok = mk_c(c)->m_smtlib_parser->parse_file(file_name); } catch(...) { ok = false; } mk_c(c)->m_smtlib_error_buffer = outs->str(); outs = nullptr; if (!ok) { mk_c(c)->reset_parser(); SET_ERROR_CODE(Z3_PARSER_ERROR); } Z3_CATCH; } unsigned Z3_API Z3_get_smtlib_num_formulas(Z3_context c) { Z3_TRY; LOG_Z3_get_smtlib_num_formulas(c); RESET_ERROR_CODE(); if (mk_c(c)->m_smtlib_parser) { return mk_c(c)->m_smtlib_parser->get_benchmark()->get_num_formulas(); } SET_ERROR_CODE(Z3_NO_PARSER); return 0; Z3_CATCH_RETURN(0); } Z3_ast Z3_API Z3_get_smtlib_formula(Z3_context c, unsigned i) { Z3_TRY; LOG_Z3_get_smtlib_formula(c, i); RESET_ERROR_CODE(); if (mk_c(c)->m_smtlib_parser) { if (i < mk_c(c)->m_smtlib_parser->get_benchmark()->get_num_formulas()) { ast * f = mk_c(c)->m_smtlib_parser->get_benchmark()->begin_formulas()[i]; mk_c(c)->save_ast_trail(f); RETURN_Z3(of_ast(f)); } else { SET_ERROR_CODE(Z3_IOB); } } else { SET_ERROR_CODE(Z3_NO_PARSER); } RETURN_Z3(0); Z3_CATCH_RETURN(0); } unsigned Z3_API Z3_get_smtlib_num_assumptions(Z3_context c) { Z3_TRY; LOG_Z3_get_smtlib_num_assumptions(c); RESET_ERROR_CODE(); if (mk_c(c)->m_smtlib_parser) { return mk_c(c)->m_smtlib_parser->get_benchmark()->get_num_axioms(); } SET_ERROR_CODE(Z3_NO_PARSER); return 0; Z3_CATCH_RETURN(0); } Z3_ast Z3_API Z3_get_smtlib_assumption(Z3_context c, unsigned i) { Z3_TRY; LOG_Z3_get_smtlib_assumption(c, i); RESET_ERROR_CODE(); if (mk_c(c)->m_smtlib_parser) { if (i < mk_c(c)->m_smtlib_parser->get_benchmark()->get_num_axioms()) { ast * a = mk_c(c)->m_smtlib_parser->get_benchmark()->begin_axioms()[i]; mk_c(c)->save_ast_trail(a); RETURN_Z3(of_ast(a)); } else { SET_ERROR_CODE(Z3_IOB); } } else { SET_ERROR_CODE(Z3_NO_PARSER); } RETURN_Z3(0); Z3_CATCH_RETURN(0); } unsigned Z3_API Z3_get_smtlib_num_decls(Z3_context c) { Z3_TRY; LOG_Z3_get_smtlib_num_decls(c); RESET_ERROR_CODE(); if (mk_c(c)->m_smtlib_parser) { mk_c(c)->extract_smtlib_parser_decls(); return mk_c(c)->m_smtlib_parser_decls.size(); } SET_ERROR_CODE(Z3_NO_PARSER); return 0; Z3_CATCH_RETURN(0); } Z3_func_decl Z3_API Z3_get_smtlib_decl(Z3_context c, unsigned i) { Z3_TRY; LOG_Z3_get_smtlib_decl(c, i); RESET_ERROR_CODE(); mk_c(c)->extract_smtlib_parser_decls(); if (mk_c(c)->m_smtlib_parser) { if (i < mk_c(c)->m_smtlib_parser_decls.size()) { func_decl * d = mk_c(c)->m_smtlib_parser_decls[i]; mk_c(c)->save_ast_trail(d); RETURN_Z3(of_func_decl(d)); } else { SET_ERROR_CODE(Z3_IOB); } } else { SET_ERROR_CODE(Z3_NO_PARSER); } RETURN_Z3(0); Z3_CATCH_RETURN(0); } unsigned Z3_API Z3_get_smtlib_num_sorts(Z3_context c) { Z3_TRY; LOG_Z3_get_smtlib_num_sorts(c); RESET_ERROR_CODE(); if (mk_c(c)->m_smtlib_parser) { mk_c(c)->extract_smtlib_parser_decls(); return mk_c(c)->m_smtlib_parser_sorts.size(); } SET_ERROR_CODE(Z3_NO_PARSER); return 0; Z3_CATCH_RETURN(0); } Z3_sort Z3_API Z3_get_smtlib_sort(Z3_context c, unsigned i) { Z3_TRY; LOG_Z3_get_smtlib_sort(c, i); RESET_ERROR_CODE(); if (mk_c(c)->m_smtlib_parser) { mk_c(c)->extract_smtlib_parser_decls(); if (i < mk_c(c)->m_smtlib_parser_sorts.size()) { sort* s = mk_c(c)->m_smtlib_parser_sorts[i]; mk_c(c)->save_ast_trail(s); RETURN_Z3(of_sort(s)); } else { SET_ERROR_CODE(Z3_IOB); } } else { SET_ERROR_CODE(Z3_NO_PARSER); } RETURN_Z3(0); Z3_CATCH_RETURN(0); } Z3_string Z3_API Z3_get_smtlib_error(Z3_context c) { Z3_TRY; LOG_Z3_get_smtlib_error(c); RESET_ERROR_CODE(); return mk_c(c)->m_smtlib_error_buffer.c_str(); Z3_CATCH_RETURN(""); } // --------------- // Support for SMTLIB2 Z3_ast parse_smtlib2_stream(bool exec, Z3_context c, std::istream& is, unsigned num_sorts, Z3_symbol const sort_names[], Z3_sort const sorts[], unsigned num_decls, Z3_symbol const decl_names[], Z3_func_decl const decls[]) { Z3_TRY; scoped_ptr<cmd_context> ctx = alloc(cmd_context, false, &(mk_c(c)->m())); ctx->set_ignore_check(true); for (unsigned i = 0; i < num_decls; ++i) { ctx->insert(to_symbol(decl_names[i]), to_func_decl(decls[i])); } for (unsigned i = 0; i < num_sorts; ++i) { psort* ps = ctx->pm().mk_psort_cnst(to_sort(sorts[i])); ctx->insert(ctx->pm().mk_psort_user_decl(0, to_symbol(sort_names[i]), ps)); } if (!parse_smt2_commands(*ctx.get(), is)) { ctx = nullptr; SET_ERROR_CODE(Z3_PARSER_ERROR); return of_ast(mk_c(c)->m().mk_true()); } ptr_vector<expr>::const_iterator it = ctx->begin_assertions(); ptr_vector<expr>::const_iterator end = ctx->end_assertions(); unsigned size = static_cast<unsigned>(end - it); return of_ast(mk_c(c)->mk_and(size, it)); Z3_CATCH_RETURN(0); } Z3_ast Z3_API Z3_parse_smtlib2_string(Z3_context c, Z3_string str, unsigned num_sorts, Z3_symbol const sort_names[], Z3_sort const sorts[], unsigned num_decls, Z3_symbol const decl_names[], Z3_func_decl const decls[]) { Z3_TRY; LOG_Z3_parse_smtlib2_string(c, str, num_sorts, sort_names, sorts, num_decls, decl_names, decls); std::string s(str); std::istringstream is(s); Z3_ast r = parse_smtlib2_stream(false, c, is, num_sorts, sort_names, sorts, num_decls, decl_names, decls); RETURN_Z3(r); Z3_CATCH_RETURN(0); } Z3_ast Z3_API Z3_parse_smtlib2_file(Z3_context c, Z3_string file_name, unsigned num_sorts, Z3_symbol const sort_names[], Z3_sort const sorts[], unsigned num_decls, Z3_symbol const decl_names[], Z3_func_decl const decls[]) { Z3_TRY; LOG_Z3_parse_smtlib2_string(c, file_name, num_sorts, sort_names, sorts, num_decls, decl_names, decls); std::ifstream is(file_name); if (!is) { SET_ERROR_CODE(Z3_PARSER_ERROR); return 0; } Z3_ast r = parse_smtlib2_stream(false, c, is, num_sorts, sort_names, sorts, num_decls, decl_names, decls); RETURN_Z3(r); Z3_CATCH_RETURN(0); } };
[ "wslee@ropas.snu.ac.kr" ]
wslee@ropas.snu.ac.kr
ddd8961a55036f25d66655cbd47213ec447b7e11
bbfc7ed9d8e68c82d9c5b4be0ef55372f7d2afbf
/src/Image/Temp.cpp
ea17132bc0662b30c51e34738d964eb877bf85fa
[ "MIT" ]
permissive
blockspacer/NGServer
c0c808c688eedf239759dba0f56e7973f2b288c4
fe10ec1092cf1f14a5f04268cffa19ea170f677a
refs/heads/master
2021-03-17T13:54:40.458141
2018-03-18T16:54:09
2018-03-18T16:54:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,357
cpp
//#include <iostream> // //#include <GLFW/glfw3.h> //#include <GLFW/glfw3.h> // //using namespace std; // //void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode); // //const GLuint WIDTH = 800, HEIGHT = 600; // //int main() //{ // cout << "Starting GLFW context, OpenGL3.3" << endl; // glfwInit(); // glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // // GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", NULL, NULL); // if(window == NULL) // { // std::cout << "Failed to create GLFW window" << std::endl; // glfwTerminate(); // return -1; // } // // glViewport(0, 0, WIDTH, HEIGHT); // // while(!glfwWindowShouldClose(window)) // { // glfwPollEvents(); // // glClearColor(0.2f, 0.3f, 0.3f, 1.0f); // glClear(GL_COLOR_BUFFER_BIT); // // glfwSwapBuffers(window); // } // // glfwTerminate(); // // return 0; //} // //void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) //{ // std::cout << key << std::endl; // if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) // glfwSetWindowShouldClose(window, GL_TRUE); //}
[ "cwj5012@gmail.com" ]
cwj5012@gmail.com
baf43b342cb66702dda805c56266db7313512cad
289b0ae4e33e7bbd3729879bd6340c0bf308d930
/src/parsing.h
82ebcde3480e945687bf545846a1dc40ec164da4
[ "Apache-2.0" ]
permissive
i04n/openrtbpp
b092faf591c386ef5de6af6ce5643e63aee700a7
262d3b72cfed4a4dcaf1b37f6d45dc32f3169a6f
refs/heads/master
2021-01-01T20:36:35.663332
2015-08-02T01:24:30
2015-08-02T01:24:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
262
h
/* parsing.h Mathieu Stefani, 01 August 2015 JSON Parser for OpenRTB */ #include <rapidjson/rapidjson.h> #pragma once #include <memory> #include "openrtb.h" std::unique_ptr<OpenRTB::BidRequest> parseBidRequest(const rapidjson::Document& document);
[ "mathieu.stefani@supinfo.com" ]
mathieu.stefani@supinfo.com
13b71fa92f57ee40d978b7a8d2238a8d04f02ef2
51d90e35cb0dbb988cbcdb58ad410333c9c26ba6
/WordJumble/main.cpp
e7de69ea336de1043e75a20febb14e633a84f01b
[]
no_license
walsh707/C-PlusPlus
f4b437a85a13acea7a25c760e470256fd2e26ebb
5f6697aa782258fc51f2857fb1b356c3317aafc5
refs/heads/master
2021-01-01T03:38:54.030120
2016-05-18T15:42:24
2016-05-18T15:42:24
59,127,528
0
0
null
null
null
null
UTF-8
C++
false
false
3,151
cpp
// Word Jumble #include <iostream> #include <string> #include <cstdlib> #include <ctime> using namespace std; int main() { string guess; int wordpoints; char another; enum fields {WORD, HINT, NUM_FIELDS}; const int NUM_WORDS = 5; const int MAX_GUESSES = 5; const string WORDS[NUM_WORDS][NUM_FIELDS] = { {"astronaut", "They fly into space"}, {"star", "The sun is one of them."}, {"anime", "Japanese cartoons"}, {"sword", "It's dangerous to go alone take this"}, {"dragon", "They breath fire."} }; srand(time(0)); int choice = (rand() % NUM_WORDS); string theWord = WORDS[choice][WORD]; // word to guess string theHint = WORDS[choice][HINT]; // hint for word string jumble = theWord; // jumbled version of word int length = jumble.size(); for (int i=0; i<length; ++i) { int index1 = (rand() % length); int index2 = (rand() % length); char temp = jumble[index1]; jumble[index1] = jumble[index2]; jumble[index2] = temp; } cout << "\t\t\tWelcome to Word Jumble!\n\n"; cout << "Solve the mixed up word.\n"; cout << "Enter 'hint' for a hint. Note: You will lose one point.\n"; cout << "Enter 'quit' to quit the game.\n\n"; bool done = false; do { int points = 0; choice = (rand() % NUM_WORDS); theWord = WORDS[choice][WORD]; // word to guess theHint = WORDS[choice][HINT]; // hint for word jumble = theWord; // jumbled version of word length = jumble.size(); for (int i = 0; i < length; ++i) { int index1 = (rand() % length); int index2 = (rand() % length); char temp = jumble[index1]; jumble[index1] = jumble[index2]; jumble[index2] = temp; } cout << "The jumble is: " << jumble; bool match = false; for(int nIndex = 0; (nIndex < MAX_GUESSES) && !match ; nIndex++) { cout << "\n\nGuess " << nIndex+1 << ": "; cin >> guess; if (guess == "hint") { cout << theHint; points--; //subtract 1 point }//end if else if (guess == "quit") { cout << "\nGood bye!\n"; break; } else if (guess == theWord) { cout << "\nWell done!\n"; wordpoints = guess.size(); points += wordpoints; //points = # of letters in word cout << "Number Points for this word is " << wordpoints << endl; match = true; }//end else if else { cout << "Sorry, that is incorrect."; }//end else }//end for cout << "\n\nYour Total Points Are: " << points; cout << "\n\n\nWould You Like To Play Again? (y/n): "; cin >> another; system("cls"); if (another == 'n') { done = true; } } while(!done); cout << "Thanks for playing!"<< endl; system("pause"); return 0; }//end main
[ "jason.walsh@live.com" ]
jason.walsh@live.com
846d0d35f859ab6995f9020a0a237cc8ed413eaa
ce4a3f0f6fad075b6bd2fe7d84fd9b76b9622394
/CLMTSMeshFileLoader.h
77463db7ca62f4c4fb43d7eb60507eb4595e8153
[]
no_license
codetiger/IrrNacl
c630187dfca857c15ebfa3b73fd271ef6bad310f
dd0bda2fb1c2ff46813fac5e11190dc87f83add7
refs/heads/master
2021-01-13T02:10:24.919588
2012-07-22T06:27:29
2012-07-22T06:27:29
4,461,459
5
2
null
null
null
null
UTF-8
C++
false
false
2,561
h
// Copyright (C) 2002-2011 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h // // I (Nikolaus Gebhardt) did some few changes to Jonas Petersen's original loader: // - removed setTexturePath() and replaced with the ISceneManager::getStringParameter()-stuff. // - added EAMT_LMTS enumeration value // Thanks a lot to Jonas Petersen for his work // on this and that he gave me his permission to add it into Irrlicht. /* CLMTSMeshFileLoader.h LMTSMeshFileLoader Written by Jonas Petersen (a.k.a. jox) Version 1.5 - 15 March 2005 */ #if !defined(__C_LMTS_MESH_FILE_LOADER_H_INCLUDED__) #define __C_LMTS_MESH_FILE_LOADER_H_INCLUDED__ #include "IMeshLoader.h" #include "SMesh.h" #include "IFileSystem.h" #include "IVideoDriver.h" namespace irr { namespace scene { class CLMTSMeshFileLoader : public IMeshLoader { public: CLMTSMeshFileLoader(io::IFileSystem* fs, video::IVideoDriver* driver, io::IAttributes* parameters); virtual ~CLMTSMeshFileLoader(); virtual bool isALoadableFileExtension(const io::path& filename) const; virtual IAnimatedMesh* createMesh(io::IReadFile* file); private: void constructMesh(SMesh* mesh); void loadTextures(SMesh* mesh); void cleanup(); // byte-align structures #if defined(_MSC_VER) || defined(__BORLANDC__) || defined (__BCPLUSPLUS__) # pragma pack( push, packing ) # pragma pack( 1 ) # define PACK_STRUCT #elif defined( __GNUC__ ) # define PACK_STRUCT __attribute__((packed)) #else # error compiler not supported #endif struct SLMTSHeader { u32 MagicID; u32 Version; u32 HeaderSize; u16 TextureCount; u16 SubsetCount; u32 TriangleCount; u16 SubsetSize; u16 VertexSize; } PACK_STRUCT; struct SLMTSTextureInfoEntry { c8 Filename[256]; u16 Flags; } PACK_STRUCT; struct SLMTSSubsetInfoEntry { u32 Offset; u32 Count; u16 TextID1; u16 TextID2; } PACK_STRUCT; struct SLMTSTriangleDataEntry { f32 X; f32 Y; f32 Z; f32 U1; f32 V1; f32 U2; f32 V2; } PACK_STRUCT; // Default alignment #if defined(_MSC_VER) || defined(__BORLANDC__) || defined (__BCPLUSPLUS__) # pragma pack( pop, packing ) #endif #undef PACK_STRUCT SLMTSHeader Header; SLMTSTextureInfoEntry* Textures; SLMTSSubsetInfoEntry* Subsets; SLMTSTriangleDataEntry* Triangles; io::IAttributes* Parameters; video::IVideoDriver* Driver; io::IFileSystem* FileSystem; bool FlipEndianess; }; } // end namespace scene } // end namespace irr #endif // !defined(__C_LMTS_MESH_FILE_LOADER_H_INCLUDED__)
[ "smackallgames@smackall-2bbd93.(none)" ]
smackallgames@smackall-2bbd93.(none)
1c0aa0e3942221b02ec1205ca062f45e04eea2a7
3e1e10fc80793bdedcda0d41c0d347ca2c9db595
/Volume02/0227/c++.cpp
1efa364862357cb8dc64de11a83b93c510bb6d81
[]
no_license
mkut/aoj
9a11999c113bc9fda6157ca174ebfb14e3af14ce
1a088f15621c72c9f9d0c9ad0030cb8547b3e66e
refs/heads/master
2016-09-05T11:17:48.734650
2013-07-13T13:18:06
2013-07-13T13:18:06
2,236,868
0
0
null
null
null
null
UTF-8
C++
false
false
388
cpp
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> using namespace std; int main() { int n, m; while(cin >> n >> m, n) { vector<int> price(n); for(int i = 0; i < n; i++) cin >> price[i]; sort(price.begin(), price.end()); int ans = 0; for(int i = 0; i < n; i++) if(i % m != m-1) ans += price[n-1-i]; cout << ans << endl; } return 0; }
[ "mkut@mkut-pc.(none)" ]
mkut@mkut-pc.(none)
32a4d1c086b5d811bbed1f7b3f13bb34cec25ad8
149baeb6eaaad68efd03fd323f273de4d7911bff
/dd_v1/include/utilcxx/task.h
6ff417f6243b7c6e865aad2351ef8c6feba24b1a
[]
no_license
lxgithub24/cppProjects
33e04275395c5f07adb4fbcbfbbc3be80117fda3
4a6492e49dc50816651cc5e09570861966bab28b
refs/heads/master
2020-07-09T08:04:35.803972
2019-08-23T04:03:42
2019-08-23T04:03:42
203,921,478
0
0
null
null
null
null
UTF-8
C++
false
false
654
h
/** * @file task.h * @author lishilong(com@baidu.com) * @date 2013/08/07 09:58:07 * @brief * **/ #ifndef __SPEECH_UTIL_TASK_H_ #define __SPEECH_UTIL_TASK_H_ #include<pthread.h> namespace speech { namespace util { class Task { public: explicit Task(int channel):channel_(channel){ } virtual ~Task(){ } virtual void handle(){}; void runHandle() { pthread_testcancel(); handle(); pthread_testcancel(); } inline int channel() { return channel_; } protected: int channel_; }; } } #endif //__TASK_H_ /* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */
[ "xiang.liu@ymm56.com" ]
xiang.liu@ymm56.com
fc3c81ea513fdc6bc5c2c6086a0c2e0ff165aa50
30d50e10785d42fc93f51d3cfa60b45190aa338b
/greeter_async_server.cc
ceaaba9834d269ea728a4334eeff98d705afb355
[]
no_license
etrirepo/grpcclient
581c6ce3848f1ae0299cc4846f694e3abe4ceb0b
443e3b31f9f513ede8941acfd22b0f1aecb4d15f
refs/heads/master
2023-05-29T10:49:42.898096
2021-06-17T02:00:52
2021-06-17T02:00:52
377,673,890
0
0
null
null
null
null
UTF-8
C++
false
false
5,885
cc
/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <iostream> #include <memory> #include <string> #include <thread> #include <grpc/support/log.h> #include <grpcpp/grpcpp.h> #ifdef BAZEL_BUILD #include "examples/protos/bossopenolt.grpc.pb.h" #else #include "bossopenolt.grpc.pb.h" #endif using grpc::Server; using grpc::ServerAsyncResponseWriter; using grpc::ServerBuilder; using grpc::ServerCompletionQueue; using grpc::ServerContext; using grpc::Status; using bossopenolt::Greeter; using bossopenolt::HelloReply; using bossopenolt::HelloRequest; class ServerImpl final { public: ~ServerImpl() { server_->Shutdown(); // Always shutdown the completion queue after the server. cq_->Shutdown(); } // There is no shutdown handling in this code. void Run() { std::string server_address("0.0.0.0:50051"); ServerBuilder builder; // Listen on the given address without any authentication mechanism. builder.AddListeningPort(server_address, grpc::InsecureServerCredentials()); // Register "service_" as the instance through which we'll communicate with // clients. In this case it corresponds to an *asynchronous* service. builder.RegisterService(&service_); // Get hold of the completion queue used for the asynchronous communication // with the gRPC runtime. cq_ = builder.AddCompletionQueue(); // Finally assemble the server. server_ = builder.BuildAndStart(); std::cout << "Server listening on " << server_address << std::endl; // Proceed to the server's main loop. HandleRpcs(); } private: // Class encompasing the state and logic needed to serve a request. class CallData { public: // Take in the "service" instance (in this case representing an asynchronous // server) and the completion queue "cq" used for asynchronous communication // with the gRPC runtime. CallData(Greeter::AsyncService* service, ServerCompletionQueue* cq) : service_(service), cq_(cq), responder_(&ctx_), status_(CREATE) { // Invoke the serving logic right away. Proceed(); } void Proceed() { if (status_ == CREATE) { // Make this instance progress to the PROCESS state. status_ = PROCESS; // As part of the initial CREATE state, we *request* that the system // start processing SayHello requests. In this request, "this" acts are // the tag uniquely identifying the request (so that different CallData // instances can serve different requests concurrently), in this case // the memory address of this CallData instance. service_->RequestSayHello(&ctx_, &request_, &responder_, cq_, cq_, this); } else if (status_ == PROCESS) { // Spawn a new CallData instance to serve new clients while we process // the one for this CallData. The instance will deallocate itself as // part of its FINISH state. new CallData(service_, cq_); // The actual processing. std::string prefix("Hello "); reply_.set_message(prefix + request_.name()); // And we are done! Let the gRPC runtime know we've finished, using the // memory address of this instance as the uniquely identifying tag for // the event. status_ = FINISH; responder_.Finish(reply_, Status::OK, this); } else { GPR_ASSERT(status_ == FINISH); // Once in the FINISH state, deallocate ourselves (CallData). delete this; } } private: // The means of communication with the gRPC runtime for an asynchronous // server. Greeter::AsyncService* service_; // The producer-consumer queue where for asynchronous server notifications. ServerCompletionQueue* cq_; // Context for the rpc, allowing to tweak aspects of it such as the use // of compression, authentication, as well as to send metadata back to the // client. ServerContext ctx_; // What we get from the client. HelloRequest request_; // What we send back to the client. HelloReply reply_; // The means to get back to the client. ServerAsyncResponseWriter<HelloReply> responder_; // Let's implement a tiny state machine with the following states. enum CallStatus { CREATE, PROCESS, FINISH }; CallStatus status_; // The current serving state. }; // This can be run in multiple threads if needed. void HandleRpcs() { // Spawn a new CallData instance to serve new clients. new CallData(&service_, cq_.get()); void* tag; // uniquely identifies a request. bool ok; while (true) { // Block waiting to read the next event from the completion queue. The // event is uniquely identified by its tag, which in this case is the // memory address of a CallData instance. // The return value of Next should always be checked. This return value // tells us whether there is any kind of event or cq_ is shutting down. GPR_ASSERT(cq_->Next(&tag, &ok)); GPR_ASSERT(ok); static_cast<CallData*>(tag)->Proceed(); } } std::unique_ptr<ServerCompletionQueue> cq_; Greeter::AsyncService service_; std::unique_ptr<Server> server_; }; int main(int argc, char** argv) { ServerImpl server; server.Run(); return 0; }
[ "yun.dh@deltaindex.kr" ]
yun.dh@deltaindex.kr
1dede56c25cb2f5f2874643c97890dee5eaaf20e
fdb673fad1d80b394bdd2bcc9ee7bd35c850cf9d
/scripts/ppi-benchmark/Parsing/Charniak-Lease-2006Aug-reranking-parser/reranking-parser/first-stage/TRAIN/FeatIter.h
89c1ca5815342d1121cb60257d46a6ce47db729e
[ "LicenseRef-scancode-warranty-disclaimer", "ISC", "LicenseRef-scancode-public-domain" ]
permissive
KerstenDoering/CPI-Pipeline
1f12c6c2502805f6f0dfbabd7ba9699e3e6faeec
18f0b3473defac31f16d25cf03fc8888ea71e769
refs/heads/master
2023-03-02T20:52:44.589714
2021-11-10T12:35:02
2021-11-10T12:35:02
51,505,375
5
4
NOASSERTION
2019-05-24T15:16:32
2016-02-11T09:36:34
GAP
UTF-8
C++
false
false
1,462
h
/* * Copyright 1999, 2005 Brown University, Providence, RI. * * All Rights Reserved * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose other than its incorporation into a * commercial product is hereby granted without fee, provided that the * above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of Brown University not be used in * advertising or publicity pertaining to distribution of the software * without specific, written prior permission. * * BROWN UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ANY * PARTICULAR PURPOSE. IN NO EVENT SHALL BROWN UNIVERSITY BE LIABLE FOR * ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef FEATITER_H #define FEATITER_H #include "Feat.h" #include "FeatTreeIter.h" class FeatIter { public: FeatIter(FeatureTree* ft); void next(); int alive() { return alive_; } Feat* curr; private: FeatTreeIter fti; FeatMap::iterator fmi; int alive_; }; #endif /* ! FEATITER_H */
[ "kersten.doering@gmail.com" ]
kersten.doering@gmail.com
060562a7655eee661185c1bdcd54e184e3080951
17794af41d7aa1ed249cb2081094d20a9e6d95bb
/AudioSource.cc
12e380edb19e5e98d49c409c8b99f33e037f84e4
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
chrissamuel/simple-audio-correlator
903f0b63c09b5987d2f2161d58bee6ba43b90cdc
a7eede0f665e45e8c358d9242d123c735a941a64
refs/heads/master
2021-01-18T17:25:36.831195
2015-04-18T10:25:22
2015-04-18T10:25:22
34,146,626
0
1
null
null
null
null
UTF-8
C++
false
false
5,666
cc
// // Copyright (C) David Brodrick, 2002 // // 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, version 2. // // $Id: AudioSource.cc,v 1.3 2003/08/27 13:02:12 bro764 Exp brodo $ //Thread to read raw data from the sound card and write it to an output //buffer. This multi-threaded scheme helps to ensure we capture as much //audio as possible - while the processor thread is busy calculating //correlation functions and Fourier transforms this thread is already busy //recording the next batch of raw audio data. #include <AudioSource.h> #include <IntegPeriod.h> #include <iostream> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <errno.h> #include <sys/soundcard.h> #include <stdio.h> #include <unistd.h> #include <assert.h> #include <sys/time.h> #include <time.h> /////////////////////////////////////////////////////////////////////// //Constructor AudioSource::AudioSource(const char *device, Buf<IntegPeriod*> *buf) :itsOutputBuf(buf), itsDevice(device), itsValid(true), itsSampRate(8000), itsIntegPeriod(1000) { ThreadedObject(); if (device==0) { itsSimulate = true; } else { //Try to open the audio device if ((itsFD = open(device, O_RDONLY, 0))==-1) { //Error, could not open the audio device perror(itsDevice); itsValid = false; } //Reset the sound card ioctl(itsFD, SNDCTL_DSP_RESET, 0); //Set audio format, 16 bits int audformat = AFMT_S16_LE; int temp = audformat; if (ioctl(itsFD, SNDCTL_DSP_SETFMT, &temp)==-1) { //Error, could not obtain desired format perror(itsDevice); itsValid = false; } if (temp!=audformat) { cerr << "AUDIO: ERROR: Audio format is not supported\n"; itsValid = false; } } //Configure the default sampling rate setSampRate(itsSampRate); //Set the default integration length (length of audio output) setIntegPeriod(itsIntegPeriod); #ifdef DEBUG_AUDIO cerr << "Audio Device Initialised\n"; #endif } /////////////////////////////////////////////////////////////////////// //Destructor AudioSource::~AudioSource() { //Close the audio device close(itsFD); } /////////////////////////////////////////////////////////////////////// //Main loop of execution for audio grabbing thread void AudioSource::run() { bool error = false; //On some sound cards the first few reads return rubbish so we //do a few dummy reads here before we start collecting data. if (!itsSimulate) { audio_t splutter[512]; for (int i=0; i<10 && !error; i++) { if (read(itsFD, (void*)splutter, 1024)==-1) { perror(itsDevice); error = true; } } } //Main data collection loop while (itsKeepRunning && !error) { //Allocate memory to hold the audio for the next period audio_t *tempdata = new audio_t[itsLength]; //Create the next IntegPeriod and configure it IntegPeriod *intper = new IntegPeriod(); intper->audioLen = itsLength/2; //Because there are 2 channels intper->rawAudio = tempdata; intper->timeStamp = getTime(); //Timestamp at start of period //Read the actual audio data from the audio device if (itsSimulate) {sleep(1);} else { if (read(itsFD, (void*)tempdata, 2*itsLength)==-1) { perror(itsDevice); error = true; } } //Insert the new data in our output buffer itsOutputBuf->put(intper); cout << "." << flush; } //Kill our thread, we have finished itsKeepRunning = false; pthread_exit(NULL); } /////////////////////////////////////////////////////////////////////// //Configure the sampling rate, returns actual rate obtained int AudioSource::setSampRate(int hz) { int res = hz; if (!itsSimulate) { //Configure the sampling rate of the audio device if (ioctl(itsFD, SNDCTL_DSP_SPEED, &hz)==-1) { perror(itsDevice); itsValid = false; res = -1; } else { itsSampRate = hz; res = hz; } } #ifdef DEBUG_AUDIO cerr << "AUDIO: Got " << hz << " Hz sampling rate\n"; #endif return res; } /////////////////////////////////////////////////////////////////////// //Set the number of channels, 1 or 2 bool AudioSource::setChannels(int num) { bool res = true; num -= 1; if (!itsSimulate) { if (ioctl(itsFD, SNDCTL_DSP_STEREO, &num)==-1) { perror(itsDevice); res = itsValid = false; } } return res; } /////////////////////////////////////////////////////////////////////// //Set the duration, in milliseconds, of each block of audio output void AudioSource::setIntegPeriod(int ms) { assert(ms>1); //If the sampling rate is accurate, each sample takes 1000/samprate ms float eachsamp = 1000/(float)itsSampRate; //Hence we want this many samples for each output block itsLength = 2*static_cast<int>(ms/eachsamp); //Ensure even length for stereo capture if (itsLength%1) itsLength++; #ifdef DEBUG_AUDIO cerr << "AUDIO: Set output length to " << itsLength << " samples\n"; #endif } /////////////////////////////////////////////////////////////////////// //Return true if hardware is configured and the thread is ready to run bool AudioSource::isValid() { return itsValid; } /////////////////////////////////////////////////////////////////////// //Return the time as microseonds since the epoch long long AudioSource::getTime() { struct timeval tv = {0,0}; long long res; //Get current time from the system gettimeofday(&tv, 0); //Convert to 64 bit res = 1000000*(long long)(tv.tv_sec) + tv.tv_usec; return res; }
[ "brodrick@c15a0e4a-5d48-0410-bc08-dd38e7c13328" ]
brodrick@c15a0e4a-5d48-0410-bc08-dd38e7c13328
1ce06335948b0c2ca54022e71cec932f703fcf20
207f876b14cc9818a90544e87911977f223c6bfb
/src/directed_graph.cpp
1b104b4236eb3cfa3badf8db0dfda7a6b4576d87
[]
no_license
mbouzid/topological_sorting
27204f75a7d9d2558b17387219420476099914e7
d2231ab79ecf949830263532ea974e851b329d29
refs/heads/master
2021-01-10T07:32:20.422772
2016-03-04T21:12:09
2016-03-04T21:12:09
51,691,946
2
0
null
null
null
null
UTF-8
C++
false
false
354
cpp
#include "directed_graph.hpp" unsigned int min_index( std::set<vertex> queue , int dist[] , unsigned int n ) { int imin = (*queue.begin()).get_label() ; for ( auto i = queue.begin() ; i!= queue.end() ; ++i ) { if ( dist[(*i).get_label()] < dist[imin] ) { imin= (*i).get_label(); } } return imin; } template class directed_graph<int> ;
[ "mariam.bouzid@icloud.com" ]
mariam.bouzid@icloud.com
a3ff453b3bb8d60552b61d25f657fb1dca8a6148
9d615fed609c890c54f00bff22fe6decaca6d8ea
/src/algorithm/coveringarray.cpp
333c32d4f81761ac0770c9a22783c9368dd86c2d
[]
no_license
mstegmaier/inviwo-property-based-testing
0daa1a3224239fcda8fb2500ea3e10daae4475d3
97f0a895221448563caf99e3262c2daff130e084
refs/heads/master
2023-01-23T02:14:57.355573
2020-12-03T10:32:27
2020-12-03T10:32:27
318,154,927
0
0
null
null
null
null
UTF-8
C++
false
false
7,057
cpp
#include <inviwo/propertybasedtesting/algorithm/coveringarray.h> #include <random> namespace inviwo { namespace util { // 2-coverage, randomized discrete SLJ strategy std::vector<Test> coveringArray(const Test& init, const std::vector<std::vector< std::shared_ptr<PropertyAssignment> >>& vars) { srand(42); // deterministic for regression testing std::cerr << "coveringArray: vars.size() = " << vars.size() << std::endl; assert(vars.size() > 0); // special case if(vars.size() == 1) { std::vector<Test> res(vars[0].size(), init); for(size_t i = 0; i < vars[0].size(); i++) { res[i].emplace_back(vars[0][i]); } std::cerr << "special case : res.size() = " << res.size() << std::endl; return res; } const size_t v = [&](){ size_t res = 0; for(const auto& v : vars) res = std::max(res, v.size()); return res; }(); std::unordered_set<size_t> uncovered; std::map< std::array<size_t,4>, size_t > idx; for(size_t i = 1; i < vars.size(); i++) { for(size_t j = 0; j < i; j++) { for(size_t ii = 0; ii < vars[i].size(); ii++) { for(size_t ji = 0; ji < vars[j].size(); ji++) { uncovered.insert(idx.size()); idx[{i,j,ii,ji}] = idx.size(); } } } } std::vector<std::vector<size_t>> coveringArray; while(!uncovered.empty()) { size_t expectedCoverage = (uncovered.size() + (v*v-1)) / (v*v); // expectedCoverage > 0 size_t coverage; std::vector<size_t> row(vars.size()); do { for(size_t i = 0; i < row.size(); i++) row[i] = rand() % vars[i].size(); coverage = 0; // number of uncovered interactions for(size_t i = 1; i < vars.size(); i++) { for(size_t j = 0; j < i; j++) { size_t id = idx[{i,j,row[i],row[j]}]; coverage += uncovered.count(id); } } } while(coverage < expectedCoverage); for(size_t i = 1; i < vars.size(); i++) { for(size_t j = 0; j < i; j++) { size_t id = idx[{i,j,row[i],row[j]}]; uncovered.erase(id); } } coveringArray.emplace_back(row); } // contruct result std::vector<Test> res(coveringArray.size(), init); for(size_t c = 0; c < coveringArray.size(); c++) { for(size_t i = 0; i < vars.size(); i++) { res[c].emplace_back( vars[i][coveringArray[c][i]] ); } } size_t naive = 0; for(size_t i = 1; i < vars.size(); i++) for(size_t j = 0; j < i; j++) naive += vars[i].size() * vars[j].size(); std::cerr << "size reduction: " << naive << " => " << res.size() << std::endl; return res; } std::vector<Test> optCoveringArray(const size_t num, const Test& init, const std::vector< std::pair< std::function<std::optional<util::PropertyEffect>( const std::shared_ptr<PropertyAssignment>& oldVal, const std::shared_ptr<PropertyAssignment>& newVal)>, std::vector< std::shared_ptr<PropertyAssignment> > > >& vars) { srand(42); // deterministic for regression testing std::cerr << "optCoveringArray: vars.size() = " << vars.size() << std::endl; for(const auto&[cmp,var] : vars) { for(const auto& as : var) { as->print(std::cerr << "\t"); std::cerr << std::endl; } std::cerr << std::endl; } assert(vars.size() > 0); // special case if(vars.size() == 1) { std::vector<Test> res(vars[0].second.size(), init); for(size_t i = 0; i < vars[0].second.size(); i++) { res[i].emplace_back(vars[0].second[i]); } std::cerr << "special case : res.size() = " << res.size() << std::endl; return res; } using TestConf = std::map<size_t, size_t>; // {var, var_idx}, vars[var][var_idx] std::vector<TestConf> unused; // init for(size_t var = 0; var < vars.size(); var++) for(size_t i = 0; i < vars[var].second.size(); i++) for(size_t var2 = 0; var2 < var; var2++) for(size_t i2 = 0; i2 < vars[var2].second.size(); i2++) unused.emplace_back(std::map<size_t,size_t>{{{var,i}, {var2,i2}}}); std::shuffle(unused.begin(), unused.end(), std::default_random_engine(rand())); std::vector<std::pair<TestConf,size_t>> finished; // {TestConf, current num of other finished comparables} size_t comparisons = 0; // just for debugging // note: assumes that all keys of the second argument are also present in // the first const std::function<bool(const TestConf&, const TestConf&)> comparable = [&](const auto& ref, const auto& vs) { std::optional<util::PropertyEffect> res = {util::PropertyEffect::ANY}; for(const auto&[var,i] : vs) { const auto& j = ref.at(var); const auto& expect = vars[var].first( vars[var].second[i], vars[var].second[j] ); comparisons++; if(!expect) return false; res = util::combine(*expect, *res); if(!res) return false; } return true; }; const std::function<std::vector<size_t>(std::vector<size_t>, const TestConf&)> filterComparables = [&](auto comparables, const auto& test) { for(size_t i = 0; i < comparables.size(); i++) if(!comparable(finished[comparables[i]].first, test)) { comparables[i] = comparables.back(); comparables.pop_back(); i--; } return comparables; }; // combined score of finished comparables when merging ref into gen const std::function<size_t(const bool, const std::vector<size_t>&, const TestConf&, const TestConf&)> cmp = [&](const bool disjoint, const auto& comparables, const auto& gen, const auto& ref) { if(disjoint) { for(const auto&[k,v] : gen) if(ref.count(k) > 0) return static_cast<size_t>(0); } auto test = ref; test.insert(gen.begin(), gen.end()); size_t res = 1; for(const size_t i : filterComparables(comparables, test)) res += 1 + (finished.size() - finished[i].second) * 2; return res; }; while(!unused.empty() && finished.size() < num) { TestConf gen{{unused.back()}}; unused.pop_back(); std::vector<size_t> comparables(finished.size()); std::iota(comparables.begin(), comparables.end(), 0); std::cerr << unused.size() << std::endl; while(gen.size() < vars.size()) { int opt = -1, idx; bool is_unused = false; for(size_t i = 0; i < unused.size(); i++) { const int val = cmp(true, comparables, gen, unused[i]); if(val > opt) opt = val, idx = i, is_unused = true; } for(size_t i = 0; i < finished.size(); i++) { const int val = cmp(false, comparables, gen, finished[i].first); if(val > opt) opt = val, idx = i, is_unused = false; } assert(opt != -1); if(is_unused) { gen.insert(unused[idx].begin(), unused[idx].end()); swap(unused[idx], unused.back()); unused.pop_back(); } else { gen.insert(finished[idx].first.begin(), finished[idx].first.end()); } comparables = filterComparables(comparables, gen); } for(const size_t i : comparables) finished[i].second++; finished.emplace_back(gen, comparables.size()); } std::cerr << comparisons << " comparisons" << std::endl; // build tests std::vector<Test> res; for(const auto& [test,val] : finished) { Test tmp = init; for(const auto&[var,i] : test) tmp.emplace_back(vars[var].second[i]); res.emplace_back(tmp); } return res; } } // namespace util } // namespace inviwo
[ "michael-1.stegmaier@uni-ulm.de" ]
michael-1.stegmaier@uni-ulm.de
0d6f2d06cc331938cda2640d1f6621b2cf02fb70
536656cd89e4fa3a92b5dcab28657d60d1d244bd
/gpu/ipc/common/gpu_info_mojom_traits.cc
44d2ea2ba903dee895b7f36a142e2d62f853b1b3
[ "BSD-3-Clause" ]
permissive
ECS-251-W2020/chromium
79caebf50443f297557d9510620bf8d44a68399a
ac814e85cb870a6b569e184c7a60a70ff3cb19f9
refs/heads/master
2022-08-19T17:42:46.887573
2020-03-18T06:08:44
2020-03-18T06:08:44
248,141,336
7
8
BSD-3-Clause
2022-07-06T20:32:48
2020-03-18T04:52:18
null
UTF-8
C++
false
false
18,774
cc
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gpu/ipc/common/gpu_info_mojom_traits.h" #include "build/build_config.h" #include "base/logging.h" #include "mojo/public/cpp/base/time_mojom_traits.h" #if BUILDFLAG(ENABLE_VULKAN) #include "gpu/ipc/common/vulkan_info_mojom_traits.h" #endif namespace mojo { // static bool StructTraits<gpu::mojom::GpuDeviceDataView, gpu::GPUInfo::GPUDevice>::Read( gpu::mojom::GpuDeviceDataView data, gpu::GPUInfo::GPUDevice* out) { out->vendor_id = data.vendor_id(); out->device_id = data.device_id(); #if defined(OS_WIN) out->sub_sys_id = data.sub_sys_id(); out->revision = data.revision(); #endif // OS_WIN out->active = data.active(); out->cuda_compute_capability_major = data.cuda_compute_capability_major(); return data.ReadVendorString(&out->vendor_string) && data.ReadDeviceString(&out->device_string) && data.ReadDriverVendor(&out->driver_vendor) && data.ReadDriverVersion(&out->driver_version); } // static gpu::mojom::VideoCodecProfile EnumTraits<gpu::mojom::VideoCodecProfile, gpu::VideoCodecProfile>::ToMojom( gpu::VideoCodecProfile video_codec_profile) { switch (video_codec_profile) { case gpu::VideoCodecProfile::VIDEO_CODEC_PROFILE_UNKNOWN: return gpu::mojom::VideoCodecProfile::VIDEO_CODEC_PROFILE_UNKNOWN; case gpu::VideoCodecProfile::H264PROFILE_BASELINE: return gpu::mojom::VideoCodecProfile::H264PROFILE_BASELINE; case gpu::VideoCodecProfile::H264PROFILE_MAIN: return gpu::mojom::VideoCodecProfile::H264PROFILE_MAIN; case gpu::VideoCodecProfile::H264PROFILE_EXTENDED: return gpu::mojom::VideoCodecProfile::H264PROFILE_EXTENDED; case gpu::VideoCodecProfile::H264PROFILE_HIGH: return gpu::mojom::VideoCodecProfile::H264PROFILE_HIGH; case gpu::VideoCodecProfile::H264PROFILE_HIGH10PROFILE: return gpu::mojom::VideoCodecProfile::H264PROFILE_HIGH10PROFILE; case gpu::VideoCodecProfile::H264PROFILE_HIGH422PROFILE: return gpu::mojom::VideoCodecProfile::H264PROFILE_HIGH422PROFILE; case gpu::VideoCodecProfile::H264PROFILE_HIGH444PREDICTIVEPROFILE: return gpu::mojom::VideoCodecProfile:: H264PROFILE_HIGH444PREDICTIVEPROFILE; case gpu::VideoCodecProfile::H264PROFILE_SCALABLEBASELINE: return gpu::mojom::VideoCodecProfile::H264PROFILE_SCALABLEBASELINE; case gpu::VideoCodecProfile::H264PROFILE_SCALABLEHIGH: return gpu::mojom::VideoCodecProfile::H264PROFILE_SCALABLEHIGH; case gpu::VideoCodecProfile::H264PROFILE_STEREOHIGH: return gpu::mojom::VideoCodecProfile::H264PROFILE_STEREOHIGH; case gpu::VideoCodecProfile::H264PROFILE_MULTIVIEWHIGH: return gpu::mojom::VideoCodecProfile::H264PROFILE_MULTIVIEWHIGH; case gpu::VideoCodecProfile::VP8PROFILE_ANY: return gpu::mojom::VideoCodecProfile::VP8PROFILE_ANY; case gpu::VideoCodecProfile::VP9PROFILE_PROFILE0: return gpu::mojom::VideoCodecProfile::VP9PROFILE_PROFILE0; case gpu::VideoCodecProfile::VP9PROFILE_PROFILE1: return gpu::mojom::VideoCodecProfile::VP9PROFILE_PROFILE1; case gpu::VideoCodecProfile::VP9PROFILE_PROFILE2: return gpu::mojom::VideoCodecProfile::VP9PROFILE_PROFILE2; case gpu::VideoCodecProfile::VP9PROFILE_PROFILE3: return gpu::mojom::VideoCodecProfile::VP9PROFILE_PROFILE3; case gpu::VideoCodecProfile::HEVCPROFILE_MAIN: return gpu::mojom::VideoCodecProfile::HEVCPROFILE_MAIN; case gpu::VideoCodecProfile::HEVCPROFILE_MAIN10: return gpu::mojom::VideoCodecProfile::HEVCPROFILE_MAIN10; case gpu::VideoCodecProfile::HEVCPROFILE_MAIN_STILL_PICTURE: return gpu::mojom::VideoCodecProfile::HEVCPROFILE_MAIN_STILL_PICTURE; case gpu::VideoCodecProfile::DOLBYVISION_PROFILE0: return gpu::mojom::VideoCodecProfile::DOLBYVISION_PROFILE0; case gpu::VideoCodecProfile::DOLBYVISION_PROFILE4: return gpu::mojom::VideoCodecProfile::DOLBYVISION_PROFILE4; case gpu::VideoCodecProfile::DOLBYVISION_PROFILE5: return gpu::mojom::VideoCodecProfile::DOLBYVISION_PROFILE5; case gpu::VideoCodecProfile::DOLBYVISION_PROFILE7: return gpu::mojom::VideoCodecProfile::DOLBYVISION_PROFILE7; case gpu::VideoCodecProfile::DOLBYVISION_PROFILE8: return gpu::mojom::VideoCodecProfile::DOLBYVISION_PROFILE8; case gpu::VideoCodecProfile::DOLBYVISION_PROFILE9: return gpu::mojom::VideoCodecProfile::DOLBYVISION_PROFILE9; case gpu::VideoCodecProfile::THEORAPROFILE_ANY: return gpu::mojom::VideoCodecProfile::THEORAPROFILE_ANY; case gpu::VideoCodecProfile::AV1PROFILE_PROFILE_MAIN: return gpu::mojom::VideoCodecProfile::AV1PROFILE_PROFILE_MAIN; case gpu::VideoCodecProfile::AV1PROFILE_PROFILE_HIGH: return gpu::mojom::VideoCodecProfile::AV1PROFILE_PROFILE_HIGH; case gpu::VideoCodecProfile::AV1PROFILE_PROFILE_PRO: return gpu::mojom::VideoCodecProfile::AV1PROFILE_PROFILE_PRO; } NOTREACHED() << "Invalid VideoCodecProfile:" << video_codec_profile; return gpu::mojom::VideoCodecProfile::VIDEO_CODEC_PROFILE_UNKNOWN; } // static bool EnumTraits<gpu::mojom::VideoCodecProfile, gpu::VideoCodecProfile>:: FromMojom(gpu::mojom::VideoCodecProfile input, gpu::VideoCodecProfile* out) { switch (input) { case gpu::mojom::VideoCodecProfile::VIDEO_CODEC_PROFILE_UNKNOWN: *out = gpu::VideoCodecProfile::VIDEO_CODEC_PROFILE_UNKNOWN; return true; case gpu::mojom::VideoCodecProfile::H264PROFILE_BASELINE: *out = gpu::VideoCodecProfile::H264PROFILE_BASELINE; return true; case gpu::mojom::VideoCodecProfile::H264PROFILE_MAIN: *out = gpu::VideoCodecProfile::H264PROFILE_MAIN; return true; case gpu::mojom::VideoCodecProfile::H264PROFILE_EXTENDED: *out = gpu::VideoCodecProfile::H264PROFILE_EXTENDED; return true; case gpu::mojom::VideoCodecProfile::H264PROFILE_HIGH: *out = gpu::VideoCodecProfile::H264PROFILE_HIGH; return true; case gpu::mojom::VideoCodecProfile::H264PROFILE_HIGH10PROFILE: *out = gpu::VideoCodecProfile::H264PROFILE_HIGH10PROFILE; return true; case gpu::mojom::VideoCodecProfile::H264PROFILE_HIGH422PROFILE: *out = gpu::VideoCodecProfile::H264PROFILE_HIGH422PROFILE; return true; case gpu::mojom::VideoCodecProfile::H264PROFILE_HIGH444PREDICTIVEPROFILE: *out = gpu::VideoCodecProfile::H264PROFILE_HIGH444PREDICTIVEPROFILE; return true; case gpu::mojom::VideoCodecProfile::H264PROFILE_SCALABLEBASELINE: *out = gpu::VideoCodecProfile::H264PROFILE_SCALABLEBASELINE; return true; case gpu::mojom::VideoCodecProfile::H264PROFILE_SCALABLEHIGH: *out = gpu::VideoCodecProfile::H264PROFILE_SCALABLEHIGH; return true; case gpu::mojom::VideoCodecProfile::H264PROFILE_STEREOHIGH: *out = gpu::VideoCodecProfile::H264PROFILE_STEREOHIGH; return true; case gpu::mojom::VideoCodecProfile::H264PROFILE_MULTIVIEWHIGH: *out = gpu::VideoCodecProfile::H264PROFILE_MULTIVIEWHIGH; return true; case gpu::mojom::VideoCodecProfile::VP8PROFILE_ANY: *out = gpu::VideoCodecProfile::VP8PROFILE_ANY; return true; case gpu::mojom::VideoCodecProfile::VP9PROFILE_PROFILE0: *out = gpu::VideoCodecProfile::VP9PROFILE_PROFILE0; return true; case gpu::mojom::VideoCodecProfile::VP9PROFILE_PROFILE1: *out = gpu::VideoCodecProfile::VP9PROFILE_PROFILE1; return true; case gpu::mojom::VideoCodecProfile::VP9PROFILE_PROFILE2: *out = gpu::VideoCodecProfile::VP9PROFILE_PROFILE2; return true; case gpu::mojom::VideoCodecProfile::VP9PROFILE_PROFILE3: *out = gpu::VideoCodecProfile::VP9PROFILE_PROFILE3; return true; case gpu::mojom::VideoCodecProfile::HEVCPROFILE_MAIN: *out = gpu::VideoCodecProfile::HEVCPROFILE_MAIN; return true; case gpu::mojom::VideoCodecProfile::HEVCPROFILE_MAIN10: *out = gpu::VideoCodecProfile::HEVCPROFILE_MAIN10; return true; case gpu::mojom::VideoCodecProfile::HEVCPROFILE_MAIN_STILL_PICTURE: *out = gpu::VideoCodecProfile::HEVCPROFILE_MAIN_STILL_PICTURE; return true; case gpu::mojom::VideoCodecProfile::DOLBYVISION_PROFILE0: *out = gpu::VideoCodecProfile::DOLBYVISION_PROFILE0; return true; case gpu::mojom::VideoCodecProfile::DOLBYVISION_PROFILE4: *out = gpu::VideoCodecProfile::DOLBYVISION_PROFILE4; return true; case gpu::mojom::VideoCodecProfile::DOLBYVISION_PROFILE5: *out = gpu::VideoCodecProfile::DOLBYVISION_PROFILE5; return true; case gpu::mojom::VideoCodecProfile::DOLBYVISION_PROFILE7: *out = gpu::VideoCodecProfile::DOLBYVISION_PROFILE7; return true; case gpu::mojom::VideoCodecProfile::DOLBYVISION_PROFILE8: *out = gpu::VideoCodecProfile::DOLBYVISION_PROFILE8; return true; case gpu::mojom::VideoCodecProfile::DOLBYVISION_PROFILE9: *out = gpu::VideoCodecProfile::DOLBYVISION_PROFILE9; return true; case gpu::mojom::VideoCodecProfile::THEORAPROFILE_ANY: *out = gpu::VideoCodecProfile::THEORAPROFILE_ANY; return true; case gpu::mojom::VideoCodecProfile::AV1PROFILE_PROFILE_MAIN: *out = gpu::VideoCodecProfile::AV1PROFILE_PROFILE_MAIN; return true; case gpu::mojom::VideoCodecProfile::AV1PROFILE_PROFILE_HIGH: *out = gpu::VideoCodecProfile::AV1PROFILE_PROFILE_HIGH; return true; case gpu::mojom::VideoCodecProfile::AV1PROFILE_PROFILE_PRO: *out = gpu::VideoCodecProfile::AV1PROFILE_PROFILE_PRO; return true; } NOTREACHED() << "Invalid VideoCodecProfile: " << input; return false; } // static bool StructTraits<gpu::mojom::VideoDecodeAcceleratorSupportedProfileDataView, gpu::VideoDecodeAcceleratorSupportedProfile>:: Read(gpu::mojom::VideoDecodeAcceleratorSupportedProfileDataView data, gpu::VideoDecodeAcceleratorSupportedProfile* out) { out->encrypted_only = data.encrypted_only(); return data.ReadProfile(&out->profile) && data.ReadMaxResolution(&out->max_resolution) && data.ReadMinResolution(&out->min_resolution); } // static bool StructTraits<gpu::mojom::VideoDecodeAcceleratorCapabilitiesDataView, gpu::VideoDecodeAcceleratorCapabilities>:: Read(gpu::mojom::VideoDecodeAcceleratorCapabilitiesDataView data, gpu::VideoDecodeAcceleratorCapabilities* out) { if (!data.ReadSupportedProfiles(&out->supported_profiles)) return false; out->flags = data.flags(); return true; } // static bool StructTraits<gpu::mojom::VideoEncodeAcceleratorSupportedProfileDataView, gpu::VideoEncodeAcceleratorSupportedProfile>:: Read(gpu::mojom::VideoEncodeAcceleratorSupportedProfileDataView data, gpu::VideoEncodeAcceleratorSupportedProfile* out) { out->max_framerate_numerator = data.max_framerate_numerator(); out->max_framerate_denominator = data.max_framerate_denominator(); return data.ReadMinResolution(&out->min_resolution) && data.ReadMaxResolution(&out->max_resolution) && data.ReadProfile(&out->profile); } // static gpu::mojom::ImageDecodeAcceleratorType EnumTraits< gpu::mojom::ImageDecodeAcceleratorType, gpu::ImageDecodeAcceleratorType>::ToMojom(gpu::ImageDecodeAcceleratorType image_type) { switch (image_type) { case gpu::ImageDecodeAcceleratorType::kJpeg: return gpu::mojom::ImageDecodeAcceleratorType::kJpeg; case gpu::ImageDecodeAcceleratorType::kWebP: return gpu::mojom::ImageDecodeAcceleratorType::kWebP; case gpu::ImageDecodeAcceleratorType::kUnknown: return gpu::mojom::ImageDecodeAcceleratorType::kUnknown; } } // static bool EnumTraits<gpu::mojom::ImageDecodeAcceleratorType, gpu::ImageDecodeAcceleratorType>:: FromMojom(gpu::mojom::ImageDecodeAcceleratorType input, gpu::ImageDecodeAcceleratorType* out) { switch (input) { case gpu::mojom::ImageDecodeAcceleratorType::kJpeg: *out = gpu::ImageDecodeAcceleratorType::kJpeg; return true; case gpu::mojom::ImageDecodeAcceleratorType::kWebP: *out = gpu::ImageDecodeAcceleratorType::kWebP; return true; case gpu::mojom::ImageDecodeAcceleratorType::kUnknown: *out = gpu::ImageDecodeAcceleratorType::kUnknown; return true; } NOTREACHED() << "Invalid ImageDecodeAcceleratorType: " << input; return false; } // static gpu::mojom::ImageDecodeAcceleratorSubsampling EnumTraits<gpu::mojom::ImageDecodeAcceleratorSubsampling, gpu::ImageDecodeAcceleratorSubsampling>:: ToMojom(gpu::ImageDecodeAcceleratorSubsampling subsampling) { switch (subsampling) { case gpu::ImageDecodeAcceleratorSubsampling::k420: return gpu::mojom::ImageDecodeAcceleratorSubsampling::k420; case gpu::ImageDecodeAcceleratorSubsampling::k422: return gpu::mojom::ImageDecodeAcceleratorSubsampling::k422; case gpu::ImageDecodeAcceleratorSubsampling::k444: return gpu::mojom::ImageDecodeAcceleratorSubsampling::k444; } } // static bool EnumTraits<gpu::mojom::ImageDecodeAcceleratorSubsampling, gpu::ImageDecodeAcceleratorSubsampling>:: FromMojom(gpu::mojom::ImageDecodeAcceleratorSubsampling input, gpu::ImageDecodeAcceleratorSubsampling* out) { switch (input) { case gpu::mojom::ImageDecodeAcceleratorSubsampling::k420: *out = gpu::ImageDecodeAcceleratorSubsampling::k420; return true; case gpu::mojom::ImageDecodeAcceleratorSubsampling::k422: *out = gpu::ImageDecodeAcceleratorSubsampling::k422; return true; case gpu::mojom::ImageDecodeAcceleratorSubsampling::k444: *out = gpu::ImageDecodeAcceleratorSubsampling::k444; return true; } NOTREACHED() << "Invalid ImageDecodeAcceleratorSubsampling: " << input; return false; } // static bool StructTraits<gpu::mojom::ImageDecodeAcceleratorSupportedProfileDataView, gpu::ImageDecodeAcceleratorSupportedProfile>:: Read(gpu::mojom::ImageDecodeAcceleratorSupportedProfileDataView data, gpu::ImageDecodeAcceleratorSupportedProfile* out) { return data.ReadImageType(&out->image_type) && data.ReadMinEncodedDimensions(&out->min_encoded_dimensions) && data.ReadMaxEncodedDimensions(&out->max_encoded_dimensions) && data.ReadSubsamplings(&out->subsamplings); } #if defined(OS_WIN) // static gpu::mojom::OverlaySupport EnumTraits<gpu::mojom::OverlaySupport, gpu::OverlaySupport>::ToMojom( gpu::OverlaySupport support) { switch (support) { case gpu::OverlaySupport::kNone: return gpu::mojom::OverlaySupport::NONE; case gpu::OverlaySupport::kDirect: return gpu::mojom::OverlaySupport::DIRECT; case gpu::OverlaySupport::kScaling: return gpu::mojom::OverlaySupport::SCALING; } } bool EnumTraits<gpu::mojom::OverlaySupport, gpu::OverlaySupport>::FromMojom( gpu::mojom::OverlaySupport input, gpu::OverlaySupport* out) { switch (input) { case gpu::mojom::OverlaySupport::NONE: *out = gpu::OverlaySupport::kNone; break; case gpu::mojom::OverlaySupport::DIRECT: *out = gpu::OverlaySupport::kDirect; break; case gpu::mojom::OverlaySupport::SCALING: *out = gpu::OverlaySupport::kScaling; break; } return true; } // static bool StructTraits<gpu::mojom::Dx12VulkanVersionInfoDataView, gpu::Dx12VulkanVersionInfo>:: Read(gpu::mojom::Dx12VulkanVersionInfoDataView data, gpu::Dx12VulkanVersionInfo* out) { out->supports_dx12 = data.supports_dx12(); out->supports_vulkan = data.supports_vulkan(); out->d3d12_feature_level = data.d3d12_feature_level(); out->vulkan_version = data.vulkan_version(); return true; } bool StructTraits<gpu::mojom::OverlayInfoDataView, gpu::OverlayInfo>::Read( gpu::mojom::OverlayInfoDataView data, gpu::OverlayInfo* out) { out->direct_composition = data.direct_composition(); out->supports_overlays = data.supports_overlays(); return data.ReadYuy2OverlaySupport(&out->yuy2_overlay_support) && data.ReadNv12OverlaySupport(&out->nv12_overlay_support); } #endif bool StructTraits<gpu::mojom::GpuInfoDataView, gpu::GPUInfo>::Read( gpu::mojom::GpuInfoDataView data, gpu::GPUInfo* out) { out->optimus = data.optimus(); out->amd_switchable = data.amd_switchable(); out->gl_reset_notification_strategy = data.gl_reset_notification_strategy(); out->software_rendering = data.software_rendering(); out->sandboxed = data.sandboxed(); out->in_process_gpu = data.in_process_gpu(); out->passthrough_cmd_decoder = data.passthrough_cmd_decoder(); out->can_support_threaded_texture_mailbox = data.can_support_threaded_texture_mailbox(); out->jpeg_decode_accelerator_supported = data.jpeg_decode_accelerator_supported(); out->oop_rasterization_supported = data.oop_rasterization_supported(); out->subpixel_font_rendering = data.subpixel_font_rendering(); return data.ReadInitializationTime(&out->initialization_time) && data.ReadGpu(&out->gpu) && data.ReadSecondaryGpus(&out->secondary_gpus) && data.ReadPixelShaderVersion(&out->pixel_shader_version) && data.ReadVertexShaderVersion(&out->vertex_shader_version) && data.ReadMaxMsaaSamples(&out->max_msaa_samples) && data.ReadMachineModelName(&out->machine_model_name) && data.ReadMachineModelVersion(&out->machine_model_version) && data.ReadGlVersion(&out->gl_version) && data.ReadGlVendor(&out->gl_vendor) && data.ReadGlRenderer(&out->gl_renderer) && data.ReadGlExtensions(&out->gl_extensions) && data.ReadGlWsVendor(&out->gl_ws_vendor) && data.ReadGlWsVersion(&out->gl_ws_version) && data.ReadGlWsExtensions(&out->gl_ws_extensions) && data.ReadDirectRenderingVersion(&out->direct_rendering_version) && #if defined(OS_WIN) data.ReadOverlayInfo(&out->overlay_info) && data.ReadDxDiagnostics(&out->dx_diagnostics) && data.ReadDx12VulkanVersionInfo(&out->dx12_vulkan_version_info) && #endif data.ReadVideoDecodeAcceleratorCapabilities( &out->video_decode_accelerator_capabilities) && data.ReadVideoEncodeAcceleratorSupportedProfiles( &out->video_encode_accelerator_supported_profiles) && data.ReadImageDecodeAcceleratorSupportedProfiles( &out->image_decode_accelerator_supported_profiles) && #if BUILDFLAG(ENABLE_VULKAN) data.ReadVulkanInfo(&out->vulkan_info) && #endif true; } } // namespace mojo
[ "pcding@ucdavis.edu" ]
pcding@ucdavis.edu
a6ad6f46f0468ff9ae42fcf4c0eda06114db79a8
6a67e23345f03d461be96884769b4a299698ae31
/src/core/thread/mutex.cpp
7e1309dafd01e8deeee5dc5a39aae6550fae4a73
[ "MIT" ]
permissive
doc22940/crown
b1a157444c6e4ef6130fac0e8ed86f6dfa5f38db
f310ca75ea0833e6146d86a456f51296c6054f49
refs/heads/master
2021-02-07T20:21:59.458423
2020-02-28T19:02:57
2020-02-28T19:02:57
244,072,764
0
0
MIT
2021-01-28T10:19:36
2020-03-01T02:18:53
null
UTF-8
C++
false
false
2,140
cpp
/* * Copyright (c) 2012-2020 Daniele Bartolini and individual contributors. * License: https://github.com/dbartolini/crown/blob/master/LICENSE */ #include "core/error/error.inl" #include "core/platform.h" #include "core/thread/mutex.h" #include <new> #if CROWN_PLATFORM_POSIX #include <pthread.h> #elif CROWN_PLATFORM_WINDOWS #include <windows.h> #endif namespace crown { struct Private { #if CROWN_PLATFORM_POSIX pthread_mutex_t mutex; #elif CROWN_PLATFORM_WINDOWS CRITICAL_SECTION cs; #endif }; Mutex::Mutex() { CE_STATIC_ASSERT(sizeof(_data) >= sizeof(*_priv)); _priv = new (_data) Private(); #if CROWN_PLATFORM_POSIX pthread_mutexattr_t attr; int err = pthread_mutexattr_init(&attr); CE_ASSERT(err == 0, "pthread_mutexattr_init: errno = %d", err); err = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK); CE_ASSERT(err == 0, "pthread_mutexattr_settype: errno = %d", err); err = pthread_mutex_init(&_priv->mutex, &attr); CE_ASSERT(err == 0, "pthread_mutex_init: errno = %d", err); err = pthread_mutexattr_destroy(&attr); CE_ASSERT(err == 0, "pthread_mutexattr_destroy: errno = %d", err); CE_UNUSED(err); #elif CROWN_PLATFORM_WINDOWS InitializeCriticalSection(&_priv->cs); #endif } Mutex::~Mutex() { #if CROWN_PLATFORM_POSIX int err = pthread_mutex_destroy(&_priv->mutex); CE_ASSERT(err == 0, "pthread_mutex_destroy: errno = %d", err); CE_UNUSED(err); #elif CROWN_PLATFORM_WINDOWS DeleteCriticalSection(&_priv->cs); #endif _priv->~Private(); } void Mutex::lock() { #if CROWN_PLATFORM_POSIX int err = pthread_mutex_lock(&_priv->mutex); CE_ASSERT(err == 0, "pthread_mutex_lock: errno = %d", err); CE_UNUSED(err); #elif CROWN_PLATFORM_WINDOWS EnterCriticalSection(&_priv->cs); #endif } void Mutex::unlock() { #if CROWN_PLATFORM_POSIX int err = pthread_mutex_unlock(&_priv->mutex); CE_ASSERT(err == 0, "pthread_mutex_unlock: errno = %d", err); CE_UNUSED(err); #elif CROWN_PLATFORM_WINDOWS LeaveCriticalSection(&_priv->cs); #endif } void* Mutex::native_handle() { #if CROWN_PLATFORM_POSIX return &_priv->mutex; #elif CROWN_PLATFORM_WINDOWS return &_priv->cs; #endif } } // namespace crown
[ "dbartolini.aa@gmail.com" ]
dbartolini.aa@gmail.com
e978f3a2878a3c0e66a6d88b836a50735b4a82a5
5b83a3eef49ac004b98ff1ff9ce30989fd85c567
/SPOJ/ONP.cpp
1a1b108f3f4e2137d15278b8e0cce1ae527bb5f2
[]
no_license
floreaadrian/AlgCodes
cd0dfe331d2b1acae26ead05c4be07d6c3c05f52
b3ba2472ba256a73daea334c22bbca282ff3a24d
refs/heads/master
2020-05-25T14:34:27.475469
2019-05-21T13:49:35
2019-05-21T13:49:35
187,846,889
1
0
null
null
null
null
UTF-8
C++
false
false
666
cpp
#include <iostream> #include <stack> #include <cctype> #include <cstring> #include <stdio.h> using namespace std; int main () { int t; scanf("%d",&t); char su[1000]; stack <char> s; for(int tt=1;tt<=t;++tt) { cin>>su; int len = strlen (su); for(int i=0;i<len;i++ ) { if(isalpha(su[i])) cout << su[i]; else if(su[i] == ')' ) { cout << s.top (); s.pop (); } else if (su[i] != '(' ) s.push (su[i]); } printf("\n"); } return 0; }
[ "florea.adrian.paul@gmail.com" ]
florea.adrian.paul@gmail.com
2930856ecd88bf6a05373a074c41c019ee96585c
bd1fea86d862456a2ec9f56d57f8948456d55ee6
/000/110/741/CWE680_Integer_Overflow_to_Buffer_Overflow__new_fixed_82_goodG2B.cpp
2d7affb62610cd1b5315cbf4a7b9ba1eb408afbe
[]
no_license
CU-0xff/juliet-cpp
d62b8485104d8a9160f29213368324c946f38274
d8586a217bc94cbcfeeec5d39b12d02e9c6045a2
refs/heads/master
2021-03-07T15:44:19.446957
2020-03-10T12:45:40
2020-03-10T12:45:40
246,275,244
0
1
null
null
null
null
UTF-8
C++
false
false
1,474
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE680_Integer_Overflow_to_Buffer_Overflow__new_fixed_82_goodG2B.cpp Label Definition File: CWE680_Integer_Overflow_to_Buffer_Overflow__new.label.xml Template File: sources-sink-82_goodG2B.tmpl.cpp */ /* * @description * CWE: 680 Integer Overflow to Buffer Overflow * BadSource: fixed Fixed value that will cause an integer overflow in the sink * GoodSource: Small number greater than zero that will not cause an integer overflow in the sink * Sinks: * BadSink : Attempt to allocate array using length value from source * Flow Variant: 82 Data flow: data passed in a parameter to a virtual method called via a pointer * * */ #ifndef OMITGOOD #include "std_testcase.h" #include "CWE680_Integer_Overflow_to_Buffer_Overflow__new_fixed_82.h" namespace CWE680_Integer_Overflow_to_Buffer_Overflow__new_fixed_82 { void CWE680_Integer_Overflow_to_Buffer_Overflow__new_fixed_82_goodG2B::action(int data) { { size_t dataBytes,i; int *intPointer; /* POTENTIAL FLAW: dataBytes may overflow to a small value */ dataBytes = data * sizeof(int); /* sizeof array in bytes */ intPointer = (int*)new char[dataBytes]; for (i = 0; i < (size_t)data; i++) { intPointer[i] = 0; /* may write beyond limit of intPointer if integer overflow occured above */ } printIntLine(intPointer[0]); delete [] intPointer; } } } #endif /* OMITGOOD */
[ "frank@fischer.com.mt" ]
frank@fischer.com.mt
62408b6f9d1810cacffdc834b1d6065102b5874c
60fa7b47403edc1503d2a16be1c43987c0ea82e4
/sanguo/Classes/GameScene/GroundLayer.h
fa74b610ee852a71438ad976a325755c94057fc6
[ "MIT" ]
permissive
fhaoquan/sanguo
a816ec5a38f5764ab44f1971b6fd4cedd523cae6
0132a64734a67fa0b3261d8e72b2dc9f3152f0bb
refs/heads/master
2021-05-29T17:15:47.736724
2015-09-07T15:57:49
2015-09-07T15:57:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
680
h
#ifndef __GAMESCENE_GROUNDLAYER_H__ #define __GAMESCENE_GROUNDLAYER_H__ #include "cocos2d.h" #include "BaseDef.h" USING_NS_CC; class GroundLayer : public cocos2d::Node { public: // implement the "static create()" method manually CREATE_FUNC(GroundLayer); public: //! 计时 void onIdle(int ot); float getWidth(); float getHeight(); void initTile(); protected: GroundLayer(); virtual ~GroundLayer(); bool init(); protected: Sprite* m_pBack; SpriteBatchNode* m_sbnGround; //! 地面节点 SpriteBatchNode* m_sbnTile; //! tile节点 }; #endif // __GAMESCENE_GROUNDLAYER_H__
[ "sssxueren@gmail.com" ]
sssxueren@gmail.com
832c26e71f9a0d5a919633916fa741e945649cc5
c1b89f5cb524007b6bb5b1304560289168ed52f6
/W1/build_the_sum/buildsum.cpp
79a1c0202be59e82fbd4e94965a1df5aae22a965
[]
no_license
Silenthinker/ETH-Algolab
a1deca905a6f144ec88c5a33f37ed13a7b5b4e83
ed98667c1cc62d496b3ceb9542f946fd9e5b3cd6
refs/heads/master
2021-01-22T03:58:16.468887
2017-02-09T19:56:47
2017-02-09T19:56:47
81,488,513
0
2
null
null
null
null
UTF-8
C++
false
false
519
cpp
/* Build the sum * g++ -Wall -O0 -g -o buildsum buildsum.cpp */ #include <iostream> using namespace std; #define forloop(i, l, h) for (int i=(l); i< (h); i++) #define rep(i, N) forloop(i, 0, N) void buildsum(int n) { double sum = 0; rep(_, n) { double fn; // float point number cin >> fn; sum += fn; } cout << sum; } int main() { int t; // # of test cases cin >> t; rep(_, t) { int n; cin >> n; buildsum(n); cout << endl; } }
[ "sparklethinker@gmail.com" ]
sparklethinker@gmail.com
b96e00da52c8eac7412da4e488e4328b073dff3c
b28d0b5625008237eb8409adb05cffe6c04176c6
/src/play.cpp
973c762401bb68f9e472b0631aecf6384495650e
[ "MIT" ]
permissive
DongdongBai/slumbot2017
daea025f342aa01181d0a9a003dcc003c65b68aa
f0ddb6af63e9f7e25ffa7ef01337d47299a6520d
refs/heads/master
2020-11-26T19:34:58.296865
2019-12-19T18:15:17
2019-12-19T18:15:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
25,535
cpp
// There are two players (computed strategies) given to the program, named // A and B. P0 and P1 in contrast refer to the two positions (big blind and // button respectively). A and B alternate during play between being the // button (P1) and the big blind (P0). #include <math.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <map> #include <memory> #include <string> #include <vector> #include "betting_abstraction.h" #include "betting_abstraction_params.h" #include "betting_tree.h" #include "board_tree.h" #include "buckets.h" #include "canonical_cards.h" #include "canonical.h" #include "card_abstraction.h" #include "card_abstraction_params.h" #include "cfr_config.h" #include "cfr_params.h" #include "cfr_values.h" #include "constants.h" #include "files.h" #include "game.h" #include "game_params.h" #include "hand_tree.h" #include "hand_value_tree.h" #include "io.h" #include "params.h" #include "rand.h" #include "sorting.h" using namespace std; class Player { public: Player(const BettingAbstraction &ba, const CardAbstraction &a_ca, const CardAbstraction &b_ca, const CFRConfig &a_cc, const CFRConfig &b_cc, unsigned int a_it, unsigned int b_it, bool mem_buckets); ~Player(void); void Go(unsigned long long int num_duplicate_hands, bool deterministic); private: void DealNCards(Card *cards, unsigned int n); void SetHCPsAndBoards(Card **raw_hole_cards, const Card *raw_board); void Play(Node **nodes, unsigned int b_pos, unsigned int *contributions, unsigned int last_bet_to, bool *folded, unsigned int num_remaining, unsigned int last_player_acting, int last_st, double *outcomes); void PlayDuplicateHand(unsigned long long int h, const Card *cards, bool deterministic, double *a_sum, double *b_sum); bool mem_buckets_; unsigned int num_players_; bool asymmetric_; BettingTree **betting_trees_; const Buckets *a_buckets_; const Buckets *b_buckets_; const BucketsFile *a_buckets_file_; const BucketsFile *b_buckets_file_; CFRValues **a_probs_; CFRValues **b_probs_; unsigned int *boards_; unsigned int **raw_hcps_; unique_ptr<unsigned int []> hvs_; unique_ptr<bool []> winners_; unsigned short **sorted_hcps_; unique_ptr<double []> sum_pos_outcomes_; struct drand48_data *rand_bufs_; }; void Player::Play(Node **nodes, unsigned int b_pos, unsigned int *contributions, unsigned int last_bet_to, bool *folded, unsigned int num_remaining, unsigned int last_player_acting, int last_st, double *outcomes) { Node *p0_node = nodes[0]; if (p0_node->Terminal()) { if (num_remaining == 1) { unsigned int sum_other_contributions = 0; unsigned int remaining_p = kMaxUInt; for (unsigned int p = 0; p < num_players_; ++p) { if (folded[p]) { sum_other_contributions += contributions[p]; } else { remaining_p = p; } } outcomes[remaining_p] = sum_other_contributions; } else { // Showdown // Temporary? if (num_players_ == 2 && (contributions[0] != contributions[1] || contributions[0] != p0_node->LastBetTo())) { fprintf(stderr, "Mismatch %u %u %u\n", contributions[0], contributions[1], p0_node->LastBetTo()); fprintf(stderr, "TID: %u\n", p0_node->TerminalID()); exit(-1); } // Find the best hand value of anyone remaining in the hand, and the // total pot size which includes contributions from remaining players // and players who folded earlier. unsigned int best_hv = 0; unsigned int pot_size = 0; for (unsigned int p = 0; p < num_players_; ++p) { pot_size += contributions[p]; if (! folded[p]) { unsigned int hv = hvs_[p]; if (hv > best_hv) best_hv = hv; } } // Determine if we won, the number of winners, and the total contribution // of all winners. unsigned int num_winners = 0; unsigned int winner_contributions = 0; for (unsigned int p = 0; p < num_players_; ++p) { if (! folded[p] && hvs_[p] == best_hv) { winners_[p] = true; ++num_winners; winner_contributions += contributions[p]; } else { winners_[p] = false; } } for (unsigned int p = 0; p < num_players_; ++p) { if (winners_[p]) { outcomes[p] = ((double)(pot_size - winner_contributions)) / ((double)num_winners); } else if (! folded[p]) { outcomes[p] = -(int)contributions[p]; } } } return; } else { unsigned int orig_pa = p0_node->PlayerActing(); Node *node = nodes[orig_pa]; unsigned int nt = node->NonterminalID(); unsigned int st = node->Street(); unsigned int num_succs = node->NumSuccs(); // Find the next player to act. Start with the first candidate and move // forward until we find someone who has not folded. The first candidate // is either the last player plus one, or, if we are starting a new // betting round, the first player to act on that street. unsigned int actual_pa; if ((int)st > last_st) { actual_pa = Game::FirstToAct(st); } else { actual_pa = last_player_acting + 1; } while (true) { if (actual_pa == num_players_) actual_pa = 0; if (! folded[actual_pa]) break; ++actual_pa; } unsigned int dsi = node->DefaultSuccIndex(); unsigned int bd = boards_[st]; unsigned int raw_hcp = raw_hcps_[actual_pa][st]; unsigned int num_hole_card_pairs = Game::NumHoleCardPairs(st); unsigned int a_offset, b_offset; // If card abstraction, hcp on river should be raw. If no card // abstraction, hcp on river should be sorted. Right? if (a_buckets_->None(st)) { unsigned int hcp = st == Game::MaxStreet() ? sorted_hcps_[bd][raw_hcp] : raw_hcp; a_offset = bd * num_hole_card_pairs * num_succs + hcp * num_succs; } else { unsigned int h = bd * num_hole_card_pairs + raw_hcp; unsigned int b; if (mem_buckets_) { b = a_buckets_->Bucket(st, h); } else { b = a_buckets_file_->Bucket(st, h); } a_offset = b * num_succs; } unsigned int hcp; if (b_buckets_->None(st)) { hcp = st == Game::MaxStreet() ? sorted_hcps_[bd][raw_hcp] : raw_hcp; b_offset = bd * num_hole_card_pairs * num_succs + hcp * num_succs; } else { unsigned int h = bd * num_hole_card_pairs + raw_hcp; unsigned int b; if (mem_buckets_) { b = b_buckets_->Bucket(st, h); } else { b = b_buckets_file_->Bucket(st, h); } b_offset = b * num_succs; } double r; // r = RandZeroToOne(); drand48_r(&rand_bufs_[actual_pa], &r); double cum = 0; unique_ptr<double []> probs(new double[num_succs]); if (actual_pa == b_pos) { b_probs_[orig_pa]->Probs(orig_pa, st, nt, b_offset, num_succs, dsi, probs.get()); #if 0 fprintf(stderr, "b pa %u st %u nt %u bd %u nhcp %u hcp %u b_offset %u " "probs %f %f r %f\n", orig_pa, st, nt, bd, num_hole_card_pairs, hcp, b_offset, probs[0], probs[1], r); #endif } else { a_probs_[orig_pa]->Probs(orig_pa, st, nt, a_offset, num_succs, dsi, probs.get()); #if 0 fprintf(stderr, "a pa %u st %u nt %u bd %u nhcp %u hcp %u b_offset %u " "probs %f %f r %f\n", orig_pa, st, nt, bd, num_hole_card_pairs, hcp, a_offset, probs[0], probs[1], r); #endif } int s; for (s = 0; s < ((int)num_succs) - 1; ++s) { // Look up probabilities with orig_pa which may be different from // actual_pa. double prob = probs[s]; cum += prob; if (r < cum) break; } if (s == (int)node->CallSuccIndex()) { unique_ptr<Node * []> succ_nodes(new Node *[num_players_]); for (unsigned int p = 0; p < num_players_; ++p) { unsigned int csi = nodes[p]->CallSuccIndex(); succ_nodes[p] = nodes[p]->IthSucc(csi); } // fprintf(stderr, "Call\n"); contributions[actual_pa] = last_bet_to; Play(succ_nodes.get(), b_pos, contributions, last_bet_to, folded, num_remaining, actual_pa, st, outcomes); } else if (s == (int)node->FoldSuccIndex()) { unique_ptr<Node * []> succ_nodes(new Node *[num_players_]); for (unsigned int p = 0; p < num_players_; ++p) { unsigned int fsi = nodes[p]->FoldSuccIndex(); succ_nodes[p] = nodes[p]->IthSucc(fsi); } // fprintf(stderr, "Fold\n"); folded[actual_pa] = true; outcomes[actual_pa] = -(int)contributions[actual_pa]; Play(succ_nodes.get(), b_pos, contributions, last_bet_to, folded, num_remaining - 1, actual_pa, st, outcomes); } else { Node *my_succ = node->IthSucc(s); unsigned int new_bet_to = my_succ->LastBetTo(); unique_ptr<Node * []> succ_nodes(new Node *[num_players_]); for (unsigned int p = 0; p < num_players_; ++p) { unsigned int ps; Node *p_node = nodes[p]; unsigned int p_num_succs = p_node->NumSuccs(); for (ps = 0; ps < p_num_succs; ++ps) { if (ps == p_node->CallSuccIndex() || ps == p_node->FoldSuccIndex()) { continue; } if (p_node->IthSucc(ps)->LastBetTo() == new_bet_to) break; } if (ps == p_num_succs) { fprintf(stderr, "No matching succ\n"); exit(-1); } succ_nodes[p] = nodes[p]->IthSucc(ps); } // fprintf(stderr, "Bet\n"); contributions[actual_pa] = new_bet_to; Play(succ_nodes.get(), b_pos, contributions, new_bet_to, folded, num_remaining, actual_pa, st, outcomes); } } } static unsigned int PrecedingPlayer(unsigned int p) { if (p == 0) return Game::NumPlayers() - 1; else return p - 1; } // Play one hand of duplicate, which is a pair of regular hands. Return // outcome from A's perspective. void Player::PlayDuplicateHand(unsigned long long int h, const Card *cards, bool deterministic, double *a_sum, double *b_sum) { unique_ptr<double []> outcomes(new double[num_players_]); unique_ptr<unsigned int []> contributions(new unsigned int[num_players_]); unique_ptr<bool []> folded(new bool[num_players_]); // Assume the big blind is last to act preflop // Assume the small blind is prior to the big blind unsigned int big_blind_p = PrecedingPlayer(Game::FirstToAct(0)); unsigned int small_blind_p = PrecedingPlayer(big_blind_p); *a_sum = 0; *b_sum = 0; for (unsigned int b_pos = 0; b_pos < num_players_; ++b_pos) { if (deterministic) { // Reseed the RNG again before play within this loop. This ensure // that if we play a system against itself, the duplicate outcome will // always be zero. // // This has a big impact on the average P1 outcome - why? Too much // coordination between the RNG for dealing the cards and the RNG for // actions? // // Temporary - to match play_agents // SeedRand(h); // Generate a separate seed for each player that depends on the hand // index. for (unsigned int p = 0; p < num_players_; ++p) { srand48_r(h * num_players_ + p, &rand_bufs_[p]); } } for (unsigned int p = 0; p < num_players_; ++p) { folded[p] = false; if (p == small_blind_p) { contributions[p] = Game::SmallBlind(); } else if (p == big_blind_p) { contributions[p] = Game::BigBlind(); } else { contributions[p] = 0; } } unique_ptr<Node * []> nodes(new Node *[num_players_]); for (unsigned int p = 0; p < num_players_; ++p) { nodes[p] = betting_trees_[p]->Root(); } Play(nodes.get(), b_pos, contributions.get(), Game::BigBlind(), folded.get(), num_players_, 1000, -1, outcomes.get()); for (unsigned int p = 0; p < num_players_; ++p) { if (p == b_pos) { *b_sum += outcomes[p]; } else { *a_sum += outcomes[p]; } sum_pos_outcomes_[p] += outcomes[p]; } } } void Player::DealNCards(Card *cards, unsigned int n) { unsigned int max_card = Game::MaxCard(); for (unsigned int i = 0; i < n; ++i) { Card c; while (true) { // c = RandBetween(0, max_card); double r; drand48_r(&rand_bufs_[0], &r); c = (max_card + 1) * r; unsigned int j; for (j = 0; j < i; ++j) { if (cards[j] == c) break; } if (j == i) break; } cards[i] = c; } } void Player::SetHCPsAndBoards(Card **raw_hole_cards, const Card *raw_board) { unsigned int max_street = Game::MaxStreet(); for (unsigned int st = 0; st <= max_street; ++st) { if (st == 0) { for (unsigned int p = 0; p < num_players_; ++p) { raw_hcps_[p][0] = HCPIndex(st, raw_hole_cards[p]); } } else { // Store the hole cards *after* the board cards unsigned int num_hole_cards = Game::NumCardsForStreet(0); unsigned int num_board_cards = Game::NumBoardCards(st); for (unsigned int p = 0; p < num_players_; ++p) { Card canon_board[5]; Card canon_hole_cards[2]; CanonicalizeCards(raw_board, raw_hole_cards[p], st, canon_board, canon_hole_cards); // Don't need to do this repeatedly if (p == 0) { boards_[st] = BoardTree::LookupBoard(canon_board, st); } Card canon_cards[7]; for (unsigned int i = 0; i < num_board_cards; ++i) { canon_cards[num_hole_cards + i] = canon_board[i]; } for (unsigned int i = 0; i < num_hole_cards; ++i) { canon_cards[i] = canon_hole_cards[i]; } raw_hcps_[p][st] = HCPIndex(st, canon_cards); } } } } void Player::Go(unsigned long long int num_duplicate_hands, bool deterministic) { double sum_a_outcomes = 0, sum_b_outcomes = 0; double sum_sqd_a_outcomes = 0, sum_sqd_b_outcomes = 0; unsigned int max_street = Game::MaxStreet(); unsigned int num_board_cards = Game::NumBoardCards(max_street); Card cards[100], hand_cards[7]; Card **hole_cards = new Card *[num_players_]; for (unsigned int p = 0; p < num_players_; ++p) { hole_cards[p] = new Card[2]; } if (! deterministic) { InitRand(); } for (unsigned long long int h = 0; h < num_duplicate_hands; ++h) { if (deterministic) { // Seed just as we do in play_agents so we can get the same cards and // compare results. // SeedRand(h); srand48_r(h, &rand_bufs_[0]); } // Assume 2 hole cards DealNCards(cards, num_board_cards + 2 * num_players_); #if 0 OutputNCards(cards + 2 * num_players_, num_board_cards); printf("\n"); OutputTwoCards(cards); printf("\n"); OutputTwoCards(cards + 2); printf("\n"); fflush(stdout); #endif for (unsigned int p = 0; p < num_players_; ++p) { SortCards(cards + 2 * p, 2); } unsigned int num = 2 * num_players_; for (unsigned int st = 1; st <= max_street; ++st) { unsigned int num_street_cards = Game::NumCardsForStreet(st); SortCards(cards + num, num_street_cards); num += num_street_cards; } for (unsigned int i = 0; i < num_board_cards; ++i) { hand_cards[i+2] = cards[i + 2 * num_players_]; } for (unsigned int p = 0; p < num_players_; ++p) { hand_cards[0] = cards[2 * p]; hand_cards[1] = cards[2 * p + 1]; hvs_[p] = HandValueTree::Val(hand_cards); hole_cards[p][0] = cards[2 * p]; hole_cards[p][1] = cards[2 * p + 1]; } SetHCPsAndBoards(hole_cards, cards + 2 * num_players_); // PlayDuplicateHand() returns the result of a duplicate hand (which is // N hands if N is the number of players) double a_outcome, b_outcome; PlayDuplicateHand(h, cards, deterministic, &a_outcome, &b_outcome); sum_a_outcomes += a_outcome; sum_b_outcomes += b_outcome; sum_sqd_a_outcomes += a_outcome * a_outcome; sum_sqd_b_outcomes += b_outcome * b_outcome; } for (unsigned int p = 0; p < num_players_; ++p) { delete [] hole_cards[p]; } delete [] hole_cards; #if 0 unsigned long long int num_a_hands = (num_players_ - 1) * num_players_ * num_duplicate_hands; double mean_a_outcome = sum_a_outcomes / (double)num_a_hands; #endif // Divide by num_players because we evaluate B that many times (once for // each position). unsigned long long int num_b_hands = num_duplicate_hands * num_players_; double mean_b_outcome = sum_b_outcomes / (double)num_b_hands; // Need to divide by two to convert from small blind units to big blind units // Multiply by 1000 to go from big blinds to milli-big-blinds double b_mbb_g = (mean_b_outcome / 2.0) * 1000.0; printf("Avg B outcome: %f (%.1f mbb/g) over %llu dup hands\n", mean_b_outcome, b_mbb_g, num_duplicate_hands); // Variance is the mean of the squares minus the square of the means double var_b = (sum_sqd_b_outcomes / ((double)num_b_hands)) - (mean_b_outcome * mean_b_outcome); double stddev_b = sqrt(var_b); double match_stddev = stddev_b * sqrt(num_b_hands); double match_lower = sum_b_outcomes - 1.96 * match_stddev; double match_upper = sum_b_outcomes + 1.96 * match_stddev; double mbb_lower = ((match_lower / (num_b_hands)) / 2.0) * 1000.0; double mbb_upper = ((match_upper / (num_b_hands)) / 2.0) * 1000.0; printf("MBB confidence interval: %f-%f\n", mbb_lower, mbb_upper); fflush(stdout); for (unsigned int p = 0; p < num_players_; ++p) { double avg_outcome = sum_pos_outcomes_[p] / (double)(num_players_ * num_duplicate_hands); printf("Avg P%u outcome: %f\n", p, avg_outcome); fflush(stdout); } } Player::Player(const BettingAbstraction &ba, const CardAbstraction &a_ca, const CardAbstraction &b_ca, const CFRConfig &a_cc, const CFRConfig &b_cc, unsigned int a_it, unsigned int b_it, bool mem_buckets) { mem_buckets_ = mem_buckets; if (mem_buckets_) { a_buckets_ = new Buckets(a_ca, false); fprintf(stderr, "Created a_buckets\n"); if (strcmp(a_ca.CardAbstractionName().c_str(), b_ca.CardAbstractionName().c_str())) { b_buckets_ = new Buckets(b_ca, false); fprintf(stderr, "Created b_buckets\n"); } else { b_buckets_ = a_buckets_; } a_buckets_file_ = nullptr; b_buckets_file_ = nullptr; } else { a_buckets_ = new Buckets(a_ca, true); b_buckets_ = new Buckets(b_ca, true); a_buckets_file_ = new BucketsFile(a_ca); b_buckets_file_ = new BucketsFile(b_ca); } num_players_ = Game::NumPlayers(); hvs_.reset(new unsigned int[num_players_]); winners_.reset(new bool[num_players_]); sum_pos_outcomes_.reset(new double[num_players_]); BoardTree::Create(); BoardTree::CreateLookup(); asymmetric_ = ba.Asymmetric(); betting_trees_ = new BettingTree *[num_players_]; if (asymmetric_) { for (unsigned int asym_p = 0; asym_p < num_players_; ++asym_p) { betting_trees_[asym_p] = BettingTree::BuildAsymmetricTree(ba, asym_p); } } else { betting_trees_[0] = BettingTree::BuildTree(ba); for (unsigned int asym_p = 1; asym_p < num_players_; ++asym_p) { betting_trees_[asym_p] = betting_trees_[0]; } } unsigned int max_street = Game::MaxStreet(); a_probs_ = new CFRValues *[num_players_]; b_probs_ = new CFRValues *[num_players_]; for (unsigned int p = 0; p < num_players_; ++p) { unique_ptr<bool []> players(new bool[num_players_]); for (unsigned int p1 = 0; p1 < num_players_; ++p1) { players[p1] = (p1 == p); } a_probs_[p] = new CFRValues(players.get(), true, nullptr, betting_trees_[p], 0, 0, a_ca, a_buckets_->NumBuckets(), nullptr); b_probs_[p] = new CFRValues(players.get(), true, nullptr, betting_trees_[p], 0, 0, b_ca, b_buckets_->NumBuckets(), nullptr); } char dir[500], buf[100]; for (unsigned int p = 0; p < num_players_; ++p) { sprintf(dir, "%s/%s.%u.%s.%u.%u.%u.%s.%s", Files::OldCFRBase(), Game::GameName().c_str(), Game::NumPlayers(), a_ca.CardAbstractionName().c_str(), Game::NumRanks(), Game::NumSuits(), Game::MaxStreet(), ba.BettingAbstractionName().c_str(), a_cc.CFRConfigName().c_str()); if (asymmetric_) { sprintf(buf, ".p%u", p); strcat(dir, buf); } a_probs_[p]->Read(dir, a_it, betting_trees_[p]->Root(), "x", kMaxUInt); fprintf(stderr, "Read A P%u probs\n", p); sprintf(dir, "%s/%s.%u.%s.%u.%u.%u.%s.%s", Files::OldCFRBase(), Game::GameName().c_str(), Game::NumPlayers(), b_ca.CardAbstractionName().c_str(), Game::NumRanks(), Game::NumSuits(), Game::MaxStreet(), ba.BettingAbstractionName().c_str(), b_cc.CFRConfigName().c_str()); if (asymmetric_) { sprintf(buf, ".p%u", p); strcat(dir, buf); } b_probs_[p]->Read(dir, b_it, betting_trees_[p]->Root(), "x", kMaxUInt); fprintf(stderr, "Read B P%u probs\n", p); } boards_ = new unsigned int[max_street + 1]; boards_[0] = 0; raw_hcps_ = new unsigned int *[num_players_]; for (unsigned int p = 0; p < num_players_; ++p) { raw_hcps_[p] = new unsigned int[max_street + 1]; } if (a_buckets_->None(max_street) || b_buckets_->None(max_street)) { unsigned int num_hole_card_pairs = Game::NumHoleCardPairs(max_street); unsigned int num_boards = BoardTree::NumBoards(max_street); sorted_hcps_ = new unsigned short *[num_boards]; Card cards[7]; unsigned int num_hole_cards = Game::NumCardsForStreet(0); unsigned int num_board_cards = Game::NumBoardCards(max_street); for (unsigned int bd = 0; bd < num_boards; ++bd) { const Card *board = BoardTree::Board(max_street, bd); for (unsigned int i = 0; i < num_board_cards; ++i) { cards[i + num_hole_cards] = board[i]; } unsigned int sg = BoardTree::SuitGroups(max_street, bd); CanonicalCards hands(2, board, num_board_cards, sg, false); hands.SortByHandStrength(board); sorted_hcps_[bd] = new unsigned short[num_hole_card_pairs]; for (unsigned int shcp = 0; shcp < num_hole_card_pairs; ++shcp) { const Card *hole_cards = hands.Cards(shcp); for (unsigned int i = 0; i < num_hole_cards; ++i) { cards[i] = hole_cards[i]; } unsigned int rhcp = HCPIndex(max_street, cards); sorted_hcps_[bd][rhcp] = shcp; } } fprintf(stderr, "Created sorted_hcps_\n"); } else { sorted_hcps_ = nullptr; fprintf(stderr, "Not creating sorted_hcps_\n"); } for (unsigned int p = 0; p < num_players_; ++p) { sum_pos_outcomes_[p] = 0; } rand_bufs_ = new drand48_data[num_players_]; } Player::~Player(void) { delete [] rand_bufs_; if (sorted_hcps_) { unsigned int max_street = Game::MaxStreet(); unsigned int num_boards = BoardTree::NumBoards(max_street); for (unsigned int bd = 0; bd < num_boards; ++bd) { delete [] sorted_hcps_[bd]; } delete [] sorted_hcps_; } delete [] boards_; for (unsigned int p = 0; p < num_players_; ++p) { delete [] raw_hcps_[p]; } delete [] raw_hcps_; if (b_buckets_ != a_buckets_) delete b_buckets_; delete a_buckets_; delete a_buckets_file_; delete b_buckets_file_; for (unsigned int p = 0; p < num_players_; ++p) { delete a_probs_[p]; delete b_probs_[p]; } delete [] a_probs_; delete [] b_probs_; if (asymmetric_) { for (unsigned int asym_p = 0; asym_p < num_players_; ++asym_p) { delete betting_trees_[asym_p]; } } else { delete betting_trees_[0]; } delete [] betting_trees_; } static void Usage(const char *prog_name) { fprintf(stderr, "USAGE: %s <game params> <A card params> <B card params> " "<betting abstraction params> <A CFR params> <B CFR params> " "<A it> <B it> <num duplicate hands> " "[determ|nondeterm] [mem|disk]\n", prog_name); exit(-1); } int main(int argc, char *argv[]) { if (argc != 12) Usage(argv[0]); Files::Init(); unique_ptr<Params> game_params = CreateGameParams(); game_params->ReadFromFile(argv[1]); Game::Initialize(*game_params); unique_ptr<Params> a_card_params = CreateCardAbstractionParams(); a_card_params->ReadFromFile(argv[2]); unique_ptr<CardAbstraction> a_card_abstraction(new CardAbstraction(*a_card_params)); unique_ptr<Params> b_card_params = CreateCardAbstractionParams(); b_card_params->ReadFromFile(argv[3]); unique_ptr<CardAbstraction> b_card_abstraction(new CardAbstraction(*b_card_params)); unique_ptr<Params> betting_params = CreateBettingAbstractionParams(); betting_params->ReadFromFile(argv[4]); unique_ptr<BettingAbstraction> betting_abstraction(new BettingAbstraction(*betting_params)); unique_ptr<Params> a_cfr_params = CreateCFRParams(); a_cfr_params->ReadFromFile(argv[5]); unique_ptr<CFRConfig> a_cfr_config(new CFRConfig(*a_cfr_params)); unique_ptr<Params> b_cfr_params = CreateCFRParams(); b_cfr_params->ReadFromFile(argv[6]); unique_ptr<CFRConfig> b_cfr_config(new CFRConfig(*b_cfr_params)); unsigned int a_it, b_it; if (sscanf(argv[7], "%u", &a_it) != 1) Usage(argv[0]); if (sscanf(argv[8], "%u", &b_it) != 1) Usage(argv[0]); unsigned long long int num_duplicate_hands; if (sscanf(argv[9], "%llu", &num_duplicate_hands) != 1) Usage(argv[0]); string darg = argv[10]; bool deterministic; if (darg == "determ") deterministic = true; else if (darg == "nondeterm") deterministic = false; else Usage(argv[0]); string marg = argv[11]; bool mem_buckets; if (marg == "mem") mem_buckets = true; else if (marg == "disk") mem_buckets = false; else Usage(argv[0]); HandValueTree::Create(); fprintf(stderr, "Created HandValueTree\n"); // Leave this in if we don't want reproducibility InitRand(); Player *player = new Player(*betting_abstraction, *a_card_abstraction, *b_card_abstraction, *a_cfr_config, *b_cfr_config, a_it, b_it, mem_buckets); player->Go(num_duplicate_hands, deterministic); delete player; }
[ "eric.jackson@gmail.com" ]
eric.jackson@gmail.com
667c3224bb6dac7cc9a40520ad20b3d9b4311f5a
412e4b48bdd9b919af2b2cfe1cf47420753eebec
/src/OTHER/flatmirror.CPP
6f40f7bb525ac98e7e4a685c44137199ce741d60
[ "MIT" ]
permissive
dainiak/winopto
c9b31e8e4c716362e65f80f2f19f0206f9bdb0df
6a39259e98cf1a354a057e384df4b6f0e1cd951e
refs/heads/main
2023-02-03T04:36:18.587019
2023-01-22T20:09:07
2023-01-22T20:09:07
83,316,254
0
0
null
null
null
null
UTF-8
C++
false
false
5,247
cpp
#include <stdafx.h> #include "globals.h" #include "cflatmirror.h" ////////////////////////////////////////////////////////////////////////////// //CFlatMirror class member functions: ////////////////////////////////////////////////////////////////////////////// CFlatMirror::CFlatMirror( void ) { m_FlatMirror.Create( 0, 0, 0, 0 ); } ////////////////////////////////////////////////////////////////////////////// void CFlatMirror::Create( int x1, int y1, int x2, int y2 ) { m_ObjectRegion.left = Min( x1, x2 ); m_ObjectRegion.right = Max( x1, x2 ); m_ObjectRegion.top = Min( y1, y2 ); m_ObjectRegion.bottom = Max( y1, y2 ); m_FlatMirror.Create( x1, y1, x2, y2 ); m_MirrorLine.Create( x1, y1, x2, y2 ); } ////////////////////////////////////////////////////////////////////////////// void CFlatMirror::Draw( void ) { GraphParams.SetStyle( GS_FLATMIRROR ); m_FlatMirror.Draw(); GraphParams.RestorePen(); } ////////////////////////////////////////////////////////////////////////////// CPoint CFlatMirror::GetIntersectPoint( void ) { CPoint NewPoint; CLine MirrorLine; MirrorLine = m_FlatMirror.GetParentLine(); NewPoint = LineIntersect( &MirrorLine, &CurrentRay ); if( IsInRect( &NewPoint, &m_ObjectRegion ) && IsValidDirection( &CurrentLSPosition, &NewPoint )) return NewPoint; NewPoint.x = -1000; return NewPoint; } ////////////////////////////////////////////////////////////////////////////// void CFlatMirror::CalculateRay( void ) { CPoint NewPoint; CPoint Reflection; NewPoint = LineIntersect( &m_MirrorLine, &CurrentRay ); Reflection = GetSymmetricPoint( &CurrentLSPosition, &m_MirrorLine ); CurrentRay.Create( Reflection.x, Reflection.y, NewPoint.x, NewPoint.y ); OldLSPosition = CurrentLSPosition; CurrentLSPosition = NewPoint; if( GraphParams.m_DrawILS && !AnimationFlag ) { ILSIsImgFlag = TRUE; ILSPosition = GetSymmetricPoint( &ILSPosition, &m_MirrorLine ); if( GraphParams.m_ILSSelectionMode ) GraphParams.SetGlobalColor( GraphParams.m_SelectionColor ); GraphParams.SetStyle( PS_SOLID, 2, GraphParams.m_ILSColor ); GlobalDC->Ellipse( ILSPosition.x - 2, ILSPosition.y - 2, ILSPosition.x + 2, ILSPosition.y + 2 ); GraphParams.RestorePen(); if( GraphParams.m_ShowRays ) { GraphParams.SetStyle( PS_DASH, 1, GraphParams.m_ILSColor ); DrawLine( NewPoint.x, NewPoint.y, ILSPosition.x, ILSPosition.y ); GraphParams.RestorePen(); } if( GraphParams.m_ILSSelectionMode ) GraphParams.RestoreColors(); } } ////////////////////////////////////////////////////////////////////////////// BOOL CFlatMirror::IsClicked( CPoint* ClickPoint, int Accuracy ) { return m_FlatMirror.IsOnSegment( ClickPoint, Accuracy ); } ////////////////////////////////////////////////////////////////////////////// void CFlatMirror::ParallelMove( int x, int y ) { m_ObjectRegion.left += x; m_ObjectRegion.right += x; m_ObjectRegion.top += y; m_ObjectRegion.bottom += y; m_FlatMirror.m_x1 += x; m_FlatMirror.m_x2 += x; m_FlatMirror.m_y1 += y; m_FlatMirror.m_y2 += y; m_MirrorLine.Create( m_FlatMirror.m_x1, m_FlatMirror.m_y1, m_FlatMirror.m_x2, m_FlatMirror.m_y2 ); } ////////////////////////////////////////////////////////////////////////////// void CFlatMirror::Rotate( double Angle ) { m_FlatMirror.RotateByCenter( Angle ); m_MirrorLine.Create( m_FlatMirror.m_x1, m_FlatMirror.m_y1, m_FlatMirror.m_x2, m_FlatMirror.m_y2 ); m_ObjectRegion.left = Min( m_FlatMirror.m_x1, m_FlatMirror.m_x2 ); m_ObjectRegion.right = Max( m_FlatMirror.m_x1, m_FlatMirror.m_x2 ); m_ObjectRegion.top = Min( m_FlatMirror.m_y1, m_FlatMirror.m_y2 ); m_ObjectRegion.bottom = Max( m_FlatMirror.m_y1, m_FlatMirror.m_y2 ); if( m_Name.IsEmpty() ) LogString.Format( "Mirror rotation" ); else LogString.Format( "Mirror rotation \"%s\"", m_Name ); } ////////////////////////////////////////////////////////////////////////////// void CFlatMirror::ChangeSize( int DeltaSize ) { m_FlatMirror.ChangeSize( DeltaSize, &m_MirrorLine ); m_ObjectRegion.left = Min( m_FlatMirror.m_x1, m_FlatMirror.m_x2 ); m_ObjectRegion.right = Max( m_FlatMirror.m_x1, m_FlatMirror.m_x2 ); m_ObjectRegion.top = Min( m_FlatMirror.m_y1, m_FlatMirror.m_y2 ); m_ObjectRegion.bottom = Max( m_FlatMirror.m_y1, m_FlatMirror.m_y2 ); if( m_Name.IsEmpty() ) LogString.Format( "Mirror size: %d", ( int )GetDistance( m_FlatMirror.m_x1, m_FlatMirror.m_y1, m_FlatMirror.m_x2, m_FlatMirror.m_y2 )); else LogString.Format( "Mirror size \"%s\": %d", m_Name, ( int )GetDistance( m_FlatMirror.m_x1, m_FlatMirror.m_y1, m_FlatMirror.m_x2, m_FlatMirror.m_y2 )); } ////////////////////////////////////////////////////////////////////////////// void CFlatMirror::Serialize( CArchive& Ar ) { if( Ar.IsStoring() ) { Ar << T_FLATMIRROR; Ar << m_Name; Ar << m_FlatMirror.m_x1; Ar << m_FlatMirror.m_y1; Ar << m_FlatMirror.m_x2; Ar << m_FlatMirror.m_y2; } else { Ar >> m_Name; Ar >> m_FlatMirror.m_x1; Ar >> m_FlatMirror.m_y1; Ar >> m_FlatMirror.m_x2; Ar >> m_FlatMirror.m_y2; Create( m_FlatMirror.m_x1, m_FlatMirror.m_y1, m_FlatMirror.m_x2, m_FlatMirror.m_y2 ); } }
[ "dainiak@gmail.com" ]
dainiak@gmail.com
b80e2a2af2640b93358214f666d282e2eaf0be52
477c8309420eb102b8073ce067d8df0afc5a79b1
/Qt/Core/pqStandardServerManagerModelInterface.cxx
5979441b80162a9ddc27adad03a59f287cfe0d04
[ "LicenseRef-scancode-paraview-1.2" ]
permissive
aashish24/paraview-climate-3.11.1
e0058124e9492b7adfcb70fa2a8c96419297fbe6
c8ea429f56c10059dfa4450238b8f5bac3208d3a
refs/heads/uvcdat-master
2021-07-03T11:16:20.129505
2013-05-10T13:14:30
2013-05-10T13:14:30
4,238,077
1
0
NOASSERTION
2020-10-12T21:28:23
2012-05-06T02:32:44
C++
UTF-8
C++
false
false
5,667
cxx
/*========================================================================= Program: ParaView Module: pqStandardServerManagerModelInterface.cxx Copyright (c) 2005-2008 Sandia Corporation, Kitware Inc. All rights reserved. ParaView is a free software; you can redistribute it and/or modify it under the terms of the ParaView license version 1.2. See License_v1.2.txt for the full ParaView license. A copy of this license can be obtained by contacting Kitware Inc. 28 Corporate Drive Clifton Park, NY 12065 USA 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 AUTHORS 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 "pqStandardServerManagerModelInterface.h" // Server Manager Includes. #include "vtkSMProxy.h" #include "vtkSMRenderViewProxy.h" #include "vtkSMRepresentationProxy.h" //#include "vtkSMScatterPlotRepresentationProxy.h" // Qt Includes. #include <QtDebug> // ParaView Includes. #include "pqAnimationCue.h" #include "pqAnimationScene.h" #include "pqApplicationCore.h" #include "pqInterfaceTracker.h" #include "pqPipelineFilter.h" #include "pqPipelineRepresentation.h" #include "pqRenderView.h" #include "pqScalarBarRepresentation.h" #include "pqScalarsToColors.h" #include "pqScalarOpacityFunction.h" //#include "pqScatterPlotRepresentation.h" #include "pqTimeKeeper.h" #include "pqViewModuleInterface.h" //----------------------------------------------------------------------------- pqStandardServerManagerModelInterface::pqStandardServerManagerModelInterface( QObject* _parent) : QObject(_parent) { } //----------------------------------------------------------------------------- pqStandardServerManagerModelInterface::~pqStandardServerManagerModelInterface() { } //----------------------------------------------------------------------------- pqProxy* pqStandardServerManagerModelInterface::createPQProxy( const QString& group, const QString& name, vtkSMProxy* proxy, pqServer* server) const { QString xml_type = proxy->GetXMLName(); pqInterfaceTracker* pluginMgr = pqApplicationCore::instance()->interfaceTracker(); if (group == "views") { QObjectList ifaces = pluginMgr->interfaces(); foreach(QObject* iface, ifaces) { pqViewModuleInterface* vmi = qobject_cast<pqViewModuleInterface*>(iface); if (vmi) { pqView* pqview = vmi->createView(xml_type, group, name, vtkSMViewProxy::SafeDownCast(proxy), server, 0); if (pqview) { return pqview; } } } } else if (group == "sources") { if (proxy->GetProperty("Input")) { return new pqPipelineFilter(name, proxy, server, 0); } else { return new pqPipelineSource(name, proxy, server, 0); } } else if (group == "timekeeper") { return new pqTimeKeeper(group, name, proxy, server, 0); } else if (group == "lookup_tables") { return new pqScalarsToColors(group, name, proxy, server, 0); } else if (group == "piecewise_functions") { return new pqScalarOpacityFunction(group, name, proxy, server, 0); } else if (group == "scalar_bars") { return new pqScalarBarRepresentation(group, name, proxy, server, 0); } else if (group == "representations") { QObjectList ifaces = pluginMgr->interfaces(); foreach(QObject* iface, ifaces) { pqViewModuleInterface* vmi = qobject_cast<pqViewModuleInterface*>(iface); if(vmi && vmi->displayTypes().contains(xml_type)) { return vmi->createDisplay( xml_type, "representations", name, proxy, server, 0); } } // if (proxy->IsA("vtkSMScatterPlotRepresentationProxy")) // { // return new pqScatterPlotRepresentation(group, name, // vtkSMScatterPlotRepresentationProxy::SafeDownCast(proxy), server, 0); // } if (proxy->IsA("vtkSMRepresentationProxy") && proxy->GetProperty("Input")) { if (proxy->IsA("vtkSMPVRepresentationProxy") || xml_type == "ImageSliceRepresentation") { // pqPipelineRepresentation is a design flaw! We need to get rid of it // and have helper code that manages the crap in that class return new pqPipelineRepresentation(group, name, proxy, server, 0); } // If everything fails, simply create a pqDataRepresentation object. return new pqDataRepresentation(group, name, proxy, server, 0); } } else if (group == "animation") { if (xml_type == "AnimationScene") { return new pqAnimationScene(group, name, proxy, server, 0); } else if (xml_type == "KeyFrameAnimationCue" || xml_type == "CameraAnimationCue" || xml_type == "TimeAnimationCue") { return new pqAnimationCue(group, name, proxy, server, 0); } } // qDebug() << "Could not determine pqProxy type: " << proxy->GetXMLName() << endl; return 0; }
[ "aashish.chaudhary@kitware.com" ]
aashish.chaudhary@kitware.com
7275268320b020741a46c3a7ec79bc3f0119ca7a
7303a4cde75b683460265b0c21f6c9aa54bceefd
/uva11709.cpp
c22bed005fec055e38a11ebca226370c45e69ee5
[]
no_license
NicolasZanatto/TeoriaDosGrafos
aaf705fd5c39e0a9a4643f1ad3b738f00d368a45
4a8e5379afed25568b03c6b5b73a2d2320c896eb
refs/heads/master
2021-08-28T01:13:16.070290
2017-12-11T01:42:43
2017-12-11T01:42:43
113,123,350
0
0
null
null
null
null
MacCentralEurope
C++
false
false
2,437
cpp
#include <stdio.h> #include<string.h> #define N 1000 int matT[N][N]; int matAdj[N][N]; int P=0; int T; int posnum[N],visit[N]; int nump=0; void DFS(int v) { visit[v]=1; int i; for (i=0;i<P;i++) if (matAdj[v][i] && visit[i]==0) DFS(i); nump++; posnum[v] = nump; } void DFS2(int v) { visit[v]=2; int i; for (i=0;i<P;i++) if (matT[v][i] && visit[i]==1) DFS2(i); } int verificaLugarNaMatriz(char string[20],int q,char matNomes[N][20]) { for(int i=0;i<q;i++) { if(strcmp(string,matNomes[i])==0) return i; } return 1001; } int main() { int i,j; scanf("%d %d",&P,&T); while(P!=0 && T!=0) { int cont=0; char matNomes[P][20]; char string1[20],string2[20]; int count,inicial; for(i=0;i<P;i++) { strcpy(matNomes[i],""); posnum[i]=0; visit[i]=0; //Zera matriz adjacÍncias for(j=0;j<N;j++) { matT[i][j]=0; matAdj[i][j]=0; } } setbuf(stdin,NULL); for(count=0;count<P;count++) { fgets(matNomes[count],20,stdin); setbuf(stdin,NULL); } /* printf("Strings digitadas.\n"); for(i=0;i<P;i++) printf("%s, posicao %d\n",matNomes[i],i); */ setbuf(stdin,NULL); for(i=0;i<T;i++) { fgets(string1,20,stdin); setbuf(stdin,NULL); fgets(string2,20,stdin); setbuf(stdin,NULL); if(strcmp(string1,string2)){ int a = verificaLugarNaMatriz(string1,P,matNomes); int b = verificaLugarNaMatriz(string2,P,matNomes); matAdj[a][b]=1; if(i==0) inicial=a; } strcpy(string1,""); strcpy(string2,""); } DFS(inicial); for (i=0;i<P;i++) //Cria matriz transposta for (j=0;j<P;j++) matT[i][j]=matAdj[j][i]; while (1) { int maior=-1,pm=0; for (i=0;i<P;i++) if (posnum[i]>maior && visit[i]==1) { maior=posnum[i]; pm=i; } if (maior==-1) break; DFS2(pm); for (i=0;i<P;i++) if (visit[i]==2) { // printf("%d ",i+1); visit[i]=3; } //printf("\n"); cont++; } for(i=0;i<P;i++) if(visit[i]==0) cont++; printf("%d\n",cont); scanf("%d %d",&P,&T); } return 0; }
[ "34211411+NicolasZanatto@users.noreply.github.com" ]
34211411+NicolasZanatto@users.noreply.github.com
c0ee2fab7287745dd276dae2e41f9ca9f61750d5
528dc610bb0513b255b613d6aaa0b59d4c9af9db
/Tool/RS232 Tool/Interface_V2.0/Interface.h
88defe8ecbf67a1da88c37ca60101acf91dba9a1
[]
no_license
hesitationer/3111
7b7e468de38950a1a357e16f643098630e33a68a
4fba49c2c2a6a78f9b3c5a006df85e33cfeb8b96
refs/heads/master
2021-05-27T19:07:55.625866
2014-07-31T01:15:38
2014-07-31T01:15:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,507
h
// Interface.h : main header file for the INTERFACE application // #if !defined(AFX_INTERFACE_H__EC6214C6_D0DF_4C54_A258_0110DA5B291B__INCLUDED_) #define AFX_INTERFACE_H__EC6214C6_D0DF_4C54_A258_0110DA5B291B__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #ifndef __AFXWIN_H__ #error include 'stdafx.h' before including this file for PCH #endif #include "resource.h" // main symbols ///////////////////////////////////////////////////////////////////////////// // CInterfaceApp: // See Interface.cpp for the implementation of this class // #include "BtnST.h" #include "ColorBtn.h" #include "Interface.h" #include "Member.h" class CInterfaceApp : public CWinApp { public: void Add(char *buff, int size); CInterfaceApp(); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CInterfaceApp) public: virtual BOOL InitInstance(); //}}AFX_VIRTUAL // Implementation //{{AFX_MSG(CInterfaceApp) // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() }; extern CInterfaceApp theApp; extern CMember m; extern UINT ReadThread(LPVOID p); ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_INTERFACE_H__EC6214C6_D0DF_4C54_A258_0110DA5B291B__INCLUDED_)
[ "harper@chroma.com.tw" ]
harper@chroma.com.tw
4d4e0e1e47fccbc515cec5b6e724041649cc7cff
03b5b626962b6c62fc3215154b44bbc663a44cf6
/sample-code/math/isgreaterequal.cpp
d72da86924ec1621c9912cc3a1e578227665ca58
[]
no_license
haochenprophet/iwant
8b1f9df8ee428148549253ce1c5d821ece0a4b4c
1c9bd95280216ee8cd7892a10a7355f03d77d340
refs/heads/master
2023-06-09T11:10:27.232304
2023-05-31T02:41:18
2023-05-31T02:41:18
67,756,957
17
5
null
2018-08-11T16:37:37
2016-09-09T02:08:46
C++
UTF-8
C++
false
false
307
cpp
/* isgreaterequal example */ #include <stdio.h> /* printf */ #include <math.h> /* isgreaterequal, log */ int main () { double result; result = log (10.0); if (isgreaterequal(result,0.0)) printf ("log(10.0) is not negative"); else printf ("log(10.0) is negative"); return 0; }
[ "hao.chen@prophet.net.cn" ]
hao.chen@prophet.net.cn
630471d6edfbb32aad940afaa7278282abe2c104
a02b69f431952221cccac1a92b5a4c857e8a9f38
/MainFrm.h
bc4aab3cad372b1a1684b204284667d40d06f01c
[]
no_license
KimMinJeong05/Mini-Game
72ebfc7b62a80b2f00fd91aa71377bffb12c7c7f
9417af5ceef312e3bacc1c78d1cce23b685ed5b7
refs/heads/main
2023-02-13T16:59:08.789152
2021-01-10T14:39:20
2021-01-10T14:39:20
328,378,129
0
0
null
null
null
null
UHC
C++
false
false
765
h
// MainFrm.h : CMainFrame 클래스의 인터페이스 // #pragma once class CMainFrame : public CFrameWnd { protected: // serialization에서만 만들어집니다. CMainFrame(); DECLARE_DYNCREATE(CMainFrame) // 특성입니다. public: // 작업입니다. public: // 재정의입니다. public: virtual BOOL PreCreateWindow(CREATESTRUCT& cs); // 구현입니다. public: virtual ~CMainFrame(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif public: // 컨트롤 모음이 포함된 멤버입니다. CToolBar m_wndToolBar; CStatusBar m_wndStatusBar; // 생성된 메시지 맵 함수 protected: afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); DECLARE_MESSAGE_MAP() };
[ "alswjd980512@naver.com" ]
alswjd980512@naver.com
a686fdb2586c1202023750d7b20f1cf7846b11d5
95b7fe7d116ecf04241f145cc90a6b500798ca27
/src/Brainfuck.cpp
4ef60888a300bb771f8e36a9843535eb8cc491cd
[]
no_license
szborows/paro16-dojo
2f4580d944f1a411aaa7b944f63930af6f5fa840
63f23b0618a10504f803f2212676b3bdfbf4a478
refs/heads/master
2021-01-01T05:23:24.435978
2016-05-11T09:37:50
2016-05-11T09:37:50
58,528,222
0
0
null
null
null
null
UTF-8
C++
false
false
205
cpp
#include "Brainfuck.hpp" #include "Memory.hpp" std::string Brainfuck::interpret(Code const& code, Input const& input) const { Memory memory; std::string result; // TODO return result; }
[ "slawomir.zborowski@nokia.com" ]
slawomir.zborowski@nokia.com
2e781cde32d66f9098585a09add641979c7c8295
785df77400157c058a934069298568e47950e40b
/TnbPtdModel/TnbLib/PtdModel/Entities/Shape/PtdModel_Shape.cxx
9d4fa644788e80b89045e9048672a19408d3dedd
[]
no_license
amir5200fx/Tonb
cb108de09bf59c5c7e139435e0be008a888d99d5
ed679923dc4b2e69b12ffe621fc5a6c8e3652465
refs/heads/master
2023-08-31T08:59:00.366903
2023-08-31T07:42:24
2023-08-31T07:42:24
230,028,961
9
3
null
2023-07-20T16:53:31
2019-12-25T02:29:32
C++
UTF-8
C++
false
false
979
cxx
#include <PtdModel_Shape.hxx> tnbLib::PtdModel_Shape::PtdModel_Shape ( const std::shared_ptr<Cad_Shape>& theShape ) : theShape_(theShape) { //- empty body } tnbLib::PtdModel_Shape::PtdModel_Shape ( std::shared_ptr<Cad_Shape>&& theShape ) : theShape_(std::move(theShape)) { //- empty body } tnbLib::PtdModel_Shape::PtdModel_Shape ( const Standard_Integer theIndex, const word& theName, const std::shared_ptr<Cad_Shape>& theShape ) : PtdModel_Entity(theIndex, theName) , theShape_(theShape) { //- empty body } tnbLib::PtdModel_Shape::PtdModel_Shape ( const Standard_Integer theIndex, const word& theName, std::shared_ptr<Cad_Shape>&& theShape ) : PtdModel_Entity(theIndex, theName) , theShape_(std::move(theShape)) { //- empty body } void tnbLib::PtdModel_Shape::SetShape(const std::shared_ptr<Cad_Shape>& theShape) { theShape_ = theShape; } void tnbLib::PtdModel_Shape::SetShape(std::shared_ptr<Cad_Shape>&& theShape) { theShape_ = std::move(theShape); }
[ "aasoleimani86@gmail.com" ]
aasoleimani86@gmail.com
db5a01afa24f9d3fe9e4eb1150a98f50cd69f07d
7ec9222114fee1574a1841e2250ce16b03b0bf72
/CF420/A.cpp
5693abea06e534bfcb2558309a1c985cada53449
[]
no_license
AKarunakaran/CodeForces
8d9d02aa814acca0c41f2d401e2cc84fcaa46610
fcd19a9734ec002d23f34378e25ee45b305950ae
refs/heads/master
2022-11-09T04:15:13.041820
2020-06-25T20:06:28
2020-06-25T20:06:28
104,012,824
1
0
null
null
null
null
UTF-8
C++
false
false
1,356
cpp
#include <iostream> #include <iomanip> #include <sstream> #include <cstdio> #include <cmath> #include <cstring> #include <cctype> #include <string> #include <vector> #include <list> #include <set> #include <map> #include <queue> #include <stack> #include <algorithm> #include <cstdio> #include <functional> using namespace std; #define DEBUG(x) cout << '>' << #x << ':' << x << endl; #define REP(i,n) for(int i=0;i<(n);i++) #define FOR(i,a,b) for(int i=(a);i<=(b);i++) #define FORD(i,a,b) for(int i=(a);i>=(b);i--) inline bool EQ(double a, double b) { return fabs(a-b) < 1e-9; } const int INF = (((1<<30)-1)<<1)+1; const int nINF = 1<<31; typedef long long ll; typedef unsigned long long ull; inline int two(int n) { return 1 << n; } ///////////////////////////////////////////////////////////////////// int main() { ios::sync_with_stdio(false); //cout << fixed << setprecision(7); int n; cin >> n; vector<vector<int>> a(n, vector<int>(n, 0)); REP(i, n) REP(j, n) cin >> a[i][j]; REP(i, n) { REP(j, n) { bool good = (a[i][j] == 1); REP(k, n) { REP(m, n) { if(k == i || m == j) continue; if(!good && a[k][j]+a[i][m] == a[i][j]) good = true; } } if(!good) { cout << "No" << endl; return 0; } } } cout << "Yes" << endl; return 0; }
[ "amankarunakaran@Amans-MacBook-Pro.local" ]
amankarunakaran@Amans-MacBook-Pro.local
c21340262e284b5430c324725315974ae45f5873
c71af56951d1c661a5819db72da1caccd9130df2
/cpp/problems/cormen/misc/sorting/quicksort2.cpp
1baf8d9c9c99be007a89ed4fb31f43c2498dbe1e
[]
no_license
adrianpoplesanu/personal-work
2940a0dc4e4e27e0cc467875bae3fdea27dd0d31
adc289ecb72c1c6f98582f3ea9ad4bf2e8e08d29
refs/heads/master
2023-08-23T06:56:49.363519
2023-08-21T17:20:51
2023-08-21T17:20:51
109,451,981
0
1
null
2022-10-07T04:53:24
2017-11-03T23:36:21
Python
UTF-8
C++
false
false
3,919
cpp
#include <iostream> #include <ctime> void swap(int &a, int &b) { int aux = a; a = b; b = aux; } int partition (int a[1000], int low, int high) { int pivot = a[high]; int k = low; for (int i = low; i <= high; i++) { if (a[i] < a[high]) { swap(a[k], a[i]); k++; } } swap(a[k], a[high]); return k; } void quicksort(int a[1000], int low, int high) { if (low < high) { int mid = partition(a, low, high); quicksort(a, low, mid - 1); quicksort(a, mid + 1, high); } } int main(int argc, char *argv[]) { clock_t start = clock(); int a[1000] = {3, 1, 3, 9, 1, 6, 6, 4, 3, 7, 0, 2, 5, 0, 5, 4, 2, 7, 1, 4, 2, 0, 9, 8, 5, 8, 3, 1, 6, 9, 0, 0, 0, 7, 1, 1, 2, 8, 8, 8, 3, 0, 3, 8, 0, 7, 2, 7, 6, 4, 7, 4, 2, 5, 5, 5, 8, 0, 0, 6, 1, 6, 1, 0, 2, 7, 7, 7, 3, 4, 4, 6, 3, 7, 6, 0, 7, 4, 8, 6, 4, 8, 2, 5, 8, 5, 7, 0, 7, 2, 4, 2, 5, 3, 4, 4, 1, 9, 4, 9, 2, 4, 8, 3, 6, 4, 9, 1, 5, 1, 9, 3, 9, 4, 7, 1, 7, 0, 2, 6, 3, 0, 2, 0, 1, 6, 3, 2, 0, 9, 0, 5, 9, 1, 4, 9, 7, 0, 0, 0, 5, 1, 0, 4, 8, 3, 1, 6, 9, 2, 5, 8, 5, 3, 1, 9, 5, 0, 3, 0, 9, 2, 6, 2, 8, 0, 4, 5, 3, 3, 9, 5, 3, 6, 6, 3, 7, 8, 3, 9, 8, 9, 1, 7, 5, 5, 3, 5, 5, 4, 5, 4, 9, 4, 4, 6, 8, 5, 5, 9, 2, 1, 1, 1, 4, 5, 0, 8, 1, 2, 5, 0, 3, 8, 9, 0, 1, 1, 6, 5, 7, 3, 8, 5, 1, 1, 5, 5, 9, 3, 9, 6, 5, 4, 9, 8, 1, 7, 3, 7, 3, 5, 1, 5, 0, 5, 2, 1, 9, 0, 3, 6, 6, 8, 5, 2, 9, 2, 2, 6, 5, 6, 1, 1, 0, 3, 8, 4, 4, 2, 7, 2, 3, 5, 4, 0, 9, 7, 7, 9, 1, 7, 2, 6, 6, 7, 0, 2, 0, 3, 3, 2, 0, 8, 4, 9, 2, 3, 7, 1, 7, 3, 5, 2, 8, 2, 1, 2, 0, 7, 0, 3, 2, 2, 1, 8, 1, 8, 3, 4, 5, 3, 4, 4, 1, 5, 3, 7, 7, 3, 4, 6, 0, 1, 7, 0, 7, 0, 6, 4, 6, 2, 0, 8, 0, 1, 4, 8, 9, 1, 4, 4, 7, 2, 7, 0, 6, 0, 5, 3, 8, 7, 8, 6, 2, 3, 6, 2, 5, 1, 9, 0, 0, 7, 3, 3, 8, 4, 1, 4, 1, 1, 0, 9, 7, 9, 0, 4, 6, 5, 1, 9, 1, 7, 5, 1, 8, 8, 7, 3, 1, 8, 4, 0, 1, 9, 1, 6, 3, 9, 1, 8, 7, 4, 4, 6, 2, 2, 3, 3, 2, 7, 9, 2, 0, 8, 7, 0, 6, 2, 5, 5, 6, 0, 4, 4, 7, 3, 0, 8, 7, 6, 9, 8, 2, 5, 1, 6, 8, 4, 5, 9, 6, 0, 8, 5, 2, 9, 7, 7, 1, 5, 1, 2, 4, 3, 0, 4, 1, 7, 8, 1, 3, 1, 1, 6, 7, 4, 6, 3, 9, 8, 7, 8, 7, 7, 6, 7, 0, 0, 8, 4, 4, 9, 7, 9, 5, 5, 8, 4, 4, 4, 7, 6, 9, 9, 5, 5, 2, 0, 6, 0, 5, 1, 8, 7, 5, 5, 7, 7, 5, 6, 7, 2, 9, 1, 9, 9, 0, 2, 4, 3, 4, 4, 8, 0, 2, 8, 1, 9, 5, 3, 3, 6, 6, 0, 3, 6, 4, 7, 9, 1, 5, 0, 6, 8, 6, 1, 5, 8, 5, 2, 8, 5, 3, 8, 2, 4, 8, 1, 1, 2, 0, 3, 0, 8, 5, 9, 2, 5, 6, 8, 1, 0, 2, 2, 9, 6, 3, 7, 0, 6, 4, 7, 1, 3, 4, 8, 2, 2, 9, 0, 4, 7, 9, 4, 1, 0, 7, 7, 9, 9, 9, 6, 8, 4, 8, 4, 2, 7, 6, 6, 5, 5, 0, 1, 2, 3, 8, 8, 1, 1, 3, 1, 9, 0, 8, 8, 7, 4, 6, 4, 1, 9, 6, 1, 0, 6, 2, 4, 9, 7, 3, 4, 3, 8, 2, 7, 4, 8, 1, 9, 7, 8, 4, 9, 4, 9, 0, 2, 4, 6, 4, 5, 3, 9, 6, 8, 5, 2, 8, 3, 1, 1, 3, 2, 2, 8, 7, 6, 3, 9, 2, 4, 3, 6, 9, 9, 2, 3, 6, 0, 2, 3, 3, 7, 1, 5, 8, 8, 9, 4, 9, 0, 0, 2, 2, 4, 9, 7, 1, 9, 0, 9, 5, 2, 2, 0, 8, 7, 2, 8, 8, 3, 8, 6, 3, 9, 6, 9, 1, 4, 8, 6, 2, 7, 4, 1, 6, 8, 3, 9, 8, 6, 4, 2, 8, 4, 4, 5, 7, 6, 2, 6, 8, 6, 6, 2, 3, 5, 9, 5, 7, 4, 8, 4, 1, 0, 4, 8, 9, 8, 3, 0, 5, 3, 3, 0, 3, 0, 6, 9, 8, 7, 0, 7, 3, 8, 9, 2, 7, 0, 8, 8, 1, 1, 8, 7, 4, 9, 5, 8, 1, 0, 5, 4, 8, 7, 9, 1, 3, 5, 4, 5, 0, 7, 5, 5, 1, 2, 6, 0, 1, 6, 6, 0, 2, 1, 2, 5, 2, 1, 3, 9, 6, 8, 5, 5, 2, 1, 9, 7, 0, 7, 3, 4, 8, 0, 0, 9, 4, 5, 1, 2, 7, 8, 5, 7, 0, 3, 4, 7, 5, 4, 9, 2, 1, 8, 5, 9, 0, 3, 6, 9, 1, 7, 9, 5, 7, 0, 6, 7, 8, 3, 5, 0, 5, 3, 6, 5, 8, 3, 8, 7, 3, 3, 3, 4, 1, 4, 1, 5, 1, 9, 6, 2, 3, 1, 5, 5, 2, 7, 4, 4, 3, 0, 9, 6, 6, 7, 7, 8, 4, 5, 3, 1, 5, 4, 8, 6, 6, 1, 7, 4, 3, 3, 2, 1, 2, 4, 9, 5, 4, 7, 5, 0, 1, 4, 8, 3, 2, 3, 2, 5, 9, 6, 5, 0, 1, 9, 4, 4, 6, 4, 9, 6, 9, 8, 9, 6, 0, 8, 4, 6, 4, 1, 3, 4, 3, 7, 3, 9, 8, 3, 6, 1, 8, 9, 0, 6}; quicksort(a, 0, 999); for (int i = 0; i < 1000; i++) { std::cout << a[i] << " "; } std::cout << "\n"; clock_t end = clock(); std::cout << "ran for " << (double) (end - start) / CLOCKS_PER_SEC << " seconds\n"; return 0; }
[ "adrian.poplesanu@yahoo.com" ]
adrian.poplesanu@yahoo.com
9d1248303ac6b7099d45d413f5a57b28cce922e5
bfd219535db029621e60e3b8f7bf1269d94391f7
/ode_wrapper.h
cafd8140f5911c99da75deb02e465f02ffbd5e53
[ "MIT" ]
permissive
siddharthdeore/satellite_dynamics_cpp
307d00ac853c8f3536325262c024bc772f35dbde
3fe6148b99ad2391242a2aa9e413fa3723b998f5
refs/heads/master
2021-09-20T03:42:26.603185
2021-08-05T12:38:51
2021-08-05T12:38:51
240,809,846
0
0
null
null
null
null
UTF-8
C++
false
false
929
h
/* Satellite Attitude Dynamics Stepper @ref : boost lib */ #pragma once template< class Obj, class Mem > class ode_wrapper { Obj m_obj; Mem m_mem; public: ode_wrapper(Obj obj, Mem mem) : m_obj(obj), m_mem(mem) { } template< class State, class Deriv, class Time > void operator()(const State& x, Deriv& dxdt, Time t) { (m_obj.*m_mem)(x, dxdt, t); } }; template< class Obj, class Mem > ode_wrapper< Obj, Mem > make_ode_wrapper(Obj obj, Mem mem) { return ode_wrapper< Obj, Mem >(obj, mem); } template< class Obj, class Mem > class observer_wrapper { Obj m_obj; Mem m_mem; public: observer_wrapper(Obj obj, Mem mem) : m_obj(obj), m_mem(mem) { } template< class State, class Time > void operator()(const State& x, Time t) { (m_obj.*m_mem)(x, t); } }; template< class Obj, class Mem > observer_wrapper< Obj, Mem > make_observer_wrapper(Obj obj, Mem mem) { return observer_wrapper< Obj, Mem >(obj, mem); }
[ "siddharthdeore@gmail.com" ]
siddharthdeore@gmail.com
3b1a8bfc1c77c6bd49e595a846113fe47543fdd3
0f0df7351c29d0ec9178afb44225c84d6e28ccd6
/DicomInfo.cpp
eb65816c93ded116168adf7e13dfe6a77b433e7d
[]
no_license
gbook/miview
070cde96c1dfbc55ea6ff8f3a87bf7004c4862e2
eea025e8e24fdd5e40986ee42eb8ea00e860b79a
refs/heads/master
2021-01-10T11:16:50.802257
2015-07-16T19:44:45
2015-07-16T19:44:45
36,947,429
1
0
null
null
null
null
UTF-8
C++
false
false
5,504
cpp
/* ---------------------------------------------------------------------------- DicomInfo.cpp MIView - Medical Image Viewer Copyright (C) 2009-2011 Gregory Book MIView 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 along with this program. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------- */ #include "MainFrame.h" //#include "LogWindow.h" #include "ImageData.h" #include "DicomInfo.h" #include "wx/dir.h" #include "wx/File.h" // -------------------------------------------------------- // ---------- DicomInfo ----------------------------------- // -------------------------------------------------------- DicomInfo::DicomInfo() { //logWindow = &logwind; InitializeVariables(); } // -------------------------------------------------------- // ---------- ~DicomInfo ---------------------------------- // -------------------------------------------------------- DicomInfo::~DicomInfo(void) { } // -------------------------------------------------------- // ---------- InitializeVariables ------------------------- // -------------------------------------------------------- void DicomInfo::InitializeVariables() { WriteLog("DicomInfo->InitializeVariables() called..."); rowCosines.SetXYZ(0.0,0.0,0.0); colCosines.SetXYZ(0.0,0.0,0.0); normCosines.SetXYZ(0.0,0.0,0.0); /* initialize orientation */ // orientation.highLabelX = "?"; // orientation.highLabelY = "?"; // orientation.highLabelZ = "?"; // orientation.lowLabelX = "?"; // orientation.lowLabelY = "?"; // orientation.lowLabelZ = "?"; // orientation.isOblique = false; // orientation.reverseX = false; // orientation.reverseY = false; // orientation.reverseZ = false; } /* the Get functions */ wxString DicomInfo::GetModality() { return modality; } wxString DicomInfo::GetModalityDescription() { return modalityDescription; } XYZTriplet DicomInfo::GetRowCosines() { return rowCosines; } XYZTriplet DicomInfo::GetColCosines() { return colCosines; } XYZTriplet DicomInfo::GetNormCosines() { return normCosines; } wxString DicomInfo::GetPatientName() { return patientName; } wxString DicomInfo::GetPatientID() { return patientID; } wxString DicomInfo::GetPatientBirthdate() { return patientBirthdate; } wxString DicomInfo::GetPatientSex() { return patientSex; } wxString DicomInfo::GetInstitutionName() { return institutionName; } wxString DicomInfo::GetStudyDate() { return studyDate; } wxString DicomInfo::GetSeriesDate() { return seriesDate; } wxString DicomInfo::GetStudyTime() { return studyTime; } wxString DicomInfo::GetSeriesTime() { return seriesTime; } wxString DicomInfo::GetStudyDescription() { return studyDescription; } wxString DicomInfo::GetSeriesDescription() { return seriesDescription; } wxString DicomInfo::GetPerformingPhysician() { return performingPhysician; } wxString DicomInfo::GetProtocolName() { return protocolName; } wxString DicomInfo::GetPatientPositionStr() { return patientPositionStr; } int DicomInfo::GetPatientPosition() { return patientPosition; } wxDateTime DicomInfo::GetStudyDateTime() { return studyDateTime; } wxDateTime DicomInfo::GetSeriesDateTime() { return seriesDateTime; } int DicomInfo::GetSwapCode() { return swapCode; } /* the Set functions */ void DicomInfo::SetColCosines(XYZTriplet value) { colCosines = value; } void DicomInfo::SetNormCosines(XYZTriplet value) { normCosines = value; } void DicomInfo::SetInstitutionName(wxString value) { institutionName = value; } void DicomInfo::SetModality(wxString value) { modality = value; } void DicomInfo::SetModalityDescription(wxString value) { modalityDescription = value; } void DicomInfo::SetPatientBirthdate(wxString value) { patientBirthdate = value; } void DicomInfo::SetPatientSex(wxString value) { patientSex = value; } void DicomInfo::SetPatientID(wxString value) { patientID = value; } void DicomInfo::SetPatientName(wxString value) { patientName = value; } void DicomInfo::SetPatientPosition(int value) { patientPosition = value; } void DicomInfo::SetPatientPositionStr(wxString value) { patientPositionStr = value; } void DicomInfo::SetPerformingPhysician(wxString value) { performingPhysician = value; } void DicomInfo::SetProtocolName(wxString value) { protocolName = value; } void DicomInfo::SetRowCosines(XYZTriplet value) { rowCosines = value; } void DicomInfo::SetSeriesDate(wxString value) { seriesDate = value; } void DicomInfo::SetSeriesDateTime(wxDateTime value) { seriesDateTime = value; } void DicomInfo::SetSeriesDescription(wxString value) { seriesDescription = value; } void DicomInfo::SetSeriesTime(wxString value) { seriesTime = value; } void DicomInfo::SetStudyDate(wxString value) { studyDate = value; } void DicomInfo::SetStudyDateTime(wxDateTime value) { studyDateTime = value; } void DicomInfo::SetStudyDescription(wxString value) { studyDescription = value; } void DicomInfo::SetStudyTime(wxString value) { studyTime = value; } void DicomInfo::SetSwapCode(int value) { swapCode = value; }
[ "gregory.a.book@gmail.com" ]
gregory.a.book@gmail.com
bbf8c25663fe20c87157d88608cf1c50f821d424
66b56f8e01c3f9bb3cd86a412b850291ee4bd7c3
/all/projects/greencloud/lib/libglobals.cpp
40bc30fd51d7f36fc140fa464e5b8cdd5aafb3e7
[]
no_license
arikhativa/infi
d6cd490fc9939bf927e1c6abf8847b3667c1d604
e1e47d0bc62d52b92d7b0c8afc43695fe8639c79
refs/heads/master
2020-06-25T10:53:06.801593
2020-02-04T14:10:44
2020-02-04T14:10:44
199,287,862
0
0
null
null
null
null
UTF-8
C++
false
false
156
cpp
#include <errno.h> // errno #include "handleton.hpp" #include "logger.hpp" namespace hrd11 { INIT_HANDLETON(Logger) } // end namespace hrd11
[ "yoavrbb@gmail.com" ]
yoavrbb@gmail.com
abe6fa9be75e195be1d47b0c7cd77423c33b811c
0329788a6657e212944fd1dffb818111e62ee2b0
/docs/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.Layout.LayoutEngine/cpp/DemoFlowLayout.cpp
8e76df324ea7ab9da63d9cbe82f858731b83c2fe
[ "CC-BY-4.0", "MIT" ]
permissive
MicrosoftDocs/visualstudio-docs
3e506da16412dfee1f83e82a600c7ce0041c0f33
bff072c38fcfc60cd02c9d1d4a7959ae26a8e23c
refs/heads/main
2023-09-01T16:13:32.046442
2023-09-01T14:26:34
2023-09-01T14:26:34
73,740,273
1,050
1,984
CC-BY-4.0
2023-09-14T17:04:58
2016-11-14T19:36:53
Python
UTF-8
C++
false
false
3,735
cpp
// <snippet1> #using <System.Drawing.dll> #using <System.dll> #using <System.Windows.Forms.dll> using namespace System; using namespace System::Collections::Generic; using namespace System::Drawing; using namespace System::Text; using namespace System::Windows::Forms; using namespace System::Windows::Forms::Layout; // <snippet3> // This class demonstrates a simple custom layout engine. public ref class DemoFlowLayout : public LayoutEngine { // <snippet4> public: virtual bool Layout(Object^ container, LayoutEventArgs^ layoutEventArgs) override { Control^ parent = nullptr; try { parent = (Control ^) container; } catch (InvalidCastException^ ex) { throw gcnew ArgumentException( "The parameter 'container' must be a control", "container", ex); } // Use DisplayRectangle so that parent.Padding is honored. Rectangle parentDisplayRectangle = parent->DisplayRectangle; Point nextControlLocation = parentDisplayRectangle.Location; for each (Control^ currentControl in parent->Controls) { // Only apply layout to visible controls. if (!currentControl->Visible) { continue; } // Respect the margin of the control: // shift over the left and the top. nextControlLocation.Offset(currentControl->Margin.Left, currentControl->Margin.Top); // Set the location of the control. currentControl->Location = nextControlLocation; // Set the autosized controls to their // autosized heights. if (currentControl->AutoSize) { currentControl->Size = currentControl->GetPreferredSize( parentDisplayRectangle.Size); } // Move X back to the display rectangle origin. nextControlLocation.X = parentDisplayRectangle.X; // Increment Y by the height of the control // and the bottom margin. nextControlLocation.Y += currentControl->Height + currentControl->Margin.Bottom; } // Optional: Return whether or not the container's // parent should perform layout as a result of this // layout. Some layout engines return the value of // the container's AutoSize property. return false; } // </snippet4> }; // </snippet3> // <snippet2> // This class demonstrates a simple custom layout panel. // It overrides the LayoutEngine property of the Panel // control to provide a custom layout engine. public ref class DemoFlowPanel : public Panel { private: DemoFlowLayout^ layoutEngine; public: DemoFlowPanel() { layoutEngine = gcnew DemoFlowLayout(); } public: virtual property System::Windows::Forms::Layout::LayoutEngine^ LayoutEngine { System::Windows::Forms::Layout::LayoutEngine^ get() override { if (layoutEngine == nullptr) { layoutEngine = gcnew DemoFlowLayout(); } return layoutEngine; } } }; // </snippet2> // </snippet1> public ref class TestForm : public Form { public: TestForm() { Panel^ testPanel = gcnew DemoFlowPanel(); for (int i = 0; i < 10; i ++) { Button^ b = gcnew Button(); testPanel->Controls->Add(b); b->Text = i.ToString( System::Globalization::CultureInfo::CurrentCulture); } this->Controls->Add(testPanel); } }; [STAThread] int main() { Application::Run(gcnew TestForm()); }
[ "v-zhecai@microsoft.com" ]
v-zhecai@microsoft.com
9604441a75cf7b692fec23f6e7a4129937e2daed
2001d14621bde954b6108d180645a893b6f47f6a
/src/ircommon-test/src/iltags/ILTagFactoryTest.cpp
458ca4d5e7b38b1e6bcc86592dc4aa7291f6f61f
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
interlockledger/interlockrecord
408810b20ec00da73be1fc6628b723d77ab8ed1b
e8336d421b101df50c3a84d0aedb3768a8851baa
refs/heads/master
2021-01-25T13:41:19.356054
2018-08-26T02:12:46
2018-08-26T02:12:46
123,603,853
1
0
null
null
null
null
UTF-8
C++
false
false
11,123
cpp
/* * Copyright (c) 2017-2018 InterlockLedger Network * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ILTagFactoryTest.h" #include <ircommon/iltag.h> #include <ircommon/iltagstd.h> #include <ircommon/ilint.h> #include <cstring> using namespace ircommon; using namespace ircommon::iltags; //============================================================================== // class ILTagFactoryTest //------------------------------------------------------------------------------ ILTagFactoryTest::ILTagFactoryTest() { } //------------------------------------------------------------------------------ ILTagFactoryTest::~ILTagFactoryTest() { } //------------------------------------------------------------------------------ void ILTagFactoryTest::SetUp() { } //------------------------------------------------------------------------------ void ILTagFactoryTest::TearDown() { } //------------------------------------------------------------------------------ TEST_F(ILTagFactoryTest,Constructor) { ILTagFactory * f; f = new ILTagFactory(); ASSERT_FALSE(f->secure()); ASSERT_FALSE(f->strictMode()); delete f; f = new ILTagFactory(false); ASSERT_FALSE(f->secure()); ASSERT_FALSE(f->strictMode()); delete f; f = new ILTagFactory(true); ASSERT_TRUE(f->secure()); ASSERT_FALSE(f->strictMode()); delete f; f = new ILTagFactory(false, false); ASSERT_FALSE(f->secure()); ASSERT_FALSE(f->strictMode()); delete f; f = new ILTagFactory(true, false); ASSERT_TRUE(f->secure()); ASSERT_FALSE(f->strictMode()); delete f; f = new ILTagFactory(false, true); ASSERT_FALSE(f->secure()); ASSERT_TRUE(f->strictMode()); delete f; f = new ILTagFactory(true, true); ASSERT_TRUE(f->secure()); ASSERT_TRUE(f->strictMode()); delete f; } //------------------------------------------------------------------------------ TEST_F(ILTagFactoryTest, create) { ILTagFactory f; f.setSecure(false); f.setStrictMode(false); for (int tagId = 0; tagId < 256; tagId++) { ILTag * tag = f.create(tagId); ASSERT_TRUE(tag != nullptr); ASSERT_EQ(tagId, tag->id()); ASSERT_EQ(typeid(*tag), typeid(ILRawTag)); ASSERT_FALSE(static_cast<ILRawTag*>(tag)->secure()); delete tag; } f.setSecure(false); f.setStrictMode(true); for (int tagId = 0; tagId < 256; tagId++) { ASSERT_EQ(nullptr, f.create(tagId)); } f.setSecure(true); f.setStrictMode(false); for (int tagId = 0; tagId < 256; tagId++) { ILTag * tag = f.create(tagId); ASSERT_TRUE(tag != nullptr); ASSERT_EQ(tagId, tag->id()); ASSERT_EQ(typeid(*tag), typeid(ILRawTag)); ASSERT_TRUE(static_cast<ILRawTag*>(tag)->secure()); delete tag; } f.setSecure(true); f.setStrictMode(true); for (int tagId = 0; tagId < 256; tagId++) { ASSERT_EQ(nullptr, f.create(tagId)); } } //------------------------------------------------------------------------------ TEST_F(ILTagFactoryTest, secure) { ILTagFactory f(false); ILTagFactory sf(true); ASSERT_FALSE(f.secure()); ASSERT_TRUE(sf.secure()); } //------------------------------------------------------------------------------ TEST_F(ILTagFactoryTest, deserialize) { ILTagFactory f; IRBuffer b; std::uint8_t buff[256]; ILTag * t; ILRawTag * r; for (unsigned int i = 0; i < sizeof(buff); i++) { buff[i] = i; } // Empty b.setSize(0); t = f.deserialize(b); ASSERT_TRUE(t == nullptr); // Implicity tags for (int tagId = 0; tagId < 16; tagId++) { if (tagId != ILTag::TAG_ILINT64) { b.setSize(0); b.writeILInt(tagId); b.write(buff, ILTag::getImplicitValueSize(tagId)); b.beginning(); t = f.deserialize(b); ASSERT_EQ(b.size(), b.position()); ASSERT_TRUE(t != nullptr); ASSERT_EQ(tagId, t->id()); ASSERT_EQ(ILTag::getImplicitValueSize(tagId), t->size()); r = static_cast<ILRawTag *>(t); ASSERT_EQ(0, std::memcmp(buff, r->value().roBuffer(), t->size())); delete t; // Incomplete b.setSize(b.size() - 1); b.beginning(); t = f.deserialize(b); ASSERT_TRUE(t == nullptr); } } // Explicit tags for (int tagId = 16; tagId < 256; tagId++) { if (tagId != ILTag::TAG_ILINT64) { b.setSize(0); b.writeILInt(tagId); b.writeILInt(tagId); b.write(buff, tagId); b.beginning(); t = f.deserialize(b); ASSERT_EQ(b.size(), b.position()); ASSERT_TRUE(t != nullptr); ASSERT_EQ(tagId, t->id()); ASSERT_EQ(tagId, t->size()); r = static_cast<ILRawTag *>(t); ASSERT_EQ(0, std::memcmp(buff, r->value().roBuffer(), t->size())); delete t; // Incomplete b.setSize(b.size() - 1); b.beginning(); t = f.deserialize(b); ASSERT_TRUE(t == nullptr); } } // TAG_ILINT64 b.setSize(0); b.writeILInt(ILTag::TAG_ILINT64); b.writeILInt(0); b.beginning(); t = f.deserialize(b); ASSERT_EQ(b.size(), b.position()); ASSERT_TRUE(t != nullptr); ASSERT_EQ(ILTag::TAG_ILINT64, t->id()); ASSERT_EQ(1, t->size()); r = static_cast<ILRawTag *>(t); ASSERT_EQ(0, std::memcmp(buff, r->value().roBuffer(), t->size())); delete t; std::uint64_t exp = 0xFF; for (int i = 1; i < 9; i++) { // TAG_ILINT64 b.setSize(0); b.writeILInt(ILTag::TAG_ILINT64); b.writeILInt(exp); b.beginning(); t = f.deserialize(b); ASSERT_EQ(b.size(), b.position()); ASSERT_TRUE(t != nullptr); ASSERT_EQ(ILTag::TAG_ILINT64, t->id()); ASSERT_EQ(ILInt::size(exp), t->size()); r = static_cast<ILRawTag *>(t); std::uint64_t v; ASSERT_TRUE(ILInt::decode(r->value().roBuffer(), t->size(), &v)); ASSERT_EQ(exp, v); delete t; // Fail // Incomplete b.setSize(b.size() - 1); b.beginning(); t = f.deserialize(b); ASSERT_TRUE(t == nullptr); exp = (exp << 8) | 0xFF; } } //------------------------------------------------------------------------------ TEST_F(ILTagFactoryTest, deserializeStrict) { ILTagFactory f; IRBuffer b; std::uint8_t buff[256]; ILTag * t; f.setStrictMode(true); for (unsigned int i = 0; i < sizeof(buff); i++) { buff[i] = i; } // Empty b.setSize(0); t = f.deserialize(b); ASSERT_TRUE(t == nullptr); // Implicity tags for (int tagId = 0; tagId < 16; tagId++) { if (tagId != ILTag::TAG_ILINT64) { b.setSize(0); b.writeILInt(tagId); b.write(buff, ILTag::getImplicitValueSize(tagId)); b.beginning(); ASSERT_TRUE(f.deserialize(b) == nullptr); // Incomplete b.setSize(b.size() - 1); b.beginning(); t = f.deserialize(b); ASSERT_TRUE(t == nullptr); } } // Explicit tags for (int tagId = 16; tagId < 256; tagId++) { if (tagId != ILTag::TAG_ILINT64) { b.setSize(0); b.writeILInt(tagId); b.writeILInt(tagId); b.write(buff, tagId); b.beginning(); ASSERT_TRUE(f.deserialize(b) == nullptr); // Incomplete b.setSize(b.size() - 1); b.beginning(); t = f.deserialize(b); ASSERT_TRUE(t == nullptr); } } // TAG_ILINT64 b.setSize(0); b.writeILInt(ILTag::TAG_ILINT64); b.writeILInt(0); b.beginning(); ASSERT_TRUE(f.deserialize(b) == nullptr); std::uint64_t exp = 0xFF; for (int i = 1; i < 9; i++) { // TAG_ILINT64 b.setSize(0); b.writeILInt(ILTag::TAG_ILINT64); b.writeILInt(exp); b.beginning(); ASSERT_TRUE(f.deserialize(b) == nullptr); // Fail // Incomplete b.setSize(b.size() - 1); b.beginning(); t = f.deserialize(b); ASSERT_TRUE(t == nullptr); exp = (exp << 8) | 0xFF; } } //------------------------------------------------------------------------------ TEST_F(ILTagFactoryTest, extractTagHeader) { IRBuffer b; std::uint64_t rTagId; std::uint64_t rTagSize; // No data b.setSize(0); ASSERT_FALSE(ILTagFactory::extractTagHeader(b, rTagId, rTagSize)); // Basic for (int tagId = 0; tagId < 16; tagId++) { if (tagId != ILTag::TAG_ILINT64) { b.setSize(0); b.writeILInt(tagId); b.beginning(); ASSERT_TRUE(ILTagFactory::extractTagHeader(b, rTagId, rTagSize)); ASSERT_EQ(b.size(), b.position()); ASSERT_EQ(tagId, rTagId); ASSERT_EQ(ILTag::getImplicitValueSize(tagId), rTagSize); // No bytes left ASSERT_FALSE(ILTagFactory::extractTagHeader(b, rTagId, rTagSize)); } } // TAG_ILINT64 for (std::uint64_t size = 0xF7; size <= 0xFF; size++) { b.setSize(0); b.writeILInt(ILTag::TAG_ILINT64); b.write(size); b.beginning(); ASSERT_TRUE(ILTagFactory::extractTagHeader(b, rTagId, rTagSize)); ASSERT_EQ(1, b.position()); ASSERT_EQ(ILTag::TAG_ILINT64, rTagId); ASSERT_EQ((size - 0xF8 + 2), rTagSize); // No bytes left b.setSize(1); b.beginning(); ASSERT_FALSE(ILTagFactory::extractTagHeader(b, rTagId, rTagSize)); } // Generic for (int tagId = 16; tagId < 256; tagId++) { if (tagId != ILTag::TAG_ILINT64) { b.setSize(0); b.writeILInt(tagId); b.writeILInt(tagId + 1); b.beginning(); ASSERT_TRUE(ILTagFactory::extractTagHeader(b, rTagId, rTagSize)); ASSERT_EQ(tagId, rTagId); ASSERT_EQ(tagId + 1, rTagSize); // Incomplete size b.setSize(b.size() - 1); b.beginning(); ASSERT_FALSE(ILTagFactory::extractTagHeader(b, rTagId, rTagSize)); // No size b.setSize(0); b.writeILInt(tagId); b.beginning(); ASSERT_FALSE(ILTagFactory::extractTagHeader(b, rTagId, rTagSize)); // Incomplete ID b.setSize(b.size() - 1); b.beginning(); ASSERT_FALSE(ILTagFactory::extractTagHeader(b, rTagId, rTagSize)); } } } //------------------------------------------------------------------------------ TEST_F(ILTagFactoryTest, strictMode) { ILTagFactory f; ASSERT_FALSE(f.strictMode()); f.setStrictMode(true); ASSERT_TRUE(f.strictMode()); f.setStrictMode(false); ASSERT_FALSE(f.strictMode()); } //------------------------------------------------------------------------------ TEST_F(ILTagFactoryTest, deserializeIRBufferILTag) { ILTagFactory f; IRBuffer out; ILInt64Tag uint64Tag; ILInt32Tag uint32Tag; ILStringTag stringTag; std::string s; // Implicity ASSERT_TRUE(out.writeILInt(ILTag::TAG_INT64)); ASSERT_TRUE(out.writeInt(std::uint64_t(0xFACADA))); out.beginning(); ASSERT_TRUE(f.deserialize(out, uint64Tag)); ASSERT_EQ(0xFACADA, uint64Tag.value()); out.beginning(); ASSERT_FALSE(f.deserialize(out, uint32Tag)); out.beginning(); ASSERT_FALSE(f.deserialize(out, stringTag)); // Full tag s = "And so it begins."; out.beginning(); ASSERT_TRUE(out.writeILInt(ILTag::TAG_STRING)); ASSERT_TRUE(out.writeILInt(s.size())); ASSERT_TRUE(out.write(s.c_str(), s.size())); out.beginning(); ASSERT_TRUE(f.deserialize(out, stringTag)); ASSERT_STREQ(s.c_str(), stringTag.value().c_str()); out.beginning(); ASSERT_FALSE(f.deserialize(out, uint32Tag)); out.beginning(); ASSERT_FALSE(f.deserialize(out, uint64Tag)); } //------------------------------------------------------------------------------
[ "fchino@opencs.com.br" ]
fchino@opencs.com.br
fd45403060165aca41c118ac72e6cf596465837c
0c89531a6444fa640929b500009206fb4aa0d11d
/Move.cpp
e71a101aba2d786c352aa9852a14814569aca8d6
[]
no_license
aboelmakarem/shatranj
147d9282a17da60d27ebf87978901adff7d2f673
8d256bc5a52728cee7d0746a97affca77f8d0544
refs/heads/master
2020-06-25T20:54:36.781060
2017-06-16T22:46:29
2017-06-16T22:46:29
94,240,543
0
0
null
null
null
null
UTF-8
C++
false
false
2,157
cpp
// Move.cpp // June 13th, 2017 // Ahmed Hussein (amhussein4@gmail.com) #include "Move.h" #include "Board.h" #include "Piece.h" namespace Shatranj { Move::Move() { Initialize(); } Move::Move(const Move& oMove) { *this = oMove; } Move::Move(Piece* poPiece,Square* poFromSquare,Square* poToSquare) { Initialize(); m_poPiece = poPiece; m_poFromSquare = poFromSquare; m_poToSquare = poToSquare; } Move::~Move() { Reset(); } Move& Move::operator=(const Move& oMove) { m_poPiece = oMove.m_poPiece; m_poFromSquare = oMove.m_poFromSquare; m_poToSquare = oMove.m_poToSquare; m_bIsCapture = oMove.m_bIsCapture; m_bIsCastle = oMove.m_bIsCastle; m_bIsPromotion = oMove.m_bIsPromotion; m_bIsEnPassant = oMove.m_bIsEnPassant; return *this; } void Move::Reset() { Initialize(); } void Move::SetPiece(Piece* poPiece) { m_poPiece = poPiece; } void Move::SetFromSquare(Square* poSquare) { m_poFromSquare = poSquare; } void Move::SetToSquare(Square* poSquare) { m_poToSquare = poSquare; } void Move::MakeCapture() { m_bIsCapture = true; m_bIsCastle = false; m_bIsPromotion = false; } void Move::MakeCastle() { m_bIsCapture = false; m_bIsCastle = true; m_bIsPromotion = true; m_bIsEnPassant = false; } void Move::MakePromotion() { m_bIsCapture = false; m_bIsCastle = false; m_bIsPromotion = true; m_bIsEnPassant = false; } void Move::MakeEnPassant() { m_bIsCapture = true; m_bIsCastle = false; m_bIsPromotion = false; m_bIsEnPassant = true; } Piece* Move::GetPiece() const { return m_poPiece; } Square* Move::GetFromSquare() const { return m_poFromSquare; } Square* Move::GetToSquare() const { return m_poToSquare; } bool Move::IsCapture() const { return m_bIsCapture; } bool Move::IsCastle() const { return m_bIsCastle; } bool Move::IsPromotion() const { return m_bIsPromotion; } bool Move::IsEnPassant() const { return m_bIsEnPassant; } void Move::Initialize() { m_poPiece = 0; m_poFromSquare = 0; m_poToSquare = 0; m_bIsCapture = false; m_bIsCastle = false; m_bIsPromotion = false; m_bIsEnPassant = false; } }
[ "ahussein@sdiahussein.win.ansys.com" ]
ahussein@sdiahussein.win.ansys.com
872222364710f50a7314b59bc9627177256f3d5d
7972eb32736afd695dc94fffcc9d1b24aa65e8ac
/Algoritmos 2/Entrega6/Entrega6/CasoDePrueba.cpp
7f8f60a5cb6376b3812337e4906a40c52a6cb398
[]
no_license
FedeJacobo/CodigosDelSur
1f0cfd2c07b6ed1317d59e4507e8a59acb09ad65
661b30deadda7324f1f9c2c0e8edb60f8742a2dd
refs/heads/master
2022-12-29T15:48:50.544026
2020-10-20T20:38:03
2020-10-20T20:38:03
305,826,910
0
0
null
null
null
null
UTF-8
C++
false
false
34,923
cpp
#include "CasoDePrueba.h" CasoDePrueba::CasoDePrueba(Puntero<ISistema>(*inicializar)()) { this->inicializar = inicializar; } Puntero<ISistema> CasoDePrueba::InicializarSistema() { Puntero<ISistema> interfaz = inicializar(); ignorarOK = false; return interfaz; } Cadena CasoDePrueba::GetNombre()const { return "Casos de Prueba"; } void CasoDePrueba::CorrerPruebaConcreta() { PruebaLaberinto(); PruebaViajero(); PruebaDegustacion(); PruebaViajero2(); PruebaProteccionAnimales(); PruebaQuickSort(); PruebaCaminoCaballo(); PruebaOptimizarGranja(); PruebaInscribirMaterias(); } void CasoDePrueba::Verificar(TipoRetorno obtenido, TipoRetorno esperado, Cadena comentario) { if (!ignorarOK || obtenido != esperado) Prueba::Verificar(obtenido, esperado, comentario); } template <class T> void CasoDePrueba::Verificar(const T& obtenido, const T& esperado, Cadena comentario) { Verificar(SonIguales(obtenido, esperado) ? OK : ERROR, OK, comentario.DarFormato(ObtenerTexto(obtenido), ObtenerTexto(esperado))); } template <class T> void CasoDePrueba::VerificarConjuntos(Iterador<T> obtenidos, Iterador<T> esperados, Cadena comentarioEncontrado, Cadena comentarioFalta, Cadena comentarioSobra) { bool verificarCantidad = true; nat totalObtenidos = 0; T aux; obtenidos.Reiniciar(); esperados.Reiniciar(); foreach(T obtenido, obtenidos) { totalObtenidos++; if (Pertenece(obtenido, esperados, aux)) Verificar(OK, OK, comentarioEncontrado.DarFormato(ObtenerTexto(obtenido), ObtenerTexto(obtenido))); else { Verificar(ERROR, OK, comentarioSobra.DarFormato(ObtenerTexto(obtenido))); verificarCantidad = false; } } nat totalEsperados = 0; obtenidos.Reiniciar(); esperados.Reiniciar(); foreach(T esperado, esperados) { totalEsperados++; if (!Pertenece(esperado, obtenidos, aux)) { Verificar(ERROR, OK, comentarioFalta.DarFormato(ObtenerTexto(esperado))); verificarCantidad = false; } } if (verificarCantidad && totalObtenidos != totalEsperados) Verificar(ERROR, OK, "Se verifica la cantidad de elementos de los conjuntos"); } template <class T> void CasoDePrueba::VerificarSecuencias(Iterador<T> obtenidos, Iterador<T> esperados, Cadena comentarioEncontrado, Cadena comentarioFalta, Cadena comentarioSobra) { esperados.Reiniciar(); foreach(T obtenido, obtenidos) { if (esperados.HayElemento()) { T esperado = *esperados; ++esperados; Verificar(obtenido, esperado, comentarioEncontrado); } else Verificar(ERROR, OK, comentarioSobra.DarFormato(ObtenerTexto(obtenido))); } while (esperados.HayElemento()) { T esperado = *esperados; ++esperados; Verificar(ERROR, OK, comentarioFalta.DarFormato(ObtenerTexto(esperado))); } } bool CasoDePrueba::SonIguales(const Tupla<int, int>& obtenido, const Tupla<int, int>& esperado) const { return (obtenido.ObtenerDato1() == esperado.ObtenerDato1() && obtenido.ObtenerDato2() == esperado.ObtenerDato2()); } bool CasoDePrueba::SonIguales(const Tupla<nat, nat>& obtenido, const Tupla<nat, nat>& esperado) const { return (obtenido.ObtenerDato1() == esperado.ObtenerDato1() && obtenido.ObtenerDato2() == esperado.ObtenerDato2()); } bool CasoDePrueba::SonIguales(const Tupla<Cadena, bool>& obtenido, const Tupla<Cadena, bool>& esperado) const { return (obtenido.ObtenerDato1() == esperado.ObtenerDato1() && obtenido.ObtenerDato2() == esperado.ObtenerDato2()); } bool CasoDePrueba::SonIguales(const nat& obtenido, const nat& esperado) const { return (obtenido == esperado); } bool CasoDePrueba::SonIguales(const Puntero<ICiudad>& obtenido, const Puntero<ICiudad>& esperado) const { return obtenido->ObtenerNombre() == esperado->ObtenerNombre() && obtenido->ObtenerNumero() == esperado->ObtenerNumero(); } template <class T> bool CasoDePrueba::SonIguales(Iterador<T> obtenidos, Iterador<T> esperados) const { obtenidos.Reiniciar(); esperados.Reiniciar(); while (obtenidos.HayElemento() && esperados.HayElemento()) { if (!SonIguales(*obtenidos, *esperados)) return false; ++obtenidos; ++esperados; } return esperados.HayElemento() == obtenidos.HayElemento(); } Cadena CasoDePrueba::ObtenerTexto(const Tupla<int, int>& t) const { Cadena sep = ","; Cadena retorno = ObtenerTexto(t.ObtenerDato1()) + sep + ObtenerTexto(t.ObtenerDato2()); return retorno; } Cadena CasoDePrueba::ObtenerTexto(const Tupla<nat, nat>& t) const { Cadena sep = ","; Cadena retorno = ObtenerTexto(t.ObtenerDato1()) + sep + ObtenerTexto(t.ObtenerDato2()); return retorno; } Cadena CasoDePrueba::ObtenerTexto(const Tupla<Cadena, bool>& materia) const { Cadena turno = " - nocturo"; if (materia.Dato2) { turno = " - matutino"; } return materia.Dato1 + turno; } Cadena CasoDePrueba::ObtenerTexto(const Puntero<ICiudad>& t) const { return t->ObtenerNombre(); } Cadena CasoDePrueba::ObtenerTexto(nat n) const { char textoE[10]; _itoa_s(n, textoE, 10); Cadena nueva = "{0}"; return nueva.DarFormato(textoE); } template <class T> Cadena CasoDePrueba::ObtenerTexto(Iterador<T> it) const { Cadena sepVacio = ""; Cadena sepGuion = "-"; Cadena sep = sepVacio; Cadena retorno = sepVacio; foreach(auto t, it) { retorno += sep + ObtenerTexto(t); sep = sepGuion; } return retorno; } template <class T> bool CasoDePrueba::Pertenece(const T& dato, Iterador<T> iterador, T& encontrado) const { foreach(T dato2, iterador) { if (SonIguales(dato, dato2)) { encontrado = dato2; return true; } } return false; } void CasoDePrueba::VerificarCaminos(const Tupla<TipoRetorno, Iterador<Iterador<Tupla<int, int>>>>& obtenido, const Tupla<TipoRetorno, Iterador<Iterador<Tupla<int, int>>>>& esperado) { if (obtenido.Dato1 == OK && esperado.Dato1 == OK) { IniciarSeccion("Caminos Caballo", esperado.Dato1); VerificarConjuntos(obtenido.Dato2, esperado.Dato2, "Se obtuvo correctamente {0}", "Falta el Camino {0}", "No se esperaba el camino {0}"); CerrarSeccion(); } else Verificar(obtenido.Dato1, esperado.Dato1, "Caminos Caballo"); } void CasoDePrueba::VerificarViajero2(const Tupla<TipoRetorno, Iterador<nat>>& obtenido, const Tupla<TipoRetorno, Iterador<nat>>& esperado) { if (obtenido.Dato1 == OK && esperado.Dato1 == OK) { IniciarSeccion("Viajero 2", esperado.Dato1); VerificarSecuencias(obtenido.Dato2, esperado.Dato2, "Se obtuvo ciudad {0}", "Falta ciudad {0}", "No se esperaba ciudad {0}"); CerrarSeccion(); } else Verificar(obtenido.Dato1, esperado.Dato1, "Viajero 2"); } void CasoDePrueba::VerificarGranja(const Array<Tupla<nat, nat, nat>>& semillas, const Tupla<TipoRetorno, Array<nat>>& esperado, const Tupla<TipoRetorno, Array<nat>>& obtenido, nat maxdinero, nat maxtierra, nat maxagua) { if (obtenido.Dato1 == OK && esperado.Dato1 == OK) { IniciarSeccion("", esperado.Dato1); if (esperado.Dato2.Largo != obtenido.Dato2.Largo) { Verificar(ERROR, OK, "Se verifica el largo del retorno."); } else { //Tupla costo, agua, ganancia int sumaEsperada = 0; int sumaObtenida = 0; nat costo = 0; nat agua = 0; nat area = 0; for (nat i = 0; i < semillas.Largo; i++) { sumaEsperada += semillas[i].Dato3 * esperado.Dato2[i]; nat cantS = obtenido.Dato2[i]; sumaObtenida += semillas[i].Dato3 * cantS; area += cantS; agua += semillas[i].Dato2 * cantS; costo += semillas[i].Dato1 * cantS; } Verificar(sumaObtenida, sumaEsperada, "Se esperaba una ganancia total de '{1}' y se obtuvo '{0}'"); Cadena maxError = "Se esperaba '{0}' maximo '{1}' y se obtuvo '{2}'"; if (area > area) { Verificar(ERROR, OK, maxError.DarFormato("area", ObtenerTexto(maxtierra), ObtenerTexto(area))); } if (agua > maxagua) { Verificar(ERROR, OK, maxError.DarFormato("agua", ObtenerTexto(maxagua), ObtenerTexto(agua))); } if (costo > maxdinero) { Verificar(ERROR, OK, maxError.DarFormato("dinero", ObtenerTexto(maxdinero), ObtenerTexto(costo))); } } CerrarSeccion(); } else Verificar(obtenido.Dato1, esperado.Dato1, "Proteccion de animales"); } void CasoDePrueba::VerificarProteccionAnimales(const Array<Accion>& acciones, const Tupla<TipoRetorno, Array<nat>>& esperado, const Tupla<TipoRetorno, Array<nat>>& obtenido, nat maxVeterinarios, nat maxVehiculos, nat maxDinero, nat maxVacunas, nat maxVoluntarios) { if (obtenido.Dato1 == OK && esperado.Dato1 == OK) { IniciarSeccion("", esperado.Dato1); if (esperado.Dato2.Largo != obtenido.Dato2.Largo) { Verificar(ERROR, OK, "Se verifica el largo del retorno."); } else { int sumaEsperada = 0; int sumaObtenida = 0; nat veterinarios = 0; nat vehiculos = 0; nat dinero = 0; nat vacunas = 0; nat voluntarios = 0; for (nat i = 0; i < acciones.Largo; i++) { sumaEsperada += acciones[i].impacto * esperado.Dato2[i]; nat obtenidoCant = obtenido.Dato2[i]; sumaObtenida += acciones[i].impacto * obtenidoCant; veterinarios += acciones[i].veterinarios * obtenidoCant; vehiculos += acciones[i].vehiculos * obtenidoCant; dinero += acciones[i].dinero * obtenidoCant; vacunas += acciones[i].vacunas * obtenidoCant; voluntarios += acciones[i].voluntarios * obtenidoCant; } Verificar(sumaObtenida, sumaEsperada, "Se esperaba un impacto total de '{1}' y se obtuvo '{0}'"); Cadena maxError = "Se esperaba '{0}' maximo '{1}' y se obtuvo '{2}'"; if (veterinarios > maxVeterinarios) { Verificar(ERROR, OK, maxError.DarFormato("Veterinarios", ObtenerTexto(maxVeterinarios), ObtenerTexto(veterinarios))); } if (vehiculos > maxVehiculos) { Verificar(ERROR, OK, maxError.DarFormato("vehiculos", ObtenerTexto(maxVehiculos), ObtenerTexto(vehiculos))); } if (dinero > maxDinero) { Verificar(ERROR, OK, maxError.DarFormato("dinero", ObtenerTexto(maxDinero), ObtenerTexto(dinero))); } if (vacunas > maxVacunas) { Verificar(ERROR, OK, maxError.DarFormato("vacunas", ObtenerTexto(maxVacunas), ObtenerTexto(vacunas))); } if (voluntarios > maxVoluntarios) { Verificar(ERROR, OK, maxError.DarFormato("voluntarios", ObtenerTexto(maxVoluntarios), ObtenerTexto(voluntarios))); } } CerrarSeccion(); } else Verificar(obtenido.Dato1, esperado.Dato1, "Proteccion de animales"); } void CasoDePrueba::VerificarMaterias(const Tupla<TipoRetorno, Iterador<Tupla<Cadena, bool>>>& obtenido, const Tupla<TipoRetorno, Iterador<Tupla<Cadena, bool>>>& esperado) { if (obtenido.Dato1 == OK && esperado.Dato1 == OK) { IniciarSeccion("Materias", esperado.Dato1); VerificarConjuntos(obtenido.Dato2, esperado.Dato2, "Se obtuvo la materia '{0}'", "Falta la materia '{0}'", "No se esperaba la materia '{0}'"); CerrarSeccion(); } else Verificar(obtenido.Dato1, esperado.Dato1, "Materias"); } void CasoDePrueba::PruebaLaberinto() { IniciarSeccion("Laberinto"); Puntero<ISistema> interfaz = InicializarSistema(); Matriz<nat> laberinto = Matriz<nat>(14,9); for ( nat i = 0; i < laberinto.Largo; i++) { for (nat j = 0; j < laberinto.Ancho; j++) { laberinto[i][j] = 0; } } laberinto[3][1] = 1; laberinto[3][2] = 1; laberinto[3][3] = 1; laberinto[4][1] = 1; laberinto[5][1] = 1; laberinto[6][1] = 1; laberinto[7][1] = 1; laberinto[8][1] = 1; laberinto[9][1] = 1; laberinto[10][1] = 1; laberinto[4][3] = 1; laberinto[5][3] = 1; laberinto[6][3] = 1; laberinto[7][3] = 1; laberinto[8][3] = 1; laberinto[9][3] = 1; laberinto[10][3] = 1; laberinto[10][2] = 1; laberinto[10][4] = 1; laberinto[10][5] = 1; laberinto[10][6] = 1; laberinto[2][3] = 1; laberinto[1][3] = 1; laberinto[1][4] = 1; laberinto[1][5] = 1; laberinto[1][6] = 1; laberinto[0][6] = 1; laberinto[0][7] = 1; laberinto[0][8] = 1; laberinto[1][8] = 1; laberinto[2][8] = 1; laberinto[3][8] = 1; laberinto[4][8] = 1; laberinto[4][7] = 1; laberinto[4][6] = 1; laberinto[5][6] = 1; laberinto[6][6] = 1; laberinto[6][5] = 1; laberinto[6][4] = 1; laberinto[7][7] = 1; laberinto[7][8] = 1; laberinto[8][7] = 1; laberinto[8][8] = 1; Array<Tupla<nat,nat>> resultado = Array<Tupla<nat,nat>>(13); resultado[0] = Tupla<nat,nat>(3,1); resultado[1] = Tupla<nat,nat>(4,1); resultado[2] = Tupla<nat,nat>(5,1); resultado[3] = Tupla<nat,nat>(6,1); resultado[4] = Tupla<nat,nat>(7,1); resultado[5] = Tupla<nat,nat>(8,1); resultado[6] = Tupla<nat,nat>(9,1); resultado[7] = Tupla<nat,nat>(10,1); resultado[8] = Tupla<nat,nat>(10,2); resultado[9] = Tupla<nat,nat>(10,3); resultado[10] = Tupla<nat,nat>(10,4); resultado[11] = Tupla<nat,nat>(10,5); resultado[12] = Tupla<nat,nat>(10,6); Iterador<Tupla<nat,nat>> esperado = resultado.ObtenerIterador(); Iterador<Tupla<nat,nat>> obtenido = interfaz->Laberinto(Tupla<nat,nat>(3,1),Tupla<nat,nat>(10,6),laberinto); VerificarSecuencias(obtenido, esperado,"Se encontró el camino {0} y se esperaba el {1}","Falta el camino {0}","No se esperaba pasar por el camino {0}"); resultado = Array<Tupla<nat,nat>>(11); resultado[0] = Tupla<nat,nat>(3,1); resultado[1] = Tupla<nat,nat>(3,2); resultado[2] = Tupla<nat,nat>(3,3); resultado[3] = Tupla<nat,nat>(4,3); resultado[4] = Tupla<nat,nat>(5,3); resultado[5] = Tupla<nat,nat>(6,3); resultado[6] = Tupla<nat,nat>(6,4); resultado[7] = Tupla<nat,nat>(6,5); resultado[8] = Tupla<nat,nat>(6,6); resultado[9] = Tupla<nat,nat>(5,6); resultado[10] = Tupla<nat,nat>(4,6); esperado = resultado.ObtenerIterador(); obtenido = interfaz->Laberinto(Tupla<nat,nat>(3,1),Tupla<nat,nat>(4,6),laberinto); VerificarSecuencias(obtenido, esperado,"Se encontró el camino {0} y se esperaba el {1}","Falta el camino {0}","No se esperaba pasar por el camino {0}"); esperado = NULL; obtenido = interfaz->Laberinto(Tupla<nat,nat>(3,1),Tupla<nat,nat>(7,8),laberinto); VerificarSecuencias(obtenido, esperado,"Se encontró el camino {0} y se esperaba el {1}","Falta el camino {0}","No se esperaba pasar por el camino {0}"); } void CasoDePrueba::PruebaViajero() { IniciarSeccion("Viajero"); Puntero<ISistema> interfaz = InicializarSistema(); Array<Puntero<ICiudad>> ciudadesDelMapa = Array<Puntero<ICiudad>>(5); ciudadesDelMapa[0] = new CiudadMock("Artigas",0); ciudadesDelMapa[1] = new CiudadMock("Paysandu",1); ciudadesDelMapa[2] = new CiudadMock("Montevideo",2); ciudadesDelMapa[3] = new CiudadMock("Salto",3); ciudadesDelMapa[4] = new CiudadMock("Punta del Este",4); Matriz<nat> mapa = Matriz<nat>(5,5); for ( nat i = 0; i < mapa.Largo; i++) { for (nat j = 0; j < mapa.Ancho; j++) { mapa[i][j] = 0; } } mapa[0][1] = 20; mapa[0][2] = 40; mapa[1][2] = 100; mapa[2][3] = 190; mapa[2][4] = 100; mapa[3][0] = 30; mapa[4][3] = 50; Array<Puntero<ICiudad>> ciudadesPasar = Array<Puntero<ICiudad>>(2); ciudadesPasar[0] = ciudadesDelMapa[0]; ciudadesPasar[1] = ciudadesDelMapa[3]; Array<Iterador<Puntero<ICiudad>>> resultados = Array<Iterador<Puntero<ICiudad>>>(1); Array<Puntero<ICiudad>> resultado = Array<Puntero<ICiudad>>(4); resultado[0] = ciudadesDelMapa[2]; resultado[1] = ciudadesDelMapa[4]; resultado[2] = ciudadesDelMapa[3]; resultado[3] = ciudadesDelMapa[0]; resultados[0] = resultado.ObtenerIterador(); Iterador<Iterador<Puntero<ICiudad>>> esperado = resultados.ObtenerIterador(); Iterador<Iterador<Puntero<ICiudad>>> obtenido = interfaz->Viajero(ciudadesDelMapa,mapa,ciudadesDelMapa[2],ciudadesPasar.ObtenerIterador(),255); VerificarConjuntos(obtenido, esperado,"Se encontró el itinerario {0} y se esperaba el itinerario {1}","Falta el itinerario {0}","No se esperaba encontrar el itinerario {0}"); ciudadesDelMapa = Array<Puntero<ICiudad>>(8); ciudadesDelMapa[0] = new CiudadMock("Artigas",0); ciudadesDelMapa[1] = new CiudadMock("Paysandu",1); ciudadesDelMapa[2] = new CiudadMock("Montevideo",2); ciudadesDelMapa[3] = new CiudadMock("Salto",3); ciudadesDelMapa[4] = new CiudadMock("Punta del Este",4); ciudadesDelMapa[5] = new CiudadMock("Rocha",5); ciudadesDelMapa[6] = new CiudadMock("Canelones",6); ciudadesDelMapa[7] = new CiudadMock("Fray Bentos",7); mapa = Matriz<nat>(8,8); for ( nat i = 0; i < mapa.Largo; i++) { for (nat j = 0; j < mapa.Ancho; j++) { mapa[i][j] = 0; } } mapa[0][1] = 30; mapa[0][4] = 40; mapa[0][5] = 35; mapa[0][6] = 70; mapa[1][5] = 45; mapa[1][6] = 20; mapa[2][0] = 50; mapa[2][3] = 60; mapa[3][0] = 20; mapa[4][2] = 10; mapa[4][3] = 40; mapa[4][7] = 30; mapa[5][6] = 15; mapa[6][4] = 55; mapa[7][0] = 90; ciudadesPasar = Array<Puntero<ICiudad>>(2); ciudadesPasar[0] = ciudadesDelMapa[0]; ciudadesPasar[1] = ciudadesDelMapa[6]; resultados = Array<Iterador<Puntero<ICiudad>>>(4); Array<Puntero<ICiudad>> resultado1 = Array<Puntero<ICiudad>>(5); resultado1[0] = ciudadesDelMapa[4]; resultado1[1] = ciudadesDelMapa[3]; resultado1[2] = ciudadesDelMapa[0]; resultado1[3] = ciudadesDelMapa[5]; resultado1[4] = ciudadesDelMapa[6]; Array<Puntero<ICiudad>> resultado2 = Array<Puntero<ICiudad>>(5); resultado2[0] = ciudadesDelMapa[4]; resultado2[1] = ciudadesDelMapa[3]; resultado2[2] = ciudadesDelMapa[0]; resultado2[3] = ciudadesDelMapa[1]; resultado2[4] = ciudadesDelMapa[6]; Array<Puntero<ICiudad>> resultado3 = Array<Puntero<ICiudad>>(5); resultado3[0] = ciudadesDelMapa[4]; resultado3[1] = ciudadesDelMapa[2]; resultado3[2] = ciudadesDelMapa[0]; resultado3[3] = ciudadesDelMapa[5]; resultado3[4] = ciudadesDelMapa[6]; Array<Puntero<ICiudad>> resultado4 = Array<Puntero<ICiudad>>(5); resultado4[0] = ciudadesDelMapa[4]; resultado4[1] = ciudadesDelMapa[2]; resultado4[2] = ciudadesDelMapa[0]; resultado4[3] = ciudadesDelMapa[1]; resultado4[4] = ciudadesDelMapa[6]; resultados[0] = resultado1.ObtenerIterador(); resultados[1] = resultado2.ObtenerIterador(); resultados[2] = resultado3.ObtenerIterador(); resultados[3] = resultado4.ObtenerIterador(); esperado = resultados.ObtenerIterador(); obtenido = interfaz->Viajero(ciudadesDelMapa,mapa,ciudadesDelMapa[4],ciudadesPasar.ObtenerIterador(),230); VerificarConjuntos(obtenido, esperado,"Se encontró el itinerario {0} y se esperaba el itinerario {1}","Falta el itinerario {0}","No se esperaba encontrar el itinerario {0}"); ciudadesDelMapa = Array<Puntero<ICiudad>>(6); ciudadesDelMapa[0] = new CiudadMock("Artigas",0); ciudadesDelMapa[1] = new CiudadMock("Paysandu",1); ciudadesDelMapa[2] = new CiudadMock("Montevideo",2); ciudadesDelMapa[3] = new CiudadMock("Salto",3); ciudadesDelMapa[4] = new CiudadMock("Punta del Este",4); ciudadesDelMapa[5] = new CiudadMock("Rocha",5); mapa = Matriz<nat>(6,6); for ( nat i = 0; i < mapa.Largo; i++) { for (nat j = 0; j < mapa.Ancho; j++) { mapa[i][j] = 0; } } mapa[0][4] = 80; mapa[1][2] = 10; mapa[2][0] = 40; mapa[2][5] = 70; mapa[2][3] = 50; mapa[3][5] = 20; mapa[4][5] = 10; mapa[5][2] = 10; mapa[5][1] = 20; ciudadesPasar = Array<Puntero<ICiudad>>(2); ciudadesPasar[0] = ciudadesDelMapa[2]; ciudadesPasar[1] = ciudadesDelMapa[5]; resultados = Array<Iterador<Puntero<ICiudad>>>(1); resultado = Array<Puntero<ICiudad>>(3); resultado[0] = ciudadesDelMapa[1]; resultado[1] = ciudadesDelMapa[2]; resultado[2] = ciudadesDelMapa[5]; resultados[0] = resultado.ObtenerIterador(); esperado = resultados.ObtenerIterador(); obtenido = interfaz->Viajero(ciudadesDelMapa,mapa,ciudadesDelMapa[1],ciudadesPasar.ObtenerIterador(),100); VerificarConjuntos(obtenido, esperado,"Se encontró el itinerario {0} y se esperaba el itinerario {1}","Falta el itinerario {0}","No se esperaba encontrar el itinerario {0}"); } void CasoDePrueba::PruebaDegustacion() { IniciarSeccion("Degustacion"); Puntero<ISistema> interfaz = InicializarSistema(); Producto p1(100, 50, 0, 2, 3); Producto p2(150, 30, 10, 10, 4); Producto p3(170, 150, 25, 3, 5); Producto p4(90, 10, 50, 15, 1); Producto p5(50, 18, 5, 3, 2); Producto p6(80, 10, 1, 4, 2); Producto p7(800, 1000, 10, 5, 5); Producto p8(5, 250, 0, 3, 2); Array<Producto> ps1(6); ps1[0] = p1; ps1[1] = p2; ps1[2] = p3; ps1[3] = p4; ps1[4] = p5; ps1[5] = p6; //Prueba 1 Array<nat> obtenido = interfaz->Degustacion(ps1, 5000, 1900, 300); int valorMochila = 0; for(nat i = 0; i < obtenido.Largo; i ++) { valorMochila += ps1[i].preferencia * obtenido[i]; } Verificar(valorMochila, 54, "Se obtuvo una suma de preferencias de valor {0} y se esperaba de valor {1}"); //Prueba 2 obtenido = interfaz->Degustacion(ps1, 3000, 4000, 3500); valorMochila = 0; for(nat i = 0; i < obtenido.Largo; i ++) { valorMochila += ps1[i].preferencia * obtenido[i]; } Verificar(valorMochila, 89, "Se obtuvo una suma de preferencias de valor {0} y se esperaba de valor {1}"); Array<Producto> ps2(8); ps2[0] = p1; ps2[1] = p2; ps2[2] = p3; ps2[3] = p4; ps2[4] = p5; ps2[5] = p6; ps2[6] = p7; ps2[7] = p8; //Prueba 3 Array<nat> obtenido2 = interfaz->Degustacion(ps2, 9000, 8000, 5000); valorMochila = 0; for(nat i = 0; i < obtenido2.Largo; i ++) { valorMochila += ps2[i].preferencia * obtenido2[i]; } Verificar(valorMochila, 120, "Se obtuvo una suma de preferencias de valor {0} y se esperaba de valor {1}"); } void CasoDePrueba::PruebaCaminoCaballo() { IniciarSeccion("Ejercicio Camino Caballo"); Puntero<ISistema> interfaz = InicializarSistema(); Tupla<TipoRetorno, Iterador<Iterador<Tupla<int, int>>>> obtenido; Tupla<TipoRetorno, Iterador<Iterador<Tupla<int, int>>>> esperado; Array<Tupla<int, int>> pasar; Array<Tupla<int, int>> noPasar; Array<Iterador<Tupla<int, int>>> mejoresCaminos; Array<Tupla<int, int>> camino; pasar = Array<Tupla<int, int>>(1); pasar[0] = Tupla<int, int>(1, 2); noPasar = Array<Tupla<int, int>>(2); noPasar[0] = Tupla<int, int>(2, 2); noPasar[1] = Tupla<int, int>(2, 1); obtenido = interfaz->CaminoCaballo(Tupla<int, int>(0, 0), Tupla<int, int>(1, 2), 1, 10, pasar.ObtenerIterador(), noPasar.ObtenerIterador(), 5); camino = Array<Tupla<int, int>>(2); camino[0] = Tupla<int, int>(0, 0); camino[1] = Tupla<int, int>(1, 2); mejoresCaminos = Array<Iterador<Tupla<int, int>>>(1); mejoresCaminos[0] = camino.ObtenerIterador(); esperado = Tupla<TipoRetorno, Iterador<Iterador<Tupla<int, int>>>>(OK, mejoresCaminos.ObtenerIterador()); VerificarCaminos(obtenido, esperado); pasar = Array<Tupla<int, int>>(4); pasar[0] = Tupla<int, int>(1, 0); pasar[1] = Tupla<int, int>(1, 5); pasar[2] = Tupla<int, int>(5, 5); pasar[3] = Tupla<int, int>(1, 4); noPasar = Array<Tupla<int, int>>(4); noPasar[0] = Tupla<int, int>(0, 0); noPasar[1] = Tupla<int, int>(1, 1); noPasar[2] = Tupla<int, int>(3, 3); noPasar[3] = Tupla<int, int>(4, 2); obtenido = interfaz->CaminoCaballo(Tupla<int, int>(3, 1), Tupla<int, int>(3, 5), 2, 6, pasar.ObtenerIterador(), noPasar.ObtenerIterador(), 5); mejoresCaminos = Array<Iterador<Tupla<int, int>>>(2); camino = Array<Tupla<int, int>>(5); camino[0] = Tupla<int, int>(3, 1); camino[1] = Tupla<int, int>(1, 0); camino[2] = Tupla<int, int>(0, 2); camino[3] = Tupla<int, int>(1, 4); camino[4] = Tupla<int, int>(3, 5); mejoresCaminos[0] = camino.ObtenerIterador(); camino = Array<Tupla<int, int>>(5); camino[0] = Tupla<int, int>(3, 1); camino[1] = Tupla<int, int>(1, 0); camino[2] = Tupla<int, int>(2, 2); camino[3] = Tupla<int, int>(1, 4); camino[4] = Tupla<int, int>(3, 5); mejoresCaminos[1] = camino.ObtenerIterador(); esperado = Tupla<TipoRetorno, Iterador<Iterador<Tupla<int, int>>>>(OK, mejoresCaminos.ObtenerIterador()); VerificarCaminos(obtenido, esperado); CerrarSeccion(); } void CasoDePrueba::PruebaOptimizarGranja() { IniciarSeccion("Ejercicio Optimizar Granja"); Puntero<ISistema> interfaz = InicializarSistema(); Tupla<TipoRetorno, Array<nat>> esperado; Tupla<TipoRetorno, Array<nat>> obtenido; Array<nat> cantEsperado(5); esperado = Tupla<TipoRetorno, Array<nat>>(OK, cantEsperado); //Tupla costo, agua, ganancia Array<Tupla<nat, nat, nat>> semillas(5); semillas[0] = Tupla<nat, nat, nat>(10, 10, 10); semillas[1] = Tupla<nat, nat, nat>(10000, 10, 100000); semillas[2] = Tupla<nat, nat, nat>(100, 10, 70); semillas[3] = Tupla<nat, nat, nat>(10, 15, 9); semillas[4] = Tupla<nat, nat, nat>(30, 7, 35); //OptimizarGranja(Array<Tupla<nat, nat, nat>>& semillas, nat dinero, nat tierra, nat agua) obtenido = interfaz->OptimizarGranja(semillas, 1, 1, 1); VerificarGranja(semillas, esperado, obtenido, 1, 1, 1); obtenido = interfaz->OptimizarGranja(semillas, 40, 3, 10); cantEsperado[4] = 1; VerificarGranja(semillas, esperado, obtenido, 40, 3, 10); obtenido = interfaz->OptimizarGranja(semillas, 500, 3, 500); cantEsperado[4] = 0; cantEsperado[2] = 3; VerificarGranja(semillas, esperado, obtenido, 500, 3, 500); obtenido = interfaz->OptimizarGranja(semillas, 81, 5, 100); cantEsperado[0] = 2; cantEsperado[2] = 0; cantEsperado[4] = 2; VerificarGranja(semillas, esperado, obtenido, 100, 5, 100); obtenido = interfaz->OptimizarGranja(semillas, 499, 5, 210); cantEsperado[0] = 0; cantEsperado[2] = 4; cantEsperado[4] = 1; VerificarGranja(semillas, esperado, obtenido, 499, 10, 210); CerrarSeccion(); } void CasoDePrueba::PruebaInscribirMaterias() { IniciarSeccion("Ejercicio Inscribir Materias"); Puntero<ISistema> interfaz = InicializarSistema(); Tupla<TipoRetorno, Iterador<Tupla<Cadena, bool>>> obtenido; Tupla<TipoRetorno, Iterador<Tupla<Cadena, bool>>> esperado; Array<Tupla<Cadena, nat, nat>> matutino; Array<Tupla<Cadena, nat, nat>> nocturno; Array<Tupla<Cadena, bool>> materias; matutino = Array<Tupla<Cadena, nat, nat>>(2); matutino[0] = Tupla<Cadena, nat, nat>("Algoritmos", 1000, 7); matutino[1] = Tupla<Cadena, nat, nat>("Matematica", 10, 6); nocturno = Array<Tupla<Cadena, nat, nat>>(1); nocturno[0] = Tupla<Cadena, nat, nat>("Algoritmos", 1000, 7); //InscribirMaterias(Iterador<Tupla<Cadena, nat, nat>> matutino, Iterador<Tupla<Cadena, nat, nat>> nocturno, nat horasM, nat horasN) obtenido = interfaz->InscribirMaterias(matutino.ObtenerIterador(), nocturno.ObtenerIterador(), 8, 8); materias = Array<Tupla<Cadena, bool>>(2); materias[0] = Tupla<Cadena, bool>("Algoritmos", false); materias[1] = Tupla<Cadena, bool>("Matematica", true); esperado = Tupla<TipoRetorno, Iterador<Tupla<Cadena, bool>>>(OK, materias.ObtenerIterador()); VerificarMaterias(obtenido, esperado); CerrarSeccion(); } void CasoDePrueba::PruebaViajero2() { IniciarSeccion("Ejercicio Viajero2"); Puntero<ISistema> interfaz = InicializarSistema(); Tupla<TipoRetorno, Iterador<nat>> obtenido; //Tupla representa <costo, distancia, tiempo> Tupla<nat, nat, nat> NoHayConexion(0, 0, 0); Tupla<nat, nat, nat> Conexion1(1, 1, 1); Array<nat> CiudadesPasar; Array<nat> CiudadesNoPasar; Tupla<TipoRetorno, Iterador<nat>> esperado; Array<nat> ciudadesEsperadas; Matriz<Tupla<nat, nat, nat>> relacionesCiudades; // Prueba 1 CiudadesPasar = Array<nat>(3); CiudadesPasar[0] = 5; CiudadesPasar[1] = 0; CiudadesPasar[2] = 3; CiudadesNoPasar = Array<nat>(1); CiudadesNoPasar[0] = 2; relacionesCiudades = Matriz<Tupla<nat, nat, nat>>(6); for (int i = 0; i < 6; i++) { for (int j = 0; j < 6; j++) { relacionesCiudades[i][j] = NoHayConexion; } } for (int i = 0; i < 6; i++) { //Conexiones ultra baratas... que no se pueden usar porque la ciudad es prohibida relacionesCiudades[i][2] = Conexion1; relacionesCiudades[2][i] = Conexion1; } relacionesCiudades[5][4] = Conexion1; relacionesCiudades[4][0] = Conexion1; relacionesCiudades[5][0] = Tupla<nat, nat, nat>(1000, 70, 15); relacionesCiudades[0][1] = Tupla<nat, nat, nat>(10, 70, 15); relacionesCiudades[1][3] = Tupla<nat, nat, nat>(10, 30, 15); relacionesCiudades[0][3] = Tupla<nat, nat, nat>(20, 100, 10); obtenido = interfaz->Viajero2(relacionesCiudades, CiudadesPasar.ObtenerIterador(), CiudadesNoPasar.ObtenerIterador()); ciudadesEsperadas = Array<nat>(4); ciudadesEsperadas[0] = 5; ciudadesEsperadas[1] = 4; ciudadesEsperadas[2] = 0; ciudadesEsperadas[3] = 3; esperado = Tupla<TipoRetorno, Iterador<nat>>(OK, ciudadesEsperadas.ObtenerIterador()); VerificarViajero2(obtenido, esperado); // Prueba 2 CiudadesPasar = Array<nat>(3); CiudadesPasar[0] = 3; CiudadesPasar[1] = 5; CiudadesPasar[2] = 10; CiudadesNoPasar = Array<nat>(3); CiudadesNoPasar[0] = 12; CiudadesNoPasar[1] = 4; CiudadesNoPasar[2] = 11; relacionesCiudades = Matriz<Tupla<nat, nat, nat>>(13); for (int i = 0; i < 13; i++) { for (int j = 0; j < 13; j++) { relacionesCiudades[i][j] = NoHayConexion; } } for (int i = 0; i < 13; i++) { //Conexiones ultra baratas... que no se pueden usar porque la ciudad es prohibida relacionesCiudades[i][11] = Conexion1; relacionesCiudades[11][i] = Conexion1; } relacionesCiudades[1][12] = Conexion1; relacionesCiudades[3][12] = Conexion1; relacionesCiudades[5][12] = Conexion1; relacionesCiudades[10][12] = Conexion1; relacionesCiudades[12][5] = Conexion1; relacionesCiudades[12][10] = Conexion1; relacionesCiudades[0][5] = Tupla<nat, nat, nat>(20, 20, 20); relacionesCiudades[5][0] = Tupla<nat, nat, nat>(10, 10, 10); relacionesCiudades[6][0] = Tupla<nat, nat, nat>(30, 30, 30); relacionesCiudades[0][10] = Tupla<nat, nat, nat>(1000, 1000, 1000); relacionesCiudades[3][1] = Tupla<nat, nat, nat>(2, 2, 10); relacionesCiudades[1][4] = Tupla<nat, nat, nat>(3, 3, 10); relacionesCiudades[1][9] = Tupla<nat, nat, nat>(4, 3, 10); relacionesCiudades[3][2] = Tupla<nat, nat, nat>(40, 40, 40); relacionesCiudades[4][2] = Tupla<nat, nat, nat>(3, 3, 10); relacionesCiudades[2][5] = Tupla<nat, nat, nat>(20, 20, 10); relacionesCiudades[2][6] = Tupla<nat, nat, nat>(20, 30, 30); relacionesCiudades[6][2] = Tupla<nat, nat, nat>(20, 30, 30); relacionesCiudades[3][6] = Tupla<nat, nat, nat>(20, 120, 120); relacionesCiudades[5][6] = Tupla<nat, nat, nat>(15, 30, 70); relacionesCiudades[6][7] = Tupla<nat, nat, nat>(15, 13, 7); relacionesCiudades[7][8] = Tupla<nat, nat, nat>(20, 30, 20); relacionesCiudades[8][10] = Tupla<nat, nat, nat>(30, 20, 30); relacionesCiudades[7][9] = Tupla<nat, nat, nat>(30, 20, 30); relacionesCiudades[9][10] = Tupla<nat, nat, nat>(20, 30, 200); relacionesCiudades[9][7] = Tupla<nat, nat, nat>(15, 13, 7); relacionesCiudades[7][10] = Tupla<nat, nat, nat>(50, 50, 50); obtenido = interfaz->Viajero2(relacionesCiudades, CiudadesPasar.ObtenerIterador(), CiudadesNoPasar.ObtenerIterador()); ciudadesEsperadas = Array<nat>(7); ciudadesEsperadas[0] = 3; ciudadesEsperadas[1] = 6; ciudadesEsperadas[2] = 2; ciudadesEsperadas[3] = 5; ciudadesEsperadas[4] = 6; ciudadesEsperadas[5] = 7; ciudadesEsperadas[6] = 10; esperado = Tupla<TipoRetorno, Iterador<nat>>(OK, ciudadesEsperadas.ObtenerIterador()); VerificarViajero2(obtenido, esperado); CerrarSeccion(); } void CasoDePrueba::PruebaProteccionAnimales() { IniciarSeccion("Ejercicio Protección Animales"); Puntero<ISistema> interfaz = InicializarSistema(); Tupla<TipoRetorno, Array<nat>> esperado; Tupla<TipoRetorno, Array<nat>> obtenido; Array<nat> cantEsperado(10); esperado = Tupla<TipoRetorno, Array<nat>>(OK, cantEsperado); Array<Accion> acciones(10); acciones[0] = Accion(10, 10, 10, 10, 10, 10); acciones[1] = Accion(100000, 100000, 100000, 100000, 100000, INT_MAX); //nunca se puede usar acciones[2] = Accion(13, 13, 13, 13, 13, 13); acciones[3] = Accion(10, 20, 15, 100, 10, 300); acciones[4] = Accion(20, 30, 10, 10, 50, 100); acciones[5] = Accion(100, 10, 70, 50, 15, 10); acciones[6] = Accion(10, 20, 15, 100, 10, 1); acciones[7] = Accion(100, 100, 100, 100, 100, 101); acciones[8] = Accion(100, 100, 200, 100, 100, 105); acciones[9] = Accion(10, 10, 10, 10, 10, 9); //ProteccionAnimales(acciones, maxVeterinarios, maxVehiculos, maxDinero, maxVacunas, maxVoluntarios) //No puede realizar ninguna accion obtenido = interfaz->ProteccionAnimales(acciones, 1, 1, 1, 1, 1); VerificarProteccionAnimales(acciones, esperado, obtenido, 1, 1, 1, 1, 1); obtenido = interfaz->ProteccionAnimales(acciones, 10, 10, 10, 10, 10); cantEsperado[0] = 1; VerificarProteccionAnimales(acciones, esperado, obtenido, 10, 10, 10, 10, 10); obtenido = interfaz->ProteccionAnimales(acciones, 110, 110, 110, 110, 110); cantEsperado[0] = 0; cantEsperado[3] = 1; cantEsperado[4] = 1; VerificarProteccionAnimales(acciones, esperado, obtenido, 110, 110, 110, 110, 110); obtenido = interfaz->ProteccionAnimales(acciones, 110, 110, 110, 99, 110); cantEsperado[0] = 1; cantEsperado[3] = 0; cantEsperado[4] = 2; VerificarProteccionAnimales(acciones, esperado, obtenido, 110, 110, 110, 99, 110); obtenido = interfaz->ProteccionAnimales(acciones, 110, 110, 110, 299, 110); cantEsperado[0] = 4; cantEsperado[3] = 2; cantEsperado[4] = 1; VerificarProteccionAnimales(acciones, esperado, obtenido, 110, 110, 110, 299, 110); obtenido = interfaz->ProteccionAnimales(acciones, 113, 113, 113, 299, 113); cantEsperado[0] = 3; cantEsperado[2] = 1; cantEsperado[3] = 2; cantEsperado[4] = 1; VerificarProteccionAnimales(acciones, esperado, obtenido, 113, 113, 113, 299, 113); CerrarSeccion(); } void CasoDePrueba::PruebaQuickSort() { IniciarSeccion("Ejercicio QuickSort"); Puntero<ISistema> interfaz = InicializarSistema(); Array<nat> elementos; Array<nat> esperado; Array<nat> obtenido; elementos = Array<nat>(7); elementos[0] = 1; elementos[1] = 7; elementos[2] = 13; elementos[3] = 17; elementos[4] = 23; elementos[5] = 27; elementos[6] = 31; esperado = Array<nat>(7); Array<nat>::Copiar(elementos, esperado); obtenido = interfaz->QuickSort(elementos); VerificarSecuencias(obtenido.ObtenerIterador(), esperado.ObtenerIterador(), "Se obtuvo elemento '{0}'", "Falta elemento '{0}'", "No se esperaba elemento '{0}'"); elementos = Array<nat>(7); elementos[0] = 77; elementos[1] = 70; elementos[2] = 37; elementos[3] = 34; elementos[4] = 25; elementos[5] = 16; elementos[6] = 7; esperado = Array<nat>(7); esperado[6] = 77; esperado[5] = 70; esperado[4] = 37; esperado[3] = 34; esperado[2] = 25; esperado[1] = 16; esperado[0] = 7; obtenido = interfaz->QuickSort(elementos); VerificarSecuencias(obtenido.ObtenerIterador(), esperado.ObtenerIterador(), "Se obtuvo elemento '{0}'", "Falta elemento '{0}'", "No se esperaba elemento '{0}'"); elementos = Array<nat>(7); elementos[0] = 77; elementos[1] = 1; elementos[2] = 37; elementos[3] = 34; elementos[4] = 80; elementos[5] = 16; elementos[6] = 7; esperado = Array<nat>(7); esperado[0] = 1; esperado[1] = 7; esperado[2] = 16; esperado[3] = 34; esperado[4] = 37; esperado[5] = 77; esperado[6] = 80; obtenido = interfaz->QuickSort(elementos); VerificarSecuencias(obtenido.ObtenerIterador(), esperado.ObtenerIterador(), "Se obtuvo elemento '{0}'", "Falta elemento '{0}'", "No se esperaba elemento '{0}'"); elementos = Array<nat>(1); elementos[0] = 111; esperado = Array<nat>(1); esperado[0] = 111; obtenido = interfaz->QuickSort(elementos); VerificarSecuencias(obtenido.ObtenerIterador(), esperado.ObtenerIterador(), "Se obtuvo elemento '{0}'", "Falta elemento '{0}'", "No se esperaba elemento '{0}'"); CerrarSeccion(); }
[ "fjacobo@menoo.com.uy" ]
fjacobo@menoo.com.uy
b2a15c8d286139d2ad6c07556c18ac833814ea5c
173ab71398d090ba1d87bc6cd3e4398f549b0679
/QtLog/main.cpp
fb5f440c7fb9808f93be216dc6278641373b02dd
[]
no_license
alvin-xian/QtLog
148b9412acbf7ab5b1b7a4099d7f29f21d91fc59
38c6606b1fff1d75cd9cc38be946224c98beb9b1
refs/heads/master
2020-06-05T01:18:45.062640
2019-06-17T05:56:55
2019-06-17T05:56:55
192,263,686
0
0
null
null
null
null
UTF-8
C++
false
false
808
cpp
#include <QCoreApplication> #include "qtlog.h" #include <QDebug> #include <QStandardPaths> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); //---------------test--------------------------- //初始化文件打印信息 QString location = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation); qtLog->setLogFilePath(location+"/Log"); qtLog->setLogFileName("Qt_Log"); qtLog->setLogFileSufix("txt"); //调试信息输出到文件 qDebug()<<"Log in file:"<<qtLog->logFilePath(); qtLog->setLogMode(QtLog::File); qDebug()<<"Log in file "<<qtLog->logFilePath(); //调试信息输出到命令行 qtLog->setLogMode(QtLog::Qt); qDebug()<<"Log in commanline "; //---------------end--------------------------- return a.exec(); }
[ "alvin.xian@ubtrobot.com" ]
alvin.xian@ubtrobot.com
e35ed0830d6c4d3a6a58253e41e82ad0cc70b279
3ba6e802ea0a759bc3d1c930e11a3e8953b57ec9
/Geometry/Cara.h
0af3f594fb2f16664989f40c7d084acf8be5ff9f
[ "Apache-2.0" ]
permissive
carlaMorral/raytracing-f01-1
f48627bfe799a0886337159e1986a994a9e73cb0
e11e23e66623cdf11fb7058b2e732e6107cd0639
refs/heads/main
2023-03-31T03:55:23.904516
2021-04-13T16:04:52
2021-04-13T16:04:52
371,656,256
0
1
Apache-2.0
2021-05-28T09:56:27
2021-05-28T09:56:26
null
UTF-8
C++
false
false
481
h
#pragma once #include <vector> #include "glm/glm.hpp" using namespace std; using namespace glm; typedef vec4 Vertices; // Face - representa una cara d'un objecte 3D class Cara { public: Cara(); // constructor a partir de 3 o 4 indexs a vertex Cara(int i1, int i2, int i3, int i4=-1); // atributs vec4 color; vector<int> idxVertices; // vector amb els indexs dels vertexs de la cara vec3 normal; void calculaNormal(vector<Vertices> &); };
[ "66690702+github-classroom[bot]@users.noreply.github.com" ]
66690702+github-classroom[bot]@users.noreply.github.com
48692ad0311b2eaca68c7915bb27a1625e381914
c776476e9d06b3779d744641e758ac3a2c15cddc
/examples/litmus/c/run-scripts/tmp_5/Z6.1+poreleaseonce+poreleaseonce+poacquirerelease.c.cbmc.cpp
b8c123be893b833c23dbd7bd419b87122019984c
[]
no_license
ashutosh0gupta/llvm_bmc
aaac7961c723ba6f7ffd77a39559e0e52432eade
0287c4fb180244e6b3c599a9902507f05c8a7234
refs/heads/master
2023-08-02T17:14:06.178723
2023-07-31T10:46:53
2023-07-31T10:46:53
143,100,825
3
4
null
2023-05-25T05:50:55
2018-08-01T03:47:00
C++
UTF-8
C++
false
false
36,582
cpp
// Global variabls: // 0:vars:3 // 3:atom_2_X0_1:1 // Local global variabls: // 0:thr0:1 // 1:thr1:1 // 2:thr2:1 #define ADDRSIZE 4 #define LOCALADDRSIZE 3 #define NTHREAD 4 #define NCONTEXT 5 #define ASSUME(stmt) __CPROVER_assume(stmt) #define ASSERT(stmt) __CPROVER_assert(stmt, "error") #define max(a,b) (a>b?a:b) char __get_rng(); char get_rng( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } char get_rng_th( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } int main(int argc, char **argv) { // Declare arrays for intial value version in contexts int local_mem[LOCALADDRSIZE]; // Dumping initializations local_mem[0+0] = 0; local_mem[1+0] = 0; local_mem[2+0] = 0; int cstart[NTHREAD]; int creturn[NTHREAD]; // declare arrays for contexts activity int active[NCONTEXT]; int ctx_used[NCONTEXT]; // declare arrays for intial value version in contexts int meminit_[ADDRSIZE*NCONTEXT]; #define meminit(x,k) meminit_[(x)*NCONTEXT+k] int coinit_[ADDRSIZE*NCONTEXT]; #define coinit(x,k) coinit_[(x)*NCONTEXT+k] int deltainit_[ADDRSIZE*NCONTEXT]; #define deltainit(x,k) deltainit_[(x)*NCONTEXT+k] // declare arrays for running value version in contexts int mem_[ADDRSIZE*NCONTEXT]; #define mem(x,k) mem_[(x)*NCONTEXT+k] int co_[ADDRSIZE*NCONTEXT]; #define co(x,k) co_[(x)*NCONTEXT+k] int delta_[ADDRSIZE*NCONTEXT]; #define delta(x,k) delta_[(x)*NCONTEXT+k] // declare arrays for local buffer and observed writes int buff_[NTHREAD*ADDRSIZE]; #define buff(x,k) buff_[(x)*ADDRSIZE+k] int pw_[NTHREAD*ADDRSIZE]; #define pw(x,k) pw_[(x)*ADDRSIZE+k] // declare arrays for context stamps char cr_[NTHREAD*ADDRSIZE]; #define cr(x,k) cr_[(x)*ADDRSIZE+k] char iw_[NTHREAD*ADDRSIZE]; #define iw(x,k) iw_[(x)*ADDRSIZE+k] char cw_[NTHREAD*ADDRSIZE]; #define cw(x,k) cw_[(x)*ADDRSIZE+k] char cx_[NTHREAD*ADDRSIZE]; #define cx(x,k) cx_[(x)*ADDRSIZE+k] char is_[NTHREAD*ADDRSIZE]; #define is(x,k) is_[(x)*ADDRSIZE+k] char cs_[NTHREAD*ADDRSIZE]; #define cs(x,k) cs_[(x)*ADDRSIZE+k] char crmax_[NTHREAD*ADDRSIZE]; #define crmax(x,k) crmax_[(x)*ADDRSIZE+k] char sforbid_[ADDRSIZE*NCONTEXT]; #define sforbid(x,k) sforbid_[(x)*NCONTEXT+k] // declare arrays for synchronizations int cl[NTHREAD]; int cdy[NTHREAD]; int cds[NTHREAD]; int cdl[NTHREAD]; int cisb[NTHREAD]; int caddr[NTHREAD]; int cctrl[NTHREAD]; __LOCALS__ buff(0,0) = 0; pw(0,0) = 0; cr(0,0) = 0; iw(0,0) = 0; cw(0,0) = 0; cx(0,0) = 0; is(0,0) = 0; cs(0,0) = 0; crmax(0,0) = 0; buff(0,1) = 0; pw(0,1) = 0; cr(0,1) = 0; iw(0,1) = 0; cw(0,1) = 0; cx(0,1) = 0; is(0,1) = 0; cs(0,1) = 0; crmax(0,1) = 0; buff(0,2) = 0; pw(0,2) = 0; cr(0,2) = 0; iw(0,2) = 0; cw(0,2) = 0; cx(0,2) = 0; is(0,2) = 0; cs(0,2) = 0; crmax(0,2) = 0; buff(0,3) = 0; pw(0,3) = 0; cr(0,3) = 0; iw(0,3) = 0; cw(0,3) = 0; cx(0,3) = 0; is(0,3) = 0; cs(0,3) = 0; crmax(0,3) = 0; cl[0] = 0; cdy[0] = 0; cds[0] = 0; cdl[0] = 0; cisb[0] = 0; caddr[0] = 0; cctrl[0] = 0; cstart[0] = get_rng(0,NCONTEXT-1); creturn[0] = get_rng(0,NCONTEXT-1); buff(1,0) = 0; pw(1,0) = 0; cr(1,0) = 0; iw(1,0) = 0; cw(1,0) = 0; cx(1,0) = 0; is(1,0) = 0; cs(1,0) = 0; crmax(1,0) = 0; buff(1,1) = 0; pw(1,1) = 0; cr(1,1) = 0; iw(1,1) = 0; cw(1,1) = 0; cx(1,1) = 0; is(1,1) = 0; cs(1,1) = 0; crmax(1,1) = 0; buff(1,2) = 0; pw(1,2) = 0; cr(1,2) = 0; iw(1,2) = 0; cw(1,2) = 0; cx(1,2) = 0; is(1,2) = 0; cs(1,2) = 0; crmax(1,2) = 0; buff(1,3) = 0; pw(1,3) = 0; cr(1,3) = 0; iw(1,3) = 0; cw(1,3) = 0; cx(1,3) = 0; is(1,3) = 0; cs(1,3) = 0; crmax(1,3) = 0; cl[1] = 0; cdy[1] = 0; cds[1] = 0; cdl[1] = 0; cisb[1] = 0; caddr[1] = 0; cctrl[1] = 0; cstart[1] = get_rng(0,NCONTEXT-1); creturn[1] = get_rng(0,NCONTEXT-1); buff(2,0) = 0; pw(2,0) = 0; cr(2,0) = 0; iw(2,0) = 0; cw(2,0) = 0; cx(2,0) = 0; is(2,0) = 0; cs(2,0) = 0; crmax(2,0) = 0; buff(2,1) = 0; pw(2,1) = 0; cr(2,1) = 0; iw(2,1) = 0; cw(2,1) = 0; cx(2,1) = 0; is(2,1) = 0; cs(2,1) = 0; crmax(2,1) = 0; buff(2,2) = 0; pw(2,2) = 0; cr(2,2) = 0; iw(2,2) = 0; cw(2,2) = 0; cx(2,2) = 0; is(2,2) = 0; cs(2,2) = 0; crmax(2,2) = 0; buff(2,3) = 0; pw(2,3) = 0; cr(2,3) = 0; iw(2,3) = 0; cw(2,3) = 0; cx(2,3) = 0; is(2,3) = 0; cs(2,3) = 0; crmax(2,3) = 0; cl[2] = 0; cdy[2] = 0; cds[2] = 0; cdl[2] = 0; cisb[2] = 0; caddr[2] = 0; cctrl[2] = 0; cstart[2] = get_rng(0,NCONTEXT-1); creturn[2] = get_rng(0,NCONTEXT-1); buff(3,0) = 0; pw(3,0) = 0; cr(3,0) = 0; iw(3,0) = 0; cw(3,0) = 0; cx(3,0) = 0; is(3,0) = 0; cs(3,0) = 0; crmax(3,0) = 0; buff(3,1) = 0; pw(3,1) = 0; cr(3,1) = 0; iw(3,1) = 0; cw(3,1) = 0; cx(3,1) = 0; is(3,1) = 0; cs(3,1) = 0; crmax(3,1) = 0; buff(3,2) = 0; pw(3,2) = 0; cr(3,2) = 0; iw(3,2) = 0; cw(3,2) = 0; cx(3,2) = 0; is(3,2) = 0; cs(3,2) = 0; crmax(3,2) = 0; buff(3,3) = 0; pw(3,3) = 0; cr(3,3) = 0; iw(3,3) = 0; cw(3,3) = 0; cx(3,3) = 0; is(3,3) = 0; cs(3,3) = 0; crmax(3,3) = 0; cl[3] = 0; cdy[3] = 0; cds[3] = 0; cdl[3] = 0; cisb[3] = 0; caddr[3] = 0; cctrl[3] = 0; cstart[3] = get_rng(0,NCONTEXT-1); creturn[3] = get_rng(0,NCONTEXT-1); // Dumping initializations mem(0+0,0) = 0; mem(0+1,0) = 0; mem(0+2,0) = 0; mem(3+0,0) = 0; // Dumping context matching equalities co(0,0) = 0; delta(0,0) = -1; mem(0,1) = meminit(0,1); co(0,1) = coinit(0,1); delta(0,1) = deltainit(0,1); mem(0,2) = meminit(0,2); co(0,2) = coinit(0,2); delta(0,2) = deltainit(0,2); mem(0,3) = meminit(0,3); co(0,3) = coinit(0,3); delta(0,3) = deltainit(0,3); mem(0,4) = meminit(0,4); co(0,4) = coinit(0,4); delta(0,4) = deltainit(0,4); co(1,0) = 0; delta(1,0) = -1; mem(1,1) = meminit(1,1); co(1,1) = coinit(1,1); delta(1,1) = deltainit(1,1); mem(1,2) = meminit(1,2); co(1,2) = coinit(1,2); delta(1,2) = deltainit(1,2); mem(1,3) = meminit(1,3); co(1,3) = coinit(1,3); delta(1,3) = deltainit(1,3); mem(1,4) = meminit(1,4); co(1,4) = coinit(1,4); delta(1,4) = deltainit(1,4); co(2,0) = 0; delta(2,0) = -1; mem(2,1) = meminit(2,1); co(2,1) = coinit(2,1); delta(2,1) = deltainit(2,1); mem(2,2) = meminit(2,2); co(2,2) = coinit(2,2); delta(2,2) = deltainit(2,2); mem(2,3) = meminit(2,3); co(2,3) = coinit(2,3); delta(2,3) = deltainit(2,3); mem(2,4) = meminit(2,4); co(2,4) = coinit(2,4); delta(2,4) = deltainit(2,4); co(3,0) = 0; delta(3,0) = -1; mem(3,1) = meminit(3,1); co(3,1) = coinit(3,1); delta(3,1) = deltainit(3,1); mem(3,2) = meminit(3,2); co(3,2) = coinit(3,2); delta(3,2) = deltainit(3,2); mem(3,3) = meminit(3,3); co(3,3) = coinit(3,3); delta(3,3) = deltainit(3,3); mem(3,4) = meminit(3,4); co(3,4) = coinit(3,4); delta(3,4) = deltainit(3,4); // Dumping thread 1 int ret_thread_1 = 0; cdy[1] = get_rng(0,NCONTEXT-1); ASSUME(cdy[1] >= cstart[1]); T1BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !34, metadata !DIExpression()), !dbg !43 // br label %label_1, !dbg !44 goto T1BLOCK1; T1BLOCK1: // call void @llvm.dbg.label(metadata !42), !dbg !45 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !35, metadata !DIExpression()), !dbg !46 // call void @llvm.dbg.value(metadata i64 2, metadata !38, metadata !DIExpression()), !dbg !46 // store atomic i64 2, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) release, align 8, !dbg !47 // ST: Guess // : Release iw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW _l19_c3 old_cw = cw(1,0+1*1); cw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM _l19_c3 // Check ASSUME(active[iw(1,0+1*1)] == 1); ASSUME(active[cw(1,0+1*1)] == 1); ASSUME(sforbid(0+1*1,cw(1,0+1*1))== 0); ASSUME(iw(1,0+1*1) >= 0); ASSUME(iw(1,0+1*1) >= 0); ASSUME(cw(1,0+1*1) >= iw(1,0+1*1)); ASSUME(cw(1,0+1*1) >= old_cw); ASSUME(cw(1,0+1*1) >= cr(1,0+1*1)); ASSUME(cw(1,0+1*1) >= cl[1]); ASSUME(cw(1,0+1*1) >= cisb[1]); ASSUME(cw(1,0+1*1) >= cdy[1]); ASSUME(cw(1,0+1*1) >= cdl[1]); ASSUME(cw(1,0+1*1) >= cds[1]); ASSUME(cw(1,0+1*1) >= cctrl[1]); ASSUME(cw(1,0+1*1) >= caddr[1]); ASSUME(cw(1,0+1*1) >= cr(1,0+0)); ASSUME(cw(1,0+1*1) >= cr(1,0+1)); ASSUME(cw(1,0+1*1) >= cr(1,0+2)); ASSUME(cw(1,0+1*1) >= cr(1,3+0)); ASSUME(cw(1,0+1*1) >= cw(1,0+0)); ASSUME(cw(1,0+1*1) >= cw(1,0+1)); ASSUME(cw(1,0+1*1) >= cw(1,0+2)); ASSUME(cw(1,0+1*1) >= cw(1,3+0)); // Update caddr[1] = max(caddr[1],0); buff(1,0+1*1) = 2; mem(0+1*1,cw(1,0+1*1)) = 2; co(0+1*1,cw(1,0+1*1))+=1; delta(0+1*1,cw(1,0+1*1)) = -1; is(1,0+1*1) = iw(1,0+1*1); cs(1,0+1*1) = cw(1,0+1*1); ASSUME(creturn[1] >= cw(1,0+1*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !39, metadata !DIExpression()), !dbg !48 // call void @llvm.dbg.value(metadata i64 1, metadata !41, metadata !DIExpression()), !dbg !48 // store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !49 // ST: Guess iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW _l20_c3 old_cw = cw(1,0); cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM _l20_c3 // Check ASSUME(active[iw(1,0)] == 1); ASSUME(active[cw(1,0)] == 1); ASSUME(sforbid(0,cw(1,0))== 0); ASSUME(iw(1,0) >= 0); ASSUME(iw(1,0) >= 0); ASSUME(cw(1,0) >= iw(1,0)); ASSUME(cw(1,0) >= old_cw); ASSUME(cw(1,0) >= cr(1,0)); ASSUME(cw(1,0) >= cl[1]); ASSUME(cw(1,0) >= cisb[1]); ASSUME(cw(1,0) >= cdy[1]); ASSUME(cw(1,0) >= cdl[1]); ASSUME(cw(1,0) >= cds[1]); ASSUME(cw(1,0) >= cctrl[1]); ASSUME(cw(1,0) >= caddr[1]); // Update caddr[1] = max(caddr[1],0); buff(1,0) = 1; mem(0,cw(1,0)) = 1; co(0,cw(1,0))+=1; delta(0,cw(1,0)) = -1; ASSUME(creturn[1] >= cw(1,0)); // ret i8* null, !dbg !50 ret_thread_1 = (- 1); goto T1BLOCK_END; T1BLOCK_END: // Dumping thread 2 int ret_thread_2 = 0; cdy[2] = get_rng(0,NCONTEXT-1); ASSUME(cdy[2] >= cstart[2]); T2BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !53, metadata !DIExpression()), !dbg !61 // br label %label_2, !dbg !44 goto T2BLOCK1; T2BLOCK1: // call void @llvm.dbg.label(metadata !60), !dbg !63 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !54, metadata !DIExpression()), !dbg !64 // call void @llvm.dbg.value(metadata i64 2, metadata !56, metadata !DIExpression()), !dbg !64 // store atomic i64 2, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) release, align 8, !dbg !47 // ST: Guess // : Release iw(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l26_c3 old_cw = cw(2,0); cw(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l26_c3 // Check ASSUME(active[iw(2,0)] == 2); ASSUME(active[cw(2,0)] == 2); ASSUME(sforbid(0,cw(2,0))== 0); ASSUME(iw(2,0) >= 0); ASSUME(iw(2,0) >= 0); ASSUME(cw(2,0) >= iw(2,0)); ASSUME(cw(2,0) >= old_cw); ASSUME(cw(2,0) >= cr(2,0)); ASSUME(cw(2,0) >= cl[2]); ASSUME(cw(2,0) >= cisb[2]); ASSUME(cw(2,0) >= cdy[2]); ASSUME(cw(2,0) >= cdl[2]); ASSUME(cw(2,0) >= cds[2]); ASSUME(cw(2,0) >= cctrl[2]); ASSUME(cw(2,0) >= caddr[2]); ASSUME(cw(2,0) >= cr(2,0+0)); ASSUME(cw(2,0) >= cr(2,0+1)); ASSUME(cw(2,0) >= cr(2,0+2)); ASSUME(cw(2,0) >= cr(2,3+0)); ASSUME(cw(2,0) >= cw(2,0+0)); ASSUME(cw(2,0) >= cw(2,0+1)); ASSUME(cw(2,0) >= cw(2,0+2)); ASSUME(cw(2,0) >= cw(2,3+0)); // Update caddr[2] = max(caddr[2],0); buff(2,0) = 2; mem(0,cw(2,0)) = 2; co(0,cw(2,0))+=1; delta(0,cw(2,0)) = -1; is(2,0) = iw(2,0); cs(2,0) = cw(2,0); ASSUME(creturn[2] >= cw(2,0)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !57, metadata !DIExpression()), !dbg !66 // call void @llvm.dbg.value(metadata i64 1, metadata !59, metadata !DIExpression()), !dbg !66 // store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !49 // ST: Guess iw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l27_c3 old_cw = cw(2,0+2*1); cw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l27_c3 // Check ASSUME(active[iw(2,0+2*1)] == 2); ASSUME(active[cw(2,0+2*1)] == 2); ASSUME(sforbid(0+2*1,cw(2,0+2*1))== 0); ASSUME(iw(2,0+2*1) >= 0); ASSUME(iw(2,0+2*1) >= 0); ASSUME(cw(2,0+2*1) >= iw(2,0+2*1)); ASSUME(cw(2,0+2*1) >= old_cw); ASSUME(cw(2,0+2*1) >= cr(2,0+2*1)); ASSUME(cw(2,0+2*1) >= cl[2]); ASSUME(cw(2,0+2*1) >= cisb[2]); ASSUME(cw(2,0+2*1) >= cdy[2]); ASSUME(cw(2,0+2*1) >= cdl[2]); ASSUME(cw(2,0+2*1) >= cds[2]); ASSUME(cw(2,0+2*1) >= cctrl[2]); ASSUME(cw(2,0+2*1) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,0+2*1) = 1; mem(0+2*1,cw(2,0+2*1)) = 1; co(0+2*1,cw(2,0+2*1))+=1; delta(0+2*1,cw(2,0+2*1)) = -1; ASSUME(creturn[2] >= cw(2,0+2*1)); // ret i8* null, !dbg !50 ret_thread_2 = (- 1); goto T2BLOCK_END; T2BLOCK_END: // Dumping thread 3 int ret_thread_3 = 0; cdy[3] = get_rng(0,NCONTEXT-1); ASSUME(cdy[3] >= cstart[3]); T3BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !71, metadata !DIExpression()), !dbg !81 // br label %label_3, !dbg !46 goto T3BLOCK1; T3BLOCK1: // call void @llvm.dbg.label(metadata !80), !dbg !83 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !73, metadata !DIExpression()), !dbg !84 // %0 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) acquire, align 8, !dbg !49 // LD: Guess // : Acquire old_cr = cr(3,0+2*1); cr(3,0+2*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN LDCOM _l33_c15 // Check ASSUME(active[cr(3,0+2*1)] == 3); ASSUME(cr(3,0+2*1) >= iw(3,0+2*1)); ASSUME(cr(3,0+2*1) >= 0); ASSUME(cr(3,0+2*1) >= cdy[3]); ASSUME(cr(3,0+2*1) >= cisb[3]); ASSUME(cr(3,0+2*1) >= cdl[3]); ASSUME(cr(3,0+2*1) >= cl[3]); ASSUME(cr(3,0+2*1) >= cx(3,0+2*1)); ASSUME(cr(3,0+2*1) >= cs(3,0+0)); ASSUME(cr(3,0+2*1) >= cs(3,0+1)); ASSUME(cr(3,0+2*1) >= cs(3,0+2)); ASSUME(cr(3,0+2*1) >= cs(3,3+0)); // Update creg_r0 = cr(3,0+2*1); crmax(3,0+2*1) = max(crmax(3,0+2*1),cr(3,0+2*1)); caddr[3] = max(caddr[3],0); if(cr(3,0+2*1) < cw(3,0+2*1)) { r0 = buff(3,0+2*1); ASSUME((!(( (cw(3,0+2*1) < 1) && (1 < crmax(3,0+2*1)) )))||(sforbid(0+2*1,1)> 0)); ASSUME((!(( (cw(3,0+2*1) < 2) && (2 < crmax(3,0+2*1)) )))||(sforbid(0+2*1,2)> 0)); ASSUME((!(( (cw(3,0+2*1) < 3) && (3 < crmax(3,0+2*1)) )))||(sforbid(0+2*1,3)> 0)); ASSUME((!(( (cw(3,0+2*1) < 4) && (4 < crmax(3,0+2*1)) )))||(sforbid(0+2*1,4)> 0)); } else { if(pw(3,0+2*1) != co(0+2*1,cr(3,0+2*1))) { ASSUME(cr(3,0+2*1) >= old_cr); } pw(3,0+2*1) = co(0+2*1,cr(3,0+2*1)); r0 = mem(0+2*1,cr(3,0+2*1)); } cl[3] = max(cl[3],cr(3,0+2*1)); ASSUME(creturn[3] >= cr(3,0+2*1)); // call void @llvm.dbg.value(metadata i64 %0, metadata !75, metadata !DIExpression()), !dbg !84 // %conv = trunc i64 %0 to i32, !dbg !50 // call void @llvm.dbg.value(metadata i32 %conv, metadata !72, metadata !DIExpression()), !dbg !81 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !76, metadata !DIExpression()), !dbg !87 // call void @llvm.dbg.value(metadata i64 1, metadata !78, metadata !DIExpression()), !dbg !87 // store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) release, align 8, !dbg !52 // ST: Guess // : Release iw(3,0+1*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW _l34_c3 old_cw = cw(3,0+1*1); cw(3,0+1*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM _l34_c3 // Check ASSUME(active[iw(3,0+1*1)] == 3); ASSUME(active[cw(3,0+1*1)] == 3); ASSUME(sforbid(0+1*1,cw(3,0+1*1))== 0); ASSUME(iw(3,0+1*1) >= 0); ASSUME(iw(3,0+1*1) >= 0); ASSUME(cw(3,0+1*1) >= iw(3,0+1*1)); ASSUME(cw(3,0+1*1) >= old_cw); ASSUME(cw(3,0+1*1) >= cr(3,0+1*1)); ASSUME(cw(3,0+1*1) >= cl[3]); ASSUME(cw(3,0+1*1) >= cisb[3]); ASSUME(cw(3,0+1*1) >= cdy[3]); ASSUME(cw(3,0+1*1) >= cdl[3]); ASSUME(cw(3,0+1*1) >= cds[3]); ASSUME(cw(3,0+1*1) >= cctrl[3]); ASSUME(cw(3,0+1*1) >= caddr[3]); ASSUME(cw(3,0+1*1) >= cr(3,0+0)); ASSUME(cw(3,0+1*1) >= cr(3,0+1)); ASSUME(cw(3,0+1*1) >= cr(3,0+2)); ASSUME(cw(3,0+1*1) >= cr(3,3+0)); ASSUME(cw(3,0+1*1) >= cw(3,0+0)); ASSUME(cw(3,0+1*1) >= cw(3,0+1)); ASSUME(cw(3,0+1*1) >= cw(3,0+2)); ASSUME(cw(3,0+1*1) >= cw(3,3+0)); // Update caddr[3] = max(caddr[3],0); buff(3,0+1*1) = 1; mem(0+1*1,cw(3,0+1*1)) = 1; co(0+1*1,cw(3,0+1*1))+=1; delta(0+1*1,cw(3,0+1*1)) = -1; is(3,0+1*1) = iw(3,0+1*1); cs(3,0+1*1) = cw(3,0+1*1); ASSUME(creturn[3] >= cw(3,0+1*1)); // %cmp = icmp eq i32 %conv, 1, !dbg !53 creg__r0__1_ = max(0,creg_r0); // %conv1 = zext i1 %cmp to i32, !dbg !53 // call void @llvm.dbg.value(metadata i32 %conv1, metadata !79, metadata !DIExpression()), !dbg !81 // store i32 %conv1, i32* @atom_2_X0_1, align 4, !dbg !54, !tbaa !55 // ST: Guess iw(3,3) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW _l36_c15 old_cw = cw(3,3); cw(3,3) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM _l36_c15 // Check ASSUME(active[iw(3,3)] == 3); ASSUME(active[cw(3,3)] == 3); ASSUME(sforbid(3,cw(3,3))== 0); ASSUME(iw(3,3) >= creg__r0__1_); ASSUME(iw(3,3) >= 0); ASSUME(cw(3,3) >= iw(3,3)); ASSUME(cw(3,3) >= old_cw); ASSUME(cw(3,3) >= cr(3,3)); ASSUME(cw(3,3) >= cl[3]); ASSUME(cw(3,3) >= cisb[3]); ASSUME(cw(3,3) >= cdy[3]); ASSUME(cw(3,3) >= cdl[3]); ASSUME(cw(3,3) >= cds[3]); ASSUME(cw(3,3) >= cctrl[3]); ASSUME(cw(3,3) >= caddr[3]); // Update caddr[3] = max(caddr[3],0); buff(3,3) = (r0==1); mem(3,cw(3,3)) = (r0==1); co(3,cw(3,3))+=1; delta(3,cw(3,3)) = -1; ASSUME(creturn[3] >= cw(3,3)); // ret i8* null, !dbg !59 ret_thread_3 = (- 1); goto T3BLOCK_END; T3BLOCK_END: // Dumping thread 0 int ret_thread_0 = 0; cdy[0] = get_rng(0,NCONTEXT-1); ASSUME(cdy[0] >= cstart[0]); T0BLOCK0: // %thr0 = alloca i64, align 8 // %thr1 = alloca i64, align 8 // %thr2 = alloca i64, align 8 // call void @llvm.dbg.value(metadata i32 %argc, metadata !103, metadata !DIExpression()), !dbg !133 // call void @llvm.dbg.value(metadata i8** %argv, metadata !104, metadata !DIExpression()), !dbg !133 // %0 = bitcast i64* %thr0 to i8*, !dbg !69 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #7, !dbg !69 // call void @llvm.dbg.declare(metadata i64* %thr0, metadata !105, metadata !DIExpression()), !dbg !135 // %1 = bitcast i64* %thr1 to i8*, !dbg !71 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #7, !dbg !71 // call void @llvm.dbg.declare(metadata i64* %thr1, metadata !109, metadata !DIExpression()), !dbg !137 // %2 = bitcast i64* %thr2 to i8*, !dbg !73 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %2) #7, !dbg !73 // call void @llvm.dbg.declare(metadata i64* %thr2, metadata !110, metadata !DIExpression()), !dbg !139 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !111, metadata !DIExpression()), !dbg !140 // call void @llvm.dbg.value(metadata i64 0, metadata !113, metadata !DIExpression()), !dbg !140 // store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !76 // ST: Guess iw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l45_c3 old_cw = cw(0,0+2*1); cw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l45_c3 // Check ASSUME(active[iw(0,0+2*1)] == 0); ASSUME(active[cw(0,0+2*1)] == 0); ASSUME(sforbid(0+2*1,cw(0,0+2*1))== 0); ASSUME(iw(0,0+2*1) >= 0); ASSUME(iw(0,0+2*1) >= 0); ASSUME(cw(0,0+2*1) >= iw(0,0+2*1)); ASSUME(cw(0,0+2*1) >= old_cw); ASSUME(cw(0,0+2*1) >= cr(0,0+2*1)); ASSUME(cw(0,0+2*1) >= cl[0]); ASSUME(cw(0,0+2*1) >= cisb[0]); ASSUME(cw(0,0+2*1) >= cdy[0]); ASSUME(cw(0,0+2*1) >= cdl[0]); ASSUME(cw(0,0+2*1) >= cds[0]); ASSUME(cw(0,0+2*1) >= cctrl[0]); ASSUME(cw(0,0+2*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+2*1) = 0; mem(0+2*1,cw(0,0+2*1)) = 0; co(0+2*1,cw(0,0+2*1))+=1; delta(0+2*1,cw(0,0+2*1)) = -1; ASSUME(creturn[0] >= cw(0,0+2*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !114, metadata !DIExpression()), !dbg !142 // call void @llvm.dbg.value(metadata i64 0, metadata !116, metadata !DIExpression()), !dbg !142 // store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !78 // ST: Guess iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l46_c3 old_cw = cw(0,0+1*1); cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l46_c3 // Check ASSUME(active[iw(0,0+1*1)] == 0); ASSUME(active[cw(0,0+1*1)] == 0); ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(cw(0,0+1*1) >= iw(0,0+1*1)); ASSUME(cw(0,0+1*1) >= old_cw); ASSUME(cw(0,0+1*1) >= cr(0,0+1*1)); ASSUME(cw(0,0+1*1) >= cl[0]); ASSUME(cw(0,0+1*1) >= cisb[0]); ASSUME(cw(0,0+1*1) >= cdy[0]); ASSUME(cw(0,0+1*1) >= cdl[0]); ASSUME(cw(0,0+1*1) >= cds[0]); ASSUME(cw(0,0+1*1) >= cctrl[0]); ASSUME(cw(0,0+1*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+1*1) = 0; mem(0+1*1,cw(0,0+1*1)) = 0; co(0+1*1,cw(0,0+1*1))+=1; delta(0+1*1,cw(0,0+1*1)) = -1; ASSUME(creturn[0] >= cw(0,0+1*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !117, metadata !DIExpression()), !dbg !144 // call void @llvm.dbg.value(metadata i64 0, metadata !119, metadata !DIExpression()), !dbg !144 // store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !80 // ST: Guess iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l47_c3 old_cw = cw(0,0); cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l47_c3 // Check ASSUME(active[iw(0,0)] == 0); ASSUME(active[cw(0,0)] == 0); ASSUME(sforbid(0,cw(0,0))== 0); ASSUME(iw(0,0) >= 0); ASSUME(iw(0,0) >= 0); ASSUME(cw(0,0) >= iw(0,0)); ASSUME(cw(0,0) >= old_cw); ASSUME(cw(0,0) >= cr(0,0)); ASSUME(cw(0,0) >= cl[0]); ASSUME(cw(0,0) >= cisb[0]); ASSUME(cw(0,0) >= cdy[0]); ASSUME(cw(0,0) >= cdl[0]); ASSUME(cw(0,0) >= cds[0]); ASSUME(cw(0,0) >= cctrl[0]); ASSUME(cw(0,0) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0) = 0; mem(0,cw(0,0)) = 0; co(0,cw(0,0))+=1; delta(0,cw(0,0)) = -1; ASSUME(creturn[0] >= cw(0,0)); // store i32 0, i32* @atom_2_X0_1, align 4, !dbg !81, !tbaa !82 // ST: Guess iw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l48_c15 old_cw = cw(0,3); cw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l48_c15 // Check ASSUME(active[iw(0,3)] == 0); ASSUME(active[cw(0,3)] == 0); ASSUME(sforbid(3,cw(0,3))== 0); ASSUME(iw(0,3) >= 0); ASSUME(iw(0,3) >= 0); ASSUME(cw(0,3) >= iw(0,3)); ASSUME(cw(0,3) >= old_cw); ASSUME(cw(0,3) >= cr(0,3)); ASSUME(cw(0,3) >= cl[0]); ASSUME(cw(0,3) >= cisb[0]); ASSUME(cw(0,3) >= cdy[0]); ASSUME(cw(0,3) >= cdl[0]); ASSUME(cw(0,3) >= cds[0]); ASSUME(cw(0,3) >= cctrl[0]); ASSUME(cw(0,3) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,3) = 0; mem(3,cw(0,3)) = 0; co(3,cw(0,3))+=1; delta(3,cw(0,3)) = -1; ASSUME(creturn[0] >= cw(0,3)); // %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #7, !dbg !86 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[1] >= cdy[0]); // %call5 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #7, !dbg !87 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[2] >= cdy[0]); // %call6 = call i32 @pthread_create(i64* noundef %thr2, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t2, i8* noundef null) #7, !dbg !88 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[3] >= cdy[0]); // %3 = load i64, i64* %thr0, align 8, !dbg !89, !tbaa !90 r2 = local_mem[0]; // %call7 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !92 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[1]); // %4 = load i64, i64* %thr1, align 8, !dbg !93, !tbaa !90 r3 = local_mem[1]; // %call8 = call i32 @pthread_join(i64 noundef %4, i8** noundef null), !dbg !94 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[2]); // %5 = load i64, i64* %thr2, align 8, !dbg !95, !tbaa !90 r4 = local_mem[2]; // %call9 = call i32 @pthread_join(i64 noundef %5, i8** noundef null), !dbg !96 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[3]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !121, metadata !DIExpression()), !dbg !158 // %6 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !98 // LD: Guess old_cr = cr(0,0+1*1); cr(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l58_c12 // Check ASSUME(active[cr(0,0+1*1)] == 0); ASSUME(cr(0,0+1*1) >= iw(0,0+1*1)); ASSUME(cr(0,0+1*1) >= 0); ASSUME(cr(0,0+1*1) >= cdy[0]); ASSUME(cr(0,0+1*1) >= cisb[0]); ASSUME(cr(0,0+1*1) >= cdl[0]); ASSUME(cr(0,0+1*1) >= cl[0]); // Update creg_r5 = cr(0,0+1*1); crmax(0,0+1*1) = max(crmax(0,0+1*1),cr(0,0+1*1)); caddr[0] = max(caddr[0],0); if(cr(0,0+1*1) < cw(0,0+1*1)) { r5 = buff(0,0+1*1); ASSUME((!(( (cw(0,0+1*1) < 1) && (1 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,1)> 0)); ASSUME((!(( (cw(0,0+1*1) < 2) && (2 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,2)> 0)); ASSUME((!(( (cw(0,0+1*1) < 3) && (3 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,3)> 0)); ASSUME((!(( (cw(0,0+1*1) < 4) && (4 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,4)> 0)); } else { if(pw(0,0+1*1) != co(0+1*1,cr(0,0+1*1))) { ASSUME(cr(0,0+1*1) >= old_cr); } pw(0,0+1*1) = co(0+1*1,cr(0,0+1*1)); r5 = mem(0+1*1,cr(0,0+1*1)); } ASSUME(creturn[0] >= cr(0,0+1*1)); // call void @llvm.dbg.value(metadata i64 %6, metadata !123, metadata !DIExpression()), !dbg !158 // %conv = trunc i64 %6 to i32, !dbg !99 // call void @llvm.dbg.value(metadata i32 %conv, metadata !120, metadata !DIExpression()), !dbg !133 // %cmp = icmp eq i32 %conv, 2, !dbg !100 creg__r5__2_ = max(0,creg_r5); // %conv10 = zext i1 %cmp to i32, !dbg !100 // call void @llvm.dbg.value(metadata i32 %conv10, metadata !124, metadata !DIExpression()), !dbg !133 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !126, metadata !DIExpression()), !dbg !162 // %7 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !102 // LD: Guess old_cr = cr(0,0); cr(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l60_c12 // Check ASSUME(active[cr(0,0)] == 0); ASSUME(cr(0,0) >= iw(0,0)); ASSUME(cr(0,0) >= 0); ASSUME(cr(0,0) >= cdy[0]); ASSUME(cr(0,0) >= cisb[0]); ASSUME(cr(0,0) >= cdl[0]); ASSUME(cr(0,0) >= cl[0]); // Update creg_r6 = cr(0,0); crmax(0,0) = max(crmax(0,0),cr(0,0)); caddr[0] = max(caddr[0],0); if(cr(0,0) < cw(0,0)) { r6 = buff(0,0); ASSUME((!(( (cw(0,0) < 1) && (1 < crmax(0,0)) )))||(sforbid(0,1)> 0)); ASSUME((!(( (cw(0,0) < 2) && (2 < crmax(0,0)) )))||(sforbid(0,2)> 0)); ASSUME((!(( (cw(0,0) < 3) && (3 < crmax(0,0)) )))||(sforbid(0,3)> 0)); ASSUME((!(( (cw(0,0) < 4) && (4 < crmax(0,0)) )))||(sforbid(0,4)> 0)); } else { if(pw(0,0) != co(0,cr(0,0))) { ASSUME(cr(0,0) >= old_cr); } pw(0,0) = co(0,cr(0,0)); r6 = mem(0,cr(0,0)); } ASSUME(creturn[0] >= cr(0,0)); // call void @llvm.dbg.value(metadata i64 %7, metadata !128, metadata !DIExpression()), !dbg !162 // %conv14 = trunc i64 %7 to i32, !dbg !103 // call void @llvm.dbg.value(metadata i32 %conv14, metadata !125, metadata !DIExpression()), !dbg !133 // %cmp15 = icmp eq i32 %conv14, 2, !dbg !104 creg__r6__2_ = max(0,creg_r6); // %conv16 = zext i1 %cmp15 to i32, !dbg !104 // call void @llvm.dbg.value(metadata i32 %conv16, metadata !129, metadata !DIExpression()), !dbg !133 // %8 = load i32, i32* @atom_2_X0_1, align 4, !dbg !105, !tbaa !82 // LD: Guess old_cr = cr(0,3); cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l62_c12 // Check ASSUME(active[cr(0,3)] == 0); ASSUME(cr(0,3) >= iw(0,3)); ASSUME(cr(0,3) >= 0); ASSUME(cr(0,3) >= cdy[0]); ASSUME(cr(0,3) >= cisb[0]); ASSUME(cr(0,3) >= cdl[0]); ASSUME(cr(0,3) >= cl[0]); // Update creg_r7 = cr(0,3); crmax(0,3) = max(crmax(0,3),cr(0,3)); caddr[0] = max(caddr[0],0); if(cr(0,3) < cw(0,3)) { r7 = buff(0,3); ASSUME((!(( (cw(0,3) < 1) && (1 < crmax(0,3)) )))||(sforbid(3,1)> 0)); ASSUME((!(( (cw(0,3) < 2) && (2 < crmax(0,3)) )))||(sforbid(3,2)> 0)); ASSUME((!(( (cw(0,3) < 3) && (3 < crmax(0,3)) )))||(sforbid(3,3)> 0)); ASSUME((!(( (cw(0,3) < 4) && (4 < crmax(0,3)) )))||(sforbid(3,4)> 0)); } else { if(pw(0,3) != co(3,cr(0,3))) { ASSUME(cr(0,3) >= old_cr); } pw(0,3) = co(3,cr(0,3)); r7 = mem(3,cr(0,3)); } ASSUME(creturn[0] >= cr(0,3)); // call void @llvm.dbg.value(metadata i32 %8, metadata !130, metadata !DIExpression()), !dbg !133 // %and = and i32 %conv16, %8, !dbg !106 creg_r8 = max(creg__r6__2_,creg_r7); r8 = (r6==2) & r7; // call void @llvm.dbg.value(metadata i32 %and, metadata !131, metadata !DIExpression()), !dbg !133 // %and17 = and i32 %conv10, %and, !dbg !107 creg_r9 = max(creg__r5__2_,creg_r8); r9 = (r5==2) & r8; // call void @llvm.dbg.value(metadata i32 %and17, metadata !132, metadata !DIExpression()), !dbg !133 // %cmp18 = icmp eq i32 %and17, 1, !dbg !108 creg__r9__1_ = max(0,creg_r9); // br i1 %cmp18, label %if.then, label %if.end, !dbg !110 old_cctrl = cctrl[0]; cctrl[0] = get_rng(0,NCONTEXT-1); ASSUME(cctrl[0] >= old_cctrl); ASSUME(cctrl[0] >= creg__r9__1_); if((r9==1)) { goto T0BLOCK1; } else { goto T0BLOCK2; } T0BLOCK1: // call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([134 x i8], [134 x i8]* @.str.1, i64 0, i64 0), i32 noundef 65, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #8, !dbg !111 // unreachable, !dbg !111 r10 = 1; goto T0BLOCK_END; T0BLOCK2: // %9 = bitcast i64* %thr2 to i8*, !dbg !114 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %9) #7, !dbg !114 // %10 = bitcast i64* %thr1 to i8*, !dbg !114 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %10) #7, !dbg !114 // %11 = bitcast i64* %thr0 to i8*, !dbg !114 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %11) #7, !dbg !114 // ret i32 0, !dbg !115 ret_thread_0 = 0; goto T0BLOCK_END; T0BLOCK_END: ASSUME(meminit(0,1) == mem(0,0)); ASSUME(coinit(0,1) == co(0,0)); ASSUME(deltainit(0,1) == delta(0,0)); ASSUME(meminit(0,2) == mem(0,1)); ASSUME(coinit(0,2) == co(0,1)); ASSUME(deltainit(0,2) == delta(0,1)); ASSUME(meminit(0,3) == mem(0,2)); ASSUME(coinit(0,3) == co(0,2)); ASSUME(deltainit(0,3) == delta(0,2)); ASSUME(meminit(0,4) == mem(0,3)); ASSUME(coinit(0,4) == co(0,3)); ASSUME(deltainit(0,4) == delta(0,3)); ASSUME(meminit(1,1) == mem(1,0)); ASSUME(coinit(1,1) == co(1,0)); ASSUME(deltainit(1,1) == delta(1,0)); ASSUME(meminit(1,2) == mem(1,1)); ASSUME(coinit(1,2) == co(1,1)); ASSUME(deltainit(1,2) == delta(1,1)); ASSUME(meminit(1,3) == mem(1,2)); ASSUME(coinit(1,3) == co(1,2)); ASSUME(deltainit(1,3) == delta(1,2)); ASSUME(meminit(1,4) == mem(1,3)); ASSUME(coinit(1,4) == co(1,3)); ASSUME(deltainit(1,4) == delta(1,3)); ASSUME(meminit(2,1) == mem(2,0)); ASSUME(coinit(2,1) == co(2,0)); ASSUME(deltainit(2,1) == delta(2,0)); ASSUME(meminit(2,2) == mem(2,1)); ASSUME(coinit(2,2) == co(2,1)); ASSUME(deltainit(2,2) == delta(2,1)); ASSUME(meminit(2,3) == mem(2,2)); ASSUME(coinit(2,3) == co(2,2)); ASSUME(deltainit(2,3) == delta(2,2)); ASSUME(meminit(2,4) == mem(2,3)); ASSUME(coinit(2,4) == co(2,3)); ASSUME(deltainit(2,4) == delta(2,3)); ASSUME(meminit(3,1) == mem(3,0)); ASSUME(coinit(3,1) == co(3,0)); ASSUME(deltainit(3,1) == delta(3,0)); ASSUME(meminit(3,2) == mem(3,1)); ASSUME(coinit(3,2) == co(3,1)); ASSUME(deltainit(3,2) == delta(3,1)); ASSUME(meminit(3,3) == mem(3,2)); ASSUME(coinit(3,3) == co(3,2)); ASSUME(deltainit(3,3) == delta(3,2)); ASSUME(meminit(3,4) == mem(3,3)); ASSUME(coinit(3,4) == co(3,3)); ASSUME(deltainit(3,4) == delta(3,3)); ASSERT(r10== 0); }
[ "tuan-phong.ngo@it.uu.se" ]
tuan-phong.ngo@it.uu.se
9b49b83172f848427ce694bd6b0c8aa93df5b1f7
1b983cdd09055677966b092294b1e3693d33042c
/src/modules/mindwave/MindwaveModule.cpp
583abd9b52e3569d525b0d6164a7395d2f0f9b7e
[]
no_license
20SecondsToSun/Mindwave
19d7f8ded5c1419c2e3fd94dfd788d0d86781d58
413ef1ad0a4f93badbfff586fb0873510317c0e1
refs/heads/master
2020-03-28T06:23:13.042247
2018-09-10T14:16:13
2018-09-10T14:16:13
147,831,505
0
0
null
null
null
null
UTF-8
C++
false
false
2,154
cpp
#include "MindwaveModule.h" #include "src/tools/MathTools.h" #include "src/components/mindwave/BaseMindwaveComponent.h" #include "src/components/mindwave/BaseMindwaveParser.h" #include "src/components/mindwave/BaseMindwaveReader.h" #include "src/components/mindwave/serial/MindwaveComponentSerial.h" #include "src/components/mindwave/tcp/MindwaveComponentTCP.h" #include "src/components/mindwave/simulation/MindwaveComponentSimulation.h" #include "src/components/mindwave/mindwaveconfig.h" MindwaveModule::MindwaveModule(QObject *parent) : BaseModule(parent) { name = "mindwave"; } MindwaveModule::~MindwaveModule() { } template <class MindwaveComponentT> void MindwaveModule::inject() { mindwave.reset(new MindwaveComponentT()); } void MindwaveModule::init() { MindwaveConfig config; if(provider == MindwaveProvider::TCP) { config.serialPortName = "COM5"; config.noDataTimeoutMills = 6000; config.reconnectionMills = 1000; inject<MindwaveComponentSerial>(); } else if(provider == MindwaveProvider::TCP) { MindwaveConfig config; config.ip = "127.0.0.1"; config.port = 13854; inject<MindwaveComponentTCP>(); } else if(provider == MindwaveProvider::Simulation) { inject<MindwaveComponentSimulation>(); } mindwave->setConfig(config); connect(mindwave.data(), SIGNAL(meditationChanged()), this, SLOT(onMeditationChanged())); connect(mindwave.data(), SIGNAL(attentionChanged()), this, SLOT(onAttentionChanged())); connect(mindwave.data(), SIGNAL(poorSignalLevelChanged()), this, SLOT(onPoorSignalLevelChanged())); } void MindwaveModule::start() { mindwave->start(); } void MindwaveModule::stop() { } void MindwaveModule::onMeditationChanged() { emit meditationChanged(mindwave->meditation()); } void MindwaveModule::onAttentionChanged() { emit attentionChanged(mindwave->attention()); } void MindwaveModule::onPoorSignalLevelChanged() { emit poorSignalLevelChanged(mindwave->poorSignalLevel()); } void MindwaveModule::onDeviceStateChanged(int value) { emit deviceStateChanged(value); }
[ "yurikblech@gmail.com" ]
yurikblech@gmail.com
acf56efa26faca1b259d3c9df87ca7f86bc2de7c
c8cf973af91404a716d08d6ac12f6cc8601421d4
/3618/7146301_AC_125MS_332K.cpp
5d3648428f81b711dae43618bd543e8c840cfac4
[ "MIT" ]
permissive
Xuhui-Wang/poj-solutions
f1cd7009fcc37672d3a2ca81851ac3b3cc64ca02
4895764ab800e8c2c4b2334a562dec2f07fa243e
refs/heads/master
2021-05-05T00:14:35.384333
2015-08-19T21:57:31
2015-08-19T21:57:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
859
cpp
#define _CRT_SECURE_NO_WARNINGS #include<cstdio> #include<algorithm> bool distanceLess(const int left,const int right){ return abs(left)<abs(right); } int main(){ int timeLimit,landmarkNum; scanf("%d%d",&timeLimit,&landmarkNum); int *landmarkPositions=new int[landmarkNum]; for(int landmarkIndex=0;landmarkIndex<landmarkNum;landmarkIndex++) scanf("%d",landmarkPositions+landmarkIndex); std::sort(landmarkPositions,landmarkPositions+landmarkNum,distanceLess); int currentPosition=0,timeUsed=0,landmarkVisitedNum=0; while(landmarkVisitedNum<landmarkNum){ timeUsed+=abs(landmarkPositions[landmarkVisitedNum]-currentPosition); if(timeUsed>timeLimit) break; currentPosition=landmarkPositions[landmarkVisitedNum]; landmarkVisitedNum++; } printf("%d\n",landmarkVisitedNum); delete landmarkPositions; return 0; }
[ "pinepara@gmail.com" ]
pinepara@gmail.com
b0ec493ac674e908561f7022f0f6e2bfe1fedfc1
2e9abb50e8c00617c6600fd0b10f6af59948a642
/src/Camera.h
46d2fe4ae15631a6210431a72bcf91cac5d6b030
[]
no_license
2020wmarvil/EM-Engine
87f8518ae1e700f69f9318903f5fa5ac807ae5a8
3c192629bfbd4a48bd0cb28ef4cd7000c4c35c01
refs/heads/master
2023-03-06T19:17:01.117245
2021-01-24T05:34:32
2021-01-24T05:34:32
216,225,828
0
0
null
null
null
null
UTF-8
C++
false
false
445
h
#pragma once #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "glm/gtc/type_ptr.hpp" #include "Entity.h" class Camera { private: const Entity *m_FocusedEntity; glm::vec2 m_CamOffset; const float m_CameraZ = 0.0f; public: Camera(const Entity *focused, int midX, int midY); ~Camera(); void SetFocusedEntity(const Entity *entity) { m_FocusedEntity = entity; } glm::mat4 GetViewMatrix(); };
[ "2020wmarvil@tjhsst.edu" ]
2020wmarvil@tjhsst.edu
94615ebf3f1c32271310fb4e21ed035d1b6c22f1
9ac56ff5b745fdebf34083ac113c577a8b120aa3
/src/game/shared/sdk/weapon_grenade.cpp
40161b0103bdcb9fd598806f0d16d626af252edf
[]
no_license
FriskTheFallenHuman/swarm-sdk-template
16e8e29edb9a19ecd1b38ededcc31fb1f6653ae1
a6e6bf7fcbe5b93b5e5fc4ad32944022dae27f90
refs/heads/master
2023-01-13T17:23:32.693199
2020-11-11T00:44:59
2020-11-11T00:44:59
38,081,794
8
3
null
2020-11-11T00:45:00
2015-06-26T00:32:09
C++
WINDOWS-1252
C++
false
false
4,232
cpp
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #include "cbase.h" #include "weapon_sdkbase.h" #include "gamerules.h" #include "npcevent.h" #include "engine/IEngineSound.h" #include "weapon_grenade.h" #ifdef CLIENT_DLL #else #include "sdk_player.h" #include "items.h" #include "sdk_basegrenade_projectile.h" #endif #define GRENADE_TIMER 3.0f //Seconds IMPLEMENT_NETWORKCLASS_ALIASED( WeaponGrenade, DT_WeaponGrenade ) BEGIN_NETWORK_TABLE(CWeaponGrenade, DT_WeaponGrenade) END_NETWORK_TABLE() BEGIN_PREDICTION_DATA( CWeaponGrenade ) END_PREDICTION_DATA() LINK_ENTITY_TO_CLASS( weapon_grenade, CWeaponGrenade ); PRECACHE_WEAPON_REGISTER( weapon_grenade ); #ifdef GAME_DLL #define GRENADE_MODEL "models/Weapons/w_eq_fraggrenade_thrown.mdl" class CGrenadeProjectile : public CBaseGrenadeProjectile { public: DECLARE_CLASS( CGrenadeProjectile, CBaseGrenadeProjectile ); //Tony; by default projectiles don't have one, so make sure derived weapons do!! virtual SDKWeaponID GetWeaponID( void ) const { return SDK_WEAPON_GRENADE; } // Overrides. public: virtual void Spawn() { SetModel( GRENADE_MODEL ); BaseClass::Spawn(); } virtual void Precache() { PrecacheModel( GRENADE_MODEL ); BaseClass::Precache(); } // Grenade stuff. public: static CGrenadeProjectile* Create( const Vector &position, const QAngle &angles, const Vector &velocity, const AngularImpulse &angVelocity, CBaseCombatCharacter *pOwner, CWeaponSDKBase *pWeapon, float timer ) { CGrenadeProjectile *pGrenade = (CGrenadeProjectile*)CBaseEntity::Create( "grenade_projectile", position, angles, pOwner ); // Set the timer for 1 second less than requested. We're going to issue a SOUND_DANGER // one second before detonation. pGrenade->SetVelocity( velocity, angVelocity ); pGrenade->SetDetonateTimerLength( timer ); pGrenade->SetAbsVelocity( velocity ); pGrenade->SetupInitialTransmittedGrenadeVelocity( velocity ); pGrenade->SetThrower( pOwner ); pGrenade->SetGravity( BaseClass::GetGrenadeGravity() ); pGrenade->SetFriction( BaseClass::GetGrenadeFriction() ); pGrenade->SetElasticity( BaseClass::GetGrenadeElasticity() ); pGrenade->m_flDamage = pWeapon->GetSDKWpnData().m_iDamage; pGrenade->m_DmgRadius = pGrenade->m_flDamage * 3.5f; pGrenade->ChangeTeam( pOwner->GetTeamNumber() ); pGrenade->ApplyLocalAngularVelocityImpulse( angVelocity ); // make NPCs afaid of it while in the air pGrenade->SetThink( &CGrenadeProjectile::DangerSoundThink ); pGrenade->SetNextThink( gpGlobals->curtime ); return pGrenade; } }; LINK_ENTITY_TO_CLASS( grenade_projectile, CGrenadeProjectile ); PRECACHE_WEAPON_REGISTER( grenade_projectile ); BEGIN_DATADESC( CWeaponGrenade ) END_DATADESC() void CWeaponGrenade::EmitGrenade( Vector vecSrc, QAngle vecAngles, Vector vecVel, AngularImpulse angImpulse, CBasePlayer *pPlayer, CWeaponSDKBase *pWeapon ) { CGrenadeProjectile::Create( vecSrc, vecAngles, vecVel, angImpulse, pPlayer, pWeapon, GRENADE_TIMER ); } #endif //Tony; todo; add ACT_MP_PRONE* activities, so we have them. acttable_t CWeaponGrenade::m_acttable[] = { { ACT_MP_STAND_IDLE, ACT_DOD_STAND_AIM_GREN_FRAG, false }, { ACT_MP_CROUCH_IDLE, ACT_DOD_CROUCH_AIM_GREN_FRAG, false }, { ACT_MP_PRONE_IDLE, ACT_DOD_PRONE_AIM_GREN_FRAG, false }, { ACT_MP_RUN, ACT_DOD_RUN_AIM_GREN_FRAG, false }, { ACT_MP_WALK, ACT_DOD_WALK_AIM_GREN_FRAG, false }, { ACT_MP_CROUCHWALK, ACT_DOD_CROUCHWALK_AIM_GREN_FRAG, false }, { ACT_MP_PRONE_CRAWL, ACT_DOD_PRONEWALK_AIM_GREN_FRAG, false }, { ACT_SPRINT, ACT_DOD_SPRINT_AIM_GREN_FRAG, false }, { ACT_MP_ATTACK_STAND_PRIMARYFIRE, ACT_DOD_PRIMARYATTACK_GREN_FRAG, false }, { ACT_MP_ATTACK_CROUCH_PRIMARYFIRE, ACT_DOD_PRIMARYATTACK_GREN_FRAG, false }, { ACT_MP_ATTACK_PRONE_PRIMARYFIRE, ACT_DOD_PRIMARYATTACK_PRONE_GREN_FRAG, false }, }; IMPLEMENT_ACTTABLE( CWeaponGrenade );
[ "kosire.dk@gmail.com" ]
kosire.dk@gmail.com
e608bf78b8ca8d5711d6f28aae4ffb416f9110b1
eae9caf6ceec52dde2334e1f0b494cecda5926ec
/MfcExamples/STYLES/Styles.h
ce62822e47325254460e2e95bb30327b7de52c4b
[]
no_license
logogin/WinApiProjects
b2b39975f94cd51f51b0077c28d3bedef2758583
f0d49539815648ecd48e9eb5604a14bf6d07264e
refs/heads/master
2020-03-28T04:47:02.159962
2018-09-06T21:42:01
2018-09-06T21:42:01
147,736,244
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
961
h
///////////////////////////////////////////////////////////// // Файл Styles.h // Copyright (c) 1999 Мешков А., Тихомиров Ю. ///////////////////////////////////////////////////////////// // main header file for the STYLES application // #ifndef __AFXWIN_H__ #error include 'stdafx.h' before including this file for PCH #endif #include "resource.h" // main symbols ///////////////////////////////////////////////////////////////////////////// // CStylesApp: // See Styles.cpp for the implementation of this class // class CStylesApp : public CWinApp { public: CStylesApp(); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CStylesApp) public: virtual BOOL InitInstance(); //}}AFX_VIRTUAL // Implementation //{{AFX_MSG(CStylesApp) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; /////////////////////////////////////////////////////////////////////////////
[ "logogin@users.noreply.github.com" ]
logogin@users.noreply.github.com
4c09b71e4fe8a0e59379efb32e132b1c10ace41b
5ea90e8ef6cc9a9e26a035d79599863dae4220c7
/SimpleParticleEngine/src/SimpleParticleEngineApp.cpp
d419f9cd07ebdc5494b4c220ec9199880e09b2a9
[]
no_license
Killeroo/CinderProjects
564ffcccb266963e6485fa10a17e36af9c115a9a
82eedd8dd55638ef36d0cc62bf32a6333f0d8785
refs/heads/master
2020-03-21T23:28:21.429967
2018-06-29T22:03:22
2018-06-29T22:03:22
139,189,158
0
0
null
null
null
null
UTF-8
C++
false
false
1,279
cpp
// https://libcinder.org/docs/guides/tour/hello_cinder_chapter1.html // https://github.com/cinder/Cinder/tree/3bb2a1d5c52a2d2548e01df6244a3afe55ee7cf0/tour/Chapter%201 #include "cinder/app/App.h" #include "cinder/app/RendererGl.h" #include "cinder/gl/gl.h" #include "ParticleController.h" using namespace ci; using namespace ci::app; using namespace std; class SimpleParticleEngineApp : public App { public: void prepareSettings(Settings *settings); void setup() override; void mouseDown( MouseEvent event ) override; void update() override; void draw() override; ParticleController mParticleController; }; // Setup window properties void SimpleParticleEngineApp::prepareSettings(Settings *settings) { settings->setWindowSize(800, 600); settings->setFrameRate(60.0f); } // Setup app void SimpleParticleEngineApp::setup() { mParticleController.addParticles(100); } void SimpleParticleEngineApp::mouseDown( MouseEvent event ) { } // Called once a frame before draw void SimpleParticleEngineApp::update() { mParticleController.update(); } // Called once a frame to draw stuff void SimpleParticleEngineApp::draw() { gl::clear( Color( 0, 0, 0 ), true ); // Draw black background mParticleController.draw(); } CINDER_APP( SimpleParticleEngineApp, RendererGl )
[ "matthewcarney64@gmail.com" ]
matthewcarney64@gmail.com
d813d90eec025d578581bcaa5befad8406379bf3
71decf3230d325a9586b9971d480d02b7bf7c86c
/cpp/libs/dsu.h
47fb62d6bc238702d4fd9704622c02bf5ffc7a0d
[]
no_license
jaichhabra/contest
4d92fc8c50fdc7e6716e7b415688520775d57113
2cdd1ed4e2e98cc6eb86d66fe0d4cba8a0c47372
refs/heads/master
2021-04-14T16:16:45.203314
2020-03-22T17:37:23
2020-03-22T17:37:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
604
h
#ifndef DSU_H #define DSU_H #include "common.h" namespace dsu { template <int N> class DSU { private: int p[N]; int rank[N]; public: DSU() { reset(); } void reset() { for (int i = 0; i < N; i++) { p[i] = i; rank[i] = 0; } } int find(int a) { return p[a] == p[p[a]] ? p[a] : (p[a] = find(p[a])); } void merge(int a, int b) { a = find(a); b = find(b); if (a == b) { return; } if (rank[a] == rank[b]) { rank[a]++; } if (rank[a] > rank[b]) { p[b] = a; } else { p[a] = b; } } }; } // namespace dsu #endif
[ "daling.tao@ideacome.com" ]
daling.tao@ideacome.com
b1f666fec7602d8eb63f93ac24e5fa681b631bc3
b2bf2bf0087f8387411965787ad2c4b65829648e
/src/object.cc
607ca402b1cabd853d2b74fd15c599564dd1b9e8
[ "MIT" ]
permissive
klantz81/path-tracer
21d9aac9bdd20e5945c44459a17303a4cbcc3d21
2de763fe6f4fce65b856cdfdb8fa363f48d58f01
refs/heads/master
2021-01-10T08:28:43.660048
2016-03-31T21:37:19
2016-03-31T21:37:19
55,160,392
5
0
null
null
null
null
UTF-8
C++
false
false
9,162
cc
#include "object.h" cObject::cObject() : color(vector3(1.0,1.0,1.0)), emissive(vector3(0.0,0.0,0.0)), material(DIFFUSE), texture(-1), e0(0.0,1.0,0.0), e1(0.0,0.0,1.0), e2(0.0,0.0,0.0), e0_(0.0,1.0,0.0), e1_(0.0,0.0,1.0), e2_(0.0,0.0,0.0) { } cObject::cObject(vector3 color, vector3 emissive, int material, int texture, vector3 e0, vector3 e1, vector3 e2) : color(color), emissive(emissive), material(material), texture(texture), e0(e0), e1(e1), e2(e2), e0_(e0), e1_(e1), e2_(e2) { } cObject::~cObject() { } cPlane::cPlane() : normal(vector3(0.0,0.0,1.0)), point(vector3()), normal_(vector3(0.0,0.0,1.0)), point_(vector3()), cObject(vector3(1.0,1.0,1.0), vector3(0.0,0.0,0.0), DIFFUSE, -1, vector3(0.0,1.0,0.0), vector3(0.0,0.0,1.0), vector3()) { this->type = PLANE; } cPlane::cPlane(vector3 normal, vector3 point, vector3 color, vector3 emissive, int material, int texture, vector3 e0, vector3 e1) : normal(normal), point(point), normal_(normal), point_(point), cObject(color, emissive, material, texture, e0, e1, vector3()) { this->type = PLANE; } cPlane::~cPlane() { } void cPlane::applyCamera(cMatrix& camera) { vector3 p = this->point_ + this->normal_; this->point = camera.mult(this->point_); p = camera.mult(p); this->normal = (p - this->point).unit(); p = this->point_ + e0_; p = camera.mult(p); this->e0 = (p - this->point); p = this->point_ + e1_; p = camera.mult(p); this->e1 = (p - this->point); } void cPlane::save() { this->normal_ = this->normal; this->point_ = this->point; this->e0_ = this->e0; this->e1_ = this->e1; } cSphere::cSphere() : center(vector3(0.0,0.0,0.0)), center_(vector3(0.0,0.0,0.0)), radius(1.0), radius_(1.0), cObject(vector3(1.0,1.0,1.0), vector3(0.0,0.0,0.0), DIFFUSE, -1, vector3(0.0,1.0,0.0), vector3(0.0,0.0,1.0), vector3()) { this->type = SPHERE; } cSphere::cSphere(vector3 center, double radius, vector3 color, vector3 emissive, int material, int texture, vector3 e0, vector3 e1) : center(center), center_(center), radius(radius), radius_(radius), cObject(color, emissive, material, texture, e0, e1, vector3()) { this->type = SPHERE; } cSphere::~cSphere() { } void cSphere::applyCamera(cMatrix& camera) { this->center = camera.mult(this->center_); vector3 p = this->center_ + e0_; p = camera.mult(p); this->e0 = (p - this->center); p = this->center_ + e1_; p = camera.mult(p); this->e1 = (p - this->center); } void cSphere::save() { this->center_ = this->center; this->radius_ = this->radius; this->e0_ = this->e0; this->e1_ = this->e1; } cTriangle::cTriangle() : p0(vector3(0.0,1.0,0.0)), p1(vector3(-1.0,0.0,0.0)), p2(vector3(1.0,0.0,0.0)), p0_(vector3(0.0,1.0,0.0)), p1_(vector3(-1.0,0.0,0.0)), p2_(vector3(1.0,0.0,0.0)), n0(vector3(0.0,0.0,1.0)), n1(vector3(0.0,0.0,1.0)), n2(vector3(0.0,0.0,1.0)), n0_(vector3(0.0,0.0,1.0)), n1_(vector3(0.0,0.0,1.0)), n2_(vector3(0.0,0.0,1.0)), cObject(vector3(1.0,1.0,1.0),vector3(0.0,0.0,0.0), DIFFUSE, -1, vector3(0.0,0.0,0.0), vector3(1.0,0.0,0.0), vector3(0.0,1.0,0.0)) { this->type = TRIANGLE; this->n = this->n_ = ((p1-p0).cross(p2-p0)).unit(); } cTriangle::cTriangle(vector3 p0, vector3 p1, vector3 p2, vector3 n0, vector3 n1, vector3 n2, vector3 color, vector3 emissive, int material, int texture, vector3 e0, vector3 e1, vector3 e2) : p0(p0), p1(p1), p2(p2), p0_(p0), p1_(p1), p2_(p2), n0(n0), n1(n1), n2(n2), n0_(n0), n1_(n1), n2_(n2), cObject(color, emissive, material, texture, e0, e1, e2) { this->type = TRIANGLE; this->n = this->n_ = ((p1-p0).cross(p2-p0)).unit(); } cTriangle::~cTriangle() { } void cTriangle::applyCamera(cMatrix& camera) { vector3 _n0, _n1, _n2; vector3 _n; _n = this->p0_ + this->n_; _n0 = this->p0_ + this->n0_; _n1 = this->p1_ + this->n1_; _n2 = this->p2_ + this->n2_; this->p0 = camera.mult(this->p0_); this->p1 = camera.mult(this->p1_); this->p2 = camera.mult(this->p2_); _n = camera.mult(_n); _n0 = camera.mult(_n0); _n1 = camera.mult(_n1); _n2 = camera.mult(_n2); this->n = (_n - this->p0).unit(); this->n0 = (_n0 - this->p0).unit(); this->n1 = (_n1 - this->p1).unit(); this->n2 = (_n2 - this->p2).unit(); } void cTriangle::save() { this->p0_ = this->p0; this->p1_ = this->p1; this->p2_ = this->p2; this->n0_ = this->n0; this->n1_ = this->n1; this->n2_ = this->n2; this->n_ = this->n; } void applyCamera(vector3 origin, vector3 forward, vector3 up, std::vector<cObject*> objects) { vector3 right = (forward.cross(up)).unit(); up = (right.cross(forward)).unit(); // forward = forward*-1; // vector3 right = (up.cross(forward)).unit(); // up = (forward.cross(right)).unit(); double cam[] = { right.x, right.y, right.z, -(right*origin), up.x, up.y, up.z, -(up*origin), -forward.x, -forward.y, -forward.z, (forward*origin), 0, 0, 0, 1 }; cMatrix camera(4, 4, cam); for (int i = 0; i < objects.size(); i++) { objects[i]->applyCamera(camera); //objects[i]->save(); } } void copyObjects(std::vector<cObject*> objects, __object _objects[], __bounds& bounds) { for (int i = 0; i < objects.size(); i++) { _objects[i].type = objects[i]->type; _objects[i].material = objects[i]->material; _objects[i].texture = objects[i]->texture; _objects[i].color.x = objects[i]->color.x; _objects[i].color.y = objects[i]->color.y; _objects[i].color.z = objects[i]->color.z; _objects[i].emission.x = objects[i]->emissive.x; _objects[i].emission.y = objects[i]->emissive.y; _objects[i].emission.z = objects[i]->emissive.z; _objects[i].e0.x = objects[i]->e0.x; _objects[i].e0.y = objects[i]->e0.y; _objects[i].e0.z = objects[i]->e0.z; _objects[i].e1.x = objects[i]->e1.x; _objects[i].e1.y = objects[i]->e1.y; _objects[i].e1.z = objects[i]->e1.z; _objects[i].e2.x = objects[i]->e2.x; _objects[i].e2.y = objects[i]->e2.y; _objects[i].e2.z = objects[i]->e2.z; if (objects[i]->type == PLANE) { _objects[i].normal.x = ((cPlane *)objects[i])->normal.x; _objects[i].normal.y = ((cPlane *)objects[i])->normal.y; _objects[i].normal.z = ((cPlane *)objects[i])->normal.z; _objects[i].point.x = ((cPlane *)objects[i])->point.x; _objects[i].point.y = ((cPlane *)objects[i])->point.y; _objects[i].point.z = ((cPlane *)objects[i])->point.z; } else if (objects[i]->type == SPHERE) { _objects[i].center.x = ((cSphere *)objects[i])->center.x; _objects[i].center.y = ((cSphere *)objects[i])->center.y; _objects[i].center.z = ((cSphere *)objects[i])->center.z; _objects[i].radius = ((cSphere *)objects[i])->radius; bounds.minx = MIN(bounds.minx,_objects[i].center.x-_objects[i].radius); bounds.miny = MIN(bounds.miny,_objects[i].center.y-_objects[i].radius); bounds.minz = MIN(bounds.minz,_objects[i].center.z-_objects[i].radius); bounds.maxx = MAX(bounds.maxx,_objects[i].center.x+_objects[i].radius); bounds.maxy = MAX(bounds.maxy,_objects[i].center.y+_objects[i].radius); bounds.maxz = MAX(bounds.maxz,_objects[i].center.z+_objects[i].radius); } else if (objects[i]->type == TRIANGLE) { _objects[i].p0.x = ((cTriangle *)objects[i])->p0.x; _objects[i].p0.y = ((cTriangle *)objects[i])->p0.y; _objects[i].p0.z = ((cTriangle *)objects[i])->p0.z; _objects[i].p1.x = ((cTriangle *)objects[i])->p1.x; _objects[i].p1.y = ((cTriangle *)objects[i])->p1.y; _objects[i].p1.z = ((cTriangle *)objects[i])->p1.z; _objects[i].p2.x = ((cTriangle *)objects[i])->p2.x; _objects[i].p2.y = ((cTriangle *)objects[i])->p2.y; _objects[i].p2.z = ((cTriangle *)objects[i])->p2.z; _objects[i].n0.x = ((cTriangle *)objects[i])->n0.x; _objects[i].n0.y = ((cTriangle *)objects[i])->n0.y; _objects[i].n0.z = ((cTriangle *)objects[i])->n0.z; _objects[i].n1.x = ((cTriangle *)objects[i])->n1.x; _objects[i].n1.y = ((cTriangle *)objects[i])->n1.y; _objects[i].n1.z = ((cTriangle *)objects[i])->n1.z; _objects[i].n2.x = ((cTriangle *)objects[i])->n2.x; _objects[i].n2.y = ((cTriangle *)objects[i])->n2.y; _objects[i].n2.z = ((cTriangle *)objects[i])->n2.z; _objects[i].n.x = ((cTriangle *)objects[i])->n.x; _objects[i].n.y = ((cTriangle *)objects[i])->n.y; _objects[i].n.z = ((cTriangle *)objects[i])->n.z; bounds.minx = MIN(bounds.minx,_objects[i].p0.x); bounds.miny = MIN(bounds.miny,_objects[i].p0.y); bounds.minz = MIN(bounds.minz,_objects[i].p0.z); bounds.maxx = MAX(bounds.maxx,_objects[i].p0.x); bounds.maxy = MAX(bounds.maxy,_objects[i].p0.y); bounds.maxz = MAX(bounds.maxz,_objects[i].p0.z); bounds.minx = MIN(bounds.minx,_objects[i].p1.x); bounds.miny = MIN(bounds.miny,_objects[i].p1.y); bounds.minz = MIN(bounds.minz,_objects[i].p1.z); bounds.maxx = MAX(bounds.maxx,_objects[i].p1.x); bounds.maxy = MAX(bounds.maxy,_objects[i].p1.y); bounds.maxz = MAX(bounds.maxz,_objects[i].p1.z); bounds.minx = MIN(bounds.minx,_objects[i].p2.x); bounds.miny = MIN(bounds.miny,_objects[i].p2.y); bounds.minz = MIN(bounds.minz,_objects[i].p2.z); bounds.maxx = MAX(bounds.maxx,_objects[i].p2.x); bounds.maxy = MAX(bounds.maxy,_objects[i].p2.y); bounds.maxz = MAX(bounds.maxz,_objects[i].p2.z); } } }
[ "klantz81@gmail.com" ]
klantz81@gmail.com
1f078393372649754d9f6ee0472d960558bc93bf
ff8252c5ff6ade3bd533823759aec06ac3c38b7f
/include/linux_parser.h
be6f16728a12a472447a31268625bb1ef42d095e
[]
no_license
LukasLeonardKoening/System-Monitor
b8d8aa350f7efc87b4fee2022ce68524b9e98096
0c5f2f8840dd45666a9de7090ad875f737a283e1
refs/heads/master
2022-04-27T20:59:51.116976
2020-04-30T09:51:12
2020-04-30T09:51:12
259,895,025
0
0
null
null
null
null
UTF-8
C++
false
false
1,206
h
#ifndef SYSTEM_PARSER_H #define SYSTEM_PARSER_H #include <fstream> #include <regex> #include <string> namespace LinuxParser { // Paths const std::string kProcDirectory{"/proc/"}; const std::string kCmdlineFilename{"/cmdline"}; const std::string kCpuinfoFilename{"/cpuinfo"}; const std::string kStatusFilename{"/status"}; const std::string kStatFilename{"/stat"}; const std::string kUptimeFilename{"/uptime"}; const std::string kMeminfoFilename{"/meminfo"}; const std::string kVersionFilename{"/version"}; const std::string kOSPath{"/etc/os-release"}; const std::string kPasswordPath{"/etc/passwd"}; // System float MemoryUtilization(); long UpTime(); std::vector<int> Pids(); int TotalProcesses(); int RunningProcesses(); std::string OperatingSystem(); std::string Kernel(); // CPU enum CPUStates { kUser_ = 0, kNice_, kSystem_, kIdle_, kIOwait_, kIRQ_, kSoftIRQ_, kSteal_, kGuest_, kGuestNice_ }; std::vector<std::string> CpuUtilization(); // Processes std::string Command(int pid); std::string Ram(int pid); std::string Uid(int pid); std::string User(int pid); long int UpTime(int pid); std::vector<std::string> ProcessCpuUtilization(int pid); }; // namespace LinuxParser #endif
[ "llkoening@posteo.de" ]
llkoening@posteo.de
90f35c7275acc76e1fec3da98564604708fcbddc
8e35349e73265a0c20834dc98ad9f64a5e9b173f
/findLine/contours.cpp
4ad5c9f7b23d9b29ee5bac0258f4a39eea9c557e
[]
no_license
EomHyeongGeun/Kobot_Turtlebot
4e4bc1526b77b097dcc8c7469a6fa63faf0e2f97
9da165f35865ad15de2681ca1cb18f99bab19813
refs/heads/master
2021-01-01T16:44:33.234748
2017-07-24T02:23:50
2017-07-24T02:23:50
97,908,604
0
0
null
null
null
null
UTF-8
C++
false
false
1,639
cpp
#ifdef _DEBUG #pragma comment (lib, "opencv_world320d.lib") #else #pragma comment (lib, "opencv_world320.lib") #endif #include <iostream> #include <vector> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/opencv.hpp> #include <stdio.h> #include <unistd.h> #include "linefinder.h" #include "edgedetector.h" #define PI 3.1415926 int main() { // Read input image //cv::Mat image= cv::imread("road.jpg",0); cv::Mat image; cv::VideoCapture cap1(0); //if (!image.data) // return 0; if (!cap1.isOpened()) { std::cerr << "ERROR! Unable to open camera1\n"; return -1; } for(;;){ cap1.read(image); //sleep(10); // Display the image cv::namedWindow("Original Image"); // cv::imshow("Original Image",image); // Compute Sobel EdgeDetector ed; if(!image.empty()) { ed.computeSobel(image); } // Apply Canny algorithm //cv::Mat contours; //cv::Canny(image,contours,125,350); // Create LineFinder instance //LineFinder ld; // Set probabilistic Hough parameters //ld.setLineLengthAndGap(100,20); //ld.setMinVote(60); // Detect lines //std::vector<cv::Vec4i> li= ld.findLines(contours); // eliminate inconsistent lines // ld.removeLinesOfInconsistentOrientations(ed.getOrientation(),0.4,0.1); //image= cv::imread("road.jpg"); //ld.drawDetectedLines(image); cv::namedWindow("Detected Lines (2)"); if(!image.empty()) { cv::imshow("Detected Lines (2)",image); } cv::waitKey(); } return 0; }
[ "eom2390@naver.com" ]
eom2390@naver.com
4340e51cf2ad056a6e4e671ae0cf99fa5aa6e895
465e13df1af3c91319fd6961074addc18dad2937
/src/Test.cpp
e4ed992dda8a5105cd377b252a89ac812ef5c462
[]
no_license
RichardBrosius/MC_Sphere
8ae364ed91fab0258d81946b68d39da408b6f039
9a2e53e7ae168ee543d5e2cbca3865bd9ce200cf
refs/heads/master
2023-04-16T22:03:19.440816
2016-09-03T21:12:13
2016-09-03T21:12:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
98
cpp
#include "Test.h" Test::Test(void) :Number (11) {} double Test::Function(int) { return 2.0; }
[ "chich36@gmail.com" ]
chich36@gmail.com
19e501ed3e3034bb1ad7809cf1176dd4096d7049
9d6947462a91a1bd5e73af40db3b75d8eb4b53db
/hw0/Graph-24916.hpp
4fe7efc49d71747c298a275aba000845adf05e5d
[]
no_license
lalyman/peercode
5081c6edb4a50d3d80105674ad03a08706839a89
46753e2f561a62a11bc9f1ef0ec8823533218144
refs/heads/master
2020-03-11T01:06:24.081274
2018-03-10T23:05:50
2018-03-10T23:05:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,403
hpp
#ifndef CME212_GRAPH_HPP #define CME212_GRAPH_HPP //I was commiting and forgot to actually push until 3:31...hope that is ok /** @file Graph.hpp * @brief An undirected graph type */ #include <algorithm> #include <vector> #include <cassert> #include "CME212/Util.hpp" #include "CME212/Point.hpp" /** @class Graph * @brief A template for 3D undirected graphs. * * Users can add and retrieve nodes and edges. Edges are unique (there is at * most one edge between any pair of distinct nodes). */ class Graph { private: // HW0: YOUR CODE HERE // Use this space for declarations of important internal types you need // later in the Graph's definition. // (As with all the "YOUR CODE HERE" markings, you may not actually NEED // code here. Just use the space if you need it.) public: // // PUBLIC TYPE DEFINITIONS // /** Type of this graph. */ using graph_type = Graph; /** Predeclaration of Node type. */ class Node; /** Synonym for Node (following STL conventions). */ using node_type = Node; /** Predeclaration of Edge type. */ class Edge; /** Synonym for Edge (following STL conventions). */ using edge_type = Edge; /** Type of indexes and sizes. Return type of Graph::Node::index(), Graph::num_nodes(), Graph::num_edges(), and argument type of Graph::node(size_type) */ using size_type = unsigned; // // CONSTRUCTORS AND DESTRUCTOR // /** Construct an empty graph. */ Graph() { // HW0: YOUR CODE HERE } /** Default destructor */ ~Graph() = default; // // NODES // /** @class Graph::Node * @brief Class representing the graph's nodes. * * Node objects are used to access information about the Graph's nodes. */ class Node { public: /** Construct an invalid node. * * Valid nodes are obtained from the Graph class, but it * is occasionally useful to declare an @i invalid node, and assign a * valid node to it later. For example: * * @code * Graph::node_type x; * if (...should pick the first node...) * x = graph.node(0); * else * x = some other node using a complicated calculation * do_something(x); * @endcode */ Node() { // HW0: YOUR CODE HERE } /** Return this node's position. */ const Point& position() const { // HW0: YOUR CODE HERE return m_graph->get_node_point(m_index); } /** Return this node's index, a number in the range [0, graph_size). */ size_type index() const { // HW0: YOUR CODE HERE return m_index; } /** Test whether this node and @a n are equal. * * Equal nodes have the same graph and the same index. */ bool operator==(const Node& n) const { // HW0: YOUR CODE HERE return (m_graph->index() == n.m_graph->index() && m_index == n.m_index); } /** Test whether this node is less than @a n in a global order. * * This ordering function is useful for STL containers such as * std::map<>. It need not have any geometric meaning. * * The node ordering relation must obey trichotomy: For any two nodes x * and y, exactly one of x == y, x < y, and y < x is true. */ bool operator<(const Node& n) const { // HW0: YOUR CODE HERE if (m_graph->index() != n.m_graph->index()) return (m_graph->index() < n.m_graph->index()); else return (m_index < n.m_index); } private: // Allow Graph to access Node's private member data and functions. friend class Graph; size_type m_index; Graph* m_graph; // HW0: YOUR CODE HERE // Use this space to declare private data members and methods for Node // that will not be visible to users, but may be useful within Graph. // i.e. Graph needs a way to construct valid Node objects }; /** Return the number of nodes in the graph. * * Complexity: O(1). */ size_type size() const { // HW0: YOUR CODE HERE return m_nodes.size(); } /** Synonym for size(). */ size_type num_nodes() const { return size(); } /** Add a node to the graph, returning the added node. * @param[in] position The new node's position * @post new num_nodes() == old num_nodes() + 1 * @post result_node.index() == old num_nodes() * * Complexity: O(1) amortized operations. */ Node add_node(const Point& position) { // HW0: YOUR CODE HERE m_nodes.push_back(position); node = Node(); node.m_index = this->size()-1 ; node.m_graph = this; return node; } /** Determine if a Node belongs to this Graph * @return True if @a n is currently a Node of this Graph * * Complexity: O(1). */ bool has_node(const Node& n) const { // HW0: YOUR CODE HERE return (n.m_graph == this); } /** Return the node with index @a i. * @pre 0 <= @a i < num_nodes() * @post result_node.index() == i * * Complexity: O(1). */ Node node(size_type i) const { // HW0: YOUR CODE HERE node = Node(); node.m_index = this->size()-1; node.m_graph = this; return node; } // // EDGES // /** @class Graph::Edge * @brief Class representing the graph's edges. * * Edges are order-insensitive pairs of nodes. Two Edges with the same nodes * are considered equal if they connect the same nodes, in either order. */ class Edge { public: /** Construct an invalid Edge. */ Edge() { // HW0: YOUR CODE HERE } /** Return a node of this Edge */ Node node1() const { // HW0: YOUR CODE HERE return m_graph*.get_edge_node(m_index,0); } /** Return the other node of this Edge */ Node node2() const { // HW0: YOUR CODE HERE return m_graph*.get_edge_node(m_index,1); } /** Test whether this edge and @a e are equal. * * Equal edges represent the same undirected edge between two nodes. */ bool operator==(const Edge& e) const { return (m_graph->index() == e.m_graph->index() && m_index == e.m_index); } /** Test whether this edge is less than @a e in a global order. * * This ordering function is useful for STL containers such as * std::map<>. It need not have any interpretive meaning. */ bool operator<(const Edge& e) const { if (m_graph->index() != e.m_graph->index()) return (m_graph->index() < e.m_graph->index()); else return (m_index < e.m_index); } private: // Allow Graph to access Edge's private member data and functions. friend class Graph; // HW0: YOUR CODE HERE graph_type* m_graph; size_type m_index; // Use this space to declare private data members and methods for Edge // that will not be visible to users, but may be useful within Graph. // i.e. Graph needs a way to construct valid Edge objects }; /** Return the total number of edges in the graph. * * Complexity: No more than O(num_nodes() + num_edges()), hopefully less */ size_type num_edges() const { // HW0: YOUR CODE HERE return m_edges.size(); } /** Return the edge with index @a i. * @pre 0 <= @a i < num_edges() * * Complexity: No more than O(num_nodes() + num_edges()), hopefully less */ Edge edge(size_type i) const { // HW0: YOUR CODE HERE assert( 0<= i && i < this->num_edges() ); edge = Edge(); edge.m_index = i; edge.m_graph = this; return edge; } /** Test whether two nodes are connected by an edge. * @pre @a a and @a b are valid nodes of this graph * @return True if for some @a i, edge(@a i) connects @a a and @a b. * * Complexity: No more than O(num_nodes() + num_edges()), hopefully less */ bool has_edge(const Node& a, const Node& b) const { // HW0: YOUR CODE HERE assert( a.m_graph.index() == this->index() && b.m_graph.index() == this->index() ); if (a.m_index < b.m_index ) for (i=0; i < this->num_edges(); i++) if (m_edges[i][0].m_index == a.m_index && m_edges[i][1].m_index == b.m_index) return true; return false; } /** Add an edge to the graph, or return the current edge if it already exists. * @pre @a a and @a b are distinct valid nodes of this graph * @return an Edge object e with e.node1() == @a a and e.node2() == @a b * @post has_edge(@a a, @a b) == true * @post If old has_edge(@a a, @a b), new num_edges() == old num_edges(). * Else, new num_edges() == old num_edges() + 1. * * Can invalidate edge indexes -- in other words, old edge(@a i) might not * equal new edge(@a i). Must not invalidate outstanding Edge objects. * * Complexity: No more than O(num_nodes() + num_edges()), hopefully less */ Edge add_edge(const Node& a, const Node& b) { // HW0: YOUR CODE HERE edge = Edge(); edge.m_graph = this; if (this->has_edge(a,b) == true) for (i=0; i < this->num_edges(); i++) if (m_edges[i][0].m_index == a.m_index && m_edges[i][1].m_index == b.m_index) edge.m_index = i; else if (m_edges[i][0].m_index == b.m_index && m_edges[i][1].m_index == a.m_index) edge.m_index = i; else // this if/else ensures that edges are always written // in the convention of the smaller node index coming first if (a.index < b.index) m_edges.push_back(std::vector<node_type> {a,b}); else m_edges.push_back(std::vector<node_type> {b,a}); edge.m_index = this->num_edges-1; return edge; } /** Remove all nodes and edges from this graph. * @post num_nodes() == 0 && num_edges() == 0 * * Invalidates all outstanding Node and Edge objects. */ void clear() { // HW0: YOUR CODE HERE m_edges.clear(); m_nodes.clear(); } private: std::vector<Point> m_nodes; std::vector< std::vector<size_type> > m_edges; Point get_node_point(size_type index) { return m_nodes[index] } node_type get_edge_node(size_type index, int num) { return m_edges[index][num] } // HW0: YOUR CODE HERE // Use this space for your Graph class's internals: // helper functions, data members, and so forth. }; #endif // CME212_GRAPH_HPP
[ "clazarus@rice13.stanford.edu" ]
clazarus@rice13.stanford.edu
32932e226dd8b7d8751ee20984219ed7eec77e9d
e8aea07d894505d0d8a04cdf8efab57f889ee690
/naesala/common/barrier.h
b18cc384a7cb4f1e3dfaddf8374e1aa5e238d557
[ "BSD-3-Clause" ]
permissive
vorfeed/naesala
2ccb69943cc4ee023a243a645f197a93dbb1682f
f2f46cb264a924c013303c0aacd2a8ac11f84e3f
refs/heads/master
2021-01-17T08:58:09.359305
2016-03-30T11:10:58
2016-03-30T11:10:58
20,612,195
3
1
null
null
null
null
UTF-8
C++
false
false
912
h
// Copyright 2014, Xiaojie Chen (swly@live.com). All rights reserved. // https://github.com/vorfeed/naesala // // Use of this source code is governed by a BSD-style license // that can be found in the License file. #pragma once #include <assert.h> #include <mutex> #include <condition_variable> #include <boost/noncopyable.hpp> namespace naesala { class Barrier : boost::noncopyable { public: explicit Barrier(uint32_t parties) : _parties(parties) { assert(_parties > 0); } void await() { MutexGuard mg(_mutex); --_parties; if (!_parties) { _cond.notify_all(); return; } _cond.wait(mg, [this] {return _parties == 0;}); assert(!_parties); } private: typedef std::unique_lock<std::mutex> MutexGuard; uint32_t _parties; std::mutex _mutex; std::condition_variable _cond; }; } // namespace naesala
[ "swly@live.com" ]
swly@live.com
3677441a1aa85b4a29fe3e90254bb47dbe3b6733
09f09cd06656848ed80f132c7073568c4ce87bd5
/CBIR/Retrieval/IP.cpp
d0305a35b44b152daa8b9894ce9c0b5cb1d957eb
[]
no_license
cyb3727/annrecognition
90ecf3af572f8b629b276a06af51785f656ca2be
6e4f200e1119196eba5e7fe56efa93e3ed978bc1
refs/heads/master
2021-01-17T11:31:39.865232
2011-07-10T13:50:44
2011-07-10T13:50:44
null
0
0
null
null
null
null
GB18030
C++
false
false
51,719
cpp
#include "stdafx.h" #include <math.h> #include "dibapi.h" // Definitions required for convolution image filtering #define KERNELCOLS 3 #define KERNELROWS 3 #define KERNELELEMENTS (KERNELCOLS * KERNELROWS) // struct for convolute kernel typedef struct { int Element[KERNELELEMENTS]; int Divisor; } KERNEL; // The following kernel definitions are for convolution filtering. // Kernel entries are specified with a divisor to get around the // requirement for floating point numbers in the low pass filters. KERNEL HP1 = { // HP filter #1 {-1, -1, -1, -1, 9, -1, -1, -1, -1}, 1 // Divisor = 1 }; KERNEL HP2 = { // HP filter #2 { 0, -1, 0, -1, 5, -1, 0, -1, 0}, 1 // Divisor = 1 }; KERNEL HP3 = { // HP filter #3 { 1, -2, 1, -2, 5, -2, 1, -2, 1}, 1 // Divisor = 1 }; KERNEL LP1 = { // LP filter #1 { 1, 1, 1, 1, 1, 1, 1, 1, 1}, 9 // Divisor = 9 }; KERNEL LP2 = { // LP filter #2 { 1, 1, 1, 1, 2, 1, 1, 1, 1}, 10 // Divisor = 10 }; KERNEL LP3 = { // LP filter #3 { 1, 2, 1, 2, 4, 2, 1, 2, 1}, 16 // Divisor = 16 }; KERNEL VertEdge = { // Vertical edge { 0, 0, 0, -1, 1, 0, 0, 0, 0}, 1 // Divisor = 1 }; KERNEL HorzEdge = { // Horizontal edge { 0, -1, 0, 0, 1, 0, 0, 0, 0}, 1 // Divisor = 1 }; KERNEL VertHorzEdge = { // Vertical Horizontal edge { -1, 0, 0, 0, 1, 0, 0, 0, 0}, 1 // Divisor = 1 }; KERNEL EdgeNorth = { // North gradient { 1, 1, 1, 1, -2, 1, -1, -1, -1}, 1 // Divisor = 1 }; KERNEL EdgeNorthEast = { // North East gradient { 1, 1, 1, -1, -2, 1, -1, -1, 1}, 1 // Divisor = 1 }; KERNEL EdgeEast = { // East gradient {-1, 1, 1, -1, -2, 1, -1, 1, 1}, 1 // Divisor = 1 }; KERNEL EdgeSouthEast = { // South East gradient {-1, -1, 1, -1, -2, 1, 1, 1, 1}, 1 // Divisor = 1 }; KERNEL EdgeSouth = { // South gadient {-1, -1, -1, 1, -2, 1, 1, 1, 1}, 1 // Divisor = 1 }; KERNEL EdgeSouthWest = { // South West gradient { 1, -1, -1, 1, -2, -1, 1, 1, 1}, 1 // Divisor = 1 }; KERNEL EdgeWest = { // West gradient { 1, 1, -1, 1, -2, -1, 1, 1, -1}, 1 // Divisor = 1 }; KERNEL EdgeNorthWest = { // North West gradient { 1, 1, 1, 1, -2, -1, 1, -1, -1}, 1 // Divisor = 1 }; KERNEL Lap1 = { // Laplace filter 1 { 0, 1, 0, 1, -4, 1, 0, 1, 0}, 1 // Divisor = 1 }; KERNEL Lap2 = { // Laplace filter 2 { -1, -1, -1, -1, 8, -1, -1, -1, -1}, 1 // Divisor = 1 }; KERNEL Lap3 = { // Laplace filter 3 { -1, -1, -1, -1, 9, -1, -1, -1, -1}, 1 // Divisor = 1 }; KERNEL Lap4 = { // Laplace filter 4 { 1, -2, 1, -2, 4, -2, 1, -2, 1}, 1 // Divisor = 1 }; KERNEL Sobel[4] = { { // Sobel1 {-1, 0, 1, -2, 0, 2, -1, 0, 1}, 1 // Divisor = 1 }, { // Sobel2 {-1, -2, -1, 0, 0, 0, 1, 2, 1}, 1 // Divisor = 1 }, { // Sobel3 {-2, -1, 0, -1, 0, 1, 0, 1, 2}, 1 // Divisor = 1 }, { // Sobel4 {0, -1, -2, 1, 0, -1, 2, 1, 0}, 1 // Divisor = 1 } }; KERNEL Hough[4] = { { // Hough1 {-1, 0, 1, -1, 0, 1, -1, 0, 1}, 1 // Divisor = 1 }, { // Hough2 {-1, -1, 0, -1, 0, 1, 0, 1, 1}, 1 // Divisor = 1 }, { // Hough3 {-1, -1, -1, 0, 0, 0, 1, 1, 1}, 1 // Divisor = 1 }, { // Hough4 {0, -1, -1, 1, 0, -1, 1, 1, 0}, 1 // Divisor = 1 } }; // local use macro #define PIXEL_OFFSET(i, j, nWidthBytes) \ (LONG)((LONG)(i)*(LONG)(nWidthBytes) + (LONG)(j)*3) // local function prototype int compare(const void *e1, const void *e2); void DoMedianFilterDIB(int *red, int *green, int *blue, int i, int j, WORD wBytesPerLine, LPBYTE lpDIBits); void DoConvoluteDIB(int *red, int *green, int *blue, int i, int j, WORD wBytesPerLine, LPBYTE lpDIBits, KERNEL *lpKernel); BOOL ConvoluteDIB(HDIB hDib, KERNEL *lpKernel, int Strength, int nKernelNum=1); // function body /************************************************************************* * * HighPassDIB() * * Parameters: * * HDIB hDib - objective DIB handle * int nAlgorithm - specify the filter to use * int Strength - operation strength set to the convolute * * Return Value: * * BOOL - True is success, else False * * Description: * * High pass filtering to sharp DIB * ************************************************************************/ BOOL HighPassDIB(HDIB hDib, int Strength, int nAlgorithm) { switch (nAlgorithm) { case FILTER1: return ConvoluteDIB(hDib, &HP1, Strength); case FILTER2: return ConvoluteDIB(hDib, &HP2, Strength); case FILTER3: return ConvoluteDIB(hDib, &HP3, Strength); } return FALSE; } /************************************************************************* * * LowPassDIB() * * Parameters: * * HDIB hDib - objective DIB handle * int nAlgorithm - specify the filter to use * int Strength - operation strength set to the convolute * * Return Value: * * BOOL - True is success, else False * * Description: * * Low pass filtering to blur DIB * ************************************************************************/ BOOL LowPassDIB(HDIB hDib, int Strength, int nAlgorithm) { switch (nAlgorithm) { case FILTER1: return ConvoluteDIB(hDib, &LP1, Strength); case FILTER2: return ConvoluteDIB(hDib, &LP2, Strength); case FILTER3: return ConvoluteDIB(hDib, &LP3, Strength); } return FALSE; } /************************************************************************* * * EdgeEnhanceDIB() * * Parameters: * * HDIB hDib - objective DIB handle * int nAlgorithm - specify the filter to use * int Strength - operation strength set to the convolute * * Return Value: * * BOOL - True is success, else False * * Description: * * Edge enhance DIB * ************************************************************************/ BOOL EdgeEnhanceDIB(HDIB hDib, int Strength, int nAlgorithm) { switch (nAlgorithm) { case VERT: return ConvoluteDIB(hDib, &VertEdge, Strength); case HORZ: return ConvoluteDIB(hDib, &HorzEdge, Strength); case VERTHORZ: return ConvoluteDIB(hDib, &VertHorzEdge, Strength); case NORTH: return ConvoluteDIB(hDib, &EdgeNorth, Strength); case NORTHEAST: return ConvoluteDIB(hDib, &EdgeNorthEast, Strength); case EAST: return ConvoluteDIB(hDib, &EdgeEast, Strength); case SOUTH: return ConvoluteDIB(hDib, &EdgeSouth, Strength); case SOUTHEAST: return ConvoluteDIB(hDib, &EdgeSouthEast, Strength); case SOUTHWEST: return ConvoluteDIB(hDib, &EdgeSouthWest, Strength); case WEST: return ConvoluteDIB(hDib, &EdgeWest, Strength); case NORTHWEST: return ConvoluteDIB(hDib, &EdgeNorthWest, Strength); case LAP1: return ConvoluteDIB(hDib, &Lap1, Strength); case LAP2: return ConvoluteDIB(hDib, &Lap2, Strength); case LAP3: return ConvoluteDIB(hDib, &Lap3, Strength); case LAP4: return ConvoluteDIB(hDib, &Lap4, Strength); case SOBEL: return ConvoluteDIB(hDib, Sobel, Strength, 4); case HOUGH: return ConvoluteDIB(hDib, Hough, Strength, 4); } return FALSE; } /************************************************************************* * * MedianFilterDIB() * * Parameters: * * HDIB hDib - objective DIB handle * * Return Value: * * BOOL - True is success, else False * * Description: * * This is the media filtering function to DIB * ************************************************************************/ BOOL MedianFilterDIB(HDIB hDib) { WaitCursorBegin(); HDIB hNewDib = NULL; // we only convolute 24bpp DIB, so first convert DIB to 24bpp WORD wBitCount = DIBBitCount(hDib); if (wBitCount != 24) hNewDib = ConvertDIBFormat(hDib, 24, NULL); else hNewDib = CopyHandle(hDib); if (! hNewDib) { WaitCursorEnd(); return FALSE; } // new DIB attributes WORD wDIBWidth = (WORD)DIBWidth(hNewDib); WORD wDIBHeight = (WORD)DIBHeight(hNewDib); WORD wBytesPerLine = (WORD)BytesPerLine(hNewDib); DWORD dwImageSize = wBytesPerLine * wDIBHeight; // Allocate and lock memory for filtered image data HGLOBAL hFilteredBits = GlobalAlloc(GHND, dwImageSize); if (!hFilteredBits) { WaitCursorEnd(); return FALSE; } LPBYTE lpDestImage = (LPBYTE)GlobalLock(hFilteredBits); // get bits address in DIB LPBYTE lpDIB = (LPBYTE)GlobalLock(hNewDib); LPBYTE lpDIBits = FindDIBBits(lpDIB); // convolute... for (int i=1; i<wDIBHeight-1; i++) for (int j=1; j<wDIBWidth-1; j++) { int red=0, green=0, blue=0; DoMedianFilterDIB(&red, &green, &blue, i, j, wBytesPerLine, lpDIBits); LONG lOffset= PIXEL_OFFSET(i,j, wBytesPerLine); *(lpDestImage + lOffset++) = BOUND(blue, 0, 255); *(lpDestImage + lOffset++) = BOUND(green, 0, 255); *(lpDestImage + lOffset) = BOUND(red, 0, 255); } // a filtered image is available in lpDestImage // copy it to DIB bits memcpy(lpDIBits, lpDestImage, dwImageSize); // cleanup temp buffers GlobalUnlock(hFilteredBits); GlobalFree(hFilteredBits); GlobalUnlock(hNewDib); // rebuild hDib HDIB hTmp = NULL; if (wBitCount != 24) hTmp = ConvertDIBFormat(hNewDib, wBitCount, NULL); else hTmp = CopyHandle(hNewDib); GlobalFree(hNewDib); DWORD dwSize = GlobalSize(hTmp); memcpy((LPBYTE)GlobalLock(hDib), (LPBYTE)GlobalLock(hTmp), dwSize); GlobalUnlock(hTmp); GlobalFree(hTmp); GlobalUnlock(hDib); WaitCursorEnd(); return TRUE; } /************************************************************************* * * ConvoluteDIB() * * Parameters: * * HDIB hDib - objective DIB handle * KERNEL *lpKernel - pointer of kernel used to convolute with DIB * int Strength - operation strength set to the convolute * int nKernelNum - kernel number used to convolute * * Return Value: * * BOOL - True is success, else False * * Description: * * This is the generic convolute function to DIB * ************************************************************************/ BOOL ConvoluteDIB(HDIB hDib, KERNEL *lpKernel, int Strength, int nKernelNum) { WaitCursorBegin(); HDIB hNewDib = NULL; // we only convolute 24bpp DIB, so first convert DIB to 24bpp WORD wBitCount = DIBBitCount(hDib); if (wBitCount != 24) hNewDib = ConvertDIBFormat(hDib, 24, NULL); else hNewDib = CopyHandle(hDib); if (! hNewDib) { WaitCursorEnd(); return FALSE; } // new DIB attributes WORD wDIBWidth = (WORD)DIBWidth(hNewDib); WORD wDIBHeight = (WORD)DIBHeight(hNewDib); WORD wBytesPerLine = (WORD)BytesPerLine(hNewDib); DWORD dwImageSize = wBytesPerLine * wDIBHeight; // Allocate and lock memory for filtered image data HGLOBAL hFilteredBits = GlobalAlloc(GHND, dwImageSize); if (!hFilteredBits) { WaitCursorEnd(); return FALSE; } LPBYTE lpDestImage = (LPBYTE)GlobalLock(hFilteredBits); // get bits address in DIB LPBYTE lpDIB = (LPBYTE)GlobalLock(hNewDib); LPBYTE lpDIBits = FindDIBBits(lpDIB); // convolute... for (int i=1; i<wDIBHeight-1; i++) for (int j=1; j<wDIBWidth-1; j++) { int red=0, green=0, blue=0; for (int k=0; k<nKernelNum; ++k) { int r=0, g=0, b=0; DoConvoluteDIB(&r, &g, &b, i, j, wBytesPerLine, lpDIBits, lpKernel+k); if (r > red) red = r; if (g > green) green = g; if (b > blue) blue = b; //red += r; green += g; blue += b; } // original RGB value in center pixel (j, i) LONG lOffset= PIXEL_OFFSET(i,j, wBytesPerLine); BYTE OldB = *(lpDIBits + lOffset++); BYTE OldG = *(lpDIBits + lOffset++); BYTE OldR = *(lpDIBits + lOffset); // When we get here, red, green and blue have the new RGB value. if (Strength != 10) { // Interpolate pixel data red = OldR + (((red - OldR) * Strength) / 10); green = OldG + (((green - OldG) * Strength) / 10); blue = OldB + (((blue - OldB) * Strength) / 10); } lOffset= PIXEL_OFFSET(i,j, wBytesPerLine); *(lpDestImage + lOffset++) = BOUND(blue, 0, 255); *(lpDestImage + lOffset++) = BOUND(green, 0, 255); *(lpDestImage + lOffset) = BOUND(red, 0, 255); } // a filtered image is available in lpDestImage // copy it to DIB bits memcpy(lpDIBits, lpDestImage, dwImageSize); // cleanup temp buffers GlobalUnlock(hFilteredBits); GlobalFree(hFilteredBits); GlobalUnlock(hNewDib); // rebuild hDib HDIB hTmp = NULL; if (wBitCount != 24) hTmp = ConvertDIBFormat(hNewDib, wBitCount, NULL); else hTmp = CopyHandle(hNewDib); GlobalFree(hNewDib); DWORD dwSize = GlobalSize(hTmp); memcpy((LPBYTE)GlobalLock(hDib), (LPBYTE)GlobalLock(hTmp), dwSize); GlobalUnlock(hTmp); GlobalFree(hTmp); GlobalUnlock(hDib); WaitCursorEnd(); return TRUE; } // local function: perform convolution to DIB with a kernel void DoConvoluteDIB(int *red, int *green, int *blue, int i, int j, WORD wBytesPerLine, LPBYTE lpDIBits, KERNEL *lpKernel) { BYTE b[9], g[9], r[9]; LONG lOffset; lOffset= PIXEL_OFFSET(i-1,j-1, wBytesPerLine); b[0] = *(lpDIBits + lOffset++); g[0] = *(lpDIBits + lOffset++); r[0] = *(lpDIBits + lOffset); lOffset= PIXEL_OFFSET(i-1,j, wBytesPerLine); b[1] = *(lpDIBits + lOffset++); g[1] = *(lpDIBits + lOffset++); r[1] = *(lpDIBits + lOffset); lOffset= PIXEL_OFFSET(i-1,j+1, wBytesPerLine); b[2] = *(lpDIBits + lOffset++); g[2] = *(lpDIBits + lOffset++); r[2] = *(lpDIBits + lOffset); lOffset= PIXEL_OFFSET(i,j-1, wBytesPerLine); b[3] = *(lpDIBits + lOffset++); g[3] = *(lpDIBits + lOffset++); r[3] = *(lpDIBits + lOffset); lOffset= PIXEL_OFFSET(i,j, wBytesPerLine); b[4] = *(lpDIBits + lOffset++); g[4] = *(lpDIBits + lOffset++); r[4] = *(lpDIBits + lOffset); lOffset= PIXEL_OFFSET(i,j+1, wBytesPerLine); b[5] = *(lpDIBits + lOffset++); g[5] = *(lpDIBits + lOffset++); r[5] = *(lpDIBits + lOffset); lOffset= PIXEL_OFFSET(i+1,j-1, wBytesPerLine); b[6] = *(lpDIBits + lOffset++); g[6] = *(lpDIBits + lOffset++); r[6] = *(lpDIBits + lOffset); lOffset= PIXEL_OFFSET(i+1,j, wBytesPerLine); b[7] = *(lpDIBits + lOffset++); g[7] = *(lpDIBits + lOffset++); r[7] = *(lpDIBits + lOffset); lOffset= PIXEL_OFFSET(i+1,j+1, wBytesPerLine); b[8] = *(lpDIBits + lOffset++); g[8] = *(lpDIBits + lOffset++); r[8] = *(lpDIBits + lOffset); *red = *green = *blue = 0; for (int k=0; k<8; ++k) { *red += lpKernel->Element[k]*r[k]; *green += lpKernel->Element[k]*g[k]; *blue += lpKernel->Element[k]*b[k]; } if (lpKernel->Divisor != 1) { *red /= lpKernel->Divisor; *green /= lpKernel->Divisor; *blue /= lpKernel->Divisor; } // getoff opposite *red = abs(*red); *green = abs(*green); *blue = abs(*blue); } // local function: perform median filter to DIB void DoMedianFilterDIB(int *red, int *green, int *blue, int i, int j, WORD wBytesPerLine, LPBYTE lpDIBits) { BYTE b[9], g[9], r[9]; LONG lOffset; lOffset= PIXEL_OFFSET(i-1,j-1, wBytesPerLine); b[0] = *(lpDIBits + lOffset++); g[0] = *(lpDIBits + lOffset++); r[0] = *(lpDIBits + lOffset); lOffset= PIXEL_OFFSET(i-1,j, wBytesPerLine); b[1] = *(lpDIBits + lOffset++); g[1] = *(lpDIBits + lOffset++); r[1] = *(lpDIBits + lOffset); lOffset= PIXEL_OFFSET(i-1,j+1, wBytesPerLine); b[2] = *(lpDIBits + lOffset++); g[2] = *(lpDIBits + lOffset++); r[2] = *(lpDIBits + lOffset); lOffset= PIXEL_OFFSET(i,j-1, wBytesPerLine); b[3] = *(lpDIBits + lOffset++); g[3] = *(lpDIBits + lOffset++); r[3] = *(lpDIBits + lOffset); lOffset= PIXEL_OFFSET(i,j, wBytesPerLine); b[4] = *(lpDIBits + lOffset++); g[4] = *(lpDIBits + lOffset++); r[4] = *(lpDIBits + lOffset); lOffset= PIXEL_OFFSET(i,j+1, wBytesPerLine); b[5] = *(lpDIBits + lOffset++); g[5] = *(lpDIBits + lOffset++); r[5] = *(lpDIBits + lOffset); lOffset= PIXEL_OFFSET(i+1,j-1, wBytesPerLine); b[6] = *(lpDIBits + lOffset++); g[6] = *(lpDIBits + lOffset++); r[6] = *(lpDIBits + lOffset); lOffset= PIXEL_OFFSET(i+1,j, wBytesPerLine); b[7] = *(lpDIBits + lOffset++); g[7] = *(lpDIBits + lOffset++); r[7] = *(lpDIBits + lOffset); lOffset= PIXEL_OFFSET(i+1,j+1, wBytesPerLine); b[8] = *(lpDIBits + lOffset++); g[8] = *(lpDIBits + lOffset++); r[8] = *(lpDIBits + lOffset); qsort(r, 9, 1, compare); qsort(g, 9, 1, compare); qsort(b, 9, 1, compare); *red = r[0]; *green = g[0]; *blue = b[0]; } // function used to sort in the call of qsort int compare(const void *e1, const void *e2) { if (*(BYTE *)e1 < *(BYTE *)e2) return -1; if (*(BYTE *)e1 > *(BYTE *)e2) return 1; return 0; } /************************************************************************* * * ReverseDIB() * * Parameters: * * HDIB hDib - objective DIB handle * * Return Value: * * BOOL - True is success, else False * * Description: * * This function reverse DIB * ************************************************************************/ BOOL ReverseDIB(HDIB hDib) { WaitCursorBegin(); HDIB hNewDib = NULL; // only support 256 grayscale image WORD wBitCount = DIBBitCount(hDib); if (wBitCount != 8) { WaitCursorEnd(); return FALSE; } // the maxium pixel value int nMaxValue = 256; // source pixel data LPBITMAPINFO lpSrcDIB = (LPBITMAPINFO)GlobalLock(hDib); if (! lpSrcDIB) { WaitCursorBegin(); return FALSE; } // new DIB attributes LPSTR lpPtr; LONG lHeight = DIBHeight(lpSrcDIB); LONG lWidth = DIBWidth(lpSrcDIB); DWORD dwBufferSize = GlobalSize(lpSrcDIB); int nLineBytes = BytesPerLine(lpSrcDIB); // convolute... for (long i=0; i<lHeight; i++) for (long j=0; j<lWidth; j++) { lpPtr=(char *)lpSrcDIB+(dwBufferSize-nLineBytes-i*nLineBytes)+j; *lpPtr = nMaxValue - *lpPtr; } // cleanup GlobalUnlock(hDib); WaitCursorEnd(); return TRUE; } /************************************************************************* * * ErosionDIB() * * Parameters: * * HDIB hDib - objective DIB handle * BOOL bHori - erosion direction * * Return Value: * * BOOL - True is success, else False * * Description: * * This function do erosion with the specified direction * ************************************************************************/ BOOL ErosionDIB(HDIB hDib, BOOL bHori) { // start wait cursor WaitCursorBegin(); // Old DIB buffer if (hDib == NULL) { WaitCursorEnd(); return FALSE; } // only support 256 color image WORD wBitCount = DIBBitCount(hDib); if (wBitCount != 8) { WaitCursorEnd(); return FALSE; } // new DIB HDIB hNewDIB = CopyHandle(hDib); if (! hNewDIB) { WaitCursorEnd(); return FALSE; } // source dib buffer LPBITMAPINFO lpSrcDIB = (LPBITMAPINFO)GlobalLock(hDib); if (! lpSrcDIB) { WaitCursorBegin(); return FALSE; } // New DIB buffer LPBITMAPINFO lpbmi = (LPBITMAPINFO)GlobalLock(hNewDIB); if (! lpbmi) { WaitCursorBegin(); return FALSE; } // start erosion... LPSTR lpPtr; LPSTR lpTempPtr; LONG x,y; BYTE num, num0; int i; LONG lHeight = DIBHeight(lpSrcDIB); LONG lWidth = DIBWidth(lpSrcDIB); DWORD dwBufferSize = GlobalSize(lpSrcDIB); int nLineBytes = BytesPerLine(lpSrcDIB); if(bHori) { for (y=0; y<lHeight; y++) { lpPtr=(char *)lpbmi+(dwBufferSize-nLineBytes-y*nLineBytes)+1; lpTempPtr=(char *)lpSrcDIB+(dwBufferSize-nLineBytes-y*nLineBytes)+1; for (x=1; x<lWidth-1; x++) { num0 = num = 0 ; for(i=0;i<3;i++) { num=(unsigned char)*(lpPtr+i-1); if(num > num0) num0 = num; } *lpTempPtr=(unsigned char)num0; /* num=(unsigned char)*lpPtr; if (num==0) { *lpTempPtr=(unsigned char)0; for(i=0;i<3;i++) { num=(unsigned char)*(lpPtr+i-1); if(num==255) { *lpTempPtr=(unsigned char)255; break; } } } else *lpTempPtr=(unsigned char)255; */ lpPtr++; lpTempPtr++; } } } else // Vertical { for (y=1; y<lHeight-1; y++) { lpPtr=(char *)lpbmi+(dwBufferSize-nLineBytes-y*nLineBytes); lpTempPtr=(char *)lpSrcDIB+(dwBufferSize-nLineBytes-y*nLineBytes); for (x=0; x<lWidth; x++) { num0 = num = 0 ; for(i=0;i<3;i++) { num=(unsigned char)*(lpPtr+i-1); if(num > num0) num0 = num; } *lpTempPtr=(unsigned char)num0; /* num=(unsigned char)*lpPtr; if (num==0) { *lpTempPtr=(unsigned char)0; for(i=0;i<3;i++) { num=(unsigned char)*(lpPtr+(i-1)*nLineBytes); if(num==255) { *lpTempPtr=(unsigned char)255; break; } } } else *lpTempPtr=(unsigned char)255; */ lpPtr++; lpTempPtr++; } } } // cleanup GlobalUnlock(hDib); GlobalUnlock(hNewDIB); GlobalFree(hNewDIB); WaitCursorEnd(); return TRUE; } /************************************************************************* * * DilationDIB() * * Parameters: * * HDIB hDib - objective DIB handle * BOOL bHori - dilation direction * * Return Value: * * BOOL - True is success, else False * * Description: * * This function do dilation with the specified direction * ************************************************************************/ BOOL DilationDIB(HDIB hDib, BOOL bHori) { // start wait cursor WaitCursorBegin(); // Old DIB buffer if (hDib == NULL) { WaitCursorEnd(); return FALSE; } // only support 256 color image WORD wBitCount = DIBBitCount(hDib); if (wBitCount != 8) { WaitCursorEnd(); return FALSE; } // new DIB HDIB hNewDIB = CopyHandle(hDib); if (! hNewDIB) { WaitCursorEnd(); return FALSE; } // source dib buffer LPBITMAPINFO lpSrcDIB = (LPBITMAPINFO)GlobalLock(hDib); if (! lpSrcDIB) { WaitCursorBegin(); return FALSE; } // New DIB buffer LPBITMAPINFO lpbmi = (LPBITMAPINFO)GlobalLock(hNewDIB); if (! lpbmi) { WaitCursorBegin(); return FALSE; } // start erosion... LPSTR lpPtr; LPSTR lpTempPtr; LONG x,y; BYTE num, num0; int i; LONG lHeight = DIBHeight(lpSrcDIB); LONG lWidth = DIBWidth(lpSrcDIB); DWORD dwBufferSize = GlobalSize(lpSrcDIB); int nLineBytes = BytesPerLine(lpSrcDIB); if(bHori) { for(y=0;y<lHeight;y++) { lpPtr=(char *)lpbmi+(dwBufferSize-nLineBytes-y*nLineBytes)+1; lpTempPtr=(char *)lpSrcDIB+(dwBufferSize-nLineBytes-y*nLineBytes)+1; for(x=1;x<lWidth-1;x++) { num0 = num = 255; for(i=0;i<3;i++) { num=(unsigned char)*(lpPtr+i-1); if(num < num0) num0 = num; } *lpTempPtr=(unsigned char)num0; /* num=(unsigned char)*lpPtr; if (num==255) { *lpTempPtr=(unsigned char)255; for(i=0;i<3;i++) { num=(unsigned char)*(lpPtr+i-1); if(num==0) { *lpTempPtr=(unsigned char)0; break; } } } else *lpTempPtr=(unsigned char)0; */ lpPtr++; lpTempPtr++; } } } else { for(y=1;y<lHeight-1;y++) { lpPtr=(char *)lpbmi+(dwBufferSize-nLineBytes-y*nLineBytes); lpTempPtr=(char *)lpSrcDIB+(dwBufferSize-nLineBytes-y*nLineBytes); for(x=0;x<lWidth;x++) { num0 = num = 255; for(i=0;i<3;i++) { num=(unsigned char)*(lpPtr+i-1); if(num < num0) num0 = num; } *lpTempPtr=(unsigned char)num0; /* num=(unsigned char)*lpPtr; if (num==255) { *lpTempPtr=(unsigned char)255; for(i=0;i<3;i++) { num=(unsigned char)*(lpPtr+(i-1)*nLineBytes); if(num==0) { *lpTempPtr=(unsigned char)0; break; } } } else *lpTempPtr=(unsigned char)0; */ lpPtr++; lpTempPtr++; } } } // cleanup GlobalUnlock(hDib); GlobalUnlock(hNewDIB); GlobalFree(hNewDIB); WaitCursorEnd(); return TRUE; } /************************************************************************* * * MorphOpenDIB() * * Parameters: * * HDIB hDib - objective DIB handle * BOOL bHori - open direction * * Return Value: * * BOOL - True is success, else False * * Description: * * This function do open with the specified direction * ************************************************************************/ BOOL MorphOpenDIB(HDIB hDib, BOOL bHori) { // Step 1: erosion if (! ErosionDIB(hDib, bHori)) return FALSE; // Step 2: dilation if (! DilationDIB(hDib, bHori)) return FALSE; return TRUE; } /************************************************************************* * * MorphCloseDIB() * * Parameters: * * HDIB hDib - objective DIB handle * BOOL bHori - close direction * * Return Value: * * BOOL - True is success, else False * * Description: * * This function do close with the specified direction * ************************************************************************/ BOOL MorphCloseDIB(HDIB hDib, BOOL bHori) { // Step 1: dilation if (! DilationDIB(hDib, bHori)) return FALSE; // Step 2: erosion if (! ErosionDIB(hDib, bHori)) return FALSE; return TRUE; } /************************************************************************* * * ContourDIB() * * Parameters: * * HDIB hDib - objective DIB handle * BOOL bHori - open direction * * Return Value: * * BOOL - True is success, else False * * Description: * * This function contour DIB with the specified direction * ************************************************************************/ BOOL ContourDIB(HDIB hDib, BOOL bHori) { // start wait cursor WaitCursorBegin(); // Old DIB buffer if (hDib == NULL) { WaitCursorEnd(); return FALSE; } // only support 256 color image WORD wBitCount = DIBBitCount(hDib); if (wBitCount != 8) { WaitCursorEnd(); return FALSE; } // new DIB HDIB hNewDIB = CopyHandle(hDib); if (! hNewDIB) { WaitCursorEnd(); return FALSE; } // source dib buffer LPBITMAPINFO lpSrcDIB = (LPBITMAPINFO)GlobalLock(hDib); if (! lpSrcDIB) { WaitCursorBegin(); return FALSE; } // New DIB buffer LPBITMAPINFO lpbmi = (LPBITMAPINFO)GlobalLock(hNewDIB); if (! lpbmi) { WaitCursorBegin(); return FALSE; } // start erosion... LPBYTE lpPtr; LPBYTE lpTempPtr; LONG x,y; BYTE num, num0; int i; LONG lHeight = DIBHeight(lpSrcDIB); LONG lWidth = DIBWidth(lpSrcDIB); DWORD dwBufferSize = GlobalSize(lpSrcDIB); int nLineBytes = BytesPerLine(lpSrcDIB); // Step 1: erosion if(bHori) { for (y=0; y<lHeight; y++) { lpPtr=(BYTE *)lpSrcDIB+(dwBufferSize-nLineBytes-y*nLineBytes)+1; lpTempPtr=(BYTE *)lpbmi+(dwBufferSize-nLineBytes-y*nLineBytes)+1; for (x=1; x<lWidth-1; x++) { num0 = num = 0 ; for(i=0;i<3;i++) { num=(unsigned char)*(lpPtr+i-1); if(num > num0) num0 = num; } *lpTempPtr=(unsigned char)num0; /* num=(unsigned char)*lpPtr; if (num==0) { *lpTempPtr=(unsigned char)0; for(i=0;i<3;i++) { num=(unsigned char)*(lpPtr+i-1); if(num==255) { *lpTempPtr=(unsigned char)255; break; } } } else *lpTempPtr=(unsigned char)255; */ lpPtr++; lpTempPtr++; } } } else // Vertical { for (y=1; y<lHeight-1; y++) { lpPtr=(BYTE *)lpSrcDIB+(dwBufferSize-nLineBytes-y*nLineBytes); lpTempPtr=(BYTE *)lpbmi+(dwBufferSize-nLineBytes-y*nLineBytes); for (x=0; x<lWidth; x++) { num0 = num = 0 ; for(i=0;i<3;i++) { num=(unsigned char)*(lpPtr+i-1); if(num > num0) num0 = num; } *lpTempPtr=(unsigned char)num0; /* num=(unsigned char)*lpPtr; if (num==0) { *lpTempPtr=(unsigned char)0; for(i=0;i<3;i++) { num=(unsigned char)*(lpPtr+(i-1)*nLineBytes); if(num==255) { *lpTempPtr=(unsigned char)255; break; } } } else *lpTempPtr=(unsigned char)255; */ lpPtr++; lpTempPtr++; } } } // Step 2: original image minues dilation image if(bHori) { for(y=0;y<lHeight;y++) { lpPtr=(BYTE *)lpbmi+(dwBufferSize-nLineBytes-y*nLineBytes)+1; lpTempPtr=(BYTE *)lpSrcDIB+(dwBufferSize-nLineBytes-y*nLineBytes)+1; for(x=1;x<lWidth-1;x++) { if (*lpTempPtr == *lpPtr) *lpTempPtr = (BYTE)255; else *lpTempPtr = *lpTempPtr - *lpPtr; lpPtr++; lpTempPtr++; } } } else { for(y=1;y<lHeight-1;y++) { lpPtr=(BYTE *)lpbmi+(dwBufferSize-nLineBytes-y*nLineBytes); lpTempPtr=(BYTE *)lpSrcDIB+(dwBufferSize-nLineBytes-y*nLineBytes); for(x=0;x<lWidth;x++) { if (*lpTempPtr == *lpPtr) *lpTempPtr = (BYTE)255; else *lpTempPtr = *lpTempPtr - *lpPtr; lpPtr++; lpTempPtr++; } } } // cleanup GlobalUnlock(hDib); GlobalUnlock(hNewDIB); GlobalFree(hNewDIB); return TRUE; } /************************************************************************* * * ThinningDIB() * * Parameters: * * HDIB hDib - objective DIB handle * * Return Value: * * BOOL - True is success, else False * * Description: * * This function thins a DIB * ************************************************************************/ BOOL ThinningDIB(HDIB hDib) { static int erasetable[256]= { 0,0,1,1,0,0,1,1, 1,1,0,1,1,1,0,1, 1,1,0,0,1,1,1,1, 0,0,0,0,0,0,0,1, 0,0,1,1,0,0,1,1, 1,1,0,1,1,1,0,1, 1,1,0,0,1,1,1,1, 0,0,0,0,0,0,0,1, 1,1,0,0,1,1,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 1,1,0,0,1,1,0,0, 1,1,0,1,1,1,0,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,1,1,0,0,1,1, 1,1,0,1,1,1,0,1, 1,1,0,0,1,1,1,1, 0,0,0,0,0,0,0,1, 0,0,1,1,0,0,1,1, 1,1,0,1,1,1,0,1, 1,1,0,0,1,1,1,1, 0,0,0,0,0,0,0,0, 1,1,0,0,1,1,0,0, 0,0,0,0,0,0,0,0, 1,1,0,0,1,1,1,1, 0,0,0,0,0,0,0,0, 1,1,0,0,1,1,0,0, 1,1,0,1,1,1,0,0, 1,1,0,0,1,1,1,0, 1,1,0,0,1,0,0,0 }; // start wait cursor WaitCursorBegin(); // Old DIB buffer if (hDib == NULL) { WaitCursorEnd(); return FALSE; } // only support 256 color image WORD wBitCount = DIBBitCount(hDib); if (wBitCount != 8) { WaitCursorEnd(); return FALSE; } // new DIB HDIB hNewDIB = CopyHandle(hDib); if (! hNewDIB) { WaitCursorEnd(); return FALSE; } // source dib buffer LPBITMAPINFO lpSrcDIB = (LPBITMAPINFO)GlobalLock(hDib); if (! lpSrcDIB) { WaitCursorBegin(); return FALSE; } // New DIB buffer LPBITMAPINFO lpbmi = (LPBITMAPINFO)GlobalLock(hNewDIB); if (! lpbmi) { WaitCursorBegin(); return FALSE; } // start erosion... LPSTR lpPtr; LPSTR lpTempPtr; LONG x,y; BYTE num; LONG lHeight = DIBHeight(lpSrcDIB); LONG lWidth = DIBWidth(lpSrcDIB); DWORD dwBufferSize = GlobalSize(lpSrcDIB); int nLineBytes = BytesPerLine(lpSrcDIB); int nw,n,ne,w,e,sw,s,se; BOOL Finished=FALSE; while(!Finished) { Finished=TRUE; for (y=1;y<lHeight-1;y++) { lpPtr=(char *)lpbmi+(dwBufferSize-nLineBytes-y*nLineBytes); lpTempPtr=(char *)lpSrcDIB+(dwBufferSize-nLineBytes-y*nLineBytes); x=1; while(x<lWidth-1) { if(*(lpPtr+x)==0) { w=(unsigned char)*(lpPtr+x-1); e=(unsigned char)*(lpPtr+x+1); if( (w==255)|| (e==255)) { nw=(unsigned char)*(lpPtr+x+nLineBytes-1); n=(unsigned char)*(lpPtr+x+nLineBytes); ne=(unsigned char)*(lpPtr+x+nLineBytes+1); sw=(unsigned char)*(lpPtr+x-nLineBytes-1); s=(unsigned char)*(lpPtr+x-nLineBytes); se=(unsigned char)*(lpPtr+x-nLineBytes+1); num=nw/255+n/255*2+ne/255*4+w/255*8+e/255*16+sw/255*32+s/255*64+se/255*128; if(erasetable[num]==1) { *(lpPtr+x)=(BYTE)255; *(lpTempPtr+x)=(BYTE)255; Finished=FALSE; x++; } } } x++; } } for (x=1;x<lWidth-1;x++) { y=1; while(y<lHeight-1) { lpPtr=(char *)lpbmi+(dwBufferSize-nLineBytes-y*nLineBytes); lpTempPtr=(char *)lpSrcDIB+(dwBufferSize-nLineBytes-y*nLineBytes); if(*(lpPtr+x)==0) { n=(unsigned char)*(lpPtr+x+nLineBytes); s=(unsigned char)*(lpPtr+x-nLineBytes); if( (n==255)|| (s==255)) { nw=(unsigned char)*(lpPtr+x+nLineBytes-1); ne=(unsigned char)*(lpPtr+x+nLineBytes+1); w=(unsigned char)*(lpPtr+x-1); e=(unsigned char)*(lpPtr+x+1); sw=(unsigned char)*(lpPtr+x-nLineBytes-1); se=(unsigned char)*(lpPtr+x-nLineBytes+1); num=nw/255+n/255*2+ne/255*4+w/255*8+e/255*16+sw/255*32+s/255*64+se/255*128; if(erasetable[num]==1) { *(lpPtr+x)=(BYTE)255; *(lpTempPtr+x)=(BYTE)255; Finished=FALSE; y++; } } } y++; } } } // cleanup GlobalUnlock(hDib); GlobalUnlock(hNewDIB); GlobalFree(hNewDIB); return TRUE; } ////////////////////////////////////////////////////////// // internal definitions #define PI (double)3.14159265359 /*complex number*/ typedef struct { double re; double im; }COMPLEX; /*complex add*/ COMPLEX Add(COMPLEX c1, COMPLEX c2) { COMPLEX c; c.re=c1.re+c2.re; c.im=c1.im+c2.im; return c; } /*complex substract*/ COMPLEX Sub(COMPLEX c1, COMPLEX c2) { COMPLEX c; c.re=c1.re-c2.re; c.im=c1.im-c2.im; return c; } /*complex multiple*/ COMPLEX Mul(COMPLEX c1, COMPLEX c2) { COMPLEX c; c.re=c1.re*c2.re-c1.im*c2.im; c.im=c1.re*c2.im+c2.re*c1.im; return c; } ////////////////////////////////////////////////////////// /* void FFT(COMPLEX * TD, COMPLEX * FD, int power); void IFFT(COMPLEX * FD, COMPLEX * TD, int power); void DCT(double *f, double *F, int power); void IDCT(double *F, double *f, int power); void WALh(double *f, double *W, int power); void IWALh(double *W, double *f, int power); */ /**************************************************** FFT() 参数: TD为时域值 FD为频域值 power为2的幂数 返回值: 无 说明: 本函数实现快速傅立叶变换 ****************************************************/ void FFT(COMPLEX * TD, COMPLEX * FD, int power) { int count; int i,j,k,bfsize,p; double angle; COMPLEX *W,*X1,*X2,*X; /*计算傅立叶变换点数*/ count=1<<power; /*分配运算所需存储器*/ W=(COMPLEX *)malloc(sizeof(COMPLEX)*count/2); X1=(COMPLEX *)malloc(sizeof(COMPLEX)*count); X2=(COMPLEX *)malloc(sizeof(COMPLEX)*count); /*计算加权系数*/ for(i=0;i<count/2;i++) { angle=-i*PI*2/count; W[i].re=cos(angle); W[i].im=sin(angle); } /*将时域点写入存储器*/ memcpy(X1,TD,sizeof(COMPLEX)*count); /*蝶形运算*/ for(k=0;k<power;k++) { for(j=0;j<1<<k;j++) { bfsize=1<<(power-k); for(i=0;i<bfsize/2;i++) { p=j*bfsize; X2[i+p]=Add(X1[i+p],X1[i+p+bfsize/2]); X2[i+p+bfsize/2]=Mul(Sub(X1[i+p],X1[i+p+bfsize/2]),W[i*(1<<k)]); } } X=X1; X1=X2; X2=X; } /*重新排序*/ for(j=0;j<count;j++) { p=0; for(i=0;i<power;i++) { if (j&(1<<i)) p+=1<<(power-i-1); } FD[j]=X1[p]; } /*释放存储器*/ free(W); free(X1); free(X2); } /**************************************************** IFFT() 参数: FD为频域值 TD为时域值 power为2的幂数 返回值: 无 说明: 本函数利用快速傅立叶变换实现傅立叶反变换 ****************************************************/ void IFFT(COMPLEX * FD, COMPLEX * TD, int power) { int i, count; COMPLEX *x; /*计算傅立叶反变换点数*/ count=1<<power; /*分配运算所需存储器*/ x=(COMPLEX *)malloc(sizeof(COMPLEX)*count); /*将频域点写入存储器*/ memcpy(x,FD,sizeof(COMPLEX)*count); /*求频域点的共轭*/ for(i=0;i<count;i++) x[i].im = -x[i].im; /*调用FFT*/ FFT(x, TD, power); /*求时域点的共轭*/ for(i=0;i<count;i++) { TD[i].re /= count; TD[i].im = -TD[i].im / count; } /*释放存储器*/ free(x); } /******************************************************* DCT() 参数: f为时域值 F为频域值 power为2的幂数 返回值: 无 说明: 本函数利用快速傅立叶变换实现快速离散余弦变换 ********************************************************/ void DCT(double *f, double *F, int power) { int i,count; COMPLEX *X; double s; /*计算离散余弦变换点数*/ count=1<<power; /*分配运算所需存储器*/ X=(COMPLEX *)malloc(sizeof(COMPLEX)*count*2); /*延拓*/ memset(X,0,sizeof(COMPLEX)*count*2); /*将时域点写入存储器*/ for(i=0;i<count;i++) { X[i].re=f[i]; } /*调用快速傅立叶变换*/ FFT(X,X,power+1); /*调整系数*/ s=1/sqrt((float)count); F[0]=X[0].re*s; s*=sqrt(2.0); for(i=1;i<count;i++) { F[i]=(X[i].re*cos(i*PI/(count*2))+X[i].im*sin(i*PI/(count*2)))*s; } /*释放存储器*/ free(X); } /************************************************************ IDCT() 参数: F为频域值 f为时域值 power为2的幂数 返回值: 无 说明: 本函数利用快速傅立叶反变换实现快速离散反余弦变换 *************************************************************/ void IDCT(double *F, double *f, int power) { int i,count; COMPLEX *X; double s; /*计算离散反余弦变换点数*/ count=1<<power; /*分配运算所需存储器*/ X=(COMPLEX *)malloc(sizeof(COMPLEX)*count*2); /*延拓*/ memset(X,0,sizeof(COMPLEX)*count*2); /*调整频域点,写入存储器*/ for(i=0;i<count;i++) { X[i].re=F[i]*cos(i*PI/(count*2)); X[i].im=F[i]*sin(i*PI/(count*2)); } /*调用快速傅立叶反变换*/ IFFT(X,X,power+1); /*调整系数*/ s=1/sqrt((float)count); for(i=1;i<count;i++) { f[i]=(1-sqrt(2.0))*s*F[0]+sqrt(2.0)*s*X[i].re*count*2; } /*释放存储器*/ free(X); } /********************************************************** WALh() 参数: f为时域值 W为频域值 power为2的幂数 返回值: 无 说明: 本函数利用快速傅立叶变换实现快速沃尔什-哈达玛变换 *************************************************************/ void WALh(double *f, double *W, int power) { int count; int i,j,k,bfsize,p; double *X1,*X2,*X; /*计算快速沃尔什变换点数*/ count=1<<power; /*分配运算所需存储器*/ X1=(double *)malloc(sizeof(double)*count); X2=(double *)malloc(sizeof(double)*count); /*将时域点写入存储器*/ memcpy(X1,f,sizeof(double)*count); /*蝶形运算*/ for(k=0;k<power;k++) { for(j=0;j<1<<k;j++) { bfsize=1<<(power-k); for(i=0;i<bfsize/2;i++) { p=j*bfsize; X2[i+p]=X1[i+p]+X1[i+p+bfsize/2]; X2[i+p+bfsize/2]=X1[i+p]-X1[i+p+bfsize/2]; } } X=X1; X1=X2; X2=X; } /*调整系数*/ // for(i=0;i<count;i++) // { // W[i]=X1[i]/count; // } for(j=0;j<count;j++) { p=0; for(i=0;i<power;i++) { if (j&(1<<i)) p+=1<<(power-i-1); } W[j]=X1[p]/count; } /*释放存储器*/ free(X1); free(X2); } /********************************************************************* IWALh() 参数: W为频域值 f为时域值 power为2的幂数 返回值: 无 说明: 本函数利用快速沃尔什-哈达玛变换实现快速沃尔什-哈达玛反变换 **********************************************************************/ void IWALh(double *W, double *f, int power) { int i, count; /*计算快速沃尔什反变换点数*/ count=1<<power; /*调用快速沃尔什-哈达玛变换*/ WALh(W, f, power); /*调整系数*/ for(i=0;i<count;i++) { f[i] *= count; } } ////////////////////////////////////////////////////////////////////////////////// // internal functions #define Point(x,y) lpPoints[(x)+(y)*nWidth] void GetPoints(int nWidth,int nHeight,BYTE *lpBits,BYTE *lpPoints) { int x,y,p; int nByteWidth = WIDTHBYTES(nWidth*24); //nWidth*3; //if (nByteWidth%4) nByteWidth+=4-(nByteWidth%4); for(y=0;y<nHeight;y++) { for(x=0;x<nWidth;x++) { p=x*3+y*nByteWidth; lpPoints[x+y*nWidth]=(BYTE)(0.299*(float)lpBits[p+2]+0.587*(float)lpBits[p+1]+0.114*(float)lpBits[p]+0.1); } } } void PutPoints(int nWidth,int nHeight,BYTE *lpBits,BYTE *lpPoints) { int x,y,p,p1; int nByteWidth = WIDTHBYTES(nWidth*24); //nWidth*3; //if (nByteWidth%4) nByteWidth+=4-(nByteWidth%4); for(y=0;y<nHeight;y++) { for(x=0;x<nWidth;x++) { p=x*3+y*nByteWidth; p1=x+y*nWidth; lpBits[p]=lpPoints[p1]; lpBits[p+1]=lpPoints[p1]; lpBits[p+2]=lpPoints[p1]; } } } ////////////////////////////////////////////////////////////////////////////// /**************************************************** FFTDIB() 参数: hDIB为输入的DIB句柄 返回值: 成功为TRUE;失败为FALSE 说明: 本函数实现DIB位图的快速傅立叶变换 ****************************************************/ BOOL FFTDIB(HDIB hDIB) { if (hDIB == NULL) return FALSE; // start wait cursor WaitCursorBegin(); HDIB hDib = NULL; HDIB hNewDib = NULL; // we only convolute 24bpp DIB, so first convert DIB to 24bpp WORD wBitCount = DIBBitCount(hDIB); if (wBitCount != 24) { hNewDib = ConvertDIBFormat(hDIB, 24, NULL); hDib = CopyHandle(hNewDib); } else { hNewDib = CopyHandle(hDIB); hDib = CopyHandle(hDIB); } if (hNewDib == NULL && hDib == NULL) { WaitCursorEnd(); return FALSE; } // process! LPBYTE lpSrcDIB = (LPBYTE)GlobalLock(hDib); LPBYTE lpDIB = (LPBYTE)GlobalLock(hNewDib); LPBYTE lpInput = FindDIBBits(lpSrcDIB); LPBYTE lpOutput = FindDIBBits(lpDIB); int nWidth = DIBWidth(lpSrcDIB); int nHeight = DIBHeight(lpSrcDIB); int w=1,h=1,wp=0,hp=0; while(w*2<=nWidth) { w*=2; wp++; } while(h*2<=nHeight) { h*=2; hp++; } int x,y; BYTE *lpPoints=new BYTE[nWidth*nHeight]; GetPoints(nWidth,nHeight,lpInput,lpPoints); COMPLEX *TD=new COMPLEX[w*h]; COMPLEX *FD=new COMPLEX[w*h]; for(y=0;y<h;y++) { for(x=0;x<w;x++) { TD[x+w*y].re=Point(x,y); TD[x+w*y].im=0; } } for(y=0;y<h;y++) { FFT(&TD[w*y],&FD[w*y],wp); } for(y=0;y<h;y++) { for(x=0;x<w;x++) { TD[y+h*x]=FD[x+w*y]; // TD[x+w*y]=FD[x*h+y]; } } for(x=0;x<w;x++) { FFT(&TD[x*h],&FD[x*h],hp); } memset(lpPoints,0,nWidth*nHeight); double m; for(y=0;y<h;y++) { for(x=0;x<w;x++) { m=sqrt(FD[x*h+y].re*FD[x*h+y].re+FD[x*h+y].im*FD[x*h+y].im)/100; if (m>255) m=255; Point((x<w/2?x+w/2:x-w/2),nHeight-1-(y<h/2?y+h/2:y-h/2))=(BYTE)(m); } } delete TD; delete FD; PutPoints(nWidth,nHeight,lpOutput,lpPoints); delete lpPoints; // recover DWORD dwSize = GlobalSize(hDib); memcpy(lpSrcDIB, lpDIB, dwSize); GlobalUnlock(hDib); GlobalUnlock(hNewDib); if (wBitCount != 24) { hNewDib = ConvertDIBFormat(hDib, wBitCount, NULL); lpSrcDIB = (LPBYTE)GlobalLock(hDIB); lpDIB = (LPBYTE)GlobalLock(hNewDib); dwSize = GlobalSize(hNewDib); memcpy(lpSrcDIB, lpDIB, dwSize); GlobalUnlock(hDIB); GlobalUnlock(hNewDib); } else { lpSrcDIB = (LPBYTE)GlobalLock(hDIB); lpDIB = (LPBYTE)GlobalLock(hDib); dwSize = GlobalSize(hDib); memcpy(lpSrcDIB, lpDIB, dwSize); GlobalUnlock(hDIB); GlobalUnlock(hDib); } // cleanup GlobalFree(hDib); GlobalFree(hNewDib); // return WaitCursorEnd(); return TRUE; } /**************************************************** DCTDIB() 参数: hDIB为输入的DIB句柄 返回值: 成功为TRUE;失败为FALSE 说明: 本函数实现DIB位图的快速余弦变换 ****************************************************/ BOOL DCTDIB(HDIB hDIB) { if (hDIB == NULL) return FALSE; // start wait cursor WaitCursorBegin(); HDIB hDib = NULL; HDIB hNewDib = NULL; // we only convolute 24bpp DIB, so first convert DIB to 24bpp WORD wBitCount = DIBBitCount(hDIB); if (wBitCount != 24) { hNewDib = ConvertDIBFormat(hDIB, 24, NULL); hDib = CopyHandle(hNewDib); } else { hNewDib = CopyHandle(hDIB); hDib = CopyHandle(hDIB); } if (hNewDib == NULL && hDib == NULL) { WaitCursorEnd(); return FALSE; } // process! LPBYTE lpSrcDIB = (LPBYTE)GlobalLock(hDib); LPBYTE lpDIB = (LPBYTE)GlobalLock(hNewDib); LPBYTE lpInput = FindDIBBits(lpSrcDIB); LPBYTE lpOutput = FindDIBBits(lpDIB); int nWidth = DIBWidth(lpSrcDIB); int nHeight = DIBHeight(lpSrcDIB); int w=1,h=1,wp=0,hp=0; while(w*2<=nWidth) { w*=2; wp++; } while(h*2<=nHeight) { h*=2; hp++; } int x,y; BYTE *lpPoints=new BYTE[nWidth*nHeight]; GetPoints(nWidth,nHeight,lpInput,lpPoints); double *f=new double[w*h]; double *W=new double[w*h]; for(y=0;y<h;y++) { for(x=0;x<w;x++) { f[x+y*w]=Point(x,y); } } for(y=0;y<h;y++) { DCT(&f[w*y],&W[w*y],wp); } for(y=0;y<h;y++) { for(x=0;x<w;x++) { f[x*h+y]=W[x+w*y]; } } for(x=0;x<w;x++) { DCT(&f[x*h],&W[x*h],hp); } double a; memset(lpPoints,0,nWidth*nHeight); for(y=0;y<h;y++) { for(x=0;x<w;x++) { a=fabs(W[x*h+y]); if (a>255) a=255; Point(x,nHeight-y-1)=(BYTE)(a); } } delete f; delete W; PutPoints(nWidth,nHeight,lpOutput,lpPoints); delete lpPoints; // recover DWORD dwSize = GlobalSize(hDib); memcpy(lpSrcDIB, lpDIB, dwSize); GlobalUnlock(hDib); GlobalUnlock(hNewDib); if (wBitCount != 24) { hNewDib = ConvertDIBFormat(hDib, wBitCount, NULL); lpSrcDIB = (LPBYTE)GlobalLock(hDIB); lpDIB = (LPBYTE)GlobalLock(hNewDib); dwSize = GlobalSize(hNewDib); memcpy(lpSrcDIB, lpDIB, dwSize); GlobalUnlock(hDIB); GlobalUnlock(hNewDib); } else { lpSrcDIB = (LPBYTE)GlobalLock(hDIB); lpDIB = (LPBYTE)GlobalLock(hDib); dwSize = GlobalSize(hDib); memcpy(lpSrcDIB, lpDIB, dwSize); GlobalUnlock(hDIB); GlobalUnlock(hDib); } // cleanup GlobalFree(hDib); GlobalFree(hNewDib); // return WaitCursorEnd(); return TRUE; } /**************************************************** WALhDIB() 参数: hDIB为输入的DIB句柄 返回值: 成功为TRUE;失败为FALSE 说明: 本函数实现DIB位图的快速沃尔什-哈达玛变换 ****************************************************/ BOOL WALhDIB(HDIB hDIB) { if (hDIB == NULL) return FALSE; // start wait cursor WaitCursorBegin(); HDIB hDib = NULL; HDIB hNewDib = NULL; // we only convolute 24bpp DIB, so first convert DIB to 24bpp WORD wBitCount = DIBBitCount(hDIB); if (wBitCount != 24) { hNewDib = ConvertDIBFormat(hDIB, 24, NULL); hDib = CopyHandle(hNewDib); } else { hNewDib = CopyHandle(hDIB); hDib = CopyHandle(hDIB); } if (hNewDib == NULL && hDib == NULL) { WaitCursorEnd(); return FALSE; } // process! LPBYTE lpSrcDIB = (LPBYTE)GlobalLock(hDib); LPBYTE lpDIB = (LPBYTE)GlobalLock(hNewDib); LPBYTE lpInput = FindDIBBits(lpSrcDIB); LPBYTE lpOutput = FindDIBBits(lpDIB); int nWidth = DIBWidth(lpSrcDIB); int nHeight = DIBHeight(lpSrcDIB); int w=1,h=1,wp=0,hp=0; while(w*2<=nWidth) { w*=2; wp++; } while(h*2<=nHeight) { h*=2; hp++; } int x,y; BYTE *lpPoints=new BYTE[nWidth*nHeight]; GetPoints(nWidth,nHeight,lpInput,lpPoints); double *f=new double[w*h]; double *W=new double[w*h]; for(y=0;y<h;y++) { for(x=0;x<w;x++) { f[x+y*w]=Point(x,y); } } for(y=0;y<h;y++) { WALh(f+w*y,W+w*y,wp); } for(y=0;y<h;y++) { for(x=0;x<w;x++) { f[x*h+y]=W[x+w*y]; } } for(x=0;x<w;x++) { WALh(f+x*h,W+x*h,hp); } double a; memset(lpPoints,0,nWidth*nHeight); for(y=0;y<h;y++) { for(x=0;x<w;x++) { a=fabs(W[x*h+y]*1000); if (a>255) a=255; Point(x,nHeight-y-1)=(BYTE)a; } } delete f; delete W; PutPoints(nWidth,nHeight,lpOutput,lpPoints); delete lpPoints; // recover DWORD dwSize = GlobalSize(hDib); memcpy(lpSrcDIB, lpDIB, dwSize); GlobalUnlock(hDib); GlobalUnlock(hNewDib); if (wBitCount != 24) { hNewDib = ConvertDIBFormat(hDib, wBitCount, NULL); lpSrcDIB = (LPBYTE)GlobalLock(hDIB); lpDIB = (LPBYTE)GlobalLock(hNewDib); dwSize = GlobalSize(hNewDib); memcpy(lpSrcDIB, lpDIB, dwSize); GlobalUnlock(hDIB); GlobalUnlock(hNewDib); } else { lpSrcDIB = (LPBYTE)GlobalLock(hDIB); lpDIB = (LPBYTE)GlobalLock(hDib); dwSize = GlobalSize(hDib); memcpy(lpSrcDIB, lpDIB, dwSize); GlobalUnlock(hDIB); GlobalUnlock(hDib); } // cleanup GlobalFree(hDib); GlobalFree(hNewDib); // return WaitCursorEnd(); return TRUE; }
[ "damoguyan8844@2e4fddd8-cc6a-11de-b393-33af5e5426e5" ]
damoguyan8844@2e4fddd8-cc6a-11de-b393-33af5e5426e5
745c06238729400d2941e3ab03ce91f903f58af6
41e81273e985ed5c540346bacdfa227835ac34ed
/logdevice/common/buffered_writer/BufferedWriterSingleLog.cpp
854414cf4bc16f3ffcc61698984b27ea5e455d73
[ "BSD-3-Clause" ]
permissive
flyfish30/LogDevice
b8bd9a02b1fdfc1516b3d02129c7a0e56e5ef0fd
0b12c381bbfcdb5a63df59cb5575b16e30e874be
refs/heads/main
2023-02-11T08:04:17.565196
2021-01-05T04:20:43
2021-01-06T03:56:43
326,886,348
0
0
NOASSERTION
2021-01-05T04:31:25
2021-01-05T04:31:24
null
UTF-8
C++
false
false
28,477
cpp
/** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include "logdevice/common/buffered_writer/BufferedWriterSingleLog.h" #include <chrono> #include <lz4.h> #include <lz4hc.h> #include <zstd.h> #include <folly/IntrusiveList.h> #include <folly/Memory.h> #include <folly/Overload.h> #include <folly/Random.h> #include <folly/ScopeGuard.h> #include <folly/Varint.h> #include "logdevice/common/AppendRequest.h" #include "logdevice/common/PayloadGroupCodec.h" #include "logdevice/common/Processor.h" #include "logdevice/common/SimpleEnumMap.h" #include "logdevice/common/Timer.h" #include "logdevice/common/Worker.h" #include "logdevice/common/buffered_writer/BufferedWriteCodec.h" #include "logdevice/common/buffered_writer/BufferedWriteDecoderImpl.h" #include "logdevice/common/buffered_writer/BufferedWriterImpl.h" #include "logdevice/common/buffered_writer/BufferedWriterShard.h" #include "logdevice/common/debug.h" #include "logdevice/common/stats/Stats.h" namespace facebook { namespace logdevice { using namespace std::literals::chrono_literals; const SimpleEnumMap<BufferedWriterSingleLog::Batch::State, std::string>& BufferedWriterSingleLog::Batch::names() { static SimpleEnumMap<BufferedWriterSingleLog::Batch::State, std::string> s_names({{State::BUILDING, "BUILDING"}, {State::CONSTRUCTING_BLOB, "CONSTRUCTING_BLOB"}, {State::READY_TO_SEND, "READY_TO_SEND"}, {State::INFLIGHT, "INFLIGHT"}, {State::RETRY_PENDING, "RETRY_PENDING"}, {State::FINISHED, "FINISHED"}}); return s_names; } using batch_flags_t = BufferedWriteDecoderImpl::flags_t; using Compression = BufferedWriter::Options::Compression; using Flags = BufferedWriteDecoderImpl::Flags; BufferedWriterSingleLog::BufferedWriterSingleLog(BufferedWriterShard* parent, logid_t log_id, GetLogOptionsFunc get_options) : parent_(parent), log_id_(log_id), get_log_options_(std::move(get_options)), options_(get_log_options_(log_id_)) {} BufferedWriterSingleLog::~BufferedWriterSingleLog() { for (std::unique_ptr<Batch>& batch : *batches_) { if (batch->state != Batch::State::FINISHED) { invokeCallbacks(*batch, E::SHUTDOWN, DataRecord(), NodeID()); finishBatch(*batch); } } dropBlockedAppends(E::SHUTDOWN, NodeID()); } void BufferedWriterSingleLog::append(AppendChunk chunk) { int rv = appendImpl(chunk, /* defer_client_size_trigger */ false); if (rv != 0) { // Buffer this chunk; when the inflight batch finishes we will re-call // appendImpl(). blocked_appends_->push_back(std::move(chunk)); blocked_appends_.observe(); // The new append can be flushed; need to inform parent flushableMayHaveChanged(); ld_check(is_flushable_); } } int BufferedWriterSingleLog::appendImpl(AppendChunk& chunk, bool defer_client_size_trigger) { // Calculate how many bytes (approx.) these records will take up in the memory size_t payload_memory_bytes_added = 0; for (const BufferedWriter::Append& append : chunk) { const auto& payload = append.payload; payload_memory_bytes_added += BufferedWriterPayloadMeter::memorySize(payload); } const size_t max_payload_size = Worker::settings().max_payload_size; if (haveBuildingBatch()) { auto& batch = batches_->back(); // Calculate how many bytes these records will take up in the blob for (const BufferedWriter::Append& append : chunk) { std::visit(folly::overload( [&](const std::string& payload) { auto iobuf = folly::IOBuf::wrapBufferAsValue( payload.data(), payload.size()); batch->blob_size_estimator.append(iobuf); }, [&](const PayloadGroup& payload_group) { batch->blob_size_estimator.append(payload_group); }), append.payload); } const size_t new_blob_bytes_total = batch->blob_size_estimator.calculateSize(checksumBits()); if (new_blob_bytes_total > max_payload_size) { // These records would take us over the payload size limit. Flush the // already buffered records first, then we will create a new batch for // these records. StatsHolder* stats{parent_->parent_->processor()->stats_}; STAT_INCR(stats, buffered_writer_max_payload_flush); flushBuildingBatch(); ld_check(!haveBuildingBatch()); } else { batch->blob_bytes_total = new_blob_bytes_total; batch->blob_format = batch->blob_size_estimator.getFormat(); } } // If there is no batch in the BUILDING state, create one now. if (!haveBuildingBatch()) { if (options_.mode == BufferedWriter::Options::Mode::ONE_AT_A_TIME && !batches_->empty()) { // In the one-at-a-time mode, if there is already a batch inflight, we // must wait for it to finish before creating a new batch. return -1; } // Refresh log options once per batch. options_ = get_log_options_(log_id_); auto batch = std::make_unique<Batch>(next_batch_num_++); // Calculate how many bytes these records will take up in the blob for (const BufferedWriter::Append& append : chunk) { std::visit(folly::overload( [&](const std::string& payload) { auto iobuf = folly::IOBuf::wrapBufferAsValue( payload.data(), payload.size()); batch->blob_size_estimator.append(iobuf); }, [&](const PayloadGroup& payload_group) { batch->blob_size_estimator.append(payload_group); }), append.payload); } batch->blob_bytes_total = batch->blob_size_estimator.calculateSize(checksumBits()); batch->blob_format = batch->blob_size_estimator.getFormat(); batches_->push_back(std::move(batch)); // Intentionally setting state after pushing to make sure is_flushable_ // becomes true *during* the setBatchState() call setBatchState(*batches_->back(), Batch::State::BUILDING); ld_check(is_flushable_); batches_.observe(); activateTimeTrigger(); } Batch& batch = *batches_->back(); // Add these appends to the BUILDING batch batch.payload_memory_bytes_total += payload_memory_bytes_added; ld_check(batch.blob_bytes_total <= MAX_PAYLOAD_SIZE_INTERNAL); for (auto& append : chunk) { auto& payload = append.payload; BufferedWriter::AppendCallback::Context& context = append.context; batch.appends.emplace_back(std::move(context), std::move(payload)); if (append.attrs.optional_keys.find(KeyType::FINDKEY) != append.attrs.optional_keys.end()) { const std::string& key = append.attrs.optional_keys[KeyType::FINDKEY]; // The batch of records will have the smallest custom key from the ones // provided by the client for each record. if (batch.attrs.optional_keys.find(KeyType::FINDKEY) == batch.attrs.optional_keys.end() || key < batch.attrs.optional_keys[KeyType::FINDKEY]) { batch.attrs.optional_keys[KeyType::FINDKEY] = key; } } if (append.attrs.counters.has_value()) { const auto& new_counters = append.attrs.counters.value(); if (!batch.attrs.counters.has_value()) { batch.attrs.counters.emplace(); } auto& curr_counters = batch.attrs.counters.value(); for (auto counter : new_counters) { auto it = curr_counters.find(counter.first); if (it == curr_counters.end()) { curr_counters.emplace(counter); continue; } it->second += counter.second; } } } // Check if we hit the size trigger and should flush flushMeMaybe(defer_client_size_trigger); return 0; } void BufferedWriterSingleLog::flushMeMaybe(bool defer_client_size_trigger) { ld_check(haveBuildingBatch()); const Batch& batch = *batches_->back(); Worker* w = Worker::onThisThread(); const size_t max_payload_size = w->immutable_settings_->max_payload_size; // If we're at the LogDevice hard limit on payload size, flush if (batch.blob_bytes_total >= max_payload_size) { ld_check(batch.blob_bytes_total <= MAX_PAYLOAD_SIZE_INTERNAL); STAT_INCR(w->getStats(), buffered_writer_max_payload_flush); flushBuildingBatch(); return; } // If client set `Options::size_trigger', check if the sum of payload bytes // buffered exceeds it if (!defer_client_size_trigger && options_.size_trigger >= 0 && batch.payload_memory_bytes_total >= options_.size_trigger) { STAT_INCR(w->getStats(), buffered_writer_size_trigger_flush); flushBuildingBatch(); return; } } void BufferedWriterSingleLog::flushBuildingBatch() { ld_check(is_flushable_); ld_check(haveBuildingBatch()); sendBatch(*batches_->back()); } void BufferedWriterSingleLog::flushAll() { ld_check(is_flushable_); if (haveBuildingBatch()) { flushBuildingBatch(); } // In the ONE_AT_A_TIME mode, there may be appends blocked because there // is a batch currently inflight. But this flushAll() call is supposed to // flush them. Defer the flush; record the count so that these appends // get flushed as soon as the currently inflight batch comes back. blocked_appends_flush_deferred_count_ = blocked_appends_->size(); flushableMayHaveChanged(); ld_check(!is_flushable_); } bool BufferedWriterSingleLog::calculateIsFlushable() const { ld_check_le(blocked_appends_flush_deferred_count_, blocked_appends_->size()); return haveBuildingBatch() || blocked_appends_flush_deferred_count_ < blocked_appends_->size(); } bool BufferedWriterSingleLog::haveBuildingBatch() const { return !batches_->empty() && batches_->back()->state == Batch::State::BUILDING; } void BufferedWriterSingleLog::flushableMayHaveChanged() { bool new_flushable = calculateIsFlushable(); if (new_flushable == is_flushable_) { return; } is_flushable_ = new_flushable; parent_->setFlushable(*this, is_flushable_); if (is_flushable_) { // If we're flushable for enough time continuously, do the flush. // Note that this applies both to BUILDING batch and to blocked_appends_. activateTimeTrigger(); } else if (time_trigger_timer_) { time_trigger_timer_->cancel(); } } struct AppendRequestCallbackImpl { void operator()(Status st, const DataRecord& record, NodeID redirect) { // Check that the BufferedWriter still exists; might have been destroyed // since the append went out Worker* w = Worker::onThisThread(); auto it = w->active_buffered_writers_.find(writer_id_); if (it == w->active_buffered_writers_.end()) { return; } parent_->onAppendReply(batch_, st, record, redirect); } buffered_writer_id_t writer_id_; BufferedWriterSingleLog* parent_; BufferedWriterSingleLog::Batch& batch_; }; void BufferedWriterSingleLog::sendBatch(Batch& batch) { if (batch.state == Batch::State::BUILDING) { ld_check_eq(batch.blob.length(), 0); setBatchState(batch, Batch::State::CONSTRUCTING_BLOB); construct_blob( batch, checksumBits(), options_.compression, options_.destroy_payloads); } else { // This is a retry, so we must have already sent it, so we can skip the // purgatory of READY_TO_SEND. ld_check(batch.state == Batch::State::RETRY_PENDING); appendBatch(batch); } } void BufferedWriterSingleLog::readyToSend(Batch& batch) { ld_check(batch.state == Batch::State::CONSTRUCTING_BLOB); StatsHolder* stats{parent_->parent_->processor()->stats_}; // Collect before&after byte counters to give clients an // idea of the compression ratio STAT_ADD(stats, buffered_writer_bytes_in, batch.payload_memory_bytes_total); STAT_ADD(stats, buffered_writer_bytes_batched, batch.blob.length()); setBatchState(batch, Batch::State::READY_TO_SEND); bool sent_at_least_one{false}; while (!batches_->empty()) { size_t index = next_batch_to_send_ - batches_->front()->num; if (index >= batches_->size()) { break; } if ((*batches_)[index]->state != Batch::State::READY_TO_SEND) { if (!sent_at_least_one) { RATELIMIT_WARNING( 1s, 1, "On log %s, %lu batches are behind next_batch_to_send_ " "(%lu), which is in state %s", toString(log_id_).c_str(), batches_->size() - index, next_batch_to_send_, Batch::names()[(*batches_)[index]->state].c_str()); } break; } next_batch_to_send_++; appendBatch(*(*batches_)[index]); sent_at_least_one = true; } } void BufferedWriterSingleLog::appendBatch(Batch& batch) { ld_check(batch.state == Batch::State::READY_TO_SEND || batch.state == Batch::State::RETRY_PENDING); ld_check(batch.blob.length() != 0); ld_check(!batch.retry_timer || !batch.retry_timer->isActive()); if (batch.total_size_freed > 0) { parent_->parent_->appendSink()->onBytesFreedByWorker( batch.total_size_freed); // Now that we've recorded that they're freed, reset the counter so we don't // double count by double calling onBytesFreedByWorker(), e.g. if we retry. batch.total_size_freed = 0; } setBatchState(batch, Batch::State::INFLIGHT); // Call into BufferedWriter::appendBuffered() which in production is just a // proxy for ClientImpl::appendBuffered() or // SequencerBatching::appendBuffered() but in tests may be overridden to fail std::pair<Status, NodeID> rv = parent_->parent_->appendSink()->appendBuffered( log_id_, batch.appends, std::move(batch.attrs), PayloadHolder(batch.blob.cloneAsValue()), AppendRequestCallbackImpl{parent_->id_, this, batch}, Worker::onThisThread()->idx_, // need the callback on this same Worker checksumBits()); if (rv.first != E::OK) { // Simulate failure reply onAppendReply(batch, rv.first, DataRecord(log_id_, Payload()), rv.second); } } void BufferedWriterSingleLog::onAppendReply(Batch& batch, Status status, const DataRecord& dr_batch, NodeID redirect) { ld_spew("status = %s", error_name(status)); ld_check(batch.state == Batch::State::INFLIGHT); if (status != E::OK && scheduleRetry(batch, status, dr_batch) == 0) { // Scheduled retry, nothing else to do return; } if (status == E::OK) { WORKER_STAT_INCR(buffered_writer_batches_succeeded); } else { WORKER_STAT_INCR(buffered_writer_batches_failed); } invokeCallbacks(batch, status, dr_batch, redirect); finishBatch(batch); reap(); if (options_.mode == BufferedWriter::Options::Mode::ONE_AT_A_TIME) { if (status == E::OK) { // Now that some batch finished successfully, reissue any appends that // were blocked in ONE_AT_A_TIME mode while the batch was inflight. unblockAppends(); } else { // Batch failed (exhausted all retries), also fail any blocked appends to // preserve ordering. This is only a best-effort measure; it's inherently // racy since more appends may be in flight (e.g. queued // BufferedAppendRequest, or user append() calls from another thread). dropBlockedAppends(status, redirect); } } } void BufferedWriterSingleLog::quiesce() { // Stop all timers. if (time_trigger_timer_) { time_trigger_timer_->cancel(); } for (std::unique_ptr<Batch>& batch : *batches_) { if (batch->retry_timer) { batch->retry_timer->cancel(); } } } void BufferedWriterSingleLog::reap() { while (!batches_->empty() && batches_->front()->state == Batch::State::FINISHED) { batches_->pop_front(); } batches_.compact(); } void BufferedWriterSingleLog::unblockAppends() { bool flush_at_end = false; while (!blocked_appends_->empty()) { // If there are more blocked appends after this one, defer the client size // trigger so that we fit as many as possible (still subject to the max // payload size limit) in the next batch. bool defer_client_size_trigger = blocked_appends_->size() > 1; int rv = appendImpl(blocked_appends_->front(), defer_client_size_trigger); if (rv != 0) { // Blocked. Must have just flushed a new batch; keep the chunk in // `blocked_appends_'. break; } // Chunk contents were moved out of the queue, pop. blocked_appends_->pop_front(); if (blocked_appends_flush_deferred_count_ > 0) { // There was a flush() call while this append was blocked. That flush // had to be deferred because there was a batch already inflight and the // flush would have created a new one (but we are in ONE_AT_A_TIME // mode). flush_at_end = true; --blocked_appends_flush_deferred_count_; } } blocked_appends_.compact(); // Despite `flush_at_end == true`, the log may not be flushable if the last // call to `appendImpl()` above has flushed the last batch if (flush_at_end && haveBuildingBatch()) { flushBuildingBatch(); } else { flushableMayHaveChanged(); } } void BufferedWriterSingleLog::dropBlockedAppends(Status status, NodeID redirect) { BufferedWriterImpl::AppendCallbackInternal* cb = parent_->parent_->getCallback(); int64_t payload_mem_bytes = 0; for (auto& chunk : *blocked_appends_) { BufferedWriter::AppendCallback::ContextSet context_set; for (auto& append : chunk) { auto& payload = append.payload; payload_mem_bytes += BufferedWriterPayloadMeter::memorySize(payload); BufferedWriter::AppendCallback::Context& context = append.context; context_set.emplace_back(std::move(context), std::move(payload)); } WORKER_STAT_ADD( buffered_append_failed_dropped_behind_failed_batch, chunk.size()); cb->onFailureInternal(log_id_, std::move(context_set), status, redirect); } blocked_appends_->clear(); blocked_appends_.compact(); blocked_appends_flush_deferred_count_ = 0; // Return the memory budget parent_->parent_->releaseMemory(payload_mem_bytes); flushableMayHaveChanged(); } void BufferedWriterSingleLog::activateTimeTrigger() { if (options_.time_trigger.count() < 0) { return; } if (!time_trigger_timer_) { time_trigger_timer_ = std::make_unique<Timer>([this] { StatsHolder* stats{parent_->parent_->processor()->stats_}; STAT_INCR(stats, buffered_writer_time_trigger_flush); flushAll(); }); } if (!time_trigger_timer_->isActive()) { time_trigger_timer_->activate(options_.time_trigger); } } int BufferedWriterSingleLog::scheduleRetry(Batch& batch, Status status, const DataRecord& /*dr_batch*/) { if (options_.retry_count >= 0 && batch.retry_count >= options_.retry_count) { return -1; } // Invoke retry callback to let the upper layer (application typically) know // about the failure (if interested) and check if it wants to block the // retry. BufferedWriterImpl::AppendCallbackInternal* cb = parent_->parent_->getCallback(); if (cb->onRetry(log_id_, batch.appends, status) != BufferedWriter::AppendCallback::RetryDecision::ALLOW) { // Client blocked the retry; bail out. The caller will invoke the failure // callback shortly. return -1; } // Initialize `retry_timer' if this is the first retry if (!batch.retry_timer) { ld_check(options_.retry_initial_delay.count() >= 0); std::chrono::milliseconds max_delay = options_.retry_max_delay.count() >= 0 ? options_.retry_max_delay : std::chrono::milliseconds::max(); max_delay = std::max(max_delay, options_.retry_initial_delay); batch.retry_timer = std::make_unique<ExponentialBackoffTimer>( [this, &batch]() { sendBatch(batch); }, options_.retry_initial_delay, max_delay); batch.retry_timer->randomize(); } setBatchState(batch, Batch::State::RETRY_PENDING); ++batch.retry_count; ld_spew( "scheduling retry in %ld ms", batch.retry_timer->getNextDelay().count()); WORKER_STAT_INCR(buffered_writer_retries); batch.retry_timer->activate(); return 0; } void BufferedWriterSingleLog::invokeCallbacks(Batch& batch, Status status, const DataRecord& dr_batch, NodeID redirect) { ld_check(batch.state != Batch::State::FINISHED); BufferedWriterImpl::AppendCallbackInternal* cb = parent_->parent_->getCallback(); if (status == E::OK) { WORKER_STAT_ADD(buffered_append_success, batch.appends.size()); cb->onSuccess(log_id_, std::move(batch.appends), dr_batch.attrs); } else { if (status == E::SHUTDOWN) { WORKER_STAT_ADD(buffered_append_failed_shutdown, batch.appends.size()); } else { WORKER_STAT_ADD( buffered_append_failed_actual_append, batch.appends.size()); } cb->onFailureInternal(log_id_, std::move(batch.appends), status, redirect); } } void BufferedWriterSingleLog::finishBatch(Batch& batch) { setBatchState(batch, Batch::State::FINISHED); // Make sure payloads are deallocated; invokeCallbacks() ought to have moved // them back to the application ld_check(batch.appends.empty()); batch.appends.shrink_to_fit(); // Free/unlink the buffer. batch.blob = folly::IOBuf(); // Return the memory budget parent_->parent_->releaseMemory(batch.payload_memory_bytes_total); } void BufferedWriterSingleLog::setBatchState(Batch& batch, Batch::State state) { batch.state = state; flushableMayHaveChanged(); } int BufferedWriterSingleLog::checksumBits() const { return parent_->parent_->shouldPrependChecksum() ? Worker::settings().checksum_bits : 0; } namespace { template <typename PayloadsEncoder> void encode_batch(BufferedWriterSingleLog::Batch& batch, int checksum_bits, Compression compression, int zstd_level, bool destroy_payloads) { ld_check(batch.total_size_freed == 0); BufferedWriteCodec::Encoder<PayloadsEncoder> encoder( checksum_bits, batch.appends.size(), batch.blob_bytes_total); for (auto& append : batch.appends) { if (destroy_payloads) { batch.total_size_freed += BufferedWriterPayloadMeter::memorySize(append.second); std::visit( folly::overload( [&](std::string& payload) { // Payload should be destroyed, so pass ownership to the encoder std::string* client_payload = new std::string(std::move(payload)); folly::IOBuf iobuf = folly::IOBuf( folly::IOBuf::TAKE_OWNERSHIP, client_payload->data(), client_payload->size(), +[](void* /* buf */, void* userData) { delete reinterpret_cast<std::string*>(userData); }, /* userData */ reinterpret_cast<void*>(client_payload)); encoder.append(std::move(iobuf)); // Can't do payload.clear() because that usually doesn't free // memory. payload.clear(); payload.shrink_to_fit(); }, [&](PayloadGroup& payload_group) { encoder.append(payload_group); payload_group.clear(); }), append.second); } else { std::visit(folly::overload( [&](const std::string& client_payload) { // It's safe to wrap buffer, since payloads are preserved // in batch. encoder.append(folly::IOBuf::wrapBufferAsValue( client_payload.data(), client_payload.size())); }, [&](const PayloadGroup& payload_group) { encoder.append(payload_group); }), append.second); } } folly::IOBufQueue encoded; encoder.encode(encoded, compression, zstd_level); batch.blob = encoded.moveAsValue(); } } // namespace void BufferedWriterSingleLog::Impl::construct_compressed_blob( BufferedWriterSingleLog::Batch& batch, int checksum_bits, Compression compression, int zstd_level, bool destroy_payloads) { switch (batch.blob_format) { case BufferedWriteCodec::Format::SINGLE_PAYLOADS: { encode_batch<BufferedWriteSinglePayloadsCodec::Encoder>( batch, checksum_bits, compression, zstd_level, destroy_payloads); break; } case BufferedWriteCodec::Format::PAYLOAD_GROUPS: { encode_batch<PayloadGroupCodec::Encoder>( batch, checksum_bits, compression, zstd_level, destroy_payloads); break; } } } void BufferedWriterSingleLog::Impl::construct_blob_long_running( BufferedWriterSingleLog::Batch& batch, int checksum_bits, Compression compression, const int zstd_level, bool destroy_payloads) { ld_check(batch.state == Batch::State::CONSTRUCTING_BLOB); construct_compressed_blob( batch, checksum_bits, compression, zstd_level, destroy_payloads); } void BufferedWriterSingleLog::construct_blob( BufferedWriterSingleLog::Batch& batch, int checksum_bits, Compression compression, bool destroy_payloads) { ld_check(batch.state == Batch::State::CONSTRUCTING_BLOB); if (parent_->parent_->isShuttingDown()) { // Our destructor will call callbacks with E::SHUTDOWN. return; } const int zstd_level = Worker::settings().buffered_writer_zstd_level; // We need to call construct_blob_long_running(), then callback(). If the // batch is large, we send it to a background thread so that this thread can // process more requests. However, if it's small, we just do that inline // since the queueing & switching overhead would cost more than we save. if (batch.blob_bytes_total < Worker::settings().buffered_writer_bg_thread_bytes_threshold) { Impl::construct_blob_long_running( batch, checksum_bits, compression, zstd_level, destroy_payloads); readyToSend(batch); } else { ProcessorProxy* processor_proxy = parent_->parent_->processorProxy(); ld_spew("Enqueueing batch %lu for log %s to background thread. Batches " "outstanding for this log: %lu Background tasks: %lu", batch.num, toString(log_id_).c_str(), batches_->size(), parent_->parent_->recentNumBackground()); processor_proxy->processor()->enqueueToBackgroundBlocking( [&batch, checksum_bits, destroy_payloads, processor_proxy, trigger = parent_->parent_->getBackgroundTaskCountHolder(), thread_affinity = Worker::onThisThread()->idx_.val(), compression, zstd_level, this]() mutable { BufferedWriterSingleLog::Impl::construct_blob_long_running( batch, checksum_bits, compression, zstd_level, destroy_payloads); std::unique_ptr<Request> request = std::make_unique<ContinueBlobSendRequest>( this, batch, thread_affinity); // Since this runs on the background thread, be careful not to access // non-constant fields of "this", unless you know what you're doing. ld_spew("Done constructing batch %lu for log %s, posting back to " "worker. Background tasks: %lu", batch.num, toString(log_id_).c_str(), parent_->parent_->recentNumBackground()); int rc = processor_proxy->postWithRetrying(request); if (rc != 0) { ld_error("Processor::postWithRetrying() failed: %d", rc); } }); } } }} // namespace facebook::logdevice
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
9afd9e3d29888378b752d44f44c7fce012337f8c
82e6375dedb79df18d5ccacd048083dae2bba383
/src/main/tests/test-thr-thread.cpp
6a514be4de66c15e5c2c0da4c85976b2eb60388f
[]
no_license
ybouret/upsylon
0c97ac6451143323b17ed923276f3daa9a229e42
f640ae8eaf3dc3abd19b28976526fafc6a0338f4
refs/heads/master
2023-02-16T21:18:01.404133
2023-01-27T10:41:55
2023-01-27T10:41:55
138,697,127
0
0
null
null
null
null
UTF-8
C++
false
false
798
cpp
#include "y/concurrent/thread.hpp" #include "y/concurrent/sync/mutex.hpp" #include "y/utest/run.hpp" using namespace upsylon; namespace { struct Working { concurrent::mutex &sync; int task; static inline void Call(void *args) { Y_ASSERT(args); Working &w = *static_cast<Working *>(args); Y_LOCK(w.sync); std::cerr << "task#" << w.task << std::endl; } }; } Y_UTEST(thr_thread) { concurrent::mutex sync; Working w0 = { sync, 0 }; Working w1 = { sync, 1 }; Working w2 = { sync, 2 }; concurrent::thread t0( Working::Call, &w0,3,0); concurrent::thread t1( Working::Call, &w1,3,1); concurrent::thread t2( Working::Call, &w2,3,2); } Y_UTEST_DONE()
[ "yann.bouret@unice.fr" ]
yann.bouret@unice.fr
82136400c49bb030bc8aeefdbbed11b73f5d3dc7
60bb67415a192d0c421719de7822c1819d5ba7ac
/blazemark/blazemark/gmm/Complex7.h
afb0676b9db22ef0c371b348639ada23f326a212
[ "BSD-3-Clause" ]
permissive
rtohid/blaze
48decd51395d912730add9bc0d19e617ecae8624
7852d9e22aeb89b907cb878c28d6ca75e5528431
refs/heads/master
2020-04-16T16:48:03.915504
2018-12-19T20:29:42
2018-12-19T20:29:42
165,750,036
0
0
null
null
null
null
UTF-8
C++
false
false
3,017
h
//================================================================================================= /*! // \file blazemark/gmm/Complex7.h // \brief Header file for the GMM++ kernel for the complex expression E = ( A + B ) * ( C - D ) // // Copyright (C) 2012-2018 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= #ifndef _BLAZEMARK_GMM_COMPLEX7_H_ #define _BLAZEMARK_GMM_COMPLEX7_H_ //************************************************************************************************* // Includes //************************************************************************************************* #include <blazemark/system/Types.h> namespace blazemark { namespace gmm { //================================================================================================= // // KERNEL FUNCTIONS // //================================================================================================= //************************************************************************************************* /*!\name GMM++ kernel functions */ //@{ double complex7( size_t N, size_t steps ); //@} //************************************************************************************************* } // namespace gmm } // namespace blazemark #endif
[ "klaus.iglberger@gmail.com" ]
klaus.iglberger@gmail.com
3856f2a561f25a9a74dc37a3f2e54fb904dbd7a2
c3b980c0138bc0ce0c1fa8dfa821394351b807fb
/cpp_04/ex03/MateriaSource.hpp
d34b655e6c4d070457ab191f69841e6d541aff4d
[]
no_license
hchorfi/cpp_modules
84f29e71d3beab4891e2ef5bf743ea2c320e3089
9328eb74344c9c84e4704c0786f1bace11c05bf3
refs/heads/main
2023-08-01T10:32:38.534013
2021-09-22T10:40:29
2021-09-22T10:40:29
378,654,456
1
1
null
null
null
null
UTF-8
C++
false
false
492
hpp
#ifndef MATERIASOURCE_H #define MATERIASOURCE_H #include "IMateriaSource.hpp" #include "AMateria.hpp" class MateriaSource : public IMateriaSource { private: AMateria *_MateriasInv[4]; public: MateriaSource(); MateriaSource(const MateriaSource& copy); MateriaSource& operator = (const MateriaSource& other); ~MateriaSource(); void learnMateria(AMateria* materia); AMateria* createMateria(std::string const & type); }; #endif
[ "hamza.chorfi.des@gmail.com" ]
hamza.chorfi.des@gmail.com
365560f9cb16ec71c5826739caf1d36cf61e1ec1
c000f89785771e2fc3376b73a8ebd969b47aeaee
/include/mc_rtc/gui/Transform.h
16355c6a804489bfafdb2fbe47b9a50492f518dd
[ "BSD-2-Clause", "Qhull", "BSD-3-Clause", "MIT" ]
permissive
fkanehiro/mc_rtc
99fa43fa44eb0b14392934ece528fba04989125c
776017e46c1a4626c1d8f1fb7d51675a9b9b9cad
refs/heads/master
2022-11-27T01:03:13.562298
2020-09-22T03:50:36
2020-09-22T03:50:36
235,250,687
1
0
BSD-2-Clause
2020-01-21T03:47:35
2020-01-21T03:47:34
null
UTF-8
C++
false
false
2,687
h
/* * Copyright 2015-2019 CNRS-UM LIRMM, CNRS-AIST JRL */ #pragma once #include <mc_rtc/gui/details/traits.h> #include <mc_rtc/gui/elements.h> #include <mc_rtc/gui/types.h> namespace mc_rtc { namespace gui { /** Transform display a widget that shows a 6D frame * * This transformation is not editable. * * This will also create an ArrayLabel with labels {"qw", "qx", "qy", * "qz", "tx", "ty", "tz"} * * \tparam GetT Must return an sva::PTransformd * */ template<typename GetT> struct TransformROImpl : public DataElement<GetT> { static constexpr auto type = Elements::Transform; TransformROImpl(const std::string & name, GetT get_fn) : DataElement<GetT>(name, get_fn) { static_assert(details::CheckReturnType<GetT, sva::PTransformd>::value, "TransformImpl getter should return an sva::PTransformd"); } constexpr static size_t write_size() { return DataElement<GetT>::write_size() + 1; } void write(mc_rtc::MessagePackBuilder & builder) { DataElement<GetT>::write(builder); builder.write(true); // Is read-only } /** Invalid element */ TransformROImpl() {} }; /** Transform display a widget that shows a 6D frame * * This transformation is editable. * * This will also create an ArrayInput with labels {"qw", "qx", "qy", * "qz", "tx", "ty", "tz"} * * \tparam GetT Must return an sva::PTransformd * * \tparam SetT Should accept an sva::PTransformd * */ template<typename GetT, typename SetT> struct TransformImpl : public CommonInputImpl<GetT, SetT> { static constexpr auto type = Elements::Transform; TransformImpl(const std::string & name, GetT get_fn, SetT set_fn) : CommonInputImpl<GetT, SetT>(name, get_fn, set_fn) { static_assert(details::CheckReturnType<GetT, sva::PTransformd>::value, "TransformImpl getter should return an sva::PTransformd"); } constexpr static size_t write_size() { return CommonInputImpl<GetT, SetT>::write_size() + 1; } void write(mc_rtc::MessagePackBuilder & builder) { CommonInputImpl<GetT, SetT>::write(builder); builder.write(false); // Is read-only } /** Invalid element */ TransformImpl() {} }; /** Helper function to create a Transform element (read-only) */ template<typename GetT> TransformROImpl<GetT> Transform(const std::string & name, GetT get_fn) { return TransformROImpl<GetT>(name, get_fn); } /** Helper function to create a Transform element (editable) */ template<typename GetT, typename SetT> TransformImpl<GetT, SetT> Transform(const std::string & name, GetT get_fn, SetT set_fn) { return TransformImpl<GetT, SetT>(name, get_fn, set_fn); } } // namespace gui } // namespace mc_rtc
[ "pierre.gergondet@gmail.com" ]
pierre.gergondet@gmail.com
1714174625ee26290fe76eb5757efa379855d282
dba4b0d853efbdf7752d30054394d0b7f6f66051
/bitio/BitReader.h
798d59f957b4d6e89bdfe3f105f6ff926b82abb5
[]
no_license
dbondin/am15-ds
b3a404c3bf60b2ec20f805b5077f8ce05bd8ba0d
bc5d665820a8c56aa460e309902cbe0948191510
refs/heads/master
2021-01-22T03:58:12.115281
2018-02-19T09:05:16
2018-02-19T09:05:16
81,488,391
0
0
null
null
null
null
UTF-8
C++
false
false
458
h
/* * BitReader.h * * Created on: Mar 17, 2017 * Author: dbondin */ #ifndef BITREADER_H_ #define BITREADER_H_ #include <istream> namespace bitio { class BitReader { public: BitReader(); virtual ~BitReader(); void attach(std::istream * is); std::istream * get_stream() const; void detach(); int read_next_bit(); private: std::istream * is; unsigned char current_byte; int current_bit; }; } /* namespace a */ #endif /* BITREADER_H_ */
[ "dbondin@ya.ru" ]
dbondin@ya.ru
55b6d89db62134dfb9f46b38daacd6ffdec77623
2dac401a4bc43bb1a4a535ec2552749bf16e50b0
/icpc/bipartite-graph.cpp
14d4d1fca57439af0848ca43dbab397df651e75d
[]
no_license
bollu/competitive
895ed10d6ca230becddd962f169f1883224ac3b7
25fdddfb515ecf1ac29f2ec628c29925e9ad402d
refs/heads/master
2020-12-25T15:07:59.763550
2016-12-12T05:41:41
2016-12-12T05:41:41
67,641,902
1
0
null
null
null
null
UTF-8
C++
false
false
3,172
cpp
#include <map> #include <vector> #include <iostream> #include <algorithm> #include <math.h> #include <assert.h> /* ID: arun.ga1 LANG: C++ TASK: */ using namespace std; #define prime 1000000007 #define DEBUG(x) cout << '>' << #x << ':' << x << endl; #define REP(i,n) for(int i=0;i<(n);i++) #define FOR(i,a,b) for(int i=(a);i<=(b);i++) #define FORD(i,a,b) for(int i=(a);i>=(b);i--) inline bool EQ(double a, double b) { return fabs(a-b) < 1e-9; } // static const int INF = 1<<29; typedef long long ll; inline int two(int n) { return 1 << n; } inline int test(int n, int b) { return (n>>b)&1; } inline void set_bit(int & n, int b) { n |= two(b); } inline void unset_bit(int & n, int b) { n &= ~two(b); } inline int last_bit(int n) { return n & (-n); } inline int ones(int n) { int res = 0; while(n && ++res) n-=n&(-n); return res; } template<class T> void chmax(T & a, const T & b) { a = max(a, b); } template<class T> void chmin(T & a, const T & b) { a = min(a, b); } ///////////////////////////////////////////////////////////////////// void quick_sort (int *a, int n,int *b) { int i,j,p,t; if(n<2) { return; } p=a[n/2]; for(i=0,j=n-1;;i++,j--) { while(a[i]<p) { i++; } while(p<a[j]) { j--; } if(i>=j) { break; } t=a[i]; a[i]=a[j]; a[j]=t; t=b[i]; b[i]=b[j]; b[j]=t; } quick_sort(a,i,b); quick_sort(a+i,n-i,b+i); } void run() { int n, m, d, D; cin>>n>>m>>d>>D; int adj[100][100]; for(int i = 0; i < 100; i++) { for(int j = 0; j < 100; j++) { adj[i][j] = 0; } } int nadjl[100]; int nadjr[100]; for(int i = 0; i < m; i++) { nadjl[i] = nadjr[i] = 0; } if (m < d * n || m > D * n) { cout<<-1<<"\n"; } else { int curm = m; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { if(nadjl[i] < d && nadjr[j] < d && !adj[i][j]) { curm--; adj[i][j] = 1; nadjl[i]++; nadjr[j]++; } } } while(curm > 0) { for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { if(nadjl[i] < D && nadjr[j] < D && !adj[i][j]) { curm--; adj[i][j] = 1; nadjl[i]++; nadjr[j]++; } if (curm == 0) { break; } } if (curm == 0) { break; } } } for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { if(adj[i][j]) { cout<<i + 1<<" "<<j + 1<<"\n"; } } } } } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int t; cin>>t; while(t--) { run(); } return 0; }
[ "siddu.druid@gmail.com" ]
siddu.druid@gmail.com
cbc3eca66238fba1a8a504c294734e4a26353f27
1a77b5eac40055032b72e27e720ac5d43451bbd6
/フォーム対応/VisualC++/MFC/Chap1/Dr4/Dr4/Dr4Doc.h
6da2e99959649b821fe01b7619dc1b3700785ba4
[]
no_license
motonobu-t/algorithm
8c8d360ebb982a0262069bb968022fe79f2c84c2
ca7b29d53860eb06a357eb268f44f47ec9cb63f7
refs/heads/master
2021-01-22T21:38:34.195001
2017-05-15T12:00:51
2017-05-15T12:01:00
85,451,237
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
603
h
// Dr4Doc.h : CDr4Doc クラスのインターフェイス // #pragma once class CDr4Doc : public CDocument { protected: // シリアル化からのみ作成します。 CDr4Doc(); DECLARE_DYNCREATE(CDr4Doc) // 属性 public: // 操作 public: // オーバーライド public: virtual BOOL OnNewDocument(); virtual void Serialize(CArchive& ar); // 実装 public: virtual ~CDr4Doc(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // 生成された、メッセージ割り当て関数 protected: DECLARE_MESSAGE_MAP() };
[ "rx_78_bd@yahoo.co.jp" ]
rx_78_bd@yahoo.co.jp
3b2ec6a15a88aec83d7d3f98d8638543cac07203
981511cfbb6533914af0f72bdf4d779ad7a1c9ae
/cppHellow/41数组类/MyArray.hpp
d3c7baa9a89bceeec8fe05d3ae8e671e7c7da8b8
[ "Apache-2.0" ]
permissive
coderTong/cppStudy
f59b70f0550bde3da414b4793900b24b652a20cb
fddf4954395b5e9b89471c1a15d33f3554710105
refs/heads/master
2023-01-22T21:14:00.648666
2020-12-05T05:11:51
2020-12-05T05:11:51
282,211,002
0
0
null
null
null
null
UTF-8
C++
false
false
1,120
hpp
// // MyArray.hpp // 41数组类 // // Created by codew on 8/24/20. // Copyright © 2020 codertom. All rights reserved. // #ifndef MyArray_hpp #define MyArray_hpp #include <iostream> #include <stdio.h> class MyArray { public: // 无参构造函数, 用户没有指定容量, 则初始化为100 MyArray(); // 有参构造函数, 用户指定容量初始化 // C++提供了关键字explicit,禁止通过构造函数进行的隐式转换。声明为explicit的构造函数不能在隐式转换中使用。 explicit MyArray(int capacity); // 用户操作接口 ================================= // 根据 位置 添加元素 void setData(int pos, int val); // 获得 指定 位置的 数据 int getData(int index); // 尾插法 void pushBack(int val); // 获得长度 int getLength(); // 析构函数 ~MyArray(); private: // 数组一共可容纳多少个元素 int mCapacity; // 当前有多少个元素 int mSize; // 指向存储数据的空间 int *pAddress; }; #endif /* MyArray_hpp */
[ "tong.wu@netviewtech.com" ]
tong.wu@netviewtech.com
483c88965d3ee9bfd1ac16df0f7869e11963ca54
734cc5a617b17c9fbcdde8b9d2ae0426cce0f43c
/gfb2d/PhysicsDebugger.h
b98d56e5e7aff096291569f0b58c6a2e873f5cbd
[ "Zlib" ]
permissive
GamedevFramework/gf-box2d
8930ea587364f98fd1ffc40bd8e7875b6063c0e6
a78d69316c123daaf9eb74b632e9a4d44ae927e3
refs/heads/master
2022-03-20T12:53:38.523211
2022-03-12T16:01:53
2022-03-12T16:01:53
250,815,168
0
0
null
null
null
null
UTF-8
C++
false
false
3,569
h
/* * gf-box2d * Copyright (C) 2020 Julien Bernard * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef GF_BOX2D_PHYSICS_DEBUGGER_H #define GF_BOX2D_PHYSICS_DEBUGGER_H #include <vector> #include <box2d/box2d.h> #include <gf/Circ.h> #include <gf/Entity.h> #include <gf/Particles.h> #include <gf/VertexArray.h> #include <gf/Vector.h> namespace gfb2d { class PhysicsModel; class PhysicsDebugger : public gf::Entity { public: PhysicsDebugger(PhysicsModel& model, float opacity = 0.8f); void setDebug(bool debug); void toggleDebug(); void render(gf::RenderTarget& target, const gf::RenderStates& states) override; private: // struct Polygon { // gf::Polygon shape; // gf::Color4f color; // }; // // struct Circle { // gf::CircF shape; // gf::Color4f color; // }; // // struct SolidCircle { // gf::CircF shape; // gf::Vector2f axis; // gf::Color4f color; // }; // // struct Segment { // gf::Vector2f p1; // gf::Vector2f p2; // gf::Color4f color; // }; // // struct Transform { // gf::Vector2f position; // gf::Vector2f xAxis; // gf::Vector2f yAxis; // }; // // struct Point { // gf::Vector2f position; // float size; // gf::Color4f color; // }; struct PhysicsDraw : public b2Draw { public: PhysicsDraw(float scale, float opacity); /// Draw a closed polygon provided in CCW order. void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) override; /// Draw a solid closed polygon provided in CCW order. void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) override; /// Draw a circle. void DrawCircle(const b2Vec2& center, float radius, const b2Color& color) override; /// Draw a solid circle. void DrawSolidCircle(const b2Vec2& center, float radius, const b2Vec2& axis, const b2Color& color) override; /// Draw a line segment. void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) override; /// Draw a transform. Choose your own length scale. /// @param xf a transform. void DrawTransform(const b2Transform& xf) override; /// Draw a point. void DrawPoint(const b2Vec2& p, float size, const b2Color& color) override; gf::ShapeParticles shapes; gf::VertexArray lines; private: gf::Vector2f toGameCoords(b2Vec2 coords); gf::Color4f toGameColor(b2Color color); private: float m_scale; float m_opacity; }; private: bool m_debug; PhysicsModel *m_model; PhysicsDraw m_draw; }; } #endif // GF_BOX2D_PHYSICS_DEBUGGER_H
[ "julien.bernard@univ-fcomte.fr" ]
julien.bernard@univ-fcomte.fr
fa6a2fbebc36687b3de9d52a96ef8cf8dd6b67ca
1af49694004c6fbc31deada5618dae37255ce978
/services/network/trust_tokens/test/signed_request_verification_util.h
90e58b213ae451ed845ec88e22630f674dab5d37
[ "BSD-3-Clause" ]
permissive
sadrulhc/chromium
59682b173a00269ed036eee5ebfa317ba3a770cc
a4b950c23db47a0fdd63549cccf9ac8acd8e2c41
refs/heads/master
2023-02-02T07:59:20.295144
2020-12-01T21:32:32
2020-12-01T21:32:32
317,678,056
3
0
BSD-3-Clause
2020-12-01T21:56:26
2020-12-01T21:56:25
null
UTF-8
C++
false
false
2,628
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 SERVICES_NETWORK_TRUST_TOKENS_TEST_SIGNED_REQUEST_VERIFICATION_UTIL_H_ #define SERVICES_NETWORK_TRUST_TOKENS_TEST_SIGNED_REQUEST_VERIFICATION_UTIL_H_ #include <string> #include "base/callback.h" #include "base/containers/span.h" #include "base/optional.h" #include "base/strings/string_piece.h" #include "net/http/http_request_headers.h" #include "services/network/public/mojom/trust_tokens.mojom-shared.h" #include "services/network/trust_tokens/suitable_trust_token_origin.h" #include "url/gurl.h" namespace network { namespace test { // Reconstructs a request's canonical request data, extracts the signatures from // its Sec-Signature header, checks that the Sec-Signature header's contained // signatures verify. // // Optionally: // - If |verification_keys_out| is non-null, on success, returns the // verification key for each issuer, so that the caller can verify further state // concerning the key (like confirming that the key was bound to a previous // redemption). // - If |error_out| is non-null, on failure, sets it to a human-readable // description of the reason the verification failed. // - If |verifier| is non-null, uses the given verifier to verify the // signatures instead of Ed25519. bool ReconstructSigningDataAndVerifySignatures( const GURL& destination, const net::HttpRequestHeaders& headers, base::RepeatingCallback<bool(base::span<const uint8_t> data, base::span<const uint8_t> signature, base::span<const uint8_t> verification_key, const std::string& sig_alg)> verifier = {}, // defaults to Ed25519 std::string* error_out = nullptr, std::map<std::string, std::string>* verification_keys_out = nullptr, mojom::TrustTokenSignRequestData* sign_request_data_out = nullptr); // Parses a Sec-Redemption-Record header and extracts the (issuer, redemption // record) pairs the header contains. On success, returns true. On // failure, returns false and, if |error_out| is not null, stores a // helpful error message in |error_out| for debugging. bool ExtractRedemptionRecordsFromHeader( base::StringPiece sec_redemption_record_header, std::map<SuitableTrustTokenOrigin, std::string>* redemption_records_per_issuer_out, std::string* error_out); } // namespace test } // namespace network #endif // SERVICES_NETWORK_TRUST_TOKENS_TEST_SIGNED_REQUEST_VERIFICATION_UTIL_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
9408e221e75fd30b6b7ab3c132c66cd05a373d7f
776b5b34abc55ae6b9fd4fae57da5c6f899e5e2d
/qtractorConnect.h
7d1ccd94f5562bcc6206f4dda5a86f2c5a8bd3e3
[]
no_license
Icenowy/Rtractor
d275ae169b6347b5cd038b505e939446a7566b98
e2ad8421554bb9efd0d0bc71c96379893f941041
refs/heads/master
2016-09-06T09:26:50.301274
2014-08-24T14:14:00
2014-08-24T14:14:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,925
h
// qtractorConnect.h // /**************************************************************************** Copyright (C) 2005-2014, rncbc aka Rui Nuno Capela. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *****************************************************************************/ #ifndef __qtractorConnect_h #define __qtractorConnect_h #include <QTreeWidget> #include <QRegExp> #include <QList> // Forward declarations. class qtractorPortListItem; class qtractorClientListItem; class qtractorClientListView; class qtractorConnectorView; class qtractorConnect; class QPainter; class QTimer; class QPaintEvent; class QResizeEvent; class QMouseEvent; class QDragMoveEvent; class QDragEnterEvent; class QDragLeaveEvent; class QDropEvent; class QContextMenuEvent; //---------------------------------------------------------------------- // qtractorPortListItem -- Port list item. // class qtractorPortListItem : public QTreeWidgetItem { public: // Constructor. qtractorPortListItem(qtractorClientListItem *pClientItem, const QString& sPortName); // Default destructor. ~qtractorPortListItem(); // Instance accessors. void setPortName(const QString& sPortName); const QString& clientName() const; const QString& portName() const; // Complete client:port name helper. QString clientPortName(); // Connections client item accessor. qtractorClientListItem *clientItem() const; // Client port cleanup marker. void markPort(int iMark); void markClientPort(int iMark); int portMark() const; // Connected port list primitives. void addConnect(qtractorPortListItem *pPortItem); void removeConnect(qtractorPortListItem *pPortItem); void cleanConnects(); // Connected port finders. qtractorPortListItem *findConnect(qtractorPortListItem *pPortItem); // Connection list accessor. const QList<qtractorPortListItem *>& connects() const; // To virtually distinguish between list view items. int rtti() const; // Connectiopn highlight methods. void setHilite (bool bHilite); bool isHilite() const; // Proxy sort override method. // - Natural decimal sorting comparator. bool operator< (const QTreeWidgetItem& other) const; private: // Instance variables. qtractorClientListItem *m_pClientItem; QString m_sPortName; int m_iPortMark; bool m_bHilite; // Connection cache list. QList<qtractorPortListItem *> m_connects; }; //---------------------------------------------------------------------------- // qtractorClientListItem -- Client list item. // class qtractorClientListItem : public QTreeWidgetItem { public: // Constructor. qtractorClientListItem(qtractorClientListView *pClientListView, const QString& sClientName); // Default destructor. ~qtractorClientListItem(); // Port finder. qtractorPortListItem *findPortItem(const QString& sPortName); // Instance accessors. void setClientName(const QString& sClientName); const QString& clientName() const; // Readable flag accessor. bool isReadable() const; // Client port cleanup marker. void markClient(int iMark); void markClientPorts(int iMark); void cleanClientPorts(int iMark); int clientMark() const; // Connection highlight methods. void setHilite (bool bHilite); bool isHilite() const; // Client item openness status. void setOpen(bool bOpen); bool isOpen() const; // Proxy sort override method. // - Natural decimal sorting comparator. bool operator< (const QTreeWidgetItem& other) const; private: // Instance variables. QString m_sClientName; int m_iClientMark; int m_iHilite; }; //---------------------------------------------------------------------------- // qtractorClientListView -- Client list view, supporting drag-n-drop. // class qtractorClientListView : public QTreeWidget { Q_OBJECT public: // Constructor. qtractorClientListView(QWidget *pParent = NULL); // Default destructor. virtual ~qtractorClientListView(); // Client finder. qtractorClientListItem *findClientItem(const QString& sClientName); // Client:port finder. qtractorPortListItem *findClientPortItem(const QString& sClientPort); // Main controller accessors. void setBinding(qtractorConnect *pConnect); qtractorConnect *binding() const; // Readable flag accessors. void setReadable(bool bReadable); bool isReadable() const; // Client name filter helpers. void setClientName(const QString& sClientName); QString clientName() const; // Port name filter helpers. void setPortName(const QString& sPortName); QString portName() const; // Maintained current client name list. const QStringList& clientNames() const; // Override clear method. void clear(); // Whether items are all open (expanded) or closed (collapsed). void setOpenAll(bool bOpen); // Client ports cleanup marker. void markClientPorts(int iMark); void cleanClientPorts(int iMark); // Client:port refreshner (return newest item count). virtual int updateClientPorts() = 0; // Client:port hilite update stabilization. void hiliteClientPorts(); // Redirect this one as public. QTreeWidgetItem *itemFromIndex(const QModelIndex& index) const { return QTreeWidget::itemFromIndex(index); } // Auto-open timer methods. void setAutoOpenTimeout(int iAutoOpenTimeout); int autoOpenTimeout() const; // Do proper contents refresh/update. void refresh(); // Natural decimal sorting comparator. static bool lessThan( const QTreeWidgetItem& i1, const QTreeWidgetItem& i2, int col = 0); protected slots: // Auto-open timeout slot. void timeoutSlot(); protected: // Client:port filter function via regular expression. bool isClientName(const QString& sClientName); bool isPortName(const QString& sPortName); // Trap for help/tool-tip events. bool eventFilter(QObject *pObject, QEvent *pEvent); // Drag-n-drop stuff. QTreeWidgetItem *dragDropItem(const QPoint& pos); // Drag-n-drop stuff -- reimplemented virtual methods. void dragEnterEvent(QDragEnterEvent *pDragEnterEvent); void dragMoveEvent(QDragMoveEvent *pDragMoveEvent); void dragLeaveEvent(QDragLeaveEvent *); void dropEvent(QDropEvent *pDropEvent); // Handle mouse events for drag-and-drop stuff. void mousePressEvent(QMouseEvent *pMouseEvent); void mouseMoveEvent(QMouseEvent *pMouseEvent); // Context menu request event handler. void contextMenuEvent(QContextMenuEvent *); private: // Local instance variables. qtractorConnect *m_pConnect; bool m_bReadable; // Auto-open timer. int m_iAutoOpenTimeout; QTimer *m_pAutoOpenTimer; // Item we'll eventually drag-and-dropping something. QTreeWidgetItem *m_pDragItem; QTreeWidgetItem *m_pDropItem; // The point from where drag started. QPoint m_posDrag; // The current highlighted item. QTreeWidgetItem *m_pHiliteItem; // Client:port regular expression filters. QRegExp m_rxClientName; QRegExp m_rxPortName; // Maintained list of client names. QStringList m_clientNames; }; //---------------------------------------------------------------------- // qtractorConnectorView -- Connector view widget. // class qtractorConnectorView : public QWidget { Q_OBJECT public: // Constructor. qtractorConnectorView(QWidget *pParent = NULL); // Default destructor. ~qtractorConnectorView(); // Main controller accessors. void setBinding(qtractorConnect *pConnect); qtractorConnect *binding() const; public slots: // Useful slots (should this be protected?). void contentsChanged(); protected: // Specific event handlers. void paintEvent(QPaintEvent *); // Context menu request event handler. void contextMenuEvent(QContextMenuEvent *); private: // Legal client/port item position helper. int itemY(QTreeWidgetItem *pListItem) const; // Drawing methods. void drawConnectionLine(QPainter *pPainter, int x1, int y1, int x2, int y2, int h1, int h2); // Local instance variables. qtractorConnect *m_pConnect; }; //---------------------------------------------------------------------------- // qtractorConnect -- Connections controller. // class qtractorConnect : public QObject { Q_OBJECT public: // Constructor. qtractorConnect( qtractorClientListView *pOListView, qtractorClientListView *pIListView, qtractorConnectorView *pConnectorView); // Default destructor. virtual ~qtractorConnect(); // QTreeWidgetItem types. enum { ClientItem = 1001, PortItem = 1002 }; // Widget accesors. qtractorClientListView *OListView() const { return m_pOListView; } qtractorClientListView *IListView() const { return m_pIListView; } qtractorConnectorView *ConnectorView() const { return m_pConnectorView; } // Connector line style accessors. void setBezierLines(bool bBezierLines); bool isBezierLines() const; // Explicit connection tests. bool canConnectSelected(); bool canDisconnectSelected(); bool canDisconnectAll(); public slots: // Explicit connection slots. bool connectSelected(); bool disconnectSelected(); bool disconnectAll(); // Complete/incremental contents rebuilder; // check dirty status if incremental. void updateContents(bool bClear); // Incremental contents refreshner; check dirty status. void refresh(); // Context menu helper. void contextMenu(const QPoint& gpos); signals: // Contents change signal. void contentsChanged(); // Connection change signal. void connectChanged(); protected: // Connect/Disconnection primitives. virtual bool connectPorts(qtractorPortListItem *pOPort, qtractorPortListItem *pIPort) = 0; virtual bool disconnectPorts(qtractorPortListItem *pOPort, qtractorPortListItem *pIPort) = 0; // Update port connection references. virtual void updateConnections() = 0; private: // Connect/Disconnection local primitives. bool connectPortsEx(qtractorPortListItem *pOPort, qtractorPortListItem *pIPort); bool disconnectPortsEx(qtractorPortListItem *pOPort, qtractorPortListItem *pIPort); // Connection methods (unguarded). bool connectSelectedEx(); bool disconnectSelectedEx(); bool disconnectAllEx(); // Controlled widgets. qtractorClientListView *m_pOListView; qtractorClientListView *m_pIListView; qtractorConnectorView *m_pConnectorView; // How we'll draw connector lines. bool m_bBezierLines; }; #endif // __qtractorConnect_h // end of qtractorConnect.h
[ "icenowylin@gmail.com" ]
icenowylin@gmail.com
74daa54148d309ea4ca79c117325000c230738ed
b805d20cebea5e836b6fb13e6b9c2a0435981288
/HaiBitwiseAnd.h
a64087857d552b5f3154b05656c819d0d71f68a6
[]
no_license
vhquang/BitWiseAND-596
d04def2d09ed6b308cebf564e94401ff3cd579a9
1a96ec5f3510e22872a226efc266070bb17f2d5a
refs/heads/master
2021-01-10T20:35:45.944424
2014-03-03T08:20:35
2014-03-03T08:20:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,693
h
// // HaiBitwiseAnd.h // TopCoder // // Created by Hai Vu on 2/27/14. // Copyright (c) 2014 Hai Vu. All rights reserved. // #ifndef TopCoder_HaiBitwiseAnd_h #define TopCoder_HaiBitwiseAnd_h #include <vector> #include <iterator> #include <iostream> #include <cassert> using namespace std; class HaiBitwiseAnd { public: /* * We grow the set, each time adding only one number. Greedy algorithm. */ vector<long long> growSubset(vector<long long> subset, int N) { if (N < subset.size()) return (vector<long long>(0)); /* * First, make sure the numbers in the subset are valid. If not, return empty. */ for (int i=0; i< subset.size(); ++i) for (int j=i+1; j<subset.size(); ++j) { long long x = subset[i]; long long y = subset[j]; if ((x & y) == 0) return vector<long long>(0); // violation the rule for (int k=j+1; k < subset.size(); ++k) { if (x & y &subset[k]) return (vector<long long>(0)); // violation the rule } } if (N == subset.size()) return subset; // subset is good, just return /* * Each number in the set should have at least N - 1 bit set. Otherwise, we can't build the subset. */ int bitsExtra = (int) N - 1 - subset.size(); long long value = 0; vector<bool> matched (subset.size(), 0); // represents each number if the current subset for (int i=0; i<60; i++) { vector<int> validBitSet(0); for (int j=0;j<subset.size(); j++) { if (subset[j] & (1LL<<i)) validBitSet.push_back(j); } // This bit i-th should either match 0 or 1 number in the subset only. If more than that, it can't be used. if (validBitSet.size() == 0) { if (bitsExtra > 0) { bitsExtra -= 1; value += (1LL<<i); } } else if (validBitSet.size() == 1) { // if there is only one number that matches this bit, it's good. if (!matched[validBitSet[0]]) { matched[validBitSet[0]] = 1; // only take the minimum number in lexigraphical order value += (1LL<<i); } } } // put the number in the set and grow more subset.push_back(value); // we could prove that we will always find a number to grow the subset //sort(subset.begin(), subset.end()); return (growSubset(subset, N)); } void run(const vector<long long>& subset, int N, vector<long long>* output) { *output = growSubset(subset, N); sort(output->begin(), output->end()); } void printSet(const vector<long long>& subset) { std::cout << "Result : { "; for (vector<long long>::const_iterator it = subset.begin(); it != subset.end(); ++it) std::cout << *it << " "; std::cout << "}" << endl; } void unitTest() { long long i1[] = {11,17,20}; vector<long long> ret; run(vector<long long>(i1, i1 + sizeof(i1)/sizeof(i1[0])), 4, &ret); printSet(ret); assert(ret.size() == 0); long long i2[] = {99,157}; ret.clear(); run(vector<long long>(i2, i2 + sizeof(i2)/sizeof(i2[0])), 4, &ret); printSet(ret); assert(ret.size() == 4); long long i3[] = {1152921504606846975}; ret.clear(); run(vector<long long>(i3, i3 + sizeof(i3)/sizeof(i3[0])), 3, &ret); printSet(ret); assert(ret.size() == 0); long long i4[] = {}; ret.clear(); run(vector<long long>(i4, i4 + sizeof(i4)/sizeof(i4[0])), 5, &ret); printSet(ret); assert(ret.size() == 5); long long i5[] = {1, 3, 5, 7, 9, 11}; ret.clear(); run(vector<long long>(i5, i5 + sizeof(i5)/sizeof(i5[0])), 6, &ret); printSet(ret); assert(ret.size() == 0); } }; #endif
[ "vhquang@gmail.com" ]
vhquang@gmail.com
affa61c981a7cdf8a0a74c8a736de47efd57812c
9030ce2789a58888904d0c50c21591632eddffd7
/SDK/ARKSurvivalEvolved_PrimalItemCostume_BoneJerboa_functions.cpp
289966a446ebaac567e77c3c67dab62f8190deec
[ "MIT" ]
permissive
2bite/ARK-SDK
8ce93f504b2e3bd4f8e7ced184980b13f127b7bf
ce1f4906ccf82ed38518558c0163c4f92f5f7b14
refs/heads/master
2022-09-19T06:28:20.076298
2022-09-03T17:21:00
2022-09-03T17:21:00
232,411,353
14
5
null
null
null
null
UTF-8
C++
false
false
1,137
cpp
// ARKSurvivalEvolved (332.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_PrimalItemCostume_BoneJerboa_parameters.hpp" namespace sdk { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function PrimalItemCostume_BoneJerboa.PrimalItemCostume_BoneJerboa_C.ExecuteUbergraph_PrimalItemCostume_BoneJerboa // () // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void UPrimalItemCostume_BoneJerboa_C::ExecuteUbergraph_PrimalItemCostume_BoneJerboa(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function PrimalItemCostume_BoneJerboa.PrimalItemCostume_BoneJerboa_C.ExecuteUbergraph_PrimalItemCostume_BoneJerboa"); UPrimalItemCostume_BoneJerboa_C_ExecuteUbergraph_PrimalItemCostume_BoneJerboa_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "sergey.2bite@gmail.com" ]
sergey.2bite@gmail.com
26f430745ce25c6babccb56e4f15bf80f0692b6c
fce7bbf20a64e08a12e30b8eb66c87c6cd62de52
/section2/lambda.cpp
d46305ee3ccb20002044b64495e2d2947edd5ebd
[ "BSD-2-Clause" ]
permissive
jac0bwang/cpp_study
d2d5bc121acbf894c21308103b6cb71e1fdebd90
e760486a3019e61948de7912c62a00fe02fcac9b
refs/heads/master
2023-04-17T08:42:50.768759
2021-04-19T23:56:02
2021-05-05T07:00:58
355,804,080
0
0
BSD-2-Clause
2021-05-05T07:00:59
2021-04-08T07:23:26
null
UTF-8
C++
false
false
2,396
cpp
// Copyright (c) 2020 by Chrono // // g++ lambda.cpp -std=c++14 -o a.out;./a.out // g++ lambda.cpp -std=c++14 -I../common -o a.out;./a.out #include <iostream> #include <string> #include <vector> #include <algorithm> #include <functional> using namespace std; void my_square(int x) { cout << x*x << endl; } void case1() { auto pfunc = &my_square; (*pfunc)(3); pfunc(3); auto func = [](int x) { cout << x*x << endl; }; func(3); } void case2() { int n = 10; auto func = [=](int x) { cout << x*n << endl; }; func(3); } void case3() { auto f1 = [](){}; auto f2 = []() { cout << "lambda f2" << endl; auto f3 = [](int x) { return x*x; };// lambda f3 cout << f3(10) << endl; }; // lambda f2 f1(); f2(); //f1 = f2; vector<int> v = {3, 1, 8, 5, 0}; cout << *find_if(begin(v), end(v), [](int x) { return x >= 5; } ) << endl; } void case4() { int x = 33; auto f1 = [=]() { //x += 10; cout << x << endl; }; auto f2 = [&]() { x += 10; }; auto f3 = [=, &x]() { x += 20; }; f1(); f2(); cout << x << endl; f3(); cout << x << endl; } class DemoLambda final { public: DemoLambda() = default; ~DemoLambda() = default; private: int x = 0; public: auto print() { //auto f = [=]() return [this]() { cout << "member = " << x << endl; }; } }; void case5() { DemoLambda obj; auto f = obj.print(); f(); } void case6() { auto f = [](const auto& x) { return x + x; }; cout << f(3) << endl; cout << f(0.618) << endl; string str = "matrix"; cout << f(str) << endl; } // demo for function + lambda class Demo final { public: using func_type = std::function<void()>; public: func_type print = [this]() { cout << "value = " << m_value << endl; cout << "hello function+lambda" << endl; }; private: int m_value = 10; }; int main() { case1(); case2(); case3(); case4(); case5(); case6(); Demo d; d.print(); cout << "lambda demo" << endl; }
[ "chrono_cpp@me.com" ]
chrono_cpp@me.com
e45e6276e8335dd5cf2368ab646eb3514154d7b5
158ad541c56105be69895543abd76bd78f0a9f4f
/c++ folder/firs1.cpp
a5ffaf977e6e80f25ee8d67f625aa1c0d585ed82
[]
no_license
Rajneesh-9088/first
b8bbf0553e759eccb935e928e5976c6ca5bd74d9
10e6e73807c3ebaa79d43e1e2e422e3648c6a63a
refs/heads/master
2022-06-28T19:40:39.121359
2020-05-08T23:20:34
2020-05-08T23:20:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
105
cpp
#include<bits/stdc++.h> using namespace std; int main(){ cout<<"my name is rajneesh"; return 0; }
[ "rp8735685@gmail.com" ]
rp8735685@gmail.com
018385799f1b8b34e75c0c2e7720ff2ba55a4c61
8062b67a418c614e92d10e9c6c3c0d271f2226ad
/KNearestNeighbor/ann_src/ANN/ANN.h
ffe82110a1e30835573bdb67286d78a5f90dce32
[]
no_license
Casidi/libDM
dfa14add15094ee74860410a9ce57db7d55be168
6234cae5046bf14b8a65cc51a83f89ad41e7d001
refs/heads/master
2021-01-21T20:42:19.626914
2017-06-19T06:09:35
2017-06-19T06:09:35
94,671,261
0
0
null
null
null
null
UTF-8
C++
false
false
34,800
h
//---------------------------------------------------------------------- // File: ANN.h // Programmer: Sunil Arya and David Mount // Description: Basic include file for approximate nearest // neighbor searching. // Last modified: 01/27/10 (Version 1.1.2) //---------------------------------------------------------------------- // Copyright (c) 1997-2010 University of Maryland and Sunil Arya and // David Mount. All Rights Reserved. // // This software and related documentation is part of the Approximate // Nearest Neighbor Library (ANN). This software is provided under // the provisions of the Lesser GNU Public License (LGPL). See the // file ../ReadMe.txt for further information. // // The University of Maryland (U.M.) and the authors make no // representations about the suitability or fitness of this software for // any purpose. It is provided "as is" without express or implied // warranty. //---------------------------------------------------------------------- // History: // Revision 0.1 03/04/98 // Initial release // Revision 1.0 04/01/05 // Added copyright and revision information // Added ANNcoordPrec for coordinate precision. // Added methods theDim, nPoints, maxPoints, thePoints to ANNpointSet. // Cleaned up C++ structure for modern compilers // Revision 1.1 05/03/05 // Added fixed-radius k-NN searching // Revision 1.1.2 01/27/10 // Fixed minor compilation bugs for new versions of gcc //---------------------------------------------------------------------- //---------------------------------------------------------------------- // ANN - approximate nearest neighbor searching // ANN is a library for approximate nearest neighbor searching, // based on the use of standard and priority search in kd-trees // and balanced box-decomposition (bbd) trees. Here are some // references to the main algorithmic techniques used here: // // kd-trees: // Friedman, Bentley, and Finkel, ``An algorithm for finding // best matches in logarithmic expected time,'' ACM // Transactions on Mathematical Software, 3(3):209-226, 1977. // // Priority search in kd-trees: // Arya and Mount, ``Algorithms for fast vector quantization,'' // Proc. of DCC '93: Data Compression Conference, eds. J. A. // Storer and M. Cohn, IEEE Press, 1993, 381-390. // // Approximate nearest neighbor search and bbd-trees: // Arya, Mount, Netanyahu, Silverman, and Wu, ``An optimal // algorithm for approximate nearest neighbor searching,'' // 5th Ann. ACM-SIAM Symposium on Discrete Algorithms, // 1994, 573-582. //---------------------------------------------------------------------- #ifndef ANN_H #define ANN_H #ifdef WIN32 //---------------------------------------------------------------------- // For Microsoft Visual C++, externally accessible symbols must be // explicitly indicated with DLL_API, which is somewhat like "extern." // // The following ifdef block is the standard way of creating macros // which make exporting from a DLL simpler. All files within this DLL // are compiled with the DLL_EXPORTS preprocessor symbol defined on the // command line. In contrast, projects that use (or import) the DLL // objects do not define the DLL_EXPORTS symbol. This way any other // project whose source files include this file see DLL_API functions as // being imported from a DLL, wheras this DLL sees symbols defined with // this macro as being exported. //---------------------------------------------------------------------- #ifdef DLL_EXPORTS #define DLL_API //__declspec(dllexport) #else #define DLL_API //__declspec(dllimport) #endif //---------------------------------------------------------------------- // DLL_API is ignored for all other systems //---------------------------------------------------------------------- #else #define DLL_API #endif //---------------------------------------------------------------------- // basic includes //---------------------------------------------------------------------- #include <cstdlib> // standard lib includes #include <cmath> // math includes #include <iostream> // I/O streams #include <cstring> // C-style strings //---------------------------------------------------------------------- // Limits // There are a number of places where we use the maximum double value as // default initializers (and others may be used, depending on the // data/distance representation). These can usually be found in limits.h // (as LONG_MAX, INT_MAX) or in float.h (as DBL_MAX, FLT_MAX). // // Not all systems have these files. If you are using such a system, // you should set the preprocessor symbol ANN_NO_LIMITS_H when // compiling, and modify the statements below to generate the // appropriate value. For practical purposes, this does not need to be // the maximum double value. It is sufficient that it be at least as // large than the maximum squared distance between between any two // points. //---------------------------------------------------------------------- #ifdef ANN_NO_LIMITS_H // limits.h unavailable #include <cvalues> // replacement for limits.h const double ANN_DBL_MAX = MAXDOUBLE; // insert maximum double #else #include <climits> #include <cfloat> const double ANN_DBL_MAX = DBL_MAX; #endif #define ANNversion "1.1.2" // ANN version and information #define ANNversionCmt "" #define ANNcopyright "David M. Mount and Sunil Arya" #define ANNlatestRev "Jan 27, 2010" //---------------------------------------------------------------------- // ANNbool // This is a simple boolean type. Although ANSI C++ is supposed // to support the type bool, some compilers do not have it. //---------------------------------------------------------------------- enum ANNbool {ANNfalse = 0, ANNtrue = 1}; // ANN boolean type (non ANSI C++) //---------------------------------------------------------------------- // ANNcoord, ANNdist // ANNcoord and ANNdist are the types used for representing // point coordinates and distances. They can be modified by the // user, with some care. It is assumed that they are both numeric // types, and that ANNdist is generally of an equal or higher type // from ANNcoord. A variable of type ANNdist should be large // enough to store the sum of squared components of a variable // of type ANNcoord for the number of dimensions needed in the // application. For example, the following combinations are // legal: // // ANNcoord ANNdist // --------- ------------------------------- // short short, int, long, float, double // int int, long, float, double // long long, float, double // float float, double // double double // // It is the user's responsibility to make sure that overflow does // not occur in distance calculation. //---------------------------------------------------------------------- typedef float ANNcoord; // coordinate data type typedef float ANNdist; // distance data type //---------------------------------------------------------------------- // ANNidx // ANNidx is a point index. When the data structure is built, the // points are given as an array. Nearest neighbor results are // returned as an integer index into this array. To make it // clearer when this is happening, we define the integer type // ANNidx. Indexing starts from 0. // // For fixed-radius near neighbor searching, it is possible that // there are not k nearest neighbors within the search radius. To // indicate this, the algorithm returns ANN_NULL_IDX as its result. // It should be distinguishable from any valid array index. //---------------------------------------------------------------------- typedef int ANNidx; // point index const ANNidx ANN_NULL_IDX = -1; // a NULL point index //---------------------------------------------------------------------- // Infinite distance: // The code assumes that there is an "infinite distance" which it // uses to initialize distances before performing nearest neighbor // searches. It should be as larger or larger than any legitimate // nearest neighbor distance. // // On most systems, these should be found in the standard include // file <limits.h> or possibly <float.h>. If you do not have these // file, some suggested values are listed below, assuming 64-bit // long, 32-bit int and 16-bit short. // // ANNdist ANN_DIST_INF Values (see <limits.h> or <float.h>) // ------- ------------ ------------------------------------ // double DBL_MAX 1.79769313486231570e+308 // float FLT_MAX 3.40282346638528860e+38 // long LONG_MAX 0x7fffffffffffffff // int INT_MAX 0x7fffffff // short SHRT_MAX 0x7fff //---------------------------------------------------------------------- const ANNdist ANN_DIST_INF = ANN_DBL_MAX; //---------------------------------------------------------------------- // Significant digits for tree dumps: // When floating point coordinates are used, the routine that dumps // a tree needs to know roughly how many significant digits there // are in a ANNcoord, so it can output points to full precision. // This is defined to be ANNcoordPrec. On most systems these // values can be found in the standard include files <limits.h> or // <float.h>. For integer types, the value is essentially ignored. // // ANNcoord ANNcoordPrec Values (see <limits.h> or <float.h>) // -------- ------------ ------------------------------------ // double DBL_DIG 15 // float FLT_DIG 6 // long doesn't matter 19 // int doesn't matter 10 // short doesn't matter 5 //---------------------------------------------------------------------- #ifdef DBL_DIG // number of sig. bits in ANNcoord const int ANNcoordPrec = DBL_DIG; #else const int ANNcoordPrec = 15; // default precision #endif //---------------------------------------------------------------------- // Self match? // In some applications, the nearest neighbor of a point is not // allowed to be the point itself. This occurs, for example, when // computing all nearest neighbors in a set. By setting the // parameter ANN_ALLOW_SELF_MATCH to ANNfalse, the nearest neighbor // is the closest point whose distance from the query point is // strictly positive. //---------------------------------------------------------------------- const ANNbool ANN_ALLOW_SELF_MATCH = ANNtrue; //---------------------------------------------------------------------- // Norms and metrics: // ANN supports any Minkowski norm for defining distance. In // particular, for any p >= 1, the L_p Minkowski norm defines the // length of a d-vector (v0, v1, ..., v(d-1)) to be // // (|v0|^p + |v1|^p + ... + |v(d-1)|^p)^(1/p), // // (where ^ denotes exponentiation, and |.| denotes absolute // value). The distance between two points is defined to be the // norm of the vector joining them. Some common distance metrics // include // // Euclidean metric p = 2 // Manhattan metric p = 1 // Max metric p = infinity // // In the case of the max metric, the norm is computed by taking // the maxima of the absolute values of the components. ANN is // highly "coordinate-based" and does not support general distances // functions (e.g. those obeying just the triangle inequality). It // also does not support distance functions based on // inner-products. // // For the purpose of computing nearest neighbors, it is not // necessary to compute the final power (1/p). Thus the only // component that is used by the program is |v(i)|^p. // // ANN parameterizes the distance computation through the following // macros. (Macros are used rather than procedures for // efficiency.) Recall that the distance between two points is // given by the length of the vector joining them, and the length // or norm of a vector v is given by formula: // // |v| = ROOT(POW(v0) # POW(v1) # ... # POW(v(d-1))) // // where ROOT, POW are unary functions and # is an associative and // commutative binary operator mapping the following types: // // ** POW: ANNcoord --> ANNdist // ** #: ANNdist x ANNdist --> ANNdist // ** ROOT: ANNdist (>0) --> double // // For early termination in distance calculation (partial distance // calculation) we assume that POW and # together are monotonically // increasing on sequences of arguments, meaning that for all // v0..vk and y: // // POW(v0) #...# POW(vk) <= (POW(v0) #...# POW(vk)) # POW(y). // // Incremental Distance Calculation: // The program uses an optimized method of computing distances for // kd-trees and bd-trees, called incremental distance calculation. // It is used when distances are to be updated when only a single // coordinate of a point has been changed. In order to use this, // we assume that there is an incremental update function DIFF(x,y) // for #, such that if: // // s = x0 # ... # xi # ... # xk // // then if s' is equal to s but with xi replaced by y, that is, // // s' = x0 # ... # y # ... # xk // // then the length of s' can be computed by: // // |s'| = |s| # DIFF(xi,y). // // Thus, if # is + then DIFF(xi,y) is (yi-x). For the L_infinity // norm we make use of the fact that in the program this function // is only invoked when y > xi, and hence DIFF(xi,y)=y. // // Finally, for approximate nearest neighbor queries we assume // that POW and ROOT are related such that // // v*ROOT(x) = ROOT(POW(v)*x) // // Here are the values for the various Minkowski norms: // // L_p: p even: p odd: // ------------------------- ------------------------ // POW(v) = v^p POW(v) = |v|^p // ROOT(x) = x^(1/p) ROOT(x) = x^(1/p) // # = + # = + // DIFF(x,y) = y - x DIFF(x,y) = y - x // // L_inf: // POW(v) = |v| // ROOT(x) = x // # = max // DIFF(x,y) = y // // By default the Euclidean norm is assumed. To change the norm, // uncomment the appropriate set of macros below. //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Use the following for the Euclidean norm //---------------------------------------------------------------------- #define ANN_POW(v) ((v)*(v)) #define ANN_ROOT(x) sqrt(x) #define ANN_SUM(x,y) ((x) + (y)) #define ANN_DIFF(x,y) ((y) - (x)) //---------------------------------------------------------------------- // Use the following for the L_1 (Manhattan) norm //---------------------------------------------------------------------- // #define ANN_POW(v) fabs(v) // #define ANN_ROOT(x) (x) // #define ANN_SUM(x,y) ((x) + (y)) // #define ANN_DIFF(x,y) ((y) - (x)) //---------------------------------------------------------------------- // Use the following for a general L_p norm //---------------------------------------------------------------------- // #define ANN_POW(v) pow(fabs(v),p) // #define ANN_ROOT(x) pow(fabs(x),1/p) // #define ANN_SUM(x,y) ((x) + (y)) // #define ANN_DIFF(x,y) ((y) - (x)) //---------------------------------------------------------------------- // Use the following for the L_infinity (Max) norm //---------------------------------------------------------------------- // #define ANN_POW(v) fabs(v) // #define ANN_ROOT(x) (x) // #define ANN_SUM(x,y) ((x) > (y) ? (x) : (y)) // #define ANN_DIFF(x,y) (y) //---------------------------------------------------------------------- // Array types // The following array types are of basic interest. A point is // just a dimensionless array of coordinates, a point array is a // dimensionless array of points. A distance array is a // dimensionless array of distances and an index array is a // dimensionless array of point indices. The latter two are used // when returning the results of k-nearest neighbor queries. //---------------------------------------------------------------------- typedef ANNcoord* ANNpoint; // a point typedef ANNpoint* ANNpointArray; // an array of points typedef ANNdist* ANNdistArray; // an array of distances typedef ANNidx* ANNidxArray; // an array of point indices //---------------------------------------------------------------------- // Basic point and array utilities: // The following procedures are useful supplements to ANN's nearest // neighbor capabilities. // // annDist(): // Computes the (squared) distance between a pair of points. // Note that this routine is not used internally by ANN for // computing distance calculations. For reasons of efficiency // this is done using incremental distance calculation. Thus, // this routine cannot be modified as a method of changing the // metric. // // Because points (somewhat like strings in C) are stored as // pointers. Consequently, creating and destroying copies of // points may require storage allocation. These procedures do // this. // // annAllocPt() and annDeallocPt(): // Allocate a deallocate storage for a single point, and // return a pointer to it. The argument to AllocPt() is // used to initialize all components. // // annAllocPts() and annDeallocPts(): // Allocate and deallocate an array of points as well a // place to store their coordinates, and initializes the // points to point to their respective coordinates. It // allocates point storage in a contiguous block large // enough to store all the points. It performs no // initialization. // // annCopyPt(): // Creates a copy of a given point, allocating space for // the new point. It returns a pointer to the newly // allocated copy. //---------------------------------------------------------------------- DLL_API ANNdist annDist( int dim, // dimension of space ANNpoint p, // points ANNpoint q); DLL_API ANNpoint annAllocPt( int dim, // dimension ANNcoord c = 0); // coordinate value (all equal) DLL_API ANNpointArray annAllocPts( int n, // number of points int dim); // dimension DLL_API void annDeallocPt( ANNpoint &p); // deallocate 1 point DLL_API void annDeallocPts( ANNpointArray &pa); // point array DLL_API ANNpoint annCopyPt( int dim, // dimension ANNpoint source); // point to copy //---------------------------------------------------------------------- //Overall structure: ANN supports a number of different data structures //for approximate and exact nearest neighbor searching. These are: // // ANNbruteForce A simple brute-force search structure. // ANNkd_tree A kd-tree tree search structure. ANNbd_tree // A bd-tree tree search structure (a kd-tree with shrink // capabilities). // // At a minimum, each of these data structures support k-nearest // neighbor queries. The nearest neighbor query, annkSearch, // returns an integer identifier and the distance to the nearest // neighbor(s) and annRangeSearch returns the nearest points that // lie within a given query ball. // // Each structure is built by invoking the appropriate constructor // and passing it (at a minimum) the array of points, the total // number of points and the dimension of the space. Each structure // is also assumed to support a destructor and member functions // that return basic information about the point set. // // Note that the array of points is not copied by the data // structure (for reasons of space efficiency), and it is assumed // to be constant throughout the lifetime of the search structure. // // The search algorithm, annkSearch, is given the query point (q), // and the desired number of nearest neighbors to report (k), and // the error bound (eps) (whose default value is 0, implying exact // nearest neighbors). It returns two arrays which are assumed to // contain at least k elements: one (nn_idx) contains the indices // (within the point array) of the nearest neighbors and the other // (dd) contains the squared distances to these nearest neighbors. // // The search algorithm, annkFRSearch, is a fixed-radius kNN // search. In addition to a query point, it is given a (squared) // radius bound. (This is done for consistency, because the search // returns distances as squared quantities.) It does two things. // First, it computes the k nearest neighbors within the radius // bound, and second, it returns the total number of points lying // within the radius bound. It is permitted to set k = 0, in which // case it effectively answers a range counting query. If the // error bound epsilon is positive, then the search is approximate // in the sense that it is free to ignore any point that lies // outside a ball of radius r/(1+epsilon), where r is the given // (unsquared) radius bound. // // The generic object from which all the search structures are // dervied is given below. It is a virtual object, and is useless // by itself. //---------------------------------------------------------------------- class DLL_API ANNpointSet { public: virtual ~ANNpointSet() {} // virtual distructor virtual void annkSearch( // approx k near neighbor search ANNpoint q, // query point int k, // number of near neighbors to return ANNidxArray nn_idx, // nearest neighbor array (modified) ANNdistArray dd, // dist to near neighbors (modified) double eps=0.0 // error bound ) = 0; // pure virtual (defined elsewhere) virtual int annkFRSearch( // approx fixed-radius kNN search ANNpoint q, // query point ANNdist sqRad, // squared radius int k = 0, // number of near neighbors to return ANNidxArray nn_idx = NULL, // nearest neighbor array (modified) ANNdistArray dd = NULL, // dist to near neighbors (modified) double eps=0.0 // error bound ) = 0; // pure virtual (defined elsewhere) virtual int theDim() = 0; // return dimension of space virtual int nPoints() = 0; // return number of points // return pointer to points virtual ANNpointArray thePoints() = 0; }; //---------------------------------------------------------------------- // Brute-force nearest neighbor search: // The brute-force search structure is very simple but inefficient. // It has been provided primarily for the sake of comparison with // and validation of the more complex search structures. // // Query processing is the same as described above, but the value // of epsilon is ignored, since all distance calculations are // performed exactly. // // WARNING: This data structure is very slow, and should not be // used unless the number of points is very small. // // Internal information: // --------------------- // This data structure bascially consists of the array of points // (each a pointer to an array of coordinates). The search is // performed by a simple linear scan of all the points. //---------------------------------------------------------------------- class DLL_API ANNbruteForce: public ANNpointSet { int dim; // dimension int n_pts; // number of points ANNpointArray pts; // point array public: ANNbruteForce( // constructor from point array ANNpointArray pa, // point array int n, // number of points int dd); // dimension ~ANNbruteForce(); // destructor void annkSearch( // approx k near neighbor search ANNpoint q, // query point int k, // number of near neighbors to return ANNidxArray nn_idx, // nearest neighbor array (modified) ANNdistArray dd, // dist to near neighbors (modified) double eps=0.0); // error bound int annkFRSearch( // approx fixed-radius kNN search ANNpoint q, // query point ANNdist sqRad, // squared radius int k = 0, // number of near neighbors to return ANNidxArray nn_idx = NULL, // nearest neighbor array (modified) ANNdistArray dd = NULL, // dist to near neighbors (modified) double eps=0.0); // error bound int theDim() // return dimension of space { return dim; } int nPoints() // return number of points { return n_pts; } ANNpointArray thePoints() // return pointer to points { return pts; } }; //---------------------------------------------------------------------- // kd- and bd-tree splitting and shrinking rules // kd-trees supports a collection of different splitting rules. // In addition to the standard kd-tree splitting rule proposed // by Friedman, Bentley, and Finkel, we have introduced a // number of other splitting rules, which seem to perform // as well or better (for the distributions we have tested). // // The splitting methods given below allow the user to tailor // the data structure to the particular data set. They are // are described in greater details in the kd_split.cc source // file. The method ANN_KD_SUGGEST is the method chosen (rather // subjectively) by the implementors as the one giving the // fastest performance, and is the default splitting method. // // As with splitting rules, there are a number of different // shrinking rules. The shrinking rule ANN_BD_NONE does no // shrinking (and hence produces a kd-tree tree). The rule // ANN_BD_SUGGEST uses the implementors favorite rule. //---------------------------------------------------------------------- enum ANNsplitRule { ANN_KD_STD = 0, // the optimized kd-splitting rule ANN_KD_MIDPT = 1, // midpoint split ANN_KD_FAIR = 2, // fair split ANN_KD_SL_MIDPT = 3, // sliding midpoint splitting method ANN_KD_SL_FAIR = 4, // sliding fair split method ANN_KD_SUGGEST = 5}; // the authors' suggestion for best const int ANN_N_SPLIT_RULES = 6; // number of split rules enum ANNshrinkRule { ANN_BD_NONE = 0, // no shrinking at all (just kd-tree) ANN_BD_SIMPLE = 1, // simple splitting ANN_BD_CENTROID = 2, // centroid splitting ANN_BD_SUGGEST = 3}; // the authors' suggested choice const int ANN_N_SHRINK_RULES = 4; // number of shrink rules //---------------------------------------------------------------------- // kd-tree: // The main search data structure supported by ANN is a kd-tree. // The main constructor is given a set of points and a choice of // splitting method to use in building the tree. // // Construction: // ------------- // The constructor is given the point array, number of points, // dimension, bucket size (default = 1), and the splitting rule // (default = ANN_KD_SUGGEST). The point array is not copied, and // is assumed to be kept constant throughout the lifetime of the // search structure. There is also a "load" constructor that // builds a tree from a file description that was created by the // Dump operation. // // Search: // ------- // There are two search methods: // // Standard search (annkSearch()): // Searches nodes in tree-traversal order, always visiting // the closer child first. // Priority search (annkPriSearch()): // Searches nodes in order of increasing distance of the // associated cell from the query point. For many // distributions the standard search seems to work just // fine, but priority search is safer for worst-case // performance. // // Printing: // --------- // There are two methods provided for printing the tree. Print() // is used to produce a "human-readable" display of the tree, with // indenation, which is handy for debugging. Dump() produces a // format that is suitable reading by another program. There is a // "load" constructor, which constructs a tree which is assumed to // have been saved by the Dump() procedure. // // Performance and Structure Statistics: // ------------------------------------- // The procedure getStats() collects statistics information on the // tree (its size, height, etc.) See ANNperf.h for information on // the stats structure it returns. // // Internal information: // --------------------- // The data structure consists of three major chunks of storage. // The first (implicit) storage are the points themselves (pts), // which have been provided by the users as an argument to the // constructor, or are allocated dynamically if the tree is built // using the load constructor). These should not be changed during // the lifetime of the search structure. It is the user's // responsibility to delete these after the tree is destroyed. // // The second is the tree itself (which is dynamically allocated in // the constructor) and is given as a pointer to its root node // (root). These nodes are automatically deallocated when the tree // is deleted. See the file src/kd_tree.h for further information // on the structure of the tree nodes. // // Each leaf of the tree does not contain a pointer directly to a // point, but rather contains a pointer to a "bucket", which is an // array consisting of point indices. The third major chunk of // storage is an array (pidx), which is a large array in which all // these bucket subarrays reside. (The reason for storing them // separately is the buckets are typically small, but of varying // sizes. This was done to avoid fragmentation.) This array is // also deallocated when the tree is deleted. // // In addition to this, the tree consists of a number of other // pieces of information which are used in searching and for // subsequent tree operations. These consist of the following: // // dim Dimension of space // n_pts Number of points currently in the tree // n_max Maximum number of points that are allowed // in the tree // bkt_size Maximum bucket size (no. of points per leaf) // bnd_box_lo Bounding box low point // bnd_box_hi Bounding box high point // splitRule Splitting method used // //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Some types and objects used by kd-tree functions // See src/kd_tree.h and src/kd_tree.cpp for definitions //---------------------------------------------------------------------- class ANNkdStats; // stats on kd-tree class ANNkd_node; // generic node in a kd-tree typedef ANNkd_node* ANNkd_ptr; // pointer to a kd-tree node class DLL_API ANNkd_tree: public ANNpointSet { protected: int dim; // dimension of space int n_pts; // number of points in tree int bkt_size; // bucket size ANNpointArray pts; // the points ANNidxArray pidx; // point indices (to pts array) ANNkd_ptr root; // root of kd-tree ANNpoint bnd_box_lo; // bounding box low point ANNpoint bnd_box_hi; // bounding box high point void SkeletonTree( // construct skeleton tree int n, // number of points int dd, // dimension int bs, // bucket size ANNpointArray pa = NULL, // point array (optional) ANNidxArray pi = NULL); // point indices (optional) public: ANNkd_tree( // build skeleton tree int n = 0, // number of points int dd = 0, // dimension int bs = 1); // bucket size ANNkd_tree( // build from point array ANNpointArray pa, // point array int n, // number of points int dd, // dimension int bs = 1, // bucket size ANNsplitRule split = ANN_KD_SUGGEST); // splitting method ANNkd_tree( // build from dump file std::istream& in); // input stream for dump file ~ANNkd_tree(); // tree destructor void annkSearch( // approx k near neighbor search ANNpoint q, // query point int k, // number of near neighbors to return ANNidxArray nn_idx, // nearest neighbor array (modified) ANNdistArray dd, // dist to near neighbors (modified) double eps=0.0); // error bound void annkPriSearch( // priority k near neighbor search ANNpoint q, // query point int k, // number of near neighbors to return ANNidxArray nn_idx, // nearest neighbor array (modified) ANNdistArray dd, // dist to near neighbors (modified) double eps=0.0); // error bound int annkFRSearch( // approx fixed-radius kNN search ANNpoint q, // the query point ANNdist sqRad, // squared radius of query ball int k, // number of neighbors to return ANNidxArray nn_idx = NULL, // nearest neighbor array (modified) ANNdistArray dd = NULL, // dist to near neighbors (modified) double eps=0.0); // error bound int theDim() // return dimension of space { return dim; } int nPoints() // return number of points { return n_pts; } ANNpointArray thePoints() // return pointer to points { return pts; } virtual void Print( // print the tree (for debugging) ANNbool with_pts, // print points as well? std::ostream& out); // output stream virtual void Dump( // dump entire tree ANNbool with_pts, // print points as well? std::ostream& out); // output stream virtual void getStats( // compute tree statistics ANNkdStats& st); // the statistics (modified) }; //---------------------------------------------------------------------- // Box decomposition tree (bd-tree) // The bd-tree is inherited from a kd-tree. The main difference // in the bd-tree and the kd-tree is a new type of internal node // called a shrinking node (in the kd-tree there is only one type // of internal node, a splitting node). The shrinking node // makes it possible to generate balanced trees in which the // cells have bounded aspect ratio, by allowing the decomposition // to zoom in on regions of dense point concentration. Although // this is a nice idea in theory, few point distributions are so // densely clustered that this is really needed. //---------------------------------------------------------------------- class DLL_API ANNbd_tree: public ANNkd_tree { public: ANNbd_tree( // build skeleton tree int n, // number of points int dd, // dimension int bs = 1) // bucket size : ANNkd_tree(n, dd, bs) {} // build base kd-tree ANNbd_tree( // build from point array ANNpointArray pa, // point array int n, // number of points int dd, // dimension int bs = 1, // bucket size ANNsplitRule split = ANN_KD_SUGGEST, // splitting rule ANNshrinkRule shrink = ANN_BD_SUGGEST); // shrinking rule ANNbd_tree( // build from dump file std::istream& in); // input stream for dump file }; //---------------------------------------------------------------------- // Other functions // annMaxPtsVisit Sets a limit on the maximum number of points // to visit in the search. // annClose Can be called when all use of ANN is finished. // It clears up a minor memory leak. //---------------------------------------------------------------------- DLL_API void annMaxPtsVisit( // max. pts to visit in search int maxPts); // the limit DLL_API void annClose(); // called to end use of ANN #endif
[ "tcfsh22215@gmail.com" ]
tcfsh22215@gmail.com
836ae33d36f78aac4a74955cc9edcda160a9c07c
f91014eb88ad7c5de1f5ecf923554030f9f8ffd6
/LoginDialog.cpp
04e54f2ffa5cd5c534cc3d6ecf79ebe26bc0c750
[]
no_license
hongning666/HttpClient
2272cf8a9746e57a64722cd41e7d6a8bdc70934b
febf67eb71d35b65c03621f02af0e9790c4b19be
refs/heads/master
2021-09-09T06:15:39.078031
2018-03-14T04:52:25
2018-03-14T04:52:25
125,156,622
0
0
null
null
null
null
UTF-8
C++
false
false
755
cpp
#include "LoginDialog.h" #include "ui_LoginDialog.h" LoginDialog::LoginDialog(QWidget *parent) : QDialog(parent), ui(new Ui::LoginDialog) { ui->setupUi(this); } LoginDialog::~LoginDialog() { delete ui; } //ok按钮对应的槽函数 void LoginDialog::on_buttonBox_accepted() { m_username = ui->usernameEdit->text(); m_password = ui->passwordEdit->text(); accept();//退出登陆窗口的事件循环,返回1 } //cancel按钮对应的槽函数 void LoginDialog::on_buttonBox_rejected() { reject();//退出登陆窗口的事件循环,返回0 } //获取用户名和密码 const QString& LoginDialog::getUsername() { return m_username; } const QString& LoginDialog::getPassword() { return m_password; }
[ "630388893@qq.com" ]
630388893@qq.com
8474a8e5290feec8fe296a89f7fa0fab856a6869
572cdaf9070086eb772ec3696dbd134c65c5c3f0
/200825Baek1913.cpp
34b4c30ba6c74e8b9328abcafcdcf590041e2eaf
[]
no_license
flylofty/coding_test
c701168326c9bd8afba23933f0e8b2088e92078b
7add9020ce3bd709b179c6f388f3fe43e894999c
refs/heads/master
2023-01-19T13:19:13.548871
2020-11-28T09:28:17
2020-11-28T09:28:17
277,563,689
0
0
null
null
null
null
UTF-8
C++
false
false
936
cpp
#include <iostream> #include <vector> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(NULL), cout.tie(NULL); int N = 0; int find; int a, b; int dir[4][2]{ {1, 0}, {0, 1}, {-1, 0}, {0, -1} }; cin >> N; cin >> find; vector<vector<int>> arr(N, vector<int>(N, 0)); int cnt = N * N; int x = -1; int y = 0; int index = 0; for (int i = N; i > 0; --i) { for (int j = i; j > 0; --j) { x = x + dir[index % 4][0]; y = y + dir[index % 4][1]; if (find == cnt) { a = x; b = y; } arr[x][y] = cnt--; } --i; ++index; for (int j = i; j > 0; --j) { x = x + dir[index % 4][0]; y = y + dir[index % 4][1]; if (find == cnt) { a = x; b = y; } arr[x][y] = cnt--; } ++i; ++index; } for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { cout << arr[i][j] << " "; } cout << "\n"; } cout << a+1 << " " << b+1 << "\n"; return 0; }
[ "ljh596088@gmail.com" ]
ljh596088@gmail.com
829107a239f5e189a5ab25a6a98b377f9806ff18
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/webrtc/modules/desktop_capture/desktop_frame.h
35ac8e2475525b71899e9d14538a8889aac88908
[ "Apache-2.0", "LGPL-2.0-or-later", "MIT", "GPL-1.0-or-later", "BSD-3-Clause", "LicenseRef-scancode-google-patent-license-webrtc", "LicenseRef-scancode-google-patent-license-webm", "LicenseRef-scancode-unknown-license-reference" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
9,682
h
/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef MODULES_DESKTOP_CAPTURE_DESKTOP_FRAME_H_ #define MODULES_DESKTOP_CAPTURE_DESKTOP_FRAME_H_ #include <stdint.h> #include <memory> #include <vector> #include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/desktop_region.h" #include "modules/desktop_capture/shared_memory.h" #include "rtc_base/system/rtc_export.h" namespace webrtc { const float kStandardDPI = 96.0f; // DesktopFrame represents a video frame captured from the screen. class RTC_EXPORT DesktopFrame { public: // DesktopFrame objects always hold BGRA data. static const int kBytesPerPixel = 4; virtual ~DesktopFrame(); DesktopFrame(const DesktopFrame&) = delete; DesktopFrame& operator=(const DesktopFrame&) = delete; // Returns the rectangle in full desktop coordinates to indicate it covers // the area of top_left() to top_letf() + size() / scale_factor(). DesktopRect rect() const; // Returns the scale factor from DIPs to physical pixels of the frame. // Assumes same scale in both X and Y directions at present. float scale_factor() const; // Size of the frame. In physical coordinates, mapping directly from the // underlying buffer. const DesktopSize& size() const { return size_; } // The top-left of the frame in full desktop coordinates. E.g. the top left // monitor should start from (0, 0). The desktop coordinates may be scaled by // OS, but this is always consistent with the MouseCursorMonitor. const DesktopVector& top_left() const { return top_left_; } void set_top_left(const DesktopVector& top_left) { top_left_ = top_left; } // Distance in the buffer between two neighboring rows in bytes. int stride() const { return stride_; } // Data buffer used for the frame. uint8_t* data() const { return data_; } // SharedMemory used for the buffer or NULL if memory is allocated on the // heap. The result is guaranteed to be deleted only after the frame is // deleted (classes that inherit from DesktopFrame must ensure it). SharedMemory* shared_memory() const { return shared_memory_; } // Indicates region of the screen that has changed since the previous frame. const DesktopRegion& updated_region() const { return updated_region_; } DesktopRegion* mutable_updated_region() { return &updated_region_; } // DPI of the screen being captured. May be set to zero, e.g. if DPI is // unknown. const DesktopVector& dpi() const { return dpi_; } void set_dpi(const DesktopVector& dpi) { dpi_ = dpi; } // Indicates if this frame may have the mouse cursor in it. Capturers that // support cursor capture may set this to true. If the cursor was // outside of the captured area, this may be true even though the cursor is // not in the image. bool may_contain_cursor() const { return may_contain_cursor_; } void set_may_contain_cursor(bool may_contain_cursor) { may_contain_cursor_ = may_contain_cursor; } // Time taken to capture the frame in milliseconds. int64_t capture_time_ms() const { return capture_time_ms_; } void set_capture_time_ms(int64_t time_ms) { capture_time_ms_ = time_ms; } // Copies pixels from a buffer or another frame. `dest_rect` rect must lay // within bounds of this frame. void CopyPixelsFrom(const uint8_t* src_buffer, int src_stride, const DesktopRect& dest_rect); void CopyPixelsFrom(const DesktopFrame& src_frame, const DesktopVector& src_pos, const DesktopRect& dest_rect); // Copies pixels from another frame, with the copied & overwritten regions // representing the intersection between the two frames. Returns true if // pixels were copied, or false if there's no intersection. The scale factors // represent the ratios between pixel space & offset coordinate space (e.g. // 2.0 would indicate the frames are scaled down by 50% for display, so any // offset between their origins should be doubled). bool CopyIntersectingPixelsFrom(const DesktopFrame& src_frame, double horizontal_scale, double vertical_scale); // A helper to return the data pointer of a frame at the specified position. uint8_t* GetFrameDataAtPos(const DesktopVector& pos) const; // The DesktopCapturer implementation which generates current DesktopFrame. // Not all DesktopCapturer implementations set this field; it's set to // kUnknown by default. uint32_t capturer_id() const { return capturer_id_; } void set_capturer_id(uint32_t capturer_id) { capturer_id_ = capturer_id; } // Copies various information from `other`. Anything initialized in // constructor are not copied. // This function is usually used when sharing a source DesktopFrame with // several clients: the original DesktopFrame should be kept unchanged. For // example, BasicDesktopFrame::CopyOf() and SharedDesktopFrame::Share(). void CopyFrameInfoFrom(const DesktopFrame& other); // Copies various information from `other`. Anything initialized in // constructor are not copied. Not like CopyFrameInfoFrom() function, this // function uses swap or move constructor to avoid data copy. It won't break // the `other`, but some of its information may be missing after this // operation. E.g. other->updated_region_; // This function is usually used when wrapping a DesktopFrame: the wrapper // instance takes the ownership of `other`, so other components cannot access // `other` anymore. For example, CroppedDesktopFrame and // DesktopFrameWithCursor. void MoveFrameInfoFrom(DesktopFrame* other); // Set and get the ICC profile of the frame data pixels. Useful to build the // a ColorSpace object from clients of webrtc library like chromium. The // format of an ICC profile is defined in the following specification // http://www.color.org/specification/ICC1v43_2010-12.pdf. const std::vector<uint8_t>& icc_profile() const { return icc_profile_; } void set_icc_profile(const std::vector<uint8_t>& icc_profile) { icc_profile_ = icc_profile; } // Sets all pixel values in the data buffer to zero. void SetFrameDataToBlack(); // Returns true if all pixel values in the data buffer are zero or false // otherwise. Also returns false if the frame is empty. bool FrameDataIsBlack() const; protected: DesktopFrame(DesktopSize size, int stride, uint8_t* data, SharedMemory* shared_memory); // Ownership of the buffers is defined by the classes that inherit from this // class. They must guarantee that the buffer is not deleted before the frame // is deleted. uint8_t* const data_; SharedMemory* const shared_memory_; private: const DesktopSize size_; const int stride_; DesktopRegion updated_region_; DesktopVector top_left_; DesktopVector dpi_; bool may_contain_cursor_ = false; int64_t capture_time_ms_; uint32_t capturer_id_; std::vector<uint8_t> icc_profile_; }; // A DesktopFrame that stores data in the heap. class RTC_EXPORT BasicDesktopFrame : public DesktopFrame { public: // The entire data buffer used for the frame is initialized with zeros. explicit BasicDesktopFrame(DesktopSize size); ~BasicDesktopFrame() override; BasicDesktopFrame(const BasicDesktopFrame&) = delete; BasicDesktopFrame& operator=(const BasicDesktopFrame&) = delete; // Creates a BasicDesktopFrame that contains copy of `frame`. // TODO(zijiehe): Return std::unique_ptr<DesktopFrame> static DesktopFrame* CopyOf(const DesktopFrame& frame); }; // A DesktopFrame that stores data in shared memory. class RTC_EXPORT SharedMemoryDesktopFrame : public DesktopFrame { public: // May return nullptr if `shared_memory_factory` failed to create a // SharedMemory instance. // `shared_memory_factory` should not be nullptr. static std::unique_ptr<DesktopFrame> Create( DesktopSize size, SharedMemoryFactory* shared_memory_factory); // Takes ownership of `shared_memory`. // Deprecated, use the next constructor. SharedMemoryDesktopFrame(DesktopSize size, int stride, SharedMemory* shared_memory); // Preferred. SharedMemoryDesktopFrame(DesktopSize size, int stride, std::unique_ptr<SharedMemory> shared_memory); ~SharedMemoryDesktopFrame() override; SharedMemoryDesktopFrame(const SharedMemoryDesktopFrame&) = delete; SharedMemoryDesktopFrame& operator=(const SharedMemoryDesktopFrame&) = delete; private: // Avoid unexpected order of parameter evaluation. // Executing both std::unique_ptr<T>::operator->() and // std::unique_ptr<T>::release() in the member initializer list is not safe. // Depends on the order of parameter evaluation, // std::unique_ptr<T>::operator->() may trigger assertion failure if it has // been evaluated after std::unique_ptr<T>::release(). By using this // constructor, std::unique_ptr<T>::operator->() won't be involved anymore. SharedMemoryDesktopFrame(DesktopRect rect, int stride, SharedMemory* shared_memory); }; } // namespace webrtc #endif // MODULES_DESKTOP_CAPTURE_DESKTOP_FRAME_H_
[ "jengelh@inai.de" ]
jengelh@inai.de
258c84b084c455df047d5cffe2ed73fa6169837e
642569762c24a1a35c44a885c8e3d36faaace496
/database3/include/Comunicacion.h
40f61b1b92345742d907be59cc41ed3aad7d4c4a
[]
no_license
clau1899/BaseDeDatos
04f5e2bda821d5c801a383ceafd41a17a4d68006
1609f87e912b86167ed31d5234ea1653d509621d
refs/heads/master
2020-03-19T12:42:36.846147
2018-07-07T21:05:20
2018-07-07T21:05:20
136,534,927
0
0
null
null
null
null
UTF-8
C++
false
false
262
h
#ifndef COMUNICACION_H #define COMUNICACION_H #include <Curso.h> #include <string> using namespace std; class Comunicacion : public Curso { public: Comunicacion(); virtual ~Comunicacion(); string tema; }; #endif // COMUNICACION_H
[ "cpc1899@gmail.com" ]
cpc1899@gmail.com
6f53600a4679c953ae07ead2d096a0e26d31a0f4
45c7a30aa5f151f54211cab18d5ff8873d57ed25
/projectUI/Exam_TT__.cpp
63b419beae3204e01e170456b25fa6184b55385e
[]
no_license
VineetMalik14/IITG_AcadSectionManagementSystem
0b860cd0a4d2f904938df6d41a21277306f13bcc
60461e482eba4b1123322559d5bfc132155161c2
refs/heads/master
2020-06-20T16:05:58.647280
2019-07-17T21:35:22
2019-07-17T21:35:22
197,171,977
0
0
null
2019-07-16T10:22:11
2019-07-16T10:22:11
null
UTF-8
C++
false
false
47
cpp
#include "StdAfx.h" #include "Exam_TT__.h"
[ "vineetmalik03@gmail.com" ]
vineetmalik03@gmail.com
d3e3d6ac4a7e7659714dcc9679f98da87701bb66
7e6cf43c62e03e7eb55b7121679be1fd4b43dcb3
/TP2/SystemC2.0.1_Modifié/src/systemc/utils/sc_report_handler.cpp
c39eabcfbd1e811fa7b3a64dbceda811a9729dcc
[]
no_license
alePereira/INF6600
8bef0ed584f0d24efcd2b3515d4319fe98dae3a5
501c70861b6bc508f6feb19410789966e26ca0e8
refs/heads/master
2020-04-03T09:57:18.542595
2016-11-16T16:38:58
2016-11-16T16:38:58
69,587,723
0
0
null
null
null
null
UTF-8
C++
false
false
4,913
cpp
/***************************************************************************** The following code is derived, directly or indirectly, from the SystemC source code Copyright (c) 1996-2002 by all Contributors. All Rights reserved. The contents of this file are subject to the restrictions and limitations set forth in the SystemC Open Source License Version 2.3 (the "License"); You may not use this file except in compliance with such restrictions and limitations. You may obtain instructions on how to receive a copy of the License at http://www.systemc.org/. Software distributed by Contributors under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. *****************************************************************************/ /***************************************************************************** sc_report_handler.cpp - Original Author: Martin Janssen, Synopsys, Inc. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include "systemc/utils/sc_exception.h" #include "systemc/utils/sc_iostream.h" #include "systemc/utils/sc_report_handler.h" #include "systemc/utils/sc_stop_here.h" #include "systemc/kernel/sc_simcontext.h" #include "systemc/kernel/sc_process_b.h" // ---------------------------------------------------------------------------- // CLASS : sc_report_handler // // Default report handler class. // ---------------------------------------------------------------------------- // for your own handler, change the handler name #define HANDLER_NAME sc_report_handler static HANDLER_NAME*& the_handler() { static HANDLER_NAME* handler = 0; return handler; } void HANDLER_NAME::install() { if( the_handler() == 0 ) { the_handler() = new HANDLER_NAME; } the_handler()->install_(); } void HANDLER_NAME::deinstall() { if( the_handler() != 0 ) { the_handler()->deinstall_(); } } HANDLER_NAME::HANDLER_NAME() {} HANDLER_NAME::~HANDLER_NAME() {} static const sc_string compose_message( sc_severity severity, int id, const char* add_msg, const char* file, int line ) { sc_string str; const char* severity_names[] = { "Info", "Warning", "Error", "Fatal" }; str += severity_names[severity]; str += ": "; str += "("; str += "IWEF"[severity]; str += sc_string::to_string( "%d", id ); str += ")"; const char* msg = sc_report::get_message( id ); if( msg != 0 && *msg != 0 ) { str += " "; str += msg; } if( add_msg != 0 && *add_msg != 0 ) { str += ": "; str += add_msg; } if( severity != SC_INFO ) { str += "\nIn file: "; str += file; str += ":"; str += sc_string::to_string( "%d", line ); sc_simcontext* simc = sc_get_curr_simcontext(); if( simc->is_running() ) { sc_process_b* p = simc->get_curr_proc_info()->process_handle; if( p != 0 ) { str += "\nIn process: "; str += p->name(); str += " @ "; str += sc_time_stamp().to_string(); } } } return str; } // for your own handler, change the body of this function void HANDLER_NAME::report( sc_severity severity, int id, const char* add_msg, const char* file, int line ) { switch( severity ) { case SC_INFO: { if( m_suppress_infos ) { return; } if( sc_report::is_suppressed( id ) ) { return; } cout << "\n"; cout << compose_message( severity, id, add_msg, file, line ) << endl; break; } case SC_WARNING: { if( m_make_warnings_errors ) { severity = SC_ERROR; // fall through to SC_ERROR } else { if( m_suppress_warnings ) { return; } if( sc_report::is_suppressed( id ) ) { return; } sc_stop_here( id, severity ); cout << "\n"; cout << compose_message( severity, id, add_msg, file, line ) << endl; break; } } case SC_ERROR: { sc_stop_here( id, severity ); throw sc_exception( compose_message( severity, id, add_msg, file, line ) ); } case SC_FATAL: { sc_stop_here( id, severity ); cout << "\n"; cout << compose_message( severity, id, add_msg, file, line ) << endl; abort(); } } } // for your own handler, change the handler garbage collector name #define HANDLER_GC_NAME sc_report_handler_gc class HANDLER_GC_NAME { public: ~HANDLER_GC_NAME() { if( the_handler() != 0 ) { delete the_handler(); } } }; static HANDLER_GC_NAME gc; // Taf!
[ "chathura.namalgamuwa@ensimag.grenoble-inp.fr" ]
chathura.namalgamuwa@ensimag.grenoble-inp.fr
dbcade49f03eb9eb7877c6644ae89639599f83cd
2075fd64d072fca5f88b4fbe2c2397a3f12a29bd
/mediatek/platform/mt6577/hardware/audio/aud_drv/AudioYusuStreamHandler.cpp
aae874fa7644d67672add694300451579de3bba0
[]
no_license
4Fwolf/signal75-77_kernel_3.4.67
380fc4cee56b52060da78eecfa70a4ecea5f1278
bcca0b70dc87e8ba7af8878666076f7baf6c6b7a
HEAD
2016-09-01T16:01:49.247082
2016-01-29T09:56:21
2016-01-29T09:56:21
48,953,336
1
3
null
null
null
null
UTF-8
C++
false
false
39,387
cpp
/***************************************************************************** * Copyright Statement: * -------------------- * This software is protected by Copyright and the information contained * herein is confidential. The software may not be copied and the information * contained herein may not be used or disclosed except with the written * permission of MediaTek Inc. (C) 2009 * * BY OPENING THIS FILE, BUYER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO BUYER ON * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT. * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR * SUPPLIED WITH THE MEDIATEK SOFTWARE, AND BUYER AGREES TO LOOK ONLY TO SUCH * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. MEDIATEK SHALL ALSO * NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE RELEASES MADE TO BUYER'S * SPECIFICATION OR TO CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM. * * BUYER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND CUMULATIVE * LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY BUYER TO * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * THE TRANSACTION CONTEMPLATED HEREUNDER SHALL BE CONSTRUED IN ACCORDANCE * WITH THE LAWS OF THE STATE OF CALIFORNIA, USA, EXCLUDING ITS CONFLICT OF * LAWS PRINCIPLES. ANY DISPUTES, CONTROVERSIES OR CLAIMS ARISING THEREOF AND * RELATED THERETO SHALL BE SETTLED BY ARBITRATION IN SAN FRANCISCO, CA, UNDER * THE RULES OF THE INTERNATIONAL CHAMBER OF COMMERCE (ICC). * *****************************************************************************/ /******************************************************************************* * * Filename: * --------- * AudioYusuStreamHandler.cpp * * Project: * -------- * Yusu * * Description: * ------------ * class and typedef of stream * * Author: * ------- * ChiPeng Chang (mtk02308) * * *------------------------------------------------------------------------------ * $Revision: #24 $ * $Modtime:$ * $Log:$ * * 03 21 2013 weiguo.li * [ALPS00508995] [Need Patch] [Volunteer Patch]6577 for 4.2 migration * update new device * * 03 20 2013 weiguo.li * [ALPS00508995] [Need Patch] [Volunteer Patch]6577 for 4.2 migration * update devicerouting * * 04 10 2012 weiguo.li * [ALPS00266592] [Need Patch] [Volunteer Patch] ICS_MP patchback to ALPS.ICS of Audio * . * * 04 06 2012 weiguo.li * [ALPS00264069] A52ΪػٶȵŻ * . * * 02 13 2012 weiguo.li * [ALPS00233775] [mATV][ICS][Line in]Preview will freeze when mute/unmute * . * * 01 05 2012 weiguo.li * [ALPS00108538] [Need Patch] [Volunteer Patch]patch from GB2 to alpsDev4.0 * . * * 11 17 2011 weiguo.li * [ALPS00090606] [WW FT][MT6575][Quanzhou][Overnight]Native (NE) in call * . * * 10 20 2011 weiguo.li * [ALPS00081607] [Need Patch] [Volunteer Patch]add headphone control * . * * 07 13 2010 chipeng.chang * [ALPS00121732][FactoryMode] Error in headset when enter it with headset plugged in * fix for factory mode . * * 07 07 2010 chipeng.chang * [ALPS00002905][Need Patch] [Volunteer Patch] add for input log * update for audio input logging. * * 06 11 2010 chipeng.chang * [ALPS00008012][Phone sound] The volume is very small and have noise. * when create track with 0 samplerate , return hardware samplerate as track's samplerate. * * 06 09 2010 chipeng.chang * [ALPS00007771][Music] Have no sound when play imy file. * modify mode change open oudpsk sequence. * * 06 01 2010 chipeng.chang * [ALPS00002042][Patch rule] If you fix the issue, please check-in your code and choose the correct type on the CR you use to check in BU Spec tab, thanks. * patch for I2S driver and add AudioyusuI2sTreamin for record * * 05 04 2010 chipeng.chang * [ALPS00001963][Need Patch] [Volunteer Patch] ALPS.10X.W10.11 Volunteer patch for * modify pvplayer audio when pause , it will read partial when clock is set to pause. * * 04 30 2010 chipeng.chang * [ALPS00005299][Call](PhoneApp)] It show Call not sent and native exception * add mutex for Ladplyer let audiohardware don't delete it. * *******************************************************************************/ #include <string.h> #include <stdint.h> #include <sys/types.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <sched.h> #include <fcntl.h> #include <sys/ioctl.h> #define LOG_TAG "AudioStreamHandler" #include <utils/Log.h> #include <utils/String8.h> #include <AudioYusuHardware.h> #include <AudioYusuStreamHandler.h> #include "AudioYusuDef.h" #include "AudioYusuLadPlayer.h" #include "AudioYusuLad.h" #include "AudioStreamInHandler.h" #ifdef ENABLE_LOG_STREAMHANDLER #define LOG_STREAMHANDLER ALOGD #else #define LOG_STREAMHANDLER ALOGV #endif #define HEADPHONE_CONTROL namespace android { // ---------------------------------------------------------------------------- AudioAttribute::AudioAttribute() { mFormat = 0; mSampleRate = 0; mChannelCount = 0; } AudioAttribute::~AudioAttribute() { } InputStreamAttribute::InputStreamAttribute() { mFormat = 0; mSampleRate = 0; mChannelCount = 0; mDevices = 0; mAcoustics = android_audio_legacy::AudioSystem::AGC_DISABLE; } InputStreamAttribute::~InputStreamAttribute() { } AudioStreamHandler::AudioStreamHandler(int Fd, AudioYusuHardware *hw, AudioAfe *Afehdr, AudioAnalog *AnaReg) { int err = -1; mFd = 0; for (int i = 0; i < MAX_OUTPUT_STREAM_NUM ; i++) { mOutput[i] = NULL; } for (int i = 0; i < MAX_INPUT_STREAM_NUM ; i++) { mInput[i] = NULL; mI2SInput[i] = NULL; } mAudioHardware = hw; mSrcBlockOccupy = 0; mSrcBlockRunning = false; mSetBTSCOSamplerateAtStartRunning = false; mRestoreSamplerateAtStartRunning = false; mFd = Fd; mAfe_handle = Afehdr; mAnaReg = AnaReg; mSrcBlockRunningNum = 0; mLadPlayerMode = 0; mI2SInstance = NULL; I2SClient = 0; echo_reference = NULL; pthread_mutex_init(&mInputstreamMutex, NULL); pthread_mutex_init(&mOutputstreamMutex, NULL); mI2SInstance = AudioI2S::getInstance(); I2SClient = mI2SInstance->open(); LOG_STREAMHANDLER("AudioStreamHandler constructor "); } AudioStreamHandler::~AudioStreamHandler() { // Delete all input/output stream for (int i = 0; i < MAX_OUTPUT_STREAM_NUM; i++) { if (mOutput != NULL) { delete mOutput[i]; mOutput[i] = NULL; } } for (int i = 0; i < MAX_INPUT_STREAM_NUM; i++) { if (mInput[i] != NULL) { delete mInput[i]; mInput[i] = NULL; } if (mI2SInput[i] != NULL) { delete mI2SInput[i]; mI2SInput[i] = NULL; } } echo_reference = NULL; } int AudioStreamHandler::FindFreeOutputStream() { int i; for (i = 0; i < MAX_OUTPUT_STREAM_NUM; i++) { if (mOutput[i] == NULL) { break; } } if (i < MAX_OUTPUT_STREAM_NUM) { return i; } else { return -1; } } int AudioStreamHandler::FindMatchOutputStream(android_audio_legacy::AudioStreamOut *out) { int i = -1; for (i = 0 ; i < MAX_OUTPUT_STREAM_NUM ; i++) { if (mOutput[i] == out) { break; } } if (i < MAX_OUTPUT_STREAM_NUM) { return i; } else { return -1; } } int AudioStreamHandler::FindFreeInputStream() { int i = -1; for (i = 0 ; i < MAX_INPUT_STREAM_NUM ; i++) { if (mInput[i] == NULL) { break; } } if (i < MAX_INPUT_STREAM_NUM) { return i; } else { return -1; } } int AudioStreamHandler::FindFreeI2SInputStream() { int i = -1; for (i = 0 ; i < MAX_INPUT_STREAM_NUM ; i++) { if (mI2SInput[i] == NULL) { break; } } if (i < MAX_INPUT_STREAM_NUM) { return i; } else { return -1; } } int AudioStreamHandler::FindMatchInputStream(android_audio_legacy::AudioStreamIn *in) { int i; for (i = 0 ; i < MAX_INPUT_STREAM_NUM ; i++) { if (mInput[i] == in) { break; } } if (i < MAX_INPUT_STREAM_NUM) { return i; } else { return -1; } } int AudioStreamHandler::FindMatchInputI2SStream(android_audio_legacy::AudioStreamIn *in) { int i; for (i = 0 ; i < MAX_INPUT_STREAM_NUM ; i++) { if (mI2SInput[i] == in) { break; } } if (i < MAX_INPUT_STREAM_NUM) { return i; } else { return -1; } } bool AudioStreamHandler::SetI2SControl(bool bEnable, int type, uint32 SampleRate) { if (mI2SInstance == NULL) { ALOGE("SetI2SControl mI2SInstance == NULL"); return false; } if (bEnable == true) { return mI2SInstance->start(I2SClient, (I2STYPE)type, SampleRate); } else if (bEnable == false) { return mI2SInstance->stop(I2SClient, (I2STYPE)type); } return true; } AnalogAFE_Mux AudioStreamHandler::FindDeviceWithMux(int device) { ALOGD("FindDeviceWithMux device = %d", device); if (device == AUDIO_DEVICE_OUT_EARPIECE) { return VOICE_PATH; } else if (device == AUDIO_DEVICE_OUT_SPEAKER || device == AUDIO_DEVICE_OUT_WIRED_HEADSET || device == AUDIO_DEVICE_OUT_WIRED_HEADPHONE) { return AUDIO_PATH; } else if (device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO || device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET || device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT) { return AUDIO_PATH; } else { ALOGW("FindDeviceWithMux warning "); return AUDIO_PATH; } } void AudioStreamHandler::AudioStartRunning(unsigned int OutStreamIndex, unsigned int InterruptCounter) { LOG_STREAMHANDLER("+AudioStartRunning InterruptCounter = %d", InterruptCounter); int mode = 0, mCurrentDevice = 0; //ALPS00264744 pthread_mutex_lock(&mAudioHardware->HardwareOnOffMutex); LOG_STREAMHANDLER("AudioStartRunning, Get HardwareOnOffMutex"); //~ALPS00264744 float volume = mAudioHardware->mVolumeController->getMasterVolume(); pthread_mutex_lock(&mAudioHardware->MasterVolumeMutex); int voice_status = mAudioHardware->GetVoiceStatus(); int comunication_status = mAudioHardware->GetCommunicationStatus(); mAudioHardware->getMode(&mode); mAudioHardware->mAnaReg->AnalogAFE_Request_ANA_CLK(); //[ALPS073048]Hardly no sound in alarm after IPO if (voice_status == false) { ::ioctl(mFd, AUDDRV_BEE_IOCTL, 0x10); mAudioHardware->setMasterVolume(volume);//restore analog gain. mAudioHardware->restoreAnalogGain(); UINT32 u4AnaCon_1, u4AnaCon_2; mAnaReg->GetAnaReg(AUDIO_CON1, &u4AnaCon_1); mAnaReg->GetAnaReg(AUDIO_CON2, &u4AnaCon_2); LOG_STREAMHANDLER("AudioStartRunning::Con1(0x%x),Con2(0x%x)", u4AnaCon_1, u4AnaCon_2); } SetSrcBlockRunning(true); if (mRestoreSamplerateAtStartRunning == true) { ALOGD("AudioStartRunning mRestoreSamplerateAtStartRunning is true!!!"); mRestoreSamplerateAtStartRunning = false; for (int i = 0; i < MAX_OUTPUT_STREAM_NUM ; i++) { mOutput[i]->RestoreOutSamplerate(); } int interval = mOutput[0]->GetInterrupttime(); ALOGD("AudioStartRunning Afe_Set_Timer =%d\n", interval); mAfe_handle->Afe_Set_Timer(IRQ1_MCU, interval); } else if (mSetBTSCOSamplerateAtStartRunning == true) { ALOGD("AudioStartRunning mSetBTSCOSamplerateAtStartRunning is true!!!"); uint32 BTSCO_SAMPLERATE = (mAfe_handle->mDaiBtMode == 0) ? 8000 : 16000; mSetBTSCOSamplerateAtStartRunning = false; for (int i = 0; i < MAX_OUTPUT_STREAM_NUM ; i++) { mOutput[i]->SetBTscoSamplerate(BTSCO_SAMPLERATE); } int interval = ASM_BUFFER_SIZE / 3; // skype interval = interval >> 2; InterruptCounter = interval; ALOGD("AudioStartRunning InterruptCounter =%d\n", InterruptCounter); } LOG_STREAMHANDLER("AudioStartRunning, +Afe_DL_Start"); // situation to open FM pinmux , if (mAudioHardware->GetFmAnalogInEnable() && mode == android_audio_legacy::AudioSystem::MODE_NORMAL) { //No Need to open audio hw, causing pop noise. (ALPS00237555) //mAnaReg->AnalogAFE_Depop(FM_STEREO_AUDIO,false); //mAnaReg->AnalogAFE_Depop(AUDIO_PATH,true); } // should open with COMMUNCATION mode , COMMUNICATION mode can open handset , headset. else if (mode == android_audio_legacy::AudioSystem::MODE_IN_COMMUNICATION) { int device = mAudioHardware->GetCurrentDevice(); mAnaReg->AnalogAFE_Open(FindDeviceWithMux(device)); } else { int device = mAudioHardware->GetCurrentDevice(); // do not open audiopath if earpiece is used in normal mode because voiepath is opened if (device == AUDIO_DEVICE_OUT_EARPIECE && (mode == android_audio_legacy::AudioSystem::MODE_NORMAL || mode == android_audio_legacy::AudioSystem::MODE_RINGTONE)) { LOG_STREAMHANDLER("AudioStartRunning,Open VOICE_PATH"); mAnaReg->AnalogAFE_Open(VOICE_PATH); mAudioHardware->EnableEarpiece(); } else { mAnaReg->AnalogAFE_Open(AUDIO_PATH); } } mAudioHardware->toggleCurrentDevices(true); usleep(100); mCurrentDevice = mAudioHardware->GetCurrentDevice() ; ALOGD("AudioStartRunning mCurrentDevice = 0x%x", mCurrentDevice); // Priority: HDMI > FM-Tx > Speaker if (mAudioHardware->GetHDMIAudioStatus() == true) { // use for HDMI case mAfe_handle->Afe_DL_Start(AFE_MODE_I2S1_OUT_HDMI); } else if (mCurrentDevice == AUDIO_DEVICE_OUT_AUX_DIGITAL) { #ifdef FM_DIGITAL_OUT_SUPPORT mAfe_handle->Afe_DL_Start(AFE_MODE_I2S0_OUT); #else mAfe_handle->Afe_DL_Start(AFE_MODE_DAC); #endif } else if (comunication_status) { ALOGD("comunication_status mAfe_handle->Afe_DL_Start();"); int device = mAudioHardware->GetCurrentDevice(); if (device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO || device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET || device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT) { mAfe_handle->Afe_Set_Timer(IRQ1_MCU, InterruptCounter); mAfe_handle->Afe_DL_Start(AFE_MODE_DAI); } else { mAfe_handle->Afe_DL_Start(AFE_MODE_DAC); } mAudioHardware->setVoiceVolume(mAudioHardware->mVolumeController->getVoiceVolume()); } else if (mCurrentDevice == AUDIO_DEVICE_OUT_BLUETOOTH_SCO || mCurrentDevice == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET || mCurrentDevice == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT) // skype { ALOGD("AudioStartRunning DEVICE_OUT_BLUETOOTH_SCO mAfe_handle->Afe_DL_Start();"); mAfe_handle->Afe_Set_Timer(IRQ1_MCU, InterruptCounter); mAfe_handle->Afe_DL_Start(AFE_MODE_DAI); } else { #ifdef ENABLE_EXT_DAC ALOGD("ENABLE_EXT_DAC"); mAfe_handle->Afe_DL_Start(AFE_MODE_I2S1_OUT); #endif mAfe_handle->Afe_DL_Start(AFE_MODE_DAC); } // mAfe_handle->Afe_DL_Unmute(AFE_MODE_DAC); mAudioHardware->mAnaReg->AnalogAFE_Release_ANA_CLK(); pthread_mutex_unlock(&mAudioHardware->MasterVolumeMutex); //ALPS00264744 pthread_mutex_unlock(&mAudioHardware->HardwareOnOffMutex); LOG_STREAMHANDLER("AudioStartRunning, Release HardwareOnOffMutex"); //~ALPS00264744 ::ioctl(mFd, AUDDRV_BEE_IOCTL, 0x11); int WaitForInterrupt = ((InterruptCounter * 1000) + (mOutput[0]->sampleRate() >> 1)) / mOutput[0]->sampleRate(); usleep(WaitForInterrupt * 1000); LOG_STREAMHANDLER("-AudioStartRunning"); } void AudioStreamHandler::AudioStopRunning() { int voice_status, mCurrentDevice = 0, mPreViousDevice = 0; LOG_STREAMHANDLER("!! AudioStopRunning"); Mutex::Autolock _l(mLock); mAfe_handle->Afe_DL_Mute(AFE_MODE_DAC); usleep(10 * 1000); voice_status = mAudioHardware->GetVoiceStatus(); pthread_mutex_lock(&mAudioHardware->MasterVolumeMutex); float mVolume = mAudioHardware->mVolumeController->getMasterVolume(); /* //Move to AnalogAFE_Close if(voice_status == false){ mAudioHardware->setMasterVolume(0); } */ ::ioctl(mFd, AUDDRV_BEE_IOCTL, 0x30); SetSrcBlockRunning(false); if (mAudioHardware->Get_Recovery_Speech() == false && mAudioHardware->GetVoiceStatus() == false && mAudioHardware->GetAnalogLineinEnable() == false) { // no voice and no FM mAudioHardware->toggleCurrentDevices(false); } else if (mAudioHardware->GetAnalogLineinEnable() == true && mAudioHardware->GetVoiceStatus() == false) { // turn on device? } mAnaReg->AnalogAFE_Close(AUDIO_PATH); mCurrentDevice = mAudioHardware->GetCurrentDevice() ; mPreViousDevice = mAudioHardware->GetPreviousDevice(); /* ALOGD("AudioStopRunning mCurrentDevice = 0x%x mPreViousDevice = %x prestate = %d", mCurrentDevice,mPreViousDevice,mAudioHardware->getPreviousMode());*/ //if((mAudioHardware->getPreviousMode() == android_audio_legacy::AudioSystem::MODE_IN_COMMUNICATION) && if (((mAudioHardware->getPreviousMode() == android_audio_legacy::AudioSystem::MODE_IN_COMMUNICATION) || (mAudioHardware->getPreviousMode() == android_audio_legacy::AudioSystem::MODE_NORMAL)) && // skype (mPreViousDevice == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET || mPreViousDevice == AUDIO_DEVICE_OUT_BLUETOOTH_SCO || mPreViousDevice == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT) && (!voice_status)) { ALOGD("AudioStopRunning DEVICE_OUT_BLUETOOTH_SCO mAfe_handle->Afe_DL_Stop(AFE_MODE_DAI)"); mAfe_handle->Afe_DL_Stop(AFE_MODE_DAI); } // Priority: HDMI > FM-Tx > Speaker if (mAudioHardware->GetHDMIAudioStatus() == true) { // use for HDMI case mAfe_handle->Afe_DL_Stop(AFE_MODE_I2S1_OUT_HDMI); } else if (mCurrentDevice == AUDIO_DEVICE_OUT_AUX_DIGITAL) { #ifdef FM_DIGITAL_OUT_SUPPORT mAfe_handle->Afe_DL_Stop(AFE_MODE_I2S0_OUT); #else mAfe_handle->Afe_DL_Stop(AFE_MODE_DAC); #endif } else { #ifdef ENABLE_EXT_DAC ALOGD("ENABLE_EXT_DAC"); mAfe_handle->Afe_DL_Stop(AFE_MODE_I2S1_OUT); #endif mAfe_handle->Afe_DL_Stop(AFE_MODE_DAC); } mAfe_handle->Afe_DL_Unmute(AFE_MODE_DAC); /* //Move to AnalogAFE_Close if(voice_status == false){ mAudioHardware->setMasterVolume(mVolume); } */ pthread_mutex_unlock(&mAudioHardware->MasterVolumeMutex); ::ioctl(mFd, AUDDRV_BEE_IOCTL, 0x31); } void AudioStreamHandler::SetSrcBlockRunning(bool Running) { mSrcBlockRunning = Running; } bool AudioStreamHandler::GetSrcBlockRunning(void) { return mSrcBlockRunning; } void AudioStreamHandler::AddSrcRunningNumber(void) { mSrcBlockRunningNum++; ALOGD("AddSrcRunningNumber mSrcBlockRunningNum:%d", mSrcBlockRunningNum); } void AudioStreamHandler::MinusSrcRunningNumber(void) { mSrcBlockRunningNum--; ALOGD("MinusSrcRunningNumber mSrcBlockRunningNum:%d", mSrcBlockRunningNum); } int AudioStreamHandler::GetSrcRunningNumber(void) { ALOGD("GetSrcRunningNumber, mSrcBlockRunningNum:%d", mSrcBlockRunningNum); return mSrcBlockRunningNum; } android_audio_legacy::AudioStreamOut *AudioStreamHandler::openOutputStream( uint32 devices, int *format, uint32_t *channelCount, uint32_t *sampleRate, status_t *status) { int Stream_index = this->FindFreeOutputStream(); ALOGD("openOutputStream "); // find a free stream if (Stream_index < 0 || Stream_index >= MAX_OUTPUT_STREAM_NUM) { LOG_STREAMHANDLER("openOutputStream, no free stream available"); return NULL; } // open and init an output stream AudioYusuStreamOut *out = new AudioYusuStreamOut(); if (out->InitOutStream(Stream_index, mFd) != true) { LOG_STREAMHANDLER("openOutputStream, initStream fail"); } // Check the Attribute if (*format == 0) { *format = android_audio_legacy::AudioSystem::PCM_16_BIT; } if (*channelCount == 0) { *channelCount = android_audio_legacy::AudioSystem::CHANNEL_OUT_STEREO; } if (*sampleRate == 0) { LOG_STREAMHANDLER("openOutputStream, set SR defauult(44100)"); *sampleRate = 44100; } ALOGD("openOutputStream, format=%d ,channels=%d, rate=%d", *format, *channelCount, *sampleRate); status_t lStatus = out->set(this->mAudioHardware, mFd, devices, format, channelCount, sampleRate); if (status) { *status = lStatus; } if (lStatus == NO_ERROR) { mOutput[Stream_index] = out; } else { delete out; // impossible } return mOutput[Stream_index]; } void AudioStreamHandler::closeOutputStream(android_audio_legacy::AudioStreamOut *out) { int Stream_index = this->FindMatchOutputStream(out); LOG_STREAMHANDLER("closeOutputStream"); if (Stream_index < 0) { LOG_STREAMHANDLER("closeOutputStream, no match stream available"); return; } if (mOutput[Stream_index] != NULL) { ALOGD("delete mOutput[%d] ",Stream_index); delete mOutput[Stream_index]; mOutput[Stream_index] = NULL; return; } } void AudioStreamHandler::StoreInputStreamAttribute(uint32 devices, int *format, uint32_t *channelCount, uint32_t *sampleRate, android_audio_legacy::AudioSystem::audio_in_acoustics acoustics) { ALOGD("StoreInputStreamAttribute (%d, %u, %u)", *format, *channelCount, *sampleRate); mInputAttribure[0].mSampleRate = *sampleRate; mInputAttribure[0].mFormat = *format; mInputAttribure[0].mChannelCount = *channelCount; mInputAttribure[0].mDevices = devices; mInputAttribure[0].mAcoustics = acoustics; } android_audio_legacy::AudioStreamIn *AudioStreamHandler::openInputStream( uint32 devices, int *format, uint32 *channelCount, uint32_t *sampleRate, status_t *status, android_audio_legacy::AudioSystem::audio_in_acoustics acoustics) { int Stream_index = -1; ALOGD("+openInputStream devices = %x format = %d channelCount = %d samplerate = %d", devices, *format, *channelCount, *sampleRate); // handle for use digital input stream if (devices == AUDIO_DEVICE_IN_AUX_DIGITAL) { ALOGD("openInputStream devices == AUDIO_DEVICE_IN_AUX_DIGITAL"); // no input available Stream_index = this->FindFreeInputStream(); if (Stream_index < 0 || Stream_index >= MAX_INPUT_STREAM_NUM) { ALOGD("openInputStream :: no free stream available"); return NULL; } // only one input stream allowed if (mI2SInput[Stream_index]) { if (status) { *status = INVALID_OPERATION; } return 0; } // create new Input stream AudioYusuI2SStreamIn *in = new AudioYusuI2SStreamIn(); status_t lStatus = in->set(this->mAudioHardware, mFd, devices, format, channelCount, sampleRate, acoustics); if (status) { *status = lStatus; } if (lStatus == NO_ERROR) { mI2SInput[Stream_index] = in; } else { delete in; } return mI2SInput[Stream_index]; } Stream_index = this->FindFreeInputStream(); if (Stream_index < 0 || Stream_index >= MAX_INPUT_STREAM_NUM) { ALOGD("openInputStream :: no free stream available"); return NULL; } // only one input stream allowed if (mInput[Stream_index]) { if (status) { *status = INVALID_OPERATION; } return 0; } AudioStreamInInterface *in = NULL; status_t lStatus = NO_ERROR; // create new Input stream , base on samplerate and vm flag int mode = 0; mAudioHardware->getMode(&mode); in = new AudioStreamInHandler(this->mAudioHardware); if (Stream_index == 1) { ALOGD("Warning : Opend 2nd StreamIn"); devices = 0xFFFFFFFF; } lStatus = in->set(this->mAudioHardware, mFd, devices, format, channelCount, sampleRate, acoustics); ALOGD("set return lStatus = %d", lStatus); StoreInputStreamAttribute(devices, format, channelCount, sampleRate, acoustics); if (status) { *status = lStatus; } if (lStatus == NO_ERROR) { mInput[Stream_index] = in; } else { delete in; return 0; } ALOGD("-openInputStream, mInput create"); return mInput[Stream_index]; } void AudioStreamHandler::closeInputStream(android_audio_legacy::AudioStreamIn *in) { int Stream_index = this->FindMatchInputStream(in); ALOGD("closeInputStream:index=%x", Stream_index); if (Stream_index < 0) { ALOGD("closeInputStream:no match instream"); } else { if (mInput[Stream_index] != NULL) { ALOGD("closeInputStream +Hdl lock"); StreamHandlerLock();//cr ALPS00090606 delete mInput[Stream_index]; mInput[Stream_index] = NULL; StreamHandlerUnLock(); ALOGD("closeInputStream -Hdl lock"); return; } } Stream_index = this->FindMatchInputI2SStream(in); if (Stream_index < 0) { LOG_STREAMHANDLER("::closeInputStream :: no match I2Sinstream available"); } else { if (mI2SInput[Stream_index] != NULL) { LOG_STREAMHANDLER("closeInputStream::delete mI2SInput"); delete mI2SInput[Stream_index]; mI2SInput[Stream_index] = NULL; return; } } } void AudioStreamHandler::SetLadPlayer(int mMode) { LOG_STREAMHANDLER("+::SetLadPlayer(mMode=%d)", mMode); pthread_mutex_lock(&mAudioHardware->LadMutex); pthread_mutex_lock(&mAudioHardware->LadBufferMutex); mLadPlayerMode = mMode; //record the mode of setplayer if (mLadPlayerMode == android_audio_legacy::AudioSystem::MODE_IN_CALL) // enter mode is ringtone { // if background is close,open. if (mAudioHardware->GetBgsStatus() == false && GetSrcRunningNumber()) { LOG_STREAMHANDLER("SetLadPlayer1, GetBgsStatus=0"); for (int i = 0; i < MAX_OUTPUT_STREAM_NUM; i++) { if (mOutput[i] != NULL) { mOutput[i]->InitLadplayerBuffer(); } } mAudioHardware->SetBgsStatus(true); mAudioHardware->pLadPlayer->LADPlayer_SetBGSoundGain(-180, -6); mAudioHardware->pLadPlayer->LADPlayer_Open(mLadPlayerMode); } } pthread_mutex_unlock(&mAudioHardware->LadBufferMutex); pthread_mutex_unlock(&mAudioHardware->LadMutex); LOG_STREAMHANDLER("-::SetLadPlayer(mMode=%d)", mMode); } void AudioStreamHandler::SetLadPlayer() { // LOG_STREAMHANDLER("+::SetLadPlayer(mLadPlayerMode = %d) ",mLadPlayerMode); pthread_mutex_lock(&mAudioHardware->LadMutex); pthread_mutex_lock(&mAudioHardware->LadBufferMutex); if (mLadPlayerMode == android_audio_legacy::AudioSystem::MODE_IN_CALL) // enter mode is ringtone { // if background is close,open. if (mAudioHardware->GetBgsStatus() == false && GetSrcRunningNumber()) { LOG_STREAMHANDLER("SetLadPlayer, GetBgsStatus:0"); for (int i = 0 ; i < MAX_OUTPUT_STREAM_NUM ; i++) { if (mOutput[i] != NULL) { mOutput[i]->InitLadplayerBuffer(); } } mAudioHardware->mForceBGSoff = true; mAudioHardware->SetBgsStatus(true); mAudioHardware->pLadPlayer->LADPlayer_SetBGSoundGain(-180, -6); mAudioHardware->pLadPlayer->LADPlayer_Open(mLadPlayerMode); } } pthread_mutex_unlock(&mAudioHardware->LadBufferMutex); pthread_mutex_unlock(&mAudioHardware->LadMutex); // LOG_STREAMHANDLER("-::SetLadPlayer(mLadPlayerMode = %d) ",mLadPlayerMode); } void AudioStreamHandler::ForceSetLadPlayer() { LOG_STREAMHANDLER("::ForceSetLadPlayer(mLadPlayerMode=%d) ", mLadPlayerMode); pthread_mutex_lock(&mAudioHardware->LadMutex); pthread_mutex_lock(&mAudioHardware->LadBufferMutex); if (mLadPlayerMode == android_audio_legacy::AudioSystem::MODE_IN_CALL) // enter mode is ringtone { // if background is close,open. if (mAudioHardware->GetBgsStatus() == false && GetSrcRunningNumber()) { LOG_STREAMHANDLER("ForceSetLadPlayer, GetBgsStatus:0"); for (int i = 0 ; i < MAX_OUTPUT_STREAM_NUM ; i++) { if (mOutput[i] != NULL) { mOutput[i]->InitLadplayerBuffer(); } } mAudioHardware->SetBgsStatus(true); mAudioHardware->pLadPlayer->LADPlayer_SetBGSoundGain(-180, -6); mAudioHardware->pLadPlayer->LADPlayer_Open(mLadPlayerMode); } } pthread_mutex_unlock(&mAudioHardware->LadBufferMutex); pthread_mutex_unlock(&mAudioHardware->LadMutex); } void AudioStreamHandler::ResetLadPlayer(int mMode) { LOG_STREAMHANDLER("+::ResetLadPlayer(mMode=%d, mLadPlayerMode=%d)", mMode, mLadPlayerMode); pthread_mutex_lock(&mAudioHardware->LadMutex); pthread_mutex_lock(&mAudioHardware->LadBufferMutex); LOG_STREAMHANDLER("::ResetLadPlayer(GetBgsStatus=%d, GetSrcRunningNumber=%d)", mAudioHardware->GetBgsStatus(), GetSrcRunningNumber()); if (mLadPlayerMode == android_audio_legacy::AudioSystem::MODE_IN_CALL && mMode != mLadPlayerMode) { // if background is open ,close. if (mAudioHardware->GetBgsStatus() == true && GetSrcRunningNumber()) { LOG_STREAMHANDLER("ResetLadPlayer1, GetBgsStatus=1"); mAudioHardware->pLadPlayer->LADPlayer_Close(); mAudioHardware->SetBgsStatus(false); for (int i = 0; i < MAX_OUTPUT_STREAM_NUM; i++) { if (mOutput[i] != NULL) { mOutput[i]->DeinitLadplayerBuffer(); } } } } mLadPlayerMode = mMode; //record the mode of setplayer pthread_mutex_unlock(&mAudioHardware->LadBufferMutex); pthread_mutex_unlock(&mAudioHardware->LadMutex); LOG_STREAMHANDLER("-::ResetLadPlayer(mMode=%d, mLadPlayerMode=%d)", mMode, mLadPlayerMode); } void AudioStreamHandler::ResetLadPlayer() { LOG_STREAMHANDLER("+::ResetLadPlayer(mLadPlayerMode=%d) ", mLadPlayerMode); pthread_mutex_lock(&mAudioHardware->LadMutex); pthread_mutex_lock(&mAudioHardware->LadBufferMutex); if (mLadPlayerMode == android_audio_legacy::AudioSystem::MODE_IN_CALL) { // if background is open ,close, GetSrcRunningNumber is little tricky , in Audioyusustreamout.cpp , I minus SrcRunningNumber // and call ResetLadPlayer if (mAudioHardware->GetBgsStatus() == true && GetSrcRunningNumber() == 0) { LOG_STREAMHANDLER("ResetLadPlayer, GetBgsStatus=1"); mAudioHardware->pLadPlayer->LADPlayer_Close(); mAudioHardware->SetBgsStatus(false); for (int i = 0 ; i < MAX_OUTPUT_STREAM_NUM ; i++) { if (mOutput[i] != NULL) { mOutput[i]->DeinitLadplayerBuffer(); } } } } pthread_mutex_unlock(&mAudioHardware->LadBufferMutex); pthread_mutex_unlock(&mAudioHardware->LadMutex); LOG_STREAMHANDLER("-::ResetLadPlayer(mLadPlayerMode=%d) ", mLadPlayerMode); } void AudioStreamHandler::ForceResetLadPlayer(int mMode) { LOG_STREAMHANDLER("+::ForceResetLadPlayer(mLadPlayerMode=%d, mMode=%d)", mLadPlayerMode, mMode); pthread_mutex_lock(&mAudioHardware->LadMutex); pthread_mutex_lock(&mAudioHardware->LadBufferMutex); if (mLadPlayerMode == android_audio_legacy::AudioSystem::MODE_IN_CALL) { // if background is open ,close, GetSrcRunningNumber is little tricky , in Audioyusustreamout.cpp , I minus SrcRunningNumber // and call ResetLadPlayer if (mAudioHardware->GetBgsStatus() == true && GetSrcRunningNumber()) { LOG_STREAMHANDLER("ForceResetLadPlayer, GetBgsStatus=1"); mAudioHardware->pLadPlayer->LADPlayer_Close(); mAudioHardware->SetBgsStatus(false); for (int i = 0 ; i < MAX_OUTPUT_STREAM_NUM ; i++) { if (mOutput[i] != NULL) { mOutput[i]->DeinitLadplayerBuffer(); } } } } mLadPlayerMode = mMode; //record the mode of setplayer pthread_mutex_unlock(&mAudioHardware->LadBufferMutex); pthread_mutex_unlock(&mAudioHardware->LadMutex); LOG_STREAMHANDLER("-::ForceResetLadPlayer(mLadPlayerMode=%d) ", mLadPlayerMode); } bool AudioStreamHandler::IsRecordOn() { for (int i = 0; i < MAX_INPUT_STREAM_NUM; i++) { if (mInput[i] != NULL) { if (mInput[i]->IsStandby() == false) { return true; } } } return false; } bool AudioStreamHandler::RecordClose(void) { ALOGD("RecordClose"); bool result = false; for (int i = 0; i < MAX_INPUT_STREAM_NUM; i++) { // have inputstream and not instandby if (mInput[i]) { mInput[i]->RecClose(); result = true; } } return result; } bool AudioStreamHandler::RecordOpen(void) { ALOGD("RecordOpen"); bool result = false; for (int i = 0; i < MAX_INPUT_STREAM_NUM; i++) { // have inputstream and in standby if (mInput[i]) { mInput[i]->RecOpen(); result = true; } } return result; } bool AudioStreamHandler::SetCloseRec(int mPreviousMode, int mMode) { ALOGD("::SetCloseRec mPreviousMode=%d, mMode=%d", mPreviousMode, mMode); return RecordClose(); } bool AudioStreamHandler::SetOpenRec(int mPreviousMode, int mMode) { ALOGD("::SetOpenRec mPreviousMode = %d , mMode = %d", mPreviousMode, mMode); return RecordOpen(); } /* when Streamin is exist , need change input device base on inputsource. */ int AudioStreamHandler::SetMicType(int InputSource) { if (mInput[0]) { mInput[0]->SetStreamInputSource(InputSource); } return true; } bool AudioStreamHandler::setMicMute(bool bMicMute) { if (mInput[0]) { mInput[0]->SetInputMute(bMicMute); } return true; } void AudioStreamHandler::SetOutputSamplerate(uint32 samplerate) { LOG_STREAMHANDLER("AudioStreamHandler::SetOutputSamplerate samplerate = %d", samplerate); int ret = 0; for (int i = 0; i < MAX_OUTPUT_STREAM_NUM ; i++) { if (mOutput[i] != NULL) { ret = mOutput[i]->SetOutSamplerate(samplerate); if (ret < 0) { ALOGE("::SetOutputSamplerate ERROR!!!"); } } } } void AudioStreamHandler::StreamHandlerLock() { mHandlerLock.lock(); } void AudioStreamHandler::StreamHandlerUnLock() { mHandlerLock.unlock(); } void AudioStreamHandler::InputStreamLock() { if (mInput[0] != NULL) { mInput[0]->MutexLock(); } } void AudioStreamHandler::InputStreamUnLock() { if (mInput[0] != NULL) { mInput[0]->MutexUnlock(); } } void AudioStreamHandler::OutputStreamLock() { pthread_mutex_lock(&mOutputstreamMutex); } void AudioStreamHandler::OutputStreamUnLock() { pthread_mutex_unlock(&mOutputstreamMutex); } void AudioStreamHandler::SetOutputStreamToBT(void) { ALOGD("SetOutputStreamToBT"); OutputStreamLock(); uint32 BTSCO_SAMPLERATE = (mAfe_handle->mDaiBtMode == 0) ? 8000 : 16000; if (GetSrcBlockRunning()) { this->AudioStopRunning(); ::ioctl(mFd, STANDBY_DL1_STREAM, 0); usleep(1 * 1000); ioctl(mFd, START_DL1_STREAM, 0); usleep(5 * 1000); for (int i = 0; i < MAX_OUTPUT_STREAM_NUM ; i++) { mOutput[i]->SetBTscoSamplerate(BTSCO_SAMPLERATE); } int interval = ASM_BUFFER_SIZE / 3; // skype interval = interval >> 2; ALOGD("SetOutputStreamToBT +release HardwareOnOffMutex"); pthread_mutex_unlock(&mAudioHardware->HardwareOnOffMutex); this->AudioStartRunning(0, interval); } else { ALOGD("SetOutputStreamToBT GetSrcBlockRunning() is false"); mSetBTSCOSamplerateAtStartRunning = true; if (mRestoreSamplerateAtStartRunning == true) { ALOGD("mRestoreSamplerateAtStartRunning is true!!! Set to false!!!"); mRestoreSamplerateAtStartRunning = false; } } mOutput[0]->SetFillinZero(true); OutputStreamUnLock(); } void AudioStreamHandler::RestoreOutputStream(void) { ALOGD("RestoreOutputStream"); OutputStreamLock(); if (GetSrcBlockRunning()) { this->AudioStopRunning(); ::ioctl(mFd, STANDBY_DL1_STREAM, 0); usleep(1 * 1000); ioctl(mFd, START_DL1_STREAM, 0); usleep(5 * 1000); for (int i = 0; i < MAX_OUTPUT_STREAM_NUM ; i++) { mOutput[i]->RestoreOutSamplerate(); } int interval = mOutput[0]->GetInterrupttime(); ALOGD("RestoreOutputStream interval=%d\n", interval); mAfe_handle->Afe_Set_Timer(IRQ1_MCU, interval); //skype ALOGD("RestoreOutputStream +release HardwareOnOffMutex"); pthread_mutex_unlock(&mAudioHardware->HardwareOnOffMutex); this->AudioStartRunning(0, interval); } else { ALOGD("RestoreOutputStream GetSrcBlockRunning() is false"); mRestoreSamplerateAtStartRunning = true; if (mSetBTSCOSamplerateAtStartRunning == true) { ALOGD("mSetBTSCOSamplerateAtStartRunning is true!!! Set to false!!!"); mSetBTSCOSamplerateAtStartRunning = false; } } OutputStreamUnLock(); } // ---------------------------------------------------------------------------- };
[ "sasha.halchin@gmail.com" ]
sasha.halchin@gmail.com
f297bf774f9663e84c32c24454be9b925fd370ed
f95fec8a9775e520cf2b1304ae861f953acd4c96
/Source/Application.cpp
626a5df10afa6555597576060ea7bcd4ecf20fea
[ "Apache-2.0" ]
permissive
uncerso/line-paint
4adac986c9628fa861409b07349e9e91a7eb0c64
756d7706ecfd0bff123db182826448d178c3b35b
refs/heads/master
2021-05-08T03:12:02.216072
2018-02-20T17:19:13
2018-02-20T17:19:13
108,174,104
0
0
Apache-2.0
2018-02-20T17:19:42
2017-10-24T19:33:24
null
UTF-8
C++
false
false
821
cpp
/* ============================================================================== Application.cpp Created: 25 Oct 2017 11:10:51am Author: uncerso ============================================================================== */ #include "Application.h" #include "MainForm.h" namespace line_paint{ Application::Application() : mainForm(nullptr) {} void Application::initialise(const String &commandLineParameters) { mainForm = new MainForm(); } void Application::shutdown() { if (mainForm) delete mainForm; } void Application::systemRequestedQuit() { quit(); } const String Application::getApplicationName() { return "line paint"; } const String Application::getApplicationVersion() { return ProjectInfo::versionString; } bool Application::moreThanOneInstanceAllowed() { return true; } }
[ "yayayayaya38@gmail.com" ]
yayayayaya38@gmail.com
9212f07ab9fcfca2d9386a86eef5aba0416265f5
cb621dee2a0f09a9a2d5d14ffaac7df0cad666a0
/http/parsers/version_number.hpp
a68117b900555a9cf5931020cfc817c71f9d14ba
[ "BSL-1.0" ]
permissive
ssiloti/http
a15fb43c94c823779f11fb02e147f023ca77c932
9cdeaa5cf2ef2848238c6e4c499ebf80e136ba7e
refs/heads/master
2021-01-01T19:10:36.886248
2011-11-07T19:29:22
2011-11-07T19:29:22
1,021,325
0
1
null
null
null
null
UTF-8
C++
false
false
1,139
hpp
// // version_number.hpp // ~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2010 Steven Siloti (ssiloti@gmail.com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_PARSERS_VERSION_NUMBER_HPP #define HTTP_PARSERS_VERSION_NUMBER_HPP #include <http/version_number.hpp> #include <boost/spirit/home/qi/numeric.hpp> #include <boost/spirit/home/qi/string.hpp> #include <boost/spirit/home/qi/operator.hpp> #include <boost/spirit/home/qi/nonterminal/rule.hpp> #include <boost/spirit/home/qi/nonterminal/grammar.hpp> namespace http { namespace parsers { template <typename Iterator> struct version_number_grammar : boost::spirit::qi::grammar<Iterator, version_number()> { version_number_grammar() : version_number_grammar::base_type(start, "version_number") { using namespace boost::spirit; start %= qi::lit("HTTP/") >> qi::uint_ >> '.' >> qi::uint_; } // start rule of grammar boost::spirit::qi::rule<Iterator, version_number()> start; }; } } // namespace parsers namespace http #endif
[ "ssiloti@gmail.com" ]
ssiloti@gmail.com
21da3feabc3dd0bfed5edbc513cdd986fb74a2cc
db06cee52d263fb49a36ddc66324d79953be6862
/app/inc/server.h
50ff7e8fb4e5bafe0fcb2c24857b2e2af059ce68
[]
no_license
andrewloomis/khet-server
85c4dcb22de63c1919cfef002471a2675ff804ee
919c067b68d47fecd067be45bd984682013845b7
refs/heads/master
2020-04-15T06:16:33.395522
2019-03-03T19:24:10
2019-03-03T19:24:10
164,454,736
0
0
null
null
null
null
UTF-8
C++
false
false
828
h
#ifndef SERVER_H #define SERVER_H #include "khetlib/player.h" #include "packetmanager.h" #include "customtypes.h" #include <QtWebSockets/QWebSocketServer> #include <QtCore/QList> #include <memory> class Server : public QObject { Q_OBJECT public: Server(); private: std::shared_ptr<Network::Connections> clients; QWebSocketServer* server; PacketManager packetManager; // UserManager userManager; // QList<std::shared_ptr<GameManager>> gameManagers; const quint16 port = 60001; private slots: void onNewConnection(); void processTextMessage(QString message); void processBinaryMessage(QByteArray message); void socketDisconnected(); void onSslErrors(const QList<QSslError> &errors); // void endGame(QString player1, QString player2, Color winner); }; #endif // SERVER_H
[ "andrew@thanics.com" ]
andrew@thanics.com
03f11a9a6f8afee043bf40734f834bed2d24fc8f
b554f692668a485f98ad8acbfd6a3dedac655333
/WebSiteAnalyzer/include/main_frame.h
c1b4d390a12d705365a146a6296f182c4a206b65
[]
no_license
ANDR-ASCII/WebSiteAnalyzer
b04f21b78e39d217f6c8054022c5fa37b244808c
02852a94d0f1749ca305ec9889b1700bc7eac47a
refs/heads/master
2021-01-20T06:12:01.792082
2017-06-17T17:15:55
2017-06-17T17:15:55
89,851,093
1
0
null
null
null
null
UTF-8
C++
false
false
946
h
#pragma once #include "stdlibs.h" #include "ui_main_frame.h" #include "start_settings_dialog.h" #include "crawler_settings.h" #include "crawler_worker.h" namespace WebSiteAnalyzer { using namespace CrawlerImpl; class MainFrame : public QMainWindow { Q_OBJECT public: MainFrame(QWidget *parent = 0); Q_SIGNAL void signal_stopCrawlerCommand(); Q_SIGNAL void signal_startCrawlerCommand(CrawlerImpl::CrawlerSettings*, bool); Q_SLOT void slot_hideProgressBarWhenStoppingCrawler(); Q_SLOT void slot_showStartSettingsDialog(); Q_SLOT void slot_queueSize(std::size_t size, int queueType); Q_SLOT void slot_DNSError(); Q_SLOT void slot_resetCrawling(); private: void clearModels(); void initialize(); void initializeModelsAndViews(); private: Ui::MainFrameClass ui; std::unique_ptr<StartSettingsDialog> m_startSettingsDialog; std::unique_ptr<CrawlerSettings> m_settings; CrawlerWorker* m_worker; QThread m_crawlerThread; }; }
[ "logforregs@gmail.com" ]
logforregs@gmail.com
b9c32904581871c930050b911da539b57eb83ae6
7ee83fb1bc2c59b24ba9fe7c44226fea59adea4b
/MPI programing/MPI programing.cpp
16676634103716f16b3758b1cbef05eb2189bceb
[]
no_license
udaravimukthi/MPI-Programming
60f6ae10799d2ad4f6c51f2dae896823aed1fd54
43e24f8aa42e867f7f435eaecb26c1235793cbfe
refs/heads/main
2023-06-13T05:43:00.966679
2021-07-05T13:32:29
2021-07-05T13:32:29
365,572,551
0
0
null
null
null
null
UTF-8
C++
false
false
1,501
cpp
// MPI programing.cpp : This file contains the 'main' function. Program execution begins and ends there. // //#include <iostream> //int main() //{ // std::cout << "Hello World!\n"; //} #include <mpi.h> #include <stdio.h> int main(int argc, char** argv) { // Initialize the MPI environment MPI_Init(NULL, NULL); // Get the number of processes int world_size; MPI_Comm_size(MPI_COMM_WORLD, &world_size); // Get the rank of the process int world_rank; MPI_Comm_rank(MPI_COMM_WORLD, &world_rank); // Get the name of the processor char processor_name[MPI_MAX_PROCESSOR_NAME]; int name_len; MPI_Get_processor_name(processor_name, &name_len); // Print off a hello world message printf("Hello world from processor %s, rank %d out of %d processors\n", processor_name, world_rank, world_size); // Finalize the MPI environment. MPI_Finalize(); } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
[ "uvlakshan@gmail.com" ]
uvlakshan@gmail.com
a516c68af8befb5ba5a11d2a9b44233f19608587
8a5a67fdf382f43477f3849daf2f0372be134e5b
/Algorithms/Linked List/06. Add two numbers given as a linked list.cpp
6ab5264ea2a25ebd28b2badf9d5fd605c75e3542
[]
no_license
akhilsaini678/All-Codes
bd57171bbf08e721c32f8fd30c26e05a02b6fd9f
6c7c7fc345d9fbe68e78723d1703f618941aefb3
refs/heads/master
2023-07-12T08:50:44.918801
2021-08-22T05:31:30
2021-08-22T05:31:30
398,625,962
0
0
null
null
null
null
UTF-8
C++
false
false
2,014
cpp
#include<bits/stdc++.h> using namespace std; // This is the node. class node{ public: int data; node* next; node(int val) { data=val; next=NULL; } }; // Insert at the begining. void insertbegin(node* &head,int val) { node* tmp = new node(val); tmp->next=head; head=tmp; } // Insert element at the end. void insert(node* &head,int val) { node* tmp = new node(val); if(head==NULL) { head=tmp; return; } node* tmp1 = head; while(tmp1->next!=NULL) tmp1=tmp1->next; tmp1->next=tmp; } // Print the elements. void printlist(node* head) { while(head!=NULL) { cout<<head->data<<" "; head=head->next; } cout<<endl; } // Add two numbers given as a linked list. node* add(node* head1,node* head2) { if(head1==NULL) return head2; if(head2==NULL) return head1; node* head3=NULL; int carry=0; int sum=0; while(1) { if(head1==NULL&&head2==NULL) break; if(head1!=NULL&&head2!=NULL) { sum=(head1->data+head2->data+carry)%10; carry=(head1->data+head2->data+carry)/10; head1=head1->next; head2=head2->next; insert(head3,sum); } else if(head1!=NULL) { sum=(head1->data+carry)%10; carry=(head1->data+carry)/10; insert(head3,sum); head1=head1->next; } else if(head2!=NULL) { sum=(head2->data+carry)%10; carry=(head2->data+carry)/10; insert(head3,sum); head2=head2->next; } } if(carry!=0) { insert(head3,carry); } return head3; } void solve() { node* head1=NULL; node* head2=NULL; insert(head1,2); insert(head1,4); insert(head1,3); insert(head2,5); insert(head2,6); insert(head2,7); insert(head2,9); printlist(head1); printlist(head2); node* head3 = add(head1,head2); printlist(head3); } void fast() { ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); #ifndef ONLINE_JUDGE freopen("C:\\Data\\Online\\Coding\\Contest\\input.txt","r",stdin); freopen("C:\\Data\\Online\\Coding\\Contest\\output.txt","w",stdout); #endif } int main() { fast(); int t=1; cin>>t; while(t--) solve(); return 0; }
[ "akhilsaini678@gmail.com" ]
akhilsaini678@gmail.com
2e2220a795b5c0fe3be9e5eb5953b724ca2e8d93
2ee0606af4b2097a9579ae0921deb7758b3bf08a
/Superpowered/AndroidIO/SuperpoweredAndroidAudioIO.cpp
9588963164482505ce18741c08c813d93ce92dcc
[]
no_license
pezzati/canto_andriod
0f6ea8774dfb4760bf86429840282fedc9f6c1f1
742676413646d5f5aa5f40d1b81bccbacf0ca492
refs/heads/master
2022-01-21T15:57:14.623936
2019-05-30T08:50:00
2019-05-30T08:50:00
156,974,892
0
0
null
null
null
null
UTF-8
C++
false
false
16,335
cpp
#include "SuperpoweredAndroidAudioIO.h" #include <SLES/OpenSLES.h> #include <SLES/OpenSLES_Android.h> #include <SLES/OpenSLES_AndroidConfiguration.h> #include <pthread.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #define NUM_CHANNELS 2 #if NUM_CHANNELS == 1 #define CHANNELMASK SL_SPEAKER_FRONT_CENTER #elif NUM_CHANNELS == 2 #define CHANNELMASK (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT) #endif typedef struct SuperpoweredAndroidAudioIOInternals { void *clientdata; audioProcessingCallback callback; SLObjectItf openSLEngine, outputMix, outputBufferQueue, inputBufferQueue; SLAndroidSimpleBufferQueueItf outputBufferQueueInterface, inputBufferQueueInterface; short int *fifobuffer, *silence; int samplerate, buffersize, silenceSamples, latencySamples, numBuffers, bufferStep, readBufferIndex, writeBufferIndex; bool hasOutput, hasInput, foreground, started; } SuperpoweredAndroidAudioIOInternals; // The entire operation is based on two Android Simple Buffer Queues, one for the audio input and one for the audio output. static void startQueues(SuperpoweredAndroidAudioIOInternals *internals) { if (internals->started) return; internals->started = true; if (internals->inputBufferQueue) { SLRecordItf recordInterface; (*internals->inputBufferQueue)->GetInterface(internals->inputBufferQueue, SL_IID_RECORD, &recordInterface); (*recordInterface)->SetRecordState(recordInterface, SL_RECORDSTATE_RECORDING); }; if (internals->outputBufferQueue) { SLPlayItf outputPlayInterface; (*internals->outputBufferQueue)->GetInterface(internals->outputBufferQueue, SL_IID_PLAY, &outputPlayInterface); (*outputPlayInterface)->SetPlayState(outputPlayInterface, SL_PLAYSTATE_PLAYING); }; } // Stopping the Simple Buffer Queues. static void stopQueues(SuperpoweredAndroidAudioIOInternals *internals) { if (!internals->started) return; internals->started = false; if (internals->outputBufferQueue) { SLPlayItf outputPlayInterface; (*internals->outputBufferQueue)->GetInterface(internals->outputBufferQueue, SL_IID_PLAY, &outputPlayInterface); (*outputPlayInterface)->SetPlayState(outputPlayInterface, SL_PLAYSTATE_STOPPED); }; if (internals->inputBufferQueue) { SLRecordItf recordInterface; (*internals->inputBufferQueue)->GetInterface(internals->inputBufferQueue, SL_IID_RECORD, &recordInterface); (*recordInterface)->SetRecordState(recordInterface, SL_RECORDSTATE_STOPPED); }; } // This is called periodically by the input audio queue. Audio input is received from the media server at this point. static void SuperpoweredAndroidAudioIO_InputCallback(SLAndroidSimpleBufferQueueItf caller, void *pContext) { SuperpoweredAndroidAudioIOInternals *internals = (SuperpoweredAndroidAudioIOInternals *) pContext; short int *buffer = internals->fifobuffer + internals->writeBufferIndex * internals->bufferStep; if (internals->writeBufferIndex < internals->numBuffers - 1) internals->writeBufferIndex++; else internals->writeBufferIndex = 0; if (!internals->hasOutput) { // When there is no audio output configured. int buffersAvailable = internals->writeBufferIndex - internals->readBufferIndex; if (buffersAvailable < 0) buffersAvailable = internals->numBuffers - (internals->readBufferIndex - internals->writeBufferIndex); if (buffersAvailable * internals->buffersize >= internals->latencySamples) { // if we have enough audio input available internals->callback(internals->clientdata, internals->fifobuffer + internals->readBufferIndex * internals->bufferStep, internals->buffersize, internals->samplerate); if (internals->readBufferIndex < internals->numBuffers - 1) internals->readBufferIndex++; else internals->readBufferIndex = 0; }; } (*caller)->Enqueue(caller, buffer, (SLuint32) internals->buffersize * NUM_CHANNELS * 2); } // This is called periodically by the output audio queue. Audio for the user should be provided here. static void SuperpoweredAndroidAudioIO_OutputCallback(SLAndroidSimpleBufferQueueItf caller, void *pContext) { SuperpoweredAndroidAudioIOInternals *internals = (SuperpoweredAndroidAudioIOInternals *) pContext; int buffersAvailable = internals->writeBufferIndex - internals->readBufferIndex; if (buffersAvailable < 0) buffersAvailable = internals->numBuffers - (internals->readBufferIndex - internals->writeBufferIndex); short int *output = internals->fifobuffer + internals->readBufferIndex * internals->bufferStep; if (internals->hasInput) { // If audio input is enabled. if (buffersAvailable * internals->buffersize >= internals->latencySamples) { // if we have enough audio input available if (!internals->callback(internals->clientdata, output, internals->buffersize, internals->samplerate)) { memset(output, 0, (size_t) internals->buffersize * NUM_CHANNELS * 2); internals->silenceSamples += internals->buffersize; } else internals->silenceSamples = 0; } else output = NULL; // dropout, not enough audio input } else { // If audio input is not enabled. short int *audioToGenerate = internals->fifobuffer + internals->writeBufferIndex * internals->bufferStep; if (!internals->callback(internals->clientdata, audioToGenerate, internals->buffersize, internals->samplerate)) { memset(audioToGenerate, 0, (size_t) internals->buffersize * NUM_CHANNELS * 2); internals->silenceSamples += internals->buffersize; } else internals->silenceSamples = 0; if (internals->writeBufferIndex < internals->numBuffers - 1) internals->writeBufferIndex++; else internals->writeBufferIndex = 0; if ((buffersAvailable + 1) * internals->buffersize < internals->latencySamples) output = NULL; // dropout, not enough audio generated }; if (output) { if (internals->readBufferIndex < internals->numBuffers - 1) internals->readBufferIndex++; else internals->readBufferIndex = 0; }; (*caller)->Enqueue(caller, output ? output : internals->silence, (SLuint32) internals->buffersize * NUM_CHANNELS * 2); if (!internals->foreground && (internals->silenceSamples > internals->samplerate)) { internals->silenceSamples = 0; stopQueues(internals); }; } SuperpoweredAndroidAudioIO::SuperpoweredAndroidAudioIO(int samplerate, int buffersize, bool enableInput, bool enableOutput, audioProcessingCallback callback, void *clientdata, int inputStreamType, int outputStreamType, int latencySamples) { static const SLboolean requireds[2] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_FALSE}; internals = new SuperpoweredAndroidAudioIOInternals; memset(internals, 0, sizeof(SuperpoweredAndroidAudioIOInternals)); internals->samplerate = samplerate; internals->buffersize = buffersize; internals->clientdata = clientdata; internals->callback = callback; internals->hasInput = enableInput; internals->hasOutput = enableOutput; internals->foreground = true; internals->started = false; internals->silence = (short int *) malloc((size_t) buffersize * NUM_CHANNELS * 2); memset(internals->silence, 0, (size_t) buffersize * NUM_CHANNELS * 2); internals->latencySamples = latencySamples < buffersize ? buffersize : latencySamples; internals->numBuffers = (internals->latencySamples / buffersize) * 2; if (internals->numBuffers < 32) internals->numBuffers = 32; internals->bufferStep = (buffersize + 64) * NUM_CHANNELS; size_t fifoBufferSizeBytes = internals->numBuffers * internals->bufferStep * sizeof(short int); internals->fifobuffer = (short int *) malloc(fifoBufferSizeBytes); memset(internals->fifobuffer, 0, fifoBufferSizeBytes); // Create the OpenSL ES engine. slCreateEngine(&internals->openSLEngine, 0, NULL, 0, NULL, NULL); (*internals->openSLEngine)->Realize(internals->openSLEngine, SL_BOOLEAN_FALSE); SLEngineItf openSLEngineInterface = NULL; (*internals->openSLEngine)->GetInterface(internals->openSLEngine, SL_IID_ENGINE, &openSLEngineInterface); // Create the output mix. (*openSLEngineInterface)->CreateOutputMix(openSLEngineInterface, &internals->outputMix, 0, NULL, NULL); (*internals->outputMix)->Realize(internals->outputMix, SL_BOOLEAN_FALSE); SLDataLocator_OutputMix outputMixLocator = {SL_DATALOCATOR_OUTPUTMIX, internals->outputMix}; if (enableInput) { // Create the audio input buffer queue. SLDataLocator_IODevice deviceInputLocator = {SL_DATALOCATOR_IODEVICE, SL_IODEVICE_AUDIOINPUT, SL_DEFAULTDEVICEID_AUDIOINPUT, NULL}; SLDataSource inputSource = {&deviceInputLocator, NULL}; SLDataLocator_AndroidSimpleBufferQueue inputLocator = { SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 1}; SLDataFormat_PCM inputFormat = {SL_DATAFORMAT_PCM, NUM_CHANNELS, (SLuint32) samplerate * 1000, SL_PCMSAMPLEFORMAT_FIXED_16, SL_PCMSAMPLEFORMAT_FIXED_16, CHANNELMASK, SL_BYTEORDER_LITTLEENDIAN}; SLDataSink inputSink = {&inputLocator, &inputFormat}; const SLInterfaceID inputInterfaces[2] = {SL_IID_ANDROIDSIMPLEBUFFERQUEUE, SL_IID_ANDROIDCONFIGURATION}; (*openSLEngineInterface)->CreateAudioRecorder(openSLEngineInterface, &internals->inputBufferQueue, &inputSource, &inputSink, 2, inputInterfaces, requireds); if (inputStreamType == -1) inputStreamType = (int) SL_ANDROID_RECORDING_PRESET_VOICE_RECOGNITION; // Configure the voice recognition preset which has no signal processing for lower latency. if (inputStreamType > -1) { SLAndroidConfigurationItf inputConfiguration; if ((*internals->inputBufferQueue)->GetInterface(internals->inputBufferQueue, SL_IID_ANDROIDCONFIGURATION, &inputConfiguration) == SL_RESULT_SUCCESS) { SLuint32 st = (SLuint32) inputStreamType; (*inputConfiguration)->SetConfiguration(inputConfiguration, SL_ANDROID_KEY_RECORDING_PRESET, &st, sizeof(SLuint32)); }; }; (*internals->inputBufferQueue)->Realize(internals->inputBufferQueue, SL_BOOLEAN_FALSE); }; if (enableOutput) { // Create the audio output buffer queue. SLDataLocator_AndroidSimpleBufferQueue outputLocator = { SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 1}; SLDataFormat_PCM outputFormat = {SL_DATAFORMAT_PCM, NUM_CHANNELS, (SLuint32) samplerate * 1000, SL_PCMSAMPLEFORMAT_FIXED_16, SL_PCMSAMPLEFORMAT_FIXED_16, CHANNELMASK, SL_BYTEORDER_LITTLEENDIAN}; SLDataSource outputSource = {&outputLocator, &outputFormat}; const SLInterfaceID outputInterfaces[2] = {SL_IID_BUFFERQUEUE, SL_IID_ANDROIDCONFIGURATION}; SLDataSink outputSink = {&outputMixLocator, NULL}; (*openSLEngineInterface)->CreateAudioPlayer(openSLEngineInterface, &internals->outputBufferQueue, &outputSource, &outputSink, 2, outputInterfaces, requireds); // Configure the stream type. if (outputStreamType > -1) { SLAndroidConfigurationItf outputConfiguration; if ((*internals->outputBufferQueue)->GetInterface(internals->outputBufferQueue, SL_IID_ANDROIDCONFIGURATION, &outputConfiguration) == SL_RESULT_SUCCESS) { SLint32 st = (SLint32) outputStreamType; (*outputConfiguration)->SetConfiguration(outputConfiguration, SL_ANDROID_KEY_STREAM_TYPE, &st, sizeof(SLint32)); }; }; (*internals->outputBufferQueue)->Realize(internals->outputBufferQueue, SL_BOOLEAN_FALSE); }; if (enableInput) { // Initialize the audio input buffer queue. (*internals->inputBufferQueue)->GetInterface(internals->inputBufferQueue, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &internals->inputBufferQueueInterface); (*internals->inputBufferQueueInterface)->RegisterCallback( internals->inputBufferQueueInterface, SuperpoweredAndroidAudioIO_InputCallback, internals); (*internals->inputBufferQueueInterface)->Enqueue(internals->inputBufferQueueInterface, internals->fifobuffer, (SLuint32) buffersize * NUM_CHANNELS * 2); }; if (enableOutput) { // Initialize the audio output buffer queue. (*internals->outputBufferQueue)->GetInterface(internals->outputBufferQueue, SL_IID_BUFFERQUEUE, &internals->outputBufferQueueInterface); (*internals->outputBufferQueueInterface)->RegisterCallback( internals->outputBufferQueueInterface, SuperpoweredAndroidAudioIO_OutputCallback, internals); (*internals->outputBufferQueueInterface)->Enqueue(internals->outputBufferQueueInterface, internals->fifobuffer, (SLuint32) buffersize * NUM_CHANNELS * 2); }; startQueues(internals); } void SuperpoweredAndroidAudioIO::onForeground() { internals->foreground = true; startQueues(internals); } void SuperpoweredAndroidAudioIO::onBackground() { internals->foreground = false; } void SuperpoweredAndroidAudioIO::start() { startQueues(internals); } void SuperpoweredAndroidAudioIO::stop() { stopQueues(internals); } SuperpoweredAndroidAudioIO::~SuperpoweredAndroidAudioIO() { stopQueues(internals); usleep(200000); if (internals->outputBufferQueue) (*internals->outputBufferQueue)->Destroy(internals->outputBufferQueue); if (internals->inputBufferQueue) (*internals->inputBufferQueue)->Destroy(internals->inputBufferQueue); (*internals->outputMix)->Destroy(internals->outputMix); (*internals->openSLEngine)->Destroy(internals->openSLEngine); free(internals->fifobuffer); free(internals->silence); delete internals; }
[ "hamed.ma7@gmail.com" ]
hamed.ma7@gmail.com
8ef8f39c6930cfb94e75b556f5f6eed380cade0b
26e0f1ce7789dd6b5eb9c0971c3438c666f42880
/79.word-search.cpp
b32457b9ceccf30c76812ec39b1792dc05b42000
[]
no_license
yanmulin/leetcode
81ee38bb8fbe8ca208bc68683d0ffb96b20f2b68
7cc1f650e1ba4d68fb3104aecf3dfbb093ad9c1d
refs/heads/master
2020-12-05T01:39:32.290473
2020-08-19T03:47:23
2020-08-19T03:47:23
231,969,717
0
0
null
null
null
null
UTF-8
C++
false
false
1,141
cpp
class Solution { private: bool existRecurse(vector<vector<char>>& board, string &word, int idx, int row, int col) { if (idx >= word.size()) return true; if (row < 0 || row >= board.size()) return false; if (col < 0 || col >= board[0].size()) return false; if (board[row][col] != word[idx]) return false; board[row][col] = '\0'; if (existRecurse(board, word, idx+1, row+1, col)) return true; if (existRecurse(board, word, idx+1, row-1, col)) return true; if (existRecurse(board, word, idx+1, row, col+1)) return true; if (existRecurse(board, word, idx+1, row, col-1)) return true; board[row][col] = word[idx]; return false; } public: bool exist(vector<vector<char>>& board, string word) { if (word.size() == 0) return true; if (board.size() == 0) return false; int n = board.size(), m = board[0].size(); for (int i=0;i<n;i++) { for (int j=0;j<m;j++) { if (existRecurse(board, word, 0, i, j)) return true; } } return false; } };
[ "yans1996@outlook.com" ]
yans1996@outlook.com
bdbd97107e63304d7dbb6f17ef36cead3e7b8402
564c21649799b8b59f47d6282865f0cf745b1f87
/chromecast/media/cma/pipeline/media_pipeline_impl.cc
14ced50a4d383c37ea7f16eac46266c695ab54b9
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
pablosalazar7/WebARonARCore
e41f6277dd321c60084abad635819e0f70f2e9ff
43c5db480e89b59e4ae6349e36d8f375ee12cc0d
refs/heads/webarcore_57.0.2987.5
2023-02-23T04:58:12.756320
2018-01-17T17:40:20
2018-01-24T04:14:02
454,492,900
1
0
NOASSERTION
2022-02-01T17:56:03
2022-02-01T17:56:02
null
UTF-8
C++
false
false
19,466
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. #include "chromecast/media/cma/pipeline/media_pipeline_impl.h" #include <algorithm> #include <utility> #include "base/bind.h" #include "base/callback.h" #include "base/callback_helpers.h" #include "base/location.h" #include "base/logging.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "chromecast/base/metrics/cast_metrics_helper.h" #include "chromecast/media/cdm/cast_cdm_context.h" #include "chromecast/media/cma/base/buffering_controller.h" #include "chromecast/media/cma/base/buffering_state.h" #include "chromecast/media/cma/base/cma_logging.h" #include "chromecast/media/cma/base/coded_frame_provider.h" #include "chromecast/media/cma/pipeline/audio_decoder_software_wrapper.h" #include "chromecast/media/cma/pipeline/audio_pipeline_impl.h" #include "chromecast/media/cma/pipeline/video_pipeline_impl.h" #include "chromecast/public/media/media_pipeline_backend.h" #include "media/base/timestamp_constants.h" namespace chromecast { namespace media { namespace { // Buffering parameters when load_type is kLoadTypeUrl. const base::TimeDelta kLowBufferThresholdURL( base::TimeDelta::FromMilliseconds(2000)); const base::TimeDelta kHighBufferThresholdURL( base::TimeDelta::FromMilliseconds(6000)); // Buffering parameters when load_type is kLoadTypeMediaSource. const base::TimeDelta kLowBufferThresholdMediaSource( base::TimeDelta::FromMilliseconds(0)); const base::TimeDelta kHighBufferThresholdMediaSource( base::TimeDelta::FromMilliseconds(300)); // Interval between two updates of the media time. const base::TimeDelta kTimeUpdateInterval( base::TimeDelta::FromMilliseconds(250)); // Interval between two updates of the statistics is equal to: // kTimeUpdateInterval * kStatisticsUpdatePeriod. const int kStatisticsUpdatePeriod = 4; // Stall duration threshold that triggers a playback stall event. constexpr int kPlaybackStallEventThresholdMs = 2500; void LogEstimatedBitrate(int decoded_bytes, base::TimeDelta elapsed_time, const char* tag, const char* metric) { int estimated_bitrate_in_kbps = 8 * decoded_bytes / elapsed_time.InMilliseconds(); if (estimated_bitrate_in_kbps <= 0) return; CMALOG(kLogControl) << "Estimated " << tag << " bitrate is " << estimated_bitrate_in_kbps << " kbps"; metrics::CastMetricsHelper* metrics_helper = metrics::CastMetricsHelper::GetInstance(); metrics_helper->RecordApplicationEventWithValue(metric, estimated_bitrate_in_kbps); } } // namespace struct MediaPipelineImpl::FlushTask { bool audio_flushed; bool video_flushed; base::Closure done_cb; }; MediaPipelineImpl::MediaPipelineImpl() : cdm_context_(nullptr), backend_state_(BACKEND_STATE_UNINITIALIZED), playback_rate_(0), audio_decoder_(nullptr), video_decoder_(nullptr), pending_time_update_task_(false), last_media_time_(::media::kNoTimestamp), statistics_rolling_counter_(0), audio_bytes_for_bitrate_estimation_(0), video_bytes_for_bitrate_estimation_(0), playback_stalled_(false), playback_stalled_notification_sent_(false), weak_factory_(this) { CMALOG(kLogControl) << __FUNCTION__; weak_this_ = weak_factory_.GetWeakPtr(); thread_checker_.DetachFromThread(); } MediaPipelineImpl::~MediaPipelineImpl() { CMALOG(kLogControl) << __FUNCTION__; DCHECK(thread_checker_.CalledOnValidThread()); if (backend_state_ != BACKEND_STATE_UNINITIALIZED && backend_state_ != BACKEND_STATE_INITIALIZED) metrics::CastMetricsHelper::GetInstance()->RecordApplicationEvent( "Cast.Platform.Ended"); } void MediaPipelineImpl::Initialize( LoadType load_type, std::unique_ptr<MediaPipelineBackend> media_pipeline_backend) { CMALOG(kLogControl) << __FUNCTION__; DCHECK(thread_checker_.CalledOnValidThread()); audio_decoder_.reset(); media_pipeline_backend_ = std::move(media_pipeline_backend); if (load_type == kLoadTypeURL || load_type == kLoadTypeMediaSource) { base::TimeDelta low_threshold(kLowBufferThresholdURL); base::TimeDelta high_threshold(kHighBufferThresholdURL); if (load_type == kLoadTypeMediaSource) { low_threshold = kLowBufferThresholdMediaSource; high_threshold = kHighBufferThresholdMediaSource; } scoped_refptr<BufferingConfig> buffering_config( new BufferingConfig(low_threshold, high_threshold)); buffering_controller_.reset(new BufferingController( buffering_config, base::Bind(&MediaPipelineImpl::OnBufferingNotification, weak_this_))); } } void MediaPipelineImpl::SetClient(const MediaPipelineClient& client) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(!client.error_cb.is_null()); DCHECK(!client.buffering_state_cb.is_null()); client_ = client; } void MediaPipelineImpl::SetCdm(int cdm_id) { CMALOG(kLogControl) << __FUNCTION__ << " cdm_id=" << cdm_id; DCHECK(thread_checker_.CalledOnValidThread()); NOTIMPLEMENTED(); // TODO(gunsch): SetCdm(int) is not implemented. // One possibility would be a GetCdmByIdCB that's passed in. } void MediaPipelineImpl::SetCdm(CastCdmContext* cdm_context) { CMALOG(kLogControl) << __FUNCTION__; DCHECK(thread_checker_.CalledOnValidThread()); cdm_context_ = cdm_context; if (audio_pipeline_) audio_pipeline_->SetCdm(cdm_context); if (video_pipeline_) video_pipeline_->SetCdm(cdm_context); } ::media::PipelineStatus MediaPipelineImpl::InitializeAudio( const ::media::AudioDecoderConfig& config, const AvPipelineClient& client, std::unique_ptr<CodedFrameProvider> frame_provider) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(!audio_decoder_); MediaPipelineBackend::AudioDecoder* backend_audio_decoder = media_pipeline_backend_->CreateAudioDecoder(); if (!backend_audio_decoder) { return ::media::PIPELINE_ERROR_ABORT; } audio_decoder_.reset(new AudioDecoderSoftwareWrapper(backend_audio_decoder)); audio_pipeline_.reset(new AudioPipelineImpl(audio_decoder_.get(), client)); if (cdm_context_) audio_pipeline_->SetCdm(cdm_context_); return audio_pipeline_->Initialize(config, std::move(frame_provider)); } ::media::PipelineStatus MediaPipelineImpl::InitializeVideo( const std::vector<::media::VideoDecoderConfig>& configs, const VideoPipelineClient& client, std::unique_ptr<CodedFrameProvider> frame_provider) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(!video_decoder_); video_decoder_ = media_pipeline_backend_->CreateVideoDecoder(); if (!video_decoder_) { return ::media::PIPELINE_ERROR_ABORT; } video_pipeline_.reset(new VideoPipelineImpl(video_decoder_, client)); if (cdm_context_) video_pipeline_->SetCdm(cdm_context_); return video_pipeline_->Initialize(configs, std::move(frame_provider)); } void MediaPipelineImpl::StartPlayingFrom(base::TimeDelta time) { CMALOG(kLogControl) << __FUNCTION__ << " t0=" << time.InMilliseconds(); DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(audio_pipeline_ || video_pipeline_); DCHECK(!pending_flush_task_); // Lazy initialize. if (backend_state_ == BACKEND_STATE_UNINITIALIZED) { if (!media_pipeline_backend_->Initialize()) { OnError(::media::PIPELINE_ERROR_ABORT); return; } backend_state_ = BACKEND_STATE_INITIALIZED; } // Start the backend. if (!media_pipeline_backend_->Start(time.InMicroseconds())) { OnError(::media::PIPELINE_ERROR_ABORT); return; } backend_state_ = BACKEND_STATE_PLAYING; ResetBitrateState(); metrics::CastMetricsHelper::GetInstance()->RecordApplicationEvent( "Cast.Platform.Playing"); // Enable time updates. last_media_time_ = time; statistics_rolling_counter_ = 0; if (!pending_time_update_task_) { pending_time_update_task_ = true; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&MediaPipelineImpl::UpdateMediaTime, weak_this_)); } // Setup the audio and video pipeline for the new timeline. if (audio_pipeline_) { scoped_refptr<BufferingState> buffering_state; if (buffering_controller_) buffering_state = buffering_controller_->AddStream("audio"); if (!audio_pipeline_->StartPlayingFrom(time, buffering_state)) { OnError(::media::PIPELINE_ERROR_ABORT); return; } } if (video_pipeline_) { scoped_refptr<BufferingState> buffering_state; if (buffering_controller_) buffering_state = buffering_controller_->AddStream("video"); if (!video_pipeline_->StartPlayingFrom(time, buffering_state)) { OnError(::media::PIPELINE_ERROR_ABORT); return; } } } void MediaPipelineImpl::Flush(const base::Closure& flush_cb) { CMALOG(kLogControl) << __FUNCTION__; DCHECK(thread_checker_.CalledOnValidThread()); DCHECK((backend_state_ == BACKEND_STATE_PLAYING) || (backend_state_ == BACKEND_STATE_PAUSED)); DCHECK(audio_pipeline_ || video_pipeline_); DCHECK(!pending_flush_task_); buffering_controller_->Reset(); // Flush both audio and video pipeline. This will flush the frame // provider and stop feeding buffers to the backend. // MediaPipelineImpl::OnFlushDone will stop the backend once flush completes. pending_flush_task_.reset(new FlushTask); pending_flush_task_->audio_flushed = !audio_pipeline_; pending_flush_task_->video_flushed = !video_pipeline_; pending_flush_task_->done_cb = flush_cb; if (audio_pipeline_) { audio_pipeline_->Flush( base::Bind(&MediaPipelineImpl::OnFlushDone, weak_this_, true)); } if (video_pipeline_) { video_pipeline_->Flush( base::Bind(&MediaPipelineImpl::OnFlushDone, weak_this_, false)); } } void MediaPipelineImpl::SetPlaybackRate(double rate) { CMALOG(kLogControl) << __FUNCTION__ << " rate=" << rate; DCHECK(thread_checker_.CalledOnValidThread()); DCHECK((backend_state_ == BACKEND_STATE_PLAYING) || (backend_state_ == BACKEND_STATE_PAUSED)); playback_rate_ = rate; if (buffering_controller_ && buffering_controller_->IsBuffering()) return; if (rate != 0.0f) { media_pipeline_backend_->SetPlaybackRate(rate); if (backend_state_ == BACKEND_STATE_PAUSED) { media_pipeline_backend_->Resume(); backend_state_ = BACKEND_STATE_PLAYING; ResetBitrateState(); metrics::CastMetricsHelper::GetInstance()->RecordApplicationEvent( "Cast.Platform.Playing"); } } else if (backend_state_ == BACKEND_STATE_PLAYING) { media_pipeline_backend_->Pause(); backend_state_ = BACKEND_STATE_PAUSED; metrics::CastMetricsHelper::GetInstance()->RecordApplicationEvent( "Cast.Platform.Pause"); } } void MediaPipelineImpl::SetVolume(float volume) { CMALOG(kLogControl) << __FUNCTION__ << " vol=" << volume; DCHECK(thread_checker_.CalledOnValidThread()); if (audio_pipeline_) audio_pipeline_->SetVolume(volume); } base::TimeDelta MediaPipelineImpl::GetMediaTime() const { DCHECK(thread_checker_.CalledOnValidThread()); return last_media_time_; } bool MediaPipelineImpl::HasAudio() const { DCHECK(thread_checker_.CalledOnValidThread()); return audio_pipeline_ != nullptr; } bool MediaPipelineImpl::HasVideo() const { DCHECK(thread_checker_.CalledOnValidThread()); return video_pipeline_ != nullptr; } void MediaPipelineImpl::OnFlushDone(bool is_audio_stream) { CMALOG(kLogControl) << __FUNCTION__ << " is_audio_stream=" << is_audio_stream; DCHECK(pending_flush_task_); if (is_audio_stream) { DCHECK(!pending_flush_task_->audio_flushed); pending_flush_task_->audio_flushed = true; } else { DCHECK(!pending_flush_task_->video_flushed); pending_flush_task_->video_flushed = true; } if (pending_flush_task_->audio_flushed && pending_flush_task_->video_flushed) { // Stop the backend, so that the backend won't push their pending buffer, // which may be invalidated later, to hardware. (b/25342604) media_pipeline_backend_->Stop(); backend_state_ = BACKEND_STATE_INITIALIZED; metrics::CastMetricsHelper::GetInstance()->RecordApplicationEvent( "Cast.Platform.Ended"); base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, pending_flush_task_->done_cb); pending_flush_task_.reset(); } } void MediaPipelineImpl::OnBufferingNotification(bool is_buffering) { CMALOG(kLogControl) << __FUNCTION__ << " is_buffering=" << is_buffering; DCHECK(thread_checker_.CalledOnValidThread()); DCHECK((backend_state_ == BACKEND_STATE_PLAYING) || (backend_state_ == BACKEND_STATE_PAUSED)); DCHECK(buffering_controller_); DCHECK_EQ(is_buffering, buffering_controller_->IsBuffering()); if (!client_.buffering_state_cb.is_null()) { if (is_buffering) { // TODO(alokp): WebMediaPlayerImpl currently only handles HAVE_ENOUGH. // See WebMediaPlayerImpl::OnPipelineBufferingStateChanged, // http://crbug.com/144683. NOTIMPLEMENTED(); } else { client_.buffering_state_cb.Run(::media::BUFFERING_HAVE_ENOUGH); } } if (is_buffering && (backend_state_ == BACKEND_STATE_PLAYING)) { media_pipeline_backend_->Pause(); backend_state_ = BACKEND_STATE_PAUSED; metrics::CastMetricsHelper::GetInstance()->RecordApplicationEvent( "Cast.Platform.Pause"); } else if (!is_buffering && (backend_state_ == BACKEND_STATE_PAUSED)) { // Once we finish buffering, we need to honour the desired playback rate // (rather than just resuming). This way, if playback was paused while // buffering, it will remain paused rather than incorrectly resuming. SetPlaybackRate(playback_rate_); } } void MediaPipelineImpl::CheckForPlaybackStall(base::TimeDelta media_time, base::TimeTicks current_stc) { DCHECK(media_time != ::media::kNoTimestamp); // A playback stall is defined as a scenario where the underlying media // pipeline has unexpectedly stopped making forward progress. The pipeline is // NOT stalled if: // // 1. Media time is progressing // 2. The backend is paused // 3. We are currently buffering (this is captured in a separate event) if (media_time != last_media_time_ || backend_state_ != BACKEND_STATE_PLAYING || (buffering_controller_ && buffering_controller_->IsBuffering())) { if (playback_stalled_) { // Transition out of the stalled condition. base::TimeDelta stall_duration = current_stc - playback_stalled_time_; CMALOG(kLogControl) << "Transitioning out of stalled state. Stall duration was " << stall_duration.InMilliseconds() << " ms"; playback_stalled_ = false; playback_stalled_notification_sent_ = false; } return; } // Check to see if this is a new stall condition. if (!playback_stalled_) { playback_stalled_ = true; playback_stalled_time_ = current_stc; return; } // If we are in an existing stall, check to see if we've been stalled for more // than 2.5 s. If so, send a single notification of the stall event. if (!playback_stalled_notification_sent_) { base::TimeDelta current_stall_duration = current_stc - playback_stalled_time_; if (current_stall_duration.InMilliseconds() >= kPlaybackStallEventThresholdMs) { CMALOG(kLogControl) << "Playback stalled"; metrics::CastMetricsHelper::GetInstance()->RecordApplicationEvent( "Cast.Platform.PlaybackStall"); playback_stalled_notification_sent_ = true; } return; } } void MediaPipelineImpl::UpdateMediaTime() { pending_time_update_task_ = false; if ((backend_state_ != BACKEND_STATE_PLAYING) && (backend_state_ != BACKEND_STATE_PAUSED)) return; if (statistics_rolling_counter_ == 0) { if (audio_pipeline_) audio_pipeline_->UpdateStatistics(); if (video_pipeline_) video_pipeline_->UpdateStatistics(); if (backend_state_ == BACKEND_STATE_PLAYING) { base::TimeTicks current_time = base::TimeTicks::Now(); if (audio_pipeline_) audio_bytes_for_bitrate_estimation_ += audio_pipeline_->bytes_decoded_since_last_update(); if (video_pipeline_) video_bytes_for_bitrate_estimation_ += video_pipeline_->bytes_decoded_since_last_update(); elapsed_time_delta_ += current_time - last_sample_time_; if (elapsed_time_delta_.InMilliseconds() > 5000) { if (audio_pipeline_) LogEstimatedBitrate(audio_bytes_for_bitrate_estimation_, elapsed_time_delta_, "audio", "Cast.Platform.AudioBitrate"); if (video_pipeline_) LogEstimatedBitrate(video_bytes_for_bitrate_estimation_, elapsed_time_delta_, "video", "Cast.Platform.VideoBitrate"); ResetBitrateState(); } last_sample_time_ = current_time; } } statistics_rolling_counter_ = (statistics_rolling_counter_ + 1) % kStatisticsUpdatePeriod; base::TimeDelta media_time = base::TimeDelta::FromMicroseconds( media_pipeline_backend_->GetCurrentPts()); if (media_time == ::media::kNoTimestamp) { pending_time_update_task_ = true; base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::Bind(&MediaPipelineImpl::UpdateMediaTime, weak_this_), kTimeUpdateInterval); return; } base::TimeTicks stc = base::TimeTicks::Now(); CheckForPlaybackStall(media_time, stc); base::TimeDelta max_rendering_time = media_time; if (buffering_controller_) { buffering_controller_->SetMediaTime(media_time); // Receiving the same time twice in a row means playback isn't moving, // so don't interpolate ahead. if (media_time != last_media_time_) { max_rendering_time = buffering_controller_->GetMaxRenderingTime(); if (max_rendering_time == ::media::kNoTimestamp) max_rendering_time = media_time; // Cap interpolation time to avoid interpolating too far ahead. max_rendering_time = std::min(max_rendering_time, media_time + 2 * kTimeUpdateInterval); } } last_media_time_ = media_time; if (!client_.time_update_cb.is_null()) client_.time_update_cb.Run(media_time, max_rendering_time, stc); pending_time_update_task_ = true; base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::Bind(&MediaPipelineImpl::UpdateMediaTime, weak_this_), kTimeUpdateInterval); } void MediaPipelineImpl::OnError(::media::PipelineStatus error) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK_NE(error, ::media::PIPELINE_OK) << "PIPELINE_OK is not an error!"; metrics::CastMetricsHelper::GetInstance()->RecordApplicationEventWithValue( "Cast.Platform.Error", error); if (!client_.error_cb.is_null()) client_.error_cb.Run(error); } void MediaPipelineImpl::ResetBitrateState() { elapsed_time_delta_ = base::TimeDelta::FromSeconds(0); audio_bytes_for_bitrate_estimation_ = 0; video_bytes_for_bitrate_estimation_ = 0; last_sample_time_ = base::TimeTicks::Now(); } } // namespace media } // namespace chromecast
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
30b7df266eb6fd129097f881cd6f515cebc0b278
c9bc87553d573edb2b1eea604f2a35ee511bfd83
/settingwidget.cpp
2705ab27dcaca999ede0a69fdff1ea0d3abcdf96
[]
no_license
ZoomTen/libentertaining
a5c9b198c425295f1511332ee0b407e3cbf21ffc
dc7d6a85e22d247571e5d88b1fa9b1e984cdd533
refs/heads/master
2022-11-10T18:16:20.924852
2020-04-10T20:39:56
2020-04-11T21:19:03
275,983,350
0
0
null
2020-06-30T03:06:31
2020-06-30T03:06:31
null
UTF-8
C++
false
false
4,150
cpp
#include "settingwidget.h" #include "ui_settingwidget.h" #include <QSettings> #include <QKeyEvent> #include <musicengine.h> #include <tswitch.h> #include "textinputoverlay.h" struct SettingWidgetPrivate { QSettings settings; QVariant currentValue; SettingWidget::Type type; QString key; QWidget* stateWidget; QVariantMap metadata; QVariant defaultValue; }; SettingWidget::SettingWidget(QWidget *parent, Type type, QString text, QString key, QVariant defaultValue, QVariantMap metadata) : QWidget(parent), ui(new Ui::SettingWidget) { ui->setupUi(this); d = new SettingWidgetPrivate(); d->type = type; d->key = key; d->metadata = metadata; d->defaultValue = defaultValue; ui->textLabel->setText(text); d->currentValue = d->settings.value(key, defaultValue); switch (type) { case Boolean: { tSwitch* s = new tSwitch(this); s->setChecked(d->currentValue.toBool()); installStateWidget(s); break; } case Text: { QLabel* l = new QLabel(this); l->setText(d->currentValue.toString()); installStateWidget(l); break; } } } SettingWidget::~SettingWidget() { delete d; delete ui; } void SettingWidget::activate() { MusicEngine::playSoundEffect(MusicEngine::Selection); switch (d->type) { case Boolean: { d->currentValue = !d->currentValue.toBool(); break; } case Text: { bool canceled; QString set = TextInputOverlay::getText(d->metadata.value("popoverOver", QVariant::fromValue(this->parentWidget())).value<QWidget*>(), ui->textLabel->text(), &canceled, d->currentValue.toString(), d->metadata.value("noEcho", false).toBool() ? QLineEdit::Password : QLineEdit::Normal); if (!canceled) { d->currentValue = set; } } } updateStateWidget(); emit settingChanged(d->currentValue); } void SettingWidget::updateSetting() { d->currentValue = d->settings.value(d->key, d->defaultValue); updateStateWidget(); } void SettingWidget::keyPressEvent(QKeyEvent* event) { switch (event->key()) { case Qt::Key_Enter: case Qt::Key_Return: case Qt::Key_Space: this->activate(); break; case Qt::Key_Up: { QKeyEvent event(QKeyEvent::KeyPress, Qt::Key_Backtab, Qt::NoModifier); QApplication::sendEvent(this, &event); QKeyEvent event1(QKeyEvent::KeyRelease, Qt::Key_Backtab, Qt::NoModifier); QApplication::sendEvent(this, &event1); break; } case Qt::Key_Down:{ QKeyEvent event(QKeyEvent::KeyPress, Qt::Key_Tab, Qt::NoModifier); QApplication::sendEvent(this, &event); QKeyEvent event1(QKeyEvent::KeyRelease, Qt::Key_Tab, Qt::NoModifier); QApplication::sendEvent(this, &event1); } } } void SettingWidget::mousePressEvent(QMouseEvent* event) { if (event->button() == Qt::LeftButton) { event->accept(); } } void SettingWidget::mouseReleaseEvent(QMouseEvent* event) { if (event->button() == Qt::LeftButton && this->geometry().contains(this->mapToParent(event->pos()))) { activate(); } } void SettingWidget::focusInEvent(QFocusEvent* event) { emit hasFocus(); } void SettingWidget::installStateWidget(QWidget* w) { w->setFocusPolicy(Qt::NoFocus); w->setAttribute(Qt::WA_TransparentForMouseEvents); ui->typeLayout->addWidget(w); d->stateWidget = w; } void SettingWidget::updateStateWidget() { switch (d->type) { case Boolean: { tSwitch* s = qobject_cast<tSwitch*>(d->stateWidget); s->setChecked(d->currentValue.toBool()); d->settings.setValue(d->key, d->currentValue); break; } case Text: { QLabel* l = qobject_cast<QLabel*>(d->stateWidget); l->setText(d->currentValue.toString()); d->settings.setValue(d->key, d->currentValue.toString()); } } }
[ "vicr12345@gmail.com" ]
vicr12345@gmail.com
f0c55a8b21a05f5744c6ff718ba7fbebd57de5fe
706877561c8e07037aac648242189c8762b08768
/Final_Project_CISC220/BST.cpp
00ff27ebbedb7e8f6658817a1ebf6897d4b60ed5
[]
no_license
allenea/Final-Project
513981b3b0834673e9b9024a24e7704162fb64d4
86971b861130275cd6ebb680dd51a026bca5926b
refs/heads/master
2020-04-06T03:58:35.200231
2017-02-25T01:08:55
2017-02-25T01:08:55
83,095,968
1
0
null
null
null
null
UTF-8
C++
false
false
5,780
cpp
/* * BST.cpp * Matt Meyers (section 40) * Eric Allen (section 41) * TA: Leighanne Hsu */ #include "BST.hpp" #include "TNode.hpp" #include <stdlib.h> #include <string> #include <iostream> using namespace std; BST::BST() { root = NULL; count = 0; } BST::~BST() { } /* Gives the height of a node in a tree * * Parameter: TNode *n - node in question * returns the height (int) */ int BST::getHeight(TNode *n) { if (n == NULL) { return 0; } else { return n->height; }//if } /* Gives the balance factor of a node in a tree * * Parameter: TNode *n - node in question * returns the balance factor (int) */ int BST::balFac(TNode *n) { return (getHeight(n->left) - getHeight(n->right)); } /*Sets the height of a node to be one greater than the max height of its children * * Parameter: NodeTB n * no return */ void BST::setHeight(TNode *n) { int lHeight = getHeight(n->left); int rHeight = getHeight(n->right); if (lHeight > rHeight) { n->height = lHeight + 1; } else { n->height = rHeight + 1; }//if } /*Recursively inserts a TNode into an AVL tree * * Parameters: TNode *n - node being inserted * returns the root node */ TNode *BST::insert(TNode *n) { if (root == NULL) { root = n; count++; return root; }//if if (n->rank < root->rank) { root->left = insert(root->left, n); } else { root->right = insert(root->right, n); }//if/else count++; root = balance(root); return root; } /*Continuation of previous function * * Parameters: TNode *r (root of subtree) * TNode *n (node being inserted) * returns the root node */ TNode *BST::insert(TNode *r, TNode *n) { if (r == NULL) { return n; } if (n->rank < r->rank) { r->left = insert(r->left, n); } else { r->right = insert(r->right, n); } return balance(r); } /*Performs rotations to balance a tree * * Parameters: TNode *n (root of tree) * returns root node */ TNode *BST::balance(TNode *n) { setHeight(n); TNode *tmp = n; if (balFac(n) <= -2) { if (balFac(n->right) > 0) { n->right = rotateRight(n->right); } //if >0 tmp = rotateLeft(n); } else if (balFac(n) >= 2) { if (balFac(n->left) < 0) { n->left = rotateLeft(n->left); } //if <0 tmp = rotateRight(n); } //if 2/-2 return tmp; } /*Performs a right rotation around the root node n * * Parameters: TNode *n (root of tree being rotated) * Returns root of new tree */ TNode *BST::rotateRight(TNode *n) { TNode *x = n->left; TNode *tmp = x->right; x->right = n; n->left = tmp; setHeight(n); setHeight(x); return x; } /*Performs a left rotation around the root node n * * Parameters: TNode n (root of tree being rotated) * Returns root of new tree */ TNode *BST::rotateLeft(TNode *n) { TNode *x = n->right; TNode *tmp = x->left; x->left = n; n->right = tmp; setHeight(n); setHeight(x); return x; } /*Recursively prints a tree in order * * no parameters or return */ void BST::printTreeio() { if (root == NULL) { return; } //cout << "GOING LEFT" << endl; printTreeio(root->left); //cout << "BACK" << endl; cout << root->rank << ": " << root->title << endl; //cout << "GOING RIGHT" << endl; printTreeio(root->right); return; } /*Recursively prints a tree in order * * Parameters: TNode n (root of subtree) * no return */ void BST::printTreeio(TNode *n) { //cout << "IN LEFT" << endl; if (n == NULL) { return; } printTreeio(n->left); cout << n->rank << ": " << n->title << endl; printTreeio(n->right); return; } /* Recursively searches a tree the node with a certain rank * * Parameter: int n (rank in question) * returns node with rank n */ TNode *BST::search(int n) { if (root->rank == n) { return root; } if (n < root->rank) { return search(root->left, n); } else { return search(root->right, n); } } /* Recursively searches a tree the node with a certain rank * * Parameter: int n (rank in question) * TNode *r (root of subtree) * returns node with rank n */ TNode *BST::search(TNode *r, int n) { if (r == NULL) { return NULL; } if (r->rank == n) { return r; } if (n < r->rank) { return search(r->left, n); } else { return search(r->right, n); } } /* Recursively find node of rank t and print recommendations * * Parameter: int t (rank of user rated movie) * no return */ void BST::printRecs(int t) { if (root->rank == t) { cout << "Title: " << root->left->title << endl; cout << "Genre: " << root->left->genre << endl; cout << "Year: " << root->left->year << endl; cout << "Rotten Tomatoes Rating: " << root->left->rating << endl; cout << endl; cout << "Title: " << root->right->title << endl; cout << "Genre: " << root->right->genre << endl; cout << "Year: " << root->right->year << endl; cout << "Rotten Tomatoes Rating: " << root->right->rating << endl; cout << endl; return; } if (t < root->rank) { return printRecs(root->left, t); } else { return printRecs(root->right, t); } } /* Recursively find node of rank t and print recommendations * * Parameter: int t (rank of user rated movie) * TNode *n (root of subtree) * no return */ void BST::printRecs(TNode *n, int t) { if (n->rank == t) { if (n->left != NULL) { cout << "Title: " << n->left->title << endl; cout << "Genre: " << n->left->genre << endl; cout << "Year: " << n->left->year << endl; cout << "Rotten Tomatoes Rating: " << root->left->rating << endl; cout << endl; } if (n->right != NULL) { cout << "Title: " << n->right->title << endl; cout << "Genre: " << n->right->genre << endl; cout << "Year: " << n->right->year << endl; cout << "Rotten Tomatoes Rating: " << n->right->rating << endl; cout << endl; } return; } if (t < n->rank) { return printRecs(n->left, t); } else { return printRecs(n->right, t); } }
[ "ericallen@wifi-roaming-128-4-148-240.host.udel.edu" ]
ericallen@wifi-roaming-128-4-148-240.host.udel.edu
6b71db157742861cc83be21f63ae3fade0956a27
4ba4fb1fc3ac67cb5dcd0ae45b01ae7205b68fb4
/구현/10797번 10부제.cpp
e3d79231e8ba09e42aafa0002bdfdd28cee5b41f
[]
no_license
sweethoneybee/baekjoon
3c966902ee18bd7cdb98bb0899006f6928ce00ec
909f7bec28c712906d0cbf16cddf9cff997de112
refs/heads/master
2021-03-25T17:50:50.194027
2020-10-09T13:08:16
2020-10-09T13:08:16
247,637,103
0
0
null
null
null
null
UTF-8
C++
false
false
326
cpp
#include <iostream> using namespace std; int main(void) { int day = 0 ; int car[5] = {0}; int answer = 0; cin >> day; for(int i = 0; i < 5; i++) { cin >> car[i]; if(car[i] == day) { answer++; } } cout << answer; system("pause"); return 0; }
[ "jsjphone8@gmail.com" ]
jsjphone8@gmail.com
7749b05dde016fa043d9fc2604a79759ea1e1e3e
6133da1f9d3ab93185b007ec4c38622ad14743b8
/2Medium/526_BeautifulArrangement.cpp
cb1609d9e781bc22db06ce53c621e509090b98ca
[]
no_license
SreejeshSaya/LeetCode-Solutions
4a98b5d506bd8b20fcddd62743d0d472abc71847
3b7b767a2fd5a85ace0b206644badba61057c100
refs/heads/main
2023-08-03T05:31:12.706752
2021-09-28T03:30:13
2021-09-28T03:30:13
395,897,277
0
0
null
null
null
null
UTF-8
C++
false
false
441
cpp
class Solution { private: int cnt=0; bool v[16]; void calculate(int n, int pos) { if(pos>n) { ++cnt; return; } for(int i=1; i<=n; ++i) { if(!v[i] && (pos%i==0 || i%pos==0)) { v[i] = true; calculate(n, pos+1); v[i] = false; } } } public: int countArrangement(int n) { calculate(n, 1); return cnt; } };
[ "40210225+SreejeshSaya@users.noreply.github.com" ]
40210225+SreejeshSaya@users.noreply.github.com
6cedefebdd05e980cf92887191d2c19ba91cf6d7
8f66e7057a4275882f810a570e8e208caa07395a
/SEAD.cpp
62b9d4fd616fb8ddfc37f6f7c20dac0eb5f65cb1
[]
no_license
amit586/cp
ab3b1d9fc12da56cde1e69c35e2b9ba627d4695b
885420a7262ee26440099ee77f430d613c55f443
refs/heads/master
2021-03-02T12:41:35.824149
2020-08-07T11:25:33
2020-08-07T11:25:33
245,869,229
0
0
null
null
null
null
UTF-8
C++
false
false
1,554
cpp
#include<stdio.h> #include<iostream> #include<algorithm> #include<map> #include<string.h> #include<string> #include<vector> #include<math.h> #include<set> #include<queue> #include<chrono> #include<unordered_map> #include<unordered_set> #define fio ios_base::sync_with_stdio(false);cin.tie(NULL); #define ll long long #define ld long double #define pb push_back #define all(x) x.begin(),x.end() #define f first #define s second using namespace std; int searchR(vector<int> &a,int n,int t) { if(t>=a[n-1]) return n-1; int mid,l=0,r=n-1; int ans=0; while(l<=r) { mid = (l+r)/2; if(a[mid]<=t) { ans=mid; l=mid+1; } else r=mid-1; //cout<<l<<" "<<r<<" "<<mid<<endl; } return ans; } int searchL(vector<vector<int>> &st,vector<int> &lg,int R,int d) { int L=R; if(R==0) return 0; int l=0,r=R-1,mid,j; while(l<=r) { mid = (l+r)/2; j = lg[r-mid+1]; if(max(st[mid][j],st[r-(1<<j)+1][j])<=d) { L = mid; r = mid-1; } else l=mid+1; } return L; } int main() { fio int n; cin>>n; vector<int> a(n); for(int i=0;i<n;i++) cin>>a[i]; vector<int> lg(n+1,0),b(n-1,0); for(int i=2;i<=n;i++) lg[i]=lg[i/2]+1; for(int i=0;i<n-1;i++) b[i]=a[i+1]-a[i]; vector<vector<int>> st(n,vector<int> (lg[n]+1,0)); for(int i=0;i<n-1;i++) st[i][0]=b[i]; for(int j=1;j<=lg[n];j++) for(int i=0;i+(1<<j)<=n-1;i++) st[i][j] = max(st[i][j-1],st[i+(1<<(j-1))][j-1]); int q,t,d,L,R; cin>>q; while(q--) { cin>>t>>d; R = searchR(a,n,t); L = searchL(st,lg,R,d); cout<<L+1<<endl; } return 0; }
[ "amit99kumar4826@gmail.com" ]
amit99kumar4826@gmail.com
dc6824fe8f9d2c5f13c4237353b64c381fdab42b
f89b03dd7ce186caf3f5e249cc0b63579ae22186
/TCoreClient/TStreamPacket.cpp
893d6620e60a81ff66c2122b38471d422f6d979a
[]
no_license
yura0525/01_YuraHomework
cdf8c645c47c71f39bf7edf44093977b9c7d273c
7f2a37ee19e1a00eb301ff676f7fbaf8f9954b22
refs/heads/master
2021-07-12T07:12:24.630819
2019-02-26T08:11:15
2019-02-26T08:11:15
146,382,373
0
0
null
null
null
null
UHC
C++
false
false
1,954
cpp
#include "TStreamPacket.h" #include "TPacketPool.h" #include "TUser.h" bool TStreamPacket::SendMsg(MSG_TYPE msg) { return true; } void TStreamPacket::Put(char* recvBuffer, int iRecvSize, TUser* pUser) { //받는 버퍼의 용량이 부족하면 if (m_iWritePos + iRecvSize >= MAX_RECV_SIZE) { char strTemp[MAX_RECV_SIZE] = { 0, }; memcpy(strTemp, &m_RecvBuffer[m_iStartPos], m_iReadPos); ZeroMemory(&m_RecvBuffer, sizeof(char) * MAX_RECV_SIZE); memcpy(&m_RecvBuffer, &strTemp, m_iReadPos); m_pPacket = (P_UPACKET)m_RecvBuffer; m_iStartPos = 0; m_iWritePos = m_iReadPos; } memcpy(&m_RecvBuffer[m_iWritePos], recvBuffer, iRecvSize); m_iWritePos += iRecvSize; m_iReadPos += iRecvSize; if (m_iReadPos < PACKET_HEADER_SIZE) return; //패킷의 시작 m_pPacket = (P_UPACKET)&m_RecvBuffer[m_iStartPos]; //1개의 패킷 사이즈만큼 받았다면 if (m_iReadPos >= m_pPacket->ph.len) { do { UPACKET add; ZeroMemory(&add, sizeof(add)); memcpy(&add, &m_RecvBuffer[m_iStartPos], m_pPacket->ph.len); if (pUser != NULL) { pUser->m_SendPacketList.push_back(add); //printf("\nTStreamPacket::Put pUser->m_SendPacketList.push_back[%s] len[%d] type[%d]", add.msg, m_pPacket->ph.len, m_pPacket->ph.type); } else { I_Pool.AddPacket(add); } //1개의 패킷을 처리하고 남은 잔여량 크기 m_iReadPos -= m_pPacket->ph.len; //패킷의 시작 위치 m_iStartPos += m_pPacket->ph.len; //잔여량이 없을 경우 if (add.ph.len == iRecvSize) break; //잔여량이 패킷 헤더보다 작을 경우 if (m_iReadPos < PACKET_HEADER_SIZE) break; m_pPacket = (P_UPACKET)m_RecvBuffer[m_iStartPos]; } while (m_iReadPos >= m_pPacket->ph.len); } } TStreamPacket::TStreamPacket() { ZeroMemory(m_RecvBuffer, sizeof(char) * MAX_RECV_SIZE); m_iStartPos = 0; m_iWritePos = 0; m_iReadPos = 0; m_pPacket = NULL; } TStreamPacket::~TStreamPacket() { }
[ "yura0525@naver.com" ]
yura0525@naver.com
7f014af2326fe79d084d516eaf1524390f689469
ad8271700e52ec93bc62a6fa3ee52ef080e320f2
/CatalystRichPresence/CatalystSDK/PamCustomSpringboardData.h
c3fbe0efdf2d82d9963dcf7a7c34fb986b2b4cd3
[]
no_license
RubberDuckShobe/CatalystRPC
6b0cd4482d514a8be3b992b55ec143273b3ada7b
92d0e2723e600d03c33f9f027c3980d0f087c6bf
refs/heads/master
2022-07-29T20:50:50.640653
2021-03-25T06:21:35
2021-03-25T06:21:35
351,097,185
2
0
null
null
null
null
UTF-8
C++
false
false
631
h
// // Generated with FrostbiteGen by Chod // File: SDK\PamCustomSpringboardData.h // Created: Wed Mar 10 19:04:43 2021 // #ifndef FBGEN_PamCustomSpringboardData_H #define FBGEN_PamCustomSpringboardData_H #include "PamFindableMovementVolumeData.h" class PamCustomSpringboardData : public PamFindableMovementVolumeData // size = 0x80 { public: static void* GetTypeInfo() { return (void*)0x0000000142884EC0; } float m_ForwardSpeed; // 0x80 float m_JumpHeight; // 0x84 int m_NumberOfDebugLines; // 0x88 bool m_Bidirectional; // 0x8c unsigned char _0x8d[0x3]; }; // size = 0x90 #endif // FBGEN_PamCustomSpringboardData_H
[ "dog@dog.dog" ]
dog@dog.dog
e20c2fa9676407c277b1319a2a49edba927a3e51
b68d57f5a0f855dbc69a7fc840bf2fb20b7bdebe
/src/rpcmining.cpp
6544f5d999c1568ba2a862c1966697a0a4a152b6
[ "MIT" ]
permissive
scottie/SAKHI
0047e316c8fef8ff84294646f6ee008df4063794
3503f8a2a81ab3a214294f3ec4d03f84a964016c
refs/heads/master
2020-03-19T10:27:05.125341
2018-06-06T18:39:16
2018-06-06T18:39:16
136,367,728
0
0
null
null
null
null
UTF-8
C++
false
false
24,655
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpcserver.h" #include "chainparams.h" #include "main.h" #include "db.h" #include "txdb.h" #include "init.h" #include "miner.h" #include "kernel.h" #include <boost/assign/list_of.hpp> using namespace json_spirit; using namespace std; using namespace boost::assign; // Key used by getwork/getblocktemplate miners. // Allocated in InitRPCMining, free'd in ShutdownRPCMining static CReserveKey* pMiningKey = NULL; void InitRPCMining() { if (!pwalletMain) return; // getwork/getblocktemplate mining rewards paid here: pMiningKey = new CReserveKey(pwalletMain); } void ShutdownRPCMining() { if (!pMiningKey) return; delete pMiningKey; pMiningKey = NULL; } Value getsubsidy(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getsubsidy [nTarget]\n" "Returns proof-of-work subsidy value for the specified value of target."); return (uint64_t)GetProofOfWorkReward(0); } Value getstakesubsidy(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getstakesubsidy <hex string>\n" "Returns proof-of-stake subsidy value for the specified coinstake."); RPCTypeCheck(params, list_of(str_type)); vector<unsigned char> txData(ParseHex(params[0].get_str())); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); CTransaction tx; try { ssData >> tx; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } uint64_t nCoinAge; CTxDB txdb("r"); if (!tx.GetCoinAge(txdb, pindexBest, nCoinAge)) throw JSONRPCError(RPC_MISC_ERROR, "GetCoinAge failed"); return (uint64_t)GetProofOfStakeReward(pindexBest, nCoinAge, 0); } Value getmininginfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getmininginfo\n" "Returns an object containing mining-related information."); uint64_t nMinWeight, nMaxWeight, nWeight = 0; if (pwalletMain) pwalletMain->GetStakeWeight(nMinWeight, nMaxWeight, nWeight); Object obj, diff, weight; obj.push_back(Pair("blocks", (int)nBestHeight)); obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize)); obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx)); diff.push_back(Pair("proof-of-work", GetDifficulty())); diff.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true)))); diff.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval)); obj.push_back(Pair("difficulty", diff)); obj.push_back(Pair("blockvalue", (uint64_t)GetProofOfWorkReward(0))); obj.push_back(Pair("netmhashps", GetPoWMHashPS())); obj.push_back(Pair("netstakeweight", GetPoSKernelPS())); obj.push_back(Pair("errors", GetWarnings("statusbar"))); obj.push_back(Pair("pooledtx", (uint64_t)mempool.size())); weight.push_back(Pair("minimum", (uint64_t)nMinWeight)); weight.push_back(Pair("maximum", (uint64_t)nMaxWeight)); weight.push_back(Pair("combined", (uint64_t)nWeight)); obj.push_back(Pair("stakeweight", weight)); obj.push_back(Pair("stakeinterest", (uint64_t)GetCoinYearReward(nBestHeight))); obj.push_back(Pair("testnet", TestNet())); return obj; } Value getstakinginfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getstakinginfo\n" "Returns an object containing staking-related information."); uint64_t nMinWeight = 0, nMaxWeight = 0, nWeight = 0; if (pwalletMain) pwalletMain->GetStakeWeight(nMinWeight, nMaxWeight, nWeight); uint64_t nNetworkWeight = GetPoSKernelPS(); bool staking = nLastCoinStakeSearchInterval && nWeight; uint64_t nExpectedTime = staking ? (GetTargetSpacing(nBestHeight) * nNetworkWeight / nWeight) : 0; Object obj; obj.push_back(Pair("enabled", GetBoolArg("-staking", true))); obj.push_back(Pair("staking", staking)); obj.push_back(Pair("errors", GetWarnings("statusbar"))); obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize)); obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx)); obj.push_back(Pair("pooledtx", (uint64_t)mempool.size())); obj.push_back(Pair("difficulty", GetDifficulty(GetLastBlockIndex(pindexBest, true)))); obj.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval)); obj.push_back(Pair("weight", (uint64_t)nWeight)); obj.push_back(Pair("netstakeweight", (uint64_t)nNetworkWeight)); obj.push_back(Pair("expectedtime", nExpectedTime)); return obj; } Value checkkernel(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "checkkernel [{\"txid\":txid,\"vout\":n},...] [createblocktemplate=false]\n" "Check if one of given inputs is a kernel input at the moment.\n" ); RPCTypeCheck(params, list_of(array_type)(bool_type)); Array inputs = params[0].get_array(); bool fCreateBlockTemplate = params.size() > 1 ? params[1].get_bool() : false; if (vNodes.empty()) throw JSONRPCError(-9, "Sakhi is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(-10, "Sakhi is downloading blocks..."); COutPoint kernel; CBlockIndex* pindexPrev = pindexBest; unsigned int nBits = GetNextTargetRequired(pindexPrev, true); int64_t nTime = GetAdjustedTime(); nTime &= ~STAKE_TIMESTAMP_MASK; BOOST_FOREACH(Value& input, inputs) { const Object& o = input.get_obj(); const Value& txid_v = find_value(o, "txid"); if (txid_v.type() != str_type) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing txid key"); string txid = txid_v.get_str(); if (!IsHex(txid)) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid"); const Value& vout_v = find_value(o, "vout"); if (vout_v.type() != int_type) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key"); int nOutput = vout_v.get_int(); if (nOutput < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive"); COutPoint cInput(uint256(txid), nOutput); if (CheckKernel(pindexPrev, nBits, nTime, cInput)) { kernel = cInput; break; } } Object result; result.push_back(Pair("found", !kernel.IsNull())); if (kernel.IsNull()) return result; Object oKernel; oKernel.push_back(Pair("txid", kernel.hash.GetHex())); oKernel.push_back(Pair("vout", (int64_t)kernel.n)); oKernel.push_back(Pair("time", nTime)); result.push_back(Pair("kernel", oKernel)); if (!fCreateBlockTemplate) return result; int64_t nFees; auto_ptr<CBlock> pblock(CreateNewBlock(*pMiningKey, true, &nFees)); pblock->nTime = pblock->vtx[0].nTime = nTime; CDataStream ss(SER_DISK, PROTOCOL_VERSION); ss << *pblock; result.push_back(Pair("blocktemplate", HexStr(ss.begin(), ss.end()))); result.push_back(Pair("blocktemplatefees", nFees)); CPubKey pubkey; if (!pMiningKey->GetReservedKey(pubkey)) throw JSONRPCError(RPC_MISC_ERROR, "GetReservedKey failed"); result.push_back(Pair("blocktemplatesignkey", HexStr(pubkey))); return result; } Value getworkex(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getworkex [data, coinbase]\n" "If [data, coinbase] is not specified, returns extended work data.\n" ); if (vNodes.empty()) throw JSONRPCError(-9, "Sakhi is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(-10, "Sakhi is downloading blocks..."); if (pindexBest->nHeight >= Params().LastPOWBlock()) throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks"); typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t; static mapNewBlock_t mapNewBlock; static vector<CBlock*> vNewBlock; if (params.size() == 0) { // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64_t nStart; static CBlock* pblock; if (pindexPrev != pindexBest || (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)) { if (pindexPrev != pindexBest) { // Deallocate old blocks since they're obsolete now mapNewBlock.clear(); BOOST_FOREACH(CBlock* pblock, vNewBlock) delete pblock; vNewBlock.clear(); } nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); pindexPrev = pindexBest; nStart = GetTime(); // Create new block pblock = CreateNewBlock(*pMiningKey); if (!pblock) throw JSONRPCError(-7, "Out of memory"); vNewBlock.push_back(pblock); } // Update nTime pblock->nTime = max(pindexPrev->GetPastTimeLimit()+1, GetAdjustedTime()); pblock->nNonce = 0; // Update nExtraNonce static unsigned int nExtraNonce = 0; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); // Save mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig); // Prebuild hash buffers char pmidstate[32]; char pdata[128]; char phash1[64]; FormatHashBuffers(pblock, pmidstate, pdata, phash1); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); CTransaction coinbaseTx = pblock->vtx[0]; std::vector<uint256> merkle = pblock->GetMerkleBranch(0); Object result; result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata)))); result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget)))); CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << coinbaseTx; result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end()))); Array merkle_arr; BOOST_FOREACH(uint256 merkleh, merkle) { merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh))); } result.push_back(Pair("merkle", merkle_arr)); return result; } else { // Parse parameters vector<unsigned char> vchData = ParseHex(params[0].get_str()); vector<unsigned char> coinbase; if(params.size() == 2) coinbase = ParseHex(params[1].get_str()); if (vchData.size() != 128) throw JSONRPCError(-8, "Invalid parameter"); CBlock* pdata = (CBlock*)&vchData[0]; // Byte reverse for (int i = 0; i < 128/4; i++) ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]); // Get saved block if (!mapNewBlock.count(pdata->hashMerkleRoot)) return false; CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first; pblock->nTime = pdata->nTime; pblock->nNonce = pdata->nNonce; if(coinbase.size() == 0) pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second; else CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK! pblock->hashMerkleRoot = pblock->BuildMerkleTree(); assert(pwalletMain != NULL); return CheckWork(pblock, *pwalletMain, *pMiningKey); } } Value getwork(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getwork [data]\n" "If [data] is not specified, returns formatted hash data to work on:\n" " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated " \"data\" : block data\n" " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated " \"target\" : little endian hash target\n" "If [data] is specified, tries to solve the block and returns true if it was successful."); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Sakhi is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Sakhi is downloading blocks..."); if (pindexBest->nHeight >= Params().LastPOWBlock()) throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks"); typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t; static mapNewBlock_t mapNewBlock; // FIXME: thread safety static vector<CBlock*> vNewBlock; if (params.size() == 0) { // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64_t nStart; static CBlock* pblock; if (pindexPrev != pindexBest || (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)) { if (pindexPrev != pindexBest) { // Deallocate old blocks since they're obsolete now mapNewBlock.clear(); BOOST_FOREACH(CBlock* pblock, vNewBlock) delete pblock; vNewBlock.clear(); } // Clear pindexPrev so future getworks make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block pblock = CreateNewBlock(*pMiningKey); if (!pblock) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); vNewBlock.push_back(pblock); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; // Update nExtraNonce static unsigned int nExtraNonce = 0; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); // Save mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig); // Pre-build hash buffers char pmidstate[32]; char pdata[128]; char phash1[64]; FormatHashBuffers(pblock, pmidstate, pdata, phash1); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); Object result; result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata)))); result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget)))); return result; } else { // Parse parameters vector<unsigned char> vchData = ParseHex(params[0].get_str()); if (vchData.size() != 128) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); CBlock* pdata = (CBlock*)&vchData[0]; // Byte reverse for (int i = 0; i < 128/4; i++) ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]); // Get saved block if (!mapNewBlock.count(pdata->hashMerkleRoot)) return false; CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first; pblock->nTime = pdata->nTime; pblock->nNonce = pdata->nNonce; pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second; pblock->hashMerkleRoot = pblock->BuildMerkleTree(); assert(pwalletMain != NULL); return CheckWork(pblock, *pwalletMain, *pMiningKey); } } Value getblocktemplate(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getblocktemplate [params]\n" "Returns data needed to construct a block to work on:\n" " \"version\" : block version\n" " \"previousblockhash\" : hash of current highest block\n" " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n" " \"coinbaseaux\" : data that should be included in coinbase\n" " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n" " \"target\" : hash target\n" " \"mintime\" : minimum timestamp appropriate for next block\n" " \"curtime\" : current timestamp\n" " \"mutable\" : list of ways the block template may be changed\n" " \"noncerange\" : range of valid nonces\n" " \"sigoplimit\" : limit of sigops in blocks\n" " \"sizelimit\" : limit of block size\n" " \"bits\" : compressed target of next block\n" " \"height\" : height of the next block\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification."); std::string strMode = "template"; if (params.size() > 0) { const Object& oparam = params[0].get_obj(); const Value& modeval = find_value(oparam, "mode"); if (modeval.type() == str_type) strMode = modeval.get_str(); else if (modeval.type() == null_type) { /* Do nothing */ } else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); } if (strMode != "template") throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Sakhi is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Sakhi is downloading blocks..."); if (pindexBest->nHeight >= Params().LastPOWBlock()) throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks"); // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64_t nStart; static CBlock* pblock; if (pindexPrev != pindexBest || (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5)) { // Clear pindexPrev so future calls make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block if(pblock) { delete pblock; pblock = NULL; } pblock = CreateNewBlock(*pMiningKey); if (!pblock) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; Array transactions; map<uint256, int64_t> setTxIndex; int i = 0; CTxDB txdb("r"); BOOST_FOREACH (CTransaction& tx, pblock->vtx) { uint256 txHash = tx.GetHash(); setTxIndex[txHash] = i++; if (tx.IsCoinBase() || tx.IsCoinStake()) continue; Object entry; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end()))); entry.push_back(Pair("hash", txHash.GetHex())); MapPrevTx mapInputs; map<uint256, CTxIndex> mapUnused; bool fInvalid = false; if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid)) { entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut()))); Array deps; BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs) { if (setTxIndex.count(inp.first)) deps.push_back(setTxIndex[inp.first]); } entry.push_back(Pair("depends", deps)); int64_t nSigOps = GetLegacySigOpCount(tx); nSigOps += GetP2SHSigOpCount(tx, mapInputs); entry.push_back(Pair("sigops", nSigOps)); } transactions.push_back(entry); } Object aux; aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end()))); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); static Array aMutable; if (aMutable.empty()) { aMutable.push_back("time"); aMutable.push_back("transactions"); aMutable.push_back("prevblock"); } Object result; result.push_back(Pair("version", pblock->nVersion)); result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex())); result.push_back(Pair("transactions", transactions)); result.push_back(Pair("coinbaseaux", aux)); result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue)); result.push_back(Pair("target", hashTarget.GetHex())); result.push_back(Pair("mintime", (int64_t)pindexPrev->GetPastTimeLimit()+1)); result.push_back(Pair("mutable", aMutable)); result.push_back(Pair("noncerange", "00000000ffffffff")); result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS)); result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE)); result.push_back(Pair("curtime", (int64_t)pblock->nTime)); result.push_back(Pair("bits", strprintf("%08x", pblock->nBits))); result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1))); return result; } Value submitblock(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "submitblock <hex data> [optional-params-obj]\n" "[optional-params-obj] parameter is currently ignored.\n" "Attempts to submit new block to network.\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification."); vector<unsigned char> blockData(ParseHex(params[0].get_str())); CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION); CBlock block; try { ssBlock >> block; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed"); } if (params.size() > 1) { const Object& oparam = params[1].get_obj(); const Value& coinstake_v = find_value(oparam, "coinstake"); if (coinstake_v.type() == str_type) { vector<unsigned char> txData(ParseHex(coinstake_v.get_str())); CDataStream ssTx(txData, SER_NETWORK, PROTOCOL_VERSION); CTransaction txCoinStake; try { ssTx >> txCoinStake; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Coinstake decode failed"); } block.vtx.insert(block.vtx.begin() + 1, txCoinStake); block.hashMerkleRoot = block.BuildMerkleTree(); CPubKey pubkey; if (!pMiningKey->GetReservedKey(pubkey)) throw JSONRPCError(RPC_MISC_ERROR, "GetReservedKey failed"); CKey key; if (!pwalletMain->GetKey(pubkey.GetID(), key)) throw JSONRPCError(RPC_MISC_ERROR, "GetKey failed"); if (!key.Sign(block.GetHash(), block.vchBlockSig)) throw JSONRPCError(RPC_MISC_ERROR, "Sign failed"); } } bool fAccepted = ProcessBlock(NULL, &block); if (!fAccepted) return "rejected"; return Value::null; }
[ "scottlindh@gmial.com" ]
scottlindh@gmial.com
9ff7566cd46c4ca9eb8f5a8d2bca6315618331ad
cb324b8e92765c535765bbb88aa69878ce2e4fe3
/src/runtime/c++/cpp-channel.h
aff8c01c193ca3b7999051074511c718028026fc
[ "BSD-3-Clause" ]
permissive
pombredanne/Rusthon
f47756c6ae465c60012e63e02ea1e912c3b391fb
343c0b2b097b18fa910f616ec2f6c09048fe92d0
refs/heads/master
2021-01-17T21:24:29.744692
2016-09-10T10:53:59
2016-09-10T10:53:59
40,818,721
1
0
null
2016-09-10T10:54:00
2015-08-16T13:20:47
Python
UTF-8
C++
false
false
23,667
h
// Copyright 2014, Alex Horn. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #ifndef CPP_CHANNEL_H #define CPP_CHANNEL_H #include <mutex> #include <deque> #include <vector> #include <limits> #include <random> #include <memory> #include <thread> #include <cstddef> #include <cassert> #include <functional> #include <type_traits> #include <condition_variable> namespace cpp { namespace internal { #if __cplusplus <= 201103L // since C++14 in std, see Herb Sutter's blog template<class T, class ...Args> std::unique_ptr<T> make_unique(Args&& ...args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } #else using std::make_unique; #endif template<class T> struct _is_exception_safe : std::integral_constant<bool, std::is_nothrow_copy_constructible<T>::value or std::is_nothrow_move_constructible<T>::value> {}; // Note that currently handshakes between send/receives inside selects // have higher priority compared to sends/receives outside selects. // TODO: investigate and ideally also discuss other scheduling algorithms template<class T, std::size_t N> class _channel { static_assert(N < std::numeric_limits<std::size_t>::max(), "N must be strictly less than the largest possible size_t value"); private: std::mutex m_mutex; std::condition_variable m_send_begin_cv; std::condition_variable m_send_end_cv; std::condition_variable m_recv_cv; // FIFO order std::deque<std::pair</* sender */ std::thread::id, T>> m_queue; bool m_is_send_done; bool m_is_try_send_done; bool m_is_recv_ready; bool m_is_try_send_ready; bool m_is_try_recv_ready; bool is_full() const { return m_queue.size() > N; } // Is nonblocking receive and nonblocking send ready for handshake? bool is_try_ready() const { return m_is_try_recv_ready && m_is_try_send_ready; } // Block calling thread until queue becomes nonempty. While waiting // (i.e. queue is empty), give try_send() a chance to succeed. // // \pre: calling thread owns lock // \post: queue is nonempty and calling thread still owns lock void _pre_blocking_recv(std::unique_lock<std::mutex>& lock) { m_is_recv_ready = true; m_recv_cv.wait(lock, [this]{ return !m_queue.empty(); }); // TODO: support the case where both ends of a channel are inside a select assert(!is_try_ready()); } // Pop front of queue and unblock one _send() (if any) // // \pre: calling thread must own lock and queue is nonempty // \post: calling thread doesn't own lock anymore, and protocol with // try_send() and try_recv() is fulfilled void _post_blocking_recv(std::unique_lock<std::mutex>& lock) { // If queue is full, then there exists either a _send() waiting // for m_send_end_cv, or try_send() has just enqueued an element. // // In general, the converse is false: if there exists a blocking send, // then a nonblocking receive might have just dequeued an element, // i.e. queue is not full. assert(!is_full() || !m_is_send_done || !m_is_try_send_done); // blocking and nonblocking send can never occur simultaneously assert(m_is_try_send_done || m_is_send_done); m_queue.pop_front(); assert(!is_full()); // protocol with nonblocking calls m_is_try_send_done = true; m_is_recv_ready = false; m_is_try_recv_ready = false; m_is_try_send_ready = false; // Consider two concurrent _send() calls denoted by s and s'. // // Suppose s is waiting to enqueue an element (i.e. m_send_begin_cv), // whereas s' is waiting for an acknowledgment (i.e. m_send_end_cv) // that its previously enqueued element has been dequeued. Since s' // is waiting and the flag m_is_send_done is only modified by _send(), // m_is_send_done is false. Hence, we notify m_send_end_cv. This // causes s' to notify s, thereby allowing s to proceed if possible. // // Now suppose there is no such s' (say, due to the fact that the // queue never became full). Then, m_is_send_done == true. Thus, // m_send_begin_cv is notified and s proceeds if possible. Note // that if we hadn't notified s this way, then it could deadlock // in case that it waited on m_is_try_send_done to become true. if (m_is_send_done) { // unlock before notifying threads; otherwise, the // notified thread would unnecessarily block again lock.unlock(); // nonblocking, see also note below about notifications m_send_begin_cv.notify_one(); } else { // unlock before notifying threads; otherwise, the // notified thread would unnecessarily block again lock.unlock(); // we rely on the following semantics of notify_one(): // // if a notification n is issued to s (i.e. s is chosen from among // a set of threads waiting on a condition variable associated with // mutex m) but another thread t locks m before s wakes up (i.e. s // has not owned yet m after n had been issued), then n is retried // as soon as t unlocks m. The retries repeat until n arrives at s // meaning that s actually owns m and checks its wait guard. m_send_end_cv.notify_one(); } } template<class U> void _send(U&&); public: // \pre: calling thread must own mutex() // \post: calling thread doesn't own mutex() anymore template<class U> bool try_send(std::unique_lock<std::mutex>&, U&&); // \pre: calling thread must own mutex() // \post: calling thread doesn't own mutex() anymore std::pair<bool, std::unique_ptr<T>> try_recv_ptr( std::unique_lock<std::mutex>&); _channel(const _channel&) = delete; // Propagates exceptions thrown by std::condition_variable constructor _channel() : m_mutex(), m_send_begin_cv(), m_send_end_cv(), m_recv_cv(), m_queue(), m_is_send_done(true), m_is_try_send_done(true), m_is_recv_ready(false), m_is_try_send_ready(false), m_is_try_recv_ready(false) {} // channel lock std::mutex& mutex() { return m_mutex; } // Propagates exceptions thrown by std::condition_variable::wait() void send(const T& t) { _send(t); } // Propagates exceptions thrown by std::condition_variable::wait() void send(T&& t) { _send(std::move(t)); } // Propagates exceptions thrown by std::condition_variable::wait() T recv(); // Propagates exceptions thrown by std::condition_variable::wait() void recv(T&); // Propagates exceptions thrown by std::condition_variable::wait() std::unique_ptr<T> recv_ptr(); }; } template<class T, std::size_t N> class ichannel; template<class T, std::size_t N> class ochannel; /// Go-style concurrency /// Thread synchronization mechanism as in the Go language. /// As in Go, cpp::channel<T, N> are first-class values. /// /// Unlike Go, however, cpp::channels<T, N> cannot be nil /// not closed. This simplifies the usage of the library. /// /// The template arguments are as follows: /// /// * T -- type of data to be communicated over channel /// * N is zero -- synchronous channel /// * N is positive -- asynchronous channel with queue size N /// /// Note that cpp::channel<T, N>::recv() is only supported if T is /// exception safe. This is automatically checked at compile time. /// If T is not exception safe, use any of the other receive member /// functions. /// /// \see http://golang.org/ref/spec#Channel_types /// \see http://golang.org/ref/spec#Send_statements /// \see http://golang.org/ref/spec#Receive_operator /// \see http://golang.org/doc/effective_go.html#chan_of_chan template<class T, std::size_t N = 0> class channel { static_assert(N < std::numeric_limits<std::size_t>::max(), "N must be strictly less than the largest possible size_t value"); private: friend class ichannel<T, N>; friend class ochannel<T, N>; std::shared_ptr<internal::_channel<T, N>> m_channel_ptr; public: channel(const channel& other) noexcept : m_channel_ptr(other.m_channel_ptr) {} // Propagates exceptions thrown by std::condition_variable constructor channel() : m_channel_ptr(std::make_shared<internal::_channel<T, N>>()) {} channel& operator=(const channel& other) noexcept { m_channel_ptr = other.m_channel_ptr; return *this; } bool operator==(const channel& other) const noexcept { return m_channel_ptr == other.m_channel_ptr; } bool operator!=(const channel& other) const noexcept { return m_channel_ptr != other.m_channel_ptr; } bool operator==(const ichannel<T, N>&) const noexcept; bool operator!=(const ichannel<T, N>&) const noexcept; bool operator==(const ochannel<T, N>&) const noexcept; bool operator!=(const ochannel<T, N>&) const noexcept; // Propagates exceptions thrown by std::condition_variable::wait() void send(const T& t) { m_channel_ptr->send(t); } // Propagates exceptions thrown by std::condition_variable::wait() void send(T&& t) { m_channel_ptr->send(std::move(t)); } // Propagates exceptions thrown by std::condition_variable::wait() T recv() { static_assert(internal::_is_exception_safe<T>::value, "Cannot guarantee exception safety, use another recv operator"); return m_channel_ptr->recv(); } // Propagates exceptions thrown by std::condition_variable::wait() std::unique_ptr<T> recv_ptr() { return m_channel_ptr->recv_ptr(); } // Propagates exceptions thrown by std::condition_variable::wait() void recv(T& t) { m_channel_ptr->recv(t); } }; class select; /// Can only be used to receive elements of type T template<class T, std::size_t N = 0> class ichannel { private: friend class select; friend class channel<T, N>; std::shared_ptr<internal::_channel<T, N>> m_channel_ptr; public: ichannel(const channel<T, N>& other) noexcept : m_channel_ptr(other.m_channel_ptr) {} ichannel(const ichannel& other) noexcept : m_channel_ptr(other.m_channel_ptr) {} ichannel(ichannel&& other) noexcept : m_channel_ptr(std::move(other.m_channel_ptr)) {} ichannel& operator=(const ichannel& other) noexcept { m_channel_ptr = other.m_channel_ptr; return *this; } bool operator==(const ichannel& other) const noexcept { return m_channel_ptr == other.m_channel_ptr; } bool operator!=(const ichannel& other) const noexcept { return m_channel_ptr != other.m_channel_ptr; } // Propagates exceptions thrown by std::condition_variable::wait() T recv() { static_assert(internal::_is_exception_safe<T>::value, "Cannot guarantee exception safety, use another recv operator"); return m_channel_ptr->recv(); } // Propagates exceptions thrown by std::condition_variable::wait() void recv(T& t) { m_channel_ptr->recv(t); } // Propagates exceptions thrown by std::condition_variable::wait() std::unique_ptr<T> recv_ptr() { return m_channel_ptr->recv_ptr(); } }; /// Can only be used to send elements of type T template<class T, std::size_t N = 0> class ochannel { private: friend class select; friend class channel<T, N>; std::shared_ptr<internal::_channel<T, N>> m_channel_ptr; public: ochannel(const channel<T, N>& other) noexcept : m_channel_ptr(other.m_channel_ptr) {} ochannel(const ochannel& other) noexcept : m_channel_ptr(other.m_channel_ptr) {} ochannel(ochannel&& other) noexcept : m_channel_ptr(std::move(other.m_channel_ptr)) {} ochannel& operator=(const ochannel& other) noexcept { m_channel_ptr = other.m_channel_ptr; return *this; } bool operator==(const ochannel& other) const noexcept { return m_channel_ptr == other.m_channel_ptr; } bool operator!=(const ochannel& other) const noexcept { return m_channel_ptr != other.m_channel_ptr; } // Propagates exceptions thrown by std::condition_variable::wait() void send(const T& t) { m_channel_ptr->send(t); } // Propagates exceptions thrown by std::condition_variable::wait() void send(T&& t) { m_channel_ptr->send(std::move(t)); } }; /// Go's select statement /// \see http://golang.org/ref/spec#Select_statements /// /// \warning select objects must not be shared between threads /// // TODO: investigate and ideally discuss pseudo-random distribution class select { private: template<class T, std::size_t N, class NullaryFunction> class try_send_nullary { private: template<class U, class V = typename std::remove_reference<U>::type> static bool _run(ochannel<V, N>& c, U&& u, NullaryFunction f) { internal::_channel<V, N>& _c = *c.m_channel_ptr; std::unique_lock<std::mutex> lock(_c.mutex(), std::defer_lock); if (lock.try_lock() && _c.try_send(lock, std::forward<U>(u))) { assert(!lock.owns_lock()); f(); return true; } return false; } public: bool operator()(ochannel<T, N>& c, const T& t, NullaryFunction f) { return _run(c, t, f); } bool operator()(ochannel<T, N>& c, T&& t, NullaryFunction f) { return _run(c, std::move(t), f); } }; template<class T, std::size_t N, class NullaryFunction> struct try_recv_nullary { bool operator()(ichannel<T, N>& c, T& t, NullaryFunction f) { internal::_channel<T, N>& _c = *c.m_channel_ptr; std::unique_lock<std::mutex> lock(_c.mutex(), std::defer_lock); if (lock.try_lock()) { std::pair<bool, std::unique_ptr<T>> pair = _c.try_recv_ptr(lock); if (pair.first) { assert(!lock.owns_lock()); t = *pair.second; f(); return true; } } return false; } }; template<class T, std::size_t N, class UnaryFunction> struct try_recv_unary { bool operator()(ichannel<T, N>& c, UnaryFunction f) { internal::_channel<T, N>& _c = *c.m_channel_ptr; std::unique_lock<std::mutex> lock(_c.mutex(), std::defer_lock); if (lock.try_lock()) { std::pair<bool, std::unique_ptr<T>> pair = _c.try_recv_ptr(lock); if (pair.first) { assert(!lock.owns_lock()); f(std::move(*pair.second)); return true; } } return false; } }; typedef std::function<bool()> try_function; typedef std::vector<try_function> try_functions; try_functions m_try_functions; std::random_device random_device; std::mt19937 random_gen; public: select() : m_try_functions(), random_device(), random_gen(random_device()) {} /* send cases */ template<class T, std::size_t N, class U = typename std::remove_reference<T>::type> select& send_only(channel<U, N> c, T&& t) { return send_only(ochannel<U, N>(c), std::forward<T>(t)); } template<class T, std::size_t N, class U = typename std::remove_reference<T>::type> select& send_only(ochannel<U, N> c, T&& t) { return send(c, std::forward<T>(t), [](){ /* skip */ }); } template<class T, std::size_t N, class NullaryFunction, class U = typename std::remove_reference<T>::type> select& send(channel<U, N> c, T&& t, NullaryFunction f) { return send(ochannel<U, N>(c), std::forward<T>(t), f); } template<class T, std::size_t N, class NullaryFunction, class U = typename std::remove_reference<T>::type> select& send(ochannel<U, N> c, T&& t, NullaryFunction f) { m_try_functions.push_back(std::bind( try_send_nullary<U, N, NullaryFunction>(), c, std::forward<T>(t), f)); return *this; } /* receive cases */ template<class T, std::size_t N> select& recv_only(channel<T, N> c, T& t) { return recv_only(ichannel<T, N>(c), t); } template<class T, std::size_t N> select& recv_only(ichannel<T, N> c, T& t) { return recv(c, t, [](){ /* skip */ }); } template<class T, std::size_t N, class NullaryFunction> select& recv(channel<T, N> c, T& t, NullaryFunction f) { return recv(ichannel<T, N>(c), t, f); } template<class T, std::size_t N, class NullaryFunction> select& recv(ichannel<T, N> c, T& t, NullaryFunction f) { m_try_functions.push_back(std::bind( try_recv_nullary<T, N, NullaryFunction>(), c, std::ref(t), f)); return *this; } template<class T, std::size_t N, class UnaryFunction> select& recv(channel<T, N> c, UnaryFunction f) { return recv(ichannel<T, N>(c), f); } template<class T, std::size_t N, class UnaryFunction> select& recv(ichannel<T, N> c, UnaryFunction f) { m_try_functions.push_back(std::bind( try_recv_unary<T, N, UnaryFunction>(), c, f)); return *this; } /// Nonblocking like Go's select statement with default case /// Returns true if and only if exactly one case succeeded bool try_once() { const try_functions::size_type n = m_try_functions.size(), i = random_gen(); for(try_functions::size_type j = 0; j < n; j++) { if (m_try_functions.at((i + j) % n)()) return true; } return false; } void wait() { const try_functions::size_type n = m_try_functions.size(); try_functions::size_type i = random_gen(); for(;;) { i = (i + 1) % n; if (m_try_functions.at(i)()) break; } } }; template<class T, std::size_t N> bool channel<T, N>::operator==(const ichannel<T, N>& other) const noexcept { return m_channel_ptr == other.m_channel_ptr; } template<class T, std::size_t N> bool channel<T, N>::operator!=(const ichannel<T, N>& other) const noexcept { return m_channel_ptr != other.m_channel_ptr; } template<class T, std::size_t N> bool channel<T, N>::operator==(const ochannel<T, N>& other) const noexcept { return m_channel_ptr == other.m_channel_ptr; } template<class T, std::size_t N> bool channel<T, N>::operator!=(const ochannel<T, N>& other) const noexcept { return m_channel_ptr != other.m_channel_ptr; } template<class T, std::size_t N> template<class U> bool internal::_channel<T, N>::try_send( std::unique_lock<std::mutex>& lock, U&& u) { m_is_try_send_ready = true; // TODO: support the case where both ends of a channel are inside a select assert(!is_try_ready()); if ((!m_is_send_done || !m_is_try_send_done || is_full() || (0 == N - m_queue.size() && !m_is_recv_ready))) { // TODO: investigate potential LLVM libc++ RAII unlocking issue lock.unlock(); return false; } assert(m_is_send_done); assert(m_is_try_send_done); assert(!is_full()); // if enqueue should block, there must be a receiver waiting m_is_try_send_done = 0 < N - m_queue.size(); assert(m_is_try_send_done || m_is_recv_ready); m_queue.emplace_back(std::this_thread::get_id(), std::forward<U>(u)); // Let v be the value enqueued by try_send(). If m_is_try_send_done // is false, no other sender (whether blocking or not) can enqueue a // value until a receiver has dequeued v, thereby ensuring the channel // FIFO order when the queue is filled up by try_send(). Moreover, in // that case, since m_is_try_send_done implies m_is_recv_ready, such a // receiver is guaranteed to exist, and it will reset m_is_try_send_done // to true so that other senders can make progress after v has been // dequeued. And by notifying m_recv_cv, other receivers waiting for // the queue to become nonempty can make progress as well. lock.unlock(); m_recv_cv.notify_one(); return true; } template<class T, std::size_t N> std::pair<bool, std::unique_ptr<T>> internal::_channel<T, N>::try_recv_ptr( std::unique_lock<std::mutex>& lock) { m_is_try_recv_ready = true; if (m_queue.empty()) return std::make_pair(false, std::unique_ptr<T>(nullptr)); // If queue is full, then there exists either a _send() waiting // for m_send_end_cv, or try_send() has just enqueued an element. // // In general, the converse is false: if there exists a blocking send, // then a nonblocking receive might have just dequeued an element, // i.e. queue is not full. assert(!is_full() || !m_is_send_done || !m_is_try_send_done); // blocking and nonblocking send can never occur simultaneously assert(m_is_try_send_done || m_is_send_done); std::pair<std::thread::id, T> pair(std::move(m_queue.front())); assert(!is_full() || std::this_thread::get_id() != pair.first); // move/copy before pop_front() to ensure strong exception safety std::unique_ptr<T> t_ptr(make_unique<T>(std::move(pair.second))); m_queue.pop_front(); assert(!is_full()); // protocol with nonblocking calls m_is_try_send_done = true; m_is_try_recv_ready = false; m_is_try_send_ready = false; // see also explanation in _channel::_post_blocking_recv() if (m_is_send_done) { lock.unlock(); m_send_begin_cv.notify_one(); } else { lock.unlock(); m_send_end_cv.notify_one(); } return std::make_pair(true, std::move(t_ptr)); } template<class T, std::size_t N> template<class U> void internal::_channel<T, N>::_send(U&& u) { // unlock before notifying threads; otherwise, the // notified thread would unnecessarily block again { // wait (if necessary) until queue is no longer full and any // previous _send() has successfully enqueued element std::unique_lock<std::mutex> lock(m_mutex); m_send_begin_cv.wait(lock, [this]{ return m_is_send_done && m_is_try_send_done && !is_full(); }); assert(m_is_send_done); assert(m_is_try_send_done); assert(!is_full()); // TODO: support the case where both ends of a channel are inside a select assert(!is_try_ready()); m_queue.emplace_back(std::this_thread::get_id(), std::forward<U>(u)); m_is_send_done = false; } // nonblocking m_recv_cv.notify_one(); // wait (if necessary) until u has been received by another thread { std::unique_lock<std::mutex> lock(m_mutex); // It is enough to check !is_full() because m_is_send_done == false. // Therefore, no other thread could have caused the queue to fill up // during the brief time we didn't own the lock. // // Performance note: unblocks after at least N successful recv calls m_send_end_cv.wait(lock, [this]{ return !is_full(); }); m_is_send_done = true; } // see also explanation in _channel<T, N>::recv() m_send_begin_cv.notify_one(); } template<class T, std::size_t N> T internal::_channel<T, N>::recv() { static_assert(internal::_is_exception_safe<T>::value, "Cannot guarantee exception safety, use another recv operator"); std::unique_lock<std::mutex> lock(m_mutex); _pre_blocking_recv(lock); std::pair<std::thread::id, T> pair(std::move(m_queue.front())); assert(!is_full() || std::this_thread::get_id() != pair.first); _post_blocking_recv(lock); return std::move(pair.second); } template<class T, std::size_t N> void internal::_channel<T, N>::recv(T& t) { std::unique_lock<std::mutex> lock(m_mutex); _pre_blocking_recv(lock); std::pair<std::thread::id, T> pair(std::move(m_queue.front())); assert(!is_full() || std::this_thread::get_id() != pair.first); // assignment before pop_front() to ensure strong exception safety t = std::move(pair.second); _post_blocking_recv(lock); } template<class T, std::size_t N> std::unique_ptr<T> internal::_channel<T, N>::recv_ptr() { std::unique_lock<std::mutex> lock(m_mutex); _pre_blocking_recv(lock); std::pair<std::thread::id, T> pair(std::move(m_queue.front())); assert(!is_full() || std::this_thread::get_id() != pair.first); // move/copy before pop_front() to ensure strong exception safety std::unique_ptr<T> t_ptr(make_unique<T>(std::move(pair.second))); _post_blocking_recv(lock); return t_ptr; } } #endif
[ "goatman.py@gmail.com" ]
goatman.py@gmail.com
2860dc6fd7a0e3ca96cdc0870b772e3700edab78
32a24d2d936908ed93ffde118459af45ca4c6aaf
/Common/Lock.h
7fc2523b18621db99afc0b82ae8b2668345d8063
[]
no_license
crazynoodle/EpollServer-1
fa904820d28a566c1be3d8cc0bfe1d4012fe12cd
a05b50bad9da482d7cf3076708c4b17f72e193c7
refs/heads/master
2021-01-18T12:19:15.632632
2016-06-02T03:54:21
2016-06-02T03:54:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
933
h
/**************************************************************************************************** Lock.h Purpose: provide RAII style locker Author: Wookong Created Time: 2014-6-5 ****************************************************************************************************/ #ifndef __LOCK_H__ #define __LOCK_H__ #if PRAGMA_ONCE #pragma once #endif #include <stdlib.h> #include <pthread.h> template <typename lock_t> struct AutoLock { AutoLock(lock_t* lock) : _lock(lock) { _lock->lock(); } ~AutoLock(void) { _lock->unlock(); } lock_t* _lock; }; /////////////////////////////////////////////////////////////////////////////////////////////////// // class #ThreadMutexLock class ThreadMutexLock { public: ThreadMutexLock(void); ~ThreadMutexLock(void); virtual void lock(void); virtual void unlock(void); private: pthread_mutex_t m_Mutex; pthread_mutexattr_t m_attr; }; #endif //__LOCK_H__
[ "honeyligo@sina.com" ]
honeyligo@sina.com