blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
247
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 4
111
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
58
| visit_date
timestamp[ns]date 2015-07-25 18:16:41
2023-09-06 10:45:08
| revision_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| github_id
int64 3.89k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 25
values | gha_event_created_at
timestamp[ns]date 2012-06-07 00:51:45
2023-09-14 21:58:52
⌀ | gha_created_at
timestamp[ns]date 2008-03-27 23:40:48
2023-08-24 19:49:39
⌀ | gha_language
stringclasses 159
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
10.5M
| extension
stringclasses 111
values | filename
stringlengths 1
195
| text
stringlengths 7
10.5M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a8a13288de37de37ec438e49526d374267e72405
|
55fba0de5f269eb0ffbc30764810ea83cf14164c
|
/iNode.cpp
|
33e81fc0e0004f5bea844b69bcbc3f84d72dab78
|
[] |
no_license
|
mdonohu6/newCS350FinalProject
|
025738a2a5b130fd413ec1cd0553d8bed85aa6b3
|
c29ae0c3b75e5b9d1665bc933e9c450a15e579ec
|
refs/heads/master
| 2021-01-20T04:05:01.924051
| 2017-05-08T18:33:18
| 2017-05-08T18:33:18
| 89,637,108
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,058
|
cpp
|
iNode.cpp
|
//
// iNode.cpp
//
//
// Created by oliver on 4/6/17.
//
//
#include "iNode.hpp"
// default all values
iNode::iNode() {
fSize = -1; //in blocks
for(int i = 0; i < 12; i++) blockAddressTable[i] = -1;
ib.pointer = -1;
doubleIndBlock = -1;
fileName[0] = '~';
fileName[1] = '\0';
}
// best to copy vals like this than to assign pointers to the original arrays
iNode::iNode(int a_fSize, int a_blockAddressTable[12], int a_indBlock, int a_doubleIndBlock, char a_fileName[32]) {
fSize = a_fSize;
for(int i = 0; i < 12; i++) blockAddressTable[i] = a_blockAddressTable[i];
ib.pointer = a_indBlock;
doubleIndBlock = a_doubleIndBlock;
for(int i = 0; i < 32; i++) fileName[i] = a_fileName[i];
}
iNode::iNode(char a_fileName[32]) {
fSize = 0;
for(int i = 0; i < 12; i++) blockAddressTable[i] = -1;
ib.pointer = -1;
doubleIndBlock = -1;
for(int i = 0; i < 32; i++) fileName[i] = a_fileName[i];
}
char * iNode::getFileName() {
return fileName;
}
void iNode::setFileName(char* fn) {
strcpy(fileName, fn);
}
|
2c3ea0e480d98a119735d46e9971bbc1964e812a
|
3864d74bb0b871149cc232db9b8c91775d1b5de5
|
/components/Chaze_Flashtraining/ChazeFlashtrainingWrapper.cpp
|
9640c9b6e0573db5f10d4473e8876205710c979c
|
[
"LicenseRef-scancode-public-domain"
] |
permissive
|
jubueche/chaze-esp32
|
55ee9b4c11ffbb3a27310ed8c99cb61488bf3f98
|
ffa183a3c4469524ad972b60c0fad326f0a9a8fe
|
refs/heads/master
| 2022-11-12T06:04:04.965845
| 2019-12-19T22:42:34
| 2019-12-19T22:42:34
| 165,647,651
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,322
|
cpp
|
ChazeFlashtrainingWrapper.cpp
|
// TODO: Remove boiler plate code by creating function. Downside: Have to move declaration inside header.
#include <stdlib.h>
#include <stdint.h>
#include "ChazeFlashtrainingWrapper.h"
#include "ChazeFlashtraining.h"
struct FlashtrainingWrapper
{
void * obj;
};
FlashtrainingWrapper_t * FlashtrainingWrapper_create(void)
{
FlashtrainingWrapper *ft;
ft = (FlashtrainingWrapper_t *) malloc (sizeof(*ft));
ft->obj = global_ft;
return ft;
}
void FlashtrainingWrapper_destroy(FlashtrainingWrapper *ft)
{
if(ft==NULL)
return;
delete static_cast<Flashtraining *>(ft->obj);
free(ft);
}
bool FlashtrainingWrapper_write_compressed_chunk(FlashtrainingWrapper *ft, uint8_t * data, uint32_t n)
{
Flashtraining *obj;
if(ft==NULL)
return false;
obj = static_cast<Flashtraining *>(ft->obj);
return obj->write_compressed_chunk(data,n);
}
bool FlashtrainingWrapper_start_new_training(FlashtrainingWrapper_t *ft)
{
Flashtraining *obj;
if(ft==NULL)
return false;
obj = static_cast<Flashtraining *>(ft->obj);
return obj->start_new_training();
}
bool FlashtrainingWrapper_stop_training(FlashtrainingWrapper_t *ft)
{
Flashtraining *obj;
if(ft==NULL)
return false;
obj = static_cast<Flashtraining *>(ft->obj);
return obj->stop_training();
}
int FlashtrainingWrapper_get_STATE(FlashtrainingWrapper_t * ft)
{
Flashtraining *obj;
if(ft==NULL)
return -1;
obj = static_cast<Flashtraining *>(ft->obj);
return obj->get_STATE();
}
float FlashtrainingWrapper_readCalibration(FlashtrainingWrapper_t * ft, uint8_t storage_address)
{
Flashtraining *obj;
if(ft==NULL)
return -1;
obj = static_cast<Flashtraining *>(ft->obj);
return obj->readCalibration(storage_address);
}
uint32_t FlashtrainingWrapper_get_number_of_unsynched_trainings(FlashtrainingWrapper_t * ft)
{
Flashtraining *obj;
if(ft==NULL)
return -1;
obj = static_cast<Flashtraining *>(ft->obj);
return obj->meta_number_of_unsynced_trainings();
}
void FlashtrainingWrapper_erase_trainings_to_erase(FlashtrainingWrapper_t * ft)
{
Flashtraining *obj;
if(ft != NULL)
{
obj = static_cast<Flashtraining *>(ft->obj);
obj->erase_trainings_to_erase();
}
}
|
57f06ccf2fc92065cf6318d4e404f0f77a59670d
|
056d0466af4fcf9a989fb377516353349f5b87e8
|
/openvkl/common/Data.h
|
2824282cad9c45e08830114bfb1f815b8a22e725
|
[
"Apache-2.0"
] |
permissive
|
NicolasHo/openvkl
|
5bba934128ea6d6fbcec3fdf3065790a1216576e
|
d48ee28c3b824c39ab7db3013b05eb25678e719e
|
refs/heads/master
| 2020-12-28T04:24:47.849006
| 2020-02-12T16:48:17
| 2020-02-12T16:48:17
| 238,180,534
| 0
| 0
|
Apache-2.0
| 2020-02-04T10:33:34
| 2020-02-04T10:33:33
| null |
UTF-8
|
C++
| false
| false
| 2,452
|
h
|
Data.h
|
// ======================================================================== //
// Copyright 2019 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#pragma once
#include "ManagedObject.h"
#include "openvkl/openvkl.h"
namespace openvkl {
struct OPENVKL_CORE_INTERFACE Data : public ManagedObject
{
Data(size_t numItems,
VKLDataType dataType,
const void *source,
VKLDataCreationFlags dataCreationFlags);
virtual ~Data() override;
virtual std::string toString() const override;
size_t size() const;
template <typename T>
T *begin();
template <typename T>
T *end();
template <typename T>
const T *begin() const;
template <typename T>
const T *end() const;
template <typename T>
T &at(size_t i);
template <typename T>
const T &at(size_t i) const;
size_t numItems;
size_t numBytes;
VKLDataType dataType;
void *data;
VKLDataCreationFlags dataCreationFlags;
};
template <typename T>
inline T *Data::begin()
{
return static_cast<T *>(data);
}
template <typename T>
inline T *Data::end()
{
return begin<T>() + numItems;
}
template <typename T>
inline const T *Data::begin() const
{
return static_cast<const T *>(data);
}
template <typename T>
inline const T *Data::end() const
{
return begin<const T>() + numItems;
}
} // namespace openvkl
|
d6ab7a48cd997d3976e282068494f733b965017e
|
727616fbd7e9d2c6bc603a549054ad642d2fc96d
|
/examples/Framework.hpp
|
1e5308002355338545a502fe7810e556d1f670ec
|
[
"MIT"
] |
permissive
|
PixelOfDeath/glCompact
|
82aca67b261a15ce68225b6573a094fc64f13438
|
68334cc9c3aa20255e8986ad1ee5fa8e23df354d
|
refs/heads/master
| 2021-07-25T18:20:03.832731
| 2021-05-13T08:31:49
| 2021-05-13T08:31:49
| 158,584,923
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 170
|
hpp
|
Framework.hpp
|
#ifdef FRAMEWORK_GLFW
#include "FrameworkGLFW.hpp"
#elif FRAMEWORK_SDL2
#include "FrameworkSDL2.hpp"
#elif FRAMEWORK_SFML
#include "FrameworkSFML.hpp"
#endif
|
1e1225476816f11ffafda127b2741ff64284773f
|
6fc4f5d0edb1aa15229e87baf89a0eacbae0c076
|
/InfiniteHappiness.cpp
|
f2874983900cdba966b1f292e37e30250b78e2b1
|
[] |
no_license
|
Crinale/Recursive-Feelgood-Project
|
8b4060a1d945defccca9c256ff37c1e1ccb13f53
|
7e18d2e9eaef7dc1770d6e5885b2ca7c65c156db
|
refs/heads/master
| 2020-12-18T13:48:13.710601
| 2016-08-12T22:24:13
| 2016-08-12T22:24:13
| 65,586,948
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 598
|
cpp
|
InfiniteHappiness.cpp
|
#include <iostream>
#include <string>
using namespace std;
string question;
string answer;
bool quest();
int main(){
if(quest()){
cout << "Done.";
}
}
bool quest(){
cout << "This world has many things happening what do you want done with it? \n";
getline(cin,question);
cout << "Are you sure you want "<< question << "?";
getline(cin,answer);
if(answer == "yes"||answer == "Yes"){
return(true);
}
if(answer == "no"||answer == "No"){
cout << "What do you want then? \n";
quest();
}
}
|
ac5414dccf3fe56793ef275abea770d45b4974ce
|
5d83739af703fb400857cecc69aadaf02e07f8d1
|
/Archive/72b8c61ddc/main.cpp
|
ce9ff368186100db02f9bb24690de8e0817bb7d5
|
[] |
no_license
|
WhiZTiM/coliru
|
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
|
2c72c048846c082f943e6c7f9fa8d94aee76979f
|
refs/heads/master
| 2021-01-01T05:10:33.812560
| 2015-08-24T19:09:22
| 2015-08-24T19:09:22
| 56,789,706
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 169
|
cpp
|
main.cpp
|
#include <iostream>
class thing {
public:
thing() : min(10E-10) {}
private:
const double min;
};
int main() {
std::cout << "bla" << std::endl;
}
|
a408b941d5d76f68e3c522642d27e6e3e7bb6d2e
|
fa1ceda1968b4b6a638dcf25b59593e9826a4be7
|
/src/a_star/include/priorityqueueset.h
|
dba28ff30898df7635bca57b5b1b29574c6f2bfa
|
[] |
no_license
|
Not/a_star
|
4bd96fed48e5e0e637f3de2171fb966869da3144
|
9856036584d83402a13e120ba7030cc9679c1a8f
|
refs/heads/master
| 2023-01-13T14:35:26.671806
| 2020-11-18T13:24:57
| 2020-11-18T13:24:57
| 312,328,146
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 787
|
h
|
priorityqueueset.h
|
#ifndef PRIORITYQUEUESET_H
#define PRIORITYQUEUESET_H
#include<set>
#include <iostream>
#include <algorithm>
#include <functional>
template <typename T,typename cmp=std::less<>>
class priorityQueueSet{
public:
std::set<T> elements;
void push(T t){elements.insert(t);}
auto begin(){return elements.begin();}
//cmp comparator;
T test;
auto end(){return elements.end();}
T pop(cmp comparator={});
priorityQueueSet(){};
bool empty(){return elements.size()==0;}
};
template <typename T,typename cmp>
T priorityQueueSet<T,cmp>::pop(cmp comparator)
{
auto result=std::min_element(elements.begin(),elements.end(),comparator);
elements.erase(result);
return *result;
}
#endif // PRIORITYQUEUESET_H
|
216371f5a22c05c0054ffa9babb67ef26543dbb0
|
cd8adc658f22b2d23ecb92cd7dea23a7592f3dad
|
/src/xalanc/XPath/XPathFunctionTable.cpp
|
1a14fbe34b33ce1e36e938bcc8b9434ecdc5d16d
|
[
"Apache-2.0"
] |
permissive
|
apache/xalan-c
|
8207ab896f4fc63009b0612d1f2c68cc53494814
|
c326619da4813acfc845c2830d904a4860f9afe1
|
refs/heads/master
| 2023-08-16T05:31:27.349782
| 2021-11-23T19:59:03
| 2021-11-23T19:59:03
| 183,135,979
| 27
| 28
|
Apache-2.0
| 2022-11-28T18:01:31
| 2019-04-24T02:57:39
|
C++
|
UTF-8
|
C++
| false
| false
| 29,017
|
cpp
|
XPathFunctionTable.cpp
|
/*
* 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.
*/
// Base class header file
#include "XPathFunctionTable.hpp"
#include <cstring>
#include <xalanc/PlatformSupport/DOMStringHelper.hpp>
#include <xalanc/PlatformSupport/XalanMessageLoader.hpp>
#include "FunctionConcat.hpp"
#include "FunctionContains.hpp"
#include "FunctionID.hpp"
#include "FunctionLang.hpp"
#include "FunctionString.hpp"
#include "FunctionNamespaceURI.hpp"
#include "FunctionNormalizeSpace.hpp"
#include "FunctionStartsWith.hpp"
#include "FunctionSubstring.hpp"
#include "FunctionSubstringAfter.hpp"
#include "FunctionSubstringBefore.hpp"
#include "FunctionTranslate.hpp"
namespace XALAN_CPP_NAMESPACE {
class FunctionNotImplemented : public Function
{
public:
FunctionNotImplemented(const XalanDOMChar* theName) :
m_name(theName)
{
}
/**
* Create a copy of the function object.
*
* @return pointer to the new object
*/
virtual Function*
clone(MemoryManager& theManager) const
{
typedef FunctionNotImplemented ThisType;
XalanAllocationGuard theGuard(theManager, theManager.allocate(sizeof(ThisType)));
ThisType* const theResult =
new (theGuard.get()) ThisType(m_name);
theGuard.release();
return theResult;
}
protected:
/**
* Get the error message to report when
* the function is called with the wrong
* number of arguments.
*
* @return function error message
*/
virtual const XalanDOMString&
getError(XalanDOMString& theResult) const
{
return XalanMessageLoader::getMessage(
theResult,
XalanMessages::FunctionIsNotImplemented_1Param,
m_name);
}
private:
// Not implemented...
Function&
operator=(const Function&);
bool
operator==(const Function&) const;
const XalanDOMChar* const m_name;
};
XPathFunctionTable::XPathFunctionTable( bool fCreateTable) :
m_memoryManager(0),
m_functionTable(),
m_functionTableEnd(m_functionTable + (sizeof(m_functionTable) / sizeof(m_functionTable[0])) - 1)
{
assert(int(s_functionNamesSize) == TableSize);
std::memset(m_functionTable, 0, sizeof(m_functionTable));
if (fCreateTable == true)
{
CreateTable();
}
}
XPathFunctionTable::~XPathFunctionTable()
{
DestroyTable();
}
void
XPathFunctionTable::InstallFunction(
const XalanDOMChar* theFunctionName,
const Function& theFunction)
{
const int theFunctionID =
getFunctionIndex(theFunctionName);
assert (m_memoryManager != 0);
if (theFunctionID == InvalidFunctionNumberID)
{
XalanDOMString theResult(*m_memoryManager);
throw XPathExceptionFunctionNotSupported(
theFunctionName,
theResult,
0);
}
else
{
if (m_functionTable[theFunctionID] == 0)
{
m_functionTable[theFunctionID] = theFunction.clone(*m_memoryManager);
}
else
{
const Function* const theOldFunction = m_functionTable[theFunctionID];
m_functionTable[theFunctionID] = theFunction.clone(*m_memoryManager);
const_cast<Function*>(theOldFunction)->~Function();
m_memoryManager->deallocate((void*)theOldFunction);
}
}
}
bool
XPathFunctionTable::UninstallFunction(const XalanDOMChar* theFunctionName)
{
const int theFunctionID =
getFunctionIndex(theFunctionName);
if (theFunctionID == InvalidFunctionNumberID)
{
return false;
}
else
{
Function* const theFunction =
const_cast<Function*>(m_functionTable[theFunctionID]);
if (theFunction != 0)
{
m_functionTable[theFunctionID] = 0;
XalanDestroy(
*m_memoryManager,
*theFunction);
}
return true;
}
}
#if 0
#include <fstream>
void
dumpTable(
const XPathFunctionTable::FunctionNameIndexMapType& theTable,
std::ostream& theSourceStream,
std::ostream& theHeaderStream)
{
XPathFunctionTable::FunctionNameIndexMapType::const_iterator i = theTable.begin();
while(i != theTable.end())
{
theSourceStream << "const XalanDOMChar\tXPathFunctionTable::s_";
const XalanDOMString& theString = (*i).first;
theHeaderStream << "\t// The string \"" << theString << "\"\n\tstatic const XalanDOMChar\ts_";
bool nextCap = false;
XalanDOMString::const_iterator j = theString.begin();
while(*j)
{
if (*j == '-')
{
nextCap = true;
}
else
{
assert(*j >= 'a' && *j <= 'z');
if (nextCap)
{
theSourceStream << char(*j -'a' + 'A');
theHeaderStream << char(*j -'a' + 'A');
nextCap = false;
}
else
{
theSourceStream << char(*j);
theHeaderStream << char(*j);
}
}
++j;
}
j = theString.begin();
theSourceStream << "[] =\n{\n";
theHeaderStream << "[];\n\n";
while(*j)
{
if (*j == '-')
{
theSourceStream << "\tXalanUnicode::charHyphenMinus,\n";
}
else
{
assert(*j >= 'a' && *j <= 'z');
theSourceStream << "\tXalanUnicode::charLetter_";
theSourceStream << char(*j) << ",\n";
}
++j;
}
theSourceStream << "\t0\n};\n\n";
++i;
}
}
#endif
void
XPathFunctionTable::CreateTable()
{
try
{
InstallFunction(
s_id,
FunctionID());
InstallFunction(
s_key,
FunctionNotImplemented(s_key));
InstallFunction(
s_not,
FunctionNotImplemented(s_not));
InstallFunction(
s_sum,
FunctionNotImplemented(s_sum));
InstallFunction(
s_lang,
FunctionLang());
InstallFunction(
s_last,
FunctionNotImplemented(s_last));
InstallFunction(
s_name,
FunctionNotImplemented(s_name));
InstallFunction(
s_true,
FunctionNotImplemented(s_true));
InstallFunction(
s_count,
FunctionNotImplemented(s_count));
InstallFunction(
s_false,
FunctionNotImplemented(s_false));
InstallFunction(
s_floor,
FunctionNotImplemented(s_floor));
InstallFunction(
s_round,
FunctionNotImplemented(s_round));
InstallFunction(
s_concat,
FunctionConcat());
InstallFunction(
s_number,
FunctionNotImplemented(s_number));
InstallFunction(
s_string,
FunctionString());
InstallFunction(
s_boolean,
FunctionNotImplemented(s_boolean));
InstallFunction(
s_ceiling,
FunctionNotImplemented(s_ceiling));
InstallFunction(
s_current,
FunctionNotImplemented(s_current));
InstallFunction(
s_contains,
FunctionContains());
InstallFunction(
s_document,
FunctionNotImplemented(s_document));
InstallFunction(
s_position,
FunctionNotImplemented(s_position));
InstallFunction(
s_substring,
FunctionSubstring());
InstallFunction(
s_translate,
FunctionTranslate());
InstallFunction(
s_localName,
FunctionNotImplemented(s_localName));
InstallFunction(
s_generateId,
FunctionNotImplemented(s_generateId));
InstallFunction(
s_startsWith,
FunctionStartsWith());
InstallFunction(
s_formatNumber,
FunctionNotImplemented(s_formatNumber));
InstallFunction(
s_namespaceUri,
FunctionNamespaceURI());
InstallFunction(
s_stringLength,
FunctionNotImplemented(s_stringLength));
InstallFunction(
s_normalizeSpace,
FunctionNormalizeSpace());
InstallFunction(
s_substringAfter,
FunctionSubstringAfter());
InstallFunction(
s_systemProperty,
FunctionNotImplemented(s_systemProperty));
InstallFunction(
s_substringBefore,
FunctionSubstringBefore());
InstallFunction(
s_elementAvailable,
FunctionNotImplemented(s_elementAvailable));
InstallFunction(
s_functionAvailable,
FunctionNotImplemented(s_functionAvailable));
InstallFunction(
s_unparsedEntityUri,
FunctionNotImplemented(s_unparsedEntityUri));
#if 0
std::ofstream theSourceStream("\\foo.cpp");
std::ofstream theHeaderStream("\\foo.hpp");
dumpTable(m_FunctionNameIndex, theSourceStream, theHeaderStream);
#endif
}
catch(...)
{
DestroyTable();
throw;
}
}
void
XPathFunctionTable::DestroyTable()
{
try
{
using std::for_each;
for_each(
m_functionTable,
m_functionTable + TableSize,
DeleteFunctorType(*m_memoryManager));
std::memset(m_functionTable, 0, sizeof(m_functionTable));
}
catch(...)
{
}
}
int
XPathFunctionTable::getFunctionIndex(
const XalanDOMChar* theName,
StringSizeType theNameLength)
{
assert(theName != 0);
// Do a binary search...
const FunctionNameTableEntry* theFirst = s_functionNames;
const FunctionNameTableEntry* theLast = s_lastFunctionName;
while(theFirst <= theLast)
{
const FunctionNameTableEntry* const theCurrent =
theFirst + (theLast - theFirst) / 2;
assert(theCurrent->m_size == length(theCurrent->m_name));
const int theResult = compare(
theName,
theNameLength,
theCurrent->m_name,
theCurrent->m_size);
if (theResult < 0)
{
theLast = theCurrent - 1;
}
else if (theResult > 0)
{
theFirst = theCurrent + 1;
}
else
{
assert(int(theCurrent - s_functionNames) == theCurrent - s_functionNames);
return int(theCurrent - s_functionNames);
}
}
return InvalidFunctionNumberID;
}
XPathExceptionFunctionNotAvailable::XPathExceptionFunctionNotAvailable(
const XalanDOMString& theFunctionNumber,
XalanDOMString& theResult,
const Locator* theLocator) :
XalanXPathException(
XalanMessageLoader::getMessage(
theResult,
XalanMessages::FunctionNumberIsNotAvailable_1Param,
theFunctionNumber),
theResult.getMemoryManager(),
theLocator)
{
}
XPathExceptionFunctionNotAvailable::XPathExceptionFunctionNotAvailable(const XPathExceptionFunctionNotAvailable& other) :
XalanXPathException(other)
{
}
XPathExceptionFunctionNotAvailable::~XPathExceptionFunctionNotAvailable()
{
}
XPathExceptionFunctionNotSupported::XPathExceptionFunctionNotSupported(
const XalanDOMChar* theFunctionName,
XalanDOMString& theResult,
const Locator* theLocator) :
XalanXPathException(
XalanMessageLoader::getMessage(
theResult,
XalanMessages::FunctionIsNotSupported_1Param,
theFunctionName),
theResult.getMemoryManager(),
theLocator)
{
}
XPathExceptionFunctionNotSupported::XPathExceptionFunctionNotSupported(const XPathExceptionFunctionNotSupported& other) :
XalanXPathException(other)
{
}
XPathExceptionFunctionNotSupported::~XPathExceptionFunctionNotSupported()
{
}
const XalanDOMChar XPathFunctionTable::s_id[] =
{
XalanUnicode::charLetter_i,
XalanUnicode::charLetter_d,
0
};
const XalanDOMChar XPathFunctionTable::s_key[] =
{
XalanUnicode::charLetter_k,
XalanUnicode::charLetter_e,
XalanUnicode::charLetter_y,
0
};
const XalanDOMChar XPathFunctionTable::s_not[] =
{
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_o,
XalanUnicode::charLetter_t,
0
};
const XalanDOMChar XPathFunctionTable::s_sum[] =
{
XalanUnicode::charLetter_s,
XalanUnicode::charLetter_u,
XalanUnicode::charLetter_m,
0
};
const XalanDOMChar XPathFunctionTable::s_lang[] =
{
XalanUnicode::charLetter_l,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_g,
0
};
const XalanDOMChar XPathFunctionTable::s_last[] =
{
XalanUnicode::charLetter_l,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_s,
XalanUnicode::charLetter_t,
0
};
const XalanDOMChar XPathFunctionTable::s_name[] =
{
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_m,
XalanUnicode::charLetter_e,
0
};
const XalanDOMChar XPathFunctionTable::s_true[] =
{
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_r,
XalanUnicode::charLetter_u,
XalanUnicode::charLetter_e,
0
};
const XalanDOMChar XPathFunctionTable::s_count[] =
{
XalanUnicode::charLetter_c,
XalanUnicode::charLetter_o,
XalanUnicode::charLetter_u,
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_t,
0
};
const XalanDOMChar XPathFunctionTable::s_false[] =
{
XalanUnicode::charLetter_f,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_l,
XalanUnicode::charLetter_s,
XalanUnicode::charLetter_e,
0
};
const XalanDOMChar XPathFunctionTable::s_floor[] =
{
XalanUnicode::charLetter_f,
XalanUnicode::charLetter_l,
XalanUnicode::charLetter_o,
XalanUnicode::charLetter_o,
XalanUnicode::charLetter_r,
0
};
const XalanDOMChar XPathFunctionTable::s_round[] =
{
XalanUnicode::charLetter_r,
XalanUnicode::charLetter_o,
XalanUnicode::charLetter_u,
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_d,
0
};
const XalanDOMChar XPathFunctionTable::s_concat[] =
{
XalanUnicode::charLetter_c,
XalanUnicode::charLetter_o,
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_c,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_t,
0
};
const XalanDOMChar XPathFunctionTable::s_number[] =
{
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_u,
XalanUnicode::charLetter_m,
XalanUnicode::charLetter_b,
XalanUnicode::charLetter_e,
XalanUnicode::charLetter_r,
0
};
const XalanDOMChar XPathFunctionTable::s_string[] =
{
XalanUnicode::charLetter_s,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_r,
XalanUnicode::charLetter_i,
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_g,
0
};
const XalanDOMChar XPathFunctionTable::s_boolean[] =
{
XalanUnicode::charLetter_b,
XalanUnicode::charLetter_o,
XalanUnicode::charLetter_o,
XalanUnicode::charLetter_l,
XalanUnicode::charLetter_e,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_n,
0
};
const XalanDOMChar XPathFunctionTable::s_ceiling[] =
{
XalanUnicode::charLetter_c,
XalanUnicode::charLetter_e,
XalanUnicode::charLetter_i,
XalanUnicode::charLetter_l,
XalanUnicode::charLetter_i,
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_g,
0
};
const XalanDOMChar XPathFunctionTable::s_current[] =
{
XalanUnicode::charLetter_c,
XalanUnicode::charLetter_u,
XalanUnicode::charLetter_r,
XalanUnicode::charLetter_r,
XalanUnicode::charLetter_e,
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_t,
0
};
const XalanDOMChar XPathFunctionTable::s_contains[] =
{
XalanUnicode::charLetter_c,
XalanUnicode::charLetter_o,
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_i,
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_s,
0
};
const XalanDOMChar XPathFunctionTable::s_document[] =
{
XalanUnicode::charLetter_d,
XalanUnicode::charLetter_o,
XalanUnicode::charLetter_c,
XalanUnicode::charLetter_u,
XalanUnicode::charLetter_m,
XalanUnicode::charLetter_e,
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_t,
0
};
const XalanDOMChar XPathFunctionTable::s_position[] =
{
XalanUnicode::charLetter_p,
XalanUnicode::charLetter_o,
XalanUnicode::charLetter_s,
XalanUnicode::charLetter_i,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_i,
XalanUnicode::charLetter_o,
XalanUnicode::charLetter_n,
0
};
const XalanDOMChar XPathFunctionTable::s_substring[] =
{
XalanUnicode::charLetter_s,
XalanUnicode::charLetter_u,
XalanUnicode::charLetter_b,
XalanUnicode::charLetter_s,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_r,
XalanUnicode::charLetter_i,
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_g,
0
};
const XalanDOMChar XPathFunctionTable::s_translate[] =
{
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_r,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_s,
XalanUnicode::charLetter_l,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_e,
0
};
const XalanDOMChar XPathFunctionTable::s_localName[] =
{
XalanUnicode::charLetter_l,
XalanUnicode::charLetter_o,
XalanUnicode::charLetter_c,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_l,
XalanUnicode::charHyphenMinus,
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_m,
XalanUnicode::charLetter_e,
0
};
const XalanDOMChar XPathFunctionTable::s_generateId[] =
{
XalanUnicode::charLetter_g,
XalanUnicode::charLetter_e,
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_e,
XalanUnicode::charLetter_r,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_e,
XalanUnicode::charHyphenMinus,
XalanUnicode::charLetter_i,
XalanUnicode::charLetter_d,
0
};
const XalanDOMChar XPathFunctionTable::s_startsWith[] =
{
XalanUnicode::charLetter_s,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_r,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_s,
XalanUnicode::charHyphenMinus,
XalanUnicode::charLetter_w,
XalanUnicode::charLetter_i,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_h,
0
};
const XalanDOMChar XPathFunctionTable::s_formatNumber[] =
{
XalanUnicode::charLetter_f,
XalanUnicode::charLetter_o,
XalanUnicode::charLetter_r,
XalanUnicode::charLetter_m,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_t,
XalanUnicode::charHyphenMinus,
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_u,
XalanUnicode::charLetter_m,
XalanUnicode::charLetter_b,
XalanUnicode::charLetter_e,
XalanUnicode::charLetter_r,
0
};
const XalanDOMChar XPathFunctionTable::s_namespaceUri[] =
{
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_m,
XalanUnicode::charLetter_e,
XalanUnicode::charLetter_s,
XalanUnicode::charLetter_p,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_c,
XalanUnicode::charLetter_e,
XalanUnicode::charHyphenMinus,
XalanUnicode::charLetter_u,
XalanUnicode::charLetter_r,
XalanUnicode::charLetter_i,
0
};
const XalanDOMChar XPathFunctionTable::s_stringLength[] =
{
XalanUnicode::charLetter_s,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_r,
XalanUnicode::charLetter_i,
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_g,
XalanUnicode::charHyphenMinus,
XalanUnicode::charLetter_l,
XalanUnicode::charLetter_e,
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_g,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_h,
0
};
const XalanDOMChar XPathFunctionTable::s_normalizeSpace[] =
{
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_o,
XalanUnicode::charLetter_r,
XalanUnicode::charLetter_m,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_l,
XalanUnicode::charLetter_i,
XalanUnicode::charLetter_z,
XalanUnicode::charLetter_e,
XalanUnicode::charHyphenMinus,
XalanUnicode::charLetter_s,
XalanUnicode::charLetter_p,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_c,
XalanUnicode::charLetter_e,
0
};
const XalanDOMChar XPathFunctionTable::s_substringAfter[] =
{
XalanUnicode::charLetter_s,
XalanUnicode::charLetter_u,
XalanUnicode::charLetter_b,
XalanUnicode::charLetter_s,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_r,
XalanUnicode::charLetter_i,
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_g,
XalanUnicode::charHyphenMinus,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_f,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_e,
XalanUnicode::charLetter_r,
0
};
const XalanDOMChar XPathFunctionTable::s_systemProperty[] =
{
XalanUnicode::charLetter_s,
XalanUnicode::charLetter_y,
XalanUnicode::charLetter_s,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_e,
XalanUnicode::charLetter_m,
XalanUnicode::charHyphenMinus,
XalanUnicode::charLetter_p,
XalanUnicode::charLetter_r,
XalanUnicode::charLetter_o,
XalanUnicode::charLetter_p,
XalanUnicode::charLetter_e,
XalanUnicode::charLetter_r,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_y,
0
};
const XalanDOMChar XPathFunctionTable::s_substringBefore[] =
{
XalanUnicode::charLetter_s,
XalanUnicode::charLetter_u,
XalanUnicode::charLetter_b,
XalanUnicode::charLetter_s,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_r,
XalanUnicode::charLetter_i,
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_g,
XalanUnicode::charHyphenMinus,
XalanUnicode::charLetter_b,
XalanUnicode::charLetter_e,
XalanUnicode::charLetter_f,
XalanUnicode::charLetter_o,
XalanUnicode::charLetter_r,
XalanUnicode::charLetter_e,
0
};
const XalanDOMChar XPathFunctionTable::s_elementAvailable[] =
{
XalanUnicode::charLetter_e,
XalanUnicode::charLetter_l,
XalanUnicode::charLetter_e,
XalanUnicode::charLetter_m,
XalanUnicode::charLetter_e,
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_t,
XalanUnicode::charHyphenMinus,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_v,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_i,
XalanUnicode::charLetter_l,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_b,
XalanUnicode::charLetter_l,
XalanUnicode::charLetter_e,
0
};
const XalanDOMChar XPathFunctionTable::s_functionAvailable[] =
{
XalanUnicode::charLetter_f,
XalanUnicode::charLetter_u,
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_c,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_i,
XalanUnicode::charLetter_o,
XalanUnicode::charLetter_n,
XalanUnicode::charHyphenMinus,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_v,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_i,
XalanUnicode::charLetter_l,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_b,
XalanUnicode::charLetter_l,
XalanUnicode::charLetter_e,
0
};
const XalanDOMChar XPathFunctionTable::s_unparsedEntityUri[] =
{
XalanUnicode::charLetter_u,
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_p,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_r,
XalanUnicode::charLetter_s,
XalanUnicode::charLetter_e,
XalanUnicode::charLetter_d,
XalanUnicode::charHyphenMinus,
XalanUnicode::charLetter_e,
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_i,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_y,
XalanUnicode::charHyphenMinus,
XalanUnicode::charLetter_u,
XalanUnicode::charLetter_r,
XalanUnicode::charLetter_i,
0
};
typedef XPathFunctionTable::SizeType SizeType;
typedef XPathFunctionTable::FunctionNameTableEntry FunctionNameTableEntry;
#define XFTBL_SIZE(str) ((sizeof(str) / sizeof(str[0]) - 1))
const FunctionNameTableEntry XPathFunctionTable::s_functionNames[] =
{
{
s_id,
XFTBL_SIZE(s_id)
},
{
s_key,
XFTBL_SIZE(s_key)
},
{
s_not,
XFTBL_SIZE(s_not)
},
{
s_sum,
XFTBL_SIZE(s_sum)
},
{
s_lang,
XFTBL_SIZE(s_lang)
},
{
s_last,
XFTBL_SIZE(s_last)
},
{
s_name,
XFTBL_SIZE(s_name)
},
{
s_true,
XFTBL_SIZE(s_true)
},
{
s_count,
XFTBL_SIZE(s_count)
},
{
s_false,
XFTBL_SIZE(s_false)
},
{
s_floor,
XFTBL_SIZE(s_floor)
},
{
s_round,
XFTBL_SIZE(s_round)
},
{
s_concat,
XFTBL_SIZE(s_concat)
},
{
s_number,
XFTBL_SIZE(s_number)
},
{
s_string,
XFTBL_SIZE(s_string)
},
{
s_boolean,
XFTBL_SIZE(s_boolean)
},
{
s_ceiling,
XFTBL_SIZE(s_ceiling)
},
{
s_current,
XFTBL_SIZE(s_current)
},
{
s_contains,
XFTBL_SIZE(s_contains)
},
{
s_document,
XFTBL_SIZE(s_document)
},
{
s_position,
XFTBL_SIZE(s_position)
},
{
s_substring,
XFTBL_SIZE(s_substring)
},
{
s_translate,
XFTBL_SIZE(s_translate)
},
{
s_localName,
XFTBL_SIZE(s_localName)
},
{
s_generateId,
XFTBL_SIZE(s_generateId)
},
{
s_startsWith,
XFTBL_SIZE(s_startsWith)
},
{
s_formatNumber,
XFTBL_SIZE(s_formatNumber)
},
{
s_namespaceUri,
XFTBL_SIZE(s_namespaceUri)
},
{
s_stringLength,
XFTBL_SIZE(s_stringLength)
},
{
s_normalizeSpace,
XFTBL_SIZE(s_normalizeSpace)
},
{
s_substringAfter,
XFTBL_SIZE(s_substringAfter)
},
{
s_systemProperty,
XFTBL_SIZE(s_systemProperty)
},
{
s_substringBefore,
XFTBL_SIZE(s_substringBefore)
},
{
s_elementAvailable,
XFTBL_SIZE(s_elementAvailable)
},
{
s_functionAvailable,
XFTBL_SIZE(s_functionAvailable)
},
{
s_unparsedEntityUri,
XFTBL_SIZE(s_unparsedEntityUri)
}
};
const FunctionNameTableEntry* const XPathFunctionTable::s_lastFunctionName =
&s_functionNames[sizeof(s_functionNames) / sizeof(s_functionNames[0]) - 1];
const SizeType XPathFunctionTable::s_functionNamesSize =
sizeof(s_functionNames) / sizeof(s_functionNames[0]);
}
|
177cced44bd92d455458cae258ffb3736744e2c7
|
24df49d2d2c6afe3196d4f2f24736794c67443e6
|
/40_combination_sum2.cpp
|
75b05477c7ecc2f57a4c893f8a33989b12bbe206
|
[] |
no_license
|
manishkhilnani2911/leetcode
|
87ba15aeac250a25dd256a36663271a30a2c9229
|
1d8e91af0ddf114aa72da38f933928c9b800a467
|
refs/heads/master
| 2021-01-20T15:49:26.187533
| 2019-03-25T19:09:58
| 2019-03-25T19:09:58
| 64,050,280
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,712
|
cpp
|
40_combination_sum2.cpp
|
/*Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
Each number in candidates may only be used once in the combination.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
Example 2:
Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
[1,2,2],
[5]
]*/
class Solution {
//Ub_Mi_Li_Sn_Ub_Am
vector<vector<int>> res;
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<int> comb;
sort(candidates.begin(),candidates.end());
combinationsum(comb,candidates,target,0);
return res;
}
void combinationsum(vector<int>& ans, vector<int>& candidates, int target, int startIndex) {
if (target == 0) {
res.push_back(ans);
return;
}
//push the first value on the stack and check if the target is still greater than 0,
//again push second value on stack, now the function will return and the second value(same as previous one would be popped) from the stack
for (int i = startIndex; i < candidates.size() && target > 0; i++) {
if (i == startIndex || candidates[i] != candidates[i-1]) {
ans.push_back(candidates[i]);
//cout<<"pushing::"<<candidates[i]<<"\n";
combinationsum(ans,candidates,target-candidates[i],i+1);
//cout<<"popping::"<<ans[ans.size()-1]<<"\n";
ans.pop_back();
}
}
}
};
|
9b80bc35c13754cf46a371ba803355c94a297d73
|
3b4476d64cfc67ad2672485d0693cf7af7c70557
|
/Source/EditView.h
|
7e5ea9860d396d8672fbf960e4e379b6344ca846
|
[
"LicenseRef-scancode-public-domain"
] |
permissive
|
HaikuArchives/ZooKeeper
|
cd4adf884842cc1634fda22a18f9447929f5e1de
|
2a07893903e427640bf4d964b0596e063c9c8c62
|
refs/heads/master
| 2020-05-17T06:08:11.682362
| 2018-11-18T04:49:15
| 2018-11-18T04:49:15
| 14,764,216
| 1
| 3
|
NOASSERTION
| 2018-11-18T04:49:16
| 2013-11-28T01:13:29
|
C++
|
UTF-8
|
C++
| false
| false
| 806
|
h
|
EditView.h
|
#ifndef __EDIT_VIEW_H__
#define __EDIT_VIEW_H__
#include <Application.h>
#include <InterfaceKit.h>
#include <Box.h>
#include <MenuField.h>
class EditView : public BBox
{
public:
EditView (entry_ref ref);
~EditView ();
virtual void MessageReceived (BMessage * message);
virtual void AllAttached (void);
void Save (void);
protected:
private:
void Init (void);
void OpenFileTypes (void);
void GotoSettingsMode (void);
void GotoDropzoneMode (void);
entry_ref m_ref;
BMenuField * m_menu_field;
BMenu * m_dropdown_menu;
BMenuItem * m_settings_item;
BMenuItem * m_dropzone_item;
BTextControl * m_dir;
BTextControl * m_command;
BCheckBox * m_in_terminal;
BCheckBox * m_keep_open;
BButton * m_filetypes_button;
bool m_views_visible;
};
#endif
|
81ce18a20d54b02028abb64718957e2cc78e9e84
|
b8376621d63394958a7e9535fc7741ac8b5c3bdc
|
/common/Server/GameServer/DualGoServer/DualGoServer/MultiUser.cpp
|
35c55d81ba8a217e0e79f687c3f4859562d87f7c
|
[] |
no_license
|
15831944/job_mobile
|
4f1b9dad21cb7866a35a86d2d86e79b080fb8102
|
ebdf33d006025a682e9f2dbb670b23d5e3acb285
|
refs/heads/master
| 2021-12-02T10:58:20.932641
| 2013-01-09T05:20:33
| 2013-01-09T05:20:33
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 43,619
|
cpp
|
MultiUser.cpp
|
//
// MultiUser.cpp
// DualGoServer
//
// Created by jin young park on 11. 11. 23..
// Copyright (c) 2011년 집. All rights reserved.
//
#include "DualGoInclude.h"
//#define DEF_USE_WRITE_QUEUE
#define DEF_USE_WRITE_QUEUE
CMultiUser::CMultiUser(boost::asio::io_service& io_service, CMultiGoManager* manager) :socket_(io_service)
{
mulManager = manager;
offset = INDEX_ZERO;
setUserState(USER_STATE_ZERO);
JoinInfo.set_roomid(ERROR_VALUE);
m_iReadSize=0;
m_iReadedSize=0;
#ifndef DEF_USE_ASIO_ASYNC_READ
m_iReadedSize=0;
#endif
kickType = GAnsGameLeave_KICK_TYPE_KICK_ZERO;
}
CMultiUser::~CMultiUser()
{
if(getRoomState() == ROOM_RUN)
{
destoryRoom();
}
}
void CMultiUser::destoryRoom()
{
setRoomState(ROOM_DIE);
if(mulManager != NULL)
{
//상대의 룸상태를 바꾼다
user_ptr pUser = mulManager->getUser(getMatchUserGameID());
if(pUser != NULL)
{
pUser->setRoomState(ROOM_DIE);
}
}
pjyDELETE(logicCommand);
}
tcp::socket& CMultiUser::socket()
{
return socket_;
}
#ifndef DEF_USE_ASIO_ASYNC_READ
void CMultiUser::_async_read_some()
{
socket_.async_read_some(boost::asio::buffer(m_pDataBuff_Read, BUFFER_SIZE),
boost::bind(&CMultiUser::handle_read, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
#endif
void CMultiUser::_async_read()
{
boost::asio::async_read(socket_,boost::asio::buffer(&m_PPacketHeader_Read
, sizeof(m_PPacketHeader_Read))
, boost::bind(&CMultiUser::handle_read_header, shared_from_this()
, boost::asio::placeholders::error) );
}
void CMultiUser::read_socket()
{
#ifdef DEF_USE_ASIO_ASYNC_READ
_async_read();
#else
_async_read_some();
#endif
}
#ifndef DEF_USE_ASIO_ASYNC_READ
void CMultiUser::handle_read(const boost::system::error_code& error, size_t bytes_transferred)
{
const int iSIZE_m_pDataBuff_Readed = nGS::BUFFER_SIZE*8;
const int iHEADER_SIZE= sizeof(int);
if (error)
{
jWARN("소켓 아웃 error");
GameUserInfo* pInfo = JoinInfo.mutable_gameuserinfo();
GameInfo* pGame = pInfo->mutable_gameinfo();
mulManager->leave(pGame->gameid());
return;
}
if((bytes_transferred + m_iReadedSize) >= iSIZE_m_pDataBuff_Readed )
{
jWARN("소켓 아웃 if((bytes_transferred+ m_iReadedSize)>= iSIZE_m_pDataBuff_Readed)");
GameUserInfo* pInfo = JoinInfo.mutable_gameuserinfo();
GameInfo* pGame = pInfo->mutable_gameinfo();
mulManager->leave(pGame->gameid());
return;
}
memcpy(m_pDataBuff_Readed+m_iReadedSize,m_pDataBuff_Read,bytes_transferred);
m_iReadedSize+=bytes_transferred;
if(m_iReadedSize<= iHEADER_SIZE)
{
_async_read_some();
return;
}
char* pBody = m_pDataBuff_Readed;
int iLengthBody=0;
memcpy(&iLengthBody , pBody, iHEADER_SIZE);
pBody+=iHEADER_SIZE;
if(iLengthBody<=0 || (iLengthBody>=(BUFFER_SIZE-iHEADER_SIZE) ) )
{
jWARN("소켓 아웃 error if(iLengthBody<=0 || (iLengthBody>=(BUFFER_SIZE-iHEADER_SIZE) ) )");
GameUserInfo* pInfo = JoinInfo.mutable_gameuserinfo();
GameInfo* pGame = pInfo->mutable_gameinfo();
mulManager->leave(pGame->gameid());
return;
}
if(iLengthBody > (m_iReadedSize-iHEADER_SIZE) )
{
// 바디가 iLengthBody만큼 못읽었으모.
_async_read_some();
return;
}
size_t iStayReadedSize = m_iReadedSize;
try
{
for(;;)
{
google::protobuf::io::ArrayInputStream is(pBody, iLengthBody);
GReqProtocol matgo;
matgo.ParseFromZeroCopyStream(&is);
switch(matgo.type())
{
case GReqProtocol_Type_GLREQGAMEPROTOCOL:
{
GLReqGameProtocol* packet = matgo.mutable_reqgameprotocol();
jBREAK(packet);
packetParse(packet);
break;
}
case GReqProtocol_Type_GREQGAMEENTER:
{
GReqGameEnter* enter = matgo.mutable_reqgameenter();
jBREAK(enter);
GameUserInfo* gameUserInfo = enter->mutable_gameuserinfo();
GameInfo* pSocGame = gameUserInfo->mutable_gameinfo();
if(mulManager->checkUser(pSocGame->gameid()))
{
mulManager->leave(pSocGame->gameid());
#ifdef LOGSET
std::cerr << "User duplicate = " << pSocGame->gameid() << "\n";
#endif
}
else
{
parseEnterGame(enter);
GAnsProtocol ansPro;
makeEnter(ansPro);
sendAllPacket(ansPro);
}
break;
}
case GReqProtocol_Type_GREQGAMELEAVE:
{
GReqGameLeave* leave = matgo.mutable_reqgameleave();
jBREAK(leave);
parseLeave(leave);
break;
}
case GReqProtocol_Type_GREQPLUG:
{
GReqPlug* plug = matgo.mutable_reqplug();
jBREAK(plug);
parsePlug(plug);
break;
}
case GReqProtocol_Type_GREQDETACH:
{
GReqDetach* detach = matgo.mutable_reqdetach();
jBREAK(detach);
parseDetach(detach);
break;
}
case GReqProtocol_Type_GDBANS:
{
AnsDB* db = matgo.mutable_ansdb();
jBREAK(db);
parseDB(db);
break;
}
// case FlowMatGo_Type_PING:
// {
// FlowMatGo req;
// req.set_type(FlowMatGo_Type_PONG);
// sendPacket(req);
// jLOG("Send Pong");
// break;
// }
default:
{
jWARN("matgo.type() : invalied packet");
GameUserInfo* pInfo = JoinInfo.mutable_gameuserinfo();
GameInfo* pGame = pInfo->mutable_gameinfo();
mulManager->leave(pGame->gameid());
return;
}
}//switch(matgo.type())
iStayReadedSize -= (iLengthBody+iHEADER_SIZE);
if(iStayReadedSize<=0)
{
m_iReadedSize=0;
break;
}
jWARN("data뭉쳐서왔다.");
if(iStayReadedSize<= iHEADER_SIZE)
{
memmove(m_pDataBuff_Readed, pBody, iStayReadedSize);
m_iReadedSize=iStayReadedSize;
break;
}
//파싱할 패킷이 남았다.
pBody = pBody+iLengthBody;
memcpy(&iLengthBody,pBody,iHEADER_SIZE);
if(iLengthBody > (iStayReadedSize-iHEADER_SIZE ) ) //아직 바디 데이타가 완성안되었으모.
{
memmove(m_pDataBuff_Readed, pBody, iLengthBody);
m_iReadedSize=iLengthBody;
break;
}
pBody+=iHEADER_SIZE;
}//for(;;)
_async_read_some();
}
catch (...)
{
jWARN("try");
GameUserInfo* pInfo = JoinInfo.mutable_gameuserinfo();
GameInfo* pGame = pInfo->mutable_gameinfo();
mulManager->leave(pGame->gameid());
}
}
#endif
void CMultiUser::handle_read_header(const boost::system::error_code& error)
{
if(error)
{
jERROR("소켓 아웃");
GameUserInfo* pInfo = JoinInfo.mutable_gameuserinfo();
GameInfo* pGame = pInfo->mutable_gameinfo();
mulManager->leave(pGame->gameid());
return;
}
if (m_PPacketHeader_Read.data_length < 0 && m_PPacketHeader_Read.data_length >= nGS::BUFFER_SIZE)
{
return;
}
boost::asio::async_read(socket_,
boost::asio::buffer(m_pDataBuff_Read, m_PPacketHeader_Read.data_length ),
boost::bind(&CMultiUser::handle_read_body, shared_from_this(),
boost::asio::placeholders::error));
}
void CMultiUser::handle_read_body(const boost::system::error_code& error)
{
if (error)
{
jERROR("소켓 아웃 여기서 에러처리한다.")
GameUserInfo* pInfo = JoinInfo.mutable_gameuserinfo();
GameInfo* pGame = pInfo->mutable_gameinfo();
mulManager->leave(pGame->gameid());
return;
}
google::protobuf::io::ArrayInputStream is(m_pDataBuff_Read, m_PPacketHeader_Read.data_length);
try
{
GReqProtocol matgo;
matgo.ParseFromZeroCopyStream(&is);
jONCE
{
if (matgo.type() == GReqProtocol_Type_GLREQGAMEPROTOCOL)
{
GLReqGameProtocol* packet = matgo.mutable_reqgameprotocol();
jBREAK(packet);
packetParse(packet);
}
// else if (matgo.type() == FlowMatGo_Type_PING)
// {
// FlowMatGo req;
// req.set_type(FlowMatGo_Type_PONG);
// sendPacket(req);
// jLOG(_T("Send Pong"));
// }
}
}
catch (...)
{
jERROR(" matgo.ParseFromZeroCopyStream");
}
this->read_socket();
}
void CMultiUser::sendPacket(GAnsProtocol& matgo)
{
int nSize = matgo.ByteSize();
m_writeBuff.header.data_length = matgo.ByteSize()+sizeof(int);
jRETURN(m_writeBuff.header.data_length<nGS::BUFFER_SIZE);
memcpy(m_writeBuff.pBody, &nSize, sizeof(int));
assert(sizeof(m_writeBuff.header)==4);
google::protobuf::io::ArrayOutputStream os(m_writeBuff.pBody+sizeof(int), matgo.ByteSize());
matgo.SerializeToZeroCopyStream(&os);
#ifdef DEF_USE_WRITE_QUEUE
//패킷을 보낸다.
bool write_msgs_empty = m_write_msgs.empty();
m_write_msgs.push_back(m_writeBuff);
if (write_msgs_empty)
#endif
{
this->_send();
}
#ifdef LOGSET
std::cerr << "send packet uid = " << getGameID() << "\n";
#endif
}
void CMultiUser::_send()
{
#ifdef DEF_USE_WRITE_QUEUE
boost::asio::async_write(socket_,
boost::asio::buffer(m_write_msgs.front().pBody,m_write_msgs.front().header.data_length),
boost::bind(&CMultiUser::handle_write, shared_from_this(),
boost::asio::placeholders::error));
#else
boost::asio::async_write(socket_,
boost::asio::buffer(m_writeBuff.pBody,m_writeBuff.header.data_length),
boost::bind(&CMultiUser::handle_write, shared_from_this(),
boost::asio::placeholders::error));
#endif
}
//패킷을 다른 사람에게 보낸다.
void CMultiUser::sendYouPacket(GAnsProtocol& matgo, int GameID)
{
//상대방 포인터를 찾는다.
user_ptr pUser = mulManager->getUser(GameID);
if(pUser != NULL)
{
pUser->sendPacket(matgo);
}
else
{
}
}
void CMultiUser::sendYouPacket(GAnsProtocol& matgo)
{
GameUserInfo* pYouInfo = YouJoinInfo.mutable_gameuserinfo();
GameUserInfo* pInfo = JoinInfo.mutable_gameuserinfo();
GameInfo* pGame = pInfo->mutable_gameinfo();
GameInfo* pYouGame = pYouInfo->mutable_gameinfo();
#ifdef LOGSET
std::cerr << "send you id = " << pYouGame->gameid() << "\n";
#endif
if((pGame->gameid() != pYouGame->gameid()) && pYouGame->gameid() > 0)
{
#ifdef LOGSET
std::cerr << "send you packet\n";
#endif
sendYouPacket(matgo, pYouGame->gameid());
}
}
//패킷을 모두 보낸다.
void CMultiUser::sendAllPacket(GAnsProtocol& matgo)
{
sendPacket(matgo);
GameUserInfo* pYouInfo = YouJoinInfo.mutable_gameuserinfo();
GameUserInfo* pInfo = JoinInfo.mutable_gameuserinfo();
GameInfo* pGame = pInfo->mutable_gameinfo();
GameInfo* pYouGame = pYouInfo->mutable_gameinfo();
#ifdef LOGSET
std::cerr << "send id = " << getGameID() << "\n";
std::cerr << "send you id = " << pYouGame->gameid() << "\n";
#endif
if((pGame->gameid() != pYouGame->gameid()) && pYouGame->gameid() > 0)
{
#ifdef LOGSET
std::cerr << "send you packet\n";
#endif
sendYouPacket(matgo, pYouGame->gameid());
}
}
//패킷 보낸후 콜백
void CMultiUser::handle_write(const boost::system::error_code& error)
{
if (error)
{
// m_write_error_count++;
// if(m_write_error_count>50)
// {
jWARN(_T("handle_write..."));
GameUserInfo* pInfo = JoinInfo.mutable_gameuserinfo();
GameInfo* pGame = pInfo->mutable_gameinfo();
mulManager->leave(pGame->gameid());
// ...
// }
return;
}
#ifdef DEF_USE_WRITE_QUEUE
m_write_msgs.pop_front();
if(!m_write_msgs.empty())
this->_send();
#endif
}
//게임 패킷을 만든다.
void CMultiUser::makePacket(GAnsProtocol_Type nType, GAnsProtocol& matgo)
{
switch (nType) {
case GReqProtocol_Type_GREQGAMEENTER:
//makeReqGameJoinRoom(matgo);
break;
case GReqProtocol_Type_GREQGAMELEAVE:
break;
case GReqProtocol_Type_GREQDETACH:
break;
case GReqProtocol_Type_GREQPLUG:
break;
// case GAnsProtocol_Type_GANSGAMEENTER:
/// makeEnter(matgo);
break;
default:
break;
}
// makeGameStartReady(matgo);
//
// setTimer(TIMER_START);
//
//
// GLAnsGameProtocol_Type
}
//게임 패킷을 만든다.
void CMultiUser::makeGamePacket(GLAnsGameProtocol_Type nType, GAnsProtocol& matgo)
{
switch (nType) {
case GLAnsGameProtocol_Type_GAME_STARTREADY:
makeGameStartReady(matgo);
setTimer(TIMER_START);
break;
default:
break;
}
}
void CMultiUser::makeEnter(GAnsProtocol& matgo)
{
matgo.set_type(::GAnsProtocol_Type_GANSGAMEENTER);
GAnsGameEnter* packet = matgo.mutable_ansgameenter();
GameRoomInfo* pRoom = packet->mutable_gameroominfo();
pRoom->set_roomid(getRoomID());
pRoom->set_pointmoney((int)getPointMoney(JoinInfo.categoryid()));
GameUserInfo* gameUserInfo = JoinInfo.mutable_gameuserinfo();
GameUserInfo* pJoin = pRoom->add_gameuserinfo();
GameInfo* pDetGame = pJoin->mutable_gameinfo();
GameInfo* pSocGame = gameUserInfo->mutable_gameinfo();
pDetGame->CopyFrom(*pSocGame);
MemberInfo* pDetMember = pJoin->mutable_memberinfo();
MemberInfo* pSocMember = gameUserInfo->mutable_memberinfo();
pDetMember->CopyFrom(*pSocMember);
pRoom = packet->mutable_gameroominfo();
pRoom->set_roomid(getRoomID());
pRoom->set_pointmoney((int)getPointMoney(JoinInfo.categoryid()));
gameUserInfo = YouJoinInfo.mutable_gameuserinfo();
pSocGame = gameUserInfo->mutable_gameinfo();
if(pSocGame->gameid() > 0)
{
pJoin = pRoom->add_gameuserinfo();
pDetGame = pJoin->mutable_gameinfo();
pSocGame = gameUserInfo->mutable_gameinfo();
pDetGame->CopyFrom(*pSocGame);
pDetMember = pJoin->mutable_memberinfo();
pSocMember = gameUserInfo->mutable_memberinfo();
pDetMember->CopyFrom(*pSocMember);
}
}
void CMultiUser::makeLeave(GAnsProtocol& matgo, int gameID, GAnsGameLeave_KICK_TYPE nType)
{
matgo.set_type(::GAnsProtocol_Type_GANSGAMELEAVE);
GAnsGameLeave* packet = matgo.mutable_ansgameleave();
packet->set_gameid(gameID);
packet->set_ntype(nType);
}
void CMultiUser::makePlug(GAnsProtocol& matgo, int gameID)
{
matgo.set_type(::GAnsProtocol_Type_GANSPLUG);
GAnsPlug* packet = matgo.mutable_ansplug();
packet->set_gameid(gameID);
}
void CMultiUser::makePlugErr(GAnsProtocol& matgo, std::string str)
{
matgo.set_type(::GAnsProtocol_Type_GERRPLUG);
GErrPlug* packet = matgo.mutable_anserr();
GError* err = packet->mutable_error();
err->set_errorcode(1);
err->set_errorinfo(str);
}
void CMultiUser::makeExitReservation(GAnsProtocol& matgo, int gameIndex, bool bExit)
{
matgo.set_type(::GAnsProtocol_Type_GLANSGAMEPROTOCOL);
GLAnsGameProtocol* packet = matgo.mutable_ansgameprotocol();
packet->set_type(::GLAnsGameProtocol_Type_GAME_EXITRESERVATION);
GLAnsExitReservation* exit = packet->mutable_ansexitreservation();
exit->set_gameindex(gameIndex);
exit->set_bexit(bExit);
}
//패킷 파서
void CMultiUser::packetParse(GLReqGameProtocol* packet)
{
#ifdef LOGSET
std::cerr << "rec packet\n";
#endif
switch (packet->type())
{
case GLReqGameProtocol_Type_REQ_GAME_READY:
parseGameReady(packet->mutable_reqgameready());
break;
case GLReqGameProtocol_Type_REQ_GAME_INITGAME:
parseGameReqInitGame(packet->mutable_reqinitgame());
break;
case GLReqGameProtocol_Type_REQ_GAME_SELECTSUNCARD:
parseGameReqSelectSunCard(packet->mutable_reqselectsuncard());
break;
case GLReqGameProtocol_Type_REQ_GAME_START:
parseGameReqGameStart(packet->mutable_reqstart());
break;
case GLReqGameProtocol_Type_REQ_GAME_SELECTCARD:
parseGameSelectCard(packet->mutable_reqselectcard());
break;
case GLReqGameProtocol_Type_REQ_GAME_ASKSHAKEANS:
parseGameAskShakeAns(packet->mutable_reqaskshakeans());
break;
case GLReqGameProtocol_Type_REQ_GAME_CHOICECARDANS:
parseGameChoiceCard(packet->mutable_reqchoicecardans());
break;
case GLReqGameProtocol_Type_REQ_GAME_RESET:
parseGameReset(packet->mutable_reqreset());
break;
case GLReqGameProtocol_Type_REQ_GAME_RESULTOK:
parseGameResultOk(packet->mutable_reqresultok());
break;
case GLReqGameProtocol_Type_REQ_GAME_ASKGOSTOPANS:
parseGameAskGostopAns(packet->mutable_reqaskgostopans());
break;
case GLReqGameProtocol_Type_REQ_GAME_MOVETEN:
parseGameMoveTen(packet->mutable_reqmoveten());
break;
case GLReqGameProtocol_Type_REQ_GAME_CHONGTONG:
parseGameChongtong(packet->mutable_reqchongtong());
break;
case GLReqGameProtocol_Type_REQ_GAME_AUTOPLAY:
parseGameAutoPlay(packet->mutable_reqgameautoplay());
break;
case GLReqGameProtocol_Type_REQ_GAME_EXITRESERVATION:
parseExitReservation(packet->mutable_reqexitreservation());
break;
case GLReqGameProtocol_Type_REQ_GAME_RELAYINFO:
parseGameRelayInfo(packet->mutable_reqrelayinfo());
break;
case GLReqGameProtocol_Type_REQ_GAME_EMOTI:
parseGameEmoti(packet->mutable_reqgameemoti());
case GLReqGameProtocol_Type_REQ_GAME_END:
break;
case GLReqGameProtocol_Type_REQ_GAME_INITGAMETAN:
parseGameInitTan(packet->mutable_reqtaninit());
break;
default:
break;
}
}
void CMultiUser::parseLeave(GReqGameLeave* packet)
{
if(packet != NULL)
{
if(logicCommand != NULL && getRoomState() == ROOM_RUN)
{
if(packet->gameid() == getGameID())
{
logicCommand->requestGameLeave(getGameID(), EXIT_RESERVATION);
}
}
else
{
GAnsProtocol matgo;
makeLeave(matgo, packet->gameid(), GAnsGameLeave_KICK_TYPE_EXIT_RESERVATION);
sendPacket(matgo);
}
#ifdef LOGSET
std::cerr << "i = " << getGameID() << "you = " << packet->gameid() << "\n";
#endif
}
}
//게임을 떠날때 정리한다.
void CMultiUser::leaveSet(int nGameID)
{
//떠나는 사람이 내가 아니면
if(getGameID() != nGameID)
{
YouJoinInfo.Clear();
//게임을 리셋한다.
logicCommand->resetInit();
setUserIndex(0);
// setLogicCommand(logicCommand);
setRoomState(ROOM_DIE);
}
else
{
//게임을 리셋한다.
logicCommand->resetInit();
user_ptr pUser = mulManager->getUser(getMatchUserGameID());
if(pUser != NULL)
{
pUser->setUserIndex(0);
}
// setLogicUser();
pUser->setRoomState(ROOM_DIE);
}
}
void CMultiUser::parseEnterGame(GReqGameEnter* packet)
{
if(packet != NULL)
{
GameUserInfo* gameUserInfo = packet->mutable_gameuserinfo();
GameUserInfo* pJoin = JoinInfo.mutable_gameuserinfo();
GameInfo* pDetGame = pJoin->mutable_gameinfo();
GameInfo* pSocGame = gameUserInfo->mutable_gameinfo();
JoinInfo.set_categoryid(packet->categoryid());
JoinInfo.set_channelid(packet->channelid());
JoinInfo.set_roomid(packet->roomid());
pDetGame->CopyFrom(*pSocGame);
MemberInfo* pDetMember = pJoin->mutable_memberinfo();
MemberInfo* pSocMember = gameUserInfo->mutable_memberinfo();
pDetMember->CopyFrom(*pSocMember);
mulManager->setMatchRoom(pSocGame->gameid(), packet->roomid());
}
}
void CMultiUser::parsePlug(GReqPlug* packet)
{
if(packet != NULL)
{
GAnsProtocol matgo;
int gameID = packet->gameid();
if(mulManager->getUserIndex(gameID) == ERROR_VALUE)
{
makePlugErr(matgo, "plug Error");
sendPacket(matgo);
//sendAllPacket(matgo);
}
else
{
makePlug(matgo, gameID);
sendPacket(matgo);
//sendAllPacket(matgo);
}
}
}
void CMultiUser::parseDetach(GReqDetach* detach)
{
int uID = detach->gameid();
user_ptr pUser = mulManager->getUser(uID);
if(pUser != NULL)
{
GAnsProtocol ans;
GAnsGameLeave_KICK_TYPE nType = GAnsGameLeave_KICK_TYPE_EXIT_RESERVATION;
if(pUser->getUserState() == USER_ROOM_WAIT)
{
makeLeave(ans, uID, nType);
sendAllPacket(ans);
mulManager->leave(uID);
}
}
}
void CMultiUser::parseDB(AnsDB* db)
{
if(db->retcode() == 1)
{
if(db->seq() == (int)GAME_RESULT)
{
GameUserInfo* pUserGame = JoinInfo.mutable_gameuserinfo();
GameInfo* pGameInfo = pUserGame->mutable_gameinfo();
GameUserInfo* pYouGame = YouJoinInfo.mutable_gameuserinfo();
GameInfo* pYou = pYouGame->mutable_gameinfo();
user_ptr pMatchUser = mulManager->getUser(getMatchUserGameID());
GameUserInfo* pMatchUserGame;
GameInfo* pMatchGameInfo;
GameUserInfo* pMatchYouGame;
GameInfo* pMatchYou;
if(pMatchUser != NULL)
{
pMatchUserGame = pMatchUser->JoinInfo.mutable_gameuserinfo();
pMatchGameInfo = pMatchUserGame->mutable_gameinfo();
pMatchYouGame = pMatchUser->YouJoinInfo.mutable_gameuserinfo();
pMatchYou = pMatchYouGame->mutable_gameinfo();
}
GameUpdateInfo upInfo;
upInfo.ParseFromString(*db->mutable_result());
MoneyInfo pInfo;
pInfo.set_money("0");
int level = -1;
for(int i=0; i< upInfo.gameinfo_size(); i++)
{
GameInfo pGame = upInfo.gameinfo(i);
if(pGame.gameid() == pGameInfo->gameid())
{
pGameInfo->CopyFrom(pGame);
if(pMatchYou != NULL)
{
pMatchYou->CopyFrom(pGame);
}
}
else if(pGame.gameid() == pYou->gameid())
{
pYou->CopyFrom(pGame);
if(pMatchGameInfo != NULL)
{
pMatchGameInfo->CopyFrom(pGame);
}
}
if(upInfo.moneyinfo_size() > 0)
{
pInfo = upInfo.moneyinfo(0);
if(pGame.gameid() == pInfo.gameid())
{
level = pGame.level();
}
}
}
logicCommand->sendDbUpdate(pInfo.gameid(), level, atoll(pInfo.money().c_str()));
}
else
{
#ifdef LOGSET
std::cerr << "Mission DB Recv";
#endif
GameUpdateInfo upInfo;
upInfo.ParseFromString(*db->mutable_result());
MoneyInfo pInfo;
for(int i=0; i<upInfo.moneyinfo_size(); i++)
{
pInfo = upInfo.moneyinfo(i);
}
}
}
else
{
//DB 에러 처리
GAnsProtocol matgo;
makeLeave(matgo, getGameID(), GAnsGameLeave_KICK_TYPE_SYSTEM_ERROR);
sendAllPacket(matgo);
}
}
unsigned long long CMultiUser::getPointMoney(int cateID)
{
unsigned long long llPoint = 1000;
switch(cateID)
{
case 0:
llPoint = 1000;
break;
case 1:
llPoint = 3000;
break;
case 2:
llPoint = 5000;
break;
case 3:
llPoint = 10000;
break;
case 4:
llPoint = 30000;
break;
case 5:
llPoint = 50000;
break;
default:
llPoint = 1000;
break;
}
return llPoint;
}
//유저 응답 응답을 보낸다.
//void CMultiUser::makeUserConnectAns(FlowMatGo& matgo)
//{
// matgo.set_type(::FlowMatGo_Type_MATGOPACKET);
//
// GamePacket* packet = matgo.mutable_gamepacket();
//
// packet->set_type(::GamePacket_Type_UG_USERCONNECT_ANS);
//
// GameUserConnectAns* ans = packet->mutable_gameuserconnectans();
//
// ans->set_gameindex(mulManager->getUserIndex(JoinInfo.gameid()));
//}
//
//GameJoinRoom 패킷을 만든다.
void CMultiUser::makeGameJoinRoom(GAnsProtocol& matgo)
{
// matgo.set_type(::FlowMatGo_Type_MATGOPACKET);
//
// GamePacket* packet = matgo.mutable_gamepacket();
//
// packet->set_type(::GamePacket_Type_GAME_JOINROOM);
//
// GameJoinRoom* pJoinRoom = packet->mutable_gamejoin();
//
// pJoinRoom->set_gameid(JoinInfo.gameid());
// pJoinRoom->set_gameindex(JoinInfo.gameindex());
//
// pJoinRoom->set_avatarurl(JoinInfo.avatarurl());
// pJoinRoom->set_nickname(JoinInfo.nickname());
// pJoinRoom->set_level(JoinInfo.level());
// pJoinRoom->set_money(JoinInfo.money());
// pJoinRoom->set_wincnt(JoinInfo.wincnt());
// pJoinRoom->set_losecnt(JoinInfo.losecnt());
// pJoinRoom->set_allincnt(JoinInfo.allincnt());
//
// pJoinRoom->set_pointmoney(JoinInfo.pointmoney());
//#ifdef LOGSET
// std::cerr << "gameID = " << pJoinRoom->gameid() << "\n";
// std::cerr << "avataUrl = " << pJoinRoom->avatarurl() << "\n";
// std::cerr << "nickname = " << pJoinRoom->nickname() << "\n";
// std::cerr << "level = " << pJoinRoom->level() << "\n";
// std::cerr << "winCnt = " << pJoinRoom->wincnt() << "\n";
// std::cerr << "losecnt = " << pJoinRoom->losecnt() << "\n";
// std::cerr << "allincnt = " << pJoinRoom->allincnt() << "\n";
// std::cerr << "point money = " << pJoinRoom->pointmoney() << "\n";
//#endif
}
void CMultiUser::makeReqGameJoinRoom(GAnsProtocol& matgo)
{
// matgo.set_type(::FlowMatGo_Type_MATGOPACKET);
//
// GamePacket* packet = matgo.mutable_gamepacket();
//
// packet->set_type(::GamePacket_Type_REQ_GAME_JOINROOM);
}
//게임 스타트 버튼을 준비 시킨다.
void CMultiUser::makeGameStartReady(GAnsProtocol& matgo)
{
#ifdef LOGSET
std::cerr << "make packet start ready!!\n";
#endif
matgo.set_type(::GAnsProtocol_Type_GLANSGAMEPROTOCOL);
GLAnsGameProtocol* packet = matgo.mutable_ansgameprotocol();
packet->set_type(::GLAnsGameProtocol_Type_GAME_STARTREADY);
GLAnsGameStartReady* ready = packet->mutable_gamestartready();
GameUserInfo* pGame = JoinInfo.mutable_gameuserinfo();
GameInfo* pInfo = pGame->mutable_gameinfo();
ready->set_gameid(pInfo->gameid());
ready->set_gameindex(pInfo->gameindex());
}
//게임룸에 입장할때
void CMultiUser::parseJoinRoom(GReqGameEnter* joinRoom)
{
//여기서 게임 룸을 조인한 정보를 가지고 있는다.
// if(joinRoom->gameid() == JoinInfo.gameid())
// {
// JoinInfo.set_gameindex(joinRoom->gameindex());
// JoinInfo.set_avatarurl(joinRoom->avatarurl());
// JoinInfo.set_nickname(joinRoom->nickname());
// JoinInfo.set_level(joinRoom->level());
// JoinInfo.set_money(joinRoom->money());
// JoinInfo.set_wincnt(joinRoom->wincnt());
// JoinInfo.set_losecnt(joinRoom->losecnt());
// JoinInfo.set_allincnt(joinRoom->allincnt());
// JoinInfo.set_pointmoney(joinRoom->pointmoney());
// }
// else
// {
// YouJoinInfo.set_gameid(joinRoom->gameid());
// YouJoinInfo.set_gameindex(joinRoom->gameindex());
// YouJoinInfo.set_avatarurl(joinRoom->avatarurl());
// YouJoinInfo.set_nickname(joinRoom->nickname());
// YouJoinInfo.set_level(joinRoom->level());
// YouJoinInfo.set_money(joinRoom->money());
// YouJoinInfo.set_wincnt(joinRoom->wincnt());
// YouJoinInfo.set_losecnt(joinRoom->losecnt());
// YouJoinInfo.set_allincnt(joinRoom->allincnt());
// YouJoinInfo.set_pointmoney(joinRoom->pointmoney());
// }
}
//게임 준비가 되었다.
void CMultiUser::parseGameReady(GLReqGameReady* gameReady)
{
//래디 상태로 바꾼다.
setUserState(USER_GAME_READY);
//게임이 전부 래디 상태인지 확인한다.
user_ptr pUSer = mulManager->getUser(getMatchUserGameID());
if(pUSer != NULL)
{
if(pUSer->getUserState() == USER_GAME_READY)
{
GAnsProtocol matgo;
GameUserInfo* pGame = JoinInfo.mutable_gameuserinfo();
GameUserInfo* pYouGame = YouJoinInfo.mutable_gameuserinfo();
GameInfo* pInfo = pGame->mutable_gameinfo();
GameInfo* pYouInfo = pYouGame->mutable_gameinfo();
if(pInfo->gameindex() == 0)
{
makeGamePacket(::GLAnsGameProtocol_Type_GAME_STARTREADY, matgo);
sendPacket(matgo);
#ifdef LOGSET
std::cerr << "gameID = " << pInfo->gameid() << " start ready send\n";
#endif
}
else if(pYouInfo->gameindex() == 0)
{
pUSer->makeGamePacket(::GLAnsGameProtocol_Type_GAME_STARTREADY, matgo);
pUSer->sendPacket(matgo);
#ifdef LOGSET
std::cerr << "gameID = " << pYouInfo->gameid() << " start ready send\n";
#endif
}
}
}
}
//처음 접속할때
//void CMultiUser::parseConnectUserReq(GameUserConnectReq* userConnectReq)
//{
// JoinInfo.set_gameid(userConnectReq->gameid());
//
// JoinInfo.set_avatarurl(userConnectReq->avataurl());
// JoinInfo.set_nickname(userConnectReq->nickname());
// JoinInfo.set_level(userConnectReq->level());
// JoinInfo.set_money(userConnectReq->money());
// JoinInfo.set_wincnt(userConnectReq->wincnt());
// JoinInfo.set_losecnt(userConnectReq->losecnt());
// JoinInfo.set_allincnt(userConnectReq->allincnt());
// JoinInfo.set_pointmoney(userConnectReq->pointmoney());
//
//#ifdef LOGSET
// std::cerr << "gameID = " << JoinInfo.gameid() << "\n";
// std::cerr << "avataUrl = " << JoinInfo.avatarurl() << "\n";
// std::cerr << "nickname = " << JoinInfo.nickname() << "\n";
// std::cerr << "level = " << JoinInfo.level() << "\n";
// std::cerr << "winCnt = " << JoinInfo.wincnt() << "\n";
// std::cerr << "losecnt = " << JoinInfo.losecnt() << "\n";
// std::cerr << "allincnt = " << JoinInfo.allincnt() << "\n";
// std::cerr << "point money = " << JoinInfo.pointmoney() << "\n";
//#endif
//}
//최초 게임을 시작한다.
void CMultiUser::parseGameReqInitGame(GLReqGameInitGame* gameInit)
{
//포인트 머니 어디서 받을것인가?
// GameUserInfo* pInfo = JoinInfo.mutable_gameuserinfo();
//
// GameInfo* pGame = pInfo->mutable_gameinfo();
if(logicCommand != NULL && getRoomState() != ROOM_DIE)
{
logicCommand->initGame();
}
}
void CMultiUser::parseGameInitTan(GLReqGameInitGameTan* tan)
{
if(tan != NULL && logicCommand != NULL)
{
logicCommand->setRoomPointMoney();
logicCommand->requestInitGame((TAN_TYPE)tan->tantype(), (MISSION_TYPE)tan->missiontype(), tan->missionmul());
}
}
//선을 선택한 인덱스
void CMultiUser::parseGameReqSelectSunCard(GLReqGameSelectSunCard* sunCard)
{
if(sunCard != NULL)
{
logicCommand->requestSelectSunCard(sunCard->gameindex(), sunCard->ncard());
}
}
//게임을 시작한다.
void CMultiUser::parseGameReqGameStart(GLReqGameStart* start)
{
if(start != NULL)
{
logicCommand->requestGameStart(MULTI_GAME, MISSION_ZERO, INDEX_ZERO, TAN_ZERO);
}
}
void CMultiUser::parseGameReset(GLReqGameReset* reset)
{
if(reset != NULL)
{
logicCommand->resetGame();
}
}
void CMultiUser::parseGameResultOk(GLReqResultOk* resultOk)
{
if(resultOk != NULL)
{
if(logicCommand != NULL && getRoomState() == ROOM_RUN)
{
logicCommand->requestResultOk(resultOk->gameindex());
}
}
}
void CMultiUser::parseGameSelectCard(GLReqGameSelectCard* slect)
{
if(getRoomState() == ROOM_RUN)
{
if(select != NULL)
{
logicCommand->requestSelectCard(slect->gameindex(), slect->ncard());
}
}
}
void CMultiUser::parseGameAskGostopAns(GLReqGameAskGoStopAns* ans)
{
if(ans != NULL)
{
logicCommand->requestAskGoStopAns(ans->gameindex(), ans->bgo());
}
}
void CMultiUser::parseGameAskShakeAns(GLReqGameAskShakeAns* ans)
{
if(ans != NULL)
{
logicCommand->requestAskShakeAns(ans->gameindex(), ans->bshake());
}
}
void CMultiUser::parseGameChoiceCard(GLReqGameChoiceCardAns* card)
{
if(card != NULL)
{
GAME_STATE nType = GAME_ZERO;
switch (card->ntype())
{
case GLReqGameChoiceCardAns_Type_SELECT:
nType = GAME_SELECTCARD;
break;
case GLReqGameChoiceCardAns_Type_UPSET:
nType = GAME_UPSET;
break;
default:
break;
}
logicCommand->requestChoiceHTAns(card->gameindex(), card->ncard(), nType);
}
}
void CMultiUser::parseGameMoveTen(GLReqGameMoveTen* move)
{
if(move != NULL)
{
logicCommand->requestMoveTenAns(move->gameindex(), move->bmove());
}
}
void CMultiUser::parseGameChongtong(GLReqGameChongTong* chong)
{
if(chong != NULL)
{
logicCommand->request4HTAns(chong->gameindex(), chong->byes());
}
}
void CMultiUser::parseGameAutoPlay(GLReqGameAutoPlay* play)
{
if(play != NULL)
{
logicCommand->requestGameAutoPlay(play->gameindex(), play->bauto());
}
}
void CMultiUser::parse_REQ_GAME_TEST_PACKET(G_REQ_GAME_TEST_PACKET* p)
{
if(p!= NULL)
{
logicCommand->request_REQ_GAME_TEST_PACKET(p->test_string(),p->test_int());
}
}
void CMultiUser::parseExitReservation(GLReqExitReservation* exit)
{
if(getRoomState() == ROOM_RUN)
{
if(exit != NULL)
{
logicCommand->reqExitReservation(exit->gameindex(), exit->bexit());
}
//바로 보내기
GAnsProtocol matgo;
matgo.set_type(::GAnsProtocol_Type_GLANSGAMEPROTOCOL);
GLAnsGameProtocol* packet = matgo.mutable_ansgameprotocol();
packet->set_type(::GLAnsGameProtocol_Type_GAME_EXITRESERVATION);
GLAnsExitReservation* pExit = packet->mutable_ansexitreservation();
pExit->set_gameindex(exit->gameindex());
pExit->set_bexit(exit->bexit());
sendAllPacket(matgo);
}
}
void CMultiUser::parseGameRelayInfo(GLReqRelayInfo* relay)
{
#ifdef LOGSET
std::cerr << "RelayInfo : ROOM STATE = " << getRoomState() << "\n";
#endif
if(relay != NULL)
{
if(getRoomState() == ROOM_RUN && logicCommand != NULL)
{
logicCommand->reqRelayInfo(relay->gameid());
}
else
{
GAnsProtocol ans;
makeLeave(ans, getGameID(), GAnsGameLeave_KICK_TYPE_SYSTEM_ERROR);
sendPacket(ans);
}
}
}
void CMultiUser::parseGameEmoti(GLReqGameEmoti* emoti)
{
if(emoti != NULL)
{
//바로 보내기
GAnsProtocol matgo;
matgo.set_type(::GAnsProtocol_Type_GLANSGAMEPROTOCOL);
GLAnsGameProtocol* packet = matgo.mutable_ansgameprotocol();
packet->set_type(::GLAnsGameProtocol_Type_GAME_EMOTI);
GLAnsGameEmoti* pEmoti = packet->mutable_ansgameemoti();
pEmoti->set_gameindex(emoti->gameindex());
pEmoti->set_ntype(emoti->ntype());
sendYouPacket(matgo);
}
}
//유저의 상태값을 가져온다.
USER_STATE CMultiUser::getUserState()
{
return userState;
}
ROOM_STATE CMultiUser::getRoomState()
{
return roomState;
}
//현재 유저의 룸의 아이디를 가져온다
int CMultiUser::getRoomID()
{
return JoinInfo.roomid();
}
//유저의 usn을 가져온다.
int CMultiUser::getGameID()
{
int nResult = ERROR_VALUE;
GameUserInfo* pGame = JoinInfo.mutable_gameuserinfo();
GameInfo* pInfo = pGame->mutable_gameinfo();
nResult = pInfo->gameid();
return nResult;
}
//true 자기 , false 남
void CMultiUser::getGameUserInfo(GameUserInfo& info, bool bMe)
{
GameUserInfo* pInfo;
if(bMe)
{
pInfo = JoinInfo.mutable_gameuserinfo();
}
else
{
pInfo = YouJoinInfo.mutable_gameuserinfo();
}
info.CopyFrom(*pInfo);
}
//로직 커맨드 포인터를 가져옴
CLogicMultiCommand* CMultiUser::getLogicCommand()
{
return logicCommand;
}
//매칭된 유저의 게임 아이디
int CMultiUser::getMatchUserGameID()
{
GameUserInfo* pGame = YouJoinInfo.mutable_gameuserinfo();
GameInfo* pInfo = pGame->mutable_gameinfo();
return pInfo->gameid();
}
//유저의 상태값을 가져온다.
void CMultiUser::setUserState(USER_STATE nState)
{
userState = nState;
}
void CMultiUser::setRoomState(ROOM_STATE nState)
{
roomState = nState;
}
//유저 인덱스 셋팅
void CMultiUser::setUserIndex(int ui)
{
GameUserInfo* pGame = JoinInfo.mutable_gameuserinfo();
GameInfo* pInfo = pGame->mutable_gameinfo();
pInfo->set_gameindex(ui);
}
//유저의 게임 인덱스를 가져온다.
int CMultiUser::getGameIndex()
{
GameUserInfo* pGame = JoinInfo.mutable_gameuserinfo();
GameInfo* pInfo = pGame->mutable_gameinfo();
return pInfo->gameindex();
}
void CMultiUser::setGameIndex(int iUI)
{
GameUserInfo* pGame = JoinInfo.mutable_gameuserinfo();
GameInfo* pInfo = pGame->mutable_gameinfo();
pInfo->set_gameindex(iUI);
}
//로직 커맨드를 셋팅한다.
void CMultiUser::setLogicCommand(CLogicMultiCommand* pLogicCommand)
{
logicCommand = pLogicCommand;
if(logicCommand != NULL)
{
GameUserInfo* pGame = JoinInfo.mutable_gameuserinfo();
GameInfo* pInfo = pGame->mutable_gameinfo();
logicCommand->SetGameType(MULTI_GAME);
logicCommand->setUserAdd(getGameID(), pInfo->gameindex());
logicCommand->setRoomID(JoinInfo.roomid());
logicCommand->setPointMoney(getPointMoney(JoinInfo.categoryid()));
logicCommand->setCategoryID(JoinInfo.categoryid());
}
}
//로직 커맨드중 상대방을 셋팅한다.
void CMultiUser::setLogicUser()
{
if(logicCommand != NULL)
{
GameUserInfo* pGame = YouJoinInfo.mutable_gameuserinfo();
GameInfo* pInfo = pGame->mutable_gameinfo();
pInfo->set_gameindex(0);
logicCommand->SetGameType(MULTI_GAME);
logicCommand->setUserAdd(pInfo->gameid(), pInfo->gameindex());
logicCommand->setRoomID(YouJoinInfo.roomid());
logicCommand->setPointMoney(getPointMoney(YouJoinInfo.categoryid()));
logicCommand->setCategoryID(YouJoinInfo.categoryid());
}
}
//상대방의 게임 usn을 셋팅한다.
void CMultiUser::setMatchUserGameId(int gameId)
{
GameUserInfo* pGame = YouJoinInfo.mutable_gameuserinfo();
GameInfo* pInfo = pGame->mutable_gameinfo();
pInfo->set_gameid(gameId);
}
void CMultiUser::setMatchUser(GReqGameEnter& matchUser) //매치 유저
{
YouJoinInfo.CopyFrom(matchUser);
}
//조인룸을 보낸다.
void CMultiUser::sendJoinRoom(GAnsProtocol& matgo)
{
//조인 메시지를 만든다.
makeGameJoinRoom(matgo);
//패캣을 만든다.
makePacket(::GAnsProtocol_Type_GANSGAMEENTER, matgo);
//모둥게 보낸다.
// user_ptr pUser = mulManager->getUser(getMatchUserGameID());
//
// pUser->sendPacket(matgo);
//패킷을 상대에게 보낸다.
// sendYouPacket(matgo, YouJoinInfo.gameid());
}
//타이머 셋팅
void CMultiUser::setTimer(TIMER_TYPE nType)
{
if(logicCommand != NULL)
{
logicCommand->setTimer(nType);
}
}
//인덱스를 변경한다.
void CMultiUser::changeIndex(int index)
{
logicCommand->changeIndex(index);
}
void CMultiUser::setKickType(GAnsGameLeave_KICK_TYPE nType)
{
kickType = nType;
}
GAnsGameLeave_KICK_TYPE CMultiUser::getKickType()
{
return kickType;
}
|
a3a1fdf5123d56ff5bd1edb2fecdf8d7d72f2c8c
|
97ce80e44d5558cad2ca42758e2d6fb1805815ce
|
/Source/Foundation/bsfCore/RenderAPI/BsRenderTexture.cpp
|
e71391437e3ba1e624500d604190cd41c894b88b
|
[
"MIT"
] |
permissive
|
cwmagnus/bsf
|
ff83ca34e585b32d909b3df196b8cf31ddd625c3
|
36de1caf1f7532d497b040d302823e98e7b966a8
|
refs/heads/master
| 2020-12-08T00:53:11.021847
| 2020-03-23T22:05:24
| 2020-03-23T22:05:24
| 232,839,774
| 3
| 0
|
MIT
| 2020-01-09T15:26:22
| 2020-01-09T15:26:21
| null |
UTF-8
|
C++
| false
| false
| 11,538
|
cpp
|
BsRenderTexture.cpp
|
//************************************ bs::framework - Copyright 2018 Marko Pintera **************************************//
//*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********//
#include "RenderAPI/BsRenderTexture.h"
#include "Error/BsException.h"
#include "Image/BsTexture.h"
#include "Managers/BsTextureManager.h"
#include "Resources/BsResources.h"
#include "CoreThread/BsCoreThread.h"
#include <Private/RTTI/BsRenderTargetRTTI.h>
namespace bs
{
RenderTextureProperties::RenderTextureProperties(const RENDER_TEXTURE_DESC& desc, bool requiresFlipping)
{
UINT32 firstIdx = (UINT32)-1;
bool requiresHwGamma = false;
for (UINT32 i = 0; i < BS_MAX_MULTIPLE_RENDER_TARGETS; i++)
{
HTexture texture = desc.colorSurfaces[i].texture;
if (!texture.isLoaded())
continue;
if (firstIdx == (UINT32)-1)
firstIdx = i;
requiresHwGamma |= texture->getProperties().isHardwareGammaEnabled();
}
if (firstIdx == (UINT32)-1)
{
HTexture texture = desc.depthStencilSurface.texture;
if (texture.isLoaded())
{
const TextureProperties& texProps = texture->getProperties();
construct(&texProps, desc.depthStencilSurface.numFaces, desc.depthStencilSurface.mipLevel,
requiresFlipping, false);
}
}
else
{
HTexture texture = desc.colorSurfaces[firstIdx].texture;
const TextureProperties& texProps = texture->getProperties();
construct(&texProps, desc.colorSurfaces[firstIdx].numFaces, desc.colorSurfaces[firstIdx].mipLevel,
requiresFlipping, requiresHwGamma);
}
}
RenderTextureProperties::RenderTextureProperties(const ct::RENDER_TEXTURE_DESC& desc, bool requiresFlipping)
{
UINT32 firstIdx = (UINT32)-1;
bool requiresHwGamma = false;
for (UINT32 i = 0; i < BS_MAX_MULTIPLE_RENDER_TARGETS; i++)
{
SPtr<ct::Texture> texture = desc.colorSurfaces[i].texture;
if (texture == nullptr)
continue;
if (firstIdx == (UINT32)-1)
firstIdx = i;
requiresHwGamma |= texture->getProperties().isHardwareGammaEnabled();
}
if(firstIdx == (UINT32)-1)
{
SPtr<ct::Texture> texture = desc.depthStencilSurface.texture;
if(texture != nullptr)
{
const TextureProperties& texProps = texture->getProperties();
construct(&texProps, desc.depthStencilSurface.numFaces, desc.depthStencilSurface.mipLevel,
requiresFlipping, false);
}
}
else
{
SPtr<ct::Texture> texture = desc.colorSurfaces[firstIdx].texture;
const TextureProperties& texProps = texture->getProperties();
construct(&texProps, desc.colorSurfaces[firstIdx].numFaces, desc.colorSurfaces[firstIdx].mipLevel,
requiresFlipping, requiresHwGamma);
}
}
void RenderTextureProperties::construct(const TextureProperties* textureProps, UINT32 numSlices,
UINT32 mipLevel, bool requiresFlipping, bool hwGamma)
{
if (textureProps != nullptr)
{
PixelUtil::getSizeForMipLevel(textureProps->getWidth(), textureProps->getHeight(), textureProps->getDepth(),
mipLevel, width, height, numSlices);
numSlices *= numSlices;
multisampleCount = textureProps->getNumSamples();
}
isWindow = false;
requiresTextureFlipping = requiresFlipping;
this->hwGamma = hwGamma;
}
SPtr<RenderTexture> RenderTexture::create(const TEXTURE_DESC& desc,
bool createDepth, PixelFormat depthStencilFormat)
{
return TextureManager::instance().createRenderTexture(desc, createDepth, depthStencilFormat);
}
SPtr<RenderTexture> RenderTexture::create(const RENDER_TEXTURE_DESC& desc)
{
return TextureManager::instance().createRenderTexture(desc);
}
SPtr<ct::RenderTexture> RenderTexture::getCore() const
{
return std::static_pointer_cast<ct::RenderTexture>(mCoreSpecific);
}
RenderTexture::RenderTexture(const RENDER_TEXTURE_DESC& desc)
:mDesc(desc)
{
for (UINT32 i = 0; i < BS_MAX_MULTIPLE_RENDER_TARGETS; i++)
{
if (desc.colorSurfaces[i].texture != nullptr)
mBindableColorTex[i] = desc.colorSurfaces[i].texture;
}
if (desc.depthStencilSurface.texture != nullptr)
mBindableDepthStencilTex = desc.depthStencilSurface.texture;
}
SPtr<ct::CoreObject> RenderTexture::createCore() const
{
ct::RENDER_TEXTURE_DESC coreDesc;
for (UINT32 i = 0; i < BS_MAX_MULTIPLE_RENDER_TARGETS; i++)
{
ct::RENDER_SURFACE_DESC surfaceDesc;
if (mDesc.colorSurfaces[i].texture.isLoaded())
surfaceDesc.texture = mDesc.colorSurfaces[i].texture->getCore();
surfaceDesc.face = mDesc.colorSurfaces[i].face;
surfaceDesc.numFaces = mDesc.colorSurfaces[i].numFaces;
surfaceDesc.mipLevel = mDesc.colorSurfaces[i].mipLevel;
coreDesc.colorSurfaces[i] = surfaceDesc;
}
if (mDesc.depthStencilSurface.texture.isLoaded())
coreDesc.depthStencilSurface.texture = mDesc.depthStencilSurface.texture->getCore();
coreDesc.depthStencilSurface.face = mDesc.depthStencilSurface.face;
coreDesc.depthStencilSurface.numFaces = mDesc.depthStencilSurface.numFaces;
coreDesc.depthStencilSurface.mipLevel = mDesc.depthStencilSurface.mipLevel;
return ct::TextureManager::instance().createRenderTextureInternal(coreDesc);
}
CoreSyncData RenderTexture::syncToCore(FrameAlloc* allocator)
{
UINT32 size = sizeof(RenderTextureProperties);
UINT8* buffer = allocator->alloc(size);
RenderTextureProperties& props = const_cast<RenderTextureProperties&>(getProperties());
memcpy(buffer, (void*)&props, size);
return CoreSyncData(buffer, size);
}
const RenderTextureProperties& RenderTexture::getProperties() const
{
return static_cast<const RenderTextureProperties&>(getPropertiesInternal());
}
/************************************************************************/
/* SERIALIZATION */
/************************************************************************/
RTTITypeBase* RenderTexture::getRTTIStatic()
{
return RenderTextureRTTI::instance();
}
RTTITypeBase* RenderTexture::getRTTI() const
{
return RenderTexture::getRTTIStatic();
}
namespace ct
{
RenderTexture::RenderTexture(const RENDER_TEXTURE_DESC& desc, UINT32 deviceIdx)
:mDesc(desc)
{ }
void RenderTexture::initialize()
{
RenderTarget::initialize();
for (UINT32 i = 0; i < BS_MAX_MULTIPLE_RENDER_TARGETS; i++)
{
if (mDesc.colorSurfaces[i].texture != nullptr)
{
SPtr<Texture> texture = mDesc.colorSurfaces[i].texture;
if ((texture->getProperties().getUsage() & TU_RENDERTARGET) == 0)
BS_EXCEPT(InvalidParametersException, "Provided texture is not created with render target usage.");
mColorSurfaces[i] = texture->requestView(mDesc.colorSurfaces[i].mipLevel, 1,
mDesc.colorSurfaces[i].face, mDesc.colorSurfaces[i].numFaces, GVU_RENDERTARGET);
}
}
if (mDesc.depthStencilSurface.texture != nullptr)
{
SPtr<Texture> texture = mDesc.depthStencilSurface.texture;
if ((texture->getProperties().getUsage() & TU_DEPTHSTENCIL) == 0)
BS_EXCEPT(InvalidParametersException, "Provided texture is not created with depth stencil usage.");
mDepthStencilSurface = texture->requestView(mDesc.depthStencilSurface.mipLevel, 1,
mDesc.depthStencilSurface.face, mDesc.depthStencilSurface.numFaces, GVU_DEPTHSTENCIL);
}
throwIfBuffersDontMatch();
}
SPtr<RenderTexture> RenderTexture::create(const RENDER_TEXTURE_DESC& desc, UINT32 deviceIdx)
{
return TextureManager::instance().createRenderTexture(desc, deviceIdx);
}
void RenderTexture::syncToCore(const CoreSyncData& data)
{
RenderTextureProperties& props = const_cast<RenderTextureProperties&>(getProperties());
props = data.getData<RenderTextureProperties>();
}
const RenderTextureProperties& RenderTexture::getProperties() const
{
return static_cast<const RenderTextureProperties&>(getPropertiesInternal());
}
void RenderTexture::throwIfBuffersDontMatch() const
{
UINT32 firstSurfaceIdx = (UINT32)-1;
for (UINT32 i = 0; i < BS_MAX_MULTIPLE_RENDER_TARGETS; i++)
{
if (mColorSurfaces[i] == nullptr)
continue;
if (firstSurfaceIdx == (UINT32)-1)
{
firstSurfaceIdx = i;
continue;
}
const TextureProperties& curTexProps = mDesc.colorSurfaces[i].texture->getProperties();
const TextureProperties& firstTexProps = mDesc.colorSurfaces[firstSurfaceIdx].texture->getProperties();
UINT32 curMsCount = curTexProps.getNumSamples();
UINT32 firstMsCount = firstTexProps.getNumSamples();
UINT32 curNumSlices = mColorSurfaces[i]->getNumArraySlices();
UINT32 firstNumSlices = mColorSurfaces[firstSurfaceIdx]->getNumArraySlices();
if (curMsCount == 0)
curMsCount = 1;
if (firstMsCount == 0)
firstMsCount = 1;
if (curTexProps.getWidth() != firstTexProps.getWidth() ||
curTexProps.getHeight() != firstTexProps.getHeight() ||
curTexProps.getDepth() != firstTexProps.getDepth() ||
curMsCount != firstMsCount ||
curNumSlices != firstNumSlices)
{
String errorInfo = "\nWidth: " + toString(curTexProps.getWidth()) + "/" + toString(firstTexProps.getWidth());
errorInfo += "\nHeight: " + toString(curTexProps.getHeight()) + "/" + toString(firstTexProps.getHeight());
errorInfo += "\nDepth: " + toString(curTexProps.getDepth()) + "/" + toString(firstTexProps.getDepth());
errorInfo += "\nNum. slices: " + toString(curNumSlices) + "/" + toString(firstNumSlices);
errorInfo += "\nMultisample Count: " + toString(curMsCount) + "/" + toString(firstMsCount);
BS_EXCEPT(InvalidParametersException, "Provided color textures don't match!" + errorInfo);
}
}
if (firstSurfaceIdx != (UINT32)-1)
{
const TextureProperties& firstTexProps = mDesc.colorSurfaces[firstSurfaceIdx].texture->getProperties();
SPtr<TextureView> firstSurfaceView = mColorSurfaces[firstSurfaceIdx];
UINT32 numSlices;
if (firstTexProps.getTextureType() == TEX_TYPE_3D)
numSlices = firstTexProps.getDepth();
else
numSlices = firstTexProps.getNumFaces();
if ((firstSurfaceView->getFirstArraySlice() + firstSurfaceView->getNumArraySlices()) > numSlices)
{
BS_EXCEPT(InvalidParametersException, "Provided number of faces is out of range. Face: " +
toString(firstSurfaceView->getFirstArraySlice() + firstSurfaceView->getNumArraySlices()) + ". Max num faces: " + toString(numSlices));
}
if (firstSurfaceView->getMostDetailedMip() > firstTexProps.getNumMipmaps())
{
BS_EXCEPT(InvalidParametersException, "Provided number of mip maps is out of range. Mip level: " +
toString(firstSurfaceView->getMostDetailedMip()) + ". Max num mipmaps: " + toString(firstTexProps.getNumMipmaps()));
}
if (mDepthStencilSurface == nullptr)
return;
const TextureProperties& depthTexProps = mDesc.depthStencilSurface.texture->getProperties();
UINT32 depthMsCount = depthTexProps.getNumSamples();
UINT32 colorMsCount = firstTexProps.getNumSamples();
if (depthMsCount == 0)
depthMsCount = 1;
if (colorMsCount == 0)
colorMsCount = 1;
if (depthTexProps.getWidth() != firstTexProps.getWidth() ||
depthTexProps.getHeight() != firstTexProps.getHeight() ||
depthMsCount != colorMsCount)
{
String errorInfo = "\nWidth: " + toString(depthTexProps.getWidth()) + "/" + toString(firstTexProps.getWidth());
errorInfo += "\nHeight: " + toString(depthTexProps.getHeight()) + "/" + toString(firstTexProps.getHeight());
errorInfo += "\nMultisample Count: " + toString(depthMsCount) + "/" + toString(colorMsCount);
BS_EXCEPT(InvalidParametersException, "Provided texture and depth stencil buffer don't match!" + errorInfo);
}
}
}
}
}
|
aae9665561fa272ba2d3d8cef9fe046e62d7edc9
|
b971f7f0d90f8f7ff81a1c17ac63db5ae8dc01be
|
/Ecom008_Heap/main.cpp
|
6405064108cae7f968d41a4eed24d77cd5a61947
|
[] |
no_license
|
AndressaM/ecom008_2014_1_03
|
8369163a2ec30f104db962fefd89f34b41db14e7
|
b96af4e26aeda0a2d6106986e2fb644a376626de
|
refs/heads/master
| 2020-12-24T13:29:20.496939
| 2014-04-26T02:18:15
| 2014-04-26T02:18:15
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 105
|
cpp
|
main.cpp
|
#include <QCoreApplication>
#include <iostream>
#include"heap.h"
using namespace std;
int main()
{
}
|
eaa79153954526a39e15e212fd85ebd883427c12
|
9c1971ad1e4ba01d7177a8e63fbb67203a0a03df
|
/problems/1010/solution.cpp
|
0f0e086865595e05da3d31c75751ba958f012e45
|
[] |
no_license
|
virtyaluk/leetcode
|
cb5a7d0957be353125861b1b9d41606f4729248a
|
2a1496e5deaf45b28647e713a82b1f5b456888fa
|
refs/heads/master
| 2023-07-07T16:52:23.152194
| 2023-06-24T00:50:09
| 2023-06-24T00:50:09
| 166,505,868
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 400
|
cpp
|
solution.cpp
|
class Solution {
public:
int numPairsDivisibleBy60(vector<int>& time) {
int ans = 0;
vector<int> rem(60, 0);
for (int t: time) {
if (t % 60 == 0) {
ans += rem[0];
} else {
ans += rem[60 - t % 60];
}
rem[t % 60]++;
}
return ans;
}
};
|
397dad2c1390f59b712d95006e942b20c2f02a13
|
7ffa9013e21deaa30d44a4d3c397c834900a4c34
|
/test/main.cpp
|
c9588b8b5976c98bcf03b8d4e9276d10abfabc34
|
[] |
no_license
|
jasonhaominglo/botrix
|
26c66c16fb001f131afa9787c4036786bf941402
|
8add83bf4224ba913f55578df2ec8d0815d5324a
|
refs/heads/master
| 2023-02-27T18:05:34.643191
| 2021-02-09T21:08:41
| 2021-02-09T21:08:41
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,298
|
cpp
|
main.cpp
|
#include <stdlib.h>
#include <stdio.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <dlfcn.h>
#endif
#include "server_plugin.h"
int main(int, char **)
{
#ifdef _WIN32
HMODULE handle = LoadLibrary("..\\..\\Release\\botrix.dll");
if ( handle == NULL )
{
fprintf( stderr, "%Error reading dll.\n" );
exit(1);
}
CreateInterfaceFn pFn = (CreateInterfaceFn)GetProcAddress( handle, "CreateInterface" );
#else
void *handle = dlopen("../../../source-sdk-2013/mp/game/mod_hl2mp/addons/botrix.so", RTLD_NOW);
if ( !handle )
{
fprintf( stderr, "%s.\n", dlerror() );
exit(1);
}
CreateInterfaceFn pFn = (CreateInterfaceFn)dlsym( handle, "CreateInterface" );
#endif
if ( !pFn )
{
fprintf(stderr, "Can't load function from library.\n");
#ifdef _WIN32
FreeLibrary(handle);
#else
dlclose(handle);
#endif
exit(1);
}
int iReturn;
CBotrixPlugin* pPlugin = (CBotrixPlugin*)pFn(INTERFACEVERSION_ISERVERPLUGINCALLBACKS, &iReturn);
if ( pPlugin && pPlugin->Load(pFn, pFn) )
{
pPlugin->LevelInit("dm_underpass");
pPlugin->NetworkIDValidated("Botrix", "[U:1:87645516]");
}
#ifdef _WIN32
FreeLibrary(handle);
#else
dlclose(handle);
#endif
}
|
16748e14c5c332595d82c14361da876ebb1d9a3b
|
05dd6c56b0c3e36c3230a620ce63b9b62e93ba8e
|
/Task/06/Homework6-3.cpp
|
dabf514ebe411c50fd59d9a7579a5990455f71b0
|
[] |
no_license
|
jckling/Learn-C
|
3b37d819ff9c40c79991a07dfcbe809e380a47c2
|
56d8c8a47ccb371d627cc6ff39ca5fda66496316
|
refs/heads/master
| 2021-01-01T04:03:50.851823
| 2019-07-07T06:07:05
| 2019-07-07T06:07:05
| 97,115,103
| 3
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 609
|
cpp
|
Homework6-3.cpp
|
#include<stdio.h>
#include<math.h>
int P(int);
int Turn(int);
int main()
{
int count = 0;
int a, b;
for (a = 10; a < 1000; a++)
{
if (P(a))
{
b = Turn(a);
if (b == a)
{
printf("%d ", a);
count++;
}
}
}
printf("\n");
printf("count=%d", count);
return 0;
}
int Turn(int x)
{
int y;
if (x < 100)
y = (x % 10) * 10 + (x / 10);
else
y = ((x % 10) * 100) + ((x % 100)/10) * 10 + (x / 100);
return y;
}
int P(int x)
{
int i;
int flag;
double n;
flag = 1;
n = sqrt(x);
for (i = 2; i <= n; i++)
{
if (x % i == 0)
{
flag = 0;
break;
}
}
return flag;
}
|
5281e28b1bbb9c09c143d4fb65538c5300ef60a0
|
dcf04edb5c67acf276e3bdac8c40aa2b9502d993
|
/Common.h
|
4cd036b07133946f51cdaf77e3f5e16f363906d1
|
[] |
no_license
|
boliuyan/stocks
|
9bc6e9a862e51bdef816f2a3ff6f5578704813d7
|
a4183b0f089538a1cb5fed06aa6f34f7514ab79c
|
refs/heads/master
| 2020-08-03T02:49:59.364813
| 2019-09-29T04:40:55
| 2019-09-29T04:40:55
| 211,602,848
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,120
|
h
|
Common.h
|
#pragma once
#ifndef __COMMON_H__
#define __COMMON_H__
#include <string>
#include <map>
#include <vector>
#include <list>
#include <windows.h>
#include <fstream>
#include <sstream>
#include <thread>
#include <mutex>
#include <luabind\luabind.hpp>
#include <boost\locale.hpp>
#include <boost/math/constants/constants.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/lexical_cast.hpp>
#endif
#define LUA_CONFIG_PATH "./config.lua"
static bool Compare(float a, float b)
{
int nBefore = a;
int nLast = b;
if (nBefore > nLast)
return true;
if (nBefore < nLast)
return false;
std::string strBefore = boost::lexical_cast<std::string>(a);
std::string strLast = boost::lexical_cast<std::string>(b);
int idxNum = strBefore.find(".");
if (idxNum == -1)
return false;
int size = strBefore.size();
if (size < strLast.size())
size = strLast.size();
for (int i = idxNum; i < size; i++) {
if (strBefore.substr(i, 1) > strLast.substr(i, 1))
return true;
if (strBefore.substr(i, 1) < strLast.substr(i, 1))
return false;
}
return false;
}
|
8be5c4715fd0c6e4acc86243d7347887f34bfed3
|
c7c73566784a7896100e993606e1bd8fdd0ea94e
|
/pandatool/src/daeegg/pre_fcollada_include.h
|
59ad054c2a22fc117362fe67356e3ee2ddd112a3
|
[
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
panda3d/panda3d
|
c3f94df2206ff7cfe4a3b370777a56fb11a07926
|
160ba090a5e80068f61f34fc3d6f49dbb6ad52c5
|
refs/heads/master
| 2023-08-21T13:23:16.904756
| 2021-04-11T22:55:33
| 2023-08-06T06:09:32
| 13,212,165
| 4,417
| 1,072
|
NOASSERTION
| 2023-09-09T19:26:14
| 2013-09-30T10:20:25
|
C++
|
UTF-8
|
C++
| false
| false
| 971
|
h
|
pre_fcollada_include.h
|
/**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file pre_fcollada_include.h
* @author rdb
* @date 2008-10-04
*/
// This file defines some stuff that need to be defined before one includes
// FCollada.h
#ifndef PRE_FCOLLADA_INCLUDE_H
#define PRE_FCOLLADA_INCLUDE_H
#ifdef FCOLLADA_VERSION
#error You must include pre_fcollada_include.h before including FCollada.h!
#endif
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#endif
#include <winsock2.h>
#endif
// FCollada expects LINUX to be defined on linux
#ifdef IS_LINUX
#ifndef LINUX
#define LINUX
#endif
#endif
#define NO_LIBXML
#define FCOLLADA_NOMINMAX
// FCollada does use global min/max.
using std::min;
using std::max;
#endif
|
1a479b42f01811c0d5e5116ec2b86838958025d5
|
3739b64d28b2b162d9b91fb3bd9a216b726b4389
|
/ConT2/B26.cpp
|
2dd61aa5bd621c7e9672a0bac75ac3fa3808290f
|
[] |
no_license
|
pewdspie24/CTDL-GT
|
63c10aac5a5941f56fde08c14c0205c9778325b8
|
980fd2a2c876be6a943594f8f901399a99a786ac
|
refs/heads/master
| 2022-12-07T20:11:22.874853
| 2020-08-25T14:53:29
| 2020-08-25T14:53:29
| 290,233,375
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,083
|
cpp
|
B26.cpp
|
#include <bits/stdc++.h>
#include <string.h>
#include <string>
#define pb push_back
#define FOR(i,n) for(i = 0; i < n; i++)
#define mp make_pair
#define fi first
#define se second
using namespace std;
typedef double ld;
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef pair<int,int> II;
const ld pi=2*acos(0);
const int im = INT_MAX;
const int in = INT_MIN;
const int limit = 1e5+5;
void sol(string s, int k, string& maxx){
if(k == 0) return;
int n = s.length();
for(int i = 0; i < n-1; i++){
for(int j = i+1; j < n; j++){
if(s[i] < s[j]){
swap(s[i], s[j]);
if(s.compare(maxx) > 0) maxx = s;
sol(s,k-1,maxx);
swap(s[i],s[j]);
}
}
}
}
int main ()
{
ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL);
int T;
cin>>T;
while(T--){
int n;
string s;
cin>>n;
cin>>s;
string maxx = s;
sol(s,n,maxx);
cout<<maxx<<endl;
}
return 0;
}
//Code by QT
|
10ec272138820f13e30262c6bc0d65e39322aa20
|
6680f8d317de48876d4176d443bfd580ec7a5aef
|
/Header/misDelagateLinkToNative.h
|
e90153bf44160805c03d6dadbff65811f6c3c7fb
|
[] |
no_license
|
AlirezaMojtabavi/misInteractiveSegmentation
|
1b51b0babb0c6f9601330fafc5c15ca560d6af31
|
4630a8c614f6421042636a2adc47ed6b5d960a2b
|
refs/heads/master
| 2020-12-10T11:09:19.345393
| 2020-03-04T11:34:26
| 2020-03-04T11:34:26
| 233,574,482
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 318
|
h
|
misDelagateLinkToNative.h
|
#pragma once
#include "misEventProxy.h"
using namespace System;
#pragma make_public(misEventProxy)
public ref class misDelagateLinkToNative
{
private:
misEventProxy* m_Proxy;
public:
misDelagateLinkToNative(misEventProxy* proxy);
void CaptureEvent(System::IntPtr event);
void SetProxy(misEventProxy* val);
};
|
bff2beac7609a2ed47f6e863cab2361323f11c89
|
01d41351c1b58e1823d0f5dda243c847616a96ac
|
/utils/subset_combination.cpp
|
f1d71716261cd70592903f8e13cb33667cc4919d
|
[] |
no_license
|
DavidHerel/PAL
|
5e75541acf32b019a1aa514a54be83bd977055d9
|
6357a31a452cc115b1df878ba6c1a7b8d66d9669
|
refs/heads/main
| 2023-05-25T02:28:01.633221
| 2021-01-25T13:08:46
| 2021-01-25T13:08:46
| 303,469,523
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,585
|
cpp
|
subset_combination.cpp
|
//
// Created by Fuji on 21.01.2021.
//
#include <iostream>
/*
* We have {1,2,4,5}
* and we want to make all possible K subsets
*/
void k_subsets(int *a, int reqLen, int s, int currLen, bool *check, int l)
//print the all possible combination of given array set
{
if (currLen > reqLen)
return;
else if (currLen == reqLen) {
for (int i = 0; i < l; i++) {
if (check[i] == true) {
std::cout << a[i] << " ";
}
}
std::cout << "\n";
return;
}
if (s == l) {
return;
}
check[s] = true;
k_subsets(a, reqLen, s + 1, currLen + 1, check, l);
//recursively call k_subsets() with incremented value of ‘currLen’ and ‘s’.
check[s] = false;
k_subsets(a, reqLen, s + 1, currLen, check, l);
//recursively call k_subsets() with only incremented value of ‘s’.
}
/*
* We have {1,2,3,4,5}
* and we want to make all possible subsets
*/
void all_subsets(int arr[], int n)
{
int count = pow(2, n);
// The outer for loop will run 2^n times to print all subset .
// Here variable i will act as a binary counter
for (int i = 0; i < count; i++) {
// The inner for loop will run n times ,
// As the maximum number of elements a set can have is n
// This loop will generate a subset
for (int j = 0; j < n; j++) {
// This if condition will check if jth bit in
// binary representation of i is set or not
// if the value of (i & (1 << j)) is not 0 ,
// include arr[j] in the current subset
// otherwise exclude arr[j]
if ((i & (1 << j)) != 0)
std::cout << arr[j] << " ";
}
std::cout << "\n";
}
}
//Postupne se rozvetvuju - to same jde udelat i s cislama, akorat by tam byly vector napriklad misto stringu
void repeating_subsets(std::string alphabet, int k, int curr_len, std::string subset){
if (k == curr_len) {
std::cout<< subset<<"\n";
return;
}
for (char i : alphabet) {
std::string temp_subset = subset + i;
repeating_subsets(alphabet, k, curr_len+1, temp_subset);
}
}
/*
//this can be done on chars too
int main() {
int N = 5;
int set[] = {5,2,3,4,1};
bool *check = new bool[N];
int k = 3;
//set which we will choose from, k, 0, 0, check, N
k_subsets(set, k, 0, 0, check, N);
std::cout<< "All subsets:\n";
all_subsets(set, N);
std::string set_ch = "abcd";
repeating_subsets(set_ch, 3, 0, "");
return 0;
}
*/
|
4932b2bdf7f48fc1a7106477d65583da3aec859e
|
b7f67a86e581b4db713652ee001c04ff6b4e126c
|
/findWords.cpp
|
d825725318873cc943340427c8cc00dab867dbf1
|
[] |
no_license
|
icesongqiang/Keyboard-Row
|
1c4d9ece1fb5f8b895a3dfee073926dea30c4b1c
|
1736d6eeb480fe5c93c6e3c941f7a588ea39b867
|
refs/heads/master
| 2021-01-22T19:15:21.082631
| 2017-03-16T10:51:49
| 2017-03-16T10:51:49
| 85,184,880
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,056
|
cpp
|
findWords.cpp
|
char** findWords(char** words, int wordsSize, int* returnSize) {
if(wordsSize == 0) return NULL;
int count = 0;
int *num = (int *)malloc(wordsSize * sizeof(int) );
const char *pattern = "(^[qwertyuiop]+$)|(^[asdfghjkl]+$)|(^[zxcvbnm]+$)";
regex_t reg;
int cflags = REG_EXTENDED|REG_ICASE;
int nErrCode = 0;
if ((nErrCode = regcomp(®, pattern, cflags)) == 0){
const size_t nmatch = 1;
regmatch_t pmatch[1];
for(int i = 0; i < wordsSize; ++i){
if ((nErrCode = regexec(®, *(words + i), nmatch, pmatch, 0)) == 0){
*(num + count++) = i; // save the index of current word for output
}
}
}
regfree(®);
char **anspp = (char **)malloc(count*sizeof(char *));
for(int i = 0 ; i< count; ++i){
*(anspp + i) = (char *)malloc( strlen(*(words + *(num + i) ) ) * sizeof(char) );
strcpy( *(anspp + i), *(words + *(num + i) ) );
}
free(num);
*returnSize = count;
return anspp;
}
|
8640683cdd7fc2a4bf8d96690825e2e6e981e1cd
|
5cce15340373fe77e0bb5274da6c804bb0da2392
|
/hash_example.cpp
|
127fbba735df34afe074b8bb38315a6b7a4c7ff6
|
[] |
no_license
|
kurenaif/kyopro
|
c9927fe2d63c66c307fbff60efedc5209f3c8c03
|
a47196c2d7d576e11a23764ae92cfafbb024b59c
|
refs/heads/master
| 2020-04-05T00:57:14.224683
| 2018-12-02T11:28:34
| 2018-12-02T11:28:34
| 156,417,347
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 413
|
cpp
|
hash_example.cpp
|
struct Node {
int company;
int pos;
Node(int company, int pos) :company(company), pos(pos) {}
Node() {}
bool operator == (const Node& rhs) {
return company == rhs.company and pos == rhs.pos;
}
};
namespace std{
template<>
class hash<Node>{
public:
size_t operator () (const Node &n) const {
auto t = make_tuple(n.company, n.pos);
return std::hash<decltype(t)>()(t);
}
};
}
|
6722069d588d5e50ea28ac74cbc57028c5012dc6
|
53f58ff431d3de19a891e967f76cf260c3d6cee8
|
/GUI/Actor.cpp
|
573e9a53822b2bf6b149f814c19f02ec06b04e86
|
[] |
no_license
|
zombie-simulation-team/Zombie-Simulation
|
2c700f69f9bda97d8fd46cd24780bc717061576b
|
c7726f80f1e81165ad19f8a2ce2d53b86586683b
|
refs/heads/develop
| 2020-04-28T08:20:09.063547
| 2019-04-27T23:01:20
| 2019-04-27T23:01:20
| 175,122,507
| 2
| 0
| null | 2019-09-26T21:47:06
| 2019-03-12T02:47:39
|
C++
|
UTF-8
|
C++
| false
| false
| 3,231
|
cpp
|
Actor.cpp
|
/*
* Actor.cpp
*
* Created on: Mar 29, 2019
* Author: Alex Rivero
*/
#include "Actor.h"
Actor::Actor(
int x,
int y,
CellColor_e color,
int healthValue,
int defenseValue,
I_Random *randomGenerator)
: Cell(x,y,color,true)
{
health = healthValue;
defense = defenseValue;
this->randomGenerator = randomGenerator;
nextX = -1;
nextY = -1;
moved = false;
moveDirectionsIndex = 0;
for(int i = 0; i < MoveDirectionSize; i++)
{
moveDirections[i] = false;
}
}
Actor::~Actor()
{
}
int Actor::GetDefense()
{
return defense;
}
int Actor::GetHealth()
{
return health;
}
void Actor::ChangeDefense(int value)
{
defense += value;
if(defense > MaxDefense)
{
defense = MaxDefense;
}
else if(defense < MinDefense)
{
defense = MinDefense;
}
}
void Actor::ChangeHealth(int value)
{
health += value;
if( health > MaxHealth)
{
health = MaxHealth;
}
else if(health < MinHealth)
{
health = MinHealth;
}
}
/*
7 0 1
\ | /
6 - C - 2
/ | \
5 4 3
*/
void Actor::Move()
{
if(moveDirections[moveDirectionsIndex] == true)
{
for(int i = moveDirectionsIndex; i < MoveDirectionSize + moveDirectionsIndex; i++)
{
if(moveDirections[i % MoveDirectionSize] == false)
{
moveDirectionsIndex = i % MoveDirectionSize;
break;
}
}
int count = 0;
for(int i = 0; i < MoveDirectionSize; i++)
{
if(moveDirections[i] == true)
{
count++;
}
}
if(count == MoveDirectionSize)
{
this->ResetNextPosition();
return;
}
}
if(moveDirectionsIndex == MoveUp)
{
this->SetNextX(this->GetX());
this->SetNextY(this->GetY() - 1);
}
else if(moveDirectionsIndex == MoveRightUp)
{
this->SetNextX(this->GetX() + 1);
this->SetNextY(this->GetY() - 1);
}
else if (moveDirectionsIndex == MoveRight)
{
this->SetNextX(this->GetX() + 1);
this->SetNextY(this->GetY());
}
else if(moveDirectionsIndex == MoveRightDown)
{
this->SetNextX(this->GetX() + 1);
this->SetNextY(this->GetY() + 1);
}
else if(moveDirectionsIndex == MoveDown)
{
this->SetNextX(this->GetX());
this->SetNextY(this->GetY() + 1);
}
else if(moveDirectionsIndex == MoveLeftDown)
{
this->SetNextX(this->GetX() - 1);
this->SetNextY(this->GetY() + 1);
}
else if(moveDirectionsIndex == MoveLeft)
{
this->SetNextX(this->GetX() - 1);
this->SetNextY(this->GetY());
}
else if(moveDirectionsIndex == MoveLeftUp)
{
this->SetNextX(this->GetX() - 1);
this->SetNextY(this->GetY() - 1);
}
moveDirections[moveDirectionsIndex] = true;
}
void Actor::SetNextX(int x)
{
nextX = x;
}
void Actor::SetNextY(int y)
{
nextY = y;
}
int Actor::GetNextX()
{
return nextX;
}
int Actor::GetNextY()
{
return nextY;
}
void Actor::ResetNextPosition()
{
nextX = -1;
nextY = -1;
}
void Actor::SetNextPosition(int x, int y)
{
SetNextX(x);
SetNextY(y);
}
bool Actor::HasMoved()
{
return moved;
}
void Actor::SetMove(bool value)
{
moved = value;
}
void Actor::ChangeNextMoveIndex()
{
moveDirectionsIndex = moveDirectionsIndex % MoveDirectionSize;
}
void Actor::SetDirectionIndex(int val)
{
moveDirectionsIndex = val;
}
void Actor::ResetDirections()
{
moveDirectionsIndex = 0;
for(int i = 0; i < MoveDirectionSize; i++)
{
moveDirections[i] = false;
}
}
|
37e20c439137139bd1776d3bd058df46334ef879
|
8b156f329c0717b46428ff97989164fb31ff1673
|
/chapter4/subarray/forceMaximumSubarray.cpp
|
be2553685eb5ca240ecb57b2addc11242682d754
|
[] |
no_license
|
a-daydream/Algorithms
|
5c6ed75a795544c93c8d0fbe544763d4a5d7b101
|
1a37a37ed5a9dc085b8618203e0822fb1578acef
|
refs/heads/master
| 2022-01-08T22:57:29.165525
| 2019-05-30T08:30:56
| 2019-05-30T08:30:56
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,201
|
cpp
|
forceMaximumSubarray.cpp
|
#include<iostream>
#include<cstdlib>
#include<ctime>
struct MaximumSubarray
{
int begin;
int end;
int sum;
};
void generateArray(int a[],int size);
void printArray(int a[],int size);
MaximumSubarray forceMaximumSubarray(int a[],int size);
int main(void)
{
using namespace std;
int array[10];
int length = sizeof(array) / sizeof(array[0]);
generateArray(array,length);
printArray(array,length);
MaximumSubarray sa = forceMaximumSubarray(array,length);
cout<<"("<<sa.begin<<","<<sa.end<<")"<<":"<<sa.sum<<endl;
return 0;
}
MaximumSubarray forceMaximumSubarray(int a[],int size)
{
MaximumSubarray sa;
int sum = INT_MIN;
for(int i =0;i<size-1;i++){
for(int j =i+1;j<size;j++){
if(sum<(a[i]-a[j])){
sum = a[i]-a[j];
sa.begin = i;
sa.end = j;
sa.sum = sum;
}
}
}
return sa;
}
void generateArray(int a[],int size)
{
srand(time(NULL));
for(int i=0;i<size;i++){
a[i] = rand()%100;
}
}
void printArray(int a[],int size)
{
for(int i=0;i<size;i++){
std::cout<<a[i]<<" ";
}
std::cout<<std::endl;
}
|
cb3d4bb43eb2492f22fd087abb179ebdfa2a03a1
|
10bea6de3a5a661c7ef8745fd5993322ced929b1
|
/src/graphics/shared_gpu_objects.hpp
|
edcf5093e587abc20c0defa0b1dd53e239186949
|
[] |
no_license
|
javascript3d/csdnblog
|
6fb3f389b94ddc4523c606169f024b3899a813e1
|
3c5dd37bfd1850ed9a6738db6a65838e4ea60486
|
refs/heads/master
| 2021-07-17T12:26:12.598439
| 2017-10-20T14:06:43
| 2017-10-20T14:06:43
| 106,515,460
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,295
|
hpp
|
shared_gpu_objects.hpp
|
// SuperTuxKart - a fun racing game with go-kart
// Copyright (C) 2014-2015 SuperTuxKart-Team
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#ifndef HEADER_SHARED_GPU_OBJECTS_HPP
#define HEADER_SHARED_GPU_OBJECTS_HPP
#include "graphics/gl_headers.hpp"
#include <assert.h>
class SharedGPUObjects
{
private:
static bool m_has_been_initialised;
static GLuint m_billboard_vbo;
static GLuint m_sky_tri_vbo;
static GLuint m_frustrum_vbo;
static GLuint m_frustrum_indices;
static GLuint m_particle_quad_vbo;
static GLuint m_View_projection_matrices_ubo;
static GLuint m_lighting_data_ubo;
static GLuint m_full_screen_quad_vao;
static GLuint m_ui_vao;
static GLuint m_quad_buffer;
static GLuint m_quad_vbo;
static void initQuadVBO();
static void initQuadBuffer();
static void initBillboardVBO();
static void initSkyTriVBO();
static void initFrustrumVBO();
static void initShadowVPMUBO();
static void initLightingDataUBO();
static void initParticleQuadVBO();
public:
static void init();
static void reset();
// ------------------------------------------------------------------------
static GLuint getBillboardVBO()
{
assert(m_has_been_initialised);
return m_billboard_vbo;
} // getBillboardVBO
// ------------------------------------------------------------------------
static GLuint getSkyTriVBO()
{
assert(m_has_been_initialised);
return m_sky_tri_vbo;
} // getSkyTriVBO
// ------------------------------------------------------------------------
static GLuint getFrustrumVBO()
{
assert(m_has_been_initialised);
return m_frustrum_vbo;
} // getFrustrumVBO
// ------------------------------------------------------------------------
static GLuint getFrustrumIndices()
{
assert(m_has_been_initialised);
return m_frustrum_indices;
} // getFrustrumIndices
// ------------------------------------------------------------------------
static GLuint getParticleQuadVBO()
{
assert(m_has_been_initialised);
return m_particle_quad_vbo;
} // getParticleQuadVBO
// ------------------------------------------------------------------------
static GLuint getViewProjectionMatricesUBO()
{
assert(m_has_been_initialised);
return m_View_projection_matrices_ubo;
} // getViewProjectionMatricesUBO
// ------------------------------------------------------------------------
static GLuint getLightingDataUBO()
{
assert(m_has_been_initialised);
return m_lighting_data_ubo;
} // getLightingDataUBO
// -------------- ----------------------------------------------------------
static GLuint getFullScreenQuadVAO()
{
assert(m_has_been_initialised);
return m_full_screen_quad_vao;
} // getFullScreenQuadVAO
// ------------------------------------------------------------------------
static GLuint getUI_VAO()
{
assert(m_has_been_initialised);
return m_ui_vao;
} // getUI_VAO
// ------------------------------------------------------------------------
static GLuint getQuadBuffer()
{
assert(m_has_been_initialised);
return m_quad_buffer;
} // getQuadBuffer
// ------------------------------------------------------------------------
static GLuint getQuadVBO()
{
assert(m_has_been_initialised);
return m_quad_vbo;
} // getQuadVBO
}; // class SharedGPUObjecctS
#endif
|
dc5df666c476bcaff3aa91fd22dcd0d3b4df0753
|
0283fa6b8fea10496a501ab602879658fa6192ce
|
/Lab2/Lab2/lab2.cpp
|
eb143f06def576342de5054dc500584c52c08a6a
|
[] |
no_license
|
pengsongyou/Cpp_Experiment
|
9da1800ee2cf930aab77cb6d32f4da0bb8adf03d
|
93d672fcd6b4e1e9fc5a6712957afdc1e2d6ef98
|
refs/heads/master
| 2021-01-10T05:28:01.600328
| 2015-12-10T21:15:38
| 2015-12-10T21:15:38
| 45,755,987
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,175
|
cpp
|
lab2.cpp
|
//
// lab2.cpp
// Lab2
//
// Created by Songyou Peng on 08/11/15.
// Copyright © 2015 Songyou Peng. All rights reserved.
//
#include <iostream>
#include <cmath>
#include "lab2.h"
void swap1(int x, int y)
{
int tmp;
tmp = x;
x = y;
y = tmp;
}
void swap2(int &x, int &y)
{
int tmp;
tmp = x;
x = y;
y = tmp;
}
void swap3(int *x, int *y)
{
int tmp;
tmp = *x;
*x = *y;
*y = tmp;
}
double* CartesianToPolar(double a, double b)
{
double *coef_fun = new double [2];
*coef_fun = sqrt(a * a + b * b);
*(coef_fun + 1) = atan2(b, a);
return coef_fun;
}
bool IsMultipleOf (int a, int b)
{
return a % b != 0 ? 0 : 1;
// if (a % b != 0)
// return false;
// else
// return true;
}
int** Pascal(int** tab, int x)
{
for (int i = 0; i < x; ++i)
{
*(*(tab + i)) = 1;//Initialize the first COLUMN!
if(i >= 1)
*(*(tab) + i) = 0; //Initialize the first ROW!
}
for (int i = 1; i < x; ++i)
for(int j = 1; j < x; ++j)
{
*(*(tab + i) + j) = *(*(tab + i - 1) + j) + *(*(tab + i - 1) + j - 1);
}
return tab;
}
|
f723b0a836d7eae076dfeada3fcfb3ed83d6360b
|
e41c5bba70d489304cc1bc5fa144c1e427955356
|
/Programming Fundamentals/NEW (3).CPP
|
21a5704db9a7218b86abb5b360260099be462136
|
[] |
no_license
|
DEEZZU/College-Backup
|
65ece21001f6978d4c40784bb348a47cdb16d5ed
|
b7f1525d929e5a342d001abfe107a7d965c90662
|
refs/heads/master
| 2021-04-29T00:40:48.280889
| 2019-01-17T18:11:13
| 2019-01-17T18:11:13
| 121,835,608
| 0
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,696
|
cpp
|
NEW (3).CPP
|
//MATRIX OPERATIONS
#include<iostream>
using namespace std;
void input(int arr[][5],int r,int c)
{
int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
cout<<"\n Enter mat["<<i+1<<"]["<<j+1<<"]=";
cin>>arr[i][j];
}
}
}
void disp(int arr[][5],int r,int c)
{
int i,j;
for(i=0;i<r;i++)
{
cout<<endl;
for(j=0;j<c;j++)
{
cout<<" "<<arr[i][j];
}
}
}
void add(int arr[][5],int ar2[][5],int res[][5],int r,int c)
{
int i,j;
res[5][5];
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
res[i][j]=arr[i][j]+ar2[i][j];
}
}
}
void sub(int arr[][5],int ar2[][5],int res_s[][5],int r,int c)
{
int i,j;
res_s[5][5];
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
res_s[i][j]=arr[i][j]-ar2[i][j];
}
}
}
void mult(int arr[][5],int const r1,int c1,int ar2[][5],int r2,int const c2,int pro[][5])
{
int i,j,k;
pro[r1][c2];
if(c1==r2)
{
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
pro[i][j]=0;
for(k=0;k<c1;k++)
pro[i][j]+=arr[i][k]*ar2[k][j];
}
}
}
else
cout<<"\n Entered matrices cannot be multiplied in the order requested";
}
void tran(int arr[][5],int r,int c)
{
int i,j,temp;
if(r==c || r>c)
{
for(i=0;i<r;i++)
for(j=0;j<=i;j++)
{
temp=arr[i][j];
arr[i][j]=arr[j][i];
arr[j][i]=temp;
}
}
else
{
for(i=0;i<c;i++)
for(j=0;j<=i;j++)
{
temp=arr[i][j];
arr[i][j]=arr[j][i];
arr[j][i]=temp;
}
}
}
void main()
{
int ch,a[5][5],ra,ca,b[5][5],rb,cb,ad[5][5],sb[5][5],pro[5][5];
char op;
do
{
cout<<"\n Menu";
cout<<"\n 1. INPUT";
cout<<"\n 2. ADD TWO MATRIX";
cout<<"\n 3. SUBTRACT MATRICES";
cout<<"\n 4. MULTIPLY THE TWO MATRICES";
cout<<"\n 5. TRANSPOSE OF THE MATRIX";
cout<<"\n 6. DISPLAY";
cout<<"\n Enter your choice";
cin>>ch;
switch(ch)
{
case 1: cout<<"\n Inputting matrices";
cout<<"\n Which matrix do you want to input";
cout<<"\n 1. MAT A";
cout<<"\n 2. MAT B";
cout<<"\n Enter choice=";
cin>>ch;
if(ch==1)
{
cout<<"\n Enter rows=";
cin>>ra;
cout<<"\n Enter columns";
cin>>ca;
input(a,ra,ca);
}
else if(ch==2)
{
cout<<"\n Enter rows=";
cin>>rb;
cout<<"\n Enter columns";
cin>>cb;
input(b,rb,cb);
}
else
cout<<"\n Wrong choice";
break;
case 2:cout<<"\n Adding the two matrices";
if(ra==rb && ca==cb)
{
add(a,b,ad,ra,ca);
disp(ad,ra,ca);
}
else
cout<<"\n Entered matrices can not be added";
break;
case 3:cout<<"\n Subtracting one matrix from the other";
if(ra==rb && ca==cb)
{
cout<<"\n Which matrix result do you want";
cout<<"\n 1. A-B";
cout<<"\n 2. B-A";
cin>>ch;
if (ch==1)
{
sub(a,b,sb,ra,ca);
disp(sb,ra,ca);
}
else if(ch==2)
{
sub(b,a,sb,ra,ca);
disp(sb,ra,ca);
}
else
cout<<"\n Wrong choice";
}
else
cout<<"\n Subtraction not possible";
break;
case 4: cout<<"\n Multiply the two matrices";
cout<<"\n Which product do you want to see";
cout<<"\n 1. A*B";
cout<<"\n 2. B*A";
cout<<"\n Enter choice=";
cin>>ch;
if(ch==1)
{
mult(a,ra,ca,b,rb,cb,pro);
disp(pro,ra,cb);
}
else if(ch==2)
{
mult(b,rb,cb,a,ra,ca,pro);
disp(pro,rb,ca);
}
else
cout<<"\n Wrong choice";
break;
case 5:cout<<"\n Transpose of the matrix";
cout<<"\n Choices";
cout<<"\n 1. A";
cout<<"\n 2. B";
cout<<"\n Enter choice=";
cin>>ch;
if(ch==1)
{
tran(a,ra,ca);
ra+=ca;
ca=ra-ca;
ra=ra-ca;
disp(a,ra,ca);
}
else if(ch==2)
{
tran(b,rb,cb);
rb+=cb;
cb=rb-cb;
rb=rb-cb;
disp(b,rb,cb);
}
else
cout<<"\n Wrong choice";
break;
case 6:cout<<"\n Display";
cout<<"\n 1. A";
cout<<"\n 2. B";
cout<<"\n choice";
cin>>ch;
if(ch==1)
{
disp(a,ra,ca);
}
else if(ch==2)
{
disp(b,rb,cb);
}
else
cout<<"\n Wrong choice";
break;
default:cout<<"\n Wrong choice";
}
cout<<"\n Do you want to continue";
cin>>op;
}
while(op=='y' || op=='Y');
}
|
b19a1f7e9f5cb243dc3ac7646a50254fd16c6d47
|
364e5cd1ce6948183e6ebb38bd8f555511b54495
|
/DesignPattern/Bridge/BridgeMessage/include/MessageEmail.h
|
d45615f07ea1d4ca0b8a3f94edc91265bfa2a5eb
|
[] |
no_license
|
danelumax/CPP_study
|
c38e37f0d2cebe4adccc65ad1064aa338913f044
|
22124f8d83d59e5b351f16983d638a821197b7ae
|
refs/heads/master
| 2021-01-22T21:41:11.867311
| 2017-03-19T09:01:11
| 2017-03-19T09:01:11
| 85,462,945
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 378
|
h
|
MessageEmail.h
|
/*
* MessageEmail.h
*
* Created on: Oct 2, 2016
* Author: eliwech
*/
#ifndef MESSAGEEMAIL_H_
#define MESSAGEEMAIL_H_
#include "MessageImplementor.h"
class MessageEmail : public MessageImplementor
{
public:
MessageEmail();
virtual ~MessageEmail();
virtual void send(std::string message, std::string toUser);
};
#endif /* MESSAGEEMAIL_H_ */
|
4a0af6b363c64ce24a433ebe38993800098f2fb0
|
bf8cd5a46d0a72d59d72b6e538e52464a290c33f
|
/log/supportinfoopendialog.h
|
82f4e28041847babac76354adb915db19c0073e6
|
[] |
no_license
|
bkbme/CALLogViewer
|
267f9dc69fd5ec13e2203756a8391bc825190b46
|
ef403c8fd9c0696db50c7c28a05d402ea648581c
|
refs/heads/master
| 2016-09-01T22:38:35.690661
| 2014-03-02T18:26:23
| 2014-03-02T18:26:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 879
|
h
|
supportinfoopendialog.h
|
#ifndef SUPPORTINFOOPENDIALOG_H
#define SUPPORTINFOOPENDIALOG_H
#include <QUrl>
#include <QDialog>
#include <QString>
#include <QStringList>
class SysLogParser;
class QItemSelection;
namespace Ui {
class SupportInfoOpenDialog;
}
class SupportInfoOpenDialog : public QDialog
{
Q_OBJECT
public:
explicit SupportInfoOpenDialog(SysLogParser *parser, const QUrl &url, QWidget *parent = 0);
~SupportInfoOpenDialog();
QStringList selectedLogfiles() const;
QString selectedSupportInfoFile() const;
public slots:
void loadSyslogFileList(const QString& supportInfoFileName);
private slots:
void on_pbBrowse_clicked();
void onReadyReadFileList();
void onFileListFinished();
void onSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected);
private:
Ui::SupportInfoOpenDialog *ui;
SysLogParser *m_parser;
};
#endif // SUPPORTINFOOPENDIALOG_H
|
9ee1d52fe80e2bcf312d4ff128fa98934bb1a4bc
|
5ac4267cf866d897e1e6446ebbc71143b10a77ef
|
/ExcelAutomationLib/include/ExcelWorkbook.h
|
12b086c0442d68a32a05f373212ef6315e04cc34
|
[] |
no_license
|
yongce/excel-automation-lib
|
404782b867b287477e96a7ef2a391dcb06210164
|
c79711a6623aa43e6d64ad9e9de87c3854cbdba5
|
refs/heads/master
| 2021-01-01T16:35:00.472266
| 2010-10-04T14:09:29
| 2010-10-04T14:09:29
| 32,120,791
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,922
|
h
|
ExcelWorkbook.h
|
/*!
* @file ExcelWorkbook.h
* @brief Header file for class ExcelWorkbook
* @date 2009-12-01
* @author Tu Yongce <tuyongce@gmail.com>
* @version $Id$
*/
#ifndef EXCELWORKBOOK_H_GUID_FFB67A8F_9104_4F1F_B552_B9EF17C5DD4E
#define EXCELWORKBOOK_H_GUID_FFB67A8F_9104_4F1F_B552_B9EF17C5DD4E
#include "LibDef.h"
#include "HandleBody.h"
#include "StringUtil.h"
// <begin> namespace
EXCEL_AUTOMATION_NAMESPACE_START
// Forward declaration
class ExcelWorksheet;
class ExcelWorksheetSet;
/*!
* @brief Class ExcelWorkbook represents the concept "Workbook" in Excel.
* @note ExcelWorkbook/ExcelWorkbookImpl is an implementation of the "Handle/Body" pattern.
*/
class EXCEL_AUTOMATION_DLL_API ExcelWorkbook : public HandleBase
{
public:
/*!
* Default constructor
*/ // Doc is needed by Doxygen
ExcelWorkbook(): HandleBase(0) { }
ExcelWorksheet GetActiveWorksheet() const;
ExcelWorksheetSet GetAllWorksheets() const;
/*!
* @brief Add a new worksheet after the active worksheet
* @param [in] name Name of the new added worksheet. If empty, the default name given by Excel will not be changed.
* @return An ExcelWorksheet object for the new added worksheet.
*/
ExcelWorksheet AddWorksheet(const ELstring &name = ELstring());
bool Save() const;
bool SaveAs(const ELstring &filename);
bool Close() const;
private:
friend class ExcelWorkbookSetImpl; // which will call the following ctor
ExcelWorkbook(IDispatch *pWorkbook);
private:
// <begin> Handle/Body pattern implementation
friend class ExcelWorkbookImpl;
ExcelWorkbook(ExcelWorkbookImpl *impl);
ExcelWorkbookImpl& Body() const;
// <end> Handle/Body pattern implementation
};
// <end> namespace
EXCEL_AUTOMATION_NAMESPACE_END
#endif //EXCELWORKBOOK_H_GUID_FFB67A8F_9104_4F1F_B552_B9EF17C5DD4E
|
fd4f21631caaa9daeac1c4ff495c280d07c89127
|
cb29307c79502a1687ff87aeb40f97a52168fea8
|
/src/dolfin_fvm/include/fvm_3d.hh
|
6f8d56741d459706fd4fed2d405e3c30ba81c012
|
[
"MIT"
] |
permissive
|
cwaluga/conservative_dolfin
|
dc72574604b5a63cae7543f2b84a07a5a313684f
|
c3d9324958a400d7bab43f21b9d462ff64d66d19
|
refs/heads/master
| 2021-01-19T14:12:41.045029
| 2015-06-14T10:56:17
| 2015-06-14T10:56:17
| 27,667,411
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,544
|
hh
|
fvm_3d.hh
|
#include <boost/shared_ptr.hpp>
#include <dolfin/fem/fem_utils.h>
#include <dolfin/mesh/Vertex.h>
#include <dolfin/fem/GenericDofMap.h>
#include <ufc_geometry.h>
namespace dolfin
{
void advance(GenericVector& s, // new coefficients
GenericVector const& s0, // old coefficients
FunctionSpace const& S, // function space
GenericFunction const& u, // velocity
double dt) // time-step size
{
// todo: this can be made more efficient if u is not projected beforehand,
// but if u and p are both passed and the fluxes are corrected here.
using namespace std;
Mesh const& mesh = *S.mesh();
vector<la_index> v2d = vertex_to_dof_map(S);
int d = mesh.topology().dim();
std::vector<double> const& coord = mesh.coordinates();
double J[9], K[9], det, coords[12], u_ij[3], x_ij[3], An[3];
// iterate over all vertices
for(VertexIterator vi(mesh); !vi.end(); ++vi)
{
size_t ii = vi->index();
double si = s0[v2d[ii]], dsi = 0.0, vol = 0.0;
// iterate over all cells adjacent to this vertex
for(CellIterator c(*vi); !c.end(); ++c)
{
unsigned const* ce = c->entities(0);
// find index of vertex in cell
unsigned v0 = 0;
while(v0 != d + 1)
if(ce[v0] == ii) break; else ++v0;
// reordering, such that vertex 0 is current one
int const tet_0 = v0, tet_1 = (v0+1)%4, tet_2 = (v0+2)%4, tet_3 = (v0+3)%4;
// get coordinates
coords[ 0] = coord[ce[tet_0]*d];
coords[ 1] = coord[ce[tet_0]*d+1];
coords[ 2] = coord[ce[tet_0]*d+2];
coords[ 3] = coord[ce[tet_1]*d];
coords[ 4] = coord[ce[tet_1]*d+1];
coords[ 5] = coord[ce[tet_1]*d+2];
coords[ 6] = coord[ce[tet_2]*d];
coords[ 7] = coord[ce[tet_2]*d+1];
coords[ 8] = coord[ce[tet_2]*d+2];
coords[ 9] = coord[ce[tet_3]*d];
coords[10] = coord[ce[tet_3]*d+1];
coords[11] = coord[ce[tet_3]*d+2];
compute_jacobian_tetrahedron_3d(J, coords);
compute_jacobian_inverse_tetrahedron_3d(K, det, J);
ufc::cell ufc_cell;
c->get_cell_topology(ufc_cell);
// assemble the equations for the convective operator
double sign = copysign(1./24, det);
vol += sign*det;
// precompute some weights
double const w1 = 17.0/48.0, w2 = 7.0/48.0;
// assemble fluxes for facet associated with edge(tet_0,tet_1)
x_ij[0] = w1*coords[0] + w1*coords[3] + w2*coords[6] + w2*coords[ 9];
x_ij[1] = w1*coords[1] + w1*coords[4] + w2*coords[7] + w2*coords[10];
x_ij[2] = w1*coords[2] + w1*coords[5] + w2*coords[8] + w2*coords[11];
u.evaluate(u_ij, x_ij, ufc_cell);
An[0] = J[3]*J[7] - J[3]*J[8] - J[4]*J[6] + 2*J[4]*J[8] + J[5]*J[6] - 2*J[5]*J[7];
An[1] = J[0]*J[8] - J[0]*J[7] + J[1]*J[6] - 2*J[1]*J[8] - J[2]*J[6] + 2*J[2]*J[7];
An[2] = J[0]*J[4] - J[0]*J[5] - J[1]*J[3] + 2*J[1]*J[5] + J[2]*J[3] - 2*J[2]*J[4];
double area_un = sign*(An[0]*u_ij[0] + An[1]*u_ij[1] + An[2]*u_ij[2]);
double abs_area_un = std::abs(area_un);
dsi += 0.5*(area_un+abs_area_un) * s0[v2d[ce[tet_0]]];
dsi += 0.5*(area_un-abs_area_un) * s0[v2d[ce[tet_1]]];;
// assemble fluxes for facet associated with edge(tet_0,tet_2)
x_ij[0] = w1*coords[0] + w2*coords[3] + w1*coords[6] + w2*coords[ 9];
x_ij[1] = w1*coords[1] + w2*coords[4] + w1*coords[7] + w2*coords[10];
x_ij[2] = w1*coords[2] + w2*coords[5] + w1*coords[8] + w2*coords[11];
u.evaluate(u_ij, x_ij, ufc_cell);
An[0] = J[3]*J[7] - 2*J[3]*J[8] - J[4]*J[6] + J[4]*J[8] + 2*J[5]*J[6] - J[5]*J[7];
An[1] = J[1]*J[6] + 2*J[0]*J[8] - J[0]*J[7] - J[1]*J[8] - 2*J[2]*J[6] + J[2]*J[7];
An[2] = J[0]*J[4] - 2*J[0]*J[5] - J[1]*J[3] + J[1]*J[5] + 2*J[2]*J[3] - J[2]*J[4];
area_un = sign*(An[0]*u_ij[0] + An[1]*u_ij[1] + An[2]*u_ij[2]);
abs_area_un = std::abs(area_un);
dsi += 0.5*(area_un+abs_area_un) * s0[v2d[ce[tet_0]]];
dsi += 0.5*(area_un-abs_area_un) * s0[v2d[ce[tet_2]]];;
// assemble fluxes for facet associated with edge(tet_0,tet_3)
x_ij[0] = w1*coords[0] + w2*coords[3] + w2*coords[6] + w1*coords[ 9];
x_ij[1] = w1*coords[1] + w2*coords[4] + w2*coords[7] + w1*coords[10];
x_ij[2] = w1*coords[2] + w2*coords[5] + w2*coords[8] + w1*coords[11];
u.evaluate(u_ij, x_ij, ufc_cell);
An[0] = 2*J[3]*J[7] - J[3]*J[8] - 2*J[4]*J[6] + J[4]*J[8] + J[5]*J[6] - J[5]*J[7];
An[1] = 2*J[1]*J[6] + J[0]*J[8] - 2*J[0]*J[7] - J[1]*J[8] - J[2]*J[6] + J[2]*J[7];
An[2] = 2*J[0]*J[4] - J[0]*J[5] - 2*J[1]*J[3] + J[1]*J[5] + J[2]*J[3] - J[2]*J[4];
area_un = sign*(An[0]*u_ij[0] + An[1]*u_ij[1] + An[2]*u_ij[2]);
abs_area_un = std::abs(area_un);
dsi += 0.5*(area_un+abs_area_un) * s0[v2d[ce[tet_0]]];
dsi += 0.5*(area_un-abs_area_un) * s0[v2d[ce[tet_3]]];;
}
// update the value
s.setitem(v2d[ii], si - dt/vol*dsi);
}
}
}
|
14523b009f8d2ed8a22007811c79e0ff083b43c6
|
9360b382c8745b1d5f5c768eb8f52fd34fb1b554
|
/gltest/gltest/Window/View.cpp
|
8bd90ffda53683b7e5a9ae0cd5a9226bf88a8070
|
[] |
no_license
|
pchenik/pchenik-physical_simulation
|
5346794bc73f29711374b7ec0fffe6516c893c2b
|
fad7343544c465d05e8ca7fa38cc9c0205734b21
|
refs/heads/master
| 2023-05-25T20:25:50.169718
| 2021-06-08T18:43:02
| 2021-06-08T18:43:02
| 375,110,629
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 14,104
|
cpp
|
View.cpp
|
#include "View.h" // Очередная отработка элементарных графических примитивов
// ©2018-08-22 Иерусалим.
const char
*_Mnt[]= {"январь","февраль","март","апрель","май","июнь","июль","август","сентябрь","октябрь","ноябрь","декабрь"},
*_Day[]= {"понедельник","вторник","среда","четверг","пятница","суббота","воскресенье"};
static byte SeaColor[black+257][4]=// переопределение расцветки для палитры-256
{
// white silver lightgray gray darkgray
{255,255,255},{192,192,192},{159,159,159},{ 96, 96, 96},{ 63, 63, 63},
// green yellow lime olive lightgreen
{ 0,128,0},{255,255,0},{ 0,255,0},{159,255, 63},{ 63,255,96 },
// navy blue lightblue cyan aqua lightcyan
{ 0,0,127},{ 0,0,255},{ 63,96,255},{ 0,159,159},{ 0,255,255},{ 96,212,212},
// maroon red lightred orange pink
{128, 0, 0},{255, 0, 0},{255, 96, 96},{255,128, 0},{255,192,203},
// purple magenta fuchsia lightmagenta black = 25\{26}
{128, 0,128},{191, 0,191},{255, 0,255},{255, 95,255},{ 0,0,0 }
};
void color( colors clr )
{
glColor4ubv( (GLubyte*)(SeaColor[clr]) );
}
#define B(c) ((b<0?(c*(1+b)):(c+(255-c)*b))/255.0) //...с затенением\подсветкой
void color( colors clr,_Real b,_Real a ) // bright: -1 на черный; +1 до белого
{
byte *C=SeaColor[clr]; // alfa:0-1
glColor4d(B(C[0]),B(C[1]),B(C[2]),a );
}
#undef B
void point( const Real* a )
{
glVertex3dv( a );
}
// тонкая линия из точки (a) в точку (b) ... в однородных координатах OpenGL
//
void point( const Real* a, colors clr )
{
if( clr!=empty )color(clr); //осторожно
glVertex3dv(a);
}
void points( const Real* a, Real Size, colors color )
{
glPointSize( Size );
glBegin( GL_POINTS );
point( a,color );
glEnd();
glPointSize( 1.0 );
}
void line( const Real* a, const Real* b )
{ glBegin( GL_LINES ),glVertex3dv( a ),glVertex3dv( b ),glEnd(); }
void line( const Real* a, const Real* b, colors clr )
{
if( clr!=empty )
color( clr );
line( a,b );
}
void lines( const Real* a, const Real* b, colors clr )
{
if( clr!=empty )color( clr );
glBegin( GL_LINES );
glVertex3dv( a );
glVertex3dv( b );
glVertex3d( a[0],-a[1],a[2] );
glVertex3d( b[0],-b[1],b[2] );
glEnd();
}
void circle( const Real *a, _Real r, bool fill )
{
glBegin( fill?GL_POLYGON:GL_LINE_LOOP );
for( Real a=0; a<_Pd; a+=_Ph/8 )
glVertex3dv( (Vector){ r*sin( a ),r*cos( a ),0.0 } );
glEnd();
}
// ... из точки (a) в точку (b) с объемной стрелкой в долях длины
//
void arrow( const Real *_a,const Real *_b,_Real l, colors clr )
{
Point &a=*(Point*)_a,&b=*(Point*)_b;
Vector d=a-b;
d*=l/abs( d );
Vector e= { d.z,d.x,d.y };
e/=5.0;
Vector f= { e.z,e.x,e.y };
if( clr!=empty )color( clr );
line( a,b+d );
glBegin( GL_LINE_LOOP );
point( b+d/2.0 ),point( b+d+e ),point( b ),point( b+d-e );
point( b+d/2.0 ),point( b+d+f ),point( b ),point( b+d-f );
point( b+d/2.0 );
glEnd();
}
void arrow_point(const Point &a,const Point &b, _Real l, colors clr )
{
//Point &a=*(Point*)_a,&b=*(Point*)_b;
Vector d=a-b;
d*=l/abs( d );
Vector e= { d.z,d.x,d.y };
e/=5.0;
Vector f= { e.z,e.x,e.y };
if( clr!=empty )
color( clr );
const Real *_a = (const Real *)&a;
const Real *_b = (const Real *)&b;
line( _a,b+d);
glBegin( GL_LINE_LOOP );
point( b+d/2.0 ),point( b+d+e ),point( _b ),point( b+d-e );
point( b+d/2.0 ),point( b+d+f ),point( _b ),point( b+d-f );
point( b+d/2.0 );
glEnd();
}
void axis ( _Real L,_Real Y,_Real Z, const char *x,const char *y,const char *z,colors clr )
{
const Real l=Real( L )/132;
arrow( (Point){0,0,-Z},(Point){0,0,Z},l,clr ),
arrow( (Point){0,-Y,0},(Point){0,Y,0},l, colors::empty ),
arrow( (Point){-L,0,0},(Point){L,0,0},l, colors::empty );
color( clr,-0.5 );
// P.Text(_North,0,0,Z,z ),
// P.Text(_North,0,Y+l,0,y ),
// P.Text(_North_East,L+l,0,0,x);
}
//void axis ( Place &P,_Real L,_Real Y,_Real Z, const char *x,const char *y,const char *z,colors clr )
//{
// const Real l=Real( L )/132;
// arrow( (Point)
// {
// 0,0,-Z
// },(Point)
// {
// 0,0,Z
// },l,clr ),
// arrow( (Point)
// {
// 0,-Y,0
// },(Point)
// {
// 0,Y,0
// },l ),
// arrow( (Point)
// {
// -L,0,0
// },(Point)
// {
// L,0,0
// },l );
// color( clr,-0.5 );
// P.Text(_North,0,0,Z,z ),
// P.Text(_North,0,Y+l,0,y ),
// P.Text(_North_East,L+l,0,0,x);
//}
//View::View( const char* Title, int X,int Y, int W,int H, _Real Size )
// : Window( Title,X,Y,W,H ),
// eye( (Vector){ -130,-10,0 } ),look( (Vector){ 0,0,30 } ),
// Distance( Size?-Size:-0.8*Width ),// расстояние от камеры до места съёмки
// mx( 0 ),my( 0 ) // указатель ставится в нулевое положение
//{ Activate(); View_initial();
//}
//Place& View::Draw(){ Activate(); // с исключением двойной перенастройки
// glMatrixMode( GL_PROJECTION ); // размерах фрагмента экрана сброс текущих
// glLoadIdentity(); // матричных координат, настройка обзора и
// gluPerspective( 16.2,Real( Width )/Height,-1,1 ); // экранных пропорций
// gluLookAt( 0,0,Distance,look.x,look.y,look.z,0,1,0 ); // местоположение сцены
// glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); // в исходное положение
// glRotated( eye.y-90,1,0,0 ); // поставить на киль
// glRotated( eye.z, 0,1,0 ); // дифферент
// glRotated( eye.x, 0,0,1 ); // рыскание
// return Place::Draw();
//}
//// Небольшой блок реагирования на мышиную возню в текущем окне
////
//Place& View::Mouse( int button, int x,int y ) // и её же указания к исполнению
// { bool ret=false; // Activate();
// if( button==_MouseWheel ) // на вращение колёсико / сенсора
// { if( ret=(y!=0) ){ Distance += y*Distance/Height/3;
// // look.x += x*Distance/Width; mx-=x;
// } } else
// if( ret=(x!=mx || y!=my) ) // местоположение курсора в локальных смещениях
// { switch( button ) // -- и не пустой вызов без свободной реакции
// { case _MouseLeft: //
// if( ScanStatus()&CTRL ) //
// eye.z+=Real( x-mx )/24,Distance-=( y-my )*Distance/Height; else
// eye.y-=Real( y-my )/24,eye.x+=Real( x-mx )/16; break;
// case _MouseRight: look.x-=( x-mx )*Distance/Width, // смещение
// look.y-=( y-my )*Distance/Width; break;
//// case _MouseMiddle: y-=my;
// } my=y,mx=x;
// } if( ret )Draw();
// return Place::Mouse( button,x,y ); //.Show().Save().Refresh()
// }
//bool View::KeyBoard( byte key ) // к спуску из внешних виртуальных транзакций
//{ static Real Di=0.0; if( !Di )Di=Distance;// запоминается из первого обращения
// Real Ds=6*Distance/Width;
// switch( key )
// { case _Left: if( ScanStatus()&SHIFT )look.x+=Ds; else
// if( ScanStatus()&CTRL )eye.z--; else eye.x--; break;
// case _Right:if( ScanStatus()&SHIFT )look.x-=Ds; else
// if( ScanStatus()&CTRL )eye.z++; else eye.x++; break;
// case _Up: if( ScanStatus()&CTRL )Distance*=1.1; else
// if( ScanStatus()&SHIFT )look.y+=Ds; else eye.y++; break;
// case _Down: if( ScanStatus()&CTRL )Distance/=1.1; else
// if( ScanStatus()&SHIFT )look.y-=Ds; else eye.y--; break;
// case _Home: Distance=Di, // ... от точки взгляда до места обзора
// eye=(Vector){ -120,-20,0 },look=(Vector){ -8,-4,30 }; break;
// default: return Window::KeyBoard(key);// передача в цикл ожидания клавиатуры
// } Draw(); return true; // либо - запрос от клавиатуры погашен
//}
//
// Настройка начальной раскраски и освещенности графического пространства/сцены
// ... здесь необходима предварительная установка контекста OpenGL
void View_initial()
{
glClearColor( 0.9,0.95,0.99,1 ); // светлый цвет экранного фона и затем
glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT ); // полная расчистка окна
// glFrontFace( GL_CW ); // CCW видимы грани с обходом по часовой стрелке
// glCullFace ( GL_FRONT_AND_BACK ); // BACK-FRONT какие грани будут отбираться
// glEnable ( GL_CULL_FACE ); // включение режима отбора треугольников
glPointSize( 1.0 );
glHint ( GL_POINT_SMOOTH_HINT,GL_NICEST );
glEnable ( GL_POINT_SMOOTH );
glLineWidth( 1.0 );
glHint ( GL_LINE_SMOOTH_HINT,GL_NICEST );
glEnable ( GL_LINE_SMOOTH ); // сглаживание линий
glPolygonMode( GL_FRONT,GL_FILL );
glPolygonMode( GL_BACK,GL_LINE ); //POINT );
glShadeModel( GL_SMOOTH ); // FLAT закраска с использованием полутонов
glHint ( GL_POLYGON_SMOOTH_HINT,GL_NICEST );
glEnable ( GL_POLYGON_SMOOTH); // Really Nice Perspective Calculations
glHint ( GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST );
glBlendFunc( GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA );
glEnable ( GL_DITHER ); // Предопределение графической среды
glEnable ( GL_ALPHA_TEST );
glEnable ( GL_BLEND );
glFogi( GL_FOG_MODE,GL_EXP2 );
glFogf( GL_FOG_DENSITY,0.0016 );
// glFogf( GL_FOG_START,Storm->Distance );
// glFogf( GL_FOG_END,-Storm->Distance );
glHint ( GL_FOG_HINT,GL_NICEST );
glEnable ( GL_FOG );
// glEnable ( GL_STENCIL_TEST );
#if 1
glLightModelfv( GL_LIGHT_MODEL_AMBIENT,(const float[])
{
0.8,1,0.9,0.75
} );
glLightModeli( GL_LIGHT_MODEL_LOCAL_VIEWER,true );
glLightModeli( GL_LIGHT_MODEL_TWO_SIDE,true );
glMaterialfv( GL_FRONT_AND_BACK,GL_AMBIENT, (const float[])
{
.2,.2,.2,1.
} ); //=окружение
glMaterialfv( GL_FRONT_AND_BACK,GL_DIFFUSE, (const float[])
{
.8,.8,.8,1.
} ); //=рассеяние
glMaterialfv( GL_FRONT_AND_BACK,GL_SPECULAR,(const float[])
{
.5,.5,.5,.5
} ); // отражение
glMaterialfv( GL_FRONT_AND_BACK,GL_EMISSION,(const float[])
{
.0,.0,.0,1.
} ); //=излучение
glMateriali( GL_FRONT_AND_BACK,GL_SHININESS,127 );// степень отсветки
glLightfv( GL_LIGHT0,GL_AMBIENT, (const float[])
{
.1,.3,.2,.6
} ); // окружение
glLightfv( GL_LIGHT0,GL_DIFFUSE, (const float[])
{
.6,.8, 1, 1
} ); // рассеяние
glLightfv( GL_LIGHT0,GL_SPECULAR,(const float[])
{
.8,.9, 1, 1
} ); // отражение
glLightfv( GL_LIGHT0,GL_EMISSION,(const float[])
{
.6,.6,.6, 1
} ); // излучение
glLightfv( GL_LIGHT0,GL_POSITION,(const float[])
{
-2000,20,-100,1
} );
glLightfv( GL_LIGHT1,GL_AMBIENT, (const float[])
{
.1,.2,.3,.8
} ); // окружение
glLightfv( GL_LIGHT1,GL_DIFFUSE, (const float[])
{
.8, 1, 1, 1
} ); // рассеяние
glLightfv( GL_LIGHT1,GL_SPECULAR,(const float[])
{
.6,.8,.9, 1
} ); // отражение
glLightfv( GL_LIGHT1,GL_EMISSION,(const float[])
{
.6,.6,.6, 1
} ); // излучение
glLightfv( GL_LIGHT1,GL_POSITION,(const float[])
{
2000,100,10,1.0
} );
#endif
glEnable( GL_COLOR_MATERIAL );
glEnable( GL_LIGHT0 );
glEnable( GL_LIGHT1 );
glEnable( GL_LIGHTING );
glDepthRange( 1,0 );
glDepthMask( GL_TRUE );
glEnable( GL_DEPTH_TEST ); // растровая разборка отсечений по глубине
// glClearDepth( 2000.0 ); // Enables Clearing Of The Depth Buffer
glDepthFunc( GL_LEQUAL ); // LESS GREATER ALWAYS взаимное накрытие объектов
glEnable( GL_AUTO_NORMAL );
glEnable( GL_NORMALIZE );
glColorMaterial( GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE );
for( int i=0; i<256; i++ )
SeaColor[1+black+i][0]=byte( pow(Real(i)/255,4)*180 ), // red красный
SeaColor[1+black+i][1]=byte( 48+pow(Real(i)/255,2)*162 ), // green зеленый
SeaColor[1+black+i][2]=byte( 96+pow(Real(i)/255,3)*94 ); // blue синий
for( int i=0; i<black+256; i++ )SeaColor[i][3]=255; // alfa-сплошной
//
//FILE *F=fopen( "Vessel.mtl","wt" ); for( int i=0; i<black+257; i++ )
//fprintf( F,"newmtl c%d\nkd %0.3f %0.3f %0.3f\n",i, //<=black?-10:i-black-1,
// Real(SeaColor[i][0])/255,Real(SeaColor[i][1])/255,Real(SeaColor[i][2])/255 );
//fclose( F );
}
|
d150748a9a3ba005ccab1085d2419df5c5bc230e
|
3ef9dbe0dd6b8161b75950f682ec2fc24f79a90e
|
/OI2019/NOIP2019/d1t2.cpp
|
1e0e893ade0b1484e6a3c1019e36786472b59bc8
|
[
"MIT"
] |
permissive
|
JackBai0914/Competitive-Programming-Codebase
|
abc0cb911e5f6b32d1bd14416f9eb398b7c65bb9
|
a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9
|
refs/heads/main
| 2023-03-29T14:17:36.190798
| 2021-04-14T23:15:12
| 2021-04-14T23:15:12
| 358,065,977
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 16
|
cpp
|
d1t2.cpp
|
#add a node:
|
65ed6d8cac2e5c5eb444d1287e65614a61243933
|
c6f08f2bb8b812bcb63a6216fbd674e1ebdf00d8
|
/ni_header/NiScriptInfoDialogs.h
|
9c14848c9c1815731af33785ae06677f758c374b
|
[] |
no_license
|
yuexiae/ns
|
b45e2e97524bd3d5d54e8a79e6796475b13bd3f9
|
ffeb846c0204981cf9ae8033a83b2aca2f8cc3ac
|
refs/heads/master
| 2021-01-19T19:11:39.353269
| 2016-06-08T05:56:35
| 2016-06-08T05:56:35
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,705
|
h
|
NiScriptInfoDialogs.h
|
// NUMERICAL DESIGN LIMITED PROPRIETARY INFORMATION
//
// This software is supplied under the terms of a license agreement or
// nondisclosure agreement with Numerical Design Limited and may not
// be copied or disclosed except in accordance with the terms of that
// agreement.
//
// Copyright (c) 1996-2004 Numerical Design Limited.
// All Rights Reserved.
//
// Numerical Design Limited, Chapel Hill, North Carolina 27514
// http://www.ndl.com
#ifndef NISCRIPTINFODIALOGS_H
#define NISCRIPTINFODIALOGS_H
#include "NiPluginToolkitLibType.h"
#include "NiPluginToolkitDefinitions.h"
#include "NiScriptInfo.h"
class NiScriptInfoSet;
class NIPLUGINTOOLKIT_ENTRY NiScriptInfoDialogs
{
public:
/// Creates a modal dialog box that allows a user to create
/// and manage existing NiScriptInfo objects
static NiScriptInfoPtr DoManagementDialog(NiScriptInfo* pkDefaultInfo,
NiScriptInfoSet* pkInputSet, NiWindowRef kWindow, NiString strTypes);
/// Creates a modal dialog box that allows a user to select
/// from existing NiScriptInfo objects
static NiScriptInfoPtr DoSelectionDialog(NiScriptInfo* pkDefaultInfo,
NiScriptInfoSet* pkInputSet, NiWindowRef kWindow, NiString strTypes);
/// Creates a modal dialog box that allows a user to save
/// an existing script
static ReturnCode DoScriptSaveDialog(NiScriptInfo* pkScript,
NiWindowRef kWindow, bool bPromptForLoc = true);
/// Creates a modal dialog box that allows a user to open
/// scripts and adds them to the known script list
static NiScriptInfo* DoScriptOpenDialog(NiWindowRef kWindow,
bool bAddToManager = true);
// *** begin NDL internal use only ***
/// Useful method for generating the default script for execution. It adds
/// the generated default script to the NiScriptInfoSet if it doesn't already
/// exist
/// Check performed:
/// 1) The input script exists. If it doesn't, use the last script executed by
/// the plugin manager.
/// 2) The input script uses valid plugins loaded by the framework. If not, strip
/// off the offending plugin info objects and return
/// 3) If the script matches an existing template from the NiScriptInfoSet,
/// check to see if it differs
/// from the template. If it differs, ask the user if they want to use the
/// template or the original input script.
static NiScriptInfo* GenerateDefaultScript(NiScriptInfo* pkInfo,
NiScriptInfoSet*& pkInfoSet, bool bPromptUser = true, bool bForceTemplateUse = false);
/// Useful method for generating the default script info set for the execution
/// It adds the set of template scripts from the NiScriptTemplateManager that
/// use known Process, Export, or Import plugins
static NiScriptInfoSet* GenerateDefaultScriptInfoSet();
/// Useful method for generating the import and export filenames for an NiScriptInfo
/// object.
static void CompileImportExportInfo(const char* pcBaseFilename, NiScriptInfo* pkScript,
bool bPromptForFiles, bool bSilentRunning);
static unsigned int CountNumberOfExportPluginInfos(NiScriptInfo* pkScript);
static unsigned int CountNumberOfImportPluginInfos(NiScriptInfo* pkScript);
// *** end NDL internal use only ***
protected:
static bool FileTypesMatch(const char* pcExtension, NiPluginInfo* pkPluginInfo);
};
#endif
|
c520a298cc1a03825f0454d0935dbfe081cfae7b
|
cd72b19d2030f36f78dab52390d092ed3dc8005f
|
/apps/src/videostitch-live-gui/src/newinputitemwidget.cpp
|
1796876a0ebc1cecca4be3de23c9f3cff2deca72
|
[
"MIT",
"DOC"
] |
permissive
|
stitchEm/stitchEm
|
08c5a3ef95c16926c944c1835fdd4ab4b6855580
|
4a0e9fc167f10c7dde46394aff302927c15ce6cb
|
refs/heads/master
| 2022-11-27T20:13:45.741733
| 2022-11-22T17:26:07
| 2022-11-22T17:26:07
| 182,059,770
| 250
| 68
|
MIT
| 2022-11-22T17:26:08
| 2019-04-18T09:36:54
|
C++
|
UTF-8
|
C++
| false
| false
| 1,924
|
cpp
|
newinputitemwidget.cpp
|
// Copyright (c) 2012-2017 VideoStitch SAS
// Copyright (c) 2018 stitchEm
#include "newinputitemwidget.hpp"
#include "ui_newinputitemwidget.h"
#include <QMovie>
static const QString LOADING_ICON(":/live/icons/assets/icon/live/loadconnecting.gif");
static const QString OK_ICON(":/live/icons/assets/icon/live/check.png");
static const QString FAIL_ICON(":/live/icons/assets/icon/live/close.png");
NewInputItemWidget::NewInputItemWidget(const QString url, const int id, QWidget* const parent)
: QWidget(parent),
ui(new Ui::NewInputItemWidget),
widgetId(id),
movieLoading(new QMovie(LOADING_ICON, nullptr, this)) {
ui->setupUi(this);
ui->lineURL->setText(url);
ui->labelField->setText(tr("URL %0:").arg(id + 1));
connect(ui->lineURL, &QLineEdit::textChanged, this, &NewInputItemWidget::onUrlChanged);
}
NewInputItemWidget::~NewInputItemWidget() { delete ui; }
bool NewInputItemWidget::hasValidUrl() const { return urlCheckStatus == UrlStatus::Verified; }
QByteArray NewInputItemWidget::getUrl() const { return ui->lineURL->text().toLatin1(); }
int NewInputItemWidget::getId() const { return widgetId; }
void NewInputItemWidget::setUrl(const QString url) { ui->lineURL->setText(url); }
void NewInputItemWidget::onTestFinished(const bool success) {
ui->labelStatusIcon->setPixmap(success ? QPixmap(OK_ICON) : QPixmap(FAIL_ICON));
movieLoading->stop();
ui->lineURL->setEnabled(true);
urlCheckStatus = (success ? UrlStatus::Verified : UrlStatus::Failed);
emit notifyUrlValidityChanged();
}
void NewInputItemWidget::onTestClicked() {
ui->labelStatusIcon->show();
ui->labelStatusIcon->setMovie(movieLoading);
ui->lineURL->setEnabled(false);
movieLoading->start();
emit notifyTestActivated(widgetId, ui->lineURL->text());
}
void NewInputItemWidget::onUrlChanged() {
ui->labelStatusIcon->clear();
urlCheckStatus = UrlStatus::Unknown;
emit notifyUrlContentChanged();
}
|
ad9adb218818f2f170680bc8ef12e06f330f3e6c
|
379c8930190f2a5f994a960fe6e67db9579bbc6f
|
/RZRenderersTest/Main.cpp
|
96421ba6d4afe1ef2be59fa81af643c895671c61
|
[] |
no_license
|
rezanour/RZRenderers
|
8b5adbe8e326be03a0c65c8ab2cc0103fcc94703
|
72ca251ff85524207a7b6b0c66b7d13ed92e087c
|
refs/heads/master
| 2021-01-19T01:16:48.369077
| 2016-08-17T06:40:14
| 2016-08-17T06:40:14
| 65,837,714
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,379
|
cpp
|
Main.cpp
|
#include "Precomp.h"
static HWND WindowInit(HINSTANCE instance, const wchar_t* class_name, int32_t width, int32_t height);
static LRESULT CALLBACK WindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
static bool LoadScene(IRZRenderer* renderer);
int WINAPI WinMain(HINSTANCE instance, HINSTANCE, LPSTR, int show_command)
{
HWND window = WindowInit(instance, L"RZRenderersTest", 1280, 960);
if (!window)
{
return -1;
}
IRZRenderer* renderer = nullptr;
RZRendererCreateParams params{};
params.WindowHandle = window;
params.RenderWidth = 640;
params.RenderHeight = 480;
params.HorizFOV = 60.f * (3.14156f / 180.f);
if (!RZRendererCreate(RZRenderer_CPURaytracer, ¶ms, &renderer))
{
return -2;
}
ShowWindow(window, show_command);
UpdateWindow(window);
if (!LoadScene(renderer))
{
renderer->Release();
return -3;
}
float speed = 2.f;
//float speed = 0.125f;
RZVector3 position{ 0.f, 25.f, -200.f };
//RZVector3 position{ 0.f, 0.f, -1.5f };
RZQuaternion orientation{ 0.f, 0.f, 0.f, 1.f };
wchar_t title[1024]{};
LARGE_INTEGER start, end, freq;
QueryPerformanceFrequency(&freq);
MSG msg = { 0 };
while (msg.message != WM_QUIT)
{
if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
QueryPerformanceCounter(&start);
if (GetAsyncKeyState(VK_LEFT) & 0x8000)
position.x -= speed;
if (GetAsyncKeyState(VK_RIGHT) & 0x8000)
position.x += speed;
if (GetAsyncKeyState(VK_DOWN) & 0x8000)
position.z -= speed;
if (GetAsyncKeyState(VK_UP) & 0x8000)
position.z += speed;
renderer->RenderScene(position, orientation);
QueryPerformanceCounter(&end);
swprintf_s(title, L"Elapsed: %3.2fms", 1000. * (end.QuadPart - start.QuadPart) / (double)freq.QuadPart);
SetWindowText(window, title);
}
}
renderer->Release();
DestroyWindow(window);
return 0;
}
HWND WindowInit(HINSTANCE instance, const wchar_t* class_name, int32_t width, int32_t height)
{
WNDCLASSEX wcx = { 0 };
wcx.cbSize = sizeof(wcx);
wcx.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wcx.hInstance = instance;
wcx.lpfnWndProc = WindowProc;
wcx.lpszClassName = class_name;
if (RegisterClassEx(&wcx) == INVALID_ATOM)
{
assert(false);
return NULL;
}
DWORD style = WS_OVERLAPPEDWINDOW;
RECT rc = { 0 };
rc.right = width;
rc.bottom = height;
AdjustWindowRect(&rc, style, FALSE);
HWND hwnd = CreateWindow(wcx.lpszClassName, wcx.lpszClassName, style, CW_USEDEFAULT, CW_USEDEFAULT,
rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, instance, NULL);
if (!hwnd)
{
assert(false);
return NULL;
}
return hwnd;
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_CLOSE:
PostQuitMessage(0);
break;
case WM_KEYDOWN:
if (wParam == VK_ESCAPE)
{
PostQuitMessage(0);
}
break;
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}
bool LoadScene(IRZRenderer* renderer)
{
UNREFERENCED_PARAMETER(renderer);
Assimp::Importer imp;
const aiScene* scene = imp.ReadFile("C:\\src\\assets\\teapot\\teapot.obj",
//const aiScene* scene = imp.ReadFile("C:\\src\\assets\\dragon\\dragon.obj",
//const aiScene* scene = imp.ReadFile("C:\\src\\assets\\buddha\\buddha.obj",
aiProcess_GenSmoothNormals | aiProcess_Triangulate |
aiProcess_OptimizeGraph | aiProcess_OptimizeMeshes |
aiProcess_JoinIdenticalVertices);
if (!scene)
{
OutputDebugStringA(imp.GetErrorString());
return false;
}
std::vector<uint32_t> indices(1024);
for (uint32_t i_mesh = 0; i_mesh < scene->mNumMeshes; ++i_mesh)
{
const aiMesh* mesh = scene->mMeshes[i_mesh];
uint32_t base_index = renderer->AddVertices(mesh->mNumVertices, (const RZVector3*)mesh->mVertices);
indices.clear();
for (uint32_t i_face = 0; i_face < mesh->mNumFaces; ++i_face)
{
const aiFace* face = &mesh->mFaces[i_face];
assert(face->mNumIndices == 3);
indices.push_back(base_index + face->mIndices[0]);
indices.push_back(base_index + face->mIndices[1]);
indices.push_back(base_index + face->mIndices[2]);
}
renderer->AddMesh((uint32_t)indices.size(), indices.data());
}
return true;
}
|
6509b533f79638b18083e3cf5986e756fa6b5490
|
c46ac3570297f694c8c363167316394e38e41e77
|
/cpp-project/directed-graph/topological_sort1.h
|
8164823e8b601e3ff2509331968e7f35de0bcdb2
|
[] |
no_license
|
luoxuwei/Graph-Algorithms
|
3a6486abcda1acf2cafcf6a3219a762236ecb8f5
|
d583dbc0497f40354414ca59efde81211602e81c
|
refs/heads/master
| 2021-12-24T00:12:38.744408
| 2021-12-01T07:18:20
| 2021-12-01T07:18:20
| 239,277,284
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 799
|
h
|
topological_sort1.h
|
//
// Created by 罗旭维 on 2021/11/29.
//
#ifndef CPP_PROJECT_TOPOLOGICAL_SORT1_H
#define CPP_PROJECT_TOPOLOGICAL_SORT1_H
#include "../CGraph.h"
#include "graph_dfs.h"
#include "cycle_detection.h"
#include <vector>
#include <algorithm>
class TopologicalSort1 {
private:
CGraph &G_;
std::vector<int> res;
public:
TopologicalSort1(CGraph &g) : G_(g) {
CycleDetection cycleDetection(g);
if (cycleDetection.HasCycle()) return;
GraphDFS graphDfs(g);
for (auto v : graphDfs.post()) {
res.push_back(v);
}
std::reverse(res.begin(), res.end());
}
void printResult() {
for (auto v : res) {
std::cout<<v<<",";
}
std::cout<<std::endl;
}
};
#endif //CPP_PROJECT_TOPOLOGICAL_SORT1_H
|
f4e45071a1f476e8b3217fa3cffaa6ef77975971
|
adb93d646fc5c7f57d4f3844a86c681a80316676
|
/include/fish_annotator/common/species_controls.h
|
812a207a4d185f9a0701d339a76b7d802581b600
|
[
"MIT"
] |
permissive
|
ltoscano/FishAnnotator
|
0e2aea30c704d7d24300a6b1bf685d354810e1ee
|
c9f3a2b1127789675b9e0161eb3d8d99f32c9c2a
|
refs/heads/master
| 2021-01-12T01:22:38.518010
| 2016-12-22T03:42:28
| 2016-12-22T03:42:28
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,471
|
h
|
species_controls.h
|
/// @file
/// @brief Defines SpeciesControls class.
#ifndef SPECIES_CONTROLS_H
#define SPECIES_CONTROLS_H
#include <memory>
#include <list>
#include <QMenu>
#include "fish_annotator/common/species_widget.h"
#include "../../src/common/ui_species_controls.h"
#ifndef NO_TESTING
class TestImageAnnotator;
#endif
namespace fish_annotator {
class SpeciesControls : public QWidget {
Q_OBJECT
#ifndef NO_TESTING
friend class ::TestImageAnnotator;
#endif
public:
/// @brief Constructor.
///
/// @param parent Parent widget.
explicit SpeciesControls(QWidget *parent = 0);
/// @brief Resets all counts to zero.
void resetCounts();
/// @brief Sets count for a given species.
void setCount(uint64_t count, const std::string &species);
/// @brief Loads species from an external source.
///
/// @param vec Vector of species used to insert widgets.
void loadFromVector(const std::vector<Species> &vec);
private slots:
/// @brief Brings up a dialog box to add a species.
void on_addSpecies_clicked();
/// @brief Brings up a dialog box to load a species file.
void on_loadSpecies_clicked();
/// @brief Brings up a dialog box to save a species file.
void on_saveSpecies_clicked();
/// @brief Clears all species widgets after asking for confirmation.
void onClearAllSpeciesWidgetsTriggered();
/// @brief Clears a specific species widget.
void clearSpeciesWidget();
/// @brief Edits a specific species widget.
void editSpeciesWidget();
signals:
/// @brief Propagates add individual signal from species widgets.
void individualAdded(std::string species, std::string subspecies);
private:
/// @brief Widget loaded from ui file.
std::unique_ptr<Ui::SpeciesControls> ui_;
/// @brief List of species widget pointers.
std::list<std::unique_ptr<SpeciesWidget>> species_widgets_;
/// @brief Drop down menu for editing species.
std::unique_ptr<QMenu> edit_species_menu_;
/// @brief Drop down menu for clearing species.
std::unique_ptr<QMenu> clear_species_menu_;
/// @brief Clears all species widgets.
void clearAllSpeciesWidgets();
/// @brief Inserts a new species widget.
///
/// @param species Species object used to construct the widget.
void insertSpeciesWidget(const Species &species);
/// @brief Loads species file.
///
/// @param in_file Path to input species file.
void loadSpeciesFile(const QString &in_file);
};
} // namespace fish_annotator
#endif // SPECIES_CONTROLS_H
|
e6738be475395c3e6df3ae9fa04be58643089954
|
9ac5ba363ad48a9f38da0d15bc45cc398c310389
|
/RankingLayer.cpp
|
34e8bda519eaeaac2e05a53d02089f1ceec2ab15
|
[] |
no_license
|
atom-chen/qiuqiuccc
|
fddee58a594db2409245f1a9fa655d092b680efb
|
4daec0a41ddd51ac5b3f66dfbb7bba5f1c32127f
|
refs/heads/master
| 2020-06-09T01:28:28.196976
| 2017-10-15T16:05:42
| 2017-10-15T16:05:42
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 35,710
|
cpp
|
RankingLayer.cpp
|
//
// RankingLayer.cpp
// qiuFight
//
// Created by 张跃东 on 16/4/9.
//
//
#include "RankingLayer.h"
#include "MainScene.h"
#include "RichLabel.h"
#define CHILD_OFFSET_X 50
#define CHILD_OFFSET_Y 100
#include "msg_client.pb.h"
#include "struct.pb.h"
#include "ExchangeInfo.h"
#include "msg_error.pb.h"
#include "Resources.h"
#include "CurCularNode.h"
#include "GameVoice.h"
/////////////////////////////////////////////////
///base
////////////////////////////////////////////////////
RankingLayerBase::RankingLayerBase()
{
}
RankingLayerBase::~RankingLayerBase()
{
}
bool RankingLayerBase::init()
{
if(!Layer::init())
return false;
initUI();
return true;
}
void RankingLayerBase::initUI()
{
Sprite* back = Sprite::create("center_back.png");
back->setPosition(Vec2(winSize.width * 0.5f, winSize.height * 0.5f));
back->setScale(0.6f);
addChild(back);
jhdwBtn = Button::createBtnWithSpriteFrameName("jianghudiwei-01.png", false);
jhdwBtn->setPosition(Vec2(130, winSize.height - 50));
jhdwBtn->setScale(0.6f);
jhdwBtn->setOnClickCallback(callfuncO_selector(RankingLayerBase::JhdwClick), this);
jhdwBtn->setPressIcon("jianghudiwei-02.png", false);
jhdwBtn->setPressIconShow(true);
addChild(jhdwBtn, 1);
cbzBtn = Button::createBtnWithSpriteFrameName("chongbaizhe-01.png", false);
cbzBtn->setPosition(Vec2(330, winSize.height - 50));
cbzBtn->setScale(0.6f);
cbzBtn->setOnClickCallback(callfuncO_selector(RankingLayerBase::CbzClick), this);
cbzBtn->setPressIcon("chongbaizhe-02.png", false);
addChild(cbzBtn, 1);
ymzBtn = Button::createBtnWithSpriteFrameName("yangmuzhe-01.png", false);
ymzBtn->setPosition(Vec2(480, winSize.height - 50));
ymzBtn->setScale(0.6f);
ymzBtn->setOnClickCallback(callfuncO_selector(RankingLayerBase::YmzClick), this);
ymzBtn->setPressIcon("yangmuzhe-02.png", false);
addChild(ymzBtn, 1);
//xzzBtn = Button::createBtnWithSpriteFrameName("xiaozhenzhu-01.png", false);
//xzzBtn->setPosition(Vec2(630, winSize.height - 50));
//xzzBtn->setScale(0.6f);
//xzzBtn->setOnClickCallback(callfuncO_selector(RankingLayerBase::XzzClick), this);
//xzzBtn->setPressIcon("xiaozhenzhu-02.png", false);
//addChild(xzzBtn, 1);
jssBtn = Button::createBtnWithSpriteFrameName("jishashu-01.png", false);
jssBtn->setPosition(Vec2(630, winSize.height - 50));
jssBtn->setScale(0.6f);
jssBtn->setOnClickCallback(callfuncO_selector(RankingLayerBase::JssClick), this);
jssBtn->setPressIcon("jishashu-02.png", false);
addChild(jssBtn, 1);
Button* backBtn = Button::createBtnWithSpriteFrameName("rankingback.png", false);
backBtn->setPosition(Vec2(winSize.width - 60, 40));
backBtn->setScale(0.6f);
backBtn->setOnClickCallback(callfuncO_selector(RankingLayerBase::BackClick), this);
addChild(backBtn, 1);
m_rankTag = TAG_NONE;
scheduleOnce(schedule_selector(RankingLayerBase::SenMSG), 0.01f);
}
void RankingLayerBase::SenMSG(float ft)
{
JhdwClick(jhdwBtn);
}
void RankingLayerBase::resetBtnState()
{
jhdwBtn->setPressIconShow(false);
cbzBtn->setPressIconShow(false);
ymzBtn->setPressIconShow(false);
//xzzBtn->setPressIconShow(false);
jssBtn->setPressIconShow(false);
if(getChildByTag(TAG_JHDW))
{
removeChildByTag(TAG_JHDW);
}
else if(getChildByTag(TAG_CBZ))
{
removeChildByTag(TAG_CBZ);
}
else if(getChildByTag(TAG_YMZ))
{
removeChildByTag(TAG_YMZ);
}
//else if(getChildByTag(TAG_XZZ))
//{
//removeChildByTag(TAG_XZZ);
//}
else if(getChildByTag(TAG_JSS))
{
removeChildByTag(TAG_JSS);
}
}
void RankingLayerBase::JhdwClick(cocos2d::Ref *pSender)
{
GameVoice::getInstance()->playClickBtnVoive();
if(TAG_JHDW == m_rankTag)
return;
resetBtnState();
m_rankTag = TAG_JHDW;
jhdwBtn->setPressIconShow(true);
RankingLayerChild* child = RankingLayerChild::create();
child->setPosition(Vec2(CHILD_OFFSET_X, CHILD_OFFSET_Y));
addChild(child, 10, TAG_JHDW);
((MainScene*)getParent())->reqRanks(1, 1);
}
void RankingLayerBase::CbzClick(cocos2d::Ref *pSender)
{
GameVoice::getInstance()->playClickBtnVoive();
if(TAG_CBZ == m_rankTag)
return;
resetBtnState();
m_rankTag = TAG_CBZ;
cbzBtn->setPressIconShow(true);
RankingLayerChild* child = RankingLayerChild::create();
child->setPosition(Vec2(CHILD_OFFSET_X, CHILD_OFFSET_Y));
addChild(child, 10, TAG_CBZ);
((MainScene*)getParent())->reqRanks(2, 1);
}
void RankingLayerBase::YmzClick(cocos2d::Ref *pSender)
{
GameVoice::getInstance()->playClickBtnVoive();
if(TAG_YMZ == m_rankTag)
return;
resetBtnState();
m_rankTag = TAG_YMZ;
ymzBtn->setPressIconShow(true);
RankingLayerChild* child = RankingLayerChild::create();
child->setPosition(Vec2(CHILD_OFFSET_X, CHILD_OFFSET_Y));
addChild(child, 10, TAG_YMZ);
((MainScene*)getParent())->reqRanks(3, 1);
}
void RankingLayerBase::XzzClick(cocos2d::Ref *pSender)
{
GameVoice::getInstance()->playClickBtnVoive();
/*
if(TAG_XZZ == m_rankTag)
return;
resetBtnState();
m_rankTag = TAG_XZZ;
xzzBtn->setPressIconShow(true);
RankingLayerChild* child = RankingLayerChild::create();
child->setPosition(Vec2(CHILD_OFFSET_X, CHILD_OFFSET_Y));
addChild(child, 10, TAG_XZZ);
((MainScene*)getParent())->reqRanks(4, 1);
*/
}
void RankingLayerBase::JssClick(cocos2d::Ref *pSender)
{
GameVoice::getInstance()->playClickBtnVoive();
if(TAG_JSS == m_rankTag)
return;
resetBtnState();
m_rankTag = TAG_JSS;
jssBtn->setPressIconShow(true);
RankingLayerChild* child = RankingLayerChild::create();
child->setPosition(Vec2(CHILD_OFFSET_X, CHILD_OFFSET_Y));
addChild(child, 10, TAG_JSS);
((MainScene*)getParent())->reqRanks(5, 1);
}
void RankingLayerBase::BackClick(cocos2d::Ref *pSender)
{
GameVoice::getInstance()->playClickBtnVoive();
MainScene* main = dynamic_cast<MainScene*>(getParent());
main->BackToLoginLayer(MainScene::TAG_LAYER_RANKING);
}
void RankingLayerBase::respRanks(const cocos2d::network::WebSocket::Data &data)
{
// 此处需要纪录有头像的
std::vector<int> icons;
icons.clear();
UM_Ranks resp;
bool re = resp.ParseFromArray(data.bytes + 2, data.len - 2);
if(re)
{
//std::vector<rank_info> items;
std::vector<TestRank> ranks;
std::vector<TestRank> ranks1;
int num = resp.list_size();
//log("list number is:%d", num);
for( int i = 0; i < num; i++)
{
TestRank rank;
rank_info item = resp.list(i);
//items.push_back(item);
rank.m_id = item.roleid();
rank.m_iconDex = item.icon();
rank.m_sex = item.sex();
rank.m_rank = item.rank();
rank.m_name = item.name();
int value1 = item.value1();
int value2 = item.value2();
char strlab[128] = {0};
switch (m_rankTag)
{
case TAG_JHDW:
{
uint8_t right, left; // right星级,left 段位
right = value1 & 0x00ff;
left = value1 >> 8;
//duanweiInfo duan = Resource::sharedResource()->GetDuanweiInfo(left);
//log("left is:%d, right is:%d", left, right);
rank.m_duanwei = left;
rank.m_xing = right;
}
break;
case TAG_CBZ:
{
sprintf(strlab, "%d",value1);
rank.m_zjrs = strlab;
sprintf(strlab, "%d",value2);
rank.m_zcbs = strlab;
}
break;
case TAG_YMZ:
{
sprintf(strlab, "%d",value1);
rank.m_zjymz = strlab;
sprintf(strlab, "%d",value2);
rank.m_zymz = strlab;
}
break;
//case TAG_XZZ:
//{
//sprintf(strlab, "%d",value1);
//rank.m_zjhds = strlab;
//sprintf(strlab, "%d",value2);
//rank.m_hdzs = strlab;
//}
break;
case TAG_JSS:
{
sprintf(strlab, "%d",value1);
rank.m_zjjss = strlab;
sprintf(strlab, "%d",value2);
rank.m_zjss = strlab;
}
break;
default:
break;
}
if(rank.m_iconDex < 101)
{
icons.push_back(rank.m_id);
}
ranks.push_back(rank);
}
((RankingLayerChild*)getChildByTag(m_rankTag))->setRanks(ranks);
// 活的icons
if(icons.size() > 0)
{
MainScene* main = dynamic_cast<MainScene*>(getParent());
main->reqIcons(icons);
}else{
((RankingLayerChild*)getChildByTag(m_rankTag))->initTableView();
}
}
}
void RankingLayerBase::respRankIcons(std::vector<icon_data> icons)
{
((RankingLayerChild*)getChildByTag(m_rankTag))->updateRanks(icons);
}
///////////////////////////////////////////////////////////////////
////RankingLayerChild
///////////////////////////////////////////////////////////////////
RankingLayerChild::RankingLayerChild()
{
m_atts.clear();
/*
TestRank rank1;
rank1.m_id = 1;
rank1.m_sex = 1;
rank1.m_name = "B0B69845026";
rank1.m_diwei = "超神127杀";
rank1.m_zjrs = "5123";
rank1.m_zcbs = "14233";
rank1.m_zjymz = "5123";
rank1.m_zymz = "14233";
rank1.m_zjhds = "5123";
rank1.m_hdzs = "14233";
rank1.m_zjjss = "5123";
rank1.m_zjss = "14233";
m_atts.push_back(rank1);
TestRank rank2;
rank2.m_id = 2;
rank2.m_sex = 1;
rank2.m_name = "B0B69845027";
rank2.m_diwei = "超神88杀";
rank2.m_zjrs = "4534";
rank2.m_zcbs = "8845";
m_atts.push_back(rank2);
TestRank rank3;
rank3.m_id = 3;
rank3.m_sex = 1;
rank3.m_name = "B0B69845028";
rank3.m_diwei = "超神68杀";
rank3.m_zjrs = "4533";
rank3.m_zcbs = "5334";
m_atts.push_back(rank3);
TestRank rank4;
rank4.m_id = 4;
rank4.m_sex = 1;
rank4.m_name = "B0B69845029";
rank4.m_diwei = "超神54杀";
rank4.m_zjrs = "3245";
rank4.m_zcbs = "4335";
m_atts.push_back(rank4);
TestRank rank5;
rank5.m_id = 5;
rank5.m_sex = 1;
rank5.m_name = "B0B69845030";
rank5.m_diwei = "超神33杀";
rank5.m_zjrs = "2415";
rank5.m_zcbs = "3322";
m_atts.push_back(rank5);
TestRank rank6;
rank6.m_id = 6;
rank6.m_sex = 1;
rank6.m_name = "B0B69845031";
rank6.m_diwei = "超神12杀";
rank6.m_zjrs = "1223";
rank6.m_zcbs = "2089";
m_atts.push_back(rank6);
*/
}
RankingLayerChild::~RankingLayerChild()
{
}
bool RankingLayerChild::init()
{
if(!Layer::init())
return false;
Sprite* title_back = Sprite::create("title_frame.png");
title_back->setPosition(Vec2(winSize.width * 0.5f-20, winSize.height - CHILD_OFFSET_Y - 100));
title_back->setScale(0.55f);
addChild((title_back));
Sprite* back = Sprite::create("dikuangbeijing-01.png");
back->setPosition(Vec2(winSize.width * 0.5f -20, winSize.height * 0.5f - CHILD_OFFSET_Y - 30));
back->setScale(0.55f);
addChild(back);
Sprite* rank_lb = Sprite::create("paiming-01.png");
rank_lb->setPosition(Vec2(winSize.width * 0.5f - 420, winSize.height - CHILD_OFFSET_Y - 100));
rank_lb->setScale(0.55f);
addChild(rank_lb, 1);
Sprite* name_lb = Sprite::create("yonghuming-01.png");
name_lb->setPosition(Vec2(winSize.width * 0.5f - 180, winSize.height - CHILD_OFFSET_Y - 100));
name_lb->setScale(0.55f);
addChild(name_lb, 1);
//scheduleOnce(schedule_selector(RankingLayerChild::initTableView), 0.1);
return true;
}
void RankingLayerChild::setRanks(std::vector<TestRank> ranks)
{
m_atts.clear();
m_atts = ranks;
}
void RankingLayerChild::updateRanks(std::vector<icon_data> datas)
{
std::vector<TestRank>::iterator it = m_atts.begin();
for(; it != m_atts.end(); ++it)
{
if((*it).m_iconDex < 101)
{
(*it).m_iconStr = getIconString((*it).m_id, datas);
}
}
initTableView();
}
std::string RankingLayerChild::getIconString(int roleID, std::vector<icon_data>datas)
{
std::vector<icon_data>::iterator it = datas.begin();
for(; it != datas.end(); ++it)
{
icon_data data = *it;
if(data.roleid() == roleID)
{
return data.data();
}
}
return "";
}
void RankingLayerChild::initTableView()
{
if (getChildByTag(101)) {
((TableView*)getChildByTag(101))->reloadData();
return;
}
RankingLayerBase* base = dynamic_cast<RankingLayerBase*>(getParent());
m_tag = base->GetCurrentTag();
if(m_tag == RankingLayerBase::TAG_JHDW)
{
Sprite* dw_lb = Sprite::create("jianghudiwei-01.png");
dw_lb->setPosition(Vec2(winSize.width * 0.5f + 180, winSize.height - CHILD_OFFSET_Y - 100));
dw_lb->setScale(0.4f);
addChild(dw_lb, 1);
btn1 = Button::createBtnWithSpriteFrameName("kuang1_2.png", false);
btn1->setPosition(Vec2(30, winSize.height - CHILD_OFFSET_Y - 160));
btn1->setScale(0.55f);
btn1->setOnClickCallback(callfuncO_selector(RankingLayerChild::clickBtn1), this);
btn1->setPressIcon("kuang1_1.png", false);
btn1->setPressIconShow(true);
addChild(btn1, 1, 111);
current_click_index = 1;
RichLabel* lab1 = RichLabel::create(Global::getInstance()->getString("50"), "STXingkai.ttf", 36.0f, Size(50, 100),false,false);
lab1->setPosition(Vec2(15, winSize.height - CHILD_OFFSET_Y - 210));
lab1->setAnchorPoint(Vec2::ZERO);
addChild(lab1, 2);
btn2 = Button::createBtnWithSpriteFrameName("kuang1_2.png", false);
btn2->setPosition(Vec2(30, winSize.height - CHILD_OFFSET_Y - 310));
btn2->setScaleX(0.55f);
btn2->setScaleY(0.4f);
btn2->setOnClickCallback(callfuncO_selector(RankingLayerChild::clickBtn2), this);
btn2->setPressIcon("kuang1_1.png", false);
addChild(btn2, 1, 112);
RichLabel* lab2 = RichLabel::create(Global::getInstance()->getString("51"), "STXingkai.ttf", 36.0f, Size(50, 100),false,false);
lab2->setAnchorPoint(Vec2::ZERO);
lab2->setPosition(Vec2(15, winSize.height - CHILD_OFFSET_Y - 385));
addChild(lab2, 2);
btn3 = Button::createBtnWithSpriteFrameName("kuang1_2.png", false);
btn3->setPosition(Vec2(30, winSize.height - CHILD_OFFSET_Y - 475));
btn3->setScaleX(0.55f);
btn3->setScaleY(0.65f);
btn3->setOnClickCallback(callfuncO_selector(RankingLayerChild::clickBtn3), this);
btn3->setPressIcon("kuang1_1.png", false);
addChild(btn3, 1, 113);
RichLabel* lab3 = RichLabel::create(Global::getInstance()->getString("52"), "STXingkai.ttf", 36.0f, Size(50, 120),false,false);
lab3->setAnchorPoint(Vec2::ZERO);
lab3->setPosition(Vec2(15, winSize.height - CHILD_OFFSET_Y - 535));
addChild(lab3, 2);
}
else if(m_tag == RankingLayerBase::TAG_CBZ)
{
Sprite* zj_lb = Sprite::create("zuijinhuoderenshu-01.png");
zj_lb->setPosition(Vec2(winSize.width * 0.5f + 130, winSize.height - CHILD_OFFSET_Y - 100));
zj_lb->setScale(0.55f);
addChild(zj_lb, 1);
Sprite* zcbz_lb = Sprite::create("zongchongbaizheshu-01.png");
zcbz_lb->setPosition(Vec2(winSize.width * 0.5f + 280, winSize.height - CHILD_OFFSET_Y - 100));
zcbz_lb->setScale(0.55f);
addChild(zcbz_lb, 1);
btn1 = Button::createBtnWithSpriteFrameName("kuang1_2.png", false);
btn1->setPosition(Vec2(30, winSize.height - CHILD_OFFSET_Y - 160));
btn1->setScale(0.55f);
btn1->setOnClickCallback(callfuncO_selector(RankingLayerChild::clickBtn1), this);
btn1->setPressIcon("kuang1_1.png", false);
btn1->setPressIconShow(true);
addChild(btn1, 1, 111);
current_click_index = 1;
RichLabel* lab1 = RichLabel::create(Global::getInstance()->getString("53"), "STXingkai.ttf", 36.0f, Size(50, 100),false,false);
lab1->setAnchorPoint(Vec2::ZERO);
lab1->setPosition(Vec2(15, winSize.height - CHILD_OFFSET_Y - 210));
addChild(lab1, 2);
btn2 = Button::createBtnWithSpriteFrameName("kuang1_2.png", false);
btn2->setPosition(Vec2(30, winSize.height - CHILD_OFFSET_Y - 330));
btn2->setScale(0.55f);
btn2->setOnClickCallback(callfuncO_selector(RankingLayerChild::clickBtn2), this);
btn2->setPressIcon("kuang1_1.png", false);
addChild(btn2, 1, 112);
RichLabel* lab2 = RichLabel::create(Global::getInstance()->getString("54"), "STXingkai.ttf", 36.0f, Size(50, 100),false,false);
lab2->setAnchorPoint(Vec2::ZERO);
lab2->setPosition(Vec2(15, winSize.height - CHILD_OFFSET_Y - 380));
addChild(lab2, 2);
btn3 = Button::createBtnWithSpriteFrameName("kuang1_2.png", false);
btn3->setPosition(Vec2(30, winSize.height - CHILD_OFFSET_Y - 500));
btn3->setScale(0.55f);
btn3->setOnClickCallback(callfuncO_selector(RankingLayerChild::clickBtn3), this);
btn3->setPressIcon("kuang1_1.png", false);
addChild(btn3, 1, 113);
RichLabel* lab3 = RichLabel::create(Global::getInstance()->getString("55"), "STXingkai.ttf", 36.0f, Size(50, 100),false,false);
lab3->setAnchorPoint(Vec2::ZERO);
lab3->setPosition(Vec2(15, winSize.height - CHILD_OFFSET_Y - 555));
addChild(lab3, 2);
}
else if(m_tag == RankingLayerBase::TAG_YMZ)
{
Sprite* zjym_lb = Sprite::create("zuijinhuodeyangmu-01.png");
zjym_lb->setPosition(Vec2(winSize.width * 0.5f + 130, winSize.height - CHILD_OFFSET_Y - 100));
zjym_lb->setScale(0.55f);
addChild(zjym_lb, 1);
Sprite* zymz_lb = Sprite::create("zonghuodeyangmu-01.png");
zymz_lb->setPosition(Vec2(winSize.width * 0.5f + 280, winSize.height - CHILD_OFFSET_Y - 100));
zymz_lb->setScale(0.55f);
addChild(zymz_lb, 1);
btn1 = Button::createBtnWithSpriteFrameName("kuang1_2.png", false);
btn1->setPosition(Vec2(30, winSize.height - CHILD_OFFSET_Y - 200));
btn1->setScaleX(0.55f);
btn1->setScaleY(0.8f);
btn1->setOnClickCallback(callfuncO_selector(RankingLayerChild::clickBtn1), this);
btn1->setPressIcon("kuang1_1.png", false);
btn1->setPressIconShow(true);
addChild(btn1, 1, 111);
current_click_index = 1;
RichLabel* lab1 = RichLabel::create(Global::getInstance()->getString("50"), "STXingkai.ttf", 40.0f, Size(50, 100),false,false);
lab1->setAnchorPoint(Vec2::ZERO);
lab1->setPosition(Vec2(15, winSize.height - CHILD_OFFSET_Y - 250));
addChild(lab1, 2);
btn2 = Button::createBtnWithSpriteFrameName("kuang1_2.png", false);
btn2->setPosition(Vec2(30, winSize.height - CHILD_OFFSET_Y - 450));
btn2->setScaleX(0.55f);
btn2->setScaleY(0.8f);
btn2->setOnClickCallback(callfuncO_selector(RankingLayerChild::clickBtn2), this);
btn2->setPressIcon("kuang1_1.png", false);
addChild(btn2, 1, 112);
RichLabel* lab2 = RichLabel::create(Global::getInstance()->getString("51"), "STXingkai.ttf", 40.0f, Size(50, 100),false,false);
lab2->setAnchorPoint(Vec2::ZERO);
lab2->setPosition(Vec2(15, winSize.height - CHILD_OFFSET_Y - 520));
addChild(lab2, 2);
}
/*
else if(m_tag == RankingLayerBase::TAG_XZZ)
{
Sprite* zjzz_lb = Sprite::create("zuijinhuodeshu-01.png");
zjzz_lb->setPosition(Vec2(winSize.width * 0.5f + 130, winSize.height - CHILD_OFFSET_Y - 100));
zjzz_lb->setScale(0.55f);
addChild(zjzz_lb, 1);
Sprite* zzz_lb = Sprite::create("zonghuodeshu-01.png");
zzz_lb->setPosition(Vec2(winSize.width * 0.5f + 280, winSize.height - CHILD_OFFSET_Y - 100));
zzz_lb->setScale(0.55f);
addChild(zzz_lb, 1);
btn1 = Button::createBtnWithSpriteFrameName("kuang1_2.png", false);
btn1->setPosition(Vec2(30, winSize.height - CHILD_OFFSET_Y - 200));
btn1->setScaleX(0.55f);
btn1->setScaleY(0.8f);
btn1->setOnClickCallback(callfuncO_selector(RankingLayerChild::clickBtn1), this);
btn1->setPressIcon("kuang1_1.png", false);
btn1->setPressIconShow(true);
addChild(btn1, 1, 111);
current_click_index = 1;
RichLabel* lab1 = RichLabel::create("上海榜", "STXingkai.ttf", 40.0f, Size(50, 100),false,false);
lab1->setAnchorPoint(Vec2::ZERO);
lab1->setPosition(Vec2(10, winSize.height - CHILD_OFFSET_Y - 230));
addChild(lab1, 2);
btn2 = Button::createBtnWithSpriteFrameName("kuang1_2.png", false);
btn2->setPosition(Vec2(30, winSize.height - CHILD_OFFSET_Y - 450));
btn2->setScaleX(0.55f);
btn2->setScaleY(0.8f);
btn2->setOnClickCallback(callfuncO_selector(RankingLayerChild::clickBtn2), this);
btn2->setPressIcon("kuang1_1.png", false);
addChild(btn2, 1, 112);
RichLabel* lab2 = RichLabel::create("总榜", "STXingkai.ttf", 40.0f, Size(50, 100),false,false);
lab2->setAnchorPoint(Vec2::ZERO);
lab2->setPosition(Vec2(10, winSize.height - CHILD_OFFSET_Y - 500));
addChild(lab2, 2);
}*/
else if(m_tag == RankingLayerBase::TAG_JSS)
{
Sprite* zjjs_lb = Sprite::create("zuijinjishashu-01.png");
zjjs_lb->setPosition(Vec2(winSize.width * 0.5f + 130, winSize.height - CHILD_OFFSET_Y - 100));
zjjs_lb->setScale(0.55f);
addChild(zjjs_lb, 1);
Sprite* zjs_lb = Sprite::create("zongjishashu-01.png");
zjs_lb->setPosition(Vec2(winSize.width * 0.5f + 280, winSize.height - CHILD_OFFSET_Y - 100));
zjs_lb->setScale(0.55f);
addChild(zjs_lb, 1);
btn1 = Button::createBtnWithSpriteFrameName("kuang1_2.png", false);
btn1->setPosition(Vec2(30, winSize.height - CHILD_OFFSET_Y - 160));
btn1->setScale(0.55f);
btn1->setOnClickCallback(callfuncO_selector(RankingLayerChild::clickBtn1), this);
btn1->setPressIcon("kuang1_1.png", false);
btn1->setPressIconShow(true);
addChild(btn1, 1, 111);
current_click_index = 1;
RichLabel* lab1 = RichLabel::create(Global::getInstance()->getString("53"), "STXingkai.ttf", 36.0f, Size(50, 100),false,false);
lab1->setAnchorPoint(Vec2::ZERO);
lab1->setPosition(Vec2(15, winSize.height - CHILD_OFFSET_Y - 210));
addChild(lab1, 2);
btn2 = Button::createBtnWithSpriteFrameName("kuang1_2.png", false);
btn2->setPosition(Vec2(30, winSize.height - CHILD_OFFSET_Y - 330));
btn2->setScale(0.55f);
btn2->setOnClickCallback(callfuncO_selector(RankingLayerChild::clickBtn2), this);
btn2->setPressIcon("kuang1_1.png", false);
addChild(btn2, 1, 112);
RichLabel* lab2 = RichLabel::create(Global::getInstance()->getString("54"), "STXingkai.ttf", 36.0f, Size(50, 100),false,false);
lab2->setAnchorPoint(Vec2::ZERO);
lab2->setPosition(Vec2(15, winSize.height - CHILD_OFFSET_Y - 380));
addChild(lab2, 2);
btn3 = Button::createBtnWithSpriteFrameName("kuang1_2.png", false);
btn3->setPosition(Vec2(30, winSize.height - CHILD_OFFSET_Y - 500));
btn3->setScale(0.55f);
btn3->setOnClickCallback(callfuncO_selector(RankingLayerChild::clickBtn3), this);
btn3->setPressIcon("kuang1_1.png", false);
addChild(btn3, 1, 113);
RichLabel* lab3 = RichLabel::create(Global::getInstance()->getString("55"), "STXingkai.ttf", 36.0f, Size(50, 100),false,false);
lab3->setAnchorPoint(Vec2::ZERO);
lab3->setPosition(Vec2(15, winSize.height - CHILD_OFFSET_Y - 555));
addChild(lab3, 2);
}
TableView* tableView = TableView::create(this, getTableSize());
//tableView->setTouchPriority(MAIN_TABLEVIEW_ACTIVE);
tableView->setDirection(ScrollView::Direction::VERTICAL);
//tableView->setPosition(Vec2(winSize.width * 0.5f - CHILD_OFFSET_X, winSize.height * 0.5f - CHILD_OFFSET_Y));
tableView->setPosition(Vec2(40,0));
tableView->setVerticalFillOrder(TableView::VerticalFillOrder::TOP_DOWN);
tableView->setDelegate(this);
addChild(tableView, 2, 101);
tableView->reloadData();
}
void RankingLayerChild::resetBtnState()
{
RankingLayerBase* base = dynamic_cast<RankingLayerBase*>(getParent());
RankingLayerBase::R_TAG tag = base->GetCurrentTag();
if(tag == RankingLayerBase::TAG_JHDW || tag == RankingLayerBase::TAG_CBZ || tag == RankingLayerBase::TAG_JSS)
{
btn1->setPressIconShow(false);
btn2->setPressIconShow(false);
btn3->setPressIconShow(false);
}
else
{
btn1->setPressIconShow(false);
btn2->setPressIconShow(false);
}
}
void RankingLayerChild::clickBtn1(cocos2d::Ref *pSender)
{
GameVoice::getInstance()->playClickBtnVoive();
Button* btn = dynamic_cast<Button*>(pSender);
int index = btn->getTag()-110;
if(index == current_click_index)
return;
resetBtnState();
current_click_index = index;
btn1->setPressIconShow(true);
// 掉协议
RankingLayerBase* base = dynamic_cast<RankingLayerBase*>(getParent());
m_tag = base->GetCurrentTag();
if(m_tag == RankingLayerBase::TAG_JHDW)
{
((MainScene*)getParent()->getParent())->reqRanks(1, 1);
}
if(m_tag == RankingLayerBase::TAG_CBZ)
{
((MainScene*)getParent()->getParent())->reqRanks(2, 1);
}
if(m_tag == RankingLayerBase::TAG_YMZ)
{
((MainScene*)getParent()->getParent())->reqRanks(3, 1);
}
/*
if(m_tag == RankingLayerBase::TAG_XZZ)
{
((MainScene*)getParent()->getParent())->reqRanks(4, 1);
}
*/
if(m_tag == RankingLayerBase::TAG_JSS)
{
((MainScene*)getParent()->getParent())->reqRanks(5, 1);
}
}
void RankingLayerChild::clickBtn2(cocos2d::Ref *pSender)
{
GameVoice::getInstance()->playClickBtnVoive();
Button* btn = dynamic_cast<Button*>(pSender);
int index = btn->getTag() - 110;
if(index == current_click_index)
return;
resetBtnState();
current_click_index = index;
btn2->setPressIconShow(true);
RankingLayerBase* base = dynamic_cast<RankingLayerBase*>(getParent());
m_tag = base->GetCurrentTag();
if(m_tag == RankingLayerBase::TAG_JHDW)
{
((MainScene*)getParent()->getParent())->reqRanks(1, 4);
}
if(m_tag == RankingLayerBase::TAG_CBZ)
{
((MainScene*)getParent()->getParent())->reqRanks(2, 2);
}
if(m_tag == RankingLayerBase::TAG_YMZ)
{
((MainScene*)getParent()->getParent())->reqRanks(3, 4);
}
/*
if(m_tag == RankingLayerBase::TAG_XZZ)
{
((MainScene*)getParent()->getParent())->reqRanks(4, 4);
}
*/
if(m_tag == RankingLayerBase::TAG_JSS)
{
((MainScene*)getParent()->getParent())->reqRanks(5, 2);
}
}
void RankingLayerChild::clickBtn3(cocos2d::Ref *pSender)
{
GameVoice::getInstance()->playClickBtnVoive();
Button* btn = dynamic_cast<Button*>(pSender);
int index = btn->getTag() - 110;
if(index == current_click_index)
return;
resetBtnState();
current_click_index = index;
btn3->setPressIconShow(true);
if(m_tag == RankingLayerBase::TAG_JHDW)
{
((MainScene*)getParent()->getParent())->reqRanks(1, 5);
}
if(m_tag == RankingLayerBase::TAG_CBZ)
{
((MainScene*)getParent()->getParent())->reqRanks(2, 4);
}
if(m_tag == RankingLayerBase::TAG_JSS)
{
((MainScene*)getParent()->getParent())->reqRanks(5, 4);
}
}
Size RankingLayerChild::getTableSize()
{
return Size(winSize.width - 2 * CHILD_OFFSET_X, winSize.height - 2 * CHILD_OFFSET_Y - 40);
}
void RankingLayerChild::tableCellTouched(cocos2d::extension::TableView *table, cocos2d::extension::TableViewCell *cell)
{
int idx = cell->getIdx();
TestRank info = m_atts[idx];
((MainScene*)getParent()->getParent())->reqRole(info.m_id);
}
TableViewCell* RankingLayerChild::tableCellAtIndex(cocos2d::extension::TableView *table, ssize_t idex)
{
TableViewCell* cell = table->dequeueCell();
if(!cell)
{
cell = new TableViewCell();
cell->autorelease();
Node* cellNode = Node::create();
//cellNode->setAnchorPoint(Vec2::ZERO);
cellNode->setPosition(Vec2(winSize.width * 0.5f - CHILD_OFFSET_X, 0));
createTableViewCell(cellNode, table, idex);
cellNode->setTag(100);
cell->addChild(cellNode, 20);
}
else
{
Node* cellNode = (Node*)cell->getChildByTag(100);
cellNode->removeAllChildrenWithCleanup(true);
createTableViewCell(cellNode, table, idex);
}
return cell;
}
void RankingLayerChild::createTableViewCell(cocos2d::Node *cell, cocos2d::extension::TableView *table, int idex)
{
int left = idex % 2;
Sprite* table_bg = NULL;
if(left == 0)
table_bg = Sprite::create("dikuangbaixian-01.png");
else
table_bg = Sprite::create("dikuangbaixian-01.png");
if(table)
{
table_bg->setScaleX(2.0);
cell->addChild(table_bg,1);
TestRank info = m_atts[idex];
char temp[8];
sprintf(temp, "%d", info.m_rank);
CCLabelTTF* index = CCLabelTTF::create(temp, "STXingkai.ttf", 29);
index->setColor(Color3B(255, 255, 255));
index->setPosition(Vec2( -430, 30));
cell->addChild(index, 1);
char temp1[32];
Sprite* icon;
CirCularNode* iconCir;
if(info.m_iconDex < 101)
{
Texture2D* tex = ExchangeInfo::GetTextureForData(info.m_iconStr.c_str());
icon = Sprite::createWithTexture(tex);
icon->setScale(0.75f);
iconCir = CirCularNode::create(25, icon);
}
else
{
sprintf(temp1, "hero_%d.png", info.m_iconDex);
icon = Sprite::create(temp1);
icon->setScale(0.2f);
iconCir = CirCularNode::create(25, icon);
}
iconCir->setPosition(Vec2(-320, 32));
cell->addChild(iconCir, 1);
if (info.m_sex == 0) {
Sprite* sex = Sprite::create("male.png");
sex->setPosition(Vec2(-260, 30));
sex->setScale(0.8f);
cell->addChild(sex, 1);
}else{
Sprite* sex = Sprite::create("female.png");
sex->setPosition(Vec2(-260, 30));
sex->setScale(0.8f);
cell->addChild(sex, 1);
}
if (info.m_name == "") {
char namlab[64] = {0};
sprintf(namlab, "S%d",info.m_id);
info.m_name = namlab;
}
CCLabelTTF* nick_name = CCLabelTTF::create(info.m_name.c_str(), "STXingkai.ttf", 29);
nick_name->setColor(Color3B(255, 255, 255));
nick_name->setAnchorPoint(Vec2(0,0));
nick_name->setPosition(Vec2(-200, 10));
cell->addChild(nick_name, 1);
if(m_tag == RankingLayerBase::TAG_JHDW)
{
duanweiInfo duan = Resource::sharedResource()->GetDuanweiInfo(info.m_duanwei);
icon = Sprite::create(duan.icon);
icon->setPosition(Vec2(130, 30));
icon->setScale(0.3f);
cell->addChild(icon, 1);
CCLabelTTF* rank = CCLabelTTF::create(duan.name, "STXingkai.ttf", 29);
rank->setColor(Color3B(255, 255, 255));
rank->setAnchorPoint(Vec2(0,0));
rank->setPosition(Vec2(150, 10));
cell->addChild(rank, 1);
icon = Sprite::create("hecheng-xx-02.png");
icon->setScale(0.6f);
icon->setPosition(Vec2(230, 30));
cell->addChild(icon, 2);
sprintf(temp1, "%d", info.m_xing);
rank = CCLabelTTF::create(temp1, "STXingkai.ttf", 29);
rank->setColor(Color3B(255, 255, 255));
rank->setAnchorPoint(Vec2(0,0));
rank->setPosition(Vec2(250, 10));
cell->addChild(rank, 1);
}
else
{
CCLabelTTF* rank1 = CCLabelTTF::create(info.m_zjrs.c_str(), "STXingkai.ttf", 29);
rank1->setColor(Color3B(255, 255, 255));
rank1->setAnchorPoint(Vec2(0,0));
rank1->setPosition(Vec2(120, 10));
cell->addChild(rank1, 1);
CCLabelTTF* rank2 = CCLabelTTF::create(info.m_zcbs.c_str(), "STXingkai.ttf", 29);
rank2->setColor(Color3B(255, 255, 255));
rank2->setAnchorPoint(Vec2(0,0));
rank2->setPosition(Vec2(260, 10));
cell->addChild(rank2, 1);
}
// CCLabelTTF* duration = CCLabelTTF::create(info.m_state.c_str(), "华文行楷", 29);
// duration->setColor(Color3B(255, 255, 255));
// //duration->setAnchorPoint(Vec2(0,0));
// duration->setPosition(Vec2(800 - size.width * 0.5f, 0));
// cell->addChild(duration, 1);
//
// if(m_tag == RelationShipBase::TAG_ATTENTION || m_tag == RelationShipBase::TAG_FRIEND)
// {
// CCLabelTTF* rank = CCLabelTTF::create(info.m_dest.c_str(), "华文行楷", 29);
// rank->setColor(Color3B(255, 255, 255));
// rank->setAnchorPoint(Vec2(0,0));
// rank->setPosition(Vec2(400 - size.width * 0.5f, -20));
// cell->addChild(rank, 1);
// }
// else if(m_tag == RelationShipBase::TAG_ENEMY)
// {
// CCLabelTTF* rank = CCLabelTTF::create(info.m_times.c_str(), "华文行楷", 29);
// rank->setColor(Color3B(255, 255, 255));
// rank->setAnchorPoint(Vec2(0,0));
// rank->setPosition(Vec2(480 - size.width * 0.5f, -20));
// cell->addChild(rank, 1);
// }
}
}
Size RankingLayerChild::cellSizeForTable(cocos2d::extension::TableView *table)
{
Size tableSize = getTableSize();
return Size(tableSize.width, tableSize.height / 6);
}
ssize_t RankingLayerChild::numberOfCellsInTableView(cocos2d::extension::TableView *table)
{
return (int)m_atts.size();
}
void RankingLayerChild::scrollViewDidScroll(cocos2d::extension::ScrollView *view)
{
}
void RankingLayerChild::scrollViewDidZoom(cocos2d::extension::ScrollView *view)
{
}
|
8c1aa98a0329ca1f40e921603b405480ec440681
|
24bac176ec2543a1c2f77ebb11af446d561437e4
|
/Exercicio30.cpp
|
ad1a6b028b879d0283fac83026975d22e7a857ee
|
[] |
no_license
|
CarlosAbolis/TPA
|
11b1eda0f2072ae5195715b54566d8934cd1ef77
|
487c87012edac3b8cd9a950decfb76d7e90d8224
|
refs/heads/master
| 2020-08-02T23:19:28.951218
| 2019-12-05T23:27:07
| 2019-12-05T23:27:07
| 211,542,050
| 0
| 0
| null | null | null | null |
ISO-8859-1
|
C++
| false
| false
| 341
|
cpp
|
Exercicio30.cpp
|
/*
Função: Exibe exclusivamente a tabuada do número 7.
Autor: Carlos Alberto Gonçalves da Silva Neto
Data: 2019/12/01
Data de alteração: 2019/12/01
*/
#include<iostream>
#include<locale.h>
int main(){
int numero = 0;
setlocale(LC_ALL,"");
for(numero = 0;numero <= 10; numero++){
printf("%i x 7 = %i \n", numero, numero*7);
}
}
|
d3380e165d25a42c365a1bb8417cf431b2c3095a
|
a2c1593fa7aeb6cd3bc7688229f672b86b3414e8
|
/PriorityQueue/PriorityQueueOnHeap/PriorityQ.hpp
|
cfcc68330dd90150a523cf180709cd1958b24b57
|
[] |
no_license
|
Anastasiya999/DataStructures
|
d686f8e85b45042c8b7d839875096bc51db4e312
|
a32236fe94e9aa4b960ef2246bbc70b6b0298a2c
|
refs/heads/master
| 2023-03-17T14:34:15.385537
| 2021-03-09T19:44:47
| 2021-03-09T19:44:47
| 346,122,896
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 254
|
hpp
|
PriorityQ.hpp
|
#pragma once
#include"Container.h"
using namespace std;
template<typename T,size_t SIZE_OF_QUEUE>
class PriorityQ:public Container<T>{
public:
virtual void Enqueue(T element, int priority)=0;
virtual T DequeueMax()=0;
virtual T FindMax()=0;
};
|
3b301a2aa047abde1f69fcc4e1de9457ba207e08
|
0588e908e8a7a7b87367c036c3df407d88b38700
|
/src/zmqserver/zmqinterface.h
|
895ec22c46b695e856e2fdd593028778fc6b3733
|
[
"MIT"
] |
permissive
|
ShroudProtocol/ShroudX
|
d4f06ef262b28aeb115f1ebbd9432e1744829ab0
|
369c800cbf4a50f4a7cd01f5c155833f1ade3093
|
refs/heads/master
| 2023-04-23T05:12:02.347418
| 2021-05-04T20:28:55
| 2021-05-04T20:28:55
| 302,146,008
| 2
| 4
|
MIT
| 2020-12-07T10:18:21
| 2020-10-07T19:56:30
|
C
|
UTF-8
|
C++
| false
| false
| 1,464
|
h
|
zmqinterface.h
|
// Copyright (c) 2018 Tadhg Riordan, Zcoin Developer
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef ZCOIN_ZMQ_ZMQNOTIFICATIONINTERFACE_H
#define ZCOIN_ZMQ_ZMQNOTIFICATIONINTERFACE_H
#include "validationinterface.h"
#include <string>
#include <map>
#include <boost/thread/thread.hpp>
class CBlockIndex;
class CZMQAbstract;
class CZMQInterface
{
public:
bool Initialize();
void Shutdown();
protected:
std::list<CZMQAbstract*> notifiers;
boost::thread* worker;
};
class CZMQPublisherInterface : public CValidationInterface, CZMQInterface
{
public:
CZMQPublisherInterface();
bool StartWorker();
virtual ~CZMQPublisherInterface();
CZMQPublisherInterface* Create();
protected:
// CValidationInterface
void WalletTransaction(const CTransaction& tx);
void UpdatedBlockTip(const CBlockIndex *pindex);
void NumConnectionsChanged();
void UpdateSyncStatus();
void NotifyShroudnodeList();
void NotifyAPIStatus();
void UpdatedShroudnode(CShroudnode &shroudnode);
void UpdatedMintStatus(std::string update);
void UpdatedSettings(std::string update);
void UpdatedBalance();
};
class CZMQReplierInterface : public CZMQInterface
{
public:
CZMQReplierInterface();
virtual ~CZMQReplierInterface();
CZMQReplierInterface* Create();
};
#endif // ZCOIN_ZMQ_ZMQNOTIFICATIONINTERFACE_H
|
315d53f216adeea86ee41b308306499d943a8465
|
cb584893ed3bc9a633636ca0e209f0cb37773928
|
/alarm_system.ino
|
2ba2aacee16a0a56a0fcb225d4909f1f54fcfc19
|
[] |
no_license
|
macie-kwambai/alarm-system
|
68c127c41376395d9c8227599a8ff80b7db55e8c
|
a558905c3553f103016f7019473376f8f2b15808
|
refs/heads/master
| 2020-03-18T14:16:37.962067
| 2018-05-25T10:23:17
| 2018-05-25T10:23:17
| 134,839,634
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 985
|
ino
|
alarm_system.ino
|
const int out=12;
const int in=13;
const int led=9;
const int buz=10;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(out,OUTPUT);
pinMode(in,INPUT);
pinMode(led,OUTPUT);
pinMode(buz,OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
long dur;
long dis;
digitalWrite(out,LOW);
delayMicroseconds(2);
digitalWrite(out,HIGH);
delayMicroseconds(10);
digitalWrite(out,LOW);
dur=pulseIn(in,HIGH);
dis= (dur/2) / 29.1;
if (dis>50 && dis<=200 )
{
digitalWrite(led,HIGH);
delay(200);
digitalWrite(led,LOW);
delay(200);
}
else {
digitalWrite(led,LOW);
}
if (dis<=50)
{
digitalWrite(led,HIGH);
tone(buz, 1000); // Send 1KHz sound signal...
delay(500); // ...for 1 sec
noTone(buz); // Stop sound...
delay(500); // ...for 1sec
}
else {
digitalWrite(led,LOW);
}
Serial.print(String(dis));
Serial.print("cm");
Serial.println();
delay(100);}
|
5eb977661e59a68dae763f38869d99f3996ad1aa
|
fe53939fb6f9ce92c7d6dd36e8abe09f9fcd2fcd
|
/algorithms/multisets.cpp
|
c74ee128b772db18034c16e95c6ec5ca5679f0ca
|
[] |
no_license
|
AaronBaldwin/personal
|
7721cd4b5f55d0fc627d9560e8603ce7c3a6691f
|
83389d8402d4a571a06ac564f9a8bb5c86e4f238
|
refs/heads/master
| 2021-05-02T09:49:59.332837
| 2019-11-23T09:01:20
| 2019-11-23T09:01:20
| 45,590,082
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 903
|
cpp
|
multisets.cpp
|
#include <cstdlib>
#include <vector>
#include <iostream>
#include <set>
using namespace std;
int main(int argc, char** argv) {
std::multiset<int> s1;
std::multiset<int, greater<int>> s2; // Sort in descending order
s1.insert(5);
s1.insert(2);
s1.insert(4);
s1.insert(4);
s2.insert(15);
s2.insert(14);
s2.insert(17);
s2.insert(10);
s2.insert(15);
// lower_bound finds the lowest index that contains that value
// upper_bound, coincidentally finds the highest index with that value
for(auto i = s2.lower_bound(15); i != s2.end(); i++) {
cout << *i << ", " << endl;
}
// lower_bound finds the next index above 3 in the case where 3 is not present
// it finds 4 in this case.
int val = *s1.lower_bound(3);
cout << " the found lower val is " << val << endl;
val = *s1.upper_bound(3);
cout << " the found upper val is " << val << endl;
return 0;
}
|
ef0772643f28deb179a3f6b5a0cf25311fb111ab
|
a5bbb807323d3d5b16e734fdd47808e40f3c6995
|
/Codeforces/Round 620(Div. 2)/1304E.cpp
|
1bcfe62a3d2d02ec4285bf49d73a86241f3acb97
|
[] |
no_license
|
gagandeepahuja09/Competitive-Programming-Contests
|
a7ad0eb7667cd5fbdb84502a7c82ae41c4ae49ea
|
b080e07281dea54f8fbb7b3097de542cad72d8cb
|
refs/heads/master
| 2021-07-18T16:41:21.409766
| 2020-06-29T12:13:21
| 2020-06-29T12:13:21
| 182,628,398
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,207
|
cpp
|
1304E.cpp
|
#include <bits/stdc++.h>
using namespace std;
#define int long long int
#define vi vector<int>
#define vvi vector<vi>
#define read(a) for(int i = 0; i < n; i++) cin >> a[i];
#define print(a) for(int i = 0; i < n; i++) cout << a[i] << " ";
#define pb push_back
#define ins insert
#define pql priority_queue<int>
#define pqs priority_queue<int, vi, greater<int>>
#define pqlv priority_queue<vi>
#define pqsv priority_queue<vi, vvi, greater<vi>>
#define endl '\n'
#define MOD 998244353
#define MAXN 100001
vvi adj;
int par[MAXN][20];
int depth[MAXN];
void buildLCA(int u, int p) {
depth[u] = depth[p] + 1;
par[u][0] = p;
for(int i = 1; i <= 19; i++) {
par[u][i] = par[par[u][i - 1]][i - 1];
}
for(int v : adj[u]) {
if(v != p) {
buildLCA(v, u);
}
}
}
int lcaLen(int a, int b) {
if(depth[a] > depth[b])
swap(a, b);
int len = 0;
for(int i = 19; i >= 0; i--) {
if(depth[par[b][i]] >= depth[a]) {
b = par[b][i];
len += (1 << i);
}
}
if(a == b)
return len;
for(int i = 19; i >= 0; i--) {
if(par[a][i] != par[b][i]) {
a = par[a][i];
b = par[b][i];
len += (1 << (i + 1));
}
}
return len + 2;
}
signed main() {
int t = 1;
// cin >> t;
while(t--) {
int n, q;
cin >> n;
adj.resize(n + 1);
for(int i = 0; i < n - 1; i++) {
int u, v;
cin >> u >> v;
adj[u].pb(v);
adj[v].pb(u);
}
buildLCA(1, 0);
cin >> q;
while(q--) {
bool ans = false;
int a, b, x, y, k;
cin >> x >> y >> a >> b >> k;
int with = lcaLen(a, b);
if(with <= k && with % 2 == k % 2)
ans = true;
int op1 = lcaLen(a, x) + 1 + lcaLen(y, b);
if(op1 <= k && op1 % 2 == k % 2)
ans = true;
int op2 = lcaLen(a, y) + 1 + lcaLen(x, b);
if(op2 <= k && op2 % 2 == k % 2)
ans = true;
if(ans) cout << "YES";
else cout << "NO";
cout << endl;
}
}
}
|
8560619e133ec2a14b13fc695e2d2d142339e668
|
184b98294943516c8575f123e6aeef348d88050d
|
/test3/d-parenteses.cpp
|
02166515b0f21821e2f4a0c8a057c8dd059e4dc6
|
[] |
no_license
|
cicerocipriano/Programming-1
|
98220e7603c1359a1caed8baf3057c09ab5964fb
|
bb4c6c9ceae1d38e5b539d9ff73724c764e63d4e
|
refs/heads/main
| 2023-03-20T20:34:36.032047
| 2021-03-11T20:30:37
| 2021-03-11T20:30:37
| 342,403,571
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,065
|
cpp
|
d-parenteses.cpp
|
#include <iostream>
#include <cstring>
using namespace std;
void check_pare (char *a) {
int pos1 = -1, pos2 = -1;
for (int i = 0; a[i] != '\0'; i++) {
if (a[i] == '(') {
pos1 = i;
a[i] = 64;
break;
}
}
for (int i = 0; a[i] != '\0'; i++) {
if (a[i] == ')') {
pos2 = i;
a[i] = 64;
break;
}
}
if (pos1 < 0 || pos2 < 0 || pos1 > pos2) {
return;
}
check_pare(a);
}
void resposta (char *a) {
for (int i = 0; a[i] != '\0'; i++) {
if (a[i] == '(' || a[i] == ')') {
cout << "NAO" << endl;
return;
}
}
int c = 0;
for (int i = 0; a[i] != '\0'; i++) {
if (a[i] == 64) {
c++;
}
}
if (c % 2 == 0) {
cout << "SIM" << endl;
}
else {
cout << "NAO" << endl;
}
return;
}
int main (int argc, char **argv) {
char a[101];
cin.getline(a,101);
check_pare(a);
resposta(a);
return 0;
}
|
a19c647dcabc85654df29448a83393f15307f540
|
619054eaea6b93fb3ad354606029363817088285
|
/rai/rai_token/crosschain/parsers/base.hpp
|
a022db3dfcf256a3811ab2fefa96f288cd912a4e
|
[
"MIT"
] |
permissive
|
raicoincommunity/Raicoin
|
e3d1047b30cde66706b994a3b31e0b541b07c79f
|
ebc480caca04caebdedbc3afb4a8a0f60a8c895f
|
refs/heads/master
| 2023-09-03T00:39:00.762688
| 2023-08-29T17:01:09
| 2023-08-29T17:01:09
| 210,498,091
| 99
| 16
|
MIT
| 2023-08-29T17:01:11
| 2019-09-24T02:52:27
|
C++
|
UTF-8
|
C++
| false
| false
| 706
|
hpp
|
base.hpp
|
#pragma once
#include <cstdint>
#include <vector>
#include <functional>
#include <rai/common/util.hpp>
#include <rai/rai_token/crosschain/event.hpp>
namespace rai
{
class BaseParser
{
public:
virtual ~BaseParser() = default;
virtual void Run() = 0;
virtual uint64_t Delay() const = 0;
virtual void Status(rai::Ptree&) const = 0;
virtual rai::Chain Chain() const = 0;
virtual std::vector<std::shared_ptr<rai::CrossChainEvent>> Events(
const std::function<bool(const rai::CrossChainEvent&)>&) const = 0;
static constexpr uint64_t MIN_DELAY = 5;
std::function<void(const std::shared_ptr<rai::CrossChainEvent>&, bool)>
event_observer_;
};
} // namespace rai
|
7c667d776bdc9b0f357a10f127a402a35f2782b8
|
7bb0491b44ee3c401201e8220c22aee882be3bfb
|
/src/srp-common.h
|
33f01fa94242b45dfb4c32ae1a3dec6405b0077b
|
[
"BSD-2-Clause"
] |
permissive
|
markyosti/uvpn
|
2530351b12628f7242fbb49456237b10dfdee376
|
2a36dd0977707c92376b8bc5ad692aec6d1b564a
|
refs/heads/master
| 2020-04-11T05:56:03.324125
| 2013-02-28T19:35:40
| 2013-02-28T19:35:40
| 7,915,780
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 659
|
h
|
srp-common.h
|
#ifndef SRP_COMMON_H
# define SRP_COMMON_H
# include "openssl-helpers.h"
class SecurePrimes {
public:
struct Prime {
const char* name;
int generator;
const char* value;
};
SecurePrimes();
~SecurePrimes();
bool ValidIndex(int index) const;
const BigNumber& GetPrime(int index) const;
const BigNumber& GetGenerator(int index) const;
const Prime& GetDescriptor(int index) const;
private:
static const Prime kValidPrimes[];
// The following are treated like a cache. Marked as "mutable" to allow for
// lazy initialization.
mutable BigNumber** generators_;
mutable BigNumber** primes_;
};
#endif /* SRP_COMMON_H */
|
5a405e2c7e530c10336c5de133d516a20a28fb7e
|
90b5c555b4e1ba763e405183a6c5defaba1720bc
|
/Crucible_Game/Map.h
|
18429862899d2c9d0913cf10a685229d3885cbac
|
[] |
no_license
|
AaronCC/The_Crucible
|
b42abc29619c41f43d5bf4f88209eeeb32bbf077
|
7125c66a46971008647a9c7a3c4c0371d148e8e0
|
refs/heads/master
| 2021-04-09T14:26:14.717276
| 2018-04-29T22:21:34
| 2018-04-29T22:21:34
| 125,675,243
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,458
|
h
|
Map.h
|
#ifndef MAP_H
#define MAP_H
#include "Game.h"
#include "Gui.h"
#include "Camera.h"
#include "Helper.h"
#include "Enemy.h"
#include "PathFinder.h"
#include "CaveGen.h"
#include "Loot.h"
#include "Dungeon.h"
#define SHR_SPN_CHANCE 15
class Map
{
public:
std::vector<Enemy*> enemies;
std::vector<Enemy*> aEnemies;
std::vector<Tile> tiles;
std::vector<Enemy*> tEnemies;
std::vector<std::vector<Loot*>> tLoot;
std::vector<Loot*> loot;
std::vector<Tile>* getTiles() { return &tiles; }
int width, height;
sf::Vector2u tileSize;
sf::Vector2i spawnPos;
sf::Vector2f drawSize;
std::vector<sf::Text> hoverText;
std::vector<sf::Text> actionText;
struct Debris {
bool cluster;
bool wall;
std::string texName;
Debris() {}
Debris(bool c, bool w, std::string t) :cluster(c), wall(w), texName(t) {}
};
std::vector<Debris> debris;
struct EnemyBase {
bool melee;
int hp;
float mult;
std::string name, tx_name;
std::pair<bool, int> group;
AbEffect::DamageType dtype;
EnemyBase(bool melee, int hp, std::string name, AbEffect::DamageType dtype, std::pair<bool,int> group, std::string tx_name, float mult) :
melee(melee), hp(hp), name(name), dtype(dtype), group(group), tx_name(tx_name), mult(mult) {};
};
std::vector<EnemyBase> ebases;
int level = 0;
int expCache = 0;
enum Action {
PICKUP,
SHRINE,
NONE
};
Action action;
sf::Vector2i oldMouseIndex;
Tile background;
Tile canSelect;
Tile cantSelect;
ItemGenerator* itemGenerator;
std::vector<Dungeon::Entity> entities;
//Tile player;
Game* game;
Camera* camera;
bool activateObjsAtTile(std::vector<sf::Vector2i> pos);
sf::Vector2i getSelectPos();
sf::Vector2i mouseIndex;
Helper helper;
sf::Vector2i truncLineOfSight(sf::Vector2i from, sf::Vector2i to);
bool hasLineOfSight(sf::Vector2i from, sf::Vector2i to);
void drawL2(sf::RenderWindow & window, float dt, sf::Vector2i pPos);
void drawL3(sf::RenderWindow & window, float dt);
void resizeMiniView(float windowH, float windowW)
{
miniMapView.setViewport(helper.resizeView(windowH, windowW, game->aspectRatio));
}
void draw(sf::RenderWindow & window, float dt);
sf::Vector2i globalToTilePos(sf::Vector2f global);
void update(float dt);
void updateHoverText();
void handleInput(sf::Event event);
void eraseLoot(sf::Vector2i pos);
void resolveAction(Player * player);
void updateActionText(sf::Vector2i playerPos);
std::vector<sf::Vector2i> entityOccToClear;
// std::vector<Enemy*> getEnemiesAtPoint(sf::Vector2i point);
std::vector<AbEffect::Effect> updateEntityAI(float tickCount, sf::Vector2i pPos, PathFinder* pf);
void resolveEntityAI(float tickCount);
void loadCave();
void genCaveEntities(int eCount, std::vector<sf::Vector2i> locs, std::vector<sf::Vector2i> oldLocs);
sf::RectangleShape youAreHere;
sf::View miniMapView;
bool showMiniMap;
void Map::loadDungeon();
void populateDungeon(bool debris);
bool spawnShrine(Dungeon::Entity e);
bool spawnBossGroupInRoom(Dungeon::Entity e);
bool spawnDebrisInRoom(Dungeon::Entity e);
bool spawnEnemyInRoom(Dungeon::Entity e);
Enemy * getEnemyAt(int x, int y);
Tile * getTile(int x, int y);
void Map::parseEbases()
{
std::string line;
std::ifstream texFile("media/Enemies.txt");
if (texFile.is_open())
{
while (std::getline(texFile, line))
{
if (line[0] == ';')
continue;
std::string name = "", tx_name;
bool melee, group;
int hp, dtype, groupSize;
float mult;
std::istringstream iss(line);
std::vector<std::string> results(std::istream_iterator<std::string>{iss},
std::istream_iterator<std::string>());
std::string word = results[0];
name = word;
int i = 0;
while (word[word.size() - 1] != ';')
{
i++;
word = results[i];
name += " " + word;
}
name = name.substr(0, name.size() - 1);
tx_name = results[1+i];
std::stringstream ss(results[2+i]);
ss >> melee;
ss = std::stringstream(results[3+i]);
ss >> hp;
ss = std::stringstream(results[4+i]);
ss >> dtype;
ss = std::stringstream(results[5+i]);
ss >> group;
ss = std::stringstream(results[6+i]);
ss >> groupSize;
ss = std::stringstream(results[7+i]);
ss >> mult;
ebases.push_back(EnemyBase(melee, hp, name, (AbEffect::DamageType)dtype, { group,groupSize }, tx_name, mult));
}
}
}
Map(Game* game, Camera* camera);
~Map();
private:
Gui buttons;
sf::Font testFont;
};
#endif /* MAP_H */
|
516a4e7488d948dcb11a8005e611b527f0c3bfd0
|
a586865e3768cd41e84bcae0e73cdabb2a50f592
|
/src/gui/HotkeyPickerDrawer.h
|
b6d9ddbf8aac0c16b85cf5d8cd18bceaafbbbb2f
|
[
"MIT"
] |
permissive
|
darksworm/hksel
|
cc0b8f32e717b1c392ea99d254a12cad08df8a3f
|
eb998343d01cc37a72e9ec9104cc3d0731f764a9
|
refs/heads/master
| 2020-05-05T10:17:16.965343
| 2019-09-21T13:08:44
| 2019-09-21T13:08:44
| 179,938,320
| 1
| 0
|
MIT
| 2019-07-01T07:10:24
| 2019-04-07T08:37:37
|
C++
|
UTF-8
|
C++
| false
| false
| 1,141
|
h
|
HotkeyPickerDrawer.h
|
#pragma once
#include <X11/Xutil.h>
#include <X11/Xlib.h>
#include <X11/extensions/xf86vmode.h>
#include <functional>
#include <memory>
#include "../hotkey/hotkey.h"
#include "Shape.h"
#include "drawer/ShapeDrawer.h"
#include "WindowManager.h"
#include "drawer/ShapeDrawerFactory.h"
enum class HotkeyPickerMove {
NONE,
LEFT,
RIGHT,
UP,
DOWN,
HOME,
END,
LINE
};
class HotkeyPickerDrawer {
private:
WindowManager *windowManager;
ShapeProperties shapeProperties;
ShapeDrawer* shapeDrawer;
Shape *selectedShape;
int page = 0;
std::vector<Hotkey> *hotkeys;
std::vector<Shape> shapes;
std::vector<Hotkey>::iterator getPageHotkeyStart();
int getHotkeyPage(long index);
void goToHotkey(long hotkeyIdx);
std::function<bool(Hotkey*)> filter;
public:
HotkeyPickerDrawer(WindowManager* windowManager, ShapeType shapeType, std::vector<Hotkey> *hotkeys);
void drawFrame(Hotkey* selectedHotkey);
bool move(HotkeyPickerMove move, unsigned int steps = 1);
void setFilter(std::function<bool(Hotkey *)> filter);
Hotkey* getSelectedHotkey();
};
|
bb576ff1ea2727e926ff385099c46983748e6dcc
|
15d1c07c71fe81d132bbd5b81005df6b59a5dc21
|
/software/ai/hl/stp/tactic/pass_simple.cpp
|
84ef12564555da718b407ef5f6f70bd087ed6e17
|
[] |
no_license
|
UBC-Thunderbots/Software-Deprecated
|
76d9a429b7fc57e4b676904d8ef36b60461ea476
|
1ad5f5a3fdc2eed79e6a364cac3e51061ba5d2b5
|
refs/heads/master
| 2020-08-10T06:54:54.925782
| 2019-10-10T21:42:14
| 2019-10-10T21:42:14
| 214,287,740
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 13,443
|
cpp
|
pass_simple.cpp
|
#include "ai/hl/stp/tactic/pass_simple.h"
#include "ai/hl/stp/tactic/util.h"
#include "ai/hl/stp/action/shoot.h"
#include "ai/hl/stp/action/move.h"
#include "ai/hl/stp/evaluation/shoot.h"
#include "ai/hl/stp/evaluation/enemy_risk.h"
#include "ai/hl/stp/evaluation/friendly_capability.h"
#include "ai/hl/stp/predicates.h"
#include "ai/hl/stp/param.h"
#include "ai/hl/util.h"
#include "ai/util.h"
#include "geom/util.h"
#include "geom/angle.h"
#include "geom/point.h"
#include "util/dprint.h"
#include "ai/hl/stp/param.h"
#include "ai/hl/stp/gradient_approach/PassInfo.h"
#include "ai/hl/stp/gradient_approach/ratepass.h"
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <assert.h>
using namespace AI::HL::STP::Tactic;
using namespace AI::HL::STP::Evaluation;
using namespace AI::HL::W;
using namespace AI::HL::STP::GradientApproach;
namespace Action = AI::HL::STP::Action;
using AI::HL::STP::Coordinate;
using AI::HL::STP::min_pass_dist;
namespace {
Angle getOnetimeShotDirection(World world, Player player, Point pos){
Point shot = get_best_shot(world, player);
Angle shotDir = (shot - pos).orientation();
Point shotVector = Point::of_angle(shotDir);
Point botVector = shotVector.norm();
Point ballVel = world.ball().velocity();
Point lateralVel = ballVel - (ballVel.dot(-botVector))*(-botVector);
double lateralSpeed = 0.3*lateralVel.len();
double kickSpeed = 5.5;
Angle shotOffset = Angle::asin(lateralSpeed/kickSpeed);
//check which direction the ball is going in so we can decide which direction to apply the offset in
if(lateralVel.dot(shotVector.rotate(Angle::quarter())) > 0){
// need to go clockwise
shotOffset = - shotOffset;
}
return shotDir + shotOffset;
}
Point passer_pos;
Point targets[3];
Point kicktarget;
double kickspeed;
Point intercept_pos;
Point passee_pos;
Angle passee_angle;
bool ball_kicked = false;
int ticks_since_kick =0;
class PasserSimple final : public Tactic {
public:
explicit PasserSimple(World world, bool shoot_on_net) : Tactic(world), kick_attempted(false), shoot_if_possible(shoot_on_net) {
ball_kicked = false;
ticks_since_kick = 0;
}
private:
bool shoot_if_possible;
bool kick_attempted;
bool done() const {
if(kick_attempted && player().autokick_fired()){
ball_kicked = true;
return true;
}
return false;
}
void player_changed() {}
bool fail() const {
//TODO: add failure condition
//TODO: add this back in (look at svn history)
return false;
}
Player select(const std::set<Player> &players) const {
Player passer;
for(auto it = players.begin(); it != players.end(); it++)
{
if(it->get_impl()->pattern() == FAVOURITE_BOT)
{
passer = *it;
}
}
if(!passer)
{
passer = *std::min_element(players.begin(), players.end(), AI::HL::Util::CmpDist<Player>(world.ball().position()));
}
passer_pos = passer.position();
if(world.ball().velocity().len() < 0.3){
PassInfo::Instance().setAltPasser(world.ball().position(), Angle::zero());
}else{
PassInfo::Instance().setAltPasser(passer.position(), passer.orientation());
}
return passer;
}
void execute(caller_t& ca) {
PassInfo::passDataStruct pass = PassInfo::Instance().getBestPass();
PassInfo::passDataStruct testPass;
targets[0] = Point(pass.params.at(0), pass.params.at(1));
PassInfo::worldSnapshot snapshot = PassInfo::Instance().convertToWorldSnapshot(world);
double currentPassScore = ratePass(snapshot,Point(pass.params.at(0), pass.params.at(1)), pass.params.at(2), pass.params.at(3));
double testPassScore;
double time_since_start = 0.0;
while(time_since_start < 10.0){
time_since_start += 0.03;
testPass = PassInfo::Instance().getBestPass();
PassInfo::worldSnapshot snapshot = PassInfo::Instance().convertToWorldSnapshot(world);
currentPassScore = ratePass(snapshot,Point(pass.params.at(0), pass.params.at(1)), pass.params.at(2), pass.params.at(3));
testPassScore = ratePass(snapshot,Point(testPass.params.at(0), testPass.params.at(1)), testPass.params.at(2), testPass.params.at(3));
printf(", pass score: %f",currentPassScore);
if(testPassScore > 1.8*currentPassScore || (testPassScore > 0.08 && currentPassScore < 0.08)){
pass = testPass;
targets[0] = Point(pass.params.at(0), pass.params.at(1));
currentPassScore = testPassScore;
printf("SWITCHING SPOTSSS!");
}
if(testPassScore > 0.08 && (passee_pos-targets[0]).len() < 1.3*Robot::MAX_RADIUS){//(pass.params.at(2) < 0.6 ||
kick_attempted = true;
passer_pos = world.ball().position();
kicktarget = passee_pos; //targets[0];
kickspeed = 4.0;//pass.params.at(3);
Action::shoot_target(ca, world, player(), targets[0], kickspeed);
}else{
printf("delay time too large: %f",pass.params.at(2));
Action::get_behind_ball(ca, world, player(), targets[0]);
// player().flags(AI::Flags::calc_flags(world.playtype()) | AI::Flags::MoveFlags::AVOID_BALL_TINY);
// Action::move(ca, world, player(), world.ball().position() - (targets[0] - world.ball().position()).norm(0.2), (targets[0] - world.ball().position()).orientation());
}
yield(ca);
}
// Just chip it up the field
targets[0] = Point(3.1, 0.0);
while(true){
double shootScore = get_best_shot_pair(world, player()).second.to_degrees();
if(shoot_if_possible && shootScore > 2.0){
Action::shoot_goal(ca, world, player());
}else{
kick_attempted = true;
Action::shoot_target(ca, world, player(), targets[0], (world.ball().position() - targets[0]).len()/2.0, true);
passer_pos = world.ball().position();
kicktarget = targets[0];
kickspeed = 2.0;
}
yield(ca);
}
}
Glib::ustring description() const {
return u8"passer-simple";
}
void draw_overlay(Cairo::RefPtr<Cairo::Context> ctx) const {
ctx->set_source_rgba(1.0, 1.0, 1.0, 4.0);
ctx->arc(targets[0].x, targets[0].y, 0.08, 0.0, 2*M_PI);
ctx->fill();
}
};
class PasseeSimple final : public Tactic {
public:
PasseeSimple(World world, unsigned index) : Tactic(world), index(index) {
}
private:
unsigned index;
Player select(const std::set<Player> &players) const {
Player passee;
if(index > 0 || ball_kicked == true){
std::vector<PassInfo::passDataStruct> bestPasses = PassInfo::Instance().getCurrentPoints();
if(bestPasses.size() > index && bestPasses.at(index).quality > 0.01){
targets[index] = Point(bestPasses.at(index).params.at(0), bestPasses.at(index).params.at(1));
std::cout << "target "<< index << ": " << targets[index].x << ", " << targets[index].y;
std::cout << "quality "<< bestPasses.at(index).quality;
}else{
targets[index] = world.ball().position() + 1.5*index*(world.field().friendly_goal() - world.ball().position()).norm();
}
}
std::set<Player> good_passees;
for (Player player : players)
{
for (unsigned int i = 0; i < world.working_dribblers.size(); i++)
{
if(player.get_impl()->pattern() == world.working_dribblers[i])
{
good_passees.insert(player);
std::cout << "player " << player.get_impl()->pattern()
<< " has good dribbler" << std::endl;
}
}
}
if(good_passees.size() > 0)
{
passee = *std::min_element(good_passees.begin(), good_passees.end(),
AI::HL::Util::CmpDist<Player>(targets[index]));
std::cout << good_passees.size() << " good passees" << std::endl;
}
else
{
passee = *std::min_element(players.begin(), players.end(),
AI::HL::Util::CmpDist<Player>(targets[index]));
}
if(index==0){
passee_pos = passee.position();
passee_angle = passee.orientation();
}
return passee;
}
void execute(caller_t& ca) {
while(true){
PassInfo::worldSnapshot snapshot = PassInfo::Instance().convertToWorldSnapshot(world);
//double score = get_passee_shoot_score(snapshot, targets[index]);
//std::cout << "shoot score "<< score;
Angle botDir = get_best_shot_pair(world, player()).second;
if(botDir.angle_diff((world.ball().position() - targets[index]).orientation()).to_degrees() >65.0){
botDir = (world.ball().position() - targets[index]).orientation();
}
printf("trying to aim in %f direction", botDir.to_degrees());
Point offset = -Point::of_angle(botDir)*Robot::MAX_RADIUS;
Action::move(ca, world, player(), targets[index] + offset, botDir); // autokick off
yield(ca);
}
}
Glib::ustring description() const {
return u8"passee-simple";
}
};
class PasseeReceive final : public Tactic{
public:
PasseeReceive(World world) : Tactic(world){
}
private:
double timeSinceKick;
~PasseeReceive(){
}
Player select(const std::set<Player> &players) const {
Player passee = *std::min_element(players.begin(), players.end(), AI::HL::Util::CmpDist<Player>(kicktarget));
return passee;
}
bool done() const {
// if(player() && (player().has_ball() || player().autokick_fired())) return true;
std::cout << "ball speed: "<< world.ball().velocity().len();
if(world.ball().velocity().len() < 0.1 && timeSinceKick > 0.5){
return true;
}
//todo: put back in fail section
Point expectedPos = passer_pos + (kicktarget - passer_pos).norm()*kickspeed*timeSinceKick;
if((world.ball().position() - expectedPos).len() > 4.0){
return true;
}
return false;
}
bool fail() const {
return false;
}
void draw_overlay(Cairo::RefPtr<Cairo::Context> ctx) const {
/*ctx->set_source_rgba(1.0, 1.0, 1.0, 4.0);
ctx->arc(targets[0].x, targets[0].y, 0.08, 0.0, 2*M_PI);
ctx->fill();
*/
ctx->set_source_rgba(1.0, 0.0, 1.0, 4.0);
ctx->arc(targets[1].x, targets[1].y, 0.08, 0.0, 2*M_PI);
ctx->fill();
ctx->set_source_rgba(1.0, 1.0, 0.0, 4.0);
ctx->arc(targets[2].x, targets[2].y, 0.08, 0.0, 2*M_PI);
ctx->fill();
ctx->set_source_rgba(0.0, 0.0, 0.0, 4.0);
ctx->arc(intercept_pos.x, intercept_pos.y, 0.02, 0.0, 2*M_PI);
ctx->fill();
}
void execute(caller_t& ca){
double shootScore = get_best_shot_pair(world, player()).second.to_degrees();
bool can_shoot = true;//(shootScore > 0.1);
timeSinceKick = 0.03;
while(true){
timeSinceKick += 0.03;
//TODO: add logic for one time shot on net
//TODO: consider moving interception with ball
//maybe could also use the direction kicker is pointing when it is kicked?
intercept_pos = closest_lineseg_point(kicktarget, world.ball().position(), world.ball().position(100));
PassInfo::Instance().setAltPasser(intercept_pos, world.ball().velocity().rotate(Angle::half()).orientation());
//todo: uncomment
PassInfo::passDataStruct pass = PassInfo::Instance().getBestPass();
targets[0] = Point(pass.params.at(0), pass.params.at(1));
Angle botDir = getOnetimeShotDirection(world, player(), intercept_pos);
if(can_shoot && botDir.angle_diff((passer_pos - intercept_pos).orientation()).to_degrees() < 60.0){
//Point alteredPos = player().position() + 1.0*(intercept_pos - player().position());
Point offset = -Point::of_angle(botDir)*Robot::MAX_RADIUS;
Action::move(ca, world, player(), intercept_pos + offset, botDir, true, false ); // autokick on
}else{
//TODO: turn dribbler on
Action::move(ca, world, player(), intercept_pos, (passer_pos - intercept_pos).orientation(), false, true); // autokick off
}
yield(ca);
}
}
Glib::ustring description() const override {
return u8"passee_simple-receive";
}
};
}
Tactic::Ptr AI::HL::STP::Tactic::passer_simple(World world, bool shoot_on_net) {
Tactic::Ptr p(new PasserSimple(world, shoot_on_net));
return p;
}
Tactic::Ptr AI::HL::STP::Tactic::passee_simple(World world, unsigned index) {
Tactic::Ptr p(new PasseeSimple(world, index));
return p;
}
Tactic::Ptr AI::HL::STP::Tactic::passee_simple_receive(World world) {
Tactic::Ptr p(new PasseeReceive(world));
return p;
}
|
ceb49d2763dc2a0888e5e55c6f06e5ddd7a390ac
|
8923163e2738e98b1a73ebbd20361698f135cee8
|
/ISSF/EthernetFrame.h
|
376a0ea89756657c494ac3428e7f8c98a1075988
|
[] |
no_license
|
dmitsov/PuzzleGame
|
5e0dd043163f9e72f92acb713f2efd10bfe2af4d
|
3f6a7d9043352aae3a1065cf17a5764519470ced
|
refs/heads/master
| 2016-09-06T03:39:17.364362
| 2014-04-24T07:26:07
| 2014-04-24T07:26:07
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 649
|
h
|
EthernetFrame.h
|
#ifndef ETHERNET_FRAME_H
#define ETHERNET_FRAME_H
#include <stdio.h>
#include <features.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "HeaderTypes.h"
#include "include/LinkLayerData.h"
class EthernetFrame: public LinkLayerData
{
private:
ethernet_info ethernetHeader;
public:
EthernetFrame(const u_char* packet);
EthernetFrame(const EthernetFrame& other);
~EthernetFrame();
//overrided inferited method
const u_char* NetworkLayerPacket();
//MAC address getters
char* getSourceMACAddress() const;
char* getDestinationMACAddress() const;
//type getter
u_short getFrameType();
};
#endif
|
dbe200aaac65c3a0fc6bcbd65c5cdbb61c87f853
|
172f1d31ab19c411c0228a1f1c2172bd88ffff1f
|
/examples/1_SimpleGPS/1_SimpleGPS.cpp
|
f91cfdeef5ae8acde83233aa73e48c7bb0d31833
|
[
"MIT"
] |
permissive
|
rickkas7/AssetTrackerRK
|
a8e03e327e3643a9b2b88786771c63689c39f870
|
fbc7f2106ad4e3dbb9182239ea6ea1b4517b6f1b
|
refs/heads/master
| 2023-03-05T17:45:26.061440
| 2021-10-13T13:31:56
| 2021-10-13T13:31:56
| 69,272,320
| 26
| 17
|
MIT
| 2023-03-02T18:25:37
| 2016-09-26T17:01:02
|
C++
|
UTF-8
|
C++
| false
| false
| 2,006
|
cpp
|
1_SimpleGPS.cpp
|
#include "Particle.h"
#include "AssetTrackerRK.h" // only used for AssetTracker::antennaExternal
// Port of TinyGPS for the Particle AssetTracker
// https://github.com/mikalhart/TinyGPSPlus
#include "TinyGPS++.h"
SYSTEM_THREAD(ENABLED);
/*
This sample sketch demonstrates the normal use of a TinyGPS++ (TinyGPSPlus) object directly.
*/
void displayInfo(); // forward declaration
const unsigned long PUBLISH_PERIOD = 120000;
const unsigned long SERIAL_PERIOD = 5000;
const unsigned long MAX_GPS_AGE_MS = 10000; // GPS location must be newer than this to be considered valid
// The TinyGPS++ object
TinyGPSPlus gps;
unsigned long lastSerial = 0;
unsigned long lastPublish = 0;
unsigned long startFix = 0;
bool gettingFix = false;
void setup()
{
Serial.begin(9600);
// The GPS module on the AssetTracker is connected to Serial1 and D6
Serial1.begin(9600);
// Settings D6 LOW powers up the GPS module
pinMode(D6, OUTPUT);
digitalWrite(D6, LOW);
startFix = millis();
gettingFix = true;
// If using an external antenna, uncomment this block
// { AssetTracker t; t.antennaExternal(); }
}
void loop()
{
while (Serial1.available() > 0) {
if (gps.encode(Serial1.read())) {
displayInfo();
}
}
}
void displayInfo()
{
if (millis() - lastSerial >= SERIAL_PERIOD) {
lastSerial = millis();
char buf[128];
if (gps.location.isValid() && gps.location.age() < MAX_GPS_AGE_MS) {
snprintf(buf, sizeof(buf), "%f,%f,%f", gps.location.lat(), gps.location.lng(), gps.altitude.meters());
if (gettingFix) {
gettingFix = false;
unsigned long elapsed = millis() - startFix;
Serial.printlnf("%lu milliseconds to get GPS fix", elapsed);
}
}
else {
strcpy(buf, "no location");
if (!gettingFix) {
gettingFix = true;
startFix = millis();
}
}
Serial.println(buf);
if (Particle.connected()) {
if (millis() - lastPublish >= PUBLISH_PERIOD) {
lastPublish = millis();
Particle.publish("gps", buf, PRIVATE);
}
}
}
}
|
9128556a1eef0dcdf4042f95bfb65ef1401c4ad5
|
4f4184a72fe3f9ca4ee342b496d22b5486a2f217
|
/weak_ai/cpp/train.cpp
|
e2ae07c227faccb2e1f98e4fadce3815c4e71bcb
|
[
"MIT"
] |
permissive
|
tonylearn09/hexagonal_gomoku_ai
|
e5ec897d3cf9934a40ecf166b6ff864c871032b0
|
ddb307ee5fac7ec824a7db09d7f7b43a7adb1aa0
|
refs/heads/master
| 2020-03-13T22:11:22.425570
| 2018-05-03T09:09:39
| 2018-05-03T09:09:39
| 131,311,684
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 194
|
cpp
|
train.cpp
|
#include "Gomoku.h"
#include "TdLearner.h"
#include <time.h>
int main() {
srand((unsigned)time(NULL));
TdLearner td(0.001, 0.9, "weight.txt");
td.learning(50);
return 0;
}
|
0621792d9129fa8665189e34880eeba38a2f3175
|
ffcc850625b8590866a36d0a607e3a73cf37598d
|
/include/boost/simd/arch/common/scalar/function/divides_s.hpp
|
49b3431bb6dd5500f1dc08aae983c1f4980ed3d5
|
[
"BSL-1.0"
] |
permissive
|
remymuller/boost.simd
|
af7e596f17294d35ddcd8f859c4a12cb3276254d
|
c6614f67be94be2608342bf5d753917b6968e821
|
refs/heads/develop
| 2021-01-02T09:00:18.137281
| 2017-07-06T14:23:04
| 2017-07-06T14:23:04
| 99,120,027
| 6
| 7
| null | 2017-08-02T13:34:55
| 2017-08-02T13:34:55
| null |
UTF-8
|
C++
| false
| false
| 2,813
|
hpp
|
divides_s.hpp
|
//==================================================================================================
/*!
@file
@copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_DIVIDES_S_HPP_INCLUDED
#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_DIVIDES_S_HPP_INCLUDED
#include <boost/simd/constant/one.hpp>
#include <boost/simd/constant/valmax.hpp>
#include <boost/simd/constant/valmin.hpp>
#include <boost/simd/constant/zero.hpp>
#include <boost/simd/function/genmask.hpp>
#include <boost/simd/detail/dispatch/function/overload.hpp>
#include <boost/simd/detail/dispatch/meta/as_unsigned.hpp>
#include <boost/config.hpp>
namespace boost { namespace simd { namespace ext
{
namespace bd = boost::dispatch;
#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable: 4723) // potential divide by 0
#endif
BOOST_DISPATCH_OVERLOAD ( divides_
, (typename A0)
, bd::cpu_
, bs::saturated_tag
, bd::scalar_< bd::floating_<A0> >
, bd::scalar_< bd::floating_<A0> >
)
{
BOOST_FORCEINLINE A0 operator() (const saturated_tag &, A0 a0, A0 a1
) const BOOST_NOEXCEPT
{
return a0/a1;
}
};
BOOST_DISPATCH_OVERLOAD ( divides_
, (typename A0)
, bd::cpu_
, bs::saturated_tag
, bd::scalar_< bd::int_<A0> >
, bd::scalar_< bd::int_<A0> >
)
{
BOOST_FORCEINLINE A0 operator() (const saturated_tag &, A0 a0, A0 a1
) const BOOST_NOEXCEPT
{
typedef bd::as_unsigned_t<A0> utype;
A0 const aa0 = a0 + !((a1 + One<A0>()) | ((utype)a0 + Valmin<A0>()));
if (a1)
return aa0/a1;
else if (a0)
return Valmax<A0>() + ((utype)a0 >> (sizeof(A0)*CHAR_BIT-1));
else
return Zero<A0>();
}
};
BOOST_DISPATCH_OVERLOAD ( divides_
, (typename A0)
, bd::cpu_
, bs::saturated_tag
, bd::scalar_< bd::uint_<A0> >
, bd::scalar_< bd::uint_<A0> >
)
{
BOOST_FORCEINLINE A0 operator() (const saturated_tag &, A0 a0, A0 a1
) const BOOST_NOEXCEPT
{
return a1 ? a0/a1 : genmask(a0);
}
};
} } }
#endif
|
dbc5d337a6c579deffa75bac1f410057ba670766
|
ad029fa220d98781004c890ff149b258b3f98da0
|
/remastered Bahadır Bozdağ/01. Svn/Server/game/src/char_item.cpp
|
1de2ef2b9aabaa200511f7aef42acd34aa654475
|
[] |
no_license
|
Bahadir016/remastered-offlineshop-system
|
5e050d9d87964afa726639dd2f02e687a9b3cdad
|
6dc4f58a1b1485f760b0435c7a3ea40087b65c12
|
refs/heads/main
| 2023-04-01T04:29:57.570455
| 2021-04-02T22:19:35
| 2021-04-02T22:19:35
| null | 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 1,483
|
cpp
|
char_item.cpp
|
//Search:
{
if (iPulse - GetMyShopTime() < PASSES_PER_SEC(g_nPortalLimitTime))
{
ChatPacket(CHAT_TYPE_INFO, LC_TEXT("개인상점 사용후 %d초 이내에는 귀환부,귀환기억부를 사용할 수 없습니다."), g_nPortalLimitTime);
return false;
}
}
//Add below:
#ifdef ENABLE_OFFLINE_SHOP_SYSTEM
if (iPulse - GetMyOfflineShopTime() < PASSES_PER_SEC(g_nPortalLimitTime))
{
ChatPacket(CHAT_TYPE_INFO, LC_TEXT("개인상점 사용후 %d초 이내에는 귀환부,귀환기억부를 사용할 수 없습니다."), g_nPortalLimitTime);
return false;
}
#endif
//Search:
if (iPulse - GetSafeboxLoadTime() < PASSES_PER_SEC(g_nPortalLimitTime)
|| iPulse - GetRefineTime() < PASSES_PER_SEC(g_nPortalLimitTime)
|| iPulse - GetMyShopTime() < PASSES_PER_SEC(g_nPortalLimitTime))
//Change:
if (iPulse - GetSafeboxLoadTime() < PASSES_PER_SEC(g_nPortalLimitTime)
|| iPulse - GetRefineTime() < PASSES_PER_SEC(g_nPortalLimitTime)
|| iPulse - GetMyShopTime() < PASSES_PER_SEC(g_nPortalLimitTime)
#ifdef ENABLE_OFFLINE_SHOP_SYSTEM
|| iPulse - GetMyOfflineShopTime() < PASSES_PER_SEC(g_nPortalLimitTime)
#endif
)
//Search:
if (m_bIsObserver) return false;
if (GetShop()) return false;
if (GetMyShop()) return false;
if (m_bUnderRefine) return false;
if (IsWarping()) return false;
//Add below:
#ifdef ENABLE_OFFLINE_SHOP_SYSTEM
if (GetOfflineShop()) return false;
#endif
|
570c6233c72cf6e07f7f6f6478e6150516b9f7d0
|
0082ee507d8add9f90ca07c580496a505e64ad8f
|
/car_node.h
|
3d5acf1ac5e0afedab6c8fbf634946969562df21
|
[] |
no_license
|
FlipperCoin/ds-hw1
|
042ca609057d756fbcffec5ac75b10a4bd0e4d8d
|
6ec1ebaec68a22809fc742c96d90c524049d4bf5
|
refs/heads/main
| 2023-05-02T14:48:11.777689
| 2021-05-24T17:36:43
| 2021-05-24T17:36:43
| 365,477,256
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,335
|
h
|
car_node.h
|
//
// Created by Itai on 08/05/2021.
//
#ifndef DS_EX1_CARNODE_H
#define DS_EX1_CARNODE_H
#include "vector.h"
#include "shared_pointer.h"
#include "model_data.h"
#include <string>
#include <sstream>
using std::string;
using std::ostringstream;
struct CarNode {
/**
* Type ID of the node
*/
int TypeID{};
/**
* Model ID of the best selling model for the corresponding car type
*/
int BestSellingModel{};
/**
* Array of metadata for all models, containing sells count and grade
* Item i corresponds to model ID i
*/
Vector<ModelData> Models;
CarNode() = default;
explicit CarNode(int typeID, int numOfModels=0) : TypeID(typeID), BestSellingModel(0),
Models(Vector<ModelData>(numOfModels)) {}
/**
* @param other node to compare to
* @return Is this node's type id higher than other's type id
*/
bool operator<(const CarNode& other) const;
/**
* @param other node to compare to
* @return Is this node's type id lower/equals to other's type id
*/
bool operator>=(const CarNode& other) const;
/**
* @param other node to compare to
* @return Is this node's type id equal to other's type id
*/
bool operator==(const CarNode& other) const;
string str() const;
};
#endif //DS_EX1_CARNODE_H
|
7e52370fd867136044011b0deb8f814c42100bbb
|
058238f45c98e0d4a7ed9883594489780f6ebe7d
|
/QTProject/3DFeatureExtract/fftw/fn_15.cpp
|
3226ad54f1da4267b649710f882c29f113a35afc
|
[] |
no_license
|
xiangliu/QSceneEdit
|
18283970032208ef6c395c200cea3bd56978f982
|
f9215782fa7896322556e20b74df1ccbe187f7b2
|
refs/heads/master
| 2020-05-04T15:32:25.091948
| 2013-06-03T01:53:44
| 2013-06-03T01:53:44
| 7,065,363
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 13,299
|
cpp
|
fn_15.cpp
|
/*
* Copyright (c) 1997-1999 Massachusetts Institute of Technology
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/* This file was automatically generated --- DO NOT EDIT */
/* Generated on Sun Nov 7 20:43:49 EST 1999 */
//#include "stdafx.h"
#include "fftw-int.h"
#include "fftw.h"
/* Generated by: ./genfft -magic-alignment-check -magic-twiddle-load-all -magic-variables 4 -magic-loopi -notwiddle 15 */
/*
* This function contains 156 FP additions, 56 FP multiplications,
* (or, 128 additions, 28 multiplications, 28 fused multiply/add),
* 62 stack variables, and 60 memory accesses
*/
static const fftw_real K587785252 = FFTW_KONST(+0.587785252292473129168705954639072768597652438);
static const fftw_real K951056516 = FFTW_KONST(+0.951056516295153572116439333379382143405698634);
static const fftw_real K250000000 = FFTW_KONST(+0.250000000000000000000000000000000000000000000);
static const fftw_real K559016994 = FFTW_KONST(+0.559016994374947424102293417182819058860154590);
static const fftw_real K500000000 = FFTW_KONST(+0.500000000000000000000000000000000000000000000);
static const fftw_real K866025403 = FFTW_KONST(+0.866025403784438646763723170752936183471402627);
/*
* Generator Id's :
* $Id: exprdag.ml,v 1.41 1999/05/26 15:44:14 fftw Exp $
* $Id: fft.ml,v 1.43 1999/05/17 19:44:18 fftw Exp $
* $Id: to_c.ml,v 1.25 1999/10/26 21:41:32 stevenj Exp $
*/
void fftw_no_twiddle_15(const fftw_complex *input, fftw_complex *output, int istride, int ostride)
{
fftw_real tmp5;
fftw_real tmp33;
fftw_real tmp57;
fftw_real tmp145;
fftw_real tmp100;
fftw_real tmp124;
fftw_real tmp21;
fftw_real tmp26;
fftw_real tmp27;
fftw_real tmp49;
fftw_real tmp54;
fftw_real tmp55;
fftw_real tmp136;
fftw_real tmp137;
fftw_real tmp147;
fftw_real tmp61;
fftw_real tmp62;
fftw_real tmp63;
fftw_real tmp112;
fftw_real tmp113;
fftw_real tmp126;
fftw_real tmp83;
fftw_real tmp88;
fftw_real tmp94;
fftw_real tmp10;
fftw_real tmp15;
fftw_real tmp16;
fftw_real tmp38;
fftw_real tmp43;
fftw_real tmp44;
fftw_real tmp139;
fftw_real tmp140;
fftw_real tmp146;
fftw_real tmp58;
fftw_real tmp59;
fftw_real tmp60;
fftw_real tmp115;
fftw_real tmp116;
fftw_real tmp125;
fftw_real tmp72;
fftw_real tmp77;
fftw_real tmp93;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp1;
fftw_real tmp97;
fftw_real tmp4;
fftw_real tmp96;
fftw_real tmp32;
fftw_real tmp98;
fftw_real tmp29;
fftw_real tmp99;
ASSERT_ALIGNED_DOUBLE;
tmp1 = c_re(input[0]);
tmp97 = c_im(input[0]);
{
fftw_real tmp2;
fftw_real tmp3;
fftw_real tmp30;
fftw_real tmp31;
ASSERT_ALIGNED_DOUBLE;
tmp2 = c_re(input[5 * istride]);
tmp3 = c_re(input[10 * istride]);
tmp4 = tmp2 + tmp3;
tmp96 = K866025403 * (tmp3 - tmp2);
tmp30 = c_im(input[5 * istride]);
tmp31 = c_im(input[10 * istride]);
tmp32 = K866025403 * (tmp30 - tmp31);
tmp98 = tmp30 + tmp31;
}
tmp5 = tmp1 + tmp4;
tmp29 = tmp1 - (K500000000 * tmp4);
tmp33 = tmp29 - tmp32;
tmp57 = tmp29 + tmp32;
tmp145 = tmp97 + tmp98;
tmp99 = tmp97 - (K500000000 * tmp98);
tmp100 = tmp96 + tmp99;
tmp124 = tmp99 - tmp96;
}
{
fftw_real tmp17;
fftw_real tmp20;
fftw_real tmp45;
fftw_real tmp79;
fftw_real tmp80;
fftw_real tmp81;
fftw_real tmp48;
fftw_real tmp82;
fftw_real tmp22;
fftw_real tmp25;
fftw_real tmp50;
fftw_real tmp84;
fftw_real tmp85;
fftw_real tmp86;
fftw_real tmp53;
fftw_real tmp87;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp18;
fftw_real tmp19;
fftw_real tmp46;
fftw_real tmp47;
ASSERT_ALIGNED_DOUBLE;
tmp17 = c_re(input[6 * istride]);
tmp18 = c_re(input[11 * istride]);
tmp19 = c_re(input[istride]);
tmp20 = tmp18 + tmp19;
tmp45 = tmp17 - (K500000000 * tmp20);
tmp79 = K866025403 * (tmp19 - tmp18);
tmp80 = c_im(input[6 * istride]);
tmp46 = c_im(input[11 * istride]);
tmp47 = c_im(input[istride]);
tmp81 = tmp46 + tmp47;
tmp48 = K866025403 * (tmp46 - tmp47);
tmp82 = tmp80 - (K500000000 * tmp81);
}
{
fftw_real tmp23;
fftw_real tmp24;
fftw_real tmp51;
fftw_real tmp52;
ASSERT_ALIGNED_DOUBLE;
tmp22 = c_re(input[9 * istride]);
tmp23 = c_re(input[14 * istride]);
tmp24 = c_re(input[4 * istride]);
tmp25 = tmp23 + tmp24;
tmp50 = tmp22 - (K500000000 * tmp25);
tmp84 = K866025403 * (tmp24 - tmp23);
tmp85 = c_im(input[9 * istride]);
tmp51 = c_im(input[14 * istride]);
tmp52 = c_im(input[4 * istride]);
tmp86 = tmp51 + tmp52;
tmp53 = K866025403 * (tmp51 - tmp52);
tmp87 = tmp85 - (K500000000 * tmp86);
}
tmp21 = tmp17 + tmp20;
tmp26 = tmp22 + tmp25;
tmp27 = tmp21 + tmp26;
tmp49 = tmp45 - tmp48;
tmp54 = tmp50 - tmp53;
tmp55 = tmp49 + tmp54;
tmp136 = tmp80 + tmp81;
tmp137 = tmp85 + tmp86;
tmp147 = tmp136 + tmp137;
tmp61 = tmp45 + tmp48;
tmp62 = tmp50 + tmp53;
tmp63 = tmp61 + tmp62;
tmp112 = tmp82 - tmp79;
tmp113 = tmp87 - tmp84;
tmp126 = tmp112 + tmp113;
tmp83 = tmp79 + tmp82;
tmp88 = tmp84 + tmp87;
tmp94 = tmp83 + tmp88;
}
{
fftw_real tmp6;
fftw_real tmp9;
fftw_real tmp34;
fftw_real tmp68;
fftw_real tmp69;
fftw_real tmp70;
fftw_real tmp37;
fftw_real tmp71;
fftw_real tmp11;
fftw_real tmp14;
fftw_real tmp39;
fftw_real tmp73;
fftw_real tmp74;
fftw_real tmp75;
fftw_real tmp42;
fftw_real tmp76;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp7;
fftw_real tmp8;
fftw_real tmp35;
fftw_real tmp36;
ASSERT_ALIGNED_DOUBLE;
tmp6 = c_re(input[3 * istride]);
tmp7 = c_re(input[8 * istride]);
tmp8 = c_re(input[13 * istride]);
tmp9 = tmp7 + tmp8;
tmp34 = tmp6 - (K500000000 * tmp9);
tmp68 = K866025403 * (tmp8 - tmp7);
tmp69 = c_im(input[3 * istride]);
tmp35 = c_im(input[8 * istride]);
tmp36 = c_im(input[13 * istride]);
tmp70 = tmp35 + tmp36;
tmp37 = K866025403 * (tmp35 - tmp36);
tmp71 = tmp69 - (K500000000 * tmp70);
}
{
fftw_real tmp12;
fftw_real tmp13;
fftw_real tmp40;
fftw_real tmp41;
ASSERT_ALIGNED_DOUBLE;
tmp11 = c_re(input[12 * istride]);
tmp12 = c_re(input[2 * istride]);
tmp13 = c_re(input[7 * istride]);
tmp14 = tmp12 + tmp13;
tmp39 = tmp11 - (K500000000 * tmp14);
tmp73 = K866025403 * (tmp13 - tmp12);
tmp74 = c_im(input[12 * istride]);
tmp40 = c_im(input[2 * istride]);
tmp41 = c_im(input[7 * istride]);
tmp75 = tmp40 + tmp41;
tmp42 = K866025403 * (tmp40 - tmp41);
tmp76 = tmp74 - (K500000000 * tmp75);
}
tmp10 = tmp6 + tmp9;
tmp15 = tmp11 + tmp14;
tmp16 = tmp10 + tmp15;
tmp38 = tmp34 - tmp37;
tmp43 = tmp39 - tmp42;
tmp44 = tmp38 + tmp43;
tmp139 = tmp69 + tmp70;
tmp140 = tmp74 + tmp75;
tmp146 = tmp139 + tmp140;
tmp58 = tmp34 + tmp37;
tmp59 = tmp39 + tmp42;
tmp60 = tmp58 + tmp59;
tmp115 = tmp71 - tmp68;
tmp116 = tmp76 - tmp73;
tmp125 = tmp115 + tmp116;
tmp72 = tmp68 + tmp71;
tmp77 = tmp73 + tmp76;
tmp93 = tmp72 + tmp77;
}
{
fftw_real tmp134;
fftw_real tmp28;
fftw_real tmp133;
fftw_real tmp142;
fftw_real tmp144;
fftw_real tmp138;
fftw_real tmp141;
fftw_real tmp143;
fftw_real tmp135;
ASSERT_ALIGNED_DOUBLE;
tmp134 = K559016994 * (tmp16 - tmp27);
tmp28 = tmp16 + tmp27;
tmp133 = tmp5 - (K250000000 * tmp28);
tmp138 = tmp136 - tmp137;
tmp141 = tmp139 - tmp140;
tmp142 = (K951056516 * tmp138) - (K587785252 * tmp141);
tmp144 = (K951056516 * tmp141) + (K587785252 * tmp138);
c_re(output[0]) = tmp5 + tmp28;
tmp143 = tmp134 + tmp133;
c_re(output[9 * ostride]) = tmp143 - tmp144;
c_re(output[6 * ostride]) = tmp143 + tmp144;
tmp135 = tmp133 - tmp134;
c_re(output[12 * ostride]) = tmp135 - tmp142;
c_re(output[3 * ostride]) = tmp135 + tmp142;
}
{
fftw_real tmp110;
fftw_real tmp56;
fftw_real tmp109;
fftw_real tmp118;
fftw_real tmp120;
fftw_real tmp114;
fftw_real tmp117;
fftw_real tmp119;
fftw_real tmp111;
ASSERT_ALIGNED_DOUBLE;
tmp110 = K559016994 * (tmp44 - tmp55);
tmp56 = tmp44 + tmp55;
tmp109 = tmp33 - (K250000000 * tmp56);
tmp114 = tmp112 - tmp113;
tmp117 = tmp115 - tmp116;
tmp118 = (K951056516 * tmp114) - (K587785252 * tmp117);
tmp120 = (K951056516 * tmp117) + (K587785252 * tmp114);
c_re(output[5 * ostride]) = tmp33 + tmp56;
tmp119 = tmp110 + tmp109;
c_re(output[14 * ostride]) = tmp119 - tmp120;
c_re(output[11 * ostride]) = tmp119 + tmp120;
tmp111 = tmp109 - tmp110;
c_re(output[2 * ostride]) = tmp111 - tmp118;
c_re(output[8 * ostride]) = tmp111 + tmp118;
}
{
fftw_real tmp150;
fftw_real tmp148;
fftw_real tmp149;
fftw_real tmp154;
fftw_real tmp156;
fftw_real tmp152;
fftw_real tmp153;
fftw_real tmp155;
fftw_real tmp151;
ASSERT_ALIGNED_DOUBLE;
tmp150 = K559016994 * (tmp146 - tmp147);
tmp148 = tmp146 + tmp147;
tmp149 = tmp145 - (K250000000 * tmp148);
tmp152 = tmp21 - tmp26;
tmp153 = tmp10 - tmp15;
tmp154 = (K951056516 * tmp152) - (K587785252 * tmp153);
tmp156 = (K951056516 * tmp153) + (K587785252 * tmp152);
c_im(output[0]) = tmp145 + tmp148;
tmp155 = tmp150 + tmp149;
c_im(output[6 * ostride]) = tmp155 - tmp156;
c_im(output[9 * ostride]) = tmp156 + tmp155;
tmp151 = tmp149 - tmp150;
c_im(output[3 * ostride]) = tmp151 - tmp154;
c_im(output[12 * ostride]) = tmp154 + tmp151;
}
{
fftw_real tmp129;
fftw_real tmp127;
fftw_real tmp128;
fftw_real tmp123;
fftw_real tmp132;
fftw_real tmp121;
fftw_real tmp122;
fftw_real tmp131;
fftw_real tmp130;
ASSERT_ALIGNED_DOUBLE;
tmp129 = K559016994 * (tmp125 - tmp126);
tmp127 = tmp125 + tmp126;
tmp128 = tmp124 - (K250000000 * tmp127);
tmp121 = tmp49 - tmp54;
tmp122 = tmp38 - tmp43;
tmp123 = (K951056516 * tmp121) - (K587785252 * tmp122);
tmp132 = (K951056516 * tmp122) + (K587785252 * tmp121);
c_im(output[5 * ostride]) = tmp124 + tmp127;
tmp131 = tmp129 + tmp128;
c_im(output[11 * ostride]) = tmp131 - tmp132;
c_im(output[14 * ostride]) = tmp132 + tmp131;
tmp130 = tmp128 - tmp129;
c_im(output[2 * ostride]) = tmp123 + tmp130;
c_im(output[8 * ostride]) = tmp130 - tmp123;
}
{
fftw_real tmp95;
fftw_real tmp101;
fftw_real tmp102;
fftw_real tmp106;
fftw_real tmp107;
fftw_real tmp104;
fftw_real tmp105;
fftw_real tmp108;
fftw_real tmp103;
ASSERT_ALIGNED_DOUBLE;
tmp95 = K559016994 * (tmp93 - tmp94);
tmp101 = tmp93 + tmp94;
tmp102 = tmp100 - (K250000000 * tmp101);
tmp104 = tmp58 - tmp59;
tmp105 = tmp61 - tmp62;
tmp106 = (K951056516 * tmp104) + (K587785252 * tmp105);
tmp107 = (K951056516 * tmp105) - (K587785252 * tmp104);
c_im(output[10 * ostride]) = tmp100 + tmp101;
tmp108 = tmp102 - tmp95;
c_im(output[7 * ostride]) = tmp107 + tmp108;
c_im(output[13 * ostride]) = tmp108 - tmp107;
tmp103 = tmp95 + tmp102;
c_im(output[ostride]) = tmp103 - tmp106;
c_im(output[4 * ostride]) = tmp106 + tmp103;
}
{
fftw_real tmp65;
fftw_real tmp64;
fftw_real tmp66;
fftw_real tmp90;
fftw_real tmp92;
fftw_real tmp78;
fftw_real tmp89;
fftw_real tmp91;
fftw_real tmp67;
ASSERT_ALIGNED_DOUBLE;
tmp65 = K559016994 * (tmp60 - tmp63);
tmp64 = tmp60 + tmp63;
tmp66 = tmp57 - (K250000000 * tmp64);
tmp78 = tmp72 - tmp77;
tmp89 = tmp83 - tmp88;
tmp90 = (K951056516 * tmp78) + (K587785252 * tmp89);
tmp92 = (K951056516 * tmp89) - (K587785252 * tmp78);
c_re(output[10 * ostride]) = tmp57 + tmp64;
tmp91 = tmp66 - tmp65;
c_re(output[7 * ostride]) = tmp91 - tmp92;
c_re(output[13 * ostride]) = tmp91 + tmp92;
tmp67 = tmp65 + tmp66;
c_re(output[4 * ostride]) = tmp67 - tmp90;
c_re(output[ostride]) = tmp67 + tmp90;
}
}
fftw_codelet_desc fftw_no_twiddle_15_desc =
{
"fftw_no_twiddle_15",
(void (*)()) fftw_no_twiddle_15,
15,
FFTW_FORWARD,
FFTW_NOTW,
331,
0,
(const int *) 0,
};
|
e5ed670e61ecbc83aca92f5e9859913124f1572c
|
f2df0a9ddd76e750891391a265b5047a95b94627
|
/src/MainWindow.cpp
|
49439b5341eb363acd608ec32c30de260fd9c78c
|
[
"MIT"
] |
permissive
|
wenjiegit/BullNote
|
be9c46b3f0a1bdc6c70770cb85a368f1f451bc29
|
f24b566ff0be2d412c63753e5c748bdaefe5ae01
|
refs/heads/master
| 2020-07-30T07:03:16.574288
| 2019-09-22T10:58:54
| 2019-09-22T10:58:54
| 210,127,597
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,723
|
cpp
|
MainWindow.cpp
|
#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QWindow>
#include <QJsonArray>
#include <QJsonDocument>
#include <QSystemTrayIcon>
#include <QMenu>
#include <QDebug>
#include "NoteItem.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
if (true) {
QString basePath = qApp->applicationDirPath();
QIcon pix(basePath + "/res/logo.png");
QSystemTrayIcon *icon = new QSystemTrayIcon(pix, this);
QMenu *m = new QMenu(this);
m->addAction(QString(QStringLiteral("显示便笺")), this, SLOT(onShow()));
m->addAction(QString(QStringLiteral("新建便笺")), this, SLOT(onNewNote()));
m->addAction(QString(QStringLiteral("置顶便笺")), this, SLOT(onForceTop()));
m->addAction(QString(QStringLiteral("取消便笺置顶")), this, SLOT(onCancelTop()));
m->addAction(QString(QStringLiteral("退出")), this, SLOT(onQuit()));
icon->setContextMenu(m);
icon->show();
}
restoreNotes();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_addNote_clicked()
{
NoteItem *item = new NoteItem();
connect(item, SIGNAL(saveRequired()), this, SLOT(onNoteSave()));
connect(item, SIGNAL(removeRequired()), this, SLOT(onNoteRemove()));
item->show();
m_items << item;
saveNotesData();
}
void MainWindow::onNoteSave()
{
saveNotesData();
}
void MainWindow::onNoteRemove()
{
NoteItem *item = dynamic_cast<NoteItem*> (sender());
if (!item) {
return;
}
removeNoteItem(item);
}
void MainWindow::onShow()
{
for (int i = 0; i < m_items.size(); ++i) {
NoteItem *item =m_items.at(i);
item->raise();
item->show();
}
}
void MainWindow::onNewNote()
{
on_addNote_clicked();
}
void MainWindow::onForceTop()
{
for (int i = 0; i < m_items.size(); ++i) {
NoteItem *item =m_items.at(i);
item->setWindowFlags(item->windowFlags() | Qt::WindowStaysOnTopHint);
item->raise();
item->show();
}
}
void MainWindow::onCancelTop()
{
for (int i = 0; i < m_items.size(); ++i) {
NoteItem *item =m_items.at(i);
item->setWindowFlags(item->windowFlags() & ~Qt::WindowStaysOnTopHint);
item->raise();
item->show();
}
}
void MainWindow::onQuit()
{
qApp->quit();
}
void MainWindow::saveNotesData()
{
QJsonArray arr;
for (int i = 0; i < m_items.size(); ++i) {
NoteItem *item = m_items.at(i);
arr.append(item->getData());
}
QJsonDocument doc(arr);
QByteArray jsonStr = doc.toJson();
QString outFilePath = qApp->applicationDirPath() + "/data.json";
QFile outFile(outFilePath);
if (outFile.open(QIODevice::WriteOnly)) {
outFile.write(jsonStr);
outFile.close();
}
}
void MainWindow::removeNoteItem(NoteItem *item)
{
m_items.removeAll(item);
item->deleteLater();
saveNotesData();
}
void MainWindow::restoreNotes()
{
QString inFilePath = qApp->applicationDirPath() + "/data.json";
QFile inFile(inFilePath);
if (inFile.open(QIODevice::ReadOnly)) {
QByteArray jsonStr = inFile.readAll();
QJsonDocument doc = QJsonDocument::fromJson(jsonStr);
QJsonArray arr = doc.array();
for (int i = 0; i < arr.size(); ++i) {
QJsonObject obj = arr.at(i).toObject();
NoteItem *item = new NoteItem;
item->setData(obj);
item->show();
m_items << item;
connect(item, SIGNAL(saveRequired()), this, SLOT(onNoteSave()));
connect(item, SIGNAL(removeRequired()), this, SLOT(onNoteRemove()));
}
}
}
|
25df1b7f46a7759494426ffe7860f93fee867cd5
|
25739059dd91cc84a65ae3abb9a7a0213caa8c81
|
/sources/funcsim/flags.h
|
6548ebdd364b4af5d27e63cdb79d5dae432f82b1
|
[
"MIT"
] |
permissive
|
MIPT-ILab/MDSP
|
70a669111c6c4518e2500c4d775fe508b2661591
|
e1d09a3b979b54c7b49883d48c05650476f366ae
|
refs/heads/master
| 2020-12-26T21:49:38.410540
| 2018-11-01T09:11:30
| 2018-11-01T09:18:23
| 33,407,032
| 2
| 2
|
MIT
| 2018-11-01T09:11:31
| 2015-04-04T13:53:13
|
C++
|
UTF-8
|
C++
| false
| false
| 850
|
h
|
flags.h
|
/**
* flags.h - Header of Flags class which defines
* fields and methods to operate with flag register
* Copyright 2009 MDSP team
*/
#ifndef FLAGS_H
#define FLAGS_H
#include <cassert>
#include "register_file.h"
#define FLAG_N_POSITION 0x80
#define FLAG_Z_POSITION 0x40
#define FLAG_C_POSITION 0x20
#define FLAG_O_POSITION 0x10
#define FLAG_N_POS_INVERSED (char)(~FLAG_N_POSITION)
#define FLAG_Z_POS_INVERSED (char)(~FLAG_Z_POSITION)
#define FLAG_C_POS_INVERSED (char)(~FLAG_C_POSITION)
#define FLAG_O_POS_INVERSED (char)(~FLAG_O_POSITION)
/**
* Class of flag register description
*/
class Flags: public RegVal
{
public:
Flags();
/* Get methods */
bool getFlag( FlagType flag);
/* Set methods */
void setFlag( FlagType flag, bool value);
void init(){ this->setByte( 0, 0x0000);}
};
#endif /* FLAGS_H */
|
3ddd0e9076d8649753a1de99326063f2095a6667
|
b6bade6e1397fac934f1aed2aff99010e03a3303
|
/src/mhash/universal_hash_table.h
|
72d08b83e11dc4a5d7a00bfffdfb3e23c5443c6f
|
[] |
no_license
|
yangzheng2115/hashcomp
|
9408f16f18790035c7123b822a36ad44e45b68f8
|
046e33b7c0d71b0392d2eaf92b339caf03c53deb
|
refs/heads/master
| 2020-07-24T21:17:49.896831
| 2019-09-09T16:27:57
| 2019-09-09T16:27:57
| 208,052,178
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 11,906
|
h
|
universal_hash_table.h
|
//
// Created by lwh on 19-7-9.
//
#ifndef HASHCOMP_UNIVERSAL_HASH_TABLE_H
#define HASHCOMP_UNIVERSAL_HASH_TABLE_H
#include <cassert>
#include <memory>
#include <cstddef>
#include <array>
#include <stack>
#include <cmath>
#include <limits>
#include <stdexcept>
#include <functional>
#include "util.h"
#include <boost/smart_ptr/atomic_shared_ptr.hpp>
#include <boost/lockfree/stack.hpp>
#define COARSE_RESERVIOR 1
namespace neatlib {
class ThreadRegistry;
extern ThreadRegistry gThreadRegistry;
struct ThreadCheckInCheckOut;
extern thread_local ThreadCheckInCheckOut tl_tcico;
extern void thread_registry_deregister_thread(const int tid);
struct ThreadCheckInCheckOut {
static const int NOT_ASSIGNED = -1;
int tid{NOT_ASSIGNED};
~ThreadCheckInCheckOut() {
if (tid == NOT_ASSIGNED) return;
thread_registry_deregister_thread(tid);
}
};
class ThreadRegistry {
private:
alignas(128) std::atomic<bool> usedTID[REGISTRY_MAX_THREADS]; // Which TIDs are in use by threads
alignas(128) std::atomic<int> maxTid{-1}; // Highest TID (+1) in use by threads
public:
ThreadRegistry() {
for (int it = 0; it < REGISTRY_MAX_THREADS; it++) {
usedTID[it].store(false, std::memory_order_relaxed);
}
}
// Progress condition: wait-free bounded (by the number of threads)
int register_thread_new(void) {
for (int tid = 0; tid < REGISTRY_MAX_THREADS; tid++) {
if (usedTID[tid].load(std::memory_order_acquire)) continue;
bool unused = false;
if (!usedTID[tid].compare_exchange_strong(unused, true)) continue;
// Increase the current maximum to cover our thread id
int curMax = maxTid.load();
while (curMax <= tid) {
maxTid.compare_exchange_strong(curMax, tid + 1);
curMax = maxTid.load();
}
tl_tcico.tid = tid;
return tid;
}
std::cout << "ERROR: Too many threads, registry can only hold " << REGISTRY_MAX_THREADS << " threads\n";
assert(false);
}
// Progress condition: wait-free population oblivious
inline void deregister_thread(const int tid) {
usedTID[tid].store(false, std::memory_order_release);
}
// Progress condition: wait-free population oblivious
static inline uint64_t getMaxThreads(void) {
return gThreadRegistry.maxTid.load(std::memory_order_acquire);
}
// Progress condition: wait-free bounded (by the number of threads)
static inline int getTID(void) {
int tid = tl_tcico.tid;
if (tid != ThreadCheckInCheckOut::NOT_ASSIGNED) return tid;
//std::cout << "Thread " << gThreadRegistry.getMaxThreads() + 1 << " registered" << endl;
return gThreadRegistry.register_thread_new();
}
};
void thread_registry_deregister_thread(const int tid) {
gThreadRegistry.deregister_thread(tid);
}
thread_local ThreadCheckInCheckOut tl_tcico{};
ThreadRegistry gThreadRegistry{};
template<class Key, class T, class Hash = std::hash<Key>,
std::size_t HASH_LEVEL = DEFAULT_NEATLIB_HASH_LEVEL,
std::size_t ROOT_HASH_LEVEL = DEFAULT_NEATLIB_HASH_LEVEL,
template<typename, typename ...> class ACCESSOR = /*std::unique_ptr*/boost::atomic_shared_ptr,
template<typename, typename ...> class STACK= /*std::stack*/boost::lockfree::stack>
class UniversalHashTable {
private:
enum node_type {
DATA_NODE = 0, ARRAY_NODE
};
template<typename N> using CHEAPER_ACCESSOR = boost::shared_ptr<N>;
//template<typename S> using STACK = /*std::stack*/boost::lockfree::stack<S>;
constexpr static std::size_t ARRAY_SIZE = static_cast<const std::size_t>(get_power2<HASH_LEVEL>::value);
constexpr static std::size_t ROOT_ARRAY_SIZE = static_cast<const std::size_t>(get_power2<ROOT_HASH_LEVEL>::value);
private:
class node {
protected:
node_type type_;
public:
explicit node(node_type type) : type_(type) {}
};
public:
class data_node : node {
std::pair<Key, T> data_;
std::size_t hash_;
public:
data_node(const Key &key, const T &mapped) : node(node_type::DATA_NODE), data_(key, mapped),
hash_(Hash()(key)) {}
data_node(const Key &key, const T &mapped, const std::size_t h) : node(node_type::DATA_NODE),
data_(key, mapped), hash_(h) {}
~data_node() {}
void reset(const Key &key, const T &mapped) {
// In case of jemalloc, the following variables will be allocated on demand, which means we cannot save time
// with inner variables being allocated in batch while initialized separately.
this->type_ = node_type::DATA_NODE;
data_ = std::pair<Key, T>(key, mapped);
hash_ = Hash()(key);
}
void set(const T &mapped) {
data_.second = mapped;
}
//const std::pair<const Key, const T> &get() { return data_; }
const std::pair<Key, T> &get() { return data_; }
std::size_t hash() const { return hash_; }
};
data_node *reserviors[REGISTRY_MAX_THREADS];
size_t thread_reservior_cursor[REGISTRY_MAX_THREADS];
private:
class array_node : node {
std::array<ACCESSOR<node>, ARRAY_SIZE> arr_;
public:
array_node() : node(node_type::ARRAY_NODE), arr_() {}
constexpr static std::size_t size() { return ARRAY_SIZE; }
};
class reserved_pool {
STACK<ACCESSOR<data_node>> data_st_;
public:
reserved_pool() : data_st_() {}
void put() {
data_st_.push(ACCESSOR<data_node>());
}
void put(std::size_t sz) {
for (std::size_t i = 0; i < sz; i++) put();
}
ACCESSOR<data_node> get_data_node(const Key &key, const T &mapped, std::size_t hash) {
ACCESSOR<data_node> p(nullptr);
data_st_.pop(p);
p->data_.first = key;
p->data_.second = mapped;
p->hash_ = hash;
return std::move(p);
}
};
class locator {
CHEAPER_ACCESSOR<node> *loc_ref = nullptr;
std::size_t root_hash(std::size_t hash) { return hash & (ROOT_ARRAY_SIZE - 1); }
std::size_t level_hash(std::size_t hash, std::size_t level) {
hash >>= ROOT_HASH_LEVEL;
level--;
return util::level_hash<Key>(hash, level, ARRAY_SIZE, HASH_LEVEL);
}
public:
const Key &key() { return static_cast<data_node *>(loc_ref->get())->data_.first; }
const std::pair<const Key, const T> &value() { return static_cast<data_node *>(loc_ref->get())->data_; }
locator(UniversalHashTable &ht, const Key &key) {
std::size_t hash = ht.hasher_(key);
std::size_t level = 0;
array_node *curr_node = nullptr;
for (; level < ht.max_level_; level++) {
std::size_t curr_hash = 0;
if (level) {
curr_hash = level_hash(hash, level);
loc_ref = curr_node->arr_[curr_hash].load(std::memory_order_release);
} else {
curr_hash = root_hash(hash);
loc_ref = ht.root_[curr_hash].load(std::memory_order_release);
}
if (!loc_ref->get()) {
break;
} else if (loc_ref->get()->type_ == DATA_NODE) {
if (hash != static_cast<data_node *>(loc_ref->get())->hash_) {
loc_ref = nullptr;
}
break;
} else {
curr_node = static_cast<array_node *>(loc_ref->get());
}
}
}
locator(UniversalHashTable &ht, const Key &key, const T *mappedp) {
const int tid = ThreadRegistry::getTID();
std::size_t hash = ht.hasher_(key);
std::size_t level = 0;
bool end = false;
array_node *curr_node = nullptr;
for (; level < ht.max_level_ && !end; level++) {
std::size_t curr_hash = 0;
ACCESSOR<node> *atomic_pos = nullptr;
if (level) {
curr_hash = level_hash(hash, level);
atomic_pos = curr_node->arr_[curr_hash];
loc_ref = atomic_pos->load(std::memory_order_release);
} else {
curr_hash = root_hash(hash);
atomic_pos = ht.root_[curr_hash];
loc_ref = atomic_pos->load(std::memory_order_release);
}
if (!loc_ref->get()) {
loc_ref = nullptr;
break;
} else if (loc_ref->get()->type_ == DATA_NODE) {
// Update/Delete bottleneck here.
CHEAPER_ACCESSOR<node> tmp_ptr(nullptr);
if (!mappedp) {
while (atomic_pos->compare_exchange_strong(loc_ref, nullptr));
} else {
#if COARSE_RESERVIOR
if (ht.thread_reservior_cursor[tid] == ARRAY_SIZE) {
ht.reserviors[tid] = new data_node[ARRAY_SIZE];
}
tmp_ptr.reset(
static_cast<data_node *>(new(
ht.reserviors[tid][ht.thread_reservior_cursor[tid]])data_node(key, *mappedp,
hash)));
#else
tmp_ptr.reset(static_cast<node *>(new data_node(key, *mappedp, hash)));
#endif
atomic<T *> currentp = nullptr;
do {
currentp = static_cast<data_node *>(loc_ref->get())->data_.second;
} while (currentp.compare_exchange_strong(loc_ref->get()));
}
} else {
curr_node = static_cast<array_node *>(loc_ref->get());
}
}
}
};
public:
UniversalHashTable() : size_(0) {
std::size_t m = 1, num = ARRAY_SIZE, level = 1;
std::size_t total_bit = sizeof(Key) * 8;
if (total_bit < 64) {
for (std::size_t i = 0; i < total_bit; i++)
m *= 2;
for (; num < m; num += num * ARRAY_SIZE)
level++;
} else {
m = std::numeric_limits<std::size_t>::max();
auto m2 = m / 2;
for (; num < m2; num += num * ARRAY_SIZE)
level++;
level++;
}
max_level_ = level;
for (int i = 0; i < REGISTRY_MAX_THREADS; i++) {
reserviors[i] = static_cast<data_node *>(malloc(sizeof(data_node) * ARRAY_SIZE));
thread_reservior_cursor[i] = ARRAY_SIZE;
}
}
std::pair<const Key, const T> Get(const Key &key) {
return std::make_pair(static_cast<Key>(0), static_cast<T>(0));
}
bool Upsert(const Key &key, const T &new_mapped) {
//cout << ThreadRegistry::getTID() << endl;
ThreadRegistry::getTID();
return true;
}
bool Insert(const Key &key, const T &new_mapped) {
return Upsert(key, new_mapped);
}
bool Update(const Key &key, const T &new_mapped) {
return Upsert(key, new_mapped);
}
bool Remove(const Key &key) {
return true;
}
std::size_t Size() { return size_; }
private:
std::array<ACCESSOR<node>, ROOT_ARRAY_SIZE> root_;
std::atomic<size_t> size_;
Hash hasher_;
std::size_t max_level_ = 0;
};
}
#endif //HASHCOMP_UNIVERSAL_HASH_TABLE_H
|
e9d75908d9fcbb52431a0b7cb8197f4164c27362
|
33b567f6828bbb06c22a6fdf903448bbe3b78a4f
|
/opencascade/ShapeConstruct.hxx
|
d3a51763d938bbbe84ecf1014295c27e04d6e3d2
|
[
"Apache-2.0"
] |
permissive
|
CadQuery/OCP
|
fbee9663df7ae2c948af66a650808079575112b5
|
b5cb181491c9900a40de86368006c73f169c0340
|
refs/heads/master
| 2023-07-10T18:35:44.225848
| 2023-06-12T18:09:07
| 2023-06-12T18:09:07
| 228,692,262
| 64
| 28
|
Apache-2.0
| 2023-09-11T12:40:09
| 2019-12-17T20:02:11
|
C++
|
UTF-8
|
C++
| false
| false
| 4,730
|
hxx
|
ShapeConstruct.hxx
|
// Created on: 1998-07-14
// Created by: data exchange team
// Copyright (c) 1998-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _ShapeConstruct_HeaderFile
#define _ShapeConstruct_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <GeomAbs_Shape.hxx>
#include <Standard_Integer.hxx>
#include <TopTools_HSequenceOfShape.hxx>
#include <TopAbs_Orientation.hxx>
class Geom_BSplineCurve;
class Geom_Curve;
class Geom2d_BSplineCurve;
class Geom2d_Curve;
class Geom_BSplineSurface;
class Geom_Surface;
class TopoDS_Face;
class TopoDS_Edge;
//! This package provides new algorithms for constructing
//! new geometrical objects and topological shapes. It
//! complements and extends algorithms available in Open
//! CASCADE topological and geometrical toolkist.
//! The functionality provided by this package are the
//! following:
//! projecting curves on surface,
//! adjusting curve to have given start and end points. P
class ShapeConstruct
{
public:
DEFINE_STANDARD_ALLOC
//! Tool for wire triangulation
Standard_EXPORT static Handle(Geom_BSplineCurve) ConvertCurveToBSpline (const Handle(Geom_Curve)& C3D, const Standard_Real First, const Standard_Real Last, const Standard_Real Tol3d, const GeomAbs_Shape Continuity, const Standard_Integer MaxSegments, const Standard_Integer MaxDegree);
Standard_EXPORT static Handle(Geom2d_BSplineCurve) ConvertCurveToBSpline (const Handle(Geom2d_Curve)& C2D, const Standard_Real First, const Standard_Real Last, const Standard_Real Tol2d, const GeomAbs_Shape Continuity, const Standard_Integer MaxSegments, const Standard_Integer MaxDegree);
Standard_EXPORT static Handle(Geom_BSplineSurface) ConvertSurfaceToBSpline (const Handle(Geom_Surface)& surf, const Standard_Real UF, const Standard_Real UL, const Standard_Real VF, const Standard_Real VL, const Standard_Real Tol3d, const GeomAbs_Shape Continuity, const Standard_Integer MaxSegments, const Standard_Integer MaxDegree);
//! join pcurves of the <theEdge> on the <theFace>
//! try to use pcurves from originas edges <theEdges>
//! Returns false if cannot join pcurves
Standard_EXPORT static Standard_Boolean JoinPCurves (const Handle(TopTools_HSequenceOfShape)& theEdges, const TopoDS_Face& theFace, TopoDS_Edge& theEdge);
//! Method for joininig curves 3D.
//! Parameters : c3d1,ac3d2 - initial curves
//! Orient1, Orient2 - initial edges orientations.
//! first1,last1,first2,last2 - parameters for trimming curves
//! (re-calculate with account of orientation edges)
//! c3dOut - result curve
//! isRev1,isRev2 - out parameters indicative on possible errors.
//! Return value : True - if curves were joined successfully,
//! else - False.
Standard_EXPORT static Standard_Boolean JoinCurves (const Handle(Geom_Curve)& c3d1, const Handle(Geom_Curve)& ac3d2, const TopAbs_Orientation Orient1, const TopAbs_Orientation Orient2, Standard_Real& first1, Standard_Real& last1, Standard_Real& first2, Standard_Real& last2, Handle(Geom_Curve)& c3dOut, Standard_Boolean& isRev1, Standard_Boolean& isRev2);
//! Method for joininig curves 3D.
//! Parameters : c3d1,ac3d2 - initial curves
//! Orient1, Orient2 - initial edges orientations.
//! first1,last1,first2,last2 - parameters for trimming curves
//! (re-calculate with account of orientation edges)
//! c3dOut - result curve
//! isRev1,isRev2 - out parameters indicative on possible errors.
//! isError - input parameter indicative possible errors due to that one from edges have one vertex
//! Return value : True - if curves were joined successfully,
//! else - False.
Standard_EXPORT static Standard_Boolean JoinCurves (const Handle(Geom2d_Curve)& c2d1, const Handle(Geom2d_Curve)& ac2d2, const TopAbs_Orientation Orient1, const TopAbs_Orientation Orient2, Standard_Real& first1, Standard_Real& last1, Standard_Real& first2, Standard_Real& last2, Handle(Geom2d_Curve)& c2dOut, Standard_Boolean& isRev1, Standard_Boolean& isRev2, const Standard_Boolean isError = Standard_False);
};
#endif // _ShapeConstruct_HeaderFile
|
a240798a106bcbd38e306de65ea623c5186b0794
|
4c00f4df7bc4948654045b36b49e790d2f0317ea
|
/src/BigPotSubtitle.cpp
|
dc86b8eaac0e84c937b401b5cc11993683751d93
|
[] |
no_license
|
amikey/bigpot
|
c2da22e18aa87127bf8cd0cf38ae2e6efd23b1dd
|
91267c48993d58c5424583bf4b5ba9ef7eaa5104
|
refs/heads/master
| 2020-06-29T21:49:24.836091
| 2016-08-21T10:09:20
| 2016-08-21T10:09:20
| 67,261,502
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 558
|
cpp
|
BigPotSubtitle.cpp
|
#include "BigPotSubtitle.h"
#include "BigPotSubtitleAss.h"
#include "BigPotSubtitleSrt.h"
#include "Config.h"
#include "File.h"
BigPotSubtitle::BigPotSubtitle()
{
fontname_ = config_->getString("sub_font");
if (!File::fileExist(fontname_))
{
#ifdef _WIN32
fontname_ = "c:/windows/fonts/msyh.ttc";
#endif
#ifdef __APPLE__
fontname_ = "/System/Library/Fonts/STHeiti Medium.ttc";
#endif
}
}
BigPotSubtitle::~BigPotSubtitle()
{
if (config_->getString("sub_font") == "")
{ config_->setString(fontname_, "sub_font"); }
}
|
03c17c2edb6060e22ea274e435295a6212031524
|
28ff4999e339fcf537b997065b31cdc78f56a614
|
/components/messages/android/message_utils_bridge.h
|
2b7dd1304c3d7f4ccdff59be95352956301976b4
|
[
"BSD-3-Clause"
] |
permissive
|
raghavanv97/chromium
|
f04e91aa24e5437793f342617515a0a95fd81478
|
5a03bdd6e398bfb1d52c241b3b154485f48174a3
|
refs/heads/master
| 2023-02-05T01:17:51.097632
| 2020-12-15T06:41:11
| 2020-12-15T06:41:11
| 320,831,053
| 0
| 0
|
BSD-3-Clause
| 2020-12-14T08:37:15
| 2020-12-12T12:56:50
| null |
UTF-8
|
C++
| false
| false
| 515
|
h
|
message_utils_bridge.h
|
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_MESSAGES_ANDROID_MESSAGE_UTILS_BRIDGE_H_
#define COMPONENTS_MESSAGES_ANDROID_MESSAGE_UTILS_BRIDGE_H_
namespace messages {
// C++ counterpart to MessageUtilsBridge.java.
class MessageUtilsBridge {
public:
static bool IsA11yEnabled();
};
} // namespace messages
#endif // COMPONENTS_MESSAGES_ANDROID_MESSAGE_UTILS_BRIDGE_H_
|
36af6ffe6bffd3c8b0baa92d11287131beea0c39
|
d2483771e04ac89a34dfef4faae65f030ffc0168
|
/dh_cryptopp/dh-agree.cpp
|
9b6c1bcf9164456dbb08bed68e57d20b966cce43
|
[] |
no_license
|
tinyauyu/elec4848
|
0255b9e9f17769cb4b4c0bb2a6f851331aabe2d3
|
94634a57d16f970e01fea8e85e55aedf9ba8c4cb
|
refs/heads/master
| 2021-01-21T13:04:55.715722
| 2016-04-22T05:49:06
| 2016-04-22T05:49:06
| 47,855,688
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,183
|
cpp
|
dh-agree.cpp
|
// g++ -g3 -ggdb -O0 -I. -I/usr/include/cryptopp dh-agree.cpp -o dh-agree.exe -lcryptopp -lpthread
// g++ -g -O2 -I. -I/usr/include/cryptopp dh-agree.cpp -o dh-agree.exe -lcryptopp -lpthread
#include <iostream>
using std::cout;
using std::cerr;
using std::endl;
#include <string>
using std::string;
#include <stdexcept>
using std::runtime_error;
#include <sstream>
using std::istringstream;
#include "osrng.h"
using CryptoPP::AutoSeededRandomPool;
#include "integer.h"
using CryptoPP::Integer;
#include "nbtheory.h"
using CryptoPP::ModularExponentiation;
#include "dh.h"
using CryptoPP::DH;
#include "secblock.h"
using CryptoPP::SecByteBlock;
#include <hex.h>
using CryptoPP::HexEncoder;
#include <filters.h>
using CryptoPP::StringSink;
int main(int argc, char** argv)
{
unsigned int bits = 1024;
AutoSeededRandomPool rndA, rndB;
try
{
// if(argc >= 2)
// {
// istringstream iss(argv[1]);
// iss >> bits;
// if(iss.fail())
// throw runtime_error("Failed to parse size in bits");
// if(bits < 6)
// throw runtime_error("Invalid size in bits");
// }
cout << "Generating prime of size " << bits << " and generator" << endl;
// Safe primes are of the form p = 2q + 1, p and q prime.
// These parameters do not state a maximum security level based
// on the prime subgroup order. In essence, we get the maximum
// security level. There is no free lunch: it means more modular
// mutliplications are performed, which affects performance.
// For a compare/contrast of meeting a security level, see dh-init.zip.
// Also see http://www.cryptopp.com/wiki/Diffie-Hellman and
// http://www.cryptopp.com/wiki/Security_level .
// CryptoPP::DL_GroupParameters_IntegerBased::GenerateRandom (gfpcrypt.cpp)
// CryptoPP::PrimeAndGenerator::Generate (nbtheory.cpp)
DH dh;
dh.AccessGroupParameters().GenerateRandomWithKeySize(rndA, bits);
if(!dh.GetGroupParameters().ValidateGroup(rndA, 3))
throw runtime_error("Failed to validate prime and generator");
size_t count = 0;
const Integer& p = dh.GetGroupParameters().GetModulus();
count = p.BitCount();
cout << "P (" << std::dec << count << "): " << std::hex << p << endl;
const Integer& q = dh.GetGroupParameters().GetSubgroupOrder();
count = q.BitCount();
cout << "Q (" << std::dec << count << "): " << std::hex << q << endl;
const Integer& g = dh.GetGroupParameters().GetGenerator();
count = g.BitCount();
cout << "G (" << std::dec << count << "): " << std::dec << g << endl;
// http://groups.google.com/group/sci.crypt/browse_thread/thread/7dc7eeb04a09f0ce
Integer v = ModularExponentiation(g, q, p);
if(v != Integer::One())
throw runtime_error("Failed to verify order of the subgroup");
return;
// RFC 5114, 1024-bit MODP Group with 160-bit Prime Order Subgroup
// http://tools.ietf.org/html/rfc5114#section-2.1
Integer p("0xB10B8F96A080E01DDE92DE5EAE5D54EC52C99FBCFB06A3C6"
"9A6A9DCA52D23B616073E28675A23D189838EF1E2EE652C0"
"13ECB4AEA906112324975C3CD49B83BFACCBDD7D90C4BD70"
"98488E9C219A73724EFFD6FAE5644738FAA31A4FF55BCCC0"
"A151AF5F0DC8B4BD45BF37DF365C1A65E68CFDA76D4DA708"
"DF1FB2BC2E4A4371");
Integer g("0xA4D1CBD5C3FD34126765A442EFB99905F8104DD258AC507F"
"D6406CFF14266D31266FEA1E5C41564B777E690F5504F213"
"160217B4B01B886A5E91547F9E2749F4D7FBD7D3B9A92EE1"
"909D0D2263F80A76A6A24C087A091F531DBF0A0169B6A28A"
"D662A4D18E73AFA32D779D5918D08BC8858F4DCEF97C2A24"
"855E6EEB22B3B2E5");
Integer q("0xF518AA8781A8DF278ABA4E7D64B7CB9D49462353");
// Schnorr Group primes are of the form p = rq + 1, p and q prime. They
// provide a subgroup order. In the case of 1024-bit MODP Group, the
// security level is 80 bits (based on the 160-bit prime order subgroup).
// For a compare/contrast of using the maximum security level, see
// dh-agree.zip. Also see http://www.cryptopp.com/wiki/Diffie-Hellman
// and http://www.cryptopp.com/wiki/Security_level .
DH dhA, dhB;
dhA.AccessGroupParameters().Initialize(p, q, g);
dhB.AccessGroupParameters().Initialize(p, q, g);
if(!dhA.GetGroupParameters().ValidateGroup(rndA, 3) ||
!dhB.GetGroupParameters().ValidateGroup(rndB, 3))
throw runtime_error("Failed to validate prime and generator");
//size_t count = 0;
p = dhA.GetGroupParameters().GetModulus();
q = dhA.GetGroupParameters().GetSubgroupOrder();
g = dhA.GetGroupParameters().GetGenerator();
// http://groups.google.com/group/sci.crypt/browse_thread/thread/7dc7eeb04a09f0ce
v = ModularExponentiation(g, q, p);
if(v != Integer::One())
throw runtime_error("Failed to verify order of the subgroup");
//////////////////////////////////////////////////////////////
SecByteBlock privA(dhA.PrivateKeyLength());
SecByteBlock pubA(dhA.PublicKeyLength());
dhA.GenerateKeyPair(rndA, privA, pubA);
SecByteBlock privB(dhB.PrivateKeyLength());
SecByteBlock pubB(dhB.PublicKeyLength());
dhB.GenerateKeyPair(rndB, privB, pubB);
cout << "Generated key pair!" << endl;
//////////////////////////////////////////////////////////////
if(dhA.AgreedValueLength() != dhB.AgreedValueLength())
throw runtime_error("Shared secret size mismatch");
SecByteBlock sharedA(dhA.AgreedValueLength()), sharedB(dhB.AgreedValueLength());
if(!dhA.Agree(sharedA, privA, pubB))
throw runtime_error("Failed to reach shared secret (1A)");
if(!dhB.Agree(sharedB, privB, pubA))
throw runtime_error("Failed to reach shared secret (B)");
count = std::min(dhA.AgreedValueLength(), dhB.AgreedValueLength());
if(!count || 0 != memcmp(sharedA.BytePtr(), sharedB.BytePtr(), count))
throw runtime_error("Failed to reach shared secret");
//////////////////////////////////////////////////////////////
Integer a, b;
a.Decode(sharedA.BytePtr(), sharedA.SizeInBytes());
cout << "Shared secret (A): " << std::hex << a << endl;
b.Decode(sharedB.BytePtr(), sharedB.SizeInBytes());
cout << "Shared secret (B): " << std::hex << b << endl;
}
catch(const CryptoPP::Exception& e)
{
cerr << e.what() << endl;
return -2;
}
catch(const std::exception& e)
{
cerr << e.what() << endl;
return -1;
}
return 0;
}
|
b418a77bcd186d6f10dd7b37fec9d421dedbc587
|
be9ef2030969d6c92c12c4cf4c3a4c3f4d31e99b
|
/chapter2/stack.cc
|
930d4691c589de4567645eb91adeb2dc977f2052
|
[] |
no_license
|
YaleCheung/LeeCode
|
45a8a77345daa3f212d51ef9f85742e281b0ad32
|
d94707fcdc5614f94bdc76a0ed5b59ad5ae1fa2e
|
refs/heads/master
| 2020-12-18T18:19:45.570073
| 2016-12-12T14:34:11
| 2016-12-12T14:34:11
| 28,800,497
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,623
|
cc
|
stack.cc
|
class Stack {
queue<int> q1; // q1 stores the elements comming later;
queue<int> q2; // q2 stores the elements comming prior
public:
// Push element x onto stack.
// pop all elements from q1 to q2; and add the element to q1;
void push(int x) {
while(! q1.empty()) {
int elem = q1.front();
q2.push(elem);
q1.pop();
}
q1.push(x);
}
// Removes the element on top of the stack.
// pop all the elem of q2.
void pop(void) {
if (q1.empty() && q2.empty())
return;
if (! q1.empty()) {
while (q1.size() > 1) {
int elem = q1.front();
q2.push(elem);
q1.pop();
}
q1.pop();
return;
} else if (! q2.empty()) {
while(q2.size() > 1) {
int elem = q2.front();
q1.push(elem);
q2.pop();
}
q2.pop();
}
}
// Get the top element.
int top(void) {
if (! q1.empty()) {
while (q1.size() > 1) {
int elem = q1.front();
q2.push(elem);
q1.pop();
}
return q1.front();
} else if (! q2.empty()) {
while(q2.size() > 1) {
int elem = q2.front();
q1.push(elem);
q2.pop();
}
return q2.front();;
}
}
// Return whether the stack is empty.
bool empty(void) {
return (q1.empty() && q2.empty());
}
};
|
4d0106a514a4abbe7e96efa59b79b220955b6d4e
|
13d750a9867dbd9527fe5e2205199b785ba08935
|
/T3/TerminalNode.h
|
0af5583c2a4fd5bb79ea87e996abe8ae90043088
|
[] |
no_license
|
nikom1912/CC5114
|
0aea4817d818e010d2af356d2f098ce28c401205
|
f60ff9ac58e3e258fb35064fea8e23832cfa7d50
|
refs/heads/master
| 2020-07-09T01:21:28.769782
| 2019-12-15T23:54:53
| 2019-12-15T23:54:53
| 203,834,302
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 655
|
h
|
TerminalNode.h
|
//
// Created by nikom on 12-12-2019.
//
#ifndef T3_TERMINALNODE_H
#define T3_TERMINALNODE_H
#include "Node.h"
template <typename T>
class TerminalNode: public Node<T> {
private:
T value;
public:
TerminalNode<T>(T value);
T eval();
void print();
};
template<typename T>
TerminalNode<T>::TerminalNode(T value): Node<T>(nullptr) {
this->value = value;
this->arguments = nullptr;
this->num_arguments = 0;
}
template<typename T>
T TerminalNode<T>::eval() {
return value;
}
template<typename T>
void TerminalNode<T>::print() {
std::cout << value;
}
#endif //T3_TERMINALNODE_H
|
6a502c53b14564dd199031e5244af903273e8d9c
|
a27d4dd7e8c11d2c55a6e1a7a5b9a05bf93d014f
|
/1_Dynamic_Programming/num_codes.cpp
|
abc18f402d5fa82bd0cf2f8339b4165cf20a705a
|
[] |
no_license
|
amanpratapsingh9/Competitive_Coding_Ninjas
|
8c0c311c1eb780398f075a09849949c2a92a7826
|
51bebab0437e57ef897fa9a933fc7b11ce0f3170
|
refs/heads/master
| 2022-01-08T09:38:21.596283
| 2019-01-25T23:50:11
| 2019-01-25T23:50:11
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,297
|
cpp
|
num_codes.cpp
|
#include<bits/stdc++.h>
using namespace std;
int num_codes(int *input, int size)
{
if(size == 1)
return 1;
if(size == 0)
return 1; //empty string
int output = num_codes(input,size-1);
if(input[size-2]*10 + input[size-1] <= 26)
output += num_codes(input,size-2); //this we don't have to do always!
return output;
}
int num_codes2(int *input, int size, int *arr)
{
if(size == 1)
return 1;
if(size == 0)
return 1; //empty string
if(arr[size] > 0)
return arr[size];
int output = num_codes2(input,size-1,arr);
if(input[size-2]*10 + input[size-1] <= 26)
output += num_codes2(input,size-2,arr); //this we don't have to do always!
arr[size] = output;
return output;
}
int num_codes_iter(int *input, int size)
{
int *output = new int[size+1];
output[0] = 1;
output[1] = 1;
for(int i=2;i<=size;i++)
{
output[i] += output[i-1];
if(( input[i-2]*10 + input[i-1]) <= 26)
output[i] += output[i-2];
}
int ans = output[size];
delete [] output;
return ans;
}
int main()
{
int input[50];
for(int i=0;i<50;i++)
{
if(i%2 == 0)
input[i] = 1;
else
input[i] = 2;
}
int size = sizeof(input)/sizeof(int);
int *arr = new int[size+1];
for(int i=0;i<=size;i++)
arr[i] = 0;
cout << num_codes2(input, size,arr) << endl;
return 0 ;
}
|
41542b9c4197868b0d3eff30469cc50310fee03d
|
2fc0325a8b7a96048ca322d66ada67878fa0710f
|
/BST-level order traversal/main.cpp
|
f9fb33c05beed8da5c369e62b4545f1e11e18a38
|
[] |
no_license
|
moodgalal/data-structures-with-c-
|
45bb8b7cc9f576bd1ececaf308990d5be74f59c8
|
19c3b713db19480ec8b0f3e8bd4dcd391d97892d
|
refs/heads/master
| 2020-05-17T10:49:42.900008
| 2019-04-26T17:18:18
| 2019-04-26T17:18:18
| 183,667,198
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,601
|
cpp
|
main.cpp
|
#include <iostream>
#include <queue>
using namespace std;
struct node
{
int data;
node *left;
node *right;
};
node* createNode(int value);
node* insertNode(node* root , int data);
void levelOrderTraversal(node *root);
int main()
{
node *root = NULL;
root = insertNode(root , 5);
root = insertNode(root , 10);
root = insertNode(root , 4);
root = insertNode(root , 2);
root = insertNode(root , 3);
root = insertNode(root , 11);
levelOrderTraversal(root);
return 0;
}
node* createNode(int value)
{
node *newNode = new node;
newNode->data = value;
newNode->left = newNode->right = NULL;
return newNode;
}
node* insertNode(node* root , int data)
{
if(root == NULL)
{
root = createNode(data);
}
else
{
if(data <= root->data)
root->left = insertNode(root->left , data);
else if(data > root->data)
root->right = insertNode(root->right , data);
}
return root;
}
void levelOrderTraversal(node *root)
{
if(root == NULL)
{
cout<<"The tree is empty"<<endl;
return;
}
else
{
queue<node*> myQ; // queue for the addresses of the nodes
myQ.push(root);
while(!myQ.empty()) // A loop to traverse all the nodes in level order
{
node *current = myQ.front();
cout<<current->data<<endl;
if(current->left != NULL)
myQ.push(current->left);
if(current->right != NULL)
myQ.push(current->right);
myQ.pop();
}
}
}
|
4355228180f4b8bd38481e02332f9b3473c71c3f
|
32739fe6c633e30600c9e41389d34672b572e679
|
/X96935 - Palíndroms amb piles.cc
|
5d74f35d249ebda66c492a29b4e4eba84019b49e
|
[] |
no_license
|
JoanK11/FIB-PRO2-Programacio-II
|
cda0c24b9ee98aa89887277a1c906eaa0d793afc
|
5aff73fc6698ebd3f480c73dea330de0cb3b1484
|
refs/heads/main
| 2023-06-21T19:13:28.484270
| 2021-06-12T10:56:32
| 2021-06-12T10:56:32
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 437
|
cc
|
X96935 - Palíndroms amb piles.cc
|
#include <iostream>
#include <stack>
using namespace std;
bool palindrom(stack<int>& S, int n) {
int x;
if (n%2 != 0) cin >> x;
for (int i = 0; i < n/2; ++i) {
cin >> x;
if (x != S.top()) return false;
S.pop();
}
return S.empty();
}
int main() {
int n;
cin >> n;
stack<int> S;
int x;
for (int i = 0; i < n/2; ++i) {
cin >> x;
S.push(x);
}
if (palindrom(S, n)) cout << "SI" << endl;
else cout << "NO" << endl;
}
|
e2f5973757e95920b76d7258f307445ecce904e4
|
9adc52bbcb5e94e666717dca705f15c3110818d2
|
/PPATH.cpp
|
7f66892e79ae140d42d9c1a94e269cf092cc250a
|
[] |
no_license
|
moulik-roy/SPOJ
|
436baddc876631af4a99ea97fad4138f8cac5c7c
|
bf7f86368f5b684cf54a345fa92464b15138671d
|
refs/heads/master
| 2022-08-20T00:24:35.048290
| 2022-07-27T18:21:05
| 2022-07-27T18:21:05
| 187,269,984
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 992
|
cpp
|
PPATH.cpp
|
#include <iostream>
#include <cstring>
#include <string>
#include <queue>
using namespace std;
bool isPrime[10000];
void seive(){
int i, j;
memset(isPrime, true, sizeof(isPrime));
isPrime[0]=isPrime[1]=false;
for(i=2; i*i<10000; i++){
if(isPrime[i]==true){
for(j=i*i; j<10000; j+=i)
isPrime[j]=false;
}
}
}
int main(){
int t, n, i, j, src, num, dist[10000];
string s;
seive();
cin>>t;
while(t--){
cin>>s;
cin>>n;
queue <string> q;
memset(dist, -1, sizeof(dist));
dist[stoi(s)]=0;
q.push(s);
while(!q.empty() && dist[n]==-1){
for(i=0; i<4; i++){
s=q.front();
src=stoi(s);
for(j=0; j<10; j++){
if(i==0 && j==0)
continue;
s[i]=(char)(j+'0');
num=stoi(s);
if(isPrime[num] && dist[num]==-1){
dist[num]=dist[src]+1;
q.push(s);
}
}
}
q.pop();
}
if(dist[n]==-1)
cout<<"Impossible\n";
else
cout<<dist[n]<<"\n";
}
return 0;
}
|
6d616aa17e606a8301c2d12ef9af1bb77f80221d
|
4ba874cb13ce3fdd843718ab93dab6ced7ee32d4
|
/examples/kmeans/kmeans.cpp
|
4089647901fbd4790d18611bbe1f5c66c0c3b121
|
[] |
no_license
|
Yuzhen11/flexps-paper-version
|
1fd1f5378da6aeb7dd1a4426c85a62a784baf843
|
8163fbeff79786c7503f605b5d46ea22f5777d4c
|
refs/heads/master
| 2021-09-12T03:52:12.184259
| 2018-04-14T01:46:28
| 2018-04-14T01:46:28
| 72,823,909
| 6
| 1
| null | 2018-04-14T01:43:46
| 2016-11-04T07:23:11
|
C++
|
UTF-8
|
C++
| false
| false
| 7,334
|
cpp
|
kmeans.cpp
|
#include "examples/kmeans/kmeans_helper.hpp"
int main(int argc, char* argv[]) {
bool rt = init_with_args(argc, argv, {"worker_port", "cluster_manager_host", "cluster_manager_port",
"hdfs_namenode", "hdfs_namenode_port", "input", "num_features", "num_iters"});
int num_iters = std::stoi(Context::get_param("num_iters"));
int num_features = std::stoi(Context::get_param("num_features"));
int K = std::stoi(Context::get_param("K"));
int batch_size = std::stoi(Context::get_param("batch_size"));
int report_interval = std::stoi(Context::get_param("report_interval")); // test performance after each test_iters
int data_size = std::stoi(Context::get_param("data_size")); // the size of the whole dataset
float learning_rate_coefficient = std::stod(Context::get_param("learning_rate_coefficient"));
int num_train_workers = std::stoi(Context::get_param("num_train_workers"));
int num_load_workers = std::stoi(Context::get_param("num_load_workers"));
std::string init_mode = Context::get_param("init_mode"); // randomly initialize the k center points
if (!rt)
return 1;
auto& engine = Engine::Get();
// Create and start the KVStore
kvstore::KVStore::Get().Start(Context::get_worker_info(), Context::get_mailbox_event_loop(),
Context::get_zmq_context());
// Create the DataStore
datastore::DataStore<LabeledPointHObj<float, int, true>> data_store(
Context::get_worker_info().get_num_local_workers());
// Create load_task
auto load_task = TaskFactory::Get().CreateTask<HuskyTask>(1, num_load_workers); // 1 epoch, 4 workers
engine.AddTask(std::move(load_task), [&data_store, &num_features](const Info& info) {
load_data(Context::get_param("input"), data_store, DataFormat::kLIBSVMFormat, num_features, info);
husky::LOG_I << RED("Finished Load Data!");
});
// submit load_task
auto start_time = std::chrono::steady_clock::now();
engine.Submit();
auto end_time = std::chrono::steady_clock::now();
auto load_time = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count();
if (Context::get_worker_info().get_process_id() == 0)
husky::LOG_I << YELLOW("Load time: " + std::to_string(load_time) + " ms");
// set hint for kvstore and MLTask
std::map<std::string, std::string> hint = {
{husky::constants::kType, husky::constants::kPS},
{husky::constants::kConsistency, husky::constants::kASP},
{husky::constants::kNumWorkers, "1"},
};
int kv = kvstore::KVStore::Get().CreateKVStore<float>(hint, K * num_features + num_features,
num_features); // set max_key and chunk_size
// initialization task
auto init_task = TaskFactory::Get().CreateTask<MLTask>(1, 1, Task::Type::MLTaskType);
init_task.set_hint(hint);
init_task.set_kvstore(kv);
// use params[K][0] - params[K][K-1] to store v[K], assuming num_features >= K
init_task.set_dimensions(K * num_features + num_features);
engine.AddTask(std::move(init_task), [K, num_features, &data_store, &init_mode](const Info& info) {
init_centers(info, num_features, K, data_store, init_mode);
});
start_time = std::chrono::steady_clock::now();
engine.Submit();
end_time = std::chrono::steady_clock::now();
auto init_time = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count();
if (Context::get_worker_info().get_process_id() == 0)
husky::LOG_I << YELLOW("Init time: " + std::to_string(init_time) + " ms");
// training task
auto training_task = TaskFactory::Get().CreateTask<MLTask>(1, num_train_workers, Task::Type::MLTaskType);
training_task.set_hint(hint);
training_task.set_kvstore(kv);
training_task.set_dimensions(K * num_features + num_features);
engine.AddTask(std::move(training_task), [&data_store, num_iters, report_interval, K, batch_size, num_features,
data_size, learning_rate_coefficient,
num_train_workers](const Info& info) {
// initialize a worker
auto worker = ml::CreateMLWorker<float>(info);
std::vector<size_t> chunk_ids(K + 1);
std::iota(chunk_ids.begin(), chunk_ids.end(), 0); // set keys
std::vector<std::vector<float>> params(K + 1);
std::vector<std::vector<float>> step_sums(K + 1);
std::vector<std::vector<float>*> pull_ptrs(K + 1);
std::vector<std::vector<float>*> push_ptrs(K + 1);
for (int i = 0; i < K + 1; ++i) {
params[i].resize(num_features);
pull_ptrs[i] = ¶ms[i];
push_ptrs[i] = &step_sums[i];
}
// read from datastore
datastore::DataSampler<LabeledPointHObj<float, int, true>> data_sampler(data_store);
// training task
for (int iter = 0; iter < num_iters; iter++) {
worker->PullChunks(chunk_ids, pull_ptrs);
step_sums = params;
// training A mini-batch
int id_nearest_center;
float learning_rate;
data_sampler.random_start_point();
auto start_train = std::chrono::steady_clock::now();
for (int i = 0; i < batch_size / num_train_workers; ++i) {
auto& data = data_sampler.next();
auto& x = data.x;
id_nearest_center = get_nearest_center(data, K, step_sums, num_features).first;
learning_rate = learning_rate_coefficient / ++step_sums[K][id_nearest_center];
std::vector<float> deltas = step_sums[id_nearest_center];
for (auto field : x)
deltas[field.fea] -= field.val;
for (int j = 0; j < num_features; j++)
step_sums[id_nearest_center][j] -= learning_rate * deltas[j];
}
// test model
if (iter % report_interval == 0 && (iter / report_interval) % num_train_workers == info.get_cluster_id()) {
test_error(params, data_store, iter, K, data_size, num_features, info.get_cluster_id());
auto current_time = std::chrono::steady_clock::now();
auto train_time =
std::chrono::duration_cast<std::chrono::milliseconds>(current_time - start_train).count();
husky::LOG_I << CLAY("Iter, Time: " + std::to_string(iter) + "," + std::to_string(train_time));
}
// update params
for (int i = 0; i < K + 1; ++i)
for (int j = 0; j < num_features; ++j)
step_sums[i][j] -= params[i][j];
worker->PushChunks(chunk_ids, push_ptrs);
}
});
start_time = std::chrono::steady_clock::now();
engine.Submit();
end_time = std::chrono::steady_clock::now();
auto train_time = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count();
if (Context::get_worker_info().get_process_id() == 0)
husky::LOG_I << YELLOW("Total training time: " + std::to_string(train_time) + " ms");
engine.Exit();
kvstore::KVStore::Get().Stop();
}
|
3caa436224f78e8502700af2fbecb36fd2006164
|
8c1a1a68ebc030c53798252b85263f22cdd00785
|
/SpaceStationRescue/Game.cpp
|
1518937636f6a0acda60c6b3b405319e7e7704c0
|
[] |
no_license
|
MatTheGreat/SpaceStationRescue
|
81b55e0f980087c174ca920b0b93d77b7fcfe0d4
|
2d4be172de263db4265c954100e0d427214accf4
|
refs/heads/master
| 2021-08-24T06:13:15.247937
| 2017-12-08T10:39:24
| 2017-12-08T10:39:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 523
|
cpp
|
Game.cpp
|
#include "Game.h"
Game::Game()
{
m_window = new sf::RenderWindow(sf::VideoMode{ 1920, 1080, 32 }, "Space Station Rescue 2!!!");
m_exitGame = false;
m_window->setFramerateLimit(60);
}
Game::~Game()
{
}
void Game::run()
{
while (m_window->isOpen())
{
processEvents(); // as many as possible
update();
render();
}
}
void Game::processEvents()
{
}
void Game::update()
{
if (m_exitGame == true)
{
m_window->close();
}
}
void Game::render()
{
m_window->clear(sf::Color::White);
m_window->display();
}
|
281e1033a9f1a96cab4dbdb361ec4f54b4c1501d
|
4b205ffc82b967173a4875a7876fcdc94d294c29
|
/time/src/time_test.cpp
|
5f0b072919348025eddb80cd537090666515427f
|
[] |
no_license
|
udooer/cpp_work
|
4bf6be00704e592191606f32982cbd72e2c96616
|
02f45f92b560be415f9e8989324a176ad07de03f
|
refs/heads/master
| 2023-04-02T06:08:45.065182
| 2021-04-13T12:07:05
| 2021-04-13T12:07:05
| 197,614,957
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 441
|
cpp
|
time_test.cpp
|
#include<iostream>
#include<string>
#include<sstream>
#include<ctime>
using namespace std;
string getTime(){
time_t now = time(0);
tm *ts = localtime(&now);
stringstream ss;
string date;
ss<<1900+ts->tm_year<<"-"<<1+ts->tm_mon<<\
"-"<<ts->tm_mday<<"_"<<ts->tm_hour<<":"<<\
ts->tm_min<<":"<<ts->tm_sec;
ss>>date;
return date;
}
int main(){
string date = getTime();
cout<<date<<endl;
return 0;
}
|
9cb96e2cb369960b971bb6ed985a02e32aaea163
|
c1d34c8db46849966a0b37b18f70c6e6ee91fc26
|
/code/AnalysisInterface/Module.cc
|
57da055444527b47883b54bd68c5b198cbdf21c6
|
[] |
no_license
|
sgnoohc/TrackLooper
|
a44c1e22d393ef760633b2cd5c30d23389bf85d6
|
f3d215051e8291f98aea24e7a554f73a7c356a09
|
refs/heads/master
| 2021-11-22T07:29:29.638458
| 2021-08-23T05:34:59
| 2021-08-23T05:34:59
| 179,347,611
| 0
| 1
| null | 2020-05-08T21:09:26
| 2019-04-03T18:30:25
|
C++
|
UTF-8
|
C++
| false
| false
| 9,462
|
cc
|
Module.cc
|
# include "Module.h"
SDL::Module::Module()
{
}
SDL::Module::Module(unsigned int detId, short layer, short ring, short rod, short module, bool isInverted, bool isLower, short subdet, SDL::ModuleType moduleType, SDL::ModuleLayerType moduleLayerType, short side)
{
detId_ = detId;
layer_ = layer;
module_ = module;
rod_ = rod;
ring_ = ring;
isInverted_ = isInverted;
isLower_ = isLower;
subdet_ = (SDL::Module::SubDet) subdet;
moduleType_ = (SDL::Module::ModuleType) moduleType;
moduleLayerType_ = (SDL::Module::ModuleLayerType) moduleLayerType;
side_ = (SDL::Module::Side)side;
partnerDetId_ = parsePartnerDetId(detId_);
}
SDL::Module::Module(unsigned int detId)
{
detId_ = detId;
setDerivedQuantities();
}
SDL::Module::~Module()
{
}
unsigned short SDL::Module::parseSubdet(unsigned int detId)
{
return (detId & (7 << 25)) >> 25;
}
unsigned short SDL::Module::parseSide(unsigned int detId)
{
if (parseSubdet(detId) == SDL::Module::Endcap)
{
return (detId & (3 << 23)) >> 23;
}
else if (parseSubdet(detId) == SDL::Module::Barrel)
{
return (detId & (3 << 18)) >> 18;
}
else
{
return 0;
}
}
unsigned short SDL::Module::parseLayer(unsigned int detId)
{
if (parseSubdet(detId) == SDL::Module::Endcap)
{
return (detId & (7 << 18)) >> 18;
}
else if (parseSubdet(detId) == SDL::Module::Barrel)
{
return (detId & (7 << 20)) >> 20;
}
else
{
return 0;
}
}
unsigned short SDL::Module::parseRod(unsigned int detId)
{
if (parseSubdet(detId) == SDL::Module::Endcap)
{
return 0;
}
else if (parseSubdet(detId) == SDL::Module::Barrel)
{
return (detId & (127 << 10)) >> 10;
}
else
{
return 0;
}
}
unsigned short SDL::Module::parseRing(unsigned int detId)
{
if (parseSubdet(detId) == SDL::Module::Endcap)
{
return (detId & (15 << 12)) >> 12;
}
else if (parseSubdet(detId) == SDL::Module::Barrel)
{
return 0;
}
else
{
return 0;
}
}
unsigned short SDL::Module::parseModule(unsigned int detId)
{
return (detId & (127 << 2)) >> 2;
}
unsigned short SDL::Module::parseIsLower(unsigned int detId)
{
return ((parseIsInverted(detId)) ? !(detId & 1) : (detId & 1));
}
bool SDL::Module::parseIsInverted(unsigned int detId)
{
if (parseSubdet(detId) == SDL::Module::Endcap)
{
if (parseSide(detId) == SDL::Module::NegZ)
{
return parseModule(detId) % 2 == 1;
}
else if (parseSide(detId) == SDL::Module::PosZ)
{
return parseModule(detId) % 2 == 0;
}
else
{
return 0;
}
}
else if (parseSubdet(detId) == SDL::Module::Barrel)
{
if (parseSide(detId) == SDL::Module::Center)
{
if (parseLayer(detId) <= 3)
{
return parseModule(detId) % 2 == 1;
}
else if (parseLayer(detId) >= 4)
{
return parseModule(detId) % 2 == 0;
}
else
{
return 0;
}
}
else if (parseSide(detId) == SDL::Module::NegZ or parseSide(detId) == SDL::Module::PosZ)
{
if (parseLayer(detId) <= 2)
{
return parseModule(detId) % 2 == 1;
}
else if (parseLayer(detId) == 3)
{
return parseModule(detId) % 2 == 0;
}
else
{
return 0;
}
}
else
{
return 0;
}
}
else
{
return 0;
}
}
unsigned int SDL::Module::parsePartnerDetId(unsigned int detId)
{
if (parseIsLower(detId))
return ((parseIsInverted(detId)) ? detId - 1 : detId + 1);
else
return ((parseIsInverted(detId)) ? detId + 1 : detId - 1);
}
SDL::Module::ModuleType SDL::Module::parseModuleType(unsigned int detId)
{
if (parseSubdet(detId) == SDL::Module::Barrel)
{
if (parseLayer(detId) <= 3)
return SDL::Module::PS;
else
return SDL::Module::TwoS;
}
else
{
if (parseLayer(detId) <= 2)
{
if (parseRing(detId) <= 10)
return SDL::Module::PS;
else
return SDL::Module::TwoS;
}
else
{
if (parseRing(detId) <= 7)
return SDL::Module::PS;
else
return SDL::Module::TwoS;
}
}
}
SDL::Module::ModuleLayerType SDL::Module::parseModuleLayerType(unsigned int detId)
{
if (parseModuleType(detId) == SDL::Module::TwoS)
return SDL::Module::Strip;
if (parseIsInverted(detId))
{
if (parseIsLower(detId))
return SDL::Module::Strip;
else
return SDL::Module::Pixel;
}
else
{
if (parseIsLower(detId))
return SDL::Module::Pixel;
else
return SDL::Module::Strip;
}
}
void SDL::Module::setDerivedQuantities()
{
subdet_ = (SDL::Module::SubDet) parseSubdet(detId_);
side_ = (SDL::Module::Side) parseSide(detId_);
layer_ = parseLayer(detId_);
rod_ = parseRod(detId_);
ring_ = parseRing(detId_);
module_ = parseModule(detId_);
isLower_ = parseIsLower(detId_);
isInverted_ = parseIsInverted(detId_);
moduleType_ = parseModuleType(detId_);
moduleLayerType_ = parseModuleLayerType(detId_);
partnerDetId_ = parsePartnerDetId(detId_);
}
const unsigned int& SDL::Module::detId() const
{
return detId_;
}
const SDL::Module::SubDet& SDL::Module::subdet() const
{
return subdet_;
}
const short& SDL::Module::side() const
{
return side_;
}
const short& SDL::Module::layer() const
{
return layer_;
}
const short& SDL::Module::rod() const
{
return rod_;
}
const short& SDL::Module::ring() const
{
return ring_;
}
const short& SDL::Module::module() const
{
return module_;
}
const bool& SDL::Module::isLower() const
{
return isLower_;
}
const bool& SDL::Module::isInverted() const
{
return isInverted_;
}
const unsigned int& SDL::Module::partnerDetId() const
{
return partnerDetId_;
}
const SDL::Module::ModuleType& SDL::Module::moduleType() const
{
return moduleType_;
}
const SDL::Module::ModuleLayerType& SDL::Module::moduleLayerType() const
{
return moduleLayerType_;
}
const std::vector<std::shared_ptr<SDL::Hit>>& SDL::Module::getHitPtrs() const
{
return hits_;
}
const std::vector<std::shared_ptr<SDL::MiniDoublet>>& SDL::Module::getMiniDoubletPtrs() const
{
return miniDoublets_;
}
const std::vector<std::shared_ptr<SDL::Segment>>& SDL::Module::getSegmentPtrs() const
{
return segments_;
}
const std::vector<std::shared_ptr<SDL::Tracklet>>& SDL::Module::getTrackletPtrs() const
{
return tracklets_;
}
const std::vector<std::shared_ptr<SDL::Triplet>>& SDL::Module::getTripletPtrs() const
{
return triplets_;
}
const std::vector<std::shared_ptr<SDL::TrackCandidate>>& SDL::Module::getTrackCandidatePtrs() const
{
return trackCandidates_;
}
void SDL::Module::addHit(std::shared_ptr<Hit> hit)
{
hits_.push_back(hit);
}
void SDL::Module::addMiniDoublet(std::shared_ptr<MiniDoublet> md)
{
miniDoublets_.push_back(md);
}
void SDL::Module::addSegment(std::shared_ptr<Segment> sg)
{
segments_.push_back(sg);
}
void SDL::Module::addTracklet(std::shared_ptr<Tracklet> tp)
{
tracklets_.push_back(tp);
}
void SDL::Module::addTriplet(std::shared_ptr<Triplet> tp)
{
triplets_.push_back(tp);
}
void SDL::Module::addTrackCandidate(std::shared_ptr<TrackCandidate> tc)
{
trackCandidates_.push_back(tc);
}
const int SDL::Module::getNumberOfMiniDoublets() const
{
return nMiniDoublets_;
}
const int SDL::Module::getNumberOfSegments() const
{
return nSegments_;
}
const int SDL::Module::getNumberOfTracklets() const
{
return nTracklets_;
}
const int SDL::Module::getNumberOfTriplets() const
{
return nTriplets_;
}
const int SDL::Module::getNumberOfTrackCandidatesT4T4() const
{
return nTrackCandidatesT4T4_;
}
const int SDL::Module::getNumberOfTrackCandidatesT4T3() const
{
return nTrackCandidatesT4T3_;
}
const int SDL::Module::getNumberOfTrackCandidatesT3T4() const
{
return nTrackCandidatesT3T4_;
}
const int SDL::Module::getNumberOfTrackCandidates() const
{
return nTrackCandidates_;
}
void SDL::Module::setNumberOfMiniDoublets(unsigned int nMiniDoublets)
{
nMiniDoublets_ = nMiniDoublets;
}
void SDL::Module::setNumberOfSegments(unsigned int nSegments)
{
nSegments_ = nSegments;
}
void SDL::Module::setNumberOfTracklets(unsigned int nTracklets)
{
nTracklets_ = nTracklets;
}
void SDL::Module::setNumberOfTriplets(unsigned int nTriplets)
{
nTriplets_ = nTriplets;
}
void SDL::Module::setNumberOfTrackCandidates(unsigned int nTrackCandidates)
{
nTrackCandidates_ = nTrackCandidates;
}
void SDL::Module::setNumberOfTrackCandidatesT4T4(unsigned int nTrackCandidates)
{
nTrackCandidatesT4T4_ = nTrackCandidates;
}
void SDL::Module::setNumberOfTrackCandidatesT4T3(unsigned int nTrackCandidates)
{
nTrackCandidatesT4T3_ = nTrackCandidates;
}
void SDL::Module::setNumberOfTrackCandidatesT3T4(unsigned int nTrackCandidates)
{
nTrackCandidatesT3T4_ = nTrackCandidates;
}
|
9a68ee499c0e1f3b577f437ae44b8a3f2e7ec9ee
|
f1cbd2f44c5b60f04cf15b2d78d6aaa8f2e9f572
|
/1996.cpp
|
3f304bac13abce6ea2bbed71287ac5f3d6e7b059
|
[] |
no_license
|
Reach220/23
|
c5812d0db69d2f5e35f9a8d9a22a2abf60a55bf7
|
ba4647301fec2cd4c6855c5db2e4fff526c6b354
|
refs/heads/master
| 2023-02-20T12:43:06.905139
| 2020-12-31T04:34:37
| 2020-12-31T04:34:37
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,447
|
cpp
|
1996.cpp
|
//n个人围成一圈,从第一个人开始报数,数到 mm 的人出列,再由下一个人重新从 11 开始报数,数到 mm 的人再出圈,依次类推,直到所有的人都出圈,请输出依次出圈人的编号。
#include<cstdio>
#include<queue>
#include<iostream>
using namespace std;
int n,m;
int a[105];
int num,cnt=0,rear;//cnt计数器,记录数了几个人(数到m为止) rear计时器,记录到n
int main(){
scanf("%d %d",&n,&m);
int num=n;
/*last=1;
while(num){//到最后一个人为止
int cnt=0;
for(int i=last;cnt!=m;i++){
if(i>n) i=1;//保证循环人数
if(a[i]==-1) continue;//已经被踢出列
++cnt;
if(cnt==m){//当前报数的正好报到m
a[i]=-1;//标记踢出
num--;//人数少一
last=i+1;//记下次数的位置
printf("%d ",i);//输出:这个人现在被踢出
break;
}
}
}*/
//num为未被选出人数
while(num){//选到没人为止
rear++;//一个一个数
if(rear>n) rear=1;//当rear大于n时,回到1
if(a[rear]!=1) cnt++;//若未标记,cnt+1,数一个人
if(cnt==m){//达到条件
a[rear]=1;//标记
num--;//减一
cnt=0;//计数器归零,开始下一次
printf("%d ",rear);
}
}
return 0;
}
|
500d31e2bf8e99a2d18c6b30fd466afd5d61ead1
|
d37b49d28edcd2a5ac905cb2cb8a67cf6a015329
|
/Lab_1/main.cpp
|
ab2e64da648245b083aa7e7253d8f011ad27b791
|
[] |
no_license
|
Bibletoon/ProgrammingSecondSem
|
d02d575cb2e741721a1d628e4577aae6e75d5a3c
|
98794829d46c2efc0a9cbe1d3804b30ee0152b38
|
refs/heads/master
| 2023-05-06T15:55:43.937618
| 2021-05-31T21:43:07
| 2021-05-31T21:43:07
| 343,347,681
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,493
|
cpp
|
main.cpp
|
#include <cassert>
#include <iostream>
#include "Point.h"
#include "PolygonalChain.h"
#include "ClosedPolygonalChain.h"
#include "Polygon.h"
#include "RegularPolygon.h"
#include "Trapezoid.h"
#include "Triangle.h"
const double EPS = 1e-9;
void PointCheck()
{
const Point p1;
assert(p1.GetX() == 0 && p1.GetY() == 0);
const Point p2(3, 4);
assert(p2.GetX() == 3 && p2.GetY() == 4);
}
void InheritancePolygonalChainCheck(const PolygonalChain* pc, const PolygonalChain* cpc)
{
assert(pc->GetPerimeter() == 9);
assert(cpc->GetPerimeter() == 12);
}
void PolygonsCheck()
{
Point* a = new Point[3]{Point(0, 0), Point(3, 4), Point(3, 0)};
Point* b = new Point[4]{Point(0, 0), Point(1, 4), Point(3, 4), Point(3, 0)};
const Polygon p(3, a);
const Triangle t(3, a);
const Trapezoid tr(4, b);
const PolygonalChain pc(3, a);
assert(pc.GetNumberOfPoints() == 3 && pc.GetPoint(1).GetX() == 3 && pc.GetPoint(1).GetY() == 4);
assert(pc.GetPerimeter() == 9);
const ClosedPolygonalChain cpc(3, a);
a[1] = Point();
assert(cpc.GetNumberOfPoints() == 3 && cpc.GetPoint(1).GetX() == 3 && cpc.GetPoint(1).GetY() == 4);
assert(cpc.GetPerimeter() == 12);
InheritancePolygonalChainCheck(&pc, &cpc);
assert(p.GetArea() == 6);
assert(t.IsRight());
Triangle trSharpestAsMyHand(3, new Point[3]{Point(0, 0), Point(1, 1), Point(0, 100)});
assert(!trSharpestAsMyHand.IsRight());
RegularPolygon rp(4, new Point[4]{Point(0, 0), Point(0, 2), Point(2, 2), Point(2, 0)});
assert(abs(rp.GetArea() - 4) < EPS && abs(rp.GetPerimeter() - 8) < EPS);
Trapezoid tra(4, b);
tra = tr;
Trapezoid* trap = new Trapezoid(4, b);
Trapezoid trCopy(*trap);
delete trap;
assert(abs(trCopy.GetArea() - 10) < EPS);
}
void checkPolymorphArea(int count, const Polygon* polygons)
{
for (int i = 0; i < count; i++)
{
assert(abs(polygons[i].GetArea() - 16) < EPS);
}
}
void checkPolymorph()
{
Point* pointsPolygon = new Point[6]{Point(0, 0), Point(1, 4), Point(3, 4), Point(6, 2), Point(3, 0)};
Point* pointsTriangle = new Point[3]{Point(0, 0), Point(4, 0), Point(0, 8)};
Point* pointsTrapezoid = new Point[4]{Point(0, 0), Point(2, 2), Point(8, 2), Point(10, 0)};
Point* pointsRegularPolygon = new Point[4]{Point(0, 0), Point(0, 4), Point(4, 4), Point(4, 0)};
Polygon* areaCalculatable = new Polygon[4]{
Polygon(5, pointsPolygon), Triangle(pointsTriangle), Trapezoid(pointsTrapezoid),
RegularPolygon(4, pointsRegularPolygon)
};
checkPolymorphArea(4, areaCalculatable);
}
int main()
{
std::cout << "Starting \"tests\"" << std::endl;
PointCheck();
PolygonsCheck();
checkPolymorph();
std::cout << "All \"tests\" passed" << std::endl;
Point* pointsTrapezoid = new Point[4]{Point(1, 1), Point(3, 3), Point(5, 3), Point(6, 1)};
Point* pointsSquare = new Point[4]{Point(1, 1), Point(3, 3), Point(5, 1), Point(3, -1)};
RegularPolygon square(4, pointsSquare);
Trapezoid trapezoid(pointsTrapezoid);
std::cout << "Trapezoid points: ";
for (int i = 0; i < 4; i++)
{
std::cout << "(" << pointsTrapezoid[i].GetX() << ";" << pointsTrapezoid[i].GetY() << ") ";
}
std::cout << std::endl;
std::cout << "Square points: ";
for (int i = 0; i < 4; i++)
{
std::cout << "(" << pointsSquare[i].GetX() << ";" << pointsSquare[i].GetY() << ") ";
}
std::cout << std::endl;
std::cout << "Perimeters: Trapezoid " << trapezoid.GetPerimeter() << " Square " << square.GetPerimeter() <<
std::endl;
std::cout << "Areas: Trapezoid " << trapezoid.GetArea() << " Square " << square.GetArea() << std::endl;
}
|
94e0000b7f60b0ba1ff19f6d42ba90f70437c1ac
|
7b417bc4422aadfa00fd5f817ac888c627046924
|
/Autonomous Claw.ino
|
0d86de61f375fa7652dceea6f88a5063fc502137
|
[] |
no_license
|
ShouryaSaklecha/AutonomousClaw
|
12c9315f04d0b8d08d2324d6ee654f913d64a171
|
44a4731dc3dc0bbb4a81d70c8e5fa8386c44db5a
|
refs/heads/main
| 2023-05-11T15:40:21.269962
| 2023-05-05T06:33:49
| 2023-05-05T06:33:49
| 345,772,222
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,308
|
ino
|
Autonomous Claw.ino
|
// --------------------------------------------------------------------------------------
// Code for Autonomous Claw: APSC 101
// Author: Shourya Saklecha
// Sources: Example codes in Arduino IDE; APSC 101
--------------------------------------------------------------------------------------
#include <Servo.h>
#define VCC_PIN 13
#define TRIGGER_PIN 12 // sonar trigger pin will be attached to Arduino pin 12
#define ECHO_PIN 11 // sonar echo pint will be attached to Arduino pin 11
#define GROUND_PIN 10 //
#define MAX_DISTANCE 200 // maximum distance set to 200 cm
#define Threshold_Distance 10 // Defines the required distance to be 10 cm
// defines variables
long duration;
int distance;
void setup() {
Serial. begin(9600); // set data transmission rate to communicate with computer
pinMode(ECHO_PIN, INPUT) ;
pinMode(TRIGGER_PIN, OUTPUT) ;
pinMode(GROUND_PIN, OUTPUT); // tell pin 10 it is going to be an output
pinMode(VCC_PIN, OUTPUT); // tell pin 13 it is going to be an output
digitalWrite(GROUND_PIN,LOW); // tell pin 10 to output LOW (OV, or ground)
digitalWrite(VCC_PIN, HIGH) ; // tell pin 13 to output HIGH (+5V)
}
void loop() {
digitalWrite(TRIGGER_PIN, LOW); // Clears the trigPin
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH); // Sets the trigPin on HIGH state for 10 micro seconds
delayMicroseconds(20);
digitalWrite(TRIGGER_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH);
distance= duration*0.034/2; // Calculating the distance
// if the distance measurement becomes extremely high, it is likely an error.
// Default to a maximum value of MAX_DISTANCE to identify this condition.
if (distance > MAX_DISTANCE)
{
distance = MAX_DISTANCE;
}
if (distance<Threshold_Distance)
{
delay(1000);
Servo myservo; // create servo object to control a servo
myservo.attach(9);
int pos = 10; // sets initial position to 10 to make a rotation
while(pos<=270)
{
myservo.write(pos);
delay(20);
pos++; // increase the position value to move the servo
}
delay(6000); // Waits 6 seconds
while (pos>=0)
{
myservo.write(pos);
delay(20);
pos--; // Goes from 270 to 0, basically just brings back the servo to initial position
}
}
}
|
5d37352561e0454582fa9978f96221a6ab4f72bf
|
5942e3e75ef7dc22a67b04fb1f12e14658a2093d
|
/duchain/helpers.h
|
a29c402be92f4baddef0a6d3efeb2e94df23b7dc
|
[] |
no_license
|
the-factory/kdevelop-python
|
9e94d2a4d4906a31a4d2a8a08300766e02d41a59
|
1e91f2cb4c94d9455a2ee22fef13df680aeed1ab
|
refs/heads/master
| 2021-01-18T08:57:16.707711
| 2012-04-09T22:37:47
| 2012-04-09T22:37:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,769
|
h
|
helpers.h
|
/*****************************************************************************
* This file is part of KDevelop *
* Copyright 2011-2012 Sven Brauch <svenbrauch@googlemail.com> *
* *
* Permission is hereby granted, free of charge, to any person obtaining *
* a copy of this software and associated documentation files (the *
* "Software"), to deal in the Software without restriction, including *
* without limitation the rights to use, copy, modify, merge, publish, *
* distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to *
* the following conditions: *
* *
* The above copyright notice and this permission notice shall be *
* included in all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, *
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND *
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE *
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION *
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION *
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
*****************************************************************************/
#ifndef GLOBALHELPERS_H
#define GLOBALHELPERS_H
#include <QList>
#include <KUrl>
#include <KDebug>
#include <interfaces/iproject.h>
#include <language/duchain/declaration.h>
#include <language/duchain/types/unsuretype.h>
#include <language/editor/simplerange.h>
#include <language/duchain/topducontext.h>
#include <language/duchain/types/structuretype.h>
#include <language/duchain/functiondeclaration.h>
#include <duchain/declarations/decorator.h>
#include "declarations/classdeclaration.h"
#include "pythonduchainexport.h"
#include "types/unsuretype.h"
#include "ast.h"
using namespace KDevelop;
namespace Python {
class KDEVPYTHONDUCHAIN_EXPORT Helper {
public:
/** get search paths for python files **/
static QList<KUrl> getSearchPaths(KUrl workingOnDocument);
static QString dataDir;
static QString documentationFile;
static DUChainPointer<TopDUContext> documentationFileContext;
static QString getDataDir();
static QString getDocumentationFile();
static ReferencedTopDUContext getDocumentationFileContext();
static QList<KUrl> cachedSearchPaths;
static UnsureType::Ptr extractTypeHints(AbstractType::Ptr type, TopDUContext* current);
static AbstractType::Ptr resolveType(AbstractType::Ptr type);
/**
* @brief Finds whether the specified called declaration is a function declaration, and, if not, checks for a class declaration; then returns the constructor
*
* @param ptr the declaration to check
* @return the function pointer which was found, or an invalid pointer
**/
static QPair<FunctionDeclarationPointer, bool> functionDeclarationForCalledDeclaration(DeclarationPointer ptr);
template<typename T> static const Decorator* findDecoratorByName(T* inDeclaration, const QString& name) {
register int count = inDeclaration->decoratorsSize();
for ( int i = 0; i < count; i++ ) {
if ( inDeclaration->decorators()[i].name() == name )
return &(inDeclaration->decorators()[i]);
}
return 0;
};
/**
* @brief merge two types into one unsure type
*
* @param type old type
* @param newType new type
* @return :AbstractType::Ptr the merged type, always valid
*
* @warning Although this looks symmetrical, it is NOT: the first argument might be modified, the second one won't be.
* So if you do something like a = mergeTypes(a, b) make sure you pass "a" as first argument.
**/
static AbstractType::Ptr mergeTypes(AbstractType::Ptr type, AbstractType::Ptr newType, TopDUContext* ctx = 0);
/** check whether the argument is a null, mixed, or none integral type **/
static bool isUsefulType(AbstractType::Ptr type);
enum ContextSearchFlags {
NoFlags,
PublicOnly
};
/**
* @brief Find all internal contexts for this class and its base classes recursively
*
* @param klass Type object for the class to search contexts
* @param context TopContext for finding the declarations for types
* @return list of contexts which were found
**/
static QList<DUContext*> internalContextsForClass(KDevelop::StructureType::Ptr klassType,
TopDUContext* context, ContextSearchFlags flags = NoFlags, int depth = 0);
/**
* @brief Resolve the given declaration if it is an alias declaration.
*
* @param decl the declaration to resolve
* @return :Declaration* decl if not an alias declaration, decl->aliasedDeclaration().data otherwise
* DUChain must be read locked
**/
static Declaration* resolveAliasDeclaration(Declaration* decl);
static Declaration* declarationForName(NameAst* ast, const QualifiedIdentifier& identifier,
const RangeInRevision& nodeRange, DUContextPointer context);
};
}
#endif
|
0eb36547636dfaeb1d2851c16852cd5e8c1b0d48
|
e7df6d41d7e04dc1c4f4ed169bf530a8a89ff17c
|
/OpenSim/Examples/Moco/exampleSlidingMass/exampleSlidingMass.cpp
|
17eb22f15c39acffbd572f9a3973396dc0dae56c
|
[
"Apache-2.0"
] |
permissive
|
opensim-org/opensim-core
|
2ba11c815df3072166644af2f34770162d8fc467
|
aeaaf93b052d598247dd7d7922fdf8f2f2f4c0bb
|
refs/heads/main
| 2023-09-04T05:50:54.783630
| 2023-09-01T22:44:04
| 2023-09-01T22:44:04
| 20,775,600
| 701
| 328
|
Apache-2.0
| 2023-09-14T17:45:19
| 2014-06-12T16:57:56
|
C++
|
UTF-8
|
C++
| false
| false
| 4,509
|
cpp
|
exampleSlidingMass.cpp
|
/* -------------------------------------------------------------------------- *
* OpenSim Moco: exampleSlidingMass.cpp *
* -------------------------------------------------------------------------- *
* Copyright (c) 2017 Stanford University and the Authors *
* *
* Author(s): Christopher Dembia *
* *
* 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. *
* -------------------------------------------------------------------------- */
/// Translate a point mass in one dimension in minimum time. This is a very
/// simple example that shows only the basics of Moco.
///
/// @verbatim
/// minimize t_f
/// subject to xdot = v
/// vdot = F/m
/// x(0) = 0
/// x(t_f) = 1
/// v(0) = 0
/// v(t_f) = 0
/// w.r.t. x in [-5, 5] position of mass
/// v in [-50, 50] speed of mass
/// F in [-50, 50] force applied to the mass
/// t_f in [0, 5] final time
/// constants m mass
/// @endverbatim
#include <OpenSim/Simulation/SimbodyEngine/SliderJoint.h>
#include <OpenSim/Actuators/CoordinateActuator.h>
#include <OpenSim/Moco/osimMoco.h>
using namespace OpenSim;
std::unique_ptr<Model> createSlidingMassModel() {
auto model = make_unique<Model>();
model->setName("sliding_mass");
model->set_gravity(SimTK::Vec3(0, 0, 0));
auto* body = new Body("body", 2.0, SimTK::Vec3(0), SimTK::Inertia(0));
model->addComponent(body);
// Allows translation along x.
auto* joint = new SliderJoint("slider", model->getGround(), *body);
auto& coord = joint->updCoordinate(SliderJoint::Coord::TranslationX);
coord.setName("position");
model->addComponent(joint);
auto* actu = new CoordinateActuator();
actu->setCoordinate(&coord);
actu->setName("actuator");
actu->setOptimalForce(1);
model->addComponent(actu);
body->attachGeometry(new Sphere(0.05));
model->finalizeConnections();
return model;
}
int main() {
MocoStudy study;
study.setName("sliding_mass");
// Define the optimal control problem.
// ===================================
MocoProblem& problem = study.updProblem();
// Model (dynamics).
// -----------------
problem.setModel(createSlidingMassModel());
// Bounds.
// -------
// Initial time must be 0, final time can be within [0, 5].
problem.setTimeBounds(MocoInitialBounds(0), MocoFinalBounds(0, 5));
// Position must be within [-5, 5] throughout the motion.
// Initial position must be 0, final position must be 1.
problem.setStateInfo("/slider/position/value", MocoBounds(-5, 5),
MocoInitialBounds(0), MocoFinalBounds(1));
// Speed must be within [-50, 50] throughout the motion.
// Initial and final speed must be 0. Use compact syntax.
problem.setStateInfo("/slider/position/speed", {-50, 50}, 0, 0);
// Applied force must be between -50 and 50.
problem.setControlInfo("/actuator", MocoBounds(-50, 50));
// Cost.
// -----
problem.addGoal<MocoFinalTimeGoal>();
// Configure the solver.
// =====================
MocoCasADiSolver& solver = study.initCasADiSolver();
solver.set_num_mesh_intervals(50);
// Now that we've finished setting up the tool, print it to a file.
study.print("sliding_mass.omoco");
// Solve the problem.
// ==================
MocoSolution solution = study.solve();
//solution.write("sliding_mass_solution.sto");
// Visualize.
// ==========
study.visualize(solution);
return EXIT_SUCCESS;
}
|
d2d6ec61ff2029ad4dccf3af1436c7a4a212a254
|
325483686eb27365fa08e39c543747d659a69099
|
/cpp/AddBinary.cpp
|
28e81b6e64aded9b492bb745b024308a127ed54e
|
[
"Apache-2.0"
] |
permissive
|
thinksource/code_interview
|
11bff53199cd47e9df3c7bc3034f0670209231d2
|
08be992240508b73894eaf6b8c025168fd19df19
|
refs/heads/master
| 2020-04-11T02:36:38.858986
| 2016-09-13T22:13:31
| 2016-09-13T22:13:31
| 68,151,728
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 647
|
cpp
|
AddBinary.cpp
|
class Solution {
public:
string addBinary(string a, string b) {
int lenA = (int)a.length();
int lenB = (int)b.length();
int i = lenA-1;
int j = lenB-1;
int carry = 0;
int sum = 0;
string res = "";
while(j>=0 || i>=0) {
int ai = (i>=0)? (a[i]-'0'):0;
int bj = (j>=0)? (b[j]-'0'):0;
sum = (ai+bj+carry);
res += char(sum%2 + '0');
carry = sum/2;
i--;
j--;
}
if(carry==1) {
res.append("1");
}
reverse(res.begin(), res.end());
return res;
}
};
|
f89a9138741185f09dc903af6f732910908b2a6e
|
aaebbe73cc851ba9ed8a3493abedb739d122533a
|
/server/yslib/utility/io_wrap.cpp
|
67ed5a97c010955fb2eca7b59321c881c4676591
|
[] |
no_license
|
coeux/lingyu-meisha-jp
|
7bc1309bf8304a294f9a42d23b985879a28afbc0
|
11972819254b8567cda33d17ffc40b384019a936
|
refs/heads/master
| 2021-01-21T13:48:12.593930
| 2017-02-14T06:46:02
| 2017-02-14T06:46:02
| 81,812,311
| 1
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 477
|
cpp
|
io_wrap.cpp
|
#include "io_wrap.h"
#include "io_service_pool.h"
#include <stdexcept>
#include <assert.h>
using namespace std;
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/syscall.h>
#define gettid() syscall(SYS_gettid)
#include "log.h"
io_wrap_t::io_wrap_t(const char* name_):m_name(name_),m_io(io_pool.get_io_service())
{
logtrace(("IO_WRAP", "%s create ok!", m_name.c_str()));
}
io_wrap_t::~io_wrap_t()
{
logtrace(("IO_WRAP","%s release ok!", m_name.c_str()));
}
|
e4d8cb266b746824483607734f02e5613f3b11ff
|
792ad26fd812df30bf9a4cc286cca43b87986685
|
/虽然是DP渣也不要放弃啊QAQ/POJ 1157 LITTLE SHOP OF FLOWERS.cpp
|
02a93a4da4da166fa39cdc72ce88a4d0e16f7656
|
[] |
no_license
|
Clqsin45/acmrec
|
39fbf6e02bb0c1414c05ad7c79bdfbc95dc26bf6
|
745b341f2e73d6b1dcf305ef466a3ed3df2e65cc
|
refs/heads/master
| 2020-06-18T23:44:21.083754
| 2016-11-28T05:10:44
| 2016-11-28T05:10:44
| 74,934,363
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 869
|
cpp
|
POJ 1157 LITTLE SHOP OF FLOWERS.cpp
|
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define N 104
int dp[N][N], f[N][N];
int main(){
int i, j, n, m, ans, k;
while(scanf("%d%d", &n, &m)!= EOF){
for(i = 1; i <= n; i++){
for(j = 1; j <= m; j++){
scanf("%d", &f[i][j]);
}
}
memset(dp, 0xbf, sizeof(dp));
dp[0][0] = 0;
for(i = 1; i <= n; i++){
int temp = dp[0][1];
for(j = 1; j <= m; j++){
for(k = 0; k < j; k++) temp = max(temp, dp[i-1][k]);
//printf("%d %d %d\n", i, j, temp);
dp[i][j] = temp + f[i][j];
}
}
int ans = dp[0][1];
for(i = 1; i <= m; i++){
ans = max(ans, dp[n][i]);
}
printf("%d\n", ans);
}
}
|
4ec117bfbea4f0fcaed4fac7be93bc1228c5aa6b
|
8515be16eb8f94bb27bb3e5e71f40092bdfa2f73
|
/src/yntdl/objects/position.cpp
|
d5b00b582bd241036e40a0da7da563e773fbef66
|
[
"MIT"
] |
permissive
|
OpenLabWorld/YNTDL
|
ea37297b889f505661060024eddca7fdbb377139
|
c21687b4ab54d9fbf1f8ac7db512cb36840c7607
|
refs/heads/master
| 2022-03-22T05:29:58.008213
| 2019-12-14T19:48:54
| 2019-12-14T19:48:54
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,418
|
cpp
|
position.cpp
|
#include <cmath>
#include <iostream>
#include <string>
#include <map>
#include "yntdl.h"
#define PI 3.141592653
using namespace yntdl;
std::ostream& std::operator<<(std::ostream &out, const Position &pos){
out << "Time: " + std::to_string(pos.time);
out << " x: " + std::to_string(pos.x);
out << " y: " + std::to_string(pos.y);
out << " z: " + std::to_string(pos.z);
return out;
}
//FIXME: Remove once refs removed
std::string Position::str(){
return ("Time: " + std::to_string(time)
+ " x: " + std::to_string(x)
+ " y: " + std::to_string(y)
+ " z: " + std::to_string(z));
}
//FIXME: Remove once moved to ns3lxc
std::string Position::ns3Str(){
return ("Seconds(" + std::to_string(time) + "), Vector("
+ std::to_string(x) + ","
+ std::to_string(y) + ","
+ std::to_string(z) + ")");
}
Positionable::Positionable(const Positionable& temp){
parent = temp.parent;
positions = temp.positions;
absPositions = temp.absPositions;
}
/**
* Computes relative positions based on its positions and parents movement
*/
void Positionable::centerPositionsAroundParent(Positionable *par){
parent = par;
if(parent != nullptr && (parent->absPositions.size() > 0 || parent->positions.size() > 0)){
absPositions.clear();
std::vector<Position> *posit;
if(parent->absPositions.size() > 0){
posit = &parent->absPositions;
} else if(parent->positions.size() > 0){
posit = &parent->positions;
}
std::map<double, bool> times;
for(auto position: positions){
times[position.time] = false;
}
for(auto position: *posit){
Position absPos;
Position myRelPos = getPosition(position.time);
absPos.time = position.time;
times[position.time] = true;
absPos.x = position.x + myRelPos.x;
absPos.y = position.y + myRelPos.y;
absPos.z = position.z + myRelPos.z;
absPositions.push_back(absPos);
}
for(auto pos: positions){
if(!times.at(pos.time)){
Position absPos;
Position myRelPos = getPosition(pos.time);
Position parentPos = parent->getAbsPosition(pos.time);
absPos.time = parentPos.time;
times[parentPos.time] = true;
absPos.x = parentPos.x + myRelPos.x;
absPos.y = parentPos.y + myRelPos.y;
absPos.z = parentPos.z + myRelPos.z;
absPositions.push_back(absPos);
}
}
} else {
absPositions = positions;
}
}
/**
* Rotates positions (and hence movement) around 0, 0, 0 counter-clockwise
*/
void Positionable::rotatePositions(double degrees){
if(positions.size() < 1){
return;
}
for(int i = 0; i < positions.size(); ++i){
double x = positions[i].x;
double y = positions[i].y;
double curAngle = 0.0;
double hypotenus = std::sqrt(x*x + y*y);
if(x != 0){
curAngle = std::atan(y/x);
}
positions[i].x = std::cos(curAngle + (PI * degrees) / 180.0) * hypotenus;
positions[i].y = std::sin(curAngle + (PI * degrees) / 180.0) * hypotenus;
}
if(parent != nullptr){
centerPositionsAroundParent();
}
}
static Position getPos(double time, std::vector<Position> positions){
if(positions.size() < 1){
return Position(time,0,0,0);
}
Position *low = nullptr, *high = nullptr;
double closeLow = 10000.0, closeHigh = 10000.0;
for(int i = 0; i < positions.size(); ++i){
if(time == positions[i].time){
return positions[i];
}
if(positions[i].time < time && time - positions[i].time < closeLow){
low = &positions[i];
closeLow = time - positions[i].time;
} else if(positions[i].time > time && positions[i].time - time < closeHigh){
high = &positions[i];
closeHigh = positions[i].time - time;
}
}
if(low != nullptr && high == nullptr){
Position ret(*low);
ret.time = time;
return ret;
} else if (low != nullptr && high != nullptr){
Position position;
double multTime = time - low->time;
double travelTime = high->time - low->time;
double travelX = high->x - low->x;
double travelY = high->y - low->y;
double travelZ = high->z - low->z;
position.x = low->x + travelX * (multTime / travelTime);
position.y = low->y + travelY * (multTime / travelTime);
position.z = low->z + travelZ * (multTime / travelTime);
position.time = time;
return position;
}
throw yntdl::YntdlException(yntdl::ErrorCode::POSITION_ERROR, std::to_string(time));
}
/**
* Computes position of positionable at a given time
*/
Position Positionable::getAbsPosition(double time){
if(absPositions.size() > 0){
return getPos(time, absPositions);
} else if (absPositions.size() < 1 && parent != nullptr){
centerPositionsAroundParent();
return getPos(time, absPositions);
} else {
return getPos(time, positions); //No parent to move relative to
}
}
/**
* Computes position of positionable at a given time
*/
Position Positionable::getPosition(double time){
return getPos(time, positions);
}
|
a8202b5f99e97841208e9a73d1cd22a79bc5976d
|
a0021d752f823b066b7ec0c0fd66a3ef26e85a86
|
/filetrans_client/BusProcessor.h
|
19cf79fb29b7a9de021c223d5ecdfaae841fd1ef
|
[] |
no_license
|
AlexGobin/filetrans_client
|
69085aa12aa4b8feb4f0f48799bde4ef23fd1877
|
c2907352e7092f5dfccb5dadbee8f6905b3e8d01
|
refs/heads/master
| 2020-04-13T15:59:07.198364
| 2019-01-14T14:05:28
| 2019-01-14T14:05:28
| 163,308,773
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 408
|
h
|
BusProcessor.h
|
#ifndef FT_BUS_MAIN_H_
#define FT_BUS_MAIN_H_
#include "user_event_handler.h"
class BusinessProcessor
{
public:
BusinessProcessor(std::shared_ptr<DispatchMsgService> dms);
bool init();
virtual ~BusinessProcessor();
private:
std::shared_ptr<DispatchMsgService> dms_;//账户接口分发系统
std::shared_ptr<UserEventHandler> ueh_; //账户管理系统
};
#endif
|
cd43d41a8a86b4c671998eead8f3a72d061ef988
|
199db94b48351203af964bada27a40cb72c58e16
|
/lang/sq/gen/Bible34.h
|
a87b58b947ff69ace491782d29dceab0bf510d09
|
[] |
no_license
|
mkoldaev/bible50cpp
|
04bf114c1444662bb90c7e51bd19b32e260b4763
|
5fb1fb8bd2e2988cf27cfdc4905d2702b7c356c6
|
refs/heads/master
| 2023-04-05T01:46:32.728257
| 2021-04-01T22:36:06
| 2021-04-01T22:36:06
| 353,830,130
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,258
|
h
|
Bible34.h
|
#include <map>
#include <string>
class Bible34
{
struct sq1 { int val; const char *msg; };
struct sq2 { int val; const char *msg; };
struct sq3 { int val; const char *msg; };
public:
static void view1() {
struct sq1 poems[] = {
{1, "1 Profecia mbi Niniven. Libri i vegimit të Nahumit nga Elkoshi."},
{2, "2 Zoti është një Perëndi xheloz dhe hakmarrës; Zoti është hakmarrës dhe plot tërbim. Zoti hakmerret me kundërshtarët e tij dhe e ruan zemërimin për armiqtë e tij."},
{3, "3 Zoti është i ngadalshëm në zemërim dhe pushtetmadh, por nuk e lë pa e ndëshkuar aspak të ligun. Zoti vazhdon rrugën e tij në shakullimë dhe në furtunë dhe retë janë pluhuri i këmbëve të tij."},
{4, "4 Ai e qorton rëndë detin dhe e than, i bën të thahen të gjithë lumenjtë. Bashani dhe Karmeli thahen dhe lulja e Libanit fishket."},
{5, "5 Malet dridhen para tij, kodrat treten; në prani të tij toka ngrihet, po, bota dhe tërë banorët e saj."},
{6, "6 Kush mund t'i rezistojë indinjatës së tij dhe kush mund të durojë zjarrin e zemërimit të tij? Tërbimi i tij derdhet si zjarr dhe shkëmbinjtë janë prej tij të thërmuara."},
{7, "7 Zoti është i mirë, është një fortesë në ditën e fatkeqësisë; ai i njeh ata që kërkojnë strehë tek ai."},
{8, "8 Por me një përmbytje të madhe ai do të kryejë një shkatërrim të plotë të vendit të tij dhe armiqtë e tij do të përndiqen nga terri."},
{9, "9 Çfarë projektoni kundër Zotit? Ai do të kryejë një shkatërrim të plotë: fatkeqësia nuk do të ndodhë dy herë."},
{10, "10 Edhe sikur të ishin si ferrat e dendura edhe të dehur nga vera që kanë pirë, ata do të gllabërohen si kashta fare e thatë."},
{11, "11 Prej teje doli ai që ka kurdisur të keqen kundër Zotit, ai që ka konceptuar ligësinë."},
{12, "12 Kështu thotë Zoti: Edhe sikur të ishin plot forcë dhe të shumtë, do të kositen dhe do të zhduken. Ndonëse të kam pikëlluar, nuk do të pikëlloj më."},
{13, "13 Tani do të thyej zgjedhën e saj nga trupi yt dhe do t'i shkul lidhjet e tua."},
{14, "14 Por lidhur me ty Zoti ka dhënë këtë urdhër: Emri yt nuk do të përjetësohet më. Nga tempulli i perëndive të tua do të zhduk figurat e gdhendura dhe ato të derdhura. Do të të përgatis varrin se je i neveritshëm."},
{15, "15 Ja mbi male këmbët e atij që njofton lajme të mira dhe që shpall paqen! Kremto festat e tua solemne, o Judë, plotëso betimet e tua, sepse i ligu nuk do të kalojë më në mes teje; ai do të shfaroset krejt."},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view2() {
struct sq2 poems[] = {
{1, "1 Ka dalë kundër teje një shkatërrues. Ruaje mirë fortesën, mbikqyr rrugën, forco ijët e tua, mblidh tërë forcat e tua."},
{2, "2 Sepse Zoti do të rivendosë lavdinë e Jakobit dhe lavdinë e Izraelit, sepse cubat i kanë plaçkitur dhe kanë shkatërruar shermendet e tyre."},
{3, "3 Mburoja e trimave të tij është ngjyrosur me të kuq, trimat e tij janë veshur me rroba të kuqe; ditën që ai përgatit hekuri i qerreve do të nxjerrë shkëndi si zjarri dhe do të vringëllojnë ushtat e qiparisit."},
{4, "4 Qerret do të lëshohen me tërbim nëpër rrugë do t'u bien kryq e tërthor shesheve; do të duken si pishtarë, do të vetëtijnë si rrufe."},
{5, "5 Ai do të kujtojë burrat e tij të fuqishëm, por ata do të pengohen në marshimin e tyre, do të sulen drejt mureve dhe mbrojtja do të përgatitet."},
{6, "6 Portat e lumenjve do të hapen dhe pallati do të shembet."},
{7, "7 Atë që rrinte palëvizur do ta zhveshin dhe do ta marrin; shërbëtoret e saj do të vajtojnë me zë si të pëllumbeshës, duke i rënë gjoksit."},
{8, "8 Ndonëse Ninive i kohëve të kaluara ishte si një rezervuar uji, tani ata ikin. Ndaluni, ndaluni!, bërtasin, por askush nuk kthehet."},
{9, "9 Plaçkitni argjendin, plaçkitni arin! Ka thesare pa fund, pasuri të çfarëdo sendi të çmuar."},
{10, "10 Ai është i shkretuar, bosh dhe i rrënuar; zemra ligështohet, gjunjët dridhen, ka një dhembje të madhe në të gjitha ijët dhe tërë fytyrat e tyre zverdhen."},
{11, "11 Ku është strofka e luanëve, vendi ku ushqeheshin luanët e vegjël, ku silleshin luani, luanesha dhe të vegjëlit e saj dhe askush nuk i trembte?"},
{12, "12 Luani shqyente për të vegjëlit e tij, mbyste për luaneshat e tij dhe mbushte strofkat e tij me gjah dhe strofullat me gjënë e grabitur."},
{13, "13 Ja, unë jam kundër teje, thotë Zoti i ushtrive, unë do t'i djeg dhe do t'i bëj tym qerret e tua dhe shpata do të gllabërojë luanët e tu të vegjël; unë do të zhduk grabitjen tënde nga dheu dhe zëri i lajmëtarëve të tu nuk do të dëgjohet më."},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view3() {
struct sq3 poems[] = {
{1, "1 Mjerë qyteti gjakatar, që është plot me hile dhe me dhunë dhe që nuk po heq dorë nga grabitjet!"},
{2, "2 Kërcet kamxhiku, zhurmë shurdhuese rrotash, kuajsh që vrapojnë dhe qerresh që hovin,"},
{3, "3 kalorës në sulm shpata flakëruese, ushta që shndritin, një shumicë e madhe të vrarësh, të vdekur të shumtë, kufoma pa fund; pengohesh te kufomat."},
{4, "4 Të gjitha këto për shkak të kurvërimeve të shumta të prostitutes joshëse, mjeshtre në artet magjike që i shiste kombet me kurvërimet e saj dhe popujt me artet e saj magjike."},
{5, "5 Ja, unë jam kundër teje, thotë Zoti i ushtrive, unë do të ngre cepat e rrobës sate deri në fytyrë dhe do t'u tregoj kombeve lakuriqësinë tënde dhe mbretërive turpin tënd."},
{6, "6 Do të të hedh përsipër ndyrësi, do të të bëj të neveritshme dhe do të të nxjerr te shtylla e turpit."},
{7, "7 Do të ndodhë që të gjithë ata që do të të shikojnë do të largohen prej teje dhe do të thonë: Ninive është shkretuar! Kujt do t'i vijë keq për të?. Ku t'i kërkoj ngushëllonjësit e saj?."},
{8, "8 A je më e bukur se No-Amoni, që ndodhet midis kanaleve të Nilit, i rrethuar nga ujërat dhe që e kishte detin si ledh dhe detin si mur?"},
{9, "9 Etiopia dhe Egjipti ishin forca e tij dhe nuk kishin kufi; Puti dhe Libianët ishin aleatët e tij."},
{10, "10 Megjithatë edhe ai u internua, shkoi në robëri; edhe fëmijët e tij u bënë copë-copë në hyrje të çdo rruge; kanë hedhur shortin mbi fisnikët e tij dhe tërë të mëdhenjtë e tij u lidhën me zinxhirë."},
{11, "11 Ti gjithashtu do të jesh e dehur dhe do të fshihesh; ti gjithashtu do të kërkosh një vend të fortifikuar përpara armikut."},
{12, "12 Tërë fortesat e tua do të jenë si druri i fikut me fiq të parë; po t'i shkundësh, bien në gojë të atij që i ha."},
{13, "13 Ja, trupat e tua në mes teje janë si gra; portat e vendit tënd janë të hapura përpara armiqve të tu; zjarri ka gllabëruar hekurat e portave të tua."},
{14, "14 Mblidh për vete ujin e nevojshëm për rrethimin, përforco fortifikimet e tua, ngjeshe argjilën, punoje llaçin, ndreqe furrën për tulla."},
{15, "15 Atje zjarri do të të gllabërojë, shpata do të të shkatërrojë, do të të hajë si një larvë karkaleci; shumohu si larvat e karkalecave, shumohu si karkalecat."},
{16, "16 I ke shumuar tregjet e tua më tepër se yjet e qiellit; larvat e karkalecave zhveshin çdo gjë dhe pastaj fluturojnë tutje."},
{17, "17 Princat e tu janë si karkalecat, oficerët e tu si mizëri karkalecash që ndalen midis gjerdheve në ditët e ftohta; po, kur del dielli, fluturojnë tutje, por nuk dihet se ku kanë shkuar."},
{18, "18 O mbret i Asirisë, barinjtë e tu po flenë, fisnikët e tu pushojnë; populli yt u shpërnda ndër male dhe kurrkush nuk po i mbledh."},
{19, "19 Nuk ka ilaç për plagën tënde, plaga jote është vdekjeprurëse; të gjithë ata që do të dëgjojnë të flitet për ty, do të përplasin duart për fatin tënd. Sepse mbi kë nuk është ushtruar vazhdimisht ligësia jote?"},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
};
|
315c0eb6fb8cc00c7bf57dc2178b79a3225148c4
|
f8c5ff527dfb289f4f9f98b0f48d08a0deb9da84
|
/lab1/V1.0/dllist.h
|
e13cc6d30d169dd700c8a75df631710dd975fa99
|
[
"Apache-2.0"
] |
permissive
|
centurion-crawler/os-nachos
|
8d8520fae71bcba6df3b77658fbd2c271e279bc0
|
f6f07c02c58f52419ed63d0751d686a72ac675c4
|
refs/heads/main
| 2023-05-07T03:36:22.580272
| 2021-05-13T06:40:49
| 2021-05-13T06:40:49
| 349,126,230
| 0
| 0
|
Apache-2.0
| 2021-03-18T15:33:34
| 2021-03-18T15:33:34
| null |
UTF-8
|
C++
| false
| false
| 1,277
|
h
|
dllist.h
|
#ifndef DLLIST_H
#define DLLIST_H
class DLLElement{
public:
DLLElement(void* itemPtr, int sortKey); // initialize a list element
DLLElement *next; // next element on the list, NULL if last
DLLElement *prev; // previous element on the list, NULL if first
int key; // priority, for a sorted list
void *item; // pointer to item on the list
};
class DLList{
public:
DLList(); // initialize a list
~DLList(); // destroy or de-allocate a list
void Prepend(void *item); // add to head of the list
void Append(void *item); // add to tail of the list
void *Remove(int *keyPtr); // remove from head of the list
void Print();
bool IsEmpty(); // check if list is empty return true
void SortedInsert(void *item, int sortKey); // insert a item before/after with key==sortkey
void *SortedRemove(int sortKey); // remove first item with key==sortKey
// return NULL if no such item exist
private:
DLLElement *first; // head of the list, NULL if empty
DLLElement *last; // last element of the list, NULL if empty
};
int GenerateInt(int);
bool CreateDLList(DLList*,int,int);
bool RemoveItems(DLList* ,int ,int);
#endif
|
db05958fa855f84d18f93d8d34ad5bc7ec6c11fb
|
4dc91b14630d507d32ec75c7c099ba3576b07232
|
/CTPPSAnalysisTools/plugins/TestAnalyzer.cc
|
452b7862485dfe13a2d87a9abc584fb5ad1d88d2
|
[] |
no_license
|
beatrizlopes/TopLJets
|
6b62ccfd5249f6d0d06c04a487e638958df229af
|
198250ab1eae8a6a11b66dad626a827f46ec0092
|
refs/heads/master
| 2023-06-21T20:10:46.840262
| 2019-08-01T10:44:01
| 2019-08-01T10:44:01
| 198,248,791
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,337
|
cc
|
TestAnalyzer.cc
|
// -*- C++ -*-
//
// Package: CTPPSAnalysisTools/Analyzer
// Class: TestAnalyzer
//
/**\class TestAnalyzer TestAnalyzer.cc CTPPSAnalysisTools/Analyzer/plugins/TestAnalyzer.cc
Description: [one line class summary]
Implementation:
[Notes on implementation]
*/
//
// Original Author: Laurent Forthomme
// Created: Fri, 23 Feb 2018 10:49:41 GMT
//
//
#include <memory>
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/one/EDAnalyzer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/ServiceRegistry/interface/Service.h"
#include "CommonTools/UtilAlgos/interface/TFileService.h"
#include "DataFormats/CTPPSDetId/interface/CTPPSDetId.h"
#include "DataFormats/CTPPSReco/interface/CTPPSLocalTrackLite.h"
#include "../interface/AlignmentsFactory.h"
#include "../interface/LHCConditionsFactory.h"
#include "../interface/XiReconstructor.h"
#include "TH1D.h"
#include "TH2D.h"
class TestAnalyzer : public edm::one::EDAnalyzer<edm::one::SharedResources>
{
public:
explicit TestAnalyzer( const edm::ParameterSet& );
~TestAnalyzer() {}
static void fillDescriptions( edm::ConfigurationDescriptions& descriptions );
private:
virtual void beginJob() override;
virtual void analyze( const edm::Event&, const edm::EventSetup& ) override;
virtual void endJob() override;
edm::EDGetTokenT<std::vector<CTPPSLocalTrackLite> > ctppsTracksToken_;
std::vector<unsigned int> rps_considered_;
ctpps::AlignmentsFactory aligns_;
ctpps::LHCConditionsFactory lhc_conds_;
ctpps::XiReconstructor xi_reco_;
std::map<unsigned short,TH2D*> h2_hitmaps_;
std::map<unsigned short,TH1D*> h_xi_;
};
TestAnalyzer::TestAnalyzer( const edm::ParameterSet& iConfig ) :
ctppsTracksToken_( consumes<std::vector<CTPPSLocalTrackLite> >( iConfig.getParameter<edm::InputTag>( "ctppsTracksTag" ) ) ),
rps_considered_( iConfig.getParameter<std::vector<unsigned int> >( "potsConsidered" ) ) // TOTEM decimal notation!
{
// retrieve all LUTs
if ( iConfig.existsAs<edm::FileInPath>( "ctppsAlignmentsFile" ) )
aligns_.feedAlignments( iConfig.getParameter<edm::FileInPath>( "ctppsAlignmentsFile" ).fullPath().c_str() );
if ( iConfig.existsAs<edm::FileInPath>( "lhcConditionsFile" ) )
lhc_conds_.feedConditions( iConfig.getParameter<edm::FileInPath>( "lhcConditionsFile" ).fullPath().c_str() );
if ( iConfig.existsAs<edm::FileInPath>( "ctppsDispersionsFile" ) )
xi_reco_.feedDispersions( iConfig.getParameter<edm::FileInPath>( "ctppsDispersionsFile" ).fullPath().c_str() );
usesResource( "TFileService" );
edm::Service<TFileService> fs;
for ( const auto& rp : rps_considered_ ) {
TFileDirectory pot_dir = fs->mkdir( Form( "pot_%d", rp ) );
h2_hitmaps_[rp] = pot_dir.make<TH2D>( Form( "hitmap_%d", rp ), Form( "Pot %d;x (cm);y (cm)", rp ), 100, 0., 5., 100, -2.5, 2.5 );
h_xi_[rp] = pot_dir.make<TH1D>( Form( "xi_%d", rp ), Form( "Pot %d;#xi_{track};Events", rp ), 100, 0., 0.2 );
}
}
// ------------ method called for each event ------------
void
TestAnalyzer::analyze( const edm::Event& iEvent, const edm::EventSetup& iSetup )
{
const edm::EventID ev_id = iEvent.id();
// LHC information retrieval from LUT
const ctpps::conditions_t lhc_cond = lhc_conds_.get( ev_id );
const double xangle = lhc_cond.crossing_angle;
// CTPPS tracks retrieval
// /!\ all tracks positions expressed in mm!
edm::Handle<std::vector<CTPPSLocalTrackLite> > rpTracks;
iEvent.getByToken( ctppsTracksToken_, rpTracks );
for ( const auto& trk : *rpTracks ) {
const CTPPSDetId detid( trk.getRPId() );
// transform the raw, 32-bit unsigned integer detId into the TOTEM "decimal" notation
const unsigned short raw_id = 100*detid.arm()+10*detid.station()+detid.rp();
//if ( detid.station() == 1 ) continue; // skip the diamonds/UFSD for the moment
if ( std::find( rps_considered_.begin(), rps_considered_.end(), raw_id ) == rps_considered_.end() )
continue; // only keep the pots we are interested in
const ctpps::alignment_t align = aligns_.get( ev_id, raw_id );
const double trk_x_corr = ( trk.getX()/10.+align.x_align );
h2_hitmaps_[raw_id]->Fill( trk_x_corr, trk.getY()/10. ); // expressed in cm
double xi = 0., xi_err = 0.;
try {
xi_reco_.reconstruct( xangle, raw_id, trk_x_corr, xi, xi_err );
h_xi_[raw_id]->Fill( xi );
} catch ( std::runtime_error ) {
// avoids to break the processing if a xing angle value was not found
// (additional ones will be added as soon as they are available)
continue;
}
}
}
// ------------ method called once each job just before starting event loop ------------
void
TestAnalyzer::beginJob()
{}
// ------------ method called once each job just after ending the event loop ------------
void
TestAnalyzer::endJob()
{}
// ------------ method fills 'descriptions' with the allowed parameters for the module ------------
void
TestAnalyzer::fillDescriptions( edm::ConfigurationDescriptions& descriptions )
{
edm::ParameterSetDescription desc;
desc.setUnknown();
descriptions.addDefault( desc );
}
//define this as a plug-in
DEFINE_FWK_MODULE( TestAnalyzer );
|
320bd9ec7d53bc4b55c9a8e12f114f922422bc5a
|
b4ff3270de066f217681a93f521a2ad68bfef932
|
/src/pyhooks.h
|
40a064d12829f837a48f3b9b4c1ed5368763d253
|
[] |
no_license
|
asmfakhrul/cyclus
|
9a988e677fe3a0a438cb55f4bbef330744c23dd3
|
aab40e97d779657c50ce927419fde58c7b035b33
|
refs/heads/master
| 2021-08-28T17:15:12.530953
| 2017-12-12T22:03:47
| 2017-12-12T22:03:47
| 106,435,279
| 0
| 0
| null | 2017-10-10T15:24:30
| 2017-10-10T15:24:29
| null |
UTF-8
|
C++
| false
| false
| 1,979
|
h
|
pyhooks.h
|
#ifndef CYCLUS_SRC_PYHOOKS_H_
#define CYCLUS_SRC_PYHOOKS_H_
#include <string>
namespace cyclus {
class Agent;
/// Because of NumPy #7595, we can only initialize & finalize the Python
/// interpreter once. This variable keeps a count of how many times we have
/// initialized so that we can know when to really stop the interpreter.
/// When Python binding are not installed, this will always remain zero.
extern int PY_INTERP_COUNT;
/// Whether or not the Python interpreter has been initilized.
extern bool PY_INTERP_INIT;
/// Convience function for appending to import table for initialization
void PyAppendInitTab(void);
/// Convience function for import initialization
void PyImportInit(void);
/// Convience function for imports when Python has already been started
void PyImportCallInit(void);
/// Initialize Python functionality, this is a no-op if Python was not
/// installed along with Cyclus. This may be called many times and safely
/// initializes the Python interpreter only once.
void PyStart(void);
/// Closes the current Python session. This is a no-op if Python was
/// not installed with Cyclus. This may safely be called many times.
void PyStop(void);
// Add some simple shims that attach C++ to Python C hooks
void EventLoop(void);
/// Finds a Python module and returns its filename.
std::string PyFindModule(std::string);
/// Finds a Python module and returns an agent pointer from it.
Agent* MakePyAgent(std::string, std::string, void*);
/// Removes all Python agents from the internal cache. There is usually
/// no need for a user to call this.
void ClearPyAgentRefs(void);
/// Removes a single Python agent from the reference cache.
void PyDelAgent(int);
namespace toolkit {
/// Convert Python simulation string to JSON
std::string PyToJson(std::string);
/// Convert JSON string to Python simulation string
std::string JsonToPy(std::string);
} // ends namespace toolkit
} // ends namespace cyclus
#endif // ends CYCLUS_SRC_PYHOOKS_H_
|
6ba22f77583b002bfa83db12e1a4c7cab5dc327e
|
40759a3d38a71023670f6510a0b03c1c84c471f7
|
/merge.h
|
1f7a644159addd997e82910981766f29682879bc
|
[
"Apache-2.0"
] |
permissive
|
phaistos-networks/Trinity
|
f78cb880fe6d24dc331659b034f97c4e19be3836
|
a745a0c13719ca9d041e1dfcfeb81e6bf85a996f
|
refs/heads/master
| 2021-01-19T04:34:31.721194
| 2019-11-08T18:12:31
| 2019-11-08T18:12:31
| 84,192,219
| 250
| 23
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,464
|
h
|
merge.h
|
#pragma once
#include "docidupdates.h"
#include "terms.h"
#include "index_source.h"
namespace Trinity {
struct merge_candidate final {
// generation of the index source
// See IndexSource::gen
uint64_t gen;
// Access to all terms of the index source
IndexSourceTermsView *terms;
// Faciliates access to the index and other content
Trinity::Codecs::AccessProxy *ap;
// All documents masked in this index source
// more recent candidates(i.e candidates where gen < this gen) will use it
// see MergeCandidatesCollection::merge() impl.
updated_documents maskedDocuments;
merge_candidate &operator=(const merge_candidate &o) {
gen = o.gen;
terms = o.terms;
ap = o.ap;
new (&maskedDocuments) updated_documents(o.maskedDocuments);
return *this;
}
};
// See IndexSourcesCollection
class MergeCandidatesCollection final {
private:
std::vector<updated_documents> all;
std::vector<std::pair<merge_candidate, uint16_t>> map;
public:
std::vector<merge_candidate> candidates;
public:
auto size() const noexcept {
return candidates.size();
}
void insert(const merge_candidate c) {
candidates.push_back(c);
}
void commit();
std::unique_ptr<Trinity::masked_documents_registry> scanner_registry_for(const uint16_t idx);
// This method will merge all registered merge candidates into a new index session and will also output all
// distinct terms and their term_index_ctx.
// It will properly and optimally handle different input codecs and mismatches between output codec(i.e is->codec_identifier() )
// and input codecs.
//
// You may want to use
// - Trinity::pack_terms() to build the terms files and then persist them
// - Trinity::persist_segment() to persist the actual index
//
// IMPORTANT:
// You should use consider_tracked_sources() after you have merge()ed to figure out what to do with all tracked sources.
//
// You are expected to outIndexSess->begin() before you merge(), and outIndexSess->end() afterwards, though you may
// want to use Trinity::persist_segment(outIndexSess) which will persist and invoke end() for you
//
// You may want to explicitly disable use of IndexSession::append_index_chunk() and IndexSession::merge(), even if it is supported by the outIndexSess's codec.
// If you are going to use ExecFlags::AccumulatedScoreScheme, and your scorer depends on IndexSource::field_statistics, those are
// only computed, during merge, for terms that are not handled by append_index_chunk(), so you may want to disable it, so that
// statistics for those terms as well will be collected.
void merge(Codecs::IndexSession *outIndexSess,
simple_allocator *,
std::vector<std::pair<str8_t, term_index_ctx>> *const outTerms,
IndexSource::field_statistics * fs,
const uint32_t flushFreq = 0,
const bool disableOptimizations = false);
enum class IndexSourceRetention : uint8_t {
RetainAll = 0,
RetainDocumentIDsUpdates,
Delete
};
// Once you have committed(), and merge(d), you should provide
// all tracked sources, and this method will return another vector with a std::pair<IndexSourceRetention, uint64_t>
// for each of the sources(identified by generation) that you should consider;
// RetainAll: don't delete anything, leave it alone
// RetainDocumentIDsUpdates: delete all index files but retain document IDs updates files
// Delete: wipe out the directory, retain nothing
std::vector<std::pair<uint64_t, IndexSourceRetention>> consider_tracked_sources(std::vector<uint64_t> trackedSources);
};
} // namespace Trinity
static inline void PrintImpl(Buffer &b, const Trinity::MergeCandidatesCollection::IndexSourceRetention r) {
switch (r) {
case Trinity::MergeCandidatesCollection::IndexSourceRetention::RetainAll:
b.append("ALL"_s32);
break;
case Trinity::MergeCandidatesCollection::IndexSourceRetention::RetainDocumentIDsUpdates:
b.append("DocIDs"_s32);
break;
case Trinity::MergeCandidatesCollection::IndexSourceRetention::Delete:
b.append("DELETE"_s32);
break;
}
}
|
d2e375aa65fc690372a92823b50540b88d06b385
|
70fbdb1feb44ca959edfdca3fac550a87c654c94
|
/src/activeobject/Activation_Queue.cpp
|
88131c2875dfe537f856ff645bcf0d78c1ff86e0
|
[] |
no_license
|
774280605/server
|
6f7898bd7090c9ba0256e32e0b131cfea00c5bc9
|
3676f1409c0891495182125c6d63ad67d03afa8b
|
refs/heads/master
| 2020-09-07T13:38:22.088638
| 2019-12-02T14:05:45
| 2019-12-02T14:05:45
| 220,797,881
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 272
|
cpp
|
Activation_Queue.cpp
|
//
// Created by zxf on 2019/11/24.
//
#include "Activation_Queue.h"
Method_Request* Activation_Queue::remove(Method_Request *methodRequest) {
return queue_.front();
}
void Activation_Queue::insert(Method_Request *methodRequest) {
queue_.push(methodRequest);
}
|
8b0586b9527b118bf903574c6c177e527ae5a62f
|
a254c8cf26e20bf46be45634a1df2bae55a274e2
|
/temp_humi_press_sketch.ino
|
cb65f54a87e529bfa3639c5e748eba8ab95476ba
|
[] |
no_license
|
bruderbb/esp8266-BME280
|
9d7a84f743fb6181e9168ab9472c3ec46e5d94e8
|
066bda211c4845caf22f205c59214f95d58c77c4
|
refs/heads/master
| 2021-01-20T00:15:47.660242
| 2016-04-12T08:09:10
| 2016-04-12T08:09:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,011
|
ino
|
temp_humi_press_sketch.ino
|
#include <ESP8266WiFi.h>
#include <Adafruit_MQTT.h>
#include <Adafruit_MQTT_Client.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#define SEALEVELPRESSURE_HPA (1013.25)
Adafruit_BME280 bme; // I2C
//Adafruit_BME280 bme(BME_CS); // hardware SPI
//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK);
/************************* WiFi Access Point *********************************/
#define WLAN_SSID "*******"
#define WLAN_PASS "*******"
/************************* MQTT Broker Setup *********************************/
const int MQTT_PORT = 12665;
const char MQTT_SERVER[] PROGMEM = "m11.cloudmqtt.com";
const char MQTT_CLIENTID[] PROGMEM = "ESP-PUBLISHER-SERVICE";
const char MQTT_USERNAME[] PROGMEM = "******";
const char MQTT_PASSWORD[] PROGMEM = "******";
WiFiClient client;
Adafruit_MQTT_Client mqtt(&client, MQTT_SERVER, MQTT_PORT, MQTT_CLIENTID, MQTT_USERNAME, MQTT_PASSWORD);
/****************************** Feeds ***************************************/
const char TEMPERATURE_FEED[] PROGMEM = "sweethome/sensors/outdoor/temperature";
Adafruit_MQTT_Publish temperature_topic = Adafruit_MQTT_Publish(&mqtt, TEMPERATURE_FEED);
const char PRESSURE_FEED[] PROGMEM = "sweethome/sensors/outdoor/pressure";
Adafruit_MQTT_Publish pressure_topic = Adafruit_MQTT_Publish(&mqtt, PRESSURE_FEED);
const char HUMIDITY_FEED[] PROGMEM = "sweethome/sensors/outdoor/humidity";
Adafruit_MQTT_Publish humidity_topic = Adafruit_MQTT_Publish(&mqtt, HUMIDITY_FEED);
/*************************** Sketch Code ************************************/
void setup() {
Serial.begin(115200);
delay(10);
Serial.println("Sensor Test");
if (!bme.begin())
{
Serial.print("Ooops, no BME280 detected ... Check your wiring or I2C ADDR!");
while (1);
}
else {
Serial.println("BME280 ready.");
}
// Connect to WiFi access point.
Serial.println();
Serial.print("Connecting to ");
Serial.println(WLAN_SSID);
WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
Serial.println("IP address: "); Serial.println(WiFi.localIP());
}
void MQTT_connect() {
int8_t ret;
// Stop if already connected.
if (mqtt.connected()) {
return;
}
Serial.print("Connecting to MQTT... ");
while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
switch (ret) {
case 1: Serial.println("Wrong protocol"); break;
case 2: Serial.println("ID rejected"); break;
case 3: Serial.println("Server unavailable"); break;
case 4: Serial.println("Bad user/password"); break;
case 5: Serial.println("Not authenticated"); break;
case 6: Serial.println("Failed to subscribe"); break;
default: Serial.print("Couldn't connect to server, code: ");
Serial.println(ret);
break;
}
Serial.println("Retrying MQTT connection in 5 seconds...");
mqtt.disconnect();
delay(5000);// wait 5 seconds
}
Serial.println("MQTT Connected!");
}
void loop() {
MQTT_connect();
float temperature = bme.readTemperature();
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" C");
Serial.print("Publish Temperature: ");
if (! temperature_topic.publish(temperature)) {
Serial.println("Failed");
} else {
Serial.println("OK!");
}
float pressure = bme.readPressure() / 100.0F;
Serial.print("Pressure: ");
Serial.print(pressure);
Serial.println(" hPa");
Serial.print("Publish Pressure: ");
if (! pressure_topic.publish(pressure)) {
Serial.println("Failed");
} else {
Serial.println("OK!");
}
float humidity = bme.readHumidity();
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println(" %");
Serial.print("Publish Humidity: ");
if (! humidity_topic.publish(humidity)) {
Serial.println("Failed");
} else {
Serial.println("OK!");
}
delay(5000);
}
|
55b4ff48b7d276acb0455d61e8a6757852eab0b8
|
b1cca159764e0cedd802239af2fc95543c7e761c
|
/ext/libgecode3/vendor/gecode-3.7.3/test/set.hh
|
80709886ba9533915cf310e633c75782876ac5f2
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
chef/dep-selector-libgecode
|
b6b878a1ed4a6c9c6045297e2bfec534cf1a1e8e
|
76d7245d981c8742dc539be18ec63ad3e9f4a16a
|
refs/heads/main
| 2023-09-02T19:15:43.797125
| 2021-08-24T17:02:02
| 2021-08-24T17:02:02
| 18,507,156
| 8
| 18
|
Apache-2.0
| 2023-08-22T21:15:31
| 2014-04-07T05:23:13
|
Ruby
|
UTF-8
|
C++
| false
| false
| 11,729
|
hh
|
set.hh
|
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Guido Tack <tack@gecode.org>
* Christian Schulte <schulte@gecode.org>
*
* Copyright:
* Guido Tack, 2005
* Christian Schulte, 2005
*
* Last modified:
* $Date: 2011-07-12 20:49:06 +1000 (Tue, 12 Jul 2011) $ by $Author: tack $
* $Revision: 12172 $
*
* This file is part of Gecode, the generic constraint
* development environment:
* http://www.gecode.org
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#ifndef __GECODE_TEST_SET_HH__
#define __GECODE_TEST_SET_HH__
#include <gecode/set.hh>
#include "test/test.hh"
#include "test/int.hh"
namespace Test {
/// Testing finite sets
namespace Set {
/**
* \defgroup TaskTestSet Testing finite sets
* \ingroup TaskTest
*/
/// Fake space for creation of regions
class FakeSpace : public Gecode::Space {
public:
/// Faked constructor
FakeSpace(void) {}
/// Faked copy function
virtual Gecode::Space* copy(bool share) {
(void) share;
return NULL;
}
};
/**
* \defgroup TaskTestSetSupport General set test support
* \ingroup TaskTestSet
*/
//@{
/// Value iterator producing subsets of an IntSet
class CountableSetValues {
private:
Gecode::IntSetValues dv;
int cur;
int i;
public:
/// Default constructor
CountableSetValues(void) {}
/// Initialize with set \a d0 and bit-pattern \a cur0
CountableSetValues(const Gecode::IntSet& d0, int cur0)
: dv(d0), cur(cur0), i(1) {
if (! (i & cur))
operator++();
}
/// Initialize with set \a d0 and bit-pattern \a cur0
void init(const Gecode::IntSet& d0, int cur0) {
dv = d0;
cur = cur0;
i = 1;
if (! (i & cur))
operator++();
}
/// Test if finished
bool operator()(void) const {
return i<=cur;
}
/// Move to next value
void operator++(void) {
do {
++dv;
i = i<<1;
} while (! (i & cur) && i<cur);
}
/// Return current value
int val(void) const { return dv.val(); }
};
/// Range iterator producing subsets of an IntSet
class CountableSetRanges
: public Gecode::Iter::Values::ToRanges<CountableSetValues> {
private:
/// The corresponding value iterator
CountableSetValues v;
public:
/// Default constructor
CountableSetRanges(void) {}
/// Initialize with set \a d0 and bit-pattern \a cur0
CountableSetRanges(const Gecode::IntSet& d, int cur) : v(d, cur) {
Gecode::Iter::Values::ToRanges<CountableSetValues>::init(v);
}
/// Initialize with set \a d0 and bit-pattern \a cur0
void init(const Gecode::IntSet& d, int cur) {
v.init(d, cur);
Gecode::Iter::Values::ToRanges<CountableSetValues>::init(v);
}
};
/// Iterate all subsets of a given set
class CountableSet {
private:
/// The superset
Gecode::IntSet d;
/// Integer representing the current subset to iterate
unsigned int cur;
/// Endpoint of iteration
unsigned int lubmax;
public:
/// Initialize with set \a s
CountableSet(const Gecode::IntSet& s);
/// Default constructor
CountableSet(void) {}
/// Initialize with set \a s
void init(const Gecode::IntSet& s);
/// Check if still subsets left
bool operator()(void) const { return cur<lubmax; }
/// Move to next subset
void operator++(void);
/// Return current subset
int val(void) const;
};
/// Generate all set assignments
class SetAssignment {
private:
/// Arity
int n;
/// Iterator for each set variable
CountableSet* dsv;
/// Iterator for int variable
Test::Int::CpltAssignment ir;
/// Flag whether all assignments have been generated
bool done;
public:
/// The common superset for all domains
Gecode::IntSet lub;
/// How many integer variables to iterate
int withInt;
/// Initialize with \a n set variables, initial bound \a d and \a i int variables
SetAssignment(int n, const Gecode::IntSet& d, int i = 0);
/// Test whether all assignments have been iterated
bool operator()(void) const { return !done; }
/// Move to next assignment
void operator++(void);
/// Return value for variable \a i
int operator[](int i) const {
assert((i>=0) && (i<n));
return dsv[i].val();
}
/// Return value for first integer variable
int intval(void) const { return ir[0]; }
/// Return assignment for integer variables
const Test::Int::Assignment& ints(void) const { return ir; }
/// Return arity
int size(void) const { return n; }
/// Destructor
~SetAssignment(void) { delete [] dsv; }
};
class SetTest;
/// Space for executing set tests
class SetTestSpace : public Gecode::Space {
public:
/// Initial domain
Gecode::IntSet d;
/// Set variables to be tested
Gecode::SetVarArray x;
/// Int variables to be tested
Gecode::IntVarArray y;
/// How many integer variables are used by the test
int withInt;
/// Control variable for reified propagators
Gecode::BoolVar b;
/// Whether the test is for a reified propagator
bool reified;
/// The test currently run
SetTest* test;
/**
* \brief Create test space
*
* Creates \a n set variables with domain \a d0,
* \a i integer variables with domain \a d0, and stores whether
* the test is for a reified propagator (\a r), and the test itself
* (\a t).
*
*/
SetTestSpace(int n, Gecode::IntSet& d0, int i, bool r, SetTest* t,
bool log=true);
/// Constructor for cloning \a s
SetTestSpace(bool share, SetTestSpace& s);
/// Copy space during cloning
virtual Gecode::Space* copy(bool share);
/// Post propagator
void post(void);
/// Compute a fixpoint and check for failure
bool failed(void);
/// Perform set tell operation on \a x[i]
void rel(int i, Gecode::SetRelType srt, const Gecode::IntSet& is);
/// Perform cardinality tell operation on \a x[i]
void cardinality(int i, int cmin, int cmax);
/// Perform integer tell operation on \a y[i]
void rel(int i, Gecode::IntRelType irt, int n);
/// Perform Boolean tell on \a b
void rel(bool sol);
/// Assign all variables to values in \a a
void assign(const SetAssignment& a);
/// Test whether all variables are assigned
bool assigned(void) const;
/// Remove value \a v from the upper bound of \a x[i]
void removeFromLub(int v, int i, const SetAssignment& a);
/// Remove value \a v from the lower bound of \a x[i]
void addToGlb(int v, int i, const SetAssignment& a);
/// Perform fixpoint computation
bool fixprob(void);
/// Perform random pruning
bool prune(const SetAssignment& a);
};
/**
* \brief %Base class for tests with set constraints
*
*/
class SetTest : public Base {
private:
/// Number of variables
int arity;
/// Domain of variables (least upper bound)
Gecode::IntSet lub;
/// Does the constraint also exist as reified constraint
bool reified;
/// Number of additional integer variables
int withInt;
/// Remove \a v values from the least upper bound of \a x, but not those in \f$\mathrm{a}_i\f$
void removeFromLub(int v, Gecode::SetVar& x, int i,
const Gecode::IntSet& a);
/// Add \a v values to the greatest lower bound of \a x, but not those in \f$\mathrm{a}_i\f$
void addToGlb(int v, Gecode::SetVar& x, int i, const Gecode::IntSet& a);
SetAssignment* make_assignment(void);
public:
/**
* \brief Constructor
*
* Constructs a test with name \a s and arity \a a and variable
* domain \a d. Also tests for a reified constraint,
* if \a r is true. In addition, \a w integer variables are provided.
*/
SetTest(const std::string& s,
int a, const Gecode::IntSet& d, bool r=false, int w=0)
: Base("Set::"+s), arity(a), lub(d), reified(r), withInt(w) {}
/// Check for solution
virtual bool solution(const SetAssignment&) const = 0;
/// Post propagator
virtual void post(Gecode::Space& home, Gecode::SetVarArray& x,
Gecode::IntVarArray& y) = 0;
/// Post reified propagator
virtual void post(Gecode::Space&, Gecode::SetVarArray&,
Gecode::IntVarArray&, Gecode::BoolVar) {}
/// Perform test
virtual bool run(void);
/// \name Mapping scalar values to strings
//@{
/// Map set relation to string
static std::string str(Gecode::SetRelType srt);
/// Map set operation to string
static std::string str(Gecode::SetOpType srt);
/// Map integer to string
static std::string str(int i);
/// Map integer array to string
static std::string str(const Gecode::IntArgs& i);
//@}
};
//@}
/// Iterator for set relation types
class SetRelTypes {
private:
/// Array of relation types
static const Gecode::SetRelType srts[6];
/// Current position in relation type array
int i;
public:
/// Initialize iterator
SetRelTypes(void);
/// Test whether iterator is done
bool operator()(void) const;
/// Increment to next relation type
void operator++(void);
/// Return current relation type
Gecode::SetRelType srt(void) const;
};
/// Iterator for Boolean operation types
class SetOpTypes {
private:
/// Array of operation types
static const Gecode::SetOpType sots[4];
/// Current position in operation type array
int i;
public:
/// Initialize iterator
SetOpTypes(void);
/// Test whether iterator is done
bool operator()(void) const;
/// Increment to next operation type
void operator++(void);
/// Return current operation type
Gecode::SetOpType sot(void) const;
};
}}
/**
* \brief Print assignment \a
* \relates SetAssignment
*/
std::ostream&
operator<<(std::ostream&, const Test::Set::SetAssignment& a);
#include "test/set.hpp"
#endif
// STATISTICS: test-set
|
5d8a6f24f22c26a469a00c49051812e146062fd2
|
f86a8fc715b8354e50314122a2a1a1b33cf351a1
|
/src/Core/ITKCommon/ThreadUtils/the_thread_pool.cxx
|
912685834f51341e26ecddd243eb5cd2a42963b8
|
[
"MIT"
] |
permissive
|
SCIInstitute/Seg3D
|
579e2a61ee8189a8c8f8249e9a680d3231c0ff3a
|
84ba5fd7672ca7d08f9f60a95ef4b68f0c81a090
|
refs/heads/master
| 2023-04-21T05:21:08.795420
| 2023-04-07T17:32:36
| 2023-04-07T17:32:36
| 32,550,368
| 103
| 51
| null | 2023-04-07T17:32:38
| 2015-03-19T22:49:29
|
C++
|
UTF-8
|
C++
| false
| false
| 18,586
|
cxx
|
the_thread_pool.cxx
|
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2016 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
// File : the_thread_pool.cxx
// Author : Pavel A. Koshevoy
// Created : Wed Feb 21 09:01:00 MST 2007
// Copyright : (C) 2004-2008 University of Utah
// Description : A thread pool class.
// local includes:
#include <Core/ITKCommon/ThreadUtils/the_thread_pool.hxx>
#include <Core/ITKCommon/ThreadUtils/the_transaction.hxx>
#include <Core/ITKCommon/ThreadUtils/the_mutex_interface.hxx>
#include <Core/ITKCommon/the_utils.hxx>
// system includes:
#include <iostream>
// namespace access:
using std::cout;
using std::cerr;
using std::endl;
//----------------------------------------------------------------
// DEBUG_THREAD
//
// #define DEBUG_THREAD
//----------------------------------------------------------------
// the_transaction_wrapper_t::the_transaction_wrapper_t
//
the_transaction_wrapper_t::
the_transaction_wrapper_t(const unsigned int & num_parts,
the_transaction_t * transaction):
mutex_(the_mutex_interface_t::create()),
cb_(transaction->notify_cb_),
cb_data_(transaction->notify_cb_data_),
num_parts_(num_parts)
{
assert(mutex_ != nullptr);
for (unsigned int i = 0; i <= the_transaction_t::DONE_E; i++)
{
notified_[i] = 0;
}
transaction->set_notify_cb(notify_cb, this);
}
//----------------------------------------------------------------
// the_transaction_wrapper_t::~the_transaction_wrapper_t
//
the_transaction_wrapper_t::~the_transaction_wrapper_t()
{
mutex_->delete_this();
mutex_ = nullptr;
}
//----------------------------------------------------------------
// the_transaction_wrapper_t::notify_cb
//
void
the_transaction_wrapper_t::notify_cb(void * data,
the_transaction_t * t,
the_transaction_t::state_t s)
{
the_transaction_wrapper_t * wrapper = (the_transaction_wrapper_t *)(data);
bool done = wrapper->notify(t, s);
if (done)
{
delete wrapper;
}
}
//----------------------------------------------------------------
// the_transaction_wrapper_t::notify
//
bool
the_transaction_wrapper_t::notify(the_transaction_t * t,
the_transaction_t::state_t s)
{
the_lock_t<the_mutex_interface_t> locker(mutex_);
notified_[s]++;
unsigned int num_terminal_notifications =
notified_[the_transaction_t::SKIPPED_E] +
notified_[the_transaction_t::ABORTED_E] +
notified_[the_transaction_t::DONE_E];
switch (s)
{
case the_transaction_t::PENDING_E:
case the_transaction_t::STARTED_E:
if (notified_[s] == 1 && num_terminal_notifications == 0 && cb_ != nullptr)
{
cb_(cb_data_, t, s);
}
return false;
case the_transaction_t::SKIPPED_E:
case the_transaction_t::ABORTED_E:
case the_transaction_t::DONE_E:
{
if (num_terminal_notifications == num_parts_)
{
// restore the transaction callback:
t->set_notify_cb(cb_, cb_data_);
// if necessary, consolidate the transaction state into one:
if (num_terminal_notifications !=
notified_[the_transaction_t::DONE_E])
{
the_transaction_t::state_t state =
notified_[the_transaction_t::ABORTED_E] > 0 ?
the_transaction_t::ABORTED_E :
the_transaction_t::SKIPPED_E;
t->set_state(state);
}
if (cb_ != nullptr)
{
cb_(cb_data_, t, t->state());
}
else
{
delete t;
}
return true;
}
return false;
}
default:
assert(0);
}
return false;
}
//----------------------------------------------------------------
// the_thread_pool_t::the_thread_pool_t
//
the_thread_pool_t::the_thread_pool_t(unsigned int num_threads):
pool_size_(num_threads)
{
mutex_ = the_mutex_interface_t::create();
assert(mutex_ != nullptr);
pool_ = new the_thread_pool_data_t[num_threads];
for (unsigned int i = 0; i < num_threads; i++)
{
pool_[i].id_ = i;
pool_[i].parent_ = this;
pool_[i].thread_ = the_thread_interface_t::create();
assert(pool_[i].thread_ != nullptr);
pool_[i].thread_->set_thread_pool_cb(this, &pool_[i]);
// mark the thread as idle, initially:
idle_.push_back(i);
}
}
//----------------------------------------------------------------
// the_thread_pool_t::~the_thread_pool_t
//
the_thread_pool_t::~the_thread_pool_t()
{
// TODO: sketchy!
mutex_->delete_this();
mutex_ = nullptr;
delete [] pool_;
pool_ = nullptr;
pool_size_ = 0;
}
//----------------------------------------------------------------
// the_thread_pool_t::start
//
void
the_thread_pool_t::start()
{
if (!transactions_.empty())
{
while (true)
{
the_lock_t<the_mutex_interface_t> locker(mutex_);
if (transactions_.empty()) return;
if (idle_.empty())
{
#ifdef DEBUG_THREAD
// sanity test:
for (unsigned int i = 0; i < pool_size_; i++)
{
the_lock_t<the_mutex_interface_t> locker(pool_[i].thread_->mutex());
if (!pool_[i].thread_->has_work())
{
cerr << "WARNING: thread " << i << ", " << pool_[i].thread_
<< " is actually idle" << endl;
}
}
#endif
return;
}
// get the next worker thread:
unsigned int id = remove_head(idle_);
busy_.push_back(id);
// get the next transaction:
the_transaction_t * t = remove_head(transactions_);
// start the thread:
thread(id)->start(t);
#ifdef DEBUG_THREAD
cerr << "starting thread " << id << ", " << thread(id) << ", " << t
<< endl;
for (std::list<unsigned int>::const_iterator i = idle_.begin();
i != idle_.end(); ++i)
{
cerr << "idle: thread " << *i << ", " << thread(*i) << endl;
}
for (std::list<unsigned int>::const_iterator i = busy_.begin();
i != busy_.end(); ++i)
{
cerr << "busy: thread " << *i << ", " << thread(*i) << endl;
}
#endif
}
}
else
{
// Transaction list is empty, perhaps they've already
// been distributed to the threads? Just start the threads
// and let them figure it out for themselves.
for (unsigned int i = 0; i < pool_size_; i++)
{
pool_[i].thread_->start();
}
}
}
//----------------------------------------------------------------
// the_thread_pool_t::set_idle_sleep_duration
//
void
the_thread_pool_t::set_idle_sleep_duration(bool enable, unsigned int microsec)
{
the_lock_t<the_mutex_interface_t> locker(mutex_);
for (unsigned int i = 0; i < pool_size_; i++)
{
pool_[i].thread_->set_idle_sleep_duration(enable, microsec);
}
}
//----------------------------------------------------------------
// notify_cb
//
static void
notify_cb(void * data,
the_transaction_t * transaction,
the_transaction_t::state_t s)
{
the_thread_pool_t * pool = (the_thread_pool_t *)(data);
pool->handle(transaction, s);
}
//----------------------------------------------------------------
// status_cb
//
static void
status_cb(void * data, the_transaction_t *, const char * text)
{
the_thread_pool_t * pool = (the_thread_pool_t *)(data);
pool->blab(text);
}
//----------------------------------------------------------------
// wrap
//
static void
wrap(the_transaction_t * transaction,
the_thread_pool_t * pool,
bool multithreaded)
{
if (transaction->notify_cb() == nullptr)
{
// override the callback:
transaction->set_notify_cb(::notify_cb, pool);
}
if (transaction->status_cb() == nullptr)
{
// override the callback:
transaction->set_status_cb(::status_cb, pool);
}
if (multithreaded)
{
// silence the compiler warning:
// the_transaction_wrapper_t * wrapper =
new the_transaction_wrapper_t(pool->pool_size(), transaction);
}
}
//----------------------------------------------------------------
// the_thread_pool_t::push_front
//
void
the_thread_pool_t::push_front(the_transaction_t * transaction,
bool multithreaded)
{
the_lock_t<the_mutex_interface_t> locker(mutex_);
no_lock_push_front(transaction, multithreaded);
}
//----------------------------------------------------------------
// the_thread_pool_t::push_back
//
void
the_thread_pool_t::push_back(the_transaction_t * transaction,
bool multithreaded)
{
the_lock_t<the_mutex_interface_t> locker(mutex_);
no_lock_push_back(transaction, multithreaded);
}
//----------------------------------------------------------------
// the_thread_pool_t::push_back
//
void
the_thread_pool_t::push_back(std::list<the_transaction_t *> & schedule,
bool multithreaded)
{
the_lock_t<the_mutex_interface_t> locker(mutex_);
no_lock_push_back(schedule, multithreaded);
}
//----------------------------------------------------------------
// the_thread_pool_t::pre_distribute_work
//
void
the_thread_pool_t::pre_distribute_work()
{
the_lock_t<the_mutex_interface_t> locker(mutex_);
std::vector<std::list<the_transaction_t *> > split_schedule_(pool_size_);
while (!transactions_.empty())
{
for (unsigned int i = 0; i < pool_size_ && !transactions_.empty(); i++)
{
the_transaction_t * job = remove_head(transactions_);
split_schedule_[i].push_back(job);
}
}
for (unsigned int i = 0; i < pool_size_; i++)
{
pool_[i].thread_->push_back(split_schedule_[i]);
}
}
//----------------------------------------------------------------
// the_thread_pool_t::has_work
//
bool
the_thread_pool_t::has_work() const
{
the_lock_t<the_mutex_interface_t> locker(mutex_);
if (!transactions_.empty()) return true;
// make sure the busy threads have work:
for (std::list<unsigned int>::const_iterator
iter = busy_.begin(); iter != busy_.end(); ++iter)
{
unsigned int i = *iter;
if (pool_[i].thread_->has_work()) return true;
}
return false;
}
//----------------------------------------------------------------
// the_thread_pool_t::start
//
void
the_thread_pool_t::start(the_transaction_t * transaction, bool multithreaded)
{
push_back(transaction, multithreaded);
start();
}
//----------------------------------------------------------------
// the_thread_pool_t::stop
//
void
the_thread_pool_t::stop()
{
// remove any pending transactions:
flush();
the_lock_t<the_mutex_interface_t> locker(mutex_);
for (unsigned int i = 0; i < pool_size_; i++)
{
pool_[i].thread_->stop();
}
}
//----------------------------------------------------------------
// the_thread_pool_t::wait
//
void
the_thread_pool_t::wait()
{
// the_lock_t<the_mutex_interface_t> locker(mutex_);
for (unsigned int i = 0; i < pool_size_; i++)
{
pool_[i].thread_->wait();
}
}
//----------------------------------------------------------------
// the_thread_pool_t::flush
//
void
the_thread_pool_t::flush()
{
the_lock_t<the_mutex_interface_t> locker(mutex_);
no_lock_flush();
}
//----------------------------------------------------------------
// the_thread_pool_t::terminate_transactions
//
void
the_thread_pool_t::terminate_transactions()
{
the_lock_t<the_mutex_interface_t> locker(mutex_);
no_lock_terminate_transactions();
}
//----------------------------------------------------------------
// the_thread_pool_t::stop_and_go
//
void
the_thread_pool_t::stop_and_go(the_transaction_t * transaction,
bool multithreaded)
{
// safely manipulate the transactions:
{
the_lock_t<the_mutex_interface_t> locker(mutex_);
no_lock_terminate_transactions();
no_lock_push_back(transaction, multithreaded);
}
start();
}
//----------------------------------------------------------------
// the_thread_pool_t::stop_and_go
//
void
the_thread_pool_t::stop_and_go(std::list<the_transaction_t *> & schedule,
bool multithreaded)
{
// safely manipulate the transactions:
{
the_lock_t<the_mutex_interface_t> locker(mutex_);
no_lock_terminate_transactions();
no_lock_push_back(schedule, multithreaded);
}
start();
}
//----------------------------------------------------------------
// the_thread_pool_t::flush_and_go
//
void
the_thread_pool_t::flush_and_go(the_transaction_t * transaction,
bool multithreaded)
{
// safely manipulate the transactions:
{
the_lock_t<the_mutex_interface_t> locker(mutex_);
no_lock_flush();
no_lock_push_back(transaction, multithreaded);
}
start();
}
//----------------------------------------------------------------
// the_thread_pool_t::flush_and_go
//
void
the_thread_pool_t::flush_and_go(std::list<the_transaction_t *> & schedule,
bool multithreaded)
{
// safely manipulate the transactions:
{
the_lock_t<the_mutex_interface_t> locker(mutex_);
no_lock_flush();
no_lock_push_back(schedule, multithreaded);
}
start();
}
//----------------------------------------------------------------
// the_thread_pool_t::blab
//
void
the_thread_pool_t::handle(the_transaction_t * transaction,
the_transaction_t::state_t s)
{
switch (s)
{
case the_transaction_t::SKIPPED_E:
case the_transaction_t::ABORTED_E:
case the_transaction_t::DONE_E:
delete transaction;
break;
default:
break;
}
}
//----------------------------------------------------------------
// the_thread_pool_t::handle
//
void
the_thread_pool_t::blab(const char * message) const
{
cerr << message << endl;
}
//----------------------------------------------------------------
// the_thread_pool_t::handle_thread
//
// prior to calling this function the thread interface locks
// the pool mutex and it's own mutex -- don't try locking these
// again while inside this callback, and don't call any other
// pool or thread member functions which lock either of these
// because that would result in a deadlock
//
void
the_thread_pool_t::handle_thread(the_thread_pool_data_t * data)
{
const unsigned int & id = data->id_;
the_thread_interface_t * t = thread(id);
if (t->stopped_)
{
#ifdef DEBUG_THREAD
cerr << "thread has stopped: " << t << endl;
#endif
if (!has(idle_, id))
{
idle_.push_back(id);
}
if (has(busy_, id))
{
busy_.remove(id);
}
return;
}
if (t->has_work())
{
#ifdef DEBUG_THREAD
cerr << "thread still has work: " << t << endl;
#endif
return;
}
if (transactions_.empty())
{
// tell the thread to stop:
t->stopped_ = true;
if (!has(idle_, id))
{
idle_.push_back(id);
}
if (has(busy_, id))
{
busy_.remove(id);
}
#ifdef DEBUG_THREAD
cerr << "no more work for thread: " << t << endl;
for (std::list<unsigned int>::const_iterator i = idle_.begin();
i != idle_.end(); ++i)
{
cerr << "idle: thread " << *i << ", " << thread(*i) << endl;
}
for (std::list<unsigned int>::const_iterator i = busy_.begin();
i != busy_.end(); ++i)
{
cerr << "busy: thread " << *i << ", " << thread(*i) << endl;
}
#endif
return;
}
// execute another transaction:
the_transaction_t * transaction = remove_head(transactions_);
#ifdef DEBUG_THREAD
cerr << "giving " << transaction << " to thread " << t << endl;
#endif
t->transactions_.push_back(transaction);
}
//----------------------------------------------------------------
// the_thread_pool_t::no_lock_flush
//
void
the_thread_pool_t::no_lock_flush()
{
while (!transactions_.empty())
{
the_transaction_t * t = remove_head(transactions_);
t->notify(this, the_transaction_t::SKIPPED_E);
}
}
//----------------------------------------------------------------
// the_thread_pool_t::no_lock_terminate_transactions
//
void
the_thread_pool_t::no_lock_terminate_transactions()
{
// remove any pending transactions:
no_lock_flush();
for (unsigned int i = 0; i < pool_size_; i++)
{
pool_[i].thread_->terminate_transactions();
}
}
//----------------------------------------------------------------
// the_thread_pool_t::no_lock_push_front
//
void
the_thread_pool_t::no_lock_push_front(the_transaction_t * transaction,
bool multithreaded)
{
wrap(transaction, this, multithreaded);
transactions_.push_front(transaction);
for (unsigned int i = 1; multithreaded && i < pool_size_; i++)
{
transactions_.push_front(transaction);
}
}
//----------------------------------------------------------------
// the_thread_pool_t::no_lock_push_back
//
void
the_thread_pool_t::no_lock_push_back(the_transaction_t * transaction,
bool multithreaded)
{
wrap(transaction, this, multithreaded);
transactions_.push_back(transaction);
for (unsigned int i = 1; multithreaded && i < pool_size_; i++)
{
transactions_.push_back(transaction);
}
}
//----------------------------------------------------------------
// the_thread_pool_t::no_lock_push_back
//
void
the_thread_pool_t::no_lock_push_back(std::list<the_transaction_t *> & schedule,
bool multithreaded)
{
// preprocess the transactions:
for (std::list<the_transaction_t *>::iterator i = schedule.begin();
i != schedule.end(); i++)
{
wrap(*i, this, multithreaded);
}
if (multithreaded)
{
while (!schedule.empty())
{
the_transaction_t * t = remove_head(schedule);
for (unsigned int i = 0; i < pool_size_; i++)
{
transactions_.push_back(t);
}
}
}
else
{
transactions_.splice(transactions_.end(), schedule);
}
}
|
7ff3cfb853ca2dacf03e63835079bd6ba5c61153
|
12cd044c57f4fb42362b28820d526e79684365f2
|
/gazebo/gui/ModelMaker.hh
|
e150a35d0b657123bbcc128f4a659ed2c8d11821
|
[
"Apache-2.0"
] |
permissive
|
ci-group/gazebo
|
29abd12997e7b8ce142c01410bdce4b46b97815f
|
1e8bdf272217e74eeb49349da22a38d3275e5d72
|
refs/heads/gazebo6-revolve
| 2021-07-09T16:05:29.272321
| 2019-11-11T17:56:01
| 2019-11-11T17:56:01
| 82,048,176
| 3
| 2
|
NOASSERTION
| 2020-05-18T13:49:18
| 2017-02-15T10:22:37
|
C++
|
UTF-8
|
C++
| false
| false
| 2,292
|
hh
|
ModelMaker.hh
|
/*
* Copyright (C) 2012-2015 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef _MODEL_MAKER_HH_
#define _MODEL_MAKER_HH_
#include <list>
#include <string>
#include <sdf/sdf.hh>
#include "gazebo/gui/EntityMaker.hh"
#include "gazebo/util/system.hh"
namespace gazebo
{
namespace msgs
{
class Visual;
}
namespace gui
{
class GAZEBO_VISIBLE ModelMaker : public EntityMaker
{
public: ModelMaker();
public: virtual ~ModelMaker();
/// \brief Initialize the model maker with an existing model
/// \param[in] _modelName Name of existing model in the scene.
/// \return True if initialization is successful.
public: bool InitFromModel(const std::string &_modelName);
public: bool InitFromSDFString(const std::string &_data);
public: bool InitFromFile(const std::string &_filename);
public: virtual void Start(const rendering::UserCameraPtr _camera);
public: virtual void Stop();
public: virtual bool IsActive() const;
public: virtual void OnMousePush(const common::MouseEvent &_event);
public: virtual void OnMouseRelease(const common::MouseEvent &_event);
public: virtual void OnMouseDrag(const common::MouseEvent &_event);
public: virtual void OnMouseMove(const common::MouseEvent &_event);
/// \brief Internal init function.
private: bool Init();
private: virtual void CreateTheEntity();
private: int state;
private: bool leftMousePressed;
private: math::Vector2i mousePushPos, mouseReleasePos;
private: rendering::VisualPtr modelVisual;
private: std::list<rendering::VisualPtr> visuals;
private: sdf::SDFPtr modelSDF;
private: bool clone;
};
}
}
#endif
|
739be2ef2736a00ab9935f0cc27927b4315da001
|
69c9ed5122cb49532e9e0d59bab78497ce3e4857
|
/ArrayStack (For Bloodshed Dev-C++)/main.cpp
|
e4f9446fd27daaf276df3ae22922104be35adb05
|
[] |
no_license
|
galvanitic/ArrayStack
|
d6a59b12b8fb3ba6cc74f0815480803058e91acd
|
ffa89e890a41cb7bbc6566f3a97393512a33f0ff
|
refs/heads/main
| 2023-01-24T00:49:02.314387
| 2020-11-25T05:22:03
| 2020-11-25T05:22:03
| 307,849,018
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,444
|
cpp
|
main.cpp
|
#include <iostream>
#include "Item.h"
#include "Stack.h"
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
void menu();
int main(int argc, char** argv) {
char choice;
cout << ">> Please hold while I create an empty stack..." << endl;
Stack newStack;
cout << ">> Thanks for holding. The stack is ready!" << endl;
cout << "---------------------------------------------------------------" << endl;
do {
menu();
cout << "\n What would you like to do?: ";
cin >> choice;
if (choice == '1'){
// code to test push()
string name;
string color;
Item newItem;
cout << " >> What's the name of the item? ";
cin >> name;
newItem.setName(name);
cout << " >> What's the color of the item? ";
cin >> color;
newItem.setColor(color);
if(newStack.push(newItem)){
cout << " >> The stack item was successfully pushed to the stack! \n\n";
}else{
cout << " >> Something went wrong. \n\n";
}
}
else if (choice == '2'){
// code to test pop()
if (newStack.pop())
{
cout << " >> The top item was successfully removed!\n\n";
}else{
cout << " >> Good try but the stack is already empty.\n\n";
}
}
else if (choice == '3'){
// code to test peek()
cout << " >> The top of stack holds a " << newStack.peek().getColor() << " " << newStack.peek().getName() << endl << endl;
}
else if (choice == '4'){
// code to test isEmpty()
if (newStack.isEmpty()){
cout << " >> The stack is empty.\n\n";
}else{
cout << " >> The stack contains items.\n\n";
}
}
else if (choice == '5'){
// code to test display()
newStack.display();
}
else if (choice == '6'){
cout << endl << "Exiting..." << endl << endl;
}
else{
cout << endl << "Not a valid option" << endl << endl;
}
} while (choice != '6');
return 0;
}
void menu(){
cout << ">> Please choose one of the following:\n"
<< " * 1 - Add an item to the stack.\n"
<< " * 2 - Remove an item from the stack.\n"
<< " * 3 - Look at the last item placed on the stack.\n"
<< " * 4 - Check to see if the stack is empty.\n"
<< " * 5 - Display the entire stack.\n"
<< " * 6 - Exit" << endl;
}
|
4bc7c111283063ea2ca95d43a590bee40c9d6314
|
2d5816c153038f51612e3610e485e4baf3f67cb7
|
/Assignments/Assignment 2/Chess/main.cpp
|
111008b74ea9c0b9b4ba76032950b481471ab8d6
|
[] |
no_license
|
Hammad-Ikhlaq/Artificial-Intelligence
|
3519267eabc4aa9c23b4b893e47df7fdd15e56e2
|
e43c17427d40c67f756f5bf8336c8a321e4a9fb4
|
refs/heads/master
| 2020-12-02T12:56:43.545421
| 2019-12-31T02:42:55
| 2019-12-31T02:42:55
| 231,012,961
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 366
|
cpp
|
main.cpp
|
#include "include\\actionList.h"
#include <iostream>
#include<iomanip>
#include "include\\chess.h"
#include "include\\autoPlayer.h"
#include "include\\humanPlayer.h"
using namespace std;
int main(){
chess Game;
Game.Players[1] = new humanPlayer("Hammad", White);
Game.Players[0] = new autoPlayer();
Game.playGame();
return 0;
}
|
31b7ef830f01286408802d36d086792ea0fc4476
|
0131f6d91da5b063b3d79330b014871c128c67ed
|
/irc/zncmodules/urlbuffer.cpp
|
ff4523d304da6ee8c8ef06dcb940d3f778aaa597
|
[
"Zlib"
] |
permissive
|
moneytech/code-2
|
f31602a702cc7e13b24c1ab5817d30d2314dde76
|
d970038329f7c4e4f0ee9dcd1b345741dd0fcc51
|
refs/heads/master
| 2021-10-02T18:24:20.159492
| 2018-11-30T02:14:18
| 2018-11-30T02:14:18
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,890
|
cpp
|
urlbuffer.cpp
|
/* Copyright (C) 2011 uberspot
*
* Compiling: znc-buildmod urlbuffer.cpp
* Dependencies: curl, wget, sed and a unix environment.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 3 as published
* by the Free Software Foundation (http://www.gnu.org/licenses/gpl.txt).
*/
#include <znc/Client.h>
#include <znc/Chan.h>
#include <znc/User.h>
#include <znc/Modules.h>
#include <znc/FileUtils.h>
#include <znc/IRCNetwork.h>
#include <climits>
#define MAX_EXTS 6
#define MAX_CHARS 16
class CUrlBufferModule : public CModule
{
private:
/* Vectors containing the last urls posted + the nicknames of the users posting them. */
VCString lastUrls, nicks;
/* Supported file extensions in links that should be downloaded. */
static const CString supportedExts[MAX_EXTS];
/* Unsupported characters that should be ignored when found in strings describing file directories. */
static const char unSupportedChars[MAX_CHARS];
/* Executes the given command in a unix pipeline and returns the result. */
static inline CString getStdoutFromCommand(const CString& cmd);
/* Load the default options if no other were found. */
inline void LoadDefaults();
inline bool isValidExtension(CString ext)
{
ext.MakeLower();
for(int i=0; i< MAX_EXTS; i++)
{
if( ext == supportedExts[i])
return true;
}
return false;
}
inline bool isValidDir(const CString& dir)
{
for(int i=0; i< MAX_CHARS; i++)
{
if (dir.find(unSupportedChars[i]) !=CString::npos)
return false;
}
return true;
}
inline void CheckLineForLink(const CString& sMessage, const CString& sOrigin);
inline void CheckLineForTrigger(const CString& sMessage, const CString& sTarget);
public:
MODCONSTRUCTOR(CUrlBufferModule) {}
bool OnLoad(const CString& sArgs, CString& sErrorMsg);
virtual ~CUrlBufferModule();
EModRet OnUserMsg(CString& sTarget, CString& sMessage);
EModRet OnPrivMsg(CNick& Nick, CString& sMessage);
EModRet OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage);
void OnModCommand(const CString& sCommand);
};
const CString CUrlBufferModule::supportedExts[MAX_EXTS] =
{"jpg", "png", "gif", "jpeg", "bmp", "tiff"} ;
const char CUrlBufferModule::unSupportedChars[MAX_CHARS] =
{'|', ';', '!', '@', '#', '(', ')', '<', '>', '"', '\'', '`', '~', '=', '&', '^'};
bool CUrlBufferModule::OnLoad(const CString& sArgs, CString& sErrorMsg)
{
LoadDefaults();
return true;
}
CUrlBufferModule::~CUrlBufferModule() {}
CUrlBufferModule::EModRet CUrlBufferModule::OnUserMsg(CString& sTarget, CString& sMessage)
{
CheckLineForLink(sMessage, "");
CheckLineForTrigger(sMessage, m_pUser->GetUserName() );
return CONTINUE;
}
CUrlBufferModule::EModRet CUrlBufferModule::OnPrivMsg(CNick& Nick, CString& sMessage)
{
CheckLineForLink(sMessage, Nick.GetNick());
CheckLineForTrigger(sMessage, Nick.GetNick());
return CONTINUE;
}
CUrlBufferModule::EModRet CUrlBufferModule::OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage)
{
CheckLineForLink(sMessage, Nick.GetNick());
CheckLineForTrigger(sMessage, Nick.GetNick());
return CONTINUE;
}
void CUrlBufferModule::OnModCommand(const CString& sCommand)
{
CString command = sCommand.Token(0).AsLower().Trim_n();
if (command == "help")
{
CTable CmdTable;
CmdTable.AddColumn("Command");
CmdTable.AddColumn("Description");
CmdTable.AddRow();
CmdTable.SetCell("Command", "ENABLE");
CmdTable.SetCell("Description", "Activates link buffering.");
CmdTable.AddRow();
CmdTable.SetCell("Command", "DISABLE");
CmdTable.SetCell("Description", "Deactivates link buffering.");
CmdTable.AddRow();
CmdTable.SetCell("Command", "ENABLELOCAL");
CmdTable.SetCell("Description", "Enables downloading of each link to local directory.");
CmdTable.AddRow();
CmdTable.SetCell("Command", "DISABLELOCAL");
CmdTable.SetCell("Description", "Disables downloading of each link to local directory.");
CmdTable.AddRow();
CmdTable.SetCell("Command","ENABLEPUBLIC");
CmdTable.SetCell("Description", "Enables the usage of !showlinks publicly, by other users.");
CmdTable.AddRow();
CmdTable.SetCell("Command","DISABLEPUBLIC");
CmdTable.SetCell("Description", "Disables the usage of !showlinks publicly, by other users.");
CmdTable.AddRow();
CmdTable.SetCell("Command", "DIRECTORY <#directory>");
CmdTable.SetCell("Description", "Sets the local directory where the links will be saved.");
CmdTable.AddRow();
CmdTable.SetCell("Command", "CLEARBUFFER");
CmdTable.SetCell("Description", "Empties the link buffer.");
CmdTable.AddRow();
CmdTable.SetCell("Command", "BUFFERSIZE <#size>");
CmdTable.SetCell("Description", "Sets the size of the link buffer. Only integers >=0.");
CmdTable.AddRow();
CmdTable.SetCell("Command", "SHOWSETTINGS");
CmdTable.SetCell("Description", "Prints all the settings.");
CmdTable.AddRow();
CmdTable.SetCell("Command", "BUFFERALLLINKS");
CmdTable.SetCell("Description", "Toggles the buffering of all links or only image links.");
CmdTable.AddRow();
CmdTable.SetCell("Command", "REUPLOAD");
CmdTable.SetCell("Description", "Toggles the reuploading of image links to imgur.");
CmdTable.AddRow();
CmdTable.SetCell("Command", "SHOWLINKS <#number>");
CmdTable.SetCell("Description", "Prints <#number> or <#buffersize> number of cached links.");
CmdTable.AddRow();
CmdTable.SetCell("Command", "HELP");
CmdTable.SetCell("Description", "This help.");
PutModule(CmdTable);
return;
} else if (command == "enable")
{
SetNV("enable","true",true);
PutModule("Enabled buffering");
} else if (command == "disable")
{
SetNV("enable","false",true);
PutModule("Disabled buffering");
} else if (command == "enablelocal")
{
if(GetNV("directory") == "")
{
PutModule("Directory is not set. First set a directory and then enable local caching");
return;
}
SetNV("enablelocal","true",true);
PutModule("Enabled local caching");
} else if (command == "disablelocal")
{
SetNV("enablelocal", "false", true);
PutModule("Disabled local caching");
} else if (command == "enablepublic")
{
SetNV("enablepublic", "true", true);
PutModule("Enabled public usage of showlinks.");
} else if (command == "disablepublic")
{
SetNV("enablepublic", "false", true);
PutModule("Disabled public usage of showlinks.");
} else if (command == "directory")
{
CString dir=sCommand.Token(1).Replace_n("//", "/").TrimRight_n("/") + "/";
if (!isValidDir(dir))
{
PutModule("Error in directory name. Avoid using: | ; ! @ # ( ) < > \" ' ` ~ = & ^ <space> <tab>");
return;
}
// Check if file exists and is directory
if (dir.empty() || !CFile::Exists(dir) || !CFile::IsDir(dir, false))
{
PutModule("Invalid path or no write access to ["+ sCommand.Token(1) +"].");
return;
}
SetNV("directory", dir, true);
PutModule("Directory for local caching set to " + GetNV("directory"));
} else if (command == "clearbuffer")
{
lastUrls.clear();
nicks.clear();
} else if (command == "buffersize")
{
unsigned int bufSize = sCommand.Token(1).ToUInt();
if(bufSize==0 || bufSize==UINT_MAX)
{
PutModule("Error in buffer size. Use only integers >= 0.");
return;
}
SetNV("buffersize", CString(bufSize), true);
PutModule("Buffer size set to " + GetNV("buffersize"));
} else if (command == "showsettings")
{
for(MCString::iterator it = BeginNV(); it != EndNV(); it++)
{
PutModule(it->first.AsUpper() + " : " + it->second);
}
} else if(command == "bufferalllinks"){
SetNV("bufferalllinks", CString(!GetNV("bufferalllinks").ToBool()), true);
PutModule( CString(GetNV("bufferalllinks").ToBool()?"Enabled":"Disabled") + " buffering of all links.");
} else if(command == "reupload"){
SetNV("reupload", CString(!GetNV("reupload").ToBool()), true);
PutModule( CString(GetNV("reupload").ToBool()?"Enabled":"Disabled") + " reuploading of images.");
} else if (command == "showlinks")
{
if(lastUrls.empty())
PutModule("No links were found...");
else
{
unsigned int maxLinks = GetNV("buffersize").ToUInt();
unsigned int size = sCommand.Token(1).ToUInt();
if(size!=0 && size<UINT_MAX) //if it was a valid number
maxLinks = size;
unsigned int maxSize = lastUrls.size()-1;
for(unsigned int i=0; i<=maxSize && i< maxLinks; i++)
{
PutModule(nicks[maxSize-i] + ": " + lastUrls[maxSize-i]);
}
}
} else
{
PutModule("Unknown command! Try HELP.");
}
}
void CUrlBufferModule::LoadDefaults()
{
if(GetNV("enable")=="")
SetNV("enable", "true", true);
if(GetNV("enablelocal")=="")
SetNV("enablelocal", "false", true);
if(GetNV("buffersize")== "")
SetNV("buffersize", "5", true);
if(GetNV("enablepublic")=="")
SetNV("enablepublic", "true", true);
if(GetNV("bufferalllinks")=="")
SetNV("bufferalllinks", "false", true);
if(GetNV("reupload")=="")
SetNV("reupload", "true", true);
}
void CUrlBufferModule::CheckLineForLink(const CString& sMessage, const CString& sOrigin)
{
if(sOrigin != m_pUser->GetUserName() && GetNV("enable").ToBool() )
{
VCString words;
CString output;
sMessage.Split(" ", words, false, "", "", true, true);
for (size_t a = 0; a < words.size(); a++)
{
CString& word = words[a];
if(word.Left(4) == "http" || word.Left(4) == "www.")
{
//if you find an image download it, save it in the www directory and keep the new link in buffer
VCString tokens;
word.Split("/", tokens, false, "", "", true, true);
CString name = tokens[tokens.size()-1];
word.Split(".", tokens, false, "", "", true, true);
//if it's an image link download/upload it else just keep the link
if(isValidExtension( tokens[tokens.size()-1] ))
{
std::stringstream ss;
if( GetNV("enablelocal").ToBool())
{
time_t curtime;
time(&curtime);
CString dir = GetNV("directory") + CUtils::FormatTime(curtime,"%Y-%m-%d", m_pUser->GetTimezone()) + "/";
if(!CFile::Exists(dir) && !CFile::IsDir(dir, false))
{
CDir::MakeDir(dir, 0755);
}
ss << "wget -b -O " << dir.c_str() << name <<" -q " << word.c_str() << " 2>&1";
getStdoutFromCommand(ss.str());
}
ss.str("");
if (!word.WildCmp("*imgur*") && GetNV("reupload").ToBool()) {
ss << "curl -d \"image=" << word.c_str() << "\" -d \"key=5ce86e7f95d8e58b18931bf290f387be\" http://api.imgur.com/2/upload.xml | sed -n 's/.*<original>\\(.*\\)<\\/original>.*/\\1/p' 2>&1";
output = getStdoutFromCommand(ss.str());
lastUrls.push_back(output);
} else {
lastUrls.push_back(word);
}
} else if(GetNV("bufferalllinks").ToBool()){
lastUrls.push_back(word);
}
nicks.push_back( (sOrigin.empty())? m_pUser->GetUserName() : sOrigin );
}
}
}
}
CString CUrlBufferModule::getStdoutFromCommand(const CString& cmd)
{
CString data="";
char buffer[128];
FILE* stream = popen(cmd.c_str(), "r");
if (stream == NULL || !stream || ferror(stream))
{
return "Error!";
}
while (!feof(stream))
{
if (fgets(buffer, 128, stream) != NULL)
data.append(buffer);
}
pclose(stream);
return data;
}
void CUrlBufferModule::CheckLineForTrigger(const CString& sMessage, const CString& sTarget)
{
if(GetNV("enablepublic").ToBool())
{
VCString words;
sMessage.Split(" ", words, false, "", "", true, true);
for (size_t a = 0; a < words.size(); a++)
{
CString& word = words[a];
if(word.AsLower() == "!showlinks")
{
if(lastUrls.empty())
PutIRC("PRIVMSG " + sTarget + " :No links were found...");
else
{
unsigned int maxLinks = GetNV("buffersize").ToUInt();
if (a+1 < words.size())
{
unsigned int size = words[a+1].ToUInt();
if(size!=0 && size<UINT_MAX) //if it was a valid number
maxLinks = size;
}
unsigned int maxSize = lastUrls.size()-1;
for(unsigned int i=0; i<=maxSize && i<maxLinks; i++)
{
sleep(1);
PutIRC("PRIVMSG " + sTarget + " :" + nicks[maxSize-i] + ": "+ lastUrls[maxSize-i]);
}
}
}
}
}
}
template<> void TModInfo<CUrlBufferModule>(CModInfo& Info) {
Info.SetWikiPage("urlbuffer");
Info.SetHasArgs(false);
}
USERMODULEDEFS(CUrlBufferModule, "Module that caches locally images/links posted on irc channels.")
|
00b129f95fd407cc8a9013895bd9effe9c4dc4f9
|
24d8838e94c1c67b5e8386aa52faf012d28e3251
|
/hw6/piece.cpp
|
43118c6efc539ee2b306dcb1ba8a8cf2e6648577
|
[] |
no_license
|
melina-delgado/CS427
|
95bc9e4c402202c958c3f42315029555dc17afda
|
1d1cef5214bcb13a3195add4450eb70bbe67dd04
|
refs/heads/master
| 2022-04-11T19:28:29.924636
| 2020-03-21T01:55:56
| 2020-03-21T01:55:56
| 105,041,487
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 380
|
cpp
|
piece.cpp
|
#include "piece.h"
namespace cs427_527
{
Piece::Piece() {}
Piece::Piece(int p, int r, int c)
: player(p), row(r), col(c) {}
Piece::~Piece() {}
int Piece::getPlayer() const
{
return player;
}
/*bool Piece::isLegalMove(const Board& board, int toR, int toC) const
{
return false;
}
void Piece::makeMove(Board& board, int toR, int toC)
{
}*/
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.