blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cb38df47959fb8c745fd459eec3da7b4ca25f10d | d0be9a869d4631c58d09ad538b0908554d204e1c | /utf8/lib/client/cegui/CEGUI/include/elements/CEGUITree.h | 88fc1ad86a3f44cacd11aa6c44b2a2664b909edc | [] | no_license | World3D/pap | 19ec5610393e429995f9e9b9eb8628fa597be80b | de797075062ba53037c1f68cd80ee6ab3ed55cbe | refs/heads/master | 2021-05-27T08:53:38.964500 | 2014-07-24T08:10:40 | 2014-07-24T08:10:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,591 | h | /***********************************************************************
filename: CEGUITree.h
created: 5-13-07
author: Jonathan Welch (Based on Code by David Durant)
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#ifndef _CEGUITree_h_
#define _CEGUITree_h_
#include "CEGUIBase.h"
#include "CEGUIWindow.h"
#include "CEGUIWindowManager.h"
#include "elements/CEGUITreeItem.h"
#include "elements/CEGUITreeProperties.h"
#include <vector>
#if defined(_MSC_VER)
# pragma warning(push)
# pragma warning(disable : 4251)
#endif
// Start of CEGUI namespace section
namespace CEGUI
{
class ImagerySection; // forward declaration
/*!
\brief
EventArgs based class that is used for objects passed to input event handlers
concerning Tree events.
*/
class CEGUIEXPORT TreeEventArgs : public WindowEventArgs
{
public:
TreeEventArgs(Window* wnd) : WindowEventArgs(wnd) { treeItem = 0; }
TreeItem *treeItem;
};
/*!
\brief
Base class for standard Tree widget.
*/
class CEGUIEXPORT Tree : public Window
{
friend class TreeItem;
typedef std::vector<TreeItem*> LBItemList;
public:
static const String EventNamespace; //!< Namespace for global events
static const utf8 WidgetTypeName[];
/*************************************************************************
Constants
*************************************************************************/
// event names
static const String EventListContentsChanged; //!< Event triggered when the contents of the list is changed.
static const String EventSelectionChanged; //!< Event triggered when there is a change to the currently selected item(s).
static const String EventSortModeChanged; //!< Event triggered when the sort mode setting changes.
static const String EventMultiselectModeChanged; //!< Event triggered when the multi-select mode setting changes.
static const String EventVertScrollbarModeChanged; //!< Event triggered when the vertical scroll bar 'force' setting changes.
static const String EventHorzScrollbarModeChanged; //!< Event triggered when the horizontal scroll bar 'force' setting changes.
static const String EventBranchOpened; //!< Event triggered when a branch of the tree is opened by the user.
static const String EventBranchClosed; //!< Event triggered when a branch of the tree is closed by the user.
//Render the actual tree
void doTreeRender() { populateRenderCache(); }
//UpdateScrollbars
void doScrollbars() { configureScrollbars(); }
/*************************************************************************
Accessor Methods
*************************************************************************/
/*!
\brief
Return number of items attached to the list box
\return
the number of items currently attached to this list box.
*/
size_t getItemCount(void) const {return d_listItems.size();}
/*!
\brief
Return the number of selected items in the list box.
\return
Total number of attached items that are in the selected state.
*/
size_t getSelectedCount(void) const;
/*!
\brief
Return a pointer to the first selected item.
\return
Pointer to a TreeItem based object that is the first selected item in the list. will return NULL if
no item is selected.
*/
TreeItem* getFirstSelectedItem(void) const;
/*!
\brief
Return a pointer to the first selected item.
\return
Pointer to a TreeItem based object that is the last item selected by the user, not necessarily the
last selected in the list. Will return NULL if no item is selected.
*/
TreeItem* getLastSelectedItem(void) const { return d_lastSelected; }
/*!
\brief
Return a pointer to the next selected item after item \a start_item
\param start_item
Pointer to the TreeItem where the search for the next selected item is to begin. If this
parameter is NULL, the search will begin with the first item in the list box.
\return
Pointer to a TreeItem based object that is the next selected item in the list after
the item specified by \a start_item. Will return NULL if no further items were selected.
\exception InvalidRequestException thrown if \a start_item is not attached to this list box.
*/
TreeItem* getNextSelected(const TreeItem* start_item) const;
TreeItem* getNextSelectedItemFromList(const LBItemList &itemList, const TreeItem* start_item, bool foundStartItem) const;
/*!
\brief
return whether list sorting is enabled
\return
true if the list is sorted, false if the list is not sorted
*/
bool isSortEnabled(void) const {return d_sorted;}
void setItemRenderArea(Rect& r)
{
d_itemArea = r;
}
Scrollbar* getVertScrollbar() { return d_vertScrollbar; }
Scrollbar* getHorzScrollbar() { return d_horzScrollbar; }
/*!
\brief
return whether multi-select is enabled
\return
true if multi-select is enabled, false if multi-select is not enabled.
*/
bool isMultiselectEnabled(void) const {return d_multiselect;}
bool isItemTooltipsEnabled(void) const {return d_itemTooltips;}
/*!
\brief
Search the list for an item with the specified text
\param text
String object containing the text to be searched for.
\param start_item
TreeItem where the search is to begin, the search will not include \a item. If \a item is
NULL, the search will begin from the first item in the list.
\return
Pointer to the first TreeItem in the list after \a item that has text matching \a text. If
no item matches the criteria NULL is returned.
\exception InvalidRequestException thrown if \a item is not attached to this list box.
*/
TreeItem* findFirstItemWithText(const String32& text);
TreeItem* findNextItemWithText(const String32& text, const TreeItem* start_item);
TreeItem* findItemWithTextFromList(const LBItemList &itemList, const String32& text, const TreeItem* start_item, bool foundStartItem);
/*!
\brief
Search the list for an item with the specified text
\param text
String32 object containing the text to be searched for.
\param start_item
TreeItem where the search is to begin, the search will not include \a item. If \a item is
NULL, the search will begin from the first item in the list.
\return
Pointer to the first TreeItem in the list after \a item that has text matching \a text. If
no item matches the criteria NULL is returned.
\exception InvalidRequestException thrown if \a item is not attached to this list box.
*/
TreeItem* findFirstItemWithID(uint searchID);
TreeItem* findNextItemWithID(uint searchID, const TreeItem* start_item);
TreeItem* findItemWithIDFromList(const LBItemList &itemList, uint searchID, const TreeItem* start_item, bool foundStartItem);
/*!
\brief
Return whether the specified TreeItem is in the List
\return
true if TreeItem \a item is in the list, false if TreeItem \a item is not in the list.
*/
bool isTreeItemInList(const TreeItem* item) const;
/*!
\brief
Return whether the vertical scroll bar is always shown.
\return
- true if the scroll bar will always be shown even if it is not required.
- false if the scroll bar will only be shown when it is required.
*/
bool isVertScrollbarAlwaysShown(void) const;
/*!
\brief
Return whether the horizontal scroll bar is always shown.
\return
- true if the scroll bar will always be shown even if it is not required.
- false if the scroll bar will only be shown when it is required.
*/
bool isHorzScrollbarAlwaysShown(void) const;
/*************************************************************************
Manipulator Methods
*************************************************************************/
/*!
\brief
Initialise the Window based object ready for use.
\note
This must be called for every window created. Normally this is handled automatically by the WindowFactory for each Window type.
\return
Nothing
*/
virtual void initialise(void);
/*!
\brief
Remove all items from the list.
Note that this will cause 'AutoDelete' items to be deleted.
*/
void resetList(void);
/*!
\brief
Add the given TreeItem to the list.
\param item
Pointer to the TreeItem to be added to the list. Note that it is the passed object that is added to the
list, a copy is not made. If this parameter is NULL, nothing happens.
\return
Nothing.
*/
void addItem(TreeItem* item);
/*!
\brief
Insert an item into the list box after a specified item already in the list.
Note that if the list is sorted, the item may not end up in the requested position.
\param item
Pointer to the TreeItem to be inserted. Note that it is the passed object that is added to the
list, a copy is not made. If this parameter is NULL, nothing happens.
\param position
Pointer to a TreeItem that \a item is to be inserted after. If this parameter is NULL, the item is
inserted at the start of the list.
\return
Nothing.
\exception InvalidRequestException thrown if no TreeItem \a position is attached to this list box.
*/
void insertItem(TreeItem* item, const TreeItem* position);
/*!
\brief
Removes the given item from the list box. If the item is has the auto delete state set, the item will be deleted.
\param item
Pointer to the TreeItem that is to be removed. If \a item is not attached to this list box then nothing
will happen.
\return
Nothing.
*/
void removeItem(const TreeItem* item);
/*!
\brief
Clear the selected state for all items.
\return
Nothing.
*/
void clearAllSelections(void);
bool clearAllSelectionsFromList(const LBItemList &itemList);
/*!
\brief
Set whether the list should be sorted.
\param setting
true if the list should be sorted, false if the list should not be sorted.
\return
Nothing.
*/
void setSortingEnabled(bool setting);
/*!
\brief
Set whether the list should allow multiple selections or just a single selection
\param setting
true if the widget should allow multiple items to be selected, false if the widget should only allow
a single selection.
\return
Nothing.
*/
void setMultiselectEnabled(bool setting);
/*!
\brief
Set whether the vertical scroll bar should always be shown.
\param setting
true if the vertical scroll bar should be shown even when it is not required. false if the vertical
scroll bar should only be shown when it is required.
\return
Nothing.
*/
void setShowVertScrollbar(bool setting);
/*!
\brief
Set whether the horizontal scroll bar should always be shown.
\param setting
true if the horizontal scroll bar should be shown even when it is not required. false if the horizontal
scroll bar should only be shown when it is required.
\return
Nothing.
*/
void setShowHorzScrollbar(bool setting);
void setItemTooltipsEnabled(bool setting);
/*!
\brief
Set the select state of an attached TreeItem.
This is the recommended way of selecting and deselecting items attached to a list box as it respects the
multi-select mode setting. It is possible to modify the setting on TreeItems directly, but that approach
does not respect the settings of the list box.
\param item
The TreeItem to be affected. This item must be attached to the list box.
\param state
true to select the item, false to de-select the item.
\return
Nothing.
\exception InvalidRequestException thrown if \a item is not attached to this list box.
*/
void setItemSelectState(TreeItem* item, bool state);
/*!
\brief
Set the select state of an attached TreeItem.
This is the recommended way of selecting and deselecting items attached to a list box as it respects the
multi-select mode setting. It is possible to modify the setting on TreeItems directly, but that approach
does not respect the settings of the list box.
\param item_index
The zero based index of the TreeItem to be affected. This must be a valid index (0 <= index < getItemCount())
\param state
true to select the item, false to de-select the item.
\return
Nothing.
\exception InvalidRequestException thrown if \a item_index is out of range for the list box
*/
void setItemSelectState(size_t item_index, bool state);
/*!
\brief
Set the LookNFeel that shoule be used for this window.
\param look
String object holding the name of the look to be assigned to the window.
\return
Nothing.
\exception UnknownObjectException
thrown if the look'n'feel specified by \a look does not exist.
\note
Once a look'n'feel has been assigned it is locked - as in cannot be changed.
*/
virtual void setLookNFeel(const String& falgardType, const String& look);
/*!
\brief
Causes the list box to update it's internal state after changes have been made to one or more
attached TreeItem objects.
Client code must call this whenever it has made any changes to TreeItem objects already attached to the
list box. If you are just adding items, or removed items to update them prior to re-adding them, there is
no need to call this method.
\return
Nothing.
*/
void handleUpdatedItemData(void);
/*!
\brief
Ensure the item at the specified index is visible within the list box.
\param item
Pointer to the TreeItem to be made visible in the list box.
\return
Nothing.
\exception InvalidRequestException thrown if \a item is not attached to this list box.
*/
void ensureItemIsVisible(const TreeItem* item);
/*************************************************************************
Construction and Destruction
*************************************************************************/
/*!
\brief
Constructor for Tree base class.
*/
Tree(const String& type, const String& name);
/*!
\brief
Destructor for Tree base class.
*/
virtual ~Tree(void);
protected:
/*************************************************************************
Abstract Implementation Functions (must be provided by derived class)
*************************************************************************/
/*!
\brief
Return a Rect object describing, in un-clipped pixels, the window relative area
that is to be used for rendering list items.
\return
Rect object describing the area of the Window to be used for rendering
list box items.
*/
virtual Rect getTreeRenderArea(void) const
{
return d_itemArea;
}
/*!
\brief
create and return a pointer to a Scrollbar widget for use as vertical scroll bar
\param name
String holding the name to be given to the created widget component.
\return
Pointer to a Scrollbar to be used for scrolling the list vertically.
*/
virtual Scrollbar* createVertScrollbar(const String& name) const
{
return (Scrollbar*)(WindowManager::getSingleton().getWindow(name));
}
/*!
\brief
create and return a pointer to a Scrollbar widget for use as horizontal scroll bar
\param name
String holding the name to be given to the created widget component.
\return
Pointer to a Scrollbar to be used for scrolling the list horizontally.
*/
virtual Scrollbar* createHorzScrollbar(const String& name) const
{
return (Scrollbar*)(WindowManager::getSingleton().getWindow(name));
}
/*!
\brief
Perform caching of the widget control frame and other 'static' areas. This
method should not render the actual items. Note that the items are typically
rendered to layer 3, other layers can be used for rendering imagery behind and
infront of the items.
\return
Nothing.
*/
virtual void cacheTreeBaseImagery()
{
}
/*************************************************************************
Implementation Functions
*************************************************************************/
/*!
\brief
Add list box specific events
*/
void addTreeEvents(void);
/*!
\brief
display required integrated scroll bars according to current state of the list box and update their values.
*/
void configureScrollbars(void);
/*!
\brief
select all strings between positions \a start and \a end. (inclusive)
including \a end.
*/
void selectRange(size_t start, size_t end);
/*!
\brief
Return the sum of all item heights
*/
float getTotalItemsHeight(void) const;
void getTotalItemsInListHeight(const LBItemList &itemList, float *heightSum) const;
/*!
\brief
Return the width of the widest item
*/
float getWidestItemWidth(void) const;
void getWidestItemWidthInList(const LBItemList &itemList, int itemDepth, float *widest) const;
/*!
\brief
Clear the selected state for all items (implementation)
\return
true if treeItem was found in the search, false if it was not.
*/
bool getHeightToItemInList(const LBItemList &itemList, const TreeItem *treeItem, int itemDepth, float *height) const;
/*!
\brief
Clear the selected state for all items (implementation)
\return
true if some selections were cleared, false nothing was changed.
*/
bool clearAllSelections_impl(void);
/*!
\brief
Return the TreeItem under the given window local pixel co-ordinate.
\return
TreeItem that is under window pixel co-ordinate \a pt, or NULL if no
item is under that position.
*/
TreeItem* getItemAtPoint(const Point& pt) const;
TreeItem* getItemFromListAtPoint(const LBItemList &itemList, float *bottomY, const Point& pt) const;
/*!
\brief
Remove all items from the list.
\note
Note that this will cause 'AutoDelete' items to be deleted.
\return
- true if the list contents were changed.
- false if the list contents were not changed (list already empty).
*/
bool resetList_impl(void);
/*!
\brief
Return whether this window was inherited from the given class name at some point in the inheritance heirarchy.
\param class_name
The class name that is to be checked.
\return
true if this window was inherited from \a class_name. false if not.
*/
virtual bool testClassName_impl(const String& class_name) const
{
if (class_name==(const utf8*)"Tree") return true;
return Window::testClassName_impl(class_name);
}
/*!
\brief
Internal handler that is triggered when the user interacts with the scrollbars.
*/
bool handle_scrollChange(const EventArgs& args);
// overridden from Window base class.
virtual void populateRenderCache();
void drawItemList(LBItemList &itemList, Rect &itemsArea, float widest, Vector3 &itemPos, RenderCache& cache, float alpha);
/*************************************************************************
New event handlers
*************************************************************************/
/*!
\brief
Handler called internally when the list contents are changed
*/
virtual void onListContentsChanged(WindowEventArgs& e);
/*!
\brief
Handler called internally when the currently selected item or items changes.
*/
virtual void onSelectionChanged(TreeEventArgs& e);
/*!
\brief
Handler called internally when the sort mode setting changes.
*/
virtual void onSortModeChanged(WindowEventArgs& e);
/*!
\brief
Handler called internally when the multi-select mode setting changes.
*/
virtual void onMultiselectModeChanged(WindowEventArgs& e);
/*!
\brief
Handler called internally when the forced display of the vertical scroll bar setting changes.
*/
virtual void onVertScrollbarModeChanged(WindowEventArgs& e);
/*!
\brief
Handler called internally when the forced display of the horizontal scroll bar setting changes.
*/
virtual void onHorzScrollbarModeChanged(WindowEventArgs& e);
/*!
\brief
Handler called internally when the user opens a branch of the tree.
*/
virtual void onBranchOpened(TreeEventArgs& e);
/*!
\brief
Handler called internally when the user closes a branch of the tree.
*/
virtual void onBranchClosed(TreeEventArgs& e);
/*************************************************************************
Overridden Event handlers
*************************************************************************/
virtual void onSized(WindowEventArgs& e);
virtual void onMouseButtonDown(MouseEventArgs& e);
virtual void onMouseWheel(MouseEventArgs& e);
virtual void onMouseMove(MouseEventArgs& e);
/*************************************************************************
Implementation Data
*************************************************************************/
bool d_sorted; //!< true if list is sorted
bool d_multiselect; //!< true if multi-select is enabled
bool d_forceVertScroll; //!< true if vertical scrollbar should always be displayed
bool d_forceHorzScroll; //!< true if horizontal scrollbar should always be displayed
bool d_itemTooltips; //!< true if each item should have an individual tooltip
Scrollbar* d_vertScrollbar; //!< vertical scroll-bar widget
Scrollbar* d_horzScrollbar; //!< horizontal scroll-bar widget
LBItemList d_listItems; //!< list of items in the list box.
TreeItem* d_lastSelected; //!< holds pointer to the last selected item (used in range selections)
ImagerySection *openButtonImagery;
ImagerySection *closeButtonImagery;
private:
/*************************************************************************
Static Properties for this class
*************************************************************************/
static TreeProperties::Sort d_sortProperty;
static TreeProperties::MultiSelect d_multiSelectProperty;
static TreeProperties::ForceVertScrollbar d_forceVertProperty;
static TreeProperties::ForceHorzScrollbar d_forceHorzProperty;
static TreeProperties::ItemTooltips d_itemTooltipsProperty;
/*************************************************************************
Private methods
*************************************************************************/
void addTreeProperties(void);
Rect d_itemArea;
};
/*!
\brief
Helper function used in sorting to compare two list box item text strings
via the TreeItem pointers and return if \a a is less than \a b.
*/
bool lbi_less(const TreeItem* a, const TreeItem* b);
/*!
\brief
Helper function used in sorting to compare two list box item text strings
via the TreeItem pointers and return if \a a is greater than \a b.
*/
bool lbi_greater(const TreeItem* a, const TreeItem* b);
} // End of CEGUI namespace section
#if defined(_MSC_VER)
# pragma warning(pop)
#endif
#endif // end of guard _CEGUITree_h_
| [
"viticm@126.com"
] | viticm@126.com |
2e4384524a2a4e2141cb3b25c637f5c67c3caa9b | 33526de9b19486100705efe849e78f6bfea25e3f | /BOJ/2609.cpp | 4f7f8615b14aae2a160fdbcc868c98e7d1c77128 | [] | no_license | whrlgus/PS | 32f6771f03afdfdec61f12b790e527f4b2a5e8bc | 596f91e7e40485b96a1199a4acc1ba9fb05d9ab2 | refs/heads/master | 2023-07-31T14:34:59.279677 | 2021-09-12T11:20:24 | 2021-09-12T11:20:24 | 277,535,565 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 296 | cpp | #include<bits/stdc++.h>
#define f(i,l,r) for(int i=l;i<r;++i)
using namespace std;
int gcd(int a, int b){
return b?gcd(b,a%b):a;
}
int main(){
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int a,b;cin>>a>>b;
int tmp=gcd(a,b);
cout<<tmp<<'\n';
cout<<tmp*a/tmp*b/tmp;
return 0;
}
| [
"whrlgus33@gmail.com"
] | whrlgus33@gmail.com |
f35a8bff1eb4cf9cf012c76f45bcae1139900b05 | 82e6375dedb79df18d5ccacd048083dae2bba383 | /src/main/tests/test-object.cpp | 069cf77917b0cd3c733d18e255124594652472af | [] | 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 | 3,177 | cpp | #include "y/object.hpp"
#include "y/utest/run.hpp"
#include "y/memory/zblock.hpp"
#include "y/memory/allocator/global.hpp"
#include "y/os/real-time-clock.hpp"
#include <cstdlib>
using namespace upsylon;
namespace
{
struct block_t
{
void *addr;
size_t size;
};
}
Y_UTEST(object0)
{
size_t N = 16384;
size_t Iter = 16;
if(argc>1) N = atol(argv[1]);
if(argc>2) Iter = atol(argv[2]);
zblock<block_t,memory::global> org(N);
block_t *blk = *org;
uint64_t s = 0;
for(size_t iter=0;iter<Iter;++iter)
{
for(size_t i=0;i<N;++i)
{
block_t &b = blk[i];
const size_t n = (b.size = 1+alea.lt(2*Y_LIMIT_SIZE));
{
void *addr = 0;
uint64_t mark = real_time_clock::ticks();
{
Y_LOCK(memory::global::access);
addr = calloc(1,n);
}
s += (real_time_clock::ticks()-mark);
b.addr = addr;
if(!addr) throw exception("no memory for calloc");
}
}
alea.shuffle(blk,N);
for(size_t i=0;i<N;++i)
{
block_t &b = blk[i];
//const size_t n = b.size;
{
void *addr = b.addr;
uint64_t mark = real_time_clock::ticks();
{
Y_LOCK(memory::global::access);
free(addr);
}
s += (real_time_clock::ticks()-mark);
}
b.addr = 0;
b.size = 0;
}
}
std::cerr << "time0=" << double(s)/double(N*Iter) << std::endl;
}
Y_UTEST_DONE()
Y_UTEST(objectY)
{
size_t N = 16384;
size_t Iter = 16;
if(argc>1) N = atol(argv[1]);
if(argc>2) Iter = atol(argv[2]);
zblock<block_t,memory::global> org(N);
block_t *blk= *org;
uint64_t s = 0;
for(size_t iter=0;iter<Iter;++iter)
{
for(size_t i=0;i<N;++i)
{
block_t &b = blk[i];
const size_t n = (b.size = 1+alea.lt(2*Y_LIMIT_SIZE));
{
void *addr = 0;
uint64_t mark = real_time_clock::ticks();
{
addr = object::operator new(n);
}
s += (real_time_clock::ticks()-mark);
b.addr = addr;
if(!addr)
{
throw exception("no memory for calloc");
}
}
}
alea.shuffle(blk,N);
for(size_t i=0;i<N;++i)
{
block_t &b = blk[i];
const size_t n = b.size;
{
void *addr = b.addr;
uint64_t mark = real_time_clock::ticks();
{
object::operator delete(addr,n);
}
s += (real_time_clock::ticks()-mark);
}
b.addr = 0;
b.size = 0;
}
}
std::cerr << "timeY=" << double(s)/double(N*Iter) << std::endl;
}
Y_UTEST_DONE()
| [
"yann.bouret@gmail.com"
] | yann.bouret@gmail.com |
00d318632781a83825ec11a636a475ed4971aff7 | 48c93efbea5fd5abb2f668f7ee769bea6fe75be9 | /43Set/set.h | 6fd03a2097a652d69e9e0d2b1946edf1869712f9 | [] | no_license | ssmero/CSCE240 | f960f1a1a0b7bf5b2c7ee36a512a8a3e7ee435aa | 5fbfde18131fa8cd86a9c8467984e44660806cef | refs/heads/master | 2020-04-25T13:35:10.444038 | 2019-02-27T01:08:03 | 2019-02-27T01:08:03 | 172,814,202 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,984 | h | /****************************************************************
* Header for the 'Set' class
*
* Author/copyright: Duncan Buell
* Used with permission and modified by: Jane Random Hacker
* Date: 13 May 2016
**/
#ifndef SET_H
#define SET_H
#include <vector>
#include <set>
using namespace std;
#include "../../Utilities/utils.h"
#include "../../Utilities/scanner.h"
#include "../../Utilities/scanline.h"
class Set {
public:
/****************************************************************
* Constructors and destructors for the class.
**/
Set(); // default
Set(int n); // create a set from a single integer
Set(string s); // create a set by parsing a string for integers
Set(vector<int> v); // create a set from a vector of integers
Set(const Set& the_set); // create a set from another set
virtual ~Set();
/****************************************************************
* General functions.
**/
bool AddToSet(const int e);
bool AddToSet(vector<int> v);
int Card() const;
bool ContainsElement(const int e) const;
bool ContainsSet(const Set& that) const;
bool Equals(const Set& that) const;
vector<int> GetElements() const;
bool IsContainedIn(const Set& that) const;
bool IsEmpty() const;
bool RemoveFromSet(const int e);
string ToString() const;
Set SetDifference(const Set& that) const;
Set SetIntersection(const Set& that) const;
Set SetSymmetricDifference(const Set& that) const;
Set SetUnion(const Set& that) const;
friend const Set operator +(const Set& set1, const Set& set2); // union
friend const Set operator &(const Set& set1, const Set& set2); // intersection
friend const Set operator -(const Set& set1, const Set& set2); // sym diff
friend const bool operator ==(const Set& set1, const Set& set2);
friend ostream& operator <<(ostream& out_stream, const Set& the_set);
private:
set<int> the_elements_;
/****************************************************************
* General private functions.
**/
};
#endif // SET_H
| [
"noreply@github.com"
] | noreply@github.com |
26a2e987b61f5a4bb948fc4813d51d5b0a6912eb | 0c207f8e5852398dbb91b96866242404e18076ae | /_cryptoys/prime3/basex.cc | 2a6b5e3fa0d1c681f6c5bc4846413acb7aef4beb | [] | no_license | BGCX067/ezonas-hg-to-git | a0ac2d6391aee65fc0156f96a56b88629b2694ed | a3904ba6faf55952ac19a1e95592ade5b042afd4 | refs/heads/master | 2016-09-01T08:54:09.134157 | 2012-04-28T14:05:12 | 2012-04-28T14:05:12 | 48,752,679 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,349 | cc | #include "basex.h"
basex :: basex() {}
// those conversions are the trickiest
inline string basex :: n2s30(intg ul)
{
// DADADADADA
string str30 = ""; // ADDED
int down = POWER30; // oddly it's the same as 27, check sizepower.py
while (ul > int_pow (30, down)) --down;
intg r = ul;
while (down > -1) // loop
{
if (ul >= int_pow ((intg)30, down))
{
str30 += chr30(r / int_pow(30, down)); //
r %= int_pow(30, down);
}
--down;
}
if(str30.length() == 1)
return " " + str30;
return str30; // ADDED
// Don't forget I changed numb to ul !
}
inline string basex :: n2s36(intg ul)
{
// DADADADADA
string str36 = ""; // ADDED
int down = POWER30; // oddly it's the same as 27, check sizepower.py
while (ul > int_pow (36, down))
--down;
intg r = ul;
while (down > -1) // loop
{
if (ul >= int_pow ((intg)36, down))
{
str36 += chr36(r / int_pow(36, down));
r %= int_pow(36, down);
}
--down;
}
if(str36.length() == 1)
return " " + str36;
return str36; // ADDED
// Don't forget I changed numb to ul !
}
// those conversions are the easiest
inline intg basex :: s2n30(string str)
{
intg sz = str.length();
if (str == "0" or sz > POWER30)
{ cout << "it's NULL" << endl; return 0u; }
intg r = 0;
for (intg i = 0; i < sz; ++i)
r += num30(str[i]) * int_pow (30, sz-i-1);
return r;
}
inline intg basex :: s2n36(string str)
{
intg sz = str.length();
if (str == "0" or sz > POWER30)
{ cout << "it's NULL" << endl; return 0u; }
intg r = 0;
for (intg i = 0; i < sz; ++i)
r += num36(str[i]) * int_pow (36, sz-i-1);
return r;
}
/// accessory functions
inline char basex :: chr30 (intg n)
{
switch(n)
{
// case 0 :
case 1 : case 2 : case 3 : case 4 : case 5 :
case 6 : case 7 : case 8 : case 9 :
return char(n + '0');
case 10 : case 11 : case 12 : case 13 : case 14 :
case 15 : case 16 : case 17 : case 18 : case 19 :
case 20 : case 21 : case 22 : case 23 : case 24 :
case 25 : case 26 : case 27 : case 28 : case 29 :
// case 30 : case 31 : case 32 : case 33 : case 34 :
// case 35 :
return char('A' + n - 10);
// return char('A' + n - 10);
default:
return '_';
}
}
inline char basex :: chr36 (intg n)
{
switch(n)
{
// case 0 :
case 1 : case 2 : case 3 : case 4 : case 5 :
case 6 : case 7 : case 8 : case 9 :
return char(n + '0');
case 10 : case 11 : case 12 : case 13 : case 14 :
case 15 : case 16 : case 17 : case 18 : case 19 :
case 20 : case 21 : case 22 : case 23 : case 24 :
case 25 : case 26 : case 27 : case 28 : case 29 :
case 30 : case 31 : case 32 : case 33 : case 34 :
case 35 :
return char('A' + n - 10);
default:
return '_';
}
}
inline char basex :: chr30_ (intg n)
{
if (n < 0 or n > 29) return '_';
if (n < 10)
return (char)(n + ASC_OFS_N);
return (char)(n + ASC_OFS - 9);
}
inline char basex :: chr36_ (intg n)
{
if (n < 0 or n > 35) return '_';
if (n < 10)
return (char)(n + ASC_OFS_N);
return (char)(n + ASC_OFS - 9);
}
inline intg basex :: int_pow (intg n, int p)
{
if (p == 0) return 1;
intg r = 1;
for(int i = 0; i < p; ++i) r *= n;
return r;
}
void basex :: show_mult_table30()
{
cout << "30-based [[0-9][A-T]] multiplication table" << endl << " ";
for(int i = 1; i < 31; ++i)
{
if(i < 10) cout << " .";
else cout << " " << i;
}
for(int i = 1; i < 31; ++i)
{
if(i < 10) cout << endl << " . ";
else cout << endl << "(" << i << ")" ;
cout << n2s30(i) << ": ";
for(int j = 2; j < 31; ++j)
{
cout << n2s30(i*j) << " ";
}
}
cout << endl << "done !" << endl;
}
void basex :: show_mult_table36()
{
cout << "36-based [[0-9][A-Z]] multiplication table" << endl << " ";
for(int i = 1; i < 37; ++i)
{
if(i < 10) cout << " .";
else cout << " " << i;
}
for(int i = 1; i < 37; ++i)
{
if(i < 10) cout << endl << " . ";
else cout << endl << "(" << i << ")" ;
cout << n2s36(i) << ": ";
for(int j = 2; j < 37; ++j)
cout << n2s36(i*j) << " ";
}
cout << endl << "done !" << endl;
}
void basex :: show30(intg u) { cout << u << " -> 30 -> " << n2s30(u) << endl; }
void basex :: show36(intg u) { cout << u << " -> 36 -> " << n2s36(u) << endl; }
void basex :: show30(string str) { cout << str << " -> 30 -> " << s2n30(str) << endl; }
void basex :: show36(string str) { cout << str << " -> 36 -> " << s2n36(str) << endl; }
intg basex :: num30_ (char c)
{
if (c < '0' or c > 'T' or (c > '9' and c < 'A')) return '_';
if (c < ASC_OFS_N10) return (intg)(c - ASC_OFS_N);
if (c == '0') return 0;
return (intg)(c - ASC_OFS + 9);
}
intg basex :: num36_ (char c)
{
if (c < '0' or c > 'Z' or (c > '9' and c < 'A')) return '_';
if (c < ASC_OFS_N10) return (intg)(c - ASC_OFS_N);
if (c == '0') return 0;
return (intg)(c - ASC_OFS + 9);
}
intg basex :: num30 (char c)
{
switch (c)
{
case '0':
case '1': case '2': case '3': case '4': case '5':
case '6': case '7': case '8': case '9':
return c - '0';
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F': case 'G': case 'H': case 'I': case 'J':
case 'K': case 'L': case 'M': case 'N': case 'O':
case 'P': case 'Q': case 'R': case 'S': case 'T':
// case 'U': case 'V': case 'W': case 'X': case 'Y':
// case 'Z':
return c - '@' + 9;
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f': case 'g': case 'h': case 'i': case 'j':
case 'k': case 'l': case 'm': case 'n': case 'o':
case 'p': case 'q': case 'r': case 's': case 't':
// case 'u': case 'v': case 'w': case 'x': case 'y':
// case 'z':
return c - '`' + 9;
default:
return '_';
}
}
intg basex :: num36 (char c)
{
switch (c)
{
case '0':
case '1': case '2': case '3': case '4': case '5':
case '6': case '7': case '8': case '9':
return c - '0';
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F': case 'G': case 'H': case 'I': case 'J':
case 'K': case 'L': case 'M': case 'N': case 'O':
case 'P': case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X': case 'Y':
case 'Z':
return c - '@' + 9;
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f': case 'g': case 'h': case 'i': case 'j':
case 'k': case 'l': case 'm': case 'n': case 'o':
case 'p': case 'q': case 'r': case 's': case 't':
case 'u': case 'v': case 'w': case 'x': case 'y':
case 'z':
return c - '`' + 9;
default:
return '_';
}
}
| [
"ezjonas@gmail.com"
] | ezjonas@gmail.com |
8064e6c078c32b9fa379ef5171e3cab96c7c3abe | de73f2effcd2826ec9f35ebbeff581618e71b908 | /C++ Projects/Daily Coding Problem/95.cpp | 2f2c1a3e0282c2169f9ba3842b8081592b87ddf9 | [] | no_license | AaronGuo213/Other-Code | 177ffb20e1e352eff313c20611025ce193e31542 | a28dcd49141f7b3dbd3288ddb709e16acde7c016 | refs/heads/master | 2023-04-14T19:59:02.907347 | 2021-05-01T15:57:02 | 2021-05-01T15:57:02 | 208,907,584 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,563 | cpp | #include <iostream>
using namespace std;
void swap(int perm[], int a, int b) { //swaps the values of two locations in an array
int hold = perm[a];
perm[a] = perm[b];
perm[b] = hold;
}
void sort(int perm[], int begin, int end) { //sorts a part of an array from least to greatest
if(begin != end) {
int lowestPlace = begin;
for(int i = begin + 1; i <= end; i++) //finds lowest value in the part of the array
if(perm[lowestPlace] > perm[i])
lowestPlace = i;
swap(perm, lowestPlace, begin); //puts the lowest value on the first place
sort(perm, begin + 1, end); //then runs the algorithm again for the rest of the array
}
}
void nextPerm(int perm[], int size) { //returns the next permutation of a given permutation
int i, j;
for(i = size - 1; perm[i] < perm[i - 1]; i--) //finds the place to be swapped
; //(the rightmost place with a value greater than the place to the left)
i --;
int lowestSwitch = i + 1; //adjusts i
for(j = i + 1; j < size; j++) { //finds the value left of i that is closest but greater than the value at i
if(perm[j] < perm[lowestSwitch] && perm[j] > perm[i])
lowestSwitch = j;
}
swap(perm, i, lowestSwitch); //swaps the two values
sort(perm, i + 1, size - 1); //organizes the rest of the values
}
int main() {
int perm[] = {1, 3, 5, 4, 2};
int size = sizeof(perm) / sizeof(perm[0]);
nextPerm(perm, size);
for(int i = 0; i < size; i++)
cout << perm[i] << endl;
} | [
"aaronguo213@gmail.com"
] | aaronguo213@gmail.com |
5941333d2a1934c66c34a279cc3e0441069bcf67 | 6dfd7e8308884c9119d2035315da85d025d965ed | /experements/Anti_air_gun_game/airGun.h | b72c534cf74e744a845c2379b0182d87ee6c3e77 | [] | no_license | VladimirGl/spbu_homework | bda3e3bb9d997fee235014dcb2d9ab850b4fe035 | 39f27d19fef2cbe337c7c32e9977907a70b5fb13 | refs/heads/master | 2020-06-02T07:15:06.214633 | 2014-05-25T15:20:45 | 2014-05-25T15:20:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 396 | h | #ifndef TURRET_H
#define TURRET_H
#include <QGraphicsItem>
#include "airGunBase.h"
#include "airGunTurret.h"
class AirGun
{
public:
AirGun(QGraphicsScene *scene);
~AirGun();
void rotateTurret(int step);
void shoot();
protected:
AirGunBase *base;
AirGunTurret *turret;
int currentRotation;
int const maxRotate;
int const minRotate;
};
#endif // TURRET_H
| [
"glazachev.vladimir@gmail.com"
] | glazachev.vladimir@gmail.com |
96943cd37420370e859df3ac410b20afa76058dd | c746b0a00bdcc10ed881933b33a17586427749cc | /ATK/Core/OutCircularPointerFilter.h | 2851c4c113c57b2617f01f2a7f42517e7b145fb3 | [
"BSD-3-Clause"
] | permissive | sbusso/AudioTK | b62647ec34f1c33b00831e1acd0cc9e267d9e949 | 82df7f5f0965a6738050e88e84ae5feae4ed08cb | refs/heads/master | 2020-04-14T20:54:40.532133 | 2018-09-15T17:18:21 | 2018-09-15T17:18:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,700 | h | /**
* \file OutCircularPointerFilter.h
*/
#ifndef ATK_CORE_OUTCIRCULARPOINTERFILTER_H
#define ATK_CORE_OUTCIRCULARPOINTERFILTER_H
#include <array>
#include <ATK/Core/TypedBaseFilter.h>
namespace ATK
{
/// Filter allowing to output data in a circular array
template<typename DataType_>
class ATK_CORE_EXPORT OutCircularPointerFilter final : public TypedBaseFilter<DataType_>
{
public:
static const unsigned int slice_size = 1024;
static const unsigned int nb_slices = 66;
static const unsigned int out_slice_size = (nb_slices - 2) * slice_size;
protected:
/// Simplify parent calls
typedef TypedBaseFilter<DataType_> Parent;
typedef std::array<DataType_, out_slice_size> SliceBuffer;
using typename Parent::DataType;
using Parent::converted_inputs;
using Parent::input_sampling_rate;
public:
using Parent::set_input_sampling_rate;
/**
* @brief Create a circular filter for the end of a pipeline
*/
OutCircularPointerFilter();
/// Destructor
~OutCircularPointerFilter() override;
void full_setup() final;
/// Retrieves a slice of the processed data, setting process to true if it's a new one
auto get_last_slice(bool& process) -> const SliceBuffer&;
protected:
/// This implementation retrieves inputs from other filters and converts it accordingly
void process_impl(gsl::index size) const final;
/// Output array
mutable std::array<DataType, nb_slices * slice_size> array;
SliceBuffer last_slice;
/// Current offset in the array
mutable gsl::index offset;
mutable gsl::index current_slice;
gsl::index last_checked_out_buffer;
};
}
#endif
| [
"matthieu.brucher@gmail.com"
] | matthieu.brucher@gmail.com |
8038b195168c437a40fee7f2ade27e249a55d00e | 4fe8448ea1fffcf92343102a916e84d47897f065 | /XOOF/drawer.h | 960a143f5e983560edacdad5ac7bfea0e2961bc3 | [] | no_license | usnistgov/OOF1 | 1a691b7aac20ab691415b4b5832d031cf86ba50c | dfaf20efffaf6b8973da673ca7e4094282bcc801 | refs/heads/master | 2020-06-29T06:17:17.469441 | 2015-01-21T19:07:01 | 2015-01-21T19:07:01 | 29,553,217 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,755 | h | // -*- C++ -*-
// $RCSfile: drawer.h,v $
// $Revision: 1.4 $
// $Author: langer $
// $Date: 2001-02-18 02:34:49 $
/* This software was produced by NIST, an agency of the U.S. government,
* and by statute is not subject to copyright in the United States.
* Recipients of this software assume all responsibilities associated
* with its operation, modification and maintenance. However, to
* facilitate maintenance we ask that before distributing modifed
* versions of this software, you first contact the authors at
* oof_manager@ctcms.nist.gov.
*/
#ifndef DRAWER_H
#define DRAWER_H
class Drawer;
class DrawerRegistration;
class Dashboard;
#include "color.h"
#include "forms.h"
#include "grid.h"
#include "menuDef.h"
#include "vec.h"
class Dashboard;
class MouseClick;
class FormDrawer;
class Drawer {
private:
Vec<Dashboard*> dashboard;
int holdchanged; // is a redraw needed when hold is released?
int holdflag;
// double xscale, yscale; // computed when clip region changes
void new_grid(Grid*); // for replacing grid
protected:
FormDrawer *formdrawer;
Dashboard *current_dashboard;
void add_dashboard(Dashboard*);
void make_dashboard_menu();
FL_OBJECT *dashboard_menu; // copy of pointer in FormDrawer
Grid *grid;
// list of all drawers
static Vec<Drawer*> alldrawers;
virtual void draw() = 0;
virtual void drawelements() = 0;
virtual void drawedges() = 0;
virtual void drawedges(const Element*) = 0;
virtual void drawelement(const Element*) = 0;
virtual void drawnodes() = 0;
virtual void drawnode(const Node*) = 0;
virtual void draw_ps(FILE*, const Rectangle&) = 0;
virtual void drawelements_ps(FILE*, const Rectangle&) = 0;
virtual void drawedges_ps(FILE*, const Rectangle&) const = 0;
virtual void drawnodes_ps(FILE*, const Rectangle&) const = 0;
// virtual void drawedges_ps(const Element*, FILE*, const Rectangle&) const = 0;
// virtual void drawelement_ps(const Element*, FILE*, const Rectangle&) const=0;
// virtual void drawnode(const Node*) const = 0;
// colors used by all drawers, but pixel value may differ from
// colormap to colormap
virtual unsigned long wallpaper_fg() const = 0;
virtual unsigned long wallpaper_bg() const = 0;
virtual unsigned long black() const = 0;
virtual unsigned long white() const = 0;
void wallpaper(const TrueFalse&); // use wallpaper?
// routines that alert the drawer that something has changed
virtual void gridchanged() {}
virtual void elementchanged(const Element*) {}
virtual void nodechanged(const Node*) {}
int hold(); // refrain from performing updates?
void set_hold();
void release_hold();
Dashboard *set_current_dashboard(int);
virtual unsigned long rubberbandpixel() const = 0;
// called whenever the coordinates of the visible ragion change
virtual void scrollcallback(const MeshCoord&, const MeshCoord&) {}
public:
Drawer(Grid*, FormDrawer*);
virtual ~Drawer();
FL_FORM *form;
static int exists(long); // check before receiving events!
virtual int showingempties() const = 0;
friend class FormDrawer;
friend class Dashboard;
friend class OofCanvas;
};
// ----------------------------------------------------- //
class DrawerRegistration {
private:
CharString the_name;
Drawer *(*create)(Grid*, FormDrawer*);
double order_; // used to order drawers in menu
static int sorted;
static void sort();
public:
DrawerRegistration(const CharString &name,
Drawer *(*create)(Grid*, FormDrawer*),
double order);
const CharString &name() const { return the_name; }
double order() const { return order_; }
friend class FormDrawer;
friend class DrawerCmd;
};
extern Vec<DrawerRegistration*> &drawerregistry();
#endif
| [
"faical.congo@nist.gov"
] | faical.congo@nist.gov |
934b1ded1cbcf3025818c08d71d044d417c44cbe | bbc0b5a306dedd1f323199454ed4409e2d5ab941 | /Sem_4/Opp_lab/cpp/a1q10/.vscode/record/pg10.cpp.record/03-26-2019 04-20-43pm.1998.cpp | 90bc6c031107d0bdbc4d6431e9b69a23f04af1a1 | [] | no_license | SATABDA0207/College | 15a28c0f0516e14ec61b0e9f899408517f0b6282 | bf949f72e226388995f8decf52c6fbc3feb897e2 | refs/heads/master | 2023-02-20T23:06:09.859161 | 2021-01-29T21:51:23 | 2021-01-29T21:51:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,553 | cpp | #include <iostream>
#include <cstring>
#include <fstream>
#include<string.h>
#include<stdlib.h>
using namespace std;
class Blance
{
protected:
char acnt_num[21];
int blance;
int month, year, day;
int type;
public:
void get(void)
{
//acnt_num = new char[12];
cout << "Enter the Acount Number: ";
cin >> acnt_num;
cin.ignore();
cout << "Enter the Amount: ";
cin >> blance;
cin.ignore();
time_t t = time(NULL);
tm *timePtr = localtime(&t);
day = (int)timePtr->tm_mday;
month = (int)(timePtr->tm_mon) + 1;
year = (int)(timePtr->tm_year) + 1900;
}
void display(void)
{
cout << "\n===================================================\n";
cout << "\nAccount Number: " << acnt_num << endl;
cout << "Blance: " << blance << endl;
cout << "Last Update: " << day << ":" << month << ":" << year << endl;
}
char *returnactno(void) { return acnt_num; }
};
class saving : public Blance
{
public:
void timeupdate(void)
{
time_t t = time(NULL);
tm *timePtr = localtime(&t);
day = (int)timePtr->tm_mday;
month = (int)(timePtr->tm_mon) + 1;
year = (int)(timePtr->tm_year) + 1900;
}
void transation(void)
{
int type, amount;
cout << "Enter the Transaction Type:(1.withdrawal/2.deposit)\n=>";
cin >> type;
cin.ignore();
cout << "Enter the Amount: ";
cin >> amount;
cin.ignore();
time_t tt = time(NULL);
tm *ttimePtr = localtime(&tt);
day = (int)ttimePtr->tm_mday;
month = (int)(ttimePtr->tm_mon) + 1;
year = (int)(ttimePtr->tm_year) + 1900;
if (amount + 500 > blance && type == 1)
{
cout << "Transaction Faild";
}
else
{
fstream f;
f.open("transaction",ios::app|ios::in|ios::out);
if (type == 1)
{
f<<"Account no: "<<acnt_num<<"\t";
f<<"Type: withdrawl\t"<<amount<<"\t";
f<<"Date: "<<day<<":"<<month<<":"<<year<<endl;
blance -= amount;
}
else
{
f<<"Account no: "<<acnt_num<<"\t";
f<<"Type: deposit\t"<<amount<<"\t";
f<<"Date: "<<day<<":"<<month<<":"<<year<<endl;
blance += amount;
}
timeupdate();
}
}
void display(void)
{
Blance::display();
cout << "Account Type: Saving Account" << endl;
cout << "\n====================================================\n";
}
int returnblance(void) { return blance; }
};
class current : public Blance
{
public:
/*int check_validity(int amount)
{
if(amount>(blance+2000) && type==1){return 0;}
else return 1;
}*/
void timeupdate(void)
{
time_t t = time(NULL);
tm *timePtr = localtime(&t);
day = (int)timePtr->tm_mday;
month = (int)(timePtr->tm_mon) + 1;
year = (int)(timePtr->tm_year) + 1900;
}
void transation(void)
{
int type, amount;
cout << "Enter the Transaction Type:(1.withdrawal/2.deposit)\n=>";
cin >> type;
cin.ignore();
cout << "Enter the Amount: ";
cin >> amount;
cin.ignore();
if (amount > (blance + 20000) && type == 1)
{
cout << "Transaction Faild";
}
else
{
if (type == 1)
{
blance -= amount;
}
else
{
blance += amount;
}
timeupdate();
}
}
void display(void)
{
Blance::display();
cout << "Account Type: Current Account";
cout << "\n====================================================\n";
}
};
class blancelist
{
public:
current clist[10];
saving slist[10];
int count1, count2;
blancelist()
{
count1 = 0;
count2 = 0;
fstream ff;
ff.open("current", ios::binary | ios::in);
current cdum;
while (ff.read((char *)&cdum, sizeof(cdum)))
{
clist[count1] = cdum;
count1++;
}
ff.close();
ff.open("saving", ios::binary | ios::in);
saving sdum;
while (ff.read((char *)&sdum, sizeof(sdum)))
{
slist[count2] = sdum;
count2++;
}
ff.close();
}
void updateFile()
{
remove("saving");
fstream ff;
ff.open("saving", ios::binary|ios::out);
for(int i=0;i<count2;i++)
{
saving dum = slist[i];
ff.write((char*)&dum,sizeof(dum));
}
//slist[0].display();
ff.close();
ff.open("current", ios::binary|ios::out);
for(int i=0;i<count1;i++)
{
current dum = clist[i];
ff.write((char*)&dum,sizeof(dum));
}
//slist[0].display();
}
int check_id(char *c)
{
int i;
for (i = 0; i <= count1; i++)
{
if (strcmp(c, clist[i].returnactno()) == 0)
{
return i;
}
}
for (i = 0; i <= count2; i++)
{
if (strcmp(c, slist[i].returnactno()) == 0)
{
return i;
}
}
return -1;
}
int check(int n, char *c)
{
if (strcmp(c, clist[n].returnactno()) == 0)
{
return 1;
}
else
{
return 0;
}
}
void cprepaird(void)
{
current t;
t.get();
if (check_id(t.returnactno()) >= 0)
{
cout << "The Account No can't be same.";
}
else
{
clist[count1] = t;
count1++;
}
}
void sprepaird(void)
{
saving t;
t.get();
if (check_id(t.returnactno()) >= 0)
{
cout << "The Account No can't be same.";
}
else if (t.returnblance() > 500)
{
slist[count2] = t;
ofstream ff;
count2++;
}
else
{
cout << "Amount cant be less then 500" << endl;
}
}
void update(void)
{
char *acc;
acc = new char[11];
cout << "Enter The Account No\n=>";
cin >> acc;
cin.ignore();
if (check_id(acc) >= 0)
{
int n = check_id(acc);
if (check(n, acc) == 0)
{
slist[n].transation();
}
else
{
clist[n].transation();
}
}
else
{
cout << "Plase Enter A valid Account No.";
}
}
void print(void)
{
char *acc;
acc = new char[11];
cout << "Enter The Account No\n=>";
cin >> acc;
cin.ignore();
if (check_id(acc) >= 0)
{
int n = check_id(acc);
if (check(n, acc) == 0)
{
slist[n].display();
}
else
{
clist[n].display();
}
}
else
{
cout << "Plase Enter A valid Account No.";
}
}
};
int main(void)
{
blancelist b;
int opt;
while (1)
{
system("clear");
cout << b.count1 << " " << b.count2 << endl;
cout << "\n--------------------------------------------------------\n";
cout << "Chose An Option";
cout << "\n---------------------------------------------------------\n";
cout << "1.Enter New saving Account\n2.Enter New Current Account\n3.Make a Transaction\n4.Display Details of an Account\n5.EXIT\n=>";
cin >> opt;
cin.ignore();
switch (opt)
{
case 1:
b.sprepaird();
getchar();
break;
case 2:
b.cprepaird();
getchar();
break;
case 3:
b.update();
getchar();
break;
case 4:
b.print();
getchar();
break;
case 5:
b.updateFile();
return 0;
default:
//cout << "Enter A Valid Option";
b.clist[0].display();
getchar();
break;
}
}
b.updateFile();
} | [
"287mdsahil@gmail.com"
] | 287mdsahil@gmail.com |
f4016933d54b1e1f9fcde6114a2268f9234592f4 | 5a7d3db1f4dc544d47430dcecf9de5ae2990fe88 | /.emacs.d/undohist/!home!sirogami!programming!compe!algorithm!factorial!sample1.cc | 6f855d1d164d68359d1bbefc3b50d7e325ed0c51 | [] | no_license | sirogamichandayo/emacs_sirogami | d990da25e5b83b23799070b4d1b5c540b12023b9 | c646cfd1c4a69cef2762432ba4492e32c2c025c8 | refs/heads/master | 2023-01-24T12:38:56.308764 | 2020-12-07T10:42:35 | 2020-12-07T10:42:35 | 245,687,325 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,325 | cc |
((digest . "40f5f19b91e17ac0ac117f8824b8832d") (undo-list nil (475 . 476) nil ("4" . -475) ((marker . 476) . -1) ((marker . 475) . -1) ((marker . 475) . -1) 476 (t 24232 8462 878032 884000) nil (475 . 476) nil ("8" . -475) ((marker . 476) . -1) 476 nil ("/" . -1) ((marker . 476) . -1) ((marker . 1) . -1) ((marker) . -1) ((marker) . -1) ((marker . 1) . -1) ((marker) . -1) ((marker) . -1) 2 nil (1 . 2) (t 24232 8409 522698 846000) nil (383 . 384) nil (374 . 383) nil (366 . 373) nil ("=" . -366) ((marker . 476) . -1) ((marker . 366) . -1) ((marker . 366) . -1) 367 nil (363 . 367) nil (362 . 364) ("(" . -362) (362 . 363) nil (359 . 362) nil (356 . 359) (t 24232 8377 807095 17000) nil ("
" . 492) (" " . -492) ((marker . 476) . -1) ((marker . 520) . -1) ((marker . 520) . -1) ((marker . 520) . -1) 493 nil (474 . 478) nil (486 . 487) nil (482 . 486) nil (480 . 482) nil (476 . 480) nil (474 . 476) nil (473 . 474) nil (471 . 473) nil (466 . 471) nil (460 . 461) (" " . 460) (465 . 466) (460 . 461) (" " . 460) ((marker . 476) . -1) (464 . 465) nil (461 . 464) nil (459 . 461) nil (455 . 456) nil (450 . 455) nil (449 . 450) nil (447 . 448) nil ("0" . -447) ((marker . 476) . -1) 448 nil (440 . 448) nil (439 . 441) ("(" . -439) (439 . 440) nil (436 . 439) nil (433 . 436) nil (422 . 423) nil (427 . 428) nil (422 . 427) nil ("
" . 423) (" " . -423) ((marker . 476) . -4) 427 nil (422 . 427) nil (414 . 421) nil ("=" . -414) ((marker . 476) . -1) (" " . -415) ((marker . 476) . -1) ("i" . -416) ((marker . 476) . -1) 417 nil (412 . 417) nil (411 . 412) nil (410 . 412) ("(" . -410) (410 . 411) nil (407 . 410) nil (404 . 407) (403 . 407) nil (400 . 402) (" " . 400) ((marker . 476) . -3) (403 . 405) ("{" . -403) (403 . 404) nil (399 . 403) nil (394 . 398) nil (393 . 394) nil (390 . 393) nil (389 . 390) nil (387 . 389) nil (380 . 381) nil ("n" . -380) ((marker . 476) . -1) 381 nil (386 . 387) nil (385 . 386) nil (377 . 385) nil (376 . 378) ("(" . -376) (376 . 377) nil (372 . 376) nil (369 . 372) nil (368 . 369) nil (366 . 367) nil (365 . 367) ("{" . -365) (365 . 366) nil (359 . 365) nil (357 . 359) (356 . 359) nil (354 . 355) (" " . 354) ((marker . 476) . -2) (356 . 358) ("{" . -356) (356 . 357) nil (353 . 356) nil (349 . 352) nil (298 . 299) nil ("n" . -298) ((marker . 476) . -1) 299 nil (308 . 309) nil ("n" . -308) ((marker . 476) . -1) 309 nil (346 . 347) nil ("n" . -346) ((marker . 476) . -1) 347 nil (348 . 349) nil (347 . 348) nil (344 . 347) nil (" " . -344) ((marker . 476) . -1) ((marker . 344) . -1) ((marker . 344) . -1) 345 nil (344 . 345) nil (343 . 344) nil (340 . 343) nil (339 . 340) nil (334 . 339) nil ("1" . -334) ((marker . 476) . -1) (" " . -335) ((marker . 476) . -1) ("=" . -336) ((marker . 476) . -1) (" " . -337) ((marker . 476) . -1) 338 nil (336 . 338) nil (331 . 336) nil (330 . 332) ("(" . -330) (330 . 331) nil (326 . 330) nil (324 . 326) (" " . 324) ((marker . 476) . -1) 325 nil (323 . 325) nil (322 . 323) nil (320 . 321) nil (319 . 321) ("{" . -319) (319 . 320) nil (313 . 319) (t 24232 8291 840170 105000) nil (311 . 313) nil (" std::cout << a[105] << std::endl;
" . 312) ((marker . 520) . -21) ((marker . 520) . -14) ((marker . 520) . -14) ((marker . 520) . -14) ((marker . 520) . -14) ((marker . 520) . -14) ((marker . 520) . -14) ((marker . 520) . -14) ((marker . 520) . -19) ((marker . 520) . -19) ((marker . 520) . -19) nil (" }
" . 312) nil (" a[n] = accumulate(tmp.begin(), tmp.end(), 0ll);
" . 312) ((marker . 520) . -2) ((marker . 520) . -9) ((marker . 520) . -9) ((marker . 520) . -9) nil (" vector<ll> tmp = factorial(n);
" . 312) nil (" {
" . 312) nil (" for (ll n = 1; n <= 105; ++n)
" . 312) ((marker . 520) . -19) ((marker . 520) . -14) nil ("
" . 312) (" vector<ll> a(106);" . -312) ((marker . 476) . -19) ((marker . 520) . -1) ((marker . 520) . -13) ((marker . 520) . -14) ((marker . 520) . -16) ((marker . 520) . -17) ((marker . 520) . -19) ((marker . 520) . -19) 331 (t 24232 8182 353542 415000) nil (468 . 471) (467 . 469) ("[" . -467) (466 . 468) nil ("*" . -466) ((marker . 476) . -1) ((marker . 520) . -1) ((marker . 520) . -1) ((marker . 520) . -1) ((marker . 520) . -1) ((marker . 520) . -1) 467 nil ("max_" . -467) ((marker . 476) . -4) ((marker . 520) . -4) ((marker . 520) . -4) ((marker . 520) . -4) ((marker . 520) . -4) ((marker . 520) . -4) 471 nil ("element(" . -471) ((marker . 476) . -8) ((marker . 520) . -8) ((marker . 520) . -8) ((marker . 520) . -8) ((marker . 520) . -8) ((marker . 520) . -8) 479 nil ("a." . -479) ((marker . 476) . -2) ((marker . 520) . -2) ((marker . 520) . -2) ((marker . 520) . -2) ((marker . 520) . -2) ((marker . 520) . -2) 481 nil ("begin(), " . -481) ((marker . 476) . -9) ((marker . 520) . -9) ((marker . 520) . -9) ((marker . 520) . -9) ((marker . 520) . -9) ((marker . 520) . -9) 490 nil ("a." . -490) ((marker . 476) . -2) ((marker . 520) . -2) ((marker . 520) . -2) ((marker . 520) . -2) ((marker . 520) . -2) ((marker . 520) . -2) 492 nil ("end())" . -492) ((marker . 476) . -6) ((marker . 520) . -5) ((marker . 520) . -5) ((marker . 520) . -5) ((marker . 520) . -5) ((marker . 520) . -5) ((marker*) . 1) ((marker) . -6) 498 (t 24232 8147 449980 739000) nil (224 . 227) nil ("!" . -221) ((marker . 476) . -1) ((marker . 221) . -1) 222 (t 24232 8052 475175 921000) nil ("," . -495) ((marker . 476) . -1) ((marker . 520) . -1) ((marker . 520) . -1) ((marker . 520) . -1) (" " . -496) ((marker . 476) . -1) ((marker . 520) . -1) ((marker . 520) . -1) ((marker . 520) . -1) ("0" . -497) ((marker . 476) . -1) ((marker . 520) . -1) ((marker . 520) . -1) ((marker . 520) . -1) 498 nil ("l" . -498) ((marker . 476) . -1) ((marker . 520) . -1) ((marker . 520) . -1) ((marker . 520) . -1) ("l" . -499) ((marker . 476) . -1) ((marker . 520) . -1) ((marker . 520) . -1) ((marker . 520) . -1) 500 (t 24232 8031 15446 523000) nil (496 . 500) nil (495 . 496) nil (")" . -494) (494 . 495) (")" . -494) (494 . 495) (493 . 495) ("(" . -493) (493 . 494) nil (490 . 493) nil ("d" . -490) ((marker . 476) . -1) ("n" . -491) ((marker . 476) . -1) 492 nil (487 . 492) nil (486 . 487) nil (485 . 486) (")" . -485) (485 . 486) (484 . 486) ("(" . -484) (484 . 485) nil (480 . 484) nil (478 . 480) nil ("[" . -478) ((marker . 476) . -1) ("1" . -479) ((marker . 476) . -1) ("0" . -480) ((marker . 476) . -1) ("5" . -481) ((marker . 476) . -1) ("]" . -482) ((marker . 476) . -1) ((marker*) . 1) ((marker) . -1) 483 nil (")" . -477) ((marker . 476) . -1) ((marker*) . 1) ((marker) . -1) 478 nil (476 . 478) ("(" . -476) (476 . 477) nil (465 . 476) nil (464 . 465) nil ("max" . -464) ((marker . 476) . -3) ((marker . 520) . -3) ((marker . 520) . -3) 467 nil (466 . 467) nil (464 . 466) (t 24232 8005 163772 788000) nil (176 . 178) nil (175 . 176) (t 24232 7979 492097 104000) nil (340 . 341) nil ("0" . -340) ((marker . 476) . -1) 341 (t 24232 7962 536311 509000) nil (249 . 250) nil ("x" . -249) 250 nil (227 . 228) nil ("x" . -227) ((marker . 476) . -1) 228 nil (170 . 171) nil ("x" . -170) ((marker . 476) . -1) ((marker . 170) . -1) 171 (t 24232 7931 688696 872000) nil (191 . 192) nil ("0" . -191) ((marker . 476) . -1) 192 (t 24232 7919 588846 873000) nil (" (ll i = 0; i < n; ++i) cin >> c[i];
" . 306) (" vector<ll> c(n); for" . -306) ((marker . 476) . -21) 327 (t 24232 7885 249272 707000) nil (525 . 526) nil (521 . 524) (520 . 522) ("[" . -520) (519 . 521) nil (531 . 532) nil (527 . 531) nil (525 . 527) nil (521 . 525) nil (519 . 521) nil (518 . 519) nil (516 . 518) nil (511 . 516) nil (505 . 506) (" " . 505) (510 . 511) (505 . 506) (" " . 505) ((marker . 476) . -1) (509 . 510) nil (506 . 509) (t 24232 7882 165310 961000) nil (505 . 506) (t 24232 7879 581343 14000) nil (496 . 499) nil ("o" . -496) ((marker . 476) . -1) ("l" . -497) ((marker . 476) . -1) ("l" . -498) ((marker . 476) . -1) 499 nil (496 . 499) nil (495 . 496) nil (494 . 495) nil (")" . -493) (493 . 494) (")" . -493) (493 . 494) (492 . 494) ("(" . -492) (492 . 493) nil (485 . 492) nil ("mp" . -485) ((marker . 476) . -2) 487 nil (484 . 487) nil (483 . 484) nil (")" . -482) (482 . 483) (")" . -482) (482 . 483) (481 . 483) ("(" . -481) (481 . 482) nil (472 . 481) nil (471 . 473) ("(" . -471) (471 . 472) nil (465 . 471) nil ("l" . -465) ((marker . 476) . -1) ("u" . -466) ((marker . 476) . -1) 467 nil (461 . 467) nil undo-tree-canary))
| [
"sirogamiemacs@gmail.com"
] | sirogamiemacs@gmail.com |
8a74d044a48e67c56be40455eed57dbb2f63e881 | 5a6398e0b197dc76eb9d79e8c9a70940c826b00e | /src/include/izenelib/include/sf1common/ScdWriter.h | 0de697eace5f02017d21f7844b51a75ca7385838 | [
"Apache-2.0",
"PostgreSQL"
] | permissive | RMoraffah/hippo-postgresql | 38b07cd802e179c3fce00097f49c843b238c3e91 | 002702bab3a820bbc8cf99e6fcf3bb1eface96c1 | refs/heads/master | 2021-01-12T00:48:53.735686 | 2016-12-02T01:01:15 | 2016-12-02T01:13:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,307 | h | #ifndef SF1COMMON_SCDWRITER_H_
#define SF1COMMON_SCDWRITER_H_
#include "ScdParser.h"
#include "Document.h"
#include <boost/function.hpp>
#include <boost/variant.hpp>
namespace izenelib
{
class DocumentOutputVisitor : public boost::static_visitor<void>
{
public:
DocumentOutputVisitor():os_(NULL) {}
DocumentOutputVisitor(std::ostream* os):os_(os) {}
void SetOutStream(std::ostream* os) {os_ = os; }
template <typename T>
void operator()(const T& value) const
{
*os_ << value;
}
void operator()(const izenelib::util::UString& value) const
{
std::string str;
value.convertString(str, izenelib::util::UString::UTF_8);
*os_ << str;
}
void operator()(const std::vector<izenelib::util::UString>& value) const
{
for(uint32_t i=0;i<value.size();i++)
{
std::string str;
value[i].convertString(str, izenelib::util::UString::UTF_8);
if(i>0) *os_ <<",";
*os_ << str;
}
}
void operator()(const std::vector<uint32_t>& value) const
{
for(uint32_t i=0;i<value.size();i++)
{
if(i>0) *os_ <<",";
*os_ << value[i];
}
}
private:
std::ostream* os_;
};
///@brief only write UString properties in Document to SCD file.
class ScdWriter
{
typedef boost::function<bool
(const std::string&) > PropertyNameFilterType;
public:
ScdWriter(const std::string& dir, SCD_TYPE scd_type);
~ScdWriter();
void SetFileName(const std::string& fn)
{
filename_ = fn;
}
std::string getFileName()
{
return filename_;
}
static std::string GenSCDFileName(SCD_TYPE scd_type);
bool Append(const Document& doc);
bool Append(const SCDDoc& doc);
bool Append(const std::string& str);//use it after DocToString
void Close();
void SetPropertyNameFilter(const PropertyNameFilterType& filter)
{
pname_filter_ = filter;
}
static void DocToString(const Document& doc, std::string& str);
private:
void Open_();
private:
std::string dir_;
std::string filename_;
SCD_TYPE scd_type_;
std::ofstream ofs_;
DocumentOutputVisitor output_visitor_;
PropertyNameFilterType pname_filter_;
};
}
#endif
| [
"jiayu198910@gmail.com"
] | jiayu198910@gmail.com |
731f7ea0008c4b77abfcf432630424673e9e6dfa | 814fd0bea5bc063a4e34ebdd0a5597c9ff67532b | /chromecast/renderer/media/cma_media_renderer_factory.cc | 2a3814939d0830128afa088d068576a4fc9039ed | [
"BSD-3-Clause"
] | permissive | rzr/chromium-crosswalk | 1b22208ff556d69c009ad292bc17dca3fe15c493 | d391344809adf7b4f39764ac0e15c378169b805f | refs/heads/master | 2021-01-21T09:11:07.316526 | 2015-02-16T11:52:21 | 2015-02-16T11:52:21 | 38,887,985 | 0 | 0 | NOASSERTION | 2019-08-07T21:59:20 | 2015-07-10T15:35:50 | C++ | UTF-8 | C++ | false | false | 1,307 | 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/renderer/media/cma_media_renderer_factory.h"
#include "base/command_line.h"
#include "chromecast/media/cma/filters/cma_renderer.h"
#include "chromecast/renderer/media/media_pipeline_proxy.h"
#include "content/public/renderer/render_thread.h"
namespace chromecast {
namespace media {
CmaMediaRendererFactory::CmaMediaRendererFactory(int render_frame_id)
: render_frame_id_(render_frame_id) {
}
CmaMediaRendererFactory::~CmaMediaRendererFactory() {
}
scoped_ptr< ::media::Renderer> CmaMediaRendererFactory::CreateRenderer(
const scoped_refptr<base::SingleThreadTaskRunner>& media_task_runner,
::media::AudioRendererSink* audio_renderer_sink) {
// TODO(erickung): crbug.com/443956. Need to provide right LoadType.
LoadType cma_load_type = kLoadTypeMediaSource;
scoped_ptr<MediaPipeline> cma_media_pipeline(
new MediaPipelineProxy(
render_frame_id_,
content::RenderThread::Get()->GetIOMessageLoopProxy(),
cma_load_type));
return scoped_ptr< ::media::Renderer>(
new CmaRenderer(cma_media_pipeline.Pass()));
}
} // namespace media
} // namespace chromecast | [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
d8d7f223dad3d7b70133c3231b1c291b8ac86a0b | 00c96f48bc1662999faec7b51cea4a86a71c0cfd | /cluster/qedis_proxy/ProxyConfig.cc | bd136f0dc95dfae97dae9fc3ae439bfc3e6adc3a | [
"MIT"
] | permissive | loveyacper/Qedis | 3dd34a0247f60e3975ee1fbae8f865a1409480e4 | a68b8261737b860da5e906563be151b91af1835a | refs/heads/master | 2023-08-11T02:06:36.694605 | 2023-05-04T03:50:03 | 2023-05-04T03:50:03 | 23,990,558 | 192 | 52 | MIT | 2021-04-02T06:10:56 | 2014-09-13T09:25:22 | C++ | UTF-8 | C++ | false | false | 962 | cc | #include <vector>
#include <iostream>
#include "ProxyConfig.h"
#include "ConfigParser.h"
namespace qedis
{
static void EraseQuotes(std::string& str)
{
// convert "hello" to hello
if (str.size() < 2)
return;
if (str[0] == '"' && str[str.size() - 1] == '"')
{
str.pop_back();
str.erase(str.begin());
}
}
const std::string ProxyConfig::kProxyPrefixPath = "/proxy/qedis_proxy_";
const std::string ProxyConfig::kQedisSetsPath = "/servers";
ProxyConfig g_config;
ProxyConfig::ProxyConfig() :
bindAddr("127.0.0.1:6379"),
logDir("log_proxy"),
clusters({"127.0.0.1:2181"})
{
}
bool LoadProxyConfig(const char* cfgFile, ProxyConfig& cfg)
{
ConfigParser parser;
if (!parser.Load(cfgFile))
return false;
cfg.bindAddr = parser.GetData<std::string>("bind", cfg.bindAddr);
cfg.logDir = parser.GetData<std::string>("logdir", cfg.logDir);
return true;
}
} // end namespace qedis
| [
"bertyoung666@gmail.com"
] | bertyoung666@gmail.com |
628d818b7575a81e9873ed36275a50c8f0f1fbf0 | 009e98ac743a1fc66a765bfd8dd2240856299a47 | /src/rpcblockchain.cpp | a72e1ce3f2e1c6a8aab356d3a3a067e983a76a23 | [
"MIT"
] | permissive | FWCC/Source | 0b9baee522917892369e2d655dcc5d562f5a4376 | 1c5b895fd75a2869e401900b09fa99b6a6101fdd | refs/heads/master | 2021-01-02T22:32:27.073403 | 2014-06-12T16:47:43 | 2014-06-12T16:47:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,269 | 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 "main.h"
#include "bitcoinrpc.h"
using namespace json_spirit;
using namespace std;
extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry);
extern enum Checkpoints::CPMode CheckpointsMode;
double GetDifficulty(const CBlockIndex* blockindex)
{
// Floating point number that is a multiple of the minimum difficulty,
// minimum difficulty = 1.0.
if (blockindex == NULL)
{
if (pindexBest == NULL)
return 1.0;
else
blockindex = GetLastBlockIndex(pindexBest, false);
}
int nShift = (blockindex->nBits >> 24) & 0xff;
double dDiff =
(double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);
while (nShift < 29)
{
dDiff *= 256.0;
nShift++;
}
while (nShift > 29)
{
dDiff /= 256.0;
nShift--;
}
return dDiff;
}
double GetPoWMHashPS()
{
if (pindexBest->nHeight >= LAST_POW_BLOCK)
return 0;
int nPoWInterval = 72;
int64_t nTargetSpacingWorkMin = 30, nTargetSpacingWork = 30;
CBlockIndex* pindex = pindexGenesisBlock;
CBlockIndex* pindexPrevWork = pindexGenesisBlock;
while (pindex)
{
if (pindex->IsProofOfWork())
{
int64_t nActualSpacingWork = pindex->GetBlockTime() - pindexPrevWork->GetBlockTime();
nTargetSpacingWork = ((nPoWInterval - 1) * nTargetSpacingWork + nActualSpacingWork + nActualSpacingWork) / (nPoWInterval + 1);
nTargetSpacingWork = max(nTargetSpacingWork, nTargetSpacingWorkMin);
pindexPrevWork = pindex;
}
pindex = pindex->pnext;
}
return GetDifficulty() * 4294.967296 / nTargetSpacingWork;
}
double GetPoSKernelPS()
{
int nPoSInterval = 72;
double dStakeKernelsTriedAvg = 0;
int nStakesHandled = 0, nStakesTime = 0;
CBlockIndex* pindex = pindexBest;;
CBlockIndex* pindexPrevStake = NULL;
while (pindex && nStakesHandled < nPoSInterval)
{
if (pindex->IsProofOfStake())
{
dStakeKernelsTriedAvg += GetDifficulty(pindex) * 4294967296.0;
nStakesTime += pindexPrevStake ? (pindexPrevStake->nTime - pindex->nTime) : 0;
pindexPrevStake = pindex;
nStakesHandled++;
}
pindex = pindex->pprev;
}
return nStakesTime ? dStakeKernelsTriedAvg / nStakesTime : 0;
}
Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool fPrintTransactionDetail)
{
Object result;
result.push_back(Pair("hash", block.GetHash().GetHex()));
CMerkleTx txGen(block.vtx[0]);
txGen.SetMerkleBranch(&block);
result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain()));
result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
result.push_back(Pair("height", blockindex->nHeight));
result.push_back(Pair("version", block.nVersion));
result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
result.push_back(Pair("mint", ValueFromAmount(blockindex->nMint)));
result.push_back(Pair("time", (boost::int64_t)block.GetBlockTime()));
result.push_back(Pair("nonce", (boost::uint64_t)block.nNonce));
result.push_back(Pair("bits", HexBits(block.nBits)));
result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
result.push_back(Pair("blocktrust", leftTrim(blockindex->GetBlockTrust().GetHex(), '0')));
result.push_back(Pair("chaintrust", leftTrim(blockindex->nChainTrust.GetHex(), '0')));
if (blockindex->pprev)
result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
if (blockindex->pnext)
result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex()));
result.push_back(Pair("flags", strprintf("%s%s", blockindex->IsProofOfStake()? "proof-of-stake" : "proof-of-work", blockindex->GeneratedStakeModifier()? " stake-modifier": "")));
result.push_back(Pair("proofhash", blockindex->IsProofOfStake()? blockindex->hashProofOfStake.GetHex() : blockindex->GetBlockHash().GetHex()));
result.push_back(Pair("entropybit", (int)blockindex->GetStakeEntropyBit()));
result.push_back(Pair("modifier", strprintf("%016"PRIx64, blockindex->nStakeModifier)));
result.push_back(Pair("modifierchecksum", strprintf("%08x", blockindex->nStakeModifierChecksum)));
Array txinfo;
BOOST_FOREACH (const CTransaction& tx, block.vtx)
{
if (fPrintTransactionDetail)
{
Object entry;
entry.push_back(Pair("txid", tx.GetHash().GetHex()));
TxToJSON(tx, 0, entry);
txinfo.push_back(entry);
}
else
txinfo.push_back(tx.GetHash().GetHex());
}
result.push_back(Pair("tx", txinfo));
if (block.IsProofOfStake())
result.push_back(Pair("signature", HexStr(block.vchBlockSig.begin(), block.vchBlockSig.end())));
return result;
}
Value getbestblockhash(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getbestblockhash\n"
"Returns the hash of the best block in the longest block chain.");
return hashBestChain.GetHex();
}
Value getblockcount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getblockcount\n"
"Returns the number of blocks in the longest block chain.");
return nBestHeight;
}
Value getdifficulty(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getdifficulty\n"
"Returns the difficulty as a multiple of the minimum difficulty.");
Object obj;
obj.push_back(Pair("proof-of-work", GetDifficulty()));
obj.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
obj.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
return obj;
}
Value settxfee(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1 || AmountFromValue(params[0]) < MIN_TX_FEE)
throw runtime_error(
"settxfee <amount>\n"
"<amount> is a real and is rounded to the nearest 0.01");
nTransactionFee = AmountFromValue(params[0]);
nTransactionFee = (nTransactionFee / CENT) * CENT; // round to cent
return true;
}
Value getrawmempool(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getrawmempool\n"
"Returns all transaction ids in memory pool.");
vector<uint256> vtxid;
mempool.queryHashes(vtxid);
Array a;
BOOST_FOREACH(const uint256& hash, vtxid)
a.push_back(hash.ToString());
return a;
}
Value getblockhash(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getblockhash <index>\n"
"Returns hash of block in best-block-chain at <index>.");
int nHeight = params[0].get_int();
if (nHeight < 0 || nHeight > nBestHeight)
throw runtime_error("Block number out of range.");
CBlockIndex* pblockindex = FindBlockByHeight(nHeight);
return pblockindex->phashBlock->GetHex();
}
Value getblock(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getblock <hash> [txinfo]\n"
"txinfo optional to print more detailed tx info\n"
"Returns details of a block with given block-hash.");
std::string strHash = params[0].get_str();
uint256 hash(strHash);
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hash];
block.ReadFromDisk(pblockindex, true);
return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
}
Value getblockbynumber(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getblock <number> [txinfo]\n"
"txinfo optional to print more detailed tx info\n"
"Returns details of a block with given block-number.");
int nHeight = params[0].get_int();
if (nHeight < 0 || nHeight > nBestHeight)
throw runtime_error("Block number out of range.");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hashBestChain];
while (pblockindex->nHeight > nHeight)
pblockindex = pblockindex->pprev;
uint256 hash = *pblockindex->phashBlock;
pblockindex = mapBlockIndex[hash];
block.ReadFromDisk(pblockindex, true);
return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
}
// FIFAWCCoin: get information of sync-checkpoint
Value getcheckpoint(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getcheckpoint\n"
"Show info of synchronized checkpoint.\n");
Object result;
CBlockIndex* pindexCheckpoint;
result.push_back(Pair("synccheckpoint", Checkpoints::hashSyncCheckpoint.ToString().c_str()));
pindexCheckpoint = mapBlockIndex[Checkpoints::hashSyncCheckpoint];
result.push_back(Pair("height", pindexCheckpoint->nHeight));
result.push_back(Pair("timestamp", DateTimeStrFormat(pindexCheckpoint->GetBlockTime()).c_str()));
// Check that the block satisfies synchronized checkpoint
if (CheckpointsMode == Checkpoints::STRICT)
result.push_back(Pair("policy", "strict"));
if (CheckpointsMode == Checkpoints::ADVISORY)
result.push_back(Pair("policy", "advisory"));
if (CheckpointsMode == Checkpoints::PERMISSIVE)
result.push_back(Pair("policy", "permissive"));
if (mapArgs.count("-checkpointkey"))
result.push_back(Pair("checkpointmaster", true));
return result;
}
| [
"dev@fifawccoin.org"
] | dev@fifawccoin.org |
23b3bd7b68078ddc385226b98e68fdd688d88991 | e0d99802bd51b5b452ced555e6a9efbfa0e656dd | /longest_increasing_subsequence/main.cpp | a9b2b211e38c78e95573476098c81dfd94c50ba0 | [] | no_license | JohnnyJ5/Algorithms | 263926bc190d2e008bdb76fd8b1ee4928aba06f4 | 378305142c7665b33c70db5f083580f6f6ac7bf6 | refs/heads/master | 2020-12-25T14:48:26.282240 | 2016-07-31T02:17:26 | 2016-07-31T02:17:26 | 62,096,245 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 105 | cpp |
#include <vector>
#include <iostream>
#include <algorithm>
int main()
{
return 0;
} | [
"michaelcoffey5@gmail.com"
] | michaelcoffey5@gmail.com |
47a2d04d1309124858cd44429aa663742eb2c4b2 | 03d3636f13b8ed7c83a9d2e4094464d24450c466 | /mediapipe_api/gpu/egl_surface_holder.h | 4fb1e613bb5ef28f97b2bed4789079422094d9b8 | [
"MIT"
] | permissive | canaxx/Akihabara | 6e7082524df1504f80a3cc2e645eb7582c0162ee | 956662f742f9c0c557b90205caddc737836231c2 | refs/heads/master | 2023-09-01T22:18:34.002536 | 2021-11-02T00:20:37 | 2021-11-02T00:20:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,220 | h | // Copyright (c) 2021 homuler
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
#ifndef C_MEDIAPIPE_API_GPU_EGL_SURFACE_HOLDER_H_
#define C_MEDIAPIPE_API_GPU_EGL_SURFACE_HOLDER_H_
#include <memory>
#include "mediapipe/gpu/egl_surface_holder.h"
#include "mediapipe/gpu/gl_context.h"
#include "mediapipe_api/common.h"
#include "mediapipe_api/framework/packet.h"
extern "C" {
typedef std::unique_ptr<mediapipe::EglSurfaceHolder> EglSurfaceHolderUniquePtr;
typedef absl::StatusOr<EglSurfaceHolderUniquePtr> StatusOrEglSurfaceHolderUniquePtr;
MP_CAPI(MpReturnCode) mp_EglSurfaceHolderUniquePtr__(EglSurfaceHolderUniquePtr** egl_surface_holder_out);
MP_CAPI(void) mp_EglSurfaceHolderUniquePtr__delete(EglSurfaceHolderUniquePtr* egl_surface_holder);
MP_CAPI(mediapipe::EglSurfaceHolder*) mp_EglSurfaceHolderUniquePtr__get(EglSurfaceHolderUniquePtr* egl_surface_holder);
MP_CAPI(mediapipe::EglSurfaceHolder*) mp_EglSurfaceHolderUniquePtr__release(EglSurfaceHolderUniquePtr* egl_surface_holder);
MP_CAPI(void) mp_EglSurfaceHolder__SetFlipY__b(mediapipe::EglSurfaceHolder* egl_surface_holder, bool flip_y);
MP_CAPI(bool) mp_EglSurfaceHolder__flip_y(mediapipe::EglSurfaceHolder* egl_surface_holder);
MP_CAPI(MpReturnCode) mp_EglSurfaceHolder__SetSurface__P_Pgc(mediapipe::EglSurfaceHolder* egl_surface_holder,
EGLSurface surface,
mediapipe::GlContext* gl_context,
absl::Status** status_out);
MP_CAPI(MpReturnCode) mp__MakeEglSurfaceHolderUniquePtrPacket__Reshup(EglSurfaceHolderUniquePtr* egl_surface_holder,
mediapipe::Packet** packet_out);
MP_CAPI(MpReturnCode) mp_Packet__GetEglSurfaceHolderUniquePtr(mediapipe::Packet* packet, const EglSurfaceHolderUniquePtr** value_out);
MP_CAPI(MpReturnCode) mp_Packet__ValidateAsEglSurfaceHolderUniquePtr(mediapipe::Packet* packet, absl::Status** status_out);
} // extern "C"
#endif // C_MEDIAPIPE_API_GPU_EGL_SURFACE_HOLDER_H_
| [
"noreply@github.com"
] | noreply@github.com |
ed6d10aec8c8a6d48666e40f94c6fcb1e59fbf58 | 0f1877a2327b6e21c9942837400182ef8ba588ae | /src/src/RightText.cpp | 21929dc19388fee512c94fc62af6e4153b514618 | [] | no_license | WesternGamer/RDR2-Duels | 8a9104b9891c793d7b242aef820403597221d885 | c582ded244de9f57814f3d14596c47331abcdd26 | refs/heads/master | 2023-05-09T07:42:53.121855 | 2021-05-14T15:31:47 | 2021-05-14T15:31:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,155 | cpp | #include "Main.h"
char rightText[200];
int rightTextDuration;
void clearRightText()
{
for (int i = 0; i < 200; i++)
{
rightText[i] = 0;
}
}
void setRightText(const char* text, int duration)
{
int i = 0;
while (i < 200 && text[i])
{
rightText[i] = text[i];
i++;
}
rightTextDuration = duration;
}
DurationsArgs rightTextArgs1;
UITextArgs rightTextArgs2;
const char* createVarString(const char* text)
{
const char* result;
result = UI::_CREATE_VAR_STRING(10, "LITERAL_STRING", text);
int attempts = 500;
while (strcmp(text, result) != 0 && attempts > 0)
{
log(attempts);
attempts--;
result = UI::_CREATE_VAR_STRING(10, "LITERAL_STRING", text);
}
log(attempts);
log(result);
return result;
}
void printRightText()
{
if (rightText[0])
{
rightTextArgs1.duration = rightTextDuration;
rightTextArgs2.unk = 0;
rightTextArgs2.text = UI::_CREATE_VAR_STRING(10, "LITERAL_STRING", rightText);
UIUNK::_0xB2920B9760F0F36B((Any*)&rightTextArgs1, (Any*)&rightTextArgs2, 1);
clearRightText();
}
} | [
"idoshtivi@gmail.com"
] | idoshtivi@gmail.com |
9b1acce4a04c0c51b3dad616cb165c8ad35016ca | 079723c57e46f1bef9335935803401fc66c41220 | /src/portionadder.cpp | 87c76fc4ae75a4378a73f83f99ce37643dec95d6 | [] | no_license | codedraughtsman/OpenExercise-Nutrition | 4b537d639de9bd95c4664a986969a50965eb4c2e | dc2b1a677d315bec32e4288a46c5606045c01b14 | refs/heads/master | 2021-08-20T04:44:01.390944 | 2020-04-11T23:38:45 | 2020-04-11T23:38:45 | 160,886,664 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,586 | cpp | #include "portionadder.h"
#include "ui_portionadder.h"
#include "storagemanager.h"
#include <QDebug>
#include <QInputDialog>
#include <QSortFilterProxyModel>
#include <QSqlQueryModel>
PortionAdder::PortionAdder( QWidget *parent )
: QDialog( parent ), ui( new Ui::PortionAdder ) {
ui->setupUi( this );
ui->dateTimeEdit->setDateTime( QDateTime::currentDateTime() );
QSqlQueryModel *model = new QSqlQueryModel;
model->setQuery(
"select "
"foodData.ShortFoodName, "
"count( portions.foodName) numOfEntries, "
"foodData.Energy kj, "
"foodData.Fat, "
"foodData.Protein, "
"foodData.Carbohydrateavailable "
"from foodData "
"left join portions on foodData.ShortFoodName = portions.foodName "
"group by foodData.ShortFoodName" );
model->setHeaderData( 0, Qt::Horizontal, tr( "Name" ) );
// connect(StorageManager::instance(),
// &StorageManager::dataChanged,model,&QSqlQueryModel::);
QSortFilterProxyModel *proxyModel = new QSortFilterProxyModel( this );
proxyModel->setSourceModel( model );
proxyModel->setFilterKeyColumn( 0 );
proxyModel->setFilterCaseSensitivity(
Qt::CaseSensitivity::CaseInsensitive );
ui->tableView->setModel( proxyModel );
ui->tableView->setSortingEnabled( true );
ui->tableView->sortByColumn( 1, Qt::DescendingOrder );
connect( ui->filterLineEdit, &QLineEdit::textChanged, proxyModel,
&QSortFilterProxyModel::setFilterWildcard );
connect( ui->closeButton, &QPushButton::released, this, &QDialog::close );
ui->tableView->setSelectionBehavior( QAbstractItemView::SelectRows );
ui->tableView->verticalHeader()->hide();
ui->tableView->horizontalHeader()->setSectionResizeMode(
0, QHeaderView::ResizeToContents );
connect( ui->tableView, &QTableView::doubleClicked, this,
&PortionAdder::onTableClicked );
}
void PortionAdder::onTableClicked( const QModelIndex &index ) {
qDebug() << "double clicked:" << index;
if ( index.isValid() ) {
const QAbstractItemModel *model = index.model();
QVariant firstCell =
model->data( model->index( index.row(), 0 ), Qt::DisplayRole );
QString foodName = firstCell.toString();
qDebug() << "food name is " << foodName;
bool ok;
int grams = QInputDialog::getInt( this, tr( "quantity of food" ),
"grams of " + foodName, 100, 0,
2147483647, 1, &ok );
if ( ok ) {
StorageManager::instance().addPortion(
foodName, grams, ui->dateTimeEdit->dateTime() );
ui->statusMessageLabel->setText( QString( "added %1 grams of %2" )
.arg( grams )
.arg( foodName ) );
}
}
}
PortionAdder::~PortionAdder() { delete ui; }
| [
"40680543+codedraughtsman@users.noreply.github.com"
] | 40680543+codedraughtsman@users.noreply.github.com |
baf1799756786896524929f03689567d2840d2c0 | c9ba0c885affbef7b54aff9c813344c319e23845 | /18.cpp | 251c224d43f9d067d72ddf3682cf95788294406a | [] | no_license | ninini976/yf_leetcode_problems | af10efb2d1ac881edb0348db3518e02aec7a93f8 | 85415872711c7c4b646f71ba44b5ef9200c03f5e | refs/heads/master | 2021-01-12T04:49:20.672851 | 2018-10-28T06:54:18 | 2018-10-28T06:54:18 | 77,801,458 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,843 | cpp | class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> result;
if(nums.size() < 4){
return result;
}
sort(nums.begin(), nums.end());
int first, second, third, fourth;
for(first = 0; first < nums.size()-3; first++){
int threesum = target - nums[first];
for(second = first+1; second < nums.size()-2; second++){
int twosum = threesum - nums[second];
third = second + 1;
fourth = nums.size() - 1;
while(third < fourth){
if(nums[third] + nums[fourth] > twosum){
fourth--;
}else if(nums[third] + nums[fourth] < twosum){
third++;
}else{
vector<int> temp;
temp.push_back(nums[first]);
temp.push_back(nums[second]);
temp.push_back(nums[third]);
temp.push_back(nums[fourth]);
result.push_back(temp);
while(third+1 < nums.size() && nums[third] == nums[third+1]){
third++;
}
third++;
while(fourth-1 >= 0 && nums[fourth] == nums[fourth-1]){
fourth--;
}
fourth--;
}
}
while(second+1 < nums.size() && nums[second] == nums[second+1]){
second++;
}
}
while(first+1 < nums.size() && nums[first] == nums[first+1]){
first++;
}
}
return result;
}
};
| [
"noreply@github.com"
] | noreply@github.com |
303534876d7131fba83ac3e4cace6baa95289535 | d3cf6d15fd4d29b8f146c26cea14c9bbe30d9f66 | /src/Addons/ofxFX/src/generative/ofxGrayScott.h | 569b9d8aa6037c591b879b47d44c9bf39efe64e7 | [
"MIT"
] | permissive | ImanolGo/MurmurRenderer | c942cd2c42628f685cfce42cf2f14023cff666e5 | 0225dc21f92801cf995b3b715f96721b8be4c0fe | refs/heads/master | 2021-01-20T20:15:51.526209 | 2016-10-24T14:44:34 | 2016-10-24T14:44:34 | 63,713,578 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,189 | h | /*
* ofxGrayScott.h
*
* Created by Patricio González Vivo on 10/1/11.
* Copyright 2011 http://PatricioGonzalezVivo.com All rights reserved.
*
* Based on Reaction Diffusion by Gray-Scott Model
* http://mrob.com/pub/comp/xmorphia/ and Gray Scott Frag shader from rdex-fluxus
* https://code.google.com/p/rdex-fluxus/source/browse/trunk/reactiondiffusion.frag
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the author 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 OFXGRAYSCOTT
#define OFXGRAYSCOTT
#include "ofMain.h"
#include "ofxFXObject.h"
class ofxGrayScott : public ofxFXObject {
public:
ofxGrayScott(){
passes = 10;
internalFormat = GL_RGB;
diffU = 0.25f;
f = 0.0195f;
diffV = 0.04f;
k = 0.066f;
fragmentShader = STRINGIFY(
float kernel[9];
vec2 offset[9];
uniform sampler2DRect backbuffer;
uniform sampler2DRect tex0;
uniform float diffU;
uniform float diffV;
uniform float f;
uniform float k;
void main(void){
vec2 st = gl_TexCoord[0].st;
kernel[0] = 0.707106781;
kernel[1] = 1.0;
kernel[2] = 0.707106781;
kernel[3] = 1.0;
kernel[4] = -6.82842712;
kernel[5] = 1.0;
kernel[6] = 0.707106781;
kernel[7] = 1.0;
kernel[8] = 0.707106781;
offset[0] = vec2( -1.0, -1.0);
offset[1] = vec2( 0.0, -1.0);
offset[2] = vec2( 1.0, -1.0);
offset[3] = vec2( -1.0, 0.0);
offset[4] = vec2( 0.0, 0.0);
offset[5] = vec2( 1.0, 0.0);
offset[6] = vec2( -1.0, 1.0);
offset[7] = vec2( 0.0, 1.0);
offset[8] = vec2( 1.0, 1.0);
vec2 texColor = texture2DRect( backbuffer, st ).rb;
float srcTexColor = texture2DRect( tex0, st ).r;
vec2 lap = vec2( 0.0, 0.0 );
for( int i=0; i < 9; i++ ){
vec2 tmp = texture2DRect( backbuffer, st + offset[i] ).rb;
lap += tmp * kernel[i];
}
float F = f + srcTexColor * 0.025 - 0.0005;
float K = k + srcTexColor * 0.025 - 0.0005;
float u = texColor.r;
float v = texColor.g + srcTexColor * 0.5;
float uvv = u * v * v;
float du = diffU * lap.r - uvv + F * (1.0 - u);
float dv = diffV * lap.g + uvv - (F + K) * v;
u += du * 0.6;
v += dv * 0.6;
gl_FragColor = vec4(clamp( u, 0.0, 1.0 ), 1.0 - u/v ,clamp( v, 0.0, 1.0 ), 1.0);
});
};
ofxGrayScott& setPasses(int _i){ passes = _i; return * this;};
ofxGrayScott& setDiffU(float _diffU){ diffU = _diffU; return * this;};
ofxGrayScott& setDiffV(float _diffV){ diffV = _diffV; return * this;};
ofxGrayScott& setK(float _k){ k = _k; return * this;};
ofxGrayScott& setF(float _f){ f = _f; return * this;};
float getDiffU(){return diffU;};
float getDiffV(){return diffV;};
float getK(){return k;};
float getF(){return f;};
void update(){
for( int i = 0; i < passes ; i++ ){
pingPong.dst->begin();
ofClear(0,0,0,255);
shader.begin();
shader.setUniformTexture("backbuffer", pingPong.src->getTextureReference(), 0 );
shader.setUniformTexture("tex0", textures[0].getTextureReference(), 1 );
shader.setUniform1f( "diffU", (float)diffU);
shader.setUniform1f( "diffV", (float)diffV);
shader.setUniform1f( "f", (float)f );
shader.setUniform1f( "k", (float)k );
renderFrame();
shader.end();
pingPong.dst->end();
pingPong.swap();
}
pingPong.swap();
};
private:
float diffU, diffV, k, f;
};
#endif
| [
"imanolgo@imanolgo.local"
] | imanolgo@imanolgo.local |
4029c3e35e70de17192a0a04787e657939b67612 | 76452106ddd27d0102fa4394ddb27ad12ca06067 | /Software/Realtime/src/Port.cpp | a9a2c814a16f29b0dddd5f1ba4e8fecf3ec6cd00 | [
"MIT"
] | permissive | littleggghost/Nomad | 097a96e74f53368b619948f2b6680e56c844c875 | f30b1f3aa1f1866a6a52f8cd583fc7f769ac3df6 | refs/heads/master | 2020-07-03T08:10:41.333585 | 2019-08-12T01:58:51 | 2019-08-12T01:58:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,464 | cpp | /*
* Port.cpp
*
* Created on: July 25, 2019
* Author: Quincy Jones
*
* Copyright (c) <2019> <Quincy Jones - quincy@implementedrobotics.com/>
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <Realtime/Port.hpp>
#include <limits.h>
#include <pthread.h>
#include <sched.h>
#include <unistd.h>
#include <assert.h>
#include <iostream>
#include <string>
#include <chrono>
#include <map>
#include <Realtime/Messages/double_vec_t.hpp>
namespace Realtime
{
Port::Port(const std::string &name, Direction direction, DataType data_type, int dimension, int period) : direction_(direction), data_type_(data_type), name_(name), update_period_(period), sequence_num_(0), dimension_(dimension)
{
queue_size_ = 1;
transport_type_ = TransportType::INPROC;
transport_url_ = "inproc"; // TODO: Noblock?
// If Input Port Create Handlers
if (direction == Direction::INPUT)
{
if (data_type == DataType::DOUBLE)
{
PortHandler<double_vec_t> *handler = new PortHandler<double_vec_t>(queue_size_);
handler_ = (void *)handler;
}
}
else // Setup Outputs
{
}
}
// TODO: Clear Handler Memory Etc,
Port::~Port()
{
if (data_type_ == DataType::DOUBLE)
{
PortHandler<double_vec_t> *handler = static_cast<PortHandler<double_vec_t> *>(handler);
if (handler)
delete handler;
}
handler_ = 0;
}
void Port::SetSignalLabel(const int signal_idx, const std::string &label)
{
signal_labels_.insert(std::make_pair(signal_idx, label));
}
// TODO: I do not love this...
bool Port::Map(std::shared_ptr<Port> input, std::shared_ptr<Port> output)
{
input->transport_url_ = output->transport_url_;
input->channel_ = output->channel_;
input->transport_type_ = output->transport_type_;
input->dimension_ = output->dimension_;
input->data_type_ = output->data_type_;
input->signal_labels_ = output->signal_labels_;
}
bool Port::Bind()
{
// Reset and Clear Reference
context_.reset();
// Setup Contexts
if (transport_type_ == TransportType::INPROC)
{
context_ = PortManager::Instance()->GetInprocContext();
}
else if (transport_type_ == TransportType::IPC)
{
context_ = std::make_shared<zcm::ZCM>("ipc");
}
else if (transport_type_ == TransportType::UDP)
{
context_ = std::make_shared<zcm::ZCM>(transport_url_);
}
else if (transport_type_ == TransportType::SERIAL)
{
context_ = std::make_shared<zcm::ZCM>(transport_url_);
}
else
{
std::cout << "[PORT:BIND]: ERROR: Invalid Transport Type!" << std::endl;
return false;
}
return true;
}
bool Port::Connect()
{
// Reset and Clear Reference
context_.reset();
// Setup Contexts
if (transport_type_ == TransportType::INPROC)
{
context_ = PortManager::Instance()->GetInprocContext();
}
else if (transport_type_ == TransportType::IPC)
{
context_ = std::make_shared<zcm::ZCM>("ipc");
}
else if (transport_type_ == TransportType::UDP)
{
context_ = std::make_shared<zcm::ZCM>(transport_url_);
}
else if (transport_type_ == TransportType::SERIAL)
{
context_ = std::make_shared<zcm::ZCM>(transport_url_);
}
else
{
std::cout << "[PORT:CONNECT]: ERROR: Invalid Transport Type!" << std::endl;
}
// Now Subscribe
// TODO: Save subs somewhere for unsubscribe
// TODO: Switch Types
if (data_type_ == DataType::DOUBLE)
{
auto subs = context_->subscribe(channel_, &PortHandler<double_vec_t>::HandleMessage, static_cast<PortHandler<double_vec_t> *>(handler_));
}
else
{
std::cout << "[PORT:CONNECT]: ERROR: Unsupported Data Type! : " << data_type_ << std::endl;
return false;
}
if(transport_type_ != TransportType::INPROC)
{
context_->start();
}
return true;
}
///////////////////////
// Port Manager Source
///////////////////////
// Global static pointer used to ensure a single instance of the class.
PortManager *PortManager::manager_instance_ = NULL;
PortManager::PortManager()
{
// ZCM Context
inproc_context_ = std::make_shared<zcm::ZCM>("inproc");
}
PortManager *PortManager::Instance()
{
if (manager_instance_ == NULL)
{
manager_instance_ = new PortManager();
}
return manager_instance_;
}
} // namespace Realtime | [
"quincy@implementedrobotics.com"
] | quincy@implementedrobotics.com |
fcb32416130d65351e3021cd767a2aa7268fc61a | 77a091c62781f6aefeebdfd6efd4bab9caa51465 | /Done/Codeforces/409/A.cpp | 983e7d8e722954f6a3fc095cb49a9112ec621d27 | [] | no_license | breno-helf/Maratona | 55ab11264f115592e1bcfd6056779a3cf27e44dc | c6970bc554621746cdb9ce53815b8276a4571bb3 | refs/heads/master | 2021-01-23T21:31:05.267974 | 2020-05-05T23:25:23 | 2020-05-05T23:25:23 | 57,412,343 | 1 | 2 | null | 2017-01-25T14:58:46 | 2016-04-29T20:54:08 | C++ | UTF-8 | C++ | false | false | 858 | cpp | //If you are trying to hack me I wish you can get it, Good Luck :D.
#include <bits/stdc++.h>
using namespace std;
#define debug(args...) fprintf (stderr,args)
#define pb push_back
#define mp make_pair
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
const int MAX = 112345;
const int INF = 0x3f3f3f3f;
const ll MOD = 1000000007;
string s;
int cnt = 0, V = 0, K = 0;
int n;
int main() {
cin >> s;
n = s.size();
for (int i = 1; i < n; i++) {
if (s[i] == 'K' && s[i - 1] == 'V') {
cnt++;
i++;
} else if (s[i] == 'K' && s[i - 1] == 'K') {
K = 1;
}
}
for (int i = (n - 1); i >= 1; i--) {
if (s[i] == 'K' && s[i - 1] == 'V') i--;
else if (s[i] == 'V' && s[i - 1] == 'V') V = 1;
}
//debug("--> %d %d %d\n", cnt, V, K);
if (V == 1 || K == 1) cnt++;
printf("%d\n", cnt);
}
| [
"breno.moura@hotmail.com"
] | breno.moura@hotmail.com |
c5eee65f2d202ac7f04fceac630cc915ad4dccdb | e07e70fd50ee903463a9fac246c6c4a1281a6315 | /source/BigQ.cc | e801155119f0b821ef730e1f6507d298095d74fe | [] | no_license | sharuu123/Database-System-Implemetation | 385f7cce19534c71c7fc73b39eae9d6757338584 | ab99a630f3a6ec205d16a2449f6ee159dcf38a9e | refs/heads/master | 2021-01-22T10:13:44.985092 | 2015-04-14T01:58:16 | 2015-04-14T01:58:16 | 32,035,921 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,604 | cc | #include "BigQ.h"
// OrderMaker G_sortorder;
// ComparisonEngine G_comp;
// static int G_runlen=0;
// static int G_curSizeInBytes = 0;
// static BigQ_input G_input;
// Schema mySchema ("../source/catalog", "orders");
// Initial creation of temp files
int BigQ::Create (char* s, merger *merge_file) {
try{
merge_file->name = s;
merge_file->f.Open(0,s);
merge_file->p.EmptyItOut();
merge_file->curpage = 0;
merge_file->totalpages = 1;
return 1;
}
catch(...){
return 0;
}
}
int BigQ::GetNext (Record &fetchme, merger *merge_file) {
if(merge_file->p.GetFirst(&fetchme)){
return 1;
}
else{
if(merge_file->curpage < merge_file->f.GetLength() - 2){
merge_file->curpage++;
merge_file->f.GetPage(&merge_file->p,merge_file->curpage);
if(GetNext(fetchme,merge_file)){
return 1;
}
}
return 0;
}
}
// helper function to send the file
int BigQ::SendAll(merger *merge_file, BigQ_input *t){
merge_file->curpage = 0;
merge_file->p.EmptyItOut();
merge_file->f.GetPage(&(merge_file->p),merge_file->curpage);
Record temp;
while(GetNext(temp,merge_file) == 1){
t->out->Insert(&temp);
}
}
// finally sending the sorted
int BigQ::SendSocket(merger *merge_file, BigQ_input *t){
// cout << merge_file->name << endl;
merge_file->curpage = 0;
merge_file->p.EmptyItOut();
// cout << "test ?" << endl;
merge_file->f.GetPage(&(merge_file->p),merge_file->curpage);
// cout << "works ?" << endl;
Record temp;
int val = 0;
mysorter.s=so;
// merge_file->ex=excess;
sort(excess.begin(),excess.end(),mysorter);
while(GetNext(temp,merge_file) == 1){
while(val< excess.size()){
if(G_comp.Compare (&temp, excess[val], so) != 1){
break;
}
else{
//Sending overflowed record
t->out->Insert(excess[val]);
val++;
}
}
// Sending record
t->out->Insert(&temp);
}
while(val<excess.size()){
// Send the overflowed pending records
t->out->Insert(excess[val]);
val++;
}
// cout << "sendng" << endl;
}
// This is a helper function to check the unsorted records after each merge
int BigQ::check_file(merger *merge_file, int runlen){
int entries = 0;
merge_file->curpage = 0;
Record recs[2];
merge_file->p.EmptyItOut();
merge_file->f.GetPage(&(merge_file->p),merge_file->curpage);
Record *lasts = NULL, *prevs = NULL;
int last_page = 0; int prev_page = 0;
int errs = 0;
int j = 0;
while (GetNext((recs[j%2]),merge_file)) {
entries++;
prevs = lasts;
prev_page = last_page;
lasts = &recs[j%2];
last_page = merge_file->curpage;
if (prevs && lasts) {
if (G_comp.Compare (prevs, lasts, so) == 1) {
errs++;
// Previous page and last page should be different
// and last_page should be multiple of runlength
// cout << j << " " << prev_page << " " << last_page << endl;
// prevs->Print (&mySchema);
// lasts->Print (&mySchema);
if(runlen > merge_file->f.GetLength()){
exit(-1);
}
}
}
j++;
}
merge_file->curpage = 0;
merge_file->p.EmptyItOut();
// cout << "Checked " << j << ", Errors: " << errs << ", totalpages: " << merge_file->f.GetLength() << endl;
}
int vals = 0;
int BigQ::savelist (vector<Record *> v, merger *merge_file) {
// cout << " Writing from: " << merge_file->curpage << endl;
vals = vals + v.size();
merge_file->p.EmptyItOut();
mysorter.s=so;
sort(v.begin(),v.end(),mysorter);
int count = rlen;
int added_file = 0;
int added_overflow = 0;
bool saved = false;
for(int i = 0;i < v.size();i++){
Record * rec = v[i];
if(count > 0){
added_file++;
if(!merge_file->p.Append(rec)){
merge_file->f.AddPage(&(merge_file->p), merge_file->curpage);
merge_file->p.EmptyItOut();
saved = true;
merge_file->curpage++;merge_file->totalpages++;
// cout << " Adding " << count << " " << merge_file->curpage-1 << endl;
count--;
if(count > 0){
merge_file->p.Append(rec);
saved = false;
}
else{
added_overflow++;
added_file--;
overflow.push_back(v[i]);
saved = true;
// pushing overflow records
}
}
}
else{
added_overflow++;
// v.erase(v.begin(), v.begin() + i);//
overflow.push_back(v[i]);
}
}
if(v.size() - added_overflow - added_file != 0){
cout << "Check Save vector " << v.size() - added_overflow - added_file << endl;
}
v.clear();
if(!saved){
merge_file->f.AddPage(&(merge_file->p), merge_file->curpage);
merge_file->curpage++;merge_file->totalpages++;
merge_file->p.EmptyItOut();
}
if(count <= 0){
return 0;
}
else{
return 1;
}
}
// void *TPMMS (void *arg) {
void* BigQ::TPMMS () {
// BigQ_input *t = (BigQ_input *) arg;
//creating two files
merger *first_file = new merger();
merger *second_file = new merger();
char first_path[100];
char second_path[100];
sprintf (first_path, "Bigq.bin");
Create(first_path,first_file);
sprintf (second_path, "Bigq_temp.bin");
Create(second_path,second_file);
// Created two files for the two way merger sort
// compare function for the vector sort.
// class Compare{
// public:
// OrderMaker *s;
// Compare(OrderMaker *sort) {
// s = sort;
// }
// bool operator()(Record * R1, Record *R2)
// {
// ComparisonEngine comp;
// if((comp).Compare(R1,R2,s) == -1){
// return true;
// }
// else{
// return false;
// }
// }
// };
// Compare mysorter(so);
vector<Record *> v;
G_curSizeInBytes = 0;
while (true) {
Record * curr = new Record();
if(t->in->Remove(curr)){
char *b = curr->GetBits();
int rec_size = ((int *) b)[0];
if (G_curSizeInBytes + rec_size < (PAGE_SIZE)*rlen) {
G_curSizeInBytes += rec_size;
// pq.push(curr);
v.push_back(curr);
}
else{
if(!savelist(v,first_file)){
// cout << "overflowww" << endl;
}
v.clear();
v.push_back(curr);
G_curSizeInBytes = rec_size;
}
}
else{
break;
}
}
// Each runlength records are sorted and added to the file
//Now adding the pending overflowed and last records
// cout << "Total : " << vals + v.size() << endl;
vector <Record *> pending;
pending.reserve( v.size() + overflow.size() ); // preallocate memory
pending.insert( pending.end(), v.begin(), v.end() );
pending.insert( pending.end(), overflow.begin(), overflow.end() );
mysorter.s=so;
sort(pending.begin(),pending.end(),mysorter);
// cout << v.size() << " " << overflow.size() << " " << pending.size() << endl;
first_file->p.EmptyItOut();
for(int i = 0;i < pending.size();i++){
Record * rec = pending[i];
if(!first_file->p.Append(rec)){
first_file->f.AddPage(&(first_file->p), first_file->curpage);
first_file->p.EmptyItOut();
first_file->curpage++;first_file->totalpages++;
first_file->p.Append(rec);
// cout << "Adding " << first_file->curpage-1 << endl;
}
}
first_file->f.AddPage(&first_file->p,first_file->curpage);
first_file->totalpages++;first_file->curpage++;
// cout << "Adding " << first_file->curpage-1 << endl;
v.clear();
overflow.clear();
pending.clear();
// clear the pending data as you have already added the records to the file
// cout << "Initial " << first_file->totalpages << " " << first_file->f.GetLength() << endl;
check_file(first_file,rlen);
// SendAll(first_file,t);
// t->out->ShutDown();
// exit(-1);
// TPMMS CODE to merge
first_file->mtype = source;
second_file->mtype = destination;
block *first = new block();
first->curpage = 0;
block *second = new block();
second->curpage = rlen;
first_file->first = first;
first_file->second = second;
second_file->first = new block();
second_file->second = new block();
second_file->first->curpage = 0;
second_file->second->curpage = rlen;
int cur_runlength = rlen;
merger * source_file = first_file;
merger * destination_file = second_file;
int max_page = 0;
block_state = initial;
source_file->ex=excess;
// cout << "Initial start" << endl;
cout << "\nTPMMS Merge start\n" << endl;
while(block_state != merge_done){
switch(block_state){
case initial:
if(source_file->mtype != source){
cout << "Source type doesnt match" << endl;
exit(-1);
}
source_file->first->count = cur_runlength;
source_file->second->count = cur_runlength;
// cout << "Merging " << source_file->first->curpage << " " << source_file->second->curpage << endl;
max_page = source_file->second->curpage + cur_runlength;
// cout << "Load page of first block" << endl;
source_file->loadpage(0);
// cout << "get record of first block" << endl;
if(!source_file->first->getRecord()){
source_file->first->curpage++;
if(!source_file->loadpage(0)){
block_state = done;
break;
}
else{
if(!source_file->first->getRecord()){
block_state = done;
break;
}
}
}
// cout << "Load page of second block" << endl;
if(!source_file->loadpage(1)){
block_state = second_done;
break;
}
// cout << "get record of second block" << endl;
// source_file->first->rec.Print(&mySchema);
if(!source_file->second->getRecord()){
source_file->second->curpage++;
if(!source_file->loadpage(1)){
block_state = second_done;
break;
}
else{
if(!source_file->second->getRecord()){
block_state = second_done;
break;
}
}
}
block_state = compare;
break;
case compare:
// cout << "compare" << endl;
if((G_comp).Compare(&(source_file->first->rec),&(source_file->second->rec),so) != 1){
// cout << "add firrst" << endl;
destination_file->AddRec(source_file->first->rec,max_page);
block_state = read_first;
}
else{
// Adding the second record
destination_file->AddRec(source_file->second->rec,max_page);
block_state = read_second;
}
break;
case read_first:
// cout << "read_first" << endl;
if(!source_file->first->getRecord()){
source_file->first->curpage++;
if(!source_file->loadpage(0)){
block_state = first_done;
break;
}
else{
if(!source_file->first->getRecord()){
block_state = first_done;
break;
}
}
}
block_state = compare;
break;
case read_second:
// cout << "read_second" << endl;
// cout << block_state << endl;
if(!source_file->second->getRecord()){
source_file->second->curpage++;
if(!source_file->loadpage(1)){
block_state = second_done;
break;
}
else{
if(!source_file->second->getRecord()){
block_state = second_done;
break;
}
}
}
block_state = compare;
break;
case first_done:
// cout << "first_done" << endl;
destination_file->AddRec(source_file->second->rec,max_page);
if(!source_file->second->getRecord()){
source_file->second->curpage++;
if(!source_file->loadpage(1)){
block_state = done;
break;
}
else{
if(!source_file->second->getRecord()){
block_state = done;
break;
}
}
}
block_state = first_done;
break;
case second_done:
// cout << "second_done" << endl;
destination_file->AddRec(source_file->first->rec,max_page);
if(!source_file->first->getRecord()){
source_file->first->curpage++;
if(!source_file->loadpage(0)){
block_state = done;
break;
}
else{
if(!source_file->first->getRecord()){
block_state = done;
break;
}
}
}
else{
block_state = second_done;
break;
}
// cout << "adding records" << endl;
break;
case done:
// cout << "Done" << endl;
destination_file->f.AddPage(&destination_file->p,destination_file->curpage);
destination_file->p.EmptyItOut();
destination_file->totalpages++;
destination_file->curpage++;
// cout << source_file->first->curpage << " " << source_file->totalpages-2 << endl;
if(source_file->first->curpage >= source_file->totalpages-1){
block_state = finish;
break;
}
else{
// cout << "After Merge " << source_file->first->curpage << " " << source_file->second->curpage << endl;
source_file->first->curpage += cur_runlength ;
source_file->second->curpage += + cur_runlength;
// cout << "Count " << source_file->first->count << " " << source_file->second->count << endl;
// cout << "Go for next merge " << source_file->first->curpage << " " << source_file->second->curpage << endl;
block_state = initial;
break;
}
break;
case finish:
// cout << "Merge done" << endl;
// cout << cur_runlength << " " << source_file->curpage << " " << source_file->totalpages-2 << endl;
destination_file->curpage++;
if(cur_runlength >= source_file->f.GetLength() ){
block_state = merge_done;
break;
}
else{
// cout << "TPMMS Merge done using " << cur_runlength << endl;
cur_runlength = 2 * cur_runlength;
// cout << "TPMMS Merge Start with Runlen: " << cur_runlength << endl;
// cout << cur_runlength << endl;
// check_file(destination_file,cur_runlength/2);
// Phase Done
// Swap Source and Destination and again do TPMMS
merger * temp = source_file;
source_file = destination_file;
destination_file = temp;
source_file->mtype = source;
source_file->curpage = 0;
destination_file->curpage = 0;
source_file->first->curpage = 0;
destination_file->totalpages = 1;
source_file->second->curpage = cur_runlength;
destination_file->mtype = destination;
block_state = initial;
break;
}
break;
}
}
cout << "TPMMS Merge done\n" << endl;
// cout << "Sending Records " << endl;
// Sending records
excess=destination_file->ex;
SendSocket(destination_file,t);
t->out->ShutDown();
// remove(first_file->name);
// remove(second_file->name);
// remove ("Bigq.bin");
// remove ("Bigq_temp.bin");
delete first_file;
delete second_file;
}
BigQ :: BigQ (Pipe &in, Pipe &out, OrderMaker &sortorder, int runlen) {
// read data from in pipe sort them into runlen pages
// construct priority queue over sorted runs and dump sorted data
// into the out pipe
// finally shut down the out pipe
// G_sortorder = sortorder;
// G_runlen = runlen;
// G_input = {&in, &out};
t = new BigQ_input;
*t = {&in,&out};
rlen = runlen;
so = new OrderMaker;
*so = sortorder;
// pthread_t thread;
pthread_create (&thread, NULL, TPMMS_helper , this);
// pthread_create (&thread, NULL, TPMMS , (void *)&G_input);
// pthread_join (thread, NULL);
}
BigQ::~BigQ () {
} | [
"sharuu123@gmail.com"
] | sharuu123@gmail.com |
e05d5033bbe6399798675ddbb982ea4bb552103a | 8c01b286917ca24bee4d6ede0f1f336cbc445577 | /Distributor/AssistantDll/Device/NDCrEnLib.cpp | e36a9051cf24d8fa51a0468cd26e283f62f37fe5 | [] | no_license | bugHappy/ND91 | 8d501682beb37212aea7e3ba73114c048c4ff689 | 0e0c44927d7b1564fa99e64d6c3ddce319d523bc | refs/heads/master | 2021-04-07T22:09:19.797378 | 2019-08-02T05:30:47 | 2019-08-02T05:30:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,113 | cpp | #include "NDCrEnLib.h"
HINSTANCE CNDCrEnLib::m_ndCrEnLib = NULL;
Encrypt CNDCrEnLib::m_Encrypt = NULL;
Decrypt CNDCrEnLib::m_Decrypt = NULL;
CNDCrEnLib::CNDCrEnLib(void)
{
m_ndCrEnLib = NULL;
}
CNDCrEnLib::~CNDCrEnLib(void)
{
}
bool CNDCrEnLib::MyLoadLibrary()
{
if (m_ndCrEnLib)
return true;
m_ndCrEnLib = ::LoadLibrary(DLLNDCREN);
if (!m_ndCrEnLib)
{
return false;
}
return true;
}
void CNDCrEnLib::MyFreeLibrary()
{
if (m_ndCrEnLib)
{
::FreeLibrary(m_ndCrEnLib);
m_ndCrEnLib = NULL;
}
}
bool CNDCrEnLib::Ios_Encrypt(const char* strPlain, unsigned char* key, unsigned char* pCryptBuf)
{
if (!MyLoadLibrary())
return false;
m_Encrypt = (Encrypt)GetProcAddress(m_ndCrEnLib, "Encrypt");
if (!m_Encrypt)
{
return false;
}
m_Encrypt(strPlain, key, pCryptBuf);
return true;
}
bool CNDCrEnLib::Ios_Decrypt(unsigned char* key, unsigned char* pCryptBuf, char* outPtr)
{
if (!MyLoadLibrary())
return false;
m_Decrypt = (Decrypt)GetProcAddress(m_ndCrEnLib, "Decrypt");
if (!m_Decrypt)
{
return false;
}
m_Decrypt(key, pCryptBuf, outPtr);
return true;
}
| [
"czy@tongbu.com"
] | czy@tongbu.com |
d4e9560960979894e4851d3d5b9280495f87e78c | 4f2283750a3bb8706f1dd176cf9823c5f67f40c8 | /chaos/common/bson/bson_builder_base.h | a3dc22672ff4c28cdf45e05a74e12efdec6cd68c | [
"Apache-2.0"
] | permissive | fast01/chaosframework | 62d97cc05823d9ec71f494ac518f927cbf837476 | 28194bcca5f976fd5cf61448ca84ce545e94d822 | refs/heads/master | 2020-12-31T04:06:07.569547 | 2014-12-05T09:37:34 | 2014-12-05T09:37:34 | 29,051,305 | 2 | 0 | null | 2015-01-10T08:07:31 | 2015-01-10T08:07:31 | null | UTF-8 | C++ | false | false | 2,044 | h | /* Copyright 2012 10gen Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <chaos/common/bson/base/string_data.h>
#include <chaos/common/bson/util/builder.h>
namespace bson {
/*
* BSONBuilderBase contains the common interface between different types of BSON builders.
*
* Currently, this interface is not comprehensive. But we should work toward that goal. If
* you are maintaining the class, please make sure that all Builders behave coherently.
*/
class BSONBuilderBase {
public:
virtual ~BSONBuilderBase() {}
virtual BSONObj obj() = 0;
virtual BufBuilder& subobjStart( const StringData& fieldName ) = 0;
virtual BufBuilder& subarrayStart( const StringData& fieldName ) = 0;
virtual BSONBuilderBase& append( const BSONElement& e) = 0;
virtual BSONBuilderBase& append( const StringData& fieldName , int n ) = 0;
virtual BSONBuilderBase& append( const StringData& fieldName , long long n ) = 0;
virtual BSONBuilderBase& append( const StringData& fieldName , double n ) = 0;
virtual BSONBuilderBase& appendArray( const StringData& fieldName , const BSONObj& subObj ) = 0;
virtual BSONBuilderBase& appendAs( const BSONElement& e , const StringData& filedName ) = 0;
virtual void appendNull( ) = 0;
virtual BSONBuilderBase& operator<<( const BSONElement& e ) = 0;
virtual bool isArray() const = 0;
};
} // namespace bson
| [
"Claudio.Bisegni@lnf.infn.it"
] | Claudio.Bisegni@lnf.infn.it |
a65e78990dd7a9c3dbaf726dcd02ab8eb2fa7d0c | 5a3af48f1993f7505167c91ce331ee8d410b6e28 | /Engine/Components/PhysicsComponent.h | 7b182f41672e3b75edd82e362ee1cd3824f1b356 | [] | no_license | LuciusEverest/Gat150 | 46040597a8dbecbc1d5c7b115b0ba81306653600 | bfff0d95d8e38dd91ba63180145298d0982d81e4 | refs/heads/master | 2022-12-16T19:25:24.621066 | 2020-09-01T22:56:06 | 2020-09-01T22:56:06 | 284,792,372 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 549 | h | #pragma once
#include "Component.h"
#include <Math\Vector2.h>
namespace bleh
{
class PhysicsComponent : public Component
{
public:
virtual void Create(void* data = nullptr) override;
virtual void Destroy() override;
virtual Object* Clone() const override { return new PhysicsComponent{ *this }; }
virtual void Update() override;
virtual void ApplyForce(const Vector2& force) { m_force = force; }
virtual Vector2 GetVelocity() { return m_velocity; }
protected:
Vector2 m_velocity;
Vector2 m_force;
float m_drag{ 1 };
};
}
| [
"61430189+LuciusEverest@users.noreply.github.com"
] | 61430189+LuciusEverest@users.noreply.github.com |
32b06f74fc2fc7070cdc2aa91995072f5f03102e | b8c72b879744e9eab3f447032a6265c5336fff6c | /CodeBlocks/Chapter07/mutex/mutex.cpp | 075d97483352a64b7761e78f42f98a4fab91d67f | [] | no_license | mobilenjoy/learning_cpp_functional_programming_kor | 3f722236af31b1eb2f79111d84f94c94573d6151 | 8b962a89ad1682179489ab725ba0a62500dff698 | refs/heads/master | 2020-04-29T06:57:47.965280 | 2019-01-20T07:18:52 | 2019-01-20T07:18:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 626 | cpp | /* mutex.cpp */
#include <thread>
#include <mutex>
#include <iostream>
using namespace std;
auto main() -> int
{
cout << "[mutex.cpp]" << endl;
mutex mtx;
int counter = 0;
thread threads[5];
for (int i = 0; i < 5; ++i)
{
threads[i] = thread([&counter, &mtx]()
{
for (int i = 0; i < 10000; ++i)
{
mtx.lock();
++counter;
mtx.unlock();
cout << "Thread ID: ";
cout << this_thread::get_id();
cout << "\tCurrent Counter = ";
cout << counter << endl;
}
});
}
for (auto& thread : threads)
{
thread.join();
}
cout << "Final result = " << counter << endl;
return 0;
}
| [
"nnhope@hotmail.com"
] | nnhope@hotmail.com |
edef2a5fda76314e94045a49510482151db454b0 | 3ac6b725d6d8c8017fce8d52c2ddb58137f935bf | /Server/server/server (3).cpp | 757dd8c240c23cfce58978636871bc4ca395a2e1 | [] | no_license | SaewookJeong/Net_test | 2cf206546914057d81827ad02b5df422612f0303 | d0ac9b8395b2e13f429d43e300fd8e6a8b3daaa5 | refs/heads/master | 2021-01-22T07:19:21.960234 | 2016-04-27T08:07:22 | 2016-04-27T08:07:22 | 53,841,125 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 2,375 | cpp | #include<stdio.h>
#include<winsock2.h>
#include<iostream>
#include<process.h> //스레드를 위한 헤더파일
using namespace std;
char echo[10];
DWORD WINAPI ProcessClient(LPVOID arg)
{
SOCKET clientsock = (SOCKET)arg;
char revmessage[1024];
SOCKADDR_IN clientinfo;
int clientsize;
int strlen;
clientsize = sizeof(clientinfo);
if(clientsock==INVALID_SOCKET) cout<<"클라이언트 소켓 연결 실패 "<<endl;
cout<<"Connect"<<endl;
while(1){
for(int i = 0; i < 1024; i ++) revmessage[i]=0;
strlen=recv(clientsock , revmessage, sizeof(revmessage)-1, 0);
if(strlen == 0)
{
cout<<"Disconnect"<<endl;
break;
}
cout<<revmessage<<endl;
if(strcmp(echo, "-echo") == 0)
send(clientsock, revmessage, sizeof(revmessage)-1, 0);
}
return 0;
}
int main(int argc, char *argv[])
{
SOCKET sock, clientsock;
WSADATA wsa;
struct sockaddr_in sockinfo, clientinfo;
int clientsize;
char message[]="Connect";
if (argc != 2)
{
if(argc == 3 && strcmp(argv[2], "-echo") == 0)
{
strcpy(echo, argv[2]);
co
}
printf("Usage : %s <PORT> <-echo> \n", argv[0]);
exit(1);
}
start:
if(WSAStartup(MAKEWORD(2,2), &wsa) != 0)
cout<<"초기화 실패"<<endl;
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(sock == INVALID_SOCKET)
cout<<"소켓 생성 실패"<<endl;
memset(&sockinfo,0,sizeof(sockinfo));
sockinfo.sin_family = AF_INET;
sockinfo.sin_port = htons(atoi(argv[1]));
sockinfo.sin_addr.s_addr=htonl(INADDR_ANY);
if(bind(sock, (SOCKADDR*)&sockinfo, sizeof(sockinfo)) == SOCKET_ERROR) // return 값 success = 0, otherwise = SOCKET_ERROR;
cout<<"bind 실패"<<endl;
if(listen(sock , 5) == SOCKET_ERROR) // return 값 success = 0, otherwise = SOCKET_ERROR;
cout<<"대기열 실패 "<<endl;
clientsize = sizeof(clientinfo);
cout<<"클라이언트로부터 접속을 기다리고 있습니다.."<<endl;
HANDLE hThread; // 스레드 핸들
DWORD ThreadID; // 스레드 아이디
while(1)
{
clientsock = accept(sock, (SOCKADDR*)&clientinfo, &clientsize);
hThread = CreateThread(NULL, 0, ProcessClient, (LPVOID)clientsock, 0, &ThreadID);
if(hThread == NULL)cout<<"스레드 생성 실패"<<endl;
}
closesocket(clientsock);
closesocket(sock);
WSACleanup();
} | [
"tpdnrzz@jungbu.ac.kr"
] | tpdnrzz@jungbu.ac.kr |
942dfae0dbca58a1813ef4d46cecbce66f0d2074 | 845257ad2a2d0d13df713802b114c3aa129aa011 | /Miscellaneous/RookBishopKing-CF.cpp | d5481f3bf7de600712d208de2a9598cbfc683a39 | [] | no_license | ayush8799/cp-templates | 7995bd8bc710837833879ec90ce26e8d54692c81 | 464255b6ae58452b8451cf1f8dd9bfa85d5214ea | refs/heads/master | 2023-06-10T15:47:02.404079 | 2021-07-03T11:34:38 | 2021-07-03T11:34:38 | 382,589,531 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,157 | cpp | #include <bits/stdc++.h>
using namespace std;
#define vi vector<int>
#define vvi vector<vector<int>>
#define vpii vector<pair<int, int>>
#define pb push_back
#define ff first
#define ss second
#define pii pair<int, int>
#define int long long int
#define el "\n"
#define inf INT_MAX
#define _inf INT_MIN
#define whilet int t;cin>>t;while(t--)
#define prDouble(x) cout<<fixed<<setprecision(10)<<x
const int N = 100005;
const int mod = 1e9 + 7;
int x, y, tx, ty;
int rook() {
return (x != tx) + (y != ty);
}
int bishop() {
if (x == tx && y == ty) return 0;
if (((x + y) & 1) and !((tx + ty) & 1) or !((x + y) & 1) and ((tx + ty) & 1) ) return 0;
return (x - y) == (tx - ty) || (x + y) == (tx + ty) ? 1 : 2;
}
int king() {
return max(abs(tx - x), abs(ty - y));
}
void solve() {
cin >> x >> y >> tx >> ty;
int r = rook();
int b = bishop();
int k = king();
cout << r << " " << b << " " << k << el;
}
void init() {
ios_base:: sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("../input.txt", "r", stdin);
freopen("../output.txt", "w", stdout);
#endif
}
int32_t main()
{
init();
// whilet solve();
solve();
} | [
"ayush.mishra8799@gmail.com"
] | ayush.mishra8799@gmail.com |
8e9d6100bc487680cd72fa76f5d90c480cc13e8a | 598cc9c041e3737b265d4bf37f6b29d75b92300e | /System.h | 714f1033a01c8b7cef351e9f4edc64d40717911a | [] | no_license | karno/heavenly | bf2b5a676af57c5d591cc49a835bd324ac104ac2 | 42c0250d0f5f7402d0cd750390cae9a16fe3682e | refs/heads/master | 2016-09-09T23:29:38.388507 | 2012-11-08T15:51:09 | 2012-11-08T15:51:09 | 6,598,814 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 806 | h | #ifndef __C_SYSTEM__
#define __C_SYSTEM__
#include <vector>
#include <cstdio>
using namespace std;
class System
{
public:
template <typename T>
static vector<T> CloneVector(const vector<T>& vec)
{
vector<T> clone;
for (typename vector<T>::const_iterator iter = vec.begin();
iter != vec.end();
++iter)
{
clone.push_back(*iter);
}
return clone;
}
template <typename T>
static vector<vector<T> > CloneVecVec(const vector<vector<T> >& vec)
{
vector<vector<T> > clone;
for (typename vector<vector<T> >::const_iterator iter = vec.begin();
iter != vec.end();
++iter)
{
clone.push_back(CloneVector(*iter));
}
return clone;
}
inline static void WaitInput()
{
fflush(stdin);
getchar();
}
};
#endif
| [
"karnoroid@gmail.com"
] | karnoroid@gmail.com |
25fd984dc255a4d8f17308e4fba878df871fbe08 | 702305f05e89b78b828e2aeff2df15133a0114c7 | /accessing_classes_and_objects/player_example.cpp | 2c829bf99bc07728bf0bfcb4178d9937d35dc2ef | [] | no_license | AnkyXCoder/cppWorkspace | bf6776120d5bdc02584e58197076cab71cbda493 | 63aa7ffcc64899d1c972408db352610929b4351c | refs/heads/master | 2023-08-08T18:18:08.062184 | 2023-08-08T16:01:03 | 2023-08-08T16:01:03 | 233,562,419 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,683 | cpp | /* Accessing Classes and Objects
- access class
- access methods
If we have an object, we can access members using dot (.) operator
If we have a pointer to an object, we can access members using
* dereference the pointer and then using dot (.) operator
* using arrow (->) operator
Some class members will not be accessible
we need an object to access instance variables
*/
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Player {
public:
// attributes
string name {"Player"};
int health {100};
int xp {0};
// methods
void greetings(string player_name) {
cout << "Hello, " << player_name << ". Welcome to the Game World." << endl;
}
void talk(string sentence) {
cout << sentence << endl;
}
bool is_dead(int health_points) {
if (health_points <= 0) {
cout << "Player is dead." << endl;
return 1;
} else {
cout << "Player is not dead." << endl;
}
};
};
int main(void) {
// declarations
Player dante;
// accessing attributes
dante.name = "Dante";
dante.health = 50;
dante.xp = 5;
// accessing methods
dante.greetings(dante.name);
dante.is_dead(dante.health);
// creating a new player in heap storage
Player *enemy = {nullptr};
// accessing attributes
enemy = new Player;
enemy->name = "Vergil";
enemy->health = 100;
(*enemy).xp = 100;
// accessing methods
(*enemy).greetings(enemy->name);
enemy->is_dead(enemy->health);
enemy->talk("I will kill you, Dante.");
delete enemy;
return 0;
} | [
"ankit.5036@gmail.com"
] | ankit.5036@gmail.com |
aa760181d16a3275341800b2956d5168148f7904 | ee9a02176e1f1af12a937bb7d413c853734d5908 | /rot13.cpp | c9dd8a876219778914221335a0131f459334bff7 | [] | no_license | thomas-osgood/CPP-Misc | 9075d8aaf80b2cc37863e756703103adec74705a | d8f7c292c16913b1a74003f04c23c69a0860eac2 | refs/heads/master | 2021-07-02T08:30:47.068234 | 2021-02-08T02:50:10 | 2021-02-08T02:50:10 | 220,572,528 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,705 | cpp | /*
ROT13 is a simple letter substitution cipher that replaces a letter with the letter 13 letters after it in the alphabet. ROT13 is an example of the Caesar cipher.
Create a function that takes a string and returns the string ciphered with Rot13. If there are numbers or special characters included in the string, they should be returned as they are. Only letters from the latin/english alphabet should be shifted, like in the original Rot13 "implementation".
*/
#include <string>
using namespace std;
/*
Strategy:
Loop through the entire string, converting every character to an
integer value. Then compare the integer value to the ranges
between 'a' and 'z', and 'A' and 'Z'. If the character falls within
one of those ranges, manipulate the character and append the new
character to the return string; otherwise append the existing
character to the return string.
*/
string rot13(string msg)
{
/* Init Local Variables */
int i = 0, end = msg.length(), current = 0;
int la = (int)'a', lz = (int)'z', ca = (int)'A', cz = (int)'Z';
char newVal;
string retVal;
/* Loop Through String */
for (i = 0; i < end; i++) {
current = (int)msg[i];
if ((current >= la) && (current <= lz)) {
/* Handle Lowercase Letters */
newVal = (((current - la) + 13) % 26) + la;
retVal += newVal;
} else if ((current >= ca) && (current <= cz)) {
/* Handle Uppercase Letters */
newVal = (((current - ca) + 13) % 26) + ca;
retVal += newVal;
} else {
/* Handle Everything Else */
retVal += msg[i];
}
}
/* Return Cypher */
return retVal;
}
| [
"noreply@github.com"
] | noreply@github.com |
71f32378e061971e578bd710b2ff68aeac25a417 | 094a76395f4e55e13393b71998e2646a5ec2c5e8 | /scriptTest/scriptTest_GLOBALS.cpp | e473583cb8660a6d6b8eaa29a8b2059a36d2db4d | [] | no_license | marcclintdion/_32bit_Stride_ADD_STRIGNS | 76b98528b13ee04ec01970bf8dd6a4d0a75c9cd8 | 74e38341068e805f7e94349601cbabe93e02a748 | refs/heads/master | 2016-09-10T18:42:57.445065 | 2015-09-18T05:05:29 | 2015-09-18T05:05:29 | 42,700,219 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,984 | cpp | GLfloat scriptTest_POSITION[] = { 0.0, 0.0, 0.0, 1.0};
GLfloat scriptTest_ROTATE[] = { 0.0, 1.0, 0.0, 0.0};
GLfloat scriptTest_SCALE[] = { 1.0, 1.0, 1.0, 1.0};
//-----------------------------------------------------------------
GLfloat scriptTest_LIGHT_POSITION_01[] = { 2.0, 15.0, 30.0, 1.0};
GLfloat scriptTest_SHININESS = 80.0;
GLfloat scriptTest_ATTENUATION = 1.0;
//-----------------------------------------------------------------
GLuint scriptTest_VBO;
GLuint scriptTest_INDICES_VBO;
//-----------------------------------------------------------------
GLuint scriptTest_NORMALMAP;
GLuint scriptTest_TEXTUREMAP;
//====================================================================================
GLfloat scriptTest_boundingBox[6];
| [
"marcclintdion@Marcs-iMac.local"
] | marcclintdion@Marcs-iMac.local |
1a240bc06464ef55dda05ecdcc74dd23afcc05ce | cb9535a1dfea27158430d25aab71f4b903968386 | /code/demo_chaos/renderer_camera.cpp | ab73c0fea3efcf233a46ab31b7cd5287f2d66333 | [] | no_license | uhacz/bitbox | 0d87a54faa4bf175a2fdb591c4ea5f71935c67fb | 63b4038a1b8cf05968c55ad11b25344fff44aba5 | refs/heads/master | 2021-01-23T09:40:25.289880 | 2017-09-09T18:15:06 | 2017-09-09T18:15:06 | 32,782,269 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,208 | cpp | #include "renderer_camera.h"
#include <util/camera.h>
namespace bx{ namespace gfx{
float Camera::aspect() const
{
return( fabsf( params.vAperture ) < 0.0001f ) ? params.hAperture : params.hAperture / params.vAperture;
}
float Camera::fov() const
{
return 2.f * atanf( ( 0.5f * params.hAperture ) / ( params.focalLength * 0.03937f ) );
}
Vector3 Camera::worldEye() const
{
return world.getTranslation();
}
Vector3 Camera::worldDir() const
{
return -world.getCol2().getXYZ();
}
Viewport computeViewport( const Camera& camera, int dstWidth, int dstHeight, int srcWidth, int srcHeight )
{
return computeViewport( camera.aspect(), dstWidth, dstHeight, srcWidth, srcHeight );
}
void computeMatrices( Camera* cam )
{
const float fov = cam->fov();
const float aspect = cam->aspect();
cam->view = inverse( cam->world );
//cam->proj = Matrix4::perspective( fov, aspect, cam->params.zNear, cam->params.zFar );
cam->proj = cameraMatrixProjection( aspect, fov, cam->params.zNear, cam->params.zFar );
cam->proj_api = cameraMatrixProjectionDx11( cam->proj );
//cam->proj = cameraMatrixProjectionDx11( cam->proj );
cam->view_proj = cam->proj_api * cam->view;
}
}}/// | [
"uhacz33@gmail.com"
] | uhacz33@gmail.com |
2bd523b8d70f3fdb75dd3a565601363a7f72a092 | 2e15aca44a9a226794bb52889718397e98db32bf | /FinalProject/CircularTower.cpp | 9df318f7551605fc519475d4bc8940375078d922 | [] | no_license | NeuraxWorm/P | da9c5573c105876f7f61d82a998293041e273fa4 | aa2cbd902d2363e126fb1b134da1d77daa9e83f0 | refs/heads/master | 2021-01-01T11:35:11.342717 | 2017-07-18T08:24:29 | 2017-07-18T08:24:29 | 97,572,981 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 941 | cpp | #include "CircularTower.h"
CircularTower::CircularTower() {}
CircularTower::~CircularTower() {}
void CircularTower::Render()
{
if (!mPlaced)
{
return;
}
// render turret
const int tWidth = mTurretSprite.GetWidth();
const int tHeight = mTurretSprite.GetHeight();
SVector2 renderPos;
renderPos.x = mPosition.x - (tWidth * 0.5f);
renderPos.y = mPosition.y - (tHeight * 0.5f);
mTurretSprite.SetPosition(renderPos);
mTurretSprite.SetRotation(mTurretAngle);
mTurretSprite.Render();
mTurretSprite.SetRotation(0.0f);
// render firing sprite once per strike
if (mAttackAnimation > 0.0f)
{
const int bWidth = mFiringSprite.GetWidth();
const int bHeight = mFiringSprite.GetHeight();
renderPos.x = mPosition.x - (tWidth * 0.5f);
renderPos.y = mPosition.y - (tHeight * 0.5f);
mFiringSprite.SetPosition(renderPos);
mFiringSprite.Render();
mFiringSprite.SetRotation(0.0f);
}
} | [
"tzrunm@gmail.com"
] | tzrunm@gmail.com |
340c4879849033a33c1b587fae5b077497c73f50 | 1ad181e5c808ecc2f7cdf6ab35ab6acd36613d2f | /currency_to_word.cpp | d8703b7b9f4e936c16348948e3b2f4e4ed7d06a8 | [] | no_license | shivamp20/CurrencyConversion | 67d08682628e5789088fc4aa2723486a8d29f93f | abb598e0aefb25cb72a9ccb9ad43c9fb6bcc6c04 | refs/heads/master | 2022-11-16T11:24:51.859522 | 2020-07-12T08:13:26 | 2020-07-12T08:13:26 | 279,019,848 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,813 | cpp | /* My program to print a given Amount of Currency in words.
The program handles till 9 digits numbers and
can be easily extended to 20 digit number */
#include <iostream>
#include<cmath>
#include<string>
#include<sstream>
using namespace std;
// Strings at index 0 is not used,For making Array Indexing Easy
string one[] = { "", "One ", "Two ", "Three ", "Four ",
"Five ", "Six ", "Seven ", "Eight ",
"Nine ", "Ten ", "Eleven ", "Twelve ",
"Thirteen ", "Fourteen ", "Fifteen ",
"Sixteen ", "Seventeen ", "Eighteen ",
"Nineteen " };
string ten[] = { "", "", "Twenty ", "Thirty ", "Forty ",
"Fifty ", "Sixty ", "Seventy ", "Eighty ",
"Ninety " };
// Function for Extracting The Decimal Value
int decval(long double n)
{
int num1;
float temp;
int res1;
//logic for seperation of decimal value
num1 = n;
temp = n - num1;
res1 = temp * 100;
return res1;
}
string numToWords(int n, string s)
{
string str = "";
// if n is more than 19, divide it
if (n > 19)
str += ten[n / 10] + one[n % 10];
else
str += one[n];
// if n is non-zero
if (n)
str += s;
return str;
}
// Function to print a given number in words
string convertToWords(long n)
{
// stores word representation of given number n
string out;
if(n == 0)
{
out += "Zero.";
}
//For digits at Ten Millions and Hundred Million Places
out += numToWords((n / 10000000), "Crore ");
//For digits at Hundred Thousands and One Millions Places
out += numToWords(((n / 100000) % 100), "Lakh ");
//For digits at Thousands and Tens Thousands Places
out += numToWords(((n / 1000) % 100), "Thousand ");
// For digit at Hundreds places (if any)
out += numToWords(((n / 100) % 10), "Hundred ");
if (n > 100 && n % 100)
out += "and ";
// For digits at Ones and Tens places (if any)
out += numToWords((n % 100), "");
return out;
}
int main()
{
long double n;
int res;
string str2;
cout<<"Enter the Number: "<<endl;
cin>>n;
if(n>1000000)
{
cout<<"Sorry Can't Handle That big Amount"<<endl;
}
else if(n<0)
{
cout<<"Amount Should Be Greater Than Zero"<<endl;
}
else if(floor(n) == n)
{
cout <<"Rs."<<convertToWords(n)<< endl;
}
else
{ //int to string conversion
res = decval(n);
ostringstream str1;
str1 << res;
str2 = str1.str();
// convert given number in words
cout <<"Rs."<<convertToWords(n)<<str2<<"/100 Only"<< endl;
}
return 0;
}
| [
"shivampandey.pandey8@gmail.com"
] | shivampandey.pandey8@gmail.com |
61b93e994ac875cf7afe1ddf37741ff8974c648a | 0dddcf4c9b98c3c9aceb4e57102461502c298f58 | /EdgeDetection/src/ArrayBuffer.cpp | 86b17ab0253173bffe4c83be0839bb048ac93314 | [] | no_license | mkarier/Thesis | c0d7b7d42e2be13d8caee2933430e4b9057f65b5 | c98bf3120573b187a00a0f8c799b060c9d753d3d | refs/heads/master | 2021-04-15T09:22:57.744677 | 2018-08-17T19:13:15 | 2018-08-17T19:13:15 | 126,725,716 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 827 | cpp | /*
* ArrayBuffer.cpp
*
* Created on: Oct 24, 2017
* Author: marco
*/
#include "ArrayBuffer.h"
void buffArray(Mat& src)
{
int rows = src.rows;
int cols = src.cols;
int type = src.type();
Mat out(rows+1, cols+1, type);
for(int y = 0; y < rows; y++)
{
for(int x = 0; x < cols; x++)
{
out.at<Vec3b>(Point(x,y)) = src.at<Vec3b>(Point(x,y));
}
out.at<Vec3b>(Point(cols,y)).val[0] = '$';
out.at<Vec3b>(Point(cols,y)).val[1] = '$';
out.at<Vec3b>(Point(cols,y)).val[2] = '$';
}//end of for loop
for(int x =0; x < cols + 1; x++)
{
out.at<Vec3b>(Point(x,rows)).val[0] = '$';
out.at<Vec3b>(Point(x,rows)).val[1] = '$';
out.at<Vec3b>(Point(x,rows)).val[2] = '$';
}
src = out;
}//end of buffArray
void buffRows(Mat& src)
{
}//end of buffRows
void buffCols(Mat& src)
{
}//end of buffCols
| [
"mkarier@eagles.ewu.edu"
] | mkarier@eagles.ewu.edu |
c85d3f37dad68ee749b60dba8a306032ffc9ce24 | 939d8e569add7fc5e0fdc3e46a9a3c61d8d19537 | /samples_2016/en/itac/icpf/include/h_container.h | 85c17c3227d8648d8a83013d2edb325d0a78b41a | [] | no_license | jiawen11/OpenCL-OpenMP-Cuda-and-Rodinia | 35fd7ab9b9d49075f7044a5f9a04ede044b681d9 | e809d1fdee12545298ad4cebbf471781e183d1a0 | refs/heads/master | 2021-06-06T12:35:37.100111 | 2016-04-08T20:02:13 | 2016-04-08T20:02:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,179 | h | /*********************************************************************
* Copyright 2003-2014 Intel Corporation.
* All Rights Reserved.
*
* The source code contained or described herein and all documents
* related to the source code ("Material") are owned by Intel
* Corporation or its suppliers or licensors. Title to the Material
* remains with Intel Corporation or its suppliers and licensors. The
* Material contains trade secrets and proprietary and confidential
* information of Intel or its suppliers and licensors. The Material
* is protected by worldwide copyright and trade secret laws and
* treaty provisions. No part of the Material may be used, copied,
* reproduced, modified, published, uploaded, posted, transmitted,
* distributed, or disclosed in any way without Intel's prior express
* written permission.
*
* No license under any patent, copyright, trade secret or other
* intellectual property right is granted to or conferred upon you by
* disclosure or delivery of the Materials, either expressly, by
* implication, inducement, estoppel or otherwise. Any license under
* such intellectual property rights must be express and approved by
* Intel in writing.
*
*********************************************************************/
#ifndef _H_CONTAINER_H_
#define _H_CONTAINER_H_
template< class T >
class Container
{
public:
/// get first element in container
/// to nest lopps, increase nesting level _level_ for each loop
/// @param _level_ nesting level for loop, default: 0
/// @return const pointer to first element, 0 if empty
virtual const T* first( int _level_ = 0 ) const = 0;
/// get next element in container for loops started with a call to first
/// to nest lopps, increase nesting level _level_ for each loop
/// @param _level_ nesting level for loop, corresponds to _level_ passed to first, default: 0
/// @return const pointer to next element, 0 if no further element
virtual const T* next( int _level_ = 0 ) const = 0;
///
/// @return the number of elements in the container
virtual unsigned int count( void ) const = 0;
virtual ~Container() {}
};
#endif
| [
"gentle.kevin1991@gmail.com"
] | gentle.kevin1991@gmail.com |
38d1e50d75adf92f0e5f53b004b9c848f7991d89 | bc84fd85c8b1ba4076023aa0e0e2f3c3b598cd1b | /include/items/bushes.hpp | 53e1732a0e7edfd640c42eaef83ef6d42a9e06a6 | [] | no_license | lduane2/ndzork | d44b549e0e2220c636eb9098c2ae098ec67bf5bc | 767d5aee41d349ce611e3f6f9b18747a230fb911 | refs/heads/master | 2021-04-27T01:09:00.543477 | 2018-03-13T17:28:42 | 2018-03-13T17:28:42 | 122,667,993 | 0 | 1 | null | 2018-03-01T16:29:54 | 2018-02-23T20:13:24 | C++ | UTF-8 | C++ | false | false | 478 | hpp | #ifndef ITEM_BUSHES_HPP
#define ITEM_BUSHES_HPP
#include "item.hpp"
#include "../command.hpp"
class Bushes : public Item {
public:
Bushes();
std::string get_name();
std::string get_full_name();
std::string get_descr();
bool is_takeable();
bool can_contain_items();
bool handle(Command command);
private:
std::string name = "bushes";
std::string full_name = "hedge of bushes";
std::string descr = "The bushes are neatly trimmed.";
bool look(Command c);
};
#endif
| [
"conradbailey92@gmail.com"
] | conradbailey92@gmail.com |
9b4cccb3f2ce96e15cbe09974ef52a87ae208284 | 6d2587c6c7edfb27b6dbe0257cd0a1400d11cca3 | /modules/planning/tasks/smoothers/smoother.h | 3d3105bf8e1849a16640466dd3e91967c6b50e90 | [
"Apache-2.0"
] | permissive | lianglia-apollo/apollo | 192956a21690f22382329a8112a5b3d7aa9e3dd7 | 64b84c48fba9963c9c4e119a8902d33b2a5e439b | refs/heads/master | 2021-07-08T10:55:02.052648 | 2019-01-07T18:14:23 | 2019-01-07T18:31:13 | 96,257,983 | 6 | 2 | Apache-2.0 | 2018-07-10T18:16:49 | 2017-07-04T22:55:38 | C++ | UTF-8 | C++ | false | false | 1,462 | h | /******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#pragma once
#include "modules/common/status/status.h"
#include "modules/common/vehicle_state/proto/vehicle_state.pb.h"
#include "modules/planning/common/frame.h"
#include "modules/planning/proto/decision.pb.h"
namespace apollo {
namespace planning {
class Smoother {
public:
Smoother() = default;
virtual ~Smoother() = default;
apollo::common::Status Smooth(
const FrameHistory* frame_history,
const Frame* current_frame,
ADCTrajectory* const current_trajectory_pb);
private:
bool IsCloseStop(const common::VehicleState& vehicle_state,
const MainStop& main_stop);
};
} // namespace planning
} // namespace apollo
| [
"hujiangtao@baidu.com"
] | hujiangtao@baidu.com |
51176a1128f34284e0aa42b03eaba9fd87d60e6c | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/net/config/netcfg/tcpipcfg/dlgdns.h | 3319d00ceb3fd2db7ceac92f2dae9a15fc8353bd | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 9,520 | h | //-----------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1997.
//
// File: T C P D N S . H
//
// Contents: CTcpDnsPage, CServerDialog and CSuffixDialog declaration
//
// Notes: The DNS page and related dialogs
//
// Author: tongl 11 Nov 1997
//
//-----------------------------------------------------------------------
#pragma once
#include <ncxbase.h>
#include <ncatlps.h>
#include "ipctrl.h"
// maximum number of characters in the suffix edit control
const int SUFFIX_LIMIT = 255;
//maximum length of domain name
const int DOMAIN_LIMIT = 255;
class CTcpDnsPage : public CPropSheetPage
{
public:
// Declare the message map
BEGIN_MSG_MAP(CTcpDnsPage)
// Initialize dialog
MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
MESSAGE_HANDLER(WM_CONTEXTMENU, OnContextMenu)
MESSAGE_HANDLER(WM_HELP, OnHelp)
// Property page notification message handlers
NOTIFY_CODE_HANDLER(PSN_APPLY, OnApply)
NOTIFY_CODE_HANDLER(PSN_KILLACTIVE, OnKillActive)
NOTIFY_CODE_HANDLER(PSN_SETACTIVE, OnActive)
NOTIFY_CODE_HANDLER(PSN_RESET, OnCancel)
// Control message handlers
// Push button message handlers
COMMAND_ID_HANDLER(IDC_DNS_SERVER_ADD, OnAddServer)
COMMAND_ID_HANDLER(IDC_DNS_SERVER_EDIT, OnEditServer)
COMMAND_ID_HANDLER(IDC_DNS_SERVER_REMOVE, OnRemoveServer)
COMMAND_ID_HANDLER(IDC_DNS_SERVER_UP, OnServerUp)
COMMAND_ID_HANDLER(IDC_DNS_SERVER_DOWN, OnServerDown)
COMMAND_ID_HANDLER(IDC_DNS_DOMAIN, OnDnsDomain)
COMMAND_ID_HANDLER(IDC_DNS_SEARCH_DOMAIN, OnSearchDomain)
COMMAND_ID_HANDLER(IDC_DNS_SEARCH_PARENT_DOMAIN, OnSearchParentDomain)
COMMAND_ID_HANDLER(IDC_DNS_USE_SUFFIX_LIST, OnUseSuffix)
COMMAND_ID_HANDLER(IDC_DNS_ADDR_REG, OnAddressRegister)
COMMAND_ID_HANDLER(IDC_DNS_NAME_REG, OnDomainNameRegister)
COMMAND_ID_HANDLER(IDC_DNS_SUFFIX_ADD, OnAddSuffix)
COMMAND_ID_HANDLER(IDC_DNS_SUFFIX_EDIT, OnEditSuffix)
COMMAND_ID_HANDLER(IDC_DNS_SUFFIX_REMOVE, OnRemoveSuffix)
COMMAND_ID_HANDLER(IDC_DNS_SUFFIX_UP, OnSuffixUp)
COMMAND_ID_HANDLER(IDC_DNS_SUFFIX_DOWN, OnSuffixDown)
// Notification handlers
COMMAND_ID_HANDLER(IDC_DNS_SERVER_LIST, OnServerList)
COMMAND_ID_HANDLER(IDC_DNS_SUFFIX_LIST, OnSuffixList)
END_MSG_MAP()
// Constructors/Destructors
CTcpDnsPage(CTcpAddrPage * pTcpAddrPage,
ADAPTER_INFO * pAdapterDlg,
GLOBAL_INFO * pGlbDlg,
const DWORD * adwHelpIDs = NULL);
~CTcpDnsPage();
// Interface
public:
// message map functions
LRESULT OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& fHandled);
LRESULT OnContextMenu(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& fHandled);
LRESULT OnHelp(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& fHandled);
// notify handlers for the property page
LRESULT OnApply(int idCtrl, LPNMHDR pnmh, BOOL& fHandled);
LRESULT OnKillActive(int idCtrl, LPNMHDR pnmh, BOOL& fHandled);
LRESULT OnActive(int idCtrl, LPNMHDR pnmh, BOOL& fHandled);
LRESULT OnCancel(int idCtrl, LPNMHDR pnmh, BOOL& fHandled);
// DNS server list
LRESULT OnAddServer(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled);
LRESULT OnEditServer(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled);
LRESULT OnRemoveServer(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled);
LRESULT OnServerUp(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled);
LRESULT OnServerDown(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled);
// DNS domain
LRESULT OnDnsDomain(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled);
// Search order radio buttons
LRESULT OnSearchDomain(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled);
LRESULT OnSearchParentDomain(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled);
LRESULT OnUseSuffix(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled);
// DNS suffix list
LRESULT OnAddSuffix(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled);
LRESULT OnEditSuffix(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled);
LRESULT OnRemoveSuffix(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled);
LRESULT OnSuffixUp(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled);
LRESULT OnSuffixDown(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled);
LRESULT OnServerList(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled);
LRESULT OnSuffixList(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled);
// ip address and name dynamic registration
LRESULT OnAddressRegister(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled);
LRESULT OnDomainNameRegister(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled);
// Handlers
public:
void OnServerChange();
void OnSuffixChange();
// Attributes
public:
tstring m_strNewIpAddress; // server: either the one added, or edited
tstring m_strNewSuffix;
// server: used as work space for moving entries in the listboxes
tstring m_strMovingEntry;
tstring m_strAddServer; // OK or Add button server dialog
tstring m_strAddSuffix; // OK or Add button suffix dialog
BOOL m_fEditState;
HANDLES m_hServers;
HANDLES m_hSuffix;
private:
CTcpAddrPage * m_pParentDlg;
ADAPTER_INFO * m_pAdapterInfo;
GLOBAL_INFO * m_pglb;
BOOL m_fModified;
const DWORD* m_adwHelpIDs;
// Inlines
BOOL IsModified() {return m_fModified;}
void SetModifiedTo(BOOL bState) {m_fModified = bState;}
void PageModified() { m_fModified = TRUE; PropSheet_Changed(GetParent(), m_hWnd);}
// help functions
void EnableSuffixGroup(BOOL fEnable);
};
class CServerDialog : public CDialogImpl<CServerDialog>
{
public:
enum { IDD = IDD_DNS_SERVER };
BEGIN_MSG_MAP(CServerDialog)
MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog);
MESSAGE_HANDLER(WM_CONTEXTMENU, OnContextMenu);
MESSAGE_HANDLER(WM_HELP, OnHelp);
MESSAGE_HANDLER(WM_SETCURSOR, OnSetCursor);
COMMAND_ID_HANDLER(IDOK, OnOk);
COMMAND_ID_HANDLER(IDCANCEL, OnCancel);
COMMAND_ID_HANDLER(IDC_DNS_CHANGE_SERVER, OnChange);
NOTIFY_CODE_HANDLER(IPN_FIELDCHANGED, OnIpFieldChange)
END_MSG_MAP()
public:
CServerDialog(CTcpDnsPage * pTcpDnsPage, const DWORD* pamhidsHelp = NULL, int iIndex = -1);
~CServerDialog(){};
LRESULT OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& fHandled);
LRESULT OnContextMenu(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& fHandled);
LRESULT OnHelp(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& fHandled);
LRESULT OnSetCursor(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& fHandled);
LRESULT OnOk(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled);
LRESULT OnCancel(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled);
LRESULT OnChange(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled);
LRESULT OnIpFieldChange(int idCtrl, LPNMHDR pnmh, BOOL& fHandled);
// Dialog creation overides
public:
IpControl m_ipAddress;
private:
HWND m_hButton; // this is the IDOK button, the text of the button changes
// with the context.
CTcpDnsPage * m_pParentDlg;
const DWORD * m_adwHelpIDs;
int m_iIndex;
};
class CSuffixDialog : public CDialogImpl<CSuffixDialog>
{
public:
enum { IDD = IDD_DNS_SUFFIX };
BEGIN_MSG_MAP(CSuffixDialog)
MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog);
MESSAGE_HANDLER(WM_CONTEXTMENU, OnContextMenu);
MESSAGE_HANDLER(WM_HELP, OnHelp);
MESSAGE_HANDLER(WM_SETCURSOR, OnSetCursor);
COMMAND_ID_HANDLER(IDOK, OnOk);
COMMAND_ID_HANDLER(IDCANCEL, OnCancel);
COMMAND_ID_HANDLER(IDC_DNS_CHANGE_SUFFIX, OnChange);
END_MSG_MAP()
//
public:
CSuffixDialog(CTcpDnsPage * pTcpDnsPage, const DWORD* pamhidsHelp = NULL, int iIndex = -1);
~CSuffixDialog(){};
LRESULT OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& fHandled);
LRESULT OnContextMenu(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& fHandled);
LRESULT OnHelp(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& fHandled);
LRESULT OnSetCursor(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& fHandled);
LRESULT OnOk(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled);
LRESULT OnCancel(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled);
LRESULT OnChange(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& fHandled);
private:
HWND m_hEdit; //
HWND m_hButton; // this is the IDOK button, the text of the button changes
// with the context.
CTcpDnsPage * m_pParentDlg;
const DWORD * m_adwHelpIDs;
int m_iIndex;
};
| [
"seta7D5@protonmail.com"
] | seta7D5@protonmail.com |
a3f791fd28ef0375476754c4a75a93d79a91120f | 96f9057a63c385043e31afe7fb33f46bf19ce45b | /datasets/gen_csr.cpp | 8c641d8d9feb2a2573a131b827f7847393889697 | [] | no_license | owensgroup/ATOS | 48f186690f51d1a84da8611dbf32bb25290e16bf | e11b724416cafce313bf57e897c176cbe6db852c | refs/heads/main | 2023-08-05T05:14:48.422336 | 2023-07-23T07:32:29 | 2023-07-23T07:38:25 | 501,874,892 | 25 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,749 | cpp | #include <iostream>
#include <string>
#include "csr.cuh"
using namespace std;
int main(int argc, char *argv[])
{
char *input_file = NULL;
bool start_from_0 = false;
bool directed = true;
bool ifvalid = false;
if(argc == 1)
{
cout<< "./test -f <file> -s <file vertex ID start from 0?=false> -d <if graph is directed=directed> -valid <if validate the generated csr file>\n";
exit(0);
}
if(argc > 1)
for(int i=1; i<argc; i++) {
if(string(argv[i]) == "-f")
input_file = argv[i+1];
else if(string(argv[i]) == "-s")
start_from_0 = stoi(argv[i+1]);
else if(string(argv[i]) == "-d")
directed = stoi(argv[i+1]);
else if(string(argv[i]) == "-valid")
ifvalid = stoi(argv[i+1]);
}
if(input_file == NULL)
{
cout << "input file is needed\n";
cout<< "./test -f <file> -s <file vertex ID start from 0?=false> -d <if graph is directed=directed>\n";
exit(0);
}
std::cout << "file: "<< input_file << " start from 0: " << start_from_0 << " directed? "<< directed << " validate generated file? "<< ifvalid << std::endl;
std::string str_file(input_file);
CSR<int, int> csr(start_from_0, directed);
if(str_file.substr(str_file.length()-4) == ".mtx")
{
csr.BuildFromMtx(input_file);
csr.Print();
// csr.PrintCSR();
csr.WriteToBinary(input_file);
cout << "Start to write to binary file\n";
if(ifvalid) {
bool res = csr.ValidWithMtx(input_file);
if(!res) std::cout <<"Validation fail\n";
if(!res) exit(1);
cout << "PASS Validation\n";
}
}
return 0;
}
| [
"yxxchen@ucdavis.edu"
] | yxxchen@ucdavis.edu |
228dd093b4b3bb04dcd2cb874c4e6d66f65cc20b | 6717142162a4f06640291cd9b5651af86043d103 | /content/browser/indexed_db/leveldb/transactional_leveldb_transaction_unittest.cc | baac7c913680e942c4b60b31fcc03891eb4d84d3 | [
"BSD-3-Clause"
] | permissive | Sharp-Rock/chromium | ad82f1be0ba36563dfab380071b8520c7c39d89a | 239aaf3cc8a338de2c668e5b9170d37b0848a238 | refs/heads/master | 2023-02-25T08:29:01.592526 | 2019-09-11T12:31:58 | 2019-09-11T12:31:58 | 207,808,804 | 0 | 0 | BSD-3-Clause | 2019-09-11T12:37:41 | 2019-09-11T12:37:41 | null | UTF-8 | C++ | false | false | 28,815 | cc | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/indexed_db/leveldb/transactional_leveldb_transaction.h"
#include <stddef.h>
#include <algorithm>
#include <cstring>
#include <memory>
#include <string>
#include "base/files/file.h"
#include "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
#include "base/no_destructor.h"
#include "base/strings/string_piece.h"
#include "base/test/bind_test_util.h"
#include "content/browser/indexed_db/leveldb/leveldb_env.h"
#include "content/browser/indexed_db/leveldb/transactional_leveldb_database.h"
#include "content/browser/indexed_db/leveldb/transactional_leveldb_iterator.h"
#include "content/browser/indexed_db/scopes/disjoint_range_lock_manager.h"
#include "content/browser/indexed_db/scopes/leveldb_scope.h"
#include "content/browser/indexed_db/scopes/leveldb_scopes.h"
#include "content/browser/indexed_db/scopes/leveldb_scopes_test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/leveldatabase/env_chromium.h"
#include "third_party/leveldatabase/src/include/leveldb/comparator.h"
namespace content {
namespace {
static const size_t kTestingMaxOpenCursors = 3;
} // namespace
class TransactionalLevelDBTransactionTest : public LevelDBScopesTestBase {
public:
TransactionalLevelDBTransactionTest() {}
void TearDown() override {
leveldb_database_.reset();
LevelDBScopesTestBase::TearDown();
}
protected:
void SetupLevelDBDatabase() {
ASSERT_TRUE(leveldb_);
std::unique_ptr<LevelDBScopes> scopes_system =
std::make_unique<LevelDBScopes>(
metadata_prefix_, kWriteBatchSizeForTesting, leveldb_,
&lock_manager_,
base::BindLambdaForTesting(
[this](leveldb::Status s) { this->failure_status_ = s; }));
leveldb::Status s = scopes_system->Initialize();
ASSERT_TRUE(s.ok()) << s.ToString();
scopes_system->StartRecoveryAndCleanupTasks(
LevelDBScopes::TaskRunnerMode::kNewCleanupAndRevertSequences);
leveldb_database_ = leveldb_factory_->CreateLevelDBDatabase(
leveldb_, std::move(scopes_system),
base::SequencedTaskRunnerHandle::Get(), kTestingMaxOpenCursors);
}
std::vector<ScopeLock> AcquireLocksSync(
ScopesLockManager* lock_manager,
base::flat_set<ScopesLockManager::ScopeLockRequest> lock_requests) {
base::RunLoop loop;
ScopesLocksHolder locks_receiver;
bool success = lock_manager->AcquireLocks(
lock_requests, locks_receiver.AsWeakPtr(),
base::BindLambdaForTesting([&loop]() { loop.Quit(); }));
EXPECT_TRUE(success);
if (success)
loop.Run();
return std::move(locks_receiver.locks);
}
// Convenience methods to access the database outside any
// transaction to cut down on boilerplate around calls.
void Put(const base::StringPiece& key, const std::string& value) {
std::string put_value = value;
leveldb::Status s = leveldb_database_->Put(key, &put_value);
ASSERT_TRUE(s.ok());
}
void Get(const base::StringPiece& key, std::string* value, bool* found) {
leveldb::Status s = leveldb_database_->Get(key, value, found);
ASSERT_TRUE(s.ok());
}
bool Has(const base::StringPiece& key) {
bool found;
std::string value;
leveldb::Status s = leveldb_database_->Get(key, &value, &found);
EXPECT_TRUE(s.ok());
return found;
}
// Convenience wrappers for LevelDBTransaction operations to
// avoid boilerplate in tests.
bool TransactionHas(TransactionalLevelDBTransaction* transaction,
const base::StringPiece& key) {
std::string value;
bool found;
leveldb::Status s = transaction->Get(key, &value, &found);
EXPECT_TRUE(s.ok());
return found;
}
void TransactionPut(TransactionalLevelDBTransaction* transaction,
const base::StringPiece& key,
const std::string& value) {
std::string put_value = value;
leveldb::Status s = transaction->Put(key, &put_value);
EXPECT_TRUE(s.ok());
}
void TransactionRemove(TransactionalLevelDBTransaction* transaction,
const base::StringPiece& key) {
leveldb::Status s = transaction->Remove(key);
ASSERT_TRUE(s.ok());
}
int Compare(const base::StringPiece& a, const base::StringPiece& b) const {
return leveldb_database_->leveldb_state()->comparator()->Compare(
leveldb_env::MakeSlice(a), leveldb_env::MakeSlice(b));
}
bool KeysEqual(const base::StringPiece& a, const base::StringPiece& b) const {
return Compare(a, b) == 0;
}
TransactionalLevelDBDatabase* db() { return leveldb_database_.get(); }
scoped_refptr<TransactionalLevelDBTransaction> CreateTransaction() {
return indexed_db::LevelDBFactory::Get()->CreateLevelDBTransaction(
db(),
db()->scopes()->CreateScope(
AcquireLocksSync(&lock_manager_, {CreateSimpleSharedLock()}), {}));
}
leveldb::Status failure_status_;
private:
std::unique_ptr<TransactionalLevelDBDatabase> leveldb_database_;
DisjointRangeLockManager lock_manager_ = {3};
DISALLOW_COPY_AND_ASSIGN(TransactionalLevelDBTransactionTest);
};
TEST_F(TransactionalLevelDBTransactionTest, GetPutDelete) {
SetUpRealDatabase();
SetupLevelDBDatabase();
leveldb::Status status;
const std::string key("key");
std::string got_value;
const std::string value("value");
Put(key, value);
bool found = false;
Get(key, &got_value, &found);
EXPECT_TRUE(found);
EXPECT_EQ(Compare(got_value, value), 0);
scoped_refptr<TransactionalLevelDBTransaction> transaction =
CreateTransaction();
status = transaction->Get(key, &got_value, &found);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(found);
EXPECT_EQ(Compare(got_value, value), 0);
const std::string added_key("b-added key");
const std::string added_value("b-added value");
Put(added_key, added_value);
Get(added_key, &got_value, &found);
EXPECT_TRUE(found);
EXPECT_EQ(Compare(got_value, added_value), 0);
EXPECT_TRUE(TransactionHas(transaction.get(), added_key));
const std::string another_key("b-another key");
const std::string another_value("b-another value");
EXPECT_EQ(12ull, transaction->GetTransactionSize());
TransactionPut(transaction.get(), another_key, another_value);
EXPECT_EQ(43ull, transaction->GetTransactionSize());
status = transaction->Get(another_key, &got_value, &found);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(found);
EXPECT_EQ(Compare(got_value, another_value), 0);
TransactionRemove(transaction.get(), another_key);
EXPECT_EQ(136ull, transaction->GetTransactionSize());
status = transaction->Get(another_key, &got_value, &found);
EXPECT_FALSE(found);
}
TEST_F(TransactionalLevelDBTransactionTest, Iterator) {
SetUpRealDatabase();
SetupLevelDBDatabase();
const std::string key1("b-key1");
const std::string value1("value1");
const std::string key2("b-key2");
const std::string value2("value2");
Put(key1, value1);
Put(key2, value2);
scoped_refptr<TransactionalLevelDBTransaction> transaction =
CreateTransaction();
std::unique_ptr<TransactionalLevelDBIterator> it =
transaction->CreateIterator();
it->Seek(std::string("b"));
ASSERT_TRUE(it->IsValid());
EXPECT_EQ(Compare(it->Key(), key1), 0) << it->Key() << ", " << key1;
EXPECT_EQ(Compare(it->Value(), value1), 0);
it->Next();
ASSERT_TRUE(it->IsValid());
EXPECT_EQ(Compare(it->Key(), key2), 0);
EXPECT_EQ(Compare(it->Value(), value2), 0);
it->Next();
EXPECT_FALSE(it->IsValid());
}
TEST_F(TransactionalLevelDBTransactionTest, Commit) {
SetUpRealDatabase();
SetupLevelDBDatabase();
const std::string key1("b-key1");
const std::string key2("b-key2");
const std::string value1("value1");
const std::string value2("value2");
const std::string value3("value3");
std::string got_value;
bool found;
scoped_refptr<TransactionalLevelDBTransaction> transaction =
CreateTransaction();
TransactionPut(transaction.get(), key1, value1);
TransactionPut(transaction.get(), key2, value2);
TransactionPut(transaction.get(), key2, value3);
leveldb::Status status = transaction->Commit(/*sync_on_commit=*/false);
EXPECT_TRUE(status.ok());
Get(key1, &got_value, &found);
EXPECT_TRUE(found);
EXPECT_EQ(value1, got_value);
Get(key2, &got_value, &found);
EXPECT_TRUE(found);
EXPECT_EQ(value3, got_value);
}
TEST_F(TransactionalLevelDBTransactionTest, IterationWithEvictedCursors) {
SetUpRealDatabase();
SetupLevelDBDatabase();
leveldb::Status status;
Put("b-key1", "value1");
Put("b-key2", "value2");
Put("b-key3", "value3");
scoped_refptr<TransactionalLevelDBTransaction> transaction =
CreateTransaction();
std::unique_ptr<TransactionalLevelDBIterator> evicted_normal_location =
transaction->CreateIterator();
std::unique_ptr<TransactionalLevelDBIterator> evicted_before_start =
transaction->CreateIterator();
std::unique_ptr<TransactionalLevelDBIterator> evicted_after_end =
transaction->CreateIterator();
std::unique_ptr<TransactionalLevelDBIterator> it1 =
transaction->CreateIterator();
std::unique_ptr<TransactionalLevelDBIterator> it2 =
transaction->CreateIterator();
std::unique_ptr<TransactionalLevelDBIterator> it3 =
transaction->CreateIterator();
evicted_normal_location->Seek("b-key1");
evicted_before_start->Seek("b-key1");
evicted_before_start->Prev();
evicted_after_end->SeekToLast();
evicted_after_end->Next();
EXPECT_FALSE(evicted_before_start->IsValid());
EXPECT_TRUE(evicted_normal_location->IsValid());
EXPECT_FALSE(evicted_after_end->IsValid());
// Nothing is purged, as we just have 3 iterators used.
EXPECT_FALSE(evicted_normal_location->IsEvicted());
EXPECT_FALSE(evicted_before_start->IsEvicted());
EXPECT_FALSE(evicted_after_end->IsEvicted());
// Should purge all of our earlier iterators.
status = it1->Seek("b-key1");
EXPECT_TRUE(status.ok());
status = it2->Seek("b-key2");
EXPECT_TRUE(status.ok());
status = it3->Seek("b-key3");
EXPECT_TRUE(status.ok());
EXPECT_TRUE(evicted_normal_location->IsEvicted());
EXPECT_TRUE(evicted_before_start->IsEvicted());
EXPECT_TRUE(evicted_after_end->IsEvicted());
EXPECT_FALSE(evicted_before_start->IsValid());
EXPECT_TRUE(evicted_normal_location->IsValid());
EXPECT_FALSE(evicted_after_end->IsValid());
// Check we don't need to reload for just the key.
EXPECT_EQ("b-key1", evicted_normal_location->Key());
EXPECT_TRUE(evicted_normal_location->IsEvicted());
// Make sure iterators are reloaded correctly.
EXPECT_TRUE(evicted_normal_location->IsValid());
EXPECT_EQ("value1", evicted_normal_location->Value());
// The iterator isn't reloaded because it caches the value.
EXPECT_TRUE(evicted_normal_location->IsEvicted());
status = evicted_normal_location->Next();
EXPECT_TRUE(status.ok());
EXPECT_FALSE(evicted_normal_location->IsEvicted());
EXPECT_FALSE(evicted_before_start->IsValid());
EXPECT_FALSE(evicted_after_end->IsValid());
// And our |Value()| call purged the earlier iterator.
EXPECT_TRUE(it1->IsEvicted());
}
TEST_F(TransactionalLevelDBTransactionTest, IteratorReloadingNext) {
SetUpRealDatabase();
SetupLevelDBDatabase();
const std::string key1("b-key1");
const std::string key2("b-key2");
const std::string key3("b-key3");
const std::string key4("b-key4");
const std::string value("value");
Put(key1, value);
Put(key2, value);
Put(key3, value);
scoped_refptr<TransactionalLevelDBTransaction> transaction =
CreateTransaction();
std::unique_ptr<TransactionalLevelDBIterator> it =
transaction->CreateIterator();
it->Seek(std::string("b"));
ASSERT_TRUE(it->IsValid());
EXPECT_EQ(Compare(it->Key(), key1), 0) << it->Key() << ", " << key1;
// Remove key2, so the next key should be key3.
TransactionRemove(transaction.get(), key2);
it->Next();
ASSERT_TRUE(it->IsValid());
EXPECT_EQ(Compare(it->Key(), key3), 0) << it->Key() << ", " << key3;
// Add key4.
TransactionPut(transaction.get(), key4, value);
it->Next();
ASSERT_TRUE(it->IsValid());
EXPECT_EQ(Compare(it->Key(), key4), 0) << it->Key() << ", " << key4;
}
TEST_F(TransactionalLevelDBTransactionTest, IteratorReloadingPrev) {
SetUpRealDatabase();
SetupLevelDBDatabase();
const std::string key1("b-key1");
const std::string key2("b-key2");
const std::string key3("b-key3");
const std::string key4("b-key4");
const std::string value("value");
Put(key2, value);
Put(key3, value);
Put(key4, value);
scoped_refptr<TransactionalLevelDBTransaction> transaction =
CreateTransaction();
std::unique_ptr<TransactionalLevelDBIterator> it =
transaction->CreateIterator();
it->SeekToLast();
ASSERT_TRUE(it->IsValid());
EXPECT_EQ(Compare(it->Key(), key4), 0) << it->Key() << ", " << key4;
// Remove key3, so the prev key should be key2.
TransactionRemove(transaction.get(), key3);
it->Prev();
ASSERT_TRUE(it->IsValid());
EXPECT_EQ(Compare(it->Key(), key2), 0) << it->Key() << ", " << key2;
// Add key1.
TransactionPut(transaction.get(), key1, value);
it->Prev();
ASSERT_TRUE(it->IsValid());
EXPECT_EQ(Compare(it->Key(), key1), 0) << it->Key() << ", " << key1;
}
TEST_F(TransactionalLevelDBTransactionTest, IteratorSkipsScopesMetadata) {
SetUpRealDatabase();
SetupLevelDBDatabase();
const std::string key1("b-key1");
const std::string pre_key("0");
const std::string value("value");
Put(key1, value);
scoped_refptr<TransactionalLevelDBTransaction> transaction =
CreateTransaction();
std::unique_ptr<TransactionalLevelDBIterator> it =
transaction->CreateIterator();
// Should skip metadata, and go to key1.
it->Seek("");
ASSERT_TRUE(it->IsValid());
EXPECT_EQ(Compare(it->Key(), key1), 0) << it->Key() << ", " << key1;
// Should skip metadata, and go to the beginning.
it->Prev();
ASSERT_FALSE(it->IsValid());
TransactionRemove(transaction.get(), key1);
TransactionPut(transaction.get(), pre_key, value);
it->SeekToLast();
ASSERT_TRUE(it->IsValid());
EXPECT_EQ(Compare(it->Key(), pre_key), 0) << it->Key() << ", " << pre_key;
}
TEST_F(TransactionalLevelDBTransactionTest, IteratorReflectsInitialChanges) {
SetUpRealDatabase();
SetupLevelDBDatabase();
const std::string key1("b-key1");
const std::string value("value");
scoped_refptr<TransactionalLevelDBTransaction> transaction =
CreateTransaction();
TransactionPut(transaction.get(), key1, value);
std::unique_ptr<TransactionalLevelDBIterator> it =
transaction->CreateIterator();
it->Seek("");
ASSERT_TRUE(it->IsValid());
EXPECT_EQ(Compare(it->Key(), key1), 0) << it->Key() << ", " << key1;
}
namespace {
enum RangePrepareMode {
DataInMemory,
DataInDatabase,
DataMixed,
};
} // namespace
class LevelDBTransactionRangeTest
: public TransactionalLevelDBTransactionTest,
public testing::WithParamInterface<RangePrepareMode> {
public:
LevelDBTransactionRangeTest() {}
void SetUp() override {
TransactionalLevelDBTransactionTest::SetUp();
SetUpRealDatabase();
SetupLevelDBDatabase();
switch (GetParam()) {
case DataInMemory:
transaction_ = CreateTransaction();
TransactionPut(transaction_.get(), key_before_range_, value_);
TransactionPut(transaction_.get(), range_start_, value_);
TransactionPut(transaction_.get(), key_in_range1_, value_);
TransactionPut(transaction_.get(), key_in_range2_, value_);
TransactionPut(transaction_.get(), range_end_, value_);
TransactionPut(transaction_.get(), key_after_range_, value_);
break;
case DataInDatabase:
Put(key_before_range_, value_);
Put(range_start_, value_);
Put(key_in_range1_, value_);
Put(key_in_range2_, value_);
Put(range_end_, value_);
Put(key_after_range_, value_);
transaction_ = CreateTransaction();
break;
case DataMixed:
Put(key_before_range_, value_);
Put(key_in_range1_, value_);
Put(range_end_, value_);
transaction_ = CreateTransaction();
TransactionPut(transaction_.get(), range_start_, value_);
TransactionPut(transaction_.get(), key_in_range2_, value_);
TransactionPut(transaction_.get(), key_after_range_, value_);
break;
}
}
protected:
const std::string key_before_range_ = "b1";
const std::string range_start_ = "b2";
const std::string key_in_range1_ = "b3";
const std::string key_in_range2_ = "b4";
const std::string range_end_ = "b5";
const std::string key_after_range_ = "b6";
const std::string value_ = "value";
scoped_refptr<TransactionalLevelDBTransaction> transaction_;
private:
DISALLOW_COPY_AND_ASSIGN(LevelDBTransactionRangeTest);
};
TEST_P(LevelDBTransactionRangeTest, RemoveRangeUpperClosed) {
leveldb::Status status;
status = transaction_->RemoveRange(
range_start_, range_end_,
LevelDBScopeDeletionMode::kImmediateWithRangeEndInclusive);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(TransactionHas(transaction_.get(), key_before_range_));
EXPECT_FALSE(TransactionHas(transaction_.get(), range_start_));
EXPECT_FALSE(TransactionHas(transaction_.get(), key_in_range1_));
EXPECT_FALSE(TransactionHas(transaction_.get(), key_in_range2_));
EXPECT_FALSE(TransactionHas(transaction_.get(), range_end_));
EXPECT_TRUE(TransactionHas(transaction_.get(), key_after_range_));
status = transaction_->Commit(/*sync_on_commit=*/false);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(Has(key_before_range_));
EXPECT_FALSE(Has(range_start_));
EXPECT_FALSE(Has(key_in_range1_));
EXPECT_FALSE(Has(key_in_range2_));
EXPECT_FALSE(Has(range_end_));
EXPECT_TRUE(Has(key_after_range_));
}
TEST_P(LevelDBTransactionRangeTest, RemoveRangeUpperOpen) {
leveldb::Status status;
status = transaction_->RemoveRange(
range_start_, range_end_,
LevelDBScopeDeletionMode::kImmediateWithRangeEndExclusive);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(TransactionHas(transaction_.get(), key_before_range_));
EXPECT_FALSE(TransactionHas(transaction_.get(), range_start_));
EXPECT_FALSE(TransactionHas(transaction_.get(), key_in_range1_));
EXPECT_FALSE(TransactionHas(transaction_.get(), key_in_range2_));
EXPECT_TRUE(TransactionHas(transaction_.get(), range_end_));
EXPECT_TRUE(TransactionHas(transaction_.get(), key_after_range_));
status = transaction_->Commit(/*sync_on_commit=*/false);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(Has(key_before_range_));
EXPECT_FALSE(Has(range_start_));
EXPECT_FALSE(Has(key_in_range1_));
EXPECT_FALSE(Has(key_in_range2_));
EXPECT_TRUE(Has(range_end_));
EXPECT_TRUE(Has(key_after_range_));
}
TEST_P(LevelDBTransactionRangeTest, RemoveRangeIteratorRetainsKey) {
leveldb::Status status;
std::unique_ptr<TransactionalLevelDBIterator> it =
transaction_->CreateIterator();
status = it->Seek(key_in_range1_);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(it->IsValid());
EXPECT_EQ(Compare(key_in_range1_, it->Key()), 0);
status = it->Next();
EXPECT_TRUE(status.ok());
EXPECT_TRUE(it->IsValid());
EXPECT_EQ(Compare(key_in_range2_, it->Key()), 0);
status = transaction_->RemoveRange(
range_start_, range_end_,
LevelDBScopeDeletionMode::kImmediateWithRangeEndInclusive);
EXPECT_TRUE(status.ok());
ASSERT_TRUE(it->IsValid());
EXPECT_EQ(Compare(key_in_range2_, it->Key()), 0)
<< key_in_range2_ << " != " << it->Key().as_string();
status = it->Next();
EXPECT_TRUE(status.ok());
ASSERT_TRUE(it->IsValid());
EXPECT_EQ(Compare(key_after_range_, it->Key()), 0)
<< key_after_range_ << " != " << it->Key().as_string();
status = transaction_->Commit(/*sync_on_commit=*/false);
EXPECT_TRUE(status.ok());
}
INSTANTIATE_TEST_SUITE_P(LevelDBTransactionRangeTests,
LevelDBTransactionRangeTest,
::testing::Values(DataInMemory,
DataInDatabase,
DataMixed));
TEST_F(TransactionalLevelDBTransactionTest, IteratorValueStaysTheSame) {
SetUpRealDatabase();
SetupLevelDBDatabase();
const std::string key1("b-key1");
const std::string value1("value1");
const std::string value2("value2");
Put(key1, value1);
scoped_refptr<TransactionalLevelDBTransaction> transaction =
CreateTransaction();
std::unique_ptr<TransactionalLevelDBIterator> it =
transaction->CreateIterator();
leveldb::Status s = it->Seek(std::string("b-key1"));
ASSERT_TRUE(it->IsValid());
EXPECT_TRUE(s.ok());
EXPECT_EQ(value1, it->Value());
TransactionPut(transaction.get(), key1, value2);
EXPECT_EQ(value1, it->Value());
it->EvictLevelDBIterator();
EXPECT_EQ(value1, it->Value());
s = it->Seek(std::string("b-key1"));
ASSERT_TRUE(it->IsValid());
EXPECT_TRUE(s.ok());
EXPECT_EQ(value2, it->Value());
}
TEST_F(TransactionalLevelDBTransactionTest, IteratorPutInvalidation) {
SetUpRealDatabase();
SetupLevelDBDatabase();
// This tests edge cases of using 'Put' with an iterator from the same
// transaction in all combinations of these edge cases:
// * 'next' value changes, and we go next,
// * the iterator was detached, and
// * 'prev' value changes and we go back.
const std::string key1("b-key1");
const std::string key2("b-key2");
const std::string key3("b-key3");
const std::string value1("value1");
const std::string value2("value2");
const std::string value3("value3");
Put(key1, value1);
Put(key2, value1);
Put(key3, value1);
scoped_refptr<TransactionalLevelDBTransaction> transaction =
CreateTransaction();
std::unique_ptr<TransactionalLevelDBIterator> it =
transaction->CreateIterator();
leveldb::Status s = it->Seek(std::string("b-key1"));
ASSERT_TRUE(it->IsValid());
EXPECT_TRUE(s.ok());
// Change the 'next' value.
TransactionPut(transaction.get(), key2, value2);
s = it->Next();
ASSERT_TRUE(it->IsValid());
EXPECT_TRUE(s.ok());
EXPECT_TRUE(KeysEqual(it->Key(), key2)) << it->Key() << ", " << key2;
EXPECT_EQ(value2, it->Value());
// Change the 'next' value and Detach.
TransactionPut(transaction.get(), key3, value2);
it->EvictLevelDBIterator();
s = it->Next();
ASSERT_TRUE(it->IsValid());
EXPECT_TRUE(s.ok());
EXPECT_TRUE(KeysEqual(it->Key(), key3)) << it->Key() << ", " << key3;
EXPECT_EQ(value2, it->Value());
// Seek past the end.
s = it->Next();
EXPECT_TRUE(s.ok());
ASSERT_FALSE(it->IsValid());
// Go to the last key (key3).
s = it->SeekToLast();
EXPECT_TRUE(s.ok());
ASSERT_TRUE(it->IsValid());
// Change the 'prev' value.
TransactionPut(transaction.get(), key2, value1);
s = it->Prev();
EXPECT_TRUE(s.ok());
EXPECT_TRUE(KeysEqual(it->Key(), key2)) << it->Key() << ", " << key2;
EXPECT_EQ(value1, it->Value());
// Change the 'prev' value and detach.
TransactionPut(transaction.get(), key1, value1);
it->EvictLevelDBIterator();
s = it->Prev();
EXPECT_TRUE(s.ok());
ASSERT_TRUE(it->IsValid());
EXPECT_TRUE(KeysEqual(it->Key(), key1)) << it->Key() << ", " << key1;
EXPECT_EQ(value1, it->Value());
s = it->Prev();
EXPECT_TRUE(s.ok());
ASSERT_FALSE(it->IsValid());
}
TEST_F(TransactionalLevelDBTransactionTest, IteratorRemoveInvalidation) {
SetUpRealDatabase();
SetupLevelDBDatabase();
// This tests edge cases of using 'Remove' with an iterator from the same
// transaction in all combinations of these edge cases:
// * 'next' key is removed, and we go next
// * the iterator was detached
// * 'prev' key was removed we go back
const std::string key0("b-key0");
const std::string key1("b-key1");
const std::string key2("b-key2");
const std::string key3("b-key3");
const std::string key4("b-key4");
const std::string key5("b-key5");
const std::string value("value");
Put(key0, value);
Put(key1, value);
Put(key2, value);
Put(key3, value);
Put(key4, value);
Put(key5, value);
scoped_refptr<TransactionalLevelDBTransaction> transaction =
CreateTransaction();
std::unique_ptr<TransactionalLevelDBIterator> it =
transaction->CreateIterator();
leveldb::Status s = it->Seek(std::string("b-key1"));
ASSERT_TRUE(it->IsValid());
EXPECT_TRUE(s.ok());
// Remove the 'next' value.
TransactionRemove(transaction.get(), key2);
s = it->Next();
ASSERT_TRUE(it->IsValid());
EXPECT_TRUE(s.ok());
EXPECT_TRUE(KeysEqual(it->Key(), key3)) << it->Key() << ", " << key3;
// Remove the 'next' value and detach.
TransactionRemove(transaction.get(), key4);
it->EvictLevelDBIterator();
s = it->Next();
ASSERT_TRUE(it->IsValid());
EXPECT_TRUE(s.ok());
EXPECT_TRUE(KeysEqual(it->Key(), key5)) << it->Key() << ", " << key5;
// Seek past the end.
s = it->Next();
EXPECT_TRUE(s.ok());
ASSERT_FALSE(it->IsValid());
// Go to the last key (key5).
s = it->SeekToLast();
EXPECT_TRUE(s.ok());
ASSERT_TRUE(it->IsValid());
// Remove the 'prev' value.
TransactionRemove(transaction.get(), key3);
s = it->Prev();
EXPECT_TRUE(s.ok());
EXPECT_TRUE(KeysEqual(it->Key(), key1)) << it->Key() << ", " << key1;
// Remove the 'prev' value and detach.
TransactionRemove(transaction.get(), key1);
it->EvictLevelDBIterator();
s = it->Prev();
EXPECT_TRUE(s.ok());
ASSERT_TRUE(it->IsValid());
EXPECT_TRUE(KeysEqual(it->Key(), key0)) << it->Key() << ", " << key0;
s = it->Prev();
EXPECT_TRUE(s.ok());
ASSERT_FALSE(it->IsValid());
}
TEST_F(TransactionalLevelDBTransactionTest, IteratorGoesInvalidAfterRemove) {
SetUpRealDatabase();
SetupLevelDBDatabase();
// Tests that the iterator correctly goes 'next' or 'prev' to invalid past a
// removed key, and tests that it does the same after being detached.
const std::string key1("b-key1");
const std::string key2("b-key2");
const std::string value("value");
Put(key1, value);
Put(key2, value);
scoped_refptr<TransactionalLevelDBTransaction> transaction =
CreateTransaction();
std::unique_ptr<TransactionalLevelDBIterator> it =
transaction->CreateIterator();
leveldb::Status s = it->Seek(std::string("b-key1"));
ASSERT_TRUE(it->IsValid());
EXPECT_TRUE(s.ok());
// Remove the 'next' value, and the iterator should go to the end.
TransactionRemove(transaction.get(), key2);
s = it->Next();
EXPECT_TRUE(s.ok());
ASSERT_FALSE(it->IsValid());
// Put key2 back, seek to it.
TransactionPut(transaction.get(), key2, value);
s = it->SeekToLast();
EXPECT_TRUE(s.ok());
ASSERT_TRUE(it->IsValid());
// Remove the 'prev' value.
TransactionRemove(transaction.get(), key1);
s = it->Prev();
EXPECT_TRUE(s.ok());
ASSERT_FALSE(it->IsValid());
// Put key1 back, seek to it.
TransactionPut(transaction.get(), key1, value);
s = it->Seek(std::string("b-key1"));
EXPECT_TRUE(s.ok());
ASSERT_TRUE(it->IsValid());
// Remove the 'next' value & detach the iterator.
TransactionRemove(transaction.get(), key2);
it->EvictLevelDBIterator();
s = it->Next();
EXPECT_TRUE(s.ok());
ASSERT_FALSE(it->IsValid());
// Put key2 back, seek to it.
TransactionPut(transaction.get(), key2, value);
s = it->SeekToLast();
EXPECT_TRUE(s.ok());
ASSERT_TRUE(it->IsValid());
// Remove the 'prev' value and detach the iterator.
TransactionRemove(transaction.get(), key1);
it->EvictLevelDBIterator();
s = it->Prev();
EXPECT_TRUE(s.ok());
ASSERT_FALSE(it->IsValid());
}
TEST_F(TransactionalLevelDBTransactionTest,
IteratorNextAfterRemovingCurrentKey) {
SetUpRealDatabase();
SetupLevelDBDatabase();
// This tests that the iterator reloading logic correctly handles not calling
// Next when it reloads after the current key was removed.
const std::string key1("b-key1");
const std::string key2("b-key2");
const std::string key3("b-key3");
const std::string value("value");
Put(key1, value);
Put(key2, value);
Put(key3, value);
scoped_refptr<TransactionalLevelDBTransaction> transaction =
CreateTransaction();
std::unique_ptr<TransactionalLevelDBIterator> it =
transaction->CreateIterator();
leveldb::Status s = it->Seek(std::string("b-key1"));
ASSERT_TRUE(it->IsValid());
EXPECT_TRUE(s.ok());
// Make sure the iterator is detached, and remove the current key.
it->EvictLevelDBIterator();
TransactionRemove(transaction.get(), key1);
// This call reloads the iterator at key "b-key1".
s = it->Next();
ASSERT_TRUE(it->IsValid());
EXPECT_TRUE(s.ok());
EXPECT_TRUE(KeysEqual(it->Key(), key2)) << it->Key() << ", " << key2;
}
} // namespace content
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
805174a3c225414647ec5878466493572c374b51 | 2facb7d47ef457a731a3cfb50d49dde5f0f331f0 | /io/hdfs_block_reader_main.cpp | 98c532d3979d30068864d77316b523c750dfdb2b | [
"Apache-2.0"
] | permissive | animeshtrivedi/tangram | 03de16276483ec535e60a0460aa9b529bdc30d0e | 67b06a0d2b23c3e263044b6e4d293e263dae7a94 | refs/heads/master | 2020-06-12T10:25:27.656292 | 2019-05-15T06:25:15 | 2019-05-15T06:25:15 | 194,270,850 | 1 | 0 | null | 2019-06-28T12:32:26 | 2019-06-28T12:32:26 | null | UTF-8 | C++ | false | false | 926 | cpp | #include "io/hdfs_block_reader.hpp"
#include "glog/logging.h"
using namespace xyz;
int main(int argc, char **argv) {
google::InitGoogleLogging(argv[0]);
const std::string namenode = "proj10";
const int port = 9000;
const std::string url = "/datasets/classification/kdd12-5blocks";
std::vector<size_t> offsets{0, 1048576, 2097152, 3145728, 4194304};
// block api
int c = 0;
for (auto offset : offsets) {
HdfsBlockReader block_reader(namenode, port);
block_reader.Init(url, offset);
auto a = block_reader.ReadBlock();
c += a.size();
}
LOG(INFO) << c << " lines in total.";
// iterator api
c = 0;
for (auto offset : offsets) {
HdfsBlockReader block_reader(namenode, port);
block_reader.Init(url, offset);
while (block_reader.HasLine()) {
auto s = block_reader.GetLine();
}
c += block_reader.GetNumLineRead();
}
LOG(INFO) << c << " lines in total.";
}
| [
"huangyuzhen93@gmail.com"
] | huangyuzhen93@gmail.com |
aef977cd332b2b9fd6f4910a1211d9fd8666d27a | 73ee941896043f9b3e2ab40028d24ddd202f695f | /external/chromium_org/chrome/browser/infobars/infobar_container.cc | 0ae38e0d90c20a0edfddbc2c4b75cda4ac65fd1a | [
"BSD-3-Clause"
] | permissive | CyFI-Lab-Public/RetroScope | d441ea28b33aceeb9888c330a54b033cd7d48b05 | 276b5b03d63f49235db74f2c501057abb9e79d89 | refs/heads/master | 2022-04-08T23:11:44.482107 | 2016-09-22T20:15:43 | 2016-09-22T20:15:43 | 58,890,600 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 8,819 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "build/build_config.h"
// TODO(pkasting): Port Mac to use this.
#if defined(TOOLKIT_VIEWS) || defined(TOOLKIT_GTK) || defined(OS_ANDROID)
#include "chrome/browser/infobars/infobar_container.h"
#include <algorithm>
#include "base/logging.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/infobars/infobar.h"
#include "chrome/browser/infobars/infobar_delegate.h"
#include "chrome/browser/infobars/infobar_service.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "ui/base/animation/slide_animation.h"
InfoBarContainer::Delegate::~Delegate() {
}
InfoBarContainer::InfoBarContainer(Delegate* delegate)
: delegate_(delegate),
infobar_service_(NULL),
top_arrow_target_height_(InfoBar::kDefaultArrowTargetHeight) {
}
InfoBarContainer::~InfoBarContainer() {
// RemoveAllInfoBarsForDestruction() should have already cleared our infobars.
DCHECK(infobars_.empty());
}
void InfoBarContainer::ChangeInfoBarService(InfoBarService* infobar_service) {
HideAllInfoBars();
infobar_service_ = infobar_service;
if (infobar_service_) {
content::Source<InfoBarService> source(infobar_service_);
registrar_.Add(this, chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED,
source);
registrar_.Add(this, chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_REMOVED,
source);
registrar_.Add(this, chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_REPLACED,
source);
for (size_t i = 0; i < infobar_service_->infobar_count(); ++i) {
// As when we removed the infobars above, we prevent callbacks to
// OnInfoBarAnimated() for each infobar.
AddInfoBar(
infobar_service_->infobar_at(i)->CreateInfoBar(infobar_service_),
i, false, NO_CALLBACK);
}
}
// Now that everything is up to date, signal the delegate to re-layout.
OnInfoBarStateChanged(false);
}
int InfoBarContainer::GetVerticalOverlap(int* total_height) {
// Our |total_height| is the sum of the preferred heights of the InfoBars
// contained within us plus the |vertical_overlap|.
int vertical_overlap = 0;
int next_infobar_y = 0;
for (InfoBars::iterator i(infobars_.begin()); i != infobars_.end(); ++i) {
InfoBar* infobar = *i;
next_infobar_y -= infobar->arrow_height();
vertical_overlap = std::max(vertical_overlap, -next_infobar_y);
next_infobar_y += infobar->total_height();
}
if (total_height)
*total_height = next_infobar_y + vertical_overlap;
return vertical_overlap;
}
void InfoBarContainer::SetMaxTopArrowHeight(int height) {
// Decrease the height by the arrow stroke thickness, which is the separator
// line height, because the infobar arrow target heights are without-stroke.
top_arrow_target_height_ = std::min(
std::max(height - InfoBar::kSeparatorLineHeight, 0),
InfoBar::kMaximumArrowTargetHeight);
UpdateInfoBarArrowTargetHeights();
}
void InfoBarContainer::OnInfoBarStateChanged(bool is_animating) {
if (delegate_)
delegate_->InfoBarContainerStateChanged(is_animating);
UpdateInfoBarArrowTargetHeights();
PlatformSpecificInfoBarStateChanged(is_animating);
}
void InfoBarContainer::RemoveInfoBar(InfoBar* infobar) {
infobar->set_container(NULL);
InfoBars::iterator i(std::find(infobars_.begin(), infobars_.end(), infobar));
DCHECK(i != infobars_.end());
PlatformSpecificRemoveInfoBar(infobar);
infobars_.erase(i);
}
void InfoBarContainer::RemoveAllInfoBarsForDestruction() {
// Before we remove any children, we reset |delegate_|, so that no removals
// will result in us trying to call
// delegate_->InfoBarContainerStateChanged(). This is important because at
// this point |delegate_| may be shutting down, and it's at best unimportant
// and at worst disastrous to call that.
delegate_ = NULL;
// TODO(pkasting): Remove this once InfoBarService calls CloseSoon().
for (size_t i = infobars_.size(); i > 0; --i)
infobars_[i - 1]->CloseSoon();
ChangeInfoBarService(NULL);
}
void InfoBarContainer::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
switch (type) {
case chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED:
AddInfoBar(
content::Details<InfoBarAddedDetails>(details)->CreateInfoBar(
infobar_service_),
infobars_.size(), true, WANT_CALLBACK);
break;
case chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_REMOVED: {
InfoBarRemovedDetails* removed_details =
content::Details<InfoBarRemovedDetails>(details).ptr();
HideInfoBar(FindInfoBar(removed_details->first), removed_details->second);
break;
}
case chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_REPLACED: {
InfoBarReplacedDetails* replaced_details =
content::Details<InfoBarReplacedDetails>(details).ptr();
ReplaceInfoBar(replaced_details->first, replaced_details->second);
break;
}
default:
NOTREACHED();
break;
}
}
void InfoBarContainer::ReplaceInfoBar(InfoBarDelegate* old_delegate,
InfoBarDelegate* new_delegate) {
InfoBar* new_infobar = new_delegate->CreateInfoBar(infobar_service_);
InfoBar* old_infobar = FindInfoBar(old_delegate);
#if defined(OS_ANDROID)
PlatformSpecificReplaceInfoBar(old_infobar, new_infobar);
#endif
AddInfoBar(
new_infobar, HideInfoBar(old_infobar, false), false, WANT_CALLBACK);
}
InfoBar* InfoBarContainer::FindInfoBar(InfoBarDelegate* delegate) {
// Search for the infobar associated with |delegate|. We cannot search for
// |delegate| in |tab_helper_|, because an InfoBar remains alive until its
// close animation completes, while the delegate is removed from the tab
// immediately.
for (InfoBars::iterator i(infobars_.begin()); i != infobars_.end(); ++i) {
InfoBar* infobar = *i;
if (infobar->delegate() == delegate)
return infobar;
}
NOTREACHED();
return NULL;
}
size_t InfoBarContainer::HideInfoBar(InfoBar* infobar, bool use_animation) {
InfoBars::iterator it =
std::find(infobars_.begin(), infobars_.end(), infobar);
DCHECK(it != infobars_.end());
size_t position = it - infobars_.begin();
// We merely need hide the infobar; it will call back to RemoveInfoBar()
// itself once it's hidden.
infobar->Hide(use_animation);
infobar->CloseSoon();
UpdateInfoBarArrowTargetHeights();
return position;
}
void InfoBarContainer::HideAllInfoBars() {
registrar_.RemoveAll();
while (!infobars_.empty()) {
InfoBar* infobar = infobars_.front();
// Inform the infobar that it's hidden. If it was already closing, this
// closes its delegate.
infobar->Hide(false);
}
}
void InfoBarContainer::AddInfoBar(InfoBar* infobar,
size_t position,
bool animate,
CallbackStatus callback_status) {
DCHECK(std::find(infobars_.begin(), infobars_.end(), infobar) ==
infobars_.end());
DCHECK_LE(position, infobars_.size());
infobars_.insert(infobars_.begin() + position, infobar);
UpdateInfoBarArrowTargetHeights();
PlatformSpecificAddInfoBar(infobar, position);
if (callback_status == WANT_CALLBACK)
infobar->set_container(this);
infobar->Show(animate);
if (callback_status == NO_CALLBACK)
infobar->set_container(this);
}
void InfoBarContainer::UpdateInfoBarArrowTargetHeights() {
for (size_t i = 0; i < infobars_.size(); ++i)
infobars_[i]->SetArrowTargetHeight(ArrowTargetHeightForInfoBar(i));
}
int InfoBarContainer::ArrowTargetHeightForInfoBar(size_t infobar_index) const {
if (!delegate_ || !delegate_->DrawInfoBarArrows(NULL))
return 0;
if (infobar_index == 0)
return top_arrow_target_height_;
const ui::SlideAnimation& first_infobar_animation =
const_cast<const InfoBar*>(infobars_.front())->animation();
if ((infobar_index > 1) || first_infobar_animation.IsShowing())
return InfoBar::kDefaultArrowTargetHeight;
// When the first infobar is animating closed, we animate the second infobar's
// arrow target height from the default to the top target height. Note that
// the animation values here are going from 1.0 -> 0.0 as the top bar closes.
return top_arrow_target_height_ + static_cast<int>(
(InfoBar::kDefaultArrowTargetHeight - top_arrow_target_height_) *
first_infobar_animation.GetCurrentValue());
}
#endif // TOOLKIT_VIEWS || defined(TOOLKIT_GTK) || defined(OS_ANDROID)
| [
"ProjectRetroScope@gmail.com"
] | ProjectRetroScope@gmail.com |
86eb8ebc01e2da4cc4403794cada60994b694cb0 | 050c8a810d34fe125aecae582f9adfd0625356c6 | /ordine/ordine.cpp | 3ba4cd283e3f9964d55888c21be9f728cce05e4a | [] | no_license | georgerapeanu/c-sources | adff7a268121ae8c314e846726267109ba1c62e6 | af95d3ce726325dcd18b3d94fe99969006b8e138 | refs/heads/master | 2022-12-24T22:57:39.526205 | 2022-12-21T16:05:01 | 2022-12-21T16:05:01 | 144,864,608 | 11 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 858 | cpp | #include <fstream>
#include <iostream>
using namespace std;
ifstream f("ordine.in");
ofstream g("ordine.out");
long afis[250001],i,j,n,v[250001];
int c;
void ordine1(void)
{
afis[1]=1;
}
int main()
{
ordine1();
cout<<afis[1];
//f>>n;
/* for(i=1;i<=n;i++)
{
f>>v[i];
}
f>>c;
if(c==1)
{
if(n%2==1)
g<<v[n/2+1];
else
g<<v[n];
}
else
{
long long afis[250001];
for(i=n;i>=1;i--)
{
if(i%2==1)
{
afis[i]=v[i/2+1];
for(j=i/2+1;j<=n;j++)
{
v[j]=v[j+1];
}
}
else
afis[i]=v[i];
}
for(i=1;i<=n;i++)
g<<afis[i]<<" ";*/
// ordine();
// }
f.close();g.close();
return 0;
}
| [
"alexandrurapeanu@yahoo.com"
] | alexandrurapeanu@yahoo.com |
da7481ed8c4f5ac6ecb89115b847dd4c81209a3c | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_1484496_0/C++/moonlight131/c.cpp | 2f060ba8387ccf0685b7cde4a481ddff592d8867 | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 985 | cpp | #include<iostream>
#include<cstdio>
#include<vector>
#include<list>
#include<string>
#include<algorithm>
#include<queue>
#include<stack>
#include<set>
#include<map>
#include<cmath>
using namespace std;
#define maxn 1100
#define maxm 1100000
#define eps 1e-10
#define inf 1000000000
int f[maxn],mat[maxn],n,l,r;
bool flag;
void dfs(int x)
{
int z,i,j;
if(x==n)
{
if(l!=r)return ;
for(j=0;j<2;j++)
{
z=0;
for(i=0;i<n;i++)
{
if(f[i]==j)
{
if(z)printf(" ");
else z=1;
printf("%d",mat[i]);
}
}
puts("");
}
flag=false;
return ;
}
if(flag)
{
f[x]=0;
l+=mat[x];
dfs(x+1);
}
if(flag)
{
f[x]=1;
l-=mat[x];
r+=mat[x];
dfs(x+1);
}
if(flag)
{
f[x]=2;
r-=mat[x];
dfs(x+1);
}
}
int main()
{
int t,ca,i;
scanf("%d",&t);
for(ca=1;ca<=t;ca++)
{
printf("Case #%d:\n",ca);
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&mat[i]);
}
l=r=0;
flag=true;
dfs(0);
if(flag)puts("Impossible");
}
}
| [
"eewestman@gmail.com"
] | eewestman@gmail.com |
126ccf5b4b2e46ef680bbf49df71b71a3a3fb00d | 8247b94227a3e4169c2c8a2b572cf57dc24917a2 | /src/ripple_app/transactors/Transactor.cpp | 8c0ff01971ba1440b15e673c2a4dccbbd060b303 | [
"MIT-Wu",
"MIT",
"ISC",
"BSL-1.0"
] | permissive | StanChe/stellar-mobile | 4e641dd27fa594e38971f549c57b218403e8522f | 43a99d4da4369ecfe5b2a907f740dfd99056058e | refs/heads/master | 2020-05-18T13:26:51.005312 | 2014-12-06T10:09:23 | 2014-12-06T10:09:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,340 | cpp | //------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012, 2013 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, 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.
*/
//==============================================================================
#include "Transactor.h"
#include "AddWallet.h"
#include "CancelOffer.h"
#include "Change.h"
#include "CreateOffer.h"
#include "Payment.h"
#include "SetAccount.h"
#include "SetRegularKey.h"
#include "SetTrust.h"
#include "InflationTransactor.h"
#include "AccountMergeTransactor.h"
namespace ripple {
std::unique_ptr<Transactor> Transactor::makeTransactor (
SerializedTransaction const& txn,
TransactionEngineParams params,
TransactionEngine* engine)
{
switch (txn.getTxnType ())
{
case ttPAYMENT:
return std::unique_ptr<Transactor> (
new PaymentTransactor (txn, params, engine));
case ttINFLATION:
return std::unique_ptr<Transactor>(
new InflationTransactor(txn, params, engine));
case ttACCOUNT_SET:
return std::unique_ptr<Transactor> (
new AccountSetTransactor (txn, params, engine));
case ttACCOUNT_MERGE:
return std::unique_ptr<Transactor>(
new AccountMergeTransactor (txn, params, engine));
case ttREGULAR_KEY_SET:
return std::unique_ptr<Transactor> (
new RegularKeySetTransactor (txn, params, engine));
case ttTRUST_SET:
return std::unique_ptr<Transactor> (
new TrustSetTransactor (txn, params, engine));
case ttOFFER_CREATE:
return make_OfferCreateTransactor (txn, params, engine);
case ttOFFER_CANCEL:
return std::unique_ptr<Transactor> (
new OfferCancelTransactor (txn, params, engine));
case ttWALLET_ADD:
return std::unique_ptr<Transactor> (
new WalletAddTransactor (txn, params, engine));
case ttAMENDMENT:
case ttFEE:
return std::unique_ptr<Transactor> (
new ChangeTransactor (txn, params, engine));
default:
return std::unique_ptr<Transactor> ();
}
}
Transactor::Transactor (
SerializedTransaction const& txn,
TransactionEngineParams params,
TransactionEngine* engine,
beast::Journal journal)
: mTxn (txn)
, mEngine (engine)
, mParams (params)
, mHasAuthKey (false)
, mSigMaster (false)
, m_journal (journal)
{
}
void Transactor::calculateFee ()
{
mFeeDue = STAmount (mEngine->getLedger ()->scaleFeeLoad (
calculateBaseFee (), is_bit_set (mParams, tapADMIN)));
}
std::uint64_t Transactor::calculateBaseFee ()
{
return getConfig ().FEE_DEFAULT;
}
TER Transactor::payFee ()
{
STAmount saPaid = mTxn.getTransactionFee ();
if (!saPaid.isLegalNet ())
return temBAD_AMOUNT;
// Only check fee is sufficient when the ledger is open.
if (is_bit_set(mParams, tapOPEN_LEDGER) &&
saPaid < mFeeDue)
{
m_journal.trace << "Insufficient fee paid: " <<
saPaid.getText () << "/" << mFeeDue.getText ();
return telINSUF_FEE_P;
}
if (saPaid < zero || !saPaid.isNative ())
return temBAD_FEE;
if (!saPaid) return tesSUCCESS;
// Deduct the fee, so it's not available during the transaction.
// Will only write the account back, if the transaction succeeds.
if (mSourceBalance < saPaid)
{
m_journal.trace << "Insufficient balance:" <<
" balance=" << mSourceBalance.getText () <<
" paid=" << saPaid.getText ();
return terINSUF_FEE_B;
}
mSourceBalance -= saPaid;
mTxnAccount->setFieldAmount (sfBalance, mSourceBalance);
return tesSUCCESS;
}
TER Transactor::checkSig ()
{
// Consistency: Check signature
// Verify the transaction's signing public key is the key authorized for signing.
if (mSigningPubKey.getAccountID () == mTxnAccountID)
{
// Authorized to continue.
mSigMaster = true;
if (mTxnAccount->isFlag(lsfDisableMaster))
return tefMASTER_DISABLED;
}
else if (mHasAuthKey && mSigningPubKey.getAccountID () == mTxnAccount->getFieldAccount160 (sfRegularKey))
{
// Authorized to continue.
nothing ();
}
else if (mHasAuthKey)
{
m_journal.trace << "applyTransaction: Delay: Not authorized to use account.";
return tefBAD_AUTH;
}
else
{
m_journal.trace << "applyTransaction: Invalid: Not authorized to use account.";
return temBAD_AUTH_MASTER;
}
return tesSUCCESS;
}
TER Transactor::checkSeq ()
{
std::uint32_t t_seq = mTxn.getSequence ();
std::uint32_t a_seq = mTxnAccount->getFieldU32 (sfSequence);
m_journal.trace << "Aseq=" << a_seq << ", Tseq=" << t_seq;
if (t_seq != a_seq)
{
if (a_seq < t_seq)
{
m_journal.trace << "apply: transaction has future sequence number";
return terPRE_SEQ;
}
else
{
uint256 txID = mTxn.getTransactionID ();
if (mEngine->getLedger ()->hasTransaction (txID))
return tefALREADY;
}
m_journal.warning << "apply: transaction has past sequence number";
return tefPAST_SEQ;
}
// Deprecated: Do not use
if (mTxn.isFieldPresent (sfPreviousTxnID) &&
(mTxnAccount->getFieldH256 (sfPreviousTxnID) != mTxn.getFieldH256 (sfPreviousTxnID)))
return tefWRONG_PRIOR;
if (mTxn.isFieldPresent (sfAccountTxnID) &&
(mTxnAccount->getFieldH256 (sfAccountTxnID) != mTxn.getFieldH256 (sfAccountTxnID)))
return tefWRONG_PRIOR;
if (mTxn.isFieldPresent (sfLastLedgerSequence) &&
(mEngine->getLedger()->getLedgerSeq() > mTxn.getFieldU32 (sfLastLedgerSequence)))
return tefMAX_LEDGER;
mTxnAccount->setFieldU32 (sfSequence, t_seq + 1);
if (mTxnAccount->isFieldPresent (sfAccountTxnID))
mTxnAccount->setFieldH256 (sfAccountTxnID, mTxn.getTransactionID ());
return tesSUCCESS;
}
// check stuff before you bother to lock the ledger
TER Transactor::preCheck ()
{
mTxnAccountID = mTxn.getSourceAccount ().getAccountID ();
if (!mTxnAccountID)
{
m_journal.warning << "apply: bad transaction source id";
return temBAD_SRC_ACCOUNT;
}
// Extract signing key
// Transactions contain a signing key. This allows us to trivially verify a transaction has at least been properly signed
// without going to disk. Each transaction also notes a source account id. This is used to verify that the signing key is
// associated with the account.
// XXX This could be a lot cleaner to prevent unnecessary copying.
mSigningPubKey = RippleAddress::createAccountPublic (mTxn.getSigningPubKey ());
// Consistency: really signed.
if (!mTxn.isKnownGood ())
{
if (mTxn.isKnownBad () || (!is_bit_set (mParams, tapNO_CHECK_SIGN) && !mTxn.checkSign (mSigningPubKey)))
{
mTxn.setBad ();
m_journal.warning << "apply: Invalid transaction (bad signature)";
return temINVALID;
}
mTxn.setGood ();
}
return tesSUCCESS;
}
TER Transactor::apply ()
{
TER terResult (preCheck ());
if (terResult != tesSUCCESS)
return (terResult);
// Restructure this to avoid the dependency on LedgerBase::mLock
Ledger::ScopedLockType sl (mEngine->getLedger ()->mLock);
mTxnAccount = mEngine->entryCache (ltACCOUNT_ROOT,
Ledger::getAccountRootIndex (mTxnAccountID));
calculateFee ();
// Find source account
// If are only forwarding, due to resource limitations, we might verifying
// only some transactions, this would be probabilistic.
if (!mTxnAccount)
{
if (mustHaveValidAccount ())
{
m_journal.trace <<
"apply: delay transaction: source account does not exist " <<
mTxn.getSourceAccount ().humanAccountID ();
return terNO_ACCOUNT;
}
}
else
{
mPriorBalance = mTxnAccount->getFieldAmount (sfBalance);
mSourceBalance = mPriorBalance;
mHasAuthKey = mTxnAccount->isFieldPresent (sfRegularKey);
}
terResult = checkSeq ();
if (terResult != tesSUCCESS) return (terResult);
terResult = payFee ();
if (terResult != tesSUCCESS) return (terResult);
terResult = checkSig ();
if (terResult != tesSUCCESS) return (terResult);
if (mTxnAccount)
mEngine->entryModify (mTxnAccount);
return doApply ();
}
}
| [
"stchervyakov@gmail.com"
] | stchervyakov@gmail.com |
2327925cc517aff866c21c2821456a8ef63447c7 | cb799009807c4c8970564f8f89542cd089c5141c | /FinalProject/src/Window.cpp | c43337ad2f8312e2b9b82792327cee97d680c3fd | [
"Apache-2.0"
] | permissive | DavidePistilli173/Computer-Vision | 102723fb22548396a0a00456a994246692332a1f | 4066a99f6f6fdc941829d3cd3015565ec0046a2f | refs/heads/master | 2022-11-06T03:49:26.365086 | 2020-06-23T10:02:44 | 2020-06-23T10:02:44 | 263,870,698 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,480 | cpp | #include "Window.hpp"
#include "Log.hpp"
#include <opencv2/highgui.hpp>
using namespace prj;
Window::Window(std::string_view name) :
name_{ name.data() }
{
cv::namedWindow(name.data(), cv::WINDOW_NORMAL | cv::WINDOW_KEEPRATIO | cv::WINDOW_GUI_EXPANDED);
trckBarVals_.reserve(max_trckbar_num); // Reserve space for the maximum number of trackbars.
}
Window::~Window()
{
cv::destroyWindow(name_);
}
bool Window::addTrackBar(std::string_view name, int maxVal)
{
return addTrackBar(name, 0, maxVal);
}
bool Window::addTrackBar(std::string_view name, int startVal, int maxVal)
{
if (trckBarVals_.size() == max_trckbar_num)
{
Log::warn("Maximum number of trackbars reached.");
return false;
}
if (startVal > maxVal)
{
Log::warn("Initial trackbar value too high. Setting it to 0.");
startVal = 0;
}
int* valPtr{ &trckBarVals_.emplace_back(startVal) };
cv::createTrackbar(name.data(), name_, valPtr, maxVal, trckCallbck_, this);
return true;
}
std::vector<int> Window::fetchTrckVals()
{
/* Return the current values and reset the modification flag. */
trckModified_ = false;
return trckBarVals_;
}
bool Window::modified() const
{
return trckModified_;
}
void Window::showImg(const cv::Mat& img) const
{
cv::imshow(name_, img);
}
void Window::trckCallbck_(int val, void* ptr)
{
Window* winPtr{ reinterpret_cast<Window*>(ptr) };
winPtr->trckModified_ = true; // Set the modification flag.
} | [
"davidepistilli173@gmail.com"
] | davidepistilli173@gmail.com |
81dfe68ce04d51d924f10cb45ce2978e2ed4e9c8 | 0e79b11e100c78e1d0b7159cb6ae369a2942d6d0 | /gsyslib/g_rect.h | 19489b4b4de461abe2191fdcdb475408a3016b9b | [] | no_license | JlblC/dcmap | e3be11c4c9da9ac4f0be693fee3b4fb2cf8af6ec | e2cbfa43dfe04125d19b4bae34e9a552db307198 | refs/heads/master | 2021-07-04T01:47:45.249683 | 2014-06-08T17:46:32 | 2014-06-08T17:46:32 | 20,622,342 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 9,435 | h | #pragma once
#ifndef G_RECT_H
#define G_RECT_H
#include "g_alg.h"
#include "g_point.h"
#include "g_binstream.h"
#include "boost/operators.hpp"
namespace gsys
{
template<class T>
struct tRect :
boost::equality_comparable<tRect<T>,
boost::multiplicative2<tRect<T>, T,
boost::multiplicative2<tRect<T>, tPoint<T>
> > >
{
typedef T value_type;
typedef gsys_ulong size_type;
typedef tRect<value_type> this_type;
typedef tPoint<value_type> point_type;
union
{
struct
{
value_type left,top;
value_type right,bottom;
};
value_type values[4];
};
tRect()
{
// top = bottom = left = right = T(0);
}
tRect(value_type val)
{
top = bottom = left = right = val;
}
tRect(value_type aleft, value_type atop, value_type aright, value_type abottom)
{
left = aleft;
top = atop ;
right = aright;
bottom = abottom;
}
this_type& set(value_type aleft, value_type atop, value_type aright, value_type abottom)
{
left = aleft;
top = atop ;
right = aright;
bottom = abottom;
return *this;
}
this_type& init_by_center_abs_size(value_type x,value_type y,value_type w,value_type h)
{
left=x-w/2;
top=y-h/2;
right=x+w/2;
bottom=y+h/2;
return *this;
}
this_type& init_by_center_abs_size(point_type const& base,point_type const& size)
{return init_by_center_abs_size(base.x,base.y,size.x,size.y);}
this_type& init_by_center_size(value_type x,value_type y,value_type w,value_type h)
{
left=x-w;
top=y-h;
right=x+w;
bottom=y+h;
return *this;
}
this_type& init_by_center_size(point_type const& base,point_type const& size)
{return init_by_center_size(base.x,base.y,size.x,size.y);}
this_type& init_by_center_size(value_type x,value_type y,value_type w){return init_by_center_size(x,y,w,w);}
this_type& init_by_size(value_type x,value_type y,value_type w,value_type h)
{
left=x;
top=y;
right=left+w;
bottom=top+h;
return *this;
}
this_type& init_by_size(tPoint<value_type> const& base,tPoint<value_type> const& size)
{return init_by_size(base.x,base.y,size.x,size.y);}
template<class _AT>
tRect(const tRect<_AT> &rc):
left((value_type)rc.left),
top((value_type)rc.top),
right((value_type)rc.right),
bottom((value_type)rc.bottom){}
template<class _AT>
this_type& operator = (const tRect<_AT> &rc)
{
left = (value_type)rc.left;
top = (value_type)rc.top;
right = (value_type)rc.right;
bottom = (value_type)rc.bottom;
return *this;
}
value_type height()const{return gsys::abs<value_type>(bottom-top);}
value_type width()const{return gsys::abs<value_type>(right-left);}
point_type origin()const{return point_type(left,top);}
point_type size()const{return point_type(width(),height());}
point_type middle_point()const
{
point_type t(left+width()/2,top+height()/2);
return t;
}
point_type center()const
{
return middle_point();
}
point_type& courner1_ref(){return *((point_type*)values);}
point_type& courner2_ref(){return *((point_type*)(values+2));}
point_type const& courner1_ref()const{return *((point_type const*)values);}
point_type const& courner2_ref()const{return *((point_type const*)(values+2));}
// shows whatever rect area is gsys_null
bool IsNull()const
{
if(top==bottom)return true;
if(left==right)return true;
return false;
}
/* Modifications */
// normalises the rect
this_type& Normalise()
{
if(top > bottom) std::swap(top,bottom);
if(left > right) std::swap(left,right);
return *this;
}
// makes left < right, top<bottom
this_type& Rectify(){return Normalise();}
// grows rect by given values
this_type& grow(value_type x){return grow(x,x);}
// grows rect by given values
this_type& grow(value_type x,value_type y)
{
left-=x;
right+=x;
top-=y;
bottom+=y;
return *this;
}
// offset rect by given values
this_type& offset(value_type x,value_type y)
{
left+=x;
right+=x;
top+=y;
bottom+=y;
return *this;
}
this_type& offset(point_type const& pt)
{
return offset(pt.x,pt.y);
}
tRect<int> GetOverlapGrid(value_type dx,value_type dy)const
{
tRect<int> rc;
rc.left = ftoi(floorf(float(left)/dx));
rc.top = ftoi(floorf(float(top)/dy));
rc.right = ftoi(ceilf(float(right)/dx));
rc.bottom = ftoi(ceilf(float(bottom)/dy));
return rc;
}
tRect<int> GetOverlapGrid(value_type d)const{return GetOverlapGrid(d,d);}
tRect<int> GetContainsGrid(value_type dx,value_type dy)const
{
tRect<int> rc;
rc.left = ftoi(ceilf(float(left)/dx));
rc.top = ftoi(ceilf(float(top)/dy));
rc.right = ftoi(floorf(float(right)/dx));
rc.bottom = ftoi(floorf(float(bottom)/dy));
return rc;
}
tRect<int> GetContainsGrid(value_type d)const{return GetContainsGrid(d,d);}
// bound rect (param) must have been normalised!
this_type Bound(const this_type &rc)const
{
return this_type(bound(left,rc.left,rc.right),
bound(top,rc.top,rc.bottom),
bound(right,rc.left,rc.right),
bound(bottom,rc.top,rc.bottom));
}
// create rect contains intersections of this rects
// gsys_null rect if whey does not intersect
this_type Intersect(const this_type &rc)const
{
tRect<value_type> irc;
irc.left = max(rc.left,left);
irc.right = min(rc.right,right);
if(irc.left > irc.right) return tRect<value_type>(0);
irc.top = max(rc.top,top);
irc.bottom = min(rc.bottom,bottom);
if(irc.top > irc.bottom) return tRect<value_type>(0);
return irc;
}
bool Contains(value_type x, value_type y)const
{
return x>=left&&x<=right&&y>=top&&y<=bottom;
}
bool Contains(point_type const& pt)const{return Contains(pt.x,pt.y);}
bool Contains(this_type const& rc)const
{
return Contains(rc.left,rc.top) && Contains(rc.right,rc.bottom);
}
// left*=x; top*=y
// rifgr*=x; bottom*=y
this_type & mult(value_type x,value_type y)
{
left *= x;
right *= x;
top *= y;
bottom *= y;
return *this;
}
operator bool() // rect = false if it have zero size
{
return !(left == right && top == bottom);
}
this_type & operator *= (value_type const& v)
{
left *= v;
right *= v;
top *= v;
bottom *= v;
return *this;
}
this_type & operator *= (point_type const& v)
{
left *= v.x;
right *= v.x;
top *= v.y;
bottom *= v.y;
return *this;
}
this_type & operator /= (value_type const& v)
{
left/=v;
right/=v;
top/=v;
bottom/=v;
return *this;
}
this_type & operator /= (point_type const& v)
{
left /= v.x;
right /= v.x;
top /= v.y;
bottom /= v.y;
return *this;
}
// compares rects
bool operator == (const this_type& rc)const
{
return equ(rc.bottom,bottom) && equ(rc.top,top) &&
equ(rc.left,left) && equ(rc.right,right);
}
};
typedef tRect<int> Rect;
typedef tRect<float> FRect;
typedef tRect<int> grect;
GSYS_SET_TYPENAME(grect,"rc");
typedef tRect<float> frect;
GSYS_SET_TYPENAME(frect,"rcf");
typedef tRect<word> wrect;
GSYS_SET_TYPENAME(wrect,"rcw");
template<class T>
std::ostream& operator<<(std::ostream& os,tRect<T> const& v)
{GSYS_ASSERTREF(os);GSYS_ASSERTREF(v);
return os << "{" << v.left << "," << v.top << "," << v.right << ","<< v.bottom<< "}";
}
template<class T>
std::istream& operator>>(std::istream& is,tRect<T> & v)
{GSYS_ASSERTREF(is);GSYS_ASSERTREF(v);
wsp_delim D_BO('{');wsp_delim D_BC('}');wsp_delim D_D(',');\
char ch = is.peek();
if(ch == 'c')
{
is.ignore();
typename tRect<T>::value_type v1,v2,cx,cy;
is >> D_BO >> ISN(v1) >> D_D >> ISN(v2) >> D_D >> ISN(cx) >> D_D >> ISN(cy) >> D_BC;
v.init_by_center_abs_size(v1,v2,cx,cy);
}
else if(ch == 's')
{
is.ignore();
typename tRect<T>::value_type v1,v2,cx,cy;
is >> D_BO >> ISN(v1) >> D_D >> ISN(v2) >> D_D >> ISN(cx) >> D_D >> ISN(cy) >> D_BC;
v.init_by_size(v1,v2,cx,cy);
}
else
{
is>>D_BO>>ISN(v.left)>>D_D>>ISN(v.top)>>D_D>>ISN(v.right)>>D_D>>ISN(v.bottom)>>D_BC;
}
return is;
}
template<class T>
binostream& operator<<(binostream& os,tRect<T> const& v)
{GSYS_ASSERTREF(os);GSYS_ASSERTREF(v);
return os << v.left << v.top << v.right << v.bottom;
}
template<class T>
binistream& operator>>(binistream& is,tRect<T> & v)
{GSYS_ASSERTREF(is);GSYS_ASSERTREF(v);
return is >> v.left >> v.top >> v.right >> v.bottom;
}
inline frect& lerp(frect const& c1,frect const& c2,gsys_real amount,frect & res)
{
res.left = c1.left + (c2.left-c1.left)*amount;
res.top = c1.top + (c2.top-c1.top)*amount;
res.right = c1.right + (c2.right-c1.right)*amount;
res.bottom = c1.bottom + (c2.bottom-c1.bottom)*amount;
return res;
}
inline frect lerp(frect const& c1,frect const& c2,gsys_real amount)
{frect cl;lerp(c1,c2,amount,cl);return cl;}
}
#endif | [
"jlblc@ya.ru"
] | jlblc@ya.ru |
697d0997fb9004f9423e732119405860cd1e560c | 3bad1ce8cd4aafd2870a3b570d297de22cff6bda | /ui/src/vclabel.h | 6edf9643c2515e86ef44a882b2d3138057da16a8 | [
"Apache-2.0"
] | permissive | hveld/qlcplus | 64ee591e641a3bfa3358f942ad2875c814841f16 | 1dd61a5a3a2c93d7fe88cd2a90574c4849b64829 | refs/heads/master | 2021-01-16T17:52:15.266518 | 2015-06-17T19:10:50 | 2015-06-17T19:10:50 | 22,361,368 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,570 | h | /*
Q Light Controller
vclabel.h
Copyright (c) Heikki Junnila, Stefan Krumm
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.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef VCLABEL_H
#define VCLABEL_H
#include "vcwidget.h"
class QDomDocument;
class QDomElement;
class QPaintEvent;
class MasterTimer;
class Doc;
/** @addtogroup ui_vc_widgets
* @{
*/
#define KXMLQLCVCLabel "Label"
class VCLabel : public VCWidget
{
Q_OBJECT
Q_DISABLE_COPY(VCLabel)
/*********************************************************************
* Initialization
*********************************************************************/
public:
VCLabel(QWidget* parent, Doc* doc);
~VCLabel();
/*********************************************************************
* Clipboard
*********************************************************************/
public:
VCWidget* createCopy(VCWidget* parent);
/*********************************************************************
* Properties
*********************************************************************/
public:
void editProperties();
/*****************************************************************************
* External input
*****************************************************************************/
/** @reimp */
void updateFeedback() { }
/*********************************************************************
* Web access
*********************************************************************/
public:
/** @reimpl */
QString getCSS();
/*********************************************************************
* Load & Save
*********************************************************************/
public:
bool loadXML(const QDomElement* root);
bool saveXML(QDomDocument* doc, QDomElement* vc_root);
/*********************************************************************
* Painting
*********************************************************************/
protected:
void paintEvent(QPaintEvent* e);
};
/** @} */
#endif
| [
"massimocallegari@yahoo.it"
] | massimocallegari@yahoo.it |
7ef53d4b417f97172e9772c796cc82982d5305fa | 99731d04935cc4ebf31067b114e35fa401b9b788 | /gtest_unit/cmd_system_para.cpp | 0545e9e34ba12e29a0f8647d28751299eaaf63f4 | [
"Apache-2.0"
] | permissive | Ansersion/libbps | 4eeaf47e8cc2fa89ecf8804697cad072fc42ec3d | d0ed8d108ee4f5ed3946c61545ab81be614b610f | refs/heads/master | 2021-07-04T02:52:02.449984 | 2020-08-12T07:01:43 | 2020-08-12T07:01:43 | 196,856,234 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,571 | cpp | // Copyright 2019-2020 Ansersion
//
// 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 <stdio.h>
#include <sys/types.h>
#include <memory.h>
#include <stdlib.h>
#include <string>
#include <list>
#include <iostream>
#include <gtest/gtest.h>
extern "C"
{
#include <bps_ret_code.h>
#include <bps_public.h>
#include <bps_cmd_system_para.h>
}
using namespace std;
/** write system parameter SN: "ABCDEFGHIJKLMNOP" */
static const int MSG_BUF_SIZE = 256;
static BPS_UINT8 buf[MSG_BUF_SIZE];
static const int MCU_ADDR = 0;
static const int MODULE_ADDR = 1;
static const BPS_WORD HEADER_SIZE = BPS_HEADER_SIZE - BPS_VERSION_SIZE - BPS_ADDR_SIZE - BPS_REMAIN_LEN_SIZE;
static const ConfigTypeSystemPara REQ_TYPE = WRITE_SYS_PARA;
static const ParaTypeSystemPara PARA_TYPE = SN_SYS_PARA_TYPE;
// static const BPS_UINT16 INTERVAL = 0x5A5A;;
static const char * SN = "ABCDEFGHIJKLMNOP";
static BPS_UINT8 REQ_MSG[] =
{
0xBB, 0xCC, 0x00, 0x01, 0x00, 0x14, 0xEE, 0x01, 0x01, 0x10, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x9D
};
// bb cc 00 10 00 15 ee 01 01 00 10
static BPS_UINT8 RSP_MSG[] =
{
0xBB, 0xCC, 0x00, 0x10, 0x00, 0x04, 0xEF, 0x01, 0x01, 0x00, 0x05
};
/** pack the system parameter command request
* packet flow: MCU -> MODULE */
TEST(COMMAND_SYSTEM_PARA, PackRequest)
{
BPS_UINT8 * buf_tmp = buf;
BPSCmdSystemParaReq data;
data.configType = REQ_TYPE;
data.paraType = PARA_TYPE;
data.len = strlen(SN);
data.data = (BPS_UINT8 *)SN;
memset(buf, 0, MSG_BUF_SIZE);
buf_tmp = PackBPSHeader(buf_tmp);
buf_tmp = PackBPSVersion(buf_tmp);
buf_tmp = PackBPSAddr(buf_tmp, MCU_ADDR, MODULE_ADDR);
buf_tmp += BPS_REMAIN_LEN_SIZE;
BPS_UINT16 tmpLen = BPSPackSystemParaReq(&data, buf_tmp, MSG_BUF_SIZE-HEADER_SIZE);
EXPECT_GT(tmpLen, 0);
PackBPSRemainLen(buf + BPS_REMAIN_LEN_POSITION, tmpLen);
EXPECT_NE(PackBPSChecksum(buf, MSG_BUF_SIZE), (BPS_UINT8 *)BPS_NULL);
tmpLen += HEADER_SIZE + BPS_CHECKSUM_SIZE;
for(size_t i = 0; i < sizeof(REQ_MSG); i++) {
EXPECT_EQ(REQ_MSG[i], buf[i]);
}
}
/** pack the system parameter command response
* packet flow: MODULE -> MCU */
TEST(COMMAND_SYSTEM_PARA, PackResponse)
{
BPS_UINT8 * buf_tmp = buf;
BPSCmdSystemParaRsp data;
data.configType = REQ_TYPE;
data.paraType = PARA_TYPE;
data.retCode = BPS_RET_CODE_OK;;
data.len = strlen(SN);
data.data = (BPS_UINT8 *)SN;
memset(buf, 0, MSG_BUF_SIZE);
buf_tmp = PackBPSHeader(buf_tmp);
buf_tmp = PackBPSVersion(buf_tmp);
buf_tmp = PackBPSAddr(buf_tmp, MODULE_ADDR, MCU_ADDR);
buf_tmp += BPS_REMAIN_LEN_SIZE;
BPS_UINT16 tmpLen = BPSPackSystemParaRsp(&data, buf_tmp, MSG_BUF_SIZE-HEADER_SIZE);
EXPECT_GT(tmpLen, 0);
PackBPSRemainLen(buf + BPS_REMAIN_LEN_POSITION, tmpLen);
EXPECT_NE(PackBPSChecksum(buf, MSG_BUF_SIZE), (BPS_UINT8 *)BPS_NULL);
tmpLen += HEADER_SIZE + BPS_CHECKSUM_SIZE;
for(size_t i = 0; i < sizeof(RSP_MSG); i++) {
// printf("%02x ", buf[i]);
EXPECT_EQ(RSP_MSG[i], buf[i]);
}
// printf("\n");
}
/** parse the system parameter command request
* packet flow: MODULE <- MCU */
TEST(COMMAND_SYSTEM_PARA, ParseRequest)
{
BPS_WORD size = sizeof(REQ_MSG);
BPSCmdSystemParaReq data;
BPS_UINT8 buffer[256];
data.data = buffer;
EXPECT_GT(BPSParseSystemParaReq(&data, REQ_MSG+BPS_CMD_WORD_POSITION+1, size), 0);
EXPECT_EQ(data.configType, REQ_TYPE);
EXPECT_EQ(data.paraType, PARA_TYPE);
EXPECT_EQ(data.len, strlen(SN));
EXPECT_EQ(strncmp((const char *)data.data, (const char *)SN, strlen(SN)), 0);
}
/** parse the system parameter command response
* packet flow: MCU <- MODULE */
TEST(COMMAND_SYSTEM_PARA, ParseResponse)
{
BPS_WORD size = sizeof(RSP_MSG);
BPSCmdSystemParaRsp data;
EXPECT_GT(BPSParseSystemParaRsp(&data, RSP_MSG+BPS_CMD_WORD_POSITION+1, size), 0);
EXPECT_EQ(data.configType, REQ_TYPE);
EXPECT_EQ(data.paraType, PARA_TYPE);
}
| [
"ansersion@gmail.com"
] | ansersion@gmail.com |
1fe330c40ac1316fb4f66a83ab2c991f1fcd15fe | 841322eddd57db0b12f6abd685dd399f28be0c68 | /qt_creator_basic/15/15_2_mydir/mainwindow.h | d83b9485823e1eae51c08da708f188475fdbda8d | [] | no_license | cat1984x/Learning_Qt | c52e030850d254b4a5541968d86c56b5cdf504f7 | 4deaa4e86112c263f5421d2f91b0ba1ca14e482a | refs/heads/master | 2022-01-08T10:24:08.201942 | 2018-05-02T07:19:03 | 2018-05-02T07:19:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 414 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QFileSystemWatcher>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void showMessage(const QString &path);
private:
Ui::MainWindow *ui;
QFileSystemWatcher myWatcher;
};
#endif // MAINWINDOW_H
| [
"chenyushen1989@163.com"
] | chenyushen1989@163.com |
d9e10e5434120bb813726f6bb1c3f1e7584f8210 | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /third_party/meerkat/Component/mmSH/attatic/ut_TunServer.cpp | a1125325807a1ba4b4c57163149bcbab1cc06a8d | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-flora-1.1"
] | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 2,119 | cpp | /*
* Copyright 2018 Samsung Electronics Co., Ltd
*
* Licensed under the Flora License, Version 1.1 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://floralicense.org/license/
*
* 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 "Debugger.h"
#include "bDataType.h"
#include "NetworkService.h"
#include "osal.h"
#define VTUN_DEV_LEN 20
int main(int argc, char** argv) {
InitDebugInfo(FALSE);
SetModuleDebugFlag(MODULE_ALL, TRUE);
SetDebugLevel(DEBUG_INFO);
SetDebugFormat(DEBUG_NORMAL);
if (argc < 3) {
RAW_PRINT("%s Launched with too few argument\n", argv[0]);
RAW_PRINT("%s Usage:\n", argv[0]);
RAW_PRINT("%s [server address] [stun port]:\n", argv[0]);
RAW_PRINT("eg. %s 192.168.0.100 5000\n", argv[0]);
return 0;
}
RAW_PRINT("\t******************************************\n");
RAW_PRINT("\t* Start up Tiny STUN/TURN Server *\n");
RAW_PRINT("\t******************************************\n");
CNetworkService* pService =
new CNetworkService("netservice", argv[1], (unsigned short)atoi(argv[2]));
pService->StartServer(5000, -1);
while (true) {
DPRINT(COMM, DEBUG_INFO, "Server Debugging Menu\n");
DPRINT(COMM, DEBUG_INFO, "table: Dump Route Mapping Table\n");
DPRINT(COMM, DEBUG_INFO, "relay: Dump Relay Channel Table\n");
DPRINT(COMM, DEBUG_INFO, "quit: quit server\n");
char input[32];
memset(input, 0, 32);
scanf("%s", input);
if (!strcmp(input, "table")) {
pService->DUMP_TABLE();
} else if (!strcmp(input, "relay")) {
pService->DUMP_CHANNEL();
} else {
DPRINT(COMM, DEBUG_INFO, "unknown request [%s]\n", input);
}
__OSAL_Sleep(1000);
}
pService->StopServer();
SAFE_DELETE(pService);
return 0;
}
| [
"35090305+younghajung@users.noreply.github.com"
] | 35090305+younghajung@users.noreply.github.com |
65e5d96a5fb059a5d2d6bc0021e0444ec53811a0 | 98b6bca8bf58996f296521921b63efc98aa98f93 | /Generate/utilities.hpp | 7f52bdc0b7409dabb3a0855f7c276ee2e97e6b9f | [] | no_license | liddyjacob/Parks | e4f0beb271fd66ee85d2e8b5b3cd6b46f8768e52 | 39a1c5d1aae6a6f0424e6deeb94e2b9c6290998e | refs/heads/master | 2020-04-08T09:45:56.086753 | 2018-12-19T21:22:38 | 2018-12-19T21:22:38 | 159,238,597 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 142 | hpp | #pragma once
#include <vector>
#include <utility>
std::vector<std::pair<int, int> > within_radius(int r, std::pair<int, int> point, int max);
| [
"liddyjacob@gmail.com"
] | liddyjacob@gmail.com |
05c7f66e69e9d251d3bb8cc1a51bd73ba657c64d | 11ee35b4dc8588c21ea9e75619fc9475e04c408d | /include/lexy/dsl/while.hpp | 5e3bd213739fd38a110bb897fb1737e29f24f945 | [
"BSL-1.0"
] | permissive | netcan/lexy | 7b258384756234135e7960e0b5dec1b0fba70d59 | 775e3d6bf1169ce13b08598d774e707c253f0792 | refs/heads/main | 2023-01-28T14:55:09.416540 | 2020-12-06T14:20:10 | 2020-12-06T16:17:25 | 318,488,104 | 0 | 0 | BSL-1.0 | 2020-12-04T10:55:56 | 2020-12-04T10:55:55 | null | UTF-8 | C++ | false | false | 4,951 | hpp | // Copyright (C) 2020 Jonathan Müller <jonathanmueller.dev@gmail.com>
// This file is subject to the license terms in the LICENSE file
// found in the top-level directory of this distribution.
#ifndef LEXY_DSL_WHILE_HPP_INCLUDED
#define LEXY_DSL_WHILE_HPP_INCLUDED
#include <lexy/dsl/base.hpp>
#include <lexy/dsl/branch.hpp>
#include <lexy/dsl/choice.hpp>
#include <lexy/dsl/loop.hpp>
namespace lexyd
{
template <typename Condition, typename Then>
struct _whl : rule_base
{
static constexpr auto has_matcher = Then::has_matcher;
struct matcher
{
template <typename Reader>
LEXY_DSL_FUNC bool match(Reader& reader)
{
auto save = reader;
while (Condition::matcher::match(reader))
{
if (!Then::matcher::match(reader))
{
reader = LEXY_MOV(save);
return false;
}
}
return true;
}
};
struct _rule : rule_base
{
static constexpr auto has_matcher = false;
template <typename NextParser>
struct parser
{
template <typename Handler, typename Reader, typename... Args>
LEXY_DSL_FUNC auto parse(_loop_handler<Handler>& handler, Reader& reader,
Args&&... args) -> typename _loop_handler<Handler>::result_type
{
if (!Condition::matcher::match(reader))
return LEXY_MOV(handler).break_();
return Then::template parser<NextParser>::parse(handler, reader, LEXY_FWD(args)...);
}
};
};
template <typename NextParser>
using parser = typename _loop<_rule>::template parser<NextParser>;
};
template <typename Pattern>
struct _whl<Pattern, void> : atom_base<_whl<Pattern, void>>
{
template <typename Reader>
LEXY_DSL_FUNC bool match(Reader& reader)
{
while (Pattern::matcher::match(reader))
{
}
return true;
}
template <typename Reader>
LEXY_DSL_FUNC void error(const Reader&, typename Reader::iterator);
};
/// Matches the pattern branch rule as often as possible.
template <typename Rule>
LEXY_CONSTEVAL auto while_(Rule rule)
{
static_assert(lexy::is_branch_rule<Rule>, "while() requires a branch condition");
if constexpr (lexy::is_pattern<Rule>)
{
(void)rule;
return _whl<Rule, void>{};
}
else
{
auto b = branch(rule);
return _whl<decltype(b.condition()), decltype(b.then())>{};
}
}
} // namespace lexyd
namespace lexyd
{
template <typename... R>
struct _whlc : rule_base
{
using _choice = _chc<R...>;
static constexpr auto has_matcher = _choice::has_matcher;
struct matcher
{
template <typename Rule, typename Reader>
LEXY_DSL_FUNC int _match(Reader& reader)
{
using as_branch = decltype(branch(Rule{}));
if (as_branch::condition_matcher::match(reader))
return as_branch::then_matcher::match(reader) ? 1 : 0;
else
return -1;
}
template <typename Reader>
LEXY_DSL_FUNC bool match(Reader& reader)
{
auto save = reader;
while (true)
{
int result = -1;
// Try to match all branches in turn, until we found one where the result isn't
// unmatched.
(void)((result = _match<R>(reader), result == -1 ? false : true) || ...);
if (result == -1)
// We no longer matched any condition, we are done.
break;
else if (result == 0)
{
// We had a match failure.
reader = LEXY_MOV(save);
return false;
}
}
return true;
}
};
template <typename NextParser>
using parser =
typename decltype(loop(_choice{} | else_ >> break_))::template parser<NextParser>;
};
/// Matches the choice as often as possible.
template <typename... R>
LEXY_CONSTEVAL auto while_(_chc<R...>)
{
return _whlc<R...>{};
}
} // namespace lexyd
namespace lexyd
{
/// Matches the rule at least once, then as often as possible.
template <typename Rule>
LEXY_CONSTEVAL auto while_one(Rule rule)
{
if constexpr (lexy::is_branch_rule<Rule>)
return rule >> while_(rule);
else
return rule + while_(rule);
}
/// Matches then once, then `while_(condition >> then)`.
template <typename Then, typename Condition>
LEXY_CONSTEVAL auto do_while(Then then, Condition condition)
{
if constexpr (lexy::is_branch_rule<Then>)
return then >> while_(condition >> then);
else
return then + while_(condition >> then);
}
} // namespace lexyd
#endif // LEXY_DSL_WHILE_HPP_INCLUDED
| [
"git@foonathan.net"
] | git@foonathan.net |
a24937a61b359d465ec6c54a6e2b47109fb05425 | 95deccf3e3646e75af236d6d0cc406381738e0d2 | /src/main/include/FRCLogger.h | cf478ba614869a7b8560ee983bf98aa1ffc4298b | [] | no_license | robowolves/2019_FRC_Code | 673575b6ec9fb5608f05c12f1baab4fc8b270464 | 05d1f3abb68bee59b013422ac0f2970ef811f321 | refs/heads/master | 2020-05-02T07:20:59.894094 | 2019-03-26T15:51:46 | 2019-03-26T15:51:46 | 177,815,564 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 765 | h | #pragma once
#include <iostream>
#include <string>
#include <fstream>
#include <ctime>
#include <chrono>
#include <mutex>
#include <frc/DriverStation.h>
#include "Constants.h"
using namespace RobotConstants::FRCLogger;
class FRCLogger
{
public:
FRCLogger(frc::DriverStation&);
FRCLogger(frc::DriverStation&, std::string);
~FRCLogger();
virtual void postMessage(logType, std::string);
virtual void postMessage(logType, int, std::string);
void enableFileLogging(bool);
bool getIsFileLogging();
void overideCompetitionMode(bool);
bool getIsInCompetitionMode();
private:
std::string getCurrentTime();
protected:
bool isFileLoggingEnabled = false;
std::string logFilePath = "";
bool isCompetitionModeEnabled = false;
std::mutex timeMutex;
};
| [
"evan_calderon@yahoo.com"
] | evan_calderon@yahoo.com |
2da5fbcace9df673a33a598878dde7e3a868dedb | 78ff78a3591b6b2cbf6c6c31daf7ec6f2a8bc327 | /src/Main.cpp | 6dad90f61dc77f9c919763c088983999728c4c0c | [] | no_license | anitnerolf/206neutrinos_2019 | 9bd3ea1cce36486f416f5d061d12c4961b4f20fa | 72222226fea5a2097b036e9bc2d9ded32d2f6f11 | refs/heads/master | 2022-11-15T00:14:17.711327 | 2020-07-14T19:38:12 | 2020-07-14T19:38:12 | 279,676,133 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,205 | cpp | /*
** EPITECH PROJECT, 2020
** neutrinos
** File description:
** main
*/
#include "../include/Neutrinos.hpp"
#include <iostream>
#include <cstring>
#include <string>
int main(int ac, char **av)
{
if (ac == 2 && strcmp(av[1], "-h") == 0) {
print_usage();
} else if (ac == 5) {
return (get_arguments(ac, av));
} else {
print_usage();
return 84;
}
return 0;
}
void print_usage(void)
{
std::cout << "USAGE\n\t./206neutrinos n a h sd\n" << std::endl;
std::cout << "DESCRIPTION\n\tn\tnumber of values" << std::endl;
std::cout << "\ta\tarithmetic mean" << std::endl;
std::cout << "\th\tharmonic mean" << std::endl;
std::cout << "\tsd\tstandard deviation" << std::endl;
}
int get_arguments(int ac, char **av)
{
Neutrinos n;
for (int i = 1; i < ac; i++) {
if (check_if_number(av[i]) != 0) {
std::cout << "You must enter positive number!" << std::endl;
return (84);
}
}
return (n.SaveValues(av));
}
int check_if_number(std::string str)
{
int i = 0;
while (str[i] != '\0') {
if (str[i] > 57 || str[i] < 48)
return 84;
i++;
}
return 0;
}
| [
"florentina.vojvoda@epitech.eu"
] | florentina.vojvoda@epitech.eu |
4ae1c4d16ccf4fb9450ca11ad74216f86df777b4 | 130ba97dd1c5adffe9cdb4922baa3b01bc24b078 | /stack.hpp | 40d388cca5f1cfda01ec90fac0741b6c16a0e948 | [] | no_license | Afaqa/stl_containers | e0a5906acd14cfe534b4d0db61c4773026e1ceb9 | c70287349fdceca7e38e86fa5fc5aa302e27d7af | refs/heads/master | 2023-06-24T21:05:23.926603 | 2021-07-07T18:48:36 | 2021-07-07T18:48:36 | 349,693,337 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,030 | hpp | #ifndef STACK_HPP
#define STACK_HPP
#include "list.hpp"
namespace stl {
template<class T, class Container = list <T> >
class stack {
public:
typedef T value_type;
typedef Container container_type;
typedef typename container_type::size_type size_type;
explicit stack(const container_type &ctnr = container_type())
: _container(ctnr) {
}
bool empty() const {
return _container.empty();
}
size_type size() const {
return _container.size();
}
value_type &top() {
return _container.back();
}
const value_type &top() const {
return _container.back();
}
void push(const value_type &val) {
_container.push_back(val);
}
void pop() {
_container.pop_back();
}
protected:
container_type _container;
template<class T1, class C1>
friend bool operator==(const stack<T1, C1> &lhs,
const stack<T1, C1> &rhs);
template<class T1, class C1>
friend bool operator!=(const stack<T1, C1> &lhs,
const stack<T1, C1> &rhs);
template<class T1, class C1>
friend bool operator<(const stack<T1, C1> &lhs,
const stack<T1, C1> &rhs);
template<class T1, class C1>
friend bool operator<=(const stack<T1, C1> &lhs,
const stack<T1, C1> &rhs);
template<class T1, class C1>
friend bool operator>(const stack<T1, C1> &lhs,
const stack<T1, C1> &rhs);
template<class T1, class C1>
friend bool operator>=(const stack<T1, C1> &lhs,
const stack<T1, C1> &rhs);
};
template<class T, class Container>
bool
operator==(const stack<T, Container> &lhs, const stack<T, Container> &rhs) {
return lhs._container == rhs._container;
}
template<class T, class Container>
bool
operator!=(const stack<T, Container> &lhs, const stack<T, Container> &rhs) {
return lhs._container != rhs._container;
}
template<class T, class Container>
bool
operator<(const stack<T, Container> &lhs, const stack<T, Container> &rhs) {
return lhs._container < rhs._container;
}
template<class T, class Container>
bool
operator<=(const stack<T, Container> &lhs, const stack<T, Container> &rhs) {
return lhs._container <= rhs._container;
}
template<class T, class Container>
bool
operator>(const stack<T, Container> &lhs, const stack<T, Container> &rhs) {
return lhs._container > rhs._container;
}
template<class T, class Container>
bool
operator>=(const stack<T, Container> &lhs, const stack<T, Container> &rhs) {
return lhs._container >= rhs._container;
}
}
#endif
| [
"itressa@student.21-school.ru"
] | itressa@student.21-school.ru |
85a57aec923f8eb598ce19514c385bc0cf9546e6 | 41b4adb10cc86338d85db6636900168f55e7ff18 | /aws-cpp-sdk-cloudfront/include/aws/cloudfront/model/Restrictions.h | 98e62bfe060ed98a271acf70e6d0fffb207a81f1 | [
"JSON",
"MIT",
"Apache-2.0"
] | permissive | totalkyos/AWS | 1c9ac30206ef6cf8ca38d2c3d1496fa9c15e5e80 | 7cb444814e938f3df59530ea4ebe8e19b9418793 | refs/heads/master | 2021-01-20T20:42:09.978428 | 2016-07-16T00:03:49 | 2016-07-16T00:03:49 | 63,465,708 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,970 | h | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/cloudfront/CloudFront_EXPORTS.h>
#include <aws/cloudfront/model/GeoRestriction.h>
namespace Aws
{
namespace Utils
{
namespace Xml
{
class XmlNode;
} // namespace Xml
} // namespace Utils
namespace CloudFront
{
namespace Model
{
/**
* A complex type that identifies ways in which you want to restrict distribution
* of your content.
*/
class AWS_CLOUDFRONT_API Restrictions
{
public:
Restrictions();
Restrictions(const Aws::Utils::Xml::XmlNode& xmlNode);
Restrictions& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);
void AddToNode(Aws::Utils::Xml::XmlNode& parentNode) const;
inline const GeoRestriction& GetGeoRestriction() const{ return m_geoRestriction; }
inline void SetGeoRestriction(const GeoRestriction& value) { m_geoRestrictionHasBeenSet = true; m_geoRestriction = value; }
inline void SetGeoRestriction(GeoRestriction&& value) { m_geoRestrictionHasBeenSet = true; m_geoRestriction = value; }
inline Restrictions& WithGeoRestriction(const GeoRestriction& value) { SetGeoRestriction(value); return *this;}
inline Restrictions& WithGeoRestriction(GeoRestriction&& value) { SetGeoRestriction(value); return *this;}
private:
GeoRestriction m_geoRestriction;
bool m_geoRestrictionHasBeenSet;
};
} // namespace Model
} // namespace CloudFront
} // namespace Aws
| [
"henso@amazon.com"
] | henso@amazon.com |
65f701b9859e4ad09824a0835c894c5ae9e0d7c9 | e7a9a9321b6dca5821a8622d7400556500563bc9 | /53_Maximum_Subarray.cc | 311e994b33a9dfd36b26230a6c6d024a35bc4d9b | [] | no_license | cpppy/leetcode | 0933f11e5de038dcb94d1aa8394a3fab230ea49b | 4edb308097ba7f8cdc46e6856ca98757eee6fa0f | refs/heads/master | 2020-05-22T03:59:18.464763 | 2016-09-21T12:33:54 | 2016-09-21T12:33:54 | 65,656,516 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 300 | cc | class Solution {
public:
int maxSubArray(vector<int>& nums) {
if(nums.size()==0) return 0;
int tmp=nums[0];
int res=tmp;
for(int i=1;i<nums.size();++i){
tmp=max(nums[i],tmp+nums[i]);
res=max(res,tmp);
}
return res;
}
};
| [
"noreply@github.com"
] | noreply@github.com |
a0f0c9cc9ffcd9fc5e84d23e3bdc102414b4d425 | b127a615439cade1d0262f630371c6cbca8a5898 | /src/see/mat.h | 008d0817a33abd3c5c66ddc15b1c05567a4ef532 | [] | no_license | ZhangWeiguo/see | 9cb41ae76dfaf64d30ade66fa6703bd1071e6c59 | 2e0462ee8bdab64d2ec8286c791f20340649cf54 | refs/heads/master | 2022-11-08T03:17:23.584389 | 2020-06-27T16:27:23 | 2020-06-27T16:27:23 | 111,185,890 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,806 | h | #pragma once
#include <initializer_list>
#include <iomanip>
#include <iostream>
#include <map>
#include <random>
#include <set>
#include <vector>
#include "algorithm"
#include "math.h"
#include "omp.h"
#include "stdio.h"
#include "time.h"
#include "utils.h"
using namespace std;
namespace see {
typedef vector<vector<double>> DoubleMat;
typedef vector<vector<int>> IntMat;
template <class T>
vector<vector<T>> ZerosMat(int m, int n) {
vector<vector<T>> v(m, vector<T>(n, 0));
return v;
}
template <class T>
vector<vector<T>> OnesMat(int m, int n) {
vector<vector<T>> v(m, vector<T>(n, 1));
return v;
}
template <class T>
vector<vector<T>> RandomMat(int m, int n, T min_value = 0, T max_value = 1) {
vector<vector<T>> v;
default_random_engine e;
uniform_real_distribution<double> uniform_random(min_value, max_value);
time_t now;
time(&now);
e.seed(now);
for (int i = 0; i < m; i++) {
vector<T> v1 = vector<T>(n, 1);
for (int j = 0; j < n; j++) {
v1[j] = (T)(uniform_random(e));
}
v.push_back(v1);
}
return v;
}
template <class T>
vector<vector<T>> EyesMat(int m) {
vector<vector<T>> v = ZerosMat<T>(m, m);
for (int i = 0; i < m; i++) v[i][i] = 1;
return v;
}
template <class T> // m = apply(a)
void MatApply(vector<vector<T>>& m, T fun(T a)) {
for (auto i = m.begin(); i != m.end(); i++) {
for (auto j = i->begin(); j != i->end(); j++) {
*j = fun(*j);
}
}
}
template <class T>
void MatSum(vector<vector<T>>& m, vector<vector<T>>& n, bool x) {
m.clear();
if (x) {
if (n.size() == 0) return;
m = vector<T>(0, n[0].size());
for (int i = 0; i < n[0].size(); i++) {
m[i] = 0;
for (int j = 0; j < n.size(); j++) {
m[i] += n[j][i];
}
}
} else {
m = vector<T>(0, n.size());
for (int i = 0; i < n.size(); i++) {
m[i] = 0;
for (int j = 0; j < n[i].size(); j++) {
m[i] += n[i][j];
}
}
}
}
template <class T>
void MatSum(T& m, vector<vector<T>>& n) {
m = 0;
for (int i = 0; i < n.size(); i++) {
for (int j = i + 1; j < n[i].size(); j++) {
m += n[i][j];
}
}
}
template <class T>
void MatAvg(vector<T>& m, vector<vector<T>>& n, bool x) {
m.clear();
int k;
if (x) {
if (n.size() == 0) return;
m = vector<T>(n[0].size(), 0);
for (int i = 0; i < n[0].size(); i++) {
m[i] = 0;
k = 0;
for (int j = 0; j < n.size(); j++) {
m[i] += n[j][i];
k++;
}
m[i] = m[i] / k;
}
} else {
m = vector<T>(n.size(), 0);
for (int i = 0; i < n.size(); i++) {
m[i] = 0;
k = 0;
for (int j = 0; j < n[i].size(); j++) {
m[i] += n[i][j];
k++;
}
m[i] = m[i] / k;
}
}
}
template <class T>
void MatAvg(T& m, vector<vector<T>>& n) {
m = 0;
int k = 0;
for (int i = 0; i < n.size(); i++) {
for (int j = i + 1; j < n[i].size(); j++) {
m += n[i][j];
k++;
}
}
m = m / k;
}
template <class T> // m = m + a
void MatAdd(vector<vector<T>>& m, double a) {
for (auto i = m.begin(); i != m.end(); i++) {
for (auto j = i->begin(); j != i->end(); j++) {
*j += a;
}
}
}
template <class T> // m = m + n
void MatAdd(vector<vector<T>>& m, vector<vector<T>>& n) {
for (int i = 0; i < m.size(); i++) {
for (int j = 0; j < m[i].size(); j++) {
m[i][j] += n[i][j];
}
}
}
template <class T> // n = m1 + m2
void MatAdd(vector<vector<T>>& n, vector<vector<T>>& m1,
vector<vector<T>>& m2) {
for (int i = 0; i < m1.size(); i++) {
for (int j = 0; j < m1[i].size(); j++) {
n[i][j] = m1[i][j] + m2[i][j];
}
}
}
template <class T> // n = m1 + m2
void MatAdd(vector<vector<T>>& n, vector<vector<T>>& m1, vector<T>& m2,
bool x) {
for (int i = 0; i < m1.size(); i++) {
for (int j = 0; j < m1[i].size(); j++) {
if (x)
n[i][j] = m1[i][j] + m2[j];
else
n[i][j] = m1[i][j] + m2[i];
}
}
}
template <class T> // n = m + a
void MatAdd(vector<vector<T>>& n, vector<vector<T>>& m, double a) {
for (int i = 0; i < m.size(); i++) {
for (int j = 0; j < m[i].size(); j++) {
n[i][j] = m[i][j] + a;
}
}
}
template <class T> // n = w0 + w1 * m1
void MatAdd(vector<vector<T>>& n, vector<vector<T>>& m1, T w0, T w1) {
for (int i = 0; i < m1.size(); i++) {
for (int j = 0; j < m1[i].size(); j++) {
n[i][j] = w0 + w1 * m1[i][j];
}
}
}
template <class T> // n = w0 + w1 * m1 + w2 * m2
void MatAdd(vector<vector<T>>& n, vector<vector<T>>& m1, vector<vector<T>>& m2,
T w0, T w1, T w2) {
for (int i = 0; i < m1.size(); i++) {
for (int j = 0; j < m1[i].size(); j++) {
n[i][j] = w0 + w1 * m1[i][j] + w2 * m2[i][j];
}
}
}
template <class T> // n = w0 + w1 * m1 + w2 * m2 + w3 * m3
void MatAdd(vector<vector<T>>& n, vector<vector<T>>& m1, vector<vector<T>>& m2,
vector<vector<T>>& m3, T w0, T w1, T w2, T w3) {
for (int i = 0; i < m1.size(); i++) {
for (int j = 0; j < m1[i].size(); j++) {
n[i][j] = w0 + w1 * m1[i][j] + w2 * m2[i][j] + w3 * m3[i][j];
}
}
}
template <class T> // n = w0 + w1 * m1 + w2 * m2 + w3 * m3 + w4 * m4
void MatAdd(vector<vector<T>>& n, vector<vector<T>>& m1, vector<vector<T>>& m2,
vector<vector<T>>& m3, vector<vector<T>>& m4, T w0, T w1, T w2,
T w3, T w4) {
for (int i = 0; i < m1.size(); i++) {
for (int j = 0; j < m1[i].size(); j++) {
n[i][j] =
w0 + w1 * m1[i][j] + w2 * m2[i][j] + w3 * m3[i][j] + w4 * m4[i][j];
}
}
}
template <class T> // n = w0 + w1 * m1 + w2 * m2 + w3 * m3 + w4 * m4 + w5 * m5
void MatAdd(vector<vector<T>>& n, vector<vector<T>>& m1, vector<vector<T>>& m2,
vector<vector<T>>& m3, vector<vector<T>>& m4, vector<vector<T>>& m5,
T w0, T w1, T w2, T w3, T w4, T w5) {
for (int i = 0; i < m1.size(); i++) {
for (int j = 0; j < m1[i].size(); j++) {
n[i][j] = w0 + w1 * m1[i][j] + w2 * m2[i][j] + w3 * m3[i][j] +
w4 * m4[i][j] + w5 * m5[i][j];
}
}
}
template <class T> // m = m * a
void MatMut(vector<vector<T>>& m, double a) {
for (auto i = m.begin(); i != m.end(); i++) {
for (auto j = i->begin(); j != i->end(); j++) {
*j = (*j) * a;
}
}
}
template <class T> // n = m * a
void MatMut(vector<vector<T>>& n, vector<vector<T>>& m, double a) {
for (int i = 0; i < m.size(); i++) {
for (int j = 0; j < m[i].size(); j++) {
n[i][j] = m[i][j] * a;
}
}
}
template <class T> // m = m * n
void MatMut(vector<vector<T>>& m, vector<vector<T>>& n) {
for (int i = 0; i < m.size(); i++) {
for (int j = 0; j < m[i].size(); j++) {
m[i][j] = m[i][j] * n[i][j];
}
}
}
template <class T> // n = m1 * m2
void MatMut(vector<vector<T>>& n, vector<vector<T>>& m1,
vector<vector<T>>& m2) {
for (int i = 0; i < m1.size(); i++) {
for (int j = 0; j < m1[i].size(); j++) {
n[i][j] = m1[i][j] * m2[i][j];
}
}
}
template <class T> // n = m1 dot m2
void MatDot(vector<vector<T>>& n, vector<vector<T>>& m1,
vector<vector<T>>& m2) {
for (int i = 0; i < n.size(); i++) {
for (int j = 0; j < n[i].size(); j++) {
n[i][j] = 0;
for (int p = 0; p < m1[i].size(); p++) {
n[i][j] += m1[i][p] * m2[p][j];
}
}
}
}
template <class T> // n = m1 T
void MatTranspose(vector<vector<T>>& n, vector<vector<T>>& m) {
for (int i = 0; i < m.size(); i++) {
for (int j = 0; j < m[i].size(); j++) {
n[j][i] = m[i][j];
}
}
}
template <class T>
void MatPrint(vector<vector<T>>& m, int p = 10, int q = 10) {
int p0 = 0, q0 = 0;
for (auto i = m.begin(); i != m.end(); i++) {
if (p0++ >= p) break;
q0 = 0;
for (auto j = i->begin(); j != i->end(); j++) {
if (q0++ >= q) break;
cout << left << setw(10) << *j << " ";
}
cout << endl;
}
}
// 有时候看着丑的东东往往效率高, 越直接越经得起推敲, 不建议使用 initializer_list
template <class T> // m = ns x ws
void MatApply(vector<vector<T>>& m, initializer_list<vector<vector<T>>>& ns,
initializer_list<T> ws) {
for (int i = 0; i < m.size(); i++) {
for (int j = 0; j < m[i].size(); j++) {
m[i][j] = 0;
int k = 0;
while (k < ws.size()) {
m[i][j] += (*(ns.begin() + k))[i][j] * *(ws.begin() + k);
k++;
}
}
}
}
template <class T> // m = ns x ws + m * w
void MatApply(vector<vector<T>>& m, initializer_list<vector<vector<T>>>& ns,
initializer_list<T> ws, T w) {
for (int i = 0; i < m.size(); i++) {
for (int j = 0; j < m[i].size(); j++) {
int k = 0;
m[i][j] = m[i][j] * w;
while (k < ws.size()) {
m[i][j] += (*(ns.begin() + k))[i][j] * *(ws.begin() + k);
k++;
}
}
}
}
template <class T> // m = fun(n1)
void MatApply(vector<vector<T>>& m, vector<vector<T>>& n1, T fun(T)) {
for (int i = 0; i < m.size(); i++) {
for (int j = 0; j < m[i].size(); j++) {
m[i][j] = fun(n1[i][j]);
}
}
}
template <class T> // m = fun(m, n1)
void MatApply(vector<vector<T>>& m, vector<vector<T>>& n1, T fun(T, T)) {
for (int i = 0; i < m.size(); i++) {
for (int j = 0; j < m[i].size(); j++) {
m[i][j] = fun(m[i][j], n1[i][j]);
}
}
}
template <class T> // m = fun(n1, n2)
void MatApply(vector<vector<T>>& m, vector<vector<T>>& n1,
vector<vector<T>>& n2, T fun(T, T)) {
for (int i = 0; i < m.size(); i++) {
for (int j = 0; j < m[i].size(); j++) {
m[i][j] = fun(n1[i][j], n2[i][j]);
}
}
}
template <class T> // m = fun(m, n1, n2)
void MatApply(vector<vector<T>>& m, vector<vector<T>>& n1,
vector<vector<T>>& n2, T fun(T, T, T)) {
for (int i = 0; i < m.size(); i++) {
for (int j = 0; j < m[i].size(); j++) {
m[i][j] = fun(m[i][j], n1[i][j], n2[i][j]);
}
}
}
template <class T> // m = fun(n1, n2, n3)
void MatApply(vector<vector<T>>& m, vector<vector<T>>& n1,
vector<vector<T>>& n2, vector<vector<T>>& n3, T fun(T, T, T)) {
for (int i = 0; i < m.size(); i++) {
for (int j = 0; j < m[i].size(); j++) {
m[i][j] = fun(n1[i][j], n2[i][j], n3[i][j]);
}
}
}
template <class T> // m = fun(m, n1, n2, n3)
void MatApply(vector<vector<T>>& m, vector<vector<T>>& n1,
vector<vector<T>>& n2, vector<vector<T>>& n3, T fun(T, T, T, T)) {
for (int i = 0; i < m.size(); i++) {
for (int j = 0; j < m[i].size(); j++) {
m[i][j] = fun(m[i][j], n1[i][j], n2[i][j], n3[i][j]);
}
}
}
template <class T> // m = fun(n1, n2, n3, n4)
void MatApply(vector<vector<T>>& m, vector<vector<T>>& n1,
vector<vector<T>>& n2, vector<vector<T>>& n3,
vector<vector<T>>& n4, T fun(T, T, T, T)) {
for (int i = 0; i < m.size(); i++) {
for (int j = 0; j < m[i].size(); j++) {
m[i][j] = fun(n1[i][j], n2[i][j], n3[i][j], n4[i][j]);
}
}
}
template <class T> // m = fun(m, n1, n2, n3, n4)
void MatApply(vector<vector<T>>& m, vector<vector<T>>& n1,
vector<vector<T>>& n2, vector<vector<T>>& n3,
vector<vector<T>>& n4, T fun(T, T, T, T, T)) {
for (int i = 0; i < m.size(); i++) {
for (int j = 0; j < m[i].size(); j++) {
m[i][j] = fun(m[i][j], n1[i][j], n2[i][j], n3[i][j], n4[i][j]);
}
}
}
} // namespace see
| [
"zhangweiguo717@163.com"
] | zhangweiguo717@163.com |
204bb3493f0eeb005ef2c04593736fee706b5d40 | ea401c3e792a50364fe11f7cea0f35f99e8f4bde | /released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/gui/ext/boost/math/special_functions/asinh.hpp | 0534f550d4006c8b254b8bef91bb9190b1e1e91a | [
"BSD-2-Clause",
"BSL-1.0",
"MIT",
"GPL-1.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"GPL-2.0-only"
] | permissive | Vaa3D/vaa3d_tools | edb696aa3b9b59acaf83d6d27c6ae0a14bf75fe9 | e6974d5223ae70474efaa85e1253f5df1814fae8 | refs/heads/master | 2023-08-03T06:12:01.013752 | 2023-08-02T07:26:01 | 2023-08-02T07:26:01 | 50,527,925 | 107 | 86 | MIT | 2023-05-22T23:43:48 | 2016-01-27T18:19:17 | C++ | UTF-8 | C++ | false | false | 4,014 | hpp | // boost asinh.hpp header file
// (C) Copyright Eric Ford & Hubert Holin 2001.
// (C) Copyright John Maddock 2008.
// 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)
// See http://www.boost.org for updates, documentation, and revision history.
#ifndef BOOST_ASINH_HPP
#define BOOST_ASINH_HPP
#ifdef _MSC_VER
#pragma once
#endif
#include <boost/config/no_tr1/cmath.hpp>
#include <boost/config.hpp>
#include <boost/math/tools/precision.hpp>
#include <boost/math/special_functions/math_fwd.hpp>
#include <boost/math/special_functions/sqrt1pm1.hpp>
#include <boost/math/special_functions/log1p.hpp>
#include <boost/math/constants/constants.hpp>
// This is the inverse of the hyperbolic sine function.
namespace boost
{
namespace math
{
namespace detail{
#if defined(__GNUC__) && (__GNUC__ < 3)
// gcc 2.x ignores function scope using declarations,
// put them in the scope of the enclosing namespace instead:
using ::std::abs;
using ::std::sqrt;
using ::std::log;
using ::std::numeric_limits;
#endif
template<typename T, class Policy>
inline T asinh_imp(const T x, const Policy& pol)
{
BOOST_MATH_STD_USING
if (x >= tools::forth_root_epsilon<T>())
{
if (x > 1 / tools::root_epsilon<T>())
{
// http://functions.wolfram.com/ElementaryFunctions/ArcSinh/06/01/06/01/0001/
// approximation by laurent series in 1/x at 0+ order from -1 to 1
return constants::ln_two<T>() + log(x) + 1/ (4 * x * x);
}
else if(x < 0.5f)
{
// As below, but rearranged to preserve digits:
return boost::math::log1p(x + boost::math::sqrt1pm1(x * x, pol), pol);
}
else
{
// http://functions.wolfram.com/ElementaryFunctions/ArcSinh/02/
return( log( x + sqrt(x*x+1) ) );
}
}
else if (x <= -tools::forth_root_epsilon<T>())
{
return(-asinh(-x, pol));
}
else
{
// http://functions.wolfram.com/ElementaryFunctions/ArcSinh/06/01/03/01/0001/
// approximation by taylor series in x at 0 up to order 2
T result = x;
if (abs(x) >= tools::root_epsilon<T>())
{
T x3 = x*x*x;
// approximation by taylor series in x at 0 up to order 4
result -= x3/static_cast<T>(6);
}
return(result);
}
}
}
template<typename T>
inline typename tools::promote_args<T>::type asinh(T x)
{
return boost::math::asinh(x, policies::policy<>());
}
template<typename T, typename Policy>
inline typename tools::promote_args<T>::type asinh(T x, const Policy&)
{
typedef typename tools::promote_args<T>::type result_type;
typedef typename policies::evaluation<result_type, Policy>::type value_type;
typedef typename policies::normalise<
Policy,
policies::promote_float<false>,
policies::promote_double<false>,
policies::discrete_quantile<>,
policies::assert_undefined<> >::type forwarding_policy;
return policies::checked_narrowing_cast<result_type, forwarding_policy>(
detail::asinh_imp(static_cast<value_type>(x), forwarding_policy()),
"boost::math::asinh<%1%>(%1%)");
}
}
}
#endif /* BOOST_ASINH_HPP */
| [
"hanchuan.peng@gmail.com"
] | hanchuan.peng@gmail.com |
0ac2f642e9d0f9db90537e8da6532b63e57d90b3 | 1ae6521d5b7379b0f544776212d842597b53fa16 | /leetcode/294_Flip_Game_II/fgii.cpp | 623e76a81f128bc2567cd8745750a4cea49f12f3 | [] | no_license | logantsai/On_the_way | 5ee57be46469d826557b1dd68695a9e0a6807796 | c2bd1265b395d96e8403a5995ad55a62f1bc1f62 | refs/heads/master | 2021-06-09T16:42:48.135902 | 2019-08-20T07:55:09 | 2019-08-20T07:55:09 | 133,130,276 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,108 | cpp | #include <iostream>
#include <vector>
using namespace std;
/*
You are playing the following Flip Game with your friend: Given a string
that contains only these two characters: + and -, you and your friend take
turns to flip twoconsecutive "++" into "--". The game ends when a person
can no longer make a move and therefore the other person will be the winner.
Write a function to determine if the starting player can guarantee a win.
For example, given s = "++++", return true. The starting player can guarantee
a win by flipping the middle "++" to become "+--+".
Follow up:
Derive your algorithm's runtime complexity.
*/
/* 題目只要我們找出先手是不是能直接勝 */
class Solution {
public:
static bool canWin(string s) {
for (int i = 1; i < s.size(); ++i) {
if (s[i] == '+' && s[i - 1] == '+' &&
!canWin(s.substr(0, i - 1) + "--" + s.substr(i + 1))) { // 剩下的字串
cout << s.substr(0, i - 1) + "--" + s.substr(i + 1) << endl;
return true;
}
}
return false;
}
};
int main()
{
string s("++++");
cout << Solution::canWin(s) << endl;
return 0;
}
| [
"Mark.Tsai@quantatw.com"
] | Mark.Tsai@quantatw.com |
efd9adef330170ed02d7a33bc875a7e79c0ba0e5 | 412cbb041e1e2f0b7a8c9571f71863ebf4574879 | /src/rpcmining.cpp | c2c7642cb83469d770037df5662a565766947e3a | [
"MIT"
] | permissive | moriowanibe/coupecoin | e8bdbc773aa23bb28e19490623727663d0c49a8e | 73f24caf3947e66dea02121c51d8cb7381eb4cb2 | refs/heads/master | 2020-03-11T01:54:17.306884 | 2018-02-10T16:54:47 | 2018-02-10T16:54:47 | 129,704,921 | 7 | 0 | null | 2018-04-16T07:46:56 | 2018-04-16T07:46:56 | null | UTF-8 | C++ | false | false | 24,148 | 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 "main.h"
#include "db.h"
#include "txdb.h"
#include "init.h"
#include "miner.h"
#include "kernel.h"
#include "bitcoinrpc.h"
#include <boost/format.hpp>
#include <boost/assign/list_of.hpp>
#include <boost/iterator/counting_iterator.hpp>
using namespace json_spirit;
using namespace std;
extern uint256 nPoWBase;
extern uint64_t nStakeInputsMapSize;
Value getsubsidy(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1 || fHelp || params.size() < 99 )
throw runtime_error(
"getsubsidy [nTarget]\n"
"Currently not in use.");
unsigned int nBits = 0;
if (params.size() != 0)
{
CBigNum bnTarget(uint256(params[0].get_str()));
nBits = bnTarget.GetCompact();
}
else
{
nBits = GetNextTargetRequired(pindexBest, false);
}
return (uint64_t)GetProofOfWorkReward(nBits, 0, 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.");
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(GetLastBlockIndex(pindexBest, false)->nBits, 0, pindexBest->nHeight)));
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()));
obj.push_back(Pair("stakeinputs", (uint64_t)nStakeInputsMapSize));
obj.push_back(Pair("stakeinterest", GetProofOfStakeReward(0, GetLastBlockIndex(pindexBest, true)->nBits, GetLastBlockIndex(pindexBest, true)->nTime, true)));
obj.push_back(Pair("testnet", fTestNet));
return obj;
}
// scaninput '{"txid":"95d640426fe66de866a8cf2d0601d2c8cf3ec598109b4d4ffa7fd03dad6d35ce","difficulty":0.01, "days":10}'
Value scaninput(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"scaninput '{\"txid\":\"txid\", \"vout\":[vout1, vout2, ..., voutN], \"difficulty\":difficulty, \"days\":days}'\n"
"Scan specified transaction or input for suitable kernel solutions.\n"
" difficulty - upper limit for difficulty, current difficulty by default;\n"
" days - time window, 90 days by default.\n"
);
RPCTypeCheck(params, boost::assign::list_of(obj_type));
Object scanParams = params[0].get_obj();
const Value& txid_v = find_value(scanParams, "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");
uint256 hash(txid);
int32_t nDays = 90;
uint32_t nBits = GetNextTargetRequired(pindexBest, true);
const Value& diff_v = find_value(scanParams, "difficulty");
if (diff_v.type() == real_type || diff_v.type() == int_type)
{
double dDiff = diff_v.get_real();
if (dDiff <= 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, diff must be greater than zero");
CBigNum bnTarget(nPoWBase);
bnTarget *= 1000;
bnTarget /= (int) (dDiff * 1000);
nBits = bnTarget.GetCompact();
}
const Value& days_v = find_value(scanParams, "days");
if (days_v.type() == int_type)
{
nDays = days_v.get_int();
if (nDays <= 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, interval length must be greater than zero");
}
CTransaction tx;
uint256 hashBlock = 0;
if (GetTransaction(hash, tx, hashBlock))
{
if (hashBlock == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to find transaction in the blockchain");
vector<int> vInputs(0);
const Value& inputs_v = find_value(scanParams, "vout");
if (inputs_v.type() == array_type)
{
Array inputs = inputs_v.get_array();
BOOST_FOREACH(const Value &v_out, inputs)
{
int nOut = v_out.get_int();
if (nOut < 0 || nOut > (int)tx.vout.size() - 1)
{
stringstream strErrorMsg;
strErrorMsg << boost::format("Invalid parameter, input number %d is out of range") % nOut;
throw JSONRPCError(RPC_INVALID_PARAMETER, strErrorMsg.str());
}
vInputs.push_back(nOut);
}
}
else if(inputs_v.type() == int_type)
{
int nOut = inputs_v.get_int();
if (nOut < 0 || nOut > (int)tx.vout.size() - 1)
{
stringstream strErrorMsg;
strErrorMsg << boost::format("Invalid parameter, input number %d is out of range") % nOut;
throw JSONRPCError(RPC_INVALID_PARAMETER, strErrorMsg.str());
}
vInputs.push_back(nOut);
}
else
{
vInputs = vector<int>(boost::counting_iterator<int>( 0 ), boost::counting_iterator<int>( tx.vout.size() ));
}
CTxDB txdb("r");
CBlock block;
CTxIndex txindex;
// Load transaction index item
if (!txdb.ReadTxIndex(tx.GetHash(), txindex))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to read block index item");
// Read block header
if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "CBlock::ReadFromDisk() failed");
uint64_t nStakeModifier = 0;
if (!GetKernelStakeModifier(block.GetHash(), nStakeModifier))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No kernel stake modifier generated yet");
std::pair<uint32_t, uint32_t> interval;
interval.first = GetTime();
// Only count coins meeting min age requirement
if (nStakeMinAge + block.nTime > interval.first)
interval.first += (nStakeMinAge + block.nTime - interval.first);
interval.second = interval.first + nDays * nOneDay;
Array results;
BOOST_FOREACH(const int &nOut, vInputs)
{
// Check for spent flag
// It doesn't make sense to scan spent inputs.
if (!txindex.vSpent[nOut].IsNull())
continue;
// Skip zero value outputs
if (tx.vout[nOut].nValue == 0)
continue;
// Build static part of kernel
CDataStream ssKernel(SER_GETHASH, 0);
ssKernel << nStakeModifier;
ssKernel << block.nTime << (txindex.pos.nTxPos - txindex.pos.nBlockPos) << tx.nTime << nOut;
CDataStream::const_iterator itK = ssKernel.begin();
std::vector<std::pair<uint256, uint32_t> > result;
if (ScanKernelForward((unsigned char *)&itK[0], nBits, tx.nTime, tx.vout[nOut].nValue, interval, result))
{
BOOST_FOREACH(const PAIRTYPE(uint256, uint32_t) solution, result)
{
Object item;
item.push_back(Pair("nout", nOut));
item.push_back(Pair("hash", solution.first.GetHex()));
item.push_back(Pair("time", DateTimeStrFormat(solution.second)));
results.push_back(item);
}
}
}
if (results.size() == 0)
return false;
return results;
}
else
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
}
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, "Coupecoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(-10, "Coupecoin is downloading blocks...");
if (pindexBest->nHeight >= LAST_POW_BLOCK)
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;
static CReserveKey reservekey(pwalletMain);
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64_t nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != 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 = nTransactionsUpdated;
pindexPrev = pindexBest;
nStart = GetTime();
// Create new block
pblock = CreateNewBlock(pwalletMain);
if (!pblock)
throw JSONRPCError(-7, "Out of memory");
vNewBlock.push_back(pblock);
}
// Update nTime
pblock->nTime = max(pindexPrev->GetMedianTimePast()+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();
return CheckWork(pblock, *pwalletMain, reservekey);
}
}
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, "Coupecoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Coupecoin is downloading blocks...");
if (pindexBest->nHeight >= LAST_POW_BLOCK)
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;
static CReserveKey reservekey(pwalletMain);
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64_t nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != 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 = nTransactionsUpdated;
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
pblock = CreateNewBlock(pwalletMain);
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();
return CheckWork(pblock, *pwalletMain, reservekey);
}
}
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, "Coupecoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Coupecoin is downloading blocks...");
if (pindexBest->nHeight >= LAST_POW_BLOCK)
throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks");
static CReserveKey reservekey(pwalletMain);
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64_t nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != 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 = nTransactionsUpdated;
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
if(pblock)
{
delete pblock;
pblock = NULL;
}
pblock = CreateNewBlock(pwalletMain);
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 = tx.GetLegacySigOpCount();
nSigOps += tx.GetP2SHSigOpCount(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->GetMedianTimePast()+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", HexBits(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 (const std::exception&) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
}
bool fAccepted = ProcessBlock(NULL, &block);
if (!fAccepted)
return "rejected";
return Value::null;
}
| [
"i@sir.co.uk"
] | i@sir.co.uk |
324713909c110677ed611d0d5a0a118b46e68b9b | fe20c86c8bd588f99d369c31cc08bfc828e89c6d | /src/util.h | 8b585c4ce23658496585107de7571dd83f82829c | [
"MIT"
] | permissive | kimseonghui/RoundCoin | 22716a69d22f1fc6389aa9fde6f86d74159cb9f5 | 8ccb5cf7598982c34db1df00d4b0e7f62aae54de | refs/heads/master | 2021-01-21T21:28:54.594263 | 2017-06-20T10:08:50 | 2017-06-20T10:08:50 | 94,851,791 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,517 | h | // Copyright (c) 2009-2015 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin developers
// Copyright (c) 2015 The RoundCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_UTIL_H
#define BITCOIN_UTIL_H
#include "uint256.h"
#include "uint256_t.h"
#ifndef WIN32
#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>
#endif
#include <map>
#include <vector>
#include <string>
#include <boost/thread.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/date_time/gregorian/gregorian_types.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <openssl/sha.h>
#include <openssl/ripemd.h>
#include "netbase.h" // for AddTimeData
// to obtain PRId64 on some old systems
#define __STDC_FORMAT_MACROS 1
#include <stdint.h>
#include <inttypes.h>
static const int64_t COIN = 100000000;
static const int64_t CENT = 1000000;
#define BEGIN(a) ((char*)&(a))
#define END(a) ((char*)&((&(a))[1]))
#define UBEGIN(a) ((unsigned char*)&(a))
#define UEND(a) ((unsigned char*)&((&(a))[1]))
#define ARRAYLEN(array) (sizeof(array)/sizeof((array)[0]))
#define UVOIDBEGIN(a) ((void*)&(a))
#define CVOIDBEGIN(a) ((const void*)&(a))
#define UINTBEGIN(a) ((uint32_t*)&(a))
#define CUINTBEGIN(a) ((const uint32_t*)&(a))
#ifndef THROW_WITH_STACKTRACE
#define THROW_WITH_STACKTRACE(exception) \
{ \
LogStackTrace(); \
throw (exception); \
}
void LogStackTrace();
#endif
/* Format characters for (s)size_t and ptrdiff_t */
#if defined(_MSC_VER) || defined(__MSVCRT__)
/* (s)size_t and ptrdiff_t have the same size specifier in MSVC:
http://msdn.microsoft.com/en-us/library/tcxf1dw6%28v=vs.100%29.aspx
*/
#define PRIszx "Ix"
#define PRIszu "Iu"
#define PRIszd "Id"
#define PRIpdx "Ix"
#define PRIpdu "Iu"
#define PRIpdd "Id"
#else /* C99 standard */
#define PRIszx "zx"
#define PRIszu "zu"
#define PRIszd "zd"
#define PRIpdx "tx"
#define PRIpdu "tu"
#define PRIpdd "td"
#endif
// This is needed because the foreach macro can't get over the comma in pair<t1, t2>
#define PAIRTYPE(t1, t2) std::pair<t1, t2>
// Align by increasing pointer, must have extra space at end of buffer
template <size_t nBytes, typename T>
T* alignup(T* p)
{
union
{
T* ptr;
size_t n;
} u;
u.ptr = p;
u.n = (u.n + (nBytes-1)) & ~(nBytes-1);
return u.ptr;
}
#ifdef WIN32
#define MSG_NOSIGNAL 0
#define MSG_DONTWAIT 0
#ifndef S_IRUSR
#define S_IRUSR 0400
#define S_IWUSR 0200
#endif
#else
#define MAX_PATH 1024
#endif
inline void MilliSleep(int64_t n)
{
#if BOOST_VERSION >= 105000
boost::this_thread::sleep_for(boost::chrono::milliseconds(n));
#else
boost::this_thread::sleep(boost::posix_time::milliseconds(n));
#endif
}
/* This GNU C extension enables the compiler to check the format string against the parameters provided.
* X is the number of the "format string" parameter, and Y is the number of the first variadic parameter.
* Parameters count from 1.
*/
#ifdef __GNUC__
#define ATTR_WARN_PRINTF(X,Y) __attribute__((format(printf,X,Y)))
#else
#define ATTR_WARN_PRINTF(X,Y)
#endif
extern std::map<std::string, std::string> mapArgs;
extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
extern bool fDebug;
extern bool fDebugNet;
extern bool fPrintToConsole;
extern bool fPrintToDebugger;
extern bool fRequestShutdown;
extern bool fShutdown;
extern bool fDaemon;
extern bool fServer;
extern bool fCommandLine;
extern std::string strMiscWarning;
extern bool fTestNet;
extern bool fNoListen;
extern bool fLogTimestamps;
extern bool fReopenDebugLog;
void RandAddSeed();
void RandAddSeedPerfmon();
int ATTR_WARN_PRINTF(1,2) OutputDebugStringF(const char* pszFormat, ...);
/*
Rationale for the real_strprintf / strprintf construction:
It is not allowed to use va_start with a pass-by-reference argument.
(C++ standard, 18.7, paragraph 3). Use a dummy argument to work around this, and use a
macro to keep similar semantics.
*/
/** Overload strprintf for char*, so that GCC format type warnings can be given */
std::string ATTR_WARN_PRINTF(1,3) real_strprintf(const char *format, int dummy, ...);
/** Overload strprintf for std::string, to be able to use it with _ (translation).
* This will not support GCC format type warnings (-Wformat) so be careful.
*/
std::string real_strprintf(const std::string &format, int dummy, ...);
#define strprintf(format, ...) real_strprintf(format, 0, __VA_ARGS__)
std::string vstrprintf(const char *format, va_list ap);
bool ATTR_WARN_PRINTF(1,2) error(const char *format, ...);
/* Redefine printf so that it directs output to debug.log
*
* Do this *after* defining the other printf-like functions, because otherwise the
* __attribute__((format(printf,X,Y))) gets expanded to __attribute__((format(OutputDebugStringF,X,Y)))
* which confuses gcc.
*/
#define printf OutputDebugStringF
void LogException(std::exception* pex, const char* pszThread);
void PrintException(std::exception* pex, const char* pszThread);
void PrintExceptionContinue(std::exception* pex, const char* pszThread);
void ParseString(const std::string& str, char c, std::vector<std::string>& v);
std::string FormatMoney(int64_t n, bool fPlus=false);
bool ParseMoney(const std::string& str, int64_t& nRet);
bool ParseMoney(const char* pszIn, int64_t& nRet);
std::vector<unsigned char> ParseHex(const char* psz);
std::vector<unsigned char> ParseHex(const std::string& str);
bool IsHex(const std::string& str);
std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL);
std::string DecodeBase64(const std::string& str);
std::string EncodeBase64(const unsigned char* pch, size_t len);
std::string EncodeBase64(const std::string& str);
std::vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid = NULL);
std::string DecodeBase32(const std::string& str);
std::string EncodeBase32(const unsigned char* pch, size_t len);
std::string EncodeBase32(const std::string& str);
void ParseParameters(int argc, const char*const argv[]);
bool WildcardMatch(const char* psz, const char* mask);
bool WildcardMatch(const std::string& str, const std::string& mask);
void FileCommit(FILE *fileout);
bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest);
boost::filesystem::path GetDefaultDataDir();
const boost::filesystem::path &GetDataDir(bool fNetSpecific = true);
boost::filesystem::path GetConfigFile();
boost::filesystem::path GetPidFile();
#ifndef WIN32
void CreatePidFile(const boost::filesystem::path &path, pid_t pid);
#endif
void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
#ifdef WIN32
boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate = true);
#endif
void ShrinkDebugFile();
int GetRandInt(int nMax);
uint64_t GetRand(uint64_t nMax);
uint256 GetRandHash();
int64_t GetTime();
void SetMockTime(int64_t nMockTimeIn);
int64_t GetAdjustedTime();
int64_t GetTimeOffset();
std::string FormatFullVersion();
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments);
void AddTimeData(const CNetAddr& ip, int64_t nTime);
void runCommand(std::string strCommand);
long hex2long(const char* hexString);
inline std::string i64tostr(int64_t n)
{
//return strprintf("%"PRId64, n);
std::ostringstream o;
o << n;
return o.str();
}
inline std::string itostr(int n)
{
return strprintf("%d", n);
}
inline int64_t atoi64(const char* psz)
{
#ifdef _MSC_VER
return _atoi64(psz);
#else
return strtoll(psz, NULL, 10);
#endif
}
inline int64_t atoi64(const std::string& str)
{
#ifdef _MSC_VER
return _atoi64(str.c_str());
#else
return strtoll(str.c_str(), NULL, 10);
#endif
}
inline int atoi(const std::string& str)
{
return atoi(str.c_str());
}
inline int roundint(double d)
{
return (int)(d > 0 ? d + 0.5 : d - 0.5);
}
inline int64_t roundint64(double d)
{
return (int64_t)(d > 0 ? d + 0.5 : d - 0.5);
}
inline int64_t abs64(int64_t n)
{
return (n >= 0 ? n : -n);
}
inline std::string leftTrim(std::string src, char chr)
{
std::string::size_type pos = src.find_first_not_of(chr, 0);
if(pos > 0)
src.erase(0, pos);
return src;
}
template<typename T>
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
{
std::string rv;
static const char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
rv.reserve((itend-itbegin)*3);
for(T it = itbegin; it < itend; ++it)
{
unsigned char val = (unsigned char)(*it);
if(fSpaces && it != itbegin)
rv.push_back(' ');
rv.push_back(hexmap[val>>4]);
rv.push_back(hexmap[val&15]);
}
return rv;
}
inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
{
return HexStr(vch.begin(), vch.end(), fSpaces);
}
template<typename T>
void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
{
printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
}
inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
{
printf(pszFormat, HexStr(vch, fSpaces).c_str());
}
inline int64_t GetPerformanceCounter()
{
int64_t nCounter = 0;
#ifdef WIN32
QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
#else
timeval t;
gettimeofday(&t, NULL);
nCounter = (int64_t) t.tv_sec * 1000000 + t.tv_usec;
#endif
return nCounter;
}
inline int64_t GetTimeMillis()
{
return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
}
inline std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)
{
time_t n = nTime;
struct tm* ptmTime = gmtime(&n);
char pszTime[200];
strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
return pszTime;
}
static const std::string strTimestampFormat = "%Y-%m-%d %H:%M:%S UTC";
inline std::string DateTimeStrFormat(int64_t nTime)
{
return DateTimeStrFormat(strTimestampFormat.c_str(), nTime);
}
template<typename T>
void skipspaces(T& it)
{
while (isspace(*it))
++it;
}
inline bool IsSwitchChar(char c)
{
#ifdef WIN32
return c == '-' || c == '/';
#else
return c == '-';
#endif
}
/**
* Return string argument or default value
*
* @param strArg Argument to get (e.g. "-foo")
* @param default (e.g. "1")
* @return command-line argument or default value
*/
std::string GetArg(const std::string& strArg, const std::string& strDefault);
/**
* Return integer argument or default value
*
* @param strArg Argument to get (e.g. "-foo")
* @param default (e.g. 1)
* @return command-line argument (0 if invalid number) or default value
*/
int64_t GetArg(const std::string& strArg, int64_t nDefault);
/**
* Return boolean argument or default value
*
* @param strArg Argument to get (e.g. "-foo")
* @param default (true or false)
* @return command-line argument or default value
*/
bool GetBoolArg(const std::string& strArg, bool fDefault=false);
/**
* Set an argument if it doesn't already have a value
*
* @param strArg Argument to set (e.g. "-foo")
* @param strValue Value (e.g. "1")
* @return true if argument gets set, false if it already had a value
*/
bool SoftSetArg(const std::string& strArg, const std::string& strValue);
/**
* Set a boolean argument if it doesn't already have a value
*
* @param strArg Argument to set (e.g. "-foo")
* @param fValue Value (e.g. false)
* @return true if argument gets set, false if it already had a value
*/
bool SoftSetBoolArg(const std::string& strArg, bool fValue);
template<typename T1>
inline uint256 Hash(const T1 pbegin, const T1 pend)
{
static unsigned char pblank[1];
uint256 hash1;
SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
uint256 hash2;
SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
return hash2;
}
class CHashWriter
{
private:
SHA256_CTX ctx;
public:
int nType;
int nVersion;
void Init() {
SHA256_Init(&ctx);
}
CHashWriter(int nTypeIn, int nVersionIn) : nType(nTypeIn), nVersion(nVersionIn) {
Init();
}
CHashWriter& write(const char *pch, size_t size) {
SHA256_Update(&ctx, pch, size);
return (*this);
}
// invalidates the object
uint256 GetHash() {
uint256 hash1;
SHA256_Final((unsigned char*)&hash1, &ctx);
uint256 hash2;
SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
return hash2;
}
template<typename T>
CHashWriter& operator<<(const T& obj) {
// Serialize to this stream
::Serialize(*this, obj, nType, nVersion);
return (*this);
}
};
template<typename T1, typename T2>
inline uint256 Hash(const T1 p1begin, const T1 p1end,
const T2 p2begin, const T2 p2end)
{
static unsigned char pblank[1];
uint256 hash1;
SHA256_CTX ctx;
SHA256_Init(&ctx);
SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
SHA256_Final((unsigned char*)&hash1, &ctx);
uint256 hash2;
SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
return hash2;
}
template<typename T1, typename T2, typename T3>
inline uint256 Hash(const T1 p1begin, const T1 p1end,
const T2 p2begin, const T2 p2end,
const T3 p3begin, const T3 p3end)
{
static unsigned char pblank[1];
uint256 hash1;
SHA256_CTX ctx;
SHA256_Init(&ctx);
SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
SHA256_Final((unsigned char*)&hash1, &ctx);
uint256 hash2;
SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
return hash2;
}
template<typename T>
uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=PROTOCOL_VERSION)
{
CHashWriter ss(nType, nVersion);
ss << obj;
return ss.GetHash();
}
inline uint160 Hash160(const std::vector<unsigned char>& vch)
{
uint256 hash1;
SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
uint160 hash2;
RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
return hash2;
}
/**
* Timing-attack-resistant comparison.
* Takes time proportional to length
* of first argument.
*/
template <typename T>
bool TimingResistantEqual(const T& a, const T& b)
{
if (b.size() == 0) return a.size() == 0;
size_t accumulator = a.size() ^ b.size();
for (size_t i = 0; i < a.size(); i++)
accumulator |= a[i] ^ b[i%b.size()];
return accumulator == 0;
}
/** Median filter over a stream of values.
* Returns the median of the last N numbers
*/
template <typename T> class CMedianFilter
{
private:
std::vector<T> vValues;
std::vector<T> vSorted;
unsigned int nSize;
T tInitial;
public:
CMedianFilter(unsigned int size, T initial_value):
nSize(size)
{
vValues.reserve(size);
vValues.push_back(initial_value);
vSorted = vValues;
tInitial = initial_value;
}
void input(T value)
{
if(vValues.size() == nSize)
{
vValues.erase(vValues.begin());
}
vValues.push_back(value);
vSorted.resize(vValues.size());
std::copy(vValues.begin(), vValues.end(), vSorted.begin());
std::sort(vSorted.begin(), vSorted.end());
}
// remove last instance of a value
void removeLast(T value)
{
for (int i = vValues.size()-1; i >= 0; --i)
{
if (vValues[i] == value)
{
vValues.erase(vValues.begin()+i);
break;
}
}
if (vValues.empty())
{
vValues.push_back(tInitial);
}
vSorted.resize(vValues.size());
std::copy(vValues.begin(), vValues.end(), vSorted.begin());
std::sort(vSorted.begin(), vSorted.end());
}
T median() const
{
int size = vSorted.size();
assert(size>0);
if(size & 1) // Odd number of elements
{
return vSorted[size/2];
}
else // Even number of elements
{
return (vSorted[size/2-1] + vSorted[size/2]) / 2;
}
}
int size() const
{
return vValues.size();
}
std::vector<T> sorted () const
{
return vSorted;
}
};
bool NewThread(void(*pfn)(void*), void* parg);
#ifdef WIN32
inline void SetThreadPriority(int nPriority)
{
SetThreadPriority(GetCurrentThread(), nPriority);
}
#else
#define THREAD_PRIORITY_LOWEST PRIO_MAX
#define THREAD_PRIORITY_BELOW_NORMAL 2
#define THREAD_PRIORITY_NORMAL 0
#define THREAD_PRIORITY_ABOVE_NORMAL 0
inline void SetThreadPriority(int nPriority)
{
// It's unclear if it's even possible to change thread priorities on Linux,
// but we really and truly need it for the generation threads.
#ifdef PRIO_THREAD
setpriority(PRIO_THREAD, 0, nPriority);
#else
setpriority(PRIO_PROCESS, 0, nPriority);
#endif
}
inline void ExitThread(size_t nExitCode)
{
pthread_exit((void*)nExitCode);
}
#endif
void RenameThread(const char* name);
inline uint32_t ByteReverse(uint32_t value)
{
value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
return (value<<16) | (value>>16);
}
#endif
| [
"ksh21tprld@naver.com"
] | ksh21tprld@naver.com |
30604816be0a514bea25780adffd3e8fd7a28e6e | 5d88627fb93523afab9501eb86c79b553188aec7 | /C352/etc/abstract/square.h | 585fef6dfd8e08d68703df1cdd479017cbacc3be | [] | no_license | nrichgels/ClassCode | 33d0a0f960790db095f60a8e865ecc4848923e3a | 2d008e9cedc33d9e24420bef14b73b28ff54cdbf | refs/heads/master | 2020-05-20T11:28:47.877621 | 2015-06-23T16:04:48 | 2015-06-23T16:04:48 | 37,929,243 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 159 | h | #ifndef SQUARE_H
#define SQUARE_H
#include "rectangle.h"
class Square : public Rectangle
{
public:
Square(double=0.0, int = 0, int = 0);
};
#endif
| [
"richgelsna@mnstate.edu"
] | richgelsna@mnstate.edu |
5e8d849b08bb8a9f3299367d9316c22e8c3f4e6b | c8c6901d75d2aad53ee2f6729f80f042029279aa | /terrain/variable_lod/voxel_mesh_block_vlt.cpp | f0bec6cf84fd080945625dc9f9457dc3c7050166 | [
"MIT"
] | permissive | jomiq/godot_voxel | a88bfdcc4d2252e8506481c549a93d59f1fe7a4d | 28fe3365e793434fd4084ab5b63a630b4417acc9 | refs/heads/master | 2022-06-09T11:05:05.090516 | 2022-05-18T22:31:37 | 2022-05-18T22:31:37 | 120,922,994 | 0 | 0 | null | 2018-02-09T15:37:49 | 2018-02-09T15:37:49 | null | UTF-8 | C++ | false | false | 8,240 | cpp | #include "voxel_mesh_block_vlt.h"
#include "../../constants/voxel_string_names.h"
#include "../../util/profiling.h"
#include "../free_mesh_task.h"
namespace zylann::voxel {
VoxelMeshBlockVLT::VoxelMeshBlockVLT(const Vector3i bpos, unsigned int size, unsigned int p_lod_index) :
VoxelMeshBlock(bpos) {
_position_in_voxels = bpos * (size << p_lod_index);
lod_index = p_lod_index;
#ifdef VOXEL_DEBUG_LOD_MATERIALS
Ref<SpatialMaterial> debug_material;
debug_material.instance();
int checker = (bpos.x + bpos.y + bpos.z) & 1;
Color debug_color =
Color(0.8, 0.4, 0.8).linear_interpolate(Color(0.0, 0.0, 0.5), static_cast<float>(p_lod_index) / 8.f);
debug_color = debug_color.lightened(checker * 0.1f);
debug_material->set_albedo(debug_color);
block->_debug_material = debug_material;
Ref<SpatialMaterial> debug_transition_material;
debug_transition_material.instance();
debug_transition_material->set_albedo(Color(1, 1, 0));
block->_debug_transition_material = debug_transition_material;
#endif
}
VoxelMeshBlockVLT::~VoxelMeshBlockVLT() {
for (unsigned int i = 0; i < _transition_mesh_instances.size(); ++i) {
FreeMeshTask::try_add_and_destroy(_transition_mesh_instances[i]);
}
}
void VoxelMeshBlockVLT::set_mesh(Ref<Mesh> mesh, DirectMeshInstance::GIMode gi_mode) {
// TODO Don't add mesh instance to the world if it's not visible.
// I suspect Godot is trying to include invisible mesh instances into the culling process,
// which is killing performance when LOD is used (i.e many meshes are in pool but hidden)
// This needs investigation.
if (mesh.is_valid()) {
if (!_mesh_instance.is_valid()) {
// Create instance if it doesn't exist
_mesh_instance.create();
_mesh_instance.set_gi_mode(gi_mode);
set_mesh_instance_visible(_mesh_instance, _visible && _parent_visible);
}
_mesh_instance.set_mesh(mesh);
if (_shader_material.is_valid()) {
_mesh_instance.set_material_override(_shader_material);
}
#ifdef VOXEL_DEBUG_LOD_MATERIALS
_mesh_instance.set_material_override(_debug_material);
#endif
} else {
if (_mesh_instance.is_valid()) {
// Delete instance if it exists
_mesh_instance.destroy();
}
}
}
void VoxelMeshBlockVLT::set_gi_mode(DirectMeshInstance::GIMode mode) {
VoxelMeshBlock::set_gi_mode(mode);
for (unsigned int i = 0; i < _transition_mesh_instances.size(); ++i) {
DirectMeshInstance &mi = _transition_mesh_instances[i];
if (mi.is_valid()) {
mi.set_gi_mode(mode);
}
}
}
void VoxelMeshBlockVLT::set_transition_mesh(Ref<Mesh> mesh, int side, DirectMeshInstance::GIMode gi_mode) {
DirectMeshInstance &mesh_instance = _transition_mesh_instances[side];
if (mesh.is_valid()) {
if (!mesh_instance.is_valid()) {
// Create instance if it doesn't exist
mesh_instance.create();
mesh_instance.set_gi_mode(gi_mode);
set_mesh_instance_visible(mesh_instance, _visible && _parent_visible && _is_transition_visible(side));
}
mesh_instance.set_mesh(mesh);
if (_shader_material.is_valid()) {
mesh_instance.set_material_override(_shader_material);
}
#ifdef VOXEL_DEBUG_LOD_MATERIALS
mesh_instance.set_material_override(_debug_transition_material);
#endif
} else {
if (mesh_instance.is_valid()) {
// Delete instance if it exists
mesh_instance.destroy();
}
}
}
void VoxelMeshBlockVLT::set_world(Ref<World3D> p_world) {
if (_world != p_world) {
_world = p_world;
// To update world. I replaced visibility by presence in world because Godot 3 culling performance is horrible
_set_visible(_visible && _parent_visible);
if (_static_body.is_valid()) {
_static_body.set_world(*p_world);
}
}
}
void VoxelMeshBlockVLT::set_visible(bool visible) {
if (_visible == visible) {
return;
}
_visible = visible;
_set_visible(_visible && _parent_visible);
}
void VoxelMeshBlockVLT::_set_visible(bool visible) {
VoxelMeshBlock::_set_visible(visible);
for (unsigned int dir = 0; dir < _transition_mesh_instances.size(); ++dir) {
DirectMeshInstance &mi = _transition_mesh_instances[dir];
if (mi.is_valid()) {
set_mesh_instance_visible(mi, visible && _is_transition_visible(dir));
}
}
}
void VoxelMeshBlockVLT::set_shader_material(Ref<ShaderMaterial> material) {
_shader_material = material;
if (_mesh_instance.is_valid()) {
_mesh_instance.set_material_override(_shader_material);
for (int dir = 0; dir < Cube::SIDE_COUNT; ++dir) {
DirectMeshInstance &mi = _transition_mesh_instances[dir];
if (mi.is_valid()) {
mi.set_material_override(_shader_material);
}
}
}
if (_shader_material.is_valid()) {
const Transform3D local_transform(Basis(), _position_in_voxels);
_shader_material->set_shader_param(VoxelStringNames::get_singleton().u_block_local_transform, local_transform);
}
}
//void VoxelMeshBlock::set_transition_bit(uint8_t side, bool value) {
// CRASH_COND(side >= Cube::SIDE_COUNT);
// uint32_t m = _transition_mask;
// if (value) {
// m |= (1 << side);
// } else {
// m &= ~(1 << side);
// }
// set_transition_mask(m);
//}
void VoxelMeshBlockVLT::set_transition_mask(uint8_t m) {
CRASH_COND(m >= (1 << Cube::SIDE_COUNT));
const uint8_t diff = _transition_mask ^ m;
if (diff == 0) {
return;
}
_transition_mask = m;
if (_shader_material.is_valid()) {
// TODO Needs translation here, because Cube:: tables use slightly different order...
// We may get rid of this once cube tables respects -x+x-y+y-z+z order
uint8_t bits[Cube::SIDE_COUNT];
for (unsigned int dir = 0; dir < Cube::SIDE_COUNT; ++dir) {
bits[dir] = (m >> dir) & 1;
}
uint8_t tm = bits[Cube::SIDE_NEGATIVE_X];
tm |= bits[Cube::SIDE_POSITIVE_X] << 1;
tm |= bits[Cube::SIDE_NEGATIVE_Y] << 2;
tm |= bits[Cube::SIDE_POSITIVE_Y] << 3;
tm |= bits[Cube::SIDE_NEGATIVE_Z] << 4;
tm |= bits[Cube::SIDE_POSITIVE_Z] << 5;
// TODO Godot 4: we may replace this with a per-instance parameter so we can lift material access limitation
_shader_material->set_shader_param(VoxelStringNames::get_singleton().u_transition_mask, tm);
}
for (int dir = 0; dir < Cube::SIDE_COUNT; ++dir) {
DirectMeshInstance &mi = _transition_mesh_instances[dir];
if ((diff & (1 << dir)) && mi.is_valid()) {
set_mesh_instance_visible(mi, _visible && _parent_visible && _is_transition_visible(dir));
}
}
}
void VoxelMeshBlockVLT::set_parent_visible(bool parent_visible) {
if (_parent_visible && parent_visible) {
return;
}
_parent_visible = parent_visible;
_set_visible(_visible && _parent_visible);
}
void VoxelMeshBlockVLT::set_parent_transform(const Transform3D &parent_transform) {
ZN_PROFILE_SCOPE();
if (_mesh_instance.is_valid() || _static_body.is_valid()) {
const Transform3D local_transform(Basis(), _position_in_voxels);
const Transform3D world_transform = parent_transform * local_transform;
if (_mesh_instance.is_valid()) {
_mesh_instance.set_transform(world_transform);
for (unsigned int i = 0; i < _transition_mesh_instances.size(); ++i) {
DirectMeshInstance &mi = _transition_mesh_instances[i];
if (mi.is_valid()) {
mi.set_transform(world_transform);
}
}
}
if (_static_body.is_valid()) {
_static_body.set_transform(world_transform);
}
}
}
// Returns `true` when finished
bool VoxelMeshBlockVLT::update_fading(float speed) {
// TODO Should probably not be on the block directly?
// Because we may want to fade transition meshes only
bool finished = false;
// x is progress in 0..1
// y is direction: 1 fades in, 0 fades out
Vector2 p;
switch (fading_state) {
case FADING_IN:
fading_progress += speed;
if (fading_progress >= 1.f) {
fading_progress = 1.f;
fading_state = FADING_NONE;
finished = true;
}
p.x = fading_progress;
p.y = 1.f;
break;
case FADING_OUT:
fading_progress -= speed;
if (fading_progress < 0.f) {
fading_progress = 0.f;
fading_state = FADING_NONE;
finished = true;
set_visible(false);
}
p.x = 1.f - fading_progress;
p.y = 0.f;
break;
case FADING_NONE:
p.x = 1.f;
p.y = active ? 1.f : 0.f;
break;
default:
CRASH_NOW();
break;
}
if (_shader_material.is_valid()) {
_shader_material->set_shader_param(VoxelStringNames::get_singleton().u_lod_fade, p);
}
return finished;
}
} // namespace zylann::voxel
| [
"marc.gilleron@gmail.com"
] | marc.gilleron@gmail.com |
700ccc6850f1e15db692a3c9d5738dc5037a6160 | 9ff8e317e7293033e3983c5e6660adc4eff75762 | /Gamecore/graphics/SGF_FireEffect.h | 7504f8fd0624e47d9cc17ba1503968773fc617cf | [] | no_license | rasputtim/SGF | b26fd29487b93c8e67c73f866635830796970116 | d8af92216bf4e86aeb452fda841c73932de09b65 | refs/heads/master | 2020-03-28T21:55:14.668643 | 2018-11-03T21:15:32 | 2018-11-03T21:15:32 | 147,579,544 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,933 | h | /*
SGF - Super Game Fabric Super Game Fabric
Copyright (C) 2010-2011 Rasputtim <raputtim@hotmail.com>
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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifndef _fire_93c6678306f3542737be4288dc09cfa9
#define _fire_93c6678306f3542737be4288dc09cfa9
#include "../../ExternalLibs/SDL2/include/SDL.h"
#include "../SGF_Config.h"
#include "../graphics/SGF_Color.h"
using namespace std;
namespace SGF{
class CBitmap;
struct Wisp{
double x, y;
int life;
int angle;
};
/**
* \class CFire
*
* \ingroup SGF_Graphics
*
* \brief Efeito de Fogo
*
* \author (last to touch it) $Autor: Rasputtim $
*
* \version 1.0 $Revision: 1.0 $
*
* Contact: raputtim@hotmail.com
*
* Created on: 05 de Janeiro de 2012
*/
class SGE_API CFire{
public:
CFire();
void update();
void draw(const CBitmap & work);
virtual ~CFire();
protected:
void updateHotspots();
void updateWisps();
protected:
unsigned char ** data;
/* enough to fill an unsigned char */
static const int MAX_COLORS = 256;
Colors::ColorDefinition colors[MAX_COLORS];
static const int MAX_HOTSPOTS = 10;
double hotspots[MAX_HOTSPOTS];
double directions[MAX_HOTSPOTS];
static const int MAX_WISPS = 30;
Wisp wisps[MAX_WISPS];
};
}
#endif
| [
"rasputtim@hotmail.com"
] | rasputtim@hotmail.com |
718e52b7f497bd89fd8a89bd13dd24f9bca3fd5e | 6e6708d1614649094d7892f7a991cafaf1e8cb50 | /Voronoi_Delaunay/Delaunay.cpp | a7b1308dc67f51107eda63b338ce0fda37b071bb | [] | no_license | ZhangHang1816/Voronoi_Delaunay | 49cb5d73d0e01d54ef0d92b68b465be3d2735935 | 2364a70e2d946fa0cf3c4ccb700bc163aa896e4e | refs/heads/master | 2022-01-26T07:07:06.167065 | 2019-05-01T09:46:33 | 2019-05-01T09:46:33 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 6,796 | cpp | #include "Delaunay.h"
namespace artstealer
{
Delaunay::Delaunay(Vec3 v1, Vec3 v2, Vec3 v3, Vec3 v4)
{
mPoints.resize(4);
mPoints[0] = v1;
mPoints[1] = v2;
mPoints[2] = v3;
mPoints[3] = v4;
mEdges.resize(4);
mEdges[0] = { 0, 1, -1}; // count -1为边界
mEdges[1] = { 1, 2, -1};
mEdges[2] = { 0, 3, -1};
mEdges[3] = { 2, 3, -1};
AddTriangle(0, 1, 2);
AddTriangle(0, 2, 3);
nBorder = 4;
}
Delaunay::~Delaunay()
{
mPoints.clear();
mEdges.clear();
mTrianges.clear();
}
void Delaunay::DeleteFrame()
{
if (nBorder == 0) {
return;
}
int border = nBorder;
nBorder = 0;
DEdgeArray borderEdges;
mPoints.erase(mPoints.begin(), mPoints.begin()+ border);
for (size_t i = 0; i < mTrianges.size(); i++)
{
if (mTrianges[i].vi[0] <= 3)
{
DelTriangle(i, borderEdges);
borderEdges.clear();
i--;
}
else
{
mTrianges[i].vi[0] -= border;
mTrianges[i].vi[1] -= border;
mTrianges[i].vi[2] -= border;
}
}
mEdges.erase(mEdges.begin(), mEdges.begin() + border);
for (size_t i = 0; i < mEdges.size(); i++)
{
mEdges[i].vi1 -= 4;
mEdges[i].vi2 -= 4;
}
}
bool Delaunay::AddPoint(const Vec3 & v)
{
DEdgeArray borderEdges;//用于存储在删除三角形后留下的边框,用于构造新的三角形
//Point newPoint = { xx,yy,zz };
mPoints.push_back(v);
std::vector<size_t> badTriangles;
size_t size = mTrianges.size();
for (size_t i = 0; i < size; i++)
{
if (isInCircle(v, mTrianges[i]))
badTriangles.push_back(i);
}
for (int i = 0; i < (int)badTriangles.size(); i++)
{
DelTriangle(badTriangles[i]-i, borderEdges);
}
int newVi = (int)mPoints.size()-1;
for (int i = 0; i < (int)borderEdges.size(); i++)
{
int vv[3];
if (newVi < borderEdges[i].vi1)
{ vv[0] = newVi; vv[1] = borderEdges[i].vi1; vv[2] = borderEdges[i].vi2; }
else if (newVi > borderEdges[i].vi2)
{ vv[0] = borderEdges[i].vi1; vv[1] = borderEdges[i].vi2; vv[2] = newVi; }
else
{ vv[0] = borderEdges[i].vi1; vv[1] = newVi; vv[2] = borderEdges[i].vi2; }
AddTriangle(vv[0], vv[1], vv[2]);
}
return true;
}
bool Delaunay::CircumCenter(int vi1, int vi2, int vi3, Vec3& center, REAL & radius)
{
Vec3 v1 = mPoints[vi1];
Vec3 v2 = mPoints[vi2];
Vec3 v3 = mPoints[vi3];
double x1, x2, x3, y1, y2, y3;
x1 = v1.x;
y1 = v1.y;
x2 = v2.x;
y2 = v2.y;
x3 = v3.x;
y3 = v3.y;
REAL x_centre = ((y2 - y1)*(y3 * y3 - y1 * y1 + x3 * x3 - x1 * x1) - (y3 - y1)*(y2 * y2 - y1 * y1 + x2 * x2 - x1 * x1)) / (2 * (x3 - x1)*(y2 - y1) - 2 * ((x2 - x1)*(y3 - y1)));//计算外接圆圆心的x坐标
REAL y_centre = ((x2 - x1)*(x3 * x3 - x1 * x1 + y3 * y3 - y1 * y1) - (x3 - x1)*(x2 * x2 - x1 * x1 + y2 * y2 - y1 * y1)) / (2 * (y3 - y1)*(x2 - x1) - 2 * ((y2 - y1)*(x3 - x1)));//计算外接圆圆心的y坐标
radius = sqrt((x1 - x_centre)*(x1 - x_centre) + (y1 - y_centre)*(y1 - y_centre));//计算外接圆的半径
center.x = x_centre;
center.y = y_centre;
return true;
//Vec3 v1 = mPoints[vi1];
//Vec3 v2 = mPoints[vi2];
//Vec3 v3 = mPoints[vi3];
//Vec3 ac = v3 - v1;
//Vec3 ab = v2 - v1;
//// 判断是否三点共线
//Vec3 ac2 = v3 - v1;
//Vec3 ab2 = v2 - v1;
//ac2.normalize();
//ab2.normalize();
//if (ac2 == ab2)
//{
// _ASSERT("三点共线");
// // 三点共线,无法计算外心
// return false;
//}
//Vec3 abXac = ab ^ ac;
//Vec3 abXacXab = abXac ^ ab;
//Vec3 acXabXac = ac ^ abXac;
//Vec3 toCenter = (abXacXab * ac.lengthSQ() + acXabXac * ab.lengthSQ()) / (2.f * abXac.lengthSQ());
//radius = toCenter.length();
//center = v1 + toCenter;
//return true;
}
bool Delaunay::AddTriangle(int vi1, int vi2, int vi3)
{
REAL radius;
Vec3 center;
if (!CircumCenter(vi1, vi2, vi3, center, radius)) {
return false;
}
DTri triangle = {{vi1, vi2, vi3}, center, radius };
mTrianges.push_back(triangle);
int EdgeSzie = (int)mEdges.size();
int flag;
for (int i = 0; i < 3; i++)
{
int starti = i;
int endi = i+1;
if (i == 2) {
starti = 0;
endi = 2;
}
flag = 1;
for (int j = 0; j < EdgeSzie; j++)
{
if ((triangle.vi[starti] == mEdges[j].vi1 && triangle.vi[endi] == mEdges[j].vi2))
{
flag = 0;
if (mEdges[j].count != -1)
mEdges[j].count += 1;
break;
}
}
if (flag == 1)
mEdges.push_back({ triangle.vi[starti],triangle.vi[endi],1});
}
return true;
}
void Delaunay::DelTriangle(int n, DEdgeArray & borderEdges)
{
DTri triangle = mTrianges[n];
for (int i = 0; i < 3; i++)
{
int starti = i;
int endi = i + 1;// 需要保持 vi2 的值大于 vi1的顺序 (i + 1) % 3;
if (i == 2) {
starti = 0;
endi = 2;
}
for (int j = 0; j < (int)mEdges.size(); j++)
{
if (mEdges[j].vi1 == triangle.vi[starti]&&mEdges[j].vi2 == triangle.vi[endi])
{
if (mEdges[j].count == 2)//若要删除三角形的一边的计数为2,则将其计数减1,并将其压入borderEdges容器中
{
mEdges[j].count = 1;
borderEdges.push_back(mEdges[j]);
}
else if (mEdges[j].count == -1) //如果是外边框,则直接压入borderEdges容器中
{
borderEdges.push_back(mEdges[j]);
}
else if (mEdges[j].count == 1)//如果删除三角形的一边的计数为1,则删除该边,同时查看borderEdges中是否有此边,若有,则删除
{
for (int k = 0; k < (int)borderEdges.size(); k++)
{
if (borderEdges[k].vi1 == mEdges[j].vi1&&borderEdges[k].vi2 == mEdges[j].vi2)
{
borderEdges.erase(borderEdges.begin() + k);
break;
}
}
mEdges.erase(mEdges.begin() + j);
j--;
}
break;
}
}
}
mTrianges.erase(mTrianges.begin() + n);//删除该三角形
}
bool Delaunay::isInCircle(const Vec3 & p, const DTri & tri)
{
double dis = (tri.cp.x - p.x)*(tri.cp.x - p.x) + (tri.cp.y - p.y)*(tri.cp.y - p.y);
if (dis > tri.radius*tri.radius)
return false;
else
return true;
}
bool Delaunay::GetCommonEdge(DTri tri1, DTri tri2, DEdge & edge)
{
// quick check
if (tri1.vi[0] >= tri2.vi[2] || tri1.vi[2] <= tri2.vi[0]) {
return false;
}
REAL e[2];
int count = 0;
size_t m = 0;
for (size_t i = 0; i < 3; i++)
{
for (size_t j = m; j < 3; j++)
{
if (tri1.vi[i] == tri2.vi[j]) {
m = j;
e[count++] = tri1.vi[i];
break;
}
}
}
if (count == 0) {
edge.vi1 = e[0];
edge.vi2 = e[1];
return true;
}
return false;
}
int Delaunay::GetEdge(int vi1, int vi2, DEdge & edge)
{
int size = mEdges.size();
for (int i = 0; i < size; i++)
{
const DEdge& e = mEdges[i];
if (e.vi1 == vi1 && e.vi2 == vi2) {
edge = e;
return i;
}
}
return -1;
}
}
| [
"artstealer@163.com"
] | artstealer@163.com |
19de917c30a61270af12fd96b76d00881b4d62ca | dd239983ea7039366fe4629c3d7dfac0212f6d79 | /demo/coastal_ratio.cpp | 65cddb2abd8cf4eb3c15feccb4910b28ace0102c | [
"BSL-1.0"
] | permissive | turkanis/Waterfront | 19b486398da42fa8fef3959109f3dff70b50aa28 | 6107e193b4425050e2e0207fc60d3cf952c60094 | refs/heads/master | 2020-04-10T03:11:11.568389 | 2013-06-03T04:47:14 | 2013-06-03T04:47:14 | 10,447,129 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 748 | cpp | /*
* 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.)
*
* File: waterfront/demo/coastal_ratio.cpp
* Date: Sun Feb 03 14:10:28 MST 2008
* Copyright: 2008 CodeRage, LLC
* Author: Jonathan Turkanis
* Contact: turkanis at coderage dot com
*
* Demonstrates the template class coastal_view.
*/
#include <iostream>
#include "ball.hpp"
#include "coastal_ratio.hpp"
#include "union.hpp"
using namespace waterfront;
int main(int, char**)
{
ball b1(400, 250, 2.0, point(200, 250), 200);
ball b2(400, 250, 2.0, point(600, 250), 200);
union_<ball, ball> u(b1, b2);
std::cout << coastal_ratio(u, 50, 3);
}
| [
"j@coderage.com"
] | j@coderage.com |
cf40aca15d2bb00ddb4512cebb88427e0252a3a4 | 1af656c548d631368638f76d30a74bf93550b1d3 | /chrome/browser/ui/autofill/local_card_migration_bubble_controller_impl.cc | f6b86e9124f10ef1b53827f7422e82e98b813d95 | [
"BSD-3-Clause"
] | permissive | pineal/chromium | 8d246c746141ef526a55a0b387ea48cd4e7d42e8 | e6901925dd5b37d55accbac55564f639bf4f788a | refs/heads/master | 2023-03-17T05:50:14.231220 | 2018-10-24T20:11:12 | 2018-10-24T20:11:12 | 154,564,128 | 1 | 0 | NOASSERTION | 2018-10-24T20:20:43 | 2018-10-24T20:20:43 | null | UTF-8 | C++ | false | false | 6,136 | cc | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/autofill/local_card_migration_bubble_controller_impl.h"
#include <stddef.h>
#include "chrome/browser/ui/autofill/local_card_migration_bubble.h"
#include "chrome/browser/ui/autofill/popup_constants.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/location_bar/location_bar.h"
#include "components/autofill/core/browser/autofill_metrics.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/browser/navigation_handle.h"
#include "ui/base/l10n/l10n_util.h"
namespace autofill {
// TODO(crbug.com/862405): Build a base class for this
// and SaveCardBubbleControllerImpl.
LocalCardMigrationBubbleControllerImpl::LocalCardMigrationBubbleControllerImpl(
content::WebContents* web_contents)
: content::WebContentsObserver(web_contents),
local_card_migration_bubble_(nullptr) {}
LocalCardMigrationBubbleControllerImpl::
~LocalCardMigrationBubbleControllerImpl() {
if (local_card_migration_bubble_)
HideBubble();
}
void LocalCardMigrationBubbleControllerImpl::ShowBubble(
base::OnceClosure local_card_migration_bubble_closure) {
// Don't show the bubble if it's already visible.
if (local_card_migration_bubble_)
return;
is_reshow_ = false;
local_card_migration_bubble_closure_ =
std::move(local_card_migration_bubble_closure);
AutofillMetrics::LogLocalCardMigrationBubbleOfferMetric(
AutofillMetrics::LOCAL_CARD_MIGRATION_BUBBLE_REQUESTED, is_reshow_);
ShowBubbleImplementation();
}
void LocalCardMigrationBubbleControllerImpl::HideBubble() {
if (local_card_migration_bubble_) {
local_card_migration_bubble_->Hide();
local_card_migration_bubble_ = nullptr;
}
}
void LocalCardMigrationBubbleControllerImpl::ReshowBubble() {
if (local_card_migration_bubble_)
return;
is_reshow_ = true;
AutofillMetrics::LogLocalCardMigrationBubbleOfferMetric(
AutofillMetrics::LOCAL_CARD_MIGRATION_BUBBLE_REQUESTED, is_reshow_);
ShowBubbleImplementation();
}
bool LocalCardMigrationBubbleControllerImpl::IsIconVisible() const {
return !local_card_migration_bubble_closure_.is_null();
}
LocalCardMigrationBubble*
LocalCardMigrationBubbleControllerImpl::local_card_migration_bubble_view()
const {
return local_card_migration_bubble_;
}
base::string16 LocalCardMigrationBubbleControllerImpl::GetBubbleMessage()
const {
return l10n_util::GetStringUTF16(
IDS_AUTOFILL_LOCAL_CARD_MIGRATION_BUBBLE_TITLE);
}
void LocalCardMigrationBubbleControllerImpl::OnConfirmButtonClicked() {
DCHECK(local_card_migration_bubble_closure_);
std::move(local_card_migration_bubble_closure_).Run();
AutofillMetrics::LogLocalCardMigrationBubbleUserInteractionMetric(
AutofillMetrics::LOCAL_CARD_MIGRATION_BUBBLE_CLOSED_ACCEPTED, is_reshow_);
}
void LocalCardMigrationBubbleControllerImpl::OnCancelButtonClicked() {
local_card_migration_bubble_closure_.Reset();
AutofillMetrics::LogLocalCardMigrationBubbleUserInteractionMetric(
AutofillMetrics::LOCAL_CARD_MIGRATION_BUBBLE_CLOSED_DENIED, is_reshow_);
}
void LocalCardMigrationBubbleControllerImpl::OnBubbleClosed() {
local_card_migration_bubble_ = nullptr;
UpdateIcon();
}
base::TimeDelta LocalCardMigrationBubbleControllerImpl::Elapsed() const {
return timer_->Elapsed();
}
void LocalCardMigrationBubbleControllerImpl::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
if (!navigation_handle->IsInMainFrame() || !navigation_handle->HasCommitted())
return;
// Nothing to do if there's no bubble available.
if (!local_card_migration_bubble_closure_)
return;
// Don't react to same-document (fragment) navigations.
if (navigation_handle->IsSameDocument())
return;
// Don't do anything if a navigation occurs before a user could reasonably
// interact with the bubble.
if (Elapsed() < kCardBubbleSurviveNavigationTime)
return;
// Otherwise, get rid of the bubble and icon.
local_card_migration_bubble_closure_.Reset();
bool bubble_was_visible = local_card_migration_bubble_;
if (bubble_was_visible) {
local_card_migration_bubble_->Hide();
OnBubbleClosed();
} else {
UpdateIcon();
}
AutofillMetrics::LogLocalCardMigrationBubbleUserInteractionMetric(
bubble_was_visible
? AutofillMetrics::
LOCAL_CARD_MIGRATION_BUBBLE_CLOSED_NAVIGATED_WHILE_SHOWING
: AutofillMetrics::
LOCAL_CARD_MIGRATION_BUBBLE_CLOSED_NAVIGATED_WHILE_HIDDEN,
is_reshow_);
}
void LocalCardMigrationBubbleControllerImpl::OnVisibilityChanged(
content::Visibility visibility) {
if (visibility == content::Visibility::HIDDEN)
HideBubble();
}
void LocalCardMigrationBubbleControllerImpl::WebContentsDestroyed() {
HideBubble();
}
void LocalCardMigrationBubbleControllerImpl::ShowBubbleImplementation() {
DCHECK(local_card_migration_bubble_closure_);
DCHECK(!local_card_migration_bubble_);
// Need to create location bar icon before bubble, otherwise bubble will be
// unanchored.
UpdateIcon();
Browser* browser = chrome::FindBrowserWithWebContents(web_contents());
local_card_migration_bubble_ =
browser->window()->ShowLocalCardMigrationBubble(web_contents(), this,
is_reshow_);
DCHECK(local_card_migration_bubble_);
UpdateIcon();
timer_.reset(new base::ElapsedTimer());
AutofillMetrics::LogLocalCardMigrationBubbleOfferMetric(
AutofillMetrics::LOCAL_CARD_MIGRATION_BUBBLE_SHOWN, is_reshow_);
}
void LocalCardMigrationBubbleControllerImpl::UpdateIcon() {
Browser* browser = chrome::FindBrowserWithWebContents(web_contents());
if (!browser)
return;
LocationBar* location_bar = browser->window()->GetLocationBar();
if (!location_bar)
return;
location_bar->UpdateLocalCardMigrationIcon();
}
} // namespace autofill
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
6e3fe24c81cf5d7448d5890231b82c839bffd085 | 44ab57520bb1a9b48045cb1ee9baee8816b44a5b | /TheLastOverlordTesting/Code/LeaderboardServerTesting/LeaderboardServerCoreTesting/TestingLib.cpp | 6613bda685334629fc68d8c9dea21b95c2879dd6 | [
"BSD-3-Clause"
] | permissive | WuyangPeng/Engine | d5d81fd4ec18795679ce99552ab9809f3b205409 | 738fde5660449e87ccd4f4878f7bf2a443ae9f1f | refs/heads/master | 2023-08-17T17:01:41.765963 | 2023-08-16T07:27:05 | 2023-08-16T07:27:05 | 246,266,843 | 10 | 0 | null | null | null | null | GB18030 | C++ | false | false | 460 | cpp | /// Copyright (c) 2010-2023
/// Threading Core Render Engine
///
/// 作者:彭武阳,彭晔恩,彭晔泽
/// 联系作者:94458936@qq.com
///
/// 标准:std:c++20
/// 最后的霸王测试版本:0.9.0.12 (2023/06/17 14:09)
#include "ThreadingCoreRenderEngine/ThreadingCoreRenderEngineLib.h"
#include "ThreadingCoreRenderEngineGame/ThreadingCoreRenderEngineGameLib.h"
#include "LeaderboardServer/LeaderboardServerCore/LeaderboardServerCoreLib.h"
| [
"94458936@qq.com"
] | 94458936@qq.com |
d9de2ef5efca6459b327d1774a9385541cd05410 | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14552/function14552_schedule_29/function14552_schedule_29.cpp | cf952072c9e5b426596a0cb547327a187067abd9 | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,686 | cpp | #include <tiramisu/tiramisu.h>
using namespace tiramisu;
int main(int argc, char **argv){
tiramisu::init("function14552_schedule_29");
constant c0("c0", 128), c1("c1", 64), c2("c2", 128), c3("c3", 64);
var i0("i0", 0, c0), i1("i1", 0, c1), i2("i2", 0, c2), i3("i3", 0, c3), i01("i01"), i02("i02"), i03("i03"), i04("i04"), i05("i05"), i06("i06");
input input00("input00", {i3}, p_int32);
input input01("input01", {i0, i1}, p_int32);
input input02("input02", {i0, i1, i2}, p_int32);
input input03("input03", {i1}, p_int32);
input input04("input04", {i3}, p_int32);
input input05("input05", {i3}, p_int32);
computation comp0("comp0", {i0, i1, i2, i3}, input00(i3) * input01(i0, i1) * input02(i0, i1, i2) + input03(i1) * input04(i3) + input05(i3));
comp0.tile(i1, i2, i3, 32, 128, 64, i01, i02, i03, i04, i05, i06);
comp0.parallelize(i0);
buffer buf00("buf00", {64}, p_int32, a_input);
buffer buf01("buf01", {128, 64}, p_int32, a_input);
buffer buf02("buf02", {128, 64, 128}, p_int32, a_input);
buffer buf03("buf03", {64}, p_int32, a_input);
buffer buf04("buf04", {64}, p_int32, a_input);
buffer buf05("buf05", {64}, p_int32, a_input);
buffer buf0("buf0", {128, 64, 128, 64}, p_int32, a_output);
input00.store_in(&buf00);
input01.store_in(&buf01);
input02.store_in(&buf02);
input03.store_in(&buf03);
input04.store_in(&buf04);
input05.store_in(&buf05);
comp0.store_in(&buf0);
tiramisu::codegen({&buf00, &buf01, &buf02, &buf03, &buf04, &buf05, &buf0}, "../data/programs/function14552/function14552_schedule_29/function14552_schedule_29.o");
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
05e946194d556368c9f7b252f1dce78072de98ea | 0210c351cddbd585438cbc8d355893dfc78968fb | /source/EAPCustomMemo.cpp | 74a567cc0803dd6a81040760b2284c9c42b0125a | [] | no_license | pbem-games/Atlaclient | d4bbe15b1a54c02b7c481fc5ae013833027d04e3 | afcc4d57824873c416d43ecf23dba38bb0933dfa | refs/heads/master | 2022-02-28T02:45:50.163379 | 2013-11-24T10:12:38 | 2013-11-24T10:12:38 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 48,582 | cpp | //---------------------------------------------------------------------------
#pragma hdrstop
#include <vcl.h>
#include "EAPCustomMemo.h"
#pragma package(smart_init)
//---------------------------------------------------------------------------
// ValidCtrCheck is used to assure that the components created do not have
// any pure virtual functions.
//
static TPoint RepPos;
static inline void ValidCtrCheck(TEAPCustomMemo *)
{
new TEAPCustomMemo(NULL);
}
static inline void ValidCtrCheck(TEAPMemo *)
{
new TEAPMemo(NULL);
}
namespace Eapmemo
{
void __fastcall PACKAGE Register()
{
TComponentClass classes[1] = {__classid(TEAPMemo)};
RegisterComponents("EAP", classes, 0);
}
}
//---------------------------------------------------------------------------
__fastcall TEAPCustomMemo::TEAPCustomMemo(TComponent* Owner)
: TCustomControl(Owner)
{
// ControlStyle=ControlStyle<<csReplicatable;
FWindowHandle=AllocateHWnd(CaretBlinkingTimeProc);
Width=320;
Height=240;
TabStop=true;
FTracking=true;
FFullRedraw=false;
FScrollBars= ssNone;
FVScrollVisible= true;
FHScrollVisible= true;
FBorderStyle= bsSingle;
FLines=new TStringList;
ParentColor=false;
Color=clWindow;
Font->Name="Courier New";//"Fixedsys";
Font->Color=clWindowText;
Font->Size=8;
FTopLine=0;
FMaxScrollH=0;
Cursor=crIBeam;
FSelected=false;
FSelMouseDwn=false;
CaretPos.x=0;
CaretPos.y=0;
oldCaretPos.x=-1;
oldCaretPos.y=-1;
PulseCaret=true;
FDblClick=false;
FTextColor=clWindowText;
// FTextBackGround=clWindow;
FSelColor=clHighlightText;
FSelBackGround=clHighlight;
FModified=false;
FVisLinesAlterCaret=0;
}
__fastcall TEAPCustomMemo::~TEAPCustomMemo(){
delete FLines;
delete ScrollTimer;
KillTimer(FWindowHandle,1);
DeallocateHWnd(FWindowHandle);
}
//---------------------------------------------------------------------------
void __fastcall TEAPCustomMemo::CreateParams(TCreateParams &Params){
static DWORD BorderStyles[bsSizeToolWin+1]={0, WS_BORDER};
inherited::CreateParams(Params);
Params.Style|=BorderStyles[FBorderStyle];
Params.Style|=WS_CLIPCHILDREN|WS_HSCROLL|WS_VSCROLL;
if(NewStyleControls&&Ctl3D&&FBorderStyle==bsSingle){
Params.Style&=~WS_BORDER;
Params.ExStyle|=WS_EX_CLIENTEDGE;
}
Params.WindowClass.style&=~(CS_HREDRAW||CS_VREDRAW);
}
void __fastcall TEAPCustomMemo::CreateWnd(void){
inherited::CreateWnd();
VPos=0;
HPos=0;
UpdateCharBounds();
UpdateScrollBars();
ScrollTimer=new TTimer(this);
ScrollTimer->Interval=100;
ScrollTimer->Enabled=false;
ScrollTimer->OnTimer=ScrollOnTimer;
if(ComponentState.Contains(csDesigning)){
if(FLines->Count==0) FLines->Add(Name);
}
UpdateTimer();
}
MESSAGE void __fastcall TEAPCustomMemo::WMGetDlgCode(Messages::TWMNoParams &Message){
// inherited::WMGetDlgCode(Message);
Message.Result|=/*DLGC_WANTTAB|*/DLGC_WANTARROWS;
}
void __fastcall TEAPCustomMemo::CaretBlinkingTimeProc(Messages::TMessage &Msg){
if(Msg.Msg==WM_TIMER){
__try{
BlinkCaret();
}catch(...){
Application->HandleException(this);
}
}else
DefWindowProc(FWindowHandle, Msg.Msg, Msg.WParam, Msg.LParam);
}
void __fastcall TEAPCustomMemo::UpdateTimer(void){
KillTimer(FWindowHandle, 1);
if(PulseCaret)
if(SetTimer(FWindowHandle, 1, 450, 0)==0)
throw EOutOfResources("CARET_TIME_ERROR");
}
void __fastcall TEAPCustomMemo::SetScrollBars(TScrollStyle value){
static bool V_SCROLL[]={false, false,true, true};
static bool H_SCROLL[]={false, true, false,true};
if(value==FScrollBars) return;
FVScrollVisible=V_SCROLL[value];
FHScrollVisible=H_SCROLL[value];
ShowScrollBar(Handle, SB_VERT, FVScrollVisible);
ShowScrollBar(Handle, SB_HORZ, FHScrollVisible);
}
void __fastcall TEAPCustomMemo::SetBorderStyle(TBorderStyle Value){
if(FBorderStyle==Value) return;
FBorderStyle=Value;
RecreateWnd();
}
void __fastcall TEAPCustomMemo::SetLines(TStrings* Value){
FLines->Assign(Value);
FModified=false;
Invalidate();
}
int __fastcall TEAPCustomMemo::GetCaretVPos(){
return CaretPos.x;
}
int __fastcall TEAPCustomMemo::GetCaretHPos(){
return CaretPos.y;
}
void __fastcall TEAPCustomMemo::UpdateScrollBars(){
TScrollInfo ScrollInfoV, ScrollInfoH;
ScrollInfoV.cbSize= sizeof(ScrollInfoV);
ScrollInfoV.fMask= SIF_ALL;
ScrollInfoV.nMin= 0;
ScrollInfoV.nPage= FVisLines - 1;
ScrollInfoV.nMax= FLines->Count;
ScrollInfoV.nPos= VPos;
ScrollInfoV.nTrackPos= 0;
SetScrollInfo(Handle, SB_VERT, &ScrollInfoV, true);
ScrollInfoH.cbSize= sizeof(ScrollInfoH);
ScrollInfoH.fMask= SIF_ALL;
ScrollInfoH.nMin= 0;
ScrollInfoH.nPage= FMaxScrollH/4;
ScrollInfoH.nMax= FMaxScrollH;
ScrollInfoH.nPos= HPos;
ScrollInfoH.nTrackPos= 0;
SetScrollInfo(Handle, SB_HORZ, &ScrollInfoH, true);
if(!FVScrollVisible) ShowScrollBar(Handle, SB_VERT, FVScrollVisible);
if(!FHScrollVisible) ShowScrollBar(Handle, SB_HORZ, FHScrollVisible);
}
void __fastcall TEAPCustomMemo::WMHScroll(Messages::TWMScroll &Message){
switch(Message.ScrollCode){
case SB_LINERIGHT: SetHPos(HPos + 1);break;
case SB_LINELEFT: SetHPos(HPos - 1);break;
case SB_PAGEUP: SetHPos(HPos - FVisCols);break;
case SB_PAGEDOWN: SetHPos(HPos + FVisCols);break;
case SB_THUMBPOSITION: SetHPos(Message.Pos);break;
case SB_THUMBTRACK: if(FTracking)SetHPos(Message.Pos);break;
case SB_TOP: SetHPos(0);break;
case SB_BOTTOM: SetHPos(XSize);break;
}
}
void __fastcall TEAPCustomMemo::WMVScroll(Messages::TWMScroll &Message){
switch(Message.ScrollCode){
case SB_LINEUP: SetVPos(VPos - 1);break;
case SB_LINEDOWN: SetVPos(VPos + 1);break;
case SB_PAGEUP: SetVPos(VPos - FVisLines);break;
case SB_PAGEDOWN: SetVPos(VPos + FVisLines);break;
case SB_THUMBPOSITION: SetVPos(GetThumbtrack_V());break;
case SB_THUMBTRACK: if(FTracking)SetVPos(GetThumbtrack_V());break;
case SB_TOP: SetVPos(0);break;
case SB_BOTTOM: SetVPos(YSize);break;
}
}
void __fastcall TEAPCustomMemo::SetVPos(int p){
TScrollInfo ScrollInfo;
int oldPos=VPos;
TRect Rc;
VPos=p;
ScrollInfo.cbSize= sizeof(ScrollInfo);
ScrollInfo.nPos=VPos;
ScrollInfo.fMask=SIF_POS;
SetScrollInfo(Handle,SB_VERT,&ScrollInfo, true);
GetScrollInfo(Handle, SB_VERT,&ScrollInfo);
VPos=ScrollInfo.nPos;
Rc=ClientRect;
if(oldPos-VPos!=0){
FTopLine=VPos;
if(FFullRedraw)
Refresh();
else if(FTopLine + FVisLines < FLines->Count)
DrawVisible();
else
ScrollWindowEx(Handle, 0, (oldPos - VPos) * FChrH, 0, &Rc, 0, 0, SW_INVALIDATE);
if(FOnScrolled_V) FOnScrolled_V(this);
if(FOnTextScrolled) FOnTextScrolled(this, FTopLine, FTopLine + FVisLines + 1,HPos, FMaxScrollH);
}
}
void __fastcall TEAPCustomMemo::SetHPos(int p){
TScrollInfo ScrollInfo;
int oldPos=HPos;
TRect Rc;
HPos=p;
ScrollInfo.cbSize=sizeof(ScrollInfo);
ScrollInfo.nPos=HPos;
ScrollInfo.fMask=SIF_POS;
SetScrollInfo(Handle,SB_HORZ,&ScrollInfo, true);
GetScrollInfo(Handle, SB_HORZ,&ScrollInfo);
HPos=ScrollInfo.nPos;
Rc=ClientRect;
if(oldPos-HPos!=0){
if(FFullRedraw)
Refresh();
else
DrawVisible();
if(FOnScrolled_H) FOnScrolled_H(this);
if(FOnTextScrolled) FOnTextScrolled(this, FTopLine, FTopLine + FVisLines, HPos, FMaxScrollH);
}
}
void __fastcall TEAPCustomMemo::ScrollTo(int X, int Y){
if(FChrH) SetVPos(Y/FChrH);
if(FChrW) SetHPos(X/FChrW);
}
int __fastcall TEAPCustomMemo::GetVScrollPos(){
return VPos;
}
void __fastcall TEAPCustomMemo::SetVScrollPos(int Pos){
SetVPos(Pos);
}
int __fastcall TEAPCustomMemo::GetHScrollPos(){
return HPos;
}
void __fastcall TEAPCustomMemo::SetHScrollPos(int Pos){
SetHPos(Pos);
}
int __fastcall TEAPCustomMemo::GetVScrollMax(){
TScrollInfo ScrollInfo;
ScrollInfo.cbSize=sizeof(ScrollInfo);
ScrollInfo.fMask=SIF_RANGE|SIF_PAGE;
GetScrollInfo(Handle, SB_VERT,&ScrollInfo);
return ScrollInfo.nMax-ScrollInfo.nPage+1;
}
int __fastcall TEAPCustomMemo::GetHScrollMax(){
TScrollInfo ScrollInfo;
ScrollInfo.cbSize=sizeof(ScrollInfo);
ScrollInfo.fMask=SIF_RANGE|SIF_PAGE;
GetScrollInfo(Handle, SB_HORZ,&ScrollInfo);
return ScrollInfo.nMax-ScrollInfo.nPage+1;
}
void __fastcall TEAPCustomMemo::CMMouseWheel(Controls::TCMMouseWheel &Message){
TPoint p(Message.Pos.x,Message.Pos.y);
MouseWheel(Message.ShiftState,Message.WheelDelta,p);
}
void __fastcall TEAPCustomMemo::MouseWheel(Classes::TShiftState Shift, int WheelDelta, const TPoint&MousePos){
int ScrollNotify;
bool hasShift, hasCtrl, NotDoIt, IsNeg;
NotDoIt= false;
if(FOnMouseWheel)
FOnMouseWheel(this, Shift, WheelDelta, MousePos, NotDoIt);
if(NotDoIt) return;
ScrollNotify=-1;
hasShift=Shift.Contains(ssShift);
hasCtrl=Shift.Contains(ssCtrl);
if(hasCtrl){
if(WheelDelta>0) ScrollNotify=SB_LINELEFT;
if(WheelDelta<0) ScrollNotify=SB_LINERIGHT;
if(ScrollNotify!=-1){
Perform(WM_HSCROLL, ScrollNotify, 0);
Perform(WM_HSCROLL, ScrollNotify, 0);
}
return;
}
if(hasShift){
DrawVisible();
HideCaret=false;
if(WheelDelta>0) CaretPos.x=CaretPos.x-1;
if(WheelDelta<0) CaretPos.x=CaretPos.x+1;
if(CaretPos.x<0) CaretPos.x=0;
if(CaretPos.x>=FLines->Count) CaretPos.x=FLines->Count-1;
DrawCaret(CaretPos.x, CaretPos.y, HideCaret);
return;
}
if(!hasShift&&!hasCtrl){
if(WheelDelta>0) ScrollNotify=SB_LINEUP;
if(WheelDelta<0) ScrollNotify=SB_LINEDOWN;
if(ScrollNotify!=-1)
Perform(WM_VSCROLL, ScrollNotify, 0);
}
FWheelAccumulator+=WheelDelta;
while(abs(FWheelAccumulator)>=WHEEL_DELTA){
IsNeg=FWheelAccumulator<0;
FWheelAccumulator=abs(FWheelAccumulator)-WHEEL_DELTA;
if(IsNeg){
if(FWheelAccumulator!=0) FWheelAccumulator=-FWheelAccumulator;
NotDoIt=MouseWheelDown(Shift, MousePos);
}else
NotDoIt=MouseWheelUp(Shift, MousePos);
}
}
bool __fastcall TEAPCustomMemo::MouseWheelDown(Classes::TShiftState Shift, const TPoint &MousePos){
bool Result=false;
if(FOnMouseWheelDown) FOnMouseWheelDown(this, Shift, MousePos, Result);
return Result;
}
bool __fastcall TEAPCustomMemo::MouseWheelUp(Classes::TShiftState Shift, const TPoint &MousePos){
bool Result=false;
if(FOnMouseWheelUp) FOnMouseWheelUp(this, Shift, MousePos, Result);
return Result;
}
void __fastcall TEAPCustomMemo::UpdateCharBounds(void){
Canvas->Font=Font;
FChrW=Canvas->TextWidth("W");
FChrH=Canvas->TextHeight("Wp");
FVisLines=(ClientHeight/FChrH)+1;
FVisCols=ClientWidth/FChrW;
}
void __fastcall TEAPCustomMemo::Paint(void){
UpdateCharBounds();
Canvas->Brush->Color=Color;
Canvas->FillRect(Canvas->ClipRect);
DrawVisible();
if(FOnPaint) FOnPaint(this);
}
void __fastcall TEAPCustomMemo::FormatLine(int I, Graphics::TBitmap* &LGliph){
int TI, Si, Ei, T;
AnsiString ss;
if(!FLines->Count) return;
if(I<0||I>=FLines->Count) return;
AnsiString s=FLines->Strings[I];
for(int i=s.Length();i>=1;i--){
if(s[i]=='\t') s[i]=' ';
}
LGliph->Width=FChrW * s.Length();
LGliph->Height=FChrH;
TCanvas *canv=LGliph->Canvas;
TRect r(0,0,LGliph->Width,LGliph->Height);
bool AllowDraw=true;
if(FOnDrawLine) FOnDrawLine(this, s, I, LGliph, r, AllowDraw);
if(AllowDraw)
DrawText(canv->Handle,s.c_str(), s.Length(), &r, DT_DRAWLINE);
if(FSelected){
canv->Font->Color=FTextColor;
canv->Brush->Color=Color;
canv->Font->Style.Clear();
if((I>StartNo)&&(I<EndNo)){
canv->Brush->Color=FSelBackGround;
canv->Font->Color=FSelColor;
r=TRect(0, 0, s.Length() * FChrW, FChrH);
DrawText(canv->Handle,s.c_str(),s.Length(), &r, DT_DRAWLINE);
}else{
Ei=EndOffs;
Si=StartOffs;
if((I==StartNo)&&(I==EndNo)){
canv->Brush->Color=FSelBackGround;
canv->Font->Color=FSelColor;
if(Ei>s.Length())
ss=s.SubString(Si + 1, s.Length() - Si);
else
ss=s.SubString(Si + 1, Ei - Si);
r=TRect(Si * FChrW, 0, (Si * FChrW) + (ss.Length() * FChrW), FChrH);
DrawText(canv->Handle, ss.c_str(), ss.Length(),&r, DT_DRAWLINE);
}else if((I==StartNo)&&(I<EndNo)){
canv->Brush->Color=FSelBackGround;
canv->Font->Color=FSelColor;
ss=s.SubString(Si + 1, s.Length() - Si);
r=TRect(Si * FChrW, 0, (Si * FChrW) + (ss.Length() * FChrW), FChrH);
DrawText(canv->Handle, ss.c_str(), ss.Length(),&r, DT_DRAWLINE);
}else if((I>StartNo)&&(I==EndNo)){
canv->Brush->Color=FSelBackGround;
canv->Font->Color=FSelColor;
if(Ei>s.Length()) Ei=s.Length();
ss=s.SubString(1,Ei);
r=TRect(0, 0, ss.Length() * FChrW, FChrH);
DrawText(canv->Handle, ss.c_str(), ss.Length(),&r, DT_DRAWLINE);
}
}
}
if(s.Length()>FMaxScrollH) FMaxScrollH=s.Length();
UpdateScrollBars();
}
void __fastcall TEAPCustomMemo::DrawLine(Graphics::TCanvas* CanvasSupport, int I, int Y){
int L, Ei, Si;
TRect Rc;
Graphics::TBitmap *LGliph=new Graphics::TBitmap;
TCanvas *canv=LGliph->Canvas;
canv->Brush->Color=Color;
canv->Font=Font;
Font->Color=FTextColor;
if(I<FLines->Count)
FormatLine(I,LGliph);
else
LGliph->Width=0;
CanvasSupport->Draw(-(HPos*FChrW),Y,LGliph);
L=LGliph->Width-(HPos*FChrW);
if(L<0) L=0;
if(FSelected){
Ei=EndOffs;
Si=StartOffs;
if((I>StartNo)&&(I<EndNo)){
CanvasSupport->Brush->Color=FSelBackGround;
Rc=TRect(L, Y, (FMaxScrollH * FChrW) + ClientWidth - (HPos * FChrW), Y + FChrH);
CanvasSupport->FillRect(Rc);
}else if((I==StartNo)&&(I<EndNo)){
if(I<FLines->Count){
if(FLines->Strings[I].Length()-1<Si){
Si=FLines->Strings[I].Length()-1;
StartOffs=Si;
}
}
if(LGliph->Width<1){
CanvasSupport->Brush->Color=Color;
Rc=TRect(-(HPos * FChrW), Y, (Si * FChrW) - (HPos * FChrW) , Y + FChrH);
CanvasSupport->FillRect(Rc);
L=(Si * FChrW) - (HPos * FChrW);
}else
L=LGliph->Width - (HPos * FChrW);
if(LGliph->Width < (Si * FChrW)){
CanvasSupport->Brush->Color=Color;
Rc=TRect(L, Y, (Si * FChrW) - (HPos * FChrW), Y + FChrH);
CanvasSupport->FillRect(Rc);
L=(Si * FChrW) - (HPos * FChrW);
}
CanvasSupport->Brush->Color=FSelBackGround;
Rc=TRect(L, Y, (FMaxScrollH * FChrW) + ClientWidth - (HPos * FChrW), Y + FChrH);
CanvasSupport->FillRect(Rc);
}else if((I>StartNo)&&(I==EndNo)){
CanvasSupport->Brush->Color=FSelBackGround;
if(LGliph->Width<1){
Rc=TRect(-(HPos * FChrW), Y, (Ei * FChrW) - (HPos * FChrW), Y + FChrH);
CanvasSupport->FillRect(Rc);
}else if(LGliph->Width < (Ei * FChrW)){
L=LGliph->Width-(HPos * FChrW);
Rc=TRect(L, Y, (Ei * FChrW) - (HPos * FChrW), Y + FChrH);
CanvasSupport->FillRect(Rc);
}
L=(Ei * FChrW) - (HPos * FChrW);
if(LGliph->Width-(HPos * FChrW)> L)
L=LGliph->Width-(HPos * FChrW);
CanvasSupport->Brush->Color=Color;
Rc=TRect(L, Y, (FMaxScrollH * FChrW) + ClientWidth - (HPos * FChrW), Y + FChrH);
CanvasSupport->FillRect(Rc);
}else{
CanvasSupport->Brush->Color=Color;
Rc=TRect(L, Y, (FMaxScrollH * FChrW) + ClientWidth - (HPos * FChrW), Y + FChrH);
CanvasSupport->FillRect(Rc);
}
}else{
CanvasSupport->Brush->Color=Color;
TRect Rc=Rect(L, Y, (FMaxScrollH * FChrW) + ClientWidth - (HPos * FChrW), Y + FChrH);
CanvasSupport->FillRect(Rc);
}
delete LGliph;
}
void __fastcall TEAPCustomMemo::DrawVisible(){
int y=0;
GetSelBounds(StartNo, EndNo, StartOffs, EndOffs);
for(int i=FTopLine,endi=FTopLine+FVisLines;i<endi;i++){
DrawLine(Canvas,i,y);
y+=FChrH;
}
}
TPoint __fastcall TEAPCustomMemo::GetSelBegin(){
TPoint Result;
Result.x=FSelStartNo;
Result.y=FSelStartOffs;
return Result;
}
TPoint __fastcall TEAPCustomMemo::GetSelEnd(){
TPoint Result;
Result.x=FSelEndNo;
Result.y=FSelEndOffs;
return Result;
}
void __fastcall TEAPCustomMemo::SetSelBegin(TPoint Value){
if(Value.x>FLines->Count) Value.x=FLines->Count;
if(Value.x<0) Value.x=0;
if(Value.y<0) Value.y=0;
FSelStartNo=Value.x;
FSelStartOffs=Value.y;
FSelected=(FSelStartNo!=FSelEndNo)||(FSelStartOffs!=FSelEndOffs);
}
void __fastcall TEAPCustomMemo::SetSelEnd(TPoint Value){
if(Value.x>FLines->Count) Value.x=FLines->Count;
if(Value.x<0) Value.x=0;
if(Value.y<0) Value.y=0;
FSelEndNo=Value.x;
FSelEndOffs=Value.y;
CaretPos.x=Value.x;
CaretPos.y=Value.y;
FSelected=(FSelStartNo!=FSelEndNo)||(FSelStartOffs!=FSelEndOffs);
MakeCaretVisible();
}
void __fastcall TEAPCustomMemo::GetSelBounds(int &StartNo, int &EndNo, int &StartOffs, int &EndOffs){
if(FSelStartNo<=FSelEndNo){
StartNo=FSelStartNo;
EndNo=FSelEndNo;
if(!((StartNo== EndNo)&&(FSelStartOffs>FSelEndOffs))){
StartOffs=FSelStartOffs;
EndOffs=FSelEndOffs;
}else{
StartOffs=FSelEndOffs;
EndOffs=FSelStartOffs;
}
}else{
StartNo=FSelEndNo;
EndNo=FSelStartNo;
StartOffs=FSelEndOffs;
EndOffs=FSelStartOffs;
}
}
void __fastcall TEAPCustomMemo::MouseDown(Controls::TMouseButton Button, Classes::TShiftState Shift, int X, int Y){
int RNo,CNo;
inherited::MouseDown(Button, Shift, X, Y);
if(!Focused()){
TCustomForm *frm=GetParentForm(this);
if(frm&&frm->ActiveControl==this)
frm->ActiveControl=0;
SetFocus();
}
ShiftState=Shift;
if(FOnMemoEvents)
switch(Button){
case mbRight: FOnMemoEvents(this, Shift, k_Mouse2, 0, CaretPos, Point(X, Y)); break;
case mbMiddle: FOnMemoEvents(this, Shift, k_Mouse3, 0, CaretPos, Point(X, Y)); break;
}
if(Button!=mbLeft) return;
if(FDblClick) return;
GetRowColAtPos(X + HPos * FChrW, Y + VPos * FChrH, RNo, CNo);
CaretPos.x=RNo;
CaretPos.y=CNo;
if(FOnMemoEvents) FOnMemoEvents(this, Shift, k_Mouse1, 0, CaretPos, Point(X, Y));
if(!Shift.Contains(ssShift)){
if(FSelected){
// Erase old selection, if any...
FSelected=false;
DrawVisible();
}else{
PulseCaret=true;
UpdateTimer();
}
FSelStartNo=RNo;
FSelEndNo=FSelStartNo;
FSelStartOffs=CNo;
FSelEndOffs=FSelStartOffs;
FSelected=true;
FSelMouseDwn=true;
ScrollTimer->Enabled=true;
}else{
FSelEndNo=RNo;
FSelEndOffs=CNo;
FSelected=true;
}
DrawVisible();
DrawCaret(CaretPos.x, CaretPos.y, True);
}
void __fastcall TEAPCustomMemo::MouseUp(Controls::TMouseButton Button, Classes::TShiftState Shift, int X, int Y){
int RNo, CNo;
inherited::MouseUp(Button, Shift, X, Y);
ShiftState=Shift;
if(FOnMemoEvents)
switch(Button){
case mbLeft: FOnMemoEvents(this, Shift, k_Mouse1, 0, CaretPos, Point(X, Y));break;
case mbRight: FOnMemoEvents(this, Shift, k_Mouse2, 0, CaretPos, Point(X, Y));break;
case mbMiddle: FOnMemoEvents(this, Shift, k_Mouse3, 0, CaretPos, Point(X, Y));break;
}
if(Button!=mbLeft) return;
if(FDblClick){
FDblClick=false;
return;
}
FSelMouseDwn=false;
ScrollTimer->Enabled=false;
GetRowColAtPos(X + HPos * FChrW, Y + VPos * FChrH, RNo, CNo);
if(RNo!=FSelEndNo) FSelEndNo=RNo;
if(CNo!=FSelEndOffs) FSelEndOffs=CNo;
FSelected=(FSelStartNo!=FSelEndNo)||(FSelStartOffs!=FSelEndOffs);
if(!FSelected &&(FSelStartNo==0)&&(FSelStartOffs==0)){
FSelStartNo=0;
FSelEndNo=FSelStartNo;
FSelStartOffs=0;
FSelEndOffs=FSelStartOffs;
DrawVisible();
DrawCaret(CaretPos.x,CaretPos.y,true);
HideCaret=true;
PulseCaret=true;
UpdateTimer();
}
}
void __fastcall TEAPCustomMemo::MouseMove(Classes::TShiftState Shift, int X, int Y){
int RNo, CNo,verY;
inherited::MouseMove(Shift, X, Y);
ShiftState=Shift;
MousePos=Point(X, Y);
if(FOnMemoEvents) FOnMemoEvents(this, Shift, k_None, 0, CaretPos, MousePos);
VScrollDelta=0;
HScrollDelta=0;
if(Y<0) VScrollDelta=-1;
if(X<0) HScrollDelta=-1;
if(Y>ClientHeight) VScrollDelta=1;
if(X>ClientWidth) HScrollDelta=1;
if(Y<-FChrH) VScrollDelta=-2;
if(Y>(ClientHeight + FChrH)) VScrollDelta=2;
if(X<-FChrW) HScrollDelta=-2;
if(X>(ClientWidth + FChrW)) HScrollDelta=2;
if(FSelected && FSelMouseDwn){
XMouse=X;
YMouse=Y;
verY=Y;
if(verY<0) verY=0;
if(verY>ClientHeight) verY=ClientHeight;
GetRowColAtPos(X + HPos * FChrW, verY + VPos * FChrH, RNo, CNo);
FSelEndNo=RNo;
FSelEndOffs=CNo;
CaretPos.x=RNo;
CaretPos.y=CNo;
DrawVisible();
}
}
bool IsValidChar(char a){
// ValidChars = ['a'..'z', 'A'..'Z', '0'..'9', '#'];
if(a>='0'&&a<='9') return true;
if(a>='a'&&a<='z') return true;
if(a>='A'&&a<='Z') return true;
if(a>='à'&&a<='ÿ') return true;
if(a>='À'&&a<='ß') return true;
return false;
}
bool GetNextWord(AnsiString SLine, int &PosX){
int I, RetX;
bool FindNext;
bool Result=false;
if(PosX>SLine.Length()) return Result;
FindNext=false;
RetX=0;
for(I=PosX;I<=SLine.Length();I++){
if(!FindNext&&!IsValidChar(SLine[I])){
FindNext=true;
continue;
}
if(FindNext&&IsValidChar(SLine[I])){
RetX=I;
Result=True;
break;
}
}
if(RetX<1) Result=false;
PosX=RetX;
return Result;
}
void __fastcall TEAPCustomMemo::DblClick(){
AnsiString s;
int XB, NextW;
inherited::DblClick();
ShiftState=ShiftState<<ssDouble;
if(FOnMemoEvents) FOnMemoEvents(this, ShiftState, k_None, 0, CaretPos, MousePos);
s=GetWordAtPos(CaretPos.y, CaretPos.x, XB);
if((s.Length())&&(XB>-1)){
FSelStartNo=CaretPos.x;
FSelEndNo=CaretPos.x;
FSelStartOffs=XB;
FSelEndOffs=XB + s.Length();
CaretPos.y=FSelStartOffs;
FSelected=true;
DrawVisible();
FDblClick=true;
}else if(CaretPos.x<FLines->Count){
s=FLines->Strings[CaretPos.x];
NextW=CaretPos.y;
if(GetNextWord(s,NextW)){
s=GetWordAtPos(NextW, CaretPos.x, XB);
if(s.Length()&&(XB > -1)){
FSelStartNo=CaretPos.x;
FSelEndNo=CaretPos.x;
FSelStartOffs=XB;
FSelEndOffs=XB+s.Length();
CaretPos.y=FSelStartOffs;
FSelected=true;
DrawVisible();
FDblClick=true;
}
}
}
}
AnsiString __fastcall TEAPCustomMemo::GetWordAtPos(int Col, int Row, int &XBegin){
AnsiString S;
char C;
int I, Si, Ei, CrX;
XBegin=-1;
Si=0;
Ei=0;
if(Row>=FLines->Count) return "";
S=FLines->Strings[Row];
if(!S.Length()) return "";
if(Col>S.Length()-1)
Col=S.Length()-1;
if(!IsValidChar(S[Col + 1])){
CrX=Col-1;
for(I=CrX;I>=1;I--){
C=S[I+1];
if(IsValidChar(C)){
Col=I;
break;
}
}
if(Col==0) return "";
}
for(I=Col + 1;I>=1;I--){
if(IsValidChar(S[I]))
Si=I;
else
break;
}
for(I=Col + 1;I<=S.Length();I++){
if(IsValidChar(S[I]))
Ei=I+1;
else
break;
}
if(Ei>=Si){
XBegin=Si-1;
return S.SubString(Si, Ei - Si);
}
return "";
}
void __fastcall TEAPCustomMemo::GetRowColAtPos(int X, int Y, int &Row, int &Col){
Row=Y/FChrH;
if(Row>FLines->Count) Row=FLines->Count;
if(X<0) X= 0;
Col=(X+FChrW/2)/FChrW;
}
void __fastcall TEAPCustomMemo::ScrollOnTimer(TObject* Sender){
if(VScrollDelta){
ScrollPos_V+=VScrollDelta;
MouseMove(TShiftState(), XMouse, YMouse);
}
if(HScrollDelta){
ScrollPos_H+=HScrollDelta;
MouseMove(TShiftState(), XMouse, YMouse);
}
}
void __fastcall TEAPCustomMemo::BlinkCaret(){
if(ComponentState.Contains(csDesigning)) return;
HideCaret=!HideCaret;
if((FSelStartNo==FSelEndNo)&&(FSelStartOffs==FSelEndOffs))
FSelected=false;
if(FSelected)
HideCaret=false;
// HWND h=GetFocus();
if(!Focused())
HideCaret=false;
DrawCaret(CaretPos.x, CaretPos.y, HideCaret);
}
void __fastcall TEAPCustomMemo::DrawCaret(int X, int Y, bool ShowCaret){
int Xp, Yp;
if(ComponentState.Contains(csDesigning)) return;
if(CaretPos.x!=oldCaretPos.x||CaretPos.y!=oldCaretPos.y){
if(OnCaretMove) OnCaretMove(this);
oldCaretPos=CaretPos;
OldHideCaret=HideCaret;
}
if(FSelected)return;
if((X<FTopLine)||(X>FTopLine + FVisLines)) return;
Yp=(X-FTopLine)*FChrH;
Xp=(Y-HPos)*FChrW;
if((Xp<0)||(Xp>ClientWidth)) return;
if(OldHideCaret!=HideCaret)
{
Canvas->Pen->Mode=pmXor;
Canvas->Pen->Color=clWhite;
for(int x=Xp;x<Xp+FChrW;x++)
{
Canvas->MoveTo(x, Yp);
Canvas->LineTo(x, Yp + FChrH);
}
Canvas->Pen->Mode=pmCopy;
}
OldHideCaret=HideCaret;
FSelStartNo=CaretPos.x;
FSelStartOffs=CaretPos.y;
}
AnsiString __fastcall TEAPCustomMemo::GetSelText(){
int StartLine, StartPos, EndLine, EndPos, I, LineI;
AnsiString FirstPart, LastPart, SLine, Result;
if(!FSelected) return Result;
if(FSelStartNo>FSelEndNo){
StartLine=FSelEndNo;
StartPos=FSelEndOffs;
EndLine=FSelStartNo;
EndPos=FSelStartOffs;
}else if((FSelStartNo==FSelEndNo)&&(FSelEndOffs<FSelStartOffs)){
StartLine=FSelStartNo;
StartPos=FSelEndOffs;
EndLine=StartLine;
EndPos=FSelStartOffs;
}else{
StartLine=FSelStartNo;
StartPos=FSelStartOffs;
EndLine=FSelEndNo;
EndPos=FSelEndOffs;
}
if(StartLine>=FLines->Count) return Result;
if(EndLine>=FLines->Count)
{
EndLine=FLines->Count-1;
EndPos=FLines->Strings[EndLine].Length();
}
SLine=FLines->Strings[StartLine];
if(StartLine<EndLine){
FirstPart=SLine.SubString(StartPos + 1,SLine.Length()-StartPos);
SLine=FLines->Strings[EndLine];
if(EndPos>SLine.Length()) EndPos=SLine.Length();
LastPart=SLine.SubString(1,EndPos);
LineI=StartLine+1;
Result=FirstPart;
for(I=LineI;I<EndLine;I++)
Result+="\r\n"+FLines->Strings[I];
Result+="\r\n"+LastPart;
}else
Result=SLine.SubString(StartPos+1,EndPos-StartPos);
return Result;
}
void __fastcall TEAPCustomMemo::SetSelText(AnsiString str){
DeleteSelection();
InsertTextAtPos(str,CaretPos.y,CaretPos.x);
}
void __fastcall TEAPCustomMemo::CopyToClipboard(){
if(!FSelected) return;
Clipboard()->SetTextBuf(GetSelText().c_str());
}
void __fastcall TEAPCustomMemo::CutToClipboard(){
if(!FSelected) return;
CopyToClipboard();
if(FReadOnly) return;
DeleteSelection();
}
void __fastcall TEAPCustomMemo::PasteFromClipboard(){
if(FReadOnly) return;
if(FSelected) DeleteSelection();
InsertTextAtPos(Clipboard()->AsText, CaretPos.y, CaretPos.x);
}
void __fastcall TEAPCustomMemo::InsertTextAtPos(AnsiString S, int Col, int Row){
if(FReadOnly) return;
AnsiString SLine, BufS1, BufS2, BufS;
int I, L;
if(!S.Length()) return;
if(Row>FLines->Count) return;
FModified=true;
if(Row==FLines->Count) FLines->Add("");
SLine=FLines->Strings[Row];
if(Col>SLine.Length()){
L=SLine.Length();
for(I=L;I<=Col;I++) SLine+=" ";
}
BufS1=SLine.SubString(1,Col);
BufS2=SLine.SubString(Col+1,SLine.Length()-Col);
SLine=BufS1+S+BufS2;
FSelected=true;
I=SLine.Pos("\r\n");
if(I>0){
BufS="";
FSelStartNo=Row;
FSelStartOffs=BufS1.Length();
while(I>0){
BufS=SLine.SubString(1,I-1);
FLines->Insert(Row, BufS);
SLine.Delete(1,I+1);
I=SLine.Pos("\r\n");
CaretPos.x=Row;
CaretPos.y=BufS.Length();
FSelEndNo=Row;
FSelEndOffs=CaretPos.y;
Row++;
}
if(SLine.Length()){
FLines->Strings[Row]=SLine;
CaretPos.x=Row;
CaretPos.y=SLine.Length()-BufS2.Length();
FSelEndNo=Row;
FSelEndOffs=CaretPos.y;
}else{
CaretPos.x=Row;
CaretPos.y=0;
FSelEndNo=Row;
FSelEndOffs=0;
}
Invalidate();
}else{
I=SLine.Pos("\r");
if(I>0){
BufS="";
FSelStartNo=Row;
FSelStartOffs=BufS1.Length();
while(I>0){
BufS=SLine.SubString(1,I-1);
FLines->Insert(Row, BufS);
SLine.Delete(1, I);
I=SLine.Pos("\r");
CaretPos.x=Row;
CaretPos.y=BufS.Length();
FSelEndNo=Row;
FSelEndOffs=CaretPos.y;
Row++;
}
if(SLine.Length()){
FLines->Strings[Row]=SLine;
CaretPos.x=Row;
CaretPos.y=SLine.Length()-BufS2.Length();
FSelEndNo=Row;
FSelEndOffs=CaretPos.y;
}
Invalidate();
}else{
CaretPos.x=Row;
FLines->Strings[Row]= SLine;
CaretPos.y=Col+S.Length();
FSelStartNo=Row;
FSelEndNo=Row;
FSelStartOffs=BufS1.Length();
FSelEndOffs=CaretPos.y;
Invalidate();
}
}
UpdateScrollBars();
MakeCaretVisible();
}
void __fastcall TEAPCustomMemo::DeleteSelection(){
if(FReadOnly) return;
AnsiString FirstPart, LastPart, SLine;
int StartLine, StartPos, EndLine, EndPos, I, DelLine;
if(!FSelected) return;
if(FReadOnly) return;
FModified=true;
if(FSelStartNo>FSelEndNo){
StartLine=FSelEndNo;
StartPos=FSelEndOffs;
EndLine=FSelStartNo;
EndPos=FSelStartOffs;
}else if((FSelStartNo==FSelEndNo)&&(FSelEndOffs<FSelStartOffs)){
StartLine=FSelStartNo;
StartPos=FSelEndOffs;
EndLine=StartLine;
EndPos=FSelStartOffs;
}else{
StartLine=FSelStartNo;
StartPos=FSelStartOffs;
EndLine=FSelEndNo;
EndPos=FSelEndOffs;
}
// { update Undo List }
if(StartLine>=FLines->Count) return;
if(EndLine>=FLines->Count)
{
EndLine=FLines->Count-1;
EndPos=FLines->Strings[EndLine].Length();
}
SLine=FLines->Strings[StartLine];
FirstPart=SLine.SubString(1,StartPos);
SLine=FLines->Strings[EndLine];
if(EndPos>SLine.Length()) EndPos=SLine.Length();
LastPart=SLine.SubString(EndPos + 1, SLine.Length()-EndPos);
DelLine=StartLine+1;
for(I=DelLine;I<=EndLine;I++) FLines->Delete(DelLine);
FLines->Strings[StartLine]=FirstPart+LastPart;
CaretPos.x=StartLine;
CaretPos.y=StartPos;
FSelected=false;
if(StartLine==EndLine){
I=(CaretPos.x - FTopLine)*FChrH;
DrawLine(Canvas, CaretPos.x, I);
}else
DrawVisible();
DrawCaret(CaretPos.x, CaretPos.y, true);
UpdateScrollBars();
}
void __fastcall TEAPCustomMemo::SelectAll(){
FSelStartNo=0;
FSelStartOffs=0;
FSelEndNo=Lines->Count;
FSelEndOffs=0;
FSelected=true;
DrawVisible();
}
void __fastcall TEAPCustomMemo::WMKeyDown(Messages::TWMKey &Message){
int GliphY, Y;
bool CaretScroll;
AnsiString SLine, AddS, SLink;
CaretScroll=false;
ShiftState=KeyDataToShiftState(Message.KeyData);
if(FOnMemoEvents)
FOnMemoEvents(this,ShiftState,k_Down,Message.CharCode,CaretPos,MousePos);
switch(Message.CharCode){
case VK_LEFT: case VK_RIGHT: case VK_DOWN:case VK_UP:
case VK_HOME: case VK_END: case VK_PRIOR: case VK_NEXT:
KeyboardCaretNav(ShiftState, Message.CharCode);
CaretScroll=true;
break;
case VK_DELETE:
if(FReadOnly) return;
if(FSelected){
DeleteSelection();
return;
}
if(CaretPos.x>=FLines->Count) return;
FModified=true;
SLine=FLines->Strings[CaretPos.x];
if(SLine.Length()>=CaretPos.y+1){
Y=CaretPos.y+1;
SLine.Delete(Y,1);
FLines->Strings[CaretPos.x]=SLine;
GliphY=(CaretPos.x-FTopLine)*FChrH;
DrawLine(Canvas,CaretPos.x,GliphY);
}else{
if(CaretPos.x+1>=FLines->Count) return;
AddS=FLines->Strings[CaretPos.x+1];
FLines->Strings[CaretPos.x]=SLine+AddS;
FLines->Delete(CaretPos.x+1);
DrawVisible();
}
DrawCaret(CaretPos.x,CaretPos.y,true);
break;
}
if(CaretScroll){
/* if(CaretPos.y>HPos+FVisCols) ScrollPos_H=CaretPos.y-FVisCols;
if(CaretPos.y<HPos) ScrollPos_H=CaretPos.y;
if(CaretPos.x<FTopLine) ScrollPos_V=CaretPos.x;
if(CaretPos.x>FTopLine+FVisLines-2) ScrollPos_V=CaretPos.x-FVisLines+2;*/
MakeCaretVisible();
}
// inherited::WMKeyDown(Message);
}
void __fastcall TEAPCustomMemo::WMKeyUp(Messages::TWMKey &Message){
ShiftState=KeyDataToShiftState(Message.KeyData);
if(FOnMemoEvents)
FOnMemoEvents(this,ShiftState,k_Up,Message.CharCode,CaretPos,MousePos);
// inherited::WMKeyUp(Message);
}
void __fastcall TEAPCustomMemo::KeyboardCaretNav(Classes::TShiftState ShiftState, Word Direction){
int GliphY, SaveXCaret;
switch(Direction){
case VK_LEFT: //Left Arrow key is pressed.
CaretPos.y--;
if(CaretPos.y<0){
if(CaretPos.x>0){
if(CaretPos.x<FLines->Count){
GliphY=(CaretPos.x-FTopLine)*FChrH;
DrawLine(Canvas, CaretPos.x, GliphY);
DrawCaret(CaretPos.x, CaretPos.y + 1,false);
if(ShiftState.Contains(ssCtrl)&&CaretPos.x>0){
CaretPos.x--;
CaretPos.y=FLines->Strings[CaretPos.x].Length();
if(FSelected){
FSelEndNo=CaretPos.x;
FSelEndOffs=CaretPos.y;
DrawVisible();
}
return;
}
}
CaretPos.x--;
CaretPos.y=FLines->Strings[CaretPos.x].Length();
if(!FSelected){
GliphY=(CaretPos.x-FTopLine)*FChrH;
DrawLine(Canvas,CaretPos.x,GliphY);
}else
DrawVisible();
}else{
CaretPos.y=0;
GliphY=(CaretPos.x-FTopLine)*FChrH;
if(!FSelected)
DrawLine(Canvas,CaretPos.x,GliphY);
else
DrawVisible();
}
}else{
GliphY=(CaretPos.x-FTopLine)*FChrH;
DrawLine(Canvas,CaretPos.x,GliphY);
DrawCaret(CaretPos.x,CaretPos.y,true);
}
if(ShiftState.Contains(ssShift)){
if(!FSelected){
if(CaretPos.x<FLines->Count)
if(CaretPos.y>FLines->Strings[CaretPos.x].Length())
CaretPos.y=FLines->Strings[CaretPos.x].Length()-1;
FSelected=true;
FSelStartNo=CaretPos.x;
FSelStartOffs=CaretPos.y+1;
FSelEndNo=CaretPos.x;
FSelEndOffs=CaretPos.y;
}else{
FSelEndNo=CaretPos.x;
FSelEndOffs=CaretPos.y;
if(FSelEndNo<FLines->Count){
if(FSelEndOffs>FLines->Strings[FSelEndNo].Length()){
FSelEndOffs=FLines->Strings[FSelEndNo].Length()-1;
CaretPos.y=FSelEndOffs;
}
}else{
FSelEndOffs=0;
CaretPos.y=0;
}
}
FSelected=(FSelStartNo!=FSelEndNo)||(FSelStartOffs!=FSelEndOffs);
DrawVisible();
return;
}
if(FSelected){
FSelected=false;
DrawVisible();
DrawCaret(CaretPos.x, CaretPos.y, true);
}
FSelStartNo=CaretPos.x;
FSelStartOffs=CaretPos.y;
break;
case VK_RIGHT: //Right Arrow key is pressed.
CaretPos.y=CaretPos.y+1;
if(CaretPos.y>FMaxScrollH){
FMaxScrollH=FMaxScrollH+2;
UpdateScrollBars();
}
if(CaretPos.x<FLines->Count){
GliphY=(CaretPos.x - FTopLine) * FChrH;
DrawLine(Canvas, CaretPos.x,GliphY);
}
if(ShiftState.Contains(ssShift)){
if(!FSelected){
FSelected=true;
FSelStartNo=CaretPos.x;
FSelStartOffs=CaretPos.y-1;
FSelEndNo=CaretPos.x;
FSelEndOffs=CaretPos.y;
}else{
FSelEndNo=CaretPos.x;
FSelEndOffs=CaretPos.y;
}
FSelected=(FSelStartNo!=FSelEndNo)||(FSelStartOffs!=FSelEndOffs);
DrawVisible();
return;
}
if(FSelected){
FSelected=false;
DrawVisible();
DrawCaret(CaretPos.x, CaretPos.y,true);
}
DrawCaret(CaretPos.x, CaretPos.y,true);
FSelStartNo=CaretPos.x;
FSelStartOffs=CaretPos.y;
break;
case VK_UP: //Up Arrow key is pressed.
if(CaretPos.x==0) return;
if(!ShiftState.Contains(ssShift)){
CaretPos.x=CaretPos.x-1;
if(FSelected){
FSelected=false;
DrawVisible();
DrawCaret(CaretPos.x, CaretPos.y, true);
return;
}
FSelStartNo=CaretPos.x;
GliphY=(CaretPos.x - FTopLine + 1) * FChrH;
DrawLine(Canvas, CaretPos.x + 1, GliphY);
GliphY=(CaretPos.x - FTopLine) * FChrH;
DrawLine(Canvas, CaretPos.x, GliphY);
DrawCaret(CaretPos.x, CaretPos.y, True);
return;
}else{
CaretPos.x=CaretPos.x-1;
if(!FSelected){
FSelStartNo=CaretPos.x + 1;
FSelStartOffs=CaretPos.y;
FSelEndNo=CaretPos.x;
FSelEndOffs=CaretPos.y;
FSelected=true;
}else{
FSelEndNo=CaretPos.x;
FSelEndOffs=CaretPos.y;
FSelected=(FSelStartNo!=FSelEndNo)||(FSelStartOffs!=FSelEndOffs);
}
DrawVisible();
}
break;
case VK_DOWN: //Down Arrow key is pressed.
if(CaretPos.x>=FLines->Count) return;
if(!ShiftState.Contains(ssShift)){
CaretPos.x=CaretPos.x+1;
if(FSelected){
FSelected=false;
DrawVisible();
DrawCaret(CaretPos.x, CaretPos.y, true);
return;
}
FSelStartNo=CaretPos.x;
GliphY=(CaretPos.x - FTopLine - 1) * FChrH;
DrawLine(Canvas, CaretPos.x - 1, GliphY);
GliphY=(CaretPos.x - FTopLine) * FChrH;
DrawLine(Canvas, CaretPos.x, GliphY);
DrawCaret(CaretPos.x, CaretPos.y, True);
return;
}else{
CaretPos.x=CaretPos.x+1;
if(!FSelected){
FSelStartNo=CaretPos.x - 1;
FSelStartOffs=CaretPos.y;
FSelEndNo=CaretPos.x;
FSelEndOffs=CaretPos.y;
FSelected=true;
}else{
FSelEndNo=CaretPos.x;
FSelEndOffs=CaretPos.y;
FSelected=(FSelStartNo!=FSelEndNo)||(FSelStartOffs!=FSelEndOffs);
}
DrawVisible();
}
break;
case VK_HOME: //Home key is pressed.
if(!ShiftState.Contains(ssShift)){
CaretPos.y=0;
GliphY=(CaretPos.x - FTopLine) * FChrH;
DrawLine(Canvas, CaretPos.x, GliphY);
DrawCaret(CaretPos.x, CaretPos.y, true);
}else{
DrawCaret(CaretPos.x, CaretPos.y, false);
if(!FSelected){
FSelStartNo=CaretPos.x;
FSelStartOffs=CaretPos.y;
FSelected=true;
}
CaretPos.y=0;
FSelEndNo=CaretPos.x;
FSelEndOffs=0;
if(FSelEndNo==FSelStartNo)
FSelected=(FSelStartOffs!=FSelEndOffs);
DrawVisible();
}
break;
case VK_END: //End key is pressed.
if(!ShiftState.Contains(ssShift)){
if(CaretPos.x<FLines->Count)
CaretPos.y=FLines->Strings[CaretPos.x].Length();
else
CaretPos.y=0;
GliphY=(CaretPos.x-FTopLine)*FChrH;
DrawLine(Canvas,CaretPos.x,GliphY);
DrawCaret(CaretPos.x,CaretPos.y,true);
}else{
DrawCaret(CaretPos.x, CaretPos.y,false);
if(FSelected){
FSelStartNo=CaretPos.x;
if(CaretPos.x<FLines->Count)
if(CaretPos.y>FLines->Strings[CaretPos.x].Length())
CaretPos.y=FLines->Strings[CaretPos.x].Length();
FSelStartOffs=CaretPos.y;
FSelected=true;
}
if(CaretPos.x<FLines->Count)
CaretPos.y=FLines->Strings[CaretPos.x].Length();
else
CaretPos.y=0;
FSelEndNo=CaretPos.x;
FSelEndOffs=CaretPos.y;
if(FSelEndNo==FSelStartNo)
FSelected=(FSelStartOffs!=FSelEndOffs);
DrawVisible();
}
break;
case VK_PRIOR: case VK_NEXT: //Page Up key or Page Down key is pressed.
if(!FSelected){
FSelStartNo=CaretPos.x;
FSelStartOffs=CaretPos.y;
}
SaveXCaret=CaretPos.x-FTopLine;
if(Direction==VK_PRIOR){
if(VPos==0){
DrawCaret(CaretPos.x, CaretPos.y,false);
CaretPos.x=0;
CaretPos.y=0;
}else{
Perform(WM_VSCROLL, SB_PAGEUP, 0);
CaretPos.x=FTopLine+SaveXCaret;
}
}else{
if(VPos>FLines->Count-FVisLines){
DrawCaret(CaretPos.x, CaretPos.y,false);
CaretPos.x=FLines->Count-1;
CaretPos.y=FLines->Strings[CaretPos.x].Length();
}else{
Perform(WM_VSCROLL, SB_PAGEDOWN, 0);
CaretPos.x=FTopLine+SaveXCaret;
}
}
DrawCaret(CaretPos.x, CaretPos.y,true);
if(ShiftState.Contains(ssShift)){
FSelEndNo=CaretPos.x;
FSelEndOffs=CaretPos.y;
// if(!FSelected)
FSelected=true;
DrawVisible();
}
break;
}
}
void __fastcall TEAPCustomMemo::KeyPress(char &Key){
AnsiString SLine, AddS;
int Fill, Y, GliphY, T;
inherited::KeyPress(Key);
if(CaretPos.x>=FLines->Count) FLines->Add("");
if(CaretPos.x>=FLines->Count) return;
if((Key==VK_ESCAPE)||ShiftState.Contains(ssCtrl)) return;
if(FSelected){
DeleteSelection();
if(Key==8) return;
}
SLine=FLines->Strings[CaretPos.x];
switch(Key){
case 8: // Backspace key
if(FReadOnly) return;
FModified=true;
if(SLine.Length()>=CaretPos.y)
Y=CaretPos.y;
else{
Y=SLine.Length();
CaretPos.y=Y;
}
SLine.Delete(Y,1);
FLines->Strings[CaretPos.x]=SLine;
CaretPos.y=CaretPos.y-1;
if(CaretPos.y<0){
if(CaretPos.x>0){
AddS=FLines->Strings[CaretPos.x];
FLines->Delete(CaretPos.x);
CaretPos.x=CaretPos.x-1;
CaretPos.y=FLines->Strings[CaretPos.x].Length();
if(AddS.Length())
FLines->Strings[CaretPos.x]=FLines->Strings[CaretPos.x]+AddS;
DrawVisible();
}else{
CaretPos.y=0;
GliphY=(CaretPos.x-FTopLine)*FChrH;
DrawLine(Canvas,CaretPos.x,GliphY);
}
}else{
GliphY=(CaretPos.x-FTopLine) * FChrH;
DrawLine(Canvas,CaretPos.x,GliphY);
}
FSelStartNo=CaretPos.x;
FSelStartOffs=CaretPos.y;
break;
case 13: //Return key
// FIX-ME Undo update...
if(FReadOnly) return;
FModified=true;
AddS="";
if(SLine.Length()>CaretPos.y){
AddS=SLine.SubString(CaretPos.y + 1, SLine.Length() - CaretPos.y + 1);
SLine.Delete(CaretPos.y+1,SLine.Length()-CaretPos.y);
FLines->Strings[CaretPos.x]=SLine;
}
if(CaretPos.x==FLines->Count-1)
FLines->Add(AddS);
else if(CaretPos.x<FLines->Count-1)
FLines->Insert(CaretPos.x+1,AddS);
else if(CaretPos.x>=FLines->Count)
FLines->Add("");
CaretPos.x=CaretPos.x+1;
CaretPos.y=0;
DrawVisible();
FSelStartNo=CaretPos.x;
FSelStartOffs=CaretPos.y;
break;
default:;
// FIX-ME Undo update...
if(unsigned(Key)<32) return;
if(FReadOnly) return;
FModified=true;
if(SLine.Length()<CaretPos.y+1)
for(Fill=SLine.Length();Fill<=CaretPos.y+1;Fill++) SLine+=" ";
AddS=Key;
SLine.Insert(AddS,CaretPos.y+1);
FLines->Strings[CaretPos.x]=SLine;
CaretPos.y=CaretPos.y+1;
GliphY=(CaretPos.x-FTopLine)*FChrH;
DrawLine(Canvas,CaretPos.x,GliphY);
FSelStartNo=CaretPos.x;
FSelStartOffs=CaretPos.y;
}
/* if(CaretPos.y>HPos+FVisCols)
ScrollPos_H=CaretPos.y-FVisCols;
if(CaretPos.y<HPos)
ScrollPos_H=CaretPos.y;
if(CaretPos.x<FTopLine)
ScrollPos_V=CaretPos.x;
if(CaretPos.x>FTopLine+FVisLines-2)
ScrollPos_V=CaretPos.x-FVisLines+2;*/
MakeCaretVisible();
DrawCaret(CaretPos.x, CaretPos.y,true);
}
bool __fastcall TEAPCustomMemo::FindReplaceProc(AnsiString TextToFind, TEAPFindOptions FindOptions,
bool Backward, bool ReplaceMode, bool &ReplaceText){
int SrcBegin, SrcEnd, I, WordPos, ScrollX, ScrollY, Fill;
AnsiString SLine, SrcWord;
TPoint FindPos;
bool AllowScroll, ContinueSrc;
bool Result=false;
if(FindOptions.Contains(foEntireScope)){
SrcBegin=0;
SrcEnd=FLines->Count-1;
}else{
SrcBegin=CaretPos_V;
if(Backward)
SrcEnd=0;
else
SrcEnd=FLines->Count-1;
}
if(!FindOptions.Contains(foMatchCase))
SrcWord=UpperCase(TextToFind);
else
SrcWord=TextToFind;
if(SrcBegin<=SrcEnd){
for(I=SrcBegin;I<=SrcEnd;I++){
SLine=FLines->Strings[I];
if(!FindOptions.Contains(foMatchCase)) SLine=UpperCase(SLine);
FindPos.x=0;
WordPos=SLine.Pos(SrcWord);
while(WordPos>0){
if((I==CaretPos.x)&&(WordPos<CaretPos.y)){
for(Fill=WordPos;Fill<WordPos+SrcWord.Length();Fill++)
SLine[Fill]='*';
FindPos.x+=WordPos;
WordPos=SLine.Pos(SrcWord);
continue;
}
FindPos.x=WordPos;
FindPos.y=I;
AllowScroll=true;
ContinueSrc=false;
if(FindOptions.Contains(foWholeWords)){
if(WordPos>1){
// if (SLine[WordPos - 1] in ['a'..'z', 'A'..'Z']) then
if(IsValidChar(SLine[WordPos-1]))
for(Fill=WordPos;Fill<WordPos+SrcWord.Length();Fill++)
SLine[Fill]='*';
FindPos.x+=WordPos;
WordPos=SLine.Pos(SrcWord);
continue;
}
if(WordPos+SrcWord.Length()<=SLine.Length())
if(IsValidChar(SLine[WordPos+SrcWord.Length()])){
for(Fill=WordPos;Fill<WordPos+SrcWord.Length();Fill++)
SLine[Fill]='*';
FindPos.x+=WordPos;
WordPos=SLine.Pos(SrcWord);
continue;
}
}
FSelStartNo=I;
FSelEndNo=I;
FSelStartOffs=FindPos.x-1;
FSelEndOffs=FindPos.x+SrcWord.Length()-1;
FSelected=true;
CaretPos.x=I;
CaretPos.y=FindPos.x+SrcWord.Length()-1;
if(AllowScroll){
ScrollX=0;
ScrollY=FTopLine*FChrH;
if(((FindPos.x+SrcWord.Length())*FChrW)-FChrW>ClientWidth)
ScrollX=(FindPos.x*FChrW)-2*FChrW;
if(I>FTopLine+FVisLines-2)
ScrollY=I*FChrH;
ScrollTo(ScrollX, ScrollY);
Invalidate();
}else
Invalidate();
Result=true;
if(ReplaceMode){
if(FOnReplaceText)
FOnReplaceText(this, FindPos, AllowScroll, ReplaceText);
RepPos=FindPos;
}else
if(FOnFindText)
FOnFindText(this, FindPos, AllowScroll);
for(Fill=WordPos;Fill<WordPos+SrcWord.Length();Fill++)
SLine[Fill]='*';
WordPos=SLine.Pos(SrcWord);
if(!ContinueSrc) return Result;
}
}
}else{
for(I=SrcBegin;I>=SrcEnd;I--){
SLine=FLines->Strings[I];
if(!FindOptions.Contains(foMatchCase))
SLine=UpperCase(SLine);
FindPos.x=0;
WordPos=SLine.Pos(SrcWord);
while(WordPos>0){
if((I==CaretPos.x)&&(WordPos<CaretPos.y)){
for(Fill=WordPos;Fill<WordPos+SrcWord.Length();Fill++)
SLine[Fill]='*';
FindPos.x+=WordPos;
WordPos=SLine.Pos(SrcWord);
continue;
}
FindPos.x=WordPos;
FindPos.y=I;
AllowScroll=true;
ContinueSrc=false;
if(FindOptions.Contains(foWholeWords)){
if(WordPos>1)
if(IsValidChar(SLine[WordPos - 1])){
for(Fill=WordPos;Fill<WordPos+SrcWord.Length();Fill++)
SLine[Fill]='*';
FindPos.x+=WordPos;
WordPos=SLine.Pos(SrcWord);
continue;
}
if(WordPos+SrcWord.Length()<=SLine.Length())
if(IsValidChar(SLine[WordPos+SrcWord.Length()])){
for(Fill=WordPos;Fill<WordPos+SrcWord.Length();Fill++)
SLine[Fill]='*';
FindPos.x+=WordPos;
WordPos=SLine.Pos(SrcWord);
continue;
}
}
FSelStartNo=I;
FSelEndNo=I;
FSelStartOffs=FindPos.x-1;
FSelEndOffs=FindPos.x+SrcWord.Length()-1;
FSelected=true;
CaretPos.x=I;
CaretPos.y=FindPos.x+SrcWord.Length()-1;
if(AllowScroll){
ScrollX=0;
ScrollY=FTopLine*FChrH;
if(((FindPos.x+SrcWord.Length())*FChrW)-FChrW>ClientWidth)
ScrollX=(FindPos.x*FChrW)-2*FChrW;
if(I>FTopLine+FVisLines-2)
ScrollY=I*FChrH;
ScrollTo(ScrollX,ScrollY);
Invalidate();
}else
Invalidate();
Result=true;
if(ReplaceMode){
if(FOnReplaceText)
FOnReplaceText(this,FindPos,AllowScroll,ReplaceText);
RepPos=FindPos;
}else
if(FOnFindText)
FOnFindText(this, FindPos, AllowScroll);
for(Fill=WordPos;Fill<WordPos+SrcWord.Length();Fill++)
SLine[Fill]='*';
WordPos=SLine.Pos(SrcWord);
if(!ContinueSrc)
return Result;
}
}
}
return Result;
}
void __fastcall TEAPCustomMemo::FindText(AnsiString TextToFind, TEAPFindOptions FindOptions, bool Backward){
bool Rep, SrcRes;
SrcRes=FindReplaceProc(TextToFind, FindOptions, Backward, false, Rep);
if(FOnSerachEnd) FOnSerachEnd(this, SrcRes, false);
}
void __fastcall TEAPCustomMemo::ReplaceText(AnsiString TextToFind, AnsiString TextToReplace, TEAPFindOptions FindOptions, bool Backward){
bool Rep, SrcRes;
Rep=true;
SrcRes=FindReplaceProc(TextToFind, FindOptions, Backward, true, Rep);
if(SrcRes&&Rep){
DeleteSelection();
InsertTextAtPos(TextToReplace, CaretPos.y, CaretPos.x);
}
if(FOnSerachEnd) FOnSerachEnd(this, SrcRes, true);
}
void __fastcall TEAPCustomMemo::Clear(void){
CaretPos.x=0;
CaretPos.y=0;
ScrollTo(0,0);
FSelStartNo=0;
FSelStartOffs=0;
FSelEndNo=0;
FSelEndOffs=0;
FLines->Clear();
FSelected=false;
Invalidate();
FModified=false;
}
void __fastcall TEAPCustomMemo::SaveToFile(const AnsiString FileName){
TStrings *BuffList=new TStringList;
bool usecopy=true;
if(FLines->Count>100000)
{
delete BuffList;
BuffList=FLines;
usecopy=false;
}else
BuffList->Assign(FLines);
for(int i=0,endi=BuffList->Count;i<endi;i++){
AnsiString SLine=BuffList->Strings[i];
int p=SLine.Length();
if(!p) continue;
char *s=SLine.c_str()+p-1;
while(p>0&&*s==' '){
s--;
p--;
}
if(p==SLine.Length())
continue;
SLine.SetLength(p);
BuffList->Strings[i]=SLine;
}
BuffList->SaveToFile(FileName);
if(usecopy) delete BuffList;
FModified=false;
}
void __fastcall TEAPCustomMemo::LoadFromFile(const AnsiString FileName){
if(!FileExists(FileName))
return;
Clear();
FLines->LoadFromFile(FileName);
Invalidate();
FModified=false;
}
void TEAPCustomMemo::MakeCaretVisible()
{
if(CaretPos.y>HPos+FVisCols)
ScrollPos_H=CaretPos.y-FVisCols;
if(CaretPos.y<HPos)
ScrollPos_H=CaretPos.y;
if(CaretPos.x<FTopLine)
ScrollPos_V=CaretPos.x;
if(CaretPos.x>FTopLine+FVisLines-2-VisLinesAlterCaret)
ScrollPos_V=CaretPos.x-FVisLines+2+VisLinesAlterCaret;
}
int __fastcall TEAPCustomMemo::GetThumbtrack_V()
{
TScrollInfo ScrollInfo;
ScrollInfo.cbSize=sizeof(ScrollInfo);
ScrollInfo.fMask=SIF_TRACKPOS;
GetScrollInfo(Handle, SB_VERT,&ScrollInfo);
return ScrollInfo.nTrackPos;
}
| [
"pradd.me@gmail.com"
] | pradd.me@gmail.com |
d403c74469aa90b212717d3521382d0083744ee1 | 5076cd860b77eb813aadb81acd4d1bc23023121c | /WDcore/Win32/dummy_imu.cpp | 95be1f54b02948a4255b5c2eff8ef6f4a889f9f8 | [] | no_license | geirwanvik/WDrov | 89ca48fc040139e7f5b2fe77fe83e1b9402aa760 | 9324f8fa98f3869e839ff429646d728e00d53158 | refs/heads/master | 2020-12-29T02:37:25.311451 | 2017-02-24T07:06:11 | 2017-02-24T07:06:11 | 54,888,595 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,495 | cpp | #include "imu.h"
#include "imuhelperfunctions.h"
#include "wiringPi.h"
#include <unistd.h>
#include <QDebug>
#include <QWaitCondition>
#include <QMutex>
#include <qmath.h>
Imu::Imu(QThread &thread, QMutex &_i2cMutex) :
QObject(0)
{
(void)_i2cMutex;
memset(&att,0,sizeof(att_t));
connect (&thread, SIGNAL(started()), this, SLOT(Calculate()));
}
void Imu::Calculate()
{
int mode = qrand() % 3;
int tilt = qrand() % 900;
int head = qrand() % 1800;
int sign = qrand() % 2;
if (sign == 1)
{
tilt *= -1;
head *= -1;
}
while (1)
{
switch (mode)
{
case 0: // pitch
if (att.angle[PITCH] == tilt)
{
mode = qrand() % 3;
tilt = qrand() % 900;
head = qrand() % 1800;
sign = qrand() % 2;
if (sign == 1)
{
tilt *= -1;
head *= -1;
}
}
else
{
if (att.angle[PITCH] < tilt)
{
att.angle[PITCH]++;
}
else
{
att.angle[PITCH]--;
}
}
break;
case 1: // roll
if (att.angle[ROLL] == tilt)
{
mode = qrand() % 3;
tilt = qrand() % 900;
head = qrand() % 1800;
sign = qrand() % 2;
if (sign == 1)
{
tilt *= -1;
head *= -1;
}
}
else
{
if (att.angle[ROLL] < tilt)
{
att.angle[ROLL]++;
}
else
{
att.angle[ROLL]--;
}
}
break;
case 2: // head
if (att.heading == head)
{
mode = qrand() % 3;
tilt = qrand() % 900;
head = qrand() % 1800;
sign = qrand() % 2;
if (sign == 1)
{
tilt *= -1;
head *= -1;
}
}
else
{
if (att.heading < head)
{
att.heading++;
}
else
{
att.heading--;
}
}
break;
}
qDebug() << "Roll: " << QString::number(att.angle[ROLL]) << " Pitch: " << QString::number(att.angle[PITCH]) << " Heading: " << QString::number(att.heading);
QMutex mutex;
mutex.lock();
QWaitCondition waitCondition;
waitCondition.wait(&mutex, 5);
mutex.unlock();
}
}
void Imu::NewMessageItem(QString cmd, QString value)
{
float data;
if (value == "READ")
{
if (cmd == "ROLL")
{
data = (float)att.angle[ROLL] / 10;
emit SendReply(cmd, QString::number(data,'f',1));
}
else if (cmd == "PITCH")
{
data = (float)att.angle[PITCH] / 10;
emit SendReply(cmd, QString::number(data,'f',1));
}
else if (cmd == "HEADING")
{
data = (float)att.heading / 10;
emit SendReply(cmd, QString::number(data,'f',1));
}
}
}
| [
"none"
] | none |
2232d94fc438273094aa5e80f6611cada4b6a44c | 93b24e6296dade8306b88395648377e1b2a7bc8c | /client/Client/CEGUI/CEGUI/include/falagard/CEGUIFalLayerSpecification.h | 86d13ef95463a91c5f828facaaf0a8bac0a9209f | [] | no_license | dahahua/pap_wclinet | 79c5ac068cd93cbacca5b3d0b92e6c9cba11a893 | d0cde48be4d63df4c4072d4fde2e3ded28c5040f | refs/heads/master | 2022-01-19T21:41:22.000190 | 2013-10-12T04:27:59 | 2013-10-12T04:27:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,847 | h | /************************************************************************
filename: CEGUIFalLayerSpecification.h
created: Mon Jun 13 2005
author: Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/*************************************************************************
Crazy Eddie's GUI System (http://www.cegui.org.uk)
Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*************************************************************************/
#ifndef _CEGUIFalLayerSpecification_h_
#define _CEGUIFalLayerSpecification_h_
#include "falagard/CEGUIFalSectionSpecification.h"
#include "CEGUIWindow.h"
#if defined(_MSC_VER)
# pragma warning(push)
# pragma warning(disable : 4251)
#endif
// Start of CEGUI namespace section
namespace CEGUI
{
/*!
\brief
Class that encapsulates a single layer of imagery.
*/
class CEGUIEXPORT LayerSpecification
{
public:
/*!
\brief
Constructor.
\param priority
Specifies the priority of the layer. Layers with higher priorities will be drawn on top
of layers with lower priorities.
*/
LayerSpecification(UINT priority);
/*!
\brief
Render this layer.
\param srcWindow
Window to use when calculating pixel values from BaseDim values.
\param base_z
base level z value to use for all imagery in the layer.
\return
Nothing.
*/
void render(Window& srcWindow, float base_z, const ColourRect* modcols = 0, const Rect* clipper = 0, bool clipToDisplay = false) const;
/*!
\brief
Render this layer.
\param srcWindow
Window to use when calculating pixel values from BaseDim values.
\param baseRect
Rect to use when calculating pixel values from BaseDim values.
\param base_z
base level z value to use for all imagery in the layer.
\return
Nothing.
*/
void render(Window& srcWindow, const Rect& baseRect, float base_z, const ColourRect* modcols = 0, const Rect* clipper = 0, bool clipToDisplay = false) const;
/*!
\brief
Add a section specification to the layer.
A section specification is a reference to a named ImagerySection within the WidgetLook.
\param section
SectionSpecification object descibing the section that should be added to this layer.
\return
Nothing,
*/
void addSectionSpecification(const SectionSpecification& section);
/*!
\brief
Clear all section specifications from this layer,
\return
Nothing.
*/
void clearSectionSpecifications();
/*!
\brief
Return the priority of this layer.
\return
UINT value descibing the priority of this LayerSpecification.
*/
UINT getLayerPriority() const;
// required to sort layers according to priority
bool operator<(const LayerSpecification& other) const;
/*!
\brief
Writes an xml representation of this Layer to \a out_stream.
\param out_stream
Stream where xml data should be output.
\return
Nothing.
*/
void writeXMLToStream(OutStream& out_stream) const;
private:
typedef std::vector<SectionSpecification> SectionList;
SectionList d_sections; //!< Collection of SectionSpecification objects descibing the sections to be drawn for this layer.
UINT d_layerPriority; //!< Priority of the layer.
};
} // End of CEGUI namespace section
#if defined(_MSC_VER)
# pragma warning(pop)
#endif
#endif // end of guard _CEGUIFalLayerSpecification_h_
| [
"viticm@126.com"
] | viticm@126.com |
69414aa9eb446ec815e840ac634dcab8e548c66b | 5231d22dadd06e81d17183b589def82eae45e77a | /fuzzers/asan-opencv-2/harness.cpp | d0e0de9675b71df820287bdbbdd1e1c5923ccf2f | [
"Apache-2.0"
] | permissive | ufwt/maxfuzz | 7be7a0a6eeaf81e4c1f4e407720a929ad1d6fc9e | 19b27664ea31030ebdaf7c4ea97d40e30a8b3482 | refs/heads/master | 2020-04-30T06:53:09.963021 | 2018-05-03T12:24:23 | 2018-05-03T20:40:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 419 | cpp | #include <opencv2/opencv.hpp>
#include <iterator>
#include <string>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
std::ifstream file(argv[1]);
std::vector<char> data;
file >> std::noskipws;
std::copy(std::istream_iterator<char>(file),
std::istream_iterator<char>(),
std::back_inserter(data));
Mat matrixJprg = imdecode(Mat(data), 1);
return 0;
}
| [
"everest.munro-zeisberger_external.targetcw@coinbase.com"
] | everest.munro-zeisberger_external.targetcw@coinbase.com |
6e1cbbaa82ceb5a044747ae84ae31dd9be32423f | 1161a8bd0ec4c18791dfee3ade806f0ad61425d4 | /big_integer/myvector.cpp | dee92d9744c8ced4d401768f55f15e21e660fab0 | [] | no_license | ghost26/big_integer | 8f86a500f858ff0cec63b710dfc34cd19603af33 | 268aa5b0e38905604856f8277459954fce9efb43 | refs/heads/master | 2021-01-24T08:36:35.056980 | 2016-09-29T09:40:21 | 2016-09-29T09:40:21 | 69,553,235 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,336 | cpp | //
// myvector.cpp
// big_integer
//
// Created by Руслан Абдулхаликов on 18.06.15.
// Copyright (c) 2015 Руслан Абдулхаликов. All rights reserved.
//
#include <stdio.h>
#include <vector>
#include <iostream>
#include "myvector.h"
void myvector::make_my_copy()
{
if (*count != 1)
{
--*count;
std::vector<unsigned int> *copy = number;
number = new std::vector<unsigned int>;
count = new size_t;
*number = *copy;
*count = 1;
}
}
myvector::myvector() {
this->number = new std::vector<unsigned int>;
this->count = new size_t;
*count = 1;
}
myvector::~myvector() {
if (*count == 1)
{
delete number;
delete count;
}
else
{
--*count;
}
}
myvector::myvector(myvector const& other)
{
this->number = other.number;
this->count = other.count;
++*count;
}
myvector::myvector(size_t t)
{
this->number = new std::vector<unsigned int> (t);
this->count = new size_t;
*count = 1;
}
void myvector::clear()
{
if (*count == 1)
{
this->number->clear();
} else
{
--*count;
this->number = new std::vector<unsigned int>;
this->count = new size_t;
*count = 1;
}
}
void myvector::resize(size_t t)
{
this->make_my_copy();
this->number->resize(t);
}
void myvector::pop_back()
{
this->make_my_copy();
this->number->pop_back();
}
void myvector::push_back(unsigned int t)
{
this->make_my_copy();
this->number->push_back(t);
}
void myvector::reverse()
{
this->make_my_copy();
std::reverse(number->begin(), number->end());
}
unsigned int myvector::back() const
{
return this->number->back();
}
size_t myvector::size() const
{
return this->number->size();
}
myvector& myvector::operator=(myvector const& other)
{
if (this == &other)
{
return *this;
}
--(*count);
if ((*count) == 0)
{
delete number;
delete count;
}
this->number = other.number;
this->count = other.count;
++*count;
return *this;
}
unsigned int& myvector::operator[](size_t t)
{
this->make_my_copy();
return number->operator[](t);
}
unsigned int const& myvector::operator[](size_t t) const
{
return number->operator[](t);
}
| [
"russtav262@yandex.ru"
] | russtav262@yandex.ru |
dd4517991e3044cd11d775d87ecf15903ceaa659 | 86f1b47aac824eb3f1f24d025c8a8d618c952d0d | /precode/done/graph/Floyed-Warshal.cpp | 635074bfa20ec49081baa4d49a60fdc9806ccd2e | [] | no_license | anwar-arif/acm-code | 2fe9b2f71c3cc65d2aa680475300acbeab551532 | ad9c6f3f2a82bf231f848e9934faf9b5e591e923 | refs/heads/master | 2023-02-07T16:35:25.368871 | 2023-01-30T08:38:41 | 2023-01-30T08:38:41 | 127,539,902 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 442 | cpp | #include<bits/stdc++.h>
using namespace std;
const int N = (int) 2e5 + 10;
const int inf = (int) 2e9;
int main() {
for (k = 1; k <= V; k++) {
for (i = 1; i <= V; i++) {
for (j = 1; j <= V; j++) {
if (dist[i][j] > dist[i][k] + dist[k][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
return 0;
}
/*
complexity = n^3 . n = number of nodes
*/
| [
"anwarhossain221095@gmail.com"
] | anwarhossain221095@gmail.com |
ae98a33e44e4c16142e33cd118a7e3c0733c9f10 | bc27ba32828e40e5cd807c8e0b27759e60a533d9 | /led_fade/led_fade.ino | cff497e8c1d616f6e7228cc5474c6736a634cc7c | [] | no_license | dladowitz/arduino | f5dcc14e2f3110a8f02d4744fa7e6add2cab2989 | f971bc2911ce28dd586b01b6877caf394b509550 | refs/heads/master | 2020-04-06T04:14:51.538382 | 2015-03-17T17:47:34 | 2015-03-17T17:47:34 | 28,849,812 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 752 | ino | const int LED = 9; // set pin for the LED
const int BUTTON = 7; // set pin for pushbutton
int brightness = 124;
int val = 0; // val will be used to store the state of the input pin
void setup()
{
pinMode(LED, OUTPUT); // set LED pin as an output.
pinMode(BUTTON, INPUT); // set BUTTON pin as input.
}
void loop()
{
// val = digitalRead(BUTTON); // read input and store
// check whether the input is HIGH (button pressed)
for (brightness=0; brightness <= 255; brightness++) {
analogWrite(LED, brightness); // turn LED on
delay(20);
}
for (brightness = 255; brightness >= 0; brightness--) {
analogWrite(LED, brightness);
delay(20);
}
delay(250);
}
| [
"david@ladowitz.com"
] | david@ladowitz.com |
9f7bfd7cbe2177a09674b074cb719093293b6d56 | 773169c73bfa09c49046997b6aa92df68fec2b4e | /08_Basic_Data_Structures/10_Heaps/01_Heap_Using_Arrays.cc | 5494c8a124e9deee0942e63a83d00147f417ec42 | [] | no_license | the-stranded-alien/Competitive_Programming_CPP | a9995869bf34cc55ce55fa31da7f7b3b9aadb65d | 65dac7953fc1cfa8315f7fe40017abae7515d82f | refs/heads/master | 2022-12-22T06:39:12.240658 | 2020-09-16T12:57:28 | 2020-09-16T12:57:28 | 270,649,612 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,296 | cc | #include<iostream>
#include<vector>
using namespace std;
class Heap {
private:
vector<int> v;
bool minHeap;
bool compare(int a, int b) {
if(minHeap) return (a < b);
else return (a > b);
}
void heapify(int idx) {
int left = 2 * idx;
int right = (2 * idx) + 1;
int min_idx = idx;
int last = v.size() - 1;
// Compare With Both Right & Left Children
if(left <= last && compare(v[left], v[idx])) min_idx = left;
if(right <= last && compare(v[right], v[min_idx])) min_idx = right;
// Swap With The Smaller Children And Recursively Call The Function To Fix The Entire Heap
if(min_idx != idx) {
swap(v[idx], v[min_idx]);
heapify(min_idx);
}
return;
}
public:
Heap(int default_size = 10, bool type = true) {
v.reserve(default_size);
v.push_back(-1); // Blocking Index - 0
minHeap = type; // Min_Heap -> true / Max_Heap -> false
}
void push(int d) {
v.push_back(d);
int idx = v.size() - 1;
int parent = idx / 2;
// Keep Pushing To The Top Till You Reach A Root Node Or Stop Midway
// Because Current Element Is Already Greater / Lesser Than Parent.
while(idx > 1 && compare(v[idx], v[parent])) {
swap(v[idx], v[parent]);
idx = parent;
parent = parent / 2;
}
}
int top() {
return v[1];
}
void pop() {
// Swap First And Last Element
int last_idx = v.size() - 1;
swap(v[1], v[last_idx]);
// Remove The Last Element
v.pop_back();
// Heapify
heapify(1);
return;
}
bool empty() {
return (v.size() == 1);
}
};
int main() {
// Give Some Initial Size & Type (Min / Max Heap)
Heap h_min;
Heap h_max(10, false);
int n;
cin >> n;
for(int i = 0; i < n; i++) {
int no;
cin >> no;
h_min.push(no);
h_max.push(no);
}
cout << "Min Heap : ";
while(!h_min.empty()) {
cout << h_min.top() << " ";
h_min.pop();
}
cout << "\nMax Heap : ";
while(!h_max.empty()) {
cout << h_max.top() << " ";
h_max.pop();
}
return 0;
}
| [
"thestrandedalien.mysticdark@gmail.com"
] | thestrandedalien.mysticdark@gmail.com |
ebac13d6bca35fd6102197896b39f7e71775bfe2 | 814fda3bc42d0b324b33c2cbb57cb4a327f71e96 | /lib/year2015/src/Day12Puzzle.cpp | fe34fff2b04989125f57d90c2413347e7ed12abb | [
"MIT"
] | permissive | MarkRDavison/AdventOfCode | 377591ce341e37ef2bffa563ccd596fdacc83b60 | a415f3311ad29a5ed2703113769b04b9614e7d57 | refs/heads/main | 2022-12-21T10:04:37.032919 | 2022-12-18T05:55:29 | 2022-12-18T05:55:29 | 162,899,531 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,885 | cpp | #include <2015/Day12Puzzle.hpp>
#include <zeno-engine/Utility/StringExtensions.hpp>
#include <zeno-engine/Utility/Json.hpp>
#include <unordered_set>
#include <unordered_map>
#include <stack>
typedef std::pair<unsigned, unsigned> containerDepth;
struct pair_hash {
template <class T1, class T2>
std::size_t operator() (const std::pair<T1, T2>& pair) const {
return std::hash<T1>()(pair.first) ^ std::hash<T2>()(pair.second);
}
};
namespace TwentyFifteen {
Day12Puzzle::Day12Puzzle() :
core::PuzzleBase("JSAbacusFramework.io", 2015, 12) {
}
Day12Puzzle::~Day12Puzzle() {
}
void Day12Puzzle::initialise(const core::InitialisationInfo& _initialisationInfo) {
setInputLines(ze::StringExtensions::splitStringByDelimeter(ze::StringExtensions::loadFileToString(_initialisationInfo.parameters[0]), "\n"));
}
void Day12Puzzle::setInputLines(const std::vector<std::string>& _inputLines) {
m_InputLines = std::vector<std::string>(_inputLines);
}
std::pair<std::string, std::string> Day12Puzzle::fastSolve() {
const auto result = solve(m_InputLines[0]);
return { std::to_string(result.first), std::to_string(result.second) };
}
std::pair<int, int> Day12Puzzle::solve(const std::string& _input) {
ze::JsonDocument doc = ze::Json::parseFromText(_input);
const int part1 = recurser(*doc.m_Root, false);
const int part2 = recurser(*doc.m_Root, true);
return std::make_pair(part1, part2);
}
int Day12Puzzle::recurser(const ze::JsonNode& _node, bool _validate) {
int total = 0;
bool valid = true;
if (_validate) {
if (_node.type == ze::JsonNode::Type::Object) {
for (const auto& c : _node.children) {
if (c->content == "red") {
valid = false;
break;
}
}
}
}
if (valid) {
for (const auto c : _node.children) {
total += recurser(*c, _validate);
}
total += _node.integer;
}
return total;
}
}
| [
"markdavison0+github@gmail.com"
] | markdavison0+github@gmail.com |
b79cbd8bc4a0181b726efbe4aa6c02c9ebbbe355 | 10b4db1d4f894897b5ee435780bddfdedd91caf7 | /thrift/compiler/test/fixtures/stream/gen-cpp2/module_types.h | 60db43a0a483a2af62810b22c50bab844a34b5b1 | [
"Apache-2.0"
] | permissive | SammyEnigma/fbthrift | 04f4aca77a64c65f3d4537338f7fbf3b8214e06a | 31d7b90e30de5f90891e4a845f6704e4c13748df | refs/heads/master | 2021-11-11T16:59:04.628193 | 2021-10-12T11:19:22 | 2021-10-12T11:20:27 | 211,245,426 | 1 | 0 | Apache-2.0 | 2021-07-15T21:12:07 | 2019-09-27T05:50:42 | C++ | UTF-8 | C++ | false | false | 3,031 | h | /**
* Autogenerated by Thrift for src/module.thrift
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated @nocommit
*/
#pragma once
#include <thrift/lib/cpp2/gen/module_types_h.h>
namespace apache {
namespace thrift {
namespace tag {
} // namespace tag
namespace detail {
} // namespace detail
} // namespace thrift
} // namespace apache
// BEGIN declare_enums
// END declare_enums
// BEGIN forward_declare
namespace cpp2 {
class FooEx;
} // cpp2
// END forward_declare
// BEGIN typedefs
// END typedefs
// BEGIN hash_and_equal_to
// END hash_and_equal_to
THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN
namespace cpp2 {
using ::apache::thrift::detail::operator!=;
using ::apache::thrift::detail::operator>;
using ::apache::thrift::detail::operator<=;
using ::apache::thrift::detail::operator>=;
} // cpp2
namespace cpp2 {
class FOLLY_EXPORT FooEx : public apache::thrift::TException {
private:
friend struct ::apache::thrift::detail::st::struct_private_access;
// used by a static_assert in the corresponding source
static constexpr bool __fbthrift_cpp2_gen_json = false;
static constexpr bool __fbthrift_cpp2_gen_nimble = false;
static constexpr bool __fbthrift_cpp2_gen_has_thrift_uri = false;
static constexpr ::apache::thrift::ExceptionKind __fbthrift_cpp2_gen_exception_kind =
::apache::thrift::ExceptionKind::UNSPECIFIED;
static constexpr ::apache::thrift::ExceptionSafety __fbthrift_cpp2_gen_exception_safety =
::apache::thrift::ExceptionSafety::UNSPECIFIED;
static constexpr ::apache::thrift::ExceptionBlame __fbthrift_cpp2_gen_exception_blame =
::apache::thrift::ExceptionBlame::UNSPECIFIED;
public:
using __fbthrift_cpp2_type = FooEx;
static constexpr bool __fbthrift_cpp2_is_union =
false;
public:
FooEx();
// FragileConstructor for use in initialization lists only.
[[deprecated("This constructor is deprecated")]]
FooEx(apache::thrift::FragileConstructor);
FooEx(FooEx&&) noexcept;
FooEx(const FooEx& src);
FooEx& operator=(FooEx&&) noexcept;
FooEx& operator=(const FooEx& src);
void __clear();
~FooEx() override;
public:
bool operator==(const FooEx&) const;
bool operator<(const FooEx&) const;
template <class Protocol_>
uint32_t read(Protocol_* iprot);
template <class Protocol_>
uint32_t serializedSize(Protocol_ const* prot_) const;
template <class Protocol_>
uint32_t serializedSizeZC(Protocol_ const* prot_) const;
template <class Protocol_>
uint32_t write(Protocol_* prot_) const;
const char* what() const noexcept override {
return "::cpp2::FooEx";
}
private:
template <class Protocol_>
void readNoXfer(Protocol_* iprot);
friend class ::apache::thrift::Cpp2Ops<FooEx>;
friend void swap(FooEx& a, FooEx& b);
};
template <class Protocol_>
uint32_t FooEx::read(Protocol_* iprot) {
auto _xferStart = iprot->getCursorPosition();
readNoXfer(iprot);
return iprot->getCursorPosition() - _xferStart;
}
} // cpp2
THRIFT_IGNORE_ISSET_USE_WARNING_END
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
63280c7a76eabcf2f54ba2c05e7b01a5cbc36693 | d6507daa66666878fb018b394cc0a959a0113ec3 | /04/043.cc | ba580759db40eb36d8848dd223f324a813aff3c8 | [] | no_license | dmnsn7/projecteuler | a5d0098cdafcdb68901ecc68c0ba9df77d039ac4 | a737037b9521c940b6b6ed12488ee73e41229b70 | refs/heads/master | 2023-06-09T21:33:46.625979 | 2023-06-07T12:17:21 | 2023-06-07T12:17:21 | 215,997,596 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 865 | cc | // Copyright [2017] <dmnsn7@gmail.com>
#include <bits/stdc++.h>
using std::string;
using std::vector;
int fac(int n) { return n ? fac(n - 1) * n : 1; }
const int N = 9;
const int M = 3;
const int K = fac(N + 1);
const vector<int> prime = {2, 3, 5, 7, 11, 13, 17};
int main() {
string s;
for (int i = 0; i <= N; i++) {
s += i + '0';
}
int64_t sum = 0;
for (int i = 0; i < K; i++) {
next_permutation(s.begin(), s.end());
if (s[0] == '0') {
continue;
}
bool flag = true;
int64_t num;
for (int j = 0; j < prime.size() && flag; j++) {
string ts = string(s.begin() + j + 1, s.begin() + j + M + 1);
sscanf(ts.c_str(), "%ld", &num);
if (num % prime[j] != 0) {
flag = false;
}
}
sscanf(s.c_str(), "%ld", &num);
sum += flag ? num : 0;
}
printf("%ld\n", sum);
return 0;
}
| [
"jie.liu@airbnb.com"
] | jie.liu@airbnb.com |
093f043789852dedc04a7a8035f990720a2bd912 | a02676c1e81ebce3cf42f716f53d60ff29b0c22e | /source/utils/thread.cpp | e57bae272af9cf9c9c8e25c3251c1e742a190f45 | [
"MIT"
] | permissive | RocketRobz/SavvyManager | 0797c54c9b4d7b0f7c420816fecd3499e73e018a | 0c4c8d4b5c905b1e551767587805cebcddfb3b63 | refs/heads/master | 2023-08-08T23:08:53.413250 | 2023-08-03T21:10:10 | 2023-08-03T21:10:10 | 221,546,987 | 24 | 4 | MIT | 2020-05-27T09:06:54 | 2019-11-13T20:37:19 | C++ | UTF-8 | C++ | false | false | 463 | cpp | #include <3ds.h>
#include <vector>
#include "thread.h"
static std::vector<Thread> threads;
void createThread(ThreadFunc entrypoint) {
s32 prio = 0;
svcGetThreadPriority(&prio, CUR_THREAD_HANDLE);
Thread thread = threadCreate((ThreadFunc)entrypoint, NULL, 4*1024, prio-1, -2, false);
threads.push_back(thread);
}
void destroyThreads(void) {
for (u32 i = 0; i < threads.size(); i++)
{
threadJoin(threads.at(i), U64_MAX);
threadFree(threads.at(i));
}
} | [
"bobesh8@gmail.com"
] | bobesh8@gmail.com |
5108cfe2bf27cec4905931633b63e20d2b3927b7 | d7e87a28c0b853cdff1f4db9f52412a6fe67cb28 | /func.h | ea6d985ee510455989efea9e76811afd7d301a47 | [] | no_license | mju-oss-13-b/team4-calender | 2513f901cec18268b6cd4d343922ca009a98744d | 310440832fd11fd48386455e93ac21709efc9a33 | refs/heads/master | 2016-09-08T01:07:06.915804 | 2013-12-12T10:11:35 | 2013-12-12T10:11:35 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 13,344 | h | #include <iostream> //For all the console stream input-output operations 콘솔 명령어 입출력
#include <fstream> //For all the file stream input-output operations 파일 입출력
#include <string> //For all the string related functions 문자열
#include <stdio.h> //For all the standard input/output functions 스탠다드 입출력을 위함.
#include <windows.h> //For all the functions required to access WINDOWS API 윈도우 api를 승인 받기 위해 필요한 것
#include <ctype.h> //For all the character related functions 모든 케릭터와 관련된 펑션
#include <stdlib.h> //For all the Standard Library Functions (such as atoi) atoi같은 스탠다드 라이브러리
#include <math.h> //For all the standard mathematical functions 수학적 계산 위함.
#include <Shlobj.h> //For all the functions related to windows shell objects 윈도우 쉘 오브젝트 관련 펑션
#include <Shlwapi.h> //For all the Shell Registry Handling Functions 쉘 레지스트리 관리 펑션
#include "extern.h"
#pragma once
using namespace std;
class calendar
{
/**
This is the Main class of the Calendar Program
it contains all the member functions required to
perform all the calender related tasks in this calender
appication.
*/
/***************************************************************************************************************************************/
private:
int passscr();
char* inpass();
void setpos();
void newline();
/***************************************************************************************************************************************/
inline void cls( HANDLE hConsole )//HANDLE은
{
COORD coordScreen = { 0, 0 };
DWORD cCharsWritten;//DWARD는 4바이트 정수로 unsigned long이다.
CONSOLE_SCREEN_BUFFER_INFO csbi;//문서 참고
DWORD dwConSize;
if( !GetConsoleScreenBufferInfo( hConsole, &csbi ))
return;
dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
if( !FillConsoleOutputCharacter( hConsole,(TCHAR)' ',dwConSize,coordScreen,&cCharsWritten ))
return;
if( !GetConsoleScreenBufferInfo( hConsole, &csbi ))
return;
if( !FillConsoleOutputAttribute(hConsole,csbi.wAttributes,dwConSize,coordScreen,&cCharsWritten ))
return;
SetConsoleCursorPosition( hConsole, coordScreen );
}
/***************************************************************************************************************************************/
public:
void chkdate(); // function to check if date entered is valid. 유효한 날짜인지 체크하는 함수
void chkstr(); // function to check for a correct string while taking input. 인풋하는 동안에 스트링이 맞는 치 확인하는 함수
void calmenu(); // function to control key input in options menu. 옵션 메뉴를 컨트롤하는 함수.
void day2date (); // function to dates from a day in a month of an year.
void printAll(); // function to print calendar of an year on console screen.
void monthcal(); // function to print calendar of a month on console screen.
void printcaltofile(); // function to print calendar of an year to a .txt file.
/***************************************************************************************************************************************/
inline void roadblock() /**
Accessor Function to access the private member funtion digestMD5
and store a value to be used to verify if the credentials enterted match.
*/
{
a = passscr();
}
/***************************************************************************************************************************************/
inline void setscr() //Function to set the size of the console screen using standard windows functions
{
HANDLE hOut;
CONSOLE_SCREEN_BUFFER_INFO SBInfo;
SMALL_RECT DisplayArea = {0, 0, 0, 0}; /*Structure in windows library
Defines the coordinates of the
upper left and lower right corners of a rectangle.*/
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hOut,&SBInfo);
DisplayArea.Right = ri; // ri is the variable for storing width of console
DisplayArea.Bottom = bt; // bt is the variable for storing height of console
SetConsoleWindowInfo(hOut,TRUE,&DisplayArea);
}
/***************************************************************************************************************************************/
void clrline()
{
for(i=23;i<25;i++)
{
for(j=0;j<70;j++)
{
gotoxy(j,i);//좌표 이동 함수
putchar('\0');
}
}
}
/***************************************************************************************************************************************/
CONSOLE_SCREEN_BUFFER_INFO csbi; /*Function to go to any point
of the console screen
*Taken from CONIO library for Windows)*/
inline void gotoxy ( short x, short y )
{ COORD coord = {x, y};
SetConsoleCursorPosition ( GetStdHandle ( STD_OUTPUT_HANDLE ), coord );
//SetConsoleCursorPosition--A COORD structure that contains the column and row coordinates of the cursor in the console screen buffer.
}
/***************************************************************************************************************************************/
inline COORD getxy () //Function to get the position of the cursor the screen
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
COORD coord = csbi.dwCursorPosition;
return coord;
}
/***************************************************************************************************************************************/
char GetCh() //Function to accept a character from the keyboard(Taken from CONIO library fow Windows)
{
HANDLE hStdin = GetStdHandle (STD_INPUT_HANDLE);
INPUT_RECORD irInputRecord;
DWORD dwEventsRead;
char cChar;
while(ReadConsoleInputA (hStdin, &irInputRecord, 1, &dwEventsRead)) // Read key press
if (
irInputRecord.EventType == KEY_EVENT
&&irInputRecord.Event.KeyEvent.wVirtualKeyCode != VK_SHIFT
&&irInputRecord.Event.KeyEvent.wVirtualKeyCode != VK_MENU
&&irInputRecord.Event.KeyEvent.wVirtualKeyCode != VK_CONTROL
)
{
cChar = irInputRecord.Event.KeyEvent.uChar.AsciiChar;
ReadConsoleInputA (hStdin, &irInputRecord , 1, &dwEventsRead); //Read key release
return cChar;
}
return EOF;
}
INPUT_RECORD readkeys() //Function to read all types of special keys
{
HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE); //handle to store keyboard input
DWORD InputsRead = 0; //long int variable to store number of inputs
INPUT_RECORD irInput; //store keyboard input
FlushConsoleInputBuffer(hInput); //flushing input buffer
ReadConsoleInput(hInput, &irInput, 2, &InputsRead); //reading new input
return irInput;
}
/***************************************************************************************************************************************/
inline void docls() //user defined function to clear the screen using Windows library
{
HANDLE hStdout;
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
cls(hStdout);
}
/***************************************************************************************************************************************/
inline void setclr(int clrcode)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),clrcode);
}
/***************************************************************************************************************************************/
inline void clr_mrks()
{
int hy;
for(hy=4;hy<11;hy++)
{
gotoxy(3,hy); putchar ('\0');
}
}
/***************************************************************************************************************************************/
inline void infl(char o)
{
cin >>numstr; cin.ignore(10000, '\n');
switch(o)
{
case 'm': {if(isdigit(numstr[0])==0) {strcpy(str,numstr); lim=12; strcase='m';chkstr(); mon=strno;} else mon=atol(numstr); break;}
case 'y': {if(isdigit(numstr[0])==0) {again=1;} else year=atol(numstr); break;}
case 'd': {if(isdigit(numstr[0])==0) {again=1;} else date=atol(numstr); break;}
case 'f': {if(isdigit(numstr[0])==0) {strcpy(str,numstr);lim=6;strcase='d';chkstr();daynum=strno;}else{if (atol(numstr)<8){daynum=atol(numstr);ket=0;}else if(strno>7 || atol(numstr)>7){again=1;}}break;}
}
}
/***************************************************************************************************************************************/
inline void showinfo()
{
docls();
setclr(14);
gotoxy(35,1); cout<<"Calendar About\n\n\n";
setclr(10);
cout<<"\t<CALENDAR-Tool To Perform Calendar Related Functions>\n\tVersion - "<<ver.c_str()<<"\n\tCopyright (C) <2011-13> under GNU Affero General Public License\n\n\t";
cout<<"compiled using "; setclr(15); cout<<"GCC 4.6.1\n\n\t"; setclr(10);
cout<<"This Calendar app has been created by "; setclr(15);cout<<"Shivam Mathur"; setclr(10);cout<<"\n\t you can reach him here\n\n\t";
cout<<"Email \t\t : \t "; setclr(15); cout<<"shivam_jpr@hotmail.com\n\n\t";setclr(10);
cout<<"Facebook \t : \t"; setclr(15); cout<<" https://facebook.com/SHIVAMROCKZ\n\n\t";setclr(10);
cout<<"Twitter \t : \t "; setclr(15); cout<<"http://twitter.com/SAM_mathur\n\n\t"; setclr(10);
cout<<"This App is hosted at - Sourceforge\n\t";setclr(15); cout<<"https://sourceforge.net/projects/c-cpp-calender\n\n\t";setclr(10);
cout<<"Licence\n\t";setclr(15); cout<<"https://sourceforge.net/projects/c-cpp-calender/files/licence.txt";
repeat(8);
}
/***************************************************************************************************************************************/
inline int dayno() /**
Function to give the dayno of any date
For eg if day is Sunday on a date, dayno is '0'
*/
{
return (((cenno[((year/100)%4)]+((short)((year%100)+double(year%100)/4)%7)+month[mon-1])%7)+date)%7; //returing day no
}
/***************************************************************************************************************************************/
inline void logcal(char bi)
{
TCHAR pth[MAX_PATH]; //variable to store file name
SHGetFolderPath(NULL,CSIDL_LOCAL_APPDATA|CSIDL_FLAG_CREATE,NULL, 0,pth); /*function to find local applaction directory*/
PathAppend(pth, TEXT("Calendar\\cal.log")); //function to edit stored path
ofstream fout; fout.open(pth, ios::app );
SYSTEMTIME tm; /*SYSTEMTIME is a structure in Windows Library
used to access Windows Time of the System clock*/
GetLocalTime(&tm); //function ti get local timr of a country as per system clock
if (bi=='l')
fout<<"\nlogin-failure\t\t\t"<<tm.wDay<<"/"<<tm.wMonth<<"/"<<tm.wYear<<" "<<tm.wHour<<":"<<tm.wMinute<<":"<<tm.wSecond;
else if (bi=='s')
fout<<"\nlogin-success\t\t\t"<<tm.wDay<<"/"<<tm.wMonth<<"/"<<tm.wYear<<" "<<tm.wHour<<":"<<tm.wMinute<<":"<<tm.wSecond;
else if (bi=='d')
fout<<"\nDay Finder launched\t\t"<<tm.wDay<<"/"<<tm.wMonth<<"/"<<tm.wYear<<" "<<tm.wHour<<":"<<tm.wMinute<<":"<<tm.wSecond;
else if (bi=='m')
fout<<"\nMonth Calendar\t\t\t"<<tm.wDay<<"/"<<tm.wMonth<<"/"<<tm.wYear<<" "<<tm.wHour<<":"<<tm.wMinute<<":"<<tm.wSecond;
else if (bi=='y')
fout<<"\nYear Calendar\t\t\t"<<tm.wDay<<"/"<<tm.wMonth<<"/"<<tm.wYear<<" "<<tm.wHour<<":"<<tm.wMinute<<":"<<tm.wSecond;
else if (bi=='f')
fout<<"\nYear Calendar printed to file\t"<<tm.wDay<<"/"<<tm.wMonth<<"/"<<tm.wYear<<" "<<tm.wHour<<":"<<tm.wMinute<<":"<<tm.wSecond;
else if (bi=='t')
fout<<"\nDate finder launched\t\t"<<tm.wDay<<"/"<<tm.wMonth<<"/"<<tm.wYear<<" "<<tm.wHour<<":"<<tm.wMinute<<":"<<tm.wSecond;
fout.close();
}
/***************************************************************************************************************************************/
inline int repeat(int kvt) //Function to repeat parts of program
{
int fixl=0;
if(kvt==3)
{
gotoxy(0,47);
fixl=22;
}
else
gotoxy(0,25);
setclr(14); cout<<"\tDo you want to go to Options Menu Again\n\n"; //Asking the user if he wants to repeat the program
setclr(15); cout<<"\t YES\t\t\t\tNO:EXIT";
bool repin=true;
setclr(2);gotoxy(8,27+fixl); setclr(12); putchar (mark);
while(repin)
{
INPUT_RECORD keym=readkeys(); //reading keyboard input
if(keym.Event.KeyEvent.wVirtualKeyCode==VK_RIGHT) //Right key
{
setclr(2); gotoxy(8,27+fixl); putchar ('\0'); gotoxy(37,27+fixl); setclr(12); putchar (mark); //moving marker
}
if(keym.Event.KeyEvent.wVirtualKeyCode==VK_LEFT) //Left key
{
setclr(2); gotoxy(37,27+fixl); putchar ('\0'); gotoxy(8,27+fixl); setclr(12); putchar (mark); //moving marker
}
if(keym.Event.KeyEvent.wVirtualKeyCode==VK_RETURN) //ending loop on return(enter)
repin=false; //assigning false value to bool running to end the loop
}
COORD coort=getxy();
if(coort.X==37 )
exit(0);
}
};
extern calendar cal; | [
"root@csb-virtual-machine.(none)"
] | root@csb-virtual-machine.(none) |
28e8a7604bbf513d41a5a2485597729887aef513 | 66bded59e135d3f9e30c4cce3843e00e4d98515b | /src/noui.cpp | 559a0101eb9a94482c69203fe861d94795de612d | [
"MIT"
] | permissive | MBMB-Project/MBMB | 9b9e5076f91d5f1b69872b520360b8331f154184 | 281ae63469ed610e90159bbdc03978d13e7db6cb | refs/heads/master | 2020-04-18T02:42:36.007392 | 2019-01-26T12:21:56 | 2019-01-26T12:21:56 | 165,615,434 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,587 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The MBMB developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "noui.h"
#include "ui_interface.h"
#include "util.h"
#include <cstdio>
#include <stdint.h>
#include <string>
static bool noui_ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style)
{
bool fSecure = style & CClientUIInterface::SECURE;
style &= ~CClientUIInterface::SECURE;
std::string strCaption;
// Check for usage of predefined caption
switch (style) {
case CClientUIInterface::MSG_ERROR:
strCaption += _("Error");
break;
case CClientUIInterface::MSG_WARNING:
strCaption += _("Warning");
break;
case CClientUIInterface::MSG_INFORMATION:
strCaption += _("Information");
break;
default:
strCaption += caption; // Use supplied caption (can be empty)
}
if (!fSecure)
LogPrintf("%s: %s\n", strCaption, message);
fprintf(stderr, "%s: %s\n", strCaption.c_str(), message.c_str());
return false;
}
static void noui_InitMessage(const std::string& message)
{
LogPrintf("init message: %s\n", message);
}
void noui_connect()
{
// Connect mbmbd signal handlers
uiInterface.ThreadSafeMessageBox.connect(noui_ThreadSafeMessageBox);
uiInterface.InitMessage.connect(noui_InitMessage);
}
| [
"46668056+MBMB-Project@users.noreply.github.com"
] | 46668056+MBMB-Project@users.noreply.github.com |
5d62cb2f753285c0db992fbbc8604f07bbd746b0 | cff923ece9e7b670f239f2660ae35c6032d59f6e | /autentification.cpp | 24a0f3c3d7a19e862c44fe71d40e06b734d688b3 | [] | no_license | ksv141/pgAdminLite | 272f9b9286b3bdb5772356f13cbd6f7f61a844ab | ef080cca17186bba525fe87dfa28b8c880e3b190 | refs/heads/main | 2023-03-09T20:00:41.457836 | 2021-02-16T13:38:03 | 2021-02-16T13:38:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,375 | cpp | #include "autentification.h"
#include "clear.h"
#include <QLabel>
#include <QMenu>
#include <QMenuBar>
#include <QImage>
#include <clear.h>
#include <QStandardItem>
clear *Clear;
QMessageBox* newMessage;
QString regstr ="^[ ]*[a-zA-Zа-яА-Я_-0-9]*";
//================================================
//============ Function Help =====================
//================================================
QStringList List_MacLabel_In_OS_F1(QStringList listDB) {
QStringList mas;
QRegExp re( "([0-9]*)([A-Za-zа-яА-Я0-9_ -]*)\n" );
int i = 0;
while ( ( i = re.indexIn(listDB.value(0),i)) != -1 ) {
i +=re.matchedLength();
mas << re.cap( 2 );
mas << re.cap( 1 );
}
return mas;
}
void List_MacLabel_In_OS_ReLoad_To_Table(QStandardItemModel *model) {
QStandardItem *item;
QProcess * Mac_List = new QProcess;
Mac_List->start("userlev ");
Mac_List->waitForReadyRead();
QStringList strlist ;
strlist.append(Mac_List->readAllStandardOutput());
QStringList strlist_reg = List_MacLabel_In_OS_F1(strlist);
int N = 0;
for( int i = 0 ; i < strlist_reg.size() ; i+=2,N++) {
item = new QStandardItem(QString(strlist_reg[i]));
model->setItem(N,0,item);
item = new QStandardItem(QString(strlist_reg[i+1]));
model->setItem(N,1,item);
}
}
void List_KatLabel_In_OS_ReLoad_To_Table(QStandardItemModel *model) {
QStandardItem *item;
QProcess * Mac_List = new QProcess;
Mac_List->start("usercat ");
Mac_List->waitForReadyRead();
QStringList strlist ;
strlist.append(Mac_List->readAllStandardOutput());
QStringList strlist_reg = List_MacLabel_In_OS_F1(strlist);
int N = 0;
for( int i = 0 ; i < strlist_reg.size() ; i+=2,N++) {
item = new QStandardItem(QString(strlist_reg[i]));
model->setItem(N,0,item);
item = new QStandardItem(QString(strlist_reg[i+1]));
model->setItem(N,1,item);
}
}
//================================================
//============ autentification ===================
//================================================
autentification::~autentification() {}
autentification::autentification(QWidget *parent) :QDialog(parent)
{
this->setWindowTitle("Мандатное разграничение доступа в СУБД");
host = new QLineEdit(tr("localhost"), this);
dbname = new QLineEdit(tr("postgres"),this);
user = new QLineEdit(this);
password = new QLineEdit(this);
password->setEchoMode(QLineEdit::Password);
btnConnect = new QPushButton(("Подключиться"),this);
scr = new QTextEdit(this);
scr->setReadOnly(true);
host->setEnabled(false);
dbname->setEnabled(false);
QGridLayout *layout = new QGridLayout(this);
layout->addWidget(new QLabel(tr("Хост:"), this),
0, 0 ,Qt::AlignRight);
layout->addWidget(host, 0, 1);
layout->addWidget(new QLabel(tr("База данных:"), this),
0, 2, Qt::AlignRight);
layout->addWidget(dbname, 0, 3);
layout->addWidget(new QLabel(tr("Пользователь:"), this),
1, 0, Qt::AlignRight);
layout->addWidget(user, 1, 1);
layout->addWidget(new QLabel(tr("Пароль:"), this),
1, 2, Qt::AlignRight);
layout->addWidget(password, 1, 3);
layout->addWidget(btnConnect, 2, 1, 1, 2);
layout->addWidget(scr, 3, 0,1,4);
layout->setMargin(6);
layout->setSpacing(5);
setLayout(layout);
connect(btnConnect,SIGNAL(clicked(bool)),this,SLOT(connect_user()));
connect(this,SIGNAL(finished(int)),this,SLOT(Close_Main_Window()));
}
//----------------------------------
// autentification SLOTS
//----------------------------------
void autentification::Close_Main_Window() {
QSqlDatabase db =QSqlDatabase::database();
if(db.open()) {
db.close();
scr->append("=======================");
scr->append(tr("Соединение с БД закрыто!"));
}
}
bool autentification::connect_user() {
if(user->text() == "" || password->text() == "")
{
scr->append(tr("Проверьте правильность введенных данных"));
return false;
}
scr->append(tr("Соединяюсь с базой данных..."));
db = QSqlDatabase::addDatabase("QPSQL" );
db.setHostName(host->text());
db.setDatabaseName(dbname->text());
db.setUserName(user->text());
db.setPassword(password->text());
if (db.open()) {
host->setEnabled(false);
dbname->setEnabled(false);
user->setEnabled(false);
password->setEnabled(false);
btnConnect->setEnabled(false);
scr->append(tr("Соединение установлено!"));
if(user->text() == tr("postgres")) {
postgres = new admin(db,0,this);
postgres->show();
}
}else{
scr->append(tr("Не могу соединиться: "));
scr->append(db.lastError().text());
return false;
}
return true;
}
//================================================
//================= admin ========================
//================================================
admin::~admin(){}
admin::admin(QSqlDatabase &db, QWidget *parent, autentification *parent_window):QDialog(parent) {
pMainWindow = parent_window;
add_db = db;
pMainWindow->setVisible(false);
QObject::connect(this,SIGNAL(finished(int)),this,SLOT(Visible_Main_Window()));
this->setWindowTitle("МРД в СУБД. Администратор");
// MENU
QMenuBar* pMainmenu = new QMenuBar(this);
QMenu* SubUsers = new QMenu("Пользователи");
QMenu* SubMac = new QMenu("Мандатные метки");
QMenu* SubHelp = new QMenu("Справка");
//QMenu* SubSql = new QMenu("Sql запрос");
//QMenu* SubDatabase = new QMenu("БД");
//QMenu* SubTables = new QMenu("Таблицы");
//SubDatabase->addAction("Добавить",this,SLOT(Visible_DB_add()));
//SubDatabase->addAction("Удалить",this,SLOT(Visible_DB_del()));
//SubDatabase->addAction("Изменить",this,SLOT(Visible_DB_edit()));
//SubTables->addAction("Добавить",this,SLOT(Visible_Table_add()()));
//SubTables->addAction("Удалить",this,SLOT(Visible_Table_del()));
//SubTables->addAction("Изменить",this,SLOT(Visible_Table_edit()));
SubUsers->addAction("Добавить",this,SLOT(Visible_User_add()));
SubMac->addAction("Уровни",this,SLOT(Visible_Mac_Level()));
pMainmenu->addMenu(SubUsers);
pMainmenu->addMenu(SubMac);
pMainmenu->addMenu(SubHelp);
pMainmenu->show();
ShowAllTreeList();
Trwgt.resize(300,220);
connect(&Trwgt,SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)),this,SLOT(UserMac_open(QTreeWidgetItem*,int)));
layout = new QGridLayout(this);
Image = new QLabel;
QPixmap pMap("/QT/Project02/Main1.jpg");
Image->setPixmap(pMap);
panel = new QGroupBox;
QGridLayout *layout_new = new QGridLayout(this);
layout_new->addWidget(Image, 0, 0 );
panel->setLayout(layout_new);
panel->setMinimumSize(Image->width(),Image->height());
panel->show();
layout->addWidget(pMainmenu, 0,0,1,0);
layout->addWidget(&Trwgt, 1, 0 );
layout->addWidget(panel, 1, 1);
layout->setColumnMinimumWidth(0,230);
setLayout(layout);
}
//----------------------------------
// admin FUNCTION
//----------------------------------
QGridLayout* admin::Start_Panel() {
Image->setVisible(0);
QGroupBox*newWidget = new QGroupBox;
newWidget->setMinimumSize(Image->width(),Image->height());
QGridLayout *layout_new123 = new QGridLayout(this);
layout_new123->setMargin(6);
layout_new123->setSpacing(5);
newWidget->setLayout(layout_new123);
newWidget->show();
QLabel *Image1 = new QLabel;
QPixmap pMap("/QT/Project02/1122.jpg");
Image1->setPixmap(pMap);
Image1->setMaximumSize(Image->size());
Image1->show();
layout->addWidget(Image1, 1, 1);
layout->addWidget(newWidget, 1, 1);
return layout_new123;
}
void admin::ClearTreeList() {
UsersWithMac.clear();
DBMacLabel.clear();
int index = DB->parent()->indexOfChild(Trwgt.currentItem());
delete DB->parent()->takeChild(index);
index = Users->parent()->indexOfChild(Trwgt.currentItem());
delete Users->parent()->takeChild(index);
}
void admin::UpDateTreeList() {
DBMacLabel.clear();
UsersWithMac.clear();
// Cписок БД
QSqlQuery query = QSqlQuery(add_db);
if ( !query.exec("SELECT maclabel,datname FROM pg_database"))
{
newMessage = new QMessageBox(QMessageBox::Question , "Ошибка!",query.lastError().text(),QMessageBox::Yes);
newMessage->exec();
}
else
{
while (query.next() )
{
if(!(query.value(1).toString() == "template0" ||
query.value(1).toString() == "template1" ||
query.value(1).toString() == "postgres"))
{
QString str = query.value(1).toString();
QString mac = query.value(0).toString();
ListDB db1;
db1.nameDB = str;
db1.MacLabel = mac;
ListMacLabel LM1;
QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL" );
db.setHostName("localhost");
db.setDatabaseName(str);
db.setUserName("postgres");
db.setPassword("ast31ra1");
if (db.open()) {
QSqlQuery query_List_Table = QSqlQuery(db);
if (query_List_Table.exec("select * from pg_tables where tablename !~'^pg' and tablename !~'^sql'"))
{
while (query_List_Table.next())
{
QString TableName = query_List_Table.value(1).toString();
LM1.name = TableName;
db1.TableList.push_back(LM1);
}
}
}
DBMacLabel.push_back(db1);
}
}
}
// Добавляем метки к таблицам
QStringList NameTabel;
QStringList MacTabel;
for(int i = 0 ; i < DBMacLabel.size(); i++ ) {
QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL" );
db.setHostName("localhost");
db.setDatabaseName(DBMacLabel[i].nameDB);
db.setUserName("postgres");
db.setPassword("ast31ra1");
if (db.open()) {
QSqlQuery query_List_Table = QSqlQuery(db);
if ( query_List_Table.exec("select maclabel,relname from pg_class where relname !~'^pg' and relname !~'^sql'"))
{
while (query_List_Table.next() )
{
QString TableName = query_List_Table.value(1).toString();
QString TableMac = query_List_Table.value(0).toString();
NameTabel << TableName;
MacTabel << TableMac;
}
}
}
for(int j = 0; j < DBMacLabel[i].TableList.size(); j++) {
for(int k = 0 ;k < NameTabel.size(); k++) {
if(DBMacLabel[i].TableList[j].name == NameTabel[k]) {
DBMacLabel[i].TableList[j].MacLabel = MacTabel[k];
}
}
}
}
// Список Пользователей
QSqlQuery query_users = QSqlQuery(add_db);
if ( !query_users.exec("SELECT rolname FROM pg_roles"))
{
newMessage = new QMessageBox(QMessageBox::Question , "Ошибка! User",query_users.lastError().text(),QMessageBox::Yes);
newMessage->exec();
}
else {
while (query_users.next() ) {
QString str = query_users.value(0).toString();
ListMacLabelUser user1;
user1.name = str;
QProcess * MacUser = new QProcess;
MacUser->start("pdp-ulbls " + str);
MacUser->waitForReadyRead();
QStringList strlist ;
strlist.append(MacUser->readAllStandardOutput());
user1.MacLabel = strlist;
UsersWithMac.push_back(user1);
}
}
}
void admin::ShowAllTreeList() {
Trwgt.clear();
QStringList header ;
header<< "Меню" << "MacLable";
Trwgt.setHeaderLabels(header);
Trwgt.setColumnWidth(0,150);
Trwgt.setColumnWidth(1,70);
DB = new QTreeWidgetItem(&Trwgt);
DB->setText(0,"БД");
Users = new QTreeWidgetItem(&Trwgt);
Users->setText(0,"Пользователи");
Trwgt.setItemExpanded(DB,true);
Trwgt.setItemExpanded(Users,true);
Trwgt.sortColumn();
UpDateTreeList();
QTreeWidgetItem*_Item = 0;
for(int i = 0 ; i < UsersWithMac.size(); ++i) {
_Item = new QTreeWidgetItem(Users);
_Item->setText(0,UsersWithMac[i].name);
}
for(int i = 0 ; i < DBMacLabel.size(); ++i) {
_Item = new QTreeWidgetItem(DB);
_Item->setText(0,DBMacLabel[i].nameDB);
_Item->setText(1,DBMacLabel[i].MacLabel);
}
}
//----------------------------------
// admin SLOT
//----------------------------------
void admin::UserMac_open(QTreeWidgetItem *TrwgtItem, int)
{
if(TrwgtItem->parent() == Users) {
QPushButton *Yes = new QPushButton("Применить");
int index = Users->indexOfChild(Trwgt.currentItem());
QString text = UsersWithMac[index].MacLabel.at(0);
QGridLayout* layoutUser = Start_Panel();
layoutUser->addWidget(new QLabel("\nМандатные атрибуты : \n"),0, 0);
layoutUser->addWidget(new QLabel("\tМакс. уровень целостности : "),1, 0);
layoutUser->addWidget(new QLabel("\tМин. уровень: "),2, 0);
layoutUser->addWidget(new QLabel("\tМакс. уровень: "),3, 0);
layoutUser->addWidget(new QLabel("\tМин. набор категорий : "),4, 0);
layoutUser->addWidget(new QLabel("\tМакс. набор категорий : "),5, 0);
QComboBox *MacAtr = new QComboBox;
QComboBox *MaxLevMac = new QComboBox;
QComboBox *MinLevMac = new QComboBox;
QComboBox *MaxKat = new QComboBox;
QComboBox *MinKat = new QComboBox;
MacAtr->addItem(" 0");
MacAtr->addItem(" 1");
QStandardItemModel *modelCombo_Mac = new QStandardItemModel;
List_MacLabel_In_OS_ReLoad_To_Table(modelCombo_Mac);
for(int i = 0 ; i < modelCombo_Mac->rowCount(); i++) {
MaxLevMac->addItem(modelCombo_Mac->item(i,0)->text()+" "+
modelCombo_Mac->item(i,1)->text()+" ");
MinLevMac->addItem(modelCombo_Mac->item(i,0)->text()+" "+
modelCombo_Mac->item(i,1)->text()+" ");
}
QStandardItemModel *modelCombo_Kat = new QStandardItemModel;
List_KatLabel_In_OS_ReLoad_To_Table(modelCombo_Kat);
for(int i = 0 ; i < modelCombo_Kat->rowCount(); i++) {
MaxKat->addItem(modelCombo_Kat->item(i,0)->text() +" "+
modelCombo_Kat->item(i,1)->text()+" ");
MinKat->addItem(modelCombo_Kat->item(i,0)->text() +" "+
modelCombo_Kat->item(i,1)->text()+" ");
}
SaveList_Mac_User_to_OS[0] = MacAtr->itemText(0);
SaveList_Mac_User_to_OS[1] = MaxLevMac->itemText(0).replace(QRegExp("^[ ]*[a-zA-Zа-яА-Я_-0-9]*"),"");
SaveList_Mac_User_to_OS[2] = MinLevMac->itemText(0).replace(QRegExp("^[ ]*[a-zA-Zа-яА-Я_-0-9]*"),"");
SaveList_Mac_User_to_OS[3] = MaxKat->itemText(0).replace(QRegExp("^[ ]*[a-zA-Zа-яА-Я_-0-9]*"),"");
SaveList_Mac_User_to_OS[4] = MinKat->itemText(0).replace(QRegExp("^[ ]*[a-zA-Zа-яА-Я_-0-9]*"),"");
layoutUser->addWidget(MacAtr,1, 1,Qt::AlignLeft);
layoutUser->addWidget(MinLevMac,2, 1,Qt::AlignLeft);
layoutUser->addWidget(MaxLevMac,3, 1,Qt::AlignLeft);
layoutUser->addWidget(MinKat,4, 1,Qt::AlignLeft);
layoutUser->addWidget(MaxKat,5, 1,Qt::AlignLeft);
QObject::connect(MacAtr,SIGNAL(currentIndexChanged(QString)),this,SLOT(Slot_Admin1(QString)));
QObject::connect(MinLevMac,SIGNAL(currentIndexChanged(QString)),this,SLOT(Slot_Admin2(QString)));
QObject::connect(MaxLevMac,SIGNAL(currentIndexChanged(QString)),this,SLOT(Slot_Admin3(QString)));
QObject::connect(MinKat,SIGNAL(currentIndexChanged(QString)),this,SLOT(Slot_Admin4(QString)));
QObject::connect(MaxKat,SIGNAL(currentIndexChanged(QString)),this,SLOT(Slot_Admin5(QString)));
layoutUser->addWidget(new QLabel("\nТекущее значение :\n"),11, 0);
layoutUser->addWidget(new QLabel(text),12, 0);
Yes->setMaximumWidth(100);
layoutUser->addWidget(Yes,13, 1,Qt::AlignCenter);
Error = new QTextEdit("");
Error->setMaximumWidth(900);
Error->setMinimumWidth(500);
Error->setMaximumHeight(200);
layoutUser->addWidget(Error,13,0,Qt::AlignLeft);
QObject::connect(Yes,SIGNAL(clicked()),this,SLOT(Save_MacLabel_User1()));
}
if(TrwgtItem->parent() == DB) {
QGridLayout* layoutDB = Start_Panel();
int Index = DB->indexOfChild(Trwgt.currentItem());
QString NameDB = DBMacLabel[Index].nameDB;
layoutDB->addWidget(new QLabel("\nМандатная метка БД(" + NameDB +") = " + DBMacLabel[Index].MacLabel),0, 0);
RedMacDB = new QPushButton("Изменить МРД");
layoutDB->addWidget(RedMacDB,0, 1);
connect(RedMacDB,SIGNAL(clicked()),this,SLOT(RedMac_DB()));
RedMacTable = new QPushButton("Изменить МРД");
layoutDB->addWidget(RedMacTable,2, 1);
connect(RedMacTable,SIGNAL(clicked()),this,SLOT(RedMac_Table()));
parametrI = 0;
RedMacZapis = new QPushButton("Изменить МРД");
layoutDB->addWidget(RedMacZapis,5, 1);
connect(RedMacZapis,SIGNAL(clicked()),this,SLOT(RedMac_zapis()));
if(DBMacLabel[Index].TableList.size() != 0){
QComboBox * CMB1 = new QComboBox;
QObject::connect(CMB1,SIGNAL(activated(int)),this,SLOT(Index_for_table_DB_change(int)));
for(int i = 0 ; i < DBMacLabel[Index].TableList.size(); i++) {
CMB1->addItem(DBMacLabel[Index].TableList[i].name + " "+
DBMacLabel[Index].TableList[i].MacLabel );}
layoutDB->addWidget(new QLabel("Выбранная таблица: " + CMB1->itemText(0)),2, 0);
layoutDB->addWidget(CMB1,3, 0);
QSqlDatabase db1 = QSqlDatabase::addDatabase("QPSQL" );
db1.setHostName("localhost");
db1.setDatabaseName(NameDB);
db1.setUserName("postgres");
db1.setPassword("ast31ra1");
model_table_from_db = new QSqlTableModel;
model_table_from_db->setEditStrategy(QSqlTableModel::OnManualSubmit);
if (db1.open()) {
QString ZaprosTable = "";
QSqlQuery query_maclabel_estOrNet = QSqlQuery(db1);
query_maclabel_estOrNet.exec("select maclabel from \"" + DBMacLabel[Index].TableList[0].name + "\"" );
if("" == query_maclabel_estOrNet.record().value(0)) {
ZaprosTable = "select maclabel, * from \"" + DBMacLabel[Index].TableList[0].name + "\"" ;
} else {
ZaprosTable = "select * from \"" + DBMacLabel[Index].TableList[0].name + "\"" ;
}
QTableView *newView = new QTableView;
QSqlQuery query_table = QSqlQuery(db1);
QSqlQueryModel *model = new QSqlTableModel(newView);
query_table.exec(ZaprosTable);
model->setQuery(query_table);
newView->setModel(model);
layoutDB->addWidget(newView,4, 0);
}
}
}
}
void admin::Index_for_table_DB_change(int index) {
int Index = DB->indexOfChild(Trwgt.currentItem());
QGridLayout* layoutDB = Start_Panel();
layoutDB->addWidget(new QLabel("\nМандатная метка БД(" + DBMacLabel[Index].nameDB +") = " + DBMacLabel[Index].MacLabel),0, 0);
QComboBox * CMB1 = new QComboBox;
QObject::connect(CMB1,SIGNAL(activated(int)),this,SLOT(Index_for_table_DB_change(int)));
for(int i = 0 ; i < DBMacLabel[Index].TableList.size(); i++) {
CMB1->addItem(DBMacLabel[Index].TableList[i].name + " "+
DBMacLabel[Index].TableList[i].MacLabel );}
layoutDB->addWidget(new QLabel("Выбранная таблица: " + CMB1->itemText(index)),2, 0);
layoutDB->addWidget(CMB1,3, 0);
RedMacDB = new QPushButton("Изменить МРД");
layoutDB->addWidget(RedMacDB,0, 1);
connect(RedMacDB,SIGNAL(clicked()),this,SLOT(RedMac_DB()));
RedMacTable = new QPushButton("Изменить МРД");
layoutDB->addWidget(RedMacTable,2, 1);
connect(RedMacTable,SIGNAL(clicked()),this,SLOT(RedMac_Table()));
parametrI = index;
RedMacZapis = new QPushButton("Изменить МРД");
layoutDB->addWidget(RedMacZapis,5, 1);
connect(RedMacZapis,SIGNAL(clicked()),this,SLOT(RedMac_zapis()));
QSqlDatabase db1 = QSqlDatabase::addDatabase("QPSQL" );
db1.setHostName("localhost");
db1.setDatabaseName(DBMacLabel[Index].nameDB);
db1.setUserName("postgres");
db1.setPassword("ast31ra1");
model_table_from_db = new QSqlTableModel;
model_table_from_db->setEditStrategy(QSqlTableModel::OnManualSubmit);
if (db1.open()) {
QString ZaprosTable = "";
QSqlQuery query_maclabel_estOrNet = QSqlQuery(db1);
query_maclabel_estOrNet.exec("select maclabel from \"" + DBMacLabel[Index].TableList[index].name + "\"" );
if("" == query_maclabel_estOrNet.record().value(0)) {
ZaprosTable = "select maclabel, * from \"" + DBMacLabel[Index].TableList[index].name + "\"" ;
} else {
ZaprosTable = "select * from \"" + DBMacLabel[Index].TableList[index].name + "\"" ;
}
QSqlQuery query_table = QSqlQuery(db1);
query_table.exec(ZaprosTable);
QTableView *newView = new QTableView;
QSqlQueryModel *model = new QSqlTableModel(newView);
model->setQuery(query_table);
newView->setModel(model);
newView->setModel(model_table_from_db);
layoutDB->addWidget(newView,4, 0);
}
}
void admin::Save_MacLabel_User1() {
QStringList strlist;
QString arg0 = SaveList_Mac_User_to_OS[0].replace(QRegExp("[ ]*"),""); // целостность
QString arg1 = SaveList_Mac_User_to_OS[1].replace(QRegExp("[ ]*"),""); // макс. мак
QString arg2 = SaveList_Mac_User_to_OS[2].replace(QRegExp("[ ]*"),""); // мин. мак.
QString arg3 = SaveList_Mac_User_to_OS[3].replace(QRegExp("[ ]*"),""); // макс. кат.
QString arg4 = SaveList_Mac_User_to_OS[4].replace(QRegExp("[ ]*"),""); // мин. кат.
int Index = Users->indexOfChild(Trwgt.currentItem());
QString user_name = Users->child(Index)->text(0);
if((arg2 >= arg1) && (arg4 >= arg3 )) {
QProcess * Mac_Add = new QProcess;
QString Zap = "pdp-ulbls -m " + arg1 + ":" + arg2 +
" -i " + arg0 + " -c " + arg3 + ":" + arg4 +
" " + user_name;
Mac_Add->start(Zap);
Mac_Add->waitForReadyRead();
strlist.append(Mac_Add->readAllStandardOutput());
QString val = strlist.value(0);
if(val != "") {
Error->setText(val);}
else {
Error->setText("Error : Сравнение категорий происходит не по абсолютному значению!");
}
} else {
Error->setText("Error : Макс. уровень или макс. набор категорий не может превышать минимальный!");
}
}
void admin::Visible_Main_Window() {
pMainWindow->setVisible(true);
pMainWindow->ReturnUser()->setEnabled(true);
pMainWindow->Returnpassword()->setEnabled(true);
pMainWindow->ReturnbtnConnect()->setEnabled(true);
pMainWindow->ReturnUser()->setText("");
pMainWindow->Returnpassword()->setText("");
}
// Мандатные метки/Уровни. MAIN
void admin::Visible_Mac_Level(){
QGridLayout * layout_new123 = Start_Panel();
QLabel *l1 = new QLabel(tr("\nУровни : "), this);
QLabel *l2 = new QLabel(tr("Создать/Удалить"), this);
QStandardItemModel *model = new QStandardItemModel;
QStringList horizontalHeader;
horizontalHeader.append("Наименование");
horizontalHeader.append("Значение");
model->setHorizontalHeaderLabels(horizontalHeader);
List_MacLabel_In_OS_ReLoad_To_Table(model);
model_Table_OSMac = model;
Table_Level_Mac = new QTableView;
Table_Level_Mac->setModel(model);
Table_Level_Mac->resizeRowsToContents();
Table_Level_Mac->resizeColumnsToContents();
layout_new123->addWidget(l1,0, 0 );
layout_new123->addWidget(Table_Level_Mac,1, 0 );
layout_new123->addWidget(l2,2, 0 );
QPushButton *Change_Mac_add = new QPushButton("+");
QPushButton *Change_Mac_del = new QPushButton("-");
QGridLayout *AddDell = new QGridLayout;
AddDell->addWidget(Change_Mac_add,1, 0 , Qt::AlignRight);
AddDell->addWidget(Change_Mac_del,1, 1 , Qt::AlignLeft);
QWidget * Wd = new QWidget;
Wd->setLayout(AddDell);
Wd->show();
layout_new123->addWidget(Wd, 3, 0 );
QPushButton *Change_Mac = new QPushButton("Применить");
layout_new123->addWidget(Change_Mac,4, 0 );
QObject::connect(Change_Mac,SIGNAL(clicked()),this,SLOT(Save_MacLabel()));
QObject::connect(Change_Mac_add,SIGNAL(clicked()),this,SLOT(Add_Row_Table()));
QObject::connect(Change_Mac_del,SIGNAL(clicked()),this,SLOT(Del_Row_Table()));
}
//// Сохранить в ОС Linux
void admin::Add_Row_Table() {
model_Table_OSMac->insertRow(model_Table_OSMac->rowCount());
}
void admin::Del_Row_Table() {
int count = Table_Level_Mac->selectionModel()->selectedRows().count();
for(int i = 0 ; i < count ; i++) {
Table_Level_Mac->model()->removeRow(Table_Level_Mac->selectionModel()->selectedRows().at(i).row(),QModelIndex());
}
}
bool OS_Del_MacLabel_All(QString N) {
QProcess * Mac_Del = new QProcess;
Mac_Del->start("userlev -d " + N);
Mac_Del->waitForReadyRead();
QStringList strlist ;
strlist.append(Mac_Del->readAllStandardOutput());
if(strlist.value(0) != "" ) {
newMessage = new QMessageBox(QMessageBox::Question , "Ошибка!",strlist.value(0),QMessageBox::Yes);
newMessage->exec();
return 0;
}
return 1;
}
bool OS_Add_MacLabel(QString arg0,QString arg1) {
QStringList strlist ;
QProcess * Mac_Add = new QProcess;
Mac_Add->start("userlev " + arg0 + " -a " + arg1);
Mac_Add->waitForReadyRead();
strlist.append(Mac_Add->readAllStandardOutput());
if(strlist.value(0) != "" ) {
newMessage = new QMessageBox(QMessageBox::Question , "Ошибка!",strlist.value(0),QMessageBox::Yes);
newMessage->exec();
return 0;
}
return 1;
}
void admin::Save_MacLabel() {
QStandardItemModel *model = new QStandardItemModel;
List_MacLabel_In_OS_ReLoad_To_Table(model);
for(int i = 0 ; i < model->rowCount(); ++i) {
if(!OS_Del_MacLabel_All(model->item(i,1)->text())) {
}
}
int count = 0;
for(int i = 0 ; i < model_Table_OSMac->rowCount(); ++i) {
if(OS_Add_MacLabel(model_Table_OSMac->item(i,0)->text(),model_Table_OSMac->item(i,1)->text()) ) {
count ++;
}
}
if(count == model_Table_OSMac->rowCount()) {
newMessage = new QMessageBox(QMessageBox::Question , "Успех" ,"Настройки успешно применены",QMessageBox::Yes);
newMessage->exec();
} else {
// Перезапись старых меток
// Удаление
QStandardItemModel *model_new = new QStandardItemModel;
List_MacLabel_In_OS_ReLoad_To_Table(model_new);
for(int i = 0 ; i < model_new->rowCount(); ++i) {
if(!OS_Del_MacLabel_All(model_new->item(i,1)->text())) {
return;
}
}
// Запись
for(int i = 0 ; i < model->rowCount(); ++i) {
if(!OS_Add_MacLabel(model->item(i,0)->text(),model->item(i,1)->text()) ) {
return;
}
}
newMessage = new QMessageBox(QMessageBox::Question , "Ошибка!!!" ,"Проверьте правильность введенных данных!!!",QMessageBox::Yes);
newMessage->exec();
}
}
void admin::Visible_User_add() {
clear *c1 = new clear;
c1->show();
}
void admin::Visible_Mac_Kategorii(){};
QVector <ListDB> admin::Spisok_BD() {
return DBMacLabel;
}
void admin::RedMac_DB() {
int Index = DB->indexOfChild(Trwgt.currentItem());
QString name = DBMacLabel[Index].nameDB;
QString mac = DBMacLabel[Index].MacLabel;
Mac *m1 = new Mac;
m1->show();
m1->Red_mac_DB(name,"",mac);
connect(m1,SIGNAL(UpDataList()),this,SLOT(UpDataList_MacDB()));
}
void admin::UpDataList_MacDB() {
int Index = DB->indexOfChild(Trwgt.currentItem());
ShowAllTreeList();
Trwgt.setCurrentItem(DB->child(Index));
Index_for_table_DB_change(parametrI);
}
void admin::RedMac_Table() {
int Index = DB->indexOfChild(Trwgt.currentItem());
QString name = DBMacLabel[Index].nameDB;
int index = parametrI;
QString Table_name= DBMacLabel[Index].TableList[index].name;
QString mac = DBMacLabel[Index].TableList[index].MacLabel ;
Mac *m1 = new Mac;
m1->show();
QString mac_new;
m1->Red_mac_DB(name,Table_name,mac);
connect(m1,SIGNAL(UpDataList()),this,SLOT(UpDataList_MacTable()));
}
void admin::UpDataList_MacTable() {
int Index = DB->indexOfChild(Trwgt.currentItem());
ShowAllTreeList();
Trwgt.setCurrentItem(DB->child(Index));
Index_for_table_DB_change(parametrI);
}
void admin::RedMac_zapis() {
int Index = DB->indexOfChild(Trwgt.currentItem());
QString NameDB = DBMacLabel[Index].nameDB;
QString Table_name = DBMacLabel[Index].TableList[parametrI].name;
QSqlDatabase db1 = QSqlDatabase::addDatabase("QPSQL" );
db1.setHostName("localhost");
db1.setDatabaseName(NameDB);
db1.setUserName("postgres");
db1.setPassword("ast31ra1");
if (db1.open()) {
QSqlQuery query = QSqlQuery(db1);
QString ERROR = "";
for(int i = 0 ; i < model_table_from_db->rowCount(); i++ ) {
QSqlRecord rec = model_table_from_db->record(i);
QString mac = rec.value("maclabel").toString();
QVariant Iint = i+1;
QString Sint = Iint.toString();
QString zapros = "chmac " + Table_name + " set maclabel = ' " + mac + " ' where \"N\" = "+ Sint +";";
query.exec(zapros);
QString error_query = query.lastError().text();
if(error_query != " ") {ERROR +="\nСТРОКА №" + Sint + " \n " + error_query + "\n";}
}
if(ERROR == "") {
newMessage = new QMessageBox(QMessageBox::Question , "Отчет!","МРД применены",QMessageBox::Yes);
newMessage->exec();
} else {
newMessage = new QMessageBox(QMessageBox::Question , "Ошибка!",ERROR,QMessageBox::Yes);
newMessage->exec();
}
}
}
| [
"78598356+anile-adnay@users.noreply.github.com"
] | 78598356+anile-adnay@users.noreply.github.com |
53a7c104092769af3593755f47f689e285dfa21c | c14b2b8a2ddb956a9dc877f2005852b51195c98b | /libs/famitracker/Source/InstrumentEditDlg.h | 803932a934f9f71a7a0fe4e6ac36aaf81f6210ff | [] | no_license | zeroCoder1/nesicide | 9d946f0961b4f1bc4ae18c4debdbcfc34e8bf293 | 7d0da9f0c31b581a29d23747b275127d41964542 | refs/heads/master | 2020-12-28T19:46:19.673017 | 2013-11-10T04:08:27 | 2013-11-10T04:08:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,206 | h | /*
** FamiTracker - NES/Famicom sound tracker
** Copyright (C) 2005-2012 Jonathan Liss
**
** 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
** Library General Public License for more details. To obtain a
** copy of the GNU Library General Public License, write to the Free
** Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
**
** Any permitted reproduction of these routines, in whole or in part,
** must bear this legend.
*/
#pragma once
#include "resource.h"
#include "SequenceEditor.h"
#include "InstrumentEditPanel.h"
// CInstrumentEditDlg dialog
class CInstrumentEditDlg : public CDialog
{
Q_OBJECT
DECLARE_DYNAMIC(CInstrumentEditDlg)
// Qt stuff
protected:
void paintEvent(QPaintEvent *);
void mouseMoveEvent(QMouseEvent *event);
void mousePressEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
void mouseDoubleClickEvent(QMouseEvent *event);
void closeEvent(QCloseEvent *);
public slots:
void instTab_currentChanged(int arg1);
public:
CInstrumentEditDlg(CWnd* pParent = NULL); // standard constructor
virtual ~CInstrumentEditDlg();
void ChangeNoteState(int Note);
void SetCurrentInstrument(int Index);
bool IsOpened() const;
void EndDialog(int nResult);
CFamiTrackerDoc *GetDocument() const { return m_pDocument; };
// Dialog Data
enum { IDD = IDD_INSTRUMENT };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
void InsertPane(CInstrumentEditPanel *pPanel, bool Show);
void ClearPanels();
void SwitchOnNote(int x, int y);
void SwitchOffNote(bool ForceHalt);
protected:
// Constants
static const int PANEL_COUNT = 2;
static const int KEYBOARD_TOP;
static const int KEYBOARD_LEFT;
static const int KEYBOARD_WIDTH;
static const int KEYBOARD_HEIGHT;
static const TCHAR *CHIP_NAMES[];
protected:
// Variables for keyboard
int m_iLastKey;
int m_iActiveKey;
// Variables for windows
CInstrumentEditPanel *m_pPanels[PANEL_COUNT];
CInstrumentEditPanel *m_pFocusPanel;
bool m_bOpened;
int m_iSelectedInstType;
int m_iPanels;
int m_iInstrument;
CFamiTrackerDoc *m_pDocument;
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnBnClickedClose();
virtual BOOL OnInitDialog();
afx_msg void OnTcnSelchangeInstTab(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnPaint();
void ChangeNoteOn(int Note, int Octave);
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point);
virtual BOOL DestroyWindow();
protected:
virtual void OnOK();
virtual void OnCancel();
public:
afx_msg void OnNcLButtonUp(UINT nHitTest, CPoint point);
protected:
virtual void PostNcDestroy();
};
| [
"christopher_pow@hotmail.com"
] | christopher_pow@hotmail.com |
25ec4a0a95400bf06b26b06d0f5064e61b11dba7 | 7b1e74f46c06bd044059ed710d651f9b5b3f4314 | /Protocols/MaliciousRepMC.h | 03c4ee1d07c095377f688df6772084ede9282413 | [
"MIT",
"BSD-2-Clause"
] | permissive | n1v0lg/MP-SPDZ | 24543c69a6a9a408d2a50bea2608693597b13f77 | 5ef70589cbcd6a8116cc20ec9fd812b90df599eb | refs/heads/master | 2020-04-05T04:18:30.574529 | 2019-07-11T04:59:18 | 2019-07-11T04:59:18 | 156,545,896 | 0 | 0 | NOASSERTION | 2018-11-07T12:51:32 | 2018-11-07T12:51:32 | null | UTF-8 | C++ | false | false | 1,790 | h | /*
* MaliciousRepMC.h
*
*/
#ifndef PROTOCOLS_MALICIOUSREPMC_H_
#define PROTOCOLS_MALICIOUSREPMC_H_
#include "ReplicatedMC.h"
template<class T>
class MaliciousRepMC : public ReplicatedMC<T>
{
protected:
typedef ReplicatedMC<T> super;
public:
virtual void POpen_Begin(vector<typename T::open_type>& values,
const vector<T>& S, const Player& P);
virtual void POpen_End(vector<typename T::open_type>& values,
const vector<T>& S, const Player& P);
virtual void Check(const Player& P);
};
template<class T>
class HashMaliciousRepMC : public MaliciousRepMC<T>
{
crypto_generichash_state* hash_state;
octetStream os;
bool needs_checking;
void reset();
void update();
public:
// emulate MAC_Check
HashMaliciousRepMC(const typename T::value_type& _, int __ = 0, int ___ = 0) : HashMaliciousRepMC()
{ (void)_; (void)__; (void)___; }
// emulate Direct_MAC_Check
HashMaliciousRepMC(const typename T::value_type& _, Names& ____, int __ = 0, int ___ = 0) : HashMaliciousRepMC()
{ (void)_; (void)__; (void)___; (void)____; }
HashMaliciousRepMC();
~HashMaliciousRepMC();
void POpen_End(vector<typename T::open_type>& values,const vector<T>& S,const Player& P);
void CheckFor(const typename T::open_type& value, const vector<T>& shares, const Player& P);
void Check(const Player& P);
};
template<class T>
class CommMaliciousRepMC : public MaliciousRepMC<T>
{
vector<octetStream> os;
public:
void POpen_Begin(vector<typename T::clear>& values, const vector<T>& S,
const Player& P);
void POpen_End(vector<typename T::clear>& values, const vector<T>& S,
const Player& P);
void Check(const Player& P);
};
#endif /* PROTOCOLS_MALICIOUSREPMC_H_ */
| [
"mks.keller@gmail.com"
] | mks.keller@gmail.com |
c799068ef4b1f958c83a0b266f4cfc5dd6e26bfd | 04b95d4f9c4d2503d19685c548953c7ca6c7cdf0 | /PlugIns/CgProgramManager/include/OgreCgPrerequisites.h | a86230b3b80a812d8768316b3292d2d2af8ee964 | [
"MIT"
] | permissive | Kanma/Ogre | f3fa67cedab75f30ab6f03d77d12c727a553397f | 21bf1fbbfd8ade12d8009c00940e136d78f21bea | refs/heads/master | 2021-01-25T06:37:10.501303 | 2014-05-08T13:07:32 | 2014-05-08T13:07:32 | 526,053 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,347 | h | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2012 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#ifndef __CgPrerequisites_H__
#define __CgPrerequisites_H__
#include "OgreException.h"
#include <Cg/cg.h>
namespace Ogre {
/** Utility function, checks Cg for errors, throw exception if detected.
@param ogreMethod Ogre method name, as Class::method
@param errorTextPrefix The text to prefix the Cg error text with
*/
void checkForCgError(const String& ogreMethod, const String& errorTextPrefix, CGcontext context);
#if (OGRE_PLATFORM == OGRE_PLATFORM_WIN32) && !defined(__MINGW32__) && !defined(OGRE_STATIC_LIB)
# ifdef OGRE_CGPLUGIN_EXPORTS
# define _OgreCgPluginExport __declspec(dllexport)
# else
# if defined( __MINGW32__ )
# define _OgreCgPluginExport
# else
# define _OgreCgPluginExport __declspec(dllimport)
# endif
# endif
#elif defined ( OGRE_GCC_VISIBILITY )
# define _OgreCgPluginExport __attribute__ ((visibility("default")))
#else
# define _OgreCgPluginExport
#endif // OGRE_WIN32
}
#endif
| [
"philip.abbet@gmail.com"
] | philip.abbet@gmail.com |
a30544ea667cbd2da26848a1495f341bef05d20a | a2183d0f4fb3a52000cad9201e89d9d0f0c400f7 | /source/Classes/Client/Layers/UI/BattleUISmallMapPanel.cpp | 4a9a69f193ede60160b8a5edac48318d81862357 | [] | no_license | atom-chen/hellopet | 985374576ab20f9cd3c16255ea1db918dd493696 | a183a8234c3992ee6f3dff8ee711779a10c5c654 | refs/heads/master | 2020-06-17T07:53:16.523687 | 2015-07-18T14:02:35 | 2015-07-18T14:02:35 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,365 | cpp | #include "BattleUISmallMapPanel.h"
#include "GameManager/CommonLookUpUtils.h"
#include "GameManager/BattleManger.h"
#include "Sprite/SpriteDefiner.h"
#include "BattleUILayer.h"
#include "Layers/UI/UIManager.h"
#include "GameManager/NotificationCenterDefiner.h"
BattleUISmallMapPanel::BattleUISmallMapPanel(CCLayer* parentLayer,UILayer* uiLayer,Layout* layout):
UIPanelEventDelegateInterface(parentLayer,uiLayer,layout),
m_touchEvent(NULL),
m_parentWidget(NULL)
{
}
BattleUISmallMapPanel::~BattleUISmallMapPanel()
{
CCNotificationCenter::sharedNotificationCenter()->removeObserver(this,NotificationFlag[ENoticePlayerCreat]);
CCNotificationCenter::sharedNotificationCenter()->removeObserver(this,NotificationFlag[ENoticePlayerDie]);
}
void BattleUISmallMapPanel::Init()
{
if (m_layout != NULL && m_uiLayer != NULL && m_parentLayer != NULL)
{
CCNotificationCenter::sharedNotificationCenter()->addObserver(this,callfuncO_selector(BattleUISmallMapPanel::playerCreaterEvent),
NotificationFlag[ENoticePlayerCreat],NULL);
CCNotificationCenter::sharedNotificationCenter()->addObserver(this,callfuncO_selector(BattleUISmallMapPanel::playerDieEvent),
NotificationFlag[ENoticePlayerDie],NULL);
// Note: 得到玩家可移动Rect
BattleLayer* pBattleLayer = CommonLookUpUtils::GetBattleLayer();
if (pBattleLayer)
{
m_battleHeroMoveRect = pBattleLayer->GetHeroMoveRect();
}
m_parentWidget = dynamic_cast<UIImageView*>(m_uiLayer->getWidgetByName("smallMap"));
// Note: 得到可视区域大小
UIImageView* pViewRect = dynamic_cast<UIImageView*>(m_uiLayer->getWidgetByName("viewRect"));
if (pViewRect)
{
CCSize size = pViewRect->getSize();
m_smallMapHeroMoveRect = CCRectMake(pViewRect->getPosition().x - size.width/2,
pViewRect->getPosition().y - size.height/2,size.width,size.height);
}
}
}
void BattleUISmallMapPanel::playerCreaterEvent(CCObject* pObj)
{
if (pObj)
{
SpriteHeroBase* pHero = dynamic_cast<SpriteHeroBase*>(pObj);
if (pHero)
{
UIImageView* dotImage = createDot(pHero->GetBattleSide());
if (dotImage)
{
m_playerDots.insert(std::make_pair(pHero,dotImage));
}
}
}
}
void BattleUISmallMapPanel::playerDieEvent(CCObject* pObj)
{
if (pObj)
{
SpriteHeroBase* pHero = dynamic_cast<SpriteHeroBase*>(pObj);
if (pHero)
{
std::map<SpriteHeroBase*,UIImageView*>::iterator iter = m_playerDots.find(pHero);
if (iter != m_playerDots.end())
{
(*iter).second->removeFromParent();
m_playerDots.erase(iter);
}
}
}
}
UIImageView* BattleUISmallMapPanel::createDot(SpriteHeroBase::SIDE side)
{
UIImageView *dotImage = NULL;
if (m_layout)
{
dotImage = UIImageView::create();
if (dotImage)
{
if (side == SpriteHeroBase::LEFT)
{
dotImage->setTexture("icon/smallMapGreenDot.png",UI_TEX_TYPE_PLIST);
}
else
{
dotImage->setTexture("icon/smallMagRedDot.png",UI_TEX_TYPE_PLIST);
}
if (m_parentWidget)
{
m_parentWidget->addChild(dotImage);
}
else
{
return NULL;
}
}
}
return dotImage;
}
bool BattleUISmallMapPanel::ccTouchBegan(CCTouch *pTouches, CCEvent *pEvent)
{
m_touchEvent = pTouches;
return true;
}
void BattleUISmallMapPanel::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent)
{
}
void BattleUISmallMapPanel::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent)
{
}
bool BattleUISmallMapPanel::transformHeroPtToSmallMap(SpriteHeroBase* pHero,CCPoint& pt)
{
bool bRet = false;
if (pHero)
{
CCPoint heroPos = pHero->getPosition();
CCPoint heroRelativePos = ccpSub(heroPos,m_battleHeroMoveRect.origin);
float x = heroRelativePos.x / (m_battleHeroMoveRect.getMaxX() - m_battleHeroMoveRect.getMinX());
float y = heroRelativePos.y / (m_battleHeroMoveRect.getMaxY() - m_battleHeroMoveRect.getMinY());
float posx = x * (m_smallMapHeroMoveRect.getMaxX() - m_smallMapHeroMoveRect.getMinX());
float posy = y * (m_smallMapHeroMoveRect.getMaxY() - m_smallMapHeroMoveRect.getMinY());
posx += m_smallMapHeroMoveRect.origin.x;
posy += m_smallMapHeroMoveRect.origin.y;
pt.x = posx;
pt.y = posy;
}
return bRet;
}
void BattleUISmallMapPanel::Update(float dt)
{
for (std::map<SpriteHeroBase*,UIImageView*>::iterator iter = m_playerDots.begin();
iter != m_playerDots.end(); iter++)
{
CCPoint pt;
transformHeroPtToSmallMap((*iter).first,pt);
(*iter).second->setPosition(pt);
}
} | [
"zhibniu@gmail.com"
] | zhibniu@gmail.com |
a7cd9a11c2ce3484d2f34d3d17a7a653365aa3e2 | 41c4c7421bf346e246e550334ee0cc19f8f17485 | /DesignMode/Realty.h | 5ca29c9d92a724db2114896a48154808bd3ff573 | [] | no_license | xingyuan1hao/DesignPattern | 31e89ede424269f64f256b130db9086266acf030 | add44c2b82fe3d4e69c02b2592685aeff4173a7e | refs/heads/master | 2020-04-05T03:59:58.567733 | 2018-12-05T10:50:35 | 2018-12-05T10:50:35 | 156,534,374 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 151 | h | #pragma once
#include "Invest.h"
class Realty:public Invest
{
public:
Realty(void);
~Realty(void);
virtual void Sell();
virtual void Buy();
};
| [
"ahhlin@163.com"
] | ahhlin@163.com |
0061a532b71429156e3bdf093253944a940022fb | a6cf383f0e54fb6f2af794c4ef5db9981c7322f9 | /src/WebSocket.h | 4d875086f0fffd26dfcf2c1d32053b9b32cd5e46 | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | permissive | lostrepo/uWebSockets | 915917380dbded40ad093dad4b27da0c1312c896 | ee8fd1079d775570c7ecef7bab645b51e0d554a0 | refs/heads/master | 2023-02-24T02:47:31.342563 | 2021-02-03T12:44:16 | 2021-02-03T12:44:16 | 288,437,596 | 0 | 0 | Apache-2.0 | 2021-02-03T12:43:11 | 2020-08-18T11:32:14 | C++ | UTF-8 | C++ | false | false | 10,655 | h | /*
* Authored by Alex Hultman, 2018-2020.
* Intellectual property of third-party.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef UWS_WEBSOCKET_H
#define UWS_WEBSOCKET_H
#include "WebSocketData.h"
#include "WebSocketProtocol.h"
#include "AsyncSocket.h"
#include "WebSocketContextData.h"
#include <string_view>
namespace uWS {
template <bool SSL, bool isServer>
struct WebSocket : AsyncSocket<SSL> {
template <bool> friend struct TemplatedApp;
template <bool> friend struct HttpResponse;
private:
typedef AsyncSocket<SSL> Super;
void *init(bool perMessageDeflate, CompressOptions compressOptions, std::string &&backpressure) {
new (us_socket_ext(SSL, (us_socket_t *) this)) WebSocketData(perMessageDeflate, compressOptions, std::move(backpressure));
return this;
}
public:
/* Returns pointer to the per socket user data */
void *getUserData() {
WebSocketData *webSocketData = (WebSocketData *) us_socket_ext(SSL, (us_socket_t *) this);
/* We just have it overallocated by sizeof type */
return (webSocketData + 1);
}
/* See AsyncSocket */
using Super::getBufferedAmount;
using Super::getRemoteAddress;
using Super::getRemoteAddressAsText;
using Super::getNativeHandle;
/* Simple, immediate close of the socket. Emits close event */
using Super::close;
/* Send or buffer a WebSocket frame, compressed or not. Returns false on increased user space backpressure. */
bool send(std::string_view message, uWS::OpCode opCode = uWS::OpCode::BINARY, bool compress = false) {
WebSocketContextData<SSL> *webSocketContextData = (WebSocketContextData<SSL> *) us_socket_context_ext(SSL,
(us_socket_context_t *) us_socket_context(SSL, (us_socket_t *) this)
);
/* Skip sending and report success if we are over the limit of maxBackpressure */
if (webSocketContextData->maxBackpressure && webSocketContextData->maxBackpressure < getBufferedAmount()) {
/* Also defer a close if we should */
if (webSocketContextData->closeOnBackpressureLimit) {
us_socket_shutdown_read(SSL, (us_socket_t *) this);
}
return true;
}
/* Transform the message to compressed domain if requested */
if (compress) {
WebSocketData *webSocketData = (WebSocketData *) Super::getAsyncSocketData();
/* Check and correct the compress hint. It is never valid to compress 0 bytes */
if (message.length() && opCode < 3 && webSocketData->compressionStatus == WebSocketData::ENABLED) {
LoopData *loopData = Super::getLoopData();
/* Compress using either shared or dedicated deflationStream */
if (webSocketData->deflationStream) {
message = webSocketData->deflationStream->deflate(loopData->zlibContext, message, false);
} else {
message = loopData->deflationStream->deflate(loopData->zlibContext, message, true);
}
} else {
compress = false;
}
}
/* Check to see if we can cork for the user */
bool automaticallyCorked = false;
if (!Super::isCorked() && Super::canCork()) {
automaticallyCorked = true;
Super::cork();
}
/* Get size, alloate size, write if needed */
size_t messageFrameSize = protocol::messageFrameSize(message.length());
auto [sendBuffer, requiresWrite] = Super::getSendBuffer(messageFrameSize);
protocol::formatMessage<isServer>(sendBuffer, message.data(), message.length(), opCode, message.length(), compress);
/* This is the slow path, when we couldn't cork for the user */
if (requiresWrite) {
auto[written, failed] = Super::write(sendBuffer, (int) messageFrameSize);
/* For now, we are slow here */
free(sendBuffer);
if (failed) {
/* Return false for failure, skipping to reset the timeout below */
return false;
}
}
/* Uncork here if we automatically corked for the user */
if (automaticallyCorked) {
auto [written, failed] = Super::uncork();
if (failed) {
return false;
}
}
/* Every successful send resets the timeout */
if (webSocketContextData->resetIdleTimeoutOnSend) {
Super::timeout(webSocketContextData->idleTimeoutComponents.first);
WebSocketData *webSocketData = (WebSocketData *) Super::getAsyncSocketData();
webSocketData->hasTimedOut = false;
}
/* Return success */
return true;
}
/* Send websocket close frame, emit close event, send FIN if successful.
* Will not append a close reason if code is 0 or 1005. */
void end(int code = 0, std::string_view message = {}) {
/* Check if we already called this one */
WebSocketData *webSocketData = (WebSocketData *) us_socket_ext(SSL, (us_socket_t *) this);
if (webSocketData->isShuttingDown) {
return;
}
/* We postpone any FIN sending to either drainage or uncorking */
webSocketData->isShuttingDown = true;
/* Format and send the close frame */
static const int MAX_CLOSE_PAYLOAD = 123;
size_t length = std::min<size_t>(MAX_CLOSE_PAYLOAD, message.length());
char closePayload[MAX_CLOSE_PAYLOAD + 2];
size_t closePayloadLength = protocol::formatClosePayload(closePayload, (uint16_t) code, message.data(), length);
bool ok = send(std::string_view(closePayload, closePayloadLength), OpCode::CLOSE);
/* FIN if we are ok and not corked */
WebSocket<SSL, true> *webSocket = (WebSocket<SSL, true> *) this;
if (!webSocket->isCorked()) {
if (ok) {
/* If we are not corked, and we just sent off everything, we need to FIN right here.
* In all other cases, we need to fin either if uncork was successful, or when drainage is complete. */
webSocket->shutdown();
}
}
/* Emit close event */
WebSocketContextData<SSL> *webSocketContextData = (WebSocketContextData<SSL> *) us_socket_context_ext(SSL,
(us_socket_context_t *) us_socket_context(SSL, (us_socket_t *) this)
);
if (webSocketContextData->closeHandler) {
webSocketContextData->closeHandler(this, code, message);
}
/* Make sure to unsubscribe from any pub/sub node at exit */
webSocketContextData->topicTree.unsubscribeAll(webSocketData->subscriber, false);
delete webSocketData->subscriber;
webSocketData->subscriber = nullptr;
}
/* Corks the response if possible. Leaves already corked socket be. */
void cork(fu2::unique_function<void()> &&handler) {
if (!Super::isCorked() && Super::canCork()) {
Super::cork();
handler();
/* There is no timeout when failing to uncork for WebSockets,
* as that is handled by idleTimeout */
auto [written, failed] = Super::uncork();
} else {
/* We are already corked, or can't cork so let's just call the handler */
handler();
}
}
/* Subscribe to a topic according to MQTT rules and syntax */
void subscribe(std::string_view topic, bool nonStrict = false) {
WebSocketContextData<SSL> *webSocketContextData = (WebSocketContextData<SSL> *) us_socket_context_ext(SSL,
(us_socket_context_t *) us_socket_context(SSL, (us_socket_t *) this)
);
/* Make us a subscriber if we aren't yet */
WebSocketData *webSocketData = (WebSocketData *) us_socket_ext(SSL, (us_socket_t *) this);
if (!webSocketData->subscriber) {
webSocketData->subscriber = new Subscriber(this);
}
webSocketContextData->topicTree.subscribe(topic, webSocketData->subscriber, nonStrict);
}
/* Unsubscribe from a topic, returns true if we were subscribed */
bool unsubscribe(std::string_view topic, bool nonStrict = false) {
WebSocketContextData<SSL> *webSocketContextData = (WebSocketContextData<SSL> *) us_socket_context_ext(SSL,
(us_socket_context_t *) us_socket_context(SSL, (us_socket_t *) this)
);
WebSocketData *webSocketData = (WebSocketData *) us_socket_ext(SSL, (us_socket_t *) this);
return webSocketContextData->topicTree.unsubscribe(topic, webSocketData->subscriber, nonStrict);
}
/* Unsubscribe from all topics you might be subscribed to */
void unsubscribeAll() {
WebSocketContextData<SSL> *webSocketContextData = (WebSocketContextData<SSL> *) us_socket_context_ext(SSL,
(us_socket_context_t *) us_socket_context(SSL, (us_socket_t *) this)
);
WebSocketData *webSocketData = (WebSocketData *) us_socket_ext(SSL, (us_socket_t *) this);
webSocketContextData->topicTree.unsubscribeAll(webSocketData->subscriber);
}
/* Publish a message to a topic according to MQTT rules and syntax */
void publish(std::string_view topic, std::string_view message, OpCode opCode = OpCode::TEXT, bool compress = false) {
WebSocketContextData<SSL> *webSocketContextData = (WebSocketContextData<SSL> *) us_socket_context_ext(SSL,
(us_socket_context_t *) us_socket_context(SSL, (us_socket_t *) this)
);
/* Make us a subscriber if we aren't yet (important for allocating a sender address) */
WebSocketData *webSocketData = (WebSocketData *) us_socket_ext(SSL, (us_socket_t *) this);
if (!webSocketData->subscriber) {
webSocketData->subscriber = new Subscriber(this);
}
/* Publish as sender, does not receive its own messages even if subscribed to relevant topics */
webSocketContextData->publish(topic, message, opCode, compress, webSocketData->subscriber);
}
};
}
#endif // UWS_WEBSOCKET_H
| [
"alexhultman@gmail.com"
] | alexhultman@gmail.com |
8e65fd6c10f0348f356037d77eac1c4dfa618fea | 7f0fecfcdadd67036443a90034d34a0b0318a857 | /sparta/sparta/report/db/SingleUpdateReport.hpp | 3f8c7cc5c6a2aa26d1ad53767ccc2ed43a98d37f | [
"MIT"
] | permissive | timsnyder/map | e01b855288fc204d12e32198b2c8bd0f13c4cdf7 | aa4b0d7a1260a8051228707fd047431e1e52e01e | refs/heads/master | 2020-12-21T19:34:48.716857 | 2020-02-17T17:29:29 | 2020-02-17T17:29:29 | 236,536,756 | 0 | 0 | MIT | 2020-01-27T16:31:24 | 2020-01-27T16:31:23 | null | UTF-8 | C++ | false | false | 2,570 | hpp | // <SingleUpdateReport> -*- C++ -*-
#ifndef __SPARTA_STATISTICS_DATABASE_SINGLE_UPDATE_REPORT_H__
#define __SPARTA_STATISTICS_DATABASE_SINGLE_UPDATE_REPORT_H__
#include <cstdint>
#include <memory>
#include <vector>
#include "simdb_fwd.hpp"
#include "simdb/ObjectRef.hpp"
#include "simdb/schema/DatabaseTypedefs.hpp"
namespace simdb {
class ObjectManager;
} // namespace simdb
namespace sparta {
namespace db {
/*!
* \brief Wrapper around SimDB tables that are dedicated
* to report/SI persistence of single-update, non-timeseries
* report formats.
*
* \note All methods in this class are performed synchronously.
* Typically, you will only call the "write*()" method once
* for this object, and synchronous operation yields basically
* the same performance as asynchronous. However, if you have
* many of these reports to write in a SimDB, consider using
* this class together with AsyncNonTimeseriesReport for better
* overall performanace across all of the single-update report
* records.
*/
class SingleUpdateReport
{
public:
//! Construct with an ObjectRef to an existing record
//! in the SingleUpdateStatInstValues table.
explicit SingleUpdateReport(
std::unique_ptr<simdb::ObjectRef> obj_ref);
//! Add a new entry in the SingleUpdateStatInstValues
//! table. This record will be added to the given SimDB
//! you pass in, and the database ID corresponding to
//! the root-level Report node (typically retrieved
//! from ReportNodeHierarchy).
SingleUpdateReport(
const simdb::ObjectManager & obj_mgr,
const simdb::DatabaseID root_report_node_id);
//! Get this report record's database ID.
int getId() const;
//! Write the given SI values to this database record.
//! No compression will be performed.
void writeStatisticInstValues(
const std::vector<double> & si_values);
//! Write the *already compressed* SI values into
//! the database record.
void writeCompressedStatisticInstValues(
const std::vector<char> & compressed_si_values,
const uint32_t original_num_si_values);
//! Retrieve the SI values for this report. As this
//! is for single-update reports only, there are no
//! start/end time points like you see with the read
//! API's for the ReportTimeseries class.
void getStatisticInstValues(
std::vector<double> & si_values);
private:
std::unique_ptr<simdb::ObjectRef> obj_ref_;
simdb::DatabaseID root_report_node_id_ = 0;
};
} // namespace db
} // namespace sparta
#endif
| [
"klingaard@gmail.com"
] | klingaard@gmail.com |
1915a91098cb7fafd20f1b813d1c72870e4a9612 | a06515f4697a3dbcbae4e3c05de2f8632f8d5f46 | /corpus/taken_from_cppcheck_tests/stolen_10813.cpp | eb9fcfd7ed86bbce51765d43a24235b7add1e7a7 | [] | no_license | pauldreik/fuzzcppcheck | 12d9c11bcc182cc1f1bb4893e0925dc05fcaf711 | 794ba352af45971ff1f76d665b52adeb42dcab5f | refs/heads/master | 2020-05-01T01:55:04.280076 | 2019-03-22T21:05:28 | 2019-03-22T21:05:28 | 177,206,313 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 50 | cpp | void f() {
label:
foo();
goto label;
} | [
"github@pauldreik.se"
] | github@pauldreik.se |
92af0f480ca2691cb9b9e888b1471dd2994c645e | bd1fea86d862456a2ec9f56d57f8948456d55ee6 | /000/106/745/CWE590_Free_Memory_Not_on_Heap__delete_array_struct_alloca_10.cpp | 69dd1ba8a40622503b84678f784c03a9b00b6da4 | [] | 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 | 3,965 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE590_Free_Memory_Not_on_Heap__delete_array_struct_alloca_10.cpp
Label Definition File: CWE590_Free_Memory_Not_on_Heap__delete_array.label.xml
Template File: sources-sink-10.tmpl.cpp
*/
/*
* @description
* CWE: 590 Free Memory Not on Heap
* BadSource: alloca Data buffer is allocated on the stack with alloca()
* GoodSource: Allocate memory on the heap
* Sink:
* BadSink : Print then free data
* Flow Variant: 10 Control flow: if(globalTrue) and if(globalFalse)
*
* */
#include "std_testcase.h"
#include <wchar.h>
namespace CWE590_Free_Memory_Not_on_Heap__delete_array_struct_alloca_10
{
#ifndef OMITBAD
void bad()
{
twoIntsStruct * data;
data = NULL; /* Initialize data */
if(globalTrue)
{
{
/* FLAW: data is allocated on the stack and deallocated in the BadSink */
twoIntsStruct * dataBuffer = (twoIntsStruct *)ALLOCA(100*sizeof(twoIntsStruct));
{
size_t i;
for (i = 0; i < 100; i++)
{
dataBuffer[i].intOne = 1;
dataBuffer[i].intTwo = 1;
}
}
data = dataBuffer;
}
}
printStructLine(&data[0]);
/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
delete [] data;
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B1() - use goodsource and badsink by changing the globalTrue to globalFalse */
static void goodG2B1()
{
twoIntsStruct * data;
data = NULL; /* Initialize data */
if(globalFalse)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
{
/* FIX: data is allocated on the heap and deallocated in the BadSink */
twoIntsStruct * dataBuffer = new twoIntsStruct[100];
{
size_t i;
for (i = 0; i < 100; i++)
{
dataBuffer[i].intOne = 1;
dataBuffer[i].intTwo = 1;
}
}
data = dataBuffer;
}
}
printStructLine(&data[0]);
/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
delete [] data;
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */
static void goodG2B2()
{
twoIntsStruct * data;
data = NULL; /* Initialize data */
if(globalTrue)
{
{
/* FIX: data is allocated on the heap and deallocated in the BadSink */
twoIntsStruct * dataBuffer = new twoIntsStruct[100];
{
size_t i;
for (i = 0; i < 100; i++)
{
dataBuffer[i].intOne = 1;
dataBuffer[i].intTwo = 1;
}
}
data = dataBuffer;
}
}
printStructLine(&data[0]);
/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
delete [] data;
}
void good()
{
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE590_Free_Memory_Not_on_Heap__delete_array_struct_alloca_10; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| [
"frank@fischer.com.mt"
] | frank@fischer.com.mt |
5d3b92952c10bd4caef239bd79bb57029ab049be | b37d061c39b58a6c82a23c481de68334688b49a2 | /Ashish/TopCoder/Div1A/LeaguePicks.cpp | 6c20e08103780b600e984e9e703411e6f5bc9e37 | [] | no_license | AshishKhatkar/ICPC-Practice | 79bee31a264c34803d6bf314fa4e486a63e8a232 | ee46bcad24697223d98c0796c6dfd04e6ae8c76a | refs/heads/master | 2021-05-03T06:03:24.430598 | 2015-12-11T16:55:21 | 2015-12-11T16:55:21 | 43,705,527 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,075 | cpp | #include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define MOD 1000000007
using namespace std;
class LeaguePicks {
public:
vector <int> returnPicks(int, int, int);
};
vector <int> LeaguePicks::returnPicks(int position, int friends, int picks) {
vector<int> res;
int turn = 1;
int pos = position;
if(pos <= picks) {
res.push_back(position);
}
while(pos <= picks) {
if(turn == 0) {
pos = pos + 2 * (position - 1) + 1;
turn = 1;
} else {
pos = pos + 2 * (friends - position) + 1;
turn = 0;
}
if(pos <= picks) {
res.push_back(pos);
}
}
return res;
}
double test0() {
int p0 = 3;
int p1 = 6;
int p2 = 15;
LeaguePicks * obj = new LeaguePicks();
clock_t start = clock();
vector <int> my_answer = obj->returnPicks(p0, p1, p2);
clock_t end = clock();
delete obj;
cout <<"Time: " <<(double)(end-start)/CLOCKS_PER_SEC <<" seconds" <<endl;
int t3[] = { 3, 10, 15 };
vector <int> p3(t3, t3+sizeof(t3)/sizeof(int));
cout <<"Desired answer: " <<endl;
cout <<"\t{ ";
if (p3.size() > 0) {
cout <<p3[0];
for (int i=1; i<p3.size(); i++)
cout <<", " <<p3[i];
cout <<" }" <<endl;
}
else
cout <<"}" <<endl;
cout <<endl <<"Your answer: " <<endl;
cout <<"\t{ ";
if (my_answer.size() > 0) {
cout <<my_answer[0];
for (int i=1; i<my_answer.size(); i++)
cout <<", " <<my_answer[i];
cout <<" }" <<endl;
}
else
cout <<"}" <<endl;
if (my_answer != p3) {
cout <<"DOESN'T MATCH!!!!" <<endl <<endl;
return -1;
}
else {
cout <<"Match :-)" <<endl <<endl;
return (double)(end-start)/CLOCKS_PER_SEC;
}
}
double test1() {
int p0 = 1;
int p1 = 1;
int p2 = 10;
LeaguePicks * obj = new LeaguePicks();
clock_t start = clock();
vector <int> my_answer = obj->returnPicks(p0, p1, p2);
clock_t end = clock();
delete obj;
cout <<"Time: " <<(double)(end-start)/CLOCKS_PER_SEC <<" seconds" <<endl;
int t3[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
vector <int> p3(t3, t3+sizeof(t3)/sizeof(int));
cout <<"Desired answer: " <<endl;
cout <<"\t{ ";
if (p3.size() > 0) {
cout <<p3[0];
for (int i=1; i<p3.size(); i++)
cout <<", " <<p3[i];
cout <<" }" <<endl;
}
else
cout <<"}" <<endl;
cout <<endl <<"Your answer: " <<endl;
cout <<"\t{ ";
if (my_answer.size() > 0) {
cout <<my_answer[0];
for (int i=1; i<my_answer.size(); i++)
cout <<", " <<my_answer[i];
cout <<" }" <<endl;
}
else
cout <<"}" <<endl;
if (my_answer != p3) {
cout <<"DOESN'T MATCH!!!!" <<endl <<endl;
return -1;
}
else {
cout <<"Match :-)" <<endl <<endl;
return (double)(end-start)/CLOCKS_PER_SEC;
}
}
double test2() {
int p0 = 1;
int p1 = 2;
int p2 = 39;
LeaguePicks * obj = new LeaguePicks();
clock_t start = clock();
vector <int> my_answer = obj->returnPicks(p0, p1, p2);
clock_t end = clock();
delete obj;
cout <<"Time: " <<(double)(end-start)/CLOCKS_PER_SEC <<" seconds" <<endl;
int t3[] = { 1, 4, 5, 8, 9, 12, 13, 16, 17, 20, 21, 24, 25, 28, 29, 32, 33, 36, 37 };
vector <int> p3(t3, t3+sizeof(t3)/sizeof(int));
cout <<"Desired answer: " <<endl;
cout <<"\t{ ";
if (p3.size() > 0) {
cout <<p3[0];
for (int i=1; i<p3.size(); i++)
cout <<", " <<p3[i];
cout <<" }" <<endl;
}
else
cout <<"}" <<endl;
cout <<endl <<"Your answer: " <<endl;
cout <<"\t{ ";
if (my_answer.size() > 0) {
cout <<my_answer[0];
for (int i=1; i<my_answer.size(); i++)
cout <<", " <<my_answer[i];
cout <<" }" <<endl;
}
else
cout <<"}" <<endl;
if (my_answer != p3) {
cout <<"DOESN'T MATCH!!!!" <<endl <<endl;
return -1;
}
else {
cout <<"Match :-)" <<endl <<endl;
return (double)(end-start)/CLOCKS_PER_SEC;
}
}
double test3() {
int p0 = 5;
int p1 = 11;
int p2 = 100;
LeaguePicks * obj = new LeaguePicks();
clock_t start = clock();
vector <int> my_answer = obj->returnPicks(p0, p1, p2);
clock_t end = clock();
delete obj;
cout <<"Time: " <<(double)(end-start)/CLOCKS_PER_SEC <<" seconds" <<endl;
int t3[] = { 5, 18, 27, 40, 49, 62, 71, 84, 93 };
vector <int> p3(t3, t3+sizeof(t3)/sizeof(int));
cout <<"Desired answer: " <<endl;
cout <<"\t{ ";
if (p3.size() > 0) {
cout <<p3[0];
for (int i=1; i<p3.size(); i++)
cout <<", " <<p3[i];
cout <<" }" <<endl;
}
else
cout <<"}" <<endl;
cout <<endl <<"Your answer: " <<endl;
cout <<"\t{ ";
if (my_answer.size() > 0) {
cout <<my_answer[0];
for (int i=1; i<my_answer.size(); i++)
cout <<", " <<my_answer[i];
cout <<" }" <<endl;
}
else
cout <<"}" <<endl;
if (my_answer != p3) {
cout <<"DOESN'T MATCH!!!!" <<endl <<endl;
return -1;
}
else {
cout <<"Match :-)" <<endl <<endl;
return (double)(end-start)/CLOCKS_PER_SEC;
}
}
int main() {
int time;
bool errors = false;
time = test0();
if (time < 0)
errors = true;
time = test1();
if (time < 0)
errors = true;
time = test2();
if (time < 0)
errors = true;
time = test3();
if (time < 0)
errors = true;
if (!errors)
cout <<"You're a stud (at least on the example cases)!" <<endl;
else
cout <<"Some of the test cases had errors." <<endl;
}
//Powered by [KawigiEdit] 2.0!
| [
"akhatkar64@gmail.com"
] | akhatkar64@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.