blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
62933d2ab5415128ce30ff704a31951039bf7d7c | ed649693468835126ae0bc56a9a9745cbbe02750 | /alljoyn_core/router/policydb/PolicyDB.cc | 104838fbc106e2bf8dbf74d4164cd7f967e86886 | [] | no_license | tkellogg/alljoyn-core | 982304d78da73f07f888c7cbd56731342585d9a5 | 931ed98b3f5e5dbd40ffb529a78825f28cc59037 | refs/heads/master | 2020-12-25T18:22:32.166135 | 2014-07-17T13:56:18 | 2014-07-17T13:58:56 | 21,984,205 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 32,144 | cc | /**
* @file
* AllJoyn-Daemon Policy database class
*/
/******************************************************************************
* Copyright (c) 2010-2011, 2014, AllSeen Alliance. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
******************************************************************************/
#include <qcc/platform.h>
#include <qcc/Debug.h>
#include <qcc/Logger.h>
#include <qcc/Util.h>
#ifndef NDEBUG
#include <qcc/StringUtil.h>
#endif
#include "PolicyDB.h"
#define QCC_MODULE "POLICYDB"
using namespace ajn;
using namespace qcc;
using namespace std;
/*
* The whole design of the PolicyDB is based around the idea that integers are
* more efficient to compare than strings. Just about everything related to
* applying policy rules involves comparing strings. With a lot of rules,
* this can get to be quite expensive computationally.
*
* To make these comparisons more efficient, a dictionary of all the strings
* found in all the rules is created where each string is assigned a unique ID
* number. Strings that appear more than once in the rules will use the same
* ID since they are the same.
*
* Now, when messages are to be routed to endpoints, the strings in the header
* fields are converted to their unique IDs using the dictionary that was
* setup while parsing the policy rule table. Not all strings seen in message
* headers will appear in the dictionary. In such a case, a special value
* will be used that indicates the string is not in the dictionary.
*
* A small complicating factor is that an endpoint may have more than one bus
* name. In such a case, an endpoint would have its unique name plus one or
* more aliases (aka well-known-names). It is very unlikely for a rule to
* specify a unique name, but highly likely to specifiy an alias. Such rules
* apply to the endpoint that sent/received the message and not only the name
* of the endpoint that appears in the message. Since the bus name that
* appears in the message could be either the unique name or any of that
* endpoint's aliases, all of those names need to be treated as equals. To
* accomplish this the PolicyDB code maintains its own name table. This name
* table maps all names to the set of all their aliases. The set of aliases
* is kept as a table of string IDs for efficiency purposes.
*/
/* Policy Groups */
#define RULE_UNKNOWN (0x0)
#define RULE_OWN (0x1 << 0)
#define RULE_SEND (0x1 << 1)
#define RULE_RECEIVE (0x1 << 2)
#define RULE_CONNECT (0x1 << 3)
#ifndef NDEBUG
static String IDSet2String(const _PolicyDB::IDSet& idset)
{
String ids;
std::unordered_set<StringID>::const_iterator it = idset->begin();
while (it != idset->end()) {
ids += I32ToString(*it);
++it;
if (it != idset->end()) {
ids += ", ";
}
}
return ids;
}
#endif
static bool MsgTypeStrToEnum(const String& str, AllJoynMessageType& type)
{
bool success = true;
if (str == "*") {
type = MESSAGE_INVALID;
} else if (str == "method_call") {
type = MESSAGE_METHOD_CALL;
} else if (str == "method_return") {
type = MESSAGE_METHOD_RET;
} else if (str == "signal") {
type = MESSAGE_SIGNAL;
} else if (str == "error") {
type = MESSAGE_ERROR;
} else {
Log(LOG_ERR, "Invalid type for policy rule: \"%s\"\n", str.c_str());
success = false;
}
return success;
}
StringID _PolicyDB::UpdateDictionary(const String& key)
{
StringID id;
if (key.empty()) {
/* A rule that specifies an empty string will never match anything. */
id = NIL_MATCH;
} else {
lock.WRLock();
StringIDMap::const_iterator it = dictionary.find(key);
if (it == dictionary.end()) {
/* New string found; assign it an ID. */
id = dictionary.size();
pair<StringMapKey, StringID> p(key, id);
dictionary.insert(p);
} else {
/* The string already has an ID. */
id = it->second;
}
lock.Unlock();
}
return id;
}
StringID _PolicyDB::LookupStringID(const char* key) const
{
StringID id = ID_NOT_FOUND;
if (key) {
lock.RDLock();
StringIDMap::const_iterator it = dictionary.find(key);
if (it != dictionary.end()) {
id = it->second;
}
lock.Unlock();
}
return id;
}
const _PolicyDB::IDSet _PolicyDB::LookupStringIDPrefix(const char* idStr, char sep) const
{
assert(idStr);
assert(sep != '\0');
IDSet ret;
char* prefix = strdup(idStr); // duplicate idStr since we are modifying it
/*
* If prefix is NULL, then the program is out of memory. While it may be
* considered reasonable to rework the design of this function to return
* an error, in this case an out-of-memory condition, we do not for the
* following reasons. One, it should never happen in real-life, and two,
* it is more likely just a small symptom of a much bigger problem that
* will quickly manifest itself in other ways. To keep this function
* simple and its usage simple, an empty IDSet will be returned in such an
* unlikely condition.
*/
if (prefix) {
while (*prefix) {
StringID id = LookupStringID(prefix);
if ((id != ID_NOT_FOUND) && (id != WILDCARD)) {
/*
* We only add ID's that are found in the string ID table. By
* not keeping prefixes that are known to not be specifed by
* the policy rules, we keep the size of the possible matches
* to a minimum and save time by not adding useless
* information to an unordered_set<>.
*/
ret->insert(id);
}
char* p = strrchr(prefix, sep);
if (p) {
*p = '\0'; // Shorten the string to the next separator.
} else {
*prefix = '\0'; // All done.
}
}
free(prefix);
}
return ret;
}
const _PolicyDB::IDSet _PolicyDB::LookupBusNameID(const char* busName) const
{
IDSet ret;
if (busName && (busName[0] != '\0')) {
lock.RDLock();
BusNameIDMap::const_iterator it = busNameIDMap.find(busName);
if (it != busNameIDMap.end()) {
/*
* We need to make a local copy of the set of aliases for the
* given bus name so that we can safely release the lock and allow
* NameOwnerChanged() to possibly modify the set without causing
* interference. While it is very unlikely that
* NameOwnerChanged() would be called while another message is
* begin processed, this measure follows the priciple of better
* safe than sorry.
*/
ret = IDSet(it->second, true); // deep copy
}
lock.Unlock();
}
return ret;
}
_PolicyDB::_PolicyDB()
{
// Prefill the string ID table with the wildcard character - used when applying rules.
dictionary[""] = WILDCARD;
dictionary["*"] = WILDCARD;
}
bool _PolicyDB::AddRule(PolicyRuleList& ownList,
PolicyRuleList& connectList,
PolicyRuleList& sendList,
PolicyRuleList& receiveList,
policydb::PolicyPermission permission,
const map<String, String>& ruleAttrs)
{
std::map<String, String>::const_iterator attr;
bool success = true;
bool skip = false; // Get's set to true if any component of a rule is guaranteed to not match.
PolicyRule rule(permission);
uint32_t prevPolicyGroup = RULE_UNKNOWN;
uint32_t policyGroup = RULE_UNKNOWN;
QCC_DEBUG_ONLY(rule.ruleString = (permission == policydb::POLICY_ALLOW) ? "<allow" : "<deny");
for (attr = ruleAttrs.begin(); attr != ruleAttrs.end(); ++attr) {
String attrStr = attr->first;
const String& attrVal = attr->second;
QCC_DEBUG_ONLY(rule.ruleString += " " + attrStr + "=\"" + attrVal);
if (attrStr.compare(0, sizeof("send_") - 1, "send_") == 0) {
policyGroup = RULE_SEND;
} else if (attrStr.compare(0, sizeof("receive_") - 1, "receive_") == 0) {
policyGroup = RULE_RECEIVE;
}
if (policyGroup & (RULE_SEND | RULE_RECEIVE)) {
// Trim off "send_"/"receive_" for a shorter/simpler comparisons below.
attrStr = attrStr.substr(attrStr.find_first_of('_') + 1);
if (attrStr == "type") {
success = MsgTypeStrToEnum(attrVal, rule.type);
} else {
StringID strID = UpdateDictionary(attrVal);
skip |= (strID == NIL_MATCH);
QCC_DEBUG_ONLY(rule.ruleString += "{" + I32ToString(strID) + "}");
if (attrStr == "interface") {
rule.interface = strID;
} else if (attrStr == "member") {
rule.member = strID;
} else if (attrStr == "error") {
rule.error = strID;
} else if (attrStr == "path") {
rule.path = strID;
} else if (attrStr == "path_prefix") {
rule.pathPrefix = strID;
} else if (attr->first == "send_destination") {
rule.busName = strID;
} else if (attr->first == "receive_sender") {
rule.busName = strID;
} else {
Log(LOG_ERR, "Unknown policy attribute: \"%s\"\n", attr->first.c_str());
success = false;
}
}
} else {
if (attrStr == "own") {
policyGroup = RULE_OWN;
rule.own = UpdateDictionary(attrVal);
skip |= (rule.own == NIL_MATCH);
} else if (attrStr == "own_prefix") {
policyGroup = RULE_OWN;
rule.ownPrefix = UpdateDictionary(attrVal);
skip |= (rule.ownPrefix == NIL_MATCH);
} else if (attrStr == "user") {
policyGroup = RULE_CONNECT;
if (attrVal == "*") {
rule.userAny = true;
} else {
rule.user = GetUsersUid(attrVal.c_str());
skip |= (rule.user == static_cast<uint32_t>(-1));
}
rule.userSet = true;
} else if (attrStr == "group") {
policyGroup = RULE_CONNECT;
if (attrVal == "*") {
rule.groupAny = true;
} else {
rule.group = GetUsersGid(attrVal.c_str());
skip |= (rule.group == static_cast<uint32_t>(-1));
}
rule.groupSet = true;
} else {
Log(LOG_ERR, "Unknown policy attribute: \"%s\"\n", attr->first.c_str());
success = false;
}
}
QCC_DEBUG_ONLY(rule.ruleString += "\"");
if ((prevPolicyGroup != RULE_UNKNOWN) && (policyGroup != prevPolicyGroup)) {
// Invalid rule spec mixed different policy group attributes.
success = false;
}
prevPolicyGroup = policyGroup;
if (!success) {
break;
}
}
QCC_DEBUG_ONLY(rule.ruleString += "/>");
if (success && !skip) {
assert(policyGroup != RULE_UNKNOWN);
if (policyGroup & RULE_SEND) {
sendList.push_back(rule);
}
if (policyGroup & RULE_RECEIVE) {
receiveList.push_back(rule);
}
if (policyGroup & RULE_OWN) {
ownList.push_back(rule);
}
if (policyGroup & RULE_CONNECT) {
connectList.push_back(rule);
}
}
#ifndef NDEBUG
if (!success && (policyGroup != RULE_UNKNOWN)) {
Log(LOG_ERR, "Invalid attribute \"%s\" in \"%s\".\n", attr->first.c_str(), rule.ruleString.c_str());
}
#endif
return success;
}
bool _PolicyDB::AddRule(const String& cat, const String& catValue, const String& permStr,
const map<String, String>& ruleAttrs)
{
bool success = false;
policydb::PolicyPermission permission;
if (permStr == "allow") {
permission = policydb::POLICY_ALLOW;
} else if (permStr == "deny") {
permission = policydb::POLICY_DENY;
} else {
// Invalid policy.
return false;
}
if (cat == "context") {
if (catValue == "default") {
// <policy context="default">
success = AddRule(ownRS.defaultRules, connectRS.defaultRules,
sendRS.defaultRules, receiveRS.defaultRules,
permission, ruleAttrs);
} else if (catValue == "mandatory") {
// <policy context="mandatory">
success = AddRule(ownRS.mandatoryRules, connectRS.mandatoryRules,
sendRS.mandatoryRules, receiveRS.mandatoryRules,
permission, ruleAttrs);
}
} else if (cat == "user") {
// <policy user="userid">
uint32_t uid = GetUsersUid(catValue.c_str());
if (uid != static_cast<uint32_t>(-1)) {
success = AddRule(ownRS.userRules[uid], connectRS.userRules[uid],
sendRS.userRules[uid], receiveRS.userRules[uid],
permission, ruleAttrs);
} else {
Log(LOG_WARNING, "Ignoring policy rules for invalid user: %s", catValue.c_str());
success = true;
}
} else if (cat == "group") {
// <policy group="groupid">
uint32_t gid = GetUsersGid(catValue.c_str());
if (gid != static_cast<uint32_t>(-1)) {
success = AddRule(ownRS.groupRules[gid], connectRS.groupRules[gid],
sendRS.groupRules[gid], receiveRS.groupRules[gid],
permission, ruleAttrs);
} else {
Log(LOG_WARNING, "Ignoring policy rules for invalid group: %s", catValue.c_str());
success = true;
}
}
return success;
}
void _PolicyDB::AddAlias(const String& alias, const String& name)
{
// We assume the write lock is already held.
StringID nameID = ID_NOT_FOUND;
/*
* Can't call LookupStringID() since it would try to get a read lock while
* we already have a write lock. That would cause a nice assert fail.
* Since the write lock trumps read locks, we'll just lookup the string ID
* directly.
*/
StringIDMap::const_iterator sit = dictionary.find(alias);
if (sit != dictionary.end()) {
nameID = sit->second;
}
IDSet bnids;
BusNameIDMap::iterator it = busNameIDMap.find(name);
if (it != busNameIDMap.end()) {
bnids = it->second;
}
if (nameID != ID_NOT_FOUND) {
QCC_DbgPrintf(("Add %s{%d} to table for %s", alias.c_str(), nameID, name.c_str()));
bnids->insert(nameID);
}
pair<StringMapKey, IDSet> p(alias, bnids);
busNameIDMap.insert(p);
}
void _PolicyDB::Finalize(Bus* bus)
{
if (bus) {
/*
* If the config was reloaded while the bus is operating, then the
* internal map of bus names and aliases has been wiped out. We need
* to regenerate that map from the information in the NameTable.
* Since the NameTable only provides vectors of Strings, the only
* thing we can do is iterate over those vectors and convert them to
* StringIDs.
*/
vector<String> nameList;
vector<String>::const_iterator nlit;
vector<pair<String, vector<String> > > aliasMap;
vector<pair<String, vector<String> > >::const_iterator amit;
DaemonRouter& router(reinterpret_cast<DaemonRouter&>(bus->GetInternal().GetRouter()));
/*
* Need to hold the name table lock for the entire duration of
* processing the bus names even though we get a separate copy of
* those names. This is to prevent a race condition where a
* NameOwnerChanged event happens while we are processing the bus
* names from the name table. We can't acquire the write lock before
* the name table lock due to a dead lock risk. This forces use to
* hold onto the name table lock for the entire duration of processing
* bus names.
*/
router.LockNameTable();
lock.WRLock();
router.GetBusNames(nameList);
router.GetUniqueNamesAndAliases(aliasMap);
for (nlit = nameList.begin(); nlit != nameList.end(); ++nlit) {
const String& name = *nlit;
if (name[0] == ':') {
// Only handle unique names right now, aliases will be handled below.
AddAlias(name, name);
}
}
for (amit = aliasMap.begin(); amit != aliasMap.end(); ++amit) {
const String& unique = amit->first;
const vector<String>& aliases = amit->second;
vector<String>::const_iterator ait;
for (ait = aliases.begin(); ait != aliases.end(); ++ait) {
AddAlias(*ait, unique);
}
}
lock.Unlock();
router.UnlockNameTable();
}
#ifndef NDEBUG
QCC_DbgPrintf(("Dictionary:"));
for (StringIDMap::const_iterator it = dictionary.begin(); it != dictionary.end(); ++it) {
QCC_DbgPrintf((" \"%s\" = %u", it->first.c_str(), it->second));
}
QCC_DbgPrintf(("Name Table:"));
for (unordered_map<qcc::StringMapKey, IDSet>::const_iterator it = busNameIDMap.begin(); it != busNameIDMap.end(); ++it) {
QCC_DbgPrintf((" \"%s\" = {%s}", it->first.c_str(), IDSet2String(it->second).c_str()));
}
#endif
}
void _PolicyDB::NameOwnerChanged(const String& alias, const String* oldOwner, const String* newOwner)
{
/*
* Bus name matching rules must treat all aliases (well known names) they
* resolve to as thesame, otherwise it would be relatively trivial to
* bypass a <deny/> rule specified with one alias by sending to either the
* unique name or a different alias owned by the same owner with a
* matching <allow/> rule. Thus, we must keep track of who owns what
* aliases.
*
* Because messages coming though will include either well known names or
* unique names in the source or destination fields, we need to map each
* unique name and alias to the set of equivalent aliases (plus unique
* name).
*
* Here we take advantage of the fact that IDSet is a MangedObj and that
* there is just one underlying instance. When a new node joins the bus
* (alias == *newOwner), a new IDSet is created with the unique name of
* the new node and that unique name is mapped to that new IDSet. When a
* node gains ownership of an alias, the IDSet for the owner is updated
* with the new alias and a mapping is created from the alias to that
* IDSet. When a node loses ownership of an alias, that alias is removed
* from the owner's IDSet and the mapping from that alias to the IDSet is
* removed. When a node leaves (alias == *oldOwner), the unique name is
* removed from the assiciated IDSet and the mapping from the unique name
* to the IDSet is removed. Due to the nature of ManagedObj and that all
* names are map keys to shared IDSets, it does not matter in what order
* aliases/nodes are added or removed.
*/
StringID aliasID = LookupStringID(alias.c_str());
lock.WRLock();
if (oldOwner) {
BusNameIDMap::iterator it = busNameIDMap.find(alias);
if (it != busNameIDMap.end()) {
QCC_DbgPrintf(("Remove %s{%d} from table for %s", alias.c_str(), aliasID, oldOwner->c_str()));
it->second->erase(aliasID);
busNameIDMap.erase(it);
} else {
QCC_LogError(ER_FAIL, ("Alias '%s' not in busNameIDMap", alias.c_str()));
}
}
if (newOwner) {
IDSet bnids;
BusNameIDMap::iterator it = busNameIDMap.find(*newOwner);
if (it != busNameIDMap.end()) {
assert(alias != *newOwner);
bnids = it->second;
}
if (aliasID != ID_NOT_FOUND) {
QCC_DbgPrintf(("Add %s{%d} to table for %s", alias.c_str(), aliasID, newOwner->c_str()));
bnids->insert(aliasID);
}
pair<StringMapKey, IDSet> p(alias, bnids);
busNameIDMap.insert(p);
}
lock.Unlock();
}
/**
* Rule check macros. The rule check functions all operate in the same way
* with the only difference being the arguments they take and what they check.
* This macro is the simplest way to put all the boilerplate code into one
* place. This is a case where macros work better than C++ templates and
* varargs while avoiding a cumbersome callback mechanism. This is truely a
* macro and not a macro that has function-like semantics.
*
* @param[out] _allow Whether the rule is an ALLOW or DENY rule
* @param _rl The ruleList to iterate over
* @param _it The name of the iterator variable to use (e.g. "it")
* @param _checks The checks to perform
* (e.g. "(it->CheckUser(uid) && it->CheckGroup(gid))")
*/
#ifndef NDEBUG
#define RULE_CHECKS(_allow, _rl, _it, _checks) \
PolicyRuleList::const_reverse_iterator _it; \
bool ruleMatch = false; \
policydb::PolicyPermission permission; \
size_t rc = 0; \
for (_it = _rl.rbegin(); !ruleMatch && (_it != _rl.rend()); ++_it) { \
ruleMatch = _checks; \
permission = _it->permission; \
QCC_DbgPrintf((" checking rule (%u/%u): %s - %s", \
_rl.size() - rc++, \
_rl.size(), \
_it->ruleString.c_str(), \
ruleMatch ? "MATCH" : "no match")); \
} \
if (ruleMatch) { \
_allow = (permission == policydb::POLICY_ALLOW); \
} \
return ruleMatch
#else
#define RULE_CHECKS(_allow, _rl, _it, _checks) \
PolicyRuleList::const_reverse_iterator _it; \
bool ruleMatch = false; \
policydb::PolicyPermission permission; \
for (_it = _rl.rbegin(); !ruleMatch && (_it != _rl.rend()); ++_it) { \
ruleMatch = _checks; \
permission = _it->permission; \
} \
if (ruleMatch) { \
_allow = (permission == policydb::POLICY_ALLOW); \
} \
return ruleMatch
#endif
bool _PolicyDB::CheckConnect(bool& allow, const PolicyRuleList& ruleList, uint32_t uid, uint32_t gid)
{
RULE_CHECKS(allow, ruleList, it,
(it->CheckUser(uid) && it->CheckGroup(gid)));
}
bool _PolicyDB::CheckOwn(bool& allow, const PolicyRuleList& ruleList, StringID bnid, const IDSet& prefixes)
{
RULE_CHECKS(allow, ruleList, it,
it->CheckOwn(bnid, prefixes));
}
bool _PolicyDB::CheckMessage(bool& allow, const PolicyRuleList& ruleList,
const NormalizedMsgHdr& nmh,
const IDSet& bnIDSet)
{
RULE_CHECKS(allow, ruleList, it,
(it->CheckType(nmh.type) &&
it->CheckInterface(nmh.ifcID) &&
it->CheckMember(nmh.memberID) &&
it->CheckPath(nmh.pathID, nmh.pathIDSet) &&
it->CheckError(nmh.errorID) &&
it->CheckBusName(bnIDSet)));
}
bool _PolicyDB::OKToConnect(uint32_t uid, uint32_t gid) const
{
/* Implicitly default to allow any endpoint to connect. */
bool allow = true;
bool ruleMatch = false;
QCC_DbgPrintf(("Check if OK for endpoint with UserID %u and GroupID %u to connect", uid, gid));
if (!connectRS.mandatoryRules.empty()) {
QCC_DbgPrintf((" checking mandatory connect rules"));
ruleMatch = CheckConnect(allow, connectRS.mandatoryRules, uid, gid);
}
if (!ruleMatch) {
IDRuleMap::const_iterator it = connectRS.userRules.find(uid);
if (it != connectRS.userRules.end()) {
QCC_DbgPrintf((" checking user=%u connect rules", uid));
ruleMatch = CheckConnect(allow, it->second, uid, gid);
}
}
if (!ruleMatch) {
IDRuleMap::const_iterator it = connectRS.groupRules.find(gid);
if (it != connectRS.groupRules.end()) {
QCC_DbgPrintf((" checking group=%u connect rules", gid));
ruleMatch = CheckConnect(allow, it->second, uid, gid);
}
}
if (!ruleMatch) {
QCC_DbgPrintf((" checking default connect rules"));
ruleMatch = CheckConnect(allow, connectRS.defaultRules, uid, gid);
}
return allow;
}
bool _PolicyDB::OKToOwn(const char* busName, BusEndpoint& ep) const
{
if (!busName || busName[0] == '\0' || busName[0] == ':') {
/* Can't claim ownership of a unique name, empty name, or a NULL pointer */
return false;
}
QCC_DbgPrintf(("Check if OK for endpoint %s to own %s{%d}",
ep->GetUniqueName().c_str(), busName, LookupStringID(busName)));
/* Implicitly default to allow any endpoint to own any name. */
bool allow = true;
bool ruleMatch = false;
StringID busNameID = LookupStringID(busName);
IDSet prefixes = LookupStringIDPrefix(busName, '.');
if (!ownRS.mandatoryRules.empty()) {
QCC_DbgPrintf((" checking mandatory own rules"));
ruleMatch = CheckOwn(allow, ownRS.mandatoryRules, busNameID, prefixes);
}
if (!ruleMatch && !ownRS.userRules.empty()) {
uint32_t uid = ep->GetUserId();
IDRuleMap::const_iterator it = ownRS.userRules.find(uid);
if (it != ownRS.userRules.end()) {
QCC_DbgPrintf((" checking user=%u own rules", uid));
ruleMatch = CheckOwn(allow, it->second, busNameID, prefixes);
}
}
if (!ruleMatch && !ownRS.groupRules.empty()) {
uint32_t gid = ep->GetGroupId();
IDRuleMap::const_iterator it = ownRS.groupRules.find(gid);
if (it != ownRS.groupRules.end()) {
QCC_DbgPrintf((" checking group=%u own rules", gid));
ruleMatch = CheckOwn(allow, it->second, busNameID, prefixes);
}
}
if (!ruleMatch) {
QCC_DbgPrintf((" checking default own rules"));
ruleMatch = CheckOwn(allow, ownRS.defaultRules, busNameID, prefixes);
}
return allow;
}
bool _PolicyDB::OKToReceive(const NormalizedMsgHdr& nmh, BusEndpoint& dest) const
{
/* Implicitly default to allow all messages to be received. */
bool allow = true;
bool ruleMatch = false;
if (nmh.destIDSet->empty()) {
/*
* Broadcast/multicast signal - need to re-check send rules for each
* destination.
*/
const IDSet destIDSet = LookupBusNameID(dest->GetUniqueName().c_str());
if (!destIDSet->empty()) {
allow = OKToSend(nmh, &destIDSet);
if (!allow) {
return false;
}
}
}
QCC_DbgPrintf(("Check if OK for endpoint %s to receive %s (%s{%s} --> %s{%s})",
dest->GetUniqueName().c_str(), nmh.msg->Description().c_str(),
nmh.msg->GetSender(), IDSet2String(nmh.senderIDSet).c_str(),
nmh.msg->GetDestination(), IDSet2String(nmh.destIDSet).c_str()));
if (!receiveRS.mandatoryRules.empty()) {
QCC_DbgPrintf((" checking mandatory receive rules"));
ruleMatch = CheckMessage(allow, receiveRS.mandatoryRules, nmh, nmh.senderIDSet);
}
uint32_t uid = dest->GetUserId();
if (!ruleMatch && !receiveRS.userRules.empty()) {
IDRuleMap::const_iterator it = receiveRS.userRules.find(uid);
if (it != receiveRS.userRules.end()) {
QCC_DbgPrintf((" checking user=%u receive rules", uid));
ruleMatch = CheckMessage(allow, it->second, nmh, nmh.senderIDSet);
}
}
uint32_t gid = dest->GetGroupId();
if (!ruleMatch && !receiveRS.groupRules.empty()) {
IDRuleMap::const_iterator it = receiveRS.groupRules.find(gid);
if (it != receiveRS.groupRules.end()) {
QCC_DbgPrintf((" checking group=%u receive rules", gid));
ruleMatch = CheckMessage(allow, it->second, nmh, nmh.senderIDSet);
}
}
if (!ruleMatch) {
QCC_DbgPrintf((" checking default receive rules"));
ruleMatch = CheckMessage(allow, receiveRS.defaultRules, nmh, nmh.senderIDSet);
}
return allow;
}
bool _PolicyDB::OKToSend(const NormalizedMsgHdr& nmh, const IDSet* destIDSet) const
{
/* Implicitly default to allow messages to be sent. */
bool allow = true;
bool ruleMatch = false;
if (!destIDSet) {
destIDSet = &nmh.destIDSet;
}
QCC_DbgPrintf(("Check if OK for endpoint %s to send %s (%s{%s} --> %s{%s})",
nmh.sender->GetUniqueName().c_str(), nmh.msg->Description().c_str(),
nmh.msg->GetSender(), IDSet2String(nmh.senderIDSet).c_str(),
nmh.msg->GetDestination(), IDSet2String(*destIDSet).c_str()));
if (!sendRS.mandatoryRules.empty()) {
QCC_DbgPrintf((" checking mandatory send rules"));
ruleMatch = CheckMessage(allow, sendRS.mandatoryRules, nmh, *destIDSet);
}
if (!ruleMatch && !sendRS.userRules.empty()) {
uint32_t uid = nmh.sender->GetUserId();
IDRuleMap::const_iterator it = sendRS.userRules.find(uid);
if (it != sendRS.userRules.end()) {
QCC_DbgPrintf((" checking user=%u send rules", uid));
ruleMatch = CheckMessage(allow, it->second, nmh, *destIDSet);
}
}
if (!ruleMatch && !sendRS.groupRules.empty()) {
uint32_t gid = nmh.sender->GetGroupId();
IDRuleMap::const_iterator it = sendRS.groupRules.find(gid);
if (it != sendRS.groupRules.end()) {
QCC_DbgPrintf((" checking group=%u send rules", gid));
ruleMatch = CheckMessage(allow, it->second, nmh, *destIDSet);
}
}
if (!ruleMatch) {
QCC_DbgPrintf((" checking default send rules"));
ruleMatch = CheckMessage(allow, sendRS.defaultRules, nmh, *destIDSet);
}
return allow;
}
| [
"stevek@qce.qualcomm.com"
] | stevek@qce.qualcomm.com |
e15aad7b319fc8a86c61408879d16bc93482b3e3 | 4e611ae6d0fc21a2df92113e35293eab1829f5f0 | /Bank/BankAccount.txt | 9ba3803a2d51618cb48affbd5d75f2a17375af09 | [] | no_license | phamhuuhoang99/hello-world | 1ee2d44030908711fbb3b6f9a1ce86b10138abc3 | 8245702ff18feb21ffd62cc37c4dc0c5a28ce227 | refs/heads/master | 2020-09-04T20:04:44.686339 | 2019-11-06T00:36:39 | 2019-11-06T00:36:39 | 219,877,712 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 40 | txt |
So Tai Khoan:5
So Du: 6
Ma kiem tra: 0
| [
"phamhuuhoang99@gmail.com"
] | phamhuuhoang99@gmail.com |
14273680af979558a7caa60983d7e9036f335728 | 95dc70a29e3ccdfb5cecce1cd8099691d5b6bb5d | /leetcode/palindrome_number_v2.cpp | 6e81b538f87764bd2f08b28aaeabfa5785758455 | [] | no_license | hotbig/letmetry | b19ba07e551aabb58c405695f5ed2a7fc0f57fd7 | 1418022a0d63c2cad41435d30d54b5a01773b0e5 | refs/heads/master | 2020-05-22T06:54:50.252554 | 2016-11-01T14:26:25 | 2016-11-01T14:26:25 | 36,932,799 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 853 | cpp | #include<iostream>
#include<string>
using namespace std;
class Solution{
public:
bool isPalindrome(int x){
// 111, 1, 121, -1, 12321 123321 22
int a = 0;
if(x < 0) return false;
while(x>a)
{
a = a*10 + (x%10);
x = x/10;
}
return (x == a || (a/10)==x);
}
};
int main()
{
Solution s;
cout << (s.isPalindrome(111) ? "yes":"no") << endl;
cout << (s.isPalindrome(1) ? "yes":"no") << endl;
cout << (s.isPalindrome(121) ? "yes":"no") << endl;
cout << (s.isPalindrome(-1) ? "yes":"no") << endl;
cout << (s.isPalindrome(12321) ? "yes":"no") << endl;
cout << (s.isPalindrome(123321) ? "yes":"no") << endl;
cout << (s.isPalindrome(22) ? "yes":"no") << endl;
return 0;
}
| [
"randyn.yang@gmail.com"
] | randyn.yang@gmail.com |
c0f8e48306ddfaf1d21545dc116e99ef17608b96 | 66330f7a1ff0b8447b4245474ab4de48727fd1c5 | /libs/multiprecision/performance/performance_test_files/test20.cpp | 8108310f3cc0fccbb6ef52a96ee55754b0e2a0e6 | [
"MIT"
] | permissive | everscalecodes/knapsack-snark | fd3cc6155125ae6ff0fc56aa979f84ba6a8c49c7 | 633515a13906407338a81b9874d964869ddec624 | refs/heads/main | 2023-07-18T06:05:22.319230 | 2021-08-31T16:10:16 | 2021-08-31T16:10:16 | 447,180,824 | 0 | 1 | MIT | 2022-01-12T10:53:21 | 2022-01-12T10:53:20 | null | UTF-8 | C++ | false | false | 511 | cpp | ///////////////////////////////////////////////////////////////
// Copyright 2019 John Maddock. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt
#include "../performance_test.hpp"
#if defined(TEST_CPP_INT_RATIONAL)
#include <nil/crypto3/multiprecision/cpp_int.hpp>
#endif
void test20() {
#ifdef TEST_CPP_INT_RATIONAL
test<nil::crypto3::multiprecision::cpp_rational>("cpp_rational", 1024);
#endif
}
| [
"curryrasul@gmail.com"
] | curryrasul@gmail.com |
ddf6f77d3531b64edd48c3de005de2707050500c | d1cfc0271f014ee313302f27007ef42c421967a0 | /Header Files.h | bcd8c6284a3366a3f8a350aa3910b8c2f3555ee5 | [] | no_license | manavchawla98/IndiaTourismCompany | e84e13a66bbb192e65d61534dcb4669486f75032 | 03be9f45d8be3818339a2fe7ef44ff2ce445b3a1 | refs/heads/master | 2021-01-11T20:48:01.351366 | 2017-01-17T04:04:48 | 2017-01-17T04:04:48 | 79,186,819 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 422 | h | /* Written by: Manav Chawla
Objective of File - Header Files
*/
#include<iostream>
#include<string.h>
#include<fstream>
#include"Functions.h"
#include"Classes.h"
#include"Kashmir.h"
#include"Rajasthan.h"
#include"Kerala.h"
#include"Andaman.h"
#include"Ooty.h"
#include"Goa.h"
#include"Welcome Paragraph.h"
#include"Package Selection.h"
#include"Total Cost.h"
using namespace std;
| [
"mc050898@gmail.com"
] | mc050898@gmail.com |
245af55b7045f9078fbebeddf948bd7f6fb2457d | 91a882547e393d4c4946a6c2c99186b5f72122dd | /Source/XPSP1/NT/multimedia/directx/dxvb/dx7vb/d3drmobjectarrayobj.cpp | 493c103a6b71ebcca7235ebca8117f8e6cbffcbc | [] | no_license | IAmAnubhavSaini/cryptoAlgorithm-nt5src | 94f9b46f101b983954ac6e453d0cf8d02aa76fc7 | d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2 | refs/heads/master | 2023-09-02T10:14:14.795579 | 2021-11-20T13:47:06 | 2021-11-20T13:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,044 | cpp | //+-------------------------------------------------------------------------
//
// Microsoft Windows
//
// Copyright (C) Microsoft Corporation, 1999 - 1999
//
// File: d3drmobjectarrayobj.cpp
//
//--------------------------------------------------------------------------
// d3drmFrameArrayObj.cpp : Implementation of CDirectApp and DLL registration.
#include "stdafx.h"
#include "Direct.h"
#include "dms.h"
#include "d3drmObjectArrayObj.h"
CONSTRUCTOR(_dxj_Direct3dRMObjectArray, {});
DESTRUCTOR(_dxj_Direct3dRMObjectArray, {});
GETSET_OBJECT(_dxj_Direct3dRMObjectArray);
GET_DIRECT_R(_dxj_Direct3dRMObjectArray,getSize, GetSize, long)
HRESULT C_dxj_Direct3dRMObjectArrayObject::getElement(long i, I_dxj_Direct3dRMObject **obj){
HRESULT hr;
IDirect3DRMObject *realObject=NULL;
hr=m__dxj_Direct3dRMObjectArray->GetElement((DWORD)i,&realObject);
if FAILED(hr) return hr;
//realObjects refcount is taken care of by CreateCoverObject
hr=CreateCoverObject(realObject, obj);
realObject->Release();
return hr;
}
| [
"support@cryptoalgo.cf"
] | support@cryptoalgo.cf |
83f2f5e8e2ad4de3e6bf2972e847fc6cfd7913a3 | e0387cf8f45d3e2b7ea3788b299f195a621708a8 | /Source/Sable/Graphics/Renderer/Renderer.cpp | cda53d846dddc604bd19d798ba8faed5fb48edff | [] | no_license | ClementVidal/sable.sable | eea0e822d90739269e35bed20805a2789b5fbc81 | 0ec2cd03867a4673472c1bc7b071a3f16b55fb1b | refs/heads/master | 2021-01-13T01:28:54.070144 | 2013-10-15T15:21:49 | 2013-10-15T15:21:49 | 39,085,785 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,286 | cpp | #include <Sable\Graphics\Renderer\Renderer.h>
#include <Sable\Graphics\PostProcess\PostProcess.h>
#include <Sable\Graphics\RenderTarget\Texture.h>
#include <Sable\Graphics\RenderPass\RenderPass.h>
#include <Sable\Graphics\RenderPass\Lighting.h>
#include <Sable\Graphics\Debug\RenderPass.h>
#include <Sable\Graphics\RenderPass\Depth.h>
#include <Sable\Application\Window.h>
#include <Sable\Gui\Common\RenderPass.h>
#include <Sable\Graphics\Common\Manager.h>
#include <Sable\Graphics\Node\Traversal.h>
using namespace Sable;
IMPLEMENT_MANAGED_CLASS( Sable, CRenderer );
/**
Default constructor for a renderer.
\param renderTarget The render target used a main output surface
*/
CRenderer::CRenderer( )
{
m_DebugPass = NULL;
m_GuiPass = NULL;
m_ActiveShader = NULL;
m_ActiveIndexBuffer = NULL;
m_ActiveVertexBuffer = NULL;
m_ActiveStateBlend = NULL;
m_ActiveStateDepthStencil = NULL;
m_ActiveStateRasterizer = NULL;
m_ActiveRenderTarget = NULL;
m_ActiveVertexLayout = NULL;
m_ActiveInstanceBuffer = NULL;
m_CurrentViewport = NULL;
m_ActiveDepthStencil = NULL;
m_RendererPassTable.SetCapacity( 16 );
CStatesBlend::SDesc blendDesc;
m_DefaultBlendStates.Acquire( blendDesc );
CStatesDepthStencil::SDesc dsDesc;
m_DefaultDepthStencilStates.Acquire( dsDesc );
CStatesRasterizer::SDesc srDesc;
m_DefaultRasterizerStates.Acquire( srDesc );
}
CRenderer::~CRenderer()
{
}
/**
Called by the GraphicsManager to prepare the scene before a render.\n
<b>Overloaded version MUST call the base one<b>
*/
Void CRenderer::TraverseNodeTree( const CNode& rootNode )
{
Index index;
for(index=0; index<GetRendererPassCount(); index++)
{
CRenderPass& pass = GetRendererPassAtIndex(index);
TraverseNodeTree( rootNode, pass );
}
}
/*
Void CRenderer::ClearRenderTarget( CRenderTarget& rt, CRenderTargetDepthStencil& ds )
{
RendererPassTable::Iterator it;
CRenderTarget* rtTable[8];
CRenderTarget* tmpRt;
for( Int32 i=0;i<8;i++)
{
rtTable[i] = NULL;
}
ForEachItem( it, m_RendererPassTable )
{
tmpRt = (*it)->GetRenderTarget();
if( !tmpRt )
tmpRt = &rt;
// Find if rt was already cleared
for( Int32 i=0;i<8;i++)
{
if( rtTable[i] == tmpRt )
{
tmpRt = NULL;
break;
}
}
// If rt was not already cleared
if( tmpRt )
{
tmpRt->Clear( CColor::Black );
for( Int32 i=0;i<8;i++)
{
if( rtTable[i] == NULL )
{
rtTable[i] = tmpRt;
break;
}
}
}
}
}
*/
/**
Called by the GraphicsManager to render the scene.\n
Call BeginRender, execute all the registered callback and call EndRender\n
<b>Overloaded version MUST call the base one<b>
*/
Void CRenderer::Render( CRenderTarget& rt, CRenderTargetDepthStencil& ds, CViewport& viewport )
{
CRenderPass* previous = NULL;
CRenderPass* tmp = NULL;
RendererPassTable::Iterator it;
CRenderTarget* tmpRt = NULL;
CRenderTargetDepthStencil* tmpDs = NULL;
CRenderPass* currentPass = NULL;
if(! m_View )
return;
rt.Clear( CColor::Blue );
ds.Clear( 1.0f, 0 );
if( m_View->GetWorld() )
{
TraverseNodeTree( m_View->GetWorld()->GetRootNode() );
TraverseNodeTree( m_View->GetWorld()->GetGuiRootNode() );
}
Activate( viewport );
ForEachItem( it, m_RendererPassTable )
{
if( (*it)->GetIsEnabled() )
{
currentPass = (*it);
if( ( previous == NULL ) || ( previous->GetRenderTarget() != currentPass->GetRenderTarget() ) )
tmpRt = currentPass->GetRenderTarget();
if( !tmpRt )
tmpRt = &rt;
if( !tmpDs )
tmpDs = &ds;
Activate( *tmpDs );
Activate( *tmpRt );
currentPass->Render( *this );
previous = currentPass;
}
}
}
Void CRenderer::Draw( EPrimitiveType primitive, UInt32 vertexCount, UInt32 offset )
{
GraphicsManager.GetImpl().Draw( primitive, vertexCount, offset );
}
Void CRenderer::DrawIndexed( EPrimitiveType primitive, UInt32 indexCount, UInt32 startIndexLocation, UInt32 baseVertexLocation )
{
GraphicsManager.GetImpl().DrawIndexed( primitive, indexCount, startIndexLocation, baseVertexLocation );
}
Void CRenderer::DrawInstanced( EPrimitiveType primitive, UInt32 vertexCount, UInt32 offset, UInt32 instanceCount )
{
GraphicsManager.GetImpl().DrawInstanced( primitive, vertexCount, offset, instanceCount );
}
Void CRenderer::DrawIndexedInstanced( EPrimitiveType primitive, UInt32 indexCount, UInt32 startIndexLocation, UInt32 baseVertexLocation, UInt32 instanceCount )
{
GraphicsManager.GetImpl().DrawIndexedInstanced( primitive, indexCount, startIndexLocation, baseVertexLocation, instanceCount );
}
CStatesBlend& CRenderer::GetDefaultBlendStates()
{
return m_DefaultBlendStates;
}
CStatesRasterizer& CRenderer::GetDefaultRasterizerStates()
{
return m_DefaultRasterizerStates;
}
CStatesDepthStencil& CRenderer::GetDefaultDepthStencilStates()
{
return m_DefaultDepthStencilStates;
}
/**
Initialize the renderer.\n
Iterate over all the registered CRenderPass and call their Initialize()\n
<b>Overloaded version MUST call the base one<b>
\param outputRenderTarget The render target used for output
*/
Void CRenderer::Initialize( )
{
Index index;
for(index=0; index<GetRendererPassCount(); index++)
{
GetRendererPassAtIndex(index).Initialize(*this);
}
}
/**
This will automaticaly resize all the render target of every renderpass to the given resolution
*/
Void CRenderer::Resize( const CVector2i& newSize )
{
UInt32 index;
for(index=0; index<GetRendererPassCount(); index++)
{
CRenderTarget* rt = GetRendererPassAtIndex(index).GetRenderTarget();
if( rt )
rt->Resize( newSize );
}
}
UInt32 CRenderer::GetRendererPassCount( ) const
{
return m_RendererPassTable.GetItemCount( );
}
CRenderPass& CRenderer::GetRendererPassAtIndex( UInt32 i ) const
{
return *m_RendererPassTable.GetItemAtIndex( i );
}
CRenderPass& CRenderer::GetRendererPassByType( const CTypeInfo& type ) const
{
RendererPassTable::Iterator it;
ForEachItem( it, m_RendererPassTable )
{
if( (*it)->GetTypeInfo() == type )
return *(*it);
}
return GetNullReference( CRenderPass );
}
/**
Push a render pass to the render pass stack
\return Return the index of this render pass in the stack
*/
UInt32 CRenderer::PushRenderPass( CRenderPass& pass )
{
m_RendererPassTable.PushItem( &pass );
// Automaticly grab Debug Renderer and depth pass
if( pass.GetTypeInfo().IsKindOf( CDebugRenderPass::GetStaticTypeInfo() ) )
{
m_DebugPass = (CDebugRenderPass*) &pass;
}
else if( pass.GetTypeInfo().IsKindOf( CRenderPassDepth::GetStaticTypeInfo() ) )
{
m_DepthPass = (CRenderPassDepth*) &pass;
}
else if( pass.GetTypeInfo().IsKindOf( CRenderPassLighting::GetStaticTypeInfo() ) )
{
m_LightingPass = (CRenderPassLighting*) &pass;
}
else if( pass.GetTypeInfo().IsKindOf( CGuiRenderPass::GetStaticTypeInfo() ) )
{
m_GuiPass = (CGuiRenderPass*) &pass;
}
return m_RendererPassTable.GetItemCount() - 1 ;
}
/**
UnInitialize the renderer.\n
Iterate over all the registered CRenderPass and call their UnInitialize()\n
<b>Overloaded version MUST call the base one<b>
*/
Void CRenderer::UnInitialize()
{
Index index;
for(index=0; index<GetRendererPassCount(); index++)
{
GetRendererPassAtIndex(index).UnInitialize(*this);
}
}
Void CRenderer::TraverseNodeTree( const CNode& node, CRenderPass& pass )
{
DebugProfile("CRenderer::TraverseNodeTree");
const CTypeInfo& nodeType = node.GetTypeInfo();
Bool canTraverse = TRUE;
CNodeSpatial* nodeSpatial = node.CastTo<CNodeSpatial>();
if( nodeSpatial )
{
if( ! nodeSpatial->IsVisible( *GetView()->GetCamera() ) )
{
canTraverse = FALSE;
}
}
if( canTraverse )
{
if( !pass.ProcessTraversedNode( (CNode&)node, *this ) )
return;
}
CNode* child = node.GetChild();
while( child )
{
TraverseNodeTree( *child, pass );
child = child->GetSibling();
}
}
Void CRenderer::Activate( CRenderTargetDepthStencil& ds )
{
if( &ds != m_ActiveDepthStencil )
{
ds.Activate( );
m_ActiveDepthStencil = &ds;
}
}
Void CRenderer::Activate( CRenderTarget& rt )
{
if( &rt != m_ActiveRenderTarget )
{
rt.Activate( *this, 0 );
m_ActiveRenderTarget = &rt;
}
}
Void CRenderer::Activate( CShader& shader )
{
// if( &shader != m_ActiveShader )
{
shader.Activate( *this );
m_ActiveShader = &shader;
}
}
Void CRenderer::Activate( CShaderProgram& program )
{
DebugAssert( program.GetType() != nShaderProgramType_Count && program.GetType() != nShaderProgramType_None );
if( &program != m_ActiveShaderProgram[program.GetType()] )
{
program.Activate( *this );
m_ActiveShaderProgram[program.GetType()] = &program;
}
}
Void CRenderer::Activate( CGeometryInstanceBuffer& ib, UInt32 index )
{
//if( &ib != m_ActiveInstanceBuffer )
{
ib.Activate( *this, index );
m_ActiveInstanceBuffer = &ib;
}
}
Void CRenderer::Activate( CGeometryIndexBuffer& ib )
{
if( &ib != m_ActiveIndexBuffer )
{
ib.Activate( *this );
m_ActiveIndexBuffer = &ib;
}
}
Void CRenderer::Activate( CViewport& vpt )
{
if( &vpt != m_CurrentViewport )
{
vpt.Activate( );
m_CurrentViewport = &vpt;
}
}
Void CRenderer::Activate( CGeometryVertexLayout& vl )
{
//if( &vl != m_ActiveVertexLayout )
{
vl.Activate( *this );
m_ActiveVertexLayout = &vl;
}
}
Void CRenderer::Activate( CGeometryVertexBuffer& vb, UInt32 index )
{
// if( &vb != m_ActiveVertexBuffer )
{
vb.Activate( *this, index );
m_ActiveVertexBuffer = &vb;
}
}
CSceneView* CRenderer::GetView( ) const
{
return m_View;
}
Void CRenderer::SetView( CSceneView* view )
{
m_View = view;
}
CDebugRenderPass* CRenderer::GetDebugRenderPass() const
{
return m_DebugPass;
}
CRenderPassDepth* CRenderer::GetDepthRenderPass() const
{
return m_DepthPass;
}
CRenderPassLighting* CRenderer::GetLightingRenderPass() const
{
return m_LightingPass;
}
CGuiRenderPass* CRenderer::GetGuiRenderPass() const
{
return m_GuiPass;
}
CViewport* CRenderer::GetCurrentViewport() const
{
return m_CurrentViewport;
}
Void CRenderer::Activate( CStatesRasterizer& sr )
{
//if( &sr != m_ActiveStateRasterizer )
{
sr.Activate( *this );
m_ActiveStateRasterizer = &sr;
}
}
Void CRenderer::Activate( CStatesDepthStencil& ds )
{
//if( &ds != m_ActiveStateDepthStencil )
{
ds.Activate( *this );
m_ActiveStateDepthStencil = &ds;
}
}
Void CRenderer::Activate( CStatesBlend& bl )
{
//if( &bl != m_ActiveStateBlend )
{
bl.Activate( *this );
m_ActiveStateBlend = &bl;
}
}
| [
"clement.vidal@lam.fr"
] | clement.vidal@lam.fr |
96fad165ab663a00b9e08b493cd2a674b9f0ee1d | f121d8685c88bd72276a3af15eea29ee102def0a | /ios/ios_standard/NinjaCat_ios_390/WiEngine/headers/WiEngine/include/astar/wyAStarTile.h | ca37057109db07289a9d5fcce91d3a755e19e67b | [] | no_license | yeadong/Game-ResidentZombies | 5aa1989c006b0fe513ae887d4110e56d58364190 | 3a6205eb897e178864f4759b806dd44fab8cbdba | refs/heads/master | 2020-03-16T21:30:27.750524 | 2018-05-07T01:58:37 | 2018-05-07T01:58:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,089 | h | #ifndef __wyAStarTile_h__
#define __wyAStarTile_h__
#include "wyArray.h"
#include "wyObject.h"
#define TILE_FREE 0
#define TILE_BLOCKED 1
/**
* @class wyAStarTile
*
* A*地图状况tile封装
*/
class WIENGINE_API wyAStarTile : public wyObject {
private:
/// tile状态, free或者block
int m_type;
/// g值得影响值, 默认为1
float m_gRate;
/// tile x value
int m_x;
/// tile y value
int m_y;
/// 子节点\link wyArray wyArray\endlink对象指针, 封装\link wyAStarTile wyAStarTile\endlink对象指针
wyArray* m_childs;
public:
/**
* 构造函数
*
* @param type tile状态, free或者block
* @param x tile x值
* @param y tile y值
*/
wyAStarTile(int type, int x, int y);
/**
* 析构函数
*/
virtual ~wyAStarTile();
/**
* 返回g值得影响值
*
* @return g值得影响值
*/
float getGRate() { return m_gRate; }
/**
* 设置g值得影响值
*
* @param gRate g值得影响值
*/
void setGRate(float gRate) { m_gRate = gRate; }
/**
* 返回tile x值
*
* @return tile x值
*/
int getX() { return m_x; }
/**
* 返回tile y值
*
* @return tile y值
*/
int getY() { return m_y; }
/**
* 返回tile状态, free或者block
*
* @return tile状态, free或者block
*/
int getType() { return m_type; }
/**
* 设置tile状态, free或者block
*
* @param type tile状态
*/
void setType(int type) { m_type = type; }
/**
* 判断是否为block状态
*
* @return true为block状态
*/
bool isBlocked() { return m_type == TILE_BLOCKED; }
/**
* 判断是否为free状态
*
* @return true为free状态
*/
bool isFree() { return m_type == TILE_FREE; }
/**
* 增加子节点\link wyAStarTile wyAStarTile\endlink对象指针
*
* @param tile 子节点\link wyAStarTile wyAStarTile\endlink对象指针
*/
void pushChild(wyAStarTile* tile);
/**
* 返回子节点\link wyArray wyArray\endlink对象指针
*
* @return 子节点\link wyArray wyArray\endlink对象指针
*/
wyArray* getChilds() { return m_childs; }
};
#endif // __wyAStarTile_h__
| [
"garrett.wu@hotmail.com"
] | garrett.wu@hotmail.com |
b6379369b9a5c562e40f827384686f859638f4b0 | 7fea4ad59786056397a0cf6b872dd77366d436bc | /misc/Optimal_BST.cpp | 311b3506924ce699a924048aaa261917558b0c91 | [] | no_license | anmolp14/summer17_codes | 6dadc636904a958cdc5f425bb31beadeae70336e | ac098b5598ba793c3a60a53fbc9c31d89e9eb835 | refs/heads/master | 2021-01-20T13:45:20.775469 | 2017-11-06T19:40:54 | 2017-11-06T19:40:54 | 90,524,744 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,303 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n; cin >> n;
float p[n+1],q[n+1],p1,q1;
for( int i=1; i<=n ; i++)
{ cin >> p1; p[i]=p1; }
for( int i=0; i < n+1; i++)
{ cin >> q1; q[i]=q1; }
float a[n+1][n+1];
for( int i=1; i<=n; i++)
{
for( int j=i; j<=n; j++)
{
a[i][j]=0;
for( int k=i; k<=j; k++)
{
a[i][j] += p[k];
a[i][j] += q[k-1];
}
a[i][j]+=q[j];
cout << a[i][j] << ' ';
}
cout << endl;
}
int root[n+1][n+1]; float w[n+1][n+1];
for( int i=0 ; i <=n; i++ )
{ w[i][0] = 0; }
for( int i =1 ; i<n+1 ; i++ )
{
for( int j=1; j<=n-i+1 ; j++)
{
if(i==1 )
{
root[j][i] = j;
w[j][i] = ( q[j-1] + q[j] ) * 2.0 + p[j];
}
else
{
int r; float mi = -1.0;
for(int k=j; k<j+i; k++)
{
if( mi == -1.0 || mi > w[j][k-j] + w[k+1][j+i-k-1] + a[j][j+i-1])
{
mi = w[j][k-j] + w[k+1][j+i-k-1] + a[j][j+i-1] ;
r=k;
}
}
root[j][i] = r;
w[j][i] = mi;
}
}
}
cout << w[1][n] << endl << root[1][n] << endl;
for( int i =1 ; i<n+1 ; i++ )
{
for( int j=1; j<=n-i+1 ; j++)
{ cout << w[i][j] << ' ' << ' ' ;}
cout << endl;
}
for( int i =1 ; i<n+1 ; i++ )
{
for( int j=1; j<=n-i+1 ; j++)
{ cout << root[i][j] << ' ' << ' ' ;}
cout << endl;
}
return 0;
}
| [
"anmolporwal14@gmail.com"
] | anmolporwal14@gmail.com |
a0756862c8ef9c5b67594c38fc3c770af99e422d | 3b97b786b99c3e4e72bf8fe211bb710ecb674f2b | /TClient_Branch101012/TClient/Tools/TConfigMP/TConfigMPDlg.cpp | 077c6e263478bbc68ac6749fecdbfb75fa4e680a | [] | no_license | moooncloud/4s | 930384e065d5172cd690c3d858fdaaa6c7fdcb34 | a36a5785cc20da19cd460afa92a3f96e18ecd026 | refs/heads/master | 2023-03-17T10:47:28.154021 | 2017-04-20T21:42:01 | 2017-04-20T21:42:01 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 10,232 | cpp | // TConfigMPDlg.cpp : 구현 파일
//
#include "stdafx.h"
#include "TConfigMP.h"
#include "TConfigMPDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// 응용 프로그램 정보에 사용되는 CAboutDlg 대화 상자입니다.
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// 대화 상자 데이터
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 지원
// 구현
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()
// CTConfigMPDlg 대화 상자
CTConfigMPDlg::CTConfigMPDlg(CWnd* pParent /*=NULL*/)
: CDialog(CTConfigMPDlg::IDD, pParent)
, m_strMainPE(_T(""))
, m_strDEST(_T(""))
, m_strSRC(_T(""))
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CTConfigMPDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Text(pDX, IDC_EDIT_MAIN_PE, m_strMainPE);
DDX_Text(pDX, IDC_EDIT_DEST, m_strDEST);
DDX_Text(pDX, IDC_EDIT_SRC, m_strSRC);
DDX_Control(pDX, IDC_BUTTON_MAIN_PE, m_cMainPE);
DDX_Control(pDX, IDC_BUTTON_DEST, m_cDEST);
DDX_Control(pDX, IDC_BUTTON_SRC, m_cSRC);
}
BEGIN_MESSAGE_MAP(CTConfigMPDlg, CDialog)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
//}}AFX_MSG_MAP
ON_BN_CLICKED(IDC_BUTTON_MAIN_PE, OnBnClickedButtonMainPe)
ON_BN_CLICKED(IDC_BUTTON_DEST, OnBnClickedButtonDest)
ON_BN_CLICKED(IDC_BUTTON_SRC, OnBnClickedButtonSrc)
ON_BN_CLICKED(ID_COMPILE, OnBnClickedCompile)
END_MESSAGE_MAP()
// CTConfigMPDlg 메시지 처리기
BOOL CTConfigMPDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// 시스템 메뉴에 "정보..." 메뉴 항목을 추가합니다.
// IDM_ABOUTBOX는 시스템 명령 범위에 있어야 합니다.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// 이 대화 상자의 아이콘을 설정합니다. 응용 프로그램의 주 창이 대화 상자가 아닐 경우에는
// 프레임워크가 이 작업을 자동으로 수행합니다.
SetIcon(m_hIcon, TRUE); // 큰 아이콘을 설정합니다.
SetIcon(m_hIcon, FALSE); // 작은 아이콘을 설정합니다.
// TODO: 여기에 추가 초기화 작업을 추가합니다.
HICON hIcon = AfxGetApp()->LoadIcon(IDI_ICON_FOLDER);
m_cMainPE.SetIcon(hIcon);
m_cDEST.SetIcon(hIcon);
m_cSRC.SetIcon(hIcon);
srand(::GetCurrentTime());
return TRUE; // 컨트롤에 대한 포커스를 설정하지 않을 경우 TRUE를 반환합니다.
}
void CTConfigMPDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// 대화 상자에 최소화 단추를 추가할 경우 아이콘을 그리려면
// 아래 코드가 필요합니다. 문서/뷰 모델을 사용하는 MFC 응용 프로그램의 경우에는
// 프레임워크에서 이 작업을 자동으로 수행합니다.
void CTConfigMPDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // 그리기를 위한 디바이스 컨텍스트
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// 클라이언트 사각형에서 아이콘을 가운데에 맞춥니다.
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// 아이콘을 그립니다.
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// 사용자가 최소화된 창을 끄는 동안에 커서가 표시되도록 시스템에서
// 이 함수를 호출합니다.
HCURSOR CTConfigMPDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CTConfigMPDlg::OnBnClickedButtonMainPe()
{
CFileDialog dlg(
TRUE,
_T("*.exe"),
NULL,
OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,
_T("PE Files (*.exe)|*.exe|All Files (*.*)|*.*||"));
dlg.m_ofn.lpstrInitialDir = LPCSTR(m_strMAINPEFOLDER);
if( dlg.DoModal() == IDOK )
{
UpdateData();
m_strMAINPEFOLDER = dlg.GetFileName();
m_strMainPE = dlg.GetPathName();
m_strMAINPEFOLDER = m_strMainPE.Left(m_strMainPE.GetLength() - m_strMAINPEFOLDER.GetLength());
UpdateData(FALSE);
}
}
void CTConfigMPDlg::OnBnClickedButtonDest()
{
CFileDialog dlg(
FALSE,
_T("*.mpc"),
"TClientMP",
OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,
_T("Module Protector Config Files (*.mpc)|*.mpc||"));
dlg.m_ofn.lpstrInitialDir = LPCSTR(m_strDESTFOLDER);
if( dlg.DoModal() == IDOK )
{
UpdateData();
m_strDESTFOLDER = dlg.GetFileName();
m_strDEST = dlg.GetPathName();
m_strDESTFOLDER = m_strDEST.Left(m_strDEST.GetLength() - m_strDESTFOLDER.GetLength());
UpdateData(FALSE);
}
}
void CTConfigMPDlg::OnBnClickedButtonSrc()
{
CFileDialog dlg(
TRUE,
_T("*.txt"),
NULL,
OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,
_T("Module list Files (*.txt)|*.txt|All Files (*.*)|*.*||"));
dlg.m_ofn.lpstrInitialDir = LPCSTR(m_strSRCFOLDER);
if( dlg.DoModal() == IDOK )
{
UpdateData();
m_strSRCFOLDER = dlg.GetFileName();
m_strSRC = dlg.GetPathName();
m_strSRCFOLDER = m_strSRC.Left(m_strSRC.GetLength() - m_strSRCFOLDER.GetLength());
UpdateData(FALSE);
}
}
void CTConfigMPDlg::OnBnClickedCompile()
{
UpdateData();
m_strMainPE.Trim();
m_strDEST.Trim();
m_strSRC.Trim();
if( m_strMainPE.IsEmpty() ||
m_strDEST.IsEmpty() ||
m_strSRC.IsEmpty() )
{
AfxMessageBox(IDS_ERROR_WRONG_PARAM);
return;
}
CFile vDEST( LPCSTR(m_strDEST), CFile::modeCreate|CFile::modeWrite|CFile::typeBinary);
BYTE vMASK[TMAX_CHECK_CODE_SIZE] = {
BYTE(rand() % 256),
BYTE(rand() % 256),
BYTE(rand() % 256),
BYTE(rand() % 256),
BYTE(rand() % 256),
BYTE(rand() % 256),
BYTE(rand() % 256)};
BYTE bMASK = BYTE(rand() % (TMAX_CHECK_CODE_SIZE - TMIN_CHECK_CODE_SIZE + 1)) + TMIN_CHECK_CODE_SIZE;
BYTE bMIDX = 0;
vDEST.Write( &bMASK, sizeof(BYTE));
vDEST.Write( vMASK, bMASK);
if(BuildPEINFO( &vDEST, vMASK, &bMIDX, bMASK))
{
BuildMODULEINFO( &vDEST, vMASK, &bMIDX, bMASK);
AfxMessageBox(IDS_SUCCESS);
}
}
BYTE CTConfigMPDlg::BuildPEINFO( CFile *pFile,
LPBYTE pMASK,
LPBYTE pMIDX,
BYTE bMASK)
{
CFile vMAIN( LPCSTR(m_strMainPE), CFile::modeRead|CFile::typeBinary);
DWORD dwLength = (DWORD) vMAIN.GetLength();
if(!dwLength)
{
CString strNAME = pFile->GetFilePath();
pFile->Close();
DeleteFile(LPCSTR(strNAME));
AfxMessageBox(IDS_ERROR_SIZE);
return FALSE;
}
LPBYTE pMAIN = new BYTE[dwLength];
vMAIN.Read( pMAIN, dwLength);
PIMAGE_NT_HEADERS pNTMAIN = GetNTHeader(pMAIN);
if(!pNTMAIN)
{
CString strNAME = pFile->GetFilePath();
pFile->Close();
DeleteFile(LPCSTR(strNAME));
AfxMessageBox(IDS_ERROR_INVALID_PE);
if(pMAIN)
{
delete[] pMAIN;
pMAIN = NULL;
}
return FALSE;
}
WriteDATA( &pNTMAIN->FileHeader.TimeDateStamp, pFile, pMASK, pMIDX, bMASK, sizeof(DWORD));
if(pMAIN)
{
delete[] pMAIN;
pMAIN = NULL;
}
return TRUE;
}
PIMAGE_NT_HEADERS CTConfigMPDlg::GetNTHeader( LPBYTE pDATA)
{
PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER) pDATA;
if( pDOS->e_magic != IMAGE_DOS_SIGNATURE )
return NULL;
PIMAGE_NT_HEADERS pNT = (PIMAGE_NT_HEADERS) (pDATA + pDOS->e_lfanew);
if( pNT->Signature != IMAGE_NT_SIGNATURE )
return NULL;
return pNT;
}
void CTConfigMPDlg::BuildMODULEINFO( CFile *pFile,
LPBYTE pMASK,
LPBYTE pMIDX,
BYTE bMASK)
{
CStdioFile vSRC( LPCSTR(m_strSRC), CFile::modeRead|CFile::typeText);
CString strESSMODULE(_T("Kernel32"));
CString strESSPROC[TESSPROC_COUNT] = {
CString(_T("CheckRemoteDebuggerPresent")),
CString(_T("IsDebuggerPresent"))};
CString strDATA = ReadString(&vSRC);
DWORD dwMCOUNT;
WORD wDATA;
sscanf( LPCSTR(strDATA), _T("%d"), &dwMCOUNT);
wDATA = WORD(dwMCOUNT);
WriteDATA( &wDATA, pFile, pMASK, pMIDX, bMASK, sizeof(WORD));
for( DWORD i=0; i<dwMCOUNT; i++)
{
strDATA = ReadString(&vSRC);
WriteString( &strDATA, pFile, pMASK, pMIDX, bMASK);
}
WriteString( &strESSMODULE, pFile, pMASK, pMIDX, bMASK);
for( i=0; i<TESSPROC_COUNT; i++)
WriteString( &strESSPROC[i], pFile, pMASK, pMIDX, bMASK);
strDATA = ReadString(&vSRC);
sscanf( LPCSTR(strDATA), _T("%d"), &dwMCOUNT);
wDATA = WORD(dwMCOUNT);
WriteDATA( &wDATA, pFile, pMASK, pMIDX, bMASK, sizeof(WORD));
for( i=0; i<dwMCOUNT; i++)
{
BYTE vTEXTBUF[MAX_PATH];
DWORD dwPCOUNT;
strDATA = ReadString(&vSRC);
ZeroMemory( vTEXTBUF, MAX_PATH);
sscanf( LPCSTR(strDATA), _T("%s %d"), vTEXTBUF, &dwPCOUNT);
wDATA = WORD(dwPCOUNT);
WriteDATA( &wDATA, pFile, pMASK, pMIDX, bMASK, sizeof(WORD));
WriteString( &CString(vTEXTBUF), pFile, pMASK, pMIDX, bMASK);
for( DWORD j=0; j<dwPCOUNT; j++)
{
strDATA = ReadString(&vSRC);
WriteString( &strDATA, pFile, pMASK, pMIDX, bMASK);
}
}
}
CString CTConfigMPDlg::ReadString( CStdioFile *pFILE)
{
CString strRESULT;
do
{
if(!pFILE->ReadString(strRESULT))
{
strRESULT.Empty();
return strRESULT;
}
strRESULT.TrimRight();
strRESULT.TrimLeft();
} while( strRESULT.IsEmpty() || strRESULT.GetAt(0) == ';' );
return strRESULT;
}
void CTConfigMPDlg::WriteDATA( LPVOID pDATA,
CFile *pFile,
LPBYTE pMASK,
LPBYTE pMIDX,
BYTE bMASK,
int nSIZE)
{
LPBYTE pBUF = (LPBYTE) pDATA;
for( int i=0; i<nSIZE; i++)
{
BYTE bCH = pBUF[i] ^ pMASK[(*pMIDX)];
(*pMIDX) = ((*pMIDX) + 1) % bMASK;
pFile->Write( &bCH, sizeof(BYTE));
}
}
void CTConfigMPDlg::WriteString( CString *pTEXT,
CFile *pFile,
LPBYTE pMASK,
LPBYTE pMIDX,
BYTE bMASK)
{
WORD wSIZE = (WORD) pTEXT->GetLength();
WriteDATA(
&wSIZE,
pFile,
pMASK,
pMIDX,
bMASK,
sizeof(WORD));
WriteDATA(
(LPVOID) LPCSTR(*pTEXT),
pFile,
pMASK,
pMIDX,
bMASK,
wSIZE);
}
| [
"great.mafia2010@gmail.com"
] | great.mafia2010@gmail.com |
12061388fe1580952c8a29a0411e402fb64a20f6 | 15f6b119c19db8471210fc99650a1974c27fbc4c | /A/1187A.cpp | 2123df8a89341579eeecfbfdf890c237372956fd | [] | no_license | AsifWatson/codeforces | 8d1afd7f56fe84836e770d2de68f9caad596480b | ee38a5e8c19a54588fecf4f26986975e258e3b6b | refs/heads/master | 2021-07-12T23:33:54.021007 | 2021-02-28T14:06:09 | 2021-02-28T14:06:09 | 234,949,673 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 821 | cpp | #include "bits/stdc++.h"
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define all(v) v.begin(),v.end()
#define allre(v) v.rbegin(),v.rend()
#define sp(x,y) fixed<<setprecision(y)<<x
#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))
#define GCD(a,b) __gcd(a,b)
#define LCM(a,b) ((a*b)/__gcd(a,b))
using namespace std;
const double pi = acos(-1.0);
const double EPS = 1e-6;
const int MOD = (int)1e9+7;
bool Reverse(long long a,long long b){return a>b;}
bool compare(pair<long long,long long> a,pair<long long,long long> b)
{
if(a.first==b.first)return a.second>b.second;
return a.first<b.first;
}
int main()
{
IOS
int t;
cin>>t;
while(t--)
{
long long n,s,t;
cin>>n>>s>>t;
cout<<max((n-s),(n-t))+1<<endl;
}
return 0;
}
| [
"ashfaqislam33@gmail.com"
] | ashfaqislam33@gmail.com |
6f4abbe82460c65b4b04fba9b5ce784831a051de | fe94014ab341d2f5493dabd5dba57b4e3f52ca10 | /01/Solution0.4/my_lib.cpp | c6322eb47dbd9858dfd346a8d5a124e930ae1d5c | [] | no_license | DaveMSU/Machine-Graphics | 6ce3944fc90cebd661a85e6ff04c155b73b7a43c | d19c9338392bfdd98fc98fb2cb455bbf2235cb9a | refs/heads/master | 2021-04-23T20:28:33.292810 | 2020-04-05T20:51:46 | 2020-04-05T20:51:46 | 249,996,660 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,965 | cpp | #include <cmath>
#include <iostream>
#include <fstream>
#include <vector>
#include "geometry.h" // Кастомная библиотека для работы с геометрическими объектами посредством законов алгебры.
#include "my_lib.h" // Основная библ-ка, в кот-ой нах-ся описания и справки всех функций.
bool scene_intersect( Vec3f orig, // Вернуть const и &!!!!!!!!!!
Vec3f dir, // Вернуть const и &!!!!!!!!!!!
std::vector <Sphere>& spheres,
std::vector <Light>& lights,
Material& this_material ){ // Вернуть const перед vector<...>!
float dist; // Расстояние до текущего объекта.
float min_dist = -1; // Расстояние до ближайшего объекта.
int min_index = -1; // Индекс ближайшего объекта.
for( int i = 0; i < spheres.size(); ++i ){
dist = spheres[i].ray_intersect( orig, dir );
if( min_index == -1 && dist != -1 ){
min_dist = dist;
min_index = i;
}
else
if( dist != -1 )
if( min_dist > dist ){
min_dist = dist;
min_index = i;
}
}
if( min_index != -1 ){
float all_cur_point_intensity = 0;
this_material = spheres[min_index].material;
for( int i = 0; i < lights.size(); ++i ){
Vec3f cur_point = orig + dir * min_dist; // Р.вектор точки, в кот. считаем цвет.
Vec3f cur_light_dir = cur_point - lights[i].position;
float cur_intensity_koef = sqrt(cur_light_dir * cur_light_dir);// Сферы дальше - света меньше.
Vec3f sphere_normal = cur_point - spheres[min_index].center;
cur_light_dir.normalize();
sphere_normal.normalize();
float cur_point_intensity = -(cur_light_dir * sphere_normal);
all_cur_point_intensity += cur_point_intensity * lights[i].intensity / cur_intensity_koef;
}
this_material.diffuse_color = this_material.diffuse_color * all_cur_point_intensity;
return true;
}
return false;
}
Vec3f cast_ray( const Vec3f& orig,
const Vec3f& dir,
std::vector <Sphere> spheres,
std::vector <Light> lights ){ // Поставить const!!!!! и &!!!!!
Material this_material;
// Бросаем луч, пишем в пиксель цвет ближайшего объекта с учетом угла и интенсивности света от источников.
if( scene_intersect( orig, dir, spheres, lights, this_material ) )
return this_material.diffuse_color;
return Vec3f( 0.2, 0.7, 0.8 ); // Фон.
}
// Рисуем композицию - если луч пересекает объект, то ставим соотв. цвету объекта пиксель с учетом падения света.
void render( const std::vector <Sphere>& objects, const std::vector <Light>& lights ){
const int width = 1024;
const int height = 768;
std::vector<Vec3f> framebuffer( width * height );
for ( size_t j = 0; j < height; j++ )
for ( size_t i = 0; i < width; i++ ){
float x = (width/(float)height)*(i - float(width)/2)/float(width);
float y = -(j - float(height)/2)/float(height);
Vec3f dir = Vec3f(x,y, 1); // +x = направо, +y = вверх, +z = вдаль.
dir.normalize(); // Приводим к длину вектора dir к равной 1, сохраняя направление.
framebuffer[i+j*width] = cast_ray( Vec3f(0,0,0), dir, objects, lights );
}
std::ofstream ofs; // save the framebuffer to file.
ofs.open("./out.ppm");
ofs << "P6\n" << width << " " << height << "\n255\n";
for ( size_t i = 0; i < height*width; ++i )
for( size_t j = 0; j < 3; ++j )
ofs << (char)( 255 * std::max( 0.f, std::min(1.f, framebuffer[i][j] )) );
ofs.close();
}
//----------------------------------------Light:-------------------------------------------------------
Light::Light( const Vec3f& p, const float& i ) : position(p), intensity(i) {}
//----------------------------------------Material:-----------------------------------------------------
Material::Material( const Vec3f& color ) : diffuse_color(color) {}
Material::Material(){}
Material Material::operator*( const float number ){ // Умножения материала (пока только цвета) на число.
Material tmp;
tmp.diffuse_color = this->diffuse_color * number;
return tmp;
}
float Material::operator*( const Material& right ){ // Умножение материала (пока только цвета) на материал (скалярно).
float scalar;
scalar = this->diffuse_color * right.diffuse_color;
return scalar;
}
//----------------------------------------Sphere:-------------------------------------------------------
Sphere::Sphere( const Vec3f& c, const float& r, const Material& m ): center(c), radius(r), material(m) {}
// >0 - растояние до пересечения, -1 - не пересекает. (подробней см. my_lib.h)
float Sphere::ray_intersect( const Vec3f& orig, const Vec3f& dir ){
Vec3f L = center - orig;
float cosFI = L*dir / (sqrt(L*L) * sqrt(dir*dir));// cos(dir,радиус-вектор ц/c).
float r2 = radius*radius;
float d2 = L*L*(1 - cosFI*cosFI);
if( d2 > r2 )
return -1; // Расстояние до ПРЯМОЙ больше радуса.
if( cosFI < 0 )
return -1; // 'Смотрят' в разные полупространства (стороны).
float dist_to_center2 = center*center; // Квадрат расстояния от источника света до центра сферы.
float dist_d = sqrt(dist_to_center2 + d2); // 'почти' Расстояние до сферы.
float d = sqrt(r2 - d2); // То самое 'почти'.
return dist_d - d;
}
| [
"noreply@github.com"
] | noreply@github.com |
09ddcffcc9561ac29f116bc68f876e4b234ed099 | 509292a51bc529392bd631b7c47b598915e1f82b | /src/sdsdkv-impl.h | 1ee945e6aff438013776ac09b2f93cd1a24ec5b3 | [
"BSD-3-Clause"
] | permissive | mochi-hpc/mochi-sdsdkv | 5f50660522ae6f944c147b0597bbe6b59d98f41d | 51f3dae9eb48a5c9b93969a4a16c2606fe7f3102 | refs/heads/main | 2023-08-22T15:06:18.678109 | 2021-10-11T18:01:19 | 2021-10-11T18:01:19 | 343,360,144 | 0 | 1 | BSD-3-Clause | 2021-04-28T23:42:16 | 2021-03-01T09:32:25 | C++ | UTF-8 | C++ | false | false | 2,428 | h | /*
* Copyright (c) 2018 Los Alamos National Security, LLC
* All rights reserved.
*
* This file is part of the sdsdkv project. See the LICENSE file at the
* top-level directory of this distribution.
*/
/**
* @file sdsdkv-impl.h
*/
#pragma once
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "sdsdkv-personality-factory.h"
#include "sdsdkv-mpi.h"
#include "sdsdkv-config.h"
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#include <iostream>
#include <stdexcept>
/** sdsdkv Implementation. */
class sdsdkv_impl {
//
personality *m_personality;
//
sdsdkv_mpi *m_mpi;
//
sdsdkv_iconfig *m_config;
//
public:
//
sdsdkv_impl(void)
: m_personality(nullptr)
, m_mpi(nullptr)
, m_config(nullptr) { }
//
~sdsdkv_impl(void)
{
delete m_personality;
delete m_mpi;
delete m_config;
}
//
int
init(
const sdsdkv_config &config
) {
// Cache user-provided configuration.
m_config = new sdsdkv_iconfig();
int rc = m_config->init(config);
if (rc != SDSDKV_SUCCESS) return rc;
// Create and initialize MPI infrastructure.
m_mpi = new sdsdkv_mpi();
rc = m_mpi->init(*m_config);
if (rc != SDSDKV_SUCCESS) return rc;
// Create and initialize personality instance based on configury.
rc = personality_factory::create(
m_config->personality,
&m_personality
);
if (rc != SDSDKV_SUCCESS) return rc;
//
rc = m_personality->init(m_mpi, config);
if (rc != SDSDKV_SUCCESS) return rc;
//
return SDSDKV_SUCCESS;
}
//
int
open(void)
{
return m_personality->open();
}
//
int
close(void)
{
return m_personality->close();
}
//
int
put(
const void *key,
uint64_t key_size,
const void *value,
uint64_t value_size
) {
return m_personality->put(key, key_size, value, value_size);
}
//
int
get(
const void *key,
uint64_t key_size,
void *value,
uint64_t *value_size
) {
return m_personality->get(key, key_size, value, value_size);
}
};
/*
* vim: ft=cpp ts=4 sts=4 sw=4 expandtab
*/
| [
"samuel@lanl.gov"
] | samuel@lanl.gov |
8dfaa0a72ef8170c34eced6169cfb06bb7541217 | 0f0dbd04f57e3b7804915fba01e0d5e05d663ce5 | /XYZEngine/vendor/asio/include/asio/detail/handler_work.hpp | 089023f1e513e880763ae4f1845aab52a706f16b | [
"Apache-2.0",
"BSL-1.0"
] | permissive | blizmax/XYZEngine-Public | 1585ccdcc779ca2d2a4084dcf8923df6f11cd919 | b6b72708af69b07ed2c04003a06de8289ccb486b | refs/heads/master | 2023-06-07T07:08:48.280760 | 2021-07-01T20:02:16 | 2021-07-01T20:02:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,700 | hpp | //
// detail/handler_work.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_DETAIL_HANDLER_WORK_HPP
#define ASIO_DETAIL_HANDLER_WORK_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/associated_executor.hpp"
#include "asio/detail/handler_invoke_helpers.hpp"
#include "asio/detail/type_traits.hpp"
#include "asio/execution/allocator.hpp"
#include "asio/execution/blocking.hpp"
#include "asio/execution/execute.hpp"
#include "asio/execution/executor.hpp"
#include "asio/execution/outstanding_work.hpp"
#include "asio/executor_work_guard.hpp"
#include "asio/prefer.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
class executor;
class io_context;
namespace execution {
#if defined(ASIO_HAS_VARIADIC_TEMPLATES)
template <typename...> class any_executor;
#else // defined(ASIO_HAS_VARIADIC_TEMPLATES)
template <typename, typename, typename, typename, typename,
typename, typename, typename, typename> class any_executor;
#endif // defined(ASIO_HAS_VARIADIC_TEMPLATES)
} // namespace execution
namespace detail {
template <typename Executor, typename CandidateExecutor = void,
typename IoContext = io_context,
typename PolymorphicExecutor = executor, typename = void>
class handler_work_base
{
public:
explicit handler_work_base(int, int, const Executor& ex) ASIO_NOEXCEPT
: executor_(asio::prefer(ex, execution::outstanding_work.tracked))
{
}
template <typename OtherExecutor>
handler_work_base(const Executor& ex,
const OtherExecutor&) ASIO_NOEXCEPT
: executor_(asio::prefer(ex, execution::outstanding_work.tracked))
{
}
handler_work_base(const handler_work_base& other) ASIO_NOEXCEPT
: executor_(other.executor_)
{
}
#if defined(ASIO_HAS_MOVE)
handler_work_base(handler_work_base&& other) ASIO_NOEXCEPT
: executor_(ASIO_MOVE_CAST(executor_type)(other.executor_))
{
}
#endif // defined(ASIO_HAS_MOVE)
bool owns_work() const ASIO_NOEXCEPT
{
return true;
}
template <typename Function, typename Handler>
void dispatch(Function& function, Handler& handler)
{
execution::execute(
asio::prefer(executor_,
execution::blocking.possibly,
execution::allocator((get_associated_allocator)(handler))),
ASIO_MOVE_CAST(Function)(function));
}
private:
typedef typename decay<
typename prefer_result<Executor,
execution::outstanding_work_t::tracked_t
>::type
>::type executor_type;
executor_type executor_;
};
template <typename Executor, typename CandidateExecutor,
typename IoContext, typename PolymorphicExecutor>
class handler_work_base<Executor, CandidateExecutor,
IoContext, PolymorphicExecutor,
typename enable_if<
!execution::is_executor<Executor>::value
&& (!is_same<Executor, PolymorphicExecutor>::value
|| !is_same<CandidateExecutor, void>::value)
>::type>
{
public:
explicit handler_work_base(int, int, const Executor& ex) ASIO_NOEXCEPT
: executor_(ex),
owns_work_(true)
{
executor_.on_work_started();
}
handler_work_base(const Executor& ex,
const Executor& candidate) ASIO_NOEXCEPT
: executor_(ex),
owns_work_(ex != candidate)
{
if (owns_work_)
executor_.on_work_started();
}
template <typename OtherExecutor>
handler_work_base(const Executor& ex,
const OtherExecutor&) ASIO_NOEXCEPT
: executor_(ex),
owns_work_(true)
{
executor_.on_work_started();
}
handler_work_base(const handler_work_base& other) ASIO_NOEXCEPT
: executor_(other.executor_),
owns_work_(other.owns_work_)
{
if (owns_work_)
executor_.on_work_started();
}
#if defined(ASIO_HAS_MOVE)
handler_work_base(handler_work_base&& other) ASIO_NOEXCEPT
: executor_(ASIO_MOVE_CAST(Executor)(other.executor_)),
owns_work_(other.owns_work_)
{
other.owns_work_ = false;
}
#endif // defined(ASIO_HAS_MOVE)
~handler_work_base()
{
if (owns_work_)
executor_.on_work_finished();
}
bool owns_work() const ASIO_NOEXCEPT
{
return owns_work_;
}
template <typename Function, typename Handler>
void dispatch(Function& function, Handler& handler)
{
executor_.dispatch(ASIO_MOVE_CAST(Function)(function),
asio::get_associated_allocator(handler));
}
private:
Executor executor_;
bool owns_work_;
};
template <typename Executor, typename IoContext, typename PolymorphicExecutor>
class handler_work_base<Executor, void, IoContext, PolymorphicExecutor,
typename enable_if<
is_same<
Executor,
typename IoContext::executor_type
>::value
>::type>
{
public:
explicit handler_work_base(int, int, const Executor&)
{
}
bool owns_work() const ASIO_NOEXCEPT
{
return false;
}
template <typename Function, typename Handler>
void dispatch(Function& function, Handler& handler)
{
// When using a native implementation, I/O completion handlers are
// already dispatched according to the execution context's executor's
// rules. We can call the function directly.
asio_handler_invoke_helpers::invoke(function, handler);
}
};
template <typename Executor, typename IoContext>
class handler_work_base<Executor, void, IoContext, Executor>
{
public:
explicit handler_work_base(int, int, const Executor& ex) ASIO_NOEXCEPT
#if !defined(ASIO_NO_TYPEID)
: executor_(
ex.target_type() == typeid(typename IoContext::executor_type)
? Executor() : ex)
#else // !defined(ASIO_NO_TYPEID)
: executor_(ex)
#endif // !defined(ASIO_NO_TYPEID)
{
if (executor_)
executor_.on_work_started();
}
handler_work_base(const Executor& ex,
const Executor& candidate) ASIO_NOEXCEPT
: executor_(ex != candidate ? ex : Executor())
{
if (executor_)
executor_.on_work_started();
}
template <typename OtherExecutor>
handler_work_base(const Executor& ex,
const OtherExecutor&) ASIO_NOEXCEPT
: executor_(ex)
{
executor_.on_work_started();
}
handler_work_base(const handler_work_base& other) ASIO_NOEXCEPT
: executor_(other.executor_)
{
if (executor_)
executor_.on_work_started();
}
#if defined(ASIO_HAS_MOVE)
handler_work_base(handler_work_base&& other) ASIO_NOEXCEPT
: executor_(ASIO_MOVE_CAST(Executor)(other.executor_))
{
}
#endif // defined(ASIO_HAS_MOVE)
~handler_work_base()
{
if (executor_)
executor_.on_work_finished();
}
bool owns_work() const ASIO_NOEXCEPT
{
return !!executor_;
}
template <typename Function, typename Handler>
void dispatch(Function& function, Handler& handler)
{
executor_.dispatch(ASIO_MOVE_CAST(Function)(function),
asio::get_associated_allocator(handler));
}
private:
Executor executor_;
};
template <
#if defined(ASIO_HAS_VARIADIC_TEMPLATES)
typename... SupportableProperties,
#else // defined(ASIO_HAS_VARIADIC_TEMPLATES)
typename T1, typename T2, typename T3, typename T4, typename T5,
typename T6, typename T7, typename T8, typename T9,
#endif // defined(ASIO_HAS_VARIADIC_TEMPLATES)
typename IoContext, typename PolymorphicExecutor>
class handler_work_base<
#if defined(ASIO_HAS_VARIADIC_TEMPLATES)
execution::any_executor<SupportableProperties...>,
#else // defined(ASIO_HAS_VARIADIC_TEMPLATES)
execution::any_executor<T1, T2, T3, T4, T5, T6, T7, T8, T9>,
#endif // defined(ASIO_HAS_VARIADIC_TEMPLATES)
void, IoContext, PolymorphicExecutor>
{
public:
typedef
#if defined(ASIO_HAS_VARIADIC_TEMPLATES)
execution::any_executor<SupportableProperties...>
#else // defined(ASIO_HAS_VARIADIC_TEMPLATES)
execution::any_executor<T1, T2, T3, T4, T5, T6, T7, T8, T9>
#endif // defined(ASIO_HAS_VARIADIC_TEMPLATES)
executor_type;
explicit handler_work_base(int, int,
const executor_type& ex) ASIO_NOEXCEPT
#if !defined(ASIO_NO_TYPEID)
: executor_(
ex.target_type() == typeid(typename IoContext::executor_type)
? executor_type()
: asio::prefer(ex, execution::outstanding_work.tracked))
#else // !defined(ASIO_NO_TYPEID)
: executor_(asio::prefer(ex, execution::outstanding_work.tracked))
#endif // !defined(ASIO_NO_TYPEID)
{
}
handler_work_base(const executor_type& ex,
const executor_type& candidate) ASIO_NOEXCEPT
: executor_(ex != candidate ? ex : executor_type())
{
}
template <typename OtherExecutor>
handler_work_base(const executor_type& ex,
const OtherExecutor&) ASIO_NOEXCEPT
: executor_(asio::prefer(ex, execution::outstanding_work.tracked))
{
}
handler_work_base(const handler_work_base& other) ASIO_NOEXCEPT
: executor_(other.executor_)
{
}
#if defined(ASIO_HAS_MOVE)
handler_work_base(handler_work_base&& other) ASIO_NOEXCEPT
: executor_(ASIO_MOVE_CAST(executor_type)(other.executor_))
{
}
#endif // defined(ASIO_HAS_MOVE)
bool owns_work() const ASIO_NOEXCEPT
{
return !!executor_;
}
template <typename Function, typename Handler>
void dispatch(Function& function, Handler&)
{
execution::execute(
asio::prefer(executor_, execution::blocking.possibly),
ASIO_MOVE_CAST(Function)(function));
}
private:
executor_type executor_;
};
template <typename Handler, typename IoExecutor, typename = void>
class handler_work :
handler_work_base<IoExecutor>,
handler_work_base<typename associated_executor<
Handler, IoExecutor>::type, IoExecutor>
{
public:
typedef handler_work_base<IoExecutor> base1_type;
typedef handler_work_base<typename associated_executor<
Handler, IoExecutor>::type, IoExecutor> base2_type;
handler_work(Handler& handler, const IoExecutor& io_ex) ASIO_NOEXCEPT
: base1_type(0, 0, io_ex),
base2_type(asio::get_associated_executor(handler, io_ex), io_ex)
{
}
template <typename Function>
void complete(Function& function, Handler& handler)
{
if (!base1_type::owns_work() && !base2_type::owns_work())
{
// When using a native implementation, I/O completion handlers are
// already dispatched according to the execution context's executor's
// rules. We can call the function directly.
asio_handler_invoke_helpers::invoke(function, handler);
}
else
{
base2_type::dispatch(function, handler);
}
}
};
template <typename Handler, typename IoExecutor>
class handler_work<
Handler, IoExecutor,
typename enable_if<
is_same<
typename associated_executor<Handler,
IoExecutor>::asio_associated_executor_is_unspecialised,
void
>::value
>::type> : handler_work_base<IoExecutor>
{
public:
typedef handler_work_base<IoExecutor> base1_type;
handler_work(Handler&, const IoExecutor& io_ex) ASIO_NOEXCEPT
: base1_type(0, 0, io_ex)
{
}
template <typename Function>
void complete(Function& function, Handler& handler)
{
if (!base1_type::owns_work())
{
// When using a native implementation, I/O completion handlers are
// already dispatched according to the execution context's executor's
// rules. We can call the function directly.
asio_handler_invoke_helpers::invoke(function, handler);
}
else
{
base1_type::dispatch(function, handler);
}
}
};
} // namespace detail
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_DETAIL_HANDLER_WORK_HPP
| [
"simongido1@gmail.com"
] | simongido1@gmail.com |
ee98e66255791efaba7a42150db48f369d97799e | 3d1c29b2001a05e0c960f9eb7adb5535572e4dfe | /TaskFileExists.cpp | 02ae2c3867e5de03385d782a983a1674b9028499 | [] | no_license | lorenzostefanopiscioli/TaskScheduler | e64b3ab4319cfe7fb6ec2f773826ad1a1f9b2b44 | 8bf91a476e2c63b1a6b653827bf5cacdc0c84962 | refs/heads/master | 2022-11-09T22:08:12.891426 | 2020-06-30T02:12:48 | 2020-06-30T02:12:48 | 275,805,808 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,222 | cpp | #include "TaskFileExists.h"
namespace TiCare {
QString TaskFileExists::getTaskName() const
{
return taskName;
}
// Implemento il task da eseguire
void TaskFileExists::ExecuteTask()
{
if ( !QFile( fileName ).exists() )
{
qDebug() << "Il file " << fileName << " non esiste o non c'è nel percorso indicato!";
}
}
void TaskFileExists::setConfiguration()
{
bool ok;
// do-while mi garantisce almeno una volta la richiesta del nome
do
{
fileName = QInputDialog::getText( 0,
"Ti-Care",
"File da controllare:",
QLineEdit::Normal,
fileName,
&ok );
if ( fileName.isEmpty() )
{
QMessageBox::information( 0,
"Attenzione",
"Deve per forza essere indicato il nome di un file!" );
}
} while ( fileName.isEmpty() || !ok );
}
}
| [
"lorenzo.piscioli@digitalview.ai"
] | lorenzo.piscioli@digitalview.ai |
3314a9704e4809be8e6610294075850ae9436ab4 | 7a5b39bae541193b6da7416897dc3e5a4df9f6d1 | /cl_dll/VRInputHandlers.h | eb571eb03bcb6d4774a4fce233b2d6915567e727 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | jgwinner/Half-Life-VR | c210a6ddac2abbb21fb942ae5cd001845ae2e7bb | 1696f058e565dd438b52bffa0ea83abbf1426517 | refs/heads/master | 2022-03-06T23:29:46.519854 | 2021-10-02T12:57:05 | 2021-10-02T12:57:05 | 235,666,385 | 1 | 0 | null | 2020-01-22T21:03:39 | 2020-01-22T21:03:38 | null | UTF-8 | C++ | false | false | 5,848 | h | #pragma once
#include <unordered_map>
#include <string>
#include "openvr/openvr.h"
namespace VR
{
namespace Input
{
class Movement
{
public:
static void HandleMoveForward(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleMoveBackward(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleMoveLeft(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleMoveRight(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleMoveUp(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleMoveDown(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleTurnLeft(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleTurnRight(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleTurn45Left(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleTurn45Right(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleTurn90Left(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleTurn90Right(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleTurn180(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleJump(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleCrouch(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleLongJump(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleWalk(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleAnalogJump(const vr::InputAnalogActionData_t& data, const std::string& action);
static void HandleAnalogCrouch(const vr::InputAnalogActionData_t& data, const std::string& action);
static void HandleAnalogLongJump(const vr::InputAnalogActionData_t& data, const std::string& action);
static void HandleMoveForwardBackward(const vr::InputAnalogActionData_t& data, const std::string& action);
static void HandleMoveSideways(const vr::InputAnalogActionData_t& data, const std::string& action);
static void HandleMoveUpDown(const vr::InputAnalogActionData_t& data, const std::string& action);
static void HandleTurn(const vr::InputAnalogActionData_t& data, const std::string& action);
static void HandleMoveForwardBackwardSideways(const vr::InputAnalogActionData_t& data, const std::string& action);
static void HandleMoveForwardBackwardTurn(const vr::InputAnalogActionData_t& data, const std::string& action);
static void HandleMoveForwardBackwardSidewaysUpDown(const vr::InputAnalogActionData_t& data, const std::string& action);
static void HandleMoveForwardBackwardTurnUpDown(const vr::InputAnalogActionData_t& data, const std::string& action);
};
class Weapons
{
public:
static void HandleFire(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleAltFire(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleAnalogFire(const vr::InputAnalogActionData_t& data, const std::string& action);
static void HandleReload(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleHolster(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleNext(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandlePrevious(const vr::InputDigitalActionData_t& data, const std::string& action);
};
class Other
{
public:
static void HandleTeleport(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleFlashlight(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleLeftGrab(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleRightGrab(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleLegacyUse(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleLetGoOffLadder(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleQuickSave(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleQuickLoad(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleRestartCurrentMap(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandlePauseGame(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleExitGame(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleCustomAction(const vr::InputDigitalActionData_t& data, const std::string& action);
static void HandleLeftHandSkeleton(const vr::VRSkeletalSummaryData_t& data, const vr::VRBoneTransform_t* bones, bool hasFingers, bool hasBones, const std::string& action);
static void HandleRightHandSkeleton(const vr::VRSkeletalSummaryData_t& data, const vr::VRBoneTransform_t* bones, bool hasFingers, bool hasBones, const std::string& action);
};
class Poses
{
public:
static void HandleFlashlight(const vr::InputPoseActionData_t& data, const std::string& action);
static void HandleMovement(const vr::InputPoseActionData_t& data, const std::string& action);
static void HandleTeleporter(const vr::InputPoseActionData_t& data, const std::string& action);
};
} // namespace Input
} // namespace VR
| [
"maxvollmer@users.noreply.github.com"
] | maxvollmer@users.noreply.github.com |
3bb5a8ac697e865fe85d5f86f534db337da4f27c | 83450868c0facabaec66c1fc897fc35f0c576426 | /BOJ/Baekjoon/그래프 (Graph)/2178. 미로 탐색.cpp | fb4545af16b4e38ca1b10367a342fa1bc2e9e58b | [] | no_license | CPFrog/Problem_Solve | db84840d132a5986386847ae405cf6968f14a197 | 83adcc5a3e1deed85568f4b735e68cebdcf5c7b3 | refs/heads/main | 2023-03-07T06:12:58.654251 | 2021-02-19T02:58:47 | 2021-02-19T02:58:47 | 301,348,638 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 873 | cpp | #include <iostream>
#include <string>
#include <queue>
#include <utility>
using namespace std;
int main() {
cin.tie(NULL);
ios_base::sync_with_stdio(0);
int n, m;
cin >> n >> m;
int a[n][m];
int dist[n][m];
int dx[] = { 0,0,1,-1 };
int dy[] = { 1,-1,0,0 };
string s;
for (int i = 0i < n; i++) {
cin >> s;
for (int j = 0; j < m; j++) {
a[i][j] = s.at(j) - '0';
dist[i][j] = -1;
}
}
dist[0][0] = 1;
queue<pair<int, int>> q;
q.push(make_pair(0, 0));
while (!q.empty()) {
int x = q.front().first;
int y = q.front().second;
q.pop();
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < m) {
if (a[nx][ny] == 1 && dist[nx][ny] == -1) {
q.push(make_pair(nx, ny));
dist[nx][ny] = dist[x][y] + 1;
}
}
}
}
cout << dist[n - 1][m - 1] << '\n';
return 0;
} | [
"35889115+CPFrog@users.noreply.github.com"
] | 35889115+CPFrog@users.noreply.github.com |
fc1c0673a6d86328ac6de7f4fb6969cc9d61bc33 | a23a76881ccf9cd31a3295e38e8aa3acc45e2a84 | /fizz/fizz/crypto/hpke/Hpke.h | 8cff57bd57371bc8427a424584a41a44e0c0f62f | [
"BSD-3-Clause"
] | permissive | wongdu/refQuic | 504273ae3e780f4114d0ad5f719a83b09b6fc499 | c586943b0877d07254d1b551e342590ed4b2fd25 | refs/heads/main | 2023-04-29T15:10:33.931909 | 2021-05-20T10:42:10 | 2021-05-20T10:42:10 | 350,197,234 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,383 | h | /*
* Copyright (c) 2019-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <fizz/crypto/aead/Aead.h>
#include <fizz/crypto/hpke/Context.h>
#include <fizz/crypto/hpke/DHKEM.h>
namespace fizz {
namespace hpke {
struct PskInputs {
Mode mode;
std::unique_ptr<folly::IOBuf> psk;
std::unique_ptr<folly::IOBuf> id;
PskInputs(
Mode givenMode,
std::unique_ptr<folly::IOBuf> givenPsk,
std::unique_ptr<folly::IOBuf> givenId)
: mode(givenMode), psk(std::move(givenPsk)), id(std::move(givenId)) {
bool gotPsk = folly::IOBufNotEqualTo()(psk, getDefaultPsk());
bool gotPskId = folly::IOBufNotEqualTo()(id, getDefaultId());
if (gotPsk != gotPskId) {
throw std::runtime_error("Inconsistent PSK inputs");
}
if (gotPsk && (mode == Mode::Base || mode == Mode::Auth)) {
throw std::runtime_error("PSK input provided when not needed");
}
if (!gotPsk && (mode == Mode::Psk || mode == Mode::AuthPsk)) {
throw std::runtime_error("Missing required PSK input");
}
}
static std::unique_ptr<folly::IOBuf> getDefaultPsk() {
return folly::IOBuf::copyBuffer("");
}
static std::unique_ptr<folly::IOBuf> getDefaultId() {
return folly::IOBuf::copyBuffer("");
}
};
struct KeyScheduleParams {
Mode mode;
std::unique_ptr<folly::IOBuf> sharedSecret;
std::unique_ptr<folly::IOBuf> info;
folly::Optional<PskInputs> pskInputs;
std::unique_ptr<Aead> cipher;
std::unique_ptr<fizz::hpke::Hkdf> hkdf;
std::unique_ptr<folly::IOBuf> suiteId;
};
HpkeContext keySchedule(KeyScheduleParams params);
struct SetupResult {
std::unique_ptr<folly::IOBuf> enc;
HpkeContext context;
};
struct SetupParam {
std::unique_ptr<DHKEM> dhkem;
std::unique_ptr<Aead> cipher;
std::unique_ptr<fizz::hpke::Hkdf> hkdf;
std::unique_ptr<folly::IOBuf> suiteId;
};
SetupResult setupWithEncap(
Mode mode,
folly::ByteRange pkR,
std::unique_ptr<folly::IOBuf> info,
folly::Optional<PskInputs> pskInputs,
SetupParam param);
HpkeContext setupWithDecap(
Mode mode,
folly::ByteRange enc,
std::unique_ptr<folly::IOBuf> info,
folly::Optional<PskInputs> pskInputs,
SetupParam param);
} // namespace hpke
} // namespace fizz
| [
"412824500@qq.com"
] | 412824500@qq.com |
9189770a68fcfe61414f8998410111af1bb2e342 | d26e48eab30661675bcde5ce1a65d40ee8b58aa5 | /verify/verify-yosupo-ntt/yosupo-inliner-multiply.test.cpp | 523cf10aef68c43d1890487959eae6c665a3f632 | [
"CC0-1.0"
] | permissive | morioprog/library-1 | 2853b62fe75af8279e59c7b04a7a3f493e7af351 | f9629eabc28ec24e559fdf9ba67daf1183f69d8c | refs/heads/master | 2023-01-31T23:54:23.599503 | 2020-12-19T03:18:33 | 2020-12-19T03:18:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 658 | cpp | #define PROBLEM "https://judge.yosupo.jp/problem/convolution_mod"
#include <immintrin.h>
//
#include "../../template/template.hpp"
#include "../../misc/fastio.hpp"
#include "../../modint/montgomery-modint.hpp"
#include "../../ntt/ntt-avx2.hpp"
NTT<LazyMontgomeryModInt<998244353>> ntt;
using namespace Nyaan;
void Nyaan::solve() {
int N, M;
rd(N, M);
for (int i = 0; i < N; i++) {
int n;
rd(n);
buf1_[i] = n;
}
for (int i = 0; i < M; i++) {
int n;
rd(n);
buf2_[i] = n;
}
ntt.inplace_multiply(N, M, false);
int len = N + M - 1;
for (int i = 0; i < len; i++) {
if (i) wt(' ');
wt(buf1_[i]);
}
wt('\n');
} | [
"suteakadapyon3@gmail.com"
] | suteakadapyon3@gmail.com |
3eff389fded8deb81b750b760c4055b94b93cff5 | 542990042c986451fbcd8f3b976b6ca9c880c904 | /tools/alive_parser.h | b76279a15c5e259daf5856d8677b27881d7fdc41 | [
"MIT"
] | permissive | rcorcs/alive2 | 1da6898b6f10d652a1501964c3192eb09de0f9f7 | f691c4c392033d4b3ca4ad732b9af34a5d73c533 | refs/heads/master | 2021-02-09T07:12:26.236641 | 2020-03-01T22:45:29 | 2020-03-01T22:45:29 | 244,255,873 | 0 | 0 | MIT | 2020-03-02T01:45:14 | 2020-03-02T01:45:13 | null | UTF-8 | C++ | false | false | 625 | h | #pragma once
// Copyright (c) 2018-present The Alive2 Authors.
// Distributed under the MIT license that can be found in the LICENSE file.
#include "tools/transform.h"
#include <string>
#include <string_view>
#include <vector>
namespace IR { class Type; }
namespace tools {
std::vector<Transform> parse(std::string_view buf);
struct parser_initializer {
parser_initializer();
~parser_initializer();
};
struct ParseException {
std::string str;
unsigned lineno;
ParseException(std::string &&str, unsigned lineno)
: str(std::move(str)), lineno(lineno) {}
};
constexpr unsigned PARSER_READ_AHEAD = 16;
}
| [
"nuno.lopes@ist.utl.pt"
] | nuno.lopes@ist.utl.pt |
541e6c7fc255367d2e62805a1d26343a0e9934e2 | fce9da7922fead6082fde2f2e31dc1df07d756e4 | /ABC/097/C/main.cpp | 0daa95bc6f7dfe7f2293754e5168e16c2b285c60 | [] | no_license | kraquos/AtCoder | df0a82171cbe04a193e0fa312899c1c05d28c23d | 4b73be2ba56b510f3349dc3e48276720e8980a0e | refs/heads/master | 2020-06-11T10:03:54.909914 | 2019-09-09T07:56:28 | 2019-09-09T07:56:28 | 193,923,921 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 744 | cpp | #include <iostream>
#include <algorithm>
#include <string>
#include <numeric>
#include <vector>
#include <queue>
#define rep(i,n) for(int i=0;i<n;i++)
#define ll long long int
#define ii pair<int,int>
#define MAX 1000000007
using namespace std;
int main(void){
string s;
int k;
cin >> s >> k;
string work[k];
rep(i,k) work[i] = "";
work[0] = s[0];
for(int i=0;i<s.length();i++){
for(int j=1;j<=k;j++){
if(work[k-1] != "" && work[k-1] < s.substr(i, j))break;
string tmp = s.substr(i, j);
rep(l,k){
if(tmp == work[l]) break;
if(tmp < work[l] || work[l] == ""){
string w = tmp;
tmp = work[l];
work[l] = w;
}
}
}
}
//rep(i,k)cout << work[i] << endl;
cout << work[k-1] << endl;
return 0;
}
| [
"[kregistaa@gmail.com]"
] | [kregistaa@gmail.com] |
bdd525b1a2b259c04b4fb266507520c20b077792 | bcd32907dc7b292350371ac5cc9b67bd3b7a99c2 | /development/core/src/include/SODaCTPBrowse.h | ea696a0233fde159e0431828fd820a08ff04a25e | [
"MIT"
] | permissive | SoftingIndustrial/OPC-Classic-SDK | c6d3777e2121d6ca34da571930a424717740171e | 08f4b3e968acfce4b775299741cef1819e24fda1 | refs/heads/main | 2022-07-28T14:53:00.481800 | 2022-01-17T13:58:46 | 2022-01-17T13:58:46 | 335,269,862 | 41 | 16 | MIT | 2022-01-17T15:11:39 | 2021-02-02T11:43:04 | C++ | UTF-8 | C++ | false | false | 1,342 | h | #ifndef _SODACTPBROWSE_H_
#define _SODACTPBROWSE_H_
#ifdef SOFEATURE_TUNNEL
#pragma pack(push,4)
//-----------------------------------------------------------------------------
// SODaCTPNameSpaceBrowserImpl |
//-----------------------------------------------------------------------------
class SODAC_EXPORT SODaCTPNameSpaceBrowserImpl
: virtual public SODaCNameSpaceBrowserICommunication
{
public:
SODaCTPNameSpaceBrowserImpl(SODaCServer* pServer);
virtual BOOL expand20(IN SOCltBrowseObject* pParent, IN LPCTSTR itemID, IN DWORD type, OUT SOCmnList<SOCltBrowseObject> &objList);
virtual BOOL expand30(IN SOCltBrowseObject* pParent, IN LPCTSTR itemID, IN LPCTSTR itemPath, IN DWORD type, IN SOCmnString& contPoint, OUT SOCmnList<SOCltBrowseObject> &objList);
virtual LPCTSTR retrieveItemID(SOCltBrowseObject* pObj);
virtual void initUse(void);
virtual void use20(void);
virtual void use30(void);
virtual BOOL support20(void);
virtual BOOL support30(void);
protected:
virtual ~SODaCTPNameSpaceBrowserImpl();
};
class SODAC_EXPORT SODaCTPNameSpaceBrowser :
public SODaCNameSpaceBrowser,
virtual public SODaCTPNameSpaceBrowserImpl
{
public:
SODaCTPNameSpaceBrowser(SODaCServer* pServer);
};
#pragma pack(pop)
#endif // SOFEATURE_TUNNEL
#endif // _SODACBROWSE_H_
| [
"35690118+FischerSeb@users.noreply.github.com"
] | 35690118+FischerSeb@users.noreply.github.com |
a82ba4933ae20bf0377fe76f1e1c2bc619c26bba | c82ac3facb85cdbd436e2f93708d2f5a7787641f | /labeler/labeler/video_labeler.hpp | 07f276118ac16d47e38955316c559fc7161e84cb | [] | no_license | lpan1010/mapbarcv | 549a9395b4d4dedbd0c70aa83f1fbecb726f8d23 | 76a855af6da229d5c079165b015c3159889a35b9 | refs/heads/master | 2016-09-03T06:53:28.498918 | 2015-02-05T05:45:31 | 2015-02-05T05:45:31 | 31,447,257 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,259 | hpp | /*
* video_labeler.hpp
*
* Created on: 2014,11,27
* Author: qin
*/
#ifndef VIDEO_LABELER_HPP_
#define VIDEO_LABELER_HPP_
#include "frame_labeler.hpp"
#include "../common_header.hpp"
#include "../os.hpp"
#include "label.hpp"
class VideoLabeler {
public:
VideoLabeler();
bool label_video(String& video_file_path,
int& frame_num,
String& meta_file);
bool label_video(String& video_file_path, int& frame_num, String& meta_file,
String& output_dir);
void jump_to_frame(int& frame_num);
// FIXME this is a so fxxking ugly design.
void refresh();
void save_current_progress(String& video_name, int& frame);
private:
bool load_video(String&);
void open_meta_file(String& meta_file_path);
VideoCapture video;
Mat frame;
FrameLabeler fl;
ofstream meta_file_stream;
};
extern int mouse_x;
extern int mouse_y;
extern VideoLabeler vl;
extern vector<Label*> * labels;
extern Label* current_label;
#endif /* VIDEO_LABELER_HPP_ */
| [
"qinjian623@gmail.com"
] | qinjian623@gmail.com |
a5aa8dbfb411e282f658af47bc13d2635db675e0 | e9a26b0d564be3337cd0799a986089f9dba61f35 | /src/sys/event.cpp | 9dee8e7aeba0f7cc9e4799b6fe8e9309acea1114 | [] | no_license | zigzed/common | 3994aae3593767283395910f443ecf7a5464ebae | 0bb51892706a8b9ab150605c2f092d08d78ce410 | refs/heads/master | 2021-01-20T07:46:22.545700 | 2013-04-23T15:46:53 | 2013-04-23T15:46:53 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 6,594 | cpp | /** Copyright (C) 2013 wilburlang@gmail.com
*/
#include "common/sys/event.h"
#include "common/sys/error.h"
#if defined(OS_LINUX)
#include <linux/version.h>
#include <features.h>
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,45)
#define HAVE_EPOLL 1
#endif
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
#include <sys/eventfd.h>
#define HAVE_EVENTFD 1
#endif
#if defined(HAVE_EPOLL)
#if (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 8)
#define HAVE_TIMERFD 1
#endif
#endif
#include <unistd.h>
#include <fcntl.h>
#include <poll.h>
#endif
#include <cassert>
namespace cxx {
namespace sys {
#if !defined(OS_WINDOWS)
static int make_fdpair(event::handle_t* r, event::handle_t* w)
{
#if HAVE_EVENTFD
#if __GLIBC__ == 2 && __GLIBC_MINOR__ < 8
event::handle_t fd = syscall(__NR_eventfd, 0);
#else
event::handle_t fd = eventfd(0, 0);
#endif
assert(fd != -1);
if(fd == -1) {
return -1;
}
*w = fd;
*r = fd;
::fcntl(fd, F_SETFL, O_NONBLOCK);
::fcntl(fd, F_SETFD, FD_CLOEXEC);
return 0;
#else /* HAVE_EVENTFD */
int pipe_fds[2];
if(pipe(pipe_fds) == 0) {
*r = pipe_fds[0];
*w = pipe_fds[1];
::fcntl(*r, F_SETFL, O_NONBLOCK);
::fcntl(*r, F_SETFD, FD_CLOEXEC);
::fcntl(*w, F_SETFL, O_NONBLOCK);
::fcntl(*w, F_SETFD, FD_CLOEXEC);
}
return -1;
#endif
}
static int close_fdpair(event::handle_t* r, event::handle_t* w)
{
if(*w != -1 && *w != *r)
close(*w);
if(*r != -1)
close(*r);
return 0;
}
event::event()
: w_(-1), r_(-1)
{
int rc = make_fdpair(&r_, &w_);
assert(rc == 0);
}
event::~event()
{
close_fdpair(&r_, &w_);
}
event::handle_t event::handle() const
{
return r_;
}
void event::send()
{
uint64_t i = 1;
ssize_t sz = write(w_, &i, sizeof(i));
assert(sz == sizeof(i));
}
bool event::wait(int timeout)
{
pollfd fds;
fds.fd = r_;
fds.events = POLLIN;
int rc = poll(&fds, 1, timeout);
if(rc < 0) {
assert(sys::err::get() == EINTR);
return false;
}
else if(rc == 0) {
return false;
}
assert(rc == 1);
assert(fds.events & POLLIN);
return true;
}
void event::recv()
{
uint64_t d = 0;
ssize_t sz = read(r_, &d, sizeof(d));
assert(sz == sizeof(d));
#if HAVE_EVENTFD
/** 如果读取到的值大于1,则说明将多次事件通知一次读到了。那么需要将多读到的再
* 写回去
*/
if(d == 2) {
uint64_t i = 1;
ssize_t sz = write(w_, &i, sizeof(i));
assert(sz == sizeof(i));
return;
}
assert(d == 1);
#endif
}
#else /* !defined(OS_WINDOWS) */
static int make_fdpair(event::handle_t *r, event::handle_t *w)
{
WSADATA wsaData = {0};
WSAStartup(MAKEWORD(2,2), &wsaData);
SOCKET l = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
assert(l != INVALID_SOCKET);
BOOL on = TRUE;
int ret = setsockopt(l, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
assert(ret != SOCKET_ERROR);
ret = setsockopt(l, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on));
assert(ret != SOCKET_ERROR);
ret = setsockopt(l, IPPROTO_TCP, TCP_NODELACK, &on, sizeof(on));
assert(ret != SOCKET_ERROR);
sockaddr_in service;
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr("127.0.0.1");
service.sin_port = 0;
ret = bind(l, (SOCKADDR* )&service, sizeof(service));
assert(ret != SOCKET_ERROR);
// get the bound port
ret = getsockname(l, (SOCKADDR* )&service, sizeof(service));
assert(ret != SOCKET_ERROR);
// some firewall set the addr to 0.0.0.0, we force the addr to localhost
service.sin_addr.s_addr = inet_addr("127.0.0.1");
ret = listen(l, SOMAXCONN);
assert(ret != SOCKET_ERROR);
*w = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
ret = setsockopt(*w, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on));
assert(ret != SOCKET_ERROR);
ret = setsockopt(*w, IPPROTO_TCP, TCP_NODELACK, &on, sizeof(on));
assert(ret != SOCKET_ERROR);
ret = connect(*w, (SOCKADDR* )&service, sizeof(service));
assert(ret != SOCKET_ERROR);
*r = accept(l, NULL, NULL);
assert(*r != SOCKET_ERROR);
closesocket(l);
}
static int close_fdpair(event::handle_t *r, event::handle_t *w)
{
closesocket(*r);
closesocket(*w);
WSACleanup();
}
event::event()
: w_(-1), r_(-1)
{
int rc = make_fdpair(&r_, &w_);
assert(rc == 0);
}
event::~event()
{
close_fdpair(&r_, &w_);
}
event::handle_t event::handle() const
{
return r_;
}
void event::send()
{
uint64_t i = 1;
int sz = ::send(w_, &i, sizeof(i), 0);
assert(sz == sizeof(i));
}
bool event::wait(int timeout)
{
fd_set fds;
FD_ZERO(&fds);
FD_SET (r_, &fds);
timeval tv;
if(timeout >= 0) {
tv.tv_sec = timeout / 1000;
tv.tv_usec = timeout % 1000 * 1000;
}
int ret = select(0, &fds, NULL, NULL, timeout >= 0 ? &tv : NULL);
assert(ret != SOCKET_ERROR);
}
void event::recv()
{
uint64_t d;
int sz = ::recv(r_, &d, sizeof(d), 0);
assert(sz == sizeof(d));
}
#endif
}
}
| [
"wilburlang@gmail.com"
] | wilburlang@gmail.com |
8a4a0135cdb19a71d8ff1232c3440c67dcbbb687 | 5fe784052e89e61a37b94c9abf07ab161d1e6c74 | /1D/src/main.cpp | b5e969cd10304648499d422e36cb7887346f582f | [] | no_license | agrabsch/MCMC | 61ea65c0e75b8e50d2b47c7ba518301548f1a3d4 | 6dead1ae81457616ca8a3ee430d17710f81b8231 | refs/heads/master | 2021-09-03T04:27:28.223003 | 2018-01-05T14:51:07 | 2018-01-05T14:51:07 | 116,266,393 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 520 | cpp | #include <iostream>
#include <fstream>
#include <sstream>
#include "mcmc.hpp"
using namespace std;
const int N = 100 ;
const int M = 20*N ;
int main()
{
// generate N points
MCMC sim(N) ;
// forget init cdt: run M iterations
sim.Iterate(M) ;
// output files
ostringstream filename;
filename << "pts_N=" << N << ".dat" ;
ofstream out(filename.str()) ;
vector<double> x = sim.get_points() ;
for(int j=0; j<N; j++)
{
out << x[j] << endl ;
}
out.close() ;
return 0 ;
}
| [
"aurelien.grabsch@gmail.ccom"
] | aurelien.grabsch@gmail.ccom |
79fe73b0dc0672a9bbd2f866a6fe2d48c8ac9013 | 536656cd89e4fa3a92b5dcab28657d60d1d244bd | /net/dns/record_parsed.cc | 8b77b6664c9db9923396241431e8c3079031d671 | [
"BSD-3-Clause"
] | permissive | ECS-251-W2020/chromium | 79caebf50443f297557d9510620bf8d44a68399a | ac814e85cb870a6b569e184c7a60a70ff3cb19f9 | refs/heads/master | 2022-08-19T17:42:46.887573 | 2020-03-18T06:08:44 | 2020-03-18T06:08:44 | 248,141,336 | 7 | 8 | BSD-3-Clause | 2022-07-06T20:32:48 | 2020-03-18T04:52:18 | null | UTF-8 | C++ | false | false | 2,938 | cc | // Copyright (c) 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 "net/dns/record_parsed.h"
#include <utility>
#include "base/logging.h"
#include "net/dns/dns_response.h"
#include "net/dns/record_rdata.h"
namespace net {
RecordParsed::RecordParsed(const std::string& name,
uint16_t type,
uint16_t klass,
uint32_t ttl,
std::unique_ptr<const RecordRdata> rdata,
base::Time time_created)
: name_(name),
type_(type),
klass_(klass),
ttl_(ttl),
rdata_(std::move(rdata)),
time_created_(time_created) {}
RecordParsed::~RecordParsed() = default;
// static
std::unique_ptr<const RecordParsed> RecordParsed::CreateFrom(
DnsRecordParser* parser,
base::Time time_created) {
DnsResourceRecord record;
std::unique_ptr<const RecordRdata> rdata;
if (!parser->ReadRecord(&record))
return std::unique_ptr<const RecordParsed>();
switch (record.type) {
case ARecordRdata::kType:
rdata = ARecordRdata::Create(record.rdata, *parser);
break;
case AAAARecordRdata::kType:
rdata = AAAARecordRdata::Create(record.rdata, *parser);
break;
case CnameRecordRdata::kType:
rdata = CnameRecordRdata::Create(record.rdata, *parser);
break;
case PtrRecordRdata::kType:
rdata = PtrRecordRdata::Create(record.rdata, *parser);
break;
case SrvRecordRdata::kType:
rdata = SrvRecordRdata::Create(record.rdata, *parser);
break;
case TxtRecordRdata::kType:
rdata = TxtRecordRdata::Create(record.rdata, *parser);
break;
case NsecRecordRdata::kType:
rdata = NsecRecordRdata::Create(record.rdata, *parser);
break;
case OptRecordRdata::kType:
rdata = OptRecordRdata::Create(record.rdata, *parser);
break;
case EsniRecordRdata::kType:
rdata = EsniRecordRdata::Create(record.rdata, *parser);
break;
default:
DVLOG(1) << "Unknown RData type for received record: " << record.type;
return std::unique_ptr<const RecordParsed>();
}
if (!rdata.get())
return std::unique_ptr<const RecordParsed>();
return std::unique_ptr<const RecordParsed>(
new RecordParsed(record.name, record.type, record.klass, record.ttl,
std::move(rdata), time_created));
}
bool RecordParsed::IsEqual(const RecordParsed* other, bool is_mdns) const {
DCHECK(other);
uint16_t klass = klass_;
uint16_t other_klass = other->klass_;
if (is_mdns) {
klass &= dns_protocol::kMDnsClassMask;
other_klass &= dns_protocol::kMDnsClassMask;
}
return name_ == other->name_ &&
klass == other_klass &&
type_ == other->type_ &&
rdata_->IsEqual(other->rdata_.get());
}
} // namespace net
| [
"pcding@ucdavis.edu"
] | pcding@ucdavis.edu |
c1fd39458082b7dd57ffed9c6031b135159e4506 | c8c97fd385a90d67549755497a72ff43220d6c53 | /Polygon.cpp | 20a26d8a8c82cf5e7c8720db9ac1f87de42b3b72 | [] | no_license | DreamVersion/LargestRect | a749a2037e6b97c7a545a93472f7c83bc6c9ee1d | 429ce55cf5d4b790f54830a01921ca1a14bfdcbb | refs/heads/master | 2021-01-20T02:56:41.922085 | 2017-04-26T11:11:41 | 2017-04-26T11:11:41 | 89,471,058 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,923 | cpp | //
// Created by qiguanjie on 2017/4/22.
//
#include <cstdlib>
#include <math.h>
#include "Polygon.h"
#include "util.h"
bool Polygon::findLargestRetangle(Point ¢er, double &resAngle, vector<Point> &maxRect, double &resWidth,
double &resHeight)
{
//https://d3plus.org/blog/behind-the-scenes/2014/07/08/largest-rect/
if (polygon.size() < 3)
{
return false;
}
double src_minx = 0.0, src_miny = 0.0, src_maxx = 0.0, src_maxy = 0.0;
util::getPolyBounds(polygon, src_minx, src_miny, src_maxx, src_maxy);
for (int i = 0; i < polygon.size(); i++)
{
polygon[i].x -= src_minx;
polygon[i].y -= src_miny;
}
double minx = 0.0, miny = 0.0, maxx = 0.0, maxy = 0.0;
util::getPolyBounds(polygon, minx, miny, maxx, maxy);
double boxWidth = maxx - minx;
double boxHeight = maxy - miny;
//const double widthStep = ConvertCoord(1.0, m_nlevel);//a font size as step
const double widthStep = 1.0;
const int minFontSize = 5;//最小字号
// double minWidth = minFontSize * widthStep * aspectRatio;
// double minHeight = minFontSize * widthStep;
const double minWidth = minFontSize * widthStep;
const double minHeight = minFontSize * widthStep;
const double maxAspectRatio = 15;
const double aspectRatioStep = 0.5;
const int tryTimes = 20;
const int angleStep = 5;
if (boxWidth < minWidth || boxHeight < minHeight)
{
return false;
}
vector<Point> origins;
Point centroid = util::centroid(polygon);
if (util::pointInPoly(centroid, polygon))
{
origins.push_back(centroid);
}
srand(time(NULL));
while (origins.size() < tryTimes)
{
Point randOrigin;
randOrigin.x = ((double) rand() / RAND_MAX) * boxWidth + minx;
randOrigin.y = ((double) rand() / RAND_MAX) * boxHeight + miny;
if (util::pointInPoly(randOrigin, polygon))
{
origins.push_back(randOrigin);
}
}
double maxArea = 0.0;
for (int angle = -90; angle < 90 + angleStep; angle += angleStep)
{
double angleRad = -angle * M_PI / 180;
for (int i = 0; i < origins.size(); i++)
{
vector<Point> modifOrigins;
Point &origOrigin = origins[i];
Point *newP1W = NULL, *p2W = NULL;
util::intersectPoints(polygon, origOrigin, angleRad, newP1W, p2W);
if (newP1W != NULL && p2W != NULL)
{
modifOrigins.push_back(Point((newP1W->x + p2W->x) / 2.0, (newP1W->y + p2W->y) / 2.0));
}
SAFE_DELETE(newP1W);
SAFE_DELETE(p2W);
Point *p1H = NULL, *p2H = NULL;
util::intersectPoints(polygon, origOrigin, angleRad + M_PI / 2, p1H, p2H);
if (p1H != NULL && p2H != NULL)
{
modifOrigins.push_back(Point((p1H->x + p2H->x) / 2.0, (p1H->y + p2H->y) / 2.0));
}
SAFE_DELETE(p1H);
SAFE_DELETE(p2H);
for (int j = 0; j < modifOrigins.size(); j++)
{
Point &origin = modifOrigins[j];
Point *newP1W = NULL, *newP2W = NULL;
util::intersectPoints(polygon, origin, angleRad, newP1W, newP2W);
if (newP1W == NULL || newP2W == NULL)
{
SAFE_DELETE(newP1W);
SAFE_DELETE(newP2W);
continue;
}
Point *newP1H = NULL, *newP2H = NULL;
util::intersectPoints(polygon, origin, angleRad + M_PI / 2, newP1H, newP2H);
if (newP1H == NULL || newP2H == NULL)
{
SAFE_DELETE(newP1H);
SAFE_DELETE(newP2H);
SAFE_DELETE(newP1W);
SAFE_DELETE(newP2W);
continue;
}
double minx1 = util::squaredDist(origin, *newP1W);
double minx2 = util::squaredDist(origin, *newP2W);
double minSqDistW = minx1 < minx2 ? minx1 : minx2;
double maxWidth = 2 * sqrt(minSqDistW);
double miny1 = util::squaredDist(origin, *newP1H);
double miny2 = util::squaredDist(origin, *newP2H);
double minSqDistH = miny1 < miny2 ? miny1 : miny2;
double maxHeight = 2 * sqrt(minSqDistH);
SAFE_DELETE(newP1H);
SAFE_DELETE(newP2H);
SAFE_DELETE(newP1W);
SAFE_DELETE(newP2W);
if (maxWidth * maxHeight <= maxArea)
{
continue;
}
double minAspectRatio = 1 > minWidth / maxHeight ? 1 : minWidth / maxHeight;
minAspectRatio = minAspectRatio > maxArea / (maxHeight * maxHeight) ? minAspectRatio : maxArea /
(maxHeight *
maxHeight);
double maxAspectRatio1 = maxAspectRatio < maxWidth / minHeight ? maxAspectRatio : maxWidth / minHeight;
maxAspectRatio1 =
maxAspectRatio1 < (maxWidth * maxWidth) / maxArea ? maxAspectRatio1 : (maxWidth * maxWidth) /
maxArea;
for (double ratio = minAspectRatio; ratio < maxAspectRatio1 + aspectRatioStep; ratio += aspectRatioStep)
{
double left = minWidth > sqrt(maxArea * ratio) ? minWidth : sqrt(maxArea * ratio);
double right = maxWidth < maxHeight * ratio ? maxWidth : maxHeight * ratio;
if (right * maxHeight < maxArea)
continue;
while ((right - left) >= widthStep)
{
double width = (left + right) / 2.0;
double height = width / ratio;
//wsl::coor::Point pt0 = origin;
vector<Point> rectPoly;
rectPoly.push_back(Point(origin.x - width / 2, origin.y - height / 2.0));
rectPoly.push_back(Point(origin.x + width / 2, origin.y - height / 2.0));
rectPoly.push_back(Point(origin.x + width / 2, origin.y + height / 2.0));
rectPoly.push_back(Point(origin.x - width / 2, origin.y + height / 2.0));
vector<Point> rotateRectPoly = util::rotatePoly(rectPoly, origin, angleRad);
if (util::polyInsidePoly(rotateRectPoly, polygon))
{
maxArea = width * height;
center.x = origin.x + src_minx;
center.y = origin.y + src_miny;
resAngle = angle;
maxRect = rotateRectPoly;
for (int rect_index = 0; rect_index < maxRect.size(); rect_index++)
{
maxRect[rect_index].x += src_minx;
maxRect[rect_index].y += src_miny;
}
resWidth = width;
resHeight = height;
left = width;
}
else
{
right = width;
}
}//endwhile
}//endfor ratio
}//endfor modifOrigins
}//endfor origin point
}//endfor angle
if (maxRect.size() > 0)
return true;
else
return false;
} | [
"qiguanjie12@126.com"
] | qiguanjie12@126.com |
9a4a631b7126c42b7ee8c6ce48145e78cdbcb083 | cbea88cde2290d9bc9380aeb80e22dc9b72ac88b | /DICT-POV-2022/pov radial/POV18-animated_Strange/CC.ino | 0904e977cf6a697b97a14687bd071bc9ae53228e | [] | no_license | synersignart/POV1 | 20224fdaaff0fc920c50dbb133fa4120893dfba2 | a43e238abb2fc3a14afa311ef1c86b768d2f8fa3 | refs/heads/master | 2022-10-20T18:07:03.905408 | 2022-10-11T03:59:01 | 2022-10-11T03:59:01 | 125,300,100 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,690 | ino | void CC() {
if (pasa == true) {
pasa = false;
tiempo = micros();
periodoini = tiempo - previoustime;
periodo = tiempo - previoustime - tvariable ;
//periodo teorico
tiempoDibujo = periodo / 360;
if (tiempoDibujo < 0) tiempoDibujo = 0;
previoustime = tiempo;
k = 0;
angulo = pgm_read_byte(PolarRedu3 + k);
if (k / 3 >= pgm_read_word_near(angreducido3 + 0)) {
angulo += 255;
};
contaang=0;
for (ang = 0; ang < 360 ; ang++) {
contaang++;
cambiaLed = false;
while (angulo == ang) {
cambiaLed = true;
if (pgm_read_byte(radio1directo + 0) == 1) {
numled = pgm_read_byte(PolarRedu3 + k+1) - 1 + pgm_read_byte(offset1 + 0);
} else {
//inverso es cero
numled = pgm_read_byte(num_leds + 0) - pgm_read_byte(PolarRedu3 + k+1) + pgm_read_byte(offset1 + 0);
}
LedColour = pgm_read_byte(PolarRedu3 + k+2);
//color option 0
vred = 0;
vgreen = 0;
vblue = 0;
if (LedColour == 4 || LedColour == 6 || LedColour == 7 || LedColour == 1) {
vblue = 255;
}
if (LedColour == 3 || LedColour == 5 || LedColour == 6 || LedColour == 1) {
vgreen = 255;
}
if (LedColour == 2 || LedColour == 5 || LedColour == 7 || LedColour == 1) {
vred = 255;
}
leds[numled].b = vred;
leds[numled].g = vgreen;
leds[numled].r = vblue;
k += 3;
if (k >= pgm_read_word_near(sizePolarRedu3 + 0)) {
angulo = 999;
}else{
angulo = pgm_read_byte(PolarRedu3 + k);
if (k / 3 >= pgm_read_word_near(angreducido3 + 0)) {
angulo += 255;
}
}
}
if (cambiaLed == true) {
FastLED.show();
if (tiempoDibujo > tiempoescritura) {
delayMicroseconds(tiempoDibujo - tiempoescritura);
}
//--------------------------<EDITED the Delay timer to Tune the Image Refresh Rate - Biggest NumPasos (-) Other Numpasos>--------------------------------------------------------------------------------------------------------------------------------------------------------------
} else {
if (tiempoDibujo > tiempoescritura) {
delayMicroseconds(tiempoDibujo + tiempoescritura * pgm_read_word_near(numpasos3 + 0) / (360 - pgm_read_word_near(numpasos3 + 0)));
} else {
delayMicroseconds(tiempoDibujo * 360 / (360 - pgm_read_word_near(numpasos3 + 0)));
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
}
if (pasa == true) {
//para que se sume a tvariable algo que se supone positivo
tvariable += (micros() - previoustime) * 360 /contaang - periodoini;
if (tvariable > 300000 || tvariable < -300000) {
tvariable = 0;
}
return;
}
}
//para que se sume a tvariable algo negativo
tvariable += (micros() - previoustime) - periodoini;
if (tvariable > 300000 || tvariable < -300000) {
tvariable = 0;
}
}
}
void pasaIman3 () {
pasa = true;
}
| [
"noreply@github.com"
] | noreply@github.com |
b645e7f5271d6a876abd41468e88eedde0d3118b | cd2ce54b4dada318e1c754e11b841d8e0682f653 | /LevelPlugin/Level/LevelPlugin.cpp | 70dbd01886610398a671321519d955aa2d7e5f40 | [] | no_license | devonchenc/Plugin | 468a3e847a8b45cb33bb21bc06ab0b9240a4929f | 1e26efe852047edff09e7ebf10fb538cf1d822ae | refs/heads/master | 2021-06-08T17:13:49.675479 | 2015-09-18T06:28:42 | 2015-09-18T06:28:42 | 17,834,839 | 10 | 9 | null | null | null | null | UTF-8 | C++ | false | false | 739 | cpp | #include "stdafx.h"
#include "LevelPlugin.h"
#include "Level.h"
IMPLEMENT_PLUGIN(CLevelPlugin)
void CLevelPlugin::Init()
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
// merge menu
CMenu append;
append.LoadMenu(IDR_LEVEL_MENU);
MergeMenu(&append, TRUE);
}
void CLevelPlugin::Query(CPluginInfo& plugininfo)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
plugininfo.m_strName = _T("LevelPlugin");
plugininfo.m_strBlurb = _T("Process Image");
plugininfo.m_strHelp = _T("For Image Processing");
plugininfo.m_strAuthor = _T("Wangqian");
plugininfo.m_strCopyRight = _T("Copyright Wangqian");
plugininfo.m_strDate = _T("2015.9.18");
// CString str;
// str.LoadString(IDS_STRING_MENU_LABEL);
// plugininfo.m_strMenuLabel = str;
} | [
"tianrolin@163.com"
] | tianrolin@163.com |
08acf940f64de129cf135c31f95ed335d55d453c | 8321132c96bbf8f7acfcb96b3439a42f7b96a318 | /src/masternode-sync.h | 0a90d7d1bc818f33d08abf84705ee62a2fe91707 | [
"MIT"
] | permissive | lycion/lkcoin | 810a55ebdec26cd7b7c699a3e0e618e3c1d7af7f | 580e6ec1e2914c135ae14f6b19c2cf8116001888 | refs/heads/master | 2020-03-21T17:29:29.199941 | 2018-06-29T04:54:51 | 2018-06-29T04:54:51 | 138,834,863 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,156 | h | // Copyright (c) 2014-2015 The Lkcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef MASTERNODE_SYNC_H
#define MASTERNODE_SYNC_H
#define MASTERNODE_SYNC_INITIAL 0
#define MASTERNODE_SYNC_SPORKS 1
#define MASTERNODE_SYNC_LIST 2
#define MASTERNODE_SYNC_MNW 3
#define MASTERNODE_SYNC_BUDGET 4
#define MASTERNODE_SYNC_BUDGET_PROP 10
#define MASTERNODE_SYNC_BUDGET_FIN 11
#define MASTERNODE_SYNC_FAILED 998
#define MASTERNODE_SYNC_FINISHED 999
#define MASTERNODE_SYNC_TIMEOUT 5
#define MASTERNODE_SYNC_THRESHOLD 2
class CMasternodeSync;
extern CMasternodeSync masternodeSync;
//
// CMasternodeSync : Sync masternode assets in stages
//
class CMasternodeSync
{
public:
std::map<uint256, int> mapSeenSyncMNB;
std::map<uint256, int> mapSeenSyncMNW;
std::map<uint256, int> mapSeenSyncBudget;
int64_t lastMasternodeList;
int64_t lastMasternodeWinner;
int64_t lastBudgetItem;
int64_t lastFailure;
int nCountFailures;
// sum of all counts
int sumMasternodeList;
int sumMasternodeWinner;
int sumBudgetItemProp;
int sumBudgetItemFin;
// peers that reported counts
int countMasternodeList;
int countMasternodeWinner;
int countBudgetItemProp;
int countBudgetItemFin;
// Count peers we've requested the list from
int RequestedMasternodeAssets;
int RequestedMasternodeAttempt;
// Time when current masternode asset sync started
int64_t nAssetSyncStarted;
CMasternodeSync();
void AddedMasternodeList(uint256 hash);
void AddedMasternodeWinner(uint256 hash);
void AddedBudgetItem(uint256 hash);
void GetNextAsset();
std::string GetSyncStatus();
void ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv);
bool IsBudgetFinEmpty();
bool IsBudgetPropEmpty();
void Reset();
void Process();
bool IsSynced();
bool IsBlockchainSynced();
void ClearFulfilledRequest();
};
#endif
| [
"lycion@gmail.com"
] | lycion@gmail.com |
9ea8fcccd28dd829162d6efed302a188cdd36a49 | 042788ddc996a6b38081922783f83023e302417c | /Covid/common.h | b6822ef91ef81e3e7464b32e74b25ccf1450b956 | [] | no_license | MathDotSqrt/Covid | 32e68dd92ff3add547bd1f9f5e1429bdaa12fb96 | b2a4c98a3055e38b2ad25622f4cff504da983144 | refs/heads/master | 2022-07-22T10:39:05.825141 | 2020-05-20T14:28:42 | 2020-05-20T14:28:42 | 264,561,914 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,459 | h | #pragma once
//types for integral types
typedef unsigned char u8;
typedef signed char i8;
typedef unsigned short u16;
typedef signed short i16;
typedef unsigned int u32;
typedef signed int i32;
typedef unsigned long u64;
typedef signed long i64;
typedef float f32;
typedef double f64;
/*MATH CONSTANTS*/
constexpr f32 PI = 3.14159265359f; //Good ole PI
constexpr f32 EPSILON = 0.1f; //Pretty large epsilon lmao
constexpr f32 t_05_5 = 2.571f;
constexpr f32 t_05_100 = 1.982f;
/*MATH CONSTANTS*/
/*MOVEMENT CONSTANTS*/
constexpr f32 MAX_MAGNITUDE = 0.004f; //Max movement
constexpr f32 CHANGE_DIR = .01f; //Probability of changin dir
constexpr f32 TELEPORT = .01f; //Probability of teleport
constexpr f32 MAX_CHARGE_DIST = 1.0f; //Maximum distance social-distance force
constexpr f32 MAX_CHARGE = .02f; //Max Social-distance force
constexpr f32 CHARGE_CONSTANT = .00002f; //Repeling force constant
/*MOVEMENT CONSTANTS*/
/*INFECTION RATE*/
constexpr f32 BETA = 0.05f; //Infection Rate
constexpr f32 GAMMA = 0.001f; //Recovary Rate
constexpr f32 RADIUS = .25f; //Infection Radius
constexpr f32 RADIUS2 = RADIUS * RADIUS; //Radius Squared
/*INFECTION RATE*/
/*AGENT PARAMETERS*/
constexpr i32 SUSCEPTIBLE = 5000; //Initial population Susceptible
constexpr i32 INFECTED = 50; //Initial population infected
constexpr f32 BAD_ACTOR = 0.00f; //Proportion of population who are bad bois
constexpr f32 TEST_ACCURACY_RATE = 0.000f; //Testing accuracy rate for covid test
constexpr i32 MAX_SHOP = 0; //Maximum occupancy in hub zones
/*AGENT PARAMETERS*/
/*DETAIL*/
constexpr int GRID_WIDTH = 25; //Spacial Width of entire map
constexpr int NUM_GRIDS = 25; //Number of spacial partitions in grid. The larger the faster the model computes (Substantially)
constexpr int NUM_EXPERIMENTS = 101; //Number of experiments to run for our statistical analysis
constexpr int NUM_THREADS = 8; //Number of worker threads to run. Should be equal to the number of cores on your cpu
constexpr i32 SCREEN_WIDTH = 1024 / 2; //Size of visual window
constexpr i32 SCREEN_HEIGHT = 1024 / 2; //Size of visual window
/*DETAIL*/
/*
NOTE: (GRID_WIDTH / NUM_GRIDS) >= RADIUS or else model is inaccurate for control.
NOTE: (GRID_WIDTH / NUM_GRIDS) >= MAX_CHARGE_DIST or else social distancing algorithm becomes instable
NOTE: GRID_WIDTH affects the size of hub zones so it effects community based models.
*/ | [
"ctrenkov@gmail.com"
] | ctrenkov@gmail.com |
619c15dce407dd06c0e4eb96daae872e046a7604 | f83ef53177180ebfeb5a3e230aa29794f52ce1fc | /ACE/ACE_wrappers/TAO/TAO_IDL/be_include/be_attribute.h | 253985339784813847ed729c0b93107a87e19b02 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-sun-iiop"
] | permissive | msrLi/portingSources | fe7528b3fd08eed4a1b41383c88ee5c09c2294ef | 57d561730ab27804a3172b33807f2bffbc9e52ae | refs/heads/master | 2021-07-08T01:22:29.604203 | 2019-07-10T13:07:06 | 2019-07-10T13:07:06 | 196,183,165 | 2 | 1 | Apache-2.0 | 2020-10-13T14:30:53 | 2019-07-10T10:16:46 | null | UTF-8 | C++ | false | false | 1,338 | h |
//=============================================================================
/**
* @file be_attribute.h
*
* Extension of class AST_Attribute that provides additional means for C++
* mapping.
*
* @author Copyright 1994-1995 by Sun Microsystems
* @author Inc. and Aniruddha Gokhale
*/
//=============================================================================
#ifndef BE_ATTRIBUTE_H
#define BE_ATTRIBUTE_H
#include "ast_attribute.h"
#include "be_field.h"
class AST_Type;
class be_visitor;
class be_attribute : public virtual AST_Attribute,
public virtual be_field
{
public:
be_attribute (bool ro,
AST_Type *ft,
UTL_ScopedName *n,
bool local,
bool abstract);
// Non-virtual override of frontend method.
be_type *field_type (void) const;
// Visiting.
virtual int accept (be_visitor *visitor);
/// Cleanup.
virtual void destroy (void);
/// Sets the original attribute from which this one was created,
/// applies only to implied IDL.
void original_attribute (be_attribute *original_attribute);
/// Returns the original attribute from which this one was created,
/// applies only to implied IDL
be_attribute *original_attribute ();
// Narrowing
DEF_NARROW_FROM_DECL (be_attribute);
};
#endif
| [
"lihuibin705@163.com"
] | lihuibin705@163.com |
f24d08ffb4af7d4395da8533871c8b70cccd8033 | 79307c7d1299fbad2a3eddcd6ad39713d30209dc | /packages/arb-avm-cpp/utils/bigint_utils.cpp | eae0a97369e0d0dfd4735f8b5bae9413bac0b1d7 | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | neuromancer/arbitrum | 05ba47c0ec315e551af48643fd7a90434994b03c | d4dc5a2c596880614d41119a13b90c09922d08de | refs/heads/master | 2022-11-17T16:40:43.458034 | 2020-06-22T15:40:26 | 2020-06-22T15:40:26 | 279,943,513 | 1 | 0 | Apache-2.0 | 2020-07-15T18:14:12 | 2020-07-15T18:14:12 | null | UTF-8 | C++ | false | false | 632 | cpp | /*
* Copyright 2019, Offchain Labs, 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 "bigint_utils.hpp"
| [
"harry@offchainlabs.com"
] | harry@offchainlabs.com |
0737c78f3c60647dac7ea3e1f7ed1c3d2b579728 | 8ceb4be36aebcc5d0e5d36389c5107f4ea7c38d1 | /Chapter11Files/EX11.23.cpp | a1982c3542296aa52338fa09b49c16b12e5f3052 | [] | no_license | StefanCardnell/C-plus-plus-primer-answers | 151b3c38efee38d0a9d2c920d39d42127140667e | a9d71a98cdad5151f203c79bd442877a43e4aaaf | refs/heads/master | 2021-05-30T23:42:41.877922 | 2016-01-24T23:47:32 | 2016-01-24T23:47:32 | 48,708,265 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,230 | cpp | //#define NDEBUG
#include <iostream>
#include <fstream> //IO file stream
#include <sstream> //stringstream
#include <iterator> //begin/end functions for arrays
#include <vector>
#include <cstring> //c-style string functions
#include <cstddef> //for size_t type and ptr_diff type
#include <cctype> //for chararacter related functions
#include <stdexcept> //Plain/Runtime/Logic exception classes
#include <initializer_list> //for initializer_list type
#include <cstdlib> //for preprocessor variables like NULL, EXIT_SUCCESS and EXIT_FAILURE
#include <cassert> //assert preprocessor macro
#include <array>
#include <list>
#include <deque>
#include <forward_list>
#include <string>
#include <stack> //sequential container adaptor
#include <queue> //sequential container adaptor, includes priority_queue
#include <algorithm>
#include <numeric> //more container algorithms
#include <functional> //for bind library function
#include <map> //for map and multimap associative containers
#include <set> //for set and multiset associative containers
#include <unordered_map> //for unordered_map and unordered_multimap
#include <unordered_set> //for unordered_set and unordered_multiset
//difference_type (iterator arithmetic) and ::size_type are for strings/vectors
//ptrdiff_t (pointer arithmetic) and size_t are for built-in arrays (inside cstddef headers!)
//-c is for separate compilation (creates .o object files)
//-D is to define preprocessor variables at the top of files (e.g. -D NDEBUG)
//-std=c++11 for C++11 support (Mingw-w64 was installed to allow c++11 extra features)
using namespace std;
int main(int argc, char* argv[]){
multimap<string, string> family;
while(cin){
cout << "Please enter the child's surname: ";
string surname;
if(getline(cin, surname)){
cout << "Please enter the children's names (on one line): ";
string children;
if(getline(cin, children)){
istringstream line(children);
for(string child; line >> child; )
family.emplace(surname, child);
}
}
}
for(const auto& c : family){
cout << c.first << ", " << c.second << endl;
}
}
| [
"raging_rush@hotmail.co.uk"
] | raging_rush@hotmail.co.uk |
941568d877eb559699fec625f074ae551df434f0 | 24c40ec66afb14f8bf5c70ea4606a2a15eaa4900 | /PluginControlInterfaceGeneric/src/CAmActionDisconnect.cpp | c04a790b8b41b17e4b2b3218deb09edc27caf510 | [
"MIT",
"MPL-2.0"
] | permissive | GENIVI/AudioManagerPlugins | b27e8d1b394de0a6bf536a067301df0dde390db1 | 2dca0ea0ec81a1fddf1aad784f73811cb60f8574 | refs/heads/master | 2023-03-31T10:25:33.333732 | 2021-02-25T11:12:43 | 2021-02-25T11:12:43 | 66,399,154 | 8 | 16 | MIT | 2021-02-25T11:12:43 | 2016-08-23T20:04:30 | C++ | UTF-8 | C++ | false | false | 5,508 | cpp | /******************************************************************************
* @file: CAmClassActionDisconnect.cpp
*
* This file contains the definition of user connection action disconnect class
* (member functions and data members) used to implement the logic of disconnect
* at user level
*
* @component: AudioManager Generic Controller
*
* @author: Toshiaki Isogai <tisogai@jp.adit-jv.com>
* Kapildev Patel <kpatel@jp.adit-jv.com>
* Prashant Jain <pjain@jp.adit-jv.com>
*
* @copyright (c) 2015 Advanced Driver Information Technology.
* This code is developed by Advanced Driver Information Technology.
* Copyright of Advanced Driver Information Technology, Bosch, and DENSO.
* All rights reserved.
*
*****************************************************************************/
#include "CAmActionDisconnect.h"
#include "CAmLogger.h"
#include "CAmClassElement.h"
#include "CAmMainConnectionElement.h"
#include "CAmMainConnectionActionDisconnect.h"
namespace am {
namespace gc {
CAmActionDisconnect::CAmActionDisconnect()
: CAmActionContainer(std::string("CAmActionDisconnect"))
{
// initialize with default
mListConnectionStatesParam.setParam({ CS_CONNECTED });
_registerParam(ACTION_PARAM_CLASS_NAME, &mClassNameParam);
_registerParam(ACTION_PARAM_SOURCE_NAME, &mSourceNameParam);
_registerParam(ACTION_PARAM_SINK_NAME, &mSinkNameParam);
_registerParam(ACTION_PARAM_CONNECTION_NAME, &mConnectionNameParam);
_registerParam(ACTION_PARAM_EXCEPT_CLASS_NAME, &mListClassExceptionsParam);
_registerParam(ACTION_PARAM_EXCEPT_SOURCE_NAME, &mlistSourceExceptionsParam);
_registerParam(ACTION_PARAM_EXCEPT_SINK_NAME, &mListSinkExceptionsParam);
_registerParam(ACTION_PARAM_CONNECTION_STATE, &mListConnectionStatesParam);
}
CAmActionDisconnect::~CAmActionDisconnect()
{
}
int CAmActionDisconnect::_execute(void)
{
std::string connectionName;
if (mConnectionNameParam.getParam(connectionName))
{
auto mainConnection = CAmMainConnectionFactory::getElement(connectionName);
if (mainConnection)
{
mpListMainConnections.push_back(mainConnection);
}
}
else
{
std::string className, sinkName, sourceName;
std::vector < am_ConnectionState_e > listConnectionStates;
std::vector < std::string > listExceptClasses;
std::vector < std::string > listExceptSources;
std::vector < std::string > listExceptSinks;
mClassNameParam.getParam(className);
mSinkNameParam.getParam(sinkName);
mSourceNameParam.getParam(sourceName);
mListConnectionStatesParam.getParam(listConnectionStates);
mListClassExceptionsParam.getParam(listExceptClasses);
mlistSourceExceptionsParam.getParam(listExceptSources);
mListSinkExceptionsParam.getParam(listExceptSinks);
// Based on the parameter get the list of the connections on which action to be taken
CAmConnectionListFilter filterObject;
filterObject.setClassName(className);
filterObject.setSourceName(sourceName);
filterObject.setSinkName(sinkName);
filterObject.setListConnectionStates(listConnectionStates);
filterObject.setListExceptClassNames(listExceptClasses);
filterObject.setListExceptSinkNames(listExceptSinks);
filterObject.setListExceptSourceNames(listExceptSources);
CAmMainConnectionFactory::getListElements(mpListMainConnections, filterObject);
connectionName = sourceName, ":", sinkName;
}
// Finally from the list of the connections create the child actions
for (auto &mainConnection : mpListMainConnections)
{
LOG_FN_INFO(__FILENAME__, __func__, connectionName, "selecting main connection"
, mainConnection->getName(), "in current state =", mainConnection->getState());
IAmActionCommand *pAction = new CAmMainConnectionActionDisconnect(mainConnection);
if (NULL != pAction)
{
auto pClassElement = mainConnection->getClassElement();
if (pClassElement)
{
CAmActionParam<gc_SetSourceStateDirection_e> setSourceStateDir;
setSourceStateDir.setParam(classTypeToDisconnectDirectionLUT[pClassElement->getClassType()]);
pAction->setParam(ACTION_PARAM_SET_SOURCE_STATE_DIRECTION, &setSourceStateDir);
}
append(pAction);
}
}
if (mpListMainConnections.size() == 0)
{
LOG_FN_INFO(__FILENAME__, __func__, connectionName, "NO connections to disconnect");
}
return E_OK;
}
int CAmActionDisconnect::_update(const int result)
{
std::vector<std::shared_ptr<CAmMainConnectionElement > >::iterator itListMainConnections;
for (itListMainConnections = mpListMainConnections.begin();
itListMainConnections != mpListMainConnections.end(); ++itListMainConnections)
{
if ((*itListMainConnections) != nullptr)
{
if ((*itListMainConnections)->permitsDispose())
{
auto pClassElement = (*itListMainConnections)->getClassElement();
if (pClassElement)
{
pClassElement->disposeConnection((*itListMainConnections));
}
*itListMainConnections = nullptr;
}
}
}
return E_OK;
}
} /* namespace gc */
} /* namespace am */
| [
"mkoch@de.adit-jv.com"
] | mkoch@de.adit-jv.com |
55eb5e525b6083303cb94e03db8efe006c47d164 | 0560f0ac0e4cf035ac0e41fe020c718960272d69 | /build/moc_coincontroldialog.cpp | 4d23cbd67179df03b6615254fbe6f4436f602070 | [
"MIT"
] | permissive | exinf/clx-wallet | 31eee4ee751e378ffc4c27e3bdf13c4f83b189b2 | 28297f53ca62ed96e3f3e5abdab04ebbdc91d371 | refs/heads/master | 2020-04-02T04:07:22.734609 | 2018-08-03T13:44:31 | 2018-08-03T13:44:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,874 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'coincontroldialog.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.9.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../src/qt/coincontroldialog.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'coincontroldialog.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.9.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_CoinControlDialog_t {
QByteArrayData data[23];
char stringdata0[353];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_CoinControlDialog_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_CoinControlDialog_t qt_meta_stringdata_CoinControlDialog = {
{
QT_MOC_LITERAL(0, 0, 17), // "CoinControlDialog"
QT_MOC_LITERAL(1, 18, 8), // "showMenu"
QT_MOC_LITERAL(2, 27, 0), // ""
QT_MOC_LITERAL(3, 28, 10), // "copyAmount"
QT_MOC_LITERAL(4, 39, 9), // "copyLabel"
QT_MOC_LITERAL(5, 49, 11), // "copyAddress"
QT_MOC_LITERAL(6, 61, 19), // "copyTransactionHash"
QT_MOC_LITERAL(7, 81, 17), // "clipboardQuantity"
QT_MOC_LITERAL(8, 99, 15), // "clipboardAmount"
QT_MOC_LITERAL(9, 115, 12), // "clipboardFee"
QT_MOC_LITERAL(10, 128, 17), // "clipboardAfterFee"
QT_MOC_LITERAL(11, 146, 14), // "clipboardBytes"
QT_MOC_LITERAL(12, 161, 17), // "clipboardPriority"
QT_MOC_LITERAL(13, 179, 18), // "clipboardLowOutput"
QT_MOC_LITERAL(14, 198, 15), // "clipboardChange"
QT_MOC_LITERAL(15, 214, 13), // "radioTreeMode"
QT_MOC_LITERAL(16, 228, 13), // "radioListMode"
QT_MOC_LITERAL(17, 242, 15), // "viewItemChanged"
QT_MOC_LITERAL(18, 258, 16), // "QTreeWidgetItem*"
QT_MOC_LITERAL(19, 275, 20), // "headerSectionClicked"
QT_MOC_LITERAL(20, 296, 16), // "buttonBoxClicked"
QT_MOC_LITERAL(21, 313, 16), // "QAbstractButton*"
QT_MOC_LITERAL(22, 330, 22) // "buttonSelectAllClicked"
},
"CoinControlDialog\0showMenu\0\0copyAmount\0"
"copyLabel\0copyAddress\0copyTransactionHash\0"
"clipboardQuantity\0clipboardAmount\0"
"clipboardFee\0clipboardAfterFee\0"
"clipboardBytes\0clipboardPriority\0"
"clipboardLowOutput\0clipboardChange\0"
"radioTreeMode\0radioListMode\0viewItemChanged\0"
"QTreeWidgetItem*\0headerSectionClicked\0"
"buttonBoxClicked\0QAbstractButton*\0"
"buttonSelectAllClicked"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_CoinControlDialog[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
19, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 1, 109, 2, 0x08 /* Private */,
3, 0, 112, 2, 0x08 /* Private */,
4, 0, 113, 2, 0x08 /* Private */,
5, 0, 114, 2, 0x08 /* Private */,
6, 0, 115, 2, 0x08 /* Private */,
7, 0, 116, 2, 0x08 /* Private */,
8, 0, 117, 2, 0x08 /* Private */,
9, 0, 118, 2, 0x08 /* Private */,
10, 0, 119, 2, 0x08 /* Private */,
11, 0, 120, 2, 0x08 /* Private */,
12, 0, 121, 2, 0x08 /* Private */,
13, 0, 122, 2, 0x08 /* Private */,
14, 0, 123, 2, 0x08 /* Private */,
15, 1, 124, 2, 0x08 /* Private */,
16, 1, 127, 2, 0x08 /* Private */,
17, 2, 130, 2, 0x08 /* Private */,
19, 1, 135, 2, 0x08 /* Private */,
20, 1, 138, 2, 0x08 /* Private */,
22, 0, 141, 2, 0x08 /* Private */,
// slots: parameters
QMetaType::Void, QMetaType::QPoint, 2,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, QMetaType::Bool, 2,
QMetaType::Void, QMetaType::Bool, 2,
QMetaType::Void, 0x80000000 | 18, QMetaType::Int, 2, 2,
QMetaType::Void, QMetaType::Int, 2,
QMetaType::Void, 0x80000000 | 21, 2,
QMetaType::Void,
0 // eod
};
void CoinControlDialog::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
CoinControlDialog *_t = static_cast<CoinControlDialog *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->showMenu((*reinterpret_cast< const QPoint(*)>(_a[1]))); break;
case 1: _t->copyAmount(); break;
case 2: _t->copyLabel(); break;
case 3: _t->copyAddress(); break;
case 4: _t->copyTransactionHash(); break;
case 5: _t->clipboardQuantity(); break;
case 6: _t->clipboardAmount(); break;
case 7: _t->clipboardFee(); break;
case 8: _t->clipboardAfterFee(); break;
case 9: _t->clipboardBytes(); break;
case 10: _t->clipboardPriority(); break;
case 11: _t->clipboardLowOutput(); break;
case 12: _t->clipboardChange(); break;
case 13: _t->radioTreeMode((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 14: _t->radioListMode((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 15: _t->viewItemChanged((*reinterpret_cast< QTreeWidgetItem*(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
case 16: _t->headerSectionClicked((*reinterpret_cast< int(*)>(_a[1]))); break;
case 17: _t->buttonBoxClicked((*reinterpret_cast< QAbstractButton*(*)>(_a[1]))); break;
case 18: _t->buttonSelectAllClicked(); break;
default: ;
}
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
switch (_id) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 17:
switch (*reinterpret_cast<int*>(_a[1])) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 0:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< QAbstractButton* >(); break;
}
break;
}
}
}
const QMetaObject CoinControlDialog::staticMetaObject = {
{ &QDialog::staticMetaObject, qt_meta_stringdata_CoinControlDialog.data,
qt_meta_data_CoinControlDialog, qt_static_metacall, nullptr, nullptr}
};
const QMetaObject *CoinControlDialog::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *CoinControlDialog::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_CoinControlDialog.stringdata0))
return static_cast<void*>(const_cast< CoinControlDialog*>(this));
return QDialog::qt_metacast(_clname);
}
int CoinControlDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QDialog::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 19)
qt_static_metacall(this, _c, _id, _a);
_id -= 19;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 19)
qt_static_metacall(this, _c, _id, _a);
_id -= 19;
}
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| [
"seif.abaza@yandex.ru"
] | seif.abaza@yandex.ru |
14789c021b08c295df6085a4ae4f0b6af1b6d348 | 5b46b0696dd152bcf254c5c0d6628d23374331f6 | /core/src/SoundQueue.cpp | 2a341cd93c4614e89540e71bd4600b2e7db7065f | [] | no_license | nwoeanhinnogaehr/Flosion | 7810a973d4446c355c86050d1bc80a79401cbb02 | cb58e1bb8abcd353b3c09e3b10964ca603c15c2b | refs/heads/master | 2020-11-26T19:50:12.107640 | 2019-12-20T04:46:34 | 2019-12-20T04:46:34 | 229,191,836 | 0 | 0 | null | 2019-12-20T04:46:53 | 2019-12-20T04:46:52 | null | UTF-8 | C++ | false | false | 1,536 | cpp | #include <Flosion/Core/SoundQueue.hpp>
namespace flo {
SoundQueue::SoundQueue(std::size_t nSamples){
resize(nSamples);
}
void SoundQueue::resize(std::size_t nSamples){
if (nSamples <= SoundChunk::size){
throw std::runtime_error("Too small");
}
m_data.clear();
m_data.resize(nSamples);
m_index = 0;
}
std::size_t SoundQueue::size() const noexcept {
return m_data.size();
}
void SoundQueue::clear(){
for (auto& s : m_data){
s.silence();
}
}
void SoundQueue::advance(std::size_t nSamples){
++m_index;
while (m_front < m_index){
m_data[m_front].silence();
++m_front;
}
}
void SoundQueue::advance(std::size_t nSamples, SingleSoundInput& input, const SoundNode* target, const SoundState* state){
if (nSamples > m_data.size()){
throw std::runtime_error("Too long");
}
m_index = (m_index + nSamples) % m_data.size();
while ((m_front + SoundChunk::size) % m_data.size() <= m_index){
SoundChunk ch;
input.getNextChunkFor(ch, target, state);
for (std::size_t i = 0; i < ch.size; ++i){
m_data[m_front] = ch[i];
++m_front;
}
}
}
Sample& SoundQueue::operator[](std::size_t index) noexcept {
assert(index < m_data.size());
return m_data[(m_index + index) % m_data.size()];
}
} // namespace flo
| [
"f2a0b@ugrad.cs.ubc.ca"
] | f2a0b@ugrad.cs.ubc.ca |
c15d977009fd75a0a723b3ec6cb3ce11fe54fdba | 2e714640e713ce667af0dea7955eee6f4e4f6d0f | /mc/src/connection/connection.cpp | 2c69a3faeb2d9a98c2464121a441059178bf824f | [] | no_license | DomWilliams0/mc-server | bc0f81146301be01564b17cf8695cdefc6e25cb2 | a27066e7c0952f9ac1664ed8896719392c27e3e1 | refs/heads/master | 2020-06-20T20:38:26.597113 | 2019-07-19T20:09:29 | 2019-07-19T20:27:41 | 197,241,182 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 974 | cpp | #include "connection.h"
#include "packet.h"
#include "loguru.hpp"
#include <sstream>
#include <cassert>
mc::BaseConnection::BaseConnection(const mc::Socket &socket) : socket(socket) {}
mc::BaseConnection *mc::BaseConnection::handle_packet(mc::Buffer &packet) {
// parse header
Varint packet_id;
packet.read(packet_id);
DLOG_F(INFO, "packet id is %d", *packet_id);
// pass off to this connection to read and handle
mc::PacketClientBound *response = nullptr;
BaseConnection *new_connection = handle_packet(*packet_id, packet, &response);
// send response if necessary
if (response != nullptr) {
DLOG_F(INFO, "sending response: %s", response->to_string().c_str());
mc::Buffer buffer;
response->write(buffer);
socket.write(buffer);
}
assert(new_connection != nullptr);
return new_connection;
}
mc::BaseConnection::BaseConnection(const mc::BaseConnection &other) : socket(other.socket) {}
| [
"me@domwillia.ms"
] | me@domwillia.ms |
6b4996fa39894f2896e78b383c24f64d2c0385df | 484baba7db5afb43168c6b166d9be535156f0075 | /proton-c/bindings/cpp/src/include/proactor_work_queue_impl.hpp | 1c94254a8a31b90a4ab1745988728802883d3f73 | [
"Apache-2.0",
"BSD-3-Clause"
] | permissive | Horadrim-TalRasha/qpid-proton | fded7d9164852ea7da84cae27453552ba65fd7e7 | 7a5ded793ef436dd1a1654345420c40926b27712 | refs/heads/master | 2021-06-25T19:44:20.793823 | 2017-09-08T16:08:14 | 2017-09-08T16:08:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,199 | hpp | #ifndef PROTON_CPP_EVENT_LOOP_IMPL_HPP
#define PROTON_CPP_EVENT_LOOP_IMPL_HPP
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 "proton/fwd.hpp"
namespace proton {
class work_queue::impl {
public:
virtual ~impl() {};
virtual bool add(work f) = 0;
virtual void schedule(duration, work) = 0;
virtual void run_all_jobs() = 0;
virtual void finished() = 0;
};
}
#endif // PROTON_CPP_EVENT_LOOP_IMPL_HPP
| [
"astitcher@apache.org"
] | astitcher@apache.org |
b825b67f5ec376eaea1c2cac0150e9d9ba5c4083 | a946c5eaa8fffacc561338076019413f76d56b85 | /Array/FindDuplicateArray.cpp | 1b035bfcb40eaf21f37f1e6016cfa4683dd03850 | [] | no_license | truongthiphuongthao/LearnCode | a77d5a5aea1a3247e58241d230b1a9c5c2da2ff3 | e0042e5b0227b06000d3bf29e88e40093c069d80 | refs/heads/master | 2023-03-25T02:46:02.368914 | 2021-03-20T14:35:49 | 2021-03-20T14:35:49 | 338,282,914 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 586 | cpp | #include <bits/stdc++.h>
using namespace std;
void findDuplicateArray(int arr[], int n){
bool f[n];
for(int i=0; i<n; i++){
f[i] = false;
}
for(int i=0; i<n ;i++){
if(f[i]){
continue;
}
int count = 0;
for(int j=0; j<n; j++){
if(arr[i] == arr[j]){
f[j] = true;
count ++;
}
}
if(count > 1){
cout << arr[i] << " ";
}
}
}
int main(){
freopen("data.txt", "r", stdin);
int arr[100];
int n;
cin >> n;
for(int i=0; i<n; i++){
cin >> arr[i];
}
for(int i=0; i<n ;i++){
cout << arr[i] << " ";
}
cout << "\n";
findDuplicateArray(arr, n);
}
| [
"thaotruong199826@gmail.com"
] | thaotruong199826@gmail.com |
32ef8111f87c02f277b1f094fdca995a38ad3418 | f96a5c7dae0d0690a86c2488dd5082db5d27b299 | /gen/Ce3_vec22_NaoH25V50.hh | ea651dc380d71d54894c59710f90d10a47479d41 | [] | no_license | TRACE-Lab/MECH5305-Nao-walking | 8a60c7593066cf239fd9cf00d6fc0f2c361c5ca5 | 0968361dcf9ff6660631b01c064126e9e21bfe92 | refs/heads/master | 2022-04-22T22:04:28.225754 | 2020-04-21T21:48:23 | 2020-04-21T21:48:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 930 | hh | /*
* Automatically Generated from Mathematica.
* Tue 10 Jul 2018 11:14:28 GMT-04:00
*/
#ifndef CE3_VEC22_NAOH25V50_HH
#define CE3_VEC22_NAOH25V50_HH
#ifdef MATLAB_MEX_FILE
// No need for external definitions
#else // MATLAB_MEX_FILE
#include "math2mat.hpp"
#include "mdefs.hpp"
namespace SymFunction
{
void Ce3_vec22_NaoH25V50_raw(double *p_output1, const double *var1,const double *var2);
inline void Ce3_vec22_NaoH25V50(Eigen::MatrixXd &p_output1, const Eigen::VectorXd &var1,const Eigen::VectorXd &var2)
{
// Check
// - Inputs
assert_size_matrix(var1, 30, 1);
assert_size_matrix(var2, 30, 1);
// - Outputs
assert_size_matrix(p_output1, 30, 1);
// set zero the matrix
p_output1.setZero();
// Call Subroutine with raw data
Ce3_vec22_NaoH25V50_raw(p_output1.data(), var1.data(),var2.data());
}
}
#endif // MATLAB_MEX_FILE
#endif // CE3_VEC22_NAOH25V50_HH
| [
"yuangao@Yuans-MacBook-Pro.local"
] | yuangao@Yuans-MacBook-Pro.local |
6720031d2f97fda5f25be215e2f62f7b201444c7 | 86ecfa4449ee010ff2b508e8e3573f5f003f3775 | /hw-6-Generics/KeyValue.h | 5aeafcd37ccb74f22ab30450b568862d63f8993b | [] | no_license | McKay-J/1440 | a57f30c1f2f374554b71985c9f9d25686b1bf864 | 5d5674ca324d8f3d14b311fc0ddeaff75955a66d | refs/heads/master | 2021-01-19T11:32:47.392957 | 2017-04-29T04:04:29 | 2017-04-29T04:04:29 | 82,253,518 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 860 | h | //
// Created by McKay Jensen on 4/3/2017.
//
#ifndef GENERICDICTIONARY_KEYVALUE_H
#define GENERICDICTIONARY_KEYVALUE_H
template <typename KeyType, typename ValueType>
class KeyValue {
private:
KeyType m_key;
ValueType m_value;
public:
KeyValue<KeyType, ValueType>(KeyType key, ValueType value) : m_key(key), m_value(value) //overloaded
{}
KeyValue<KeyType, ValueType>() //default constructor
{}
KeyType getKey() const { return m_key; }
ValueType getValue() const { return m_value; }
KeyValue(const KeyValue<KeyType, ValueType>& obj); //copy constructor
};
template <typename KeyType, typename ValueType>
KeyValue<KeyType, ValueType>::KeyValue(const KeyValue<KeyType, ValueType>& obj) //implementing copy constructor
{
m_key = obj.m_key;
m_value = obj.m_value;
}
#endif //GENERICDICTIONARY_KEYVALUE_H
| [
"mckay.jensen@aggiemail.usu.edu"
] | mckay.jensen@aggiemail.usu.edu |
92a9ae20f47a694a8ca32ff75b5c1f3fe7a5ba61 | 713659538c3e4d0d332d43002b7ef96400ed6b53 | /src/game/generated/gs_data.cpp | 31ae146a72506d21a1b71a422ed4cffa51eb4514 | [
"LicenseRef-scancode-other-permissive",
"Zlib",
"BSD-3-Clause"
] | permissive | Berzzzebub/TeeFork | 449b31ce836a47476efa15f32930a28908a56b37 | 53142119f62af52379b7a5e7344f38b1b2e56cf7 | refs/heads/master | 2016-09-06T08:21:23.745520 | 2010-12-12T09:37:52 | 2010-12-12T09:37:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,882 | cpp | #include "gs_data.hpp"
static SOUND x1890[] = {
/* x1890[0] */ { 0, "audio/wp_gun_fire-01.wv", },
/* x1890[1] */ { 0, "audio/wp_gun_fire-02.wv", },
/* x1890[2] */ { 0, "audio/wp_gun_fire-03.wv", },
};
static SOUND x1906[] = {
/* x1906[0] */ { 0, "audio/wp_shotty_fire-01.wv", },
/* x1906[1] */ { 0, "audio/wp_shotty_fire-02.wv", },
/* x1906[2] */ { 0, "audio/wp_shotty_fire-03.wv", },
};
static SOUND x1922[] = {
/* x1922[0] */ { 0, "audio/wp_flump_launch-01.wv", },
/* x1922[1] */ { 0, "audio/wp_flump_launch-02.wv", },
/* x1922[2] */ { 0, "audio/wp_flump_launch-03.wv", },
};
static SOUND x1938[] = {
/* x1938[0] */ { 0, "audio/wp_hammer_swing-01.wv", },
/* x1938[1] */ { 0, "audio/wp_hammer_swing-02.wv", },
/* x1938[2] */ { 0, "audio/wp_hammer_swing-03.wv", },
};
static SOUND x1954[] = {
/* x1954[0] */ { 0, "audio/wp_hammer_hit-01.wv", },
/* x1954[1] */ { 0, "audio/wp_hammer_hit-02.wv", },
/* x1954[2] */ { 0, "audio/wp_hammer_hit-03.wv", },
};
static SOUND x1970[] = {
/* x1970[0] */ { 0, "audio/wp_ninja_attack-01.wv", },
/* x1970[1] */ { 0, "audio/wp_ninja_attack-02.wv", },
/* x1970[2] */ { 0, "audio/wp_ninja_attack-03.wv", },
};
static SOUND x1986[] = {
/* x1986[0] */ { 0, "audio/wp_flump_explo-01.wv", },
/* x1986[1] */ { 0, "audio/wp_flump_explo-02.wv", },
/* x1986[2] */ { 0, "audio/wp_flump_explo-03.wv", },
};
static SOUND x2002[] = {
/* x2002[0] */ { 0, "audio/wp_ninja_hit-01.wv", },
/* x2002[1] */ { 0, "audio/wp_ninja_hit-02.wv", },
/* x2002[2] */ { 0, "audio/wp_ninja_hit-03.wv", },
};
static SOUND x2018[] = {
/* x2018[0] */ { 0, "audio/wp_rifle_fire-01.wv", },
/* x2018[1] */ { 0, "audio/wp_rifle_fire-02.wv", },
/* x2018[2] */ { 0, "audio/wp_rifle_fire-03.wv", },
};
static SOUND x2034[] = {
/* x2034[0] */ { 0, "audio/wp_rifle_bnce-01.wv", },
/* x2034[1] */ { 0, "audio/wp_rifle_bnce-02.wv", },
/* x2034[2] */ { 0, "audio/wp_rifle_bnce-03.wv", },
};
static SOUND x2050[] = {
/* x2050[0] */ { 0, "audio/wp_switch-01.wv", },
/* x2050[1] */ { 0, "audio/wp_switch-02.wv", },
/* x2050[2] */ { 0, "audio/wp_switch-03.wv", },
};
static SOUND x2066[] = {
/* x2066[0] */ { 0, "audio/vo_teefault_pain_short-01.wv", },
/* x2066[1] */ { 0, "audio/vo_teefault_pain_short-02.wv", },
/* x2066[2] */ { 0, "audio/vo_teefault_pain_short-03.wv", },
/* x2066[3] */ { 0, "audio/vo_teefault_pain_short-04.wv", },
/* x2066[4] */ { 0, "audio/vo_teefault_pain_short-05.wv", },
/* x2066[5] */ { 0, "audio/vo_teefault_pain_short-06.wv", },
/* x2066[6] */ { 0, "audio/vo_teefault_pain_short-07.wv", },
/* x2066[7] */ { 0, "audio/vo_teefault_pain_short-08.wv", },
/* x2066[8] */ { 0, "audio/vo_teefault_pain_short-09.wv", },
/* x2066[9] */ { 0, "audio/vo_teefault_pain_short-10.wv", },
/* x2066[10] */ { 0, "audio/vo_teefault_pain_short-11.wv", },
/* x2066[11] */ { 0, "audio/vo_teefault_pain_short-12.wv", },
};
static SOUND x2109[] = {
/* x2109[0] */ { 0, "audio/vo_teefault_pain_long-01.wv", },
/* x2109[1] */ { 0, "audio/vo_teefault_pain_long-02.wv", },
};
static SOUND x2122[] = {
/* x2122[0] */ { 0, "audio/foley_land-01.wv", },
/* x2122[1] */ { 0, "audio/foley_land-02.wv", },
/* x2122[2] */ { 0, "audio/foley_land-03.wv", },
/* x2122[3] */ { 0, "audio/foley_land-04.wv", },
};
static SOUND x2141[] = {
/* x2141[0] */ { 0, "audio/foley_dbljump-01.wv", },
/* x2141[1] */ { 0, "audio/foley_dbljump-02.wv", },
/* x2141[2] */ { 0, "audio/foley_dbljump-03.wv", },
};
static SOUND x2157[] = {
/* x2157[0] */ { 0, "audio/foley_foot_left-01.wv", },
/* x2157[1] */ { 0, "audio/foley_foot_left-02.wv", },
/* x2157[2] */ { 0, "audio/foley_foot_left-03.wv", },
/* x2157[3] */ { 0, "audio/foley_foot_left-04.wv", },
/* x2157[4] */ { 0, "audio/foley_foot_right-01.wv", },
/* x2157[5] */ { 0, "audio/foley_foot_right-02.wv", },
/* x2157[6] */ { 0, "audio/foley_foot_right-03.wv", },
/* x2157[7] */ { 0, "audio/foley_foot_right-04.wv", },
};
static SOUND x2188[] = {
/* x2188[0] */ { 0, "audio/foley_body_splat-01.wv", },
/* x2188[1] */ { 0, "audio/foley_body_splat-02.wv", },
/* x2188[2] */ { 0, "audio/foley_body_splat-03.wv", },
};
static SOUND x2204[] = {
/* x2204[0] */ { 0, "audio/vo_teefault_spawn-01.wv", },
/* x2204[1] */ { 0, "audio/vo_teefault_spawn-02.wv", },
/* x2204[2] */ { 0, "audio/vo_teefault_spawn-03.wv", },
/* x2204[3] */ { 0, "audio/vo_teefault_spawn-04.wv", },
/* x2204[4] */ { 0, "audio/vo_teefault_spawn-05.wv", },
/* x2204[5] */ { 0, "audio/vo_teefault_spawn-06.wv", },
/* x2204[6] */ { 0, "audio/vo_teefault_spawn-07.wv", },
};
static SOUND x2232[] = {
/* x2232[0] */ { 0, "audio/sfx_skid-01.wv", },
/* x2232[1] */ { 0, "audio/sfx_skid-02.wv", },
/* x2232[2] */ { 0, "audio/sfx_skid-03.wv", },
/* x2232[3] */ { 0, "audio/sfx_skid-04.wv", },
};
static SOUND x2251[] = {
/* x2251[0] */ { 0, "audio/vo_teefault_cry-01.wv", },
/* x2251[1] */ { 0, "audio/vo_teefault_cry-02.wv", },
};
static SOUND x2264[] = {
/* x2264[0] */ { 0, "audio/hook_loop-01.wv", },
/* x2264[1] */ { 0, "audio/hook_loop-02.wv", },
};
static SOUND x2277[] = {
/* x2277[0] */ { 0, "audio/hook_attach-01.wv", },
/* x2277[1] */ { 0, "audio/hook_attach-02.wv", },
/* x2277[2] */ { 0, "audio/hook_attach-03.wv", },
};
static SOUND x2293[] = {
/* x2293[0] */ { 0, "audio/foley_body_impact-01.wv", },
/* x2293[1] */ { 0, "audio/foley_body_impact-02.wv", },
/* x2293[2] */ { 0, "audio/foley_body_impact-03.wv", },
};
static SOUND x2309[] = {
/* x2309[0] */ { 0, "audio/hook_noattach-01.wv", },
/* x2309[1] */ { 0, "audio/hook_noattach-02.wv", },
};
static SOUND x2322[] = {
/* x2322[0] */ { 0, "audio/sfx_pickup_hrt-01.wv", },
/* x2322[1] */ { 0, "audio/sfx_pickup_hrt-02.wv", },
};
static SOUND x2335[] = {
/* x2335[0] */ { 0, "audio/sfx_pickup_arm-01.wv", },
/* x2335[1] */ { 0, "audio/sfx_pickup_arm-02.wv", },
/* x2335[2] */ { 0, "audio/sfx_pickup_arm-03.wv", },
/* x2335[3] */ { 0, "audio/sfx_pickup_arm-04.wv", },
};
static SOUND x2354[] = {
/* x2354[0] */ { 0, "audio/sfx_pickup_launcher.wv", },
};
static SOUND x2364[] = {
/* x2364[0] */ { 0, "audio/sfx_pickup_sg.wv", },
};
static SOUND x2374[] = {
/* x2374[0] */ { 0, "audio/sfx_pickup_ninja.wv", },
};
static SOUND x2384[] = {
/* x2384[0] */ { 0, "audio/sfx_spawn_wpn-01.wv", },
/* x2384[1] */ { 0, "audio/sfx_spawn_wpn-02.wv", },
/* x2384[2] */ { 0, "audio/sfx_spawn_wpn-03.wv", },
};
static SOUND x2400[] = {
/* x2400[0] */ { 0, "audio/wp_noammo-01.wv", },
/* x2400[1] */ { 0, "audio/wp_noammo-02.wv", },
/* x2400[2] */ { 0, "audio/wp_noammo-03.wv", },
/* x2400[3] */ { 0, "audio/wp_noammo-04.wv", },
/* x2400[4] */ { 0, "audio/wp_noammo-05.wv", },
};
static SOUND x2422[] = {
/* x2422[0] */ { 0, "audio/sfx_hit_weak-01.wv", },
/* x2422[1] */ { 0, "audio/sfx_hit_weak-02.wv", },
};
static SOUND x2435[] = {
/* x2435[0] */ { 0, "audio/sfx_msg-server.wv", },
};
static SOUND x2445[] = {
/* x2445[0] */ { 0, "audio/sfx_msg-client.wv", },
};
static SOUND x2455[] = {
/* x2455[0] */ { 0, "audio/sfx_ctf_drop.wv", },
};
static SOUND x2465[] = {
/* x2465[0] */ { 0, "audio/sfx_ctf_rtn.wv", },
};
static SOUND x2475[] = {
/* x2475[0] */ { 0, "audio/sfx_ctf_grab_pl.wv", },
};
static SOUND x2485[] = {
/* x2485[0] */ { 0, "audio/sfx_ctf_grab_en.wv", },
};
static SOUND x2495[] = {
/* x2495[0] */ { 0, "audio/sfx_ctf_cap_pl.wv", },
};
static SOUNDSET x9[] = {
/* x9[0] */ { "gun_fire", 3,x1890, -1, },
/* x9[1] */ { "shotgun_fire", 3,x1906, -1, },
/* x9[2] */ { "grenade_fire", 3,x1922, -1, },
/* x9[3] */ { "hammer_fire", 3,x1938, -1, },
/* x9[4] */ { "hammer_hit", 3,x1954, -1, },
/* x9[5] */ { "ninja_fire", 3,x1970, -1, },
/* x9[6] */ { "grenade_explode", 3,x1986, -1, },
/* x9[7] */ { "ninja_hit", 3,x2002, -1, },
/* x9[8] */ { "rifle_fire", 3,x2018, -1, },
/* x9[9] */ { "rifle_bounce", 3,x2034, -1, },
/* x9[10] */ { "weapon_switch", 3,x2050, -1, },
/* x9[11] */ { "player_pain_short", 12,x2066, -1, },
/* x9[12] */ { "player_pain_long", 2,x2109, -1, },
/* x9[13] */ { "body_land", 4,x2122, -1, },
/* x9[14] */ { "player_airjump", 3,x2141, -1, },
/* x9[15] */ { "player_jump", 8,x2157, -1, },
/* x9[16] */ { "player_die", 3,x2188, -1, },
/* x9[17] */ { "player_spawn", 7,x2204, -1, },
/* x9[18] */ { "player_skid", 4,x2232, -1, },
/* x9[19] */ { "tee_cry", 2,x2251, -1, },
/* x9[20] */ { "hook_loop", 2,x2264, -1, },
/* x9[21] */ { "hook_attach_ground", 3,x2277, -1, },
/* x9[22] */ { "hook_attach_player", 3,x2293, -1, },
/* x9[23] */ { "hook_noattach", 2,x2309, -1, },
/* x9[24] */ { "pickup_health", 2,x2322, -1, },
/* x9[25] */ { "pickup_armor", 4,x2335, -1, },
/* x9[26] */ { "pickup_grenade", 1,x2354, -1, },
/* x9[27] */ { "pickup_shotgun", 1,x2364, -1, },
/* x9[28] */ { "pickup_ninja", 1,x2374, -1, },
/* x9[29] */ { "weapon_spawn", 3,x2384, -1, },
/* x9[30] */ { "weapon_noammo", 5,x2400, -1, },
/* x9[31] */ { "hit", 2,x2422, -1, },
/* x9[32] */ { "chat_server", 1,x2435, -1, },
/* x9[33] */ { "chat_client", 1,x2445, -1, },
/* x9[34] */ { "ctf_drop", 1,x2455, -1, },
/* x9[35] */ { "ctf_return", 1,x2465, -1, },
/* x9[36] */ { "ctf_grab_pl", 1,x2475, -1, },
/* x9[37] */ { "ctf_grab_en", 1,x2485, -1, },
/* x9[38] */ { "ctf_capture", 1,x2495, -1, },
};
static IMAGE x14[] = {
/* x14[0] */ { "null", "", -1, },
/* x14[1] */ { "game", "game.png", -1, },
/* x14[2] */ { "game_gray", "game.png", -1, },
/* x14[3] */ { "particles", "particles.png", -1, },
/* x14[4] */ { "cursor", "gui_cursor.png", -1, },
/* x14[5] */ { "banner", "gui_logo.png", -1, },
/* x14[6] */ { "emoticons", "emoticons.png", -1, },
/* x14[7] */ { "browseicons", "browse_icons.png", -1, },
/* x14[8] */ { "console_bg", "console.png", -1, },
/* x14[9] */ { "console_bar", "console_bar.png", -1, },
};
static PICKUPSPEC x19[] = {
/* x19[0] */ { "health", 15, 0, },
/* x19[1] */ { "armor", 15, 0, },
/* x19[2] */ { "weapon", 15, 0, },
/* x19[3] */ { "ninja", 90, 90, },
};
static SPRITESET x28[] = {
/* x28[0] */ { &x14[3], 8, 8, },
/* x28[1] */ { &x14[1], 32, 16, },
/* x28[2] */ { &x14[0], 8, 4, },
/* x28[3] */ { &x14[7], 4, 1, },
/* x28[4] */ { &x14[6], 4, 4, },
};
static SPRITE x44[] = {
/* x44[0] */ { "part_slice", &x28[0], 0, 0, 1, 1, },
/* x44[1] */ { "part_ball", &x28[0], 1, 0, 1, 1, },
/* x44[2] */ { "part_splat01", &x28[0], 2, 0, 1, 1, },
/* x44[3] */ { "part_splat02", &x28[0], 3, 0, 1, 1, },
/* x44[4] */ { "part_splat03", &x28[0], 4, 0, 1, 1, },
/* x44[5] */ { "part_smoke", &x28[0], 0, 1, 1, 1, },
/* x44[6] */ { "part_shell", &x28[0], 0, 2, 2, 2, },
/* x44[7] */ { "part_expl01", &x28[0], 0, 4, 4, 4, },
/* x44[8] */ { "part_airjump", &x28[0], 2, 2, 2, 2, },
/* x44[9] */ { "health_full", &x28[1], 21, 0, 2, 2, },
/* x44[10] */ { "health_empty", &x28[1], 23, 0, 2, 2, },
/* x44[11] */ { "armor_full", &x28[1], 21, 2, 2, 2, },
/* x44[12] */ { "armor_empty", &x28[1], 23, 2, 2, 2, },
/* x44[13] */ { "star1", &x28[1], 15, 0, 2, 2, },
/* x44[14] */ { "star2", &x28[1], 17, 0, 2, 2, },
/* x44[15] */ { "star3", &x28[1], 19, 0, 2, 2, },
/* x44[16] */ { "part1", &x28[1], 6, 0, 1, 1, },
/* x44[17] */ { "part2", &x28[1], 6, 1, 1, 1, },
/* x44[18] */ { "part3", &x28[1], 7, 0, 1, 1, },
/* x44[19] */ { "part4", &x28[1], 7, 1, 1, 1, },
/* x44[20] */ { "part5", &x28[1], 8, 0, 1, 1, },
/* x44[21] */ { "part6", &x28[1], 8, 1, 1, 1, },
/* x44[22] */ { "part7", &x28[1], 9, 0, 2, 2, },
/* x44[23] */ { "part8", &x28[1], 11, 0, 2, 2, },
/* x44[24] */ { "part9", &x28[1], 13, 0, 2, 2, },
/* x44[25] */ { "weapon_gun_body", &x28[1], 2, 4, 4, 2, },
/* x44[26] */ { "weapon_gun_cursor", &x28[1], 0, 4, 2, 2, },
/* x44[27] */ { "weapon_gun_proj", &x28[1], 6, 4, 2, 2, },
/* x44[28] */ { "weapon_gun_muzzle1", &x28[1], 8, 4, 3, 2, },
/* x44[29] */ { "weapon_gun_muzzle2", &x28[1], 12, 4, 3, 2, },
/* x44[30] */ { "weapon_gun_muzzle3", &x28[1], 16, 4, 3, 2, },
/* x44[31] */ { "weapon_shotgun_body", &x28[1], 2, 6, 8, 2, },
/* x44[32] */ { "weapon_shotgun_cursor", &x28[1], 0, 6, 2, 2, },
/* x44[33] */ { "weapon_shotgun_proj", &x28[1], 10, 6, 2, 2, },
/* x44[34] */ { "weapon_shotgun_muzzle1", &x28[1], 12, 6, 3, 2, },
/* x44[35] */ { "weapon_shotgun_muzzle2", &x28[1], 16, 6, 3, 2, },
/* x44[36] */ { "weapon_shotgun_muzzle3", &x28[1], 20, 6, 3, 2, },
/* x44[37] */ { "weapon_grenade_body", &x28[1], 2, 8, 7, 2, },
/* x44[38] */ { "weapon_grenade_cursor", &x28[1], 0, 8, 2, 2, },
/* x44[39] */ { "weapon_grenade_proj", &x28[1], 10, 8, 2, 2, },
/* x44[40] */ { "weapon_hammer_body", &x28[1], 2, 1, 4, 3, },
/* x44[41] */ { "weapon_hammer_cursor", &x28[1], 0, 0, 2, 2, },
/* x44[42] */ { "weapon_hammer_proj", &x28[1], 0, 0, 0, 0, },
/* x44[43] */ { "weapon_ninja_body", &x28[1], 2, 10, 7, 2, },
/* x44[44] */ { "weapon_ninja_cursor", &x28[1], 0, 10, 2, 2, },
/* x44[45] */ { "weapon_ninja_proj", &x28[1], 0, 0, 0, 0, },
/* x44[46] */ { "weapon_rifle_body", &x28[1], 2, 12, 7, 3, },
/* x44[47] */ { "weapon_rifle_cursor", &x28[1], 0, 12, 2, 2, },
/* x44[48] */ { "weapon_rifle_proj", &x28[1], 10, 12, 2, 2, },
/* x44[49] */ { "hook_chain", &x28[1], 2, 0, 1, 1, },
/* x44[50] */ { "hook_head", &x28[1], 3, 0, 2, 1, },
/* x44[51] */ { "weapon_ninja_muzzle1", &x28[1], 25, 0, 7, 4, },
/* x44[52] */ { "weapon_ninja_muzzle2", &x28[1], 25, 4, 7, 4, },
/* x44[53] */ { "weapon_ninja_muzzle3", &x28[1], 25, 8, 7, 4, },
/* x44[54] */ { "pickup_health", &x28[1], 10, 2, 2, 2, },
/* x44[55] */ { "pickup_armor", &x28[1], 12, 2, 2, 2, },
/* x44[56] */ { "pickup_weapon", &x28[1], 3, 0, 6, 2, },
/* x44[57] */ { "pickup_ninja", &x28[1], 3, 10, 7, 2, },
/* x44[58] */ { "flag_blue", &x28[1], 12, 8, 4, 8, },
/* x44[59] */ { "flag_red", &x28[1], 16, 8, 4, 8, },
/* x44[60] */ { "tee_body", &x28[2], 0, 0, 3, 3, },
/* x44[61] */ { "tee_body_outline", &x28[2], 3, 0, 3, 3, },
/* x44[62] */ { "tee_foot", &x28[2], 6, 1, 2, 1, },
/* x44[63] */ { "tee_foot_outline", &x28[2], 6, 2, 2, 1, },
/* x44[64] */ { "tee_hand", &x28[2], 6, 0, 1, 1, },
/* x44[65] */ { "tee_hand_outline", &x28[2], 7, 0, 1, 1, },
/* x44[66] */ { "tee_eye_normal", &x28[2], 2, 3, 1, 1, },
/* x44[67] */ { "tee_eye_angry", &x28[2], 3, 3, 1, 1, },
/* x44[68] */ { "tee_eye_pain", &x28[2], 4, 3, 1, 1, },
/* x44[69] */ { "tee_eye_happy", &x28[2], 5, 3, 1, 1, },
/* x44[70] */ { "tee_eye_dead", &x28[2], 6, 3, 1, 1, },
/* x44[71] */ { "tee_eye_surprise", &x28[2], 7, 3, 1, 1, },
/* x44[72] */ { "oop", &x28[4], 0, 0, 1, 1, },
/* x44[73] */ { "exclamation", &x28[4], 1, 0, 1, 1, },
/* x44[74] */ { "hearts", &x28[4], 2, 0, 1, 1, },
/* x44[75] */ { "drop", &x28[4], 3, 0, 1, 1, },
/* x44[76] */ { "dotdot", &x28[4], 0, 1, 1, 1, },
/* x44[77] */ { "music1", &x28[4], 1, 1, 1, 1, },
/* x44[78] */ { "music2", &x28[4], 2, 1, 1, 1, },
/* x44[79] */ { "ghost", &x28[4], 3, 1, 1, 1, },
/* x44[80] */ { "sushi", &x28[4], 0, 2, 1, 1, },
/* x44[81] */ { "splattee", &x28[4], 1, 2, 1, 1, },
/* x44[82] */ { "deviltee", &x28[4], 2, 2, 1, 1, },
/* x44[83] */ { "zomg", &x28[4], 3, 2, 1, 1, },
/* x44[84] */ { "zzz", &x28[4], 0, 3, 1, 1, },
/* x44[85] */ { "blank1", &x28[4], 1, 3, 1, 1, },
/* x44[86] */ { "deadtee", &x28[4], 2, 3, 1, 1, },
/* x44[87] */ { "blank2", &x28[4], 3, 3, 1, 1, },
/* x44[88] */ { "browse_lock", &x28[3], 0, 0, 1, 1, },
/* x44[89] */ { "browse_heart", &x28[3], 1, 0, 1, 1, },
/* x44[90] */ { "browse_unpure", &x28[3], 3, 0, 1, 1, },
};
static ANIM_KEYFRAME x3969[] = {
/* x3969[0] */ { 0.000000, 0.000000, -4.000000, 0.000000, },
};
static ANIM_KEYFRAME x3976[] = {
/* x3976[0] */ { 0.000000, 0.000000, 10.000000, 0.000000, },
};
static ANIM_KEYFRAME x3983[] = {
/* x3983[0] */ { 0.000000, 0.000000, 10.000000, 0.000000, },
};
static ANIM_KEYFRAME *x3990 = 0;
static ANIM_KEYFRAME *x4014 = 0;
static ANIM_KEYFRAME x4021[] = {
/* x4021[0] */ { 0.000000, -7.000000, 0.000000, 0.000000, },
};
static ANIM_KEYFRAME x4028[] = {
/* x4028[0] */ { 0.000000, 7.000000, 0.000000, 0.000000, },
};
static ANIM_KEYFRAME *x4035 = 0;
static ANIM_KEYFRAME *x4054 = 0;
static ANIM_KEYFRAME x4061[] = {
/* x4061[0] */ { 0.000000, -3.000000, 0.000000, -0.100000, },
};
static ANIM_KEYFRAME x4068[] = {
/* x4068[0] */ { 0.000000, 3.000000, 0.000000, -0.100000, },
};
static ANIM_KEYFRAME *x4075 = 0;
static ANIM_KEYFRAME x4094[] = {
/* x4094[0] */ { 0.000000, 0.000000, 0.000000, 0.000000, },
/* x4094[1] */ { 0.200000, 0.000000, -1.000000, 0.000000, },
/* x4094[2] */ { 0.400000, 0.000000, 0.000000, 0.000000, },
/* x4094[3] */ { 0.600000, 0.000000, 0.000000, 0.000000, },
/* x4094[4] */ { 0.800000, 0.000000, -1.000000, 0.000000, },
/* x4094[5] */ { 1.000000, 0.000000, 0.000000, 0.000000, },
};
static ANIM_KEYFRAME x4101[] = {
/* x4101[0] */ { 0.000000, 8.000000, 0.000000, 0.000000, },
/* x4101[1] */ { 0.200000, -8.000000, 0.000000, 0.000000, },
/* x4101[2] */ { 0.400000, -10.000000, -4.000000, 0.200000, },
/* x4101[3] */ { 0.600000, -8.000000, -8.000000, 0.300000, },
/* x4101[4] */ { 0.800000, 4.000000, -4.000000, -0.200000, },
/* x4101[5] */ { 1.000000, 8.000000, 0.000000, 0.000000, },
};
static ANIM_KEYFRAME x4108[] = {
/* x4108[0] */ { 0.000000, -10.000000, -4.000000, 0.200000, },
/* x4108[1] */ { 0.200000, -8.000000, -8.000000, 0.300000, },
/* x4108[2] */ { 0.400000, 4.000000, -4.000000, -0.200000, },
/* x4108[3] */ { 0.600000, 8.000000, 0.000000, 0.000000, },
/* x4108[4] */ { 0.800000, 8.000000, 0.000000, 0.000000, },
/* x4108[5] */ { 1.000000, -10.000000, -4.000000, 0.200000, },
};
static ANIM_KEYFRAME *x4115 = 0;
static ANIM_KEYFRAME *x4214 = 0;
static ANIM_KEYFRAME *x4221 = 0;
static ANIM_KEYFRAME *x4228 = 0;
static ANIM_KEYFRAME x4235[] = {
/* x4235[0] */ { 0.000000, 0.000000, 0.000000, -0.100000, },
/* x4235[1] */ { 0.300000, 0.000000, 0.000000, 0.250000, },
/* x4235[2] */ { 0.400000, 0.000000, 0.000000, 0.300000, },
/* x4235[3] */ { 0.500000, 0.000000, 0.000000, 0.250000, },
/* x4235[4] */ { 1.000000, 0.000000, 0.000000, -0.100000, },
};
static ANIM_KEYFRAME *x4269 = 0;
static ANIM_KEYFRAME *x4276 = 0;
static ANIM_KEYFRAME *x4283 = 0;
static ANIM_KEYFRAME x4290[] = {
/* x4290[0] */ { 0.000000, 0.000000, 0.000000, -0.250000, },
/* x4290[1] */ { 0.100000, 0.000000, 0.000000, -0.050000, },
/* x4290[2] */ { 0.150000, 0.000000, 0.000000, 0.350000, },
/* x4290[3] */ { 0.420000, 0.000000, 0.000000, 0.400000, },
/* x4290[4] */ { 0.500000, 0.000000, 0.000000, 0.350000, },
/* x4290[5] */ { 1.000000, 0.000000, 0.000000, -0.250000, },
};
static ANIMATION x75[] = {
/* x75[0] */ { "base", /* x75[0].body */ { 1,x3969, }, /* x75[0].back_foot */ { 1,x3976, }, /* x75[0].front_foot */ { 1,x3983, }, /* x75[0].attach */ { 0,x3990, }, },
/* x75[1] */ { "idle", /* x75[1].body */ { 0,x4014, }, /* x75[1].back_foot */ { 1,x4021, }, /* x75[1].front_foot */ { 1,x4028, }, /* x75[1].attach */ { 0,x4035, }, },
/* x75[2] */ { "inair", /* x75[2].body */ { 0,x4054, }, /* x75[2].back_foot */ { 1,x4061, }, /* x75[2].front_foot */ { 1,x4068, }, /* x75[2].attach */ { 0,x4075, }, },
/* x75[3] */ { "walk", /* x75[3].body */ { 6,x4094, }, /* x75[3].back_foot */ { 6,x4101, }, /* x75[3].front_foot */ { 6,x4108, }, /* x75[3].attach */ { 0,x4115, }, },
/* x75[4] */ { "hammer_swing", /* x75[4].body */ { 0,x4214, }, /* x75[4].back_foot */ { 0,x4221, }, /* x75[4].front_foot */ { 0,x4228, }, /* x75[4].attach */ { 5,x4235, }, },
/* x75[5] */ { "ninja_swing", /* x75[5].body */ { 0,x4269, }, /* x75[5].back_foot */ { 0,x4276, }, /* x75[5].front_foot */ { 0,x4283, }, /* x75[5].attach */ { 6,x4290, }, },
};
static SPRITE* *x4447 = 0;
static SPRITE* x4584[] = {
&x44[28],
&x44[29],
&x44[30],
};
static SPRITE* x4769[] = {
&x44[34],
&x44[35],
&x44[36],
};
static SPRITE* *x4954 = 0;
static SPRITE* *x5091 = 0;
static SPRITE* x5228[] = {
&x44[51],
&x44[52],
&x44[53],
};
static WEAPONSPEC x1884[] = {
/* x1884[0] */ { "hammer", &x44[40], &x44[41], &x44[42], 0,x4447, 96, 125, 10, 0, 3, 4.000000, -20.000000, 0.000000, 0.000000, 5.000000, },
/* x1884[1] */ { "gun", &x44[25], &x44[26], &x44[27], 3,x4584, 64, 125, 10, 500, 1, 32.000000, -4.000000, 50.000000, 6.000000, 5.000000, },
/* x1884[2] */ { "shotgun", &x44[31], &x44[32], &x44[33], 3,x4769, 96, 500, 10, 0, 1, 24.000000, -2.000000, 70.000000, 6.000000, 5.000000, },
/* x1884[3] */ { "grenade", &x44[37], &x44[38], &x44[39], 0,x4954, 96, 500, 10, 0, 1, 24.000000, -2.000000, 0.000000, 0.000000, 5.000000, },
/* x1884[4] */ { "rifle", &x44[46], &x44[47], &x44[48], 0,x5091, 92, 800, 10, 0, 5, 24.000000, -2.000000, 0.000000, 0.000000, 5.000000, },
/* x1884[5] */ { "ninja", &x44[43], &x44[44], &x44[45], 3,x5228, 96, 800, 10, 0, 9, 0.000000, 0.000000, 40.000000, -4.000000, 5.000000, },
};
DATACONTAINER datacontainer =
/* datacontainer */ {
39,x9,
10,x14,
4,x19,
5,x28,
91,x44,
6,x75,
/* datacontainer.weapons */ { /* datacontainer.weapons.hammer */ { &x1884[0], }, /* datacontainer.weapons.gun */ { &x1884[1], }, /* datacontainer.weapons.shotgun */ { &x1884[2], 1.250000, 2200.000000, 0.800000, 0.250000, }, /* datacontainer.weapons.grenade */ { &x1884[3], 7.000000, 1000.000000, 2.000000, }, /* datacontainer.weapons.rifle */ { &x1884[4], 800.000000, 150, 1, 0.000000, }, /* datacontainer.weapons.ninja */ { &x1884[5], 15000, 200, 50, }, 6,x1884, },
}
;
DATACONTAINER *data = &datacontainer;
| [
"berzzzebub@gmail.com"
] | berzzzebub@gmail.com |
a31196f1785bd4d3cf59428c08f1f3b72e374c9a | a9f981ad539111fa7aecad2810c2a190548d7acd | /tera/utils/utils_cmd.cc | bacc5bbf508f967c9c858ebad4cfeb3b5f98c8e4 | [] | no_license | hazhashua/tera | d9a695e361a28fc1d6934090533712d71f46c203 | 9ed887002dfb661d4efd116ecaff8c05757d8827 | refs/heads/master | 2021-01-18T02:39:11.256465 | 2015-03-15T22:49:31 | 2015-03-15T22:49:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,336 | cc | // Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "tera/utils/utils_cmd.h"
#include <stdio.h>
#include <stdlib.h>
#include "common/base/scoped_ptr.h"
#include "common/base/string_ext.h"
#include "common/base/string_format.h"
#include "common/base/string_number.h"
#include "common/file/file_path.h"
#include "gflags/gflags.h"
#include "glog/logging.h"
#include "tera/types.h"
DECLARE_string(log_dir);
namespace tera {
namespace utils {
std::string GetBinaryLocationDir() {
char exec_full_path[1024] = {'\0'};
readlink ("/proc/self/exe", exec_full_path, 1024);
VLOG(5) << "current binary location: " << exec_full_path;
std::string full_dir;
SplitStringPath(exec_full_path, &full_dir, NULL);
return full_dir;
}
std::string GetCurrentLocationDir() {
char current_path[1024] = {'\0'};
std::string current_dir;
if (getcwd(current_path, 1024)) {
current_dir = current_path;
}
return current_dir;
}
std::string GetValueFromeEnv(const std::string& env_name) {
if (env_name.empty()) {
return "";
}
const char* env = getenv(env_name.c_str());
if (!env) {
VLOG(5) << "fail to fetch from env: " << env_name;
return "";
}
return env;
}
std::string ConvertByteToString(const uint64_t size) {
std::string hight_unit;
double min_size;
const uint64_t kKB = 1024;
const uint64_t kMB = kKB * 1024;
const uint64_t kGB = kMB * 1024;
const uint64_t kTB = kGB * 1024;
const uint64_t kPB = kTB * 1024;
if (size == 0) {
return "0 ";
}
if (size > kPB) {
min_size = (1.0 * size) / kPB;
hight_unit = "P";
} else if (size > kTB) {
min_size = (1.0 * size) / kTB;
hight_unit = "T";
} else if (size > kGB) {
min_size = (1.0 * size) / kGB;
hight_unit = "G";
} else if (size > kMB) {
min_size = (1.0 * size) / kMB;
hight_unit = "M";
} else if (size > kKB) {
min_size = (1.0 * size) / kKB;
hight_unit = "K";
} else {
min_size = size;
hight_unit = " ";
}
if ((int)min_size - min_size == 0) {
return StringFormat("%d%s", (int)min_size, hight_unit.c_str());
} else {
return StringFormat("%.2f%s", min_size, hight_unit.c_str());
}
}
bool ExecuteShellCmd(const std::string cmd, std::string* ret_str) {
char output_buffer[80];
FILE *fp = popen(cmd.c_str(), "r");
if (!fp) {
LOG(ERROR) << "fail to execute cmd: " << cmd;
return false;
}
fgets(output_buffer, sizeof(output_buffer), fp);
pclose(fp);
if (ret_str) {
*ret_str = std::string(output_buffer);
}
return true;
}
std::string GetLocalHostAddr() {
std::string cmd =
"/sbin/ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}'";
std::string addr;
if (!ExecuteShellCmd(cmd, &addr)) {
LOG(ERROR) << "fail to fetch local host addr";
} else if (addr.length() > 1) {
addr.erase(addr.length() - 1, 1);
}
return addr;
}
std::string GetLocalHostName() {
char str[kMaxHostNameSize + 1];
if (0 != gethostname(str, kMaxHostNameSize + 1)) {
LOG(FATAL) << "gethostname fail";
exit(1);
}
std::string hostname(str);
return hostname;
}
void SetupLog(const std::string& name) {
// log info/warning/error/fatal to tera.log
// log warning/error/fatal to tera.wf
std::string program_name = "tera";
if (!name.empty()) {
program_name = name;
}
std::string log_filename = FLAGS_log_dir + "/" + program_name + ".INFO.";
std::string wf_filename = FLAGS_log_dir + "/" + program_name + ".WARNING.";
google::SetLogDestination(google::INFO, log_filename.c_str());
google::SetLogDestination(google::WARNING, wf_filename.c_str());
google::SetLogDestination(google::ERROR, "");
google::SetLogDestination(google::FATAL, "");
google::SetLogSymlink(google::INFO, program_name.c_str());
google::SetLogSymlink(google::WARNING, program_name.c_str());
google::SetLogSymlink(google::ERROR, "");
google::SetLogSymlink(google::FATAL, "");
}
} // namespace utils
} // namespace tera
| [
"shiguang31@163.com"
] | shiguang31@163.com |
6626491a308054e149854541ddfbf0e8c26f89f2 | 4f7b5c1d9b2fda9dc4c756ff921fc4fd620cfd81 | /src/NGLScene.cpp | 79d70889f5c2d747db18169a5cb71677968630fb | [] | no_license | quentinjcm/NGLScene | 7635d90ee18f9f331118010fae631c518bc47963 | 7f5dc7915362b2af6a566ab6ee389430b63d19e6 | refs/heads/master | 2021-01-10T04:50:52.800880 | 2016-03-08T14:45:56 | 2016-03-08T14:45:56 | 53,339,813 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,230 | cpp | #include <QMouseEvent>
#include <QGuiApplication>
#include "NGLScene.h"
#include <ngl/NGLInit.h>
#include <iostream>
#include <ngl/ShaderLib.h>
#include <ngl/VAOPrimitives.h>
#include <ngl/Util.h>
#include <ngl/NGLStream.h>
NGLScene::NGLScene()
{
// re-size the widget to that of the parent (in this case the GLFrame passed in on construction)
setTitle("Blank NGL");
m_view = ngl::lookAt(ngl::Vec3(2, 2, 2),
ngl::Vec3(0, 0, 0),
ngl::Vec3(0, 1, 0));
}
NGLScene::~NGLScene()
{
std::cout<<"Shutting down NGL, removing VAO's and Shaders\n";
}
void NGLScene::resizeGL(QResizeEvent *_event)
{
m_width=_event->size().width()*devicePixelRatio();
m_height=_event->size().height()*devicePixelRatio();
m_project = ngl::perspective(45.0f,
float(m_width/m_height),
0.2f,
20.0f);
}
void NGLScene::resizeGL(int _w , int _h)
{
m_width=_w*devicePixelRatio();
m_height=_h*devicePixelRatio();
m_project = ngl::perspective(45.0f,
float(m_width/m_height),
0.2f,
20.0f);
}
void NGLScene::initializeGL()
{
// we need to initialise the NGL lib which will load all of the OpenGL functions, this must
// be done once we have a valid GL context but before we call any GL commands. If we dont do
// this everything will crash
ngl::NGLInit::instance();
glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // Grey Background
// enable depth testing for drawing
glEnable(GL_DEPTH_TEST);
// enable multisampling for smoother drawing
glEnable(GL_MULTISAMPLE);
//name creates a sphere that we can access through a map using "sphere"
ngl::VAOPrimitives::instance()->createCone("cone", 0.5, 1, 30, 30);
//initialize shader lib singleton
ngl::ShaderLib *shader = ngl::ShaderLib::instance();
shader->createShaderProgram("diffuse");
//create shaders
shader->attachShader("diffuseVertex", ngl::ShaderType::VERTEX);
shader->attachShader("diffuseFragment", ngl::ShaderType::FRAGMENT);
shader->loadShaderSource("diffuseVertex" ,"shaders/DiffuseVertex.glsl");
shader->loadShaderSource("diffuseFragment" ,"shaders/DiffuseFragment.glsl");
shader->compileShader("diffuseVertex");
shader->compileShader("diffuseFrafment");
shader->attachShaderToProgram("diffuse", "diffuseVertex");
shader->attachShaderToProgram("diffuse", "diffuseFragment");
shader->linkProgramObject("diffuse");
shader->use("diffuse");
shader->setRegisteredUniform("colour", 0.0f, 1.0f, 1.0f, 1.0f);
shader->setRegisteredUniform("lightPos", 3.0f, 0.0f, 0.0f);
shader->setRegisteredUniform("lightDiffuse", 1.0f, 1.0f, 1.0f, 1.0f);
}
void NGLScene::paintGL()
{
ngl::ShaderLib *shader = ngl::ShaderLib::instance();
// clear the screen and depth buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glViewport(0,0,m_width,m_height);
ngl::VAOPrimitives *prim = ngl::VAOPrimitives::instance();
shader->setRegisteredUniform("colour", 0.0f, 0.0f, 1.0f, 1.0f);
m_transform.reset();
m_transform.setScale(1.0, 1.0, 1.0);
m_transform.setRotation(-90, 0, 0);
loadMatToShader();
//draw sphere that was initialised in initializeGL()
prim->draw("cone");
shader->setRegisteredUniform("colour", 1.0f, 0.0f, 0.0f, 1.0f);
m_transform.reset();
m_transform.setScale(1.0, 1.0, 1.0);
m_transform.setRotation(90, 0, 0);
loadMatToShader();
//draw sphere that was initialised in initializeGL()
prim->draw("cone");
std::cout << m_view << "\n" << m_project << std::endl;
}
//----------------------------------------------------------------------------------------------------------------------
void NGLScene::mouseMoveEvent (QMouseEvent * _event)
{
}
//----------------------------------------------------------------------------------------------------------------------
void NGLScene::mousePressEvent ( QMouseEvent * _event)
{
}
//----------------------------------------------------------------------------------------------------------------------
void NGLScene::mouseReleaseEvent ( QMouseEvent * _event )
{
}
//----------------------------------------------------------------------------------------------------------------------
void NGLScene::wheelEvent(QWheelEvent *_event)
{
}
//----------------------------------------------------------------------------------------------------------------------
void NGLScene::keyPressEvent(QKeyEvent *_event)
{
// this method is called every time the main window recives a key event.
// we then switch on the key value and set the camera in the GLWindow
switch (_event->key())
{
// escape key to quite
case Qt::Key_Escape : QGuiApplication::exit(EXIT_SUCCESS); break;
case Qt::Key_W : glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); break;
case Qt::Key_S : glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); break;
default : break;
}
// finally update the GLWindow and re-draw
update();
}
void NGLScene::loadMatToShader()
{
ngl::ShaderLib *shader = ngl::ShaderLib::instance();
ngl::Mat4 MVP = m_transform.getMatrix() * m_view * m_project;
shader->setRegisteredUniform("MVP", MVP);
}
| [
"i7624405@bournemouth.ac.uk"
] | i7624405@bournemouth.ac.uk |
3c833c7d82a89d2cda5f34fefb13b967d8714ab9 | 18f5c381b18c54f56909015db389af9a3aa5d45c | /apps/src/extension_fix/param_process.hpp | 6fb6a2b67abf1c5b06908c66f65db7d296bc0ee1 | [
"MIT"
] | permissive | dogesoulseller/weirdlib | 71cd15b7f1a2b342dced8fadb1af2fb671ca5f6d | 35d3be8a7621890e6870a48f3839f00b87d5ced9 | refs/heads/master | 2022-04-12T09:45:30.664608 | 2020-03-20T05:54:46 | 2020-03-20T05:54:46 | 178,538,978 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 421 | hpp | #pragma once
#include <weirdlib_fileops.hpp>
#include <string>
#include <filesystem>
#include <vector>
#include <iostream>
#include <functional>
#include <unordered_map>
#include <algorithm>
enum ParameterName
{
RECURSION_DEPTH,
OUTPUT_DIR,
PREPEND_STRING,
APPEND_STRING
};
bool StringIsInteger(const std::string& str);
std::unordered_map<ParameterName, std::string> GetParameters(std::vector<std::string>& args);
| [
"mcmarcinoser5@gmail.com"
] | mcmarcinoser5@gmail.com |
75030ba8c9928436823713569b4c6c98c5fba018 | b012b15ec5edf8a52ecf3d2f390adc99633dfb82 | /releases/moos-ivp-14.7.1/ivp/src/lib_ivpbuild/RT_Smart.h | de3a7cb9b188fc64a7556587a54a8fbd991511ca | [] | no_license | crosslore/moos-ivp-aro | cbe697ba3a842961d08b0664f39511720102342b | cf2f1abe0e27ccedd0bbc66e718be950add71d9b | refs/heads/master | 2022-12-06T08:14:18.641803 | 2020-08-18T06:39:14 | 2020-08-18T06:39:14 | 263,586,714 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,121 | h | /*****************************************************************/
/* NAME: Michael Benjamin, Henrik Schmidt, and John Leonard */
/* ORGN: Dept of Mechanical Eng / CSAIL, MIT Cambridge MA */
/* FILE: RT_Smart.h */
/* DATE: Jan 20th, 2006 */
/* NOTE: "RT_" stands for "Reflector Tool" */
/* */
/* This file is part of IvP Helm Core Libs */
/* */
/* IvP Helm Core Libs is free software: you can redistribute it */
/* and/or modify it under the terms of the Lesser GNU General */
/* Public License as published by the Free Software Foundation, */
/* either version 3 of the License, or (at your option) any */
/* later version. */
/* */
/* IvP Helm Core Libs 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 Lesser GNU General Public License for more */
/* details. */
/* */
/* You should have received a copy of the Lesser GNU General */
/* Public License along with MOOS-IvP. If not, see */
/* <http://www.gnu.org/licenses/>. */
/*****************************************************************/
#ifdef _WIN32
#pragma warning(disable : 4786)
#pragma warning(disable : 4503)
#endif
#ifndef RT_SMART_REFINE_HEADER
#define RT_SMART_REFINE_HEADER
#include "PDMap.h"
#include "PQueue.h"
class Regressor;
class RT_Smart {
public:
RT_Smart(Regressor*);
virtual ~RT_Smart() {};
public:
PDMap* create(PDMap*, PQueue&, int more_pcs, double thresh=0);
protected:
Regressor* m_regressor;
};
#endif
| [
"zouxueson@hotmail.com"
] | zouxueson@hotmail.com |
3e7e272c8d7751875aa4996fcf61c3cec25b9ab6 | 191126328427ffb1d2cebcc5d3ccb670a7f4f8be | /easy.cpp | 280c61e2e139ddea37f248f1933998ae7fc99d35 | [] | no_license | drviruses/CP | 090ca7db998f7f113d85ab96a91a73fd9d5892ac | 69294c62218fda3453daf4b69251ab98bb24cccb | refs/heads/master | 2023-03-14T06:09:15.174975 | 2021-03-01T05:04:26 | 2021-03-01T05:04:26 | 305,608,273 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,103 | cpp | /*
@uthor: Amit Kumar
user: CodeChef: dr_virus_ ; Codeforces,Hackerearth,Hakerrank: dr_virus;
*/
#include <bits/stdc++.h>
using namespace std;
//#include <boost/multiprecision/cpp_int.hpp>
//namespace mp = boost::multiprecision;
//#define ln mp::cpp_int;
#define ll long long
#define ld double
#define pp pair<ll,ll>
#define endl "\n"
#define nfrep(a) for(size_t i=0;i<a;i++)
#define fnrep(a,b) for(size_t i=a;i<=b;i++)
#define nbrep(a) for(size_t i=a;i>=0;i--)
#define bnrep(a,b) for(size_t i=a;i>=b;i--)
const ll mod = 1e9+7;
const ll inf = 1e18;
int32_t main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
/* #ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif */
ll t=1;
//cin>>t;
while(t--){
ll n,f=0,val;
cin>>n;
for(auto i=0;i<n;i++){
cin>>val;
if(val==1) {f=1;break;}
}
if(f) cout<<"HARD";
else cout<<"EASY";
//your code goes here
}
return 0;
} | [
"amitkumarhero28@gmail.com"
] | amitkumarhero28@gmail.com |
0cdcad23587dbfa72482aa96676a8230c54c4286 | 32acab328c74a004c1612953f70aa9eb0b195d3c | /MouseMove/AssemblyInfo.cpp | c3eb3de92d170743b1e1ceb80c7d1e763d66f088 | [] | no_license | asuser1/MouseMove-Library | c6503cb56b72e576e4ca6eca4313342b656bbbf1 | 3be30223e47c2c42c79c5453cc9771b5439a3e0a | refs/heads/master | 2020-03-18T04:44:45.302340 | 2018-05-21T17:49:12 | 2018-05-21T17:49:12 | 134,302,728 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,215 | cpp | #include "stdafx.h"
using namespace System;
using namespace System::Reflection;
using namespace System::Runtime::CompilerServices;
using namespace System::Runtime::InteropServices;
using namespace System::Security::Permissions;
//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly:AssemblyTitleAttribute(L"MouseMove")];
[assembly:AssemblyDescriptionAttribute(L"")];
[assembly:AssemblyConfigurationAttribute(L"")];
[assembly:AssemblyCompanyAttribute(L"")];
[assembly:AssemblyProductAttribute(L"MouseMove")];
[assembly:AssemblyCopyrightAttribute(L"Copyright (c) 2017")];
[assembly:AssemblyTrademarkAttribute(L"")];
[assembly:AssemblyCultureAttribute(L"")];
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the value or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly:AssemblyVersionAttribute("1.0.*")];
[assembly:ComVisible(false)];
[assembly:CLSCompliantAttribute(true)]; | [
"austinswearman@msn.com"
] | austinswearman@msn.com |
7b82f17c0c93122043288f32806097ab2a11d82c | 844969bd953d7300f02172c867725e27b518c08e | /SDK/ALK_ThirdPerson_Male_Default_classes.h | 1a9f080c80c44231fb2dd0be85ae8dc37a052830 | [] | no_license | zanzo420/SoT-Python-Offset-Finder | 70037c37991a2df53fa671e3c8ce12c45fbf75a5 | d881877da08b5c5beaaca140f0ab768223b75d4d | refs/heads/main | 2023-07-18T17:25:01.596284 | 2021-09-09T12:31:51 | 2021-09-09T12:31:51 | 380,604,174 | 0 | 0 | null | 2021-06-26T22:07:04 | 2021-06-26T22:07:03 | null | UTF-8 | C++ | false | false | 834 | h | #pragma once
// Name: SoT, Version: 2.2.1.1
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass ALK_ThirdPerson_Male_Default.ALK_ThirdPerson_Male_Default_C
// 0x0000 (FullSize[0x0028] - InheritedSize[0x0028])
class UALK_ThirdPerson_Male_Default_C : public UAnimationDataStoreId
{
public:
static UClass* StaticClass()
{
static UClass* ptr = UObject::FindClass("BlueprintGeneratedClass ALK_ThirdPerson_Male_Default.ALK_ThirdPerson_Male_Default_C");
return ptr;
}
void AfterRead();
void BeforeDelete();
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"51171051+DougTheDruid@users.noreply.github.com"
] | 51171051+DougTheDruid@users.noreply.github.com |
4d79523a24bb7f1d55109d94e1f16b73e1791335 | d10085bbcfe017b1f038fa280e391adbb3584589 | /src/lib/wattcp32/src/gormcb_c.inc | f63ba811c74953a1b73fea32e0d11e17858ff00c | [] | no_license | markjolesen/openbsd | 20a8cb9d8ad580773768bd1ebc7985bf057258b4 | d723bf1fed6740c5e431eee434ad8366c3de6736 | refs/heads/master | 2021-09-27T00:22:37.317087 | 2021-09-21T07:37:15 | 2021-09-21T07:37:15 | 185,104,408 | 8 | 1 | null | 2019-05-06T01:39:26 | 2019-05-06T01:39:25 | null | UTF-8 | C++ | false | false | 6,903 | inc | /* Copyright (C) 1999 DJ Delorie, see COPYING.DJ for details */
/* Copyright (C) 1998 DJ Delorie, see COPYING.DJ for details */
/* Copyright (C) 1996 DJ Delorie, see COPYING.DJ for details */
/* Copyright (C) 1995 DJ Delorie, see COPYING.DJ for details */
/* This code really can't be nested since the RMCB structure isn't copied,
so the stack check isn't really useful. But someone may fix it someday.
On entry CS is known to be ours, ES is probably ours (since we passed it),
SS:ESP is locked 4K stack. ES:EDI is regs structure, DS:ESI is RM SS:SP.
Do NOT enable interrupts in the user routine. Thanks to ctm@ardi.com for
the improvements. C. Sandmann 3/95 */
#ifndef RMCB_STK_SIZE
#error This file must be included from pcpkt.c only
#endif
#if !defined(USE_FAST_PKT)
#define STACK_WAS_MALLOCED (1 << 0)
#define FILL 0x00
/* !! Doesn't save FS/GS registers */
static unsigned char wrapper[] = {
/* 00 */ 0x06, /* push es */
/* 01 */ 0x1e, /* push ds */
/* 02 */ 0x06, /* push es */
/* 03 */ 0x1f, /* pop ds */
/* 04 */ 0x66, 0xb8, /* mov ax, */
/* 06 */ FILL, FILL, /* _our_selector */
/* 08 */ 0x8e, 0xd8, /* mov ds, ax */
/* 0a */ 0xff, 0x05, /* incl */
/* 0c */ FILL, FILL, FILL, FILL, /* _call_count */
/* 10 */ 0x83, 0x3d, /* cmpl */
/* 12 */ FILL, FILL, FILL, FILL, /* _in_this_handler */
/* 16 */ 0x00, /* $0 */
/* 17 */ 0x75, /* jne */
/* 18 */ 0x33, /* bypass */
/* 19 */ 0xc6, 0x05, /* movb */
/* 1b */ FILL, FILL, FILL, FILL, /* _in_this_handler */
/* 1f */ 0x01, /* $1 */
/* 20 */ 0x8e, 0xc0, /* mov es, ax */
/* 22 */ 0x8e, 0xe0, /* mov fs, ax */
/* 24 */ 0x8e, 0xe8, /* mov gs, ax */
/* 26 */ 0xbb, /* mov ebx, */
/* 27 */ FILL, FILL, FILL, FILL, /* _local_stack */
/* 2b */ 0xfc, /* cld */
/* 2c */ 0x89, 0xe1, /* mov ecx, esp */
/* 2e */ 0x8c, 0xd2, /* mov dx, ss */
/* 30 */ 0x8e, 0xd0, /* mov ss, ax */
/* 32 */ 0x89, 0xdc, /* mov esp, ebx */
/* 34 */ 0x52, /* push edx */
/* 35 */ 0x51, /* push ecx */
/* 36 */ 0x56, /* push esi */
/* 37 */ 0x57, /* push edi */
/* 38 */ 0xe8, /* call */
/* 39 */ FILL, FILL, FILL, FILL, /* _rmcb */
/* 3d */ 0x5f, /* pop edi */
/* 3e */ 0x5e, /* pop esi */
/* 3f */ 0x58, /* pop eax */
/* 40 */ 0x5b, /* pop ebx */
/* 41 */ 0x8e, 0xd3, /* mov ss, bx */
/* 43 */ 0x89, 0xc4, /* mov esp, eax */
/* 45 */ 0xc6, 0x05, /* movb */
/* 47 */ FILL, FILL, FILL, FILL, /* _in_this_handler */
/* 4b */ 0x00, /* $0 */
/* 4c */ 0x1f, /* bypass: pop ds */
/* 4d */ 0x07, /* pop es */
/* 4e */ 0x8b, 0x06, /* mov eax,[esi] */
/* 50 */ 0x26, 0x89, 0x47, 0x2a, /* mov es:[edi+42],eax ; 42 = EIP */
0x66, 0x26, 0x83, 0x47, 0x2e, 0x04, /* add es:[edi+46],0x4 ; 46 = ESP */
0xcf /* iret */
};
static DWORD stack_length;
static BYTE *stack;
static int setup_rmcb (unsigned char *stub,
_go32_dpmi_seginfo *info,
__dpmi_regs *regs)
{
stack_length = RMCB_STK_SIZE;
int i;
if (stack_length < 512 ||
(stack = calloc (stack_length, 1)) == NULL)
return (0x8015);
if (_go32_dpmi_lock_data(stack, stack_length))
{
free (stack);
return (0x8015);
}
((long*)stack)[0] = STACK_WAS_MALLOCED;
((long*)stack)[1] = 0;
((long*)stack)[2] = 0;
if (_go32_dpmi_lock_data(regs, sizeof(__dpmi_regs)))
{
free (stack);
return (0x8015);
}
*(short*)(stub+0x06) = __djgpp_ds_alias;
*(long *)(stub+0x0c) = (long) stack + 8;
*(long *)(stub+0x12) = (long) stack + 4;
*(long *)(stub+0x1b) = (long) stack + 4;
*(long *)(stub+0x27) = (long) stack + stack_length - 8; /* !! added '-4' */
*(long *)(stub+0x39) = info->pm_offset - ((long)stub + 0x3d);
*(long *)(stub+0x47) = (long) stack + 4;
for (i = 0x10; i <= 0x18 ; i++)
*(BYTE*) (stub+i) = 0x90;
info->size = (int)stub;
if (__dpmi_allocate_real_mode_callback ((void*)stub, regs,
(__dpmi_raddr *)&info->rm_offset))
{
free (stack);
return (0x8015);
}
return (0);
}
static DWORD get_rmcb_callcount (void)
{
if (!stack)
return (0);
return *(DWORD*) (stack + 8);
}
static int _pkt_dpmi_allocate_real_mode_callback_retf (
_go32_dpmi_seginfo *info, __dpmi_regs *regs)
{
unsigned char *stub = calloc (sizeof(wrapper)+4, 1);
if (stub == 0)
return (0x8015);
if (_go32_dpmi_lock_data(stub,sizeof(wrapper)+4))
{
free (stub);
return (0x8015);
}
memcpy (stub, wrapper, sizeof(wrapper));
if (setup_rmcb (stub, info, regs))
{
free (stub);
return (0x8015);
}
return (0);
}
static int _pkt_dpmi_free_real_mode_callback (_go32_dpmi_seginfo *info)
{
BYTE *stk = (BYTE*) (*(long*)((long)info->size+0x47) - 4);
if (stk != stack)
fprintf (stderr, "%s: stack error; stk %08lX, stack %08lX\n",
__FUNCTION__, (DWORD)stk, (DWORD)stack);
else
{
if (*(long*)stack & STACK_WAS_MALLOCED)
free (stk);
free ((char*)info->size); /* free 'stub' */
}
stack = NULL;
return __dpmi_free_real_mode_callback ((__dpmi_raddr *)&info->rm_offset);
}
#endif /* !USE_FAST_PKT */
| [
"markjolesen@gmail.com"
] | markjolesen@gmail.com |
94ed413c9c71bff44f33bd236818dbf2048c9b8d | 94bd7f8df2d840632d6bbf7807b0d511ef66bca4 | /src/state/OperationBindingSingletone.cpp | f74b2c5dfcb2ae34b91ca912aca7ca434e87672b | [] | no_license | Ho-Holic/stamp | 594adce7062f29c5a1a648f5f1ae0911d894cd28 | b88c04709df6cbfee4c410b4b1ca10da203eb6ce | refs/heads/main | 2023-02-25T14:42:03.626301 | 2021-02-03T21:51:24 | 2021-02-03T21:51:24 | 335,104,121 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,238 | cpp | #include "OperationBindingSingletone.h"
#include "operations/CreateProjectOperation.h"
#include "operations/EnvOperation.h"
#include "operations/ExtractOperation.h"
#include "operations/InitProjectOperation.h"
#include "operations/MakedirOperation.h"
#include "operations/SkipOperation.h"
#include "operations/SystemOperation.h"
#include <QTextStream>
namespace {
const QString DEFAULT_OPERATION = "skip";
}
stamp::OperationBindingSingletone& stamp::operationBinding()
{
static OperationBindingSingletone instance;
return instance;
}
stamp::Operation* stamp::OperationBindingSingletone::operation(const QString& operationName)
{
auto it = m_operations.find(operationName);
Q_ASSERT_X(m_operations.find(DEFAULT_OPERATION) != m_operations.end(), __FUNCTION__,
"Default operation must be in container");
return (it != m_operations.end()) ? it->second.get() : m_operations[DEFAULT_OPERATION].get();
}
stamp::OperationBindingSingletone::OperationBindingSingletone()
{
m_operations = {
{ "create", std::make_shared<stamp::CreateProjectOperation>() },
{ "skip", std::make_shared<stamp::SkipOperation>() },
{ "extract", std::make_shared<stamp::ExtractOperation>() },
{ "makedir", std::make_shared<stamp::MakedirOperation>() },
{ "system", std::make_shared<stamp::SystemOperation>() },
{ "init", std::make_shared<stamp::InitProjectOperation>() },
{ "env", std::make_shared<stamp::EnvOperation>() },
};
}
void stamp::OperationBindingSingletone::executeScript(const QStringList& script)
{
// TODO: replace recursion with queue
QTextStream out(stdout);
for (QStringList::ConstIterator it = script.begin(); it != script.end(); ++it) {
const QString& actionLine = (*it);
out << actionLine << Qt::endl;
QStringList splittedArguments = stamp::Operation::escapeSplit(actionLine);
if (!splittedArguments.isEmpty()) {
QString actionName = splittedArguments.at(ActionIndex);
splittedArguments.pop_front(); // pop operation name
stamp::Operation* currentOperation = this->operation(actionName);
currentOperation->tryExecute(splittedArguments);
}
}
}
| [
"isysoev@zeptolab.com"
] | isysoev@zeptolab.com |
2a8926b0d8594daadba9f002dd15e0bae836d28c | ad2ea0f5a7b82f0eb50136a69f844382879f9f49 | /lib/solver_interface/pyoptsolver/src/wrapper.cpp | fd8eb914dbcea9486d5b17177145ac70efb0accb | [
"MIT"
] | permissive | paperstiger/trajOptLib | 7ccad1eebc1969c3edf1e8b3640d6cf72c9cd5e6 | 5e86a33537d89c0d1e35df7a436f9266fe817c49 | refs/heads/master | 2021-07-09T23:42:39.277003 | 2020-11-18T04:30:09 | 2020-11-18T04:30:09 | 216,307,330 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,478 | cpp | /*
* solverwrapper.cpp
* Copyright (C) 2017 Gao <gao.tang@duke.edu>
*
* Distributed under terms of the license.
*/
/* Write a python wrapper for the problem */
#include "pybind11/eigen.h"
#include "pybind11/functional.h"
#ifdef SNOPT
#include "snoptWrapper.h"
#include "funcStyle.h"
#include "classStyle.h"
#endif
#ifdef IPOPT
#include "ipoptWrapper.h"
#endif
#define VERSION_INFO "0.6.0"
double PYOPTSOLVER_FD_STEP = 1e-6;
class pyProbFun: public ProblemFun{
public:
using ProblemFun::ProblemFun;
int operator()(cRefV x, RefV F) override{
PYBIND11_OVERLOAD_NAME(
int,
ProblemFun,
"__callf__",
operator(),
x, F
);
}
pint operator()(cRefV x, RefV F, RefV G, RefVl row, RefVl col, bool rec, bool needg) override {
PYBIND11_OVERLOAD_NAME(
pint,
ProblemFun,
"__callg__",
operator(),
x, F, G, row, col, rec, needg
);
}
#ifdef ENABLEIP
double evalF(cRefV x) override{
PYBIND11_OVERLOAD_NAME(
double,
ProblemFun,
"__cost__",
evalF,
x
);
}
bool evalGrad(cRefV x, RefV grad) override{
PYBIND11_OVERLOAD_NAME(
bool,
ProblemFun,
"__gradient__",
evalGrad,
x, grad
);
}
int evalG(cRefV x, RefV g) override{
PYBIND11_OVERLOAD_NAME(
int,
ProblemFun,
"__constraint__",
evalG,
x, g
);
}
int evalJac(cRefV x, RefV g, RefVl row, RefVl col, bool rec) override{
PYBIND11_OVERLOAD_NAME(
int,
ProblemFun,
"__jacobian__",
evalJac,
x, g, row, col, rec
);
}
int evalHess(cRefV x, double sigma, cRefV lmd, RefV g, RefVl row, RefVl col, bool rec) override{
PYBIND11_OVERLOAD_NAME(
int,
ProblemFun,
"__hessian__",
evalHess,
x, sigma, lmd, g, row, col, rec
);
}
#endif
};
namespace py = pybind11;
PYBIND11_MODULE(pyoptsolvercpp, m){
m.doc() = R"pbdoc(
A Python interface for large scale optimization solver SNOPT and Ipopt
)pbdoc";
// this class was called result previously, consider changing __init__.py
py::class_<optResult>(m, "OptResult", R"pbdoc(
A class that contains the solution returned by either one.
This class has the default constructor.
Attributes:
flag (int): the return flag by SNOPT.solve()
obj (float): the cost function
sol (ndarray): a copy of the solution
fval (ndarray): a copy of F
lmd (ndarray): a copy of Lagrangian multipliers
xmul (ndarray): a copy of multipliers associated with bounds on x
)pbdoc")
.def(py::init<>(), R"pbdoc(
Constructor for SnoptResult.
It takes no arguments.
)pbdoc")
.def("get_sol", &optResult::get_sol, R"pbdoc(
Return a reference to the solution without copying.
)pbdoc")
.def("get_history", &optResult::get_history, R"pbdoc(
Return a reference to the history of solution without copying.
)pbdoc")
.def("get_fval", &optResult::get_fval, R"pbdoc(
Return a reference to the function evaluation without copying.
)pbdoc")
.def("get_lambda", &optResult::get_lambda, R"pbdoc(
Return a reference to the Lagrangian multiplier without copying.
)pbdoc")
.def("get_xmul", &optResult::get_xmul, R"pbdoc(
Return a reference to the Lagrangian multiplier on bounds without copying.
)pbdoc")
.def_readwrite("flag", &optResult::flag)
.def_readwrite("obj", &optResult::val)
.def_readwrite("sol", &optResult::sol)
.def_readwrite("history", &optResult::history)
.def_readwrite("fval", &optResult::c)
.def_readwrite("xmul", &optResult::xmul)
.def_readwrite("lmd", &optResult::lmd);
py::class_<ProblemFun, pyProbFun>(m, "OptProblem", R"pbdoc(
A class sub-classed by users to define a custom optimization problem.
:currentmodule:
.. automethod:: __callf__.
.. automethod:: __callg__.
.. automethod:: __cost__.
.. automethod:: __gradient__.
.. automethod:: __constraint__
.. automethod:: __jacobian__.
.. automethod:: __hessian__.
This class defines an optimization problem to optimize :math:`y(0)` where :math:`y=f(x)+Ax`
subject to constraints :math:`lb \le y \le ub` and :math:`xlb \le x \le xub`.
Attributes:
nx (int): number of variables to be optimized. The same with :class:`.FunBase`.
nf (int): number of constraints. The same with :class:`.FunBase`.
nG (int=0): nnz of the Jacobian matrix. The same with :class:`.FunBase`.
grad (bool=False): if the function __callg__ has been implemented so we enable gradient.
lb (ndarray): lower bound for f. It is readonly, use get_lb() to get a reference.
ub (ndarray): upper bound for f. It is readonly, use get_ub() to get a reference.
xlb (ndarray): lower bound for x. It is readonly, use get_xlb() to get a reference.
xub (ndarray): upper bound for x. It is readonly, use get_xub() to get a reference.
Aval (ndarray): the value ndarray for triplet A, use get_aval() to get a reference.
Arow (ndarray): integer ndarray of rows for triplet A, use get_arow() to get a reference.
Acol (ndarray): integer ndarray of columns for triplet A, use get_acol() to get a reference.
Note:
This class has 2 constructors. Refer to :class:`.FunBase` for details.
The first entry of lb and ub should be -np.inf and np.inf, respectively.
For linear function part, you have to set function return 0.
Use ipopt_style() and snopt_style() to toggle function evaluation mode.
)pbdoc")
.def(py::init<>())
.def(py::init<int>())
.def(py::init<int, int>())
.def(py::init<int, int, int>())
.def("set_size", &ProblemFun::set_size, R"pbdoc(Set size of the problem using nx and nf)pbdoc")
.def("set_sizeg", &ProblemFun::set_sizeg, R"pbdoc(Set size of the problem using nx and nf and ng)pbdoc")
.def("update_nf", &ProblemFun::updateNf, R"pbdoc(
Update nf and reallocate space for lb and ub, if necessary.
Args:
nf (int): the desired nf
)pbdoc")
.def("update_ng", &ProblemFun::updateNg, R"pbdoc(
Update nnz value, equivalently to directly writing to nG.
Args:
ng (int): the desired nG
)pbdoc")
.def("set_a_by_matrix", (void (ProblemFun::*)(crRefM)) &pyProbFun::setA, R"pbdoc(
Set triplet matrix A by a dense row major matrix, i.e. 2d ndarray of size (m, n).
Args:
mat (ndarray): the 2d float A matrix in row major.
)pbdoc")
.def("set_a_by_triplet", (void (ProblemFun::*)(cRefV, cRefVi, cRefVi)) &pyProbFun::setA, R"pbdoc(
Set triplet matrix A by the value, row, column triplet pairs.
Args:
val (ndarray): the value ndarray
row (ndarray): the integer row ndarray
col (ndarray): thet integer column ndarray
)pbdoc")
.def("set_a_by_triplet", (void (ProblemFun::*)(cRefV, cRefVl, cRefVl)) &pyProbFun::setA, R"pbdoc(
Set triplet matrix A by the value, row, column triplet pairs.
Args:
val (ndarray): the value ndarray
row (ndarray): the integer row ndarray
col (ndarray): thet integer column ndarray
)pbdoc")
.def("check_overlap", &pyProbFun::overlap_check, R"pbdoc(
Check if user provided linear and nonlinear Jacobian has overlap.
)pbdoc")
.def("detect_prob_size", (void (ProblemFun::*)(int, int)) &pyProbFun::detect_prob_size,
R"pbdoc(
Automatically detect nf and nG.
This function requires __callf__ or __callg__ return non-trivial values.
Args:
nf (int): an estimated size for :math:`y`, it has to be larger.
nG (int): an estimated size for Jacobian, it has to be larger. If set to 0, __callf__ is used and
has to be defined. Otherwise __callg__ has to be defined.
)pbdoc")
.def("detect_prob_size", (void (ProblemFun::*)(cRefV, int, int)) &pyProbFun::detect_prob_size,
R"pbdoc(
Automatically detect nf and nG.
This function requires __callf__ or __callg__ return non-trivial values.
Args:
x( ndarray): the guess being used. This will change nf too so please make sure its size is correct
nf (int): an estimated size for :math:`y`, it has to be larger.
nG (int): an estimated size for Jacobian, it has to be larger. If set to 0, __callf__ is used and
has to be defined. Otherwise __callg__ has to be defined.
)pbdoc")
.def("enable_timer", &pyProbFun::enable_time_record, R"pbdoc(
Turn on internal timer. By doing so, user is able to call get_timer function.
)pbdoc")
.def("set_debug_verbose", &pyProbFun::set_debug_verbose, R"pbdoc(
Turn on or off verbosity.
)pbdoc")
.def("get_timer", &pyProbFun::get_time_obj_history, R"pbdoc(
Return a tuple of time, cost, constr
)pbdoc")
.def("get_lb", &pyProbFun::get_lb)
.def("get_ub", &pyProbFun::get_ub)
.def("get_xlb", &pyProbFun::get_xlb)
.def("get_xub", &pyProbFun::get_xub)
.def("get_aval", &pyProbFun::get_aval)
.def("get_arow", &pyProbFun::get_arow)
.def("get_acol", &pyProbFun::get_acol)
.def("set_lb", &pyProbFun::set_lb)
.def("set_ub", &pyProbFun::set_ub)
.def("set_xlb", &pyProbFun::set_xlb)
.def("set_xub", &pyProbFun::set_xub)
.def("batch_set_lb", &pyProbFun::batchSetLb, R"pydoc(
Set lb in batch mode by specifying an ndarray and starting index.
This value is not necessary since you can get a reference by get_lb and directly operate on that.
We keep it here for backward compatibility.
Other similar functions are not documented. Please refer to this.
Args:
lb (ndarray): a segment of lower bound to be set
ind0 (int): the starting index for this segment.
)pydoc")
.def("batch_set_ub", &pyProbFun::batchSetUb)
.def("batch_set_xlb", &pyProbFun::batchSetXlb)
.def("batch_set_xub", &pyProbFun::batchSetXub)
.def("random_gen_x", &pyProbFun::randomGenX, R"pydoc(
Randomly generate an initial guess of x within lb and ub bounds.
Returns:
ndarray: the generated initial guess.
)pydoc")
.def("eval_f", &pyProbFun::eval_f, R"pydoc(
Evaluate __callf__ once.
This serves for debugging purpose.
Args:
x (ndarray): a candidate solution
Returns:
y (ndarray): the evaluated function.
)pydoc")
.def("eval_g", &pyProbFun::eval_g, R"pydoc(
Evaluate __callf__ once.
This serves for debugging purpose.
Args:
x (ndarray): a candidate solution
Returns:
y (ndarray): the evaluated function.
G (ndarray): the value part of the returned Jacobian triplet.
row (ndarray): the row part of the returned Jacobian triplet.
col (ndarray): the column part of the returned Jacobian triplet.
)pydoc")
.def("__callf__", (int (ProblemFun::*)(cRefV, RefV)) &pyProbFun::operator())
.def("__callg__", (std::pair<int, int> (ProblemFun::*)(cRefV, RefV, RefV, RefVl, RefVl, bool, bool)) &pyProbFun::operator())
#ifdef ENABLEIP
.def("eval_cost", [](ProblemFun* self, cRefV x) {return self->evalF(x);})
.def("eval_gradient", [](ProblemFun* self, cRefV x) {VX grad(self->nx); self->evalGrad(x, grad); return grad;})
.def("eval_constr", [](ProblemFun* self, cRefV x) {VX g(self->nf); self->evalG(x, g); return g;})
.def("eval_jacobian", [](ProblemFun *self, cRefV x) {
int nG = self->nG;
VX g(nG);
VXl row(nG), col(nG);
self->evalJac(x, g, row, col, true);
return std::make_tuple(g, row, col);
})
.def("__cost__", &ProblemFun::evalF)
.def("__constraint__", &ProblemFun::evalG)
.def("__gradient__", &ProblemFun::evalGrad)
.def("__jacobian__", &ProblemFun::evalJac)
.def("__hessian__", &ProblemFun::evalHess)
#endif
.def("ipopt_style", [](ProblemFun *self) {self->ipStyle=true;})
.def("snopt_style", [](ProblemFun *self) {self->ipStyle=false;})
.def_readonly("ipstyle", &pyProbFun::ipStyle)
.def_readwrite("nx", &pyProbFun::nx)
.def_readwrite("nf", &pyProbFun::nf)
.def_readwrite("nG", &pyProbFun::nG)
.def_readwrite("nH", &pyProbFun::hess_nnz)
.def_readwrite("grad", &pyProbFun::grad)
.def_readwrite("Aval", &pyProbFun::Aval)
.def_readwrite("Arow", &pyProbFun::Arow)
.def_readwrite("Acol", &pyProbFun::Acol)
.def_readwrite("lb", &pyProbFun::lb)
.def_readwrite("ub", &pyProbFun::ub)
.def_readwrite("xlb", &pyProbFun::xlb)
.def_readwrite("xub", &pyProbFun::xub);
#ifdef SNOPT
// this class was called snoptConfig previously, consider changing __init__.py
py::class_<snoptConfig>(m, "SnoptConfig", R"pbdoc(
A class that specifies configuration to snopt solver, keep for backward compatibility.
This class has the default constructor.
Attributes:
name (str="Toy"): the name for the problem.
print_file (str): the filename for printing results.
print_level (int=0): the print level for major iteration; 0 disable iterations; 1 enables iterations.
minor_print_level (int=0): print level for minor iteration.
verify_level (int=0): level for gradient verification; 0 disable; 3 full verify.
major_iter_limit (int=0): major iteration limit
minor_iter_limit (int=0): minor iteration limit
iter_limit (int=0): total iteration limit
opt_tol (float=1e-6): tolerance for optimality
fea_tol (float=1e-6): tolerance for feasibility
int_options (list of (string, int) tuple): integer options
float_options (list of (string, float) tuple): float options
string_options (list of (string, string) tuple): string options
)pbdoc")
.def(py::init<>())
.def("add_int_option", &snoptConfig::addIntOption, R"pbdoc(
Add an integer option to configurations.
Args:
option (str): the option to configure
value (int): the integer value for configuration
)pbdoc")
.def("add_float_option", &snoptConfig::addFloatOption, R"pbdoc(
Add a float option to configurations.
Args:
option (str): the option to configure
value (float): the float value for configuration
)pbdoc")
.def("add_string_option", &snoptConfig::addStringOption, R"pbdoc(
Add a string option to configurations.
Args:
option (str): the option to configure
)pbdoc")
.def("set_major_iter", &snoptConfig::setMajorIter, R"pbdoc(
Set up the major iteration limit.
Args:
iter (int): limit for major iteration
)pbdoc")
.def("set_minor_iter", &snoptConfig::setMinorIter, R"pbdoc(
Set up the minor iteration limit.
Args:
iter (int): limit for minor iteration
)pbdoc")
.def("set_iter_limit", &snoptConfig::setIterLimit, R"pbdoc(
Set up the total iteration limit.
Args:
iter (int): limit for total iteration
)pbdoc")
.def("set_opt_tol", &snoptConfig::setOptTol, R"pbdoc(
Set up the optimization tolerance.
Args:
tol (float): the tolerance
)pbdoc")
.def("set_fea_tol", &snoptConfig::setFeaTol, R"pbdoc(
Set up the feasibility tolerance.
Args:
tol (float): the tolerance
)pbdoc")
.def("set_print_level", &snoptConfig::setPrintLevel, R"pbdoc(
Set up the print level.
Args:
level (int): the print level
)pbdoc")
.def("enable_deriv_check", &snoptConfig::enableDerivCheck, py::arg("lvl")=3, R"pbdoc(
Set up the derivative check param.
Args:
level (int): the derivative check level
)pbdoc")
//.def("enable_history", &snoptConfig::enableIterHistory, R"pbdoc(
// Store iteration history and return to the user.
//)pbdoc")
.def("addIntOption", &snoptConfig::addIntOption)
.def("addFloatOption", &snoptConfig::addFloatOption)
.def("addStringOption", &snoptConfig::addStringOption)
.def_readwrite("name", &snoptConfig::name)
.def_readwrite("print_file", &snoptConfig::printFile)
.def_readwrite("print_level", &snoptConfig::printlevel)
.def_readwrite("minor_print_level", &snoptConfig::minorprintlevel)
.def_readwrite("verify_level", &snoptConfig::verifylevel)
.def_readwrite("major_iter_limit", &snoptConfig::majoriterlimit)
.def_readwrite("minor_iter_limit", &snoptConfig::minoriterlimit)
.def_readwrite("iter_limit", &snoptConfig::iterationslimit)
.def_readwrite("opt_tol", &snoptConfig::optTol)
.def_readwrite("fea_tol", &snoptConfig::feaTol)
.def_readwrite("int_options", &snoptConfig::intOptions)
.def_readwrite("float_options", &snoptConfig::floatOptions)
.def_readwrite("string_options", &snoptConfig::stringOptions)
.def_readwrite("printFile", &snoptConfig::printFile)
.def_readwrite("printLevel", &snoptConfig::printlevel)
.def_readwrite("minorPrintLevel", &snoptConfig::minorprintlevel)
.def_readwrite("verifyLevel", &snoptConfig::verifylevel)
.def_readwrite("majorIterLimit", &snoptConfig::majoriterlimit)
.def_readwrite("minorIterLimit", &snoptConfig::minoriterlimit)
.def_readwrite("iterLimit", &snoptConfig::iterationslimit)
.def_readwrite("optTol", &snoptConfig::optTol)
.def_readwrite("feaTol", &snoptConfig::feaTol)
.def_readwrite("intOptions", &snoptConfig::intOptions)
.def_readwrite("floatOptions", &snoptConfig::floatOptions)
.def_readwrite("stringOptions", &snoptConfig::stringOptions);
//.def("init", (void (pyServer::*)(const config &cfgin)) &pyServer::init, "init by config object")
py::class_<pySnoptWrapper>(m, "SnoptSolver", R"pbdoc(
The snopt solver class that is constructed by a SnoptProblem object and a SnoptConfig object.
Args:
prob (SnoptProblem): the problem object.
cfg (SnoptConfig): the configuration.
)pbdoc")
.def(py::init<ProblemFun&, snoptConfig&>())
.def("solve_rand", (optResult (pySnoptWrapper::*)()) &pySnoptWrapper::solve, R"pbdoc(
Solve the problem using a random guess generated by the solver itself.
Returns:
SnoptResult: a SnoptResult object.
)pbdoc")
.def("solve_guess", (optResult (pySnoptWrapper::*)(cRefV x)) &pySnoptWrapper::solve, R"pbdoc(
Solve the problem using a user-specified guess.
Args:
x (ndarray): an initial guess.
Returns:
SnoptResult: a SnoptResult object.
)pbdoc")
.def("solve_more", &pySnoptWrapper::solve_more, R"pbdoc(
Use hot restart and continue a few major iterations.
It can be used when SNOPT is solely used for backtracking.
Args:
iter (int): desired iteration number
Returns:
SnoptResult: a SnoptResult object
)pbdoc")
.def("obj_search", &pySnoptWrapper::obj_search, R"pbdoc(
Given an initial, use search style to control how solver proceed.
Args:
guess (ndarray): an initial guess
iter (int): initial iteration time
step (int): iteration time for later search
step_num (int): how many more step iterations do we play.
abstol (float): absolute cost tolerance, exit if improvement is smaller than it
reltol (float): relative cost tolerance, exit if improvement is smaller than reltol * last cost
Returns:
SnoptResult: a SnoptResult object
costs: ndarray, recorded costs during search
times: ndarray, recorded used times during search
)pbdoc")
.def("get_info", &pySnoptWrapper::getInfo, R"pbdoc(
Get the inform variable from the solver. It indicates solving status.
Returns:
int: the info.
)pbdoc")
#ifdef ENABLE_WORKSPACE
.def("set_workspace", &pySnoptWrapper::setWorkspace, R"pbdoc(
Set the integer and real workspace size, this is necessary sometimes.
Args:
size (int): the desired integer workspace size.
size (int): the desired real workspace size.
)pbdoc")
.def("setWorkspace", &pySnoptWrapper::setWorkspace)
#endif
.def("fEval", &pySnoptWrapper::fEval)
.def("setOptTol", &pySnoptWrapper::setOptTol)
.def("setFeaTol", &pySnoptWrapper::setFeaTol)
.def("setIntOption", &pySnoptWrapper::setIntOption)
.def("setFloatOption", &pySnoptWrapper::setDoubleOption)
.def("setMajorIter", &pySnoptWrapper::setMajorIter)
.def("setPrintFile", &pySnoptWrapper::setPrintFile)
.def("solveRand", (optResult (pySnoptWrapper::*)()) &pySnoptWrapper::solve)
.def("solveGuess", (optResult (pySnoptWrapper::*)(cRefV x)) &pySnoptWrapper::solve)
.def("getInfo", &pySnoptWrapper::getInfo)
.def("fEval", &pySnoptWrapper::fEval);
m.def("directSolve", &directSolve);
m.def("inDirectSolve", &directInSolve);
m.def("gradSolve", &gradFunSolve);
m.def("inGradSolve", &inGradFunSolve);
m.def("spGradSolve", &spGradFunSolve);
m.def("inSpGradSolve", &inSpGradFunSolve);
m.attr("__with_snopt__") = true;
#else
m.attr("__with_snopt__") = false;
#endif
#ifdef IPOPT
// this class was called snoptConfig previously, consider changing __init__.py
py::class_<IpoptConfig>(m, "IpoptConfig", R"pbdoc(
A class that specifies configuration to ipopt solver.
This class has the default constructor.
Attributes:
print_level (int): level for printing = 4
max_iter (int): maximum iteration = 1000
linear_solver (string): linear solver = "mumps";
hessian_approximation (string): Hessian approach = "limited-memory"
jacobian_appximation (string): Jacobian approach = "exact";
derivative_test (string): if test derivative = "no";
tol (float): convergence tolerance = 1e-6;
constr_vio_tol (float): tolerance on constraint = 1e-6;
max_cpu_time (float): computation time = 1e6;
)pbdoc")
.def(py::init<>())
.def("add_int_option", &IpoptConfig::addIntOption, R"pbdoc(
Add an integer option to configurations.
Args:
option (str): the option to configure
value (int): the integer value for configuration
)pbdoc")
.def("add_float_option", &IpoptConfig::addFloatOption, R"pbdoc(
Add a float option to configurations.
Args:
option (str): the option to configure
value (float): the float value for configuration
)pbdoc")
.def("add_string_option", &IpoptConfig::addPairStringOption, R"pbdoc(
Add a string option to configurations.
Args:
option (str): the option to configure
value (str): the string value for configuration
)pbdoc")
.def("set_major_iter", &IpoptConfig::setMajorIter, R"pbdoc(
Set up the major iteration limit.
Args:
iter (int): limit for major iteration
)pbdoc")
.def("set_opt_tol", &IpoptConfig::setOptTol, R"pbdoc(
Set up the optimization tolerance.
Args:
tol (float): the tolerance
)pbdoc")
.def("set_fea_tol", &IpoptConfig::setFeaTol, R"pbdoc(
Set up the feasibility tolerance.
Args:
tol (float): the tolerance
)pbdoc")
.def("set_print_level", &IpoptConfig::setPrintLevel, R"pbdoc(
Set up the print level.
Args:
level (int): the print level
)pbdoc")
.def("enable_deriv_check", &IpoptConfig::enableDerivCheck, py::arg("lvl")=0, R"pbdoc(
Set up the derivative check param.
Args:
level (int): the derivative check level
)pbdoc")
.def("set_print_freq", &IpoptConfig::setPrintFreq, R"pbdoc(
Set up the print frequency.
Args:
freq (int): the print frequency
)pbdoc")
.def("set_linear_solver", &IpoptConfig::setLinearSolver, R"pbdoc(
Set the linear solver.
Args:
solver (str): the selected linear solver.
)pbdoc")
.def("enable_exact_hessian", &IpoptConfig::enableExactHessian, R"pbdoc(
Enable usage of exact Hessian.
)pbdoc")
.def("enable_fd_jacobian", &IpoptConfig::enableFDJacobian, R"pbdoc(
Enable usage of finite-difference approximation of Jacobian.
)pbdoc")
.def_readwrite("print_level", &IpoptConfig::print_level)
.def_readwrite("print_frequency_iter", &IpoptConfig::print_frequency_iter)
.def_readwrite("max_iter", &IpoptConfig::max_iter)
.def_readwrite("linear_solver", &IpoptConfig::linear_solver)
.def_readwrite("hessian_approximation", &IpoptConfig::hessian_approximation)
.def_readwrite("jacobian_approximation", &IpoptConfig::jacobian_approximation)
.def_readwrite("derivative_test", &IpoptConfig::derivative_test)
.def_readwrite("tol", &IpoptConfig::tol)
.def_readwrite("constr_vio_tol", &IpoptConfig::constr_viol_tol)
.def_readwrite("max_cpu_time", &IpoptConfig::max_cpu_time)
;
py::class_<IpoptSolver>(m, "IpoptSolver", R"pbdoc(
The solver class.
)pbdoc")
.def(py::init<ProblemFun&, IpoptConfig &>())
.def("solve_rand", &IpoptSolver::solve_rand)
.def("solve_guess", &IpoptSolver::solve_guess)
;
m.def("solve_problem", &solve_problem);
m.def("set_verbosity", [](bool verbose) {VERBOSE = verbose;});
m.attr("__with_ipopt__") = true;
#else
m.attr("__with_ipopt__") = false;
#endif
m.def("set_fd_step", [](double step) {PYOPTSOLVER_FD_STEP = step;});
#ifdef VERSION_INFO
m.attr("__version__") = VERSION_INFO;
#else
m.attr("__version__") = "dev";
#endif
}
| [
"gaotang2@illinois.edu"
] | gaotang2@illinois.edu |
5008d485a30f1123c79dfc76c3e11046a6f24dfd | fe5e4748939432af1d691f9d5837206fbf6c6c2f | /C++/ex_pow.cpp | b77b5b1b3d438ad530c7e69c2183ddbb11e539f8 | [] | no_license | soadkhan/My-Code | e0ebe0898d68df983e8c41e56633780d6ac22c39 | 72fc258cdbf08d86f20a565afe371713e8e8bc39 | refs/heads/master | 2021-01-23T03:27:34.181019 | 2017-03-24T14:42:15 | 2017-03-24T14:42:15 | 86,077,758 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,019 | cpp | #include<new>
#include<sstream>
#include<cstdlib>
#include<cctype>
#include<math.h>
#include<algorithm>
#include<set>
#include<queue>
#include<stack>
#include<list>
#include<iostream>
#include<fstream>
#include<numeric>
#include<string>
#include<vector>
#include<cstring>
#include<map>
#include<iterator>
#include<cstdio>
#include<cstdlib>
using namespace std;
long long int pw(long long int a,long long int b){long long int sum=1;for(long long int i=0;i<b;i++){sum*=a;}return sum;}
long long int dif(long long int a,long long int b){if(a>b) return (a-b);else return (b-a);}
int strlen(string s){int len = 0;while (s[len]) len++;return len;}
long long int max(long long int a,long long int b){if(a>b ) return a;else return b;}
long long int min(long long int a,long long int b){if(a<b ) return a;else return b;}
int main(void)
{
freopen("uva.txt","rt",stdin);
unsigned long long int a,b;
while(cin>>a>>b){
cout<<pow((long double)b,1.0/(long double)a)<<endl;
}
return 0;
}
| [
"khancse5914@gmail.com"
] | khancse5914@gmail.com |
42f00bb7b603f7653b598f6237457f5645f365af | 3193d3c261bb04ce03c28c7d930f4104199a89aa | /FPGA/filtering_algorithm_util.cpp | 668dd1ac7282ccd66c7ee815bf15a9dc618a6a11 | [] | no_license | eejlny/KMEANS-SDSOC | 6b22ec0f7cc8e0d9c2bea131ea1130ec102ac2ac | cf1b189766c6a86aa9260f7efc10f3fef1b0f96c | refs/heads/master | 2021-04-12T08:16:18.808283 | 2018-03-26T11:12:06 | 2018-03-26T11:12:06 | 125,993,498 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,688 | cpp | /**********************************************************************
* Felix Winterstein, Imperial College London
*
* File: filtering_algorithm_util.cpp
*
* Revision 1.01
* Additional Comments: distributed under a BSD license, see LICENSE.txt
*
**********************************************************************/
#include <math.h>
#include "filtering_algorithm_util.h"
/* overloading operators */
/*
data_type& data_type::operator=(const data_type& a)
{
value = a.value;
return *this;
}
data_type& data_type::operator=(const volatile data_type& a)
{
value = a.value;
return *this;
}
data_type_ext& data_type_ext::operator=(const data_type_ext& a)
{
value = a.value;
return *this;
}
data_type_ext& data_type_ext::operator=(const volatile data_type_ext& a)
{
value = a.value;
return *this;
}
kdTree_type& kdTree_type::operator=(const kdTree_type& a)
{
count = a.count;
wgtCent = a.wgtCent;
sum_sq = a.sum_sq;
midPoint = a.midPoint;
bnd_lo = a.bnd_lo;
bnd_hi = a.bnd_hi;
left = a.left;
right = a.right;
#ifndef __SYNTHESIS__
idx = a.idx;
#endif
return *this;
}
kdTree_type& kdTree_type::operator=(const volatile kdTree_type& a)
{
count = a.count;
wgtCent = a.wgtCent;
sum_sq = a.sum_sq;
midPoint = a.midPoint;
bnd_lo = a.bnd_lo;
bnd_hi = a.bnd_hi;
left = a.left;
right = a.right;
#ifndef __SYNTHESIS__
idx = a.idx;
#endif
return *this;
}
kdTree_leaf_type& kdTree_leaf_type::operator=(const kdTree_leaf_type& a)
{
wgtCent = a.wgtCent;
sum_sq = a.sum_sq;
return *this;
}
kdTree_leaf_type& kdTree_leaf_type::operator=(const volatile kdTree_leaf_type& a)
{
wgtCent = a.wgtCent;
sum_sq = a.sum_sq;
return *this;
}
centre_type& centre_type::operator=(const centre_type& a)
{
count = a.count;
wgtCent = a.wgtCent;
sum_sq = a.sum_sq;
return *this;
}
centre_type& centre_type::operator=(const volatile centre_type& a)
{
count = a.count;
wgtCent = a.wgtCent;
sum_sq = a.sum_sq;
return *this;
}
/* ****** helper functions *******/
void set_coord_type_vector_item(coord_type_vector *a, const coord_type b, const uint idx)
{
#pragma HLS function_instantiate variable=idx
a->range((idx+1)*COORD_BITWIDTH-1,idx*COORD_BITWIDTH) = b;
}
void set_coord_type_vector_ext_item(coord_type_vector_ext *a, const coord_type_ext b, const uint idx)
{
#pragma HLS function_instantiate variable=idx
a->range((idx+1)*COORD_BITWITDH_EXT-1,idx*COORD_BITWITDH_EXT) = b;
}
coord_type get_coord_type_vector_item(const coord_type_vector a, const uint idx)
{
#pragma HLS function_instantiate variable=idx
coord_type tmp= a.range((idx+1)*COORD_BITWIDTH-1,idx*COORD_BITWIDTH);
return tmp;
}
coord_type_ext get_coord_type_vector_ext_item(const coord_type_vector_ext a, const uint idx)
{
#pragma HLS function_instantiate variable=idx
coord_type_ext tmp= a.range((idx+1)*COORD_BITWITDH_EXT-1,idx*COORD_BITWITDH_EXT);
return tmp;
}
// conversion from data_type_ext to data_type
data_type conv_long_to_short(data_type_ext p)
{
#pragma HLS inline
data_type result;
for (uint d=0; d<D; d++) {
#pragma HLS unroll
coord_type tmp = (coord_type)get_coord_type_vector_ext_item(p.value,d);
set_coord_type_vector_item(&result.value,tmp,d);
}
return result;
}
// conversion from data_type to data_type_ext
data_type_ext conv_short_to_long(data_type p)
{
#pragma HLS inline
data_type_ext result;
for (uint d=0; d<D; d++) {
#pragma HLS unroll
coord_type_ext tmp = (coord_type_ext)get_coord_type_vector_item(p.value,d);
set_coord_type_vector_ext_item(&result.value,tmp,d);
}
return result;
}
mul_input_type saturate_mul_input(coord_type_ext val)
{
#pragma HLS inline
if (val > MUL_MAX_VAL) {
val = MUL_MAX_VAL;
} else if (val < MUL_MIN_VAL) {
val = MUL_MIN_VAL;
}
return (mul_input_type)val;
}
// fixed-point multiplication with saturation and scaling
coord_type_ext fi_mul(coord_type_ext op1, coord_type_ext op2)
{
#pragma HLS inline
mul_input_type tmp_op1 = saturate_mul_input(op1);
mul_input_type tmp_op2 = saturate_mul_input(op2);
ap_int<2*(MUL_INTEGER_BITS+MUL_FRACTIONAL_BITS)> result_unscaled;
result_unscaled = tmp_op1*tmp_op2;
#pragma HLS resource variable=result_unscaled core=MulnS
ap_int<2*(MUL_INTEGER_BITS+MUL_FRACTIONAL_BITS)> result_scaled;
result_scaled = result_unscaled >> MUL_FRACTIONAL_BITS;
coord_type_ext result;
result = (coord_type_ext)result_scaled;
return result;
}
// tree adder
coord_type_ext tree_adder(coord_type_ext *input_array)
{
#pragma HLS inline
for(uint j=0;j<MYCEILLOG2[D];j++)
{
#pragma HLS unroll
#pragma HLS dependence variable=input_array inter false
if (j<MYCEILLOG2[D]-1) {
for(uint i = 0; i < uint(D/(1<<(j+1))); i++)
{
#pragma HLS unroll
#pragma HLS dependence variable=input_array inter false
coord_type_ext tmp1 = input_array[2*i];
coord_type_ext tmp2 = input_array[2*i+1];
coord_type_ext tmp3 = tmp1+tmp2;
input_array[i] = tmp3;
}
if (D > uint(D/(1<<(j+1)))*(1<<(j+1)) ) {
input_array[uint(D/(1<<(j+1)))] = input_array[uint(D/(1<<(j+1))-1)*2+2];
}
}
if (j== MYCEILLOG2[D]-1) {
coord_type_ext tmp1 = input_array[0];
coord_type_ext tmp2 = input_array[1];
coord_type_ext tmp3 = tmp1+tmp2;
input_array[0] = tmp3;
}
}
return input_array[0];
}
// tree adder (overloaded function)
coord_type_ext tree_adder(coord_type_ext *input_array,const uint m)
{
#pragma HLS inline
for(uint j=0;j<MYCEILLOG2[m];j++)
{
#pragma HLS unroll
if (j<MYCEILLOG2[m]-1) {
for(uint i = 0; i < uint(m/(1<<(j+1))); i++)
{
#pragma HLS unroll
coord_type_ext tmp1 = input_array[2*i];
coord_type_ext tmp2 = input_array[2*i+1];
coord_type_ext tmp3 = tmp1+tmp2;
input_array[i] = tmp3;
#pragma HLS resource variable=tmp3 core=AddSubnS
}
if (m > uint(m/(1<<(j+1)))*(1<<(j+1)) ) {
input_array[uint(m/(1<<(j+1)))] = input_array[uint(m/(1<<(j+1))-1)*2+2];
}
}
if (j== MYCEILLOG2[m]-1) {
coord_type_ext tmp1 = input_array[0];
coord_type_ext tmp2 = input_array[1];
coord_type_ext tmp3 = tmp1+tmp2;
input_array[0] = tmp3;
#pragma HLS resource variable=tmp3 core=AddSubnS
}
}
return input_array[0];
}
// inner product of p1 and p2
void dot_product(data_type_ext p1,data_type_ext p2, coord_type_ext *r)
{
#pragma HLS inline
coord_type_ext tmp_mul_res[D];
#pragma HLS array_partition variable=tmp_mul_res complete dim=0
for (uint d=0;d<D;d++) {
#pragma HLS unroll
mul_input_type tmp_op1 = saturate_mul_input(get_coord_type_vector_ext_item(p1.value,d));
mul_input_type tmp_op2 = saturate_mul_input(get_coord_type_vector_ext_item(p2.value,d));
coord_type_ext tmp_mul = tmp_op1*tmp_op2;
tmp_mul_res[d] = tmp_mul;
#pragma HLS resource variable=tmp_mul core=MulnS
}
*r = tree_adder(tmp_mul_res);
}
// compute the Euclidean distance between p1 and p2
void compute_distance(data_type_ext p1, data_type_ext p2, coord_type_ext *dist)
{
#pragma HLS inline
data_type_ext tmp_p1 = p1;
data_type_ext tmp_p2 = p2;
coord_type_ext tmp_mul_res[D];
for (uint d=0; d<D; d++) {
#pragma HLS unroll
coord_type_ext tmp_sub1 = get_coord_type_vector_ext_item(tmp_p1.value,d);
coord_type_ext tmp_sub2 = get_coord_type_vector_ext_item(tmp_p2.value,d);
coord_type_ext tmp = tmp_sub1 - tmp_sub2;
coord_type_ext tmp_mul = fi_mul(tmp,tmp);
tmp_mul_res[d] = tmp_mul;
#pragma HLS resource variable=tmp_mul core=MulnS
}
*dist = tree_adder(tmp_mul_res);
}
// check whether any point of bounding box is closer to z than to z*
// this is a modified version of David Mount's code (http://www.cs.umd.edu/~mount/Projects/KMeans/ )
void tooFar_fi(data_type closest_cand, data_type cand, data_type bnd_lo, data_type bnd_hi, bool *too_far)
{
#pragma HLS inline
coord_type_ext boxDot;
coord_type_ext ccDot;
data_type_ext tmp_closest_cand = conv_short_to_long(closest_cand);
data_type_ext tmp_cand = conv_short_to_long(cand);
data_type_ext tmp_bnd_lo = conv_short_to_long(bnd_lo);
data_type_ext tmp_bnd_hi = conv_short_to_long(bnd_hi);
coord_type_ext tmp_mul_res[D];
coord_type_ext tmp_mul_res2[D];
for (uint d = 0; d<D; d++) {
#pragma HLS unroll
#pragma HLS dependence variable=tmp_mul_res inter false
#pragma HLS dependence variable=tmp_mul_res2 inter false
coord_type_ext tmp_sub_op1 = get_coord_type_vector_ext_item(tmp_cand.value,d);
coord_type_ext tmp_sub_op2 = get_coord_type_vector_ext_item(tmp_closest_cand.value,d);
coord_type_ext ccComp = tmp_sub_op1-tmp_sub_op2;
coord_type_ext tmp_mul = fi_mul(ccComp,ccComp);
tmp_mul_res[d] = tmp_mul;
#pragma HLS resource variable=tmp_mul core=MulnS
coord_type_ext tmp_diff2;
coord_type_ext tmp_sub_op3;
coord_type_ext tmp_sub_op4;
if (ccComp > 0) {
tmp_sub_op3 = get_coord_type_vector_ext_item(tmp_bnd_hi.value,d);
}
else {
tmp_sub_op3 = get_coord_type_vector_ext_item(tmp_bnd_lo.value,d);
}
tmp_sub_op4 = get_coord_type_vector_ext_item(tmp_closest_cand.value,d);
tmp_diff2 = tmp_sub_op3 - tmp_sub_op4;
coord_type_ext tmp_mul2 = fi_mul(tmp_diff2,ccComp);
tmp_mul_res2[d] = tmp_mul2;
#pragma HLS resource variable=tmp_mul2 core=MulnS
}
ccDot = tree_adder(tmp_mul_res);
boxDot = tree_adder(tmp_mul_res2);
coord_type_ext tmp_boxDot = boxDot<<1;
bool tmp_res;
if (ccDot>tmp_boxDot) {
tmp_res = true;
} else {
tmp_res = false;
}
*too_far = tmp_res;
}
| [
"eejlny@bristol.ac.uk"
] | eejlny@bristol.ac.uk |
c56cbd40477a03cfed473e16885d81405e80888f | a2c3028bbb015596e6d1b83fe23bd4c9fda0d72d | /info/wip/in-process/src/xk/external/xpdf/xpdf/xpdf-qt/QtPDFCore.cc | 751ceb8acb9a6d889c6a0cd78d70870124f3db9c | [] | no_license | scignscape/ntxh | 1c025b0571ecde6b25062c4013bf8a47aeb7fdcb | ee9576360c1962afb742830828670aca5fa153d6 | refs/heads/master | 2023-04-01T07:20:26.138527 | 2021-03-17T17:59:48 | 2021-03-17T17:59:48 | 225,418,021 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,739 | cc | //========================================================================
//
// QtPDFCore.cc
//
// Copyright 2009-2014 Glyph & Cog, LLC
//
//========================================================================
#include <aconf.h>
#ifdef USE_GCC_PRAGMAS
#pragma implementation
#endif
#include <math.h>
#include <string.h>
#include <QApplication>
#include <QClipboard>
#include <QDesktopServices>
#include <QFileInfo>
#include <QImage>
#include <QInputDialog>
#include <QMessageBox>
#include <QPainter>
#include <QProcess>
#include <QScrollBar>
#include <QStyle>
#include <QUrl>
#include <QWidget>
#include "gmem.h"
#include "gmempp.h"
#include "gfile.h"
#include "GString.h"
#include "GList.h"
#include "Error.h"
#include "GlobalParams.h"
#include "PDFDoc.h"
#include "Link.h"
#include "ErrorCodes.h"
#include "GfxState.h"
#include "PSOutputDev.h"
#include "TextOutputDev.h"
#include "SplashBitmap.h"
#include "DisplayState.h"
#include "TileMap.h"
#include "QtPDFCore.h"
//------------------------------------------------------------------------
// QtPDFCore
//------------------------------------------------------------------------
QtPDFCore::QtPDFCore(QWidget *viewportA,
QScrollBar *hScrollBarA, QScrollBar *vScrollBarA,
SplashColorPtr paperColor, SplashColorPtr matteColor,
GBool reverseVideo):
PDFCore(splashModeRGB8, 4, reverseVideo, paperColor)
{
int dpiX, dpiY;
viewport = viewportA;
hScrollBar = hScrollBarA;
vScrollBar = vScrollBarA;
hScrollBar->setRange(0, 0);
hScrollBar->setSingleStep(16);
vScrollBar->setRange(0, 0);
vScrollBar->setSingleStep(16);
viewport->setMouseTracking(true);
state->setMatteColor(matteColor);
oldFirstPage = -1;
oldMidPage = -1;
linkAction = NULL;
lastLinkAction = NULL;
dragging = gFalse;
panning = gFalse;
inUpdateScrollbars = gFalse;
updateCbk = NULL;
midPageChangedCbk = NULL;
preLoadCbk = NULL;
postLoadCbk = NULL;
actionCbk = NULL;
linkCbk = NULL;
selectDoneCbk = NULL;
// optional features default to on
hyperlinksEnabled = gTrue;
selectEnabled = gTrue;
panEnabled = gTrue;
showPasswordDialog = gTrue;
// get Qt's HiDPI scale factor
#if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
scaleFactor = viewport->devicePixelRatioF();
#elif QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
scaleFactor = viewport->devicePixelRatio();
#else
scaleFactor = 1;
#endif
// get the display resolution (used for HiDPI scaling)
dpiX = viewport->logicalDpiX();
dpiY = viewport->logicalDpiY();
displayDpi = dpiX < dpiY ? dpiX : dpiY;
displayDpi = (int)(displayDpi * scaleFactor);
}
QtPDFCore::~QtPDFCore() {
}
//------------------------------------------------------------------------
// loadFile / displayPage / displayDest
//------------------------------------------------------------------------
int QtPDFCore::loadFile(GString *fileName, GString *ownerPassword,
GString *userPassword) {
int err;
err = PDFCore::loadFile(fileName, ownerPassword, userPassword);
if (err == errNone) {
// save the modification time
modTime = QFileInfo(doc->getFileName()->getCString()).lastModified();
// update the parent window
if (updateCbk) {
(*updateCbk)(updateCbkData, doc->getFileName(), -1,
doc->getNumPages(), NULL);
}
oldFirstPage = oldMidPage = -1;
}
return err;
}
#ifdef _WIN32
int QtPDFCore::loadFile(wchar_t *fileName, int fileNameLen,
GString *ownerPassword,
GString *userPassword) {
int err;
err = PDFCore::loadFile(fileName, fileNameLen, ownerPassword, userPassword);
if (err == errNone) {
// save the modification time
modTime = QFileInfo(doc->getFileName()->getCString()).lastModified();
// update the parent window
if (updateCbk) {
(*updateCbk)(updateCbkData, doc->getFileName(), -1,
doc->getNumPages(), NULL);
}
oldFirstPage = oldMidPage = -1;
}
return err;
}
#endif
int QtPDFCore::loadFile(BaseStream *stream, GString *ownerPassword,
GString *userPassword) {
int err;
err = PDFCore::loadFile(stream, ownerPassword, userPassword);
if (err == errNone) {
// no file
modTime = QDateTime();
// update the parent window
if (updateCbk) {
(*updateCbk)(updateCbkData, doc->getFileName(), -1,
doc->getNumPages(), NULL);
}
oldFirstPage = oldMidPage = -1;
}
return err;
}
void QtPDFCore::loadDoc(PDFDoc *docA) {
PDFCore::loadDoc(docA);
// save the modification time
if (doc->getFileName()) {
modTime = QFileInfo(doc->getFileName()->getCString()).lastModified();
} else {
modTime = QDateTime();
}
// update the parent window
if (updateCbk) {
(*updateCbk)(updateCbkData, doc->getFileName(), -1,
doc->getNumPages(), NULL);
}
oldFirstPage = oldMidPage = -1;
}
int QtPDFCore::reload() {
int err;
err = PDFCore::reload();
if (err == errNone) {
// save the modification time
modTime = QFileInfo(doc->getFileName()->getCString()).lastModified();
// update the parent window
if (updateCbk) {
(*updateCbk)(updateCbkData, doc->getFileName(), -1,
doc->getNumPages(), NULL);
}
oldFirstPage = oldMidPage = -1;
}
return err;
}
void QtPDFCore::finishUpdate(GBool addToHist, GBool checkForChangedFile) {
int firstPage, midPage;
PDFCore::finishUpdate(addToHist, checkForChangedFile);
firstPage = getPageNum();
if (doc && firstPage != oldFirstPage && updateCbk) {
(*updateCbk)(updateCbkData, NULL, firstPage, -1, "");
}
oldFirstPage = firstPage;
midPage = getMidPageNum();
if (doc && midPage != oldMidPage && midPageChangedCbk) {
(*midPageChangedCbk)(midPageChangedCbkData, midPage);
}
oldMidPage = midPage;
linkAction = NULL;
lastLinkAction = NULL;
}
//------------------------------------------------------------------------
// panning and selection
//------------------------------------------------------------------------
void QtPDFCore::startPan(int wx, int wy) {
if (!panEnabled) {
return;
}
panning = gTrue;
panMX = wx;
panMY = wy;
}
void QtPDFCore::endPan(int wx, int wy) {
panning = gFalse;
}
void QtPDFCore::startSelection(int wx, int wy) {
int pg, x, y;
takeFocus();
if (!doc || doc->getNumPages() == 0 || !selectEnabled) {
return;
}
if (!cvtWindowToDev(wx, wy, &pg, &x, &y)) {
return;
}
startSelectionDrag(pg, x, y);
doSetCursor(Qt::CrossCursor);
dragging = gTrue;
}
void QtPDFCore::endSelection(int wx, int wy) {
LinkAction *action;
int pg, x, y;
double xu, yu;
GBool ok;
if (!doc || doc->getNumPages() == 0) {
return;
}
ok = cvtWindowToDev(wx, wy, &pg, &x, &y);
if (dragging) {
dragging = gFalse;
doUnsetCursor();
if (ok) {
moveSelectionDrag(pg, x, y);
}
finishSelectionDrag();
if (selectDoneCbk) {
(*selectDoneCbk)(selectDoneCbkData);
}
#ifndef NO_TEXT_SELECT
if (hasSelection()) {
copySelection(gFalse);
}
#endif
}
if (ok) {
if (hasSelection()) {
action = NULL;
} else {
cvtDevToUser(pg, x, y, &xu, &yu);
action = findLink(pg, xu, yu);
}
if (linkCbk && action) {
doLinkCbk(action);
}
if (hyperlinksEnabled && action) {
doAction(action);
}
}
}
void QtPDFCore::mouseMove(int wx, int wy) {
LinkAction *action;
int pg, x, y;
double xu, yu;
const char *s;
GBool ok;
if (!doc || doc->getNumPages() == 0) {
return;
}
ok = cvtWindowToDev(wx, wy, &pg, &x, &y);
if (dragging) {
if (ok) {
moveSelectionDrag(pg, x, y);
}
} else if (hyperlinksEnabled) {
cvtDevToUser(pg, x, y, &xu, &yu);
if (ok && (action = findLink(pg, xu, yu))) {
doSetCursor(Qt::PointingHandCursor);
if (action != linkAction) {
linkAction = action;
if (updateCbk) {
//~ should pass a QString to updateCbk()
s = getLinkInfo(action).toLocal8Bit().constData();
(*updateCbk)(updateCbkData, NULL, -1, -1, s);
}
}
} else {
doUnsetCursor();
if (linkAction) {
linkAction = NULL;
if (updateCbk) {
(*updateCbk)(updateCbkData, NULL, -1, -1, "");
}
}
}
}
if (panning) {
scrollTo(getScrollX() - (wx - panMX),
getScrollY() - (wy - panMY));
panMX = wx;
panMY = wy;
}
}
void QtPDFCore::doLinkCbk(LinkAction *action) {
LinkDest *dest;
GString *namedDest;
Ref pageRef;
int pg;
GString *cmd, *params;
char *s;
if (!linkCbk) {
return;
}
switch (action->getKind()) {
case actionGoTo:
dest = NULL;
if ((dest = ((LinkGoTo *)action)->getDest())) {
dest = dest->copy();
} else if ((namedDest = ((LinkGoTo *)action)->getNamedDest())) {
dest = doc->findDest(namedDest);
}
pg = 0;
if (dest) {
if (dest->isPageRef()) {
pageRef = dest->getPageRef();
pg = doc->findPage(pageRef.num, pageRef.gen);
} else {
pg = dest->getPageNum();
}
delete dest;
}
(*linkCbk)(linkCbkData, "goto", NULL, pg);
break;
case actionGoToR:
(*linkCbk)(linkCbkData, "pdf",
((LinkGoToR *)action)->getFileName()->getCString(), 0);
break;
case actionLaunch:
cmd = ((LinkLaunch *)action)->getFileName()->copy();
s = cmd->getCString();
if (strcmp(s + cmd->getLength() - 4, ".pdf") &&
strcmp(s + cmd->getLength() - 4, ".PDF") &&
(params = ((LinkLaunch *)action)->getParams())) {
cmd->append(' ')->append(params);
}
(*linkCbk)(linkCbkData, "launch", cmd->getCString(), 0);
delete cmd;
break;
case actionURI:
(*linkCbk)(linkCbkData, "url",
((LinkURI *)action)->getURI()->getCString(), 0);
break;
case actionNamed:
(*linkCbk)(linkCbkData, "named",
((LinkNamed *)action)->getName()->getCString(), 0);
break;
case actionMovie:
case actionJavaScript:
case actionSubmitForm:
case actionHide:
case actionUnknown:
(*linkCbk)(linkCbkData, "unknown", NULL, 0);
break;
}
}
QString QtPDFCore::getSelectedTextQString(int* page) {
GString *s, *enc;
QString qs;
QChar c;
int i;
// // dsC
if(!doc) return "";
if (!doc->okToCopy()) {
return "";
}
if (!(s = getSelectedText(page))) {
return "";
}
enc = globalParams->getTextEncodingName();
if (!s->cmp("UTF-8")) {
qs = QString::fromUtf8(s->getCString());
} else if (!s->cmp("UCS-2")) {
for (i = 0; i+1 < s->getLength(); i += 2) {
qs.append((QChar)(((s->getChar(i) & 0xff) << 8) +
(s->getChar(i+1) & 0xff)));
}
} else {
qs = QString(s->getCString());
}
delete s;
delete enc;
return qs;
}
void QtPDFCore::copySelection(GBool toClipboard) {
QString qs;
// only X11 has the copy-on-select behavior
if (!toClipboard && !QApplication::clipboard()->supportsSelection()) {
return;
}
if (!doc->okToCopy()) {
return;
}
if (hasSelection()) {
QApplication::clipboard()->setText(getSelectedTextQString(),
toClipboard ? QClipboard::Clipboard
: QClipboard::Selection);
}
}
//------------------------------------------------------------------------
// hyperlinks
//------------------------------------------------------------------------
GBool QtPDFCore::doAction(LinkAction *action) {
LinkActionKind kind;
LinkDest *dest;
GString *namedDest;
char *s;
GString *fileName, *fileName2, *params;
GString *cmd;
GString *actionName;
Object movieAnnot, obj1, obj2;
GString *msg;
int i;
switch (kind = action->getKind()) {
// GoTo / GoToR action
case actionGoTo:
case actionGoToR:
if (kind == actionGoTo) {
dest = NULL;
namedDest = NULL;
if ((dest = ((LinkGoTo *)action)->getDest())) {
dest = dest->copy();
} else if ((namedDest = ((LinkGoTo *)action)->getNamedDest())) {
namedDest = namedDest->copy();
}
} else {
dest = NULL;
namedDest = NULL;
if ((dest = ((LinkGoToR *)action)->getDest())) {
dest = dest->copy();
} else if ((namedDest = ((LinkGoToR *)action)->getNamedDest())) {
namedDest = namedDest->copy();
}
s = ((LinkGoToR *)action)->getFileName()->getCString();
if (isAbsolutePath(s)) {
fileName = new GString(s);
} else {
fileName = appendToPath(grabPath(doc->getFileName()->getCString()), s);
}
if (loadFile(fileName) != errNone) {
if (dest) {
delete dest;
}
if (namedDest) {
delete namedDest;
}
delete fileName;
return gFalse;
}
delete fileName;
}
if (namedDest) {
dest = doc->findDest(namedDest);
delete namedDest;
}
if (dest) {
displayDest(dest);
delete dest;
} else {
if (kind == actionGoToR) {
displayPage(1, gFalse, gFalse, gTrue);
}
}
break;
// Launch action
case actionLaunch:
fileName = ((LinkLaunch *)action)->getFileName();
s = fileName->getCString();
if (fileName->getLength() >= 4 &&
(!strcmp(s + fileName->getLength() - 4, ".pdf") ||
!strcmp(s + fileName->getLength() - 4, ".PDF"))) {
if (isAbsolutePath(s)) {
fileName = fileName->copy();
} else {
fileName = appendToPath(grabPath(doc->getFileName()->getCString()), s);
}
if (loadFile(fileName) != errNone) {
delete fileName;
return gFalse;
}
delete fileName;
displayPage(1, gFalse, gFalse, gTrue);
} else {
cmd = fileName->copy();
if ((params = ((LinkLaunch *)action)->getParams())) {
cmd->append(' ')->append(params);
}
if (globalParams->getLaunchCommand()) {
cmd->insert(0, ' ');
cmd->insert(0, globalParams->getLaunchCommand());
QProcess::startDetached(cmd->getCString());
} else {
msg = new GString("About to execute the command:\n");
msg->append(cmd);
if (QMessageBox::question(viewport, "PDF Launch Link",
msg->getCString(),
QMessageBox::Ok | QMessageBox::Cancel,
QMessageBox::Ok)
== QMessageBox::Ok) {
QProcess::startDetached(cmd->getCString());
}
delete msg;
}
delete cmd;
}
break;
// URI action
case actionURI:
QDesktopServices::openUrl(QUrl(((LinkURI *)action)->getURI()->getCString(),
QUrl::TolerantMode));
break;
// Named action
case actionNamed:
actionName = ((LinkNamed *)action)->getName();
if (!actionName->cmp("NextPage")) {
gotoNextPage(1, gTrue);
} else if (!actionName->cmp("PrevPage")) {
gotoPrevPage(1, gTrue, gFalse);
} else if (!actionName->cmp("FirstPage")) {
displayPage(1, gTrue, gFalse, gTrue);
} else if (!actionName->cmp("LastPage")) {
displayPage(doc->getNumPages(), gTrue, gFalse, gTrue);
} else if (!actionName->cmp("GoBack")) {
goBackward();
} else if (!actionName->cmp("GoForward")) {
goForward();
} else if (!actionName->cmp("Quit")) {
if (actionCbk) {
(*actionCbk)(actionCbkData, actionName->getCString());
}
} else {
error(errSyntaxError, -1,
"Unknown named action: '{0:t}'", actionName);
return gFalse;
}
break;
// Movie action
case actionMovie:
if (!(cmd = globalParams->getMovieCommand())) {
error(errConfig, -1, "No movieCommand defined in config file");
return gFalse;
}
if (((LinkMovie *)action)->hasAnnotRef()) {
doc->getXRef()->fetch(((LinkMovie *)action)->getAnnotRef()->num,
((LinkMovie *)action)->getAnnotRef()->gen,
&movieAnnot);
} else {
//~ need to use the correct page num here
doc->getCatalog()->getPage(tileMap->getFirstPage())->getAnnots(&obj1);
if (obj1.isArray()) {
for (i = 0; i < obj1.arrayGetLength(); ++i) {
if (obj1.arrayGet(i, &movieAnnot)->isDict()) {
if (movieAnnot.dictLookup("Subtype", &obj2)->isName("Movie")) {
obj2.free();
break;
}
obj2.free();
}
movieAnnot.free();
}
obj1.free();
}
}
if (movieAnnot.isDict()) {
if (movieAnnot.dictLookup("Movie", &obj1)->isDict()) {
if (obj1.dictLookup("F", &obj2)) {
if ((fileName = LinkAction::getFileSpecName(&obj2))) {
if (!isAbsolutePath(fileName->getCString())) {
fileName2 = appendToPath(
grabPath(doc->getFileName()->getCString()),
fileName->getCString());
delete fileName;
fileName = fileName2;
}
runCommand(cmd, fileName);
delete fileName;
}
obj2.free();
}
obj1.free();
}
}
movieAnnot.free();
break;
// unimplemented actions
case actionJavaScript:
case actionSubmitForm:
case actionHide:
return gFalse;
// unknown action type
case actionUnknown:
error(errSyntaxError, -1, "Unknown link action type: '{0:t}'",
((LinkUnknown *)action)->getAction());
return gFalse;
}
return gTrue;
}
QString QtPDFCore::getLinkInfo(LinkAction *action) {
LinkDest *dest;
GString *namedDest;
Ref pageRef;
int pg;
QString info;
if (action == lastLinkAction && !lastLinkActionInfo.isEmpty()) {
return lastLinkActionInfo;
}
switch (action->getKind()) {
case actionGoTo:
dest = NULL;
if ((dest = ((LinkGoTo *)action)->getDest())) {
dest = dest->copy();
} else if ((namedDest = ((LinkGoTo *)action)->getNamedDest())) {
dest = doc->findDest(namedDest);
}
pg = 0;
if (dest) {
if (dest->isPageRef()) {
pageRef = dest->getPageRef();
pg = doc->findPage(pageRef.num, pageRef.gen);
} else {
pg = dest->getPageNum();
}
delete dest;
}
if (pg) {
info = QString("[page ") + QString::number(pg) + QString("]");
} else {
info = "[internal]";
}
break;
case actionGoToR:
info = QString(((LinkGoToR *)action)->getFileName()->getCString());
break;
case actionLaunch:
info = QString(((LinkLaunch *)action)->getFileName()->getCString());
break;
case actionURI:
info = QString(((LinkURI *)action)->getURI()->getCString());
break;
case actionNamed:
info = QString(((LinkNamed *)action)->getName()->getCString());
break;
case actionMovie:
info = "[movie]";
break;
case actionJavaScript:
case actionSubmitForm:
case actionHide:
case actionUnknown:
default:
info = "[unknown]";
break;
}
lastLinkAction = action;
lastLinkActionInfo = info;
return info;
}
// Run a command, given a <cmdFmt> string with one '%s' in it, and an
// <arg> string to insert in place of the '%s'.
void QtPDFCore::runCommand(GString *cmdFmt, GString *arg) {
GString *cmd;
char *s;
if ((s = strstr(cmdFmt->getCString(), "%s"))) {
cmd = mungeURL(arg);
cmd->insert(0, cmdFmt->getCString(),
s - cmdFmt->getCString());
cmd->append(s + 2);
} else {
cmd = cmdFmt->copy();
}
QProcess::startDetached(cmd->getCString());
delete cmd;
}
// Escape any characters in a URL which might cause problems when
// calling system().
GString *QtPDFCore::mungeURL(GString *url) {
static const char *allowed = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789"
"-_.~/?:@&=+,#%";
GString *newURL;
char c;
char buf[4];
int i;
newURL = new GString();
for (i = 0; i < url->getLength(); ++i) {
c = url->getChar(i);
if (strchr(allowed, c)) {
newURL->append(c);
} else {
sprintf(buf, "%%%02x", c & 0xff);
newURL->append(buf);
}
}
return newURL;
}
//------------------------------------------------------------------------
// find
//------------------------------------------------------------------------
GBool QtPDFCore::find(char *s, GBool caseSensitive, GBool next,
GBool backward, GBool wholeWord, GBool onePageOnly) {
if (!PDFCore::find(s, caseSensitive, next,
backward, wholeWord, onePageOnly)) {
return gFalse;
}
#ifndef NO_TEXT_SELECT
copySelection(gFalse);
#endif
return gTrue;
}
// // dsC: paren_pattern
GBool QtPDFCore::findU(Unicode *u, int len, GBool caseSensitive,
GBool next, GBool backward,
GBool wholeWord, GBool onePageOnly, QVector<Unicode*>* us) {
if (!PDFCore::findU(u, len, caseSensitive, next,
backward, wholeWord, onePageOnly, us)) {
return gFalse;
}
#ifndef NO_TEXT_SELECT
copySelection(gFalse);
#endif
return gTrue;
}
//------------------------------------------------------------------------
// misc access
//------------------------------------------------------------------------
void QtPDFCore::setBusyCursor(GBool busy) {
if (busy) {
doSetCursor(Qt::WaitCursor);
} else {
doUnsetCursor();
}
}
void QtPDFCore::doSetCursor(const QCursor &cursor) {
#ifndef QT_NO_CURSOR
viewport->setCursor(cursor);
#endif
}
void QtPDFCore::doUnsetCursor() {
#ifndef QT_NO_CURSOR
viewport->unsetCursor();
#endif
}
void QtPDFCore::takeFocus() {
viewport->setFocus(Qt::OtherFocusReason);
}
QSize QtPDFCore::getBestSize() {
DisplayMode mode;
double zoomPercent;
int w, h, pg, rot;
if (!doc) {
//~ what should this return?
return QSize(612, 792);
}
mode = state->getDisplayMode();
pg = tileMap->getFirstPage();
rot = (state->getRotate() + doc->getPageRotate(pg)) % 360;
zoomPercent = state->getZoom();
if (zoomPercent < 0) {
zoomPercent = globalParams->getDefaultFitZoom();
if (zoomPercent <= 0) {
zoomPercent = (int)((100 * displayDpi) / 72.0 + 0.5);
if (zoomPercent < 100) {
zoomPercent = 100;
}
}
}
if (rot == 90 || rot == 270) {
w = (int)(doc->getPageCropHeight(pg) * 0.01 * zoomPercent + 0.5);
h = (int)(doc->getPageCropWidth(pg) * 0.01 * zoomPercent + 0.5);
} else {
w = (int)(doc->getPageCropWidth(pg) * 0.01 * zoomPercent + 0.5);
h = (int)(doc->getPageCropHeight(pg) * 0.01 * zoomPercent + 0.5);
}
if (mode == displayContinuous) {
w += QApplication::style()->pixelMetric(QStyle::PM_ScrollBarExtent);
h += tileMap->getContinuousPageSpacing();
} else if (mode == displaySideBySideContinuous) {
w = w * 2
+ tileMap->getHorizContinuousPageSpacing()
+ QApplication::style()->pixelMetric(QStyle::PM_ScrollBarExtent);
h += tileMap->getContinuousPageSpacing();
} else if (mode == displayHorizontalContinuous) {
w += tileMap->getHorizContinuousPageSpacing();
h += QApplication::style()->pixelMetric(QStyle::PM_ScrollBarExtent);
} else if (mode == displaySideBySideSingle) {
w = w * 2 + tileMap->getHorizContinuousPageSpacing();
}
//~ these additions are a kludge to make this work -- 2 pixels are
//~ padding in the QAbstractScrollArea; not sure where the rest go
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
w += 6;
h += 2;
#else
w += 10;
h += 4;
#endif
return QSize((int)(w / scaleFactor), (int)(h / scaleFactor));
}
//------------------------------------------------------------------------
// GUI code
//------------------------------------------------------------------------
void QtPDFCore::resizeEvent() {
setWindowSize((int)(viewport->width() * scaleFactor),
(int)(viewport->height() * scaleFactor));
}
void QtPDFCore::paintEvent(int x, int y, int w, int h) {
SplashBitmap *bitmap;
GBool wholeWindow;
QPainter painter(viewport);
wholeWindow = x == 0 && y == 0 &&
w == viewport->width() && h == viewport->height();
bitmap = getWindowBitmap(wholeWindow);
QImage image(bitmap->getDataPtr(), bitmap->getWidth(),
bitmap->getHeight(), QImage::Format_RGB888);
painter.drawImage(QRect(x, y, w, h), image,
QRect((int)(x * scaleFactor), (int)(y * scaleFactor),
(int)(w * scaleFactor), (int)(h * scaleFactor)));
if (paintDoneCbk) {
(*paintDoneCbk)(paintDoneCbkData, (bool)isBitmapFinished());
}
}
void QtPDFCore::scrollEvent() {
// avoid loops, e.g., scrollTo -> finishUpdate -> updateScrollbars ->
// hScrollbar.setValue -> scrollContentsBy -> scrollEvent -> scrollTo
if (inUpdateScrollbars) {
return;
}
scrollTo(hScrollBar->value(), vScrollBar->value());
}
void QtPDFCore::tick() {
PDFCore::tick();
}
void QtPDFCore::invalidate(int x, int y, int w, int h) {
viewport->update((int)(x / scaleFactor), (int)(y / scaleFactor),
(int)(w / scaleFactor), (int)(h / scaleFactor));
}
void QtPDFCore::updateScrollbars() {
int winW, winH, horizLimit, vertLimit, horizMax, vertMax;
bool vScrollBarVisible, hScrollBarVisible;
inUpdateScrollbars = gTrue;
winW = state->getWinW();
winH = state->getWinH();
tileMap->getScrollLimits(&horizLimit, &vertLimit);
if (horizLimit > winW) {
horizMax = horizLimit - winW;
} else {
horizMax = 0;
}
if (vertLimit > winH) {
vertMax = vertLimit - winH;
} else {
vertMax = 0;
}
// Problem case A: in fixed zoom, there is a case where the page
// just barely fits in the window; if the scrollbars are visible,
// they reduce the available window size enough that they are
// necessary, i.e., the scrollbars are only necessary if they're
// visible -- so check for that situation and force the scrollbars
// to be hidden.
// NB: {h,v}ScrollBar->isVisible() are unreliable at startup, so
// we compare the viewport size to the ScrollArea size (with
// some slack for margins)
vScrollBarVisible =
viewport->parentWidget()->width() - viewport->width() > 8;
hScrollBarVisible =
viewport->parentWidget()->height() - viewport->height() > 8;
if (state->getZoom() >= 0 &&
vScrollBarVisible &&
hScrollBarVisible &&
horizMax <= vScrollBar->width() &&
vertMax <= hScrollBar->height()) {
horizMax = 0;
vertMax = 0;
}
// Problem case B: in fit-to-width mode, with the vertical scrollbar
// visible, if the window is just tall enough to fit the page, then
// the vertical scrollbar will be hidden, resulting in a wider
// window, resulting in a taller page (because of fit-to-width),
// resulting in the scrollbar being unhidden, in an infinite loop --
// so always force the vertical scroll bar to be visible in
// fit-to-width mode (and in fit-to-page cases where the vertical
// scrollbar is potentially visible).
if (state->getZoom() == zoomWidth ||
(state->getZoom() == zoomPage &&
(state->getDisplayMode() == displayContinuous ||
state->getDisplayMode() == displaySideBySideContinuous))) {
if (vertMax == 0) {
vertMax = 1;
}
// Problem case C: same as case B, but for fit-to-height mode and
// the horizontal scrollbar.
} else if (state->getZoom() == zoomHeight ||
(state->getZoom() == zoomPage &&
state->getDisplayMode() == displayHorizontalContinuous)) {
if (horizMax == 0) {
horizMax = 1;
}
}
hScrollBar->setMaximum(horizMax);
hScrollBar->setPageStep(winW);
hScrollBar->setValue(state->getScrollX());
vScrollBar->setMaximum(vertMax);
vScrollBar->setPageStep(winH);
vScrollBar->setValue(state->getScrollY());
inUpdateScrollbars = gFalse;
}
GBool QtPDFCore::checkForNewFile() {
QDateTime newModTime;
if (doc->getFileName()) {
newModTime = QFileInfo(doc->getFileName()->getCString()).lastModified();
if (newModTime != modTime) {
modTime = newModTime;
return gTrue;
}
}
return gFalse;
}
void QtPDFCore::preLoad() {
if (preLoadCbk) {
(*preLoadCbk)(preLoadCbkData);
}
}
void QtPDFCore::postLoad() {
if (postLoadCbk) {
(*postLoadCbk)(postLoadCbkData);
}
}
//------------------------------------------------------------------------
// password dialog
//------------------------------------------------------------------------
GString *QtPDFCore::getPassword() {
QString s;
bool ok;
if (!showPasswordDialog) {
return NULL;
}
s = QInputDialog::getText(viewport, "PDF Password",
"This document requires a password",
QLineEdit::Password, "", &ok, Qt::Dialog);
if (ok) {
return new GString(s.toLocal8Bit().constData());
} else {
return NULL;
}
}
| [
"axiatropicsemantics@gmail.com"
] | axiatropicsemantics@gmail.com |
cda18fd3ae9bee2b965e8dc6be6e623ca848ed9c | 539c62dc1499eb840a45a706dacb2cc16f1fdb09 | /ChatScript/SRC/constructCode.cpp | 74c5548b6a3bd22bced8b16962fc96b511fb3945 | [
"MIT"
] | permissive | isabelbicalho/grace | bf882f0c9be7eb2111f9c0211fba1665fac08129 | f8ace8fc9c1962f71d9d7d1bace350a3ab1ba986 | refs/heads/master | 2021-01-11T08:17:17.193224 | 2016-11-10T22:51:54 | 2016-11-10T22:51:54 | 68,973,156 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,935 | cpp | #include "common.h"
int impliedIf = ALREADY_HANDLED; // testing context of an if
unsigned int withinLoop = 0;
static void TestIf(char* ptr,FunctionResult& result)
{ // word is a stream terminated by )
// if (%rand == 5 ) example of a comparison
// if (@14) {} nonempty factset
// if (^QuerySubject()) example of a call or if (!QuerySubject())
// if ($var) example of existence
// if ('_3 == 5) quoted matchvar
// if (1) what an else does
char* word1 = AllocateInverseString(NULL,MAX_BUFFER_SIZE);
char* word2 = AllocateInverseString(NULL,MAX_BUFFER_SIZE);
char op[MAX_WORD_SIZE];
int id;
impliedIf = 1;
if (trace & TRACE_OUTPUT && CheckTopicTrace()) Log(STDTRACETABLOG,(char*)"If ");
resume:
ptr = ReadCompiledWord(ptr,word1); // the var or whatever
bool invert = false;
if (*word1 == '!') // inverting, go get the actual
{
invert = true;
// get the real token
if (word1[1]) memmove(word1,word1+1,strlen(word1));
else ptr = ReadCompiledWord(ptr,word1);
}
ptr = ReadCompiledWord(ptr,op); // the test if any, or (for call or ) for closure or AND or OR
bool call = false;
if (*op == '(') // function call instead of a variable. but the function call might output a value which if not used, must be considered for failure
{
call = true;
ptr -= strlen(word1) + 3; // back up so output can see the fn name and space
ptr = FreshOutput(ptr,word2,result,OUTPUT_ONCE|OUTPUT_KEEPSET); // word2 hold output value // skip past closing paren
if (result & SUCCESSCODES) result = NOPROBLEM_BIT; // legal way to terminate the piece with success at any level
if (trace & TRACE_OUTPUT && CheckTopicTrace())
{
if (result & ENDCODES) id = Log(STDTRACETABLOG,(char*)"%c%s ",(invert) ? '!' : ' ',word1);
else if (*word1 == '1' && word1[1] == 0) id = Log(STDTRACETABLOG,(char*)"else ");
else id = Log(STDTRACETABLOG,(char*)"%c%s ",(invert) ? '!' : ' ',word1);
}
ptr = ReadCompiledWord(ptr,op); // find out what happens next after function call
if (!result && IsComparison(*op)) // didnt fail and followed by a relationship op, move output as though it was the variable
{
strcpy(word1,word2);
call = false; // proceed normally
}
else if (result != NOPROBLEM_BIT) {;} // failed
else if (!stricmp(word2,(char*)"0") || !stricmp(word2,(char*)"false")) result = FAILRULE_BIT; // treat 0 and false as failure along with actual failures
}
if (call){;} // call happened
else if (IsComparison(*op)) // a comparison test
{
char word1val[MAX_WORD_SIZE];
char word2val[MAX_WORD_SIZE];
ptr = ReadCompiledWord(ptr,word2);
result = HandleRelation(word1,op,word2,true,id,word1val,word2val);
ptr = ReadCompiledWord(ptr,op); // AND, OR, or )
}
else // existence of non-failure or any content
{
if (*word1 == SYSVAR_PREFIX || *word1 == '_' || *word1 == USERVAR_PREFIX || *word1 == '@' || *word1 == '?' || *word1 == '^')
{
char remap[MAX_WORD_SIZE];
strcpy(remap,word1); // for tracing
if (*word1 == '^' && IsDigit(word1[1])) strcpy(word1,callArgumentList[atoi(word1+1)+fnVarBase]); // simple function var, remap it
char* found;
if (word1[0] == LCLVARDATA_PREFIX && word1[1] == LCLVARDATA_PREFIX)
found = word1 + 2; // preevaled function variable
else if (*word1 == SYSVAR_PREFIX) found = SystemVariable(word1,NULL);
else if (*word1 == '_') found = wildcardCanonicalText[GetWildcardID(word1)];
else if (*word1 == USERVAR_PREFIX) found = GetUserVariable(word1);
else if (*word1 == '?') found = (tokenFlags & QUESTIONMARK) ? (char*) "1" : (char*) "";
else if (*word1 == '^' && word1[1] == USERVAR_PREFIX) // indirect var
{
found = GetUserVariable(word1+1);
found = GetUserVariable(found,true);
}
else if (*word1 == '^' && word1[1] == '^' && IsDigit(word1[2])) found = ""; // indirect function var
else if (*word1 == '^' && word1[1] == '_') found = ""; // indirect var
else if (*word1 == '^' && word1[1] == '\'' && word1[2] == '_') found = ""; // indirect var
else if (*word1 == '@') found = FACTSET_COUNT(GetSetID(word1)) ? (char*) "1" : (char*) "";
else found = word1;
if (trace & TRACE_OUTPUT && CheckTopicTrace())
{
char label[MAX_WORD_SIZE];
strcpy(label,word1);
if (*remap == '^') sprintf(label,"%s->%s",remap,word1);
if (!*found)
{
if (invert) id = Log(STDTRACELOG,(char*)"!%s (null) ",label);
else id = Log(STDTRACELOG,(char*)"%s (null) ",label);
}
else
{
if (invert) id = Log(STDTRACELOG,(char*)"!%s (%s) ",label,found);
else id = Log(STDTRACELOG,(char*)"%s (%s) ",label,found);
}
}
if (!*found) result = FAILRULE_BIT;
else result = NOPROBLEM_BIT;
}
else // its a constant of some kind
{
if (trace & TRACE_OUTPUT && CheckTopicTrace())
{
if (result & ENDCODES) id = Log(STDTRACELOG,(char*)"%c%s ",(invert) ? '!' : ' ',word1);
else if (*word1 == '1' && word1[1] == 0) id = Log(STDTRACELOG,(char*)"else ");
else id = Log(STDTRACELOG,(char*)"%c%s ",(invert) ? '!' : ' ',word1);
}
ptr -= strlen(word1) + 3; // back up to process the word and space
ptr = FreshOutput(ptr,word2,result,OUTPUT_ONCE|OUTPUT_KEEPSET) + 2; // returns on the closer and we skip to accel
}
}
if (invert) result = (result & ENDCODES) ? NOPROBLEM_BIT : FAILRULE_BIT;
if (*op == 'a') // AND - compiler validated it
{
if (!(result & ENDCODES))
{
if (trace & TRACE_OUTPUT && CheckTopicTrace()) id = Log(STDTRACELOG,(char*)" AND ");
goto resume;
// If he fails (result is one of ENDCODES), we fail
}
else
{
if (trace & TRACE_OUTPUT && CheckTopicTrace()) id = Log(STDTRACELOG,(char*)" ... ");
}
}
else if (*op == 'o') // OR
{
if (!(result & ENDCODES))
{
if (trace & TRACE_OUTPUT && CheckTopicTrace()) id = Log(STDTRACELOG,(char*)" ... ");
result = NOPROBLEM_BIT;
}
else
{
if (trace & TRACE_OUTPUT && CheckTopicTrace()) id = Log(STDTRACELOG,(char*)" OR ");
goto resume;
}
}
ReleaseInverseString(word1);
impliedIf = ALREADY_HANDLED;
}
char* HandleIf(char* ptr, char* buffer,FunctionResult& result)
{
// If looks like this: ^^if ( _0 == null ) 00m{ this is it } 00G else ( 1 ) 00q { this is not it } 004
// a nested if would be ^^if ( _0 == null ) 00m{ ^^if ( _0 == null ) 00m{ this is it } 00G else ( 1 ) 00q { this is not it } 004 } 00G else ( 1 ) 00q { this is not it } 004
// after a test condition is code to jump to next test branch when condition fails
// after { } chosen branch is offset to jump to end of if
ChangeDepth(1,"if");
bool executed = false;
while (ALWAYS) // do test conditions until match
{
char* endptr;
if (*ptr == '(') // old format - std if internals
{
endptr = strchr(ptr,'{') - 3; // offset to jump past pattern
}
else // new format, can use std if or pattern match
{
endptr = ptr + Decode(ptr);
ptr += 3; // skip jump to end of pattern and point to pattern
}
// Perform TEST condition
if (!strnicmp(ptr,(char*)"( pattern ",10)) // pattern if
{
int start = 0;
int end = 0;
unsigned int gap = 0;
wildcardIndex = 0;
bool uppercasem = false;
int whenmatched = 0;
bool failed = false;
if (!Match(ptr+10,0,start,(char*)"(",1,0,start,end,uppercasem,whenmatched,0,0)) failed = true; // skip paren and blank, returns start as the location for retry if appropriate
if (clearUnmarks) // remove transient global disables.
{
clearUnmarks = false;
for (int i = 1; i <= wordCount; ++i) unmarked[i] = 1;
}
ShowMatchResult((failed) ? FAILRULE_BIT : NOPROBLEM_BIT, ptr+10,NULL);
if (!failed)
{
if (trace & (TRACE_PATTERN|TRACE_MATCH|TRACE_SAMPLE) && CheckTopicTrace() ) // display the entire matching responder and maybe wildcard bindings
{
Log(STDTRACETABLOG,(char*)" ** Match: ");
if (wildcardIndex)
{
Log(STDTRACETABLOG,(char*)" Wildcards: (");
for (int i = 0; i < wildcardIndex; ++i)
{
if (*wildcardOriginalText[i]) Log(STDTRACELOG,(char*)"_%d=%s / %s (%d-%d) ",i,wildcardOriginalText[i],wildcardCanonicalText[i],wildcardPosition[i] & 0x0000ffff,wildcardPosition[i]>>16);
else Log(STDTRACELOG,(char*)"_%d= ",i);
}
}
Log(STDTRACELOG,(char*)"\r\n");
}
}
result = (failed) ? FAILRULE_BIT : NOPROBLEM_BIT;
}
else TestIf(ptr+2,result);
if (trace & TRACE_OUTPUT && CheckTopicTrace())
{
if (result & ENDCODES) Log(STDTRACELOG,(char*)"%s\r\n", "FAIL-if");
else Log(STDTRACELOG,(char*)"%s\r\n", "PASS-if");
}
ptr = endptr; // now after pattern, pointing to the skip data to go past body.
// perform SUCCESS branch and then end if
if (!(result & ENDCODES)) // IF test success - we choose this branch
{
executed = true;
ptr = Output(ptr+5,buffer,result); // skip accelerator-3 and space and { and space - returns on next useful token
ptr += Decode(ptr); // offset to end of if entirely
if (*(ptr-1) == 0) --ptr;// no space after?
break;
}
else
result = NOPROBLEM_BIT; // test result is not the IF result
// On fail, move to next test
ptr += Decode(ptr);
if (*(ptr-1) == 0)
{
--ptr;
break; // the if ended abruptly as a stream like in NOTRACE, and there is no space here
}
if (strncmp(ptr,(char*)"else ",5)) break; // not an ELSE, the IF is over.
ptr += 5; // skip over ELSE space, aiming at the ( of the next condition condition
}
if (executed && trace & TRACE_OUTPUT && CheckTopicTrace()) Log(STDTRACETABLOG,"End If\r\n");
ChangeDepth(-1,"if");
return ptr;
}
char* HandleLoop(char* ptr, char* buffer, FunctionResult &result)
{
unsigned int oldIterator = currentIterator;
currentIterator = 0;
char* buffer1 = AllocateInverseString(NULL,MAX_BUFFER_SIZE);
ptr = ReadCommandArg(ptr+2,buffer1,result)+2; // get the loop counter value and skip closing ) space
char* endofloop = ptr + (size_t) Decode(ptr);
int counter;
if (*buffer1 == '@')
{
int set = GetSetID(buffer1);
if (set < 0)
{
result = FAILRULE_BIT; // illegal id
ReleaseInverseString(buffer1);
return ptr;
}
counter = FACTSET_COUNT(set);
}
else counter = atoi(buffer1);
ReleaseInverseString(buffer1);
if (result & ENDCODES) return endofloop;
++withinLoop;
ptr += 5; // skip jump + space + { + space
char* value = GetUserVariable((char*)"$cs_looplimit");
int limit = atoi(value);
if (limit == 0) limit = 1000;
if (counter > limit || counter < 0) counter = limit; // LIMITED
ChangeDepth(1,(char*)"HandleLoop");
while (counter-- > 0)
{
if (trace & TRACE_OUTPUT && CheckTopicTrace()) Log(STDTRACETABLOG,(char*)"loop(%d)\r\n",counter+1);
FunctionResult result1;
Output(ptr,buffer,result1,OUTPUT_LOOP);
buffer += strlen(buffer);
if (result1 & ENDCODES)
{
if (result1 == NEXTLOOP_BIT) continue;
result = (FunctionResult)( (result1 & (ENDRULE_BIT | FAILRULE_BIT)) ? NOPROBLEM_BIT : (result1 & ENDCODES) ); // rule level terminates only the loop
if (result == FAILLOOP_BIT) result = FAILRULE_BIT; // propagate failure outside of loop
if (result == ENDLOOP_BIT) result = NOPROBLEM_BIT; // propagate ok outside of loop
break;// potential failure if didnt add anything to buffer
}
}
if (trace & TRACE_OUTPUT && CheckTopicTrace()) Log(STDTRACETABLOG,(char*)"end of loop\r\n");
ChangeDepth(-1,(char*)"HandleLoop");
--withinLoop;
currentIterator = oldIterator;
return endofloop;
}
FunctionResult HandleRelation(char* word1,char* op, char* word2,bool output,int& id, char* word1val, char* word2val)
{ // word1 and word2 are RAW, ready to be evaluated.
*word1val = 0;
*word2val = 0;
char* val1 = AllocateInverseString(NULL,MAX_BUFFER_SIZE);
char* val2 = AllocateInverseString(NULL,MAX_BUFFER_SIZE);
WORDP D;
WORDP D1;
WORDP D2;
int64 v1 = 0;
int64 v2 = 0;
FunctionResult result,val1Result;
FreshOutput(word1,val1,result,OUTPUT_ONCE|OUTPUT_KEEPSET|OUTPUT_NOCOMMANUMBER); // 1st arg
val1Result = result;
if (word2 && *word2) FreshOutput(word2,val2,result,OUTPUT_ONCE|OUTPUT_KEEPSET|OUTPUT_NOCOMMANUMBER); // 2nd arg
result = FAILRULE_BIT;
if (!stricmp(val1,(char*)"null") ) *val1 = 0;
if (!stricmp(val2,(char*)"null") ) *val2 = 0;
if (!op)
{
if (val1Result & ENDCODES); // explicitly failed
else if (*val1) result = NOPROBLEM_BIT; // has some value
}
else if (*op == '?' || op[1] == '?') // ? and !?
{
if (*word1 == '\'') ++word1; // ignore the quote since we are doing positional
if (*word1 == '_') // try for precomputed match from memorization
{
unsigned int index = GetWildcardID(word1);
index = WILDCARD_START(wildcardPosition[index]);
D = FindWord(val2);
if (index && D)
{
int junk;
if (GetNextSpot(D,index-1,junk,junk) == index) result = NOPROBLEM_BIT; // otherwise failed and we would have known
}
char* was = wildcardOriginalText[GetWildcardID(word1)];
if (result == FAILRULE_BIT && (!index || strchr(was,'_') || strchr(was,' '))) // laborious match try now
{
D1 = FindWord(val1);
if (D1 && D)
{
NextInferMark();
if (SetContains(MakeMeaning(D),MakeMeaning(D1))) result = NOPROBLEM_BIT;
}
}
if (*op == '!') result = (result != NOPROBLEM_BIT) ? NOPROBLEM_BIT : FAILRULE_BIT;
}
else // laborious.
{
D1 = FindWord(val1);
D2 = FindWord(val2);
if (D1 && D2)
{
NextInferMark();
if (SetContains(MakeMeaning(D2),MakeMeaning(D1))) result = NOPROBLEM_BIT;
}
if (result != NOPROBLEM_BIT)
{
char* verb = GetInfinitive(val1,true);
if (verb && stricmp(verb,val1))
{
D1 = FindWord(verb);
if (D1 && D2)
{
NextInferMark();
if (SetContains(MakeMeaning(D2),MakeMeaning(D1))) result = NOPROBLEM_BIT;
}
}
}
if (result != NOPROBLEM_BIT)
{
char* noun = GetSingularNoun(val1,true,true);
if (noun && stricmp(noun,val1))
{
D1 = FindWord(noun);
if (D1 && D2)
{
NextInferMark();
if (SetContains(MakeMeaning(D2),MakeMeaning(D1))) result = NOPROBLEM_BIT;
}
}
}
if (*op == '!') result = (result != NOPROBLEM_BIT) ? NOPROBLEM_BIT : FAILRULE_BIT;
}
}
else // boolean tests
{
// convert null to numeric operator for < or > -- but not for equality
if (!*val1 && IsDigit(*val2) && IsNumber(val2) && (*op == '<' || *op == '>')) strcpy(val1,(char*)"0");
else if (!*val2 && IsDigit(*val1) && IsNumber(val1) && (*op == '<' || *op == '>')) strcpy(val2,(char*)"0");
// treat #123 as string but +21545 and -12345 as numbers
if (*val1 == '#' || !IsDigitWord(val1,true) || *val2 == '#' || !IsDigitWord(val2,true)) // non-numeric string compare - bug, can be confused if digit starts text string
{
char* arg1 = val1;
char* arg2 = val2;
if (*arg1 == '"')
{
size_t len = strlen(arg1);
if (arg1[len-1] == '"') // remove STRING markers
{
arg1[len-1] = 0;
++arg1;
}
}
if (*arg2 == '"')
{
size_t len = strlen(arg2);
if (arg2[len-1] == '"') // remove STRING markers
{
arg2[len-1] = 0;
++arg2;
}
}
if (*op == '!') result = (stricmp(arg1,arg2)) ? NOPROBLEM_BIT : FAILRULE_BIT;
else if (*op == '=') result = (!stricmp(arg1,arg2)) ? NOPROBLEM_BIT: FAILRULE_BIT;
else result = FAILRULE_BIT;
}
// handle float ops
else if ((strchr(val1,'.') && val1[1]) || (strchr(val2,'.') && val2[1])) // at least one arg is float
{
char* comma = 0;
while ((comma = strchr(val1,','))) memmove(comma,comma+1,strlen(comma+1)); // remove embedded commas
while ((comma = strchr(val2,','))) memmove(comma,comma+1,strlen(comma+1)); // remove embedded commas
float v1f = (float) atof(val1);
float v2f = (float) atof(val2);
if (*op == '=') result = (v1f == v2f) ? NOPROBLEM_BIT : FAILRULE_BIT;
else if (*op == '<')
{
if (!op[1]) result = (v1f < v2f) ? NOPROBLEM_BIT : FAILRULE_BIT;
else result = (v1f <= v2f) ? NOPROBLEM_BIT : FAILRULE_BIT;
}
else if (*op == '>')
{
if (!op[1]) result = (v1f > v2f) ? NOPROBLEM_BIT : FAILRULE_BIT;
else result = (v1f >= v2f) ? NOPROBLEM_BIT : FAILRULE_BIT;
}
else if (*op == '!') result = (v1f != v2f) ? NOPROBLEM_BIT : FAILRULE_BIT;
else result = FAILRULE_BIT;
}
else // int compare
{
char* comma = 0; // pretty number?
while ((comma = strchr(val1,','))) memmove(comma,comma+1,strlen(comma+1));
while ((comma = strchr(val2,','))) memmove(comma,comma+1,strlen(comma+1));
ReadInt64(val1,v1);
ReadInt64(val2,v2);
if (strchr(val1,',') && strchr(val2,',')) // comma numbers
{
size_t len1 = strlen(val1);
size_t len2 = strlen(val2);
if (len1 != len2) result = FAILRULE_BIT;
else if (strcmp(val1,val2)) result = FAILRULE_BIT;
else result = NOPROBLEM_BIT;
if (*op == '!') result = (result == NOPROBLEM_BIT) ? FAILRULE_BIT : NOPROBLEM_BIT;
else if (*op != '=') ReportBug((char*)"Op not implemented for comma numbers %s",op)
}
else if (*op == '=') result = (v1 == v2) ? NOPROBLEM_BIT : FAILRULE_BIT;
else if (*op == '<')
{
if (!op[1]) result = (v1 < v2) ? NOPROBLEM_BIT : FAILRULE_BIT;
else result = (v1 <= v2) ? NOPROBLEM_BIT : FAILRULE_BIT;
}
else if (*op == '>')
{
if (!op[1]) result = (v1 > v2) ? NOPROBLEM_BIT : FAILRULE_BIT;
else result = (v1 >= v2) ? NOPROBLEM_BIT : FAILRULE_BIT;
}
else if (*op == '!') result = (v1 != v2) ? NOPROBLEM_BIT : FAILRULE_BIT;
else if (*op == '&') result = (v1 & v2) ? NOPROBLEM_BIT : FAILRULE_BIT;
else result = FAILRULE_BIT;
}
}
if (trace & TRACE_OUTPUT && output && CheckTopicTrace())
{
char x[MAX_WORD_SIZE];
char y[MAX_WORD_SIZE];
*x = *y = 0;
if (*op == '&')
{
#ifdef WIN32
sprintf(x,(char*)"0x%016I64x",v1);
sprintf(y,(char*)"0x%016I64x",v2);
#else
sprintf(x,(char*)"0x%016llx",v1);
sprintf(y,(char*)"0x%016llx",v2);
#endif
}
if (!stricmp(word1,val1))
{
if (*word1) Log(STDTRACELOG,(char*)"%s %s ",(*x) ? x : word1,op); // no need to show value
else Log(STDTRACELOG,(char*)"null %s ",op);
}
else if (!*val1) Log(STDTRACELOG,(char*)"%s(null) %s ",word1,op);
else if (*op == '&') Log(STDTRACELOG,(char*)"%s(%s) %s ",word1,x,op);
else Log(STDTRACELOG,(char*)"%s(%s) %s ",word1,val1,op);
if (word2 && !strcmp(word2,val2))
{
if (*val2) id = Log(STDTRACELOG,(char*)" %s ",(*y) ? y : word2); // no need to show value
else id = Log(STDTRACELOG,(char*)" null ");
}
else if (!*val2) id = Log(STDTRACELOG,(char*)" %s(null) ",word2);
else if (*op == '&') id = Log(STDTRACELOG,(char*)" %s(%s) ",word2,y);
else id = Log(STDTRACELOG,(char*)" %s(%s) ",word2,val2);
}
else if (trace & TRACE_PATTERN && !output && CheckTopicTrace())
{
if (strlen(val1) >=( MAX_WORD_SIZE-1)) val1[MAX_WORD_SIZE-1] = 0;
if (strlen(val2) >=( MAX_WORD_SIZE-1)) val2[MAX_WORD_SIZE-1] = 0;
strcpy(word1val,val1);
strcpy(word2val,val2);
}
ReleaseInverseString(val1);
return result;
}
| [
"isabel_bicalho@yahoo.com.br"
] | isabel_bicalho@yahoo.com.br |
9b16dd6706ce062e916b0d071c9b60296a7e487b | cd8724e822bfa4a04ac61c9dadfa05c7bcadd09a | /lib_test/eva/eva_file.cpp | 16ef2b089a8d1b3ca03d74532e98f6db6db57de4 | [] | no_license | zhangzma/ctest | 49ad421308cda8335d794cb653fb6053204e51d2 | fdfceb48d91d843574c1b0844cc97f68d7f228a9 | refs/heads/master | 2020-12-24T10:11:12.840970 | 2017-02-08T06:46:39 | 2017-02-08T06:46:39 | 73,243,951 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,697 | cpp | // eva_file.cpp
#include "eva_std.hpp"
#include <string>
#include <unistd.h>
#include <cstdio>
#include <cstring>
using namespace std;
namespace eva
{
File::File()
{
m_pFile = NULL;
}
File::File(const char *file_name)
{
m_pFile = NULL;
m_strFileName = file_name;
}
File::~File()
{
if (m_pFile != NULL) {
fclose(m_pFile);
m_pFile = NULL;
}
}
bool File::set_file_name(const char *file_name)
{
if (file_name) {
m_strFileName = file_name;
return true;
}
return false;
}
eva::String File::get_file_name() const
{
return m_strFileName;
}
/**
* 打开文件
* @param nMode -- 二进制格式
* @return
*/
bool File::open(int nMode)
{
bool bBinary = false;
bool bRead = false;
bool bWrite = false;
bool bCreate = false;
bool bEmpty = false;
std::string mode;
if (nMode & EVA_IO_BINARY) {
bBinary = true;
}
if (nMode & EVA_IO_CREATE) {
bCreate = true;
}
if (nMode & EVA_IO_TRUNCATE) {
bEmpty = true;
}
if (nMode & EVA_IO_READONLY) {
bRead = true;
}
if (nMode & EVA_IO_WRITEONLY) {
bWrite = true;
}
if (!bWrite && bRead) {
mode = "r";
}
else if (!bRead && bWrite) {
mode = "w";
}
else {
if (!bCreate) {
mode = "r+";
}
else {
if (bEmpty) {
mode = "w+";
}
else {
mode = "a+";
}
}
}
if (bBinary) {
mode += "b";
}
return this->open(mode.c_str());
}
bool File::open(const char *mode)
{
m_pFile = fopen(m_strFileName.GetBuf(), mode);
if (m_pFile == NULL) {
return false;
}
return true;
}
void File::close()
{
if (m_pFile != NULL) {
fclose(m_pFile);
m_pFile = NULL;
}
}
bool File::is_exist()
{
FILE * pfile = fopen(m_strFileName.GetBuf(), "r+");
if (pfile != NULL) {
fclose(pfile);
return true;
}
else {
return false;
}
// return (access(m_strFileName.c_str(), 0) != -1);
}
int File::get_length()
{
int len = 0;
int oldPos = 0;
if (m_pFile != NULL) {
oldPos = ftell(m_pFile);
if (fseek(m_pFile, 0, SEEK_END) != 0) {
return -1;
}
len = ftell(m_pFile);
fseek(m_pFile, oldPos, SEEK_SET);
}
else {
// try {
open("r");
if (m_pFile == NULL) {
return -1;
}
if (fseek(m_pFile, 0, SEEK_END) != NULL) {
close();
return -1;
}
len = ftell(m_pFile);
// } catch (...) {
// XXX: Deal the exception.
// }
m_pFile = NULL;
}
return len;
}
int File::read(char *pbuf, int count)
{
if (m_pFile == NULL) {
return -1;
}
size_t ret = fread(pbuf, 1, count, m_pFile);
return (int)ret;
}
int File::write(const char *pbuf, int count)
{
if (m_pFile == NULL) {
return -1;
}
size_t ret = fwrite(pbuf, 1, count, m_pFile);
return (int)ret;
}
bool File::read_line(char *pbuf, int count)
{
if (m_pFile) {
char *ret = fgets(pbuf, count, m_pFile);
return (ret != NULL);
}
return false;
}
void File::write_line(const char *pbuf)
{
if (m_pFile != NULL) {
fputs(pbuf, m_pFile);
fputs("\n", m_pFile);
}
}
bool File::seek(int offset, int from)
{
int mode;
bool from_ok = true;
switch (from) {
case EVA_IO_BEGIN:
mode = SEEK_SET;
break;
case EVA_IO_END:
mode = SEEK_END;
break;
case EVA_IO_CURRENT:
mode = SEEK_CUR;
break;
default:
from_ok = false;
break;
}
if (from_ok && !fseek(m_pFile, offset, mode)) {
return true;
}
else {
return false;
}
}
void File::seek_to_begin()
{
rewind(m_pFile);
}
void File::seek_to_end()
{
seek(0, EVA_IO_END);
}
bool File::rename(const char *new_name)
{
this->close();
if (::rename(m_strFileName.GetBuf(), new_name) == 0) {
m_strFileName = new_name;
return true;
}
return false;
}
bool File::remove()
{
this->close();
if (::unlink(m_strFileName.GetBuf()) == 0) {
m_strFileName.Empty();
return true;
}
return false;
}
}
| [
"zhaingbo@foxmail.com"
] | zhaingbo@foxmail.com |
e546e2ce8e0b8b7580fafa78443ea0f73c6cbafb | 74bdc90df12ffe6d885806bc7cd98b1056430c00 | /2회차/base/buzzer.ino | d6c125a6f65cec592847ffef2aaaa768bf0cbcdb | [] | no_license | manisjun/SeoHyun_IOT_2020 | f2d45aaa0f71a2198d50cd2f87c415db6bd6a37f | 73d7ec96e270cb7b85263c061cb64d71a3280ed6 | refs/heads/master | 2022-11-19T08:42:39.385496 | 2020-07-22T08:25:42 | 2020-07-22T08:25:42 | 278,222,587 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 599 | ino | #include "pitches.h"
#define BUZERPIN 6
int melody[] = {
NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};
// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
4, 8, 8, 4, 4, 4, 4, 4
};
void Buzzer_setup() {
}
void Buzzer_loop() {
melody_call();
}
void melody_call(){
for (int thisNote = 0; thisNote < 8; thisNote++) {
int noteDuration = 1000 / noteDurations[thisNote];
tone(BUZERPIN, melody[thisNote], noteDuration);
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
noTone(BUZERPIN);
}
}
| [
"manisjun28@gmail.com"
] | manisjun28@gmail.com |
dab2bf5f1826fd3976112ba59a28d5af0959ca1b | c51febc209233a9160f41913d895415704d2391f | /library/ATF/tagACTCTXA.hpp | 66ae58d60f4f658f21303bf732a055e97702172c | [
"MIT"
] | permissive | roussukke/Yorozuya | 81f81e5e759ecae02c793e65d6c3acc504091bc3 | d9a44592b0714da1aebf492b64fdcb3fa072afe5 | refs/heads/master | 2023-07-08T03:23:00.584855 | 2023-06-29T08:20:25 | 2023-06-29T08:20:25 | 463,330,454 | 0 | 0 | MIT | 2022-02-24T23:15:01 | 2022-02-24T23:15:00 | null | UTF-8 | C++ | false | false | 570 | hpp | // This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <HINSTANCE__.hpp>
START_ATF_NAMESPACE
struct tagACTCTXA
{
unsigned int cbSize;
unsigned int dwFlags;
const char *lpSource;
unsigned __int16 wProcessorArchitecture;
unsigned __int16 wLangId;
const char *lpAssemblyDirectory;
const char *lpResourceName;
const char *lpApplicationName;
HINSTANCE__ *hModule;
};
END_ATF_NAMESPACE
| [
"b1ll.cipher@yandex.ru"
] | b1ll.cipher@yandex.ru |
1c4561cecd4901b94c8735614318742f9e20e7c1 | 7bbc63a7a74680dc2e532e65c5f6d6a272687f13 | /include/ros_sec/SEC/mainGraph.h | d01c0d8ef69f52393c8c3a074d24c454b0727fd4 | [
"BSD-2-Clause"
] | permissive | zengzhen/ros_sec | 5f704cbafe9c898df061154d712f669caa73d9f1 | 110d07c3a786262b874386b266fc845c24fc43ae | refs/heads/master | 2021-01-23T09:29:06.010616 | 2014-08-28T01:28:07 | 2014-08-28T01:28:07 | 22,965,715 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,744 | h | /**
* \file mainGraph.h
* \author Zhen Zeng (zengzhen@umich.edu)
* \brief main graph of manipulation action
*/
#ifndef MAINGRAPH_H
#define MAINGRAPH_H
#include "ros_sec/typeDef.h"
namespace TableObject{
class mainGraph {
public:
/** \brief Constructor
* \param[in] start_index index of starting frame of processed video
*/
mainGraph(int start_index);
/** Add initial relational graph for the 1st frame
* \param[in] relation digit representing the relation (0: untouch, 2: touch)
*/
void addInitialRelationalGraph(int relation);
/** Add relational graph for frames after the 1st frame
* \param[in] relation digit representing the relation (0: untouch, 2: touch)
*/
void addRelationalGraph(int relation);
/** Compare relational graphs between frame_index and frame_index-1
* \param[in] frame_index the index of the frame to be compared
*/
bool compareRelationGraph(int frame_index);
/** Accessor main graph
*/
std::vector<graph> getMainGraph();
/** Display main graph in terminal
*/
void displayMainGraph();
/** Record main graph in file
* \param[in] file_name file to be written to
*/
void recordMainGraph(std::string file_name);
private:
std::vector<graph> _graph;
std::vector<int> _cur_graph; //to store relational graph of current frame for comparison
std::vector<int> _pre_graph; //to store relational graph of previous frame for comparison
};
}
#endif // MAINGRAPH_H | [
"kuipers@umich.edu"
] | kuipers@umich.edu |
159f955b73f361ffb34827a91f102a9053da1dc4 | 62a7d30053e7640ef770e041f65b249d101c9757 | /XVII Open Cup named after E.V. Pankratiev. XXI Ural Championship/E.cpp | d274101c8629f9160196af169dd274ad9f5eb02d | [] | no_license | wcysai/Calabash | 66e0137fd59d5f909e4a0cab940e3e464e0641d0 | 9527fa7ffa7e30e245c2d224bb2fb77a03600ac2 | refs/heads/master | 2022-05-15T13:11:31.904976 | 2022-04-11T01:22:50 | 2022-04-11T01:22:50 | 148,618,062 | 76 | 16 | null | 2019-11-07T05:27:40 | 2018-09-13T09:53:04 | C++ | UTF-8 | C++ | false | false | 3,452 | cpp | #include<bits/stdc++.h>
#define MAXN 1000005
#define INF 1000000000
#define MOD 1000000007
#define F first
#define S second
#define dec asdkoasdoa
#define div doskdoa
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
int lb,rb,len;
int cnt[10];
int mult;
int add;
int dec;
int div;
int operand;//0: = 1:< 2:> 3:!= 4:<= 5:>=
char str[3];
mt19937 wcy(time(NULL));
string op[6]=
{
"=",
"<",
">",
"!=",
"<=",
">=",
};
string pool[6][6]=
{
"=","<",">","!=","<=",">=",
"4","+","-","(","(",")",
"0","/","/","/","8","+",
"2","3","4","5","-",")",
"+","-","*","/","1","9",
"6","7","+","-","(",")",
};
char ask(int x)
{
printf("%d\n",x); fflush(stdout);
scanf("%s",str);
len++;
return str[0];
}
void get_relation()
{
printf("1\n"); fflush(stdout);
scanf("%s",str);
if(str[0]=='=') operand=0,len++;
else if(str[0]=='!') operand=3,len+=2;
else if(strlen(str)==2) operand=(str[0]=='<'?4:5),len+=2;
else operand=(str[0]=='<'?1:2),len++;
}
void analyze(char ch)
{
if(ch=='(') lb++;
else if(ch==')') rb++;
else if(ch>='0'&&ch<='9') cnt[ch-'0']++;
else if(ch=='+') add++;
else if(ch=='-') dec++;
else if(ch=='*') mult++;
else if(ch=='/') div++;
}
void get_type(int x)
{
char ch=ask(x);
analyze(ch);
}
int get_nonzero()
{
for(int i=1;i<=9;i++) if(cnt[i]) {cnt[i]--; return i;}
assert(0);//should not reach here
}
int get_any()
{
for(int i=0;i<=9;i++) if(cnt[i]) {cnt[i]--; return i;}
assert(0);//should not reach here
}
string get_allnum()
{
string str="";
int x=get_nonzero();
str+=(char)('0'+x);
for(int i=0;i<=9;i++)
for(int j=0;j<cnt[i];j++)
str+=(char)('0'+i);
return str;
}
string construct_any()
{
string str="";
int x=get_nonzero();
str+=(char)('0'+x);
while(div)
{
int x=get_nonzero();
str+='/';
str+=(char)('0'+x);
div--;
}
while(mult)
{
int x=get_any();
str+='*';
str+=(char)('0'+x);
mult--;
}
while(add)
{
int x=get_any();
str+='+';
str+=(char)('0'+x);
add--;
}
assert(dec>0);
while(dec>1)
{
int x=get_any();
str+='-';
str+=(char)('0'+x);
dec--;
}
str+='-';
str+=get_allnum();
assert(lb==rb);
while(lb) {lb--; rb--; str='('+str+')';}
return str;
}
string construct_eq()
{
cnt[0]-=2;
lb--; rb--; mult--;
string str=construct_any();
str='('+str+')'+'*'+'0';
return str;
}
string construct_neq()
{
cnt[0]--; cnt[2]--;
lb--; rb--; mult--;
string str=construct_any();
str='('+str+')'+'*'+'0';
return str;
}
string construct_ans()
{
if(operand==0||operand==4||operand==5)
{
string str=construct_eq();
str=str+op[operand]+'0';
return str;
}
else
{
string str=construct_neq();
if(operand==2) str='2'+op[operand]+str;
else str=str+op[operand]+'2';
return str;
}
}
int main()
{
get_relation();
int tot=301;
for(int i=0;i<300;i++) get_type(4);
while(lb<rb) {get_type(2); tot++; assert(tot<=1000);}
while(cnt[0]<2) {get_type(3); tot++; assert(tot<=1000);}
while(!mult) {get_type(5); tot++; assert(tot<=1000);}
string s=construct_ans();
assert((int)s.size()==len);
cout<<"0 "<<s<<endl;
return 0;
}
| [
"wcysai@foxmail.com"
] | wcysai@foxmail.com |
e48bc81f9f53626dbed7376bc3bb0be68dba9fa5 | 1c44df508a04e16aa68d21f7711f92a2934c7b6c | /src/Bull/Core/Time/Win32/DateImpl.hpp | d202e344004f7ea889ff0f44700a2307c7af582f | [] | no_license | reyqn/Bull | b75983f46608f464d594ed500867d1ae88fa30f4 | bcd570695abbdd2ca613cf53aeb8a6558639b857 | refs/heads/master | 2021-01-12T18:14:14.409825 | 2016-10-18T20:51:55 | 2016-10-18T20:51:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 380 | hpp | #ifndef Bull_DateImpl_hpp
#define Bull_DateImpl_hpp
#include <Bull/Core/Time/Date.hpp>
namespace Bull
{
namespace prv
{
struct DateImpl
{
/*! \brief Get the current date
*
* \return Return the current date
*
*/
static Date now();
};
}
}
#endif // Bull_DateImpl_hpp
| [
"benjber69@gmail.com"
] | benjber69@gmail.com |
10a898ea6ee1cef9fd2e41d8b75fc237081bab44 | 52542a6fb85c8c31d5af8fc3b27e64081dba573e | /include/system/Signal_s.h | 4f32ebe08f0de123fe481d41b52ff83b091927e8 | [] | no_license | fxlghb/Foundation | 242b3f807071a0e396d0befa294cf5a7beff29bd | a5ff03acb0212a8b9d4622f33b43d1f4149f0f7d | refs/heads/master | 2020-03-31T08:30:24.200058 | 2019-02-20T14:36:12 | 2019-02-20T14:36:12 | 152,060,249 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 6,079 | h |
#define SIGNAL_NODE MACRO_JOIN(TSigNode,SIGNAL_NUMBER)
#define SIGNAL_SIGNAL MACRO_JOIN(TSignal,SIGNAL_NUMBER)
#define SIGNAL_SIGNAL_S MACRO_JOIN(SIGNAL_SIGNAL, _S)
#define SIGNAL_NODE_EMPTY 0x00
#define SIGNAL_NODE_NEW 0x01
#define SIGNAL_NODE_DELETE 0x02
#define SIGNAL_NODE_NORMAL 0x03
#ifdef WIN32
#define INLINE
#else
#define INLINE inline
#endif
#include <vector>
#include "Foundation/Mutex.h"
#include "Foundation/Semaphore.h"
#include "Foundation/Object.h"
#include <string.h>
template <SIGNAL_CLASS_TYPES> class SIGNAL_NODE
{
typedef void (CObject::*SigProc)(SIGNAL_TYPES);
public:
SIGNAL_NODE( )
:m_pObj(NULL),m_pProc(NULL),m_Status(SIGNAL_NODE_EMPTY)
{
};
INLINE void operator()(SIGNAL_TYPE_ARGS)
{
(m_pObj->*m_pProc)(SIGNAL_ARGS);
};
CObject * m_pObj;
SigProc m_pProc;
int m_Status; //added by jili,0x00:Empty; 0x01:New; 0x02:Delete;0x03:Normal
};
template <SIGNAL_CLASS_TYPES> class SIGNAL_SIGNAL
{
public:
typedef void (CObject::*SigProc)(SIGNAL_TYPES);
typedef SIGNAL_NODE < SIGNAL_TYPES > MySignalNode;
private:
int m_nMaxSlots;
std::vector < MySignalNode > m_Vector;
CMutex m_Mutex;
int calcSize()
{
int i, ret;
for(i = 0, ret = 0; i < m_nMaxSlots; i++)
if(m_Vector[i].m_Status == SIGNAL_NODE_NORMAL)
ret ++;
return ret;
}
public:
SIGNAL_SIGNAL(int MaxSlots) :
m_nMaxSlots(MaxSlots), m_Vector(MaxSlots)
{
if(MaxSlots < 4) {
m_nMaxSlots = 4;
m_Vector.resize(m_nMaxSlots);
}
};
~SIGNAL_SIGNAL()
{
};
int Attach(void * pObj, SigProc pProc)
{
int i, ret = -1;
m_Mutex.Enter();
for(i = 0; i < m_nMaxSlots; i++)
{
if(m_Vector[i].m_pObj == pObj
//&& m_Vector[i].m_pProc == pProc
&& (memcmp(&m_Vector[i].m_pProc, &pProc, sizeof(SigProc)) == 0) //
&& m_Vector[i].m_Status == SIGNAL_NODE_NORMAL)
{
ret = -2;
break;
}
if(m_Vector[i].m_Status == SIGNAL_NODE_EMPTY)
{
m_Vector[i].m_pObj = (CObject*)pObj;
m_Vector[i].m_pProc = pProc;
m_Vector[i].m_Status = SIGNAL_NODE_NORMAL;
ret = calcSize();
break;
}
}
m_Mutex.Leave();
return ret;
};
int Detach(void * pObj, SigProc pProc)
{
int i, ret = -1;
m_Mutex.Enter();
for(i = 0; i < m_nMaxSlots; i++)
{
if(m_Vector[i].m_pObj == pObj
//&& m_Vector[i].m_pProc == pProc )
&& (memcmp(&m_Vector[i].m_pProc, &pProc, sizeof(SigProc)) == 0)) //__TCS__
{
m_Vector[i].m_Status = SIGNAL_NODE_EMPTY;
ret = calcSize();
break;
}
};
m_Mutex.Leave();
return ret;
};
int IsAttached(void * pObj, SigProc pProc)
{
int i , ret = -1;
m_Mutex.Enter();
for(i = 0; i < m_nMaxSlots; i++)
{
if(m_Vector[i].m_pObj == pObj
//&& m_Vector[i].m_pProc == pProc
&& (memcmp(&m_Vector[i].m_pProc, &pProc, sizeof(SigProc)) == 0) //__TCS__
&& m_Vector[i].m_Status == SIGNAL_NODE_NORMAL)
{
ret = calcSize();
break;
}
}
m_Mutex.Leave();
return ret;
};
void operator()(SIGNAL_TYPE_ARGS)
{
int i;
for(i=0; i<m_nMaxSlots; i++)
{
if(m_Vector[i].m_Status == SIGNAL_NODE_NORMAL) //¿É²Ù×÷״̬
{
m_Vector[i](SIGNAL_ARGS); //call back
}
}
};
};
template <SIGNAL_CLASS_TYPES> class SIGNAL_SIGNAL_S
{
public:
typedef void (CObject::*SigProc)(SIGNAL_TYPES);
typedef SIGNAL_NODE < SIGNAL_TYPES > MySignalNode;
private:
int m_nMaxSlots;
std::vector < MySignalNode > m_Vector;
CMutex m_Mutex;
bool m_bCalled;
bool m_bSempore;
CSemaphore m_sem;
int calcSize()
{
int i, ret;
for(i = 0, ret = 0; i < m_nMaxSlots; i++)
if(m_Vector[i].m_Status == SIGNAL_NODE_NORMAL)
ret ++;
return ret;
}
public:
SIGNAL_SIGNAL_S(int MaxSlots) :
m_nMaxSlots(MaxSlots), m_Vector(MaxSlots), m_bCalled(false), m_bSempore(false)
{
if(MaxSlots < 4) {
m_nMaxSlots = 4;
m_Vector.resize(m_nMaxSlots);
}
};
~SIGNAL_SIGNAL_S()
{
};
int Attach(void * pObj, SigProc pProc)
{
int i, ret = -1;
if(IsAttached(pObj, pProc) > 0 )
{
return -2;
}
m_Mutex.Enter();
for(i = 0; i < m_nMaxSlots; i++)
{
if(m_Vector[i].m_pObj == pObj
//&& m_Vector[i].m_pProc == pProc
&& (memcmp(&m_Vector[i].m_pProc, &pProc, sizeof(SigProc)) == 0) //
&& m_Vector[i].m_Status == SIGNAL_NODE_NORMAL)
{
ret = -2;
break;
}
if(m_Vector[i].m_Status == SIGNAL_NODE_EMPTY)
{
m_Vector[i].m_pObj = (CObject*)pObj;
m_Vector[i].m_pProc = pProc;
m_Vector[i].m_Status = SIGNAL_NODE_NORMAL;
ret = calcSize();
break;
}
}
m_Mutex.Leave();
return ret;
};
int Detach(void * pObj, SigProc pProc)
{
int i, ret = -1;
m_Mutex.Enter();
for(i = 0; i < m_nMaxSlots; i++)
{
if(m_Vector[i].m_pObj == pObj
//&& m_Vector[i].m_pProc == pProc )
&& (memcmp(&m_Vector[i].m_pProc, &pProc, sizeof(SigProc)) == 0)) //__TCS__
{
m_Vector[i].m_Status = SIGNAL_NODE_EMPTY;
ret = calcSize();
break;
}
}
if( m_bCalled )
{
m_bSempore = true;
m_Mutex.Leave();
m_sem.Pend();
m_Mutex.Enter();
}
m_Mutex.Leave();
return ret;
};
int IsAttached(void * pObj, SigProc pProc)
{
int i , ret = -1;
m_Mutex.Enter();
for(i = 0; i < m_nMaxSlots; i++)
{
if(m_Vector[i].m_pObj == pObj
//&& m_Vector[i].m_pProc == pProc
&& (memcmp(&m_Vector[i].m_pProc, &pProc, sizeof(SigProc)) == 0) //__TCS__
&& m_Vector[i].m_Status == SIGNAL_NODE_NORMAL)
{
ret = calcSize();
break;
}
}
m_Mutex.Leave();
return ret;
};
void operator()(SIGNAL_TYPE_ARGS)
{
int i;
m_Mutex.Enter();
m_bCalled = true;
m_Mutex.Leave();
for(i=0; i<m_nMaxSlots; i++)
{
if(m_Vector[i].m_Status == SIGNAL_NODE_NORMAL) //¿É²Ù×÷״̬
{
m_Vector[i](SIGNAL_ARGS); //call back
}
}
m_Mutex.Enter();
m_bCalled = false;
if(m_bSempore)
{
m_bSempore = false;
m_sem.Post();
}
m_Mutex.Leave();
};
};
#undef INLINE
#undef SIGNAL_NODE
#undef SIGNAL_SIGNAL
#undef SIGNAL_SIGNAL_S
#undef SIGNAL_NODE_EMPTY
#undef SIGNAL_NODE_NEW
#undef SIGNAL_NODE_DELETE
#undef SIGNAL_NODE_NORMAL
| [
"xinliang.fu@visionfocus.cn"
] | xinliang.fu@visionfocus.cn |
8db4612554f6f86c9740663ca6b6431cdd919123 | 00898a0e0ac2ae92cd112d2febf8d2b16fb65da4 | /Project_code/PLC-Comm/include/Qt3DRenderer/5.5.0/Qt3DRenderer/private/cameraselectornode_p.h | 6c828d5b77469c29b06f61a3457101df81bf0cd1 | [] | no_license | yisea123/AM-project | 24dd643a2f2086ea739cf48a4c6e8f95c11e42a7 | f1f7386a04985fcbd5d4fc00707cc5c3726c4ff4 | refs/heads/master | 2020-09-01T23:47:58.300736 | 2018-09-24T11:57:57 | 2018-09-24T11:57:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,461 | h | /****************************************************************************
**
** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt3D module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL3$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPLv3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or later 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 2.0 requirements will be
** met: http://www.gnu.org/licenses/gpl-2.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QT3D_RENDER_CAMERASELECTOR_H
#define QT3D_RENDER_CAMERASELECTOR_H
#include <Qt3DRenderer/private/framegraphnode_p.h>
#include <Qt3DCore/qnodeid.h>
QT_BEGIN_NAMESPACE
namespace Qt3D {
class QEntity;
class QCameraSelector;
namespace Render {
class Renderer;
class CameraSelector : public FrameGraphNode
{
public:
CameraSelector();
void updateFromPeer(QNode *peer) Q_DECL_OVERRIDE;
void sceneChangeEvent(const QSceneChangePtr &e) Q_DECL_OVERRIDE;
QNodeId cameraUuid() const;
private:
QNodeId m_cameraUuid;
};
} // namespace Render
} // namespace Qt3D
QT_END_NAMESPACE
#endif // QT3D_RENDER_CAMERASELECTOR_H
| [
"2539722953@qq.com"
] | 2539722953@qq.com |
a2b355f2766bdeba563e259a8d06c39d5b0a6488 | 0adcae0ad5f0f29cb8220c00321791a60b09b92b | /BST.h | efa0551a64fb6d6464a904f0f82029113cd0fea4 | [] | no_license | khangvtran/BinarySearchTree | 6fda71faaed08bb0119740a65839c8149d86ff29 | cc29141fc1184613552e25d593e1c8e17ad9632f | refs/heads/master | 2021-10-11T21:21:31.398882 | 2019-01-30T00:04:31 | 2019-01-30T00:04:31 | 109,341,086 | 0 | 0 | null | 2017-11-11T02:07:36 | 2017-11-03T02:13:08 | C++ | UTF-8 | C++ | false | false | 9,709 | h | /*
* BST.h
*
* Created on: Nov 2, 2017
* Author: Khang Vinh Tran, Tri Doan
*/
# ifndef BST_H_
# define BST_H_
# include <iostream>
# include <cstddef>
# include <string>
# include <assert.h>
# include <algorithm>
using namespace std;
template<typename bstdata>
class BST {
private:
struct Node {
bstdata data;
Node* leftchild;
Node* rightchild;
Node(bstdata newdata){
data = newdata;
leftchild = NULL;
rightchild = NULL;
}
};
Node* root;
/**Private helper functions*/
void insertNode(Node* root, bstdata data);
//private helper function for insert
//recursively inserts a value into the BST
void inOrderPrint(ostream& out, Node* root) const;
//private helper function for inOrderPrint
//recursively prints tree values in order from smallest to largest
void preOrderPrint(ostream& out, Node* root) const;
//private helper function for preOrderPrint
//recursively prints tree values in pre order
void postOrderPrint(ostream& out, Node* root) const;
//private helper function for postOrderPrint
//recursively prints tree values in post order
void copyNode(Node* copy);
//recursive helper function to the copy constructor
void freeNode(Node* root);
//private helper function for the destructor
//recursively frees the memory in the BST
bool searchNode(Node* root, bstdata data) const;
//recursive helper function to search
//returns whether the value is found in the tree
bstdata minimum(Node* root) const;
//recursive helper function to minimum
//returns the minimum value in the tree
bstdata maximum(Node* root) const;
//recursive helper function to maximum
//returns the maximum value in the tree
Node* deleteNode(Node* root, bstdata data);
//recursive helper function to remove
//removes data from the tree
void getSize(Node* root, int& size) const;
//recursive helper function to the size function
//calculates the size of the tree
//stores the result in size
int getHeight(Node* root) const;
//recursive helper function to the height function
//returns the height of the tree
public:
/**constructors and destructor*/
BST();
//Instantiates a new BST
BST(const BST &bst);
//copy constructor
~BST();
//deallocates the tree memory
/**access functions*/
bstdata minimum() const;
//returns the minimum value in the BST
//pre: !empty()
bstdata maximum() const;
//returns the maximum value in the BST
//pre: !empty()
bool isEmpty() const;
//determines whether the BST is empty
int getSize() const;
//returns the size of the tree
bstdata getRoot() const;
//returns the value stored at the root of the BST
//pre: !isEmpty()
int getHeight() const;
//returns the height of the tree
bool search(bstdata data) const;
//returns whether the data is found in the tree
//pre: !isEmpty()
/**manipulation procedures*/
void insert(bstdata data);
//inserts new data into the BST
void remove(bstdata data);
//removes the specified value from the tree
//pre: data is located in the tree
//pre: !isEmpty()
/**additional functions*/
void inOrderPrint(ostream& out) const;
//calls the inOrderPrint function to print out the values
//stored in the BST
void preOrderPrint(ostream& out) const;
//calls the reOrderPrint function to print out the values
//stored in the BST
void postOrderPrint(ostream& out) const;
//calls the postOrderPrint function to print out the values
//stored in the BST
};
/************ constructors and destructor ************/
template <typename bstdata>
BST<bstdata>::BST()
{
root = NULL;
}
template <typename bstdata>
BST<bstdata>::BST(const BST &bst)
{
if (bst.root == NULL) root = NULL; // WHAT'S THE DIFFERENCE BETWEEN USING . AND ->
else
{
//root = new Node(bst.getRoot());
copyNode(bst.root);
}
}
template <typename bstdata>
void BST<bstdata>::copyNode(Node* copy)
{
if (copy == NULL) return;
else
{
insert(copy->data);
copyNode(copy->leftchild);
copyNode(copy->rightchild);
}
}
template <typename bstdata>
BST<bstdata>::~BST()
{
freeNode(root);
}
template <typename bstdata>
void BST<bstdata>::freeNode(Node* root)
{
if (root == NULL) return;
else
{
freeNode(root->leftchild);
freeNode(root->rightchild);
delete root;
}
}
/************ manipulation procedures ************/
template<typename bstdata>
void BST<bstdata>::insert(bstdata data)
{
if (root == NULL) root = new Node(data);
else insertNode(root, data);
}
template<typename bstdata>
void BST<bstdata>::insertNode(Node* root, bstdata data)
{
if (root->data == data) return;
else if (root->data > data)
{
if (root->leftchild == NULL) root->leftchild = new Node(data);
else insertNode(root->leftchild, data);
}
else
{
if (root->rightchild == NULL) root->rightchild = new Node(data);
else insertNode(root->rightchild, data);
}
}
template<typename bstdata>
bool BST<bstdata>::search(bstdata data) const
{
assert(!isEmpty());
if (root->data == data) return true;
else return searchNode(root, data);
}
template<typename bstdata>
bool BST<bstdata>::searchNode(Node* root, bstdata data) const
{
if (root->data == data) return true;
else if (root->data > data)
{
if (root->leftchild == NULL) return false;
else return searchNode(root->leftchild, data);
}
else
{
if (root->rightchild == NULL) return false;
else return searchNode(root->rightchild, data);
}
}
template <typename bstdata>
void BST<bstdata>::remove(bstdata data)
{
assert(!isEmpty());
assert(search(data)); // isEmpty() is actually already enforced in this
root = deleteNode(root, data);
}
template <class bstdata>
typename BST<bstdata>::Node* BST<bstdata>::deleteNode(Node* root, bstdata data)
{
if (root == NULL) return root; // base case: Is this necessary?
else if (data < root->data) root->leftchild = deleteNode(root->leftchild, data);
else if (data > root->data) root->rightchild = deleteNode(root->rightchild, data);
else
{
if (root->leftchild == NULL && root->rightchild == NULL)
{
delete root;
root = NULL;
}
else if (root->rightchild == NULL)
{
Node* temp = root->leftchild;
delete root;
return temp;
}
else if (root->leftchild == NULL)
{
Node* temp = root->rightchild;
delete root;
return temp;
}
else
{
bstdata minRightChild = minimum(root->rightchild);
root->data = minRightChild;
root->rightchild = deleteNode(root->rightchild, minRightChild);
}
}
return root;
}
/************ access functions ************/
template <typename bstdata>
bool BST<bstdata>::isEmpty() const
{
return (getSize() == 0);
}
template<typename bstdata>
bstdata BST<bstdata>::getRoot() const
{
assert(!isEmpty());
return root->data;
}
template<typename bstdata>
int BST<bstdata>::getSize() const
{
int size = 0;
getSize(root, size);
return size;
}
template <typename bstdata>
void BST<bstdata>::getSize(Node* root, int& size) const
{
if (root == NULL) return;
else
{
size++;
getSize(root->leftchild, size);
getSize(root->rightchild, size);
}
}
template <typename bstdata>
int BST<bstdata>::getHeight() const
{
return getHeight(root);
}
template <typename bstdata>
int BST<bstdata>::getHeight(Node* root) const
{
if (root == NULL) return -1;
else
{
if (getHeight(root->leftchild) >= getHeight(root->rightchild)) return 1+getHeight(root->leftchild);
else return 1+getHeight(root->rightchild);
}
}
/*
template <typename bstdata>
int BST<bstdata>::getHeight(Node* root) const
{
if (root == NULL)
{
return -1;
}
else
{
return 1+max(getHeight(root->leftchild), getHeight(root->rightchild));
}
}
*/
template <typename bstdata>
bstdata BST<bstdata>::minimum() const
{
assert(!isEmpty());
return minimum(root);
}
template <typename bstdata>
bstdata BST<bstdata>::minimum(Node* root) const
{
if (root->leftchild == NULL) return root->data;
else return minimum(root->leftchild);
}
template <typename bstdata>
bstdata BST<bstdata>::maximum() const
{
assert(!isEmpty());
return maximum(root);
}
template <typename bstdata>
bstdata BST<bstdata>::maximum(Node* root) const
{
if (root->rightchild == NULL) return root->data;
else return maximum(root->rightchild);
}
/************ additional functions ************/
template <typename bstdata> // PUBLIC
void BST<bstdata>::inOrderPrint(ostream& out) const
{
inOrderPrint(out, root);
cout << endl;
}
template <typename bstdata> // PRIVATE
void BST<bstdata>::inOrderPrint(ostream& out, Node* root) const
{
if (root == NULL) return;
else
{
inOrderPrint(out, root->leftchild);
out << root->data << " ";
inOrderPrint(out, root->rightchild);
}
}
template <typename bstdata>
void BST<bstdata>::preOrderPrint(ostream& out) const
{
preOrderPrint(out, root);
cout << endl;
}
template <typename bstdata>
void BST<bstdata>::preOrderPrint(ostream& out, Node* root) const
{
if (root == NULL) return;
else
{
out << root->data << " ";
preOrderPrint(out, root->leftchild);
preOrderPrint(out, root->rightchild);
}
}
template <typename bstdata>
void BST<bstdata>::postOrderPrint(ostream& out) const
{
postOrderPrint(out, root);
cout << endl;
}
template <typename bstdata>
void BST<bstdata>::postOrderPrint(ostream& out, Node* root) const
{
if (root == NULL) return;
else
{
postOrderPrint(out, root->leftchild);
postOrderPrint(out, root->rightchild);
out << root->data << " ";
}
}
#endif /* BST_H_ */
| [
"vinhkhangtran09@gmail.com"
] | vinhkhangtran09@gmail.com |
a7920bd05b92d58716584a4e32d0e939ce215f91 | 29b81bdc013d76b057a2ba12e912d6d4c5b033ef | /boost/include/boost/asio/detail/macos_fenced_block.hpp | 8a32b993c859833d05a8c606e67b01cfde52497a | [] | no_license | GSIL-Monitor/third_dependences | 864d2ad73955ffe0ce4912966a4f0d1c60ebd960 | 888ebf538db072a92d444a9e5aaa5e18b0f11083 | refs/heads/master | 2020-04-17T07:32:49.546337 | 2019-01-18T08:47:28 | 2019-01-18T08:47:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 129 | hpp | version https://git-lfs.github.com/spec/v1
oid sha256:4e6908cd30564a3104143b5367ef60f460946bd36604f8295e93c5607a12b718
size 1398
| [
"you@example.com"
] | you@example.com |
1a7241e1114ae8ae6503b0a59fb2dbf5331537a0 | cc5efd4ed5b6451a2ee7667046043b67e9e24ca8 | /source/core/Timer.cpp | 4644f88bb4be1a0961a95e1bd9e0a18c2f46ed41 | [] | no_license | ceari/spaceshooter | f4e11ae26aec2a937474b5768a55aca8ebc1c81b | 5fba95cb2646d319c7b607de4ce820ee31b74f22 | refs/heads/master | 2016-09-01T22:12:20.976966 | 2012-12-03T16:29:53 | 2012-12-03T16:29:53 | 6,985,499 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 514 | cpp | #include "Timer.h"
namespace DFXEngine
{
void Timer::update()
{
last_update = SDL_GetTicks();
}
unsigned int Timer::dt()
{
return SDL_GetTicks() - last_update;
}
void Timer::startLoop()
{
start = SDL_GetTicks();
}
void Timer::endLoop()
{
end = SDL_GetTicks();
}
void Timer::limitFPS(int fps)
{
if ((SDL_GetTicks() - start) < 1000.0 / fps)
{
SDL_Delay( ( 1000.0 / fps ) - (SDL_GetTicks() - start) );
}
}
unsigned int Timer::currentTime()
{
return SDL_GetTicks();
}
}
| [
"daniel.diepold@gmail.com"
] | daniel.diepold@gmail.com |
1375a6fdafb8ee5347820cd9881e66a59984921b | 9bc87fbd3db4aabaff6e60e77d72e229ce066c43 | /src/core/Camera.cpp | d753c6afc431e389c2cd83a1f2349ad15f1bee92 | [] | no_license | invke/Nine-opengl | fa25efb358015d12e8ea23f4110f65036ee154e9 | 74b592200cbf475ec9fb97197546adaee9a2a405 | refs/heads/master | 2023-02-17T02:25:39.567910 | 2021-01-15T04:36:25 | 2021-01-15T04:36:25 | 75,697,984 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,413 | cpp | //
// Created by montgomery anderson on 9/12/16.
//
#include "core/Camera.h"
#include "core/Constants.h"
#include <glm/glm.hpp>
using namespace constants;
Camera::Camera() {
screenDimensions = glm::vec2(WINDOW_WIDTH, WINDOW_HEIGHT);
}
void Camera::key_press(GLFWwindow *window, int key, int scancode, int action, int mods) {
if (key == GLFW_KEY_W) move_forward();
if (key == GLFW_KEY_A) strafe_left();
if (key == GLFW_KEY_S) move_backwards();
if (key == GLFW_KEY_D) strafe_right();
if (key == GLFW_KEY_SPACE) move_up();
if (key == GLFW_KEY_LEFT_SHIFT) move_down();
}
Camera::Camera(glm::vec3 pos, glm::vec3 upDir, glm::vec3 viewDir) : Camera() {
this->pos = pos;
this->upDir = upDir;
this->viewDir = viewDir;
viewPt = pos + viewDir;
}
void Camera::move_forward() {
pos += viewDir * DIRECTIONAL_SPEED;
viewPt = pos + viewDir;
}
void Camera::move_backwards() {
pos -= viewDir * DIRECTIONAL_SPEED;
viewPt = pos + viewDir;
}
void Camera::strafe_left() {
pos -= glm::cross(viewDir, upDir) * LATERAL_SPEED;
viewPt = pos + viewDir;
}
void Camera::strafe_right() {
pos += glm::cross(viewDir, upDir) * LATERAL_SPEED;
viewPt = pos + viewDir;
}
void Camera::move_up() {
pos += upDir * VERTICAL_SPEED;
viewPt = pos + viewDir;
}
void Camera::move_down() {
pos -= upDir * VERTICAL_SPEED;
viewPt = pos + viewDir;
}
| [
"montgomeryanderson@montgomerys-iMac.local"
] | montgomeryanderson@montgomerys-iMac.local |
ec93d8e857a77e99dea3c541304b89908ab7b90c | 4703e7ae907292598812704846a97db3533f4dc7 | /VektoriaApp/Save.cpp | b6f6079ba305bce7d26944e69a42dd6cb19cfaf0 | [] | no_license | cutecrait/marsgodgames | 57495692f3a14945c7c504263c8e87f7e99561fa | 6f1a94cc0172a27c0ef7150bb1f023c98fc6a6cd | refs/heads/master | 2023-06-24T11:42:43.377216 | 2021-07-26T09:39:10 | 2021-07-26T09:39:10 | 353,086,425 | 0 | 1 | null | null | null | null | ISO-8859-1 | C++ | false | false | 4,808 | cpp | #include "Save.h"
//Karo start
Save::Save()
{
*pos_arr = new float[100];
pos_id = 0;
}
Save::~Save()
{
}
void Save::getObjects()
{
}
void Save::deleteTxt()
{
remove("PlayerDetails.txt");
}
std::string Save::getObjName(GameObject *GO)
{
std::string objName;
if (dynamic_cast<Apartment*>(GO))
{
objName = "Apartment";
//ULDebug(objName.c_str());
}
else if(dynamic_cast<Barrack*>(GO))
{
objName = "Barrack";
//ULDebug(objName.c_str());
}
/*else if (dynamic_cast<Building*>(GO))
{
objName = "Building";
//ULDebug(objName.c_str());
}*/
else if (dynamic_cast<ControlCenter*>(GO))
{
objName = "ControlCenter";
//ULDebug(objName.c_str());
}
else if (dynamic_cast<FoodFarm*>(GO))
{
objName = "FoodFarm";
//ULDebug(objName.c_str());
}
else if (dynamic_cast<Foundry*>(GO))
{
objName = "Foundry";
//ULDebug(objName.c_str());
}
else if (dynamic_cast<GravelPlant*>(GO))
{
objName = "GavelPlant";
//ULDebug(objName.c_str());
}
else if (dynamic_cast<Hospital*>(GO))
{
objName = "Hospital";
//ULDebug(objName.c_str());
}
else if (dynamic_cast<Laboratory*>(GO))
{
objName = "Laboratory";
//ULDebug(objName.c_str());
}
else if (dynamic_cast<Launchpad*>(GO))
{
objName = "Launchpad";
//ULDebug(objName.c_str());
}
else if (dynamic_cast<Mine*>(GO))
{
objName = "Mine";
//ULDebug(objName.c_str());
}
else if (dynamic_cast<NuclearPowerPlant*>(GO))
{
objName = "NuclearPowerPlant";
//ULDebug(objName.c_str());
}
else if (dynamic_cast<RobotFactory*>(GO))
{
objName = "RobotFactory";
//ULDebug(objName.c_str());
}
else if (dynamic_cast<SolarPowerPlant*>(GO))
{
objName = "SolarPowerPlant";
//ULDebug(objName.c_str());
}
else if (dynamic_cast<TreeFarm*>(GO))
{
objName = "TreeFarm";
//ULDebug(objName.c_str());
}
else if (dynamic_cast<Well*>(GO))
{
objName = "Well";
//ULDebug(objName.c_str());
}
else if (dynamic_cast<OxygenTank*>(GO))
{
objName = "OxygenTank";
//ULDebug(objName.c_str());
}
else {
ULDebug("Failure: Object Name not found.");
objName = "Fail";
}
return objName;
}
void Save::writePosToTxt(std::string file_name, std::string object_name, float x_pos, float z_pos)
{
std::ofstream file;
file.open(file_name, std::ios_base::app);
file << object_name << ", " << x_pos << ", " << z_pos << std::endl;
file.close();
}
void Save::fillPosAr(GameObject* GO, float x, float z)
{
std::string obj_class = this->getObjName(GO);
geo_arr[pos_id] = obj_class;
pos_arr[pos_id] = new float[2];
pos_arr[pos_id][0] = x;
pos_arr[pos_id][1] = z;
pos_id += 1;
}
bool Save::saveItAll()
{
/*if (pos_arr[pos_id][0] == undefined) {
pos_arr[pos_id][0] = 1.0f;
pos_arr[pos_id][1] = 1.0f;
}*/
//ULDebug(geo_arr[0].c_str());
for (int i = 0; i < pos_id; i++) {
this->writePosToTxt("Positions.txt", geo_arr[i], pos_arr[i][0], pos_arr[i][1]);
}
this->writePlayerDetailstoTxt();
return true;
}
void Save::writePlayerDetailstoTxt()
{
remove("PlayerDetails.txt");
std::ofstream file;
file.open("PlayerDetails.txt", std::ios_base::app);
file << Player::Instance().getConcrete() << std::endl;
file << Player::Instance().getSteel() << std::endl;
file << Player::Instance().getWood() << std::endl;
file << Player::Instance().getConcretePM() << std::endl;
file << Player::Instance().getSteelPM() << std::endl;
file << Player::Instance().getWoodPM() << std::endl;
file << Player::Instance().getUseWater() << std::endl;
file << Player::Instance().getUsePower() << std::endl;
file << Player::Instance().getUseFood() << std::endl;
file << Player::Instance().getWater() << std::endl;
file << Player::Instance().getPower() << std::endl;
file << Player::Instance().getFood() << std::endl;
file << Player::Instance().getWohnung() << std::endl;
file << Player::Instance().getUsedWohnungen() << std::endl;
file << Player::Instance().getRobots() << std::endl;
file.close();
}
void Save::ResetGame()
{
//Reset Resources in den Player Details
remove("PlayerDetails.txt");
std::ofstream file;
file.open("PlayerDetails.txt", std::ios_base::app);
file << 1000 << std::endl;
file << 1000 << std::endl;
file << 1000 << std::endl;
file << 0 << std::endl;
file << 0 << std::endl;
file << 0 << std::endl;
file << 0 << std::endl;
file << 0 << std::endl;
file << 0 << std::endl;
file << 0 << std::endl;
file << 0 << std::endl;
file << 0 << std::endl;
file << 0 << std::endl;
file << 0 << std::endl;
file << 0 << std::endl;
file.close();
// Reset Positions: alles löschen, erste 2 Zeilen hinzufügen
remove("Positions.txt");
std::ofstream filepos;
filepos.open("Positions.txt", std::ios_base::app);
filepos << "ControlCenter" << ", " << 4 << ", " << 4 << std::endl;
filepos << "Launchpad" << ", " << 4 << ", " << 6 << std::endl;
}
//Karo end | [
"karolinpatricia.brandes@stud.hs-kemtpen.de"
] | karolinpatricia.brandes@stud.hs-kemtpen.de |
569e56879fed6018940d052baeca177b0796b74e | ecd81edc6779a4de8999bf8473e950d6c6b3aa92 | /src/my_thread.cpp | a37db04a5d15d01f8b34491c936b232819d6ebe5 | [] | no_license | Adrian925492/Concurency | 11590594f3c34cd7492131cd1affba37dc584b25 | 1bf59e40ef3fe6e969131174b57f23bb10345d8b | refs/heads/master | 2022-11-26T15:53:08.696086 | 2020-08-08T10:41:48 | 2020-08-08T10:41:48 | 282,683,213 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,708 | cpp | #include <thread>
/* <thread> - the stadard library containing basic tools for operating with threads.
Threads represents concurently executable functions. std::thread defines thread object, which is
representation of single thead of execution.
Thread is executed immidietly after construction. The <thread> provides basic api for low-level
OS dependent multithreading mechanisms. Not all features provided by lower-level, OS specific threads
API are provided by standard API (for example, like ability of cancelling thread from other
thread as provided for pthread lib.)
The function for thread is provided by constructor argumet. Thread can exit iself by finishing
thread function execution.
Threads has 2 special abilities:
-> Joining - means, that other thread can wait for joined thread. The waiting thread will
do nothing, untill waited thread will finish its execution.
-> Detachong - means, that one thread will do not care about other thread, even if
the other thread has been created by the thread, and thread object (playing thread handler role)
would be lost. It permits the thread to execute independently.
Both, joining and detaching can be done only once on thread (by one thread).
.join() - wait for thread
.detach() - allow thread to run independently (rarely used, be careful! - detached thread
is not quaranteed to release all its resources when parent thread exits)
Thread has joinable() method, which informs, if the thread has already started its
concurent execution and can be waited for or detached. Beforejoining the thread we should
check it, to prevent, that we will join unstarted (yet) thread.
.swap() - Allws to swap 2 thread objects each other
.operator=() - Allows to move thread object (assign) given by argument to our thread.
Thread id - each thread has its unique number (int) - id.
.get_id() - Returns thread's id.
.native_handle() - Returns underlaying (native API type) thread handler object
Thread initialization - constructors
-> thread()- initializes empty thread object
-> thread(thread) - copy thread passed by argument
-> template<F, Args> thread(f, args) - initializes thread object with f (of return type F) as
thread function (can be functor, function, method, lambda), and allows to pass arguments
of the thread function by args (type of args we pass in template as Args).
! If You use threads with UNIX based system, the base API if std::thread is pthread. You have to add
-pthread flag to compilation to let it run concurently.
! In non realtime OS schedule of thread execution is undefined - nobody knows which thread will be running in time
and when contex switching wil occur.
*/
#include <thread>
#include <iostream>
#include <chrono>
using namespace std;
void thread_fcn1(void)
{
cout << "Thread 1\n" << endl;
this_thread::sleep_for(chrono::milliseconds(100));
}
void thread_fcn2(int param)
{
cout << "Thread 2, param(int): " << param << "\n" << endl;
this_thread::sleep_for(chrono::milliseconds(200));
}
void thread_example()
{
cout << "Thread example >>>>>>>>>>>>> \n\n";
thread t1; //Initialize empty thread object
thread t2(thread_fcn2, 5); //Initialize thread and assign function to it, run it at once
t1 = thread(thread_fcn1); //Assign thread to t1, run it
thread t3 = thread([](){ cout << "Thread 3 - by lambda notation\n";}); //Create and assign thread 3 - by lambda
if (t1.joinable()) //Check if threads are joinable and join all of them
{
t1.join();
}
if (t2.joinable())
{
t2.join();
}
if (t3.joinable())
{
t3.join();
}
cout << "<<<<<<<<<<<<<<<<<<<<<<<<<<<<< \n";
}
| [
"adrian.podsiadlowski@gmail.com"
] | adrian.podsiadlowski@gmail.com |
1bb878f0943dcad08f193b26c97a341db4aa4f03 | 1446a45de06399c141ad722b70f8a4e2f88f01c8 | /boost_1_34_1/boost_1_34_1/libs/date_time/test/testint64_range.cpp | b7a431da8a2cebcd205c08f97693acad4c8e5a64 | [
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] | permissive | Thrinaria/Codebase | 270d2b837242e113d733a7e6405b5294faede534 | 85e541a9d1e57f7bf30b5114e5e0a2063275a75d | refs/heads/master | 2021-01-01T20:34:47.359877 | 2015-01-30T06:04:42 | 2015-01-30T06:04:42 | 29,504,087 | 3 | 4 | null | 2015-01-25T01:55:41 | 2015-01-20T00:41:11 | C++ | UTF-8 | C++ | false | false | 2,918 | cpp | /* Copyright (c) 2002,2003 CrystalClear Software, Inc.
* Use, modification and distribution is subject to the
* Boost Software License, Version 1.0. (See accompanying
* file LICENSE-1.0 or http://www.boost.org/LICENSE-1.0)
* Author: Jeff Garland
*/
//#include "date_time/testfrmwk.hpp"
#include <iostream>
#include "boost/date_time/gregorian/gregorian.hpp"
#include "boost/cstdint.hpp"
int
main()
{
#if (defined(BOOST_MSVC) && (_MSC_VER < 1300))
//skipping tests here due to lack of operator<< support in msvc6
// TODO: this is a bit misleading: using STLport, this should work.
std::cout << "Skipping tests on MSVC6" << std::endl;
#else
std::cout << "int64_t max: "
<< (std::numeric_limits<boost::int64_t>::max)()
<< std::endl;
std::cout << "uint64_t max: "
<< (std::numeric_limits<boost::uint64_t>::max)()
<< std::endl;
boost::int64_t seconds_per_day = 60*60*24;
boost::int64_t microsec_per_sec = 1000000;
boost::int64_t microsec_per_day = seconds_per_day*microsec_per_sec;
std::cout << "microsec per day: "
<< microsec_per_day
<< std::endl;
boost::uint64_t total_days = (std::numeric_limits<boost::int64_t>::max)() / microsec_per_day;
std::cout << "Representable days: "
<< total_days
<< std::endl;
boost::int64_t approx_years = total_days / 366;
std::cout << "Approximate years: "
<< approx_years
<< std::endl;
//getting day count
// usec_count / (seconds_per_day*usec_per_sec);
boost::int64_t day_count = 1000;
boost::int64_t usec_count1000 = day_count*microsec_per_day + 999999;
std::cout << "usec count at day 1000 + 999999: "
<< usec_count1000
<< std::endl;
boost::int64_t day_count_calc = usec_count1000 / microsec_per_day;
std::cout << "calc day count at day 1000: "
<< day_count_calc
<< std::endl;
boost::int64_t remaining_usec_count = usec_count1000 % microsec_per_day;
std::cout << "remaining usec count: "
<< remaining_usec_count
<< std::endl;
boost::int32_t day_count3M = 3000000;
boost::int64_t usec_count3M = day_count3M*microsec_per_day + 999999;
std::cout << "usec count at day 3M + 999999: "
<< usec_count3M
<< std::endl;
boost::int64_t day_count_calc3M = usec_count3M / microsec_per_day;
std::cout << "calc day count at day 3M: "
<< day_count_calc3M
<< std::endl;
boost::int64_t remaining_usec_count3M = usec_count3M % microsec_per_day;
std::cout << "remaining usec count 3M: "
<< remaining_usec_count3M
<< std::endl;
#endif
// std::cout << "Days from: "
// << to_simple_string(d1) << " to "
// << to_simple_string(d2) << " = "
// << day_count << std::endl;
// printTestStats();
return 0;
};
| [
"thrin_d@live.nl"
] | thrin_d@live.nl |
e297c5832cb0e74dce3c5fa4d5dacba031f91011 | cdfc8ccda581285be76cf2c16581bfb356497476 | /OpenFOAM/FE41/tutorials/forwardStep/system/fvSchemes | 560b6e64464519618013790af7cba6916010aa8d | [] | no_license | mariomatuzovic/Centrifugalni-kompresor | be770310b7c97d58d647bcc47ed6f2aa53d3aa7c | d6279e3f399a5174f6592105051976a02bbb12ff | refs/heads/master | 2023-06-29T23:46:08.391967 | 2021-08-08T16:41:12 | 2021-08-08T16:41:12 | 394,016,997 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,618 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | foam-extend: Open Source CFD |
| \\ / O peration | Version: 4.1 |
| \\ / A nd | Web: http://www.foam-extend.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class dictionary;
location "system";
object fvSchemes;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
ddtSchemes
{
default Euler;
}
gradSchemes
{
default Gauss linear;
}
divSchemes
{
default none;
div(phi,U) Gauss MinmodDC;
div(phid,p) Gauss MinmodDC;
div(phi,T) Gauss MinmodDC;
div(phi,e) Gauss MinmodDC; //upwind;
div((muEff*dev2(T(grad(U))))) Gauss linear;
div((phi|interpolate(rho)),p) Gauss linear;
}
laplacianSchemes
{
default Gauss linear corrected;
}
interpolationSchemes
{
default linear;
// upwindRho vanLeer phi;
// upwindPsi vanLeer phi;
upwindRho Minmod phi;
upwindPsi Minmod phi;
// interpolate(rho) linear;
// interpolate(rAU) linear;
// interpolate(U) linear;
}
snGradSchemes
{
default corrected;
}
// ************************************************************************* //
| [
"matuzovic.mario@gmail.com"
] | matuzovic.mario@gmail.com | |
aa2dcb58e116009946ba90d1ae6cb4f5ab74f0d6 | 4eee1fe33dab2b5d6ebff4eb87e1652385c54fbd | /Cpp_project/Math.cpp | cefbf1e24786952c9279ead9585b2fe009afad7b | [] | no_license | ryansan/Cpp_learning_project | efe8a5aa3834f1f8186d433812877cc9d64cc621 | ec7002fea4b48284aa84a530d2fe99b60c5430ad | refs/heads/master | 2020-03-21T06:25:37.548947 | 2018-06-25T15:38:50 | 2018-06-25T15:38:50 | 138,218,731 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 204 | cpp | //
// Math.cpp
// Cpp_project
//
// Created by Ryan Sangha on 21/06/2018.
// Copyright © 2018 Ryan Sangha. All rights reserved.
//
#include "Math.hpp"
int multiply(int a, int b){
return a*b;
}
| [
"31653675+ryansan@users.noreply.github.com"
] | 31653675+ryansan@users.noreply.github.com |
d555e699f7232dd1cd35ab4958e4d9b66c67e697 | 47f84bdfb5d17ebfd7ecfe2e0678ad26653f26f7 | /app/src/main/cpp/shapes/triangle.h | 5d5abab44e53f56b6c125253d864ec0783039e63 | [] | no_license | yjoo9317/ObjModelTest | e259352fa34105d64ed0d26b2e5fd909a6f5d3c4 | 567ec73163154117c2c22c1de29ec6c76a5474ba | refs/heads/master | 2020-03-19T18:58:27.098433 | 2018-06-12T06:10:24 | 2018-06-12T06:10:24 | 136,834,133 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 808 | h | //
// Created by Youngjoo Park on 6/4/18.
//
#ifndef NATIVETEST_TRIANGLE_H
#define NATIVETEST_TRIANGLE_H
#include "myLogger.h"
#include "glesNative.h"
#include <sstream>
#include <iostream>
#include <stdio.h>
#include <string>
class Triangle {
public:
Triangle();
void initGL();
void Render();
void SetViewport(int width, int height);
bool IsInitsDone() { return initDone; }
private:
void renderTriangle();
void animateTriangle();
bool initDone;
// vertex buffer for triangle's vertices, colors
GLuint vertexBuffer, colorBuffer;
// will hold attributed for shader variables
GLuint vertexAttribute, colorAttribute;
GLuint shaderProgramID;
float triangleVertexDelta, triangleSwapRate;
};
#endif //NATIVETEST_TRIANGLE_H
| [
"yjoo9317@gmail.com"
] | yjoo9317@gmail.com |
4c9d4ee4a40ccf2a7ff7878fe699af7683d1cf93 | 9ce1f0f2652f81903f31452451bfd17ae6873623 | /Code/Core/Process/Process.cpp | 43ca90119c1eca5f2060e1a6a0cb711de8879a9c | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-other-permissive"
] | permissive | missmah/fastbuild | 7044b4f62b696956dbd1651b12262aa0bd052e06 | 310dcff973cf8e6902b2608cf72dbf928fe89e9c | refs/heads/master | 2021-01-19T16:50:38.890910 | 2017-04-14T19:27:44 | 2017-04-14T19:27:44 | 88,291,891 | 1 | 2 | null | 2019-10-30T04:37:30 | 2017-04-14T18:17:37 | C++ | UTF-8 | C++ | false | false | 23,012 | cpp | // Process.cpp
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include "Core/PrecompiledHeader.h"
#include "Process.h"
#include "Core/Env/Assert.h"
#include "Core/FileIO/FileIO.h"
#include "Core/Math/Conversions.h"
#include "Core/Process/Thread.h"
#include "Core/Profile/Profile.h"
#include "Core/Time/Timer.h"
#include "Core/Strings/AStackString.h"
#include "Core/Strings/AString.h"
#if defined( __WINDOWS__ )
#include <windows.h>
#endif
#if defined( __LINUX__ ) || defined( __APPLE__ )
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
#endif
// CONSTRUCTOR
//------------------------------------------------------------------------------
Process::Process()
: m_Started( false )
#if defined( __WINDOWS__ )
, m_SharingHandles( false )
, m_RedirectHandles( true )
, m_StdOutRead( nullptr )
, m_StdOutWrite( nullptr )
, m_StdErrRead( nullptr )
, m_StdErrWrite( nullptr )
#endif
#if defined( __LINUX__ ) || defined( __APPLE__ )
, m_ChildPID( -1 )
, m_HasAlreadyWaitTerminated( false )
#endif
{
#if defined( __WINDOWS__ )
static_assert( sizeof( m_ProcessInfo ) == sizeof( PROCESS_INFORMATION ), "Unexpected sizeof(PROCESS_INFORMATION)" );
#endif
}
// DESTRUCTOR
//------------------------------------------------------------------------------
Process::~Process()
{
if ( m_Started )
{
WaitForExit();
}
}
// Spawn
//------------------------------------------------------------------------------
bool Process::Spawn( const char * executable,
const char * args,
const char * workingDir,
const char * environment,
bool shareHandles )
{
PROFILE_FUNCTION
ASSERT( !m_Started );
ASSERT( executable );
#if defined( __WINDOWS__ )
// Set up the start up info struct.
STARTUPINFO si;
ZeroMemory( &si, sizeof(STARTUPINFO) );
si.cb = sizeof( STARTUPINFO );
si.dwFlags |= STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
SECURITY_ATTRIBUTES sa;
ZeroMemory( &sa, sizeof( SECURITY_ATTRIBUTES ) );
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = nullptr;
m_SharingHandles = shareHandles;
if ( m_RedirectHandles )
{
// create the pipes
if ( shareHandles )
{
si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
}
else
{
if ( ! CreatePipe( &m_StdOutRead, &m_StdOutWrite, &sa, MEGABYTE ) )
{
return false;
}
SetHandleInformation( m_StdOutRead, HANDLE_FLAG_INHERIT, 0 );
if ( ! CreatePipe( &m_StdErrRead, &m_StdErrWrite, &sa, MEGABYTE ) )
{
VERIFY( CloseHandle( m_StdOutRead ) );
VERIFY( CloseHandle( m_StdOutWrite ) );
return false;
}
SetHandleInformation( m_StdErrRead, HANDLE_FLAG_INHERIT, 0 );
si.hStdOutput = m_StdOutWrite;
si.hStdError = m_StdErrWrite;
si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
}
si.dwFlags |= STARTF_USESTDHANDLES;
}
// Make sure the first arg is the executable
// We also need to make a copy, as CreateProcess can write back to this string
AStackString< 1024 > fullArgs;
fullArgs += '\"';
fullArgs += executable;
fullArgs += '\"';
if ( args )
{
fullArgs += ' ';
fullArgs += args;
}
// create the child
if ( !CreateProcess( nullptr, //executable,
fullArgs.Get(),
nullptr,
nullptr,
(BOOL)m_RedirectHandles, // inherit handles
0,
(void *)environment,
workingDir,
&si,
(LPPROCESS_INFORMATION)&m_ProcessInfo ) )
{
return false;
}
m_Started = true;
return true;
#elif defined( __LINUX__ ) || defined( __APPLE__ )
(void)shareHandles; // unsupported
// create StdOut and StdErr pipes to capture output of spawned process
int stdOutPipeFDs[ 2 ];
int stdErrPipeFDs[ 2 ];
VERIFY( pipe( stdOutPipeFDs ) == 0 );
VERIFY( pipe( stdErrPipeFDs ) == 0 );
// prepare args
Array< AString > splitArgs( 64, true );
Array< const char * > argVector( 64, true );
argVector.Append( executable ); // first arg is exe name
if ( args )
{
// Tokenize
AStackString<> argCopy( args );
argCopy.Tokenize( splitArgs );
// Build Vector
for ( auto & arg : splitArgs )
{
if ( arg.BeginsWith( '"' ) && arg.EndsWith( '"' ) )
{
// strip quotes
arg.SetLength( arg.GetLength() - 1 ); // trim end quote
argVector.Append( arg.Get() + 1 ); // skip start quote
continue;
}
argVector.Append( arg.Get() ); // leave arg as-is
}
}
argVector.Append( nullptr ); // argv must have be nullptr terminated
// prepare environment
Array< const char* > envVector( 8, true );
if ( environment )
{
// Iterate double-null terminated string vector
while( *environment != 0 )
{
envVector.Append( environment );
environment += strlen( environment );
environment += 1; // skip null terminator for string
}
}
envVector.Append( nullptr ); // env must be terminated with a nullptr
// fork the process
const pid_t childProcessPid = fork();
if ( childProcessPid == -1 )
{
// cleanup pipes
VERIFY( close( stdOutPipeFDs[ 0 ] ) == 0 );
VERIFY( close( stdOutPipeFDs[ 1 ] ) == 0 );
VERIFY( close( stdErrPipeFDs[ 0 ] ) == 0 );
VERIFY( close( stdErrPipeFDs[ 1 ] ) == 0 );
ASSERT( false ); // fork failed - should not happen in normal operation
return false;
}
const bool isChild = ( childProcessPid == 0 );
if ( isChild )
{
VERIFY( dup2( stdOutPipeFDs[ 1 ], STDOUT_FILENO ) != -1 );
VERIFY( dup2( stdErrPipeFDs[ 1 ], STDERR_FILENO ) != -1 );
VERIFY( close( stdOutPipeFDs[ 0 ] ) == 0 );
VERIFY( close( stdOutPipeFDs[ 1 ] ) == 0 );
VERIFY( close( stdErrPipeFDs[ 0 ] ) == 0 );
VERIFY( close( stdErrPipeFDs[ 1 ] ) == 0 );
if ( workingDir )
{
VERIFY( chdir( workingDir ) == 0 );
}
// transfer execution to new executable
char * const * argV = (char * const *)argVector.Begin();
if ( environment )
{
char * const * envV = (char * const *)envVector.Begin();
execve( executable, argV, envV );
}
else
{
execv( executable, argV );
}
exit( -1 ); // only get here if execv fails
}
else
{
// close write pipes (we never write anything)
VERIFY( close( stdOutPipeFDs[ 1 ] ) == 0 );
VERIFY( close( stdErrPipeFDs[ 1 ] ) == 0 );
// keep pipes for reading child process
m_StdOutRead = stdOutPipeFDs[ 0 ];
m_StdErrRead = stdErrPipeFDs[ 0 ];
m_ChildPID = (int)childProcessPid;
// TODO: How can we tell if child spawn failed?
m_Started = true;
m_HasAlreadyWaitTerminated = false;
return true;
}
#else
#error Unknown platform
#endif
}
// IsRunning
//----------------------------------------------------------
bool Process::IsRunning() const
{
ASSERT( m_Started );
#if defined( __WINDOWS__ )
switch ( WaitForSingleObject( GetProcessInfo().hProcess, 0 ) )
{
case WAIT_OBJECT_0:
return false;
case WAIT_TIMEOUT:
return true;
}
ASSERT( false ); // we should never get here
return false;
#elif defined( __LINUX__ ) || defined( __APPLE__ )
// already waited?
if ( m_HasAlreadyWaitTerminated )
{
return false;
}
// non-blocking "wait"
int status( -1 );
pid_t result = waitpid( m_ChildPID, &status, WNOHANG );
ASSERT ( result != -1 ); // usage error
if ( result == 0 )
{
return true; // Still running
}
// store wait result: can't call again if we just cleaned up process
ASSERT( result == m_ChildPID );
m_ReturnStatus = WEXITSTATUS(status);
m_HasAlreadyWaitTerminated = true;
return false; // no longer running
#else
#error Unknown platform
#endif
}
// WaitForExit
//------------------------------------------------------------------------------
int Process::WaitForExit()
{
ASSERT( m_Started );
m_Started = false;
#if defined( __WINDOWS__ )
// wait for it to finish
VERIFY( WaitForSingleObject( GetProcessInfo().hProcess, INFINITE ) == WAIT_OBJECT_0 );
// get the result code
DWORD exitCode = 0;
VERIFY( GetExitCodeProcess( GetProcessInfo().hProcess, (LPDWORD)&exitCode ) );
// cleanup
VERIFY( CloseHandle( GetProcessInfo().hProcess ) );
VERIFY( CloseHandle( GetProcessInfo().hThread ) );
if ( !m_SharingHandles && m_RedirectHandles )
{
VERIFY( CloseHandle( m_StdOutRead ) );
VERIFY( CloseHandle( m_StdOutWrite ) );
VERIFY( CloseHandle( m_StdErrRead ) );
VERIFY( CloseHandle( m_StdErrWrite ) );
}
return exitCode;
#elif defined( __LINUX__ ) || defined( __APPLE__ )
VERIFY( close( m_StdOutRead ) == 0 );
VERIFY( close( m_StdErrRead ) == 0 );
if ( m_HasAlreadyWaitTerminated == false )
{
int status;
for( ;; )
{
pid_t ret = waitpid( m_ChildPID, &status, 0 );
if ( ret == -1 )
{
if ( errno == EINTR )
{
continue; // Try again
}
ASSERT( false ); // Usage error
}
ASSERT( ret == m_ChildPID );
m_ReturnStatus = WEXITSTATUS(status);
break;
}
}
return m_ReturnStatus;
#else
#error Unknown platform
#endif
}
// Detach
//------------------------------------------------------------------------------
void Process::Detach()
{
ASSERT( m_Started );
m_Started = false;
#if defined( __WINDOWS__ )
// cleanup
VERIFY( CloseHandle( GetProcessInfo().hProcess ) );
VERIFY( CloseHandle( GetProcessInfo().hThread ) );
if ( !m_SharingHandles && m_RedirectHandles )
{
VERIFY( CloseHandle( m_StdOutRead ) );
VERIFY( CloseHandle( m_StdOutWrite ) );
VERIFY( CloseHandle( m_StdErrRead ) );
VERIFY( CloseHandle( m_StdErrWrite ) );
}
#elif defined( __APPLE__ )
// TODO:MAC Implement Process
#elif defined( __LINUX__ )
ASSERT( false ); // TODO:LINUX Implement Process
#else
#error Unknown platform
#endif
}
// ReadAllData
//------------------------------------------------------------------------------
bool Process::ReadAllData( AutoPtr< char > & outMem, uint32_t * outMemSize,
AutoPtr< char > & errMem, uint32_t * errMemSize,
uint32_t timeOutMS )
{
// we'll capture into these growing buffers
uint32_t outSize = 0;
uint32_t errSize = 0;
uint32_t outBufferSize = 0;
uint32_t errBufferSize = 0;
Timer t;
bool processExited = false;
for ( ;; )
{
uint32_t prevOutSize = outSize;
uint32_t prevErrSize = errSize;
Read( m_StdOutRead, outMem, outSize, outBufferSize );
Read( m_StdErrRead, errMem, errSize, errBufferSize );
// did we get some data?
if ( ( prevOutSize != outSize ) || ( prevErrSize != errSize ) )
{
continue; // try reading again right away incase there is more
}
// nothing to read right now
#if defined( __WINDOWS__ )
if ( processExited == false )
{
DWORD result = WaitForSingleObject( GetProcessInfo().hProcess, 15 );
if ( result == WAIT_TIMEOUT )
{
// Check if timeout is hit
if ( ( timeOutMS > 0 ) && ( t.GetElapsedMS() >= timeOutMS ) )
{
Terminate();
return false; // Timed out
}
continue; // still running - try to read
}
else
{
// exited - will do one more read
ASSERT( result == WAIT_OBJECT_0 );
}
}
#else
if ( IsRunning() )
{
// Check if timeout is hit
if ( ( timeOutMS > 0 ) && ( t.GetElapsedMS() >= timeOutMS ) )
{
Terminate();
return false; // Timed out
}
// no data available, but process is still going, so wait
// TODO:C Replace this sleep with event-based wait
Thread::Sleep( 15 );
continue;
}
#endif
// process exited - is this the first time to this point?
if ( processExited == false )
{
processExited = true;
continue; // get remaining output
}
break; // all done
}
// if owner asks for pointers, they now own the mem
if ( outMemSize ) { *outMemSize = outSize; }
if ( errMemSize ) { *errMemSize = errSize; }
return true;
}
// Read
//------------------------------------------------------------------------------
#if defined( __WINDOWS__ )
void Process::Read( HANDLE handle, AutoPtr< char > & buffer, uint32_t & sizeSoFar, uint32_t & bufferSize )
{
// anything available?
DWORD bytesAvail( 0 );
if ( !::PeekNamedPipe( handle, nullptr, 0, nullptr, (LPDWORD)&bytesAvail, nullptr ) )
{
return;
}
if ( bytesAvail == 0 )
{
return;
}
// will it fit in the buffer we have?
if ( ( sizeSoFar + bytesAvail ) > bufferSize )
{
// no - allocate a bigger buffer (also handles the first time with no buffer)
// TODO:B look at a new container type (like a linked list of 1mb buffers) to avoid the wasteage here
// The caller has to take a copy to avoid the overhead if they want to hang onto the data
// grow buffer in at least 16MB chunks, to prevent future reallocations
uint32_t newBufferSize = Math::Max< uint32_t >( sizeSoFar + bytesAvail, bufferSize + ( 16 * MEGABYTE ) );
char * newBuffer = (char *)ALLOC( newBufferSize + 1 ); // +1 so we can always add a null char
if ( buffer.Get() )
{
// transfer and free old buffer
memcpy( newBuffer, buffer.Get(), sizeSoFar );
}
buffer = newBuffer; // will take care of deletion of old buffer
bufferSize = newBufferSize;
buffer.Get()[ sizeSoFar ] = '\000';
}
ASSERT( sizeSoFar + bytesAvail <= bufferSize ); // sanity check
// read the new data
DWORD bytesReadNow = 0;
if ( !::ReadFile( handle, buffer.Get() + sizeSoFar, bytesAvail, (LPDWORD)&bytesReadNow, 0 ) )
{
return;
}
ASSERT( bytesReadNow == bytesAvail );
sizeSoFar += bytesReadNow;
// keep data null char terminated for caller convenience
buffer.Get()[ sizeSoFar ] = '\000';
}
#endif
// Read
//------------------------------------------------------------------------------
#if defined( __LINUX__ ) || defined( __APPLE__ )
void Process::Read( int handle, AutoPtr< char > & buffer, uint32_t & sizeSoFar, uint32_t & bufferSize )
{
// any data available?
timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 0;
fd_set fdSet;
FD_ZERO( &fdSet );
FD_SET( handle, &fdSet );
int ret = select( handle+1, &fdSet, nullptr, nullptr, &timeout );
if ( ret == -1 )
{
ASSERT( false ); // usage error?
return;
}
if ( ret == 0 )
{
return; // no data available
}
// how much space do we have left for reading into?
uint32_t spaceInBuffer = ( bufferSize - sizeSoFar );
if ( spaceInBuffer == 0 )
{
// allocate a bigger buffer (also handles the first time with no buffer)
// TODO:B look at a new container type (like a linked list of 1mb buffers) to avoid the wasteage here
// The caller has to take a copy to avoid the overhead if they want to hang onto the data
// grow buffer in at least 16MB chunks, to prevent future reallocations
uint32_t newBufferSize = ( sizeSoFar + ( 16 * MEGABYTE ) );
char * newBuffer = (char *)ALLOC( newBufferSize + 1 ); // +1 so we can always add a null char
if ( buffer.Get() )
{
// transfer and free old buffer
memcpy( newBuffer, buffer.Get(), sizeSoFar );
}
buffer = newBuffer; // will take care of deletion of old buffer
bufferSize = newBufferSize;
spaceInBuffer = ( bufferSize - sizeSoFar );
buffer.Get()[ sizeSoFar ] = '\000';
}
// read the new data
ssize_t result = read( handle, buffer.Get() + sizeSoFar, spaceInBuffer );
if ( result == -1 )
{
ASSERT( false ); // error!
return;
}
// account for newly read bytes
sizeSoFar += (uint32_t)result;
// keep data null char terminated for caller convenience
buffer.Get()[ sizeSoFar ] = '\000';
}
#endif
// ReadStdOut
//------------------------------------------------------------------------------
#if defined( __WINDOWS__ )
char * Process::ReadStdOut( uint32_t * bytesRead )
{
return Read( m_StdOutRead, bytesRead );
}
#endif
// ReadStdOut
//------------------------------------------------------------------------------
#if defined( __WINDOWS__ )
char * Process::ReadStdErr( uint32_t * bytesRead )
{
return Read( m_StdErrRead, bytesRead );
}
#endif
// ReadStdOut
//------------------------------------------------------------------------------
#if defined( __WINDOWS__ )
uint32_t Process::ReadStdOut( char * outputBuffer, uint32_t outputBufferSize )
{
return Read( m_StdOutRead, outputBuffer, outputBufferSize );
}
#endif
// ReadStdErr
//------------------------------------------------------------------------------
#if defined( __WINDOWS__ )
uint32_t Process::ReadStdErr( char * outputBuffer, uint32_t outputBufferSize )
{
return Read( m_StdErrRead, outputBuffer, outputBufferSize );
}
#endif
// Read
//------------------------------------------------------------------------------
#if defined( __WINDOWS__ )
char * Process::Read( HANDLE handle, uint32_t * bytesRead )
{
// see if there's anything in the pipe
DWORD bytesAvail;
VERIFY( PeekNamedPipe( handle, nullptr, 0, nullptr, (LPDWORD)&bytesAvail, nullptr ) );
if ( bytesAvail == 0 )
{
if ( bytesRead )
{
*bytesRead = 0;
}
return nullptr;
}
// allocate output buffer
char * mem = (char *)ALLOC( bytesAvail + 1 ); // null terminate for convenience
mem[ bytesAvail ] = 0;
// read the data
DWORD bytesReadNow = 0;
VERIFY( ReadFile( handle, mem, bytesAvail, (LPDWORD)&bytesReadNow, 0 ) );
ASSERT( bytesReadNow == bytesAvail );
if ( bytesRead )
{
*bytesRead = bytesReadNow;
}
return mem;
}
#endif
// Read
//------------------------------------------------------------------------------
#if defined( __WINDOWS__ )
uint32_t Process::Read( HANDLE handle, char * outputBuffer, uint32_t outputBufferSize )
{
// see if there's anything in the pipe
DWORD bytesAvail;
VERIFY( PeekNamedPipe( handle, nullptr, 0, 0, (LPDWORD)&bytesAvail, 0 ) );
if ( bytesAvail == 0 )
{
return 0;
}
// if there is more available than we have space for, just read as much as we can
uint32_t bytesToRead = Math::Min<uint32_t>( outputBufferSize, bytesAvail );
// read the data
DWORD bytesReadNow = 0;
VERIFY( ReadFile( handle, outputBuffer, bytesToRead, (LPDWORD)&bytesReadNow, 0 ) );
ASSERT( bytesReadNow == bytesToRead );
return bytesToRead;
}
#endif
// GetCurrentId
//------------------------------------------------------------------------------
/*static*/ uint32_t Process::GetCurrentId()
{
#if defined( __WINDOWS__ )
return ::GetCurrentProcessId();
#elif defined( __LINUX__ )
return 0; // TODO: Implement GetCurrentId()
#elif defined( __OSX__ )
return 0; // TODO: Implement GetCurrentId()
#endif
}
// Terminate
//------------------------------------------------------------------------------
void Process::Terminate()
{
#if defined( __WINDOWS__ )
VERIFY( ::TerminateProcess( GetProcessInfo().hProcess, 1 ) );
#else
kill( m_ChildPID, SIGKILL );
#endif
}
//------------------------------------------------------------------------------
| [
"franta.fulin@gmail.com"
] | franta.fulin@gmail.com |
3b73241de22a2698a7edb3dda96bf9b37e8d066c | c6175098886ab432b22c25d6b67769952471ad5b | /code/MazeF4/f4rect.h | 18a476a2fc730a825fb38b73f42b2e8ef43074b1 | [] | no_license | AllenOris/Maze-F4 | 1e30321d7118ee4a9f5455f8cfe5ccd6d16b321e | 27fff097cd05aa437e12364b6038abb6586acc60 | refs/heads/master | 2020-03-22T23:04:30.129776 | 2018-07-29T12:56:32 | 2018-07-29T12:56:32 | 140,788,274 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 220 | h | #ifndef F4RECT_H
#define F4RECT_H
#include <QRectF>
class F4rect:public QRectF
{
protected:
int pattern;
public:
F4rect();
F4rect(qreal,qreal,qreal,qreal,int);
bool isobstacle();
};
#endif // F4RECT_H
| [
"34499426+AllenTaken@users.noreply.github.com"
] | 34499426+AllenTaken@users.noreply.github.com |
6e43782eb9a4b27fedd2e9234ce9d38018d7d9ab | 199f9f07bf5be0b9c45751403ce8d6eaedc60df6 | /CollisionsThisFrame.h | e5c586d69640645b93a2ed69e90431483929d79f | [] | no_license | ChocoPuppy/Game-Engine | b5dda3a31dce20c109f940fde0e8a6ab02d76d0f | 4845ffa95bcc3c85628d9f1f0f90aa45728eeeb9 | refs/heads/master | 2023-08-27T04:55:40.329851 | 2021-09-28T03:08:26 | 2021-09-28T03:08:26 | 359,722,719 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 768 | h | #pragma once
#include <map>
#include <set>
#include <type_traits>
namespace Collision
{
struct CollisionData;
class ICollider;
class PhysicsEngine;
struct CollisionsThisFrame : std::map<std::pair<ICollider *, ICollider *>, CollisionData >
{
friend PhysicsEngine;
using ColliderPair = std::pair<ICollider *, ICollider *>;
using BaseMap = std::map<ColliderPair, CollisionData >;
std::set<ColliderPair *> getCollisionsInvolvingCollider( ICollider const * collider ) const;
std::set<ColliderPair> getCollisions();
CollisionData dataOfCollision( ColliderPair key ) const;
private:
mutable std::multimap<ICollider const *, ColliderPair> _associatedCollisionsCache;
CollisionsThisFrame( BaseMap && collisions );
void _recalculateCache();
};
} | [
"7753274+ChocoPuppy@users.noreply.github.com"
] | 7753274+ChocoPuppy@users.noreply.github.com |
6ec3c3a35b4dccec1cfbc6af50abfef5d8687170 | 5c6ccc082d9d0d42a69e22cfd9a419a5b87ff6cd | /coursera/cppYandex/red/week5/split_into_sentences.cpp | b5413021f5c87ec92f2930fb03735a3cfa395094 | [] | no_license | kersky98/stud | 191c809bacc982c715d9610be282884a504d456d | d395a372e72aeb17dfad5c72d46e84dc59454410 | refs/heads/master | 2023-03-09T20:47:25.082673 | 2023-03-01T08:28:32 | 2023-03-01T08:28:32 | 42,979,807 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,801 | cpp | /*Дан вектор токенов. Напишите функцию, разбивающую токены на предложения:
Token — шаблонный тип, про который известно лишь то, что он имеет константный метод
IsEndSentencePunctuation, возвращающий true, если токен является знаком пунктуации, заканчивающим
предложение, и false в противном случае. Объекты этого типа запрещено копировать.
При наличии копирования этих объектов вы получите ошибку компиляции.
Sentence — синоним для типа vector, объявленный следующим образом:
Предложением считается последовательность токенов, заканчивающаяся подряд идущими токенами,
являющимися знаками пунктуации конца предложения. Иными словами, любое предложение должно состоять
из двух частей:
токены, для которых IsEndSentencePunctuation возвращает false (такие токены обязаны присутствовать
в предложении за исключением, возможно, первого предложения);
токены, для которых IsEndSentencePunctuation возвращает true (такие токены обязаны присутствовать
в предложении за исключением, возможно, последнего предложения).
Ограничения
Максимальное количество токенов — 10^6. Время выполнения одного вызова функции ограничено 1 секундой.
*/
#include "test_runner.h"
#include <vector>
using namespace std;
// Объявляем Sentence<Token> для произвольного типа Token
// синонимом vector<Token>.
// Благодаря этому в качестве возвращаемого значения
// функции можно указать не малопонятный вектор векторов,
// а вектор предложений — vector<Sentence<Token>>.
template <typename Token>
using Sentence = vector<Token>;
// Класс Token имеет метод bool IsEndSentencePunctuation() const
template <typename Token>
vector<Sentence<Token>> SplitIntoSentences(vector<Token> tokens) {
// Напишите реализацию функции, не копируя объекты типа Token
vector<Sentence<Token>> vv;
Sentence<Token> v;
for(size_t i = 0; i < tokens.size(); i++){
v.push_back(move(tokens[i]));
if(i<tokens.size()-1 &&
tokens[i].IsEndSentencePunctuation() &&
!tokens[i+1].IsEndSentencePunctuation()){
vv.push_back(move(v));
v.clear();
}
}
if(v.size() > 0){
vv.push_back(move(v));
}
return vv;
}
struct TestToken {
string data;
bool is_end_sentence_punctuation = false;
bool IsEndSentencePunctuation() const {
return is_end_sentence_punctuation;
}
bool operator==(const TestToken& other) const {
return data == other.data && is_end_sentence_punctuation == other.is_end_sentence_punctuation;
}
};
ostream& operator<<(ostream& stream, const TestToken& token) {
return stream << token.data;
}
// Тест содержит копирования объектов класса TestToken.
// Для проверки отсутствия копирований в функции SplitIntoSentences
// необходимо написать отдельный тест.
void TestSplitting() {
ASSERT_EQUAL(
SplitIntoSentences(vector<TestToken>({{"Split"}, {"into"}, {"sentences"}, {"!"}})),
vector<Sentence<TestToken>>({
{{"Split"}, {"into"}, {"sentences"}, {"!"}}
})
);
ASSERT_EQUAL(
SplitIntoSentences(vector<TestToken>({{"Split"}, {"into"}, {"sentences"}, {"!", true}})),
vector<Sentence<TestToken>>({
{{"Split"}, {"into"}, {"sentences"}, {"!", true}}
})
);
ASSERT_EQUAL(
SplitIntoSentences(vector<TestToken>({{"Split"}, {"into"}, {"sentences"}, {"!", true}, {"!", true}, {"Without"}, {"copies"}, {".", true}})),
vector<Sentence<TestToken>>({
{{"Split"}, {"into"}, {"sentences"}, {"!", true}, {"!", true}},
{{"Without"}, {"copies"}, {".", true}},
})
);
}
int main() {
TestRunner tr;
RUN_TEST(tr, TestSplitting);
return 0;
}
| [
"kerskyev@gmail.com"
] | kerskyev@gmail.com |
1d62852a133f45424774720e6ffa7b340d2082b9 | a15950e54e6775e6f7f7004bb90a5585405eade7 | /ash/message_center/message_list_view.cc | 17f53b415071df0abef4567d6bb93403628a6066 | [
"BSD-3-Clause"
] | permissive | whycoding126/chromium | 19f6b44d0ec3e4f1b5ef61cc083cae587de3df73 | 9191e417b00328d59a7060fa6bbef061a3fe4ce4 | refs/heads/master | 2023-02-26T22:57:28.582142 | 2018-04-09T11:12:57 | 2018-04-09T11:12:57 | 128,760,157 | 1 | 0 | null | 2018-04-09T11:17:03 | 2018-04-09T11:17:03 | null | UTF-8 | C++ | false | false | 21,225 | cc | // Copyright (c) 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.
#include "ash/message_center/message_list_view.h"
#include "ash/message_center/message_center_style.h"
#include "ash/message_center/message_center_view.h"
#include "ash/public/cpp/ash_features.h"
#include "ash/public/cpp/ash_switches.h"
#include "base/command_line.h"
#include "base/location.h"
#include "base/single_thread_task_runner.h"
#include "base/stl_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "ui/gfx/animation/slide_animation.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/message_center/public/cpp/message_center_constants.h"
#include "ui/message_center/public/cpp/notification.h"
#include "ui/message_center/views/message_view.h"
#include "ui/views/background.h"
#include "ui/views/border.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/widget/widget.h"
using message_center::MessageView;
using message_center::Notification;
namespace ash {
namespace {
const int kAnimateClearingNextNotificationDelayMS = 40;
bool HasBorderPadding() {
return !switches::IsSidebarEnabled() &&
!features::IsSystemTrayUnifiedEnabled();
}
int GetMarginBetweenItems() {
return HasBorderPadding() ? message_center::kMarginBetweenItemsInList : 0;
}
} // namespace
MessageListView::MessageListView()
: reposition_top_(-1),
fixed_height_(0),
has_deferred_task_(false),
clear_all_started_(false),
animator_(this),
weak_ptr_factory_(this) {
auto layout = std::make_unique<views::BoxLayout>(views::BoxLayout::kVertical,
gfx::Insets(), 1);
layout->SetDefaultFlex(1);
SetLayoutManager(std::move(layout));
if (HasBorderPadding()) {
SetBorder(views::CreateEmptyBorder(
gfx::Insets(message_center::kMarginBetweenItemsInList)));
}
animator_.AddObserver(this);
}
MessageListView::~MessageListView() {
animator_.RemoveObserver(this);
}
void MessageListView::Layout() {
if (animator_.IsAnimating())
return;
gfx::Rect child_area = GetContentsBounds();
int top = child_area.y();
for (int i = 0; i < child_count(); ++i) {
views::View* child = child_at(i);
if (!child->visible())
continue;
int height = child->GetHeightForWidth(child_area.width());
child->SetBounds(child_area.x(), top, child_area.width(), height);
top += height + GetMarginBetweenItems();
}
}
void MessageListView::AddNotificationAt(MessageView* view, int index) {
// |index| refers to a position in a subset of valid children. |real_index|
// in a list includes the invalid children, so we compute the real index by
// walking the list until |index| number of valid children are encountered,
// or to the end of the list.
int real_index = 0;
while (real_index < child_count()) {
if (IsValidChild(child_at(real_index))) {
--index;
if (index < 0)
break;
}
++real_index;
}
if (real_index == 0)
ExpandSpecifiedNotificationAndCollapseOthers(view);
AddChildViewAt(view, real_index);
if (GetContentsBounds().IsEmpty())
return;
adding_views_.insert(view);
DoUpdateIfPossible();
}
void MessageListView::RemoveNotification(MessageView* view) {
DCHECK_EQ(view->parent(), this);
// TODO(yhananda): We should consider consolidating clearing_all_views_,
// deleting_views_ and deleted_when_done_.
if (base::ContainsValue(clearing_all_views_, view) ||
deleting_views_.find(view) != deleting_views_.end() ||
deleted_when_done_.find(view) != deleted_when_done_.end()) {
// Let's skip deleting the view if it's already scheduled for deleting.
// Even if we check clearing_all_views_ here, we actualy have no idea
// whether the view is due to be removed or not because it could be in its
// animation before removal.
// In short, we could delete the view twice even if we check these three
// lists.
return;
}
if (GetContentsBounds().IsEmpty()) {
delete view;
} else {
if (adding_views_.find(view) != adding_views_.end())
adding_views_.erase(view);
if (animator_.IsAnimating(view))
animator_.StopAnimatingView(view);
if (view->layer()) {
deleting_views_.insert(view);
} else {
delete view;
}
DoUpdateIfPossible();
}
int index = GetIndexOf(view);
if (index == 0)
ExpandTopNotificationAndCollapseOthers();
}
void MessageListView::UpdateNotification(MessageView* view,
const Notification& notification) {
// Skip updating the notification being cleared.
if (base::ContainsValue(clearing_all_views_, view))
return;
int index = GetIndexOf(view);
DCHECK_LE(0, index); // GetIndexOf is negative if not a child.
if (index == 0)
ExpandSpecifiedNotificationAndCollapseOthers(view);
animator_.StopAnimatingView(view);
if (deleting_views_.find(view) != deleting_views_.end())
deleting_views_.erase(view);
if (deleted_when_done_.find(view) != deleted_when_done_.end())
deleted_when_done_.erase(view);
view->UpdateWithNotification(notification);
DoUpdateIfPossible();
}
std::pair<int, MessageView*> MessageListView::GetNotificationById(
const std::string& id) {
for (int i = child_count() - 1; i >= 0; --i) {
MessageView* view = static_cast<MessageView*>(child_at(i));
if (view->notification_id() == id && IsValidChild(view))
return std::make_pair(i, view);
}
return std::make_pair(-1, nullptr);
}
MessageView* MessageListView::GetNotificationAt(int index) {
for (int i = child_count() - 1; i >= 0; --i) {
MessageView* view = static_cast<MessageView*>(child_at(i));
if (IsValidChild(view)) {
if (index == 0)
return view;
index--;
}
}
return nullptr;
}
size_t MessageListView::GetNotificationCount() const {
int count = 0;
for (int i = child_count() - 1; i >= 0; --i) {
const MessageView* view = static_cast<const MessageView*>(child_at(i));
if (IsValidChild(view))
count++;
}
return count;
}
gfx::Size MessageListView::CalculatePreferredSize() const {
// Just returns the current size. All size change must be done in
// |DoUpdateIfPossible()| with animation , because we don't want to change
// the size in unexpected timing.
return size();
}
int MessageListView::GetHeightForWidth(int width) const {
if (fixed_height_ > 0)
return fixed_height_;
width -= GetInsets().width();
int height = 0;
int padding = 0;
for (int i = 0; i < child_count(); ++i) {
const views::View* child = child_at(i);
if (!IsValidChild(child))
continue;
height += child->GetHeightForWidth(width) + padding;
padding = GetMarginBetweenItems();
}
return height + GetInsets().height();
}
void MessageListView::PaintChildren(const views::PaintInfo& paint_info) {
// Paint in the inversed order. Otherwise upper notification may be
// hidden by the lower one.
for (int i = child_count() - 1; i >= 0; --i) {
if (!child_at(i)->layer())
child_at(i)->Paint(paint_info);
}
}
void MessageListView::ReorderChildLayers(ui::Layer* parent_layer) {
// Reorder children to stack the last child layer at the top. Otherwise
// upper notification may be hidden by the lower one.
for (int i = 0; i < child_count(); ++i) {
if (child_at(i)->layer())
parent_layer->StackAtBottom(child_at(i)->layer());
}
}
void MessageListView::UpdateFixedHeight(int requested_height,
bool prevent_scroll) {
int previous_fixed_height = fixed_height_;
int min_height;
// When the |prevent_scroll| flag is set, we use |fixed_height_|, which is the
// bottom position of the visible rect. It's to keep the current visible
// window, in other words, not to be scrolled, when the visible rect has a
// blank area at the bottom.
// Otherwise (in else block), we use the height of the visible rect to make
// the height of the message list as small as possible.
if (prevent_scroll) {
// TODO(yoshiki): Consider the case with scrolling. If the message center
// has scrollbar and its height is maximum, we may not need to keep the
// height of the list in the scroll view.
min_height = fixed_height_;
} else {
if (scroller_) {
gfx::Rect visible_rect = scroller_->GetVisibleRect();
min_height = visible_rect.height();
} else {
// Fallback for testing.
min_height = fixed_height_;
}
}
fixed_height_ = std::max(min_height, requested_height);
if (previous_fixed_height != fixed_height_) {
PreferredSizeChanged();
}
}
void MessageListView::SetRepositionTarget(const gfx::Rect& target) {
reposition_top_ = std::max(target.y(), 0);
UpdateFixedHeight(GetHeightForWidth(width()), false);
}
void MessageListView::ResetRepositionSession() {
// Don't call DoUpdateIfPossible(), but let Layout() do the task without
// animation. Reset will cause the change of the bubble size itself, and
// animation from the old location will look weird.
if (reposition_top_ >= 0) {
has_deferred_task_ = false;
// cancel cause OnBoundsAnimatorDone which deletes |deleted_when_done_|.
animator_.Cancel();
for (auto* view : deleting_views_)
delete view;
deleting_views_.clear();
adding_views_.clear();
}
reposition_top_ = -1;
UpdateFixedHeight(fixed_height_, false);
}
void MessageListView::ClearAllClosableNotifications(
const gfx::Rect& visible_scroll_rect) {
for (int i = 0; i < child_count(); ++i) {
// Safe cast since all views in MessageListView are MessageViews.
MessageView* child = static_cast<MessageView*>(child_at(i));
if (!child->visible())
continue;
if (gfx::IntersectRects(child->bounds(), visible_scroll_rect).IsEmpty())
continue;
if (child->GetPinned())
continue;
if (deleting_views_.find(child) != deleting_views_.end() ||
deleted_when_done_.find(child) != deleted_when_done_.end()) {
// We don't check clearing_all_views_ here, so this can lead to a
// notification being deleted twice. Even if we do check it, there is a
// problem similar to the problem in RemoveNotification(), it could be
// currently in its animation before removal, and we could similarly
// delete it twice. This is a bug.
continue;
}
clearing_all_views_.push_back(child);
}
if (clearing_all_views_.empty()) {
for (auto& observer : observers_)
observer.OnAllNotificationsCleared();
} else {
DoUpdateIfPossible();
}
}
void MessageListView::AddObserver(MessageListView::Observer* observer) {
observers_.AddObserver(observer);
}
void MessageListView::RemoveObserver(MessageListView::Observer* observer) {
observers_.RemoveObserver(observer);
}
void MessageListView::OnBoundsAnimatorProgressed(
views::BoundsAnimator* animator) {
DCHECK_EQ(&animator_, animator);
for (auto* view : deleted_when_done_) {
const gfx::SlideAnimation* animation = animator->GetAnimationForView(view);
if (animation)
view->layer()->SetOpacity(animation->CurrentValueBetween(1.0, 0.0));
}
}
void MessageListView::OnBoundsAnimatorDone(views::BoundsAnimator* animator) {
// It's possible for the delayed task that queues the next animation for
// clearing all notifications to be delayed more than we want. In this case,
// the BoundsAnimator can finish while a clear all is still happening. So,
// explicitly check if |clearing_all_views_| is empty.
if (clear_all_started_ && !clearing_all_views_.empty()) {
return;
}
bool need_update = false;
if (clear_all_started_) {
clear_all_started_ = false;
for (auto& observer : observers_)
observer.OnAllNotificationsCleared();
// Just return here if new animation is initiated in the above observers,
// since the code below assumes no animation is running. In the current
// impelementation, the observer tries removing the notification and their
// views and starts animation if the message center keeps opening.
// The code below will be executed when the new animation is finished.
if (animator_.IsAnimating())
return;
}
// None of these views should be deleted.
DCHECK(std::all_of(deleted_when_done_.begin(), deleted_when_done_.end(),
[this](views::View* view) { return Contains(view); }));
for (auto* view : deleted_when_done_)
delete view;
deleted_when_done_.clear();
if (has_deferred_task_) {
has_deferred_task_ = false;
need_update = true;
}
if (need_update)
DoUpdateIfPossible();
if (GetWidget())
GetWidget()->SynthesizeMouseMoveEvent();
}
bool MessageListView::IsValidChild(const views::View* child) const {
return child->visible() &&
deleting_views_.find(const_cast<views::View*>(child)) ==
deleting_views_.end() &&
deleted_when_done_.find(const_cast<views::View*>(child)) ==
deleted_when_done_.end() &&
!base::ContainsValue(clearing_all_views_, child);
}
void MessageListView::DoUpdateIfPossible() {
gfx::Rect child_area = GetContentsBounds();
if (child_area.IsEmpty())
return;
if (animator_.IsAnimating()) {
has_deferred_task_ = true;
return;
}
// Start the clearing all animation if necessary.
if (!clearing_all_views_.empty() && !clear_all_started_) {
AnimateClearingOneNotification();
return;
}
// Skip during the clering all animation.
// This checks |clear_all_started_! rather than |clearing_all_views_|, since
// the latter is empty during the animation of the last element.
if (clear_all_started_) {
DCHECK(!clearing_all_views_.empty());
return;
}
AnimateNotifications();
// Should calculate and set new size after calling AnimateNotifications()
// because fixed_height_ may be updated in it.
int new_height = GetHeightForWidth(child_area.width() + GetInsets().width());
SetSize(gfx::Size(child_area.width() + GetInsets().width(), new_height));
adding_views_.clear();
deleting_views_.clear();
if (!animator_.IsAnimating() && GetWidget())
GetWidget()->SynthesizeMouseMoveEvent();
}
void MessageListView::ExpandSpecifiedNotificationAndCollapseOthers(
message_center::MessageView* target_view) {
if (!target_view->IsManuallyExpandedOrCollapsed() &&
target_view->IsAutoExpandingAllowed()) {
target_view->SetExpanded(true);
}
for (int i = 0; i < child_count(); ++i) {
MessageView* view = static_cast<MessageView*>(child_at(i));
// Target view is already processed above.
if (target_view == view)
continue;
// Skip if the view is invalid.
if (!IsValidChild(view))
continue;
// We don't touch if the view has been manually expanded or collapsed.
if (view->IsManuallyExpandedOrCollapsed())
continue;
// Otherwise, collapse the notification.
view->SetExpanded(false);
}
}
void MessageListView::ExpandTopNotificationAndCollapseOthers() {
MessageView* top_notification = nullptr;
for (int i = 0; i < child_count(); ++i) {
MessageView* view = static_cast<MessageView*>(child_at(i));
if (!IsValidChild(view))
continue;
top_notification = view;
break;
}
if (top_notification != nullptr)
ExpandSpecifiedNotificationAndCollapseOthers(top_notification);
}
std::vector<int> MessageListView::ComputeRepositionOffsets(
const std::vector<int>& heights,
const std::vector<bool>& deleting,
int target_index,
int padding) {
DCHECK_EQ(heights.size(), deleting.size());
// Calculate the vertical length between the top of message list and the top
// of target. This is to shrink or expand the height of the message list
// when the notifications above the target is changed.
int vertical_gap_to_target_from_top = GetInsets().top();
for (int i = 0; i < target_index; i++) {
if (!deleting[i])
vertical_gap_to_target_from_top += heights[i] + padding;
}
// If the calculated length is expanded from |repositon_top_|, it means that
// some of items above the target are updated and their height increased.
// Adjust the vertical length above the target.
if (vertical_gap_to_target_from_top > reposition_top_) {
fixed_height_ += vertical_gap_to_target_from_top - reposition_top_;
reposition_top_ = vertical_gap_to_target_from_top;
}
// TODO(yoshiki): Scroll the parent container to keep the physical position
// of the target notification when the scrolling is caused by a size change
// of notification above.
std::vector<int> positions;
positions.reserve(heights.size());
// Layout the items above the target.
int y = GetInsets().top();
for (int i = 0; i < target_index; i++) {
positions.push_back(y);
if (!deleting[i])
y += heights[i] + padding;
}
DCHECK_EQ(y, vertical_gap_to_target_from_top);
DCHECK_LE(y, reposition_top_);
// Match the top with |reposition_top_|.
y = reposition_top_;
// Layout the target and the items below the target.
for (int i = target_index; i < int(heights.size()); i++) {
positions.push_back(y);
if (!deleting[i])
y += heights[i] + padding;
}
// Update the fixed height. |requested_height| is the height to have all
// notifications in the list and to keep the vertical position of the target
// notification. It may not just a total of all the notification heights if
// the target exists.
int requested_height = y - padding + GetInsets().bottom();
UpdateFixedHeight(requested_height, true);
return positions;
}
void MessageListView::AnimateNotifications() {
int target_index = -1;
int padding = GetMarginBetweenItems();
gfx::Rect child_area = GetContentsBounds();
if (reposition_top_ >= 0) {
// Find the target item.
for (int i = 0; i < child_count(); ++i) {
views::View* child = child_at(i);
if (child->y() >= reposition_top_ &&
deleting_views_.find(child) == deleting_views_.end()) {
// Find the target.
target_index = i;
break;
}
}
}
if (target_index != -1) {
std::vector<int> heights;
std::vector<bool> deleting;
heights.reserve(child_count());
deleting.reserve(child_count());
for (int i = 0; i < child_count(); i++) {
views::View* child = child_at(i);
heights.push_back(child->GetHeightForWidth(child_area.width()));
deleting.push_back(deleting_views_.find(child) != deleting_views_.end());
}
std::vector<int> ys =
ComputeRepositionOffsets(heights, deleting, target_index, padding);
for (int i = 0; i < child_count(); ++i) {
bool above_target = (i < target_index);
AnimateChild(child_at(i), ys[i], heights[i],
!above_target /* animate_on_move */);
}
} else {
// Layout all the items.
int y = GetInsets().top();
for (int i = 0; i < child_count(); ++i) {
views::View* child = child_at(i);
int height = child->GetHeightForWidth(child_area.width());
if (AnimateChild(child, y, height, true))
y += height + padding;
}
int new_height = y - padding + GetInsets().bottom();
UpdateFixedHeight(new_height, false);
}
}
bool MessageListView::AnimateChild(views::View* child,
int top,
int height,
bool animate_on_move) {
// Do not call this during clearing all animation.
DCHECK(clearing_all_views_.empty());
DCHECK(!clear_all_started_);
gfx::Rect child_area = GetContentsBounds();
if (adding_views_.find(child) != adding_views_.end()) {
child->SetBounds(child_area.right(), top, child_area.width(), height);
animator_.AnimateViewTo(
child, gfx::Rect(child_area.x(), top, child_area.width(), height));
} else if (deleting_views_.find(child) != deleting_views_.end()) {
DCHECK(child->layer());
// No moves, but animate to fade-out.
animator_.AnimateViewTo(child, child->bounds());
deleted_when_done_.insert(child);
return false;
} else {
gfx::Rect target(child_area.x(), top, child_area.width(), height);
if (child->origin() != target.origin() && animate_on_move)
animator_.AnimateViewTo(child, target);
else
child->SetBoundsRect(target);
}
return true;
}
void MessageListView::AnimateClearingOneNotification() {
DCHECK(!clearing_all_views_.empty());
clear_all_started_ = true;
views::View* child = clearing_all_views_.front();
clearing_all_views_.pop_front();
// Slide from left to right.
gfx::Rect new_bounds = child->bounds();
new_bounds.set_x(new_bounds.right() + GetMarginBetweenItems());
animator_.AnimateViewTo(child, new_bounds);
// Schedule to start sliding out next notification after a short delay.
if (!clearing_all_views_.empty()) {
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(&MessageListView::AnimateClearingOneNotification,
weak_ptr_factory_.GetWeakPtr()),
base::TimeDelta::FromMilliseconds(
kAnimateClearingNextNotificationDelayMS));
}
}
} // namespace ash
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
a4da74d544fc3bfb8443dce679f752a32459c5d9 | 0d423538336b5067781fb76c0fb6ac1daa3d0ccb | /1_NMLT/ThucHanh-T6/MangSoThuc/main.cpp | 9ee77bd7ee2660201a416d211e14eb9b873e8b42 | [
"MIT"
] | permissive | NhatPhuong02/HCMUS-Lectures | 73f098c6322133116dc9f57423f1433bf32a5730 | b376e144e2601a73684e2ff437ab5c94a943909c | refs/heads/master | 2022-01-13T01:52:40.707561 | 2018-06-16T17:22:19 | 2018-06-16T17:22:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,982 | cpp | // MSSV: 1612
// Ho ten: Nguyen Tran Hau
// Bai tap mang so thuc
#include "MangSoThuc.h"
int main(void)
{
float arr[MAX], arr2[MAX];
float x;
int len_mang, len2, k;
printf("Bai tap mang so thuc.\n");
nhap_mang(arr, len_mang); // Bai 128
xuat_mang(arr, len_mang); // Bai 130
lke_vt_am(arr, len_mang); // Bai 133
printf("Gia tri lon nhat cua mang: %0.2f\n",
lon_nhat(arr, len_mang)); // Bai 134
printf("Gia tri duong dau tien cua mang: %0.2f\n",
duong_dau(arr, len_mang)); // Bai 135
printf("Vi tri gia tri nho nhat cua mang: vi tri thu %d\n",
vi_tri_nho_nhat(arr, len_mang)); // Bai 137
printf("Gia tri duong nho nhat cua mang: %0.2f\n",
duong_nho_nhat(arr, len_mang)); // Bai 140
printf("Gia tri nho nhat cua mang: %0.2f\n",
nho_nhat(arr, len_mang)); // Bai 142
printf("Gia tri am lon nhat cua mang: %0.2f\n",
am_lon_nhat(arr, len_mang)); // Bai 150
printf("Vi tri gia tri am lon nhat cua mang: vi tri thu %d\n",
vt_am_lon_nhat(arr, len_mang)); // Bai 154
printf("Nhap x (trong bai 155): ");
scanf("%f", &x);
printf("Gia tri trong mang xa x nhat: %0.2f\n",
xa_nhat(x, arr, len_mang)); // Bai 155
tim_doan(arr, len_mang); // Bai 157
printf("Doan: [-%0.2f,%0.2f]\n", tim_x(arr, len_mang),
tim_x(arr, len_mang)); // Bai 158
printf("Gia tri am cuoi cung lon hon -1 cua mang: %0.2f\n",
cuoi_cung(arr, len_mang)); // Bai 160
lke_cap(arr, len_mang); // Bai 174
gan_nhau_nhat(arr, len_mang); // Bai 175
liet_ke_am(arr, len_mang); // Bai 176
lke_180(arr, len_mang); // Bai 180
lke_vtri_lon_nhat(arr, len_mang); // Bai 183
lke_duong_nho_nhat(arr, len_mang); // Bai 187
lke_a_b_c(arr, len_mang); // Bai 195
printf("Tong cac gia tri cua mang: %0.2f\n",
tong(arr, len_mang)); // Bai 200
printf("Tong cac gia tri lon hon gia tri lien truoc no: %0.2f\n",
tong_204(arr, len_mang)); // Bai 204
printf("Tong cac gia tri lon hon tri tuyet doi gia tri lien sau no: "
"%0.2f\n",
tong_205(arr, len_mang)); // Bai 205
printf("Tong cac gia tri lon gia tri xung quang: %0.2f\n",
tong_cuc_dai(arr, len_mang)); // Bai 206
printf("Nhap x (Bai 213): ");
scanf("%f", &x);
printf("Trung binh cong cac gia tri lon hon %0.2f: %0.2f\n", x,
tbc_lon_hon(x, arr, len_mang)); // Bai 213
printf("Khoang cach trung binh giua cac gia tri trong mang: %0.2f\n",
khoang_cach_tb(arr, len_mang)); // Bai 215
printf("Nhap x (Bai 219): ");
scanf("%f", &x);
printf("Tan suat cua %0.2f: %d\n", x,
tan_suat(x, arr, len_mang)); // Bai 219
dem_cuc_tri(arr, len_mang); // Bai 222
printf("So gia tri lon nhat: %d\n",
dem_lon_nhat(arr, len_mang)); // Bai 225
printf("So gia tri ke nhau, cung dau, tri tuyet doi so lien sau lon "
"hon so lien truoc: %d\n",
dem_gia_tri(arr, len_mang)); // Bai 228
printf("So cac gia tri phan biet: %d\n",
dem_phan_biet(arr, len_mang)); // Bai 229
lke_khong_duy_nhat(arr, len_mang); // Bai 232
lke_tan_suat(arr, len_mang); // Bai 233
nhap_mang(arr2, len2);
printf("So luong gia tri chi xuat hien mot trong hai mang: %d\n",
dem_gia_tri_xuat_hien(arr, len_mang, arr2, len2)); // Bai 234
lke_gia_tri_xuat_hien(arr, len_mang, arr2, len2); // Bai 235
printf("Kiem tra tinh tang dan: %d\n",
tang_dan(arr, len_mang)); // Bai 248
printf("Kiem tra mang dang song: %d\n",
ktra_dang_song(arr, len_mang)); // Bai 252
printf("Nhap mang (Bai 253): ");
nhap_mang(arr2, len2);
printf("Mang truoc nam trong mang sau: %d\n",
ktra_a_trong_b(arr, len_mang, arr2, len2)); // Bai 253
printf("So cac gia tri trong mang lon hon moi gia tri dung dang truoc "
"no: %d\n",
dem_lon_truoc(arr, len_mang)); // Bai 254
sap_xep_tang(arr, len_mang); // Bai 255
printf("Mang tang dan: \n");
xuat_mang(arr, len_mang);
printf("Nhap mang (Bai 260): \n");
nhap_mang(arr2, len2);
printf("Kiem tra mang 1 mang 2 co phai la hoan vi: %d\n",
ktra_hoanvi(arr, len_mang, arr2, len2)); // Bai 260
sap_xep_duong(arr, len_mang); // Bai 261
duong_tang_am_giam(arr, len_mang); // Bai 263
printf("Nhap mang (Bai 264): \n");
nhap_mang(arr2, len2);
tron_mang(arr, len_mang, arr2, len2); // Bai 264
them_vi_tri(x, k, arr, len_mang); // Bai 266
nhap_giam_dan(arr, len_mang);
printf("Nhap x (Bai 269): ");
scanf("%f", &x);
them_bao_toan(x, arr, len_mang); // Bai 269
xoa_lon_nhat(arr, len_mang); // Bai 272
xoa_trung(arr, len_mang); // Bai 278
xoa_trung_tat_ca(arr, len_mang); // Bai 279
dao_nguoc(arr, len_mang); // Bai 283
nguyen_hoa(arr, len_mang);
tao_mang_am(arr, len_mang, arr2, len2); // Bai 308
tao_mang_lan_can(arr, len_mang, arr2, len2); // Bai 309
lke_con_tang(arr, len_mang); // Bai 295
lke_con_lon_nhat(arr, len_mang); // Bai 296
return 0;
} | [
"hauvipapro@gmail.com"
] | hauvipapro@gmail.com |
c4061c1f932b608807c68bc91eea92c461e34fa9 | 376411fef9e7a0a502dce12cca96ecb387363484 | /pytorch/third_party/tensorpipe/tensorpipe/util/ringbuffer/producer.h | 35db39868e01176a991bf25e702992ad371350db | [
"BSD-3-Clause",
"BSL-1.0",
"BSD-Source-Code",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"LicenseRef-scancode-generic-cla"
] | permissive | sugangsky/example | 46914984f419915cb7f94a1ea07c10e6875f2d42 | 647a05613fb7135f8333235c111b6950474cc964 | refs/heads/master | 2023-03-30T08:27:48.974146 | 2021-03-30T09:00:53 | 2021-03-30T09:00:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,639 | h | /*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <tensorpipe/util/ringbuffer/ringbuffer.h>
namespace tensorpipe {
namespace util {
namespace ringbuffer {
///
/// Producer of data for a RingBuffer.
///
/// Provides methods to write data into a ringbuffer.
///
class Producer {
public:
Producer() = delete;
explicit Producer(RingBuffer& rb)
: header_{rb.getHeader()}, data_{rb.getData()} {
TP_THROW_IF_NULLPTR(data_);
}
Producer(const Producer&) = delete;
Producer(Producer&&) = delete;
Producer& operator=(const Producer&) = delete;
Producer& operator=(Producer&&) = delete;
~Producer() noexcept {
TP_THROW_ASSERT_IF(inTx());
}
size_t getSize() const {
return header_.kDataPoolByteSize;
}
//
// Transaction based API.
//
// Only one writer can have an active transaction at any time.
// *InTx* operations that fail do not cancel transaction.
//
bool inTx() const noexcept {
return inTx_;
}
[[nodiscard]] ssize_t startTx() noexcept {
if (unlikely(inTx())) {
return -EBUSY;
}
if (header_.beginWriteTransaction()) {
return -EAGAIN;
}
inTx_ = true;
TP_DCHECK_EQ(txSize_, 0);
return 0;
}
[[nodiscard]] ssize_t commitTx() noexcept {
if (unlikely(!inTx())) {
return -EINVAL;
}
header_.incHead(txSize_);
txSize_ = 0;
// <inWriteTx_> flags that we are in a transaction,
// so enforce no stores pass it.
inTx_ = false;
header_.endWriteTransaction();
return 0;
}
[[nodiscard]] ssize_t cancelTx() noexcept {
if (unlikely(!inTx())) {
return -EINVAL;
}
txSize_ = 0;
// <inWriteTx_> flags that we are in a transaction,
// so enforce no stores pass it.
inTx_ = false;
header_.endWriteTransaction();
return 0;
}
struct Buffer {
uint8_t* ptr{nullptr};
size_t len{0};
};
// The first item is negative in case of error, otherwise it contains how many
// elements of the array are valid (0, 1 or 2). The elements are ptr+len pairs
// of contiguous areas of the ringbuffer that, chained together, represent a
// slice of the requested size (or less if not enough data is available, and
// AllowPartial is set to true).
template <bool AllowPartial>
[[nodiscard]] std::pair<ssize_t, std::array<Buffer, 2>> accessContiguousInTx(
size_t size) noexcept {
std::array<Buffer, 2> result;
if (unlikely(!inTx())) {
return {-EINVAL, result};
}
if (unlikely(size == 0)) {
return {0, result};
}
const uint64_t head = header_.readHead();
const uint64_t tail = header_.readTail();
TP_DCHECK_LE(head - tail, header_.kDataPoolByteSize);
const size_t avail = header_.kDataPoolByteSize - (head - tail) - txSize_;
TP_DCHECK_GE(avail, 0);
if (!AllowPartial && avail < size) {
return {-ENOSPC, result};
}
if (avail == 0) {
return {0, result};
}
size = std::min(size, avail);
const uint64_t start = (head + txSize_) & header_.kDataModMask;
const uint64_t end = (start + size) & header_.kDataModMask;
txSize_ += size;
// end == 0 is the same as end == bufferSize, in which case it doesn't wrap.
const bool wrap = (start >= end && end > 0);
if (likely(!wrap)) {
result[0] = {.ptr = data_ + start, .len = size};
return {1, result};
} else {
result[0] = {
.ptr = data_ + start, .len = header_.kDataPoolByteSize - start};
result[1] = {.ptr = data_, .len = end};
return {2, result};
}
}
// Copy data from the provided buffer into the ringbuffer, up to the given
// size (only copy less data if AllowPartial is set to true).
template <bool AllowPartial>
[[nodiscard]] ssize_t writeInTx(
const void* buffer,
const size_t size) noexcept {
ssize_t numBuffers;
std::array<Buffer, 2> buffers;
std::tie(numBuffers, buffers) = accessContiguousInTx<AllowPartial>(size);
if (unlikely(numBuffers < 0)) {
return numBuffers;
}
if (unlikely(numBuffers == 0)) {
// Nothing to do.
return 0;
} else if (likely(numBuffers == 1)) {
std::memcpy(buffers[0].ptr, buffer, buffers[0].len);
return buffers[0].len;
} else if (likely(numBuffers == 2)) {
std::memcpy(buffers[0].ptr, buffer, buffers[0].len);
std::memcpy(
buffers[1].ptr,
reinterpret_cast<const uint8_t*>(buffer) + buffers[0].len,
buffers[1].len);
return buffers[0].len + buffers[1].len;
} else {
TP_THROW_ASSERT() << "Bad number of buffers: " << numBuffers;
// Dummy return to make the compiler happy.
return -EINVAL;
}
}
//
// High-level atomic operations.
//
// Copy data from the provided buffer into the ringbuffer, exactly the given
// size. Take care of opening and closing the transaction.
[[nodiscard]] ssize_t write(const void* buffer, size_t size) noexcept {
auto ret = startTx();
if (0 > ret) {
return ret;
}
ret = writeInTx</*AllowPartial=*/false>(buffer, size);
if (0 > ret) {
auto r = cancelTx();
TP_DCHECK_EQ(r, 0);
return ret;
}
TP_DCHECK_EQ(ret, size);
ret = commitTx();
TP_DCHECK_EQ(ret, 0);
return size;
}
private:
RingBufferHeader& header_;
uint8_t* const data_;
unsigned txSize_ = 0;
bool inTx_{false};
};
} // namespace ringbuffer
} // namespace util
} // namespace tensorpipe
| [
"sugangsky@gmail.com"
] | sugangsky@gmail.com |
44c085b67dda1e03bd659fbf61db7a6c4831347e | 22ee7658700691218e586d90837d491e2c64a89d | /src/fcst/GUI/contrib/parameter_delegate.h | a6cbd83af8cde31fba38f7856fe759a6828f20a1 | [
"MIT",
"DOC"
] | permissive | Aslan-Kosakian/OpenFCSTv03 | 1099cf8468aa868d788dff334596448fe0449076 | 00a721a58341b287b52cec36bfaff741fd3a7ee3 | refs/heads/master | 2021-01-12T09:37:33.261888 | 2017-01-16T17:05:49 | 2017-01-16T17:05:49 | 76,203,415 | 0 | 0 | null | 2016-12-11T22:15:03 | 2016-12-11T22:15:03 | null | UTF-8 | C++ | false | false | 4,583 | h | // ---------------------------------------------------------------------
// $Id: parameter_delegate.h 2226 2014-04-04 21:21:00Z secanell $
//
// Copyright (C) 2010 - 2013 by Martin Steigemann and Wolfgang Bangerth
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
#ifndef PARAMETERDELEGATE_H
#define PARAMETERDELEGATE_H
#include <QItemDelegate>
#include <QModelIndex>
#include <QObject>
#include <QLineEdit>
#include <QComboBox>
#include <QFileDialog>
#include "browse_lineedit.h"
namespace dealii
{
/*! @addtogroup ParameterGui
*@{
*/
namespace ParameterGui
{
/**
* The ParameterDelegate class implements special delegates for the QTreeWidget class used in the parameterGUI.
* The QTreeWidget class provides some different standard delegates for editing parameters shown in the
* tree structure. The ParameterDelegate class provides special editors for the different types of parameters defined in
* the ParameterHandler class. For all parameter types based on strings as "Anything", "MultipleSelection" "Map" and
* "List" a simple line editor will be shown up. In the case of integer and double type parameters the editor is a spin box and for
* "Selection" type parameters a combo box will be shown up. For parameters of type "FileName" and "DirectoryName"
* the delegate shows a @ref BrowseLineEdit editor. The column of the tree structure with the parameter values has to be set
* in the constructor.
*
* @note This class is used in the graphical user interface for the @ref ParameterHandler class.
* It is not compiled into the deal.II libraries and can not be used by applications using deal.II.
*
* @ingroup ParameterGui
* @author Martin Steigemann, Wolfgang Bangerth, 2010
*/
class ParameterDelegate : public QItemDelegate
{
Q_OBJECT
public:
/**
* Constructor, @p value_column specifies the column
* of the parameter tree this delegate will be used on.
*/
ParameterDelegate (const int value_column, QObject *parent = 0);
/**
* This function creates the appropriate editor for the parameter
* based on the <tt>index</tt>.
*/
QWidget * createEditor(QWidget *parent, const QStyleOptionViewItem &option,
const QModelIndex &index) const;
/**
* Reimplemented from QItemDelegate.
*/
QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const;
/**
* Reimplemented from QItemDelegate.
*/
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
/**
* Reimplemented from QItemDelegate.
*/
void setEditorData(QWidget *editor, const QModelIndex &index) const;
/**
* Reimplemented from QItemDelegate.
*/
void setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const;
private slots:
/**
* Reimplemented from QItemDelegate.
*/
void commit_and_close_editor();
private:
/**
* The column this delegate will be used on.
*/
int value_column;
/**
* For parameters of type <tt>double</tt> a spin box
* will be shown as editor. Any click on the spin box
* will change the value about <tt>double_steps</tt>.
*/
double double_steps;
/**
* For parameters of type <tt>integer</tt> a spin box
* will be shown as editor. Any click on the spin box
* will change the value about <tt>int_steps</tt>.
*/
unsigned int int_steps;
/**
* For parameters of type <tt>double</tt> a spin box
* will be shown as editor. The spin box will show
* parameters with a precision of <tt>double_decimals</tt>.
*/
unsigned int double_decimals;
};
}
/**@}*/
}
#endif
| [
"secanell@ualberta.ca"
] | secanell@ualberta.ca |
36f28005761bf9a6d2d5b61ca01bbbd1f0d65e82 | 088a7e176cccee1f9fa0ed3c1c9fa3267dc0648b | /src/lidarOptimization.cpp | f3d6b6cbac70c797c44bca76d8aeeb6e6ff47058 | [
"BSD-3-Clause"
] | permissive | chang-hun0820/FLOAM_ssl | 079a4ebbc9a89eb1c54ecaffcd78289ef8a75e12 | a4a35b8a7c5a47b97a1a95be5f01338991b38d59 | refs/heads/master | 2022-12-05T13:02:07.500301 | 2020-08-08T10:23:44 | 2020-08-08T10:23:44 | 286,672,847 | 1 | 0 | BSD-3-Clause | 2020-08-11T07:12:38 | 2020-08-11T07:12:37 | null | UTF-8 | C++ | false | false | 5,117 | cpp | // Author of FLOAM: Wang Han
// Email wh200720041@gmail.com
// Homepage https://wanghan.pro
#include "lidarOptimization.h"
EdgeAnalyticCostFunction::EdgeAnalyticCostFunction(Eigen::Vector3d curr_point_, Eigen::Vector3d last_point_a_, Eigen::Vector3d last_point_b_)
: curr_point(curr_point_), last_point_a(last_point_a_), last_point_b(last_point_b_){
}
bool EdgeAnalyticCostFunction::Evaluate(double const *const *parameters, double *residuals, double **jacobians) const
{
Eigen::Map<const Eigen::Quaterniond> q_last_curr(parameters[0]);
Eigen::Map<const Eigen::Vector3d> t_last_curr(parameters[0] + 4);
Eigen::Vector3d lp;
lp = q_last_curr * curr_point + t_last_curr; //new point
Eigen::Vector3d nu = (lp - last_point_a).cross(lp - last_point_b);
Eigen::Vector3d de = last_point_a - last_point_b;
residuals[0] = nu.x() / de.norm();
residuals[1] = nu.y() / de.norm();
residuals[2] = nu.z() / de.norm();
if(jacobians != NULL)
{
if(jacobians[0] != NULL)
{
Eigen::Matrix3d skew_lp = skew(lp);
Eigen::Matrix<double, 3, 6> dp_by_so3;
dp_by_so3.block<3,3>(0,0) = -skew_lp;
(dp_by_so3.block<3,3>(0, 3)).setIdentity();
Eigen::Map<Eigen::Matrix<double, 3, 7, Eigen::RowMajor> > J_se3(jacobians[0]);
J_se3.setZero();
Eigen::Vector3d re = last_point_b - last_point_a;
Eigen::Matrix3d skew_re = skew(re);
J_se3.block<3,6>(0,0) = skew_re * dp_by_so3/de.norm();
}
}
return true;
}
//surf norm cost
SurfNormAnalyticCostFunction::SurfNormAnalyticCostFunction(Eigen::Vector3d curr_point_, Eigen::Vector3d plane_unit_norm_, double negative_OA_dot_norm_)
: curr_point(curr_point_), plane_unit_norm(plane_unit_norm_), negative_OA_dot_norm(negative_OA_dot_norm_) {
}
bool SurfNormAnalyticCostFunction::Evaluate(double const *const *parameters, double *residuals, double **jacobians) const
{
Eigen::Map<const Eigen::Quaterniond> q_w_curr(parameters[0]);
Eigen::Map<const Eigen::Vector3d> t_w_curr(parameters[0] + 4);
Eigen::Vector3d point_w = q_w_curr * curr_point + t_w_curr;
residuals[0] = plane_unit_norm.dot(point_w) + negative_OA_dot_norm;
if(jacobians != NULL)
{
if(jacobians[0] != NULL)
{
Eigen::Matrix3d skew_point_w = skew(point_w);
Eigen::Matrix<double, 3, 6> dp_by_so3;
dp_by_so3.block<3,3>(0,0) = -skew_point_w;
(dp_by_so3.block<3,3>(0, 3)).setIdentity();
Eigen::Map<Eigen::Matrix<double, 1, 7, Eigen::RowMajor> > J_se3(jacobians[0]);
J_se3.setZero();
J_se3.block<1,6>(0,0) = plane_unit_norm.transpose() * dp_by_so3;
}
}
return true;
}
bool PoseSE3Parameterization::Plus(const double *x, const double *delta, double *x_plus_delta) const
{
Eigen::Map<const Eigen::Vector3d> trans(x + 4);
Eigen::Quaterniond delta_q;
Eigen::Vector3d delta_t;
getTransformFromSe3(Eigen::Map<const Eigen::Matrix<double,6,1>>(delta), delta_q, delta_t);
Eigen::Map<const Eigen::Quaterniond> quater(x);
Eigen::Map<Eigen::Quaterniond> quater_plus(x_plus_delta);
Eigen::Map<Eigen::Vector3d> trans_plus(x_plus_delta + 4);
quater_plus = delta_q * quater;
trans_plus = delta_q * trans + delta_t;
return true;
}
bool PoseSE3Parameterization::ComputeJacobian(const double *x, double *jacobian) const
{
Eigen::Map<Eigen::Matrix<double, 7, 6, Eigen::RowMajor>> j(jacobian);
(j.topRows(6)).setIdentity();
(j.bottomRows(1)).setZero();
return true;
}
void getTransformFromSe3(const Eigen::Matrix<double,6,1>& se3, Eigen::Quaterniond& q, Eigen::Vector3d& t){
Eigen::Vector3d omega(se3.data());
Eigen::Vector3d upsilon(se3.data()+3);
Eigen::Matrix3d Omega = skew(omega);
double theta = omega.norm();
double half_theta = 0.5*theta;
double imag_factor;
double real_factor = cos(half_theta);
if(theta<1e-10)
{
double theta_sq = theta*theta;
double theta_po4 = theta_sq*theta_sq;
imag_factor = 0.5-0.0208333*theta_sq+0.000260417*theta_po4;
}
else
{
double sin_half_theta = sin(half_theta);
imag_factor = sin_half_theta/theta;
}
q = Eigen::Quaterniond(real_factor, imag_factor*omega.x(), imag_factor*omega.y(), imag_factor*omega.z());
Eigen::Matrix3d J;
if (theta<1e-10)
{
J = q.matrix();
}
else
{
Eigen::Matrix3d Omega2 = Omega*Omega;
J = (Eigen::Matrix3d::Identity() + (1-cos(theta))/(theta*theta)*Omega + (theta-sin(theta))/(pow(theta,3))*Omega2);
}
t = J*upsilon;
}
Eigen::Matrix<double,3,3> skew(Eigen::Matrix<double,3,1>& mat_in){
Eigen::Matrix<double,3,3> skew_mat;
skew_mat.setZero();
skew_mat(0,1) = -mat_in(2);
skew_mat(0,2) = mat_in(1);
skew_mat(1,2) = -mat_in(0);
skew_mat(1,0) = mat_in(2);
skew_mat(2,0) = -mat_in(1);
skew_mat(2,1) = mat_in(0);
return skew_mat;
}
| [
"wh200720041@vip.qq.com"
] | wh200720041@vip.qq.com |
6a1550fa631f3e505fcc5d8740bacefe3223f71c | a38892b11624565ef618508a29c85b839576afd6 | /ThreadTest/MyTest.h | 982e7f7a83739e37b9555c33fd9e4e085b2e0c97 | [] | no_license | softboy536/MyTest | e42ae19327495b8d88ccff7aa902a411c9b2c48f | 6e13661e898cc2682a8160a5f36ba9e59988f024 | refs/heads/master | 2020-12-14T01:25:44.824245 | 2020-01-17T16:43:19 | 2020-01-17T16:43:19 | 234,591,672 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 382 | h | #ifndef MYTEST_H
#define MYTEST_H
#include <QObject>
class MyTest : public QObject
{
Q_OBJECT
public:
explicit MyTest(QObject *parent = nullptr);
explicit MyTest(const MyTest &myTest, QObject *parent = nullptr);
QString getString() {return testString;}
signals:
public slots:
private:
QString testString;
};
Q_DECLARE_METATYPE(MyTest)
#endif // MYTEST_H
| [
"stonex_2000@163.com"
] | stonex_2000@163.com |
827d76e5f569eac9300a1e40655236d5517e3cd8 | 13f8b217dbaf9faac2dc54efcbacb745d5c87edb | /CvGameCoreDLL_Expansion2/CvPolicyAI.cpp | e95c9829f27c6cb3e12b58ac12a03621632c7fff | [] | no_license | TataTawa/DLL-VMC | 2905681a09ca1a504e43bb775db9c50e542058ac | fe1b17df263ca34b21384f664c1bcf9ab745524b | refs/heads/master | 2020-07-04T00:19:01.245584 | 2018-08-19T09:55:40 | 2018-08-19T09:55:40 | 202,096,645 | 0 | 0 | null | 2019-08-13T08:13:15 | 2019-08-13T08:13:15 | null | WINDOWS-1252 | C++ | false | false | 39,662 | cpp | /* -------------------------------------------------------------------------------------------------------
© 1991-2012 Take-Two Interactive Software and its subsidiaries. Developed by Firaxis Games.
Sid Meier's Civilization V, Civ, Civilization, 2K Games, Firaxis Games, Take-Two Interactive Software
and their respective logos are all trademarks of Take-Two interactive Software, Inc.
All other marks and trademarks are the property of their respective owners.
All rights reserved.
------------------------------------------------------------------------------------------------------- */
#include "CvGameCoreDLLPCH.h"
#include "CvGameCoreDLLUtil.h"
#include "CvPolicyAI.h"
#include "CvGrandStrategyAI.h"
#include "CvInfosSerializationHelper.h"
// Include this after all other headers.
#include "LintFree.h"
/// Constructor
CvPolicyAI::CvPolicyAI(CvPlayerPolicies* currentPolicies):
m_pCurrentPolicies(currentPolicies)
{
}
/// Destructor
CvPolicyAI::~CvPolicyAI(void)
{
}
/// Clear out AI local variables
void CvPolicyAI::Reset()
{
m_PolicyAIWeights.clear();
m_iPolicyWeightPropagationLevels = GC.getPOLICY_WEIGHT_PROPAGATION_LEVELS();
m_iPolicyWeightPercentDropNewBranch = GC.getPOLICY_WEIGHT_PERCENT_DROP_NEW_BRANCH();
CvAssertMsg(m_pCurrentPolicies != NULL, "Policy AI init failure: player policy data is NULL");
if(m_pCurrentPolicies != NULL)
{
CvPolicyXMLEntries* pPolicyEntries = m_pCurrentPolicies->GetPolicies();
CvAssertMsg(pPolicyEntries != NULL, "Policy AI init failure: no policy data");
if(pPolicyEntries != NULL)
{
// Loop through reading each one and add an entry with 0 weight to our vector
const int nPolicyEntries = pPolicyEntries->GetNumPolicies();
for(int i = 0; i < nPolicyEntries; i++)
{
m_PolicyAIWeights.push_back(i, 0);
}
}
}
}
/// Serialization read
void CvPolicyAI::Read(FDataStream& kStream)
{
// Version number to maintain backwards compatibility
uint uiVersion;
kStream >> uiVersion;
MOD_SERIALIZE_INIT_READ(kStream);
int iWeight;
CvAssertMsg(m_pCurrentPolicies->GetPolicies() != NULL, "Policy AI serialization failure: no policy data");
CvAssertMsg(m_pCurrentPolicies->GetPolicies()->GetNumPolicies() > 0, "Policy AI serialization failure: number of policies not greater than 0");
// Reset vector
m_PolicyAIWeights.clear();
uint uiPolicyArraySize = m_pCurrentPolicies->GetPolicies()->GetNumPolicies();
// Must set to the final size because we might not be adding in sequentially
m_PolicyAIWeights.resize(uiPolicyArraySize);
// Clear the contents in case we are loading a smaller set
for(uint uiIndex = 0; uiIndex < uiPolicyArraySize; ++uiIndex)
m_PolicyAIWeights.SetWeight(uiIndex, 0);
uint uiPolicyCount;
kStream >> uiPolicyCount;
for(uint uiIndex = 0; uiIndex < uiPolicyCount; ++uiIndex)
{
PolicyTypes ePolicy = (PolicyTypes)CvInfosSerializationHelper::ReadHashed(kStream);
kStream >> iWeight;
if(ePolicy != NO_POLICY && (uint)ePolicy < uiPolicyArraySize)
m_PolicyAIWeights.SetWeight((uint)ePolicy, iWeight);
}
}
/// Serialization write
void CvPolicyAI::Write(FDataStream& kStream)
{
// Current version number
uint uiVersion = 1;
kStream << uiVersion;
MOD_SERIALIZE_INIT_WRITE(kStream);
CvAssertMsg(m_pCurrentPolicies->GetPolicies() != NULL, "Policy AI serialization failure: no policy data");
CvAssertMsg(m_pCurrentPolicies->GetPolicies()->GetNumPolicies() > 0, "Policy AI serialization failure: number of policies not greater than 0");
// Loop through writing each entry
uint uiPolicyCount = m_pCurrentPolicies->GetPolicies()->GetNumPolicies();
kStream << uiPolicyCount;
for(int i = 0; i < m_pCurrentPolicies->GetPolicies()->GetNumPolicies(); i++)
{
CvInfosSerializationHelper::WriteHashed(kStream, static_cast<const PolicyTypes>(i));
kStream << m_PolicyAIWeights.GetWeight(i);
}
}
/// Establish weights for one flavor; can be called multiple times to layer strategies
void CvPolicyAI::AddFlavorWeights(FlavorTypes eFlavor, int iWeight, int iPropagationPercent)
{
int iPolicy;
CvPolicyEntry* entry;
int* paiTempWeights;
CvPolicyXMLEntries* pkPolicyEntries = m_pCurrentPolicies->GetPolicies();
// Create a temporary array of weights
paiTempWeights = (int*)_alloca(sizeof(int*) * pkPolicyEntries->GetNumPolicies());
// Loop through all our policies
for(iPolicy = 0; iPolicy < pkPolicyEntries->GetNumPolicies(); iPolicy++)
{
entry = pkPolicyEntries->GetPolicyEntry(iPolicy);
// Set its weight by looking at policy's weight for this flavor and using iWeight multiplier passed in
if(entry)
paiTempWeights[iPolicy] = entry->GetFlavorValue(eFlavor) * iWeight;
else
paiTempWeights[iPolicy] = 0;
}
// Propagate these values left in the tree so prereqs get bought
if(iPropagationPercent > 0)
{
WeightPrereqs(paiTempWeights, iPropagationPercent);
}
// Add these weights over previous ones
for(iPolicy = 0; iPolicy < m_pCurrentPolicies->GetPolicies()->GetNumPolicies(); iPolicy++)
{
m_PolicyAIWeights.IncreaseWeight(iPolicy, paiTempWeights[iPolicy]);
}
}
/// Choose a player's next policy purchase (could be opening a branch)
int CvPolicyAI::ChooseNextPolicy(CvPlayer* pPlayer)
{
RandomNumberDelegate fcn;
fcn = MakeDelegate(&GC.getGame(), &CvGame::getJonRandNum);
int iRtnValue = (int)NO_POLICY;
int iPolicyLoop;
vector<int> aLevel3Tenets;
bool bMustChooseTenet = (pPlayer->GetNumFreeTenets() > 0);
// Create a new vector holding only policies we can currently adopt
m_AdoptablePolicies.clear();
// Loop through adding the adoptable policies
for(iPolicyLoop = 0; iPolicyLoop < m_pCurrentPolicies->GetPolicies()->GetNumPolicies(); iPolicyLoop++)
{
if(m_pCurrentPolicies->CanAdoptPolicy((PolicyTypes) iPolicyLoop) && (!bMustChooseTenet || m_pCurrentPolicies->GetPolicies()->GetPolicyEntry(iPolicyLoop)->GetLevel() > 0))
{
int iWeight = 0;
iWeight += m_PolicyAIWeights.GetWeight(iPolicyLoop);
// Does this policy finish a branch for us?
if(m_pCurrentPolicies->WillFinishBranchIfAdopted((PolicyTypes) iPolicyLoop))
{
int iPolicyBranch = m_pCurrentPolicies->GetPolicies()->GetPolicyEntry(iPolicyLoop)->GetPolicyBranchType();
if(iPolicyBranch != NO_POLICY_BRANCH_TYPE)
{
int iFinisherPolicy = m_pCurrentPolicies->GetPolicies()->GetPolicyBranchEntry(iPolicyBranch)->GetFreeFinishingPolicy();
if(iFinisherPolicy != NO_POLICY)
{
iWeight += m_PolicyAIWeights.GetWeight(iFinisherPolicy);
}
}
}
m_AdoptablePolicies.push_back(iPolicyLoop + GC.getNumPolicyBranchInfos(), iWeight);
if (m_pCurrentPolicies->GetPolicies()->GetPolicyEntry(iPolicyLoop)->GetLevel() == 3)
{
aLevel3Tenets.push_back(iPolicyLoop);
}
}
}
// Did we already start a branch in the set that is mutually exclusive?
bool bStartedAMutuallyExclusiveBranch = false;
for(int iBranchLoop = 0; iBranchLoop < GC.getNumPolicyBranchInfos(); iBranchLoop++)
{
const PolicyBranchTypes ePolicyBranch = static_cast<PolicyBranchTypes>(iBranchLoop);
CvPolicyBranchEntry* pkPolicyBranchInfo = GC.getPolicyBranchInfo(ePolicyBranch);
if(pkPolicyBranchInfo)
{
if(pPlayer->GetPlayerPolicies()->IsPolicyBranchUnlocked(ePolicyBranch))
{
if(pkPolicyBranchInfo->IsMutuallyExclusive())
{
bStartedAMutuallyExclusiveBranch = true;
}
}
}
}
AIGrandStrategyTypes eCultureGrandStrategy = (AIGrandStrategyTypes) GC.getInfoTypeForString("AIGRANDSTRATEGY_CULTURE");
AIGrandStrategyTypes eCurrentGrandStrategy = pPlayer->GetGrandStrategyAI()->GetActiveGrandStrategy();
// Loop though the branches adding each as another possibility
if (!bMustChooseTenet)
{
for(int iBranchLoop = 0; iBranchLoop < GC.getNumPolicyBranchInfos(); iBranchLoop++)
{
const PolicyBranchTypes ePolicyBranch = static_cast<PolicyBranchTypes>(iBranchLoop);
CvPolicyBranchEntry* pkPolicyBranchInfo = GC.getPolicyBranchInfo(ePolicyBranch);
if(pkPolicyBranchInfo)
{
if(bStartedAMutuallyExclusiveBranch && pkPolicyBranchInfo->IsMutuallyExclusive())
{
continue;
}
if(pPlayer->GetPlayerPolicies()->CanUnlockPolicyBranch(ePolicyBranch) && !pPlayer->GetPlayerPolicies()->IsPolicyBranchUnlocked(ePolicyBranch))
{
int iBranchWeight = 0;
// Does this branch actually help us, based on game options?
if(IsBranchEffectiveInGame(ePolicyBranch))
{
iBranchWeight += WeighBranch(ePolicyBranch);
iBranchWeight *= (100 - m_iPolicyWeightPercentDropNewBranch);
iBranchWeight /= 100;
#if defined(MOD_AI_SMART_V3)
if (MOD_AI_SMART_V3 && !pPlayer->GetPlayerPolicies()->IsEraPrereqBranch(ePolicyBranch))
{
iBranchWeight *= 80;
iBranchWeight /= 100;
}
#endif
if(eCurrentGrandStrategy == eCultureGrandStrategy)
{
iBranchWeight /= 3;
}
}
m_AdoptablePolicies.push_back(iBranchLoop, iBranchWeight);
}
}
}
}
m_AdoptablePolicies.SortItems();
LogPossiblePolicies();
// If there were any Level 3 tenets found, consider going for the one that matches our victory strategy
if (aLevel3Tenets.size() > 0)
{
vector<int>::const_iterator it;
for (it = aLevel3Tenets.begin(); it != aLevel3Tenets.end(); it++)
{
CvPolicyEntry *pEntry;
pEntry = m_pCurrentPolicies->GetPolicies()->GetPolicyEntry(*it);
if (pEntry)
{
AIGrandStrategyTypes eGrandStrategy = pPlayer->GetGrandStrategyAI()->GetActiveGrandStrategy();
if (eGrandStrategy == GC.getInfoTypeForString("AIGRANDSTRATEGY_CONQUEST"))
{
if (pEntry->GetFlavorValue((FlavorTypes)GC.getInfoTypeForString("FLAVOR_OFFENSE")) > 0)
{
LogPolicyChoice((PolicyTypes)*it);
return (*it) + GC.getNumPolicyBranchInfos();
}
}
else if(eGrandStrategy == GC.getInfoTypeForString("AIGRANDSTRATEGY_SPACESHIP"))
{
if (pEntry->GetFlavorValue((FlavorTypes)GC.getInfoTypeForString("FLAVOR_SPACESHIP")) > 0)
{
LogPolicyChoice((PolicyTypes)*it);
return (*it) + GC.getNumPolicyBranchInfos();
}
}
else if(eGrandStrategy == GC.getInfoTypeForString("AIGRANDSTRATEGY_UNITED_NATIONS"))
{
if (pEntry->GetFlavorValue((FlavorTypes)GC.getInfoTypeForString("FLAVOR_DIPLOMACY")) > 0)
{
LogPolicyChoice((PolicyTypes)*it);
return (*it) + GC.getNumPolicyBranchInfos();
}
}
else if(eGrandStrategy == GC.getInfoTypeForString("AIGRANDSTRATEGY_CULTURE"))
{
if (pEntry->GetFlavorValue((FlavorTypes)GC.getInfoTypeForString("FLAVOR_CULTURE")) > 0)
{
LogPolicyChoice((PolicyTypes)*it);
return (*it) + GC.getNumPolicyBranchInfos();
}
}
}
}
}
CvAssertMsg(m_AdoptablePolicies.GetTotalWeight() >= 0, "Total weights of considered policies should not be negative! Please send Anton your save file and version.");
// If total weight is above 0, choose one above a threshold
if(m_AdoptablePolicies.GetTotalWeight() > 0)
{
int iNumChoices = GC.getGame().getHandicapInfo().GetPolicyNumOptions();
iRtnValue = m_AdoptablePolicies.ChooseFromTopChoices(iNumChoices, &fcn, "Choosing policy from Top Choices");
}
// Total weight may be 0 if the only branches and policies left are ones that are ineffective in our game, but we gotta pick something
else if(m_AdoptablePolicies.GetTotalWeight() == 0 && m_AdoptablePolicies.size() > 0)
{
iRtnValue = m_AdoptablePolicies.ChooseAtRandom(&fcn, "Choosing policy at random (no good choices)");
}
// Log our choice
if(iRtnValue != (int)NO_POLICY)
{
if(iRtnValue >= GC.getNumPolicyBranchInfos())
{
LogPolicyChoice((PolicyTypes)(iRtnValue - GC.getNumPolicyBranchInfos()));
}
else
{
LogBranchChoice((PolicyBranchTypes)iRtnValue);
}
}
return iRtnValue;
}
void CvPolicyAI::DoChooseIdeology(CvPlayer *pPlayer)
{
int iFreedomPriority = 0;
int iAutocracyPriority = 0;
int iOrderPriority = 0;
int iFreedomMultiplier = 1;
int iAutocracyMultiplier = 1;
int iOrderMultiplier = 1;
PolicyBranchTypes eFreedomBranch = (PolicyBranchTypes)GC.getPOLICY_BRANCH_FREEDOM();
PolicyBranchTypes eAutocracyBranch = (PolicyBranchTypes)GC.getPOLICY_BRANCH_AUTOCRACY();
PolicyBranchTypes eOrderBranch = (PolicyBranchTypes)GC.getPOLICY_BRANCH_ORDER();
if (eFreedomBranch == NO_POLICY_BRANCH_TYPE || eAutocracyBranch == NO_POLICY_BRANCH_TYPE || eOrderBranch == NO_POLICY_BRANCH_TYPE)
{
return;
}
#if defined(MOD_DIPLOMACY_CIV4_FEATURES)
if(MOD_DIPLOMACY_CIV4_FEATURES)
{
if(GET_TEAM(pPlayer->getTeam()).IsVassalOfSomeone())
{
TeamTypes eMasterTeam = GET_TEAM(pPlayer->getTeam()).GetMaster();
if(eMasterTeam != NO_TEAM)
{
// Loop through all players to see if they're on our team
for(int iPlayerLoop = 0; iPlayerLoop < MAX_MAJOR_CIVS; iPlayerLoop++)
{
PlayerTypes eMaster = (PlayerTypes) iPlayerLoop;
// Assumes one player per team for master
if(GET_PLAYER(eMaster).getTeam() == GET_TEAM(eMasterTeam).GetID())
{
if(GET_PLAYER(eMaster).GetPlayerPolicies()->GetLateGamePolicyTree() != NO_POLICY_BRANCH_TYPE)
{
pPlayer->GetPlayerPolicies()->SetPolicyBranchUnlocked(GET_PLAYER(eMaster).GetPlayerPolicies()->GetLateGamePolicyTree(), true, false);
LogBranchChoice(GET_PLAYER(eMaster).GetPlayerPolicies()->GetLateGamePolicyTree());
return;
}
}
}
}
}
}
#endif
// First consideration is our victory type
int iConquestPriority = max(0, pPlayer->GetGrandStrategyAI()->GetConquestPriority());
int iDiploPriority = max(0, pPlayer->GetGrandStrategyAI()->GetUnitedNationsPriority());
int iTechPriority = max(0, pPlayer->GetGrandStrategyAI()->GetSpaceshipPriority());
int iCulturePriority = max(0, pPlayer->GetGrandStrategyAI()->GetCulturePriority());
#if defined(MOD_EVENTS_IDEOLOGIES)
if (MOD_EVENTS_IDEOLOGIES) {
CvPlayerPolicies* pPolicies = pPlayer->GetPlayerPolicies();
// Just jump on the band-wagon and hard code for three ideologies!!!
if (!pPolicies->CanAdoptIdeology(eFreedomBranch)) {
iFreedomMultiplier = 0;
}
if (!pPolicies->CanAdoptIdeology(eAutocracyBranch)) {
iAutocracyMultiplier = 0;
}
if (!pPolicies->CanAdoptIdeology(eOrderBranch)) {
iOrderMultiplier = 0;
}
}
#endif
#if defined(MOD_EVENTS_IDEOLOGIES)
if (iFreedomMultiplier != 0 && iAutocracyMultiplier != 0 && iOrderMultiplier != 0) {
#endif
// Rule out one ideology if we are clearly (at least 25% more priority) going for the victory this ideology doesn't support
int iClearPrefPercent = GC.getIDEOLOGY_PERCENT_CLEAR_VICTORY_PREF();
if (iConquestPriority > (iDiploPriority * (100 + iClearPrefPercent) / 100) &&
iConquestPriority > (iTechPriority * (100 + iClearPrefPercent) / 100) &&
iConquestPriority > (iCulturePriority * (100 + iClearPrefPercent) / 100))
{
iFreedomMultiplier = 0;
}
else if (iDiploPriority > (iConquestPriority * (100 + iClearPrefPercent) / 100) &&
iDiploPriority > (iTechPriority * (100 + iClearPrefPercent) / 100) &&
iDiploPriority > (iCulturePriority * (100 + iClearPrefPercent) / 100))
{
iOrderMultiplier = 0;
}
else if (iTechPriority > (iConquestPriority * (100 + iClearPrefPercent) / 100) &&
iTechPriority > (iDiploPriority * (100 + iClearPrefPercent) / 100) &&
iTechPriority > (iCulturePriority * (100 + iClearPrefPercent) / 100))
{
iAutocracyMultiplier = 0;
}
#if defined(MOD_EVENTS_IDEOLOGIES)
}
#endif
int iFreedomTotal = iDiploPriority + iTechPriority + iCulturePriority;
int iAutocracyTotal = iDiploPriority + iConquestPriority + iCulturePriority;
int iOrderTotal = iTechPriority + iConquestPriority + iCulturePriority;
int iGrandTotal = iFreedomTotal + iAutocracyTotal + iOrderTotal;
if (iGrandTotal > 0)
{
int iPriorityToDivide = GC.getIDEOLOGY_SCORE_GRAND_STRATS();
iFreedomPriority = (iFreedomTotal * iPriorityToDivide) / iGrandTotal;
iAutocracyPriority = (iAutocracyTotal * iPriorityToDivide) / iGrandTotal;
iOrderPriority = (iOrderTotal * iPriorityToDivide) / iGrandTotal;
}
CvString stage = "After Grand Strategies";
LogIdeologyChoice(stage, iFreedomPriority, iAutocracyPriority, iOrderPriority);
// Next look at free policies we can get
iFreedomPriority += PolicyHelpers::GetNumFreePolicies(eFreedomBranch) * GC.getIDEOLOGY_SCORE_PER_FREE_TENET();
iAutocracyPriority += PolicyHelpers::GetNumFreePolicies(eAutocracyBranch) * GC.getIDEOLOGY_SCORE_PER_FREE_TENET();
iOrderPriority += PolicyHelpers::GetNumFreePolicies(eOrderBranch) * GC.getIDEOLOGY_SCORE_PER_FREE_TENET();;
stage = "After Free Policies";
LogIdeologyChoice(stage, iFreedomPriority, iAutocracyPriority, iOrderPriority);
// Finally see what our friends (and enemies) have already chosen
PlayerTypes eLoopPlayer;
for (int iPlayerLoop = 0; iPlayerLoop < MAX_MAJOR_CIVS; iPlayerLoop++)
{
eLoopPlayer = (PlayerTypes) iPlayerLoop;
if (eLoopPlayer != pPlayer->GetID() && pPlayer->GetDiplomacyAI()->IsPlayerValid(eLoopPlayer))
{
CvPlayer &kOtherPlayer = GET_PLAYER(eLoopPlayer);
PolicyBranchTypes eOtherPlayerIdeology;
eOtherPlayerIdeology = kOtherPlayer.GetPlayerPolicies()->GetLateGamePolicyTree();
switch(pPlayer->GetDiplomacyAI()->GetMajorCivApproach(eLoopPlayer, /*bHideTrueFeelings*/ true))
{
case MAJOR_CIV_APPROACH_HOSTILE:
if (eOtherPlayerIdeology == eFreedomBranch)
{
iAutocracyPriority += GC.getIDEOLOGY_SCORE_HOSTILE();
iOrderPriority += GC.getIDEOLOGY_SCORE_HOSTILE();
}
else if (eOtherPlayerIdeology == eAutocracyBranch)
{
iFreedomPriority += GC.getIDEOLOGY_SCORE_HOSTILE();
iOrderPriority += GC.getIDEOLOGY_SCORE_HOSTILE();
}
else if (eOtherPlayerIdeology == eOrderBranch)
{
iAutocracyPriority += GC.getIDEOLOGY_SCORE_HOSTILE();;
iFreedomPriority += GC.getIDEOLOGY_SCORE_HOSTILE();
}
break;
case MAJOR_CIV_APPROACH_GUARDED:
if (eOtherPlayerIdeology == eFreedomBranch)
{
iAutocracyPriority += GC.getIDEOLOGY_SCORE_GUARDED();
iOrderPriority += GC.getIDEOLOGY_SCORE_GUARDED();
}
else if (eOtherPlayerIdeology == eAutocracyBranch)
{
iFreedomPriority += GC.getIDEOLOGY_SCORE_GUARDED();
iOrderPriority += GC.getIDEOLOGY_SCORE_GUARDED();
}
else if (eOtherPlayerIdeology == eOrderBranch)
{
iAutocracyPriority += GC.getIDEOLOGY_SCORE_GUARDED();
iFreedomPriority += GC.getIDEOLOGY_SCORE_GUARDED();
}
break;
case MAJOR_CIV_APPROACH_AFRAID:
if (eOtherPlayerIdeology == eFreedomBranch)
{
iFreedomPriority += GC.getIDEOLOGY_SCORE_AFRAID();
}
else if (eOtherPlayerIdeology == eAutocracyBranch)
{
iAutocracyPriority += GC.getIDEOLOGY_SCORE_AFRAID();
}
else if (eOtherPlayerIdeology == eOrderBranch)
{
iOrderPriority += GC.getIDEOLOGY_SCORE_AFRAID();
}
break;
case MAJOR_CIV_APPROACH_FRIENDLY:
if (eOtherPlayerIdeology == eFreedomBranch)
{
iFreedomPriority += GC.getIDEOLOGY_SCORE_FRIENDLY();
}
else if (eOtherPlayerIdeology == eAutocracyBranch)
{
iAutocracyPriority += GC.getIDEOLOGY_SCORE_FRIENDLY();
}
else if (eOtherPlayerIdeology == eOrderBranch)
{
iOrderPriority += GC.getIDEOLOGY_SCORE_FRIENDLY();
}
break;
case MAJOR_CIV_APPROACH_NEUTRAL:
// No changes
break;
}
}
}
stage = "After Relations";
LogIdeologyChoice(stage, iFreedomPriority, iAutocracyPriority, iOrderPriority);
// Look at Happiness impacts
int iHappinessModifier = GC.getIDEOLOGY_SCORE_HAPPINESS();
// -- Happiness we could add through tenets
int iHappinessDelta;
int iHappinessPoliciesInBranch;
iHappinessDelta = GetBranchBuildingHappiness(pPlayer, eFreedomBranch);
iHappinessPoliciesInBranch = GetNumHappinessPolicies(pPlayer, eFreedomBranch);
if (iHappinessPoliciesInBranch > 0)
{
iFreedomPriority += iHappinessDelta * iHappinessModifier / iHappinessPoliciesInBranch;
}
iHappinessDelta = GetBranchBuildingHappiness(pPlayer, eAutocracyBranch);
iHappinessPoliciesInBranch = GetNumHappinessPolicies(pPlayer, eAutocracyBranch);
if (iHappinessPoliciesInBranch > 0)
{
iAutocracyPriority += iHappinessDelta * iHappinessModifier / iHappinessPoliciesInBranch;
}
iHappinessDelta = GetBranchBuildingHappiness(pPlayer, eOrderBranch);
iHappinessPoliciesInBranch = GetNumHappinessPolicies(pPlayer, eOrderBranch);
if (iHappinessPoliciesInBranch > 0)
{
iOrderPriority += iHappinessDelta * iHappinessModifier / iHappinessPoliciesInBranch;
}
stage = "After Tenet Happiness Boosts";
LogIdeologyChoice(stage, iFreedomPriority, iAutocracyPriority, iOrderPriority);
// -- Happiness we'd lose through Public Opinion
iHappinessDelta = max (0, 100 - pPlayer->GetCulture()->ComputeHypotheticalPublicOpinionUnhappiness(eFreedomBranch));
iFreedomPriority += iHappinessDelta * iHappinessModifier;
iHappinessDelta = max (0, 100 - pPlayer->GetCulture()->ComputeHypotheticalPublicOpinionUnhappiness(eAutocracyBranch));
iAutocracyPriority += iHappinessDelta * iHappinessModifier;
iHappinessDelta = max (0, 100 - pPlayer->GetCulture()->ComputeHypotheticalPublicOpinionUnhappiness(eOrderBranch));
iOrderPriority += iHappinessDelta * iHappinessModifier;
stage = "After Public Opinion Happiness";
LogIdeologyChoice(stage, iFreedomPriority, iAutocracyPriority, iOrderPriority);
// Small random add-on
iFreedomPriority += GC.getGame().getJonRandNum(10, "Freedom random priority bump");
iAutocracyPriority += GC.getGame().getJonRandNum(10, "Autocracy random priority bump");
iOrderPriority += GC.getGame().getJonRandNum(10, "Order random priority bump");
stage = "After Random (1 to 10)";
LogIdeologyChoice(stage, iFreedomPriority, iAutocracyPriority, iOrderPriority);
// Rule out any branches that are totally out of consideration
iFreedomPriority = iFreedomPriority * iFreedomMultiplier;
iAutocracyPriority = iAutocracyPriority * iAutocracyMultiplier;
iOrderPriority = iOrderPriority * iOrderMultiplier;
stage = "Final (after Clear Victory Preference)";
LogIdeologyChoice(stage, iFreedomPriority, iAutocracyPriority, iOrderPriority);
// Pick the ideology
PolicyBranchTypes eChosenBranch;
if (iFreedomPriority >= iAutocracyPriority && iFreedomPriority >= iOrderPriority)
{
eChosenBranch = eFreedomBranch;
}
else if (iAutocracyPriority >= iFreedomPriority && iAutocracyPriority >= iOrderPriority)
{
eChosenBranch = eAutocracyBranch;
}
else
{
eChosenBranch = eOrderBranch;
}
pPlayer->GetPlayerPolicies()->SetPolicyBranchUnlocked(eChosenBranch, true, false);
LogBranchChoice(eChosenBranch);
#if defined(MOD_BUGFIX_MISSING_POLICY_EVENTS)
if (MOD_BUGFIX_MISSING_POLICY_EVENTS)
{
ICvEngineScriptSystem1* pkScriptSystem = gDLL->GetScriptSystem();
if(pkScriptSystem)
{
CvLuaArgsHandle args;
args->Push(pPlayer->GetID());
args->Push(eChosenBranch);
bool bResult = false;
LuaSupport::CallHook(pkScriptSystem, "PlayerAdoptPolicyBranch", args.get(), bResult);
}
}
#endif
}
/// Should the AI look at switching ideology branches?
void CvPolicyAI::DoConsiderIdeologySwitch(CvPlayer* pPlayer)
{
// Gather basic Ideology info
int iCurrentHappiness = pPlayer->GetExcessHappiness();
int iPublicOpinionUnhappiness = pPlayer->GetCulture()->GetPublicOpinionUnhappiness();
PolicyBranchTypes ePreferredIdeology = pPlayer->GetCulture()->GetPublicOpinionPreferredIdeology();
PolicyBranchTypes eCurrentIdeology = pPlayer->GetPlayerPolicies()->GetLateGamePolicyTree();
#if !defined(NO_ACHIEVEMENTS)
PlayerTypes eMostPressure = pPlayer->GetCulture()->GetPublicOpinionBiggestInfluence();
#endif
#if defined(MOD_DIPLOMACY_CIV4_FEATURES)
if(MOD_DIPLOMACY_CIV4_FEATURES)
{
if(GET_TEAM(pPlayer->getTeam()).IsVassalOfSomeone() && pPlayer->GetPlayerPolicies()->GetLateGamePolicyTree() != NO_POLICY_BRANCH_TYPE)
{
TeamTypes eMasterTeam = GET_TEAM(pPlayer->getTeam()).GetMaster();
if(eMasterTeam != NO_TEAM)
{
// Loop through all players to see if they're on our team
for(int iPlayerLoop = 0; iPlayerLoop < MAX_MAJOR_CIVS; iPlayerLoop++)
{
PlayerTypes eMaster = (PlayerTypes) iPlayerLoop;
// Assumes one player per team for master
if(GET_PLAYER(eMaster).getTeam() == GET_TEAM(eMasterTeam).GetID())
{
if(GET_PLAYER(eMaster).GetPlayerPolicies()->GetLateGamePolicyTree() != NO_POLICY_BRANCH_TYPE && GET_PLAYER(eMaster).GetPlayerPolicies()->GetLateGamePolicyTree() != pPlayer->GetPlayerPolicies()->GetLateGamePolicyTree())
{
// Cleared all obstacles -- REVOLUTION!
pPlayer->SetAnarchyNumTurns(GC.getSWITCH_POLICY_BRANCHES_ANARCHY_TURNS());
pPlayer->GetPlayerPolicies()->DoSwitchIdeologies(GET_PLAYER(eMaster).GetPlayerPolicies()->GetLateGamePolicyTree());
Localization::String strSummary = Localization::Lookup("TXT_KEY_ANARCHY_BEGINS_SUMMARY");
Localization::String strMessage = Localization::Lookup("TXT_KEY_ANARCHY_BEGINS");
pPlayer->GetNotifications()->Add(NOTIFICATION_GENERIC, strMessage.toUTF8(), strSummary.toUTF8(), pPlayer->GetID(), GC.getSWITCH_POLICY_BRANCHES_ANARCHY_TURNS(), -1);
return;
}
}
}
}
}
}
#endif
// Possible enough that we need to look at this in detail?
if (iCurrentHappiness <= GC.getSUPER_UNHAPPY_THRESHOLD() && iPublicOpinionUnhappiness >= 10)
{
// How much Happiness could we gain from a switch?
int iHappinessCurrentIdeology = GetBranchBuildingHappiness(pPlayer, eCurrentIdeology);
int iHappinessPreferredIdeology = GetBranchBuildingHappiness(pPlayer, ePreferredIdeology);
// Does the switch fight against our clearly preferred victory path?
bool bDontSwitchFreedom = false;
bool bDontSwitchOrder = false;
bool bDontSwitchAutocracy = false;
int iConquestPriority = pPlayer->GetGrandStrategyAI()->GetConquestPriority();
int iDiploPriority = pPlayer->GetGrandStrategyAI()->GetUnitedNationsPriority();
int iTechPriority = pPlayer->GetGrandStrategyAI()->GetSpaceshipPriority();
int iCulturePriority = pPlayer->GetGrandStrategyAI()->GetCulturePriority();
int iClearPrefPercent = GC.getIDEOLOGY_PERCENT_CLEAR_VICTORY_PREF();
if (iConquestPriority > (iDiploPriority * (100 + iClearPrefPercent) / 100) &&
iConquestPriority > (iTechPriority * (100 + iClearPrefPercent) / 100) &&
iConquestPriority > (iCulturePriority * (100 + iClearPrefPercent) / 100))
{
bDontSwitchFreedom = true;
}
else if (iDiploPriority > (iConquestPriority * (100 + iClearPrefPercent) / 100) &&
iDiploPriority > (iTechPriority * (100 + iClearPrefPercent) / 100) &&
iDiploPriority > (iCulturePriority * (100 + iClearPrefPercent) / 100))
{
bDontSwitchOrder = true;
}
else if (iTechPriority > (iConquestPriority * (100 + iClearPrefPercent) / 100) &&
iTechPriority > (iDiploPriority * (100 + iClearPrefPercent) / 100) &&
iTechPriority > (iCulturePriority * (100 + iClearPrefPercent) / 100))
{
bDontSwitchAutocracy = true;
}
int iTotalHappinessImprovement = iPublicOpinionUnhappiness + iHappinessPreferredIdeology - iHappinessCurrentIdeology;
if (iTotalHappinessImprovement >= 10)
{
if (bDontSwitchFreedom && ePreferredIdeology == GC.getPOLICY_BRANCH_FREEDOM())
{
return;
}
if (bDontSwitchAutocracy && ePreferredIdeology == GC.getPOLICY_BRANCH_AUTOCRACY())
{
return;
}
if (bDontSwitchOrder && ePreferredIdeology == GC.getPOLICY_BRANCH_ORDER())
{
return;
}
// Cleared all obstacles -- REVOLUTION!
pPlayer->SetAnarchyNumTurns(GC.getSWITCH_POLICY_BRANCHES_ANARCHY_TURNS());
pPlayer->GetPlayerPolicies()->DoSwitchIdeologies(ePreferredIdeology);
#if !defined(NO_ACHIEVEMENTS)
if (ePreferredIdeology == GC.getPOLICY_BRANCH_FREEDOM() && eCurrentIdeology == GC.getPOLICY_BRANCH_ORDER())
{
if (GET_PLAYER(eMostPressure).GetID() == GC.getGame().getActivePlayer())
{
gDLL->UnlockAchievement(ACHIEVEMENT_XP2_39);
}
}
#endif
}
}
}
/// What's the total Happiness benefit we could get from all policies/tenets in the branch based on our current buildings?
int CvPolicyAI::GetBranchBuildingHappiness(CvPlayer* pPlayer, PolicyBranchTypes eBranch)
{
// Policy Building Mods
int iSpecialPolicyBuildingHappiness = 0;
int iBuildingClassLoop;
BuildingClassTypes eBuildingClass;
for(int iPolicyLoop = 0; iPolicyLoop < GC.getNumPolicyInfos(); iPolicyLoop++)
{
PolicyTypes ePolicy = (PolicyTypes)iPolicyLoop;
CvPolicyEntry* pkPolicyInfo = GC.getPolicyInfo(ePolicy);
if(pkPolicyInfo)
{
if (pkPolicyInfo->GetPolicyBranchType() == eBranch)
{
for(iBuildingClassLoop = 0; iBuildingClassLoop < GC.getNumBuildingClassInfos(); iBuildingClassLoop++)
{
eBuildingClass = (BuildingClassTypes) iBuildingClassLoop;
CvBuildingClassInfo* pkBuildingClassInfo = GC.getBuildingClassInfo(eBuildingClass);
if (!pkBuildingClassInfo)
{
continue;
}
if (pkPolicyInfo->GetBuildingClassHappiness(eBuildingClass) != 0)
{
BuildingTypes eBuilding = (BuildingTypes)pPlayer->getCivilizationInfo().getCivilizationBuildings(eBuildingClass);
if (eBuilding != NO_BUILDING)
{
CvCity *pCity;
int iLoop;
for (pCity = pPlayer->firstCity(&iLoop); pCity != NULL; pCity = pPlayer->nextCity(&iLoop))
{
if (pCity->GetCityBuildings()->GetNumBuilding(eBuilding) > 0)
{
iSpecialPolicyBuildingHappiness += pkPolicyInfo->GetBuildingClassHappiness(eBuildingClass);
}
}
}
}
}
}
}
}
return iSpecialPolicyBuildingHappiness;
}
/// How many policies in this branch help happiness?
int CvPolicyAI::GetNumHappinessPolicies(CvPlayer* pPlayer, PolicyBranchTypes eBranch)
{
int iRtnValue = 0;
int iBuildingClassLoop;
BuildingClassTypes eBuildingClass;
for(int iPolicyLoop = 0; iPolicyLoop < GC.getNumPolicyInfos(); iPolicyLoop++)
{
PolicyTypes ePolicy = (PolicyTypes)iPolicyLoop;
CvPolicyEntry* pkPolicyInfo = GC.getPolicyInfo(ePolicy);
if(pkPolicyInfo)
{
if (pkPolicyInfo->GetPolicyBranchType() == eBranch)
{
for(iBuildingClassLoop = 0; iBuildingClassLoop < GC.getNumBuildingClassInfos(); iBuildingClassLoop++)
{
eBuildingClass = (BuildingClassTypes) iBuildingClassLoop;
CvBuildingClassInfo* pkBuildingClassInfo = GC.getBuildingClassInfo(eBuildingClass);
if (!pkBuildingClassInfo)
{
continue;
}
BuildingTypes eBuilding = (BuildingTypes)pPlayer->getCivilizationInfo().getCivilizationBuildings(eBuildingClass);
if (eBuilding != NO_BUILDING)
{
// Don't count a building that can only be built in conquered cities
CvBuildingEntry *pkEntry = GC.getBuildingInfo(eBuilding);
if (!pkEntry || pkEntry->IsNoOccupiedUnhappiness())
{
continue;
}
if (pkPolicyInfo->GetBuildingClassHappiness(eBuildingClass) != 0)
{
iRtnValue++;
break;
}
}
}
}
}
}
return iRtnValue;
}
//=====================================
// PRIVATE METHODS
//=====================================
/// Add weights to policies that are prereqs for the ones already weighted in this strategy
void CvPolicyAI::WeightPrereqs(int* paiTempWeights, int iPropagationPercent)
{
int iPolicyLoop;
// Loop through policies looking for ones that are just getting some new weight
for(iPolicyLoop = 0; iPolicyLoop < m_pCurrentPolicies->GetPolicies()->GetNumPolicies(); iPolicyLoop++)
{
// If found one, call our recursive routine to weight everything to the left in the tree
if(paiTempWeights[iPolicyLoop] > 0)
{
PropagateWeights(iPolicyLoop, paiTempWeights[iPolicyLoop], iPropagationPercent, 0);
}
}
}
/// Recursive routine to weight all prerequisite policies
void CvPolicyAI::PropagateWeights(int iPolicy, int iWeight, int iPropagationPercent, int iPropagationLevel)
{
if(iPropagationLevel < m_iPolicyWeightPropagationLevels)
{
int iPropagatedWeight = iWeight * iPropagationPercent / 100;
// Loop through all prerequisites
for(int iI = 0; iI < GC.getNUM_OR_TECH_PREREQS(); iI++)
{
// Did we find a prereq?
int iPrereq = m_pCurrentPolicies->GetPolicies()->GetPolicyEntry(iPolicy)->GetPrereqAndPolicies(iI);
if(iPrereq != NO_POLICY)
{
// Apply reduced weight here. Note that we apply these to the master weight array, not
// the temporary one. The temporary one is just used to hold the newly weighted policies
// (from which this weight propagation must originate).
m_PolicyAIWeights.IncreaseWeight(iPrereq, iPropagatedWeight);
// Recurse to its prereqs (assuming we have any weight left)
if(iPropagatedWeight > 0)
{
PropagateWeights(iPrereq, iPropagatedWeight, iPropagationPercent, iPropagationLevel++);
}
}
else
{
break;
}
}
}
}
/// Priority for opening up this branch
int CvPolicyAI::WeighBranch(PolicyBranchTypes eBranch)
{
int iWeight = 0;
CvPolicyBranchEntry* pkPolicyBranchInfo = GC.getPolicyBranchInfo(eBranch);
if(pkPolicyBranchInfo)
{
for(int iPolicyLoop = 0; iPolicyLoop < m_pCurrentPolicies->GetPolicies()->GetNumPolicies(); iPolicyLoop++)
{
const PolicyTypes ePolicyLoop = static_cast<PolicyTypes>(iPolicyLoop);
CvPolicyEntry* pkLoopPolicyInfo = GC.getPolicyInfo(ePolicyLoop);
if(pkLoopPolicyInfo)
{
// Policy we don't have?
if(!m_pCurrentPolicies->HasPolicy(ePolicyLoop))
{
// From this branch we are considering opening?
if(pkLoopPolicyInfo->GetPolicyBranchType() == eBranch)
{
// With no prereqs?
if(pkLoopPolicyInfo->GetPrereqAndPolicies(0) == NO_POLICY)
{
iWeight += m_PolicyAIWeights.GetWeight(iPolicyLoop);
}
}
}
}
}
// Add weight of free policy from branch
iWeight += m_PolicyAIWeights.GetWeight(pkPolicyBranchInfo->GetFreePolicy());
}
return iWeight;
}
/// Based on game options (religion off, science off, etc.), would this branch do us any good?
bool CvPolicyAI::IsBranchEffectiveInGame(PolicyBranchTypes eBranch)
{
CvPolicyBranchEntry* pBranchInfo = GC.getPolicyBranchInfo(eBranch);
CvAssertMsg(pBranchInfo, "Branch info not found! Please send Anton your save file and version.");
if (!pBranchInfo) return false;
if (pBranchInfo->IsDelayWhenNoReligion())
if (GC.getGame().isOption(GAMEOPTION_NO_RELIGION))
return false;
if (pBranchInfo->IsDelayWhenNoCulture())
if (GC.getGame().isOption(GAMEOPTION_NO_POLICIES))
return false;
if (pBranchInfo->IsDelayWhenNoScience())
if (GC.getGame().isOption(GAMEOPTION_NO_SCIENCE))
return false;
if (pBranchInfo->IsDelayWhenNoCityStates())
if (GC.getGame().GetNumMinorCivsEver() <= 0)
return false;
return true;
}
/// Log all possible policy choices
void CvPolicyAI::LogPossiblePolicies()
{
if(GC.getLogging() && GC.getAILogging())
{
CvString strOutBuf;
CvString strBaseString;
CvString strTemp;
CvString playerName;
CvString strDesc;
// Find the name of this civ and city
playerName = m_pCurrentPolicies->GetPlayer()->getCivilizationShortDescription();
FILogFile* pLog;
pLog = LOGFILEMGR.GetLog(GetLogFileName(playerName), FILogFile::kDontTimeStamp);
// Get the leading info for this line
strBaseString.Format("%03d, ", GC.getGame().getElapsedGameTurns());
strBaseString += playerName + ", ";
int iNumBranches = GC.getNumPolicyBranchInfos();
// Dump out the weight of each possible policy
for(int iI = 0; iI < m_AdoptablePolicies.size(); iI++)
{
int iWeight = m_AdoptablePolicies.GetWeight(iI);
if(m_AdoptablePolicies.GetElement(iI) < iNumBranches)
{
strTemp.Format("Branch %d, %d", m_AdoptablePolicies.GetElement(iI), iWeight);
}
else
{
PolicyTypes ePolicy = (PolicyTypes)(m_AdoptablePolicies.GetElement(iI) - iNumBranches);
CvPolicyEntry* pPolicyEntry = GC.getPolicyInfo(ePolicy);
const char* szPolicyType = (pPolicyEntry != NULL)? pPolicyEntry->GetType() : "Unknown";
strTemp.Format("%s, %d", szPolicyType, iWeight);
}
strOutBuf = strBaseString + strTemp;
pLog->Msg(strOutBuf);
}
}
}
/// Log chosen policy
void CvPolicyAI::LogPolicyChoice(PolicyTypes ePolicy)
{
if(GC.getLogging() && GC.getAILogging())
{
CvString strOutBuf;
CvString strBaseString;
CvString strTemp;
CvString playerName;
CvString strDesc;
// Find the name of this civ and city
playerName = m_pCurrentPolicies->GetPlayer()->getCivilizationShortDescription();
FILogFile* pLog;
pLog = LOGFILEMGR.GetLog(GetLogFileName(playerName), FILogFile::kDontTimeStamp);
// Get the leading info for this line
strBaseString.Format("%03d, ", GC.getGame().getElapsedGameTurns());
strBaseString += playerName + ", ";
CvPolicyEntry* pPolicyEntry = GC.getPolicyInfo(ePolicy);
const char* szPolicyType = (pPolicyEntry != NULL)? pPolicyEntry->GetType() : "Unknown";
strTemp.Format("CHOSEN, %s", szPolicyType);
strOutBuf = strBaseString + strTemp;
pLog->Msg(strOutBuf);
}
}
/// Log chosen policy
void CvPolicyAI::LogBranchChoice(PolicyBranchTypes eBranch)
{
if(GC.getLogging() && GC.getAILogging())
{
CvString strOutBuf;
CvString strBaseString;
CvString strTemp;
CvString playerName;
CvString strDesc;
// Find the name of this civ and city
playerName = m_pCurrentPolicies->GetPlayer()->getCivilizationShortDescription();
FILogFile* pLog;
pLog = LOGFILEMGR.GetLog(GetLogFileName(playerName), FILogFile::kDontTimeStamp);
// Get the leading info for this line
strBaseString.Format("%03d, ", GC.getGame().getElapsedGameTurns());
strBaseString += playerName + ", ";
strTemp.Format("CHOSEN, Branch %d", eBranch);
strOutBuf = strBaseString + strTemp;
pLog->Msg(strOutBuf);
}
}
/// Logging function to write out info on Ideology choices
void CvPolicyAI::LogIdeologyChoice(CvString &decisionState, int iWeightFreedom, int iWeightAutocracy, int iWeightOrder)
{
if(GC.getLogging() && GC.getAILogging())
{
CvString strOutBuf;
CvString strBaseString;
CvString strTemp;
CvString playerName;
// Find the name of this civ
playerName = m_pCurrentPolicies->GetPlayer()->getCivilizationShortDescription();
FILogFile* pLog;
pLog = LOGFILEMGR.GetLog(GetLogFileName(playerName), FILogFile::kDontTimeStamp);
// Get the leading info for this line
strBaseString.Format("%03d, ", GC.getGame().getElapsedGameTurns());
strBaseString += playerName + ", ";
strTemp.Format("%s, Freedom: %d, Order: %d, Autocracy: %d", decisionState.c_str(), iWeightFreedom, iWeightOrder, iWeightAutocracy);
strOutBuf = strBaseString + strTemp;
pLog->Msg(strOutBuf);
}
}
/// Build log filename
CvString CvPolicyAI::GetLogFileName(CvString& playerName) const
{
CvString strLogName;
// Open the log file
if(GC.getPlayerAndCityAILogSplit())
{
strLogName = "PolicyAILog_" + playerName + ".csv";
}
else
{
strLogName = "PolicyAILog.csv";
}
return strLogName;
} | [
"whoward69@o2.co.uk"
] | whoward69@o2.co.uk |
c62491ba35d269ddb1242577adeb6a6e319062c9 | 5553a92a31975fb5abef887fd84065b64484313f | /src/cubica/cubica_tet.cpp | 73e25d3f3c9751f86211f80de3b5895fd9e9e0ae | [] | no_license | rajaditya-m/Recalc_Final_Demo_Fork | 4c2ce450d976d9a32ec0d00ad8cc6a6d412e0ae7 | 35be877b37fb9351a3b811570ca582208bf1519a | refs/heads/master | 2021-03-24T10:46:21.408874 | 2015-05-29T22:44:15 | 2015-05-29T22:44:15 | 36,526,142 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 44,136 | cpp | #include "cubica_tet.h"
#include <cstdio>
#include <tuple>
#include <fstream>
#include <fixed_vector.h>
#include "opengl_helper.h"
#include "vector_io.h"
#include "tet_mesh_simulator_bridge.h"
#include "BLOCK_MATRIX_GRAPH.h"
#include "config_file.h"
#include "matlab_io.h"
#include "subspace_tet.h"
#include "vega_tet_mesh_io.h"
#include "global.h"
#include "vector_lib.h"
#include "print_macro.h"
#include "basis_io.h"
#ifdef HAS_BASIS_GENERATION_MODULE
#include "basis_generator.h"
#endif
CubicaTet::CubicaTet(const char* mesh_file, const char *folder)
: Super(mesh_file, 0, NULL) {
ui_selected_domain_ = -1;
gravity_ = Vec3(global::gravity[0], global::gravity[1], global::gravity[2]);
char file_name[512];
if (0) {
sprintf(file_name, "%s/global_mesh.veg", folder);
std::vector<double> verts(rest_pos_, rest_pos_ + vertex_num_ * 3);
std::vector<int> tets(tet_, tet_ + tet_number * 4);
VegaTetMeshIO::Instance()->Write(file_name, verts, tets);
exit(0);
}
// read the list of partitions and their partition ids
{
sprintf(file_name, "%s/partition_id.txt", folder);
std::ifstream in(file_name);
ASSERT(in.is_open(), P(file_name));
in >> part_num_;
parts_.resize(part_num_);
for (int p = 0; p < part_num_; ++p) {
in >> parts_[p];
}
in.close();
}
domain_container_.resize(part_num_);
domain_ = &domain_container_[0];
// read the tet mesh for each domain
for (int p = 0; p < part_num_; ++p) {
// KK;P(p);
sprintf(file_name, "%s/partition_%d", folder, parts_[p]);
P(p);
domain_[p] = new SubspaceTet(file_name, 0, NULL);
KK;
// sprintf(file_name, "%s/partition_%d.veg", folder, parts_[p]);
// std::vector<double> verts(domain_[p]->rest_pos_, domain_[p]->rest_pos_ + domain_[p]->vertex_num_ * 3);
// std::vector<int> tets(domain_[p]->tet_, domain_[p]->tet_ + domain_[p]->tet_number * 4);
// VegaTetMeshIO::Instance()->Write(file_name, verts, tets);
}
// exit(0);
vert_partition_info_ = std::vector<int>(vertex_num_ * 4, -1);
block_edge_ = Mati::Zero(part_num_, part_num_);
block_edge_.fill(-1);
{
sprintf(file_name, "%s/vert_partition.txt", folder);
std::ifstream in(file_name);
ASSERT(in.is_open(), P(file_name));
int v_num;
in >> v_num;
ASSERT(v_num == vertex_num_);
for (int i = 0; i < vertex_num_ * 4; ++i) {
in >> vert_partition_info_[i];
}
in.close();
}
vert_local_id2global_id_.resize(part_num_);
is_interface_vert_.resize(part_num_);
for (int p = 0; p < part_num_; ++p) {
is_interface_vert_[p] = std::vector<int>(domain_[p]->vertex_num_, 0);
vert_local_id2global_id_[p].resize(domain_[p]->vertex_num_);
}
part_connectivity_ = std::vector<std::vector<int> >(part_num_, std::vector<int>(part_num_, 0));
for (int v = 0; v < vertex_num_; ++v) {
// a vertex belongs to two domains
if (vert_partition_info_[v * 4 + 2] != -1) {
ASSERT(vert_partition_info_[v * 4 + 0] != -1);
int p0 = vert_partition_info_[v * 4 + 0];
int v0 = vert_partition_info_[v * 4 + 1];
int p1 = vert_partition_info_[v * 4 + 2];
int v1 = vert_partition_info_[v * 4 + 3];
part_connectivity_[p0][p1] = 1;
part_connectivity_[p1][p0] = 1;
is_interface_vert_[p0][v0] = 1;
is_interface_vert_[p1][v1] = 1;
vert_local_id2global_id_[p0][v0] = v;
vert_local_id2global_id_[p1][v1] = v;
} else {
int p0 = vert_partition_info_[v * 4 + 0];
int v0 = vert_partition_info_[v * 4 + 1];
vert_local_id2global_id_[p0][v0] = v;
}
}
std::vector<int> dummy_block_size(part_num_, 1);
auto tmp_connectivity_ = part_connectivity_;
solver::BLOCK_MATRIX_GRAPH<double> solve(tmp_connectivity_, dummy_block_size);
block_edge_num_ = solve.e_number0;
edge_list_ = std::vector<int>(solve.E, solve.E + solve.e_number0 * 2);
for (int i = 0; i < part_num_; ++i) {
for (int j = 0; j < part_num_; ++j) {
block_edge_(i, j) = tmp_connectivity_[i][j];
}
}
interface_vert_num_ = std::vector<int>(block_edge_num_, 0);
interface_vert_.resize(block_edge_num_);
for (int v = 0; v < vertex_num_; ++v) {
if (vert_partition_info_[v * 4 + 2] != -1) {
ASSERT(vert_partition_info_[v * 4 + 0] != -1);
int p0 = vert_partition_info_[v * 4 + 0];
int p1 = vert_partition_info_[v * 4 + 2];
int e = block_edge_(p0, p1);
interface_vert_num_[e]++;
interface_vert_[e].push_back(v);
interface_vert_[e].push_back(vert_partition_info_[v * 4 + 1]);
interface_vert_[e].push_back(vert_partition_info_[v * 4 + 3]);
}
}
subspace_force_projection_matrix_.resize(block_edge_num_ * 4);
ComputeVertexInterfacialArea();
}
void CubicaTet::ComputeSubspaceForceProjectionMatrix() {
typedef Eigen::Matrix<double, 6, 1> Vec6;
typedef Eigen::Matrix<double, 6, 6> Mat6;
for (int e = 0; e < block_edge_num_; ++e) {
int p0 = edge_list_[e * 2 + 0];
int p1 = edge_list_[e * 2 + 1];
Mat momentum_matrix0 = domain_[p0]->rotation_ * domain_[p0]->momentum_matrix_;
Mat momentum_matrix1 = domain_[p1]->rotation_ * domain_[p1]->momentum_matrix_;
Mat interface_torque_matrix0 = domain_[p0]->rotation_ * interface_torque_matrix_[e * 2 + 0];
Mat interface_torque_matrix1 = domain_[p1]->rotation_ * interface_torque_matrix_[e * 2 + 1];
Mat momentum_matrix0_transpose = momentum_matrix0.transpose();
Mat momentum_matrix1_transpose = momentum_matrix1.transpose();
Mat interface_torque_matrix0_transpose = interface_torque_matrix0.transpose();
Mat interface_torque_matrix1_transpose = interface_torque_matrix1.transpose();
Mat6 lagrangian_matrix;
lagrangian_matrix.block<3, 3>(0, 0) = momentum_matrix0 * momentum_matrix0_transpose +
momentum_matrix1 * momentum_matrix1_transpose;
lagrangian_matrix.block<3, 3>(0, 3) = momentum_matrix0 * interface_torque_matrix0_transpose +
momentum_matrix1 * interface_torque_matrix1_transpose;
lagrangian_matrix.block<3, 3>(3, 0) = interface_torque_matrix0 * momentum_matrix0_transpose +
interface_torque_matrix1 * momentum_matrix1_transpose;
lagrangian_matrix.block<3, 3>(3, 3) = interface_torque_matrix0 * interface_torque_matrix0_transpose +
interface_torque_matrix1 * interface_torque_matrix1_transpose;
Mat6 inv_lagrangian_matrix = (-1) * lagrangian_matrix.inverse();
// Mat ldlt = lagrangian_matrix.ldlt();
// for (int i = 0; i < 6; ++i) {
// Vec6 vec6_zero = Vec6::Zero();
// vec6_zero(i) = 1;
// inv_lagrangian_matrix.col(i) = lagrangian_matrix.ldlt().solve(vec6_zero);
// vec6_zero(i) = 0;
// }
// {
// Mat6 zero = lagrangian_matrix.inverse() * lagrangian_matrix - Mat6::Identity();
// ASSERT(zero.norm() < 1e-3, P(zero.norm(), zero.maxCoeff(), zero.minCoeff()));
// }
Mat tmp00 = inv_lagrangian_matrix.block<3, 3>(0, 0) * momentum_matrix0 +
inv_lagrangian_matrix.block<3, 3>(0, 3) * interface_torque_matrix0;
Mat tmp01 = inv_lagrangian_matrix.block<3, 3>(0, 0) * momentum_matrix1 +
inv_lagrangian_matrix.block<3, 3>(0, 3) * interface_torque_matrix1;
Mat tmp10 = inv_lagrangian_matrix.block<3, 3>(3, 0) * momentum_matrix0 +
inv_lagrangian_matrix.block<3, 3>(3, 3) * interface_torque_matrix0;
Mat tmp11 = inv_lagrangian_matrix.block<3, 3>(3, 0) * momentum_matrix1 +
inv_lagrangian_matrix.block<3, 3>(3, 3) * interface_torque_matrix1;
if (0) {
using namespace dj;
WriteEigenMatrixToMatlab(lagrangian_matrix, "/tmp/lag");
WriteEigenMatrixToMatlab(inv_lagrangian_matrix, "/tmp/invlag");
WriteEigenMatrixToMatlab(momentum_matrix0, "/tmp/m0");
WriteEigenMatrixToMatlab(momentum_matrix1, "/tmp/m1");
WriteEigenMatrixToMatlab(interface_torque_matrix0, "/tmp/t0");
WriteEigenMatrixToMatlab(interface_torque_matrix1, "/tmp/t1");
WriteEigenMatrixToMatlab(subspace_force_projection_matrix_[e * 4 + 0], "/tmp/r0");
WriteEigenMatrixToMatlab(subspace_force_projection_matrix_[e * 4 + 1], "/tmp/r1");
WriteEigenMatrixToMatlab(subspace_force_projection_matrix_[e * 4 + 2], "/tmp/r2");
WriteEigenMatrixToMatlab(subspace_force_projection_matrix_[e * 4 + 3], "/tmp/r3");
}
subspace_force_projection_matrix_[e * 4 + 0] = momentum_matrix0_transpose * tmp00 + interface_torque_matrix0_transpose * tmp10;
subspace_force_projection_matrix_[e * 4 + 1] = momentum_matrix0_transpose * tmp01 + interface_torque_matrix0_transpose * tmp11;
subspace_force_projection_matrix_[e * 4 + 2] = momentum_matrix1_transpose * tmp00 + interface_torque_matrix1_transpose * tmp10;
subspace_force_projection_matrix_[e * 4 + 3] = momentum_matrix1_transpose * tmp01 + interface_torque_matrix1_transpose * tmp11;
for (int i = 0; i < subspace_force_projection_matrix_[e * 4 + 0].rows(); ++i) {
subspace_force_projection_matrix_[e * 4 + 0](i, i) += 1;
}
for (int i = 0; i < subspace_force_projection_matrix_[e * 4 + 3].rows(); ++i) {
subspace_force_projection_matrix_[e * 4 + 3](i, i) += 1;
}
}
}
void CubicaTet::ComputeInterfaceTorqueMatrix() {
auto GetInterfaceTorqueMatrix = [&](int p, Vec3 & center_of_mass, Mat & matrix) {
matrix = Mat::Zero(3, domain_[p]->basis_num_);
for (int v = 0; v < domain_[p]->vertex_num_; ++v) {
double mass = domain_[p]->mass_[v];
for (int c = 0; c < domain_[p]->basis_num_; ++c) {
Vec3 col(domain_[p]->basis_(v * 3 + 0, c),
domain_[p]->basis_(v * 3 + 1, c),
domain_[p]->basis_(v * 3 + 2, c));
col *= mass;
MapVec3 pos(domain_[p]->rest_pos_ + v * 3);
Vec3 r = pos - center_of_mass;
Vec3 cross = r.cross(col);
matrix(0, c) += cross[0];
matrix(1, c) += cross[1];
matrix(2, c) += cross[2];
}
}
};
interface_center_of_mass_.clear();
interface_torque_matrix_.resize(block_edge_num_ * 2);
for (int e = 0; e < block_edge_num_; ++e) {
int p0 = edge_list_[e * 2 + 0];
int p1 = edge_list_[e * 2 + 1];
int vert_num = int(interface_vert_[e].size()) / 3;
Vec3 center_of_mass(0, 0, 0);
double total_mass = 0;
for (int i = 0; i < vert_num; ++i) {
int v = interface_vert_[e][i * 3 + 1];
double mass = domain_[p0]->mass_[v];
center_of_mass += (mass * MapVec3(domain_[p0]->rest_pos_ + v * 3));
total_mass += mass;
}
center_of_mass /= total_mass;
interface_center_of_mass_.push_back(center_of_mass);
GetInterfaceTorqueMatrix(p0, center_of_mass, interface_torque_matrix_[e * 2 + 0]);
GetInterfaceTorqueMatrix(p1, center_of_mass, interface_torque_matrix_[e * 2 + 1]);
}
}
void CubicaTet::LoadSubspace(std::function<const char *(int)> GetSubspaceFileName) {
basis_offset_ = std::vector<int>(part_num_ + 1, 0);
total_basis_num_ = 0;
for (int p = 0; p < part_num_; ++p) {
const char* file_name = GetSubspaceFileName(parts_[p]);
std::vector<double> basis;
int v_num, basis_num;
ReadBasisInBinary(file_name, v_num, basis_num, basis);
total_basis_num_ += basis_num;
basis_offset_[p + 1] = basis_offset_[p] + basis_num;
// ReadBasisInText(file_name, v_num, basis_num, basis);
ASSERT(v_num == domain_[p]->vertex_num_);
MapMatCol mat_basis(&basis[0], v_num * 3, basis_num);
domain_[p]->LoadSubspaceFromEigenMatrix(mat_basis);
}
ComputeInterfaceTorqueMatrix();
PreComputeInterDomainCouplingMatrix();
}
void CubicaTet::LoadCubature(std::function<const char *(int)> GetCubatureFileName) {
(void) GetCubatureFileName;
for (int p = 0; p < part_num_; ++p) {
domain_[p]->LoadCubature(NULL);
}
}
void CubicaTet::PreComputeInterDomainCouplingMatrix() {
// inter-domain coupling force on domain q, ('ed quanity is from neighbor domain
// F_vv'(q, q') = -\sum_{all v} k_v*(R*U_v*q + R*r0 + MassCenter - R'U'_v*q'- R'*r0'- R'MassCenter')
// f(q, q') = -\sum_{all v} k_v*(U_v^T*U_v*q + U_v^T*r0 + U^T*R^T*MassCenter - U_v^T*R^T*R'U'_v*q'-U_v^T*R^T*R'*r0'-U_v^T*R^TMassCenter')
// = \sum_{all v} k_v*(-U_v^T*U_v*q + U_v^T*R^T*R'*U'_v*q' + U_v^T*R^T*(-MassCenter+MassCenter') - U_v^T*r0 + U_v^T*R^T*R'*r0')
// = \sum_{all v} mat0*q + mat1*{R^T*R'}*q' + mat2*{R^T}*(-MassCenter+MassCenter') + vec0 + vec1*{R^T*R'} * r0'
// mat0 = \sum_{all v} -k_v*U_v^T*U_v
// mat1 = \sum_{all v} +k_v*U_v^T*R^T*R'*U'_v
// mat2 = \sum_{all v} +k_v*U_v^T*R^T
// vec0 = \sum_{all v} -k_v*U_v^T*r0
// vec1 = \sum_{all v} +k_v*U_v^T*R^T*R'*r0'
mat0_.resize(block_edge_num_ * 2);
mat1_.resize(block_edge_num_ * 2 * 9);
mat2_.resize(block_edge_num_ * 2 * 9);
vec0_.resize(block_edge_num_ * 2);
vec1_.resize(block_edge_num_ * 2 * 9);
for (int e = 0; e < block_edge_num_; ++e) {
int p0 = edge_list_[e * 2 + 0];
int p1 = edge_list_[e * 2 + 1];
mat0_[e * 2 + 0] = Mat::Zero(domain_[p0]->basis_num_, domain_[p0]->basis_num_);
mat0_[e * 2 + 1] = Mat::Zero(domain_[p1]->basis_num_, domain_[p1]->basis_num_);
vec0_[e * 2 + 0] = Vec::Zero(domain_[p0]->basis_num_);
vec0_[e * 2 + 1] = Vec::Zero(domain_[p1]->basis_num_);
for (int i = 0; i < 9; ++i) {
mat1_[e * 18 + i] = Mat::Zero(domain_[p0]->basis_num_, domain_[p1]->basis_num_);
mat1_[e * 18 + 9 + i] = Mat::Zero(domain_[p1]->basis_num_, domain_[p0]->basis_num_);
mat2_[e * 18 + i] = Mat::Zero(domain_[p0]->basis_num_, 3);
mat2_[e * 18 + 9 + i] = Mat::Zero(domain_[p1]->basis_num_, 3);
vec1_[e * 18 + i] = Vec::Zero(domain_[p0]->basis_num_);
vec1_[e * 18 + 9 + i] = Vec::Zero(domain_[p1]->basis_num_);
}
int vert_num = int(interface_vert_[e].size()) / 3;
for (int v = 0; v < vert_num; ++v) {
int global_v = interface_vert_[e][v * 3 + 0];
int v0 = interface_vert_[e][v * 3 + 1];
int v1 = interface_vert_[e][v * 3 + 2];
mat0_[e * 2 + 0] -= vert_interfacial_area_[global_v] * (domain_[p0]->vert_basis_transpose_[v0] * domain_[p0]->vert_basis_[v0]);
mat0_[e * 2 + 1] -= vert_interfacial_area_[global_v] * (domain_[p1]->vert_basis_transpose_[v1] * domain_[p1]->vert_basis_[v1]);
Vec3 r0 = MapVec3(domain_[p0]->rest_pos_ + v0 * 3) - domain_[p0]->center_of_mass_;
Vec3 r1 = MapVec3(domain_[p1]->rest_pos_ + v1 * 3) - domain_[p1]->center_of_mass_;
vec0_[e * 2 + 0] -= vert_interfacial_area_[global_v] * (domain_[p0]->vert_basis_transpose_[v0] * r0);
vec0_[e * 2 + 1] -= vert_interfacial_area_[global_v] * (domain_[p1]->vert_basis_transpose_[v1] * r1);
for (int row = 0, idx = 0; row < 3; ++row) {
for (int col = 0; col < 3; ++col, ++idx) {
Mat3 R = Mat3::Zero();
R(row, col) = 1;
mat1_[e * 18 + idx] += vert_interfacial_area_[global_v] * (domain_[p0]->vert_basis_transpose_[v0] * (R * domain_[p1]->vert_basis_[v1]));
mat1_[e * 18 + 9 + idx] += vert_interfacial_area_[global_v] * (domain_[p1]->vert_basis_transpose_[v1] * (R * domain_[p0]->vert_basis_[v0]));
mat2_[e * 18 + idx] += vert_interfacial_area_[global_v] * (domain_[p0]->vert_basis_transpose_[v0] * R);
mat2_[e * 18 + 9 + idx] += vert_interfacial_area_[global_v] * (domain_[p1]->vert_basis_transpose_[v1] * R);
vec1_[e * 18 + idx] += vert_interfacial_area_[global_v] * (domain_[p0]->vert_basis_transpose_[v0] * R * r1);
vec1_[e * 18 + 9 + idx] += vert_interfacial_area_[global_v] * (domain_[p1]->vert_basis_transpose_[v1] * R * r0);
}
}
}
}
}
//int CubicaTet::Select(double *ray_start, double *ray_end, double *clicked_world_pos, double *selected_pos)
//{
// for (int p = 0; p < vertex_num_; ++p) {
// int vert = domain_[p]->Select(ray_start, ray_end, clicked_world_pos, selected_pos);
// if (vert >= 0) {
// ui_selected_domain_ = p;
// return vert;
// }
// }
// return -1;
//}
//bool CubicaTet::GetVertexPosition(double *pos)
//{
// if (ui_selected_domain_ >= 0) {
// SubspaceTet* mesh = domain_[ui_selected_domain_];
// int vert = mesh->SelectedVertex();
//// ASSERT(vert >= 0);
// pos[0] = mesh->X[vert * 3 + 0];
// pos[1] = mesh->X[vert * 3 + 1];
// pos[2] = mesh->X[vert * 3 + 2];
// return true;
// } else {
// return false;
// }
//}
template <class Vector0, class Vector1>
void CubicaTet::ProjectSubspaceForce(int e, Vector0 &force0, Vector1 &force1) {
#if 0
force0 = subspace_force_projection_matrix_[e * 4 + 0] * force0 + subspace_force_projection_matrix_[e * 4 + 1] * force1;
force1 = subspace_force_projection_matrix_[e * 4 + 2] * force0 + subspace_force_projection_matrix_[e * 4 + 3] * force1;
#else
typedef Eigen::Matrix<double, 6, 1> Vec6;
int p0 = edge_list_[e * 2 + 0];
int p1 = edge_list_[e * 2 + 1];
// P(domain_container_.size());
Mat3 rot0 = domain_[p0]->rotation_;
Mat3 rot1 = domain_[p1]->rotation_;
Mat3 rot0_tran = rot0.transpose();
Mat3 rot1_tran = rot1.transpose();
Mat6 lagrangian_matrix;
Mat mom0 = domain_[p0]->momentum_matrix_;
Mat mom1 = domain_[p1]->momentum_matrix_;
Mat mom0_tran = mom0.transpose();
Mat mom1_tran = mom1.transpose();
Mat tor0 = interface_torque_matrix_[e * 2 + 0];
Mat tor1 = interface_torque_matrix_[e * 2 + 1];
Mat tor0_tran = tor0.transpose();
Mat tor1_tran = tor1.transpose();
lagrangian_matrix.block<3, 3>(0, 0) = rot0 * (mom0 * mom0_tran) * rot0_tran + rot1 * (mom1 * mom1_tran) * rot1_tran;
lagrangian_matrix.block<3, 3>(0, 3) = rot0 * (mom0 * tor0_tran) * rot0_tran + rot1 * (mom1 * tor1_tran) * rot1_tran;
lagrangian_matrix.block<3, 3>(3, 0) = rot0 * (tor0 * mom0_tran) * rot0_tran + rot1 * (tor1 * mom1_tran) * rot1_tran;
lagrangian_matrix.block<3, 3>(3, 3) = rot0 * (tor0 * tor0_tran) * rot0_tran + rot1 * (tor1 * tor1_tran) * rot1_tran;
Vec6 residual;
residual.block<3, 1>(0, 0) = rot0 * (mom0 * force0) + rot1 * (mom1 * force1);
residual.block<3, 1>(3, 0) = rot0 * (tor0 * force0) + rot1 * (tor1 * force1);
Vec6 lagranian_multiplier = lagrangian_matrix.ldlt().solve(residual);
MapVec3 lambda0(&lagranian_multiplier[0]);
if (0) {
using namespace dj;
WriteEigenMatrixToMatlab(lagrangian_matrix, "/tmp/lag");
Mat m0 = rot0 * mom0;
Mat m1 = rot1 * mom1;
Mat t0 = rot0 * tor0;
Mat t1 = rot1 * tor1;
// WriteEigenMatrixToMatlab(inv_lagrangian_matrix, "/tmp/invlag");
WriteEigenMatrixToMatlab(m0, "/tmp/m0");
WriteEigenMatrixToMatlab(m1, "/tmp/m1");
WriteEigenMatrixToMatlab(t0, "/tmp/t0");
WriteEigenMatrixToMatlab(t1, "/tmp/t1");
WriteVectorToMatlab(6, &lagranian_multiplier[0], "/tmp/lambda");
WriteVectorToMatlab(force0.size(), &force0[0], "/tmp/f0");
WriteVectorToMatlab(force1.size(), &force1[0], "/tmp/f1");
}
MapVec3 lambda1(&lagranian_multiplier[3]);
force0 -= (mom0_tran * (rot0_tran * lambda0)) + (tor0_tran * (rot0_tran * lambda1));
force1 -= (mom1_tran * (rot1_tran * lambda0)) + (tor1_tran * (rot1_tran * lambda1));
if (0) {
using namespace dj;
WriteVectorToMatlab(force0.size(), &force0[0], "/tmp/truth0");
WriteVectorToMatlab(force1.size(), &force1[0], "/tmp/truth1");
}
// force0 = -(mom0_tran * (rot0_tran * lambda0)) + (tor0_tran * (rot0_tran * lambda1));
// force1 = -(mom1_tran * (rot1_tran * lambda0)) + (tor1_tran * (rot1_tran * lambda1));
#endif
}
CubicaTet::~CubicaTet() {
for (SubspaceTet * tet : domain_container_) {
delete tet;
}
}
void CubicaTet::Simulate(double dt) {
const float kInternalForceScaling = conf.Get<double>("internal force scaling");
// dt = 0.033; P(dt);
std::vector<Vec3> net_force(part_num_, Vec3(0, 0, 0));
std::vector<Vec3> net_torque(part_num_, Vec3(0, 0, 0));
// gravity
for (int p = 0; p < part_num_; ++p) {
net_force[p] += domain_[p]->total_mass_ * gravity_;
}
// collision
std::vector<std::tuple<int, int, Vec3> > collision_force;
collision_force.reserve(vertex_num_ / 100);
const double kFloor = 0.00;
const double kFloorStiffness = 3000;
for (int p = 0; p < part_num_; ++p) {
for (int v = 0; v < domain_[p]->vertex_num_; ++v) {
// if (0)
if (domain_[p]->X[v * 3 + 1] < kFloor) {
Vec3 force(0, 0, 0);
force[1] = (kFloor - domain_[p]->X[v * 3 + 1]) * domain_[p]->mass_[v] * kFloorStiffness;
collision_force.emplace_back(p, v, force);
net_force[p][1] += force[1];
Vec3 r = MapVec3(domain_[p]->X + v * 3) - domain_[p]->center_of_mass_;
net_torque[p] += r.cross(force);
}
}
}
Vec3 force;
int ui_force_vert = GetUIForce(&force[0]);
if (ui_force_vert >= 0) {
int p = vert_partition_info_[ui_force_vert * 4 + 0];
int local_v = vert_partition_info_[ui_force_vert * 4 + 1];
collision_force.emplace_back(p, local_v, force);
}
#define ASSUME_RIGID
// ComputeSubspaceForceProjectionMatrix();
// inter-domain elastic force
// if (0)
for (int e = 0; e < block_edge_num_; ++e) {
int p0 = edge_list_[e * 2 + 0];
int p1 = edge_list_[e * 2 + 1];
// inter-domain coupling force on domain q, ('ed quanity is from neighbor domain
// F_vv'(q, q') = -\sum_{all v} k_v*(R*U_v*q + R*r0 + MassCenter - R'U'_v*q'- R'*r0'- R'MassCenter')
// f(q, q') = -\sum_{all v} k_v*(U_v^T*U_v*q + U_v^T*r0 + U^T*R^T*MassCenter - U_v^T*R^T*R'U'_v*q'-U_v^T*R^T*R'*r0'-U_v^T*R^TMassCenter')
// = \sum_{all v} k_v*(-U_v^T*U_v*q + U_v^T*R^T*R'*U'_v*q' + U_v^T*R^T*(-MassCenter+MassCenter') - U_v^T*r0 + U_v^T*R^T*R'*r0')
// = \sum_{all v} mat0*q + mat1*{R^T*R'}*q' + mat2*{R^T}*(-MassCenter+MassCenter') + vec0 + vec1*{R^T*R'}
// mat0 = \sum_{all v} -k_v*U_v^T*U_v
// mat1 = \sum_{all v} +k_v*U_v^T*R^T*R'*U'_v
// mat2 = \sum_{all v} +k_v*U_v^T*R^T
// vec0 = \sum_{all v} -k_v*U_v^T*r0
// vec1 = \sum_{all v} +k_v*U_v^T*R^T*R'*r0'
#ifndef ASSUME_RIGID
Vec subspace_force0 = mat0_[e * 2 + 0] * domain_[p0]->q_ + vec0_[e * 2 + 0];
Vec subspace_force1 = mat0_[e * 2 + 1] * domain_[p1]->q_ + vec0_[e * 2 + 1];
Mat mat10 = Mat::Zero(domain_[p0]->basis_num_, domain_[p0]->basis_num_);
Mat mat11 = Mat::Zero(domain_[p1]->basis_num_, domain_[p1]->basis_num_);
Mat mat20 = Mat::Zero(domain_[p0]->basis_num_, 3);
Mat mat21 = Mat::Zero(domain_[p1]->basis_num_, 3);
Vec vec10 = Vec::Zero(domain_[p0]->basis_num_);
Vec vec11 = Vec::Zero(domain_[p1]->basis_num_);
Mat3& rot0 = domain_[p0]->rotation_;
Mat3 rot0_tran = rot0.transpose();
Mat3& rot1 = domain_[p1]->rotation_;
Mat3 rot1_tran = rot1.transpose();
Mat3 rot0_tran_dot_rot1 = rot0_tran * rot1;
Mat3 rot1_tran_dot_rot0 = rot1_tran * rot0;
for (int row = 0, idx = 0; row < 3; ++row) {
for (int col = 0; col < 3; ++col, ++idx) {
mat10 += rot0_tran_dot_rot1(row, col) * mat1_[e * 18 + idx];
mat11 += rot1_tran_dot_rot0(row, col) * mat1_[e * 18 + 9 + idx];
mat20 += rot0_tran(row, col) * mat2_[e * 18 + idx];
mat21 += rot1_tran(row, col) * mat2_[e * 18 + 9 + idx];
vec10 += rot0_tran_dot_rot1(row, col) * vec1_[e * 18 + idx];
vec11 += rot1_tran_dot_rot0(row, col) * vec1_[e * 18 + 9 + idx];
}
}
Vec diff_mass_center = domain_[p1]->center_of_mass_ - domain_[p0]->center_of_mass_;
subspace_force0 += mat10 * domain_[p0]->q_ + mat20 * (diff_mass_center) + vec10;
subspace_force1 += mat11 * domain_[p1]->q_ - mat21 * (diff_mass_center) + vec11;
#else
Vec subspace_force0 = vec0_[e * 2 + 0];
Vec subspace_force1 = vec0_[e * 2 + 1];
Mat mat10 = Mat::Zero(domain_[p0]->basis_num_, domain_[p0]->basis_num_);
Mat mat11 = Mat::Zero(domain_[p1]->basis_num_, domain_[p1]->basis_num_);
Mat mat20 = Mat::Zero(domain_[p0]->basis_num_, 3);
Mat mat21 = Mat::Zero(domain_[p1]->basis_num_, 3);
Vec vec10 = Vec::Zero(domain_[p0]->basis_num_);
Vec vec11 = Vec::Zero(domain_[p1]->basis_num_);
Mat3& rot0 = domain_[p0]->rotation_;
Mat3 rot0_tran = rot0.transpose();
Mat3& rot1 = domain_[p1]->rotation_;
Mat3 rot1_tran = rot1.transpose();
Mat3 rot0_tran_dot_rot1 = rot0_tran * rot1;
Mat3 rot1_tran_dot_rot0 = rot1_tran * rot0;
for (int row = 0, idx = 0; row < 3; ++row) {
for (int col = 0; col < 3; ++col, ++idx) {
mat10 += rot0_tran_dot_rot1(row, col) * mat1_[e * 18 + idx];
mat11 += rot1_tran_dot_rot0(row, col) * mat1_[e * 18 + 9 + idx];
mat20 += rot0_tran(row, col) * mat2_[e * 18 + idx];
mat21 += rot1_tran(row, col) * mat2_[e * 18 + 9 + idx];
vec10 += rot0_tran_dot_rot1(row, col) * vec1_[e * 18 + idx];
vec11 += rot1_tran_dot_rot0(row, col) * vec1_[e * 18 + 9 + idx];
}
}
Vec diff_mass_center = domain_[p1]->center_of_mass_ - domain_[p0]->center_of_mass_;
subspace_force0 += vec10 + mat20 * (diff_mass_center);
subspace_force1 += vec11 - mat21 * (diff_mass_center);
#endif
// Verify fast sandwich transform
if (0) {
Vec f0, f1;
ComputeInterDomainSubspaceForce(e, f0, f1);
Vec diff0 = f0 - subspace_force0;
Vec diff1 = f1 - subspace_force1;
// P(diff0.norm(), f0.norm(), subspace_force0.norm());
// P(diff1.norm(), f1.norm(), subspace_force1.norm());
ASSERT(diff0.norm() < 1e-8, P(diff0.norm(), f0.norm(), subspace_force0.norm()));
ASSERT(diff1.norm() < 1e-8, P(diff1.norm(), f1.norm(), subspace_force1.norm()));
}
// {
// Vec f0 = subspace_force0, f1 = subspace_force1;
// PROJECT_SUBSPACE_FORCE(e, f0, f1);
// }
ProjectSubspaceForce(e, subspace_force0, subspace_force1);
if (0) {
// Vec diff0 = f0 - subspace_force0;
// Vec diff1 = f1 - subspace_force1;
// P(diff0.norm(), f0.norm(), subspace_force0.norm());
// P(diff1.norm(), f1.norm(), subspace_force1.norm());
// ASSERT(diff0.norm() < 1e-8);
// ASSERT(diff1.norm() < 1e-8);
}
// Verify projection matrix
if (0) {
{
Vec f0 = rot0 * (domain_[p0]->momentum_matrix_ * subspace_force0);
Vec f1 = rot1 * (domain_[p1]->momentum_matrix_ * subspace_force1);
Vec diff = f0 + f1;
ASSERT(diff.norm() < 1e-7, P(diff.norm(), f0.norm(), f1.norm()));
}
{
Vec f0 = rot0 * (interface_torque_matrix_[e * 2 + 0] * subspace_force0);
Vec f1 = rot1 * (interface_torque_matrix_[e * 2 + 1] * subspace_force1);
Vec diff = f0 + f1;
ASSERT(diff.norm() < 1e-7, P(diff.norm(), f0.norm(), f1.norm()));
// P(diff.norm());
}
}
net_force[p0] += rot0 * (domain_[p0]->momentum_matrix_ * subspace_force0);
net_torque[p0] += rot0 * (domain_[p0]->torque_matrix_ * subspace_force0);
// P(net_force[p0], net_torque[p0]);
net_force[p1] += rot1 * (domain_[p1]->momentum_matrix_ * subspace_force1);
net_torque[p1] += rot1 * (domain_[p1]->torque_matrix_ * subspace_force1);
}
Vec rigid_rhs = Vec::Zero(part_num_ * 6);
Mat rigid_k = Mat::Zero(part_num_ * 6, part_num_ * 6);
for (int p = 0; p < part_num_; ++p) {
SubspaceTet* mesh = domain_[p];
MapVec3 force_rhs(&rigid_rhs[p * 6 + 0]);
MapVec3 torque_rhs(&rigid_rhs[p * 6 + 3]);
// net_force[p].setZero();
force_rhs = net_force[p] * dt + mesh->total_mass_ * mesh->translation_vel_;
Mat3 cur_inertial_tensor = mesh->rotation_ * mesh->inertial_tensor_ * mesh->rotation_.transpose();
// net_torque[p].setZero();
torque_rhs = net_torque[p] * dt + cur_inertial_tensor * mesh->angular_vel_;
}
auto Dr_Dw = [](Mat3 & rotation, Mat3 & dr_dx, Mat3 & dr_dy, Mat3 & dr_dz) {
dr_dx(0, 0) = dr_dx(0, 1) = dr_dx(0, 2) = 0;
dr_dx(1, 0) = -rotation(2, 0);
dr_dx(1, 1) = -rotation(2, 1);
dr_dx(1, 2) = -rotation(2, 2);
dr_dx(2, 0) = +rotation(1, 0);
dr_dx(2, 1) = +rotation(1, 1);
dr_dx(2, 2) = +rotation(1, 2);
dr_dy(1, 0) = dr_dy(1, 1) = dr_dy(1, 2) = 0;
dr_dy(0, 0) = +rotation(2, 0);
dr_dy(0, 1) = +rotation(2, 1);
dr_dy(0, 2) = +rotation(2, 2);
dr_dy(2, 0) = -rotation(0, 0);
dr_dy(2, 1) = -rotation(0, 1);
dr_dy(2, 2) = -rotation(0, 2);
dr_dz(2, 0) = dr_dz(2, 1) = dr_dz(2, 2) = 0;
dr_dz(0, 0) = -rotation(1, 0);
dr_dz(0, 1) = -rotation(1, 1);
dr_dz(0, 2) = -rotation(1, 2);
dr_dz(1, 0) = +rotation(0, 0);
dr_dz(1, 1) = +rotation(0, 1);
dr_dz(1, 2) = +rotation(0, 2);
};
// TODO delete
// if (0)
for (int e = 0; e < block_edge_num_; ++e) {
int p0 = edge_list_[e * 2 + 0];
int p1 = edge_list_[e * 2 + 1];
Mat t_mat2_0 = Mat::Zero(domain_[p0]->basis_num_, 3);
Mat t_mat2_1 = Mat::Zero(domain_[p1]->basis_num_, 3);
Mat r_mat1_vec1_0_r0 = Mat::Zero(domain_[p0]->basis_num_, 3);
Mat r_mat1_vec1_0_r1 = Mat::Zero(domain_[p0]->basis_num_, 3);
Mat r_mat1_vec1_1_r0 = Mat::Zero(domain_[p1]->basis_num_, 3);
Mat r_mat1_vec1_1_r1 = Mat::Zero(domain_[p1]->basis_num_, 3);
Vec diff_mass_center = domain_[p1]->center_of_mass_ - domain_[p0]->center_of_mass_;
Mat3& rot0 = domain_[p0]->rotation_;
Mat3& rot1 = domain_[p1]->rotation_;
Mat3 dr0_dx, dr0_dy, dr0_dz;
Mat3 dr1_dx, dr1_dy, dr1_dz;
Dr_Dw(rot0, dr0_dx, dr0_dy, dr0_dz);
Dr_Dw(rot1, dr1_dx, dr1_dy, dr1_dz);
Mat3 dr0_T_r1_dx0 = (dr0_dx.transpose() * domain_[p1]->rotation_);
Mat3 dr0_T_r1_dy0 = (dr0_dy.transpose() * domain_[p1]->rotation_);
Mat3 dr0_T_r1_dz0 = (dr0_dz.transpose() * domain_[p1]->rotation_);
Mat3 dr0_T_r1_dx1 = (domain_[p0]->rotation_.transpose() * dr1_dx);
Mat3 dr0_T_r1_dy1 = (domain_[p0]->rotation_.transpose() * dr1_dy);
Mat3 dr0_T_r1_dz1 = (domain_[p0]->rotation_.transpose() * dr1_dz);
Mat3 dr1_T_r0_dx0 = (domain_[p1]->rotation_.transpose() * dr0_dx);
Mat3 dr1_T_r0_dy0 = (domain_[p1]->rotation_.transpose() * dr0_dy);
Mat3 dr1_T_r0_dz0 = (domain_[p1]->rotation_.transpose() * dr0_dz);
Mat3 dr1_T_r0_dx1 = (dr1_dx.transpose() * domain_[p0]->rotation_);
Mat3 dr1_T_r0_dy1 = (dr1_dy.transpose() * domain_[p0]->rotation_);
Mat3 dr1_T_r0_dz1 = (dr1_dz.transpose() * domain_[p0]->rotation_);
// = \sum_{all v} R * (mat0*q + mat1*{R^T*R'}*q' + mat2*{R^T}*(-MassCenter+MassCenter') + vec0 + vec1*{R^T*R'})
for (int row = 0, idx = 0; row < 3; ++row) {
for (int col = 0; col < 3; ++col, ++idx) {
t_mat2_0 += mat2_[e * 18 + 0 + idx] * domain_[p0]->rotation_(col, row); // rotation tranpose
t_mat2_1 += mat2_[e * 18 + 9 + idx] * domain_[p1]->rotation_(col, row); // rotation tranpose
#ifndef ASSUME_RIGID
r_mat1_vec1_0_r0.col(0) += (mat1_[e * 18 + idx] * domain_[p0]->q_ + vec1_[e * 18 + idx]) * dr0_T_r1_dx0(row, col) +
mat2_[e * 18 + idx] * (dr0_dx(col, row) * diff_mass_center); // tranpose
r_mat1_vec1_0_r0.col(1) += (mat1_[e * 18 + idx] * domain_[p0]->q_ + vec1_[e * 18 + idx]) * dr0_T_r1_dy0(row, col) +
mat2_[e * 18 + idx] * (dr0_dy(col, row) * diff_mass_center); // tranpose
r_mat1_vec1_0_r0.col(2) += (mat1_[e * 18 + idx] * domain_[p0]->q_ + vec1_[e * 18 + idx]) * dr0_T_r1_dz0(row, col) +
mat2_[e * 18 + idx] * (dr0_dz(col, row) * diff_mass_center); // tranpose
r_mat1_vec1_0_r1.col(0) += (mat1_[e * 18 + idx] * domain_[p0]->q_ + vec1_[e * 18 + idx]) * dr0_T_r1_dx1(row, col);
r_mat1_vec1_0_r1.col(1) += (mat1_[e * 18 + idx] * domain_[p0]->q_ + vec1_[e * 18 + idx]) * dr0_T_r1_dy1(row, col);
r_mat1_vec1_0_r1.col(2) += (mat1_[e * 18 + idx] * domain_[p0]->q_ + vec1_[e * 18 + idx]) * dr0_T_r1_dz1(row, col);
r_mat1_vec1_1_r0.col(0) += (mat1_[e * 18 + 9 + idx] * domain_[p1]->q_ + vec1_[e * 18 + 9 + idx]) * dr1_T_r0_dx0(row, col);
r_mat1_vec1_1_r0.col(1) += (mat1_[e * 18 + 9 + idx] * domain_[p1]->q_ + vec1_[e * 18 + 9 + idx]) * dr1_T_r0_dy0(row, col);
r_mat1_vec1_1_r0.col(2) += (mat1_[e * 18 + 9 + idx] * domain_[p1]->q_ + vec1_[e * 18 + 9 + idx]) * dr1_T_r0_dz0(row, col);
r_mat1_vec1_1_r1.col(0) += (mat1_[e * 18 + 9 + idx] * domain_[p1]->q_ + vec1_[e * 18 + 9 + idx]) * dr1_T_r0_dx1(row, col) +
mat2_[e * 18 + 9 + idx] * (-dr1_dx(col, row) * diff_mass_center);// transpose
r_mat1_vec1_1_r1.col(1) += (mat1_[e * 18 + 9 + idx] * domain_[p1]->q_ + vec1_[e * 18 + 9 + idx]) * dr1_T_r0_dy1(row, col) +
mat2_[e * 18 + 9 + idx] * (-dr1_dy(col, row) * diff_mass_center);// transpose
r_mat1_vec1_1_r1.col(2) += (mat1_[e * 18 + 9 + idx] * domain_[p1]->q_ + vec1_[e * 18 + 9 + idx]) * dr1_T_r0_dz1(row, col) +
mat2_[e * 18 + 9 + idx] * (-dr1_dz(col, row) * diff_mass_center);// transpose
#else
r_mat1_vec1_0_r0.col(0) += (vec1_[e * 18 + idx]) * dr0_T_r1_dx0(row, col) +
mat2_[e * 18 + idx] * (dr0_dx(col, row) * diff_mass_center); // tranpose
r_mat1_vec1_0_r0.col(1) += (vec1_[e * 18 + idx]) * dr0_T_r1_dy0(row, col) +
mat2_[e * 18 + idx] * (dr0_dy(col, row) * diff_mass_center); // tranpose
r_mat1_vec1_0_r0.col(2) += (vec1_[e * 18 + idx]) * dr0_T_r1_dz0(row, col) +
mat2_[e * 18 + idx] * (dr0_dz(col, row) * diff_mass_center); // tranpose
r_mat1_vec1_0_r1.col(0) += (vec1_[e * 18 + idx]) * dr0_T_r1_dx1(row, col);
r_mat1_vec1_0_r1.col(1) += (vec1_[e * 18 + idx]) * dr0_T_r1_dy1(row, col);
r_mat1_vec1_0_r1.col(2) += (vec1_[e * 18 + idx]) * dr0_T_r1_dz1(row, col);
r_mat1_vec1_1_r0.col(0) += (vec1_[e * 18 + 9 + idx]) * dr1_T_r0_dx0(row, col);
r_mat1_vec1_1_r0.col(1) += (vec1_[e * 18 + 9 + idx]) * dr1_T_r0_dy0(row, col);
r_mat1_vec1_1_r0.col(2) += (vec1_[e * 18 + 9 + idx]) * dr1_T_r0_dz0(row, col);
r_mat1_vec1_1_r1.col(0) += (vec1_[e * 18 + 9 + idx]) * dr1_T_r0_dx1(row, col) +
mat2_[e * 18 + 9 + idx] * (-dr1_dx(col, row) * diff_mass_center);// transpose
r_mat1_vec1_1_r1.col(1) += (vec1_[e * 18 + 9 + idx]) * dr1_T_r0_dy1(row, col) +
mat2_[e * 18 + 9 + idx] * (-dr1_dy(col, row) * diff_mass_center);// transpose
r_mat1_vec1_1_r1.col(2) += (vec1_[e * 18 + 9 + idx]) * dr1_T_r0_dz1(row, col) +
mat2_[e * 18 + 9 + idx] * (-dr1_dz(col, row) * diff_mass_center);// transpose
#endif
}
}
t_mat2_0 *= -1;
for (int col = 0; col < 3; ++col) {
{
auto f0 = t_mat2_0.col(col);
auto f1 = t_mat2_1.col(col);
ProjectSubspaceForce(e, f0, f1);
}
{
auto f0 = r_mat1_vec1_0_r0.col(col);
auto f1 = r_mat1_vec1_1_r0.col(col);
ProjectSubspaceForce(e, f0, f1);
}
{
auto f0 = r_mat1_vec1_0_r1.col(col);
auto f1 = r_mat1_vec1_1_r1.col(col);
ProjectSubspaceForce(e, f0, f1);
}
}
// rotation
rigid_k.block<3, 3>(p0 * 6 + 0, p0 * 6 + 3) += rot0 * domain_[p0]->momentum_matrix_ * r_mat1_vec1_0_r0;
rigid_k.block<3, 3>(p0 * 6 + 3, p0 * 6 + 3) += rot0 * domain_[p0]->torque_matrix_ * r_mat1_vec1_0_r0;
rigid_k.block<3, 3>(p0 * 6 + 0, p1 * 6 + 3) += rot0 * domain_[p0]->momentum_matrix_ * r_mat1_vec1_0_r1;
rigid_k.block<3, 3>(p0 * 6 + 3, p1 * 6 + 3) += rot0 * domain_[p0]->torque_matrix_ * r_mat1_vec1_0_r1;
rigid_k.block<3, 3>(p1 * 6 + 0, p0 * 6 + 3) += rot1 * domain_[p1]->momentum_matrix_ * r_mat1_vec1_1_r0;
rigid_k.block<3, 3>(p1 * 6 + 3, p0 * 6 + 3) += rot1 * domain_[p1]->torque_matrix_ * r_mat1_vec1_1_r0;
rigid_k.block<3, 3>(p1 * 6 + 0, p1 * 6 + 3) += rot1 * domain_[p1]->momentum_matrix_ * r_mat1_vec1_1_r1;
rigid_k.block<3, 3>(p1 * 6 + 3, p1 * 6 + 3) += rot1 * domain_[p1]->torque_matrix_ * r_mat1_vec1_1_r1;
// translation
rigid_k.block<3, 3>(p0 * 6 + 0, p0 * 6) += rot0 * domain_[p0]->momentum_matrix_ * t_mat2_0;
rigid_k.block<3, 3>(p0 * 6 + 3, p0 * 6) += rot0 * domain_[p0]->torque_matrix_ * t_mat2_0;
rigid_k.block<3, 3>(p0 * 6 + 0, p1 * 6) -= rot0 * domain_[p0]->momentum_matrix_ * t_mat2_0;
rigid_k.block<3, 3>(p0 * 6 + 3, p1 * 6) -= rot0 * domain_[p0]->torque_matrix_ * t_mat2_0;
rigid_k.block<3, 3>(p1 * 6 + 0, p0 * 6) += rot1 * domain_[p1]->momentum_matrix_ * t_mat2_1;
rigid_k.block<3, 3>(p1 * 6 + 3, p0 * 6) += rot1 * domain_[p1]->torque_matrix_ * t_mat2_1;
rigid_k.block<3, 3>(p1 * 6 + 0, p1 * 6) -= rot1 * domain_[p1]->momentum_matrix_ * t_mat2_1;
rigid_k.block<3, 3>(p1 * 6 + 3, p1 * 6) -= rot1 * domain_[p1]->torque_matrix_ * t_mat2_1;
}
rigid_k *= -dt * dt;
for (int p = 0; p < part_num_; ++p) {
SubspaceTet* mesh = domain_[p];
Mat3 cur_inertial_tensor = mesh->rotation_ * mesh->inertial_tensor_ * mesh->rotation_.transpose();
rigid_k(p * 6 + 0, p * 6 + 0) += mesh->total_mass_;
rigid_k(p * 6 + 1, p * 6 + 1) += mesh->total_mass_;
rigid_k(p * 6 + 2, p * 6 + 2) += mesh->total_mass_;
rigid_k.block<3, 3>(p * 6 + 3, p * 6 + 3) += cur_inertial_tensor;
}
// PVEC(nt_force[0]);
// P(rigid_rhs.norm());
// P(rigid_k.norm());
// WriteEigenMatrixToMatlab(rigid_k, "/tmp/log/k");
Vec new_rigid_vel = rigid_k.colPivHouseholderQr().solve(rigid_rhs);
// new_rigid_vel.setZero();
if (0) {
Vec diff = rigid_k * new_rigid_vel - rigid_rhs;
P(diff.norm());
P(new_rigid_vel.norm());
}
for (int p = 0; p < part_num_; ++p) {
domain_[p]->translation_acc_ = (MapVec3(&new_rigid_vel[p * 6]) - domain_[p]->translation_vel_) / dt;
domain_[p]->angular_acc_ = (MapVec3(&new_rigid_vel[p * 6 + 3]) - domain_[p]->angular_vel_) / dt;
// P(p, dj::Vec3d(domain_[p]->translation_acc_.data()), dj::Vec3d(domain_[p]->angular_acc_.data()));
}
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// Local deformation
#if 1
Vec rhs = Vec::Zero(total_basis_num_);
// collision force
for (int i = 0; i < int(collision_force.size()); ++i) {
int& p = std::get<0>(collision_force[i]);
int& v = std::get<1>(collision_force[i]);
Vec3 force = domain_[p]->rotation_.transpose() * std::get<2>(collision_force[i]);
MapVec subspace_force(&rhs[basis_offset_[p]], domain_[p]->basis_num_);
subspace_force += domain_[p]->vert_basis_transpose_[v] * force;
}
// gravity and fititious force
for (int p = 0; p < part_num_; ++p) {
domain_[p]->AddFictitiousForceAndGravity(&rhs[basis_offset_[p]]);
}
Mat k = Mat::Zero(total_basis_num_, total_basis_num_);
// reduced internal force and diagonal terms of reduce k
for (int p = 0; p < part_num_; ++p) {
int basis_num = domain_[p]->basis_num_;
domain_[p]->inv_fem_->ComputeInternalForceAndTangentStiffnessMatrix(dt);
MatCol part_reduced_k;
domain_[p]->GetReducedTangentStiffnessMatrix(part_reduced_k);
k.block(basis_offset_[p], basis_offset_[p], basis_num, basis_num) += part_reduced_k;
MapVec subspace_force(&rhs[basis_offset_[p]], domain_[p]->basis_num_);
// vega internal force is in opposite direction of actual force
subspace_force -= kInternalForceScaling *
(domain_[p]->basis_transpose_ * MapVec((double*) domain_[p]->inv_fem_->internal_force_, domain_[p]->vertex_num_ * 3));
subspace_force *= dt;
subspace_force += domain_[p]->vel_q_;
}
// off diagonal terms of reudced k
// = \sum_{all v} (mat0*q + mat1*{R^T*R'}*q' + mat2*{R^T}*(-MassCenter+MassCenter') + vec0 + vec1*{R^T*R'})
for (int e = 0; e < block_edge_num_; ++e) {
int p0 = edge_list_[e * 2 + 0];
int p1 = edge_list_[e * 2 + 1];
Mat mat1_0 = Mat::Zero(domain_[p0]->basis_num_, domain_[p1]->basis_num_);
Mat mat1_1 = Mat::Zero(domain_[p1]->basis_num_, domain_[p0]->basis_num_);
Mat3& rot0 = domain_[p0]->rotation_;
Mat3& rot1 = domain_[p1]->rotation_;
Mat3 r0_T_dot_r1 = rot0.transpose() * rot1;
Mat3 r1_T_dot_r0 = r0_T_dot_r1.transpose();
// F = (mat0*q + mat1*{R^T*R'}*q' + mat2*{R^T}*(-MassCenter+MassCenter') + vec0 + vec1*{R^T*R'})
for (int row = 0, idx = 0; row < 3; ++row) {
for (int col = 0; col < 3; ++col, ++idx) {
mat1_0 += mat1_[e * 18 + 0 + idx] * r0_T_dot_r1(row, col);
mat1_1 += mat1_[e * 18 + 9 + idx] * r1_T_dot_r0(row, col);
}
}
k.block(basis_offset_[p0], basis_offset_[p0], domain_[p0]->basis_num_, domain_[p0]->basis_num_) -= mat0_[e * 2 + 0];
k.block(basis_offset_[p0], basis_offset_[p1], domain_[p0]->basis_num_, domain_[p1]->basis_num_) -= mat1_0;
k.block(basis_offset_[p1], basis_offset_[p1], domain_[p1]->basis_num_, domain_[p1]->basis_num_) -= mat0_[e * 2 + 1];
k.block(basis_offset_[p1], basis_offset_[p0], domain_[p1]->basis_num_, domain_[p0]->basis_num_) -= mat1_1;
}
k *= (kInternalForceScaling * dt * dt);
for (int i = 0; i < total_basis_num_; ++i) {
k(i, i) += 1;
}
Vec new_vel_q = k.colPivHouseholderQr().solve(rhs);
// P(new_vel_q.norm());
if (0) {
Vec diff = k * new_vel_q - rhs;
P(diff.norm());
}
// new_vel_q.setZero();
for (int p = 0; p < part_num_; ++p) {
MapVec part_vel(&new_vel_q[basis_offset_[p]], domain_[p]->basis_num_);
domain_[p]->vel_q_ = part_vel;
domain_[p]->q_ += domain_[p]->vel_q_ * dt;
domain_[p]->vel_q_ *= 0.96;
}
#endif
profiler.Start("update");
OMP_FOR
for (int p = 0; p < part_num_; ++p) {
domain_[p]->UpdateRigidMotionAndLocalDeformation(dt);
}
profiler.End("update");
}
void CubicaTet::NextRenderMode() {
for (SubspaceTet * tet : domain_container_) {
tet->NextRenderMode();
}
}
void CubicaTet::Render() {
// Super::Render(); return;
for (SubspaceTet * tet : domain_container_) {
tet->Render();
}
if (1) {
glPointSize(8);
glColor3f(1, 1, 1);
glBegin(GL_POINTS);
for (int p = 0; p < part_num_; ++p) {
Vertex3v(&domain_[p]->center_of_mass_[0]);
}
glEnd();
}
}
void CubicaTet::ComputeInterDomainSubspaceForce(int e, CubicaTet::Vec & force0, CubicaTet::Vec & force1) {
int p0 = edge_list_[e * 2 + 0];
int p1 = edge_list_[e * 2 + 1];
int v_num = int(interface_vert_[e].size()) / 3;
force0 = Vec::Zero(domain_[p0]->basis_num_);
force1 = Vec::Zero(domain_[p1]->basis_num_);
for (int i = 0; i < v_num; ++i) {
const int global_v = interface_vert_[e][i * 3 + 0];
const int v0 = interface_vert_[e][i * 3 + 1];
const int v1 = interface_vert_[e][i * 3 + 2];
MapVec3 pos0(domain_[p0]->X + v0 * 3);
MapVec3 pos1(domain_[p1]->X + v1 * 3);
Vec3 diff = vert_interfacial_area_[global_v] * (pos1 - pos0);
force0 += domain_[p0]->vert_basis_transpose_[v0] * domain_[p0]->rotation_.transpose() * diff;
// Vec tmp = domain_[p0]->vert_basis_transpose_[v0] * domain_[p0]->rotation_.transpose() * diff;
diff *= -1;
force1 += domain_[p1]->vert_basis_transpose_[v1] * domain_[p1]->rotation_.transpose() * diff;
}
P(force0.norm(), force1.norm());
}
void CubicaTet::ComputeVertexInterfacialArea() {
const double kStiffness = 1.0e7;
vert_interfacial_area_ = std::vector<double>(vertex_num_, 0);
for (int p = 0; p < part_num_; ++p) {
for (int t = 0; t < domain_[p]->triangle_num_; ++t) {
int* verts = domain_[p]->T + t * 3;
bool is_surface_tri = true;
for (int i = 0; i < 3; ++i) {
if (!is_interface_vert_[p][verts[i]]) {
is_surface_tri = false;
break;
}
}
if (is_surface_tri) {
double area = dj::ComputeTriangleArea(domain_[p]->rest_pos_ + verts[0] * 3,
domain_[p]->rest_pos_ + verts[1] * 3,
domain_[p]->rest_pos_ + verts[2] * 3);
area /= 3;
for (int i = 0; i < 3; ++i) {
int global_v = vert_local_id2global_id_[p][verts[i]];
vert_interfacial_area_[global_v] += area;
}
}
}
}
for (int v = 0; v < vertex_num_; ++v) {
vert_interfacial_area_[v] /= 2;
vert_interfacial_area_[v] *= kStiffness;
}
}
| [
"rajadityamukherjee.osu@outlook.com"
] | rajadityamukherjee.osu@outlook.com |
5066b2e4ea05d4f5deaba911b338046d8629a590 | 373fe5c10e6852c7af0f79d4b22ca641901b40fc | /src/cfmap/marker/cfmapmarker_android_p.h | 1a825db585e91abaad9c7cd176f9e11abe693764 | [
"MIT"
] | permissive | firatagdas/cfmap | ebbd801df80edf9ab174537cd1206af821703588 | bffb242164b6e81196f582f434dc947414668bbf | refs/heads/master | 2021-01-13T02:24:32.661645 | 2015-02-01T09:01:15 | 2015-02-01T09:01:15 | 29,901,831 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,628 | h | #ifndef CFMAPMARKER_ANDROID_P_H
#define CFMAPMARKER_ANDROID_P_H
#include <QObject>
#include <qqml.h>
#include "cfmap_global.h"
#include "cfmapmarker_p.h"
class CFMapMarkerAndroidPrivate : public CFMapMarkerPrivate
{
Q_OBJECT
public:
CFMapMarkerAndroidPrivate(CFMapMarker *q);
~CFMapMarkerAndroidPrivate();
void setCoordinate(CFMapCoordinate *coordinate);
CFMapCoordinate *coordinate() const;
void setText(const QString &text);
QString text() const;
void setTitle(const QString &title);
QString title() const;
void setIcon(const QString &icon);
QString icon() const;
void setSnippet(const QString &snippet);
QString snippet() const;
void setInfoWindowAnchor(const QPointF &point);
QPointF infoWindowAnchor() const;
void setGroundAnchor(const QPointF &point);
QPointF groundAnchor() const;
void setAnimationType(CFMapMarker::AppearAnimationType animationType);
CFMapMarker::AppearAnimationType animationType() const;
void setDraggable(bool value);
bool draggable() const;
void setFlat(bool value);
bool flat() const;
void setRotation(qreal rotation);
qreal rotation() const;
void setOpacity(qreal opacity);
qreal opacity() const;
void setUserData(const QVariant &userData);
QVariant userData() const;
void setLayer(CFMapMarkerLayer *layer);
CFMapMarkerLayer *layer() const;
void setTappable(bool value);
bool tappable() const;
void setZIndex(int zIndex);
int zIndex() const;
bool active() const;
void removeFromMap();
void *nativeObject() const;
};
#endif
| [
"firatagdas@gmail.com"
] | firatagdas@gmail.com |
12d1b70787ae84ef04616b89d285bc1eec87e661 | 62b65136f605a8d6447d997f8ff4b87e412465c4 | /loader/bffDump.cpp | 40d895771a14b68f0e8a823aa7fcbcae3631a706 | [
"FSFUL"
] | permissive | 51103220/Boomerang-Production | bd48efbc39544182e4396f1469aa3bb81a29645c | 38bc25688f85c9567b081f1346a78f2954e4184e | refs/heads/master | 2021-01-13T00:38:19.460172 | 2015-12-20T17:32:49 | 2015-12-20T17:32:49 | 48,330,254 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,886 | cpp | /*
* Copyright (C) 2001, Sun Microsystems, Inc
* Copyright (C) 2001, The University of Queensland
*
* See the file "LICENSE.TERMS" for information on usage and
* redistribution of this file, and for a DISCLAIMER OF ALL
* WARRANTIES.
*
*/
/* File: bffDump_skel.cc
* Desc: Skeleton driver for a binary-file dumper program.
*
* This file is a generic skeleton for a binary-file dumper,
* it dumps all the information it finds about sections in the
* file, and it displays any code sections in raw hexadecimal
* notation.
*/
/*
* $Revision: 1.4 $
*
* Apr 01 - Cristina: Created
* 11 May 01 - Nathan: Print text section name (suppresses warning)
* 11 May 01 - Mike: use bCode (prints text section of hppa binaries)
* 11 May 01 - Cristina: minor cleanup for generality
* 02 Aug 01 - Brian: Fixed arg mismatch in printf.
*/
// Include all binary file headers for different binary-file formats
// so that we can support them all.
#include "BinaryFile.h"
#include "ElfBinaryFile.h"
#include "ExeBinaryFile.h"
#include "HpSomBinaryFile.h"
#include "PalmBinaryFile.h"
#include "Win32BinaryFile.h"
int main(int argc, char* argv[])
{
// Usage
if (argc != 2) {
printf ("Usage: %s <filename>\n", argv[0]);
printf ("%s dumps the contents of the given executable file\n", argv[0]);
return 1;
}
// Load the file
BinaryFile *pbf = NULL;
BinaryFileFactory bff;
pbf = bff.Load(argv[1]);
if (pbf == NULL) {
return 2;
}
// Display program and section information
// If the DisplayDetails() function has not been implemented
// in the derived class (ElfBinaryFile in this case), then
// uncomment the commented code below to display section information.
pbf->DisplayDetails (argv[0]);
// This is an alternative way of displaying binary-file information
// by using individual sections. The above approach is more general.
/*
printf ("%d sections:\n", pbf->GetNumSections());
for (int i=0; i < pbf->GetNumSections(); i++)
{
SectionInfo* pSect = pbf->GetSectionInfo(i);
printf(" Section %s at %X\n", pSect->pSectionName, pSect->uNativeAddr);
}
printf("\n");
*/
// Display the code section in raw hexadecimal notation
// Note: this is traditionally the ".text" section in Elf binaries.
// In the case of Prc files (Palm), the code section is named "code0".
for (int i=0; i < pbf->GetNumSections(); i++) {
SectionInfo* pSect = pbf->GetSectionInfo(i);
if (pSect->bCode) {
printf(" Code section:\n");
ADDRESS a = pSect->uNativeAddr;
unsigned char* p = (unsigned char*) pSect->uHostAddr;
for (unsigned off = 0; off < pSect->uSectionSize; ) {
printf("%04X: ", a);
for (int j=0; (j < 16) && (off < pSect->uSectionSize); j++) {
printf("%02X ", *p++);
a++;
off++;
}
printf("\n");
}
printf("\n");
}
}
// Display the data section(s) in raw hexadecimal notation
for (int i=0; i < pbf->GetNumSections(); i++) {
SectionInfo* pSect = pbf->GetSectionInfo(i);
if (pSect->bData) {
printf(" Data section: %s\n", pSect->pSectionName);
ADDRESS a = pSect->uNativeAddr;
unsigned char* p = (unsigned char*) pSect->uHostAddr;
for (unsigned off = 0; off < pSect->uSectionSize; ) {
printf("%04X: ", a);
for (int j=0; (j < 16) && (off < pSect->uSectionSize); j++) {
printf("%02X ", *p++);
a++;
off++;
}
printf("\n");
}
printf("\n");
}
}
pbf->UnLoad();
return 0;
}
| [
"donbinhvn@gmail.com"
] | donbinhvn@gmail.com |
066fa1af8161b92b491c2df162dc6ba43700f988 | f99e4759fc5a40e780b3d319b584b766d502c031 | /CPP - Pirate/CPP-Pirate/commodity.h | 98d18348065cf78409949eac0f901545313eb4ee | [] | no_license | beschoenen/school | 41f66dcc85190039729eb0ddc1329ac400446a78 | aba375fbb59c65577c70c5301053c5c20293498a | refs/heads/master | 2020-03-07T14:09:52.637641 | 2018-03-31T09:53:54 | 2018-03-31T09:53:54 | 127,520,045 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 136 | h | #pragma once
#include "str.h"
class commodity
{
public:
str* name;
explicit commodity(const char* name);
~commodity();
};
| [
"me@kevinrichter.nl"
] | me@kevinrichter.nl |
00b6841dfa34ede30c912e3d8df9bd5bbdc2517f | 8e175a942fd893fff64acc094d45743a7704d96a | /src/Bomb.cpp | 7f85db7d95d566370a39e8575d0037d16e95ef8e | [] | no_license | yadaro/Bomberman-Irrlicht | c39e0fd9b76ac4b935570026838c5ffb51cb402f | 08c16897b1e9f2b904329b4594c357d7ca63c15c | refs/heads/master | 2020-03-27T05:04:32.634483 | 2018-08-24T13:19:54 | 2018-08-24T13:19:54 | 145,992,345 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 339 | cpp | //
// EPITECH PROJECT, 2018
// indie_studio
// File description:
// bomb for bomberman
//
#include "Bomb.hpp"
Bomb::Bomb() : _InGame(false), _range(3),
_timer(10), _x(-1), _y(-1)
{
}
bool Bomb::IsInGame() const
{
return _InGame;
}
int Bomb::getTimer() const
{
return _timer;
}
int Bomb::decTimer()
{
_timer = _timer - 1;
}
| [
"yadaro.yun@epitech.eu"
] | yadaro.yun@epitech.eu |
8dce33c6302b66d26353e7cec0f46337274d217e | 6fadc1810cb4f6ba6d3d0e181e400c5ce7450454 | /Sources/ResultsModel.cpp | 6de0cd32d7898eb97a1feb5f8c52cbaba48162c9 | [] | no_license | kpusmo/fem | 012f011da06875669cea2b1dc30d54c5e08258b1 | 6b83e7f2928f67f246bafef2c1c63b190778c64c | refs/heads/master | 2020-05-09T14:33:33.931054 | 2019-04-21T20:30:08 | 2019-04-21T20:30:08 | 181,198,542 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,219 | cpp |
#include <ResultsModel.h>
#include "ResultsModel.h"
ResultsModel::ResultsModel(QObject *parent) : QAbstractTableModel(parent) {}
int ResultsModel::rowCount(const QModelIndex &index) const {
return rows;
}
int ResultsModel::columnCount(const QModelIndex &index) const {
return columns;
}
QVariant ResultsModel::data(const QModelIndex &index, int role) const {
auto row = static_cast<unsigned int>(index.row());
auto column = static_cast<unsigned int>(index.column());
// if (role == Qt::BackgroundRole) {
// return grid[row][column].getColor();
// }
if (role == Qt::DisplayRole) {
return results[currentResult].getTemperatures()(row * columns + column);
}
return QVariant();
}
void ResultsModel::nextResult() {
if (currentResult + 1 == results.size()) {
return;
}
++currentResult;
}
void ResultsModel::previousResult() {
if (currentResult == 0) {
return;
}
--currentResult;
}
void ResultsModel::setResults(const std::vector<Result> &resultsVector, unsigned r, unsigned c) {
beginResetModel();
rows = r;
columns = c;
results = resultsVector;
currentResult = results.size() - 1;
endResetModel();
}
| [
"kpusmo@gmail.com"
] | kpusmo@gmail.com |
90ed442398b3f2d034b4771541b53afe514b7378 | 93382b7570e2a614cabfd02c308419e1488f7d45 | /util/fipstools/cavp/cavp_ecdsa2_keypair_test.cc | f99bb8f83a381df539075f55207a2beeee650e93 | [
"BSD-3-Clause",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-ssleay-windows",
"OpenSSL",
"MIT",
"ISC",
"Apache-2.0"
] | permissive | jylama99/aws-lc | dd4c3ef1066630da0f59d633eea0de367a9610d7 | 80ab8f6b963b39e6281aa4fede1c4e86d1348748 | refs/heads/main | 2023-07-28T17:56:31.635799 | 2021-08-12T17:27:28 | 2021-08-12T17:27:28 | 385,368,928 | 0 | 0 | NOASSERTION | 2021-07-12T20:02:28 | 2021-07-12T20:02:28 | null | UTF-8 | C++ | false | false | 3,344 | cc | /* Copyright (c) 2017, Google Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
// cavp_ecdsa2_keypair_test processes a NIST CAVP ECDSA2 KeyPair test vector
// request file and emits the corresponding response.
#include <stdlib.h>
#include <vector>
#include <openssl/bn.h>
#include <openssl/crypto.h>
#include <openssl/ec_key.h>
#include <openssl/err.h>
#include <openssl/nid.h>
#include "../crypto/test/file_test.h"
#include "../crypto/test/test_util.h"
#include "cavp_test_util.h"
static bool TestECDSA2KeyPair(FileTest *t, void *arg) {
std::string n_str;
const char *group_str;
int nid = GetECGroupNIDFromInstruction(t, &group_str);
if (nid == NID_undef ||
!t->GetAttribute(&n_str, "N")) {
return false;
}
// Don't use CurrentTestToString to avoid printing the N.
printf(
"[%s]\r\n\r\n[B.4.2 Key Pair Generation by Testing Candidates]\r\n\r\n",
group_str);
unsigned long n = strtoul(n_str.c_str(), nullptr, 10);
for (unsigned long i = 0; i < n; i++) {
bssl::UniquePtr<BIGNUM> qx(BN_new()), qy(BN_new());
bssl::UniquePtr<EC_KEY> key(EC_KEY_new_by_curve_name(nid));
if (!key ||
!EC_KEY_generate_key_fips(key.get()) ||
!EC_POINT_get_affine_coordinates_GFp(EC_KEY_get0_group(key.get()),
EC_KEY_get0_public_key(key.get()),
qx.get(), qy.get(), nullptr)) {
return false;
}
size_t degree_len =
(EC_GROUP_get_degree(EC_KEY_get0_group(key.get())) + 7) / 8;
size_t order_len =
BN_num_bytes(EC_GROUP_get0_order(EC_KEY_get0_group(key.get())));
std::vector<uint8_t> qx_bytes(degree_len), qy_bytes(degree_len);
std::vector<uint8_t> d_bytes(order_len);
if (!BN_bn2bin_padded(qx_bytes.data(), qx_bytes.size(), qx.get()) ||
!BN_bn2bin_padded(qy_bytes.data(), qy_bytes.size(), qy.get()) ||
!BN_bn2bin_padded(d_bytes.data(), d_bytes.size(),
EC_KEY_get0_private_key(key.get()))) {
return false;
}
printf("d = %s\r\nQx = %s\r\nQy = %s\r\n\r\n", EncodeHex(d_bytes).c_str(),
EncodeHex(qx_bytes).c_str(), EncodeHex(qy_bytes).c_str());
}
return true;
}
int cavp_ecdsa2_keypair_test_main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "usage: %s <test file>\n",
argv[0]);
return 1;
}
FileTest::Options opts;
opts.path = argv[1];
opts.callback = TestECDSA2KeyPair;
opts.silent = true;
opts.comment_callback = EchoComment;
return FileTestMain(opts);
}
| [
"lamjyoti@amazon.com"
] | lamjyoti@amazon.com |
1c25d7d0bca22cc96f5f58984269a9af98b595d4 | b4d3259cbc14eeefe1a91ee4bb9fb03ef05c21ae | /studies/Triggerless/checkReweight.cpp | d6527bc750c6a8a0406d2f9b8e5ff037bf7ef1f1 | [] | no_license | camendola/KLUBAnalysis | 3e13a4c29edc072471d37c015fce032302aaee77 | d68e03b6027f98de57b57d016ad0dc53c07fcef2 | refs/heads/master | 2021-06-21T09:19:36.918332 | 2017-07-20T12:28:01 | 2017-07-20T12:28:01 | 73,919,585 | 1 | 0 | null | 2020-04-30T18:35:29 | 2016-11-16T12:48:06 | C++ | UTF-8 | C++ | false | false | 12,910 | cpp | #include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include "TTree.h"
#include "TH1F.h"
#include "TFile.h"
#include "TBranch.h"
#include "TString.h"
#include "TLorentzVector.h"
#include "bigTree.h"
#include "OfflineProducerHelper.h"
#include "triggerReader.h"
using namespace std;
// apply
// c++ -lm -o checkReweight checkReweight.cpp ../../src/OfflineProducerHelper.cc ../../src/triggerReader.cc -I ../../interface/ `root-config --glibs --cflags`
float getTriggerWeight(int partType, float pt, TH1F* weightHisto)
{
if (partType == 0) return 0.95;
else if (partType == 1) return 0.95;
else if (partType == 2)
{
int ibin = weightHisto->FindBin(pt);
if (ibin < 1) ibin = 1;
if (ibin > weightHisto->GetNbinsX()) ibin = weightHisto->GetNbinsX() ;
return weightHisto->GetBinContent(ibin);
}
cout << "** WARNING: trigger weight now known for particle type " << partType << endl;
return 1.;
}
// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- -
// open input txt file and append all the files it contains to TChain
void appendFromFileList (TChain* chain, TString filename)
{
//cout << "=== inizio parser ===" << endl;
std::ifstream infile(filename.Data());
std::string line;
while (std::getline(infile, line))
{
line = line.substr(0, line.find("#", 0)); // remove comments introduced by #
while (line.find(" ") != std::string::npos) line = line.erase(line.find(" "), 1); // remove white spaces
while (line.find("\n") != std::string::npos) line = line.erase(line.find("\n"), 1); // remove new line characters
while (line.find("\r") != std::string::npos) line = line.erase(line.find("\r"), 1); // remove carriage return characters
if (!line.empty()) // skip empty lines
chain->Add(line.c_str());
}
return;
}
// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- -
// open the first file in the input list, retrieve the histogram "Counters" for the trigger names and return a copy of it
TH1F* getFirstFileHisto (TString filename, bool isForTriggers=true)
{
std::ifstream infile(filename.Data());
std::string line;
while (std::getline(infile, line))
{
line = line.substr(0, line.find("#", 0)); // remove comments introduced by #
while (line.find(" ") != std::string::npos) line = line.erase(line.find(" "), 1); // remove white spaces
while (line.find("\n") != std::string::npos) line = line.erase(line.find("\n"), 1); // remove new line characters
while (line.find("\r") != std::string::npos) line = line.erase(line.find("\r"), 1); // remove carriage return characters
if (!line.empty()) // skip empty lines
break;
}
TFile* fIn = TFile::Open (line.c_str());
TH1F* dummy = (TH1F*) fIn->Get ("HTauTauTree/Counters");
TString name = "Counters_perTrigger";
if(!isForTriggers) {
dummy = (TH1F*) fIn->Get ("HTauTauTree/TauIDs");
name = "Counters_pertauID";
}
TH1F* histo = new TH1F (*dummy);
histo-> SetDirectory(0);
histo->SetName (name.Data());
fIn->Close();
return histo;
}
// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- -
int main()
{
bool askGetMatch = true;
bool askIsoInBaseline = true;
cout << endl;
cout << "** asking gen match? " << askGetMatch << endl;
cout << "** asking iso in baseline? " << askIsoInBaseline << endl;
cout << endl;
cout << ".. start, opening files" << endl;
string filelist = "Radion700_fixMatch.txt";
TChain * bigChain = new TChain ("HTauTauTree/HTauTauTree") ;
appendFromFileList (bigChain, filelist);
bigTree theBigTree (bigChain) ;
cout << ".. files opened" << endl;
TH1F* hTriggers = getFirstFileHisto (filelist);
TH1F* hTauIDS = getFirstFileHisto (filelist,false);
OfflineProducerHelper oph (hTriggers, hTauIDS) ;
TFile* fOut = new TFile ("reweightTree.root", "recreate");
TTree* tOut = new TTree("triggerlessTree", "triggerlessTree");
int triggerAccept;
float evtWeight;
float evtLeg1weight;
float evtLeg2weight;
int pairType ;
float pt1, pt2;
tOut->Branch("triggerAccept", &triggerAccept);
tOut->Branch("evtWeight", &evtWeight);
tOut->Branch("evtLeg1weight", &evtLeg1weight);
tOut->Branch("evtLeg2weight", &evtLeg2weight);
tOut->Branch("pairType", &pairType);
tOut->Branch("pt1", &pt1);
tOut->Branch("pt2", &pt2);
// to check trigger match flag
triggerReader trigReader (hTriggers);
vector<string> trigMuTau; trigMuTau .push_back("HLT_IsoMu18_v");
vector<string> trigEleTau; trigEleTau .push_back("HLT_Ele23_WPLoose_Gsf_v");
vector<string> trigTauTau; trigTauTau .push_back("HLT_DoubleMediumIsoPFTau35_Trk1_eta2p1_Reg_v");
trigReader.addMuTauTrigs (trigMuTau);
trigReader.addEleTauTrigs (trigEleTau);
trigReader.addTauTauTrigs (trigTauTau);
TFile* fHistoTriggerRew = new TFile ("/home/llr/cms/cadamuro/TauTagAndProbe/CMSSW_7_6_3/src/TauTagAndProbe/TauTagAndProbe/test/turnOn_2GevIso.root");
TH1F* weightHisto = (TH1F*) fHistoTriggerRew->Get("hTurnOn");
int totAccDATA[3] = {0,0,0};
float totAccMC[3] = {0,0,0};
for (Long64_t iEvent = 0 ; true ; ++iEvent)
{
if (iEvent % 10000 == 0) cout << "reading event " << iEvent << endl ;
int got = theBigTree.fChain->GetEntry(iEvent);
if (got == 0) break;
// loop over the daughters to select pair type: mu > e > tau
// apply tight baseline (with iso to check)
int nmu = 0;
int nele = 0;
// int ntau = 0;
for (unsigned int idau = 0; idau < theBigTree.daughters_px->size(); ++idau)
{
int dauType = theBigTree.particleType->at(idau);
if (oph.isMuon(dauType))
{
if (oph.muBaseline (&theBigTree, idau, 19., 2.1, 0.1, string("All")) ) ++nmu;
}
else if (oph.isElectron(dauType))
{
if (oph.eleBaseline (&theBigTree, idau, 24., 0.1, 0, string("All")) ) ++nele;
}
}
pairType = 2; // tau tau
if (nmu > 0) pairType = 0 ; // mu tau
else if (nele > 0) pairType = 1 ; // ele tau
/////////////////////////////
////////////// choose the first pair passing baseline and being of the right pair type
/////////////////////////////
int pairIndex = -1;
for (unsigned int iPair = 0 ; iPair < theBigTree.indexDau1->size () ; ++iPair)
{
int t_firstDaughterIndex = theBigTree.indexDau1->at (iPair) ;
int t_secondDaughterIndex = theBigTree.indexDau2->at (iPair) ;
int t_type1 = theBigTree.particleType->at (t_firstDaughterIndex) ;
int t_type2 = theBigTree.particleType->at (t_secondDaughterIndex) ;
if ( oph.getPairType (t_type1, t_type2) != pairType ) continue ;
if (askGetMatch)
{
TLorentzVector t_vdau1 (
theBigTree.daughters_px->at (t_firstDaughterIndex),
theBigTree.daughters_py->at (t_firstDaughterIndex),
theBigTree.daughters_pz->at (t_firstDaughterIndex),
theBigTree.daughters_e->at (t_firstDaughterIndex)
);
TLorentzVector t_vdau2 (
theBigTree.daughters_px->at (t_secondDaughterIndex),
theBigTree.daughters_py->at (t_secondDaughterIndex),
theBigTree.daughters_pz->at (t_secondDaughterIndex),
theBigTree.daughters_e->at (t_secondDaughterIndex)
);
bool match1 = false;
bool match2 = false;
int idToMatch1 = 66615;
if (t_type1 == 0) idToMatch1 = 13;
else if (t_type1 == 1) idToMatch1 = 11;
int idToMatch2 = 66615;
if (t_type2 == 0) idToMatch2 = 13;
else if (t_type2 == 1) idToMatch2 = 11;
for (int igen = 0; igen < theBigTree.genpart_px->size(); ++igen)
{
TLorentzVector t_vgen (
theBigTree.genpart_px->at (igen),
theBigTree.genpart_py->at (igen),
theBigTree.genpart_pz->at (igen),
theBigTree.genpart_e->at (igen)
);
int agenId = abs(theBigTree.genpart_pdg->at(igen));
// match to 1
if (agenId == idToMatch1 && t_vgen.DeltaR(t_vdau1) < 0.3) match1 = true;
// match to 2
if (agenId == idToMatch2 && t_vgen.DeltaR(t_vdau2) < 0.3) match2 = true;
// skip if done
if (match1 && match2) continue;
}
if (!match1 || !match2) continue;
}
string whatApply = askIsoInBaseline ? "All" : "Vertex-LepID-pTMin-etaMax-againstEle-againstMu" ;
// if ( oph.pairPassBaseline (&theBigTree, iPair, string("Vertex-LepID-pTMin-etaMax-againstEle-againstMu") ) )
if ( oph.pairPassBaseline (&theBigTree, iPair, whatApply ) )
{
pairIndex = iPair;
break;
}
}
if (pairIndex < 0) continue; // no pair found over baseline
/////////////////////////////
////////////// trigger reweight vs trigger matching
/////////////////////////////
int firstDaughterIndex = theBigTree.indexDau1->at (pairIndex) ;
int secondDaughterIndex = theBigTree.indexDau2->at (pairIndex) ;
int type1 = theBigTree.particleType->at (firstDaughterIndex) ;
int type2 = theBigTree.particleType->at (secondDaughterIndex) ;
TLorentzVector vdau1 (
theBigTree.daughters_px->at (firstDaughterIndex),
theBigTree.daughters_py->at (firstDaughterIndex),
theBigTree.daughters_pz->at (firstDaughterIndex),
theBigTree.daughters_e->at (firstDaughterIndex)
);
TLorentzVector vdau2 (
theBigTree.daughters_px->at (secondDaughterIndex),
theBigTree.daughters_py->at (secondDaughterIndex),
theBigTree.daughters_pz->at (secondDaughterIndex),
theBigTree.daughters_e->at (secondDaughterIndex)
);
pt1 = vdau1.Pt();
pt2 = vdau2.Pt();
// ----- DATA STRATEGY
Long64_t triggerbit = theBigTree.triggerbit;
bool passTrg = trigReader.checkOR (pairType, triggerbit) ;
Long64_t matchFlag1 = (Long64_t) theBigTree.daughters_L3FilterFired->at(firstDaughterIndex);
Long64_t matchFlag2 = (Long64_t) theBigTree.daughters_L3FilterFired->at(secondDaughterIndex);
bool passMatch1 = false;
bool passMatch2 = false;
if (pairType == 0 || pairType == 1)
{
passMatch1 = trigReader.checkOR (pairType, matchFlag1) ;
passMatch2 = true;
}
else if (pairType == 2)
{
passMatch1 = trigReader.checkOR (pairType, matchFlag1) ;
passMatch2 = trigReader.checkOR (pairType, matchFlag2) ;
}
triggerAccept = (passTrg && passMatch1 && passMatch2) ? 1 : 0 ;
if (triggerAccept == 1) totAccDATA[pairType] += 1 ;
// ----- MC STRATEGY
evtLeg1weight = 1.0;
evtLeg2weight = 1.0;
if (pairType == 0 || pairType == 1)
{
evtLeg1weight = getTriggerWeight(type1, vdau1.Pt(), weightHisto) ;
evtLeg2weight = 1.0;
}
else if (pairType == 2)
{
evtLeg1weight = getTriggerWeight(type1, vdau1.Pt(), weightHisto) ;
evtLeg2weight = getTriggerWeight(type2, vdau2.Pt(), weightHisto) ;
}
evtWeight = evtLeg1weight*evtLeg2weight;
totAccMC[pairType] += evtWeight;
/////////////////////////////
////////////// fill output
/////////////////////////////
tOut->Fill();
}
cout << "=== Mu Tau === " << endl;
cout << "ACCEPTED DATA: " << totAccDATA[0] << endl;
cout << "ACCEPTED MC : " << totAccMC[0] << endl;
cout << endl;
cout << "=== E Tau === " << endl;
cout << "ACCEPTED DATA: " << totAccDATA[1] << endl;
cout << "ACCEPTED MC : " << totAccMC[1] << endl;
cout << endl;
cout << "=== Tau Tau === " << endl;
cout << "ACCEPTED DATA: " << totAccDATA[2] << endl;
cout << "ACCEPTED MC : " << totAccMC[2] << endl;
cout << endl;
fOut->cd();
tOut->Write();
} | [
"lc.cadamuro@gmail.com"
] | lc.cadamuro@gmail.com |
28f872583e74eb61c5453ec39ee328d5ca111c7d | 90bd9ea54fc6e489a275523fcaba0eecb5d675ba | /app/src/main/cpp/jni/jni_reference.cpp | bc21973fb0dfccd4ced9e8e1c5bec40cfbf27754 | [] | no_license | shanallen/NDKStudy | f7e896ec0743cacb93ec6c78c3f9d28eb850dfea | 3207753b718c0609ee7f8071e257ede92847f807 | refs/heads/master | 2022-06-07T21:15:56.744876 | 2020-05-02T10:04:33 | 2020-05-02T10:04:33 | 260,648,793 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,717 | cpp | //
// Created by 单继强 on 2020-05-01.
//
#include <base.h>
//局部引用
extern "C"
JNIEXPORT jstring JNICALL
Java_com_sjq_learnndk_jni_JNIReference_errorCacheLocalReference(JNIEnv *env,jobject instance){
// jclass localRefs = env->FindClass("java/lang/String");
// jmethodID mid = env->GetMethodID(localRefs,"<init>","(Ljava/lang/String;)V");
// jstring str = env->NewStringUTF("string");
// return static_cast<jstring>(env->NewObject(localRefs, mid, str));
}
//全局引用
extern "C"
JNIEXPORT jstring JNICALL
Java_com_sjq_learnndk_jni_JNIReference_cacheWithGlobalReference(JNIEnv *env,jobject instance){
// static jclass stringClass = nullptr;
// if(stringClass == nullptr){
//
// jclass cls = env->FindClass("java/lang/String");
// stringClass = static_cast<jclass>(env->NewGlobalRef(cls));
// env->DeleteLocalRef(cls);
// } else{
// LOGD("use cached");
// }
// jmethodID mid = env->GetMethodID(stringClass,"<init>","(Ljava/lang/String;)V");
// jstring str = env->NewStringUTF("string");
// return static_cast<jstring>(env->NewObject(stringClass, mid, str));
}
extern "C"
JNIEXPORT void JNICALL
Java_com_sjq_learnndk_jni_JNIReference_useWeakGLobalReference(JNIEnv *env,jobject instance){
// static jclass stringClass = nullptr;
// if(stringClass == nullptr){
//
// jclass cls = env->FindClass("java/lang/String");
// stringClass = static_cast<jclass>(env->NewGlobalRef(cls));
// env->DeleteLocalRef(cls);
// } else{
// LOGD("use cached");
// }
// jmethodID mid = env->GetMethodID(stringClass,"<init>","(Ljava/lang/String;)V");
// jboolean isGc = env->IsSameObject(stringClass, nullptr);
} | [
""
] | |
75890f855a5d9cf1bd2eeecd16e6fe821f7d30e0 | ca6efca2ebbe78eb5a5060104ea474800c576e1b | /IndexBWA.h | 613dd426c32a9e8bb571fec2131294fda8c4a484 | [] | no_license | Zuza/bwa-index | da87b6c8c0777ade148d888d84f28c8b9e7da862 | 8cb25ccdcfedd25ecc619d545ef2db22b960201f | refs/heads/master | 2021-01-19T08:16:41.686069 | 2013-12-13T02:59:22 | 2013-12-13T02:59:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,007 | h | /*
* IndexBWA.h
*
* Created on: Oct 13, 2013
* Author: ivan
*/
#ifndef INDEXBWA_H_
#define INDEXBWA_H_
#include <stdio.h>
#include <string.h>
#include <vector>
#include <list>
#include "bwa/bwamem.h"
#include "bwa/kseq.h" // for the FASTA/Q parser
#include "bwa/bwt.h"
#include "bwa/bwa.h"
#include "bwa/bwase.h"
#include "bwa/utils.h"
#include "bwtindex.h"
#include "IndexLocation.h"
typedef std::vector<IndexLocation> IndexLocationList;
class IndexBWA
{
public:
IndexBWA();
// IndexBWA(SequenceSet *sequences, unsigned int seedLength);
// IndexBWA(std::string sequencesPath);
~IndexBWA();
/** Process a fasta file to create an index. If an index with the given filename already exists, function skips index creation.
* @param sequencesPath Path to an input FASTA file.
* @param numItrs Number of threads that will be used (paralelizirao sam svoj aligner s OpenMP-om, pa sam ove iteratore multiplicirao tako da imam za svaku jezgru zaseban. Cini mi se da je radilo dosta brze nego da sam stavio pragma omp critical, ali opet, ovo je moje prvo iskustvo s paralelizacijom. Ako koristis jednu jezgru, ovaj dio koji koristi numIters mozes maknuti (i smem_i **itrs_; dolje u private dijelu moze biti onda jednostruki pointer).
*/
void process(std::string sequencesPath, unsigned int numItrs);
/** Finds all exact matches of a query (given as a char pointer and its length), and returns them as a list (or a vector, depends on the typedef at the begining of this file).
* @param query Char pointer to the beginning of a seed. Note that the query sequence needs to be 2-bit coded, as used by BWA, otherwise it won't work correctly.
* @param queryLength Length of the seed. Explicitly stated
* @param threadId ID of the thread that currently accesses the index (thread ID is used as the index for the itrs_ array).
* @param retNumHits Total number of exact matches for a given seed.
* @param maxNumHits Maximum allowed number of hits. Sometimes the number of hits can be really large (dozens of thousands), which can indicate highly repetitive regions, and may introduce noise in the alignment procedure. Only if the number of hits is lesser than (or equal to) maxNumHits will the hit locations be returned. Otherwise, the return value will be equal to NULL;
* @return Pointer to the list of hit locations. Equal to NULL if there are no hits, or the number of hits is larger than maxNumHits.
*/
IndexLocationList* convertedFind(char *query, unsigned int queryLength, unsigned int threadId, unsigned long long int *retNumHits, unsigned long int maxNumHits);
/** Returns the header of an indexed reference sequence.
* @param sequenceId ID of the sequence.
* @return String containing the header of the sequence.
*/
std::string getHeader(unsigned long long int sequenceId);
// void verbose(std::ostream &outStream);
bwaidx_t *getIndex();
smem_i** getItrs();
private:
bwaidx_t *idx_;
smem_i **itrs_;
unsigned int numItrs_;
};
#endif /* INDEXBWA_H_ */
| [
"zuza777@gmail.com"
] | zuza777@gmail.com |
5d067d0faf00e7e0815476aeebd74bd35b7339c6 | fc2d01d1afa08ffc46c23901163c37e679c3beaf | /ShadowEditor/G_GroundToolSetStartPos.h | 75010d9418b3fbc391c8e976a027bcafb26f7518 | [] | no_license | seblef/ShadowEngine | a9428607b49cdd41eb22dcbd8504555454e26a0c | fba95e910c63269bfe0a05ab639dc78b6c16ab8b | refs/heads/master | 2023-02-14T19:08:25.878492 | 2021-01-08T16:16:44 | 2021-01-08T16:16:44 | 113,681,956 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 573 | h |
#ifndef _G_GROUNDTOOLSETSTARTPOS_H_
#define _G_GROUNDTOOLSETSTARTPOS_H_
#include "G_Tool.h"
#include <StdRenderer.h>
class G_GroundToolSetStartPos : public G_Tool
{
protected:
Plane _ground;
unsigned short _flags;
public:
G_GroundToolSetStartPos() : _ground(Vector3::NullVector, Vector3::YAxisVector) {}
~G_GroundToolSetStartPos() {}
void mouseDown(int x, int y, unsigned short flags)
{
_flags=flags;
mouseMove(x,y);
}
void mouseMove(int x, int y);
void draw(G_EditorObjDrawer* d);
};
#endif | [
"sebast.lefort@gmail.com"
] | sebast.lefort@gmail.com |
95e86363999ec9c1ec2df7343ba825bb8120ebed | 4ffdc4341ce50d462dc9ed0198691b9aa5f2d0ba | /week-02/day-4/02.cpp | a6a016119f7fed8d436a5b6070f9301db5029a35 | [] | no_license | greenfox-zerda-sparta/Akatakata | b1289cc176a88f5e51133e4e723e97ad9a71e402 | a4a7f464c66582568c238eea7b98ecc949f87c05 | refs/heads/master | 2021-01-12T18:14:53.086793 | 2017-02-14T14:32:17 | 2017-02-14T14:32:17 | 71,350,782 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 403 | cpp | #include <iostream>
using namespace std;
void filler(int *array, int length);
int main() {
int array[10];
// write a function that takes an array and a length and it fills the array
// with numbers from zero till the length
filler(array, 10);
return 0;
}
void filler(int *array, int length) {
for (int i = 0; i < length + 1; i++) {
array[i] = i;
cout << array[i] << " ";
}
}
| [
"almasy.kata@gmail.com"
] | almasy.kata@gmail.com |
ae1ecbe17302ad5dee84d16ba04026a40dfb116a | 1f3bbdecf90e340555a3fdb6cd58c7b8a891dc48 | /applicachun/ch14ex09.cpp | bb9dfe5c2551971119f9c0eed22d4cbbec97bfc8 | [] | no_license | ohnley/stroustrup_fltk | 771ffb2cdc964ceadb443c8ac901d80a34349e0c | 138d6561a517c412357d943d31ca3d4f61dfb864 | refs/heads/master | 2023-06-04T12:18:36.768125 | 2021-06-19T14:49:00 | 2021-06-19T14:49:00 | 372,058,811 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 888 | cpp | #include "dummycmake/Simple_window.h"
#include "dummycmake/Graph.h"
#include <iostream>
int main(){
Simple_window win (Point{100,100}, 1200, 800, "hexagon example");
std::cout << 100;
Group g;
g.add_shape(Graph_lib::Rectangle{Point{100,200}, Point{150,400}});
g.add_shape(Graph_lib::Rectangle{Point{100,100}, Point{150,400}});
g.add_shape(Graph_lib::Rectangle{Point{500,200}, Point{550,400}});
g.add_shape(Graph_lib::Regular_hexagon{Point{300,300},50});
g.add_shape(Graph_lib::Arrow{Point{300,300},Point{50,50}});
g.set_color(Color::black);
win.attach(g);
win.wait_for_button();
g.move(10,10);
win.wait_for_button();
g.move(10,10);
win.wait_for_button();
g.move(10,10);
g.set_color(Color::blue);
win.wait_for_button();
std::cout << 100;
g.move(10,10);
win.wait_for_button();
return EXIT_SUCCESS;
} | [
"28885446+ohnley@users.noreply.github.com"
] | 28885446+ohnley@users.noreply.github.com |
24581c80975c5939339037ec47f05cdfe0495a60 | 6f154afa302efeac5256e82c973616c0a428d3d5 | /src/main/strategy_engine_common/StrategyUtils/StrategyConstants.cpp | 592f080f3a3118c68e7d55b0f291126e93ea1134 | [] | no_license | clhongooo/trading_engine | 2ff58cc5d6cf7bef0a619549a4b4d63f923483dd | d4d74ad7ba21caa01f49054d63cdd8b2317d1702 | refs/heads/master | 2020-06-03T21:38:44.509346 | 2019-07-05T10:16:24 | 2019-07-05T10:16:24 | 191,741,370 | 0 | 1 | null | 2019-06-13T10:23:32 | 2019-06-13T10:23:32 | null | UTF-8 | C++ | false | false | 2,742 | cpp | #include <StrategyConstants.h>
string GetStrategyName(const StrategyID id)
{
switch (id)
{
case STY_NIR: { return "NIR"; }
case STY_B1_HKF: { return "B1_HKF"; }
case STY_B2_US1: { return "B2_US1"; }
case STY_B2_US2: { return "B2_US2"; }
case STY_B2_US3: { return "B2_US3"; }
case STY_B2_HK: { return "B2_HK"; }
case STY_B3_US: { return "B3_US"; }
case STY_NIR1: { return "NIR1"; }
case STY_CMA: { return "CMA"; }
case STY_S11A: { return "S11A"; }
case STY_A1: { return "A1"; }
case STY_A6: { return "A6"; }
case STY_R1: { return "R1"; }
case STY_R3: { return "R3"; }
case STY_R7: { return "R7"; }
case STY_R8: { return "R8"; }
case STY_R9: { return "R9"; }
case STY_TEST: { return "TEST"; }
default: { return "_UNKWN_"; }
}
}
void GetStrategyNameCStr(const StrategyID id, char outputStrategyName[STYNAMELEN+1])
{
switch (id)
{
case STY_NIR: { strcpy(outputStrategyName,"NIR\0"); break; }
case STY_B1_HKF: { strcpy(outputStrategyName,"B1_HKF\0"); break; }
case STY_B2_US1: { strcpy(outputStrategyName,"B2_US1\0"); break; }
case STY_B2_US2: { strcpy(outputStrategyName,"B2_US2\0"); break; }
case STY_B2_US3: { strcpy(outputStrategyName,"B2_US3\0"); break; }
case STY_B2_HK: { strcpy(outputStrategyName,"B2_HK\0"); break; }
case STY_B3_US: { strcpy(outputStrategyName,"B3_US\0"); break; }
case STY_NIR1: { strcpy(outputStrategyName,"NIR1\0"); break; }
case STY_CMA: { strcpy(outputStrategyName,"CMA\0"); break; }
case STY_S11A: { strcpy(outputStrategyName,"S11A\0"); break; }
case STY_A1: { strcpy(outputStrategyName,"A1\0"); break; }
case STY_A6: { strcpy(outputStrategyName,"A6\0"); break; }
case STY_R1: { strcpy(outputStrategyName,"R1\0"); break; }
case STY_R3: { strcpy(outputStrategyName,"R3\0"); break; }
case STY_R7: { strcpy(outputStrategyName,"R7\0"); break; }
case STY_R8: { strcpy(outputStrategyName,"R8\0"); break; }
case STY_R9: { strcpy(outputStrategyName,"R9\0"); break; }
case STY_TEST: { strcpy(outputStrategyName,"TEST\0"); break; }
default: { strcpy(outputStrategyName,"_UNKWN_\0"); break; }
}
}
| [
"sunny.yan@cashalgo.com"
] | sunny.yan@cashalgo.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.