blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
809b39b3a66ac1c187725f109cdb0327a677afbd | a283b170dd56a16a05cbddaa6d8be4398c630d80 | /d01/ex10/Cat.hpp | 9c5b39d3048d3b964e29faeb0efaac2b7c7d6a30 | [] | no_license | Julow/cpp_pool | 9ac75e34d88ef136f40917f5edc84ee24f7a4a58 | c6b0ab48a352b17f1942a4415bd31305395ff9ee | refs/heads/master | 2021-01-15T11:48:41.431464 | 2016-01-13T16:02:58 | 2016-01-13T16:02:58 | 34,286,820 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,127 | hpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Cat.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jaguillo <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/04/07 17:51:04 by jaguillo #+# #+# */
/* Updated: 2015/04/07 18:20:22 by jaguillo ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef CAT_HPP
# define CAT_HPP
# include <string>
# define BUFF_SIZE 512
class Cat
{
public:
void read(std::string const &str);
private:
void _readFile(std::string const &str);
void _read(std::istream &in);
};
#endif
| [
"[email protected]"
] | |
490931b07704328fa1635c9be3eead64234b776a | 70488ceead10ebf62ef7187c61609f7953dae198 | /three/lights/hemisphere_light.hpp | b0237b1a02d3bf18747aec8f875e6f470554cc70 | [
"MIT"
] | permissive | darkcoordinate/three_cpp | acde3a110f6bda95dd5ff480219738b872f5120f | 0b25c423f063956197f0af93fbaa50983a5a491f | refs/heads/master | 2021-01-19T21:57:59.793428 | 2016-04-09T06:43:52 | 2016-04-09T06:43:52 | 55,829,890 | 0 | 0 | null | 2016-04-09T06:38:25 | 2016-04-09T06:38:25 | null | UTF-8 | C++ | false | false | 939 | hpp | #ifndef THREE_HEMISPHERE_LIGHT_HPP
#define THREE_HEMISPHERE_LIGHT_HPP
#include <three/common.hpp>
#include <three/lights/light.hpp>
namespace three {
class HemisphereLight : public Light {
public:
typedef std::shared_ptr<HemisphereLight> Ptr;
static Ptr create( int skyColorHex, int groundColorHex, float intensity = 1 ) {
return make_shared<HemisphereLight>( skyColorHex, groundColorHex, intensity );
}
virtual THREE::Type type() const { return THREE::HemisphereLight; }
//////////////////////////////////////////////////////////////////////////
Color groundColor;
//////////////////////////////////////////////////////////////////////////
protected:
HemisphereLight( int skyColorHex, int groundColorHex, float intensity )
: Light( skyColorHex, intensity ),
groundColor( groundColorHex ) {
position = Vector3( 0, 100, 0 );
}
};
} // namespace three
#endif // THREE_HEMISPHERE_LIGHT_HPP | [
"[email protected]"
] | |
8f075ad6ebfc702ecc769942f96004bfec3bc9a0 | 2cf838b54b556987cfc49f42935f8aa7563ea1f4 | /aws-cpp-sdk-network-firewall/include/aws/network-firewall/model/DisassociateSubnetsRequest.h | 68d7a657035acb32083ab344caec8e9736e6ee4d | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | QPC-database/aws-sdk-cpp | d11e9f0ff6958c64e793c87a49f1e034813dac32 | 9f83105f7e07fe04380232981ab073c247d6fc85 | refs/heads/main | 2023-06-14T17:41:04.817304 | 2021-07-09T20:28:20 | 2021-07-09T20:28:20 | 384,714,703 | 1 | 0 | Apache-2.0 | 2021-07-10T14:16:41 | 2021-07-10T14:16:41 | null | UTF-8 | C++ | false | false | 17,304 | h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/network-firewall/NetworkFirewall_EXPORTS.h>
#include <aws/network-firewall/NetworkFirewallRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <utility>
namespace Aws
{
namespace NetworkFirewall
{
namespace Model
{
/**
*/
class AWS_NETWORKFIREWALL_API DisassociateSubnetsRequest : public NetworkFirewallRequest
{
public:
DisassociateSubnetsRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "DisassociateSubnets"; }
Aws::String SerializePayload() const override;
Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;
/**
* <p>An optional token that you can use for optimistic locking. Network Firewall
* returns a token to your requests that access the firewall. The token marks the
* state of the firewall resource at the time of the request. </p> <p>To make an
* unconditional change to the firewall, omit the token in your update request.
* Without the token, Network Firewall performs your updates regardless of whether
* the firewall has changed since you last retrieved it.</p> <p>To make a
* conditional change to the firewall, provide the token in your update request.
* Network Firewall uses the token to ensure that the firewall hasn't changed since
* you last retrieved it. If it has changed, the operation fails with an
* <code>InvalidTokenException</code>. If this happens, retrieve the firewall again
* to get a current copy of it with a new token. Reapply your changes as needed,
* then try the operation again using the new token. </p>
*/
inline const Aws::String& GetUpdateToken() const{ return m_updateToken; }
/**
* <p>An optional token that you can use for optimistic locking. Network Firewall
* returns a token to your requests that access the firewall. The token marks the
* state of the firewall resource at the time of the request. </p> <p>To make an
* unconditional change to the firewall, omit the token in your update request.
* Without the token, Network Firewall performs your updates regardless of whether
* the firewall has changed since you last retrieved it.</p> <p>To make a
* conditional change to the firewall, provide the token in your update request.
* Network Firewall uses the token to ensure that the firewall hasn't changed since
* you last retrieved it. If it has changed, the operation fails with an
* <code>InvalidTokenException</code>. If this happens, retrieve the firewall again
* to get a current copy of it with a new token. Reapply your changes as needed,
* then try the operation again using the new token. </p>
*/
inline bool UpdateTokenHasBeenSet() const { return m_updateTokenHasBeenSet; }
/**
* <p>An optional token that you can use for optimistic locking. Network Firewall
* returns a token to your requests that access the firewall. The token marks the
* state of the firewall resource at the time of the request. </p> <p>To make an
* unconditional change to the firewall, omit the token in your update request.
* Without the token, Network Firewall performs your updates regardless of whether
* the firewall has changed since you last retrieved it.</p> <p>To make a
* conditional change to the firewall, provide the token in your update request.
* Network Firewall uses the token to ensure that the firewall hasn't changed since
* you last retrieved it. If it has changed, the operation fails with an
* <code>InvalidTokenException</code>. If this happens, retrieve the firewall again
* to get a current copy of it with a new token. Reapply your changes as needed,
* then try the operation again using the new token. </p>
*/
inline void SetUpdateToken(const Aws::String& value) { m_updateTokenHasBeenSet = true; m_updateToken = value; }
/**
* <p>An optional token that you can use for optimistic locking. Network Firewall
* returns a token to your requests that access the firewall. The token marks the
* state of the firewall resource at the time of the request. </p> <p>To make an
* unconditional change to the firewall, omit the token in your update request.
* Without the token, Network Firewall performs your updates regardless of whether
* the firewall has changed since you last retrieved it.</p> <p>To make a
* conditional change to the firewall, provide the token in your update request.
* Network Firewall uses the token to ensure that the firewall hasn't changed since
* you last retrieved it. If it has changed, the operation fails with an
* <code>InvalidTokenException</code>. If this happens, retrieve the firewall again
* to get a current copy of it with a new token. Reapply your changes as needed,
* then try the operation again using the new token. </p>
*/
inline void SetUpdateToken(Aws::String&& value) { m_updateTokenHasBeenSet = true; m_updateToken = std::move(value); }
/**
* <p>An optional token that you can use for optimistic locking. Network Firewall
* returns a token to your requests that access the firewall. The token marks the
* state of the firewall resource at the time of the request. </p> <p>To make an
* unconditional change to the firewall, omit the token in your update request.
* Without the token, Network Firewall performs your updates regardless of whether
* the firewall has changed since you last retrieved it.</p> <p>To make a
* conditional change to the firewall, provide the token in your update request.
* Network Firewall uses the token to ensure that the firewall hasn't changed since
* you last retrieved it. If it has changed, the operation fails with an
* <code>InvalidTokenException</code>. If this happens, retrieve the firewall again
* to get a current copy of it with a new token. Reapply your changes as needed,
* then try the operation again using the new token. </p>
*/
inline void SetUpdateToken(const char* value) { m_updateTokenHasBeenSet = true; m_updateToken.assign(value); }
/**
* <p>An optional token that you can use for optimistic locking. Network Firewall
* returns a token to your requests that access the firewall. The token marks the
* state of the firewall resource at the time of the request. </p> <p>To make an
* unconditional change to the firewall, omit the token in your update request.
* Without the token, Network Firewall performs your updates regardless of whether
* the firewall has changed since you last retrieved it.</p> <p>To make a
* conditional change to the firewall, provide the token in your update request.
* Network Firewall uses the token to ensure that the firewall hasn't changed since
* you last retrieved it. If it has changed, the operation fails with an
* <code>InvalidTokenException</code>. If this happens, retrieve the firewall again
* to get a current copy of it with a new token. Reapply your changes as needed,
* then try the operation again using the new token. </p>
*/
inline DisassociateSubnetsRequest& WithUpdateToken(const Aws::String& value) { SetUpdateToken(value); return *this;}
/**
* <p>An optional token that you can use for optimistic locking. Network Firewall
* returns a token to your requests that access the firewall. The token marks the
* state of the firewall resource at the time of the request. </p> <p>To make an
* unconditional change to the firewall, omit the token in your update request.
* Without the token, Network Firewall performs your updates regardless of whether
* the firewall has changed since you last retrieved it.</p> <p>To make a
* conditional change to the firewall, provide the token in your update request.
* Network Firewall uses the token to ensure that the firewall hasn't changed since
* you last retrieved it. If it has changed, the operation fails with an
* <code>InvalidTokenException</code>. If this happens, retrieve the firewall again
* to get a current copy of it with a new token. Reapply your changes as needed,
* then try the operation again using the new token. </p>
*/
inline DisassociateSubnetsRequest& WithUpdateToken(Aws::String&& value) { SetUpdateToken(std::move(value)); return *this;}
/**
* <p>An optional token that you can use for optimistic locking. Network Firewall
* returns a token to your requests that access the firewall. The token marks the
* state of the firewall resource at the time of the request. </p> <p>To make an
* unconditional change to the firewall, omit the token in your update request.
* Without the token, Network Firewall performs your updates regardless of whether
* the firewall has changed since you last retrieved it.</p> <p>To make a
* conditional change to the firewall, provide the token in your update request.
* Network Firewall uses the token to ensure that the firewall hasn't changed since
* you last retrieved it. If it has changed, the operation fails with an
* <code>InvalidTokenException</code>. If this happens, retrieve the firewall again
* to get a current copy of it with a new token. Reapply your changes as needed,
* then try the operation again using the new token. </p>
*/
inline DisassociateSubnetsRequest& WithUpdateToken(const char* value) { SetUpdateToken(value); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of the firewall.</p> <p>You must specify the
* ARN or the name, and you can specify both. </p>
*/
inline const Aws::String& GetFirewallArn() const{ return m_firewallArn; }
/**
* <p>The Amazon Resource Name (ARN) of the firewall.</p> <p>You must specify the
* ARN or the name, and you can specify both. </p>
*/
inline bool FirewallArnHasBeenSet() const { return m_firewallArnHasBeenSet; }
/**
* <p>The Amazon Resource Name (ARN) of the firewall.</p> <p>You must specify the
* ARN or the name, and you can specify both. </p>
*/
inline void SetFirewallArn(const Aws::String& value) { m_firewallArnHasBeenSet = true; m_firewallArn = value; }
/**
* <p>The Amazon Resource Name (ARN) of the firewall.</p> <p>You must specify the
* ARN or the name, and you can specify both. </p>
*/
inline void SetFirewallArn(Aws::String&& value) { m_firewallArnHasBeenSet = true; m_firewallArn = std::move(value); }
/**
* <p>The Amazon Resource Name (ARN) of the firewall.</p> <p>You must specify the
* ARN or the name, and you can specify both. </p>
*/
inline void SetFirewallArn(const char* value) { m_firewallArnHasBeenSet = true; m_firewallArn.assign(value); }
/**
* <p>The Amazon Resource Name (ARN) of the firewall.</p> <p>You must specify the
* ARN or the name, and you can specify both. </p>
*/
inline DisassociateSubnetsRequest& WithFirewallArn(const Aws::String& value) { SetFirewallArn(value); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of the firewall.</p> <p>You must specify the
* ARN or the name, and you can specify both. </p>
*/
inline DisassociateSubnetsRequest& WithFirewallArn(Aws::String&& value) { SetFirewallArn(std::move(value)); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of the firewall.</p> <p>You must specify the
* ARN or the name, and you can specify both. </p>
*/
inline DisassociateSubnetsRequest& WithFirewallArn(const char* value) { SetFirewallArn(value); return *this;}
/**
* <p>The descriptive name of the firewall. You can't change the name of a firewall
* after you create it.</p> <p>You must specify the ARN or the name, and you can
* specify both. </p>
*/
inline const Aws::String& GetFirewallName() const{ return m_firewallName; }
/**
* <p>The descriptive name of the firewall. You can't change the name of a firewall
* after you create it.</p> <p>You must specify the ARN or the name, and you can
* specify both. </p>
*/
inline bool FirewallNameHasBeenSet() const { return m_firewallNameHasBeenSet; }
/**
* <p>The descriptive name of the firewall. You can't change the name of a firewall
* after you create it.</p> <p>You must specify the ARN or the name, and you can
* specify both. </p>
*/
inline void SetFirewallName(const Aws::String& value) { m_firewallNameHasBeenSet = true; m_firewallName = value; }
/**
* <p>The descriptive name of the firewall. You can't change the name of a firewall
* after you create it.</p> <p>You must specify the ARN or the name, and you can
* specify both. </p>
*/
inline void SetFirewallName(Aws::String&& value) { m_firewallNameHasBeenSet = true; m_firewallName = std::move(value); }
/**
* <p>The descriptive name of the firewall. You can't change the name of a firewall
* after you create it.</p> <p>You must specify the ARN or the name, and you can
* specify both. </p>
*/
inline void SetFirewallName(const char* value) { m_firewallNameHasBeenSet = true; m_firewallName.assign(value); }
/**
* <p>The descriptive name of the firewall. You can't change the name of a firewall
* after you create it.</p> <p>You must specify the ARN or the name, and you can
* specify both. </p>
*/
inline DisassociateSubnetsRequest& WithFirewallName(const Aws::String& value) { SetFirewallName(value); return *this;}
/**
* <p>The descriptive name of the firewall. You can't change the name of a firewall
* after you create it.</p> <p>You must specify the ARN or the name, and you can
* specify both. </p>
*/
inline DisassociateSubnetsRequest& WithFirewallName(Aws::String&& value) { SetFirewallName(std::move(value)); return *this;}
/**
* <p>The descriptive name of the firewall. You can't change the name of a firewall
* after you create it.</p> <p>You must specify the ARN or the name, and you can
* specify both. </p>
*/
inline DisassociateSubnetsRequest& WithFirewallName(const char* value) { SetFirewallName(value); return *this;}
/**
* <p>The unique identifiers for the subnets that you want to disassociate. </p>
*/
inline const Aws::Vector<Aws::String>& GetSubnetIds() const{ return m_subnetIds; }
/**
* <p>The unique identifiers for the subnets that you want to disassociate. </p>
*/
inline bool SubnetIdsHasBeenSet() const { return m_subnetIdsHasBeenSet; }
/**
* <p>The unique identifiers for the subnets that you want to disassociate. </p>
*/
inline void SetSubnetIds(const Aws::Vector<Aws::String>& value) { m_subnetIdsHasBeenSet = true; m_subnetIds = value; }
/**
* <p>The unique identifiers for the subnets that you want to disassociate. </p>
*/
inline void SetSubnetIds(Aws::Vector<Aws::String>&& value) { m_subnetIdsHasBeenSet = true; m_subnetIds = std::move(value); }
/**
* <p>The unique identifiers for the subnets that you want to disassociate. </p>
*/
inline DisassociateSubnetsRequest& WithSubnetIds(const Aws::Vector<Aws::String>& value) { SetSubnetIds(value); return *this;}
/**
* <p>The unique identifiers for the subnets that you want to disassociate. </p>
*/
inline DisassociateSubnetsRequest& WithSubnetIds(Aws::Vector<Aws::String>&& value) { SetSubnetIds(std::move(value)); return *this;}
/**
* <p>The unique identifiers for the subnets that you want to disassociate. </p>
*/
inline DisassociateSubnetsRequest& AddSubnetIds(const Aws::String& value) { m_subnetIdsHasBeenSet = true; m_subnetIds.push_back(value); return *this; }
/**
* <p>The unique identifiers for the subnets that you want to disassociate. </p>
*/
inline DisassociateSubnetsRequest& AddSubnetIds(Aws::String&& value) { m_subnetIdsHasBeenSet = true; m_subnetIds.push_back(std::move(value)); return *this; }
/**
* <p>The unique identifiers for the subnets that you want to disassociate. </p>
*/
inline DisassociateSubnetsRequest& AddSubnetIds(const char* value) { m_subnetIdsHasBeenSet = true; m_subnetIds.push_back(value); return *this; }
private:
Aws::String m_updateToken;
bool m_updateTokenHasBeenSet;
Aws::String m_firewallArn;
bool m_firewallArnHasBeenSet;
Aws::String m_firewallName;
bool m_firewallNameHasBeenSet;
Aws::Vector<Aws::String> m_subnetIds;
bool m_subnetIdsHasBeenSet;
};
} // namespace Model
} // namespace NetworkFirewall
} // namespace Aws
| [
"[email protected]"
] | |
2f70ca5a05e7a4a5bd2649fb1d5e608052825fe2 | 734c74789108492d64af40594e641ca320f0d4ff | /DummyChoosers.cpp | 3ef45610430665ec73708f4737e0a86f3b2506aa | [] | no_license | Vladimir-Trushin/BullPgia | cf871bb94266cf6e05589bb6622c6bb30d1e3cc1 | 91408215562fc9fc246ab16af0d0c024838ed149 | refs/heads/master | 2023-06-30T17:12:01.538550 | 2021-08-04T16:15:16 | 2021-08-04T16:15:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 216 | cpp | #include "DummyChoosers.hpp"
#include <stdlib.h>
std::string RandomChooser::choose(uint length)
{
std::string r = "";
for (uint i = 0; i < length; ++i)
{
char c = '0' + (rand() % 10);
r += c;
}
return r;
}
| [
"[email protected]"
] | |
eac525cadfddfb2544e8247122d243d2139ac4bd | 7dee761622fa4dd8993d400d323d898280c8d4b5 | /0404 Sum of Left Leaves/Sum of Left Leaves.cpp | 3c43498ae9b273c6d4703a9a71c66b50fcc1b1c4 | [] | no_license | garlinplus/leetcode | 2f8395dac07620329485bf68de6229482767b8c3 | af040db766b6a32f244a56d1e2510f8c7a1a6516 | refs/heads/master | 2020-04-09T11:42:45.238403 | 2020-03-20T12:11:08 | 2020-03-20T12:11:08 | 244,287,935 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 473 | cpp | class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(!root) return 0;
return dfs(root,0);
}
int dfs(TreeNode* root,int flag){
if(!root){
return 0;
}
int sum = 0;
if(flag){
if(!root->left && !root->right){
sum = root->val;
}
}
return sum + dfs(root->left,1) + dfs(root->right,0);
}
}; | [
"[email protected]"
] | |
2f37361643c519dbe464dcf1d6c305ac50db6cfe | 4db58e7e02f66c155edacc63e1fda60cb4a5eea6 | /frameworks/runtime-src/Classes/AppDelegate.cpp | 4a465aedc1c9c68a67bad56ad444d2fa49e8060f | [] | no_license | hongjie104/Libra-lua | f9d5fe234bfaf0fe3ef4d372ce17dc17eac81177 | 7813ffcabc142adfb82affb8ac752215c46b16d5 | refs/heads/master | 2021-05-29T14:51:16.966095 | 2015-09-24T12:53:03 | 2015-09-24T12:53:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,891 | cpp | #include "AppDelegate.h"
#include "CCLuaEngine.h"
#include "SimpleAudioEngine.h"
#include "cocos2d.h"
#if (CC_TARGET_PLATFORM != CC_PLATFORM_WP8)
#include "CodeIDESupport.h"
#include "Runtime.h"
#endif
#include "ConfigParser.h"
#include "lua_module_register.h"
// extra lua module
#include "cocos2dx_extra.h"
#include "lua_extensions/lua_extensions_more.h"
#include "luabinding/lua_cocos2dx_extension_filter_auto.hpp"
#include "luabinding/lua_cocos2dx_extension_nanovg_auto.hpp"
#include "luabinding/lua_cocos2dx_extension_nanovg_manual.hpp"
#include "luabinding/cocos2dx_extra_luabinding.h"
#include "luabinding/HelperFunc_luabinding.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
#include "luabinding/cocos2dx_extra_ios_iap_luabinding.h"
#endif
#if ANYSDK_DEFINE > 0
#include "anysdkbindings.h"
#include "anysdk_manual_bindings.h"
#endif
#include "pbc-lua.h"
using namespace CocosDenshion;
USING_NS_CC;
using namespace std;
static void quick_module_register(lua_State *L)
{
luaopen_lua_extensions_more(L);
lua_getglobal(L, "_G");
if (lua_istable(L, -1))//stack:...,_G,
{
register_all_quick_manual(L);
// extra
luaopen_cocos2dx_extra_luabinding(L);
register_all_cocos2dx_extension_filter(L);
register_all_cocos2dx_extension_nanovg(L);
register_all_cocos2dx_extension_nanovg_manual(L);
luaopen_HelperFunc_luabinding(L);
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
luaopen_cocos2dx_extra_ios_iap_luabinding(L);
#endif
luaopen_protobuf_c(L);
}
lua_pop(L, 1);
}
//
AppDelegate::AppDelegate()
:_launchMode(1)
{
}
AppDelegate::~AppDelegate()
{
SimpleAudioEngine::end();
#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
endRuntime();
#elif (COCOS2D_DEBUG > 0 && CC_CODE_IDE_DEBUG_SUPPORT > 0)
// NOTE:Please don't remove this call if you want to debug with Cocos Code IDE
if (_launchMode)
{
endRuntime();
}
#endif
ConfigParser::purge();
}
//if you want a different context,just modify the value of glContextAttrs
//it will takes effect on all platforms
void AppDelegate::initGLContextAttrs()
{
//set OpenGL context attributions,now can only set six attributions:
//red,green,blue,alpha,depth,stencil
GLContextAttrs glContextAttrs = { 8, 8, 8, 8, 24, 8 };
GLView::setGLContextAttrs(glContextAttrs);
}
bool AppDelegate::applicationDidFinishLaunching()
{
#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
initRuntime();
#elif (COCOS2D_DEBUG > 0 && CC_CODE_IDE_DEBUG_SUPPORT > 0)
// NOTE:Please don't remove this call if you want to debug with Cocos Code IDE
if (_launchMode)
{
initRuntime();
}
#endif
// initialize director
auto director = Director::getInstance();
auto glview = director->getOpenGLView();
if(!glview) {
Size viewSize = ConfigParser::getInstance()->getInitViewSize();
string title = ConfigParser::getInstance()->getInitViewName();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
extern void createSimulator(const char* viewName, float width, float height, bool isLandscape = true, float frameZoomFactor = 1.0f);
bool isLanscape = ConfigParser::getInstance()->isLanscape();
createSimulator(title.c_str(),viewSize.width,viewSize.height, isLanscape);
#else
glview = cocos2d::GLViewImpl::createWithRect(title.c_str(), Rect(0, 0, viewSize.width, viewSize.height));
director->setOpenGLView(glview);
#endif
director->startAnimation();
}
auto engine = LuaEngine::getInstance();
ScriptEngineManager::getInstance()->setScriptEngine(engine);
lua_State* L = engine->getLuaStack()->getLuaState();
lua_module_register(L);
// use Quick-Cocos2d-X
quick_module_register(L);
LuaStack* stack = engine->getLuaStack();
#if ANYSDK_DEFINE > 0
lua_getglobal(stack->getLuaState(), "_G");
tolua_anysdk_open(stack->getLuaState());
tolua_anysdk_manual_open(stack->getLuaState());
lua_pop(stack->getLuaState(), 1);
#endif
// stack->setXXTEAKeyAndSign("2dxLua", strlen("2dxLua"), "XXTEA", strlen("XXTEA"));
//register custom function
//LuaStack* stack = engine->getLuaStack();
//register_custom_function(stack->getLuaState());
#if (COCOS2D_DEBUG > 0 && CC_CODE_IDE_DEBUG_SUPPORT > 0)
// NOTE:Please don't remove this call if you want to debug with Cocos Code IDE
if (_launchMode)
{
startRuntime();
}
else
{
engine->executeScriptFile(ConfigParser::getInstance()->getEntryFile().c_str());
}
/*
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
// load game
stack->setXXTEAKeyAndSign("apowo2014", 9, "XXTEA", 5);
stack->loadChunksFromZIP("res/game.zip");
stack->executeString("require 'main'");
*/
#else
engine->executeScriptFile(ConfigParser::getInstance()->getEntryFile().c_str());
#endif
return true;
}
// This function will be called when the app is inactive. When comes a phone call,it's be invoked too
void AppDelegate::applicationDidEnterBackground()
{
Director::getInstance()->stopAnimation();
Director::getInstance()->pause();
SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
SimpleAudioEngine::getInstance()->pauseAllEffects();
Director::getInstance()->getEventDispatcher()->dispatchCustomEvent("APP_ENTER_BACKGROUND_EVENT");
}
// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground()
{
Director::getInstance()->resume();
Director::getInstance()->startAnimation();
SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
SimpleAudioEngine::getInstance()->resumeAllEffects();
Director::getInstance()->getEventDispatcher()->dispatchCustomEvent("APP_ENTER_FOREGROUND_EVENT");
}
void AppDelegate::setLaunchMode(int mode)
{
_launchMode = mode;
}
| [
"[email protected]"
] | |
117fa9dd5d3f00a78e1001566dfaa65b2f695e38 | b615e948c1417665b008f145ac507cbe41caca46 | /src/libtsduck/base/tsUserInterrupt.h | 5510ae8e6df646712c9862f2b936b973ecc127a7 | [
"BSD-2-Clause"
] | permissive | spnngl/tsduck | 41f260c009a3bed9c2babb996ce98473bb598c93 | ca411244bf7dfe741466762baf96e16a4a5867cc | refs/heads/master | 2021-06-27T16:03:42.093986 | 2021-03-21T11:57:20 | 2021-03-21T11:57:20 | 221,499,020 | 0 | 0 | BSD-2-Clause | 2019-11-13T16:04:42 | 2019-11-13T16:04:41 | null | UTF-8 | C++ | false | false | 4,644 | h | //----------------------------------------------------------------------------
//
// TSDuck - The MPEG Transport Stream Toolkit
// Copyright (c) 2005-2021, Thierry Lelegard
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
//----------------------------------------------------------------------------
//!
//! @file
//! User interrupt handling (Ctrl+C).
//!
//----------------------------------------------------------------------------
#pragma once
#include "tsInterruptHandler.h"
#include "tsThread.h"
namespace ts {
//!
//! An instance of this class handles the Ctrl+C user interrupt.
//! @ingroup system
//!
//! There must be at most one active instance at a time.
//!
//! Can be used in two ways:
//! - Interrupt notification through one InterruptHandler
//! - Interrupt polling through isInterrupted()/resetInterrupted().
//!
class TSDUCKDLL UserInterrupt
#if defined(TS_UNIX)
: private Thread
#endif
{
TS_NOBUILD_NOCOPY(UserInterrupt);
public:
//!
//! Constructor.
//! @param [in] handler Address of interrupt handler. Can be null.
//! @param [in] one_shot If true, the interrupt will be handled only once,
//! the second time the process will be terminated.
//! @param [in] auto_activate If true, the interrupt handling is immediately activated.
//!
UserInterrupt(InterruptHandler* handler, bool one_shot, bool auto_activate);
//!
//! Destructor, auto-deactivate.
//!
#if defined(TS_UNIX)
virtual ~UserInterrupt() override;
#else
~UserInterrupt();
#endif
//!
//! Check if this interrupt handler is active.
//! @return True if this interrupt handler is active.
//!
bool isActive() const {return _active;}
//!
//! Check if this interrupt was triggered.
//! @return True if this interrupt handler was triggered.
//!
bool isInterrupted() const {return _interrupted;}
//!
//! Reset interrupt state.
//! Now, isInterrupted() will return false, until the next time the interrupt is triggered.
//!
void resetInterrupted() {_interrupted = false;}
//!
//! Activate this interrupt handler.
//! Only one handler can be active at a time. This method does nothing
//! if this handler or another handler is already active.
//!
void activate();
//!
//! Deactivate this interrupt handler.
//!
void deactivate();
private:
#if defined(TS_WINDOWS)
static ::BOOL WINAPI sysHandler(__in ::DWORD dwCtrlType);
#elif defined(TS_UNIX)
static void sysHandler(int sig);
virtual void main() override; // ts::Thread implementation
volatile ::sig_atomic_t _terminate;
volatile ::sig_atomic_t _got_sigint;
#if defined(TS_MAC)
std::string _sem_name;
::sem_t* _sem_address;
#else
::sem_t _sem_instance;
#endif
#endif
InterruptHandler* _handler;
bool _one_shot;
bool _active;
volatile bool _interrupted;
// There is only one active instance at a time
static UserInterrupt* volatile _active_instance;
};
}
| [
"[email protected]"
] | |
6d712c6a81a5bc76f8f540d6ffc3d6dad2a08b90 | 990d1d75f9eaa79298adc9f269b4f6a56c1044c6 | /Not Current/homework2_Nawavi/particles/pthreads.cpp | f86f30173377662fec6e2f58c1cfafc0250e19b5 | [] | no_license | royanguiano/CIS-625-homework | a9bb170c0a20a17eff6e116f6d0949ba49ac4b82 | ff0decde3d11d04becac469fa089733333f12da1 | refs/heads/master | 2020-03-11T12:38:59.727704 | 2016-04-25T05:38:13 | 2016-04-25T05:38:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,547 | cpp | #include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <math.h>
#include <pthread.h>
#include "common.h"
#include <sched.h>
static __inline__ unsigned long long rdtsc(void)
{
unsigned long long int x;
__asm__ volatile (".byte 0x0f, 0x31" : "=A" (x));
return x;
}
int P = 0;
int bar = 0; // Counter of threads, faced barrier.
volatile int passed = 0; // Number of barriers, passed by all threads.
void barrier_wait()
{
int passed_old = passed; // Should be evaluated before incrementing *bar*!
if(__sync_fetch_and_add(&bar,1) == (P - 1))
{
// The last thread, faced barrier.
bar = 0;
// *bar* should be reseted strictly before updating of barriers counter.
__sync_synchronize();
passed++; // Mark barrier as passed.
}
else
{
// Not the last thread. Wait others.
unsigned long long cycles = rdtsc(); //1
//10^9 per second or 1000000000
//1000000 per millisecond
//
while(passed == passed_old) {
//unsigned long long cycles2 = rdtsc() - cycles; //2
//if (cycles >= 1000000) {
sched_yield();
//printf("Time is %d\n", (unsigned)cycles);
//}
}; /*sched_yield();*/
// Need to synchronize cache with other threads, passed barrier.
__sync_synchronize();
//cycles = rdtsc() - cycles; //2
//printf("Time is %d\n", (unsigned)cycles);
}
}
#if !defined density
#define density 0.0005
#endif
#if !defined mass
#define mass 0.01
#endif
#if !defined cutoff
#define cutoff 0.01
#endif
#if !defined min_r
#define min_r (cutoff/100)
#endif
#if !defined dt
#define dt 0.0005
#endif
//
// particle data structure
//
struct particleNode
{
particle_t *particle;
particle_t particleCopy;
int gridX, gridY;
int index;
struct particleNode *next, *prev;
//List nearbyParticles;
};
typedef struct particleNode ParticleNode;
//My updated force function that updates both particles at the same time
void static inline apply_forceBoth( particle_t &particle, particle_t &neighbor , double *dmin, double *davg, int *navg)
{
double dx = neighbor.x - particle.x;
double dy = neighbor.y - particle.y;
double r2 = dx * dx + dy * dy;
if( r2 > cutoff*cutoff )
return;
if (r2 != 0)
{
if (r2/(cutoff*cutoff) < *dmin * (*dmin))
*dmin = sqrt(r2)/cutoff;
(*davg) += sqrt(r2)/cutoff;
(*navg) ++;
}
r2 = fmax( r2, min_r*min_r );
double r = sqrt( r2 );
//
// very simple short-range repulsive force
//
double coef = ( 1 - cutoff / r ) / r2 / mass;
double coefdx = coef * dx;
double coefdy = coef * dy;
particle.ax += coefdx;
particle.ay += coefdy;
neighbor.ax -= coefdx;
neighbor.ay -= coefdy;
}
//This is to debug our grid to make sure particle nodes are where they should be
void printGrid(ParticleNode ***grid, int gridSize) {
printf("***PRINT GRID %dx%d***\n", gridSize, gridSize);
ParticleNode* particleNode;
for (int x = 0; x < gridSize; x++) {
printf("[");
for (int y = 0; y < gridSize; y++) {
particleNode = grid[x][y];
printf("%d, %d=", x, y);
bool correct = true;
int nodeCount = 0;
while (particleNode != NULL) {
nodeCount++;
if (!(particleNode->gridX == x && particleNode->gridY == y)) {
printf("(invalid location: %d, %d)\n", particleNode->gridX, particleNode->gridY);
correct = false;
}
particleNode = particleNode->next;
}
if (correct) {
printf("correct(%d nodes), ", nodeCount);
} else {
particleNode = grid[x][y];
while (particleNode != NULL) {
printf("|Node Details: %d <-- %d, %d --> %d|\n", particleNode->prev, particleNode->gridX, particleNode->gridY, particleNode->next);
particleNode = particleNode->next;
}
printf("incorrect(%d nodes), ", nodeCount);
}
}
printf("]\n");
}
}
inline void addParticleNodeToGrid(int particleIndex, int x, int y, ParticleNode* addNode, ParticleNode ***grid) {
//Get the first node at the current grid spot
ParticleNode* node = grid[x][y];
if (node == NULL) { //Grid is empty so just set the node in the grid
addNode->gridX = x;
addNode->gridY = y;
grid[x][y] = addNode;
} else { //Add the particle node to the grid but place it ordered in the linked list based on index to make memory lookup slightly faster
addNode->gridX = x;
addNode->gridY = y;
ParticleNode* firstNode = node;
ParticleNode* pastNode = NULL;
while (node->index < particleIndex) {
pastNode = node;
node = node->next;
if (node == NULL) break;
}
//Node should equal either null or a node we need to place our particle node in front of
if (node == firstNode) {
//Just push back the first node
addNode->next = node;
node->prev = addNode;
grid[x][y] = addNode;
} else if (node != NULL) {
//Put the particle node between two nodes
ParticleNode* leftNode = node->prev;
ParticleNode* rightNode = node;
addNode->prev = leftNode;
leftNode->next = addNode;
addNode->next = rightNode;
rightNode->prev = addNode;
} else {
//Put the particle node at the end
ParticleNode* leftNode = pastNode;
addNode->prev = leftNode;
leftNode->next = addNode;
}
}
}
inline void removeParticleNodeFromGrid(int x, int y, ParticleNode* node, ParticleNode ***grid) {
//Get the neighbor nodes in the same grid as this particle node
ParticleNode* nextNode = node->next;
ParticleNode* prevNode = node->prev;
//We need to remove the Node from it's neighbors and from the grid
if (nextNode != NULL && prevNode != NULL) { //Particle is in the middle of a linked list
//Splice the particle node out by setting our neighbors to be next to each other
nextNode->prev = prevNode;
prevNode->next = nextNode;
} else if (nextNode != NULL && prevNode == NULL) { //Particle is first in the linked list and is connected to another node
//Set the second node to be the first on the grid and remove the second node's reference to this particle node
nextNode->prev = NULL;
grid[x][y] = nextNode;
} else if (nextNode == NULL && prevNode != NULL) { //Particle is the last in the linked list
//Remove the neighbor's connection to this particle node
prevNode->next = NULL;
} else if (nextNode == NULL && prevNode == NULL) { //Grid is empty except for this particle node
//Set the grid at this location to NULL cause the particle node is being removed and it is the only node there
grid[x][y] = NULL;
}
//Particle node was removed so remove references to neighbors
node->next = NULL;
node->prev = NULL;
}
struct searchArea {
int startX, startY, endX, endY;
};
typedef struct searchArea SearchArea;
inline SearchArea getSearchArea(int x, int y, int searchArea, int gridSize) {
SearchArea search;
search.startX = x - searchArea;
if (search.startX < 0) search.startX = 0;
search.startY = y - searchArea;
if (search.startY < 0) search.startY = 0;
search.endX = x + searchArea;
if (search.endX >= gridSize) search.endX = gridSize-1;
search.endY = y + searchArea;
if (search.endY >= gridSize) search.endY = gridSize-1;
return search;
}
ParticleNode ***grid;
ParticleNode ***gridCopy;
double blockSize;
int searchArea;
double fieldSize;
int gridSize;
ParticleNode **particleNodes;
ParticleNode **particleNodesCopy;
volatile bool* threadBools;
//
// global variables
//
int n, n_threads,no_output=0;
particle_t *particles;
particle_t *particlesCopy;
FILE *fsave,*fsum;
pthread_barrier_t barrier;
bool *myThreadBooleanLock, *myThreadBooleanLocks2;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_spinlock_t** gridLocks;
pthread_spinlock_t* spinLockArray1;
double gabsmin=1.0,gabsavg=0.0;
//
// check that pthreads routine call was successful
//
#define P( condition ) {if( (condition) != 0 ) { printf( "\n FAILURE in %s, line %d\n", __FILE__, __LINE__ );exit( 1 );}}
//
// This is where the action happens
//
void *thread_routine( void *pthread_id )
{
int navg,nabsavg=0;
double dmin,absmin=1.0,davg,absavg=0.0;
int thread_id = *(int*)pthread_id;
int particles_per_thread = (n + n_threads - 1) / n_threads;
int first = min( thread_id * particles_per_thread, n );
int last = min( (thread_id+1) * particles_per_thread, n );
//
// simulate a number of time steps
//
for( int step = 0; step < NSTEPS; step++ )
{
//for (int i = 0; i < numthreads; i++) {
threadBools[thread_id] = false;
pthread_barrier_wait( &barrier );
//}
dmin = 1.0;
navg = 0;
davg = 0.0;
//Loop through all particles
for( int i = first; i < last; i++ )
{
//Get the particle Node and particle to simulate
ParticleNode* particleNodeI = particleNodes[i];
particle_t *particleI = particleNodeI->particle;
int locationX = particleNodeI->gridX;
int locationY = particleNodeI->gridY;
SearchArea search = getSearchArea(locationX, locationY, searchArea, gridSize);
//for each particle in nearbyParticles
for (int x = search.startX; x <= search.endX; x++) {
for (int y = search.startY; y <= search.endY; y++) {
ParticleNode* startingNode = grid[x][y];
while (startingNode != NULL) { //Go down the entire linked list on the grid location and calculate particle forces
//if (startingNode->index > particleNodeI->index) {
apply_force( *particleI, *(startingNode->particle),&dmin,&davg,&navg);
//}
//Set the node to the next node so we continue down the chain of nodes
startingNode = startingNode->next;
}
}
}
//Move a copy of the particle
ParticleNode* particleNodeICopy = particleNodesCopy[i];
particle_t *particleICopy = particleNodeICopy->particle;
particleICopy->ax = particleI->ax;
particleICopy->ay = particleI->ay;
move( *particleICopy );
particleICopy->ax = particleICopy->ay = 0;
//Place the copy of the particle node into the right spot in the copy of the grid array
int oldLocationX = particleNodeICopy->gridX;
int oldLocationY = particleNodeICopy->gridY;
int newLocationX = floor(particleICopy->x / blockSize);
int newLocationY = floor(particleICopy->y / blockSize);
//Update the grid cause the particle moved
if (oldLocationX != newLocationX || oldLocationY != newLocationY) {
pthread_spin_lock(&(gridLocks[oldLocationX][oldLocationY]));
removeParticleNodeFromGrid(oldLocationX, oldLocationY, particleNodeICopy, gridCopy);
pthread_spin_unlock(&(gridLocks[oldLocationX][oldLocationY]));
pthread_spin_lock(&(gridLocks[newLocationX][newLocationY]));
addParticleNodeToGrid(i, newLocationX, newLocationY, particleNodeICopy, gridCopy);
pthread_spin_unlock(&(gridLocks[newLocationX][newLocationY]));
}
}
//Lets make a staggered thread descent into moving the particles
//if (thread_id != 0) {
// while (threadBools[thread_id - 1] == false) {
// sched_yield();
//asm ("");
// }
//}
pthread_barrier_wait( &barrier );
for( int i = first; i < last; i++ ) {
particles[i] = particlesCopy[i];
}
/*
for (int i = first; i < last; i++) {
//Get the particle Node and particle to simulate
ParticleNode* particleNodeI = particleNodes[i];
particle_t *particleI = particleNodeI->particle;
move( *particleI );
//Reset the particle's forces because we just moved the particle and we don't need the forces anymore
particleI->ax = particleI->ay = 0;
}*/
//threadBools[thread_id] = true;
//pthread_barrier_wait( &barrier );
/*
for (int i = first; i < last; i++) {
//Get the particle Node and particle to simulate
ParticleNode* particleNodeI = particleNodes[i];
particle_t *particleI = particleNodeI->particle;
move( *particleI );
//Reset the particle's forces because we just moved the particle and we don't need the forces anymore
particleI->ax = particleI->ay = 0;
//Create a grid search area for particle collision
int oldLocationX = particleNodeI->gridX;
int oldLocationY = particleNodeI->gridY;
//Find the old and new location in the grid of the particle
int newLocationX = floor(particleI->x / blockSize);
int newLocationY = floor(particleI->y / blockSize);
//Update the grid cause the particle moved
if (oldLocationX != newLocationX || oldLocationY != newLocationY) {
//Lock the two sections of grid we are modifying
pthread_spin_lock(&(gridLocks[oldLocationX][oldLocationY]));
//Get the neighbor nodes in the same grid as this particle node
ParticleNode* nextNode = particleNodeI->next;
ParticleNode* prevNode = particleNodeI->prev;
//We need to remove the Node from it's neighbors and from the grid
if (nextNode != NULL && prevNode != NULL) { //Particle is in the middle of a linked list
//Splice the particle node out by setting our neighbors to be next to each other
nextNode->prev = prevNode;
prevNode->next = nextNode;
} else if (nextNode != NULL && prevNode == NULL) { //Particle is first in the linked list and is connected to another node
//Set the second node to be the first on the grid and remove the second node's reference to this particle node
nextNode->prev = NULL;
grid[oldLocationX][oldLocationY] = nextNode;
} else if (nextNode == NULL && prevNode != NULL) { //Particle is the last in the linked list
//Remove the neighbor's connection to this particle node
prevNode->next = NULL;
} else if (nextNode == NULL && prevNode == NULL) { //Grid is empty except for this particle node
//Set the grid at this location to NULL cause the particle node is being removed and it is the only node there
grid[oldLocationX][oldLocationY] = NULL;
}
//Particle node was removed so remove references to neighbors
particleNodeI->next = NULL;
particleNodeI->prev = NULL;
pthread_spin_unlock(&(gridLocks[oldLocationX][oldLocationY]));
pthread_spin_lock(&(gridLocks[newLocationX][newLocationY]));
//Put the node back in the next grid
ParticleNode* node = grid[newLocationX][newLocationY];
if (node == NULL) { //Grid is empty so just set the node in the grid
particleNodeI->gridX = newLocationX;
particleNodeI->gridY = newLocationY;
grid[newLocationX][newLocationY] = particleNodeI;
} else { //Add the particle node to the grid but place it ordered in the linked list based on index to make memory lookup slightly faster
particleNodeI->gridX = newLocationX;
particleNodeI->gridY = newLocationY;
ParticleNode* firstNode = node;
ParticleNode* pastNode = NULL;
while (node->index < i) {
pastNode = node;
node = node->next;
if (node == NULL) break;
}
//Node should equal either null or a node we need to place our particle node in front of
if (node == firstNode) {
//Just push back the first node
particleNodeI->next = node;
node->prev = particleNodeI;
grid[newLocationX][newLocationY] = particleNodeI;
} else if (node != NULL) {
//Put the particle node between two nodes
ParticleNode* leftNode = node->prev;
ParticleNode* rightNode = node;
particleNodeI->prev = leftNode;
leftNode->next = particleNodeI;
particleNodeI->next = rightNode;
rightNode->prev = particleNodeI;
} else {
//Put the particle node at the end
ParticleNode* leftNode = pastNode;
particleNodeI->prev = leftNode;
leftNode->next = particleNodeI;
}
}
pthread_spin_unlock(&(gridLocks[newLocationX][newLocationY]));
}
}
*/
pthread_barrier_wait( &barrier );
if (thread_id == 0) {
//Swap
ParticleNode **particleNodesTemp = particleNodesCopy;
particleNodesCopy = particleNodes;
particleNodes = particleNodesTemp;
//Swap
particle_t *particlesTemp = particlesCopy;
particlesCopy = particles;
particles = particlesTemp;
//Swap
ParticleNode ***gridTemp = gridCopy;
gridCopy = grid;
grid = gridTemp;
}
pthread_barrier_wait( &barrier );
//barrier_wait();
if( no_output == 0 )
{
//
// Computing statistical data
//
if (navg) {
absavg += davg/navg;
nabsavg++;
}
if (dmin < absmin) absmin = dmin;
}
//
// save if necessary
//
if (no_output == 0)
if( thread_id == 0 && fsave && (step%SAVEFREQ) == 0 )
save( fsave, n, particles );
}
if (no_output == 0 )
{
absavg /= nabsavg;
//printf("Thread %d has absmin = %lf and absavg = %lf\n",thread_id,absmin,absavg);
pthread_mutex_lock(&mutex);
gabsavg += absavg;
if (absmin < gabsmin) gabsmin = absmin;
pthread_mutex_unlock(&mutex);
}
return NULL;
}
//
// benchmarking program
//
int main( int argc, char **argv )
{
//
// process command line
//
if( find_option( argc, argv, "-h" ) >= 0 )
{
printf( "Options:\n" );
printf( "-h to see this help\n" );
printf( "-n <int> to set the number of particles\n" );
printf( "-p <int> to set the number of threads\n" );
printf( "-o <filename> to specify the output file name\n" );
printf( "-s <filename> to specify a summary file name\n" );
printf( "-no turns off all correctness checks and particle output\n");
return 0;
}
n = read_int( argc, argv, "-n", 1000 );
n_threads = read_int( argc, argv, "-p", 2 );
char *savename = read_string( argc, argv, "-o", NULL );
char *sumname = read_string( argc, argv, "-s", NULL );
fsave = savename ? fopen( savename, "w" ) : NULL;
fsum = sumname ? fopen ( sumname, "a" ) : NULL;
if( find_option( argc, argv, "-no" ) != -1 )
no_output = 1;
//
// allocate resources
//
particles = (particle_t*) malloc( n * sizeof(particle_t) );
particlesCopy = (particle_t*) malloc( n * sizeof(particle_t) );
set_size( n );
init_particles( n, particles );
for (int i = 0; i < n; i++) {
particlesCopy[i] = particles[i];
}
//Create the field grid
blockSize = cutoff; //Use to be cutoff
searchArea = 2;
fieldSize = sqrt(density * n);
gridSize = ceil(fieldSize / blockSize);
//Create particle grid
grid = (ParticleNode ***)malloc(gridSize * sizeof(ParticleNode **));
for (int i=0; i<gridSize; i++)
grid[i] = (ParticleNode **)malloc(gridSize * sizeof(ParticleNode*));
gridCopy = (ParticleNode ***)malloc(gridSize * sizeof(ParticleNode **));
for (int i=0; i<gridSize; i++)
gridCopy[i] = (ParticleNode **)malloc(gridSize * sizeof(ParticleNode*));
//Create grid locks
gridLocks = (pthread_spinlock_t **)malloc(gridSize * sizeof(pthread_spinlock_t *));
for (int i=0; i<gridSize; i++) {
gridLocks[i] = (pthread_spinlock_t *)malloc(gridSize * sizeof(pthread_spinlock_t));
for (int j = 0; j < gridSize; j++) {
pthread_spin_init(&gridLocks[i][j], PTHREAD_PROCESS_PRIVATE);
}
}
spinLockArray1 = (pthread_spinlock_t *)malloc(n_threads * sizeof(pthread_spinlock_t));
for (int j = 0; j < n_threads; j++) {
pthread_spin_init(&spinLockArray1[j], PTHREAD_PROCESS_PRIVATE);
}
//Create particle node array
particleNodes = (ParticleNode**) malloc( n * sizeof(ParticleNode*) );
particleNodesCopy = (ParticleNode**) malloc( n * sizeof(ParticleNode*) );
P = n_threads;
myThreadBooleanLock = (bool *) malloc( n_threads * sizeof(bool) );
for (int i = 0; i < n_threads; i++) {
myThreadBooleanLock[i] = false;
}
myThreadBooleanLocks2 = (bool *) malloc( n_threads * sizeof(bool) );
for (int i = 0; i < n_threads; i++) {
myThreadBooleanLocks2[i] = true;
}
//Clear the particle grid
for (int x = 0; x < gridSize; x++) {
for (int y = 0; y < gridSize; y++) {
grid[x][y] = NULL;
}
}
threadBools = (bool*) malloc(n_threads * sizeof(bool) );;
//Sort particles in linked lists in the grid
for (int i = 0; i < n; i++) {
particle_t *particle = &particles[i];
//Get location in grid
int locationX = floor(particle->x / blockSize);
int locationY = floor(particle->y / blockSize);
//Get node at that grid location
ParticleNode* node = grid[locationX][locationY];
//Create new node for particle we are adding
ParticleNode* newNode = (ParticleNode*) malloc(sizeof(ParticleNode));
newNode->particle = particle;
newNode->next = NULL;
newNode->prev = NULL;
newNode->index = i;
addParticleNodeToGrid(i, locationX, locationY, newNode, grid);
//Set the new particle node in the particle nodes array
particleNodes[i] = newNode;
}
///Sort copies
for (int i = 0; i < n; i++) {
particle_t *particle = &particlesCopy[i];
//Get location in grid
int locationX = floor(particle->x / blockSize);
int locationY = floor(particle->y / blockSize);
//Get node at that grid location
ParticleNode* node = gridCopy[locationX][locationY];
//Create new node for particle we are adding
ParticleNode* newNode = (ParticleNode*) malloc(sizeof(ParticleNode));
newNode->particle = particle;
newNode->next = NULL;
newNode->prev = NULL;
newNode->index = i;
addParticleNodeToGrid(i, locationX, locationY, newNode, gridCopy);
//Set the new particle node in the particle nodes array
particleNodesCopy[i] = newNode;
}
//Simulate
pthread_attr_t attr;
P( pthread_attr_init( &attr ) );
P( pthread_barrier_init( &barrier, NULL, n_threads ) );
int *thread_ids = (int *) malloc( n_threads * sizeof( int ) );
for( int i = 0; i < n_threads; i++ )
thread_ids[i] = i;
pthread_t *threads = (pthread_t *) malloc( n_threads * sizeof( pthread_t ) );
//
// do the parallel work
//
double simulation_time = read_timer( );
for( int i = 1; i < n_threads; i++ )
P( pthread_create( &threads[i], &attr, thread_routine, &thread_ids[i] ) );
thread_routine( &thread_ids[0] );
for( int i = 1; i < n_threads; i++ )
P( pthread_join( threads[i], NULL ) );
simulation_time = read_timer( ) - simulation_time;
printf( "n = %d, simulation time = %g seconds", n, simulation_time);
if( find_option( argc, argv, "-no" ) == -1 )
{
gabsavg /= (n_threads*1.0);
//
// -the minimum distance absmin between 2 particles during the run of the simulation
// -A Correct simulation will have particles stay at greater than 0.4 (of cutoff) with typical values between .7-.8
// -A simulation were particles don't interact correctly will be less than 0.4 (of cutoff) with typical values between .01-.05
//
// -The average distance absavg is ~.95 when most particles are interacting correctly and ~.66 when no particles are interacting
//
printf( ", absmin = %lf, absavg = %lf", gabsmin, gabsavg);
if (gabsmin < 0.4) printf ("\nThe minimum distance is below 0.4 meaning that some particle is not interacting ");
if (gabsavg < 0.8) printf ("\nThe average distance is below 0.8 meaning that most particles are not interacting ");
}
printf("\n");
//
// Printing summary data
//
if( fsum)
fprintf(fsum,"%d %d %g\n",n,n_threads,simulation_time);
//
// release resources
//
P( pthread_barrier_destroy( &barrier ) );
free(myThreadBooleanLock);
free(myThreadBooleanLocks2);
P( pthread_attr_destroy( &attr ) );
free( thread_ids );
free( threads );
for (int i=0; i<gridSize; i++) {
free(grid[i]);
}
free(grid);
for (int i=0; i<gridSize; i++) {
for (int j = 0; j < gridSize; j++) {
pthread_spin_destroy(&gridLocks[i][j]);
}
// free(gridLocks[i]);
}
for (int j = 0; j < n_threads; j++) {
pthread_spin_destroy(&spinLockArray1[j]);
}
free(gridLocks);
for (int i = 0; i < n; i++) {
free(particleNodes[i]);
}
free(particleNodes);
free( particles );
if( fsave )
fclose( fsave );
if( fsum )
fclose ( fsum );
return 0;
}
| [
"[email protected]"
] | |
1ccba416b5cf82cf52c66c435531ecffa614149f | 2485005ebb1b9ac79a3f9195b6bfeb7817ae7a9c | /include/braincloud/internal/win/Win32RelayTCPSocket.h | 57372b1a11d282ecccd8ccfa9df0097b29455165 | [
"LicenseRef-scancode-public-domain",
"Apache-2.0"
] | permissive | getbraincloud/braincloud-cpp | c2ca31e9971b1103178eedc55cd40ea98a03bbb1 | 03c2446cd512529a35fdf4d041da0ec84c785b4a | refs/heads/master | 2023-09-01T15:47:48.536831 | 2023-08-03T19:40:31 | 2023-08-03T19:40:31 | 51,466,360 | 4 | 19 | Apache-2.0 | 2023-09-14T20:39:40 | 2016-02-10T19:33:02 | C++ | UTF-8 | C++ | false | false | 1,234 | h | #ifndef _WIN32RELAYTCPSOCKER_H_
#define _WIN32RELAYTCPSOCKER_H_
#include "braincloud/internal/IRelayTCPSocket.h"
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <thread>
#include <atomic>
namespace BrainCloud
{
class Win32RelayTCPSocket final : public IRelayTCPSocket
{
public:
~Win32RelayTCPSocket();
void updateConnection() override;
bool isConnected() override;
bool isValid() override;
void send(const uint8_t* pData, int size) override;
const uint8_t* peek(int& size) override; // Returns null if nothing to read
void close() override;
protected:
friend class IRelayTCPSocket;
Win32RelayTCPSocket(const std::string& address, int port, int maxPacketSize);
private:
enum class State
{
FetchingRemotes,
Connecting,
Connected,
Error
};
void connect(addrinfo* pAddress);
bool poll();
SOCKET m_socket = INVALID_SOCKET;
std::atomic<State> m_state;
struct addrinfo* m_pRemoteAddresses = nullptr;
struct addrinfo* m_pRemoteAddress = nullptr;
std::thread m_getAddrInfoThread;
fd_set m_fdsSet;
fd_set m_fdsRead;
fd_set m_fdsWrite;
int m_maxPacketSize;
int m_read = 0;
uint8_t* m_buffer;
};
};
#endif /* _WIN32RELAYTCPSOCKER_H_ */
| [
"[email protected]"
] | |
ea3d5a922a18e8bd0d84587b756007540ccbabe0 | 7e48d392300fbc123396c6a517dfe8ed1ea7179f | /RodentVR/Intermediate/Build/Win64/RodentVR/Inc/RodentVR/StartPosition.gen.cpp | 09847110f7ccdbb90ba6b4e55b307ee619cf88b3 | [] | no_license | WestRyanK/Rodent-VR | f4920071b716df6a006b15c132bc72d3b0cba002 | 2033946f197a07b8c851b9a5075f0cb276033af6 | refs/heads/master | 2021-06-14T18:33:22.141793 | 2020-10-27T03:25:33 | 2020-10-27T03:25:33 | 154,956,842 | 1 | 1 | null | 2018-11-29T09:56:21 | 2018-10-27T11:23:11 | C++ | UTF-8 | C++ | false | false | 16,249 | cpp | // Copyright Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/GeneratedCppIncludes.h"
#include "RodentVR/Private/Simulator/StartPosition.h"
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodeStartPosition() {}
// Cross Module References
RODENTVR_API UClass* Z_Construct_UClass_AStartPosition_NoRegister();
RODENTVR_API UClass* Z_Construct_UClass_AStartPosition();
ENGINE_API UClass* Z_Construct_UClass_AActor();
UPackage* Z_Construct_UPackage__Script_RodentVR();
RODENTVR_API UClass* Z_Construct_UClass_UStartPositionSettings_NoRegister();
ENGINE_API UClass* Z_Construct_UClass_UStaticMeshComponent_NoRegister();
// End Cross Module References
DEFINE_FUNCTION(AStartPosition::execGetStartPositionTag)
{
P_FINISH;
P_NATIVE_BEGIN;
*(FName*)Z_Param__Result=AStartPosition::GetStartPositionTag();
P_NATIVE_END;
}
DEFINE_FUNCTION(AStartPosition::execUpdateFromSettings)
{
P_FINISH;
P_NATIVE_BEGIN;
P_THIS->UpdateFromSettings();
P_NATIVE_END;
}
DEFINE_FUNCTION(AStartPosition::execSetSettings)
{
P_GET_OBJECT(UStartPositionSettings,Z_Param_SettingsValue);
P_FINISH;
P_NATIVE_BEGIN;
P_THIS->SetSettings(Z_Param_SettingsValue);
P_NATIVE_END;
}
DEFINE_FUNCTION(AStartPosition::execGetSettings)
{
P_FINISH;
P_NATIVE_BEGIN;
*(UStartPositionSettings**)Z_Param__Result=P_THIS->GetSettings();
P_NATIVE_END;
}
void AStartPosition::StaticRegisterNativesAStartPosition()
{
UClass* Class = AStartPosition::StaticClass();
static const FNameNativePtrPair Funcs[] = {
{ "GetSettings", &AStartPosition::execGetSettings },
{ "GetStartPositionTag", &AStartPosition::execGetStartPositionTag },
{ "SetSettings", &AStartPosition::execSetSettings },
{ "UpdateFromSettings", &AStartPosition::execUpdateFromSettings },
};
FNativeFunctionRegistrar::RegisterFunctions(Class, Funcs, UE_ARRAY_COUNT(Funcs));
}
struct Z_Construct_UFunction_AStartPosition_GetSettings_Statics
{
struct StartPosition_eventGetSettings_Parms
{
UStartPositionSettings* ReturnValue;
};
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_ReturnValue;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_AStartPosition_GetSettings_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(StartPosition_eventGetSettings_Parms, ReturnValue), Z_Construct_UClass_UStartPositionSettings_NoRegister, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_AStartPosition_GetSettings_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_AStartPosition_GetSettings_Statics::NewProp_ReturnValue,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AStartPosition_GetSettings_Statics::Function_MetaDataParams[] = {
{ "BlueprintGetter", "" },
{ "ModuleRelativePath", "Private/Simulator/StartPosition.h" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AStartPosition_GetSettings_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AStartPosition, nullptr, "GetSettings", nullptr, nullptr, sizeof(StartPosition_eventGetSettings_Parms), Z_Construct_UFunction_AStartPosition_GetSettings_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_AStartPosition_GetSettings_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x14020401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AStartPosition_GetSettings_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_AStartPosition_GetSettings_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_AStartPosition_GetSettings()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AStartPosition_GetSettings_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_AStartPosition_GetStartPositionTag_Statics
{
struct StartPosition_eventGetStartPositionTag_Parms
{
FName ReturnValue;
};
static const UE4CodeGen_Private::FNamePropertyParams NewProp_ReturnValue;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
const UE4CodeGen_Private::FNamePropertyParams Z_Construct_UFunction_AStartPosition_GetStartPositionTag_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Name, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(StartPosition_eventGetStartPositionTag_Parms, ReturnValue), METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_AStartPosition_GetStartPositionTag_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_AStartPosition_GetStartPositionTag_Statics::NewProp_ReturnValue,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AStartPosition_GetStartPositionTag_Statics::Function_MetaDataParams[] = {
{ "ModuleRelativePath", "Private/Simulator/StartPosition.h" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AStartPosition_GetStartPositionTag_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AStartPosition, nullptr, "GetStartPositionTag", nullptr, nullptr, sizeof(StartPosition_eventGetStartPositionTag_Parms), Z_Construct_UFunction_AStartPosition_GetStartPositionTag_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_AStartPosition_GetStartPositionTag_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x14022401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AStartPosition_GetStartPositionTag_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_AStartPosition_GetStartPositionTag_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_AStartPosition_GetStartPositionTag()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AStartPosition_GetStartPositionTag_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_AStartPosition_SetSettings_Statics
{
struct StartPosition_eventSetSettings_Parms
{
UStartPositionSettings* SettingsValue;
};
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_SettingsValue;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_AStartPosition_SetSettings_Statics::NewProp_SettingsValue = { "SettingsValue", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(StartPosition_eventSetSettings_Parms, SettingsValue), Z_Construct_UClass_UStartPositionSettings_NoRegister, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_AStartPosition_SetSettings_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_AStartPosition_SetSettings_Statics::NewProp_SettingsValue,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AStartPosition_SetSettings_Statics::Function_MetaDataParams[] = {
{ "BlueprintSetter", "" },
{ "ModuleRelativePath", "Private/Simulator/StartPosition.h" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AStartPosition_SetSettings_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AStartPosition, nullptr, "SetSettings", nullptr, nullptr, sizeof(StartPosition_eventSetSettings_Parms), Z_Construct_UFunction_AStartPosition_SetSettings_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_AStartPosition_SetSettings_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04020401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AStartPosition_SetSettings_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_AStartPosition_SetSettings_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_AStartPosition_SetSettings()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AStartPosition_SetSettings_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_AStartPosition_UpdateFromSettings_Statics
{
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AStartPosition_UpdateFromSettings_Statics::Function_MetaDataParams[] = {
{ "ModuleRelativePath", "Private/Simulator/StartPosition.h" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AStartPosition_UpdateFromSettings_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AStartPosition, nullptr, "UpdateFromSettings", nullptr, nullptr, 0, nullptr, 0, RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04020401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AStartPosition_UpdateFromSettings_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_AStartPosition_UpdateFromSettings_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_AStartPosition_UpdateFromSettings()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AStartPosition_UpdateFromSettings_Statics::FuncParams);
}
return ReturnFunction;
}
UClass* Z_Construct_UClass_AStartPosition_NoRegister()
{
return AStartPosition::StaticClass();
}
struct Z_Construct_UClass_AStartPosition_Statics
{
static UObject* (*const DependentSingletons[])();
static const FClassFunctionLinkInfo FuncInfo[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[];
#endif
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_StaticMesh_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_StaticMesh;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Settings_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_Settings;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
static const FCppClassTypeInfoStatic StaticCppClassTypeInfo;
static const UE4CodeGen_Private::FClassParams ClassParams;
};
UObject* (*const Z_Construct_UClass_AStartPosition_Statics::DependentSingletons[])() = {
(UObject* (*)())Z_Construct_UClass_AActor,
(UObject* (*)())Z_Construct_UPackage__Script_RodentVR,
};
const FClassFunctionLinkInfo Z_Construct_UClass_AStartPosition_Statics::FuncInfo[] = {
{ &Z_Construct_UFunction_AStartPosition_GetSettings, "GetSettings" }, // 3770094197
{ &Z_Construct_UFunction_AStartPosition_GetStartPositionTag, "GetStartPositionTag" }, // 3221701757
{ &Z_Construct_UFunction_AStartPosition_SetSettings, "SetSettings" }, // 3997540743
{ &Z_Construct_UFunction_AStartPosition_UpdateFromSettings, "UpdateFromSettings" }, // 2932015467
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AStartPosition_Statics::Class_MetaDataParams[] = {
{ "IncludePath", "Simulator/StartPosition.h" },
{ "ModuleRelativePath", "Private/Simulator/StartPosition.h" },
};
#endif
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AStartPosition_Statics::NewProp_StaticMesh_MetaData[] = {
{ "EditInline", "true" },
{ "ModuleRelativePath", "Private/Simulator/StartPosition.h" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_AStartPosition_Statics::NewProp_StaticMesh = { "StaticMesh", nullptr, (EPropertyFlags)0x0040000000080008, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AStartPosition, StaticMesh), Z_Construct_UClass_UStaticMeshComponent_NoRegister, METADATA_PARAMS(Z_Construct_UClass_AStartPosition_Statics::NewProp_StaticMesh_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_AStartPosition_Statics::NewProp_StaticMesh_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AStartPosition_Statics::NewProp_Settings_MetaData[] = {
{ "BlueprintGetter", "GetSettings" },
{ "BlueprintSetter", "SetSettings" },
{ "Category", "StartPosition" },
{ "ModuleRelativePath", "Private/Simulator/StartPosition.h" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_AStartPosition_Statics::NewProp_Settings = { "Settings", nullptr, (EPropertyFlags)0x0040000000000004, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AStartPosition, Settings), Z_Construct_UClass_UStartPositionSettings_NoRegister, METADATA_PARAMS(Z_Construct_UClass_AStartPosition_Statics::NewProp_Settings_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_AStartPosition_Statics::NewProp_Settings_MetaData)) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_AStartPosition_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AStartPosition_Statics::NewProp_StaticMesh,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AStartPosition_Statics::NewProp_Settings,
};
const FCppClassTypeInfoStatic Z_Construct_UClass_AStartPosition_Statics::StaticCppClassTypeInfo = {
TCppClassTypeTraits<AStartPosition>::IsAbstract,
};
const UE4CodeGen_Private::FClassParams Z_Construct_UClass_AStartPosition_Statics::ClassParams = {
&AStartPosition::StaticClass,
"Engine",
&StaticCppClassTypeInfo,
DependentSingletons,
FuncInfo,
Z_Construct_UClass_AStartPosition_Statics::PropPointers,
nullptr,
UE_ARRAY_COUNT(DependentSingletons),
UE_ARRAY_COUNT(FuncInfo),
UE_ARRAY_COUNT(Z_Construct_UClass_AStartPosition_Statics::PropPointers),
0,
0x008000A4u,
METADATA_PARAMS(Z_Construct_UClass_AStartPosition_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_AStartPosition_Statics::Class_MetaDataParams))
};
UClass* Z_Construct_UClass_AStartPosition()
{
static UClass* OuterClass = nullptr;
if (!OuterClass)
{
UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_AStartPosition_Statics::ClassParams);
}
return OuterClass;
}
IMPLEMENT_CLASS(AStartPosition, 1683886366);
template<> RODENTVR_API UClass* StaticClass<AStartPosition>()
{
return AStartPosition::StaticClass();
}
static FCompiledInDefer Z_CompiledInDefer_UClass_AStartPosition(Z_Construct_UClass_AStartPosition, &AStartPosition::StaticClass, TEXT("/Script/RodentVR"), TEXT("AStartPosition"), false, nullptr, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(AStartPosition);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
| [
"[email protected]"
] | |
20b494fa308b77a6339c8a57c7a3d02340a1d2ca | 95b33131d5d9749a4ffb8482ff51bf63c5e5f145 | /Design/CityMonitor/Sources/HistoryVideoPlayer.cpp | 344d35e6e226b4c9f6daf68e22c83ecda3cae851 | [] | no_license | TongYinHuang-Swift/CityMonitor | 5ef7b17b50777489923fec7fe61cd783cfe3c2fe | 589a1f3eba85f138e0cfbd6a2b9ad6c3bc6486fc | refs/heads/master | 2021-01-17T05:24:46.850756 | 2016-07-11T03:27:22 | 2016-07-11T03:28:28 | 62,879,311 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 533 | cpp | #include "HistoryVideoPlayer.h"
#include "Debugger.h"
HistoryVideoPlayer::HistoryVideoPlayer()
{
}
HistoryVideoPlayer::HistoryVideoPlayer(VideoManager* manager, byte videoID, DateTime startTime, DateTime endTime)
{
}
HistoryVideoPlayer::~HistoryVideoPlayer()
{
}
void HistoryVideoPlayer::run()
{
PRINT(ALWAYS_PRINT, "HistoryVideoPlayer", __FUNCTION__, __LINE__);
}
void HistoryVideoPlayer::SetPlaySpeed(byte playSpeed)
{
PRINT(ALWAYS_PRINT, "HistoryVideoPlayer", __FUNCTION__, __LINE__, "playSpeed = %d", playSpeed);
}
| [
"[email protected]"
] | |
1a5cccd1cb457ad0decc663f84260f5d5cacafc3 | 31f5cddb9885fc03b5c05fba5f9727b2f775cf47 | /engine/core/render/base/pipeline/image_filter.cpp | a7140641c0cec6d7f22424137b6a6f090511f328 | [
"MIT"
] | permissive | timi-liuliang/echo | 2935a34b80b598eeb2c2039d686a15d42907d6f7 | d6e40d83c86431a819c6ef4ebb0f930c1b4d0f24 | refs/heads/master | 2023-08-17T05:35:08.104918 | 2023-08-11T18:10:35 | 2023-08-11T18:10:35 | 124,620,874 | 822 | 102 | MIT | 2021-06-11T14:29:03 | 2018-03-10T04:07:35 | C++ | UTF-8 | C++ | false | false | 2,743 | cpp | #include "engine/core/render/base/mesh/mesh.h"
#include "engine/core/render/base/renderer.h"
#include "image_filter.h"
namespace Echo
{
ImageFilter::~ImageFilter()
{
}
void ImageFilter::bindMethods()
{
CLASS_BIND_METHOD(ImageFilter, getMaterial);
CLASS_BIND_METHOD(ImageFilter, setMaterial);
CLASS_REGISTER_PROPERTY(ImageFilter, "Material", Variant::Type::Object, getMaterial, setMaterial);
CLASS_REGISTER_PROPERTY_HINT(ImageFilter, "Material", PropertyHintType::ObjectType, "Material");
}
void ImageFilter::setMaterial(Object* material)
{
m_material = (Material*)material;
if (m_material)
{
setGlobalUniforms();
m_material->onShaderChanged.connectClassMethod(this, createMethodBind(&ImageFilter::setGlobalUniforms));
}
m_isRenderableDirty = true;
}
void ImageFilter::setGlobalUniforms()
{
if (m_material)
{
m_material->setUniformValue("u_WorldMatrix", &Matrix4::IDENTITY);
m_material->setUniformValue("u_ViewProjMatrix", &Matrix4::IDENTITY);
}
}
void ImageFilter::render(FrameBufferPtr& frameBuffer)
{
onRenderBegin();
Renderer* render = Renderer::instance();
if (render)
{
if(buildRenderable())
render->draw(m_renderable, frameBuffer);
}
onRenderEnd();
}
void ImageFilter::clearRenderable()
{
m_renderable.reset();
m_mesh.reset();
}
bool ImageFilter::buildRenderable()
{
if (m_isRenderableDirty && m_material)
{
clearRenderable();
updateMeshBuffer();
// create render able
m_renderable = RenderProxy::create(m_mesh, m_material, nullptr, false);
m_renderable->setSubmitToRenderQueue(false);
m_isRenderableDirty = false;
}
return m_renderable ? true : false;
}
void ImageFilter::buildMeshData(VertexArray& oVertices, IndiceArray& oIndices)
{
// https://www.khronos.org/opengl/wiki/Face_Culling
// On a freshly created OpenGL Context, the default front face is Counter-Clockwise(CL_CCW)
oIndices = { 0, 1, 2, 0, 2, 3 };
float hw = -1.f;
float hh = 1.f;
// vertices
oVertices.emplace_back(Vector3(-hw, -hh, 0.f), Vector2(1.f, 0.f));
oVertices.emplace_back(Vector3(hw, -hh, 0.f), Vector2(0.f, 0.f));
oVertices.emplace_back(Vector3(hw, hh, 0.f), Vector2(0.f, 1.f));
oVertices.emplace_back(Vector3(-hw, hh, 0.f), Vector2(1.f, 1.f));
}
void ImageFilter::updateMeshBuffer()
{
// create mesh
if (!m_mesh) m_mesh = Mesh::create(true, true);
// update data
VertexArray vertices;
IndiceArray indices;
buildMeshData(vertices, indices);
MeshVertexFormat define;
define.m_isUseUV = true;
m_mesh->updateIndices(static_cast<ui32>(indices.size()), sizeof(ui16), indices.data());
m_mesh->updateVertexs(define, static_cast<ui32>(vertices.size()), (const Byte*)vertices.data());
}
} | [
"[email protected]"
] | |
592f9038feddd2898f4801f1255c032754fc58ad | 2f892cf2781f5ab439e062cae9b491084699a766 | /client/client-multi/client-cpp/impl/log/DefaultLogUploadStrategy.cpp | 7e48fe633f27f760e104390fb94500c17672c1a5 | [
"Apache-2.0"
] | permissive | kamilerman/kaa | 29311880722d4bb52d6411f8a472695faef843ad | 096ac6c684d7ce49fa34945667459f0c90b6a502 | refs/heads/master | 2021-01-22T14:45:27.014228 | 2015-05-18T08:53:28 | 2015-05-18T08:53:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,751 | cpp | /*
* Copyright 2014-2015 CyberVision, 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.
*/
#include "kaa/log/DefaultLogUploadStrategy.hpp"
#include "kaa/logging/Log.hpp"
#include "kaa/log/ILogStorageStatus.hpp"
#include "kaa/common/exception/KaaException.hpp"
namespace kaa {
const std::size_t DefaultLogUploadStrategy::DEFAULT_BATCH_SIZE;
const std::size_t DefaultLogUploadStrategy::DEFAULT_UPLOAD_TIMEOUT;
const std::size_t DefaultLogUploadStrategy::DEFAULT_RETRY_PERIOD;
const std::size_t DefaultLogUploadStrategy::DEFAULT_UPLOAD_VOLUME_THRESHOLD;
const std::size_t DefaultLogUploadStrategy::DEFAULT_UPLOAD_COUNT_THRESHOLD;
DefaultLogUploadStrategy::DefaultLogUploadStrategy(IKaaChannelManagerPtr manager)
{
if (!manager) {
KAA_LOG_ERROR("Failed to create default upload strategy: channel manager is null");
throw KaaException("Channel manager is null");
}
channelManager_ = manager;
}
LogUploadStrategyDecision DefaultLogUploadStrategy::isUploadNeeded(ILogStorageStatus& status)
{
LogUploadStrategyDecision decision = LogUploadStrategyDecision::NOOP;
if (nextUploadAttemptTS_.time_since_epoch().count()) {
if (Clock::now() >= nextUploadAttemptTS_) {
KAA_LOG_INFO("Retry log upload after failure");
nextUploadAttemptTS_ = std::chrono::time_point<Clock>();
decision = LogUploadStrategyDecision::UPLOAD;
}
return decision;
}
if (status.getConsumedVolume() >= uploadVolumeThreshold_) {
KAA_LOG_INFO(boost::format("Need to upload logs - current size: %1%, max: %2%")
% status.getConsumedVolume() % uploadVolumeThreshold_);
decision = LogUploadStrategyDecision::UPLOAD;
} else if (status.getRecordsCount() >= uploadCountThreshold_) {
KAA_LOG_INFO(boost::format("Need to upload logs - current record count: %1%, max: %2%")
% status.getRecordsCount() % uploadCountThreshold_);
decision = LogUploadStrategyDecision::UPLOAD;
}
return decision;
}
void DefaultLogUploadStrategy::onTimeout()
{
KAA_LOG_WARN("Log upload timeout occurred. Try to switch to another Operations server");
IDataChannelPtr logChannel = channelManager_->getChannelByTransportType(TransportType::LOGGING);
if (logChannel) {
channelManager_->onServerFailed(logChannel->getServer());
} else {
KAA_LOG_ERROR("Can't find LOGGING data channel");
}
}
void DefaultLogUploadStrategy::onFailure(LogDeliveryErrorCode code)
{
switch (code) {
case LogDeliveryErrorCode::NO_APPENDERS_CONFIGURED:
case LogDeliveryErrorCode::APPENDER_INTERNAL_ERROR:
case LogDeliveryErrorCode::REMOTE_CONNECTION_ERROR:
case LogDeliveryErrorCode::REMOTE_INTERNAL_ERROR:
KAA_LOG_WARN(boost::format("Log upload failed with error code %1%. Retry upload after %2% seconds")
% code % retryReriod_);
nextUploadAttemptTS_ = std::chrono::system_clock::now() + std::chrono::seconds(retryReriod_);
break;
default:
break;
}
}
} /* namespace kaa */
| [
"[email protected]"
] | |
adf1aebe80f83297e2bff0c052567d73eefd9593 | 4ec0273325d763a5e3e613307d3212cdb35786a8 | /Source/TestingGrounds/ActorPool.cpp | 144320887ee45d5a184110afbb56cb0d1220eca1 | [] | no_license | araujojr82/TestingGrounds | ddbe45d0c3b20a88b75c71beaef32d14ed1ef7ee | 69f7bfc1fa484ba8a624a35cbc01660ee309f5b2 | refs/heads/master | 2020-05-16T06:48:24.944699 | 2019-05-12T05:54:25 | 2019-05-12T05:54:25 | 182,856,631 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 730 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "ActorPool.h"
#include "GameFramework/Actor.h"
// Sets default values for this component's properties
UActorPool::UActorPool()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = true;
// ...
}
AActor* UActorPool::Checkout()
{
if( Pool.Num() == 0 )
{
return nullptr;
}
return Pool.Pop();
}
void UActorPool::Return( AActor* ActorToReturn )
{
Add( ActorToReturn );
}
void UActorPool::Add( AActor* ActorToAdd )
{
if( ActorToAdd )
{
Pool.Push( ActorToAdd );
}
} | [
"[email protected]"
] | |
e982c7679c9a5f5f23e2f03189045ad3b80f0857 | 8267a9d167f9c58848c7aaabcc28192ef1b54342 | /Assignments/1(ftree)/inc/Person.h | 553a217dc93f0713e6da0bdb0239eb94e05982eb | [] | no_license | Tyler-Gauch/SystemsProgramming | 027b4cf0b4ea4e5cedf414bc5baecda5f6ca70e8 | cf7f3c92e77d8f6917c11ede8fb4a7c1e38544b7 | refs/heads/master | 2021-01-16T20:44:35.453427 | 2016-08-02T20:13:29 | 2016-08-02T20:13:29 | 64,789,214 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 767 | h | #ifndef __PERSON__
#define __PERSON__
#include <iostream>
#include <string>
#include <vector>
class Person{
public:
Person();
Person(std::string firstName);
std::string getFirstName();
void setFirstName(std::string firstName);
std::string getLastName();
void setLastName(std::string lastName);
std::string getFullName();
std::string getSex();
void setSex(std::string sex);
Person* getMother();
void setMother(Person* mother);
Person* getFather();
void setFather(Person* father);
void print();
void addChild(Person * child);
std::vector<Person*> getChildren();
bool isMale();
bool isFemale();
private:
std::string firstName;
std::string lastName;
std::string sex;
Person * mother;
Person * father;
std::vector<Person*> children;
};
#endif
| [
"[email protected]"
] | |
53291c597490824cb9bcdc2779c7e17b305d5e6a | 9b882c3dfaa41e62b15fb635599ef6780f2c8379 | /net/reporting/reporting_cache_unittest.cc | d1e03ae27ea2c565c40dcdf5594dc9036dd604ee | [
"BSD-3-Clause"
] | permissive | cqtangsong/chromium | 1e042e2f49d9cb194790674805afcc1308a08f81 | e73c1f260913f418bf5886b996b02dae372cfffa | refs/heads/master | 2023-01-14T07:34:05.166609 | 2020-03-12T03:07:32 | 2020-03-12T03:07:32 | 246,735,752 | 2 | 0 | BSD-3-Clause | 2020-03-12T03:32:44 | 2020-03-12T03:32:43 | null | UTF-8 | C++ | false | false | 69,028 | 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 "net/reporting/reporting_cache.h"
#include <algorithm>
#include <string>
#include <utility>
#include "base/bind.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/test/simple_test_tick_clock.h"
#include "base/test/values_test_util.h"
#include "base/time/time.h"
#include "base/values.h"
#include "net/base/network_isolation_key.h"
#include "net/reporting/mock_persistent_reporting_store.h"
#include "net/reporting/reporting_cache_impl.h"
#include "net/reporting/reporting_cache_observer.h"
#include "net/reporting/reporting_endpoint.h"
#include "net/reporting/reporting_report.h"
#include "net/reporting/reporting_test_util.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
#include "url/origin.h"
namespace net {
namespace {
using CommandType = MockPersistentReportingStore::Command::Type;
class TestReportingCacheObserver : public ReportingCacheObserver {
public:
TestReportingCacheObserver()
: cached_reports_update_count_(0), cached_clients_update_count_(0) {}
void OnReportsUpdated() override { ++cached_reports_update_count_; }
void OnClientsUpdated() override { ++cached_clients_update_count_; }
int cached_reports_update_count() const {
return cached_reports_update_count_;
}
int cached_clients_update_count() const {
return cached_clients_update_count_;
}
private:
int cached_reports_update_count_;
int cached_clients_update_count_;
};
// The tests are parametrized on a boolean value which represents whether or not
// to use a MockPersistentReportingStore.
class ReportingCacheTest : public ReportingTestBase,
public ::testing::WithParamInterface<bool> {
protected:
ReportingCacheTest() : ReportingTestBase() {
ReportingPolicy policy;
policy.max_report_count = 5;
policy.max_endpoints_per_origin = 3;
policy.max_endpoint_count = 5;
policy.max_group_staleness = base::TimeDelta::FromDays(3);
UsePolicy(policy);
if (GetParam())
store_ = std::make_unique<MockPersistentReportingStore>();
else
store_ = nullptr;
UseStore(store_.get());
context()->AddCacheObserver(&observer_);
}
~ReportingCacheTest() override { context()->RemoveCacheObserver(&observer_); }
void LoadReportingClients() {
// All ReportingCache methods assume that the store has been initialized.
if (store()) {
store()->LoadReportingClients(
base::BindOnce(&ReportingCache::AddClientsLoadedFromStore,
base::Unretained(cache())));
store()->FinishLoading(true);
}
}
TestReportingCacheObserver* observer() { return &observer_; }
size_t report_count() {
std::vector<const ReportingReport*> reports;
cache()->GetReports(&reports);
return reports.size();
}
MockPersistentReportingStore* store() { return store_.get(); }
// Adds a new report to the cache, and returns it.
const ReportingReport* AddAndReturnReport(
const GURL& url,
const std::string& user_agent,
const std::string& group,
const std::string& type,
std::unique_ptr<const base::Value> body,
int depth,
base::TimeTicks queued,
int attempts) {
const base::Value* body_unowned = body.get();
// The public API will only give us the (unordered) full list of reports in
// the cache. So we need to grab the list before we add, and the list after
// we add, and return the one element that's different. This is only used
// in test cases, so I've optimized for readability over execution speed.
std::vector<const ReportingReport*> before;
cache()->GetReports(&before);
cache()->AddReport(url, user_agent, group, type, std::move(body), depth,
queued, attempts);
std::vector<const ReportingReport*> after;
cache()->GetReports(&after);
for (const ReportingReport* report : after) {
// If report isn't in before, we've found the new instance.
if (std::find(before.begin(), before.end(), report) == before.end()) {
// Sanity check the result before we return it.
EXPECT_EQ(url, report->url);
EXPECT_EQ(user_agent, report->user_agent);
EXPECT_EQ(group, report->group);
EXPECT_EQ(type, report->type);
EXPECT_EQ(*body_unowned, *report->body);
EXPECT_EQ(depth, report->depth);
EXPECT_EQ(queued, report->queued);
EXPECT_EQ(attempts, report->attempts);
return report;
}
}
// This can actually happen! If the newly created report isn't in the after
// vector, that means that we had to evict a report, and the new report was
// the only one eligible for eviction!
return nullptr;
}
// Creates a new endpoint group by way of adding two endpoints.
void CreateGroupAndEndpoints(const ReportingEndpointGroupKey& group) {
EXPECT_FALSE(EndpointGroupExistsInCache(group, OriginSubdomains::DEFAULT));
ASSERT_TRUE(SetEndpointInCache(group, kEndpoint1_, kExpires1_));
ASSERT_TRUE(SetEndpointInCache(group, kEndpoint2_, kExpires1_));
}
// If |exist| is true, expect that the given group exists and has two
// endpoints, and its client exists. If |exist| is false, expect that the
// group and its endpoints don't exist (does not check the client in that
// case).
void ExpectExistence(const ReportingEndpointGroupKey& group, bool exist) {
ReportingEndpoint endpoint1 = FindEndpointInCache(group, kEndpoint1_);
ReportingEndpoint endpoint2 = FindEndpointInCache(group, kEndpoint2_);
EXPECT_EQ(exist, endpoint1.is_valid());
EXPECT_EQ(exist, endpoint2.is_valid());
if (exist) {
EXPECT_EQ(endpoint1.group_key, group);
EXPECT_EQ(endpoint2.group_key, group);
EXPECT_TRUE(cache()->ClientExistsForTesting(group.network_isolation_key,
group.origin));
}
EXPECT_EQ(exist,
EndpointGroupExistsInCache(group, OriginSubdomains::DEFAULT));
}
const GURL kUrl1_ = GURL("https://origin1/path");
const GURL kUrl2_ = GURL("https://origin2/path");
const url::Origin kOrigin1_ = url::Origin::Create(GURL("https://origin1/"));
const url::Origin kOrigin2_ = url::Origin::Create(GURL("https://origin2/"));
const NetworkIsolationKey kNik_;
const NetworkIsolationKey kOtherNik_ =
NetworkIsolationKey(kOrigin1_, kOrigin2_);
const GURL kEndpoint1_ = GURL("https://endpoint1/");
const GURL kEndpoint2_ = GURL("https://endpoint2/");
const GURL kEndpoint3_ = GURL("https://endpoint3/");
const GURL kEndpoint4_ = GURL("https://endpoint4/");
const std::string kUserAgent_ = "Mozilla/1.0";
const std::string kGroup1_ = "group1";
const std::string kGroup2_ = "group2";
const std::string kType_ = "default";
const base::TimeTicks kNowTicks_ = tick_clock()->NowTicks();
const base::Time kNow_ = clock()->Now();
const base::Time kExpires1_ = kNow_ + base::TimeDelta::FromDays(7);
const base::Time kExpires2_ = kExpires1_ + base::TimeDelta::FromDays(7);
// There are 2^3 = 8 of these to test the different combinations of matching
// vs mismatching NIK, origin, and group.
const ReportingEndpointGroupKey kGroupKey11_ =
ReportingEndpointGroupKey(kNik_, kOrigin1_, kGroup1_);
const ReportingEndpointGroupKey kGroupKey21_ =
ReportingEndpointGroupKey(kNik_, kOrigin2_, kGroup1_);
const ReportingEndpointGroupKey kGroupKey12_ =
ReportingEndpointGroupKey(kNik_, kOrigin1_, kGroup2_);
const ReportingEndpointGroupKey kGroupKey22_ =
ReportingEndpointGroupKey(kNik_, kOrigin2_, kGroup2_);
const ReportingEndpointGroupKey kOtherGroupKey11_ =
ReportingEndpointGroupKey(kOtherNik_, kOrigin1_, kGroup1_);
const ReportingEndpointGroupKey kOtherGroupKey21_ =
ReportingEndpointGroupKey(kOtherNik_, kOrigin2_, kGroup1_);
const ReportingEndpointGroupKey kOtherGroupKey12_ =
ReportingEndpointGroupKey(kOtherNik_, kOrigin1_, kGroup2_);
const ReportingEndpointGroupKey kOtherGroupKey22_ =
ReportingEndpointGroupKey(kOtherNik_, kOrigin2_, kGroup2_);
TestReportingCacheObserver observer_;
std::unique_ptr<MockPersistentReportingStore> store_;
};
// Note: These tests exercise both sides of the cache (reports and clients),
// aside from header parsing (i.e. OnParsedHeader(), AddOrUpdate*(),
// Remove*OtherThan() methods) which are exercised in the unittests for the
// header parser.
TEST_P(ReportingCacheTest, Reports) {
LoadReportingClients();
std::vector<const ReportingReport*> reports;
cache()->GetReports(&reports);
EXPECT_TRUE(reports.empty());
cache()->AddReport(kUrl1_, kUserAgent_, kGroup1_, kType_,
std::make_unique<base::DictionaryValue>(), 0, kNowTicks_,
0);
EXPECT_EQ(1, observer()->cached_reports_update_count());
cache()->GetReports(&reports);
ASSERT_EQ(1u, reports.size());
const ReportingReport* report = reports[0];
ASSERT_TRUE(report);
EXPECT_EQ(kUrl1_, report->url);
EXPECT_EQ(kUserAgent_, report->user_agent);
EXPECT_EQ(kGroup1_, report->group);
EXPECT_EQ(kType_, report->type);
// TODO(juliatuttle): Check body?
EXPECT_EQ(kNowTicks_, report->queued);
EXPECT_EQ(0, report->attempts);
EXPECT_FALSE(cache()->IsReportPendingForTesting(report));
EXPECT_FALSE(cache()->IsReportDoomedForTesting(report));
cache()->IncrementReportsAttempts(reports);
EXPECT_EQ(2, observer()->cached_reports_update_count());
cache()->GetReports(&reports);
ASSERT_EQ(1u, reports.size());
report = reports[0];
ASSERT_TRUE(report);
EXPECT_EQ(1, report->attempts);
cache()->RemoveReports(reports, ReportingReport::Outcome::UNKNOWN);
EXPECT_EQ(3, observer()->cached_reports_update_count());
cache()->GetReports(&reports);
EXPECT_TRUE(reports.empty());
}
TEST_P(ReportingCacheTest, RemoveAllReports) {
LoadReportingClients();
cache()->AddReport(kUrl1_, kUserAgent_, kGroup1_, kType_,
std::make_unique<base::DictionaryValue>(), 0, kNowTicks_,
0);
cache()->AddReport(kUrl1_, kUserAgent_, kGroup1_, kType_,
std::make_unique<base::DictionaryValue>(), 0, kNowTicks_,
0);
EXPECT_EQ(2, observer()->cached_reports_update_count());
std::vector<const ReportingReport*> reports;
cache()->GetReports(&reports);
EXPECT_EQ(2u, reports.size());
cache()->RemoveAllReports(ReportingReport::Outcome::UNKNOWN);
EXPECT_EQ(3, observer()->cached_reports_update_count());
cache()->GetReports(&reports);
EXPECT_TRUE(reports.empty());
}
TEST_P(ReportingCacheTest, RemovePendingReports) {
LoadReportingClients();
cache()->AddReport(kUrl1_, kUserAgent_, kGroup1_, kType_,
std::make_unique<base::DictionaryValue>(), 0, kNowTicks_,
0);
EXPECT_EQ(1, observer()->cached_reports_update_count());
std::vector<const ReportingReport*> reports;
cache()->GetReports(&reports);
ASSERT_EQ(1u, reports.size());
EXPECT_FALSE(cache()->IsReportPendingForTesting(reports[0]));
EXPECT_FALSE(cache()->IsReportDoomedForTesting(reports[0]));
EXPECT_EQ(reports, cache()->GetReportsToDeliver());
EXPECT_TRUE(cache()->IsReportPendingForTesting(reports[0]));
EXPECT_FALSE(cache()->IsReportDoomedForTesting(reports[0]));
// After getting reports to deliver, everything in the cache should be
// pending, so another call to GetReportsToDeliver should return nothing.
EXPECT_EQ(0u, cache()->GetReportsToDeliver().size());
cache()->RemoveReports(reports, ReportingReport::Outcome::UNKNOWN);
EXPECT_TRUE(cache()->IsReportPendingForTesting(reports[0]));
EXPECT_TRUE(cache()->IsReportDoomedForTesting(reports[0]));
EXPECT_EQ(2, observer()->cached_reports_update_count());
// After removing report, future calls to GetReports should not return it.
std::vector<const ReportingReport*> visible_reports;
cache()->GetReports(&visible_reports);
EXPECT_TRUE(visible_reports.empty());
EXPECT_EQ(1u, cache()->GetFullReportCountForTesting());
// After clearing pending flag, report should be deleted.
cache()->ClearReportsPending(reports);
EXPECT_EQ(0u, cache()->GetFullReportCountForTesting());
}
TEST_P(ReportingCacheTest, RemoveAllPendingReports) {
LoadReportingClients();
cache()->AddReport(kUrl1_, kUserAgent_, kGroup1_, kType_,
std::make_unique<base::DictionaryValue>(), 0, kNowTicks_,
0);
EXPECT_EQ(1, observer()->cached_reports_update_count());
std::vector<const ReportingReport*> reports;
cache()->GetReports(&reports);
ASSERT_EQ(1u, reports.size());
EXPECT_FALSE(cache()->IsReportPendingForTesting(reports[0]));
EXPECT_FALSE(cache()->IsReportDoomedForTesting(reports[0]));
EXPECT_EQ(reports, cache()->GetReportsToDeliver());
EXPECT_TRUE(cache()->IsReportPendingForTesting(reports[0]));
EXPECT_FALSE(cache()->IsReportDoomedForTesting(reports[0]));
// After getting reports to deliver, everything in the cache should be
// pending, so another call to GetReportsToDeliver should return nothing.
EXPECT_EQ(0u, cache()->GetReportsToDeliver().size());
cache()->RemoveAllReports(ReportingReport::Outcome::UNKNOWN);
EXPECT_TRUE(cache()->IsReportPendingForTesting(reports[0]));
EXPECT_TRUE(cache()->IsReportDoomedForTesting(reports[0]));
EXPECT_EQ(2, observer()->cached_reports_update_count());
// After removing report, future calls to GetReports should not return it.
std::vector<const ReportingReport*> visible_reports;
cache()->GetReports(&visible_reports);
EXPECT_TRUE(visible_reports.empty());
EXPECT_EQ(1u, cache()->GetFullReportCountForTesting());
// After clearing pending flag, report should be deleted.
cache()->ClearReportsPending(reports);
EXPECT_EQ(0u, cache()->GetFullReportCountForTesting());
}
TEST_P(ReportingCacheTest, GetReportsAsValue) {
LoadReportingClients();
// We need a reproducible expiry timestamp for this test case.
const base::TimeTicks now = base::TimeTicks();
const ReportingReport* report1 =
AddAndReturnReport(kUrl1_, kUserAgent_, kGroup1_, kType_,
std::make_unique<base::DictionaryValue>(), 0,
now + base::TimeDelta::FromSeconds(200), 0);
const ReportingReport* report2 =
AddAndReturnReport(kUrl1_, kUserAgent_, kGroup2_, kType_,
std::make_unique<base::DictionaryValue>(), 0,
now + base::TimeDelta::FromSeconds(100), 1);
// Mark report1 and report2 as pending.
EXPECT_THAT(cache()->GetReportsToDeliver(),
::testing::UnorderedElementsAre(report1, report2));
// Mark report2 as doomed.
cache()->RemoveReports({report2}, ReportingReport::Outcome::UNKNOWN);
base::Value actual = cache()->GetReportsAsValue();
base::Value expected = base::test::ParseJson(R"json(
[
{
"url": "https://origin1/path",
"group": "group2",
"type": "default",
"status": "doomed",
"body": {},
"attempts": 1,
"depth": 0,
"queued": "100000",
},
{
"url": "https://origin1/path",
"group": "group1",
"type": "default",
"status": "pending",
"body": {},
"attempts": 0,
"depth": 0,
"queued": "200000",
},
]
)json");
EXPECT_EQ(expected, actual);
// Add two new reports that will show up as "queued".
const ReportingReport* report3 =
AddAndReturnReport(kUrl2_, kUserAgent_, kGroup1_, kType_,
std::make_unique<base::DictionaryValue>(), 2,
now + base::TimeDelta::FromSeconds(200), 0);
const ReportingReport* report4 =
AddAndReturnReport(kUrl1_, kUserAgent_, kGroup1_, kType_,
std::make_unique<base::DictionaryValue>(), 0,
now + base::TimeDelta::FromSeconds(300), 0);
actual = cache()->GetReportsAsValue();
expected = base::test::ParseJson(R"json(
[
{
"url": "https://origin1/path",
"group": "group2",
"type": "default",
"status": "doomed",
"body": {},
"attempts": 1,
"depth": 0,
"queued": "100000",
},
{
"url": "https://origin1/path",
"group": "group1",
"type": "default",
"status": "pending",
"body": {},
"attempts": 0,
"depth": 0,
"queued": "200000",
},
{
"url": "https://origin2/path",
"group": "group1",
"type": "default",
"status": "queued",
"body": {},
"attempts": 0,
"depth": 2,
"queued": "200000",
},
{
"url": "https://origin1/path",
"group": "group1",
"type": "default",
"status": "queued",
"body": {},
"attempts": 0,
"depth": 0,
"queued": "300000",
},
]
)json");
EXPECT_EQ(expected, actual);
// GetReportsToDeliver only returns the non-pending reports.
EXPECT_THAT(cache()->GetReportsToDeliver(),
::testing::UnorderedElementsAre(report3, report4));
}
TEST_P(ReportingCacheTest, Endpoints) {
LoadReportingClients();
EXPECT_EQ(0u, cache()->GetEndpointCount());
ASSERT_TRUE(SetEndpointInCache(kGroupKey11_, kEndpoint1_, kExpires1_));
EXPECT_EQ(1u, cache()->GetEndpointCount());
const ReportingEndpoint endpoint1 =
FindEndpointInCache(kGroupKey11_, kEndpoint1_);
ASSERT_TRUE(endpoint1);
EXPECT_EQ(kOrigin1_, endpoint1.group_key.origin);
EXPECT_EQ(kEndpoint1_, endpoint1.info.url);
EXPECT_EQ(kGroup1_, endpoint1.group_key.group_name);
EXPECT_TRUE(EndpointGroupExistsInCache(
kGroupKey11_, OriginSubdomains::DEFAULT, kExpires1_));
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
// Insert another endpoint in the same group.
ASSERT_TRUE(SetEndpointInCache(kGroupKey11_, kEndpoint2_, kExpires1_));
EXPECT_EQ(2u, cache()->GetEndpointCount());
const ReportingEndpoint endpoint2 =
FindEndpointInCache(kGroupKey11_, kEndpoint2_);
ASSERT_TRUE(endpoint2);
EXPECT_EQ(kOrigin1_, endpoint2.group_key.origin);
EXPECT_EQ(kEndpoint2_, endpoint2.info.url);
EXPECT_EQ(kGroup1_, endpoint2.group_key.group_name);
EXPECT_TRUE(EndpointGroupExistsInCache(
kGroupKey11_, OriginSubdomains::DEFAULT, kExpires1_));
EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting());
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
std::set<url::Origin> origins_in_cache = cache()->GetAllOrigins();
EXPECT_EQ(1u, origins_in_cache.size());
// Insert another endpoint for a different origin with same group name.
ASSERT_TRUE(SetEndpointInCache(kGroupKey21_, kEndpoint2_, kExpires1_));
EXPECT_EQ(3u, cache()->GetEndpointCount());
const ReportingEndpoint endpoint3 =
FindEndpointInCache(kGroupKey21_, kEndpoint2_);
ASSERT_TRUE(endpoint3);
EXPECT_EQ(kOrigin2_, endpoint3.group_key.origin);
EXPECT_EQ(kEndpoint2_, endpoint3.info.url);
EXPECT_EQ(kGroup1_, endpoint3.group_key.group_name);
EXPECT_TRUE(EndpointGroupExistsInCache(
kGroupKey21_, OriginSubdomains::DEFAULT, kExpires1_));
EXPECT_EQ(2u, cache()->GetEndpointGroupCountForTesting());
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin2_));
origins_in_cache = cache()->GetAllOrigins();
EXPECT_EQ(2u, origins_in_cache.size());
}
TEST_P(ReportingCacheTest, ClientsKeyedByEndpointGroupKey) {
// Raise the endpoint limits for this test.
// (This needs to first remove the cache observer because this destroys the
// old ReportingContext, which must not have any observers upon destruction.)
context()->RemoveCacheObserver(&observer_);
ReportingPolicy policy;
policy.max_endpoints_per_origin = 5; // This test should use 4.
policy.max_endpoint_count = 20; // This test should use 16.
UsePolicy(policy);
context()->AddCacheObserver(&observer_);
LoadReportingClients();
const ReportingEndpointGroupKey kGroupKeys[] = {
kGroupKey11_, kGroupKey12_, kGroupKey21_,
kGroupKey22_, kOtherGroupKey11_, kOtherGroupKey12_,
kOtherGroupKey21_, kOtherGroupKey22_,
};
size_t endpoint_group_count = 0u;
size_t endpoint_count = 0u;
// Check that the group keys are all considered distinct, and nothing is
// overwritten.
for (const auto& group : kGroupKeys) {
CreateGroupAndEndpoints(group);
ExpectExistence(group, true);
++endpoint_group_count;
EXPECT_EQ(endpoint_group_count, cache()->GetEndpointGroupCountForTesting());
endpoint_count += 2u;
EXPECT_EQ(endpoint_count, cache()->GetEndpointCount());
}
// Check that everything is there at the end.
for (const auto& group : kGroupKeys) {
ExpectExistence(group, true);
}
size_t client_count = 4u;
EXPECT_EQ(client_count, cache()->GetClientCountForTesting());
// Test that Clients with different NIKs are considered different, and test
// RemoveEndpointGroup() and RemoveClient().
const std::pair<NetworkIsolationKey, url::Origin> kNikOriginPairs[] = {
{kNik_, kOrigin1_},
{kNik_, kOrigin2_},
{kOtherNik_, kOrigin1_},
{kOtherNik_, kOrigin2_},
};
// SetEndpointInCache doesn't update store counts, which is why we start from
// zero and they go negative.
// TODO(crbug.com/895821): Populate the cache via the store so we don't
// need negative counts.
MockPersistentReportingStore::CommandList expected_commands;
int stored_group_count = 0;
int stored_endpoint_count = 0;
int store_remove_group_count = 0;
int store_remove_endpoint_count = 0;
for (const auto& pair : kNikOriginPairs) {
EXPECT_TRUE(cache()->ClientExistsForTesting(pair.first, pair.second));
ReportingEndpointGroupKey group1(pair.first, pair.second, kGroup1_);
ReportingEndpointGroupKey group2(pair.first, pair.second, kGroup2_);
ExpectExistence(group1, true);
ExpectExistence(group2, true);
cache()->RemoveEndpointGroup(group1);
ExpectExistence(group1, false);
ExpectExistence(group2, true);
EXPECT_TRUE(cache()->ClientExistsForTesting(pair.first, pair.second));
cache()->RemoveClient(pair.first, pair.second);
ExpectExistence(group1, false);
ExpectExistence(group2, false);
EXPECT_FALSE(cache()->ClientExistsForTesting(pair.first, pair.second));
--client_count;
EXPECT_EQ(client_count, cache()->GetClientCountForTesting());
endpoint_group_count -= 2u;
stored_group_count -= 2;
EXPECT_EQ(endpoint_group_count, cache()->GetEndpointGroupCountForTesting());
endpoint_count -= 4u;
stored_endpoint_count -= 4;
EXPECT_EQ(endpoint_count, cache()->GetEndpointCount());
if (store()) {
store()->Flush();
EXPECT_EQ(stored_endpoint_count, store()->StoredEndpointsCount());
EXPECT_EQ(stored_group_count, store()->StoredEndpointGroupsCount());
store_remove_group_count += 2u;
expected_commands.emplace_back(
CommandType::DELETE_REPORTING_ENDPOINT_GROUP, group1);
expected_commands.emplace_back(
CommandType::DELETE_REPORTING_ENDPOINT_GROUP, group2);
store_remove_endpoint_count += 4u;
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
group1, kEndpoint1_);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
group1, kEndpoint2_);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
group2, kEndpoint1_);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
group2, kEndpoint2_);
EXPECT_EQ(
store_remove_group_count,
store()->CountCommands(CommandType::DELETE_REPORTING_ENDPOINT_GROUP));
EXPECT_EQ(store_remove_endpoint_count,
store()->CountCommands(CommandType::DELETE_REPORTING_ENDPOINT));
EXPECT_THAT(store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
}
}
TEST_P(ReportingCacheTest, RemoveClientsForOrigin) {
LoadReportingClients();
// Origin 1
ASSERT_TRUE(SetEndpointInCache(kGroupKey11_, kEndpoint1_, kExpires1_));
ASSERT_TRUE(SetEndpointInCache(kOtherGroupKey11_, kEndpoint1_, kExpires1_));
ASSERT_TRUE(SetEndpointInCache(kOtherGroupKey12_, kEndpoint1_, kExpires1_));
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
// Origin 2
ASSERT_TRUE(SetEndpointInCache(kGroupKey21_, kEndpoint1_, kExpires1_));
ASSERT_TRUE(SetEndpointInCache(kOtherGroupKey22_, kEndpoint2_, kExpires1_));
ASSERT_TRUE(ClientExistsInCacheForOrigin(kOrigin2_));
EXPECT_EQ(5u, cache()->GetEndpointCount());
cache()->RemoveClientsForOrigin(kOrigin1_);
EXPECT_EQ(2u, cache()->GetEndpointCount());
EXPECT_FALSE(ClientExistsInCacheForOrigin(kOrigin1_));
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin2_));
if (store()) {
store()->Flush();
// SetEndpointInCache doesn't update store counts, which is why they go
// negative here.
// TODO(crbug.com/895821): Populate the cache via the store so we don't need
// negative counts.
EXPECT_EQ(-3, store()->StoredEndpointsCount());
EXPECT_EQ(-3, store()->StoredEndpointGroupsCount());
MockPersistentReportingStore::CommandList expected_commands;
EXPECT_EQ(3,
store()->CountCommands(CommandType::DELETE_REPORTING_ENDPOINT));
EXPECT_EQ(3, store()->CountCommands(
CommandType::DELETE_REPORTING_ENDPOINT_GROUP));
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT_GROUP,
kGroupKey11_);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT_GROUP,
kOtherGroupKey11_);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT_GROUP,
kOtherGroupKey12_);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
kGroupKey11_, kEndpoint1_);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
kOtherGroupKey11_, kEndpoint1_);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
kOtherGroupKey12_, kEndpoint1_);
EXPECT_THAT(store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
}
TEST_P(ReportingCacheTest, RemoveAllClients) {
LoadReportingClients();
ASSERT_TRUE(SetEndpointInCache(kGroupKey11_, kEndpoint1_, kExpires1_));
ASSERT_TRUE(SetEndpointInCache(kGroupKey11_, kEndpoint2_, kExpires1_));
ASSERT_TRUE(SetEndpointInCache(kGroupKey21_, kEndpoint1_, kExpires1_));
ASSERT_TRUE(SetEndpointInCache(kGroupKey22_, kEndpoint2_, kExpires1_));
EXPECT_EQ(4u, cache()->GetEndpointCount());
ASSERT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
ASSERT_TRUE(ClientExistsInCacheForOrigin(kOrigin2_));
cache()->RemoveAllClients();
EXPECT_EQ(0u, cache()->GetEndpointCount());
EXPECT_FALSE(ClientExistsInCacheForOrigin(kOrigin1_));
EXPECT_FALSE(ClientExistsInCacheForOrigin(kOrigin2_));
if (store()) {
store()->Flush();
// SetEndpointInCache doesn't update store counts, which is why they go
// negative here.
// TODO(crbug.com/895821): Populate the cache via the store so we don't need
// negative counts.
EXPECT_EQ(-4, store()->StoredEndpointsCount());
EXPECT_EQ(-3, store()->StoredEndpointGroupsCount());
MockPersistentReportingStore::CommandList expected_commands;
EXPECT_EQ(4,
store()->CountCommands(CommandType::DELETE_REPORTING_ENDPOINT));
EXPECT_EQ(3, store()->CountCommands(
CommandType::DELETE_REPORTING_ENDPOINT_GROUP));
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
kGroupKey11_, kEndpoint1_);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
kGroupKey11_, kEndpoint2_);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
kGroupKey21_, kEndpoint1_);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
kGroupKey22_, kEndpoint2_);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT_GROUP,
kGroupKey11_);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT_GROUP,
kGroupKey21_);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT_GROUP,
kGroupKey22_);
EXPECT_THAT(store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
}
TEST_P(ReportingCacheTest, RemoveEndpointGroup) {
LoadReportingClients();
ASSERT_TRUE(SetEndpointInCache(kGroupKey11_, kEndpoint1_, kExpires1_));
ASSERT_TRUE(SetEndpointInCache(kGroupKey11_, kEndpoint2_, kExpires1_));
ASSERT_TRUE(SetEndpointInCache(kGroupKey21_, kEndpoint1_, kExpires1_));
ASSERT_TRUE(SetEndpointInCache(kGroupKey22_, kEndpoint2_, kExpires1_));
EXPECT_EQ(4u, cache()->GetEndpointCount());
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin2_));
EXPECT_TRUE(EndpointGroupExistsInCache(
kGroupKey11_, OriginSubdomains::DEFAULT, kExpires1_));
EXPECT_TRUE(EndpointGroupExistsInCache(
kGroupKey21_, OriginSubdomains::DEFAULT, kExpires1_));
EXPECT_TRUE(EndpointGroupExistsInCache(
kGroupKey22_, OriginSubdomains::DEFAULT, kExpires1_));
cache()->RemoveEndpointGroup(kGroupKey21_);
EXPECT_TRUE(EndpointGroupExistsInCache(
kGroupKey11_, OriginSubdomains::DEFAULT, kExpires1_));
EXPECT_FALSE(EndpointGroupExistsInCache(
kGroupKey21_, OriginSubdomains::DEFAULT, kExpires1_));
EXPECT_TRUE(EndpointGroupExistsInCache(
kGroupKey22_, OriginSubdomains::DEFAULT, kExpires1_));
cache()->RemoveEndpointGroup(kGroupKey22_);
EXPECT_FALSE(EndpointGroupExistsInCache(
kGroupKey22_, OriginSubdomains::DEFAULT, kExpires1_));
// Removal of the last group for an origin also removes the client.
EXPECT_FALSE(ClientExistsInCacheForOrigin(kOrigin2_));
// Other origins are not affected.
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
EXPECT_TRUE(EndpointGroupExistsInCache(
kGroupKey11_, OriginSubdomains::DEFAULT, kExpires1_));
if (store()) {
store()->Flush();
// SetEndpointInCache doesn't update store counts, which is why they go
// negative here.
// TODO(crbug.com/895821): Populate the cache via the store so we don't need
// negative counts.
EXPECT_EQ(-2, store()->StoredEndpointsCount());
EXPECT_EQ(-2, store()->StoredEndpointGroupsCount());
EXPECT_EQ(2,
store()->CountCommands(CommandType::DELETE_REPORTING_ENDPOINT));
EXPECT_EQ(2, store()->CountCommands(
CommandType::DELETE_REPORTING_ENDPOINT_GROUP));
MockPersistentReportingStore::CommandList expected_commands;
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
kGroupKey21_, kEndpoint1_);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
kGroupKey22_, kEndpoint2_);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT_GROUP,
kGroupKey21_);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT_GROUP,
kGroupKey22_);
EXPECT_THAT(store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
}
TEST_P(ReportingCacheTest, RemoveEndpointsForUrl) {
LoadReportingClients();
ASSERT_TRUE(SetEndpointInCache(kGroupKey11_, kEndpoint1_, kExpires1_));
ASSERT_TRUE(SetEndpointInCache(kGroupKey11_, kEndpoint2_, kExpires1_));
ASSERT_TRUE(SetEndpointInCache(kGroupKey21_, kEndpoint1_, kExpires1_));
ASSERT_TRUE(SetEndpointInCache(kGroupKey22_, kEndpoint2_, kExpires1_));
EXPECT_EQ(4u, cache()->GetEndpointCount());
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin2_));
EXPECT_TRUE(EndpointGroupExistsInCache(
kGroupKey11_, OriginSubdomains::DEFAULT, kExpires1_));
EXPECT_TRUE(EndpointGroupExistsInCache(
kGroupKey21_, OriginSubdomains::DEFAULT, kExpires1_));
EXPECT_TRUE(EndpointGroupExistsInCache(
kGroupKey22_, OriginSubdomains::DEFAULT, kExpires1_));
cache()->RemoveEndpointsForUrl(kEndpoint1_);
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin2_));
EXPECT_TRUE(EndpointGroupExistsInCache(
kGroupKey11_, OriginSubdomains::DEFAULT, kExpires1_));
EXPECT_FALSE(EndpointGroupExistsInCache(
kGroupKey21_, OriginSubdomains::DEFAULT, kExpires1_));
EXPECT_TRUE(EndpointGroupExistsInCache(
kGroupKey22_, OriginSubdomains::DEFAULT, kExpires1_));
EXPECT_EQ(2u, cache()->GetEndpointCount());
EXPECT_FALSE(FindEndpointInCache(kGroupKey11_, kEndpoint1_));
EXPECT_TRUE(FindEndpointInCache(kGroupKey11_, kEndpoint2_));
EXPECT_FALSE(FindEndpointInCache(kGroupKey21_, kEndpoint1_));
EXPECT_TRUE(FindEndpointInCache(kGroupKey22_, kEndpoint2_));
if (store()) {
store()->Flush();
// SetEndpointInCache doesn't update store counts, which is why they go
// negative here.
// TODO(crbug.com/895821): Populate the cache via the store so we don't need
// negative counts.
EXPECT_EQ(-2, store()->StoredEndpointsCount());
EXPECT_EQ(-1, store()->StoredEndpointGroupsCount());
EXPECT_EQ(2,
store()->CountCommands(CommandType::DELETE_REPORTING_ENDPOINT));
EXPECT_EQ(1, store()->CountCommands(
CommandType::DELETE_REPORTING_ENDPOINT_GROUP));
MockPersistentReportingStore::CommandList expected_commands;
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
kGroupKey11_, kEndpoint1_);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
kGroupKey21_, kEndpoint1_);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT_GROUP,
kGroupKey21_);
EXPECT_THAT(store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
}
TEST_P(ReportingCacheTest, GetClientsAsValue) {
LoadReportingClients();
// These times are bogus but we need a reproducible expiry timestamp for this
// test case.
const base::TimeTicks expires_ticks =
base::TimeTicks() + base::TimeDelta::FromDays(7);
const base::Time expires =
base::Time::UnixEpoch() + (expires_ticks - base::TimeTicks::UnixEpoch());
ASSERT_TRUE(SetEndpointInCache(kGroupKey11_, kEndpoint1_, expires,
OriginSubdomains::EXCLUDE));
ASSERT_TRUE(SetEndpointInCache(kOtherGroupKey21_, kEndpoint2_, expires,
OriginSubdomains::INCLUDE));
cache()->IncrementEndpointDeliveries(kGroupKey11_, kEndpoint1_,
/* reports */ 2, /* succeeded */ true);
cache()->IncrementEndpointDeliveries(kOtherGroupKey21_, kEndpoint2_,
/* reports */ 1, /* succeeded */ false);
base::Value actual = cache()->GetClientsAsValue();
std::unique_ptr<base::Value> expected =
base::test::ParseJsonDeprecated(base::StringPrintf(
R"json(
[
{
"network_isolation_key": "%s",
"origin": "https://origin1",
"groups": [
{
"name": "group1",
"expires": "604800000",
"includeSubdomains": false,
"endpoints": [
{"url": "https://endpoint1/", "priority": 1, "weight": 1,
"successful": {"uploads": 1, "reports": 2},
"failed": {"uploads": 0, "reports": 0}},
],
},
],
},
{
"network_isolation_key": "%s",
"origin": "https://origin2",
"groups": [
{
"name": "group1",
"expires": "604800000",
"includeSubdomains": true,
"endpoints": [
{"url": "https://endpoint2/", "priority": 1, "weight": 1,
"successful": {"uploads": 0, "reports": 0},
"failed": {"uploads": 1, "reports": 1}},
],
},
],
},
]
)json",
kNik_.ToDebugString().data(), kOtherNik_.ToDebugString().data()));
// Compare disregarding order.
auto expected_list = expected->TakeList();
auto actual_list = actual.TakeList();
std::sort(expected_list.begin(), expected_list.end());
std::sort(actual_list.begin(), actual_list.end());
EXPECT_EQ(expected_list, actual_list);
}
TEST_P(ReportingCacheTest, GetCandidateEndpointsForDelivery) {
LoadReportingClients();
ASSERT_TRUE(SetEndpointInCache(kGroupKey11_, kEndpoint1_, kExpires1_));
ASSERT_TRUE(SetEndpointInCache(kGroupKey11_, kEndpoint2_, kExpires1_));
ASSERT_TRUE(SetEndpointInCache(kGroupKey21_, kEndpoint1_, kExpires1_));
ASSERT_TRUE(SetEndpointInCache(kGroupKey22_, kEndpoint2_, kExpires1_));
std::vector<ReportingEndpoint> candidate_endpoints =
cache()->GetCandidateEndpointsForDelivery(kGroupKey11_);
ASSERT_EQ(2u, candidate_endpoints.size());
EXPECT_EQ(kGroupKey11_, candidate_endpoints[0].group_key);
EXPECT_EQ(kGroupKey11_, candidate_endpoints[1].group_key);
candidate_endpoints = cache()->GetCandidateEndpointsForDelivery(kGroupKey21_);
ASSERT_EQ(1u, candidate_endpoints.size());
EXPECT_EQ(kGroupKey21_, candidate_endpoints[0].group_key);
}
TEST_P(ReportingCacheTest, GetCandidateEndpointsDifferentNik) {
LoadReportingClients();
// Test that NIKs are respected by using 2 groups with the same origin and
// group name but different NIKs.
ASSERT_TRUE(SetEndpointInCache(kGroupKey11_, kEndpoint1_, kExpires1_));
ASSERT_TRUE(SetEndpointInCache(kGroupKey11_, kEndpoint2_, kExpires1_));
ASSERT_TRUE(SetEndpointInCache(kOtherGroupKey11_, kEndpoint1_, kExpires1_));
ASSERT_TRUE(SetEndpointInCache(kOtherGroupKey11_, kEndpoint2_, kExpires1_));
std::vector<ReportingEndpoint> candidate_endpoints =
cache()->GetCandidateEndpointsForDelivery(kGroupKey11_);
ASSERT_EQ(2u, candidate_endpoints.size());
EXPECT_EQ(kGroupKey11_, candidate_endpoints[0].group_key);
EXPECT_EQ(kGroupKey11_, candidate_endpoints[1].group_key);
candidate_endpoints =
cache()->GetCandidateEndpointsForDelivery(kOtherGroupKey11_);
ASSERT_EQ(2u, candidate_endpoints.size());
EXPECT_EQ(kOtherGroupKey11_, candidate_endpoints[0].group_key);
EXPECT_EQ(kOtherGroupKey11_, candidate_endpoints[1].group_key);
}
TEST_P(ReportingCacheTest, GetCandidateEndpointsExcludesExpired) {
LoadReportingClients();
ASSERT_TRUE(SetEndpointInCache(kGroupKey11_, kEndpoint1_, kExpires1_));
ASSERT_TRUE(SetEndpointInCache(kGroupKey11_, kEndpoint2_, kExpires1_));
ASSERT_TRUE(SetEndpointInCache(kGroupKey21_, kEndpoint1_, kExpires1_));
ASSERT_TRUE(SetEndpointInCache(kGroupKey22_, kEndpoint2_, kExpires2_));
// Make kExpires1_ expired but not kExpires2_.
clock()->Advance(base::TimeDelta::FromDays(8));
ASSERT_GT(clock()->Now(), kExpires1_);
ASSERT_LT(clock()->Now(), kExpires2_);
std::vector<ReportingEndpoint> candidate_endpoints =
cache()->GetCandidateEndpointsForDelivery(kGroupKey11_);
ASSERT_EQ(0u, candidate_endpoints.size());
candidate_endpoints = cache()->GetCandidateEndpointsForDelivery(kGroupKey21_);
ASSERT_EQ(0u, candidate_endpoints.size());
candidate_endpoints = cache()->GetCandidateEndpointsForDelivery(kGroupKey22_);
ASSERT_EQ(1u, candidate_endpoints.size());
EXPECT_EQ(kEndpoint2_, candidate_endpoints[0].info.url);
}
TEST_P(ReportingCacheTest, ExcludeSubdomainsDifferentPort) {
LoadReportingClients();
const url::Origin kOrigin = url::Origin::Create(GURL("https://example/"));
const url::Origin kDifferentPortOrigin =
url::Origin::Create(GURL("https://example:444/"));
ASSERT_TRUE(SetEndpointInCache(
ReportingEndpointGroupKey(kNik_, kDifferentPortOrigin, kGroup1_),
kEndpoint1_, kExpires1_, OriginSubdomains::EXCLUDE));
std::vector<ReportingEndpoint> candidate_endpoints =
cache()->GetCandidateEndpointsForDelivery(
ReportingEndpointGroupKey(kNik_, kOrigin, kGroup1_));
ASSERT_EQ(0u, candidate_endpoints.size());
}
TEST_P(ReportingCacheTest, ExcludeSubdomainsSuperdomain) {
LoadReportingClients();
const url::Origin kOrigin = url::Origin::Create(GURL("https://foo.example/"));
const url::Origin kSuperOrigin =
url::Origin::Create(GURL("https://example/"));
ASSERT_TRUE(SetEndpointInCache(
ReportingEndpointGroupKey(kNik_, kSuperOrigin, kGroup1_), kEndpoint1_,
kExpires1_, OriginSubdomains::EXCLUDE));
std::vector<ReportingEndpoint> candidate_endpoints =
cache()->GetCandidateEndpointsForDelivery(
ReportingEndpointGroupKey(kNik_, kOrigin, kGroup1_));
ASSERT_EQ(0u, candidate_endpoints.size());
}
TEST_P(ReportingCacheTest, IncludeSubdomainsDifferentPort) {
LoadReportingClients();
const url::Origin kOrigin = url::Origin::Create(GURL("https://example/"));
const url::Origin kDifferentPortOrigin =
url::Origin::Create(GURL("https://example:444/"));
ASSERT_TRUE(SetEndpointInCache(
ReportingEndpointGroupKey(kNik_, kDifferentPortOrigin, kGroup1_),
kEndpoint1_, kExpires1_, OriginSubdomains::INCLUDE));
std::vector<ReportingEndpoint> candidate_endpoints =
cache()->GetCandidateEndpointsForDelivery(
ReportingEndpointGroupKey(kNik_, kOrigin, kGroup1_));
ASSERT_EQ(1u, candidate_endpoints.size());
EXPECT_EQ(kDifferentPortOrigin, candidate_endpoints[0].group_key.origin);
}
TEST_P(ReportingCacheTest, IncludeSubdomainsSuperdomain) {
LoadReportingClients();
const url::Origin kOrigin = url::Origin::Create(GURL("https://foo.example/"));
const url::Origin kSuperOrigin =
url::Origin::Create(GURL("https://example/"));
ASSERT_TRUE(SetEndpointInCache(
ReportingEndpointGroupKey(kNik_, kSuperOrigin, kGroup1_), kEndpoint1_,
kExpires1_, OriginSubdomains::INCLUDE));
std::vector<ReportingEndpoint> candidate_endpoints =
cache()->GetCandidateEndpointsForDelivery(
ReportingEndpointGroupKey(kNik_, kOrigin, kGroup1_));
ASSERT_EQ(1u, candidate_endpoints.size());
EXPECT_EQ(kSuperOrigin, candidate_endpoints[0].group_key.origin);
}
TEST_P(ReportingCacheTest, IncludeSubdomainsPreferOriginToDifferentPort) {
LoadReportingClients();
const url::Origin kOrigin = url::Origin::Create(GURL("https://foo.example/"));
const url::Origin kDifferentPortOrigin =
url::Origin::Create(GURL("https://example:444/"));
ASSERT_TRUE(
SetEndpointInCache(ReportingEndpointGroupKey(kNik_, kOrigin, kGroup1_),
kEndpoint1_, kExpires1_, OriginSubdomains::INCLUDE));
ASSERT_TRUE(SetEndpointInCache(
ReportingEndpointGroupKey(kNik_, kDifferentPortOrigin, kGroup1_),
kEndpoint1_, kExpires1_, OriginSubdomains::INCLUDE));
std::vector<ReportingEndpoint> candidate_endpoints =
cache()->GetCandidateEndpointsForDelivery(
ReportingEndpointGroupKey(kNik_, kOrigin, kGroup1_));
ASSERT_EQ(1u, candidate_endpoints.size());
EXPECT_EQ(kOrigin, candidate_endpoints[0].group_key.origin);
}
TEST_P(ReportingCacheTest, IncludeSubdomainsPreferOriginToSuperdomain) {
LoadReportingClients();
const url::Origin kOrigin = url::Origin::Create(GURL("https://foo.example/"));
const url::Origin kSuperOrigin =
url::Origin::Create(GURL("https://example/"));
ASSERT_TRUE(
SetEndpointInCache(ReportingEndpointGroupKey(kNik_, kOrigin, kGroup1_),
kEndpoint1_, kExpires1_, OriginSubdomains::INCLUDE));
ASSERT_TRUE(SetEndpointInCache(
ReportingEndpointGroupKey(kNik_, kSuperOrigin, kGroup1_), kEndpoint1_,
kExpires1_, OriginSubdomains::INCLUDE));
std::vector<ReportingEndpoint> candidate_endpoints =
cache()->GetCandidateEndpointsForDelivery(
ReportingEndpointGroupKey(kNik_, kOrigin, kGroup1_));
ASSERT_EQ(1u, candidate_endpoints.size());
EXPECT_EQ(kOrigin, candidate_endpoints[0].group_key.origin);
}
TEST_P(ReportingCacheTest, IncludeSubdomainsPreferMoreSpecificSuperdomain) {
LoadReportingClients();
const url::Origin kOrigin =
url::Origin::Create(GURL("https://foo.bar.example/"));
const url::Origin kSuperOrigin =
url::Origin::Create(GURL("https://bar.example/"));
const url::Origin kSuperSuperOrigin =
url::Origin::Create(GURL("https://example/"));
ASSERT_TRUE(SetEndpointInCache(
ReportingEndpointGroupKey(kNik_, kSuperOrigin, kGroup1_), kEndpoint1_,
kExpires1_, OriginSubdomains::INCLUDE));
ASSERT_TRUE(SetEndpointInCache(
ReportingEndpointGroupKey(kNik_, kSuperSuperOrigin, kGroup1_),
kEndpoint1_, kExpires1_, OriginSubdomains::INCLUDE));
std::vector<ReportingEndpoint> candidate_endpoints =
cache()->GetCandidateEndpointsForDelivery(
ReportingEndpointGroupKey(kNik_, kOrigin, kGroup1_));
ASSERT_EQ(1u, candidate_endpoints.size());
EXPECT_EQ(kSuperOrigin, candidate_endpoints[0].group_key.origin);
}
TEST_P(ReportingCacheTest, IncludeSubdomainsPreserveNik) {
LoadReportingClients();
const url::Origin kOrigin = url::Origin::Create(GURL("https://foo.example/"));
const url::Origin kSuperOrigin =
url::Origin::Create(GURL("https://example/"));
ASSERT_TRUE(SetEndpointInCache(
ReportingEndpointGroupKey(kNik_, kSuperOrigin, kGroup1_), kEndpoint1_,
kExpires1_, OriginSubdomains::INCLUDE));
ASSERT_TRUE(SetEndpointInCache(
ReportingEndpointGroupKey(kOtherNik_, kSuperOrigin, kGroup1_),
kEndpoint1_, kExpires1_, OriginSubdomains::INCLUDE));
std::vector<ReportingEndpoint> candidate_endpoints =
cache()->GetCandidateEndpointsForDelivery(
ReportingEndpointGroupKey(kOtherNik_, kOrigin, kGroup1_));
ASSERT_EQ(1u, candidate_endpoints.size());
EXPECT_EQ(kOtherNik_, candidate_endpoints[0].group_key.network_isolation_key);
}
TEST_P(ReportingCacheTest, EvictOldestReport) {
LoadReportingClients();
size_t max_report_count = policy().max_report_count;
ASSERT_LT(0u, max_report_count);
ASSERT_GT(std::numeric_limits<size_t>::max(), max_report_count);
base::TimeTicks earliest_queued = tick_clock()->NowTicks();
// Enqueue the maximum number of reports, spaced apart in time.
for (size_t i = 0; i < max_report_count; ++i) {
cache()->AddReport(kUrl1_, kUserAgent_, kGroup1_, kType_,
std::make_unique<base::DictionaryValue>(), 0,
tick_clock()->NowTicks(), 0);
tick_clock()->Advance(base::TimeDelta::FromMinutes(1));
}
EXPECT_EQ(max_report_count, report_count());
// Add one more report to force the cache to evict one.
cache()->AddReport(kUrl1_, kUserAgent_, kGroup1_, kType_,
std::make_unique<base::DictionaryValue>(), 0,
tick_clock()->NowTicks(), 0);
// Make sure the cache evicted a report to make room for the new one, and make
// sure the report evicted was the earliest-queued one.
std::vector<const ReportingReport*> reports;
cache()->GetReports(&reports);
EXPECT_EQ(max_report_count, reports.size());
for (const ReportingReport* report : reports)
EXPECT_NE(earliest_queued, report->queued);
}
TEST_P(ReportingCacheTest, DontEvictPendingReports) {
LoadReportingClients();
size_t max_report_count = policy().max_report_count;
ASSERT_LT(0u, max_report_count);
ASSERT_GT(std::numeric_limits<size_t>::max(), max_report_count);
// Enqueue the maximum number of reports, spaced apart in time.
std::vector<const ReportingReport*> reports;
for (size_t i = 0; i < max_report_count; ++i) {
reports.push_back(
AddAndReturnReport(kUrl1_, kUserAgent_, kGroup1_, kType_,
std::make_unique<base::DictionaryValue>(), 0,
tick_clock()->NowTicks(), 0));
tick_clock()->Advance(base::TimeDelta::FromMinutes(1));
}
EXPECT_EQ(max_report_count, report_count());
// Mark all of the queued reports pending.
EXPECT_THAT(cache()->GetReportsToDeliver(),
::testing::UnorderedElementsAreArray(reports));
// Add one more report to force the cache to evict one. Since the cache has
// only pending reports, it will be forced to evict the *new* report!
cache()->AddReport(kUrl1_, kUserAgent_, kGroup1_, kType_,
std::make_unique<base::DictionaryValue>(), 0, kNowTicks_,
0);
// Make sure the cache evicted a report, and make sure the report evicted was
// the new, non-pending one.
std::vector<const ReportingReport*> reports_after_eviction;
cache()->GetReports(&reports_after_eviction);
EXPECT_EQ(max_report_count, reports_after_eviction.size());
for (const ReportingReport* report : reports_after_eviction) {
EXPECT_TRUE(cache()->IsReportPendingForTesting(report));
}
EXPECT_THAT(reports_after_eviction,
::testing::UnorderedElementsAreArray(reports));
}
TEST_P(ReportingCacheTest, EvictEndpointsOverPerOriginLimit) {
LoadReportingClients();
for (size_t i = 0; i < policy().max_endpoints_per_origin; ++i) {
ASSERT_TRUE(SetEndpointInCache(kGroupKey11_, MakeURL(i), kExpires1_));
EXPECT_EQ(i + 1, cache()->GetEndpointCount());
}
EXPECT_EQ(policy().max_endpoints_per_origin, cache()->GetEndpointCount());
// Insert one more endpoint; eviction should be triggered.
SetEndpointInCache(kGroupKey11_, kEndpoint1_, kExpires1_);
EXPECT_EQ(policy().max_endpoints_per_origin, cache()->GetEndpointCount());
}
TEST_P(ReportingCacheTest, EvictExpiredGroups) {
LoadReportingClients();
for (size_t i = 0; i < policy().max_endpoints_per_origin; ++i) {
ASSERT_TRUE(SetEndpointInCache(kGroupKey11_, MakeURL(i), kExpires1_));
EXPECT_EQ(i + 1, cache()->GetEndpointCount());
}
EXPECT_EQ(policy().max_endpoints_per_origin, cache()->GetEndpointCount());
// Make the group expired (but not stale).
clock()->SetNow(kExpires1_ - base::TimeDelta::FromMinutes(1));
cache()->GetCandidateEndpointsForDelivery(kGroupKey11_);
clock()->SetNow(kExpires1_ + base::TimeDelta::FromMinutes(1));
// Insert one more endpoint in a different group (not expired); eviction
// should be triggered and the expired group should be deleted.
SetEndpointInCache(kGroupKey12_, kEndpoint1_, kExpires2_);
EXPECT_GE(policy().max_endpoints_per_origin, cache()->GetEndpointCount());
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
EXPECT_FALSE(
EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT));
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey12_, OriginSubdomains::DEFAULT));
}
TEST_P(ReportingCacheTest, EvictStaleGroups) {
LoadReportingClients();
for (size_t i = 0; i < policy().max_endpoints_per_origin; ++i) {
ASSERT_TRUE(SetEndpointInCache(kGroupKey11_, MakeURL(i), kExpires1_));
EXPECT_EQ(i + 1, cache()->GetEndpointCount());
}
EXPECT_EQ(policy().max_endpoints_per_origin, cache()->GetEndpointCount());
// Make the group stale (but not expired).
clock()->Advance(2 * policy().max_group_staleness);
ASSERT_LT(clock()->Now(), kExpires1_);
// Insert one more endpoint in a different group; eviction should be
// triggered and the stale group should be deleted.
SetEndpointInCache(kGroupKey12_, kEndpoint1_, kExpires1_);
EXPECT_GE(policy().max_endpoints_per_origin, cache()->GetEndpointCount());
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
EXPECT_FALSE(
EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT));
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey12_, OriginSubdomains::DEFAULT));
}
TEST_P(ReportingCacheTest, EvictFromStalestGroup) {
LoadReportingClients();
for (size_t i = 0; i < policy().max_endpoints_per_origin; ++i) {
ReportingEndpointGroupKey group_key(kNik_, kOrigin1_,
base::NumberToString(i));
ASSERT_TRUE(SetEndpointInCache(group_key, MakeURL(i), kExpires1_));
EXPECT_EQ(i + 1, cache()->GetEndpointCount());
EXPECT_TRUE(
EndpointGroupExistsInCache(group_key, OriginSubdomains::DEFAULT));
// Mark group used.
cache()->GetCandidateEndpointsForDelivery(group_key);
clock()->Advance(base::TimeDelta::FromMinutes(1));
}
EXPECT_EQ(policy().max_endpoints_per_origin, cache()->GetEndpointCount());
// Insert one more endpoint in a different group; eviction should be
// triggered and (only) the stalest group should be evicted from (and in this
// case deleted).
SetEndpointInCache(kGroupKey12_, kEndpoint1_, kExpires1_);
EXPECT_GE(policy().max_endpoints_per_origin, cache()->GetEndpointCount());
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
EXPECT_FALSE(EndpointGroupExistsInCache(
ReportingEndpointGroupKey(kNik_, kOrigin1_, "0"),
OriginSubdomains::DEFAULT));
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey12_, OriginSubdomains::DEFAULT));
for (size_t i = 1; i < policy().max_endpoints_per_origin; ++i) {
ReportingEndpointGroupKey group_key(kNik_, kOrigin1_,
base::NumberToString(i));
EXPECT_TRUE(
EndpointGroupExistsInCache(group_key, OriginSubdomains::DEFAULT));
}
}
TEST_P(ReportingCacheTest, EvictFromLargestGroup) {
LoadReportingClients();
ASSERT_TRUE(SetEndpointInCache(kGroupKey11_, MakeURL(0), kExpires1_));
// This group should be evicted from because it has 2 endpoints.
ASSERT_TRUE(SetEndpointInCache(kGroupKey12_, MakeURL(1), kExpires1_));
ASSERT_TRUE(SetEndpointInCache(kGroupKey12_, MakeURL(2), kExpires1_));
// max_endpoints_per_origin is set to 3.
ASSERT_EQ(policy().max_endpoints_per_origin, cache()->GetEndpointCount());
// Insert one more endpoint in a different group; eviction should be
// triggered.
SetEndpointInCache(ReportingEndpointGroupKey(kNik_, kOrigin1_, "default"),
kEndpoint1_, kExpires1_);
EXPECT_EQ(policy().max_endpoints_per_origin, cache()->GetEndpointCount());
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT));
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey12_, OriginSubdomains::DEFAULT));
// Count the number of endpoints remaining in kGroupKey12_.
std::vector<ReportingEndpoint> endpoints_in_group =
cache()->GetCandidateEndpointsForDelivery(kGroupKey12_);
EXPECT_EQ(1u, endpoints_in_group.size());
}
TEST_P(ReportingCacheTest, EvictLeastImportantEndpoint) {
LoadReportingClients();
ASSERT_TRUE(SetEndpointInCache(kGroupKey11_, MakeURL(0), kExpires1_,
OriginSubdomains::DEFAULT, 1 /* priority*/,
1 /* weight */));
ASSERT_TRUE(SetEndpointInCache(kGroupKey11_, MakeURL(1), kExpires1_,
OriginSubdomains::DEFAULT, 2 /* priority */,
2 /* weight */));
// This endpoint will be evicted because it is lowest priority and lowest
// weight.
ASSERT_TRUE(SetEndpointInCache(kGroupKey11_, MakeURL(2), kExpires1_,
OriginSubdomains::DEFAULT, 2 /* priority */,
1 /* weight */));
// max_endpoints_per_origin is set to 3.
ASSERT_EQ(policy().max_endpoints_per_origin, cache()->GetEndpointCount());
// Insert one more endpoint in a different group; eviction should be
// triggered and the least important endpoint should be deleted.
SetEndpointInCache(kGroupKey12_, kEndpoint1_, kExpires1_);
EXPECT_EQ(policy().max_endpoints_per_origin, cache()->GetEndpointCount());
EXPECT_TRUE(FindEndpointInCache(kGroupKey11_, MakeURL(0)));
EXPECT_TRUE(FindEndpointInCache(kGroupKey11_, MakeURL(1)));
EXPECT_FALSE(FindEndpointInCache(kGroupKey11_, MakeURL(2)));
EXPECT_TRUE(FindEndpointInCache(kGroupKey12_, kEndpoint1_));
}
TEST_P(ReportingCacheTest, EvictEndpointsOverGlobalLimitFromStalestClient) {
LoadReportingClients();
// Set enough endpoints to reach the global endpoint limit.
for (size_t i = 0; i < policy().max_endpoint_count; ++i) {
ReportingEndpointGroupKey group_key(kNik_, url::Origin::Create(MakeURL(i)),
kGroup1_);
ASSERT_TRUE(SetEndpointInCache(group_key, MakeURL(i), kExpires1_));
EXPECT_EQ(i + 1, cache()->GetEndpointCount());
clock()->Advance(base::TimeDelta::FromMinutes(1));
}
EXPECT_EQ(policy().max_endpoint_count, cache()->GetEndpointCount());
// Insert one more endpoint for a different origin; eviction should be
// triggered and the stalest client should be evicted from (and in this case
// deleted).
SetEndpointInCache(kGroupKey11_, kEndpoint1_, kExpires1_);
EXPECT_EQ(policy().max_endpoint_count, cache()->GetEndpointCount());
EXPECT_FALSE(ClientExistsInCacheForOrigin(url::Origin::Create(MakeURL(0))));
for (size_t i = 1; i < policy().max_endpoint_count; ++i) {
EXPECT_TRUE(ClientExistsInCacheForOrigin(url::Origin::Create(MakeURL(i))));
}
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
}
TEST_P(ReportingCacheTest, AddClientsLoadedFromStore) {
if (!store())
return;
base::Time now = clock()->Now();
std::vector<ReportingEndpoint> endpoints;
endpoints.emplace_back(kGroupKey11_,
ReportingEndpoint::EndpointInfo{kEndpoint1_});
endpoints.emplace_back(kGroupKey22_,
ReportingEndpoint::EndpointInfo{kEndpoint2_});
endpoints.emplace_back(kGroupKey11_,
ReportingEndpoint::EndpointInfo{kEndpoint2_});
endpoints.emplace_back(kGroupKey21_,
ReportingEndpoint::EndpointInfo{kEndpoint1_});
std::vector<CachedReportingEndpointGroup> groups;
groups.emplace_back(kGroupKey21_, OriginSubdomains::DEFAULT,
now + base::TimeDelta::FromMinutes(2) /* expires */,
now /* last_used */);
groups.emplace_back(kGroupKey11_, OriginSubdomains::DEFAULT,
now + base::TimeDelta::FromMinutes(1) /* expires */,
now /* last_used */);
groups.emplace_back(kGroupKey22_, OriginSubdomains::DEFAULT,
now + base::TimeDelta::FromMinutes(3) /* expires */,
now /* last_used */);
store()->SetPrestoredClients(endpoints, groups);
LoadReportingClients();
EXPECT_EQ(4u, cache()->GetEndpointCount());
EXPECT_EQ(3u, cache()->GetEndpointGroupCountForTesting());
EXPECT_TRUE(EndpointExistsInCache(kGroupKey11_, kEndpoint1_));
EXPECT_TRUE(EndpointExistsInCache(kGroupKey11_, kEndpoint2_));
EXPECT_TRUE(EndpointExistsInCache(kGroupKey21_, kEndpoint1_));
EXPECT_TRUE(EndpointExistsInCache(kGroupKey22_, kEndpoint2_));
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT,
now + base::TimeDelta::FromMinutes(1)));
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey21_, OriginSubdomains::DEFAULT,
now + base::TimeDelta::FromMinutes(2)));
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey22_, OriginSubdomains::DEFAULT,
now + base::TimeDelta::FromMinutes(3)));
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin2_));
}
TEST_P(ReportingCacheTest, AddStoredClientsWithDifferentNetworkIsolationKeys) {
if (!store())
return;
base::Time now = clock()->Now();
// This should create 4 different clients, for (2 origins) x (2 NIKs).
// Intentionally in a weird order to check sorting.
std::vector<ReportingEndpoint> endpoints;
endpoints.emplace_back(kGroupKey11_,
ReportingEndpoint::EndpointInfo{kEndpoint1_});
endpoints.emplace_back(kGroupKey21_,
ReportingEndpoint::EndpointInfo{kEndpoint1_});
endpoints.emplace_back(kOtherGroupKey21_,
ReportingEndpoint::EndpointInfo{kEndpoint1_});
endpoints.emplace_back(kOtherGroupKey11_,
ReportingEndpoint::EndpointInfo{kEndpoint1_});
std::vector<CachedReportingEndpointGroup> groups;
groups.emplace_back(kGroupKey21_, OriginSubdomains::DEFAULT,
now /* expires */, now /* last_used */);
groups.emplace_back(kOtherGroupKey21_, OriginSubdomains::DEFAULT,
now /* expires */, now /* last_used */);
groups.emplace_back(kOtherGroupKey11_, OriginSubdomains::DEFAULT,
now /* expires */, now /* last_used */);
groups.emplace_back(kGroupKey11_, OriginSubdomains::DEFAULT,
now /* expires */, now /* last_used */);
store()->SetPrestoredClients(endpoints, groups);
LoadReportingClients();
EXPECT_EQ(4u, cache()->GetEndpointCount());
EXPECT_EQ(4u, cache()->GetEndpointGroupCountForTesting());
EXPECT_EQ(4u, cache()->GetClientCountForTesting());
EXPECT_TRUE(EndpointExistsInCache(kGroupKey11_, kEndpoint1_));
EXPECT_TRUE(EndpointExistsInCache(kGroupKey21_, kEndpoint1_));
EXPECT_TRUE(EndpointExistsInCache(kOtherGroupKey11_, kEndpoint1_));
EXPECT_TRUE(EndpointExistsInCache(kOtherGroupKey21_, kEndpoint1_));
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT));
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey21_, OriginSubdomains::DEFAULT));
EXPECT_TRUE(
EndpointGroupExistsInCache(kOtherGroupKey11_, OriginSubdomains::DEFAULT));
EXPECT_TRUE(
EndpointGroupExistsInCache(kOtherGroupKey21_, OriginSubdomains::DEFAULT));
EXPECT_TRUE(cache()->ClientExistsForTesting(
kGroupKey11_.network_isolation_key, kGroupKey11_.origin));
EXPECT_TRUE(cache()->ClientExistsForTesting(
kGroupKey21_.network_isolation_key, kGroupKey21_.origin));
EXPECT_TRUE(cache()->ClientExistsForTesting(
kOtherGroupKey11_.network_isolation_key, kOtherGroupKey11_.origin));
EXPECT_TRUE(cache()->ClientExistsForTesting(
kOtherGroupKey21_.network_isolation_key, kOtherGroupKey21_.origin));
}
TEST_P(ReportingCacheTest, DoNotStoreMoreThanLimits) {
if (!store())
return;
base::Time now = clock()->Now();
// We hardcode the number of endpoints in this test, so we need to manually
// update the test when |max_endpoint_count| changes. You'll need to
// add/remove elements to |endpoints| when that happens.
EXPECT_EQ(5u, policy().max_endpoint_count) << "You need to update this test "
<< "to reflect a change in "
<< "max_endpoint_count";
std::vector<ReportingEndpoint> endpoints;
endpoints.emplace_back(kGroupKey11_,
ReportingEndpoint::EndpointInfo{kEndpoint1_});
endpoints.emplace_back(kGroupKey11_,
ReportingEndpoint::EndpointInfo{kEndpoint2_});
endpoints.emplace_back(kGroupKey11_,
ReportingEndpoint::EndpointInfo{kEndpoint3_});
endpoints.emplace_back(kGroupKey11_,
ReportingEndpoint::EndpointInfo{kEndpoint4_});
endpoints.emplace_back(kGroupKey22_,
ReportingEndpoint::EndpointInfo{kEndpoint1_});
endpoints.emplace_back(kGroupKey22_,
ReportingEndpoint::EndpointInfo{kEndpoint2_});
endpoints.emplace_back(kGroupKey22_,
ReportingEndpoint::EndpointInfo{kEndpoint3_});
endpoints.emplace_back(kGroupKey22_,
ReportingEndpoint::EndpointInfo{kEndpoint4_});
std::vector<CachedReportingEndpointGroup> groups;
groups.emplace_back(kGroupKey11_, OriginSubdomains::DEFAULT,
now /* expires */, now /* last_used */);
groups.emplace_back(kGroupKey22_, OriginSubdomains::DEFAULT,
now /* expires */, now /* last_used */);
store()->SetPrestoredClients(endpoints, groups);
LoadReportingClients();
EXPECT_GE(5u, cache()->GetEndpointCount());
EXPECT_GE(2u, cache()->GetEndpointGroupCountForTesting());
}
TEST_P(ReportingCacheTest, DoNotLoadMismatchedGroupsAndEndpoints) {
if (!store())
return;
base::Time now = clock()->Now();
std::vector<ReportingEndpoint> endpoints;
// This endpoint has no corresponding endpoint group
endpoints.emplace_back(kGroupKey11_,
ReportingEndpoint::EndpointInfo{kEndpoint1_});
endpoints.emplace_back(kGroupKey21_,
ReportingEndpoint::EndpointInfo{kEndpoint1_});
// This endpoint has no corresponding endpoint group
endpoints.emplace_back(kGroupKey22_,
ReportingEndpoint::EndpointInfo{kEndpoint1_});
std::vector<CachedReportingEndpointGroup> groups;
// This endpoint group has no corresponding endpoint
groups.emplace_back(kGroupKey12_, OriginSubdomains::DEFAULT,
now /* expires */, now /* last_used */);
groups.emplace_back(kGroupKey21_, OriginSubdomains::DEFAULT,
now /* expires */, now /* last_used */);
// This endpoint group has no corresponding endpoint
groups.emplace_back(ReportingEndpointGroupKey(kNik_, kOrigin2_, "last_group"),
OriginSubdomains::DEFAULT, now /* expires */,
now /* last_used */);
store()->SetPrestoredClients(endpoints, groups);
LoadReportingClients();
EXPECT_GE(1u, cache()->GetEndpointCount());
EXPECT_GE(1u, cache()->GetEndpointGroupCountForTesting());
EXPECT_TRUE(EndpointExistsInCache(kGroupKey21_, kEndpoint1_));
}
// This test verifies that we preserve the last_used field when storing clients
// loaded from disk. We don't have direct access into individual cache elements,
// so we test this indirectly by triggering a cache eviction and verifying that
// a stale element (i.e., one older than a week, by default) is selected for
// eviction. If last_used weren't populated then presumably that element
// wouldn't be evicted. (Or rather, it would only have a 25% chance of being
// evicted and this test would then be flaky.)
TEST_P(ReportingCacheTest, StoreLastUsedProperly) {
if (!store())
return;
base::Time now = clock()->Now();
// We hardcode the number of endpoints in this test, so we need to manually
// update the test when |max_endpoints_per_origin| changes. You'll need to
// add/remove elements to |endpoints| and |grups| when that happens.
EXPECT_EQ(3u, policy().max_endpoints_per_origin)
<< "You need to update this test to reflect a change in "
"max_endpoints_per_origin";
// We need more than three endpoints to trigger eviction.
std::vector<ReportingEndpoint> endpoints;
ReportingEndpointGroupKey group1(kNik_, kOrigin1_, "1");
ReportingEndpointGroupKey group2(kNik_, kOrigin1_, "2");
ReportingEndpointGroupKey group3(kNik_, kOrigin1_, "3");
ReportingEndpointGroupKey group4(kNik_, kOrigin1_, "4");
endpoints.emplace_back(group1, ReportingEndpoint::EndpointInfo{kEndpoint1_});
endpoints.emplace_back(group2, ReportingEndpoint::EndpointInfo{kEndpoint1_});
endpoints.emplace_back(group3, ReportingEndpoint::EndpointInfo{kEndpoint1_});
endpoints.emplace_back(group4, ReportingEndpoint::EndpointInfo{kEndpoint1_});
std::vector<CachedReportingEndpointGroup> groups;
groups.emplace_back(group1, OriginSubdomains::DEFAULT, now /* expires */,
now /* last_used */);
groups.emplace_back(group2, OriginSubdomains::DEFAULT, now /* expires */,
now /* last_used */);
// Stale last_used on group "3" should cause us to select it for eviction
groups.emplace_back(group3, OriginSubdomains::DEFAULT, now /* expires */,
base::Time() /* last_used */);
groups.emplace_back(group4, OriginSubdomains::DEFAULT, now /* expires */,
now /* last_used */);
store()->SetPrestoredClients(endpoints, groups);
LoadReportingClients();
EXPECT_TRUE(EndpointExistsInCache(group1, kEndpoint1_));
EXPECT_TRUE(EndpointExistsInCache(group2, kEndpoint1_));
EXPECT_FALSE(EndpointExistsInCache(group3, kEndpoint1_));
EXPECT_TRUE(EndpointExistsInCache(group4, kEndpoint1_));
}
INSTANTIATE_TEST_SUITE_P(ReportingCacheStoreTest,
ReportingCacheTest,
testing::Bool());
} // namespace
} // namespace net
| [
"[email protected]"
] | |
ce004c739357e2dcbef1e62b50351887967e4be6 | 38089ef195e9fa325bd4e193e7693d4ae9a9bb4b | /SuffixArray.cpp | 3fec2f835752aca51d7ac5407e687b669f939009 | [] | no_license | 1k2222/ACMTemplates | 1539ffed33f89760d396747809ff7dad3db4f0da | 0550c98a6f8722fafec859696a900d698b5d4459 | refs/heads/master | 2020-05-29T08:47:18.657100 | 2017-04-28T02:02:43 | 2017-04-28T02:02:43 | 69,145,063 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,991 | cpp | /*
需要自行定义的变量:
1. maxn:数据最大长度
2. N:当前数据长度
*/
struct SuffixArray
{
int bucket[maxn];
int sa[maxn];
int ran[maxn];
char str[maxn];
int tmp1[maxn], tmp2[maxn];
int height[maxn];
static inline bool cmp(int a, int b, int l, int *r)
{
if ((b + l >= N) || (a + l) >= N) return false;
return (r[a] == r[b]) && (r[a + l] == r[b + l]);
}
void getsa()
{
int i, j, t, p, *x = tmp1, *y = tmp2;
for (i = 0; i < N; ++i) sa[i] = str[i];
for (i = 0; i < M; ++i) bucket[i] = 0;
for (i = 0; i < N; ++i)
++bucket[str[i]];
for (i = 1; i < M; ++i) bucket[i] += bucket[i - 1];
for (i = 0; i < N; ++i) sa[--bucket[str[i]]] = i;
for (i = 1, p = 0, x[sa[0]] = 0; i < N; ++i)
x[sa[i]] = (str[sa[i]] == str[sa[i - 1]]) ? p : ++p;
j = 1;
for (j = 1; j < N; j <<= 1)
{
for (i = N - j, p = 0; i < N; ++i) y[p++] = i;
for (i = 0; i < N; ++i) if (sa[i] >= j) y[p++] = sa[i] - j;
for (i = 0; i < N; ++i) bucket[i] = 0;
for (i = 0; i < N; ++i) ++bucket[x[i]];
for (i = 1; i < N; ++i) bucket[i] += bucket[i - 1];
for (i = N - 1; i >= 0; --i) sa[--bucket[x[y[i]]]] = y[i];
swap(x, y);
for (i = 1, p = 0, x[sa[0]] = 0; i < N; ++i) x[sa[i]] = (cmp(sa[i], sa[i - 1], j, y)) ? p : ++p;
if (p == N - 1) break;
}
for (i = 0; i < N; ++i) ran[i] = x[i];
}
void getheight()
{
int i, h = 0;
for (i = 0; i < N; ++i)
if (ran[i] > 0)
{
while (str[i + h] == str[sa[ran[i] - 1] + h])
{
if (i + h >= N || sa[ran[i] - 1] + h >= N) break;
++h;
}
height[ran[i]] = h;
if (h > 0) --h;
}
}
void cal()
{
getsa();
getheight();
}
}; | [
"[email protected]"
] | |
0beb53194650a9405ec63392e2d91658bb481dd2 | 474a9dcd9f2038dd3e32cd6a98afe2670561580f | /CppWinThread1/CppWinThread1.cpp | 5f5922069f06d34c27a8b4653ae0403d480f984c | [] | no_license | Ams627/CppWinThread1 | 2c0340783e9757d58fc3cf8500a93e1d41a97706 | b93319658540a5f62df8adfdd9b252105f605702 | refs/heads/master | 2020-07-21T10:15:29.553560 | 2019-09-06T16:06:45 | 2019-09-06T16:06:45 | 206,830,093 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 190 | cpp | #include "stdafx.h"
DWORD WINAPI ThreadProc(LPVOID pParam)
{
std::cout << "test";
}
int main()
{
DWORD threadId;
auto handle = CreateThread(NULL, NULL, ThreadProc, 0, 0, &threadId)
}
| [
"[email protected]"
] | |
9069a5246f906a98f60aa033b32f9179acea63b3 | 5456502f97627278cbd6e16d002d50f1de3da7bb | /components/sync/base/mock_unrecoverable_error_handler.h | 4800e8949e2a978c26559548cbcd64bce0f61b6d | [
"BSD-3-Clause"
] | permissive | TrellixVulnTeam/Chromium_7C66 | 72d108a413909eb3bd36c73a6c2f98de1573b6e5 | c8649ab2a0f5a747369ed50351209a42f59672ee | refs/heads/master | 2023-03-16T12:51:40.231959 | 2017-12-20T10:38:26 | 2017-12-20T10:38:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,326 | h | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_SYNC_BASE_MOCK_UNRECOVERABLE_ERROR_HANDLER_H_
#define COMPONENTS_SYNC_BASE_MOCK_UNRECOVERABLE_ERROR_HANDLER_H_
#include <string>
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "components/sync/base/unrecoverable_error_handler.h"
namespace syncer {
// Mock implementation of UnrecoverableErrorHandler that counts how many times
// it has been invoked.
class MockUnrecoverableErrorHandler : public UnrecoverableErrorHandler {
public:
MockUnrecoverableErrorHandler();
~MockUnrecoverableErrorHandler() override;
void OnUnrecoverableError(const tracked_objects::Location& from_here,
const std::string& message) override;
// Returns the number of times this handler has been invoked.
int invocation_count() const;
base::WeakPtr<MockUnrecoverableErrorHandler> GetWeakPtr();
private:
int invocation_count_;
base::WeakPtrFactory<MockUnrecoverableErrorHandler> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(MockUnrecoverableErrorHandler);
};
} // namespace syncer
#endif // COMPONENTS_SYNC_BASE_MOCK_UNRECOVERABLE_ERROR_HANDLER_H_
| [
"[email protected]"
] | |
c3f5ab73c1b845a61eac3a8751057a3bfb55a904 | f019ca1e4029b4077472087d1b677052583c0392 | /src/qt/addressbookpage.cpp | ef93d21f6849378ed62910b504299313982ebd82 | [
"MIT"
] | permissive | mirzaei-ce/core-civilbit | 9204dd9c4c3ce04f867105da4e7fa9a56af1f8ba | cab3e53bdc6b04a84f4bc48114efc07865be814a | refs/heads/master | 2021-04-26T05:03:32.282526 | 2017-10-16T15:39:44 | 2017-10-16T15:39:44 | 107,148,188 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,110 | cpp | // Copyright (c) 2011-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/civilbit-config.h"
#endif
#include "addressbookpage.h"
#include "ui_addressbookpage.h"
#include "addresstablemodel.h"
#include "civilbitgui.h"
#include "csvmodelwriter.h"
#include "editaddressdialog.h"
#include "guiutil.h"
#include "platformstyle.h"
#include <QIcon>
#include <QMenu>
#include <QMessageBox>
#include <QSortFilterProxyModel>
AddressBookPage::AddressBookPage(const PlatformStyle *platformStyle, Mode mode, Tabs tab, QWidget *parent) :
QDialog(parent),
ui(new Ui::AddressBookPage),
model(0),
mode(mode),
tab(tab)
{
ui->setupUi(this);
if (!platformStyle->getImagesOnButtons()) {
ui->newAddress->setIcon(QIcon());
ui->copyAddress->setIcon(QIcon());
ui->deleteAddress->setIcon(QIcon());
ui->exportButton->setIcon(QIcon());
} else {
ui->newAddress->setIcon(platformStyle->SingleColorIcon(":/icons/add"));
ui->copyAddress->setIcon(platformStyle->SingleColorIcon(":/icons/editcopy"));
ui->deleteAddress->setIcon(platformStyle->SingleColorIcon(":/icons/remove"));
ui->exportButton->setIcon(platformStyle->SingleColorIcon(":/icons/export"));
}
switch(mode)
{
case ForSelection:
switch(tab)
{
case SendingTab: setWindowTitle(tr("Choose the address to send coins to")); break;
case ReceivingTab: setWindowTitle(tr("Choose the address to receive coins with")); break;
}
connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept()));
ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->tableView->setFocus();
ui->closeButton->setText(tr("C&hoose"));
ui->exportButton->hide();
break;
case ForEditing:
switch(tab)
{
case SendingTab: setWindowTitle(tr("Sending addresses")); break;
case ReceivingTab: setWindowTitle(tr("Receiving addresses")); break;
}
break;
}
switch(tab)
{
case SendingTab:
ui->labelExplanation->setText(tr("These are your Civilbit addresses for sending payments. Always check the amount and the receiving address before sending coins."));
ui->deleteAddress->setVisible(true);
break;
case ReceivingTab:
ui->labelExplanation->setText(tr("These are your Civilbit addresses for receiving payments. It is recommended to use a new receiving address for each transaction."));
ui->deleteAddress->setVisible(false);
break;
}
// Context menu actions
QAction *copyAddressAction = new QAction(tr("&Copy Address"), this);
QAction *copyLabelAction = new QAction(tr("Copy &Label"), this);
QAction *editAction = new QAction(tr("&Edit"), this);
deleteAction = new QAction(ui->deleteAddress->text(), this);
// Build context menu
contextMenu = new QMenu();
contextMenu->addAction(copyAddressAction);
contextMenu->addAction(copyLabelAction);
contextMenu->addAction(editAction);
if(tab == SendingTab)
contextMenu->addAction(deleteAction);
contextMenu->addSeparator();
// Connect signals for context menu actions
connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyAddress_clicked()));
connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction()));
connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction()));
connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteAddress_clicked()));
connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint)));
connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(accept()));
}
AddressBookPage::~AddressBookPage()
{
delete ui;
}
void AddressBookPage::setModel(AddressTableModel *model)
{
this->model = model;
if(!model)
return;
proxyModel = new QSortFilterProxyModel(this);
proxyModel->setSourceModel(model);
proxyModel->setDynamicSortFilter(true);
proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
switch(tab)
{
case ReceivingTab:
// Receive filter
proxyModel->setFilterRole(AddressTableModel::TypeRole);
proxyModel->setFilterFixedString(AddressTableModel::Receive);
break;
case SendingTab:
// Send filter
proxyModel->setFilterRole(AddressTableModel::TypeRole);
proxyModel->setFilterFixedString(AddressTableModel::Send);
break;
}
ui->tableView->setModel(proxyModel);
ui->tableView->sortByColumn(0, Qt::AscendingOrder);
// Set column widths
#if QT_VERSION < 0x050000
ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Label, QHeaderView::Stretch);
ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents);
#else
ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Label, QHeaderView::Stretch);
ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents);
#endif
connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
this, SLOT(selectionChanged()));
// Select row for newly created address
connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(selectNewAddress(QModelIndex,int,int)));
selectionChanged();
}
void AddressBookPage::on_copyAddress_clicked()
{
GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Address);
}
void AddressBookPage::onCopyLabelAction()
{
GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Label);
}
void AddressBookPage::onEditAction()
{
if(!model)
return;
if(!ui->tableView->selectionModel())
return;
QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows();
if(indexes.isEmpty())
return;
EditAddressDialog dlg(
tab == SendingTab ?
EditAddressDialog::EditSendingAddress :
EditAddressDialog::EditReceivingAddress, this);
dlg.setModel(model);
QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0));
dlg.loadRow(origIndex.row());
dlg.exec();
}
void AddressBookPage::on_newAddress_clicked()
{
if(!model)
return;
EditAddressDialog dlg(
tab == SendingTab ?
EditAddressDialog::NewSendingAddress :
EditAddressDialog::NewReceivingAddress, this);
dlg.setModel(model);
if(dlg.exec())
{
newAddressToSelect = dlg.getAddress();
}
}
void AddressBookPage::on_deleteAddress_clicked()
{
QTableView *table = ui->tableView;
if(!table->selectionModel())
return;
QModelIndexList indexes = table->selectionModel()->selectedRows();
if(!indexes.isEmpty())
{
table->model()->removeRow(indexes.at(0).row());
}
}
void AddressBookPage::selectionChanged()
{
// Set button states based on selected tab and selection
QTableView *table = ui->tableView;
if(!table->selectionModel())
return;
if(table->selectionModel()->hasSelection())
{
switch(tab)
{
case SendingTab:
// In sending tab, allow deletion of selection
ui->deleteAddress->setEnabled(true);
ui->deleteAddress->setVisible(true);
deleteAction->setEnabled(true);
break;
case ReceivingTab:
// Deleting receiving addresses, however, is not allowed
ui->deleteAddress->setEnabled(false);
ui->deleteAddress->setVisible(false);
deleteAction->setEnabled(false);
break;
}
ui->copyAddress->setEnabled(true);
}
else
{
ui->deleteAddress->setEnabled(false);
ui->copyAddress->setEnabled(false);
}
}
void AddressBookPage::done(int retval)
{
QTableView *table = ui->tableView;
if(!table->selectionModel() || !table->model())
return;
// Figure out which address was selected, and return it
QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address);
Q_FOREACH (const QModelIndex& index, indexes) {
QVariant address = table->model()->data(index);
returnValue = address.toString();
}
if(returnValue.isEmpty())
{
// If no address entry selected, return rejected
retval = Rejected;
}
QDialog::done(retval);
}
void AddressBookPage::on_exportButton_clicked()
{
// CSV is currently the only supported format
QString filename = GUIUtil::getSaveFileName(this,
tr("Export Address List"), QString(),
tr("Comma separated file (*.csv)"), NULL);
if (filename.isNull())
return;
CSVModelWriter writer(filename);
// name, column, role
writer.setModel(proxyModel);
writer.addColumn("Label", AddressTableModel::Label, Qt::EditRole);
writer.addColumn("Address", AddressTableModel::Address, Qt::EditRole);
if(!writer.write()) {
QMessageBox::critical(this, tr("Exporting Failed"),
tr("There was an error trying to save the address list to %1. Please try again.").arg(filename));
}
}
void AddressBookPage::contextualMenu(const QPoint &point)
{
QModelIndex index = ui->tableView->indexAt(point);
if(index.isValid())
{
contextMenu->exec(QCursor::pos());
}
}
void AddressBookPage::selectNewAddress(const QModelIndex &parent, int begin, int /*end*/)
{
QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AddressTableModel::Address, parent));
if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect))
{
// Select row of newly created address, once
ui->tableView->setFocus();
ui->tableView->selectRow(idx.row());
newAddressToSelect.clear();
}
}
| [
"[email protected]"
] | |
e46e9d0e54866c058dd88728cdae69f2a877fad1 | 2dc9d0346eec290af664004910a3473d9dfd20e2 | /src/client2_app.cc | e07532593c9de5d765ae0c676421a30d9823abe4 | [] | no_license | alvas/jerryfish | a9412093c0e932a6c7f69cc5237409823310bec6 | c0866836f094e8072fd6cabda44807ec824b4113 | refs/heads/master | 2020-07-11T19:21:37.405515 | 2019-10-06T18:27:12 | 2019-10-06T18:27:12 | 204,625,265 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 528 | cc | /*
* client2_app.cpp
* Copyright (C) 2019 qingyun <[email protected]>
*
* Distributed under terms of the MIT license.
*/
//#include "client2_app.h"
#include "client2.hpp"
#include <string>
using namespace JerryFish;
std::string fileName;
std::string fileName2("./test/test1.json");
int main(int argc, char** argv)
{
int num = 2;
if (argc > 1 && atoi(argv[1]) > 0)
{
num = atoi(argv[1]);
}
Client client(num);
client.ReadTasks(fileName);
client.Run();
return 0;
}
| [
"[email protected]"
] | |
5523039c9d2f1153f2a12233ab4752e461335753 | 050c8a810d34fe125aecae582f9adfd0625356c6 | /gift/main.cpp | 0e1a07d7de843f4e01c4842f68c8d632692d62b2 | [] | 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 | 412 | cpp | #include <cstdio>
#define MOD 1000000007
using namespace std;
int dp[2000005];
int N,K;
void fix(int &val)
{
if(val>=MOD)val-=MOD;
if(val<0)val+=MOD;
}
int main()
{
scanf("%d%d",&N,&K);
dp[0]=1;
for(int i=1;i<=N;i++)
{
dp[i]=dp[i-1];
fix(dp[i]-=(i-K-1>=0 ? dp[i-K-1]:0));
fix(dp[i]+=dp[i-1]);
}
fix(dp[N]-=dp[N-1]);
printf("%d",dp[N]);
return 0;
}
| [
"[email protected]"
] | |
5acec7c16759584589029eb19882c49966dca126 | 022d99a325a0291fd123d54b714cd7d79d6a637c | /src/gameEngine/encapsulation/CheckBox.cpp | 4f0a8521ddd907c6dcec860eab0ea6f03b86be17 | [] | no_license | polBachelin/BomberVerse | 160bfe8648f1e75b80b36ca4eb6e336cb7dd75cb | 29ebe562751b7aeabde6c2d2481d655d9548e09b | refs/heads/master | 2023-09-02T13:09:11.339868 | 2021-06-21T08:32:05 | 2021-06-21T08:32:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,640 | cpp | /*
** EPITECH PROJECT, 2021
** B-YEP-400-REN-4-1-indiestudio-pol.bachelin
** File description:
** CheckBox
*/
#include "CheckBox.hpp"
using namespace gameEngine::object;
CheckBox::CheckBox(const Vector<float> &size,
const Vector<float> &pos,
const encapsulation::BText &content,
const encapsulation::BColor &color,
const encapsulation::BColor &selectColor,
bool initState,
const encapsulation::BColor &trueColor,
const encapsulation::BColor &falseColor
)
: AButton(size, pos, content, color, selectColor)
{
_checkState = initState;
_trueColor = trueColor;
_falseColor = falseColor;
initCheckRect();
initText();
}
CheckBox::~CheckBox()
{
}
//-----------------
void CheckBox::initText() noexcept
{
Vector<float> pos = (*_content).getTextPosition();
pos._x += _rectangle.get()->setTransform()._position._x;
pos._y += _rectangle.get()->setTransform()._position._y;
float rect_height = _rectangle.get()->setTransform()._scale._y;
float rect_width = _rectangle.get()->setTransform()._scale._x;
float size = (rect_height * 20) / 100;
pos._y += ((rect_height / 2 ) - (size / 2));
pos._x += (rect_width * 10) / 100;
(*_content).setTextSize(size);
(*_content).setTextPosition(pos);
}
void CheckBox::initCheckRect() noexcept
{
Vector3T<float> size{_rectangle.get()->setTransform()._scale};
Vector3T<float> pos{_rectangle.get()->setTransform()._position};
pos._x += size._x;
pos._y += size._y;
size._y = (size._y * 90) / 100;
size._x = (size._x * 20) / 100;
float padding = (_rectangle.get()->setTransform()._scale._y - size._y) / 2;
pos._x -= (size._x + padding);
pos._y -= (size._y + padding);
_checkRect.setTransform().setPosition(pos);
_checkRect.setTransform().setScale(size);
setCheckRectColor();
}
void CheckBox::setCheckRectColor() noexcept
{
if (_checkState) {
_checkRect.setColor(_trueColor);
} else {
_checkRect.setColor(_falseColor);
}
}
//getter
bool CheckBox::getState() const noexcept
{
return _checkState;
}
void CheckBox::draw()
{
this->AButton::draw();
this->AButton::drawOutline();
_checkRect.draw();
}
void CheckBox::toggleState() noexcept
{
if (_checkState)
_checkState = false;
else
_checkState = true;
}
bool CheckBox::isButtonReleased()
{
bool ret = this->AButton::isButtonReleased();
if (ret)
toggleState();
setCheckRectColor();
return ret;
}
| [
"[email protected]"
] | |
e63bf350aa2f960d536d531b15251c161cf2e6ef | 2124d0b0d00c3038924f5d2ad3fe14b35a1b8644 | /source/GamosCore/GamosScoring/Scorers/src/GmPSRBEPhenom_Carabe.cc | 4d917ee0095aa9606c17e7bec917a91493d1c0e0 | [] | no_license | arceciemat/GAMOS | 2f3059e8b0992e217aaf98b8591ef725ad654763 | 7db8bd6d1846733387b6cc946945f0821567662b | refs/heads/master | 2023-07-08T13:31:01.021905 | 2023-06-26T10:57:43 | 2023-06-26T10:57:43 | 21,818,258 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,907 | cc | #include "GmPSRBEPhenom_Carabe.hh"
#include "G4UnitsTable.hh"
#include "G4EmCalculator.hh"
#include "GamosCore/GamosScoring/Management/include/GmScoringVerbosity.hh"
//--------------------------------------------------------------------
GmPSRBEPhenom_Carabe::GmPSRBEPhenom_Carabe(G4String name)
:GmVPrimitiveScorer(name),GmComputeRBEPhenom(name)
{
theUnit = 1.;
theUnitName = G4String("");
// new G4EmCalculator;
}
//--------------------------------------------------------------------
GmPSRBEPhenom_Carabe::~GmPSRBEPhenom_Carabe()
{;}
//--------------------------------------------------------------------
G4double GmPSRBEPhenom_Carabe::GetRBEMin( G4double LETd, G4double alphaBetaX )
{
G4double rbeMin = 1.09 + 0.01612 * LETd/alphaBetaX;
if( ScoringVerb(debugVerb) ) G4cout << " GmPSRBEPhenom_Carabe::GetRBEMin " << rbeMin << G4endl;
return rbeMin;
}
//--------------------------------------------------------------------
G4double GmPSRBEPhenom_Carabe::GetRBEMax( G4double LETd, G4double alphaBetaX )
{
G4double rbeMax = 0.843 + 0.413644 * LETd/alphaBetaX;
if( ScoringVerb(debugVerb) ) G4cout << " GmPSRBEPhenom_Carabe::GetRBEMax " << rbeMax << G4endl;
return rbeMax;
}
//--------------------------------------------------------------------
G4bool GmPSRBEPhenom_Carabe::ProcessHits(G4Step* aStep,G4TouchableHistory*)
{
if( aStep == 0 ) return FALSE; // it is 0 when called by GmScoringMgr after last event
if( !AcceptByFilter( aStep ) ) return false;
G4double edep = aStep->GetTotalEnergyDeposit();
if ( edep == 0. ) return FALSE;
G4double rbe = GetRBE(aStep);
G4double weight = aStep->GetPreStepPoint()->GetWeight();
#ifndef GAMOS_NO_VERBOSE
if( ScoringVerb(debugVerb) )
G4cout << " GmPSRBEPhenom_Carabe::ProcessHits rbe " << rbe
<< G4endl;
#endif
G4int index = GetIndex(aStep);
FillScorer( aStep, index, rbe, weight );
return TRUE;
}
| [
"[email protected]"
] | |
c3523aaec6c97e5a804b45c31cb09dd0cdd4876c | 492f3f0bfa78c1d6cdf4a9ed4c85ba31fa1e58c7 | /src/bgkoctomap/cassie_node.cpp | a53502dcde6102bacebbfc32394f458d55859bfb | [] | no_license | DrZhouKarl/MultilayerMapping | dbdbf30acdbd77861ae35e8360c326ae87fa4a5d | a9b6d6010470f8062bfd2feee2bd785e8a19957c | refs/heads/master | 2023-04-13T14:04:17.662217 | 2021-04-27T01:20:44 | 2021-04-27T01:20:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,958 | cpp | #include <string>
#include <iostream>
#include <ros/ros.h>
#include "bgkoctomap.h"
#include "markerarray_pub.h"
#include "cassie_util.h"
int main(int argc, char **argv) {
ros::init(argc, argv, "cassie_node");
ros::NodeHandle nh("~");
int num_class = 2;
std::string static_frame("/odom");
std::string dir;
std::string prefix;
int scan_num = 0;
std::string map_topic("/semantic_map");
std::string traversability_map_topic("/traversability_map");
double max_range = -1;
double resolution = 0.1;
int block_depth = 4;
double sf2 = 1.0;
double ell = 1.0;
double free_resolution = 0.5;
double ds_resolution = 0.1;
double free_thresh = 0.3;
double occupied_thresh = 0.7;
double min_z = 0;
double max_z = 0;
bool original_size = false;
float var_thresh = 1.0f;
float prior_A = 1.0f;
float prior_B = 1.0f;
float prior = 1.0f;
nh.param<int>("num_class", num_class, num_class);
nh.param<std::string>("static_frame", static_frame, static_frame);
nh.param<std::string>("dir", dir, dir);
nh.param<std::string>("prefix", prefix, prefix);
nh.param<std::string>("topic", map_topic, map_topic);
nh.param<int>("scan_num", scan_num, scan_num);
nh.param<double>("max_range", max_range, max_range);
nh.param<double>("resolution", resolution, resolution);
nh.param<int>("block_depth", block_depth, block_depth);
nh.param<double>("sf2", sf2, sf2);
nh.param<double>("ell", ell, ell);
nh.param<double>("free_resolution", free_resolution, free_resolution);
nh.param<double>("ds_resolution", ds_resolution, ds_resolution);
nh.param<double>("free_thresh", free_thresh, free_thresh);
nh.param<double>("occupied_thresh", occupied_thresh, occupied_thresh);
nh.param<double>("min_z", min_z, min_z);
nh.param<double>("max_z", max_z, max_z);
nh.param<bool>("original_size", original_size, original_size);
nh.param<float>("var_thresh", var_thresh, var_thresh);
nh.param<float>("prior_A", prior_A, prior_A);
nh.param<float>("prior_B", prior_B, prior_B);
nh.param<float>("prior", prior, prior);
ROS_INFO_STREAM("Parameters:" << std::endl <<
"num_class: " << num_class << std::endl <<
"static_frame: " << static_frame << std::endl <<
"dir: " << dir << std::endl <<
"prefix: " << prefix << std::endl <<
"topic: " << map_topic << std::endl <<
"scan_sum: " << scan_num << std::endl <<
"max_range: " << max_range << std::endl <<
"resolution: " << resolution << std::endl <<
"block_depth: " << block_depth << std::endl <<
"sf2: " << sf2 << std::endl <<
"ell: " << ell << std::endl <<
"free_resolution: " << free_resolution << std::endl <<
"ds_resolution: " << ds_resolution << std::endl <<
"free_thresh: " << free_thresh << std::endl <<
"occupied_thresh: " << occupied_thresh << std::endl <<
"min_z: " << min_z << std::endl <<
"max_z: " << max_z << std::endl <<
"original_size: " << original_size << std::endl <<
"var_thresh: " << var_thresh << std::endl <<
"prior_A: " << prior_A << std::endl <<
"prior_B: " << prior_B << std::endl <<
"prior: " << prior
);
CassieData cassie_data(nh, static_frame, map_topic, traversability_map_topic,
resolution, block_depth, num_class,
sf2, ell, free_thresh, occupied_thresh, var_thresh,
prior_A, prior_B, prior,
ds_resolution, free_resolution, max_range);
ros::Subscriber ssub = nh.subscribe("/labeled_pointcloud", 1, &CassieData::SemanticPointCloudCallback, &cassie_data);
ros::Subscriber tsub = nh.subscribe("/labeled_pointcloud_traversability", 1, &CassieData::TraversabilityPointCloudCallback, &cassie_data);
ros::spin();
return 0;
}
| [
"[email protected]"
] | |
7f898271c7189e5f1bb9fa422ff3585d78c20288 | 4fc9d5d49b9d0c9a8aec35e02418230c4a439bf7 | /Include/Mathematics/GteIntrRay2Circle2.h | 47eb8b9223b1bed6c82ba09484c4753556b270e3 | [] | no_license | zhouxs1023/GTEngine | 07d8a299522a8b33b6960dca06a4ca6cb459622c | 16c1af003106798dd2d91800085818b40adfad1a | refs/heads/master | 2020-03-27T18:03:37.798691 | 2019-12-30T13:49:17 | 2019-12-30T13:49:17 | 146,895,580 | 9 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 2,951 | h | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2019
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// File Version: 3.0.0 (2016/06/19)
#pragma once
#include <Mathematics/GteRay.h>
#include <Mathematics/GteIntrIntervals.h>
#include <Mathematics/GteIntrLine2Circle2.h>
// The queries consider the circle to be a solid (disk).
namespace gte
{
template <typename Real>
class TIQuery<Real, Ray2<Real>, Circle2<Real>>
{
public:
struct Result
{
bool intersect;
};
Result operator()(Ray2<Real> const& ray, Circle2<Real> const& circle);
};
template <typename Real>
class FIQuery<Real, Ray2<Real>, Circle2<Real>>
:
public FIQuery<Real, Line2<Real>, Circle2<Real>>
{
public:
struct Result
:
public FIQuery<Real, Line2<Real>, Circle2<Real>>::Result
{
// No additional information to compute.
};
Result operator()(Ray2<Real> const& ray, Circle2<Real> const& circle);
protected:
void DoQuery(Vector2<Real> const& rayOrigin,
Vector2<Real> const& rayDirection, Circle2<Real> const& circle,
Result& result);
};
template <typename Real>
typename TIQuery<Real, Ray2<Real>, Circle2<Real>>::Result
TIQuery<Real, Ray2<Real>, Circle2<Real>>::operator()(
Ray2<Real> const& ray, Circle2<Real> const& circle)
{
Result result;
FIQuery<Real, Ray2<Real>, Circle2<Real>> rcQuery;
result.intersect = rcQuery(ray, circle).intersect;
return result;
}
template <typename Real>
typename FIQuery<Real, Ray2<Real>, Circle2<Real>>::Result
FIQuery<Real, Ray2<Real>, Circle2<Real>>::operator()(
Ray2<Real> const& ray, Circle2<Real> const& circle)
{
Result result;
DoQuery(ray.origin, ray.direction, circle, result);
for (int i = 0; i < result.numIntersections; ++i)
{
result.point[i] = ray.origin + result.parameter[i] * ray.direction;
}
return result;
}
template <typename Real>
void FIQuery<Real, Ray2<Real>, Circle2<Real>>::DoQuery(
Vector2<Real> const& rayOrigin, Vector2<Real> const& rayDirection,
Circle2<Real> const& circle, Result& result)
{
FIQuery<Real, Line2<Real>, Circle2<Real>>::DoQuery(rayOrigin,
rayDirection, circle, result);
if (result.intersect)
{
// The line containing the ray intersects the disk; the t-interval is
// [t0,t1]. The ray intersects the disk as long as [t0,t1] overlaps
// the ray t-interval [0,+infinity).
std::array<Real, 2> rayInterval = { (Real)0, std::numeric_limits<Real>::max() };
FIQuery<Real, std::array<Real, 2>, std::array<Real, 2>> iiQuery;
auto iiResult = iiQuery(result.parameter, rayInterval);
result.intersect = iiResult.intersect;
result.numIntersections = iiResult.numIntersections;
result.parameter = iiResult.overlap;
}
}
}
| [
"[email protected]"
] | |
6de42cd7d8622f2be398dda3044b91bab6f791c2 | 1ef5a27c9326065db448dd539810e900cae9460d | /Classes/Round034_03.cpp | 078b1c44c2ff5a9cbd6291bffbc10434453e9676 | [] | no_license | langtuandroid/SuperBaby | c4e3f7faaa82d40c8da0f518b71251a8ff466c2f | 957a5202ba7d1078bdcfb6b0cd6b73a966893efe | refs/heads/master | 2021-01-06T20:43:54.083245 | 2017-06-18T14:19:00 | 2017-06-18T14:19:00 | 99,549,410 | 0 | 1 | null | 2017-08-07T07:25:29 | 2017-08-07T07:25:29 | null | UTF-8 | C++ | false | false | 9,016 | cpp | //
// Round034_03.cpp
// superBaby
//
// Created by Administrator on 15/6/23.
//
//
#include "Round034_03.h"
#include "Player.h"
#include "StageScene.h"
#include "StageData.h"
#include "Actor.h"
#include "MyAudioEngine.h"
#include "RoundUINode.h"
// 庆祝延时
#define CELEBRATE_DELAY 5.0f
#define PAOPAO_GAF_FILE "res/stage028/HY-GK-paopao01/HY-GK-paopao01.gaf"
#define PAOPAO_GAF_POS Vec2(818,868)
#define PAOPAO_GAF_ZORDER 1
#define WHITELIGHT_GAF_FILE "res/stage028/HY-GK-guang/HY-GK-guang.gaf"
#define WHITELIGHT_GAF_POS Vec2(518,868)
#define WHITELIGHT_GAF_ZORDER 1
#define ANCHORS_ZORDER 2
#define ROPE_ZORDER 3
/*
* constructor
*/
Round034_03::Round034_03() {
m_nodesPos[0] = Vec2(605, 700);
m_nodesPos[1] = Vec2(907, 710);
m_nodesPos[2] = Vec2(1210, 711);
m_ropesPos[0] = Vec2(189, 441);
m_ropesPos[1] = Vec2(189, 441);
m_ropesPos[2] = Vec2(169, 441);
m_anchorsPos[0] = Vec2(125, 340);
m_anchorsPos[1] = Vec2(151, 340);
m_anchorsPos[2] = Vec2(153, 340);
}
/*
* destructor
*/
Round034_03::~Round034_03()
{
cleanUp();
}
//
void Round034_03::cleanUp()
{
auto dispatcher = Director::getInstance()->getEventDispatcher();
dispatcher->removeCustomEventListeners("openTouch");
dispatcher->removeCustomEventListeners("endRound");
}
//
Round034_03* Round034_03::createWithRoundIndex(const int roundIndex, StageScene* pStageScene, const Vec2& pos)
{
auto pRound = new Round034_03();
if (pRound && pRound->initWithRoundIndex(roundIndex, pStageScene,pos))
{
pRound->autorelease();
} else {
CC_SAFE_DELETE(pRound);
}
return pRound;
}
/*
* 初始化
*/
bool Round034_03::initWithRoundIndex(const int roundIndex, StageScene* pStageScene, const Vec2& pos)
{
m_roundIndex = roundIndex;
m_pStageScene = pStageScene;
setAnchorPoint(Vec2::ZERO);
setPosition(pos);
m_pPaopaoActor = Actor::createWithGafFile(PAOPAO_GAF_FILE);
m_pPaopaoActor->setPosition(PAOPAO_GAF_POS);
this->addChild(m_pPaopaoActor, PAOPAO_GAF_ZORDER);
m_pWhiteLightActor = Actor::createWithGafFile(WHITELIGHT_GAF_FILE);
m_pWhiteLightActor->setPosition(WHITELIGHT_GAF_POS);
m_pWhiteLightActor->setSize(Size(300, 300));
m_pWhiteLightActor->setPosAtNode(Vec2(-300, 400));
this->addChild(m_pWhiteLightActor, WHITELIGHT_GAF_ZORDER);
for (unsigned long i = 0; i < 3; i++) {
m_pNodes[i] = LayerColor::create(Color4B(255, 255, 255, 0), 300, 600);
m_pNodes[i]->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
m_pNodes[i]->setUserData((void*)i);
this->addChild(m_pNodes[i]);
}
char buffer[64];
for (unsigned long i = 0; i < 3; i++) {
sprintf(buffer, "HY-GK10-2-TM%02ld.png",i+2);
m_pRopesImageView[i] = ImageView::create(buffer,ui::Widget::TextureResType::PLIST);
m_pRopesImageView[i]->setPosition(m_ropesPos[i]);
m_pNodes[i]->addChild(m_pRopesImageView[i], ROPE_ZORDER);
}
for (unsigned long i = 0; i < 3; i++) {
sprintf(buffer, "HY-GK10-2-TM01.png");
m_pAnchorsImageView[i] = ImageView::create(buffer,ui::Widget::TextureResType::PLIST);
m_pAnchorsImageView[i]->setAnchorPoint(Vec2::ANCHOR_MIDDLE_TOP);
m_pAnchorsImageView[i]->setPosition(m_anchorsPos[i]);
m_pNodes[i]->addChild(m_pAnchorsImageView[i], ANCHORS_ZORDER);
m_pAnchorsImageView[i]->runAction(RepeatForever::create(Sequence::create(RotateBy::create(0.6f, -20),RotateBy::create(1.2f, 40),RotateBy::create(0.6f, -20), NULL)));
}
unsigned int all = 0;
bool selected[3] = {false, false, false};
srand(unsigned(time(0)));
while (all < 3) {
unsigned int randIndex = static_cast<unsigned int>(rand() % 3);
if (selected[randIndex]) continue;
selected[randIndex] = true;
m_pNodes[all]->setPosition(m_nodesPos[all]);
all++;
} /*while*/
return true;
}
// 进入本回合
void Round034_03::onEnterRound()
{
auto dispatcher = Director::getInstance()->getEventDispatcher();
dispatcher->addCustomEventListener("openTouch", [this] (EventCustom *) {
auto dispatcher = Director::getInstance()->getEventDispatcher();
dispatcher->removeCustomEventListeners("openTouch");
m_opentouched = true;
if (m_jumped) {
openTouch();
}
});
dispatcher->addCustomEventListener("endRound", [this] (EventCustom *) {
auto dispatcher = Director::getInstance()->getEventDispatcher();
dispatcher->removeCustomEventListeners("endRound");
endRound();
});
this->schedule(CC_SCHEDULE_SELECTOR(Round034_03::changeScaleSchedule), 2.0f, -1, 0); //
}
//依次放大锚和绳子
void Round034_03::changeScaleSchedule(float)
{
if (m_InitAniIndex >= 3) {
unschedule(CC_SCHEDULE_SELECTOR(Round034_03::changeScaleSchedule));
m_jumped = true;
if (m_opentouched) {
openTouch();
}
return;
}
m_pNodes[m_InitAniIndex]->runAction(Sequence::create(ScaleTo::create(0.7f, 1.1f),CallFunc::create([this]{
char buffer[64];
sprintf(buffer, "HY-GK10-2-TM%02d.png",m_InitAniIndex+6);
m_pRopesImageView[m_InitAniIndex]->loadTexture(buffer,ui::Widget::TextureResType::PLIST);
m_pAnchorsImageView[m_InitAniIndex]->loadTexture("HY-GK10-2-TM05.png",ui::Widget::TextureResType::PLIST);
}),DelayTime::create(0.5f),CallFunc::create([this]{
char buffer[64];
sprintf(buffer, "HY-GK10-2-TM%02d.png",m_InitAniIndex+2);
m_pRopesImageView[m_InitAniIndex]->loadTexture(buffer,ui::Widget::TextureResType::PLIST);
m_pAnchorsImageView[m_InitAniIndex]->loadTexture("HY-GK10-2-TM01.png",ui::Widget::TextureResType::PLIST);
}),ScaleTo::create(0.7f, 1.0f),CallFunc::create([this]{
m_InitAniIndex++;
}), NULL));
}
/* 开启触摸 */
void Round034_03::openTouch()
{
///////////////////
// 事件派发
auto dispatcher = Director::getInstance()->getEventDispatcher();
auto listenerDrag = EventListenerTouchOneByOne::create();
listenerDrag->onTouchBegan = [this](Touch* touch, Event* event) -> bool
{
auto target = static_cast<Sprite*>(event->getCurrentTarget());
auto touchPoint = target->convertTouchToNodeSpace(touch);
Rect rect = Rect(0.0f, 0.0f, target->getContentSize().width, target->getContentSize().height);
if (rect.containsPoint(touchPoint))
{
target->setScale(1.1f);
return true;
}
return false;
};
listenerDrag->onTouchEnded = [this](Touch* touch, Event* event)
{
auto target = static_cast<Sprite*>(event->getCurrentTarget());
auto touchPoint = target->convertTouchToNodeSpace(touch);
Rect rect = Rect(0.0f, 0.0f, target->getContentSize().width, target->getContentSize().height+100);
auto index = (long)target->getUserData();
target->setScale(1.0f);
if (rect.containsPoint(touchPoint)) {
if (index == 2) { //答对
m_pStageScene->getRoundUINode()->stopReadEffect(); //停止题目音效
m_pStageScene->getRoundUINode()->endReadTopic(); //停止读题目改变动作
playAnswerCorrectEffect();
if (getEffIndex() != -1) {
MyAudioEngine::getInstance()->stopAudio(getEffIndex());
}
// 答对时主角说话
playLeadAnsCorEff();
m_pStageScene->playAnswerCorrectEffect(touch->getLocation());
celebrate(CELEBRATE_DELAY);
for (unsigned int i = 0; i < 3; i++) {
Director::getInstance()->getEventDispatcher()->removeEventListenersForTarget(m_pNodes[i]);
} /*for*/
m_InitAniIndex = 0;
} else {
playAnswerErrorEffect();
if (getEffIndex() != -1) {
MyAudioEngine::getInstance()->stopAudio(getEffIndex());
}
// 答错时主角说话
playLeadAnsErrEff();
if (m_anwerErrorCB) {
m_anwerErrorCB();
}
}
}
};
dispatcher->addEventListenerWithSceneGraphPriority(listenerDrag, m_pNodes[0]);
for (unsigned int i = 1; i < 3; i++) {
dispatcher->addEventListenerWithSceneGraphPriority(listenerDrag->clone(), m_pNodes[i]);
} /*for*/
}
/*
* 庆祝
*/
void Round034_03::celebrate(const float celebrateDelay /*庆祝延时*/ )
{
if (m_celebrateCB) {
m_celebrateCB(1);
}
m_pStageScene->getRoundUINode()->playPassActor(1);
}
/* 回合结束回调 */
void Round034_03::endRound()
{
if (m_completeCB) {
m_completeCB();
}
} | [
"[email protected]"
] | |
2d2be0c458ce0a3f385ebb9f185dc2f214e04eb9 | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /tat/src/v20201028/model/ModifyRegisterInstanceResponse.cpp | f8720dde9b4499d5efa3fced61caf3f149ccbc3c | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp | 9f5df8220eaaf72f7eaee07b2ede94f89313651f | 42a76b812b81d1b52ec6a217fafc8faa135e06ca | refs/heads/master | 2023-08-30T03:22:45.269556 | 2023-08-30T00:45:39 | 2023-08-30T00:45:39 | 188,991,963 | 55 | 37 | Apache-2.0 | 2023-08-17T03:13:20 | 2019-05-28T08:56:08 | C++ | UTF-8 | C++ | false | false | 3,079 | cpp | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/tat/v20201028/model/ModifyRegisterInstanceResponse.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Tat::V20201028::Model;
using namespace std;
ModifyRegisterInstanceResponse::ModifyRegisterInstanceResponse()
{
}
CoreInternalOutcome ModifyRegisterInstanceResponse::Deserialize(const string &payload)
{
rapidjson::Document d;
d.Parse(payload.c_str());
if (d.HasParseError() || !d.IsObject())
{
return CoreInternalOutcome(Core::Error("response not json format"));
}
if (!d.HasMember("Response") || !d["Response"].IsObject())
{
return CoreInternalOutcome(Core::Error("response `Response` is null or not object"));
}
rapidjson::Value &rsp = d["Response"];
if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.RequestId` is null or not string"));
}
string requestId(rsp["RequestId"].GetString());
SetRequestId(requestId);
if (rsp.HasMember("Error"))
{
if (!rsp["Error"].IsObject() ||
!rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() ||
!rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.Error` format error").SetRequestId(requestId));
}
string errorCode(rsp["Error"]["Code"].GetString());
string errorMsg(rsp["Error"]["Message"].GetString());
return CoreInternalOutcome(Core::Error(errorCode, errorMsg).SetRequestId(requestId));
}
return CoreInternalOutcome(true);
}
string ModifyRegisterInstanceResponse::ToJsonString() const
{
rapidjson::Document value;
value.SetObject();
rapidjson::Document::AllocatorType& allocator = value.GetAllocator();
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RequestId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value().SetString(GetRequestId().c_str(), allocator), allocator);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
value.Accept(writer);
return buffer.GetString();
}
| [
"[email protected]"
] | |
84161ca83bc99b6f63c0efa2730e88b1f428628d | 05a0eec7be0ec8b3669ce418d3394357b0e694bf | /백준/dfs/boj_2331(dfs로안품..).cpp | b1baa93c78230cc43ad1adc1c868396c8f184a6b | [] | no_license | lee-younggwan/Algorithm | 1960bbc3af19d0ccabaa913485794917057d3087 | a1c4ccf9a298a3bda1c9e5a84220968b35633636 | refs/heads/master | 2020-06-28T07:05:33.938906 | 2019-10-04T13:53:39 | 2019-10-04T13:53:39 | 200,171,538 | 1 | 0 | null | null | null | null | UHC | C++ | false | false | 751 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <string>
#include <cmath>
#include <vector>
#include <queue>
using namespace std;
#define MAX 3000001
vector <int> graph[MAX];
int visit[MAX];
int A, P;
int main()
{
int i = 0;
int num;
int sum = 0;
scanf("%d %d", &A, &P);
graph[0].push_back(A);
graph[A].push_back(0);
visit[A] = 1;
num = A;
i = 1;
while (1)
{
sum = 0;
while (num)
{
sum += (int)pow((num % 10), P);
num /= 10;
}
if (visit[sum] == 1) { // 이미 방문했다면
printf("%d\n", graph[sum].front());
break;
}
//방문하지 않았다면
visit[sum] = 1;
graph[i].push_back(sum);
graph[sum].push_back(i);
num = sum;
i++;
}
return 0;
} | [
"[email protected]"
] | |
50459d1b052ead1e4718e6e96fce6ec83d307ec7 | 9ceed10c13ad2ce666d74db72a040ed25476a18a | /ScriptEngine/ScriptEngine/lib/vm/parser/error/vm_error.h | 5c760bbf33e861a585d817a7c4d1a7d935ae5071 | [] | no_license | kawawa1989/ScriptEngine | b7a550e8e5d56d464861e0322ef449bf8d18cd5b | 3911b77c35ca5642cfa8175d73c0677af87157dc | refs/heads/master | 2022-02-18T15:14:41.395205 | 2019-09-11T13:30:00 | 2019-09-11T13:30:00 | 22,090,779 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,645 | h | #pragma once
#include "../../vm_define.h"
namespace Sencha {
namespace VM {
namespace Assembly {
using namespace std;
enum ERR_ID {
ERROR_C2065 , // "symbolName" : 定義されていない識別子です。
ERROR_C2059 , // 構文エラー : 's'
ERROR_C2143 , // 構文エラー : ']' が ';' の前にありません。
};
/*
* エラー列挙型の拡張機能
*/
class ERR_ID_EX{
public :
/*
* IDを文字列にする
*/
static string toString( ERR_ID value );
};
/*
* エラー時のパラメータ基底
* エラーの種類によって欲しいパラメータが異なるので抽象的にオブジェクトのみ用意する
*/
class VMErrorParameter {
public :
ERR_ID errId;
public :
VMErrorParameter( ERR_ID errid ){
this->errId = errid;
}
virtual ~VMErrorParameter(){
}
};
class ERROR_INFO_C2065 : public VMErrorParameter {
public :
string symbolName;
ERROR_INFO_C2065( const string& symbolName ) : VMErrorParameter( ERROR_C2065 ){
this->symbolName = symbolName;
}
};
class ERROR_INFO_C2143 : public VMErrorParameter {
public :
int tokenType;
ERROR_INFO_C2143( int tokenType ) : VMErrorParameter( ERROR_C2143 ){
this->tokenType = tokenType;
}
};
class ERROR_INFO_C2059 : public VMErrorParameter {
public :
string s;
ERROR_INFO_C2059( string s ) : VMErrorParameter( ERROR_C2059 ){
this->s = s;
}
};
/*
* 仮想機械関係でのエラー処理など
*/
class VMError {
protected :
string m_message;
VMErrorParameter* m_param;
public :
VMError( VMErrorParameter* param );
virtual ~VMError();
const string& getMessage(){
return m_message;
}
};
} // Assembly
} // VM
} // Sencha | [
"[email protected]"
] | |
7bbbcf85493e6f10f07885edc0b87d4dff053c9b | 2c37c298a494ed37bff11b0b240371eaba6575b7 | /Interview/1/interview-10.01/main.cpp | c179eccfc7685c0f140db0054af9ebe47a8588eb | [] | no_license | chichuyun/LeetCode | 04ec78bf5b05d4febfd8daff5e0e0145cfcfacf4 | 44752f2b58cd7a850b8e02cd3735f93bb82bcb85 | refs/heads/master | 2021-06-04T11:03:04.297131 | 2020-11-19T14:48:32 | 2020-11-19T14:48:32 | 148,440,792 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 617 | cpp | class Solution {
public:
void merge(vector<int>& A, int m, vector<int>& B, int n) {
int len=A.size(), lenB=B.size(), lenA=len-lenB;
int i=lenA-1, j=lenB-1;
for(int k=len-1;k>=0;--k) {
if(i>=0 && j>=0) {
if(A[i]>B[j]) {
A[k] = A[i];
--i;
} else {
A[k] = B[j];
--j;
}
} else if(i>=0) {
A[k] = A[i];
--i;
} else {
A[k] = B[j];
--j;
}
}
}
}; | [
"[email protected]"
] | |
5e568acc178f816dc509f15250f00f6eb461f0ef | 550298aa2d16cd94549dcbc38314f84812d2db53 | /host/pixymon/clut.h | 3e212c9ba13d1787b97edfc0b829b89894c97af6 | [] | no_license | Neon22/pixy | 3280d4d7d9f0e548d25e26aae5f6f53d8aeb6e06 | b3d3ae75c3477ed91427aa969666a25a99c874ea | refs/heads/master | 2021-01-14T12:20:49.148046 | 2014-01-11T11:03:24 | 2014-01-11T11:03:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 304 | h | #ifndef CLUT_H
#define CLUT_H
#include "stdint.h"
#define PI 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068
class CLUT
{
public:
static void generateFromImgSample(uint32_t *data, int d_len, uint8_t* tempLut);
};
#endif // CLUT_H
| [
"[email protected]"
] | |
467c2389ed05fdbaee56386731e7880baf145148 | 9a8e3137db2b3e29dceb170887144e991974c1f2 | /eXemplar's-collection/exemplar/Apps 'n Bots/Apps 'n Bots/OCR/FOCRSource/src/KFC_KTL/consts.cpp | 579f6cfe33898bab1136b561d81754b2bb59ec2f | [] | no_license | drewjbartlett/runescape-classic-dump | 07155b735cfb6bf7b7b727557d1dd0c6f8e0db0b | f90e3bcc77ffb7ea4a78f087951f1d4cb0f6ad8e | refs/heads/master | 2021-01-19T21:32:45.000029 | 2015-09-05T22:36:22 | 2015-09-05T22:36:22 | 88,663,647 | 1 | 0 | null | 2017-04-18T19:40:23 | 2017-04-18T19:40:23 | null | UTF-8 | C++ | false | false | 47 | cpp | #include "kfc_ktl_pch.h"
#include "consts.h"
| [
"[email protected]"
] | |
a8cd640a08b3859c7c4e049f34667a801443e086 | 7708c94fbedf7abe362823904828d306d07f1bc0 | /task_junior_cpp/Primes.cpp | 689d284a24f491a951f5afb81e834455a0826219 | [] | no_license | vladsaukhin/task_junior_cpp | 4dd0516730168119b6ff5975b27b4dfe9b20ad14 | 0dfb34cfdbe3bad605f3cc846093119fe20784b5 | refs/heads/master | 2020-03-26T19:52:41.002402 | 2018-08-29T16:56:59 | 2018-08-29T16:56:59 | 145,291,142 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,804 | cpp | #include "Primes.h"
Primes::Primes()
:leftRange(0), rightRange(0)
{}
Primes::Primes(int64_t a, int64_t b)
: leftRange(a), rightRange(b)
{}
/*Primes::Primes(const Primes & other){
leftRange = other.getLeftRange();
rightRange = other.getRightRange();
}
Primes & Primes::operator=(const Primes & other)
{
if (this == &other) return *this;
leftRange = other.getLeftRange();
rightRange = other.getRightRange();
return *this;
}
Primes::Primes(Primes && other)
{
leftRange = other.getLeftRange();
rightRange = other.getRightRange();
}
Primes & Primes::operator=(Primes && other)
{
if (this == &other) return *this;
leftRange = other.getLeftRange();
rightRange = other.getRightRange();
return *this;
}*/
Primes::~Primes() {}
void Primes::uniqueness() {
std::cout << "Uniqueness...";
for (int64_t i = 0; i < result.size() - 1; i++) {
for (int64_t j = i + 1; j < result.size(); j++) {
if (result.at(i) == result.at(j))
result.erase(result.begin() + j);
}
}
std::cout << "Done" << std::endl;
}
bool Primes::Quick_Sort(int l, int r) {
if (l > r) return false;
int i, j;
i = l;
j = r;
int middle = result.at((i + j) / 2);
do {
while (middle > result.at(i)) i++;
while (middle < result.at(j)) j--;
if (i <= j) {
std::swap(result.at(i), result.at(j));
i++;
j--;
}
} while (i < j);
if (i < r) Quick_Sort(i, r);
if (j > l) Quick_Sort(l, j);
}
void Primes::output() {
std::cout << "Sorting...";
Primes::Quick_Sort(0, result.size() - 1);
std::cout << "Done" << std::endl;
Primes::uniqueness();
std::string out;
const char* xml =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<root>"
"<primes></primes>"
"</root>";
tinyxml2::XMLDocument doc;
doc.Parse(xml);
tinyxml2::XMLElement* el = doc.FirstChildElement("root")->FirstChildElement("primes");
for (int64_t i = 0; i < result.size(); i++) {
out += std::to_string(result.at(i));
out += " ";
}
el->SetText(out.c_str());
doc.SaveFile("output.xml");
}
void Primes::primes_alg(int64_t l, int64_t r) {
//std::cout << "Searching primes num...";
//avoiding errors
//the vector will not be threaded into two streams simultaneously if the calculations take a long time
std::mutex mtx;
bool flag = false;
if (l == 1) ++l;
if (l == 2) {
std::lock_guard<std::mutex> lcg(mtx); //critical section
Primes::result.push_back(l);
}
if (!(l & 1)) ++l; // paired numbers are not primes
if (!(r & 1)) --r;
for (; l <= r; l += 2) {
flag = true;
if (l % 2 == 0) flag = false;
for (int64_t i = 3; i <= round(sqrt(l)); i += 2)
if (l%i == 0) {
flag = false;
break;
}
if (flag) {
std::lock_guard<std::mutex> lcg(mtx); //critical section
Primes::result.push_back(l);
}
}
//std::cout << "Done" << std::endl;
}
| [
"[email protected]"
] | |
22c562054c3392db3739c136f2d4c713cd9ba3b6 | 69416d808cdb41609874104401f25b084193eab8 | /CLion/P2878.cpp | dbc385f763c343a271ae6c52fad34bd7fcc7b89f | [] | no_license | CubeDr/Bakejoon | 50196f5fcf063c651cebfc9a4f019aada474fa2d | 127f12196517ba834eb1b5bbe742625375a595d1 | refs/heads/master | 2020-03-29T11:43:41.497063 | 2019-10-20T06:03:39 | 2019-10-20T06:03:39 | 149,867,522 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,375 | cpp | #include <iostream>
#include <queue>
using namespace std;
typedef unsigned long long ull;
struct Want {
int want; // 원하는 사탕의 개수
int count; // 원하는 친구의 수
bool operator<(const Want& o) const {
return want < o.want;
}
};
int M, N;
int main() {
priority_queue<Want> wants;
cin >> M >> N;
for(int i=0; i<N; i++) {
int w;
cin >> w;
wants.push(Want{w, 1});
}
while(M>0) {
Want w = wants.top();
wants.pop();
while(!wants.empty() && wants.top().want == w.want) {
w.count += wants.top().count;
wants.pop();
}
int target = 0;
if(!wants.empty()) target = wants.top().want;
int required = (w.want - target) * w.count;
if(M >= required) {
M -= required;
wants.push(Want{target, w.count});
} else {
int equal = M / w.count;
int left = M % w.count;
wants.push(Want{w.want - equal - 1, left});
wants.push(Want{w.want - equal, w.count - left});
M = 0;
}
}
ull rageSum = 0;
while(!wants.empty()) {
ull want = (ull) wants.top().want;
ull count = (ull) wants.top().count;
wants.pop();
rageSum += want * want * count;
}
cout << rageSum;
return 0;
} | [
"[email protected]"
] | |
8829703e26b001e42d85941e585ac1ab26f36be8 | dca0a4f625e7df6ec4da5c888cf356d357b2d061 | /Libs/PylonCamera/include/pylon/PylonDeviceProxy.h | 505a5373289a36e0faea75c1d02733089c51c30b | [] | no_license | radtek/Trunk | 60de74b0a6b0f8f78d046a2d44ede802173003a7 | 9b33801ee65d1e1363f5f692348d9dd709638d96 | refs/heads/master | 2022-01-19T15:00:09.587661 | 2019-07-15T08:54:23 | 2019-07-15T08:54:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,064 | h | //-----------------------------------------------------------------------------
// Basler pylon SDK
// Copyright (c) 2007-2019 Basler AG
// http://www.baslerweb.com
// Author: AH
//-----------------------------------------------------------------------------
/*!
\file
\brief Low Level API: Pylon generic device interface declaration
*/
#ifndef __PYLON_PYLONDEVICEPROXY__H__
#define __PYLON_PYLONDEVICEPROXY__H__
#if _MSC_VER > 1000
#pragma once
#endif
#include <pylon/Platform.h>
#ifdef _MSC_VER
# pragma pack(push, PYLON_PACKING)
#endif /* _MSC_VER */
#include <Base/GCException.h>
#include "Device.h"
#include "TlFactory.h"
//! Macro to define a custom camera class
#define PYLON_DEFINE_CAMERA(ClassName, BaseClass) \
class ClassName : public BaseClass \
{ \
public: \
/** \name Construction */ \
/*@{*/ \
/** \brief \copybrief Pylon::CPylonDeviceProxyT::CPylonDeviceProxyT()
\copydetails Pylon::CPylonDeviceProxyT::CPylonDeviceProxyT()
*/ \
ClassName() {}; \
/** \brief \copybrief Pylon::CPylonDeviceProxyT::CPylonDeviceProxyT(IPylonDevice*,bool)
\copydetails Pylon::CPylonDeviceProxyT::CPylonDeviceProxyT(IPylonDevice*,bool)
*/ \
ClassName(IPylonDevice* pDevice, bool takeOwnership = true) \
: BaseClass(pDevice, takeOwnership) {} \
/** \brief \copybrief Pylon::CPylonDeviceProxyT::~CPylonDeviceProxyT()
\copydetails Pylon::CPylonDeviceProxyT::~CPylonDeviceProxyT()
*/ \
virtual ~ClassName(){} \
/*@}*/ \
};
namespace Pylon
{
//**************************************************************************************************
//! Low Level API: The camera class for generic camera devices
/**
This is the base class for pylon camera classes providing access to camera parameters.
\see \ref configuringcameras
\tparam TCameraParams The camera specific parameter class (auto generated from camera xml file)
\ingroup Pylon_LowLevelApi
*/
//**************************************************************************************************
template<class TCameraParams>
class CPylonDeviceProxyT : public TCameraParams
{
public:
//! \name Construction
// \{
//! Creates a camera object that is not attached to an pylon device. Use the Attach() method to attach the device
CPylonDeviceProxyT();
/** \brief Creates a camera object and attaches a camera object to a pylon device that takes the ownership over an pylon device.
When having the ownership, the destructor of this camera object destroys the pylon device
the camera object is attached to. Otherwise, the pylon device object remains valid when the camera
object has been destroyed.
*/
CPylonDeviceProxyT(IPylonDevice*, bool takeOwnership = true);
//! Destructor
virtual ~CPylonDeviceProxyT();
//\}
private:
//! \name Assignment and copying is not supported
// \{
CPylonDeviceProxyT(const CPylonDeviceProxyT&);
CPylonDeviceProxyT& operator=(const CPylonDeviceProxyT&);
// \}
public:
//! \name Some smart pointer functionality
// \{
/** \brief Attach the camera object to a pylon device
It is not allowed to call Attach when the camera object is already attached!
When having the ownership, the destructor of this camera object destroys the pylon device
the camera object is attached to. Otherwise, the pylon device object remains valid when the camera
object has been destroyed.
*/
virtual void Attach(IPylonDevice*, bool takeOwnership = true);
//! Checks if a pylon device is attached to the camera object
virtual bool IsAttached() const;
//! Checks if the camera object has the ownership of the pylon device
virtual bool HasOwnership() const;
//! Returns the pylon device interface pointer
virtual IPylonDevice* GetDevice() const;
// \}
public:
//! \name Implementation of the IPylonDevice interface.
//! See Pylon::IPylonDevice for more details.
// \{
/** \brief \copybrief Pylon::IPylonDevice::Open()
\copydetails Pylon::IPylonDevice::Open()
*/
void Open(AccessModeSet mode = (Stream | Control | Event))
{
CheckDevicePtr();
m_pDevice->Open(mode);
}
/** \brief \copybrief Pylon::IPylonDevice::Close()
\copydetails Pylon::IPylonDevice::Close()
*/
void Close(void)
{
CheckDevicePtr();
m_pDevice->Close();
}
/** \brief \copybrief Pylon::IPylonDevice::IsOpen()
\copydetails Pylon::IPylonDevice::IsOpen()
*/
bool IsOpen(void) const
{
CheckDevicePtr();
return m_pDevice->IsOpen();
}
/** \brief \copybrief Pylon::IPylonDevice::AccessMode()
\copydetails Pylon::IPylonDevice::AccessMode()
*/
AccessModeSet AccessMode(void) const
{
CheckDevicePtr();
return m_pDevice->AccessMode();
}
/** \brief \copybrief Pylon::IPylonDevice::GetDeviceInfo()
\copydetails Pylon::IPylonDevice::GetDeviceInfo()
*/
const CDeviceInfo& GetDeviceInfo(void) const
{
CheckDevicePtr();
return m_pDevice->GetDeviceInfo();
}
/** \brief \copybrief Pylon::IPylonDevice::GetNumStreamGrabberChannels()
\copydetails Pylon::IPylonDevice::GetNumStreamGrabberChannels()
*/
uint32_t GetNumStreamGrabberChannels(void) const
{
CheckDevicePtr();
return m_pDevice->GetNumStreamGrabberChannels();
}
/** \brief \copybrief Pylon::IPylonDevice::GetStreamGrabber()
\copydetails Pylon::IPylonDevice::GetStreamGrabber()
*/
IStreamGrabber* GetStreamGrabber(uint32_t index)
{
CheckDevicePtr();
return m_pDevice->GetStreamGrabber(index);
}
/** \brief \copybrief Pylon::IPylonDevice::GetEventGrabber()
\copydetails Pylon::IPylonDevice::GetEventGrabber()
*/
IEventGrabber* GetEventGrabber(void)
{
CheckDevicePtr();
return m_pDevice->GetEventGrabber();
}
/** \brief \copybrief Pylon::IPylonDevice::GetNodeMap()
\copydetails Pylon::IPylonDevice::GetNodeMap()
*/
GENAPI_NAMESPACE::INodeMap* GetNodeMap(void)
{
CheckDevicePtr();
return m_pDevice->GetNodeMap();
}
/** \brief \copybrief Pylon::IPylonDevice::GetTLNodeMap()
\copydetails Pylon::IPylonDevice::GetTLNodeMap()
*/
GENAPI_NAMESPACE::INodeMap* GetTLNodeMap(void)
{
CheckDevicePtr();
return m_pDevice->GetTLNodeMap();
}
/** \brief \copybrief Pylon::IPylonDevice::CreateChunkParser()
\copydetails Pylon::IPylonDevice::CreateChunkParser()
*/
Pylon::IChunkParser* CreateChunkParser(void)
{
CheckDevicePtr();
return m_pDevice->CreateChunkParser();
}
/** \brief \copybrief Pylon::IPylonDevice::DestroyChunkParser()
\copydetails Pylon::IPylonDevice::DestroyChunkParser()
*/
void DestroyChunkParser(Pylon::IChunkParser* pChunkParser)
{
CheckDevicePtr();
m_pDevice->DestroyChunkParser(pChunkParser);
}
/** \brief \copybrief Pylon::IPylonDevice::CreateEventAdapter()
\copydetails Pylon::IPylonDevice::CreateEventAdapter()
*/
IEventAdapter* CreateEventAdapter(void)
{
CheckDevicePtr();
return m_pDevice->CreateEventAdapter();
}
/** \brief \copybrief Pylon::IPylonDevice::DestroyEventAdapter()
\copydetails Pylon::IPylonDevice::DestroyEventAdapter()
*/
void DestroyEventAdapter(IEventAdapter* pAdapter)
{
CheckDevicePtr();
m_pDevice->DestroyEventAdapter(pAdapter);
}
/** \brief \copybrief Pylon::IPylonDevice::CreateSelfReliantChunkParser()
\copydetails Pylon::IPylonDevice::CreateSelfReliantChunkParser()
*/
virtual ISelfReliantChunkParser* CreateSelfReliantChunkParser()
{
CheckDevicePtr();
return m_pDevice->CreateSelfReliantChunkParser();
}
/** \brief \copybrief Pylon::IPylonDevice::DestroySelfReliantChunkParser()
\copydetails Pylon::IPylonDevice::DestroySelfReliantChunkParser()
*/
virtual void DestroySelfReliantChunkParser(ISelfReliantChunkParser* pChunkParser)
{
CheckDevicePtr();
m_pDevice->DestroySelfReliantChunkParser(pChunkParser);
}
/** \brief \copybrief Pylon::IPylonDevice::RegisterRemovalCallback()
\copydetails Pylon::IPylonDevice::RegisterRemovalCallback()
*/
DeviceCallbackHandle RegisterRemovalCallback(DeviceCallback& d)
{
CheckDevicePtr();
return m_pDevice->RegisterRemovalCallback(d);
}
/** \brief \copybrief Pylon::IPylonDevice::DeregisterRemovalCallback()
\copydetails Pylon::IPylonDevice::DeregisterRemovalCallback()
*/
bool DeregisterRemovalCallback(DeviceCallbackHandle h)
{
CheckDevicePtr();
return m_pDevice->DeregisterRemovalCallback(h);
}
// \}
protected:
void CheckDevicePtr() const
{
if (NULL == m_pDevice)
{
throw LOGICAL_ERROR_EXCEPTION("The camera class is not attached to a IPylonDevice");
}
}
IPylonDevice* m_pDevice;
bool m_hasOwnership;
};
//**************************************************************************************************
// CPylonDeviceProxyT implementation
//**************************************************************************************************
template<class TCameraParams>
inline CPylonDeviceProxyT<TCameraParams>::CPylonDeviceProxyT(void)
: m_pDevice(NULL)
, m_hasOwnership(false)
{
}
template<class TCameraParams>
inline CPylonDeviceProxyT<TCameraParams>::CPylonDeviceProxyT(IPylonDevice* pDevice, bool takeOwnership)
: m_pDevice(NULL)
, m_hasOwnership(false)
{
Attach(pDevice, takeOwnership);
}
template<class TCameraParams>
inline CPylonDeviceProxyT<TCameraParams>::~CPylonDeviceProxyT(void)
{
if ( HasOwnership() && IsAttached() )
{
CTlFactory::GetInstance().DestroyDevice(m_pDevice);
}
}
template<class TCameraParams>
inline void CPylonDeviceProxyT<TCameraParams>::Attach(IPylonDevice* pDevice, bool takeOwnership)
{
if ( IsAttached() )
{
throw LOGICAL_ERROR_EXCEPTION("Object is already attached to a pylon device");
}
if ( NULL == pDevice )
{
throw LOGICAL_ERROR_EXCEPTION("Tried to attach a NULL pointer as device");
}
TCameraParams::_Initialize(pDevice->GetNodeMap());
m_pDevice = pDevice;
m_hasOwnership = takeOwnership;
}
template<class TCameraParams>
inline bool CPylonDeviceProxyT<TCameraParams>::IsAttached() const
{
return NULL != m_pDevice;
}
template<class TCameraParams>
inline bool CPylonDeviceProxyT<TCameraParams>::HasOwnership() const
{
return m_hasOwnership;
}
template<class TCameraParams>
inline IPylonDevice* CPylonDeviceProxyT<TCameraParams>::GetDevice() const
{
return m_pDevice;
}
} // namespace Pylon
#ifdef _MSC_VER
# pragma pack(pop)
#endif /* _MSC_VER */
#endif
| [
"[email protected]"
] | |
a86cae430fe8a69704a18550abd8165fd884cb48 | 372d9af1222320fdee7412446b55efb73aac83cf | /Managed/Src/detail/Policies/ReceiverFactory.cpp | 178d7afac38facdaf50ba46bc6ee84371c747181 | [
"MIT"
] | permissive | JunExplore/IPC | dc81941a4f9806b279276c030d78f9989679ce3c | b04a4333b936c8aa18b99ca85390690054face85 | refs/heads/master | 2023-07-09T20:27:41.619083 | 2017-07-28T18:14:30 | 2017-07-28T18:14:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,880 | cpp | #include "IPC/Managed/detail/Policies/ReceiverFactory.h"
#include "Exception.h"
#include "detail/ThreadDetector.h"
#include "IPC/Managed/detail/NativeObject.h"
#include <msclr/gcroot.h>
#include <msclr/auto_handle.h>
namespace IPC
{
namespace Managed
{
namespace detail
{
namespace Policies
{
ref class Scheduler
{
public:
void Schedule(Interop::Callback<void()>&& callback)
{
System::Threading::ThreadPool::QueueUserWorkItem(
gcnew System::Threading::WaitCallback(
gcnew TaskCallback{ this, std::move(callback) }, &TaskCallback::operator()));
}
void Stop()
{
m_counter->Signal();
if (!System::Environment::HasShutdownStarted && !System::AppDomain::CurrentDomain->IsFinalizingForUnload())
{
if (!m_recursionDetector.IsExpectedThread)
{
m_counter->Wait();
}
}
}
internal:
ref class TaskCallback
{
public:
TaskCallback(Scheduler^ scheduler, Interop::Callback<void()>&& callback)
: m_scheduler{ scheduler },
m_callback{ std::move(callback) }
{
m_scheduler->m_counter->AddCount();
}
~TaskCallback()
{
m_scheduler->m_counter->Signal();
}
void operator()(System::Object^ /*state*/)
{
msclr::auto_handle<TaskCallback> disposer{ this };
auto detector = m_scheduler->m_recursionDetector.AutoDetect();
(*m_callback)();
}
private:
Scheduler^ m_scheduler;
NativeObject<Interop::Callback<void()>> m_callback;
};
private:
ThreadDetector m_recursionDetector;
System::Threading::CountdownEvent^ m_counter{ gcnew System::Threading::CountdownEvent{ 1 } };
};
Interop::Policies::ReceiverFactory MakeReceiverFactory()
{
return []
{
msclr::gcroot<Scheduler^> scheduler{ gcnew Scheduler{} };
std::shared_ptr<void> disposer{ (void*) true, [scheduler](void*) { scheduler->Stop(); } };
return [scheduler, disposer = std::move(disposer)](Interop::Callback<void()>&& callback)
{
scheduler->Schedule(std::move(callback));
};
};
}
} // Policies
} // detail
} // Managed
} // IPC
| [
"[email protected]"
] | |
8167ed1693db1794861b8518688938f8b37a6d4c | 77c5f0bfa074bb1d707de148e79d490db28d604d | /test/include/asserts.h | a186fd93d9556efc5ddb534cc05928e2ccdcbe48 | [] | no_license | ageev-aleksey/abstract_positions_fort | 08d912c2b2edcfda67bf9f3b1142b4f2deb0e151 | e0f1ac17e0a87a097457ccbb4d184ccc6e6960e1 | refs/heads/master | 2022-11-09T17:53:29.980582 | 2020-07-03T19:18:33 | 2020-07-03T19:29:29 | 276,636,167 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 714 | h | #include <iostream>
#include <unordered_set>
template<typename T>
std::ostream& operator<<(std::ostream &stream, const std::unordered_set<T> set) {
stream << "std::unordered_set{ ";
for(const T &el : set) {
stream << el << " ";
}
stream << "}\n";
return stream;
}
template <typename T>
bool assertEq(const T& expected, const T& actual, const std::string &testName) {
if(expected != actual) {
std::cout << "Test ERROR: " << testName << "\n"
<< "-- Expected value: " << expected << "\n"
<< "-- Actual value: " << actual << std::endl;
return false;
}
std::cout << "Test OK: " << testName << std::endl;
return true;
}
| [
"[email protected]"
] | |
938e8ba52df7a7ecaf0718caf5da0a558bc1cd26 | 2f6d39c2daf70ebaae90e72ca503f8b275d3572a | /opt/uses-names/UsesNames.h | b12a154ef1fa4b9bb28345fd7e894edc74e95bb8 | [
"MIT"
] | permissive | facebook/redex | 5a39c5b733e729ecb52101dd3f941a63f9fa32f0 | 36c6607be749ba2009210aae404d68cd57e747eb | refs/heads/main | 2023-09-01T18:21:21.839608 | 2023-09-01T02:01:59 | 2023-09-01T02:01:59 | 54,664,770 | 6,459 | 775 | MIT | 2023-08-25T00:06:04 | 2016-03-24T18:26:35 | C++ | UTF-8 | C++ | false | false | 1,521 | h | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include "Pass.h"
class ProcessUsesNamesAnnoPass : public Pass {
public:
struct Metrics {
int32_t used_classes{0};
int32_t used_classes_by_subclass{0};
int32_t used_classes_by_field{0};
int32_t used_fields{0};
int32_t used_methods{0};
int32_t uses_names_anno{0};
int32_t uses_names_trans_anno{0};
};
ProcessUsesNamesAnnoPass() : Pass("ProcessUsesNamesAnnoPass") {}
redex_properties::PropertyInteractions get_property_interactions()
const override {
using namespace redex_properties::interactions;
using namespace redex_properties::names;
return {
{HasSourceBlocks, Preserves},
{NoResolvablePureRefs, Preserves},
{NoSpuriousGetClassCalls, Preserves},
};
}
void bind_config() override {
bind("uses_names_annotation",
DexType::get_type("Lcom/facebook/redex/annotations/UsesNames;"),
m_uses_names_annotation);
bind("uses_names_trans_annotation",
DexType::get_type(
"Lcom/facebook/redex/annotations/UsesNamesTransitive;"),
m_uses_names_trans_annotation);
}
bool is_cfg_legacy() override { return true; }
void run_pass(DexStoresVector&, ConfigFiles&, PassManager&) override;
private:
DexType* m_uses_names_annotation;
DexType* m_uses_names_trans_annotation;
};
| [
"[email protected]"
] | |
d17a55f9f451a7b97f35de06f1db34ec8b53fe18 | 1ead07230b0726719ad46048aafe3d87ec7f3777 | /str.cpp | 4e3831c423dac22ca70cbf6ec7084f14189b2926 | [] | no_license | bpskong/lab | f8d369ec49faea28f286a2d7e52f2399f94d8d94 | 40bc02a1cba4a082c95d9754a0b528928de05adf | refs/heads/master | 2021-01-18T18:35:10.371248 | 2013-08-24T09:42:24 | 2013-08-24T09:42:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,251 | cpp | #include <str.h>
const unsigned char g_table_upcase[256] =
{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 123,124,125,126,127,
128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255
};
str ws2s(const wstr& ws)
{
str s(ws.length() * 2 + 1, 0);
size_t n = wcstombs(&s[0], &ws[0], s.capacity());
s.resize(n);
return s;
}
| [
"[email protected]"
] | |
b6408d0542544073ab6eedf2c844b0c6517c8320 | e1ecd3146b56dcd9b4ffaf1d343ef64e8c42dc64 | /Baekjoon/baek_14503_로봇청소기/baek_14503_로봇청소기/main.cpp | 785bdfbd5ddb05bc95f5b668ac0bd943cdeb9ad6 | [] | no_license | wjddlsy/Algorithm | 7bbeca6b5d21867355c88de8b4218bcfe8eeea75 | 385247c63337cae1cf3d9adbf8be38d6f62f2945 | refs/heads/master | 2022-12-04T19:35:48.763646 | 2020-08-23T08:14:29 | 2020-08-23T08:14:29 | 198,079,854 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,218 | cpp | //
// main.cpp
// baek_14503_로봇청소기
//
// Created by 윤정인 on 2018. 9. 24..
// Copyright © 2018년 윤정인. All rights reserved.
//
#include <iostream>
using namespace std;
int dx[4]={0, -1, 0, 1}, dy[4]={-1,0,1,0};
int initd[4] = {0, 3, 2, 1};
int N, M;
int board[50][50];
int answer=0;
void dfs(int y, int x, int d){
// 종료조건
if(board[y][x]!=2){
board[y][x]=2;
answer++;
}
bool chk=true;
for(int i=0; i<4; ++i){
int rd = (i+d+1)%4;
int rx = x+dx[rd], ry=y+dy[rd];
if(!board[ry][rx]) {
dfs(ry,rx, rd);
chk = false;
break;
}
}
if(chk){
int rx = x + dx[(d+2)%4], ry = y + dy[(d+2)%4];
if(board[ry][rx]==1)
return;
else
dfs(ry, rx, d);
}
return;
}
int main(int argc, const char * argv[]) {
// insert code here...
cin >> N >> M;
int r,c, d;
cin >> r >> c >> d;
for(int i=0; i<N; ++i){
for(int j=0; j<M; ++j)
cin >> board[i][j];
}
dfs(r,c,initd[d]);
cout << answer;
//std::cout << "Hello, World!\n";
return 0;
}
| [
"[email protected]"
] | |
0164cd7bb4e1f1a777f2e466a33b4a8a6d601fbb | fc33ec4fd149843556442ae420547a294509e411 | /cpp/POM3/Object.cpp | 18803507a57c5ad89af0e121991f01a694d3ea38 | [] | no_license | majunfu/essential | 317179e5d39bcf1327c29b769933326367456035 | d1f4de29c3188a7864c2bc01c09b09d182f7426a | refs/heads/master | 2021-01-14T08:54:41.919316 | 2015-06-02T21:39:19 | 2015-06-02T21:39:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 572 | cpp | #include "Object.h"
using namespace std;
using namespace cv;
Object::Object () {
;
}
void Object::addViews (std::vector<Mat> views) {
for ( size_t i = 0; i < views.size(); ++i ) {
views_.push_back (views[i]);
}
}
void Object::addFace (Face face) {
for ( size_t i = 0; i < face.views_.size(); ++i ) {
views_.push_back (face.views_[i]);
keypoints_.push_back (face.keypoints_[i]);
descriptors_.push_back (face.descriptors_[i]);
bows_.push_back (face.bows_[i]);
}
vocabulary_.push_back (face.vocabulary_);
}
| [
"[email protected]"
] | |
9532b9e1003701c542e8b2a928b93911ca057b58 | fcc0fdd505b343150de2040bf8458361447c33be | /src/uint256.h | 578c5046c87e2f870e60548b97c0014fe909a379 | [
"MIT"
] | permissive | oakey22/0uant0n1um | eae47a6a64b2b8b9cb331b02b8c7a38bd14295e9 | 8c41274f2dbb01524e060e4865a24bc4a1d6d030 | refs/heads/master | 2021-09-02T09:44:46.940817 | 2018-01-01T15:36:19 | 2018-01-01T15:36:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,622 | h | // Copyright (c) 2009-2016 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef Quantonium_UINT256_H
#define Quantonium_UINT256_H
#include <string>
#include <vector>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
inline int Testuint256AdHoc(std::vector<std::string> vArg);
/** Base class without constructors for uint256 and uint160.
* This makes the compiler let u use it in a union.
*/
template<unsigned int BITS>
class base_uint
{
protected:
enum { WIDTH=BITS/32 };
unsigned int pn[WIDTH];
public:
bool operator!() const
{
for (int i = 0; i < WIDTH; i++)
if (pn[i] != 0)
return false;
return true;
}
const base_uint operator~() const
{
base_uint ret;
for (int i = 0; i < WIDTH; i++)
ret.pn[i] = ~pn[i];
return ret;
}
const base_uint operator-() const
{
base_uint ret;
for (int i = 0; i < WIDTH; i++)
ret.pn[i] = ~pn[i];
ret++;
return ret;
}
double getdouble() const
{
double ret = 0.0;
double fact = 1.0;
for (int i = 0; i < WIDTH; i++) {
ret += fact * pn[i];
fact *= 4294967296.0;
}
return ret;
}
base_uint& operator=(uint64_t b)
{
pn[0] = (unsigned int)b;
pn[1] = (unsigned int)(b >> 32);
for (int i = 2; i < WIDTH; i++)
pn[i] = 0;
return *this;
}
base_uint& operator^=(const base_uint& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] ^= b.pn[i];
return *this;
}
base_uint& operator&=(const base_uint& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] &= b.pn[i];
return *this;
}
base_uint& operator|=(const base_uint& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] |= b.pn[i];
return *this;
}
base_uint& operator^=(uint64_t b)
{
pn[0] ^= (unsigned int)b;
pn[1] ^= (unsigned int)(b >> 32);
return *this;
}
base_uint& operator|=(uint64_t b)
{
pn[0] |= (unsigned int)b;
pn[1] |= (unsigned int)(b >> 32);
return *this;
}
base_uint& operator<<=(unsigned int shift)
{
base_uint a(*this);
for (int i = 0; i < WIDTH; i++)
pn[i] = 0;
int k = shift / 32;
shift = shift % 32;
for (int i = 0; i < WIDTH; i++)
{
if (i+k+1 < WIDTH && shift != 0)
pn[i+k+1] |= (a.pn[i] >> (32-shift));
if (i+k < WIDTH)
pn[i+k] |= (a.pn[i] << shift);
}
return *this;
}
base_uint& operator>>=(unsigned int shift)
{
base_uint a(*this);
for (int i = 0; i < WIDTH; i++)
pn[i] = 0;
int k = shift / 32;
shift = shift % 32;
for (int i = 0; i < WIDTH; i++)
{
if (i-k-1 >= 0 && shift != 0)
pn[i-k-1] |= (a.pn[i] << (32-shift));
if (i-k >= 0)
pn[i-k] |= (a.pn[i] >> shift);
}
return *this;
}
base_uint& operator+=(const base_uint& b)
{
uint64_t carry = 0;
for (int i = 0; i < WIDTH; i++)
{
uint64_t n = carry + pn[i] + b.pn[i];
pn[i] = n & 0xffffffff;
carry = n >> 32;
}
return *this;
}
base_uint& operator-=(const base_uint& b)
{
*this += -b;
return *this;
}
base_uint& operator+=(uint64_t b64)
{
base_uint b;
b = b64;
*this += b;
return *this;
}
base_uint& operator-=(uint64_t b64)
{
base_uint b;
b = b64;
*this += -b;
return *this;
}
base_uint& operator++()
{
// prefix operator
int i = 0;
while (++pn[i] == 0 && i < WIDTH-1)
i++;
return *this;
}
const base_uint operator++(int)
{
// postfix operator
const base_uint ret = *this;
++(*this);
return ret;
}
base_uint& operator--()
{
// prefix operator
int i = 0;
while (--pn[i] == -1 && i < WIDTH-1)
i++;
return *this;
}
const base_uint operator--(int)
{
// postfix operator
const base_uint ret = *this;
--(*this);
return ret;
}
friend inline bool operator<(const base_uint& a, const base_uint& b)
{
for (int i = base_uint::WIDTH-1; i >= 0; i--)
{
if (a.pn[i] < b.pn[i])
return true;
else if (a.pn[i] > b.pn[i])
return false;
}
return false;
}
friend inline bool operator<=(const base_uint& a, const base_uint& b)
{
for (int i = base_uint::WIDTH-1; i >= 0; i--)
{
if (a.pn[i] < b.pn[i])
return true;
else if (a.pn[i] > b.pn[i])
return false;
}
return true;
}
friend inline bool operator>(const base_uint& a, const base_uint& b)
{
for (int i = base_uint::WIDTH-1; i >= 0; i--)
{
if (a.pn[i] > b.pn[i])
return true;
else if (a.pn[i] < b.pn[i])
return false;
}
return false;
}
friend inline bool operator>=(const base_uint& a, const base_uint& b)
{
for (int i = base_uint::WIDTH-1; i >= 0; i--)
{
if (a.pn[i] > b.pn[i])
return true;
else if (a.pn[i] < b.pn[i])
return false;
}
return true;
}
friend inline bool operator==(const base_uint& a, const base_uint& b)
{
for (int i = 0; i < base_uint::WIDTH; i++)
if (a.pn[i] != b.pn[i])
return false;
return true;
}
friend inline bool operator==(const base_uint& a, uint64_t b)
{
if (a.pn[0] != (unsigned int)b)
return false;
if (a.pn[1] != (unsigned int)(b >> 32))
return false;
for (int i = 2; i < base_uint::WIDTH; i++)
if (a.pn[i] != 0)
return false;
return true;
}
friend inline bool operator!=(const base_uint& a, const base_uint& b)
{
return (!(a == b));
}
friend inline bool operator!=(const base_uint& a, uint64_t b)
{
return (!(a == b));
}
std::string GetHex() const
{
char psz[sizeof(pn)*2 + 1];
for (unsigned int i = 0; i < sizeof(pn); i++)
sprintf(psz + i*2, "%02x", ((unsigned char*)pn)[sizeof(pn) - i - 1]);
return std::string(psz, psz + sizeof(pn)*2);
}
void SetHex(const char* psz)
{
for (int i = 0; i < WIDTH; i++)
pn[i] = 0;
// skip leading spaces
while (isspace(*psz))
psz++;
// skip 0x
if (psz[0] == '0' && tolower(psz[1]) == 'x')
psz += 2;
// hex string to uint
static const unsigned char phexdigit[256] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,1,2,3,4,5,6,7,8,9,0,0,0,0,0,0, 0,0xa,0xb,0xc,0xd,0xe,0xf,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0xa,0xb,0xc,0xd,0xe,0xf,0,0,0,0,0,0,0,0,0 };
const char* pbegin = psz;
while (phexdigit[(unsigned char)*psz] || *psz == '0')
psz++;
psz--;
unsigned char* p1 = (unsigned char*)pn;
unsigned char* pend = p1 + WIDTH * 4;
while (psz >= pbegin && p1 < pend)
{
*p1 = phexdigit[(unsigned char)*psz--];
if (psz >= pbegin)
{
*p1 |= (phexdigit[(unsigned char)*psz--] << 4);
p1++;
}
}
}
void SetHex(const std::string& str)
{
SetHex(str.c_str());
}
std::string ToString() const
{
return (GetHex());
}
unsigned char* begin()
{
return (unsigned char*)&pn[0];
}
unsigned char* end()
{
return (unsigned char*)&pn[WIDTH];
}
const unsigned char* begin() const
{
return (unsigned char*)&pn[0];
}
const unsigned char* end() const
{
return (unsigned char*)&pn[WIDTH];
}
unsigned int size()
{
return sizeof(pn);
}
uint64_t Get64(int n=0) const
{
return pn[2*n] | (uint64_t)pn[2*n+1] << 32;
}
unsigned int GetSerializeSize(int nType, int nVersion) const
{
return sizeof(pn);
}
template<typename Stream>
void Serialize(Stream& s, int nType, int nVersion) const
{
s.write((char*)pn, sizeof(pn));
}
template<typename Stream>
void Unserialize(Stream& s, int nType, int nVersion)
{
s.read((char*)pn, sizeof(pn));
}
friend class uint160;
friend class uint256;
friend class uint512;
friend inline int Testuint256AdHoc(std::vector<std::string> vArg);
};
typedef base_uint<160> base_uint160;
typedef base_uint<256> base_uint256;
typedef base_uint<512> base_uint512;
//
// uint160 and uint256 could be implemented as templates, but to keep
// compile errors and debugging cleaner, they're copy and pasted.
//
//////////////////////////////////////////////////////////////////////////////
//
// uint160
//
/** 160-bit unsigned integer */
class uint160 : public base_uint160
{
public:
typedef base_uint160 basetype;
uint160()
{
for (int i = 0; i < WIDTH; i++)
pn[i] = 0;
}
uint160(const basetype& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] = b.pn[i];
}
uint160& operator=(const basetype& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] = b.pn[i];
return *this;
}
uint160(uint64_t b)
{
pn[0] = (unsigned int)b;
pn[1] = (unsigned int)(b >> 32);
for (int i = 2; i < WIDTH; i++)
pn[i] = 0;
}
uint160& operator=(uint64_t b)
{
pn[0] = (unsigned int)b;
pn[1] = (unsigned int)(b >> 32);
for (int i = 2; i < WIDTH; i++)
pn[i] = 0;
return *this;
}
explicit uint160(const std::string& str)
{
SetHex(str);
}
explicit uint160(const std::vector<unsigned char>& vch)
{
if (vch.size() == sizeof(pn))
memcpy(pn, &vch[0], sizeof(pn));
else
*this = 0;
}
};
inline bool operator==(const uint160& a, uint64_t b) { return (base_uint160)a == b; }
inline bool operator!=(const uint160& a, uint64_t b) { return (base_uint160)a != b; }
inline const uint160 operator<<(const base_uint160& a, unsigned int shift) { return uint160(a) <<= shift; }
inline const uint160 operator>>(const base_uint160& a, unsigned int shift) { return uint160(a) >>= shift; }
inline const uint160 operator<<(const uint160& a, unsigned int shift) { return uint160(a) <<= shift; }
inline const uint160 operator>>(const uint160& a, unsigned int shift) { return uint160(a) >>= shift; }
inline const uint160 operator^(const base_uint160& a, const base_uint160& b) { return uint160(a) ^= b; }
inline const uint160 operator&(const base_uint160& a, const base_uint160& b) { return uint160(a) &= b; }
inline const uint160 operator|(const base_uint160& a, const base_uint160& b) { return uint160(a) |= b; }
inline const uint160 operator+(const base_uint160& a, const base_uint160& b) { return uint160(a) += b; }
inline const uint160 operator-(const base_uint160& a, const base_uint160& b) { return uint160(a) -= b; }
inline bool operator<(const base_uint160& a, const uint160& b) { return (base_uint160)a < (base_uint160)b; }
inline bool operator<=(const base_uint160& a, const uint160& b) { return (base_uint160)a <= (base_uint160)b; }
inline bool operator>(const base_uint160& a, const uint160& b) { return (base_uint160)a > (base_uint160)b; }
inline bool operator>=(const base_uint160& a, const uint160& b) { return (base_uint160)a >= (base_uint160)b; }
inline bool operator==(const base_uint160& a, const uint160& b) { return (base_uint160)a == (base_uint160)b; }
inline bool operator!=(const base_uint160& a, const uint160& b) { return (base_uint160)a != (base_uint160)b; }
inline const uint160 operator^(const base_uint160& a, const uint160& b) { return (base_uint160)a ^ (base_uint160)b; }
inline const uint160 operator&(const base_uint160& a, const uint160& b) { return (base_uint160)a & (base_uint160)b; }
inline const uint160 operator|(const base_uint160& a, const uint160& b) { return (base_uint160)a | (base_uint160)b; }
inline const uint160 operator+(const base_uint160& a, const uint160& b) { return (base_uint160)a + (base_uint160)b; }
inline const uint160 operator-(const base_uint160& a, const uint160& b) { return (base_uint160)a - (base_uint160)b; }
inline bool operator<(const uint160& a, const base_uint160& b) { return (base_uint160)a < (base_uint160)b; }
inline bool operator<=(const uint160& a, const base_uint160& b) { return (base_uint160)a <= (base_uint160)b; }
inline bool operator>(const uint160& a, const base_uint160& b) { return (base_uint160)a > (base_uint160)b; }
inline bool operator>=(const uint160& a, const base_uint160& b) { return (base_uint160)a >= (base_uint160)b; }
inline bool operator==(const uint160& a, const base_uint160& b) { return (base_uint160)a == (base_uint160)b; }
inline bool operator!=(const uint160& a, const base_uint160& b) { return (base_uint160)a != (base_uint160)b; }
inline const uint160 operator^(const uint160& a, const base_uint160& b) { return (base_uint160)a ^ (base_uint160)b; }
inline const uint160 operator&(const uint160& a, const base_uint160& b) { return (base_uint160)a & (base_uint160)b; }
inline const uint160 operator|(const uint160& a, const base_uint160& b) { return (base_uint160)a | (base_uint160)b; }
inline const uint160 operator+(const uint160& a, const base_uint160& b) { return (base_uint160)a + (base_uint160)b; }
inline const uint160 operator-(const uint160& a, const base_uint160& b) { return (base_uint160)a - (base_uint160)b; }
inline bool operator<(const uint160& a, const uint160& b) { return (base_uint160)a < (base_uint160)b; }
inline bool operator<=(const uint160& a, const uint160& b) { return (base_uint160)a <= (base_uint160)b; }
inline bool operator>(const uint160& a, const uint160& b) { return (base_uint160)a > (base_uint160)b; }
inline bool operator>=(const uint160& a, const uint160& b) { return (base_uint160)a >= (base_uint160)b; }
inline bool operator==(const uint160& a, const uint160& b) { return (base_uint160)a == (base_uint160)b; }
inline bool operator!=(const uint160& a, const uint160& b) { return (base_uint160)a != (base_uint160)b; }
inline const uint160 operator^(const uint160& a, const uint160& b) { return (base_uint160)a ^ (base_uint160)b; }
inline const uint160 operator&(const uint160& a, const uint160& b) { return (base_uint160)a & (base_uint160)b; }
inline const uint160 operator|(const uint160& a, const uint160& b) { return (base_uint160)a | (base_uint160)b; }
inline const uint160 operator+(const uint160& a, const uint160& b) { return (base_uint160)a + (base_uint160)b; }
inline const uint160 operator-(const uint160& a, const uint160& b) { return (base_uint160)a - (base_uint160)b; }
//////////////////////////////////////////////////////////////////////////////
//
// uint256
//
/** 256-bit unsigned integer */
class uint256 : public base_uint256
{
public:
typedef base_uint256 basetype;
uint256()
{
for (int i = 0; i < WIDTH; i++)
pn[i] = 0;
}
uint256(const basetype& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] = b.pn[i];
}
uint256& operator=(const basetype& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] = b.pn[i];
return *this;
}
uint256(uint64_t b)
{
pn[0] = (unsigned int)b;
pn[1] = (unsigned int)(b >> 32);
for (int i = 2; i < WIDTH; i++)
pn[i] = 0;
}
uint256& operator=(uint64_t b)
{
pn[0] = (unsigned int)b;
pn[1] = (unsigned int)(b >> 32);
for (int i = 2; i < WIDTH; i++)
pn[i] = 0;
return *this;
}
explicit uint256(const std::string& str)
{
SetHex(str);
}
explicit uint256(const std::vector<unsigned char>& vch)
{
if (vch.size() == sizeof(pn))
memcpy(pn, &vch[0], sizeof(pn));
else
*this = 0;
}
};
inline bool operator==(const uint256& a, uint64_t b) { return (base_uint256)a == b; }
inline bool operator!=(const uint256& a, uint64_t b) { return (base_uint256)a != b; }
inline const uint256 operator<<(const base_uint256& a, unsigned int shift) { return uint256(a) <<= shift; }
inline const uint256 operator>>(const base_uint256& a, unsigned int shift) { return uint256(a) >>= shift; }
inline const uint256 operator<<(const uint256& a, unsigned int shift) { return uint256(a) <<= shift; }
inline const uint256 operator>>(const uint256& a, unsigned int shift) { return uint256(a) >>= shift; }
inline const uint256 operator^(const base_uint256& a, const base_uint256& b) { return uint256(a) ^= b; }
inline const uint256 operator&(const base_uint256& a, const base_uint256& b) { return uint256(a) &= b; }
inline const uint256 operator|(const base_uint256& a, const base_uint256& b) { return uint256(a) |= b; }
inline const uint256 operator+(const base_uint256& a, const base_uint256& b) { return uint256(a) += b; }
inline const uint256 operator-(const base_uint256& a, const base_uint256& b) { return uint256(a) -= b; }
inline bool operator<(const base_uint256& a, const uint256& b) { return (base_uint256)a < (base_uint256)b; }
inline bool operator<=(const base_uint256& a, const uint256& b) { return (base_uint256)a <= (base_uint256)b; }
inline bool operator>(const base_uint256& a, const uint256& b) { return (base_uint256)a > (base_uint256)b; }
inline bool operator>=(const base_uint256& a, const uint256& b) { return (base_uint256)a >= (base_uint256)b; }
inline bool operator==(const base_uint256& a, const uint256& b) { return (base_uint256)a == (base_uint256)b; }
inline bool operator!=(const base_uint256& a, const uint256& b) { return (base_uint256)a != (base_uint256)b; }
inline const uint256 operator^(const base_uint256& a, const uint256& b) { return (base_uint256)a ^ (base_uint256)b; }
inline const uint256 operator&(const base_uint256& a, const uint256& b) { return (base_uint256)a & (base_uint256)b; }
inline const uint256 operator|(const base_uint256& a, const uint256& b) { return (base_uint256)a | (base_uint256)b; }
inline const uint256 operator+(const base_uint256& a, const uint256& b) { return (base_uint256)a + (base_uint256)b; }
inline const uint256 operator-(const base_uint256& a, const uint256& b) { return (base_uint256)a - (base_uint256)b; }
inline bool operator<(const uint256& a, const base_uint256& b) { return (base_uint256)a < (base_uint256)b; }
inline bool operator<=(const uint256& a, const base_uint256& b) { return (base_uint256)a <= (base_uint256)b; }
inline bool operator>(const uint256& a, const base_uint256& b) { return (base_uint256)a > (base_uint256)b; }
inline bool operator>=(const uint256& a, const base_uint256& b) { return (base_uint256)a >= (base_uint256)b; }
inline bool operator==(const uint256& a, const base_uint256& b) { return (base_uint256)a == (base_uint256)b; }
inline bool operator!=(const uint256& a, const base_uint256& b) { return (base_uint256)a != (base_uint256)b; }
inline const uint256 operator^(const uint256& a, const base_uint256& b) { return (base_uint256)a ^ (base_uint256)b; }
inline const uint256 operator&(const uint256& a, const base_uint256& b) { return (base_uint256)a & (base_uint256)b; }
inline const uint256 operator|(const uint256& a, const base_uint256& b) { return (base_uint256)a | (base_uint256)b; }
inline const uint256 operator+(const uint256& a, const base_uint256& b) { return (base_uint256)a + (base_uint256)b; }
inline const uint256 operator-(const uint256& a, const base_uint256& b) { return (base_uint256)a - (base_uint256)b; }
inline bool operator<(const uint256& a, const uint256& b) { return (base_uint256)a < (base_uint256)b; }
inline bool operator<=(const uint256& a, const uint256& b) { return (base_uint256)a <= (base_uint256)b; }
inline bool operator>(const uint256& a, const uint256& b) { return (base_uint256)a > (base_uint256)b; }
inline bool operator>=(const uint256& a, const uint256& b) { return (base_uint256)a >= (base_uint256)b; }
inline bool operator==(const uint256& a, const uint256& b) { return (base_uint256)a == (base_uint256)b; }
inline bool operator!=(const uint256& a, const uint256& b) { return (base_uint256)a != (base_uint256)b; }
inline const uint256 operator^(const uint256& a, const uint256& b) { return (base_uint256)a ^ (base_uint256)b; }
inline const uint256 operator&(const uint256& a, const uint256& b) { return (base_uint256)a & (base_uint256)b; }
inline const uint256 operator|(const uint256& a, const uint256& b) { return (base_uint256)a | (base_uint256)b; }
inline const uint256 operator+(const uint256& a, const uint256& b) { return (base_uint256)a + (base_uint256)b; }
inline const uint256 operator-(const uint256& a, const uint256& b) { return (base_uint256)a - (base_uint256)b; }
//////////////////////////////////////////////////////////////////////////////
//
// uint512
//
/** 512-bit unsigned integer */
class uint512 : public base_uint512
{
public:
typedef base_uint512 basetype;
uint512()
{
for (int i = 0; i < WIDTH; i++)
pn[i] = 0;
}
uint512(const basetype& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] = b.pn[i];
}
uint512& operator=(const basetype& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] = b.pn[i];
return *this;
}
uint512(uint64_t b)
{
pn[0] = (unsigned int)b;
pn[1] = (unsigned int)(b >> 32);
for (int i = 2; i < WIDTH; i++)
pn[i] = 0;
}
uint512& operator=(uint64_t b)
{
pn[0] = (unsigned int)b;
pn[1] = (unsigned int)(b >> 32);
for (int i = 2; i < WIDTH; i++)
pn[i] = 0;
return *this;
}
explicit uint512(const std::string& str)
{
SetHex(str);
}
explicit uint512(const std::vector<unsigned char>& vch)
{
if (vch.size() == sizeof(pn))
memcpy(pn, &vch[0], sizeof(pn));
else
*this = 0;
}
uint256 trim256() const
{
uint256 ret;
for (unsigned int i = 0; i < uint256::WIDTH; i++){
ret.pn[i] = pn[i];
}
return ret;
}
};
inline bool operator==(const uint512& a, uint64_t b) { return (base_uint512)a == b; }
inline bool operator!=(const uint512& a, uint64_t b) { return (base_uint512)a != b; }
inline const uint512 operator<<(const base_uint512& a, unsigned int shift) { return uint512(a) <<= shift; }
inline const uint512 operator>>(const base_uint512& a, unsigned int shift) { return uint512(a) >>= shift; }
inline const uint512 operator<<(const uint512& a, unsigned int shift) { return uint512(a) <<= shift; }
inline const uint512 operator>>(const uint512& a, unsigned int shift) { return uint512(a) >>= shift; }
inline const uint512 operator^(const base_uint512& a, const base_uint512& b) { return uint512(a) ^= b; }
inline const uint512 operator&(const base_uint512& a, const base_uint512& b) { return uint512(a) &= b; }
inline const uint512 operator|(const base_uint512& a, const base_uint512& b) { return uint512(a) |= b; }
inline const uint512 operator+(const base_uint512& a, const base_uint512& b) { return uint512(a) += b; }
inline const uint512 operator-(const base_uint512& a, const base_uint512& b) { return uint512(a) -= b; }
inline bool operator<(const base_uint512& a, const uint512& b) { return (base_uint512)a < (base_uint512)b; }
inline bool operator<=(const base_uint512& a, const uint512& b) { return (base_uint512)a <= (base_uint512)b; }
inline bool operator>(const base_uint512& a, const uint512& b) { return (base_uint512)a > (base_uint512)b; }
inline bool operator>=(const base_uint512& a, const uint512& b) { return (base_uint512)a >= (base_uint512)b; }
inline bool operator==(const base_uint512& a, const uint512& b) { return (base_uint512)a == (base_uint512)b; }
inline bool operator!=(const base_uint512& a, const uint512& b) { return (base_uint512)a != (base_uint512)b; }
inline const uint512 operator^(const base_uint512& a, const uint512& b) { return (base_uint512)a ^ (base_uint512)b; }
inline const uint512 operator&(const base_uint512& a, const uint512& b) { return (base_uint512)a & (base_uint512)b; }
inline const uint512 operator|(const base_uint512& a, const uint512& b) { return (base_uint512)a | (base_uint512)b; }
inline const uint512 operator+(const base_uint512& a, const uint512& b) { return (base_uint512)a + (base_uint512)b; }
inline const uint512 operator-(const base_uint512& a, const uint512& b) { return (base_uint512)a - (base_uint512)b; }
inline bool operator<(const uint512& a, const base_uint512& b) { return (base_uint512)a < (base_uint512)b; }
inline bool operator<=(const uint512& a, const base_uint512& b) { return (base_uint512)a <= (base_uint512)b; }
inline bool operator>(const uint512& a, const base_uint512& b) { return (base_uint512)a > (base_uint512)b; }
inline bool operator>=(const uint512& a, const base_uint512& b) { return (base_uint512)a >= (base_uint512)b; }
inline bool operator==(const uint512& a, const base_uint512& b) { return (base_uint512)a == (base_uint512)b; }
inline bool operator!=(const uint512& a, const base_uint512& b) { return (base_uint512)a != (base_uint512)b; }
inline const uint512 operator^(const uint512& a, const base_uint512& b) { return (base_uint512)a ^ (base_uint512)b; }
inline const uint512 operator&(const uint512& a, const base_uint512& b) { return (base_uint512)a & (base_uint512)b; }
inline const uint512 operator|(const uint512& a, const base_uint512& b) { return (base_uint512)a | (base_uint512)b; }
inline const uint512 operator+(const uint512& a, const base_uint512& b) { return (base_uint512)a + (base_uint512)b; }
inline const uint512 operator-(const uint512& a, const base_uint512& b) { return (base_uint512)a - (base_uint512)b; }
inline bool operator<(const uint512& a, const uint512& b) { return (base_uint512)a < (base_uint512)b; }
inline bool operator<=(const uint512& a, const uint512& b) { return (base_uint512)a <= (base_uint512)b; }
inline bool operator>(const uint512& a, const uint512& b) { return (base_uint512)a > (base_uint512)b; }
inline bool operator>=(const uint512& a, const uint512& b) { return (base_uint512)a >= (base_uint512)b; }
inline bool operator==(const uint512& a, const uint512& b) { return (base_uint512)a == (base_uint512)b; }
inline bool operator!=(const uint512& a, const uint512& b) { return (base_uint512)a != (base_uint512)b; }
inline const uint512 operator^(const uint512& a, const uint512& b) { return (base_uint512)a ^ (base_uint512)b; }
inline const uint512 operator&(const uint512& a, const uint512& b) { return (base_uint512)a & (base_uint512)b; }
inline const uint512 operator|(const uint512& a, const uint512& b) { return (base_uint512)a | (base_uint512)b; }
inline const uint512 operator+(const uint512& a, const uint512& b) { return (base_uint512)a + (base_uint512)b; }
inline const uint512 operator-(const uint512& a, const uint512& b) { return (base_uint512)a - (base_uint512)b; }
#ifdef TEST_UINT256
inline int Testuint256AdHoc(std::vector<std::string> vArg)
{
uint256 g(0);
printf("%s\n", g.ToString().c_str());
g--; printf("g--\n");
printf("%s\n", g.ToString().c_str());
g--; printf("g--\n");
printf("%s\n", g.ToString().c_str());
g++; printf("g++\n");
printf("%s\n", g.ToString().c_str());
g++; printf("g++\n");
printf("%s\n", g.ToString().c_str());
g++; printf("g++\n");
printf("%s\n", g.ToString().c_str());
g++; printf("g++\n");
printf("%s\n", g.ToString().c_str());
uint256 a(7);
printf("a=7\n");
printf("%s\n", a.ToString().c_str());
uint256 b;
printf("b undefined\n");
printf("%s\n", b.ToString().c_str());
int c = 3;
a = c;
a.pn[3] = 15;
printf("%s\n", a.ToString().c_str());
uint256 k(c);
a = 5;
a.pn[3] = 15;
printf("%s\n", a.ToString().c_str());
b = 1;
b <<= 52;
a |= b;
a ^= 0x500;
printf("a %s\n", a.ToString().c_str());
a = a | b | (uint256)0x1000;
printf("a %s\n", a.ToString().c_str());
printf("b %s\n", b.ToString().c_str());
a = 0xfffffffe;
a.pn[4] = 9;
printf("%s\n", a.ToString().c_str());
a++;
printf("%s\n", a.ToString().c_str());
a++;
printf("%s\n", a.ToString().c_str());
a++;
printf("%s\n", a.ToString().c_str());
a++;
printf("%s\n", a.ToString().c_str());
a--;
printf("%s\n", a.ToString().c_str());
a--;
printf("%s\n", a.ToString().c_str());
a--;
printf("%s\n", a.ToString().c_str());
uint256 d = a--;
printf("%s\n", d.ToString().c_str());
printf("%s\n", a.ToString().c_str());
a--;
printf("%s\n", a.ToString().c_str());
a--;
printf("%s\n", a.ToString().c_str());
d = a;
printf("%s\n", d.ToString().c_str());
for (int i = uint256::WIDTH-1; i >= 0; i--) printf("%08x", d.pn[i]); printf("\n");
uint256 neg = d;
neg = ~neg;
printf("%s\n", neg.ToString().c_str());
uint256 e = uint256("0xABCDEF123abcdef12345678909832180000011111111");
printf("\n");
printf("%s\n", e.ToString().c_str());
printf("\n");
uint256 x1 = uint256("0xABCDEF123abcdef12345678909832180000011111111");
uint256 x2;
printf("%s\n", x1.ToString().c_str());
for (int i = 0; i < 270; i += 4)
{
x2 = x1 << i;
printf("%s\n", x2.ToString().c_str());
}
printf("\n");
printf("%s\n", x1.ToString().c_str());
for (int i = 0; i < 270; i += 4)
{
x2 = x1;
x2 >>= i;
printf("%s\n", x2.ToString().c_str());
}
for (int i = 0; i < 100; i++)
{
uint256 k = (~uint256(0) >> i);
printf("%s\n", k.ToString().c_str());
}
for (int i = 0; i < 100; i++)
{
uint256 k = (~uint256(0) << i);
printf("%s\n", k.ToString().c_str());
}
return (0);
}
#endif
#endif
| [
"[email protected]"
] | |
e6e67eff52be0ac8c59752f001ffbcc43eea506b | 80d2f7deb79e7ebace8ec3393bb6d41d01cb038b | /binkd/ftnq.cpp | 075d7b45741d9125d4bef5c7fe532e46e68ab815 | [] | no_license | kosfango/fips | 6558729e2ab17a49c37bf171302a7dec6fcff98c | a8191bbd3c7c72f0ff6e82e7c4ac5b507d01d9e6 | refs/heads/master | 2021-01-17T16:09:32.406267 | 2016-08-10T23:02:42 | 2016-08-10T23:02:42 | 63,811,332 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,223 | cpp |
#include "stdafx.h"
#include <sys/stat.h>
#include "readcfg.h"
#include "readdir.h"
#include "ftnq.h"
const char prio[] = "IiCcDdOoFfHh";
static const char flo_flvrs[] = "icdfhICDFH";
static const char out_flvrs[] = "icdohICDOH";
static FTNQ *q_add_dir (FTNQ *q, char *dir, FTN_ADDR *fa1);
FTNQ *q_add_file (FTNQ *q, char *filename, FTN_ADDR *fa1, char flvr, char action, char type);
/*
* q_free(): frees memory allocated by q_scan()
*/
static int qn_free (FTN_NODE *fn, void *arg)
{
fn->hold_until = 0;
fn->mail_flvr = fn->files_flvr = 0;
fn->busy = 0;
return 0;
}
void q_free (FTNQ *q)
{
if (q != SCAN_LISTED)
{
FTNQ *last = 0;
while (q)
{
last = q;
q = q->next;
}
while (last)
{
if (!last->prev)
{
free (last);
break;
}
else
{
last = last->prev;
if (last->next)
free (last->next);
}
}
}
else
foreach_node (qn_free, 0);
}
/*
* q_scan: scans outbound. Return value must be q_free()'d.
*/
static int qn_scan (FTN_NODE *fn, void *arg)
{
char buf[FTN_ADDR_SZ + 1];
ftnaddress_to_str (buf, &fn->fa);
*(FTNQ **) arg = q_scan_boxes (*(FTNQ **) arg, &fn->fa, 1);
return 0;
}
FTNQ *q_scan (FTNQ *q)
{
char *s;
char buf[MAXPATHLEN + 1], outb_path[MAXPATHLEN + 1];
extern FTN_DOMAIN *pDomains;
FTN_DOMAIN *curr_domain;
for (curr_domain = pDomains; curr_domain; curr_domain = curr_domain->next)
{
DIR *dp;
struct dirent *de;
int len;
if (curr_domain->alias4 == 0)
{
strnzcpy (outb_path, curr_domain->path, sizeof (buf) - 1);
/* `FOO:/bar means FOO:\..\bar on Amiga */
#ifndef AMIGA
if (outb_path[strlen (outb_path) - 1] == ':')
strcat (outb_path, PATH_SEPARATOR);
#endif
if ((dp = opendir (outb_path)) == 0)
{
Log (1, "cannot opendir %s: %s", outb_path, strerror (errno));
continue;
}
len = strlen (curr_domain->dir);
strnzcpy (buf, curr_domain->path, sizeof (buf));
strnzcpy (buf + strlen (buf), PATH_SEPARATOR, sizeof (buf) - strlen (buf));
s = buf + strlen (buf);
while ((de = readdir (dp)) != 0)
{
if (!STRNICMP (de->d_name, curr_domain->dir, len) &&
(de->d_name[len] == 0 ||
(de->d_name[len] == '.' && isxdigit (de->d_name[len + 1]))))
{
FTN_ADDR fa;
FA_ZERO (&fa);
fa.z = ((de->d_name[len] == '.') ?
strtol (de->d_name + len + 1, (char **) NULL, 16) :
curr_domain->z[0]);
if (de->d_name[len] == 0 || fa.z != curr_domain->z[0])
{
strcpy (fa.domain, curr_domain->name);
strnzcpy (buf + strlen (buf), de->d_name, sizeof (buf) - strlen (buf));
q = q_add_dir (q, buf, &fa);
}
*s = 0;
}
}
closedir (dp);
}
}
foreach_node (qn_scan, &q);
return q;
}
/*
* Adds to the q all files for n akas stored in fa
*/
FTNQ *q_scan_addrs (FTNQ *q, FTN_ADDR *fa, int n)
{
char buf[MAXPATHLEN + 1];
int i;
char *s;
for (i = 0; i < n; ++i)
{
ftnaddress_to_filename (buf, fa + i);
if (*buf)
{
if ((s = max (strrchr (buf, '\\'), strrchr (buf, '/'))) != 0)
{
*s = 0;
q = q_add_dir (q, buf, fa + i);
}
}
}
q = q_scan_boxes (q, fa, n);
return q;
}
static int weight_by_name (char *s)
{
if (ispkt (s))
return 100;
if (isarcmail (s))
return 50;
if (istic (s))
return -100;
return 0;
}
static int cmp_filebox_files (FTNQ *a, FTNQ *b)
{
int w_a = weight_by_name (a->path);
int w_b = weight_by_name (b->path);
if (w_a - w_b == 0)
return b->time - a->time;
else
return w_a - w_b;
}
#ifdef MAILBOX
static char to32(int N)
{
if ((N >= 0) && (N <=9)) return '0'+N;
if ((N > 9) && (N < 32)) return 'A'+ N - 10;
return 'Z'; /* fake return */
};
static struct {
char * ext;
char flv;
} brakeExt[] =
{
#ifdef UNIX
{"immediate", 'i'},
{"crash", 'c'},
{"direct", 'd'},
{"normal", 'f'},
{"hold", 'h'},
#endif
{"Immediate", 'i'},
{"Crash", 'c'},
{"Direct", 'd'},
{"Normal", 'f'},
{"Hold", 'h'}
};
#endif
static FTNQ *q_scan_box (FTNQ *q, FTN_ADDR *fa, char *boxpath, char flvr, int deleteempty)
{
FTNQ *files = NULL;
int n_files = 0, i;
DIR *dp;
char buf[MAXPATHLEN + 1], *s;
struct dirent *de;
struct stat sb;
strnzcpy (buf, boxpath, sizeof (buf));
strnzcat (buf, PATH_SEPARATOR, sizeof (buf));
s = buf + strlen (buf);
if ((dp = opendir (boxpath)) != NULL)
{
while ((de = readdir (dp)) != 0)
{
strnzcat (buf, de->d_name, sizeof (buf));
if (stat (buf, &sb) == 0 && (sb.st_mode & S_IFDIR) == 0 &&
de->d_name[0] != '.')
{
files = (struct _FTNQ *) xrealloc (files, sizeof (FTNQ) * (n_files + 1));
strcpy (files[n_files].path, buf);
files[n_files].time = sb.st_mtime;
memcpy (&files[n_files].fa, fa, sizeof (FTN_ADDR));
files[n_files].flvr = flvr;
++n_files;
}
*s = 0;
}
closedir (dp);
if (n_files == 0 && deleteempty) {
if (rmdir (boxpath) == 0)
Log (3, "Empty filebox %s deleted", boxpath);
else
Log (1, "Cannot delete empty filebox %s: %s", boxpath, strerror (errno));
}
}
if (files)
{
qsort (files, n_files, sizeof (FTNQ),
(int (*) (const void *, const void *)) cmp_filebox_files);
for (i = 0; i < n_files; ++i)
q = q_add_file (q, files[i].path, &files[i].fa, files[i].flvr, 'd', 0);
free (files);
}
return q;
}
/*
* Scans fileboxes for n akas stored in fa
*/
FTNQ *q_scan_boxes (FTNQ *q, FTN_ADDR *fa, int n)
{
FTN_NODE *node;
int i;
#ifdef MAILBOX
char buf[MAXPATHLEN + 1];
char *s;
int j;
#endif
for (i = 0; i < n; ++i)
{
#ifndef MAILBOX
if ((node = get_node_info (fa + i)) != NULL && node->obox != NULL)
{
q = q_scan_box (q, fa+i, node->obox, node->obox_flvr, 0);
}
#else
if ((node = get_node_info (fa + i)) != NULL && ((node->obox != NULL) || tfilebox[0] || bfilebox[0]))
{
if (node->obox)
q = q_scan_box (q, fa+i, node->obox, node->obox_flvr, 0);
if (bfilebox[0]) {
strnzcpy (buf, bfilebox, sizeof (buf));
strnzcat (buf, PATH_SEPARATOR, sizeof (buf));
#ifdef HAVE_SNPRINTF
snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
#else
sprintf(buf + strlen(buf),
#endif
"%s.%u.%u.%u.%u.",
node->fa.domain,
node->fa.z,
node->fa.net,
node->fa.node,
node->fa.p);
s = buf + strlen(buf);
for (j = 0; j < sizeof(brakeExt)/sizeof(brakeExt[0]); j++) {
strnzcat (buf, brakeExt[j].ext, sizeof (buf));
q = q_scan_box (q, fa+i, buf, brakeExt[j].flv, deleteablebox);
*s = '\0';
}
}
if (tfilebox[0]) {
strnzcpy ( buf, tfilebox, sizeof (buf));
strnzcat ( buf, PATH_SEPARATOR, sizeof (buf));
#ifdef HAVE_SNPRINTF
snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
#else
sprintf(buf + strlen(buf),
#endif
"%u.%u.%u.%u",
node->fa.z,
node->fa.net,
node->fa.node,
node->fa.p);
q = q_scan_box (q, fa+i, buf, 'f', deleteablebox);
strnzcat ( buf, ".h", sizeof (buf));
q = q_scan_box (q, fa+i, buf, 'h', deleteablebox);
strnzcpy ( buf, tfilebox, sizeof (buf));
strnzcat ( buf, PATH_SEPARATOR, sizeof (buf));
#ifdef HAVE_SNPRINTF
snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
#else
sprintf(buf + strlen(buf),
#endif
"%c%c%c%c%c%c%c%c.%c%c",
to32(node->fa.z/32), to32(node->fa.z%32),
to32(node->fa.net/1024), to32((node->fa.net/32)%32), to32(node->fa.net%32),
to32(node->fa.node/1024),to32((node->fa.node/32)%32),to32(node->fa.node%32),
to32(node->fa.p/32), to32(node->fa.p%32));
q = q_scan_box (q, fa+i, buf, 'f', deleteablebox);
strnzcat (buf, "h", sizeof (buf));
q = q_scan_box (q, fa+i, buf, 'h', deleteablebox);
}
}
#endif
}
return q;
}
void process_hld (FTN_ADDR *fa, char *path)
{
FTN_NODE *node = get_node_info (fa);
if (node)
{
FILE *f;
if ((f = fopen (path, "r")) == NULL ||
fscanf (f, "%ld", &node->hold_until) != 1)
{
node->hold_until = 0;
}
if (f)
fclose (f);
if (node->hold_until <= time (0))
{
node->hold_until = 0;
deletefile (path);
}
}
}
void process_bsy (FTN_ADDR *fa, char *path)
{
char *s = path + strlen (path) - 4;
FTN_NODE *node;
struct stat sb;
if (stat (path, &sb) == 0 && kill_old_bsy != 0
&& time (0) - sb.st_mtime > kill_old_bsy)
{
char buf[FTN_ADDR_SZ + 1];
ftnaddress_to_str (buf, fa);
Log (2, "found old %s file for %s", s, buf);
deletefile (path);
}
else if ((node = get_node_info (fa)) != 0 && node->busy != 'b' &&
(!STRICMP (s, ".bsy") || !STRICMP (s, ".csy")))
{
node->busy = tolower (s[1]);
}
}
/*
* Adds files from outbound directory _dir_ to _q_. _fa1_ is
* the address wildcard for this outbound. E.g.
* c:\bbs\outbound\ fa1 = 2:-1/-1.-1@fidonet
* or
* c:\bbs\outbound\00030004.pnt\ fa1 = 2:3/4.-1@fidonet
* or even
* c:\bbs\outbound\00030004.pnt\ fa1 = 2:3/4.5@fidonet
*/
static FTNQ *q_add_dir (FTNQ *q, char *dir, FTN_ADDR *fa1)
{
DIR *dp;
FTN_ADDR fa2;
char buf[MAXPATHLEN + 1];
int j;
char *s;
if ((dp = opendir (dir)) != 0)
{
struct dirent *de;
while ((de = readdir (dp)) != 0)
{
s = de->d_name;
for (j = 0; j < 8; ++j)
if (!isxdigit (s[j]))
break;
if (j == 8 && strchr (s, 0) - s == 12 &&
strchr (s, '.') - s == 8 && strrchr (s, '.') - s == 8)
{
/* fa2 will store dest.address for the current (de->d_name) file */
memcpy (&fa2, fa1, sizeof (FTN_ADDR));
if (fa1->node != -1 && fa1->p != 0)
sscanf (s, "%8x", &fa2.p); /* We now in /xxxxyyyy.pnt */
else
sscanf (s, "%4x%4x", &fa2.net, &fa2.node);
/* add the file if wildcard (f1) match the address (fa2) */
if (fa1->node == -1 || fa1->p == -1 || !ftnaddress_cmp (fa1, &fa2))
{
strnzcpy (buf, dir, sizeof (buf));
strnzcpy (buf + strlen (buf), PATH_SEPARATOR,
sizeof (buf) - strlen (buf));
strnzcpy (buf + strlen (buf), s, sizeof (buf) - strlen (buf));
if (!STRICMP (s + 9, "pnt") && fa2.p == -1)
{
struct stat sb;
if (stat (buf, &sb) == 0 && sb.st_mode & S_IFDIR)
q = q_add_dir (q, buf, &fa2);
}
else
{
if (fa2.p == -1)
fa2.p = 0;
if (!STRICMP (s + 9, "bsy") || !STRICMP (s + 9, "csy"))
process_bsy (&fa2, buf);
if (get_node_info (&fa2) || is5D (fa1))
{
if (strchr (out_flvrs, s[9]) &&
tolower (s[10]) == 'u' && tolower (s[11]) == 't')
{
/* Adding *.?ut */
q = q_add_file (q, buf, &fa2, s[9], 'd', 'm');
}
else if (!STRICMP (s + 9, "req"))
{
/* Adding *.req */
q = q_add_file (q, buf, &fa2, 'h', 's', 'r');
}
else if (!STRICMP (s + 9, "hld"))
{
process_hld (&fa2, buf);
}
else if (strchr (flo_flvrs, s[9]) &&
tolower (s[10]) == 'l' && tolower (s[11]) == 'o')
{
/* Adding *.?lo */
q = q_add_file (q, buf, &fa2, s[9], 'd', 'l');
}
else if (!STRICMP (s + 9, "stc"))
{
/* Adding *.stc */
q = q_add_file (q, buf, &fa2, 'h', 0, 's');
}
}
}
}
}
}
closedir (dp);
}
else
Log (1, "cannot opendir %s: %s", dir, strerror (errno));
return q;
}
/*
* Add a file to the queue.
*/
FTNQ *q_add_file (FTNQ *q, char *filename, FTN_ADDR *fa1, char flvr, char action, char type)
{
const int argc=3;
char *argv[3];
char str[MAXPATHLEN+1];
if (q != SCAN_LISTED)
{
FTNQ *new_file;
if (type == 's')
{ char *p;
FILE *f;
f = fopen(filename, "r");
if (f == NULL)
{ Log(1, "Can't open %s: %s", filename, strerror(errno));
return q;
}
if (!fgets(str, sizeof(str), f))
{ Log(1, "Incorrect status (can't fgets), ignored");
fclose(f);
return q;
}
fclose(f);
if (*str && isspace(*str))
{ Log(1, "Incorrect status (space first), ignored");
return q;
}
for (p=str+strlen(str)-1; isspace(*p); *p--='\0');
Log(2, "Status is '%s'", str);
if (!parse_args (argc, argv, str, "Status"))
{ Log(1, "Incorrect status, ignored");
return q;
}
}
new_file = (struct _FTNQ *) xalloc (sizeof (FTNQ));
FQ_ZERO (new_file);
new_file->next = q;
if (q)
q->prev = new_file;
q = new_file;
if (fa1)
memcpy (&q->fa, fa1, sizeof (FTN_ADDR));
q->flvr = flvr;
q->action = action;
q->type = type;
q->sent = 0;
if (type == 's')
{ q->size = atol(argv[1]);
q->time = atol(argv[2]);
strnzcpy (q->path, argv[0], MAXPATHLEN);
}
else
strnzcpy (q->path, filename, MAXPATHLEN);
}
else
{
FTN_NODE *node = get_node_info (fa1);
if (node)
{
if (type == 'm')
node->mail_flvr = MAXFLVR (flvr, node->mail_flvr);
else
node->files_flvr = MAXFLVR (flvr, node->files_flvr);
}
}
return q;
}
/*
* q_list: just lists q, not more
*/
typedef struct
{
int first_pass;
FILE *out;
} qn_list_arg;
static int qn_list (FTN_NODE *fn, void *arg)
{
char tmp[60], buf[FTN_ADDR_SZ + 1];
qn_list_arg *a = (qn_list_arg *) arg;
if (fn->mail_flvr || fn->files_flvr || fn->busy)
{
if (fn->hold_until > 0)
{
struct tm *tm;
#ifdef __WATCOMC__
struct tm stm;
tm = &stm;
_localtime (&fn->hold_until, tm);
#else
tm = localtime (&fn->hold_until);
#endif
strftime (tmp, sizeof (tmp), " (hold until %Y/%m/%d %H:%M:%S)", tm);
}
else
*tmp = 0;
ftnaddress_to_str (buf, &fn->fa);
fprintf (a->out, "%c %c%c %s%s%s\n",
a->first_pass ? '$' : ' ', fn->mail_flvr ? fn->mail_flvr : '-',
fn->files_flvr ? fn->files_flvr : '-', buf, tmp,
fn->busy ? (fn->busy == 'c' ? "\tcall" : "\tbusy") : "");
if (a->first_pass)
a->first_pass = 0;
}
return 0;
}
void q_list (FILE *out, FTNQ *q)
{
char buf[FTN_ADDR_SZ + 1];
if (q == SCAN_LISTED)
{
qn_list_arg qnla;
qnla.first_pass = 1;
qnla.out = out;
foreach_node (qn_list, &qnla);
}
else
{
for (; q; q = q->next)
{
if (!q->sent)
{
ftnaddress_to_str (buf, &q->fa);
fprintf (out, "%-20s %c%c%c %8lu %s\n",
buf, q->flvr, q->action ? q->action : '-',
q->type ? q->type : '-',
q->size, q->path);
}
}
}
}
/*
* Selects from q the next file for fa (Returns a pointer to a q element)
*/
FTNQ *select_next_file (FTNQ *q, FTN_ADDR *fa, int nAka)
{
int j, k;
FTNQ *curr;
for (k = 0; k < nAka; ++k)
{
for (curr = q; curr; curr = curr->next) /* Status first */
{
if (!curr->sent &&
(FA_ISNULL (&curr->fa) || !ftnaddress_cmp (&curr->fa, fa + k)) &&
curr->type == 's')
{
curr->sent = 1;
return curr;
}
}
for (j = 0; prio[j]; ++j)
{
for (curr = q; curr; curr = curr->next) /* Netmail first */
{
if (!curr->sent &&
(FA_ISNULL (&curr->fa) || !ftnaddress_cmp (&curr->fa, fa + k)) &&
curr->flvr == prio[j] &&
curr->type == 'm')
{
curr->sent = 1;
return curr;
}
}
}
for (j = 0; prio[j]; ++j)
{
for (curr = q; curr; curr = curr->next) /* Then go files and .flo */
{
if (!curr->sent &&
(FA_ISNULL (&curr->fa) || !ftnaddress_cmp (&curr->fa, fa + k)) &&
curr->flvr == prio[j])
{
curr->sent = 1;
return curr;
}
}
}
}
return 0;
}
/*
* get size of files in the queue
*/
void q_get_sizes (FTNQ *q, unsigned long *netsize, unsigned long *filessize)
{
FTNQ *curr;
struct stat st;
char *p;
*netsize = *filessize = 0;
for (curr = q; curr; curr = curr->next)
{
if (curr->type == 'l')
{ FILE *f;
char str[MAXPATHLEN+2];
if ((f = fopen(curr->path, "r")) != NULL)
{
while (fgets (str, sizeof(str), f))
{
if (*str == '~' || *str == '$') continue;
if ((p = strchr(str, '\n')) != NULL) *p='\0';
p=str;
if (*str == '#' || *str == '^') p++;
if (stat(p, &st) == 0)
*filessize += st.st_size;
}
fclose(f);
}
}
else if (curr->type == 's')
*filessize += curr->size;
else if (stat(curr->path, &st) == 0)
*(curr->type == 'm' ? netsize : filessize) += st.st_size;
}
}
/*
* q_not_empty () == 0: the queue is empty.
*/
typedef struct
{
int maxflvr;
FTN_NODE *fn;
} qn_not_empty_arg;
static int qn_not_empty (FTN_NODE *fn, void *arg)
{
qn_not_empty_arg *a = (qn_not_empty_arg *) arg;
if (!fn->busy && strcmp (fn->hosts, "-") && fn->hold_until < time (0))
{
if (a->maxflvr != MAXFLVR (fn->mail_flvr, MAXFLVR (fn->files_flvr, a->maxflvr)))
{
a->maxflvr = MAXFLVR (fn->mail_flvr, fn->files_flvr);
a->fn = fn;
}
}
return 0;
}
FTN_NODE *q_not_empty ()
{
qn_not_empty_arg arg;
arg.maxflvr = 0;
arg.fn = 0;
foreach_node (qn_not_empty, &arg);
if (arg.maxflvr && tolower (arg.maxflvr) != 'h')
return arg.fn;
else
return 0;
}
FTN_NODE *q_next_node ()
{
FTN_NODE *fn = q_not_empty ();
if (fn == 0)
return 0;
else
{
fn->mail_flvr = fn->files_flvr = 0;
return fn;
}
}
/*
* Creates an empty .?lo
*/
int create_poll (FTN_ADDR *fa, int flvr)
{
char buf[MAXPATHLEN + 1];
char ext[5];
int rc = 0;
strcpy (ext, ".flo");
if (flvr && strchr (flo_flvrs, flvr))
ext[1] = tolower (flvr);
ftnaddress_to_filename (buf, fa);
if (*buf)
{
mkpath (buf);
strnzcat (buf, ext, sizeof (buf));
if ((rc = create_empty_sem_file (buf)) == 0)
if (errno != EEXIST)
Log (1, "cannot create %s: %s", buf, strerror (errno));
}
else
Log (1, "%s: unknown domain", fa->domain);
return rc;
}
/*
* Set .hld for a node
*/
void hold_node (FTN_ADDR *fa, time_t hold_until)
{
char buf[MAXPATHLEN + 1];
char addr[FTN_ADDR_SZ + 1];
char time[80];
struct tm *tm;
#ifdef __WATCOMC__
struct tm stm;
tm = &stm;
_localtime (&hold_until, tm);
#else
tm = localtime (&hold_until);
#endif
strftime (time, sizeof (time), "%Y/%m/%d %H:%M:%S", tm);
ftnaddress_to_str (addr, fa);
ftnaddress_to_filename (buf, fa);
Log (2, "holding %s (%s)", addr, time);
if (*buf)
{
FILE *f;
FTN_NODE *fn = get_node_info (fa);
strnzcat (buf, ".hld", sizeof (buf));
if ((f = fopen (buf, "w")) != NULL)
{
fprintf (f, "%li", (long int) hold_until);
if (fn)
fn->hold_until = hold_until;
fclose (f);
}
else
{
Log (1, "%s: %s", buf, strerror (errno));
}
}
}
void write_try (FTN_ADDR *fa, unsigned *nok, unsigned *nbad, char *comment)
{
char buf[MAXPATHLEN + 1];
if (tries > 0)
{
ftnaddress_to_filename (buf, fa);
if (*buf)
{
FILE *f;
strnzcat (buf, ".try", sizeof (buf));
if ((f = fopen (buf, "wb")) != NULL)
{
fprintf (f, "%c%c%c%c%c%s",
*nok & 0xff, *nok >> 8,
*nbad & 0xff, *nbad >> 8,
(int) strlen (comment),
comment);
fclose (f);
}
}
}
}
void read_try (FTN_ADDR *fa, unsigned *nok, unsigned *nbad)
{
char buf[MAXPATHLEN + 1];
ftnaddress_to_filename (buf, fa);
if (*buf)
{
FILE *f;
unsigned char ch1, ch2, ch3, ch4;
strnzcat (buf, ".try", sizeof (buf));
if ((f = fopen (buf, "rb")) != NULL &&
fscanf (f, "%c%c%c%c", &ch1, &ch2, &ch3, &ch4) == 4)
{
*nok = ch1 + (ch2 << 8);
*nbad = ch3 + (ch4 << 8);
}
else
{
*nok = *nbad = 0;
}
if (f)
fclose (f);
}
}
void bad_try (FTN_ADDR *fa, const char *error)
{
unsigned nok, nbad;
read_try (fa, &nok, &nbad);
if (tries > 0 && ++nbad >= (unsigned) tries)
{
nok = nbad = 0;
hold_node (fa, time (0) + hold);
}
write_try (fa, &nok, &nbad, (char *) error);
}
void good_try (FTN_ADDR *fa, char *comment)
{
unsigned nok, nbad;
read_try (fa, &nok, &nbad);
nbad = 0;
++nok;
write_try (fa, &nok, &nbad, comment);
}
| [
"[email protected]"
] | |
9e271c637f77eb7a809fa26d68133b747151c960 | fb8b16f9588b7ea1fb03c077caf777086f3bffaa | /c++/PTA——画圆的游戏.cpp | 7ad33b77be89b27c182a3f81f95cc22b2a06f0a1 | [] | no_license | Hanmengnan/AlgorithmPractice | 3d5bc25bfefd103bf3d893a2ab67b18b964e6639 | 848377d2f760d67a5f256636b41be4a02a363877 | refs/heads/master | 2021-07-09T17:23:01.386025 | 2020-11-02T14:38:48 | 2020-11-02T14:38:48 | 196,815,543 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 289 | cpp | #include <iostream>
#include <math.h>
using namespace std;
int main()
{
int x, y, r;
while (cin >> x >> y >> r)
{
if (x < 2 * r || y < 2 * r)
cout << "It is boring!" << endl;
else
cout << "It is so easy!" << endl;
}
return 0;
} | [
"[email protected]"
] | |
4c1e928f973f10ec0dbfb4e196c1f1fadf1a6961 | 930bef05488f9be429e58f0279111f9e61fb87dd | /key_with_timer/key_with_timer.ino | 9fc50550f57f74fbde13332e3ca861bb420ee90a | [] | no_license | mywdka/Arduino_Examples | 074826193d72dbbefe77fe365e572a0e649c23f4 | 7a5ed280d26a8608a9e6aed51a1b647755b2932c | refs/heads/master | 2020-06-04T23:14:47.979668 | 2015-04-01T10:52:21 | 2015-04-01T10:52:21 | 33,242,410 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 541 | ino | #define LED1 11
#define LED2 12
#define BUTTON 2
#define DELAY 1000
int ledState = LOW;
unsigned long previousMillis = 0;
void setup() {
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(BUTTON, INPUT);
}
void loop()
{
int buttonState;
unsigned long currentMillis = millis();
buttonState = digitalRead(BUTTON);
digitalWrite(LED2, !buttonState);
if(currentMillis - previousMillis >= DELAY) {
previousMillis = currentMillis;
ledState = !ledState;
digitalWrite(LED1, ledState);
}
}
| [
"[email protected]"
] | |
19b2f853c3890a3eb12b352f5154b456b17ff8b6 | 9bd5c68596fa09e228c51c98fbcfc44887eccb8b | /src/proto/Forward.h | 165b060786c95acdcaa2a034657b222151f396b2 | [
"Zlib"
] | permissive | JWhiteCat/mud | 8467ae2170cf18cefc032e997490d51f2bb67c2a | dfe00b464f7819f308c683c90fc5ecb1101c0dd1 | refs/heads/master | 2020-03-26T06:21:37.294909 | 2018-08-13T00:32:32 | 2018-08-13T00:32:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 273 | h |
#pragma once
#include <infra/Config.h>
#include <infra/Forward.h>
#include <obj/Forward.h>
#include <refl/Forward.h>
#ifndef MUD_PROTO_EXPORT
#define MUD_PROTO_EXPORT MUD_IMPORT
#endif
namespace mud {
class Prototype;
class Complex;
}
| [
"[email protected]"
] | |
6e9fcca85e18a5e990326851acdaac5c8afda36f | b955899dd15f36876783c15ec62f64d6f67f0f1f | /overlay.cpp | 5badde61b2d6b2d47cbd4c5a809ca5267e70ef66 | [] | no_license | mesozoicreserve/Game | 1d36e7618e66f4f4bc2f83d9bb62dd499570dfbe | 076210a606315d6b6093f879240b93e44e6922a1 | refs/heads/master | 2016-09-10T18:57:15.366674 | 2015-07-30T04:52:10 | 2015-07-30T04:52:10 | 39,478,528 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,774 | cpp | #include "overlay.h"
SDL_Rect Overlay::getPosition()
{
return position;
}
Overlay::Overlay()
{
//undefined
position.x=0;
position.y=0;
position.w=0;
position.h=0;
name="undefined";
shown=false;
}
void Overlay::show()
{
shown=true;
}
void Overlay::hide()
{
shown= false;
}
Overlay::Overlay(std::string olName,int iX, int iY,Uint8 iA, bool vis,SDL_Renderer* renderer)
{
createOverlay(olName,iX,iY,iA,vis,renderer);
}
void Overlay::createOverlay(std::string olName,int iX, int iY,Uint8 iA, bool vis,SDL_Renderer* renderer)
{
alpha=iA;
name=olName;
position.x=iX;
position.y=iY;
shown = vis;
locked = false;
genOverlay();
overlayTexture = loadTexture(renderer);
}
void Overlay::genOverlay()
{
if (name == "SelectionMenu")
{
position.w=187;
position.h=450;
resName="BuildOverlay.bmp";
}
if (name == "CornerStatus")
{
position.w=300;
position.h=100;
resName="Corner.bmp";
}
if (name == "GuestMouseOverOverlay")
{
position.w=125;
position.h=100;
resName="GuestMouseOverOverlay.bmp";
}
if(name == "BuildContext" )
{
position.w=150;
position.h=100;
resName = "buildcontext.bmp";
}
}
SDL_Texture* Overlay::loadTexture(SDL_Renderer* renderer )
{
//The final texture
SDL_Texture* newTexture = NULL;
//Load image at specified path
SDL_Surface* loadedSurface = SDL_LoadBMP( resName.c_str() );
if( loadedSurface == NULL )
{
printf( "Unable to load image %s! SDL_image Error: %s\n", resName.c_str(), IMG_GetError() );
}
else
{
SDL_SetColorKey( loadedSurface, SDL_TRUE, SDL_MapRGB( loadedSurface->format, 0, 0xFF, 0xFF ) );
//Create texture from surface pixels
newTexture = SDL_CreateTextureFromSurface( renderer, loadedSurface );
if( newTexture == NULL )
{
printf( "Unable to create texture from %s! SDL Error: %s\n", resName.c_str(), SDL_GetError() );
} //Get rid of old loaded surface
SDL_FreeSurface( loadedSurface );
}
//Transperancy //Set blending function
SDL_SetTextureBlendMode( newTexture, SDL_BLENDMODE_BLEND );
SDL_SetTextureAlphaMod(newTexture,alpha);
return newTexture;
}
bool Overlay::isShown()
{
return shown;
}
void Overlay::applySurface(SDL_Renderer* renderer)
{
//render
SDL_RenderCopy( renderer,overlayTexture,NULL,&position);
}
Overlay::~Overlay()
{
shown = false;
name = "";
if (overlayTexture != NULL)
{
SDL_DestroyTexture(overlayTexture);
}
resName = "";
alpha = NULL;
}
void Overlay::lock()
{
locked = true;
}
void Overlay::unLock()
{
locked = false;
}
bool Overlay::isLocked()
{
return locked;
}
| [
"[email protected]"
] | |
955d8263189a01e171d6e598bf4a35d11120b5a1 | 80dc9e61db1a903c6a8240a68bbf5166136f6f2b | /src/type-system/factories/constants/IntConstantFactory.cpp | 06edf61c44381d83a16b10eb5c7200718a1354ef | [
"MIT"
] | permissive | tauonteilchen/entity-system | 6d024b62c9811e011605ee677be73d13d1609df8 | 351f9dc39ee38ec3f51a9c56651d3861f949b76c | refs/heads/master | 2020-04-26T09:51:39.482476 | 2019-02-16T21:57:42 | 2019-02-16T21:57:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,077 | cpp | // Inexor entity system
// (c)2018 Inexor
#include "IntConstantFactory.hpp"
using namespace inexor::entity_system;
using namespace std;
namespace inexor {
namespace entity_system {
namespace type_system {
IntConstantFactory::IntConstantFactory(
shared_ptr<IntConstantEntityTypeProvider> entity_type_provider,
shared_ptr<EntityInstanceBuilderManager> entity_instance_builder_manager
)
{
this->entity_type_provider = entity_type_provider;
this->entity_instance_builder_manager = entity_instance_builder_manager;
}
IntConstantFactory::~IntConstantFactory()
{
}
O_ENT_INST IntConstantFactory::create_instance()
{
return entity_instance_builder_manager->get_builder()
->type(entity_type_provider->get_type())
->attribute("name", "")
->attribute("value", 0)
->build();
}
O_ENT_INST IntConstantFactory::create_instance(const string& name, const int& value)
{
return entity_instance_builder_manager->get_builder()
->type(entity_type_provider->get_type())
->attribute("name", name)
->attribute("value", value)
->build();
}
}
}
}
| [
"[email protected]"
] | |
2c9df6c9606338d3331b79d7ae54c8ba13dc9246 | eae233056af494f0738d6516d5d76c6489dbe12c | /BluzGatewaySwitch.ino | b5156badf4632564ede6e3a71693707e9609690f | [] | no_license | dleffo/Bluz-Lifx-Switch | 45f99598830a64abb4035b413e1c51aea5fa669d | 6342ed776d08442e6bd2ded4279d05b08bd2c30e | refs/heads/master | 2020-06-13T19:05:27.908860 | 2016-12-05T11:41:12 | 2016-12-05T11:41:12 | 75,565,054 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,073 | ino | // This #include statement was automatically added by the Particle IDE.
#include "MQTT/MQTT.h"
// This #include statement was automatically added by the Particle IDE.
#include "bluz_gateway/bluz_gateway.h"
#define POLL_CONNECTIONS_INTERVAL 30000
SYSTEM_MODE(AUTOMATIC);
bluz_gateway gateway;
void callback(char* topic, byte* payload, unsigned int length);
void callback(char* topic, byte* payload, unsigned int length) {
}
char server[] = "mqtt.home.local";
String deviceID = "bluzgateway";
MQTT client(server, 1883, callback);
int lastButtonState[5] = {LOW,LOW,LOW,LOW,LOW};
int connected = FALSE;
int lastconnected = FALSE;
int lifxswitch[5] = {D1,D1,D2,D3,D4};
char name[] = "bluzgateway.home.local";
unsigned long t;
unsigned long deltat = 1000; //keep alive time for mqtt queue
std::string message = "";
std::string topic = "";
char* chrtopic;
std::string pressed = "";
int debouncefix;
int debounce = 200;
void handle_custom_data(uint8_t *data, uint16_t length) {
//if you use BLE.send from any connected DK, the data will end up here
Particle.publish("Bluz Custom Data", String((char*)data));
pressed = String((char*)data);
}
void handle_gateway_event(uint8_t event, uint8_t *data, uint16_t length) {
//will return any polling queries from the gateway here
}
void setup() {
gateway.init();
//register the callback functions
gateway.register_data_callback(handle_custom_data);
gateway.register_gateway_event(handle_gateway_event);
// Connect mqtt to broker
while(client.isConnected() == FALSE){
client.connect(name);
delay(10);
}
debouncefix = millis();
}
long timeToNextPoll = POLL_CONNECTIONS_INTERVAL;
void loop() {
if (client.isConnected()){
client.loop();
connected = TRUE;
if (connected != lastconnected){
Spark.publish("reconnected", NULL, 60, PRIVATE); //publish the event for IFTTT to consume
lastconnected = connected;
}
}
gateway.loop();
if (pressed != ""){
if (millis()-debouncefix > debounce){
topic = "particle/" + deviceID + "/buttons"; //build topic
char* chrtopic = strdup(topic.c_str()); //need to convert string to char
message = "Button " + pressed + " Pressed";
char* chrmessage = strdup(message.c_str());
client.publish(chrtopic, chrmessage); //publish click to MQTT.
Particle.publish("Pressed",chrmessage, 60, PRIVATE); //publish button press to particle cloud for IFTTT to consume.
free(chrmessage);
free(chrtopic); //free memory. Not sure if this is needed.
debouncefix = millis();
}
pressed = "";
}
if (millis() > timeToNextPoll) {
timeToNextPoll = POLL_CONNECTIONS_INTERVAL + millis();
gateway.poll_connections();
}
if(client.isConnected() == FALSE){
client.connect(name);
}
}
| [
"[email protected]"
] | |
db9adfd0a309ac03b25b5a842594c0a158ca9f3a | cdd335e5037c24804a827117dea28f0a38563cf8 | /GameManager.h | 1410399b379e3b71a92a399c39d4bb7596e2c7d8 | [] | no_license | Hybromech/AI-for-Games-Wildlife-Simulator | f0afbd4d4971df3bedd7da90ac18699c77ff6e58 | 2c2fbc3832384ce550a5d54da17de5f161b1a15f | refs/heads/master | 2023-04-22T15:26:59.650828 | 2021-05-13T07:47:31 | 2021-05-13T07:47:31 | 351,982,682 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 364 | h | #pragma once
#include<Vector>
class Agent;
///Manages the game.
/**
Provides methods for the agents.
*/
class GameManager
{
public :
//std::vector<Agent*> agents;
std::vector<Agent*> agents;
//!Returns true if another agent is within a certain distance.
bool DetectAgent(Agent*);
GameManager(std::vector<Agent*> passed_agents);
~GameManager();
}; | [
"[email protected]"
] | |
6ea68d619889cd93bebd1d46431378b6c3f6e7b7 | 8f50c262f89d3dc4f15f2f67eb76e686b8f808f5 | /MuonSpectrometer/MuonValidation/MuonDQA/MuonRawDataMonitoring/CscRawDataMonitoring/src/CscPrdValMonAlg.cxx | 30e457638e64aef8de7d4cb380b4e7fb561c9f75 | [
"Apache-2.0"
] | permissive | strigazi/athena | 2d099e6aab4a94ab8b636ae681736da4e13ac5c9 | 354f92551294f7be678aebcd7b9d67d2c4448176 | refs/heads/master | 2022-12-09T02:05:30.632208 | 2020-09-03T14:03:18 | 2020-09-03T14:03:18 | 292,587,480 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 12,917 | cxx | /*
Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
/* NAME : CscPrdValMonAlg.cxx
* PACKAGE : MuonRawDataMonitoring/CscRawDataMonitoring
* PURPOSE : CSC PrepRawData (PRD) monitoring
* AUTHOR : Ken Johns, Xiaowen Lei (U.Arizona)
*
* MODIFIED: N. Benekos(Illinois)
* V. Kaushik(U.Arizona) : 2009-05-12
* J. Veatch(U.Arizona) : 2012-02-08
* MODIFIED: C.Kitsaki, C.Paraskevopoulos
*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
#include "AthenaMonitoring/AthenaMonManager.h"
// Athena include(s)
#include "MuonPrepRawData/CscStripPrepDataCollection.h"
#include "MuonPrepRawData/CscStripPrepData.h"
#include "CscRawDataMonitoring/CscPrdValMonAlg.h"
using namespace Muon;
CscPrdValMonAlg::CscPrdValMonAlg( const std::string& name, ISvcLocator* pSvcLocator ) :
AthMonitorAlgorithm(name,pSvcLocator)
{
declareProperty("NoiseCutADC", m_cscNoiseCut = 50);
declareProperty("MapYXandRZ", m_mapxyrz = false);
}
StatusCode CscPrdValMonAlg::initialize() {
ATH_MSG_INFO( "CscPrdValMonAlg: in initialize" );
ATH_CHECK(m_idHelperSvc.retrieve());
ATH_CHECK(m_stripFitter.retrieve());
ATH_MSG_INFO( "CscPrdValMonAlg " << name() << ": retrieved " << m_stripFitter );
ATH_CHECK(m_cscPrdKey.initialize());
return AthMonitorAlgorithm::initialize();
}
//
// fillHistograms ----------------------------------------------------------------
//
StatusCode CscPrdValMonAlg::fillHistograms( const EventContext& ctx ) const {
int lumiblock = -1;
SG::ReadHandle<xAOD::EventInfo> evt(m_EventInfoKey, ctx);
lumiblock = evt->lumiBlock();
auto lumiblock_mon = Monitored::Scalar<int>("lumiblock_mon",lumiblock);
if(lumiblock < 0 ) return StatusCode::FAILURE;
// Part 1: Get the messaging service, print where you are
ATH_MSG_DEBUG( "CscPrdValMonAlg: in fillHistograms" );
SG::ReadHandle<CscStripPrepDataContainer> CscPRD(m_cscPrdKey, ctx);
// ==============================================================================
// Field Range Notes
// ==============================================================================
// StationName unsigned integer maps to "CSS", "CSL", etc.
// StationEta [-1,1] -1 for backward, 1 for forward endcap
// StationPhi [1,8] increases with Phi
// Technology [1] maps to "CSC"
// ChamberLayer [1,2] increases with |Z|
// WireLayer [1,4] increases with |Z|
// MeasuresPhi [0,1] 0 if measures R, 1 if measures Phi
// Strip [1,n] increases with R for MeasuresPhi=0
// increases with Phi for MeasuresPhi=1
// ==============================================================================
// Begin Event ==================================================
ATH_MSG_DEBUG ( " BEGIN EVENT ========================================== " );
ATH_MSG_DEBUG(" Size of PRD Container : " << CscPRD->size());
for (CscStripPrepDataContainer::const_iterator it = CscPRD->begin(); it != CscPRD->end(); ++it) {
const CscStripPrepDataCollection *prd = *it;
ATH_MSG_DEBUG ( " Size of Collection : " << prd->size() );
// size_t noStrips = prd->size(); // no. of strips in this cluster = m_stripIds.size()
auto noStrips = Monitored::Scalar<int>("noStrips",prd->size());
size_t nEtaClusWidthCnt[5], nPhiClusWidthCnt[5]; // cluster position in each phi-layer
int clusCount[33][9], sigclusCount[33][9];
for(size_t kl = 0; kl < 33; kl++ ) {
for(size_t km = 0; km < 9; km++ ) {
if(kl == 0 && km < 5) {
nEtaClusWidthCnt[km] = 0;
nPhiClusWidthCnt[km] = 0;
}
clusCount[kl][km] = 0;
sigclusCount[kl][km] = 0;
} // end loop over km
} // end loop over kl
// loop over PRD-clusters
// Loop over strip id's vector -- this is just one strip even though its a vector of ID's
ATH_MSG_DEBUG ( " BEGIN Loop over Strips ========================================== " );
for (CscStripPrepDataCollection::const_iterator ic = (*it)->begin(); ic != (*it)->end(); ++ic) { // for-loop over PRD collection
const CscStripPrepData& praw = **ic;
// Identify the PRD cluster
Identifier prawId = praw.identify();
int stationName = m_idHelperSvc->cscIdHelper().stationName(prawId);
std::string stationString = m_idHelperSvc->cscIdHelper().stationNameString(stationName);
int chamberType = stationString == "CSS" ? 0 : 1;
int stationEta = m_idHelperSvc->cscIdHelper().stationEta(prawId);
int stationPhi = m_idHelperSvc->cscIdHelper().stationPhi(prawId);
int wireLayer = m_idHelperSvc->cscIdHelper().wireLayer(prawId);
int measuresPhi = m_idHelperSvc->cscIdHelper().measuresPhi(prawId);
int stripId = m_idHelperSvc->cscIdHelper().strip(prawId);
int sectorNo = stationEta * (2 * stationPhi - chamberType);
// compute the indices to store cluster count
int ns = sectorNo < 0 ? sectorNo*(-1) : sectorNo+16; // [-16 -> -1] shifted to [1 -> 16] and [+1 -> +16] shifted to [+17 -> +32]
int nl = (measuresPhi ? wireLayer : wireLayer+4); // [ 1 -> 4] (phi-layers) and [5 -> 8] (eta-layers)
clusCount[ns][nl]++;
// indices for ns = [+1 -> +32]; 32 places (index '0' is not counted); allocated 33 places
// indices for nl = [+1 -> +8]; 8 places (index '0' is not counted); allocated 9 places
ATH_MSG_DEBUG(" ns = " << ns << "\tm_nl = " << nl << "\tm_sec = " << sectorNo << "\t m_lay= "
<< wireLayer << "\t strip = " << stripId << "\tmPhi = " << measuresPhi);
// y-axis fill value
// sector# +2 layer 1 maps to +2 + 0.2*(1-1) + 0.1 = +2.1
// sector# +2 layer 2 maps to +2 + 0.2*(2-1) + 0.1 = +2.3
// sector# +2 layer 3 maps to +2 + 0.2*(3-1) + 0.1 = +2.5
// sector# +2 layer 4 maps to +2 + 0.2*(4-1) + 0.1 = +2.7
auto secLayer = Monitored::Scalar<float>("secLayer", (sectorNo + 0.2 * (wireLayer - 1) + 0.1));
int xfac = measuresPhi ? -1 : 1; // [-1 -> -48] / [+1 -> +192]
// x-axis fill value
auto spid = Monitored::Scalar<float>("spid", (stripId * xfac) );
auto measphi = Monitored::Scalar<int>("measphi", (int)measuresPhi);
auto measeta = Monitored::Scalar<int>("measeta", (int)!(measuresPhi));
fill("CscPrdMonitor",spid, secLayer, noStrips, measphi, measeta);
if(m_mapxyrz) {
auto x = Monitored::Scalar<float>("x",praw.globalPosition().x());
auto y = Monitored::Scalar<float>("y",praw.globalPosition().y());
auto z = Monitored::Scalar<float>("z",praw.globalPosition().z());
auto r = Monitored::Scalar<float>("r",std::hypot(x,y));
fill("CscPrdMonitor",z,r);
fill("CscPrdMonitor",y,x);
ATH_MSG_DEBUG(" prd x = " << x << "\t y = " << y << "\t z = " << z );
} // end if(m_mapxyrz)
// Fit this strip and get Charge (in units of: # of electrons)
ICscStripFitter::Result res;
res = m_stripFitter->fit(praw);
ATH_MSG_DEBUG ( "Strip q +- dq = " << res.charge << " +- " << res.dcharge << "\t t +- dt = "
<< res.time << " +- " << res.dtime << "\t w +- dw = " << res.width << " +- "
<< res.dwidth << "\t status= " << res.status << "\t chisq= " << res.chsq);
// determine of the cluster is a noise/signal cluster Max_Delta_ADC > NoiseCut
float kiloele = 1.0e-3; // multiply # of electrons by this number to get kiloElectrons (1 ke = 1 ADC)
float qstripADC = res.charge * kiloele;
// By default res.status = -1
// if strip fit is success res.status = 0
// If fit fails use the peak sample. In this case res.status = 1
bool signal = ((qstripADC > m_cscNoiseCut) && (res.status >= 0)) ? true : false;
auto signal_mon = Monitored::Scalar<int>("signal_mon", (int)signal);
auto noise_mon = Monitored::Scalar<int>("noise_mon", (int)!(signal));
auto clus_phiSig = Monitored::Scalar<int>("clus_phiSig", (int)measuresPhi && (signal));
auto clus_etaSig = Monitored::Scalar<int>("clus_etaSig", (int)(!measuresPhi) && (signal));
auto clus_phiNoise = Monitored::Scalar<int>("clus_phiNoise", (int)measuresPhi && !(signal));
auto clus_etaNoise = Monitored::Scalar<int>("clus_etaNoise", (int)(!measuresPhi) && !(signal));
auto sideA = Monitored::Scalar<int>("sideA",(int)(stationEta==1) && (signal));
auto sideC = Monitored::Scalar<int>("sideC",(int)(stationEta==-1) && (signal));
// increment the signal-cluster count
if(signal){
sigclusCount[ns][nl]++;
measuresPhi ? nPhiClusWidthCnt[wireLayer]++ : nEtaClusWidthCnt[wireLayer]++ ;
}
fill("CscPrdMonitor", spid, secLayer, lumiblock_mon, noStrips, signal_mon, noise_mon, clus_phiSig, clus_etaSig, clus_etaNoise, clus_etaNoise, sideC, sideA);
} // end for-loop over PRD collection
ATH_MSG_DEBUG ( " End loop over PRD collection======================" );
for(size_t lcnt = 1; lcnt < 5; lcnt++ ) {
int tmp_phiClus = nPhiClusWidthCnt[lcnt];
int tmp_etaClus = nEtaClusWidthCnt[lcnt];
auto nPhiClusWidthCnt_mon = Monitored::Scalar<int>("nPhiClusWidthCnt_mon",tmp_phiClus);
auto nEtaClusWidthCnt_mon = Monitored::Scalar<int>("nEtaClusWidthCnt_mon",tmp_etaClus);
fill("CscPrdMonitor", nPhiClusWidthCnt_mon, nEtaClusWidthCnt_mon);
// m_h2csc_prd_eta_vs_phi_cluswidth->Fill(nPhiClusWidthCnt[lcnt],nEtaClusWidthCnt[lcnt]);
} // end loop over lcnt
int numeta = 0, numphi = 0;
int numetasignal = 0, numphisignal = 0;
int tmp_val = 0;
for(int kl = 1; kl < 33; kl++ ) {
for(int km = 1; km < 9; km++ ) {
int lay = (km > 4 && km < 9) ? km-4 : km; // 1,2,3,4 (phi-layers) 5-4, 6-4, 7-4, 8-4 (eta-layers)
bool mphi = (km > 0 && km < 5) ? true : false; // 1,2,3,4 (phi-layers) 5,6,7,8 (eta-layers)
std::string wlay = mphi ? "Phi-Layer " : "Eta-Layer: ";
int count = clusCount[kl][km];
auto count_mon = Monitored::Scalar<int>("count_mon",count);
int scount = sigclusCount[kl][km];
auto scount_mon = Monitored::Scalar<int>("scount_mon",scount);
auto mphi_true = Monitored::Scalar<int>("mphi_true",(int)mphi && count == 1);
auto mphi_false = Monitored::Scalar<int>("mphi_false",(int)!(mphi) && count == 1 );
auto scount_phi_true = Monitored::Scalar<int>("scount_phi_true", (int)mphi && count == 1 && scount == 1 );
auto scount_phi_false = Monitored::Scalar<int>("scount_phi_false", (int)mphi && count == 1 && scount == 0 );
auto scount_eta_true = Monitored::Scalar<int>("scount_eta_true", (int)!(mphi) && count == 1 && scount == 1 );
auto scount_eta_false = Monitored::Scalar<int>("scount_eta_false", (int)!(mphi) && count == 1 && scount == 0 );
auto secLayer = Monitored::Scalar<float>("secLayer",(kl-16 + 0.2 * (lay - 1) + 0.1));
auto tmp_val_mon = Monitored::Scalar<int>("tmp_val_mon", tmp_val);
if(count) {
if(mphi){
numphi += count;
if(scount){
numphisignal += scount;
tmp_val = count - scount;
} else tmp_val = count;
} else{
numeta += count;
if(scount){
numetasignal += scount;
tmp_val = count - scount;
} else tmp_val = count;
}
ATH_MSG_DEBUG ( wlay << "Counts sec: [" << kl-16 << "]\tlayer: [" << km << "] = " <<
secLayer << "\t = " << count << "\t" << scount);
}//end count
fill("CscPrdMonitor", count_mon, scount_mon, tmp_val_mon, secLayer, mphi_true, mphi_false, scount_phi_false, scount_phi_true, scount_eta_false, scount_eta_true );
} //end for km
} //end for kl
auto numphi_mon = Monitored::Scalar<int>("numphi_mon", numphi);
auto numeta_mon = Monitored::Scalar<int>("numeta_mon", numeta);
auto numphi_sig_mon = Monitored::Scalar<int>("numphi_sig_mon", numphisignal);
auto numeta_sig_mon = Monitored::Scalar<int>("numeta_sig_mon", numetasignal);
auto numphi_diff_mon = Monitored::Scalar<int>("numphi_diff_mon", numphi-numphisignal);
auto numeta_diff_mon = Monitored::Scalar<int>("numeta_diff_mon", numeta-numetasignal);
fill("CscPrdMonitor", numphi_mon, numeta_mon, numphi_sig_mon, numeta_sig_mon, numphi_diff_mon, numeta_diff_mon );
} // end for-loop over container
ATH_MSG_DEBUG ( " End EVENT======================" );
ATH_MSG_DEBUG( "CscPrdValMonAlg: fillHistograms reports success" );
return StatusCode::SUCCESS;
} // end CscPrdValMonAlg::fillHistograms()
| [
"[email protected]"
] | |
e3841e4cd321b01ea84fe46d0ad117514992aa22 | 63a76e8ae81d1d97211df92d00805a280f463897 | /engine/enginecode/src/independent/platforms/openGL/OpenGLVertexArray.cpp | a84756791e90285dbbc30cf5cce6e9d8619bab5e | [] | no_license | ahmed-mahraf/NG-Game-Engine | 2c32076de41d37082c22fc45f509afca36334f32 | b9d503134fd4af2440833df81efbe0bcf5d7f744 | refs/heads/main | 2023-01-31T08:54:00.417968 | 2020-12-17T23:47:39 | 2020-12-17T23:47:39 | 321,818,121 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,372 | cpp | /** @file OpenGLVertexArray.cpp
* initialise and created vertex array for opengl functions
*/
#include "engine_pch.h"
#include "platforms/openGL/OpenGLVertexArray.h"
#include <glad/glad.h>
namespace Engine
{
//<!for different shader data types, return which GL data type
static GLenum ShaderDataTypeToOpenGLBaseType(ShaderDataType type)
{
switch (type)
{
case ShaderDataType::Float: return GL_FLOAT;
case ShaderDataType::Float2: return GL_FLOAT;
case ShaderDataType::Float3: return GL_FLOAT;
case ShaderDataType::Float4: return GL_FLOAT;
case ShaderDataType::Mat3: return GL_FLOAT;
case ShaderDataType::Mat4: return GL_FLOAT;
case ShaderDataType::Int: return GL_INT;
case ShaderDataType::Int2: return GL_INT;
case ShaderDataType::Int3: return GL_INT;
case ShaderDataType::Int4: return GL_INT;
case ShaderDataType::Bool: return GL_BOOL;
}
GE_CORE_ASSERT(false, "unknown ShaderDataType");
return 0;
}
//<!constructor for vertex array
OpenGLVertexArray::OpenGLVertexArray()
{
NG_PROFILE_FUNCTION();
glCreateVertexArrays(1, &m_rendererID);
}
//<!deconstructor for vertex array
OpenGLVertexArray::~OpenGLVertexArray()
{
NG_PROFILE_FUNCTION();
glDeleteVertexArrays(1, &m_rendererID);
}
//<!bind vertext array
void OpenGLVertexArray::bind() const
{
NG_PROFILE_FUNCTION();
glBindVertexArray(m_rendererID);
}
//<!unbind vertex array
void OpenGLVertexArray::unbind() const
{
NG_PROFILE_FUNCTION();
glBindVertexArray(0);
}
//<!add vertex buffer to vertex array
void OpenGLVertexArray::addVertexBuffer(const Ref<VertexBuffer>& vB)
{
NG_PROFILE_FUNCTION();
GE_CORE_ASSERT(vB->getLayout().getElements().size(), "Vertex buffer has no layout!");
glBindVertexArray(m_rendererID);
vB->bind();
uint32_t index = 0;
const auto& layout = vB->getLayout();
for (const auto& element : layout)
{
glEnableVertexAttribArray(index);
glVertexAttribPointer
(index,
element.getComponentCount(),
ShaderDataTypeToOpenGLBaseType(element.Type),
element.Normalized ? GL_TRUE : GL_FALSE,
layout.getStride(),
(const void*)element.Offset);
index++;
}
m_VB.push_back(vB);
}
//<!set indexbuffer
void OpenGLVertexArray::setIndexBuffer(const Ref<IndexBuffer>& iB)
{
NG_PROFILE_FUNCTION();
glBindVertexArray(m_rendererID);
iB->bind();
m_IB = iB;
}
} | [
"[email protected]"
] | |
bf105cbb9000f6401dd8857f402b31a50df21e0a | 6628f7069d202b0bb16c201c96c6946092a70082 | /src/Shell.cpp | 00fe7a146e7fe9c6923fbabf9da2e8f32c80dc42 | [
"Apache-2.0"
] | permissive | rbrich/termic | 3300b4cae8abc5831d442e19fe227e8ccc8facf0 | 4d80f2f5b25404fffe7e181bd75b506bcc61458f | refs/heads/master | 2023-08-25T05:53:30.990664 | 2021-10-19T22:04:31 | 2021-10-19T22:04:31 | 411,199,315 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,698 | cpp | // Shell.cpp created on 2018-07-28
// This file is part of Termic project <https://github.com/rbrich/termic>
// Copyright 2018–2021 Radek Brich
// Licensed under the Apache License, Version 2.0 (see LICENSE file)
#include "Shell.h"
#include "Terminal.h"
#include <xci/core/log.h>
#include <unistd.h>
#include <poll.h>
#include <chrono>
#include <csignal>
#include <cstdlib>
#include <cassert>
#include <pwd.h>
#include <sys/wait.h>
using namespace std::chrono_literals;
using namespace xci::core;
namespace xci::term {
Shell::~Shell()
{
stop();
join();
}
bool Shell::start()
{
if (!m_pty.open())
return false;
m_pid = m_pty.fork();
if (m_pid == -1)
return false;
if (m_pid == 0) {
// child
::setenv("TERM", "xterm", 1);
auto* shell = getpwuid(getuid())->pw_shell;
if (execlp(shell, shell, nullptr) == -1) {
log::error("execlp: {m}");
_exit(-1);
}
__builtin_unreachable();
} else {
// parent
assert(m_pid > 0);
return true;
}
}
void Shell::stop()
{
if (m_pid != -1)
::kill(m_pid, SIGHUP);
}
ssize_t Shell::read(char* buffer, size_t size)
{
return m_pty.read(buffer, size);
}
void Shell::write(const std::string &data)
{
m_pty.write(data);
}
int Shell::join()
{
m_pty.close();
if (m_pid == -1)
return 0;
int wstatus;
waitpid(m_pid, &wstatus, 0);
m_pid = -1;
if (WIFEXITED(wstatus))
log::info("Shell exited: {}", WEXITSTATUS(wstatus));
if (WIFSIGNALED(wstatus))
log::warning("Shell killed: {}", WTERMSIG(wstatus));
return wstatus;
}
} // namespace xci::term
| [
"[email protected]"
] | |
a39fb9bd9b4cfe529d6060f752fc7d533f494286 | a9ee8e069318bf53bfbeae625370dab4f9ab6c8a | /SimpleFits/src/DiTauConstrainedFitter.cc | 5c65cdff65b1e1315d869c7979508283d093db82 | [] | no_license | cherepan/SimpleFitsStandalone | 344e50cdd98c37c939538ba4e6bd88f75b155c9d | 37fc0251a6b3c616bfce4ca47394bd96cda74cf0 | refs/heads/master | 2021-09-09T00:12:44.520439 | 2018-03-12T20:49:47 | 2018-03-12T20:49:47 | 124,949,580 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 43,813 | cc | #include "TauPolSoftware/SimpleFits/interface/DiTauConstrainedFitter.h"
#include "TauPolSoftware/SimpleFits/interface/PDGInfo.h"
#include "TauPolSoftware/SimpleFits/interface/Logger.h"
#include <iostream>
double DiTauConstrainedFitter::MassConstraint_ = 91.5;
DiTauConstrainedFitter::DiTauConstrainedFitter(LorentzVectorParticle TauA1,TrackParticle MuTrack, double phiz, TVector3 PVertex, TMatrixTSym<double> VertexCov){
DiTauConstrainedFitter(TauA1, MuTrack, phiz, PVertex, VertexCov, 91.5);
}
DiTauConstrainedFitter::DiTauConstrainedFitter(LorentzVectorParticle TauA1,TrackParticle MuTrack, double phiz, TVector3 PVertex, TMatrixTSym<double> VertexCov, double MassConstraint):
LagrangeMultipliersFitter()
{
debug = false;
AnalyticalCovariance =false;
phiz_ = phiz;
RecoilX_ = 0; //not used in this version
RecoilY_ = 0; //not used in this version
useFullRecoil_ = false;
MassConstraint_ = MassConstraint;
Configure(TauA1, MuTrack, PVertex, VertexCov);
}
DiTauConstrainedFitter::DiTauConstrainedFitter(LorentzVectorParticle TauA1,TrackParticle MuTrack, PTObject ResPtEstimate, TVector3 PVertex, TMatrixTSym<double> VertexCov, double MassConstraint):
LagrangeMultipliersFitter()
{
debug = false;
AnalyticalCovariance =false;
ResPtEstimate_ = ResPtEstimate;
phiz_ = 0; //not used in this version
RecoilX_ = ResPtEstimate.Par()(0,0);
RecoilY_ = ResPtEstimate.Par()(1,0);
useFullRecoil_ = true;
MassConstraint_ = MassConstraint;
Configure(TauA1, MuTrack, PVertex, VertexCov);
}
void DiTauConstrainedFitter::Configure(LorentzVectorParticle TauA1,TrackParticle MuTrack, TVector3 PVertex, TMatrixTSym<double> VertexCov){
debug = false;
AnalyticalCovariance =false;
MuTrack_ = MuTrack;
PV_ = PVertex;
LorentzVectorParticle TauMuGuess;
LorentzVectorParticle DiTau;
if(!useFullRecoil_) TauMuGuess = TauMuStartingPoint( MuTrack,TauA1,PVertex, VertexCov, TauA1.Vertex(),TauA1.VertexCov());
else{
TauMuGuess = TauMuStartingPointwithFullRecoil(MuTrack,TauA1, ResPtEstimate_, PVertex, VertexCov, TauA1.Vertex(),TauA1.VertexCov());
}
Logger(Logger::Debug) << "TauA1 covariance: " << std::endl;
if(Logger::Instance()->Level() == Logger::Debug){
TauA1.getCovMatrix().Print();
}
Logger(Logger::Debug) << "TauMuGuess covariance: " << std::endl;
if(Logger::Instance()->Level() == Logger::Debug){
TauMuGuess.getCovMatrix().Print();
}
Logger(Logger::Debug) << "Passed: TauMuStartingPoint" << std::endl;
ThetaForConstrTemporaryImplementation_=TauMuGuess.LV().Theta();
particles_.push_back(TauA1);
particles_.push_back(TauMuGuess);
particles0_.push_back(TauA1);
particles0_.push_back(TauMuGuess);
Logger(Logger::Debug) << "(TauA1.LV() + TauMuGuess.LV()).M(): " << (TauA1.LV() + TauMuGuess.LV()).M() << std::endl;
isconfigured=false;
int size=particles_.size()*3;
int sizeTrunc = 3;
TMatrixT<double> inpar(size,1);
TMatrixTSym<double> incov(size);
// Get primary vertex information
if(VertexCov.GetNrows()!=LorentzVectorParticle::NVertex)return;
//set input paramterts: TauA1 - TauMu
inpar(taua1_px,0)=TauA1.LV().Px();
inpar(taua1_py,0)=TauA1.LV().Py();
inpar(taua1_pz,0)=TauA1.LV().Pz();
inpar(taumu_px,0)=TauMuGuess.LV().Px();
inpar(taumu_py,0)=TauMuGuess.LV().Py();
inpar(taumu_pz,0)=TauMuGuess.LV().Pz();
int TauA1offset=0;
int TauMuoffset=3;
for(int i=0; i<3;i++){
for(int j=0; j<3;j++){
incov(i+TauA1offset,j+TauA1offset)=TauA1.Covariance(i+3,j+3);
incov(i+TauMuoffset,j+TauMuoffset)=TauMuGuess.Covariance(i+3,j+3);
}
}
// store expanded par for computation of final par (assumes fit has neglegible impact on a1 correlations with vertex uncertainties)
exppar.ResizeTo(size,1);
expcov.ResizeTo(size,size);
exppar=ComputeInitalExpPar(inpar);
expcov=ErrorMatrixPropagator::PropagateError(&DiTauConstrainedFitter::ComputeInitalExpPar,inpar,incov);
// store linearization point
TMatrixT<double> PAR_0(size,1);
par_0.ResizeTo(size);
cov_0.ResizeTo(size,size);
PAR_0=ComputeExpParToPar(exppar);
for(int i=0; i<npar;i++)par_0(i)=PAR_0(i,0);
cov_0=ErrorMatrixPropagator::PropagateError(&DiTauConstrainedFitter::ComputeExpParToPar,exppar,expcov);
// set up inital point for fit (cov handled in Fit() function)
par.ResizeTo(npar);
par=par_0;
TMatrixT<double> PARa_0(sizeTrunc,1);
para_0.ResizeTo(sizeTrunc);
cova_0.ResizeTo(sizeTrunc,sizeTrunc);
PARa_0=ComputeExpParToPara(exppar);
for(int i=0; i<npartr;i++)para_0(i)=PARa_0(i,0);
cova_0=ErrorMatrixPropagator::PropagateError(&DiTauConstrainedFitter::ComputeExpParToPara,exppar,expcov);
para.ResizeTo(npartr);
para=para_0;
TMatrixT<double> PARb_0(sizeTrunc,1);
parb_0.ResizeTo(sizeTrunc);
covb_0.ResizeTo(sizeTrunc,sizeTrunc);
PARb_0=ComputeExpParToParb(exppar);
for(int i=0; i<npartr;i++)parb_0(i)=PARb_0(i,0);
y_.ResizeTo(npartr,1); y_ = convertToMatrix(para_0);
covb_0=ErrorMatrixPropagator::PropagateError(&DiTauConstrainedFitter::ComputeExpParToParb,exppar,expcov);
parb.ResizeTo(npartr);
parb=parb_0;
isconfigured=true;
Init_Resonance_ = GetMother();
Logger(Logger::Debug) << "exppar covariance: " << std::endl;
if(Logger::Instance()->Level() == Logger::Debug){
expcov.Print();
}
Logger(Logger::Debug) << "para_0 covariance: " << std::endl;
if(Logger::Instance()->Level() == Logger::Debug){
cova_0.Print();
}
Logger(Logger::Debug) << "parb covariance: " << std::endl;
if(Logger::Instance()->Level() == Logger::Debug){
covb_0.Print();
}
}
TMatrixT<double> DiTauConstrainedFitter::ComputeInitalExpPar(TMatrixT<double> &inpar){
TMatrixT<double> outpar(6,1);
int offset=0;//LorentzVectorParticle::NVertex;// for TauA1
outpar(taua1_px,0)=inpar(LorentzVectorParticle::vx+offset,0);
outpar(taua1_py,0)=inpar(LorentzVectorParticle::vy+offset,0);
outpar(taua1_pz,0)=inpar(LorentzVectorParticle::vz+offset,0);
offset+=3;//LorentzVectorParticle::NLorentzandVertexPar; // for TauNu
outpar(taumu_px,0)=inpar(LorentzVectorParticle::vx+offset,0);
outpar(taumu_py,0)=inpar(LorentzVectorParticle::vy+offset,0);
outpar(taumu_pz,0)=inpar(LorentzVectorParticle::vz+offset,0);
return outpar;
}
TMatrixT<double> DiTauConstrainedFitter::ComputeExpParToPar(TMatrixT<double> &inpar){
TMatrixT<double> outpar(npar,1);
for(int i=0;i<npar;i++){outpar(i,0)=inpar(i,0);}
return outpar;
}
TMatrixT<double> DiTauConstrainedFitter::ComputeExpParToPara(TMatrixT<double> &inpar){
TMatrixT<double> outpar(npartr,1);
for(int i=0;i<npartr;i++){outpar(i,0)=inpar(i,0);}
return outpar;
}
TMatrixT<double> DiTauConstrainedFitter::ComputeExpParToParb(TMatrixT<double> &inpar){
TMatrixT<double> outpar(npartr,1);
int offset = 3;
for(int i=0;i<npartr;i++){outpar(i,0)=inpar(i+offset,0);}
return outpar;
}
TMatrixT<double> DiTauConstrainedFitter::ComputeTauMuLorentzVectorPar(TMatrixT<double> &inpar){
// start with index 3 to fill only momenta part
TMatrixT<double> outpar(7,1);
outpar(LorentzVectorParticle::vx,0)=0;
outpar(LorentzVectorParticle::vy,0)=0;
outpar(LorentzVectorParticle::vz,0)=0;
outpar(LorentzVectorParticle::px,0)=inpar(3,0);
outpar(LorentzVectorParticle::py,0)=inpar(4,0);
outpar(LorentzVectorParticle::pz,0)=inpar(5,0);
outpar(LorentzVectorParticle::m,0)=PDGInfo::tau_mass();
return outpar;
}
TMatrixT<double> DiTauConstrainedFitter::ComputeTauA1LorentzVectorPar(TMatrixT<double> &inpar){
// start with index 3 to fill only momenta part
TMatrixT<double> outpar(7,1);
outpar(LorentzVectorParticle::vx,0)=0;
outpar(LorentzVectorParticle::vy,0)=0;
outpar(LorentzVectorParticle::vz,0)=0;
outpar(LorentzVectorParticle::px,0)=inpar(0,0);
outpar(LorentzVectorParticle::py,0)=inpar(1,0);
outpar(LorentzVectorParticle::pz,0)=inpar(2,0);
outpar(LorentzVectorParticle::m,0) =PDGInfo::tau_mass();
return outpar;
}
TMatrixT<double> DiTauConstrainedFitter::ComputeMotherLorentzVectorPar(TMatrixT<double> &inpar){
TMatrixT<double> outpar(7,1);
TMatrixT<double> Taumupar=ComputeTauMuLorentzVectorPar(inpar);
TMatrixT<double> Taua1par=ComputeTauA1LorentzVectorPar(inpar);
outpar(LorentzVectorParticle::px,0)=Taumupar(LorentzVectorParticle::px,0)+Taua1par(LorentzVectorParticle::px,0);
outpar(LorentzVectorParticle::py,0)=Taumupar(LorentzVectorParticle::py,0)+Taua1par(LorentzVectorParticle::py,0);
outpar(LorentzVectorParticle::pz,0)=Taumupar(LorentzVectorParticle::pz,0)+Taua1par(LorentzVectorParticle::pz,0);
double Etaumu2=pow(Taumupar(LorentzVectorParticle::px,0),2.0)+pow(Taumupar(LorentzVectorParticle::py,0),2.0)+pow(Taumupar(LorentzVectorParticle::pz,0),2.0)+pow(Taumupar(LorentzVectorParticle::m,0),2.0);
double Etaua12=pow(Taua1par(LorentzVectorParticle::px,0),2.0)+pow(Taua1par(LorentzVectorParticle::py,0),2.0)+pow(Taua1par(LorentzVectorParticle::pz,0),2.0)+pow(Taua1par(LorentzVectorParticle::m,0),2.0);
double P2=pow(outpar(LorentzVectorParticle::px,0),2.0)+pow(outpar(LorentzVectorParticle::py,0),2.0)+pow(outpar(LorentzVectorParticle::pz,0),2.0);
outpar(LorentzVectorParticle::m,0)=sqrt(fabs(pow(sqrt(Etaumu2)+sqrt(Etaua12),2.0)-P2));
return outpar;
}
void DiTauConstrainedFitter::UpdateExpandedPar(){
for(int i=0; i<npartr;i++){
exppar(i,0)=para(i);
for(int j=0; j<npartr;j++){expcov(i,j)=cova_0(i,j);}
}
int offset = npartr;
for(int i=0; i<npartr;i++){
exppar(i+offset,0)=parb(i);
for(int j=0; j<npartr;j++){expcov(i+offset,j+offset)=covb_0(i,j);}
}
}
std::vector<LorentzVectorParticle> DiTauConstrainedFitter::GetReFitDaughters(){
std::vector<LorentzVectorParticle> refitParticles;
UpdateExpandedPar();
double c(0),b(0);
for(unsigned int i=0;i<particles_.size();i++){c+=particles_.at(i).Charge();b=particles_.at(i).BField();}
TMatrixT<double> a1=ComputeTauA1LorentzVectorPar(exppar);
TMatrixTSym<double> a1cov=ErrorMatrixPropagator::PropagateError(&DiTauConstrainedFitter::ComputeTauA1LorentzVectorPar,exppar,expcov);
for(int i=0; i<LorentzVectorParticle::NVertex; i++){
for(int j=0; j<LorentzVectorParticle::NVertex; j++){
a1cov(i,j)=particles_.at(0).VertexCov()(i,j);
}
}
refitParticles.push_back(LorentzVectorParticle(a1,a1cov,PDGInfo::tau_plus,c,b));
TMatrixT<double> mu=ComputeTauMuLorentzVectorPar(exppar);
mu(0,0)= particles_.at(1).Parameter(LorentzVectorParticle::vx);
mu(1,0)= particles_.at(1).Parameter(LorentzVectorParticle::vy);
mu(2,0)= particles_.at(1).Parameter(LorentzVectorParticle::vz);
TMatrixTSym<double> mucov=ErrorMatrixPropagator::PropagateError(&DiTauConstrainedFitter::ComputeTauMuLorentzVectorPar,exppar,expcov);
for(int i=0; i<LorentzVectorParticle::NVertex; i++){
for(int j=0; j<LorentzVectorParticle::NVertex; j++){
mucov(i,j)=particles_.at(1).VertexCov()(i,j);
}
}
refitParticles.push_back(LorentzVectorParticle(mu,mucov,PDGInfo::tau_minus,0.0,b));
return refitParticles;
}
LorentzVectorParticle
DiTauConstrainedFitter::GetMother(){
UpdateExpandedPar();
double c(0),b(0);
for(unsigned int i=0;i<particles_.size();i++){c+=particles_.at(i).Charge();b=particles_.at(i).BField();}
TMatrixT<double> m=ComputeMotherLorentzVectorPar(exppar);
TMatrixTSym<double> mcov=ErrorMatrixPropagator::PropagateError(&DiTauConstrainedFitter::ComputeMotherLorentzVectorPar,exppar,expcov);
return LorentzVectorParticle(m,mcov,PDGInfo::Z0,c,b);
}
TVectorD
DiTauConstrainedFitter::HardValue(TVectorD &va,TVectorD &vb){
TLorentzVector Taua1,Taumu;
double ZMass;
CovertParToObjects(va,vb,Taua1,Taumu,ZMass);
TLorentzVector z=Taua1+Taumu;
TVectorD d(NConstraints());
//d(0) = pow(Taua1.E() + Taumu.E(), 2.) - (Taua1.Vect() + Taumu.Vect()).Mag2()- pow(MassConstraint_,2.);
//d(1) = Taumu.Pz() - CosThetaTauMu(Taumu)*Taumu.P();
d(0) = z.M() - MassConstraint_;
d(1) = Taumu.Pz() - CosThetaTauMu(Taumu)*Taumu.P();
return d;
}
TVectorD
DiTauConstrainedFitter::SoftValue(TVectorD &va,TVectorD &vb){
TLorentzVector Taua1,Taumu;
double ZMass;
CovertParToObjects(va,vb,Taua1,Taumu,ZMass);
TVectorD d(NSoftConstraints());
if(!useFullRecoil_){
d(0) = Taua1.Px() + Taumu.Px();
d(1) = Taua1.Py() + Taumu.Py();
d(2) = ( (Taua1.Py() + Taumu.Py())/(Taua1.Px() + Taumu.Px())) - tan(phiz_);
Logger(Logger::Debug) << "SCVec: " << d(0) << ", " << d(1) << ", " << d(2) << std::endl;
Logger(Logger::Debug) << "RecoilX_: " << RecoilX_ << ", RecoilY_: " << RecoilY_ << std::endl;
}
else{
d(0) = Taua1.Px() + Taumu.Px() - RecoilX_;
d(1) = Taua1.Py() + Taumu.Py() - RecoilY_;
Logger(Logger::Debug) << "SCVec: " << d(0) << ", " << d(1) << std::endl;
Logger(Logger::Debug) << "RecoilX_: " << RecoilX_ << ", RecoilY_: " << RecoilY_ << std::endl;
}
return d;
}
void DiTauConstrainedFitter::CovertParToObjects(TVectorD &va,TVectorD &vb,TLorentzVector &Taua1,TLorentzVector &Taumu, double &Zmass){
// Taua1=particles_.at(0).LV();//TLorentzVector(v(taua1_px),v(taua1_py),v(taua1_pz),sqrt(1.777*1.777+v(taua1_px)*v(taua1_px)+v(taua1_py)*v(taua1_py)+v(taua1_pz)*v(taua1_pz)));
// Taumu=TLorentzVector(v(taua1_px),v(taua1_py),v(taua1_pz),sqrt(1.777*1.777+v(taua1_px)*v(taua1_px)+v(taua1_py)*v(taua1_py)+v(taua1_pz)*v(taua1_pz)));
Taua1=TLorentzVector(va(tau_px),va(tau_py),va(tau_pz),sqrt(PDGInfo::tau_mass()*PDGInfo::tau_mass()+va(tau_px)*va(tau_px)+va(tau_py)*va(tau_py)+va(tau_pz)*va(tau_pz)));
Taumu=TLorentzVector(vb(tau_px),vb(tau_py),vb(tau_pz),sqrt(PDGInfo::tau_mass()*PDGInfo::tau_mass()+vb(tau_px)*vb(tau_px)+vb(tau_py)*vb(tau_py)+vb(tau_pz)*vb(tau_pz)));
Zmass = 91.5;
}
LorentzVectorParticle
DiTauConstrainedFitter::TauMuStartingPoint(TrackParticle MuTrack,LorentzVectorParticle TauA1, TVector3 PV,TMatrixTSym<double> PVCov, TVector3 SV, TMatrixTSym<double> SVCov){
TVector3 TauDir = PV - SV;
TVector3 TauDirError(sqrt(SVCov(0,0) + PVCov(0,0)),
sqrt(SVCov(1,1) + PVCov(1,1)),
sqrt(SVCov(2,2) + PVCov(2,2)));
TMatrixT<double> parameters;
parameters.ResizeTo(5,1);
TMatrixT<double> parameterErrors;
parameterErrors.ResizeTo(5,5);
TMatrixT<double> parametersAd;
parametersAd.ResizeTo(9,1);
TMatrixTSym<double> parameterErrorsAd;
parameterErrorsAd.ResizeTo(9,9);
TMatrixT<double> taumudirection;
taumudirection.ResizeTo(2,1);
TMatrixTSym<double> taumudirectionError;
taumudirectionError.ResizeTo(2,2);
TMatrixT<double> kinematicparameters;
kinematicparameters.ResizeTo(5,1);
TMatrixTSym<double> kinematicparametererrors;
kinematicparametererrors.ResizeTo(5,5);
TMatrixT<double> TauKin;
TauKin.ResizeTo(3,1);
TMatrixT<double> TauKinErrorAnalytical;
TauKinErrorAnalytical.ResizeTo(3,3);
TMatrixT<double> TauKinErrorNumerical;
TauKinErrorNumerical.ResizeTo(3,3);
parameters = ConfigureParameters(MuTrack, EstimatePhiAngle(TauDir,TauDirError));
parameterErrors= ConfigureParameterErrors(MuTrack, EstimatePhiAngle(TauDir,TauDirError));
parametersAd = ConfigureInitialAdvancedParameters(MuTrack, PV, TauA1);
parameterErrorsAd= ConfigureInitialAdvancedParameterErrors(MuTrack, PVCov, TauA1.getCovMatrix());
taumudirection = EstimateTauDirectionAdvanced(parametersAd);
taumudirectionError = ErrorMatrixPropagator::PropagateError(&DiTauConstrainedFitter::EstimateTauDirectionAdvanced,ConfigureInitialAdvancedParameters(MuTrack, PV, TauA1),ConfigureInitialAdvancedParameterErrors(MuTrack, PVCov, TauA1.getCovMatrix()));
kinematicparameters = ConfigureKinematicParameters(taumudirection,TauA1);
kinematicparametererrors = ConfigureKinematicParameterErrors(taumudirectionError,TauA1);
TauKin=EstimateTauKinematic(kinematicparameters);
TauKinErrorNumerical = ErrorMatrixPropagator::PropagateError(&DiTauConstrainedFitter::EstimateTauKinematic,ConfigureKinematicParameters(taumudirection,TauA1),ConfigureKinematicParameterErrors(taumudirectionError,TauA1));
TauKinErrorAnalytical=ComputeAngleCovarianceAnalytically(MuTrack,EstimatePhiAngle(TauDir,TauDirError),PV,SV,TauA1);
if(debug){
std::cout<<"Tau Kinematic Paramteres 'TauKin' ====>"<<std::endl;
TauKin.Print();
std::cout<<"Numericaly calculated tau kinematic parameter errors 'TauKinErrorNumerical' ====> "<< std::endl;
TauKinErrorNumerical.Print();
std::cout<<"Inpute Kinematic Parameters 'kinematicparameters' ====>"<<std::endl;
kinematicparameters.Print();
std::cout<<"Input Kinematic Paramter Errors 'kinematicparametererrors' ====>"<< std::endl;
kinematicparametererrors.Print();
std::cout<<"TauMu direction paramters 'taumudirection' ====> "<< std::endl;
taumudirection.Print();
std::cout<<"TauMu direction paramter errors 'taumudirectionError' ====> "<< std::endl;
taumudirectionError.Print();
std::cout<<"Analitically calculated tau kinematic parameter errors 'TauKinErrorNumerical' ====> "<< std::endl;
TauKinErrorAnalytical.Print();
}
TMatrixT<double> par(LorentzVectorParticle::NLorentzandVertexPar,1);
TMatrixTSym<double> Cov(LorentzVectorParticle::NLorentzandVertexPar);
par(LorentzVectorParticle::vx,0)=0; // fill zero vertex for now
par(LorentzVectorParticle::vy,0)=0;
par(LorentzVectorParticle::vz,0)=0;
par(LorentzVectorParticle::px,0)=TauKin(0,0);
par(LorentzVectorParticle::py,0)=TauKin(1,0);
par(LorentzVectorParticle::pz,0)=TauKin(2,0);
par(LorentzVectorParticle::m,0) =PDGInfo::tau_mass();
for(int i=0; i<LorentzVectorParticle::NVertex; i++){
for(int j=0; j<LorentzVectorParticle::NVertex; j++){
if(AnalyticalCovariance){Cov(i+3,j+3)=TauKinErrorAnalytical(i,j);}
else{Cov(i+3,j+3)=TauKinErrorNumerical(i,j);}
}
}
return LorentzVectorParticle(par,Cov,PDGInfo::tau_minus,0,0);
}
LorentzVectorParticle
DiTauConstrainedFitter::TauMuStartingPointwithFullRecoil(TrackParticle MuTrack,LorentzVectorParticle TauA1, PTObject METminusNeutrino, TVector3 PV, TMatrixTSym<double> PVCov, TVector3 SV, TMatrixTSym<double> SVCov){
TMatrixT<double> kinematicparameters;
kinematicparameters.ResizeTo(12,1);
TMatrixTSym<double> kinematicparametererrors;
kinematicparametererrors.ResizeTo(12,12);
TMatrixT<double> TauKin;
TauKin.ResizeTo(6,1);
TMatrixT<double> TauKinErrorNumerical;
TauKinErrorNumerical.ResizeTo(6,6);
TMatrixT<double> TauKinErrorAnalytical;
TauKinErrorAnalytical.ResizeTo(6,6);
TMatrixTSym<double> TauMuErrorAnalytical;
TauMuErrorAnalytical.ResizeTo(3,3);
kinematicparameters = ConfigureKinematicParametersFullRecoil(MuTrack, PV, TauA1, METminusNeutrino);
kinematicparametererrors = ConfigureKinematicParameterErrorsFullRecoil(MuTrack, PVCov, TauA1, METminusNeutrino);
TauKin=EstimateTauKinematicFullRecoil(kinematicparameters);
TauKinErrorNumerical = ErrorMatrixPropagator::PropagateError(&DiTauConstrainedFitter::EstimateTauKinematicFullRecoil,kinematicparameters,kinematicparametererrors);
TLorentzVector TauMu(TauKin(3,0),TauKin(4,0),TauKin(5,0),PDGInfo::tau_mass());
TauKinErrorAnalytical = TauKinErrorNumerical;
TauMuErrorAnalytical = EstimateTauKinematicErrorFullRecoil(TauA1, TauMu, METminusNeutrino);
if(Logger::Instance()->Level() == Logger::Debug){
Logger(Logger::Debug) << "TauKinErrorAnalytical: " << std::endl;
TauKinErrorAnalytical.Print();
Logger(Logger::Debug) << "TauMuErrorAnalytical: " << std::endl;
TauMuErrorAnalytical.Print();
}
TMatrixT<double> par(LorentzVectorParticle::NLorentzandVertexPar,1);
TMatrixTSym<double> Cov(LorentzVectorParticle::NLorentzandVertexPar);
par(LorentzVectorParticle::vx,0)=PV_.X(); // fill tauh as "vertex" to save correlations
par(LorentzVectorParticle::vy,0)=PV_.Y();
par(LorentzVectorParticle::vz,0)=PV_.Z();
par(LorentzVectorParticle::px,0)=TauKin(3,0);
par(LorentzVectorParticle::py,0)=TauKin(4,0);
par(LorentzVectorParticle::pz,0)=TauKin(5,0);
par(LorentzVectorParticle::m,0) =PDGInfo::tau_mass();
for(int i=0; i<LorentzVectorParticle::NVertex; i++){
for(int j=0; j<LorentzVectorParticle::NVertex; j++){
Cov(i,j)=PVCov(i,j);
Cov(i+3,j+3)=TauMuErrorAnalytical(i,j);
}
}
if(Logger::Instance()->Level() == Logger::Debug){
Logger(Logger::Debug) << "Cov: " << std::endl;
Cov.Print();
}
return LorentzVectorParticle(par,Cov,PDGInfo::tau_minus,0,0);
}
TMatrixT<double>
DiTauConstrainedFitter::EstimateTauDirectionAdvanced(TMatrixT<double> &inpar){
TMatrixT<double> outpar(2,1);
double dxy =inpar(0,0);
double phi0 =inpar(1,0);
double lam =inpar(2,0);
double dz =inpar(3,0);
TVector3 PV(inpar(4,0),inpar(5,0),inpar(6,0));
TVector2 TauMuPt(-inpar(7,0), -inpar(8,0));
double tanphi_tau = TauMuPt.Y()/TauMuPt.X();
double a = tanphi_tau;
double b = PV.Y() - a*PV.X();
double tmu = (dxy*(cos(phi0) + a*sin(phi0)) - b) / (a*cos(phi0) - sin(phi0)); //projection onto XY plane
double xdoc = -dxy*sin(phi0) + tmu*cos(phi0);
double ydoc = dxy*cos(phi0) + tmu*sin(phi0);
double zdoc = dz + tmu*tan(lam);
TVector3 PointGuess(xdoc, ydoc, zdoc);
TVector3 TauMuDir = PointGuess - PV;
outpar(0,0) = TauMuDir.Theta();
outpar(1,0) = atan2(TauMuPt.Y(),TauMuPt.X());
Logger(Logger::Debug) << "PV: " << inpar(4,0) << ", " << inpar(5,0) << ", " << inpar(6,0) << std::endl;
Logger(Logger::Debug) << "dxy, phi0, lam, dz: " << dxy << ", " << phi0 << ", " << lam << ", " << dz << std::endl;
Logger(Logger::Debug) << "PointGuess: " << xdoc << ", " << ydoc << ", " << zdoc << std::endl;
Logger(Logger::Debug) << "DirGuess: " << TauMuDir.X() << ", " << TauMuDir.Y() << ", " << TauMuDir.Z() << std::endl;
Logger(Logger::Debug) << "a, b, t: " << a << ", " << b << ", " << tmu << std::endl;
Logger(Logger::Debug) << "TauH X, Y: " << inpar(7,0) << ", " << inpar(8,0) << std::endl;
Logger(Logger::Debug) << "TauMuDir.Phi(): " << TauMuDir.Phi() << " TauH phi: " << atan2(inpar(8,0), inpar(7,0)) << std::endl;
Logger(Logger::Debug) << "dPhi: " << TauMuDir.Phi() - atan2(inpar(8,0), inpar(7,0)) << "/pi= " << (TauMuDir.Phi() - atan2(inpar(8,0), inpar(7,0)))/TMath::Pi() << std::endl;
return outpar;
}
TMatrixT<double>
DiTauConstrainedFitter::EstimateTauKinematic(TMatrixT<double> &inpar){
TMatrixT<double> outpar(3,1);
TLorentzVector TauA1p4(inpar(2,0),
inpar(3,0),
inpar(4,0),
sqrt(pow(PDGInfo::tau_mass(),2) + pow(inpar(2,0),2) + pow(inpar(3,0),2) + pow(inpar(4,0),2) ) );
TVector3 TauMuDir(cos(inpar(1,0))*sin(inpar(0,0)), sin(inpar(1,0))*sin(inpar(0,0)), cos(inpar(0,0)));
TVector3 P_Tauh(inpar(2,0), inpar(3,0), inpar(4,0));
TLorentzVector P4_Tauh; P4_Tauh.SetXYZM(P_Tauh.X(),P_Tauh.Y(),P_Tauh.Z(),PDGInfo::tau_mass());
double theta = P_Tauh.Angle(TauMuDir);
double MassDiffsq = pow(MassConstraint_, 2.) - pow(PDGInfo::tau_mass(), 2.);
double Denominator = pow(P4_Tauh.P()*sin(theta),2.) + pow(PDGInfo::tau_mass(),2.);
double P_TauMu = (MassDiffsq*P4_Tauh.P()*cos(theta) + P4_Tauh.E()*sqrt( pow(MassDiffsq, 2.) - 4*pow(PDGInfo::tau_mass(),2.)*Denominator))/2/(Denominator);
outpar(0,0) = P_TauMu*TauMuDir.X();
outpar(1,0) = P_TauMu*TauMuDir.Y();
outpar(2,0) = P_TauMu*TauMuDir.Z();
//outpar(0,0) = P_Tauh.Pt()*cos(inpar(1,0));
//outpar(1,0) = P_Tauh.Pt()*sin(inpar(1,0));
//outpar(2,0) = P_Tauh.Pt()/tan(inpar(0,0));
Logger(Logger::Debug) << "TauDir.Phi(): " << TauA1p4.Phi() << " TauMuDirNEW2.Phi(): " << inpar(1,0) << std::endl;
Logger(Logger::Debug) << "TauA1 p3: " << TauA1p4.X() << ", " << TauA1p4.Y() << ", " << TauA1p4.Z() << std::endl;
Logger(Logger::Debug) << "TauMu p3: " << outpar(0,0) << ", " << outpar(1,0) << ", " << outpar(2,0) << std::endl;
return outpar;
}
TMatrixT<double>
DiTauConstrainedFitter::ConfigureParameters(TrackParticle MuTrack, std::pair<double, double> phiAngle){
TMatrixT<double> outpar(5,1);
outpar(0,0) = MuTrack.Parameter(TrackParticle::dxy);
outpar(1,0) = MuTrack.Parameter(TrackParticle::phi);
outpar(2,0) = MuTrack.Parameter(TrackParticle::lambda);
outpar(3,0) = MuTrack.Parameter(TrackParticle::dz);
outpar(4,0) = phiAngle.first;
return outpar;
}
TMatrixT<double>
DiTauConstrainedFitter::ConfigureParameterErrors(TrackParticle MuTrack, std::pair<double, double> phiAngle){
TMatrixT<double> Cov;
Cov.ResizeTo(5,5);
Cov(0,0) = MuTrack.Covariance(TrackParticle::dxy,TrackParticle::dxy);
Cov(0,1) = MuTrack.Covariance(TrackParticle::dxy,TrackParticle::phi);
Cov(0,2) = MuTrack.Covariance(TrackParticle::dxy,TrackParticle::dz);
Cov(0,3) = MuTrack.Covariance(TrackParticle::dxy,TrackParticle::lambda);
Cov(0,4) = 0;
Cov(1,0) = MuTrack.Covariance(TrackParticle::phi,TrackParticle::dxy);
Cov(1,1) = MuTrack.Covariance(TrackParticle::phi,TrackParticle::phi);
Cov(1,2) = MuTrack.Covariance(TrackParticle::phi,TrackParticle::dz);
Cov(1,3) = MuTrack.Covariance(TrackParticle::phi,TrackParticle::lambda);
Cov(1,4) = 0;
Cov(2,0) = MuTrack.Covariance(TrackParticle::dz,TrackParticle::dxy);
Cov(2,1) = MuTrack.Covariance(TrackParticle::dz,TrackParticle::phi);
Cov(2,2) = MuTrack.Covariance(TrackParticle::dz,TrackParticle::dz);
Cov(2,3) = MuTrack.Covariance(TrackParticle::dz,TrackParticle::lambda);
Cov(2,4) = 0;
Cov(3,0) = MuTrack.Covariance(TrackParticle::lambda,TrackParticle::dxy);
Cov(3,1) = MuTrack.Covariance(TrackParticle::lambda,TrackParticle::phi);
Cov(3,2) = MuTrack.Covariance(TrackParticle::lambda,TrackParticle::dz);
Cov(3,3) = MuTrack.Covariance(TrackParticle::lambda,TrackParticle::lambda);
Cov(3,4) = 0;
Cov(4,0) = 0;
Cov(4,1) = 0;
Cov(4,2) = 0;
Cov(4,3) = 0;
Cov(4,4) = phiAngle.second;
return Cov;
}
TMatrixT<double>
DiTauConstrainedFitter::ConfigureInitialAdvancedParameters(TrackParticle MuTrack, TVector3 PV, LorentzVectorParticle TauA1){
TMatrixT<double> outpar;
outpar.ResizeTo(9,1);
outpar(0,0) = MuTrack.Parameter(TrackParticle::dxy);
outpar(1,0) = MuTrack.Parameter(TrackParticle::phi);
outpar(2,0) = MuTrack.Parameter(TrackParticle::lambda);
outpar(3,0) = MuTrack.Parameter(TrackParticle::dz);
outpar(4,0) = PV.X();
outpar(5,0) = PV.Y();
outpar(6,0) = PV.Z();
outpar(7,0) = TauA1.LV().X();
outpar(8,0) = TauA1.LV().Y();
return outpar;
}
TMatrixTSym<double>
DiTauConstrainedFitter::ConfigureInitialAdvancedParameterErrors(TrackParticle MuTrack, TMatrixTSym<double> PVCov, TMatrixTSym<double> TauA1Cov){
TMatrixTSym<double> Cov;
Cov.ResizeTo(9,9);
Cov(0,0) = MuTrack.Covariance(TrackParticle::dxy,TrackParticle::dxy);
Cov(0,1) = MuTrack.Covariance(TrackParticle::dxy,TrackParticle::phi);
Cov(0,2) = MuTrack.Covariance(TrackParticle::dxy,TrackParticle::dz);
Cov(0,3) = MuTrack.Covariance(TrackParticle::dxy,TrackParticle::lambda);
Cov(1,0) = MuTrack.Covariance(TrackParticle::phi,TrackParticle::dxy);
Cov(1,1) = MuTrack.Covariance(TrackParticle::phi,TrackParticle::phi);
Cov(1,2) = MuTrack.Covariance(TrackParticle::phi,TrackParticle::dz);
Cov(1,3) = MuTrack.Covariance(TrackParticle::phi,TrackParticle::lambda);
Cov(2,0) = MuTrack.Covariance(TrackParticle::lambda,TrackParticle::dxy);
Cov(2,1) = MuTrack.Covariance(TrackParticle::lambda,TrackParticle::phi);
Cov(2,2) = MuTrack.Covariance(TrackParticle::lambda,TrackParticle::dz);
Cov(2,3) = MuTrack.Covariance(TrackParticle::lambda,TrackParticle::lambda);
Cov(3,0) = MuTrack.Covariance(TrackParticle::dz,TrackParticle::dxy);
Cov(3,1) = MuTrack.Covariance(TrackParticle::dz,TrackParticle::phi);
Cov(3,2) = MuTrack.Covariance(TrackParticle::dz,TrackParticle::dz);
Cov(3,3) = MuTrack.Covariance(TrackParticle::dz,TrackParticle::lambda);
for(int i=0; i<3; i++){
for(int j=0; j<3; j++){
Cov(i+4,j+4)=PVCov(i,j);
}
}
for(int i=0; i<2; i++){
for(int j=0; j<2; j++){
Cov(i+7,j+7)=TauA1Cov(i+4,j+4);
}
}
if(debug){
std::cout<<" Input paramters covariance matrix "<<std::endl;
for(int str =0; str < Cov.GetNrows(); str++){
for(int kol =0; kol < Cov.GetNcols(); kol++){
std::cout<<" "<< Cov(str,kol)<<" ";
}
std::cout<<std::endl;
}
}
return Cov;
}
TMatrixT<double>
DiTauConstrainedFitter::ConfigureKinematicParameters(TMatrixT<double> TauMuDir, LorentzVectorParticle TauA1){
TMatrixT<double> outpar;
outpar.ResizeTo(5,1);
outpar(0,0) = TauMuDir(0,0);
outpar(1,0) = TauMuDir(1,0);
outpar(2,0) = TauA1.LV().Px();
outpar(3,0) = TauA1.LV().Py();
outpar(4,0) = TauA1.LV().Pz();
if(debug){
std::cout<<"EstimateTauKinematic TauA1 "<<TauA1.LV().Px()<<" "<<TauA1.LV().Py()<<" "<<TauA1.LV().Pz()<<std::endl;
std::cout<<"ConfigureKinematicParameters: outpar(0,0) "<<outpar(0,0) <<std::endl;
std::cout<<"ConfigureKinematicParameters: outpar(1,0) "<<outpar(1,0) <<std::endl;
std::cout<<"ConfigureKinematicParameters: outpar(2,0) "<<outpar(2,0) <<std::endl;
std::cout<<"ConfigureKinematicParameters: outpar(3,0) "<<outpar(3,0) <<std::endl;
std::cout<<"ConfigureKinematicParameters: outpar(4,0) "<<outpar(4,0) <<std::endl;
}
return outpar;
}
TMatrixTSym<double>
DiTauConstrainedFitter::ConfigureKinematicParameterErrors(TMatrixTSym<double> TauMuDirError, LorentzVectorParticle TauA1){
TMatrixTSym<double> outpar;
outpar.ResizeTo(5,5);
for(int i=0; i<5; i++){
for(int j=0; j<5; j++){
if(i<2 && j < 2){
outpar(i,j)=TauMuDirError(i,j);
}else{
outpar(i,j)=TauA1.Covariance(i+1,j+1);
}
}
}
return outpar;
}
std::pair<double, double>
DiTauConstrainedFitter::EstimatePhiAngle( TVector3 dir, TVector3 dirE){
std::pair<double, double> outpar;
double phi = atan2(dir.Y(),dir.X());
double deltaphi = sqrt(dirE.Y()*dirE.Y()/dir.X()/dir.X()+
dirE.X()*dirE.X()*dir.Y()*dir.Y()/dir.X()/dir.X()/dir.X()/dir.X() )*cos(phi)*cos(phi);
outpar = std::make_pair(phi, deltaphi);
return outpar;
}
//////////////////////////////////////////////////////////////////////
// Analytical calculation of TauMu Covariance; Has to be rewritten....
TMatrixT<double>
DiTauConstrainedFitter::ComputeAngleCovarianceAnalytically(TrackParticle MuTrack, std::pair<double, double> phiAngle, TVector3 PV, TVector3 SV, LorentzVectorParticle TauA1){
TMatrixT<double> outpar;
outpar.ResizeTo(3,3);
double dxy =MuTrack.Parameter(TrackParticle::dxy);
//double kappa =MuTrack.Parameter(TrackParticle::kappa);
double phi0 =MuTrack.Parameter(TrackParticle::phi);
double lam =MuTrack.Parameter(TrackParticle::lambda);
double dz =MuTrack.Parameter(TrackParticle::dz);
//double c =MuTrack.Charge();
TVector3 A1SV = -SV + PV;
double phiAnot = atan2(A1SV.Y(), A1SV.X());
double xpoca2Anot = dxy*sin(phi0) - PV.X();
double ypoca2Anot = -dxy*cos(phi0) - PV.Y();
double aAnot = tan(phi0);
double bAnot = ypoca2Anot - aAnot*xpoca2Anot;
double r = sqrt( pow(bAnot/(tan(phiAnot) - aAnot ) ,2) + pow(bAnot*tan(phiAnot)/(tan(phiAnot) - aAnot) ,2));//(bAnot)/(tan(phiAnot) - tan(phi0))/cos(phiAnot);
//double bz0 = fabs(dxy) - dz/lam ;
double ZNeu = lam*(r + dxy) - dz;
//double XNeu = r*cos(phiAnot);
//double YNeu = r*sin(phiAnot);
double br = tan(phi0)*cos(phiAnot) - sin(phiAnot);
double Zc = ZNeu;
double MinusSintheta = -sqrt(1 - Zc*Zc/(r*r + Zc*Zc) );
double cosTheta = Zc/sqrt(r*r + Zc*Zc) ;
double sinTheta = -MinusSintheta;
if(fabs(phiAnot - TauA1.LV().Phi()) < 0.05) phiAnot = phiAnot - TMath::Pi();
//-derivaticves
double drdphi =2*dxy*sin(phi0)*(cos(phiAnot) + tan(phi0)*sin(phiAnot))/ (tan(phi0)*cos(phiAnot) - sin(phiAnot))/(tan(phi0)*cos(phiAnot) - sin(phiAnot));
double drzdd = 2*sin(phi0)/br/Zc - 2*dxy*sin(phi0)*lam/br/Zc/Zc;
double drzdphi0 = (2*dxy*cos(phi0)/(tan(phi0)*cos(phiAnot) - sin(phiAnot)) - 2*dxy*sin(phi0)*cos(phiAnot)/cos(phi0)/cos(phi0)/(tan(phi0)*cos(phiAnot) - sin(phiAnot))/(tan(phi0)*cos(phiAnot) - sin(phiAnot)))/Zc;
double drzdlam = -2*dxy*sin(phi0)*(r+dxy)/br/Zc/Zc;
double drzdz0 = -2*dxy*sin(phi0)/br/Zc;
double drzdphi = drdphi*(1 - r*lam/Zc)/Zc;//2*dxy*sin(phi0)*(cos(phiAnot) + tan(phi0)*sin(phiAnot))/ (tan(phi0)*cos(phiAnot) - sin(phiAnot))/(tan(phi0)*cos(phiAnot) - sin(phiAnot));
double dcosThetadrz = -r/Zc/sqrt(pow(1 + r*r/Zc/Zc,3));
//double dThetadPhi = -dcosThetadrz*drzdphi/sinTheta;
//-derivaticves
double cosTauTau2 = cos(TauA1.LV().Theta() + acos(cosTheta));
//double sinTauTau2 = sin(TauA1.LV().Theta() + acos(cosTheta));
TMatrixT<double> HelixCov;
HelixCov.ResizeTo(5,5);
HelixCov(0,0) = MuTrack.Covariance(TrackParticle::dxy,TrackParticle::dxy);
HelixCov(0,1) = MuTrack.Covariance(TrackParticle::dxy,TrackParticle::phi);
HelixCov(0,2) = MuTrack.Covariance(TrackParticle::dxy,TrackParticle::dz);
HelixCov(0,3) = MuTrack.Covariance(TrackParticle::dxy,TrackParticle::lambda);
HelixCov(0,4) = 0;
HelixCov(1,0) = MuTrack.Covariance(TrackParticle::phi,TrackParticle::dxy);
HelixCov(1,1) = MuTrack.Covariance(TrackParticle::phi,TrackParticle::phi);
HelixCov(1,2) = MuTrack.Covariance(TrackParticle::phi,TrackParticle::dz);
HelixCov(1,3) = MuTrack.Covariance(TrackParticle::phi,TrackParticle::lambda);
HelixCov(1,4) = 0;
HelixCov(2,0) = MuTrack.Covariance(TrackParticle::dz,TrackParticle::dxy);
HelixCov(2,1) = MuTrack.Covariance(TrackParticle::dz,TrackParticle::phi);
HelixCov(2,2) = MuTrack.Covariance(TrackParticle::dz,TrackParticle::dz);
HelixCov(2,3) = MuTrack.Covariance(TrackParticle::dz,TrackParticle::lambda);
HelixCov(2,4) = 0;
HelixCov(3,0) = MuTrack.Covariance(TrackParticle::lambda,TrackParticle::dxy);
HelixCov(3,1) = MuTrack.Covariance(TrackParticle::lambda,TrackParticle::phi);
HelixCov(3,2) = MuTrack.Covariance(TrackParticle::lambda,TrackParticle::dz);
HelixCov(3,3) = MuTrack.Covariance(TrackParticle::lambda,TrackParticle::lambda);
HelixCov(3,4) = 0;
HelixCov(4,0) = 0;
HelixCov(4,1) = 0;
HelixCov(4,2) = 0;
HelixCov(4,3) = 0;
HelixCov(4,4) = phiAngle.second;//sqrt(TauDirError.Y()*TauDirError.Y()/A1SV.X()/A1SV.X() + TauDirError.X()*TauDirError.X()*A1SV.Y()*A1SV.Y()/A1SV.X()/A1SV.X()/A1SV.X()/A1SV.X() ) *cos(phiAnot)*cos(phiAnot);
TMatrixT<double> DerivativesHelixToAngles;
DerivativesHelixToAngles.ResizeTo(2,5);
DerivativesHelixToAngles(0,0) = 0;
DerivativesHelixToAngles(0,1) = 0;
DerivativesHelixToAngles(0,2) = 0;
DerivativesHelixToAngles(0,3) = 0;
DerivativesHelixToAngles(0,4) = 1;
DerivativesHelixToAngles(1,0) = dcosThetadrz*drzdd/MinusSintheta;
DerivativesHelixToAngles(1,1) = dcosThetadrz*drzdphi0/MinusSintheta;
DerivativesHelixToAngles(1,2) = dcosThetadrz*drzdlam/MinusSintheta;
DerivativesHelixToAngles(1,3) = dcosThetadrz*drzdz0/MinusSintheta;
DerivativesHelixToAngles(1,4) = dcosThetadrz*drzdphi/MinusSintheta;
TMatrixT<double> DerivativesHelixToAnglesT=DerivativesHelixToAngles; DerivativesHelixToAnglesT.T();
TMatrixT<double> CovAngleFrame=DerivativesHelixToAngles*HelixCov*DerivativesHelixToAnglesT;
//double ZMassR = 91.5;
double TauA1deltaP = sqrt( (pow(TauA1.LV().Px(),2)*fabs(TauA1.Covariance(3,3)) + pow(TauA1.LV().Py(),2)*fabs(TauA1.Covariance(4,4)) + pow(TauA1.LV().Pz(),2)*fabs(TauA1.Covariance(5,5)) )/TauA1.LV().P()/TauA1.LV().P() ) ;
double TauMudeltaP_2 = TauA1deltaP*pow(MassConstraint_/2/TauA1.LV().P(),2)/(1-cosTauTau2);
double TauMuP_2 = MassConstraint_*MassConstraint_/2/(1-cosTauTau2)/TauA1.LV().P();
TMatrixT<double> CovPPhiThetaFrame;
CovPPhiThetaFrame.ResizeTo(3,3);
//---------- dp dphi dtheta
CovPPhiThetaFrame(0,0) = TauMudeltaP_2;
CovPPhiThetaFrame(0,1) = 0;
CovPPhiThetaFrame(0,2) = 0;
CovPPhiThetaFrame(1,0) = 0;
CovPPhiThetaFrame(1,1) = CovAngleFrame(0,0);
CovPPhiThetaFrame(1,2) = CovAngleFrame(0,1);
CovPPhiThetaFrame(2,0) = 0;
CovPPhiThetaFrame(2,1) = CovAngleFrame(1,0);
CovPPhiThetaFrame(2,2) = CovAngleFrame(1,1);
TMatrixT<double> DirevativesPPhiThetaToPxPyPz;
DirevativesPPhiThetaToPxPyPz.ResizeTo(3,3);
DirevativesPPhiThetaToPxPyPz(0,0) = cos(phiAnot)*sinTheta;
DirevativesPPhiThetaToPxPyPz(0,1) = -TauMuP_2*sin(phiAnot)*sinTheta;
DirevativesPPhiThetaToPxPyPz(0,2) = TauMuP_2*cos(phiAnot)*cosTheta;
DirevativesPPhiThetaToPxPyPz(1,0) = sin(phiAnot)*sinTheta;
DirevativesPPhiThetaToPxPyPz(1,1) = TauMuP_2*cos(phiAnot)*sinTheta;
DirevativesPPhiThetaToPxPyPz(1,2) = TauMuP_2*sin(phiAnot)*cosTheta;
DirevativesPPhiThetaToPxPyPz(2,0) = cosTheta;
DirevativesPPhiThetaToPxPyPz(2,1) = 0;
DirevativesPPhiThetaToPxPyPz(2,2) =-TauMuP_2*sinTheta;
TMatrixT<double> DirevativesPPhiThetaToPxPyPzT=DirevativesPPhiThetaToPxPyPz; DirevativesPPhiThetaToPxPyPzT.T();
TMatrixT<double> CovPxPyPzFrame=DirevativesPPhiThetaToPxPyPz*CovPPhiThetaFrame*DirevativesPPhiThetaToPxPyPzT;
outpar = CovPxPyPzFrame;
return outpar;
}
LorentzVectorParticle
DiTauConstrainedFitter::GetTauMuEstimate(){
return particles_.at(1);
}
TMatrixT<double> DiTauConstrainedFitter::ConfigureKinematicParametersFullRecoil(TrackParticle MuTrack, TVector3 PV, LorentzVectorParticle TauA1, PTObject METMinusNeutrino){
TMatrixT<double> outpar;
outpar.ResizeTo(12,1);
outpar(0,0) = MuTrack.Parameter(TrackParticle::dxy);
outpar(1,0) = MuTrack.Parameter(TrackParticle::phi);
outpar(2,0) = MuTrack.Parameter(TrackParticle::lambda);
outpar(3,0) = MuTrack.Parameter(TrackParticle::dz);
outpar(4,0) = PV.X();
outpar(5,0) = PV.Y();
outpar(6,0) = PV.Z();
outpar(7,0) = TauA1.LV().X();
outpar(8,0) = TauA1.LV().Y();
outpar(9,0) = TauA1.LV().Z();
outpar(10,0) = METMinusNeutrino.Par()(0,0);
outpar(11,0) = METMinusNeutrino.Par()(1,0);
return outpar;
}
TMatrixTSym<double> DiTauConstrainedFitter::ConfigureKinematicParameterErrorsFullRecoil(TrackParticle MuTrack, TMatrixTSym<double> PVCov, LorentzVectorParticle TauA1, PTObject METMinusNeutrino){
TMatrixTSym<double> Cov;
Cov.ResizeTo(12,12);
Cov(0,0) = MuTrack.Covariance(TrackParticle::dxy,TrackParticle::dxy);
Cov(0,1) = MuTrack.Covariance(TrackParticle::dxy,TrackParticle::phi);
Cov(0,2) = MuTrack.Covariance(TrackParticle::dxy,TrackParticle::dz);
Cov(0,3) = MuTrack.Covariance(TrackParticle::dxy,TrackParticle::lambda);
Cov(1,0) = MuTrack.Covariance(TrackParticle::phi,TrackParticle::dxy);
Cov(1,1) = MuTrack.Covariance(TrackParticle::phi,TrackParticle::phi);
Cov(1,2) = MuTrack.Covariance(TrackParticle::phi,TrackParticle::dz);
Cov(1,3) = MuTrack.Covariance(TrackParticle::phi,TrackParticle::lambda);
Cov(2,0) = MuTrack.Covariance(TrackParticle::lambda,TrackParticle::dxy);
Cov(2,1) = MuTrack.Covariance(TrackParticle::lambda,TrackParticle::phi);
Cov(2,2) = MuTrack.Covariance(TrackParticle::lambda,TrackParticle::dz);
Cov(2,3) = MuTrack.Covariance(TrackParticle::lambda,TrackParticle::lambda);
Cov(3,0) = MuTrack.Covariance(TrackParticle::dz,TrackParticle::dxy);
Cov(3,1) = MuTrack.Covariance(TrackParticle::dz,TrackParticle::phi);
Cov(3,2) = MuTrack.Covariance(TrackParticle::dz,TrackParticle::dz);
Cov(3,3) = MuTrack.Covariance(TrackParticle::dz,TrackParticle::lambda);
for(int i=0; i<3; i++){
for(int j=0; j<3; j++){
Cov(i+4,j+4)=PVCov(i,j);
Cov(i+7,j+7)=TauA1.Covariance(i+4,j+4);
}
}
for(int i=0; i<2; i++){
for(int j=0; j<2; j++){
Cov(i+10,j+10)=METMinusNeutrino.Cov()(i,j);
}
}
return Cov;
}
TMatrixT<double> DiTauConstrainedFitter::EstimateTauKinematicFullRecoil(TMatrixT<double> &inpar){
TMatrixT<double> outpar;
outpar.ResizeTo(6,1);
double dxy =inpar(0,0);
double phi0 =inpar(1,0);
double lam =inpar(2,0);
double dz =inpar(3,0);
TVector3 PV(inpar(4,0),inpar(5,0),inpar(6,0));
TVector3 P_Tauh(inpar(7,0), inpar(8,0), inpar(9,0));
TLorentzVector P4_Tauh; P4_Tauh.SetXYZM(P_Tauh.X(),P_Tauh.Y(),P_Tauh.Z(),PDGInfo::tau_mass());
TVector2 TauMuPt(inpar(10,0) - P_Tauh.X(), inpar(11,0) - P_Tauh.Y());
double tanphi_tau = TauMuPt.Y()/TauMuPt.X();
double a = tanphi_tau;
double b = PV.Y() - a*PV.X();
double tmu = (dxy*(cos(phi0) + a*sin(phi0)) - b) / (a*cos(phi0) - sin(phi0)); //projection onto XY plane
double xdoc = -dxy*sin(phi0) + tmu*cos(phi0);
double ydoc = dxy*cos(phi0) + tmu*sin(phi0);
double zdoc = dz + tmu*tan(lam);
TVector3 PointGuess(xdoc, ydoc, zdoc);
TVector3 TauMuDir = PointGuess - PV;
double phitau = TauMuDir.Phi();
double thetatau = TauMuDir.Theta();
outpar(0,0) = P4_Tauh.X();
outpar(1,0) = P4_Tauh.Y();
outpar(2,0) = P4_Tauh.Z();
outpar(3,0) = TauMuPt.Mod()*cos(phitau);
outpar(4,0) = TauMuPt.Mod()*sin(phitau);
outpar(5,0) = TauMuPt.Mod()/tan(thetatau);
Logger(Logger::Debug) << "PV: " << inpar(4,0) << ", " << inpar(5,0) << ", " << inpar(6,0) << std::endl;
Logger(Logger::Debug) << "dxy, phi0, lam, dz: " << dxy << ", " << phi0 << ", " << lam << ", " << dz << std::endl;
Logger(Logger::Debug) << "PointGuess: " << xdoc << ", " << ydoc << ", " << zdoc << std::endl;
Logger(Logger::Debug) << "DirGuess: " << TauMuDir.X() << ", " << TauMuDir.Y() << ", " << TauMuDir.Z() << std::endl;
Logger(Logger::Debug) << "a, b, t: " << a << ", " << b << ", " << tmu << std::endl;
Logger(Logger::Debug) << "TauH X, Y: " << inpar(7,0) << ", " << inpar(8,0) << std::endl;
Logger(Logger::Debug) << "TauMuDir.Phi(): " << TauMuDir.Phi() << " TauH phi: " << atan2(inpar(8,0), inpar(7,0)) << std::endl;
Logger(Logger::Debug) << "dPhi: " << TauMuDir.Phi() - atan2(inpar(8,0), inpar(7,0)) << "/pi= " << (TauMuDir.Phi() - atan2(inpar(8,0), inpar(7,0)))/TMath::Pi() << std::endl;
return outpar;
}
TMatrixDSym DiTauConstrainedFitter::EstimateTauKinematicErrorFullRecoil(LorentzVectorParticle TauA1, TLorentzVector TauMu, PTObject ResPtEstimate){
double TauMuPt = sqrt(pow(ResPtEstimate.X() - TauA1.LV().X(), 2.) + pow(ResPtEstimate.Y() - TauA1.LV().Y(), 2.));
TMatrixDSym TauA1_ZPt_Cov(4);
for(int i_row = 0; i_row<ResPtEstimate.Cov().GetNrows(); i_row++){
for(int i_col = 0; i_col<ResPtEstimate.Cov().GetNcols(); i_col++){
TauA1_ZPt_Cov(i_row,i_col) = TauA1.Covariance(i_row + LorentzVectorParticle::px, i_col + LorentzVectorParticle::px);
TauA1_ZPt_Cov(i_row+2,i_col+2) = ResPtEstimate.Cov()(i_row, i_col);
}
}
TMatrixD Jacobi(3,4);
Jacobi(0,0) = -1.;
Jacobi(0,2) = +1.;
Jacobi(1,1) = -1.;
Jacobi(1,3) = +1.;
Jacobi(2,0) = -TauA1.LV().X()/TauMuPt*tan(TauMu.Theta());
Jacobi(2,1) = +ResPtEstimate.X()/TauMuPt*tan(TauMu.Theta());
Jacobi(2,2) = -TauA1.LV().Y()/TauMuPt*tan(TauMu.Theta());
Jacobi(2,3) = +ResPtEstimate.Y()/TauMuPt*tan(TauMu.Theta());
TMatrixDSym TauMuCov(TauA1_ZPt_Cov);
TauMuCov.Similarity(Jacobi);
if(Logger::Instance()->Level() == Logger::Debug){
Logger(Logger::Debug) << "TauA1_ZPt_Cov: " << std::endl;
TauA1_ZPt_Cov.Print();
Logger(Logger::Debug) << "Jacobi: " << std::endl;
Jacobi.Print();
Logger(Logger::Debug) << "TauMuCov: " << std::endl;
TauMuCov.Print();
}
return TauMuCov;
}
double DiTauConstrainedFitter::CosThetaTauMu(TLorentzVector TauMu){
double dxy = MuTrack_.Parameter(TrackParticle::dxy);
double phi0 = MuTrack_.Parameter(TrackParticle::phi);
double lam = MuTrack_.Parameter(TrackParticle::lambda);
double dz = MuTrack_.Parameter(TrackParticle::dz);
double tanphi_tau = TauMu.Y()/TauMu.X();
double a = tanphi_tau;
double b = PV_.Y() - a*PV_.X();
double tmu = (dxy*(cos(phi0) + a*sin(phi0)) - b) / (a*cos(phi0) - sin(phi0)); //projection onto XY plane
double xdoc = -dxy*sin(phi0) + tmu*cos(phi0);
double ydoc = dxy*cos(phi0) + tmu*sin(phi0);
double zdoc = dz + tmu*tan(lam);
TVector3 PointGuess(xdoc, ydoc, zdoc);
TVector3 TauMuDir = PointGuess - PV_;
return TauMuDir.CosTheta();
}
| [
"[email protected]"
] | |
fd73896b8542fd41079229ea248085150ec70233 | 5cce90d8a8c739da50997ae31980407f3b79c60c | /code/userprog/memorymanager.cc | af7319259b85494091f9611138c43eeb55598cd0 | [] | no_license | ronel129/code | da44af8cc35317cf5bedcf99dfc90b348ed73b43 | f62c37d795aed720dfbb743ff4c9f89abc3cff46 | refs/heads/master | 2016-08-04T21:49:43.980362 | 2013-04-09T01:46:59 | 2013-04-09T01:46:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,490 | cc | // memorymanager.cc
// A memory manager helper class. Used by address space to make nachos use contigous virtual memory.
#include "memorymanager.h"
#include "machine.h"
//----------------------------------------------------------------------
// MemoryManager::MemoryManager
// Initialize a memory manager with a bitmap of "NumPhysPages"
//----------------------------------------------------------------------
MemoryManager::MemoryManager():bitMap(NumPhysPages){
}
//----------------------------------------------------------------------
// MemoryManager::~MemoryManager
//----------------------------------------------------------------------
MemoryManager::~MemoryManager() {
}
//----------------------------------------------------------------------
// MemoryManager::GetPage
//----------------------------------------------------------------------
int MemoryManager::GetPage() {
return bitMap.Find();
}
//----------------------------------------------------------------------
// MemoryManager::ClearPage
// Take the index "i" of a page and clears this bit.
//----------------------------------------------------------------------
void MemoryManager::ClearPage(int i) {
bitMap.Clear(i);
}
//----------------------------------------------------------------------
// MemoryManager::GetClearPages
// Return the number of clear pages
//----------------------------------------------------------------------
int MemoryManager::GetClearPages() {
return bitMap.NumClear();
}
| [
"[email protected]"
] | |
046222b9243dd8eb8970b224c024b36d4eb8d6ca | ce9cdf053f77b2192b75d1912b8b227216c51498 | /pynq_chainer/HLS/src/include_hls/hls/dsp/utils/hls_cordic.h | 5f9c92835b22d25d9c6aedd258020e4314c81af0 | [
"MIT"
] | permissive | tkat0/pynq-chainer | bf0fcf2bc4261ec68d1f7239a584794499017ee8 | 30ffed5d08cd37207841623fcdaae4328d6e26eb | refs/heads/master | 2020-05-27T20:49:25.152182 | 2017-07-09T06:27:59 | 2017-07-09T06:27:59 | 82,570,098 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,457 | h | /*****************************************************************************
*
* Author: Xilinx, Inc.
*
* This text contains proprietary, confidential information of
* Xilinx, Inc. , is distributed by under license from Xilinx,
* Inc., and may be used, copied and/or disclosed only pursuant to
* the terms of a valid license agreement with Xilinx, Inc.
*
* XILINX IS PROVIDING THIS DESIGN, CODE, OR INFORMATION "AS IS"
* AS A COURTESY TO YOU, SOLELY FOR USE IN DEVELOPING PROGRAMS AND
* SOLUTIONS FOR XILINX DEVICES. BY PROVIDING THIS DESIGN, CODE,
* OR INFORMATION AS ONE POSSIBLE IMPLEMENTATION OF THIS FEATURE,
* APPLICATION OR STANDARD, XILINX IS MAKING NO REPRESENTATION
* THAT THIS IMPLEMENTATION IS FREE FROM ANY CLAIMS OF INFRINGEMENT,
* AND YOU ARE RESPONSIBLE FOR OBTAINING ANY RIGHTS YOU MAY REQUIRE
* FOR YOUR IMPLEMENTATION. XILINX EXPRESSLY DISCLAIMS ANY
* WARRANTY WHATSOEVER WITH RESPECT TO THE ADEQUACY OF THE
* IMPLEMENTATION, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OR
* REPRESENTATIONS THAT THIS IMPLEMENTATION IS FREE FROM CLAIMS OF
* INFRINGEMENT, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE.
*
* Xilinx products are not intended for use in life support appliances,
* devices, or systems. Use in such applications is expressly prohibited.
*
* (c) Copyright 2014 Xilinx Inc.
* All rights reserved.
*
*****************************************************************************/
#ifndef HLS_CORDIC_H
#define HLS_CORDIC_H
#include "hls/dsp/utils/hls_cordic_functions.h"
namespace hls {
#if (defined(CordicFunction) || \
defined(CoarseRotate) || \
defined(DataFormat) || \
defined(PhaseFormat) || \
defined(InputWidth) || \
defined(OutputWidth) || \
defined(Iterations) || \
defined(Precision) || \
defined(RoundMode) || \
defined(ScaleComp))
#error One or more of the template parameters used by this function is already defined and will cause a conflict
#endif
// ===================================================================================================================
// CORDIC: Entry point function.
// o Template parameters:
// - CordicFunction : Selects the CORDIC function to implement
// - CoarseRotate : When true, extends the input/output range from the first quadrant [-pi/4,+pi/4] to the full circle
// - DataFormat : Selects between unsigned fraction (with integer width of 1 bit) and unsigned integer formats
// - PhaseFormat : Selects whether the phase is expressed in radians or scaled radians (pi * 1 radian)
// - InputWidth : Defines overall input data width
// - OutputWidth : Defines overall output data width
// - Iterations : Overrides automatic calculation of required number of iterations to meet precision requirements
// - Precision : Overrides automatic calculation of internal precision requirements
// - RoundMode : Selects the rounding mode to apply to the output data
// - ScaleComp : Enables compensation of the CORDIC magnitude scale factor at the output, for rotation and translation only
// o Arguments:
// - inputData : Input with format dependent on CordicFunction. See hls_cordic_functions.h for details
// - outputData : Output with format dependent on CordicFunction. See hls_cordic_functions.h for details
// o The CORDIC function applies its own rounding, therefore the interface ap_fixed types need not specify rounding and saturation modes
template <
int CordicFunction,
bool CoarseRotate,
int DataFormat,
int PhaseFormat,
int InputWidth,
int OutputWidth,
int Iterations,
int Precision,
int RoundMode,
int ScaleComp
> void cordic_base(const cordic_inputs<InputWidth,CordicFunction,DataFormat> &inputData,
cordic_outputs<OutputWidth,CordicFunction,DataFormat> &outputData) {
Function_cordic_base:;
#ifndef __SYNTHESIS__
// Verify template parameters are correct in simulation
if ((CordicFunction < CORDIC_F_ROTATE) || (CordicFunction > CORDIC_F_SQRT)) {
std::cout << "ERROR: " << __FILE__ << ": CordicFunction must be in range 0 (CORDIC_F_ROTATE) to 6 (CORDIC_F_SQRT)" << std::endl;
exit(1);
}
if (CordicFunction != CORDIC_F_SQRT && DataFormat != CORDIC_FORMAT_SIG_FRAC) {
std::cout << "ERROR: " << __FILE__ << ": DataFormat must be " << CORDIC_FORMAT_SIG_FRAC << " for this function" << std::endl;
exit(1);
}
if (CordicFunction == CORDIC_F_SQRT && DataFormat == CORDIC_FORMAT_SIG_FRAC) {
std::cout << "ERROR: " << __FILE__ << ": DataFormat must be " << CORDIC_FORMAT_USIG_INT << " or " << CORDIC_FORMAT_USIG_FRAC << " for square root" << std::endl;
exit(1);
}
if((PhaseFormat != CORDIC_FORMAT_RAD) && (PhaseFormat != CORDIC_FORMAT_SCA)) {
std::cout << "ERROR: " << __FILE__ << ": PhaseFormat must be " << CORDIC_FORMAT_RAD << " or " << CORDIC_FORMAT_SCA << std::endl;
exit(1);
}
if((InputWidth < CORDIC_DATA_WIDTH_MIN) || (InputWidth > CORDIC_DATA_WIDTH_MAX)) {
std::cout << "ERROR: " << __FILE__ << ": InputWidth must be " << CORDIC_DATA_WIDTH_MIN << " to " << CORDIC_DATA_WIDTH_MAX << std::endl;
exit(1);
}
if ((CordicFunction != CORDIC_F_SQRT) || (DataFormat != CORDIC_FORMAT_USIG_INT)) {
if ( (OutputWidth < CORDIC_DATA_WIDTH_MIN) || (OutputWidth > CORDIC_DATA_WIDTH_MAX)) {
std::cout << "ERROR: " << __FILE__ << ": OutputWidth must be " << CORDIC_DATA_WIDTH_MIN << " to " << CORDIC_DATA_WIDTH_MAX << std::endl;
exit(1);
}
} else {
//Minimum value has to change as output width is fixed to int(input_width/2)+1 then unsigned integer format
if ((InputWidth/2+1) != OutputWidth) {
std::cout << "ERROR: " << __FILE__ << ": OutputWidth must be " << InputWidth/2+1 << " for integer square root with input width " << InputWidth << std::endl;
exit(1);
}
}
if (( (Precision != 0) && (Precision < OutputWidth) ) || (Precision > CORDIC_DATA_WIDTH_MAX ) || (Precision < 0)) {
std::cout << "ERROR: " << __FILE__ << ": Precision must be >= OutputWidth, <= " << CORDIC_DATA_WIDTH_MAX << " and > 0" << std::endl;
exit(1);
}
if ((RoundMode < CORDIC_ROUND_TRUNCATE) || (RoundMode > CORDIC_ROUND_NEAREST_EVEN)) {
std::cout << "ERROR: " << __FILE__ << ": RoundMode must be " << CORDIC_ROUND_TRUNCATE << " to " << CORDIC_ROUND_NEAREST_EVEN << std::endl;
exit(1);
}
if ((ScaleComp < CORDIC_SCALE_NONE) || (ScaleComp > CORDIC_SCALE_EMB_MULT)) {
std::cout << "ERROR: " << __FILE__ << ": ScaleComp must be " << CORDIC_SCALE_NONE << " to " << CORDIC_SCALE_EMB_MULT << std::endl;
exit(1);
}
#endif
const int ITERATIONS_INT = c_iterations_int<CordicFunction,CoarseRotate,Iterations,OutputWidth,RoundMode,InputWidth,DataFormat>::prec;
const int PRECISION_INT = c_precision_int<CordicFunction,CoarseRotate,DataFormat,InputWidth,Iterations,OutputWidth,Precision,RoundMode>::prec;
const ap_int<PRECISION_INT> c_neg_pi_1_4_const = (PhaseFormat == CORDIC_FORMAT_RAD ?
c_neg_pi_1_4_rads_const(CORDIC_MAX_ROM_WIDTH-1,CORDIC_MAX_ROM_WIDTH-PRECISION_INT) :
c_neg_pi_1_4_jrads_const(CORDIC_MAX_ROM_WIDTH-1,CORDIC_MAX_ROM_WIDTH-PRECISION_INT)
);
const ap_int<PRECISION_INT> c_neg_pi_2_4_const = (PhaseFormat == CORDIC_FORMAT_RAD ?
c_neg_pi_2_4_rads_const(CORDIC_MAX_ROM_WIDTH-1,CORDIC_MAX_ROM_WIDTH-PRECISION_INT) :
c_neg_pi_2_4_jrads_const(CORDIC_MAX_ROM_WIDTH-1,CORDIC_MAX_ROM_WIDTH-PRECISION_INT)
);
const ap_int<PRECISION_INT> c_neg_pi_3_4_const = (PhaseFormat == CORDIC_FORMAT_RAD ?
c_neg_pi_3_4_rads_const(CORDIC_MAX_ROM_WIDTH-1,CORDIC_MAX_ROM_WIDTH-PRECISION_INT) :
c_neg_pi_3_4_jrads_const(CORDIC_MAX_ROM_WIDTH-1,CORDIC_MAX_ROM_WIDTH-PRECISION_INT)
);
const ap_int<PRECISION_INT> c_neg_pi_const = (PhaseFormat == CORDIC_FORMAT_RAD ?
c_neg_pi_rads_const(CORDIC_MAX_ROM_WIDTH-1,CORDIC_MAX_ROM_WIDTH-PRECISION_INT) :
c_neg_pi_jrads_const(CORDIC_MAX_ROM_WIDTH-1,CORDIC_MAX_ROM_WIDTH-PRECISION_INT)
);
const ap_uint<1> ENG_MODE = CORDIC_get_eng_mode(CordicFunction);
ap_uint<1> add_nsub_x_int_v, add_nsub_y_int_v, add_nsub_p_int_v;
ap_uint<1> transform_type_v = CORDIC_get_transform_type(CordicFunction);
const ap_int<PRECISION_INT> c_inv_scale = CORDIC_inv_cordic_scale_slv<CordicFunction,CoarseRotate,DataFormat,InputWidth,Iterations,OutputWidth,Precision,RoundMode>();
const int CTRL_WIDTH = gen_ctrl_width<CoarseRotate>::width;
ap_int<InputWidth> x_in, y_in, phase_in;
ap_int<PRECISION_INT> data_x_int, data_x_int_v, data_x_hw_shift_v;
ap_int<PRECISION_INT> data_y_int, data_y_int_v, data_y_hw_shift_v;
ap_int<PRECISION_INT> phase_int, phase_int_v;
ap_int<PRECISION_INT> data_x_init;
ap_int<PRECISION_INT> data_y_init;
ap_int<PRECISION_INT> phase_init;
ap_uint<4> inp_data_sign_vect;
ap_int<PRECISION_INT+1> data_x_init_ext;
ap_int<PRECISION_INT+1> data_y_init_ext;
ap_int<PRECISION_INT+1> inp_x_min_y_ext;
ap_int<PRECISION_INT+1> inp_x_plus_y_ext;
ap_int<PRECISION_INT> inp_data_x_cr_async;
ap_int<PRECISION_INT> inp_data_y_cr_async;
ap_int<PRECISION_INT> inp_phase_cr_async;
ap_uint<2> inp_data_quad;
ap_uint<3> inp_phase_sign_vect;
ap_int<PRECISION_INT> inp_phase_pi_3_rot;
ap_int<PRECISION_INT> inp_phase_pi_1_rot;
ap_uint<2> inp_phase_quad;
ap_uint<4> inp_phase_data_quad;
ap_uint<CTRL_WIDTH> inp_ctrl_cr_async;
ap_int<PRECISION_INT> inp_data_x_cr;
ap_int<PRECISION_INT> inp_data_y_cr;
ap_int<PRECISION_INT> inp_phase_cr ;
ap_uint<CTRL_WIDTH> inp_ctrl_cr ;
ap_int<PRECISION_INT> data_x_inp;
ap_int<PRECISION_INT> data_y_inp;
ap_int<PRECISION_INT> phase_inp ;
ap_uint<CTRL_WIDTH> ctrl_inp ;
ap_int<PRECISION_INT> data_x_eng;
ap_int<PRECISION_INT> data_y_eng;
ap_int<PRECISION_INT> phase_eng ;
ap_uint<CTRL_WIDTH> ctrl_eng ;
ap_int<PRECISION_INT> outp_data_x_cr;
ap_int<PRECISION_INT> outp_data_y_cr;
ap_int<PRECISION_INT> outp_phase_cr ;
ap_uint<2> outp_cr_quad ;
ap_int<PRECISION_INT> outp_data_x_sca;
ap_int<PRECISION_INT> outp_data_y_sca;
ap_int<PRECISION_INT> outp_phase_sca ;
ap_int<2*PRECISION_INT> outp_data_x_sca_ext;
ap_int<2*PRECISION_INT> outp_data_y_sca_ext;
ap_int<2*PRECISION_INT> outp_phase_sca_ext ;
ap_int<OutputWidth> outp_data_x_rnd;
ap_int<OutputWidth> outp_data_y_rnd;
ap_int<OutputWidth> outp_phase_rnd ;
ap_int<OutputWidth> data_x_outp;
ap_int<OutputWidth> data_y_outp;
ap_int<OutputWidth> phase_outp;
ap_int<PRECISION_INT> sqrt_data_trunc_async;
ap_int<PRECISION_INT> sqrt_data_trunc_async_ext;
ap_int<OutputWidth> sqrt_data_round_async;
ap_int<PRECISION_INT> eng_rom_vect[ITERATIONS_INT];
// Initialize ROM contents, if required
fn_rom_data_int<CordicFunction,CoarseRotate,DataFormat,InputWidth,Iterations,OutputWidth,RoundMode,Precision,PhaseFormat,ITERATIONS_INT, PRECISION_INT>(eng_rom_vect);
// Internal variables to hold FIFO read and write contents
cordic_inputs<InputWidth,CordicFunction,DataFormat> din;
cordic_outputs<OutputWidth,CordicFunction,DataFormat> dout;
// Input read
din = inputData;
// Extract subfields, reformat to internal types
get_inputs<InputWidth,CordicFunction,DataFormat>(din,x_in,y_in,phase_in);
// Scale inputs to suit internal precision
const int SCALE_UP = (PRECISION_INT - InputWidth);
const int SCALE_DOWN = (InputWidth - PRECISION_INT);
if (PRECISION_INT > InputWidth) {
data_x_int = ap_int<PRECISION_INT>(x_in) << SCALE_UP;
data_y_int = ap_int<PRECISION_INT>(y_in) << SCALE_UP;
phase_int = ap_int<PRECISION_INT>(phase_in) << SCALE_UP;
} else if (PRECISION_INT < InputWidth) {
data_x_int = x_in >> SCALE_DOWN;
data_y_int = y_in >> SCALE_DOWN;
phase_int = phase_in >> SCALE_DOWN;
} else {
data_x_int = x_in;
data_y_int = y_in;
phase_int = phase_in;
}
// Implicit sign-extension or truncation during assignment
switch (CordicFunction) {
case CORDIC_F_ROTATE:
data_x_init = data_x_int;
data_y_init = data_y_int;
phase_init = phase_int;
break;
case CORDIC_F_TRANSLATE:
case CORDIC_F_ATAN:
case CORDIC_F_ATANH:
data_x_init = data_x_int;
data_y_init = data_y_int;
phase_init = 0;
break;
case CORDIC_F_SIN_COS:
case CORDIC_F_SINH_COSH:
data_x_init = c_inv_scale;
data_y_init = 0;
phase_init = phase_int;
break;
default: // case CORDIC_F_SQRT
data_x_init = data_x_int;
data_y_init = 0;
phase_init = 0;
}
if (CordicFunction != CORDIC_F_SQRT) {
if (CoarseRotate) {
// implicit sign-extend
data_x_init_ext = data_x_init;
data_y_init_ext = data_y_init;
inp_x_plus_y_ext = data_x_init_ext + data_y_init;
inp_x_min_y_ext = data_x_init_ext - data_y_init;
inp_data_sign_vect[3] = inp_x_min_y_ext[PRECISION_INT];
inp_data_sign_vect[2] = inp_x_plus_y_ext[PRECISION_INT];
inp_data_sign_vect[1] = data_x_init_ext[PRECISION_INT];
inp_data_sign_vect[0] = data_y_init_ext[PRECISION_INT];
inp_data_quad[1] = ~inp_data_sign_vect[3];
inp_data_quad[0] = ~inp_data_sign_vect[2];
ap_int<PRECISION_INT+1> a, b, x, c, d, y;
a(PRECISION_INT,1) = 0;
a[0] = ap_uint<1>(1);
inp_data_x_cr_async_loop : for (int i=1; i<PRECISION_INT+1; i++) {
if (inp_data_sign_vect(3,2) == 0) {
b[i] = data_x_init[i-1];
} else if (inp_data_sign_vect(3,2) == 2) {
b[i] = data_y_init[i-1];
} else if (inp_data_sign_vect(3,2) == 3) {
b[i] = ~data_x_init[i-1];
} else {
b[i] = ~data_y_init[i-1];
}
}
b[0] = inp_data_sign_vect[2];
x = a + b;
inp_data_x_cr_async = x(PRECISION_INT,1);
c(PRECISION_INT,1) = 0;
c[0] = ap_uint<1>(1);
inp_data_y_cr_async_loop : for (int i=1; i<PRECISION_INT+1; i++) {
if (inp_data_sign_vect(3,2) == 0) {
d[i] = data_y_init[i-1];
} else if (inp_data_sign_vect(3,2) == 2) {
d[i] = ~data_x_init[i-1];
} else if (inp_data_sign_vect(3,2) == 3) {
d[i] = ~data_y_init[i-1];
} else {
d[i] = data_x_init[i-1];
}
}
d[0] = inp_data_sign_vect[3];
y = c + d;
inp_data_y_cr_async = y(PRECISION_INT,1);
// No add/sub optimization required here
if (phase_init < 0) {
inp_phase_pi_3_rot = phase_init - c_neg_pi_3_4_const;
inp_phase_pi_1_rot = phase_init - c_neg_pi_1_4_const;
} else {
inp_phase_pi_3_rot = phase_init + c_neg_pi_3_4_const;
inp_phase_pi_1_rot = phase_init + c_neg_pi_1_4_const;
}
inp_phase_sign_vect[2] = phase_init[PRECISION_INT-1];
inp_phase_sign_vect[1] = inp_phase_pi_3_rot[PRECISION_INT-1];
inp_phase_sign_vect[0] = inp_phase_pi_1_rot[PRECISION_INT-1];
switch (inp_phase_sign_vect) {
case 3:
case 4:
inp_phase_cr_async = phase_init;
inp_phase_quad = 3;
break;
case 2:
inp_phase_cr_async = phase_init + c_neg_pi_2_4_const;
inp_phase_quad = 1;
break;
case 0:
inp_phase_cr_async = phase_init + c_neg_pi_const;
inp_phase_quad = 0;
break;
case 5:
inp_phase_cr_async = phase_init - c_neg_pi_2_4_const;
inp_phase_quad = 2;
break;
default: // case 7
inp_phase_cr_async = phase_init - c_neg_pi_const;
inp_phase_quad = 0;
}
// Combine coarse rotation from phase and data inputs
inp_phase_data_quad[3] = inp_phase_quad[1];
inp_phase_data_quad[2] = inp_phase_quad[0];
inp_phase_data_quad[1] = inp_data_quad[1];
inp_phase_data_quad[0] = inp_data_quad[0];
switch (inp_phase_data_quad) {
case 0:
case 6:
case 9:
case 15:
inp_ctrl_cr_async = 6;
break;
case 1:
case 4:
case 11:
case 14:
inp_ctrl_cr_async = 4;
break;
case 3:
case 5:
case 10:
case 12:
inp_ctrl_cr_async = 0;
break;
default: // cases 2,7,8,13
inp_ctrl_cr_async = 2;
}
} // end if CoarseRotate
// Select between coarse rotate pass through input data
if (!CoarseRotate) {
inp_data_x_cr = data_x_init;
inp_data_y_cr = data_y_init;
inp_phase_cr = phase_init;
} else {
inp_data_x_cr = inp_data_x_cr_async;
inp_data_y_cr = inp_data_y_cr_async;
inp_phase_cr = inp_phase_cr_async;
}
inp_ctrl_cr = inp_ctrl_cr_async;
data_x_inp = inp_data_x_cr;
data_y_inp = inp_data_y_cr;
phase_inp = inp_phase_cr;
ctrl_inp = inp_ctrl_cr;
//Implement CORDIC engine stage
if ( ( ( ( (ENG_MODE == 1) && (data_y_inp<0) ) ||
( (ENG_MODE == 0) && (phase_inp>=0) )
) && (transform_type_v == 1) ) ||
( ( ( (ENG_MODE == 1) && (data_y_inp>=0) ) ||
( (ENG_MODE == 0) && (phase_inp<0 ) )
) && (transform_type_v == 0) )
) {
add_nsub_x_int_v = 1;
} else {
add_nsub_x_int_v = 0;
}
if ( ( (ENG_MODE == 1) && (data_y_inp<0) ) ||
( (ENG_MODE == 0) && (phase_inp>=0) )
) {
add_nsub_y_int_v = 1;
} else {
add_nsub_y_int_v = 0;
}
if ( ( (ENG_MODE == 1) && (data_y_inp>=0) ) ||
( (ENG_MODE == 0) && (phase_inp<0) )
) {
add_nsub_p_int_v = 1;
} else {
add_nsub_p_int_v = 0;
}
data_x_int_v = data_x_inp;
data_y_int_v = data_y_inp;
phase_int_v = phase_inp;
iteration_loop : for (int i=0; i < ITERATIONS_INT; i++) {
int i_int_v = CORDIC_get_current_iteration(i,(int)transform_type_v);
data_x_hw_shift_v = data_x_int_v >> (i_int_v + 1);
data_y_hw_shift_v = data_y_int_v >> (i_int_v + 1);
// Optimized add/sub
ap_int<PRECISION_INT+1> a, b, x, c, d, y, e, f, z;
a = (data_x_int_v,ap_uint<1>(1));
data_x_int_v_loop : for (int i=1; i<PRECISION_INT+1; i++) {
if (add_nsub_x_int_v == 1) {
b[i] = data_y_hw_shift_v[i-1];
} else {
b[i] = ~data_y_hw_shift_v[i-1];
}
}
b[0] = ~add_nsub_x_int_v[0];
x = a + b;
data_x_int_v = x(PRECISION_INT,1);
c = (data_y_int_v,ap_uint<1>(1));
data_y_int_v_loop : for (int i=1; i<PRECISION_INT+1; i++) {
if (add_nsub_y_int_v == 1) {
d[i] = data_x_hw_shift_v[i-1];
} else {
d[i] = ~data_x_hw_shift_v[i-1];
}
}
d[0] = ~add_nsub_y_int_v[0];
y = c + d;
data_y_int_v = y(PRECISION_INT,1);
e = (phase_int_v,ap_uint<1>(1));
phase_int_v_loop : for (int i=1; i<PRECISION_INT+1; i++) {
if (add_nsub_p_int_v == 1) {
f[i] = eng_rom_vect[i_int_v][i-1];
} else {
f[i] = ~eng_rom_vect[i_int_v][i-1];
}
}
f[0] = ~add_nsub_p_int_v[0];
z = e + f;
phase_int_v = z(PRECISION_INT,1);
// End optimized add/sub
if ( ( ( ( (ENG_MODE == 1) && (data_y_int_v<0) ) ||
( (ENG_MODE == 0) && (phase_int_v>=0) )
) && (transform_type_v == 1) ) ||
( ( ( (ENG_MODE == 1) && (data_y_int_v>=0) ) ||
( (ENG_MODE == 0) && (phase_int_v<0 ) )
) && (transform_type_v == 0) )
) {
add_nsub_x_int_v = 1;
} else {
add_nsub_x_int_v = 0;
}
if ( ( (ENG_MODE == 1) && (data_y_int_v<0) ) ||
( (ENG_MODE == 0) && (phase_int_v>=0) )
) {
add_nsub_y_int_v = 1;
} else {
add_nsub_y_int_v = 0;
}
if ( ( (ENG_MODE == 1) && (data_y_int_v>=0) ) ||
( (ENG_MODE == 0) && (phase_int_v<0) )
) {
add_nsub_p_int_v = 1;
} else {
add_nsub_p_int_v = 0;
}
} // for i
data_x_eng = data_x_int_v;
data_y_eng = data_y_int_v;
phase_eng = phase_int_v;
ctrl_eng = ctrl_inp;
// Apply coarse rotation correction
if (!CoarseRotate) {
outp_data_x_cr = data_x_eng;
outp_data_y_cr = data_y_eng;
outp_phase_cr = phase_eng;
} else {
outp_cr_quad = ctrl_eng >> 1;
if (ENG_MODE == 0){
ap_int<PRECISION_INT+1> a, b, x, c, d, y;
a(PRECISION_INT,1) = 0;
a[0] = ap_uint<1>(1);
outp_data_x_cr_loop : for (int i=1; i<PRECISION_INT+1; i++) {
if (outp_cr_quad == 3) {
b[i] = data_x_eng[i-1];
} else if (outp_cr_quad == 2) {
b[i] = data_y_eng[i-1];
} else if (outp_cr_quad == 1) {
b[i] = ~data_y_eng[i-1];
} else {
b[i] = ~data_x_eng[i-1];
}
}
b[0] = ~outp_cr_quad[1];
x = a + b;
outp_data_x_cr = x(PRECISION_INT,1);
c(PRECISION_INT,1) = 0;
c[0] = ap_uint<1>(1);
outp_data_y_cr_loop : for (int i=1; i<PRECISION_INT+1; i++) {
if (outp_cr_quad == 3) {
d[i] = data_y_eng[i-1];
} else if (outp_cr_quad == 2) {
d[i] = ~data_x_eng[i-1];
} else if (outp_cr_quad == 1) {
d[i] = data_x_eng[i-1];
} else {
d[i] = ~data_y_eng[i-1];
}
}
d[0] = ~outp_cr_quad[0];
y = c + d;
outp_data_y_cr = y(PRECISION_INT,1);
outp_phase_cr = phase_eng;
} else {
outp_data_x_cr = data_x_eng;
outp_data_y_cr = data_y_eng;
switch(outp_cr_quad) {
case 3:
outp_phase_cr = phase_eng;
break;
case 2:
outp_phase_cr = phase_eng + c_neg_pi_2_4_const;
break;
case 0:
if (phase_eng>=0) {
outp_phase_cr = phase_eng + c_neg_pi_const;
} else {
outp_phase_cr = phase_eng - c_neg_pi_const;
}
break;
default:
// case 1:
outp_phase_cr = phase_eng - c_neg_pi_2_4_const;
}
}
}
// Apply Scaling Correction
if (ScaleComp != CORDIC_SCALE_NONE ) {
outp_data_x_sca_ext = c_inv_scale;
outp_data_x_sca_ext = outp_data_x_sca_ext * outp_data_x_cr;
outp_data_x_sca = outp_data_x_sca_ext(2*PRECISION_INT-3,PRECISION_INT-2);
outp_data_y_sca_ext = c_inv_scale;
outp_data_y_sca_ext = outp_data_y_sca_ext * outp_data_y_cr;
outp_data_y_sca = outp_data_y_sca_ext(2*PRECISION_INT-3,PRECISION_INT-2);
outp_phase_sca = outp_phase_cr;
} else {
outp_data_x_sca = outp_data_x_cr;
outp_data_y_sca = outp_data_y_cr;
outp_phase_sca = outp_phase_cr;
}
outp_data_x_rnd = CORDIC_rnd_slv<PRECISION_INT,OutputWidth>(outp_data_x_sca,
PRECISION_INT,
RoundMode,
OutputWidth);
outp_data_y_rnd = CORDIC_rnd_slv<PRECISION_INT,OutputWidth>(outp_data_y_sca,
PRECISION_INT,
RoundMode,
OutputWidth);
outp_phase_rnd = CORDIC_rnd_slv<PRECISION_INT,OutputWidth>(outp_phase_sca,
PRECISION_INT,
RoundMode,
OutputWidth);
data_x_outp = outp_data_x_rnd;
data_y_outp = outp_data_y_rnd;
phase_outp = outp_phase_rnd;
} else { // CordicFunction == CORDIC_F_SQRT
sqrt_data_trunc_async = sqrt_slv<InputWidth,DataFormat,PRECISION_INT>(x_in);
sqrt_data_trunc_async_ext = sqrt_data_trunc_async;
const int c_rnd_mode_int = rnd_mode_int_v<CordicFunction,RoundMode>::mode;
sqrt_data_round_async = CORDIC_rnd_slv< PRECISION_INT , OutputWidth>(sqrt_data_trunc_async_ext,
PRECISION_INT,
c_rnd_mode_int,
OutputWidth);
data_x_outp = sqrt_data_round_async;
data_y_outp = 0;
phase_outp = 0;
} // end if (CordicFunction != CORDIC_F_SQRT)
set_outputs<OutputWidth,CordicFunction,DataFormat>(data_x_outp, data_y_outp, phase_outp, dout);
outputData = dout;
}
} // end namespace hls
#endif // HLS_CORDIC_H
| [
"[email protected]"
] | |
470b6ccab90ae1e2dfaab6b1e6b94d2872efb538 | 45cff8629bffd5cd15a1015326a2e7daf19655c3 | /2019/s2/pssd/week02practice/AlternateColors.hpp | edb328f145b87a2d6984477a5de8bf5e56c13791 | [] | no_license | yaoReadingCode/University-SVN | cab1cf42135345a0743a64bf771384c392fc8ffe | dacbabaab68810a91f573ba4f25eae63c8e68769 | refs/heads/master | 2023-03-27T06:58:58.592594 | 2021-03-31T10:52:30 | 2021-03-31T10:52:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,991 | hpp | #include <iostream>
#include <string>
using namespace std;
class AlternateColors
{
public:
string getColor(long r, long g, long b, long k)
{
//Initialize
string color = "NONE";
long inc = 0;
long runTime = (r + g + b);
int none = 0;
long min = r;
int minPoint = 0;
bool zero[3];
int zeroes = 0;
int index = k;
for (int i = 0; i < 3; i++)
{
zero[i] = false;
}
//Reduce to series
for (int i = 0; i < 3; i++)
{
//Ensure a non-zero minimum exists
if(r != 0)
{
min = r;
} else if (g != 0) {
min = g;
} else if (b != 0) {
min = b;
}
//Determine which has nothing left
if (r == 0 && zero[0] == false)
{
zero[0] = true;
zeroes++;
}
if (g == 0 && zero[1] == false)
{
zero[1] = true;
zeroes++;
}
if (b == 0 && zero[2] == false)
{
zero[2] = true;
zeroes++;
}
//Find the minimum
if(r < min && zero[0] == false)
{
min = r;
minPoint = 0;
}
if(g < min && zero[1] == false)
{
min = g;
minPoint = 1;
}
if(b < min && zero[2] == false)
{
min = b;
minPoint = 2;
}
//Reduce the scope of the problem
if ((min*(3-zeroes)) <= k && zeroes < 2)
{
//Reduce everything by a factor of minimum
if(zero[0] == false)
{
r = r-min;
}
if(zero[1] == false)
{
g = g-min;
}
if(zero[2] == false)
{
b = b-min;
}
k = k-(min*(3-zeroes));
//If k is reduced to nothing, find the result
if(k == 0) {
if (minPoint == 0)
{
color = "RED";
break;
}
else if (minPoint == 1)
{
color = "GREEN";
break;
}
else if (minPoint == 2)
{
color = "BLUE";
break;
}
}
}
}
//Calculate the remainer
int remain = k%(3-zeroes);
//Large If block to determine the colour
if(remain == 0 && zeroes == 0) {
color = "BLUE";
} else if (remain == 1 && zeroes == 0) {
color = "RED";
} else if (remain == 2 && zeroes == 0) {
color = "GREEN";
} else if (remain == 0 && zeroes == 1 && zero[0] == true) {
color = "BLUE";
} else if (remain == 0 && zeroes == 1 && zero[1] == true) {
color = "BLUE";
} else if (remain == 0 && zeroes == 1 && zero[2] == true) {
color = "GREEN";
} else if (remain == 1 && zeroes == 1 && zero[0] == true) {
color = "GREEN";
} else if (remain == 1 && zeroes == 1 && zero[1] == true) {
color = "RED";
} else if (remain == 1 && zeroes == 1 && zero[2] == true) {
color = "RED";
} else if (zeroes == 2 && zero[0] == false) {
color = "RED";
} else if (zeroes == 2 && zero[1] == false) {
color = "GREEN";
} else if (zeroes == 2 && zero[2] == false) {
color = "BLUE";
}
return color;
}
};
| [
"[email protected]"
] | |
04da1f5044e5943d7f6549d9751bb1b870c27973 | f20263e46c5b79ecd27a68f57c888e73a6093585 | /Actor/Characters/Enemy/TutorialEnemy/State/StateMng_TutorialEnemy.cpp | ab2161d1d96e25d07031bb1adba28aa32ddfab59 | [
"MIT"
] | permissive | Bornsoul/Revenger_JoyContinue | 63cd4365a725ce50b5c9e0d41c00e3b1eb0ff6da | 599716970ca87a493bf3a959b36de0b330b318f1 | refs/heads/master | 2020-06-13T09:50:47.245820 | 2019-09-16T05:01:50 | 2019-09-16T05:01:50 | 194,618,283 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,124 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "StateMng_TutorialEnemy.h"
UStateMng_TutorialEnemy::UStateMng_TutorialEnemy()
{
}
UStateMng_TutorialEnemy::~UStateMng_TutorialEnemy()
{
}
void UStateMng_TutorialEnemy::Init(class AGameCharacter* pRoot)
{
Super::Init(pRoot);
m_pRootCharacter_Override = Cast<ATutorialEnemy>(pRoot);
if (m_pRootCharacter_Override == nullptr)
{
ULOG(TEXT("m_pRootCharacter_Override is nullptr"));
}
m_pStateClass.Add(static_cast<int32>(E_State_TutoEnemy::E_Idle), NewObject<UState_TutoEnemy_Idle>());
m_pStateClass.Add(static_cast<int32>(E_State_TutoEnemy::E_Hit), NewObject<UState_TutoEnemy_Hit>());
m_pStateClass.Add(static_cast<int32>(E_State_TutoEnemy::E_Die), NewObject<UState_TutoEnemy_Die>());
m_pStateClass.Add(static_cast<int32>(E_State_TutoEnemy::E_Spawn), NewObject<UState_TutoEnemy_Spawn>());
for (TMap<int, class UStateRoot_GC*>::TIterator it = m_pStateClass.CreateIterator(); it; ++it)
{
it->Value->Init(this);
}
}
void UStateMng_TutorialEnemy::Destroy()
{
Super::Destroy();
m_pRootCharacter_Override = nullptr;
}
| [
"[email protected]"
] | |
b4746b9028f7e0a1d842c93d561ee6c2684fa145 | c1e982f4bbc6258dbd1a327b64ae8cf8a9e0b95c | /gui/bw/bindingwizard.h | 7db10b39afc8dcaa39ab5b7f71f7982150b55b6a | [] | no_license | dusktreader/configurator | 4d813ff864d2382ca1b0aae71685e6f8d988c678 | 90c79b07004f90db26c2a0d3caab59975be0de65 | refs/heads/master | 2021-04-09T16:52:17.042392 | 2012-08-30T04:37:25 | 2012-08-30T04:37:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 696 | h | #ifndef BINDINGWIZARD_H
#define BINDINGWIZARD_H
#include <QWizard>
#include <QWizardPage>
#include <bindingwizardintropage.h>
#include <bindingwizardtypeselectpage.h>
#include <bindingwizarddirectpage.h>
#include <bindingwizardfinitepage.h>
#include <bindingwizardnumericalpage.h>
namespace Ui {
class BindingWizard;
}
class BindingWizard : public QWizard
{
Q_OBJECT
public:
explicit BindingWizard(QWidget *parent = 0);
~BindingWizard();
int nextId() const;
int lastId;
enum PageId
{
INTRO_PAGE,
TYPE_PAGE,
DIRECT_PAGE,
FINITE_PAGE,
NUMERIC_PAGE
};
private:
Ui::BindingWizard *ui;
};
#endif // BINDINGWIZARD_H
| [
"[email protected]"
] | |
4b2ab3fa499d7ea0016c9635103b7f9b9bd72c73 | 4e5e1fdff04cd9c642e32c01769aa01fa2d15476 | /4153/main.cpp | d282083b4dade9b9cf06cd7c19393deb900d5c00 | [] | no_license | WashSwang/SJTUOJ | 2ef775270f2600bbfdc32ae17d8a25d37c4fe31b | 33b15363a014304c79f62596e4511f65482b8ff1 | refs/heads/master | 2020-03-29T11:42:37.640147 | 2018-11-17T08:52:07 | 2018-11-17T08:52:07 | 149,866,648 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,301 | cpp | #include <iostream>
#include <algorithm>
using namespace std;
int l,r,m,n,k,a[200000],mid,ans;
bool test(int x){
int now=a[0],len=1;
if (k==1){
for (int i=1;i<n;++i)
if (a[i]-now>=x) {
now=a[i];
len++;
if (len>=m) return true;
}
return false;
}
else{
int p[200000],q[200000];
p[0]=1;
for (int i=1;i<n;++i) {
if (a[i] - now >= x) {
now = a[i];
len++;
p[i] = len;
} else p[i] = p[i - 1];
}
if (p[n-1]>=m) return true;
now=a[n-1];
q[n-1]=1;
len=1;
for (int i=n-2;i>=0;--i){
if (now-a[i]>=x) {
now=a[i];
len++;
q[i]=len;
}
else q[i]=q[i+1];
if (p[i]+q[i+1]>=m) return true;
}
if (q[0]>=m) return true;
return false;
}
}
int main() {
cin>>n>>m>>k;
for (int i=0;i<n;++i)
cin>>a[i];
sort(a,a+n);
l=0;
r=2000000000;
while (l<=r)
{
mid=(r-l)/2+l;
if (test(mid)){
if (mid>ans) ans=mid;
l=mid+1;
}
else r=mid-1;
}
cout<<ans;
return 0;
} | [
"[email protected]"
] | |
504cc577e263c6fe67d1786e6f64294e8347ac11 | 93a2743d1a0ed709ae75f2736617333c9563e2a3 | /src/cmp/BusIc.cpp | 19ba3fb7573d0716b9bf61031ce4e613452b4ec2 | [
"Apache-2.0"
] | permissive | nikitainikitin/cmpexplore | cd6d29727465505ae35decf43e30b2d6594a978a | c39278daa4a65d8cdc1dacb88c0b631f20180dbb | refs/heads/master | 2021-01-16T23:09:50.808346 | 2014-03-13T22:50:45 | 2014-03-13T22:50:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,069 | cpp | // ----------------------------------------------------------------------
// Copyright 2011-2012 Nikita Nikitin <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------
#include <iostream>
#include "BusIc.hpp"
#include "Cluster.hpp"
#include "CmpConfig.hpp"
#include "Config.hpp"
#include "../model/BusModel.hpp"
using std::cout;
using std::endl;
namespace cmpex {
extern cmp::CmpConfig cmpConfig;
extern Config config;
using namespace model;
namespace cmp {
//=======================================================================
/*
* Constructors and destructor
*/
BusIc::BusIc (Cluster * c, UInt subnCnt) : Interconnect (ITBUS, c, subnCnt),
accessTime_ (1) {}
BusIc::~BusIc () {}
//=======================================================================
/*
* Returns hop-count distance from component with index 'srcIdx' to
* another component with index 'dstIdx'.
*/
int BusIc::DistanceCompToComp (UShort srcIdx, UShort dstIdx)
{
//return AccessTime();
return 1;
}
//=======================================================================
/*
* Returns hop-count distance from component with index 'idx' to
* the Iface component.
* Assume Iface component is in the top-right tile.
*/
int BusIc::DistanceCompToIface (UShort idx)
{
//return AccessTime();
return 1;
}
//=======================================================================
/*
* Returns latency from component with index 'srcIdx' to
* another component with latency 'dstIdx'.
*/
double BusIc::LatencyCompToComp (UShort srcIdx, UShort dstIdx, UShort pSize, bool dynamic, UShort subnIdx)
{
return AccessTime()*pSize + (dynamic ? BufDelay(subnIdx, srcIdx) : 0.0);
}
//=======================================================================
/*
* Returns latency from component with index 'idx' to the memory
* controller 'mcIdx'.
* Assume routers are placed in the top-right corner of the tile.
*/
double BusIc::LatencyCompToMemCtrl (UShort idx, UShort mcIdx, UShort pSize, bool dynamic, UShort subnIdx)
{
return AccessTime()*pSize + (dynamic ? BufDelay(subnIdx, idx) : 0.0);
}
//=======================================================================
/*
* Returns latency from memory controller with index 'mcIdx' to
* component with index 'idx'.
* Assume routers are placed in the top-right corner of the tile.
*/
double BusIc::LatencyMemCtrlToComp (UShort mcIdx, UShort idx, UShort pSize, bool dynamic, UShort subnIdx)
{
cout << "Warning: memory controllers are not fully supported in connection with buses" << endl;
cout << "Warning: buffers for MCs should be added to BusIC for dynamic latency" << endl;
return AccessTime()*pSize; // + dynamic latency in MC buffer
}
//=======================================================================
/*
* Returns latency from component with index 'idx' to
* the interface component.
* Assume that the interface component is the last one in the list.
*/
double BusIc::LatencyCompToIface (UShort idx, UShort pSize, bool dynamic, UShort subnIdx)
{
return AccessTime()*pSize + (dynamic ? BufDelay(subnIdx, idx) : 0.0);
}
//=======================================================================
/*
* Returns latency from the interface component to
* component with index 'idx'.
* Assume that the interface component is the last one in the list.
*/
double BusIc::LatencyIfaceToComp (UShort idx, UShort pSize, bool dynamic, UShort subnIdx)
{
return AccessTime()*pSize + (dynamic ? BufDelay(subnIdx, TotalCompCnt()-1) : 0.0);
}
//=======================================================================
/*
* Follow route between components and save traffic rates into the matrix.
*/
void BusIc::MarkPathCompToComp (UShort srcIdx, UShort dstIdx, double traffic, UShort subnIdx)
{
Traffic(subnIdx, srcIdx, dstIdx) += traffic;
}
//=======================================================================
/*
* Follow route between a component and a memctrl
* and save traffic rates into the matrix.
*/
void BusIc::MarkPathCompToMemCtrl (UShort cIdx, UShort mcIdx, double traffic, UShort subnIdx)
{
cout << "Warning: memory controllers are not fully supported in connection with buses" << endl;
cout << "Warning: buffers for MCs should be added to BusIC for dynamic latency" << endl;
cout << "Warning: MCs have to be associated with some component index" << endl;
DASSERT(0);
}
//=======================================================================
/*
* Follow route between a memctrl and a component
* and save traffic rates into the matrix.
*/
void BusIc::MarkPathMemCtrlToComp (UShort mcIdx, UShort cIdx, double traffic, UShort subnIdx)
{
cout << "Warning: memory controllers are not fully supported in connection with buses" << endl;
cout << "Warning: buffers for MCs should be added to BusIC for dynamic latency" << endl;
cout << "Warning: MCs have to be associated with some component index" << endl;
DASSERT(0);
}
//=======================================================================
/*
* Follow route from component 'idx' to the interface component
* and save traffic rates into the matrix.
* Assume that the interface component is the last one in the list.
*/
void BusIc::MarkPathCompToIface (UShort idx, double traffic, UShort subnIdx)
{
Traffic(subnIdx, idx, TotalCompCnt()-1) += traffic;
}
//=======================================================================
/*
* Follow route from the interface component to the component 'idx'
* and save traffic rates into the matrix.
* Assume that the interface component is the last one in the list.
*/
void BusIc::MarkPathIfaceToComp (UShort idx, double traffic, UShort subnIdx)
{
Traffic(subnIdx, TotalCompCnt()-1, idx) += traffic;
}
//=======================================================================
/*
* Initialize traffic matrix: resize and set all values to zero.
* Resize the buffer delay matrix accordingly.
*/
void BusIc::InitModel()
{
tm_.resize(SubnCnt()*TotalCompCnt()*TotalCompCnt());
tm_.assign(SubnCnt()*TotalCompCnt()*TotalCompCnt(), 0.0);
bufDelays_.resize(SubnCnt()*TotalCompCnt());
}
//=======================================================================
/*
* Run analytical modeling of the contention delays in input buffers.
*/
int BusIc::EstimateBufferDelays(bool fixNegDelays)
{
// Create an array of bus models, one per subnetwork:
// - if CC is not modeled, i.e. the number of subnetworks is 1,
// use service time as (Req + Reply)/2
// - if CC is modeled, i.e. the number of subnetworks is 3,
// use Req service time for Req, Ack and Reply time for Data
vector<BusModel*> bms;
if (!config.SimulateCC()) {
bms.push_back(new BusModel(TotalCompCnt(), (cmpConfig.MemReplySize()+1.0)*AccessTime()/2.0));
}
else {
bms.push_back(new BusModel(TotalCompCnt(), AccessTime())); // REQ
bms.push_back(new BusModel(TotalCompCnt(), AccessTime())); // ACK
bms.push_back(new BusModel(TotalCompCnt(), cmpConfig.MemReplySize()*AccessTime())); // DATA
}
bool error = false;
for (int s = 0; s < SubnCnt(); ++s) {
if (bms[s]->CalcBufferDelays( &Traffic(s,0,0), &BufDelay(s,0), fixNegDelays )) {
error = true; break;
}
}
for (vector<BusModel*>::const_iterator it = bms.begin(); it != bms.end(); ++it)
delete *it;
return error ? 1 : 0;
}
//=======================================================================
} // namespace cmp
} // namespace cmpex
| [
"[email protected]"
] | |
c3be96757b902fffb90cc8a0d9b326d8a8e54ba0 | 216e6d787fd144f965dc59716f36293335be8882 | /real/real/real.cpp | e66b9ae5f850a67a96cbb3c14ef3fbdb6488f7e2 | [] | no_license | youngc00/realSinsamo | 43310a3692569c3c53c48c36eb49192114fb188f | bd648f86b9c52256e65b3834819b623e914f7279 | refs/heads/master | 2021-01-10T01:09:08.118964 | 2016-03-24T11:49:59 | 2016-03-24T11:49:59 | 54,635,189 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 4,539 | cpp | // real.cpp : 응용 프로그램에 대한 진입점을 정의합니다.
//
#include "stdafx.h"
#include "real.h"
#define ASDF dfdssdf
#define MAX_LOADSTRING 100
#define pi sdf
// 전역 변수:
HINSTANCE hInst; // 현재 인스턴스입니다.
TCHAR szTitle[MAX_LOADSTRING]; // 제목 표시줄 텍스트입니다.
TCHAR szWindowClass[MAX_LOADSTRING]; // 기본 창 클래스 이름입니다.
// 이 코드 모듈에 들어 있는 함수의 정방향 선언입니다.
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPTSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: 여기에 코드를 입력합니다.
MSG msg;
HACCEL hAccelTable;
// 전역 문자열을 초기화합니다.
LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDC_REAL, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// 응용 프로그램 초기화를 수행합니다.
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_REAL));
// 기본 메시지 루프입니다.
while (GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
//
// 함수: MyRegisterClass()
//
// 목적: 창 클래스를 등록합니다.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_REAL));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCE(IDC_REAL);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassEx(&wcex);
}
//
// 함수: InitInstance(HINSTANCE, int)
//
// 목적: 인스턴스 핸들을 저장하고 주 창을 만듭니다.
//
// 설명:
//
// 이 함수를 통해 인스턴스 핸들을 전역 변수에 저장하고
// 주 프로그램 창을 만든 다음 표시합니다.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
hInst = hInstance; // 인스턴스 핸들을 전역 변수에 저장합니다.
hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// 함수: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// 목적: 주 창의 메시지를 처리합니다.
//
// WM_COMMAND - 응용 프로그램 메뉴를 처리합니다.
// WM_PAINT - 주 창을 그립니다.
// WM_DESTROY - 종료 메시지를 게시하고 반환합니다.
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
switch (message)
{
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// 메뉴 선택을 구문 분석합니다.
switch (wmId)
{
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
break;
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
// TODO: 여기에 그리기 코드를 추가합니다.
EndPaint(hWnd, &ps);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// 정보 대화 상자의 메시지 처리기입니다.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
| [
"[email protected]"
] | |
66dd206a2fac3589a0db62457ef8ed1e01ad5527 | 6e0be4fdfd8f074ec752c2f274eb47bfc64f226d | /platformio/test/freertos_logging/src/freertos_logging.ino | 13db84ca9fbce278ee2315d4cf43209fb94ff1ae | [] | no_license | LynnL4/rmap | 28581bfe5df16acd076368b8a5a59e2202214a74 | 19c6a515fe7ab4e8d3edd23d2cc03581415115b5 | refs/heads/master | 2022-07-08T22:58:18.359930 | 2020-05-16T09:28:53 | 2020-05-16T09:28:53 | 265,510,561 | 1 | 0 | null | 2020-05-20T09:09:09 | 2020-05-20T09:09:08 | null | UTF-8 | C++ | false | false | 1,823 | ino | /****************************************************************************
*
* Copyright (c) 2020, Paolo Patruno ([email protected])
*
***************************************************************************/
#ifdef ARDUINO_ARCH_AVR
#include <ArduinoSTL.h>
#include <Arduino_FreeRTOS.h>
#else
#ifdef ARDUINO_ARCH_STM32
#include "STM32FreeRTOS.h"
#else
#include "FreeRTOS.h"
#endif
#endif
#include "task.h"
#include "thread.hpp"
#include "ticks.hpp"
#include <frtosLog.h>
void printTimestamp(Print* _logOutput) {
char c[12];
sprintf(c, "%10lu ", millis());
_logOutput->print(c);
}
void printNewline(Print* _logOutput) {
_logOutput->print('\n');
}
using namespace cpp_freertos;
class sampleThread : public Thread {
public:
sampleThread(int i, int delayInSeconds)
: Thread("Thread One", 200, 1),
Id (i),
DelayInSeconds(delayInSeconds)
{
Start();
};
protected:
virtual void Run() {
frtosLog.notice("Starting Thread %d", Id);
while (true) {
Delay(Ticks::SecondsToTicks(DelayInSeconds));
frtosLog.notice("message from thread %d", Id);
}
};
private:
int Id;
int DelayInSeconds;
};
void setup (void)
{
MutexStandard loggingmutex;
// start up the serial interface
Serial.begin(115200);
frtosLog.begin(LOG_LEVEL_VERBOSE, &Serial,loggingmutex);
frtosLog.setPrefix(printTimestamp); // Uncomment to get timestamps as prefix
frtosLog.setSuffix(printNewline); // Uncomment to get newline as suffix
//Start logging
frtosLog.notice(F("Testing FreeRTOS C++ wrappers with logger")); // Info string with Newline
static sampleThread p1(1, 2);
static sampleThread p2(2, 5);
Thread::StartScheduler();
}
void loop()
{
// Empty. Things are done in Tasks.
}
| [
"[email protected]"
] | |
f6745296e1d161df846c419c05971f62eb19e395 | 2aea549a86cb48d545f1d1273dc770e9ee5cc845 | /Engine/Code/Engine/RHI/ShaderProgram.cpp | 74780a1f1e16bc10b47d6dfb2f4a79a7ccbc1ef0 | [] | no_license | soxymo/EphanovBox | 00dbda3a38f46138fc4ec6471854acf883fb144c | 473c7f01408959f7b9b2981412a019389a790050 | refs/heads/master | 2021-01-22T04:54:20.395695 | 2017-03-01T01:52:49 | 2017-03-01T01:52:49 | 81,597,897 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,114 | cpp | #include "Engine/RHI/ShaderProgram.hpp"
#include "Engine/RHI/RHIDevice.hpp"
#include "Engine/Math/Vertex3.hpp"
#include "Engine/Core/ErrorWarningAssert.hpp"
#include <d3dcompiler.h>
#pragma comment( lib, "d3dcompiler.lib" )
#define DX_SAFE_RELEASE(dx_resource) if ((dx_resource) != nullptr) { dx_resource->Release(); dx_resource = nullptr; }
#define D3D_COMPILE_STANDARD_FILE_INCLUDE ((ID3DInclude*)(UINT_PTR)1)
//I love PI
ShaderProgram::ShaderProgram(RHIDevice *owner, char const* filename) {
create_shaders(owner, filename);
create_input_layout(owner);
//owner->dx_device->VSSetShader(dx_vertex_shader, nullptr, 0U); //TODO gotta set the shader somewhere, why not here?
//gD3DContext->PSSetShader(gD3DFragmentShader, nullptr, 0U);
//DX_SAFE_RELEASE(vs_byte_code);
//DX_SAFE_RELEASE(fs_byte_code);
}
ShaderProgram::~ShaderProgram() {
}
void ShaderProgram::set_shader(ShaderProgram* program) {
//gD3DContext->VSSetShader(gD3DVertexShader, nullptr, 0U);
//gD3DContext->PSSetShader(gD3DFragmentShader, nullptr, 0U);
dx_vertex_shader = program->dx_vertex_shader;
dx_fragment_shader = program->dx_fragment_shader;
dx_input_layout = program->dx_input_layout;
}
void ShaderProgram::create_input_layout(RHIDevice* device) {
D3D11_INPUT_ELEMENT_DESC DESC[3];
memset(DESC, 0, sizeof(DESC));
DESC[0].SemanticName = "POSITION";
DESC[0].SemanticIndex = 0;
DESC[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;//DXGI_FORMAT_R32G32B32_FLOAT;
DESC[0].InputSlot = 0U;
DESC[0].AlignedByteOffset = offsetof(Vertex3, m_pos);
DESC[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
DESC[0].InstanceDataStepRate = 0U;
DESC[1].SemanticName = "COLOR";
DESC[1].SemanticIndex = 0;
DESC[1].Format = DXGI_FORMAT_R8G8B8A8_UINT;//DXGI_FORMAT_R32G32B32_FLOAT;
DESC[1].InputSlot = 0U;
DESC[1].AlignedByteOffset = offsetof(Vertex3, m_tint);
DESC[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
DESC[1].InstanceDataStepRate = 0U;
DESC[2].SemanticName = "TEXCOORDS";
DESC[2].SemanticIndex = 0;
DESC[2].Format = DXGI_FORMAT_R32G32_FLOAT;//DXGI_FORMAT_R32G32B32_FLOAT;
DESC[2].InputSlot = 0U;
DESC[2].AlignedByteOffset = offsetof(Vertex3, m_texCoords);
DESC[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
DESC[2].InstanceDataStepRate = 0U;
const void* bytePointer = vs_byte_code->GetBufferPointer();
SIZE_T byteLength = vs_byte_code->GetBufferSize();
UINT arraysize = ARRAYSIZE(DESC);
HRESULT hr = device->dx_device->CreateInputLayout(DESC, arraysize,
bytePointer,
byteLength,
&dx_input_layout);
if (FAILED(hr)) {
DebuggerPrintf("Unable to Create Input Layout");
}
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// Helper - File IO Example - Read an entire file to a buffer
// NOTE: Be sure for free it when you're done.
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
void* FileReadToBuffer(char const *filename, size_t *out_size) { //TODO use my fileUtilities instead
*out_size = 0U;
// I'm going to use Windows file functions for no particular reason
// outside of familiarity. Feel free to use whatever.
DWORD file_access = GENERIC_READ;
DWORD share = FILE_SHARE_READ;
DWORD options = OPEN_EXISTING;
HANDLE file_handle = CreateFileA(filename, file_access, share, NULL, options, FILE_ATTRIBUTE_NORMAL, NULL);
if (file_handle == INVALID_HANDLE_VALUE) {
DebuggerPrintf("File [%s] could not be opened.", filename);
return nullptr;
}
// Get File Size
DWORD high_word;
DWORD lo_word = ::GetFileSize(file_handle, &high_word);
// 64-bit way - use a 64-bit type, but we will never have a 4GB+ file, so ignore it and just using lo-word to prevent warnings
// size_t size = ((size_t)high_word << 32) | (size_t)lo_word;
size_t size = (size_t)lo_word;
// Make a buffer that big
void *buffer = malloc(size + 1U); // I allocae one extra for a null terminator - but do not include it in the size
// just in the cases I load strings it null terminates.
if (nullptr != buffer) {
DWORD read = 0U;
ReadFile(file_handle, buffer, (DWORD)size, &read, nullptr);
*out_size = read;
((char*)buffer)[size] = NULL;
}
CloseHandle((HANDLE)file_handle);
return buffer;
}
static ID3DBlob* CompileHLSLToShaderBlob(char const *opt_filename, // optional: used for error messages
void const *source_code, // buffer containing source code.
size_t const source_code_size, // size of the above buffer.
char const *entrypoint, // Name of the Function we treat as the entry point for this stage
char const* target) // What stage we're compiling for (Vertex/Fragment/Hull/Compute... etc...)
{
/* DEFINE MACROS - CONTROLS SHADER
// You can optionally define macros to control compilation (for instance, DEBUG builds, disabling lighting, etc...)
D3D_SHADER_MACRO defines[1];
defines[0].Name = "TEST_MACRO";
defines[0].Definition = nullptr;
*/
DWORD compile_flags = 0U;
#if defined(DEBUG_SHADERS)
compile_flags |= D3DCOMPILE_DEBUG;
compile_flags |= D3DCOMPILE_SKIP_OPTIMIZATION;
compile_flags |= D3DCOMPILE_WARNINGS_ARE_ERRORS; // cause, FIX YOUR WARNINGS
else
// compile_flags |= D3DCOMPILE_SKIP_VALIDATION; // Only do this if you know for a fact this shader works with this device (so second run through of a game)
compile_flags |= D3DCOMPILE_OPTIMIZATION_LEVEL3; // Yay, fastness (default is level 1)
#endif
ID3DBlob *code = nullptr;
ID3DBlob *errors = nullptr;
HRESULT hr = D3DCompile(source_code,
source_code_size, // plain text source code
opt_filename, // optional, used for error messages (If you HLSL has includes - it will not use the includes names, it will use this name)
nullptr, // pre-compiler defines - used more for compiling multiple versions of a single shader (different quality specs, or shaders that are mostly the same outside some constants)
D3D_COMPILE_STANDARD_FILE_INCLUDE, // include rules - this allows #includes in the shader to work relative to the src_file path or my current working directly
entrypoint, // Entry Point for this shader
target, // Compile Target (MSDN - "Specifying Compiler Targets")
compile_flags, // Flags that control compilation
0, // Effect Flags (we will not be doing Effect Files)
&code, // [OUT] ID3DBlob (buffer) that will store the byte code.
&errors); // [OUT] ID3DBlob (buffer) that will store error information
if (FAILED(hr) || (errors != nullptr)) {
if (errors != nullptr) {
char *error_string = (char*)errors->GetBufferPointer();
DebuggerPrintf("Failed to compile [%s]. Compiler gave the following output;\n%s",
opt_filename,
error_string);
DX_SAFE_RELEASE(errors);
}
}
// will be nullptr if it failed to compile
return code;
}
void ShaderProgram::create_shaders(RHIDevice* device, const char* filename) {
size_t size = 0U;
void *source_code = FileReadToBuffer(filename, &size);
if (source_code == nullptr) {
DebuggerPrintf("--Shader file could not be read. The filename may be wrong.--");
return;
}
// Compile hlsl to byte code (generic compiled version)
vs_byte_code = CompileHLSLToShaderBlob(filename, source_code, size, "VertexFunction", "vs_5_0");
fs_byte_code = CompileHLSLToShaderBlob(filename, source_code, size, "FragmentFunction", "ps_5_0");
HRESULT hr;
// Compile the byte code to the final shader (driver/hardware specific program)
hr = device->dx_device->CreateVertexShader(vs_byte_code->GetBufferPointer(),
vs_byte_code->GetBufferSize(),
nullptr,
&dx_vertex_shader);
if (FAILED(hr)) {
DebuggerPrintf("It broke yo");
}
hr = device->dx_device->CreatePixelShader(fs_byte_code->GetBufferPointer(),
fs_byte_code->GetBufferSize(),
nullptr,
&dx_fragment_shader);
if (FAILED(hr)) {
DebuggerPrintf("It broke yo");
}
}
| [
"[email protected]"
] | |
e2c19ea65de3e825bb39e88611df47433003193b | 2ba48648eefadee113a7c2f5d608cab5209c3a8b | /code/Configurator/Configurator.cpp | 435ca6d7e9393bf3ef3b35465c1fc41bbcb0c586 | [] | no_license | wangdong412/Consen-SIS | 879762175575d0a62f26ec1effeb46c3fd62e3e8 | bca3fac35c961c3558a3438bca55e6d20825da3a | refs/heads/master | 2020-07-11T05:17:18.814104 | 2019-08-27T09:41:41 | 2019-08-27T09:41:41 | 204,450,874 | 1 | 5 | null | null | null | null | GB18030 | C++ | false | false | 63,133 | cpp |
// Configurator.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "afxwinappex.h"
#include "afxdialogex.h"
#include "Configurator.h"
#include "MainFrm.h"
#include "ConfiguratorDoc.h"
#include "ConfiguratorView.h"
// Added by wangdong begin
#include "Splash.h" // Splash screen
#include "resource.h" // LoadString
#include "afxwin.h"
#include "VersionInfo.h" // Versions in About Dialog
#include "SelAppTypeDlg.h" // Select Application Type
#include "CommSettings.h" // Communication Settings
#include "CalSheet.h"
#include "PasswordDlg.h"
//#include "HistoryRecordData.h"
//#include "HistoryRecordDatas.h"
//#include "HistoryFileData.h"
// Added by wangdong end
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
extern std::auto_ptr<CCommSettings> CommSettings;
extern std::auto_ptr<CCalSheet> CalSheet;
// CConfiguratorApp
BEGIN_MESSAGE_MAP(CConfiguratorApp, CWinAppEx)
ON_COMMAND(ID_APP_ABOUT, &CConfiguratorApp::OnAppAbout)
// Standard file based document commands
//ON_COMMAND(ID_FILE_NEW, &CWinAppEx::OnFileNew)
//ON_COMMAND(ID_FILE_OPEN, &CWinAppEx::OnFileOpen)
// Standard print setup command
ON_COMMAND(ID_FILE_PRINT_SETUP, &CWinAppEx::OnFilePrintSetup)
ON_COMMAND(ID_FILE_NEW, &CConfiguratorApp::OnFileNew)
ON_COMMAND_EX_RANGE( ID_FILE_MRU_FILE1, ID_FILE_MRU_FILE16, &CConfiguratorApp::OnOpenRecentFile)
ON_COMMAND(IDM_DEVICE_SELAPPTYPE, &CConfiguratorApp::OnDeviceSelapptype)
ON_COMMAND(IDM_VIEW_LANGUAGE_CHS, &CConfiguratorApp::OnViewLanguageChs)
ON_COMMAND(IDM_VIEW_LANGUAGE_ENG, &CConfiguratorApp::OnViewLanguageEng)
ON_COMMAND(IDM_DEVICE_DSC100, &CConfiguratorApp::OnDeviceDsc100)
ON_COMMAND(IDM_DEVICE_TS350, &CConfiguratorApp::OnDeviceTs350)
ON_COMMAND(IDM_DEVICE_DSC110, &CConfiguratorApp::OnDeviceDsc110)
ON_COMMAND(IDM_LOGLEVEL_ALL, &CConfiguratorApp::OnLoglevelAll)
ON_COMMAND(IDM_LOGLEVEL_ERR, &CConfiguratorApp::OnLoglevelErr)
ON_COMMAND(IDM_LOGLEVEL_OPR, &CConfiguratorApp::OnLoglevelOpr)
ON_UPDATE_COMMAND_UI(IDM_LOGLEVEL_ALL, &CConfiguratorApp::OnUpdateLoglevelAll)
ON_UPDATE_COMMAND_UI(IDM_LOGLEVEL_ERR, &CConfiguratorApp::OnUpdateLoglevelErr)
ON_UPDATE_COMMAND_UI(IDM_LOGLEVEL_OPR, &CConfiguratorApp::OnUpdateLoglevelOpr)
END_MESSAGE_MAP()
// CConfiguratorApp construction
CConfiguratorApp::CConfiguratorApp()
:m_hLangDLL( NULL ),
m_hEngLangDLL( NULL ),
m_uLanguageType( CHS ),
m_uProductType( DSC100 ),
m_nProductNumber( 100 ),
m_nCurrentCode( 0 ),
m_fXMLVersion( 0.0 ),
m_nAppType( 1 ),
m_uLogLevel( LOG_OPR ),
m_bAccessRedraw( false ),
m_bResetViewFlag( false ),
m_bAppMismatch( false ),
m_pVersionCTL( new CVersionCtl())
{
m_bHiColorIcons = TRUE;
// support Restart Manager
m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_ALL_ASPECTS;
#ifdef _MANAGED
// If the application is built using Common Language Runtime support (/clr):
// 1) This additional setting is needed for Restart Manager support to work properly.
// 2) In your project, you must add a reference to System.Windows.Forms in order to build.
System::Windows::Forms::Application::SetUnhandledExceptionMode(System::Windows::Forms::UnhandledExceptionMode::ThrowException);
#endif
// TODO: replace application ID string below with unique ID string; recommended
// format for string is CompanyName.ProductName.SubProduct.VersionInformation
SetAppID(_T("Configurator.AppID.NoVersion"));
// TODO: add construction code here,
// Place all significant initialization in InitInstance
LeftViewVector.clear();
RightViewVector.clear();
}
// The one and only CConfiguratorApp object
CConfiguratorApp theApp;
// CConfiguratorApp initialization
BOOL CConfiguratorApp::InitInstance()
{
// CG: The following block was added by the Splash Screen component.
{
CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);
CSplashWnd::EnableSplashScreen(cmdInfo.m_bShowSplash);
}
// InitCommonControlsEx() is required on Windows XP if an application
// manifest specifies use of ComCtl32.dll version 6 or later to enable
// visual styles. Otherwise, any window creation will fail.
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// Set this to include all the common control classes you want to use
// in your application.
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinAppEx::InitInstance();
// Initialize OLE libraries
if (!AfxOleInit())
{
AfxMessageBox(IDP_OLE_INIT_FAILED);
return FALSE;
}
AfxEnableControlContainer();
EnableTaskbarInteraction(FALSE);
// AfxInitRichEdit2() is required to use RichEdit control
// AfxInitRichEdit2();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need
// Change the registry key under which our settings are stored
// TODO: You should modify this string to be something appropriate
// such as the name of your company or organization
SetRegistryKey(_T("Tri-Sen"));
LoadStdProfileSettings(4); // Load standard INI file options (including MRU)
InitContextMenuManager();
InitKeyboardManager();
InitTooltipManager();
CMFCToolTipInfo ttParams;
ttParams.m_bVislManagerTheme = TRUE;
theApp.GetTooltipManager()->SetTooltipParams(AFX_TOOLTIP_TYPE_ALL,
RUNTIME_CLASS(CMFCToolTipCtrl), &ttParams);
// Added by wangdong: 此项保持菜单栏的可视属性(0x0000 0001即可视),如果不删除,则切换语言时,菜单栏不能正常切换
HKEY hAppKey = GetAppRegistryKey(); // HKEY_CURRENT_USER\"Software"\RegistryKey\ProfileName
if( hAppKey != NULL ) // Tri-Sen Configurator
{
long lResult = -1;
HKEY key;
// Menu
lResult = RegOpenKey( hAppKey, _T("Workspace\\BasePane-593980"), &key);
if( lResult == ERROR_SUCCESS )
{
lResult = RegDeleteKey( hAppKey, _T("Workspace\\BasePane-593980"));
ASSERT( lResult == ERROR_SUCCESS );
}
// Standard ToolBar
lResult = RegOpenKey( hAppKey, _T("Workspace\\MFCToolBar-59392"), &key);
if( lResult == ERROR_SUCCESS )
{
lResult = RegDeleteKey( hAppKey, _T("Workspace\\MFCToolBar-59392"));
ASSERT( lResult == ERROR_SUCCESS );
}
// View ToolBar
lResult = RegOpenKey( hAppKey, _T("Workspace\\MFCToolBar-1101"), &key);
if( lResult == ERROR_SUCCESS )
{
lResult = RegDeleteKey( hAppKey, _T("Workspace\\MFCToolBar-1101"));
ASSERT( lResult == ERROR_SUCCESS );
}
RegCloseKey(hAppKey);
}
/// Version control
/// DSC100: xml 1.0 code 980,981; xml 1.1 code 982
// xml 1.0: code, 980,981.982
vermaps *pvers = new vermaps();
float fver = 1.0f;
CVersion *pver = new CVersion( fver );
pver->Add( 980 );
pver->Add( 981 );
pver->Add( 982 );
pvers->insert( make_pair( fver, pver ));
// xml 1.1: code, 1000
fver = 1.1f;
pver = new CVersion( fver );
pver->Add( 1000 );
pvers->insert( make_pair( fver, pver ));
m_pVersionCTL->Add( DSC100, pvers );
// TS350: xml 1.0 code 1;
pvers = new vermaps();
fver = 1.0f;
pver = new CVersion( fver );
pver->Add( 10 );
pvers->insert( make_pair( fver, pver ));
m_pVersionCTL->Add( TS350, pvers );
// DSC110: xml 1.0 code 1;
pvers = new vermaps();
fver = 1.0f;
pver = new CVersion( fver );
pver->Add( 10 );
pvers->insert( make_pair( fver, pver ));
m_pVersionCTL->Add( DSC110, pvers );
// Get product type from the registry, default DSC100
m_uProductType = GetProfileInt( L"SETTINGS", L"PRODUCT_TYPE", DSC100 );
SetProductNumberByType();
CString strProductRegPath( GetPathAccordingToProduct( m_uProductType ));
// Update current code and xml version
m_nCurrentCode = GetProfileInt( strProductRegPath, L"FIRM_CODE", 0 );
if( 0 == m_nCurrentCode ) //not exist
{
m_nCurrentCode = m_pVersionCTL->GetNewestCode( m_uProductType );
ASSERT( m_nCurrentCode != -1 );
}
m_fXMLVersion = m_pVersionCTL->GetXMLVersionFromCode( m_uProductType, m_nCurrentCode );
ASSERT( fabs(m_fXMLVersion) > EPSILON_FLT );
// Get Default Resource: English
m_hEngLangDLL = AfxGetResourceHandle();
/// Load language dll according to the product's language type
// Get the product's language type by producttype
m_uLanguageType = GetLanguageByProduct( m_uProductType );
if( ENG != m_uLanguageType ) // Default: English(not resource file)
{
switch( m_uLanguageType )
{
case CHS: // Chinese
m_hLangDLL = AfxLoadLibrary( _T("Configurator_Chs.dll"));
ASSERT( m_hLangDLL );
if( m_hLangDLL )
{
AfxSetResourceHandle( m_hLangDLL );
}
else
{
LogInfo( _T("Language_Chs.dll has not been found!"));
return FALSE;
}
break;
default: // Default English
break;
}//switch
}//if( ENG != m_uLanguageType )
/// Grid Size
// SettingGrid Size
global::SettingGridColWidths[0] = 5000;
global::SettingGridColWidths[1] = 1200;
global::SettingGridColWidths[2] = 1200;
global::SettingGridColWidths[3] = 1200;
global::SettingGridColWidths[4] = 1200;
global::SettingGridColWidths[5] = 2400;
global::SettingGridColWidths[6] = 2400;
CString strGrid = strProductRegPath + L"\\Grid Window";
for( int i = 0; i < global::SETTING_GRID_COLUMNS; i++ )
{
CString strCol;
strCol.Format( L"ColWidth %d", i );
global::SettingGridColWidths[i] = GetProfileInt( strGrid, strCol, global::SettingGridColWidths[i] );
}
// Alias Grid Size
global::TagsGridColWidths[0] = 5000;
global::TagsGridColWidths[1] = 1700;
global::TagsGridColWidths[2] = 1200;
global::TagsGridColWidths[3] = 1200;
global::TagsGridColWidths[4] = 1400;
global::TagsGridColWidths[4] = 1200;
strGrid = strProductRegPath + L"\\Alias Window";
for( int i = 0; i < global::TAGS_GRID_COLUMNS; i++ )
{
CString strCol;
strCol.Format( L"ColWidth %d", i );
global::TagsGridColWidths[i] = GetProfileInt( strGrid, strCol, global::TagsGridColWidths[i] );
}
// History Grid Size
global::HisGridColWidths[0] = 5000;
global::HisGridColWidths[1] = 1700;
global::HisGridColWidths[2] = 1200;
global::HisGridColWidths[3] = 1200;
strGrid = strProductRegPath + L"\\History Window";
for( int i = 0; i < global::HISTORY_GRID_COLUMNS; i++ )
{
CString strCol;
strCol.Format( L"ColWidth %d", i );
global::HisGridColWidths[i] = GetProfileInt( strGrid, strCol, global::HisGridColWidths[i] );
}
// Font
CString strFont = strProductRegPath + L"\\Font";
global::FontName = GetProfileStringW( strFont, L"Font Name", global::FontName );
global::FontSize = (float)GetProfileIntW( strFont, L"Font Size", static_cast<int>(global::FontSize));
/// Log file
// Get log level stored in the registry
m_uLogLevel = GetProfileInt( GetPathAccordingToProduct( m_uProductType ), L"LOG_LEVEL", LOG_OPR );
// Rename existing log files
global::RenameLogFiles();
// Open new log file, and log User name and Computer name
CString strLogFileName;
strLogFileName.Format( L"%s\\%s%s", GetFilePath(), global::LOG_FILE_NAME, global::LOG_FILE_EXT );
m_strLogFile = strLogFileName;
m_osLogFile.open( m_strLogFile );
if( m_osLogFile )
{
LogInfo( L"Opening log file" );
CString str;
wchar_t w[MAX_PATH];
memset( w, 0, sizeof(w));
DWORD dwSize = MAX_PATH;
// User Name
if( ::GetUserNameW( w, &dwSize )) // in characters, include null
{
str.Format( L"User: %s", w );
LogInfo( str );
}
// Computer Name
str.Empty();
memset( w, 0, sizeof(w));
dwSize = MAX_PATH;
if( ::GetComputerNameW( w, &dwSize )) // in characters, not include null
{
str.Format( L"Machine: %s", w );
LogInfo( str );
}
}
// Register the application's document templates. Document templates
// serve as the connection between documents, frame windows and views
CSingleDocTemplate* pDocTemplate;
pDocTemplate = new CSingleDocTemplate(
IDR_MAINFRAME,
RUNTIME_CLASS(CConfiguratorDoc),
RUNTIME_CLASS(CMainFrame), // main SDI frame window
RUNTIME_CLASS(CConfiguratorView));
if(!pDocTemplate)
{
return FALSE;
}
AddDocTemplate(pDocTemplate);
// Relate File to Configurator Program
RegisterFileandProgram();
// Parse command line for standard shell commands, DDE, file open
CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);
// Dispatch commands specified on the command line. Will return FALSE if
// app was launched with /RegServer, /Register, /Unregserver or /Unregister.
if (!ProcessShellCommand(cmdInfo))
{
return FALSE;
}
// The one and only window has been initialized, so show and update it
m_pMainWnd->ShowWindow(SW_SHOW);
m_pMainWnd->UpdateWindow();
// call DragAcceptFiles only if there's a suffix
// In an SDI app, this should occur after ProcessShellCommand
return TRUE;
}
int CConfiguratorApp::ExitInstance()
{
//TODO: handle additional resources you may have added
AfxOleTerm(FALSE);
/// Write Registry
CString strProductRegPath( GetPathAccordingToProduct( m_uProductType ));
// Product Type
WriteProfileInt( L"SETTINGS", L"PRODUCT_TYPE", m_uProductType );
// Log Level
WriteProfileInt( strProductRegPath, L"LOG_LEVEL", m_uLogLevel );
// Firm code
WriteProfileInt( strProductRegPath, L"FIRM_CODE", m_nCurrentCode );
// SettingGrid Size
CString strGrid = strProductRegPath + L"\\Grid Window";
for( int i = 0; i < global::SETTING_GRID_COLUMNS; i++ )
{
CString strCol;
strCol.Format( L"ColWidth %d", i );
WriteProfileInt( strGrid, strCol, global::SettingGridColWidths[i] );
}
// Alias Grid Size
strGrid = strProductRegPath + L"\\Alias Window";
for( int i = 0; i < global::TAGS_GRID_COLUMNS; i++ )
{
CString strCol;
strCol.Format( L"ColWidth %d", i );
WriteProfileInt( strGrid, strCol, global::TagsGridColWidths[i] );
}
// History Grid Size
strGrid = strProductRegPath + L"\\History Window";
for( int i = 0; i < global::HISTORY_GRID_COLUMNS; i++ )
{
CString strCol;
strCol.Format( L"ColWidth %d", i );
WriteProfileInt( strGrid, strCol, global::HisGridColWidths[i] );
}
// Font
CString strFont = strProductRegPath + L"\\Font";
WriteProfileString( strFont, L"Font Name", global::FontName );
WriteProfileInt( strFont, L"Font Size", static_cast<int>(global::FontSize));
/// Log info and close log file
if( m_osLogFile )
{
LogInfo( L"Closing log file" );
}
m_osLogFile.close();
/// Free DLL library
if( m_hLangDLL )
{
AfxFreeLibrary( m_hLangDLL );
}
if( m_hEngLangDLL )
{
AfxFreeLibrary( m_hEngLangDLL );
}
// Clear View Vector
LeftViewVector.clear();
RightViewVector.clear();
// Global font
if( global::g_Font.m_hObject )
{
global::g_Font.DeleteObject();
}
SAFE_DELETE( m_pVersionCTL );
return CWinAppEx::ExitInstance();
}
// =======================================================================
// Function name : LogInfo
// Description :
// Return type : void
// Parameters :
// Author : WangDong 2011.04.11 13:00:00
// =======================================================================
void CConfiguratorApp::LogInfo( CString strInfo )
{
if( !m_osLogFile )
{
return;
}
// Get Current time: Year-Month-Day Hour:Minite:Second.milliseconds
SYSTEMTIME tm;
::GetLocalTime( &tm );
COleDateTime time( tm );
CString strLogTime = time.Format( L"%Y-%m-%d %H:%M:%S" );
CString strMillSec;
strMillSec.Format( L".%03d", tm.wMilliseconds );
strLogTime += strMillSec;
CString strLog( strLogTime + L" | " + strInfo + L"\r\n" );
m_osLogFile.imbue( std::locale("chs"));
m_osLogFile.write( strLog, strLog.GetLength());
m_osLogFile.flush();
}
// =======================================================================
// Function name : SetProductInfo
// Description : Product Number and Type, Application Type
// No need to check, when double-click a file to start the app,
// we need to update these two parameters with file's information
// Return type : void
// Parameters :
// Author : WangDong 2011.01.19 10:30:00
// =======================================================================
void CConfiguratorApp::SetProductInfo( int nProductNumber, int nAppType )
{
if((nProductNumber != m_nProductNumber) || (nAppType != m_nAppType))
{
m_bResetViewFlag = true;
if( nAppType != m_nAppType )
{
SetAppType( nAppType );
}
if( nProductNumber != m_nProductNumber )
{
m_nProductNumber = nProductNumber; // Product ID
SetProductTypeByNumber(); // Set Product type according to Number
}
}
}
// ------------------------------------------------------------------------
// Function name : SetProductNumberByType / SetProductTypeByNumber
// Description : Make product number and type synchronous
// Return type : void
// Parameters :
// Author : WangDong 2011.01.19 10:30:00
// -------------------------------------------------------------------------
void CConfiguratorApp::SetProductNumberByType()
{
// Set m_nProductNumber according to m_uProductType
switch( m_uProductType )
{
case DSC100:
m_nProductNumber = 100;
break;
case TS350:
m_nProductNumber = 350;
break;
case DSC110:
m_nProductNumber = 110;
break;
default:
m_nProductNumber = 100;
}
}
//--------------------------------------------------------------------------
// Set m_uProductType according to m_nProductNumber
void CConfiguratorApp::SetProductTypeByNumber()
{
switch( m_nProductNumber )
{
case 100:
m_uProductType = DSC100;
break;
case 350:
m_uProductType = TS350;
break;
case 110:
m_uProductType = DSC110;
break;
default:
m_uProductType = DSC100;
}
}
// =======================================================================
// Function name : GetLanguageByProduct
// Description : Get language type according to the current product type
// Return type : void
// Parameters :
// Author : WangDong 2011.01.19 10:30:00
// =======================================================================
CString CConfiguratorApp::GetPathAccordingToProduct( UINT uProductType )
{
CString strPath( L"SETTINGS\\" );
switch( uProductType )
{
case DSC100:
strPath += L"DSC100";
break;
case TS350:
strPath += L"TS350";
break;
case DSC110:
strPath += L"DSC110";
break;
default:
strPath += L"DSC100";
}
return strPath;
}
// =======================================================================
// Function name : GetLanguageByProduct
// Description : Get language type according to the current product type
// Return type : void
// Parameters :
// Author : WangDong 2011.01.19 10:30:00
// =======================================================================
UINT CConfiguratorApp::GetLanguageByProduct( UINT uProductType )
{
CString strPath( GetPathAccordingToProduct( uProductType ));
return GetProfileInt( strPath, L"LANGUAGE_CFG", ENG );
}
// =======================================================================
// Function name : GetProductName
// Description :
// Return type : product name, such as "DSC100"
// Parameters :
// Author : WangDong 2011.01.19 10:30:00
// =======================================================================
CString CConfiguratorApp::GetProductName()
{
CString strProductName;
switch( m_uProductType )
{
case DSC100:
strProductName = L"DSC100";
break;
case TS350:
strProductName = L"TS350";
break;
case DSC110:
strProductName = L"DSC110";
break;
default:
strProductName = L"DSC100";
}
return strProductName;
}
// =======================================================================
// Function name : GetProductTypeByName
// Description :
// Return type :
// Parameters :
// Author : WangDong 2011.01.19 10:30:00
// =======================================================================
UINT CConfiguratorApp::GetProductTypeByName( CString strName )
{
UINT uProductType = DSC100;
if( strName.CompareNoCase( L"DSC100" ) == 0 )
{
uProductType = DSC100;
}
else if( strName.CompareNoCase( L"TS350" ) == 0 )
{
uProductType = TS350;
}
else if( strName.CompareNoCase( L"DSC110" ) == 0 )
{
uProductType = DSC110;
}
else
{
uProductType = DSC100;
}
return uProductType;
}
// =======================================================================
// Function name : GetXMLFileName
// Description : TS320: AppType 1: Gen320; 2: Mech320
// Others: such as DSC100, T121, TS312...
// Return type : xml file name, such as "DSC100_Eng.xml", "DSC100_Chs.xml"
// Parameters :
// Author : WangDong 2011.04.15 11:30:00
// =======================================================================
CString CConfiguratorApp::GetXMLFileName( bool bForSave )
{
/// Exe file Path
CString strPath( GetFilePath());
/// XML File Name
CString strProductName( GetProductName()); // such as "DSC100"
CString strXMLFileName( strProductName );
if( bForSave ) // not include language info
{
strXMLFileName += L".xml";
return strXMLFileName;
}
else
{
switch( m_uLanguageType )
{
case ENG:
strXMLFileName += L".xml";
break;
case CHS:
strXMLFileName += L"_Chs.xml";
break;
default:
strXMLFileName += L".xml";
}//switch
}
/// Full path xml file name
CString strResult;
strResult.Format( L"%s\\%s\\%.1f\\%s", strPath, strProductName, m_fXMLVersion, strXMLFileName );
return strResult;
}
// =======================================================================
// Function name : GetHelpFilePathName
// Description :
// Return type : product name, such as "DSC100", "TS320"
// Parameters :
// Author : WangDong 2011.01.19 10:30:00
// =======================================================================
CString CConfiguratorApp::GetHelpFilePathName()
{
// Exe file Path
CString strPath( GetFilePath());
// Help Name: such as "DSC100.chm"
CString strProductName( GetProductName()), strHelpName( strProductName ); // such as "DSC100"
switch( m_uLanguageType )
{
case ENG:
strHelpName += L".chm";
break;
case CHS:
strHelpName += L"_Chs.chm";
break;
default:
strHelpName += L".chm";
}//switch
// Help File Path
CString strResult;
strResult.Format( L"%s\\%s\\%.1f\\%s", strPath, strProductName, m_fXMLVersion, strHelpName );
return strResult;
}
// =======================================================================
// Function name : GetDefTraceName
// Description :
// Return type : product name, such as "DSC100", "TS320"
// Parameters :
// Author : WangDong 2011.01.19 10:30:00
// =======================================================================
void CConfiguratorApp::GetDefTraceName( CString& strTraceName1, CString& strTraceName2, CString& strTraceName3 )
{
switch( m_uProductType )
{
case DSC100:
strTraceName1 = L"iAPI1P";
strTraceName2 = L"iSPP";
strTraceName3 = L"iAO1P";
break;
case TS350:
strTraceName1 = L"rVALVEV1";
strTraceName2 = L"rVALVEV2";
strTraceName3 = L"SP5_OUT";
break;
case DSC110:
strTraceName1 = L"iPV01AngP";
strTraceName2 = L"iPV02AngP";
strTraceName3 = L"iSelSP";
break;
default: // DSC100
strTraceName1 = L"iAPI1P";
strTraceName2 = L"iSPP";
strTraceName3 = L"iAO1P";
}
}
// =======================================================================
// Function name : GetProductName
// Description :
// Return type : product name, such as "DSC100", "TS320"
// Parameters :
// Author : WangDong 2011.01.19 10:30:00
// =======================================================================
CString CConfiguratorApp::GetCommMessage( int nModbusType )
{
CString str;
UINT uMsgID = 0;
if( nModbusType != 0 ) // Modbus Tcp
{
uMsgID = IDS_TCP_COMMMSG;
}
else
{
switch( m_uProductType )
{
case DSC100:
uMsgID = IDS_DSC100_SERMSG;
break;
default: // Serial communication message
uMsgID = IDS_SERIAL_COMMMSG;
}
}
str.LoadStringW( uMsgID );
return str;
}
// =======================================================================
// Function name : SetAppType
// Description :
// Return type :
// Parameters :
// Author : WangDong 2011.12.13 15:00:00
// =======================================================================
void CConfiguratorApp::SetAppType( int nAppType )
{
if( m_nAppType != nAppType )
{
/// Reset Compare Information
//1 Default Compare Type: controller
m_uCmpType = CMP_REM;
//2 Reset compare file path name
CMainFrame* pMainFrame = (CMainFrame*)AfxGetMainWnd();
if( pMainFrame )
{
CConfiguratorDoc* pDoc = (CConfiguratorDoc*)pMainFrame->GetActiveDocument();
if( pDoc )
{
pDoc->ResetCmpFilePathName();
// History
pDoc->SetRecordModified( false ); // Reset RecordModified Flag
pDoc->ResetHistory(); // Reset History Ctrls, Datas and Clear history views
}
}
m_bResetViewFlag = true;
m_nAppType = nAppType;
}
}
// CConfiguratorApp message handlers
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
~CAboutDlg();
// Dialog Data
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
DECLARE_MESSAGE_MAP()
public:;
CStatic m_stcCfgName;
CStatic m_stcWarning;
CListBox m_listVersion;
virtual BOOL OnInitDialog();
private:
CFont m_font;
CImage m_imgLogo;
CImage m_imgImage;
public:
afx_msg void OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct);
afx_msg void OnPaint();
};
CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}
CAboutDlg::~CAboutDlg()
{
m_imgLogo.ReleaseGDIPlus();
m_imgImage.ReleaseGDIPlus();
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_CRWARNING, m_stcWarning);
DDX_Control(pDX, IDC_STC_CFGNAME, m_stcCfgName);
DDX_Control(pDX, IDC_LIST_VERSION, m_listVersion);
}
BOOL CAboutDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// TODO: 在此添加额外的初始化
/// Font of "Configurator"
CClientDC dc(this);
LOGFONT lf;
memset( &lf, 0, sizeof(LOGFONT));
lf.lfHeight = ::MulDiv( 18, -dc.GetDeviceCaps( LOGPIXELSY ), 72 );
lf.lfWeight = 700;
::StrCpyNW( lf.lfFaceName, global::FontName, 32 );
if( m_font.CreateFontIndirectW( &lf ))
{
m_stcCfgName.SetFont( &m_font );
}
/// Copy Right Warning
CString strWarning;
if( strWarning.LoadStringW( IDS_COPYRIGHT_WARNING ))
{
m_stcWarning.SetWindowTextW( strWarning );
}
/// Version
std::vector<LPCTSTR> files;
files.push_back( L"Configurator.exe" );
files.push_back( L"vsflex8n.ocx" );
files.push_back( L"TeeChart8.ocx" );
files.push_back( L"hhctrl.ocx" );
files.push_back( L"advapi32.dll" );
files.push_back( L"comctl32.dll" );
files.push_back( L"comdlg32.dll" );
files.push_back( L"gdi32.dll" );
files.push_back( L"kernel32.dll" );
files.push_back( L"mpr.dll" );
files.push_back( L"ole32.dll" );
files.push_back( L"oleaut32.dll" );
files.push_back( L"shell32.dll" );
files.push_back( L"user32.dll" );
files.push_back( L"version.dll" );
files.push_back( L"wsock32.dll" );
CVersionInfo v;
for( size_t i = 0; i < files.size(); i++ )
{
CString strFileName = files[i];
CString strVersion( strFileName );
if( v.GetVersionInfo( strFileName ) == S_OK )
{
strVersion += L" " + v.FileVersion();
}
else
{
strVersion += L" !Error!";
}
if( ::GetModuleHandleW( strFileName ) == NULL )
{
if( theApp.GetLogLevel() >= CConfiguratorApp::LOG_ALL )
{
CString str;
str.Format( L"Dependency %s not loaded. (GetLastError()=%d)", strFileName, ::GetLastError());
theApp.LogInfo( str );
}
}
m_listVersion.AddString( strVersion );
}//for
/* Load Logo
m_imgLogo.LoadFromResource( theApp.m_hInstance, IDB_LOGO );
m_imgImage.LoadFromResource( theApp.m_hInstance, IDB_IMAGE );*/
return TRUE; // return TRUE unless you set the focus to a control
// 异常: OCX 属性页应返回 FALSE
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
ON_WM_PAINT()
END_MESSAGE_MAP()
void CAboutDlg::OnPaint()
{
CPaintDC dc(this); // device context for painting
// TODO: 在此处添加消息处理程序代码
// 不为绘图消息调用 CDialogEx::OnPaint()
// Check if bitmaps are currently loaded.
if( m_imgLogo.IsNull() ||
m_imgImage.IsNull())
{
return;
}
if( CImage::IsTransparencySupported())
{
m_imgLogo.SetTransparentColor( RGB(255,255,255)); // white
m_imgImage.SetTransparentColor( RGB(255,255,255));
}
// CImage::TransparentBlt: 4,8 bit source bitmaps with transparency
// CImage::AlphaBlend: 32 bits-per-pixel bitmaps with transparency
CRect rect;
GetClientRect( &rect );
m_imgLogo.Draw( dc.GetSafeHdc(), 10, 10 );
m_imgImage.Draw( dc.GetSafeHdc(), rect.right - m_imgImage.GetWidth() - 10, 10 );
}
// App command to run the dialog
void CConfiguratorApp::OnAppAbout()
{
CAboutDlg aboutDlg;
aboutDlg.DoModal();
}
// CConfiguratorApp customization load/save methods
void CConfiguratorApp::PreLoadState()
{
BOOL bNameValid;
CString strName;
bNameValid = strName.LoadString(IDS_EDIT_MENU);
ASSERT(bNameValid);
GetContextMenuManager()->AddMenu(strName, IDR_POPUP_EDIT);
}
void CConfiguratorApp::LoadCustomState()
{
}
void CConfiguratorApp::SaveCustomState()
{
}
// CConfiguratorApp message handlers
// Added by wangdong for Splash screen
BOOL CConfiguratorApp::PreTranslateMessage(MSG* pMsg)
{
// TODO: 在此添加专用代码和/或调用基类
// CG: The following lines were added by the Splash Screen component.
if (CSplashWnd::PreTranslateAppMessage(pMsg))
{
return TRUE;
}
return CWinAppEx::PreTranslateMessage(pMsg);
}
void CConfiguratorApp::OnUpdateLoglevelErr(CCmdUI *pCmdUI)
{
// TODO: 在此添加命令更新用户界面处理程序代码
if( pCmdUI )
{
if( m_uLogLevel == LOG_ERR )
{
pCmdUI->SetCheck();
}
}
}
void CConfiguratorApp::OnUpdateLoglevelOpr(CCmdUI *pCmdUI)
{
// TODO: 在此添加命令更新用户界面处理程序代码
if( pCmdUI )
{
if( m_uLogLevel == LOG_OPR )
{
pCmdUI->SetCheck();
}
}
}
void CConfiguratorApp::OnUpdateLoglevelAll(CCmdUI *pCmdUI)
{
// TODO: 在此添加命令更新用户界面处理程序代码
if( pCmdUI )
{
if( m_uLogLevel == LOG_ALL )
{
pCmdUI->SetCheck();
}
}
}
void CConfiguratorApp::OnLoglevelErr()
{
// TODO: 在此添加命令处理程序代码
CString str;
str.Format( L"Log level changed to: %s", L"Error" );
LogInfo( str );
m_uLogLevel = LOG_ERR;
}
void CConfiguratorApp::OnLoglevelOpr()
{
// TODO: 在此添加命令处理程序代码
CString str;
str.Format( L"Log level changed to: %s", L"Error and Operation" );
LogInfo( str );
m_uLogLevel = LOG_OPR;
}
void CConfiguratorApp::OnLoglevelAll()
{
// TODO: 在此添加命令处理程序代码
CString str;
str.Format( L"Log level changed to: %s", L"All" );
LogInfo( str );
m_uLogLevel = LOG_ALL;
}
// =======================================================================
// Function name : SwitchLanguageType
// Description :
// Return type : void
// Parameters :
// Author : WangDong 2012.01.04 10:00:00
// =======================================================================
void CConfiguratorApp::SwitchLanguageType( UINT uLanguageType, bool bFromOpenMenuCommand, bool bSwitchPd )
{
switch( uLanguageType )
{
case ENG:
ASSERT( m_hEngLangDLL != NULL );
AfxSetResourceHandle( m_hEngLangDLL );
break;
case CHS:
if( m_hEngLangDLL == NULL )
{
m_hEngLangDLL = AfxGetResourceHandle(); // English Resource
}
m_hLangDLL = AfxLoadLibrary( _T("Configurator_Chs.dll"));
ASSERT( m_hLangDLL != NULL );
if( m_hLangDLL != NULL )
{
AfxSetResourceHandle( m_hLangDLL );
}
break;
default:
ASSERT( m_hEngLangDLL != NULL );
AfxSetResourceHandle( m_hEngLangDLL );
break;
}// switch
m_uLanguageType = uLanguageType;
// Set the product's language type to registry
CString strPath = GetPathAccordingToProduct( m_uProductType );
WriteProfileInt( strPath, L"LANGUAGE_CFG", m_uLanguageType );
// Reset Menu and ToolBar
((CMainFrame*)m_pMainWnd)->m_wndMenuBar.ResetAll();
((CMainFrame*)m_pMainWnd)->m_wndMenuBar.SetRecentlyUsedMenus( FALSE );
// Set View ToolBar Text
std::vector<CString> strVector;
CString strToolBar;
for( size_t i = IDS_TOOL_CFG; i <= IDS_TOOL_ALARM; i++ )
{
strToolBar.LoadStringW( i );
strVector.push_back( strToolBar );
}
((CMainFrame*)m_pMainWnd)->m_viewToolBar.SetToolBarBtnText( 0, strVector.at( 0 ));
((CMainFrame*)m_pMainWnd)->m_viewToolBar.SetToolBarBtnText( 1, strVector.at( 1 ));
((CMainFrame*)m_pMainWnd)->m_viewToolBar.SetToolBarBtnText( 2, strVector.at( 2 ));
((CMainFrame*)m_pMainWnd)->m_viewToolBar.SetToolBarBtnText( 3, strVector.at( 3 ));
((CMainFrame*)m_pMainWnd)->m_viewToolBar.SetToolBarBtnText( 4, strVector.at( 4 ));
((CMainFrame*)m_pMainWnd)->m_viewToolBar.AdjustSizeImmediate();
if( !bFromOpenMenuCommand )
{
// Set m_bResetViewFlag Flag
if( !m_bResetViewFlag )
{
m_bResetViewFlag = true;
}
// New or Open Document
CString strTitle(((CMainFrame*)m_pMainWnd)->GetActiveDocument()->GetTitle());
int index = strTitle.ReverseFind( L'.' );
if( index == -1 )
{
if( TS350 == m_uProductType )
{
// When only switch laguage, New don't need to select application type
// When switch product, need to select application type
m_bMenuSelFlag = !bSwitchPd;
}
OnFileNew(); // New Document
m_bMenuSelFlag = false;
}
else
{
CString strName( strTitle.Right( strTitle.GetLength() - index - 1 ));
if( strName.CompareNoCase( GetProductName()) == 0 )
{
m_pDocManager->GetBestTemplate( strTitle )->OpenDocumentFile( strTitle, TRUE, TRUE );
}
else
{
if( TS350 == m_uProductType )
{
m_bMenuSelFlag = true; // When New, don't need to select application type
}
OnFileNew(); // New Document
m_bMenuSelFlag = false;
}
}
}
}
// =======================================================================
// Function name : OnViewLanguageChs
// Description :
// Return type : void
// Parameters :
// Author : WangDong 2012.01.04 10:00:00
// =======================================================================
void CConfiguratorApp::OnViewLanguageChs()
{
// TODO: 在此添加命令处理程序代码
ASSERT( m_uLanguageType != CHS );
SwitchLanguageType( CHS );
}
// =======================================================================
// Function name : OnViewLanguageEng
// Description :
// Return type : void
// Parameters :
// Author : WangDong 2012.01.04 10:15:00
// =======================================================================
void CConfiguratorApp::OnViewLanguageEng()
{
// TODO: 在此添加命令处理程序代码
ASSERT( m_uLanguageType != ENG );
SwitchLanguageType( ENG );
}
// =======================================================================
// Function name : SwitchProductType
// Description :
// Return type : void
// Parameters :
// Author : WangDong 2011.04.14 15:00:00
// =======================================================================
void CConfiguratorApp::SwitchProductType( UINT uProductType, bool bFromOpenMenuCommand )
{
// If not TS350, Update title, delete application type information
if((uProductType != TS350) && AfxGetMainWnd()->GetSafeHwnd())
{
((CMainFrame*)AfxGetMainWnd())->UpdateTitle( CMainFrame::TITLE_NONE );
}
try
{
CString strPreProduct( GetProductName()); // Get product name before switch
//1. Set m_bResetViewFlag
m_bResetViewFlag = true;
//2. Write registry in order to save product information
CString strProductRegPath( GetPathAccordingToProduct( m_uProductType ));
//2.1 Product Type
WriteProfileInt( L"SETTINGS", L"PRODUCT_TYPE", m_uProductType );
//2.2 Log Level
WriteProfileInt( strProductRegPath, L"LOG_LEVEL", m_uLogLevel );
//2.3 Language Type
WriteProfileInt( strProductRegPath, L"LANGUAGE_CFG", m_uLanguageType );
//2.5 SettingGrid Size
CString strGrid = strProductRegPath + L"\\Grid Window";
for( int i = 0; i < global::SETTING_GRID_COLUMNS; i++ )
{
CString strCol;
strCol.Format( L"ColWidth %d", i );
WriteProfileInt( strGrid, strCol, global::SettingGridColWidths[i] );
}
//2.6 Alias Grid Size
strGrid = strProductRegPath + L"\\Alias Window";
for( int i = 0; i < global::TAGS_GRID_COLUMNS; i++ )
{
CString strCol;
strCol.Format( L"ColWidth %d", i );
WriteProfileInt( strGrid, strCol, global::TagsGridColWidths[i] );
}
//2.7 History Grid Size
strGrid = strProductRegPath + L"\\History Window";
for( int i = 0; i < global::HISTORY_GRID_COLUMNS; i++ )
{
CString strCol;
strCol.Format( L"ColWidth %d", i );
WriteProfileInt( strGrid, strCol, global::HisGridColWidths[i] );
}
//2.8 Font
CString strFont = strProductRegPath + L"\\Font";
WriteProfileString( strFont, L"Font Name", global::FontName );
WriteProfileInt( strFont, L"Font Size", static_cast<int>(global::FontSize));
//2.8 Calibrate sheet
CalSheet.reset();
//2.9 History
CMainFrame* pMainFrame = (CMainFrame*)AfxGetMainWnd();
if( pMainFrame )
{
CConfiguratorDoc* pDoc = (CConfiguratorDoc*)pMainFrame->GetActiveDocument();
if( pDoc )
{
pDoc->SetRecordModified( false ); //2.9.1 Reset RecordModified Flag
pDoc->ResetHistory(); //2.9.2 Reset History Ctrls, Datas and Clear history views
}
}
//3. Switch Product Type
m_uProductType = uProductType;
SetProductNumberByType();
CString strTargetProduct( GetProductName()); // Get Target Product Name
//4. Application Type: If TS350,User will select it in CConfiguratorDoc::OnNewDocument;
// else, Set default value 1.
if((m_uProductType != TS350) && (m_nAppType != 1))
{
m_nAppType = 1;
}
//5. Read from registry to get target product informatio
strProductRegPath = GetPathAccordingToProduct( m_uProductType );
//5.1 SettingGrid Size
strGrid = strProductRegPath + L"\\Grid Window";
for( int i = 0; i < global::SETTING_GRID_COLUMNS; i++ )
{
CString strCol;
strCol.Format( L"ColWidth %d", i );
global::SettingGridColWidths[i] = GetProfileInt( strGrid, strCol, 0 );
}
//5.2 Alias Grid Size
strGrid = strProductRegPath + L"\\Alias Window";
for( int i = 0; i < global::TAGS_GRID_COLUMNS; i++ )
{
CString strCol;
strCol.Format( L"ColWidth %d", i );
global::TagsGridColWidths[i] = GetProfileInt( strGrid, strCol, 0 );
}
//5.3 History Grid Size
strGrid = strProductRegPath + L"\\History Window";
for( int i = 0; i < global::HISTORY_GRID_COLUMNS; i++ )
{
CString strCol;
strCol.Format( L"ColWidth %d", i );
global::HisGridColWidths[i] = GetProfileInt( strGrid, strCol, 0 );
}
//5.4 Font
strFont = strProductRegPath + L"\\Font";
global::FontName = GetProfileStringW( strFont, L"Font Name", global::FontName );
global::FontSize = (float)GetProfileIntW( strFont, L"Font Size", static_cast<int>(global::FontSize));
//5.5 Comm Settings
if( CommSettings.get())
{
CommSettings->ReadRegistry();
}
//5.6 Log Level
m_uLogLevel = GetProfileInt( GetPathAccordingToProduct( m_uProductType ), L"LOG_LEVEL", LOG_OPR );
//6. Compare
//6.1 Default Compare Type: controller
m_uCmpType = CMP_REM;
//6.2 Reset compare file path name
if( pMainFrame )
{
CConfiguratorDoc* pDoc = (CConfiguratorDoc*)pMainFrame->GetActiveDocument();
if( pDoc )
{
pDoc->ResetCmpFilePathName();
}
}
if( !bFromOpenMenuCommand )
{
//7 Language Type
if( m_uLanguageType != GetProfileInt( GetPathAccordingToProduct( m_uProductType ), L"LANGUAGE_CFG", ENG ))
{
m_uLanguageType = GetProfileInt( GetPathAccordingToProduct( m_uProductType ), L"LANGUAGE_CFG", ENG );
// Switch Language
SwitchLanguageType( m_uLanguageType, bFromOpenMenuCommand, true );
}
else
{
OnFileNew(); //8. New Document
}
}
//9. Log
CString str;
str.Format( L"Converting product from %s to %s.", strPreProduct, strTargetProduct );
LogInfo( str );
}//try
catch( CException &e )
{
e.ReportError();
e.Delete();
theApp.LogInfo( L"Exception occured in CConfiguratorApp::SwitchProductType!" );
}
catch(...)
{
theApp.LogInfo( L"Unknown exception occured in CConfiguratorApp::SwitchProductType!" );
}
}
void CConfiguratorApp::OnDeviceDsc100()
{
// TODO: 在此添加命令处理程序代码
DeviceSwitch( DSC100 );
}
void CConfiguratorApp::OnDeviceTs350()
{
// TODO: 在此添加命令处理程序代码
DeviceSwitch( TS350 );
}
void CConfiguratorApp::OnDeviceDsc110()
{
// TODO: 在此添加命令处理程序代码
DeviceSwitch( DSC110 );
}
void CConfiguratorApp::DeviceSwitch( const UINT uNewProduct )
{
if( m_uProductType != uNewProduct )
{
// Save code for the ori product
CString strProductRegPath( GetPathAccordingToProduct( m_uProductType ));
WriteProfileInt( strProductRegPath, L"FIRM_CODE", m_nCurrentCode );
// New Product
strProductRegPath = GetPathAccordingToProduct( uNewProduct );
int code = GetProfileInt( strProductRegPath, L"FIRM_CODE", 0 );
if( code != 0 )
{
m_nCurrentCode = code;
}
else
{
m_nCurrentCode = GetNewestCode( uNewProduct );
}
m_fXMLVersion = GetXMLVersionFromCode( uNewProduct, m_nCurrentCode );
SwitchProductType( uNewProduct );
}
}
// ====================================================================
// Function name: OnFileNew
// Description : 1. DoDisconnected
// 2. Call CWinApp::OnFileNew
// Return type :
// Parameters :
// Author : WangDong 2011.03.30 10:30:00
// =====================================================================
void CConfiguratorApp::OnFileNew()
{
try
{
if( m_pMainWnd->GetSafeHwnd())
{
CMainFrame* pFrame = (CMainFrame*)m_pMainWnd;
CConfiguratorDoc* pDoc = (CConfiguratorDoc*)pFrame->GetActiveDocument();
ASSERT( pDoc != NULL );
if( !pDoc->IsStoppingHistoryRecord())
{
return;
}
pFrame->DoDisconnect(); // Do Disconnected
}
// Call CWinApp::OnFileNew
CWinAppEx::OnFileNew(); // When m_pDocManager is not NULL, m_pDocManager->OnFileNew()
// Access level: Enter password
if( !global::Security.CanTune()) // None or ReadOnly
{
std::auto_ptr<CPasswordDlg> dlg( new CPasswordDlg());
dlg->DoModal();
// Refresh all views
if(((CMainFrame*)AfxGetMainWnd() != NULL) && (((CMainFrame*)m_pMainWnd)->GetActiveDocument() != NULL))
{
((CMainFrame*)m_pMainWnd)->GetActiveDocument()->UpdateAllViews( NULL, CConfiguratorDoc::HINT_REFRESH );
}
}
// Reset m_bResetViewFlag flag
if( m_bResetViewFlag )
{
m_bResetViewFlag = false;
}
}
catch( CException &e )
{
e.ReportError();
e.Delete();
theApp.LogInfo( L"Exception occured in CConfiguratorApp::OnFileNew!" );
}
catch(...)
{
theApp.LogInfo( L"Unknown exception occured in CConfiguratorApp::OnFileNew!" );
}
}
// ====================================================================
// Function name: OnOpenRecentFile
// Description : 1. DoDisconnected
// 2. Call CWinApp::OnOpenRecentFile
// Return type :
// Parameters :
// Author : WangDong 2011.03.30 14:40:00
// =====================================================================
BOOL CConfiguratorApp::OnOpenRecentFile( UINT nID )
{
CMainFrame* pFrame = (CMainFrame*)AfxGetMainWnd();
ASSERT( pFrame->GetSafeHwnd());
CConfiguratorDoc* pDoc = (CConfiguratorDoc*)(pFrame->GetActiveDocument());
ASSERT( pDoc != NULL );
if( !pDoc->IsStoppingHistoryRecord())
{
return TRUE;
}
pFrame->DoDisconnect();
return CWinAppEx::OnOpenRecentFile( nID );
}
// ====================================================================
// Function name: OnDeviceSelapptype
// Description : IDOK: if not same, show warning, if choose yes, do new operation
// Return type :
// Parameters :
// Author : WangDong 2011.11.04 11:30:00
// =====================================================================
void CConfiguratorApp::OnDeviceSelapptype()
{
// TODO: 在此添加命令处理程序代码
ASSERT( TS350 == m_uProductType );
std::auto_ptr<CSelAppTypeDlg> dlg ( new CSelAppTypeDlg());
if( dlg.get() && (dlg->DoModal() == IDOK))
{
int nAppType = -1;
switch( dlg->m_nIndex )
{
case 0: // Gen
nAppType = CConfiguratorDoc::APPTYPE_GEN;
break;
case 1: // Mech
nAppType = CConfiguratorDoc::APPTYPE_MECH;
break;
default:
nAppType = CConfiguratorDoc::APPTYPE_GEN;
}
// Set Application Type
if( nAppType != GetAppType())
{
// Show Warning
if( AfxMessageBox( IDS_APPTYPE_CHANGE, MB_ICONEXCLAMATION | MB_YESNO) == IDYES )
{
m_bMenuSelFlag = true;
SetAppType( nAppType );
OnFileNew();
m_bMenuSelFlag = false;
}
}
}// IDOK
}
// ====================================================================
// Function name: CanMatch
// Description : Check if Configurator can match the product and xml file
// Return type : 0: OK;
// 1: Product mismatch
// 2: xml mismatch
// Parameters :
// Author : WangDong 2011.11.04 11:30:00
// =====================================================================
int CConfiguratorApp::CanMatch( UINT uProductType, float fXMLVersion )
{
ASSERT( m_pVersionCTL != NULL );
if( NULL == m_pVersionCTL )
{
return PRODUCT_MISMATCH;
}
return m_pVersionCTL->CanMatch( uProductType, fXMLVersion );
}
// ===============================================================
// Function name : IsXMLMatchCode
// Description : Check if the current xml file can match the code
// Return : true, xml can match the code;
// Parameters : type: Product type, such as DSC100
// fversion:XML file version to be checked
// code: Firmware code
// Author : WangDong 2012.08.07 14:00:00
// ===============================================================
bool CConfiguratorApp::IsXMLMatchCode( const UINT uProductType, const float fXMLVersion, const int nCode ) const
{
ASSERT( m_pVersionCTL != NULL );
if( NULL == m_pVersionCTL )
{
return false;
}
return m_pVersionCTL->IsXMLMatchCode( uProductType, fXMLVersion, nCode );
}
// ===============================================================
// Function name : GetNewestCode
// Description :
// Return : >0: The newest firmware code; others -1
// Parameters : uProductType: Product type, such as DSC100
// Author : WangDong 2012.08.08 13:30:00
// ===============================================================
int CConfiguratorApp::GetNewestCode( const UINT uProductType )
{
ASSERT( m_pVersionCTL != NULL );
if( NULL == m_pVersionCTL )
{
return -1;
}
return m_pVersionCTL->GetNewestCode( uProductType );
}
// ===============================================================
// Function name : GetNewestCodeFromXML
// Description :
// Return : newest code of the xml file if success, others -1
// Parameters : type: Product type, such as DSC100
// fversion: xml file version
// Author : WangDong 2012.08.07 13:00:00
// ===============================================================
int CConfiguratorApp::GetNewestCodeFromXML( const UINT type, const float fversion )
{
ASSERT( m_pVersionCTL != NULL );
if( NULL == m_pVersionCTL )
{
return -1;
}
return m_pVersionCTL->GetNewestCodeFromXML( type, fversion );
}
// ===============================================================
// Function name : GetXMLVersionFromCode
// Description :
// Return : xml file version if success, others 0.0
// Parameters : type: Product type, such as DSC100
// code: Firmware code
// Author : WangDong 2012.08.08 13:00:00
// ===============================================================
float CConfiguratorApp::GetXMLVersionFromCode( const UINT type, const int code )
{
ASSERT( m_pVersionCTL != NULL );
if( NULL == m_pVersionCTL )
{
return 0.0;
}
return m_pVersionCTL->GetXMLVersionFromCode( type, code );
}
//=====================================================================
/// Global Functions
// ====================================================================
// Function name: RegSetRelated
// Description :
// Return type :
// Parameters :
// Author : WangDong 2011.04.29 09:50:00
// =====================================================================
BOOL RegSetRelated( CString& strExt, CString& strCommand, CString& strDefaultIcon )
{
if( strExt.IsEmpty() || strCommand.IsEmpty() || strDefaultIcon.IsEmpty())
{
return FALSE;
}
// Such as: .DSC100 Configurator.Document
LPCTSTR lpData = L"Configurator.Document";
RegSetValueW( HKEY_CLASSES_ROOT, strExt, REG_SZ, lpData, ::wcslen( lpData )); // not include a null terminator
CString strSubKey;
strSubKey.Format( L"%s%s", strExt, L"\\shell\\open\\command" );
RegSetValueW( HKEY_CLASSES_ROOT, strSubKey, REG_SZ, strCommand, strCommand.GetLength());
/// Configurator.Document
// Default Icon
strSubKey.Format( L"%s\\%s", lpData, L"DefaultIcon" );
RegSetValueW( HKEY_CLASSES_ROOT, strSubKey, REG_SZ, strDefaultIcon, strDefaultIcon.GetLength());
// shell
strSubKey.Format( L"%s%s", lpData, L"\\shell\\open\\command" );
RegSetValueW( HKEY_CLASSES_ROOT, strSubKey, REG_SZ, strCommand, strCommand.GetLength());
return TRUE;
}
// ====================================================================
// Function name: RegisterFileandProgram
// Description :
// Return type :
// Parameters :
// Author : WangDong 2011.04.29 09:50:00
// =====================================================================
void RegisterFileandProgram()
{
// File Extention
std::vector<LPCTSTR> FileExtension;
FileExtension.push_back( L".DSC100" );
FileExtension.push_back( L".TS350" );
FileExtension.push_back( L".DSC110" );
// Get exe path
wchar_t exepath[MAX_PATH];
memset( exepath, 0, sizeof(exepath));
GetModuleFileNameW( NULL, exepath, sizeof(exepath));
CString strCommand( exepath );
strCommand += L" \"%1\""; // C:\Program Files\Tri-Sen\Configurator\Configurator.exe "%1"
CString strDefaultIcon( exepath );
strDefaultIcon += L",1"; // C:\Program Files\Tri-Sen\Configurator\Configurator.exe,1
// Set File Extention
std::vector<LPCTSTR>::iterator it = FileExtension.begin();
std::vector<LPCTSTR>::iterator eit = FileExtension.end();
while( it != eit )
{
CString strExt( *it );
RegSetRelated( strExt, strCommand, strDefaultIcon );
it++;
}
FileExtension.clear();
}
// ====================================================================
// Function name: RegisterFileandProgram
// Description :
// Return type :
// Parameters :
// Author : wangdong 2011.04.11 15:30:00
// =====================================================================
CString GetFilePath()
{
wchar_t exepath[MAX_PATH];
CString strdir, tmpdir;
memset( exepath, 0, sizeof(exepath));
GetModuleFileNameW( NULL, exepath, sizeof(exepath));
tmpdir = exepath;
strdir = tmpdir.Left( tmpdir.ReverseFind( L'\\' ));
return strdir;
}
// =======================================================================
// Function name : ValidateHisFile
// Description : Check product type and if file exists
// Note: NULL is valid
// Return type : bool
// Parameters :
// Author : WangDong 2013.04.12 17:15:00
// =======================================================================
UINT ValidateHisFile( const CString strHisFileName )
{
if( strHisFileName.IsEmpty())
{
return E_FILE_EMPTY;
}
// File Name: *-%s-*.xml
// Ext: xml
CString str( strHisFileName.Right(3));
if( str.CompareNoCase( L"xml" ) != 0 )
{
return E_FILE_EXT;
}
// Product Name
int last = strHisFileName.ReverseFind( '-' );
if( -1 == last )
{
return E_FILE_FORMAT;
}
str = strHisFileName.Left( last ); // *-%s
int index = str.ReverseFind( '-' );
if( -1 == index )
{
return E_FILE_FORMAT;
}
str = str.Right( str.GetLength() - index -1 ); // %s
if( str.CompareNoCase( theApp.GetProductName()) != 0 )
{
return E_FILE_PRODUCT;
}
// File Exists
if( !::PathFileExistsW( strHisFileName ))
{
return E_FILE_EXIST;
}
return E_NONE;
}
// ====================================================================
// Function name: GetEFileString
// Description :
// Return type :
// Parameters :
// Author : wangdong 2011.04.11 15:30:00
// =====================================================================
CString GetEHisFileString( UINT nType )
{
CString strFileError;
switch( nType )
{
case E_NONE:
strFileError = L"None";
break;
case E_FILE_EMPTY:
strFileError = L"File name empty";
break;
case E_FILE_EXT:
strFileError = L"File ext is not xml";
break;
case E_FILE_FORMAT:
strFileError = L"Format error";
break;
case E_FILE_PRODUCT:
strFileError = L"Product type error";
break;
case E_FILE_EXIST:
strFileError = L"File not exists";
break;
default:
strFileError = L"Others";
break;
}
return strFileError;
}
// =======================================================================
// Function name : IsHisFileSameArray
// Description : 判断两历史文件是否属于同一序列:文件路径名中除序列号不同外,其他均相同;
// 即启动记录的时间相同,只是写满后,增加了序列号
// Return type :
// Parameters :
// Author : WangDong 2013.04.17 16:00:00
// =======================================================================
bool IsHisFileSameArray(const CString strName1, const CString strName2)
{
if((ValidateHisFile(strName1) != E_NONE) || (ValidateHisFile(strName2) != E_NONE))
{
return false;
}
// *-%s-*.xml
int index = strName1.ReverseFind( '-' );
CString str1( strName1.Left(index));
index = strName2.ReverseFind( '-' );
CString str2( strName2.Left(index));
bool bResult = str1.CompareNoCase( str2 ) == 0;
return bResult;
}
// =======================================================================
// Function name : GetArrayCode
// Description : 获取文件序列号
// Return type : 文件无效时,返回-1;有效时,返回文件序列号
// Parameters :
// Author : WangDong 2013.04.17 16:00:00
// =======================================================================
int GetHisFileArrayCode(const CString strHisFileName)
{
if( ValidateHisFile(strHisFileName) != E_NONE )
{
return -1;
}
// *-%s-*.xml
int index = strHisFileName.Find( '.' );
CString str( strHisFileName.Left(index));
// *-%s-*
index = str.ReverseFind( '-' );
str = str.Right( str.GetLength() - index -1 );
int code = -1;
::swscanf_s( str, L"%d", &code );
return code;
}
void VariantToRecordString( const VARIANT& v, CString& s )
{
switch( V_VT( &v ))
{
case VT_BOOL:
s = ( V_BOOL(&v)? L"1" : L"0" );
break;
case VT_I2: // short
s.Format( L"%d", V_I2(&v));
break;
case VT_UI2: // USHORT
s.Format( L"%d", V_UI2(&v));
break;
case VT_R4:
s.Format( L"%.2f", V_R4(&v));
break;
case VT_I4: // long
case VT_UI4:
s.Format( L"%d", V_I4(&v));
break;
default:
s = L"";
}
}
void VariantToString(const VARIANT& v, CString& s, UINT nHexType)
{
switch( V_VT( &v ))
{
case VT_BOOL:
s = ( V_BOOL( &v )? L"True" : L"False");
break;
case VT_I2: // short
if( TYPE_BIN == nHexType )
{
s.Format( L"%d", V_I2(&v));
}
else
{
s.Format( L"0x%04X", V_I2(&v));
}
break;
case VT_UI2: // USHORT
if( TYPE_BIN == nHexType )
{
s.Format( L"%d", V_UI2(&v));
}
else
{
s.Format( L"0x%04X", V_UI2(&v));
}
break;
case VT_R4:
if( CConfiguratorApp::DSC110 == theApp.GetProductType())
{
s.Format( L"%.3f", V_R4(&v));
}
else
{
s.Format( L"%.2f", V_R4(&v));
}
break;
case VT_I4: // long
case VT_UI4:
if( TYPE_BIN == nHexType )
{
s.Format( L"%d", V_I4(&v));
}
else
{
s.Format( L"0x%04X", V_I4(&v));
}
break;
case (VT_I1 | VT_BYREF):
case (VT_UI1 | VT_BYREF):
if (V_I1REF(&v) == NULL)
{
s = L"";
}
else
{
s = V_I1REF(&v);
}
break;
default:
ASSERT( false );
s = L"";
}
}
//========================================================================
// Function name : PointTwipsToPixels
// Description : Convert twips to pixels
// Return type : void
// Parameters :
// Author : rjvs 2002-03-14 16:43:03 (UTC-6:00)
// =======================================================================
void PointTwipsToPixels(int x, int y, CPoint& pt)
{
HDC hdc = ::CreateIC( TEXT("DISPLAY"), NULL, NULL, NULL );
int pix = ::GetDeviceCaps( hdc, LOGPIXELSX );
pt.x = ::MulDiv( x, pix, 1440 );
pix = ::GetDeviceCaps( hdc, LOGPIXELSY );
pt.y = ::MulDiv( y, pix, 1440 );
::DeleteDC( hdc );
}
//========================================================================
// Function name : EncodeTimeSec
// Description : Time/seconds function
// Return type : COleDateTime
// Parameters : ASeconds
// Author : rjvs
// wangdong
// =======================================================================
COleDateTime EncodeTimeSec( double ASeconds )
{
if( ASeconds < 0.0 )
{
ASeconds = 0.0;
}
// Days
WORD d = static_cast<WORD>(ASeconds / 86400.0);
// Hours
WORD h = static_cast<WORD>(static_cast<int>(ASeconds / 3600.0) % 24);
// Minutes
WORD m = static_cast<WORD>(static_cast<int>(ASeconds / 60.0) % 60);
// Seconds
WORD s = static_cast<WORD>(static_cast<int>(ASeconds) % 60);
// Milliseconds
WORD z = static_cast<WORD>((ASeconds - static_cast<int>(ASeconds)) * 1000.0);
SYSTEMTIME ts;
ts.wYear = 1899;
ts.wMonth = 12;
ts.wDay = 30;
ts.wDayOfWeek = 6;
ts.wHour = h;
ts.wMinute = m;
ts.wSecond = s;
ts.wMilliseconds = 0;
COleDateTime Result( ts );
double dt = 1.0/(24*3600*1000); // the double value represent by 1ms
Result.m_dt += (d + z*dt);
return Result;
}
/// <summary>
/// Returns an error message from Windows or from executable.</summary>
/// <created>
/// rjvs 2002-03-08 11:05:46 (UTC-6:00)
/// wangdong 2011-02-28 18:50:00
/// </created>
CString HrGetMessage( HRESULT hr )
{
// Check the facility
CString strMessage;
if( HRESULT_FACILITY(hr) == FACILITY_MODBUS ) // User defined mosbus code
{
strMessage.LoadStringW( HRESULT_CODE(hr));
}
else
{
LPVOID lpMsgBuf;
DWORD c = ::FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER ,
NULL,
hr,
NULL,
(LPWSTR)&lpMsgBuf,
0,
NULL );
strMessage = (LPWSTR)lpMsgBuf;
LocalFree(lpMsgBuf);
}
return strMessage;
}
//========================================================================
// Function name : GetSubKeyString
// Description : L"software\\tri-sen\\configurator\\settings" + L"\\product type"
// such as TS320, DSC100
// Return type : void
// Parameters :
// Author : Wangdong 2011-03-02 14:30:00 (UTC-6:00)
// =======================================================================
CString GetSubKeyString()
{
CString strSubKey( L"software\\tri-sen\\configurator\\settings" );
switch( theApp.GetProductType())
{
case CConfiguratorApp::DSC100:
strSubKey += L"\\DSC100";
break;
case CConfiguratorApp::TS350:
strSubKey += L"\\TS350";
break;
case CConfiguratorApp::DSC110:
strSubKey += L"\\DSC110";
break;
default:
strSubKey += L"\\DSC100";
}
return strSubKey;
}
//========================================================================
// Function name : DumpBytes
// Description :
// Return type : void
// Parameters :
// Author : Wangdong 2011-03-08 14:10:00 (UTC-6:00)
// =======================================================================
CString DumpBytes( const BYTE* Buffer, int Count )
{
CString strDataBytes;
if( !CheckReadPtr( Buffer, Count*sizeof(BYTE)))
{
return strDataBytes;
}
for( int i = 0; i < Count; ++i )
{
CString s;
if( i == 0 )
{
s.Format( L"%02X", *Buffer );
}
else
{
s.Format( L" %02X", *Buffer );
}
strDataBytes += s;
++Buffer;
}
return strDataBytes;
}
//==========================================================================
/// global parameters
// Only for TS350:
bool g_bCfgRefresh = false; // 改变配置项时,Configuration左视图节点,Tuning视图左视图的PID项的可视属性可能需要动态刷新
bool g_bReadRefresh = false; // Retrieve操作或者Aliases视图中读操作引起的刷新
/// global namespace
namespace global
{
CCfgSecurity Security;
// font
float FontSize = 10.0;
CString FontName(L"Arial");
CFont g_Font;
// Column Counts
std::vector<int> SettingGridColWidths( SETTING_GRID_COLUMNS, 0 );
std::vector<int> TagsGridColWidths( TAGS_GRID_COLUMNS, 0 );
std::vector<int> HisGridColWidths( HISTORY_GRID_COLUMNS, 0 );
// Trace Colors
const long TraceColors[8] = { clRed, clGreen, clBlue, clGray, clMaroon, clFuchsia, clTeal, clLBlue /*clYellow clHiPurple clNavy*/ };
// Rename Existing log files
void RenameLogFiles(void)
{
CString strExePath = GetFilePath();
strExePath += L"\\" + LOG_FILE_NAME; // ...Configurator
for( int i = LOG_FILE_COUNT; i > 0; --i )
{
// Rename existing file
CString strLogName;
if( i > 1 )
{
strLogName.Format( L"%s-%d%s", strExePath, i-1, LOG_FILE_EXT );
}
else
{
strLogName.Format( L"%s%s", strExePath, LOG_FILE_EXT );
}
if( ::PathFileExistsW( strLogName ))
{
if( i == LOG_FILE_COUNT )
{
::DeleteFileW( strLogName );
}
else
{
CString strNewName;
strNewName.Format( L"%s-%d%s", strExePath, i, LOG_FILE_EXT );
const char* pOld = CW2A(strLogName);
const char* pNew = CW2A(strNewName);
::rename( CW2A(strLogName), CW2A(strNewName));
}
}//if exists
}//for
}
}//namespace
//----------------------------------------------------------------
| [
"[email protected]"
] | |
a6e848d20e67f7aa4fe99de4435f9a00ede9025d | 6d0ab0f05b0732549d8e13c41e52853001563d41 | /GLMain.hpp | 7d6545d0b655ebb8e586dd15fbf74eceba5092e0 | [
"MIT"
] | permissive | Philipp-M/MandelbrotCL | 7101149c6a5036d232172a677cd9416cb6b2cf5d | 5c02065b72eb46292017be36757c9e088652f981 | refs/heads/master | 2016-08-12T14:48:25.914996 | 2016-01-03T01:10:53 | 2016-01-03T01:10:53 | 48,928,933 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,017 | hpp | #pragma once
#include "ShaderProgram.hpp"
#include "OCLRenderer.hpp"
#include <SDL2/SDL.h>
#include <memory>
class GLMain
{
private:
std::shared_ptr<ShaderProgram> shaderProgram;
std::shared_ptr<OCLRenderer> oclRenderer;
GLuint vao;
GLuint vbo;
/**
* initializes a basic opengl window and the opencl renderer
*/
void initialize(size_t width, size_t height, SDL_Window *window, SDL_GLContext &context);
public:
GLMain(SDL_Window *window, SDL_GLContext &context);
~GLMain();
/**
* deletes all the acquired buffers and the opencl renderer
*/
void cleanup();
/**
* displays the rendered texture
*/
void display();
/**
* resizes the opengl screen and does the same to the opencl renderer
*/
void reshape(int width, int height);
/**
* saves a screencapture in the current directory with the following name scheme:
* render_{CURRENT_TIME}_{SAMPLE_COUNT}_Spp.bmp
*/
void saveRenderedImage();
/**
* reference to the opencl renderer
*/
OCLRenderer * getOclRenderer();
};
| [
"[email protected]"
] | |
a21ddef24f1ff1420bb657bce94238726a6565a7 | 7e4c23c78d3bf5db111cb9771ca6e7dedaceb0b8 | /Source/Compiler/InstanceLoaders/GuiInstanceLoader_Tab.cpp | 6d8944b48d91cb9db7d118d4110d46278178391b | [
"MS-PL"
] | permissive | qqaaqqaa123456/GacUI | 582f5353b5e6e9fb15b45a30d7f95187d7dfbe55 | e2a0703d1dd95ea2f611a8693fb4f27752fde9f0 | refs/heads/master | 2021-01-11T21:37:42.245601 | 2017-01-10T21:34:05 | 2017-01-10T21:34:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,111 | cpp | #include "GuiInstanceLoader_TemplateControl.h"
#ifndef VCZH_DEBUG_NO_REFLECTION
namespace vl
{
namespace presentation
{
namespace instance_loaders
{
/***********************************************************************
GuiTabInstanceLoader
***********************************************************************/
#define BASE_TYPE GuiTemplateControlInstanceLoader<GuiTab, GuiTabTemplate_StyleProvider, GuiTabTemplate>
class GuiTabInstanceLoader : public BASE_TYPE
{
public:
GuiTabInstanceLoader()
:BASE_TYPE(description::TypeInfo<GuiTab>::content.typeName, L"CreateTabStyle")
{
}
void GetPropertyNames(const TypeInfo& typeInfo, collections::List<GlobalStringKey>& propertyNames)override
{
propertyNames.Add(GlobalStringKey::Empty);
BASE_TYPE::GetPropertyNames(typeInfo, propertyNames);
}
Ptr<GuiInstancePropertyInfo> GetPropertyType(const PropertyInfo& propertyInfo)override
{
if (propertyInfo.propertyName == GlobalStringKey::Empty)
{
return GuiInstancePropertyInfo::CollectionWithParent(description::GetTypeDescriptor<GuiTabPage>());
}
return BASE_TYPE::GetPropertyType(propertyInfo);
}
Ptr<workflow::WfStatement> AssignParameters(const TypeInfo& typeInfo, GlobalStringKey variableName, ArgumentMap& arguments, collections::List<WString>& errors)override
{
auto block = MakePtr<WfBlockStatement>();
FOREACH_INDEXER(GlobalStringKey, prop, index, arguments.Keys())
{
const auto& values = arguments.GetByIndex(index);
if (prop == GlobalStringKey::Empty)
{
auto value = values[0].expression;
auto type = values[0].type;
Ptr<WfExpression> expr;
if (type->CanConvertTo(description::GetTypeDescriptor<GuiTabPage>()))
{
auto refControl = MakePtr<WfReferenceExpression>();
refControl->name.value = variableName.ToString();
auto refCreatePage = MakePtr<WfMemberExpression>();
refCreatePage->parent = refControl;
refCreatePage->name.value = L"CreatePage";
auto refMinus1 = MakePtr<WfIntegerExpression>();
refMinus1->value.value = L"-1";
auto call = MakePtr<WfCallExpression>();
call->function = refCreatePage;
call->arguments.Add(value);
call->arguments.Add(refMinus1);
expr = call;
}
if (expr)
{
auto stat = MakePtr<WfExpressionStatement>();
stat->expression = expr;
block->statements.Add(stat);
}
}
}
if (block->statements.Count() > 0)
{
return block;
}
return BASE_TYPE::AssignParameters(typeInfo, variableName, arguments, errors);
}
};
#undef BASE_TYPE
/***********************************************************************
GuiTabPageInstanceLoader
***********************************************************************/
class GuiTabPageInstanceLoader : public Object, public IGuiInstanceLoader
{
protected:
GlobalStringKey typeName;
public:
GuiTabPageInstanceLoader()
{
typeName = GlobalStringKey::Get(description::TypeInfo<GuiTabPage>::content.typeName);
}
GlobalStringKey GetTypeName()override
{
return typeName;
}
void GetPropertyNames(const TypeInfo& typeInfo, collections::List<GlobalStringKey>& propertyNames)override
{
propertyNames.Add(GlobalStringKey::Empty);
}
Ptr<GuiInstancePropertyInfo> GetPropertyType(const PropertyInfo& propertyInfo)override
{
if (propertyInfo.propertyName == GlobalStringKey::Empty)
{
auto info = GuiInstancePropertyInfo::Collection();
info->acceptableTypes.Add(description::GetTypeDescriptor<GuiControl>());
info->acceptableTypes.Add(description::GetTypeDescriptor<GuiGraphicsComposition>());
return info;
}
return IGuiInstanceLoader::GetPropertyType(propertyInfo);
}
Ptr<workflow::WfStatement> AssignParameters(const TypeInfo& typeInfo, GlobalStringKey variableName, ArgumentMap& arguments, collections::List<WString>& errors)override
{
auto block = MakePtr<WfBlockStatement>();
FOREACH_INDEXER(GlobalStringKey, prop, index, arguments.Keys())
{
const auto& values = arguments.GetByIndex(index);
if (prop == GlobalStringKey::Empty)
{
auto value = values[0].expression;
auto type = values[0].type;
Ptr<WfExpression> expr;
if (type->CanConvertTo(description::GetTypeDescriptor<GuiControl>()))
{
auto refBoundsComposition = MakePtr<WfMemberExpression>();
refBoundsComposition->parent = value;
refBoundsComposition->name.value = L"BoundsComposition";
expr = refBoundsComposition;
}
else if (type->CanConvertTo(description::GetTypeDescriptor<GuiGraphicsComposition>()))
{
expr = value;
}
if (expr)
{
auto refControl = MakePtr<WfReferenceExpression>();
refControl->name.value = variableName.ToString();
auto refContainerComposition = MakePtr<WfMemberExpression>();
refContainerComposition->parent = refControl;
refContainerComposition->name.value = L"ContainerComposition";
auto refAddChild = MakePtr<WfMemberExpression>();
refAddChild->parent = refContainerComposition;
refAddChild->name.value = L"AddChild";
auto call = MakePtr<WfCallExpression>();
call->function = refAddChild;
call->arguments.Add(expr);
auto stat = MakePtr<WfExpressionStatement>();
stat->expression = call;
block->statements.Add(stat);
}
}
}
if (block->statements.Count() > 0)
{
return block;
}
return nullptr;
}
};
/***********************************************************************
Initialization
***********************************************************************/
void LoadTabControls(IGuiInstanceLoaderManager* manager)
{
manager->SetLoader(new GuiTabInstanceLoader);
manager->SetLoader(new GuiTabPageInstanceLoader);
}
}
}
}
#endif | [
"[email protected]"
] | |
2371c92a7c5ce4961f5c628f2d9662a24d339777 | 1ca041e8cdb3065c61e9c51e6fa66d2851ebe35d | /2D Local Multiplayer Game/Engine/Scene.cpp | 00801e45de8a5b2e00c158496b24b688a65b9a70 | [] | no_license | Zeploc/2D-Local-Multiplayer-Game | 995e2df94c08520d8a2e2552050cb30aafe1ff7b | 3fd1219397e75d29139022c11e1c33524581926f | refs/heads/master | 2021-08-06T17:14:59.296221 | 2018-10-25T05:03:38 | 2018-10-25T05:03:38 | 141,252,466 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,967 | cpp | //
// Bachelor of Software Engineering
// Media Design School
// Auckland
// New Zealand
//
// (c) 2005 - 2018 Media Design School
//
// File Name : Scene.cpp
// Description : main implementation for Scene
// Author : Alex Coultas
// Mail : [email protected]
//
// Library Includes //
// OpenGL Library Includes //
// Engine Includes //
#include "Input.h"
#include "Camera.h"
#include "UIText.h"
#include "Shader.h"
#include "Plane.h"
#include "UIButton.h"
// Local Includes //
// This Includes //
#include "Scene.h"
/************************************************************
#--Description--#: Constructor function
#--Author--#: Alex Coultas
#--Parameters--#: Takes contructor values
#--Return--#: NA
************************************************************/
Scene::Scene(std::string sSceneName)
: SceneName(sSceneName)
{
}
/************************************************************
#--Description--#: Destructor function
#--Author--#: Alex Coultas
#--Parameters--#: NA
#--Return--#: NA
************************************************************/
Scene::~Scene()
{
DeleteScene();
}
/************************************************************
#--Description--#: Delete all entities in scene
#--Author--#: Alex Coultas
#--Parameters--#: NA
#--Return--#: NA
************************************************************/
void Scene::DeleteScene()
{
for (auto it : Entities)
{
it = nullptr;
}
for (auto it : UIElements)
{
it = nullptr;
}
}
/************************************************************
#--Description--#: Render Scene to the screen
#--Author--#: Alex Coultas
#--Parameters--#: NA
#--Return--#: NA
************************************************************/
void Scene::RenderScene()
{
glEnable(GL_DEPTH_TEST);
//glEnable(GL_CULL_FACE);
for (unsigned int i = 0; i < Entities.size(); i++)
{
//if (it->transform.Scale.x < 0) // || it->transform.Scale.y < 0 || it->transform.Scale.z < 0)
//{
// glCullFace(GL_FRONT); // Switches to front culling if scale is negative
//}
//else glCullFace(GL_BACK); // Cull the Back faces as per normal
Entities[i]->DrawEntity();
}
glDisable(GL_DEPTH_TEST);
//glDisable(GL_CULL_FACE);
for (auto it : UIElements)
{
it->DrawUIElement();
}
}
/************************************************************
#--Description--#: Add entity to scene
#--Author--#: Alex Coultas
#--Parameters--#: Entity to add
#--Return--#: NA
************************************************************/
void Scene::AddEntity(std::shared_ptr<Entity> _Entity, bool IsInitial)
{
Entities.push_back(_Entity);
_Entity->SetInitialEntity(IsInitial);
}
/************************************************************
#--Description--#: Destroys entity
#--Author--#: Alex Coultas
#--Parameters--#: Entity to destroy
#--Return--#: NA
************************************************************/
void Scene::DestroyEntity(std::shared_ptr<Entity> _Entity)
{
_Entity->SetActive(false);
if (_Entity->IsInitialEntity())
{
DestroyedEntities.push_back(_Entity);
}
else
{
EntitiesToBeDestroyed.push_back(_Entity);
}
_Entity->OnDestroy();
// Reset all but this option?
//EntDetroy.reset();
}
/************************************************************
#--Description--#: Adds UI element
#--Author--#: Alex Coultas
#--Parameters--#: UI Element to add
#--Return--#: NA
************************************************************/
void Scene::AddUIElement(std::shared_ptr<UIElement> Element)
{
UIElements.push_back(Element);
}
/************************************************************
#--Description--#: Adds UI Text element
#--Author--#: Alex Coultas
#--Parameters--#: UI Text Element to add
#--Return--#: NA
************************************************************/
void Scene::AddUITextElement(std::shared_ptr<UIText> Element)
{
UIElements.push_back(Element);
}
/************************************************************
#--Description--#: Adds UI Text element
#--Author--#: Alex Coultas
#--Parameters--#: UI Text Element paramters to add
#--Return--#: NA
************************************************************/
void Scene::AddUITextElement(glm::vec2 _Position, float _fRotation, glm::vec4 _Colour, std::string _sText, std::string font, int iPSize, Utils::EANCHOR _Anchor)
{
std::shared_ptr<UIText> NewElement = std::make_shared<UIText>(_Position, _fRotation, _Colour, _sText, font, iPSize, _Anchor);
UIElements.push_back(NewElement);
}
/************************************************************
#--Description--#: Destroys UI Text element
#--Author--#: Alex Coultas
#--Parameters--#: UI Text Element paramters to destroy
#--Return--#: NA
************************************************************/
void Scene::DestroyUIElement(std::shared_ptr<UIElement> _Element)
{
UIElementsToBeDestroyed.push_back(_Element);
_Element->SetActive(false);
}
/************************************************************
#--Description--#: Updated every frame
#--Author--#: Alex Coultas
#--Parameters--#: NA
#--Return--#: NA
************************************************************/
void Scene::Update()
{
for (int i = 0; i < Entities.size(); i++)
{
if (Entities[i])
Entities[i]->BaseUpdate();
}
for (int i = 0; i < UIElements.size(); i++)
{
if (UIElements[i])
UIElements[i]->BaseUpdate();
}
for (auto& UIDestroy : UIElementsToBeDestroyed)
{
for (auto it = UIElements.begin(); it != UIElements.end(); ++it)
{
if (*it == UIDestroy)
{
UIElements.erase(it);
break;
}
}
UIDestroy.reset();
}
if (!UIElementsToBeDestroyed.empty()) UIElementsToBeDestroyed.clear();
for (auto& EDestroy : EntitiesToBeDestroyed)
{
for (auto it = Entities.begin(); it != Entities.end(); ++it)
{
if (*it == EDestroy)
{
Entities.erase(it);
break;
}
}
EDestroy.reset();
}
if (!EntitiesToBeDestroyed.empty()) EntitiesToBeDestroyed.clear();
}
void Scene::OnLoadScene()
{
if (!bIsPersistant)
{
for (auto& EntDestroy : DestroyedEntities)
{
Entities.push_back(EntDestroy);
}
DestroyedEntities.clear();
DestroyAllNonInitialEntities();
for (auto& Ent : Entities)
{
Ent->Reset();
}
}
}
/************************************************************
#--Description--#: == operator overloading
#--Author--#: Alex Coultas
#--Parameters--#: Comparing scene
#--Return--#: NA
************************************************************/
bool Scene::operator==(const Scene & rhs) const
{
if (SceneName == rhs.SceneName) return true;
return false;
}
void Scene::DestroyAllNonInitialEntities()
{
auto EndIt = Entities.end();
for (auto it = Entities.begin(); it != EndIt; ++it)
{
if (!(*it)->IsInitialEntity())
{
b2Body* EntBody = (*it)->body;
if (EntBody) EntBody->GetWorld()->DestroyBody(EntBody);
it = Entities.erase(it);
it--;
EndIt = Entities.end();
}
}
}
| [
"[email protected]"
] | |
7757f08902bb6a323d404291de89064dba1b0a2a | c762b42f95987426c223b9d292b264ebad2aad98 | /Zip/Zipper.cpp | 275543319fcfdb997c407efe83ea077f0d1a04c9 | [] | no_license | jhbaessi/BDPlayground | 9cd09d7b38bbea5ab397e8831e40cfd7def2c7e1 | 4f8b3266dc06faa2164e62affb676a2f33d3675c | refs/heads/master | 2020-04-29T01:18:18.059865 | 2019-03-15T01:38:30 | 2019-03-15T01:38:53 | 175,725,651 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,783 | cpp | #include "stdafx.h"
#include "Zipper.h"
#include <windows.h>
#include <direct.h>
#include <io.h>
#include <fstream>
using namespace std;
#define DIRECTORY_SEPARATOR '\\'
#define READ_BUFFER_SIZE (1024)
bool Zipper::Zip(const string &source_path, const string &zip_file_path, const string &password/* = string()*/)
{
vector<pair<string, uint32_t>> entry = GetEntry(source_path);
if (entry.empty())
{
printf("empty directory\n");
return false;
}
int errorp;
// create a new archive
// ZIP_CHECKCONS : Perform additional stricter consistency checks on the archive, and error if they fail.
// ZIP_CREATE : Create the archive if it does not exist.
// ZIP_EXCL : Error if archive already exists.
// ZIP_TRUNCATE : If archive exists, ignore its current contents. In other words, handle it the same way as an empty archive.
// ZIP_RDONLY : Open archive in read-only mode.
zip_t *archive = zip_open(zip_file_path.c_str(), ZIP_CREATE | ZIP_TRUNCATE, &errorp);
if (archive == nullptr)
{
printf("failed to open: %s\n", zip_strerror(archive));
return false;
}
for (auto file : entry)
{
if (file.second & FILE_ATTRIBUTE_DIRECTORY)
AddDir(archive, source_path + DIRECTORY_SEPARATOR + file.first, file.first);
else
AddFile(archive, source_path + DIRECTORY_SEPARATOR + file.first, file.first, password);
}
// close
if (archive && zip_close(archive) < 0)
{
printf("failed to close the archive: %s\n", zip_strerror(archive));
return false;
}
return true;
}
bool Zipper::Unzip(const string &zip_file_path, const string &target_path, const string &password/* = string()*/)
{
if (!IsDirExists(target_path))
{
if (_mkdir(target_path.c_str()) != 0)
{
printf("failed to create the directory: %s\n", target_path.c_str());
return false;
}
}
int errorp;
zip_t *archive = zip_open(zip_file_path.c_str(), 0, &errorp);
if (archive == nullptr)
{
printf("failed to open: %s\n", zip_file_path.c_str());
return false;
}
if (!password.empty())
{
if (zip_set_default_password(archive, password.c_str()) < 0)
printf("failed to set password: %s\n", zip_strerror(archive));
}
zip_stat_t stat;
for (zip_int64_t i = 0; i < zip_get_num_entries(archive, 0); i++)
{
if (zip_stat_index(archive, i, 0, &stat) == 0)
{
printf("=================================================\n");
printf("name: %s\n", stat.name);
printf("index: %llu\n", stat.index);
printf("size: %llu / %llu\n", stat.comp_size, stat.size);
}
string name(stat.name);
if (name.back() == '/')
{
// create the directory
string dir_path = target_path + DIRECTORY_SEPARATOR + stat.name;
if (_mkdir(dir_path.c_str()) != 0)
printf("failed to create the directory: %s\n", dir_path.c_str());
}
else
{
// create the file
zip_file_t *file = zip_fopen_index(archive, i, 0);
if (file == nullptr)
{
printf("failed to open the zip source file: %s\n", zip_strerror(archive));
continue;
}
string out_path = target_path + DIRECTORY_SEPARATOR + stat.name;
ofstream out_file(out_path.c_str(), ofstream::binary);
zip_uint64_t offset = 0;
char read_buffer[READ_BUFFER_SIZE];
while (offset < stat.size)
{
zip_int64_t read_byte = zip_fread(file, read_buffer, READ_BUFFER_SIZE);
if (read_byte < 0)
{
printf("failed to read a data: %s\n", stat.name);
break;
}
out_file.write(read_buffer, read_byte);
offset += read_byte;
}
out_file.close();
if (zip_fclose(file) != 0)
printf("failed to close the zip source file: %s\n", zip_strerror(archive));
}
}
// close
if (archive && zip_close(archive) < 0)
{
printf("failed to close the archive: %s\n", zip_strerror(archive));
return false;
}
return true;
}
vector<zip_stat_t> Zipper::GetZipEntry(const std::string &path)
{
int errorp;
std::vector<zip_stat_t> entry;
zip_t *archive = zip_open(path.c_str(), 0, &errorp);
if (archive == nullptr)
{
printf("failed to open: %s\n", path.c_str());
}
else
{
for (zip_int64_t i = 0; i < zip_get_num_entries(archive, 0); i++)
{
zip_stat_t stat;
if (zip_stat_index(archive, i, 0, &stat) == 0)
entry.push_back(stat);
}
}
return entry;
}
bool Zipper::AddFile(zip_t *archive, const string &path, const string &name, const string &password/* = string()*/)
{
if (archive == nullptr) return false;
if (path.empty() || name.empty()) return false;
zip_source_t *source = zip_source_file(archive, path.c_str(), 0, 0);
if (source == nullptr)
{
printf("failed to create zip source from '%s': %s\n", name.c_str(), zip_strerror(archive));
return false;
}
zip_int64_t index = zip_file_add(archive, name.c_str(), source, ZIP_FL_OVERWRITE | ZIP_FL_ENC_UTF_8);
if (index < 0)
{
zip_source_free(source);
printf("%s\n", zip_strerror(archive));
return false;
}
if (!password.empty())
{
if (zip_file_set_encryption(archive, index, ZIP_EM_AES_128, password.c_str()) < 0)
printf("failed to set password: %s\n", zip_strerror(archive));
}
printf("added file: %s\n", name.c_str());
return true;
}
bool Zipper::AddDir(zip_t *archive, const string &path, const string &name, const string &password/* = string()*/)
{
if (archive == nullptr) return false;
if (path.empty() || name.empty()) return false;
if (zip_dir_add(archive, name.c_str(), ZIP_FL_ENC_UTF_8) < 0)
{
printf("failed to add the directory: %s\n", zip_strerror(archive));
return false;
}
printf("added dir: %s\n", name.c_str());
vector<pair<string, uint32_t>> entry = GetEntry(path);
for (auto file : entry)
{
if (file.second & FILE_ATTRIBUTE_DIRECTORY)
AddDir(archive, path + DIRECTORY_SEPARATOR + file.first, name + DIRECTORY_SEPARATOR + file.first);
else
AddFile(archive, path + DIRECTORY_SEPARATOR + file.first, name + DIRECTORY_SEPARATOR + file.first, password);
}
return true;
}
vector<pair<string, uint32_t>> Zipper::GetEntry(const string &path)
{
vector<pair<string, uint32_t>> entry;
// get all files in the source path
HANDLE hFind = INVALID_HANDLE_VALUE;
WIN32_FIND_DATA ffd;
// convert to wide char array
wstring search_pattern = wstring(path.begin(), path.end()) + L"\\*";
// get files in the path
hFind = FindFirstFile(search_pattern.c_str(), &ffd);
if (hFind != INVALID_HANDLE_VALUE)
{
do
{
if (wcscmp(L".", ffd.cFileName) == 0 || wcscmp(L"..", ffd.cFileName) == 0) continue;
entry.push_back(
make_pair(string(ffd.cFileName, ffd.cFileName + wcslen(ffd.cFileName))
, ffd.dwFileAttributes));
} while (FindNextFile(hFind, &ffd) != 0);
}
return entry;
}
bool Zipper::IsDirExists(const std::string &path)
{
if (_access(path.c_str(), 0) == 0)
{
struct stat status;
stat(path.c_str(), &status);
return (status.st_mode & S_IFDIR) != 0;
}
return false;
} | [
"[email protected]"
] | |
381d3155fe2fa5e42d085f42f954abc93603590f | ae3ee095b30d1ec008bca950baf556933a175c38 | /main/trajectories/trajectories.h | db98a165916ef43856b153bd13b919efd0d096c0 | [] | no_license | evilfer/trajectories_qt | e7fd2e8939cd43c2681ef48acef54e5c6cd1a949 | b5c5db61c8bdb4f84e171384174c26a570faeff9 | refs/heads/master | 2021-05-28T07:33:12.376733 | 2014-03-26T23:51:48 | 2014-03-26T23:51:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,199 | h | /*
Copyright (C) 2010-2013 Eloy David Villasclaras Fernandez.
[email protected]
This file is part of Trajectories.
Trajectories is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Trajectories 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 Trajectories. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TRAJECTORIES_H
#define TRAJECTORIES_H
#include <QObject>
#include <map>
#include "html5bridgeviewer/cppjavascriptbridgelistener.h"
#include "solarsystemstatemanager.h"
class Trajectories : public bridge::CppJavascriptBridgeListener {
SolarSystemStateManager * solarSystemManager_m;
public:
Trajectories();
~Trajectories();
virtual void processCall(QString & op, QVariantMap & data, QVariantMap &result);
};
#endif // TRAJECTORIES_H
| [
"[email protected]"
] | |
183f889039c0b58a1493c8ea37dd96f6e4113f78 | ea401c3e792a50364fe11f7cea0f35f99e8f4bde | /hackathon/zhi/neurontracing_region_neuronchaser/neurontracing_region_neuronchaser_plugin.h | 18ac3aaadb5d774bb670cc8899ddf1a7f245f817 | [
"MIT"
] | 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 | 789 | h | /* neurontracing_region_neuronchaser_plugin.h
* This is a test plugin, you can use it as a demo.
* 2015-12-15 : by Zhi Zhou
*/
#ifndef __NEURONTRACING_REGION_NEURONCHASER_PLUGIN_H__
#define __NEURONTRACING_REGION_NEURONCHASER_PLUGIN_H__
#include <QtGui>
#include <v3d_interface.h>
class neurontracing_region_neuronchaser : public QObject, public V3DPluginInterface2_1
{
Q_OBJECT
Q_INTERFACES(V3DPluginInterface2_1);
public:
float getPluginVersion() const {return 1.1f;}
QStringList menulist() const;
void domenu(const QString &menu_name, V3DPluginCallback2 &callback, QWidget *parent);
QStringList funclist() const ;
bool dofunc(const QString &func_name, const V3DPluginArgList &input, V3DPluginArgList &output, V3DPluginCallback2 &callback, QWidget *parent);
};
#endif
| [
"[email protected]"
] | |
987915ce717baeb14470e87d576ce5365c0b1827 | 6e189b79daf85591f371d1d92057773a429f623c | /q5.cpp | 70194b6c782e5eb9693c601a186cadb06a7691ac | [] | no_license | ishon19/Arrays | 656f036005c0750e46081a5dc0ef2d9a794aaa4e | 580dfd184f0de159e84f51172ad1f6d3e753909a | refs/heads/master | 2021-01-10T22:08:27.133721 | 2014-10-20T12:31:58 | 2014-10-20T12:31:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 667 | cpp | #include<iostream>
#include<string.h>
using namespace std;
int main()
{
char arr[]="happydiwali";
int char_count[256];
char result[strlen(arr)];
memset(char_count , 0 , sizeof(char_count));
for(int i=0 ; arr[i]; ++i)
{
++char_count[arr[i]];
}
for(int i=0; i<=255; ++i)
{
char_count[i]+=char_count[i-1];
}
for(int i=0; arr[i]; ++i)
{
result[char_count[arr[i]]-1] = arr[i];
--char_count[arr[i]];
}
for(int i=0; arr[i]; ++i)
{
arr[i] = result[i];
}
cout<<"\n Sorted Array is: ";
for(int i=0; i<=strlen(arr); ++i)
{
cout<<arr[i];
}
}
| [
"[email protected]"
] | |
715fc8f81adbb1147e6efa52c90dcb8cfd0c0b16 | c583a5fd60d8497c82c2864e5dec2d1b0853f3b1 | /0071-Simplify_Path/main-3.cpp | f7a3b328253d0cbabac05e232535f53930b957b9 | [] | no_license | oliver-zeng/leetcode | 401c9455c73cfe198b1d947407596aaa4d61f6fe | d98fbefb9c6fc0dc78da3cfabf7906f3fa712102 | refs/heads/master | 2020-12-19T19:17:45.522346 | 2020-06-04T12:25:03 | 2020-06-04T12:25:03 | 235,826,235 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,252 | cpp | class Solution {
public:
string simplifyPath(string path) {
// 避免不以'/'结尾,导致最后一个内容拿不到
// "/a//b////c/d//././/.."
path += "/";
int sz = path.size();
int left = 0, right = 1;
stack<string> st;
while (right < sz) {
if (path[right] != '/') {
right++;
continue;
}
string str = path.substr(left+1, right - left - 1);
left = right;
right++;
if (str == "." || str == "")
continue;
// 这里st.empty()必须写在里面,否则"/../"会算作else,走进else push进st
else if (str == "..") {
if (!st.empty())
st.pop();
continue;
} else
st.push(str);
}
// 如果为空也是有路径的,为"/"
if (st.empty())
return "/";
string res;
while (!st.empty()) {
// 每次拼接一个新的串,前段是要拼接的新内容,后段是之前的串,这样就变成了往前插
res = "/" + st.top() + res;
st.pop();
}
return res;
}
}; | [
"[email protected]"
] | |
f89d6bc77ad5f304133b45b572e70036d7a74140 | 60b8b4a2c561c4066e22c045b2b68c6ccd509682 | /cpp_db/driver_registry.cpp | 3f6f92f7e35c400510e2171c12adc19028aa64c6 | [] | no_license | JohannAnhofer/cpp_db | a481686b014136f7a08d0961cefe7a0c5500173e | 93e7e4d8f23444b1b5d09e8c41e6bf344f5e7fed | refs/heads/master | 2021-06-02T13:38:49.132356 | 2019-11-19T20:39:25 | 2019-11-19T20:39:25 | 15,143,743 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 618 | cpp | #include "driver_factory.h"
#include "driver_interface.h"
#include "driver_factory.h"
namespace cpp_db
{
using driver_creator_function = std::function<std::unique_ptr<driver_interface>()>;
namespace driver_registry
{
void register_driver(const std::string &name, driver_creator_function creator)
{
driver_factory::instance().register_driver(name, creator);
}
void unregister_driver(const std::string &name)
{
driver_factory::instance().unregister_driver(name);
}
std::shared_ptr<driver_interface> make_driver(const std::string &name)
{
return driver_factory::instance().create_driver(name);
}
}
}
| [
"[email protected]"
] | |
09cc65e8aede85065bb90ae05c2c34922da61178 | 1218876456e9b148d2a3b8c990dbf7afce6fef05 | /oop 7/worker.h | 435ec0288ddcfe220a31c561b6e9d9bb58d706bc | [] | no_license | Barsik-sus/oop-7 | 33c462dd599adb56d2d45383a2a1662b7a63ede3 | 2f9317a8fc9c117ba3a7df6b481bce2e739423b1 | refs/heads/master | 2022-07-13T06:23:23.142875 | 2019-11-24T17:37:05 | 2019-11-24T17:37:05 | null | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 323 | h | #pragma once
#include "pers.h"
class worker :
public pers
{
std::string specialty; // название специальности
int depart; // номер цеха
public:
worker(std::string specialty, int depart);
void set_specialty(std::string specialty);
void set_depart(int depart);
void print_info();
};
| [
"[email protected]"
] | |
2d4e346f9872c2eeecc3035c5168d8e58e726f20 | 9291fb1161991259b8077f8f9a850867d5464770 | /src/dingoo.cpp | cfd6b08348ee7c4d5345d5dbee58f2acdbb2fe03 | [] | no_license | goldmojo/uae4all | 1d67266e1984810645281e07dc21021ad0441da2 | 9988f9924a5da4d21fde414b8d531301f8b1076c | refs/heads/master | 2023-01-07T11:29:49.356720 | 2020-11-11T15:11:34 | 2020-11-11T15:11:34 | 255,284,950 | 7 | 2 | null | 2020-04-13T09:35:06 | 2020-04-13T09:35:05 | null | UTF-8 | C++ | false | false | 5,515 | cpp | #include <stdlib.h>
#include <stdio.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/soundcard.h>
#include <sys/ioctl.h>
/* Define this to the CPU frequency */
#define DEFAULT_CPU_FREQ 336000000 /* CPU clock: 336 MHz */
#define CFG_EXTAL 12000000 /* EXT clock: 12 Mhz */
// SDRAM Timings, unit: ns
#define SDRAM_TRAS 45 /* RAS# Active Time */
#define SDRAM_RCD 20 /* RAS# to CAS# Delay */
#define SDRAM_TPC 20 /* RAS# Precharge Time */
#define SDRAM_TRWL 7 /* Write Latency Time */
#define SDRAM_TREF 15625 /* Refresh period: 4096 refresh cycles/64ms */
/* Clock Control Register */
#define CPM_CPCCR_I2CS (1 << 31)
#define CPM_CPCCR_CLKOEN (1 << 30)
#define CPM_CPCCR_UCS (1 << 29)
#define CPM_CPCCR_UDIV_BIT 23
#define CPM_CPCCR_UDIV_MASK (0x3f << CPM_CPCCR_UDIV_BIT)
#define CPM_CPCCR_CE (1 << 22)
#define CPM_CPCCR_PCS (1 << 21)
#define CPM_CPCCR_LDIV_BIT 16
#define CPM_CPCCR_LDIV_MASK (0x1f << CPM_CPCCR_LDIV_BIT)
#define CPM_CPCCR_MDIV_BIT 12
#define CPM_CPCCR_MDIV_MASK (0x0f << CPM_CPCCR_MDIV_BIT)
#define CPM_CPCCR_PDIV_BIT 8
#define CPM_CPCCR_PDIV_MASK (0x0f << CPM_CPCCR_PDIV_BIT)
#define CPM_CPCCR_HDIV_BIT 4
#define CPM_CPCCR_HDIV_MASK (0x0f << CPM_CPCCR_HDIV_BIT)
#define CPM_CPCCR_CDIV_BIT 0
#define CPM_CPCCR_CDIV_MASK (0x0f << CPM_CPCCR_CDIV_BIT)
/* I2S Clock Divider Register */
#define CPM_I2SCDR_I2SDIV_BIT 0
#define CPM_I2SCDR_I2SDIV_MASK (0x1ff << CPM_I2SCDR_I2SDIV_BIT)
/* PLL Control Register */
#define CPM_CPPCR_PLLM_BIT 23
#define CPM_CPPCR_PLLM_MASK (0x1ff << CPM_CPPCR_PLLM_BIT)
#define CPM_CPPCR_PLLN_BIT 18
#define CPM_CPPCR_PLLN_MASK (0x1f << CPM_CPPCR_PLLN_BIT)
#define CPM_CPPCR_PLLOD_BIT 16
#define CPM_CPPCR_PLLOD_MASK (0x03 << CPM_CPPCR_PLLOD_BIT)
#define CPM_CPPCR_PLLS (1 << 10)
#define CPM_CPPCR_PLLBP (1 << 9)
#define CPM_CPPCR_PLLEN (1 << 8)
#define CPM_CPPCR_PLLST_BIT 0
#define CPM_CPPCR_PLLST_MASK (0xff << CPM_CPPCR_PLLST_BIT)
static volatile unsigned long *jz_cpmregl;
static volatile unsigned short *jz_emcregs;
static int sdram_convert(unsigned int pllin,unsigned int *sdram_freq)
{
register unsigned int ns, tmp;
ns = 1000000000 / pllin;
/* Set refresh registers */
tmp = SDRAM_TREF/ns;
tmp = tmp/64 + 1;
if (tmp > 0xff) tmp = 0xff;
*sdram_freq = tmp;
return 0;
}
static void pll_init(unsigned int clock)
{
register unsigned int cfcr, plcr1;
unsigned int sdramclock = 0;
int n2FR[33] = {
0, 0, 1, 2, 3, 0, 4, 0, 5, 0, 0, 0, 6, 0, 0, 0,
7, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0,
9
};
int div[5] = {1, 3, 3, 3, 3}; /* divisors of I:S:P:L:M */
int nf, pllout2;
cfcr = CPM_CPCCR_CLKOEN |
(n2FR[div[0]] << CPM_CPCCR_CDIV_BIT) |
(n2FR[div[1]] << CPM_CPCCR_HDIV_BIT) |
(n2FR[div[2]] << CPM_CPCCR_PDIV_BIT) |
(n2FR[div[3]] << CPM_CPCCR_MDIV_BIT) |
(n2FR[div[4]] << CPM_CPCCR_LDIV_BIT);
pllout2 = (cfcr & CPM_CPCCR_PCS) ? clock : (clock / 2);
/* Init UHC clock */
jz_cpmregl[0x6C>>2] = pllout2 / 48000000 - 1;
nf = clock * 2 / CFG_EXTAL;
plcr1 = ((nf - 2) << CPM_CPPCR_PLLM_BIT) | /* FD */
(0 << CPM_CPPCR_PLLN_BIT) | /* RD=0, NR=2 */
(0 << CPM_CPPCR_PLLOD_BIT) | /* OD=0, NO=1 */
(0x20 << CPM_CPPCR_PLLST_BIT) | /* PLL stable time */
CPM_CPPCR_PLLEN; /* enable PLL */
/* init PLL */
jz_cpmregl[0] = cfcr;
jz_cpmregl[0x10>>2] = plcr1;
sdram_convert(clock,&sdramclock);
if(sdramclock > 0)
{
jz_emcregs[0x8C>>1] = sdramclock;
jz_emcregs[0x88>>1] = sdramclock;
}
}
void dingoo_set_clock(unsigned int mhz)
{
unsigned long jz_dev=open("/dev/mem", O_RDWR);
volatile unsigned long *jz_emcregl;
jz_cpmregl=(unsigned long *)mmap(0, 0x80, PROT_READ|PROT_WRITE, MAP_SHARED, jz_dev, 0x10000000);
jz_emcregl=(unsigned long *)mmap(0, 0x90, PROT_READ|PROT_WRITE, MAP_SHARED, jz_dev, 0x13010000);
jz_emcregs=(unsigned short *)jz_emcregl;
if (mhz > 430) mhz = 430;
if (mhz < 200) mhz = 200;
pll_init(mhz*1000000);
munmap((void *)jz_cpmregl, 0x80);
munmap((void *)jz_emcregl, 0x90);
close(jz_dev);
}
unsigned int dingoo_get_clock(void)
{
unsigned long dev=open("/dev/mem", O_RDWR);
volatile unsigned long *jz=(unsigned long *)mmap(0, 0x80, PROT_READ|PROT_WRITE, MAP_SHARED, dev, 0x10000000);
unsigned int plcr1=jz[0x10>>2];
int nf=2+(plcr1 >> CPM_CPPCR_PLLM_BIT);
munmap((void *)jz, 0x80);
close(dev);
return 2+(nf*6);
}
void dingoo_set_brightness(int value)
{
unsigned long dev=open("/proc/jz/lcd_backlight", O_RDWR);
if (dev)
{
char backlight[4];
if (value > 99) value = 99;
if (value < 0) value = 0;
snprintf(backlight, 3, "%d", value);
backlight[3]='\0';
write(dev, backlight, 4);
close(dev);
sync();
}
}
int dingoo_get_brightness(void)
{
unsigned long dev=open("/proc/jz/lcd_backlight", O_RDWR);
if (dev)
{
char backlight[4]={ 0, 0, 0, 0 };
read(dev, backlight, 4);
backlight[3]='\0';
close(dev);
return 1+atoi(backlight);
}
return 0;
}
void dingoo_set_volumen(int value)
{
unsigned long dev=open("/dev/mixer", O_WRONLY);
if (dev)
{
if (value > 100) value = 100;
if (value < 0) value = 0;
value|=(value<<8);
ioctl(dev, SOUND_MIXER_WRITE_VOLUME, &value);
close(dev);
sync();
}
}
int dingoo_get_volumen(void)
{
unsigned long dev=open("/dev/mixer", O_WRONLY);
if (dev)
{
int value=0;
ioctl(dev, SOUND_MIXER_READ_VOLUME, &value);
close(dev);
return value&0xff;
}
return 0;
}
| [
"[email protected]"
] | |
dd159ae1c92d84afbcc07be4231346d3d8e5f8bf | 2f491c23be7135826b70e5c2b2bb10ca331f03b8 | /Concurrent/Concurrent/main.cpp | f95cd903622bae3e8c5a29d7c2938cc0e4d8ce20 | [] | no_license | AnnePieter/SchoolStuff | 132f6e916d86be58a834e0e402dbcdcacd2fc8b4 | 73ab946eaa822ad7da65347285fbc63deb1637d1 | refs/heads/main | 2023-07-24T09:05:35.755294 | 2021-09-13T10:24:39 | 2021-09-13T10:24:39 | 371,488,674 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,140 | cpp | #include <iostream>
#include "mandelbrot.h"
#include "dotproduct.h"
#include "tree.h"
#include "threadpool.h"
#define Wait std::cout << "Press Enter to continue \n"; std::getLine()
int exercise = 0;
using namespace Concurrent;
int main()
{
Mandelbrot m = Mandelbrot();
while (exercise != 7)
{
char arg = ' ';
std::cout << "Welcome to my concurrency project please select the excercise you would like to execute by inputting the number associated with it: \n1. Mandelbrot single threaded \n2. Mandelbrot multithreaded.\n3. Dot product of two vectors with mutex\n4. Dot product of two vectors with atomic types.\n5. Evaluating an expression tree.\n6. Threadpool pattern\n7. Exit\nSelection: ";
std::cin >> exercise;
switch (exercise)
{
case 1:
m.mandelbrot(false);
exercise = 0;
break;
case 2:
m.mandelbrot(true);
exercise = 0;
break;
case 3:
dotproduct(false);
break;
case 4:
dotproduct(true);
break;
case 5:
tree();
break;
case 6:
threadpool();
break;
case 7:
return 0;
default:
std::cout << "Please input a number listed to continue";
}
}
return 0;
} | [
"[email protected]"
] | |
b25b3257e8270c94599f4f85dc6d217b0476e230 | 45f18f3492866be124ed64b1914813073f476fb6 | /zmq_server/ToJson.h | d11f69fc8a15b4d0c278ff509c5dd71dd72f53aa | [] | no_license | dengpanZX/matcher | 97d844c2d2795f0b8101718f8c380156abf4a3f6 | e4ba2e968d3119b0fa0e19f2838a601c9ddb630d | refs/heads/master | 2020-09-16T17:28:12.326685 | 2018-06-29T08:31:32 | 2018-06-29T08:31:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,079 | h | #pragma once
#include "O.h"
#include <iostream>
#include <queue>
#include "json/json.h"
#include <boost/property_tree/json_parser.hpp>
using namespace std;
using namespace boost::property_tree;
template <typename T>
class ToJson
{
ptree OtoJSON(O o) {
ptree root;
root.put("orderId", o.getOrderId());
root.put("orderType", o.getOrderType());
root.put("freezeAmt", o.getFreezeAmt());
root.put("cancel", o.getIsCancel());
root.put("price", o.getPrice());
root.put("quantity", o.getQantity());
root.put("symbol", o.getSymbol());
root.put("time", o.getTime());
root.put("tradeType", o.getTradeType());
root.put("userUuid", o.getUserUuid());
return root;
}
O OJson(Json::Value root)
{
O order;
if (!root["orderId"].isNull())
{
string orId = root["orderId"].asString();
order.setOrderId(orId);
}
if (!root["orderType"].isNull())
{
order.setOrderType(root["orderType"].asCString());
}
if (!root["freezeAmt"].isNull())
{
cpp_dec_float_50 freezeAmt = cpp_dec_float_50(root["freezeAmt"].asString());
order.setFreezeAmt(freezeAmt);
}
if (!root["cancel"].isNull())
{
order.setIsCancel(boost::lexical_cast<int>(root["cancel"].asString()));
}
if (!root["price"].isNull())
{
cpp_dec_float_50 price = cpp_dec_float_50(root["price"].asString());
order.setPrice(price);
}
if (!root["quantity"].isNull())
{
cpp_dec_float_50 quantity = cpp_dec_float_50(root["quantity"].asString());
order.setQuantity(quantity);
}
if (!root["symbol"].isNull())
{
order.setSymbol(root["symbol"].asCString());
}
if (!root["time"].isNull())
{
try
{
order.setTime(root["time"].asCString());
}
catch (const std::exception&)
{
order.setTime("");
}
}
if (!root["tradeType"].isNull())
{
order.setTradeType(root["tradeType"].asCString());
}
if (!root["userUuid"].isNull())
{
order.setUserUuid(root["userUuid"].asCString());
}
return order;
}
public:
ToJson() {}
string OToJson(priority_queue<O, vector<O>, T> queue) {
ptree arr , queue_redis;
while (!queue.empty()) {
arr.push_back(make_pair("", OtoJSON(queue.top())));
queue.pop();
}
queue_redis.put_child("array", arr);
stringstream s;
write_json(s, queue_redis, false);
return s.str();
}
priority_queue<O, vector<O>, T> JsonObject(string json)
{
Json::Reader readerinfo;
Json::Value root,root_;
if (!readerinfo.parse(json, root))
{
cout << (TEXT("json error!")) << endl;
}
priority_queue<O, vector<O>, T> queue;
try
{
if (!root["array"].isNull())
{
root_ = root["array"];
if (root_["orderId"].isNull())
{
for (int j = 0; j < root_.size(); j++)
{
O order = OJson(root_[j]);
queue.push(order);
}
}
else
{
O order = OJson(root_);
queue.push(order);
}
}
}
catch (const std::exception&)
{
root_ = root["array"];
for (int j = 0; j < root_.size(); j++)
{
O order = OJson(root_[j]);
queue.push(order);
}
}
return queue;
}
~ToJson(){}
};
| [
"[email protected]"
] | |
040c07ae36d48af96e762e45adba655ca9839986 | 37be9d32218cbd1c789f36a0f509526919966dbf | /src/be/opt/opt_verify.h | e76a7fd377985a4f21c4f21d378d51f1bfa27b70 | [] | no_license | Akheon23/nvopencc | 5072b3d68974e92a3e8ca92ac518ff97df4fe312 | 5676f95bbcca75610554115747bb075bf1cd16d6 | refs/heads/master | 2020-12-25T01:50:18.190179 | 2010-06-17T17:23:28 | 2010-06-17T17:23:28 | 50,400,638 | 1 | 0 | null | 2016-01-26T03:32:09 | 2016-01-26T03:32:09 | null | UTF-8 | C++ | false | false | 2,229 | h | /*
* Copyright 2005-2010 NVIDIA Corporation. All rights reserved.
*/
//-*-c++-*-
// ====================================================================
// ====================================================================
//
// Module: opt_verify.h
// $Revision: 1.2 $
// $Date: 02/11/07 23:41:56-00:00 $
// $Author: [email protected] $
// $Source: /scratch/mee/Patch0002-taketwo/kpro64-pending/be/opt/SCCS/s.opt_verify.h $
//
// ====================================================================
//
// Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of version 2 of the GNU General Public License as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it would be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
// Further, this software is distributed without any warranty that it
// is free of the rightful claim of any third person regarding
// infringement or the like. Any license provided herein, whether
// implied or otherwise, applies only to this software file. Patent
// licenses, if any, provided herein do not apply to combinations of
// this program with other software, or any other product whatsoever.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write the Free Software Foundation,
// Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, USA.
//
// Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky,
// Mountain View, CA 94043, or:
//
// http://www.sgi.com
//
// For further information regarding this notice, see:
//
// http://oss.sgi.com/projects/GenInfo/NoticeExplan
//
// ====================================================================
// ====================================================================
#ifndef opt_verify_INCLUDED
#define opt_verify_INCLUDED
#if Is_True_On
#if defined(TARG_NVISA)
extern BOOL Def_before_use(CODEREP *, const BB_NODE *);
#else
extern BOOL Def_before_use(const CODEREP *, const BB_NODE *);
#endif
#endif
#endif
| [
"asura@m4400.(none)"
] | asura@m4400.(none) |
7eadaf415a0cd440a8655656b1b931197178f1e9 | f4cfafe698191c6a72fae71850dc82878a5afc3e | /third_party/gfootball_engine/src/onthepitch/player/controller/strategies/offtheball/goalie_default.cpp | bef6fb6ddc5d530392876804359b41a52c70ae0e | [
"Unlicense",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | nczempin/gfootball | 3e9478a5a970f47de2fe59afd98951f1a52efed3 | 617e9cb6d48b4ac7187b9b3de68bd4ab44ea528e | refs/heads/master | 2020-06-01T20:21:40.815706 | 2019-07-12T21:15:16 | 2019-07-12T21:15:16 | 190,915,700 | 0 | 0 | Apache-2.0 | 2019-07-12T21:15:17 | 2019-06-08T17:22:31 | Python | UTF-8 | C++ | false | false | 14,020 | cpp | // Copyright 2019 Google LLC & Bastiaan Konings
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// written by bastiaan konings schuiling 2008 - 2015
// this work is public domain. the code is undocumented, scruffy, untested, and should generally not be used for anything important.
// i do not offer support, so don't ask. to be used for inspiration :)
#include "goalie_default.hpp"
#include "../../../../../base/geometry/triangle.hpp"
#include "../../../../../main.hpp"
GoalieDefaultStrategy::GoalieDefaultStrategy(ElizaController *controller) : Strategy(controller) {
name = "goalie default";
ballBoundForGoal_ycoord = 0.0f;
}
GoalieDefaultStrategy::~GoalieDefaultStrategy() {
}
void GoalieDefaultStrategy::RequestInput(const MentalImage *mentalImage, Vector3 &direction, float &velocity) {
// base position
float lineDistance = 10.0f; // default distance keeper stays in front of goal line
Vector3 ballPos = mentalImage->GetBallPrediction(600 + CastPlayer()->GetTimeNeededToGetToBall_ms() * 0.2f).Get2D();
Vector3 targetPos = Vector3((pitchHalfW - lineDistance) * team->GetSide(), 0, 0);
Vector3 goalPos = Vector3(pitchHalfW * team->GetSide(), 0, 0);
float maxVelocity = sprintVelocity;
if (ballPos.coords[0] * team->GetSide() > 0) { // optimization
CalculateIfBallIsBoundForGoal(mentalImage);
if (!IsBallBoundForGoal()) {
// tactical position, make goal as small as possible
maxVelocity = sprintVelocity;//walkVelocity;
// first, make line from ballPos to one post, then one to the other post, then calculate the line in between.
// this line is the line we want our goalie to be on: it splits the goal in to equal halves (in the 'ball view projection', that is)
Vector3 toPost1 = Vector3(pitchHalfW * team->GetSide(), 3.7f, 0) - ballPos;
Vector3 toPost2 = Vector3(pitchHalfW * team->GetSide(), -3.7f, 0) - ballPos;
radian angle = toPost2.GetAngle2D(toPost1);
Vector3 middle = toPost1.GetRotated2D(angle * 0.5f).GetNormalized(Vector3(team->GetSide(), 0, 0));
Line ballToGoal;
ballToGoal.SetVertex(0, ballPos);
ballToGoal.SetVertex(1, ballPos + middle);
// this line is now arbitrary length - make it so long that v2 is on the backline
// (or rather, near the backline - keeping ON the backline is dangerous; some anims may only touch the ball when it's already behind the line, which is pretty useless :p)
Line backLine;
backLine.SetVertex(0, Vector3((pitchHalfW - 0.7f) * team->GetSide(), -pitchHalfH, 0));
backLine.SetVertex(1, Vector3((pitchHalfW - 0.7f) * team->GetSide(), pitchHalfH, 0));
Vector3 intersect = ballToGoal.GetIntersectionPoint(backLine).Get2D();
intersect.coords[1] = clamp(intersect.coords[1], -3.7f, 3.7f);
ballToGoal.SetVertex(1, intersect);
float awayFromGoalOffset_m = 0.7f; // meters away from goal line (over the ballToGoal line, not straight forward)
float awayFromGoalBias = 0.3f; // factor between goal and ball
awayFromGoalBias *= NormalizedClamp(controller->GetFadingTeamPossessionAmount(), 1.0f, 1.5f);
// when opponent comes rushing in and team mates are too far away to help, come out to 'reduce goal size'
if (controller->GetFadingTeamPossessionAmount() < 1.0f) {
Player *opp = controller->GetOppTeam()->GetDesignatedTeamPossessionPlayer();
Vector3 oppPos = opp->GetPosition() + opp->GetMovement() * 0.32f;
// if opp isn't in ball control, don't use ball pos but opp pos
if (opp->HasPossession() == false) {
ballToGoal.SetVertex(0, oppPos * 0.6f + ballPos * 0.4f);
} else {
ballToGoal.SetVertex(0, oppPos * 0.4f + ballPos * 0.6f);
}
// first, calculate how close the opponent on the ball is to the goal/shooting treshold
float shootThreshold = 20.0f; // average/base value; this distance is dynamic
float oppToGoalDistance = (goalPos - oppPos).GetLength();
float oppToThresholdDistance = clamp(oppToGoalDistance - shootThreshold * NormalizedClamp(oppToGoalDistance, 0.0f, shootThreshold * 2.0f), 0.0f, pitchHalfW); // variable threshold distance
Vector3 shootingPoint = oppPos + (goalPos - oppPos).GetNormalized(0) * oppToThresholdDistance;
//SetGreenDebugPilon(shootingPoint);
// now calculate the distance between this shooting point and our closest mate
Player *mate = AI_GetClosestPlayer(team, shootingPoint, false, CastPlayer());
float mateToThresholdDistance = 99999;
if (mate) {
Vector3 matePos = mate->GetPosition() + mate->GetMovement() * 0.24f;
mateToThresholdDistance = (shootingPoint - matePos).GetLength();
}
if (mateToThresholdDistance > oppToThresholdDistance + 1.0f) { // come out, brave keeper!
awayFromGoalBias = 1.0f;
// the amount of 'come out bias' is related to how dangerous the opponent's closest mate is if they are to receive the ball.
// basically, the same as the above code, but with the secondary opponent and mate
Player *oppHelper = AI_GetClosestPlayer(controller->GetOppTeam(), goalPos, false, opp);
if (oppHelper) {
Vector3 oppHelperPosition = oppHelper->GetPosition() + oppHelper->GetMovement() * 0.32f;
// first, calculate how close the opponent helper is to the goal/shooting treshold
float helperShootThreshold = 24.0f; // average/base value; this distance is dynamic
float oppHelperToGoalDistance = (goalPos - oppHelperPosition).GetLength();
float oppHelperToThresholdDistance = clamp(oppHelperToGoalDistance - helperShootThreshold * NormalizedClamp(oppHelperToGoalDistance, 0.0f, helperShootThreshold * 2.0f), 0.0f, pitchHalfW); // variable threshold distance
Vector3 helperShootingPoint = oppHelperPosition + (goalPos - oppHelperPosition).GetNormalized(0) * oppHelperToThresholdDistance;
//SetYellowDebugPilon(helperShootingPoint);
// now calculate the distance between this shooting point and our closest mate
Player *mateHelper = AI_GetClosestPlayer(team, helperShootingPoint, false, CastPlayer());
float mateHelperToThresholdDistance = 99999;
if (mateHelper) mateHelperToThresholdDistance = (helperShootingPoint - (mateHelper->GetPosition() + mateHelper->GetMovement() * 0.24f)).GetLength();
float secondaryDistanceDiff = 0.0f;
// if this var is bigger, LESS likely to come out because of secondary danger
if (mateHelperToThresholdDistance > oppHelperToThresholdDistance) secondaryDistanceDiff = NormalizedClamp(mateHelperToThresholdDistance - oppHelperToThresholdDistance, 0.0f, 2.0f);
// also take into account the ratio between the primary opp to goal and the helper opp to goal distance
// if this var is bigger, LESS likely to come out because of secondary danger
float helperVSPrimaryDistanceRatio = 1.0f - NormalizedClamp(oppHelperToThresholdDistance / (oppToThresholdDistance + 0.0001f), 1.0f, 1.5f);
helperVSPrimaryDistanceRatio *= 0.7f; // always allow some coming out despite opp mate danger
awayFromGoalBias = clamp(1.0f - (secondaryDistanceDiff * helperVSPrimaryDistanceRatio), 0.0f, 1.0f);
}
}
} // end keeper come out code
bool applyRushOut = team->GetController()->GetEndApplyKeeperRush_ms() > match->GetActualTime_ms();
if (applyRushOut) awayFromGoalBias = 1.0f;
float distance = std::max(ballToGoal.GetLength() - 0.5f, 0.0f); // keep distance from target, we don't want to overshoot
awayFromGoalOffset_m = clamp(distance * awayFromGoalBias, awayFromGoalOffset_m, pitchHalfW); // when ball is farther away, goalie stays farther away from goal (to make runs when necessary)
// offset from goal line
targetPos = ballToGoal.GetVertex(1) + (ballToGoal.GetVertex(0) - ballToGoal.GetVertex(1)).GetNormalized(0) * awayFromGoalOffset_m;
//SetGreenDebugPilon(targetPos);
/* disabled: just rush to ball even if we probably can't make it there. this stuff doesn't work good enough (yet?)
// time we assume it will take for the ball to arrive at some point (in other words: how fast the attacker gets the ball there)
float time1_sec = (targetPos - ballToGoal.GetVertex(0)).GetLength() / sprintVelocity;
float time2_sec = (ballToGoal.GetVertex(1) - ballToGoal.GetVertex(0)).GetLength() / sprintVelocity;
//SetYellowDebugPilon(targetPos);
targetPos = CalculateBestAchievableTarget(CastPlayer(), targetPos, time1_sec, ballToGoal.GetVertex(1), time2_sec);
SetRedDebugPilon(targetPos + Vector3(0, 0, 0.1f));
*/
// when going back to goal: go slower to allow for proper body direction
float u = 0.0f;
float distanceToBallToGoalLine = ballToGoal.GetDistanceToPoint(player->GetPosition(), u);
if ((targetPos - goalPos).GetLength() < (player->GetPosition() - goalPos).GetLength() &&
distanceToBallToGoalLine < 1.0f && u > 0.0f) maxVelocity = walkVelocity;
targetPos.coords[0] = clamp(targetPos.coords[0], -pitchHalfW + 0.2f, pitchHalfW - 0.2f); // not very useful to stand behind backline
} else {
// intercept ball
maxVelocity = sprintVelocity;
Line ballToGoal;
ballToGoal.SetVertex(0, mentalImage->GetBallPrediction(10).Get2D());
float minGoalLineDist = 0.4f;
Vector3 ballOverGoalLinePos = Vector3(pitchHalfW * team->GetSide(), ballBoundForGoal_ycoord, 0);
ballOverGoalLinePos += (ballToGoal.GetVertex(0) - ballOverGoalLinePos).GetNormalized(0) * minGoalLineDist;
ballToGoal.SetVertex(1, ballOverGoalLinePos);
float u = 0.0f;
float distance = ballToGoal.GetDistanceToPoint(player->GetPosition() + player->GetMovement() * 0.05f, u);
float u_at_1sec = 0.0f;
float distance_at_1sec = ballToGoal.GetDistanceToPoint(mentalImage->GetBallPrediction(1010).Get2D(), u_at_1sec);
bool should_gk_run_towards_the_goal = false;
if (u_at_1sec > 1e-4) {
float time_to_reach_gk = u / u_at_1sec;
Vector3 ball_position_at_gk = mentalImage->GetBallPrediction(10 + 1000 * time_to_reach_gk);
if (ball_position_at_gk.coords[2] > 2.5) {
should_gk_run_towards_the_goal = true;
}
}
u = clamp(u, 0.0f, 1.0f);
if (should_gk_run_towards_the_goal) {
targetPos = ballOverGoalLinePos;
} else {
targetPos = ballToGoal.GetVertex(0) + (ballToGoal.GetVertex(1) - ballToGoal.GetVertex(0)) * u;
targetPos.coords[2] = 0.0;
targetPos.coords[0] = clamp(targetPos.coords[0], -pitchHalfW + 0.2f, pitchHalfW - 0.2f); // not very useful to stand behind line
}
}
}
direction = targetPos - player->GetPosition();
velocity = clamp(direction.GetLength() * distanceToVelocityMultiplier, idleVelocity, maxVelocity);
direction.Normalize(player->GetDirectionVec());
}
void GoalieDefaultStrategy::CalculateIfBallIsBoundForGoal(const MentalImage *mentalImage) {
ballBoundForGoal = false;
bool intersect = false;
ballBoundForGoal_ycoord = 0;
int side = team->GetSide();
float panic = 1.02f + (1.0f - (CastPlayer()->GetStat("mental_defensivepositioning") * 0.6f + CastPlayer()->GetStat("mental_vision") * 0.4f)) * 0.5f;
if (mentalImage->GetBallPrediction(4000).coords[0] * side > pitchHalfW && (player->GetPosition() - mentalImage->GetBallPrediction(250)).GetLength() < 32.0f) { // only if ball is close enough (cpu optimization)
/* 3d version
Line line;
line.SetVertex(0, mentalImage->GetBallPrediction(40));
line.SetVertex(1, mentalImage->GetBallPrediction(4000));
//line.SetVertex(1, mentalImage->GetBallPrediction(0) + match->GetBall()->GetMovement() * 800);
Triangle goal1;
goal1.SetVertex(0, Vector3((pitchHalfW - 0.0) * side, 3.7 * panic, 0));
goal1.SetVertex(1, Vector3((pitchHalfW - 0.0) * side, -3.7 * panic, 0));
goal1.SetVertex(2, Vector3((pitchHalfW - 0.0) * side, 3.7 * panic, 2.5 * panic));
goal1.SetNormals(Vector3(-side, 0, 0));
Triangle goal2;
goal2.SetVertex(0, Vector3((pitchHalfW - 0.0) * side, -3.7 * panic, 0));
goal2.SetVertex(1, Vector3((pitchHalfW - 0.0) * side, -3.7 * panic, 2.5 * panic));
goal2.SetVertex(2, Vector3((pitchHalfW - 0.0) * side, 3.7 * panic, 2.5 * panic));
goal2.SetNormals(Vector3(-side, 0, 0));
//match->SetDebugPilon(Vector3(55 * side, 3.66, 2.44));
//match->SetDebugPilon2(line.GetVertex(1));
Vector3 intersectVec;
intersect = goal1.IntersectsLine(line, intersectVec);
if (!intersect) {
intersect = goal2.IntersectsLine(line, intersectVec);
}
*/
// 2d version
Line ballToGoal;
ballToGoal.SetVertex(0, mentalImage->GetBallPrediction(0).Get2D());
ballToGoal.SetVertex(1, mentalImage->GetBallPrediction(800).Get2D());
Line goalLine;
goalLine.SetVertex(0, Vector3(pitchHalfW * side, -pitchHalfH, 0));
goalLine.SetVertex(1, Vector3(pitchHalfW * side, pitchHalfH, 0));
Vector3 intersectPoint = ballToGoal.GetIntersectionPoint(goalLine).Get2D();
if (fabs(intersectPoint.coords[1]) > 3.7 * panic) intersect = false; else intersect = true;
if (intersect) {
//SetGreenDebugPilon(intersectPoint);
ballBoundForGoal_ycoord = intersectPoint.coords[1];
ballBoundForGoal = true;
} else {
//SetGreenDebugPilon(Vector3(0, 0, -10));
}
}
}
| [
"[email protected]"
] | |
076058171d763fa0d024a491e0459ebf5e33c441 | 061348a6be0e0e602d4a5b3e0af28e9eee2d257f | /Source/Contrib/UserInterface/src/Layout/OSGLayoutConstraintsFields.h | eef1d8903051a7b7705c5c71be6c34d0497d8c50 | [] | no_license | passthefist/OpenSGToolbox | 4a76b8e6b87245685619bdc3a0fa737e61a57291 | d836853d6e0647628a7dd7bb7a729726750c6d28 | refs/heads/master | 2023-06-09T22:44:20.711657 | 2010-07-26T00:43:13 | 2010-07-26T00:43:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,497 | h | /*---------------------------------------------------------------------------*\
* OpenSG *
* *
* *
* Copyright (C) 2000-2006 by the OpenSG Forum *
* *
* www.opensg.org *
* *
* contact: David Kabala ([email protected]) *
* *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
* License *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Library General Public License as published *
* by the Free Software Foundation, version 2. *
* *
* 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 *
* Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *
* *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
* Changes *
* *
* *
* *
* *
* *
* *
\*---------------------------------------------------------------------------*/
/*****************************************************************************\
*****************************************************************************
** **
** This file is automatically generated. **
** **
** Any changes made to this file WILL be lost when it is **
** regenerated, which can become necessary at any time. **
** **
*****************************************************************************
\*****************************************************************************/
#ifndef _OSGLAYOUTCONSTRAINTSFIELDS_H_
#define _OSGLAYOUTCONSTRAINTSFIELDS_H_
#ifdef __sgi
#pragma once
#endif
#include "OSGConfig.h"
#include "OSGContribUserInterfaceDef.h"
#include "OSGFieldContainerFields.h"
#include "OSGPointerSField.h"
#include "OSGPointerMField.h"
OSG_BEGIN_NAMESPACE
class LayoutConstraints;
OSG_GEN_CONTAINERPTR(LayoutConstraints);
/*! \ingroup GrpContribUserInterfaceFieldTraits
\ingroup GrpLibOSGContribUserInterface
*/
template <>
struct FieldTraits<LayoutConstraints *> :
public FieldTraitsFCPtrBase<LayoutConstraints *>
{
private:
static DataType _type;
public:
typedef FieldTraits<LayoutConstraints *> Self;
enum { Convertible = NotConvertible };
static OSG_CONTRIBUSERINTERFACE_DLLMAPPING DataType &getType(void);
template<typename RefCountPolicy> inline
static const Char8 *getSName (void);
// static const char *getSName(void) { return "SFLayoutConstraintsPtr"; }
template<typename RefCountPolicy> inline
static const Char8 *getMName (void);
// static const char *getMName(void) { return "MFLayoutConstraintsPtr"; }
};
template<> inline
const Char8 *FieldTraits<LayoutConstraints *, 0>::getSName<RecordedRefCountPolicy>(void)
{
return "SFRecLayoutConstraintsPtr";
}
template<> inline
const Char8 *FieldTraits<LayoutConstraints *, 0>::getSName<UnrecordedRefCountPolicy>(void)
{
return "SFUnrecLayoutConstraintsPtr";
}
template<> inline
const Char8 *FieldTraits<LayoutConstraints *, 0>::getSName<WeakRefCountPolicy>(void)
{
return "SFWeakLayoutConstraintsPtr";
}
template<> inline
const Char8 *FieldTraits<LayoutConstraints *, 0>::getSName<NoRefCountPolicy>(void)
{
return "SFUnrefdLayoutConstraintsPtr";
}
template<> inline
const Char8 *FieldTraits<LayoutConstraints *, 0>::getMName<RecordedRefCountPolicy>(void)
{
return "MFRecLayoutConstraintsPtr";
}
template<> inline
const Char8 *FieldTraits<LayoutConstraints *, 0>::getMName<UnrecordedRefCountPolicy>(void)
{
return "MFUnrecLayoutConstraintsPtr";
}
template<> inline
const Char8 *FieldTraits<LayoutConstraints *, 0>::getMName<WeakRefCountPolicy>(void)
{
return "MFWeakLayoutConstraintsPtr";
}
template<> inline
const Char8 *FieldTraits<LayoutConstraints *, 0>::getMName<NoRefCountPolicy>(void)
{
return "MFUnrefdLayoutConstraintsPtr";
}
#ifndef DOXYGEN_SHOULD_SKIP_THIS
/*! \ingroup GrpContribUserInterfaceFieldSFields */
typedef PointerSField<LayoutConstraints *,
RecordedRefCountPolicy > SFRecLayoutConstraintsPtr;
/*! \ingroup GrpContribUserInterfaceFieldSFields */
typedef PointerSField<LayoutConstraints *,
UnrecordedRefCountPolicy> SFUnrecLayoutConstraintsPtr;
/*! \ingroup GrpContribUserInterfaceFieldSFields */
typedef PointerSField<LayoutConstraints *,
WeakRefCountPolicy > SFWeakLayoutConstraintsPtr;
/*! \ingroup GrpContribUserInterfaceFieldSFields */
typedef PointerSField<LayoutConstraints *,
NoRefCountPolicy > SFUncountedLayoutConstraintsPtr;
/*! \ingroup GrpContribUserInterfaceFieldMFields */
typedef PointerMField<LayoutConstraints *,
RecordedRefCountPolicy > MFRecLayoutConstraintsPtr;
/*! \ingroup GrpContribUserInterfaceFieldMFields */
typedef PointerMField<LayoutConstraints *,
UnrecordedRefCountPolicy> MFUnrecLayoutConstraintsPtr;
/*! \ingroup GrpContribUserInterfaceFieldMFields */
typedef PointerMField<LayoutConstraints *,
WeakRefCountPolicy > MFWeakLayoutConstraintsPtr;
/*! \ingroup GrpContribUserInterfaceFieldMFields */
typedef PointerMField<LayoutConstraints *,
NoRefCountPolicy > MFUncountedLayoutConstraintsPtr;
#else // these are the doxygen hacks
/*! \ingroup GrpContribUserInterfaceFieldSFields \ingroup GrpLibOSGContribUserInterface */
struct SFRecLayoutConstraintsPtr :
public PointerSField<LayoutConstraints *,
RecordedRefCountPolicy> {};
/*! \ingroup GrpContribUserInterfaceFieldSFields \ingroup GrpLibOSGContribUserInterface */
struct SFUnrecLayoutConstraintsPtr :
public PointerSField<LayoutConstraints *,
UnrecordedRefCountPolicy> {};
/*! \ingroup GrpContribUserInterfaceFieldSFields \ingroup GrpLibOSGContribUserInterface */
struct SFWeakLayoutConstraintsPtr :
public PointerSField<LayoutConstraints *,
WeakRefCountPolicy> {};
/*! \ingroup GrpContribUserInterfaceFieldSFields \ingroup GrpLibOSGContribUserInterface */
struct SFUncountedLayoutConstraintsPtr :
public PointerSField<LayoutConstraints *,
NoRefCountPolicy> {};
/*! \ingroup GrpContribUserInterfaceFieldMFields \ingroup GrpLibOSGContribUserInterface */
struct MFRecLayoutConstraintsPtr :
public PointerMField<LayoutConstraints *,
RecordedRefCountPolicy > {};
/*! \ingroup GrpContribUserInterfaceFieldMFields \ingroup GrpLibOSGContribUserInterface */
struct MFUnrecLayoutConstraintsPtr :
public PointerMField<LayoutConstraints *,
UnrecordedRefCountPolicy> {};
/*! \ingroup GrpContribUserInterfaceFieldMFields \ingroup GrpLibOSGContribUserInterface */
struct MFWeakLayoutConstraintsPtr :
public PointerMField<LayoutConstraints *,
WeakRefCountPolicy > {};
/*! \ingroup GrpContribUserInterfaceFieldMFields \ingroup GrpLibOSGContribUserInterface */
struct MFUncountedLayoutConstraintsPtr :
public PointerMField<LayoutConstraints *,
NoRefCountPolicy > {};
#endif // these are the doxygen hacks
OSG_END_NAMESPACE
#endif /* _OSGLAYOUTCONSTRAINTSFIELDS_H_ */
| [
"[email protected]"
] | |
b3b9dc6d293e99357f2f35765e97b313f7771915 | 1adbd2b461e014e49184334e9a7c78d2aeb08641 | /common/src/dbcomid.hpp | 637ef03d756d22f87606f28b6db91816616dd19b | [] | no_license | zhangshunqiu/mir2x | 0aae819750e663376fc7dea2b835cba9af7212bd | 69678adc6482e093ea0c3179d8d3b0f4e98a745f | refs/heads/master | 2021-05-09T22:38:02.398195 | 2017-12-20T23:14:31 | 2017-12-20T23:14:31 | 118,757,690 | 0 | 1 | null | 2018-01-24T11:42:46 | 2018-01-24T11:42:46 | null | UTF-8 | C++ | false | false | 4,983 | hpp | /*
* =====================================================================================
*
* Filename: dbcomid.hpp
* Created: 07/28/2017 23:03:43
* Last Modified: 08/31/2017 14:01:37
*
* Description: global constexpr _Inn_XXXXX[] declared here
* any files including this would have an identical copy of them
*
* for files only call DBCOM_XXXXID() with literal constant I hope the
* compiler should remove this copy, because which can be envaluated at
* compile time
*
* for files include this and call DBCOM_XXXXID() with string variable
* they have to keep a copy of all _Inn_XXXXXs. But that's OK since we
* only do string comparison using these copies
*
* if need to return references to entries in these _Inn_XXXXXs, use
* dbcomrecord.hpp instead, it will provide a unique copy, introduced
* by dbcomrecord.cpp (which includes this header file), then all return
* reference will point to that unique copy
*
* Version: 1.0
* Revision: none
* Compiler: gcc
*
* Author: ANHONG
* Email: [email protected]
* Organization: USTC
*
* =====================================================================================
*/
#pragma once
#include <cstdint>
#include "maprecord.hpp"
#include "itemrecord.hpp"
#include "magicrecord.hpp"
#include "monsterrecord.hpp"
namespace
{
// TODO
// should be very very very careful here
// this is an constant variable in header file
// for each unit (.cpp file) include it, there is a identical copy of it
// so between different .cpp file, never aceess pointer of this _Inn_XXXXX[]
// why I introduce such a mess?
// I want use following statement in switch/case
//
// switch(nMonsterID){
// case DBCOM_MONSTERID("鹿"):
// case DBCOM_MONSTERID("鸡"):
// case DBCOM_MONSTERID("狼"):
// default:
// }
//
// this is very useful since
// 1. don't need to think about all monster english name
// 2. don't need to assign monster ID to each type, just automatically generate one by .inc file
//
// but this need DBCOM_MONSTERID() to be ``constexpr"
// and a constexpr function implies it's an inline function
constexpr ItemRecord _Inn_ItemRecordList []
{
#include "itemrecord.inc"
};
constexpr MonsterRecord _Inn_MonsterRecordList []
{
#include "monsterrecord.inc"
};
constexpr MagicRecord _Inn_MagicRecordList []
{
#include "magicrecord.inc"
};
constexpr MapRecord _Inn_MapRecordList []
{
#include "maprecord.inc"
};
}
// constexpr function to map utf-8 string to item record id
// when use it in compile time never warry about its performance
//
// if fallback to runtime:
//
// auto nID = DBCOM_ITEMID(szName);
//
// this would cause line search for all item record in itemrecord.inc
// would be better if we can create a constexpr hashmap based on the data
// check following repo:
//
// https://github.com/benjibc/constexpr_hash_map.git
//
// but we don't need it currently, principle:
// transfer ID between client and server but not string name
// so we won't need to retrieve ID by a given a string variable name
// only use this function with literal string to get ID since ID is not fixed (but unique)
constexpr uint32_t DBCOM_ITEMID(const char *szName)
{
if(szName){
for(size_t nIndex = 0; nIndex < sizeof(_Inn_ItemRecordList) / sizeof(_Inn_ItemRecordList[0]); ++nIndex){
if(ConstExprFunc::CompareUTF8(szName, _Inn_ItemRecordList[nIndex].Name)){
return (uint32_t)(nIndex);
}
}
}
return 0;
}
constexpr uint32_t DBCOM_MONSTERID(const char *szName)
{
if(szName){
for(size_t nIndex = 0; nIndex < sizeof(_Inn_MonsterRecordList) / sizeof(_Inn_MonsterRecordList[0]); ++nIndex){
if(ConstExprFunc::CompareUTF8(szName, _Inn_MonsterRecordList[nIndex].Name)){
return (uint32_t)(nIndex);
}
}
}
return 0;
}
constexpr uint32_t DBCOM_MAGICID(const char *szName)
{
if(szName){
for(size_t nIndex = 0; nIndex < sizeof(_Inn_MagicRecordList) / sizeof(_Inn_MagicRecordList[0]); ++nIndex){
if(ConstExprFunc::CompareUTF8(szName, _Inn_MagicRecordList[nIndex].Name)){
return (uint32_t)(nIndex);
}
}
}
return 0;
}
constexpr uint32_t DBCOM_MAPID(const char *szName)
{
if(szName){
for(size_t nIndex = 0; nIndex < sizeof(_Inn_MapRecordList) / sizeof(_Inn_MapRecordList[0]); ++nIndex){
if(ConstExprFunc::CompareUTF8(szName, _Inn_MapRecordList[nIndex].Name)){
return (uint32_t)(nIndex);
}
}
}
return 0;
}
| [
"[email protected]"
] | |
9f2c188139cf1a85708d0f00e23d1c0e4d4eaf65 | fe2836176ca940977734312801f647c12e32a297 | /LeetCode/old/PrepForGoogleInterview2018/C++/first/647.cpp | f4b6aafa7e80acdc18840d8b98a757aeb60b7253 | [] | no_license | henrybear327/Sandbox | ef26d96bc5cbcdc1ce04bf507e19212ca3ceb064 | d77627dd713035ab89c755a515da95ecb1b1121b | refs/heads/master | 2022-12-25T16:11:03.363028 | 2022-12-10T21:08:41 | 2022-12-10T21:08:41 | 53,817,848 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,035 | cpp | // clang-format -style=LLVM -i *.cpp && astyle --style=linux *.cpp && rm *.orig
// && g++ -Wall -Wextra -std=c++11 ...
#include <bits/stdc++.h>
using namespace std;
static int initialSetup = []()
{
// toggle off cout & cin, instead, use printf & scanf
std::ios::sync_with_stdio(false);
// untie cin & cout
cin.tie(NULL);
return 0;
}
();
class Solution
{
public:
int countSubstrings(string s)
{
int ans = 0;
string ns = "";
for (int i = 0; i < (int)s.length(); i++) {
ns += s[i];
if (i != (int)s.length() - 1)
ns += "$";
}
for (int i = 0; i < (int)ns.length(); i++) {
int start = (ns[i] == '$' ? 1 : 0);
for (int j = start; i + j < (int)ns.length() && i - j >= 0; j += 2) {
if (ns[i + j] == ns[i - j]) {
ans++;
} else {
break;
}
}
}
return ans;
}
};
int main()
{
return 0;
} | [
"[email protected]"
] | |
8a033f2bf41d68f104b3c3499b17e857af3f0dcf | 376606835cb0bd37980f8890a4cc92bdad1d2e33 | /SRM/GameOfSegments.cpp | ddf45419129e5e22d94a3efecfd3fd1a8573e90c | [] | no_license | Mukit09/TopCoder-Solutions | b8ce8720c9e48dd7e518dad4129eeedc6412a88b | c27b98a0e4698ee18ac362558120c3bcd78415ba | refs/heads/master | 2020-04-14T19:33:54.623936 | 2019-01-04T05:39:53 | 2019-01-04T05:39:53 | 164,062,620 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,617 | cpp | //BISMILLAHIR RAHMANIR RAHIM
#include<bits/stdc++.h>
using namespace std;
// Define Some Variables
#define eps 1e-14
#define si 110
#define pi acos(-1.0)
#define inf (1<<30)-1
#define mod 1000000000 //10^9
//Define Some Functions
#define even(a) ((a)%2==0)
#define odd(a) ((a)%2==1)
#define max(a,b) (a>b ?a:b)
#define min(a,b) (a<b ?a:b)
#define sqr(a)((a)*(a))
#define area(x1,y1,x2,y2,x3,y3) (x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2)) //Area of a triangle
#define dist(x1,y1,x2,y2) (sqr(x1-x2)+sqr(y1-y2)) //Distance between two points
#define mem(a,v) memset(a,v,sizeof(a))
inline bool compare( double a, double b ) { return fabs( a-b ) < 1e-9 ; }
#define fr(i,a,b) for(i=a;i<=b;i++)
#define rep(i,a,b) for(i=a;i<b;i++)
#define rev(i,a,b) for(i=a;i>=b;i--)
typedef long long i64;
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
int i,j,l,n,cs=1,cnt,sm,fg,a[si];
char ch[si];
i64 bmod(i64 a,i64 b)
{
if(b==0)
return 1;
i64 x=bmod(a,b/2);
x=(x*x)%mod;
if(b%2==1)
x=(x*a)%mod;
return x;
}
int gcd(int a,int b)
{
while(b>0)
{
a%=b;
a^=b;
b^=a;
a^=b;
}
return a;
}
i64 lcm(i64 a,i64 b)
{
return ((a*b)/gcd(a,b));
}
struct GameOfSegments{
int winner(int N)
{
int ret;
return ret;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arg0 = 3; int Arg1 = 1; verify_case(0, Arg1, winner(Arg0)); }
void test_case_1() { int Arg0 = 4; int Arg1 = 1; verify_case(1, Arg1, winner(Arg0)); }
void test_case_2() { int Arg0 = 15; int Arg1 = 2; verify_case(2, Arg1, winner(Arg0)); }
void test_case_3() { int Arg0 = 191; int Arg1 = 2; verify_case(3, Arg1, winner(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
GameOfSegments ___test;
___test.run_test(-1);
int gbase;
cin>>gbase; // erase this line if you are not using dev-cpp! :)
return 0;
}
| [
"[email protected]"
] | |
5b76fa360332557d37878a16a6e13f88873309cd | b11e139d868f593280dc1fba3486cf81ba2b55ac | /src/chapter4/L4-01.cpp | d20a535542d7c5a88968161bf7af4acbb09b757f | [] | no_license | dzheleznyakov/CPP | b7b11a9b12f3d4ba458db54afb556dffcd28bcc4 | e820f617c35af5b827da922a0711b20dc24f51a4 | refs/heads/master | 2021-04-09T13:54:36.271233 | 2018-06-13T15:33:25 | 2018-06-13T15:33:25 | 125,508,558 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 479 | cpp | #include <iostream>
int mainL4_01() {
char first {};
char second {};
std::cout << "Enter a character: ";
std::cin >> first;
std::cout << "Enter a second character: ";
std::cin >> second;
std::cout << "The value of the expression " << first << '<' << second
<< " is: " << std::boolalpha << (first < second) << std::endl;
std::cout << "The value of the expression " << first << "==" << second
<< " is: " << std::boolalpha << (first == second) << std::endl;
}
| [
"[email protected]"
] | |
fd3f5a9291b364712fe0f73fe8eadba671fa8bfd | 22ebcde0f235b60c1c5cff32461f477ac4f72ecf | /QtSrc/qt3support/widgets/q3widgetstack.cpp | 5c0127946a680d9ba5e055af5454d5ee9d908849 | [] | no_license | kystyn/ui | 13dc1e7c0e01761b0658be101528bea440be70d9 | 083a011a735f6dc65c271bc92e397c75155ca61f | refs/heads/master | 2020-07-29T03:45:08.929517 | 2020-06-17T23:42:05 | 2020-06-17T23:42:05 | 209,656,041 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,305 | cpp | /****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt3Support module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "q3widgetstack.h"
#include "qlayout.h"
#include "private/qlayoutengine_p.h"
#include "qapplication.h"
#include "qpainter.h"
QT_BEGIN_NAMESPACE
using namespace Qt;
class Q3WidgetStackPrivate {
public:
class Invisible: public QWidget
{
public:
Invisible(Q3WidgetStack * parent): QWidget(parent, "qt_invisible_widgetstack")
{
setBackgroundMode(NoBackground);
}
const char * className() const
{
return "Q3WidgetStackPrivate::Invisible";
}
protected:
void paintEvent(QPaintEvent *)
{
QPainter(this).eraseRect(rect());
}
};
int nextNegativeID;
int nextPositiveID;
};
/*!
\class Q3WidgetStack
\brief The Q3WidgetStack class provides a stack of widgets of which
only the top widget is user-visible.
\compat
The application programmer can move any widget to the top of the
stack at any time using raiseWidget(), and add or remove widgets
using addWidget() and removeWidget(). It is not sufficient to pass
the widget stack as parent to a widget which should be inserted into
the widgetstack.
visibleWidget() is the \e get equivalent of raiseWidget(); it
returns a pointer to the widget that is currently at the top of
the stack.
Q3WidgetStack also provides the ability to manipulate widgets
through application-specified integer IDs. You can also translate
from widget pointers to IDs using id() and from IDs to widget
pointers using widget(). These numeric IDs are unique (per
Q3WidgetStack, not globally), but Q3WidgetStack does not attach any
additional meaning to them.
The default widget stack is frameless, but you can use the usual
Q3Frame functions (such as setFrameStyle()) to add a frame.
Q3WidgetStack provides a signal, aboutToShow(), which is emitted
just before a managed widget is shown.
\sa Q3TabDialog QTabWidget QTabBar Q3Frame
*/
/*!
Constructs an empty widget stack.
The \a parent, \a name and \a f arguments are passed to the Q3Frame
constructor.
*/
Q3WidgetStack::Q3WidgetStack(QWidget * parent, const char *name, Qt::WindowFlags f)
: Q3Frame(parent, name, f) //## merge constructors in 4.0
{
init();
}
void Q3WidgetStack::init()
{
d = new Q3WidgetStackPrivate();
d->nextNegativeID = -2;
d->nextPositiveID = 0;
dict = new Q3IntDict<QWidget>;
focusWidgets = 0;
topWidget = 0;
invisible = 0;
invisible = new Q3WidgetStackPrivate::Invisible(this);
invisible->hide();
}
/*!
Destroys the object and frees any allocated resources.
*/
Q3WidgetStack::~Q3WidgetStack()
{
delete focusWidgets;
delete d;
delete dict;
}
/*!
Adds widget \a w to this stack of widgets, with ID \a id.
If you pass an id \>= 0 this ID is used. If you pass an \a id of
-1 (the default), the widgets will be numbered automatically. If
you pass -2 a unique negative integer will be generated. No widget
has an ID of -1. Returns the ID or -1 on failure (e.g. \a w is 0).
If you pass an id that is already used, then a unique negative
integer will be generated to prevent two widgets having the same
id.
If \a w already exists in the stack the widget will be removed first.
If \a w is not a child of this Q3WidgetStack moves it using
reparent().
*/
int Q3WidgetStack::addWidget(QWidget * w, int id)
{
if (!w || w == invisible || invisible == 0)
return -1;
// prevent duplicates
removeWidget(w);
if (id >= 0 && dict->find(id))
id = -2;
if (id < -1)
id = d->nextNegativeID--;
else if (id == -1)
id = d->nextPositiveID++;
else
d->nextPositiveID = qMax(d->nextPositiveID, id + 1);
// use id >= 0 as-is
dict->insert(id, w);
// preserve existing focus
QWidget * f = w->focusWidget();
while(f && f != w)
f = f->parentWidget();
if (f) {
if (!focusWidgets)
focusWidgets = new Q3PtrDict<QWidget>(17);
focusWidgets->replace(w, w->focusWidget());
}
w->hide();
if (w->parent() != this)
w->reparent(this, contentsRect().topLeft(), false);
w->setGeometry(contentsRect());
updateGeometry();
return id;
}
/*!
Removes widget \a w from this stack of widgets. Does not delete \a
w. If \a w is the currently visible widget, no other widget is
substituted.
\sa visibleWidget() raiseWidget()
*/
void Q3WidgetStack::removeWidget(QWidget * w)
{
int i;
if (!w || (i = id(w)) == -1)
return ;
dict->take(i);
if (w == topWidget)
topWidget = 0;
if (dict->isEmpty())
invisible->hide(); // let background shine through again
updateGeometry();
}
/*!
Raises the widget with ID \a id to the top of the widget stack.
\sa visibleWidget()
*/
void Q3WidgetStack::raiseWidget(int id)
{
if (id == -1)
return;
QWidget * w = dict->find(id);
if (w)
raiseWidget(w);
}
static bool isChildOf(QWidget* child, QWidget *parent)
{
if (!child)
return false;
QObjectList list = parent->children();
for (int i = 0; i < list.size(); ++i) {
QObject *obj = list.at(i);
if (!obj->isWidgetType())
continue;
QWidget *widget = static_cast<QWidget *>(obj);
if (!widget->isWindow())
continue;
if (widget == child || isChildOf(child, widget))
return true;
}
return false;
}
/*!
\overload
Raises widget \a w to the top of the widget stack.
*/
void Q3WidgetStack::raiseWidget(QWidget *w)
{
if (!w || w == invisible || w->parent() != this || w == topWidget)
return;
if (id(w) == -1)
addWidget(w);
if (!isVisible()) {
topWidget = w;
return;
}
if (w->maximumSize().width() < invisible->width()
|| w->maximumSize().height() < invisible->height())
invisible->setBackgroundMode(backgroundMode());
else if (invisible->backgroundMode() != NoBackground)
invisible->setBackgroundMode(NoBackground);
if (invisible->isHidden()) {
invisible->setGeometry(contentsRect());
invisible->lower();
invisible->show();
QApplication::sendPostedEvents(invisible, QEvent::ShowWindowRequest);
}
// try to move focus onto the incoming widget if focus
// was somewhere on the outgoing widget.
if (topWidget) {
QWidget * fw = window()->focusWidget();
if (topWidget->isAncestorOf(fw)) { // focus was on old page
// look for the best focus widget we can find
QWidget *p = w->focusWidget();
if (!p) {
// second best == first child widget in the focus chain
QWidget *i = fw;
while ((i = i->nextInFocusChain()) != fw) {
if (((i->focusPolicy() & Qt::TabFocus) == Qt::TabFocus)
&& !i->focusProxy() && i->isVisibleTo(w) && i->isEnabled()
&& w->isAncestorOf(i)) {
p = i;
break;
}
}
}
if (p)
p->setFocus();
} else {
// the focus wasn't on the old page, so we have to ensure focus doesn't go to
// the widget in the page that last had focus when we show the page again.
QWidget *oldfw = topWidget->focusWidget();
if (oldfw)
oldfw->clearFocus();
}
}
if (isVisible()) {
emit aboutToShow(w);
int i = id(w);
if (i != -1)
emit aboutToShow(i);
}
topWidget = w;
QObjectList c = children();
for (int i = 0; i < c.size(); ++i) {
QObject * o = c.at(i);
if (o->isWidgetType() && o != w && o != invisible)
static_cast<QWidget *>(o)->hide();
}
w->setGeometry(invisible->geometry());
w->show();
}
/*!
\reimp
*/
void Q3WidgetStack::frameChanged()
{
Q3Frame::frameChanged();
setChildGeometries();
}
/*!
\internal
*/
void Q3WidgetStack::setFrameRect(const QRect & r)
{
// ### this function used to be virtual in QFrame in Qt 3; it is no longer virtual in Qt 4
Q3Frame::setFrameRect(r);
setChildGeometries();
}
/*!
Fixes up the children's geometries.
*/
void Q3WidgetStack::setChildGeometries()
{
invisible->setGeometry(contentsRect());
if (topWidget)
topWidget->setGeometry(invisible->geometry());
}
/*!
\reimp
*/
void Q3WidgetStack::setVisible(bool visible)
{
if (visible) {
// Reimplemented in order to set the children's geometries
// appropriately and to pick the first widget as d->topWidget if no
// topwidget was defined
QObjectList c = children();
if (!isVisible() && !c.isEmpty()) {
for (int i = 0; i < c.size(); ++i) {
QObject * o = c.at(i);
if (o->isWidgetType()) {
if (!topWidget && o != invisible)
topWidget = static_cast<QWidget*>(o);
if (o == topWidget)
static_cast<QWidget *>(o)->show();
else
static_cast<QWidget *>(o)->hide();
}
}
setChildGeometries();
}
}
Q3Frame::setVisible(visible);
}
/*!
Returns the widget with ID \a id. Returns 0 if this widget stack
does not manage a widget with ID \a id.
\sa id() addWidget()
*/
QWidget * Q3WidgetStack::widget(int id) const
{
return id != -1 ? dict->find(id) : 0;
}
/*!
Returns the ID of the \a widget. Returns -1 if \a widget is 0 or
is not being managed by this widget stack.
\sa widget() addWidget()
*/
int Q3WidgetStack::id(QWidget * widget) const
{
if (!widget)
return -1;
Q3IntDictIterator<QWidget> it(*dict);
while (it.current() && it.current() != widget)
++it;
return it.current() == widget ? it.currentKey() : -1;
}
/*!
Returns the currently visible widget (the one at the top of the
stack), or 0 if nothing is currently being shown.
\sa aboutToShow() id() raiseWidget()
*/
QWidget * Q3WidgetStack::visibleWidget() const
{
return topWidget;
}
/*!
\fn void Q3WidgetStack::aboutToShow(int id)
This signal is emitted just before a managed widget is shown if
that managed widget has an ID != -1. The \a id parameter is the numeric
ID of the widget.
If you call visibleWidget() in a slot connected to aboutToShow(),
the widget it returns is the one that is currently visible, not
the one that is about to be shown.
*/
/*!
\fn void Q3WidgetStack::aboutToShow(QWidget *widget)
\overload
This signal is emitted just before a managed widget is shown. The
argument is a pointer to the \a widget.
If you call visibleWidget() in a slot connected to aboutToShow(),
the widget returned is the one that is currently visible, not the
one that is about to be shown.
*/
/*!
\reimp
*/
void Q3WidgetStack::resizeEvent(QResizeEvent * e)
{
Q3Frame::resizeEvent(e);
setChildGeometries();
}
/*!
\reimp
*/
QSize Q3WidgetStack::sizeHint() const
{
constPolish();
QSize size(0, 0);
Q3IntDictIterator<QWidget> it(*dict);
QWidget *w;
while ((w = it.current()) != 0) {
++it;
QSize sh = w->sizeHint();
if (w->sizePolicy().horData() == QSizePolicy::Ignored)
sh.rwidth() = 0;
if (w->sizePolicy().verData() == QSizePolicy::Ignored)
sh.rheight() = 0;
#ifndef QT_NO_LAYOUT
size = size.expandedTo(sh).expandedTo(qSmartMinSize(w));
#endif
}
if (size.isNull())
size = QSize(128, 64);
size += QSize(2*frameWidth(), 2*frameWidth());
return size;
}
/*!
\reimp
*/
QSize Q3WidgetStack::minimumSizeHint() const
{
constPolish();
QSize size(0, 0);
Q3IntDictIterator<QWidget> it(*dict);
QWidget *w;
while ((w = it.current()) != 0) {
++it;
QSize sh = w->minimumSizeHint();
if (w->sizePolicy().horData() == QSizePolicy::Ignored)
sh.rwidth() = 0;
if (w->sizePolicy().verData() == QSizePolicy::Ignored)
sh.rheight() = 0;
#ifndef QT_NO_LAYOUT
size = size.expandedTo(sh).expandedTo(w->minimumSize());
#endif
}
if (size.isNull())
size = QSize(64, 32);
size += QSize(2*frameWidth(), 2*frameWidth());
return size;
}
/*!
\reimp
*/
void Q3WidgetStack::childEvent(QChildEvent *e)
{
if (e->child()->isWidgetType() && e->removed())
removeWidget((QWidget *) e->child());
}
/*!
\reimp
*/
bool Q3WidgetStack::event(QEvent* e)
{
if (e->type() == QEvent::LayoutRequest || e->type() == QEvent::LayoutHint )
updateGeometry(); // propgate layout hints to parent
return Q3Frame::event(e);
}
QT_END_NAMESPACE
| [
"[email protected]"
] | |
493a1bf7d917348706c127b2f2d2cffe79df66e6 | e3e5b59c7d3292dc73225a817feae38627d590c8 | /src/qt/rpcconsole.cpp | da02932e960688f16d0ee6458516b42ca713b997 | [
"MIT"
] | permissive | hichman/CWXT | f97e14d47c0a99d1980e31bc057dd116800ad77f | bea710b603cb16ac61a4cae85dd9805ddfd18e55 | refs/heads/master | 2021-05-15T03:12:24.284304 | 2017-01-07T05:45:46 | 2017-01-07T05:45:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,479 | cpp | #include "rpcconsole.h"
#include "ui_rpcconsole.h"
#include "clientmodel.h"
#include "bitcoinrpc.h"
#include "guiutil.h"
#include <QTime>
#include <QTimer>
#include <QThread>
#include <QTextEdit>
#include <QKeyEvent>
#include <QUrl>
#include <QScrollBar>
#include <openssl/crypto.h>
// TODO: make it possible to filter out categories (esp debug messages when implemented)
// TODO: receive errors and debug messages through ClientModel
const int CONSOLE_SCROLLBACK = 50;
const int CONSOLE_HISTORY = 50;
const QSize ICON_SIZE(24, 24);
const struct {
const char *url;
const char *source;
} ICON_MAPPING[] = {
{"cmd-request", ":/icons/tx_input"},
{"cmd-reply", ":/icons/tx_output"},
{"cmd-error", ":/icons/tx_output"},
{"misc", ":/icons/tx_inout"},
{NULL, NULL}
};
/* Object for executing console RPC commands in a separate thread.
*/
class RPCExecutor: public QObject
{
Q_OBJECT
public slots:
void start();
void request(const QString &command);
signals:
void reply(int category, const QString &command);
};
#include "rpcconsole.moc"
void RPCExecutor::start()
{
// Nothing to do
}
/**
* Split shell command line into a list of arguments. Aims to emulate \c bash and friends.
*
* - Arguments are delimited with whitespace
* - Extra whitespace at the beginning and end and between arguments will be ignored
* - Text can be "double" or 'single' quoted
* - The backslash \c \ is used as escape character
* - Outside quotes, any character can be escaped
* - Within double quotes, only escape \c " and backslashes before a \c " or another backslash
* - Within single quotes, no escaping is possible and no special interpretation takes place
*
* @param[out] args Parsed arguments will be appended to this list
* @param[in] strCommand Command line to split
*/
bool parseCommandLine(std::vector<std::string> &args, const std::string &strCommand)
{
enum CmdParseState
{
STATE_EATING_SPACES,
STATE_ARGUMENT,
STATE_SINGLEQUOTED,
STATE_DOUBLEQUOTED,
STATE_ESCAPE_OUTER,
STATE_ESCAPE_DOUBLEQUOTED
} state = STATE_EATING_SPACES;
std::string curarg;
foreach(char ch, strCommand)
{
switch(state)
{
case STATE_ARGUMENT: // In or after argument
case STATE_EATING_SPACES: // Handle runs of whitespace
switch(ch)
{
case '"': state = STATE_DOUBLEQUOTED; break;
case '\'': state = STATE_SINGLEQUOTED; break;
case '\\': state = STATE_ESCAPE_OUTER; break;
case ' ': case '\n': case '\t':
if(state == STATE_ARGUMENT) // Space ends argument
{
args.push_back(curarg);
curarg.clear();
}
state = STATE_EATING_SPACES;
break;
default: curarg += ch; state = STATE_ARGUMENT;
}
break;
case STATE_SINGLEQUOTED: // Single-quoted string
switch(ch)
{
case '\'': state = STATE_ARGUMENT; break;
default: curarg += ch;
}
break;
case STATE_DOUBLEQUOTED: // Double-quoted string
switch(ch)
{
case '"': state = STATE_ARGUMENT; break;
case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break;
default: curarg += ch;
}
break;
case STATE_ESCAPE_OUTER: // '\' outside quotes
curarg += ch; state = STATE_ARGUMENT;
break;
case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text
if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself
curarg += ch; state = STATE_DOUBLEQUOTED;
break;
}
}
switch(state) // final state
{
case STATE_EATING_SPACES:
return true;
case STATE_ARGUMENT:
args.push_back(curarg);
return true;
default: // ERROR to end in one of the other states
return false;
}
}
void RPCExecutor::request(const QString &command)
{
std::vector<std::string> args;
if(!parseCommandLine(args, command.toStdString()))
{
emit reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \""));
return;
}
if(args.empty())
return; // Nothing to do
try
{
std::string strPrint;
// Convert argument list to JSON objects in method-dependent way,
// and pass it along with the method name to the dispatcher.
json_spirit::Value result = tableRPC.execute(
args[0],
RPCConvertValues(args[0], std::vector<std::string>(args.begin() + 1, args.end())));
// Format result reply
if (result.type() == json_spirit::null_type)
strPrint = "";
else if (result.type() == json_spirit::str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
emit reply(RPCConsole::CMD_REPLY, QString::fromStdString(strPrint));
}
catch (json_spirit::Object& objError)
{
try // Nice formatting for standard-format error
{
int code = find_value(objError, "code").get_int();
std::string message = find_value(objError, "message").get_str();
emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")");
}
catch(std::runtime_error &) // raised when converting to invalid type, i.e. missing code or message
{ // Show raw JSON object
emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(write_string(json_spirit::Value(objError), false)));
}
}
catch (std::exception& e)
{
emit reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what()));
}
}
RPCConsole::RPCConsole(QWidget *parent) :
QDialog(parent),
ui(new Ui::RPCConsole),
historyPtr(0)
{
ui->setupUi(this);
#ifndef Q_OS_MAC
ui->openDebugLogfileButton->setIcon(QIcon(":/icons/export"));
ui->showCLOptionsButton->setIcon(QIcon(":/icons/options"));
#endif
// Install event filter for up and down arrow
ui->lineEdit->installEventFilter(this);
ui->messagesWidget->installEventFilter(this);
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
// set OpenSSL version label
ui->openSSLVersion->setText(SSLeay_version(SSLEAY_VERSION));
startExecutor();
clear();
}
RPCConsole::~RPCConsole()
{
emit stopExecutor();
delete ui;
}
bool RPCConsole::eventFilter(QObject* obj, QEvent *event)
{
if(event->type() == QEvent::KeyPress) // Special key handling
{
QKeyEvent *keyevt = static_cast<QKeyEvent*>(event);
int key = keyevt->key();
Qt::KeyboardModifiers mod = keyevt->modifiers();
switch(key)
{
case Qt::Key_Up: if(obj == ui->lineEdit) { browseHistory(-1); return true; } break;
case Qt::Key_Down: if(obj == ui->lineEdit) { browseHistory(1); return true; } break;
case Qt::Key_PageUp: /* pass paging keys to messages widget */
case Qt::Key_PageDown:
if(obj == ui->lineEdit)
{
QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt));
return true;
}
break;
default:
// Typing in messages widget brings focus to line edit, and redirects key there
// Exclude most combinations and keys that emit no text, except paste shortcuts
if(obj == ui->messagesWidget && (
(!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) ||
((mod & Qt::ControlModifier) && key == Qt::Key_V) ||
((mod & Qt::ShiftModifier) && key == Qt::Key_Insert)))
{
ui->lineEdit->setFocus();
QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt));
return true;
}
}
}
return QDialog::eventFilter(obj, event);
}
void RPCConsole::setClientModel(ClientModel *model)
{
this->clientModel = model;
if(model)
{
// Subscribe to information, replies, messages, errors
connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
connect(model, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int)));
// Provide initial values
ui->clientVersion->setText(model->formatFullVersion());
ui->clientName->setText(model->clientName());
ui->buildDate->setText(model->formatBuildDate());
ui->startupTime->setText(model->formatClientStartupTime());
setNumConnections(model->getNumConnections());
ui->isTestNet->setChecked(model->isTestNet());
setNumBlocks(model->getNumBlocks(), model->getNumBlocksOfPeers());
}
}
static QString categoryClass(int category)
{
switch(category)
{
case RPCConsole::CMD_REQUEST: return "cmd-request"; break;
case RPCConsole::CMD_REPLY: return "cmd-reply"; break;
case RPCConsole::CMD_ERROR: return "cmd-error"; break;
default: return "misc";
}
}
void RPCConsole::clear()
{
ui->messagesWidget->clear();
ui->lineEdit->clear();
ui->lineEdit->setFocus();
// Add smoothly scaled icon images.
// (when using width/height on an img, Qt uses nearest instead of linear interpolation)
for(int i=0; ICON_MAPPING[i].url; ++i)
{
ui->messagesWidget->document()->addResource(
QTextDocument::ImageResource,
QUrl(ICON_MAPPING[i].url),
QImage(ICON_MAPPING[i].source).scaled(ICON_SIZE, Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
}
// Set default style sheet
ui->messagesWidget->document()->setDefaultStyleSheet(
"table { }"
"td.time { color: #808080; padding-top: 3px; } "
"td.message { font-family: Monospace; font-size: 12px; } "
"td.cmd-request { color: #006060; } "
"td.cmd-error { color: red; } "
"b { color: #006060; } "
);
message(CMD_REPLY, (tr("Welcome to the cryptoworldxtoken RPC console.") + "<br>" +
tr("Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.") + "<br>" +
tr("Type <b>help</b> for an overview of available commands.")), true);
}
void RPCConsole::message(int category, const QString &message, bool html)
{
QTime time = QTime::currentTime();
QString timeString = time.toString();
QString out;
out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>";
out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>";
out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">";
if(html)
out += message;
else
out += GUIUtil::HtmlEscape(message, true);
out += "</td></tr></table>";
ui->messagesWidget->append(out);
}
void RPCConsole::setNumConnections(int count)
{
ui->numberOfConnections->setText(QString::number(count));
}
void RPCConsole::setNumBlocks(int count, int countOfPeers)
{
ui->numberOfBlocks->setText(QString::number(count));
ui->totalBlocks->setText(QString::number(countOfPeers));
if(clientModel)
{
// If there is no current number available display N/A instead of 0, which can't ever be true
ui->totalBlocks->setText(clientModel->getNumBlocksOfPeers() == 0 ? tr("N/A") : QString::number(clientModel->getNumBlocksOfPeers()));
ui->lastBlockTime->setText(clientModel->getLastBlockDate().toString());
}
}
void RPCConsole::on_lineEdit_returnPressed()
{
QString cmd = ui->lineEdit->text();
ui->lineEdit->clear();
if(!cmd.isEmpty())
{
message(CMD_REQUEST, cmd);
emit cmdRequest(cmd);
// Remove command, if already in history
history.removeOne(cmd);
// Append command to history
history.append(cmd);
// Enforce maximum history size
while(history.size() > CONSOLE_HISTORY)
history.removeFirst();
// Set pointer to end of history
historyPtr = history.size();
// Scroll console view to end
scrollToEnd();
}
}
void RPCConsole::browseHistory(int offset)
{
historyPtr += offset;
if(historyPtr < 0)
historyPtr = 0;
if(historyPtr > history.size())
historyPtr = history.size();
QString cmd;
if(historyPtr < history.size())
cmd = history.at(historyPtr);
ui->lineEdit->setText(cmd);
}
void RPCConsole::startExecutor()
{
QThread* thread = new QThread;
RPCExecutor *executor = new RPCExecutor();
executor->moveToThread(thread);
// Notify executor when thread started (in executor thread)
connect(thread, SIGNAL(started()), executor, SLOT(start()));
// Replies from executor object must go to this object
connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString)));
// Requests from this object must go to executor
connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString)));
// On stopExecutor signal
// - queue executor for deletion (in execution thread)
// - quit the Qt event loop in the execution thread
connect(this, SIGNAL(stopExecutor()), executor, SLOT(deleteLater()));
connect(this, SIGNAL(stopExecutor()), thread, SLOT(quit()));
// Queue the thread for deletion (in this thread) when it is finished
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
// Default implementation of QThread::run() simply spins up an event loop in the thread,
// which is what we want.
thread->start();
}
void RPCConsole::on_tabWidget_currentChanged(int index)
{
if(ui->tabWidget->widget(index) == ui->tab_console)
{
ui->lineEdit->setFocus();
}
}
void RPCConsole::on_openDebugLogfileButton_clicked()
{
GUIUtil::openDebugLogfile();
}
void RPCConsole::scrollToEnd()
{
QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar();
scrollbar->setValue(scrollbar->maximum());
}
void RPCConsole::on_showCLOptionsButton_clicked()
{
GUIUtil::HelpMessageBox help;
help.exec();
}
| [
"git@git"
] | git@git |
63b4161c09aba7b10109c032de9738b72fa269e1 | d0af1f52a74c3d4b3350512dd0ba71bfb3e293af | /src/pthread_execution_queue.h | 9f0cbf3d980a64da13ff29824a8ca19c78acc73c | [
"MIT"
] | permissive | KaidoRen/AmxxCurl | be5f36401bb4eec7f435f9fb10f179b63b4485c6 | c4b5c96f8a4f5209e71fd373e28c6762bd4f7398 | refs/heads/master | 2020-04-21T17:36:41.456327 | 2019-02-08T18:33:38 | 2019-02-08T18:33:38 | 169,741,460 | 0 | 0 | MIT | 2019-02-08T13:47:27 | 2019-02-08T13:47:26 | null | UTF-8 | C++ | false | false | 2,555 | h | #if AMXXCURL_USE_PTHREADS_EXPLICITLY
#ifndef _PTHREAD_EXECUTION_QUEUE_H_
#define _PTHREAD_EXECUTION_QUEUE_H_
#include <pthread.h>
#include <queue>
#include "execution_queue_interface.h"
class PthreadExecutionQueue : public ExecutionQueueInterface
{
struct ThreadData
{
ThreadData(pthread_cond_t& condition_variable, bool& notify)
: condition_variable(condition_variable),
notify(notify)
{ }
pthread_cond_t& condition_variable;
bool& notify;
};
public:
PthreadExecutionQueue() :
executed_(false)
{
pthread_mutex_init(&mutex_thread_signal_, NULL);
pthread_mutex_init(&mutex_thread_executed_, NULL);
pthread_mutex_init(&queue_mutex_, NULL);
pthread_cond_init(&cv_thread_executed_, NULL);
}
void WaitSignal() override
{
pthread_cond_t cv;
pthread_cond_init(&cv, NULL);
bool notify = false;
pthread_mutex_lock(&queue_mutex_);
threads_queue_.emplace(cv, notify);
pthread_mutex_unlock(&queue_mutex_);
pthread_mutex_lock(&mutex_thread_signal_);
while (!notify)
pthread_cond_wait(&cv, &mutex_thread_signal_);
pthread_mutex_unlock(&mutex_thread_signal_);
}
void Executed() override
{
pthread_mutex_lock(&mutex_thread_executed_);
executed_ = true;
pthread_cond_signal(&cv_thread_executed_);
pthread_mutex_unlock(&mutex_thread_executed_);
}
void ExecuteAll() override
{
pthread_mutex_lock(&queue_mutex_);
while (!threads_queue_.empty())
{
pthread_mutex_lock(&mutex_thread_signal_);
ThreadData& thread_data = threads_queue_.front();
thread_data.notify = true;
pthread_cond_signal(&thread_data.condition_variable);
threads_queue_.pop();
pthread_mutex_unlock(&mutex_thread_signal_);
pthread_mutex_lock(&mutex_thread_executed_);
while (!executed_)
pthread_cond_wait(&cv_thread_executed_, &mutex_thread_executed_);
executed_ = false;
pthread_mutex_unlock(&mutex_thread_executed_);
}
pthread_mutex_unlock(&queue_mutex_);
}
private:
std::queue<ThreadData> threads_queue_;
bool executed_;
pthread_mutex_t mutex_thread_signal_;
pthread_mutex_t mutex_thread_executed_;
pthread_cond_t cv_thread_executed_;
pthread_mutex_t queue_mutex_;
};
#endif // _PTHREAD_EXECUTION_QUEUE_H_
#endif
| [
"[email protected]"
] | |
e8203edf4fb6ca74852d3f8a31f307cb1b33497b | 68b0ef8cf0710e0be34d4b64882a28eefa44b2a8 | /TP3/Ejercicio-1/Bullet.cpp | a32166cbd770e5543dd3c3505010551df63c1bb7 | [] | no_license | MatiasRT/Graficos1-TP3 | bb4d2518d0d83a456a03e7cc616a0cf038c9df01 | 92f67f2918cceea7d32bb7ca4ebd39872ad5298b | refs/heads/master | 2020-03-18T22:24:11.531743 | 2018-06-05T01:44:45 | 2018-06-05T01:44:45 | 135,343,262 | 0 | 0 | null | 2018-05-29T19:26:46 | 2018-05-29T19:26:46 | null | UTF-8 | C++ | false | false | 539 | cpp | #include "Bullet.h"
#define SPEED 800
#define TAM -25
Bullet::Bullet(int x, int y, const char* imagePath) :Object(x, y, imagePath) {
_speed = SPEED;
_enable = false;
}
Bullet::~Bullet(){
}
void Bullet::update(float elapsed) {
if (_enable) {
if (_y > TAM)
_y -= _speed * elapsed;
else
_enable = false;
}
}
void Bullet::reset(int x, int y) {
_x = x;
_y = y;
}
bool Bullet::isEnable() {
return _enable;
}
void Bullet::disable() {
_enable = false;
}
void Bullet::enable() {
_enable = true;
} | [
"[email protected]"
] | |
b8fc8762b027d7033e3f5b442b9eea411688faa3 | 2ccb99e0b35b58622c5a0be2a698ebda3ab29dec | /gfx/skia/skia/src/pathops/SkPathOpsConic.cpp | 86bad262e32ba4f72ac7f9949f4556ab814efce9 | [
"BSD-3-Clause"
] | permissive | roytam1/palemoon27 | f436d4a3688fd14ea5423cbcaf16c4539b88781f | 685d46ffdaee14705ea40e7ac57c4c11e8f31cd0 | refs/heads/master | 2023-08-20T10:11:13.367377 | 2023-08-17T07:28:43 | 2023-08-17T07:28:43 | 142,234,965 | 61 | 16 | NOASSERTION | 2022-03-30T07:54:03 | 2018-07-25T02:10:02 | null | UTF-8 | C++ | false | false | 5,128 | cpp | /*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkIntersections.h"
#include "SkLineParameters.h"
#include "SkPathOpsConic.h"
#include "SkPathOpsCubic.h"
#include "SkPathOpsQuad.h"
// cribbed from the float version in SkGeometry.cpp
static void conic_deriv_coeff(const double src[],
SkScalar w,
double coeff[3]) {
const double P20 = src[4] - src[0];
const double P10 = src[2] - src[0];
const double wP10 = w * P10;
coeff[0] = w * P20 - P20;
coeff[1] = P20 - 2 * wP10;
coeff[2] = wP10;
}
static double conic_eval_tan(const double coord[], SkScalar w, double t) {
double coeff[3];
conic_deriv_coeff(coord, w, coeff);
return t * (t * coeff[0] + coeff[1]) + coeff[2];
}
int SkDConic::FindExtrema(const double src[], SkScalar w, double t[1]) {
double coeff[3];
conic_deriv_coeff(src, w, coeff);
double tValues[2];
int roots = SkDQuad::RootsValidT(coeff[0], coeff[1], coeff[2], tValues);
SkASSERT(0 == roots || 1 == roots);
if (1 == roots) {
t[0] = tValues[0];
return 1;
}
return 0;
}
SkDVector SkDConic::dxdyAtT(double t) const {
SkDVector result = {
conic_eval_tan(&fPts[0].fX, fWeight, t),
conic_eval_tan(&fPts[0].fY, fWeight, t)
};
if (result.fX == 0 && result.fY == 0) {
if (zero_or_one(t)) {
result = fPts[2] - fPts[0];
} else {
// incomplete
SkDebugf("!k");
}
}
return result;
}
static double conic_eval_numerator(const double src[], SkScalar w, double t) {
SkASSERT(src);
SkASSERT(t >= 0 && t <= 1);
double src2w = src[2] * w;
double C = src[0];
double A = src[4] - 2 * src2w + C;
double B = 2 * (src2w - C);
return (A * t + B) * t + C;
}
static double conic_eval_denominator(SkScalar w, double t) {
double B = 2 * (w - 1);
double C = 1;
double A = -B;
return (A * t + B) * t + C;
}
bool SkDConic::hullIntersects(const SkDCubic& cubic, bool* isLinear) const {
return cubic.hullIntersects(*this, isLinear);
}
SkDPoint SkDConic::ptAtT(double t) const {
if (t == 0) {
return fPts[0];
}
if (t == 1) {
return fPts[2];
}
double denominator = conic_eval_denominator(fWeight, t);
SkDPoint result = {
conic_eval_numerator(&fPts[0].fX, fWeight, t) / denominator,
conic_eval_numerator(&fPts[0].fY, fWeight, t) / denominator
};
return result;
}
/* see quad subdivide for point rationale */
/* w rationale : the mid point between t1 and t2 could be determined from the computed a/b/c
values if the computed w was known. Since we know the mid point at (t1+t2)/2, we'll assume
that it is the same as the point on the new curve t==(0+1)/2.
d / dz == conic_poly(dst, unknownW, .5) / conic_weight(unknownW, .5);
conic_poly(dst, unknownW, .5)
= a / 4 + (b * unknownW) / 2 + c / 4
= (a + c) / 4 + (bx * unknownW) / 2
conic_weight(unknownW, .5)
= unknownW / 2 + 1 / 2
d / dz == ((a + c) / 2 + b * unknownW) / (unknownW + 1)
d / dz * (unknownW + 1) == (a + c) / 2 + b * unknownW
unknownW = ((a + c) / 2 - d / dz) / (d / dz - b)
Thus, w is the ratio of the distance from the mid of end points to the on-curve point, and the
distance of the on-curve point to the control point.
*/
SkDConic SkDConic::subDivide(double t1, double t2) const {
double ax, ay, az;
if (t1 == 0) {
ax = fPts[0].fX;
ay = fPts[0].fY;
az = 1;
} else if (t1 != 1) {
ax = conic_eval_numerator(&fPts[0].fX, fWeight, t1);
ay = conic_eval_numerator(&fPts[0].fY, fWeight, t1);
az = conic_eval_denominator(fWeight, t1);
} else {
ax = fPts[2].fX;
ay = fPts[2].fY;
az = 1;
}
double midT = (t1 + t2) / 2;
double dx = conic_eval_numerator(&fPts[0].fX, fWeight, midT);
double dy = conic_eval_numerator(&fPts[0].fY, fWeight, midT);
double dz = conic_eval_denominator(fWeight, midT);
double cx, cy, cz;
if (t2 == 1) {
cx = fPts[2].fX;
cy = fPts[2].fY;
cz = 1;
} else if (t2 != 0) {
cx = conic_eval_numerator(&fPts[0].fX, fWeight, t2);
cy = conic_eval_numerator(&fPts[0].fY, fWeight, t2);
cz = conic_eval_denominator(fWeight, t2);
} else {
cx = fPts[0].fX;
cy = fPts[0].fY;
cz = 1;
}
double bx = 2 * dx - (ax + cx) / 2;
double by = 2 * dy - (ay + cy) / 2;
double bz = 2 * dz - (az + cz) / 2;
SkDConic dst = {{{{ax / az, ay / az}, {bx / bz, by / bz}, {cx / cz, cy / cz}}},
SkDoubleToScalar(bz / sqrt(az * cz)) };
return dst;
}
SkDPoint SkDConic::subDivide(const SkDPoint& a, const SkDPoint& c, double t1, double t2,
SkScalar* weight) const {
SkDConic chopped = this->subDivide(t1, t2);
*weight = chopped.fWeight;
return chopped[1];
}
| [
"[email protected]"
] | |
ed41a461d68dd340c52ed0f3aa0b6bb86eb7bc6e | 20398160981e03c60357c482b308e721b48ca97c | /simple_servo_controll/simple_servo_controll.ino | 44ffd4abdd9e0bfabd0125bd3234ed96dc01286e | [] | no_license | Sciencethebird/2019_ASME | 08d1b914b1179492b3343b3fef160d988109847b | 89c04b52c6374bc3e54f0ffe970c39b3ca64fdcc | refs/heads/master | 2020-04-20T19:10:46.730813 | 2019-03-02T04:47:09 | 2019-03-02T04:47:09 | 169,042,506 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,986 | ino | #include<Servo.h>
#define cw HIGH
#define ccw LOW
#define OPEN 1
#define CLOSE 0
Servo servo1;
int pos = 0;
const int motorIn1 = 6;
const int motorIn2 = 7;
const int motorIn3 = 8;
const int motorIn4 = 9;
const int motorIn5 = 10;
const int motorIn6 = 11;
const int motorIn7 = 12;
const int motorIn8 = 13;
const int stprA_step = 50;
const int stprA_dir = 51;
const int stprB_step = 48;
const int stprB_dir = 49;
void stpr_rotate(int stpr_dir, int stpr_step, int dir, int steps) {
//two stepper motor together
digitalWrite(stpr_dir, dir);
digitalWrite(stpr_dir - 2, dir);
for (int i = 0; i < steps; i++) {
digitalWrite(stpr_step, HIGH);
digitalWrite(stpr_step - 2, HIGH);
delayMicroseconds(100);
digitalWrite(stpr_step, LOW);
digitalWrite(stpr_step - 2, LOW);
delayMicroseconds(100);
}
}
void gate_servo(int action) {
if (action == OPEN)
for (pos = 0; pos <= 90; pos += 1) {
servo1.write(pos);
delay(15);
}
if (action == CLOSE)
for (pos = 90; pos >= 0; pos -= 1) {
servo1.write(pos);
delay(15);
}
}
void setup() {
// put your setup code here, to run once:
pinMode(motorIn1, OUTPUT);
pinMode(motorIn2, OUTPUT);
pinMode(motorIn3, OUTPUT);
pinMode(motorIn4, OUTPUT);
pinMode(motorIn5, OUTPUT);
pinMode(motorIn6, OUTPUT);
pinMode(motorIn7, OUTPUT);
pinMode(motorIn8, OUTPUT);
pinMode(stprA_step, OUTPUT);
pinMode(stprA_dir, OUTPUT);
pinMode(stprB_step, OUTPUT);
pinMode(stprB_dir, OUTPUT);
servo1.attach(3);
}
void loop() {
for (int i = 0; i < 256; i++) {
//analogWrite(motorIn3, 200);
//analogWrite(motorIn4, 0);
//analogWrite(motorIn1, 200);
//analogWrite(motorIn2, 0);
// analogWrite(motorIn5, 200);
// analogWrite(motorIn6, 0);
// analogWrite(motorIn7, 200);
// analogWrite(motorIn8, 0);
// delay(10);
}
stpr_rotate(stprA_dir, stprA_step, cw, 20000);
stpr_rotate(stprA_dir, stprA_step, ccw, 20000);
gate_servo(OPEN);
}
| [
"[email protected]"
] | |
8e7d3870736a0344df728082c2f905c1f18a7533 | 7716142f322977cb56bd5078f9a62449841921cb | /chrome/browser/ui/app_list/search/extension_app_result.cc | 781b24217cbd73c09ec7e7ce8965a8f84f42cf53 | [
"LicenseRef-scancode-generic-cla",
"BSD-3-Clause"
] | permissive | 3p3r/ChromiumGStreamerBackend | 9f63ac11aff4326003f74cb118b5ac69eda68fb5 | 269b7cabe31f1b438051a464d661ac66404191e9 | refs/heads/master | 2021-05-31T03:20:38.570165 | 2016-04-26T17:00:00 | 2016-04-26T17:00:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,996 | cc | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/app_list/search/extension_app_result.h"
#include "chrome/browser/extensions/extension_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/app_list/app_list_controller_delegate.h"
#include "chrome/browser/ui/app_list/extension_app_context_menu.h"
#include "chrome/browser/ui/app_list/search/search_util.h"
#include "chrome/browser/ui/extensions/extension_enable_flow.h"
#include "chrome/common/extensions/extension_metrics.h"
#include "content/public/browser/user_metrics.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_system_provider.h"
#include "extensions/browser/extensions_browser_client.h"
#include "extensions/common/constants.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_icon_set.h"
#include "extensions/common/manifest_handlers/icons_handler.h"
#include "ui/app_list/app_list_switches.h"
#include "ui/events/event_constants.h"
#include "ui/gfx/color_utils.h"
#include "ui/gfx/image/image_skia_operations.h"
namespace app_list {
ExtensionAppResult::ExtensionAppResult(Profile* profile,
const std::string& app_id,
AppListControllerDelegate* controller,
bool is_recommendation)
: AppResult(profile, app_id, controller, is_recommendation) {
set_id(extensions::Extension::GetBaseURLFromExtensionId(app_id).spec());
const extensions::Extension* extension =
extensions::ExtensionRegistry::Get(profile)->GetInstalledExtension(
app_id);
DCHECK(extension);
is_platform_app_ = extension->is_platform_app();
icon_.reset(
new extensions::IconImage(profile,
extension,
extensions::IconsInfo::GetIcons(extension),
GetPreferredIconDimension(),
extensions::util::GetDefaultAppIcon(),
this));
UpdateIcon();
StartObservingExtensionRegistry();
}
ExtensionAppResult::~ExtensionAppResult() {
StopObservingExtensionRegistry();
}
void ExtensionAppResult::Open(int event_flags) {
RecordHistogram(APP_SEARCH_RESULT);
const extensions::Extension* extension =
extensions::ExtensionRegistry::Get(profile())->GetInstalledExtension(
app_id());
if (!extension)
return;
// Don't auto-enable apps that cannot be launched.
if (!extensions::util::IsAppLaunchable(app_id(), profile()))
return;
// Check if enable flow is already running or should be started
if (RunExtensionEnableFlow())
return;
if (display_type() != DISPLAY_RECOMMENDATION) {
extensions::RecordAppListSearchLaunch(extension);
content::RecordAction(
base::UserMetricsAction("AppList_ClickOnAppFromSearch"));
}
controller()->ActivateApp(
profile(),
extension,
AppListControllerDelegate::LAUNCH_FROM_APP_LIST_SEARCH,
event_flags);
}
scoped_ptr<SearchResult> ExtensionAppResult::Duplicate() const {
scoped_ptr<SearchResult> copy(
new ExtensionAppResult(profile(), app_id(), controller(),
display_type() == DISPLAY_RECOMMENDATION));
copy->set_title(title());
copy->set_title_tags(title_tags());
copy->set_relevance(relevance());
return copy;
}
ui::MenuModel* ExtensionAppResult::GetContextMenuModel() {
if (!context_menu_) {
context_menu_.reset(new ExtensionAppContextMenu(
this, profile(), app_id(), controller()));
context_menu_->set_is_platform_app(is_platform_app_);
}
return context_menu_->GetMenuModel();
}
void ExtensionAppResult::StartObservingExtensionRegistry() {
DCHECK(!extension_registry_);
extension_registry_ = extensions::ExtensionRegistry::Get(profile());
extension_registry_->AddObserver(this);
}
void ExtensionAppResult::StopObservingExtensionRegistry() {
if (extension_registry_)
extension_registry_->RemoveObserver(this);
extension_registry_ = NULL;
}
bool ExtensionAppResult::RunExtensionEnableFlow() {
if (extensions::util::IsAppLaunchableWithoutEnabling(app_id(), profile()))
return false;
if (!extension_enable_flow_) {
controller()->OnShowChildDialog();
extension_enable_flow_.reset(new ExtensionEnableFlow(
profile(), app_id(), this));
extension_enable_flow_->StartForNativeWindow(
controller()->GetAppListWindow());
}
return true;
}
void ExtensionAppResult::UpdateIcon() {
gfx::ImageSkia icon = icon_->image_skia();
if (!extensions::util::IsAppLaunchable(app_id(), profile())) {
const color_utils::HSL shift = {-1, 0, 0.6};
icon = gfx::ImageSkiaOperations::CreateHSLShiftedImage(icon, shift);
}
SetIcon(icon);
}
void ExtensionAppResult::OnExtensionIconImageChanged(
extensions::IconImage* image) {
DCHECK_EQ(icon_.get(), image);
UpdateIcon();
}
void ExtensionAppResult::OnExtensionIconImageDestroyed(
extensions::IconImage* image) {
SetIcon(gfx::ImageSkia());
}
void ExtensionAppResult::ExecuteLaunchCommand(int event_flags) {
Open(event_flags);
}
void ExtensionAppResult::ExtensionEnableFlowFinished() {
extension_enable_flow_.reset();
controller()->OnCloseChildDialog();
// Automatically open app after enabling.
Open(ui::EF_NONE);
}
void ExtensionAppResult::ExtensionEnableFlowAborted(bool user_initiated) {
extension_enable_flow_.reset();
controller()->OnCloseChildDialog();
}
void ExtensionAppResult::OnExtensionLoaded(
content::BrowserContext* browser_context,
const extensions::Extension* extension) {
UpdateIcon();
}
void ExtensionAppResult::OnShutdown(extensions::ExtensionRegistry* registry) {
DCHECK_EQ(extension_registry_, registry);
StopObservingExtensionRegistry();
}
} // namespace app_list
| [
"[email protected]"
] | |
70b1a4a1ebf10476a99d9b4e3517c989d85626de | 797879e58a63264776a62ac762d6a5fe5709a7c9 | /libs/log/preprocess/VariableParser.h | 14a2a0966201659d243f0954eab88053c99d6d51 | [] | no_license | epfl-vlsc/NvmFlow | f1ba6887748e9411377608f2f3bf30de43d1faf2 | 9a2a016b8cd5f005bdd3cdd790cfa6c1141e9ff6 | refs/heads/master | 2023-04-17T03:13:39.105728 | 2021-04-27T14:01:08 | 2021-04-27T14:01:08 | 195,298,535 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 366 | h | #pragma once
#include "Common.h"
#include "DbgParser.h"
#include "VarParser.h"
#include "VarFiller.h"
namespace llvm {
template <typename Globals> class VariableParser {
public:
VariableParser(Globals& globals) {
// ordering matters!
DbgParser dParser(globals);
VarParser vParser(globals);
VarFiller fParser(globals);
}
};
} // namespace llvm | [
"[email protected]"
] | |
c94aae47e6d1e99441cf953300155b0a5f8bb6a1 | e655384bfab5b8ce2705e35428755a5701854f3e | /Data Structures/arrays/printLeaders.cpp | 7a64082f188d07f06e08b4ecf2e6a873cb330004 | [] | no_license | sulemanrai/GeeksforGeeks | f4ad99b1881fc7b385db7a9af95267abac084a5d | ba90a60ae6559b734d616f84eaef786d79cd072c | refs/heads/master | 2020-03-08T02:43:16.225555 | 2018-07-09T08:54:13 | 2018-07-09T08:54:13 | 127,868,622 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 973 | cpp | #include<iostream>
#include <vector>
#include <algorithm>
using namespace std;
void printLeaders(vector<int> vec)
{
bool isgreater = false;
vector<int> ans;
std::vector<int>::iterator it;
for(int i = 0; i < vec.size(); i++)
{
for(int j = i+1; j < vec.size(); j++)
{
if(vec[j] > vec[i])
{
isgreater = false;
break;
} else
{
isgreater = true;
}
}
it = find(ans.begin(), ans.end(), vec[i]);
if ((isgreater == true && it == ans.end())) {
//cout << vec[i] << ' ';
ans.push_back(vec[i]);
}
isgreater = false;
}
it = find(ans.begin(), ans.end(), vec[vec.size() - 1]);
if(it == ans.end())
{
ans.push_back(vec[vec.size() - 1]);
}
for (int i : ans)
cout << i << ' ';
}
int main()
{
//code
int T;
cin >> T;
while(T--)
{
int N;
cin >> N;
vector<int> vec;
for(int i = 0; i < N; i++)
{
int element;
cin >> element;
vec.push_back(element);
}
printLeaders(vec);
cout << endl;
}
return 0;
}
| [
"[email protected]"
] | |
adc538c5f575085e964cc5ccf19995e5c45e643f | a52ff34d3a126815867698dc09266924e089054d | /vulkan/renderPasses.h | 01b7326fee7fabcf279ef80b11b53f02c6eb5948 | [] | no_license | tangxiaohuang/Vinkle-VK_study | 32e2faa11b1aa6442a1585f7334c6085e849b990 | 9fddaf0e77ef958de7204415bb7a378797051df2 | refs/heads/master | 2023-07-21T06:10:36.375791 | 2021-08-26T10:04:07 | 2021-08-26T10:04:07 | 398,993,965 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 111 | h | #pragma once
#include <iostream>
#include <vector>
class renderPasses
{
public:
void createRenderPass();
};
| [
"[email protected]"
] | |
30ee7c5e8f565f82d056d44dea71228ef4ba7881 | 8fd65814f4983061f5cc46da9c67cc5fa2eb01a3 | /arduino/servo_test/servo_test.ino | 478587e86ffd61c9df8d415be6f60faf36ecd9b3 | [] | no_license | klund1/checkers_ws | b3db4d6caec1890ac8c0ce43d503cb9a4970568d | ff3fc507160ba1074a9f11c38770cc2285415e34 | refs/heads/master | 2021-01-11T10:38:37.839415 | 2016-12-13T00:34:50 | 2016-12-13T00:34:50 | 72,957,348 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,161 | ino | #define J0 2
#define J1 3
#define J2 4
#define J3 5
#define EM_PIN 6
#include <ros.h>
#include <std_msgs/Bool.h>
#include <checkers_arm/JointAngles.h>
#include <Servo.h>
Servo joint0, joint1, joint2, joint3;
void setElectroMagnet(bool on_off) {
digitalWrite(EM_PIN,on_off);
}
void setArmPosition(float a0, float a1, float a2, float a3) {
if (a0 >= -90 && a0 <= 90) {
float write_angle = map(a0,-90,90,0,180);
joint0.write(write_angle);
}
if (a1 >= 0 && a1 <= 180) {
float write_angle = map(a1,0,180,180,0);
joint1.write(write_angle);
}
if (a2 >= -90 && a2 <= 90) {
float write_angle = map(a2,-90,90,0,180);
joint2.write(write_angle);
}
if (a3 >= -90 && a3 <= 90) {
float write_angle = map(a3,-90,90,0,160);
joint3.write(write_angle);
}
}
void setup() {
Serial.begin(9600);
pinMode(EM_PIN, OUTPUT);
joint0.attach(J0);
joint1.attach(J1);
joint2.attach(J2);
joint3.attach(J3);
setArmPosition(0,45,-45,0);
setElectroMagnet(false);
}
long read_in;
bool EM_state;
void loop() {
if (Serial.available()) {
EM_state = (Serial.parseInt() != 0);
setElectroMagnet(EM_state);
}
}
| [
"[email protected]"
] | |
77734eb939ee5106cc531dc37aeaf2c6e8fa36a5 | 96cf049c958982c1294a36eace2e8ad12ec0f697 | /ancientmain.cpp | 4d1da734d4121483ca89451808d4a2aff1224f6b | [] | no_license | Cevernaya/PenguinParty_Zoonie | 09be93b2dbc8cf8c922d9795f0088f983c7a0629 | 8968c39ea07c94346a0013edb3518e53e6f9f95f | refs/heads/master | 2023-02-02T05:49:06.442857 | 2020-12-13T05:53:19 | 2020-12-13T05:53:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,705 | cpp | #include <iostream>
#include <cstdlib>
using namespace std;
/* R,G,B(8),Y,P*/
int turnorder = 0; // defalut = 0; player = 1; computer = 2;
//print out player's hand state
void printHands(int hands[5]){
for(int i=0; i<5; i++)
{
cout<<i+1<<" : "<<hands[i]<<" "<<"\n";
}
}
//to make a board in initial state
void printBoard(int board[8][8]){
for(int i=0; i<8; i++){
cout << i+1;
for(int k=8; k>i; k--)
{
cout << " ";
}
for(int j=0; j<=i; j++){
cout << board[i][j] << " ";
}
cout << "\n";
}
}
//check whether a rule is violated or not
bool checking(int board[8][8], int step, int place, int kind){
if(kind<0 || kind>6)
{
return false;
}
if(board[step-1][place-1] == 0)
{
if(step==8)
{
return true;
}
else
{
if(board[step][place-1]!=0 && board[step][place]!=0)
{
if(board[step][place-1]==kind || board[step][place]==kind)
{
return true;
}
}
}
}
return false;
}
int main(){
int board[8][8]={0,0};
int hand[5]={3,3,3,3,3};
int comhand[5]={3,3,3,3,3};
printBoard(board);
cout << "\n";
cout << "\n" << "Choose 1st player. Player first : 1 , Computer first : 2";
int temp = 0;
cin >> temp;
while(temp!=1 && temp!=2) //잘못된 값이 입력될경우 걸러내기
{
cout << "\n다시 입력해주세요.\n";
cin >> temp;
}
turnorder = temp;
while(true)
{
printBoard(board);
int step, place, kind;
if(turnorder == 1) //player choose a card
{
printHands(hand);
cout << "Player's turn\n";
cout << "step place kind\n";
cin >> step >> place >> kind;
// check setcard
if(checking(board, step, place, kind) == 1 && hand[kind-1]!=0)
{
board[step-1][place-1]=kind;
hand[kind-1]=hand[kind-1]-1;
turnorder = 2;
}
else{
cout << "다시 시도해주세요\n";
}
// check win
if(hand[0]==0 && hand[1] ==0 && hand[2] ==0 && hand[3]==0 && hand[4] ==0)
{
cout << "You win!\n";
break;
}
// check that is next player (computer) lose?
bool canSet = false;
for(int i=1; i<=8; i++)//i=step
{
for(int j=1; j<=i; j++)//j=place
{
for(int k = 1; k<=5; k++) //k=kind
{
if(checking(board, i, j, k) == 1 && comhand[k-1] != 0)
{
canSet = true;
}
}
}
}
if(!canSet)
{
cout << "Computer Lose...!\n";
break;
}
}
else if(turnorder == 2) //Computer choose a card
{
printHands(comhand);
int tempstep, tempplace, tempkind;
while(true) //to get appropriate info about card
{
tempstep = rand()%8+1;
tempplace = rand()%8+1;
tempkind = rand()%5+1;
if(checking(board, tempstep, tempplace, tempkind) == 1 && comhand[tempkind-1]!=0)
{
step = tempstep;
place = tempplace;
kind = tempkind;
cout << "Computer Set: " << step << ", " << place << ", " << kind << "\n";
break;
}
}
// check setcard
if(checking(board, step, place, kind) == 1 && comhand[kind-1]!=0)
{
board[step-1][place-1]=kind;
comhand[kind-1]=comhand[kind-1]-1;
turnorder = 1;
}
//check com's win
if(comhand[0]==0 && comhand[1] ==0 && comhand[2] ==0 && comhand[3]==0 && comhand[4] ==0)
{
cout << "Computer win!\n";
break; // <- 전체 while문 탈출?
}
//check that if next player (player) lose?
bool canSet = false;
for(int i=1; i<=8; i++)//i=step
{
for(int j=1; j<=i; j++)//j=place
{
for(int k = 1; k<=5; k++) //k=kind
{
if(checking(board, i, j, k) == 1 && hand[k-1] != 0)
{
canSet = true;
}
}
}
}
if(!canSet)
{
cout << "Player Lose...!\n";
break;
}
}
}
return 0;
}
//ⒶⒷⒸⒹⒺ①②③④⑤ | [
"[email protected]"
] | |
a54dcf03e67b14385b9204a113851a6de9f2f1b9 | dec6ccea75f197f3fdd6bfcdb458712c39b312e4 | /trunk/bin/daemon/src/services/btool_module_p.h | 59354e64102c9981d7183030accdc239acd0c149 | [] | no_license | BackupTheBerlios/bluetool-svn | 9ee059455fb4c5542152408b894485fed9dfeb9d | 0a5d016b2362f4b7759e7119e5d0dd241e37399b | refs/heads/master | 2016-08-05T17:35:42.055563 | 2006-05-17T18:49:01 | 2006-05-17T18:49:01 | 40,718,464 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 440 | h | #ifndef __BTOOL_MODULE_P_H
#define __BTOOL_MODULE_P_H
#include <Python.h>
#include "../bluedebug.h"
#include "py_obj.h"
#include "btool_module.h"
namespace Bluetool
{
struct Module::Private
{
Py::Obj module;
PyObject* modclass; // python class describing the service
PyObject* modservices;
std::string name;
std::string dbus_root;
std::string conf_root;
/*
*/
Private();
};
}//namespace Bluetool
#endif//__BTOOL_MODULE_P_H
| [
"shackan@11aa4a43-84fa-0310-b3ba-94ccd3ab820a"
] | shackan@11aa4a43-84fa-0310-b3ba-94ccd3ab820a |
0ea6f1145f0f66e222dbeecc44c1b5781e0ded2b | 2ba2b07343d8d72c1b1f426e77a65f9eda153aed | /includes/PrintGlm.hpp | df015cc83ccf7f97f85fc112820b8de027c02a05 | [] | no_license | jloro/GameEngine | 0e894977c618ca63258473b7de1643f536367d4f | 2a1498d1ee7f91052e96e7dbca8b05bddad28aac | refs/heads/master | 2020-08-08T20:14:32.932173 | 2019-12-12T11:31:15 | 2019-12-12T11:31:15 | 213,907,306 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,293 | hpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* PrintGlm.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jloro <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/07/27 19:17:06 by jloro #+# #+# */
/* Updated: 2019/09/17 18:31:19 by jloro ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef PRINTGLM_HPP
# define PRINTGLM_HPP
# include <iostream>
# include "glm.hpp"
//# include "gtc/matrix_transform.hpp"
# include "gtc/type_ptr.hpp"
std::ostream &operator<<(std::ostream &o, glm::vec3 & vec);
std::ostream &operator<<(std::ostream &o, glm::vec4 & vec);
std::ostream &operator<<(std::ostream &o, glm::mat3 & mat);
std::ostream &operator<<(std::ostream &o, glm::mat4 & mat);
#endif
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.